foamlib 0.2.1__py3-none-any.whl → 0.2.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.
foamlib/__init__.py CHANGED
@@ -1,7 +1,7 @@
1
- __version__ = "0.2.1"
1
+ __version__ = "0.2.3"
2
2
 
3
3
  from ._cases import FoamCase, AsyncFoamCase, FoamCaseBase
4
- from ._dictionaries import FoamFile, FoamFieldFile
4
+ from ._dictionaries import FoamFile, FoamFieldFile, FoamDictionaryBase
5
5
 
6
6
  __all__ = [
7
7
  "FoamCase",
@@ -9,4 +9,5 @@ __all__ = [
9
9
  "FoamCaseBase",
10
10
  "FoamFile",
11
11
  "FoamFieldFile",
12
+ "FoamDictionaryBase",
12
13
  ]
foamlib/_cases.py CHANGED
@@ -64,6 +64,14 @@ class FoamCaseBase(Sequence["FoamCaseBase.TimeDirectory"]):
64
64
  except FileNotFoundError as e:
65
65
  raise KeyError(key) from e
66
66
 
67
+ def __contains__(self, obj: object) -> bool:
68
+ if isinstance(obj, FoamFieldFile):
69
+ return obj.path.parent == self.path
70
+ elif isinstance(obj, str):
71
+ return (self.path / obj).is_file()
72
+ else:
73
+ return False
74
+
67
75
  def __iter__(self) -> Iterator[FoamFieldFile]:
68
76
  for p in self.path.iterdir():
69
77
  if p.is_file():
@@ -0,0 +1,8 @@
1
+ from ._files import FoamFile, FoamFieldFile
2
+ from ._base import FoamDictionaryBase
3
+
4
+ __all__ = [
5
+ "FoamFile",
6
+ "FoamFieldFile",
7
+ "FoamDictionaryBase",
8
+ ]
@@ -0,0 +1,43 @@
1
+ from abc import abstractmethod
2
+ from dataclasses import dataclass
3
+ from typing import Dict, NamedTuple, Optional, Sequence, Union
4
+
5
+
6
+ class FoamDictionaryBase:
7
+ class DimensionSet(NamedTuple):
8
+ mass: Union[int, float] = 0
9
+ length: Union[int, float] = 0
10
+ time: Union[int, float] = 0
11
+ temperature: Union[int, float] = 0
12
+ moles: Union[int, float] = 0
13
+ current: Union[int, float] = 0
14
+ luminous_intensity: Union[int, float] = 0
15
+
16
+ def __repr__(self) -> str:
17
+ return f"{type(self).__qualname__}({', '.join(f'{n}={v}' for n, v in zip(self._fields, self) if v != 0)})"
18
+
19
+ @dataclass
20
+ class Dimensioned:
21
+ value: Union[int, float, Sequence[Union[int, float]]] = 0
22
+ dimensions: Union[
23
+ "FoamDictionaryBase.DimensionSet", Sequence[Union[int, float]]
24
+ ] = ()
25
+ name: Optional[str] = None
26
+
27
+ def __post_init__(self) -> None:
28
+ if not isinstance(self.dimensions, FoamDictionaryBase.DimensionSet):
29
+ self.dimensions = FoamDictionaryBase.DimensionSet(*self.dimensions)
30
+
31
+ Value = Union[str, int, float, bool, Dimensioned, DimensionSet, Sequence["Value"]]
32
+ """
33
+ A value that can be stored in an OpenFOAM dictionary.
34
+ """
35
+
36
+ _Dict = Dict[str, Union["FoamDictionaryBase.Value", "_Dict"]]
37
+
38
+ @abstractmethod
39
+ def as_dict(self) -> _Dict:
40
+ """
41
+ Return a nested dict representation of the dictionary.
42
+ """
43
+ raise NotImplementedError
@@ -0,0 +1,382 @@
1
+ from pathlib import Path
2
+ from typing import (
3
+ Any,
4
+ Iterator,
5
+ Mapping,
6
+ MutableMapping,
7
+ Optional,
8
+ Sequence,
9
+ Tuple,
10
+ Union,
11
+ cast,
12
+ )
13
+
14
+ from ._base import FoamDictionaryBase
15
+ from ._parsing import Parsed, as_dict, get_entry_locn, get_value, parse
16
+ from ._serialization import serialize_value
17
+
18
+ try:
19
+ import numpy as np
20
+ from numpy.typing import NDArray
21
+ except ModuleNotFoundError:
22
+ pass
23
+
24
+
25
+ class FoamFile(
26
+ FoamDictionaryBase,
27
+ MutableMapping[str, Union["FoamFile.Value", "FoamFile.Dictionary"]],
28
+ ):
29
+ """
30
+ An OpenFOAM dictionary file.
31
+
32
+ Use as a mutable mapping (i.e., like a dict) to access and modify entries.
33
+
34
+ Use as a context manager to make multiple changes to the file while saving all changes only once at the end.
35
+ """
36
+
37
+ class Dictionary(
38
+ FoamDictionaryBase,
39
+ MutableMapping[str, Union["FoamFile.Value", "FoamFile.Dictionary"]],
40
+ ):
41
+ """
42
+ An OpenFOAM dictionary within a file as a mutable mapping.
43
+ """
44
+
45
+ def __init__(self, _file: "FoamFile", _keywords: Sequence[str]) -> None:
46
+ self._file = _file
47
+ self._keywords = _keywords
48
+
49
+ def __getitem__(
50
+ self, keyword: str
51
+ ) -> Union["FoamFile.Value", "FoamFile.Dictionary"]:
52
+ return self._file[(*self._keywords, keyword)]
53
+
54
+ def _setitem(
55
+ self,
56
+ keyword: str,
57
+ value: Any,
58
+ *,
59
+ assume_field: bool = False,
60
+ assume_dimensions: bool = False,
61
+ ) -> None:
62
+ self._file._setitem(
63
+ (*self._keywords, keyword),
64
+ value,
65
+ assume_field=assume_field,
66
+ assume_dimensions=assume_dimensions,
67
+ )
68
+
69
+ def __setitem__(self, keyword: str, value: Any) -> None:
70
+ self._setitem(keyword, value)
71
+
72
+ def __delitem__(self, keyword: str) -> None:
73
+ del self._file[(*self._keywords, keyword)]
74
+
75
+ def __iter__(self) -> Iterator[str]:
76
+ return self._file._iter(tuple(self._keywords))
77
+
78
+ def __len__(self) -> int:
79
+ return len(list(iter(self)))
80
+
81
+ def __repr__(self) -> str:
82
+ return f"{type(self).__qualname__}({self._file}, {self._keywords})"
83
+
84
+ def as_dict(self) -> FoamDictionaryBase._Dict:
85
+ """
86
+ Return a nested dict representation of the dictionary.
87
+ """
88
+ ret = self._file.as_dict()
89
+
90
+ for k in self._keywords:
91
+ assert isinstance(ret, dict)
92
+ v = ret[k]
93
+ assert isinstance(v, dict)
94
+ ret = v
95
+
96
+ return ret
97
+
98
+ def __init__(self, path: Union[str, Path]) -> None:
99
+ self.path = Path(path).absolute()
100
+ if self.path.is_dir():
101
+ raise IsADirectoryError(self.path)
102
+ elif not self.path.is_file():
103
+ raise FileNotFoundError(self.path)
104
+
105
+ self._contents: Optional[str] = None
106
+ self._parsed: Optional[Parsed] = None
107
+ self._defer_io = 0
108
+ self._dirty = False
109
+
110
+ def __enter__(self) -> "FoamFile":
111
+ if self._defer_io == 0:
112
+ self._read()
113
+ self._defer_io += 1
114
+ return self
115
+
116
+ def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
117
+ self._defer_io -= 1
118
+ if self._defer_io == 0 and self._dirty:
119
+ assert self._contents is not None
120
+ self._write(self._contents)
121
+ assert not self._dirty
122
+
123
+ def _read(self) -> Tuple[str, Parsed]:
124
+ if not self._defer_io:
125
+ contents = self.path.read_text()
126
+ if contents != self._contents:
127
+ self._contents = contents
128
+ self._parsed = None
129
+
130
+ assert self._contents is not None
131
+
132
+ if self._parsed is None:
133
+ self._parsed = parse(self._contents)
134
+
135
+ return self._contents, self._parsed
136
+
137
+ def _write(self, contents: str) -> None:
138
+ self._contents = contents
139
+ self._parsed = None
140
+ if not self._defer_io:
141
+ self.path.write_text(contents)
142
+ self._dirty = False
143
+ else:
144
+ self._dirty = True
145
+
146
+ def __getitem__(
147
+ self, keywords: Union[str, Tuple[str, ...]]
148
+ ) -> Union["FoamFile.Value", "FoamFile.Dictionary"]:
149
+ if not isinstance(keywords, tuple):
150
+ keywords = (keywords,)
151
+
152
+ _, parsed = self._read()
153
+
154
+ value = get_value(parsed, keywords)
155
+
156
+ if value is None:
157
+ return FoamFile.Dictionary(self, keywords)
158
+ else:
159
+ return value
160
+
161
+ def _setitem(
162
+ self,
163
+ keywords: Union[str, Tuple[str, ...]],
164
+ value: Any,
165
+ *,
166
+ assume_field: bool = False,
167
+ assume_dimensions: bool = False,
168
+ ) -> None:
169
+ if not isinstance(keywords, tuple):
170
+ keywords = (keywords,)
171
+
172
+ contents, parsed = self._read()
173
+
174
+ if isinstance(value, Mapping):
175
+ with self:
176
+ if isinstance(value, FoamDictionaryBase):
177
+ value = value.as_dict()
178
+
179
+ start, end = get_entry_locn(parsed, keywords, missing_ok=True)
180
+
181
+ self._write(
182
+ f"{contents[:start]} {keywords[-1]} {{\n}}\n {contents[end:]}"
183
+ )
184
+
185
+ for k, v in value.items():
186
+ self[(*keywords, k)] = v
187
+ else:
188
+ start, end = get_entry_locn(parsed, keywords, missing_ok=True)
189
+
190
+ value = serialize_value(
191
+ value, assume_field=assume_field, assume_dimensions=assume_dimensions
192
+ )
193
+
194
+ self._write(
195
+ f"{contents[:start]} {keywords[-1]} {value};\n {contents[end:]}"
196
+ )
197
+
198
+ def __setitem__(self, keywords: Union[str, Tuple[str, ...]], value: Any) -> None:
199
+ self._setitem(keywords, value)
200
+
201
+ def __delitem__(self, keywords: Union[str, Tuple[str, ...]]) -> None:
202
+ if not isinstance(keywords, tuple):
203
+ keywords = (keywords,)
204
+
205
+ contents, parsed = self._read()
206
+
207
+ start, end = get_entry_locn(parsed, keywords)
208
+
209
+ self._write(contents[:start] + contents[end:])
210
+
211
+ def _iter(self, keywords: Union[str, Tuple[str, ...]] = ()) -> Iterator[str]:
212
+ if not isinstance(keywords, tuple):
213
+ keywords = (keywords,)
214
+
215
+ contents = self.path.read_text()
216
+ parsed = parse(contents)
217
+
218
+ yield from (k[-1] for k in parsed if k[:-1] == keywords)
219
+
220
+ def __iter__(self) -> Iterator[str]:
221
+ return self._iter()
222
+
223
+ def __len__(self) -> int:
224
+ return len(list(iter(self)))
225
+
226
+ def __fspath__(self) -> str:
227
+ return str(self.path)
228
+
229
+ def __repr__(self) -> str:
230
+ return f"{type(self).__name__}({self.path})"
231
+
232
+ def as_dict(self) -> FoamDictionaryBase._Dict:
233
+ """
234
+ Return a nested dict representation of the file.
235
+ """
236
+ _, parsed = self._read()
237
+ return as_dict(parsed)
238
+
239
+
240
+ class FoamFieldFile(FoamFile):
241
+ """An OpenFOAM dictionary file representing a field as a mutable mapping."""
242
+
243
+ class BoundariesDictionary(FoamFile.Dictionary):
244
+ def __getitem__(self, keyword: str) -> "FoamFieldFile.BoundaryDictionary":
245
+ return cast(FoamFieldFile.BoundaryDictionary, super().__getitem__(keyword))
246
+
247
+ class BoundaryDictionary(FoamFile.Dictionary):
248
+ """An OpenFOAM dictionary representing a boundary condition as a mutable mapping."""
249
+
250
+ def __setitem__(self, key: str, value: Any) -> None:
251
+ if key == "value":
252
+ self._setitem(key, value, assume_field=True)
253
+ else:
254
+ self._setitem(key, value)
255
+
256
+ @property
257
+ def type(self) -> str:
258
+ """
259
+ Alias of `self["type"]`.
260
+ """
261
+ ret = self["type"]
262
+ if not isinstance(ret, str):
263
+ raise TypeError("type is not a string")
264
+ return ret
265
+
266
+ @type.setter
267
+ def type(self, value: str) -> None:
268
+ self["type"] = value
269
+
270
+ @property
271
+ def value(
272
+ self,
273
+ ) -> Union[
274
+ int,
275
+ float,
276
+ Sequence[Union[int, float, Sequence[Union[int, float]]]],
277
+ "NDArray[np.generic]",
278
+ ]:
279
+ """
280
+ Alias of `self["value"]`.
281
+ """
282
+ ret = self["value"]
283
+ if not isinstance(ret, (int, float, Sequence)):
284
+ raise TypeError("value is not a field")
285
+ return cast(Union[int, float, Sequence[Union[int, float]]], ret)
286
+
287
+ @value.setter
288
+ def value(
289
+ self,
290
+ value: Union[
291
+ int,
292
+ float,
293
+ Sequence[Union[int, float, Sequence[Union[int, float]]]],
294
+ "NDArray[np.generic]",
295
+ ],
296
+ ) -> None:
297
+ self["value"] = value
298
+
299
+ @value.deleter
300
+ def value(self) -> None:
301
+ del self["value"]
302
+
303
+ def __getitem__(
304
+ self, keywords: Union[str, Tuple[str, ...]]
305
+ ) -> Union[FoamFile.Value, FoamFile.Dictionary]:
306
+ if not isinstance(keywords, tuple):
307
+ keywords = (keywords,)
308
+
309
+ ret = super().__getitem__(keywords)
310
+ if keywords[0] == "boundaryField" and isinstance(ret, FoamFile.Dictionary):
311
+ if len(keywords) == 1:
312
+ ret = FoamFieldFile.BoundariesDictionary(self, keywords)
313
+ elif len(keywords) == 2:
314
+ ret = FoamFieldFile.BoundaryDictionary(self, keywords)
315
+ return ret
316
+
317
+ def __setitem__(self, keywords: Union[str, Tuple[str, ...]], value: Any) -> None:
318
+ if not isinstance(keywords, tuple):
319
+ keywords = (keywords,)
320
+
321
+ if keywords == ("internalField",):
322
+ self._setitem(keywords, value, assume_field=True)
323
+ elif keywords == ("dimensions",):
324
+ self._setitem(keywords, value, assume_dimensions=True)
325
+ else:
326
+ self._setitem(keywords, value)
327
+
328
+ @property
329
+ def dimensions(self) -> FoamFile.DimensionSet:
330
+ """
331
+ Alias of `self["dimensions"]`.
332
+ """
333
+ ret = self["dimensions"]
334
+ if not isinstance(ret, FoamFile.DimensionSet):
335
+ raise TypeError("dimensions is not a DimensionSet")
336
+ return ret
337
+
338
+ @dimensions.setter
339
+ def dimensions(
340
+ self, value: Union[FoamFile.DimensionSet, Sequence[Union[int, float]]]
341
+ ) -> None:
342
+ self["dimensions"] = value
343
+
344
+ @property
345
+ def internal_field(
346
+ self,
347
+ ) -> Union[
348
+ int,
349
+ float,
350
+ Sequence[Union[int, float, Sequence[Union[int, float]]]],
351
+ "NDArray[np.generic]",
352
+ ]:
353
+ """
354
+ Alias of `self["internalField"]`.
355
+ """
356
+ ret = self["internalField"]
357
+ if not isinstance(ret, (int, float, Sequence)):
358
+ raise TypeError("internalField is not a field")
359
+ return cast(Union[int, float, Sequence[Union[int, float]]], ret)
360
+
361
+ @internal_field.setter
362
+ def internal_field(
363
+ self,
364
+ value: Union[
365
+ int,
366
+ float,
367
+ Sequence[Union[int, float, Sequence[Union[int, float]]]],
368
+ "NDArray[np.generic]",
369
+ ],
370
+ ) -> None:
371
+ self["internalField"] = value
372
+
373
+ @property
374
+ def boundary_field(self) -> "FoamFieldFile.BoundariesDictionary":
375
+ """
376
+ Alias of `self["boundaryField"]`.
377
+ """
378
+ ret = self["boundaryField"]
379
+ if not isinstance(ret, FoamFieldFile.BoundariesDictionary):
380
+ assert not isinstance(ret, FoamFile.Dictionary)
381
+ raise TypeError("boundaryField is not a dictionary")
382
+ return ret
@@ -0,0 +1,177 @@
1
+ from typing import Mapping, MutableMapping, Optional, Sequence, Tuple
2
+
3
+ from pyparsing import (
4
+ Dict,
5
+ Forward,
6
+ Group,
7
+ Keyword,
8
+ LineEnd,
9
+ Literal,
10
+ Located,
11
+ Opt,
12
+ ParseResults,
13
+ ParserElement,
14
+ QuotedString,
15
+ Word,
16
+ c_style_comment,
17
+ common,
18
+ cpp_style_comment,
19
+ identbodychars,
20
+ printables,
21
+ )
22
+
23
+ from ._base import FoamDictionaryBase
24
+
25
+ _YES = Keyword("yes").set_parse_action(lambda: True)
26
+ _NO = Keyword("no").set_parse_action(lambda: False)
27
+ _DIMENSIONS = (
28
+ Literal("[").suppress() + common.number * 7 + Literal("]").suppress()
29
+ ).set_parse_action(lambda tks: FoamDictionaryBase.DimensionSet(*tks))
30
+
31
+
32
+ def _list_of(elem: ParserElement) -> ParserElement:
33
+ return Opt(
34
+ Literal("List") + Literal("<") + common.identifier + Literal(">")
35
+ ).suppress() + (
36
+ (
37
+ Opt(common.integer).suppress()
38
+ + (
39
+ Literal("(").suppress()
40
+ + Group((elem)[...], aslist=True)
41
+ + Literal(")").suppress()
42
+ )
43
+ )
44
+ | (
45
+ common.integer + Literal("{").suppress() + elem + Literal("}").suppress()
46
+ ).set_parse_action(lambda tks: [[tks[1]] * tks[0]])
47
+ )
48
+
49
+
50
+ _TENSOR = _list_of(common.number) | common.number
51
+ _IDENTIFIER = Word(identbodychars + "$", printables.replace(";", ""))
52
+ _DIMENSIONED = (Opt(_IDENTIFIER) + _DIMENSIONS + _TENSOR).set_parse_action(
53
+ lambda tks: FoamDictionaryBase.Dimensioned(*reversed(tks.as_list()))
54
+ )
55
+ _FIELD = (Keyword("uniform").suppress() + _TENSOR) | (
56
+ Keyword("nonuniform").suppress() + _list_of(_TENSOR)
57
+ )
58
+ _TOKEN = QuotedString('"', unquote_results=False) | _IDENTIFIER
59
+ _ITEM = Forward()
60
+ _LIST = _list_of(_ITEM)
61
+ _ITEM <<= (
62
+ _FIELD | _LIST | _DIMENSIONED | _DIMENSIONS | common.number | _YES | _NO | _TOKEN
63
+ )
64
+ _TOKENS = (
65
+ QuotedString('"', unquote_results=False) | Word(printables.replace(";", ""))
66
+ )[2, ...].set_parse_action(lambda tks: " ".join(tks))
67
+
68
+ _VALUE = _ITEM ^ _TOKENS
69
+
70
+ _ENTRY = Forward()
71
+ _DICTIONARY = Dict(Group(_ENTRY)[...])
72
+ _ENTRY <<= Located(
73
+ _TOKEN
74
+ + (
75
+ (Literal("{").suppress() + _DICTIONARY + Literal("}").suppress())
76
+ | (Opt(_VALUE, default="") + Literal(";").suppress())
77
+ )
78
+ )
79
+ _FILE = (
80
+ _DICTIONARY.ignore(c_style_comment)
81
+ .ignore(cpp_style_comment)
82
+ .ignore(Literal("#include") + ... + LineEnd()) # type: ignore [no-untyped-call]
83
+ )
84
+
85
+ Parsed = Mapping[Sequence[str], Tuple[int, Optional[FoamDictionaryBase.Value], int]]
86
+
87
+
88
+ def _flatten_result(
89
+ parse_result: ParseResults, *, _keywords: Sequence[str] = ()
90
+ ) -> Parsed:
91
+ ret: MutableMapping[
92
+ Sequence[str], Tuple[int, Optional[FoamDictionaryBase.Value], int]
93
+ ] = {}
94
+ start = parse_result.locn_start
95
+ assert isinstance(start, int)
96
+ item = parse_result.value
97
+ assert isinstance(item, Sequence)
98
+ end = parse_result.locn_end
99
+ assert isinstance(end, int)
100
+ key, *values = item
101
+ assert isinstance(key, str)
102
+ ret[(*_keywords, key)] = (start, None, end)
103
+ for value in values:
104
+ if isinstance(value, ParseResults):
105
+ ret.update(_flatten_result(value, _keywords=(*_keywords, key)))
106
+ else:
107
+ ret[(*_keywords, key)] = (start, value, end)
108
+ return ret
109
+
110
+
111
+ def parse(
112
+ contents: str,
113
+ ) -> Parsed:
114
+ parse_results = _FILE.parse_string(contents, parse_all=True)
115
+ ret: MutableMapping[
116
+ Sequence[str], Tuple[int, Optional[FoamDictionaryBase.Value], int]
117
+ ] = {}
118
+ for parse_result in parse_results:
119
+ ret.update(_flatten_result(parse_result))
120
+ return ret
121
+
122
+
123
+ def get_value(
124
+ parsed: Parsed,
125
+ keywords: Tuple[str, ...],
126
+ ) -> Optional[FoamDictionaryBase.Value]:
127
+ """
128
+ Value of an entry.
129
+ """
130
+ _, value, _ = parsed[keywords]
131
+ return value
132
+
133
+
134
+ def get_entry_locn(
135
+ parsed: Parsed,
136
+ keywords: Tuple[str, ...],
137
+ *,
138
+ missing_ok: bool = False,
139
+ ) -> Tuple[int, int]:
140
+ """
141
+ Location of an entry or where it should be inserted.
142
+ """
143
+ try:
144
+ start, _, end = parsed[keywords]
145
+ except KeyError:
146
+ if missing_ok:
147
+ if len(keywords) > 1:
148
+ _, _, end = parsed[keywords[:-1]]
149
+ end -= 1
150
+ else:
151
+ end = -1
152
+
153
+ start = end
154
+ else:
155
+ raise
156
+
157
+ return start, end
158
+
159
+
160
+ def as_dict(parsed: Parsed) -> FoamDictionaryBase._Dict:
161
+ """
162
+ Return a nested dict representation of the file.
163
+ """
164
+ ret: FoamDictionaryBase._Dict = {}
165
+ for keywords, (_, value, _) in parsed.items():
166
+
167
+ r = ret
168
+ for k in keywords[:-1]:
169
+ assert isinstance(r, dict)
170
+ v = r[k]
171
+ assert isinstance(v, dict)
172
+ r = v
173
+
174
+ assert isinstance(r, dict)
175
+ r[keywords[-1]] = {} if value is None else value
176
+
177
+ return ret
@@ -0,0 +1,103 @@
1
+ from contextlib import suppress
2
+ from typing import Any, Sequence
3
+
4
+ from ._base import FoamDictionaryBase
5
+
6
+ try:
7
+ import numpy as np
8
+ except ModuleNotFoundError:
9
+ numpy = False
10
+ else:
11
+ numpy = True
12
+
13
+
14
+ def _is_sequence(value: Any) -> bool:
15
+ return (
16
+ isinstance(value, Sequence)
17
+ and not isinstance(value, str)
18
+ or numpy
19
+ and isinstance(value, np.ndarray)
20
+ )
21
+
22
+
23
+ def _serialize_bool(value: Any) -> str:
24
+ if value is True:
25
+ return "yes"
26
+ elif value is False:
27
+ return "no"
28
+ else:
29
+ raise TypeError(f"Not a bool: {type(value)}")
30
+
31
+
32
+ def _serialize_list(value: Any) -> str:
33
+ if _is_sequence(value):
34
+ return f"({' '.join(serialize_value(v) for v in value)})"
35
+ else:
36
+ raise TypeError(f"Not a valid sequence: {type(value)}")
37
+
38
+
39
+ def _serialize_field(value: Any) -> str:
40
+ if _is_sequence(value):
41
+ try:
42
+ s = _serialize_list(value)
43
+ except TypeError:
44
+ raise TypeError(f"Not a valid field: {type(value)}") from None
45
+ else:
46
+ if len(value) < 10:
47
+ return f"uniform {s}"
48
+ else:
49
+ if isinstance(value[0], (int, float)):
50
+ kind = "scalar"
51
+ elif len(value[0]) == 3:
52
+ kind = "vector"
53
+ elif len(value[0]) == 6:
54
+ kind = "symmTensor"
55
+ elif len(value[0]) == 9:
56
+ kind = "tensor"
57
+ else:
58
+ raise TypeError(
59
+ f"Unsupported sequence length for field: {len(value[0])}"
60
+ )
61
+ return f"nonuniform List<{kind}> {len(value)}{s}"
62
+ else:
63
+ return f"uniform {value}"
64
+
65
+
66
+ def _serialize_dimensions(value: Any) -> str:
67
+ if _is_sequence(value) and len(value) == 7:
68
+ return f"[{' '.join(str(v) for v in value)}]"
69
+ else:
70
+ raise TypeError(f"Not a valid dimension set: {type(value)}")
71
+
72
+
73
+ def _serialize_dimensioned(value: Any) -> str:
74
+ if isinstance(value, FoamDictionaryBase.Dimensioned):
75
+ if value.name is not None:
76
+ return f"{value.name} {_serialize_dimensions(value.dimensions)} {serialize_value(value.value)}"
77
+ else:
78
+ return f"{_serialize_dimensions(value.dimensions)} {serialize_value(value.value)}"
79
+ else:
80
+ raise TypeError(f"Not a valid dimensioned value: {type(value)}")
81
+
82
+
83
+ def serialize_value(
84
+ value: Any, *, assume_field: bool = False, assume_dimensions: bool = False
85
+ ) -> str:
86
+ if isinstance(value, FoamDictionaryBase.DimensionSet) or assume_dimensions:
87
+ with suppress(TypeError):
88
+ return _serialize_dimensions(value)
89
+
90
+ if assume_field:
91
+ with suppress(TypeError):
92
+ return _serialize_field(value)
93
+
94
+ with suppress(TypeError):
95
+ return _serialize_dimensioned(value)
96
+
97
+ with suppress(TypeError):
98
+ return _serialize_list(value)
99
+
100
+ with suppress(TypeError):
101
+ return _serialize_bool(value)
102
+
103
+ return str(value)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: foamlib
3
- Version: 0.2.1
3
+ Version: 0.2.3
4
4
  Summary: A Python interface for interacting with OpenFOAM
5
5
  Author-email: "Gabriel S. Gerlero" <ggerlero@cimec.unl.edu.ar>
6
6
  Project-URL: Homepage, https://github.com/gerlero/foamlib
@@ -0,0 +1,14 @@
1
+ foamlib/__init__.py,sha256=VYMos2oCtIAGQx88R_0tco49MZogwcC6yvwQ2oqmSmU,287
2
+ foamlib/_cases.py,sha256=4f3c5BXnsHPhFvgXNjUcGGHyu7I0WZT6zxlvGhb9kMY,21213
3
+ foamlib/_subprocesses.py,sha256=5vqdQvpN_2v4GgDqxi-s88NGhZ6doFxkh0XY89ZWuHA,1926
4
+ foamlib/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ foamlib/_dictionaries/__init__.py,sha256=6UWBGe1t7cq-d6WWQrVm0Xpi7Whpkr-mkTWgAM4NwcE,160
6
+ foamlib/_dictionaries/_base.py,sha256=H8XfiaX1LD6OWwZ9m61SaKgI-_szF1udyEfiLurrCB8,1493
7
+ foamlib/_dictionaries/_files.py,sha256=baObt7Ewf_sM-9Y5JGMFCYK1CVdNQg3vYbOfjCgQA64,11582
8
+ foamlib/_dictionaries/_parsing.py,sha256=65kwMU6b4WmMngOR5ED8IBvMa59FQqTRmd9o0xPnWJM,4768
9
+ foamlib/_dictionaries/_serialization.py,sha256=P_eP46c-kCXx6rIGXL7hfDuEbS9h7uANZlgXsdcNwl8,3005
10
+ foamlib-0.2.3.dist-info/LICENSE.txt,sha256=5Dte9TUnLZzPRs4NQzl-Jc2-Ljd-t_v0ZR5Ng5r0UsY,35131
11
+ foamlib-0.2.3.dist-info/METADATA,sha256=DA7Kq6YIun5m2yisx_F4DSrYP13RZKgXwq0mTTX2y9A,4600
12
+ foamlib-0.2.3.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
13
+ foamlib-0.2.3.dist-info/top_level.txt,sha256=ZdVYtetXGwPwyfL-WhlhbTFQGAwKX5P_gXxtH9JYFPI,8
14
+ foamlib-0.2.3.dist-info/RECORD,,
foamlib/_dictionaries.py DELETED
@@ -1,494 +0,0 @@
1
- from pathlib import Path
2
- from dataclasses import dataclass
3
- from collections import namedtuple
4
- from contextlib import suppress
5
- from typing import (
6
- Any,
7
- Union,
8
- Sequence,
9
- Iterator,
10
- Optional,
11
- Mapping,
12
- MutableMapping,
13
- cast,
14
- )
15
-
16
- from pyparsing import (
17
- Dict,
18
- Forward,
19
- Group,
20
- Keyword,
21
- LineEnd,
22
- Literal,
23
- Located,
24
- Opt,
25
- QuotedString,
26
- Word,
27
- c_style_comment,
28
- common,
29
- cpp_style_comment,
30
- printables,
31
- identchars,
32
- identbodychars,
33
- )
34
-
35
- try:
36
- import numpy as np
37
- from numpy.typing import NDArray
38
- except ModuleNotFoundError:
39
- numpy = False
40
- else:
41
- numpy = True
42
-
43
- from ._subprocesses import run_process, CalledProcessError
44
-
45
-
46
- class _FoamDictionary(MutableMapping[str, Union["FoamFile.Value", "_FoamDictionary"]]):
47
-
48
- def __init__(self, _file: "FoamFile", _keywords: Sequence[str]) -> None:
49
- self._file = _file
50
- self._keywords = _keywords
51
-
52
- def _cmd(self, args: Sequence[str], *, key: Optional[str] = None) -> str:
53
- keywords = self._keywords
54
-
55
- if key is not None:
56
- keywords = [*self._keywords, key]
57
-
58
- if keywords:
59
- args = ["-entry", "/".join(keywords), *args]
60
-
61
- try:
62
- return (
63
- run_process(
64
- ["foamDictionary", *args, "-precision", "15", self._file.path],
65
- )
66
- .stdout.decode()
67
- .strip()
68
- )
69
- except CalledProcessError as e:
70
- stderr = e.stderr.decode()
71
- if "Cannot find entry" in stderr:
72
- raise KeyError(key) from None
73
- else:
74
- raise RuntimeError(
75
- f"{e.cmd} failed with return code {e.returncode}\n{e.stderr.decode()}"
76
- ) from None
77
-
78
- def __getitem__(self, key: str) -> Union["FoamFile.Value", "_FoamDictionary"]:
79
- contents = self._file.path.read_text()
80
- value = _DICTIONARY.parse_string(contents, parse_all=True).as_dict()
81
-
82
- for key in [*self._keywords, key]:
83
- value = value[key]
84
-
85
- if isinstance(value, dict):
86
- return _FoamDictionary(self._file, [*self._keywords, key])
87
- else:
88
- start, end = value
89
- return _VALUE.parse_string(contents[start:end], parse_all=True).as_list()[0]
90
-
91
- def _setitem(
92
- self,
93
- key: str,
94
- value: Any,
95
- *,
96
- assume_field: bool = False,
97
- assume_dimensions: bool = False,
98
- ) -> None:
99
- if isinstance(value, _FoamDictionary):
100
- value = value._cmd(["-value"])
101
- elif isinstance(value, Mapping):
102
- self._cmd(["-set", "{}"], key=key)
103
- subdict = self[key]
104
- print(subdict)
105
- assert isinstance(subdict, _FoamDictionary)
106
- for k, v in value.items():
107
- subdict[k] = v
108
- return
109
- else:
110
- value = serialize(
111
- value, assume_field=assume_field, assume_dimensions=assume_dimensions
112
- )
113
-
114
- if len(value) < 1000:
115
- self._cmd(["-set", value], key=key)
116
- else:
117
- self._cmd(["-set", "_foamlib_value_"], key=key)
118
- contents = self._file.path.read_text()
119
- contents = contents.replace("_foamlib_value_", value, 1)
120
- self._file.path.write_text(contents)
121
-
122
- def __setitem__(self, key: str, value: Any) -> None:
123
- self._setitem(key, value)
124
-
125
- def __delitem__(self, key: str) -> None:
126
- if key not in self:
127
- raise KeyError(key)
128
- self._cmd(["-remove"], key=key)
129
-
130
- def __iter__(self) -> Iterator[str]:
131
- value = _DICTIONARY.parse_file(self._file.path, parse_all=True).as_dict()
132
-
133
- for key in self._keywords:
134
- value = value[key]
135
-
136
- yield from value
137
-
138
- def __len__(self) -> int:
139
- return len(list(iter(self)))
140
-
141
- def __repr__(self) -> str:
142
- return "FoamFile.Dictionary"
143
-
144
-
145
- class FoamFile(_FoamDictionary):
146
- """An OpenFOAM dictionary file as a mutable mapping."""
147
-
148
- Dictionary = _FoamDictionary
149
-
150
- DimensionSet = namedtuple(
151
- "DimensionSet",
152
- [
153
- "mass",
154
- "length",
155
- "time",
156
- "temperature",
157
- "moles",
158
- "current",
159
- "luminous_intensity",
160
- ],
161
- defaults=(0, 0, 0, 0, 0, 0, 0),
162
- )
163
-
164
- @dataclass
165
- class Dimensioned:
166
- value: Union[int, float, Sequence[Union[int, float]]] = 0
167
- dimensions: Union["FoamFile.DimensionSet", Sequence[Union[int, float]]] = ()
168
- name: Optional[str] = None
169
-
170
- def __post_init__(self) -> None:
171
- if not isinstance(self.dimensions, FoamFile.DimensionSet):
172
- self.dimensions = FoamFile.DimensionSet(*self.dimensions)
173
-
174
- Value = Union[str, int, float, bool, Dimensioned, DimensionSet, Sequence["Value"]]
175
- """
176
- A value that can be stored in an OpenFOAM dictionary.
177
- """
178
-
179
- def __init__(self, path: Union[str, Path]) -> None:
180
- super().__init__(self, [])
181
- self.path = Path(path).absolute()
182
- if self.path.is_dir():
183
- raise IsADirectoryError(self.path)
184
- elif not self.path.is_file():
185
- raise FileNotFoundError(self.path)
186
-
187
- def __fspath__(self) -> str:
188
- return str(self.path)
189
-
190
- def __repr__(self) -> str:
191
- return f"{type(self).__name__}({self.path})"
192
-
193
-
194
- class FoamFieldFile(FoamFile):
195
- """An OpenFOAM dictionary file representing a field as a mutable mapping."""
196
-
197
- class BoundariesDictionary(_FoamDictionary):
198
- def __getitem__(
199
- self, key: str
200
- ) -> Union["FoamFile.Value", "FoamFieldFile.BoundaryDictionary"]:
201
- ret = super().__getitem__(key)
202
- if isinstance(ret, _FoamDictionary):
203
- ret = FoamFieldFile.BoundaryDictionary(
204
- self._file, [*self._keywords, key]
205
- )
206
- return ret
207
-
208
- def __repr__(self) -> str:
209
- return "FoamFieldFile.BoundariesDictionary"
210
-
211
- class BoundaryDictionary(_FoamDictionary):
212
- """An OpenFOAM dictionary representing a boundary condition as a mutable mapping."""
213
-
214
- def __setitem__(self, key: str, value: Any) -> None:
215
- if key == "value":
216
- self._setitem(key, value, assume_field=True)
217
- else:
218
- self._setitem(key, value)
219
-
220
- @property
221
- def type(self) -> str:
222
- """
223
- Alias of `self["type"]`.
224
- """
225
- ret = self["type"]
226
- if not isinstance(ret, str):
227
- raise TypeError("type is not a string")
228
- return ret
229
-
230
- @type.setter
231
- def type(self, value: str) -> None:
232
- self["type"] = value
233
-
234
- @property
235
- def value(
236
- self,
237
- ) -> Union[
238
- int,
239
- float,
240
- Sequence[Union[int, float, Sequence[Union[int, float]]]],
241
- "NDArray[np.generic]",
242
- ]:
243
- """
244
- Alias of `self["value"]`.
245
- """
246
- ret = self["value"]
247
- if not isinstance(ret, (int, float, Sequence)):
248
- raise TypeError("value is not a field")
249
- return cast(Union[int, float, Sequence[Union[int, float]]], ret)
250
-
251
- @value.setter
252
- def value(
253
- self,
254
- value: Union[
255
- int,
256
- float,
257
- Sequence[Union[int, float, Sequence[Union[int, float]]]],
258
- "NDArray[np.generic]",
259
- ],
260
- ) -> None:
261
- self["value"] = value
262
-
263
- @value.deleter
264
- def value(self) -> None:
265
- del self["value"]
266
-
267
- def __repr__(self) -> str:
268
- return "FoamFieldFile.BoundaryDictionary"
269
-
270
- def __getitem__(self, key: str) -> Union[FoamFile.Value, _FoamDictionary]:
271
- ret = super().__getitem__(key)
272
- if key == "boundaryField" and isinstance(ret, _FoamDictionary):
273
- ret = FoamFieldFile.BoundariesDictionary(self, [key])
274
- return ret
275
-
276
- def __setitem__(self, key: str, value: Any) -> None:
277
- if key == "internalField":
278
- self._setitem(key, value, assume_field=True)
279
- elif key == "dimensions":
280
- self._setitem(key, value, assume_dimensions=True)
281
- else:
282
- self._setitem(key, value)
283
-
284
- @property
285
- def dimensions(self) -> FoamFile.DimensionSet:
286
- """
287
- Alias of `self["dimensions"]`.
288
- """
289
- ret = self["dimensions"]
290
- if not isinstance(ret, FoamFile.DimensionSet):
291
- raise TypeError("dimensions is not a DimensionSet")
292
- return ret
293
-
294
- @dimensions.setter
295
- def dimensions(
296
- self, value: Union[FoamFile.DimensionSet, Sequence[Union[int, float]]]
297
- ) -> None:
298
- self["dimensions"] = value
299
-
300
- @property
301
- def internal_field(
302
- self,
303
- ) -> Union[
304
- int,
305
- float,
306
- Sequence[Union[int, float, Sequence[Union[int, float]]]],
307
- "NDArray[np.generic]",
308
- ]:
309
- """
310
- Alias of `self["internalField"]`.
311
- """
312
- ret = self["internalField"]
313
- if not isinstance(ret, (int, float, Sequence)):
314
- raise TypeError("internalField is not a field")
315
- return cast(Union[int, float, Sequence[Union[int, float]]], ret)
316
-
317
- @internal_field.setter
318
- def internal_field(
319
- self,
320
- value: Union[
321
- int,
322
- float,
323
- Sequence[Union[int, float, Sequence[Union[int, float]]]],
324
- "NDArray[np.generic]",
325
- ],
326
- ) -> None:
327
- self["internalField"] = value
328
-
329
- @property
330
- def boundary_field(self) -> "FoamFieldFile.BoundariesDictionary":
331
- """
332
- Alias of `self["boundaryField"]`.
333
- """
334
- ret = self["boundaryField"]
335
- if not isinstance(ret, FoamFieldFile.BoundariesDictionary):
336
- assert not isinstance(ret, _FoamDictionary)
337
- raise TypeError("boundaryField is not a dictionary")
338
- return ret
339
-
340
-
341
- _YES = Keyword("yes").set_parse_action(lambda: True)
342
- _NO = Keyword("no").set_parse_action(lambda: False)
343
- _DIMENSIONS = (
344
- Literal("[").suppress() + common.number * 7 + Literal("]").suppress()
345
- ).set_parse_action(lambda tks: FoamFile.DimensionSet(*tks))
346
- _TOKEN = QuotedString('"', unquote_results=False) | Word(
347
- identchars + "$", identbodychars
348
- )
349
- _ITEM = Forward()
350
- _LIST = Opt(
351
- Literal("List") + Literal("<") + common.identifier + Literal(">")
352
- ).suppress() + (
353
- (
354
- Opt(common.integer).suppress()
355
- + Literal("(").suppress()
356
- + Group(_ITEM[...])
357
- + Literal(")").suppress()
358
- )
359
- | (
360
- common.integer + Literal("{").suppress() + _ITEM + Literal("}").suppress()
361
- ).set_parse_action(lambda tks: [tks[1]] * tks[0])
362
- )
363
- _FIELD = (Keyword("uniform").suppress() + _ITEM) | (
364
- Keyword("nonuniform").suppress() + _LIST
365
- )
366
- _DIMENSIONED = (Opt(common.identifier) + _DIMENSIONS + _ITEM).set_parse_action(
367
- lambda tks: FoamFile.Dimensioned(*reversed(tks.as_list()))
368
- )
369
- _ITEM <<= (
370
- _FIELD | _LIST | _DIMENSIONED | _DIMENSIONS | common.number | _YES | _NO | _TOKEN
371
- )
372
-
373
- _TOKENS = (
374
- QuotedString('"', unquote_results=False)
375
- | Word(printables.replace(";", "").replace("{", "").replace("}", ""))
376
- )[2, ...].set_parse_action(lambda tks: " ".join(tks))
377
-
378
- _VALUE = (_ITEM ^ _TOKENS).ignore(c_style_comment).ignore(cpp_style_comment)
379
-
380
-
381
- _UNPARSED_VALUE = (
382
- QuotedString('"', unquote_results=False)
383
- | Word(printables.replace(";", "").replace("{", "").replace("}", ""))
384
- )[...]
385
- _KEYWORD = QuotedString('"', unquote_results=False) | Word(
386
- identchars + "$(,.)", identbodychars + "$(,.)"
387
- )
388
- _DICTIONARY = Forward()
389
- _ENTRY = _KEYWORD + (
390
- (
391
- Located(_UNPARSED_VALUE).set_parse_action(lambda tks: (tks[0], tks[2]))
392
- + Literal(";").suppress()
393
- )
394
- | (Literal("{").suppress() + _DICTIONARY + Literal("}").suppress())
395
- )
396
- _DICTIONARY <<= (
397
- Dict(Group(_ENTRY)[...])
398
- .set_parse_action(lambda tks: {} if not tks else tks)
399
- .ignore(c_style_comment)
400
- .ignore(cpp_style_comment)
401
- .ignore(Literal("#include") + ... + LineEnd()) # type: ignore
402
- )
403
-
404
-
405
- def _serialize_bool(value: Any) -> str:
406
- if value is True:
407
- return "yes"
408
- elif value is False:
409
- return "no"
410
- else:
411
- raise TypeError(f"Not a bool: {type(value)}")
412
-
413
-
414
- def _is_sequence(value: Any) -> bool:
415
- return (
416
- isinstance(value, Sequence)
417
- and not isinstance(value, str)
418
- or numpy
419
- and isinstance(value, np.ndarray)
420
- )
421
-
422
-
423
- def _serialize_list(value: Any) -> str:
424
- if _is_sequence(value):
425
- return f"({' '.join(serialize(v) for v in value)})"
426
- else:
427
- raise TypeError(f"Not a valid sequence: {type(value)}")
428
-
429
-
430
- def _serialize_field(value: Any) -> str:
431
- if _is_sequence(value):
432
- try:
433
- s = _serialize_list(value)
434
- except TypeError:
435
- raise TypeError(f"Not a valid field: {type(value)}") from None
436
- else:
437
- if len(value) < 10:
438
- return f"uniform {s}"
439
- else:
440
- if isinstance(value[0], (int, float)):
441
- kind = "scalar"
442
- elif len(value[0]) == 3:
443
- kind = "vector"
444
- elif len(value[0]) == 6:
445
- kind = "symmTensor"
446
- elif len(value[0]) == 9:
447
- kind = "tensor"
448
- else:
449
- raise TypeError(
450
- f"Unsupported sequence length for field: {len(value[0])}"
451
- )
452
- return f"nonuniform List<{kind}> {len(value)}{s}"
453
- else:
454
- return f"uniform {value}"
455
-
456
-
457
- def _serialize_dimensions(value: Any) -> str:
458
- if _is_sequence(value) and len(value) == 7:
459
- return f"[{' '.join(str(v) for v in value)}]"
460
- else:
461
- raise TypeError(f"Not a valid dimension set: {type(value)}")
462
-
463
-
464
- def _serialize_dimensioned(value: Any) -> str:
465
- if isinstance(value, FoamFile.Dimensioned):
466
- if value.name is not None:
467
- return f"{value.name} {_serialize_dimensions(value.dimensions)} {serialize(value.value)}"
468
- else:
469
- return f"{_serialize_dimensions(value.dimensions)} {serialize(value.value)}"
470
- else:
471
- raise TypeError(f"Not a valid dimensioned value: {type(value)}")
472
-
473
-
474
- def serialize(
475
- value: Any, *, assume_field: bool = False, assume_dimensions: bool = False
476
- ) -> str:
477
- if isinstance(value, FoamFile.DimensionSet) or assume_dimensions:
478
- with suppress(TypeError):
479
- return _serialize_dimensions(value)
480
-
481
- if assume_field:
482
- with suppress(TypeError):
483
- return _serialize_field(value)
484
-
485
- with suppress(TypeError):
486
- return _serialize_dimensioned(value)
487
-
488
- with suppress(TypeError):
489
- return _serialize_list(value)
490
-
491
- with suppress(TypeError):
492
- return _serialize_bool(value)
493
-
494
- return str(value)
@@ -1,10 +0,0 @@
1
- foamlib/__init__.py,sha256=XdOd0DaoULxz-haiaIbfRNQjU3_oX2Rz7ZmKYkng1kQ,241
2
- foamlib/_cases.py,sha256=FL6d2_fCB9KCu9ps8Ur8ITlla3rSFsuvdvMYEXGCBM4,20923
3
- foamlib/_dictionaries.py,sha256=admW5ZhNvmNi6cpnOEEbESoEL5wLeiQa62o9l7ojZ8M,14828
4
- foamlib/_subprocesses.py,sha256=5vqdQvpN_2v4GgDqxi-s88NGhZ6doFxkh0XY89ZWuHA,1926
5
- foamlib/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
- foamlib-0.2.1.dist-info/LICENSE.txt,sha256=5Dte9TUnLZzPRs4NQzl-Jc2-Ljd-t_v0ZR5Ng5r0UsY,35131
7
- foamlib-0.2.1.dist-info/METADATA,sha256=tlM7gkY0jb3U4by5u0O59zbvSw3V8L2l5b0UrYTvMhE,4600
8
- foamlib-0.2.1.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
9
- foamlib-0.2.1.dist-info/top_level.txt,sha256=ZdVYtetXGwPwyfL-WhlhbTFQGAwKX5P_gXxtH9JYFPI,8
10
- foamlib-0.2.1.dist-info/RECORD,,