Truchas.py 17.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
#=============================================================================
#
#  Copyright (c) Kitware, Inc.
#  All rights reserved.
#  See LICENSE.txt for details.
#
#  This software is distributed WITHOUT ANY WARRANTY; without even
#  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
#  PURPOSE.  See the above copyright notice for more information.
#
#=============================================================================
"""
13
Export operator for Truchas workflows
14
"""
15 16
import os
print 'loading', os.path.basename(__file__)
17 18
import sys

19
import smtk
20 21 22 23 24 25 26
import smtk.attribute
import smtk.io
import smtk.operation

# 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()))))
27

28
import internal
29
from internal import writer
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
# 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.parameters(), self.log())
        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

85 86 87 88 89 90 91

# ---------------------------------------------------------------------
#
# Dictionary of formatters for output lines
# Arguments are: (keyword, attribute type, item path, **kwargs)
#
# ---------------------------------------------------------------------
92

93
# Predefined strings for "if_condition" arguments
94
from internal.writer.writer import THERMAL_ANALYSIS, ONLY_THERMAL_ANALYSIS, FLOW_ANALYSIS, \
95
  VISCOUS_FLOW, INVISCID_FLOW, FLUID_PHASE, MASS_LIMITER, BC_INFLOW, \
96
  VOID_MATERIAL, ENCLOSURE_RADIATION, MOVING_RADIATION
97

