Exemplo n.º 1
0
    def SSA_MA_complex(self, Desc, sub1, sub2, complex, kf, kr):
        #rescale kf for second order stochastic propensity
        if str(self.pvaldict[kf]
               ) == self.SSAmodel.listOfParameters[kf].expression:
            self.SSAmodel.setParameter(
                kf, self.SSAmodel.listOfParameters[kf].expression + '/(' +
                str(self.vol) + ')')
        rxn1 = stk.Reaction(
            name=Desc + "_formation",
            reactants={
                self.species_array[self.ydict[sub1]]: 1,
                self.species_array[self.ydict[sub2]]: 1
            },
            products={self.species_array[self.ydict[complex]]: 1},
            massaction=True,
            rate=self.param_array[self.pdict[kf]])
        self.SSAmodel.addReaction(rxn1)

        rxn2 = stk.Reaction(
            name=Desc + "degradation",
            reactants={self.species_array[self.ydict[complex]]: 1},
            products={
                self.species_array[self.ydict[sub1]]: 1,
                self.species_array[self.ydict[sub2]]: 1
            },
            massaction=True,
            rate=self.param_array[self.pdict[kr]])
        self.SSAmodel.addReaction(rxn2)

        #print Desc+' added successfully.'
        return
Exemplo n.º 2
0
    def SSA_MA_meanfield(self, sharedspecies, indx, xlen, indy, ylen, kcouple):

        #set-up indexes for mixing. Note that this makes sure there is only one reaction each time
        #since the inxed relationship only goes in one direction
        annt = None
        index = '_' + str(indx) + '_' + str(indy)

        if indx + 1 == xlen:
            ind_x1 = '_' + str(0) + '_' + str(indy)
        else:
            ind_x1 = '_' + str(indx + 1) + '_' + str(indy)

        if indy + 1 == ylen:
            ind_y1 = '_' + str(indx) + '_' + str(0)
        else:
            ind_y1 = '_' + str(indx) + '_' + str(indy + 1)

        rctsf = {self.species_array[self.ydict[sharedspecies + index]]: 1}
        prodsxf = {self.species_array[self.ydict[sharedspecies + ind_x1]]: 1}
        prodsyf = {self.species_array[self.ydict[sharedspecies + ind_y1]]: 1}

        prodsr = {self.species_array[self.ydict[sharedspecies + index]]: 1}
        rctsxr = {self.species_array[self.ydict[sharedspecies + ind_x1]]: 1}
        rctsyr = {self.species_array[self.ydict[sharedspecies + ind_y1]]: 1}

        propfcnxr = kcouple + '*' + sharedspecies + ind_x1  #('+sharedspecies+ind_x1+'-'+sharedspecies+index+')'
        propfcnyr = kcouple + '*' + sharedspecies + ind_y1  #('+sharedspecies+ind_y1+'-'+sharedspecies+index+')'

        propfcnxf = kcouple + '*' + sharedspecies + index  #('+sharedspecies+index+'-'+sharedspecies+ind_x1+')'
        propfcnyf = kcouple + '*' + sharedspecies + index  #('+sharedspecies+index+'-'+sharedspecies+ind_y1+')'

        #Add forward and backward mixing for x and y both
        rxn1 = stk.Reaction(name=sharedspecies + 'mixing' + index + '_xf',
                            reactants=rctsf,
                            products=prodsxf,
                            propensity_function=propfcnxf,
                            annotation=annt)
        self.SSAmodel.addReaction(rxn1)

        rxn3 = stk.Reaction(name=sharedspecies + 'mixing' + index + '_xr',
                            reactants=rctsxr,
                            products=prodsr,
                            propensity_function=propfcnxr,
                            annotation=annt)
        self.SSAmodel.addReaction(rxn3)

        rxn2 = stk.Reaction(name=sharedspecies + 'mixing' + index + '_yf',
                            reactants=rctsf,
                            products=prodsyf,
                            propensity_function=propfcnyf,
                            annotation=annt)
        self.SSAmodel.addReaction(rxn2)

        rxn4 = stk.Reaction(name=sharedspecies + 'mixing' + index + '_yr',
                            reactants=rctsyr,
                            products=prodsr,
                            propensity_function=propfcnyr,
                            annotation=annt)
        self.SSAmodel.addReaction(rxn4)
