Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def write(filename, mesh):
import netCDF4
with netCDF4.Dataset(filename, "w") as rootgrp:
# set global data
rootgrp.title = "Created by meshio v{}, {}".format(
__version__, datetime.datetime.now().isoformat()
)
rootgrp.version = numpy.float32(5.1)
rootgrp.api_version = numpy.float32(5.1)
rootgrp.floating_point_word_size = 8
# set dimensions
total_num_elems = sum([c.data.shape[0] for c in mesh.cells])
rootgrp.createDimension("num_nodes", len(mesh.points))
rootgrp.createDimension("num_dim", mesh.points.shape[1])
rootgrp.createDimension("num_elem", total_num_elems)
rootgrp.createDimension("num_el_blk", len(mesh.cells))
rootgrp.createDimension("num_node_sets", len(mesh.point_sets))
rootgrp.createDimension("len_string", 33)
rootgrp.createDimension("len_line", 81)
rootgrp.createDimension("four", 4)
rootgrp.createDimension("time_step", None)
def write(filename, mesh, float_fmt=".16e", binary=False):
"""Write FLAC3D f3grid grid file."""
if not any(c.type in meshio_only.keys() for c in mesh.cells):
raise WriteError("FLAC3D format only supports 3D cells")
mode = "wb" if binary else "w"
with open_file(filename, mode) as f:
if binary:
f.write(
struct.pack("<2I", 1375135718, 3)
) # Don't know what these values represent
else:
f.write("* FLAC3D grid produced by meshio v{}\n".format(version))
f.write("* {}\n".format(time.ctime()))
_write_points(f, mesh.points, binary, float_fmt)
_write_cells(f, mesh.points, mesh.cells, binary)
_write_zgroups(f, mesh.cell_data, mesh.field_data, binary)
if binary:
f.write(struct.pack("<2I", 0, 0)) # No face and face group
def _get_version_text():
return "\n".join(
[
"meshio {} [Python {}.{}.{}]".format(
__version__,
sys.version_info.major,
sys.version_info.minor,
sys.version_info.micro,
),
"Copyright (c) 2015-2020 Nico Schlömer et al.",
]
v = numpy.concatenate([v[ic] for ic in cell_blocks])
if v.ndim == 1:
variables += [k]
data += [v]
varrange[1] += 1
elif v.ndim == 2:
for i, vv in enumerate(v.T):
variables += [f"{k}_{i}"]
data += [vv]
varrange[1] += 1
else:
logging.warning(f"Skipping cell data '{k}'.")
with open_file(filename, "w") as f:
# Title
f.write(f'TITLE = "Written by meshio v{version}"\n')
# Variables
variables_str = ", ".join(f'"{var}"' for var in variables)
f.write(f"VARIABLES = {variables_str}\n")
# Zone record
num_nodes = len(mesh.points)
num_cells = sum(len(mesh.cells[ic].data) for ic in cell_blocks)
f.write(f"ZONE NODES = {num_nodes}, ELEMENTS = {num_cells},\n")
f.write(f"DATAPACKING = BLOCK, ZONETYPE = {zone_type}")
if varrange[0] < varrange[1]:
f.write(",\n")
varlocation_str = (
f"{varrange[0]}"
if varrange[0] == varrange[1]
else f"{varrange[0]}-{varrange[1]}"
for name, data in mesh.cell_data.items():
for k, values in enumerate(data):
if len(values.shape) == 2 and values.shape[1] == 2:
logging.warning(
"VTK requires 3D vectors, but 2D vectors given. "
"Appending 0 third component to {}.".format(name)
)
data[k] = pad(data[k])
if not binary:
logging.warning("VTK ASCII files are only meant for debugging.")
with open_file(filename, "wb") as f:
f.write(b"# vtk DataFile Version 4.2\n")
f.write("written by meshio v{}\n".format(__version__).encode("utf-8"))
f.write(("BINARY\n" if binary else "ASCII\n").encode("utf-8"))
f.write(b"DATASET UNSTRUCTURED_GRID\n")
# write points and cells
_write_points(f, points, binary)
_write_cells(f, mesh.cells, binary)
# write point data
if mesh.point_data:
num_points = mesh.points.shape[0]
f.write("POINT_DATA {}\n".format(num_points).encode("utf-8"))
_write_field_data(f, mesh.point_data, binary)
# write cell data
if mesh.cell_data:
total_num_cells = sum(len(c.data) for c in mesh.cells)
fh.write(fmt.format(k, pt[0], pt[1], pt[2]))
if not any(c.type == "tetra" for c in mesh.cells):
raise WriteError("TegGen only supports tetrahedra")
if any(c.type != "tetra" for c in mesh.cells):
logging.warning(
"TetGen only supports tetrahedra, but mesh has {}. Skipping those.".format(
", ".join([c.type for c in mesh.cells if c.type != "tetra"])
)
)
# write cells
# TODO remove .as_posix when requiring Python 3.6
with open(ele_filename.as_posix(), "w") as fh:
fh.write("# This file was created by meshio v{}\n".format(__version__))
for cell_type, data in filter(lambda c: c.type == "tetra", mesh.cells):
fh.write("{} {} {}\n".format(data.shape[0], 4, 0))
for k, tet in enumerate(data):
fh.write("{} {} {} {} {}\n".format(k, tet[0], tet[1], tet[2], tet[3]))
def write(filename, mesh):
for c in mesh.cells:
if c.type not in ["triangle", "quad"]:
raise WriteError(
"Wavefront .obj files can only contain triangle or quad cells."
)
with open_file(filename, "w") as f:
f.write(
"# Created by meshio v{}, {}\n".format(
__version__, datetime.datetime.now().isoformat()
)
)
for p in mesh.points:
f.write("v {} {} {}\n".format(p[0], p[1], p[2]))
for cell_type, cell_array in mesh.cells:
fmt = "f {} {} {}"
if cell_type == "quad":
fmt += " {}"
for c in cell_array:
f.write(f"{fmt}\n".format(*(c + 1)))
def write(filename, mesh):
if mesh.points.shape[1] == 2:
logging.warning(
"Nastran requires 3D points, but 2D points given. "
"Appending 0 third component."
)
points = numpy.column_stack([mesh.points, numpy.zeros(mesh.points.shape[0])])
else:
points = mesh.points
with open_file(filename, "w") as f:
f.write("$ Nastran file written by meshio v{}\n".format(__version__))
f.write("BEGIN BULK\n")
# Points
point_refs = mesh.point_data.get("nastran:ref", None)
if point_refs is not None:
for point_id, x in enumerate(points):
f.write(
"GRID, {:d}, {:d}, {:.16e}, {:.16e}, {:.16e}\n".format(
point_id + 1, point_refs[point_id], x[0], x[1], x[2]
)
)
else:
for point_id, x in enumerate(points):
f.write(
"GRID, {:d},, {:.16e}, {:.16e}, {:.16e}\n".format(
point_id + 1, x[0], x[1], x[2]
def write(filename, mesh, float_fmt=".16e", translate_cell_names=True):
with open_file(filename, "wt") as f:
f.write("*HEADING\n")
f.write("Abaqus DataFile Version 6.14\n")
f.write("written by meshio v{}\n".format(__version__))
f.write("*NODE\n")
fmt = ", ".join(["{}"] + ["{:" + float_fmt + "}"] * mesh.points.shape[1]) + "\n"
for k, x in enumerate(mesh.points):
f.write(fmt.format(k + 1, *x))
eid = 0
for cell_type, node_idcs in mesh.cells:
name = (
meshio_to_abaqus_type[cell_type] if translate_cell_names else cell_type
)
f.write("*ELEMENT, TYPE={}\n".format(name))
for row in node_idcs:
eid += 1
nids_strs = (str(nid + 1) for nid in row.tolist())
f.write(str(eid) + "," + ",".join(nids_strs) + "\n")
nnl = 8
def write(filename, mesh, binary=True):
with open_file(filename, "wb") as fh:
# header
fh.write('(1 "meshio {}")\n'.format(__version__).encode("utf8"))
# dimension
dim = mesh.points.shape[1]
if dim not in [2, 3]:
raise WriteError("Can only write dimension 2, 3, got {}.".format(dim))
fh.write(("(2 {})\n".format(dim)).encode("utf8"))
# total number of nodes
first_node_index = 1
fh.write(
(
"(10 (0 {:x} {:x} 0))\n".format(first_node_index, len(mesh.points))
).encode("utf8")
)
# total number of cells