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
16 changes: 8 additions & 8 deletions pyphare/pyphare/core/box.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,26 +70,26 @@ def copy(self):


class nDBox(Box):
def __init__(self, dim, l, u):
def __init__(self, dim, lower, upper):
def _get(self, p):
return np.asarray([p] * dim)

super().__init__(_get(dim, l), _get(dim, u))
super().__init__(_get(dim, lower), _get(dim, upper))


class Box1D(nDBox):
def __init__(self, l, u):
super().__init__(1, l, u)
def __init__(self, lower, upper):
super().__init__(1, lower, upper)


class Box2D(nDBox):
def __init__(self, l, u):
super().__init__(2, l, u)
def __init__(self, lower, upper):
super().__init__(2, lower, upper)


class Box3D(nDBox):
def __init__(self, l, u):
super().__init__(3, l, u)
def __init__(self, lower, upper):
super().__init__(3, lower, upper)


def refine(box, ratio):
Expand Down
141 changes: 141 additions & 0 deletions pyphare/pyphare/core/operators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
import numpy as np

from pyphare.pharesee.hierarchy import ScalarField, VectorField
from pyphare.pharesee.hierarchy.hierarchy_utils import compute_hier_from
from pyphare.pharesee.hierarchy.hierarchy_utils import rename


def _compute_dot_product(patch_datas, **kwargs):
ref_name = next(iter(patch_datas.keys()))

dset = (
patch_datas["left_x"][:] * patch_datas["right_x"][:]
+ patch_datas["left_y"][:] * patch_datas["right_y"][:]
+ patch_datas["left_z"][:] * patch_datas["right_z"][:]
)

return (
{"name": "value", "data": dset, "centering": patch_datas[ref_name].centerings},
)


def _compute_sqrt(patch_datas, **kwargs):
ref_name = next(iter(patch_datas.keys()))

dset = np.sqrt(patch_datas["value"][:])

return (
{"name": "value", "data": dset, "centering": patch_datas[ref_name].centerings},
)


def _compute_cross_product(patch_datas, **kwargs):
ref_name = next(iter(patch_datas.keys()))

dset_x = (
patch_datas["left_y"][:] * patch_datas["right_z"][:]
- patch_datas["left_z"][:] * patch_datas["right_y"][:]
)
dset_y = (
patch_datas["left_z"][:] * patch_datas["right_x"][:]
- patch_datas["left_x"][:] * patch_datas["right_z"][:]
)
dset_z = (
patch_datas["left_x"][:] * patch_datas["right_y"][:]
- patch_datas["left_y"][:] * patch_datas["right_x"][:]
)

return (
{"name": "x", "data": dset_x, "centering": patch_datas[ref_name].centerings},
{"name": "y", "data": dset_y, "centering": patch_datas[ref_name].centerings},
{"name": "z", "data": dset_z, "centering": patch_datas[ref_name].centerings},
)


def _compute_grad(patch_data, **kwargs):
ndim = patch_data["value"].box.ndim
nb_ghosts = kwargs["nb_ghosts"]
ds = patch_data["value"].dataset

ds_shape = list(ds.shape)

ds_x = np.full(ds_shape, np.nan)
ds_y = np.full(ds_shape, np.nan)
ds_z = np.full(ds_shape, np.nan)

grad_ds = np.gradient(ds)
select = tuple([slice(nb_ghosts, -nb_ghosts) for _ in range(ndim)])
if ndim == 2:
ds_x[select] = np.asarray(grad_ds[0][select])
ds_y[select] = np.asarray(grad_ds[1][select])
ds_z[select].fill(0.0) # TODO at 2D, gradient is null in z dir
Comment thread
nicolasaunai marked this conversation as resolved.

else:
raise RuntimeError("dimension not yet implemented")

return (
{"name": "x", "data": ds_x, "centering": patch_data["value"].centerings},
{"name": "y", "data": ds_y, "centering": patch_data["value"].centerings},
{"name": "z", "data": ds_z, "centering": patch_data["value"].centerings},
)
Comment thread
nicolasaunai marked this conversation as resolved.


def dot(hier_left, hier_right, **kwargs):
if isinstance(hier_left, VectorField) and isinstance(hier_right, VectorField):
names_left = ["left_x", "left_y", "left_z"]
names_right = ["right_x", "right_y", "right_z"]