Exemplo n.º 3
0
 def SSA_MA_deg(self, Desc, S, k):
     rxn = stk.Reaction(name=Desc,
                        reactants={self.species_array[self.ydict[S]]: 1},
                        propensity_function=k + '*' + S)
     self.SSAmodel.addReaction(rxn)
     #print Desc+' added successfully.'
     return
Exemplo n.º 4
0
 def SSA_MA_tln(self, Desc, P, k, mRNA):
     rxn = stk.Reaction(name=Desc,
                        products={self.species_array[self.ydict[P]]: 1},
                        propensity_function=mRNA + "*" + k,
                        annotation="EmptySet->" + P)
     self.SSAmodel.addReaction(rxn)
     #print Desc+' added successfully.'
     return
Exemplo n.º 5
0
    def SSA_Ptf(self, Desc, per, tf, kf, kr):

        rxn1 = stk.Reaction(name=Desc + "_formation",
                            reactants={self.species_array[self.ydict[per]]: 1},
                            products={self.species_array[self.ydict[tf]]: 1},
                            massaction=True,
                            rate=self.param_array[self.pdict[kf]])
        self.SSAmodel.addReaction(rxn1)

        rxn2 = stk.Reaction(name=Desc + "degradation",
                            reactants={self.species_array[self.ydict[tf]]: 1},
                            products={self.species_array[self.ydict[per]]: 1},
                            massaction=True,
                            rate=self.param_array[self.pdict[kr]])
        self.SSAmodel.addReaction(rxn2)

        #print Desc+' added successfully.'
        return
Exemplo n.º 6
0
 def SSA_MF_deg(self, Desc, S, k, xlen, ylen):
     cellcount = xlen * ylen
     rxn = stk.Reaction(name=Desc,
                        reactants={self.species_array[self.ydict[S]]: 1},
                        propensity_function=k + '*' + S + '/' +
                        str(cellcount))
     self.SSAmodel.addReaction(rxn)
     #print Desc+' added successfully.'
     return
Exemplo n.º 7
0
    def SSA_MA_cytonuc(self, Desc, cyto, nuc, kf, kr):
        #rescale kf for second order stochastic propensity
        rxn1 = stk.Reaction(
            name=Desc + "_tonuc",
            reactants={self.species_array[self.ydict[cyto]]: 1},
            products={self.species_array[self.ydict[nuc]]: 1},
            massaction=True,
            rate=self.param_array[self.pdict[kf]])
        self.SSAmodel.addReaction(rxn1)

        rxn2 = stk.Reaction(name=Desc + "_tocyto",
                            reactants={self.species_array[self.ydict[nuc]]: 1},
                            products={self.species_array[self.ydict[cyto]]: 1},
                            massaction=True,
                            rate=self.param_array[self.pdict[kr]])
        self.SSAmodel.addReaction(rxn2)

        #print Desc+' added successfully.'
        return
Exemplo n.º 8
0
    def SSA_tyson_y(self, Desc, Y, a0, a1, a2):
        rcts = {self.species_array[self.ydict[Y]]: 1}
        prods = {}

        propfcn = Y + '/(a0 + a1*(' + Y + '/' + str(
            self.vol) + ') + a2*' + Y + '*' + Y + '/(' + str(
                self.vol) + '*' + str(self.vol) + '))'

        rxn = stk.Reaction(name=Desc,
                           reactants=rcts,
                           products=prods,
                           propensity_function=propfcn,
                           annotation=0)
        self.SSAmodel.addReaction(rxn)
        return
Exemplo n.º 9
0
    def SSA_PR16f(self, Desc, prod, act, rep1, rep2, vtr, vtp, knp):
        rcts = {}
        prods = {self.species_array[self.ydict[prod]]: 1}

        om = str(self.vol)

        propfcn = om + '*(' + vtr + '*(' + act + '/' + om + ')+' + vtp + ')/(' + knp + '+(' + rep1 + '/' + om + ')+(' + rep2 + '/' + om + '))'

        annt = 0

        rxn = stk.Reaction(name=Desc,
                           reactants=rcts,
                           products=prods,
                           propensity_function=propfcn,
                           annotation=annt)
        self.SSAmodel.addReaction(rxn)
