Exemple #1
0
    def test_diff_expr(self):
        cases = [('x', 'x'), ('+x', 'x'), ('y', 'x'), ('x+y', 'x'),
                 ('x*y', 'x'), ('x/y', 'x'), ('x**y', 'x'), ('x**x', 'x'),
                 ('y**x', 'x'), ('acos(x)', 'x'), ('asin(x)', 'x'),
                 ('atan(x)', 'x'), ('cos(x)', 'x'), ('cosh(x)', 'x'),
                 ('exp(x)', 'x'), ('log(x)', 'x'), ('log10(x)', 'x'),
                 ('sin(x)', 'x'), ('sinh(x)', 'x'), ('sqrt(x)', 'x'),
                 ('tan(x)', 'x'), ('tanh(x)', 'x'), ('pow(x, 2)', 'x'),
                 ('pow(y, x)', 'x'), ('y**2 - 4*x*z', 'x'),
                 ('(-y + sqrt(y**2 - 4*x*z))/(2*x)', 'x'),
                 ('(-y + sqrt(y**2 - 4*x*z))/(2*x)', 'y'),
                 ('(-y + sqrt(y**2 - 4*x*z))/(2*x)', 'z'),
                 ('sqrt(y - x)', 'x'), ('f(x)', 'x'),
                 ('f(x - y*x + cos(x*z))', 'x'),
                 ('g(x - y*x + cos(x*z), y, x)', 'x'),
                 ('g(x - y*x + cos(x*z), y, x)', 'y'),
                 ('g(x - y*x + cos(x*z), y**z, x - 14*z)', 'y'),
                 ('g(x - y*x + cos(x*z), y, x)', 'y'),
                 ('g(x*y, x*y**2, y)', 'z')]

        for expr, wrt in cases:
            d = ExprManip.diff_expr(expr, wrt)
            ad = eval(d)
            fd = self._num_diff(expr, wrt, x=x, y=y, z=z)
            # We test that our numeric and analytic derivatives differ by less
            #  than 0.1%
            if ad != 0:
                assert abs(fd - ad) / (0.5 * (ad + fd)) < 1e-3
            else:
                assert ad == fd
    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 list2predict2(l, pids, uids=None, us=None, yids=None, c=None, p0=None):
    """
    pred = list2predict(['exp(-p1*1)+exp(-p2*1)', 'exp(-p1*2)+exp(-p2*2)', 'exp(-p1*1)-exp(-p2*1)'],
                        pids=['p1','p2'], p0=None)
    
    pred = list2predict(['(k1f*C1-k1r*X1)-(k2f*X1-k2r*X2)', 
                         '(k2f*X1-k2r*X2)-(k3f*X2-k3r*C2)'],
                        uids=['X1','X2'],
                        us=butil.get_product([1,2,3],[1,2,3]),
                        pids=['k1f','k1r','k2f','k2r','k3f','k3r'], 
                        c={'C1':2,'C2':1})
                        
    Input:
        c: a mapping
    """
    if c is not None:
        l = [exprmanip.sub_for_vars(s, c) for s in l]
    
    ystr = str(l).replace("'", "")
    ycode = compile(ystr, '', 'eval')
    
    def f(p):
        return np.array(eval(ycode, dict(zip(pids, p)), mathsubs))
    
    jaclist = []
    for s in l:
        jacrow = [exprmanip.simplify_expr(exprmanip.diff_expr(s, pid))
                  for pid in pids]
        jaclist.append(jacrow)
        
    if us is not None:
        jaclist = [[[exprmanip.sub_for_vars(jacentry, dict(zip(uids, u))) 
                     for jacentry in jacrow] 
                    for jacrow in jaclist]
                   for u in us]
        jaclist = butil.flatten(jaclist, depth=1)       

    jacstr = str(jaclist).replace("'", "")
    jaccode = compile(jacstr, '', 'eval')

    def Df(p):
        return np.array(eval(jaccode, dict(zip(pids, p)), mathsubs))
    
    if p0 is None:
        p0 = [1] * len(pids)
        
    if yids is None:
        yids = ['y%d'%i for i in range(1, len(l)+1)]
        if us is not None:
            uids = ['u%d'%i for i in range(1, len(us)+1)]
            yids = butil.get_product(yids, uids)
        
    return Predict(f=f, Df=Df, p0=p0, pids=pids, yids=yids)    
