PyCoBi.pycobi

Module that contains the base class ODESystem that represents the main user interface of PyCoBi for parameter continuations, results visualization and results storage.

class pycobi.pycobi.Continuation(key: int, name: str | None, branch_id: int, icps: ~typing.List[tuple] = <factory>, auto_solution: ~typing.Any | None = None, summary: ~pandas.core.frame.DataFrame | None = None)[source]

Bases: object

One continuation tracked by ODESystem — bundles together what was previously scattered across the auto_solutions, results, _results_map, and _branches dicts.

Fields

key

The pycobi key (an int) under which this continuation is stored.

name

User-supplied name passed to run(…, name=…), or None.

branch_id

auto-07p’s BR identifier for the branch this continuation lives on. Multiple continuations may share a branch_id (e.g. when one extends another or when bidirectional merges into the same branch).

icps

Continuation parameter index tuples used to grow this branch. A bidirectional run that goes both ways in PAR(4) records [(4,)] once; a branch that was extended a second time in PAR(5) appends (5,).

auto_solution

The auto-07p bifDiag object holding the actual solution data. Not pickle-safe — excluded from to_file; on from_file this will be None for loaded instances.

summary

PyCoBi’s parsed DataFrame summary of the continuation. Populated by _create_summary after auto.run returns.

auto_solution: Any = None
branch_id: int
icps: List[tuple]
key: int
name: str | None
summary: DataFrame | None = None
class pycobi.pycobi.ODESystem(eq_file: str, working_dir: str | None = None, auto_dir: str | None = None, init_cont: bool = False, params: list | None = None, state_vars: list | None = None, **kwargs)[source]

Bases: object

additional_attributes
auto_solutions
blocked_indices = (10, 15)
close_session(clear_files: bool = False, **kwargs)[source]
continuations
dir
extract(keys: list, cont: Any | str | int, point: str | int | None = None) tuple[source]

Extract properties from a solution.

Parameters:
  • keys – Keys of the properties (e.g. state variable names, parameter names, …).

  • cont – Key of the solution branch.

  • point – Key of the solution on the branch. When omitted (default), all rows of the summary are returned; when provided, only the row at that label.

Returns:

Tuple with 2 entries: (1) the requested slice of the continuation summary, either a DataFrame (when point is None — multiple rows × len(keys) cols) or a Series (when point is provided — a single labeled row indexed by the requested keys); (2) a dict mapping each input key to the column name that was actually used to look it up in the summary (these can differ when PyCoBi’s _var_map_inv translates ‘PAR(i)’ / ‘U(i)’ back to user-facing names).

Return type:

tuple

classmethod from_file(filename: str, auto_dir: str | None = None)[source]

Load ODESystem from a pickle file written by to_file.

Parameters:
  • filename – Path to the pickle file written by ODESystem.to_file.

  • auto_dir – Installation directory of auto-07p.

Returns:

ODESystem instance with state restored from the file. Slots not stored on disk (the live auto module, the PyRates CircuitTemplate, the cwd snapshots) are re-initialised by __init__ rather than from the file.

Return type:

ODESystem

classmethod from_template(template: CircuitTemplate, working_dir: str | None = None, auto_dir: str | None = None, init_cont: bool = False, init_kwargs: dict | None = None, analytical_jacobian: bool = True, auto_constants: str | tuple | list = ('ivp',), **kwargs)[source]

Instantiates ODESystem from a pyrates.CircuitTemplate.

