-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathraw.py
More file actions
244 lines (188 loc) · 7.65 KB
/
Copy pathraw.py
File metadata and controls
244 lines (188 loc) · 7.65 KB
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
233
234
235
236
237
238
239
240
241
242
243
244
from pathlib import Path
import typing
import numpy as np
import logging
import struct
from datetime import datetime, timedelta
from functools import lru_cache
LSP = 7
@lru_cache()
def get_simsize(fn: Path) -> tuple:
"""
get simulation dimensions from simsize.dat
in the future, this would be in the .h5 HDF5 output.
Parameters
----------
fn: pathlib.Path
filepath to simsize.dat
Returns
-------
size: tuple of int, int, int
3 integers telling simulation grid size
"""
fn = Path(fn).expanduser()
if fn.stat().st_size != 12:
raise ValueError(f"{fn} is not expected 12 bytes long")
return struct.unpack("III", fn.open("rb").read(12))
def readgrid(fn: Path) -> typing.Dict[str, np.ndarray]:
"""
get simulation dimensions
in the future, this would be in the .h5 HDF5 output.
Parameters
----------
fn: pathlib.Path
filepath to simgrid.dat
Returns
-------
grid: dict
grid parameters
"""
lxs = get_simsize(fn.parent / "simsize.dat")
lgridghost = (lxs[0] + 4) * (lxs[1] + 4) * (lxs[2] + 4)
gridsizeghost = [lxs[0] + 4, lxs[1] + 4, lxs[2] + 4]
grid: typing.Dict[str, typing.Any] = {"lx": lxs}
if not fn.is_file():
logging.error(f"{fn} grid file is not present. Will try to load rest of data.")
return grid
with fn.open("r") as f:
read = np.fromfile
for i in (1, 2, 3):
grid[f"x{i}"] = read(f, np.float64, lxs[i - 1] + 4)
grid[f"x{i}i"] = read(f, np.float64, lxs[i - 1] + 1)
grid[f"dx{i}b"] = read(f, np.float64, lxs[i - 1] + 3)
grid[f"dx{i}h"] = read(f, np.float64, lxs[i - 1])
for i in (1, 2, 3):
grid[f"h{i}"] = read(f, np.float64, lgridghost).reshape(gridsizeghost)
L = [lxs[0] + 1, lxs[1], lxs[2]]
for i in (1, 2, 3):
grid[f"h{i}x1i"] = read(f, np.float64, np.prod(L)).reshape(L)
L = [lxs[0], lxs[1] + 1, lxs[2]]
for i in (1, 2, 3):
grid[f"h{i}x2i"] = read(f, np.float64, np.prod(L)).reshape(L)
L = [lxs[0], lxs[1], lxs[2] + 1]
for i in (1, 2, 3):
grid[f"h{i}x3i"] = read(f, np.float64, np.prod(L)).reshape(L)
for i in (1, 2, 3):
grid[f"gx{i}"] = read(f, np.float64, np.prod(lxs)).reshape(lxs)
for k in ("alt", "glat", "glon", "Bmag"):
grid[k] = read(f, np.float64, np.prod(lxs)).reshape(lxs)
grid["Bincl"] = read(f, np.float64, lxs[1] * lxs[2]).reshape(lxs[1:])
grid["nullpts"] = read(f, np.float64, np.prod(lxs)).reshape(lxs)
if f.tell() == fn.stat().st_size: # not EOF
return grid
L = [lxs[0], lxs[1], lxs[2], 3]
for i in (1, 2, 3):
grid[f"e{i}"] = read(f, np.float64, np.prod(L)).reshape(L)
for k in ("er", "etheta", "ephi"):
grid[k] = read(f, np.float64, np.prod(L)).reshape(L)
for k in ("r", "theta", "phi"):
grid[k] = read(f, np.float64, np.prod(lxs)).reshape(lxs)
if f.tell() == fn.stat().st_size: # not EOF
return grid
for k in ("x", "y", "z"):
grid[k] = read(f, np.float64, np.prod(lxs)).reshape(lxs)
return grid
def load_Efield(fn: Path) -> typing.Dict[str, np.ndarray]:
"""
load Efield_inputs files that contain input electric field in V/m
"""
read = np.fromfile
E: typing.Dict[str, np.ndarray] = {}
sizefn = fn.parent / "simsize.dat" # NOT the whole sim simsize.dat
with sizefn.open("r") as f:
E["Nlon"], E["Nlat"] = read(f, np.int32, 2)
lxs = (0, E["Nlon"], E["Nlat"])
gridfn = fn.parent / "simgrid.dat" # NOT the whole sim simgrid.dat
with gridfn.open("r") as f:
E["mlon"] = read(f, np.float64, E["Nlon"])
E["mlat"] = read(f, np.float64, E["Nlat"])
with fn.open("r") as f:
E["flagdirich"] = read(f, np.int32, 1)
for p in ("Exit", "Eyit", "Vminx1it", "Vmaxx1it"):
E[p] = read2D(f, lxs)
for p in ("Vminx2ist", "Vmaxx2ist"):
E[p] = read(f, np.float64, E["Nlat"])
for p in ("Vminx3ist", "Vmaxx3ist"):
E[p] = read(f, np.float64, E["Nlon"])
return E
def loadframe3d_curv(fn: Path, lxs: typing.Sequence[int]) -> typing.Dict[str, typing.Any]:
"""
end users should normally use loadframe() instead
Parameters
----------
fn: pathlib.Path
filename of this timestep of simulation output
lxs: list of int
array dimension
"""
# grid = readgrid(fn.parent / "inputs/simgrid.dat")
# dat = xarray.Dataset(
# coords={"x1": grid["x1"][2:-2], "x2": grid["x2"][2:-2], "x3": grid["x3"][2:-2]}
# )
dat: typing.Dict[str, typing.Any] = {}
with fn.open("r") as f:
dat["time"] = read_time(f)
ns = read4D(f, LSP, lxs)
dat["ne"] = (("x1", "x2", "x3"), ns[:, :, :, LSP - 1])
vs1 = read4D(f, LSP, lxs)
dat["v1"] = (("x1", "x2", "x3"), (ns[:, :, :, :6] * vs1[:, :, :, :6]).sum(axis=3) / dat["ne"][1])
Ts = read4D(f, LSP, lxs)
dat["Ti"] = (("x1", "x2", "x3"), (ns[:, :, :, :6] * Ts[:, :, :, :6]).sum(axis=3) / dat["ne"][1])
dat["Te"] = (("x1", "x2", "x3"), Ts[:, :, :, LSP - 1].squeeze())
for p in ("J1", "J2", "J3", "v2", "v3"):
dat[p] = [("x1", "x2", "x3"), read3D(f, lxs)]
dat["Phitop"] = [("x2", "x3"), read2D(f, lxs)]
return dat
def loadframe3d_curvavg(fn: Path, lxs: typing.Sequence[int]) -> typing.Dict[str, typing.Any]:
"""
end users should normally use loadframe() instead
Parameters
----------
fn: pathlib.Path
filename of this timestep of simulation output
lxs: list of int
array dimension
"""
# grid = readgrid(fn.parent / "inputs/simgrid.dat")
# dat = xarray.Dataset(
# coords={"x1": grid["x1"][2:-2], "x2": grid["x2"][2:-2], "x3": grid["x3"][2:-2]}
# )
dat: typing.Dict[str, typing.Any] = {}
with fn.open("r") as f:
dat["time"] = read_time(f)
for p in ("ne", "v1", "Ti", "Te", "J1", "J2", "J3", "v2", "v3"):
dat[p] = [("x1", "x2", "x3"), read3D(f, lxs)]
dat["Phitop"] = [("x2", "x3"), read2D(f, lxs)]
return dat
def read4D(f, lsp: int, lxs: typing.Sequence[int]) -> np.ndarray:
"""
end users should normally use laodframe() instead
"""
if not len(lxs) == 3:
raise ValueError(f"lxs must have 3 elements, you have lxs={lxs}")
return np.fromfile(f, np.float64, np.prod(lxs) * lsp).reshape((*lxs, lsp), order="F")
def read3D(f, lxs: typing.Sequence[int]) -> np.ndarray:
"""
end users should normally use loadframe() instead
"""
if not len(lxs) == 3:
raise ValueError(f"lxs must have 3 elements, you have lxs={lxs}")
return np.fromfile(f, np.float64, np.prod(lxs)).reshape(*lxs, order="F")
def read2D(f, lxs: typing.Sequence[int]) -> np.ndarray:
"""
end users should normally use laodframe() instead
"""
if not len(lxs) == 3:
raise ValueError(f"lxs must have 3 elements, you have lxs={lxs}")
return np.fromfile(f, np.float64, np.prod(lxs[1:])).reshape(*lxs[1:], order="F")
def loadglow_aurmap(f, lxs: typing.Sequence[int], lwave: int) -> typing.Dict[str, typing.Any]:
"""
read the auroral output from GLOW
"""
if not len(lxs) == 3:
raise ValueError(f"lxs must have 3 elements, you have lxs={lxs}")
raw = np.fromfile(f, np.float64, np.prod(lxs[1:]) * lwave).reshape(np.prod(lxs[1:]) * lwave, order="F")
return {"rayleighs": [("wavelength", "x2", "x3"), raw]}
def read_time(f) -> datetime:
t = np.fromfile(f, np.float64, 4)
return datetime(int(t[0]), int(t[1]), int(t[2])) + timedelta(hours=t[3])