Exemple #5
0
def get_Ep_str(net):
    """
    """
    Ep = []
    for rxnid in net.rxnids:
        ratelaw = net.rxns[rxnid].kineticLaw
        Ep_rxn = []
        for pid in net.pids:
            Ep_rxn.append(expr.diff_expr(ratelaw, pid))  # diff also simplifies
        Ep.append(Ep_rxn)
    Ep_str = str(Ep).replace("'", "")   
    Ep_code = compile(Ep_str, '', 'eval')  # compile to code object
    net.Ep_str, net.Ep_code = Ep_str, Ep_code
    return Ep_str, Ep_code
Exemple #6
0
def get_Ex_str(net):
    """
    """
    Ex = []
    for rxnid in net.rxnids:
        ratelaw = net.rxns[rxnid].kineticLaw
        Ex_rxn = []
        for xid in net.xids:
            Ex_rxn.append(expr.diff_expr(ratelaw, xid))  # diff also simplifies
        Ex.append(Ex_rxn)
    Ex_str = str(Ex).replace("'", "")   
    Ex_code = compile(Ex_str, '', 'eval')  # compile to code object
    net.Ex_str, net.Ex_code = Ex_str, Ex_code
    return Ex_str, Ex_code
Exemple #7
0
def get_Ep_str(net):
    """
    """
    Ep = []
    for rxnid in net.rxnids:
        ratelaw = exprmanip.sub_for_vars(net.rxns[rxnid].kineticLaw, 
                                         net.asgrules.to_od())
        Ep_rxn = []
        for pid in net.pids:
            Ep_rxn.append(exprmanip.simplify_expr(exprmanip.diff_expr(ratelaw, pid)))
        Ep.append(Ep_rxn)
    Ep_str = str(Ep).replace("'", "")   
    Ep_code = compile(Ep_str, '', 'eval')  # compile to code object
    net.Ep_str, net.Ep_code = Ep_str, Ep_code
    return Ep_str, Ep_code
Exemple #8
0
def get_concentration_elasticity_string(net):
    """
    """
    Ex = []
    for rxnid in net.rxnids:
        ratelaw = exprmanip.sub_for_vars(net.rxns[rxnid].kineticLaw,
                                         net.asgrules.to_dict())
        Ex_rxn = []
        for xid in net.xids:
            Ex_rxn.append(
                exprmanip.simplify_expr(exprmanip.diff_expr(ratelaw, xid)))
        Ex.append(Ex_rxn)
    Ex_str = str(Ex).replace("'", "")
    Ex_code = compile(Ex_str, '', 'eval')  # compile to code object
    net.Ex_str, net.Ex_code = Ex_str, Ex_code
    return Ex_str, Ex_code
def str2predict(s, pids, uids, us, c=None, p0=None, yids=None):
    """
    Input:
        us: a list of u's where each u has the same length as uids and has the 
            same order
        c: if given, a mapping from convarid to convarval 
    """
    if c is not None:
        s = exprmanip.sub_for_vars(s, c)
    
    ystr = str([exprmanip.sub_for_vars(s, dict(zip(uids, u))) for u in us]).\
        replace("'", "")
    ycode = compile(ystr, '', 'eval')
    
    def f(p):
        return np.array(eval(ycode, dict(zip(pids, p)), mathsubs))
    
    jaclist = []
    for u in us:
        s_u = exprmanip.sub_for_vars(s, dict(zip(uids, u)))
        jacrow = [exprmanip.simplify_expr(exprmanip.diff_expr(s_u, pid))
                  for pid in pids]
        jaclist.append(jacrow)
    jacstr = str(jaclist).replace("'", "")
    jaccode = compile(jacstr, '', 'eval')

    def Df(p):
        return np.array(eval(jaccode, dict(zip(pids, p)), mathsubs))
    
    if p0 is None:
        p0 = [1] * len(pids)
    
    if yids is None:
        yids = ['u=%s'%str(list(u)) for u in us]
        
    return Predict(f=f, Df=Df, p0=p0, pids=pids, yids=yids)
    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