98
# Please order the namelists alphabetically in this table
99
card = writer.CardFormat
100
format_table = {
101 102 103 104 105 106 107 108 109 110 111
  'BC': [
    card('bc_name', use_name_for_value=True),
    card('bc_variable', item_path='variable'),
    card('bc_type', is_custom=True),
    card('surface_name',literal_value='from mesh file'),
    card('mesh_surface', use_model_entities_for_value=True),
    card('bc_value', is_custom=True, expression_keyword='bc_table'),
    card('inflow_material', item_path='variable/inflow/inflow-material',
      if_condition=BC_INFLOW),
    card('inflow_temperature', item_path='variable/inflow/inflow-temperature',
      if_condition=BC_INFLOW)
112
  ],
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
  'BODY': [
    card('surface_name', literal_value='from mesh file'),
    card('mesh_material_number', use_model_entities_for_value=True),
    card('material_number', is_custom=True),
    card('temperature', item_path='temperature',
      expression_keyword='temperature_function'),
    card('velocity', item_path='velocity')
  ],
  'CHAPARRAL': [
    card('blocking_enclosure', item_path='blocking-enclosure'),
    card(None, item_path='partial-enclosure-area',
      set_condition='partial-enclosure'),
    card('partial_enclosure', item_path='partial-enclosure-area',
      use_condition_for_boolean='partial-enclosure'),
    card('partial_area', item_path='partial-enclosure-area',
      if_condition='partial-enclosure'),
    card('bsp_max_tree_depth', item_path='bsp-max-tree-depth'),
    card('bsp_min_leaf_length', item_path='bsp-min-leaf-length'),
    card('spatial_tolerance', item_path='spatial-tolerance'),
    card('hemicube_resolution', item_path='hemicube-resolution'),
    card('min_separation', item_path='min-separation'),
    card('max_subdivisions', item_path='max-subdivisions'),
    card('smoothing_tolerance', item_path='smoothing-tolerance'),
    card('smoothing_max_iter', item_path='smoothing-max-iter'),
    card('smoothing_weigth', item_path='smoothing-weight'),
    card('verbosity_level', item_path='verbosity-level')
  ],
  'DIFFUSION_SOLVER': [
    card('stepping_method', literal_value='Adaptive BDF2',
      if_condition=ONLY_THERMAL_ANALYSIS),
    card('stepping_method',literal_value='Non-adaptive BDF1',
      if_condition=FLOW_ANALYSIS),

    card('abs_enthalpy_tol', item_path='abs-enthalpy-tol',
      if_condition=ONLY_THERMAL_ANALYSIS),
    card('rel_enthalpy_tol', item_path='rel-enthalpy-tol',
      if_condition=ONLY_THERMAL_ANALYSIS),
    card('abs_temp_tol', item_path='abs-temperature-tol',
      if_condition=ONLY_THERMAL_ANALYSIS),
    card('rel_temp_tol', item_path='rel-temperature-tol',
      if_condition=ONLY_THERMAL_ANALYSIS),

    card('residual_atol', item_path='residual-atol',
      if_condition=FLOW_ANALYSIS),
    card('residual_rtol', item_path='residual-rtol',
      if_condition=FLOW_ANALYSIS),
    card('nlk_preconditioner', item_path='nlk-preconditioner',
      literal_value='Hypre_AMG'),
    card('max_nlk_itr', item_path='max-nlk-itr'),
    card('max_nlk_vec', item_path='max-nlk-vec'),
    card('nlk_tol', item_path='nlk-tol',
        if_condition=ONLY_THERMAL_ANALYSIS),
    card('nlk_vec_tol', item_path='nlk-vec-tol'),
    card('verbose_stepping', item_path='verbose-stepping'),
    card('pc_amg_cycles', item_path='pc-amg-cycles'),
    card('cond_vfrac_threshold', item_path='cond-vfrac-threshold',
      if_condition=FLOW_ANALYSIS)
  ],
  'DS_BOUNDARY_CONDIATION': [],
  'DS_INTERFACE_CONDITION': [],
  'DS_SOURCE': [
    card('equation', literal_value='temperature'),
    card('cell_set_ids', use_model_entities_for_value=True),
    card('source_constant', item_path='source',
      expression_keyword='source_function')
178
  ],
179 180
  'ENCLOSURE': [
    card('name', item_path='enclosure-name'),
181
    card('mesh_file', is_custom=True),
182
    card('coord_scale_factor', att_type="mesh", item_path='coordinate-scale-factor'),
183
    card('symmetries', item_path='symmetries', is_custom=True),
184
    card('side_set_ids', is_custom=True),
185
    card('moving_enclosure', use_condition_for_boolean=MOVING_RADIATION),
186
    card('displacement_set_ids', is_custom=True),
187 188
    card('displacement_sequence', item_path='moving-radiation/displacement-sequence',
      is_custom=True),
189 190
    card('enclosure_file_sequence_prefix',
      item_path='moving-radiation/enclosure-file-prefix',
191
      if_condition=MOVING_RADIATION),
192 193 194
    card('ignore_block_ids',
      item_path='ignore-block-ids',
      use_model_entities_for_value=True)
195 196 197 198 199 200 201 202 203 204 205 206 207
  ],
  'ENCLOSURE_RADIATION': [
    card('name', item_path='enclosure-name'),
    card('ambient_constant', item_path='ambient-temperature',
      expression_keyword='ambient_function'),
    card('error_tolerance', item_path='error-tolerance'),
    card('moving_enclosure', use_condition_for_boolean=MOVING_RADIATION),
    card('linear_interpolation', item_path='moving-radiation/linear-interpolation',
      if_condition=MOVING_RADIATION),
    card('skip_geometry_check', use_condition_for_boolean=MOVING_RADIATION,
      if_condition=MOVING_RADIATION),
    card('enclosure_file_sequence_prefix',
      item_path='moving-radiation/enclosure-file-prefix',
208 209 210
      if_condition=MOVING_RADIATION),
    card('time_sequence', item_path='moving-radiation/displacement-sequence',
      is_custom=True)
211
  ],
212 213
  'ENCLOSURE_SURFACE': [
    card('name', use_name_for_value=True),
214 215 216
    card('enclosure_name', att_type='enclosure-radiation',
      item_path='enable/enclosure/enclosure-name'),
    card('face_block_ids', use_model_entities_for_value=True),
217 218
    card('emissivity', item_path='emissivity')
  ],
219 220 221 222 223 224 225 226 227 228 229 230 231 232
  'FUNCTION': [
    card('name', use_name_for_value=True),
    card('type', literal_value='tabular')
  ],
  'LINEAR_SOLVER': [
    card('name', item_path='', use_name_for_value=True),
    card('method', item_path='method'),
    card('preconditioning_method', item_path='preconditioning-method'),
    card('preconditioning_steps', item_path='preconditioning-steps'),
    card('relaxation_parameter', item_path='relaxation-parameter'),
    card('stopping_criterion', item_path='stopping-criterion'),
    card('convergence_criterion', item_path='convergence-criterion'),
    card('krylov_vectors', item_path='krylov-vectors'),
    card('output_mode', item_path='output-mode')
John Tourtellott's avatar
John Tourtellott committed
233
  ],
234 235
  'MATERIAL': [
    card('density', item_path='material-type/density'),
236 237 238 239
    card('void_temperature', item_path='material-type/void-temperature',
      if_condition=VOID_MATERIAL),
    card('sound_speed', item_path='material-type/sound-speed',
      if_condition=VOID_MATERIAL)
240 241
  ],
  'MATERIAL_SYSTEM': [
242 243 244 245
    card('transition_temps_low',
      item_path='material-type/solid-transition-temperature'),
    card('transition_temps_high',
      item_path='material-type/liquid-transition-temperature'),
246 247
    card('latent_heat', item_path='material-type/thermal-two-phase/latent-heat')
  ],
248 249 250 251 252
  'MESH': [
    card('mesh_file', is_custom=True),
    card('coordinate_scale_factor', item_path='coordinate-scale-factor'),
    card('exodus_block_modulus', item_path='exodus-block-modulus'),
    card('interface_side_sets', is_custom=True)
253
  ],
254 255 256 257 258
  'NUMERICS': [
    card('dt_init', att_type='numerics', item_path='dt_init'),
    card('dt_grow', att_type='numerics', item_path='dt_grow'),
    card('dt_max', att_type='numerics', item_path='dt_max'),
    card('dt_min', att_type='numerics', item_path='dt_min'),
259
    card('t', att_type='outputs', item_path='start-time'),
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
    card('discrete_ops_type', item_path='analysis/fluid/flow-numerics/discrete-ops-type',
      if_condition=FLOW_ANALYSIS),
    card('projection_linear_solution', item_path='analysis/fluid/projection-linear-solver',
      use_name_for_value=True, if_condition=FLOW_ANALYSIS),
    card('viscous_implictness', item_path='analysis/fluid/viscous-flow-model/viscous-implicitness',
      if_condition=VISCOUS_FLOW),
    card('viscous_linear_solution',
      item_path='analysis/fluid/viscous-flow-model/viscous-linear-solver',
      use_name_for_value=True, if_condition=VISCOUS_FLOW),
    card('viscous_number', item_path='analysis/fluid/flow-numerics/viscous-number',
      if_condition=FLOW_ANALYSIS),
    card('volume_track_subcycles', item_path='analysis/fluid/flow-numerics/volume-track-subcycles',
      if_condition=FLOW_ANALYSIS),
    card('body_force_implicitness', item_path='analysis/fluid/flow-numerics/body-force-implicitness',
      if_condition=FLOW_ANALYSIS),
    card('mass_limiter', item_path='analysis/fluid/flow-numerics/mass-limiter',
      if_condition=FLOW_ANALYSIS, as_boolean=True, set_condition=MASS_LIMITER),
    # Note that mass_limiter_cutoff must come AFTER mass_limiter
    card('mass_limiter_cutoff', item_path='analysis/fluid/flow-numerics/mass-limiter/mass-limiter-cutoff',
      if_condition=MASS_LIMITER),
    card('mechanical_energy_bound', item_path='analysis/fluid/flow-numerics/mechanical-energy-bound',
      if_condition=FLOW_ANALYSIS),
    card('momentum_solidify_implicitness', item_path='analysis/fluid/flow-numerics/momentum-solidify-implicitness',
      if_condition=FLOW_ANALYSIS)
  ],
285 286 287 288
  'OUTPUTS': [
    # Writer has custom code for output time lists
    card('output_t', item_path='output-times/time'),
    card('output_dt', item_path='output-times/time')
289
  ],
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
  'PHASE': [
    card('density', item_path='material-type/density', as_property=True),
    card('specific heat', item_path='material-type/thermal/specific-heat',
      if_condition='fluid', as_property=True),
    card('specific heat', item_path='material-type/thermal/specific-heat',
      if_condition='solid', as_property=True),
    card('specific heat',
      item_path='material-type/thermal-two-phase/specific-heat',
      if_condition='two-phase',
      as_property=True),
    card('conductivity', item_path='material-type/conductivity', as_property=True),
    card('viscosity', item_path='material-type/viscosity', \
      if_condition=[VISCOUS_FLOW, FLUID_PHASE], as_property=True),
    card('density deviation', item_path='material-type/density-deviation', \
      if_condition=FLUID_PHASE, as_property=True)
305
  ],
306 307 308
  'PHYSICAL_CONSTANTS': [
    card('absolute_zero', item_path='absolute-zero'),
    card('stefan_boltzmann', item_path='stefan-boltzmann')
309
  ],
310 311 312 313 314 315 316
  'PHYSICS': [
    card('fluid_flow', use_condition_for_boolean=FLOW_ANALYSIS),
    card('heat_transfer', use_condition_for_boolean=THERMAL_ANALYSIS),
    card('body_force', att_type='physics', item_path='fluid-body-force',
      if_condition=FLOW_ANALYSIS),
    card('inviscid', if_condition=FLOW_ANALYSIS,
      use_condition_for_boolean=INVISCID_FLOW)
317 318
  ],
  'PROBE': [
319
    card('probe_name', use_name_for_value=True),
320 321 322
    card('probe_description', item_path='description'),
    card('probe_coords', item_path='coords')
  ],
323
  'SIMULATION_CONTROL': [
324 325
    card('phase_start_times', item_path='simulation-control/phase-start-times'),
    card('phase_init_dt_factor', item_path='simulation-control/phase-init-dt-factor')
326 327 328
  ]
}

