Utils¶
Plotting and the analysis helpers. Batch and collection moved to their own
packages in 2.1 — see Batch and Collect;
cellpy.utils.batch / cellpy.utils.collectors are thin re-export shims of
those.
Batch (shim)¶
Re-exports cellpy.batch.
batch ¶
Deprecated shim: cellpy.utils.batch -> batch.
The batch subsystem was redesigned and now lives in batch
(journal / policy / runner / store / aggregate / qc / outputs / facade). This
module keeps the historical import path and entry points working -- returning
the new Batch -- and will remain permanently as a thin
re-export. The legacy batch_tools internals were removed in 2.1;
the DB-journal path they used to own is now native in batch.
Batch ¶
A loaded experiment: journal, cells, summaries, and a summary plot.
Typical use::
from cellpy import batch
b = batch.load(name="exp", project="proj")
b.summaries
b.cells["cell_01"]
b.plot()
b.result.report()
Attributes:
-
journal–The
Journal(pages + session). -
policy–The
LoadPolicyused on the last load. -
pages(DataFrame) –Journal table (filename, mass, group, …).
-
cell_names(list[str]) –Labels in journal order.
-
cells(CellStore) –Lazy
CellStoreofCellpyCellobjects. -
summaries(DataFrame) –Combined per-cycle summaries.
-
result(BatchResult | None) –BatchResultfrom the lastupdate.
experiment
property
¶
Backward-compat view for legacy consumers (helpers/collectors).
cellpy.utils.helpers and cellpy.utils.collectors still reach
into b.experiment.{cell_names,data,journal.pages,summary_frames}.
This adapter keeps them working against the new Batch until they are
migrated (Epic B/C); it is not part of the blessed API.
result
property
¶
Per-cell load outcomes from the last update / load.
Use b.result.report() for a tidy frame (outcome, source, error).
summaries
property
¶
Combined per-cycle summary frame across the batch (cached).
tests
property
¶
Per-test metadata across the batch (tidy long-format).
One row per (cell, test_id) with the native TestMeta fields plus
cell/group/sub_group keys -- the per-test records a merged
(campaign) cell carries. Empty frame if no cell exposes test metadata.
combine_summaries ¶
Rebuild and return the combined summary frame (clears the cache).
create_journal ¶
Populate the journal from the configured database (if any).
Mirrors the legacy init() -> create_journal() flow: init
stores the db config, create_journal performs the read.
drop ¶
Remove label from the journal and the store now.
Parameters:
-
label(str) –Cell name as in
b.cell_names.
drop_cells_marked_bad ¶
Drop every label listed in journal.session["bad_cells"].
export_project ¶
Write a shareable bundle: .cellpy files plus a rewritten journal.
2.x replacement for 1.x duplicate_cellpy_files(location="standard").
Each loaded cell is saved to <destination>/<label>.cellpy, journal
cellpy_file_name is rewritten to those paths (cwd-relative posix
when possible), and the journal is saved (Batch.save semantics:
cellpy_batch_<name>.json in the cwd unless journal_path is
given).
Does not copy raw files or clear raw_file_names. Unloaded cells
raise ValueError — call update first.
Parameters:
-
destination(Path | str) –directory for the
.cellpyfiles (created if needed). -
journal_path(Path | str | None, default:None) –optional journal JSON path; default is cwd
cellpy_batch_<name>.json.
Returns:
-
Path–Path of the written journal.
from_cells
classmethod
¶
from_cells(cells: Mapping[str, Any] | Sequence[Any], *, groups: Mapping[str, Any] | None = None, sub_groups: Mapping[str, Any] | None = None, group_labels: Mapping[Any, str] | None = None, selected: Mapping[str, bool] | None = None, name: str = 'in_memory', project: str = 'in_memory', policy: LoadPolicy | None = None) -> 'Batch'
Build a batch from already-loaded CellpyCell objects.
The pieces a batch needs -- a journal pages frame (polars, keyed by
filename) plus a populated cell store -- are constructed here, so a
GUI/notebook holding cells in memory can feed them straight to
collect_summaries / collect_cycles or
batch.plot() without writing a journal to disk.
Parameters:
-
cells(Mapping[str, Any] | Sequence[Any]) –{label: CellpyCell}or a sequence of cells (labels are taken fromcell.cell_name, falling back tocell_001..., de-duplicated). -
groups / sub_groups–optional
{label: value}maps (defaults: group 1 for all; sub_group 1..N). -
group_labels(Mapping[Any, str] | None, default:None) –optional
{group: display label}map. -
selected(Mapping[str, bool] | None, default:None) –optional
{label: bool}(defaults True) for the journalselectedcolumn. -
name / project–journal name/project.
from_db
classmethod
¶
Build a batch by reading a database (Excel or JSON).
load ¶
Load cells (alias of update, kept for the legacy surface).
Takes the same executor / on_progress / progress / policy
overrides as update, e.g. b.load(executor="threads").
mark_as_bad ¶
Flag label in journal.session['bad_cells'] (does not drop).
Parameters:
-
label(str) –Cell name as in
b.cell_names.
plot ¶
Plot combined summaries for this batch.
Parameters:
-
backend(str | None, default:None) –Plotting backend (
Noneuses the configured default). -
show(bool, default:False) –If True, display the figure immediately.
-
**kwargs–Forwarded to the summary plotter (columns, grouping, …).
Returns:
-
Any–A figure from the plotting layer (backend-dependent).
recalc ¶
Reload every cell and remake step tables and summaries.
Same kwargs as update.
report ¶
QC-style per-cell status frame (not the same as result.report()).
Parameters:
-
check(bool, default:True) –kept for the legacy surface; the frame is always built.
save ¶
update ¶
Load every cell, caching them in the store.
executor is "serial" (default), "threads" or "processes".
"threads" mainly speeds up reopening cells from local .cellpy
files; a first load of remote raw files does not overlap on the wire,
and "processes" usually loses to spawn overhead on Windows.
Process workers strip live cells; a raw load is written to .cellpy
in the worker so save_cellpy=True can persist without None.save.
progress is None (auto: TTY or Jupyter), False (off),
True (force), or a callable that receives progress events.
on_progress(i, n, result) still wins when set (3-arg callback).
Known LoadPolicy fields in overrides update the policy;
unknown (legacy) kwargs like testing are forwarded to the loader
(cellpy.get) via loader_kwargs.
CellSpec
dataclass
¶
CellSpec(label: str, raw_files: list = list(), cellpy_file: Any | None = None, instrument: str | None = None, model: str | None = None, mass: float | None = None, nom_cap: float | None = None, nom_cap_specifics: str | None = None, area: float | None = None, cycle_mode: str | None = None, overrides: dict = dict())
Fully resolved per-cell loading instructions.
LoadPolicy
dataclass
¶
LoadPolicy(source: SourcePreference = SourcePreference.AUTO, recalc: bool = False, max_cycle: int | None = None, accept_errors: bool = True, all_in_memory: bool = False, skip_bad_cells: bool = False, selector: dict | None = None, loader_kwargs: dict = dict(), overrides: dict = dict())
Batch-wide loading options (one object instead of a kwargs tunnel).
combine_summaries ¶
Concatenate per-cell summaries into one tidy long-format frame.
Each row keeps its cell's summary columns plus cell/group/
sub_group keys. Cells without a summary are skipped. Returns an empty
frame when nothing has a summary.
from_journal ¶
Create a batch from a journal file (shim -> from_journal).
init ¶
Initialise a batch (shim -> load).
Legacy flow init() -> create_journal() -> update() is preserved: with a
database source, init defers the read to create_journal.
load ¶
load(name=None, project=None, *, journal_file=None, reader=None, column_map=None, batch_col=None, frame=None, testing=False, raw_file_dir=None, cellpy_file_dir=None, policy=None, **kwargs) -> Batch
Load a batch (shim -> orchestrated load).
Plotting¶
plotutils ¶
Utilities for helping to plot cellpy-data.
SummaryPlotConfig
dataclass
¶
SummaryPlotConfig(x: Optional[str] = None, y: str = 'capacities_gravimetric_coulombic_efficiency', height: Optional[int] = None, width: int = 900, markers: bool = True, title: Optional[str] = None, x_range: Optional[list] = None, y_range: Optional[list] = None, ce_range: Optional[list] = None, norm_range: Optional[list] = None, cv_share_range: Optional[list] = None, split: bool = True, hover_columns: Optional[list] = None, auto_convert_legend_labels: bool = True, backend: Optional[str] = None, share_y: bool = False, rangeslider: bool = False, return_data: bool = False, verbose: bool = False, plotly_template: Optional[str] = None, seaborn_palette: str = 'deep', seaborn_style: str = 'dark', formation_cycles: int = 3, show_formation: bool = True, show_legend: bool = True, x_axis_domain_formation_fraction: float = 0.2, column_separator: float = 0.01, reset_losses: bool = True, link_capacity_scales: bool = False, fullcell_standard_normalization_type: str = 'max', fullcell_standard_normalization_factor: Optional[float] = None, fullcell_standard_normalization_scaler: float = 1.0, fullcell_standard_normalization_cycle_numbers: Optional[list[int]] = None, seaborn_line_hooks: Optional[list[tuple[str, list, dict]]] = None, filters: Optional[dict] = None, nominal_capacity: Optional[float] = None, rate_filter_columns: Optional[Union[str, tuple, list]] = None, additional_kwargs: dict = dict())
Configuration dataclass for summary_plot parameters.
Encapsulates all parameters for summary_plot to improve maintainability and enable easier refactoring.
SummaryPlotInfo ¶
Initialize SummaryPlotInfo.
This class contains information about the summary plot. It is used to store the information about the columns and labels.
Parameters:
-
c(Any) –cellpy object
normalize_col
staticmethod
¶
normalize_col(x: ndarray, normalization_factor: Optional[float] = None, normalization_type: str = 'max', normalization_scaler: float = 1.0, normalization_indexes: list[int] = [1]) -> np.ndarray
Normalize a column.
Parameters:
-
x(ndarray) –column to normalize
-
normalization_factor(Optional[float], default:None) –normalization factor
-
normalization_type(str, default:'max') –normalization type
-
normalization_scaler(float, default:1.0) –normalization scaler
-
normalization_indexes(list[int], default:[1]) –indexes to use for normalization
Normalization types
- divide: divide by normalization factor and then multiply by normalization scaler
- shift-divide: shift by normalization factor and then divide by normalization factor and then multiply by normalization scaler
- multiply: multiply by normalization factor and normalization scaler
- area: divide by area (integrated using trapezoid rule) and then multiply by normalization scaler
- max: divide by maximum value and then multiply by normalization scaler
- on-max: divide by maximum value over normalization factor and then multiply by normalization scaler
- on-cycles: divide by mean value of the cycles in normalization_indexes and then multiply by normalization scaler
- false: no normalization is done
Returns:
-
ndarray–normalized column
create_colormarkerlist ¶
create_colormarkerlist(groups, sub_groups, symbol_label='all', color_style_label='seaborn-colorblind')
Fetch lists with color names and marker types of correct length.
Parameters:
-
groups–list of group numbers (used to generate the list of colors)
-
sub_groups–list of sub-group numbers (used to generate the list of markers).
-
symbol_label–sub-set of markers to use
-
color_style_label–cmap to use for colors
Returns:
-
–
colors (list), markers (list)
create_colormarkerlist_for_journal ¶
create_colormarkerlist_for_journal(journal, symbol_label='all', color_style_label='seaborn-colorblind')
Fetch lists with color names and marker types of correct length for a journal.
Parameters:
-
journal–cellpy journal
-
symbol_label–sub-set of markers to use
-
color_style_label–cmap to use for colors
Returns:
-
–
colors (list), markers (list)
cycle_info_plot ¶
cycle_info_plot(cell, cycle=None, get_axes=False, backend: Optional[str] = None, t_unit='hours', v_unit='V', i_unit='mA', **kwargs)
Show raw data together with step and cycle information.
Draws through prepare → spec → render.
Parameters:
-
cell–cellpy object
-
cycle(int or list or tuple, default:None) –cycle(s) to select (must be int for matplotlib)
-
get_axes(bool, default:False) –return axes (for matplotlib) or figure (for plotly)
-
backend(str, default:None) –"plotly"(default) or"matplotlib". -
t_unit(str, default:'hours') –unit for x-axis (default: "hours")
-
v_unit(str, default:'V') –unit for y-axis (default: "V")
-
i_unit(str, default:'mA') –unit for current (default: "mA")
-
**kwargs–parameters specific to plotting backend.
Returns:
-
–
matplotlib.axesor None (or a figure whenget_axes/ backend semantics require it)
cycles_plot ¶
cycles_plot(c, cycles=None, inter_cycle_shift=True, cycle_mode=None, formation_cycles=3, show_formation=True, mode='gravimetric', method='forth-and-forth', interpolated=True, number_of_points=200, colormap='Blues_r', formation_colormap='autumn', cut_colorbar=True, title=None, figsize=(6, 4), x_range=None, y_range=None, backend: Optional[str] = None, return_figure=None, width=800, height=600, marker_size=5, formation_line_color='rgba(152, 0, 0, .8)', force_colorbar=False, force_nonbar=False, plotly_template=None, seaborn_palette: str = 'deep', seaborn_style: str = 'dark', return_data=False, **kwargs)
Plot the voltage vs. capacity for different cycles of a cell.
This function is meant as an easy way of visualizing the voltage vs. capacity for different cycles of a cell. The cycles are plotted with different colors, and the formation cycles are highlighted with a different colormap. It is not intended to provide you with high quality plots, but rather to give you a quick overview of the data.
Draws through prepare → spec → render.
Parameters:
-
c–cellpy object containing the data to plot.
-
cycles(list, default:None) –List of cycle numbers to plot. If None, all cycles are plotted.
-
inter_cycle_shift(bool, default:True) –Whether to shift the cycles by one. Default is True.
-
cycle_mode(str, default:None) –Mode for the test (anode or other). Default is None (i.e. use the cellpy cell object's cycle_mode).
-
formation_cycles(int, default:3) –Number of formation cycles to highlight. Default is 3.
-
show_formation(bool, default:True) –Whether to show formation cycles. Default is True.
-
mode(str, default:'gravimetric') –Mode for capacity ('gravimetric', 'areal', etc.). Default is 'gravimetric'.
-
method(str, default:'forth-and-forth') –Method for interpolation. Default is 'forth-and-forth'.
-
interpolated(bool, default:True) –Whether to interpolate the data. Default is True.
-
number_of_points(int, default:200) –Number of points for interpolation. Default is 200.
-
colormap(str, default:'Blues_r') –Colormap for the cycles. Default is 'Blues_r'.
-
formation_colormap(str, default:'autumn') –Colormap for the formation cycles. Default is 'autumn'.
-
cut_colorbar(bool, default:True) –Whether to cut the colorbar. Default is True.
-
title(str, default:None) –Title of the plot. If None, the cell name is used.
-
figsize(tuple, default:(6, 4)) –Size of the figure for matplotlib. Default is (6, 4).
-
x_range(list, default:None) –Limits for the x-axis.
-
y_range(list, default:None) –Limits for the y-axis.
-
backend(str, default:None) –"plotly"(default) or"matplotlib". -
return_figure(bool, default:None) –Whether to return the figure object. Default is
Truefor matplotlib andFalsefor plotly (fig.show()). -
width(int, default:800) –Width of the figure for Plotly. Default is 800.
-
height(int, default:600) –Height of the figure for Plotly. Default is 600.
-
marker_size(int, default:5) –Size of the markers for Plotly. Default is 5.
-
formation_line_color(str, default:'rgba(152, 0, 0, .8)') –Color for the formation cycle lines in Plotly. Default is 'rgba(152, 0, 0, .8)'.
-
force_colorbar(bool, default:False) –Whether to force the colorbar to be shown. Default is False.
-
force_nonbar(bool, default:False) –Whether to force the colorbar to be hidden. Default is False.
-
plotly_template(str, default:None) –Plotly template to use (uses default template if None).
-
seaborn_palette(str, default:'deep') –name of the seaborn palette to use (only if seaborn is available).
-
seaborn_style(str, default:'dark') –name of the seaborn style to use (only if seaborn is available).
-
return_data(bool, default:False) –Whether to return the data used for the plot. Default is False.
-
**kwargs–Additional keyword arguments for the plotting backend.
Additional keyword arguments for Plotly
plotly_max_individual_traces_for_lines (int, optional): Maximum number of individual traces (not including formation cycles) for lines in Plotly. Default is 8. plotly_xaxes_kwargs (dict, optional): propagated to plotly.update_xaxes. plotly_yaxes_kwargs (dict, optional): propagated to plotly.update_yaxes. plotly_layout_kwargs (dict, optional): propagated to plotly.update_layout.
Returns:
-
–
The figure is a matplotlib.figure.Figure or a plotly.graph_objects.Figure, depending on the backend used.
-
–
If return_data is True: tuple: (figure, data)
-
–
If return_figure is True: figure: The generated plot figure (same as the return value).
-
Else–None: The plot is shown in the default browser.
dva_plot ¶
dva_plot(cell, cycles=None, direction='both', options=None, *, backend: Optional[str] = None, title=None, colormap='viridis', width=800, height=600, figsize=(6, 4), x_range=None, y_range=None, plotly_template=None, return_data=False, **kwargs)
Plot differential voltage analysis (dV/dQ vs capacity).
Draws through prepare → spec → render. Data come from
cellpy.ica.dvdq; both half-cycles are overlaid when
direction="both" (plotly hover shows charge/discharge).
Parameters:
-
cell–cellpy object.
-
cycles–Cycle number or list (
None= all). -
direction–"charge","discharge", or"both". -
options–Optional
IcaOptions(defaults to DVA-oriented options insidedvdq). -
backend(Optional[str], default:None) –"plotly"(default) or"matplotlib". -
title–Figure title.
-
colormap–Cycle colour map.
-
width, height–Plotly figure size.
-
figsize–Matplotlib figure size.
-
x_range, y_range–Optional axis ranges.
-
plotly_template–Optional plotly template name.
-
return_data–If True, return
(figure, frame). -
**kwargs–Extra knobs (
strict,cycle_mode,number_of_points, and individualIcaOptionsfield overrides).
Returns:
-
–
Plotly or matplotlib figure (or
(figure, frame)whenreturn_data).
ica_plot ¶
ica_plot(cell, cycles=None, direction='both', options=None, *, backend: Optional[str] = None, title=None, colormap='viridis', width=800, height=600, figsize=(6, 4), x_range=None, y_range=None, plotly_template=None, return_data=False, **kwargs)
Plot incremental capacity (dQ/dV vs voltage).
Draws through prepare → spec → render. Data come from
cellpy.ica.dqdv; both half-cycles are overlaid when
direction="both" (plotly hover shows charge/discharge).
Parameters:
-
cell–cellpy object.
-
cycles–Cycle number or list (
None= all). -
direction–"charge","discharge", or"both". -
options–Optional
IcaOptions. -
backend(Optional[str], default:None) –"plotly"(default) or"matplotlib". -
title–Figure title.
-
colormap–Cycle colour map.
-
width, height–Plotly figure size.
-
figsize–Matplotlib figure size.
-
x_range, y_range–Optional axis ranges.
-
plotly_template–Optional plotly template name.
-
return_data–If True, return
(figure, frame). -
**kwargs–Extra knobs (
strict,cycle_mode,number_of_points, and individualIcaOptionsfield overrides).
Returns:
-
–
Plotly or matplotlib figure (or
(figure, frame)whenreturn_data).
notebook_docstring_printer ¶
Decorator that prints the function's docstring when called from a notebook environment.
This decorator checks if the function is being called from a Jupyter notebook or IPython environment and prints the function's docstring if it is.
Parameters:
-
func–The function to decorate
Returns:
-
–
The decorated function
partition_summary_cv_steps ¶
partition_summary_cv_steps(c, x: str, column_set: list, split: bool = False, var_name: str = 'variable', value_name: str = 'value')
Partition the summary data into CV and non-CV steps.
Parameters:
-
c–cellpy object
-
x(str) –x-axis column name
-
column_set(list) –names of columns to include
-
split(bool, default:False) –add additional column that can be used to split the data when plotting.
-
var_name(str, default:'variable') –name of the variable column after melting
-
value_name(str, default:'value') –name of the value column after melting
Returns:
-
–
pandas.DataFrame(melted with columns x, var_name, value_name, and optionally "row" if split is True)
raw_plot ¶
raw_plot(cell, y=None, y_label=None, x=None, x_label=None, title=None, backend: Optional[str] = None, plot_type='voltage-current', double_y=True, cycles=None, max_points: Optional[int] = None, **kwargs)
Plot raw data.
Draws through prepare → spec → render.
Parameters:
-
cell–cellpy object
-
y(str or list, default:None) –y-axis column
-
y_label(str or list, default:None) –label for y-axis
-
x(str, default:None) –x-axis column
-
x_label(str, default:None) –label for x-axis
-
title(str, default:None) –title of the plot
-
backend(str, default:None) –"plotly"(default) or"matplotlib". -
plot_type(str, default:'voltage-current') –type of plot (defaults to "voltage-current") (overrides given y if y is not None), currently only "voltage-current", "raw", "capacity", "capacity-current", and "full" is supported.
-
double_y(bool, default:True) –use double y-axis (only for matplotlib and when plot_type with 2 rows is used)
-
cycles(int or list, default:None) –only plot these cycle numbers (defaults to all).
-
max_points(int, default:None) –thin the data to roughly this many points, keeping the minimum and maximum of every trace within each bucket so spikes survive. Defaults to no thinning.
-
**kwargs–additional parameters for the plotting backend
Returns:
-
–
matplotlibfigure orplotlyfigure
save_image_files ¶
save_image_files(figure: Any, name: str = 'my_figure', scale: float = 3.0, dpi: int = 300, backend: str = 'plotly', formats: Optional[list] = None)
Save to image files (png, svg, json/pickle).
Notes
This method requires kaleido for the plotly backend.
Notes
Exporting to json is only applicable for the plotly backend.
Parameters:
-
figure(fig - object) –The figure to save.
-
name(Path or str, default:'my_figure') –The path of the file (without extension).
-
scale(float, default:3.0) –The scale of the image.
-
dpi(int, default:300) –The dpi of the image.
-
backend(str, default:'plotly') –The backend to use (plotly or seaborn/matplotlib).
-
formats(list, default:None) –The formats to save (default: ["png", "svg", "json", "pickle"]).
set_plotly_template ¶
Set the default plotly template.
summary_plot ¶
summary_plot(c, x: Optional[str] = None, y: str = 'capacities_gravimetric_coulombic_efficiency', height: Optional[int] = None, width: int = 900, markers: bool = True, title: Optional[str] = None, x_range: Optional[list] = None, y_range: Optional[list] = None, ce_range: Optional[list] = None, norm_range: Optional[list] = None, cv_share_range: Optional[list] = None, split: bool = True, hover_columns: Optional[list] = None, auto_convert_legend_labels: bool = True, backend: Optional[str] = None, share_y: bool = False, rangeslider: bool = False, return_data: bool = False, verbose: bool = False, plotly_template: Optional[str] = None, seaborn_palette: str = 'deep', seaborn_style: str = 'dark', formation_cycles: int = 3, show_formation: bool = True, show_legend: bool = True, x_axis_domain_formation_fraction: float = 0.2, column_separator: float = 0.01, reset_losses: bool = True, link_capacity_scales: bool = False, fullcell_standard_normalization_type: str = 'max', fullcell_standard_normalization_factor: Optional[float] = None, fullcell_standard_normalization_scaler: float = 1.0, fullcell_standard_normalization_cycle_numbers: Optional[list[int]] = None, seaborn_line_hooks: Optional[list[tuple[str, list, dict]]] = None, filters: Optional[dict] = None, nominal_capacity: Optional[float] = None, rate_filter_columns: Optional[Union[str, tuple, list]] = None, **kwargs) -> Any
Create a summary plot.
Parameters:
-
c–cellpy object
-
x(Optional[str], default:None) –x-axis column (default: 'cycle_index')
-
y(str, default:'capacities_gravimetric_coulombic_efficiency') –y-axis column or column set. Currently, the following predefined sets exists: "voltages", "capacities_gravimetric", "capacities_areal", "capacities_absolute", "capacities_gravimetric_split_constant_voltage", "capacities_areal_split_constant_voltage", "capacities_gravimetric_coulombic_efficiency", "capacities_areal_coulombic_efficiency", "capacities_absolute_coulombic_efficiency", "capacities_gravimetric_with_rate", "capacities_areal_with_rate", "capacities_absolute_with_rate", "fullcell_standard_gravimetric", "fullcell_standard_areal", "fullcell_standard_absolute",
-
height(Optional[int], default:None) –height of the plot (for plotly)
-
width(int, default:900) –width of the plot (for plotly)
-
markers(bool, default:True) –use markers
-
title(Optional[str], default:None) –title of the plot
-
x_range(Optional[list], default:None) –limits for x-axis
-
y_range(Optional[list], default:None) –limits for y-axis
-
ce_range(Optional[list], default:None) –limits for coulombic efficiency (if present)
-
norm_range(Optional[list], default:None) –limits for normalized capacity (if present)
-
cv_share_range(Optional[list], default:None) –limits for cv share (if present)
-
split(bool, default:True) –split the plot
-
hover_columns(Optional[list], default:None) –columns to show in the hover tooltip (only for plotly)
-
auto_convert_legend_labels(bool, default:True) –convert the legend labels to a nicer format.
-
backend(Optional[str], default:None) –plotting backend (
"plotly"or"matplotlib"; default"plotly") -
rangeslider(bool, default:False) –add a range slider to the x-axis (only for plotly)
-
share_y(bool, default:False) –share y-axis (only for plotly)
-
return_data(bool, default:False) –return the data used for plotting
-
verbose(bool, default:False) –print out some extra information to make it easier to find out what to plot next time
-
plotly_template(Optional[str], default:None) –name of the plotly template to use
-
seaborn_palette(str, default:'deep') –name of the seaborn palette to use (matplotlib backend)
-
seaborn_style(str, default:'dark') –name of the seaborn style to use (matplotlib backend)
-
formation_cycles(int, default:3) –number of formation cycles to show
-
show_formation(bool, default:True) –show formation cycles
-
show_legend(bool, default:True) –show the legend
-
x_axis_domain_formation_fraction(float, default:0.2) –fraction of the x-axis domain for the formation cycles (default: 0.2)
-
column_separator(float, default:0.01) –separation between columns when splitting the plot (only for plotly)
-
reset_losses(bool, default:True) –reset the losses to the first cycle (only for fullcell_standard plots)
-
link_capacity_scales(bool, default:False) –link the capacity scales (only for fullcell_standard plots)
-
fullcell_standard_normalization_type(str, default:'max') –normalization type for the fullcell standard plots (capacity retention) (divide, multiply, area, max, on-max, False)
-
fullcell_standard_normalization_factor(Optional[float], default:None) –normalization factor for the fullcell standard plots
-
fullcell_standard_normalization_scaler(float, default:1.0) –scaler for the fullcell standard plots
-
fullcell_standard_normalization_cycle_numbers(Optional[list[int]], default:None) –cycle numbers to use for normalization (only for fullcell_standard plots)
-
seaborn_line_hooks(Optional[list[tuple[str, list, dict]]], default:None) –list of functions to hook into the seaborn lines (e.g. to update the marker_size)
-
filters(Optional[dict], default:None) –optional dict forwarded to
filter_summaryto drop rows from the summary before plotting (e.g.filters={"rate": (0, 0.5)}drops slow-rate characterisation cycles). Seefilter_summaryfor range semantics. -
nominal_capacity(Optional[float], default:None) –optional plain float in
c.cellpy_units.nominal_capacityunits. When given, thecharge_c_rate/discharge_c_ratecolumns are rescaled to use this nominal capacity instead ofc.data.nom_cap(multiplies rates byc.data.nom_cap / nominal_capacity). -
rate_filter_columns(Optional[Union[str, tuple, list]], default:None) –optional override for which rate column(s) the
ratefilter targets. Defaults to both(charge_c_rate, discharge_c_rate); pass a single string (e.g."discharge_c_rate") to filter only one side. -
**kwargs–includes additional parameters for the plotting backend (not properly documented yet).
Returns:
-
Any–if
return_datais True, returns a tuple with the figure and the data used for plotting. -
Any–Otherwise, it returns only the figure. With
backend="plotly"the figure is a -
Any–plotly figure; with
backend="matplotlib"it is a matplotlib figure.
Examples:
Default plot (capacity and Coulombic efficiency vs cycle number)::
>>> from cellpy.utils.plotutils import summary_plot
>>> fig = summary_plot(c)
>>> fig.show()
Plot gravimetric capacity alone, with formation cycles disabled::
>>> fig = summary_plot(c, y="capacities_gravimetric", show_formation=False)
Use the matplotlib backend (seaborn styling), e.g. for an SVG export from a script::
>>> fig = summary_plot(c, y="capacities_gravimetric", backend="matplotlib")
>>> fig.savefig("summary.svg")
Get the prepared DataFrame back together with the figure (useful for custom annotations or follow-up analysis)::
>>> fig, data = summary_plot(c, y="capacities_gravimetric", return_data=True)
>>> data.head()
New *_with_rate y-set adds a C-rate subplot on row 0::
>>> fig = summary_plot(c, y="capacities_gravimetric_with_rate")
Drop slow-rate characterisation cycles (e.g. keep only rows where
both charge_c_rate and discharge_c_rate are above 0.1)::
>>> fig = summary_plot(
... c,
... y="capacities_gravimetric",
... filters={"rate": (0.1, 10.0)},
... )
Same idea using the symmetric {value, delta} form to keep
rows close to a target C/2 rate::
>>> fig = summary_plot(
... c,
... y="capacities_gravimetric_with_rate",
... filters={"rate": {"value": 0.5, "delta": 0.05}},
... )
Filter on the discharge rate only (charge rate is ignored)::
>>> fig = summary_plot(
... c,
... y="capacities_gravimetric",
... filters={"rate": (0.1, 1.0)},
... rate_filter_columns="discharge_c_rate",
... )
Override the nominal capacity used for the C-rate axis without
re-running make_summary. The rate columns are rescaled by
c.data.nom_cap / nominal_capacity; here we both rescale and
filter in the new units::
>>> fig = summary_plot(
... c,
... y="capacities_gravimetric_with_rate",
... nominal_capacity=200.0,
... filters={"rate": (0.1, 5.0)},
... )
The same filter is available without plotting via
filtered_summary (returns a DataFrame copy)::
>>> trimmed = c.filtered_summary(rate=(0.1, 10.0))
Or as a free function on any summary-shaped DataFrame::
>>> from cellpy.filters import filter_summary
>>> trimmed = filter_summary(c.data.summary.reset_index(),
... rate=(0.1, 10.0))
Analysis¶
Incremental capacity analysis lives at cellpy.ica since 2.0;
cellpy.utils.ica re-exports it.
ocv_rlx ¶
MultiCycleOcvFit ¶
Object for performing fitting of multiple cycles.
Remarks
This is only tested for OCV relaxation data for half-cells in anode mode where the OCV relaxation is performed according to the standard protocol implemented at IFE in the battery development group.
If you want to use this for other data or protocols, please report an issue on the GitHub page.
Object for performing fitting of multiple cycles.
Parameters:
-
cellpydata–CellpyCell-object -
cycles(list) –cycles to fit.
-
circuits(int, default:3) –number of circuits to use in fitting.
data
property
writable
¶
Deprecated alias for cell (the held CellpyCell) -- ends the self.data.data.steps double-.data trap.
get_best_fit_parameters_grouped ¶
Returns a dictionary of the best fit.
get_best_fit_parameters_translated ¶
Returns the parameters in 'real units' for the best fit.
get_best_fit_parameters_translated_grouped ¶
Returns the parameters as a dictionary of the 'real units' for the best fit.
plot_summary_translated ¶
Convenience function for plotting the summary of the fit (translated)
run_fitting ¶
Parameters:
-
direction(up | down, default:'up') –what type of ocv relaxation to fit
-
weighted(bool, default:True) –use weighted fitting.
Returns:
-
–
None
summary_translated ¶
Convenience function for creating a dataframe of the summary of the fit (translated)
OcvFit ¶
Bases: object
Class for fitting open circuit relaxation data.
The model is a sum of exponentials and a constant offset (Ohmic resistance). The number of exponentials is set by the number of circuits. The model is: v(t) = v0 + R0 + sum(wi * exp(-t/tau_i)) where v0 is the OCV, wi is the weight of the exponential tau_i is the time constant of the exponential and R0 is the Ohmic resistance.
r is found by calculating v0 / i_start --> err(r)= err(v0) + err(i_start).
c is found from using tau / r --> err(c) = err(r) + err(tau).
The fit is performed by using lmfit.
Attributes:
-
data(cellpydata - object) –The data to be fitted.
-
time(list) –Time measured during relaxation (extracted from data if provided).
-
voltage(list) –Time measured during relaxation (extracted from data if provided).
-
steps(str) –Step information (if data is provided).
-
circuits(int) –The number of circuits to be fitted.
-
weights(list) –The weights of the different circuits.
-
zero_current(float) –Last current observed before turning the current off.
-
zero_voltage(float) –Last voltage observed before turning the current off.
-
model(lmfit - object) –The model used for fitting.
-
params(lmfit - object) –The parameters used for fitting.
-
result(lmfit - object) –The result of the fitting.
-
best_fit_data(list) –The best fit data [x, y_measured, y_fitted].
-
best_fit_parameters(dict) –The best fit parameters.
Remarks
This class does not take advantage of the cellpydata-object. It is primarily used for fitting data that does not originate from cellpy, but it can also be used for fitting cellpy-data.
If you have cellpy-data, you should use the MultiCycleOcvFit class instead.
Initializes the class.
Parameters:
-
circuits(int, default:None) –The number of circuits to be fitted (including R0).
-
direction(str, default:None) –The direction of the relaxation (up or down).
-
zero_current(float, default:0.1) –Last current observed before turning the current off.
-
zero_voltage(float, default:0.05) –Last voltage observed before turning the current off.
run_fit ¶
Performing fit of the OCV steps in the cycles set by set_cycles() from the data set by set_data()
r is found by calculating v0 / i_start → err®= err(v0) + err(i_start).
c is found from using tau / r → err© = err® + err(tau).
The resulting best fit parameters are stored in self.result for the given cycles.
Returns:
-
–
None
set_cellpydata ¶
Convenience method for setting the data from a cellpydata-object. Args: cellpydata (CellpyCell): data object from cellreader cycle (int): cycle number to get from CellpyCell object
Remarks
You need to set the direction before calling this method if you don't want to use the default direction (up).
Returns:
-
–
None
fit ¶
Fits the OCV steps in CellpyCell object c.
Parameters:
-
c–CellpyCell object
-
direction–direction of the OCV steps ('up' or 'down')
-
circuits–number of circuits to use (first is IR, rest is RC) in the fitting (min=1, max=4)
-
cycles–list of cycles to fit (if None, all cycles will be used)
-
return_fit_object–if True, returns the MultiCycleOcvFit instance.
Returns:
-
–
pd.DataFrame with the fitted parameters for each cycle if return_fit_object=False,
-
–
else MultiCycleOcvFit instance
select_ocv_points ¶
select_ocv_points(cellpydata, cycles=None, cell_label=None, include_times=True, selection_method='martin', number_of_points=5, interval=10, relative_voltage=False, report_times=False, direction='both')
Select points from the ocvrlx steps.
Parameters:
-
cellpydata–CellpyData-object -
cycles–list of cycle numbers to process (optional)
-
cell_label(str, default:None) –optional, will be added to the frame if given
-
include_times(bool, default:True) –include additional information including times.
-
selection_method(martin | fixed_times, default:'martin') –criteria for selecting points ('martin': select first and last, and then last/2, last/2/2 etc. until you have reached the wanted number of points; 'fixed_times': select first, and then same interval between each subsequent point).
-
number_of_points–number of points you want.
-
interval–interval between each point (in use only for methods where interval makes sense). If it is a list, then number_of_points will be calculated as len(interval) + 1 (and override the set number_of_points).
-
relative_voltage–set to True if you would like the voltage to be relative to the voltage before starting the ocv rlx step. Defaults to False. Remark that for the initial rxl step (when you just have put your cell on the tester) does not have any prior voltage. The relative voltage will then be versus the first measurement point.
-
report_times–also report the ocv rlx total time if True (defaults to False)
-
direction((up, down or both), default:'both') –select "up" if you would like to process only the ocv rlx steps where the voltage is relaxing upwards and vice versa. Defaults to "both".
Returns:
-
–
pandas.DataFrame(and anotherpandas.DataFrameif return_times is True)
helpers ¶
add_c_rate ¶
Adds C-rates to the step table data frame.
This functionality is now also implemented as default when creating the step_table (make_step_table). However, it is kept here if you would like to recalculate the C-rates, for example if you want to use another nominal capacity or if you would like to have more than one column with C-rates.
Parameters:
-
cell(CellpyCell) –cell object
-
nom_cap(float, default:None) –nominal capacity to use for estimating C-rates. Defaults to the nominal capacity defined in the cell object (this is typically set during creation of the CellpyData object based on the value given in the parameter file).
-
column_name(str, default:None) –name of the new column. Uses the name defined in cellpy.parameters.internal_settings as default.
Returns:
-
–
data object.
add_normalized_capacity ¶
Add normalized capacity to the summary.
Parameters:
-
cell(CellpyCell) –cell to add normalized capacity to.
-
norm_cycles(list of ints, default:None) –the cycles that will be used to find the normalization factor from (averaging their capacity)
-
individual_normalization(bool, default:False) –find normalization factor for both the charge and the discharge if true, else use normalization factor from charge on both charge and discharge.
-
scale(float, default:1.0) –scale of normalization (default is 1.0).
Returns:
-
–
cell (CellpyData) with added normalization capacity columns in
-
–
the summary.
add_normalized_cycle_index ¶
Adds normalized cycles to the summary data frame.
This functionality is now also implemented as default when creating the summary (make_summary). However, it is kept here if you would like to redo the normalization, for example if you want to use another nominal capacity or if you would like to have more than one normalized cycle index.
Parameters:
-
summary(DataFrame) –data summary
-
nom_cap(float) –nominal capacity to use when normalizing.
-
column_name(str, default:None) –name of the new column. Uses the name defined in cellpy.parameters.internal_settings as default.
Returns:
-
–
data object now with normalized cycle index in its summary.
collect_frames ¶
collect_frames(frames, group_it: bool, hdr_norm_cycle: str, keys: list, normalize_cycles: bool, hooks: list = None)
Helper function for concat_summaries.
concat_summaries ¶
concat_summaries(b: Batch, max_cycle=None, rate=None, on='charge', columns=None, column_names=None, normalize_capacity_on=None, scale_by=None, nom_cap=None, normalize_cycles=False, group_it=False, custom_group_labels=None, rate_std=None, rate_column=None, inverse=False, inverted=False, key_index_bounds=None, pages=None, recalc_summary_kwargs=None, recalc_step_table_kwargs=None, only_selected=False, experimental_feature_cell_selector=None, partition_by_cv=False, replace_inf_with_nan=True, individual_summary_hooks=None, concatenated_summary_hooks=None, drop_columns=None, average_method='mean', replace_extremes_with_nan=True, low_limit=-1000000.0, high_limit=1000000.0, *args, **kwargs) -> pd.DataFrame
Merge all summaries in a batch into a gigantic summary data frame.
Parameters:
-
b(cellpy.batch object) –the batch with the cells.
-
max_cycle(int, default:None) –drop all cycles above this value.
-
rate(float, default:None) –filter on rate (C-rate)
-
on(str or list of str, default:'charge') –only select cycles if based on the rate of this step-type (e.g. on="charge").
-
columns(list, default:None) –selected column(s) (using cellpy attribute name) [defaults to "charge_capacity_gravimetric"]
-
column_names(list, default:None) –selected column(s) (using exact column name)
-
normalize_capacity_on(list, default:None) –list of cycle numbers that will be used for setting the basis of the normalization (typically the first few cycles after formation)
-
scale_by(float or str, default:None) –scale the normalized data with nominal capacity if "nom_cap", or given value (defaults to one).
-
nom_cap(float, default:None) –nominal capacity of the cell
-
normalize_cycles(bool, default:False) –perform a normalization of the cycle numbers (also called equivalent cycle index)
-
group_it(bool, default:False) –if True, average pr group.
-
partition_by_cv(bool, default:False) –if True, partition the data by cv_step.
-
custom_group_labels(dict, default:None) –dictionary of custom labels (key must be the group number/name).
-
rate_std(float, default:None) –allow for this inaccuracy when selecting cycles based on rate
-
rate_column(str, default:None) –name of the column containing the C-rates.
-
inverse(bool, default:False) –select steps that do not have the given C-rate.
-
inverted(bool, default:False) –select cycles that do not have the steps filtered by given C-rate.
-
key_index_bounds(list, default:None) –used when creating a common label for the cells by splitting the label on '_' and combining again using the key_index_bounds as start and end index.
-
pages(DataFrame, default:None) –alternative pages (journal) of the batch object (if not given, it will use the pages from the batch object).
-
recalc_summary_kwargs(dict, default:None) –keyword arguments to be used when recalculating the summary. If not given, it will not recalculate the summary.
-
recalc_step_table_kwargs(dict, default:None) –keyword arguments to be used when recalculating the step table. If not given, it will not recalculate the step table.
-
only_selected(bool, default:False) –only use the selected cells.
-
experimental_feature_cell_selector(list, default:None) –list of cell names to select.
-
partition_by_cv(bool, default:False) –if True, partition the data by cv_step.
-
replace_inf_with_nan(bool, default:True) –if True, replace inf with nan in the summary data.
-
individual_summary_hooks(list, default:None) –list of functions to be applied to the individual summary data.
-
concatenated_summary_hooks(list, default:None) –list of functions to be applied to the concatenated summary data (passed to the collect_frames function).
-
drop_columns(list, default:None) –list of columns to drop before concatenation.
-
average_method(str, default:'mean') –method to be used when averaging the summary data. Remark that for backward compatibility, the column name will be "mean" regardless of the actual method used.
-
replace_extremes_with_nan(bool, default:True) –if True, replace values outside the range [low_limit, high_limit] with nan in the summary data.
-
low_limit(float, default:-1000000.0) –lower limit for replacing extremes with nan if replace_extremes_with_nan is True.
-
high_limit(float, default:1000000.0) –upper limit for replacing extremes with nan if replace_extremes_with_nan is True.
-
remove_last(bool) –if True, remove the last cycle from the summary data.
-
*args,**kwargs–additional arguments to be passed to the hooks.
Returns:
-
DataFrame–pandas.DataFrame
concatenate_summaries ¶
concatenate_summaries(b: Batch, max_cycle=None, rate=None, on='charge', columns=None, column_names=None, normalize_capacity_on=None, scale_by=None, nom_cap=None, normalize_cycles=False, group_it=False, custom_group_labels=None, rate_std=None, rate_column=None, inverse=False, inverted=False, key_index_bounds=None) -> pd.DataFrame
Merge all summaries in a batch into a gigantic summary data frame.
Parameters:
-
b(cellpy.batch object) –the batch with the cells.
-
max_cycle(int, default:None) –drop all cycles above this value.
-
rate(float, default:None) –filter on rate (C-rate)
-
on(str or list of str, default:'charge') –only select cycles if based on the rate of this step-type (e.g. on="charge").
-
columns(list, default:None) –selected column(s) (using cellpy attribute name) [defaults to "charge_capacity_gravimetric"]
-
column_names(list, default:None) –selected column(s) (using exact column name)
-
normalize_capacity_on(list, default:None) –list of cycle numbers that will be used for setting the basis of the normalization (typically the first few cycles after formation)
-
scale_by(float or str, default:None) –scale the normalized data with nominal capacity if "nom_cap", or given value (defaults to one).
-
nom_cap(float, default:None) –nominal capacity of the cell
-
normalize_cycles(bool, default:False) –perform a normalization of the cycle numbers (also called equivalent cycle index)
-
group_it(bool, default:False) –if True, average pr group.
-
custom_group_labels(dict, default:None) –dictionary of custom labels (key must be the group number/name).
-
rate_std(float, default:None) –allow for this inaccuracy when selecting cycles based on rate
-
rate_column(str, default:None) –name of the column containing the C-rates.
-
inverse(bool, default:False) –select steps that do not have the given C-rate.
-
inverted(bool, default:False) –select cycles that do not have the steps filtered by given C-rate.
-
key_index_bounds(list, default:None) –used when creating a common label for the cells by splitting and combining from key_index_bound[0] to key_index_bound[1].
Returns:
-
DataFrame–pandas.DataFrame
create_group_names ¶
Helper function for concat_summaries.
The prioritisation of methods for creating the group name is as follows: 1. custom_group_labels (if given) 2. group_label in pages (if given) 3. key_index_bounds and keys_sub (if no other option is available)
Parameters:
-
custom_group_labels(dict) –dictionary of custom labels (key must be the group number).
-
gno(int) –group number.
-
key_index_bounds(list) –used when creating a common label for the cells by splitting the label on '_' and combining again using the key_index_bounds as start and end index.
-
keys_sub(list) –list of keys.
-
pages(DataFrame) –pages (journal) of the batch object. If the column "group_label" is present, it will be used to create the group name.
create_rate_column ¶
Adds a rate column to the dataframe (steps).
filter_cells ¶
Filter cells based on some criteria.
This is a helper function that can be used to filter cells based on some criteria. It is not very flexible, but it is easy to use.
Returns:
-
–
a list of cell names that passed the criteria.
load_and_save_resfile ¶
Load a raw data file and save it as cellpy-file.
Parameters:
-
mass(float, default:1.0) –active material mass [mg].
-
outdir(path, default:None) –optional, path to directory for saving the hdf5-file.
-
outfile(str, default:None) –optional, name of hdf5-file.
-
filename(str) –name of the resfile.
Returns:
-
out_file_name(str) –name of saved file.
remove_first_cycles_from_summary ¶
Remove last rows after given cycle number
remove_last_cycles_from_summary ¶
Remove last rows after given cycle number
remove_outliers_from_summary_on_index ¶
remove_outliers_from_summary_on_nn_distance ¶
Remove outliers with missing neighbours.
Parameters:
-
s(DataFrame) –summary frame
-
distance(float, default:0.7) –cut-off (all cycles that have a closest neighbour further apart this number will be removed)
-
filter_cols(list, default:None) –list of column headers to perform the filtering on (defaults to charge and discharge capacity)
-
freeze_indexes(list, default:None) –list of cycle indexes that should never be removed (defaults to cycle 1)
Returns:
-
–
filtered summary (pandas.DataFrame)
Returns:
remove_outliers_from_summary_on_value ¶
Remove outliers based highest and lowest allowed value
Parameters:
-
s(DataFrame) –summary frame
-
low(float, default:0.0) –low cut-off (all cycles with values below this number will be removed)
-
high(float, default:7000) –high cut-off (all cycles with values above this number will be removed)
-
filter_cols(list, default:None) –list of column headers to perform the filtering on (defaults to charge and discharge capacity)
-
freeze_indexes(list, default:None) –list of cycle indexes that should never be removed (defaults to cycle 1)
Returns:
-
–
filtered summary (pandas.DataFrame)
Returns:
remove_outliers_from_summary_on_window ¶
remove_outliers_from_summary_on_window(s, window_size=3, cut=0.1, iterations=1, col_name=None, freeze_indexes=None)
Removes outliers based on neighbours
remove_outliers_from_summary_on_zscore ¶
Remove outliers based on z-score.
Parameters:
-
s(DataFrame) –summary frame
-
zscore_limit(int, default:4) –remove outliers outside this z-score limit
-
filter_cols(list, default:None) –list of column headers to perform the filtering on (defaults to charge and discharge capacity)
-
freeze_indexes(list, default:None) –list of cycle indexes that should never be removed (defaults to cycle 1)
Returns:
-
–
filtered summary (pandas.DataFrame)
select_summary_based_on_rate ¶
select_summary_based_on_rate(cell, rate=None, on=None, rate_std=None, rate_column=None, inverse=False, inverted=False, fix_index=True, partition_by_cv=False)
Select only cycles charged or discharged with a given rate.
Parameters:
-
rate(float, default:None) –the rate to filter on. Remark that it should be given as a float, i.e. you will have to convert from C-rate to the actual numeric value. For example, use rate=0.05 if you want to filter on cycles that has a C/20 rate.
-
on(str, default:None) –only select cycles if based on the rate of this step-type (e.g. on="charge").
-
rate_std(float, default:None) –allow for this inaccuracy in C-rate when selecting cycles
-
rate_column(str, default:None) –column header name of the rate column,
-
inverse(bool, default:False) –select steps that do not have the given C-rate.
-
inverted(bool, default:False) –select cycles that do not have the steps filtered by given C-rate.
-
fix_index(bool, default:True) –automatically set cycle indexes as the index for the summary dataframe if not already set.
Returns:
-
–
filtered summary (Pandas.DataFrame).
update_journal_cellpy_data_dir ¶
Update the path in the pages (batch) from one type of OS to another.
I use this function when I switch from my work PC (windows) to my home computer (mac).
Parameters:
-
pages–the (batch.experiment.)journal.pages object (pandas.DataFrame)
-
new_path–the base path (uses config.paths.cellpydatadir if not given)
-
from_path–type of path to convert from.
-
to_path–type of path to convert to.
Returns:
-
–
journal.pages (pandas.DataFrame)
yank_after ¶
Cut all cycles after a given cycle index number.
Parameters:
-
b(batch object) –the batch object to perform the cut on.
-
last (int or dict {cell_name–last index}): the last cycle index to keep (if dict: use individual last indexes for each cell).
-
keep_old(bool, default:False) –keep the original batch object and return a copy instead.
Returns:
-
–
batch object if keep_old is True, else None
yank_before ¶
Cut all cycles before a given cycle index number.
Parameters:
-
b(batch object) –the batch object to perform the cut on.
-
first (int or dict {cell_name–first index}): the first cycle index to keep (if dict: use individual first indexes for each cell).
-
keep_old(bool, default:False) –keep the original batch object and return a copy instead.
Returns:
-
–
batch object if keep_old is True, else None
yank_outliers ¶
yank_outliers(b: Batch, zscore_limit=None, low=0.0, high=7000.0, filter_cols=None, freeze_indexes=None, remove_indexes=None, remove_last=False, iterations=1, zscore_multiplyer=1.3, distance=None, window_size=None, window_cut=0.1, keep_old=False)
Remove outliers from a batch object.
Parameters:
-
b(cellpy.utils.batch object) –the batch object to perform filtering one (required).
-
zscore_limit(int, default:None) –will filter based on z-score if given.
-
low(float, default:0.0) –low cut-off (all cycles with values below this number will be removed)
-
high(float, default:7000.0) –high cut-off (all cycles with values above this number will be removed)
-
filter_cols(str, default:None) –what columns to filter on.
-
freeze_indexes(list, default:None) –indexes (cycles) that should never be removed.
-
remove_indexes(dict or list, default:None) –if dict, look-up on cell label, else a list that will be the same for all
-
remove_last(dict or bool, default:False) –if dict, look-up on cell label.
-
iterations(int, default:1) –repeat z-score filtering if
zscore_limitis given. -
zscore_multiplyer(int, default:1.3) –multiply
zscore_limitwith this number between each z-score filtering (should usually be less than 1). -
distance(float, default:None) –nearest neighbour normalised distance required (typically 0.5).
-
window_size(int, default:None) –number of cycles to include in the window.
-
window_cut(float, default:0.1) –cut-off.
-
keep_old(bool, default:False) –perform filtering of a copy of the batch object (not recommended at the moment since it then loads the full cellpyfile).
Returns:
-
–
if keep_old: new cellpy.utils.batch object.
-
else–dictionary of removed cycles
Collectors (shim)¶
Re-exports cellpy.collect.
collectors ¶
Deprecated shim: cellpy.utils.collectors -> collect.
The collector subsystem was redesigned and now lives in collect
(options / collection / summary / curves / ica / collector). The legacy
BatchCollector family and the *_collector functions -- built on the
"elevated arguments" machinery (~20 parameters redeclared per subclass and
merged through three priority layers) -- are removed in 2.1: this module
keeps the import path alive but the old entry points raise, pointing at their
collect replacements.
The shared figure/label/drawing helpers (load_figure & friends,
legend_replacer/remove_markers, collected_plot/_select_direction)
are still re-exported from here -- they are canonical single copies owned by
plotting, unrelated to the collector classes.
BatchCyclesCollector ¶
BatchICACollector ¶
BatchSummaryCollector ¶
collected_plot ¶
collected_plot(frame: Any, *, family_kind: str = 'cycles', layout: Optional[str] = None, kind: Optional[str] = None, backend: str = 'plotly', method: Optional[str] = None, plot_type: Optional[str] = None, spread: bool = False, **opts: Any) -> Any
Plot an already-collected tidy multi-cell frame.
Parameters:
-
frame(Any) –long/tidy frame with
cell/group/sub_groupas needed. -
family_kind(str, default:'cycles') –summary|cycles|ica|dva(selects column defaults). -
layout(Optional[str], default:None) –per_cell|per_cycle|summary. -
kind(Optional[str], default:None) –line|film|spread. -
backend(str, default:'plotly') –plotly(primary) orseaborn/matplotlib(best-effort). -
method / plot_type–legacy collector knobs (mapped to layout/kind).
-
spread(bool, default:False) –legacy flag →
kind="spread". -
**opts(Any, default:{}) –forwarded to the collected renderers (cycles, labels, sizes, …). For
family_kind="summary"(Plotly):share_y/match_axescontrol shared vs independent facet y-scales (default independent);y_rangesmaps variable name →[lo, hi]for per-panel limits. App chrome (#801):plotly_template,layout_updates,y_label_mapper(pretty labels with units by default),height/height_per_panel/figure_border_height. Cycles / ICA (#820): Plotly facet strips default toCycle N/ cell label (preferlayout=over legacymethod="fig_pr_*").layout="per_cell"colours by cycle and follows the shared legend-vs-colorbar policy (#928): more thanlegend_cycle_limitcycles (default 8) get a colorbar instead of a long legend;force_colorbar/force_legendoverride.
Returns:
-
Any–Backend-native figure object.
legend_replacer ¶
Replace a "group,subgroup" legend label with the cell name.
Plotly names a trace after the columns it was grouped by, so a batch figure
ends up with legends like "2,1". This looks the pair up in the journal
and substitutes the cell name, in the legend and in the hover text.
Parameters:
-
trace–the plotly trace to update, in place.
-
df–journal frame carrying group / sub-group / cell columns.
-
group_legends–put every sub-group of a group in one legend entry.
-
inverted_mode–the label reads
"subgroup,group"rather than"group,subgroup".
Returns:
-
–
The trace, updated.
load_figure ¶
Load a figure saved by cellpy.
Parameters:
-
filename–the file to read.
-
backend–"plotly","matplotlib"or"seaborn"(an alias for matplotlib). Inferred from the suffix when not given.
Returns:
-
–
The figure, or
Noneif it could not be loaded.
load_matplotlib_figure ¶
Unpickle a matplotlib figure.
Parameters:
-
filename–the pickle written by
save_matplotlib_figure. -
create_new_manager–attach a canvas manager so the figure can be shown.
load_plotly_figure ¶
Read a plotly figure from JSON.
Returns None — rather than raising — when plotly is not installed or
the file cannot be read, which is what the plotutils copy always did.
make_matplotlib_manager ¶
Attach a fresh canvas manager to an unpickled figure.
An unpickled figure has no manager, so it cannot be shown. Borrowing one from a throwaway figure is the standard workaround (https://stackoverflow.com/a/54579616/8508004).
save_matplotlib_figure ¶
Pickle a matplotlib figure to filename.