-
Notifications
You must be signed in to change notification settings - Fork 1
/
examples.py
232 lines (167 loc) · 5.91 KB
/
examples.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
"""
Examples (:mod:`~lnpy.examples`)
================================
"""
from __future__ import annotations
import json
from dataclasses import asdict, dataclass
from typing import TYPE_CHECKING, TypedDict
import numpy as np
import xarray as xr
from ._compat import resources
# from .lnpiseries import lnPiCollection
from .segment import BuildPhasesBase, PhaseCreator
from .utils import dataset_to_lnpimasked
if TYPE_CHECKING:
from typing import Any, Iterator, Literal, Sequence
from ._typing import MyNDArray
from .lnpidata import lnPiMasked
_ExampleNames = Literal["lj_sub", "lj_sup", "ljmix_sup", "hsmix", "watermof"]
def json_to_dict(basename: str) -> dict[str, Any]:
"""
Load a json file into a dict.
All files names are relative to 'lnpy/data/'
Parameters
----------
basename : string
Name of file to load in 'lnpy/data' directory.
Returns
-------
output : dict
"""
if basename.endswith(".gz"):
import gzip
fopen = gzip.open
else:
fopen = open # type: ignore[assignment]
# path = Path(resources.files("lnpy.data").joinpath(basename))
# with fopen(path, "r") as f: # pyright: ignore[reportCallIssue,reportArgumentType]
# return json.load(f) # type: ignore[no-any-return]
with resources.as_file(
resources.files("lnpy.data").joinpath(basename)
) as path, fopen(path, "r") as f:
return json.load(f) # type: ignore[no-any-return]
class ExampleDict(TypedDict):
"""Example dict"""
lnPi_data: MyNDArray
lnPi_mask: MyNDArray
state_kws: dict[str, Any]
extra_kws: dict[str, Any]
lnz: MyNDArray
def load_example_dict(name: _ExampleNames) -> ExampleDict:
"""
Load a dictionary of data
Parameters
----------
name : {'lj_sub', 'lj_sup', 'ljmix_sup', 'hsmix', 'watermof}
"""
ref = load_example_lnpimasked(name)
return ExampleDict(
lnPi_data=ref.data,
lnPi_mask=ref.mask,
state_kws=ref.state_kws,
extra_kws=ref.extra_kws,
lnz=ref.lnz,
)
def load_example_lnpimasked(name: _ExampleNames) -> lnPiMasked:
"""
Load an example file
Parameters
----------
name : {'lj_sub', 'lj_sup', 'ljmix_sup', 'hsmix', 'watermof}
"""
extensions = {
"lj_sub": "json",
"lj_sup": "json",
"ljmix_sup": "json.gz",
"hsmix": "json.gz",
"watermof": "json",
}
if name not in extensions:
msg = f"{name=} not in {extensions=}"
raise ValueError(msg)
basename = f"{name}_example.{extensions[name]}"
d = json_to_dict(basename)
ds = xr.Dataset.from_dict(d)
return dataset_to_lnpimasked(ds)
@dataclass
class Example:
"""Dataclass to hold example data."""
#: Reference state :class:`~lnpy.lnpidata.lnPiMasked`.
ref: lnPiMasked
#: :class:`~lnpy.segment.PhaseCreator` instance
phase_creator: PhaseCreator
#: Callable to build phases.
build_phases: BuildPhasesBase | None
def to_dict(self) -> dict[str, Any]:
"""Transform class to dictionary."""
return asdict(self)
def unpack(self, keys: list[str] | None = None) -> Iterator[Any]:
"""Unpack keys."""
if keys is None:
keys = ["ref", "phase_creator", "build_phases"]
return (getattr(self, k) for k in keys)
def lj_sup_example() -> Example:
"""Create an :class:`Example` instance for a Lennard-Jones fluid (subcritical)"""
ref = load_example_lnpimasked("lj_sup")
phase_creator = PhaseCreator(
nmax=1,
nmax_peak=1,
ref=ref,
merge_kws={"efac": 0.8},
tag_phases=None,
)
build_phases = phase_creator.build_phases_mu([None])
return Example(ref=ref, phase_creator=phase_creator, build_phases=build_phases)
def tag_phases_single_comp_simple(x: Sequence[lnPiMasked]) -> MyNDArray:
if len(x) > 2:
msg = "bad tag function"
raise ValueError(msg)
argmax0 = np.array([xx.local_argmax()[0] for xx in x])
return np.where(argmax0 <= x[0].shape[0] / 2, 0, 1)
def lj_sub_example() -> Example:
"""Create an :class:`Example` instance for a Lennard-Jones fluid (subcritical)"""
ref = load_example_lnpimasked("lj_sub")
phase_creator = PhaseCreator(
nmax=2,
nmax_peak=4,
ref=ref,
merge_kws={"efac": 0.8},
tag_phases=tag_phases_single_comp_simple,
)
build_phases = phase_creator.build_phases_mu([None])
return Example(ref=ref, phase_creator=phase_creator, build_phases=build_phases)
def ljmix_sup_example() -> Example:
"""Create an :class:`Example` instance for a Lennard-Jones mixture (supercritical)."""
ref = load_example_lnpimasked("ljmix_sup")
phase_creator = PhaseCreator(
nmax=1,
ref=ref,
)
build_phases = phase_creator.build_phases_mu([None])
return Example(ref=ref, phase_creator=phase_creator, build_phases=build_phases)
def hsmix_example() -> Example:
"""Create an :class:`Example` instance for a hard-sphere mixture."""
def tag_phases(x: Sequence[lnPiMasked]) -> MyNDArray:
if len(x) > 2:
msg = "bad tag function"
raise ValueError(msg)
argmax0 = np.array([xx.local_argmax()[0] for xx in x])
return np.where(argmax0 <= x[0].shape[0] / 2, 0, 1)
ref = load_example_lnpimasked("hsmix")
phase_creator = PhaseCreator(
nmax=2, nmax_peak=4, ref=ref, tag_phases=tag_phases, merge_kws={"efac": 0.8}
)
return Example(ref=ref, phase_creator=phase_creator, build_phases=None)
# def watermof_example():
# def tag_phases(x):
# if len(x) > 2:
# raise ValueError("bad tag function")
# argmax0 = np.array([xx.local_argmax()[0] for xx in x])
# return np.where(argmax0 <= x[0].shape[0] / 2, 0, 1)
# ref = load_example_lnpimasked('watermof')
# phase_creator = PhaseCreator(
# nmax=2,
# nmax_peak=10,
# merge_kws={'efac': 0.8}
# )