Skip to content

Commit

Permalink
Merge pull request #1241 from nschloe/rich
Browse files Browse the repository at this point in the history
unify warnings, use rich
  • Loading branch information
nschloe authored Dec 18, 2021
2 parents b019c68 + 5648150 commit b75f0aa
Show file tree
Hide file tree
Showing 38 changed files with 136 additions and 157 deletions.
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ jobs:
uses: pre-commit/[email protected]

build:
needs: [lint]
runs-on: ${{ matrix.os }}
strategy:
matrix:
Expand Down
3 changes: 2 additions & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[metadata]
name = meshio
version = 5.1.2
version = 5.2.0
author = Nico Schlömer et al.
author_email = [email protected]
description = I/O for many mesh formats
Expand Down Expand Up @@ -40,6 +40,7 @@ packages = find:
install_requires =
importlib_metadata;python_version<"3.8"
numpy
rich
python_requires = >=3.7

[options.packages.find]
Expand Down
3 changes: 2 additions & 1 deletion src/meshio/_cli/_ascii.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import pathlib

from .. import ansys, flac3d, gmsh, mdpa, ply, stl, vtk, vtu, xdmf
from .._common import error
from .._helpers import _filetype_from_path, read, reader_map


Expand Down Expand Up @@ -49,7 +50,7 @@ def ascii(args):
elif fmt == "xdmf":
xdmf.write(args.infile, mesh, data_format="XML")
else:
print(f"Don't know how to convert {args.infile} to ASCII format.")
error(f"Don't know how to convert {args.infile} to ASCII format.")
return 1

size = os.stat(args.infile).st_size
Expand Down
3 changes: 2 additions & 1 deletion src/meshio/_cli/_compress.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import pathlib

from .. import ansys, cgns, gmsh, h5m, mdpa, ply, stl, vtk, vtu, xdmf
from .._common import error
from .._helpers import _filetype_from_path, read, reader_map


Expand Down Expand Up @@ -69,7 +70,7 @@ def compress(args):
compression_opts=9 if args.max else 4,
)
else:
print(f"Don't know how to compress {args.infile}.")
error(f"Don't know how to compress {args.infile}.")
exit(1)

size = os.stat(args.infile).st_size
Expand Down
3 changes: 2 additions & 1 deletion src/meshio/_cli/_decompress.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import pathlib

from .. import cgns, h5m, vtu, xdmf
from .._common import error
from .._helpers import _filetype_from_path, read, reader_map


Expand Down Expand Up @@ -38,7 +39,7 @@ def decompress(args):
elif fmt == "xdmf":
xdmf.write(args.infile, mesh, data_format="HDF", compression=None)
else:
print(f"Don't know how to decompress {args.infile}.")
error(f"Don't know how to decompress {args.infile}.")
exit(1)

size = os.stat(args.infile).st_size
Expand Down
5 changes: 3 additions & 2 deletions src/meshio/_cli/_info.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import numpy as np

from .._common import warn
from .._helpers import read, reader_map


Expand All @@ -24,7 +25,7 @@ def info(args):
is_consistent = True
for cells in mesh.cells:
if np.any(cells.data > mesh.points.shape[0]):
print("\nATTENTION: Inconsistent mesh. Cells refer to nonexistent points.")
warn("Inconsistent mesh. Cells refer to nonexistent points.")
is_consistent = False
break

Expand All @@ -34,6 +35,6 @@ def info(args):
for cells in mesh.cells:
point_is_used[cells.data] = True
if np.any(~point_is_used):
print("ATTENTION: Some points are not part of any cell.")
warn("Some points are not part of any cell.")

return 0
11 changes: 11 additions & 0 deletions src/meshio/_common.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from xml.etree import ElementTree as ET

import numpy as np
from rich.console import Console

# See <https://github.com/nschloe/meshio/wiki/Node-ordering-in-cells> for the node
# ordering.
Expand Down Expand Up @@ -117,3 +118,13 @@ def _pick_first_int_data(data):
other = []

return key, other


def warn(string, highlight: bool = True) -> None:
Console(stderr=True).print(
f"[yellow]Warning: {string}[/yellow]", highlight=highlight
)


def error(string, highlight: bool = True) -> None:
Console(stderr=True).print(f"[red]Error: {string}[/red]", highlight=highlight)
15 changes: 5 additions & 10 deletions src/meshio/_mesh.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
from __future__ import annotations

import copy
import warnings

import numpy as np
from numpy.typing import ArrayLike

from ._common import num_nodes_per_cell
from ._common import num_nodes_per_cell, warn

