Exemplo n.º 1
0
def sim02(iter_cnt):
    sim = (Simulation().add([
        ProgressFluIncomeRule(),
        GroupSizeProbe.by_attr('flu',
                               'flu', ['s', 'e', 'r'],
                               msg_mode=ProbeMsgMode.CUMUL),
        Group(m=500, attr={'income': 'l'}),
        Group(m=500, attr={'income': 'm'})
    ]).run(iter_cnt))
    print(sim.probes[0].get_msg())
    print()
Exemplo n.º 2
0
def runSimulations(n):
    for n in range(numberOfSimulations):
      (Simulation().
          set().
              pragma_autocompact(True).
              done().
          add([
              FluProgressRule(),
              Group('Susceptible', initialSusceptible, attr={ 'flu': 's' }, rel={ Site.AT: site }),
              Group('Exposed',     initialExposed,     attr={ 'flu': 'e' }, rel={ Site.AT: site }),
              Group('Infectious',  initialInfectious,  attr={ 'flu': 'i' }, rel={ Site.AT: site }),
              Group('Recovered',   initialRecovered,   attr={ 'flu': 'r' }, rel={ Site.AT: site }),
          ]).
          run(numberOfDays)
       )
      print()
Exemplo n.º 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)
Exemplo n.º 4
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
Exemplo n.º 5
0
Arquivo: sim.py Projeto: momacs/pram
def sim01(iter_cnt):
    sim = (Simulation().add([
        ProgressFluRule(),
        GroupSizeProbe.by_attr('flu',
                               'flu', ['s', 'e', 'r'],
                               msg_mode=ProbeMsgMode.CUMUL),
        Group(m=1000)
    ]).run(iter_cnt))
    print(sim.probes[0].get_msg())
    print()
Exemplo n.º 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()
Exemplo n.º 7
0
    def graph(self):
        if os.path.isfile(fpath_db): os.remove(fpath_db)

        te = TrajectoryEnsemble(fpath_db)

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

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

            fpath_diag = os.path.join(os.path.dirname(__file__), 'out', 'sim-04.diag')
            fpath_pdf  = os.path.join(os.path.dirname(__file__), 'out', 'sim-04.pdf')
            te.traj[2].sim.gen_diagram(fpath_diag, fpath_pdf)
Exemplo n.º 8
0
def run_simulation():
    sim_info = json.loads(request.form['runInfo'])

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

    add_initial_rules(time_offset)

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

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

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

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

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

    flows = run_and_get_mass_flow(s, runs)

    return jsonify(flows)
Exemplo n.º 9
0
    def apply(self, pop, group, iter, t):
        return [
            GroupSplitSpec(p=0.90, attr_set={ 'flu': 'i' }),
            GroupSplitSpec(p=0.10)
        ]

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


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


# ----------------------------------------------------------------------------------------------------------------------
# dpath_cwd = os.path.dirname(__file__)
# fpath_db  = os.path.join(dpath_cwd, f'sim.sqlite3')
#
# if os.path.isfile(fpath_db):
#     os.remove(fpath_db)
#
# probe = GroupSizeProbe(
#     name='flu',
#     queries=[
#         GroupQry(attr={ 'flu': 's' }),
Exemplo n.º 10
0
import random

from scipy.stats import poisson

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

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

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

