Skip to content

Public API

Symbols below match cellpycore.__all__ — the supported top-level import surface.

cellpy-core: the core summarization engine for battery-cycling raw data.

The public, stable surface is the curated set of names re-exported here: the cell classes (CellpyCellCore, its legacy bridge OldCellpyCellCore), the Data container, the engine entry points (make_step_table, add_step_c_rate, make_summary), the column-header schema types, and the package exceptions. Everything else (units, timestamps, legacy, metadata, testing ...) remains importable as submodules but is not part of the guaranteed top-level API.

CellpyCellCore

CellpyCellCore(initialize: bool = False, debug: bool = False)

Native orchestration class for the cellpy-core summarization engine.

Primary entry point for the full cellpy package and for slim standalone consumers. Attach a native-schema polars raw frame to a Data object, then run the step-table and summary pipeline without the legacy pandas / Headers* bridge (OldCellpyCellCore).

The cell holds the column-header schema (raw_cols, cycle_cols, step_cols), exposes data and cycle_mode, and delegates computation to summarizers through make_core_step_table, make_core_summary, and add_scaled_summary_columns. Subclass to add application-specific helpers (cached views, loaders, etc.) while reusing the engine wiring.

Attributes:

  • raw_cols (Cols) –

    Raw-frame column names (default config.RawCols).

  • cycle_cols (Cols) –

    Per-cycle summary column names (default config.CycleCols).

  • step_cols (Cols) –

    Step-table column names (default config.StepCols).

  • data (Data) –

    The attached Data instance (raises NoDataFound when unset).

  • cycle_mode (Optional[str]) –

    Charge/discharge convention (e.g. "anode" for anodehalf-cells). When data is attached, read/write goes through data.meta_test_dependent; otherwise the value is kept on the cell.

  • schema (Schema) –

    Bundled config.Schema built from the three *_cols objects.

Note

Processing order matters: run make_core_step_table before make_core_summary (the summary engine reads data.steps). cycle_mode controls coulombic-efficiency direction and the default capacity column in add_scaled_summary_columns. Unset cycle_mode maps to normal convention; set "anode" explicitly for half-cells.

Example

Basic pipeline::

from cellpycore import CellpyCellCore, Data

cell = CellpyCellCore()
cell.data = Data.from_raw_frame(raw_polars_frame)
cell.cycle_mode = "anode"  # anode half-cell; omit for normal convention

data = cell.make_core_step_table(cell.data, nom_cap_abs=1.0)
data = cell.make_core_summary(data)
data = cell.add_scaled_summary_columns(
    data,
    nom_cap_abs=1.0,
    normalization_cycles=None,
    specific_conversion_factors={"gravimetric": f_g, "areal": f_a},
)

Subclassing for custom helpers::

from functools import cached_property

from cellpycore import CellpyCellCore

class MyCell(CellpyCellCore):
    @cached_property
    def tests(self):
        return build_tests_summary(self.data)

# Note: build_tests_summary is a custom function that builds a summary frame for the tests.
# It is currently not part of cellpy core, but is on the roadmap to be added.

Parameters:

  • initialize (bool, default: False ) –

    set to True if you want to initialize the cellpy object with an empty Data instance.

  • debug (bool, default: False ) –

    set to True if you want to see debug messages.

data property writable

data: Data

Returns the DataSet instance.

Returns:

  • Data

    DataSet instance.

Raises:

  • NoDataFound

    If the CellpyCell does not have any data.

schema property

schema: Schema

The column-header schema for this cell.

Bundles the raw / cycle (summary) / step header objects so the summary and step engine can read their column names from an injected object instead of module-level globals. Built on access so subclass overrides of raw_cols / cycle_cols / step_cols (e.g. the legacy bridge) are always reflected.

add_scaled_summary_columns

add_scaled_summary_columns(data: Data, nom_cap_abs: float, normalization_cycles: Union[Sequence, int, None], step_txt: Optional[str] = None, specifics: Optional[List[str]] = None, specific_conversion_factors: Optional[dict] = None, cell_meta: Optional[CellMeta] = None, *, specific_converters: Optional[dict] = None) -> Data

