def read(group): """Reads from a zarr-ply group and returns a Mesh object """ point_props = [ p[-1] for p in group.attrs["elements"]["vertex"]["properties"] ] coords = [c for c in "xyz" if c in point_props] points = np.vstack([group.points[c] for c in coords]).T point_data = {} for key in point_props: if key in coords: continue point_data[key] = np.array(group.points[key]) cells = [] cell_data = defaultdict(list) cell_props = group.attrs["elements"]["face"]["properties"] for key in group.keys(): if not key.isnumeric(): continue nsides = int(key) cell_type = cell_type_from_count(nsides) cells.append((cell_type, np.array(group[key]["vertex_indices"]))) for *_, prop in cell_props: if prop == "vertex_indices": continue cell_data[prop].append(np.array(group[key][prop]), ) return Mesh(points=points, cells=cells, point_data=point_data, cell_data=cell_data)
def get_meshio(self, idx: int) -> Optional[Mesh]: if Mesh is None: # pragma: no cover raise RuntimeError( "The get_meshio function can only be used if you have installed meshio. " "Try pip install meshio") array = self.arrays[idx] mesh = self.meshes[idx] if len(mesh) == 0: return None return Mesh( np.stack((array["X"], array["Y"], array["Z"]), 1), [("triangle", np.stack((mesh["A"], mesh["B"], mesh["C"]), 1))], )
def Write(self): #Update filepath self.GetFilePath() #DFN geo file if (self.DFN_Writer is not None): self.DFN_Writer.Write() print("[Output] Saved Geometry VTK file %s) !" % (self.fname_geo)) #return self.fname_geo #Mesh file if (self.DFN_MeshData is not None): meshio_cells = {'triangle': self.DFN_MeshData.Elements} meshio_points = self.DFN_MeshData.Points mesh = Mesh(meshio_points, meshio_cells, point_data=self.meshio_ptsdata, cell_data=self.meshio_celldata) meshio.vtu.write(self.fname_mesh, mesh) print("[Output] Saved VTK mesh and solution file %s) !" % (self.fname_mesh))
K12 = asm(b12, basis["p"], basis["u"], disp=uv, press=pv) K22 = asm(b22, basis["p"], basis["p"], disp=uv, press=pv) f = concatenate(( asm(a1, basis["u"], disp=uv, press=pv), asm(a2, basis["p"], disp=uv, press=pv) )) K = bmat( [[K11, K12], [K12.T, K22]], "csr" ) uvp = solve(*condense(K, -f, I=I), use_umfpack=True) delu, delp = npsplit(uvp, [du.shape[0]]) du += delu dp += delp normu = nla.norm(delu) normp = nla.norm(delp) print(f"{itr+1}, norm_du: {normu}, norm_dp: {normp}") if normu < 1.e-8 and normp < 1.e-8: break if __name__ == "__main": from meshio import xdmf, Mesh xdmf.write("example36_results.xdmf", Mesh(mesh.p, cells={"tetra": mesh.t.T}, point_data={ "u": du[basis["u"].nodal_dofs].T, "p": dp[basis["p"].nodal_dofs].T }) )
def read(filetype, filename): import vtk from vtk.util import numpy_support def _read_data(data): """Extract numpy arrays from a VTK data set. """ # Go through all arrays, fetch data. out = {} for k in range(data.GetNumberOfArrays()): array = data.GetArray(k) if array: array_name = array.GetName() out[array_name] = numpy.copy( vtk.util.numpy_support.vtk_to_numpy(array)) return out def _read_cells(vtk_mesh): data = numpy.copy( vtk.util.numpy_support.vtk_to_numpy(vtk_mesh.GetCells().GetData())) offsets = numpy.copy( vtk.util.numpy_support.vtk_to_numpy( vtk_mesh.GetCellLocationsArray())) types = numpy.copy( vtk.util.numpy_support.vtk_to_numpy(vtk_mesh.GetCellTypesArray())) # `data` is a one-dimensional vector with # (num_points0, p0, p1, ... ,pk, numpoints1, p10, p11, ..., p1k, ... # Translate it into the cells dictionary. cells = {} for vtk_type, meshio_type in vtk_to_meshio_type.items(): # Get all offsets for vtk_type os = offsets[numpy.argwhere(types == vtk_type).transpose()[0]] num_cells = len(os) if num_cells > 0: if meshio_type == "polygon": for idx_cell in range(num_cells): num_pts = data[os[idx_cell]] cell = data[os[idx_cell] + 1:os[idx_cell] + 1 + num_pts] key = meshio_type + str(num_pts) if key in cells: cells[key] = numpy.vstack([cells[key], cell]) else: cells[key] = cell else: num_pts = data[os[0]] # instantiate the array arr = numpy.empty((num_cells, num_pts), dtype=int) # store the num_pts entries after the offsets into the columns # of arr for k in range(num_pts): arr[:, k] = data[os + k + 1] cells[meshio_type] = arr return cells if filetype in ["vtk", "vtk-ascii", "vtk-binary"]: reader = vtk.vtkUnstructuredGridReader() reader.SetFileName(filename) reader.SetReadAllNormals(1) reader.SetReadAllScalars(1) reader.SetReadAllTensors(1) reader.SetReadAllVectors(1) reader.Update() vtk_mesh = reader.GetOutput() elif filetype in ["vtu", "vtu-ascii", "vtu-binary"]: reader = vtk.vtkXMLUnstructuredGridReader() reader.SetFileName(filename) reader.Update() vtk_mesh = reader.GetOutput() elif filetype in ["xdmf", "xdmf2"]: reader = vtk.vtkXdmfReader() reader.SetFileName(filename) reader.SetReadAllColorScalars(1) reader.SetReadAllFields(1) reader.SetReadAllNormals(1) reader.SetReadAllScalars(1) reader.SetReadAllTCoords(1) reader.SetReadAllTensors(1) reader.SetReadAllVectors(1) reader.Update() vtk_mesh = reader.GetOutputDataObject(0) elif filetype == "xdmf3": reader = vtk.vtkXdmf3Reader() reader.SetFileName(filename) reader.SetReadAllColorScalars(1) reader.SetReadAllFields(1) reader.SetReadAllNormals(1) reader.SetReadAllScalars(1) reader.SetReadAllTCoords(1) reader.SetReadAllTensors(1) reader.SetReadAllVectors(1) reader.Update() vtk_mesh = reader.GetOutputDataObject(0) else: assert filetype == "exodus", "Unknown file type '{}'.".format(filename) reader = vtk.vtkExodusIIReader() reader.SetFileName(filename) vtk_mesh = _read_exodusii_mesh(reader) # Explicitly extract points, cells, point data, field data points = numpy.copy( numpy_support.vtk_to_numpy(vtk_mesh.GetPoints().GetData())) cells = _read_cells(vtk_mesh) point_data = _read_data(vtk_mesh.GetPointData()) field_data = _read_data(vtk_mesh.GetFieldData()) cell_data = _read_data(vtk_mesh.GetCellData()) # split cell_data by the cell type cd = {} index = 0 for cell_type in cells: num_cells = len(cells[cell_type]) cd[cell_type] = {} for name, array in cell_data.items(): cd[cell_type][name] = array[index:index + num_cells] index += num_cells cell_data = cd return Mesh(points, cells, point_data=point_data, cell_data=cell_data, field_data=field_data)
def read_xdmf3(self, root): domains = list(root) if len(domains) != 1: raise ReadError() domain = domains[0] if domain.tag != "Domain": raise ReadError() grids = list(domain) if len(grids) != 1: raise ReadError("XDMF reader: Only supports one grid right now.") grid = grids[0] if grid.tag != "Grid": raise ReadError() points = None cells = [] point_data = {} cell_data_raw = {} field_data = {} for c in grid: if c.tag == "Topology": data_items = list(c) if len(data_items) != 1: raise ReadError() data_item = data_items[0] data = self._read_data_item(data_item) # The XDMF2 key is `TopologyType`, just `Type` for XDMF3. # Allow both. if c.get("Type"): if c.get("TopologyType"): raise ReadError() cell_type = c.get("Type") else: cell_type = c.get("TopologyType") if cell_type == "Mixed": cells = translate_mixed_cells(data) else: cells.append( CellBlock(xdmf_to_meshio_type[cell_type], data)) elif c.tag == "Geometry": if c.get("Type"): if c.get("GeometryType"): raise ReadError() geometry_type = c.get("Type") else: geometry_type = c.get("GeometryType") if geometry_type not in ["XY", "XYZ"]: raise ReadError( f'Illegal geometry type "{geometry_type}".') data_items = list(c) if len(data_items) != 1: raise ReadError() data_item = data_items[0] points = self._read_data_item(data_item) elif c.tag == "Information": c_data = c.text if not c_data: raise ReadError() field_data = self.read_information(c_data) elif c.tag == "Attribute": # Don't be too strict here: FEniCS, for example, calls this # 'AttributeType'. # assert c.attrib['Type'] == 'None' data_items = list(c) if len(data_items) != 1: raise ReadError() data_item = data_items[0] data = self._read_data_item(data_item) name = c.get("Name") if c.get("Center") == "Node": point_data[name] = data else: if c.get("Center") != "Cell": raise ReadError() cell_data_raw[name] = data else: raise ReadError(f"Unknown section '{c.tag}'.") cell_data = cell_data_from_raw(cells, cell_data_raw) from meshio import Mesh return Mesh( points, cells, point_data=point_data, cell_data=cell_data, field_data=field_data, )