emout.utils package

Submodules

emout.utils.eflux module

エネルギーフラックス計算およびピッチ角分類の機能をまとめたライブラリ。 エネルギーは eV 単位で扱う。

emout.utils.eflux.compute_energy_flux_histogram(velocities, probs, mass, energy_bins)[source]
emout.utils.eflux.compute_energy_flux_histograms(velocities, probs, B, mass, energy_bins, pitch_ranges=None)[source]

速度ベクトル群と存在確率配列から、ユーザーが指定するピッチ角区間および方向ごとに エネルギー x エネルギーフラックスのヒストグラムを返す。 エネルギーは eV 単位で計算する。

Parameters:
  • velocities (np.ndarray, shape (N, 3)) – 各粒子の速度ベクトル (m/s)。N はサンプル数。

  • probs (np.ndarray, shape (N,)) – 各速度ベクトルに対応する存在確率や重み。

  • B (np.ndarray, shape (3,)) – 磁場ベクトル (T) または方向ベクトル。

  • mass (float) – 粒子質量 (kg)。

  • energy_bins (int or np.ndarray, shape (M+1,)) –

    • int の場合: numpy.histogram に自動生成を任せる。

    • np.ndarray の場合: ビン境界をそのまま使う。

  • pitch_ranges (list of (a_deg, b_deg, direction) | None) –

    ピッチ角範囲および方向を指定するリスト。各タプルは

    (a_deg, b_deg, direction)

    の形式で、 direction は ‘both’,’pos’,’neg’ のいずれか。 None を指定するとデフォルトの 6 クラス分けを使用。

Returns:

histograms – キーは f”{a_deg:02.0f}-{b_deg:02.0f}_{direction}” の形式。 値は (hist, bin_edges) のタプルで、 - hist: 各ビンにおけるエネルギーフラックス(eV x v x prob)の合計。shape=(M,) - bin_edges: eV 単位のビン境界配列。shape=(M+1,)

Return type:

dict[str, (hist, bin_edges)]

emout.utils.eflux.get_indices_in_pitch_range(velocities, B, a_deg, b_deg, direction='both')[source]

速度ベクトル群と磁場ベクトルから、ピッチ角が [a_deg, b_deg] の範囲にある粒子のインデックスを返す。

Parameters:
  • velocities (np.ndarray, shape (N, 3)) – 各粒子の速度ベクトル (m/s)。N はサンプル数。

  • B (np.ndarray, shape (3,)) – 磁場ベクトル (T) または方向ベクトル。大きさが 0 でないこと。

  • a_deg (float) – ピッチ角の下限 (度)。0° ≤ a_deg < b_deg ≤ 180° の範囲で指定。

  • b_deg (float) – ピッチ角の上限 (度)。

  • direction (str, default='both') –

    ピッチ角の符号方向を指定:
    • ’both’: 内積の符号にかかわらずすべての粒子

    • ’pos’ : 磁場と同方向のみ (v·B > 0)

    • ’neg’ : 磁場と逆方向のみ (v·B < 0)

Returns:

idx – 指定した角度範囲かつ方向条件を満たす粒子のインデックス配列。

Return type:

np.ndarray

emout.utils.eflux.plot_energy_flux(velocities, probs, B, mass, energy_bins, pitch_ranges=None, cmap='plasma')[source]

単一データセットの速度データから、全粒子および指定したピッチ角区間ごとの エネルギー x エネルギーフラックス分布を重ねてプロットする。 エネルギーは eV 単位で計算する。

Parameters:
  • velocities (np.ndarray, shape (N, 3)) – 各粒子の速度ベクトル (m/s)。N はサンプル数。

  • probs (np.ndarray, shape (N,)) – 각速度벡터에 대응하는存在확률や重み。

  • B (np.ndarray, shape (3,)) – 磁場ベクトル (T) または方向ベクトル。

  • mass (float) – 粒子質量 (kg)。

  • energy_bins (int or np.ndarray, shape (M+1,)) –

    • int の場合: numpy.histogram に自動生成を任せる。

    • np.ndarray の場合: ビン境界をそのまま使う。

  • pitch_ranges (list of (a_deg, b_deg, direction) | None) – ピッチ角範囲および方向を指定するリスト。None の場合はデフォルトの 6 クラス分け。

  • cmap (str, default='plasma') – Matplotlib のカラーマップ名。

Returns:

fig, ax – 作成した Figure と Axes を返します。

Return type:

matplotlib.figure.Figure, matplotlib.axes.Axes

emout.utils.eflux.plot_energy_fluxes(velocities_list, x, mass, energy_bins, use_probs=False, probs_list=None, cmap='viridis')[source]

複数系列にわたる速度ベクトルリストから、2D ヒートマップ(x vs Energy、カラースケールはエネルギーフラックス)を描画する。 各系列のエネルギーフラックスは eV x v x (prob) の合計としてヒストグラム化する。

Parameters:
  • velocities_list (list[np.ndarray]) – 長さ T のリストで、要素は shape=(NT, 3) の速度ベクトル配列。

  • x (np.ndarray, shape (T,)) – 各速度リストに対応する x 軸の値 (汎用的に使用可)。

  • mass (float) – 粒子質量 (kg)。

  • energy_bins (int or np.ndarray, shape (M+1,)) –

    • int の場合: numpy.histogram に自動生成を任せる (全系列を通じた energies_eV から)。

    • np.ndarray の場合: ビン境界をそのまま使う。

  • use_probs (bool, default=False) – True の場合、probs_list から各系列ごとに存在確率を読み込んでエネルギーフラックス重みに含める。 False の場合は probs = np.ones(NT) とみなす (eV x v のみを重みとする)。

  • probs_list (list[np.ndarray] | None, default=None) – 長さ T のリストで、要素は shape=(NT,) の存在確率配列。 use_probs=True の場合に必須。

  • cmap (str, default='viridis') – Matplotlib のカラーマップ名。

Returns:

fig, ax – 作成した Figure と Axes を返します。

Return type:

matplotlib.figure.Figure, matplotlib.axes.Axes

emout.utils.emsesinp module

class emout.utils.emsesinp.AttrDict(*args, **kwargs)[source]

Bases: dict

class emout.utils.emsesinp.InpFile(filename=None, convkey=None)[source]

Bases: object

パラメータファイルを管理する.

nmlf90nml.Namelist

Namelistオブジェクト

conversion(unit_from, unit_to)[source]
property dx: float
remove(key, index=None)[source]

パラメータを削除する.

Parameters:
  • key (str) – グループ名(&groupname)またはパラメータ名(parameter)

  • index (int, optional) – 特定のインデックスのみ削除する場合指定する, by default None

save(filename, convkey=None)[source]

パラメータをファイルに保存する.

Parameters:
  • filename (str or Path) – 保存するファイル名

  • convkey (UnitConversionKey, optional) – 単位変換キー, by default None

setlist(group, name, value, start_index=1)[source]

リスト型のパラメータを設定する.

Parameters:
  • group (str) – グループ名(&groupname)

  • name (str) – パラメータ名(parameter)

  • value (type or list(type)) – 設定する値

  • start_index (int, optional) – 設定するインデックス, by default 1

property to_c: float
class emout.utils.emsesinp.UnitConversionKey(dx, to_c)[source]

Bases: object

単位変換キー.

dx

グリッド幅[m]

Type:

float

to_c

EMSES単位系での光速の値

Type:

float

property keytext

単位変換キーの文字列を返す.

Returns:

単位変換キーの文字列

Return type:

str

classmethod load(filename)[source]

ファイルから単位変換キーをロードする.

ファイルの一行目に以下のような文字列が書かれている場合dx, to_cを読み取る. !!key dx=[1.0],to_c=[10000.0]

Parameters:

filename (str or Path) – 単位変換キーを含むファイル.

Returns:

単位変換キー

Return type:

UnitConversionKey or None

emout.utils.group module

class emout.utils.group.Group(objs, attrs=None)[source]

Bases: object

複数のオブジェクトをまとめて処理するクラス.

objs

オブジェクトのリスト

Type:

list[Any]

Notes

以下の関数以外の組み込み関数は管理するオブジェクトに対して実行する. - repr : return ‘Group([objs]) - str : return ‘Group([objs])’ - format : return ‘Group([objs])’ - len : return len(objs) - iter : return iter(objs) - in : return other in objs

Examples

以下のように複数のオブジェクトをまとめて処理することができる.

>>> group = Group([[1, 2], [3, 4]])
>>> print(group)
Group([[1, 2], [3, 4]])
>>> print(group[0])
Group([1, 3])
>>> group.append(5)
>>> print(group)
Group([[1, 2, 5], [3, 4, 5]])
filter(predicate)[source]

オブジェクトのうち関数が真を返すもののみで新しいグループを生成する.

Parameters:

predicate (Callable[Any, bool]) – フィルタ関数

Returns:

新しいグループ

Return type:

Group

Examples

>>> group = Group([1, 2, 3])
>>> group.filter(lambda n: n <= 2)
Group([1, 2])
foreach(callable)[source]

すべてのオブジェクトに対して関数を適用する.

Parameters:

callable (Callable[Any, ]) – 適用する関数

Examples

