Skip to content

Running stuff

A couple of methods used in run_simulation.py

Contains some useful methods that get used in run_simulation_2.py

Functions:

Name Description
print_attributes

Recursively prints the attributes of an object.

set_random_seed

Sets global seed infections for testing purposes.

str_to_bool

interprets strings saying "true" as a bool object, and all other strings as false.

parse_arguments(description='Default run_simulation_2.py')

Parse arguments given to run_simulation.py

Sets tons of defaults here. This is almost like a configuration file.

Parameters:

Name Type Description Default
description str

(Default value = 'Default run_simulation_2.py')

'Default run_simulation_2.py'
Source code in june/utils/running_stuff.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
def parse_arguments(description: str = 'Default run_simulation_2.py') -> argparse.Namespace:
    """Parse arguments given to run_simulation.py

    Sets tons of defaults here. This is almost like a configuration file.

    Args:
        description (str, optional): (Default value = 'Default run_simulation_2.py')

    """
    default_disease = 'covid19'

    parser = argparse.ArgumentParser(description=description)

    parser.add_argument("-w", "--world_path", help="Path to saved world file", default="tests.hdf5")
    parser.add_argument("-c", "--comorbidities", help="Include comorbidities", default="True")
    parser.add_argument("-con", "--config", help="Config file path", default=paths.configs_path / "config_simulation.yaml")
    parser.add_argument("-dcon", "--disease_config_path", help="Disease configuration file path", default=paths.configs_path / f"defaults/epidemiology/infection/disease/{default_disease}.yaml")
    parser.add_argument(
        "-p", "--parameters",
        help="Parameter file path",
        default=paths.configs_path / f"defaults/interaction/interaction_{default_disease}.yaml"
    )
    parser.add_argument("-ro", "--region_only", help="Run only one region", default="False")
    parser.add_argument("-hb", "--household_beta", help="Household beta", type=float, default=0.25)
    parser.add_argument("-nnv", "--no_vaccines", help="Implement no vaccine policies", default="False")
    parser.add_argument("-v", "--vaccines", help="Implement vaccine policies", default="False")
    parser.add_argument("-nv", "--no_visits", help="No shelter visits", default="False")
    parser.add_argument("-ih", "--indoor_beta_ratio", help="Indoor/household beta ratio scaling", type=float, default=0.55)
    parser.add_argument("-oh", "--outdoor_beta_ratio", help="Outdoor/household beta ratio scaling", type=float, default=0.05)
    parser.add_argument("-inf", "--infectiousness_path", help="Path to infectiousness parameter file", default="nature")
    parser.add_argument("-cs", "--child_susceptibility", help="Reduce child susceptibility for under 12s", default="False")
    parser.add_argument("-u", "--isolation_units", help="Include isolation units", default="False")
    parser.add_argument("-t", "--isolation_testing", help="Mean testing time", type=int, default=3)
    parser.add_argument("-i", "--isolation_time", help="Isolation time", type=int, default=7)
    parser.add_argument("-ic", "--isolation_compliance", help="Isolation compliance", type=float, default=0.6)
    parser.add_argument("-m", "--mask_wearing", help="Include mask wearing", default="False")
    parser.add_argument("-mc", "--mask_compliance", help="Mask wearing compliance", default="False")
    parser.add_argument("-mb", "--mask_beta_factor", help="Mask beta factor reduction", type=float, default=0.5)
    parser.add_argument("-s", "--save_path", help="Path to save results", default="results")
    parser.add_argument("--n_seeding_days", help="Number of seeding days", type=int, default=10)
    parser.add_argument("--n_seeding_case_per_day", help="Number of seeding cases per day", type=int, default=10)
    parser.add_argument("--seeding_config", help="Path to seeding configuration YAML file (optional, uses default if not specified)", default=None)
    parser.add_argument("--disable_mpi", help="Disable MPI even if available", action="store_true")
    parser.add_argument("--resume-from", help="Checkpoint name to resume from", default=None)
    parser.add_argument("--resume-latest", help="Resume from latest checkpoint", action="store_true")

    # RunManager options
    parser.add_argument("--run-id", help="Specific run ID to use or resume", default=None)
    parser.add_argument("--description", help="Description for this simulation run", default=None)
    parser.add_argument("--tags", help="Comma-separated tags for this run (e.g., baseline,production)", default=None)
    parser.add_argument("--resume-run", help="Resume from specific run ID", default=None)
    parser.add_argument("--list-runs", help="List recent runs and exit", action="store_true")
    parser.add_argument("--clean-runs", help="Clean old runs", action="store_true")
    parser.add_argument("--older-than", help="Only clean runs older than N days (use with --clean-runs)", type=int, default=30)

    args = parser.parse_args()

    return args

print_attributes(obj, indent=0)

Recursively prints the attributes of an object.

Parameters:

Name Type Description Default
obj
required
indent

(Default value = 0)

0
Source code in june/utils/running_stuff.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
def print_attributes(obj, indent=0):
    """Recursively prints the attributes of an object.

    Args:
        obj: 
        indent: (Default value = 0)

    """
    space = "  " * indent
    if hasattr(obj, "__dict__"):
        for attr, value in vars(obj).items():
            if hasattr(value, "__dict__"):  # If the value is another object
                print(f"{space}{attr}:")
                print_attributes(value, indent + 1)
            else:
                print(f"{space}{attr}: {value}")
    else:
        print(f"{space}{obj}")  # Print primitive types or objects without attributes

quick_run_check(args)

Handles commands passed to the RunManager that do not require a full simulation setup.

Some of the arguments that can be passed to the parser when run_simulation is called do not require a full blown simulation. This is a quick step to deal with those before the bulky full simulations are required.

Parameters:

Name Type Description Default
args
required
Source code in june/utils/running_stuff.py
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
def quick_run_check(args):
    """Handles commands passed to the RunManager that do not require a full simulation setup.

    Some of the arguments that can be passed to the parser when run_simulation is called do not require a full blown simulation. This is a quick step to deal with those before the bulky full simulations are required.

    Args:
        args: 

    """
    if args.list_runs:
        run_manager = RunManager()
        runs = run_manager.list_runs(limit=20)
        if runs:
            print("\nRecent simulation runs:")
            print("-" * 80)
            for run in runs:
                tags_str = ", ".join(run.get("tags", [])) if run.get("tags") else "no tags"
                print(f"{run['run_id'][:8]}... | {run.get('status', 'unknown'):>12} | {tags_str}")
                print(f"   {run.get('description', 'No description')}")
                print(f"   {run.get('created_at', 'Unknown time')}")
                print()
        else:
            logger.info("No simulation runs found.")
        sys.exit(0)

    if args.clean_runs:
        run_manager = RunManager()
        logger.info(f"Cleaning runs older than {args.older_than} days...")
        run_manager.cleanup_old_runs(keep_count=5, older_than_days=args.older_than)
        logger.info("Cleanup completed.")
        sys.exit(0)