else:
raise RuntimeError("type of hierarchy not yet considered")

hl = rename(hier_left, names_left)
hr = rename(hier_right, names_right)

h = compute_hier_from(
_compute_dot_product,
(hl, hr),
)

return ScalarField(h)


def cross(hier_left, hier_right, **kwargs):
if isinstance(hier_left, VectorField) and isinstance(hier_right, VectorField):
names_left = ["left_x", "left_y", "left_z"]
names_right = ["right_x", "right_y", "right_z"]

else:
raise RuntimeError("type of hierarchy not yet considered")

hl = rename(hier_left, names_left)
hr = rename(hier_right, names_right)

h = compute_hier_from(
_compute_cross_product,
(hl, hr),
)

return VectorField(h)


def sqrt(hier, **kwargs):
h = compute_hier_from(
_compute_sqrt,
hier,
)

return ScalarField(h)


def modulus(hier):
assert isinstance(hier, VectorField)

return sqrt(dot(hier, hier))


def grad(hier, **kwargs):
assert isinstance(hier, ScalarField)
nb_ghosts = list(hier.level(0).patches[0].patch_datas.values())[0].ghosts_nbr[0]
h = compute_hier_from(_compute_grad, hier, nb_ghosts=nb_ghosts)

return VectorField(h)
3 changes: 2 additions & 1 deletion pyphare/pyphare/core/phare_utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,8 @@ def run_cli_cmd(cmd, shell=True, capture_output=True, check=False, print_cmd=Fal


def print_trace():
import sys, traceback
import sys
import traceback

_, _, tb = sys.exc_info()
traceback.print_tb(tb)
Expand Down
2 changes: 1 addition & 1 deletion pyphare/pyphare/cpp/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def cpp_lib(override=None):
return importlib.import_module("pybindlibs.cpp")
try:
return importlib.import_module("pybindlibs.cpp_dbg")
except ImportError as err:
except ImportError:
return importlib.import_module("pybindlibs.cpp")


Expand Down
46 changes: 28 additions & 18 deletions pyphare/pyphare/pharein/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,34 @@
import numpy as np

from pyphare.core.phare_utilities import is_scalar
from .uniform_model import UniformModel
from .maxwellian_fluid_model import MaxwellianFluidModel
from .electron_model import ElectronModel
from .diagnostics import (
FluidDiagnostics,
ElectromagDiagnostics,
ParticleDiagnostics,
MetaDiagnostics,
InfoDiagnostics,
)
from .simulation import (
Simulation,
serialize as serialize_sim,
deserialize as deserialize_sim,
)
from .load_balancer import LoadBalancer

__all__ = [
"UniformModel",
"MaxwellianFluidModel",
"ElectronModel",
"FluidDiagnostics",
"ElectromagDiagnostics",
"ParticleDiagnostics",
"MetaDiagnostics",
"InfoDiagnostics",
"Simulation",
]

# This exists to allow a condition variable for when we are running PHARE from C++ via phare-exe
# It is configured to "True" in pyphare/pyphare/pharein/init.py::get_user_inputs(jobname)
Expand All @@ -29,24 +57,6 @@
sys.path = sys.path + pythonpath


from .uniform_model import UniformModel
from .maxwellian_fluid_model import MaxwellianFluidModel
from .electron_model import ElectronModel
from .diagnostics import (
FluidDiagnostics,
ElectromagDiagnostics,
ParticleDiagnostics,
MetaDiagnostics,
InfoDiagnostics,
)
from .simulation import (
Simulation,
serialize as serialize_sim,
deserialize as deserialize_sim,
)
from .load_balancer import LoadBalancer


def NO_GUI():
"""prevents issues when command line only and no desktop etc"""
import matplotlib as mpl
Expand Down
3 changes: 1 addition & 2 deletions pyphare/pyphare/pharein/diagnostics.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ def __init__(self, name, **kwargs):

self.__extent = None

# if a diag already is registered we just contactenate the timestamps
# if a diag already is registered we just concatenate the timestamps
addIt = True
registered_diags = global_vars.sim.diagnostics
for diagname, diag in registered_diags.items():
Expand Down Expand Up @@ -313,7 +313,6 @@ def __init__(self, **kwargs):
)

def _setSubTypeAttributes(self, **kwargs):

