예제 #1
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
예제 #2
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'] = []
예제 #3
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)
예제 #4
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()
    )
예제 #5
0
파일: app.py 프로젝트: PatHealy/PRAMity
def add_initial_rules(time_offset):
    "Imports rules built into pram and inserts them into the rules dictionary"
    global sites
    sites = {
        s: Site(s)
        for s in ['home', 'work-a', 'work-b', 'work-c', 'store-a', 'store-b']
    }
    mall_sites_names = [
        "big_theater", "down_store1", "down_store2", "down_store3",
        "down_store4", "down_store5", "down_store6", "down_store7",
        "down_store8", "down_store9", "big_down_store10", "big_down_store11",
        "big_down_store12", "up_store1", "up_store2", "up_store3", "up_store4",
        "up_store5", "up_store6", "up_store7", "up_store8", "up_store9",
        "big_down_courtyard_1", "big_down_courtyard_2", "big_down_courtyard_3",
        "big_down_courtyard_4"
    ]
    mall_sites = [Site(s) for s in mall_sites_names]
    for i in range(len(mall_sites)):
        sites[mall_sites_names[i]] = mall_sites[i]

    #rules["Mall Movement"] = [MallMovement(0.2, mall_sites)]
    rules["Mall Flu"] = [MallFlu(1, 0.2, mall_sites)]

    rules["Simple Flu Progress Rule"] = [
        SimpleFluProgress(
            'flu-status', {
                's': [0.95, 0.05, 0.00],
                'i': [0.00, 0.50, 0.50],
                'r': [0.10, 0.00, 0.90]
            }, sites['home'])
    ]
    # rules["Home-Work-School Rules"] = [SimpleGoTo(TimeInt( (8 - time_offset)%24,(12 - time_offset)%24), 0.4, 'home',  'work',  'Some agents leave home to go to work'),
    # 	SimpleGoTo(TimeInt((16- time_offset)%24,(20- time_offset)%24), 0.4, 'work',  'home',  'Some agents return home from work'),
    # 	SimpleGoTo(TimeInt((16- time_offset)%24,(21- time_offset)%24), 0.2, 'home',  'store', 'Some agents go to a store after getting back home'),
    # 	SimpleGoTo(TimeInt((17- time_offset)%24,(23- time_offset)%24), 0.3, 'store', 'home',  'Some shopping agents return home from a store'),
    # 	SimpleGoTo(TimePoint((24- time_offset)%25),  1.0, 'store', 'home',  'All shopping agents return home after stores close'),
    # 	SimpleGoTo(TimePoint( (2- time_offset)%25),  1.0, None, 'home',  'All still-working agents return home')]

    global probe_grp_size_site
    probe_grp_size_site = GroupSizeProbe.by_rel(
        'site',
        Site.AT,
        sites.values(),
        msg_mode=ProbeMsgMode.DISP,
        memo='Mass distribution across sites')
    return