topological_dimension = {
"line": 1,
Expand Down Expand Up @@ -130,8 +129,7 @@ def __init__(
self.points = np.asarray(points)
if isinstance(cells, dict):
# Let's not deprecate this for now.
# import warnings
# warnings.warn(
# warn(
# "cell dictionaries are deprecated, use list of tuples, e.g., "
# '[("triangle", [[0, 1, 2], ...])]',
# DeprecationWarning,
Expand Down Expand Up @@ -311,10 +309,7 @@ def read(cls, path_or_buf, file_format=None):
from ._helpers import read

# 2021-02-21
warnings.warn(
"meshio.Mesh.read is deprecated, use meshio.read instead",
DeprecationWarning,
)
warn("meshio.Mesh.read is deprecated, use meshio.read instead")
return read(path_or_buf, file_format)

def sets_to_int_data(self):
Expand All @@ -335,7 +330,7 @@ def sets_to_int_data(self):
for item in intfun:
num_default = np.sum(item == default_value)
if num_default > 0:
warnings.warn(
warn(
f"{num_default} cells are not part of any cell set. "
f"Using default value {default_value}."
)
Expand All @@ -353,7 +348,7 @@ def sets_to_int_data(self):
intfun[cc] = i

if np.any(intfun == default_value):
warnings.warn(
warn(
"Not all points are part of a point set. "
f"Using default value {default_value}."
)
Expand Down
6 changes: 2 additions & 4 deletions src/meshio/_vtk_common.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import warnings

import numpy as np

from ._common import num_nodes_per_cell
from ._common import num_nodes_per_cell, warn
from ._exceptions import ReadError
from ._mesh import CellBlock

Expand Down Expand Up @@ -113,7 +111,7 @@ def vtk_cells_from_data(connectivity, offsets, types, cell_data_raw):
try:
meshio_type = vtk_to_meshio_type[types[start]]
except KeyError:
warnings.warn(
warn(
f"File contains cells that meshio cannot handle (type {types[start]})."
)
continue
Expand Down
10 changes: 5 additions & 5 deletions src/meshio/ansys/_ansys.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@
<https://romeo.univ-reims.fr/documents/fluent/tgrid/ug/appb.pdf>
"""
import logging
import re

import numpy as np

from ..__about__ import __version__
from .._common import warn
from .._exceptions import ReadError, WriteError
from .._files import open_file
from .._helpers import register_format
Expand Down Expand Up @@ -357,23 +357,23 @@ def read(filename): # noqa: C901
cells.append((key, data[key]))

elif index == "39":
logging.warning("Zone specification not supported yet. Skipping.")
warn("Zone specification not supported yet. Skipping.")
_skip_close(f, line.count("(") - line.count(")"))

elif index == "45":
# (45 (2 fluid solid)())
obj = re.match("\\(45 \\([0-9]+ ([\\S]+) ([\\S]+)\\)\\(\\)\\)", line)
if obj:
logging.warning(
warn(
"Zone specification not supported yet (%r, %r). " "Skipping.",
obj.group(1),
obj.group(2),
)
else:
logging.warning("Zone specification not supported yet.")
warn("Zone specification not supported yet.")

else:
logging.warning("Unknown index %r. Skipping.", index)
warn("Unknown index %r. Skipping.", index)
# Skipping ahead to the next line with two closing brackets.
_skip_close(f, line.count("(") - line.count(")"))

Expand Down
8 changes: 3 additions & 5 deletions src/meshio/avsucd/_avsucd.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,10 @@
I/O for AVS-UCD format, cf.
<https://lanl.github.io/LaGriT/pages/docs/read_avs.html>.
"""
import logging

import numpy as np

from ..__about__ import __version__ as version
from .._common import _pick_first_int_data
from .._common import _pick_first_int_data, warn
from .._files import open_file
from .._helpers import register_format
from .._mesh import CellBlock, Mesh
Expand Down Expand Up @@ -147,7 +145,7 @@ def _read_data(f, num_entities, entity_ids):

def write(filename, mesh):
if len(mesh.points.shape) > 1 and mesh.points.shape[1] == 2:
logging.warning(
warn(
"AVS-UCD requires 3D points, but 2D points given. "
"Appending 0 third component."
)
Expand All @@ -165,7 +163,7 @@ def write(filename, mesh):
key, other = _pick_first_int_data(mesh.cell_data)
if key and other:
other_string = ", ".join(other)
logging.warning(
warn(
"AVS-UCD can only write one cell data array. "
f"Picking {key}, skipping {other_string}."
)
Expand Down
8 changes: 4 additions & 4 deletions src/meshio/dolfin/_dolfin.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@
I/O for DOLFIN's XML format, cf.
<https://people.sc.fsu.edu/~jburkardt/data/dolfin_xml/dolfin_xml.html>.
"""
import logging
import os
import pathlib
import re
from xml.etree import ElementTree as ET

import numpy as np

from .._common import warn
from .._exceptions import ReadError, WriteError
from .._helpers import register_format
from .._mesh import Mesh
Expand Down Expand Up @@ -71,7 +71,7 @@ def _read_mesh(filename):
assert cell_tags is not None
cells[0][1][k] = [elem.attrib[t] for t in cell_tags]
else:
logging.warning("Unknown entry %s. Ignoring.", elem.tag)
warn("Unknown entry %s. Ignoring.", elem.tag)

elem.clear()

Expand Down Expand Up @@ -138,7 +138,7 @@ def _write_mesh(filename, points, cell_type, cells):

if any(c.type != cell_type for c in cells):
discarded_cell_types = {c.type for c in cells if c.type != cell_type}
logging.warning(
warn(
"DOLFIN XML can only handle one cell type at a time. "
"Using %s, discarding %s.",
cell_type,
Expand Down Expand Up @@ -215,7 +215,7 @@ def _write_cell_data(filename, dim, cell_data):


def write(filename, mesh):
logging.warning("DOLFIN XML is a legacy format. Consider using XDMF instead.")
warn("DOLFIN XML is a legacy format. Consider using XDMF instead.")

if any("tetra" == c.type for c in mesh.cells):
cell_type = "tetra"
Expand Down
6 changes: 3 additions & 3 deletions src/meshio/exodus/_exodus.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@
"""
import datetime
import re
import warnings

import numpy as np

from ..__about__ import __version__
from .._common import warn
from .._exceptions import ReadError
from .._helpers import register_format
from .._mesh import Mesh
Expand Down Expand Up @@ -122,7 +122,7 @@ def read(filename): # noqa: C901
# For now only take the first value
pd[idx] = value[0]
if len(value) > 1:
warnings.warn("Skipping some time data")
warn("Skipping some time data")
elif key == "name_elem_var":
value.set_auto_mask(False)
cell_data_names = [b"".join(c).decode("UTF-8") for c in value[:]]
Expand All @@ -139,7 +139,7 @@ def read(filename): # noqa: C901
cd[idx][block] = value[0]

if len(value) > 1:
warnings.warn("Skipping some time data")
warn("Skipping some time data")
elif key == "ns_names":
value.set_auto_mask(False)
ns_names = [b"".join(c).decode("UTF-8") for c in value[:]]
Expand Down
21 changes: 10 additions & 11 deletions src/meshio/flac3d/_flac3d.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
"""
I/O for FLAC3D format.
"""
import logging
import struct
import time
from warnings import warn

import numpy as np

from ..__about__ import __version__ as version
from .._common import _pick_first_int_data
from .._common import _pick_first_int_data, warn
from .._files import open_file
from .._helpers import register_format
from .._mesh import Mesh
Expand Down Expand Up @@ -170,10 +168,13 @@ def read_buffer(f, binary):
]

if len(cell_sets) > 0:
# Can only deal with sequential cell_ids for now. If the order is messed
# up, or if some indices are missing, cell_sets will be wrong.
if not np.all(np.arange(cell_ids[0], cell_ids[-1] + 1) == cell_ids):
warn("FLAC3D cell IDs not sequential. Cell sets probably messed up.")
# Can only deal with arange cell_ids for now.
if not np.array_equal(np.arange(0, cell_ids[-1] + 1), cell_ids):
warn(
"FLAC3D cell IDs not arange (0, 1, 2, ..., n). "
+ "Cell sets probably messed up.",
highlight=False,
)

# cell_sets contains the indices into the global cell list. Since this is
# split up into blocks, we need to split the cell_sets, too.
Expand Down Expand Up @@ -278,9 +279,7 @@ def write(filename, mesh: Mesh, float_fmt: str = ".16e", binary: bool = False):
"""Write FLAC3D f3grid grid file."""
skip = [c.type for c in mesh.cells if c.type not in meshio_only["zone"]]
if skip:
logging.warning(
f'FLAC3D format only supports 3D cells. Skipping {", ".join(skip)}.'
)
warn(f'FLAC3D format only supports 3D cells. Skipping {", ".join(skip)}.')

# Pick out material
material = None
Expand All @@ -289,7 +288,7 @@ def write(filename, mesh: Mesh, float_fmt: str = ".16e", binary: bool = False):
if key:
material = np.concatenate(mesh.cell_data[key])
if other:
logging.warning(
warn(
"FLAC3D can only write one cell data array. "
f'Picking {key}, skipping {", ".join(other)}.'
)
Expand Down
Loading

0 comments on commit b75f0aa

Please sign in to comment.