# domain is good default for users who should not worry about what that means
# even less about ghosts...
kwargs["quantity"] = kwargs.get("quantity", "domain")
Expand Down
42 changes: 20 additions & 22 deletions pyphare/pyphare/pharein/examples/job.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,20 @@
#!/usr/bin/env python


from pyphare.pharein import Simulation
from pyphare.pharein import MaxwellianFluidModel
from pyphare.pharein import ElectronModel
from pyphare.pharein import ElectromagDiagnostics
from pyphare.pharein import FluidDiagnostics
from pyphare.pharein import getSimulation
import numpy as np
import pyphare.pharein as ph


# ------------------------------------
# configure the simulation
# ------------------------------------

Simulation(
ph.Simulation(
time_step_nbr=1000, # number of time steps (not specified if time_step and final_time provided)
final_time=1.0, # simulation final time (not specified if time_step and time_step_nbr given)
boundary_types="periodic", # boundary condition, string or tuple, length == len(cell) == len(dl)
cells=80, # integer or tuple length == dimension
dl=0.1, # mesh size of the root level, float or tuple
path="test5" # directory where INI file and diagnostics directories will be
path="test5", # directory where INI file and diagnostics directories will be
Comment thread
nicolasaunai marked this conversation as resolved.
# time_step = 0.005, # simulation time step (not specified if time_step_nbr and final_time given)
# domain_size = 8., # float or tuple, not specified if dl and cells are
# interp_order = 1, # interpolation order, [default = 1] can be 1, 2, 3 or 4
Expand All @@ -36,7 +31,6 @@

# in the following we use the MaxwellianFluidModel

import numpy as np

Te = 0.12

Expand All @@ -46,17 +40,17 @@ def n(x):


def bx(x):
xmax = getSimulation().simulation_domain()[0]
xmax = ph.getSimulation().simulation_domain()[0]
return np.cos(2 * np.pi / xmax * x)


MaxwellianFluidModel(bx=bx, protons={"density": n}, background={})
ph.MaxwellianFluidModel(bx=bx, protons={"density": n}, background={})


ElectronModel(closure="isothermal", Te=Te)
ph.ElectronModel(closure="isothermal", Te=Te)


ElectromagDiagnostics(
ph.ElectromagDiagnostics(
diag_type="E", # available : ("E", "B")
write_every=10,
compute_every=5,
Expand All @@ -66,18 +60,18 @@ def bx(x):
)


FluidDiagnostics(
ph.FluidDiagnostics(
diag_type="density", # choose in (rho_s, flux_s)
write_every=10, # write on disk every x iterations
compute_every=5, # compute diagnostics every x iterations ( x <= write_every)
start_iteration=0, # iteration at which diag is enabled
last_iteration=990, # iteration at which diag is turned off
population_name="protons" # name of the population for which the diagnostics is made
population_name="protons", # name of the population for which the diagnostics is made
# ,path = 'FluidDiagnostics1' # where output files will be written, [default: name]
)


FluidDiagnostics(
ph.FluidDiagnostics(
diag_type="bulkVelocity",
write_every=10,
compute_every=5,
Expand All @@ -86,7 +80,7 @@ def bx(x):
population_name="background",
)

FluidDiagnostics(
ph.FluidDiagnostics(
diag_type="density",
write_every=10,
compute_every=5,
Expand All @@ -95,7 +89,7 @@ def bx(x):
population_name="all",
)

FluidDiagnostics(
ph.FluidDiagnostics(
diag_type="flux",
write_every=10,
compute_every=5,
Expand All @@ -104,9 +98,13 @@ def bx(x):
population_name="background",
)

ElectromagDiagnostics(
diag_type="B", write_every=10, compute_every=5, start_teration=0, last_iteration=990
ph.ElectromagDiagnostics(
diag_type="B",
write_every=10,
compute_every=5,
start_iteration=0,
last_iteration=990,
)

for item in getSimulation().electrons.dict_path():
for item in ph.getSimulation().electrons.dict_path():
print(item[0], item[1])
2 changes: 1 addition & 1 deletion pyphare/pyphare/pharein/maxwellian_fluid_model.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import numpy as np
from pyphare.core import phare_utilities
from pyphare.core.box import Box
from pyphare.core.gridlayout import GridLayout, yee_element_is_primal
from pyphare.core.gridlayout import GridLayout
from pyphare.pharein import global_vars


Expand Down
Loading