예제 #6
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 })
예제 #7
0
def pop_db_gen():
    # Add foreign keys to the 'people' table:
    # BEGIN TRANSACTION;
    # CREATE TABLE people_tmp (sp_id INTEGER, sp_hh_id INTEGER, age INTEGER, sex TEXT, race INTEGER, relate INTEGER, income INTEGER, school_id INTEGER, work_id INTEGER);
    # INSERT INTO people_tmp SELECT sp_id, sp_hh_id, age, sex, race, relate, income, school_id, work_id FROM people;
    # DROP TABLE people;
    # CREATE TABLE people     (sp_id INTEGER, sp_hh_id INTEGER, age INTEGER, sex TEXT, race INTEGER, relate INTEGER, income INTEGER, school_id INTEGER, work_id INTEGER, CONSTRAINT fk__people__households FOREIGN KEY (sp_hh_id) REFERENCES households (sp_id), CONSTRAINT fk__people__schools FOREIGN KEY (school_id) REFERENCES schools (sp_id), CONSTRAINT fk__people__workplaces FOREIGN KEY (work_id) REFERENCES workplaces (sp_id));
    # INSERT INTO people     SELECT sp_id, sp_hh_id, age, sex, race, relate, income, school_id, work_id FROM people_tmp;
    # DROP TABLE people_tmp;
    # COMMIT;

    if not 'sim-flu-ac' in session:
        return jsonify({ 'res': False, 'err': 'The simulation has not been initialized' })

    json = request.get_json()

    fpath = db_get_fpath(json['db'])
    if not fpath:
        return jsonify({ 'res': False, 'err': 'Incorrect database specified' })

    attr_db = json['attr_db']
    rel_db = json['rel_db']

    site_home = Site('home')

    stdout = io.StringIO()
    with redirect_stdout(stdout):
        sim = session['sim-flu-ac']
        sim.gen_groups_from_db(
            fpath_db   = fpath,
            tbl        = json['tbl'],
            attr_db    = attr_db,
            rel_db     = [GroupDBRelSpec(name=rel['name'], col=rel['col']) for rel in rel_db],
            attr_fix   = {},
            rel_fix    = { 'home': site_home },
            rel_at     = 'school',
            is_verbose = False
        )
    session['stdout'].append(stdout.getvalue())

    return jsonify({ 'res': True, 'pop': sim.get_state()['pop'], 'stdout': session['stdout'] })
예제 #8
0
파일: __init__-01.py 프로젝트: momacs/pram
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()
예제 #9
0
This simulation is an extension of 'sim-02.py' and adds the eventual settlement of the migrating population in one of
the counties bordering the conflict country.
"""

from pram.data import Probe, ProbePersistenceMem, Var
from pram.entity import Group, GroupQry, GroupSplitSpec, Site
from pram.rule import IterAlways, TimeAlways, Rule
from pram.sim import Simulation

import random
import statistics

from pram2mesa.pram2mesa import pram2mesa

# ----------------------------------------------------------------------------------------------------------------------
site_sudan = Site('Sudan')
site_ethiopia = Site('Ethiopia', attr={'travel-time': 8})  # [months]
site_chad = Site('Chad', attr={'travel-time': 9})
site_egypt = Site('Egypt', attr={'travel-time': 10})
site_libya = Site('Libya', attr={'travel-time': 11})

site_conflict = site_sudan
sites_dst = [site_egypt, site_ethiopia, site_chad,
             site_libya]  # migration destinations


# ----------------------------------------------------------------------------------------------------------------------
class ConflictRule(Rule):
    """
    Conflict causes death and migration.  The probability of death scales with the conflict's severity and scale
    while the probability of migration scales with the conflict's scale only.  Multipliers for both factors are exposed
예제 #10
0
'''
A test of the mass transfer graph for the segregation model.
'''

import math
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]})),
예제 #11
0
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')
예제 #12
0
'''
A simulation of agents going from home to work and then, sometimes, to a store and back home again.
'''

from pram.data   import GroupSizeProbe
from pram.entity import GroupQry, Site
from pram.rule   import GotoRule, TimeInt, TimePoint
from pram.sim    import Simulation


rand_seed = 1928


# ----------------------------------------------------------------------------------------------------------------------
sites = {
    'home'    : Site('home'),
    'work-a'  : Site('work-a'),
    'work-b'  : Site('work-b'),
    'work-c'  : Site('work-c'),
    'store-a' : Site('store-a'),
    'store-b' : Site('store-b')
}

probe_grp_size_site = GroupSizeProbe.by_rel('site', Site.AT, sites.values(), memo='Mass distribution across sites')

