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)
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
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() )
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()
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()
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 )
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'] )
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'] )
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'])
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
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 })
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()
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()
def analysis_simple(tx_dict=None, population=10000, iteration=16): if tx_dict is None: tx_dict = dict( round_seed_a=0.3, round_seed_failure=0.67, round_a_b=0.2, round_a_failure=0.6, round_b_c=0.3, round_b_failure=0.4, round_c_success=0.5, round_c_failure=0.5, round_success_success=1, round_success_failure=0, round_failure_success=0, round_failure_failure=1, # round_a_a=0.2, # round_b_b=0.2, # round_c_c=0.2, ) old_p = GroupSizeProbe.by_attr( 'stage', 'stage', ['seed', 'a', 'b', 'c', 'success', 'failure'], persistance=ProbePersistanceMem(), msg_mode=ProbeMsgMode.CUMUL) p = GroupSizeProbe.by_attr('stage', 'stage', ['seed', 'a', 'b', 'c', 'success', 'failure'], persistance=ProbePersistanceDB()) sim = (Simulation().add( [UserStartupGrowthRule(tx_dict), p, Group(m=population)]).run(iteration)) series = [ { 'var': 'n0' }, { 'var': 'n1' }, { 'var': 'n2' }, { 'var': 'n3' }, { 'var': 'n4' }, { 'var': 'n5' }, ] col_names = { 'n0': 'seed', 'n1': 'a', 'n2': 'b', 'n3': 'c', 'n4': 'success', 'n5': 'failure' } probe_data = p.probe_data(series) probe_frame: pd.DataFrame probe_frame = pd.DataFrame.from_dict(probe_data) probe_frame.rename(columns=col_names, inplace=True) probe_frame["i"] = probe_frame["i"] + 1 initial_condition = { 'seed': population, 'a': 0, 'b': 0, 'c': 0, 'success': 0, 'failure': 0, 'i': 0 } probe_frame = pd.concat( [pd.DataFrame(initial_condition, index=[0]), probe_frame[:]]).reset_index(drop=True) probe_frame.drop(columns=['i'], inplace=True) print(probe_frame) d = probe_frame.iloc[0] print(d) # for chart plot_data = probe_frame.iloc[0] # probe_names = probe_frame print(plot_data.values) print(list(plot_data.index)) # data_source = ColumnDataSource(probe_frame) return probe_frame
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
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,
''' A test simulation involving the SEIR flu model in isolation. ''' 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()).
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']). 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).
# (0) Init: 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)
''' A simulation implementing the SIRS model of infectious disease spread in a population and in particular demonstrating probe plotting. ''' from pram.data import ProbePersistenceMem, GroupSizeProbe from pram.entity import Group from pram.model.epi import SIRSModel from pram.sim import Simulation # ---------------------------------------------------------------------------------------------------------------------- p = GroupSizeProbe.by_attr('flu', 'flu', ['s', 'i', 'r'], persistence=ProbePersistenceMem()) (Simulation().add_probe(p).add_rule( SIRSModel('flu', beta=0.05, gamma=0.50, alpha=0.10)).add_group(Group(m=1000, attr={'flu': 's'})).run(100)) series = [{ 'var': 'p0', 'lw': 0.75, 'ls': 'solid', 'marker': 'o', 'color': 'red', 'ms': 0, 'lbl': 'S' }, { 'var': 'p1', 'lw': 0.75,
import random from scipy.stats import poisson from pram.data import GroupSizeProbe, ProbeMsgMode from pram.entity import Group, GroupDBRelSpec, GroupQry, GroupSplitSpec, Site from pram.rule import SegregationModel from pram.sim import Simulation # ---------------------------------------------------------------------------------------------------------------------- # (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)
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
def setup(self, pop, group): return [GroupSplitSpec(p=1.0, attr_set={'stage': 's'})] # ---------------------------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------------------------- if __name__ == "__main__": i = 1 eq = 50 print(eq * "=", "starting sim {}".format(i), eq * "=") sim = (Simulation().add([ StartupGrowthRule(), GroupSizeProbe.by_attr('stage', 'stage', ['s', 'a', 'b', 'c', 'success', 'failure'], msg_mode=ProbeMsgMode.CUMUL), Group(m=10000) ]).run(10)) print(sim.probes[0].get_msg()) print() i += 1 print(eq * "=", "starting sim {}".format(i), eq * "=") sim = (Simulation().add([ StartupLocationRule(), GroupSizeProbe( 'startup-location', [ GroupQry(attr={ 'location': 'usa',
''' 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))
] if group.has_attr({'flu': 'I'}): return [ GroupSplitSpec(p=0.5, attr_set={'flu': 'I'}), GroupSplitSpec(p=0.5, attr_set={'flu': 'R'}), ] if group.has_attr({'flu': 'R'}): return [ GroupSplitSpec(p=0.7, attr_set={'flu': 'R'}), GroupSplitSpec(p=0.3, attr_set={'flu': 'S'}), ] 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 = [{
'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).
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()) print(f'Attributes : {s.last_run.attr_used}') print(f'Relations : {s.last_run.rel_used}') print()
class FluSpikeEvent(Event): 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(
return [ GroupSplitSpec(p=0.75, attr_set={'value': 0 * failure_value}), GroupSplitSpec(p=0.2, attr_set={'value': 2 * failure_value}), GroupSplitSpec(p=0.05, attr_set={'value': 1.5 * failure_value}) ] def is_applicable(self, group, iter, t): return super().is_applicable(group, iter, t) and group.has_attr( ['stage', 'value']) 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"})
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())