Esempio n. 1
0
def run_the_app():

    # Draw the UI elements to search for objects (pedestrians, cars, etc.)
    gsize, s1, s2, s3, i1, i2, i3, r1, r2, r3, run = frame_selector_ui()

    progress_flu_rule = DiscreteInvMarkovChain('flu-status',
    { 's': [s1, s2, s3], 'i': [i1, i2, i3], 'r': [r1, r2, r3] })
    # s - susceptible
    # i - infectious
    # r - recovered

    sites = { 'home': Site('h'), 'work': Site('w') }

    probe_grp_size_flu = GroupSizeProbe.by_attr('flu', 'flu-status', progress_flu_rule.get_states(), msg_mode=ProbeMsgMode.DISP, memo='Mass distribution across flu status')
    probe_grp_size_site = GroupSizeProbe.by_rel('site', Site.AT, sites.values(), msg_mode=ProbeMsgMode.DISP, memo='Mass distribution across sites')

    data = ""
    s = Simulation()
    s.add_rule(progress_flu_rule)
    s.add_probe(probe_grp_size_flu)
    s.add_group(Group('g0', gsize, { 'flu-status': 's' }))
    sys.stdout = open('out.dat', 'w')
    s.run(int(run))
    sys.stdout.close()

    with open('out.dat') as file:
        data = file.readlines()
        for line in data:
            st.write(line)
Esempio n. 2
0
    def simple(self):
        progress_flu_rule = DiscreteInvMarkovChain('flu-status', { 's': [0.95, 0.05, 0.00], 'i': [0.00, 0.50, 0.50], 'r': [0.10, 0.00, 0.90] })
        # s - susceptible
        # i - infectious
        # r - recovered

        sites = { 'home': Site('h'), 'work': Site('w') }

        probe_grp_size_flu = GroupSizeProbe.by_attr('flu', 'flu-status', progress_flu_rule.get_states(), msg_mode=ProbeMsgMode.DISP, memo='Mass distribution across flu status')
        probe_grp_size_site = GroupSizeProbe.by_rel('site', Site.AT, sites.values(), msg_mode=ProbeMsgMode.DISP, memo='Mass distribution across sites')


    # ----------------------------------------------------------------------------------------------------------------------
    # (1) Simulations testing the basic operations on groups and rules:

        # (1.1) A single-group, single-rule (1g.1r) simulation:
        s = Simulation()
        s.add_rule(progress_flu_rule)
        s.add_probe(probe_grp_size_flu)
        s.add_group(Group('g0', 1000, { 'flu-status': 's' }))
        sys.stdout = open('out.dat', 'w')
        s.run(24)
        sys.stdout.close()
        
        with open('out.dat') as file:
            self.data = file.readlines()
            self.data = str(self.data)
        apple  = self.data.replace('\\n', '<br>')
       # print(apple)
        return apple
Esempio n. 3
0
File: sim.py Progetto: momacs/pram
    def run_sim(p_lst):
        for p in p_lst:
            sim = (Simulation().
                # add_rule(ResetSchoolDayRule(7)).
                add_rule(GoToAndBackTimeAtRule()).
                add_rule(flu_rule).
                add_probes(probes_grp_size_flu_school)
            )

            for s in school_specs:
                (sim.new_group(s.name, s.m).
                    set_attr('is-student', True).
                    set_attr('flu', 's').
                    set_rel(Site.AT,  sites['home']).
                    set_rel('home',   sites['home']).
                    set_rel('school', sites[f'school-{s.name}']).
                    done()
                )

            setattr(flu_rule, 'p_infection_min', p)
            for p in probes_grp_size_flu_school:
                p.set_consts([Const('p_inf_min', 'float', str(flu_rule.p_infection_min))])
                p.set_persistence(probe_persistence)

            sim.run(24 * sim_dur_days)
Esempio n. 4
0
def sim_flu_ac_init(session, do_force=False):
    if 'sim-flu-ac' in session and not do_force:
        return

    if 'sim-flu-ac' in session:
        session.pop('sim-flu-ac')
        gc.collect()

    school_l  = Site(450149323)  # 88% low income students
    school_m  = Site(450067740)  #  7% low income students

    session['sim-flu-ac'] = (
        Simulation().
            set().
                pragma_autocompact(True).
                pragma_live_info(True).
                pragma_live_info_ts(False).
                pragma_rule_analysis_for_db_gen(False).
                done().
            add().
                probe(sim_flu_ac_init_get_probe(school_l, 'low-income')).
                probe(sim_flu_ac_init_get_probe(school_m, 'med-income')).
                done()
    )
    session['stdout'] = []
Esempio n. 5
0
def sim_flu_init(session, do_force=False):
    if 'sim-flu' in session and not do_force:
        return

    if 'sim-flu' in session:
        session.pop('sim-flu')

    sites = { s:Site(s) for s in ['home', 'school-a', 'school-b']}
    probe_grp_size_site = GroupSizeProbe.by_rel('site', Site.AT, sites.values(), msg_mode=ProbeMsgMode.CUMUL)

    session['sim-flu'] = (
        Simulation().
            set().
                pragma_live_info(False).
                pragma_live_info_ts(False).
                done().
            add().
                rule(ResetSchoolDayRule(TimePoint(7))).
                rule(GoToAndBackTimeAtRule(t_at_attr='t@school')).
                probe(probe_grp_size_site).
                done().
            new_group(500).
                set_rel(Site.AT,  sites['home']).
                set_rel('home',   sites['home']).
                set_rel('school', sites['school-a']).
                done().
            new_group(500).
                set_rel(Site.AT,  sites['home']).
                set_rel('home',   sites['home']).
                set_rel('school', sites['school-b']).
                done()
    )
Esempio n. 6
0
File: sim.py Progetto: momacs/pram
def sim01(iter_cnt):
    sim = (Simulation().add([
        ProgressFluRule(),
        GroupSizeProbe.by_attr('flu',
                               'flu', ['s', 'e', 'r'],
                               msg_mode=ProbeMsgMode.CUMUL),
        Group(m=1000)
    ]).run(iter_cnt))
    print(sim.probes[0].get_msg())
    print()
Esempio n. 7
0
def sim02(iter_cnt):
    sim = (Simulation().add([
        ProgressFluIncomeRule(),
        GroupSizeProbe.by_attr('flu',
                               'flu', ['s', 'e', 'r'],
                               msg_mode=ProbeMsgMode.CUMUL),
        Group(m=500, attr={'income': 'l'}),
        Group(m=500, attr={'income': 'm'})
    ]).run(iter_cnt))
    print(sim.probes[0].get_msg())
    print()
Esempio n. 8
0
def runSimulations(n):
    for n in range(numberOfSimulations):
      (Simulation().
          set().
              pragma_autocompact(True).
              done().
          add([
              FluProgressRule(),
              Group('Susceptible', initialSusceptible, attr={ 'flu': 's' }, rel={ Site.AT: site }),
              Group('Exposed',     initialExposed,     attr={ 'flu': 'e' }, rel={ Site.AT: site }),
              Group('Infectious',  initialInfectious,  attr={ 'flu': 'i' }, rel={ Site.AT: site }),
              Group('Recovered',   initialRecovered,   attr={ 'flu': 'r' }, rel={ Site.AT: site }),
          ]).
          run(numberOfDays)
       )
      print()
def run(iter):
    (Simulation().set().rand_seed(1928).pragma_autocompact(
        True).pragma_live_info(True).pragma_live_info_ts(False).fn_group_setup(
            grp_setup).done().add().rule(
                FluProgressRule()).rule(FluLocationRule()).probe(
                    probe_flu_at(school_l, 'low-income')
                ).  # the simulation output we care about and want monitored
     probe(probe_flu_at(school_m, 'med-income')).  # ^
     done().db(fpath_db).gen_groups(
         tbl='students',
         attr_db=[],
         rel_db=[GroupDBRelSpec(name='school', col='school_id')],
         attr_fix={},
         rel_fix={
             'home': site_home
         },
         rel_at='school').done().run(iter))
Esempio n. 10
0
    def graph(self):
        if os.path.isfile(fpath_db): os.remove(fpath_db)

        te = TrajectoryEnsemble(fpath_db)

        if te.is_db_empty:
            te.set_pragma_memoize_group_ids(True)
            te.add_trajectories([
                (Simulation().
                    add([
                        SARSQuarantineIntervention(
                            SEQIHRModel('sars', beta=0.80, alpha_n=0.75, alpha_q=0.40, delta_n=0.01, delta_h=0.03, mu=0.01, chi=0.01, phi=0.20, rho=0.75, solver=ODESolver()),
                            chi=0.99,
                            i=int(intervention_onset)
                        ),
                        Group(m=95000, attr={ 'sars': 's' }),
                        Group(m= 5000, attr={ 'sars': 'e' })
                    ])
                ) for intervention_onset in TN(30,120, 75,100, 5)
            ])
            te.set_group_names(group_names)
            
            sys.stdout = open('out.dat', 'w')
            s.run(400)
            sys.stdout.close()
        
            with open('out.dat') as file:
                self.data = file.readlines()
                self.data = str(self.data)
            apple  = self.data.replace('\\n', '<br>')
            # print(apple)

             te.plot_mass_locus_line     ((1200,300), os.path.join(os.path.dirname(__file__), 'out', 'plot-line.png'), col_scheme='tableau10', opacity_min=0.35)
             te.plot_mass_locus_line_aggr((1200,300), os.path.join(os.path.dirname(__file__), 'out', 'plot-ci.png'),   col_scheme='tableau10')

            fpath_diag = os.path.join(os.path.dirname(__file__), 'out', 'sim-04.diag')
            fpath_pdf  = os.path.join(os.path.dirname(__file__), 'out', 'sim-04.pdf')
            te.traj[2].sim.gen_diagram(fpath_diag, fpath_pdf)
