def main(bdf_name, run_first_nastran=True, debug=True):
    base = os.path.splitext(bdf_name)[0]

    print("len(sys.argv) = %s" % len(sys.argv))
    #===========================
    if run_first_nastran:
        # run nastran and verify the starting model is correct
        os.system('nastran scr=yes bat=no news=no old=no %s' % bdf_name)

        f06_name = base + '.f06'
        try:
            model2 = F06()
            model2.read_f06(f06_name)
        except FatalError as e:
            print(e)
            #return
    else:
        pass
    #===========================
    # read/write the model in double precision
    out_bdf_8 = base + '_8.bdf'
    out_bdf_16 = base + '_16.bdf'
    out_bdf_16s = base + '_16s.bdf'
    model3 = BDF(debug=debug)
    model3.read_bdf(bdf_name)
    update_bdf(model3, post=-1)

    model3.write_bdf(out_bdf_8, size=8, is_double=False)
    model3.write_bdf(out_bdf_16s, size=16, is_double=False)
    model3.write_bdf(out_bdf_16, size=16, is_double=True)
    if debug:
        print("---wrote the bdf---")
    #===========================
    # run nastran again
    os.system('nastran scr=yes bat=no news=no old=no %s' % out_bdf_8)
    os.system('nastran scr=yes bat=no news=no old=no %s' % out_bdf_16)
    #===========================
    # verify it's correct
    if is_f06:
        out_f06_8 = base + '_8.f06'
        out_f06_16 = base + '_16.f06'
        model4 = F06(debug=False)
        model4.read_f06(out_f06_8)

        model5 = F06(debug=False)
        model5.read_f06(out_f06_16)

    out_op2_8 = base + '_8.op2'
    out_op2_16 = base + '_16.op2'

    model6 = OP2(debug=False)
    model6.read_op2(out_op2_16)
    print('\n\npassed!!')
예제 #2
0
def main(bdf_name, run_first_nastran=True, debug=True):
    base, ext = os.path.splitext(bdf_name)

    print "len(sys.argv) =", len(sys.argv)
    #===========================
    if run_first_nastran:
        # run nastran and verify the starting model is correct
        os.system('nastran scr=yes bat=no news=no old=no %s' % bdf_name)

        f06_name = base + '.f06'
        try:
            model2 = F06(f06_name)
            model2.read_f06()
        except FatalError as e:
            print(e)
            #return
    else:
        pass
    #===========================
    # read/write the model in double precision
    out_bdf_8 = base + '_8.bdf'
    out_bdf_16 = base + '_16.bdf'
    model3 = BDF()
    model3.read_bdf(bdf_name)
    update_bdf(model3)

    model3.write_bdf(out_bdf_8, size=8, precision='single')
    model3.write_bdf(out_bdf_16, size=16, precision='double')
    if debug:
        print "---wrote the bdf---"
    #===========================
    # run nastran again
    os.system('nastran scr=yes bat=no news=no old=no %s' % out_bdf_8)
    os.system('nastran scr=yes bat=no news=no old=no %s' % out_bdf_16)
    #===========================
    # verify it's correct
    out_f06_8 = base + '_8.f06'
    out_f06_16 = base + '_16.f06'
    out_op2_16 = base + '_16.op2'

    model4 = F06(out_f06_8, debug=False)
    model4.read_f06()

    model5 = F06(out_f06_16, debug=False)
    model5.read_f06()

    model6 = OP2(out_op2_16, debug=False)
    model6.read_op2()
    print('\n\npassed!!')
예제 #3
0
    def __init__(self):
        F06.__initAlt__(self)
        OP2.__objectsInit__(self)
        self.nU = 0
        self.nUs = 0
        self.nUm = 0

        # displacments
        self.U = []
        self.Us = []
        self.Um = []

        # indicies in U that correspond to Us/Um
        self.iUs = []
        self.iUm = []
    def __init__(self):
        F06.__initAlt__(self)
        OP2.__objectsInit__(self)
        self.nU = 0
        self.nUs = 0
        self.nUm = 0

        # displacments
        self.U = []
        self.Us = []
        self.Um = []

        # indicies in U that correspond to Us/Um
        self.iUs = []
        self.iUm = []
