pykingenie package

Public API for surface- and solution-based kinetic analysis.

Subpackages

Submodules

pykingenie.biacore module

Import surface plasmon resonance (SPR) data from Biacore result files (.blr).

A .blr file is a compound file (see utils/compound_file.py) written by the Biacore control software (checked with Biacore T200 Control Software 2.0.2). It holds one storage per cycle, with:

  • an event log (_Cycle N/EventLog), with the injections of the cycle;

  • one curve per flow cell and per reference-subtracted pair (_Cycle N/_Window 1/_Curve K), with keywords (flow cell, sample, concentration, ligand) and the sensorgram, stored as Segment (equally spaced times) or XYData (explicit times).

Each flow cell (and subtracted pair, e.g. Fc4-3) becomes a sensor. The cycles are placed on a single time axis at their start in the run (seconds after the run start, from the date stamps of the event logs), and each cycle is split into steps from its event log:

  • sample injection start to end: association (‘ASSOC’);

  • from the end of the sample injection to the end of the report period (event 37) or the next injection: dissociation (‘DISASSOC’);

  • regeneration injections: ‘KREGENERATION’; capture injections: ‘LOADING’;

  • the periods of buffer flow in between: ‘BASELINE’.

class pykingenie.biacore.BiacoreExperiment(name='biacore')[source]

Bases: SurfaceBasedExperiment

Surface plasmon resonance experiment read from a Biacore result file (.blr).

Parameters:

name (str, optional) – Name of the experiment. Default is ‘biacore’.

xs

Time values, one list per sensor (flow cell) with one array per step.

Type:

list of list of numpy.ndarray

ys

Response values (RU), one list per sensor with one array per step.

Type:

list of list of numpy.ndarray

df_steps

Step information with columns ‘#Step’, ‘Name’, ‘Type’, ‘Start’, ‘Cycle’, ‘Sample_position’, ‘Column_location’ and ‘Loading_location’.

Type:

pandas.DataFrame

ligand_conc_df

One row per sensor and association step, with the analyte concentration.

Type:

pandas.DataFrame

exp_info

Run information: instrument software, run type, run start and end, sensor chip, ligand and immobilization level per flow cell, and the concentration unit of the file.

Type:

dict

sample_row, sample_column, sample_type, sample_id, sample_conc, sample_conc_labeled

Rack positions used by the injections, one entry per position, for plot_plate_info. Rows carry the rack (e.g. ‘R1 C’ for position R1C5).

read_blr(file)[source]

Read a Biacore result file (.blr) and populate the experiment.

Parameters:

file (str) – Path to the .blr file.

Return type:

None

pykingenie.carterra module

Import Carterra row-oriented CSV exports: Label, X1, Y1, X2, Y2, ....

What the file provides

  • One sensorgram per row: a Label and its time/response pairs, each row on its own time grid. Rows marked NotFitted are still imported.

  • The row label (for example [Ligand 1-CH31 Conc. 13] [Fitted]). The Conc. N in it is an index, not a molar concentration.

What the file does not provide

  • When each injection starts and ends, or the time between injections.

  • Analyte concentrations: every concentration is NaN unless supplied.

  • Which spot/ROI the rows come from, beyond what the label says.

  • Native Carterra .xlsx files are not read: save the worksheet as CSV first.

What the user must provide

A TitrationAnalysis Data Info Sheet (info=, see pykingenie.info_sheet) can supply the timing, concentrations, sample_id and cycle_duration below.

  • To import: association_end and, if not 0 s, association_start, in seconds on each row’s time axis. The same boundaries apply to every row. Also time_unit="min" if time is in minutes. The decimal mark (. or ,) is detected; pass decimal only if the file uses both.

  • To fit: one concentration per row (concentrations, in µM unless concentration_unit is given), or for a dilution series just top_concentration and dilution_factor; and sample_id to group rows of the same analyte (by default all rows form one group).

  • For a single-cycle (titration) series on one sensor: single_cycle=True, cycle_duration (seconds from one injection to the next, used to rebuild the run clock), rows in acquisition order, one sample_id and a concentration for every row. Different sensors need separate imports.

  • Alignment is not done on import; call align_association before fitting.

class pykingenie.carterra.CarterraExperiment(name='carterra')[source]

Bases: SensorgramTextExperiment

Carterra row-oriented CSV export: Label, X1, Y1, X2, Y2, … .

Each row is a sensorgram. Conc. N in a label is an index, not a molar value. XLSX exports must first be saved as CSV; no Excel dependency is required.

read_csv(file, *, association_end=None, association_start=None, concentrations=None, concentration_unit=None, time_unit='s', sample_id=None, decimal=None, encoding='utf-8-sig', single_cycle=False, cycle_duration=None, info=None, top_concentration=None, dilution_factor=None, highest_last=True)[source]

Read Carterra CSV with caller-supplied phase boundaries in seconds.

Comma, semicolon and tab delimiters are detected automatically. Standard CSV quoting and spaces after delimiters are accepted.

Concentrations and sample_id follow SprTextExperiment.read_file(). Original row labels and each curve’s time grid are retained. Labels marked NotFitted remain measured data and are included in the import.

With single_cycle=True, rows must be consecutive injections on one physical sensor, in acquisition order. Supply cycle_duration in seconds: each row’s exported clock is translated by this period. This timing is caller supplied, not inferred from labels or signal shape. Rows must not overlap on the resulting clock. The next row’s pre-association baseline extends the preceding dissociation, yielding BASELINE, ASSOC, DISASSOC, ASSOC, DISASSOC, … . This lets align_association preserve occupied states after the first injection and lets the existing fitter carry the bound state between injections. No response is shifted or interpolated during import. Different physical sensors need separate imports.

info is a TitrationAnalysis Data Info Sheet path, or one row of read_info_sheet(). It supplies the association boundaries, the molar concentrations, sample_id (the analyte) and, with single_cycle=True, cycle_duration = Baseline + Association + Dissociation. Arguments you pass take precedence. Without info, association_start defaults to 0 s and sample_id to “sample”.

For a dilution series, pass top_concentration (in concentration_unit, µM by default) and dilution_factor instead of concentrations: row k from the highest gets top_concentration / dilution_factor**k. By default the highest concentration is the last row, as in a titration run from low to high; set highest_last=False if it is the first row. The series is assigned by row order only, not from the labels.

pykingenie.file_detection module

Identify supported input layouts without fitting or inferring experiment metadata.

pykingenie.file_detection.detect_file_format(file)[source]

Return a supported format identifier, or 'unknown' when ambiguous.

Identify content rather than the filename extension. Text headers are searched within the first 64 KiB of uncompressed data, including metadata preambles, UTF-8 BOMs, Windows-1252 text, and comma/tab/semicolon delimiters. Gzip text exports are recognized by their compression signature. Numeric data and injection boundaries are not validated or inferred.

Returns one of octet_frd, biacore_blr, gator_csv, gator_steps, gator_settings, gator_zip, kingenie_surface, kingenie_solution, surface_csv_steps, surface_csv_traces, spr_text, carterra_csv, or unknown. All paired-column SPR header variants use spr_text; this identifies their common reader, not the instrument manufacturer.

Missing or inaccessible files raise the underlying filesystem error. Generic Time/Signal data and unsupported native XLSX exports return unknown. Detection does not imply that all required companion files or fit metadata are present, or that the full file will pass reader validation.

pykingenie.fitter module

Shared base class for kinetics fitting result state and utilities.

pykingenie.fitter.store_fit_result(model, **variants)[source]

Archive successful public fits, excluding internal fits for initial guesses.

variants maps boolean option names to distinct model keys. Other fitting options are recorded in the snapshot’s fit_settings dictionary.

pykingenie.fitter.update_fit_result(method)[source]

Keep the active snapshot current after optional diagnostics are added.

class pykingenie.fitter.KineticsFitterGeneral[source]

Bases: object

A class used to handle kinetics data both for solution-based and surface-based experiments.

save_fit_result(name=None, **fit_arguments)[source]

Save an independent snapshot of the active fit and return its key.

Parameters:
  • name (str, optional) – Custom key, for example ‘one_site_shared_smax’. Defaults to the active result’s key. Existing entries at that key are replaced.

  • **fit_arguments – Arguments used for the active fit, for example shared_smax=True, fixed_t0=False or time_limit=100. Supplied values are checked against the fitted configuration. All actual arguments, including defaults, are saved even when none are supplied here. A mismatch raises ValueError; unknown argument names raise TypeError.

Notes

Snapshots contain fitted signals, tables, errors, correlations, bounds, initial guesses, settings and any calculated LOO/CI diagnostics. They live in memory on this fitter; this does not write a file.

Each distinct argument combination is retained in fit_result_history. Use restore_fit_result(model, **fit_arguments) to select a configuration or restore_fit_result(name) to load an explicitly named version.

validate_fit_result(name=None, **fit_arguments)[source]

Check that a saved or active fit belongs to this fitter’s current data.

Returns True for a matching dataset. Raises ValueError for changed data or missing validation metadata, without modifying the result or archive. Name and fitting arguments select results as in restore_fit_result(). With no name, validates the active result.

restore_fit_result(name, **fit_arguments)[source]

Restore a saved result for plotting, export or further diagnostics.

Switching to another result saves changes to the current one first. Restoring the active result discards its unsaved edits. Restored arrays and tables are copied, so editing them cannot change the saved snapshot. Raises KeyError if name has not been saved on this fitter. Changed traces, times, concentrations, grouping or trimming raise ValueError before the active result or archive is changed.

Parameters:
  • name (str) – Model key or explicitly saved name.

  • **fit_arguments – Select a saved configuration of this model, for example shared_smax=True and fixed_t0=False. Unspecified arguments may be omitted if the selection is unique. Raises ValueError when no configuration matches or the selection is ambiguous. With no arguments, restores the latest snapshot at the given key.

compare_saved_fits(names=None, sort_by=None)[source]

Compare saved fits of the same observations, optionally sorted by BIC.

Parameters:
  • names (sequence of str or str, optional) – Saved result keys/names to compare. With None, include each stored model/argument configuration once, without duplicating named aliases.

  • sort_by (str or None, optional) – With None (default), preserve the selected result order. With ‘BIC’, sort by increasing BIC, preserving order for equal scores.

Returns:

Model, Fit settings, Parameter count, Reduced χ² and BIC columns, indexed by Result. Lower BIC is preferred. Empty archives return an empty table with these columns.

Return type:

pandas.DataFrame

Notes

Fits are unweighted: reduced chi squared is RSS/(n-k), assuming unit observation variance. BIC is n*log(RSS/n) + k*log(n). k counts all free parameters, including amplitudes, offsets and per-trace parameters. n is the actual fitted point count. Requires n > k, finite predictions, unchanged input data and identical fitted observations/time ranges across selected fits. This method does not refit or restore any result.

clear_fittings()[source]

Clear active fitting results, retaining the saved model snapshots.

Resets all fitted signal arrays and parameter dataframes to None. Outside a fit, saves the active result before clearing it.

Return type:

None

create_fitting_bounds_table()[source]

Create a dataframe with the fitting bounds and the fitted parameters.

Uses the class attributes params, low_bounds and high_bounds to create a DataFrame with fitting boundaries.

Returns:

Updates the fitted_params_boundaries attribute with a DataFrame.

Return type:

None

pykingenie.fitter_solution module

Fit kinetic models to solution-based experimental data.

class pykingenie.fitter_solution.KineticsFitterSolution(name, assoc, lig_conc, protein_conc, time_assoc)[source]

