def get_predict(self): R = self.R def _f(p): y = [ R * np.sin(p[0]) * np.cos(p[1]), R * np.sin(p[0]) * np.sin(p[1]), R * np.cos(p[0]) ] return np.array(y) def _Df(p): jac = [[ R * np.cos(p[0]) * np.cos(p[1]), -R * np.sin(p[0]) * np.sin(p[1]) ], [ R * np.cos(p[0]) * np.sin(p[1]), R * np.sin(p[0]) * np.cos(p[1]) ], [-R * np.sin(p[0]), 0]] return np.array(jac) pred = predict.Predict(f=_f, p0=self.p0, name='sphere', pids=self.pids, yids=['x', 'y', 'z'], Df=_Df) return pred
def get_h(self, keep1=True): """ c = h(p) """ hs = [poly.get_h(keep1=keep1) for poly in self] yids = butil.flatten([h_.yids for h_ in hs]) coefstrs = butil.flatten([h_.frepr.tolist() for h_ in hs]) senstrs = [[exprmanip.simplify_expr(exprmanip.diff_expr(coefstr, pid)) for pid in self.pids] for coefstr in coefstrs] hstr = str(coefstrs).replace("'", "") Dhstr = str(senstrs).replace("'", "") subs0 = dict(butil.flatten([poly.convarvals.items() for poly in self], depth=1)) def f(p): subs = subs0.copy() subs.update(dict(zip(self.pids, p))) return np.array(eval(hstr, subs)) def Df(p): subs = subs0.copy() subs.update(dict(zip(self.pids, p))) return np.array(eval(Dhstr, subs)) h = predict.Predict(f=f, Df=Df, pids=self.pids, p0=self.p0, yids=yids, frepr=butil.Series(coefstrs, yids), Dfrepr=butil.DF(senstrs, yids, self.pids)) return h
def get_h(self, keep1=True): """ """ coefs = self.get_coefs() if not keep1: coefs = butil.get_submapping(coefs, f_value=lambda s: s != '1') subcoefids, subcoefstrs = coefs.keys(), coefs.values() yids = ['%s, %s, %s'%((self.polyid,)+subcoefid) for subcoefid in subcoefids] senstrs = [[exprmanip.diff_expr(subcoefstr, pid) for pid in self.pids] for subcoefstr in subcoefstrs] hstr = str(subcoefstrs).replace("'", "") Dhstr = str(senstrs).replace("'", "") subs0 = self.convarvals.to_dict() def h(p): subs = subs0.copy() subs.update(dict(zip(self.pids, p))) return np.array(eval(hstr, subs)) def Dh(p): subs = subs0.copy() subs.update(dict(zip(self.pids, p))) return np.array(eval(Dhstr, subs)) h = predict.Predict(f=h, Df=Dh, pids=self.pids, p0=self.p0, yids=yids, frepr=butil.Series(subcoefstrs, yids), Dfrepr=butil.DF(senstrs, yids, self.pids)) return h
def preds(): Cs = [(2,1), (3,1)] ts = [1,2,3] x0 = 0 pids = ['k1','k2'] def f_xc(p): k1, k2 = p return np.array([(k1*C1+k2*C2)/(k1+k2) for C1, C2 in Cs]) def Df_xc(p): k1, k2 = p return np.array([[(k2*(C1-C2))/(k1+k2)**2, (k1*(C2-C1))/(k1+k2)**2] for C1, C2 in Cs]) pred_xc = predict.Predict(f=f_xc, Df=Df_xc, pids=pids, ydim=len(Cs)) def f_jc(p): k1, k2 = p return np.array([(k1*k2)/(k1+k2)*(C1-C2) for C1, C2 in Cs]) def Df_jc(p): (k1, k2), ksum = p, np.sum(p) return np.array([[k2**2*(C1-C2)/ksum**2, k1**2*(C1-C2)/ksum**2] for C1, C2 in Cs]) pred_jc = predict.Predict(f=f_jc, Df=Df_jc, pids=pids, ydim=len(Cs)) def f_xt(p): k1, k2 = p C1, C2 = Cs[0] return np.array([(k1*C1+k2*C2)/(k1+k2)*(1-np.exp(-(k1+k2)*t))+\ x0*np.exp(-(k1+k2)*t) for t in ts]) def Df_xt(p): (k1, k2), ksum = p, np.sum(p) C1, C2 = Cs[0] return np.array([[np.exp(-ksum*t)*((C1*(k1**2*t+k2*(np.exp(ksum*t)+k1*t-1))+\ k2*C2*(ksum*t-np.exp(ksum*t)+1))/ksum**2-x0*t), np.exp(-ksum*t)*((C2*(k2**2*t+k1*(np.exp(ksum*t)+k2*t-1))+\ k1*C1*(ksum*t-np.exp(ksum*t)+1))/ksum**2-x0*t)] for t in ts]) pred_xt = predict.Predict(f=f_xt, Df=Df_xt, pids=pids, ydim=len(ts)) return pred_xc, pred_jc, pred_xt
def get_predict(self, expts, **kwargs_prior): def _f(p): return np.array([self(t, p) for t in expts]) def _Df(p): jac = [] for t in expts: jac.append([-np.exp(-r * t) * t for r in p]) return np.array(jac) pred = predict.Predict(f=_f, Df=_Df, p0=self.p0, pids=self.pids, yids=expts.yids, name='sumexp%d' % len(self.p0)) if kwargs_prior: pred.set_prior(**kwargs_prior) return pred
def get_predict(net, expts, **kwargs): """ """ # other cases have not been implemented yet assert expts.nrow == 1 and expts.get_conditions() == [None] varids = expts.get_varids() times = expts.get_times() atol = kwargs.pop('atol', None) rtol = kwargs.pop('rtol', None) def _f(p): traj = integrate(net, list(times), varids=varids, p=p, atol=atol, rtol=rtol) return traj.T.values.flatten() def _Df(p): # note that sensitivity integration also returns x(t) straj = integrate_sensitivity(net, list(times), varids=varids, p=p, rtol=rtol) return np.vstack([ straj.values[:, i * net.pdim:(i + 1) * net.pdim] for i in range(len(varids)) ]) pred = predict.Predict(f=_f, Df=_Df, p0=net.p0, pids=net.pids, yids=expts.get_yids(), expts=expts) return pred
def get_predict(net, expts, **kwargs_ss): """ """ varids = list(set(butil.flatten(expts['varids']))) if set(varids) <= set(net.xids): vartype = 's' idxs = [idx for idx, xid in enumerate(net.xids) if xid in varids] elif set(varids) <= set(net.Jids): vartype = 'J' idxs = [idx for idx, Jid in enumerate(net.Jids) if Jid in varids] else: vartype = 'sJ' xJids = net.xids + net.Jids idxs = [idx for idx, xJid in enumerate(xJids) if xJid in varids] net0 = net.copy() if not net0.compiled: net0.compile() nets = [net0.perturb(cond) for cond in expts.conds] [net.get_Ep_str() for net in nets] [net.get_Ex_str() for net in nets] L, Nr = net.L.values, net.Nr.values def f(p): y = [] for net in nets: net.update_optimizable_vars(p) s = get_s(net, **kwargs_ss) if vartype == 's': y_cond = s[idxs].tolist() if vartype == 'J': y_cond = [ net.evaluate_expr(net.reactions[idx].kineticLaw) for idx in idxs ] if vartype == 'sJ': sJ = np.concatenate( (get_s(net, **kwargs_ss), get_J(net, **kwargs_ss))) y_cond = sJ[idxs].tolist() y.extend(y_cond) return np.array(y) def Df(p): jac = [] for net in nets: net.update_optimizable_vars(p) if vartype == 's': #jac_cond = get_Rs(net, p, Nr, L, to_mat=1, **kwargs_ss).loc[varids].dropna() # why dropna? jac_cond = get_Rs(net, Nr, L, **kwargs_ss)[idxs] if vartype == 'J': jac_cond = get_RJ(net, Nr, L, **kwargs_ss)[idxs] if vartype == 'sJ': # to be refined R = np.vstack( (get_Rs(net, Nr, L, **kwargs_ss), get_RJ(net, Nr, L, **kwargs_ss))) jac_cond = R[idxs] jac.extend(jac_cond.tolist()) return np.array(jac) pred = predict.Predict(f=f, Df=Df, p0=net.p0, pids=net.pids, yids=expts.yids, expts=expts, nets=nets) return pred
def to_tex(self, d_tex=None, eqn=True, filepath='', landscape=True, margin=2): """ Input: d_tex: a mapping... """ _repl = exprmanip.sub_for_vars _raisepower = lambda tu: tu[0] ** tu[1] def _2tex_pid(pid): if pid.startswith('Vf_') or pid.startswith('Vb_'): pid = '%s^{%s}' % tuple(pid.split('_')) if pid.count('_') == 2: pid = '%s^{%s}_{%s}' % tuple(pid.split('_')) return pid d_tex = dict(zip(self.pids, [_2tex_pid(pid) for pid in self.pids]) +\ d_tex.items()) _2tex = lambda sympyexpr:\ sympy.latex(sympyexpr, mode='plain', long_frac_ratio=10, mul_symbol='dot', symbol_names=butil.chkeys(d_tex, lambda k: sympy.symbols(k))) _rm1pt0 = lambda expr: re.sub('(?<![0-9])1.0\s*\\\cdot', '', expr) lines = [] lines.append(r'\documentclass{article}') lines.append(r'\usepackage{amsmath,fullpage,longtable,array,calc,mathastext,breqn,xcolor}') if landscape == True: lines.append(r'\usepackage[a4paper,landscape,margin=1in]{geometry}') else: lines.append(r'\usepackage[a4paper,margin=%fin]{geometry}'%margin) lines.append(r'\begin{document}') coefs_r = [] yids = [] for poly in self: termstrs = [] leadingcoef_r = sympy.Poly(poly.coeffs()[0], r).coeffs()[0] for monom_X, coef_X in poly.terms(): coef_X = sympy.simplify(coef_X, ratio=1) poly_r = sympy.Poly(coef_X, r) coefs_r.extend([coef_r/leadingcoef_r for coef_r in poly_r.coeffs()]) monom_X = sympy.prod(map(_raisepower, zip(X, monom_X))) monomstr_X = _2tex(monom_X) if monomstr_X == '1': monomstr_X = '' monomstr_X = '\\textcolor{red}{%s}' % monomstr_X termstrs_r = [] for monom_r, coef_r in poly_r.terms(): coefstr_r = _rm1pt0(_2tex(coef_r)) if coef_r.is_Add: coefstr_r = '\left('+ coefstr_r +'\\right)' monom_r = sympy.prod(map(_raisepower, zip(r, monom_r))) monomstr_r = _2tex(monom_r) if monomstr_r == '1': monomstr_r = '' monomstr_r = '\\textcolor{blue}{%s}' % monomstr_r termstrs_r.append(coefstr_r + '\t' + monomstr_r) coefstr_X = '\\left(' + '+'.join(termstrs_r) + '\\right)' yids.append((ixid, str(monom_X), str(monom_r))) termstrs.append(coefstr_X + '\t' + monomstr_X) linestr = '\\begin{dmath} \n' + '+'.join(termstrs) + '=0\n\end{dmath} \n\n' lines.append(linestr.replace('+-', '-')) lines.append('\\end{document}') if filepath: fh = file(filepath, 'w') fh.write(os.linesep.join(lines)) fh.close() coefs_r = [_rm1pt0(str(coef)) for coef in coefs_r] str_h = str(coefs_r).replace("'", "") str_Dh = str([[exprmanip.diff_expr(coef, pid) for pid in self.pids] for coef in coefs_r]).replace("'", "") def h(p): self.update(p=p) return np.array(eval(str_h, self.varvals.to_dict())) def Dh(p): self.update(p=p) return np.array(eval(str_Dh, self.varvals.to_dict())) coefs = predict.Predict(f=h, Df=Dh, pids=self.pids, p0=self.p0, yids=yids, funcform=coefs_r) return coefs
def get_predict(net, expts, **kwargs): """ :param net: :param expts: :param kwargs: kwargs for networks getting steady states """ assert expts.get_times() == [np.inf] # require varids to be the same; have not implemented heterogeneous varids # yet, but it can otherwise be easily achieved through predict composition assert all( expts.varids.apply(lambda varids: varids == expts.varids.iloc[0])) varids = expts.get_varids() if set(varids) <= set(net.xids): vartype = 's' idxs = [net.xids.index(varid) for varid in varids] elif set(varids) <= set(net.Jids): vartype = 'J' idxs = [net.Jids.index(varid) for varid in varids] else: vartype = 'sJ' idxs = [(net.xids + net.Jids).index(varid) for varid in varids] net = net.copy() if not net.compiled: net.compile() nets = [net.perturb(cond) for cond in expts.condition] for net in nets: _Ex_str = get_concentration_elasticity_string(net) _Ep_str = get_parameter_elasticity_string(net) _L = net.L _Nr = net.Nr def _f(p): y = [] for net in nets: net.update(p=p, t=np.inf, **kwargs) if vartype == 's': y_cond = net.x[idxs] if vartype == 'J': y_cond = net.v[idxs] if vartype == 'sJ': y_cond = np.concatenate((net.x, net.v))[idxs] y.extend(y_cond.tolist()) return np.array(y) def _Df(p): jac = [] for net in nets: net.update(p=p, t=np.inf, **kwargs) if vartype == 's': #jac_cond = get_Rs(net, p, Nr, L, to_mat=1, **kwargs).loc[varids].dropna() # why dropna? jac_cond = net.Rs.iloc[idxs] if vartype == 'J': jac_cond = net.RJ.iloc[idxs] if vartype == 'sJ': jac_cond = np.vstack((net.Rs, net.RJ)).iloc[idxs] jac.extend(jac_cond.values.tolist()) return np.array(jac) pred = predict.Predict(f=_f, Df=_Df, p0=net.p0, pids=net.pids, yids=expts.get_yids(), expts=expts, nets=nets) return pred