Beispiel #1
0
def test_all_tutorials():

    # Get and run tests
    filenames = sc.getfilelist(tex.examples_dir, pattern='t*.py', nopath=True)
    for filename in filenames:
        if filename[
                1] in '0123456789':  # Should have format e.g. t5_foo.py, not test_foo.py
            sc.heading(f'Running {filename}...')
            try:
                tex.run_example(filename)
            except (
                    pickle.PicklingError, NameError
            ):  # Ignore these: issue with how the modules are loaded in the run_example function
                pass
        else:
            print(f'[Skipping "{filename}" since does not match pattern]')

    # Tidy up
    testfiles = sc.getfilelist(tex.examples_dir, pattern='my-*.*')

    sc.heading('Tidying...')
    print(f'Deleting:')
    for filename in testfiles:
        print(f'  {filename}')
    print('in 3 seconds...')
    sc.timedsleep(3)
    for filename in testfiles:
        os.remove(filename)
        print(f'  Deleted {filename}')

    return
def test_progress_bar():
    sc.heading('Progress bar')
    n = 50
    for i in range(n):
        sc.progressbar(i + 1, n)
        sc.timedsleep(1.0 / n, verbose=False)
    return i
def run_sim(index,
            scenpars=None,
            label=None,
            runinfo=None,
            do_shrink=True,
            from_cache=True,
            verbose=True):
    ''' Load, modify, and run the simulation '''

    if scenpars is None:
        print('WARNING, loading default parameters!')
        scenpars = sc.dcp(d_pars)

    if label is None:
        label = f'full_sim_trial{index}_nolabel'

    # Run sim or load up until scenarios start
    sim_loaded = 0
    filename = f'./simcache/projection_trial{index}.sim'
    if from_cache and os.path.exists(filename):
        tries = 0
        while not sim_loaded and tries < 3:
            try:
                print(f'run_sim(): Loading sim from cache ({filename})...')
                sim = cv.load(filename)
                assert isinstance(
                    sim, cv.Sim
                )  # Sometimes unpickling fails, but can reload locally
                tn = sim.get_interventions('tn')
                tn.subtarget = test_num_subtarg
                sim_loaded = 1
            except Exception as E:
                print(f'Loading failed on try {tries}! {E}')
                string = '\n\n'.join([
                    f'Index {index}', filename, f'Try {tries}',
                    str(E),
                    sc.traceback()
                ])
                fn = f'simcache_exception_index{index}_try{tries}.err'
                sc.savetext(fn, string)
                tries += 1
                sc.timedsleep(0.5)

    if not sim_loaded:
        print(f'run_sim(): Creating new sim (and saving to {filename})...')
        sim = create_sim(index, verbose=verbose)
        sim.run(until=sim.sceninfo.calib_end)
        sim.save(filename, keep_people=True)

    # Modify the sim with these scenario values
    sim = modify_sim(sim, scenpars=scenpars, label=label, runinfo=runinfo)

    # Rerun till the end and optionally shrink
    sim.run(restore_pars=False)  # So we can see the changes made
    if do_shrink:
        sim.shrink()

    return sim
    sc.toc(T)
def make_study(restart=False):
    ''' Make a study, deleting one if it already exists '''
    try:
        if restart:
            print(f'About to delete {storage}:{name}, you have 5 seconds to intervene!')
            sc.timedsleep(5.0)
            op.delete_study(storage=storage, study_name=name)
    except:
        pass
    output = op.create_study(storage=storage, study_name=name, load_if_exists=not(restart))
    return output
Beispiel #5
0
if __name__ == '__main__':

    T = sc.tic()

    try:
        sh.rmtree('./progress/', ignore_errors=True)
        os.makedirs('./progress/', exist_ok=True)
    except Exception as E:
        print(f'Could not make progress folder: {E}')

    if which == 'a':
        sweeps = construct1dsweeps()
        ntrials = len(sweeps)

    sc.heading(f'Beginning run for type "{which}" for {ntrials} trials...')
    sc.timedsleep(3)

    sims = sc.parallelize(run_scenario,
                          iterarg=np.arange(ntrials),
                          ncpus=ncpus,
                          kwargs={'which': which})

    msim = cv.MultiSim(sims)
    msim.save(msimfile)
    if doplot:
        msim.plot(max_sims=8,
                  to_plot='overview',
                  fig_args={'figsize': (38, 19)})

    print('Done.')
    sc.toc(T)
Beispiel #6
0
        n_scenarios = len(scenarios)
        goodseeds = cv.load(f'{resfolder}/goodseeds.obj')[:max_seeds]
        sims_file = f'{cachefolder}/all_sims.obj'
        T = sc.tic()

        # Optionally remove the cache folder
        if do_load and os.path.exists(cachefolder):
            response = input(
                f'Do you want to delete the cache folder "{os.path.abspath(cachefolder)}" before starting? y/[n] '
            )
            if response in ['y', 'yes', 'Yes']:
                print(f'Deleting "{cachefolder}"...')
                shutil.rmtree(cachefolder)
            else:
                print(f'OK, not deleting "{cachefolder}" -- you were warned!')
            sc.timedsleep(2)  # Wait for a moment so messages can be seen

        # Make sims
        sc.heading('Making sims...')
        if os.path.isfile(sims_file) and do_load:  # Don't run, just load
            sim_configs = cv.load(sims_file)
        else:
            n_sims = n_scenarios * sy_npts * tr_npts * max_seeds
            count = 0
            ikw = []
            for i_sc, scenname in enumerate(scenarios):
                for i_fst, future_symp_test in enumerate(symp_test_vals):
                    print(f'Creating arguments for sim {count} of {n_sims}...')
                    daily_test = np.round(1 - (1 - future_symp_test)**(1 / 10),
                                          3) if future_symp_test < 1 else 0.4
                    for i_fte, future_t_eff in enumerate(trace_eff_vals):