# This file contains AI-generated changes (PR #15).
"""Fit steady-state and kinetic models to surface-based experimental data."""
import itertools
import copy
import numpy as np
import pandas as pd
from .utils.fitting_surface import (
fit_steady_state_one_site,
fit_steady_state_two_site,
fit_steady_state_two_site_heterogeneous_ligand,
fit_two_site_assoc_and_disso,
steady_state_one_site_asymmetric_ci95,
fit_one_site_association,
fit_one_site_dissociation,
fit_one_site_assoc_and_disso,
fit_induced_fit_sites_assoc_and_disso,
fit_one_site_assoc_and_disso_ktr,
fit_two_site_heterogeneous_ligand_assoc_and_disso,
fit_bivalent_analyte_assoc_and_disso,
one_site_assoc_and_disso_asymmetric_ci95,
one_site_assoc_and_disso_asymmetric_ci95_koff,
trim_masks,
get_smax_upper_bound_factor,
fit_single_exponential_fast
)
from .utils.fitting_general import (
re_fit,
re_fit_2
)
from .utils.processing import (
subset_data,
concat_signal_lst,
detect_time_list_continuos,
expand_parameter_list,
remove_at
)
from .utils.math import get_desired_rss, correlation_from_covariance
from .fitter import KineticsFitterGeneral, store_fit_result, update_fit_result
def _leave_one_out_parameters(params, low_bounds, high_bounds, smax_ids, omitted,
shared_smax, n_global, group_blocks=(), response_width=1):
"""Select parameters and bounds for the traces and groups retained by a LOO fit.
Parameters are ordered as global rates, optional per-group blocks (such as
t0 and Ktr), then one response block per group or per trace. Return the
original retained group IDs as well, so group-specific results stay aligned.
"""
# This function is AI generated (PR #15).
retained_traces = [i for i in range(len(smax_ids)) if i != omitted]
retained_groups = sorted({smax_ids[i] for i in retained_traces})
group_map = {group: i for i, group in enumerate(retained_groups)}
remapped_ids = [group_map[smax_ids[i]] for i in retained_traces]
n_groups = len(set(smax_ids))
indices = list(range(n_global))
offset = n_global
for width in group_blocks:
for group in retained_groups:
indices.extend(range(offset + width * group, offset + width * (group + 1)))
offset += width * n_groups
responses = retained_groups if shared_smax else retained_traces
for response in responses:
indices.extend(range(offset + response_width * response,
offset + response_width * (response + 1)))
selected = [[values[i] for i in indices] for values in (params, low_bounds, high_bounds)]
return *selected, remapped_ids, retained_groups
def _loo_state_refit_indices(assoc_times, disso_times):
"""Find omissions whose successor needs a new starting state at the vacated index."""
continuous = detect_time_list_continuos(assoc_times, disso_times)
return {i - 1 for i in range(1, len(continuous))
if continuous[i] and assoc_times[i][0] >= 2}
[docs]
class KineticsFitter(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.
Attributes
----------
names : list
List of experiment names.
assoc_lst : list
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.
disso_lst : list
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).
lig_conc_lst : list
List of ligand concentrations, one per replicate.
time_assoc_lst : list
List of time points for the association signals, one per replicate.
time_disso_lst : list
List of time points for the dissociation signals, one per replicate.
is_single_cycle : bool
Whether the experiment is a single cycle kinetics experiment.
signal_ss : list
List of steady state signals, one per replicate.
signal_ss_fit : list
List of steady state fitted signals, one per replicate.
signal_assoc_fit : list
List of association kinetics fitted signals, one per replicate.
signal_disso_fit : list
List of dissociation kinetics fitted signals, one per replicate.
lig_conc_lst_per_id : list
Ligand concentrations per Smax ID.
smax_guesses_unq : list
Smax guesses per association signal.
smax_guesses_shared : list
Smax guesses per Smax ID.
fit_params_kinetics : pd.DataFrame
DataFrame with the fitted parameters for the association/dissociation kinetics.
fit_params_ss : pd.DataFrame
DataFrame with the values of the fitted parameters - steady state.
"""
def __init__(self,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):
"""
Initialize the KineticsFitter class.
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, default is False.
trim_time : float, optional
Time, in seconds from the first point of each association and each
dissociation, left out of the kinetic fits, their errors and
confidence intervals. The models still start at the first point of
each step, so the fitted parameters are not shifted. Default is 0
(every point is fitted).
"""
# This function contains AI-generated changes (PR #15).
# Edited with AI assistance: trim_time.
if trim_time < 0:
raise ValueError("trim_time must be zero or positive.")
super().__init__()
self.names = name_lst
self.assoc_lst = association_signal_lst
self.disso_lst = dissociation_signal_lst
self.lig_conc_lst = lig_conc_lst
self.time_assoc_lst = time_assoc_lst
self.time_disso_lst = time_diss_lst
self.is_single_cycle = is_single_cycle
self.trim_time = trim_time
self.lig_conc_lst_per_id = None # Ligand concentrations per Smax ID
self.smax_guesses_unq = None # Smax guesses per association signal
self.smax_guesses_shared = None # Smax guesses per Smax ID
self.Kd_ss = None
# If smax_id is None, set it to a list of zeros
if smax_id is None:
smax_id = [0 for _ in range(len(association_signal_lst))]
# Renumber groups in first-seen order without changing trace membership.
group_map = {group: i for i, group in enumerate(dict.fromkeys(smax_id))}
self.smax_id = [group_map[group] for group in smax_id]
self.signal_assoc_fit = None
self.signal_disso_fit = None
self.signal_ss_fit = None
self.Smax_upper_bound_factor = 1e2 # Normal values for lower than micromolar affinity
def _fit_masks(self, time_assoc_lst, time_disso_lst):
"""
Masks of the points to fit, as keyword arguments of the fitting functions.
Parameters
----------
time_assoc_lst, time_disso_lst : list
Time arrays of the association and dissociation traces being fitted.
Returns
-------
dict
assoc_mask_lst and disso_mask_lst, from trim_masks and trim_time.
Both are None (every point is fitted) if trim_time is 0.
"""
# This function is AI generated.
return {'assoc_mask_lst': trim_masks(time_assoc_lst, self.trim_time),
'disso_mask_lst': trim_masks(time_disso_lst, self.trim_time)}
def _grid_rss(self, assoc_lst, fit_assoc_lst, time_assoc_lst,
disso_lst, fit_disso_lst, time_disso_lst):
"""Residual sum of squares over the points to fit (see trim_time)."""
# This function is AI generated.
masks = self._fit_masks(time_assoc_lst, time_disso_lst)
rss = 0.0
for signals, fits, mask_lst in [(assoc_lst, fit_assoc_lst, masks['assoc_mask_lst']),
(disso_lst, fit_disso_lst, masks['disso_mask_lst'])]:
if mask_lst is None:
mask_lst = [slice(None)] * len(signals)
for y, fit_y, mask in zip(signals, fits, mask_lst):
rss += np.sum((np.asarray(y)[mask] - np.asarray(fit_y)[mask]) ** 2)
return rss
[docs]
def get_steady_state(self):
"""
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
-------
None
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
"""
signals_steady_state = [np.median(assoc[-10:]) for assoc in self.assoc_lst]
# Create a new list, that will contain one element per Smax ID
# each element will be a list of steady-state signals
self.signal_ss = [] # convert to list of lists, one list per unique smax id
self.lig_conc_lst_per_id = [] # convert to list of lists, one list per unique smax id
# Obtain the smax guesses, the maximum signal
smax_guesses_unq = [] # One element per association signal
smax_guesses_shared = [] # One element per Smax ID
for i,smax_id in enumerate(np.unique(self.smax_id)):
idx = np.where(self.smax_id == smax_id)[0]
self.signal_ss.append([signals_steady_state[i] for i in idx])
self.lig_conc_lst_per_id.append([self.lig_conc_lst[i] for i in idx])
smax = np.max(self.signal_ss[i])
smax_guesses_unq.append(smax*1.5)
smax_guesses_shared += [smax*1.5 for _ in range(len(idx))]
self.smax_guesses_unq = smax_guesses_unq
self.smax_guesses_shared = smax_guesses_shared
return None
@staticmethod
def _group_labels(names, n_groups):
"""
Labels for parameters fitted once per group, numbered from 1.
Parameters
----------
names : str or tuple of str
Parameter name, or several names fitted together for each group
(for example ('Rmax_PL', 'Rmax_LPL')).
n_groups : int
Number of groups.
Returns
-------
list of str
For example ['Smax 1', 'Smax 2'], or
['Rmax_PL 1', 'Rmax_LPL 1', 'Rmax_PL 2', 'Rmax_LPL 2'].
"""
# This function is AI generated and reviewed by a human (PR #19).
names = (names,) if isinstance(names, str) else tuple(names)
return [f"{name} {i + 1}" for i in range(n_groups) for name in names]
def _trace_labels(self, names):
"""
Labels for parameters fitted once per trace, named by the trace's
analyte concentration.
Parameters
----------
names : str or tuple of str
Parameter name, or several names fitted together for each trace.
Returns
-------
list of str
For example ['Smax (0.2 µM)', 'Smax (0.441 µM)']. Traces with the
same concentration are numbered, for example 'Smax (1 µM, 2)'.
"""
# This function is AI generated and reviewed by a human (PR #19).
names = (names,) if isinstance(names, str) else tuple(names)
concs = [f"{c:.3g} µM" for c in self.lig_conc_lst]
totals = {c: concs.count(c) for c in concs}
seen = {}
tags = []
for c in concs:
seen[c] = seen.get(c, 0) + 1
tags.append(f"{c}, {seen[c]}" if totals[c] > 1 else c)
return [f"{name} ({tag})" for tag in tags for name in names]
def _amplitude_labels(self, names, shared_smax):
"""
Labels for the signal amplitudes of a kinetics fit: numbered per
group when they are shared, otherwise named by trace concentration.
"""
# This function is AI generated and reviewed by a human (PR #19).
if shared_smax:
return self._group_labels(names, len(np.unique(self.smax_id)))
return self._trace_labels(names)
def _add_concentrations(self, per_trace):
"""
Add the analyte concentration of each trace as the first column of
the kinetics tables, when the tables have one row per trace.
Parameters
----------
per_trace : bool
Whether the rows of fit_params_kinetics are one per trace (for
example when Smax is fitted for each trace).
"""
# This function is AI generated and reviewed by a human (PR #19).
if not per_trace:
return None
for name in ('fit_params_kinetics', 'fit_params_kinetics_error'):
df = getattr(self, name)
if df is not None and len(df) == len(self.lig_conc_lst) and 'Concentration [µM]' not in df:
df.insert(0, 'Concentration [µM]', list(self.lig_conc_lst))
return None
def _store_correlation(self, cov, labels, kind='kinetics'):
"""
Store the correlation matrix of the fitted parameters.
Parameters
----------
cov : np.ndarray
Covariance matrix from the fit.
labels : list of str
Parameter names, in the order of the fitted parameter vector.
kind : str, optional
'kinetics' (default) or 'ss' for steady state.
Returns
-------
None
Sets fit_params_kinetics_correlation or fit_params_ss_correlation.
"""
# This function is AI generated and reviewed by a human (PR #19).
corr = correlation_from_covariance(cov, labels)
if kind == 'ss':
self.fit_params_ss_correlation = corr
else:
self.fit_params_kinetics_correlation = corr
return None
[docs]
@store_fit_result('steady_state_one_site')
def fit_steady_state_one_site(self):
"""
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
-------
None
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
"""
# This function contains AI-generated changes (PR #19).
self.clear_fittings()
self.get_steady_state()
Kd_init = np.median(self.lig_conc_lst_per_id[0])
p0 = [Kd_init] + [np.max(signal) for signal in self.signal_ss]
kd_min = np.min(self.lig_conc_lst_per_id[0]) / 1e3
kd_max = np.max(self.lig_conc_lst_per_id[0]) * 1e3
low_bounds = [kd_min]
high_bounds = [kd_max]
fit_fx = fit_steady_state_one_site
# Find the upper bound for the Kd
upper_bound = 1e3 if Kd_init >= 1 else 1e2
low_bounds = low_bounds + [x*0.5 for x in p0[1:]]
high_bounds = high_bounds + [x*upper_bound for x in p0[1:]]
fit, cov, fit_vals = fit_fx(
self.signal_ss,self.lig_conc_lst_per_id,
p0,low_bounds,high_bounds)
# Prepare the arguments for re-fitting fit_steady_state_one_site
kwargs = {
"signal_lst": self.signal_ss,
"ligand_lst": self.lig_conc_lst_per_id
}
fit, cov, fit_vals, low_bounds, high_bounds = re_fit(
fit=fit,
cov=cov,
fit_vals=fit_vals,
fit_fx=fit_fx,
low_bounds=low_bounds,
high_bounds= high_bounds,
times=3,
**kwargs)
self.Kd_ss = fit[0]
Smax = fit[1:]
self.params = fit
self.p0 = p0
self._store_correlation(cov, ['Kd [µM]'] + self._group_labels('Smax', len(fit) - 1), kind='ss')
self.low_bounds = low_bounds
self.high_bounds = high_bounds
self.signal_ss_fit = fit_vals
n = np.sum([len(signal) for signal in self.signal_ss])
p = len(p0)
rss_desired = get_desired_rss(concat_signal_lst(self.signal_ss), concat_signal_lst(fit_vals), n, p)
minKd, maxKd = steady_state_one_site_asymmetric_ci95(
self.Kd_ss, self.signal_ss, self.lig_conc_lst_per_id, p0[1:],
low_bounds[1:], high_bounds[1:], rss_desired)
# Create a dataframe with the fitted parameters
df_fit = pd.DataFrame({'Kd [µM]': self.Kd_ss,
'Kd_min95': minKd,
'Kd_max95': maxKd,
'Smax': Smax,
'Name': self.names})
self.fit_params_ss = df_fit
self.Smax_upper_bound_factor = get_smax_upper_bound_factor(self.Kd_ss)
self.fit_params_ss = df_fit
# Fit the steady state signal
return None
[docs]
def fit_steady_state(self, model='one_site', fit_sigma=False):
"""
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.
Returns
-------
None
"""
if model == 'one_site':
return self.fit_steady_state_one_site()
if model == 'two_site':
return self.fit_steady_state_two_site(fit_sigma=fit_sigma)
if model == 'two_site_heterogeneous_ligand':
return self.fit_steady_state_two_site_heterogeneous_ligand()
raise ValueError("Unknown steady-state model: " + model)
[docs]
@store_fit_result('steady_state_two_site_heterogeneous_ligand')
def fit_steady_state_two_site_heterogeneous_ligand(self):
"""
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
-------
None
Updates fitted steady-state signals, fitted parameters, and bounds.
"""
# This function contains AI-generated changes (PR #19).
self.clear_fittings()
self.get_steady_state()
ligand_values = np.array(self.lig_conc_lst_per_id[0], dtype=float)
Kd_init = np.median(ligand_values)
kd_min = np.min(ligand_values) / 1e3
kd_max = np.max(ligand_values) * 1e3
kd_mid = Kd_init
Kd1_init = max(kd_min * 10, Kd_init / 10)
Kd2_init = min(kd_max / 10, Kd_init * 10)
p0 = [Kd1_init, Kd2_init, 0.5]
low_bounds = [kd_min, kd_mid, 1e-6]
high_bounds = [kd_mid, kd_max, 1.0]
upper_bound = 1e3 if Kd_init >= 1 else 1e2
for signal in self.signal_ss:
ymax = np.max(signal)
p0.append(ymax)
low_bounds.append(max(ymax * 0.2, 1e-12))
high_bounds.append(max(ymax * upper_bound, 1e-12))
fit, cov, fit_vals = fit_steady_state_two_site_heterogeneous_ligand(
self.signal_ss,
self.lig_conc_lst_per_id,
p0,
low_bounds,
high_bounds,
)
kwargs = {
"signal_lst": self.signal_ss,
"ligand_lst": self.lig_conc_lst_per_id,
}
fit, cov, fit_vals, low_bounds, high_bounds = re_fit(
fit=fit,
cov=cov,
fit_vals=fit_vals,
fit_fx=fit_steady_state_two_site_heterogeneous_ligand,
low_bounds=low_bounds,
high_bounds=high_bounds,
times=3,
**kwargs,
)
self.Kd1_ss = fit[0]
self.Kd2_ss = fit[1]
self.fraction_site1_ss = fit[2]
self.Kd_ss = np.sqrt(self.Kd1_ss * self.Kd2_ss)
Rmax = fit[3:]
self.params = fit
self.p0 = p0
self._store_correlation(
cov, ['Kd1 [µM]', 'Kd2 [µM]', 'fraction_site1'] + self._group_labels('Rmax', len(fit) - 3), kind='ss')
self.low_bounds = low_bounds
self.high_bounds = high_bounds
self.signal_ss_fit = fit_vals
n_groups = len(Rmax)
if self.names is None:
names = [f"group_{i}" for i in range(n_groups)]
elif len(self.names) == n_groups:
names = self.names
else:
names = [self.names[0] for _ in range(n_groups)]
self.fit_params_ss = pd.DataFrame(
{
'Kd1 [µM]': [self.Kd1_ss] * n_groups,
'Kd2 [µM]': [self.Kd2_ss] * n_groups,
'fraction_site1': [self.fraction_site1_ss] * n_groups,
'Rmax': Rmax,
'Name': names,
}
)
self.Smax_upper_bound_factor = get_smax_upper_bound_factor(self.Kd_ss)
return None
[docs]
@store_fit_result('steady_state_two_site', fit_sigma='steady_state_two_site_cooperative')
def fit_steady_state_two_site(self, fit_sigma=False):
"""
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
-------
None
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
"""
# This function contains AI-generated changes (PR #19).
self.clear_fittings()
self.get_steady_state()
Kd_init = np.median(self.lig_conc_lst_per_id[0])
kd_min = np.min(self.lig_conc_lst_per_id[0]) / 1e3
kd_max = np.max(self.lig_conc_lst_per_id[0]) * 1e3
# Per-group two-site amplitudes: [Rmax_PL_i, Rmax_LPL_i]
p0_rmax = []
for signal in self.signal_ss:
ymax = np.max(signal)
p0_rmax.extend([0.5 * ymax, 1.2 * ymax])
p0 = [Kd_init]
low_bounds = [kd_min]
high_bounds = [kd_max]
if fit_sigma:
p0.append(1.0)
low_bounds.append(1e-6)
high_bounds.append(1e3)
upper_bound = 1e3 if Kd_init >= 1 else 1e2
for i, val in enumerate(p0_rmax):
factor_low = 0.2 if i % 2 == 0 else 0.2
low_bounds.append(val * factor_low)
high_bounds.append(val * upper_bound)
p0 += p0_rmax
fit, cov, fit_vals = fit_steady_state_two_site(
self.signal_ss,
self.lig_conc_lst_per_id,
p0,
low_bounds,
high_bounds,
fit_sigma=fit_sigma,
)
kwargs = {
"signal_lst": self.signal_ss,
"ligand_lst": self.lig_conc_lst_per_id,
"fit_sigma": fit_sigma,
}
fit, cov, fit_vals, low_bounds, high_bounds = re_fit(
fit=fit,
cov=cov,
fit_vals=fit_vals,
fit_fx=fit_steady_state_two_site,
low_bounds=low_bounds,
high_bounds=high_bounds,
times=3,
**kwargs,
)
self.Kd_ss = fit[0]
idx = 1
if fit_sigma:
self.sigma_ss = fit[1]
idx = 2
else:
self.sigma_ss = None
rmax_vals = fit[idx:]
rmax_pl = rmax_vals[0::2]
rmax_lpl = rmax_vals[1::2]
self.params = fit
self.p0 = p0
self._store_correlation(
cov, ['Kd [µM]'] + (['sigma'] if fit_sigma else []) + self._group_labels(('Rmax_PL', 'Rmax_LPL'), len(rmax_pl)),
kind='ss')
self.low_bounds = low_bounds
self.high_bounds = high_bounds
self.signal_ss_fit = fit_vals
n_groups = len(rmax_pl)
if self.names is None:
names = [f"group_{i}" for i in range(n_groups)]
elif len(self.names) == n_groups:
names = self.names
else:
names = [self.names[0] for _ in range(n_groups)]
df_fit = pd.DataFrame(
{
'Kd [µM]': [self.Kd_ss] * n_groups,
'Rmax_PL': rmax_pl,
'Rmax_LPL': rmax_lpl,
'Name': names,
}
)
if fit_sigma:
df_fit['sigma'] = [self.sigma_ss] * n_groups
self.fit_params_ss = df_fit
self.Smax_upper_bound_factor = get_smax_upper_bound_factor(self.Kd_ss)
return None
[docs]
def get_k_off_initial_guess(self):
"""
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
-------
tuple
A tuple containing:
- p0: Initial parameter guesses [Kd, k_off]
- low_bounds: Lower bounds for the parameters
- high_bounds: Upper bounds for the parameters
Raises
------
ValueError
If Kd_ss is not set and fit_steady_state has not been run
"""
# Initial guess for Kd_ss for single_cycle_kinetics
if self.is_single_cycle:
self.Kd_ss = np.median(self.lig_conc_lst)
# Requires that Kd_ss is set
if self.Kd_ss is None:
raise ValueError("Kd_ss is not set. Please run fit_steady_state() first.")
# We check if we have dissociation curves and fit them to get a better estimate of k_off
if self.disso_lst is not None and self.time_disso_lst is not None:
self.fit_one_site_dissociation()
p0 = [self.Kd_ss, self.k_off]
low_bounds = [self.Kd_ss/7e2, self.k_off/7e2]
high_bounds = [self.Kd_ss*7e2, self.k_off*7e2]
self.clear_fittings()
else:
p0 = [self.Kd_ss,0.01]
low_bounds = [self.Kd_ss/7e2,1e-7]
high_bounds = [self.Kd_ss*7e2,10]
return p0, low_bounds, high_bounds
[docs]
@store_fit_result('one_site_association')
def fit_one_site_association(self, shared_smax=True, calc_loo=False):
"""
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
-------
None
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
"""
# This function contains AI-generated changes (PR #19).
self.clear_fittings()
self.shared_smax = shared_smax
p0, low_bounds, high_bounds = self.get_k_off_initial_guess()
self.model = "one_site_association"
smax_guesses = self.smax_guesses_unq if shared_smax else self.smax_guesses_shared
p0 += smax_guesses
low_bounds += [x/15 for x in p0[2:]]
high_bounds += [x*self.Smax_upper_bound_factor for x in p0[2:]]
self.p0 = p0
self.low_bounds = low_bounds
self.high_bounds = high_bounds
fit, cov, fit_vals = fit_one_site_association(
self.assoc_lst,self.time_assoc_lst,self.lig_conc_lst,
p0,low_bounds,high_bounds,smax_idx=self.smax_id,shared_smax=shared_smax,
mask_lst=trim_masks(self.time_assoc_lst, self.trim_time)
)
self.params = fit
self._store_correlation(cov, ['Kd [µM]', 'k_off [1/s]'] + self._amplitude_labels('Smax', shared_smax))
self.signal_assoc_fit = fit_vals
self.Kd = fit[0]
self.k_off = fit[1]
self.Smax = fit[2:]
# Create a dataframe with the fitted parameters
df_fit = pd.DataFrame({'Kd [µM]': self.Kd,
'k_off [1/s]': self.k_off,
'Smax': self.Smax})
error = np.sqrt(np.diag(cov))
rel_error = error/fit * 100
df_error = pd.DataFrame({'Kd [µM]': rel_error[0],
'k_off': rel_error[1],
'Smax': rel_error[2:]})
self.fit_params_kinetics = df_fit
self.fit_params_kinetics_error = df_error
self._add_concentrations(per_trace=not shared_smax)
if calc_loo:
self.calc_leave_one_out_errors()
return None
[docs]
@update_fit_result
def one_site_association_loo(self):
"""
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.
Returns
-------
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
"""
# This function contains AI-generated changes (PR #15).
"""
Leave-one-out curve method for error estimation of the fitted parameters.
"""
Kd_loo = []
k_off_loo = []
n_fits_loo_ok = 0
n_fits_loo_fail = 0
# Iterate over replicates that may share Smax ID
for i in range(len(self.assoc_lst)):
temp_assoc_lst = copy.deepcopy(self.assoc_lst)
temp_time_assoc_lst = copy.deepcopy(self.time_assoc_lst)
# Remove element ii from replicate i
temp_assoc_lst = remove_at(temp_assoc_lst, i)
temp_time_assoc_lst = remove_at(temp_time_assoc_lst, i)
temp_lig_conc_lst = copy.deepcopy(self.lig_conc_lst)
temp_lig_conc_lst = remove_at(temp_lig_conc_lst, i)
temp_p0, temp_low_bounds, temp_high_bounds, temp_smax_idx, _ = (
_leave_one_out_parameters(
self.params, self.low_bounds, self.high_bounds, self.smax_id, i,
shared_smax=self.shared_smax, n_global=2,
group_blocks=(), response_width=1,
)
)
try:
# run the fitting function on the modified lists
fit_loo, _, _ = fit_one_site_association(
temp_assoc_lst,
temp_time_assoc_lst,
temp_lig_conc_lst,
temp_p0,
low_bounds=temp_low_bounds,
high_bounds=temp_high_bounds,
smax_idx=temp_smax_idx,
shared_smax=self.shared_smax,
mask_lst=trim_masks(temp_time_assoc_lst, self.trim_time)
)
Kd_loo.append(fit_loo[0])
k_off_loo.append(fit_loo[1])
n_fits_loo_ok += 1
except Exception as e:
n_fits_loo_fail += 1
pass # If the fitting fails, we just skip this iteration
self.Kd_loo = Kd_loo
self.k_off_loo = k_off_loo
self.Kd_loo_mean = np.mean(Kd_loo)
self.k_off_loo_mean = np.mean(k_off_loo)
self.Kd_loo_std = np.std(Kd_loo)
self.k_off_loo_std = np.std(k_off_loo)
# Create a dataframe with mean ± SD
df_fit_loo = pd.DataFrame({
'Kd [µM]': [f'{self.Kd_loo_mean:.2e} ± {self.Kd_loo_std:.2e}'],
'k_off [1/s]': [f'{self.k_off_loo_mean:.2e} ± {self.k_off_loo_std:.2e}']
})
self.df_fit_loo = df_fit_loo
return None
[docs]
@store_fit_result('one_site_dissociation')
def fit_one_site_dissociation(self, time_limit=0, calc_loo=False):
"""
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
-------
None
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
"""
# This function contains AI-generated changes (PR #19).
self.model = "one_site_dissociation"
self.clear_fittings()
disso_lst = self.disso_lst
time_disso_lst = self.time_disso_lst
# Fit only some data. If time_limit = 0, fit all data
if time_limit > 0:
disso_lst = [x[t < (np.min(t)+time_limit)] for x,t in zip(disso_lst,time_disso_lst)]
time_disso_lst = [t[t < (np.min(t)+time_limit)] for t in time_disso_lst]
self.disso_lst_subset = disso_lst
self.time_disso_lst_subset = time_disso_lst
mask_lst = trim_masks(time_disso_lst, self.trim_time)
if mask_lst is None:
p0 = [0.1] + [np.max(signal) for signal in disso_lst]
else:
p0 = [0.1] + [np.max(signal[mask]) for signal, mask in zip(disso_lst, mask_lst)]
low_bounds = [1e-7] + [x/5 for x in p0[1:]]
high_bounds = [10] + [x*5 for x in p0[1:]]
self.p0 = p0
self.low_bounds = low_bounds
self.high_bounds = high_bounds
fit, cov, fit_vals = fit_one_site_dissociation(disso_lst,time_disso_lst,
p0,low_bounds,high_bounds,
mask_lst=mask_lst)
self.signal_disso_fit = fit_vals
self.k_off = fit[0]
# generate dataframe with the fitted parameters
df_fit = pd.DataFrame({'k_off': self.k_off,
'S0': fit[1:]})
self.fit_params_kinetics = df_fit
# Add the fitted errors to the dataframe
error = np.sqrt(np.diag(cov))
rel_error = error/fit * 100
df_error = pd.DataFrame({'k_off [1/s]': rel_error[0],
'S0': rel_error[1:]})
self.fit_params_kinetics_error = df_error
self._add_concentrations(per_trace=True)
self.params = fit
self._store_correlation(cov, ['k_off [1/s]'] + self._trace_labels('S0'))
if calc_loo:
self.calc_leave_one_out_errors()
return None
[docs]
@update_fit_result
def one_site_dissociation_loo(self):
"""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
"""
k_off_loo = []
n_fits_loo_ok = 0
n_fits_loo_fail = 0
# Iterate over replicates that may share Smax ID
for i in range(len(self.disso_lst_subset)):
temp_disso_lst = copy.deepcopy(self.disso_lst_subset)
temp_time_disso_lst = copy.deepcopy(self.time_disso_lst_subset)
# Remove element ii from replicate i
temp_disso_lst = remove_at(temp_disso_lst, i)
temp_time_disso_lst = remove_at(temp_time_disso_lst, i)
temp_p0 = copy.deepcopy(self.params)
temp_low_bounds = copy.deepcopy(self.low_bounds)
temp_high_bounds = copy.deepcopy(self.high_bounds)
# Remove element from the initial guess and bounds corresponding to the removed measurement
idx = 1 + i # Koff + index of the S0 to remove
temp_p0 = remove_at(temp_p0, idx)
temp_low_bounds = remove_at(temp_low_bounds, idx)
temp_high_bounds = remove_at(temp_high_bounds, idx)
try:
# Run the fitting function on the modified lists.
fit_loo, _, _ = fit_one_site_dissociation(
temp_disso_lst,
temp_time_disso_lst,
temp_p0,
low_bounds=temp_low_bounds,
high_bounds=temp_high_bounds,
mask_lst=trim_masks(temp_time_disso_lst, self.trim_time))
k_off_loo.append(fit_loo[0])
n_fits_loo_ok += 1
except Exception:
n_fits_loo_fail += 1
self.k_off_loo = k_off_loo
self.k_off_loo_mean = np.mean(k_off_loo)
self.k_off_loo_std = np.std(k_off_loo)
# Create a dataframe with mean ± SD
df_fit_loo = pd.DataFrame({
'k_off [1/s]': [f'{self.k_off_loo_mean:.2e} ± {self.k_off_loo_std:.2e}']
})
self.df_fit_loo = df_fit_loo
return None
[docs]
@update_fit_result
def fit_single_exponentials(self):
"""
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
-------
None
Updates the k_obs attribute with a list of observed rate constants
for each association curve.
"""
# Fit one exponential to each signal
# Initialize a list to store the k_obs values - filld with NaNs
k_obs = [np.nan for _ in range(len(self.assoc_lst))]
masks = trim_masks(self.time_assoc_lst, self.trim_time)
for i, (y, t) in enumerate(zip(self.assoc_lst, self.time_assoc_lst)):
# Edited with AI assistance: leave out the first trim_time seconds
if masks is not None:
y, t = y[masks[i]], t[masks[i]]
# A curve that a single exponential cannot describe keeps k_obs = NaN,
# so this diagnostic never invalidates the kinetic fit before it.
try:
fit_params, _, _ = fit_single_exponential_fast(y, t)
except RuntimeError:
continue
k_obs[i] = fit_params[2]
self.k_obs = k_obs
return None
def _mtl_start_candidates(self, p0, fixed_t0,
kd_factors=(1/3, 1, 3),
koff_factors=(0.3, 1, 3, 10, 30, 100),
transport_factors=(0.01, 0.1, 1, 10, 100)):
"""Grid of starting points for the mass-transport fit.
Rebinding slows the observed rates, so the 1:1 koff guess is usually too
low, and the Kd guess from steady state can be off when binding is
transport limited. The grid scales Kd and koff around their guesses and
sets Ktr = kon * Smax * factor (factor > 1: binding-limited, factor < 1:
transport-limited). The grid point whose curves are closest to the
data is used as a second starting point.
Parameters
----------
p0 : list
Starting point ordered [Kd, koff, (t0...), Ktr..., Smax...], with one
t0 and one Ktr per Smax group.
fixed_t0 : bool
Whether t0 is fixed (and absent from p0).
kd_factors, koff_factors, transport_factors : tuple, optional
Grid values, as multiples of the guesses.
Returns
-------
list of list
One starting point per grid point.
"""
# This function is AI generated and reviewed by a human (PR #18).
n_groups = len(self.smax_guesses_unq)
ktr_start = 2 + (0 if fixed_t0 else n_groups)
candidates = []
for kd_f, koff_f, tr_f in itertools.product(kd_factors, koff_factors, transport_factors):
p = list(p0)
p[0] = p0[0] * kd_f
p[1] = p0[1] * koff_f
kon = p[1] / p[0]
for g, smax in enumerate(self.smax_guesses_unq):
p[ktr_start + g] = kon * smax * tr_f
candidates.append(p)
return candidates
[docs]
@store_fit_result('one_site_association_and_dissociation', fit_ktr='one_site_mass_transport')
def fit_one_site_assoc_and_disso(self,shared_smax=True,fixed_t0=True,fit_ktr=False,calc_loo=False):
"""
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.
"""
# This function contains AI-generated changes (PR #19).
# Edited with AI assistance and reviewed by a human in PR #18: grid of starting points for the mass-transport fit.
self.clear_fittings()
self.shared_smax = shared_smax
self.fit_ktr = fit_ktr
self.fixed_t0 = fixed_t0
p0, low_bounds, high_bounds = self.get_k_off_initial_guess()
self.model = "one_site_association_and_dissociation"
# Extend the lower bound for Kd_ss
low_bounds[0] = np.min([self.Kd_ss/1e3] + self.lig_conc_lst) # Kd lower bound
smax_guesses = self.smax_guesses_unq if shared_smax else self.smax_guesses_shared
p0 += smax_guesses
low_bounds += [x/4 for x in p0[2:]]
high_bounds += [x*self.Smax_upper_bound_factor for x in p0[2:]]
smax_param_start = 2
if fit_ktr:
# Ktr is in signal per µM per second. Start where transport is as fast as binding
# (Ktr = kon * Smax), so both Kd and koff shape the first fitted curves.
kon_guess = p0[1] / p0[0]
for smax_guess in reversed(self.smax_guesses_unq):
ktr_guess = kon_guess * smax_guess
p0.insert(2, ktr_guess)
low_bounds.insert(2, ktr_guess * 1e-4)
high_bounds.insert(2, ktr_guess * 1e4)
smax_param_start += 1
if not fixed_t0:
for _ in self.smax_guesses_unq:
p0.insert(2,0)
low_bounds.insert(2,-0.01)
high_bounds.insert(2,0.1)
smax_param_start += 1
if fit_ktr:
fit, cov, fit_vals_assoc, fit_vals_disso = fit_one_site_assoc_and_disso_ktr(
self.assoc_lst,self.time_assoc_lst,self.lig_conc_lst,
self.disso_lst,self.time_disso_lst,
p0,low_bounds,high_bounds,
smax_idx=self.smax_id,
shared_smax=shared_smax,
fixed_t0=fixed_t0,
start_candidates=self._mtl_start_candidates(p0, fixed_t0),
**self._fit_masks(self.time_assoc_lst, self.time_disso_lst)
)
kwargs = {
'assoc_signal_lst' :self.assoc_lst,
'assoc_time_lst' : self.time_assoc_lst,
'analyte_conc_lst' : self.lig_conc_lst,
'disso_signal_lst' :self.disso_lst,
'disso_time_lst' : self.time_disso_lst,
'shared_smax' : shared_smax,
'smax_idx' : self.smax_id,
'fixed_t0' : fixed_t0,
**self._fit_masks(self.time_assoc_lst, self.time_disso_lst)
}
fit, cov, fit_vals_assoc, fit_vals_disso,low_bounds, high_bounds = re_fit_2(
fit=fit,
cov=cov,
fit_vals_a=fit_vals_assoc,
fit_vals_b=fit_vals_disso,
fit_fx=fit_one_site_assoc_and_disso_ktr,
low_bounds=low_bounds,
high_bounds=high_bounds,
times=2,
**kwargs
)
else:
fit, cov, fit_vals_assoc, fit_vals_disso = fit_one_site_assoc_and_disso(
self.assoc_lst,self.time_assoc_lst,self.lig_conc_lst,
self.disso_lst,self.time_disso_lst,
p0,low_bounds,high_bounds,
smax_idx=self.smax_id,
shared_smax=shared_smax,
fixed_t0=fixed_t0,
**self._fit_masks(self.time_assoc_lst, self.time_disso_lst))
self.signal_assoc_fit = fit_vals_assoc
self.signal_disso_fit = fit_vals_disso
self.smax_param_start = smax_param_start
self.Kd = fit[0]
self.k_off = fit[1]
self.Smax = fit[smax_param_start:]
# Create a dataframe with the fitted parameters
df_fit = pd.DataFrame({'Kd [µM]': self.Kd,
'k_off [1/s]': self.k_off,
'Smax': self.Smax})
# Include the Kon, derived from the Kd and Koff
df_fit['(Derived) k_on [1/µM/s]'] = df_fit['k_off [1/s]'] / df_fit['Kd [µM]']
error = np.sqrt(np.diag(cov))
rel_error = error/fit * 100
df_error = pd.DataFrame({'Kd [µM]': rel_error[0],
'k_off [1/s]': rel_error[1],
'Smax': rel_error[smax_param_start:]})
# Add the t0 parameter
if not fixed_t0:
t0 = fit[2:2+len(np.unique(self.smax_id))]
t0_error = rel_error[2:2+len(np.unique(self.smax_id))]
if not shared_smax:
t0_all = expand_parameter_list(t0, self.smax_id)
t0_error_all = expand_parameter_list(t0_error, self.smax_id)
df_fit['t0'] = t0_all
df_error['t0'] = t0_error_all
else:
df_fit['t0'] = t0
df_error['t0'] = t0_error
if fit_ktr:
n_ktr = len(np.unique(self.smax_id))
idx_start = 2+(not fixed_t0)*n_ktr
ktrs = fit[idx_start:smax_param_start]
ktrs_error = rel_error[idx_start:smax_param_start]
if not shared_smax:
ktr_all = expand_parameter_list(ktrs, self.smax_id)
ktr_error_all = expand_parameter_list(ktrs_error, self.smax_id)
df_fit['Ktr'] = ktr_all
df_error['Ktr'] = ktr_error_all
else:
df_fit['Ktr'] = ktrs
df_error['Ktr'] = ktrs_error
self.fit_params_kinetics = df_fit
self.fit_params_kinetics_error = df_error
self._add_concentrations(per_trace=not shared_smax)
self.params = fit
self.p0 = p0
n_groups = len(np.unique(self.smax_id))
labels = ['Kd [µM]', 'k_off [1/s]']
labels += [] if fixed_t0 else self._group_labels('t0', n_groups)
labels += self._group_labels('Ktr', n_groups) if fit_ktr else []
self._store_correlation(cov, labels + self._amplitude_labels('Smax', shared_smax))
self.low_bounds = low_bounds
self.high_bounds = high_bounds
if calc_loo:
self.calc_leave_one_out_errors()
return None
[docs]
@update_fit_result
def one_site_assoc_and_disso_loo(self):
"""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
"""
# This function contains AI-generated changes (PR #15).
Kd_loo = []
k_off_loo = []
fit_ktr = self.fit_ktr
fixed_t0 = self.fixed_t0
shared_smax = self.shared_smax
n_ktr = len(np.unique(self.smax_id))
n_fits_loo_ok = 0
n_fits_loo_fail = 0
if fit_ktr:
# one ktr per Smax group - replicates with the same Smax ID share the same ktr
ktrs_loo = [[] for _ in range(n_ktr)]
state_refits = _loo_state_refit_indices(self.time_assoc_lst, self.time_disso_lst)
# Iterate over replicates that may share Smax ID
for i in range(len(self.assoc_lst)):
temp_assoc_lst = copy.deepcopy(self.assoc_lst)
temp_time_assoc_lst = copy.deepcopy(self.time_assoc_lst)
temp_disso_lst = copy.deepcopy(self.disso_lst)
temp_time_disso_lst = copy.deepcopy(self.time_disso_lst)
# Remove element ii from replicate i
temp_assoc_lst = remove_at(temp_assoc_lst, i)
temp_time_assoc_lst = remove_at(temp_time_assoc_lst, i)
temp_disso_lst = remove_at(temp_disso_lst, i)
temp_time_disso_lst = remove_at(temp_time_disso_lst, i)
temp_lig_conc_lst = copy.deepcopy(self.lig_conc_lst)
temp_lig_conc_lst = remove_at(temp_lig_conc_lst, i)
temp_p0, temp_low_bounds, temp_high_bounds, temp_smax_idx, retained_groups = (
_leave_one_out_parameters(
self.params, self.low_bounds, self.high_bounds, self.smax_id, i,
shared_smax=shared_smax, n_global=2,
group_blocks=(1,) * ((not fixed_t0) + fit_ktr), response_width=1,
)
)
kwargs = {
'assoc_signal_lst' : temp_assoc_lst,
'assoc_time_lst' : temp_time_assoc_lst,
'analyte_conc_lst' : temp_lig_conc_lst,
'disso_signal_lst' : temp_disso_lst,
'disso_time_lst' : temp_time_disso_lst,
'shared_smax' : shared_smax,
'smax_idx' : temp_smax_idx,
'fixed_t0' : fixed_t0,
'initial_parameters' : temp_p0,
'low_bounds' : temp_low_bounds,
'high_bounds' : temp_high_bounds,
**self._fit_masks(temp_time_assoc_lst, temp_time_disso_lst)
}
fit_fx = fit_one_site_assoc_and_disso_ktr if fit_ktr else fit_one_site_assoc_and_disso
if fit_ktr and i in state_refits:
kwargs['fit_initial_state_at'] = i
try:
# Run the fitting function on the modified lists.
fit_loo, _, _, _ = fit_fx(**kwargs)
ktrs = []
if fit_ktr:
n_retained = len(retained_groups)
idx_start = 2 + (not fixed_t0) * n_retained
ktrs = fit_loo[idx_start:idx_start + n_retained]
Kd_loo.append(fit_loo[0])
k_off_loo.append(fit_loo[1])
if fit_ktr:
for group, ktr in zip(retained_groups, ktrs):
ktrs_loo[group].append(ktr)
n_fits_loo_ok += 1
except Exception:
n_fits_loo_fail += 1
self.Kd_loo = Kd_loo
self.k_off_loo = k_off_loo
self.Kd_loo_mean = np.mean(Kd_loo)
self.k_off_loo_mean = np.mean(k_off_loo)
self.Kd_loo_std = np.std(Kd_loo)
self.k_off_loo_std = np.std(k_off_loo)
# Create a dataframe with mean ± SD
df_fit_loo = pd.DataFrame({
'Kd [µM]': [f'{self.Kd_loo_mean:.2e} ± {self.Kd_loo_std:.2e}'],
'k_off [1/s]': [f'{self.k_off_loo_mean:.2e} ± {self.k_off_loo_std:.2e}']
})
if fit_ktr:
ktr_loo_means = []
ktr_loo_stds = []
for j, ktr_loo in enumerate(ktrs_loo):
ktr_loo_means.append(np.mean(ktr_loo))
ktr_loo_stds.append(np.std(ktr_loo))
df_fit_loo['Ktr [signal/(µM·s)] - Replicate ' + str(j)] = [
f'{np.mean(ktr_loo):.2e} ± {np.std(ktr_loo):.2e}']
self.ktr_loo_means = ktr_loo_means
self.ktr_loo_stds = ktr_loo_stds
self.df_fit_loo = df_fit_loo
return None
[docs]
@store_fit_result('two_site_association_and_dissociation', fit_sigma='two_site_cooperative')
def fit_two_site_assoc_and_disso(self, shared_smax=True, fixed_t0=True, fit_sigma=False, calc_loo=False):
"""
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.
"""
# This function contains AI-generated changes (PR #19).
self.clear_fittings()
# Obtain initial guesses and bounds for Kd and k_off
self.fit_one_site_assoc_and_disso(shared_smax=shared_smax, fixed_t0=True, fit_ktr=False)
self.model = "two_site_association_and_dissociation"
k_off_init = self.k_off
Kd_init = self.Kd
# Increase Kd initial guess by a factor of 10, to account for the higher apparent affinity of the two-site model
Kd_init *= 10
# Expand Smax, we need two Smax values per Smax ID, one for the single-bound state and one for the double-bound state
Smax_init = []
for smax in self.Smax:
Smax_init.extend([0.5*smax, 0.5*smax])
n_unq_smax = len(np.unique(self.smax_id))
# Stage 1: fit without sigma and without t0.
p0 = [Kd_init, k_off_init] + Smax_init
p0_low = [Kd_init/1e3, k_off_init/1e3] + [x/50 for x in Smax_init]
p0_high = [Kd_init*1e3, k_off_init*1e3] + [x*25 for x in Smax_init]
kwargs = {
'assoc_signal_lst' : self.assoc_lst,
'assoc_time_lst' : self.time_assoc_lst,
'analyte_conc_lst' : self.lig_conc_lst,
'disso_signal_lst' :self.disso_lst,
'disso_time_lst' : self.time_disso_lst,
'shared_smax' : shared_smax,
'smax_idx' : self.smax_id,
**self._fit_masks(self.time_assoc_lst, self.time_disso_lst),
}
global_fit_params, cov, fitted_values_assoc, fitted_values_disso = fit_two_site_assoc_and_disso(
**kwargs,
initial_parameters=p0,
low_bounds=p0_low,
high_bounds=p0_high,
fixed_t0=True,
fit_sigma=False,
)
# Stage 2: optionally fit sigma (still without t0).
if fit_sigma:
sigma_init = 1.0
# Insert sigma_init at the correct position in p0, which is after Kd and k_off, but before the Smax values
p0 = np.insert(global_fit_params, 2, sigma_init).tolist()
p0_low = [p0[0]/1e3, p0[1]/1e3, 1e-3] + [x/50 for x in p0[3:]]
p0_high = [p0[0]*1e3, p0[1]*1e3, 1e3] + [x*25 for x in p0[3:]]
global_fit_params, cov, fitted_values_assoc, fitted_values_disso = fit_two_site_assoc_and_disso(
**kwargs,
initial_parameters=p0,
low_bounds=p0_low,
high_bounds=p0_high,
fixed_t0=True,
fit_sigma=True,
)
# Stage 3: optionally fit t0 with the selected sigma mode.
if not fixed_t0:
insert_idx = 3 if fit_sigma else 2
p0 = np.array(global_fit_params, dtype=float).tolist()
p0 = p0[:insert_idx] + [0.0 for _ in range(len(self.smax_guesses_unq))] + p0[insert_idx:]
p0_low = [p0[0]/1e3, p0[1]/1e3]
p0_high = [p0[0]*1e3, p0[1]*1e3]
if fit_sigma:
p0_low += [1e-3]
p0_high += [1e3]
# Keep t0 tightly centered around zero.
p0_low += [-1e-3 for _ in range(len(self.smax_guesses_unq))]
p0_high += [1e-3 for _ in range(len(self.smax_guesses_unq))]
amp_start = insert_idx + n_unq_smax
p0_low += [x/50 for x in p0[amp_start:]]
p0_high += [x*25 for x in p0[amp_start:]]
global_fit_params, cov, fitted_values_assoc, fitted_values_disso = fit_two_site_assoc_and_disso(
**kwargs,
initial_parameters=p0,
low_bounds=p0_low,
high_bounds=p0_high,
fixed_t0=False,
fit_sigma=fit_sigma,
)
self.signal_assoc_fit = fitted_values_assoc
self.signal_disso_fit = fitted_values_disso
fit = np.array(global_fit_params, dtype=float)
self.Kd = fit[0]
self.k_off = fit[1]
idx = 2
sigma_val = None
if fit_sigma:
sigma_val = fit[idx]
idx += 1
n_unq_smax = len(np.unique(self.smax_id))
t0_vals = None
if not fixed_t0:
t0_vals = fit[idx:idx + n_unq_smax]
idx += n_unq_smax
rmax_vals = fit[idx:]
rmax_pl = rmax_vals[0::2]
rmax_lpl = rmax_vals[1::2]
self.Smax = rmax_vals
# Create dataframe with fitted parameters
df_fit = pd.DataFrame(
{
'Kd [µM]': self.Kd,
'k_off [1/s]': self.k_off,
'Rmax_PL': rmax_pl,
'Rmax_LPL': rmax_lpl,
}
)
if fit_sigma:
df_fit['sigma'] = sigma_val
df_fit['(Derived) k_on [1/µM/s]'] = df_fit['k_off [1/s]'] / df_fit['Kd [µM]']
# Relative errors (in %) from covariance diagonal
error = np.sqrt(np.diag(cov))
rel_error = error / fit * 100
idx_err = 2
sigma_err = None
if fit_sigma:
sigma_err = rel_error[idx_err]
idx_err += 1
t0_err_vals = None
if not fixed_t0:
t0_err_vals = rel_error[idx_err:idx_err + n_unq_smax]
idx_err += n_unq_smax
rmax_err = rel_error[idx_err:]
rmax_pl_err = rmax_err[0::2]
rmax_lpl_err = rmax_err[1::2]
df_error = pd.DataFrame(
{
'Kd [µM]': rel_error[0],
'k_off [1/s]': rel_error[1],
'Rmax_PL': rmax_pl_err,
'Rmax_LPL': rmax_lpl_err,
}
)
if fit_sigma:
df_error['sigma'] = sigma_err
if not fixed_t0:
if not shared_smax:
t0_all = expand_parameter_list(t0_vals, self.smax_id)
t0_err_all = expand_parameter_list(t0_err_vals, self.smax_id)
df_fit['t0'] = t0_all
df_error['t0'] = t0_err_all
else:
df_fit['t0'] = t0_vals
df_error['t0'] = t0_err_vals
self.fit_params_kinetics = df_fit
self.fit_params_kinetics_error = df_error
self._add_concentrations(per_trace=not shared_smax)
self.params = fit
self.p0 = p0
labels = ['Kd [µM]', 'k_off [1/s]'] + (['sigma'] if fit_sigma else [])
labels += [] if fixed_t0 else self._group_labels('t0', n_unq_smax)
self._store_correlation(cov, labels + self._amplitude_labels(('Rmax_PL', 'Rmax_LPL'), shared_smax))
self.low_bounds = p0_low
self.high_bounds = p0_high
# below and not on top because the first fitting with one site will overwrite fixed_t0 otherwise
self.shared_smax = shared_smax
self.fixed_t0 = fixed_t0
self.fit_sigma = fit_sigma
if calc_loo:
self.calc_leave_one_out_errors()
return None
[docs]
@update_fit_result
def two_site_assoc_and_disso_loo(self):
"""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
"""
# This function contains AI-generated changes (PR #15).
shared_smax = self.shared_smax
fixed_t0 = self.fixed_t0
fit_sigma = self.fit_sigma
n_fits_loo_ok = 0
n_fits_loo_fail = 0
state_refits = _loo_state_refit_indices(self.time_assoc_lst, self.time_disso_lst)
Kd_loo = []
k_off_loo = []
if fit_sigma:
sigma_loo = []
# Iterate over replicates that may share Smax ID
for i in range(len(self.assoc_lst)):
temp_assoc_lst = copy.deepcopy(self.assoc_lst)
temp_time_assoc_lst = copy.deepcopy(self.time_assoc_lst)
temp_disso_lst = copy.deepcopy(self.disso_lst)
temp_time_disso_lst = copy.deepcopy(self.time_disso_lst)
# Remove element ii from replicate i
temp_assoc_lst = remove_at(temp_assoc_lst, i)
temp_time_assoc_lst = remove_at(temp_time_assoc_lst, i)
temp_disso_lst = remove_at(temp_disso_lst, i)
temp_time_disso_lst = remove_at(temp_time_disso_lst, i)
temp_lig_conc_lst = copy.deepcopy(self.lig_conc_lst)
temp_lig_conc_lst = remove_at(temp_lig_conc_lst, i)
temp_p0, temp_low_bounds, temp_high_bounds, temp_smax_idx, _ = (
_leave_one_out_parameters(
self.params, self.low_bounds, self.high_bounds, self.smax_id, i,
shared_smax=shared_smax, n_global=2 + fit_sigma,
group_blocks=(1,) * (not fixed_t0), response_width=2,
)
)
kwargs_loo = {
'assoc_signal_lst' : temp_assoc_lst,
'assoc_time_lst' : temp_time_assoc_lst,
'analyte_conc_lst' : temp_lig_conc_lst,
'disso_signal_lst' : temp_disso_lst,
'disso_time_lst' : temp_time_disso_lst,
'initial_parameters' : temp_p0,
'low_bounds' : temp_low_bounds,
'high_bounds' : temp_high_bounds,
'shared_smax' : shared_smax,
'smax_idx' : temp_smax_idx,
'fixed_t0' : fixed_t0,
'fit_sigma' : fit_sigma,
'fit_initial_state_at': i if i in state_refits else None,
**self._fit_masks(temp_time_assoc_lst, temp_time_disso_lst),
}
try:
fit_loo, _, _, _ = fit_two_site_assoc_and_disso(**kwargs_loo)
Kd = fit_loo[0]
k_off = fit_loo[1]
sigma = fit_loo[2] if fit_sigma else None
Kd_loo.append(Kd)
k_off_loo.append(k_off)
if fit_sigma:
sigma_loo.append(sigma)
n_fits_loo_ok += 1
except Exception:
n_fits_loo_fail += 1
self.Kd_loo = Kd_loo
self.k_off_loo = k_off_loo
self.Kd_loo_mean = np.mean(Kd_loo)
self.k_off_loo_mean = np.mean(k_off_loo)
self.Kd_loo_std = np.std(Kd_loo)
self.k_off_loo_std = np.std(k_off_loo)
df_fit_loo = pd.DataFrame({
'Kd [µM]': [f'{self.Kd_loo_mean:.2e} ± {self.Kd_loo_std:.2e}'],
'k_off [1/s]': [f'{self.k_off_loo_mean:.2e} ± {self.k_off_loo_std:.2e}']
})
# Add sigma to the dataframe if it was fitted
if fit_sigma:
self.sigma_loo = sigma_loo
self.sigma_loo_mean = np.mean(sigma_loo)
self.sigma_loo_std = np.std(sigma_loo)
df_fit_loo['sigma'] = [f'{self.sigma_loo_mean:.2e} ± {self.sigma_loo_std:.2e}']
self.df_fit_loo = df_fit_loo
return None
[docs]
@store_fit_result('two_site_heterogeneous_ligand_association_and_dissociation')
def fit_two_site_heterogeneous_ligand_assoc_and_disso(
self,
shared_smax=True,
fixed_t0=True,
Kd1_values=None,
Kd2_values=None,
calc_loo=False
):
"""
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
-------
None
Updates fitted signal, parameter, bounds, and grid-search attributes.
"""
# This function contains AI-generated changes (PR #19).
self.clear_fittings()
if self.Kd_ss is None and not self.is_single_cycle:
self.fit_steady_state_one_site()
if self.smax_guesses_unq is None or self.smax_guesses_shared is None:
self.get_steady_state()
self.fit_one_site_assoc_and_disso(shared_smax=shared_smax, fixed_t0=True, fit_ktr=False)
self.model = "two_site_heterogeneous_ligand_association_and_dissociation"
Kd_init = float(self.Kd)
koff_init = float(self.k_off)
smax_init = np.array(self.Smax, dtype=float).tolist()
if Kd1_values is None:
Kd1_values = Kd_init * np.array([1e-2, 5e-2, 1e-1, 5e-1, 1.0])
if Kd2_values is None:
Kd2_values = Kd_init * np.array([1e-1, 5e-1,1.0, 3.0, 1e1, 5e1, 1e2])
Kd1_values = np.array(Kd1_values, dtype=float)
Kd2_values = np.array(Kd2_values, dtype=float)
candidate_pairs = [(Kd1, Kd2) for Kd1, Kd2 in itertools.product(Kd1_values, Kd2_values) if Kd1 > 0 and Kd2 > 0 and Kd1 < Kd2]
if len(candidate_pairs) == 0:
raise ValueError("Grid search requires at least one Kd pair with Kd1 < Kd2.")
# Edited with AI assistance: keep only the pairs whose Kd2 is within the lower
# bound of the final fit (10 * min_kd, computed below in the same way). Otherwise
# the best pair could start the final fit outside its bounds, and the fit failed.
min_conc = np.min(self.lig_conc_lst)
candidate_pairs = [(Kd1, Kd2) for Kd1, Kd2 in candidate_pairs
if Kd2 >= np.min([Kd1, Kd2, min_conc/10])*10]
if len(candidate_pairs) == 0:
raise ValueError("Grid search requires at least one Kd pair with Kd2 >= 10 * min(Kd1, lowest concentration / 10).")
time_assoc_lst_subsampled = [subset_data(t) for t in self.time_assoc_lst]
time_disso_lst_subsampled = [subset_data(t) for t in self.time_disso_lst]
assoc_lst_subsampled = [subset_data(y) for y in self.assoc_lst]
disso_lst_subsampled = [subset_data(y) for y in self.disso_lst]
kwargs_grid = {
'assoc_signal_lst': assoc_lst_subsampled,
'assoc_time_lst': time_assoc_lst_subsampled,
'analyte_conc_lst': self.lig_conc_lst,
'disso_signal_lst': disso_lst_subsampled,
'disso_time_lst': time_disso_lst_subsampled,
'shared_smax': shared_smax,
'smax_idx': self.smax_id,
'fixed_t0': True,
**self._fit_masks(time_assoc_lst_subsampled, time_disso_lst_subsampled),
}
# Edited with AI assistance: the fraction of site 1 has the same lower bound
# (0.01) as in the final fit. With 1e-6 the grid could return a fraction
# below 0.01, and the final fit then failed because its start was outside
# the bounds; a site with less than 1% of the signal is not meaningful.
p0_grid_base = [koff_init, koff_init, 0.5] + smax_init
low_grid_base = [max(koff_init / 1e3, 1e-8), max(koff_init / 1e3, 1e-8), 0.01] + [max(x / 50, 1e-12) for x in smax_init]
high_grid_base = [min(koff_init * 1e3, 10.0), min(koff_init * 1e3, 10.0), 1.0] + [max(x * 25, 1e-12) for x in smax_init]
best_rss = np.inf
best_params = None
best_Kd1 = None
best_Kd2 = None
grid_rows = []
for Kd1_value, Kd2_value in candidate_pairs:
try:
params, _, fit_vals_assoc, fit_vals_disso = fit_two_site_heterogeneous_ligand_assoc_and_disso(
**kwargs_grid,
initial_parameters=p0_grid_base,
low_bounds=low_grid_base,
high_bounds=high_grid_base,
fixed_Kd1=True,
Kd1_value=Kd1_value,
fixed_Kd2=True,
Kd2_value=Kd2_value,
)
rss = self._grid_rss(assoc_lst_subsampled, fit_vals_assoc, time_assoc_lst_subsampled,
disso_lst_subsampled, fit_vals_disso, time_disso_lst_subsampled)
grid_rows.append({'Kd1_value': Kd1_value, 'Kd2_value': Kd2_value, 'rss': rss})
if rss < best_rss:
best_rss = rss
best_params = np.array(params, dtype=float)
best_Kd1 = float(Kd1_value)
best_Kd2 = float(Kd2_value)
except Exception:
grid_rows.append({'Kd1_value': Kd1_value, 'Kd2_value': Kd2_value, 'rss': np.inf})
continue
if best_params is None:
raise RuntimeError("Grid search failed for all Kd1/Kd2 candidate pairs.")
self.heterogeneous_ligand_grid_search = pd.DataFrame(grid_rows)
best_koff1 = best_params[0]
best_koff2 = best_params[1]
best_fraction = best_params[2]
best_smax = best_params[3:].tolist()
p0 = [best_Kd1, best_koff1, best_Kd2, best_koff2, best_fraction]
min_kd = np.min([best_Kd1, best_Kd2, np.min(self.lig_conc_lst)/10])
max_kd = np.max([best_Kd1, best_Kd2, np.max(self.lig_conc_lst)*10])
min_koff = np.min([best_koff1, best_koff2, 1e-3])
max_koff = np.max([best_koff1, best_koff2, 10.0])
min_koff = np.max([min_koff, 1e-9])
max_koff = np.min([max_koff, 10.0])
low_bounds = [min_kd, min_koff, min_kd*10, min_koff, 0.01]
high_bounds = [max_kd, max_koff, max_kd*10, max_koff, 1.0]
n_unq_smax = len(np.unique(self.smax_id))
if not fixed_t0:
p0 += [0.0 for _ in range(n_unq_smax)]
low_bounds += [-0.01 for _ in range(n_unq_smax)]
high_bounds += [0.1 for _ in range(n_unq_smax)]
p0 += best_smax
low_bounds += [max(x / 50, 1e-12) for x in best_smax]
high_bounds += [max(x * 50, 1e-12) for x in best_smax]
kwargs = {
'assoc_signal_lst': self.assoc_lst,
'assoc_time_lst': self.time_assoc_lst,
'analyte_conc_lst': self.lig_conc_lst,
'disso_signal_lst': self.disso_lst,
'disso_time_lst': self.time_disso_lst,
'shared_smax': shared_smax,
'smax_idx': self.smax_id,
'fixed_t0': fixed_t0,
**self._fit_masks(self.time_assoc_lst, self.time_disso_lst)
}
fit, cov, fit_vals_assoc, fit_vals_disso = fit_two_site_heterogeneous_ligand_assoc_and_disso(
**kwargs,
initial_parameters=p0,
low_bounds=low_bounds,
high_bounds=high_bounds,
)
self.signal_assoc_fit = fit_vals_assoc
self.signal_disso_fit = fit_vals_disso
fit = np.array(fit, dtype=float)
self.Kd1 = fit[0]
self.k_off1 = fit[1]
self.Kd2 = fit[2]
self.k_off2 = fit[3]
self.fraction_site1 = fit[4]
idx = 5
t0_vals = None
if not fixed_t0:
t0_vals = fit[idx:idx + n_unq_smax]
idx += n_unq_smax
self.Smax = fit[idx:]
rows = len(self.Smax)
if self.names is None:
names = [f"group_{i}" for i in range(rows)]
elif len(self.names) == rows:
names = self.names
else:
names = [self.names[0] for _ in range(rows)]
df_fit = pd.DataFrame(
{
'Kd1 [µM]': [self.Kd1] * rows,
'k_off1 [1/s]': [self.k_off1] * rows,
'Kd2 [µM]': [self.Kd2] * rows,
'k_off2 [1/s]': [self.k_off2] * rows,
'fraction_site1': [self.fraction_site1] * rows,
'Rmax': self.Smax,
'Name': names,
}
)
df_fit['(Derived) k_on1 [1/µM/s]'] = df_fit['k_off1 [1/s]'] / df_fit['Kd1 [µM]']
df_fit['(Derived) k_on2 [1/µM/s]'] = df_fit['k_off2 [1/s]'] / df_fit['Kd2 [µM]']
error = np.sqrt(np.diag(cov))
with np.errstate(divide='ignore', invalid='ignore'):
rel_error = error / fit * 100
idx_err = 5
t0_err_vals = None
if not fixed_t0:
t0_err_vals = rel_error[idx_err:idx_err + n_unq_smax]
idx_err += n_unq_smax
smax_error = rel_error[idx_err:]
df_error = pd.DataFrame(
{
'Kd1 [µM]': [rel_error[0]] * rows,
'k_off1 [1/s]': [rel_error[1]] * rows,
'Kd2 [µM]': [rel_error[2]] * rows,
'k_off2 [1/s]': [rel_error[3]] * rows,
'fraction_site1': [rel_error[4]] * rows,
'Rmax': smax_error,
'Name': names,
}
)
if not fixed_t0:
if not shared_smax:
t0_all = expand_parameter_list(t0_vals, self.smax_id)
t0_err_all = expand_parameter_list(t0_err_vals, self.smax_id)
df_fit['t0'] = t0_all
df_error['t0'] = t0_err_all
else:
df_fit['t0'] = t0_vals
df_error['t0'] = t0_err_vals
self.fit_params_kinetics = df_fit
self.fit_params_kinetics_error = df_error
self._add_concentrations(per_trace=not shared_smax)
self.params = fit
self.p0 = p0
labels = ['Kd1 [µM]', 'k_off1 [1/s]', 'Kd2 [µM]', 'k_off2 [1/s]', 'fraction_site1']
labels += [] if fixed_t0 else self._group_labels('t0', n_unq_smax)
self._store_correlation(cov, labels + self._amplitude_labels('Rmax', shared_smax))
self.low_bounds = low_bounds
self.high_bounds = high_bounds
self.best_Kd1_grid = best_Kd1
self.best_Kd2_grid = best_Kd2
self.shared_smax = shared_smax
self.fixed_t0 = fixed_t0
if calc_loo:
self.calc_leave_one_out_errors()
return None
[docs]
@update_fit_result
def two_site_heterogeneous_ligand_assoc_and_disso_loo(self):
"""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
"""
# This function contains AI-generated changes (PR #15).
shared_smax = self.shared_smax
fixed_t0 = self.fixed_t0
n_fits_loo_ok = 0
n_fits_loo_fail = 0
Kd1_loo = []
k_off1_loo = []
Kd2_loo = []
k_off2_loo = []
fraction_site1_loo = []
state_refits = _loo_state_refit_indices(self.time_assoc_lst, self.time_disso_lst)
for i in range(len(self.assoc_lst)):
temp_assoc_lst = copy.deepcopy(self.assoc_lst)
temp_time_assoc_lst = copy.deepcopy(self.time_assoc_lst)
temp_disso_lst = copy.deepcopy(self.disso_lst)
temp_time_disso_lst = copy.deepcopy(self.time_disso_lst)
temp_assoc_lst = remove_at(temp_assoc_lst, i)
temp_time_assoc_lst = remove_at(temp_time_assoc_lst, i)
temp_disso_lst = remove_at(temp_disso_lst, i)
temp_time_disso_lst = remove_at(temp_time_disso_lst, i)
temp_lig_conc_lst = copy.deepcopy(self.lig_conc_lst)
temp_lig_conc_lst = remove_at(temp_lig_conc_lst, i)
temp_p0, temp_low_bounds, temp_high_bounds, temp_smax_idx, _ = (
_leave_one_out_parameters(
self.params, self.low_bounds, self.high_bounds, self.smax_id, i,
shared_smax=shared_smax, n_global=5,
group_blocks=(1,) * (not fixed_t0), response_width=1,
)
)
kwargs_loo = {
'assoc_signal_lst': temp_assoc_lst,
'assoc_time_lst': temp_time_assoc_lst,
'analyte_conc_lst': temp_lig_conc_lst,
'disso_signal_lst': temp_disso_lst,
'disso_time_lst': temp_time_disso_lst,
'initial_parameters': temp_p0,
'low_bounds': temp_low_bounds,
'high_bounds': temp_high_bounds,
'shared_smax': shared_smax,
'smax_idx': temp_smax_idx,
'fixed_t0': fixed_t0,
'fit_initial_state_at': i if i in state_refits else None,
**self._fit_masks(temp_time_assoc_lst, temp_time_disso_lst),
}
try:
fit_loo, _, _, _ = fit_two_site_heterogeneous_ligand_assoc_and_disso(
**kwargs_loo
)
Kd1, k_off1, Kd2, k_off2, fraction_site1 = fit_loo[:5]
Kd1_loo.append(Kd1)
k_off1_loo.append(k_off1)
Kd2_loo.append(Kd2)
k_off2_loo.append(k_off2)
fraction_site1_loo.append(fraction_site1)
n_fits_loo_ok += 1
except Exception:
n_fits_loo_fail += 1
self.Kd1_loo = Kd1_loo
self.k_off1_loo = k_off1_loo
self.Kd2_loo = Kd2_loo
self.k_off2_loo = k_off2_loo
self.fraction_site1_loo = fraction_site1_loo
self.Kd1_loo_mean = np.mean(Kd1_loo)
self.k_off1_loo_mean = np.mean(k_off1_loo)
self.Kd2_loo_mean = np.mean(Kd2_loo)
self.k_off2_loo_mean = np.mean(k_off2_loo)
self.fraction_site1_loo_mean = np.mean(fraction_site1_loo)
self.Kd1_loo_std = np.std(Kd1_loo)
self.k_off1_loo_std = np.std(k_off1_loo)
self.Kd2_loo_std = np.std(Kd2_loo)
self.k_off2_loo_std = np.std(k_off2_loo)
self.fraction_site1_loo_std = np.std(fraction_site1_loo)
df_fit_loo = pd.DataFrame({
'Kd1 [µM]': [f'{self.Kd1_loo_mean:.2e} ± {self.Kd1_loo_std:.2e}'],
'k_off1 [1/s]': [f'{self.k_off1_loo_mean:.2e} ± {self.k_off1_loo_std:.2e}'],
'Kd2 [µM]': [f'{self.Kd2_loo_mean:.2e} ± {self.Kd2_loo_std:.2e}'],
'k_off2 [1/s]': [f'{self.k_off2_loo_mean:.2e} ± {self.k_off2_loo_std:.2e}'],
'fraction_site1': [f'{self.fraction_site1_loo_mean:.2e} ± {self.fraction_site1_loo_std:.2e}']
})
self.df_fit_loo = df_fit_loo
return None
[docs]
@store_fit_result('bivalent_analyte_association_and_dissociation')
def fit_bivalent_analyte_assoc_and_disso(self, shared_smax=True, fixed_t0=True,
ka2_rmax_values=None, kd2_factors=None,
koff1_factors=None, n_starts=3, calc_loo=False):
"""
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
-------
None
Updates the fitted signals, parameters (Kd1, k_off1, k_a2, k_d2, Rmax),
bounds and the grid search table (bivalent_analyte_grid_search).
"""
# This function is AI generated.
self.clear_fittings()
if self.Kd_ss is None and not self.is_single_cycle:
self.fit_steady_state_one_site()
if self.smax_guesses_unq is None or self.smax_guesses_shared is None:
self.get_steady_state()
self.fit_one_site_assoc_and_disso(shared_smax=shared_smax, fixed_t0=True, fit_ktr=False)
self.model = "bivalent_analyte_association_and_dissociation"
# Without the second arm, the model is one-to-one with kon = 2 * ka1
koff_init = float(self.k_off)
kon1_init = koff_init / float(self.Kd) / 2
rmax_init = np.array(self.Smax, dtype=float).tolist()
rmax_ref = float(np.max(rmax_init))
# The grid fits one Rmax per Smax group, also when the final fit has one per
# curve: fewer parameters make each grid fit cheaper
smax_id = np.asarray(self.smax_id)
n_unq_smax = len(np.unique(smax_id))
if shared_smax:
rmax_grid = rmax_init
else:
rmax_grid = [float(np.mean(np.asarray(rmax_init)[smax_id == g])) for g in range(n_unq_smax)]
if ka2_rmax_values is None:
ka2_rmax_values = [1e-3, 1e-2, 1e-1, 1.0, 10.0]
if kd2_factors is None:
kd2_factors = [0.1, 1.0, 10.0, 100.0, 1000.0]
if koff1_factors is None:
koff1_factors = [1.0, 10.0, 100.0, 1000.0]
time_assoc_lst_subsampled = [subset_data(t) for t in self.time_assoc_lst]
time_disso_lst_subsampled = [subset_data(t) for t in self.time_disso_lst]
assoc_lst_subsampled = [subset_data(y) for y in self.assoc_lst]
disso_lst_subsampled = [subset_data(y) for y in self.disso_lst]
kwargs_grid = {
'assoc_signal_lst': assoc_lst_subsampled,
'assoc_time_lst': time_assoc_lst_subsampled,
'analyte_conc_lst': self.lig_conc_lst,
'disso_signal_lst': disso_lst_subsampled,
'disso_time_lst': time_disso_lst_subsampled,
'shared_smax': True,
'smax_idx': self.smax_id,
'fixed_t0': True,
# The grid only ranks starting points: a looser integration and
# optimizer tolerance make it 2-4x faster
'rtol': 1e-5,
'coarse': True,
**self._fit_masks(time_assoc_lst_subsampled, time_disso_lst_subsampled),
}
grid_rows = []
grid_points = []
for koff1_factor, ka2_rmax, kd2_factor in itertools.product(koff1_factors, ka2_rmax_values, kd2_factors):
koff1 = koff1_factor * koff_init
Kd1 = koff1 / kon1_init
ka2 = ka2_rmax / rmax_ref
kd2 = kd2_factor * koff_init
p0_grid = [Kd1, koff1] + rmax_grid
low_grid = [Kd1 / 1e3, koff1 / 1e3] + [x / 10 for x in rmax_grid]
high_grid = [Kd1 * 1e3, koff1 * 1e3] + [x * 10 for x in rmax_grid]
try:
params, _, fit_vals_assoc, fit_vals_disso = fit_bivalent_analyte_assoc_and_disso(
**kwargs_grid,
initial_parameters=p0_grid, low_bounds=low_grid, high_bounds=high_grid,
fixed_ka2=True, ka2_value=ka2, fixed_kd2=True, kd2_value=kd2)
rss = self._grid_rss(assoc_lst_subsampled, fit_vals_assoc, time_assoc_lst_subsampled,
disso_lst_subsampled, fit_vals_disso, time_disso_lst_subsampled)
except Exception:
rss, params = np.inf, None
grid_rows.append({'koff1_start': koff1, 'ka2_value': ka2, 'kd2_value': kd2, 'rss': rss})
if params is not None and np.isfinite(rss):
grid_points.append((rss, ka2, kd2, np.array(params, dtype=float)))
if not grid_points:
raise RuntimeError("Grid search failed for all k_a2/k_d2 candidates.")
self.bivalent_analyte_grid_search = pd.DataFrame(grid_rows)
# The coarse grid can rank a point of another basin first, so the final fit
# starts from the best few grid points and keeps the lowest residual
full_fit_kwargs = dict(smax_idx=self.smax_id, shared_smax=shared_smax, fixed_t0=fixed_t0,
**self._fit_masks(self.time_assoc_lst, self.time_disso_lst))
# Grid fits that differ only in the k_off1 start often converge to the same
# point, so keep the best one for each fixed (k_a2, k_d2) pair
starts = {}
for point in sorted(grid_points, key=lambda x: x[0]):
starts.setdefault((point[1], point[2]), point)
best, last_error = None, None
for _, ka2_init, kd2_init, grid_params in list(starts.values())[:n_starts]:
Kd1_0, koff1_0 = grid_params[:2]
rmax_0 = grid_params[2:].tolist()
if not shared_smax:
rmax_0 = [rmax_0[g] for g in smax_id]
p0 = [Kd1_0, koff1_0, ka2_init, kd2_init]
low_bounds = [Kd1_0 / 1e3, koff1_0 / 1e3, ka2_init / 1e4, kd2_init / 1e4]
high_bounds = [Kd1_0 * 1e3, koff1_0 * 1e3, ka2_init * 1e4, kd2_init * 1e4]
if not fixed_t0:
p0 += [0.0] * n_unq_smax
low_bounds += [-0.01] * n_unq_smax
high_bounds += [0.1] * n_unq_smax
p0 += rmax_0
low_bounds += [x / 10 for x in rmax_0]
high_bounds += [x * 10 for x in rmax_0]
try:
result = fit_bivalent_analyte_assoc_and_disso(
self.assoc_lst, self.time_assoc_lst, self.lig_conc_lst,
self.disso_lst, self.time_disso_lst,
p0, low_bounds, high_bounds, **full_fit_kwargs)
except (RuntimeError, ValueError) as error:
last_error = error
continue
rss = self._grid_rss(self.assoc_lst, result[2], self.time_assoc_lst,
self.disso_lst, result[3], self.time_disso_lst)
if best is None or rss < best[0]:
best = (rss, result, p0, low_bounds, high_bounds)
if best is None:
raise last_error
_, (fit, cov, fit_vals_assoc, fit_vals_disso), p0, low_bounds, high_bounds = best
self.signal_assoc_fit = fit_vals_assoc
self.signal_disso_fit = fit_vals_disso
fit = np.array(fit, dtype=float)
self.Kd1, self.k_off1, self.k_a2, self.k_d2 = fit[:4]
idx = 4
t0_vals = None
if not fixed_t0:
t0_vals = fit[idx:idx + n_unq_smax]
idx += n_unq_smax
self.Smax = fit[idx:]
rows = len(self.Smax)
df_fit = pd.DataFrame({
'Kd1 [µM]': [self.Kd1] * rows,
'k_off1 [1/s]': [self.k_off1] * rows,
'k_a2 [1/(signal·s)]': [self.k_a2] * rows,
'k_d2 [1/s]': [self.k_d2] * rows,
'Rmax': self.Smax,
})
df_fit['(Derived) k_on1 [1/µM/s]'] = df_fit['k_off1 [1/s]'] / df_fit['Kd1 [µM]']
df_fit['(Derived) Kd2 [signal]'] = df_fit['k_d2 [1/s]'] / df_fit['k_a2 [1/(signal·s)]']
with np.errstate(divide='ignore', invalid='ignore'):
rel_error = np.sqrt(np.diag(cov)) / fit * 100
df_error = pd.DataFrame({
'Kd1 [µM]': [rel_error[0]] * rows,
'k_off1 [1/s]': [rel_error[1]] * rows,
'k_a2 [1/(signal·s)]': [rel_error[2]] * rows,
'k_d2 [1/s]': [rel_error[3]] * rows,
'Rmax': rel_error[idx:],
})
if not fixed_t0:
t0_err = rel_error[4:4 + n_unq_smax]
if shared_smax:
df_fit['t0'], df_error['t0'] = t0_vals, t0_err
else:
df_fit['t0'] = expand_parameter_list(t0_vals, self.smax_id)
df_error['t0'] = expand_parameter_list(t0_err, self.smax_id)
self.fit_params_kinetics = df_fit
self.fit_params_kinetics_error = df_error
self._add_concentrations(per_trace=not shared_smax)
self.params = fit
self.p0 = p0
self.low_bounds = low_bounds
self.high_bounds = high_bounds
labels = ['Kd1 [µM]', 'k_off1 [1/s]', 'k_a2 [1/(signal·s)]', 'k_d2 [1/s]']
labels += [] if fixed_t0 else self._group_labels('t0', n_unq_smax)
self._store_correlation(cov, labels + self._amplitude_labels('Rmax', shared_smax))
self.shared_smax = shared_smax
self.fixed_t0 = fixed_t0
if calc_loo:
self.calc_leave_one_out_errors()
return None
[docs]
@update_fit_result
def bivalent_analyte_assoc_and_disso_loo(self):
"""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).
"""
# This function is AI generated.
names = ['Kd1', 'k_off1', 'k_a2', 'k_d2']
columns = ['Kd1 [µM]', 'k_off1 [1/s]', 'k_a2 [1/(signal·s)]', 'k_d2 [1/s]']
estimates = {name: [] for name in names}
state_refits = _loo_state_refit_indices(self.time_assoc_lst, self.time_disso_lst)
for i in range(len(self.assoc_lst)):
temp_time_assoc_lst = remove_at(copy.deepcopy(self.time_assoc_lst), i)
temp_time_disso_lst = remove_at(copy.deepcopy(self.time_disso_lst), i)
temp_p0, temp_low_bounds, temp_high_bounds, temp_smax_idx, _ = _leave_one_out_parameters(
self.params, self.low_bounds, self.high_bounds, self.smax_id, i,
shared_smax=self.shared_smax, n_global=4,
group_blocks=(1,) * (not self.fixed_t0), response_width=1)
try:
fit_loo, _, _, _ = fit_bivalent_analyte_assoc_and_disso(
remove_at(copy.deepcopy(self.assoc_lst), i), temp_time_assoc_lst,
remove_at(copy.deepcopy(self.lig_conc_lst), i),
remove_at(copy.deepcopy(self.disso_lst), i), temp_time_disso_lst,
temp_p0, temp_low_bounds, temp_high_bounds,
smax_idx=temp_smax_idx, shared_smax=self.shared_smax, fixed_t0=self.fixed_t0,
fit_initial_state_at=i if i in state_refits else None,
**self._fit_masks(temp_time_assoc_lst, temp_time_disso_lst))
except Exception:
continue
for name, value in zip(names, fit_loo[:4]):
estimates[name].append(value)
df_fit_loo = {}
for name, column in zip(names, columns):
values = estimates[name]
setattr(self, f'{name}_loo', values)
setattr(self, f'{name}_loo_mean', np.mean(values))
setattr(self, f'{name}_loo_std', np.std(values))
df_fit_loo[column] = [f'{np.mean(values):.2e} ± {np.std(values):.2e}']
self.df_fit_loo = pd.DataFrame(df_fit_loo)
return None
[docs]
@update_fit_result
def calculate_ci95(self, shared_smax=None, fixed_t0=None, fit_ktr=None):
"""
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
-------
None
Updates the fit_params_kinetics_ci95 attribute with a DataFrame containing
the 95% confidence intervals for Kd and k_off.
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.
"""
# Edited with AI assistance: use the settings of the fit instead of the caller's.
fit_settings = {'shared_smax': getattr(self, 'shared_smax', None),
'fixed_t0': getattr(self, 'fixed_t0', None),
'fit_ktr': getattr(self, 'fit_ktr', None)}
given = {'shared_smax': shared_smax, 'fixed_t0': fixed_t0, 'fit_ktr': fit_ktr}
for name, value in given.items():
if value is not None and fit_settings[name] is not None and value != fit_settings[name]:
raise ValueError(
f"{name}={value} differs from the fit, which used {name}={fit_settings[name]}. "
f"Leave it out to use the setting of the fit.")
# Only the one-site association and dissociation fit is supported. Other
# models have other parameters, and the mass transport case is not done.
if getattr(self, 'model', None) != "one_site_association_and_dissociation" or fit_settings['fit_ktr']:
self.fit_params_kinetics_ci95 = pd.DataFrame()
return None
shared_smax = fit_settings['shared_smax']
fixed_t0 = fit_settings['fixed_t0']
try:
# Compute asymmetrical 95% confidence intervals
if not fit_ktr:
exp_signal_concat = concat_signal_lst(self.assoc_lst+self.disso_lst)
fit_signal_concat = concat_signal_lst(self.signal_assoc_fit+self.signal_disso_fit)
# Edited with AI assistance: only the points to fit count (trim_time)
masks = self._fit_masks(self.time_assoc_lst, self.time_disso_lst)
if self.trim_time:
keep = np.concatenate(masks['assoc_mask_lst'] + masks['disso_mask_lst'])
exp_signal_concat = exp_signal_concat[keep]
fit_signal_concat = fit_signal_concat[keep]
n = len(exp_signal_concat)
p = len(self.p0)
rss_desired = get_desired_rss(exp_signal_concat,
fit_signal_concat,
n, p)
Kd_min, Kd_max = one_site_assoc_and_disso_asymmetric_ci95(
self.Kd,rss_desired,
self.assoc_lst,self.time_assoc_lst,
self.lig_conc_lst,
self.disso_lst,self.time_disso_lst,
self.p0[1:],self.low_bounds[1:],self.high_bounds[1:],
self.smax_id,shared_smax=shared_smax,fixed_t0=fixed_t0,**masks)
p0 = self.p0[:1] + self.p0[2:]
low_bounds = self.low_bounds[:1] + self.low_bounds[2:]
high_bounds = self.high_bounds[:1] + self.high_bounds[2:]
koff_min, koff_max = one_site_assoc_and_disso_asymmetric_ci95_koff(
self.k_off,rss_desired,
self.assoc_lst,self.time_assoc_lst,
self.lig_conc_lst,
self.disso_lst,self.time_disso_lst,
p0,low_bounds,high_bounds,
self.smax_id,shared_smax=shared_smax,fixed_t0=fixed_t0,**masks)
# Convert ci95_Kd and ci95_koff to a nice Table
header = ['Parameter','95% CI lower','95% CI upper']
row1 = ['Kd [µM]',Kd_min,Kd_max]
row2 = ['k_off [1/s]',koff_min,koff_max]
df = pd.DataFrame([row1,row2],columns=header)
self.fit_params_kinetics_ci95 = df
except:
# Generate an empty dataframe if the procedure did not work
self.fit_params_kinetics_ci95 = pd.DataFrame()
return None
[docs]
@store_fit_result('one_site_if_assoc_and_disso', fit_signal_ratio='one_site_if_variable_signal')
def fit_one_site_if_assoc_and_disso(self, shared_smax=True, calc_loo=False,
fit_signal_ratio=False,
signal_ratio_bounds=(1e-1, 1e1)):
"""
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).
Returns
-------
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
"""
# This function contains AI-generated changes (PR #19, PR #21).
# Fit first a model without induced-fit
self.fit_one_site_assoc_and_disso(shared_smax=shared_smax)
self.model = "one_site_if_assoc_and_disso"
# Get the initial parameters from the single site fit
p0 = self.p0
low_bounds = self.low_bounds
high_bounds = self.high_bounds
# Find kon from Kd (1st fitted param) and koff (2nd fitted param)
kon = p0[1] / p0[0]
p0[0] = kon
low_bounds[0] = kon / 1e3
high_bounds[0] = kon * 1e3
# We need to find good initial guesses for the kc and krev parameters
kc_init = np.logspace(-4, 1, 6)
k_rev_init = kc_init
# Build combinations as numpy array, filter kc >= krev/100
combinations = np.array(list(itertools.product(kc_init, k_rev_init)))
mask = combinations[:, 0] >= combinations[:, 1] / 100
combinations = combinations[mask]
grid_results = [] # (rss, kc, krev, params) of each grid point that could be fitted
# We create a subsample of the time points to speed up the fitting for the initial guess
time_assoc_lst_subsampled = [subset_data(t) for t in self.time_assoc_lst]
time_disso_lst_subsampled = [subset_data(t) for t in self.time_disso_lst]
assoc_lst_subsampled = [subset_data(y) for y in self.assoc_lst]
disso_lst_subsampled = [subset_data(y) for y in self.disso_lst]
# Loop through each combination of kc and krev
# Apply fit_induced_fit_sites_assoc_and_disso with fixed kon2 and koff2 (corresponding to kc and krev)
for kc, krev in combinations:
try:
params, _, fit_vals_assoc, fit_vals_disso = fit_induced_fit_sites_assoc_and_disso(
assoc_lst_subsampled,time_assoc_lst_subsampled,self.lig_conc_lst,
disso_lst_subsampled,time_disso_lst_subsampled,
p0,low_bounds,high_bounds,
smax_idx=self.smax_id,
shared_smax=shared_smax,
fixed_t0=True,
fixed_kon2 = True, # k_on2 refers here to the forward rate constant of the induced fit
kon2_value=kc,
fixed_koff2 = True, # k_off2 refers here to the reverse rate constant of the induced fit
koff2_value=krev,
**self._fit_masks(time_assoc_lst_subsampled, time_disso_lst_subsampled)
)
# Calculate the residuals for the signals - use the subsampled data
rss = self._grid_rss(assoc_lst_subsampled, fit_vals_assoc, time_assoc_lst_subsampled,
disso_lst_subsampled, fit_vals_disso, time_disso_lst_subsampled)
grid_results.append((rss, kc, krev, params))
except:
# If the fit fails, just continue to the next combination
continue
# Edited with AI assistance and reviewed by a human in PR #21: when kc and krev
# are fast, the curves only fix kon and an apparent koff, and the fit creeps
# along a flat valley of equally good solutions. It gets four times the
# default number of evaluations to stop, and if it still fails it starts
# again from the next-best grid points.
grid_results.sort(key=lambda result: result[0])
factor = 1e3 # Factor to scale the bounds for kc and krev
n_starts = 3 # Grid points tried, best first, until one fit succeeds
best = None
last_error = None
for _, best_kc, best_krev, best_params in grid_results[:n_starts]:
# Insert the kc and krev parameters into the p0, low_bounds and high_bounds lists
start = list(p0)
start_low = list(low_bounds)
start_high = list(high_bounds)
start.insert(2, best_kc)
start_low.insert(2, best_kc/factor)
start_high.insert(2, best_kc*factor)
start.insert(3, best_krev)
start_low.insert(3, best_krev/factor)
start_high.insert(3, best_krev*factor)
if fit_signal_ratio:
# Start from equal signals for ALint and AL
start.insert(4, float(np.clip(1.0, *signal_ratio_bounds)))
start_low.insert(4, signal_ratio_bounds[0])
start_high.insert(4, signal_ratio_bounds[1])
# The Smax bounds come from the one-to-one fit, which sees the total
# plateau, about Smax * ratio. Smax is now the signal of a surface full
# of ALint, so widen its bounds by the allowed ratios. Otherwise, for a
# ratio above about 3.5 the true Smax is below the lower bound and the
# fit stops on it with wrong rates.
for j in range(5, len(start)):
start_low[j] /= max(1.0, signal_ratio_bounds[1])
start_high[j] *= max(1.0, 1.0 / signal_ratio_bounds[0])
# Replace the kon and koff with the best parameters
start[0] = best_params[0] # kon
start[1] = best_params[1] # koff
start_low[0] = best_params[0] / factor # kon
start_high[0] = best_params[0] * factor
start_low[1] = best_params[1] / factor # koff
start_high[1] = best_params[1] * factor
try:
result = fit_induced_fit_sites_assoc_and_disso(
self.assoc_lst,self.time_assoc_lst,self.lig_conc_lst,
self.disso_lst,self.time_disso_lst,
start,start_low,start_high,
smax_idx=self.smax_id,
shared_smax=shared_smax,
fixed_t0=True,
max_nfev=400 * len(start),
fit_signal_ratio=fit_signal_ratio,
**self._fit_masks(self.time_assoc_lst, self.time_disso_lst))
except RuntimeError as error:
last_error = error
continue
best = (result, start, start_low, start_high)
break
if best is None:
raise last_error if last_error is not None else RuntimeError(
"The induced-fit model could not be fitted from any starting point.")
(fit, cov, fit_vals_assoc, fit_vals_disso), p0, low_bounds, high_bounds = best
self.signal_assoc_fit = fit_vals_assoc
self.signal_disso_fit = fit_vals_disso
n_global = 4 + bool(fit_signal_ratio)
self.k_on, self.k_off, self.k_c, self.k_rev = fit[:4]
self.signal_ratio = fit[4] if fit_signal_ratio else 1.0
self.Smax = list(fit[n_global:])
# Create a dataframe with the fitted parameters
fit_columns = {'k_on [1/(s*µM)]': self.k_on,
'k_off [1/s]': self.k_off,
'k_c [1/s]': self.k_c,
'k_rev [1/s]': self.k_rev}
# Relative errors (%) of this fit, replacing the table left by the
# one-to-one fit used for the starting values (AI generated, PR #19).
with np.errstate(divide='ignore', invalid='ignore'):
rel_error = np.sqrt(np.diag(cov)) / np.abs(fit) * 100
error_columns = {'k_on [1/(s*µM)]': rel_error[0],
'k_off [1/s]': rel_error[1],
'k_c [1/s]': rel_error[2],
'k_rev [1/s]': rel_error[3]}
# A is the analyte and L the immobilised ligand: ALint is the
# intermediate complex and AL the induced complex.
if fit_signal_ratio:
fit_columns['Signal ratio (AL/ALint)'] = self.signal_ratio
error_columns['Signal ratio (AL/ALint)'] = rel_error[4]
fit_columns['Smax'] = self.Smax
error_columns['Smax'] = rel_error[n_global:]
df_fit = pd.DataFrame(fit_columns)
df_error = pd.DataFrame(error_columns)
self.fit_params_kinetics = df_fit
self.fit_params_kinetics_error = df_error
self._add_concentrations(per_trace=not shared_smax)
self.params = fit
self.p0 = p0
global_labels = ['k_on [1/(s*µM)]', 'k_off [1/s]', 'k_c [1/s]', 'k_rev [1/s]']
if fit_signal_ratio:
global_labels.append('Signal ratio (AL/ALint)')
self._store_correlation(
cov, global_labels + self._amplitude_labels('Smax', shared_smax))
self.low_bounds = low_bounds
self.high_bounds = high_bounds
self.shared_smax = shared_smax
self.fit_signal_ratio = fit_signal_ratio
if calc_loo:
self.calc_leave_one_out_errors()
return None
[docs]
@update_fit_result
def one_site_if_assoc_and_disso_loo(self):
"""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.
"""
# This function contains AI-generated changes (PR #15).
shared_smax = self.shared_smax
fit_signal_ratio = getattr(self, 'fit_signal_ratio', False)
n_global = 4 + bool(fit_signal_ratio)
k_on_loo = []
k_off_loo = []
k_c_loo = []
k_rev_loo = []
signal_ratio_loo = []
n_fits_loo_ok = 0
n_fits_loo_fail = 0
state_refits = _loo_state_refit_indices(self.time_assoc_lst, self.time_disso_lst)
for i in range(len(self.assoc_lst)):
temp_assoc_lst = copy.deepcopy(self.assoc_lst)
temp_time_assoc_lst = copy.deepcopy(self.time_assoc_lst)
temp_disso_lst = copy.deepcopy(self.disso_lst)
temp_time_disso_lst = copy.deepcopy(self.time_disso_lst)
# Remove element ii from replicate i
temp_assoc_lst = remove_at(temp_assoc_lst, i)
temp_time_assoc_lst = remove_at(temp_time_assoc_lst, i)
temp_disso_lst = remove_at(temp_disso_lst, i)
temp_time_disso_lst = remove_at(temp_time_disso_lst, i)
temp_lig_conc_lst = copy.deepcopy(self.lig_conc_lst)
temp_lig_conc_lst = remove_at(temp_lig_conc_lst, i)
temp_p0, temp_low_bounds, temp_high_bounds, temp_smax_idx, _ = (
_leave_one_out_parameters(
self.params, self.low_bounds, self.high_bounds, self.smax_id, i,
shared_smax=shared_smax, n_global=n_global,
group_blocks=(), response_width=1,
)
)
kwargs_loo = {
'fit_signal_ratio' : fit_signal_ratio,
'assoc_signal_lst' : temp_assoc_lst,
'assoc_time_lst' : temp_time_assoc_lst,
'analyte_conc_lst' : temp_lig_conc_lst,
'disso_signal_lst' : temp_disso_lst,
'disso_time_lst' : temp_time_disso_lst,
'initial_parameters' : temp_p0,
'low_bounds' : temp_low_bounds,
'high_bounds' : temp_high_bounds,
'shared_smax' : shared_smax,
'smax_idx' : temp_smax_idx,
'fixed_t0' : True,
'fit_initial_state_at': i if i in state_refits else None,
**self._fit_masks(temp_time_assoc_lst, temp_time_disso_lst)
}
try:
fit_loo, _, _, _ = fit_induced_fit_sites_assoc_and_disso(**kwargs_loo)
k_on, k_off, k_c, k_rev = fit_loo[:4]
k_on_loo.append(k_on)
k_off_loo.append(k_off)
k_c_loo.append(k_c)
k_rev_loo.append(k_rev)
if fit_signal_ratio:
signal_ratio_loo.append(fit_loo[4])
n_fits_loo_ok += 1
except Exception:
n_fits_loo_fail += 1
self.k_on_loo = k_on_loo
self.k_off_loo = k_off_loo
self.k_c_loo = k_c_loo
self.k_rev_loo = k_rev_loo
self.k_on_loo_mean = np.mean(k_on_loo)
self.k_off_loo_mean = np.mean(k_off_loo)
self.k_c_loo_mean = np.mean(k_c_loo)
self.k_rev_loo_mean = np.mean(k_rev_loo)
self.k_on_loo_std = np.std(k_on_loo)
self.k_off_loo_std = np.std(k_off_loo)
self.k_c_loo_std = np.std(k_c_loo)
self.k_rev_loo_std = np.std(k_rev_loo)
df_fit_loo = pd.DataFrame({
'k_on [1/(s*µM)]': [f'{self.k_on_loo_mean:.2e} ± {self.k_on_loo_std:.2e}'],
'k_off [1/s]': [f'{self.k_off_loo_mean:.2e} ± {self.k_off_loo_std:.2e}'],
'k_c [1/s]': [f'{self.k_c_loo_mean:.2e} ± {self.k_c_loo_std:.2e}'],
'k_rev [1/s]': [f'{self.k_rev_loo_mean:.2e} ± {self.k_rev_loo_std:.2e}']
})
if fit_signal_ratio:
self.signal_ratio_loo = signal_ratio_loo
self.signal_ratio_loo_mean = np.mean(signal_ratio_loo)
self.signal_ratio_loo_std = np.std(signal_ratio_loo)
df_fit_loo['Signal ratio (AL/ALint)'] = [
f'{self.signal_ratio_loo_mean:.2e} ± {self.signal_ratio_loo_std:.2e}']
self.df_fit_loo = df_fit_loo
return None
[docs]
def calc_leave_one_out_errors(self):
"""Calculate leave-one-out estimates for the currently fitted model."""
loo_methods = {
"one_site_association": self.one_site_association_loo,
"one_site_dissociation": self.one_site_dissociation_loo,
"one_site_association_and_dissociation": self.one_site_assoc_and_disso_loo,
"two_site_association_and_dissociation": self.two_site_assoc_and_disso_loo,
"two_site_heterogeneous_ligand_association_and_dissociation": (
self.two_site_heterogeneous_ligand_assoc_and_disso_loo
),
"one_site_if_assoc_and_disso": self.one_site_if_assoc_and_disso_loo,
"bivalent_analyte_association_and_dissociation": self.bivalent_analyte_assoc_and_disso_loo,
}
model = getattr(self, "model", None)
if model not in loo_methods:
raise ValueError(f"No LOO calculation is available for model: {model!r}")
return loo_methods[model]()
[docs]
def create_export_df(self,type='raw'):
"""
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
-------
pd.DataFrame
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.
"""
df_list = []
for i, name in enumerate(self.names):
time_assoc = self.time_assoc_lst[i]
if type == 'raw':
signal_assoc = self.assoc_lst[i]
else:
signal_assoc = self.signal_assoc_fit[i]
lig_conc = self.lig_conc_lst[i]
dic = {
'Time': time_assoc,
'Signal': signal_assoc,
'Analyte_concentration_micromolar': lig_conc,
'Type': 'Association',
'ID': name
}
df = pd.DataFrame(dic)
df_list.append(df)
if self.disso_lst is not None and self.time_disso_lst is not None:
time_disso = self.time_disso_lst[i]
signal_disso = None
if type == 'raw':
signal_disso = self.disso_lst[i]
else:
if self.signal_disso_fit is not None:
signal_disso = self.signal_disso_fit[i]
# Append only if we have signal_disso
if signal_disso is not None:
dic = {
'Time': time_disso,
'Signal': signal_disso,
'Analyte_concentration_micromolar': 0,
'Type': 'Dissociation',
'ID': name
}
df = pd.DataFrame(dic)
df_list.append(df)
df = pd.concat(df_list, ignore_index=True)
return df