Esempio n. 11
0
def sim03(iter_cnt):
    sim = (Simulation().add([
        ProgressFluIncomeRule(),
        GroupSizeProbe(
            'flu-income',
            [
                GroupQry(attr={
                    'income': 'l',
                    'flu': 's'
                }),
                GroupQry(attr={
                    'income': 'l',
                    'flu': 'e'
                }),
                GroupQry(attr={
                    'income': 'l',
                    'flu': 'r'
                }),
                GroupQry(attr={
                    'income': 'm',
                    'flu': 's'
                }),
                GroupQry(attr={
                    'income': 'm',
                    'flu': 'e'
                }),
                GroupQry(attr={
                    'income': 'm',
                    'flu': 'r'
                })
            ],
            msg_mode=ProbeMsgMode.CUMUL,
        ),
        Group(m=500, attr={'income': 'l'}),
        Group(m=500, attr={'income': 'm'})
    ]).run(iter_cnt))
    print(sim.probes[0].get_msg())
    print()
Esempio n. 12
0
def sim01():
    from pram.data import GroupSizeProbe, ProbeMsgMode
    from pram.entity import Site
    from pram.rule import GoToAndBackTimeAtRule, ResetSchoolDayRule, TimePoint
    from pram.sim import Simulation

    sites = {s: Site(s) for s in ['home', 'school-a', 'school-b']}

    probe_grp_size_site = GroupSizeProbe.by_rel('site',
                                                Site.AT,
                                                sites.values(),
                                                msg_mode=ProbeMsgMode.CUMUL)

    (Simulation().add().rule(ResetSchoolDayRule(TimePoint(7))).rule(
        GoToAndBackTimeAtRule(t_at_attr='t@school')).probe(
            probe_grp_size_site).commit().new_group(500).set_rel(
                Site.AT, sites['home']).set_rel('home', sites['home']).set_rel(
                    'school',
                    sites['school-a']).commit().new_group(500).set_rel(
                        Site.AT,
                        sites['home']).set_rel('home', sites['home']).set_rel(
                            'school', sites['school-b']).commit().run(18))

    return probe_grp_size_site.get_msg()
Esempio n. 13
0
def run_simulation():
    sim_info = json.loads(request.form['runInfo'])

    initial_groups = sim_info['groups']
    included_rules = sim_info['rules']
    runs = sim_info['runs']
    time_offset = sim_info['start_time']

    add_initial_rules(time_offset)

    s = Simulation(do_keep_mass_flow_specs=True)
    #s.add_probe(probe_grp_size_site)

    for rule_name in included_rules:
        for r in rules[rule_name]:
            s.add_rule(r)

    g_index = 0
    for group in initial_groups:
        g_name = "g" + str(g_index)
        g_index = g_index + 1
        g_mass = group['n']
        g_attributes = get_attribute_dictionary(group['attributeKeys'],
                                                group['attributeValues'])
        g_relations = get_attribute_dictionary(group['relationKeys'],
                                               group['relationValues'])
        g = Group(g_name, g_mass, g_attributes)

        if not group['site'] == "":
            g.set_rel(Site.AT, sites[group['site']])

        for k, v in g_relations.items():
            g.set_rel(k, sites[v])
        s.add_group(g)

    flows = run_and_get_mass_flow(s, runs)

    return jsonify(flows)
Esempio n. 14
0
    queries=[GroupQry(attr={ 'flu': 's' }), GroupQry(attr={ 'flu': 'i' }), GroupQry(attr={ 'flu': 'r' })],
    qry_tot=None,
    var_names=['ps', 'pi', 'pr', 'ns', 'ni', 'nr'],
    persistence=ProbePersistenceMem(),
    msg_mode=ProbeMsgMode.NONE
)


# ----------------------------------------------------------------------------------------------------------------------
# (3) Simulation:

s = (Simulation().
    set_pragma_autocompact(True).
    add([
        ODESystemMass(f_sir_model, [DotMap(attr={ 'flu': 's' }), DotMap(attr={ 'flu': 'i' }), DotMap(attr={ 'flu': 'r' })], dt=0.1),
        Group(m=950, attr={ 'flu': 's' }),
        Group(m= 50, attr={ 'flu': 'i' }),
        probe
    ]).
    run(1000)
)


# ----------------------------------------------------------------------------------------------------------------------
# (4) Results:

# Time series plot (group mass):
cmap = plt.get_cmap('tab20')
series = [
    { 'var': 'ps', 'lw': 2, 'linestyle': '--', 'marker': '+', 'color': cmap(0), 'markersize': 0, 'lbl': 'Susceptible' },
    { 'var': 'pi', 'lw': 2, 'linestyle': '-',  'marker': 'o', 'color': cmap(4), 'markersize': 0, 'lbl': 'Infectious'  },
Esempio n. 15
0
        l = self.get_lambda(age)
        p0 = poisson(l).pmf(0)
        print(
            f'n: {round(group.m,2):>12}  age: {age:>3}  l: {round(l,2):>3}  p0: {round(p0,2):<4}  p1: {round(1-p0,2):<4}'
        )

        return [
            GroupSplitSpec(p=1.00,
                           attr_set={
                               'age': age + age_inc,
                               'ad': False
                           })
        ]  # testing so don't move mass

    def is_applicable(self, group, iter, t):
        return super().is_applicable(group, iter, t) and group.ha(
            ['age', 'ad'])

    def setup(self, pop, group):
        if group.ha('age'):
            return self.get_split_specs(group, 0)
        else:
            return None


# ----------------------------------------------------------------------------------------------------------------------
(Simulation().set().pragma_autocompact(True).pragma_live_info(
    False).done().add().rule(DoubleIncidenceADRule()).group(
        Group(m=100, attr={'age': 60})).done().run(40))
Esempio n. 16
0
    def __init__(self, t=TimeAlways()):
        super().__init__(t=t, name='flu-spike-evt')

    def apply(self, pop, group, iter, t):
        return [
            GroupSplitSpec(p=0.90, attr_set={ 'flu': 'i' }),
            GroupSplitSpec(p=0.10)
        ]

    def is_applicable(self, group, iter, t):
        return super().is_applicable(group, iter, t) and iter == 30 and (group.ha({ 'flu': 's' }) or group.ha({ 'flu': 'r' }))


(Simulation().
    add_probe(GroupSizeProbe.by_attr('flu', 'flu', ['s', 'i', 'r'], msg_mode=ProbeMsgMode.DISP)).
    add_rule(SIRSModel('flu', beta=0.05, gamma=0.50, alpha=0.10)).
    add_rule(FluSpikeEvent()).
    add_group(Group(m=1000, attr={ 'flu': 's' })).
    run(48)
)


# ----------------------------------------------------------------------------------------------------------------------
# dpath_cwd = os.path.dirname(__file__)
# fpath_db  = os.path.join(dpath_cwd, f'sim.sqlite3')
#
# if os.path.isfile(fpath_db):
#     os.remove(fpath_db)
#
# probe = GroupSizeProbe(
#     name='flu',
#     queries=[
Esempio n. 17
0
        if self.persistence:
            self.persistence.persist(self, [
                self.pop.m, self.pop.m_out, migrating_m, migrating_p,
                migrating_time_mean, migrating_time_sd, settled_m, settled_p
            ], iter, t, traj_id)


# ----------------------------------------------------------------------------------------------------------------------
# persistence = None
persistence = ProbePersistenceMem()
# persistence = ProbePersistenceDB(os.path.join(os.path.dirname(__file__), f'sim-03.sqlite3'), mode=ProbePersistenceMode.OVERWRITE)

# ----------------------------------------------------------------------------------------------------------------------
# Simulation:

sim = (
    Simulation().set_pragmas(analyze=False, autocompact=True).add([
        ConflictRule(severity=0.05, scale=0.2, i=[0, 3 * 12]),
        MigrationRule(env_harshness=0.05),
        PopProbe(persistence),
        Group(m=1 * 1000 * 1000,
              attr={'is-migrating': False},
              rel={Site.AT: site_conflict})
    ]).add(
        sites_dst
    )  # this line is explicitly required for translation since no agents start outside Sudan
)

# ----------------------------------------------------------------------------------------------------------------------
pram2mesa(sim, 'Migration')
Esempio n. 18
0
from pram.data import GroupSizeProbe, ProbeMsgMode
from pram.entity import Group, Site
from pram.rule import SEIRFluRule
from pram.sim import Simulation

rand_seed = 1928
probe_grp_size_flu = GroupSizeProbe.by_attr(
    'flu',
    SEIRFluRule.ATTR,
    SEIRFluRule.State,
    msg_mode=ProbeMsgMode.DISP,
    memo='Mass distribution across flu states')

(Simulation().set().rand_seed(rand_seed).done().add().rule(
    SEIRFluRule()).probe(probe_grp_size_flu).done().new_group(
        1000).done().summary(True, 0, 0, 0, 0,
                             (0, 1)).run(16).compact().summary(
                                 False, 8, 0, 0, 0, (1, 0)))

# (Simulation().
#     set().
#         rand_seed(rand_seed).
#         pragma_analyze(False).
#         pragma_autocompact(True).
#         done().
#     add().
#         rule(SEIRFluRule()).
#         probe(probe_grp_size_flu).
#         done().
#     new_group(1000).
#         done().
Esempio n. 19
0
'''
A test of the mass transfer graph.
'''

from pram.entity import Group
from pram.model.epi import SIRSModel
from pram.sim import Simulation
from pram.traj import Trajectory, TrajectoryEnsemble


# ----------------------------------------------------------------------------------------------------------------------
def get_out_dir(filename):
    return os.path.join(os.path.dirname(__file__), 'out', filename)


te = (TrajectoryEnsemble().add_trajectories([
    Trajectory(sim=(Simulation().add(
        [SIRSModel('flu', beta, 0.50, 0.10),
         Group(m=1000, attr={'flu': 's'})])),
               name=f'SIR: b={round(beta,2)}') for beta in [0.05, 0.10]
]).set_group_names([(0, 'S', Group.gen_hash(attr={'flu': 's'})),
                    (1, 'I', Group.gen_hash(attr={'flu': 'i'})),
                    (2, 'R', Group.gen_hash(attr={'flu': 'r'}))]).run(100))

# te.plot_mass_locus_line     ((1200,300), get_out_dir('_plot-line.png'), iter_range=(-1, -1))
# te.plot_mass_locus_line_aggr((1200,300), get_out_dir('_plot-aggr.png'), iter_range=(-1, -1))
# te.traj[1].plot_mass_locus_streamgraph((900,600), get_out_dir('_plot.png'), do_sort=True)
# te.traj[1].plot_heatmap((800,800), get_out_dir('_plot-heatmap.png'), (-1,20))
Esempio n. 20
0
(Simulation(6,1,24, rand_seed=rand_seed).
    new_group('g0', 1000).
        set_rel(Site.AT, sites['home']).
        set_rel('home',  sites['home']).
        set_rel('work',  sites['work-a']).
        set_rel('store', sites['store-a']).
        commit().
    new_group('g1', 1000).
        set_rel(Site.AT, sites['home']).
        set_rel('home',  sites['home']).
        set_rel('work',  sites['work-b']).
        set_rel('store', sites['store-b']).
        commit().
    new_group('g2', 100).
        set_rel(Site.AT, sites['home']).
        set_rel('home',  sites['home']).
        set_rel('work',  sites['work-c']).
        commit().
    add_rule(GotoRule(TimeInt( 8,12), 0.4, 'home',  'work',  'Some agents leave home to go to work')).
    add_rule(GotoRule(TimeInt(16,20), 0.4, 'work',  'home',  'Some agents return home from work')).
    add_rule(GotoRule(TimeInt(16,21), 0.2, 'home',  'store', 'Some agents go to a store after getting back home')).
    add_rule(GotoRule(TimeInt(17,23), 0.3, 'store', 'home',  'Some shopping agents return home from a store')).
    add_rule(GotoRule(TimePoint(24),  1.0, 'store', 'home',  'All shopping agents return home after stores close')).
    add_rule(GotoRule(TimePoint( 2),  1.0, None,    'home',  'All still-working agents return home')).
    add_probe(probe_grp_size_site).
    summary((True, True, True, True, True), (0,1)).
    run().
    summary((False, True, False, False, False), (1,1)).
    run(4)
)
Esempio n. 21
0
    'flu-status',
    progress_flu_rule.get_states(),
    msg_mode=ProbeMsgMode.DISP,
    memo='Mass distribution across flu status')