329
# This list sets the order that namelists are written to the Truchas input file
330
namelist = writer.Namelist
331
namelist_sequence = [
332
  namelist('MESH', att_type='mesh', custom_method='_write_mesh'),
333
  namelist('OUTPUTS', att_type='outputs', custom_method='_write_outputs'),
334
  namelist('ENCLOSURE', att_type='enclosure-radiation',
335
    base_item_path='enable/enclosure',
336 337
    if_condition=ENCLOSURE_RADIATION,
    custom_method='_write_enclosure'),
338 339
  namelist('ENCLOSURE_RADIATION',
    att_type='enclosure-radiation',
340 341
    base_item_path='enable/enclosure',
    if_condition=ENCLOSURE_RADIATION,
342
    custom_method='_write_enclosure_radiation'),
343 344 345 346
  namelist('ENCLOSURE_SURFACE',
    att_type='thermal-surface-condition',
    base_item_path='type',
    if_condition=ENCLOSURE_RADIATION,
347
    custom_method='_write_thermal_condition'),
348
  namelist('PHYSICS', att_type='solver'),
349
  # Note: internally, the materials writer includes PHASE and MATERIAL_SYSTEM
John Tourtellott's avatar
John Tourtellott committed
350
  namelist('MATERIAL', custom_method='_write_materials'),
351 352 353 354 355 356 357 358
  namelist('DIFFUSION_SOLVER',
    if_condition=ONLY_THERMAL_ANALYSIS,
    att_type='solver',
    base_item_path='analysis/thermal'),
  namelist('DIFFUSION_SOLVER',
    if_condition=[THERMAL_ANALYSIS, FLOW_ANALYSIS],
    att_type='solver',
    base_item_path='analysis/thermal-plus-fluid/thermal-solver'),
359 360 361
  namelist('CHAPARRAL', att_type='enclosure-radiation',
    base_item_path='enable/chaparral',
    if_condition=ENCLOSURE_RADIATION),
362 363 364 365 366 367 368 369 370
  namelist('NUMERICS', att_type='solver'),
  namelist('LINEAR_SOLVER',
    if_condition=FLOW_ANALYSIS,
    att_type='solver',
    base_item_path='analysis/fluid/projection-linear-solver'),
  namelist('LINEAR_SOLVER',
    if_condition=VISCOUS_FLOW,
    att_type='solver',
    base_item_path='analysis/fluid/viscous-flow-model/viscous-linear-solver'),
371 372
  namelist(
    'DS_BOUNDARY_CONDITION',
373 374
    att_type='thermal-surface-condition',
    base_item_path='type/ds-boundary-condition',
375
    custom_method='_write_thermal_condition'),
376 377
  namelist(
    'DS_INTERFACE_CONDITION',
378 379
    att_type='thermal-surface-condition',
    base_item_path='type/ds-interface-condition',
380
    custom_method='_write_thermal_condition'),
381 382
  namelist('BC',
    att_type='boundary-condition', custom_method='_write_bc'),
383
  namelist('BODY', att_type='body', custom_method='_write_body'),
384
  namelist('DS_SOURCE', att_type='ds-source'),
385
  namelist('PROBE', att_type='probe'),
386 387 388 389
  namelist(
    'SIMULATION_CONTROL',
    att_type='simulation-control',
    custom_method='_write_simcontrol'),
390
  namelist('FUNCTION', att_type='tabular-function', custom_method='_write_function'),
391
  namelist('PHYSICAL_CONSTANTS', att_type='physical-constants')
392 393 394 395
]