예제 #5
0
 def test_blade2dv_fatal_1(self):
     f06_filename = os.path.join(model_path, 'blade_2dv',
                                 'blade_2dv.f06_fatal')
     f06 = F06(debug=False, log=None)
     with self.assertRaises(AttributeError):
         f06.readF06(f06_filename)
     with self.assertRaises(FatalError):
         f06.read_f06(f06_filename)
예제 #6
0
def read_f06(f06_filename, isubcase=1):
    log.info('---starting deflectionReader.init of %s---' % f06_filename)
    f06 = F06()
    #terms = ['force','stress','stress_comp','strain','strain_comp','displacement','grid_point_forces']
    f06.set_results('displacements')
    f06.read_f06(f06_filename)
    displacment_obj = f06.displacements[isubcase]

    #op2.nastranModel.printDisplacement()
    #displacements = convertDisplacements(displacements)
    log.info('---finished deflectionReader.init of %s---' % f06_filename)
    return displacment_obj.translations
예제 #7
0
    def run_model(self,
                  bdf_name=None,
                  f06_name=None,
                  op2_name=None,
                  op4_name=None,
                  dynamic_vars=None,
                  f06_has_weight=True):
        outputs = []
        if bdf_name:
            bdf = BDF(debug=False, log=None)
            if dynamic_vars is not None:
                #print('dynamic')
                bdf.set_dynamic_syntax(dynamic_vars)
            bdf.read_bdf(bdf_name)
            bdf.write_bdf(bdf_name + '.out', interspersed=False)
            bdf.write_bdf(bdf_name + '.out', interspersed=True)
            outputs.append(bdf)

        if f06_name:
            f06 = F06(debug=False, log=None)
            f06.read_f06(f06_name)
            f06.write_f06(f06_name[:-4] + '.test_f06.out')
            outputs.append(f06)
            if f06_has_weight:
                assert f06.grid_point_weight.reference_point is not None
            else:
                assert f06.grid_point_weight.reference_point is None

        if op2_name:
            op2 = OP2(debug=False)
            op2.read_op2(op2_name)
            op2.write_f06(op2_name[:-4] + '.test_op2.out')
            outputs.append(op2)

        if op4_name:
            op4 = OP4()
            op4.read_op4(op4_name, matrixNames=None, precision='default')

        assert len(outputs) > 0
        if len(outputs) == 1: return outputs[0]
        return outputs
예제 #8
0
    def run_model(self,
                  bdf_name=None,
                  f06_name=None,
                  op2_name=None,
                  op4_name=None,
                  dynamic_vars=None):
        outputs = []
        if bdf_name:
            bdf = BDF(debug=False, log=None)
            if dynamic_vars is not None:
                print('dynamic')
                bdf.set_dynamic_syntax(dynamic_vars)
            bdf.read_bdf(bdf_name)
            bdf.write_bdf(bdf_name + '.out', interspersed=False)
            bdf.write_bdf(bdf_name + '.out', interspersed=True)
            outputs.append(bdf)

        if f06_name:
            f06 = F06(f06_name, debug=False, log=None)
            f06.read_f06()
            f06.write_f06(f06_name + '.out')
            outputs.append(f06)

        if op2_name:
            op2 = OP2(op2_name, debug=False)
            op2.read_op2()
            op2.write_f06(op2_name + '.out')
            outputs.append(op2)

        if op4_name:
            op4 = OP4(op4_name)
            op4.read_op4(op4Name, matrixNames=None, precision='default')

        assert len(outputs) > 0
        if len(outputs) == 1: return outputs[0]
        return outputs
예제 #9
0
def main():
    vars = {
        'bar1_a' : 1.0,
        'bar2_a' : 2.0,
        'bar3_a' : 3.0,
        'loadx' : 50000.0,
        'loady' : 100000.0,
        'loadmag': 1.,
        'rho'   : 0.284,
        'youngs': 30000000.0,

    }
    model = BDF()
    model.set_dynamic_syntax(vars)
    model.read_bdf('vared_bar3.bdf')
    out_bdf = 'out.bdf'
    out_f06 = 'out.f06'
    out_op2 = 'out.op2'

    if 'POST' in model.params:
        # change "PARAM, POST, 0"  to "PARAM, POST, -1"

        # option 1
        #model.params['POST'].update_field(2, -1)

        # option 2
        model.params['POST'].update_values(value1=-1, value2=None)

    model.write_bdf(out_bdf, size=16, precision='double')
    os.system('nastran scr=yes bat=no news=no old=no %s' % out_bdf)

    model2 = F06(out_f06)
    if 0:
        model2.markerMap = {
            'O U T P U T   F R O M   G R I D   P O I N T   W E I G H T   G E N E R A T O R': model2._grid_point_weight_generator,
        }
        model2.markers = model2.markerMap.keys()

    if 0:
        model2.stop_after_reading_grid_point_weight(stop=True)
    model2.read_f06()

    #print '\n'.join(dir(subcase1))
    print ""
    print "mass = %s" % model2.grid_point_weight.mass

    #========================================
    model3 = OP2(out_op2)
    model3.read_op2()
    #========================================
    for form, modeli in [('f06', model2), ('op2', model3)]:
        print "---%s---" % form
        subcase1 = modeli.rodStress[1]

        eid = 2
        print 'axial   stress[%s] = %s' % (eid, subcase1.axial[eid])
        print 'torsion stress[%s] = %s' % (eid, subcase1.torsion[eid])
        print '        stress[%s] = %s\n' % (eid, calculate_stress(subcase1.axial[eid], subcase1.torsion[eid]))

        eid = 3
        print 'axial   stress[%s] = %s' % (eid, subcase1.axial[eid])
        print 'torsion stress[%s] = %s' % (eid, subcase1.torsion[eid])
        print '        stress[%s] = %s\n' % (eid, calculate_stress(subcase1.axial[eid], subcase1.torsion[eid]))
예제 #10
0
    def test_blade2dv_fatal_2(self):
        f06_filename = os.path.join(model_path, 'blade_2dv',
                                    'blade_2dv.f06_fatal')
        bdf_filename = os.path.join(model_path, 'blade_2dv', 'blade_2dv.bdf')
        #bdf2 = self.run_model(bdfname2, dynamic_vars=dynamic_vars)
        #self.assertEquals(bdf2.properties[1].t, 42., 't=%s' % bdf2.properties[1].t)

        f06 = F06(debug=False, log=None)

        try:  # this is supposed to raise a FatalError
            f06.read_f06(f06_filename)
            assert False, 'a FATAL should have been raised'
        except FatalError:
            pass

        f06.write_f06(f06_filename + '.out')

        ref_point = f06.grid_point_weight.reference_point
        #print("ref_point = %s" % ref_point)
        ref_point_exact = 0
        self.assertEqual(ref_point, ref_point_exact)

        MO = f06.grid_point_weight.MO
        #print("MO %s" % MO)
        MO_exact = array([[
            1.22085800e-01, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
            5.33146300e-01, -1.22767700e-05
        ],
                          [
                              0.00000000e+00, 1.22085800e-01, 0.00000000e+00,
                              -5.33146300e-01, 0.00000000e+00, 1.57186600e-01
                          ],
                          [
                              0.00000000e+00, 0.00000000e+00, 1.22085800e-01,
                              1.22767700e-05, -1.57186600e-01, 0.00000000e+00
                          ],
                          [
                              0.00000000e+00, -5.33146300e-01, 1.22767700e-05,
                              3.20227600e+00, -7.13340800e-06, -6.83890800e-01
                          ],
                          [
                              5.33146300e-01, 0.00000000e+00, -1.57186600e-01,
                              -7.13340800e-06, 3.45033400e+00, -7.35886500e-05
                          ],
                          [
                              -1.22767700e-05, 1.57186600e-01, 0.00000000e+00,
                              -6.83890800e-01, -7.35886500e-05, 2.50287600e-01
                          ]])

        S = f06.grid_point_weight.S
        S_exact = array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]])
        #print("S %s" % S)

        mass = f06.grid_point_weight.mass
        mass_exact = array([0.1220858, 0.1220858, 0.1220858])
        self.assertTrue(array_equiv(mass, mass_exact))
        #print("mass = %s" % mass)

        cg = f06.grid_point_weight.cg
        cg_exact = array([[
            0.00000000e+00, 1.00558600e-04, 4.36698100e+00, 0.00000000e+00,
            0.00000000e+00, 0.00000000e+00
        ],
                          [
                              1.28751000e+00, 0.00000000e+00, 4.36698100e+00,
                              0.00000000e+00, 0.00000000e+00, 0.00000000e+00
                          ],
                          [
                              1.28751000e+00, 1.00558600e-04, 0.00000000e+00,
                              0.00000000e+00, 0.00000000e+00, 0.00000000e+00
                          ],
                          [
                              0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
                              0.00000000e+00, 0.00000000e+00, 0.00000000e+00
                          ],
                          [
                              0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
                              0.00000000e+00, 0.00000000e+00, 0.00000000e+00
                          ],
                          [
                              0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
                              0.00000000e+00, 0.00000000e+00, 0.00000000e+00
                          ]])
        #print("cg = %s", cg)
        self.assertTrue(array_equiv(cg, cg_exact))

        IS = f06.grid_point_weight.IS
        #print("IS = %s" % IS)
        IS_exact = array([[8.74036600e-01, -8.67305300e-06, -2.54028500e-03],
                          [-8.67305300e-06, 9.19714300e-01, 1.99762300e-05],
                          [-2.54028500e-03, 1.99762300e-05, 4.79082500e-02]])

        IQ = f06.grid_point_weight.IQ
        #print("IQ %s" % IQ)
        IQ_exact = array([[0.04790044, 0.9197143, 0.8740444]])
        msg = 'IQ=%s\nexact=%s' % (str(IQ), str(IQ_exact))
        self.assertTrue(array_equiv(IQ, IQ_exact), msg=msg)
예제 #11
0
    def test_blade2dv_fatal_3(self):
        f06_filename = os.path.join(model_path, 'blade_2dv',
                                    'blade_2dv.f06_fatal')
        bdf_filename = os.path.join(model_path, 'blade_2dv', 'blade_2dv.bdf')
        #bdf2 = self.run_model(bdfname2, dynamic_vars=dynamic_vars)
        #self.assertEquals(bdf2.properties[1].t, 42., 't=%s' % bdf2.properties[1].t)
        f06 = F06(debug=False, log=None)

        # we skip the fatal by stopping after reading the matrices
        f06.stop_after_reading_grid_point_weight()
        f06.read_f06(f06_filename)

        f06.write_f06(f06_filename + '.out')

        ref_point = f06.grid_point_weight.reference_point
        #print("ref_point = %s" % ref_point)
        ref_point_exact = 0
        self.assertEqual(ref_point, ref_point_exact)

        MO = f06.grid_point_weight.MO
        #print("MO = %s" % MO)
        MO_exact = array([[
            1.22085800e-01, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
            5.33146300e-01, -1.22767700e-05
        ],
                          [
                              0.00000000e+00, 1.22085800e-01, 0.00000000e+00,
                              -5.33146300e-01, 0.00000000e+00, 1.57186600e-01
                          ],
                          [
                              0.00000000e+00, 0.00000000e+00, 1.22085800e-01,
                              1.22767700e-05, -1.57186600e-01, 0.00000000e+00
                          ],
                          [
                              0.00000000e+00, -5.33146300e-01, 1.22767700e-05,
                              3.20227600e+00, -7.13340800e-06, -6.83890800e-01
                          ],
                          [
                              5.33146300e-01, 0.00000000e+00, -1.57186600e-01,
                              -7.13340800e-06, 3.45033400e+00, -7.35886500e-05
                          ],
                          [
                              -1.22767700e-05, 1.57186600e-01, 0.00000000e+00,
                              -6.83890800e-01, -7.35886500e-05, 2.50287600e-01
                          ]])

        S = f06.grid_point_weight.S
        S_exact = array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]])
        #print("S %s" % S)

        mass = f06.grid_point_weight.mass
        mass_exact = array([0.1220858, 0.1220858, 0.1220858])
        self.assertTrue(array_equiv(mass, mass_exact))
        #print("mass = %s" % mass)

        cg = f06.grid_point_weight.cg
        cg_exact = array([[
            0.00000000e+00, 1.00558600e-04, 4.36698100e+00, 0.00000000e+00,
            0.00000000e+00, 0.00000000e+00
        ],
                          [
                              1.28751000e+00, 0.00000000e+00, 4.36698100e+00,
                              0.00000000e+00, 0.00000000e+00, 0.00000000e+00
                          ],
                          [
                              1.28751000e+00, 1.00558600e-04, 0.00000000e+00,
                              0.00000000e+00, 0.00000000e+00, 0.00000000e+00
                          ],
                          [
                              0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
                              0.00000000e+00, 0.00000000e+00, 0.00000000e+00
                          ],
                          [
                              0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
                              0.00000000e+00, 0.00000000e+00, 0.00000000e+00
                          ],
                          [
                              0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
                              0.00000000e+00, 0.00000000e+00, 0.00000000e+00
                          ]])
        #print("cg = %s" % cg)
        self.assertTrue(array_equiv(cg, cg_exact))

        IS = f06.grid_point_weight.IS
        #print("IS  %s" % IS)
        IS_exact = array([[8.74036600e-01, -8.67305300e-06, -2.54028500e-03],
                          [-8.67305300e-06, 9.19714300e-01, 1.99762300e-05],
                          [-2.54028500e-03, 1.99762300e-05, 4.79082500e-02]])

        IQ = f06.grid_point_weight.IQ
        #print("IQ %s" % IQ)
        IQ_exact = array([[0.04790044, 0.9197143, 0.8740444]])
        self.assertTrue(array_equiv(IQ, IQ_exact))
예제 #12
0
def main():
    """runs the dynamic syntax problem"""
    is_op2 = True
    variables = {
        'bar1_a': 1.0,
        'bar2_a': 2.0,
        'bar3_a': 3.0,
        'loadx': 50000.0,
        'loady': 100000.0,
        'loadmag': 1.,
        'rho': 0.284,
        'youngs': 30000000.0,
    }
    model = BDF(debug=False)
    model.set_dynamic_syntax(variables)
    model.read_bdf('vared_bar3.bdf')
    out_bdf = 'out.bdf'
    out_f06 = 'out.f06'
    out_op2 = 'out.op2'

    if 'POST' in model.params:
        # change "PARAM, POST, 0"  to "PARAM, POST, -1"

        # option 1
        #model.params['POST'].update_field(2, -1)

        # option 2
        model.params['POST'].update_values(value1=-1, value2=None)

    model.write_bdf(out_bdf, size=16, is_double=False)
    os.system('nastran scr=yes bat=no news=no old=no %s' % out_bdf)

    if is_f06:
        model2 = F06()
        model2.read_f06(out_f06)
        print("")
        print("mass = %s" % model2.grid_point_weight.mass)
    else:
        model2 = None

    #========================================
    model4 = OP2()
    model4.read_op2(out_op2)

    eids = [2, 3]

    #========================================
    subcase1 = model4.crod_stress[1]
    combined_stress = calculate_stress(subcase1.data[0, :, 0],
                                       subcase1.data[0, :, 1])

    search = searchsorted(subcase1.element, eids)

    print("---op2 vectorized---")
    #[axial, torsion, SMa, SMt]
    for i, j in enumerate(search):
        eid = eids[i]
        axial = subcase1.data[0, j, 0]
        torsion = subcase1.data[0, j, 1]
        combined = combined_stress[i]
        print('axial   stress[%s] = %s' % (eid, axial))
        print('torsion stress[%s] = %s' % (eid, torsion))
        print('        stress[%s] = %s\n' % (eid, combined))
