mewarpx.diags_store package

Submodules

mewarpx.diags_store.checkpoint_diagnostic module

Class for installing a checkpoint diagnostic

class mewarpx.diags_store.checkpoint_diagnostic.CheckPointDiagnostic(diag_steps, name='checkpoint', clear_old_checkpoints=True, num_to_keep=2, **kwargs)[source]

Bases: WarpXDiagnostic

This class is a wrapper for creating checkpoints from which a simulation can be restarted. Adding flux diagnostic data to checkpoints are supported, but since this class has to be initialized before the simulation and flux diagnostics are initialized after the simulation, the user is responsible for adding the flux_diag attribute to this object in a simulation input file.

Parameters
  • diag_steps (int) – Run the diagnostic with this period. Also plot on this period if enabled.

  • name (str) – The name of the diagnostic to be passed into the picmi checkpoint diagnostic.

  • clear_old_checkpoints (bool) – If True old checkpoints will be deleted after new ones are created.

  • num_to_keep (int) – Number of checkpoints to keep. Default 1.

  • kwargs – For a list of valid keyword arguments see mewarpx.diags_store.diag_base.WarpXDiagnostic

add_checkpoint()[source]
checkpoint_manager(force_run=False)[source]

Function executed on checkpoint steps to perform various tasks related to checkpoint management. These include copying the flux diagnostic data needed for a restart as well as deleting old checkpoints.

mewarpx.diags_store.diag_base module

Base diagnostic code used in many diagnostics.

class mewarpx.diags_store.diag_base.TextDiag(diag_steps, preset_string='default', custom_string=None, install=True, **kwargs)[source]

Bases: WarpXDiagnostic

Output diagnostics every certain number of steps.

Contains:

text_diag (function): Function to do the write-out. Use only if needed for a future reference in script.

Generate and install function to write out step #.

Parameters
  • diag_steps (int) – Number of steps between each output

  • simulation (mespecies.Simulation) – Main simulation object

  • preset_string (str) –

    Defaults to choose between:

    • default - just the step number and total particle num

    • perfdebug - like particledebug, plus interval wall time, step rate, and particle-step rate

    • memdebug - print out verbose memory usage information

  • custom_string (str) –

    Overrides preset_string if not None. The full

    string to output, with:

    • {step} formatting symbol for where the step number should go

    • {wall_time} run time of the last diag_steps steps

    • {step_rate} diag_steps / wall_time

    • {particle_step_rate} nplive * diag_steps / wall_time

    • {nplive} for number of live particles (global).

    • {npperspecies} for number of particles per species (global).

    • {iproc} for the current processor number

    • {system_memory} for verbose information on system memory usage.

    • {memory_usage} for memory usage of the current process only.

  • install (bool) – If False, don’t actually install this into WarpX. Use if you want to call manually for debugging.

  • kwargs – See mewarpx.mewarpx.diags_store.diag_base.WarpXDiagnostic for more timing options.

init_timers_and_counters()[source]

Start timers.

print_performance_summary()[source]
text_diag()[source]

Write requested information to output.

update_memory()[source]

Update memory usage information with psutil.

class mewarpx.diags_store.diag_base.WarpXDiagnostic(diag_steps, diag_step_offset=0, extended_interval_level=None, manual_timesteps=None)[source]

Bases: object

Hold attributes common to all diagnostics, especially logic on when to run.

Initialize timing. Will often be called within a child object’s init.

Parameters
  • diag_steps (int) – Run the diagnostic with this period.

  • diag_step_offset (int) – Run when simulation_step % diag_steps = diag_step_offset. Default 0.

  • extended_interval_level (int) – Enable an exponentially-increasing interval as the run progresses. If None (default), calculate every time period. Otherwise, the interval increases on an exponential scale. 0 is most aggressive at skipping diagnostic timesteps; 1, 2, etc. are progressively less aggressive but still exponential. Specifically, 0 executes once during each power-of-2 set of diagnostic steps; 1 twice; 2 four times, etc.

  • manual_timesteps (list of ints) – A list of timesteps to execute on within each diag_steps. If this list contains steps for the entire run, set diag_steps to a very large number. Default None.

DIAG_DIR = 'diags'
check_timestep()[source]

