Beispiel #1
0
    def mkcfg(sample):
        cfg = config_load(args.yaml, sample)

        for meta in ("model", "tmax", "steps", "samples", "output"):
            arg = getattr(args, meta)
            if arg is not None:
                cfg["meta"][meta] = arg
        for init in ("N", "IU"):
            arg = getattr(args, init)
            if arg is not None:
                cfg["initial"][init] = arg

        for v in args.var:
            k, v = v.split("=", 1)
            v = float(v)
            cfg["parameters"][k] = v

        if isinstance(cfg["meta"]["model"], str):
            model = models.get(cfg["meta"]["model"])
            if model is None:
                log.error("Unknown model: {}".format(cfg["meta"]["model"]))
                sys.exit(255)
            cfg["meta"]["model"] = model

        log.debug("Config: {}".format(cfg))
        return cfg
Beispiel #2
0
    plt.setp(ax.get_xticklabels(), rotation=30, horizontalalignment='right')
    # ax.set_xlim([70, ax.get_xlim()[1]])
    ax.set_xlabel('Date')
    return


st.title("UK COVID-19 Policy Simulator")
st.markdown("""
Compare COVID-19 control policies in the UK using the  [PTTI](https://github.com/ptti/ptti) model.
""")
st.sidebar.title("COVID-19 Policy Choices")

HTML_WRAPPER = """<div style="overflow-x: auto; border: 1px solid #e6e9ef; border-radius: 0.25rem; padding: 1rem; margin-bottom: 2.5rem">{}</div>"""

cfg = config_load(
    os.path.join("..", "examples", "structured",
                 "ptti-past.yaml"))  # To pull basics - actual load below.
start = date(int(cfg['meta']['start'][0:4]), int(cfg['meta']['start'][5:7]),
             int(cfg['meta']['start'][8:10]))

cfg_1 = os.path.join(
    "..", "examples", "bowie",
    "cal2809test8dur5eta9chi9.yaml")  # Need High / Low Compliance.
cfg_2 = os.path.join("..", "examples", "bowie",
                     "recal5_dur7_lock10beta23c167pow16mob1.yaml")
cfg_3 = os.path.join("..", "examples", "bowie",
                     "recal2809dur7beta23c167pow16hols155.yaml")

Scenario = st.sidebar.radio("Scenario to use",
                            ['Scenario 1', 'Scenario 2', 'Scenario 3'],
                            index=0)
Beispiel #3
0
    plt.setp(ax.get_xticklabels(), rotation=30, horizontalalignment='right')
    # ax.set_xlim([70, ax.get_xlim()[1]])
    ax.set_xlabel('Date')
    return


st.title("UK COVID-19 Policy Simulator")
st.markdown("""
Compare COVID-19 control policies in the UK using the  [PTTI](https://github.com/ptti/ptti) model.
""")
st.sidebar.title("COVID-19 Policy Choices")

HTML_WRAPPER = """<div style="overflow-x: auto; border: 1px solid #e6e9ef; border-radius: 0.25rem; padding: 1rem; margin-bottom: 2.5rem">{}</div>"""

cfg = config_load(
    os.path.join("..", "examples", "structured",
                 "ptti-past.yaml"))  # To pull basics - actual load below.
start = date(int(cfg['meta']['start'][0:4]), int(cfg['meta']['start'][5:7]),
             int(cfg['meta']['start'][8:10]))

cfg_mask = os.path.join("..", "examples", "structured",
                        "ptti-masks.yaml")  # Need High / Low Compliance.

