예제 #1
0
def _check_element_node(table1: BaseElement, table2: BaseElement, log: SimpleLogger) -> None:
    """checks the ``element_node`` variable"""
    if not hasattr(table1, 'element_node'):
        return
    if table1.element_node is None:
        return

    if not np.array_equal(table1.element_node, table2.element_node):
        if table1.element_node.shape != table2.element_node.shape:
            msg = (
                f'{table1}\n'
                f'table1.element_node.shape={table1.element_node.shape} '
                f'table2.element_node.shape={table2.element_node.shape}')

            print(table1.element_node.tolist())
            print(table2.element_node.tolist())
            raise ValueError(msg)
        msg = f'table_name={table1.table_name!r} class_name={table1.__class__.__name__}\n'
        msg += '%s\n' % str(table1.code_information())
        for i, (eid1, nid1), (eid2, nid2) in zip(count(), table1.element_node, table2.element_node):
            msg += '%s : (%s, %s), (%s, %s)\n' % (i, eid1, nid1, eid2, nid2)
        print(msg)
        raise ValueError(msg)

    eids = table1.element_node[:, 0]
    if eids.min() <= 0:
        print(table1.element_node)
        print(table2.element_node)
        log.error(f'{table1}\neids={eids}.min={eids.min()}; n={len(eids)}')
        raise ValueError(f'{table1}\neids={eids}.min={eids.min()}; n={len(eids)}')
예제 #2
0
def _check_element(table1: BaseElement, table2: BaseElement, log: SimpleLogger) -> None:
    """checks the ``element_node`` variable"""
    if not hasattr(table1, 'element'):
        return
    if table1.element is None:
        return

    if not np.array_equal(table1.element, table2.element):
        assert table1.element.shape == table2.element.shape, 'shape=%s element.shape=%s' % (
            table1.element.shape, table2.element.shape)
        msg = f'table_name={table1.table_name!r} class_name={table1.__class__.__name__}\n'
        msg += '%s\nEid\n' % str(table1.code_information())
        for eid1, eid2 in zip(table1.element, table2.element):
            msg += '%s, %s\n' % (eid1, eid2)
        print(msg)
        raise ValueError(msg)

    element = table1.element
    eid_min = element.min()
    nshape = len(element.shape)
    if eid_min <= 0:
        if nshape == 1:
            msg = (f'{table1}\ntable_name={table1.table_name}\n'
                      f'eids={element}.min = {eid_min}')
            log.error(msg)
        else:
            if table1.table_name not in ['ONRGY1', 'ONRGY2']:
                msg = f'table_name = {table1.table_name}\n'
                for i, eidsi in enumerate(element):
                    eid_min = eidsi.min()
                    if eid_min <= 0:
                        msg += f'{table1}\neids[{i}]={eidsi}.min = {eid_min}\n'
                log.error(msg)
예제 #3
0
 def test_simple_logger(self):
     """tests all the logging levels"""
     log = SimpleLogger(level='critical')
     log.info('info')
     log.warning('warning')
     log.error('error')
     log.debug('debug')
     log.exception('exception')
     out = log.critical('critical')
     assert out is None
예제 #4
0
def build_actions(self: QMainWindow, base_actions: Dict[str, QAction],
                  icon_path: str, tools_list: List[Tuple[str, str, str, str,
                                                         str, Callable[Any]]],
                  checkables_set: Set[str],
                  log: SimpleLogger) -> Dict[str, Any]:
    checkables = {}

    actions = base_actions
    for tool in tools_list:
        (name, txt, icon, shortcut, tip, func) = tool
        if name in actions:
            log.error('trying to create a duplicate action %r' % name)
            continue

        if icon is None:
            msg = f'missing_icon = {name!r}!!!'
            print(msg)
            self.log.warning(msg)
            ico = None
        else:
            ico = QtGui.QIcon()
            pth = os.path.join(icon_path, icon)
            if icon.endswith('.png') and not os.path.exists(pth):
                self.log.warning(str((name, pth)))

            ico.addPixmap(QtGui.QPixmap(pth), QtGui.QIcon.Normal,
                          QtGui.QIcon.Off)

        if name in checkables:
            is_checked = checkables[name]
            actions[name] = QAction(ico, txt, self, checkable=True)
            actions[name].setChecked(is_checked)
        else:
            actions[name] = QAction(ico, txt, self)

        if shortcut:
            actions[name].setShortcut(shortcut)
            #actions[name].setShortcutContext(QtCore.Qt.WidgetShortcut)
        if tip:
            actions[name].setStatusTip(tip)
        if func:
            actions[name].triggered.connect(func)
    return actions
