Skip to main content

Profiling and debugging

Profiling

One of the main reasons people don’t use ABMs is because they can be very slow. While “vanilla Starsim” is quite fast (10,000 agents running for 100 timesteps should take about a second), custom modules, if not properly written, can be quite slow.

The first step of fixing a slow module is to identify the problem. To do this, Starsim includes some built-in profiling tools.

Let’s look at a simple simulation:

import sciris as sc
import starsim as ss
ss.options(jupyter=True)
sc.options(jupyter=True)

pars = dict(
    start = '2000-01-01',
    stop = '2020-01-01',
    diseases = 'sis',
    networks = 'random'
)

# Profile sim
sim = ss.Sim(pars)
prof = sim.profile()
Initializing sim with 10000 agents
Profiling 15 function(s):
 <bound method Sim.run of Sim(n=10000; 2000.01.01—2020.01.01; networks=randomnet; diseases=sis)>
<bound method Sim.start_step of Sim(n=10000; 2000.01.01—2020.01.01; networks=randomnet; diseases=sis [...]
<function Module.start_step at 0x79d2b7259da0>
<function Module.start_step at 0x79d2b7259da0>
<bound method SIS.step_state of sis(pars=[init_prev, beta, dur_inf, waning, imm_boost]; states=[susc [...]
<bound method RandomExactNet.step of randomnet(n_edges=50000; pars=[n_contacts, dur, beta, age_range [...]
<bound method Infection.step of sis(pars=[init_prev, beta, dur_inf, waning, imm_boost]; states=[susc [...]
<bound method People.step_die of People(n=10000; age=30.2±17.4)>
<bound method People.update_results of People(n=10000; age=30.2±17.4)>
<bound method Network.update_results of randomnet(n_edges=50000; pars=[n_contacts, dur, beta, age_ra [...]
<function SIS.update_results at 0x79d2b72bb6a0>
<function Module.finish_step at 0x79d2b7259f80>
<function Module.finish_step at 0x79d2b7259f80>
<bound method People.finish_step of People(n=10000; age=30.2±17.4)>
<bound method Sim.finish_step of Sim(n=10000; 2000.01.01—2020.01.01; networks=randomnet; diseases=si [...] 

  Running 2000.01.01 ( 0/21) (0.00 s)  ———————————————————— 5%
  Running 2010.01.01 (10/21) (0.12 s)  ••••••••••—————————— 52%
  Running 2020.01.01 (20/21) (0.18 s)  •••••••••••••••••••• 100%

Elapsed time: 0.192 s


—————————————————————————————————————————————————————————————————————
Profile of networks.Network.update_results: 0.000351293 s (0.183098%)
—————————————————————————————————————————————————————————————————————

Total time: 0.000351293 s
File: /home/runner/work/starsim/starsim/starsim/networks.py
Function: Network.update_results at line 332

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
   332                                               def update_results(self):
   333                                                   """ Store the number of edges in the network """
   334        21     145030.0   6906.2     41.3          super().update_results()
   335        21     197333.0   9396.8     56.2          self.results['n_edges'][self.ti] = len(self)
   336        21       8930.0    425.2      2.5          return



———————————————————————————————————————————————————————————————
Profile of people.People.finish_step: 0.000803191 s (0.418631%)
———————————————————————————————————————————————————————————————

Total time: 0.000803191 s
File: /home/runner/work/starsim/starsim/starsim/people.py
Function: People.finish_step at line 542

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
   542                                               def finish_step(self):
   543                                                   """ Remove dead agents and run post-step updates """
   544        21     684538.0  32597.0     85.2          self.remove_dead()
   545        21     110176.0   5246.5     13.7          self.update_post()
   546        21       8477.0    403.7      1.1          return



———————————————————————————————————————————————————————————————
Profile of diseases.SIS.update_results: 0.00262966 s (1.37061%)
———————————————————————————————————————————————————————————————

Total time: 0.00262966 s
File: /home/runner/work/starsim/starsim/starsim/diseases.py
Function: SIS.update_results at line 1071

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
  1071                                               @ss.required()
  1072                                               def update_results(self):
  1073                                                   """ Store the population immunity (susceptibility) """
  1074        21    1665344.0  79302.1     63.3          super().update_results()
  1075        21     954637.0  45458.9     36.3          self.results['rel_sus'][self.ti] = self.rel_sus.mean()
  1076        21       9677.0    460.8      0.4          return



——————————————————————————————————————————————————————————
Profile of people.People.step_die: 0.00295636 s (1.54089%)
——————————————————————————————————————————————————————————

Total time: 0.00295636 s
File: /home/runner/work/starsim/starsim/starsim/people.py
Function: People.step_die at line 502

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
   502                                               def step_die(self):
   503                                                   """ Carry out any deaths or removals that took place this timestep """
   504        21    2697741.0 128463.9     91.3          death_uids = ((self.ti_dead <= self.sim.ti) | (self.ti_removed <= self.sim.ti)).uids
   505        21      95817.0   4562.7      3.2          self.alive[death_uids] = False  # Whilst not dead, removed agents should not be included in alive totals
   506                                           
   507                                                   # Execute deaths that took place this timestep (i.e., changing the `alive` state of the agents). This is executed
   508                                                   # before analyzers have run so that analyzers are able to inspect and record outcomes for agents that died this timestep
   509        42     105127.0   2503.0      3.6          for disease in self.sim.diseases():
   510        21      17012.0    810.1      0.6              if isinstance(disease, ss.Disease):
   511        21      31579.0   1503.8      1.1                  disease.step_die(death_uids)
   512                                           
   513        21       9085.0    432.6      0.3          return death_uids



———————————————————————————————————————————————————————————————
Profile of people.People.update_results: 0.00360929 s (1.8812%)
———————————————————————————————————————————————————————————————

Total time: 0.00360929 s
File: /home/runner/work/starsim/starsim/starsim/people.py
Function: People.update_results at line 531

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
   531                                               def update_results(self):
   532                                                   """ Record per-timestep population counts into the simulation results """
   533        21      38231.0   1820.5      1.1          ti = self.sim.ti
   534        21      10777.0    513.2      0.3          res = self.sim.results
   535        63     485970.0   7713.8     13.5          for state in self.auto_state_list: # Count each auto-generated BoolState result, e.g. n_alive, n_female
   536        42     843114.0  20074.1     23.4              res[f'n_{state.name}'][ti] = np.count_nonzero(getattr(self, state.name))
   537        21    1028148.0  48959.4     28.5          res.new_deaths[ti] = np.count_nonzero(self.ti_dead == ti)
   538        21     892964.0  42522.1     24.7          res.new_emigrants[ti] = np.count_nonzero(self.ti_removed == ti)
   539        21     299932.0  14282.5      8.3          res.cum_deaths[ti] = res.new_deaths[ti] if ti == 0 else res.cum_deaths[ti-1] + res.new_deaths[ti]
   540        21      10156.0    483.6      0.3          return



——————————————————————————————————————————————————————
Profile of sim.Sim.start_step: 0.00536715 s (2.79741%)
——————————————————————————————————————————————————————

Total time: 0.00536715 s
File: /home/runner/work/starsim/starsim/starsim/sim.py
Function: Sim.start_step at line 589

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
   589                                               def start_step(self):
   590                                                   """ Start the step -- only print progress; all actual changes happen in the modules """
   591                                           
   592                                                   # Set the time and if we have reached the end of the simulation, then do nothing
   593        21      10727.0    510.8      0.2          if self.complete:
   594                                                       errormsg = 'Simulation already complete'
   595                                                       raise AlreadyRunError(errormsg)
   596                                           
   597                                                   # Print out progress if needed
   598        21    4054055.0 193050.2     75.5          self.elapsed = self.timer.toc(output=True)
   599        21      13325.0    634.5      0.2          if self.verbose: # Print progress
   600        21      10079.0    480.0      0.2              t = self.t
   601        21      87654.0   4174.0      1.6              simlabel = f'"{self.label}": ' if self.label else ''
   602        21     693138.0  33006.6     12.9              string = f'  Running {simlabel}{t.now("str")} ({t.ti:2.0f}/{t.npts}) ({self.elapsed:0.2f} s) '
   603        21      15489.0    737.6      0.3              if self.verbose >= 1:
   604                                                           sc.heading(string)
   605        21      11701.0    557.2      0.2              elif self.verbose > 0:
   606        21      20580.0    980.0      0.4                  if not (t.ti % int(1.0 / self.verbose)):
   607         3     439944.0 146648.0      8.2                      sc.progressbar(t.ti + 1, t.npts, label=string, length=20, newline=True)
   608        21      10461.0    498.1      0.2          return



————————————————————————————————————————————————————————————
Profile of modules.Module.start_step: 0.0124788 s (6.50408%)
————————————————————————————————————————————————————————————

Total time: 0.0124788 s
File: /home/runner/work/starsim/starsim/starsim/modules.py
Function: Module.start_step at line 840

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
   840                                               @required()
   841                                               def start_step(self):
   842                                                   """ Tasks to perform at the beginning of the step """
   843        42      31499.0    750.0      0.3          if self.finalized:
   844                                                       errormsg = f'The module {self._debug_name} has already been run. Did you mean to copy it before running it?'
   845                                                       raise RuntimeError(errormsg)
   846        42     134786.0   3209.2      1.1          if self.dists is not None and ss.options.crn: # Will be None if no distributions are defined; jumping is a no-op under crn=False (see Dist.jump), so skip the per-dist loop entirely
   847        42   12289901.0 292616.7     98.5              self.dists.jump_dt() # Advance random number generators forward for calls on this step
   848        42      22633.0    538.9      0.2          return



——————————————————————————————————————————————————————————
Profile of diseases.SIS.step_state: 0.0160813 s (8.38174%)
——————————————————————————————————————————————————————————

Total time: 0.0160813 s
File: /home/runner/work/starsim/starsim/starsim/diseases.py
Function: SIS.step_state at line 1026

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
  1026                                               def step_state(self):
  1027                                                   """ Progress infectious -> recovered """
  1028        21    2096465.0  99831.7     13.0          recovered = (self.infected & (self.ti_recovered <= self.ti)).uids
  1029        21     111055.0   5288.3      0.7          self.infected[recovered] = False
  1030        21      72232.0   3439.6      0.4          self.susceptible[recovered] = True
  1031        21   13790905.0 656709.8     85.8          self.update_immunity()
  1032        21      10662.0    507.7      0.1          return



———————————————————————————————————————————————————————————————
Profile of networks.RandomExactNet.step: 0.0402062 s (20.9559%)
———————————————————————————————————————————————————————————————

Total time: 0.0402062 s
File: /home/runner/work/starsim/starsim/starsim/networks.py
Function: RandomExactNet.step at line 709

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
   709                                               def step(self):
   710                                                   """ If dynamic, replace expired edges; otherwise, do nothing """
   711        21      73105.0   3481.2      0.2          if self.pars.dynamic:
   712        21   40123095.0 1.91e+06     99.8              super().step()
   713        21       9955.0    474.0      0.0          return



—————————————————————————————————————————————————————————
Profile of diseases.Infection.step: 0.103723 s (54.0615%)
—————————————————————————————————————————————————————————

Total time: 0.103723 s
File: /home/runner/work/starsim/starsim/starsim/diseases.py
Function: Infection.step at line 246

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
   246                                               def step(self):
   247                                                   """
   248                                                   Perform key infection updates, including infection and setting prognoses
   249                                                   """
   250                                                   # Create new cases
   251        21   81948020.0  3.9e+06     79.0          new_cases, sources, networks = self.infect() # TODO: store outputs in self or use objdict rather than 3 returns
   252                                           
   253                                                   # Set prognoses
   254        21      15297.0    728.4      0.0          if len(new_cases):
   255        21   21735520.0 1.04e+06     21.0              self.set_outcomes(new_cases, sources)
   256        21      12134.0    577.8      0.0              if self.infection_log:
   257                                                           self.infection_log.add_data(new_cases, network=networks)
   258                                           
   259        21      11789.0    561.4      0.0          return new_cases, sources, networks

Figure(672x480)
/home/runner/work/starsim/starsim/starsim/loop.py:613: RuntimeWarning: 
No CPU timing was recorded: run with sim.run(profile=True) (or loop.run(profile=True)) to populate cpu_time.
  ss.warn('No CPU timing was recorded: run with sim.run(profile=True) (or loop.run(profile=True)) to populate cpu_time.')

This graph (which is a shortcut to sim.loop.plot_cpu()) shows us how much time each step in the integration loop takes. We can get line-by-line detail of where each function is taking time, though:

prof.disp(maxentries=5)


——————————————————————————————————————————————————————
Profile of sim.Sim.start_step: 0.00536715 s (2.79741%)
——————————————————————————————————————————————————————

Total time: 0.00536715 s
File: /home/runner/work/starsim/starsim/starsim/sim.py
Function: Sim.start_step at line 589

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
   589                                               def start_step(self):
   590                                                   """ Start the step -- only print progress; all actual changes happen in the modules """
   591                                           
   592                                                   # Set the time and if we have reached the end of the simulation, then do nothing
   593        21      10727.0    510.8      0.2          if self.complete:
   594                                                       errormsg = 'Simulation already complete'
   595                                                       raise AlreadyRunError(errormsg)
   596                                           
   597                                                   # Print out progress if needed
   598        21    4054055.0 193050.2     75.5          self.elapsed = self.timer.toc(output=True)
   599        21      13325.0    634.5      0.2          if self.verbose: # Print progress
   600        21      10079.0    480.0      0.2              t = self.t
   601        21      87654.0   4174.0      1.6              simlabel = f'"{self.label}": ' if self.label else ''
   602        21     693138.0  33006.6     12.9              string = f'  Running {simlabel}{t.now("str")} ({t.ti:2.0f}/{t.npts}) ({self.elapsed:0.2f} s) '
   603        21      15489.0    737.6      0.3              if self.verbose >= 1:
   604                                                           sc.heading(string)
   605        21      11701.0    557.2      0.2              elif self.verbose > 0:
   606        21      20580.0    980.0      0.4                  if not (t.ti % int(1.0 / self.verbose)):
   607         3     439944.0 146648.0      8.2                      sc.progressbar(t.ti + 1, t.npts, label=string, length=20, newline=True)
   608        21      10461.0    498.1      0.2          return



————————————————————————————————————————————————————————————
Profile of modules.Module.start_step: 0.0124788 s (6.50408%)
————————————————————————————————————————————————————————————

Total time: 0.0124788 s
File: /home/runner/work/starsim/starsim/starsim/modules.py
Function: Module.start_step at line 840

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
   840                                               @required()
   841                                               def start_step(self):
   842                                                   """ Tasks to perform at the beginning of the step """
   843        42      31499.0    750.0      0.3          if self.finalized:
   844                                                       errormsg = f'The module {self._debug_name} has already been run. Did you mean to copy it before running it?'
   845                                                       raise RuntimeError(errormsg)
   846        42     134786.0   3209.2      1.1          if self.dists is not None and ss.options.crn: # Will be None if no distributions are defined; jumping is a no-op under crn=False (see Dist.jump), so skip the per-dist loop entirely
   847        42   12289901.0 292616.7     98.5              self.dists.jump_dt() # Advance random number generators forward for calls on this step
   848        42      22633.0    538.9      0.2          return



——————————————————————————————————————————————————————————
Profile of diseases.SIS.step_state: 0.0160813 s (8.38174%)
——————————————————————————————————————————————————————————

Total time: 0.0160813 s
File: /home/runner/work/starsim/starsim/starsim/diseases.py
Function: SIS.step_state at line 1026

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
  1026                                               def step_state(self):
  1027                                                   """ Progress infectious -> recovered """
  1028        21    2096465.0  99831.7     13.0          recovered = (self.infected & (self.ti_recovered <= self.ti)).uids
  1029        21     111055.0   5288.3      0.7          self.infected[recovered] = False
  1030        21      72232.0   3439.6      0.4          self.susceptible[recovered] = True
  1031        21   13790905.0 656709.8     85.8          self.update_immunity()
  1032        21      10662.0    507.7      0.1          return



———————————————————————————————————————————————————————————————
Profile of networks.RandomExactNet.step: 0.0402062 s (20.9559%)
———————————————————————————————————————————————————————————————

Total time: 0.0402062 s
File: /home/runner/work/starsim/starsim/starsim/networks.py
Function: RandomExactNet.step at line 709

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
   709                                               def step(self):
   710                                                   """ If dynamic, replace expired edges; otherwise, do nothing """
   711        21      73105.0   3481.2      0.2          if self.pars.dynamic:
   712        21   40123095.0 1.91e+06     99.8              super().step()
   713        21       9955.0    474.0      0.0          return



—————————————————————————————————————————————————————————
Profile of diseases.Infection.step: 0.103723 s (54.0615%)
—————————————————————————————————————————————————————————

Total time: 0.103723 s
File: /home/runner/work/starsim/starsim/starsim/diseases.py
Function: Infection.step at line 246

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
   246                                               def step(self):
   247                                                   """
   248                                                   Perform key infection updates, including infection and setting prognoses
   249                                                   """
   250                                                   # Create new cases
   251        21   81948020.0  3.9e+06     79.0          new_cases, sources, networks = self.infect() # TODO: store outputs in self or use objdict rather than 3 returns
   252                                           
   253                                                   # Set prognoses
   254        21      15297.0    728.4      0.0          if len(new_cases):
   255        21   21735520.0 1.04e+06     21.0              self.set_outcomes(new_cases, sources)
   256        21      12134.0    577.8      0.0              if self.infection_log:
   257                                                           self.infection_log.add_data(new_cases, network=networks)
   258                                           
   259        21      11789.0    561.4      0.0          return new_cases, sources, networks

(Note that the names of the functions here refer to the actual functions called, which may not match the graph above. That’s because, for example, ss.SIS does not define its own step() method, but instead inherits step() from Infection. In the graph, this is shown as sis.step(), but is listed in the table as Infection.step(). This is because it’s referring to the actual code being run, so refers to where those lines of code exist in the codebase; there is no code corresponding to SIS.step() since it’s just inherited from Infection.step().)

If you want more detail, you can also define custom functions to follow. For example, we can see that ss.SIS.infect() takes the most time in ss.SIS.step(), so let’s profile that:

prof = sim.profile(follow=ss.SIS.infect, plot=False)
prof.disp()
Initializing sim with 10000 agents
Profiling 1 function(s):
 <function Infection.infect at 0x79d2b72b96c0> 

  Running 2000.01.01 ( 0/21) (0.00 s)  ———————————————————— 5%
  Running 2010.01.01 (10/21) (0.06 s)  ••••••••••—————————— 52%
  Running 2020.01.01 (20/21) (0.12 s)  •••••••••••••••••••• 100%

Elapsed time: 0.124 s


————————————————————————————————————————————————————————————
Profile of diseases.Infection.infect: 0.0438902 s (35.3169%)
————————————————————————————————————————————————————————————

Total time: 0.0438902 s
File: /home/runner/work/starsim/starsim/starsim/diseases.py
Function: Infection.infect at line 302

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
   302                                               def infect(self):
   303                                                   """
   304                                                   Determine who gets infected on this timestep via transmission on the network
   305                                           
   306                                                   Computes the effective transmissibility and susceptibility, calls `infect_route()`
   307                                                   for each network (or other route), and then removes duplicate infections with
   308                                                   `finalize_infections()`. A multi-strain disease can override this method to loop
   309                                                   over strains, calling `infect_route()` with per-strain values.
   310                                                   """
   311        21     688392.0  32780.6      1.6          betamap = self.validate_beta()
   312                                           
   313                                                   # Compute effective transmissibility and susceptibility directly on the raw
   314                                                   # (full-length) arrays. This avoids the gather/scatter, full-length astype copy,
   315                                                   # and extra wrapper allocations of the Arr math operators; edges only ever index
   316                                                   # living agents, so stale raw values for inactive agents are never used.
   317        21     644786.0  30704.1      1.5          rel_trans = self.rel_trans.asnew(self.infectious.raw * self.rel_trans.raw, copy=False)
   318        21     415209.0  19771.9      0.9          rel_sus   = self.rel_sus.asnew(self.susceptible.raw * self.rel_sus.raw, copy=False)
   319                                           
   320        21      10539.0    501.9      0.0          new_cases = []
   321        21       9280.0    441.9      0.0          sources = []
   322        21       8918.0    424.7      0.0          networks = []
   323        42     111393.0   2652.2      0.3          for i, (nkey,route) in enumerate(self.sim.networks.items()):
   324        21     202443.0   9640.1      0.5              betas = betamap[ss.standardize_netkey(nkey)]
   325        21   39733985.0 1.89e+06     90.5              target_uids, source_uids, network_ids = self.infect_route(i, route, betas, rel_trans, rel_sus)
   326        21      14327.0    682.2      0.0              new_cases.append(target_uids)
   327        21      10312.0    491.0      0.0              sources.append(source_uids)
   328        21       9710.0    462.4      0.0              networks.append(network_ids)
   329                                           
   330        21    2030875.0  96708.3      4.6          return self.finalize_infections(new_cases, sources, networks)



————————————————————————————————————————————————————————————
Profile of diseases.Infection.infect: 0.0438902 s (35.3169%)
————————————————————————————————————————————————————————————

Total time: 0.0438902 s
File: /home/runner/work/starsim/starsim/starsim/diseases.py
Function: Infection.infect at line 302

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
   302                                               def infect(self):
   303                                                   """
   304                                                   Determine who gets infected on this timestep via transmission on the network
   305                                           
   306                                                   Computes the effective transmissibility and susceptibility, calls `infect_route()`
   307                                                   for each network (or other route), and then removes duplicate infections with
   308                                                   `finalize_infections()`. A multi-strain disease can override this method to loop
   309                                                   over strains, calling `infect_route()` with per-strain values.
   310                                                   """
   311        21     688392.0  32780.6      1.6          betamap = self.validate_beta()
   312                                           
   313                                                   # Compute effective transmissibility and susceptibility directly on the raw
   314                                                   # (full-length) arrays. This avoids the gather/scatter, full-length astype copy,
   315                                                   # and extra wrapper allocations of the Arr math operators; edges only ever index
   316                                                   # living agents, so stale raw values for inactive agents are never used.
   317        21     644786.0  30704.1      1.5          rel_trans = self.rel_trans.asnew(self.infectious.raw * self.rel_trans.raw, copy=False)
   318        21     415209.0  19771.9      0.9          rel_sus   = self.rel_sus.asnew(self.susceptible.raw * self.rel_sus.raw, copy=False)
   319                                           
   320        21      10539.0    501.9      0.0          new_cases = []
   321        21       9280.0    441.9      0.0          sources = []
   322        21       8918.0    424.7      0.0          networks = []
   323        42     111393.0   2652.2      0.3          for i, (nkey,route) in enumerate(self.sim.networks.items()):
   324        21     202443.0   9640.1      0.5              betas = betamap[ss.standardize_netkey(nkey)]
   325        21   39733985.0 1.89e+06     90.5              target_uids, source_uids, network_ids = self.infect_route(i, route, betas, rel_trans, rel_sus)
   326        21      14327.0    682.2      0.0              new_cases.append(target_uids)
   327        21      10312.0    491.0      0.0              sources.append(source_uids)
   328        21       9710.0    462.4      0.0              networks.append(network_ids)
   329                                           
   330        21    2030875.0  96708.3      4.6          return self.finalize_infections(new_cases, sources, networks)

(Note: you can only follow functions that are called as part of sim.run() this way. To follow other functions, such as those run by sim.init(), you can use sc.profile() directly.)

Debugging

When figuring out what your sim is doing – whether it’s doing something it shouldn’t be, or not doing something it should – sim.loop is your friend. It shows everything that will happen in the sim, and in what order:

import starsim as ss

sim = ss.Sim(
    start = 2000,
    stop = 2002,
    diseases = 'sis',
    networks = 'random',
    verbose = 0,
)
sim.run()
sim.loop.to_df().disp()
# %%
    time  ti  func_order                     label     module       func_name  cpu_time
0   2000   0           0            sim.start_step        sim      start_step       NaN
1   2000   0           1      randomnet.start_step  randomnet      start_step       NaN
2   2000   0           2            sis.start_step        sis      start_step       NaN
3   2000   0           3            sis.step_state        sis      step_state       NaN
4   2000   0           4            randomnet.step  randomnet            step       NaN
5   2000   0           5                  sis.step        sis            step       NaN
6   2000   0           6           people.step_die     people        step_die       NaN
7   2000   0           7     people.update_results     people  update_results       NaN
8   2000   0           8  randomnet.update_results  randomnet  update_results       NaN
9   2000   0           9        sis.update_results        sis  update_results       NaN
10  2000   0          10     randomnet.finish_step  randomnet     finish_step       NaN
11  2000   0          11           sis.finish_step        sis     finish_step       NaN
12  2000   0          12        people.finish_step     people     finish_step       NaN
13  2000   0          13           sim.finish_step        sim     finish_step       NaN
14  2001   1           0            sim.start_step        sim      start_step       NaN
15  2001   1           1      randomnet.start_step  randomnet      start_step       NaN
16  2001   1           2            sis.start_step        sis      start_step       NaN
17  2001   1           3            sis.step_state        sis      step_state       NaN
18  2001   1           4            randomnet.step  randomnet            step       NaN
19  2001   1           5                  sis.step        sis            step       NaN
20  2001   1           6           people.step_die     people        step_die       NaN
21  2001   1           7     people.update_results     people  update_results       NaN
22  2001   1           8  randomnet.update_results  randomnet  update_results       NaN
23  2001   1           9        sis.update_results        sis  update_results       NaN
24  2001   1          10     randomnet.finish_step  randomnet     finish_step       NaN
25  2001   1          11           sis.finish_step        sis     finish_step       NaN
26  2001   1          12        people.finish_step     people     finish_step       NaN
27  2001   1          13           sim.finish_step        sim     finish_step       NaN
28  2002   2           0            sim.start_step        sim      start_step       NaN
29  2002   2           1      randomnet.start_step  randomnet      start_step       NaN
30  2002   2           2            sis.start_step        sis      start_step       NaN
31  2002   2           3            sis.step_state        sis      step_state       NaN
32  2002   2           4            randomnet.step  randomnet            step       NaN
33  2002   2           5                  sis.step        sis            step       NaN
34  2002   2           6           people.step_die     people        step_die       NaN
35  2002   2           7     people.update_results     people  update_results       NaN
36  2002   2           8  randomnet.update_results  randomnet  update_results       NaN
37  2002   2           9        sis.update_results        sis  update_results       NaN
38  2002   2          10     randomnet.finish_step  randomnet     finish_step       NaN
39  2002   2          11           sis.finish_step        sis     finish_step       NaN
40  2002   2          12        people.finish_step     people     finish_step       NaN
41  2002   2          13           sim.finish_step        sim     finish_step       NaN

As you can see, it’s a lot – this is only three timesteps and two modules, and it’s already 41 steps.

The typical way to do debugging is to insert breakpoints or print statements into your modules for custom debugging (e.g., to print a value), or to use analyzers for heavier-lift debugging. Starsim also lets you manually modify the loop by inserting “probes” or other arbitrary functions. For example, if you wanted to check the population size after each time the People object is updated:

def check_pop_size(sim):
    print(f'Population size is {len(sim.people)}')

sim = ss.Sim(diseases='sir', networks='random', demographics=True, dur=10)
sim.init()
sim.loop.insert(check_pop_size, label='people.finish_step')
sim.run()
Initializing sim with 10000 agents
  Running 2000 ( 0/11) (0.00 s)  •——————————————————— 9%
Population size is 10074
Population size is 10191
Population size is 10281
Population size is 10376
Population size is 10454
Population size is 10556
Population size is 10652
Population size is 10742
Population size is 10853
Population size is 10946
  Running 2010 (10/11) (0.05 s)  •••••••••••••••••••• 100%

Population size is 11041
Sim(n=10000; 2000—2010.0; demographics=births, deaths; networks=randomnet; diseases=sir)

In this case, you get the same output as using an analyzer:

def check_pop_size(sim):
    print(f'Population size is {len(sim.people)}')

sim = ss.Sim(diseases='sir', networks='random', demographics=True, dur=10, analyzers=check_pop_size)
sim.run()
Initializing sim with 10000 agents
  Running 2000 ( 0/11) (0.00 s)  •——————————————————— 9%
Population size is 10179
Population size is 10287
Population size is 10379
Population size is 10485
Population size is 10559
Population size is 10665
Population size is 10750
Population size is 10857
Population size is 10951
Population size is 11066
  Running 2010 (10/11) (0.05 s)  •••••••••••••••••••• 100%

Population size is 11163
Sim(n=10000; 2000—2010.0; demographics=births, deaths; networks=randomnet; diseases=sir; analyzers=check_pop_size)

However, inserting functions directly in the loop gives you more control over their exact placement, whereas analyzers are always executed last in the timestep.

The loop also has methods for visualizing itself. You can get a simple representation of the loop with loop.plot():

sim.loop.plot()
Figure(672x480)

Or a slightly more detailed one with loop.plot_step_order():

sim.loop.plot_step_order()
Figure(672x480)

This is especially useful if your simulation has modules with different timesteps, e.g.:

sis = ss.SIS(dt=0.1)
net = ss.RandomNet(dt=0.5)
births = ss.Births(dt=1)
sim = ss.Sim(dt=0.1, dur=5, diseases=sis, networks=net, demographics=births)
sim.init()
sim.loop.plot_step_order()
Initializing sim with 10000 agents
Figure(672x480)

(Note: this is a 3D plot, so it helps if you can plot it in a separate window interactively to be able to move it around, rather than just in a notebook.)