Package: ppsimtest
ppsim Python packageTheppsimpackage is used for simulating population protocols. The package and further example notebooks can be found onGithub.The core of the simulator uses abatching algorithmwhich gives significant asymptotic gains for protocols with relatively small reachable state sets. The package is designed to be run in a Python notebook, to concisely describe complex protocols, efficiently simulate their dynamics, and provide helpful visualization of the simulation.Table of contentsInstallationFirst example protocolLarger state protocolProtocol with Multiple FieldsSimulating Chemical Reaction Networks (CRNs)InstallationThe package can be installed withpipviapipinstallppsimThe most important part of the package is theSimulationclass, which is responsible for parsing a protocol, performing the simulation, and giving data about the simulation.fromppsimimportSimulationFirst example protocolA state can be any hashable Python object. The simplest way to describe a protocol is a dictionary mapping pairs of input states to pairs of output states.
For example, here is a description of the classic 3-stateapproximate majority protocol. There are two initial statesAandB, and the protocol converges with high probability to the majority state with the help of a third "undecided" stateU.a,b,u='A','B','U'approximate_majority={(a,b):(u,u),(a,u):(a,a),(b,u):(b,b)}To instantiate aSimulation, we must specify a protocol along with an initial condition, which is a dictionary mapping states to counts. Let's simulate approximate majority with in a population of one billion agents with a slight majority ofAagents.n=10**9init_config={a:0.501*n,b:0.499*n}sim=Simulation(init_config,approximate_majority)Now let's run this simulation for10units of parallel time (10 * ninteractions). We will record the configuration every0.1units of time.sim.run(10,0.1)Time: 10.000TheSimulationclass can display all these configurations in apandasdataframe in the attributehistory.sim.historyABUtime (n interactions)0.050100000049900000000.1459457762457439751831024870.24302767894282175651415056460.34090273764068982541840743700.4393162729390949934215887337............9.7771074143553578121735680459.8789103074489739251619230019.98066679294307638315025568810.08236413883766854713869006510.082364138937668547138690064102 rows × 3 columnsp=sim.history.plot()Without specifying an end time,runwill run the simulation until the configuration is silent (all interactions are null). In this case, that will be when the protocol reaches a silent majority consensus configuration.sim.run()p=sim.history.plot()Time: 21.000Note that by default,Simulationassumes that input pair(b,a)will have the same transition as(a,b), so order doesn't matter, with the default settingtransition_order = 'symmetric'.
Thus we have the exact same protocol as if we had spent more time explicitly specifyingapproximate_majority_symmetric={(a,b):(u,u),(b,a):(u,u),(a,u):(a,a),(u,a):(a,a),(b,u):(b,b),(u,b):(b,b)}If we intentionally meant for these pairwise transitions to only happen in this specified order, we can declare that. We see in this case that it has the same behavior, but just runs twice as slow because now every interaction must happen in a specified order.sim=Simulation(init_config,approximate_majority,transition_order='asymmetric')print(sim.reactions)sim.run()p=sim.history.plot()A, B  -->  U, U      with probability 0.5
A, U  -->  A, A      with probability 0.5
B, U  -->  B, B      with probability 0.5
 Time: 44.000A key result about this protocol is it converges in expected O(log n) time, which surprisingly is very nontrivial to prove. We can use this package to very quickly gather some convincing data that the convergence really is O(log n) time, with the functiontime_trials.fromppsimimporttime_trialsimportnumpyasnpns=[int(n)forninnp.geomspace(10,10**8,20)]definitial_condition(n):return{'A':n//2,'B':n//2}df=time_trials(approximate_majority,ns,initial_condition,num_trials=100,max_wallclock_time=30)dfntime0103.01102.12102.83102.74103.8.........14924281332323.8149310000000028.1149410000000025.2149510000000025.1149610000000024.61497 rows × 2 columnsThis dataframe collected time from up to 100 trials for each population size n across a many orders of magnitude, limited by the budget of 30 seconds of wallclock time that we gave it.
We can now use theseabornlibrary to get a convincing plot of the data.importseabornassnslp=sns.lineplot(x='n',y='time',data=df)lp.set_xscale('log')Larger state protocolFor more complicated protocols, it would be very tedious to use this dictionary format. Instead we can give an arbitrary Python function which takes a pair of states as input (along with possible other protocol parameters) and returns a pair of states as output (or if we wanted a randomized transition, it would output a dictionary which maps pairs of states to probabilities).As a quick example, let's take a look at the discrete averaging dynamics, as analyzedhereandhere, which have been a key subroutine used in counting and majority protocols.frommathimportceil,floordefdiscrete_averaging(a,b):avg=(a+b)/2returnfloor(avg),ceil(avg)n=10**6sim=Simulation({0:n//2,50:n//2},discrete_averaging)We did not need to explicitly describe the state set. Upon initialization,Simulationused breadth first search to find all states reachable from the initial configuration.print(sim.state_list)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]This enumeration will call the functionrulewe give it O(q^2) times, where q is the number of reachable states. This preprocessing step also builds an internal representation of the transition function, so it will not need to continue callingrule. Thus we don't need to worry too much about our code forrulebeing efficient.Rather than the dictionary format used to input the configuration, internallySimulationrepresents the configuration as an array of counts, where the ordering of the indices is given bystate_list.sim.config_dict{0: 500000, 50: 500000}sim.config_arrayarray([500000,      0,      0,      0,      0,      0,      0,      0,
            0,      0,      0,      0,      0,      0,      0,      0,
            0,      0,      0,      0,      0,      0,      0,      0,
            0,      0,      0,      0,      0,      0,      0,      0,
            0,      0,      0,      0,      0,      0,      0,      0,
            0,      0,      0,      0,      0,      0,      0,      0,
            0,      0, 500000], dtype=int64)A key result about these discrete averaging dynamics is that they converge in O(log n) time to at most 3 consecutive values. It could take longer to reach the ultimate silent configuration with only 2 consecutive values, so if we wanted to check for the faster convergence condition, we could use a function that checks for the condition. This function takes a configuration dictionary (mapping states to counts) as input and returnsTrueif the convergence criterion has been met.defthree_consecutive_values(config):states=config.keys()returnmax(states)-min(states)<=2Now we can run until this condition is met (or also usetime_trialsas above to generate statistics about this convergence time).sim.run(three_consecutive_values,0.1)sim.historyTime: 14.8000123456789...41424344454647484950time (n interactions)0.0500000000000000...0000000005000000.145021511203139113428...901253950216004502430.240125711112293014212569418199...18826684216511271761074013370.335472646617151467048181643114721...753134173050867512272053333543120.43102481061451572360251829729533401720...1708399292685232333271653161116309999..................................................................14.40000000000...000000000014.50000000000...000000000014.60000000000...000000000014.70000000000...000000000014.80000000000...0000000000149 rows × 51 columnsWith a much larger number of states, thehistorydataframe is more unwieldly, so trying to directly callhistory.plot()would be very messy and not very useful. Instead, we will define a function that makes a barplot, using the data in a single row ofsim.historyto visualize the distribution at that recorded time step.frommatplotlibimportpyplotaspltdefplot_row(row):fig,ax=plt.subplots(figsize=(12,5))sim.history.iloc[row].plot(ax=ax,kind='bar',title=f'Discrete averaging at time{sim.history.index[row]:.2f}',xlabel='minute',ylim=(0,n))plot_row(0)plot_row(30)plot_row(-1)Theipywidgetslibrary gives a quick way to make a slider that lets us visualize the evolution of this distribution:importipywidgetsaswidgetsbar=widgets.interact(plot_row,row=widgets.IntSlider(min=0,max=len(sim.history)-1,step=1,value=0,layout=widgets.Layout(width='100%')))It is recommended to use an interactive matplotlib backend, such asipympl, which can be installed withpip install ipympland then activated with the cell magic%matplotlib widget. The recommended environment to use for these notebooks isJupyter Lab. Unfortunately, these interactive backends are not supported withGoogle Colab, so there does not seem to be an easy way to have access to interactive backends with something that can be run only in a browser without local installation.The code with the slider above was designed to work in the non-interactive backend. The following cell shows how to accomplish the same thing with an interactive backend:# The following example uses the ipympl backend. It creates one figure and axis once and then modifies the axis directly with plot_row.# If ipympl is installed, then uncommenting and running the following code will produce a slider that changes one single interactive figure object.# %matplotlib widget# def plot_row(row):#     ax.clear()#     sim.history.iloc[row].plot(ax=ax, kind='bar',#                               title=f'Discrete averaging at time {sim.history.index[row]:.2f}',#                               xlabel='minute',#                               ylim=(0,n))#     fig.canvas.draw()# fig, ax = plt.subplots()# bar = widgets.interact(plot_row, row = widgets.IntSlider(#     min=0, max=len(sim.history)-1, step=1, value=0, layout = widgets.Layout(width='100%')))Because the population average was exactly 25, the ultimate silent configuration will have every agent in state 50, but it will take a a very long time to reach, as we must wait for pairwise interactions between dwindling counts of states 24 and 26. We can check that this reaction is now the only possible non-null interaction.print(sim.enabled_reactions)24, 26  -->  25, 25As a result, the probability of a non-null interaction will grow very small, upon which the simulator will switch to the Gillespie algorithm. This allows it to relatively quickly run all the way until silence, which we can confirm takes a very long amount of parallel time.# Setting history_interval to be a function of time t that shrinks, to not record too many configurations over a long time scalesim.run(history_interval=lambdat:10**len(str(int(t)))/100)Time: 578983.800To better visualize small count states, we add an option to changeyscalefromlineartosymlog.defplot_row(row,yscale):fig,ax=plt.subplots(figsize=(12,5))sim.history.iloc[row].plot(ax=ax,kind='bar',title=f'Discrete averaging at time{sim.history.index[row]:.2f}',xlabel='minute',ylim=(0,n))ax.set_yscale(yscale)bar=widgets.interact(plot_row,row=widgets.IntSlider(min=0,max=len(sim.history)-1,step=1,value=0,layout=widgets.Layout(width='100%')),yscale=['linear','symlog'])Protocol with Multiple FieldsFor more complicated protocol, it is helpful to have the states be more complicated Python objects. A recommended method is to define an Agentdataclassthat includes various fields.As a concrete example, we will use the protocol fromSimple and Efficient Leader Election. We start by translating the explicit description of an agents state into our Agent class.importdataclassesfromdataclassesimportdataclass# The parameter unsafe_hash=True makes the state hashable, as required, but still lets the transition code change the field values# Note that ppsim will by default make safe copies of the agent states before applying the rule,#  so it is safe to mutate the fields of an agent in the transition rule@dataclass(unsafe_hash=True)classAgent:role:str='contender'flip_bit:int=0marker:int=0phase:str='marking'counter:int=0defleader_election(v:Agent,u:Agent,loglogn:int,Ulogn:int):# marking phaseifv.phase=='marking':ifv.counter>=3*loglognandu.flip_bit==0:v.phase='tournament'else:v.counter+=1ifv.counter==4*loglogn:v.marker=1v.phase='tournament'ifv.phase=='tournament':ifv.role=='contender':ifu.markerandv.counter<=Ulogn:v.counter+=1ifv.counter<u.counter:v.role='minion'ifu.role=='contender'andv.counter==u.counterandv.flip_bit<u.flip_bit:v.role='minion'v.counter=max(v.counter,u.counter)v.flip_bit=1-v.flip_bitreturnvThe pseudocode was described in the following way:We can implement this assumption by having our transition rule call the theleader_electionfunction twice:deftransition(v:Agent,u:Agent,loglogn:int,Ulogn:int):returnleader_election(v,dataclasses.replace(u),loglogn,Ulogn),leader_election(u,dataclasses.replace(v),loglogn,Ulogn)We can first check instantiate the protocol for various population sizes, to confirm that the number of reachable states is scaling like we expect.importnumpyasnpns=[int(n)forninnp.geomspace(10,10**8,8)]states=[]forninns:sim=Simulation({Agent():n},transition,loglogn=int(np.log2(np.log2(n))),Ulogn=u*int(np.log2(n)))states.append(len(sim.state_list))plt.plot(ns,states)plt.xscale('log')plt.xlabel('population size n')plt.ylabel('number of states')plt.show()Now we will simulate the rule for a population of one billion agents, and run it until it gets to one leader.n=10**9sim=Simulation({Agent():n},transition,loglogn=int(np.log2(np.log2(n))),Ulogn=u*int(np.log2(n)))defone_leader(config):leader_states=[stateforstateinconfig.keys()ifstate.role=='contender']returnlen(leader_states)==1andconfig[leader_states[0]]==1sim.run(one_leader)Time: 67.253Because there are hundreds of states, the full history dataframe is more complicated.sim.historyrolecontender...minionflip_bit0...1marker0...1phasemarkingtournament...tournamentcounter024681012141213...50515253545556575859time (n interactions)0.0000001000000000000000000...00000000001.00000013533683727066169690227329120281568590803816211486108...00000000002.00000018312018146524448195383216104189030297735125298122641440139083015314976...00000000003.00000024786904462612613386736316063102310326314841305948112693445569071287669649759...00000000004.000000335736107366165726044412213899013956837099261227481239254232398104873175527630...0000000000..................................................................64.0000000000000000...000000000065.0000000000000000...000000000066.0000000000000000...000000000067.0000000000000000...000000000067.2525490000000000...000000000069 rows × 384 columnsBecause we defined a state as a dataclassAgent, which had fields, the columns of thehistorydataframe are a pandasMultiIndex.sim.history.columnsMultiIndex([('contender', 0, 0,    'marking',  0),
            ('contender', 0, 0,    'marking',  2),
            ('contender', 0, 0,    'marking',  4),
            ('contender', 0, 0,    'marking',  6),
            ('contender', 0, 0,    'marking',  8),
            ('contender', 0, 0,    'marking', 10),
            ('contender', 0, 0,    'marking', 12),
            ('contender', 0, 0,    'marking', 14),
            ('contender', 0, 0, 'tournament', 12),
            ('contender', 0, 0, 'tournament', 13),
            ...
            (   'minion', 1, 1, 'tournament', 50),
            (   'minion', 1, 1, 'tournament', 51),
            (   'minion', 1, 1, 'tournament', 52),
            (   'minion', 1, 1, 'tournament', 53),
            (   'minion', 1, 1, 'tournament', 54),
            (   'minion', 1, 1, 'tournament', 55),
            (   'minion', 1, 1, 'tournament', 56),
            (   'minion', 1, 1, 'tournament', 57),
            (   'minion', 1, 1, 'tournament', 58),
            (   'minion', 1, 1, 'tournament', 59)],
           names=['role', 'flip_bit', 'marker', 'phase', 'counter'], length=384)We can use the pandasgroupbyfunction to conveniently look at the values of just one field. For a field whose name is the stringfield, then callingsim.history.groupby(field, axis=1).sum()gives the counts of values of just a single state. If we have a set of fieldsfield1, field2, ...then callingsim.history.groupby([field1, field2, ...], axis=1).sum()will give the counts of values of just those fields.sim.history.groupby('role',axis=1).sum()rolecontenderminiontime (n interactions)0.000000100000000001.000000100000000002.000000999999972283.000000999969579304214.0000009980424141957586.........64.000000299999999865.000000299999999866.000000299999999867.000000299999999867.252549199999999969 rows × 2 columnsThis lets us quickly plot the counts of leaders, to see how it decreases down to one leader, and the count in each phase, to see when the agents transition from the marking phase to the tournament phase.sim.history.groupby('role',axis=1).sum().plot()plt.yscale('symlog')plt.ylim(0,2*n)plt.show()sim.history.groupby('phase',axis=1).sum().plot()plt.show()For this protocol, a good understanding of why it is working comes from looking at the product ofroleandcountervalues. The way the protocol works is that contenders increase their counter values, which spread by epidemic among all minions, to eliminate other contenders with smaller counter values.We will again try to visualize a single row of the dataframe that projects onto just theroleandcountervalues. Callingdf.iloc[index]gives us aSeriesdf=sim.history.groupby(['counter','role'],axis=1).sum()df.iloc[10]counter  role     
0        contender        2
1        contender       48
2        contender      441
3        contender     2876
4        contender    13600
                      ...  
57       minion           0
58       contender        0
         minion           0
59       contender        0
         minion           0
Name: 10.0, Length: 108, dtype: int64Then callingunstack()on the series will give pull off the first field, and give us a dataframe that can immediately plotted as a multibar plot.df.iloc[10].unstack()rolecontenderminioncounter02.0NaN148.0NaN2441.0NaN32876.0NaN413600.0NaN555257.0NaN6183276.0NaN7523542.0NaN81305762.0NaN92908411.0NaN105815321.0NaN1110577404.0NaN1219519273.0144731.01315633037.02774308.01412659059.011179251.0159794528.030343520.01631088600.0522306882.0177599591.0292467764.018951336.021176355.01982136.0856059.0205498.030677.021277.01087.02210.068.0230.011.0241.01.0250.00.0260.00.0270.00.0280.00.0290.00.0300.00.0310.00.0320.00.0330.00.0340.00.0350.00.0360.00.0370.00.0380.00.0390.00.0400.00.0410.00.0420.00.0430.00.0440.00.0450.00.0460.00.0470.00.0480.00.0490.00.0500.00.0510.00.0520.00.0530.00.0540.00.0550.00.0560.00.0570.00.0580.00.0590.00.0df.iloc[10].unstack().plot(kind='bar',figsize=(12,5))plt.show()Now we can define a function that creates one of these plots at an arbitrary row, to get a similar slider that lets us quickly visualize the evolution of the distributions.defplot_row(row,yscale):fig,ax=plt.subplots(figsize=(12,5))df.iloc[row].unstack().plot(ax=ax,kind='bar',ylim=(0,n))ax.set_yscale(yscale)bar=widgets.interact(plot_row,row=widgets.IntSlider(min=0,max=len(sim.history)-1,step=1,value=0,layout=widgets.Layout(width='100%')),yscale=['linear','symlog'])Simulating Chemical Reaction Networks (CRNs)ppsimis able to simulate any Chemical Reaction Network that has only bimolecular (2-input, 2-output) and unimolecular (1-input, 1-output) reactions. There is a special syntax used to specify CRNs, such asfromppsimimportspeciesa,b,c,d=species('A B C D')crn=[(a+b|2*c).k(0.5).r(4),(c>>d).k(5)]First we definespeciesobjectsa,b,c,d. We then createcrn, a list ofreactionobjects, which are created by composing these species. Using the>>operator creates an irreversible (one-way) reaction, while using the|operator creates a reversible (two-way) reaction. A rate constant can be added with the methodreaction.k(...), and the reverse rate constant is added with the methodreaction.r(...). If not specified, rate constants are assumed to be 1.sim=Simulation({a:2000,b:1000},crn)sim.run()p=sim.history.plot()Time: 37.000CRNs are normally modelled by Gillespie kinetics, which gives a continuous time Markov process. The unimolecular reactionC ->(5) Dhappens as a Poisson process with rate 5. The forward bimolecular reactionA+B ->(0.5) 2Chappens as a Poisson process with rate0.5 (#A * #B / v), and the reverse bimolecular reaction happens as a Poisson process with rate4 * #B (\#B - 1) / (2*v), wherevis the volume parameter.When creating aSimulationwith a list ofreactionobjects,ppsimwill by default use this continuous time model.
By default,ppsimsets the volumevto be the population sizen, which makes the time units independent of population size. In some models, this volume parameter is instead baked directly into the numerical rate constant. In this case, the volume should be set manually in the Simulation constructor, withSimulation(..., volume = 1). In addition, if these numerical rate constants are specified in specific time units (such as per second), this can be specified withSimulation(..., time_units='seconds'), and then all times will appear with appropriate units.For more details about the CRN model and how it is faithfully represented as a continuous time population protocol, seethis paper.More examplesSeehttps://github.com/UC-Davis-molecular-computing/population-protocols-python-package/tree/main/examples/