Parameters:
  • template – Instance of the class pyrates.CircuitTemplate.

  • working_dir – Directory in which all the fortran equation and auto-07p constant files are saved.

  • auto_dir – Installation directory of auto-07p.

  • init_cont – If true, an IVP time integration is run at instantiation against the freshly generated c.ivp file. Defaults to false — set to true to opt into the legacy behaviour. See __init__ for details.

  • init_kwargs – Additional keyword arguments that will be provided to the ODESystem.run method for performing the time integration.

  • analytical_jacobian – If true (default), instruct PyRates to symbolically differentiate the vector field and emit DFDU/DFDP inside the generated func subroutine; the generated c.* file will set JAC=1 so auto-07p uses the analytical Jacobian. Set to false to fall back to auto-07p’s finite-difference Jacobian (useful when symbolic differentiation is slow or produces unwieldy expressions for the model at hand). Can be overridden on a per-continuation basis by passing JAC=0 or JAC=1 to ODESystem.run.

  • auto_constants

    Name (or iterable of names) of auto-07p continuation scenarios PyRates should emit c.<name> files for. One file is written per requested scenario, each pre-configured with auto-07p constants appropriate for that mode. Recognised scenarios:

    • 'ivp' — initial-value problem / time integration (IPS=-2). Required when init_cont=True.

    • 'eq' — equilibrium continuation in one parameter (IPS=1).

    • 'lc' — limit-cycle continuation in one parameter, with PAR(11) as the period (IPS=2).

    • 'bvp' — boundary-value problem (IPS=4).

    Pass e.g. auto_constants=('ivp', 'eq', 'lc') to set up all three at once and then switch scenarios on a per-call basis via ode.run(c='eq', ...). Auto-07p constants passed as kwargs (NMX, DSMAX, UZSTOP, …) apply to every requested scenario; per-scenario overrides can be applied at run-time on the corresponding ODESystem.run call. Defaults to ('ivp',) for backward compatibility.

  • kwargs – Additional keyword arguments provided to the pyrates.CircuitTemplate.get_run_func method that is used to generate the fortran equation file and the auto constants file that will be used to initialize ODESystem.

Returns:

ODESystem instance.

Return type:

ODESystem

classmethod from_yaml(path: str, working_dir: str | None = None, auto_dir: str | None = None, init_cont: bool = False, init_kwargs: dict | None = None, analytical_jacobian: bool = True, auto_constants: str | tuple | list = ('ivp',), **kwargs)[source]

Instantiates ODESystem from a YAML definition file.

Parameters:
  • path – Full path to a YAML model definition file for a pyrates.CircuitTemplate.

  • working_dir – Directory in which all the fortran equation and auto-07p constant files are saved.

  • auto_dir – Installation directory of auto-07p.

  • init_cont – If true, an IVP time integration is run at instantiation against the freshly generated c.ivp file. Defaults to false — set to true to opt into the legacy behaviour. See __init__ for details.

  • init_kwargs – Additional keyword arguments that will be provided to the ODESystem.run method for performing the time integration.

  • analytical_jacobian – If true (default), instruct PyRates to symbolically differentiate the vector field and emit DFDU/DFDP inside the generated func subroutine; the generated c.* file will set JAC=1 so auto-07p uses the analytical Jacobian. Set to false to fall back to auto-07p’s finite-difference Jacobian (useful when symbolic differentiation is slow or produces unwieldy expressions for the model at hand).

  • auto_constants – Name (or iterable of names) of auto-07p continuation scenarios to generate c.<name> files for. See from_template for the recognised scenarios and their default constants. Defaults to (‘ivp’,) for backward compatibility.

  • kwargs – Additional keyword arguments provided to the pyrates.CircuitTemplate.get_run_func method that is used to generate the fortran equation file and the auto constants file that will be used to initialize ODESystem.

Returns:

ODESystem instance.

Return type:

ODESystem

get_continuation(key_or_name: int | str) Continuation[source]

Return the Continuation dataclass for a stored continuation, looked up by user-supplied name or by pyauto-key int.

Examples

>>> sols, _ = ode.run(starting_point='EP2', name='eta_branch', ICP='eta', ...)
>>> cont = ode.get_continuation('eta_branch')
>>> cont.branch_id, cont.icps, len(cont.summary)
(1, [(4,)], 30)
get_solution(cont: Any | str | int, point: str | int | None = None) Any | tuple[source]

Extract auto solution object of a given solution/solution branch.