예제 #5
0
    def test_gpforce_02(self):
        IS_MATPLOTLIB = False
        op2_filename = os.path.join(MODEL_PATH, 'grid_point_forces', 'bar_grid_point_forces.op2')
        #from pyNastran.bdf.bdf import read_bdf
        #bdf_model = read_bdf()
        log = SimpleLogger(level='warning')
        model = read_op2(op2_filename, load_geometry=True, combine=True,
                         exclude_results=None, log=log)
        log = model.log
        gpforce = model.grid_point_forces[1]  # type: RealGridPointForcesArray
        force = model.cbar_force[1]
        #['station', 'bending_moment1', 'bending_moment2', 'shear1', 'shear2', 'axial', 'torque']
        headers = force.get_headers()
        #istation = headers.index('station')
        itime = 0
        #ibending_moment1 = headers.index('bending_moment1')
        ibending_moment2 = headers.index('bending_moment2')
        #station = force.data[itime, :, istation]
        #bending_moment1 = force.data[itime, :, ibending_moment1]
        bending_moment2 = force.data[itime, :, ibending_moment2]

        coord_out = model.coords[0]
        nid_cp_cd, xyz_cid0, xyz_cp, icd_transform, icp_transform = model.get_xyz_in_coord_array(
            cid=0, fdtype='float64', idtype='int32')
        all_nids = nid_cp_cd[:, 0]

        all_eids, element_centroids_cid0 = get_element_centroids(model, idtype='int32', fdtype='float64')
        #stations = element_centroids_cid0[:-1, 0]
        stations = np.linspace(0., 10., num=51)
        #model.log.level = 'warning'
        #print(stations)

        nids_bar = []
        nids_beam = []
        for eid, elem in sorted(model.elements.items()):
            if elem.type == 'CBAR':
                nids_bar.append(elem.nodes)
            elif elem.type == 'BEAM':
                nids_beam.append(elem.nodes)
        nids_bar = np.array(nids_bar, dtype='int32')
        nids_beam = np.array(nids_beam, dtype='int32')
        inid_bar = np.searchsorted(all_nids, nids_bar)
        x1 = xyz_cid0[inid_bar[:, 0], 0]
        x2 = xyz_cid0[inid_bar[:, 1], 0]

        with self.assertRaises(AssertionError):
            log.error('problem with extract_freebody_loads...')
            fb_force, fb_moment = gpforce.extract_freebody_loads(
                all_eids,
                coord_out, model.coords,
                nid_cp_cd,
                icd_transform,
                itime=0, debug=True,
                log=log)

        if IS_MATPLOTLIB:  # pragma: no cover
            fig = plt.figure()
            ax = fig.gca()
            L = 10.0
            x = xyz_cid0[:, 0].copy()
            x.sort()
            M = x ** 2 / 2
            # F = wx
            # M = wx^2/2
            ax.plot(x1, bending_moment2[::2], 'o-', label='BM2', linewidth=3)
            ax.plot(x2, bending_moment2[1::2], 'o--', )
            ax.plot(L-x, M, 'o-', label='exact', linewidth=1)
            ax.grid(True)

        #nids = [1]
        #eids = [1]
        force_out_sum, moment_out_sum = gpforce.extract_interface_loads(
            all_nids, all_eids,
            coord_out, model.coords,
            nid_cp_cd, icd_transform,
            xyz_cid0,
            #summation_point: Optional[NDArray3float]=None,
            consider_rxf=True, itime=0,
            debug=True, log=log)
        assert np.allclose(force_out_sum, [0., 0., 0.]), force_out_sum
        assert np.allclose(moment_out_sum, [0., 0., 0.]), moment_out_sum

        # this one is empty...
        nids = [1]
        eids = [2]
        force_out_sum, moment_out_sum = gpforce.extract_interface_loads(
            nids, eids,
            coord_out, model.coords,
            nid_cp_cd, icd_transform,
            xyz_cid0,
            #summation_point: Optional[NDArray3float]=None,
            consider_rxf=True, itime=0,
            debug=True, log=log)
        #assert force_out.size == 0, force_out
        #assert moment_out.size == 0, moment_out
        assert not np.any(np.isfinite(force_out_sum)), force_out_sum
        assert not np.any(np.isfinite(moment_out_sum)), moment_out_sum
        #coord0 = model.coords[0]
        #gpforce.extract_interface_loads(nids: np.ndarray,
                                        #eids: np.ndarray,
                                        #coord_out=coord0,
                                        #model.coords,
                                        #nid_cd,
                                        #icd_transform,
                                        #xyz_cid0,
                                        #summation_point=None,
                                        #consider_rxf=True,
                                        #itime=0,
                                        #debug=True,
                                        #log=model.log,
                                        #idtype='int32')
        # ----------------------------------------
        nodes_list = list(model.nodes.keys())
        nids = np.array(nodes_list, dtype='int32')
        nids.sort()
        #eids = np.ndarray(list(model.elements.keys()), dtype='int32')
        #eids.sort()
        # bar is [0,10] in x
        force_sum, moment_sum = gpforce.shear_moment_diagram(
                                        xyz_cid0,
                                        all_eids,
                                        nids,
                                        icd_transform,
                                        element_centroids_cid0,
                                        model.coords,
                                        nid_cp_cd,
                                        stations,
                                        coord_out,
                                        idir=0, itime=0,
                                        debug=True, log=model.log)
        force_sum_expected = np.array([
            [0.,  0., -9.5],
            [0.,  0., -9.5],
            [0.,  0., -9.5],
            [0.,  0., -9.5],
            [0.,  0., -9.5],
            [0.,  0., -8.5],
            [0.,  0., -8.5],
            [0.,  0., -8.5],
            [0.,  0., -8.5],
            [0.,  0., -8.5],
            [0.,  0., -7.5],
            [0.,  0., -7.5],
            [0.,  0., -7.5],
            [0.,  0., -7.5],
            [0.,  0., -7.5],
            [0.,  0., -6.5],
            [0.,  0., -6.5],
            [0.,  0., -6.5],
            [0.,  0., -6.5],
            [0.,  0., -6.5],
            [0.,  0., -5.5],
            [0.,  0., -5.5],
            [0.,  0., -5.5],
            [0.,  0., -5.5],
            [0.,  0., -5.5],
            [0.,  0., -4.5],
            [0.,  0., -4.5],
            [0.,  0., -4.5],
            [0.,  0., -4.5],
            [0.,  0., -4.5],
            [0.,  0., -3.5],
            [0.,  0., -3.5],
            [0.,  0., -3.5],
            [0.,  0., -3.5],
            [0.,  0., -3.5],
            [0.,  0., -2.5],
            [0.,  0., -2.5],
            [0.,  0., -2.5],
            [0.,  0., -2.5],
            [0.,  0., -2.5],
            [0.,  0., -1.5],
            [0.,  0., -1.5],
            [0.,  0., -1.5],
            [0.,  0., -1.5],
            [0.,  0., -1.5],
            [0.,  0., -0.5],
            [0.,  0., -0.5],
            [0.,  0., -0.5]])
        moment_sum_expected = np.array([
            [0.0,  4.42166672e+01,  0.0],
            [0.0,  4.23166695e+01,  0.0],
            [0.0,  4.04166679e+01,  0.0],
            [0.0,  3.85166664e+01,  0.0],
            [0.0,  3.66166687e+01,  0.0],
            [0.0,  3.53166695e+01,  0.0],
            [0.0,  3.36166687e+01,  0.0],
            [0.0,  3.19166679e+01,  0.0],
            [0.0,  3.02166672e+01,  0.0],
            [0.0,  2.85166683e+01,  0.0],
            [0.0,  2.74166679e+01,  0.0],
            [0.0,  2.59166679e+01,  0.0],
            [0.0,  2.44166679e+01,  0.0],
            [0.0,  2.29166679e+01,  0.0],
            [0.0,  2.14166679e+01,  0.0],
            [0.0,  2.05166683e+01,  0.0],
            [0.0,  1.92166672e+01,  0.0],
            [0.0,  1.79166679e+01,  0.0],
            [0.0,  1.66166687e+01,  0.0],
            [0.0,  1.53166676e+01,  0.0],
            [0.0,  1.46166677e+01,  0.0],
            [0.0,  1.35166683e+01,  0.0],
            [0.0,  1.24166679e+01,  0.0],
            [0.0,  1.13166676e+01,  0.0],
            [0.0,  1.02166681e+01,  0.0],
            [0.0,  9.71666813e+00,  0.0],
            [0.0,  8.81666756e+00,  0.0],
            [0.0,  7.91666794e+00,  0.0],
            [0.0,  7.01666784e+00,  0.0],
            [0.0,  6.11666775e+00,  0.0],
            [0.0,  5.81666803e+00,  0.0],
            [0.0,  5.11666775e+00,  0.0],
            [0.0,  4.41666794e+00,  0.0],
            [0.0,  3.71666789e+00,  0.0],
            [0.0,  3.01666784e+00,  0.0],
            [0.0,  2.91666794e+00,  0.0],
            [0.0,  2.41666794e+00,  0.0],
            [0.0,  1.91666794e+00,  0.0],
            [0.0,  1.41666794e+00,  0.0],
            [0.0,  9.16667938e-01,  0.0],
            [0.0,  1.01666796e+00,  0.0],
            [0.0,  7.16667950e-01,  0.0],
            [0.0,  4.16667938e-01,  0.0],
            [0.0,  1.16667941e-01,  0.0],
            [0.0, -1.83332056e-01,  0.0],
            [0.0,  1.16670445e-01,  0.0],
            [0.0,  1.66695174e-02,  0.0],
            [0.0, -8.33295286e-02,  0.0]])
        assert np.allclose(force_sum[3:, :], force_sum_expected), force_out_sum
        assert np.allclose(moment_sum[3:, :], moment_sum_expected), moment_out_sum
        if IS_MATPLOTLIB:  # pragma: no cover
            M2 = moment_sum[:, 1]
            ax.plot(stations, M2, '*-', label='SMT')
            ax.legend()
            fig.show()
            x = 1