(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']).
예제 #13
0
파일: seir.py 프로젝트: momacs/simsearch
  print(initialSusceptible,end=' ')
  print(initialExposed,end=' ')
  print(initialInfectious,end=' ')
  print(initialRecovered,end=' ')
  print(R0,end=' ')
  print(latentPeriod,end=' ')
  print(infectiousPeriod,end=' ')
  print(numberOfSimulations,end=' ')
  print(numberOfDays)

#
# Define flu progression rule:
#

siteName = 'Pittsburgh'
site = Site(siteName)

class FluProgressRule(Rule):
    def __init__(self): super().__init__('flu-progress', TimeAlways())
    def apply(self, pop, group, iter, t):
        if group.has_attr({ 'flu': 's' }):
            at  = group.get_rel(Site.AT)
            n   = at.get_pop_size()
            n_s = at.get_pop_size(GroupQry(attr={ 'flu': 's' }))
            n_e = at.get_pop_size(GroupQry(attr={ 'flu': 'e' }))
            n_i = at.get_pop_size(GroupQry(attr={ 'flu': 'i' }))
            beta = R0 / (population*infectiousPeriod)
            lambdat = beta*n_i
            fractionInfected = float(n_i) / float(n)
            numberOfNewlyInfected = np.random.binomial(n_s,lambdat)
            p_infection = float(numberOfNewlyInfected+n_e)/float(n)
예제 #14
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')
예제 #15
0
파일: sim-test.py 프로젝트: momacs/pram
'''
Tests of simulation construction exceptions associated with (1) improper order of adding rules and groups and
(2) superfluous attributes or relations.

Based on the simulation from: sim/04-flu-prog/sim.py
'''

from pram.data import GroupSizeProbe, ProbeMsgMode
from pram.entity import AttrFluStage, Group, GroupSplitSpec, Site
from pram.rule import GoToRule, GoToAndBackTimeAtRule, TimeInt
from pram.sim import Simulation, SimulationConstructionError, SimulationConstructionWarning, TimeHour

from rules import ProgressFluRule

# ----------------------------------------------------------------------------------------------------------------------
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())
예제 #16
0
파일: sim.py 프로젝트: momacs/pram
'''
A simulation of agents going from home to work and then, sometimes, to a store and back home again.  Apart from
testing the mechanics of a simulation, this module mainly tests the GoToRule rule.
'''

from pram.data import GroupSizeProbe, ProbeMsgMode
from pram.entity import GroupQry, Site
from pram.rule import GoToRule, TimeInt, TimePoint
from pram.sim import Simulation

# ----------------------------------------------------------------------------------------------------------------------
sites = {
    s: Site(s)
    for s in ['home', 'work-a', 'work-b', 'work-c', 'store-a', 'store-b']
}

probe_grp_size_site = GroupSizeProbe.by_rel(
    'site',
    Site.AT,
    sites.values(),
    msg_mode=ProbeMsgMode.DISP,
    memo='Mass distribution across sites')