Exemplo n.º 10
0
    def SSA_tyson_y(self, Desc, Y, a0, a1, a2, tc=None):
        rcts = {self.species_array[self.ydict[Y]]: 1}
        prods = {}

        propfcn = (Y + '/(' + a0 + '+ ' + a1 + '*(' + Y + '/' + str(self.vol) +
                   ') + ' + a2 + '*' + Y + '*' + Y + '/(' + str(self.vol) +
                   '*' + str(self.vol) + '))')

        if tc: propfcn = tc + '*' + propfcn

        rxn = stk.Reaction(name=Desc,
                           reactants=rcts,
                           products=prods,
                           propensity_function=propfcn,
                           annotation=0)
        self.SSAmodel.addReaction(rxn)
        return
Exemplo n.º 11
0
    def SSA_MM_P_Goodwin(self, Desc, Prod=None, Rep=None, P=None):
        """ Peter's hacked function to allow for hill kinetics in
        Goodwin Model """

        # Add the 3rd order hill term

        vmax_expr = str(self.vol)
        km0_expr = '1'
        rep_expr = '*'.join(['(' + Rep + '/' + str(self.vol) + ')'] * int(P))

        propfcn = vmax_expr + '/(' + km0_expr + '+' + rep_expr + ')'

        rxn = stk.Reaction(name=Desc,
                           products={self.species_array[self.ydict[Prod]]: 1},
                           propensity_function=propfcn,
                           annotation="EmptySet->" + Prod)
        self.SSAmodel.addReaction(rxn)
Exemplo n.º 12
0
    def SSA_MA(self, name='', reactants={}, products={}, rate=''):
        """ Deal with mass-action rates where volume affects the
        stochastic propensity """

        # Scale rate by appropriate volume power
        degree = sum(reactants.values())
        if str(self.pvaldict[rate.name]) == rate.expression:
            self.SSAmodel.setParameter(
                rate.name, (rate.expression + '/pow(' + str(self.vol) + ', ' +
                            str(degree - 1) + ')'))

        rxn = stk.Reaction(name=name,
                           reactants=reactants,
                           products=products,
                           massaction=True,
                           rate=rate)

        self.SSAmodel.addReaction(rxn)
Exemplo n.º 13
0
    def SSA_tyson_x(self, Desc, X, Y, P):
        rcts = {}
        prods = {self.species_array[self.ydict[X]]: 1}

        exp_P = int(float(self.SSAmodel.listOfParameters[P].expression))

        ymult = Y + ('*' + Y) * (exp_P - 1)
        volmult = '(' + str(
            self.vol) + ('*' + str(self.vol)) * (exp_P - 1) + ')'

        propfcn = str(self.vol) + '*1/(1+(' + ymult + '/(' + volmult + ')))'

        rxn = stk.Reaction(name=Desc,
                           reactants=rcts,
                           products=prods,
                           propensity_function=propfcn,
                           annotation=None)
        self.SSAmodel.addReaction(rxn)

        return