Parameters:
  • cont – Key of the solution branch.

  • point – Key of the solution on the branch.

Returns:

Solution type (only if point is provided), auto solution object.

Return type:

Union[Any, tuple]

get_summary(cont: Any | str | int | None = None, point=None) DataFrame[source]

Extract summary of continuation from PyCoBi.

Parameters:
  • cont – Key of the solution branch.

  • point – Key of the solution on the branch.

Returns:

All recorded state variables, parameters, etc. for the solution/solution branch.

Return type:

DataFrame

merge(key: int, cont, icp: tuple)[source]

Merges two solutions from two separate auto continuations.

Parameters:
  • key – PyCoBi identifier under which the merged solution should be stored. Must be equal to identifier of first continuation.

  • cont – auto continuation object that should be merged with the continuation object under key.

  • icp – Continuation parameter that was used in both continuations that are to be merged.

plot_bifurcation_points(solution_types: DataFrame, x_vals: DataFrame, y_vals: DataFrame, ax: Axes, default_color: str = 'k', default_marker: str = '*', default_size: float = 10, ignore: list | None = None, custom_bf_styles: dict | None = None) tuple[source]

Plot markers for special solutions at coordinates in 2D space.

Parameters:
  • solution_types – Type of each solution, entries of DataFrame should be strings.

  • x_vals – X-coordinates of each solution.

  • y_vals – Y-coordinates of each special solution

  • ax – Axis in which to plot the data. If not provided, a new figure will be created.

  • default_color – Default color to be used if bifurcation style is not known.

  • default_marker – Default marker style to be used if bifurcation style is not known.

  • default_size – Default marker size.

  • ignore – List of solution types that should not be displayed.

  • custom_bf_styles – Dictionary containing adjustments to the default bifurcation markers and colors.

Returns:

A 2-entry tuple of (1) a list of PathCollections that correspond to bifurcation points, and (2) a list of corresponding bifurcation types.

Return type:

tuple

plot_continuation(x: str, y: str, cont: Any | str | int, ax: Axes | None = None, force_axis_lim_update: bool = False, bifurcation_legend: bool = True, get_stability: bool = True, **kwargs) LineCollection[source]

Line plot of 1D/2D parameter continuations and the respective codimension 1/2 bifurcations.

Parameters:
  • x – Key of the parameter/variable plotted on the x-axis.

  • y – Key of the variable/parameter plotted on the y-axis.

  • cont – Key of the solution branch to be plotted.

  • ax – Axis in which to plot the data. If not provided, a new figure will be created.

  • force_axis_lim_update – If true, the axis limits of x and y axis will be updated after creating the line plots.

  • bifurcation_legend – If true, a legend will be plotted that lists the type of all special solutions on a continuation curve.

  • get_stability – If true, the stability of the solutions will be indicated via different line styles.

  • kwargs – Additional keyword arguments that allow to control the appearance of the line plot.

Returns:

Line object that was created.

Return type:

LineCollection

plot_continuation_grid(plots: list, ncols: int = 2, figsize: tuple | None = None, sharex: bool = False, sharey: bool = False, **shared_kwargs) tuple[source]

Lay out multiple 1D/2D continuations as a grid of subplots.

Convenience helper to compare continuations side-by-side (e.g. a codim-1 scan in eta next to its codim-2 fold curve in (eta, Delta), or several “same x/y, different parameter setting” diagrams).

Parameters:
  • plots – List of dicts, one per subplot. Each dict must contain 'x', 'y', and 'cont' (forwarded to plot_continuation() as the corresponding positional args). Any additional keys override shared_kwargs for that specific subplot — except 'title', which is set on the subplot’s axes via ax.set_title. The optional 'panel_label' key is drawn in the upper-left corner of the subplot (useful for figure-quality (a), (b), (c) annotations).

  • ncols – Number of columns in the grid. Rows are derived from ceil(len(plots) / ncols). Default 2.

  • figsize – Forwarded to matplotlib.pyplot.subplots(). Defaults to (5 * ncols, 4 * nrows) — i.e. each subplot gets ~5x4 inches.

  • sharex – Forwarded to matplotlib.pyplot.subplots(). Useful when all panels live on the same parameter range.

  • sharey – Forwarded to matplotlib.pyplot.subplots(). Useful when all panels live on the same parameter range.

  • shared_kwargs – Keyword arguments applied to every subplot (e.g. bifurcation_legend=False to suppress the per-panel legend). Per-plot keys override these.