(Simulation().add().rule(
    GoToRule(0.4,
             'home',
             'work',
             TimeInt(8, 12),
             memo='Some agents leave home to go to work')).rule(
                 GoToRule(0.4,
                          'work',
예제 #17
0
        if self.is_verbose: print('begins to eat')

        return [GroupSplitSpec(p=1.0, attr_set={ self.ATTR: self.State.EATING})]

    def is_applicable(self, group, iter, t):
        return (
            super().is_applicable(group, iter, t) and
            group.get_mass() > 0 and
            group.has_rel(self.FORK_L) and
            group.has_rel(self.FORK_R)
        )


# ----------------------------------------------------------------------------------------------------------------------
forks = {
    'f1'  : Site('f1'),
    'f4'  : Site('f4'),
    'f6'  : Site('f6'),
    'f8'  : Site('f8'),
    'f11' : Site('f11'),
}

(Simulation().
    set_rand_seed(rand_seed).
    add_rule(TERule(is_verbose=True)).
    new_group('p0',  1).set_attr(TERule.ATTR, TERule.State.THINKING).set_rel(TERule.FORK_L, forks['f1' ]).set_rel(TERule.FORK_R, forks['f11']).done().
    new_group('p2',  1).set_attr(TERule.ATTR, TERule.State.THINKING).set_rel(TERule.FORK_L, forks['f4' ]).set_rel(TERule.FORK_R, forks['f1' ]).done().
    new_group('p5',  1).set_attr(TERule.ATTR, TERule.State.THINKING).set_rel(TERule.FORK_L, forks['f6' ]).set_rel(TERule.FORK_R, forks['f4' ]).done().
    new_group('p7',  1).set_attr(TERule.ATTR, TERule.State.THINKING).set_rel(TERule.FORK_L, forks['f8' ]).set_rel(TERule.FORK_R, forks['f6' ]).done().
    new_group('p10', 1).set_attr(TERule.ATTR, TERule.State.THINKING).set_rel(TERule.FORK_L, forks['f11']).set_rel(TERule.FORK_R, forks['f8' ]).done().
    run(20, do_disp_t=True)
예제 #18
0
    def test_comparisons(self):
        eq = self.assertEqual
        ne = self.assertNotEqual

        eq(Site('a'), Site('a'))  # different objects, same name
        ne(Site('a'), Site('b'))  # different objects, different name
예제 #19
0
파일: sim.py 프로젝트: momacs/pram
    Spec('s4', 500),
    Spec('s5', 5000),
    Spec('s6', 50000)
]

dpath_cwd = os.path.dirname(__file__)
fpath_db = os.path.join(dpath_cwd, f'probes-{sim_dur_days}d.sqlite3')

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

probe_persistence = ProbePersistenceDB(fpath_db)

probes_grp_size_flu_school = []

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})
                       ],
예제 #20
0
파일: sim-test-03b.py 프로젝트: momacs/pram
from pram.entity import Group, GroupDBRelSpec, GroupQry, Site
from pram.rule   import SimpleFluLocationRule, SimpleFluProgressRule, SimpleFluProgressMoodRule
from pram.sim    import Simulation


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

fpath_db_out = os.path.join(os.path.dirname(__file__), 'sim-test-03b.sqlite3')

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'
)
예제 #21
0
from pram.entity import Site

# ----------------------------------------------------------------------------------------------------------------------
# Parameters:

N = 100_000

attr = {
    'flu': 's',
    'age_group': '10_19',
    'is_migrating': True,
    't-migration': 3,
    'history': [2, 4, 8.0]
}
rel = {
    'home': Site('home-x').__hash__(),
    'school': Site('school-01').__hash__()
}
cond = [lambda x: x > 1, lambda x: x < 1, lambda x: x == 1]
full = False

# ----------------------------------------------------------------------------------------------------------------------
# Algorithms:

# (1) hash + str + inspect.getsource (64):
t0 = time.time()
for i in range(N):
    hash(str((attr, rel, str([inspect.getsource(i) for i in cond]), full)))
print(f'01: {time.time() - t0}')

# (2) hash + json + inspect.getsource (64):
예제 #22
0
파일: sim-01.py 프로젝트: momacs/pram
''' '''

import os,sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..'))


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.DISP, memo='Mass distribution across sites')

# s = (Simulation().
#     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']).
예제 #23
0
do_remove_file_sites = False
do_remove_file_groups = False

if do_remove_file_sites and os.path.isfile(fpath_sites):
    os.remove(fpath_sites)

if do_remove_file_groups and os.path.isfile(fpath_groups):
    os.remove(fpath_groups)

# ----------------------------------------------------------------------------------------------------------------------
# (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', []),
        'work': Site.gen_from_db(fpath_db, 'workplaces', 'sp_id', 'work', [])
    }, fpath_sites)

site_home = Site('home')

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

fpath_db_out = os.path.join(dpath_cwd, 'sim.sqlite3')

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