def SSAnetwork(fn,y0in,param,adjacency):
    """
    This is the network-level SSA model, with coupling. Call with:
        SSAcoupled,state_names,param_names = SSAmodelC(ODEmodel(),y0in,param)
    
    To uncouple the model, set adjacency matrix to zeros    
    """
    
    #Converts concentration to population
    y0in_ssa = (vol*y0in).astype(int)
    
    #collects state and parameter array to be converted to species and parameter objects,
    #makes copies of the names so that they are on record
    species_array = []
    state_names=[]
    if randomy0==False:
        y0in_pop = []
    

    #coupling section===========================
    for indx in range(cellcount):
        index = '_'+str(indx)+'_0'
        #loops to include all species, normally this is the only line needed without index
        species_array = species_array + [fn.inputSX(cs.DAE_X)[i].getDescription()+index
                        for i in xrange(EqCount)]
        state_names = state_names + [fn.inputSX(cs.DAE_X)[i].getDescription()+index
                        for i in xrange(EqCount)]  
        if randomy0==False:                
            y0in_pop = np.append(y0in_pop, y0in_ssa)       
                
    if randomy0 == True:
        #random initial locations
        y0in_pop = 1*np.ones(EqCount*cellcount)
        for i in range(len(y0in_pop)):
            y0in_pop[i] = vol*4*random.random()

    #===========================================
            
    param_array   = [fn.inputSX(cs.DAE_P)[i].getDescription()
                    for i in xrange(ParamCount)]
    param_names   = [fn.inputSX(cs.DAE_P)[i].getDescription()
                    for i in xrange(ParamCount)]
    #Names model
    SSAmodel = stk.StochKitModel(name=modelversion)
    
    #creates SSAmodel class object
    SSA_builder = mb.SSA_builder(species_array,param_array,y0in_pop,param,SSAmodel,vol)
    

    #coupling section
    for indx in range(cellcount):
            
        index = '_'+str(indx)+'_0'
        
        #Coupled terms - - -------------------------------------------------
        #loops for all cells accumulating their input
        avg = '0'
        mcount = 0
        for fromcell in range(cellcount):
            if adjacency[fromcell,indx]!= 0:
                #The Coupling Part
                mcount = mcount+1
                avg = avg+'+M_'+str(fromcell)+'_0'

        
        weight = 1.0/mcount
        #FIXES PARAMETERS FROM DETERMINISTIC TO STOCHASTIC VALUES
        if (str(SSA_builder.pvaldict['vs0']) ==
                        SSA_builder.SSAmodel.listOfParameters['vs0'].expression):
                SSA_builder.SSAmodel.setParameter('vs0',
                                SSA_builder.SSAmodel.listOfParameters['vs0'].expression+'*('+str(SSA_builder.vol)+')')
        if (str(SSA_builder.pvaldict['k1']) ==
                        SSA_builder.SSAmodel.listOfParameters['k1'].expression):
                SSA_builder.SSAmodel.setParameter('k1',
                                SSA_builder.SSAmodel.listOfParameters['k1'].expression+'*('+str(SSA_builder.vol)+')')
        
        if (str(SSA_builder.pvaldict['alocal']) ==
                        SSA_builder.SSAmodel.listOfParameters['alocal'].expression):
                SSA_builder.SSAmodel.setParameter('alocal',
                                SSA_builder.SSAmodel.listOfParameters['alocal'].expression+'*('+str(SSA_builder.vol)+')')
        #####
        #Adds reaction for coupling
        rxn=stk.Reaction(name='Cell'+str(indx)+'_Reaction0',
                         reactants={},
                        products={'M_'+str(indx)+'_0':1},
                        propensity_function=('std::max(0.0,(vs0+alocal*(('+avg+')*'
                                    +str(weight)+'-M_'+str(indx)+'_0)))'+ 
                                    '*pow(k1,n)/(pow(k1,n)+pow(Pn_'+str(indx)+'_0,n))'),annotation='')#
   
        SSAmodel.addReaction(rxn)
        #-------------------------------------------------------------------
        
        # REACTIONS
        SSA_builder.SSA_MM('Cell'+str(indx)+'_Reaction1','vm',
                           km=['km'],Rct=['M'+index])
        
        SSA_builder.SSA_MA_tln('Cell'+str(indx)+'_Reaction2', 'Pc'+index,
                               'ks','M'+index)
        
        SSA_builder.SSA_MM('Cell'+str(indx)+'_Reaction3','vd',
                           km=['kd'],Rct=['Pc'+index])
        
        #The complexing four:
        SSA_builder.SSA_MA_cytonuc('Cell'+str(indx)+'_Reaction4','Pc'+index,
                                   'Pn'+index,'k1_','k2_')
        

    return SSAmodel,state_names,param_names