Bases: KineticsFitterGeneral

A class used to fit solution-based kinetics data with shared thermodynamic parameters.

Parameters:
  • name (str) – Name of the experiment.

  • assoc (list) – List containing the association signals.

  • lig_conc (list) – List of ligand concentrations, one per element in assoc.

  • protein_conc (list) – List of protein concentrations, one per element in assoc.

  • time_assoc (list) – List of time points for the association signals.

name

Name of the experiment.

Type:

str

assoc_lst

List containing the association signals.

Type:

list

lig_conc

List of ligand concentrations, one per element in assoc.

Type:

list

prot_conc

List of protein concentrations, one per element in assoc.

Type:

list

time_assoc_lst

List of time points for the association signals.

Type:

list

signal_ss

List of steady state signals.

Type:

list

signal_ss_fit

List of steady state fitted signals.

Type:

list

signal_assoc_fit

List of association kinetics fitted signals.

Type:

list

fit_params_kinetics

DataFrame with the fitted parameters.

Type:

pd.DataFrame

fit_params_ss

DataFrame with the values of the fitted parameters - steady state.

Type:

pd.DataFrame

get_steady_state()[source]

Get the steady state signals from the association signals.

The steady state signal is calculated as the median of the last 5 values of each association signal. The signals are grouped by protein concentration.

Returns:

Updates the following instance attributes: - unq_prot_conc: Unique protein concentrations - signal_ss_per_protein: Steady state signals grouped by protein concentration - lig_conc_per_protein: Ligand concentrations grouped by protein concentration

Return type:

None

fit_single_exponentials()[source]

Fit single exponentials to the association signals in the solution kinetics experiment.

This method fits each association curve with a single exponential function and extracts the observed rate constants (k_obs). The results are then grouped by protein concentration.

Returns:

Updates the following instance attributes: - k_obs: List of observed rate constants for each association curve - signal_assoc_fit: List of fitted association signals - fit_params_kinetics: DataFrame with the fitted parameters

Return type:

None

group_k_obs_by_protein_concentration()[source]

Group the observed rate constants by protein concentration.

This is useful for plotting the rate constants against the protein concentration and for subsequent analysis of the concentration dependence of the kinetics.

Returns:

Updates the k_obs_per_prot attribute with a dictionary mapping protein concentrations to arrays of observed rate constants.

Return type:

None

fit_double_exponentials(min_log_k=-4, max_log_k=4, log_k_points=22)[source]

Fit double exponentials to the association signals in the solution kinetics experiment.

This method fits each association curve with a double exponential function and extracts two observed rate constants (k_obs_1 and k_obs_2). The results are then grouped by protein concentration.

Parameters:
  • min_log_k (float, optional) – Minimum value of log10(k) to search, default is -4.

  • max_log_k (float, optional) – Maximum value of log10(k) to search, default is 4.

  • log_k_points (int, optional) – Number of points to sample in the log(k) space, default is 22.

Returns:

Updates the following instance attributes: - k_obs_1: List of first observed rate constants for each association curve - k_obs_2: List of second observed rate constants for each association curve - signal_assoc_fit: List of fitted association signals - fit_params_kinetics: DataFrame with the fitted parameters

Return type:

None

group_double_exponential_k_obs_by_protein_concentration()[source]

Group the observed rate constants by protein concentration for double exponential fits.

This is useful for plotting the rate constants against the protein concentration and for subsequent analysis of the concentration dependence of the kinetics when using double exponential fits.

Returns:

Updates the following instance attributes: - k_obs_1_per_prot: Dictionary mapping protein concentrations to arrays of first observed rate constants - k_obs_2_per_prot: Dictionary mapping protein concentrations to arrays of second observed rate constants

Return type:

None

fit_one_binding_site(fit_signal_E=False, fit_signal_S=False, fit_signal_ES=True, fixed_t0=True)[source]

Fit the association signals assuming one binding site.

This is a simplified model that assumes a single binding site for the ligand on the protein. The model fits global parameters to all curves simultaneously.

Parameters:
  • fit_signal_E (bool, optional) – If True, fit the signal of the free protein E, default is False.

  • fit_signal_S (bool, optional) – If True, fit the signal of the free ligand S, default is False.

  • fit_signal_ES (bool, optional) – If True, fit the signal of the complex ES, default is True.

  • fixed_t0 (bool, optional) – If True, fix the t0 parameter to 0, default is True.

Returns:

Updates the following instance attributes: - signal_assoc_fit: List of fitted association signals - fit_params_kinetics: DataFrame with the fitted parameters

Return type:

None

find_initial_params_if(fit_signal_E=False, fit_signal_S=False, fit_signal_ES=True, ESint_equals_ES=True, fixed_t0=True, fit_scale_factor=False, scale_factor_tolerance=0.2)[source]

Find optimal initial parameters for the induced fit model.

Heuristically finds the best initial parameters for the fit by exploring fixed values of kc and krev and fitting kon and koff (and the signal of the complex).

Parameters:
  • fit_signal_E (bool, optional) – If True, fit the signal of the free protein E, default is False.

  • fit_signal_S (bool, optional) – If True, fit the signal of the free ligand S, default is False.

  • fit_signal_ES (bool, optional) – If True, fit the signal of the complex ES, default is True.

  • ESint_equals_ES (bool, optional) – If True, assume that the signal of the intermediate ESint is equal to the signal of the complex ES, default is True.

  • fixed_t0 (bool, optional) – If True, fix the t0 parameter to 0, default is True.

  • fit_scale_factor (bool, optional) – If True, fit a scale factor for the signals, default is False.

  • scale_factor_tolerance (float, optional) – Tolerance for the scale factor fit, default is 0.2.

Returns:

Updates the params_guess attribute with the best initial parameters.

Return type:

None

fit_induced_fit(fit_signal_E=False, fit_signal_S=False, fit_signal_ES=True, ESint_equals_ES=True, fixed_t0=True, fit_scale_factor=False, scale_factor_tolerance=0.2)[source]

Fit the association signals assuming an induced-fit mechanism.

A + B <-> AB_intermediate <-> AB_trapped

This model accounts for conformational changes in the protein upon ligand binding.

Parameters:
  • fit_signal_E (bool, optional) – If True, fit the signal of the free protein E, default is False.

  • fit_signal_S (bool, optional) – If True, fit the signal of the free ligand S, default is False.

  • fit_signal_ES (bool, optional) – If True, fit the signal of the complex ES, default is True.

  • ESint_equals_ES (bool, optional) – If True, assume that the signal of the intermediate ESint is equal to the signal of the complex ES, default is True.

  • fixed_t0 (bool, optional) – If True, fix the t0 parameter to 0, default is True.

  • fit_scale_factor (bool, optional) – If True, fit a scale factor for the signals, default is False.

  • scale_factor_tolerance (float, optional) – Tolerance for the scale factor fit, default is 0.2.

Returns:

Updates the following instance attributes: - signal_assoc_fit: List of fitted association signals - fit_params_kinetics: DataFrame with the fitted parameters

Return type:

None

find_initial_params_cs(fit_signal_E=False, E1_equals_E2=True, fit_signal_S=False, fit_signal_E2S=True, fixed_t0=True, fit_scale_factor=False, scale_factor_tolerance=0.2)[source]

Find optimal initial parameters for the conformational selection model.

Heuristically finds the best initial parameters for the fit by exploring fixed values of kc and krev and fitting kon and koff (and the signal of the complex).

Parameters:
  • fit_signal_E (bool, optional) – If True, fit the signal of the free protein E, default is False.

  • E1_equals_E2 (bool, optional) – If True, assume that the signal of the two conformations of the free protein E1 and E2 are equal, default is True.

  • fit_signal_S (bool, optional) – If True, fit the signal of the free ligand S, default is False.

  • fit_signal_E2S (bool, optional) – If True, fit the signal of the complex E2S, default is True.

  • fixed_t0 (bool, optional) – If True, fix the t0 parameter to 0, default is True.

  • fit_scale_factor (bool, optional) – If True, fit a scale factor for the signals, default is False.

  • scale_factor_tolerance (float, optional) – Tolerance for the scale factor fit, default is 0.2.

Returns:

Updates the params_guess attribute with the best initial parameters.

Return type:

None

fit_conformational_selection(fit_signal_E=False, E1_equals_E2=True, fit_signal_S=False, fit_signal_E2S=True, fixed_t0=True, fit_scale_factor=False, scale_factor_tolerance=0.2)[source]

Fit the association signals assuming an conformational selection mechanism.

A_active <-> A_inactive

A_active + B <-> AB

This model accounts for conformational changes in the protein before ligand binding.

Parameters:
  • fit_signal_E (bool, optional) – If True, fit the signal of the free protein E, default is False.

  • E1_equals_E2 (bool, optional) – If True, assume that the signal of the two conformations of the free protein E1 and E2 are equal, default is True.

  • fit_signal_S (bool, optional) – If True, fit the signal of the free ligand S, default is False.

  • fit_signal_E2S (bool, optional) – If True, fit the signal of the complex E2S, default is True.

  • fixed_t0 (bool, optional) – If True, fix the t0 parameter to 0, default is True.

Returns:

Updates the following instance attributes: - signal_assoc_fit: List of fitted association signals - fit_params_kinetics: DataFrame with the fitted parameters

Return type:

None

create_export_df(type='raw')[source]

Create

Parameters:
type
Returns:
namestr

Name of the experiment.

assoc_lstlist

List containing the association signals.

lig_conclist

List of ligand concentrations, one per element in assoc.

prot_conclist

List of protein concentrations, one per element in assoc.

time_assoc_lstlist

List of time points for the association signals.

pykingenie.fitter_surface module

Fit steady-state and kinetic models to surface-based experimental data.

class pykingenie.fitter_surface.KineticsFitter(time_assoc_lst, association_signal_lst, lig_conc_lst, time_diss_lst=None, dissociation_signal_lst=None, smax_id=None, name_lst=None, is_single_cycle=False, trim_time=0)[source]

Bases: KineticsFitterGeneral

A class used to fit kinetics data with shared thermodynamic parameters.

Parameters:
  • time_assoc_lst (list) – List of time points for the association signals, one per replicate.

  • association_signal_lst (list) – List of association signals, one per replicate.

  • lig_conc_lst (list) – List of ligand concentrations, one per replicate.

  • time_diss_lst (list, optional) – List of time points for the dissociation signals, one per replicate.

  • dissociation_signal_lst (list, optional) – List of dissociation signals, one per replicate.

  • smax_id (list, optional) – List containing the Smax IDs (maximum amplitude identifiers).

  • name_lst (list, optional) – List of experiment names.

  • is_single_cycle (bool, optional) – Whether the experiment is a single cycle kinetics experiment.

names

List of experiment names.

Type:

list

assoc_lst

List of association signals, one per replicate. Each signal is a numpy matrix of size n*m where n is the number of time points and m is the number of ligand concentrations.

Type:

list

disso_lst

List of dissociation signals, one per replicate. Each signal is a numpy matrix of size n*m where n is the number of time points and m is the number of ligand concentrations (different from zero).

Type:

list

lig_conc_lst

List of ligand concentrations, one per replicate.

Type:

list

time_assoc_lst

List of time points for the association signals, one per replicate.

Type:

list

time_disso_lst

List of time points for the dissociation signals, one per replicate.

Type:

list

is_single_cycle

Whether the experiment is a single cycle kinetics experiment.

Type:

bool

