AdHSurfaceWater.py 9.42 KB
Newer Older
Bob Obara's avatar
Bob Obara committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#=============================================================================
#
#  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.
#
#=============================================================================
"""
Export script for Shallow Water 2D applications
"""
import imp
import os
import sys
import smtk
19 20
if smtk.wrappingProtocol() == 'pybind11':
  import smtk.attribute
21
  import smtk.io
22 23
  import smtk.mesh
  import smtk.model
24 25
  import smtk.simulation

26 27 28
# so devs don't complain about pyc files in source
sys.dont_write_bytecode = True

Bob Obara's avatar
Bob Obara committed
29 30 31 32 33 34 35
# Explicitly load adhcommon.py, so that it reloads each time
module_name = 'adhcommon'
abs_path = os.path.abspath(__file__)
abs_dir = os.path.dirname(abs_path)
module_args = imp.find_module(module_name, [abs_dir])
imp.load_module(module_name, *module_args)
adh = sys.modules.get(module_name)
36
#print 'adh', adh
Bob Obara's avatar
Bob Obara committed
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 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 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

# Define placeholder/passthrough functions for custom writer functions
# Actual implementations, prefixed by "_", are further below
def write_outputseries(scope, item, card_format, context_id):
  return _write_outputseries(scope, item, card_format, context_id)


# ---------------------------------------------------------------------
#
# Dictionary of formatters for each output card
#
# Card format types are: val, idval, bc, multival
# Arguments are: (item name, opcode, comment=None, subitems=None, \
#  custom_writer=None)
#
# ---------------------------------------------------------------------
fmt = adh.CardFormat
format_table = {
  'Solvers': [
    fmt.val('MemoryIncrementBlockSize', 'OP INC'),
    fmt.val('PreconditioningBlocks', 'OP BLK'),
    fmt.val('PreconditionerType', 'OP PRE'),
    fmt.val('TemporalSchemeCoefficient', 'OP TEM'),
    fmt.val('PetrovGalerkinCoefficient', 'OP TPG'),
    fmt.val('VesselMovement', 'OP BT'),
    fmt.val('VesselEntrainment', 'OP BTS'),
    fmt.val('SW2Gradients', 'OP NF2'),
    fmt.val('NonLinearTolMaxNorm', 'IP NTL'),
    fmt.val('MaxNonLinearIters', 'IP NIT'),
    fmt.val('MaxLinearIters', 'IP MIT'),
    fmt.val('NonLinearTolMaxChange', 'IP ITL'),
    fmt.val('RungeKuttaTol', 'IP RTL'),
  ],

  'Time': [
    fmt.val('TimestepSize', 'TC IDT'),
    fmt.val('StartTime', 'TC T0', subitem_names=['Value', 'Units']),
    fmt.val('EndTime', 'TC TF', subitem_names=['Value', 'Units']),
    fmt.val('SteadyStateSolveParams', 'TC STD'),
    fmt.val('QuasiUnsteadyParams', 'TC STH',
            subitem_names=['SteadyStateHydrodynamicCondition"', 'MaxIterations', 'InitialTimeStep']),
    fmt.val('AutoTimeStepFind', 'TC ATF', subitem_names=['InitialTimeStep', 'TimeSeries']),
    fmt.val('PrintAdaptedMeshes', 'PC ADP'),
    fmt.val('HotStartFile', 'PC HOT'),
    fmt.val('OutputSeries', 'OS', custom_writer=write_outputseries)
  ],

  'SolidMaterial': [
    fmt.idconval('TurbulentDiffusionRate', 'MP DF'),
    fmt.idval('KinematicEddyViscosity', 'MP EVS',
      subitem_names=['Value1', 'Value2', 'Value3']),
    fmt.idval('CoriolisLatitude', 'MP COR'),
    fmt.idval('MaxRefineLevels', 'MP ML'),
    fmt.idval('HydroRefineTol', 'MP SRT'),
    fmt.idconval('TransportRefineTol', 'MP TRT')
  ],

  # Boundary Conditions
  'VelocityBound':
    fmt.bc('DirichletVelocity', 'DB OVL', subitem_names=['Value1', 'Value2']),
  'VelocityAndDepthBound':
    fmt.bc('Dirichlet transport', 'DB TRN',
      subitem_names=['Value1', 'Value2', 'Value3']),
  'LidElevation':        fmt.bc('Value', 'DB LDE'),
  'WaterDepthLid':       fmt.bc('Value', 'DB LDH'),
  'FloatingStationary':  fmt.bc('Value', 'DB LID'),
  'TotalDischarge':      fmt.bc('Value', 'NB DIS'),
  'UnitFlow':            fmt.bc('Value', 'NB OVL'),
  'WaterSurfElev':       fmt.bc('Value', 'NB OTW'),
  'StageDischargeBound': fmt.bc('Value', 'NB SDR'),
  'SpillWayBound':       fmt.bc('Value', 'NB SPL'),
  'OutflowBound':        fmt.bc('Value', 'OB OF'),
  'DirichletTransport':  fmt.conbc('Value', 'DB TRN'),
  'NaturalTransport':    fmt.conbc('Value', 'NB TRN'),

  'FrictionType1': [ fmt.idval('Value', 'FR MNG') ],
  'FrictionType2': [ fmt.idval('Value', 'FR ERH') ],
  'FrictionType3': [ fmt.idval('Value', 'FR SAV') ],
  'FrictionType4': [ fmt.idval('Value', 'FR URV') ],

  'Globals': [
    fmt.val('Gravity', 'MP G'),
    fmt.val('KinMolViscosity', 'MP MU'),
    fmt.val('ReferenceDensity', 'MP RHO'),
    fmt.val('ManningsUnitConstant', 'MP MUC'),
    fmt.val('WetDryLimits', 'MP DTL')
  ],

  'GeneralConstituent':     [ fmt.idval('GenConstituentParams',  'CN CON',
    subitem_names=['ReferenceConcentration']) ],
  'SalinityConstituent':    [ fmt.idval('SalConstituentParams',  'CN SAL',
    subitem_names=['ReferenceConcentration']) ],
  'VorticityConstituent':   [ fmt.idval('VortConstituentParams', 'CN VOR',
    subitem_names=['NormalizationFactor', 'AsTerm', 'DsTerm']) ],
  'TemperatureConstituent': [ fmt.idval('TempConstituentParams', 'CN TEM',
    subitem_names=['ReferenceConcentration']) ],
}