예제 #6
0
def _create_bar_types_dict(model: BDF,
                           bar_types: Dict[str, List[List[int], List[Any],
                                                     List[Any]]],
                           bar_beam_eids: List[int],
                           eid_map,
                           log: SimpleLogger,
                           scale: float,
                           debug: bool = False):
    node0 = 0
    found_bar_types = set()
    nid_release_map = defaultdict(list)
    ugrid = vtk.vtkUnstructuredGrid()
    points_list = []

    allowed_types = [
        'BAR',
        'BOX',
        'BOX1',
        'CHAN',
        'CHAN1',
        'CHAN2',
        'CROSS',
        'DBOX',
        'H',
        'HAT',
        'HAT1',
        'HEXA',
        'I',
        'I1',
        'L',
        'ROD',
        'T',
        'T1',
        'T2',
        'TUBE',
        'TUBE2',
        'Z',
        'bar',
        'beam',
        'pbcomp',
    ]

    #debug = True
    bar_nids = set()
    #print('bar_beam_eids = %s' % bar_beam_eids)
    for eid in bar_beam_eids:
        if eid not in eid_map:
            log.error('eid=%s is not a valid bar/beam element...' % eid)
            if debug:  # pragma: no cover
                print('eid=%s is not a valid bar/beam element...' % eid)
            continue
        #unused_ieid = self.eid_map[eid]
        elem = model.elements[eid]
        pid_ref = elem.pid_ref
        if pid_ref is None:
            pid_ref = model.Property(elem.pid)
        assert not isinstance(pid_ref, integer_types), elem

        ptype = pid_ref.type
        bar_type = get_bar_type(ptype, pid_ref)

        if debug:  # pragma: no cover
            print('%s' % elem)
            print('  bar_type = %s' % bar_type)
        found_bar_types.add(bar_type)

        (nid1, nid2) = elem.node_ids
        bar_nids.update([nid1, nid2])
        node1 = model.nodes[nid1]
        node2 = model.nodes[nid2]
        n1 = node1.get_position()
        n2 = node2.get_position()

        # wa/wb are not considered in i_offset
        # they are considered in ihat
        i = n2 - n1
        Li = norm(i)
        ihat = i / Li

        if elem.pa != 0:
            nid_release_map[nid1].append((eid, elem.pa))
        if elem.pb != 0:
            nid_release_map[nid2].append((eid, elem.pb))

        if isinstance(elem.offt, int):
            continue
        unused_v, wa, wb, xform = rotate_v_wa_wb(model, elem, n1, n2, node1,
                                                 node2, ihat, i, eid, Li,
                                                 model.log)
        if wb is None:
            # one or more of v, wa, wb are bad
            continue

        yhat = xform[1, :]
        zhat = xform[2, :]

        ## concept has a GOO

        #if debug:  # pragma: no cover
        #print('  centroid = %s' % centroid)
        #print('  ihat = %s' % ihat)
        #print('  yhat = %s' % yhat)
        #print('  zhat = %s' % zhat)
        #print('  scale = %s' % scale)
        #if eid == 616211:
        #print('  check - eid=%s yhat=%s zhat=%s v=%s i=%s n%s=%s n%s=%s' % (
        #eid, yhat, zhat, v, i, nid1, n1, nid2, n2))

        #print('adding bar %s' % bar_type)
        #print('   centroid=%s' % centroid)
        #print('   yhat=%s len=%s' % (yhat, np.linalg.norm(yhat)))
        #print('   zhat=%s len=%s' % (zhat, np.linalg.norm(zhat)))
        #print('   Li=%s scale=%s' % (Li, scale))
        if bar_type not in allowed_types:
            allowed_types_str = ', '.join(allowed_types)
            msg = f'bar_type={bar_type!r} allowed=[{allowed_types_str}]'
            raise RuntimeError(msg)

        if bar_type in BEAM_GEOM_TYPES:
            node0 = add_3d_bar_element(bar_type, ptype, pid_ref, n1 + wa,
                                       n2 + wb, xform, ugrid, node0,
                                       points_list)

        centroid = (n1 + n2) / 2.
        bar_types[bar_type][0].append(eid)
        bar_types[bar_type][1].append((centroid, centroid + yhat * Li * scale))
        bar_types[bar_type][2].append((centroid, centroid + zhat * Li * scale))
    return node0, ugrid, points_list, bar_nids, nid_release_map
