PyBNF model and parameter containers (pybnf.pset)

Classes for storing models, parameter sets, and the fitting trajectory

class pybnf.pset.Action[source]

Represents a simulation action performed within a model

output_length()[source]

Number of output rows this action produces.

One row per explicit output point when the grid is data-derived (ADR-0028 explicit_points, which always includes the forced t=0 for a time course), else the uniform n_steps grid’s row count (stepnumber + 1, including t_start). Used to size the per-experiment output arrays (config.py::_load_experiments -> _load_t_length -> adaptive_mcmc).

class pybnf.pset.BNGLModel(bngl_file, pset=None, suppress_free_param_error=False)[source]

Class representing a BNGL model

add_action(action)[source]

Append a config-file action as a BNGL action string.

Translates a TimeCourse or ParamScan object into a BNGL action line and appends it to the model’s action list. Only a subset of BioNetGen arguments are supported here; for full control, write actions in the BNGL file’s begin actions block instead.

copy_with_param_set(pset)[source]

Returns a copy of this model containing the specified parameter set.

Parameters:

pset (PSet) – A PSet object containing the parameters for the new instance

Returns:

BNGLModel

execute(folder, filename, timeout, with_mutants=True)[source]
Parameters:

folder – Folder in which to do all the file creation

Returns:

Data object

find_t_length()[source]

Builds a dict mapping each simulate action’s suffix to the number of output time points minus one, which is used to size the trajectory-output arrays (an array of length time + 1 holds one entry per output row).

The number of output rows depends on how the simulation length is specified:

  • n_steps=>N produces N + 1 rows (including t_start), so time = N.

  • sample_times=>[t0,...,tM] produces one row per listed time, so time = len(sample_times) - 1.

Returns:

dict keyed on suffix string with integer values

get_suffixes()[source]

Return a list of valid data suffixes to use in this model, including all combinations of action suffix + mutation name

model_text(gen_only=False)[source]

Returns the text of a runnable BNGL file, which includes the contents of the original BNGL file, and also values assigned to each __FREE parameter, as determined by this model’s PSet

Returns:

str

save(file_prefix, gen_only=False, pset=None)[source]

Saves a runnable BNGL file of the model, including definitions of the __FREE parameter values that are defined by this model’s pset, to the specified location.

Parameters:
  • file_prefix – str, path where the file should be saved

  • gen_only – bool, output model with only generate_network action if True

save_all(file_prefix)[source]

Saves BNGL files of the original model and all mutants :param file_prefix:

exception pybnf.pset.FailedSimulationError[source]

Raised when a simulation fails that was not a result of a subprocess.run() call (currently only use with SbmlModelNoTimeout)

class pybnf.pset.FreeParameter(name, type, p1, p2, value=None, bounded=True, lb=None, ub=None, initialization_distribution='prior', initialization_lb=None, initialization_ub=None, p3=None)[source]

Class representing a free parameter in a model

add(summand, reflect=True)[source]

Adds a value to the existing value and returns a new FreeParameter instance. Since free parameters can exist in regular or logarithmic space, the value to add is expected to already be transformed to the appropriate space

Parameters:

summand – Value to add

Returns:

add_rand(lb, ub, rng, reflect=True)[source]

Like FreeParameter.add but instead adds a uniformly distributed random value according to the bounds provided

Parameters:
  • lb

  • ub

  • rng – the caller’s np.random.Generator

Returns:

diff(other)[source]

Calculates the difference between two FreeParameter instances. Both instances must occupy the same space (log or regular) and if they are both in log space, the difference will be calculated based on their logarithms. :param other: A FreeParameter from which the difference will be calculated :return:

from_sampling_space(u)[source]

Map a sampling-space value u back to a stored value – 10**u for a log parameter, identity otherwise. The inverse of to_sampling_space() and the public peer of _scale.inverse.

Unguarded, bit-for-bit 10.0 ** u (matching the inline 10** the proposal arithmetic already used); an out-of-range result is handled by the box clamp / reflection at the call site. The guarded inverse for user-supplied logvar / lognormal start values is the separate exp10 helper, which raises a configuration hint on overflow (#412).

from_sampling_space_jax(u)[source]

JAX-traceable peer of from_sampling_space() (the u -> theta map, ADR-0059).

The gradient-based hmc sampler evaluates the model’s NLL at theta = scale.inverse(u) inside jax.grad, so a log-scaled parameter composes with NUTS. Delegates to Scale.inverse_jax (10**u / exp(u) / identity), keeping the sampler off the private _scale; no Jacobian is added here – the prior is defined in u (ADR-0010), so theta enters only through the likelihood.

property has_bounded_initialization

Whether this parameter can participate in Latin-hypercube seeding.

property has_bounded_support

Whether the prior family has finite support (the Uniform families). Drives latin-hypercube participation and the box-escape warning – the property the algorithms ask instead of matching the *_var type string.

property has_prior

Whether this parameter has a proper prior distribution (False for the no-prior var/logvar Simplex start points). Used by samplers to decide which parameters contribute to the log prior.

initial_value_from_quantile(q)[source]

Map a [0, 1] quantile through the initialization distribution.

multiply(summand, reflect=True)[source]

Adds a value to the existing value and returns a new FreeParameter instance. This version of add does not consider the space that the value is in and just sums them

Parameters:

summand – Value to a multiply

Returns:

prior_logpdf(value)[source]

Evaluate the log prior density for a regular-space parameter value.

For log-space variables, the prior is evaluated in base-10 logarithmic space to match the historical parameterization of lognormal_var and loguniform_var.

prior_logpdf_jax(u)[source]

JAX-traceable log prior density at a sampling-space value u (ADR-0059).

The JAX peer of prior_logpdf(), used by the gradient-based hmc sampler. It takes u directly (HMC samples in u, where the prior is defined – ADR-0010), so there is no theta -> u forward transform and no Jacobian here; the family supplies the differentiable log-density via Prior.logpdf_jax. A no-prior carrier contributes 0 (NoPrior.logpdf_jax). Keeps the sampler off the private _prior attribute, mirroring the numpy prior_logpdf.

prior_support()[source]

The prior family’s (lo, hi) support in sampling space u (ADR-0010).

The information a support-aware unconstraining bijector keys on (ADR-0059 item 5): the gradient-based hmc sampler builds one bijector per parameter from this to reparameterize a constrained prior onto the unbounded space NUTS samples. Delegates to Prior.support – e.g. (-inf, inf) for a normal, (0, inf) for a positive family, (lo, hi) for a uniform/loguniform box or a truncated prior – so the bijection respects the parameter’s scale automatically (a loguniform box is finite in log10 space, where its prior and proposal arithmetic already live).

sample_initial_value(rng)[source]

Draw a start-point value from the configured initialization distribution.

sample_value(rng)[source]

Samples a value from this parameter’s objective prior distribution.

Parameters:

rng – the caller’s np.random.Generator, passed through to the prior

Returns:

new FreeParameter instance or None

set_value(new_value, reflect=True)[source]

Creates a copy of the parameter with the given value

Parameters:
  • new_value (float) – A numeric value assigned to the FreeParameter

  • reflect (bool) – Determines whether to reflect the parameter value if it is outside of the defined bounds

Returns:

FreeParameter

to_sampling_space(theta)[source]

Map a stored value theta into the sampling space u the prior and the proposal arithmetic operate in – log10(theta) for a log parameter, identity otherwise.

The public peer of the private _scale.forward (ADR-0010), added so the algorithm layer asks the parameter for the transform instead of inlining np.log10(x) if v.log_space else x at a dozen sites (#412). Accepts a scalar or a numpy array (the histogram path passes a column).

value_from_quantile(q)[source]

Map a [0, 1] quantile to a value via the prior’s inverse CDF, in scale.

For the bounded (Uniform) families this is the latin-hypercube rescale: scale.inverse(lo + q*(hi - lo)) – equal bit-for-bit to the historical p1 + q*(p2 - p1) (linear) / exp10(log10(p1) + q*…) (log10).

class pybnf.pset.Model[source]

An abstract class representing an executable model

add_mutant(mut_set)[source]

Add a mutant to run along with this model :param mut_set: MutationSet that should be applied to this mutant :type mut_set: MutationSet :return:

copy_with_param_set(pset)[source]

Returns a copy of the model with a new parameter set

Parameters:

pset (PSet) – A new parameter set

Returns:

Model

execute(folder, filename, timeout)[source]

Executes the model, working in folder/filename, with a max runtime of timeout. Loads the resulting data, and returns a dictionary mapping suffixes to data objects. For model types without a notion of suffixes, the dictionary will contain one key mapping to one Data object

Parameters:
  • folder – The folder to save to, eg ‘Simulations/init22’

  • filename – The name of the model file to create, not including the extension, eg ‘init22’

  • timeout – Maximum runtime in seconds

Returns:

dict of Data

get_suffixes()[source]

Return a list of valid data suffixes to use in this model, including all combinations of action suffix + mutation name

save(file_prefix, **kwargs)[source]

Saves the model to file

Returns:

exception pybnf.pset.ModelError(message)[source]
class pybnf.pset.MutationSet(mutations=(), suffix='')[source]

A set of mutations that represents a mutant model

class pybnf.pset.NetModel(name, acts, suffs, mutants, ls=None, nf=None, source_dir=None)[source]
copy_with_param_set(pset)[source]

Returns a copy of the model in .net format, but with a new parameter set

Parameters:

pset (PSet) – A set of new parameters for the model

Returns:

NetModel

save(file_prefix)[source]

Saves a runnable BNGL file of the model, including definitions of the __FREE parameter values that are defined by this model’s pset, to the specified location.

Parameters:
  • file_prefix – str, path where the file should be saved

  • gen_only – bool, output model with only generate_network action if True

exception pybnf.pset.OutOfBoundsException[source]
class pybnf.pset.PSet(fps)[source]

Class representing a parameter set

get_param(name)[source]

Gets the full FreeParameter based on its name

Parameters:

name

Returns:

keys()[source]

Returns a list of the parameter keys :return: list

keys_to_string()[source]

Returns the keys (parameter names) in a tab-separated str in alphabetical order

Returns:

str

values_to_string()[source]

Returns the parameter values in a tab-separated str, in alphabetical order according to the parameter name :return: str

class pybnf.pset.ParamScan(d, explicit_points=None)[source]

A parameter-scan action parsed from the PyBNF configuration file.

This supports a subset of BioNetGen’s parameter_scan arguments. For BNGL models, users should prefer writing actions directly in the BNGL file’s begin actions block, which supports the full set of BioNetGen arguments (e.g., steady_state, atol, rtol). Config-file actions are primarily intended for SBML models, which have no native action syntax.

class pybnf.pset.SbmlModel(file, abs_file, pset=None, actions=(), save_files=False, integrator='cvode')[source]
execute(folder, filename, timeout)[source]

Executes the model, working in folder/filename, with a max runtime of timeout. Loads the resulting data, and returns a dictionary mapping suffixes to data objects. For model types without a notion of suffixes, the dictionary will contain one key mapping to one Data object

Parameters:
  • folder – The folder to save to, eg ‘Simulations/init22’

  • filename – The name of the model file to create, not including the extension, eg ‘init22’

  • timeout – Maximum runtime in seconds

Returns:

dict of Data

class pybnf.pset.SbmlModelNoTimeout(file, abs_file, pset=None, actions=(), save_files=False, integrator='cvode')[source]
copy_with_param_set(pset)[source]

Returns a copy of the model with a new parameter set

Parameters:

pset (PSet) – A new parameter set

Returns:

Model

execute(folder, filename, timeout)[source]

Executes the model, working in folder/filename, with a max runtime of timeout. Loads the resulting data, and returns a dictionary mapping suffixes to data objects. For model types without a notion of suffixes, the dictionary will contain one key mapping to one Data object

Parameters:
  • folder – The folder to save to, eg ‘Simulations/init22’

  • filename – The name of the model file to create, not including the extension, eg ‘init22’

  • timeout – Maximum runtime in seconds

Returns:

dict of Data

get_suffixes()[source]

Return a list of valid data suffixes to use in this model, including all combinations of action suffix + mutation name

model_text(mut=None)[source]

Generates the XML text of the model, optionally applying the MutationSet mut Should only be used when saving the model to disk, which is not often done. :return:

save(file_prefix)[source]

Saves the model to file

Returns:

class pybnf.pset.TimeCourse(d, explicit_points=None)[source]

A time-course simulation action parsed from the PyBNF configuration file.

This supports a subset of BioNetGen’s simulate arguments. For BNGL models, users should prefer writing actions directly in the BNGL file’s begin actions block, which supports the full set of BioNetGen arguments (e.g., steady_state, atol, rtol, continue, stop_if). Config-file actions are primarily intended for SBML models, which have no native action syntax.

set_preequilibration(equil_perturbations, measure_perturbations, equil_max_time=1000000.0)[source]

Mark this time course as the measured phase of a pre-equilibration protocol (ADR-0052). equil_perturbations are applied (as absolute setParameter) before the unmeasured steady-state equilibration; measure_perturbations after it, before this measurement. Each is a list of (param_name, value) pairs.

class pybnf.pset.Trajectory(max_output)[source]

Tracks the various PSet instances and the corresponding objective function values

add(pset, obj, name, append_file=None, first=False)[source]

Adds a PSet to the fitting trajectory

Parameters:
  • pset – A particular point in parameter space

  • obj – The objective function value upon executing the model at this point in parameter space

Raises:

Exception

best_fit()[source]

Finds the best fit parameter set

Returns:

PSet

best_fit_name()[source]

Finds the name of the best fit parameter set (which is also the folder where that result is stored)

Returns:

str

best_score()[source]

Returns the best objective value in this trajectory :return: float

static load_trajectory(filename, variables, max_output)[source]

Loads a Trajectory from file given Algorithm.variables information

write_to_file(filename)[source]

Writes the Trajectory to a specified file

Parameters:

filename – File to store Trajectory

pybnf.pset.clear_sim_registry()[source]

Remove this run’s registry directory and disable the registry (called at normal run end so the directory does not linger in tempdir).

pybnf.pset.reap_active_sims()[source]

SIGKILL every process group recorded in this node’s registry, returning the PGIDs killed. Called from pybnf.main()’s finally on every exit – a no-op on normal completion (finished sims have deregistered). Already-dead groups (ProcessLookupError) and non-PGID filenames are skipped.

pybnf.pset.run_subprocess(cmd, timeout, stdout=None, stderr=None, input=None, env=None)[source]

Run a subprocess with process-group-based cleanup on timeout.

Uses start_new_session=True so that on timeout, the entire process group (including any grandchild processes) is killed via os.killpg(). This prevents zombie processes when e.g. run_network spawns children that outlive the parent.

On Windows, falls back to proc.kill() (no process group support).

Parameters:
  • cmd – Command to run (list of strings)

  • timeout – Timeout in seconds, or None for no timeout

  • stdout – File object or subprocess constant for stdout

  • stderr – File object or subprocess constant for stderr

  • input – Bytes to send to stdin, or None

  • env – Optional environment overrides

Raises:
  • CalledProcessError – If the subprocess exits with non-zero return code

  • TimeoutExpired – If the subprocess exceeds the timeout

Returns:

stdout bytes if stdout=PIPE, else None

pybnf.pset.set_sim_registry(run_id)[source]

Enable the live-sim registry for this run (called once by pybnf.main()).

Sets PYBNF_SIM_REGISTRY so locally-spawned dask workers inherit it, sweeps stale registry directories from previous kill -9’d runs, and creates this run’s directory up front.