Check if the diagnostic should run on this timestep.

Returns

If True, run on this timestep. If False, don’t.

Return type

l_execute (bool)

mewarpx.diags_store.field_diagnostic module

Class for installing a field diagnostic with optional plotting

class mewarpx.diags_store.field_diagnostic.FieldDiagnostic(diag_steps, process_phi=True, process_E=False, process_rho=True, species_list=None, plot=True, barrier_slices=None, max_dim=16.0, min_dim=0.0, dpi=300, install_field_diagnostic=False, post_processing=False, **kwargs)[source]

Bases: WarpXDiagnostic

This class handles diagnostics for field quantities (output and plotting) typically of interest in Modern Electron simulations. Optionally a picmi FieldDiagnostic can also be installed.

Parameters
  • diag_steps (int) – Run the diagnostic with this period. Also plot on this period if enabled.

  • process_phi (bool) – If True, output phi. Default True.

  • process_E (bool) – If True, output E. Default False.

  • process_rho (bool) – If True, output rho. Default True.

  • species_list (list) – Optional list of picmi.Species objects for which output density. If not specified all species will be tabulated.

  • plot (bool) – If True, also generate plots. Default True.

  • barrier_slices (list) – If provided, also plot potential energy slices as a function of z for each value of x/r in the list. Units are in meters.

  • max_dim (float) – Maximum figure dimension in inches for field plots.

  • min_dim (float) – Minimum figure dimension in inches for field plots.

  • dpi (int) – Resolution to use for saved plots

  • install_field_diagnostic (bool) – If true, install a picmi FieldDiagnostic. All parameters for the diagnostic should be passed as keyword arguments.

  • post_processing (bool) – Whether or not to plot data after simulation ends from any yt files generated during the run.

  • kwargs – For a list of valid keyword arguments see diag_base.WarpXDiagnostic

FIELD_DIAG_DIR = 'fields'
add_field_diag()[source]

Add a picmi FieldDiagnostic to the simulation.

do_post_processing()[source]
fields_diag()[source]

Function to process (get, plot and save) field quantities. This function is called on every step, but only executes if check_timestep() evaluated to True.

get_fileprefix(title)[source]

Return filepath except for the filetype.

Parameters

title (str) – String for title; whitespace will become underscores

plot_barrier_slices(phi_array, slices, **kwargs)[source]
Plot 1D potential energy slices from the phi array in order to

visualize changes in the barrier index during the simulation.

Other kwargs are passed on to plotting.

Parameters
  • phi_array (numpy.ndarray) – Full electrostatic potential array

  • slices (float or list of floats) – Positions (in m) along x/r for plotting barrier index lineouts.

plot_field(data, plottype, titlestr, plot1d=False, **kwargs)[source]

Plot given field and save to file as both pdf and png.

Other kwargs are passed on to plotting.

Parameters
  • data (numpy.ndarray) – Full array to plot

  • plottype – Choose ‘phi’, ‘E’, ‘barrier’ or ‘rho’ to set correct labels

  • titlestr (string) – Title for plot and filename.

  • plot1d (bool) – Used to determine figure size and plotting call.

process_field(data, titlestr, plottype=None, **kwargs)[source]

Save given field to file, and optionally plot it as well.

Other kwargs are passed on to plotting.

Parameters
  • data (numpy.ndarray) – Array to output

  • titlestr (string) – String to use as first part of the file name. Also used for the title in plotting.

  • plottype – Choose ‘phi’, ‘E’, or ‘rho’ to set correct labels

mewarpx.diags_store.flux_diagnostic module

class mewarpx.diags_store.flux_diagnostic.FluxCalcDataframe(df, area, step_begin=None, step_end=None, dt=None)[source]

Bases: Timeseries

A FluxCalc created from a pandas Dataframe. Dataframes passed to this class should only consist of a single species; as a result multiple lines at the same timestep are not supported. Desired concatenation or summation across timeseries should be done on the processed timeseries, not on the raw dataframes. INSERT TEXT ABOUT EXTRA COLUMNS HERE – ESPECIALLY IMPLICATIONS FOR WHICH QUANTITIES MAKE SENSE BECAUSE THE NORMALIZATION BY WEIGHT MAKES SENSE FOR THEM All calculations are done with reference to ground (V_e=0).

