tecio-python 0.4.2__py3-none-any.whl → 0.4.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
tecio/__init__.py CHANGED
@@ -11,7 +11,7 @@ from importlib import metadata
11
11
  try:
12
12
  __version__ = metadata.version("tecio")
13
13
  except metadata.PackageNotFoundError:
14
- __version__ = "0.4.2"
14
+ __version__ = "0.4.3"
15
15
 
16
16
  from . import cli, libtecio
17
17
  from ._constants import (
tecio/_plt_read.py CHANGED
@@ -819,11 +819,13 @@ class _PltParser:
819
819
  def _var_value_count(self, meta: _ZoneMeta, var_idx: int) -> int:
820
820
  """Return the number of values on disk for variable *var_idx*.
821
821
 
822
- For cell-centered variables in ORDERED zones the PLT format writes ``IMax * JMax
823
- * (KMax - 1)`` values on disk (see Note 5 of the format spec). The significant
824
- cell count is ``(I-1) * (J-1) * (K-1)``; the remainder are ghost (zero-padded)
825
- values that are trimmed in :meth:`TecplotPltVariableReader.get_values` after
826
- reshaping.
822
+ For cell-centered variables in ORDERED zones the PLT format pads every
823
+ dimension but the last one with more than one node (see Note 5 of the format
824
+ spec): ``IMax * JMax * (KMax - 1)`` values on disk for an IJK-ordered zone,
825
+ ``IMax * (JMax - 1)`` for an IJ-ordered zone and ``IMax - 1`` for an I-ordered
826
+ zone. The significant cell count is ``(I-1) * (J-1) * (K-1)``; the remainder
827
+ are ghost (zero-padded) values that are trimmed in
828
+ :meth:`TecplotPltVariableReader.get_values` after reshaping.
827
829
 
828
830
  For FE zones, cell-centered variables store exactly one value per element with
829
831
  no padding.
@@ -835,10 +837,14 @@ class _PltParser:
835
837
  j = max(meta.j_max, 1)
836
838
  k = max(meta.k_max, 1)
837
839
  if loc == ValueLocation.CELL_CENTERED:
838
- # PLT Note 5: IMax * JMax * (KMax - 1) values on disk. Only K is
839
- # reduced; I and J retain their full extent as ghost padding in the
840
- # Fortran-order layout.
841
- return i * j * max(k - 1, 1)
840
+ # PLT Note 5: only the last dimension with more than one node is
841
+ # reduced; the dimensions before it retain their full extent as ghost
842
+ # padding in the Fortran-order layout.
843
+ if k > 1:
844
+ return i * j * (k - 1)
845
+ if j > 1:
846
+ return i * (j - 1)
847
+ return max(i - 1, 1)
842
848
  return i * j * k
843
849
  else:
844
850
  # FE zones — no ghost padding.
@@ -1260,11 +1266,17 @@ class TecplotPltVariableReader(TecplotVariableReader):
1260
1266
  if full_read and meta.zone_type == ZoneType.ORDERED:
1261
1267
  ni, nj, nk = meta.i_max, meta.j_max, meta.k_max
1262
1268
  if meta.value_locations[self.var_index] == ValueLocation.CELL_CENTERED:
1263
- # On disk: i * j * (k-1) values in Fortran order. Ghost padding occupies
1264
- # the last row in I and J after reshape, so reshape to (ni, nj, nk-1)
1265
- # then slice to (ni-1, nj-1, nk-1) to discard the ghost values and
1266
- # return only significant cells.
1267
- data = data.reshape((ni, nj, max(nk - 1, 1)), order="F")
1269
+ # On disk: the padded layout of _var_value_count in Fortran order. Ghost
1270
+ # padding occupies the last row of each padded dimension after reshape,
1271
+ # so reshape to the padded shape then slice to (ni-1, nj-1, nk-1) to
1272
+ # discard the ghost values and return only significant cells.
1273
+ if nk > 1:
1274
+ padded = (ni, nj, nk - 1)
1275
+ elif nj > 1:
1276
+ padded = (ni, nj - 1, 1)
1277
+ else:
1278
+ padded = (max(ni - 1, 1), 1, 1)
1279
+ data = data.reshape(padded, order="F")
1268
1280
  data = data[: max(ni - 1, 1), : max(nj - 1, 1), :]
1269
1281
  else:
1270
1282
  shape = (ni, nj, nk)
tecio/cli/tectable.py ADDED
@@ -0,0 +1,1134 @@
1
+ r"""Convert a delimited text table to ordered Tecplot zones.
2
+
3
+ Simplify loading plain text tables into Tecplot with some additional tools that operate
4
+ on database-like text tables from a command-line interface.
5
+
6
+ Automatically parse numeric columns to ordered zone variables variables. While text
7
+ columns cannot be represented in data arrays, if every entry of the column is the same
8
+ within a zone, the text is stored as zone-level auxiliary data
9
+ ``column_header=column_text`` and otherwise automatically skipped. Database parsing
10
+ tools allow families of data to be grouped my constant values similar to pivot tables
11
+ with ``-g``/``--group``. The group values are stored in each zone as auxiliary data, and
12
+ in its title. For data that is a function of two or more independent variables, optional
13
+ ``-m``/``--mesh`` allow the uesr to specify columns containing one-dimensional
14
+ coordinate arrays to be converted to N-dimensional IJ(K) ordered arrays (such as a
15
+ surface of a coefficient over two angles). The user may filter data that is written to
16
+ file with ``--filter`` supporting all math comparison operators.
17
+
18
+ :Usage:
19
+
20
+ .. code:: bash
21
+
22
+ tectable [-h] [-o PATH] [-f] [-d DELIMITER] [--header {auto,yes,no}]
23
+ [-n NAMES] [--filter EXPR [--filter ...]] [-g COLUMN [-g ...]]
24
+ [-r | --no-sort] [--keep-group] [-m COLUMN [-m ...]]
25
+ [--precision {auto,single,double}] [--comment PREFIX] [PATH]
26
+
27
+ :Positional Arguments:
28
+ ``PATH``
29
+ Path to the delimited text table. Use ``-`` or leave it out to read standard
30
+ input.
31
+
32
+ :Options:
33
+ ``-o PATH``, ``--output PATH``
34
+ Output file path. The extension determines the output format (either ``.szplt``,
35
+ ``.plt``, or ``.dat``). Defaults to the input path with the extension
36
+ ``.szplt``, or to ``table.szplt`` when reading standard input.
37
+
38
+ ``-f``, ``--force``
39
+ Overwrite the output file if it already exists. Files are not overwritten by
40
+ default.
41
+
42
+ ``-d DELIMITER``, ``--delimiter DELIMITER``
43
+ Field separator: ``comma``, ``space`` (any run of spaces and tabs), ``tab``, or
44
+ a single character such as ``;``. The default, ``auto``, picks ``comma`` if the
45
+ first line holds a comma and ``space`` otherwise. Spaces around the fields are
46
+ removed, and fields may be quoted with ``"``.
47
+
48
+ ``--header {auto,yes,no}``
49
+ Whether the first line holds the column names. With ``auto``, the first line is
50
+ a header if a column that is numeric in the other rows is not numeric there.
51
+ Without a header the variables are named ``V1``, ``V2``, and so on.
52
+
53
+ ``-n NAMES``, ``--names NAMES``
54
+ Comma-separated column names, replacing the header. A header line is then
55
+ dropped only with ``--header yes``.
56
+
57
+ ``--filter EXPR``
58
+ Keep only the rows where ``COLUMN OP VALUE`` holds, with ``OP`` one of ``==``,
59
+ ``!=``, ``<``, ``<=``, ``>`` and ``>=``. The column is named exactly as in the
60
+ header (case-sensitive), so quote the expression in a shell, for example
61
+ ``--filter 'Alpha!=0'``. Text columns support ``==`` and ``!=`` only.
62
+ Repeatable: a row is kept if it satisfies all of the filters. Missing values
63
+ (NaN) fail every comparison except ``!=``.
64
+
65
+ ``-g COLUMN``, ``--group COLUMN``
66
+ Split the rows into zones by the values of this column, named exactly as in
67
+ the header (case-sensitive). Names with spaces are quoted in the shell, for
68
+ example ``-g "Mach number"``. Repeatable: with several columns, rows are
69
+ grouped by the first, then by the second within each of those, and so on.
70
+ Zones are ordered by the group values, numerically for numeric columns and
71
+ alphabetically for text columns. Rows keep their file order within a zone.
72
+
73
+ ``-r``, ``--reverse``
74
+ Order the zones by descending group values.
75
+
76
+ ``--no-sort``
77
+ Order the zones by the first appearance of each group in the table.
78
+
79
+ ``--keep-group``
80
+ Keep numeric group columns as variables. By default they are dropped, since
81
+ each zone holds a single constant value that is stored as auxiliary data.
82
+
83
+ ``-m COLUMN``, ``--mesh COLUMN``
84
+ Write each zone as an IJ (two columns) or IJK (three columns) ordered zone
85
+ instead of a list of points. The first column varies fastest. Every zone must
86
+ hold each combination of the distinct values of these columns exactly once,
87
+ which is a complete, not necessarily square, grid. Otherwise the command
88
+ fails and names the zone. The columns must be numeric and not be group
89
+ columns. They stay in the file as variables.
90
+
91
+ ``--precision {auto,single,double}``
92
+ Data type of the variables. With ``auto`` a column of whole numbers is stored
93
+ as the smallest of ``uint8``, ``int16`` and ``int32`` that holds it. Any other
94
+ column is stored in single precision if every value has at most 6 significant
95
+ digits, which single precision holds as written, and in double precision
96
+ otherwise. ``.szplt`` files choose per variable. A ``.dat`` file chooses the
97
+ integer types per variable, and one precision for its other variables. A
98
+ ``.plt`` file has no integer variables, and one precision for all of them. Use
99
+ ``single`` or ``double`` to store every variable as a float of that precision.
100
+ Default ``auto``.
101
+
102
+ ``--comment PREFIX``
103
+ Ignore text from this prefix to the end of a line. Default ``#``. An empty
104
+ string turns it off.
105
+
106
+ :Returns:
107
+ A Tecplot file with one ordered zone per group, or one zone without ``-g``. Exit
108
+ code ``0`` on success and non-zero if the input cannot be read or parsed, a column
109
+ cannot be resolved, a filter removes every row, a mesh is not complete, no numeric
110
+ column remains, or the output file already exists and ``--force`` is not set.
111
+
112
+ Notes:
113
+ A column is numeric if its first rows (up to 200,000) are all numbers. Empty fields
114
+ and ``NA``, ``N/A``, ``null``, ``none`` and ``nan`` are read as NaN, and Fortran
115
+ ``D`` exponents are accepted. Any other text in such a column later in the table
116
+ is an error.
117
+
118
+ Text values are matched exactly, apart from the removal of surrounding spaces.
119
+ Auxiliary data names are the column names with other characters than letters,
120
+ digits, ``_`` and ``.`` replaced by ``_``. Text columns that vary within some zone
121
+ are skipped in that zone, with a note on standard error.
122
+
123
+ Examples:
124
+ Convert a CSV file with a header row into ``results.szplt``::
125
+
126
+ $ tectable results.csv
127
+
128
+ Read from a pipe, picking the output format by extension::
129
+
130
+ $ awk '$3 > 0' raw.txt | tectable -o filtered.plt
131
+
132
+ Split rows into one zone per category, with the category as auxiliary data::
133
+
134
+ $ tectable -g Category runs.csv
135
+
136
+ Group by two columns, in descending order of the first::
137
+
138
+ $ tectable -g Case -g Run -r runs.csv -o runs.szplt
139
+
140
+ From an aerodynamic database, one zone for each Mach, Altitude and Beta, with the
141
+ columns Alpha, CX, CY and so on as variables, and the three group values as
142
+ auxiliary data of the zone::
143
+
144
+ $ tectable -g Mach -g Altitude -g Beta --filter 'Alpha!=0' aero.csv
145
+
146
+ Surfaces over Alpha and Beta, one for each Mach and Altitude::
147
+
148
+ $ tectable -g Mach -g Altitude -m Alpha -m Beta aero.csv
149
+
150
+ A semicolon separated table without a header::
151
+
152
+ $ tectable -d ';' -n x,y,p scan.txt -o scan.dat
153
+
154
+ Call directly from a Python session::
155
+
156
+ from tecio.cli.tectable import main as tectable
157
+
158
+ tectable(["-g", "Category", "table.csv", "-o", "table.szplt"])
159
+
160
+ Without a file, ``table.szplt`` is written to the current directory::
161
+
162
+ $ cat table.csv | tectable
163
+
164
+ See Also:
165
+ :mod:`tecio.cli.teconvert` - Convert between Tecplot file formats.
166
+
167
+ """
168
+
169
+ from __future__ import annotations
170
+
171
+ import argparse
172
+ import math
173
+ import re
174
+ import sys
175
+ from collections.abc import Callable, Iterator, Sequence
176
+ from itertools import islice
177
+ from pathlib import Path
178
+ from typing import IO, Any, NamedTuple, cast
179
+
180
+ import numpy as np
181
+ import numpy.typing as npt
182
+
183
+ from .. import open as tecio_open
184
+
185
+ # Rows parsed at a time, which also bounds the rows that decide the type of a column
186
+ _CHUNK_ROWS = 200_000
187
+ # Delimiter names mapped to the characters for np.loadtxt, None meaning any whitespace
188
+ _DELIMITERS: dict[str, str | None] = {"comma": ",", "space": None, "tab": "\t"}
189
+ _MISSING = ("", "na", "n/a", "null", "none")
190
+ _OUTPUT_EXTENSIONS = (".szplt", ".plt", ".dat")
191
+ _DEFAULT_OUTPUT = "table.szplt"
192
+ # Two-character operators come first so that "<=" is not read as "<"
193
+ _FILTER_OPERATORS: dict[str, Callable[[Any, Any], Any]] = {
194
+ "==": np.equal,
195
+ "!=": np.not_equal,
196
+ "<=": np.less_equal,
197
+ ">=": np.greater_equal,
198
+ "<": np.less,
199
+ ">": np.greater,
200
+ }
201
+ # Values of a column checked first when classifying it, so that a column that does not
202
+ # fit a narrow type is rejected at once
203
+ _SAMPLE_ROWS = 1024
204
+ # Integer types of Tecplot with their value range, smallest first
205
+ _INTEGER_TYPES = (
206
+ (np.dtype(np.uint8), 0, 2**8 - 1),
207
+ (np.dtype(np.int16), -(2**15), 2**15 - 1),
208
+ (np.dtype(np.int32), -(2**31), 2**31 - 1),
209
+ )
210
+ # The .dat writer prints integers with 9 significant digits, which is exact below this
211
+ _DAT_INTEGER_LIMIT = 10**9 - 1
212
+
213
+ # --------------------------------------------------------------------------------------
214
+ # Argument parsing
215
+ # --------------------------------------------------------------------------------------
216
+
217
+
218
+ def _parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
219
+ parser = argparse.ArgumentParser(
220
+ prog="tectable",
221
+ description=(
222
+ # -|-------------------|---------------------------------------------|
223
+ "Convert a delimited text table, from a file or standard input, to\n"
224
+ "ordered Tecplot zones. Numeric columns become variables."
225
+ ),
226
+ epilog=(
227
+ "Example usage:\n"
228
+ " Convert a CSV file with a header row\n"
229
+ " $ tectable results.csv\n"
230
+ " Read from a pipe\n"
231
+ " $ awk '$3 > 0' raw.txt | tectable -o filtered.plt\n"
232
+ " One zone per category, category stored as aux data\n"
233
+ " $ tectable -g Category runs.csv\n"
234
+ " Group by two columns, descending order\n"
235
+ " $ tectable -g Case -g Run -r runs.csv -o runs.szplt\n"
236
+ " Keep some rows, then make Alpha x Beta surfaces per Mach\n"
237
+ " $ tectable --filter 'Beta<3' -g Mach -m Alpha -m Beta a.csv\n"
238
+ ),
239
+ formatter_class=lambda prog: argparse.RawDescriptionHelpFormatter(
240
+ prog, width=70, max_help_position=24
241
+ ),
242
+ )
243
+ parser.add_argument(
244
+ "filename",
245
+ nargs="?",
246
+ default="-",
247
+ type=str,
248
+ help="Input text table. Use - or omit to read standard input.",
249
+ )
250
+ parser.add_argument(
251
+ "-o",
252
+ "--output",
253
+ type=str,
254
+ default=None,
255
+ metavar="PATH",
256
+ help=(
257
+ "Output file path (.szplt, .plt or .dat). Defaults to the input "
258
+ "path with the extension .szplt, or table.szplt for standard input."
259
+ ),
260
+ )
261
+ parser.add_argument(
262
+ "-f",
263
+ "--force",
264
+ action="store_true",
265
+ default=False,
266
+ help="Overwrite the output file if it already exists.",
267
+ )
268
+ parser.add_argument(
269
+ "-d",
270
+ "--delimiter",
271
+ type=str,
272
+ default="auto",
273
+ metavar="DELIMITER",
274
+ help=(
275
+ "Field separator: comma, space (runs of spaces and tabs), tab, or a "
276
+ "single character. Default auto: comma if the first line has one, "
277
+ "otherwise space."
278
+ ),
279
+ )
280
+ parser.add_argument(
281
+ "--header",
282
+ choices=["auto", "yes", "no"],
283
+ default="auto",
284
+ help="Whether the first line holds column names. Default auto.",
285
+ )
286
+ parser.add_argument(
287
+ "-n",
288
+ "--names",
289
+ type=str,
290
+ default=None,
291
+ metavar="NAMES",
292
+ help="Comma-separated column names, replacing the header.",
293
+ )
294
+ parser.add_argument(
295
+ "--filter",
296
+ action="append",
297
+ default=[],
298
+ metavar="EXPR",
299
+ dest="filters",
300
+ help=(
301
+ "Keep rows where 'COLUMN OP VALUE' holds, OP is one of == != < <= > >=. "
302
+ "Repeatable, all must hold. Quote it, e.g. --filter 'Alpha!=0'."
303
+ ),
304
+ )
305
+ parser.add_argument(
306
+ "-g",
307
+ "--group",
308
+ action="append",
309
+ default=[],
310
+ metavar="COLUMN",
311
+ help=(
312
+ "Split rows into one zone per value of this column, named as in the "
313
+ "header (case-sensitive). Repeatable for nested groups, first is "
314
+ "the outermost."
315
+ ),
316
+ )
317
+ order = parser.add_mutually_exclusive_group()
318
+ order.add_argument(
319
+ "-r",
320
+ "--reverse",
321
+ action="store_true",
322
+ default=False,
323
+ help="Order zones by descending group values.",
324
+ )
325
+ order.add_argument(
326
+ "--no-sort",
327
+ action="store_true",
328
+ default=False,
329
+ help="Order zones by first appearance of each group.",
330
+ )
331
+ parser.add_argument(
332
+ "--keep-group",
333
+ action="store_true",
334
+ default=False,
335
+ help="Keep numeric group columns as variables.",
336
+ )
337
+ parser.add_argument(
338
+ "-m",
339
+ "--mesh",
340
+ action="append",
341
+ default=[],
342
+ metavar="COLUMN",
343
+ help=(
344
+ "Write zones as IJ(K) ordered zones over the distinct values of this "
345
+ "numeric column. Repeatable up to 3 times, first varies fastest."
346
+ ),
347
+ )
348
+ parser.add_argument(
349
+ "--precision",
350
+ choices=["auto", "single", "double"],
351
+ default="auto",
352
+ help=(
353
+ "Variable type. auto stores whole numbers as integers and other "
354
+ "columns in single precision if all values have at most 6 "
355
+ "significant digits. Default auto."
356
+ ),
357
+ )
358
+ parser.add_argument(
359
+ "--comment",
360
+ type=str,
361
+ default="#",
362
+ metavar="PREFIX",
363
+ help="Ignore text from this prefix to the end of a line. Default '#'.",
364
+ )
365
+ return parser.parse_args(argv)
366
+
367
+
368
+ # --------------------------------------------------------------------------------------
369
+ # Reading the table
370
+ # --------------------------------------------------------------------------------------
371
+
372
+
373
+ class _Table(NamedTuple):
374
+ """A parsed table: numeric columns as values, text columns as coded labels."""
375
+
376
+ names: list[str]
377
+ numeric: dict[int, npt.NDArray[np.float64]]
378
+ codes: dict[int, npt.NDArray[np.int32]]
379
+ labels: dict[int, list[str]]
380
+ num_rows: int
381
+
382
+
383
+ def _data_lines(stream: IO[str], comment: str | None) -> Iterator[str]:
384
+ """Yield the lines that hold data, without blank and comment-only lines."""
385
+ for raw in stream:
386
+ text = raw.strip()
387
+ if text and not (comment and text.startswith(comment)):
388
+ yield text
389
+
390
+
391
+ def _resolve_delimiter(spec: str, first_line: str) -> str | None:
392
+ """Return the ``np.loadtxt`` delimiter for *spec*, ``None`` for whitespace.
393
+
394
+ Raises:
395
+ ValueError: If *spec* is not a name or a single character.
396
+ """
397
+ name = spec.lower()
398
+ if name == "auto":
399
+ return "," if "," in first_line else None
400
+ if name in _DELIMITERS:
401
+ return _DELIMITERS[name]
402
+ if len(spec) == 1:
403
+ return None if spec == " " else spec
404
+ raise ValueError(
405
+ f"delimiter {spec!r} must be auto, comma, space, tab or a single character."
406
+ )
407
+
408
+
409
+ def _split_fields(
410
+ lines: Sequence[str], delimiter: str | None, comment: str | None
411
+ ) -> npt.NDArray[np.str_]:
412
+ """Split *lines* into fields.
413
+
414
+ Returns:
415
+ A ``(rows, columns)`` array of strings.
416
+
417
+ Raises:
418
+ ValueError: If the lines do not all have the same number of fields, or a quote
419
+ is not closed on its line, which would join it with the next lines.
420
+ """
421
+ rows = np.loadtxt(
422
+ lines,
423
+ dtype=str,
424
+ delimiter=delimiter,
425
+ comments=comment or None,
426
+ quotechar='"',
427
+ ndmin=2,
428
+ )
429
+ if len(rows) != len(lines):
430
+ raise ValueError("a quote is not closed on its line.")
431
+ return rows
432
+
433
+
434
+ def _to_float(column: npt.NDArray[np.str_]) -> npt.NDArray[np.float64] | None:
435
+ """Convert a column of strings to numbers, or return ``None`` if it is text.
436
+
437
+ Missing-value words become NaN and a Fortran ``D`` exponent is read as ``E``. A
438
+ column without a single number is text.
439
+
440
+ Returns:
441
+ The values, or ``None`` for a text column.
442
+ """
443
+ try:
444
+ return column.astype(np.float64)
445
+ except ValueError:
446
+ pass
447
+ low = np.char.lower(np.char.strip(column))
448
+ low = np.where(np.isin(low, _MISSING), "nan", low)
449
+ try:
450
+ values = np.char.replace(low, "d", "e").astype(np.float64)
451
+ except ValueError:
452
+ return None
453
+ return None if np.isnan(values).all() else values
454
+
455
+
456
+ def _load_floats(
457
+ lines: Sequence[str], delimiter: str | None, comment: str | None, columns: int
458
+ ) -> npt.NDArray[np.float64] | None:
459
+ """Parse *lines* directly as numbers, which is much faster than via strings.
460
+
461
+ Returns:
462
+ A ``(rows, columns)`` array, or ``None`` if the lines hold anything but
463
+ numbers, or do not have *columns* fields, or have an open quote. The caller
464
+ then parses them again as text, which also describes the problem.
465
+ """
466
+ try:
467
+ values = np.loadtxt(
468
+ lines,
469
+ dtype=np.float64,
470
+ delimiter=delimiter,
471
+ comments=comment or None,
472
+ quotechar='"',
473
+ ndmin=2,
474
+ )
475
+ except ValueError:
476
+ return None
477
+ return values if values.shape == (len(lines), columns) else None
478
+
479
+
480
+ def _factorize(
481
+ column: npt.NDArray[np.str_], labels: list[str], index: dict[str, int]
482
+ ) -> npt.NDArray[np.int32]:
483
+ """Code the strings of a column as integers into *labels*, adding new strings.
484
+
485
+ Returns:
486
+ The index into *labels* of each string.
487
+ """
488
+ unique, inverse = np.unique(np.char.strip(column), return_inverse=True)
489
+ lookup = np.empty(len(unique), dtype=np.int32)
490
+ for k, text in enumerate(unique.tolist()):
491
+ if text not in index:
492
+ index[text] = len(labels)
493
+ labels.append(text)
494
+ lookup[k] = index[text]
495
+ return lookup[inverse.reshape(-1)]
496
+
497
+
498
+ def _clean_names(fields: Sequence[str]) -> list[str]:
499
+ """Make column names non-empty and unique.
500
+
501
+ Returns:
502
+ The cleaned names.
503
+ """
504
+ names: list[str] = []
505
+ for j, field in enumerate(fields):
506
+ name = field.strip() or f"V{j + 1}"
507
+ base, count = name, 1
508
+ while name in names:
509
+ count += 1
510
+ name = f"{base}_{count}"
511
+ names.append(name)
512
+ return names
513
+
514
+
515
+ def _ragged(
516
+ lines: Sequence[str],
517
+ delimiter: str | None,
518
+ comment: str | None,
519
+ num_columns: int,
520
+ first_number: int,
521
+ error: ValueError,
522
+ ) -> ValueError:
523
+ """Describe the first line that does not have *num_columns* fields.
524
+
525
+ Args:
526
+ lines: The lines that were parsed together.
527
+ delimiter: Field delimiter for ``np.loadtxt``.
528
+ comment: Comment prefix, or ``None``.
529
+ num_columns: Expected number of fields.
530
+ first_number: 1-based data line number of ``lines[0]``.
531
+ error: The error raised while parsing, used if no line is at fault.
532
+
533
+ Returns:
534
+ The error to raise, naming the line when one can be found.
535
+ """
536
+ for k, line in enumerate(lines):
537
+ if _split_fields([line], delimiter, comment).shape[1] != num_columns:
538
+ return ValueError(
539
+ f"line {first_number + k}: expected {num_columns} fields."
540
+ )
541
+ return error
542
+
543
+
544
+ def _read_table(
545
+ stream: IO[str],
546
+ delimiter_spec: str,
547
+ comment: str | None,
548
+ header: str,
549
+ names: list[str] | None,
550
+ ) -> _Table:
551
+ """Parse a delimited text table in chunks of rows.
552
+
553
+ Args:
554
+ stream: Text stream to read.
555
+ delimiter_spec: ``--delimiter`` value.
556
+ comment: Comment prefix, or ``None``.
557
+ header: ``auto``, ``yes`` or ``no``, whether the first line is a header.
558
+ names: Column names given by the user, or ``None``.
559
+
560
+ Returns:
561
+ The table. A column is numeric if its first chunk of rows is.
562
+
563
+ Raises:
564
+ ValueError: If the table is empty or ragged, a header cannot be used, or a
565
+ column turns out not to be numeric after its first rows.
566
+ """
567
+ lines = _data_lines(stream, comment)
568
+ first = next(lines, None)
569
+ if first is None:
570
+ raise ValueError("the input holds no data.")
571
+ delimiter = _resolve_delimiter(delimiter_spec, first)
572
+ pending = [first, *islice(lines, _CHUNK_ROWS)]
573
+ try:
574
+ rows = _split_fields(pending, delimiter, comment)
575
+ except ValueError as exc:
576
+ expected = _split_fields([first], delimiter, comment).shape[1]
577
+ error = _ragged(pending, delimiter, comment, expected, 1, exc)
578
+ raise error from exc
579
+ num_columns = rows.shape[1]
580
+ if names is not None and len(names) != num_columns:
581
+ raise ValueError(
582
+ f"--names has {len(names)} names but the table has {num_columns} columns."
583
+ )
584
+
585
+ first_fields, body = rows[0], rows[1:]
586
+ body_values: list[npt.NDArray[np.float64] | None] = []
587
+ if header == "auto":
588
+ if names is None and len(body) > 0:
589
+ body_values = [_to_float(body[:, j]) for j in range(num_columns)]
590
+ is_header = any(
591
+ v is not None and _to_float(first_fields[j : j + 1]) is None
592
+ for j, v in enumerate(body_values)
593
+ )
594
+ else:
595
+ is_header = header == "yes"
596
+ if names is None:
597
+ names = _clean_names(first_fields if is_header else [""] * num_columns)
598
+ data = body if is_header else rows
599
+ if len(data) == 0:
600
+ raise ValueError("the input holds a header but no data rows.")
601
+
602
+ numeric: dict[int, list[npt.NDArray[np.float64]]] = {}
603
+ coded: dict[int, list[npt.NDArray[np.int32]]] = {}
604
+ labels: dict[int, list[str]] = {}
605
+ index: dict[int, dict[str, int]] = {}
606
+ for j in range(num_columns):
607
+ values = body_values[j] if is_header and body_values else None
608
+ if values is None:
609
+ values = _to_float(data[:, j])
610
+ if values is not None:
611
+ numeric[j] = [values]
612
+ else:
613
+ labels[j], index[j] = [], {}
614
+ coded[j] = [_factorize(data[:, j], labels[j], index[j])]
615
+ num_rows = len(data)
616
+ line_number = len(rows) + 1
617
+
618
+ while True:
619
+ pending = list(islice(lines, _CHUNK_ROWS))
620
+ if not pending:
621
+ break
622
+ if not coded:
623
+ floats = _load_floats(pending, delimiter, comment, num_columns)
624
+ if floats is not None:
625
+ for j in range(num_columns):
626
+ numeric[j].append(floats[:, j])
627
+ num_rows += len(floats)
628
+ line_number += len(floats)
629
+ continue
630
+ try:
631
+ rows = _split_fields(pending, delimiter, comment)
632
+ except ValueError as exc:
633
+ error = _ragged(pending, delimiter, comment, num_columns, line_number, exc)
634
+ raise error from exc
635
+ if rows.shape[1] != num_columns:
636
+ error = _ragged(
637
+ pending, delimiter, comment, num_columns, line_number, ValueError()
638
+ )
639
+ raise error
640
+ for j in range(num_columns):
641
+ if j in numeric:
642
+ values = _to_float(rows[:, j])
643
+ if values is None:
644
+ raise ValueError(
645
+ f"column '{names[j]}' is numeric at first but holds text "
646
+ f"near line {line_number}."
647
+ )
648
+ numeric[j].append(values)
649
+ else:
650
+ coded[j].append(_factorize(rows[:, j], labels[j], index[j]))
651
+ num_rows += len(rows)
652
+ line_number += len(rows)
653
+
654
+ return _Table(
655
+ names=names,
656
+ numeric={j: np.concatenate(v) for j, v in numeric.items()},
657
+ codes={j: np.concatenate(v) for j, v in coded.items()},
658
+ labels=labels,
659
+ num_rows=num_rows,
660
+ )
661
+
662
+
663
+ # --------------------------------------------------------------------------------------
664
+ # Filtering
665
+ # --------------------------------------------------------------------------------------
666
+
667
+
668
+ def _parse_filter(expr: str, names: list[str]) -> tuple[int, str, str]:
669
+ """Split a filter such as ``Alpha>=2`` into its column, operator and value.
670
+
671
+ The longest column name that starts the expression is used, so names may hold
672
+ spaces and operator characters.
673
+
674
+ Returns:
675
+ The 0-based column, the operator and the value text.
676
+
677
+ Raises:
678
+ ValueError: If no column name is followed by an operator.
679
+ """
680
+ text = expr.strip()
681
+ for j in sorted(range(len(names)), key=lambda k: -len(names[k])):
682
+ if not text.startswith(names[j]):
683
+ continue
684
+ rest = text[len(names[j]) :].lstrip()
685
+ for op in _FILTER_OPERATORS:
686
+ if rest.startswith(op):
687
+ return j, op, rest[len(op) :].strip()
688
+ raise ValueError(
689
+ f"cannot read filter '{expr}': expected COLUMN OP VALUE with COLUMN one of "
690
+ f"{names} and OP one of {list(_FILTER_OPERATORS)}."
691
+ )
692
+
693
+
694
+ def _apply_filters(table: _Table, filters: Sequence[str]) -> _Table:
695
+ """Keep the rows of *table* that satisfy all *filters*.
696
+
697
+ The columns are replaced one at a time in place, so the filtered table and a
698
+ single original column are in memory together, not two copies of the table.
699
+
700
+ Returns:
701
+ The table with the remaining rows.
702
+
703
+ Raises:
704
+ ValueError: If a filter cannot be read or used with its column, or no row is
705
+ left.
706
+ """
707
+ mask = np.ones(table.num_rows, dtype=bool)
708
+ for expr in filters:
709
+ j, op, value = _parse_filter(expr, table.names)
710
+ compare = _FILTER_OPERATORS[op]
711
+ if j in table.numeric:
712
+ try:
713
+ number = float(value)
714
+ except ValueError:
715
+ raise ValueError(
716
+ f"filter '{expr}': '{value}' is not a number, but column "
717
+ f"'{table.names[j]}' is numeric."
718
+ ) from None
719
+ mask &= compare(table.numeric[j], number)
720
+ else:
721
+ if op not in ("==", "!="):
722
+ raise ValueError(
723
+ f"filter '{expr}': text column '{table.names[j]}' supports "
724
+ "only == and !=."
725
+ )
726
+ text = value[1:-1] if value[:1] == value[-1:] == '"' else value
727
+ labels = table.labels[j]
728
+ code = labels.index(text) if text in labels else -1
729
+ mask &= compare(table.codes[j], code)
730
+ kept = int(mask.sum())
731
+ if kept == 0:
732
+ raise ValueError("no row satisfies the filters.")
733
+ if kept == table.num_rows:
734
+ return table
735
+ for column in (table.numeric, table.codes):
736
+ for j in column:
737
+ column[j] = column[j][mask]
738
+ return table._replace(num_rows=kept)
739
+
740
+
741
+ # --------------------------------------------------------------------------------------
742
+ # Grouping
743
+ # --------------------------------------------------------------------------------------
744
+
745
+
746
+ class _Group(NamedTuple):
747
+ """Rows of one group (``None`` for all rows) and the text of its group values."""
748
+
749
+ rows: npt.NDArray[np.intp] | None
750
+ key: list[str]
751
+
752
+
753
+ def _format_number(value: float) -> str:
754
+ """Format a group value without a needless ``.0``.
755
+
756
+ Returns:
757
+ The text of the value.
758
+ """
759
+ if np.isfinite(value) and float(value).is_integer() and abs(value) < 1e15:
760
+ return str(int(value))
761
+ return repr(float(value))
762
+
763
+
764
+ def _resolve_column(spec: str, names: list[str]) -> int:
765
+ """Return the 0-based column named exactly *spec*.
766
+
767
+ Raises:
768
+ ValueError: If *spec* matches no column.
769
+ """
770
+ if spec in names:
771
+ return names.index(spec)
772
+ raise ValueError(f"column '{spec}' not found. Available: {names}")
773
+
774
+
775
+ def _split_groups(
776
+ table: _Table, group_cols: list[int], *, reverse: bool, sort: bool
777
+ ) -> list[_Group]:
778
+ """Split the rows into groups of equal values in *group_cols*.
779
+
780
+ Groups are in ascending order of their values, the first column varying slowest,
781
+ or descending with *reverse*, or in order of first appearance without *sort*. Rows
782
+ keep their table order within a group.
783
+
784
+ Returns:
785
+ The groups, each with its rows and the text of its group values.
786
+ """
787
+ if not group_cols:
788
+ return [_Group(None, [])]
789
+ codes: list[npt.NDArray[np.intp]] = []
790
+ texts: list[list[str]] = []
791
+ for j in group_cols:
792
+ if j in table.numeric:
793
+ unique, inverse = np.unique(table.numeric[j], return_inverse=True)
794
+ codes.append(inverse.reshape(-1))
795
+ texts.append([_format_number(v) for v in unique])
796
+ else:
797
+ ordered = np.argsort(np.array(table.labels[j]), kind="stable")
798
+ rank = np.empty(len(ordered), dtype=np.intp)
799
+ rank[ordered] = np.arange(len(ordered))
800
+ codes.append(rank[table.codes[j]])
801
+ texts.append([table.labels[j][k] for k in ordered])
802
+
803
+ order = np.lexsort(codes[::-1])
804
+ changed = np.zeros(len(order), dtype=bool)
805
+ changed[0] = True
806
+ for c in codes:
807
+ ranked = c[order]
808
+ changed[1:] |= ranked[1:] != ranked[:-1]
809
+ starts = np.flatnonzero(changed)
810
+ ends = np.append(starts[1:], len(order))
811
+ groups = [
812
+ _Group(order[s:e], [t[c[order[s]]] for t, c in zip(texts, codes, strict=True)])
813
+ for s, e in zip(starts, ends, strict=True)
814
+ ]
815
+ if not sort:
816
+ groups.sort(key=lambda g: int(cast(npt.NDArray[np.intp], g.rows)[0]))
817
+ elif reverse:
818
+ groups.reverse()
819
+ return groups
820
+
821
+
822
+ # --------------------------------------------------------------------------------------
823
+ # Meshes and precision
824
+ # --------------------------------------------------------------------------------------
825
+
826
+
827
+ def _resolve_mesh(
828
+ specs: Sequence[str], table: _Table, group_cols: list[int]
829
+ ) -> list[int]:
830
+ """Return the columns of the ``--mesh`` names.
831
+
832
+ Raises:
833
+ ValueError: If a name is unknown or repeated, there are more than 3, or a
834
+ column is not numeric or is a group column.
835
+ """
836
+ cols = [_resolve_column(m, table.names) for m in specs]
837
+ if len(cols) > 3 or len(set(cols)) != len(cols):
838
+ raise ValueError("--mesh takes 1 to 3 different columns.")
839
+ for j in cols:
840
+ if j not in table.numeric or j in group_cols:
841
+ raise ValueError(
842
+ f"mesh column '{table.names[j]}' must be numeric and not a group."
843
+ )
844
+ return cols
845
+
846
+
847
+ def _mesh_layout(
848
+ table: _Table, rows: npt.NDArray[np.intp] | None, mesh_cols: list[int], label: str
849
+ ) -> tuple[npt.NDArray[np.intp], tuple[int, ...]]:
850
+ """Order the rows of a zone as a complete grid over the *mesh_cols* values.
851
+
852
+ Args:
853
+ table: The table.
854
+ rows: Table rows of the zone, or ``None`` for all rows.
855
+ mesh_cols: Numeric columns that span the grid, the first varying fastest.
856
+ label: Text that names the zone in errors, or an empty string.
857
+
858
+ Returns:
859
+ The table rows in grid order, and the grid dimensions.
860
+
861
+ Raises:
862
+ ValueError: If a mesh column holds NaN, or the rows are not each combination
863
+ of the distinct values exactly once.
864
+ """
865
+ count = table.num_rows if rows is None else len(rows)
866
+ axes: list[npt.NDArray[np.intp]] = []
867
+ dims: list[int] = []
868
+ for j in mesh_cols:
869
+ values = table.numeric[j] if rows is None else table.numeric[j][rows]
870
+ if np.isnan(values).any():
871
+ raise ValueError(
872
+ f"{label}mesh column '{table.names[j]}' has missing values."
873
+ )
874
+ unique, inverse = np.unique(values, return_inverse=True)
875
+ axes.append(inverse.reshape(-1))
876
+ dims.append(len(unique))
877
+ total = math.prod(dims)
878
+ shape = " x ".join(str(d) for d in dims)
879
+ names = " x ".join(table.names[j] for j in mesh_cols)
880
+ if total != count:
881
+ raise ValueError(
882
+ f"{label}the rows are not a complete {names} grid: {count} rows for "
883
+ f"{shape} = {total} points."
884
+ )
885
+ slot = np.ravel_multi_index(tuple(axes), tuple(dims), order="F")
886
+ seen = np.zeros(total, dtype=bool)
887
+ seen[slot] = True
888
+ if not seen.all():
889
+ raise ValueError(f"{label}the {names} grid has repeated points.")
890
+ order = np.empty(total, dtype=np.intp)
891
+ order[slot] = np.arange(total)
892
+ return (order if rows is None else rows[order]), tuple(dims)
893
+
894
+
895
+ def _blocks(values: npt.NDArray[np.float64]) -> Iterator[npt.NDArray[np.float64]]:
896
+ """Yield the first rows of *values*, then the rest in blocks of limited size.
897
+
898
+ The small temporary arrays of a check stay small, and a check that fails on the
899
+ first rows ends early.
900
+ """
901
+ step = max(_CHUNK_ROWS // 4, _SAMPLE_ROWS)
902
+ edges = [0, min(len(values), _SAMPLE_ROWS), *range(step, len(values), step)]
903
+ edges.append(len(values))
904
+ for start, stop in zip(edges[:-1], edges[1:], strict=True):
905
+ yield values[start:stop]
906
+
907
+
908
+ def _integer_dtype(values: npt.NDArray[np.float64], limit: int) -> np.dtype[Any] | None:
909
+ """Return the smallest Tecplot integer type that holds every value, if any.
910
+
911
+ Returns:
912
+ ``uint8``, ``int16`` or ``int32``, or ``None`` if a value is not a whole number
913
+ (NaN and infinity are not), or its magnitude is more than *limit*.
914
+ """
915
+ low = high = 0.0
916
+ for block in _blocks(values):
917
+ if not np.array_equal(block, np.rint(block)):
918
+ return None
919
+ if block.size:
920
+ low, high = min(low, np.min(block)), max(high, np.max(block))
921
+ if max(-low, high) > limit:
922
+ return None
923
+ return next((t for t, lo, hi in _INTEGER_TYPES if lo <= low and high <= hi), None)
924
+
925
+
926
+ def _fits_single(values: npt.NDArray[np.float64]) -> bool:
927
+ """Tell if single precision holds every value as written in the table.
928
+
929
+ Single precision keeps 6 significant decimal digits, so that is the test.
930
+
931
+ Returns:
932
+ ``True`` if every value has at most 6 significant digits.
933
+ """
934
+ for block in _blocks(values):
935
+ magnitude = np.abs(block[np.isfinite(block)])
936
+ magnitude = magnitude[magnitude != 0]
937
+ if magnitude.size == 0:
938
+ continue
939
+ if magnitude.min() < 1e-30 or magnitude.max() > 1e30:
940
+ return False
941
+ # Scale to 6 digits before the decimal point, which must leave an integer
942
+ scaled = magnitude * 10.0 ** (5 - np.floor(np.log10(magnitude)))
943
+ if (np.abs(scaled - np.rint(scaled)) > 1e-8).any():
944
+ return False
945
+ return True
946
+
947
+
948
+ def _best_dtype(values: npt.NDArray[np.float64], limit: int) -> np.dtype[Any]:
949
+ """Pick the narrowest type that keeps every value of a column as written.
950
+
951
+ Returns:
952
+ An integer type for whole numbers up to *limit*, else ``float32`` if single
953
+ precision holds the values, else ``float64``.
954
+ """
955
+ integer = _integer_dtype(values, limit)
956
+ if integer is not None:
957
+ return integer
958
+ return np.dtype(np.float32 if _fits_single(values) else np.float64)
959
+
960
+
961
+ # --------------------------------------------------------------------------------------
962
+ # Main
963
+ # --------------------------------------------------------------------------------------
964
+
965
+
966
+ def _aux_name(name: str) -> str:
967
+ """Make a column name usable as an auxiliary data name.
968
+
969
+ Returns:
970
+ The name with characters other than letters, digits, ``_`` and ``.`` replaced.
971
+ """
972
+ return re.sub(r"[^A-Za-z0-9_.]", "_", name) or "_"
973
+
974
+
975
+ def main(argv: Sequence[str] | None = None) -> int:
976
+ """Convert a delimited text table to ordered Tecplot zones.
977
+
978
+ Returns:
979
+ Exit code -- ``0`` on success, ``1`` on error.
980
+ """
981
+ args = _parse_args(argv)
982
+
983
+ from_stdin = args.filename == "-"
984
+ src = None if from_stdin else Path(args.filename)
985
+ if src is not None and not src.is_file():
986
+ print(f"Error: input file not found: {src}", file=sys.stderr)
987
+ return 1
988
+ if from_stdin and sys.stdin.isatty():
989
+ print("Error: no input. Give a file or pipe a table in.", file=sys.stderr)
990
+ return 1
991
+
992
+ if args.output is not None:
993
+ dst = Path(args.output)
994
+ elif src is not None:
995
+ dst = src.with_suffix(".szplt")
996
+ else:
997
+ dst = Path(_DEFAULT_OUTPUT)
998
+ if dst.suffix.lower() not in _OUTPUT_EXTENSIONS:
999
+ print(
1000
+ f"Error: output extension must be one of {_OUTPUT_EXTENSIONS}, "
1001
+ f"got '{dst.suffix}'.",
1002
+ file=sys.stderr,
1003
+ )
1004
+ return 1
1005
+ if src is not None and dst.resolve() == src.resolve():
1006
+ print("Error: the output would overwrite the input.", file=sys.stderr)
1007
+ return 1
1008
+ if dst.exists() and not args.force:
1009
+ print(
1010
+ f"Error: output file already exists: {dst}\nUse --force to overwrite.",
1011
+ file=sys.stderr,
1012
+ )
1013
+ return 1
1014
+
1015
+ names = None if args.names is None else [n.strip() for n in args.names.split(",")]
1016
+ try:
1017
+ if src is None:
1018
+ table = _read_table(
1019
+ sys.stdin, args.delimiter, args.comment, args.header, names
1020
+ )
1021
+ else:
1022
+ with src.open(encoding="utf-8-sig") as stream:
1023
+ table = _read_table(
1024
+ stream, args.delimiter, args.comment, args.header, names
1025
+ )
1026
+ read_rows = table.num_rows
1027
+ table = _apply_filters(table, args.filters)
1028
+ group_cols = list(
1029
+ dict.fromkeys(_resolve_column(g, table.names) for g in args.group)
1030
+ )
1031
+ mesh_cols = _resolve_mesh(args.mesh, table, group_cols)
1032
+ groups = _split_groups(
1033
+ table, group_cols, reverse=args.reverse, sort=not args.no_sort
1034
+ )
1035
+ except (ValueError, OSError, UnicodeDecodeError) as exc:
1036
+ print(f"Error: {exc}", file=sys.stderr)
1037
+ return 1
1038
+
1039
+ var_cols = [
1040
+ j for j in sorted(table.numeric) if args.keep_group or j not in group_cols
1041
+ ]
1042
+ if not var_cols:
1043
+ print("Error: no numeric column is left to write.", file=sys.stderr)
1044
+ return 1
1045
+ text_cols = [j for j in sorted(table.codes) if j not in group_cols]
1046
+ print(
1047
+ f"Read {read_rows} rows: {len(table.numeric)} numeric and "
1048
+ f"{len(table.codes)} text columns."
1049
+ )
1050
+ if args.filters:
1051
+ print(f"Kept {table.num_rows} of {read_rows} rows.")
1052
+
1053
+ # Only .szplt files choose the type per variable, by the dtype of the data. A .dat
1054
+ # file takes integers per variable but one floating point precision for the rest.
1055
+ # A .plt file has one floating point precision for all variables.
1056
+ options: dict[str, str] = {}
1057
+ dtypes: dict[int, np.dtype[Any]] = {}
1058
+ suffix = dst.suffix.lower()
1059
+ if args.precision != "auto":
1060
+ options["precision"] = args.precision
1061
+ elif suffix == ".plt":
1062
+ fits = all(_fits_single(table.numeric[j]) for j in var_cols)
1063
+ options["precision"] = "single" if fits else "double"
1064
+ else:
1065
+ limit = _DAT_INTEGER_LIMIT if suffix == ".dat" else 2**31
1066
+ dtypes = {j: _best_dtype(table.numeric[j], limit) for j in var_cols}
1067
+ if suffix == ".dat":
1068
+ floats = {d for d in dtypes.values() if d.kind == "f"}
1069
+ options["precision"] = (
1070
+ "double" if np.dtype(np.float64) in floats else "single"
1071
+ )
1072
+ dtypes = {j: d for j, d in dtypes.items() if d != np.dtype(np.float64)}
1073
+
1074
+ varying: set[str] = set()
1075
+ try:
1076
+ with tecio_open(
1077
+ str(dst),
1078
+ "w",
1079
+ title=src.stem if src is not None else "",
1080
+ variables=[table.names[j] for j in var_cols],
1081
+ **options,
1082
+ ) as writer:
1083
+ for group in groups:
1084
+ rows = group.rows
1085
+ title = ", ".join(
1086
+ f"{table.names[j]}={text}"
1087
+ for j, text in zip(group_cols, group.key, strict=True)
1088
+ )
1089
+ aux: dict[str, str] = {}
1090
+ for j, text in zip(group_cols, group.key, strict=True):
1091
+ aux[_aux_name(table.names[j])] = text
1092
+ data: list[npt.NDArray[Any]]
1093
+ shape: tuple[int, ...] | None = None
1094
+ if mesh_cols:
1095
+ label = f"zone '{title}': " if title else ""
1096
+ index, shape = _mesh_layout(table, rows, mesh_cols, label)
1097
+ data = [table.numeric[j][index] for j in var_cols]
1098
+ else:
1099
+ data = [
1100
+ table.numeric[j] if rows is None else table.numeric[j][rows]
1101
+ for j in var_cols
1102
+ ]
1103
+ for k, j in enumerate(var_cols):
1104
+ if j in dtypes:
1105
+ data[k] = data[k].astype(dtypes[j])
1106
+ if shape is not None:
1107
+ data[k] = data[k].reshape(shape, order="F")
1108
+ for j in text_cols:
1109
+ codes = table.codes[j] if rows is None else table.codes[j][rows]
1110
+ if (codes != codes[0]).any():
1111
+ varying.add(table.names[j])
1112
+ elif text := table.labels[j][codes[0]]:
1113
+ aux[_aux_name(table.names[j])] = text
1114
+ writer.write_ordered_zone(
1115
+ data=data, title=title or None, aux=aux or None
1116
+ )
1117
+ except Exception as exc: # noqa: BLE001
1118
+ print(f"Error: {exc}", file=sys.stderr)
1119
+ dst.unlink(missing_ok=True)
1120
+ return 1
1121
+
1122
+ if varying:
1123
+ print(
1124
+ "Skipped text column(s) that vary within a zone: "
1125
+ + ", ".join(sorted(varying)),
1126
+ file=sys.stderr,
1127
+ )
1128
+ print(f"Wrote {len(groups)} zone(s) with {len(var_cols)} variable(s).")
1129
+ print(f"Done. Output written to: {dst}")
1130
+ return 0
1131
+
1132
+
1133
+ if __name__ == "__main__": # pragma: no cover
1134
+ sys.exit(main())
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tecio-python
3
- Version: 0.4.2
3
+ Version: 0.4.3
4
4
  Summary: Python interface for reading and writing Tecplot data files
5
5
  License-Expression: Apache-2.0
6
6
  Project-URL: Homepage, https://github.com/meersman/tecio-python
@@ -1,4 +1,4 @@
1
- tecio/__init__.py,sha256=758Zy3UEg2XVK4Pj1Qiui4_QDuJ5wvzNA2HTm9Jd1HE,4260
1
+ tecio/__init__.py,sha256=RaemnbCHS1psRikpABIyRiAWFMltXgq4R3vBv4ASIgI,4260
2
2
  tecio/_constants.py,sha256=PwWSUzncWlYUk35Y_jQn3-EtuadO9PrvsqbnhIrJlB0,7190
3
3
  tecio/_containers.py,sha256=PmVUwYfImIHB8uCHtA0AWQEcOHGBRkGlkMRrY8ONGZA,10501
4
4
  tecio/_dat_read.py,sha256=Vst02nRLl8fuDx2CyRMENXSrEYZYcOsM0u5kXrHfSGc,91166
@@ -7,7 +7,7 @@ tecio/_elements.py,sha256=16Y8IoCsvCiy66tprZX5zLgwcU5NuL-_0VawfTUsoMc,53176
7
7
  tecio/_io.py,sha256=DyVUIXVS2ndDjpYxaCVfiGExB_YDkRShB8_Y1YxuHdw,44854
8
8
  tecio/_meta.py,sha256=kR8w0K3nqNdn18t05fzzT4OM-qoQ0-8y9wjMNPvLztY,9501
9
9
  tecio/_plt_legacy.py,sha256=-JbRCjO21ZDtQWUSWo3wkrFGjDqHEe9hRg07CROCWAc,16664
10
- tecio/_plt_read.py,sha256=jQx0dS18tpxdExsi_Tj_jiUgDiJOSxDoCiCw7d4YUjU,70632
10
+ tecio/_plt_read.py,sha256=g8tlsFSRn8E9nxXw3QRGkdlCWwHvo09A1pQKeD39Mms,71192
11
11
  tecio/_plt_write.py,sha256=1eT_3uWIWboUwTBUBkTZPf15LMSqx7QzHhX2XFhnxDc,47317
12
12
  tecio/_reader.py,sha256=I2nXonsZzX4SwENcZ8Dj5gOTMd5co4aFx3CePISKGZY,58651
13
13
  tecio/_szl_read.py,sha256=e_NQOXeC4Aykd_y905bTFW-4VKbEXepXPDvWTABstCM,26758
@@ -27,14 +27,15 @@ tecio/cli/teconvert.py,sha256=sGSPQqGARDcxsoOpNAitYYo4caShaXVK8cP-yWXwZ1w,12934
27
27
  tecio/cli/tecscale.py,sha256=n3O9YR1grBdVx-ERMX7Xhr8Yu8bDUdQqVEhGahaYxaA,19018
28
28
  tecio/cli/tecslice.py,sha256=RtgY22RU3dl9VbfO7Z4alqM7etpJzwsSt1wjElrb2eA,39340
29
29
  tecio/cli/tecstats.py,sha256=BxTrmslbZaSA79Ypz-S0fRqn0jnPz1HLL8U2jrzVteg,20968
30
- tecio_python-0.4.2.data/data/share/tecio/plugins/matlab/contourfe.m,sha256=26QzDSSjhZvc-Xlhv-zhbF9z0jwOh2lYQvvhDCh1HUc,3212
31
- tecio_python-0.4.2.data/data/share/tecio/plugins/matlab/tecmat2struct.m,sha256=aVdWjrxv1Gir2g-lTvErgP1WAvid8nzft_b9IqocaEM,5626
32
- tecio_python-0.4.2.data/data/share/tecio/plugins/paraview/TecplotTecioReader.py,sha256=5ADNt21W1OQ-lVO1hexYF6lSlSFr_xiTSaulgG2Rp78,60217
33
- tecio_python-0.4.2.data/data/share/tecio/plugins/paraview/TecplotTecioWriter.py,sha256=OSbzaYlFbUwRgmeWNkC5GkZm_HuLPljndUYnaMRU-cw,42716
34
- tecio_python-0.4.2.dist-info/licenses/LICENSE,sha256=WYmcYJG1QFgu1hfo7qrEkZ3Jhcz8NUWe6XUraZvlIFs,10172
35
- tecio_python-0.4.2.dist-info/licenses/NOTICE,sha256=bDcDOguk8dYN4FpHJCHuCsDgR2VnP5XlK2C4BzVCtwg,340
36
- tecio_python-0.4.2.dist-info/METADATA,sha256=zXj1LJAiBrYgRW0Q5cT9QdKbZviVI2-e9lxUlgg4wWQ,5929
37
- tecio_python-0.4.2.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
38
- tecio_python-0.4.2.dist-info/entry_points.txt,sha256=kXvNrHXQCWlYtbb4OT5AR6hO862OD8JNQcesuiqDgkg,401
39
- tecio_python-0.4.2.dist-info/top_level.txt,sha256=ayCfhWQNUimgwyaTSyamJ3LbgjloZRWl2vlcZCjYWmQ,6
40
- tecio_python-0.4.2.dist-info/RECORD,,
30
+ tecio/cli/tectable.py,sha256=PfTKGFPWwe3aVXppitP2BjDMYp6oWim903x_dlrElSI,42187
31
+ tecio_python-0.4.3.data/data/share/tecio/plugins/matlab/contourfe.m,sha256=26QzDSSjhZvc-Xlhv-zhbF9z0jwOh2lYQvvhDCh1HUc,3212
32
+ tecio_python-0.4.3.data/data/share/tecio/plugins/matlab/tecmat2struct.m,sha256=aVdWjrxv1Gir2g-lTvErgP1WAvid8nzft_b9IqocaEM,5626
33
+ tecio_python-0.4.3.data/data/share/tecio/plugins/paraview/TecplotTecioReader.py,sha256=5ADNt21W1OQ-lVO1hexYF6lSlSFr_xiTSaulgG2Rp78,60217
34
+ tecio_python-0.4.3.data/data/share/tecio/plugins/paraview/TecplotTecioWriter.py,sha256=OSbzaYlFbUwRgmeWNkC5GkZm_HuLPljndUYnaMRU-cw,42716
35
+ tecio_python-0.4.3.dist-info/licenses/LICENSE,sha256=WYmcYJG1QFgu1hfo7qrEkZ3Jhcz8NUWe6XUraZvlIFs,10172
36
+ tecio_python-0.4.3.dist-info/licenses/NOTICE,sha256=bDcDOguk8dYN4FpHJCHuCsDgR2VnP5XlK2C4BzVCtwg,340
37
+ tecio_python-0.4.3.dist-info/METADATA,sha256=AAi_xzdXRe0RY5swawGkchJjQid5bZVHotM-8Q2iZRw,5929
38
+ tecio_python-0.4.3.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
39
+ tecio_python-0.4.3.dist-info/entry_points.txt,sha256=o7IdvpYbgO3UMbNssF0OZA7QMLnhYwU-RCNCfOhwVro,436
40
+ tecio_python-0.4.3.dist-info/top_level.txt,sha256=ayCfhWQNUimgwyaTSyamJ3LbgjloZRWl2vlcZCjYWmQ,6
41
+ tecio_python-0.4.3.dist-info/RECORD,,
@@ -10,3 +10,4 @@ teconvert = tecio.cli.teconvert:main
10
10
  tecscale = tecio.cli.tecscale:main
11
11
  tecslice = tecio.cli.tecslice:main
12
12
  tecstats = tecio.cli.tecstats:main
13
+ tectable = tecio.cli.tectable:main