{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# SPARCED Model Initialization\n", "\n", "The model initialization procedure calibrates the parameter values (i) to make sure the tranlation rate constants induce a steady-state and (ii) to sustain certain phenotypic observations, such as serum-starved cells should not enter cell cycle or apoptosis. \n", "\n", "Each new cell line or cellular context (tumor microenvironement) should follow a custom `Initilization` procedure, based on user choices. So, below code should be handled as a guide on how to do this. \n", "\n", "Here, we made sure this script reproduces Bouhaddou2018 results. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1) Pre-processing and model preparation\n", "\n", "Below are some adjustments and manual settings to match earlier model results." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Import packages\n", "import pandas as pd\n", "import numpy as np\n", "import re\n", "import libsbml\n", "import os\n", "import sys\n", "import importlib\n", "import amici\n", "import amici.plotting" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Load the model file, input files, and initialization specs\n", "\n", "To start running `Initilization`, the user should first run `createModel` notebook and define the model SBML file name below. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#%% load model and input files\n", "sbml_file = \"SPARCED.xml\"\n", "model_name= sbml_file[0:-4]\n", "model_output_dir = model_name\n", "sys.path.insert(0, os.path.join(model_output_dir))\n", "model_module = importlib.import_module(model_name)\n", "model = model_module.getModel()\n", "\n", "sbml_reader = libsbml.SBMLReader()\n", "sbml_doc = sbml_reader.readSBML(sbml_file)\n", "sbml_model = sbml_doc.getModel()\n", "params_model = []\n", "[params_model.append(pr.getId()) for pr in sbml_model.getListOfParameters()]\n", "\n", "# Ratelaws input file\n", "ratelaw_sheet = np.array([np.array(line.strip().split(\"\\t\")) for line in open('Ratelaws.txt')])\n", "ratelaw_data = np.array([line[1:] for line in ratelaw_sheet[1:]])\n", "\n", "# OmicsData input file\n", "gene_params = pd.read_csv('OmicsData.txt', sep='\\t', index_col=0, header=0)\n", "model_genes = gene_params.index\n", "mExp_mpc = gene_params['Exp RNA'].copy()\n", "\n", "# Species input file\n", "ICf = pd.read_csv('Species.txt',header=0,index_col=0,sep='\\t')\n", "\n", "# Compartments input file\n", "cell_params = pd.read_csv('Compartments.txt', header=0, index_col=0, sep='\\t')\n", "Vc = cell_params.loc['Cytoplasm','volume']\n", "Vn = cell_params.loc['Nucleus','volume']\n", "Vm = cell_params.loc['Mitochondrion','volume']\n", "Ve = cell_params.loc['Extracellular','volume']\n", "volumeofcell = Vc + Vn" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Define and calculate translation related parameters\n", "\n", "Here, we define and calculate protein degradation rate constants. For definition of these parameter choices, please refer to Bouhaddou2018 paper." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# pre-process\n", "gene_params['kTLd'] = np.log(2)/gene_params['Protein_half_life_lit_h']/3600\n", "gene_params['kTLd'][np.isnan(gene_params['kTLd'].values)] = np.log(2)/gene_params['Protein_half_life_Schwan_h'][np.isnan(gene_params['kTLd'].values)]/3600\n", "gene_params['kTLd'][np.isnan(gene_params['kTLd'].values)] = 0\n", "gene_params['kTL_nat_cells'] = gene_params['Exp Protein']*gene_params['kTLd']/gene_params['Exp RNA']\n", "gene_params['kTL_nat_cells'][np.isnan(gene_params['kTL_nat_cells']) | np.isinf(gene_params['kTL_nat_cells'])] = 0\n", "gene_params['kTL_nat'] = gene_params['kTL_nat_cells']\n", "gene_params['kTL_nat'][np.where(gene_params['kTL_nat']==0)[0]] = gene_params['kTLnatLit_s'][np.where(gene_params['kTL_nat']==0)[0]]\n", "gene_params['kTL_nat'][np.where(gene_params['kTL_nat']==0)[0]] = gene_params['kTLnatSchwan_s'][np.where(gene_params['kTL_nat']==0)[0]]\n", "gene_params['kTL_nat'][np.array([list(model_genes).index(x) for x in ['CCND1', 'CCND2', 'CCND3']])] = gene_params['kTL_nat'][np.array([list(model_genes).index(x) for x in ['CCND1', 'CCND2', 'CCND3']])].values * 5\n", "\n", "xp_mpc = gene_params['kTL_nat']*mExp_mpc/gene_params['kTLd']\n", "xp_mpc[np.isnan(xp_mpc)] = 0" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Read-in Initializer.txt file\n", "\n", "The details of what to modify or keep constant are defined in the `Initializer.txt` input file. We will use different columns from that file at different stages of the `Initialization` procedure. For definitions of each column, please refer to out paper." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Read-in genes with modified mRNA levels\n", "Step1_mrna = pd.read_csv('Initializer.txt',sep='\\t',squeeze=True,usecols=['Step1_mrna','Step1_mrna_mpc'],index_col='Step1_mrna')\n", "Step1_mrna = Step1_mrna[Step1_mrna.index.notnull()]\n", "for gene_symbol in Step1_mrna.index:\n", " gene_params.loc[gene_symbol,'Exp RNA'] = Step1_mrna[gene_symbol]\n", "\n", "# Finding reactions\n", "reactions_all = [ratelaw_sheet[i][0] for i in range(len(ratelaw_sheet))]\n", "vTL_pattern = re.compile(\"vTL\\d+\")\n", "# Find translation ratelaws from the input\n", "reactions_vTL = list(filter(vTL_pattern.match, reactions_all))\n", "params_all = pd.read_csv('ParamsAll.txt', header=0, index_col=0, sep='\\t') # List of all model parameters, output file from createModel notebook\n", "def params_getid(rxn,idx):\n", " param_id = str(params_all.index[np.logical_and(params_all['rxn'].values==rxn, params_all['idx'].values==int(idx))][0])\n", " return param_id\n", "\n", "# Find the piece of stoichiometric matrix with translation ratelaws only\n", "numberofgenes = len(model_genes)\n", "S_PARCDL = pd.read_csv('StoicMat.txt', header=0, index_col=0, sep='\\t')\n", "S_TL = S_PARCDL.loc[:,S_PARCDL.columns.isin(reactions_vTL)]\n", "\n", "# Read-in observables of the model - from the createModel notebook output\n", "ObsMat = pd.read_csv('Observables.txt', header=0, index_col=0, sep='\\t')\n", "NumObs = len(ObsMat.columns)\n", "\n", "kTL_id = []\n", "kTL_default = []\n", "k50E_id = []\n", "k50E_values = []\n", "kTL_genes = []\n", "for rowNum, ratelaw in enumerate(ratelaw_data):\n", " if \"kTL\" in str(ratelaw[1]):\n", " kTL_i = \"k\"+str(rowNum+1)+\"_1\"\n", " kTL_id.append(kTL_i)\n", " kTL_gene = re.search(r'm_\\w+', ratelaw[1]).group()[2:]\n", " kTL_genes.append(kTL_gene)\n", " params_i = np.array(list(ratelaw[2:]))\n", " params_i = np.array([float(params_i[k]) for k in range(len(params_i))])\n", " params_i = params_i[~np.isnan(params_i)]\n", " kTL_value = params_i[0]\n", " kTL_default.append(float(kTL_value))\n", " a = len(params_i)\n", " if \"EIF4E\" in str(ratelaw[1]):\n", " if 'MDM2pro' in str(ratelaw[1]):\n", " k50E_id_i = \"k\"+str(rowNum+1)+\"_3\"\n", " elif 'CCND1' in str(ratelaw[1]) or 'CCND2' in str(ratelaw[1]) or 'CCND3' in str(ratelaw[1]):\n", " k50E_id_i = \"k\"+str(rowNum+1)+\"_5\"\n", " else:\n", " k50E_id_i = \"k\"+str(rowNum+1)+\"_2\"\n", " k50E_id.append(k50E_id_i)\n", " k50E_value_i = params_i[-1]\n", " k50E_values.append(k50E_value_i) \n", " \n", "# Define/read-in observables to exclude from fitting \n", "obs2exclude = pd.read_csv('Initializer.txt', sep='\\t', usecols=['Step1_obs_excl'])\n", "obs2exclude = obs2exclude.values[obs2exclude.notnull()]\n", "\n", "kTLest = gene_params['kTL_nat'].values # Initial values for the kTL parameters\n", "\n", "mrna_id = []\n", "mrna_filter = filter(lambda a: a.startswith('m_'), list(ICf.index))\n", "for m in mrna_filter:\n", " mrna_id.append(m)\n", "\n", "species_sheet = np.array([np.array(line.strip().split(\"\\t\")) for line in open('Species.txt', encoding='latin-1')])\n", "compartment_sheet = np.array([np.array(line.strip().split(\"\\t\")) for line in open('Compartments.txt')])\n", "species_names = np.array([species_sheet[i][0] for i in range(1,len(species_sheet))])\n", "# Volumes array of the species in the model\n", "VxPARCDL = np.array([species_sheet[i][1] for i in range(1,len(species_sheet))])\n", "VxPARCDL = [float(compartment_sheet[compartment_sheet[:,0]==VxPARCDL[i],1][0]) for i in range(len(VxPARCDL))]\n", "VxPARCDL = pd.Series(VxPARCDL, index=species_names)\n", "\n", "VxTL = np.ones(numberofgenes)*Vc\n", "for i in range(np.shape(S_TL)[1]):\n", " if len(np.nonzero(S_TL.values[:,i])[0]) != 0:\n", " obs_ind = int(np.nonzero(S_TL.values[:,i])[0])\n", " VxTL[i] = VxPARCDL[obs_ind]\n", "\n", "# protein levels in nanomolar \n", "pExp_nM = xp_mpc*1e9/(VxTL*6.023e23)\n", "# model species concentrations\n", "x0PARCDL = np.matmul(S_TL.values,pExp_nM)\n", "x0PARCDL = pd.Series(x0PARCDL)\n", "x0PARCDL.index = S_TL.index\n", "\n", "mpc2nmcf_Vc=1E9/(Vc*6.023E+23)\n", "mExp_nM=mExp_mpc*mpc2nmcf_Vc\n", "mExp_nM = pd.Series(data=mExp_nM.values,index=mrna_id) # mRNA experimental levels in nanomolar\n", "for m in mrna_id:\n", " x0PARCDL[m] = mExp_nM[m]\n", "\n", "# Read-in species-species concentration pairs \n", "Step1sp = pd.read_csv('Initializer.txt',sep='\\t',squeeze=True,usecols=['Step1_sp','Step1_val'],index_col='Step1_sp')\n", "Step1sp = Step1sp[Step1sp.index.notnull()]\n", "for sp in Step1sp.index:\n", " x0PARCDL[sp] = Step1sp[sp]\n", "\n", "k50E_default = max(k50E_values)\n", "x0 = x0PARCDL" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Define functions to handle model observables and to find corresponding species indices" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def get_observables(xout, VxPARCDL, Vc): \n", " Obs = [] \n", " Vr = VxPARCDL/Vc\n", " for i in range(np.shape(ObsMat)[1]):\n", " Obs_i = np.sum(ObsMat.values[:,i]*xout*Vr.flatten())\n", " Obs.append(Obs_i)\n", " Obs = [0 if i <= 1e-6 else i for i in Obs]\n", " Obs = np.array(Obs) \n", " return Obs\n", "obs0 = get_observables(x0.values, VxPARCDL.values, Vc)\n", "kTL_mod = np.ones(numberofgenes)*0.25\n", "def obs2gene (obs_name):\n", " gene = model_genes[np.nonzero(np.matmul(ObsMat.values[:,list(ObsMat.columns).index(obs_name)],S_TL.values))[0]]\n", " return gene\n", "def obs2gene_i (obs_name):\n", " gene_i = np.nonzero(np.matmul(ObsMat.values[:,list(ObsMat.columns).index(obs_name)],S_TL.values))[0]\n", " return gene_i\n", "for m in obs2exclude:\n", " kTL_mod[obs2gene_i(m)] = 1.0\n", " kTLest[obs2gene_i(m)]\n", " for k in range(len(obs2gene_i(m))):\n", " kTLest[obs2gene_i(m)[k]] = model.getFixedParameterById(np.array(kTL_id)[obs2gene_i(m)][k])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Read-in parameters with modified values" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "Step1_par = pd.read_csv('Initializer.txt',sep='\\t',squeeze=True,usecols=['Step1_par_rxn','Step1_par_idx','Step1_par_val'])\n", "Step1_par = Step1_par[Step1_par.Step1_par_rxn.notnull()]\n", "Step1_par_ids = [str(params_all.index[np.logical_and(params_all['rxn'].values==Step1_par.Step1_par_rxn[i], params_all['idx'].values==int(Step1_par.Step1_par_idx[i]))][0]) for i in range(len(Step1_par.Step1_par_rxn))]\n", "[model.setFixedParameterById(Step1_par_ids[i],Step1_par.Step1_par_val[i]) for i in range(len(Step1_par_ids))]\n", "[model.setFixedParameterById(k50E_id[k],0) for k in range(len(k50E_id))]\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Cyclin D\n", "All three Cyclin D gene isoforms produce the same Cyclin D (Cd) protein species. Cyclin D controls the first entry point\n", "to the cell cycle and its value is controled during Initialization procedure." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "Cd_genes = np.array([list(model_genes).index(x) for x in ['CCND1', 'CCND2', 'CCND3']])\n", "Step1_Cd = pd.read_csv('Initializer.txt',sep='\\t',squeeze=True,usecols=['Step1_Cd_par','Step1_Cd_val'],index_col='Step1_Cd_par')\n", "Step1_Cd = Step1_Cd[Step1_Cd.index.notnull()]\n", "kC173 = Step1_Cd['kC173']\n", "kTL10_12 = kC173/sum(mExp_nM[Cd_genes]) \n", "[model.setFixedParameterById(Cd_kTL,kTL10_12) for Cd_kTL in np.array(kTL_id)[Cd_genes]]\n", "kTLest[Cd_genes] = kTL10_12\n", "kTL_initial = kTLest" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Model instance\n", "Set model initial conditions" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Set simulation time in seconds\n", "ts = 1000*3600 \n", "model.setTimepoints(np.linspace(0,ts,1000))\n", "\n", "# set species initial conditions\n", "x0 = x0PARCDL\n", "model.setInitialStates(x0.values)\n", "\n", "# model solver instance\n", "solver = model.getSolver()\n", "solver.setMaxSteps = 1e10" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### The main function `kTLadjustwhile`\n", "\n", "This function is used multiple times during the Initialization procedure. It adjusts translation rate constnants and makes sure to reach steady-state values." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def kTLadjustwhile(model,solver,x0, obs0, kTL_id, kTLest, kTL_mod, k50E_id, k50E_values, ObsMat, S_TL, flagE):\n", " if flagE == 0:\n", " [model.setFixedParameterById(k50E_id[k],0) for k in range(len(k50E_id))]\n", " elif flagE == 1:\n", " [model.setFixedParameterById(k50E_id[k],k50E_values[k]) for k in range(len(k50E_id))]\n", " model.setInitialStates(x0.values)\n", " [model.setFixedParameterById(kTL_id[k],kTLest[k]) for k in range(len(kTL_id))]\n", " m = len(ObsMat.columns)\n", " margin = 0.001\n", " # Repeat until convergence\n", " while m!=0:\n", " rdata = amici.runAmiciSimulation(model,solver)\n", " obs1 = rdata['y'][-1]\n", " error_fe = (obs0 - obs1)/obs0\n", " kTLf_obs = np.ones(len(obs0))\n", " for i in range(len(error_fe)):\n", " if ObsMat.columns[i] in obs2exclude:\n", " kTLf_obs[i] = 1\n", " elif obs0[i] == 0:\n", " kTLf_obs[i] = 0 \n", " elif error_fe[i] > margin and ~np.isinf(error_fe[i]):\n", " kTLf_obs[i] = 1/(1-error_fe[i])\n", " elif error_fe[i] < -1 * margin and ~np.isinf(error_fe[i]):\n", " kTLf_obs[i] = 1/(1-error_fe[i])\n", " elif error_fe[i] > -1 * margin and error_fe[i] < margin:\n", " kTLf_obs[i] = 1\n", " kTLf = []\n", " for i in range(len(S_TL.columns)):\n", " a = np.nonzero(np.array(S_TL.iloc[:,i]))[0]\n", " if len(a) != 0:\n", " sp_ind = a[0]\n", " obs_ind = np.nonzero(np.array(ObsMat.iloc[sp_ind,:]))[0][0]\n", " kTLf.append(kTLf_obs[obs_ind])\n", " else:\n", " kTLf.append(1)\n", " kTLf = pd.Series(kTLf)\n", " kTLf = kTLf.transform(lambda x: 1 if np.isinf(x) or np.isnan(x) else x)\n", " kTLf = np.array(kTLf)\n", " kTLest = kTLest*(1+(kTLf-1)*kTL_mod)\n", " [model.setFixedParameterById(kTL_id[k],kTLest[k]) for k in range(len(kTL_id))]\n", " obs_notmatched = ObsMat.columns[~((error_fe > -1*margin) & (error_fe < margin) | (obs0==0))]\n", " obs_notmatched = obs_notmatched[~np.isin(obs_notmatched,obs2exclude)]\n", " m = len(obs_notmatched)\n", " kTLnew = kTLest\n", " [model.setFixedParameterById(kTL_id[k], kTLnew[k]) for k in range(len(kTL_id))]\n", " rdata_new = amici.runAmiciSimulation(model,solver)\n", " x_new = rdata_new['x']\n", " x1 = pd.Series(data=rdata_new['x'][-1], index=ObsMat.index)\n", " x1[x1.values<1e-6] = 0.0\n", " flagA = 0\n", " apop_def = x0['PARP']*.5 # Apoptosis event definition: If [cPARP]>[PARP], the cell dies!\n", " parp_all = x_new[:,list(ObsMat.index).index('PARP')]\n", " if sum(parp_all < apop_def) != 0:\n", " flagA = 1 \n", " return kTLnew, rdata_new, x1, flagA" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Setting degredation rate constants" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "kTLd = gene_params['kTLd'] # Degradation rate constants\n", "kTLCd = np.zeros(len(ObsMat.columns))\n", "for i,obs in enumerate(ObsMat.columns):\n", " kTLCd[i] = sum(kTLd[obs2gene(obs).values]*xp_mpc[obs2gene(obs)].values/sum(xp_mpc[obs2gene(obs)].values)) \n", "kTLCd[np.isnan(kTLCd)] = 0\n", "\n", "# Read-in and exclude\n", "kTLCd2exclude = pd.read_csv('Initializer.txt',sep='\\t',squeeze=True,usecols=['Step1_sp_kTLCd'])\n", "kTLCd2exclude = kTLCd2exclude.values[pd.notnull(kTLCd2exclude.values)]\n", "for k in kTLCd2exclude:\n", " kTLCd[list(ObsMat.columns).index(k)] = 0\n", "\n", "# Find degradation ratelaws\n", "vXd_pattern = re.compile(\"v\\D+d\\d+\")\n", "reactions_vXd = list(filter(vXd_pattern.match, reactions_all))\n", "reactions_vTLCd = list(filter(lambda x: ('vTLCd' in x),reactions_vXd))\n", "reactions_vXd = list(filter(lambda x: ('vTLCd' not in x),reactions_vXd))\n", "\n", "# Find the piece of stoichiometric with degradation reactions\n", "S_Xd = S_PARCDL.loc[:,S_PARCDL.columns.isin(reactions_vXd)]\n", "\n", "# Degradation constants array\n", "kXd = np.zeros(np.shape(S_Xd)[1])\n", "for kXdi in range(len(kXd)):\n", " ProtInd = np.nonzero(S_Xd.iloc[:,kXdi].values==-1)[0][0]\n", " Obs2Include = np.nonzero(ObsMat.iloc[ProtInd,:].values)[0]\n", " if len(Obs2Include) != 0:\n", " kXd[kXdi] = max(kTLCd[Obs2Include])\n", "kXd = pd.Series(data=kXd,index=reactions_vXd)\n", "\n", "# Manually setting some of the parameters as done in the Bouhaddou2018 model\n", "kXdmod_1000 = ['Ractive']\n", "for sp in kXdmod_1000:\n", " p = S_Xd.columns[np.argwhere(S_Xd.loc[sp].values==-1)[0][0]]\n", " kXd[p] = kXd[p]*1000\n", "\n", "kXdmod_100 = ['C8','C3','C6','tBid','Baxactive']\n", "for sp in kXdmod_100:\n", " p = S_Xd.columns[np.argwhere(S_Xd.loc[sp].values==-1)[0][0]]\n", " kXd[p] = kXd[p]*100\n", "\n", "kXdmod_10 = ['pBIM','pBAD','pFOXO']\n", "for sp in kXdmod_10:\n", " p = S_Xd.columns[np.argwhere(S_Xd.loc[sp].values==-1)[0][0]]\n", " kXd[p] = kXd[p]*10\n", "\n", "# Read-in and exclude\n", "kXd2exclude = pd.read_csv('Initializer.txt',sep='\\t',squeeze=True,usecols=['Step1_sp_kXd'])\n", "kXd2exclude = kXd2exclude.values[pd.notnull(kXd2exclude.values)]\n", "kXd2remove = []\n", "for k in kXd2exclude:\n", " kXd2remove.append(S_Xd.columns[np.argwhere(S_Xd.loc[k].values == -1)[0][0]])\n", "kXd = kXd[~np.isin(kXd.index,kXd2remove)]\n", "\n", "# Set the above parameter values in the model instance\n", "for i in range(len(kXd)):\n", " model.setFixedParameterById(params_getid(reactions_vXd[i],0),kXd[i])\n", "for i in range(len(kTLCd)):\n", " model.setFixedParameterById(params_getid(reactions_vTLCd[i],0), kTLCd[i])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2) Start Initialization Steps" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Fixed EIF4E, no ribosome" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "kTLnew1, rdata_new, x1, flagA = kTLadjustwhile(model,solver,x0, obs0, kTL_id, kTLest, kTL_mod, k50E_id, k50E_values, ObsMat, S_TL, 0)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Dynamic EIF4E, no ribosome" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "kTLnew2, rdata_new, x2, flagA = kTLadjustwhile(model,solver,x1, obs0, kTL_id, kTLnew1, kTL_mod, k50E_id, k50E_values, ObsMat, S_TL, 1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Dynamic EIF4E, with ribosome back" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "Step3_par = pd.read_csv('Initializer.txt',sep='\\t',squeeze=True,usecols=['Step3_par_rxn','Step3_par_idx','Step3_par_val'])\n", "Step3_par = Step3_par[Step3_par.Step3_par_rxn.notnull()]\n", "Step3_par_ids = [params_getid(Step3_par.Step3_par_rxn[i],Step3_par.Step3_par_idx[i]) for i in range(len(Step3_par.Step3_par_rxn))]\n", "\n", "kbRi = float(Step3_par.Step3_par_val[np.logical_and(Step3_par.Step3_par_rxn=='vbR',Step3_par.Step3_par_idx==int(1))])\n", "kdR0 = float(Step3_par.Step3_par_val[np.logical_and(Step3_par.Step3_par_rxn=='vdR',Step3_par.Step3_par_idx==int(0))])\n", "nR = float(Step3_par.Step3_par_val[np.logical_and(Step3_par.Step3_par_rxn=='vbR',Step3_par.Step3_par_idx==int(2))])\n", "k50R = float(Step3_par.Step3_par_val[np.logical_and(Step3_par.Step3_par_rxn=='vbR',Step3_par.Step3_par_idx==int(3))])\n", " \n", "ps6ki = x0['pS6K']\n", "f1 = (ps6ki**nR)/(k50R**nR+ps6ki**nR)\n", "Rt = x0['Ribosome']\n", "kbR0 = Rt*kdR0 - kbRi*f1\n", "\n", "Step3_par.Step3_par_val[(Step3_par['Step3_par_rxn']=='vbR')&(Step3_par['Step3_par_idx']==0)] = kbR0\n", "[model.setFixedParameterById(Step3_par_ids[i],Step3_par.Step3_par_val[i]) for i in range(len(Step3_par_ids))]\n", "kTLnew3, rdata_new, x3, flagA = kTLadjustwhile(model,solver,x2, obs0, kTL_id, kTLnew2, kTL_mod, k50E_id, k50E_values, ObsMat, S_TL, 1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Adjust Cyclin D (Cd) and p21 levels" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "totalcyclinDfromdata = sum(pExp_nM[np.array([list(model_genes).index(x) for x in ['CCND1', 'CCND2', 'CCND3']])])\n", "totalp21fromdata = pExp_nM[list(model_genes).index('CDKN1A')]\n", "kC82_id = params_all.index[np.logical_and(params_all.rxn=='vC104',params_all.idx==0)][0]\n", "kC82 = pd.read_csv('Initializer.txt',sep='\\t',usecols=['Step4_par','Step4_par_val'],index_col='Step4_par', squeeze=True)['kC82']\n", "x_in = rdata_new['x'][-1]\n", "th=0.001\n", "ratio_cd=0.5\n", "ratio_p21 = 0.5\n", "model.setInitialStates(x_in)\n", "model.setFixedParameterById(kC82_id,kC82)\n", "cd_sp = np.argwhere(ObsMat.loc[:,'Cd'].values>0).flatten()\n", "p21_sp = np.argwhere(ObsMat.loc[:,'p21'].values>0).flatten()\n", "while (ratio_cd < (1-th) or ratio_cd > (1+th)) or (ratio_p21 < (1-th) or ratio_p21 > (1+th)):\n", " rdata_loop = amici.runAmiciSimulation(model,solver)\n", " ratio_cd = totalcyclinDfromdata/sum(rdata_loop['x'][-1][cd_sp])\n", " if ratio_cd < (1-th) or ratio_cd > (1+th): \n", " f = 1 + (ratio_cd-1)*0.125\n", " kC173 = kC173*f\n", " kTL10_12 = kC173*17/sum(mExp_nM[Cd_genes])\n", " [model.setFixedParameterById(Cd_kTL,kTL10_12) for Cd_kTL in np.array(kTL_id)[Cd_genes]]\n", " ratio_p21 = totalp21fromdata/sum(rdata_loop['x'][-1][p21_sp])\n", " if ratio_p21 < (1-th) or ratio_p21 > (1+th): \n", " p = 1 + (ratio_p21-1)*0.5\n", " kC82 = kC82/p\n", " model.setFixedParameterById(kC82_id,kC82) \n", "x4 = pd.Series(data=rdata_loop['x'][-1], index=ObsMat.index)\n", "x4[x4.values<1e-6] = 0.0\n", "kTLnew3[Cd_genes] = kTL10_12" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Adjust Caspase 8 (C8) basal cleavage rate" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ts = 1000*3600*0.5\n", "model.setTimepoints(np.linspace(0,ts,1000))\n", "kA77_id = params_all.index[np.logical_and(params_all['rxn']=='vA77',params_all['idx']==0)][0]\n", "kA87_id = params_all.index[np.logical_and(params_all['rxn']=='vA87',params_all['idx']==0)][0]\n", "kA77 = pd.read_csv('Initializer.txt',sep='\\t',usecols=['Step5_kA77','Step5_kA77_val'],index_col='Step5_kA77', squeeze=True)['kA77']\n", "model.setFixedParameterById(kA77_id, kA77)\n", "kA87s = pd.read_csv('Initializer.txt', sep='\\t',usecols=['Step5_kA87s'], squeeze=True)\n", "kA87s = kA87s.values[~np.isnan(kA87s.values)]\n", "for k in range(len(kA87s)):\n", " model.setFixedParameterById(kA87_id, kA87s[k])\n", " kTLnew4, rdata_loop, x5, flagA = kTLadjustwhile(model,solver,x4, obs0, kTL_id, kTLnew3, kTL_mod, k50E_id, k50E_values, ObsMat, S_TL, 1)\n", " if flagA == 0:\n", " x5last = x5\n", " kTLnew4last = kTLnew4\n", " if flagA == 1:\n", " kA87 = kA87s[k-1]\n", " model.setFixedParameterById(kA87_id, kA87)\n", " break\n", "x5 = x5last\n", "kTLnew4 = kTLnew4last\n", "x5[x5.values<1e-6] = 0.0\n", "model.setInitialStates(x5.values)\n", "[model.setFixedParameterById(kTL_id[k], kTLnew4[k]) for k in range(len(kTL_id))]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Adjust basal DNA damage response" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "BRCA2 = x5['BRCA2']\n", "MSH6 = x5['MSH6']\n", "MGMT = x5['MGMT']\n", "Me = x5['Me']\n", "Ma = x5['Ma']\n", "\n", "fixdsb1 = model.getFixedParameterById(params_getid('vD63',0))\n", "fixmsh = model.getFixedParameterById(params_getid('vD64',0))\n", "fixmgmt = model.getFixedParameterById(params_getid('vD65',0))\n", "kDDE = model.getFixedParameterById(params_getid('vD66',1))\n", "kDEtop = model.getFixedParameterById(params_getid('vD66',3))\n", "Etop = model.getFixedParameterById(params_getid('vD66',2))\n", "kDnSP = model.getFixedParameterById(params_getid('vD66',4))\n", "kDkmSP = model.getFixedParameterById(params_getid('vD66',5))\n", "kDkmSS = model.getFixedParameterById(params_getid('vD17',2))\n", "kDkmDS = model.getFixedParameterById(params_getid('vD14',2))\n", "\n", "kDDbasal = 1e-6 # set this value manually\n", "damageDSB_cycling = kDDbasal/(fixdsb1*BRCA2)\n", "damageSSB_cycling = kDDbasal/(fixmsh*MSH6+fixmgmt*MGMT)\n", "\n", "if damageDSB_cycling > kDkmDS:\n", " np.disp('ERROR --- DSB damage is too high, must reduce kDDbasal or increase strength of repair')\n", "if damageSSB_cycling > kDkmSS:\n", " np.disp('ERROR --- SSB damage is too high, must reduce kDDbasal or increase strentgh of repair')\n", "\n", "vdamage_on = (kDDbasal + kDDE*(Etop/(Etop+kDEtop)))*(((Me+Ma)**kDnSP)/(((Me+Ma)**kDnSP)+(kDkmSP**kDnSP)))\n", "damageDSB = vdamage_on/(fixdsb1*BRCA2)\n", "damageSSB = vdamage_on/(fixmsh*MSH6+fixmgmt*MGMT)\n", "kDDbasal_id = params_getid('vD66',0)\n", "model.setFixedParameterById(kDDbasal_id, kDDbasal)\n", "x5['damageDSB'] = damageDSB\n", "x5['damageSSB'] = damageSSB\n", "rdata_new = amici.runAmiciSimulation(model,solver)\n", "x6 = rdata_new['x'][-1]\n", "x6[x6<1e-6] = 0\n", "x6 = pd.Series(data=x6, index=ObsMat.index)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Calculate the leak terms" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "genereg = pd.read_csv('GeneReg.txt', sep='\\t', header=0, index_col=0)\n", "numberofgenes = int(len(genereg.index))\n", "numberofTARs = int(len(genereg.columns))\n", "\n", "for gene_symbol in Step1_mrna.index:\n", " mExp_mpc[gene_symbol] = Step1_mrna[gene_symbol]\n", "gExp_mpc = np.float64(gene_params.loc[:,'Exp GCN'].values)\n", "kGin = np.float64(gene_params.loc[:,'kGin'].values)\n", "kGac = np.float64(gene_params.loc[:,'kGac'].values)\n", "kTCd = np.float64(gene_params.loc[:,'kTCd'].values)\n", "xgac_mpc_D = (kGac*gExp_mpc)/(kGin+kGac)\n", "\n", "TARs0 = (genereg.values)\n", "tcnas = np.ones((numberofgenes, numberofTARs))\n", "tck50as = np.zeros((numberofgenes, numberofTARs))\n", "tcnrs = np.ones((numberofgenes, numberofTARs))\n", "tck50rs = np.zeros((numberofgenes, numberofTARs))\n", "for qq in range(numberofgenes):\n", " for ww in range(numberofTARs):\n", " pars = TARs0[qq,ww].find(';')\n", " if pars>0:\n", " nH = np.float(TARs0[qq,ww][0:pars])\n", " kH = np.float(TARs0[qq,ww][pars+2::])\n", " if nH>0:\n", " tcnas[qq,ww] = nH\n", " tck50as[qq,ww] = kH\n", " else:\n", " tcnrs[qq,ww] = abs(nH)\n", " tck50rs[qq,ww] = kH\n", "\n", "mpc2nmcf_Vn = 1.0E9/(Vn*6.023E+23)\n", "# Convert to molecules per cell\n", "tck50as = tck50as*(1/mpc2nmcf_Vn)\n", "tck50rs = tck50rs*(1/mpc2nmcf_Vn)\n", "\n", "spnames = [ele for ele in model.getStateIds()]\n", "spIDs = []\n", "for qq in range(numberofTARs):\n", " sps = spnames.index(genereg.columns[qq]) \n", " spIDs.append(sps)\n", "TARarr = np.array(x6[spIDs])\n", "TAs = np.zeros((numberofgenes,numberofTARs))\n", "TRs = np.zeros((numberofgenes,numberofTARs))\n", "for qq in range(numberofTARs):\n", " TAs[tck50as[:,qq] > 0, qq] = TARarr[qq]\n", " TRs[tck50rs[:,qq] > 0, qq] = TARarr[qq]\n", "TAs = TAs*(1.0/mpc2nmcf_Vn) # convert to mpc from nM\n", "TAs.flatten()\n", "TRs = TRs*(1.0/mpc2nmcf_Vn)\n", "TRs.flatten() \n", "\n", "# make hills\n", "aa = np.divide(TAs,tck50as)\n", "TFa = np.power(aa,tcnas)\n", "TFa[np.isnan(TFa)] = 0.0\n", "bb = np.divide(TRs,tck50rs)\n", "TFr = np.power(bb,tcnrs)\n", "TFr[np.isnan(TFr)] = 0.0\n", "hills = np.sum(TFa,axis=1)/(1 + np.sum(TFa,axis=1) + np.sum(TFr,axis=1))\n", "# With AP1*cMYC exception:\n", "hills[Cd_genes] = np.multiply((TFa[Cd_genes,0]/(1+TFa[Cd_genes,0])),(TFa[Cd_genes,1]/(1+TFa[Cd_genes,1])))\n", "\n", "# vTCd\n", "vTCd= np.transpose(np.multiply(kTCd,mExp_mpc));TFa[Cd_genes,1]\n", "vTCd = np.squeeze(np.asarray(vTCd))\n", "\n", "kTCmax = 0.1\n", "kTCmaxs = np.ones(len(model_genes))*kTCmax\n", "kTCmaxs = kTCmaxs*mExp_mpc.values.astype('bool').astype('int')\n", "\n", "induced = np.multiply(np.multiply(xgac_mpc_D,kTCmaxs),hills)\n", "induced = induced.flatten()\n", "\n", "negativecheck = np.array(mExp_mpc,dtype=bool).astype(int)*(vTCd - induced)\n", "i2c = np.nonzero(negativecheck<0)[0]\n", "if len(i2c)!=0:\n", " np.disp('WARNING -- Some induction term exceed degradation terms')\n", "leak = vTCd-induced\n", "kTCleak_new=leak/xgac_mpc_D\n", "kTCleak_new[np.isnan(kTCleak_new)] = 0\n", "kTCleak_new[np.isinf(kTCleak_new)] = 0" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3) Save the adjusted species concentration and parameter values into NEW files\n", "\n", "We will save the newly calculated values into files with `\"FileName\"+\"i\".txt` format. Users can change this depending on their preference. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for i in range(np.shape(params_all)[0]):\n", " params_all.loc[params_all.index[i],'value'] = model.getFixedParameterById(str(params_all.index[i]))\n", "params_all.to_csv('ParamsAll_10Ai.txt',sep='\\t')\n", "x6.to_csv('Species_10Ai.txt',sep='\\t',index=True, header=False)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4) Create a new SBML file and compile the Initialized model" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Create the new SBML file" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sbml_model_10Ai = sbml_doc.getModel()\n", "for sp in x6.index:\n", " sbml_model_10Ai.getSpecies(sp).setInitialConcentration(float(x6[sp])) \n", "for par in params_all.index:\n", " sbml_model_10Ai.getParameter(par).setValue(float(model.getFixedParameterById(par)))\n", "sbml_doc_10Ai = sbml_model_10Ai.getSBMLDocument()\n", "writer = libsbml.SBMLWriter()\n", "writer.writeSBML(sbml_doc_10Ai,'SPARCED_10Ai.xml')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Define observables and compile using `AMICI` package" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Define observables\n", "formula_obs = []\n", "for obs in ObsMat.columns:\n", " sp_obs = ObsMat.index[np.nonzero(np.array(ObsMat.loc[:,obs]>0))[0]]\n", " sp_obs_id = np.nonzero(np.array(ObsMat.loc[:,obs]>0))[0]\n", " Vr = VxPARCDL/Vc\n", " Vf = Vr*ObsMat.loc[:,obs].values\n", " \n", " if len(sp_obs) == 1:\n", " formula_i = sp_obs[0]+'*'+str(Vf[sp_obs_id][0])\n", " elif len(sp_obs) == 2:\n", " formula_i = str(sp_obs[0]+'*'+str(Vf[sp_obs_id][0])+'+'+sp_obs[1]+'*'+str(Vf[sp_obs_id][1]))\n", " elif len(sp_obs) > 2:\n", " formula_i = ''\n", " for j in range(len(sp_obs)-1):\n", " formula_i = formula_i+sp_obs[j]+'*'+str(Vf[sp_obs_id][j])+'+'\n", " formula_i = formula_i+str(sp_obs[-1])+'*'+str(Vf[sp_obs_id][-1])\n", " formula_obs.append(formula_i)\n", "observables = {}\n", "obs_names = list(ObsMat.columns)\n", "for i in range(len(obs_names)):\n", " observables[obs_names[i]] = {}\n", " observables[obs_names[i]]['formula'] = formula_obs[i]\n", "\n", "# Compile the initialized model\n", "sbml_importer = amici.SbmlImporter('SPARCED_10Ai.xml')\n", "model_output_dir_10A = str(model_output_dir+'_10Ai')\n", "model_path = os.path.join(model_output_dir_10A)\n", "constantParameters = np.array(params_all.index)\n", "sbml_importer.sbml2amici('SPARCED_10Ai',\n", " model_path,\n", " verbose=False,\n", " observables=observables,\n", " constantParameters=constantParameters)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Finally, check if the model is successfully compiled and ready to run." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Import the model and simulate\n", "sys.path.insert(0, model_path)\n", "model_module = importlib.import_module('SPARCED_10Ai')\n", "model = model_module.getModel()\n", "solver = model.getSolver()\n", "solver.setMaxSteps = 1e10\n", "model.setTimepoints(np.linspace(0,10)) # set timepoints\n", "rdatabbb = amici.runAmiciSimulation(model,solver)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.9" } }, "nbformat": 4, "nbformat_minor": 4 }