Initialize the FluxCalc object, transforming df into the appropriate array.

Parameters
  • df (pandas.DataFrame) – A single dataframe with columns:

  • t (-) – Time in sec

  • step (-) – Step number, integer, with constant dt necessary.

  • n (-) – Number of macroparticles

  • q (-) – Injected/deposited charge

  • E_part (-) – Total KE + PE of the particles, relative to phi = 0, assuming potential energy = q*phi. For scraped data, this has already been multiplied by -1 in the scraper to denote energy leaving the system.

  • V_e (-) – Fermi level of the emitting or collecting surface.

  • columns (- Optional extra) –

  • area (float) – Area to consider for calculating current densities, usually Lx*Ly from the simulation, in m^2. Values are transformed to /cm^2 internally.

  • step_begin (int) – Beginning timestep to consider. If not provided, take min step in df. Must be <= min step in df.

  • step_end (int) – Last timestep +1 to consider. If not provided, take max step in df +1. Must be > max step in df.

  • dt (float) – Timestep increment. If not provided, use warp.top.dt. Must provide in post-processing.

class mewarpx.diags_store.flux_diagnostic.FluxDiagBase(diag_steps, runinfo, overwrite=True, sig_figs=6, printed_qtys=None, fullhist_dict=None, ts_dict=None, **kwargs)[source]

Bases: WarpXDiagnostic

Handle generic printing & plotting of charge injection and absorption. This Base class should work with both postprocessing and during-run analyses.

Generate and install function to write out fluxes.

Parameters
  • diag_steps (int) – Number of steps between each output

  • runinfo (mewarpx.runinfo.RunInfo) – RunInfo object is used to get the species, injectors, surfaces, and system area.

  • overwrite (bool) – If True the dill pickled save file will overwrite the previous diagnostic period’s saved file.

  • sig_figs (int) – Number of significant figures in text output. Default 6.

  • printed_qtys (dict) – Override individual values of default_printed_qtys; same input format but keys can be omitted to use defaults.

  • fullhist_dict (dict) – Dictionary of timeseries for the full run

  • ts_dict (dict) – Dictionary of timeseries for the last 8 steps

  • kwargs – See mewarpx.diags_store.diag_base.WarpXDiagnostic for more timing options.

FLUX_DIAG_DIR = 'fluxes'
default_printed_qtys = {'J': {'by_component': 'all', 'description': 'Current', 'total': 'all', 'units': 'A/cm^2'}, 'P': {'by_component': None, 'description': 'Power', 'total': 'net', 'units': 'W/cm^2'}, 'dQ': {'by_component': None, 'description': 'Heat transfer', 'total': None, 'units': 'W/cm^2'}, 'n': {'by_component': None, 'description': 'Macroparticle rate', 'total': None, 'units': 'particles per step'}}
get_net_flux_timeseries(electrode_name, flux_type='J')[source]

Sum the emitted and absorbed flux across all species for a given electrode, and return a timeseries array containing the net flux from the electrode surface into the simulation volume.

Parameters
  • electrode_name (str) – Surface name such as ‘cathode’ or ‘anode’. Must be present in the RunInfo injector_dict and surface_dict in order to be a valid key.

  • flux_type (str) – Either ‘J’, ‘P’, ‘dQ’, or ‘n’. Defaults to ‘J’.

Returns

n x 2 array containing the time in

seconds in first column and the net flux from the electrode in second column.

Return type

flux_timeseries (np.ndarray)

plot_fluxes(ts_dict, save=False)[source]
Parameters

save (bool) – If True, save and close figure. write_dir must be defined. If False, leave figure open and return it.

print_fluxes(tsdict)[source]

Print the float results of calculations for the given dictionary of timeseries.

Parameters

tsdict (dict of (str, str, str)) – First string is either ‘inject’ or ‘scrape’; second string is the group name (eg cathode, accgrid); third value is species_name for the species. Note any cropping etc. should be done before this dict is passed in!

Returns

A string that can be printed for the performance.

Return type

resultstr (str)

print_fluxset(prefixstr, key, suffixstr, emit_ts=None, collect_ts=None, net_only=False)[source]