# ---------------------------------------------------------------------
def ExportCMB(spec):
    '''Entry function, called by CMB to write export files

    Returns boolean indicating success
    Parameters
    ----------
    spec: Top-level object passed in from CMB
    '''
145
    #print 'Enter ExportCMB()'
Bob Obara's avatar
Bob Obara committed
146 147 148 149 150 151 152 153 154 155 156 157

    # Initialize scope instance to store spec values and other info
    scope = adh.init_scope(spec)
    if scope.logger.hasErrors():
      print scope.logger.convertToString()
      print 'FILES NOT WRITTEN because of errors'
      return False
    scope.format_table = format_table

    print 'Analysis types:', scope.analysis_types
    if not scope.analysis_types:
      msg = 'No analysis types selected'
158 159 160
      print 'ERROR:', msg
      scope.logger.addError(msg)
      return False
Bob Obara's avatar
Bob Obara committed
161 162 163
    else:
      print 'Categories:', sorted(list(scope.categories))

164
    # Write mesh file
165 166 167 168 169 170
    if scope.mesh_collection is None:
      print 'WARNING: No mesh collection; cannot write .2dm file'
    else:
      mesh_filename = scope.output_filebase + '.2dm'
      mesh_path = os.path.join(scope.output_directory, mesh_filename)
      print 'Writing mesh data to', mesh_path
171 172
      status = smtk.io.exportMesh(
        mesh_path,
173 174
        scope.mesh_collection,
        scope.model.manager(),
175
        scope.matid_property_name)
176
      print 'mesh write returned status', status
177

Bob Obara's avatar
Bob Obara committed
178 179
    # Open output file and start exporting content
    completed = False
180 181 182
    bc_filename = scope.output_filebase + '.bc'
    bc_path = os.path.join(scope.output_directory, bc_filename)
    with open(bc_path, 'w') as scope.output:
Bob Obara's avatar
Bob Obara committed
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
      scope.output.write('OP SW2\n')
      n = len(scope.constituent_dict)
      scope.output.write('OP TRN %d\n' % n)

      # Call write-content functions in specified top-level order
      att_type_list = [
        'Solvers', 'Time', 'SolidMaterial', 'BoundaryCondition',
        'Friction', 'Globals', 'Constituent'
      ]
      for att_type in att_type_list:
        ok = adh.write_section(scope, att_type)
        #if not ok:
        #    break

      # Write function attributes
      adh.write_functions(scope)

      # Write MTS cards (material id for each model domain)
      adh.write_MTS_cards(scope)

      # Write NDS & EGS cards for boundary conditions
      adh.write_bc_sets(scope)

      # Last line
      scope.output.write('END\n')
208
      print 'Wrote', bc_path
Bob Obara's avatar
Bob Obara committed
209 210
      completed = True

211 212 213
    # Write hotstart file if enabled
    completed &= adh.write_hotstart(scope)

Bob Obara's avatar
Bob Obara committed
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
    if not completed:
      print 'WARNING: Export terminated unexpectedly -- output might be invalid.'

    return completed


# ---------------------------------------------------------------------
def _write_outputseries(scope, item, card_format, context_id):
  '''Custom writer (implementation) for OutputSeries attribute

  Writes either OC or OS card, depending on item'd discrete value
    0 == OC (Output Control Series)
    1 == OS (Auto-Build Time Series)
  '''
  discrete_value = item.value(0)
  if 0 == discrete_value:
    output_item = adh.find_active_child(scope, item, 'OutputFunction')
    exp_att = output_item.expression(0)
    exp_id = adh.get_function_id(scope, exp_att)
    scope.output.write('OC %d\n' % exp_id)
  elif 1 == discrete_value:
    # Get function (series) ID for TimeSeriesData
    time_series_item = adh.find_active_child(scope, item, 'TimeSeriesData')
    series_id = adh.get_function_id(scope, time_series_item)

    # Get number of points
    n = time_series_item.numberOfGroups()

    # Get units
    units_item = adh.find_active_child(scope, item, 'OutputUnits')
    units_value = units_item.discreteIndex(0)

    scope.output.write('OS %d %d %d\n' % (series_id, n, units_value))

    # Process subgroup items, one line per
    if n < 1:  # but safety first
      return

    for i in range(n):
      #print 'i', i
      start_item = adh.find_subgroup_item(time_series_item, i, 'StartTime')
      start = start_item.value(0)

      end_item = adh.find_subgroup_item(time_series_item, i, 'EndTime')
      end = end_item.value(0)

      interval_item = adh.find_subgroup_item(time_series_item, i, 'TimeInterval')
      interval = interval_item.value(0)

      units_item = adh.find_subgroup_item(time_series_item, i, 'Units')
      units = units_item.value(0)

      scope.output.write('%8s %8s %8s   %s\n' % (start, end, interval, units))
  else:
    msg = 'Unexpected value for OutputSeries: %d (expecting 0 or 1)' % \
      discrete_value
    print 'WARNING:', msg
    scope.logger.addWarning(msg)