Returns:

(fig, axes, line_cols). axes is the flat list of Axes (length len(plots); trailing positions in the grid that have no plot are deleted). line_cols is the list of LineCollections returned by each plot_continuation call, in the same order as plots.

Return type:

tuple

plot_timeseries(var: str, cont: Any | str | int, points: list | None = None, ax: Axes | None = None, linespecs: list | None = None, **kwargs) Axes[source]

Plot state variable of a periodic solution over time.

Parameters:
  • var – Key of the state variable.

  • cont – Key of the solution branch.

  • points – List with keys of the solutions for which to create time series plots. When None (default), every labelled point on the continuation is plotted as a separate trace.

  • ax – Axis in which to plot the data. If not provided, a new figure will be created.

  • linespecs – Per-trace keyword overrides; linespecs[i] is merged into kwargs for the i-th point.

  • kwargs – Additional keyword arguments that control the appearance of the plot.

Returns:

Axis object that contains the plotted timeseries.

Return type:

plt.Axes

plot_trajectory(variables: list | tuple, cont: Any | str | int, point: str | int | None = None, ax: Axes | None = None, force_axis_lim_update: bool = False, cutoff: float | None = None, colorbar: bool = False, colorbar_label: str | None = None, **kwargs) LineCollection[source]

Plot trajectory of state variables through phase space over time.

Parameters:
  • variables – State variables for which to create the trajectory. If 2, a 2D plot will be created, if 3, a 3D plot.

  • cont – Key of the solution branch to be plotted.

  • point – Key of the solution on the solution branch for which to plot the trajectories.

  • ax – Axis in which to plot the data. If not provided, a new figure will be created.

  • force_axis_lim_update – If true, the axis limits of x and y-axis will be updated after creating the line plots.

  • cutoff – Initial time to be disregarded for plotting.

  • colorbar – For 3D plots only: if true, attach a colorbar to the figure showing the scalar that _get_3d_line_collection mapped onto the LineCollection’s color (default: the projected x-axis variable). Useful when the colour gradient already encodes time or a state variable. Ignored for 2D plots.

  • colorbar_label – Label for the colorbar. Defaults to the array key ('x' / 'y' / 'z' — whichever the LineCollection’s array= kwarg points at).

  • kwargs – Additional keyword arguments that allow to control the appearance of the line plot.

Returns:

Line object that was created.

Return type:

LineCollection

property pyrates_template
static reset_auto_state() None[source]

Clear auto-07p’s per-process cross-run state (parnames, unames).

auto-07p’s Python wrapper deliberately leaves the parnames / unames entries on its global runner intact between successive run() calls — see auto/runAUTO.py:

# do not completely replace existing constants data but
# leave the special keys such as unames, parnames, etc, intact

That’s helpful when iterating on a single model, but it leaks across unrelated model loads. Concretely: an ODESystem for model A whose generated c.* declares unames = {1: 'r', 2: 'v'} populates the global runner; instantiating model B whose c.* declares no unames will inherit {1: 'r', 2: 'v'} and silently relabel B’s DataFrame columns with A’s state-variable names. The same applies to parnames.

Call this between unrelated model loads (typically in test teardown, or right before constructing a fresh ODESystem from a different model). No-ops if auto was never imported, or if its internal layout differs from what we expect.

results
run(origin: int | str | object | None = None, starting_point: str | int | None = None, variables: list | None = None, params: list | None = None, get_stability: bool = True, get_period: bool = False, get_timeseries: bool = False, get_eigenvals: bool = False, get_lyapunov_exp: bool = False, reduce_limit_cycle: bool = True, bidirectional: bool = False, name: str | None = None, _reverse_direction: bool = False, **auto_kwargs) tuple[source]

