Example #1
0
def get_probe_flu_at(school, name=None):
    return GroupSizeProbe(
        name=name or school.name,
        queries=[
            GroupQry(attr={ 'flu': 's' }, rel={ 'school': school }),
            GroupQry(attr={ 'flu': 'i' }, rel={ 'school': school }),
            GroupQry(attr={ 'flu': 'r' }, rel={ 'school': school })
        ],
        qry_tot=GroupQry(rel={ 'school': school }),
        msg_mode=ProbeMsgMode.DISP
    )
Example #2
0
def sim_flu_ac_init_get_probe(school, name=None):
    return GroupSizeProbe(
        name=name or str(school.name),
        queries=[
            GroupQry(attr={ 'flu': 's' }, rel={ 'school': school }),
            GroupQry(attr={ 'flu': 'e' }, rel={ 'school': school }),
            GroupQry(attr={ 'flu': 'r' }, rel={ 'school': school })
        ],
        qry_tot=GroupQry(rel={ 'school': school }),
        persistance=None,  # pp,
        var_names=['ps', 'pe', 'pr', 'ns', 'ne', 'nr']
    )
Example #3
0
def probe_flu_at(school, name=None):
    return GroupSizeProbe(
        name=name or school.name,
        queries=[
            GroupQry(attr={ 'flu': 's' }, rel={ 'school': school }),
            GroupQry(attr={ 'flu': 'i' }, rel={ 'school': school }),
            GroupQry(attr={ 'flu': 'r' }, rel={ 'school': school })
        ],
        qry_tot=GroupQry(rel={ 'school': school }),
        persistance=pp,
        var_names=['ps', 'pi', 'pr', 'ns', 'ni', 'nr']
    )
Example #4
0
def probe_grp_size_flu_school(name, school, pp):
    return GroupSizeProbe(name=name,
                          queries=[
                              GroupQry(attr={'flu': 's'},
                                       rel={'school': school}),
                              GroupQry(attr={'flu': 'e'},
                                       rel={'school': school}),
                              GroupQry(attr={'flu': 'r'},
                                       rel={'school': school})
                          ],
                          qry_tot=GroupQry(rel={'school': school}),
                          persistence=pp,
                          var_names=['ps', 'pe', 'pr', 'ns', 'ne', 'nr'])
Example #5
0
def probes_ls():
    school_l  = Site(450149323)  # 88% low income students
    school_m  = Site(450067740)  #  7% low income students

    return GroupSizeProbe(
        name=name or str(school.name),
        queries=[
            GroupQry(attr={ 'flu': 's' }, rel={ 'school': school }),
            GroupQry(attr={ 'flu': 'e' }, rel={ 'school': school }),
            GroupQry(attr={ 'flu': 'r' }, rel={ 'school': school })
        ],
        qry_tot=GroupQry(rel={ 'school': school }),
        persistance=pp,
        var_names=['ps', 'pe', 'pr', 'ns', 'ne', 'nr']
    )

    probes = [
        { 'name': 'Low-income school',    'inf': '88% low income students', 'persistenceName': 'low-income', 'id': 450149323 },
        { 'name': 'medium-income school', 'inf':  '7% low income students', 'persistenceName': 'med-income', 'id': 450067740 }
    ]
    return jsonify({ 'res': True, 'probes': probes })
Example #6
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()
Example #7
0
    s,i,r = state
    n = s + i + r
    return [
        -beta * s * i / n,
         beta * s * i / n - gamma * i,
                            gamma * i
    ]


# ----------------------------------------------------------------------------------------------------------------------
# (2) Probe:

probe = GroupSizeProbe(
    name='flu',
    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
Example #8
0
File: sim.py Project: momacs/pram
# ----------------------------------------------------------------------------------------------------------------------
# (1) Simulation (two locations)

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

probe_loc = GroupSizeProbe.by_rel('loc',
                                  Site.AT,
                                  loc,
                                  msg_mode=ProbeMsgMode.DISP)
probe_sim = GroupSizeProbe(name='sim',
                           queries=[
                               GroupQry(attr={'team': 'blue'},
                                        rel={Site.AT: loc[0]}),
                               GroupQry(attr={'team': 'red'},
                                        rel={Site.AT: loc[0]}),
                               GroupQry(attr={'team': 'blue'},
                                        rel={Site.AT: loc[1]}),
                               GroupQry(attr={'team': 'red'},
                                        rel={Site.AT: loc[1]})
                           ],
                           qry_tot=None,
                           msg_mode=ProbeMsgMode.DISP)

(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]}),
        # probe_loc  # the distribution should tend to 50%-50%