# ----------------------------------------------------------------------------------------------------------------------
te = (TrajectoryEnsemble().add_trajectory(Trajectory(
    'segregation', None, s)).set_group_names([
        (0, 'Blue A',
         Group.gen_hash(attr={'team': 'blue'}, rel={Site.AT: loc[0]})),
        (1, 'Blue B',
         Group.gen_hash(attr={'team': 'blue'}, rel={Site.AT: loc[1]})),
        (2, 'Red A', Group.gen_hash(attr={'team': 'red'},
                                    rel={Site.AT: loc[0]})),
        (3, 'Red B', Group.gen_hash(attr={'team': 'red'},
Exemplo n.º 11
0
        if self.persistence:
            self.persistence.persist(self, [
                self.pop.m, self.pop.m_out, migrating_m, migrating_p,
                migrating_time_mean, migrating_time_sd, settled_m, settled_p
            ], iter, t, traj_id)


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

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

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

# ----------------------------------------------------------------------------------------------------------------------
pram2mesa(sim, 'Migration')
Exemplo n.º 12
0
    memo='Mass distribution across flu status')
probe_grp_size_site = GroupSizeProbe.by_rel(
    'site',
    Site.AT,
    sites.values(),
    msg_mode=ProbeMsgMode.DISP,
    memo='Mass distribution across sites')

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

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

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

# (1.3) As above (1g.2r), but with reversed rule order (which should not, and does not, change the results):
# s = Simulation()
# s.add_rule(GoToRule(TimeInt(10,16), 0.4, 'home', 'work'))
# s.add_rule(progress_flu_rule)
# s.add_probe(probe_grp_size_flu)
Exemplo n.º 13
0
from pram.model.epi import SEQIHRModel
from pram.rule import ODESystemMass, Intervention
from pram.sim import Simulation
from pram.traj import Trajectory, TrajectoryEnsemble
from pram.util import Err

# ----------------------------------------------------------------------------------------------------------------------
fpath_db = os.path.join(os.path.dirname(__file__), 'data', 'seqihr.sqlite3')


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


group_names = [(0, 'S', Group.gen_hash(attr={'sars': 's'})),
               (1, 'E', Group.gen_hash(attr={'sars': 'e'})),
               (2, 'Q', Group.gen_hash(attr={'sars': 'q'})),
               (3, 'I', Group.gen_hash(attr={'sars': 'i'})),
               (4, 'H', Group.gen_hash(attr={'sars': 'h'})),
               (5, 'R', Group.gen_hash(attr={'sars': 'r'}))]

# ----------------------------------------------------------------------------------------------------------------------
# A quarantine intervention rule:


class SARSQuarantineIntervention(Intervention):
    def __init__(self, seqihr_model, chi, i):
        Err.type(seqihr_model, 'seqihr_model', SEQIHRModel)

        super().__init__(i=i)
Exemplo n.º 14
0
'''
A test of the mass transfer graph.
'''

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


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


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

# te.plot_mass_locus_line     ((1200,300), get_out_dir('_plot-line.png'), iter_range=(-1, -1))
# te.plot_mass_locus_line_aggr((1200,300), get_out_dir('_plot-aggr.png'), iter_range=(-1, -1))
# te.traj[1].plot_mass_locus_streamgraph((900,600), get_out_dir('_plot.png'), do_sort=True)
# te.traj[1].plot_heatmap((800,800), get_out_dir('_plot-heatmap.png'), (-1,20))
Exemplo n.º 15
0
from pram.sim import Simulation

# ----------------------------------------------------------------------------------------------------------------------
# (1) Simulation (test population):

(Simulation().set().pragma_autocompact(True).pragma_live_info(
    False).done().add().rule(
        PoissonIncidenceProcess(
            'ad',
            65,
            0.01,
            2,
            5,
            rate_delta_mode=PoissonIncidenceProcess.RateDeltaMode.EXP)).group(
                Group(m=100,
                      attr={'age': 60
                            })).done().run(20).summary(False, 1024, 0, 0, 0,
                                                       (1, 0)))

# ----------------------------------------------------------------------------------------------------------------------
# (2) Simulation (synthetic Allegheny County population):

# fpath_db = os.path.join(os.path.dirname(__file__), '..', '..', '..', 'data', 'allegheny-county', 'allegheny.sqlite3')
#
# (Simulation().
#     set().
#         pragma_autocompact(True).
#         pragma_live_info(False).
#         done().
#     add().
#         rule(PoissonIncidenceProcess('ad', 65, 0.01, 2, 5, rate_delta_mode=PoissonIncidenceProcess.RateDeltaMode.EXP)).
Exemplo n.º 16
0
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,
    'ls': 'dashed',
    'marker': '+',
    'color': 'blue',
Exemplo n.º 17
0
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
Exemplo n.º 18
0
# ----------------------------------------------------------------------------------------------------------------------

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

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',
                    'stage': 'success'
                }),
Exemplo n.º 19
0
from pram.rule        import GammaDistributionProcess, IterAlways, IterInt, TimeAlways
from pram.sim         import Simulation
from pram.traj        import Trajectory, TrajectoryEnsemble, ClusterInf


# ----------------------------------------------------------------------------------------------------------------------
fpath_db = os.path.join(os.path.dirname(__file__), 'data', 'sir-comp.sqlite3')

def U(a,b, n=None):
    return uniform(a,a+b).rvs(n)

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

group_names = [
    (0, 'S', Group.gen_hash(attr={ 'flu': 's' })),
    (1, 'I', Group.gen_hash(attr={ 'flu': 'i' })),
    (2, 'R', Group.gen_hash(attr={ 'flu': 'r' }))
]


# ----------------------------------------------------------------------------------------------------------------------
# A gamma distribution process rule:

class FluProcess(GammaDistributionProcess):
    def apply(self, pop, group, iter, t):
        p = self.get_p(iter)
        return [
            GroupSplitSpec(p=p, attr_set={ 'flu': 's' }),
            GroupSplitSpec(p=1-p)
        ]
Exemplo n.º 20
0
Arquivo: sim.py Projeto: momacs/pram
from pram.entity import Group, GroupQry, GroupSplitSpec
from pram.model.model import MCSolver
from pram.model.epi import SIRSModel
from pram.sim import Simulation

# ----------------------------------------------------------------------------------------------------------------------
(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,
                                         solver=MCSolver())).add_group(
                                             Group(m=1000,
                                                   attr={'flu': 's'})).run(48))

