Commit 5b798ff8 authored by Simeon Doetsch's avatar Simeon Doetsch

Added reading of definitions.h

Fixed bugs with getattribute and __str__/__repr__
parent a5d3ed71
......@@ -16,7 +16,7 @@ class Grid:
self.mappings = {}
self.mappings_tex = {}
self.read_gridfile(gridfile)
def set_coordinate_system(self, coordinates, mappings={}, mappings_tex={}):
self.coordinates = coordinates
self.mappings = mappings
......@@ -44,7 +44,7 @@ class Grid:
data = np.fromfile(gf, sep=' ', count=dim*3).reshape(-1, 3)
# calculate center of cell, and difference between cells
x.append((np.sum(data[:, 1:], axis=1)/2, data[:, 2] - data[:, 1]))
# save in grid datastructure
for i, xn in enumerate(x, start=1):
setattr(self, f"x{i}", xn[0])
......@@ -64,13 +64,13 @@ class Grid:
def mesh(self):
return generate_coordinate_mesh(self.coordinates, self.x1, self.x2)
def __getattr__(self, name):
try:
return object.__getattribute__(self, self.mappings[name])
except KeyError:
raise AttributeError
def __str__(self):
return f"PLUTO Grid, Dimensions {self.dims}"
__repr__ = __str__
......@@ -79,7 +79,7 @@ class Grid:
class SimulationMetadata:
def __init__(self, path, format) -> None:
self.read_vars(path, format)
def read_vars(self, path, format) -> None:
"""Read simulation step data and written variables"""
with open(path, 'r') as f:
......@@ -207,32 +207,22 @@ class Definitions_h(OrderedDict):
def __init__(self, path: str):
super().__init__()
self.path = path
self.base = OrderedDict()
self.phys_dep = OrderedDict()
self.parse()
# self.general = OrderedDict()
# self.physics_dep = OrderedDict()
# self.userdef = OrderedDict()
## TODO
# def _parse_def(self, txt):
# if not line:
# continue
# segments = line.split()
# if segments[0] == "#define":
# return segments[1].lower(), segments[2].lower()
def parse(self, txt: str=None) -> None:
if txt is None:
with open(self.path, 'r') as f:
lines = [l.strip() for l in f.readlines()]
else:
lines = [l.strip() for l in txt.split("\n")]
with open(self.path, 'r') as f:
lines = [l.strip() for l in f.readlines()]
for line in lines:
key, value = _parse_def(line)
if key in self.base_opt:
self.base[key], value
elif key in self.physics_dep[self.base['physics']]:
self.phys_dep[key] = value
if not line:
continue
segments = line.split()
if segments[0] == "#define":
self[segments[1].lower()] = segments[2].lower()
def __getitem__(self, key):
return super().__getitem__(key.lower())
def __setitem__(self, key, value):
super().__setitem__(key.lower(), value)
......@@ -23,7 +23,7 @@ class PlutoData(object):
self.file_mode = simulation.metadata.file_mode
self.wdir, self.grid, self.vars = simulation.data_dir, simulation.grid, simulation.vars
self.n, self.t, self.dt, self.nstep = n, simulation.t[n], simulation.dt[n], simulation.nstep[n]
self.data = {}
......@@ -46,7 +46,6 @@ class PlutoData(object):
if name in getattribute(self, 'vars'):
getattribute(self, '_load_var')(name)
return data[name]
# simulation
try:
return getattr(getattribute(self, 'simulation'), name)
......@@ -90,7 +89,7 @@ class PlutoData(object):
return latex_map[coord]
except KeyError:
return coord
def plot(self, var=None, **kwargs):
if var is None:
var = self.vars[0]
......@@ -99,19 +98,18 @@ class PlutoData(object):
var = getattr(self, var)
else:
varname = None
return plot(var, self.grid, label=f"${self.grid.mappings_tex.get(varname, varname)}$", **kwargs)
def __str__(self) -> None:
return f"""PlutoData, wdir: '{self.wdir}'
resolution: {self.dims}, {self.coordinate_system} coordinates
resolution: {self.dims}, {self.grid.coordinates} coordinates
file nr: {self.n}, time: {self.t}, simulation step: {self.nstep}
Variables: {self.vars}"""
def __repr__(self) -> None:
return f"PlutoData({self.n}, wdir='{self.wdir}'" + \
(f", coordinates='{self.coordinate_system}'" if self.coordinate_system != 'cartesian' else "") + ")"
return f"PlutoData({self.n}, wdir='{self.wdir}', coordinates='{self.grid.coordinates}')"
def __dir__(self) -> list:
return object.__dir__(self) + self.vars + list(self.grid.keys())
......@@ -55,7 +55,7 @@ class Simulation:
self.vars = self.metadata.vars
if coordinates is None:
coordinates = 'cartesian'
coordinates = self.definitions['geometry']
self.grid.set_coordinate_system(coordinates,
mappings=generate_coord_mapping(coordinates),
......@@ -71,30 +71,32 @@ class Simulation:
except AttributeError:
self._ini = Pluto_ini(join(self.sim_dir, 'pluto.ini'))
return self._ini
@property
def definitions(self):
try:
return self._definitions
except AttributeError:
self._definitions = Definitions_h(join(self.sim_dir, 'definitions.h'))
return self._definitions
def __getattr__(self, name):
metadata = object.__getattribute__(self, 'metadata')
getattribute = object.__getattribute__
# metadata
try:
return getattr(metadata, name)
return getattr(getattribute(self, 'metadata'), name)
except:
pass
# grid
grid = object.__getattribute__(self, 'grid')
grid = getattribute(self, 'grid')
try:
return getattr(grid, name)
except AttributeError:
pass
try:
return getattr(grid, self.mappings[name])
return getattr(grid, getattribute(self, 'mappings')[name])
except KeyError:
pass
......@@ -107,7 +109,7 @@ class Simulation:
raise AttributeError(f"{type(self)} has no attribute '{name}'")
def _index(self, key: int) -> int:
"""Check if index is in range and implements negative indexing"""
"""Checks if index is in range and implements negative indexing"""
if not isinstance(key, int):
raise IndexError("Data index has to be int")
elif key >= self.n:
......@@ -167,7 +169,6 @@ class Simulation:
for i, d in enumerate(self):
result[i] = func(d)
def reduce_parallel(self, func):
with multiprocessing.Pool() as p:
return np.array(p.map(func, self.iter()))
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment