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 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 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()
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()
] 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 = [{
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(
# (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)
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',
# 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, memo='Mass distribution across sites') # ---------------------------------------------------------------------------------------------------------------------- # (2) Simulation: if __name__ == '__main__': sim = ( Simulation().
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
def analysis_Complex_version2(tx_dict=None, population=100, iteration=20): np.set_printoptions(suppress=True) 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.3, round_b_c=0.3, round_b_failure=0.2, round_c_success=0.3, round_c_failure=0.4, round_success_success=1, round_success_failure=0, round_failure_success=0, round_failure_failure=1, round_a_a=0.4, round_b_b=0.3, round_c_c=0.3, ) # seed = 1, a = 0, b = 0, c = 0, success = 0, failure = 0 tx_matrix = np.array([ [ 0, tx_dict['round_seed_a'], 0, 0, 1 - tx_dict['round_seed_failure'] - tx_dict['round_seed_a'], tx_dict['round_seed_failure'] ], [ 0, tx_dict['round_a_a'], tx_dict['round_a_b'], 0, 1 - tx_dict['round_a_failure'] - tx_dict['round_a_a'] - tx_dict['round_a_b'], tx_dict['round_a_failure'] ], [ 0, 0, tx_dict['round_b_b'], tx_dict['round_b_c'], 1 - tx_dict['round_b_failure'] - tx_dict['round_b_c'] - tx_dict['round_b_b'], tx_dict['round_b_failure'] ], [ 0, 0, 0, tx_dict['round_c_c'], 1 - tx_dict['round_c_failure'] - tx_dict['round_c_c'], tx_dict['round_c_failure'] ], [ 0, 0, 0, 0, 1 - tx_dict['round_success_failure'], tx_dict['round_success_failure'] ], [ 0, 0, 0, 0, 1 - tx_dict['round_failure_failure'], tx_dict['round_failure_failure'] ], ]) 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( [UserStartupGrowthRuleVersion2(tx_dict), p, Group(m=population)]).run(iteration)) print(sim.probes[0].get_msg()) print() series = [ { 'var': 'p0' }, { 'var': 'p1' }, { 'var': 'p2' }, { 'var': 'p3' }, { 'var': 'p4' }, { 'var': 'p5' }, ] col_names = { "p0": "p_seed", "p1": "p_a", "p2": "p_b", "p3": "p_c", "p4": "p_success", "p5": "p_failure" } names = ["p0", "p1", "p2", "p3", "p4", "p5"] probe_data: dict probe_data = p.probe_data(series) probe_data_ordered = OrderedDict() for name in names: probe_data_ordered[col_names.get(name)] = probe_data.pop(name) # pp(probe_data_ordered) probe_data_frame = pd.DataFrame.from_dict(probe_data_ordered) pp(probe_data_frame) value_df = pd.DataFrame(columns=list(probe_data_ordered.keys())) # print(value_df) # proportion of investment investment_proportion = OrderedDict(seed=1, a=0, b=0, c=0, success=0, failure=0) # hyper-parameters # stage_multiplier = {"seed": 3, "a": 5, "b": 7, "c": 5, "success": 5, "failure": 0} # stage_multiplier_dict = OrderedDict(seed=3, a=5, b=7, c=5, success=5, failure=0) stage_multiplier_list = [1, 1.1, 1.25, 1.3, 1, 0] # stage_multiplier_list = [1, 2, 3, 4, 5, 0] inital_investment_dict = OrderedDict( seed=population * investment_proportion.get("seed"), a=population * investment_proportion.get("a"), b=population * investment_proportion.get("b"), c=population * investment_proportion.get("c"), success=population * investment_proportion.get("success"), failure=population * investment_proportion.get("failure"), ) sim_length = len(probe_data_ordered.get('p_a')) valuation_list = [population] for i in range(sim_length): # print(valuation_list[i] * probe_data_frame.iloc[[i]]) val = valuation_list[i] * probe_data_frame.iloc[i] val = stage_multiplier_list * val valuation_list.append(np.sum(val)) print(valuation_list) # print("sim_length",sim_length) # # # total_investment = sum(inital_investment) # print("inital_investment",inital_investment_dict) 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, "p_seed": 1, "p_a": 0, "p_b": 0, "p_c": 0, "p_success": 0, "p_failure": 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) probe_frame.to_csv("data_file.csv") return probe_frame
def analysis_Complex_version1(tx_dict=None, population=10000, iteration=20): 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.3, round_b_c=0.3, round_b_failure=0.2, round_c_success=0.3, round_c_failure=0.4, round_success_success=1, round_success_failure=0, round_failure_success=0, round_failure_failure=1, round_a_a=0.4, round_b_b=0.3, round_c_c=0.3, ) tx_numpy_array = np.array([]) 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( [UserStartupGrowthRuleVersion2(tx_dict), p, Group(m=population)]).run(iteration)) print(sim.probes[0].get_msg()) print() series = [ { 'var': 'p0' }, { 'var': 'p1' }, { 'var': 'p2' }, { 'var': 'p3' }, { 'var': 'p4' }, { 'var': 'p5' }, { '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', "p0": "p_seed", "p1": "p_a", "p2": "p_b", "p3": "p_c", "p4": "p_success", "p5": "p_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, "p_seed": 1, "p_a": 0, "p_b": 0, "p_c": 0, "p_success": 0, "p_failure": 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) probe_frame.to_csv("data_file.csv") return probe_frame
Original PRAM Simulation from: pram/src/sim/04-flu-prog-01/sim.py """ from pram.data import ProbePersistenceDB, ProbeMsgMode, GroupSizeProbe from pram.entity import Group, GroupQry, GroupSplitSpec from pram.model.model import MCSolver from pram.model.epi import SIRSModel from pram.sim import Simulation import matplotlib.pyplot as plt import time # ---------------------------------------------------------------------------------------------------------------------- sir_probe = GroupSizeProbe.by_attr('flu', 'flu', ['s', 'i', 'r'], persistence=ProbePersistenceDB(), msg_mode=ProbeMsgMode.DISP) s = (Simulation().add_probe(sir_probe).add_rule( SIRSModel('flu', beta=0.05, gamma=0.50, alpha=0.10, solver=MCSolver())).add_group(Group(m=1000, attr={'flu': 's'}))) runs = 48 t0 = time.time() s.run(runs) time_elapsed = time.time() - t0 print(f'Time elapsed in {runs} runs: {time_elapsed} seconds') series = [ {
''' 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()).
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"})
''' 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,