Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 2 additions & 7 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -151,11 +151,6 @@ dmypy.json
# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
test/
temp/
temp/
*.bak
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
BSD 3-Clause License

Copyright (c) 2023, Entity toolkit
Copyright (c) 2025, Entity development team

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Expand Down
107 changes: 105 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,114 @@
## nt2.py

Python package for visualization and post-processing of the [`Entity`](https://github.com/entity-toolkit/entity) simulation data. For usage, please refer to the [documentation](https://entity-toolkit.github.io/entity/howto/vis/#nt2py). The package is distributed via [`PyPI`](https://pypi.org/project/nt2py/):
Python package for visualization and post-processing of the [`Entity`](https://github.com/entity-toolkit/entity) simulation data. For usage, please refer to the [documentation](https://entity-toolkit.github.io/wiki/getting-started/vis/#nt2py). The package is distributed via [`PyPI`](https://pypi.org/project/nt2py/):

```sh
pip install nt2py
```

### Usage

The Library works both with single-file output as well as with separate files. In either case, the location of the data is passed via `path` keyword argument.

```python
import nt2

data = nt2.Data(path="path/to/data")
# example:
# data = nt2.Data(path="path/to/shock.h5") : for single-file
# data = nt2.Data(path="path/to/shock") : for multi-file
```

The data is stored in specialized containers which can be accessed via corresponding attributes:

```python
data.fields # < xr.Dataset
data.particles # < dict[int : xr.Dataset]
data.spectra # < xr.Dataset
```

#### Examples

Plot a field (in cartesian space) at a specific time (or output step):

```python
data.fields.Ex.sel(t=10.0, method="nearest").plot() # time ~ 10
data.fields.Ex.isel(t=5).plot() # output step = 5
```

Plot a slice or time-averaged field quantities:

```python
data.fields.Bz.mean("t").plot()
data.fields.Bz.sel(t=10.0, x=0.5, method="nearest").plot()
```

Plot in spherical coordinates (+ combine several fields):

```python
e_dot_b = (data.fields.Er * data.fields.Br +\
data.fields.Eth * data.fields.Bth +\
data.fields.Eph * data.fields.Bph)
bsqr = data.fields.Br**2 + data.fields.Bth**2 + data.fields.Bph**2
# only plot radial extent of up to 10
(e_dot_b / bsqr).sel(t=50.0, method="nearest").sel(r=slice(None, 10)).polar.pcolor()
```

You can also quickly plot the fields at a specific time using the handy `.inspect` accessor:

```python
data.fields\
.sel(t=3.0, method="nearest")\
.sel(x=slice(-0.2, 0.2))\
.inspect.plot(only_fields=["E", "B"])
# Hint: use `<...>.plot?` to see all options
```

Or if no time is specified, it will create a quick movie (need to also provide a `name` in that case):

```python
data.fields\
.sel(x=slice(-0.2, 0.2))\
.inspect.plot(name="inspect", only_fields=["E", "B", "N"])
```

You can also create a movie of a single field quantity (can be custom):

```python
(data.fields.Ex * data.fields.Bx).sel(x=slice(None, 0.2)).movie.plot(name="ExBx", vmin=-0.01, vmax=0.01, cmap="BrBG")
```

You may also combine different quantities and plots (e.g., fields & particles) to produce a more customized movie:

```python
def plot(t, data):
fig, ax = mpl.pyplot.subplots()
data.fields.Ex.sel(t=t, method="nearest").sel(x=slice(None, 0.2)).plot(
ax=ax, vmin=-0.001, vmax=0.001, cmap="BrBG"
)
for sp in range(1, 3):
ax.scatter(
data.particles[sp].sel(t=t, method="nearest").x,
data.particles[sp].sel(t=t, method="nearest").y,
c="r" if sp == 1 else "b",
)
ax.set_aspect(1)
data.makeMovie(plot)
```

> If using Jupyter notebook, you can quickly preview the loaded metadata by simply running a cell with just `data` in it (or in regular python, by doing `print(data)`).

### Dashboard

Support for the dask dashboard is still in beta, but you can access it by first launching the dashboard client:

```python
import nt2
nt2.Dashboard()
```

This will output the port where the dashboard server is running, e.g., `Dashboard: http://127.0.0.1:8787/status`. Click on it (or enter in your browser) to open the dashboard.

### Features

1. Lazy loading and parallel processing of the simulation data with [`dask`](https://dask.org/).
Expand All @@ -16,4 +119,4 @@ pip install nt2py

- [ ] Unit tests
- [ ] Plugins for other simulation data formats
- [ ] Usage examples
- [x] Usage examples
Binary file added dist/nt2py-0.5.0-py3-none-any.whl
Binary file not shown.
Binary file added dist/nt2py-0.5.0.tar.gz
Binary file not shown.
5 changes: 4 additions & 1 deletion nt2/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
__version__ = "0.4.1"
__version__ = "0.5.0"

from nt2.data import Data as Data
from nt2.dashboard import Dashboard as Dashboard
Empty file added nt2/containers/__init__.py
Empty file.
158 changes: 158 additions & 0 deletions nt2/containers/container.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
import os
import h5py
import numpy as np
from typing import Any


def _read_attribs_SingleFile(file: h5py.File):
attribs = {}
for k in file.attrs.keys():
attr = file.attrs[k]
if type(attr) is bytes or type(attr) is np.bytes_:
attribs[k] = attr.decode("UTF-8")
else:
attribs[k] = attr
return attribs


class Container:
"""
* * * * Container * * * *

Parent class for all data containers.

Args
----
path : str
The path to the data.

Kwargs
------
single_file : bool, optional
Whether the data is stored in a single file. Default is False.

pickle : bool, optional
Whether to use pickle for reading the data. Default is True.

greek : bool, optional
Whether to use Greek letters for the spherical coordinates. Default is False.

dask_props : dict, optional
Additional properties for Dask [NOT IMPLEMENTED]. Default is {}.

Attributes
----------
path : str
The path to the data.

configs : dict
The configuration settings for the data.

metadata : dict
The metadata for the data.

mesh : dict
Coordinate grid of the domain (cell-centered & edges).

master_file : h5py.File
The master file for the data (from which the main attributes are read).

attrs : dict
The attributes of the master file.

Methods
-------
plotGrid(ax, **kwargs)
Plots the gridlines of the domain.

"""

def __init__(
self, path, single_file=False, pickle=True, greek=False, dask_props={}
):
super(Container, self).__init__()

self.configs: dict[str, Any] = {
"single_file": single_file,
"use_pickle": pickle,
"use_greek": greek,
}
self.path = path
self.metadata = {}
self.mesh = None
if self.configs["single_file"]:
try:
self.master_file: h5py.File | None = h5py.File(self.path, "r")
except OSError:
raise OSError(f"Could not open file {self.path}")
else:
field_path = os.path.join(self.path, "fields")
file = os.path.join(field_path, os.listdir(field_path)[0])
try:
self.master_file: h5py.File | None = h5py.File(file, "r")
except OSError:
raise OSError(f"Could not open file {file}")

self.attrs = _read_attribs_SingleFile(self.master_file)

self.configs["ngh"] = int(self.master_file.attrs.get("NGhosts", 0))
self.configs["layout"] = (
"right" if self.master_file.attrs.get("LayoutRight", 1) == 1 else "left"
)
self.configs["dimension"] = int(self.master_file.attrs.get("Dimension", 1))
self.configs["coordinates"] = self.master_file.attrs.get(
"Coordinates", b"cart"
).decode("UTF-8")
if self.configs["coordinates"] == "qsph":
self.configs["coordinates"] = "sph"

if not self.configs["single_file"]:
self.master_file.close()
self.master_file = None

def __del__(self):
if self.master_file is not None:
self.master_file.close()

def plotGrid(self, ax, **kwargs):
from matplotlib import patches

xlim, ylim = ax.get_xlim(), ax.get_ylim()
options = {
"lw": 1,
"color": "k",
"ls": "-",
}
options.update(kwargs)

if self.configs["coordinates"] == "cart":
for x in self.attrs["X1"]:
ax.plot([x, x], [self.attrs["X2Min"], self.attrs["X2Max"]], **options)
for y in self.attrs["X2"]:
ax.plot([self.attrs["X1Min"], self.attrs["X1Max"]], [y, y], **options)
else:
for r in self.attrs["X1"]:
ax.add_patch(
patches.Arc(
(0, 0),
2 * r,
2 * r,
theta1=-90,
theta2=90,
fill=False,
**options,
)
)
for th in self.attrs["X2"]:
ax.plot(
[
self.attrs["X1Min"] * np.sin(th),
self.attrs["X1Max"] * np.sin(th),
],
[
self.attrs["X1Min"] * np.cos(th),
self.attrs["X1Max"] * np.cos(th),
],
**options,
)
ax.set(xlim=xlim, ylim=ylim)
Loading