Print emitted and collected flux for specific timeseries and specific flux quantity.

Parameters
Returns

A string that can be printed for the performance.

Return type

resultstr (str)

refresh_species(runinfo)[source]

When species are updated, this can be used to re-synchronize an existing FluxDiag with the new information. Will not update surfaces or injectors, however.

Note

In the future, it may be best to replace this with something that more fully resets all references to runinfo, and/or just always explicitly reference runinfo rather than getting information from it at init. However, for now this is the quickest way to proceed.

Parameters

runinfo (mewarpx.runinfo.RunInfo) – An updated RunInfo object is solely used to get new species name information.

save(filepath=None)[source]

Save only the critical variables to a pickle file. Since this can be done often, a specific function is used to minimize file size.

Parameters

filepath (str) – If None, this is generated internally. Otherwise save the pickle file to this path.

class mewarpx.diags_store.flux_diagnostic.FluxDiagFromFile(basedir='diags', fluxdatafile=None, fluxdatafileformat='fluxes/fluxdata*', fs=None)[source]

Bases: FluxDiagBase

Load a flux diag from its minimal saved file. This is meant for postprocessing ONLY; it will not initialize things properly for during-run operations.

Load from fluxdata_XXXXXXXXXX.dpkl files.

Parameters
  • basedir (str) – Base directory of the diagnostic files.

  • fluxdatafile (str) – Filename dill-pickled with FluxDiagBase.save().

  • fluxdatafileformat (str) – If a specific fluxdatafile is not specified, this naming format will be used to search for the latest fluxdata file in the base directory.

  • fs (s3fs filesystem) – Optional S3 filesystem to load data directly from a S3 bucket.

class mewarpx.diags_store.flux_diagnostic.FluxDiagnostic(diag_steps, runinfo, overwrite=True, history_maxlen=5000, sig_figs=6, printed_qtys=None, check_charge_conservation=True, print_per_diagnostic=True, print_total=False, plot=True, save_csv=False, profile_decorator=None, **kwargs)[source]

Bases: FluxDiagBase

Handles writing out charge injection and absorption.

Generate and install function to write out fluxes.

Parameters
  • diag_steps (int) – Number of steps between each output

  • runinfo (mewarpx.runinfo.RunInfo) – RunInfo object is used to get the species, injectors, surfaces, and system area.

  • overwrite (bool) – If True the dill pickled save file will overwrite the previous diagnostic period’s saved file.

  • history_maxlen (int) – Maximum length of full history to keep. If this is exceeded, history is resampled to a 2x lower frequency. Default 5000.

  • sig_figs (int) – Number of significant figures in text output. Default 6.

  • printed_qtys (dict) – Override individual values of default_printed_qtys; same input format but keys can be omitted to use defaults.

  • check_charge_conservation (bool) – Whether to check if charge is conserved in simulation.

  • print_per_diagnostic (bool) – Whether to print current results for the latest diagnostic period.

  • print_total (bool) – Whether to print total history of fluxes after a diagnostic period.

  • plot (bool) – Whether to save a plot of fluxes after each diagnostic period.

  • save_csv (bool) – Whether to save csv files of scraped / injected particles.

  • profile_decorator (decorator) – A decorator used to profile the timeseries update methods and related functions.

  • kwargs – See mewarpx.diags_store.diag_base.WarpXDiagnostic for more timing options.

check_scraping()[source]

Checks that particles scraping at the appropriate boundaries is turned on when flux diagnostics are on.

update_fullhist_dict()[source]

Once current diagnostic period is updated, update full history and resample if needed.

update_ts_dict()[source]

Run early in flux analysis to get this diagnostic period’s timeseries.

class mewarpx.diags_store.flux_diagnostic.InjectorFluxDiag(diag_steps, injector, write_dir, **kwargs)[source]

Bases: ParticleCSVDiag

Handles writing out charge absorption by injectors.

Generate and install function to write out charge accumulation.

Parameters
class mewarpx.diags_store.flux_diagnostic.ParticleCSVDiag(diag_steps, write_dir=None, save_name=None, **kwargs)[source]

Bases: WarpXDiagnostic

Handles writing out, and accumulating real-time, a per-step record of charge injected or deposited. Provides a base for specific implementations. At present species_name is a required column and must be str.

Basic initialization. If write_dir or save_name are None, no data is saved to file and only accumulated data is kept.

Parameters
  • diag_steps (int) – Number of steps between each output

  • write_dir (string) – Directory to write CSV files to.

  • save_name (string) – Full filename within the directory to write CSV files to.

  • kwargs – See mewarpx.diags_store.diag_base.WarpXDiagnostic for more timing options.

charge_accum_diag()[source]

Generate flux dataframe; write to CSV if requested. Called by the FluxDiag owning this at appropriate timesteps.

columns_no_accumulate = ['t', 'step', 'species_id']
get_species_list()[source]

Get sorted list of all species names recorded by this diagnostic.

get_updated_accumulators()[source]

Return up-to-date accumulated values in a separate dictionary, without clearing and/or writing the values.

class mewarpx.diags_store.flux_diagnostic.SurfaceFluxDiag(diag_steps, surface, write_dir, **kwargs)[source]

Bases: ParticleCSVDiag

Handles writing out for a single surface.

This class is used by FluxDiag; rarely used directly.

Initialize surface-specific features.

Parameters
  • diag_steps (int) – Number of steps between each output

  • surface (mewarpx.Assembly object) – The assembly object in which particles are scraped.

  • write_dir (string) – Directory to write CSV files to.

  • kwargs – See mewarpx.diags_store.diag_base.WarpXDiagnostic for more timing options.

fields = ['t', 'step', 'species_id', 'V_e', 'n', 'q', 'E_total']
mewarpx.diags_store.flux_diagnostic.gen_timeseries(step_begin, step_end, dt, step_array, n_array, q_array, E_array, V_e_array, extra_arrays, num_extra_arrays)[source]

Transform dataframe entries, with potentially sparse rows (eg some timesteps have no associated row), into an array capturing all timesteps between step_begin and step_end. Multiple rows for the same timestep are not supported.

Note

Signs are somewhat confusing here! For particles that don’t have scattering or ionization, E_array is essentially KE_emit + q*V_emit. dQ for emission is then KE_emit + q*V_emit - q*V_e, but V_emit = V_e - WF, so dQ = KE_emit - q*WF. Since q is negative for electrons, we’re adding |q|*WF potential energy into simulation, which does correctly represent surface cooling due to electron evaporation. dQ for absorption – the arguments passed in, E_array and q_array, are already both negated to represent absorption vs injection. With standard physical signs for q, Q, KE, etc., then, dQ = -(KE_emit + q*V_cathode) + q*V_e_anode = -(KE_emit + q(V_cathode - (V_anode + WF))), where V_cathode and V_anode are vacuum biases. The front minus sign indicates absorption of this heat onto the surface/out of the system. q*(V_cathode - V_anode) captures kinetic energy from accelerating the particle across the gap. -q*WF is the heat deposited from the electron falling back to the Fermi level. So it should all work, and tests confirm energy conservation – see test_diags_fluxdiag.py.

Parameters
  • step_begin (int) – First step to consider

  • step_end (int) – n + 1th step to consider (eg python indexing)

  • dt (float) – Timestep in seconds, necessary for normalization

  • step_array (np.ndarray) – m-length array of the step number for each row. All entries in step_array must be integers >= step_begin and < step_end. m is the number of rows in the original dataframe.

  • n_array (np.ndarray) – m-length array of the macroparticle count for each row.

  • q_array (np.ndarray) – m-length array of the charge (in C) for each row.

  • E_array (np.ndarray) – m-length array of the KE + PE for each row. For scraped data, this has already been multiplied by -1 in the scraper to denote energy leaving the system.

  • V_e_array (np.ndarray) – m-length array of the Fermi level voltage for each row.

  • extra_arrays (np.ndarrays) – m-length arrays that are averaged into a timeseries.

  • num_extra_arrays (int) – Number of extra arrays included.

Returns

(step_end - step_begin)x(4 + len(extra_arrays)) array with n, J, dQ, P at each timestep. Extra arrays are also made into a timeseries. Q=(E_part - q*V_e)/dt, and P=-(q*V_e)/dt (eg electrical power). Signs mean we get heat INTO system, and “standard” power production. (Note q is signed like Q: positive into system / negative out of system. That means electrons leaving the system give positive q.)

Return type

timeseries_array (np.ndarray)

mewarpx.diags_store.particle_diagnostic module

Diagnostic code that wraps the picmi.ParticleDiagnostics class

class mewarpx.diags_store.particle_diagnostic.ParticleDiagnostic(diag_steps, name=None, species=None, data_list=None, post_processing=False, plot_data_list=None, plot_species=None, **kwargs)[source]

Bases: WarpXDiagnostic

Output particle diagnostics every diagnostic period and produce plots from the diagnostics

Contains:
add_particle_diag (function): Function to add the particle diagnostic to

the mwxrun.simulation

post_processing: plot particle diagnostic data, not yet implemented

Initializes the picmi.ParticleDiagnostic and adds the diagnostic to the simulation

Parameters
  • diag_steps (int) – Number of steps between each diagnostic output

  • name (str) – name of the diag output folder, defaults to particle_diag

  • species (mewarpx.mespecies.Species) – species in the simulation, if None then uses all particles in the simulation

  • data_list (list str) – list of attributes to be outputted by the diagnostic, default uses ["position", "momentum", "weighting"]

  • post_process (bool) – generate plots for each diagnostic data directory produced

  • plot_data_list (list str) – list of data to be plotted for each diagnostic step (“particle_position_x”, “particle_position_y”, “particle_position_z”, “particle_momentum_x”, “particle_momentum_y”, “particle_momentum_z”)

  • plot_species (list str) – list of species names to be plotted, defaults to all species if not specified. Name variable in mewarpx.mespecies.Species must be set for each species in the simulation

PARTICLE_DIAG_DIR = 'particles'
add_particle_diag()[source]
check_for_end_of_sim()[source]
do_post_processing()[source]

mewarpx.diags_store.timeseries module

class mewarpx.diags_store.timeseries.Timeseries(step_begin, step_end, dt, array_dict=None)[source]

Bases: object

Hold a regularly-spaced array of values that we can then manipulate.

Initialize timeseries object with the arrays for it to hold.

Parameters
  • step_begin (int) – First timestep stored in the arrays

  • step_end (int) – Last timestep stored in the arrays

  • dt (float) – Time increment between steps in seconds

  • array_dict (dict of np.ndarray) – A dictionary with keys that are strings, and values that are one-dimensional arrays with length (step_end - step_begin)/stride, containing the value of that string’s quantity at each step = step_begin + i*stride. If None, initialize an empty dictionary that can be used later. All quantities should already be rates for resampling to work (eg current, not charge, at a given timestep).

static gauss_smooth(array, sigma)[source]

Apply Gaussian smoothing to the given array. This function is based on minerva.util.gaussian_smoothing, but since it operates in a given way on 1D arrays only, with no resampling, it’s re-implemented in simplified form here.

Parameters
  • array (np.ndarray) – The 1D array to smooth.

  • sigma (float) – The sigma, in units of steps, to use for smoothing.

Returns

1D array with smoothing applied.

Return type

smoothed_array (np.ndarray)

get_averagevalue_by_key(key, default=None)[source]

Get the rate value of a timeseries.

Parameters
  • key (str) – Key to look up.

  • default (float) – Value to return if the given key does not exist in the dictionary or if the dictionary is empty. If None, AttributeError will be raised for an invalid query.

Returns

Average value

Return type

value (float)

get_timeseries_by_key(key, include_times=True, default=None)[source]

Get timeseries, including an array of times if requested.

Parameters
  • key (str) – Key to look up.

  • include_times (bool) – If True, return an n_elements x 2 array that has time in seconds in first column; values in second. If False, return an n_elements array with values only.

  • default (None or float) – Value to fill timeseries array with if the given key does not exist in the dictionary or if the dictionary is empty. If None, AttributeError will be raised for an invalid query.

keys()[source]

A user accessible list of keys.

static mean_smooth(array, dt_factor, idx_offset=0)[source]

Apply smoothing and resampling to the given array. This function is a simplified smoothing scheme appropriate for cases where many data points will be combined into a single point. Smoothing is done by simply averaging the points to be combined.

Parameters
  • array (np.ndarray) – The 1D array to smooth.

  • dt_factor (int) – The units of steps to use for smoothing. If 1 or smaller, then no smoothing is performed and the original array is returned as is. If len(array) or larger, then the entire array is smoothed down to a single point.

  • idx_offset (int) – Smoothing calculation is performed on the slice array[idx_offset:]. Entries 0:idx_offset are ignored in the input and not returned in the output. Defaults to 0.

Returns

1D array with smoothing applied.

Return type

smoothed_array (np.ndarray)

property n_elements

A property so that it automatically adapts to resampling.

resample(new_dt, inplace=False, smooth=True)[source]

Resample the time series at a longer timescale.

Parameters
  • new_dt (float) – Must be a multiple of existing dt!

  • inplace (bool) – If True, modify this Timeseries. If False, return a new one. Note that if resample is the identity operation, the current Timeseries is returned regardless of this setting. Default False.

  • smooth (bool) – If True, first apply Gaussian smoothing with sigma = 0.5*new_dt to the timeseries before sampling from the timeseries. Default True. Note smoothing is never applied if new_dt is equal to current dt. If resampling by 500x or more, smooth using mean values instead.

Returns

Object with new dt.

Return type

timeseries (Timeseries)

set_array(key, array)[source]

Add or set an array in the dictionary.

Parameters
  • key (str) – Key to add

  • array (np.ndarray) – Array to add

class mewarpx.diags_store.timeseries.TimeseriesPlot(array_list, ax=None, **kwargs)[source]

Bases: object

Handle plotting of arbitrary timeseries.

Plot fluxes throughout the simulation.

Parameters
  • array_list (list of tuples of (name, timeseries_array)) – timeseries_arrays are those returned by Timeseries.get_timeseries_by_key(key, include_times=True). name is the label for the plot legend for that timeseries. List order determines plotting order. Smoothing should be performed before being passed to this function.

  • ax (matplotlib.Axes) – If specified, plot on this axes object. If unspecified, get current axes.

  • xlabel (string) – abscissa label. Must include ‘ns’ or ‘$mu$s’ to specify units in this string.

  • ylabel (string) – ordinate label

  • title (string) –

  • labelsize (int) – default 24

  • legendsize (int) – default 14

  • titlesize (int) – default 32

  • alpha (float) – Transparency of lines to avoid obscuring lines, if desired. Default 1 (disabled).

  • yfactor (float) – Multiply y-axis by this value. Eg for correcting the effective area in currents.

  • legend_loc (str) – ‘loc’ argument in legend call

  • legend_bbox_to_anchor (tuple of float) – bbox_to_anchor argument in legend call

  • xoffset (float) – Offset to apply to times, in seconds

default_timeseries_params = {'alpha': 1.0, 'labelsize': 24, 'legend_bbox_to_anchor': None, 'legend_loc': 'best', 'legendsize': 14, 'title': 'Timeseries plot', 'titlesize': 32, 'xlabel': 'Time ($\\mu$s)', 'xoffset': 0.0, 'yfactor': 1.0, 'ylabel': 'Timeseries output'}
mewarpx.diags_store.timeseries.concat_crop_timeseries(timeseries_list, step_begin=None, step_end=None, keys=None, dt=None, debug=False)[source]

Combine or crop timeseries object(s).

Note

dt must be a multiple of all individual timeseries’ dt. Timeseries that do not share the final dt will be resampled with default smoothing.

Parameters
  • timeseries_list (list of Timeseries) – List of objects to concatenate. If empty, return None.

  • step_begin (int) – Step to begin the array with, cropping timeseries if needed. If None (default), take all timesteps from inputs.

  • step_end (int) – Step to end the array with + 1, cropping timeseries if needed. If None (default), take all timesteps from inputs.

  • dt (float) – The timestep to use. If None, use the maximum dt among the series. In all cases, this must be a multiple of each timeseries dt.

  • keys (list of str) – If specified, concatenate only these keys and ignore any others held by the objects.

  • debug (bool) – If True, print out lots of diagnostic info. Default False. These print statements are commented out by default to prevent frequent if statement checks; so uncomment to enable debug functionality.

Returns

The concatenated, cropped, Timeseries object.

Return type

timeseries (Timeseries)

Module contents