예제 #13
0
def run_f06(f06_filename,
            isubcases=None,
            write_f06=True,
            is_vector=False,
            debug=False,
            stop_on_failure=True):
    if isubcases is None:
        isubcases = []
    is_passed = False
    #stopOnFailure = False
    #debug = True
    try:
        f06 = F06(debug=debug)
        #f06.set_subcases(isubcases)  # TODO not supported

        #f06.read_bdf(f06.bdf_filename, includeDir=None, xref=False)
        f06.read_f06(f06_filename, vectorized=is_vector)
        #tableNamesF06 = parseTableNamesFromF06(f06.f06FileName)
        #tableNamesF06 = f06.getTableNamesFromF06()
        #assert write_f06 == True, write_f06
        if write_f06:
            model = os.path.splitext(f06_filename)[0]
            #print(f06.get_f06_stats())
            f06.write_f06(model + '.test_f06.f06')

        #print("subcases = ",f06.subcases)

        #assert tableNamesF06==tableNamesF06,'tableNamesF06=%s tableNamesF06=%s' %(tableNamesF06,tableNamesF06)
        #f06.case_control_deck.sol = f06.sol
        #print(f06.case_control_deck.getF06Data())
        #print(f06.print_results())
        #print(f06.case_control_deck.getF06Data())
        is_passed = True
    except KeyboardInterrupt:
        sys.stdout.flush()
        print_exc(file=sys.stdout)
        sys.stderr.write('**file=%r\n' % f06_filename)
        sys.exit('keyboard stop...')
    #except AddNewElementError:
    #    raise
    #except IOError: # missing file
    #pass
    #except AssertionError:
    #    is_passed = True
    except FatalError:  # remove this later...
        is_passed = True
    #except InvalidFormatCodeError:
    #    is_passed = True
    #except RuntimeError: #InvalidAnalysisCode
    #    is_passed = True
    #except SyntaxError: #Invalid Markers
    #    is_passed = True
    except SystemExit:
        #print_exc(file=sys.stdout)
        #sys.exit('stopping on sys.exit')
        raise
    #except NameError:  # variable isnt defined
    #    if stop_on_failure:
    #        raise
    #    else:
    #        is_passed = True
    #except AttributeError:  # missing function
    #    if stop_on_failure:
    #        raise
    #    else:
    #        is_passed = True
    #except KeyError:
    #    raise
    #except TypeError:  # numpy error
    #    is_passed = True
    #except IndexError: # bad bdf
    #    is_passed = True
    #except IOError:  # missing bdf file
    #is_passed = False
    #raise
    #except SyntaxError: #Invalid Subcase
    #    is_passed = True
    #except SyntaxError: # Param Parse:
    #    is_passed = True
    #except NotImplementedError:
    #is_passed = True
    #except InvalidFieldError: # bad bdf field
    #    is_passed = True
    except:
        #print(e)
        print_exc(file=sys.stdout)
        if stop_on_failure:
            raise
        else:
            is_passed = False
    #print("is_passed = %s" % is_passed)
    return is_passed
예제 #14
0
def run_f06(f06file,
            iSubcases=[],
            write_f06=True,
            printF06=False,
            debug=False,
            stopOnFailure=True):
    isPassed = False
    stopOnFailure = False
    #debug = True
    try:
        f06 = F06(f06file, debug=debug)
        #f06.set_subcases(iSubcases)  # TODO not supported

        #f06.readBDF(f06.bdf_filename,includeDir=None,xref=False)
        f06.readF06()
        #tableNamesF06 = parseTableNamesFromF06(f06.f06FileName)
        #tableNamesF06 = f06.getTableNamesFromF06()
        if write_f06:
            (model, ext) = os.path.splitext(f06file)
            f06.write_f06(model + '.f06.out')

        if printF06:
            f06.print_results()
        #print "subcases = ",f06.subcases

        #assert tableNamesF06==tableNamesF06,'tableNamesF06=%s tableNamesF06=%s' %(tableNamesF06,tableNamesF06)
        pass
        #f06.caseControlDeck.sol = f06.sol
        #print f06.caseControlDeck.getF06Data()
        #print f06.print_results()
        #print f06.caseControlDeck.getF06Data()
        isPassed = True
    except KeyboardInterrupt:
        sys.stdout.flush()
        print_exc(file=sys.stdout)
        sys.stderr.write('**file=%s\n' % (f06file))
        sys.exit('keyboard stop...')
    #except AddNewElementError:
    #    raise
    #except IOError: # missing file
    #pass
    #except AssertionError:
    #    isPassed = True

    #except InvalidFormatCodeError:
    #    isPassed = True
    #except RuntimeError: #InvalidAnalysisCode
    #    isPassed = True
    #except SyntaxError: #Invalid Markers
    #    isPassed = True
    except SystemExit:
        #print_exc(file=sys.stdout)
        #sys.exit('stopping on sys.exit')
        raise
    #except NameError:  # variable isnt defined
    #    if stopOnFailure:
    #        raise
    #    else:
    #        isPassed = True
    #except AttributeError:  # missing function
    #    if stopOnFailure:
    #        raise
    #    else:
    #        isPassed = True
    #except KeyError:
    #    raise
    #except TypeError:  # numpy error
    #    isPassed = True
    #except IndexError: # bad bdf
    #    isPassed = True
    except IOError:  # missing bdf file
        isPassed = False
        raise
    #except SyntaxError: #Invalid Subcase
    #    isPassed = True
    #except SyntaxError: # Param Parse:
    #    isPassed = True
    except NotImplementedError:
        isPassed = True
    #except InvalidFieldError: # bad bdf field
    #    isPassed = True
    except:
        #print e
        print_exc(file=sys.stdout)
        if stopOnFailure:
            raise
        else:
            isPassed = False
    return isPassed