Exemplo n.º 15
0
def SSAmodel(fn,y0in,param):
    """
    This is the network-level SSA model, with coupling. Call with:
    SSAcoupled,state_names,param_names = SSAmodelC(ODEmodel(),y0in,param)
    By default, there is no coupling in this model.    
    """
    
    #Converts concentration to population
    y0in_pop = (vol*y0in).astype(int)
    
    #collects state and parameter array to be converted to species and parameter objects,
    #makes copies of the names so that they are on record
    species_array = [fn.inputExpr(cs.DAE_X)[i].getName()
                    for i in xrange(EqCount)]
    param_array   = [fn.inputExpr(cs.DAE_P)[i].getName()
                    for i in xrange(ParamCount)]
    
    state_names = [fn.inputExpr(cs.DAE_X)[i].getName()
                        for i in xrange(EqCount)]  
    param_names   = [fn.inputExpr(cs.DAE_P)[i].getName()
                        for i in xrange(ParamCount)]

    #creates SSAmodel class object    
    SSAmodel = stk.StochKitModel(name=modelversion)
    SSA_builder = mb.SSA_builder(species_array,param_array,y0in_pop,param,SSAmodel,vol)
    

    #FIXES PARAMETERS FROM DETERMINISTIC TO STOCHASTIC VALUES
    if (str(SSA_builder.pvaldict['vs0']) ==
                    SSA_builder.SSAmodel.listOfParameters['vs0'].expression):
            SSA_builder.SSAmodel.setParameter('vs0',
                            SSA_builder.SSAmodel.listOfParameters['vs0'].expression+'*('+str(SSA_builder.vol)+')')
    if (str(SSA_builder.pvaldict['k1']) ==
                    SSA_builder.SSAmodel.listOfParameters['k1'].expression):
            SSA_builder.SSAmodel.setParameter('k1',
                            SSA_builder.SSAmodel.listOfParameters['k1'].expression+'*('+str(SSA_builder.vol)+')')
    
    if (str(SSA_builder.pvaldict['alocal']) ==
                    SSA_builder.SSAmodel.listOfParameters['alocal'].expression):
            SSA_builder.SSAmodel.setParameter('alocal',
                            SSA_builder.SSAmodel.listOfParameters['alocal'].expression+'*('+str(SSA_builder.vol)+')')
    
    
    # REACTIONS
    rxn0=stk.Reaction(name='Reaction0',
                         reactants={},
                        products={'M':1},
                        propensity_function=(
                        'vs0*pow(k1,n)/(pow(k1,n)+pow(Pn,n))'),annotation='')
   
    SSAmodel.addReaction(rxn0)    
    
    SSA_builder.SSA_MM('Reaction1','vm',
                       km=['km'],Rct=['M'])
    
    SSA_builder.SSA_MA_tln('Reaction2', 'Pc',
                           'ks','M')
    
    SSA_builder.SSA_MM('Reaction3','vd',
                       km=['kd'],Rct=['Pc'])

    SSA_builder.SSA_MA_cytonuc('Reaction4','Pc',
                               'Pn','k1_','k2_')
        

    return SSAmodel,state_names,param_names
Exemplo n.º 16
0
        def SSA_genMM(self,
                      Desc,
                      vmax,
                      km=None,
                      Sub=None,
                      Prod=None,
                      Act=None,
                      CInh=None,
                      UCInh=None,
                      NCInh=None):
            """general michaelis-menten term that includes re-scaling for a population model
            
                        
            """

            #counts components
            try:
                rctcount = len(Rct)
            except:
                rctcount = 0
            try:
                prodcount = len(Prod)
            except:
                prodcount = 0
            try:
                actcount = len(Act)
            except:
                actcount = 0
            try:
                repcount = len(Rep)
            except:
                repcount = 0

            #Adds Reactants
            rcts = {}
            if Rct is not None:
                rcts.update({self.species_array[self.ydict[Rct[0]]]: 1})

            #Adds Products
            prods = {}
            for i in range(prodcount):
                prods.update({self.species_array[self.ydict[Prod[i]]]: 1})

            #redefine vmax -- need some way to determine if it has been updated or not
            if str(self.pvaldict[vmax]
                   ) == self.SSAmodel.listOfParameters[vmax].expression:
                self.SSAmodel.setParameter(
                    vmax, self.SSAmodel.listOfParameters[vmax].expression +
                    '*(' + str(self.vol) + '**2)/(' + str(self.vol) + '**(' +
                    str(actcount + (Rct is not None)) + '))')

            if len(km) == 1:

                #redefine k -- need some way to determine if it has been updated or not
                if str(self.pvaldict[km[0]]) == self.SSAmodel.listOfParameters[
                        km[0]].expression:
                    self.SSAmodel.setParameter(
                        km[0],
                        self.SSAmodel.listOfParameters[km[0]].expression +
                        '*(' + str(self.vol) + ')')

                #propensity funtion setup
                rctmult = ''
                rctsum = ''
                for i in range(Rct is not None):
                    rctmult = rctmult + '*' + Rct[i]

                for i in range(rctcount):
                    rctsum = rctsum + '+' + Rct[i]

                actmult = ''
                actsum = ''
                for i in range(actcount):
                    actsum = actsum + '+' + Act[i]
                    actmult = actmult + '*' + Act[i]

                repmult = ''
                repsum = ''
                for i in range(repcount):
                    repsum = repsum + '+' + Rep[i]
                    repmult = repmult + '*' + Rep[i]

                #creates the propensity function
                propfcn = vmax + rctmult + actmult + '/(' + km[
                    0] + rctsum + actsum + repsum + ')'

                annt = 0  #no annotations necessary yet

                rxn = stk.Reaction(name=Desc,
                                   reactants=rcts,
                                   products=prods,
                                   propensity_function=propfcn,
                                   annotation=annt)
            self.SSAmodel.addReaction(rxn)
            #print Desc+' added successfully.'
            return