pp = ProbePersistenceDB(fpath_db_out, flush_every=1)
예제 #24
0
        # Recovered:
        if group.has_attr({'flu': 'r'}):
            return [
                GroupSplitSpec(p=0.8,
                               rel_set={Site.AT: group.get_rel('school')}),
                GroupSplitSpec(p=0.2)
            ]

        return None


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

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

# ----------------------------------------------------------------------------------------------------------------------
# (2) Simulation:


def grp_setup(pop, group):
    return [
        GroupSplitSpec(p=0.9, attr_set={'flu': 's'}),
        GroupSplitSpec(p=0.1, attr_set={'flu': 'i'})
    ]


def run(iter):
예제 #25
0
파일: sim.py 프로젝트: momacs/pram
do_remove_file_sites = False
do_remove_file_groups = False

if do_remove_file_sites and os.path.isfile(fpath_sites):
    os.remove(fpath_sites)

if do_remove_file_groups and os.path.isfile(fpath_groups):
    os.remove(fpath_groups)

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

sites = Simulation.gen_sites_from_db(
    fpath_db_in, lambda fpath_db: {
        'hosp':
        Site.gen_from_db(fpath_db, 'hospitals', 'hosp_id', 'hospital',
                         ['workers', 'physicians', 'beds']),
        'home_gq':
        Site.gen_from_db(fpath_db, 'gq', 'sp_id', 'home',
                         ['gq_type', 'persons']),
        'home':
        Site.gen_from_db(fpath_db, 'households', 'sp_id', 'home',
                         ['hh_income']),
        'school':
        Site.gen_from_db(fpath_db, 'schools', 'sp_id', 'school', []),
        'work':
        Site.gen_from_db(fpath_db, 'workplaces', 'sp_id', 'work', [])
    }, fpath_sites)

site_home = Site('home')

# ----------------------------------------------------------------------------------------------------------------------
예제 #26
0
n_weeks = 8

do_sim = True  # set to False to plot only (probe DB must exist)
do_plot = True
do_rm_traj_ens_db = True

do_school = False
do_work = False
do_school_work = True

disease_name = 'COVID-19'

fpath_traj_ens_db = os.path.join(os.path.dirname(__file__), 'out', sim_name,
                                 'te.sqlite3')

site_home = Site('home')


# ----------------------------------------------------------------------------------------------------------------------
def TN(a, b, mu, sigma, n=None):
    return truncnorm((a - mu) / sigma, (b - mu) / sigma, mu, sigma).rvs(n)


# ----------------------------------------------------------------------------------------------------------------------
# Population and environment source:

locale_db = SQLiteDB(
    os.path.join(os.path.dirname(__file__), '..', '..', '..', 'data',
                 'allegheny-county', 'allegheny.sqlite3'))
locale_db.open_conn()
예제 #27
0
    def is_applicable(self, group, t):
        return (super().is_applicable(t)
                and group.has_attr({'is-student': True})
                and group.has_rel(['home', 'school']))

    @staticmethod
    def setup(pop, group):
        return [
            GroupSplitSpec(p=1.0, attr_set={'did-attend-school-today': False})
        ]  # attr_del=['t-at-school'],


# ----------------------------------------------------------------------------------------------------------------------
sites = {
    'home': Site('home'),
    'school-a': Site('school-a'),
    'school-b': Site('school-b')
}

probe_grp_size_site = GroupSizeProbe.by_rel(
    'site', Site.AT, sites.values(), memo='Mass distribution across sites')

(Simulation(7, 1, 10, rand_seed=rand_seed).new_group('0', 500).set_attr(
    'is-student', True).set_rel(Site.AT, sites['home']).set_rel(
        'home',
        sites['home']).set_rel('school', sites['school-a']).commit().new_group(
            '1', 500).set_attr('is-student', True).set_rel(
                Site.AT, sites['home']).set_rel('home', sites['home']).set_rel(
                    'school', sites['school-b']).commit().add_rule(
                        ResetDayRule(TimePoint(7))).add_rule(