# ---------------------------------------------------------------------
396
def ExportCMB(operator_spec, logger):
397 398 399
  '''
  Entry function, called by CMB to write export file
  '''
400 401

  # Get project name
402
  project_name_item = operator_spec.findString('ProjectName')
403 404 405 406 407 408 409 410 411 412 413
  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
    logger.addWarning(msg)
  print 'project_name', project_name
  project_name = project_name

  # Initialize project path (folder)
  project_path = None
414
  item = operator_spec.find('ProjectDir')
415
  if item is not None:
416
    dir_item = item
417 418 419 420 421 422 423 424 425 426 427 428 429
    project_path = dir_item.value(0)
    print 'project_path', project_path

  if not project_path:
    project_path = os.getcwd()
    msg = 'No project_path specified -- using', project_path
    print 'ERROR:', msg
    logger.addWarning(msg)
    return False

  # Create output folder if needed
  if not os.path.exists(project_path):
    os.makedirs(project_path)
430

431
  # Initialize writer object
432 433
  output_filename = '%s.inp' % project_name
  output_path = os.path.join(project_path, output_filename)
434 435
  completed = True
  truchas_writer = writer.Writer(operator_spec, logger)
436
  completed = truchas_writer.write(output_path, namelist_sequence, format_table)
437 438 439
  # print 'Writer completion status %s' % completed
  # sys.stdout.flush()
  print 'TODO truchas_writer'
440
  return completed