signal_ss

List of steady state signals, one per replicate.

Type:

list

signal_ss_fit

List of steady state fitted signals, one per replicate.

Type:

list

signal_assoc_fit

List of association kinetics fitted signals, one per replicate.

Type:

list

signal_disso_fit

List of dissociation kinetics fitted signals, one per replicate.

Type:

list

lig_conc_lst_per_id

Ligand concentrations per Smax ID.

Type:

list

smax_guesses_unq

Smax guesses per association signal.

Type:

list

smax_guesses_shared

Smax guesses per Smax ID.

Type:

list

fit_params_kinetics

DataFrame with the fitted parameters for the association/dissociation kinetics.

Type:

pd.DataFrame

fit_params_ss

DataFrame with the values of the fitted parameters - steady state.

Type:

pd.DataFrame

get_steady_state()[source]

Calculate the steady state signal and group it by Smax ID.

This function calculates the steady state signal for each association curve and groups the signals by Smax ID. It also calculates the Smax guesses for each association signal.

Returns:

Updates the following instance attributes: - signal_ss: List of steady state signals grouped by Smax ID - lig_conc_lst_per_id: List of ligand concentrations grouped by Smax ID - smax_guesses_unq: Smax guesses for each association signal - smax_guesses_shared: Smax guesses for each Smax ID

Return type:

None

fit_steady_state_one_site()[source]

Fit the steady state signal to a one-site binding model.

This function fits the steady state signal to a one-site binding model to estimate the equilibrium dissociation constant (Kd) and maximum signal (Smax). It also calculates the 95% confidence intervals for the Kd.

Returns:

Updates the following instance attributes: - params: The fitted parameters [Kd, Smax1, Smax2, …] - signal_ss_fit: The fitted steady state signals - fit_params_ss: DataFrame with the fitted parameters - Kd_ss: The equilibrium dissociation constant(s) - Smax_upper_bound_factor: Factor to determine the upper bound for Smax

Return type:

None

fit_steady_state(model='one_site', fit_sigma=False)[source]

Backward-compatible steady-state fitting entry point.

Parameters:
  • model (str, optional) – Steady-state model to use. Options: ‘one_site’, ‘two_site’, ‘two_site_heterogeneous_ligand’. Default is ‘one_site’.

  • fit_sigma (bool, optional) – Only used for model=’two_site’. If True, fit cooperativity.

Return type:

None

fit_steady_state_two_site_heterogeneous_ligand()[source]

Fit the steady-state signal to a 2:1 heterogeneous ligand model.

The model is the weighted sum of two independent 1:1 interactions. Kd1, Kd2, and fraction_site1 are shared across all Smax groups; each group has its own total Rmax.

Returns:

Updates fitted steady-state signals, fitted parameters, and bounds.

Return type:

None

fit_steady_state_two_site(fit_sigma=False)[source]

Fit the steady state signal to a two-site binding model.

This function fits the steady state signal to a two-site binding model to estimate the intrinsic equilibrium dissociation constant (Kd), plus two response amplitudes per Smax group: - Rmax_PL : singly-bound state - Rmax_LPL : doubly-bound state

Optionally, a shared cooperativity factor (sigma) can be fitted.

Parameters:

fit_sigma (bool, optional) – If True, fit a shared cooperativity factor sigma. If False, use the non-cooperative two-site model.

Returns:

Updates the following instance attributes: - params: The fitted parameters - signal_ss_fit: The fitted steady state signals - fit_params_ss: DataFrame with the fitted parameters - Kd_ss: The fitted intrinsic dissociation constant - sigma_ss: The fitted cooperativity factor (if fit_sigma=True) - Smax_upper_bound_factor: Factor to determine upper Smax bounds

Return type:

None

get_k_off_initial_guess()[source]

Get initial guess and bounds for k_off parameter.

This method determines initial values and fitting bounds for Kd and k_off. If dissociation data is available, it fits the dissociation curves to get a better estimate of k_off.

Returns:

A tuple containing: - p0: Initial parameter guesses [Kd, k_off] - low_bounds: Lower bounds for the parameters - high_bounds: Upper bounds for the parameters

Return type:

tuple

Raises:

ValueError – If Kd_ss is not set and fit_steady_state has not been run

fit_one_site_association(shared_smax=True, calc_loo=False)[source]

Fit the association curves using the one-site binding model.

This function fits the association curves to a one-site binding model to estimate the equilibrium dissociation constant (Kd), dissociation rate constant (k_off), and maximum signal (Smax).

Parameters:
  • shared_smax (bool, optional) – Whether to share Smax across curves with the same Smax ID, default is True.

  • calc_loo (bool, optional) – Whether to calculate leave-one-out (LOO) estimates for Kd and k_off, default is False.

Returns:

Updates the following instance attributes: - params: The fitted parameters [Kd, k_off, Smax1, Smax2, …] - signal_assoc_fit: The fitted association signals - Kd: The equilibrium dissociation constant - k_off: The dissociation rate constant - Smax: The maximum signal values

Return type:

None

one_site_association_loo()[source]

Calculate leave-one-out (LOO) estimates for Kd and k_off.

This function calculates the LOO estimates for Kd and k_off by fitting the association curves while leaving out one curve at a time.

Return type:

None

Notes

Updates the following instance attributes: - Kd_loo: List of LOO estimates for Kd - k_off_loo: List of LOO estimates for k_off - Kd_loo_mean: Mean of LOO estimates for Kd - k_off_loo_mean: Mean of LOO estimates for k_off - Kd_loo_std: Standard deviation of LOO estimates for Kd - k_off_loo_std: Standard deviation of LOO estimates for k_off - df_fit_loo: DataFrame with mean ± SD for Kd and k_off

fit_one_site_dissociation(time_limit=0, calc_loo=False)[source]

Fit the dissociation curves using the one-site binding model.

This function fits the dissociation curves to a one-site binding model to estimate the dissociation rate constant (k_off) and the initial signal (S0).

Parameters:
  • time_limit (float, optional) – Time limit for fitting (in seconds). If > 0, only fit data up to this time, default is 0 (fit all data).

  • calc_loo (bool, optional) – Whether to calculate leave-one-out (LOO) estimates for k_off, default is False.

Returns:

Updates the following instance attributes: - params: The fitted parameters [k_off, S0_1, S0_2, …] - signal_disso_fit: The fitted dissociation signals - k_off: The dissociation rate constant - fit_params_kinetics: DataFrame with the fitted parameters - fit_params_kinetics_error: DataFrame with the relative errors

Return type:

None

one_site_dissociation_loo()[source]

Estimate dissociation-rate uncertainty by doing n-fits and leaving out each curve at a time.

Stores the leave-one-out rate estimates and their mean and standard deviation on the fitter.

Notes

Updates the following instance attributes: - k_off_loo: List of leave-one-out estimates for k_off - k_off_loo_mean: Mean of leave-one-out estimates for k_off - k_off_loo_std: Standard deviation of leave-one-out estimates for k_off - df_fit_loo: DataFrame with mean ± SD for k_off

fit_single_exponentials()[source]

Fit single exponentials to the association signals.

This method fits each association curve with a single exponential function and extracts the observed rate constants (k_obs).

Returns:

Updates the k_obs attribute with a list of observed rate constants for each association curve.

Return type:

None

fit_one_site_assoc_and_disso(shared_smax=True, fixed_t0=True, fit_ktr=False, calc_loo=False)[source]

Fit association and dissociation curves simultaneously using a one-site binding model.

Parameters:
  • shared_smax (bool, optional) – Whether to share Smax across curves with the same Smax ID, default is True.

  • fixed_t0 (bool, optional) – Whether to fix the t0 parameter (time offset) during fitting, default is True.

  • fit_ktr (bool, optional) – Whether to fit the k_tr parameter (mass transfer rate) during fitting, default is False.

  • calc_loo (bool, optional) – Whether to calculate leave-one-out cross-validation, default is False.

one_site_assoc_and_disso_loo()[source]

Estimate one-site kinetic parameter uncertainty by leave-one-out fits.

Repeats the global association/dissociation fit after omitting each curve and stores the resulting parameter distributions.

Notes

Updates the following instance attributes: - Kd_loo: List of leave-one-out estimates for Kd - k_off_loo: List of leave-one-out estimates for k_off - Kd_loo_mean: Mean of leave-one-out estimates for Kd - k_off_loo_mean: Mean of leave-one-out estimates for k_off - Kd_loo_std: Standard deviation of leave-one-out estimates for Kd - k_off_loo_std: Standard deviation of leave-one-out estimates for k_off - df_fit_loo: DataFrame with mean ± SD for Kd and k_off

fit_two_site_assoc_and_disso(shared_smax=True, fixed_t0=True, fit_sigma=False, calc_loo=False)[source]

Fit a two-to-one binding model, where the ligand (attached molecule) has two binding sites

Parameters:
  • shared_smax (bool, optional) – Whether to share Smax across curves with the same Smax ID, default is True. In this case, there are two Smax parameters, one for the single-bound state and one for the double-bound state, but they are shared across curves with the same Smax ID.

  • fixed_t0 (bool, optional) – Whether to fix the time offset (t0) to zero, default is True.

  • fit_sigma (bool, optional) – Whether to fit a shared cooperativity factor (sigma) for the two binding sites, default is False. If False, the model assumes non-cooperative binding (sigma=1).

  • calc_loo (bool, optional) – Whether to calculate leave-one-out (LOO) estimates for Kd and k_off, default is False. If True, the function will fit the model multiple times, each time leaving out one curve, to estimate the variability of the fitted parameters.

two_site_assoc_and_disso_loo()[source]

Estimate two-site kinetic parameter uncertainty by leave-one-out fits.

Repeats the global association/dissociation fit after omitting each curve and stores the resulting parameter distributions.

Notes