Add specific summary columns to the summary.

Parameters:

  • data (Data) –

    The data to add the specific summary columns to.

  • nom_cap_abs (float) –

    The nominal capacity of the cell.

  • normalization_cycles (Union[Sequence, int, None]) –

    The number of cycles to normalize the data by.

  • step_txt (Optional[str], default: None ) –

    The step text to use (charge or discharge capacity, will pick 'first' based on cycle mode if not provided)

  • specifics (Optional[List[str]], default: None ) –

    The specifics to add.

  • specific_conversion_factors (Optional[dict], default: None ) –

    Mapping of mode -> conversion factor supplied by value by the caller (so this method needs no unit handling). If not provided, the factors are computed lazily via the units helper using self.cellpy_units as a fallback (legacy / standalone).

  • cell_meta (Optional[CellMeta], default: None ) –

    Optional CellMeta supplying geometry for the units fallback when specific_conversion_factors is omitted. Bare Data without specific_conversion_factors and without geometry (via cell_meta or attrs on data) raises ValueError.

  • specific_converters (Optional[dict], default: None ) –

    Deprecated alias for specific_conversion_factors.

Returns:

  • Data

    The data with the specific summary columns added.

initialize

initialize()

Initialize the CellpyCell object with empty Data instance.

make_core_step_table

make_core_step_table(data: Data, raw_limits: Optional[dict] = None, step_specifications=None, short: bool = False, override_step_types: Optional[dict] = None, override_raw_limits: Optional[dict] = None, usteps: bool = False, nom_cap_abs: Optional[float] = None, skip_steps: Optional[Sequence] = None, sort_rows: bool = True, from_data_point: Optional[int] = None, *, nom_cap: Optional[float] = None) -> Union[Data, DataFrame]

Make the core step table.

Delegates to summarizers.make_step_table using this cell's schema, then appends the per-step C-rate via summarizers.add_step_c_rate (the downstream summary extras, e.g. c_rates_to_summary, need it). The instrument resolution limits (raw_limits) and the absolute nominal capacity (nom_cap_abs, for the C-rate) are supplied by the caller.

Parameters:

  • data (Data) –

    The data to make the step table from.

  • raw_limits (Optional[dict], default: None ) –

    The instrument resolution limits. If None, the summarizer default (DEFAULT_RAW_LIMITS) is used.

  • step_specifications

    Optional explicit step specifications.

  • short (bool, default: False ) –

    Whether step specifications are in short format.

  • override_step_types (Optional[dict], default: None ) –

    Override the detected step types.

  • override_raw_limits (Optional[dict], default: None ) –

    Override individual raw limits.

  • usteps (bool, default: False ) –

    Whether to investigate all (sub-)steps within a cycle.

  • nom_cap_abs (Optional[float], default: None ) –

    Absolute nominal capacity used for the C-rate (default 1.0).

  • skip_steps (Optional[Sequence], default: None ) –

    Step numbers to skip.

  • sort_rows (bool, default: True ) –

    Whether to sort the rows after processing.

  • from_data_point (Optional[int], default: None ) –

    First data point to use (returns a DataFrame when set).

  • nom_cap (Optional[float], default: None ) –

    Deprecated alias for nom_cap_abs.

Returns:

  • Union[Data, DataFrame]

    Data object with the step table, or a DataFrame when from_data_point

  • Union[Data, DataFrame]

    is given.

make_core_summary

make_core_summary(data: Data, find_ir: bool = True, final_data_points: Optional[Iterable[int]] = None, current_conversion_factor: float = 1.0, ir_extractor: Optional[Callable] = None, exclude_step_types: Optional[Iterable[str]] = None) -> Data

Make the core summary.

Note

The native engine always emits the clean CycleCols subset including the end potentials; the legacy-only find_end_voltage / select_columns knobs live on the bridge (OldCellpyCellCore.make_core_summary).