Wraps auto-07p command run and stores requested solution details on instance.

Parameters:
  • origin – Key of the solution branch that contains the solution starting_point, from which the new continuation will be started.

  • starting_point

    Solution on the origin branch to start the new continuation from. Accepted forms:

    • Auto-07p label string — 'EP', 'LP1', 'HB2' etc. The first two characters are the bifurcation type; the optional trailing integer disambiguates when the branch carries several solutions of the same type (1-based, defaults to 1). The IVP that init_cont=True runs produces 'EP1' for the initial state and 'EP2' for the converged steady state — use 'EP2' when starting an equilibrium continuation from the IVP’s terminal state.

    • Bare bifurcation type (no number) — 'EP' is equivalent to 'EP1'.

    • Integer point index — a 1-based auto-07p point number on the branch (the PT column of the printed table). Useful when auto produced unlabeled regular points that you want to continue from.

    • None — only valid on the very first call against a fresh ODESystem (when no prior continuation exists to extend); subsequent calls require an explicit starting point so PyCoBi knows which branch to extend.

  • variables – Keys of the state variables that should be recorded for each continuation recording step.

  • params – Keys of the parameters that should be recorded for each continuation recording step.

  • get_stability – If true, the stability of each solution will be stored in the results under the key ‘stability’.

  • get_period – If true, the period of periodic solutions will be stored in the results under the key ‘period’.

  • get_timeseries – If true, the time vector associated with the state variables of a periodic solution will be stored under the key ‘time’.

  • get_eigenvals – If true, the eigenvalues (floquet multipliers) or steady-state (periodic) solutions will be stored under the key ‘eigenvalues’.

  • get_lyapunov_exp – If true, the local lyapunov exponents of solutions will be stored under the key ‘lyapunov’.

  • reduce_limit_cycle – If true, the values of each state variable will be reduced to the minimum and maximum for limit cycle solutions. Else, the state variable values will be stored for multiple discretized points along the limit cycle solution (number depends on the arguments passed to Auto).

  • bidirectional – If true, parameter continuation will be performed into both directions for a given continuation parameter.

  • name – Name, under which the resulting solution branch will be accessible for future continuations.

  • _reverse_direction – Private flag set internally by the recursive call that bidirectional=True makes. Tells run() that this invocation is the reverse-direction half of a bidirectional continuation, so the result is merged into the forward branch rather than registered as a fresh continuation. Don’t pass manually.

  • auto_kwargs – Additional keyword arguments to be passed to the auto command run. All auto-07p constants can be overridden here (e.g. NMX, DSMAX, ICP, …). In particular, JAC=0/JAC=1 overrides the Jacobian source for this single continuation: pass JAC=0 to force finite-difference Jacobian even if from_template / from_yaml was instantiated with analytical_jacobian=True, and vice versa.

Returns:

DataFrame with the results, auto solution branch object.

Return type:

tuple

to_file(filename: str, results_only: bool = True, **kwargs) None[source]

Save the instance state on disc via pickle.

Parameters:
  • filename – Path to write the pickle file to. If a file already exists at this path it will be overwritten.

  • results_only – When true (default), only the PyCoBi-side bookkeeping (results, _branches, _results_map) is saved — enough to reproduce DataFrames and plots without rerunning auto-07p. When false, all pickle-safe slots are saved (see _PICKLE_EXCLUDE for the slots intentionally omitted because they can’t round-trip).

  • kwargs – Extra metadata to attach to the dump. Restored as additional_attributes.

Return type:

None

update_bifurcation_style(bf_type: str, marker: str | None = None, color: str | None = None) None[source]

Update the default marker and color of a given special solution type.

Parameters:
  • bf_type – Type of the special solution.

  • marker – New marker type.

  • color – New color.

Return type:

None