Exemplo n.º 17
0
def ssa_resync(fn,
               y0in_desync,
               param,
               cellcount,
               adjacency,
               couplingstr=couplingstr,
               vol=40):
    """
    This is the network-level SSA model, with coupling. Call with:
        SSAcoupled,state_names,param_names = SSAmodelC(ODEmodel(),y0in,param)
    
    To uncouple the model, set adjacency matrix to zeros    
    """

    #collects state and parameter array to be converted to species and parameter objects,
    #makes copies of the names so that they are on record
    species_array = []
    state_names = []

    #coupling section===========================
    for indx in range(cellcount):
        index = '_' + str(indx) + '_0'
        #loops to include all species, normally this is the only line needed without index
        species_array = species_array + [
            fn.inputExpr(cs.DAE_X)[i].getName() + index
            for i in xrange(EqCount)
        ]
        state_names = state_names + [
            fn.inputExpr(cs.DAE_X)[i].getName() + index
            for i in xrange(EqCount)
        ]

    y0in_pop = y0in_desync

    #===========================================

    param_array = [
        fn.inputExpr(cs.DAE_P)[i].getName() for i in xrange(ParamCount)
    ]
    param_names = [
        fn.inputExpr(cs.DAE_P)[i].getName() for i in xrange(ParamCount)
    ]
    #Names model
    SSAmodel = stk.StochKitModel(name=modelversion)

    #creates SSAmodel class object
    SSA_builder = mb.SSA_builder(species_array, param_array, y0in_pop, param,
                                 SSAmodel, vol)

    # now set up mean field(?) coupling for all uncoupled cells

    #coupling section
    for indx in range(cellcount):

        index = '_' + str(indx) + '_0'

        #Coupled terms - - -------------------------------------------------
        #loops for all cells accumulating their input
        avg = 'M' + index
        mcount = 1

        for fromcell in range(cellcount):
            if adjacency[fromcell, indx] != 0:
                #The Coupling Part
                mcount = mcount + couplingstr
                avg = avg + '+M_' + str(fromcell) + '_0*' + str(couplingstr)
            if mcount == 1:
                # then the cell is "uncoupled" so we'll put it to a mean field
                for fromcell in range(cellcount):
                    mcount += couplingstr * 0.25 / cellcount
                    avg = avg + '+M_' + str(fromcell) + '_0*0.33*' + str(
                        couplingstr / cellcount)

        weight = 1.0 / mcount
        #FIXES PARAMETERS FROM DETERMINISTIC TO STOCHASTIC VALUES
        if (str(SSA_builder.pvaldict['vs0']) ==
                SSA_builder.SSAmodel.listOfParameters['vs0'].expression):
            SSA_builder.SSAmodel.setParameter(
                'vs0',
                SSA_builder.SSAmodel.listOfParameters['vs0'].expression +
                '*(' + str(SSA_builder.vol) + ')')
        if (str(SSA_builder.pvaldict['k1']) ==
                SSA_builder.SSAmodel.listOfParameters['k1'].expression):
            SSA_builder.SSAmodel.setParameter(
                'k1', SSA_builder.SSAmodel.listOfParameters['k1'].expression +
                '*(' + str(SSA_builder.vol) + ')')

        if (str(SSA_builder.pvaldict['alocal']) ==
                SSA_builder.SSAmodel.listOfParameters['alocal'].expression):
            SSA_builder.SSAmodel.setParameter(
                'alocal',
                SSA_builder.SSAmodel.listOfParameters['alocal'].expression +
                '*(' + str(SSA_builder.vol) + ')')
        #####
        #Adds reaction
        rxn = stk.Reaction(
            name='Cell' + str(indx) + '_Reaction0',
            reactants={},
            products={'M_' + str(indx) + '_0': 1},
            propensity_function=('std::max(0.0,(vs0+alocal*((' + avg + ')*' +
                                 str(weight) + '-M_' + str(indx) + '_0)))' +
                                 '*pow(k1,n)/(pow(k1,n)+pow(Pn_' + str(indx) +
                                 '_0,n))'),
            annotation='')  #

        SSAmodel.addReaction(rxn)
        #-------------------------------------------------------------------

        # REACTIONS
        SSA_builder.SSA_MM('Cell' + str(indx) + '_Reaction1',
                           'vm',
                           km=['km'],
                           Rct=['M' + index])

        SSA_builder.SSA_MA_tln('Cell' + str(indx) + '_Reaction2', 'Pc' + index,
                               'ks', 'M' + index)

        SSA_builder.SSA_MM('Cell' + str(indx) + '_Reaction3',
                           'vd',
                           km=['kd'],
                           Rct=['Pc' + index])

        #The complexing four:
        SSA_builder.SSA_MA_cytonuc('Cell' + str(indx) + '_Reaction4',
                                   'Pc' + index, 'Pn' + index, 'k1_', 'k2_')

    print 'weak, mean-field coupling'
    return SSAmodel, state_names, param_names