Updates the following instance attributes: - Kd_loo: List of leave-one-out estimates for Kd - k_off_loo: List of leave-one-out estimates for k_off - Kd_loo_mean: Mean of leave-one-out estimates for Kd - k_off_loo_mean: Mean of leave-one-out estimates for k_off - Kd_loo_std: Standard deviation of leave-one-out estimates for Kd - k_off_loo_std: Standard deviation of leave-one-out estimates for k_off - df_fit_loo: DataFrame with mean ± SD for Kd and k_off - sigma_loo: List of leave-one-out estimates for sigma (if fitted) - sigma_loo_mean: Mean of leave-one-out estimates for sigma (if fitted) - sigma_loo_std: Standard deviation of leave-one-out estimates for sigma (if fitted

fit_two_site_heterogeneous_ligand_assoc_and_disso(shared_smax=True, fixed_t0=True, Kd1_values=None, Kd2_values=None, calc_loo=False)[source]

Fit a 2:1 heterogeneous ligand kinetic model.

The model is a weighted sum of two independent 1:1 interactions. A grid search over fixed Kd1/Kd2 pairs is used to find initial parameters before the full model is fitted. Only pairs where Kd1 < Kd2 are evaluated, so Kd1 represents the higher-affinity site.

Parameters:
  • shared_smax (bool, optional) – Whether to share Rmax across curves with the same Smax ID.

  • fixed_t0 (bool, optional) – Whether to fix the time offset (t0) to zero.

  • Kd1_values (list, optional) – Candidate Kd1 values for the grid search.

  • Kd2_values (list, optional) – Candidate Kd2 values for the grid search.

  • calc_loo (bool, optional) – Whether to calculate leave-one-out cross-validation.

Returns:

Updates fitted signal, parameter, bounds, and grid-search attributes.

Return type:

None

two_site_heterogeneous_ligand_assoc_and_disso_loo()[source]

Estimate heterogeneous-ligand fit uncertainty by doing n-fits leaving out one curve at a time.

Repeats the global association/dissociation fit after omitting each curve and stores the resulting parameter distributions.

Notes

Updates the following instance attributes: - Kd1_loo: List of leave-one-out estimates for Kd1 - k_off1_loo: List of leave-one-out estimates for k_off1 - Kd2_loo: List of leave-one-out estimates for Kd2 - k_off2_loo: List of leave-one-out estimates for k_off2 - fraction_site1_loo: List of leave-one-out estimates for fraction_site1 - Kd1_loo_mean: Mean of leave-one-out estimates for Kd1 - k_off1_loo_mean: Mean of leave-one-out estimates for k_off1 - Kd2_loo_mean: Mean of leave-one-out estimates for Kd2 - k_off2_loo_mean: Mean of leave-one-out estimates for k_off2 - fraction_site1_loo_mean: Mean of leave-one-out estimates for fraction_site1 - Kd1_loo_std: Standard deviation of leave-one-out estimates for Kd1 - k_off1_loo_std: Standard deviation of leave-one-out estimates for k_off1 - Kd2_loo_std: Standard deviation of leave-one-out estimates for Kd2 - k_off2_loo_std: Standard deviation of leave-one-out estimates for k_off2 - fraction_site1_loo_std: Standard deviation of leave-one-out estimates for fraction_site1 - df_fit_loo: DataFrame with mean ± SD for Kd1, k_off1, Kd2, k_off2, and fraction_site1

fit_bivalent_analyte_assoc_and_disso(shared_smax=True, fixed_t0=True, ka2_rmax_values=None, kd2_factors=None, koff1_factors=None, n_starts=3, calc_loo=False)[source]

Fit the bivalent analyte model to the association and dissociation curves.

The analyte binds the immobilised ligand with one arm (Kd1, k_off1) and the bound analyte binds a second ligand with its other arm (k_a2, k_d2). See ode_bivalent_analyte in utils.signal_surface for the rate equations.

Both bound states give the same signal per analyte (signal = AL + AL2), and Rmax is the signal with one analyte on every ligand. k_a2 and Kd2 are in the units of the data (signal: RU for SPR, nm for BLI), so they depend on the ligand density and are not comparable between instruments.

Avidity slows the observed dissociation, so the one-to-one fit underestimates k_off1, but its association rate approximates 2 * k_on1. A grid search on subsampled curves tries k_off1 starts at multiples of the one-to-one k_off, with Kd1 from that association rate, and fixed k_a2 and k_d2 values. The grid fits share Rmax within each Smax group and use looser solver and optimizer tolerances, since they only rank starting points. All parameters are then fitted from the best grid points with distinct k_a2 and k_d2 values, and the fit with the lowest residual is kept.

Parameters:
  • shared_smax (bool, optional) – Whether to share Rmax across curves with the same Smax ID, default is True.

  • fixed_t0 (bool, optional) – Whether to fix the time offset (t0) to zero, default is True.

  • ka2_rmax_values (list, optional) – Grid values of k_a2 * Rmax, in 1/s: the initial rate at which a bound analyte binds its second ligand on an empty surface. Default is [1e-3, 1e-2, 1e-1, 1, 10].

  • kd2_factors (list, optional) – Grid values of k_d2, as multiples of the one-to-one k_off. Default is [0.1, 1, 10, 100, 1000]: with a fast second arm, k_d2 can be orders of magnitude above the observed dissociation rate.

  • koff1_factors (list, optional) – Starting values of k_off1 in the grid, as multiples of the one-to-one k_off. Default is [1, 10, 100, 1000].

  • n_starts (int, optional) – Number of grid points the final fit starts from: the best grid point for each of the n_starts best (k_a2, k_d2) pairs. The fit with the lowest residual is kept. Default is 3.

  • calc_loo (bool, optional) – Whether to calculate leave-one-out errors, default is False.

Returns:

Updates the fitted signals, parameters (Kd1, k_off1, k_a2, k_d2, Rmax), bounds and the grid search table (bivalent_analyte_grid_search).

Return type:

None

bivalent_analyte_assoc_and_disso_loo()[source]

Estimate the bivalent analyte fit uncertainty by leaving out one curve at a time.

If the omitted curve feeds into another injection in a single-cycle run, fit the starting bound state of that injection from the retained data.

Notes

Updates Kd1_loo, k_off1_loo, k_a2_loo and k_d2_loo (lists of estimates), their _mean and _std, and df_fit_loo (mean ± SD of each).

calculate_ci95(shared_smax=None, fixed_t0=None, fit_ktr=None)[source]

Calculate 95% confidence intervals for the fitted parameters.

This method computes asymmetrical 95% confidence intervals for the equilibrium dissociation constant (Kd) and the dissociation rate constant (k_off) of the one-site association and dissociation fit.

Parameters:
  • shared_smax (bool, optional) – Whether Smax was shared across curves with the same Smax ID. Default is None: use the setting of the fit.

  • fixed_t0 (bool, optional) – Whether the time offset (t0) was fixed to zero. Default is None: use the setting of the fit.

  • fit_ktr (bool, optional) – Whether mass transport rate constants were included in the model. Default is None: use the setting of the fit.

Returns:

Updates the fit_params_kinetics_ci95 attribute with a DataFrame containing the 95% confidence intervals for Kd and k_off.

Return type:

None

Raises:

ValueError – If a setting is given and differs from the one used by the fit. The fitted parameters would otherwise be read in the wrong order.

Notes

This method will create an empty DataFrame if the confidence interval calculation fails, if the last fit is not the one-site association and dissociation fit, or if it included mass transport.

fit_one_site_if_assoc_and_disso(shared_smax=True, calc_loo=False, fit_signal_ratio=False, signal_ratio_bounds=(0.1, 10.0))[source]

Fit the association and dissociation signals using the induced fit model.

This method first fits a simple one-site model to get initial parameter estimates, then explores different values of the conformational change rate constants (kc and krev) to find good initial guesses for the induced fit model. Finally, it fits the full induced fit model with these initial guesses. If that fit fails, it starts again from the next-best guesses (up to three) and raises the error only if all fail.

Parameters:
  • shared_smax (bool, optional) – Whether to share Smax across curves with the same Smax ID, default is True.

  • calc_loo (bool, optional) – Whether to calculate leave-one-out cross-validation.

  • fit_signal_ratio (bool, optional) – If True, the induced complex (AL) may produce a different signal than the intermediate complex (ALint). Their ratio is fitted as one global parameter, and Smax is the signal of the surface fully occupied by ALint. Default is False (both produce the same signal). A is the analyte (the molecule in solution) and L the ligand immobilised on the sensor: A + L <-> ALint <-> AL.

  • signal_ratio_bounds (tuple of float, optional) – Lower and upper bounds for the signal ratio, default is (0.1, 10).

Return type:

None

Notes

Updates the following instance attributes: - params: The fitted parameters [k_on, k_off, k_c, k_rev, (signal_ratio), Smax1, Smax2, …] - signal_assoc_fit: The fitted association signals - signal_disso_fit: The fitted dissociation signals - k_on: The association rate constant - k_off: The dissociation rate constant - k_c: The forward conformational change rate constant - k_rev: The reverse conformational change rate constant - signal_ratio: Signal of AL relative to ALint (1 if not fitted) - Smax: The maximum signal values - fit_params_kinetics: DataFrame with the fitted parameters

one_site_if_assoc_and_disso_loo()[source]

Estimate induced-fit parameter uncertainty by leave-one-out refitting.

Repeats the global association/dissociation fit after omitting each replicate and stores the resulting parameter distributions.

calc_leave_one_out_errors()[source]

Calculate leave-one-out estimates for the currently fitted model.

create_export_df(type='raw')[source]

Create a data frame with the raw or fitted signals for the association and dissociation phases.

Parameters:

type (str, optional) – The type of signal to include in the ‘Signal’ column. If ‘raw’, the raw association and dissociation signals are used. If ‘fit’, the fitted association and dissociation signals are used. Default is ‘raw’.

Returns:

A DataFrame with the following columns: - ‘Time’: Time points for the association and dissociation signals. - ‘Signal’: The corresponding signal values (raw or fitted). - ‘Analyte_concentration_micromolar’: The analyte concentration in micromolar for each signal. - ‘Type’: A categorical variable indicating whether the signal is from the association or dissociation phase. - ‘ID’: The identifier corresponding to the fitter name for each signal.

Return type:

pd.DataFrame

pykingenie.gator module

Import and manage Gator bio-layer interferometry experiments.

class pykingenie.gator.GatorExperiment(name='Gator_experiment')[source]

Bases: SurfaceBasedExperiment

Class to handle Gator Bio-Layer Interferometry (BLI) experiments.

This class extends the SurfaceBasedExperiment to provide functionality specific to Gator BLI instruments, including parsing experiment files and loading sensor data.

Parameters:

name (str, optional) – Name of the experiment, default is ‘Gator_experiment’.

read_all_gator_data(files, names=None)[source]

Read all Gator data files for the experiment.

This method reads all necessary files for a Gator experiment, including the experiment settings, step information, and sensor data.

Parameters:
  • files (str or list) – Path to a zip file containing Gator data files or a list of file paths. If a zip file is provided, it will be extracted to the same directory.

  • names (list, optional) – List of file names corresponding to the file paths in files. If None, the file names will be extracted from the file paths.

Returns:

Updates instance attributes with the loaded experiment data.

Return type:

None

read_experiment_ini(file, nr_max_columns=12)[source]

Read the experiment initialization file.

Parses the ExperimentStep.ini file that contains information about the experimental steps, their durations, and types (baseline, association, dissociation, etc.).

Parameters:
  • file (str) – Path to the ExperimentStep.ini file.

  • nr_max_columns (int, optional) – Maximum number of columns in the plate, default is 12.

Returns:

Updates the df_steps attribute with a DataFrame containing step information.

Return type:

None

Notes

Example format for ExperimentStep.ini:

[Experiment] Num=4 [Experiment1] Step1=0,0,60,0 Step2=1,60,104,1 Step3=5,104,164,0 Step4=6,164,464,2 Step5=7,464,764,3 Num=5 ProbeIndex=12 [ExperimentLog] Step1=”{“StepType”:0,”AssayNumber”:1,”PlateIndex”:1,”PlateColumnType”:12,”RowLocation”:0,”Location”:0,”Speed”:400,”Time”:600,”SumTime”:0,”ProbeIndex”:0,”PickerUsed”:1,”AllChannelUsed”:[255],”ChannelUsed”:0,”bAssayFirstStep”:false,”kst”:0,”Status”:0}” Step2=”{“StepType”:3,”AssayNumber”:1,”PlateIndex”:1,”PlateColumnType”:12,”RowLocation”:0,”Location”:1,”Speed”:1000,”Time”:5,”SumTime”:0,”ProbeIndex”:0,”PickerUsed”:1,”AllChannelUsed”:[255],”ChannelUsed”:0,”bAssayFirstStep”:false,”kst”:0,”Status”:0}” Step3=”{“StepType”:4,”AssayNumber”:1,”PlateIndex”:1,”PlateColumnType”:12,”RowLocation”:0,”Location”:2,”Speed”:1000,”Time”:5,”SumTime”:0,”ProbeIndex”:0,”PickerUsed”:1,”AllChannelUsed”:[255],”ChannelUsed”:0,”bAssayFirstStep”:false,”kst”:0,”Status”:0}” Step4=”{“StepType”:3,”AssayNumber”:1,”PlateIndex”:1,”PlateColumnType”:12,”RowLocation”:0,”Location”:1,”Speed”:1000,”Time”:5,”SumTime”:0,”ProbeIndex”:0,”PickerUsed”:1,”AllChannelUsed”:[255],”ChannelUsed”:0,”bAssayFirstStep”:false,”kst”:0,”Status”:0}” Step5=”{“StepType”:4,”AssayNumber”:1,”PlateIndex”:1,”PlateColumnType”:12,”RowLocation”:0,”Location”:2,”Speed”:1000,”Time”:5,”SumTime”:0,”ProbeIndex”:0,”PickerUsed”:1,”AllChannelUsed”:[255],”ChannelUsed”:0,”bAssayFirstStep”:false,”kst”:0,”Status”:0}” Step6=”{“StepType”:3,”AssayNumber”:1,”PlateIndex”:1,”PlateColumnType”:12,”RowLocation”:0,”Location”:1,”Speed”:1000,”Time”:5,”SumTime”:0,”ProbeIndex”:0,”PickerUsed”:1,”AllChannelUsed”:[255],”ChannelUsed”:0,”bAssayFirstStep”:false,”kst”:0,”Status”:0}” Step7=”{“StepType”:4,”AssayNumber”:1,”PlateIndex”:1,”PlateColumnType”:12,”RowLocation”:0,”Location”:2,”Speed”:1000,”Time”:5,”SumTime”:0,”ProbeIndex”:0,”PickerUsed”:1,”AllChannelUsed”:[255],”ChannelUsed”:0,”bAssayFirstStep”:false,”kst”:0,”Status”:0}” Step8=”{“StepType”:2,”AssayNumber”:1,”PlateIndex”:0,”PlateColumnType”:12,”RowLocation”:0,”Location”:12,”Speed”:1000,”Time”:60,”SumTime”:0,”ProbeIndex”:0,”PickerUsed”:1,”AllChannelUsed”:[255],”ChannelUsed”:0,”bAssayFirstStep”:true,”kst”:0,”Status”:0}” Step9=”{“StepType”:2,”AssayNumber”:1,”PlateIndex”:0,”PlateColumnType”:12,”RowLocation”:0,”Location”:13,”Speed”:400,”Time”:44,”SumTime”:60,”ProbeIndex”:0,”PickerUsed”:1,”AllChannelUsed”:[255],”ChannelUsed”:0,”bAssayFirstStep”:false,”kst”:1,”Status”:1}”

read_settings_ini(file, nr_max_sensors=8, nr_max_columns=12)[source]

Read the settings initialization file.

Parses the Setting.ini file that contains information about the experiment settings, including sensor configurations, sample concentrations, and plate layout.

Parameters:
  • file (str) – Path to the Setting.ini file.

  • nr_max_sensors (int, optional) – Maximum number of sensors per column, default is 8.

  • nr_max_columns (int, optional) – Maximum number of columns in the plate, default is 12.

Returns:

Updates several instance attributes: - sensor_names: List of sensor names - ligand_conc_df: DataFrame with ligand concentration information

Return type:

None

Notes

Example format for Setting.ini:

[BasicInformation] PreExperiment=”{“AssayDescription”:””,”AssayUser”:”Marianna”,”CreationTime”:”03-31-2025 14:01:50”,…}” ExperimentType=Kinetics SaveTime=03/31/2025 15:55:27 Frequency=10Hz DataVersion=2.15.5.1221 [Regeneration] RegenerationEnable=1 Repeat=3 RTime=5 RSpeed=1000 NTime=5 NSpeed=1000 [SampleKinetics] Well1=4,-1,-1,-1,, Well2=4,-1,-1,-1,, …

read_sensor_data(files, names=None)[source]

Read the sensor data from CSV files.

Parses the Gator sensor data CSV files containing time series data for each sensor channel. The method organizes the data according to experimental steps and sensors.

Parameters:
  • files (list) – List of file paths that may include sensor data CSV files.

  • names (list, optional) – List of file names corresponding to the file paths in files. If None, the file names will be extracted from the file paths.

Returns:

Updates several instance attributes: - xs: List of time arrays for each sensor - ys: List of signal arrays for each sensor - df_steps: DataFrame with filtered step information containing only steps with data - no_steps: Number of steps with data - traces_loaded: Boolean indicating if traces were successfully loaded

Return type:

None

Notes

The sensor data files are expected to be in CSV format with the following characteristics: - File names contain ‘Channel’ and have a ‘.csv’ extension - The first column contains signal values - The second column contains time values

Comma, semicolon and tab separators are detected automatically; numeric values use decimal points.

pykingenie.info_sheet module

Read TitrationAnalysis “Data Info Sheet” tables that describe SPR runs.

The sheet is the input table of the TitrationAnalysis tool (Duke University). It has one row per sensor position and is used here to fill the settings that sensorgram exports (SprTextExperiment, CarterraExperiment) lack.

What the file provides

  • Timing of each cycle in seconds: Bsl Start (time of the first baseline point), Baseline, Association and Dissociation durations, and the Asso. Skip / Disso. Skip times left out of the fit.

  • All Concentrations: the molar analyte concentrations, lowest first, and Incl. Conc.: the ones used in the analysis (All or a subset).

  • The analyte and ligand names, the sensor position, and Y/N flags for bulk shift, regeneration, baseline correction and global Rmax.

What the readers take from it

  • association_start = Bsl Start + Baseline; association_end = association_start + Association.

  • concentrations (converted to µM) and sample_id = Analyte.

  • For Carterra single-cycle imports, cycle_duration = Baseline + Association + Dissociation.

  • Curves whose concentration is not in Incl. Conc. start unselected (Select column) for fitting. Everything else is kept in exp_info["info_sheet"], for example the skip times to pass as trim_time.

What the user must still provide

  • Which row applies, when the included rows of a sheet differ in timing, analyte or concentrations.

  • concentrations when the data file holds a different number of curves than the sheet lists concentrations (for example an excerpt of the run).

pykingenie.info_sheet.read_info_sheet(file)[source]

Read a TitrationAnalysis Data Info Sheet (.xlsx, CSV or TSV).

Returns one row per sensor position with normalised columns: times in seconds (Baseline_s, Association_s …), concentrations as lists in µM (Included_concentrations_micromolar is None for All) and Y/N flags as booleans. Pass the path, or one row, to the info argument of SprTextExperiment.read_file or CarterraExperiment.read_csv.

pykingenie.kingenie_solution module

Load solution-based simulation data exported by KinGenie.

class pykingenie.kingenie_solution.KinGenieCsvSolution(name)[source]

Bases: SolutionBasedExp

A class used to represent a KinGenie simulation (solution-based).

This class handles KinGenie solution simulation data that can be exported from the Simulation panel.

Parameters:

name (str) – Name of the experiment.

name

Name of the experiment.

Type:

str

xs

List of x values (time), one array per trace.

Type:

list of numpy.ndarray

ys

List of y values (signal), one array per trace.

Type:

list of numpy.ndarray

no_traces

Number of traces.

Type:

int

traces_names

List of trace names, one per trace.

Type:

list of str

traces_names_unique

List of unique trace names.

Type:

list of str

conc_df

DataFrame with the concentration information for each trace.

Type:

pandas.DataFrame

traces_loaded

Whether traces have been loaded.

Type:

bool

read_csv(file)[source]

Read the KinGenie CSV file containing solution-based simulation data.

Parameters:

file (str) – Path to the CSV file.

Returns:

The method populates class attributes with data from the CSV file.

Return type:

None

Notes

Comma, semicolon and tab separators are detected automatically, with standard CSV quoting and decimal-point numeric values.

The CSV file should have the following columns: - Time: time points of the simulation - Signal: signal values at each time point - Protein_concentration_micromolar: protein concentration - Ligand_concentration_micromolar: ligand concentration

Example CSV format:

Time Signal Protein_concentration_micromolar Ligand_concentration_micromolar 0 0 5 0.1 0.5 1 5 0.1

After reading, this method creates the following attributes: - self.xs: list of time values for each trace - self.ys: list of signal values for each trace - self.no_traces: number of unique traces - self.traces_names: list of trace names - self.conc_df: DataFrame with concentration information

pykingenie.kingenie_surface module

Load surface-based simulation data exported by KinGenie.

class pykingenie.kingenie_surface.KinGenieCsv(name='kingenie_csv')[source]

Bases: SurfaceBasedExperiment

A class used to represent a KinGenie surface-based simulation.

This class handles data from KinGenie simulation CSV files that can be exported from the Simulation panel.

Parameters:

name (str, optional) – Name of the experiment. Default is ‘kingenie_csv’.

name

Name of the experiment.

Type:

str

fn

File name.

Type:

str

xs

List of time values for each sensor and phase. Structure is: [sensor_1[assoc_phase, disso_phase], sensor_2[assoc_phase, disso_phase], …].

Type:

list of list of numpy.ndarray

ys

List of signal values for each sensor and phase. Structure is: [sensor_1[assoc_phase, disso_phase], sensor_2[assoc_phase, disso_phase], …].

Type:

list of list of numpy.ndarray

no_sensors

Number of sensors.

Type:

int

sensor_names

List of sensor names, one per sensor.

Type:

list of str

sensor_names_unique

List of unique sensor names.

Type:

list of str

ligand_conc_df

DataFrame with the ligand concentration information.

Type:

pandas.DataFrame

df_steps

DataFrame with step information (association, dissociation).

Type:

pandas.DataFrame

traces_loaded

Whether traces have been loaded.

Type:

bool

Notes

The CSV file should contain columns for Time, Signal, Smax, and Analyte_concentration_micromolar_constant. For single cycle kinetics, it should also include a Cycle column.

read_csv(file)[source]

Read the KinGenie CSV file containing surface-based simulation data.

Parameters:

file (str) – Path to the CSV file.

Returns:

The method populates class attributes with data from the CSV file.

Return type:

None

Notes

The CSV file should have the following columns: - Time: time points of the simulation - Signal: signal values at each time point - Smax: maximum signal value - Analyte_concentration_micromolar_constant: analyte concentration - Cycle: (optional) cycle number for single cycle kinetics

This method creates the following attributes: - self.xs: list of time values for each sensor and phase - self.ys: list of signal values for each sensor and phase - self.no_sensors: number of sensors - self.sensor_names: list of sensor names - self.ligand_conc_df: DataFrame with concentration information - self.df_steps: DataFrame with step information

The method handles both multi-cycle and single-cycle kinetics data. Comma, semicolon and tab separators are detected automatically, with standard CSV quoting and decimal-point numeric values.

pykingenie.loader module

Choose and run the reader for a set of input files.

KineticsAnalyzer.load calls load_experiment. It runs detect_file_format on every file, checks that the files form one experiment of one format, creates the matching experiment class and calls its reader. Settings the files do not contain (SPR timing, concentrations, info=) are passed through as keyword options to that reader.

pykingenie.loader.load_experiment(files, name=None, taken=(), **options)[source]

Read files with the reader their format needs; return the experiment.

files is one path or a list of paths that together form one experiment: Octet .frd files (plus optional .fmf plate files), a Biacore .blr file, a Gator zip or its Setting.ini, ExperimentStep.ini and sensor CSVs, a KinGenie surface or solution CSV, a generic steps file plus traces file, a paired-column SPR export, or a Carterra CSV. options go to the reader and are accepted only by the readers that take them (SPR text, Carterra, generic steps/traces). The experiment is named name, or after the Octet run or the file, with a number appended if that automatic name is in taken.

pykingenie.main module

Manage experiments and kinetic analyses through the analyzer API.

class pykingenie.main.KineticsAnalyzer[source]

Bases: object

Coordinate experiment storage, fitting, and result access.

delete_experiment(experiment_names)[source]

Delete experiment(s) from the analyzer.

Parameters:

experiment_names (str or list of str) – Name(s) of the experiment(s) to delete.

add_experiment(experiment, experiment_name)[source]

Add an experiment to the analyzer.

Parameters:
  • experiment (object) – Experiment instance to add.

  • experiment_name (str) – Name of the experiment.

load(files, name=None, **options)[source]

Read input files with the reader their format needs and add the experiment.

The format of each file is found with detect_file_format; the files must form one experiment of one format (for example all the .frd files of an Octet run, or one SPR export). Keyword options go to that reader, such as association_end, concentrations or info for SPR text and Carterra exports.

Parameters:
  • files (str, path-like or list) – Path or paths of one experiment.

  • name (str, optional) – Experiment name. By default the Octet run name or the file name, numbered if another experiment already uses it. An explicit name replaces an experiment of the same name, as add_experiment does.

  • **options – Passed to the reader (SprTextExperiment.read_file, CarterraExperiment.read_csv or SurfaceCsvExperiment.read_files).

Returns:

The experiment that was read and added.

Return type:

object

collapse_solution_experiments(new_name='Experiment')[source]

Useful when many csv files are imported, and each is assigned to a different experiment.

init_fittings()[source]

Initialize (reset) the fittings dictionary and names list.

Parameters:

None

add_fitting(fitting, fitting_name)[source]

Add a fitting object to the analyzer.

Parameters:
  • fitting (object) – Fitting object to add.

  • fitting_name (str) – Name of the fitting.

get_experiment_properties(variable, fittings=False)[source]

Get a list of properties from experiments or fittings.

Parameters:
  • variable (str) – Name of the property to retrieve.

  • fittings (bool, optional) – If True, get from fittings; else from experiments. Default is False.

Returns:

List of property values.

Return type:

list

merge_ligand_conc_df()[source]

Merge ligand concentration DataFrames from all experiments.

Return type:

None

merge_conc_df_solution()[source]

Merge concentration DataFrames from all solution-based experiments.

Parameters:

None

Returns:

Creates a combined_conc_df attribute containing the merged concentration data.

Return type:

None

Notes

This method combines the concentration DataFrames from all solution-based experiments in the analyzer. It adds a ‘Select’ column with all values set to True, which can be used for filtering data in subsequent analyses.

generate_fittings(df, trim_time=0)[source]

Generate fitting objects for surface-based experiments from a DataFrame.

Parameters:
  • df (pandas.DataFrame) – DataFrame containing experiment data.

  • trim_time (float, optional) – Seconds, from the start of each association and each dissociation, left out of the kinetic fits. For example, 1 leaves out the first second of each step, where SPR curves show the bulk refractive index spike. The points are kept and plotted, and the models still start at the beginning of each step, so the fitted rates are not shifted. Default is 0 (every point is fitted).

Returns:

List of messages about fitting creation.

Return type:

list

generate_fittings_solution(df)[source]

Generate fitting objects for solution-based experiments from a DataFrame.

Parameters:

df (pandas.DataFrame) – DataFrame containing experiment data.

Returns:

List of messages about fitting creation.

Return type:

list

submit_steady_state_fitting(fitting_model='one_to_one', fit_sigma=False)[source]

Submit steady-state fitting for all fitting objects.

Parameters:
  • fitting_model (str, optional) – Steady-state model to fit for surface data. Options: ‘one_to_one’, ‘two_to_one’, ‘two_to_one_heterogeneous_ligand’, ‘heterogeneous_ligand’. Default is ‘one_to_one’.

  • fit_sigma (bool, optional) – Only used when fitting_model=’two_to_one’. If True, fit a shared cooperativity factor (sigma). Default is False.

Return type:

None

submit_fitting_solution(fitting_model='single', **kwargs)[source]

Fit models to solution-based kinetics data.

Parameters:
  • fitting_model (str, optional) – Model to fit. Options: ‘single’, ‘double’, ‘one_binding_site’, ‘one_binding_site_if’, ‘one_binding_site_cs’ Default is ‘single’.

  • **kwargs (dict) – Additional keyword arguments for fitting methods.

Return type:

None

submit_kinetics_fitting(fitting_model='one_to_one', fitting_region='association_dissociation', shared_smax=False, fit_sigma=False, fixed_t0=True, Kd1_values=None, Kd2_values=None, fit_signal_ratio=False, compute_k_obs=True)[source]

Fit models to surface-based kinetics data.

Parameters:
  • fitting_model (str, optional) – Model to fit. Options: ‘one_to_one’, ‘one_to_one_mtl’, ‘one_to_one_if’, ‘two_to_one’, ‘two_to_one_heterogeneous_ligand’, ‘heterogeneous_ligand’, ‘bivalent_analyte’. Default is ‘one_to_one’.

  • fitting_region (str, optional) – Region to fit. Options: ‘association_dissociation’, ‘association’, ‘dissociation’. Default is ‘association_dissociation’.

  • shared_smax (bool, optional) – Whether to share Smax values across curves. Default is False.

  • fit_sigma (bool, optional) – Whether to fit sigma (cooperativity) for the two_to_one model. Ignored for one_to_one and one_to_one_if models. Default is False.

  • fixed_t0 (bool, optional) – Whether to fix t0 for association/dissociation fitting. Used by the heterogeneous ligand and bivalent analyte models. Default is True.

  • Kd1_values (list, optional) – Candidate Kd1 values for the heterogeneous ligand grid search.

  • Kd2_values (list, optional) – Candidate Kd2 values for the heterogeneous ligand grid search.

  • fit_signal_ratio (bool, optional) – For the one_to_one_if model, let the induced complex (AL) produce a different signal than the intermediate complex (ALint) by fitting their ratio. A is the analyte and L the immobilised ligand. Ignored by the other models. Default is False.

  • compute_k_obs (bool, optional) – For the one_to_one model fitted to the association, or to the association and dissociation, also fit a single exponential to each association trace and store the observed rates in k_obs. The kinetic fit does not use them, so False makes the fit faster. They can still be computed later with fit_single_exponentials(). Ignored by the other models. Default is True.

Return type:

tuple

calculate_leave_one_out_errors()[source]

Find the fitted parameters (only the thermodynamic ones) errors using the leave-one-out method.

We leave one curve at a time for a given Sample ID.

Notes

  • This function must be called after running ‘submit_kinetics_fitting’

  • This function will create ‘df_fit_loo’ attribute with the mean and std of the leave-one-out method

calculate_asymmetric_error(shared_smax=None, fixed_t0=None, fit_ktr=None)[source]

Calculate asymmetric error (confidence intervals) for all fitting objects.

Each fitting object uses the settings of its own fit. The arguments are kept for backward compatibility: if given, they must match those settings.

Parameters:
  • shared_smax (bool, optional) – Whether Smax is shared across different curves. Default is None (use the fit’s setting).

  • fixed_t0 (bool, optional) – Whether t0 (start time) is fixed during fitting. Default is None (use the fit’s setting).

  • fit_ktr (bool, optional) – Whether the mass transport parameter ktr was fitted. Default is None (use the fit’s setting).

Returns:

Updates the fitting objects with confidence intervals for the fitted parameters.

Return type:

None

Notes

This method calculates asymmetric confidence intervals for the kinetic parameters (kon, koff, Kd) for each fitting object. The confidence intervals are stored in the fitting objects and can be accessed through the get_fitting_results method.

get_fitting_results()[source]

Get the results of the fitting process as a DataFrame.

Parameters:

None

Returns:

DataFrame containing fitting results from all fitting objects. The DataFrame includes parameters like kon, koff, Kd, and their confidence intervals. Returns None if no fitting results are available.

Return type:

pandas.DataFrame or None

get_correlation_matrices(kind='kinetics')[source]

Get the correlation matrices of the fitted parameters.

Correlations near ±1 mean two parameters trade off against each other: the data determine a combination of them, not each one separately, and their individual values should not be trusted.

Parameters:

kind (str, optional) – ‘kinetics’ (default) for the latest kinetics fit, or ‘steady_state’ for the latest steady-state fit.

Returns:

One correlation matrix per fitting, keyed by fitting name. Fittings without a matrix of that kind are left out.

Return type:

dict of str to pandas.DataFrame

get_legends_table()[source]

Get the legends table for plotting the kinetics data.

Returns:

DataFrame containing legend information for plotting.

Return type:

pandas.DataFrame

create_export_df(type='raw')[source]

Creates a DataFrame for exporting the kinetics data.

Parameters:

type (str, optional) – Type of data to include in the export. Options: ‘raw’, ‘fitted’. Default is ‘raw’.

Returns:

DataFrame containing the data to be exported.

Return type:

pandas.DataFrame

pykingenie.octet module

Import and manage Octet bio-layer interferometry experiments.

class pykingenie.octet.OctetExperiment(name='BLI_experiment')[source]

Bases: SurfaceBasedExperiment

OctetExperiment class for handling Octet BLI data.

Parameters:

name (str) – Name of the experiment.

name(str)
Type:

name of the experiment

fns(list)
Type:

list of file names (length n, one per sensor)

xs(list)
Type:

list of x values (time, length n, one per sensor)

ys(list)
Type:

list of y values (length n, one per sensor)

exp_info(list)
Type:

list of dictionaries with experimental information

step_info(list)
Type:

list of dictionaries with step information

no_steps(int)
Type:

number of steps

no_sensors(int)
Type:

number of sensors

sample_column(np.ndarray)
Type:

array of sample column information (96 elements, one per well)

sample_row(np.ndarray)
Type:

array of sample row information (96 elements, one per well)

sample_type(list)
Type:

list of sample types (96 elements, one per well)

sample_id(list)
Type:

list of sample ids (96 elements, one per well)

sensor_names_unique(list)
Type:

list of unique sensor names (length n, one per sensor)

sensor_names(list)
Type:

list of sensor names (length n, one per sensor)

df_steps(pd.DataFrame)
Type:

dataframe with the steps information

ligand_conc_df(pd.DataFrame)
Type:

dataframe with the ligand concentration information

ligand_conc_df.head(2)
Sensor Analyte_location  Concentration_micromolar SampleID  Replicate Experiment
A1        5                    0.1300       wt          1          t
B1        5                    0.0692       wt          1          t
traces_loaded(bool)
Type:

True if traces are loaded

sample_plate_loaded(bool)
Type:

True if sample plate information is loaded

sample_conc(np.array)
Type:

array with the sample concentrations (96 elements, one per well)

sample_conc_labeled(list)
Type:

list with the sample concentrations labeled (96 elements, one per well)

steps_performed(pd.DataFrame)
Type:

dataframe with the steps performed

steps_performed.head(2)
#Step         Type              Column   Time
1            Regeneration      1        25
2  BaselineNeutralization      2        90
3         BaselineLoading      3        50
read_sensor_data(files, names=None)[source]

Read the sensor data from the .frd files.

Parameters:
  • files (str or list of str) – Path(s) to .frd file(s) to read.

  • names (str or list of str, optional) – Name(s) to assign to the sensors. If None, file names are used.

Returns:

The method populates class attributes with data from the files.

Return type:

None

Notes

This method creates the following attributes:

  • traces_loaded : bool Whether traces were successfully loaded.

  • xs : list List of x values (time) for each sensor.

  • ys : list List of y values (signal) for each sensor.

  • exp_info : list List of dictionaries with experimental information.

  • step_info : list List of dictionaries with step information.

  • no_steps : int Number of steps in the experiment.

  • no_sensors : int Number of sensors in the experiment.

generate_ligand_conc_df()[source]

Generate a DataFrame with the analyte concentrations based on step_info and exp_info.

Parameters:

None

Returns:

This method populates class attributes related to ligand concentration.

Return type:

None

Notes

This method requires the following attributes to be already populated:

  • step_info : list List of dictionaries with step information.

  • exp_info : list List of dictionaries with experimental information.

  • fns : list List of file names.

This method creates/updates the following attributes:

  • no_steps : int Number of steps in the experiment.

  • no_sensors : int Number of sensors.

  • sensor_names : list List of sensor names.

  • df_steps : pandas.DataFrame DataFrame with step information.

  • ligand_conc_df : pandas.DataFrame DataFrame with ligand concentration information.

merge_consecutive_steps(idx_ref, idx_to_merge)[source]

Combine two consecutive steps into one step.

Parameters:
  • idx_ref (int) – Index of the reference step. The type of step will be taken from this step.

  • idx_to_merge (int) – Index of the step to merge with the reference step.

Returns:

The method modifies the xs, ys, and step information in place.

Return type:

None

Notes

The two steps must be consecutive (their indices must differ by exactly 1).

merge_consecutive_steps_by_name(step_name, reference=True)[source]

Merge steps with a specific name with their consecutive step.

Parameters:
  • step_name (str) – Name of the step to merge with the next/previous step.

  • reference (bool, optional) – If True, the step with name step_name will be used as reference to extract the analyte concentration, loading location, etc. Default is True.

Returns:

The method modifies the xs, ys, and step information in place.

Return type:

None

Notes

This method finds all steps with the given name and merges them with their adjacent step. The merged step inherits properties from the reference step.

read_sample_plate_info(files, names=None)[source]

Read the sample plate information from the .fmf file.

Parameters:
  • files (str or list of str) – Path(s) to .fmf file(s) containing sample plate information.

  • names (str or list of str, optional) – Name(s) to assign to the files. If None, file names are used.

Returns:

The method populates class attributes with sample plate data.

Return type:

None

Notes

This method creates the following attributes:

  • sample_column : numpy.ndarray Array of sample column information (96 elements, one per well).

  • sample_row : numpy.ndarray Array of sample row information (96 elements, one per well).

  • sample_type : list List of sample types (96 elements, one per well).

  • sample_id : list List of sample IDs (96 elements, one per well).

  • sample_plate_loaded : bool Set to True if sample plate information is successfully loaded.

  • sample_conc : numpy.ndarray Array with the sample concentrations (96 elements, one per well).

  • sample_conc_labeled : list List with the sample concentrations labeled (96 elements, one per well).

convert_to_numbers()[source]

Convert the strings in the step info to numbers.

Parameters:

None

Returns:

The method modifies the step_info attribute in place.

Return type:

None

Notes

This method processes the following entries in step_info: ‘Concentration’, ‘MolarConcentration’, ‘MolecularWeight’, ‘Temperature’, ‘StartTime’, ‘AssayTime’, ‘FlowRate’, ‘ActualTime’, ‘CycleTime’.

pykingenie.solution_exp module

Base abstractions for solution-based kinetic experiments.

class pykingenie.solution_exp.SolutionBasedExp(name, type)[source]

Bases: object

Base class for solution-based kinetics experiments.

This class serves as a foundation for classes that handle solution-based kinetic experiments data.

Parameters:
  • name (str) – Name of the experiment.

  • type (str) – Type of the experiment.

name

Name of the experiment.

Type:

str

type

Type of the experiment.

Type:

str

xs

List of x values (time) for each trace.

Type:

list of numpy.ndarray or None

ys

List of y values (signal) for each trace.

Type:

list of numpy.ndarray or None

no_traces

Number of traces.

Type:

int or None

traces_names

List of trace names.

Type:

list of str or None

traces_names_unique

List of unique trace names (includes experiment name).

Type:

list of str or None

conc_df

DataFrame with concentration information.

Type:

pandas.DataFrame or None

traces_loaded

Whether traces have been loaded.

Type:

bool

create_unique_traces_names()[source]

Create unique trace names by appending the experiment name to the trace names.

Parameters:

None

Returns:

Updates the traces_names_unique attribute.

Return type:

None

Notes

This method creates unique identifiers for each trace by combining the experiment name with the individual trace names.

cut_off_time(time)[source]

Remove all data before a specified time.

Parameters:

time (float) – The time to cut off the data.

get_trace_xy(trace_name, type='y')[source]

Return the x or y values of a specific trace.

Parameters:
  • trace_name (str) – Name of the trace to retrieve data from.

  • type ({'x', 'y'}, optional) – Type of data to return. Default is ‘y’.

Returns:

The x or y values of the specified trace.

Return type:

numpy.ndarray

Notes

This method finds the trace by name in the traces_names list and returns either its x values (time) or y values (signal).

pykingenie.spr_text module

Import paired-column SPR text exports (one _X/_Y pair per curve).

What the file provides

  • One sensorgram per <label>_X / <label>_Y column pair: time and response, each curve on its own time grid. Columns of fitted curves are ignored.

  • The curve label from the header (for example Cycle=1_Fc=4-3 or Run 1; Ch 1; Cy 14; conc=15). It becomes the sensor name.

  • A concentration only when the label ends in conc=<value>, with a molar unit (M, mM, uM, nM, pM) in the label or given as concentration_unit. Other labels give NaN and a warning.

What the file does not provide

  • When each injection starts and ends.

  • Concentrations, in most exports.

  • Which curves belong to the same analyte, and which flow cell is the reference.

  • Plate positions, ligand loading or regeneration steps.

What the user must provide

A TitrationAnalysis Data Info Sheet (info=, see pykingenie.info_sheet) can supply the timing, concentrations and sample_id below.

  • To import: association_end and, if not 0 s, association_start, in seconds on the exported time axis: one value for every curve, or one per curve (list or curve-label mapping) when injections start at different times. Also time_unit="min" if time is in minutes. The decimal mark (. or ,) is detected; pass decimal only if the file uses both.

  • To fit: one concentration per curve (concentrations, in µM unless concentration_unit is given), and sample_id to group curves of the same analyte (by default all curves form one group). Reference subtraction and alignment are not done on import; use subtraction and align_association on the experiment.

Multi-cycle and single-cycle kinetics

  • Multi-cycle (the default): each curve is one cycle with one injection, so each curve gets one association_start/association_end and one concentration.

  • Single-cycle (single_cycle=True): each curve holds several injections of increasing concentration without regeneration. association_start, association_end and concentrations are then lists with one value per injection, shared by every curve, or curve-label mappings of such lists. Each dissociation lasts until the next injection starts. Every curve needs its own sample_id, and the concentrations cannot come from the labels.

class pykingenie.spr_text.SprTextExperiment(name='spr_text')[source]

Bases: SensorgramTextExperiment

SPR text exports containing one named _X/_Y column pair per sensorgram.

Verified with Biacore T200 Cycle/Fc and Cycle/sample headers and the public rstoolbox Run/Ch/Cy/conc example. Fitted-curve columns are excluded.

read_file(file, *, association_end=None, association_start=None, concentrations=None, concentration_unit=None, time_unit='s', sample_id=None, decimal=None, encoding='utf-8-sig', info=None, single_cycle=False)[source]

Read paired-column text/CSV/TSV, optionally gzip compressed.

Comma, semicolon and tab delimiters are detected automatically. Standard CSV quoting and spaces after delimiters are accepted.

Boundaries are seconds on the exported time axis; association is [start, end) and dissociation starts at end. Each boundary is one number for all curves, or a list or curve-label mapping with one number per curve; with different values, exp_info keeps them under association_start_seconds_by_curve and association_end_seconds_by_curve. Missing baseline points are allowed. Concentrations are a list or curve-name mapping, in µM unless concentration_unit is supplied. Without concentrations, only conc= labels are used, with their own molar unit or, if they have none, concentration_unit; other values stay NaN with a warning. sample_id accepts a common string or one value per curve (list or mapping), to distinguish different binding interactions. A pandas Series counts as a mapping: its index must be the curve labels. time_unit describes the file (‘s’ or ‘min’). decimal is detected from the measurements (‘.’ or ‘,’); pass decimal=’.’ or ‘,’ to set it. encoding can be changed for older instrument exports. No times, units or concentrations are inferred from signal shape or curve position.

info is a TitrationAnalysis Data Info Sheet path, or one row of read_info_sheet(). It supplies the association boundaries, the molar concentrations and sample_id (the analyte); arguments you pass take precedence. Without info, association_start defaults to 0 s and sample_id to “sample”.

With single_cycle=True each curve holds several injections without regeneration (single-cycle kinetics). association_start, association_end and concentrations then give one value per injection: a list used for every curve, or a curve-label mapping of lists. All curves need the same number of injections and each curve its own sample_id. The steps become BASELINE, then ASSOC and DISASSOC per injection, each dissociation lasting until the next injection starts, and ligand_conc_df has one row per curve and injection.

pykingenie.surface_csv module

Import surface-based binding data from a steps table and a column-formatted traces file.

This importer is instrument-agnostic. It needs two plain-text files:

  1. A steps file (tab-, comma- or semicolon-delimited) with one row per assay step, for example:

    Assay  Step Number  Step Name     Step Time  Step Type Name  Sample Location
    1      1            Baseline      60         Baseline        p1A1
    1      2            Loading       120        Loading         p1A2
    1      3            Association   120        Association     p1A3
    1      4            Dissociation  60         Dissociation    p1A4
    

    Required columns are the step duration (Step Time, in seconds) and the step type (Step Type Name). Step Name and Sample Location are optional. An optional Concentration column (in µM) can hold the analyte concentration of each association step.

  2. A traces file (comma-, tab- or semicolon-delimited) with the time in the first column and one sensor per remaining column, for example:

    X Values, A1, B1
    0, 0, 0
    0.2, -0.0016, 0.0085
    

    Any metadata lines before the header row are skipped automatically. The time axis must be continuous across steps, i.e. step i spans the time interval [sum(step_time[:i]), sum(step_time[:i+1])).

pykingenie.surface_csv.map_step_type(step_type)[source]

Convert a step type name (e.g. ‘Association’) to the internal pykingenie code (e.g. ‘ASSOC’).

Parameters:

step_type (str) – Step type name as written in the steps file.

Returns:

Internal step type code. Unknown names are returned upper-cased.

Return type:

str

pykingenie.surface_csv.location_to_column(location, default)[source]

Extract the plate column number from a well location string.

Parameters:
  • location (str) – Well location, e.g. ‘A7’, ‘p1A7’ or ‘7’.

  • default (int) – Value returned if no column number can be parsed.

Returns:

Column number as a string (e.g. ‘7’).

Return type:

str

pykingenie.surface_csv.read_traces_file(file)[source]

Read a column-formatted traces file (time in the first column, one sensor per column).

Metadata lines before the header are skipped. The header is the last non-numeric line before the first fully numeric line.

Parameters:

file (str) – Path to the traces file.

Returns:

DataFrame with the time in the first column and one column per sensor.

Return type:

pandas.DataFrame

pykingenie.surface_csv.read_steps_file(file)[source]

Read a steps file describing the assay steps.

Parameters:

file (str) – Path to the steps file.

Returns:

DataFrame with standardised columns: ‘Name’, ‘Time’, ‘Type’ (internal code), ‘Location’ and, if present, ‘Concentration’ and ‘SampleID’.

Return type:

pandas.DataFrame

class pykingenie.surface_csv.SurfaceCsvExperiment(name='surface_csv')[source]

Bases: SurfaceBasedExperiment

Surface-based experiment imported from a steps file and a column-formatted traces file.

Useful for data exported from any instrument (e.g. Octet ‘Time Interpolated Data’ exports) where the native binary format is not available.

Parameters:

name (str, optional) – Name of the experiment. Default is ‘surface_csv’.

xs

Time values, one list per sensor with one array per step.

Type:

list of list of numpy.ndarray

ys

Signal values, one list per sensor with one array per step.

Type:

list of list of numpy.ndarray

df_steps

Step information with columns ‘#Step’, ‘Name’, ‘Type’, ‘Start’, ‘Column_location’ and ‘Loading_location’.

Type:

pandas.DataFrame

ligand_conc_df

One row per sensor and association step, with the analyte concentration.

Type:

pandas.DataFrame

read_files(steps_file, traces_file, concentrations=None, sample_id='sample')[source]

Read the steps file and the traces file and populate the experiment.

Parameters:
  • steps_file (str) – Path to the steps file (one row per step).

  • traces_file (str) – Path to the traces file (time column followed by one column per sensor).

  • concentrations (list, dict or None, optional) – Analyte concentrations in µM. Either a list with one value per association step (shared by all sensors) or a dict mapping sensor name to such a list. If None, the ‘Concentration’ column of the steps file is used; if that is also missing, concentrations are set to NaN and a warning is issued (they can be edited later in ligand_conc_df).

  • sample_id (str, optional) – Sample ID used when the steps file has no ‘Sample ID’ column (or it is empty for an association step). Default ‘sample’. If the loading steps also have a Sample ID and more than one ligand was loaded, the association Sample IDs become ‘<analyte> - <ligand>’, so each ligand is fitted separately.

Return type:

None

pykingenie.surface_exp module

Base abstractions for surface-based kinetic experiments.

class pykingenie.surface_exp.SurfaceBasedExperiment(name, type)[source]

Bases: object

A class representing surface-based kinetics experiments.

This class handles operations related to surface-based experiments, such as biolayer interferometry (BLI) or surface plasmon resonance (SPR). It provides functionality for data processing, analysis, and visualization.

Parameters:
  • name (str) – The name of the experiment.

  • type (str) – The type of the experiment (e.g., ‘Octet’, ‘SPR’).

name

The name of the experiment.

Type:

str

type

The type of the experiment.

Type:

str

xs

Time values for each sensor and step.

Type:

list of list

ys

Signal values for each sensor and step.

Type:

list of list

sensor_names

Names of the sensors.

Type:

list

ligand_conc_df

DataFrame containing ligand concentration information.

Type:

pandas.DataFrame

df_steps

DataFrame containing step information.

Type:

pandas.DataFrame

steps_performed

List of steps performed in the experiment.

Type:

list

traces_loaded

Whether traces have been loaded.

Type:

bool

sample_plate_loaded

Whether the sample plate information has been loaded.

Type:

bool

create_unique_sensor_names()[source]

Create unique sensor names by adding the experiment name to each sensor name.

This method updates the sensor_names_unique attribute by prefixing each sensor name with the experiment name.

Returns:

The method modifies the sensor_names_unique attribute in-place.

Return type:

None

check_sensor_name(new_sensor_name)[source]

Check if a sensor name already exists and modify it if necessary.

Parameters:

new_sensor_name (str) – The proposed name for a new sensor.

Returns:

A unique sensor name, either the original if it doesn’t exist or a modified version with ‘ rep’ appended.

Return type:

str

subtraction_one_to_one(sensor_name1, sensor_name2, inplace=True)[source]

Subtract the signal of one sensor from another.

Parameters:
  • sensor_name1 (str) – Name of the sensor to subtract from.

  • sensor_name2 (str) – Name of the sensor to subtract.

  • inplace (bool, optional) – If True, the subtraction is done in place, otherwise a new sensor is created, by default True.

Returns:

The method modifies the instance attributes in-place.

Return type:

None

Notes

This method modifies the following attributes: - self.xs - self.ys - self.sensor_names - self.ligand_conc_df

Raises:

RuntimeError – If no traces are loaded or if sensors are incompatible.

subtraction(list_of_sensor_names, reference_sensor, inplace=True)[source]

Apply subtraction operation to a list of sensors.

Parameters:
  • list_of_sensor_names (list or str) – List of sensor names to subtract from. If a string is provided, it will be converted to a list.

  • reference_sensor (str) – Name of the sensor to subtract.

  • inplace (bool, optional) – If True, the subtraction is done in place, otherwise new sensors are created, by default True.

Returns:

The method modifies the instance attributes in-place.

Return type:

None

Notes

This method modifies the following attributes: - self.xs - self.ys - self.sensor_names - self.ligand_conc_df

average(list_of_sensor_names, new_sensor_name='Average')[source]

Average the signals of the sensors in the list.

Parameters:
  • list_of_sensor_names (list) – List of sensor names to average.

  • new_sensor_name (str, optional) – Name of the new sensor, by default ‘Average’.

Returns:

The method modifies the instance attributes in-place.

Return type:

None

Notes

This method modifies the following attributes: - self.xs - self.ys - self.sensor_names - self.ligand_conc_df

Raises:

RuntimeError – If no traces are loaded.

align_association(sensor_names=None, inplace=True, new_names=False, npoints=10)[source]

Align BLI traces based on the signal before the association step(s).

Parameters:
  • sensor_names (str or list) – Name of the sensor(s) to align. If a string is provided, it will be converted to a list. If None, all sensors will be aligned.

  • inplace (bool, optional) – If True, the alignment is done in place, otherwise new sensors are created, by default True.

  • new_names (bool, optional) – If True, new sensor names are generated, otherwise the original names are kept, by default False.

  • npoints (int, optional) – Number of points to use for averaging at alignment positions, by default 10.

Returns:

The method modifies the instance attributes in-place.

Return type:

None

Notes

This method modifies the following attributes: - self.xs - self.ys - self.sensor_names - self.ligand_conc_df

The alignment is performed by subtracting the average signal of the last npoints points before each association step.

find_experiments_compatibility(other_experiment)[source]

Find if the other experiment can be subtracted from the current one

Parameters:

other_experiment (SurfaceBasedExperiment) – The experiment to check compatibility with.

Returns:

  • bool_status (bool) – Boolean indicating if the experiments are compatible.

  • compatibility_type (str) – Description of the compatibility type. Can be one of the following: ‘all’ if the x-data is exactly the same ‘interaction’ if the x-data is the same (start time is ignored) during the association and dissociation phases only ‘none’ if the x-data is different even during the interaction phases

subtract_experiment(other_experiment, inplace=True, only_interaction=False)[source]

Subtract another SurfaceBasedExperiment from this one on a sensor-by-sensor basis.

Parameters:
  • other_experiment (SurfaceBasedExperiment) – The experiment to subtract from this one.

  • inplace (bool, optional) – If True, the subtraction is done in place, otherwise new sensors are created, by default True.

  • only_interaction (bool, optional) – If True, only the interaction part of the signal is subtracted, that is, the association and dissociation phases. by default False.

subtraction_by_column(sensors_column_one, sensors_column_two, inplace=True)[source]

Subtract a whole column of sensors from another column of sensors. Useful when a screening experiment has been done

Parameters:
  • sensors_column_one (int) – Column number of the sensors to subtract from.

  • sensors_column_two (int) – Column number of the sensors to subtract.

  • inplace (bool, optional) – If True, the subtraction is done in place, otherwise new sensors are created, by default True.

Return type:

A list of strings mentioning which sensors were subtracted from which.

assoc_inter_step_correction(sensor_names, inplace=True, new_names=False, npoints=4)[source]

First, find the difference between the end of the association step and the beginning of the dissociation step. Then, subtract the difference from the association step. Note: This correction requires that the dissociation step and baseline where done in the exact same well!

Parameters:
  • sensor_names (str or list) – Name of the sensor(s) to align. If a string is provided, it will be converted to a list.

  • inplace (bool, optional) – If True, the alignment is done in place, otherwise new sensors are created, by default True.

  • new_names (bool, optional) – If True, new sensor names are generated, otherwise the original names are kept, by default False.

  • npoints (int, optional) – Number of points to use for averaging at alignment positions, by default 4.

Returns:

The method modifies the instance attributes in-place.

Return type:

None

Notes

This method modifies the following attributes: - self.xs - self.ys - self.sensor_names - self.ligand_conc_df

The alignment is performed by smoothing the transition between association and dissociation steps.

align_dissociation(sensor_names, inplace=True, new_names=False, npoints=10)[source]

Align BLI traces based on the signal before the dissociation step(s).

Parameters:
  • sensor_names (str or list) – Name of the sensor(s) to align. If a string is provided, it will be converted to a list.

  • inplace (bool, optional) – If True, the alignment is done in place, otherwise new sensors are created, by default True.

  • new_names (bool, optional) – If True, new sensor names are generated, otherwise the original names are kept, by default False.

  • npoints (int, optional) – Number of points to use for averaging at alignment positions, by default 10.

Returns:

The method modifies the instance attributes in-place.

Return type:

None

Notes

This method modifies the following attributes: - self.xs - self.ys - self.sensor_names - self.ligand_conc_df

The alignment is performed by smoothing the transition between association and dissociation steps.

discard_steps(sensor_names, step_types=['KREGENERATION', 'LOADING'])[source]

Discard specific step types from the sensors in the list.

Parameters:
  • sensor_names (str or list) – Name of the sensor(s) to process. If a string is provided, it will be converted to a list.

  • step_types (str or list, optional) – Type(s) of steps to discard, by default [‘KREGENERATION’, ‘LOADING’]. If a string is provided, it will be converted to a list.

Returns:

The method modifies the instance attributes in-place.

Return type:

None

Notes

This method modifies the following attributes: - self.ys

The discarded steps are replaced with NaN values.

get_step_xy(sensor_name, location_loading, location_sample, step_type='ASSOC', replicate=1, type='y')[source]

Return the x or y values of a specific step.

Parameters:
  • sensor_name (str) – Name of the sensor.

  • location_loading (int) – Column location of the loading. If zero, assumes only one location.

  • location_sample (int) – Column location of the sample. If zero, assumes only one location.

  • step_type (str, optional) – Type of step, only ‘ASSOC’ or ‘DISASSOC’ are valid, by default ‘ASSOC’.

  • replicate (int, optional) – Replicate number, by default 1.

  • type (str, optional) – Data type to return, either ‘x’ or ‘y’, by default ‘y’.

Returns:

The x (time) or y (signal) values of the specified step.

Return type:

numpy.ndarray

Raises:
  • ValueError – If location_sample, location_loading, or replicate are not valid integers.

  • TypeError – If any parameter has an incorrect type.

Notes

For ‘x’ type data, time values are processed to start from zero for each step. For association steps, time starts at the beginning of the step. For dissociation steps, time continues from the association step.