Commit 208298da authored by John Tourtellott's avatar John Tourtellott

Merge branch 'truchas-rework-templates' into 'master'

Interim Truchas update

See merge request !64
parents 0a4a9668 c793bdf9
......@@ -10,20 +10,81 @@
#
#=============================================================================
"""
Root writer script for Truchas workflows
Export operator for Truchas workflows
"""
from __future__ import print_function
import os
print 'loading', os.path.basename(__file__)
print('loading', os.path.basename(__file__))
import sys
sys.dont_write_bytecode
import smtk
if 'pybind11' == smtk.wrappingProtocol():
#print 'Using pybind11 bindings'
import smtk.simulation
import smtk.attribute
import smtk.io
import smtk.operation
import smtk.session.mesh
# Add the directory containing this file to the python module search list
import inspect
sys.path.insert(0, os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))))
import internal
from internal import writer
reload(writer) # for development
# reload(writer) # for development
class Export(smtk.operation.Operation):
def __init__(self):
smtk.operation.Operation.__init__(self)
def name(self):
return "Export Truchas"
def operateInternal(self):
try:
success = ExportCMB(self)
except:
print('Error', self.log().convertToString())
#smtk.ErrorMessage(self.log(), sys.exc_info()[0])
raise
return self.createResult(smtk.operation.Operation.Outcome.FAILED)
# Return with success
result = self.createResult(smtk.operation.Operation.Outcome.SUCCEEDED)
result.find('success').setValue(success)
return result
def createSpecification(self):
spec = self.createBaseSpecification()
print('spec:', spec)
# Load export atts
source_dir = os.path.abspath(os.path.dirname(__file__))
print('source_dir:', source_dir)
sbt_path = os.path.join(source_dir, 'internal', 'truchas-export.sbt')
print('sbt_path:', sbt_path)
reader = smtk.io.AttributeReader()
result = reader.read(spec, sbt_path, self.log())
print('reader result:', result)
# opDef = spec.createDefinition('test op', 'operation')
opDef = spec.findDefinition('truchas-export')
simulationDef = smtk.attribute.ResourceItemDefinition.New('attributes')
simulationDef.setAcceptsEntries('smtk::attribute::Resource', '', True)
opDef.addItemDefinition(simulationDef)
modelDef = smtk.attribute.ResourceItemDefinition.New('model')
modelDef.setAcceptsEntries('smtk::model::Resource', '', True)
opDef.addItemDefinition(modelDef)
resultDef = spec.createDefinition('test result', 'result')
successDef = smtk.attribute.IntItemDefinition.New('success')
resultDef.addItemDefinition(successDef)
return spec
# ---------------------------------------------------------------------
#
......@@ -312,18 +373,16 @@ namelist_sequence = [
base_item_path='analysis/fluid/viscous-flow-model/viscous-linear-solver'),
namelist(
'DS_BOUNDARY_CONDITION',
att_type='thermal-surface-condition',
base_item_path='type/ds-boundary-condition',
att_type='ht/boundary',
custom_method='_write_thermal_condition'),
namelist(
'DS_INTERFACE_CONDITION',
att_type='thermal-surface-condition',
base_item_path='type/ds-interface-condition',
att_type='ht/interface',
custom_method='_write_thermal_condition'),
namelist('BC',
att_type='boundary-condition', custom_method='_write_bc'),
namelist('BODY', att_type='body', custom_method='_write_body'),
namelist('DS_SOURCE', att_type='ds-source'),
namelist('DS_SOURCE', att_type='ht/source'),
namelist('PROBE', att_type='probe'),
namelist(
'SIMULATION_CONTROL',
......@@ -335,52 +394,37 @@ namelist_sequence = [
# ---------------------------------------------------------------------
def ExportCMB(spec):
def ExportCMB(export_op):
'''
Entry function, called by CMB to write export file
'''
logger = spec.getLogger()
# Get export attributes
export_spec_att = None
export_atts = spec.getExportAttributes()
if export_atts is not None:
att_list = export_atts.findAttributes('ExportSpec')
if att_list:
export_spec_att = att_list[0]
if export_spec_att is None:
msg = 'No ExportSpec instance -- cannot export'
print 'WARNING:', msg
logger.addError(msg)
return False
# Get project name
project_name_item = export_spec_att.findString('ProjectName')
operator_spec = export_op.parameters()
logger = export_op.log()
project_name_item = operator_spec.findString('ProjectName')
project_name = project_name_item.value(0)
if not project_name:
project_name = 'truchas'
msg = 'No Project Name specified; using \"%s\"' % project_name
print 'WARNING:', msg
print('WARNING:', msg)
logger.addWarning(msg)
print 'project_name', project_name
print('project_name', project_name)
project_name = project_name
# Initialize project path (folder)
project_path = None
item = export_spec_att.find('ProjectDir')
item = operator_spec.find('ProjectDir')
if item is not None:
if 'shiboken' == smtk.wrappingProtocol():
dir_item = smtk.attribute.to_concrete(item)
else:
dir_item = item
dir_item = item
project_path = dir_item.value(0)
print 'project_path', project_path
print('project_path', project_path)
if not project_path:
project_path = os.getcwd()
msg = 'No project_path specified -- using', project_path
print 'ERROR:', msg
print('ERROR:', msg)
logger.addWarning(msg)
return False
......@@ -388,11 +432,31 @@ def ExportCMB(spec):
if not os.path.exists(project_path):
os.makedirs(project_path)
# Initialize writer object
# Write mesh file
model_entity = smtk.model.Entity.CastTo(operator_spec.find('model').objectValue(0))
write_mesh_op = smtk.session.mesh.Export.create()
if write_mesh_op is None:
print('MESH OPERATOR IS NONE')
mesh_filename = 'NOT-FOUND'
else:
mesh_filename = project_name + ".exo"
mesh_path = os.path.join(project_path, mesh_filename)
write_mesh_op.parameters().associate(model_entity)
file_item = write_mesh_op.parameters().findFile('filename')
file_item.setIsEnabled(True)
file_item.setValue(mesh_path)
result = write_mesh_op.operate()
outcome = result.findInt("outcome").value(0);
if (outcome != int(smtk.operation.Operation.Outcome.SUCCEEDED)):
logger.addError('Error writing model file %s, outcome %s' % (mesh_path, outcome))
return False
# Write input file
output_filename = '%s.inp' % project_name
output_path = os.path.join(project_path, output_filename)
truchas_writer = writer.Writer(spec)
truchas_writer = writer.Writer(operator_spec, logger, mesh_filename)
completed = truchas_writer.write(output_path, namelist_sequence, format_table)
print 'Writer completion status %s' % completed
print('Writer completion status %s' % completed)
sys.stdout.flush()
return completed
<?xml version="1.0" encoding="utf-8" ?>
<SMTK_AttributeSystem Version="2">
<!-- Category & Analysis specifications -->
<Categories Default="Heat Transfer">
<Cat>Enclosure Radiation</Cat>
<Cat>Fluid Flow</Cat>
<Cat>Heat Transfer</Cat>
<Cat>Induction Heating</Cat>
<Cat>Solid Mechanics</Cat>
</Categories>
<Analyses>
<Analysis Type="Heat Transfer">
<Cat>Heat Transfer</Cat>
</Analysis>
</Analyses>
<!-- Attribute definitions -->
<Includes>
<!-- Note: order is important, e.g., put expressions first -->
<File>internal/templates/tabular-function.sbt</File>
<File>internal/templates/material.sbt</File>
<File>internal/templates/thermal-surface-condition.sbt</File>
<File>internal/templates/boundary-condition.sbt</File>
<File>internal/templates/fluid-numerics.sbt</File>
<File>internal/templates/numerics-solver.sbt</File>
<File>internal/templates/body-source-probe.sbt</File>
<File>internal/templates/enclosure.sbt</File>
<File>internal/templates/other.sbt</File>
<File>internal/templates/initial-conditions.sbt</File>
<File>internal/templates/views/fluid-flow-views.sbt</File>
<File>internal/templates/views/heat-transfer-views.sbt</File>
</Includes>
<Definitions>
<!-- For enabling simulation modules -->
<AttDef Type="analysis">
<ItemDefinitions>
<Group Name="Heat Transfer" Optional="true" IsEnabledByDefault="false">
<ItemDefinitions>
<Void Name="Enclosure Radiation" Optional="true" IsEnabledByDefault="false">
<Categories>
<Cat>Enclosure Radiation</Cat>
<Cat>Fluid Flow</Cat>
<Cat>Heat Transfer</Cat>
<Cat>Induction Heating</Cat>
<Cat>Solid Mechanics</Cat>
</Categories>
</Void>
<Void Name="Induction Heating" Optional="true" IsEnabledByDefault="false">
<Categories>
<Cat>Enclosure Radiation</Cat>
<Cat>Fluid Flow</Cat>
<Cat>Heat Transfer</Cat>
<Cat>Induction Heating</Cat>
<Cat>Solid Mechanics</Cat>
</Categories>
</Void>
</ItemDefinitions>
</Group>
<Void Name="Fluid Flow" Optional="true" IsEnabledByDefault="false">
<Categories>
<Cat>Enclosure Radiation</Cat>
<Cat>Fluid Flow</Cat>
<Cat>Heat Transfer</Cat>
<Cat>Induction Heating</Cat>
<Cat>Solid Mechanics</Cat>
</Categories>
</Void>
<Void Name="Solid Mechanics" Optional="true" IsEnabledByDefault="false">
<Categories>
<Cat>Enclosure Radiation</Cat>
<Cat>Fluid Flow</Cat>
<Cat>Heat Transfer</Cat>
<Cat>Induction Heating</Cat>
<Cat>Solid Mechanics</Cat>
</Categories>
</Void>
</ItemDefinitions>
</AttDef>
<AttDef Type="export">
</AttDef>
<!-- Selector attribute - used by selector view-->
<!-- <AttDef Type="ModuleSelectorAtt" Version="0">
<ItemDefinitions>
<String Name="ModuleSelectorItem" Label="Select Module:">
<DiscreteInfo DefaultIndex="1">
<Value Enum="Fluid Flow">Fluid Flow</Value>
<Value Enum="Heat Transfer">Heat Transfer</Value>
<Value Enum="Enclosure Radiation">Enclosure Radiation</Value>
<Value Enum="Induction Heating">Induction Heating</Value>
<Value Enum="Solid Mechanics">Solid Mechanics</Value>
</DiscreteInfo>
</String>
</ItemDefinitions>
</AttDef> -->
</Definitions>
<!-- View specifications -->
<Views>
<View Type="Group" Title="TopLevel" TopLevel="true" TabPosition="North"
FilterByAdvanceLevel="true" FilterByCategory="false">
<Views>
<View Title="Analysis" />
<View Title="Materials" />
<View Title="Modules" />
<View Title="Body" />
<View Title="Globals" />
<View Title="Other" />
</Views>
</View>
<!-- Placeholder for "analysis view" Todo -->
<View Type="Group" Title="Analysis" Style="Tiled">
<Views>
<View Title="SelectModules" />
<View Title="General" />
</Views>
</View>
<View Type="Instanced" Name="SelectModules" Label="Select Modules">
<InstancedAttributes>
<Att Name="analysis-att" Type="analysis"></Att>
</InstancedAttributes>
</View>
<View Type="Group" Name="Modules" Label="Modules" TabPosition="North">
<Views>
<View Title="Enclosure Radiation" />
<View Title="Fluid Flow" /> <!-- In views/fluid-flow-views.sbt -->
<View Title="Heat Transfer" /> <!-- In views/heat-transfer-views.sbt -->
<View Title="Induction Heating" />
<View Title="Solid Mechanics" />
</Views>
</View>
<View Type="Instanced" Name="Enclosure Radiation">
<InstancedAttributes>
<Att Name="enclosure-radiation" Type="enclosure-radiation" />
</InstancedAttributes>
</View>
<View Type="Instanced" Name="Induction Heating">
<InstancedAttributes>
</InstancedAttributes>
</View>
<View Type="Instanced" Name="Solid Mechanics">
<InstancedAttributes>
</InstancedAttributes>
</View>
<View Type="Group" Title="Materials" TabPosition="North">
<Views>
<!--View Title="Background Material" /-->
<View Title="Material" />
<View Title="Material Assignment" />
</Views>
</View>
<!-- <View Type="Instanced" Title="Background Material">
<InstancedAttributes>
<Att Name="Background Material" Type="background-material" />
</InstancedAttributes>
</View> -->
<View Type="Attribute" Title="Material" Label="Specification">
<AttributeTypes>
<Att Type="material"/>
</AttributeTypes>
</View>
<View Type="Instanced" Title="Material Assignment" Label="Assignment">
<!-- Todo association view -->
</View>
<View Type="Group" Title="Body" Label="Initial Conditions" TabPosition="North">
<Views>
<View Title="Temperature IC" />
<View Title="Velocity IC" />
</Views>
</View>
<View Type="Attribute" Name="Temperature IC" Label="Temperature">
<AttributeTypes>
<Att Type="TemperatureInitialCondition" />
</AttributeTypes>
</View>
<View Type="Attribute" Name="Velocity IC" Label="Velocity">
<AttributeTypes>
<Att Type="VelocityInitialCondition" />
</AttributeTypes>
</View>
<View Type="Group" Title="Other" Style="tiled">
<Views>
<View Title="Other Instanced" />
<View Title="Probes" />
</Views>
</View>
<View Type="Instanced" Title="Other Instanced" Label="Mesh">
<InstancedAttributes>
<Att Name="Mesh" Type="mesh" />
</InstancedAttributes>
</View>
<View Type="Attribute" Title="Probes">
<AttributeTypes>
<Att Type="probe" />
</AttributeTypes>
</View>
<View Type="SimpleExpression" Title="Functions">
<Att Type="tabular-function"/>
</View>
<View Type="Instanced" Title="General">
<InstancedAttributes>
<Att Name="numerics-att" Type="numerics" />
<Att Name="outputs-att" Type="outputs" />
<Att Name="simulation-control-att" Type="simulation-control" />
<!-- <Att Name="Mesh" Type="mesh" /> -->
</InstancedAttributes>
</View>
<View Type="Group" Title="Globals" Style="Tiled">
<Views>
<View Title="Global Constants" />
<View Title="Functions" />
</Views>
</View>
<View Type="Instanced" Title="Global Constants">
<InstancedAttributes>
<Att Name="physics" Type="physics" />
<Att Name="physical-constants" Type="physical-constants" />
</InstancedAttributes>
</View>
</Views>
</SMTK_AttributeSystem>
"""
Script to fix <BriefDescription> newlines
"""
from __future__ import print_function
import os
import re
......@@ -9,23 +10,23 @@ from lxml import etree
if __name__ == '__main__':
#print sys.argv
#print(sys.argv)
if len(sys.argv) < 2:
app = os.path.basename(sys.argv[0])
print
print 'Script to prune whitespace from xml text'
print 'Usage: python %s filename' % app
print
print()
print('Script to prune whitespace from xml text')
print('Usage: python %s filename' % app)
print()
sys.exit(-1)
filename = sys.argv[1]
dom = etree.parse(filename)
root = dom.getroot()
#print root.tag
#print(root.tag)
mods = 0 # count the modified elements
for element in root.iter(tag="BriefDescription"):
#print element.text
#print( element.text)
text = element.text
# Check for any newline-followed-by-whitespace
if re.match(r"\n\s", text):
......@@ -35,17 +36,17 @@ if __name__ == '__main__':
content_list = [item for item in split_list if item != '']
new_string = '\n'.join(content_list)
# print 'new_string:'
# print new_string
# print
# print('new_string:')
# print(new_string)
# print()
element.text = new_string
mods += 1
if mods:
dom.write(filename)
print 'Wrote %d text-element updates to %s' % (mods, filename)
print('Wrote %d text-element updates to %s' % (mods, filename))
else:
print 'No text-element updates to %s' % filename
print('No text-element updates to %s' % filename)
#print 'Finis'
#print('Finis')
#!/usr/bin/env bash
# List of templates in subfolder
declare -a names=( \
"body-source-probe" \
"boundary-condition" \
"thermal-surface-condition" \
"material" \
"numerics-solver" \
"enclosure" \
"other" \
)
subfolder="templates"
for name in ${names[@]}; do
#echo ${name}
rm -f ${subfolder}/${name}.sbt
jade ${subfolder}/${name}.jade --pretty --extension sbt
python fixmultilinetext.py ${subfolder}/${name}.sbt
done
#!/usr/bin/env bash
# Script to generate .sbt files from pug templates
# For convenience only, but in order to use:
# * pug-cli must be installed
# * python bindings for libxml must be installed (pip install libxml)
# List of pug templates to render
declare -a names=( \
"body-source-probe" \
"boundary-condition" \
"thermal-surface-condition" \
"material" \
"numerics-solver" \
"fluid-numerics" \
"enclosure" \
"other" \
)
# Get script directory, per http://stackoverflow.com/questions/59895
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
TARGET="$(readlink "$SOURCE")"
if [[ $TARGET == /* ]]; then
SOURCE="$TARGET"
else
DIR="$( dirname "$SOURCE" )"
SOURCE="$DIR/$TARGET" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
fi
done
RDIR="$( dirname "$SOURCE" )"
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
echo "script DIR is '$DIR'"
subfolder="templates"
for name in ${names[@]}; do
#echo ${name}
rm -f ${subfolder}/${name}.sbt
pug ${subfolder}/pug/${name}.pug --pretty --extension sbt -o ${subfolder}
python fixmultilinetext.py ${subfolder}/${name}.sbt
done
<?xml version="1.0" encoding="utf-8" ?>
<SMTK_AttributeSystem Version="2">
<SMTK_AttributeResource Version="3">
<Categories>
<Cat>Heat Transfer</Cat>
<Cat>Fluid Flow</Cat>
<Cat>Heat Transfer</Cat>
<Cat>Induction Heating</Cat>
<Cat>Solid Mechanics</Cat>
</Categories>
<!-- Attribute Definitions-->
<Definitions>
......@@ -12,7 +14,7 @@
<MembershipMask>volume</MembershipMask>
</AssociationsDef>
<ItemDefinitions>
<Double Name="temperature" Label="Temperature">
<Double Name="temperature" Label="Temperature" Optional="true" IsEnabledByDefault="true">
<BriefDescription>Initial temperature of the material body</BriefDescription>
<Categories>
<Cat>Fluid Flow</Cat>
......@@ -20,7 +22,7 @@
</Categories>
<ExpressionType>tabular-function</ExpressionType>
</Double>
<Double Name="velocity" Label="Velocity" NumberOfRequiredValues="3">
<Double Name="velocity" Label="Velocity" NumberOfRequiredValues="3" Optional="true" IsEnabledByDefault="false">
<BriefDescription>Initial velocity of the material body</BriefDescription>
<Categories>
<Cat>Fluid Flow</Cat>
......@@ -31,7 +33,7 @@
</ItemDefinitions>
</AttDef>
<!-- DS_SOURCE-->
<AttDef Type="ds-source" Label="Volumetric Heat Source" BaseType="" Version="0">
<AttDef Type="ht/source" Label="Volumetric Heat Source" BaseType="" Version="0">
<AssociationsDef Name="DSSourceAssociations" Version="0" NumberOfRequiredValues="0" Extensible="true">
<MembershipMask>volume</MembershipMask>
</AssociationsDef>
......@@ -50,6 +52,9 @@
<String Name="description" Label="Description" MultipleLInes="true" Optional="true" IsEnabledByDefault="false"></String>
<Double Name="coords" Label="Coordinates" NumberOfRequiredValues="3">
<BriefDescription>Used to define the location of the probe</BriefDescription>
<Categories>
<Cat>Heat Transfer</Cat>
</Categories>
<ComponentLabels>
<Label>x:</Label>
<Label>y:</Label>
......@@ -62,4 +67,4 @@
</ItemDefinitions>
</AttDef>
</Definitions>
</SMTK_AttributeSystem>
</SMTK_AttributeResource>
<?xml version="1.0" encoding="utf-8" ?>
<SMTK_AttributeSystem Version="2">
<Categories>
<Cat>Heat Transfer</Cat>
<Cat>Enclosure Radiation</Cat>
<Cat>Fluid Flow</Cat>
<Cat>Heat Transfer</Cat>
<Cat>Solid Mechanics</Cat>
</Categories>
<Definitions>
<!-- Boundary Conditions-->
......
......@@ -7,7 +7,7 @@
<Definitions>
<AttDef Type="enclosure-radiation" Label="Enclosure Radiation" BaseType="" Version="0" Unique="true">
<ItemDefinitions>
<Group Name="enable" Label="Enable" Version="0" Optional="true" IsEnabledByDefault="true">
<Group Name="enable" Label="Enable" Version="0" Optional="true" IsEnabledByDefault="false">
<ItemDefinitions>
<Group Name="chaparral" Label="Chaparral" Version="0">
<ItemDefinitions>
......
//- Item definitions common to fluid-only and fluid-plus-thermal analyses
//- Parented by ItemDefinitions element
//- Root path to this file is solver/analysis/fluid/
Group(Name="flow-numerics" Label="Flow Numerics")
ItemDefinitions
String(Name="discrete-ops-type" Label="Discrete_Ops_type")
BriefDescription
| Numerical reconstruction method for estimating face-centered
| spatial graients and values of discrete cell-centered data.
DiscreteInfo(DefaultIndex=0)
Value(Enum="Default") default
Value(Enum="Ortho") ortho
Value(Enum="Non-ortho") nonortho
Categories
Cat Fluid Flow
Double(Name="viscous-number" Label="Viscous Number")
RangeInfo
Min(Inclusive="true") 0.0
Int(Name="volume-track-subcycles" Label="Volume Track Subcycles")
BriefDescription
| Volume tracking time step specification, expressed as a
| multiplicative factor relative to the time step
DefaultValue 2
RangeInfo
Min(Inclusive="false") 0
Max(Inclusive="true") 20
//- Advanced flow-solver parameters
Double(Name="body-force-implicitness" Label="Body Force Implicitness"
AdvanceLevel="1")
BriefDescription
| Degree of time implicitness used for the body-forces in the
| discrete form of the momentum equations
DefaultValue 0.5
RangeInfo
Min(Inclusive="true") 0.0
Max(Inclusive="true") 1.0
Group(Name="mass-limiter" Label="Mass Limiter" AdvanceLevel="1"
Optional="true" IsEnabledByDefault="false")
BriefDescription
| Used to avoid the generation of excessively large velocities
| in partially-filled fluid-void cells where the fluid mass
| approaches the cutoff volume-fraction
ItemDefinitions