# ----------------------------------------------------------------------------------------------------------------------
# dpath_cwd = os.path.dirname(__file__)
# fpath_db  = os.path.join(dpath_cwd, f'sim.sqlite3')
#
# if os.path.isfile(fpath_db):
#     os.remove(fpath_db)
#
# probe = GroupSizeProbe(
#     name='flu',
#     queries=[
#         GroupQry(attr={ 'flu': 's' }),
#         GroupQry(attr={ 'flu': 'i' }),
#         GroupQry(attr={ 'flu': 'r' })
#     ],
Exemplo n.º 21
0
    TrajectoryEnsemble(fpath_db).set_pragma_memoize_group_ids(True).
    add_trajectories([
        Trajectory(sim=(
            Simulation().add([
                sir_a1,
                # sir_b1,
                # make_sir_b1_fixed_delay(iter0),
                # make_sir_b1_random_delay(iter0),
                # make_sir_b1_random_delay(),
                # make_sir_b1_random_delay(iter0_dist=gamma(a=5.0, loc=50.0, scale=25.0)),
                make_sir_b1_random_delay_gamma(),
                RecurrentFluProcess(i=IterInt(2000, 0),
                                    p_max=gamma_proc_p_max,
                                    a=5.0,
                                    scale=50.0),
                Group(m=950, attr={'flu': 's'}),
                Group(m=50, attr={'flu': 'i'})
            ]))
                   # ) for _ in range(5)
                   # ) for iter0 in [900, 950, 1000, 1050, 1100]
                   # ) for gamma_proc_p_max in uniform(loc=0.75, scale=0.20).rvs(1)
                   ) for gamma_proc_p_max in [1.00]
    ]).set_group_names([(0, 'S', Group.gen_hash(attr={'flu': 's'})),
                        (1, 'I', Group.gen_hash(attr={'flu': 'i'})),
                        (2, 'R', Group.gen_hash(attr={'flu': 'r'}))
                        ]).run(4000))

# ----------------------------------------------------------------------------------------------------------------------
# Load data:

# te = TrajectoryEnsemble(fpath_db).stats()
Exemplo n.º 22
0
    def test_attributes_and_relations(self):
        f = self.assertFalse
        t = self.assertTrue

        g0 = Group('g.0', 100)
        g1 = Group('g.1', 200, {
            'sex': 'f',
            'income': 'l'
        }, {'location': 'home'})

        # Attributes:
        f(g0.has_attr('sex'))  # query is a string
        f(g0.has_attr(['sex']))  # query is an iterable (one string)
        f(g0.has_attr(['sex',
                       'income']))  # query is an iterable (multiple strings)
        f(g0.has_attr({'sex': 'f'}))  # query is a dict (one element)
        f(g0.has_attr({
            'sex': 'f',
            'income': 'l'
        }))  # query is a dict (multiple elements)

        f(g0.has_rel({'location': 'home'}))

        t(g1.has_attr('sex'))  # query is a string
        t(g1.has_attr(['sex']))  # query is an iterable (one string)
        t(g1.has_attr(['sex',
                       'income']))  # query is an iterable (multiple strings)
        t(g1.has_attr({'sex': 'f'}))  # query is a dict (one element)
        t(g1.has_attr({
            'sex': 'f',
            'income': 'l'
        }))  # query is a dict (multiple elements)
        f(g1.has_attr({
            'sex': 'f',
            'income': 'h'
        }))  # query is a dict (multiple elements)

        # Relations (the mechanism is identical to that for attributes, so we only test two relations):
        t(g1.has_rel({'location': 'home'}))
        f(g1.has_rel({'location': 'work'}))
Exemplo n.º 23
0
        l = self.get_lambda(age)
        p0 = poisson(l).pmf(0)
        print(
            f'n: {round(group.m,2):>12}  age: {age:>3}  l: {round(l,2):>3}  p0: {round(p0,2):<4}  p1: {round(1-p0,2):<4}'
        )

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

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

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


# ----------------------------------------------------------------------------------------------------------------------
(Simulation().set().pragma_autocompact(True).pragma_live_info(
    False).done().add().rule(DoubleIncidenceADRule()).group(
        Group(m=100, attr={'age': 60})).done().run(40))
Exemplo n.º 24
0
Arquivo: sim.py Projeto: momacs/pram
                               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%
        probe_sim  # mass should tend to move towards two of the four sites
    ]).run(70))

# ----------------------------------------------------------------------------------------------------------------------
# (2) Simulation (arbitrary numer of locations)

# loc = [Site('a'), Site('b'), Site('c')]
#
# probe_loc = GroupSizeProbe.by_rel('site', Site.AT, loc, msg_mode=ProbeMsgMode.DISP)
#
# def grp_setup(pop, group):
Exemplo n.º 25
0
    queries=[GroupQry(attr={ 'flu': 's' }), GroupQry(attr={ 'flu': 'i' }), GroupQry(attr={ 'flu': 'r' })],
    qry_tot=None,
    var_names=['ps', 'pi', 'pr', 'ns', 'ni', 'nr'],
    persistence=ProbePersistenceMem(),
    msg_mode=ProbeMsgMode.NONE
)


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

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


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

# Time series plot (group mass):
cmap = plt.get_cmap('tab20')
series = [
    { 'var': 'ps', 'lw': 2, 'linestyle': '--', 'marker': '+', 'color': cmap(0), 'markersize': 0, 'lbl': 'Susceptible' },
    { 'var': 'pi', 'lw': 2, 'linestyle': '-',  'marker': 'o', 'color': cmap(4), 'markersize': 0, 'lbl': 'Infectious'  },
Exemplo n.º 26
0
# ax.plot(h[1][0], h[1][1], h[1][2])
# plt.show()

# ----------------------------------------------------------------------------------------------------------------------
# (2) Lotka-Volterra:

alpha = 1.1  # baboon
beta = 0.4
delta = 0.1  # cheetah
gamma = 0.4


def f_lotka_volterra(t, state):
    x, y = state
    return [x * (alpha - beta * y), y * (-gamma + delta * x)]


r = ODESystem(f_lotka_volterra, [10, 10], dt=0.1)

(Simulation().add([r, Group(n=1)]).run(500))

h = r.get_hist()

import matplotlib.pyplot as plt
plt.plot(h[0], h[1][0], 'b-', h[0], h[1][1], 'r-')  # red - predator
plt.show()

# Phase-space plot:
# plt.plot(h[1][0], h[1][1], 'k-')
# plt.show()
Exemplo n.º 27
0
    'flu',
    'flu', ['S', 'I', 'R'],
    msg_mode=ProbeMsgMode.DISP,
    persistance=ProbePersistanceDB(),
    memo='Mass distribution across flu status')

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

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

series = [{
    'var': 'p0',
    'lw': 0.75,
    'linestyle': '-',
    'marker': 'o',
    'color': 'red',
    'markersize': 0,
    'lbl': 'S'
}, {
    'var': 'p1',
    'lw': 0.75,
    'linestyle': '--',
    'marker': '+',
    'color': 'blue',
Exemplo n.º 28
0
    def test_comparisons(self):
        eq = self.assertEqual
        ne = self.assertNotEqual

        eq(Group(), Group())  # different objects
        eq(Group('g.10', 100), Group('g.20', 100))  # different names
        eq(Group('g.10', 11), Group('g.20', 22))  # different sizes

        eq(Group(attr={}), Group())  # no attributes
        eq(Group(attr={}), Group(attr={}))  # no attributes
        eq(Group(attr={}), Group(attr=None))  # no attributes
        eq(Group(), Group(rel=None))  # no relations

        eq(Group(attr={'sex': 'f'}),
           Group(attr={'sex': 'f'}))  # same attributes (primitive data types)
        eq(Group(attr={'age': 99}),
           Group(attr={'age': 99}))  # same attributes (primitive data types)

        eq(Group(attr={'sex': AttrSex.F}), Group(
            attr={'sex': AttrSex.F}))  # same attributes (composite data types)
        eq(Group(attr={'sex': AttrFluStage.NO}),
           Group(attr={'sex': AttrFluStage.NO
                       }))  # same attributes (composite data types)
        ne(Group(attr={'sex': AttrFluStage.NO}),
           Group(attr={'sex': AttrFluStage.SYMPT
                       }))  # different attributes (composite data types)

        ne(Group(attr={'sex': 'f'}),
           Group(attr={'xes': 'f'}))  # different attribute keys
        ne(Group(attr={'sex': 'f'}),
           Group(attr={'sex': 'm'}))  # different attribute values

        eq(Group(attr={
            'sex': 'f',
            'income': 'l'
        }), Group(attr={
            'income': 'l',
            'sex': 'f'
        }))  # same attributes, different order
Exemplo n.º 29
0
    def setup(self, pop, group):
        return [GroupSplitSpec(p=1.0, attr_set={"value": 1000})]


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

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

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

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

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

print(sim.probes[0].get_msg())
print(sim.probes[1].get_msg())
print()
Exemplo n.º 30
0
fpath_db = os.path.join(os.path.dirname(__file__), f'trajectory.sqlite3')


# ----------------------------------------------------------------------------------------------------------------------
# (1) Create the database and run a trajectory ensemble:

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

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


# ----------------------------------------------------------------------------------------------------------------------
# (2) Restore a trajectory ensemble from the database for additional runs: