mewarpx.utils_store package¶
Submodules¶
mewarpx.utils_store.appendablearray module¶
Array type which can be appended to in an efficient way.
- class mewarpx.utils_store.appendablearray.AppendableArray(initlen=1, unitshape=None, typecode=None, autobump=100, initunit=None, aggressivebumping=1.5)[source]¶
Bases:
objectCreates an array which can be appended to in an efficient manner. The object keeps an internal array which is bigger than the actual data. When new data is appended, it is only copied to fill in the extra space. More space is only allocated when that space fills up. This saves both the allocation time, and the time to copy the existing data to the new space. This code was written by David P. Grote for Warp(8/19/99).
- Parameters
initlen (int) – The initial size of the array. The most efficiency is gained when initlen is close to the total expected length.
unitshape (tuple) – The appendable unit can be an array. This gives the shape of the unit. The full shape of the array then would be [n]+unitshape, where n is the number of units appended.
typecode (str) – Typecode of the array. Uses the same default as the standard array creation routines.
autobump (int) – The size of the increment used when additional extra space is needed.
initunit (np.ndarray) – When given, the unitshape and the typecode are taken from it. Also, this unit is make the first unit in the array.
aggressivebumping (float) – Whenever new space is added, autobump will be increased by this factor in an attempt to minimize the number of reallocations. Its new value will be the max of the size of the appended data and this times the old autobump size. A good value is 1.5 - this can greatly reduce the amount of rallocation without a significant amount of wasted space.
Create an instance like so >>> a = AppendableArray(initlen=100,typecode=’d’) Append a single unit like this >>> a.append(7.) or multiple units like this >>> a.append(numpy.ones(5,’d’)) The data can be obtained by directly indexing the instance, like this >>> print a[:4] [ 7., 1., 1., 1.,] will give the first four number appended Other methods include len, data, setautobump, cleardata, reshape
- compressdata(data, whereidx)[source]¶
Takes in data and copies into preallocated array using boolean indexing
- Parameters
data (array) – raw data to be copied
whereidx (boolean array) – must be same size as first index in data
- resetdata(data)[source]¶
Resets the data to be the input values - all of the original data is thrown away. The unit shape of data must be the same.
- reshape(newunitshape)[source]¶
Change the shape of the appendable unit. Can only be used if a unitshape was specified on creation.
- Arguments
- newunitshape (tuple): must have the same number of dimensions as the original
unitshape
mewarpx.utils_store.init_restart_util module¶
Utility functions to start a run from a checkpoint or restart.
- mewarpx.utils_store.init_restart_util.clean_old_checkpoints(checkpoint_directory='diags', checkpoint_prefix='checkpoint', num_to_keep=2)[source]¶
Utility function to remove old checkpoints.
- Parameters
checkpoint_directory (str) – Look in this directory for checkpoint directories. Default is
diags.checkpoint_prefix (str) – Look for a checkpoint directory starting with this prefix to restart from.
num_to_keep (int) – Keep this many of the newest checkpoints. Default 2, so that one being judged corrupt will never ruin all checkpoints.
- mewarpx.utils_store.init_restart_util.get_sorted_checkpoints(checkpoint_directory, checkpoint_prefix)[source]¶
Function to return valid checkpoints for restarting or removing checkpoints.
Also warns if any checkpoints with .old. exist, which shouldn’t in normal workflow.
- Parameters
- Returns
List of checkpoint directory strings, sorted by timestep from earliest to latest.
- Return type
- mewarpx.utils_store.init_restart_util.run_restart(checkpoint_directory='diags', checkpoint_prefix='checkpoint', force=False, additional_steps=None)[source]¶
Attempts to restart a run by looking for checkpoint files starting with a prefix in the given directory.
- Parameters
checkpoint_directory (str) – Look in this directory for checkpoint directories. Default is
diags.checkpoint_prefix (str) – Look for a checkpoint directory starting with this prefix to restart from.
force (bool) – If true, a problem with restarting from a checkpoint will cause an error, otherwise simply print a warning.
additional_steps (int) – The number of steps to run after restarting from the checkpoint. If this is None then it will run to the current value of mwxrun.simulation.max_steps.
mewarpx.utils_store.mwxconstants module¶
File to keep constants not already in picmi.py that are needed in mewarpx.
mewarpx.utils_store.mwxlogging module¶
- class mewarpx.utils_store.mwxlogging.MEFilter(name='')[source]¶
Bases:
FilterInitialize a filter.
Initialize with the name of the logger which, together with its children, will have its events allowed through the filter. If no name is specified, allow every event.
- class mewarpx.utils_store.mwxlogging.MEHandler(stream)[source]¶
Bases:
StreamHandlerInitialize the handler.
If stream is not specified, sys.stderr is used.
- emit(record)[source]¶
Emit a record.
If a formatter is specified, it is used to format the record. The record is then written to the stream with a trailing newline. If exception information is present, it is formatted using traceback.print_exception and appended to the stream. If the stream has an ‘encoding’ attribute, it is used to determine how to do the output to the stream.
mewarpx.utils_store.parallel_util module¶
mewarpx.utils_store.plotting module¶
- class mewarpx.utils_store.plotting.ArrayPlot(array, template=None, plot1d=False, ax=None, style=None, **kwargs)[source]¶
Bases:
objectInitialize and plot the passed array data. Many processing steps.
Plot given array data.
- Parameters
array (np.ndarray) – Numpy array containing the data to plot.
template (string) – One of ‘phi’, ‘E’, ‘rho’, ‘barrier’, or None; used to determine default labels. Default None.
plot1d (bool) – If True, plot 1D cuts instead of normal plots. Note the xaxis is used in this case as the plotted axis, and the yaxis becomes the swept axis.
ax (matplotlib.Axes) – If specified, plot on this axes object. If unspecified, get current axes.
style (string) – If not None, override default parameters with a pre-defined style set. Currently ‘arvind’ is implemented. Manually supplied parameters will override the defaults in the style.
numpoints (int) – If plot1d is True; number of cuts to use
points (float or list of floats) – If plot1d is True, position(s) (in m) to plot. If None, plot equally spaced positions. If this is used, it overrides numpoints.
draw_contourlines (bool) – If True, draw contour lines. Default False.
draw_fieldlines (bool) – If True, draw field lines. Default False.
xlabel (string) –
ylabel (string) –
title (string) – If specified, use only this title. Otherwise the title is constructed if None. Use empty string to remove the title completely.
titlestr (string) – If title is not specified, the name of the quantity to be used in the title.
titleunits (string) – If title is not specified, the name of the units to be used for the title.
titleline2 (string) – If title is not specified, use as optional 2nd line of title.
labelsize (int) –
titlesize (int) –
scale (string) – Either ‘linear’ or ‘symlog’. The ‘linthresh’ and ‘linportion’ parameters are ignored if using a linear scale.
linthresh (float) – occurs. Default 0.2, always positive
linportion (float) – portion. Default 0.33, always positive
ncontours (int) – Default 100
ncontour_lines (int) – labels on color bar. Default 15.
multiplier (float) – factor, e.g. -1.0 to see negative potentials.
zeroinitial (bool) – If True, for 1D cuts only, perform a vertical shift such that leftmost point is at y=0.
cmap (string) – String for a matplotlib colormap. Default inferno.
draw_cbar (bool) – If True, draw color bar. Default True.
cbar_shrink (float) – If < 1, shrink colorbar size, enlarge if > 1. Default 1.0.
cbar_label (str) – Label for the color bar if used. Default empty string (no label).
draw_surface (bool) – If True, use ax.plot_surface() rather than ax.contourf. Better display for 3D plots (do not use with 2D). Default False.
draw_image (bool) – If True, use ax.imshow() rather than ax.contourf. Displays pixelation with no interpolation. Default True.
repeat (bool) – If True, draw two periods in ordinate direction. Default False.
xaxis (string) – Axis along the abscissa, one of [‘r’, ‘x’, ‘y’, ‘z’]. Default ‘z’.
yaxis (string) – Axis along the ordinate, one of [‘r’, ‘x’, ‘y’, ‘z’]. Default ‘x’.
slicepos (float) – Position to take slice along 3rd dimension for 3D (m). Default 0.
animated (bool) – If True, set up the plot for an animation rather than a static image. Defaults to False, and ignored unless draw_image is True.
valmin (float) – If not None, override default minimum of the array being plotted for color scales etc.
valmax (float) – If not None, override default maximum of the array being plotted for color scales etc.
offset (float) – Constant offset added to values, e.g. for changing potential zero. Applied after the multiplier.
- param_defaults = {'_linthreshmin': 1, '_linthreshper': 5, 'animated': False, 'cbar_label': '', 'cbar_shrink': 1.0, 'cmap': 'viridis', 'default_ticks': False, 'draw_cbar': True, 'draw_contourlines': False, 'draw_fieldlines': False, 'draw_image': True, 'draw_surface': False, 'labelsize': 24, 'legendsize': 12, 'linportion': 0.33, 'linthresh': 0.2, 'multiplier': 1.0, 'ncontour_lines': 15, 'ncontours': 100, 'numpoints': 7, 'offset': 0.0, 'plot_name': 'plot.png', 'plottype': 'phi', 'points': None, 'repeat': False, 'scale': 'symlog', 'slicepos': None, 'sweepaxlabel': None, 'templates': {'E': {'_linthreshmin': 1e-20, '_linthreshper': 1, 'linportion': 0.01, 'linthresh': None, 'titlestr': 'Electric field magnitude', 'titleunits': 'V/nm'}, 'barrier': {'multiplier': -1.0, 'title': 'Potential energy profiles', 'ylabel': 'Barrier index (eV)', 'zeroinitial': True}, 'image': {'default_ticks': True, 'scale': 'linear'}, 'n': {'_linthreshmin': 1, '_linthreshper': 5, 'linportion': 0.05, 'linthresh': None, 'titlestr': 'Particle number density', 'titleunits': 'cm$^{3}$'}, 'phi': {'linportion': 0.33, 'linthresh': 0.2, 'titlestr': 'Electrostatic potential', 'titleunits': 'V'}, 'rho': {'_linthreshmin': 1, '_linthreshper': 5, 'linportion': 0.05, 'linthresh': None, 'titlestr': 'Electron density', 'titleunits': '|e|/cm$^{3}$'}}, 'title': None, 'titleline2': None, 'titlesize': 32, 'titlestr': 'Array plot', 'titleunits': '', 'valmax': None, 'valmin': None, 'xaxis': 'z', 'xlabel': None, 'yaxis': 'x', 'ylabel': None, 'zeroinitial': False}¶
- styles = {'arvind': {'default_ticks': True, 'labelsize': 'medium', 'legendsize': 'medium', 'templates': {'E': {'linportion': 0.1, 'titleunits': 'V nm$^{-1}$'}, 'phi': {'scale': 'linear', 'titleunits': 'volts'}, 'rho': {'linportion': 0.1}}, 'titlesize': 'large'}, 'roelof': {'default_ticks': True, 'labelsize': 'medium', 'legendsize': 'medium', 'templates': {'E': {'linportion': 0.1, 'titleunits': 'V nm$^{-1}$'}, 'barrier': {'zeroinitial': False}}, 'titlesize': 'medium'}}¶
- mewarpx.utils_store.plotting.get_2D_field_slice(data, xaxis, yaxis, slicevec=None, slicepos=None)[source]¶
Return appropriate 2D field slice given the geometry.
- Parameters
data (np.ndarray) – 2D or 3D array, depending on geometry
xaxis (int) – Index of abscissa dimension of data
yaxis (int) – Index of ordinate dimension of data
sliceaxis (int) – Index of dimension of data to slice from. None for 2D.
slicevec (np.ndarray) – 1D vector of positions along slice. None for 2D, or to take middle element in 3D.
slicepos (float) – Position to slice along sliceaxis (m). Default 0 if slicevec != None; ignored if slicevec == None.
- Returns
2D array. Ordinate is the first dimension of the array, abscissa the 2nd.
- Return type
slice (np.ndarray)
- mewarpx.utils_store.plotting.get_axis_idxs(axis1, axis2, dim=2)[source]¶
Return the indices appropriate for the given axes and dimension.
- mewarpx.utils_store.plotting.get_figsize(aspect_ratio, max_dim=16.0, min_dim=0.0)[source]¶
Return tuple based on aspect ratio and desired size.
- Parameters
- Returns
Figure size with given aspect ratio
- Return type
figsize (tuple (xwidth, ywidth))
mewarpx.utils_store.profileparser module¶
- class mewarpx.utils_store.profileparser.FullProfile(lines, stdout_path, write_dir=None)[source]¶
Bases:
objectClass for parsing, storing and writing the full profile data
mewarpx.utils_store.pulsing module¶
File to hold utility functions associated with setting up and plotting time varying voltage functions.
- class mewarpx.utils_store.pulsing.PulseFunction(get_voltage, V_off, V_on, pulse_period, pulse_length, t_rise, t_fall, wait_time)¶
Bases:
tupleCreate new instance of PulseFunction(get_voltage, V_off, V_on, pulse_period, pulse_length, t_rise, t_fall, wait_time)
- V_off¶
Alias for field number 1
- V_on¶
Alias for field number 2
- get_voltage¶
Alias for field number 0
- pulse_length¶
Alias for field number 4
- pulse_period¶
Alias for field number 3
- t_fall¶
Alias for field number 6
- t_rise¶
Alias for field number 5
- wait_time¶
Alias for field number 7
- mewarpx.utils_store.pulsing.linear_pulse_function(V_off, V_on, pulse_period, pulse_length, t_rise=2.5e-08, t_fall=2.5e-08, wait_time=5e-09, plot=True)[source]¶
Function to construct an expression for a voltage pulse that can be parsed by the WarpX parser. This version uses linear segments to build a pulse with form
____ ____
/ /
____/ ___________________________/ _____
- Parameters
V_off (float) – Electrode bias in the off-phase in Volt.
V_on (float) – Electrode voltage at the peak of the pulse in Volt.
pulse_period (float) – Full period from pulse start to the subsequent pulse start in seconds.
pulse_length (float) – Time duration of on-pulse phase in seconds. Does not include t_rise and t_fall.
t_rise (float) – Time for pulse to rise to its on value in seconds. Defaults to 25 ns.
t_fall (float) – Time for pulse to decrease to its off value in seconds. Defaults to 25 ns.
wait_time (float) – Time in seconds to offset the pulse function back to allow the simulation time to equilibrate before starting the pulse. Defaults to 5 ns.
plot (bool) – Optional parameter, if True the pulse waveform will be plotted.
- Returns
String expression of voltage function that can be parsed by the WarpX parser.
- mewarpx.utils_store.pulsing.plot_pulse(pulse_function, save_dir='diags/circuit')[source]¶
Utility function that plots the pulse shape applied to the device with annotations showing pulse parameters.
- Parameters
pulse_function (PulseFunction) – Contains pulse details as well as a callable function get_voltage to get the pulse voltage at a given time.
save_dir (str) – Directory where the pulse schematic should be saved.
mewarpx.utils_store.testing_util module¶
Utility functions for pytest in mewarpx. Make sure to import after init_libwarpx is run!
- mewarpx.utils_store.testing_util.change_to_warpxdir(wd)[source]¶
Handle logic of moving to correct directory. The directory is created if needed. :param wd: Path of desired working directory. :type wd: str
- Returns
Path of original working directory
- Return type
origwd (str)
- mewarpx.utils_store.testing_util.get_max_wmargin(array, margin=0.1)[source]¶
Get a maximum value with a multiplicative margin of safety.
- mewarpx.utils_store.testing_util.get_min_wmargin(array, margin=0.1)[source]¶
Get a minimum value with a multiplicative margin of safety.
- mewarpx.utils_store.testing_util.initialize_testingdir(name)[source]¶
Change into an appropriate directory for testing. This means placing it in util.temp_dir, and attaching “_XXXXXX”, a random 6-digit integer, to the end of the path. :param name: The base string used in the new directory. :type name: str
- mewarpx.utils_store.testing_util.test_df_in_margin(testdf, refdf, margin=0.1)[source]¶
Test that a DataFrame is within min/max of another, within a margin.
- mewarpx.utils_store.testing_util.test_df_vs_ref(testname, df, suffix=None, margin=0.1)[source]¶
Handle loading and test a reference DataFrame against test results.
This creates or appends to a
<testname>.csvor<testname>_<suffix>.csvfile intests/temp_files/Result_Stats. It then compares the results to a dataframe stored intests/test_files/Result_Statsunder the same filename. This means that running and failing the test many times will generate a csv file with all the information needed to check that stats don’t change in the future. See e.g.test_runsuite_vweights.py::test_runsuite_vweights2diag.- Parameters
testname (str) – Name of the test
df (pandas.DataFrame) – DataFrame containing the test results to compare against a reference
suffix (str) – An append to test names, allowing multiple DataFrames to be referenced in a single test.
margin (float) – A multiplicative safety margin: The tested df values should be within (1 +- margin) * [min or max](ref_val). Default 0.1.
test_root_dir (str) – Location of tests directory that contains test_files and temp_files. If None, will default to mwxutil.mewarpx_dir/../tests.
- Returns
True if equal within the margin. False if reference file does not exist or data frames do not agree, meaning that the test value does not fall within min and max of reference values within some error margin.
- Return type
equal_within_margin (bool)
mewarpx.utils_store.util module¶
Utility functions for mewarpx.
- mewarpx.utils_store.util.J_RD(T, WF, A)[source]¶
Returns the Richardson-Dushmann thermionic emission given a temperature and effective work function. Constant coefficient of emission (A) is assumed.
- mewarpx.utils_store.util.check_version(script_version, script_physics_version)[source]¶
Check that a run script is compatible with this mewarpx.
If this mewarpx distribution is lower than that of the run script, throw an error. If this mewarpx distribution API or physics version is higher than that of the run script, throw a warning. Else do nothing.
- mewarpx.utils_store.util.get_positions(num_samples, xmin, xmax, ymin=0, ymax=0, z=0, rseed=None)[source]¶
Provide random samples of [x, y, z] for electrons in simulation. In x and y, positions are uniformly distributed. In z, positions are placed at the emitter.
- Parameters
num_samples (int) – Number of particles to generate positions for
xmin (float) – Min position in x (meters)
xmax (float) – Max position in x (meters)
ymin (float) – Min position in y (meters)
ymax (float) – Max position in y (meters)
z (float) – Position of the emitter on the z-axis (meters)
rseed (positive int) – If specified, seed the random number generator. Used for testing. The random number generator is set back at the end of the function.
- Returns
Array of shape (num_samples, 3) with positions.
- Return type
positions (np.ndarray)
- mewarpx.utils_store.util.get_positions_RZ(num_samples, rmin, rmax, theta_min=0, theta_max=6.283185307179586, z=0, rseed=None)[source]¶
Provide random samples of [x, y, z] for electrons in simulation. Positions are uniformly distributed in r. In z, positions are placed at the emitter.
- Parameters
num_samples (int) – Number of particles to generate positions for
rmin (float) – Min position in r (meters)
rmax (float) – Max position in r (meters)
theta_min (float) – Min angle (radians)
theta_max (float) – Max angle (radians)
z (float) – Position of the emitter on the z-axis (meters)
rseed (positive int) – If specified, seed the random number generator. Used for testing. The random number generator is set back at the end of the function.
- Returns
Array of shape (num_samples, 3) with positions.
- Return type
positions (np.ndarray)
- mewarpx.utils_store.util.get_vel_vector(v_mag)[source]¶
Function that returns a random velocity vector given a magnitude. The random point on a unit sphere is found according to https://math.stackexchange.com/questions/44689/how-to-find-a-random- axis-or-unit-vector-in-3d.
- mewarpx.utils_store.util.get_velocities(num_samples, T, m, emission_type='thermionic', transverse_fac=1.0, rseed=None)[source]¶
Generate array of random [vx, vy, vz] for cathode-emitted electrons.
- Parameters
num_samples (int) – Number of particles to generate velocities for
T (float) – Temperature for the electrons (usually material temp) (K)
m (float) – Mass of elementary particle (kg)
emission_type (str) – Use “thermionic” for a thermionic emitter oriented along +zhat, and use “random” for a purely thermal distribution with no preferred direction. “half_maxwellian” is used at present for surface ionization, again along +zhat. Defaults to “thermionic”.
transverse_fac (float) – Scale the particle’s x and y average energies by this factor, scales z average energy to conserve total average particle energy in the distribution. Default 1., Min 0., Max 2.
rseed (positive int) – If specified, seed the random number generator. Used for testing. The random number generator is set back at the end of the function.
- Returns
array of shape (num_samples, 3) with (vx, vy, vz) for each electron.
- Return type
velocities (np.ndarray)
- mewarpx.utils_store.util.ideal_gas_density(p, T)[source]¶
Calculate neutral gas density (in 1/m^3) from the ideal gas law using pressure in Torr.
- mewarpx.utils_store.util.interpolate_from_grid(coords, grid)[source]¶
Function to interpolate from grid quantities to given coordinates.
- Parameters
coords (np.array) – Numpy array of coordinates of points where the grid values should be interpolated, with shape (dim, n) where dim is the simulation dimension and n the number of points to interpolate.
grid (np.array) – Numpy array holding the grid point values (on nodes of the grid).
- Returns
- Numpy array of length n holding the interpolated values
for each coordinate given.
- Return type
fpos (np.array)
- mewarpx.utils_store.util.mkdir_p(path)[source]¶
Make directory and parent directories if they don’t exist.
Do not throw error if all directories already exist.
- mewarpx.utils_store.util.mwx_round(x, base=1)[source]¶
Rounding function that allows rounding around a base value. :param x: value to round :type x: float :param base: base number to round around :type base: float
- mewarpx.utils_store.util.plasma_Debye_length(T, n)[source]¶
Returns the thermal Debye length of a plasma.
- mewarpx.utils_store.util.recursive_update(d, u)[source]¶
Recursively update dictionary d with keys from u. If u[key] is not a dictionary, this works the same as dict.update(). If u[key] is a dictionary, then update the keys of that dictionary within d[key], rather than replacing the whole dictionary.
- mewarpx.utils_store.util.return_iterable(x, depth=1)[source]¶
Return x if x is iterable, None if x is None, [x] otherwise.
Useful for arguments taking either a list or single value. Strings are a special case counted as ‘not iterable’.
- Parameters
depth (int) – This many levels must be iterable. So if you need an iterable of an iterable, this is 2.