예제 #7
0
    def test_gpforce_02(self):
        IS_MATPLOTLIB = False
        log = SimpleLogger(level='warning')
        (model, coord_out, nid_cp_cd, icd_transform,
         all_nids, xyz_cid0,
         all_eids, element_centroids_cid0,
         gpforce, x1, x2, bending_moment2,
         stations) = _setup_bar_grid_point_forces(log)

        with self.assertRaises(AssertionError):
            log.error('problem with extract_freebody_loads...')
            fb_force, fb_moment = gpforce.extract_freebody_loads(
                all_eids,
                coord_out, model.coords,
                nid_cp_cd,
                icd_transform,
                itime=0, debug=True,
                log=log)

        if IS_MATPLOTLIB:  # pragma: no cover
            fig = plt.figure()
            ax = fig.gca()
            L = 10.0
            x = xyz_cid0[:, 0].copy()
            x.sort()
            M = x ** 2 / 2
            # F = wx
            # M = wx^2/2
            ax.plot(x1, bending_moment2[::2], 'o-', label='BM2', linewidth=3)
            ax.plot(x2, bending_moment2[1::2], 'o--', )
            ax.plot(L-x, M, 'o-', label='exact', linewidth=1)
            ax.grid(True)

        # trivial case
        #nids = [1]
        #eids = [1]
        force_out_sum, moment_out_sum = gpforce.extract_interface_loads(
            all_nids, all_eids,
            coord_out, model.coords,
            nid_cp_cd, icd_transform,
            xyz_cid0,
            #summation_point: Optional[NDArray3float]=None,
            consider_rxf=True, itime=0,
            stop_on_nan=True,
            debug=True, log=log)
        assert np.allclose(force_out_sum, [0., 0., 0.]), force_out_sum
        assert np.allclose(moment_out_sum, [0., 0., 0.]), moment_out_sum

        # some problematic case...
        eids = [1]
        nids = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
        force_out_sum, moment_out_sum = gpforce.extract_interface_loads(
            nids, eids,
            coord_out, model.coords,
            nid_cp_cd, icd_transform,
            xyz_cid0,
            #summation_point: Optional[NDArray3float]=None,
            consider_rxf=True, itime=0,
            stop_on_nan=True,
            debug=True, log=log)
        assert np.allclose(force_out_sum, [0., 0., 9.5]), force_out_sum
        assert np.allclose(moment_out_sum, [0., -49.916668, 0.]), moment_out_sum

        # this one is empty...
        nids = [1]
        eids = [2]
        force_out_sum, moment_out_sum = gpforce.extract_interface_loads(
            nids, eids,
            coord_out, model.coords,
            nid_cp_cd, icd_transform,
            xyz_cid0,
            #summation_point: Optional[NDArray3float]=None,
            consider_rxf=False, itime=0,
            stop_on_nan=False,
            debug=False, log=log)

        # array([nan, nan, nan], dtype=float32)
        assert not np.any(np.isfinite(force_out_sum)), force_out_sum
        assert not np.any(np.isfinite(moment_out_sum)), moment_out_sum
        #coord0 = model.coords[0]
        #gpforce.extract_interface_loads(nids: np.ndarray,
                                        #eids: np.ndarray,
                                        #coord_out=coord0,
                                        #model.coords,
                                        #nid_cd,
                                        #icd_transform,
                                        #xyz_cid0,
                                        #summation_point=None,
                                        #consider_rxf=True,
                                        #itime=0,
                                        #debug=True,
                                        #log=model.log,
                                        #idtype='int32')
        # ----------------------------------------
        nodes_list = list(model.nodes.keys())
        nids = np.array(nodes_list, dtype='int32')
        nids.sort()
        #eids = np.ndarray(list(model.elements.keys()), dtype='int32')
        #eids.sort()
        # bar is [0,10] in x
        istations = np.where(stations > 0.5)[0]
        stations = stations[istations]
        force_sum, moment_sum, new_coords, nelems, nnodes = gpforce.shear_moment_diagram(
            nids, xyz_cid0, nid_cp_cd, icd_transform,
            all_eids, element_centroids_cid0,
            stations, model.coords, coord_out,
            #idir=0,
            itime=0, debug=True,
            nodes_tol=0.5,
            stop_on_nan=True, log=model.log)
        force_sum_expected = np.array([
            [0., 0., 9.5],
            [0., 0., 9.5],
            [0., 0., 9.5],
            [0., 0., 9.5],
            [0., 0., 9.5],
            [0., 0., 8.5],
            [0., 0., 8.5],
            [0., 0., 8.5],
            [0., 0., 8.5],
            [0., 0., 8.5],
            [0., 0., 7.5],
            [0., 0., 7.5],
            [0., 0., 7.5],
            [0., 0., 7.5],
            [0., 0., 7.5],
            [0., 0., 6.5],
            [0., 0., 6.5],
            [0., 0., 6.5],
            [0., 0., 6.5],
            [0., 0., 6.5],
            [0., 0., 5.5],
            [0., 0., 5.5],
            [0., 0., 5.5],
            [0., 0., 5.5],
            [0., 0., 5.5],
            [0., 0., 4.5],
            [0., 0., 4.5],
            [0., 0., 4.5],
            [0., 0., 4.5],
            [0., 0., 4.5],
            [0., 0., 3.5],
            [0., 0., 3.5],
            [0., 0., 3.5],
            [0., 0., 3.5],
            [0., 0., 3.5],
            [0., 0., 2.5],
            [0., 0., 2.5],
            [0., 0., 2.5],
            [0., 0., 2.5],
            [0., 0., 2.5],
            [0., 0., 1.5],
            [0., 0., 1.5],
            [0., 0., 1.5],
            [0., 0., 1.5],
            [0., 0., 1.5],
            [0., 0., 0.5],
            [0., 0., 0.5],
            [0., 0., 0.5],
        ])
        moment_sum_expected = np.array([
            [0., -4.42166672e+01, 0.],
            [0., -4.23166695e+01, 0.],
            [0., -4.04166679e+01, 0.],
            [0., -3.85166664e+01, 0.],
            [0., -3.66166687e+01, 0.],
            [0., -3.53166656e+01, 0.],
            [0., -3.36166649e+01, 0.],
            [0., -3.19166660e+01, 0.],
            [0., -3.02166653e+01, 0.],
            [0., -2.85166664e+01, 0.],
            [0., -2.74166660e+01, 0.],
            [0., -2.59166660e+01, 0.],
            [0., -2.44166660e+01, 0.],
            [0., -2.29166660e+01, 0.],
            [0., -2.14166660e+01, 0.],
            [0., -2.05166664e+01, 0.],
            [0., -1.92166653e+01, 0.],
            [0., -1.79166660e+01, 0.],
            [0., -1.66166668e+01, 0.],
            [0., -1.53166656e+01, 0.],
            [0., -1.46166668e+01, 0.],
            [0., -1.35166674e+01, 0.],
            [0., -1.24166670e+01, 0.],
            [0., -1.13166666e+01, 0.],
            [0., -1.02166672e+01, 0.],
            [0., -9.71666622e+00, 0.],
            [0., -8.81666660e+00, 0.],
            [0., -7.91666651e+00, 0.],
            [0., -7.01666641e+00, 0.],
            [0., -6.11666632e+00, 0.],
            [0., -5.81666660e+00, 0.],
            [0., -5.11666632e+00, 0.],
            [0., -4.41666651e+00, 0.],
            [0., -3.71666646e+00, 0.],
            [0., -3.01666641e+00, 0.],
            [0., -2.91666651e+00, 0.],
            [0., -2.41666651e+00, 0.],
            [0., -1.91666663e+00, 0.],
            [0., -1.41666663e+00, 0.],
            [0., -9.16666627e-01, 0.],
            [0., -1.01666665e+00, 0.],
            [0., -7.16666639e-01, 0.],
            [0., -4.16666657e-01, 0.],
            [0., -1.16666660e-01, 0.],
            [0.,  1.83333337e-01, 0.],
            [0., -1.16666667e-01, 0.],
            [0., -1.66666638e-02, 0.],
            [0.,  8.33333358e-02, 0.]])
        assert force_sum.shape == force_sum_expected.shape, force_out_sum
        assert moment_sum.shape == moment_sum_expected.shape, moment_sum.shape
        assert np.allclose(force_sum, force_sum_expected), force_out_sum
        assert np.allclose(moment_sum, moment_sum_expected), moment_sum
        if IS_MATPLOTLIB:  # pragma: no cover
            M2 = moment_sum[:, 1]
            ax.plot(stations, -M2, '*-', label='SMT')
            ax.legend()
            fig.show()
            x = 1