>>> group = Group([1, 2, 3])
>>> group.foreach(print)
1
2
3
map(callable)[source]

すべてのオブジェクトに対して関数を適用し、新しいグループを生成する.

Parameters:

callable (Callable[Any, Any]) – 適用する関数

Returns:

新しいグループ

Return type:

Group

Examples

>>> group = Group([1, 2, 3])
>>> group.map(lambda n: n * 2)
Group([2, 4, 6])

emout.utils.poisson module

class emout.utils.poisson.DirichletPoissonBoundary(axis, boundary_values=(0.0, 0.0))[source]

Bases: PoissonBoundary

correct_boundary_values(phi)[source]
Return type:

None

property fft_backward: Callable[[ndarray], ndarray]
property fft_forward: Callable[[ndarray], ndarray]
get_target_slice()[source]
Return type:

slice

modified_wave_number(k, n)[source]
Return type:

float

transpose_boundary_values(rho_target, dx)[source]
Return type:

None

class emout.utils.poisson.FFT3d(forwards, backwards)[source]

Bases: object

backward(data3d)[source]
Return type:

ndarray

forward(data3d)[source]
Return type:

ndarray

class emout.utils.poisson.NeumannPoissonBoundary(axis, boundary_values=(0.0, 0.0))[source]

Bases: PoissonBoundary

correct_boundary_values(phi)[source]
Return type:

None

property fft_backward: Callable[[ndarray], ndarray]
property fft_forward: Callable[[ndarray], ndarray]
get_target_slice()[source]
Return type:

slice

modified_wave_number(k, n)[source]
Return type:

float

transpose_boundary_values(rho_target, dx)[source]
Return type:

None

class emout.utils.poisson.PeriodicPoissonBoundary(axis, boundary_values=(0.0, 0.0))[source]

Bases: PoissonBoundary

correct_boundary_values(phi)[source]
Return type:

None

property fft_backward: Callable[[ndarray], ndarray]
property fft_forward: Callable[[ndarray], ndarray]
get_target_slice()[source]
Return type:

slice

modified_wave_number(k, n)[source]
Return type:

float

transpose_boundary_values(rho_target, dx)[source]
Return type:

None

class emout.utils.poisson.PoissonBoundary(axis, boundary_values=(0.0, 0.0))[source]

Bases: object

property axis: int
property boundary_values: Tuple[float]
abstractmethod correct_boundary_values(phi)[source]
Return type:

None

abstract property fft_backward: Callable[[ndarray], ndarray]
abstract property fft_forward: Callable[[ndarray], ndarray]
abstractmethod get_target_slice()[source]
Return type:

slice

abstractmethod modified_wave_number(k, n)[source]
Return type:

float

abstractmethod transpose_boundary_values(rho_target, dx)[source]
Return type:

None

emout.utils.poisson.poisson(rho, dx, boundary_types=['periodic', 'periodic', 'periodic'], boundary_values=[(0.0, 0.0), (0.0, 0.0), (0.0, 0.0)], btypes=None, epsilon_0=8.8541878188e-12)[source]

Solve Poisson’s equation with FFT.

Parameters:
  • rho (np.ndarray) – 3-dimentional array of the charge density [C/m^3]. The shape is (nz+1, ny+1, nx+1).

  • boundary_types (List[str] of {'periodic', 'dirichlet', 'neumann'},) – the boundary condition types, by default [‘periodic’, ‘periodic’, ‘periodic’]

  • boundary_values (List[Tuple[float]]) – the boundary values [(x-lower, x-upper), (y-lower, y-upper), (z-lower, z-upper)], by default [(0., 0.), (0., 0.), (0., 0.)]

  • btypes (str) – string consisting of prefixes of boundary conditions, by default None. If this is set, it takes precedence over boundary_types.

  • dx (float, optional) – the grid width [m], by default 1.0

  • epsilon_0 (_type_, optional) – the electric constant (vacuum permittivity) [F/m], by default cn.epsilon_0

Returns:

3-dimentional of the potential [V].

Return type:

np.ndarray

emout.utils.units module

class emout.utils.units.UnitTranslator(from_unit, to_unit, name=None, unit=None)[source]

Bases: object

単位変換器.

from_unit

変換前の値

Type:

float

to_unit

変換後の値

Type:

float

ratio

変換係数 (変換後 = 変換係数 * 変換前)

Type:

float

name

単位の名前(例: “Mass”, “Frequency”)

Type:

str or None

unit

単位(例: “kg”, “Hz”)

Type:

str or None

reverse(value)[source]

単位逆変換を行う.

Parameters:

value (float) – 変換後の値

Returns:

変換前の値

Return type:

float

set_name(name, unit=None)[source]

名前を設定する.

Parameters:
  • name (str) – 名前

  • unit (str) – 単位

Returns:

self

Return type:

UnitTranslator

trans(value, reverse=False)[source]

単位変換を行う.

Parameters:
  • value (float) – 変換前の値(reverse=Trueの場合変換後の値)

  • reverse (bool, optional) – 逆変換を行う場合True, by default False

Returns:

変換後の値(reverse=Trueの場合変換前の値)

Return type:

float

class emout.utils.units.Units(dx, to_c)[source]

Bases: object

EMSES用の単位変換器を管理する.

SI単位系からEMSES単位系への変換を行う.

B

Unit translator for Magnetic flux density [T]

C

Unit translator for Capacitance [F]

E

Unit translator for Electric field [V/m]

EC

Unit translator for Electric conductivity [S/m]

F

Unit translator for Force [N]

G

Unit translator for Conductance [S]

H

Unit translator for Magnetic field [A/m]

J

Unit translator for Current density [A/m^2]

L

Unit translator for Inductance [H]

N

Unit translator for Flux [/m^2s]

P

Unit translator for Power [W]

R

Unit translator for Resistance [Ω]

T

Unit translator for Temperature [K]

W

Unit translator for Energy [J]

a

Unit translator for Acceleration [m/s^2]

c

Unit translator for Light Speed [m/s]

dx

Grid length [m]

e

Unit translator for Napiers constant []

e0

Unit translator for FS-Permttivity [F/m]

eps

Unit translator for Permittivity [F/m]

f

Unit translator for Frequency [Hz]

i

Unit translator for Current [A]

kB

Unit translator for Boltzmann constant [J/K]

length

Unit translator for Sim-to-Real length ratio [m]

m

Unit translator for Mass [kg]

m0

Unit translator for FS-Permeablity [N/A^2]

me

Unit translator for Electron mass [kg]

mi

Unit translator for Proton mass [kg]

mu

Unit translator for Permiability [H/m]

n

Unit translator for Number density [/m^3]

phi

Unit translator for Potential [V]

pi

Unit translator for Circular constant []

q

Unit translator for Charge [C]

q_m

Unit translator for Charge-to-mass ratio [C/kg]

qe

Unit translator for Elementary charge [C]

qe_me

Unit translator for Electron charge-to-mass ratio [C/kg]

rho

Unit translator for Charge density [C/m^3]

t

Unit translator for Time [s]

to_c

Light speed in EMSES

translators()[source]

変換器のリストを返す.

Returns:

変換器のリスト

Return type:

list(UnitTranslator)

v

Unit translator for Velocity [m/s]

w

Unit translator for Energy density [J/m^3]

emout.utils.util module

class emout.utils.util.DataFileInfo(filename)[source]

Bases: object

データファイル情報を管理するクラス.

property abspath

ファイルの絶対パスを返す.

Returns:

ファイルの絶対パス

Return type:

Path

property directory

ディレクトリの絶対パスを返す.

Returns:

ディレクトリの絶対パス

Return type:

Path

property filename

ファイル名を返す.

Returns:

ファイル名

Return type:

Path

class emout.utils.util.QuantizedPillowWriter(fps=5, metadata=None, codec=None, bitrate=None)[source]

Bases: PillowWriter

色数を256としたPillowWriterラッパークラス.

grab_frame(**savefig_kwargs)[source]

Grab the image information from the figure and save as a movie frame.

All keyword arguments in savefig_kwargs are passed on to the ~.Figure.savefig call that saves the figure. However, several keyword arguments that are supported by ~.Figure.savefig may not be passed as they are controlled by the MovieWriter:

  • dpi, bbox_inches: These may not be passed because each frame of the

    animation much be exactly the same size in pixels.

  • format: This is controlled by the MovieWriter.

class emout.utils.util.RegexDict[source]

Bases: dict

正規表現をキーとする辞書クラス.

get(key, default=None)[source]

Return the value for key if key is in the dictionary, else default.

emout.utils.util.hole_mask(inp, reverse=False)[source]
emout.utils.util.interp2d(mesh, n, **kwargs)[source]
emout.utils.util.range_with_slice(slice_obj, maxlen)[source]

スライスを引数とするrange関数.

Parameters:
  • slice_obj (slice) – スライスオブジェクト

  • maxlen (int) – 最大数(スライスの値が負である場合に用いる)

Returns:

rangeジェネレータ

Return type:

generator

emout.utils.util.slice2tuple(slice_obj)[source]

スライスオブジェクトをタプルに変換する.

Parameters:

slice_obj (slice) – スライスオブジェクト

Returns:

(start, stop, step) – スライス情報をもつタプル

Return type:

int

Module contents