cfg_relax = os.path.join("..", "examples", "structured", "ptti-relax.yaml")
cfg_reopen = os.path.join("..", "examples", "structured", "ptti-reopen.yaml")
cfg_flu = os.path.join("..", "examples", "structured", "ptti-fluseason.yaml")
# Add flu season to TTI...
cfg_ti = os.path.join("..", "examples", "structured", "ptti-all_ti.yaml")
#cfg_tti = os.path.join("..", "examples", "structured", "ptti-tti.yaml")
#cfg_uti = os.path.join("..", "examples", "structured", "ptti-uti.yaml")
#cfg_combo_tti = os.path.join("..", "examples", "structured", "ptti-combo-tti.yaml")
Beispiel #4
0
Datei: fit.py Projekt: ptti/ptti
def command():
    logging.basicConfig(
        stream=sys.stdout,
        level=logging.INFO,
        format='%(asctime)s - %(name)s:%(levelname)s - %(message)s')

    parser = argparse.ArgumentParser("fit")
    parser.add_argument("-y", "--yaml", default=None, help="Config file")
    parser.add_argument("-m",
                        "--mask",
                        nargs="*",
                        default=[],
                        help="Variables to mask")
    parser.add_argument("-e",
                        "--end",
                        default=None,
                        help="Truncate the data at end date")
    parser.add_argument("-t",
                        "--time",
                        default=0,
                        type=float,
                        help="Shift dataset time by given amount")
    parser.add_argument(
        "--dgu",
        default=None,
        help=
        "coronavirus.data.gov.uk format for the dead\n\t\thttps://coronavirus.data.gov.uk/downloads/csv/coronavirus-deaths_latest.csv"
    )
    parser.add_argument("--data",
                        default=None,
                        help="generic YYYY-MM-DD,dead format for data")

    args = parser.parse_args()

    if args.yaml is None:
        log.error("--yaml is a required argument")

    dead = None
    if args.data:
        dead = data(args.data)
    elif args.dgu:
        dead = dgu(args.dgu)

    if dead is None:
        log.error("There are no dead. Need a data file of some sort")

    if args.end:
        end = time.strptime(args.end, "%Y-%m-%d")
        idx = np.sum(dead[:, 0] <= end.tm_yday)
        dead = dead[:idx]

    cfg = config_load(args.yaml)
    model = SEIRCTODEMem
    cfg["meta"]["model"] = model

    def getm(traj):
        return traj[:, model.colindex("M")]

    getp, setp = paramArray(cfg, args.mask)

    ## the times of the dead
    dead_t = dead[:, 0] + args.time
    ## these are the actual counts of the dead
    dead_d = dead[:, 1]

    ## this is the last day of data
    tmax = max(dead_t)
    ## one output point per day
    steps = int(tmax)
    ## we want a time-series of
    times = np.linspace(0, tmax, steps)
    ## interpolate the dead onto this time support
    dead_i = interp1d(dead_t,
                      dead_d,
                      kind="previous",
                      bounds_error=False,
                      fill_value=np.nan)(times)

    ## set to run for the specific required time at the specific step
    cfg["meta"]["tmax"] = tmax
    cfg["meta"]["steps"] = steps + 1

    interventions = cfg.get("interventions", [])

    ## perform a stochastic gradient descent
    t0, params = optimise(cfg, getm, setp, getp(cfg), times, dead_i,
                          interventions)
    cfg["meta"]["t0"] = t0
    setp(cfg, params)

    save_human(cfg, "{}-fit.yaml".format(cfg["meta"]["output"]))

    t, traj, _, _ = runModel(**cfg["meta"], **cfg)
    M = getm(traj)

    fig, (ax1, ax2) = plt.subplots(2, 1)

    ax1.set_xlabel("Days since outbreak start")
    ax1.set_ylabel("Cumulative infections")
    ax1.set_xlim(0, tmax)
    ax1.plot(t, M, label="Simulated")
    ax1.plot(times, dead_i, label="Data")
    for e in interventions:
        ax1.axvline(e["time"], c=(0, 0, 0), lw=0.5, ls='--')
    ax1.legend()

    ax2.set_xlabel("Days since outbreak start")
    ax2.set_ylabel("Cumulative infections")
    ax2.set_xlim(0, tmax)
    ax2.set_yscale("log")
    ax2.plot(t, M, label="Simulated")
    ax2.plot(times, dead_i, label="Data")
    for e in interventions:
        ax2.axvline(e["time"], c=(0, 0, 0), lw=0.5, ls='--')
    ax2.legend()

    plt.savefig("{}-fit.png".format(cfg["meta"]["output"]))
Beispiel #5
0
def basic_config():
    configfile = os.path.join(
        pkg_resources.get_distribution("ptti").location, "examples",
        "ptti-methods.yaml")
    return config_load(configfile)
Beispiel #6
0
parser.add_argument('seeds', type=str, nargs='+')
# Time resolution for events
parser.add_argument('-tres', type=float, default=1.0)
# Gnuplot linestyle for interventions
parser.add_argument('-ls-int', type=str, default='dt 1 lc 0')
# Gnuplot linestyle for triggers
parser.add_argument('-ls-trig', type=str, default='dt 1 lc rgb "#ff0000"')

args = parser.parse_args()

for seed in args.seeds:
    # Open the original parameter file
    param_history = []
    with open(seed + '.yaml') as f:
        data = config_load(seed + '.yaml')
        params = data['parameters']
        t0 = datetime.strptime(data["meta"]["start"], '%Y/%m/%d')
        tmax = t0 + timedelta(days=data['meta']['tmax'])
    param_history.append((0, params))
    with open(seed + '-out-0-events.yaml') as f:
        events = yaml.safe_load(f)
    # Merge non-unique events
    event_times = np.array([e['time'] for e in events])
    event_times = np.round(event_times/args.tres)*args.tres
    event_times, inds = np.unique(event_times, True)

    for t, e_i in zip(event_times, inds):
        e = events[e_i]
        params = dict(param_history[-1][1])
        params.update(e['parameters'])