예제 #8
0
def _cast_matrix_matpool(table_name: str,
                         real_imag_array,
                         col_nids_array,
                         col_dofs_array,
                         row_nids_array,
                         row_dofs_array,
                         matrix_shape: Tuple[int, int],
                         dtype: str,
                         is_symmetric: bool,
                         log: SimpleLogger,
                         apply_symmetry: bool = False) -> Matrix:
    """helper method for _read_matpool_matrix"""
    #op2 = self.op2
    make_matrix_symmetric = apply_symmetry and matrix_shape == 'symmetric'

    # TODO: this is way slower than it should be
    #       because we didn't preallocate the data and the
    #       grids_comp_array_to_index function needs work
    grids1 = col_nids_array
    comps1 = col_dofs_array
    grids2 = row_nids_array
    comps2 = row_dofs_array
    assert len(grids1) == len(comps1), 'ngrids1=%s ncomps1=%s' % (len(grids1),
                                                                  len(comps1))
    assert len(grids1) == len(grids2), 'ngrids1=%s ngrids2=%s' % (len(grids1),
                                                                  len(grids2))
    assert len(comps1) == len(comps2), 'ncomps1=%s ncomps2=%s' % (len(comps1),
                                                                  len(comps2))

    j1, j2, nj1, nj2, nj = grids_comp_array_to_index(grids1,
                                                     comps1,
                                                     grids2,
                                                     comps2,
                                                     make_matrix_symmetric,
                                                     idtype='int32')
    assert len(j1) == len(j2), 'nj1=%s nj2=%s' % (len(j1), len(j2))
    assert len(grids1) == len(real_imag_array), 'ngrids1=%s nreals=%s' % (
        len(j1), len(real_imag_array))

    # not 100% on these, they might be flipped
    #ncols = len(np.unique(j1))
    #mrows = len(np.unique(j2))

    if is_symmetric and make_matrix_symmetric:
        mrows = nj
        ncols = nj
        #print('  j1 =', j1)
        #print('  j2 =', j2)
    else:
        ncols = nj1
        mrows = nj2

    # C:\MSC.Software\simcenter_nastran_2019.2\tpl_post2\tr1071x.op2
    #print(real_imag_array)
    #print(j1)
    #print(j2)
    #print(mrows, ncols)
    try:
        matrix = scipy.sparse.coo_matrix((real_imag_array, (j2, j1)),
                                         shape=(mrows, ncols),
                                         dtype=dtype)
    except ValueError:
        print('gc1', grids1, comps1)
        print('gc2', grids2, comps2)
        print(f'j1={j1}')
        print(f'j2={j2}')
        print(f'shape=({mrows}, {ncols})')
        msg = 'Passed all the checks; cannot build MATPOOL sparse matrix...\n'
        spaces = '                                          '
        msg += '%sname=%s dtype=%s nrows=%s ncols=%s nj1=%s nj2=%s nj=%s' % (
            spaces, table_name, dtype, mrows, ncols, nj1, nj2, nj)
        log.error(msg)
        raise

    # enforce symmetry if necessary
    if make_matrix_symmetric:
        # get the upper and lower triangular matrices
        upper_tri = scipy.sparse.triu(matrix)
        lower_tri = scipy.sparse.tril(matrix)

        # extracts a [1, 2, 3, ..., n] off the diagonal of the matrix
        # and make it a diagonal matrix
        diagi = scipy.sparse.diags(scipy.sparse.diagional(upper_tri))

        # Check to see which triangle is populated.
        # If they both are, make sure they're equal
        # or average them and throw a warning
        lnnz = (lower_tri - diagi).nnz
        unnz = (upper_tri - diagi).nnz
        assert isinstance(lnnz, int), type(lnnz)
        assert isinstance(unnz, int), type(unnz)

        # both upper and lower triangle are populated
        if lnnz > 0 and unnz > 0:
            upper_tri_t = upper_tri.T
            if lower_tri == upper_tri_t:
                matrix = upper_tri + upper_tri_t - diagi
            else:
                log.warning(
                    f'Matrix {table_name!r} marked as symmetric does not contain '
                    'symmetric data.  Data will be symmetrized by averaging.')
                matrix = (matrix + matrix.T) / 2.
        elif lnnz > 0:
            #  lower triangle is populated
            matrix = lower_tri + lower_tri.T - diagi
        elif unnz > 0:
            #  upper triangle is populated
            matrix = upper_tri + upper_tri_t - diagi
        else:
            # matrix is diagonal (or null)
            matrix = diagi
        data = matrix

        # matrix is symmetric, but is not stored as symmetric
        matrix_shape = 'rectangular'

    m = Matrix(table_name, is_matpool=True, form=matrix_shape)
    m.data = matrix
    m.col_nid = col_nids_array
    m.col_dof = col_dofs_array
    m.row_nid = row_nids_array
    m.row_dof = row_dofs_array
    m.form = matrix_shape
    #print(m)
    log.debug(m)
    return m