# AUTOGENERATED! DO NOT EDIT! File to edit: ../05_chemical_equations.ipynb.

# %% auto 0
__all__ = ['ChemSimulation']

# %% ../05_chemical_equations.ipynb 3
def ChemSimulation(eqnstr,verbose=True,**kwargs):
    from pyndamics3 import Simulation
    lines=eqnstr.strip().split('\n')
    
    components=set([])
    parameters=set([])
    for line in lines:
        lhs=[_.strip() for _ in line.split('--')[0].strip().split('+')]
        rhs=[_.strip() for _ in line.split('->')[-1].strip().split('+')]
        middle=line.split('--')[1].lstrip('\t ->').split('->')[0].rstrip('\t ->')

        components=components.union(set(lhs+rhs))
        parameters=parameters.union([middle])
        
        if verbose:
            print(lhs,middle,rhs)
        
        
    components=sorted(components)
    parameters=sorted(parameters)
    
    if verbose:
        print("Components",components)
        print("Parameters",parameters)
    
    
    diffeqs=[]
    for c in components:
        
        if c=='ϕ':
            continue
        
        eqn="%s' = " % c

        for line in lines:
            lhs=[_.strip() for _ in line.split('--')[0].strip().split('+')]
            rhs=[_.strip() for _ in line.split('->')[-1].strip().split('+')]
            middle=line.split('--')[1].lstrip('\t ->').split('->')[0].rstrip('\t ->')


            sign='0'
            if c in lhs:
                sign='-'
                if len(rhs)>1:
                    sign+='%d*' % len(rhs)


            if c in rhs:
                sign='+'
                if len(lhs)>1:
                    sign+='%d*' % len(lhs)

            if sign=='0':
                continue
                
            if c in rhs and c in lhs:  # A -> A +B doesn't change A
                continue

            plhs='*'.join(lhs)

            eqn+=f" {sign}{middle}*{plhs}"

        if eqn=="%s' = " % c:
            eqn="%s' = 0" % c
            
        diffeqs.append(eqn)  
        
    if verbose:
        print("diffeqs",diffeqs)
        
    sim=Simulation()
        
    for c,d in zip(components,diffeqs):
        if not c in kwargs:
            c0=0
        else:
            c0=kwargs[c]
            
            
        sim.add(d,c0)
        
    for p in parameters:
        if p in kwargs:
            sim.params(**{p:kwargs[p]})
        
    return sim