probe_grp_size_site = GroupSizeProbe.by_rel(
    'site',
    Site.AT,
    sites.values(),
    msg_mode=ProbeMsgMode.DISP,
    memo='Mass distribution across sites')

# ----------------------------------------------------------------------------------------------------------------------
# (1) Simulations testing the basic operations on groups and rules:

# (1.1) A single-group, single-rule (1g.1r) simulation:
s = Simulation()
s.add_rule(progress_flu_rule)
s.add_probe(probe_grp_size_flu)
s.add_group(Group('g0', 1000, {'flu-status': 's'}))
s.run(24)

# (1.2) A single-group, two-rule (1g.2r) simulation:
# s = Simulation()
# s.add_rule(progress_flu_rule)
# s.add_rule(GoToRule(TimeInt(10,16), 0.4, 'home', 'work'))
# s.add_probe(probe_grp_size_flu)
# s.add_group(Group('g0', 1000, { 'flu-status': 's' }, { Site.AT: sites['home'], 'home': sites['home'], 'work': sites['work'] }))
# s.run(24)

# (1.3) As above (1g.2r), but with reversed rule order (which should not, and does not, change the results):
# s = Simulation()
Esempio n. 22
0
# ----------------------------------------------------------------------------------------------------------------------
sites = {'home': Site('h'), 'work': Site('w')}