Example #9
0
File: sim.py Project: momacs/pram
site_home = Site('home')

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

fpath_db_out = os.path.join(os.path.dirname(__file__), 'out.sqlite3')

if os.path.isfile(fpath_db_out):
    os.remove(fpath_db_out)

pp = ProbePersistenceDB(fpath_db_out, flush_every=1)

probe_school_pop_size = GroupSizeProbe(
    name='school-pop-size',
    queries=[GroupQry(rel={Site.AT: s}) for s in sites['school'].values()],
    persistence=pp,
    var_names=[f'p{i}' for i in range(len(sites['school']))] +
    [f'n{i}' for i in range(len(sites['school']))],
    memo=f'Population size across all schools')

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

(Simulation().add_rule(ResetSchoolDayRule(TimePoint(7))).add_rule(
    GoToAndBackTimeAtRule(t_at_attr='t@school')).add_probe(
        probe_school_pop_size).gen_groups_from_db(
            fpath_db_in,
            tbl='people',
            attr_fix={},
            rel_fix={
                'home': site_home
Example #10
0
    i += 1
    print(eq * "=", "starting sim {}".format(i), eq * "=")
    sim = (Simulation().add([
        StartupLocationRule(),
        GroupSizeProbe(
            'startup-location',
            [
                GroupQry(attr={
                    'location': 'usa',
                    'stage': 'success'
                }),
                GroupQry(attr={
                    'location': 'usa',
                    'stage': 'failure'
                }),
                GroupQry(attr={
                    'location': 'others',
                    'stage': 'success'
                }),
                GroupQry(attr={
                    'location': 'others',
                    'stage': 'failure'
                }),
            ],
            msg_mode=ProbeMsgMode.CUMUL,
        ),
        Group(m=10000, attr={'location': 'usa'}),
        Group(m=10000, attr={'location': 'others'})
    ]).run(10))
    print(sim.probes[0].get_msg())
    print()
Example #11
0
            p = 0.1

        return [
            GroupSplitSpec(p=p, attr_set={"form": "c"}),
            GroupSplitSpec(p=1 - p)
        ]

    def is_applicable(self, group, iter, t):
        return super().is_applicable(
            group, iter, t) and group.m > 0 and group.attr['form'] == 's'


#probe including snakes
probe_grp_size_attr = GroupSizeProbe('form', [
    GroupQry(attr={'form': 'm'}),
    GroupQry(attr={'form': 'h'}),
    GroupQry(attr={'form': 's'})
],
                                     msg_mode=ProbeMsgMode.DISP)

#probe not including snakes
#probe_grp_size_attr = GroupSizeProbe('form', [GroupQry(attr={ 'form': 'm' }), GroupQry(attr={ 'form': 'h' })], msg_mode=ProbeMsgMode.DISP)

# 1 carbon => 1 mouse
# 5 carbon => 1 hawk
# 3 carbon => 1 snake

#1750 mice
mice = Group("Mice", 1750)
mice.attr['form'] = "m"

#100 hawks
Example #12
0
def main():
    # SAMPLE SIMULATION FROM 09-segregation
    import os

    from pram.data import GroupSizeProbe, ProbeMsgMode, ProbePersistenceDB
    from pram.entity import Group, GroupQry, Site, GroupSplitSpec
    from pram.rule import SegregationModel
    from pram.sim import Simulation

    # -----------------------------------------------------------------------------------------------------------------
    # (1) Simulation (two locations)

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

    def gs(pop, group):
        return [
            GroupSplitSpec(p=0.7, attr_set={'foobar': 'foo'}),
            GroupSplitSpec(p=0.3, attr_set={'foobar': 'bar'})
        ]

    probe_loc = GroupSizeProbe.by_rel('loc',
                                      Site.AT,
                                      loc,
                                      msg_mode=ProbeMsgMode.DISP)
    probe_sim = GroupSizeProbe(name='sim',
                               queries=[
                                   GroupQry(attr={'team': 'blue'},
                                            rel={Site.AT: loc[0]}),
                                   GroupQry(attr={'team': 'red'},
                                            rel={Site.AT: loc[0]}),
                                   GroupQry(attr={'team': 'blue'},
                                            rel={Site.AT: loc[1]}),
                                   GroupQry(attr={'team': 'red'},
                                            rel={Site.AT: loc[1]})
                               ],
                               qry_tot=None,
                               persistence=ProbePersistenceDB(),
                               msg_mode=ProbeMsgMode.DISP)

    s = (
        Simulation().set().pragma_autocompact(True).pragma_live_info(False).
        fn_group_setup(gs).done().add([
            SegregationModel('team', len(loc)),
            # TranslateEverything(),
            # LambdasAndArguments(),
            Group(m=200,
                  attr={'team': 'blue'},
                  rel={
                      Site.AT: loc[0],
                      'origin': loc[0]
                  }),
            Group(m=300,
                  attr={'team': 'blue'},
                  rel={
                      Site.AT: loc[1],
                      'origin': loc[1]
                  }),
            Group(m=100,
                  attr={'team': 'red'},
                  rel={
                      Site.AT: loc[0],
                      'origin': loc[0]
                  }),
            Group(m=400,
                  attr={'team': 'red'},
                  rel={
                      Site.AT: loc[1],
                      'origin': loc[1]
                  }),
            probe_loc,  # the distribution should tend to 50%-50%
            probe_sim  # mass should tend to move towards two of the four sites
            # fixed naming issue in pram/sim.py line 815
        ]))
    pram2mesa(s, 'TestSimultaneousGrammar')
Example #13
0
from pram.sim import Simulation
from pram.entity import AttrFluStage, GroupQry, GroupSplitSpec
from pram.data import GroupSizeProbe, ProbeMsgMode, ProbePersistenceDB
from pram.rule import Rule, TimeInt

from rules import ProgressFluRule

# ----------------------------------------------------------------------------------------------------------------------
rand_seed = 1928

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=[
                           GroupQry(attr={'flu-stage': AttrFluStage.NO}),
                           GroupQry(attr={'flu-stage': AttrFluStage.ASYMPT}),
                           GroupQry(attr={'flu-stage': AttrFluStage.SYMPT})
                       ],
                       qry_tot=None,
                       var_names=['pn', 'pa', 'ps', 'nn', 'na', 'ns'],
                       persistence=ProbePersistenceDB(fpath_db))

(Simulation(6, 1, 16, rand_seed=rand_seed).add_rule(
    ProgressFluRule()).add_probe(probe).new_group('0', 1000).set_attr(
        'flu-stage', AttrFluStage.NO).commit().run())
Example #14
0
        'work'    : Site.gen_from_db(fpath_db, 'workplaces', 'sp_id',   'work',     [])
    },
    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_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')

if os.path.isfile(fpath_db):
    os.remove(fpath_db)

pp = ProbePersistenceDB(fpath_db)


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

(Simulation().
    set().
        rand_seed(rand_seed).
Example #15
0
File: sim.py Project: momacs/pram
sites = {'home': Site('home')}

for s in school_specs:
    # Site:
    site_name = f'school-{s.name}'
    site = Site(site_name)
    sites[site_name] = site

    # Probe:
    probes_grp_size_flu_school.append(
        GroupSizeProbe(name=f'flu-{s.name}',
                       queries=[
                           GroupQry(attr={'flu': 's'}, rel={'school': site}),
                           GroupQry(attr={'flu': 'i'}, rel={'school': site}),
                           GroupQry(attr={'flu': 'r'}, rel={'school': site})
                       ],
                       qry_tot=GroupQry(rel={'school': site}),
                       var_names=['ps', 'pi', 'pr', 'ns', 'ni', 'nr'],
                       persistence=probe_persistence,
                       memo=f'Flu at school {s.name.upper()}'))

probe_grp_size_flu = GroupSizeProbe.by_attr(
    'flu',
    'flu', ['s', 'i', 'r'],
    msg_mode=ProbeMsgMode.DISP,
    memo='Mass distribution across flu stages')
probe_grp_size_site = GroupSizeProbe.by_rel(
    'site',
    Site.AT,
    sites.values(),
    msg_mode=ProbeMsgMode.DISP,
Example #16
0
if os.path.isfile(fpath_db_out):
    os.remove(fpath_db_out)

pp = ProbePersistenceDB(fpath_db_out)

home     = Site('home')
school_l = Site('school-l')
school_m = Site('school-m')

probe_grp_size_flu_school_l = GroupSizeProbe(
    name='flu-school-l',
    queries=[
        GroupQry(attr={ 'flu': 's' }, rel={ 'school': school_l }),
        GroupQry(attr={ 'flu': 'e' }, rel={ 'school': school_l }),
        GroupQry(attr={ 'flu': 'r' }, rel={ 'school': school_l })
    ],
    qry_tot=GroupQry(rel={ 'school': school_l }),
    persistence=pp,
    var_names=['ps', 'pe', 'pr', 'ns', 'ne', 'nr'],
    memo='Population size across flu states for low-income school'
)

probe_grp_size_flu_school_m = GroupSizeProbe(
    name='flu-school-m',
    queries=[
        GroupQry(attr={ 'flu': 's' }, rel={ 'school': school_m }),
        GroupQry(attr={ 'flu': 'e' }, rel={ 'school': school_m }),
        GroupQry(attr={ 'flu': 'r' }, rel={ 'school': school_m })
    ],
    qry_tot=GroupQry(rel={ 'school': school_m }),
    persistence=pp,
Example #17
0
                               ],
                               rel_at='home')
    print('done.')

    print('Saving groups... ', end='')
    with gzip.GzipFile(fpath_groups, 'wb') as f:
        pickle.dump(groups, f)
    print('done.')

inf('groups', groups, do_calc_size_groups)

# groups: 164,459  (175.2M)
# file  5.1M

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

n_schools = 8
few_schools = [
    sites['school'][k] for k in list(sites['school'].keys())[:n_schools]
]

probe_grp_size_schools = GroupSizeProbe(
    'school', [GroupQry(rel={Site.AT: v}) for v in few_schools])

# sys.exit(0)

(Simulation(6, 1, 16, rand_seed=rand_seed).add_groups(groups).add_rule(
    ResetDayRule(TimePoint(7))).add_rule(
        AttendSchoolRule()).add_probe(probe_grp_size_schools).run())
Example #18
0
'''
A simulation implementing the flu progression model.  This version tests probe database persistence.
'''

from pram.sim import Simulation
from pram.entity import GroupQry, GroupSplitSpec
from pram.data import GroupSizeProbe, ProbeMsgMode, ProbePersistenceDB
from pram.rule import Rule, TimeInt

from rules import ProgressFluRule

# ----------------------------------------------------------------------------------------------------------------------
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=[
                           GroupQry(attr={'flu': 's'}),
                           GroupQry(attr={'flu': 'i'}),
                           GroupQry(attr={'flu': 'r'})
                       ],
                       qry_tot=None,
                       var_names=['pn', 'pa', 'ps', 'nn', 'na', 'ns'],
                       persistence=ProbePersistenceDB(fpath_db))

(Simulation().add_rule(ProgressFluRule()).add_probe(probe).new_group(
    '0', 1000).set_attr('flu', 's').done().run(16))
Example #19
0
def f_decay_a(t, state):
    n1, n2 = state
    return [-l_a * n1, l_a * n1]

def f_decay_b(t, state):
    n1, n2 = state
    return [-l_b * n1, l_b * n1]


# ----------------------------------------------------------------------------------------------------------------------
# (2) Probe:

probe_u = GroupSizeProbe(
    name='sub',  # substance
    queries=[GroupQry(attr={ 'sub-a': 'u' }), GroupQry(attr={ 'sub-b': 'u' })],
    qry_tot=None,
    var_names=['pau', 'pbu', 'nau', 'nbu'],  # pau - proportion of substance A undecayed, etc.
    persistence=ProbePersistenceMem(),
    msg_mode=ProbeMsgMode.NONE
)

probe_d = GroupSizeProbe(
    name='sub',  # substance
    queries=[GroupQry(attr={ 'sub-a': 'd' }), GroupQry(attr={ 'sub-b': 'd' })],
    qry_tot=None,
    var_names=['pad', 'pbd', 'nad', 'nbd'],  # pad - proportion of substance A decayed, etc.
    persistence=ProbePersistenceMem(),
    msg_mode=ProbeMsgMode.NONE
)


# ----------------------------------------------------------------------------------------------------------------------