예제 #15
0
    def execute(self):
        """Runs the NastranComponent.

        We are overiding ExternalCode's execute function.
        The steps are:
           1. Get a list of the input variables
           2. Read the BDF file into pyNastran's BDF object
           3. Using the info collected in Step #1, replace some
                of the values in the BDF object
           4. Call the update_hook method. Subclasses can override that
               to do processing of the BDF file before it is written out
               again
           5. Write the modified BDF file
           6. Run Nastran
           7. Read the OP2 file ( and the F06 if needed to get Nastran run error info )
           8. Read the results from the OP2 file and set output variables for this
                Component

        RuntimeError
            The component relies on ExternalCode which can throw all
            sorts of RuntimeError-like exceptions (RunStopped,
            RunInterrupted also included).

        Filesystem-type Errors
            NastranComponent makes a temporary directory with mkdtemp
            in the temp module. If that fails, the error just
            propagates up.


        While there are no explicit parameters or return values for this
        function, it gets all the input it needs from the design
        variables that are connected to the subclass of NastranComponent.
        This should be described pretty well in the :ref:`documentation<NastranComponent>`.

        """

        # all of these are {"traitname" : trait}
        smart_replacements = {}
        output_variables = {}
        grid_outputs = {}

        for name, trait in iteritems(self.traits()):
            if trait.iotype == "in":
                if trait.nastran_card and trait.nastran_id and trait.nastran_field:
                    smart_replacements[name] = trait
                elif trait.nastran_card or trait.nastran_id or trait.nastran_fieldnum:
                    raise RuntimeError("You specified at least one of " + \
                                    "nastran_card, nastran_id, and " + \
                                    "nastran_fieldnum, but you did " + \
                                    "not specify all of them. You " + \
                                    "most probably mistyped.")

            elif trait.iotype == "out":

                # if we want to supply a function that will parse
                # out the wanted information from the output object
                if trait.nastran_func:
                    output_variables[name] = trait

                # this is the grid method of accessing. We have to
                # specify a header, id, and column and
                # the output variable will be set to that value
                elif trait.nastran_header and trait.nastran_constraints :
                    grid_outputs[name] = trait
                elif trait.nastran_header or trait.nastran_constraints:
                    raise RuntimeError("You specified at least one of " + \
                                    "nastran_header and nastran_constraints"+\
                                    ", but you " + \
                                    "did not specify all them. You " + \
                                    "most probably mistyped")

        # do our work in a tmp dir
        tmpdir = mkdtemp(dir = self.output_tempdir_dir)
        tmppath = os.path.join(tmpdir, "input.bdf")

        pyNastran_get_card_methods = {
            'PSHELL': 'Property',
            'PROD': 'Property',
            'FORCE': 'Load',
            'MAT1': 'Material',
            }

        ########## Read BDF ##########
        self.timing_section( "Read BDF" )

        self.bdf = BDF(debug=False,log=logging.getLogger() )
        self.bdf.readBDF(self.nastran_filename,xref=True)

        ########## Modify BDF ##########
        self.timing_section( "Modify BDF" )
        for name, trait in iteritems(smart_replacements):
            value = getattr(self, name)
            nastran_id = int( trait.nastran_id )
            get_method = getattr( self.bdf, pyNastran_get_card_methods[ trait.nastran_card ] )
            # some of these methods have an extra arg for error reporting
            args = inspect.getargspec(get_method).args
            if 'msg' in args:
                nastran_item = get_method( nastran_id, 'dummy msg' )
            else:
                nastran_item = get_method( nastran_id )

            if trait.nastran_card == 'FORCE' :
                nastran_item = nastran_item[0]

            setattr(nastran_item, trait.nastran_field, value)

        ########## update hook ##########
        self.update_hook()

        ########## write modified BDF ##########
        self.timing_section( "Write modified BDF" )
         #self.bdf.write_bdf(tmppath)
        self.bdf.write_bdf(tmppath,precision='double',size=16)

        ########## Run Nastran via subprocess ##########
        self.timing_section( "Run Nastran" )
        self.output_filename = os.path.join(tmpdir, "input.out")
        print(self.output_filename)  # perhaps this should be logged, or something

        # Then we run the nastran file
        if self.nastran_command == 'python':  # True when using fake_nastran.py
            self.command = [self.nastran_command,
                            self.nastran_command_args[0], tmppath]
            self.command.extend(self.nastran_command_args[1:])
        else:
            self.command = [self.nastran_command, tmppath]
            self.command.extend(self.nastran_command_args)
        self.command.extend(["batch=no", "out=" + tmpdir, "dbs=" + tmpdir])

        # This calls ExternalCode's execute which will run
        super(NastranComponent, self).execute()

        ########## read OP2 ##########
        self.timing_section( "Read OP2" )
        op2_filename = self.output_filename[:-4] + '.op2'
        f06_filename = self.output_filename
        self.op2 = OP2(op2_filename, debug=False,log=None)
        #self.op2.make_op2_debug = True   # can create a HUGE file that slows things down a lot

        if os.path.exists(op2_filename):
            try:
                self.op2.read_op2()  # doesn't tell you what the error message is
            except FatalError:
                try:
                    self.f06 = F06(f06_filename,debug=False)  # debug True makes it slow
                    self.f06.read_f06()
                except FatalError as err:
                    raise RuntimeError('Nastran fatal error:' + str( err ) )
        elif os.path.exists(f06_filename):
            try:
                self.f06 = F06(f06_filename,debug=False)  # debug True makes it slow
                self.f06.read_f06()  # this will stop with a FatalError with the proper FATAL message
            except FatalError as err:
                raise RuntimeError('Nastran fatal error:' + str( err ) )
        else:
            raise RuntimeError('nastran fatal error' )

        ########## get the outputs using pyNastran ##########
        self.timing_section( "Set outputs using data from OP2" )

        from pyNastran.utils import object_attributes
        for name, trait in iteritems(grid_outputs):
            if trait.nastran_header == 'displacements' :
                var = getattr(self.op2, trait.nastran_header)
                case = var[trait.nastran_subcase]
                for key, eid in iteritems(trait.nastran_constraints):  # e.g., "translations", 18
                    if not hasattr(case, key):
                        #op2.displacements[isubcase=1] doesn't have an attribute "translation".
                        #valid attributes are:  ["translations", "rotations"]
                        msg = "op2.%s[isubcase=%i] does not have an attribute '%s'. " % (trait.nastran_header, trait.nastran_subcase, key )
                        msg += "Valid attributes are: %s" % str(['%s' % att for att in object_attributes(case)])
                        raise KeyError(msg)
                    results_data = getattr(case, key)  # get the translations
                    if trait.nastran_time_step_freq_mode:
                        disp = results_data[trait.nastran_time_step_freq_mode][eid]
                    else:  # "transient" result
                        disp = results_data[eid] # get the specific ID
                    setattr( self, name, disp[trait.nastran_dof] )
            else:
                raise RuntimeError("The Nastran header, %s, is not supported yet" % trait.nastran_header )