def ssa_resync(fn, y0in_desync, param, cellcount, adjacency):
    """
    This is the network-level SSA model, with coupling. Call with:
        SSAcoupled,state_names,param_names = SSAmodelC(ODEmodel(),y0in,param)
    
    To uncouple the model, set adjacency matrix to zeros    
    """

    #Converts concentration to population
    y0in_ssa = (vol * y0in).astype(int)

    #collects state and parameter array to be converted to species and parameter objects,
    #makes copies of the names so that they are on record
    species_array = []
    state_names = []
    y0in_pop = y0in_desync

    #coupling section===========================
    for indx in range(cellcount):
        index = '_' + str(indx) + '_0'
        #loops to include all species, normally this is the only line needed without index
        species_array = species_array + [
            fn.inputExpr(cs.DAE_X)[i].getName() + index
            for i in xrange(EqCount)
        ]
        state_names = state_names + [
            fn.inputExpr(cs.DAE_X)[i].getName() + index
            for i in xrange(EqCount)
        ]
        if randomy0 == False:
            y0in_pop = np.append(y0in_pop, y0in_ssa)

    if randomy0 == True:
        #random initial locations
        y0in_pop = 1 * np.ones(EqCount * cellcount)
        for i in range(len(y0in_pop)):
            y0in_pop[i] = vol * 1 * random.random()

    #===========================================

    param_array = [
        fn.inputExpr(cs.DAE_P)[i].getName() for i in xrange(ParamCount)
    ]
    param_names = [
        fn.inputExpr(cs.DAE_P)[i].getName() for i in xrange(ParamCount)
    ]
    #Names model
    SSAmodel = stk.StochKitModel(name=modelversion)

    #creates SSAmodel class object
    SSA_builder = mb.SSA_builder(species_array, param_array, y0in_pop, param,
                                 SSAmodel, vol)

    #coupling section
    for indx in range(cellcount):

        index = '_' + str(indx) + '_0'

        # REACTIONS
        #per mRNA

        SSA_builder.SSA_PR16f('per mRNA activation' + index, 'p' + index,
                              'CREB' + index, 'C1P' + index, 'C2P' + index,
                              'vtpr', 'vtpp', 'knpr')
        SSA_builder.SSA_MM('per mRNA degradation' + index,
                           'vdp',
                           km=['kdp'],
                           Rct=['p' + index])

        #cry1 mRNA
        SSA_builder.SSA_MM('c1 mRNA repression' + index,
                           'vtc1r',
                           km=['kncr'],
                           Prod=['c1' + index],
                           Rep=['C1P' + index, 'C2P' + index])
        SSA_builder.SSA_MM('c1 mRNA degradation' + index,
                           'vdc1',
                           km=['kdc'],
                           Rct=['c1' + index])

        #cry2 mRNA
        SSA_builder.SSA_MM('c2 mRNA repression' + index,
                           'vtc2r',
                           km=['kncr'],
                           Prod=['c2' + index],
                           Rep=['C1P' + index, 'C2P' + index])
        SSA_builder.SSA_MM('c2 mRNA degradation' + index,
                           'vdc2',
                           km=['kdc'],
                           Rct=['c2' + index])

        #vip mRNA
        SSA_builder.SSA_MM('vip mRNA repression' + index,
                           'vtvr',
                           km=['knvr'],
                           Prod=['vip' + index],
                           Rep=['C1P' + index, 'C2P' + index])
        SSA_builder.SSA_MM('vip mRNA degradation' + index,
                           'vdv',
                           km=['kdv'],
                           Rct=['vip' + index])

        #CRY1, CRY2, PER, VIP creation and degradation
        SSA_builder.SSA_MA_tln('PER translation' + index, 'P' + index, 'ktlnp',
                               'p' + index)
        SSA_builder.SSA_MA_tln('CRY1 translation' + index, 'C1' + index,
                               'ktlnc', 'c1' + index)
        SSA_builder.SSA_MA_tln('CRY2 translation' + index, 'C2' + index,
                               'ktlnc', 'c2' + index)

        SSA_builder.SSA_MM('PER degradation' + index,
                           'vdP',
                           km=['kdP'],
                           Rct=['P' + index])
        SSA_builder.SSA_MM('C1 degradation' + index,
                           'vdC1',
                           km=['kdC'],
                           Rct=['C1' + index])
        SSA_builder.SSA_MM('C2 degradation' + index,
                           'vdC2',
                           km=['kdC'],
                           Rct=['C2' + index])
        SSA_builder.SSA_MA_deg('eVIP degradation' + index, 'eVIP' + index,
                               'kdVIP')

        #CRY1 CRY2 complexing
        SSA_builder.SSA_MA_complex('CRY1-P complex' + index, 'C1' + index,
                                   'P' + index, 'C1P' + index, 'vaCP', 'vdCP')
        SSA_builder.SSA_MA_complex('CRY2-P complex' + index, 'C2' + index,
                                   'P' + index, 'C2P' + index, 'vaCP', 'vdCP')
        SSA_builder.SSA_MM('C1P degradation' + index,
                           'vdC1n',
                           km=['kdCn'],
                           Rct=['C1P' + index, 'C2P' + index])
        SSA_builder.SSA_MM('C2P degradation' + index,
                           'vdC2n',
                           km=['kdCn'],
                           Rct=['C2P' + index, 'C1P' + index])

        #VIP/CREB Pathway
        SSA_builder.SSA_MM('CREB formation' + index,
                           'vgpka',
                           km=['kgpka'],
                           Prod=['CREB' + index],
                           Act=['eVIP' + index])
        SSA_builder.SSA_MM('CREB degradation' + index,
                           'vdCREB',
                           km=['kdCREB'],
                           Rct=['CREB' + index])

    for currentcell in range(cellcount):
        for affectedcell in range(cellcount):
            if adjacency[currentcell, affectedcell] != 0:
                #The Coupling Part
                rxn = stk.Reaction(
                    name='vip from ' + str(currentcell) + ' to ' +
                    str(affectedcell),
                    products={'eVIP_' + str(affectedcell) + '_0': 1},
                    propensity_function='vip_' + str(currentcell) + "_0*" +
                    'ktlnv' + '*' + str(adjacency[currentcell, affectedcell]),
                    annotation='')
                SSAmodel.addReaction(rxn)

    return SSAmodel, state_names, param_names