probe_grp_size_flu = GroupSizeProbe.by_attr(
    'flu',
    'flu-stage',
    AttrFluStage,
    msg_mode=ProbeMsgMode.DISP,
    memo='Mass distribution across flu stages')

# ----------------------------------------------------------------------------------------------------------------------
# (1) A proper simulation:

print('(1)')
s = (Simulation(TimeHour(6), 16).add_rule(ProgressFluRule()).add_rule(
    GoToAndBackTimeAtRule()).add_probe(probe_grp_size_flu).new_group(
        '0', 1000).set_attr('flu-stage', AttrFluStage.NO).commit())

print(f'Attributes : {s.last_run.attr_used}')
print(f'Relations  : {s.last_run.rel_used}')

print()

# ----------------------------------------------------------------------------------------------------------------------
# (2) Improper simulations (rendered proper automatically):

# (2.1) A group has superfluous attributes and relations, but automatic group pruning saved the day:
print('(2.1)')
(Simulation(TimeHour(6), 16).set_pragma_autoprune_groups(True).add_rule(
    ProgressFluRule()).add_probe(probe_grp_size_flu).new_group(
        '0',
Esempio n. 23
0

probe_grp_size_flu = GroupSizeProbe.by_attr(
    'flu',
    'flu', ['S', 'I', 'R'],
    msg_mode=ProbeMsgMode.DISP,
    persistance=ProbePersistanceDB(),
    memo='Mass distribution across flu status')

p = GroupSizeProbe.by_attr('flu',
                           'flu', ['S', 'I', 'R'],
                           persistance=ProbePersistanceDB())

(Simulation().add_probe(
    GroupSizeProbe.by_attr('flu',
                           'flu', ['S', 'I', 'R'],
                           msg_mode=ProbeMsgMode.DISP)).add_probe(p).add_rule(
                               SIRRule()).add_group(
                                   Group(m=1000, attr={'flu': 'S'})).run(26))

series = [{
    'var': 'p0',
    'lw': 0.75,
    'linestyle': '-',
    'marker': 'o',
    'color': 'red',
    'markersize': 0,
    'lbl': 'S'
}, {
    'var': 'p1',
    'lw': 0.75,
    'linestyle': '--',
Esempio n. 24
0
# (0) Init:

rand_seed = 1928

pragma_live_info = True
pragma_live_info_ts = False

fpath_db_in = os.path.join(os.path.dirname(__file__), '..', '..', '..', 'data',
                           'allegheny-county', 'allegheny-students.sqlite3')

# ----------------------------------------------------------------------------------------------------------------------
# (1) Sites:

sites = Simulation.gen_sites_from_db(
    fpath_db_in,
    lambda fpath_db:
    {'school': Site.gen_from_db(fpath_db, 'schools', 'sp_id', 'school', [])},
    pragma_live_info=pragma_live_info,
    pragma_live_info_ts=pragma_live_info_ts)

site_home = Site('home')

# ----------------------------------------------------------------------------------------------------------------------
# (2) Probes:

# n_schools = 8
# few_schools = [sites['school'][k] for k in list(sites['school'].keys())[:n_schools]]
#
# probe_grp_size_few_schools = GroupSizeProbe('school', [GroupQry(rel={ Site.AT: s }) for s in few_schools], msg_mode=ProbeMsgMode.DISP)

fpath_db = os.path.join(os.path.dirname(__file__), 'out-test-03c.sqlite3')
Esempio n. 25
0
# ----------------------------------------------------------------------------------------------------------------------
if os.path.isfile(fpath_db): os.remove(fpath_db)

te = TrajectoryEnsemble(fpath_db)
# te = TrajectoryEnsemble(fpath_db, cluster_inf=ClusterInf(address='auto'))
# te = TrajectoryEnsemble(fpath_db, cluster_inf=ClusterInf(num_cpus=6, memory=500*1024*1024, object_store_memory=500*1024*1024, include_webui=True))

if te.is_db_empty:
    te.set_pragma_memoize_group_ids(True)
    te.add_trajectories([
        Trajectory(
            (Simulation().
                add([
                    SIRModel('flu', beta=0.10, gamma=0.05, solver=MCSolver()),
                    SIRModel('flu', beta=0.50, gamma=U(0.01, 0.15), i=[int(5 + TN(0,50, 5,10)), 50], solver=MCSolver()),
                    FluProcess(i=[50,0], p_max=None, a=3.0, scale=flu_proc_scale),
                    Group(m=950, attr={ 'flu': 's' }),
                    Group(m= 50, attr={ 'flu': 'i' })
                ])
            )
        ) for flu_proc_scale in U(1,5, 1)
    ])
    te.set_group_names(group_names)
    te.run(120)


# Visualize:
te.plot_mass_locus_line     ((1200,300), os.path.join(os.path.dirname(__file__), 'out', '_plot-line.png'), opacity_min=0.2)
te.plot_mass_locus_line_aggr((1200,300), os.path.join(os.path.dirname(__file__), 'out', '_plot-iqr.png'))
Esempio n. 26
0
                       var_names=['ps', 'pi', 'pr', 'ns', 'ni', 'nr'],
                       persistence=ProbePersistenceMem(),
                       msg_mode=ProbeMsgMode.NONE)

# ----------------------------------------------------------------------------------------------------------------------
# (3) Simulation:

s = (
    Simulation().set_pragma_autocompact(True).add([
        ODESystemMass(f_sir_model, [
            DotMap(attr={'flu': 's'}),
            DotMap(attr={'flu': 'i'}),
            DotMap(attr={'flu': 'r'})
        ],
                      dt=0.1),
        # FluEvent(),
        # FluLinProcess(),
        # FluExpProcess(),
        FluGammaProcess(),
        # ODESystemMass(f_decay, [DotMap(attr={ 'flu': 'r' }), DotMap(attr={ 'flu': 's' })], dt=0.1),
        Group(m=950, attr={'flu': 's'}),
        Group(m=50, attr={'flu': 'i'}),
        probe
    ]).run(3000))

# ----------------------------------------------------------------------------------------------------------------------
# (4) Results:

# Time series plot (group mass):
cmap = plt.get_cmap('tab20')
series = [{
    'var': 'ps',
Esempio n. 27
0
 Simulation(pop_hist_len=0).set().pragma_analyze(
     False).pragma_autocompact(True).pragma_comp_summary(
         False).pragma_fractional_mass(False).
 pragma_live_info(False).fn_group_setup(grp_setup).done().add([
     DailyBehaviorRule('school', p_home_IS=0.90),
     DailyBehaviorRule('work', p_home_IS=0.90),
     # DiseaseRule('school', r0=1.8, p_E_IA=0.40, p_IA_IS=0.40, p_IS_R=0.40, p_home_E=0.025, p_social_E=0.05, soc_dist_comp_young=sdc, soc_dist_comp_old=sdc, p_fat_by_age_group=p_covid19_fat_by_age_group_comb),
     # DiseaseRule('work',   r0=1.8, p_E_IA=0.40, p_IA_IS=0.40, p_IS_R=0.40, p_home_E=0.025, p_social_E=0.05, soc_dist_comp_young=sdc, soc_dist_comp_old=sdc, p_fat_by_age_group=p_covid19_fat_by_age_group_comb),
     DiseaseRule2(
         'school',
         SEI2RModelParams.by_clinical_obs(s0=2,
                                          r0=1.8,
                                          incub_period=5.1 * 2,
                                          asympt_period=2.5 * 2,
                                          inf_dur=5.0 * 2),
         p_home_E=0.0,
         p_social_E=0.95,
         soc_dist_comp_young=0.66,
         soc_dist_comp_old=0.45,
         p_fat_by_age_group=p_covid19_fat_by_age_group_comb),
     DiseaseRule2(
         'work',
         SEI2RModelParams.by_clinical_obs(s0=2,
                                          r0=1.8,
                                          incub_period=5.1 * 2,
                                          asympt_period=2.5 * 2,
                                          inf_dur=5.0 * 2),
         p_home_E=0.0,
         p_social_E=0.95,
         soc_dist_comp_young=0.66,
         soc_dist_comp_old=0.45,
         p_fat_by_age_group=p_covid19_fat_by_age_group_comb),
     ClosedownIntervention(prop_pop_IS_threshold=0.01),
     ReopenIntervention(prop_pop_IS_threshold=0.02),
     PopProbe(persistence, do_print=False),
 ]))
Esempio n. 28
0
if os.path.isfile(fpath_db): os.remove(fpath_db)

te = TrajectoryEnsemble(fpath_db)

if te.is_db_empty:
    te.set_pragma_memoize_group_ids(True)
    te.add_trajectories([(Simulation().add([
        SARSQuarantineIntervention(SEQIHRModel('sars',
                                               beta=0.80,
                                               alpha_n=0.75,
                                               alpha_q=0.40,
                                               delta_n=0.01,
                                               delta_h=0.03,
                                               mu=0.01,
                                               chi=0.01,
                                               phi=0.20,
                                               rho=0.75,
                                               solver=ODESolver()),
                                   chi=0.99,
                                   i=int(intervention_onset)),
        Group(m=95000, attr={'sars': 's'}),
        Group(m=5000, attr={'sars': 'e'})
    ])) for intervention_onset in TN(30, 120, 75, 100, 5)])
    te.set_group_names(group_names)
    te.run(400)

# te.plot_mass_locus_line     ((1200,300), os.path.join(os.path.dirname(__file__), 'out', 'plot-line.png'), col_scheme='tableau10', opacity_min=0.35)
# te.plot_mass_locus_line_aggr((1200,300), os.path.join(os.path.dirname(__file__), 'out', 'plot-ci.png'),   col_scheme='tableau10')

# fpath_diag = os.path.join(os.path.dirname(__file__), 'out', 'sim-04.diag')
Esempio n. 29
0
    def setup(self, pop, group):
        return [GroupSplitSpec(p=1.0, attr_set={"value": 1000})]


old_p = GroupSizeProbe.by_attr('stage',
                               'stage', ['c', 'success', 'failure'],
                               persistance=ProbePersistanceMem(),
                               msg_mode=ProbeMsgMode.CUMUL)

probe2 = GroupSizeProbe.by_attr("value",
                                "value", ['c', 'success', 'failure'],
                                persistance=ProbePersistanceMem(),
                                msg_mode=ProbeMsgMode.DISP)

# c_group = Group(name="c", m = 100, attr = {"stage" : "c", "value": 1000})
# success_group = Group(name="success", m = 100, attr ={"stage":"success", "value" : 1000})
# failure_group = Group(name="failure", m = 100, attr = {"stage": "failure", "value" : 1000})

c_group = Group(name="c", m=100, attr={"stage": "c"})
success_group = Group(name="success", m=100, attr={"stage": "success"})
failure_group = Group(name="failure", m=100, attr={"stage": "failure"})

sim = (Simulation().add([
    SimpleMultiplyCombined(), old_p, probe2, c_group, success_group,
    failure_group
]).run(10))

print(sim.probes[0].get_msg())
print(sim.probes[1].get_msg())
print()
Esempio n. 30
0
import random

from scipy.stats import poisson

from pram.entity import Group, Site
from pram.rule import SegregationModel
from pram.sim import Simulation
from pram.traj import Trajectory, TrajectoryEnsemble

# ----------------------------------------------------------------------------------------------------------------------
loc = [Site('a'), Site('b')]

s = (Simulation().set().pragma_autocompact(True).pragma_live_info(
    False).done().add([
        SegregationModel('team', len(loc)),
        Group(m=200, attr={'team': 'blue'}, rel={Site.AT: loc[0]}),
        Group(m=300, attr={'team': 'blue'}, rel={Site.AT: loc[1]}),
        Group(m=100, attr={'team': 'red'}, rel={Site.AT: loc[0]}),
        Group(m=400, attr={'team': 'red'}, rel={Site.AT: loc[1]})
    ]))

# ----------------------------------------------------------------------------------------------------------------------
te = (TrajectoryEnsemble().add_trajectory(Trajectory(
    'segregation', None, s)).set_group_names([
        (0, 'Blue A',
         Group.gen_hash(attr={'team': 'blue'}, rel={Site.AT: loc[0]})),
        (1, 'Blue B',
         Group.gen_hash(attr={'team': 'blue'}, rel={Site.AT: loc[1]})),
        (2, 'Red A', Group.gen_hash(attr={'team': 'red'},
                                    rel={Site.AT: loc[0]})),
        (3, 'Red B', Group.gen_hash(attr={'team': 'red'},
                                    rel={Site.AT: loc[1]}))