Parameters:

  • data (Data) –

    The data to make the summary from.

  • find_ir (bool, default: True ) –

    Whether to find the IR.

  • final_data_points (Optional[Iterable[int]], default: None ) –

    The final data point for each cycle to use for the selector.

  • current_conversion_factor (float, default: 1.0 ) –

    Precomputed factor that converts the raw current unit to the desired output current unit for the C-rate columns (by value; default 1.0 = no conversion).

  • ir_extractor (Optional[Callable], default: None ) –

    Optional SummaryExtractor controlling how the per-cycle internal-resistance columns are derived. Defaults to extractors.LastIRExtractor when None.

  • exclude_step_types (Optional[Iterable[str]], default: None ) –

    Optional step-type prefixes to exclude from the summary (e.g. ["cv_"]); forwarded to summarizers.make_summary (issue #54).

Returns:

  • Data

    Data object with the summary.

merge_core_data

merge_core_data(left: Data, right: Data, *, renumber_cycles: bool = True, allow_duplicate_test_id: bool = False) -> Data

Merge two Data objects via merge_data using this cell's schema.

Parameters:

  • left (Data) –

    First dataset.

  • right (Data) –

    Second dataset, appended after left.

  • renumber_cycles (bool, default: True ) –

    Offset right-side cycle numbers and carry cumulative summary values forward when True (default).

  • allow_duplicate_test_id (bool, default: False ) –

    Reassign colliding right-side test_id values when True.

Returns:

  • Data

    A new merged Data object. Inputs are not modified.

update_core_data

update_core_data(data: Data, new_raw, *, nom_cap_abs: float = 1.0, refresh_derived: bool = True, find_ir: bool = True, current_conversion_factor: float = 1.0, nom_cap: Optional[float] = None, **kwargs) -> Data

Incrementally update Data via update_data using this cell's schema.

Parameters:

  • data (Data) –

    Processed data to update.

  • new_raw

    New raw rows to append.

  • nom_cap_abs (float, default: 1.0 ) –

    Absolute nominal capacity for per-step C-rate.

  • refresh_derived (bool, default: True ) –

    When True (default), run c_rates_to_summary and ir_to_summary after rebuilding the summary (mirrors make_core_summary extras).

  • find_ir (bool, default: True ) –

    Whether to add IR columns when refresh_derived is True.

  • current_conversion_factor (float, default: 1.0 ) –

    Current-unit factor for C-rate columns.

  • nom_cap (Optional[float], default: None ) –

    Deprecated alias for nom_cap_abs.

  • **kwargs

    Forwarded to update_data / make_step_table.

Returns:

  • Data

    A new updated Data object. The input is not modified.

OldCellpyCellCore

OldCellpyCellCore(*args, **kwargs)

Bases: CellpyCellCore

Legacy CellpyCellCore class to make it easier to migrate to cellpy core.

data property writable

data: Data

Returns the DataSet instance.

Returns:

  • Data

    DataSet instance.

Raises:

  • NoDataFound

    If the CellpyCell does not have any data.

schema property

schema: Schema

The column-header schema for this cell.

Bundles the raw / cycle (summary) / step header objects so the summary and step engine can read their column names from an injected object instead of module-level globals. Built on access so subclass overrides of raw_cols / cycle_cols / step_cols (e.g. the legacy bridge) are always reflected.

add_scaled_summary_columns

add_scaled_summary_columns(data: Data, nom_cap_abs: float, normalization_cycles: Union[Sequence, int, None], step_txt: Optional[str] = None, specifics: Optional[List[str]] = None, specific_conversion_factors: Optional[dict] = None, cell_meta: Optional[CellMeta] = None, *, specific_converters: Optional[dict] = None) -> Data

Legacy-bridge add_scaled_summary_columns (pandas<->polars seam).

The native helpers are polars-native on the native schema, but cellpy calls this on the legacy pandas summary. So this bridges: legacy pandas summary -> native polars -> native equivalent_cycles / generate_specific -> legacy pandas, mapping the produced specific columns back to legacy names.

initialize

initialize()

Initialize the CellpyCell object with empty Data instance.

make_core_step_table

make_core_step_table(data: Data, raw_limits: Optional[dict] = None, step_specifications=None, short: bool = False, override_step_types: Optional[dict] = None, override_raw_limits: Optional[dict] = None, usteps: bool = False, add_c_rate: bool = True, nom_cap: Optional[float] = None, skip_steps: Optional[Sequence] = None, sort_rows: bool = True, from_data_point: Optional[int] = None) -> Union[Data, DataFrame]

Build the step table via the polars engine, in/out in legacy form.

See the bridge note above. Returns a pandas frame with legacy HeadersStepTable columns (or that frame directly when from_data_point is given).

make_core_summary

make_core_summary(data: Data, find_ir: bool = True, find_end_voltage: bool = False, select_columns: bool = True, final_data_points: Optional[Iterable[int]] = None, current_conversion_factor: float = 1.0, ir_extractor: Optional[Callable] = None, exclude_step_types: Optional[Iterable[str]] = None) -> Data

Build the per-cycle summary via the polars engine, in/out in legacy form.

Runs the native make_summary engine plus the now-native polars C-rate / IR helpers, renames native->legacy, then adds the remaining pandas-only legacy cruft to reproduce the legacy HeadersSummary frame.

ir_extractor is forwarded to summarizers.ir_to_summary (defaults to extractors.LastIRExtractor when None). exclude_step_types is forwarded to summarizers.make_summary (step-type prefixes whose capacity contributions are subtracted from the summary, issue #54).

merge_core_data

merge_core_data(left: Data, right: Data, *, renumber_cycles: bool = True, allow_duplicate_test_id: bool = False) -> Data

Merge two Data objects via merge_data using this cell's schema.

Parameters:

  • left (Data) –

    First dataset.

  • right (Data) –

    Second dataset, appended after left.

  • renumber_cycles (bool, default: True ) –

    Offset right-side cycle numbers and carry cumulative summary values forward when True (default).

  • allow_duplicate_test_id (bool, default: False ) –

    Reassign colliding right-side test_id values when True.

Returns:

  • Data

    A new merged Data object. Inputs are not modified.

update_core_data

update_core_data(data: Data, new_raw, *, nom_cap_abs: float = 1.0, refresh_derived: bool = True, find_ir: bool = True, current_conversion_factor: float = 1.0, nom_cap: Optional[float] = None, **kwargs) -> Data

Incrementally update Data via update_data using this cell's schema.

Parameters:

  • data (Data) –

    Processed data to update.

  • new_raw

    New raw rows to append.

  • nom_cap_abs (float, default: 1.0 ) –

    Absolute nominal capacity for per-step C-rate.

  • refresh_derived (bool, default: True ) –

    When True (default), run c_rates_to_summary and ir_to_summary after rebuilding the summary (mirrors make_core_summary extras).

  • find_ir (bool, default: True ) –

    Whether to add IR columns when refresh_derived is True.

  • current_conversion_factor (float, default: 1.0 ) –

    Current-unit factor for C-rate columns.

  • nom_cap (Optional[float], default: None ) –

    Deprecated alias for nom_cap_abs.

  • **kwargs

    Forwarded to update_data / make_step_table.

Returns:

  • Data

    A new updated Data object. The input is not modified.

Data

Data()

has_steps property

has_steps: bool

True if a step table has been computed.

has_summary property

has_summary: bool

True if a summary has been computed.

from_raw_frame classmethod

from_raw_frame(raw, validate: bool = True, raw_cols: Optional[Cols] = None) -> Data

Create a Data object from a native-schema raw frame.

The validating front door for slim consumers that build a polars frame in the native config.RawCols schema themselves and want step/cycle summaries straight from cellpy-core.

Parameters:

  • raw

    A polars.DataFrame in the native raw schema.

  • validate (bool, default: True ) –

    Whether to check the frame against the schema via validate_raw_frame before wrapping it. Set to False to skip all checks.

  • raw_cols (Optional[Cols], default: None ) –

    The raw column-header schema to validate against. Defaults to the native config.RawCols.

Returns:

  • Data

    A fresh Data with raw attached (and the usual

  • Data

    MockMetaTestDependent metadata placeholder).

Raises:

  • TypeError

    If raw is not a polars.DataFrame (when validating).

  • ValueError

    If the frame does not match the schema (when validating).

RawCols dataclass

RawCols(__version__: str = '0.1.0')

Bases: Cols

Column-header definitions for the harmonized raw data table.

Each attribute maps a logical quantity to the column name used in the harmonized raw format that cellpy-core consumes. The authoritative spec is docs/specifications/harmonized-raw.md; the column order here mirrors that spec table.

__getitem__

__getitem__(key: str) -> str

Allow for bracket notation

dtype_map

dtype_map() -> dict[str, pl.DataType]

Return the authoritative column name -> polars dtype map.

Single source of truth for the polars dtype of every RawCols column, aligned with the spec table in docs/specifications/harmonized-raw.md (ints Int64, floats Float64, strings Utf8, mask Boolean, epoch_time_utc Int64 nanoseconds since the Unix epoch, UTC).

Instance method (not classmethod) so renamed schemas — subclass overrides or FlexibleCols transforms — resolve through attribute access, mirroring Cols.ordered_names.

Returns:

  • dict[str, DataType]

    dict[str, pl.DataType]: One entry per RawCols column

  • dict[str, DataType]

    (required and optional alike), keyed by the resolved column name.

Example

import polars as pl RawCols().dtype_map()["epoch_time_utc"] is pl.Int64 True

ordered_names classmethod

ordered_names() -> list[str]

Return native column name strings in class declaration order.

Iterates cls.__annotations__ (declaration order) and resolves each attribute on a fresh instance so FlexibleCols subclasses can transform names via __getattribute__. Attributes whose names start with _ are omitted.

Returns:

  • list[str]

    list[str]: Column name strings in spec/declaration order.

Note

Prefer this over vars(RawCols) (picks up non-column class entries) or dataclasses.fields(RawCols) (only sees inherited BaseCols fields such as __version__, not subclass columns).

StepCols dataclass

StepCols(__version__: str = '0.1.0')

Bases: Cols

Column-header definitions for the per-step summary table.

Each attribute maps a logical quantity to the column name used in the per-step summary (per-step statistics such as mean/std/min/max/first/last/ delta for time, current, potential, capacity, energy, power and internal resistance, plus the per-step C-rate estimate).

Note

Attributes name the native output columns for the default contract. The step engine builds aggregates as <base>_<stat> where <base> comes from the raw signal stems in summarizers._SIGNAL_BASES (current, potential, charge_capacity, …) and <stat> is one of mean, std, min, max, first, last, or delta. Custom StepCols.current_mean (etc.) does not retarget aggregation or step-type classification today; only group keys, step_type, and c_rate honour injected renames. The legacy bridge renames via legacy.mapping.native_to_legacy_step() after the engine runs.

__getitem__

__getitem__(key: str) -> str

Allow for bracket notation

ordered_names classmethod

ordered_names() -> list[str]

Return native column name strings in class declaration order.

Iterates cls.__annotations__ (declaration order) and resolves each attribute on a fresh instance so FlexibleCols subclasses can transform names via __getattribute__. Attributes whose names start with _ are omitted.

Returns:

  • list[str]

    list[str]: Column name strings in spec/declaration order.

Note

Prefer this over vars(RawCols) (picks up non-column class entries) or dataclasses.fields(RawCols) (only sees inherited BaseCols fields such as __version__, not subclass columns).

CycleCols dataclass

CycleCols(__version__: str = '0.1.0')

Bases: Cols

Column-header definitions for the per-cycle summary table.

Each attribute maps a logical quantity to the column name used in the per-cycle summary produced by the summary engine (capacities, efficiencies, durations, per-direction current/potential/power statistics, etc.).

specific_columns property

specific_columns: list

Summary columns that get specific (per mass / area / volume) variants.

Returns the capacity-like columns that generate_specific_summary_columns scales into {col}_gravimetric / {col}_areal / {col}_absolute variants. Mirrors the legacy HeadersSummary.specific_columns list using the native column names (the native schema has no shifted_* columns, so those legacy entries are dropped).

__getitem__

__getitem__(key: str) -> str

Allow for bracket notation

ordered_names classmethod

ordered_names() -> list[str]

Return native column name strings in class declaration order.

Iterates cls.__annotations__ (declaration order) and resolves each attribute on a fresh instance so FlexibleCols subclasses can transform names via __getattribute__. Attributes whose names start with _ are omitted.

Returns:

  • list[str]

    list[str]: Column name strings in spec/declaration order.

Note

Prefer this over vars(RawCols) (picks up non-column class entries) or dataclasses.fields(RawCols) (only sees inherited BaseCols fields such as __version__, not subclass columns).

Schema dataclass

Schema(raw: BaseCols, cycle: BaseCols, step: BaseCols)

Bundle of the column-header objects for one cell.

Holds the raw, cycle (summary) and step header definitions so the summary / step engine can read its column names from an injected object instead of module-level globals. This is what makes the engine schema-agnostic and thread-safe: each cell carries its own schema.

Units are handled by value (the engine multiplies by precomputed conversion factors supplied by the caller), so units are deliberately not part of the schema.

CellpyError

Bases: Exception

Base class for other Cellpy Core exceptions

NoDataFound

Bases: CellpyError

Exception raised when no data is found

make_step_table

make_step_table(data: Data, schema: Optional[Schema] = None, step_specifications=None, short=False, override_step_types=None, override_raw_limits=None, usteps=False, skip_steps=None, sort_rows=True, from_data_point=None, raw_limits: Optional[dict] = None) -> Union[Data, DataFrame]

Create a table (v.5) that contains summary information for each step.

This function creates a table containing information about the different steps for each cycle and, based on that, decides what type of step it is (e.g. charge) for each cycle.

The format of the steps is:

  • index: cycleno - stepno - sub-step-no - ustep
  • Time info: average, stdev, max, min, start, end, delta
  • Logging info: average, stdev, max, min, start, end, delta
  • Current info: average, stdev, max, min, start, end, delta
  • Voltage info: average, stdev, max, min, start, end, delta
  • Type: (from pre-defined list) - SubType
  • Info: not used.

Parameters:

  • data (Data) –

    The data object.

  • schema (Optional[Schema], default: None ) –

    The column-header schema to use. Defaults to the native cellpy-core schema when not provided.

  • step_specifications (DataFrame, default: None ) –

    step specifications

  • short (bool, default: False ) –

    step specifications in short format

  • override_step_types (dict, default: None ) –

    override the provided step types, for example set all steps with step number 5 to "charge" by providing {5: "charge"}.

  • override_raw_limits (dict, default: None ) –

    override the instrument limits (resolution), for example set 'current_hard' to 0.1 by providing {'current_hard': 0.1}.

  • usteps (bool, default: False ) –

    investigate all steps including same steps within one cycle (this is useful for e.g. GITT).

  • skip_steps (list of integers, default: None ) –

    list of step numbers that should not be processed (future feature - not used yet).

  • sort_rows (bool, default: True ) –

    sort the rows after processing.

  • from_data_point (int, default: None ) –

    first data point to use.

  • raw_limits (dict, default: None ) –

    the raw limits (resolution) for the instrument. Defaults to a fresh copy of DEFAULT_RAW_LIMITS.

Note

Per-step statistic columns are emitted as <base>_<stat> (fixed engine contract). Only group keys and step_type honour injected StepCols renames. See config.StepCols for the full contract.

Note

The per-step C-rate (c_rate / legacy rate_avr) is not part of the base step table; append it with :func:add_step_c_rate when needed (e.g. before :func:c_rates_to_summary).

Returns:

  • Union[Data, DataFrame]

    core.Data: The data object with the step table added if from_data_point is None, otherwise the step table is returned as a DataFrame.

Raises:

  • NoDataFound

    If data.raw is missing.

  • ValueError

    If the raw frame lacks required columns (datapoint, cycle or step numbers).

add_step_c_rate

add_step_c_rate(data: Data, schema: Optional[Schema] = None, nom_cap_abs: float = 1.0, *, nom_cap: Optional[float] = None) -> Data

Append the per-step C-rate (c_rate / legacy rate_avr) to the steps.

Separate opt-in step after :func:make_step_table (mirroring the post-summary helpers such as :func:c_rates_to_summary): computes abs(round(current_mean / nom_cap_abs, DIGITS_C_RATE)) for each step row and adds it as the c_rate column of data.steps.

Parameters:

  • data (Data) –

    The data object (needs steps with a current_mean column).

  • schema (Optional[Schema], default: None ) –

    The column-header schema to use. Defaults to the native cellpy-core schema when not provided.

  • nom_cap_abs (float, default: 1.0 ) –

    The absolute nominal capacity (same unit as the raw capacity columns, e.g. Ah) used to compute the C-rate. Supplied by the caller (by value) so this function needs no unit handling. Defaults to 1.0.

  • nom_cap (float, default: None ) –

    Deprecated alias for nom_cap_abs.

Returns:

  • Data

    core.Data: The data object with the c_rate column added to the steps.

Raises:

  • NoDataFound

    If data.steps is missing.

  • ValueError

    If the step table lacks the current_mean column.

make_summary

make_summary(data: Data, schema: Optional[Schema] = None, final_data_points: Optional[Sequence] = None, test_mode: TestMode = TestMode.NORMAL, exclude_step_types: Optional[Sequence[str]] = None) -> Data

Polars-native per-cycle summary (the clean native CycleCols subset).

One row per cycle, built from the cycle-end raw values plus the step table. Capacities are cycle-cumulative per direction, so the cycle-end raw value is the per-cycle total.

Parameters:

  • data (Data) –

    The data object (needs raw and steps).

  • schema (Optional[Schema], default: None ) –

    The column-header schema to use. Defaults to the native cellpy-core schema when not provided.

  • final_data_points (Optional[Sequence], default: None ) –

    Optional explicit cycle-end datapoints (one per cycle); computed from the step table when not given.

  • test_mode (TestMode, default: NORMAL ) –

    Cell convention. TestMode.NORMAL (full-/cathode cell, charge first) uses CE = 100*discharge/charge and coulombic_difference = charge - discharge. TestMode.INVERTED (anode half-cell, discharge first) flips the reference electrode so CE = 100*charge/discharge and coulombic_difference = discharge - charge (mirrors legacy cycle_mode == "anode").

  • exclude_step_types (Optional[Sequence[str]], default: None ) –

    Optional step-type prefixes to exclude from the summary (e.g. ["cv_"] for a non-CV summary). The excluded steps' per-cycle capacity deltas are subtracted from the cycle-end values before any derived column is computed (see _subtract_excluded_step_deltas). None (the default) leaves the summary untouched.

Returns:

  • Data ( Data ) –

    The data object with the per-cycle summary added.

Raises:

  • NoDataFound

    If data.raw or data.steps is missing.

  • ValueError

    If the raw or step frame lacks required columns.

Note

The legacy-only summary columns (cumulated CE, shifted capacities, RIC) are deliberately not produced here; the legacy bridge (OldCellpyCellCore) adds those for cellpy compatibility.

merge_data

merge_data(left: Data, right: Data, *, schema: Optional['Schema'] = None, renumber_cycles: bool = True, allow_duplicate_test_id: bool = False) -> Data

Merge two processed Data objects into a new one.

Vertically concatenates raw and, when present on both sides, steps and summary. Offsets datapoint_num on the right side by the last left datapoint (always). When renumber_cycles is True, also offsets cycle numbers on the right and carries cumulative summary columns forward from the last left summary row.

Parameters:

  • left (Data) –

    First dataset (D1).

  • right (Data) –

    Second dataset (D2), appended after left.

  • schema (Optional['Schema'], default: None ) –

    Column-header schema. Defaults to config.default_schema().

  • renumber_cycles (bool, default: True ) –

    If True (default), offset right cycle_num values by max(left.cycle_num) and shift cumulative summary columns. If False, cycle numbers are kept as-is (multi-test isolation via test_id).

  • allow_duplicate_test_id (bool, default: False ) –

    If False (default), raise when both sides share a test_id. If True, reassign colliding right-side test_id values to the next free ids.

Returns:

  • Data

    A new Data with merged frames. Inputs are not modified.

Raises:

  • ValueError

    If either side lacks raw, or test_id values collide and allow_duplicate_test_id is False.

update_data

update_data(data: Data, new_raw: DataFrame, *, schema: Optional['Schema'] = None, nom_cap_abs: float = 1.0, partition_col: str | None = None, test_mode: TestMode = config.TestMode.NORMAL, nom_cap: Optional[float] = None, **step_table_kwargs: Any) -> Data

Incrementally update processed Data with new raw rows.

Trims the overlap at source_datapoint_num (or datapoint_num when absent), refreshes affected step rows via make_step_table(from_data_point=…), and rebuilds the per-cycle summary on the combined frames.

Parameters:

  • data (Data) –

    Processed Data with raw, steps, and summary.

  • new_raw (DataFrame) –

    New raw rows to append (may overlap the tail of data.raw).

  • schema (Optional['Schema'], default: None ) –

    Column-header schema. Defaults to config.default_schema().

  • nom_cap_abs (float, default: 1.0 ) –

    Absolute nominal capacity for the per-step C-rate appended to the rebuilt step rows (via add_step_c_rate), so they match the kept steps.

  • partition_col (str | None, default: None ) –

    Column used to detect overlap. Defaults to source_datapoint_num, falling back to datapoint_num.

  • test_mode (TestMode, default: NORMAL ) –

    Cell convention forwarded to make_summary.

  • nom_cap (Optional[float], default: None ) –

    Deprecated alias for nom_cap_abs.

  • **step_table_kwargs (Any, default: {} ) –

    Extra keyword arguments forwarded to make_step_table (except schema, nom_cap_abs, from_data_point).

Returns:

  • Data

    A new Data object. The input is not modified.

Raises:

  • ValueError

    If data is not fully processed, new_raw is invalid, more than one test_id is present, or new_raw starts at or before the beginning of the existing partition range (full reload).

cast_raw_frame

cast_raw_frame(raw, raw_cols: Optional[RawCols] = None)

Cast a raw frame's columns to the native RawCols dtypes.

Convenience for consumers converting foreign raw data (e.g. legacy pandas frames turned into polars) to the harmonized raw format: every column present in raw that appears in raw_cols.dtype_map() is cast to its authoritative dtype. Columns missing from the frame (optional columns) are skipped, and extra columns (e.g. custom aux_* columns) pass through untouched.

Casts are strict — a lossy or impossible cast raises instead of silently coercing. Typical use is casting before the validating front door::

data = Data.from_raw_frame(cast_raw_frame(df))

Parameters:

  • raw

    The raw frame to cast (must be a polars.DataFrame).

  • raw_cols (Optional[RawCols], default: None ) –

    The raw column-header schema providing dtype_map(). Defaults to the native config.RawCols.

Returns:

  • A new polars.DataFrame with the covered columns cast.

Raises:

  • TypeError

    If raw is not a polars.DataFrame.

  • InvalidOperationError

    If a cast fails (e.g. a non-numeric string in an integer column).

validate_raw_frame

validate_raw_frame(raw, raw_cols: Optional[Cols] = None) -> None

Validate a native-schema raw frame against config.RawCols.

Checks that raw is a polars DataFrame carrying the load-bearing columns the step/summary engine needs, with sane dtypes. All problems are collected and reported in a single error so the caller sees the full picture at once instead of a deep polars stack trace later.

Optional columns (test_id, internal_resistance, ref_potential, step_time, the source_* and aux_* columns, …) are allowed absent and are not dtype-checked.

Parameters:

  • raw

    The candidate raw frame (must be a polars.DataFrame).

  • raw_cols (Optional[Cols], default: None ) –

    The raw column-header schema to validate against. Defaults to the native config.RawCols when not provided.

Raises:

  • TypeError

    If raw is not a polars.DataFrame.

  • ValueError

    If required columns are missing or load-bearing columns have the wrong dtype. The message lists every problem found.

default_schema

default_schema() -> Schema

Return a Schema using the native cellpy-core column definitions.

Used as a standalone fallback when no schema is injected; the legacy bridge (OldCellpyCellCore) always injects its own legacy-named schema.