Exemplo n.º 1
0
    def __init__(self,
                 make_geom=True,
                 debug=False,
                 log=None,
                 debug_file=None,
                 mode='msc'):
        """
        Initializes the OP2 object

        Parameters
        ----------
        make_geom : bool; default=False
            reads the BDF tables
        debug : bool; default=False
            enables the debug log and sets the debug in the logger
        log: log()
            a logging object to write debug messages to
            (.. seealso:: import logging)
        debug_file : default=None -> no debug
            sets the filename that will be written to
        mode : str; default='msc'
            {msc, nx}
        """
        BDF.__init__(self, debug=debug, log=log, mode=mode)
        OP2GeomCommon.__init__(self,
                               debug=debug,
                               log=log,
                               debug_file=debug_file,
                               mode=mode)
Exemplo n.º 2
0
def compare_card_count(fem1: BDF, fem2: BDF,
                       print_stats: bool=False, quiet: bool=False) -> List[str]:
    """Checks that no cards from fem1 are lost when we write fem2"""
    cards1 = fem1.card_count
    cards2 = fem2.card_count
    for key in cards1:
        if key != key.upper():
            raise RuntimeError('Proper capitalization wasnt determined')
    if print_stats:
        print(fem1.get_bdf_stats())
        print(fem1.loads)
    else:
        fem1.get_bdf_stats()
    return compute_ints(cards1, cards2, fem1, quiet=quiet)
Exemplo n.º 3
0
def test_get_cards_by_card_types(model: BDF) -> None:
    """
    Verifies the ``model.get_cards_by_card_types`` method works
    """
    # setup to remove hackish cards
    card_types = list(model.card_count.keys())
    removed_cards = []
    for card_type in ['ENDDATA', 'INCLUDE', 'JUNK']:
        if card_type in model.card_count:
            removed_cards.append(card_type)
    for removed_card in removed_cards:
        card_types.remove(removed_card)

    removed_cards = []
    for card_type in card_types:
        if card_type not in model.cards_to_read:
            try:
                removed_cards.append(card_type)
                #print('removed %s' % card_type)
            except ValueError:
                msg = 'card_type=%s cant be removed' % card_type
                raise ValueError(msg)
    for removed_card in removed_cards:
        card_types.remove(removed_card)

    # we now have a list of card types we would like to extract
    # we'll get the associated cards
    card_dict = model.get_cards_by_card_types(card_types,
                                              reset_type_to_slot_map=False)
    for card_type, cards in card_dict.items():
        for card in cards:
            msg = 'this should never crash here...card_type=%s card.type=%s' % (
                card_type, card.type)
            if card_type != card.type:
                raise RuntimeError(msg)
Exemplo n.º 4
0
def remake_model(bdf_model, fem1, pickle_obj):
    """reloads the model if we're testing pickling"""
    remake = pickle_obj
    if remake:
        #log = fem1.log
        model_name = os.path.splitext(bdf_model)[0]
        obj_model = '%s.test_bdfv.obj' % (model_name)
        #out_model_8 = '%s.test_bdfv.bdf' % (model_name)
        #out_model_16 = '%s.test_bdfv.bdf' % (model_name)

        fem1.save(obj_model)
        fem1.save(obj_model, unxref=False)
        #fem1.write_bdf(out_model_8)
        fem1.get_bdf_stats()

        fem1 = BDF(debug=fem1.debug, log=fem1.log)
        fem1.load(obj_model)
        #fem1.write_bdf(out_model_8)
        #fem1.log = log
        os.remove(obj_model)
        fem1.get_bdf_stats()
    return fem1
Exemplo n.º 5
0
    def test_cord2_rcs_03(self):
        """
        all points are located at <30,40,50>
        """
        model = BDF(debug=False)
        cards = [
            [
                'CORD2S*                2               0              0.              0.',
                '*                     0.              0.              0.              1.*       ',
                '*                     1.              0.              1.',],
            [
                #'$ Coordinate System 30 : rectangular in spherical',
                'CORD2R*               30               2             14.             30.',
                '*                    70.    13.431863852   32.1458443949   75.2107442927*       ',
                '*          14.4583462334   33.4569982885   68.2297989286',],
            [
                #'$ Coordinate System 31 : cylindrical in spherical',
                'CORD2C*               31               2              3.             42.',
                '*                  -173.   2.86526881213   45.5425615252   159.180363517*       ',
                '*          3.65222385965   29.2536614627  -178.631312271',],
            [
                #'$ Coordinate System 32 : spherical in spherical',
                'CORD2S*               32               2             22.             14.',
                '*                    85.   22.1243073983   11.9537753718   77.9978191005*       ',
                '*          21.0997242967   13.1806120497   88.4824763008',],
            [
                'GRID*                 30              30   40.7437952957  -23.6254877994',
                '*           -33.09784854               0',],
            [
                'GRID*                 31              31   62.9378078196   15.9774797923',
                '*          31.0484428362               0',],
            [
                'GRID*                 32              32   53.8270847449   95.8215692632',
                '*          159.097767463               0',],
        ]
        for lines in cards:
            card = model._process_card(lines)
            model.add_card(card, card[0])
        unused_xyz_cid0b = model.get_xyz_in_coord_no_xref(cid=0, fdtype='float64')
        unused_xyz_cid0c = model.get_xyz_in_coord_no_xref(cid=32, fdtype='float64')
        bdf_file = StringIO()
        model.write_bdf(bdf_file, close=False)
        bdf_file.seek(0)

        #-------------------------------------------------
        model.cross_reference()

        model2 = BDFv(debug=False)
        model2.read_bdf(bdf_file, punch=True, xref=False, save_file_structure=False)
        bdf_file.seek(0)
        #-------------------------------------------------

        xyz_cid0_actual = array([
            [30., 40., 50.],
            [30., 40., 50.],
            [30., 40., 50.],
        ], dtype='float64')
        for nid in model.nodes:
            node = model.Node(nid)
            a = array([30., 40., 50.])
            b = node.get_position()
            self.assertTrue(allclose(array([30., 40., 50.]),
                                     node.get_position()), str(a - b))
        xyz_cid0 = model.get_xyz_in_coord(cid=0, fdtype='float64')
        assert np.allclose(xyz_cid0_actual, xyz_cid0), '%s' % (xyz_cid0_actual - xyz_cid0)

        out = model.get_displacement_index_xyz_cp_cd()
        unused_icd_transform, icp_transform, xyz_cp, nid_cp_cd = out
        nids = nid_cp_cd[:, 0]
        xyz_cid0_xform = model.transform_xyzcp_to_xyz_cid(
            xyz_cp, nids, icp_transform, cid=0)
        array_equal(xyz_cid0_actual, xyz_cid0_xform)
        assert array_equal(nids, array([30, 31, 32]))
        model2.nodes.nids = nid_cp_cd[:, 0]


        for cid in [30, 31, 32]:
            unused_xyz_cid_a = model.transform_xyzcp_to_xyz_cid(
                xyz_cp, nids, icp_transform, cid=cid)
            unused_xyz_cid_b = model2.transform_xyzcp_to_xyz_cid(
                xyz_cp, nids, icp_transform, cid=cid, atol=None)
            #assert np.allclose(xyz_cid_a, xyz_cid_b), '%s' % np.isclose(xyz_cid_a, xyz_cid_b)

            #print(xyz_cid_a)
            #print(xyz_cid_b)
            #print(xyz_cid_a - xyz_cid_b)
            #print('-------------')
            #assert array_equal(xyz_cid_a, xyz_cid_b), 'error=%s'  % (
                #xyz_cid_a - xyz_cid_b)

        #---------------------------------------------
        xyz_cid0 = model.transform_xyzcp_to_xyz_cid(
            xyz_cp, nids, icp_transform,
            cid=0, atol=None)
        array_equal(xyz_cid0_actual, xyz_cid0)

        model.write_bdf(bdf_file, close=False)

        model3 = BDF(debug=False)
        origin = [14., 30., 70.]
        zaxis = [13.431863852, 32.1458443949, 75.2107442927]
        xzplane = [14.4583462334, 33.4569982885, 68.2297989286]
        cord2r = model3.add_cord2r(30, origin, zaxis, xzplane, rid=2, comment='')

        origin = [3., 42., -173.]
        zaxis = [2.86526881213, 45.5425615252, 159.180363517]
        xzplane = [3.65222385965, 29.2536614627, -178.631312271]
        cord2c = model3.add_cord2c(31, origin, zaxis, xzplane, rid=2, comment='')

        origin = [22., 14., 85.]
        zaxis = [22.1243073983, 11.9537753718, 77.9978191005]
        xzplane = [21.0997242967, 13.1806120497, 88.4824763008]
        cord2s = model3.add_cord2s(32, origin, zaxis, xzplane, rid=2, comment='')

        assert cord2r == model.coords[cord2r.cid], 'cord2r:\n%r\ncord2r[cid]:\n%r' % (str(cord2r), str(model.coords[cord2r.cid]))
        assert cord2c == model.coords[cord2c.cid], 'cord2c:\n%r\ncord2c[cid]:\n%r' % (str(cord2c), str(model.coords[cord2c.cid]))
        assert cord2s == model.coords[cord2s.cid], 'cord2s:\n%r\ncord2s[cid]:\n%r' % (str(cord2s), str(model.coords[cord2s.cid]))
Exemplo n.º 6
0
def run_fem2(bdf_model,
             out_model,
             xref,
             punch,
             sum_load,
             size,
             is_double,
             mesh_form,
             encoding=None,
             debug=False,
             quiet=False,
             stop_on_failure=True):
    """
    Reads/writes the BDF to verify nothing has been lost

    Parameters
    ----------
    bdf_model : str
        the filename to run
    out_model
    xref : bool
       xrefs
    punch : bool
       punches
    sum_load : bool
       sums static load
    size : int
        ???
    is_double : bool
        ???
    mesh_form : str {combined, separate}
        'combined' : interspersed=True
        'separate' : interspersed=False
    debug : bool
        debugs
    quiet : bool
        supress prints
    """
    assert os.path.exists(bdf_model), bdf_model
    assert os.path.exists(out_model), out_model

    fem2 = BDF(debug=debug, log=None)
    if not quiet:
        fem2.log.info('starting fem2')
    sys.stdout.flush()
    try:
        fem2.read_bdf(out_model, xref=False, punch=punch, encoding=encoding)
    except:
        print("failed reading %r" % out_model)
        raise

    out_model_2 = bdf_model + '_out2'

    if xref and sum_load:
        if 'POST' in fem2.params:
            value = fem2.params['POST'].values[0]
            if value >= 0:
                msg = 'PARAM,POST,%i is not supported by the OP2 reader' % value
                fem2.log.error(msg)
        else:
            msg = 'PARAM,POST,0 is not supported by the OP2 reader'
            fem2.log.error(msg)

        p0 = np.array([0., 0., 0.])

        subcase_keys = fem2.case_control_deck.get_subcase_list()
        subcases = fem2.subcases

        sol_200_map = fem2.case_control_deck.sol_200_map
        sol_base = fem2.sol
        is_restart = False
        for line in fem2.system_command_lines:
            if line.strip().upper().startswith('RESTART'):
                is_restart = True
        #if not is_restart:
        #validate_case_control(fem2, p0, sol_base, subcase_keys, subcases, sol_200_map,
        #stop_on_failure=stop_on_failure)

    if mesh_form is not None:
        fem2.write_bdf(out_model_2,
                       interspersed=False,
                       size=size,
                       is_double=is_double)
        os.remove(out_model_2)
    #fem2.write_as_ctria3(out_model_2)
    return fem2
Exemplo n.º 7
0
def run_and_compare_fems(
    bdf_model,
    out_model,
    debug=False,
    xref=True,
    check=True,
    punch=False,
    cid=None,
    mesh_form='combined',
    print_stats=False,
    encoding=None,
    sum_load=True,
    size=8,
    is_double=False,
    stop=False,
    nastran='',
    post=-1,
    dynamic_vars=None,
    quiet=False,
    dumplines=False,
    dictsort=False,
    nerrors=0,
    dev=False,
    crash_cards=None,
    safe_xref=True,
    run_extract_bodies=False,
    pickle_obj=False,
    stop_on_failure=True,
):
    """runs two fem models and compares them"""
    assert os.path.exists(bdf_model), '%r doesnt exist' % bdf_model

    fem1 = BDF(debug=debug, log=None)

    fem1.set_error_storage(nparse_errors=nerrors,
                           stop_on_parsing_error=True,
                           nxref_errors=nerrors,
                           stop_on_xref_error=True)
    if dynamic_vars:
        fem1.set_dynamic_syntax(dynamic_vars)

    if not quiet:
        fem1.log.info('starting fem1')
    sys.stdout.flush()
    fem2 = None
    diff_cards = []

    try:
        #nastran_cmd = 'nastran scr=yes bat=no old=no news=no '
        nastran_cmd = ''
        #try:

        fem1 = run_fem1(fem1,
                        bdf_model,
                        out_model,
                        mesh_form,
                        xref,
                        punch,
                        sum_load,
                        size,
                        is_double,
                        cid,
                        run_extract_bodies=run_extract_bodies,
                        encoding=encoding,
                        crash_cards=crash_cards,
                        safe_xref=safe_xref,
                        pickle_obj=pickle_obj,
                        stop=stop)
        if stop:
            if not quiet:
                print('card_count:')
                print('-----------')
                for card_name, card_count in sorted(iteritems(
                        fem1.card_count)):
                    print('key=%-8s value=%s' % (card_name, card_count))
            return fem1, None, None
        fem2 = run_fem2(bdf_model,
                        out_model,
                        xref,
                        punch,
                        sum_load,
                        size,
                        is_double,
                        mesh_form,
                        encoding=encoding,
                        debug=debug,
                        quiet=quiet,
                        stop_on_failure=stop_on_failure)

        diff_cards = compare(fem1,
                             fem2,
                             xref=xref,
                             check=check,
                             print_stats=print_stats,
                             quiet=quiet)
        test_get_cards_by_card_types(fem2)

        #fem2.update_model_by_desvars(xref)
        #except:
        #return 1, 2, 3

        run_nastran(bdf_model, nastran_cmd, post, size, is_double)

    except KeyboardInterrupt:
        sys.exit('KeyboardInterrupt...sys.exit()')
    except IOError:  # only temporarily uncomment this when running lots of tests
        if not dev:
            raise
    except CardParseSyntaxError:  # only temporarily uncomment this when running lots of tests
        if not dev:
            raise
        print('failed test because CardParseSyntaxError...ignoring')
    except MissingDeckSections:
        if not dev:
            raise
        print('failed test because MissingDeckSections...ignoring')
    except DuplicateIDsError as e:
        # only temporarily uncomment this when running lots of tests
        if 'GRIDG' in fem1.card_count or 'CGEN' in fem1.card_count or 'SPCG' in fem1.card_count:
            print(
                'failed test because mesh adaption (GRIDG,CGEN,SPCG)...ignoring'
            )
            print(e)
        elif not dev:
            raise
        else:
            print('failed test because DuplicateIDsError...ignoring')
    except DisabledCardError as e:
        if not dev:
            raise
    except RuntimeError as e:
        # only temporarily uncomment this when running lots of tests
        if not dev:
            raise
        if 'GRIDG' in fem1.card_count or 'CGEN' in fem1.card_count or 'SPCG' in fem1.card_count:
            print(
                'failed test because mesh adaption (GRIDG,CGEN,SPCG)...ignoring'
            )
            print(e)
        else:
            raise
    #except AttributeError:  # only temporarily uncomment this when running lots of tests
    #pass
    except SyntaxError as e:
        # only temporarily uncomment this when running lots of tests
        if not dev:
            raise
        if 'GRIDG' in fem1.card_count or 'CGEN' in fem1.card_count or 'SPCG' in fem1.card_count:
            print(
                'failed test because mesh adaption (GRIDG,CGEN,SPCG)...ignoring'
            )
            print(e)
        else:
            raise
    except KeyError as e:  # only temporarily uncomment this when running lots of tests
        if not dev:
            raise
        if 'GRIDG' in fem1.card_count or 'CGEN' in fem1.card_count or 'SPCG' in fem1.card_count:
            print(
                'failed test because mesh adaption (GRIDG,CGEN,SPCG)...ignoring'
            )
            print(e)
        else:
            raise
    #except AssertionError:  # only temporarily uncomment this when running lots of tests
    #pass
    except SystemExit:
        sys.exit('sys.exit...')
    except:
        #exc_type, exc_value, exc_traceback = sys.exc_info()
        #print "\n"
        traceback.print_exc(file=sys.stdout)
        #print msg
        print("-" * 80)
        raise

    if not quiet:
        print("-" * 80)
    return (fem1, fem2, diff_cards)