Skip to content

Analysis

This class stores a series of methods to make plots and output data generated with COMORBUSS, this class can load data from a community object or from an hdf5 file.

do_plot(self, t, dt, data, colors, seeds, filename=None, size=(5, 4), title=None, events=False, events_type=0, skip=[], start_day=None, end_day=None, bands=True, colorsmap=None, start=True, close=True, dates=True, xlim=None, ylim=None, xlabel=False, ylabel=False, log_y=False, show_legend=True, legend_args={}, show_bands_legend=True, bands_legend_args={}, plt_args={})

Internal method used to plot one or more curve.

**plot_args:

Parameters:

Name Type Description Default
filename str

File name to save the graph, if not informed will only show the plot.

None
size tuple

Size to generate the plot. Defaults to (5, 4).

(5, 4)
title str

Title to be printed on the plot.

None
events bool

Overlay simulation events on the plot. Defaults to False.

False
events_type int

Type of logs to overlay as events. Defaults to S.MSG_EVENTS.

0
skip list

List of curves to skip plotting. Use the same string used in the legend of the plot to skip curves.

[]
start_day float

Plot only the interval from start_day. Defaults to 0.

None
end_day float

Plot only the interval to end_day. Defaults to last day.

None
bands bool

Plot standard deviation bands and 95% percentiles if data has multiple seeds. Defaults to True.

True
colorsmap arr[str]

If provided, the list of string is used to initialize colormaps, used in the shading of bands

None
close bool

If False doesn't show, save or close the plot so that the user can add more information to plot using the plt attribute from the class. Defaults to False.

True
dates bool

Use dates instead of days in the x axis. Defaults to True.

True
xlabel str

Label for the x axis.

False
ylabel str

Label for the y axis.

False
log_y bool

Sets the y scale to log. Defaults to False

False
show_legend bool

Hides legends if False. Defaults to True.

True
legend_args dict

Arguments to be passed to pyplot.legend when drawing the legend.

{}
show_bands_legend bool

Hides bands legends if False. Defaults to True.

True
bands_legend_args dict

Arguments to be passed to pyplot.legend when drawing the bands legend.

{}
plt_args dict

Additional arguments to be passed to pyplot.plot when drawing the curves.

{}

Internal parameters:

Parameters:

Name Type Description Default
t [type]

[description]

required
dt [type]

[description]

required
data [type]

[description]

required
colors [type]

[description]

required
seeds [type]

[description]

required
Source code in comorbuss/lab/analysis.py
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
def do_plot(
    self,
    t,
    dt,
    data,
    colors,
    seeds,
    filename=None,
    size=(5, 4),
    title=None,
    events=False,
    events_type=S.MSG_EVENT,
    skip=[],
    start_day=None,
    end_day=None,
    bands=True,
    colorsmap=None,
    start=True,
    close=True,
    dates=True,
    xlim=None,
    ylim=None,
    xlabel=False,
    ylabel=False,
    log_y=False,
    show_legend=True,
    legend_args={},
    show_bands_legend=True,
    bands_legend_args={},
    plt_args={},
):
    """Internal method used to plot one or more curve.

    ### **plot_args:

    Args:
        filename (str, optional): File name to save the graph, if not informed will only show the plot.
        size (tuple, optional): Size to generate the plot. Defaults to (5, 4).
        title (str, optional): Title to be printed on the plot.
        events (bool, optional): Overlay simulation events on the plot. Defaults to False.
        events_type (int, optional): Type of logs to overlay as events. Defaults to S.MSG_EVENTS.
        skip (list, optional): List of curves to skip plotting. Use the same string used in the legend
            of the plot to skip curves.
        start_day (float, optional): Plot only the interval from start_day. Defaults to 0.
        end_day (float, optional): Plot only the interval to end_day. Defaults to last day.
        bands (bool, optional): Plot standard deviation bands and 95% percentiles if data has
            multiple seeds. Defaults to True.
        colorsmap (arr[str], optional): If provided, the list of string is used to initialize colormaps,
            used in the shading of bands
        close (bool, optional): If False doesn't show, save or close the plot so that the user can add
            more information to plot using the plt attribute from the class. Defaults to False.
        dates (bool, optional): Use dates instead of days in the x axis. Defaults to True.
        xlabel (str, optional): Label for the x axis.
        ylabel (str, optional): Label for the y axis.
        log_y (bool, optional): Sets the y scale to log. Defaults to False
        show_legend (bool, optional): Hides legends if False. Defaults to True.
        legend_args (dict, optional): Arguments to be passed to pyplot.legend when drawing the legend.
        show_bands_legend (bool, optional): Hides bands legends if False. Defaults to True.
        bands_legend_args (dict, optional): Arguments to be passed to pyplot.legend when drawing the
            bands legend.
        plt_args (dict, optional): Additional arguments to be passed to pyplot.plot when drawing the curves.

    Internal parameters:

    Args:
        t ([type]): [description]
        dt ([type]): [description]
        data ([type]): [description]
        colors ([type]): [description]
        seeds ([type]): [description]
    """
    interval = self.days_to_interval(start_day, end_day, dt)
    if start:
        self.start_plt(size=size, title=title)
    if bands:
        bands = bands and (len(seeds) > 1)
    for i, k in enumerate(data.keys()):
        if not k in skip:
            colormap = None
            if bands and (colorsmap != None):
                try:
                    colormap = colorsmap[i]
                except:
                    pass
            self.plot_line(
                t,
                data[k],
                interval=interval,
                bands=bands,
                colormap=colormap,
                color=colors[i],
                label=k,
                **plt_args
            )
    if events:
        self.plot_events(seeds, events_type=events_type)
    dates_args = {"start_day": start_day, "end_day": end_day}
    if not close and dates:
        self.add_dates(**dates_args)
    show_bands_legend = show_bands_legend and bands
    if close:
        self.stop_plt(
            filename=filename,
            xlim=xlim,
            ylim=ylim,
            xlabel=xlabel,
            ylabel=ylabel,
            log_y=log_y,
            dates=dates,
            dates_args=dates_args,
            legend=show_legend,
            legend_args=legend_args,
            bands_legend=show_bands_legend,
            bands_legend_args=bands_legend_args,
        )

from_comm(comm, use_plotly=False, **loader_args) classmethod

Initialize an Analysis object from a community object.

Parameters:

Name Type Description Default
comm community

Community to extract data.

required

Returns:

Type Description
Analysis

An Analysis object.

Source code in comorbuss/lab/analysis.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
@classmethod
def from_comm(cls, comm, use_plotly=False, **loader_args):
    """Initialize an Analysis object from a community object.

    Args:
        comm (community): Community to extract data.

    Returns:
        Analysis: An Analysis object.
    """
    parameters = tools.recursive_copy(comm.parameters)
    try:
        data = tools.load_from_comms([comm], {}, **loader_args)
        return cls(data["realizations"], parameters, True, use_plotly=use_plotly)
    except:
        print("Coudn't load default to_store from given community.")
        return cls({}, {}, False)

from_hdf5(hdf5_file='', use_plotly=False, **loader_args) classmethod

Initialize an Analysis object from an hdf5 file.

Parameters:

Name Type Description Default
if seed == ""

seed = list(results["realizations"].keys())[0]file (str): Path to the hdf5 file, if not informed a prompt will be open for the user to select the file.

required
seed int

An execution seed in the hdf5 file to be loaded, if not informed will load the first in the file.

required

Returns:

Type Description
Analysis

An Analysis object.

Source code in comorbuss/lab/analysis.py
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
@classmethod
def from_hdf5(cls, hdf5_file="", use_plotly=False, **loader_args):
    """Initialize an Analysis object from an hdf5 file.

    Args:
        hdf5_
        if seed == "":
            seed = list(results["realizations"].keys())[0]file (str): Path to the hdf5 file, if not informed a prompt will be open for the user
            to select the file.
        seed (int, optional): An execution seed in the hdf5 file to be loaded, if not informed will load
            the first in the file.

    Returns:
        Analysis: An Analysis object.
    """
    results, filename = tools.load_hdf5(hdf5_file, keep_open=True, **loader_args)
    try:
        return cls(
            results["realizations"],
            results["triaged_parameters"].to_dict(),
            True,
            hdf5=results,
            use_plotly=use_plotly,
        )
    except:
        return cls({}, {}, False)

get_data(self, required_data, seeds=None)

Get data from hdf5 file.

Parameters:

Name Type Description Default
required_data list

List of data to get.

required
seeds list

If informed will filter for given seeds.

None

Returns:

Type Description
dict

A dictionary of required_data, in each item is passed a list the data for each seed.

Source code in comorbuss/lab/analysis.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
def get_data(self, required_data, seeds=None):
    """Get data from hdf5 file.

    Args:
        required_data (list): List of data to get.
        seeds (list, optional): If informed will filter for given seeds.

    Returns:
        dict: A dictionary of required_data, in each item is passed a list the data for each seed.
    """
    seeds = self.get_seeds(seeds)
    if not self.check_data(required_data, seeds):
        return None
    data = dict()
    data["seeds"] = seeds
    for key in required_data:
        data[key] = []
        for s in seeds:
            if type(key) in [list, tuple]:
                data_source = self.data[s]
                for k in key:
                    data_source = data_source[k]
                data[key].append(data_source)
            else:
                data[key].append(self.data[s][key])
    return data

get_srvc_data(self, required_data, seeds=None)

Get service data from hdf5 file.

Parameters:

Name Type Description Default
required_data list

List of data to get.

required
seeds list

If informed will filter for given seeds.

None

Returns:

Type Description
dict

A dictionary of required_data, in each item is passed a list the data for each seed.

Source code in comorbuss/lab/analysis.py
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
def get_srvc_data(self, required_data, seeds=None):
    """Get service data from hdf5 file.

    Args:
        required_data (list): List of data to get.
        seeds (list, optional): If informed will filter for given seeds.

    Returns:
        dict: A dictionary of required_data, in each item is passed a list the data for each seed.
    """
    seeds = self.get_seeds(seeds)
    if not self.check_data(required_data, seeds, srvc_check=True):
        return None
    data = []
    for sid in range(len(self.parameters["services"])):
        srvc_data = dict()
        srvc_data["seeds"] = seeds
        for d in required_data:
            srvc_data[d] = []
            for s in seeds:
                srvc_data[d].append(self.data[s]["services"][sid][d])
        data.append(srvc_data)
    return data

list_data(self, parameter=None, seeds=None)

Lists all available data for seeds.

Parameters:

Name Type Description Default
parameter str, list

If informed will inform data contained in a key.

None
seeds list

If informed will filter for given seeds.

None

Returns:

Type Description
list

List of available data

Source code in comorbuss/lab/analysis.py
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
def list_data(self, parameter=None, seeds=None):
    """Lists all available data for seeds.

    Args:
        parameter (str, list, optional): If informed will inform data contained in a key.
        seeds (list, optional): If informed will filter for given seeds.

    Returns:
        list: List of available data
    """
    seeds = self.get_seeds(seeds)
    source = self._get_source(parameter, seeds[0])
    available_data = set(source.keys())
    for seed in seeds:
        source = self._get_source(parameter, seed)
        seed_data = set(source.keys())
        available_data = available_data.intersection(seed_data)
    return list(available_data)

list_srvc_data(self, seeds=None)

Lists all available service data for seeds.

Parameters:

Name Type Description Default
seeds list

If informed will filter for given seeds.

None

Returns:

Type Description
list

List of available data

Source code in comorbuss/lab/analysis.py
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
def list_srvc_data(self, seeds=None):
    """Lists all available service data for seeds.

    Args:
        seeds (list, optional): If informed will filter for given seeds.

    Returns:
        list: List of available data
    """
    seeds = self.get_seeds(seeds)
    available_data = set(self.data[seeds[0]]["services"][0].keys())
    for seed in seeds:
        seed_data = set(self.data[seed]["services"][0].keys())
        available_data = available_data.intersection(seed_data)
    return list(available_data)

placement_statistics(self, placement, txtfile=None, filename=None, plot_hist=True, size=(5, 4), include_guests=False, seeds=None)

Show placement visitation statistics.

Parameters:

Name Type Description Default
placement int or str

Placement id or placement name to show statistics.

required
txtfile str

File name to save text output, if not informed will only show it.

None
plot_hist bool

Plots a histogram of the number of visits. Defaults to True.

True
filename str

File name to save the histogram, if not informed will only show the plot.

None
size tuple

Size to generate the plot. Defaults to (5, 4).

(5, 4)
include_guests bool

Includes guests as visitors. Defaults to False.

False
seeds list

List of seeds to plot, if None will plot all seeds available.

None
Source code in comorbuss/lab/analysis.py
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
def placement_statistics(
    self,
    placement,
    txtfile=None,
    filename=None,
    plot_hist=True,
    size=(5, 4),
    include_guests=False,
    seeds=None,
):
    """Show placement visitation statistics.

    Args:
        placement (int or str): Placement id or placement name to show statistics.
        txtfile (str, optional): File name to save text output, if not informed will only show it.
        plot_hist (bool, optional): Plots a histogram of the number of visits. Defaults to True.
        filename (str, optional): File name to save the histogram, if not informed will only show the plot.
        size (tuple, optional): Size to generate the plot. Defaults to (5, 4).
        include_guests (bool, optional): Includes guests as visitors. Defaults to False.
        seeds (list, optional): List of seeds to plot, if None will plot all seeds available.
    """
    # Load data and parameters
    data = self.get_data(["placement"], seeds)
    data_srvc = self.get_srvc_data(
        ["name", "placement", "workers", "chosen_instance", "guests"], seeds
    )
    placements = np.array(data["placement"])
    seeds = data["seeds"]
    Nparticles = self.parameters["Nparticles"]
    Nsteps = self.parameters["Nsteps"]
    Nseeds = len(seeds)
    Ndays = self.parameters["Ndays"]
    pid = np.arange(Nparticles)

    # Prepare data
    is_srvc = False
    if not placement in [S.PLC_HOME, S.PLC_ENV, "Homes", "Environment"]:
        # Find service
        srvc_found = False
        for srvc in data_srvc:
            if srvc["placement"][0] == placement:
                srvc_found = True
                break
            if srvc["name"][0] == placement:
                srvc_found = True
                placement = srvc["placement"][0]
                break
        if not srvc_found:
            self.raise_runtime(
                "{} is not a valid placement or placement name.".format(placement)
            )
        # Select visitors
        mask_visitors = np.array(srvc["chosen_instance"]) != -1
        for i in range(Nseeds):
            mask_workers = np.isin(pid, srvc["workers"][i])
            mask_visitors[i, mask_workers] = False
        is_srvc = True
        title = "{} visitations".format(srvc["name"][0])
    elif placement in [S.PLC_HOME, S.PLC_ENV, "Homes", "Environment"]:
        if placement == "Homes":
            placement = S.PLC_HOME
        if placement == "Environment":
            placement = S.PLC_ENV
        # If not service all particles are visitors
        mask_visitors = np.ones((Nseeds, Nparticles), dtype=bool)
        title = "Placement = {}".format(placement)
    else:
        self.raise_runtime(
            "{} is not a valid placement or placement name.".format(placement)
        )

    # Prepare to count visits and steps in placement
    count_visit = np.zeros((Nseeds, Nparticles))
    count_steps = np.zeros((Nseeds, Nparticles))
    for i in range(Nseeds):
        last_placement = placements[i, 0, :]
        for step in range(1, Nsteps):
            mask_change_plc = last_placement != placements[i, step, :]
            last_placement = placements[i, step, :]
            mask_plc = placements[i, step, :] == placement
            mask_visit = mask_change_plc & mask_plc
            if is_srvc and not include_guests:
                mask_guest = np.isin(pid, srvc["guests"][i][step])
                mask_visit = mask_visit & ~mask_guest
                mask_plc = mask_plc & ~mask_guest
            count_visit[i, mask_visit] += 1
            count_steps[i, mask_plc] += 1

    # Calculate values
    mean_n = np.mean(count_visit[mask_visitors])
    duration = count_steps / count_visit
    mask_duration = duration > 0
    mean_duration = np.mean(duration[mask_duration & mask_visitors])

    # Plot histogram
    if plot_hist:
        weights = (
            np.ones(count_visit[mask_visitors].shape)
            / count_visit[mask_visitors].shape
        )
        self.start_plt(size=size, title=title)
        self.plt.hist(
            count_visit[mask_visitors],
            weights=weights,
            bins=int(np.max(count_visit[mask_visitors])),
        )
        ax = self.plt.gca()
        ax.yaxis.set_major_formatter(PercentFormatter(1))
        self.stop_plt(
            filename=filename, xlabel="Number of visits", ylabel="% population"
        )
    out_strs = []

    # Save/print text output
    if Nseeds > 1:
        out_strs.append(
            "Mean number of available visitors: {}".format(
                np.sum(mask_visitors) / Nseeds
            )
        )
    else:
        out_strs.append(
            "Number of available visitors: {}".format(np.sum(mask_visitors))
        )
    out_strs.append("Mean number of visitations: {}".format(mean_n))
    out_strs.append("Mean visitation period: {} Days".format(Ndays / mean_n))
    out_strs.append("Mean visitation duration: {} Steps".format(mean_duration))
    if txtfile != None:
        f = open(txtfile, "w")
    for str in out_strs:
        try:
            f.write(str + "\n")
        except:
            print(str)
    if txtfile != None:
        f.close()

plot_R(self, seeds=None, **plot_args)

Save a R graph.

Important

This plot uses the do_plot method, see plot_args to see all available arguments.

Parameters:

Name Type Description Default
seeds list

List of seeds to plot, if None will plot all seeds available.

None
**plot_args kwargs

Arguments for the do_plot method (see plot_args).

{}
Source code in comorbuss/lab/analysis.py
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
def plot_R(self, seeds=None, **plot_args):
    """Save a R graph.

    !!! Important
        This plot uses the do_plot method, see [plot_args](#plot_args) to see all available arguments.

    Args:
        seeds (list, optional): List of seeds to plot, if None will plot all seeds available.
        **plot_args (kwargs): Arguments for the do_plot method (see [plot_args](#plot_args)).
    """
    # Prepare Data
    data = self.get_data(["Rot"], seeds)
    seeds = data["seeds"]
    data = {"R0t": np.array(data["Rot"])}
    Nsteps = self.parameters["Nsteps"]
    dt = self.parameters["dt"]
    t = dt * np.arange(Nsteps) / 24

    # Plot graphs
    def_plot_args = {
        "xlabel": "Days",
        "ylabel": "$R_{0t}$",
        "legend_args": {
            "labels": ["$R_0 $ = {:.3g} ".format(np.mean(data["R0t"][:, -1]))],
            "loc": "upper right",
        },
        "bands_legend_args": {"color": S.COLORS["blue"]},
    }
    plot_args = self.args_parse(plot_args, def_plot_args)
    self.do_plot(t, dt, data, [S.COLORS["blue"]], seeds, **plot_args)

plot_SEIR(self, seeds=None, **plot_args)

Save a SEIR graph.

Important

This plot uses the do_plot method, see plot_args to see all available arguments.

Parameters:

Name Type Description Default
seeds list

List of seeds to plot, if None will plot all seeds available.

None
**plot_args kwargs

Arguments for the do_plot method (see plot_args).

{}
Source code in comorbuss/lab/analysis.py
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
def plot_SEIR(self, seeds=None, **plot_args):
    """Save a SEIR graph.

    !!! Important
        This plot uses the do_plot method, see [plot_args](#plot_args) to see all available arguments.

    Args:
        seeds (list, optional): List of seeds to plot, if None will plot all seeds available.
        **plot_args (kwargs): Arguments for the do_plot method (see [plot_args](#plot_args)).
    """
    # Prepare Data
    data, seeds = self.seir_data(seeds)
    Nsteps = self.parameters["Nsteps"]
    dt = self.parameters["dt"]
    t = dt * np.arange(Nsteps) / 24

    # Plot graphs
    def_plot_args = {
        "xlabel": "Days",
        "ylabel": "% Population",
    }
    plot_args = self.args_parse(plot_args, def_plot_args)
    self.do_plot(t, dt, data, S.COLORS_STATES, seeds, **plot_args)

plot_SEIR_stack(self, filename=None, size=(5, 4), seed=-1, show_legend=True, dates=True, events_type=0, title=None)

Save a stacked SEIR graph. Can only plot one seed.

Parameters:

Name Type Description Default
filename str

File name to save the graph, if not informed will only show the plot.

None
size tuple

Size to generate the plot. Defaults to (5, 4).

(5, 4)
title str

Title to be printed on the plot.

None
seed str

Seed to be plotted, if None will plot last loaded.

-1
dates bool

Use dates instead of days in the x axis. Defaults to True.

True
show_legend bool

Hides legends if False. Defaults to True.

True
Source code in comorbuss/lab/analysis.py
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
def plot_SEIR_stack(
    self,
    filename=None,
    size=(5, 4),
    seed=-1,
    show_legend=True,
    dates=True,
    events_type=0,
    title=None,
):
    """Save a stacked SEIR graph. Can only plot one seed.

    Args:
        filename (str, optional): File name to save the graph, if not informed will only show the plot.
        size (tuple, optional): Size to generate the plot. Defaults to (5, 4).
        title (str, optional): Title to be printed on the plot.
        seed (str, optional): Seed to be plotted, if None will plot last loaded.
        dates (bool, optional): Use dates instead of days in the x axis. Defaults to True.
        show_legend (bool, optional): Hides legends if False. Defaults to True.
    """
    # Prepare Data
    if type(seed) is list:
        if len(seed) != 1:
            print(
                "[WARNING] Can only plot stacked SEIR with single seed, plotting last seed loaded."
            )
    data, seed = self.seir_data(seed)
    Nsteps = self.parameters["Nsteps"]
    dt = self.parameters["dt"]
    t = dt * np.arange(Nsteps) / 24

    # Plot graphs
    self.start_plt(size=size, title=title)
    stack = {}
    for k in reversed(list(data.keys())):
        stack[k] = data[k][0]
    self.plt.stackplot(
        t,
        stack.values(),
        colors=list(reversed(S.COLORS_STATES)),
        labels=stack.keys(),
    )
    self.plt.xlim(0, self.parameters["Ndays"])
    self.plt.ylim(0, 100)
    if show_legend:
        self.plt.legend(loc="upper left")
    self.stop_plt(
        filename=filename, xlabel="Days", ylabel="% Population", dates=dates
    )

plot_age_group_histogram(self, data='infected', percentage=False, filename=None, size=(5, 4), title=None, seed=-1, close=True)

Plots a specift count of particles per age group. Can only plot one seed.

Available counts:

  • infected: number of infected particles.
  • vaccinated: number of vaccinated particles.
  • deceased: number of deceased particles.
  • particles: total number of particles

Parameters:

Name Type Description Default
data str

Type of count to plot. Defaults to "infected".

'infected'
percentage bool

Y axis as a percentage. Defaults to False.

False
filename str

File name to save the graph, if not informed will only show the plot.

None
size tuple

Size for the plot. Defaults to (5, 4).

(5, 4)
title str

Title to be printed on the plot.

None
seed str

Seed to be plotted, if None will plot last loaded.

-1
close bool

If False doesn't show, save or close the plot so that the user can add more information to plot using the plt attribute from the class. Defaults to False.

True
Source code in comorbuss/lab/analysis.py
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
def plot_age_group_histogram(
    self,
    data="infected",
    percentage=False,
    filename=None,
    size=(5, 4),
    title=None,
    seed=-1,
    close=True,
):
    """Plots a specift count of particles per age group. Can only plot one seed.

    Available counts:

    * `infected`: number of infected particles.
    * `vaccinated`: number of vaccinated particles.
    * `deceased`: number of deceased particles.
    * `particles`: total number of particles

    Args:
        data (str, optional): Type of count to plot. Defaults to "infected".
        percentage (bool, optional): Y axis as a percentage. Defaults to False.
        filename (str, optional): File name to save the graph, if not informed will only show the plot.
        size (tuple, optional): Size for the plot. Defaults to (5, 4).
        title (str, optional): Title to be printed on the plot.
        seed (str, optional): Seed to be plotted, if None will plot last loaded.
        close (bool, optional): If False doesn't show, save or close the plot so that the user can add
            more information to plot using the plt attribute from the class. Defaults to False.
    """
    if type(seed) is list:
        if len(seed) != 1:
            print(
                "[WARNING] Can only plot age group histograms with single seed, plotting last seed loaded."
            )
    data_loaded = self.get_data(["inf_tree"], seed)
    particles = False
    if data.lower() == "infected":
        tag = "time_exposed"
    elif data.lower() == "vaccinated":
        tag = "time_vaccinated"
    elif data.lower() == "deceased":
        tag = "time_deceased"
    elif data.lower() == "particles":
        data = "of " + data
        tag = "age_group"
        particles = True
    else:
        self.raise_runtime("Invalid data {}, can't plot.".format(data))
    data_plot = np.zeros(len(S.ALL_AGES))
    count = np.zeros(len(S.ALL_AGES))
    inf_tree = data_loaded["inf_tree"][0]
    for node in inf_tree.nodes:
        for key in inf_tree.nodes[node].keys():
            if key.split("]")[-1] == tag:
                data_plot[inf_tree.nodes[node]["age_group"]] += 1
                break
        count[inf_tree.nodes[node]["age_group"]] += 1
    if particles:
        count = self.parameters["Nparticles"]
    if percentage:
        data_plot = (data_plot / count) * 100.0

    self.start_plt(size=size, title=title)
    plt.bar(S.AGE_DEF, data_plot)
    plt.xticks(rotation=45, horizontalalignment="right")
    if close:
        if percentage:
            self.stop_plt(
                filename=filename,
                xlabel="Age Groups",
                ylabel="Percentage {}".format(data),
            )
        else:
            self.stop_plt(
                filename=filename,
                xlabel="Age Groups",
                ylabel="Number {}".format(data),
            )

plot_contact_matrix_age_group(self, filename=None, slice_rng=slice(1, None, None), size=(10, 4), title=None, seed=-1, close=True)

Plot a contacts matrix per age group. Contacts are unique in a day, encounters are not (particle A can have multiple encounters with particle B in a single day, but only one contact).

Parameters:

Name Type Description Default
filename str

File name to save the graph, if not informed will only show the plot.

None
slice_rng slice

Slice of days (steps?) to plot. Defaults to slice(1, None).

slice(1, None, None)
size tuple

Size for the plot. Defaults to (10, 4).

(10, 4)
title str

Title to be printed on the plot.

None
seed str

Seed to be plotted, if None will plot last loaded.

-1
close bool

If False doesn't show, save or close the plot so that the user can add more information to plot using the plt attribute from the class. Defaults to False.

True
Source code in comorbuss/lab/analysis.py
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
def plot_contact_matrix_age_group(
    self,
    filename=None,
    slice_rng=slice(1, None),
    size=(10, 4),
    title=None,
    seed=-1,
    close=True,
):
    """Plot a contacts matrix per age group. Contacts are unique in a day,
        encounters are not (particle A can have multiple encounters with particle B in a
        single day, but only one contact).

    Args:
        filename (str, optional): File name to save the graph, if not informed will only show the plot.
        slice_rng (slice, optional): Slice of days (steps?) to plot. Defaults to slice(1, None).
        size (tuple, optional): Size for the plot. Defaults to (10, 4).
        title (str, optional): Title to be printed on the plot.
        seed (str, optional): Seed to be plotted, if None will plot last loaded.
        close (bool, optional): If False doesn't show, save or close the plot so that the user can add
            more information to plot using the plt attribute from the class. Defaults to False.
    """
    return self.plot_contact_or_encounters_age_group(
        True, filename, slice_rng, size, seed, title, close
    )

plot_diagnosed(self, seeds=None, cumulative=True, **plot_args)

Plots the number of encounters.

Important

This plot uses the do_plot method, see plot_args to see all available arguments.

Parameters:

Name Type Description Default
seeds list

List of seeds to plot, if None will plot all seeds available.

None
cumulative bool

Plot the cumulative diagnostics curve as well. Defaults to True.

True
**plot_args kwargs

Arguments for the do_plot method (see plot_args).

{}
Source code in comorbuss/lab/analysis.py
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
def plot_diagnosed(self, seeds=None, cumulative=True, **plot_args):
    """Plots the number of encounters.

    !!! Important
        This plot uses the do_plot method, see [plot_args](#plot_args) to see all available arguments.

    Args:
        seeds (list, optional): List of seeds to plot, if None will plot all seeds available.
        cumulative (bool, optional): Plot the cumulative diagnostics curve as well. Defaults to True.
        **plot_args (kwargs): Arguments for the do_plot method (see [plot_args](#plot_args)).
    """
    data = self.get_data(["diagnosed", "diagnosed_cum"], seeds)
    seeds = data["seeds"]
    Nparticles = self.parameters["Nparticles"]
    diag_cumm = np.array(data["diagnosed_cum"])
    data = {"diagnosed": np.array(data["diagnosed"]) * 100.0 / Nparticles}
    if cumulative:
        data["diagnosed cumulative"] = diag_cumm * 100.0 / Nparticles
    Nsteps = self.parameters["Nsteps"]
    dt = self.parameters["dt"]
    t = dt * np.arange(Nsteps) / 24

    # Plot graphs
    def_plot_args = {
        "xlabel": "Days",
        "ylabel": "% population diagnosed",
        "legend_args": {"loc": "upper left"},
        "bands_legend_args": {"color": S.COLORS["orange"], "loc": "center left"},
    }
    plot_args = self.args_parse(plot_args, def_plot_args)
    self.do_plot(
        t, dt, data, [S.COLORS["orange"], S.COLORS["red"]], seeds, **plot_args
    )

plot_encounters(self, seeds=None, plot_per_day=True, **plot_args)

Plots the number of encounters.

Important

This plot uses the do_plot method, see plot_args to see all available arguments.

Parameters:

Name Type Description Default
seeds list

List of seeds to plot, if None will plot all seeds available.

None
plot_per_day bool

Consolidate the data on a one day resolution.

True
**plot_args kwargs

Arguments for the do_plot method (see plot_args).

{}
Source code in comorbuss/lab/analysis.py
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
def plot_encounters(self, seeds=None, plot_per_day=True, **plot_args):
    """Plots the number of encounters.

    !!! Important
        This plot uses the do_plot method, see [plot_args](#plot_args) to see all available arguments.

    Args:
        seeds (list, optional): List of seeds to plot, if None will plot all seeds available.
        plot_per_day (bool, optional): Consolidate the data on a one day resolution.
        **plot_args (kwargs): Arguments for the do_plot method (see [plot_args](#plot_args)).
    """
    data = self.get_data(
        ["encounters", "encounters_infectious", "possible_infections"], seeds
    )
    seeds = data["seeds"]
    encounters = np.array(data["encounters"])
    encounters_infectious = np.array(data["encounters_infectious"])
    possible_infections = np.array(data["possible_infections"])
    Nparticles = self.parameters["Nparticles"]
    Nsteps = self.parameters["Nsteps"]
    dt = self.parameters["dt"]
    n_seeds = len(data["seeds"])
    if plot_per_day:
        encounters = (
            np.sum(
                encounters.reshape((n_seeds, int(Nsteps * dt / 24), int(24 / dt))),
                axis=2,
            )
            / Nparticles
        )
        encounters_infectious = (
            np.sum(
                encounters_infectious.reshape(
                    (n_seeds, int(Nsteps * dt / 24), int(24 / dt))
                ),
                axis=2,
            )
            / Nparticles
        )
        possible_infections = (
            np.sum(
                possible_infections.reshape(
                    (n_seeds, int(Nsteps * dt / 24), int(24 / dt))
                ),
                axis=2,
            )
            / Nparticles
        )
        t = np.arange(int(Nsteps * dt / 24))
        yLabel = "N of encounters per day*particle"
    else:
        t = dt * np.arange(Nsteps) / 24
        yLabel = "N of encounters per step"
    data = {
        "all encounters": encounters,
        "infectious -> any": encounters_infectious,
        "infectious -> susceptible": possible_infections,
    }
    colors = [S.COLORS["red"], S.COLORS["green"], S.COLORS["blue"]]

    # Plot graphs
    def_plot_args = {
        "xlabel": "Days",
        "ylabel": yLabel,
        "legend_args": {"loc": "upper left"},
        "bands_legend_args": {"color": S.COLORS["red"], "loc": "upper right"},
    }
    plot_args = self.args_parse(plot_args, def_plot_args)
    self.do_plot(t, dt, data, colors, seeds, **plot_args)

plot_encounters_age_group(self, filename=None, slice_rng=slice(1, None, None), size=(5, 4), title=None, seed=-1, close=True)

Plots number of encounters per age group on a slice of time.

Parameters:

Name Type Description Default
filename str

File name to save the graph, if not informed will only show the plot.

None
slice_rng slice

Slice of (steps?) to plot. Defaults to slice(1, None).

slice(1, None, None)
size tuple

Size for the plot. Defaults to (5, 4).

(5, 4)
title str

Title to be printed on the plot.

None
seed str

Seed to be plotted, if None will plot last loaded.

-1
close bool

If False doesn't show, save or close the plot so that the user can add more information to plot using the plt attribute from the class. Defaults to False.

True
Source code in comorbuss/lab/analysis.py
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
def plot_encounters_age_group(
    self,
    filename=None,
    slice_rng=slice(1, None),
    size=(5, 4),
    title=None,
    seed=-1,
    close=True,
):
    """Plots number of encounters per age group on a slice of time.

    Args:
        filename (str, optional): File name to save the graph, if not informed will only show the plot.
        slice_rng (slice, optional): Slice of (steps?) to plot. Defaults to slice(1, None).
        size (tuple, optional): Size for the plot. Defaults to (5, 4).
        title (str, optional): Title to be printed on the plot.
        seed (str, optional): Seed to be plotted, if None will plot last loaded.
        close (bool, optional): If False doesn't show, save or close the plot so that the user can add
            more information to plot using the plt attribute from the class. Defaults to False.
    """
    if type(seed) is list:
        if len(seed) != 1:
            print(
                "[WARNING] Can only plot encounters per age group with single seed, plotting last seed loaded."
            )
    data = self.get_data(["ages", "tracing"], seed)
    tracing = []
    for i in range(len(data["tracing"][0])):
        d = nx.to_dict_of_lists(data["tracing"][0][i])
        d = {int(pid): [int(i) for i in d[pid]] for pid in d.keys()}
        tracing.append(d)
    matrix_age_group = tools.get_mean_encounter_time_array_age_group(
        tracing, data["ages"][0], self.parameters["dt"]
    )
    bars = S.AGE_DEF
    pos = S.ALL_AGES

    self.start_plt(size=size, title=title)
    self.plt.title("Mean number of contacts between age groups / day")
    ax = self.plt.gca()
    ax.set_xlim(0, matrix_age_group.shape[0] - 1)
    ax.set_ylim(0, matrix_age_group.shape[1] - 1)
    sc = self.plt.imshow(matrix_age_group)
    sc.set_cmap("jet")
    self.plt.colorbar(sc)
    self.plt.tight_layout(pad=0.5)
    self.plt.xticks(pos[::5], bars[::5], rotation=45, horizontalalignment="right")
    self.plt.yticks(pos[4::5], bars[4::5], rotation=45, horizontalalignment="right")
    if close:
        self.stop_plt(filename=filename, xlabel="Age Groups", ylabel="Age Groups")

plot_encounters_matrix_age_group(self, filename=None, slice_rng=slice(1, None, None), size=(10, 4), title=None, seed=-1, close=True)

Plot an encounters matrix per age group. Contacts are unique in a day, encounters are not (particle A can have multiple encounters with particle B in a single day, but only one contact).

Parameters:

Name Type Description Default
filename str

File name to save the graph, if not informed will only show the plot.

None
slice_rng slice

Slice of days (steps?) to plot. Defaults to slice(1, None).

slice(1, None, None)
size tuple

Size for the plot. Defaults to (10, 4).

(10, 4)
title str

Title to be printed on the plot.

None
seed str

Seed to be plotted, if None will plot last loaded.

-1
close bool

If False doesn't show, save or close the plot so that the user can add more information to plot using the plt attribute from the class. Defaults to False.

True
Source code in comorbuss/lab/analysis.py
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
def plot_encounters_matrix_age_group(
    self,
    filename=None,
    slice_rng=slice(1, None),
    size=(10, 4),
    title=None,
    seed=-1,
    close=True,
):
    """Plot an encounters matrix per age group. Contacts are unique in a day,
        encounters are not (particle A can have multiple encounters with particle B in a
        single day, but only one contact).

    Args:
        filename (str, optional): File name to save the graph, if not informed will only show the plot.
        slice_rng (slice, optional): Slice of days (steps?) to plot. Defaults to slice(1, None).
        size (tuple, optional): Size for the plot. Defaults to (10, 4).
        title (str, optional): Title to be printed on the plot.
        seed (str, optional): Seed to be plotted, if None will plot last loaded.
        close (bool, optional): If False doesn't show, save or close the plot so that the user can add
            more information to plot using the plt attribute from the class. Defaults to False.
    """
    return self.plot_contact_or_encounters_age_group(
        False, filename, slice_rng, size, seed, title, close
    )

plot_homes_hist(self, data='Symptoms', bins=10, filename=None, size=(5, 4), title=None, seed=-1)

Plots histograms of the percentage of particles on each category on all homes. Can only plot one seed.

Available data:

  • symptoms: Plots percentages of mild symptomatic, severe symptomatic, asymptomatic and not infected;
  • infections: Plots percentages of Infected ans not infected.

Parameters:

Name Type Description Default
data str

Data to be plotted, "Symptoms" or "Infections". Defaults to "Symptoms".

'Symptoms'
bins int

Number of bins in the histogram. Defaults to 10.

10
filename str

File name to save the graph, if not informed will only show the plot.

None
size tuple

Size for the plot. Defaults to (5, 4).

(5, 4)
title str

Title to be printed on the plot.

None
seed str

Seed to be plotted, if None will plot last loaded.

-1

Exceptions:

Type Description
RuntimeWarning

Invalid data selected or data unavailible.

Source code in comorbuss/lab/analysis.py
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
def plot_homes_hist(
    self, data="Symptoms", bins=10, filename=None, size=(5, 4), title=None, seed=-1
):
    """Plots histograms of the percentage of particles on each category on all homes.
        Can only plot one seed.

    Available data:

    * `symptoms`: Plots percentages of mild symptomatic, severe symptomatic, asymptomatic
        and not infected;
    * `infections`: Plots percentages of Infected ans not infected.

    Args:
        data (str, optional): Data to be plotted, \"Symptoms\" or \"Infections\".
            Defaults to "Symptoms".
        bins (int, optional): Number of bins in the histogram. Defaults to 10.
        filename (str, optional): File name to save the graph, if not informed will only show the plot.
        size (tuple, optional): Size for the plot. Defaults to (5, 4).
        title (str, optional): Title to be printed on the plot.
        seed (str, optional): Seed to be plotted, if None will plot last loaded.

    Raises:
        RuntimeWarning: Invalid data selected or data unavailible.
    """
    if type(seed) is list:
        if len(seed) != 1:
            print(
                "[WARNING] Can only plot homes histograms with single seed, plotting last seed loaded."
            )
    if data.lower() == "symptoms":
        data_loaded = self.get_data(["symptoms", "homes"], seed)
        data_source = data_loaded["symptoms"][0][-1]
        data_dict = {
            "Mild Symptomatic": [S.SYMPT_YES, S.SYMPT_YES * 10],
            "Severe Symptomatic": [S.SYMPT_SEVERE, S.SYMPT_SEVERE * 10],
            "Asymptomatic": [S.SYMPT_NO, S.SYMPT_NO * 10, S.SYMPT_NYET],
            "Not Infected": [S.NO_INFEC],
        }
        data_color = S.COLORS_SYMPT[: len(data_dict)]
    elif data.lower() == "infections":
        data_loaded = self.get_data(["states", "homes"], seed)
        data_source = data_loaded["states"][0][-1]
        data_dict = {
            "Not Infected": [S.STATE_S],
            "Infected": [S.STATE_E, S.STATE_I, S.STATE_R],
        }
        data_color = [S.COLORS["blue"], S.COLORS["red"]]
    else:
        raise RuntimeWarning("{} is not a valid data.".format(data))
    homes = data_loaded["homes"][0]
    data_array = np.zeros((len(homes), len(data_dict)))
    for i, home in enumerate(homes.values()):
        for j, l in enumerate(data_dict.values()):
            for pid in home["pids"]:
                if data_source[pid] in l:
                    data_array[i, j] += 1
        data_array[i, :] /= home["nparticles"]

    for j, k in enumerate(data_dict.keys()):
        title = title or "Histogram of {} at homes".format(data.lower())
        self.start_plt(size=size, title=title)
        heights, x = np.histogram(data_array[:, j], bins=bins)
        heights = heights / np.sum(heights)
        x = x[:-1] + (x[1] - x[0]) / 2
        width = x[1] - x[0]
        self.plt.bar(x, heights, width=width, color=data_color[j], label=k)
        ax = self.plt.gca()
        ax.yaxis.set_major_formatter(PercentFormatter(1))
        ax.xaxis.set_major_formatter(PercentFormatter(1))
        if filename != None and len(data_dict) > 1:
            f = "{}_{}.{}".format(
                ".".join(filename.split(".")[:-1]), j, filename.split(".")[-1]
            )
        else:
            f = filename
        self.stop_plt(
            filename=f,
            xlabel="Percentage of the family",
            ylabel="Percentage of homes",
            legend=True,
        )

plot_homes_infection_hist(self, filename=None, size=(5, 4), seed=-1, title=None, bins=10, close=True)

Plots a histogram of the percentage of infection that occurred inside each home. Can only plot one seed.

Parameters:

Name Type Description Default
filename str

File name to save the graph, if not informed will only show the plot.

None
size tuple

Size to generate the plot. Defaults to (5, 4).

(5, 4)
title str

Title to be printed on the plot.

None
seed str

Seed to be plotted, if None will plot last loaded.

-1
bins int

Number of bins in the histogram. Defaults to 100.

10
close bool

If False doesn't show, save or close the plot so that the user can add more information to plot using the plt attribute from the class. Defaults to False.

True
Source code in comorbuss/lab/analysis.py
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
def plot_homes_infection_hist(
    self, filename=None, size=(5, 4), seed=-1, title=None, bins=10, close=True
):
    """Plots a histogram of the percentage of infection that occurred inside each home. Can only
        plot one seed.

    Args:
        filename (str, optional): File name to save the graph, if not informed will only show the plot.
        size (tuple, optional): Size to generate the plot. Defaults to (5, 4).
        title (str, optional): Title to be printed on the plot.
        seed (str, optional): Seed to be plotted, if None will plot last loaded.
        bins (int, optional): Number of bins in the histogram. Defaults to 100.
        close (bool, optional): If False doesn't show, save or close the plot so that the user can add
            more information to plot using the plt attribute from the class. Defaults to False.
    """
    if type(seed) is list:
        if len(seed) != 1:
            print(
                "[WARNING] Can only plot homes infection histogram with single seed, plotting last seed loaded."
            )
    data = self.get_data(["homesNumber", "home_id", "inf_placement"], seed)
    Nhomes = data["homesNumber"][0]
    serv_per_id = data["home_id"][0]
    inf_placement = data["inf_placement"][0]
    [inf_servs, tot_servs, inf_servs_percent] = tools.get_service_infection_percent(
        Nhomes, serv_per_id, inf_placement
    )

    # Plot graphs
    self.start_plt(size=size, title=title)
    plt.hist(inf_servs_percent, bins=bins)
    if close:
        self.stop_plt(
            filename=filename,
            xlabel="Percentage of particles infected at home",
            ylabel="Number of homes",
        )
    return inf_servs, tot_servs, inf_servs_percent

plot_inf_probability(self, filename=None, seed=-1, bins=100, size=(5, 4), title=None, remove_zeros=False, close=True)

Plot a histogram of the maximum infection probability of all particles. Can only plot one seed.

Parameters:

Name Type Description Default
filename str

File name to save the graph, if not informed will only show the plot.

None
bins int

Number of bins in the histogram. Defaults to 100.

100
size tuple

Size to generate the plot. Defaults to (5, 4).

(5, 4)
title str

Title to be printed on the plot.

None
seed str

Seed to be plotted, if None will plot last loaded.

-1
remove_zeros bool

Ignore particles with infection probability equals to zero. Defaults to False.

False
close bool

If False doesn't show, save or close the plot so that the user can add more information to plot using the plt attribute from the class. Defaults to False.

True
Source code in comorbuss/lab/analysis.py
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
def plot_inf_probability(
    self,
    filename=None,
    seed=-1,
    bins=100,
    size=(5, 4),
    title=None,
    remove_zeros=False,
    close=True,
):
    """Plot a histogram of the maximum infection probability of all particles. Can only plot one seed.

    Args:
        filename (str, optional): File name to save the graph, if not informed will only show the plot.
        bins (int, optional): Number of bins in the histogram. Defaults to 100.
        size (tuple, optional): Size to generate the plot. Defaults to (5, 4).
        title (str, optional): Title to be printed on the plot.
        seed (str, optional): Seed to be plotted, if None will plot last loaded.
        remove_zeros (bool, optional): Ignore particles with infection probability equals to zero.
            Defaults to False.
        close (bool, optional): If False doesn't show, save or close the plot so that the user can add
            more information to plot using the plt attribute from the class. Defaults to False.
    """
    if type(seed) is list:
        if len(seed) != 1:
            print(
                "[WARNING] Can only plot infection probability with single seed, plotting last seed loaded."
            )
    data = self.get_data(["inf_prob"], seed)
    inf_prob = np.max(data["inf_prob"][0], axis=0)
    if remove_zeros:
        inf_prob = inf_prob[inf_prob > 0]
    mean = np.mean(inf_prob)
    median = np.median(inf_prob)

    # Plot graphs
    self.start_plt(size=size, title=title)
    count, _, _ = self.plt.hist(inf_prob, bins=bins, density=False)
    self.plt.plot(
        [mean, mean], [0, np.max(count)], "--", label="mean = {:}".format(mean)
    )
    self.plt.plot(
        [median, median],
        [0, np.max(count)],
        "--",
        label="median = {:}".format(median),
    )
    if close:
        self.stop_plt(
            filename=filename,
            xlabel="Infection probability",
            ylabel="Number of particles",
        )

plot_inf_source_symptoms(self, filename=None, seed=-1, hide_zeros=False, size=(5, 4), title=None, pie=True, close=True)

Plot vector symptom data. Can only plot one seed.

Parameters:

Name Type Description Default
filename str

File name to save the graph, if not informed will only show the plot.

None
hide_zeros bool

Hide placements with no infections. Defaults to False.

False
size tuple

Size to generate the plot. Defaults to (10, 4).

(5, 4)
title str

Title to be printed on the plot.

None
seed str

Seed to be plotted, if None will plot last loaded.

-1
close bool

If False doesn't show, save or close the plot so that the user can add more information to plot using the plt attribute from the class. Defaults to False.

True
Source code in comorbuss/lab/analysis.py
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
def plot_inf_source_symptoms(
    self,
    filename=None,
    seed=-1,
    hide_zeros=False,
    size=(5, 4),
    title=None,
    pie=True,
    close=True,
):
    """Plot vector symptom data. Can only plot one seed.

    Args:
        filename (str, optional): File name to save the graph, if not informed will only show the plot.
        hide_zeros (bool, optional): Hide placements with no infections. Defaults to False.
        size (tuple, optional): Size to generate the plot. Defaults to (10, 4).
        title (str, optional): Title to be printed on the plot.
        seed (str, optional): Seed to be plotted, if None will plot last loaded.
        close (bool, optional): If False doesn't show, save or close the plot so that the user can add
            more information to plot using the plt attribute from the class. Defaults to False.
    """
    if type(seed) is list:
        if len(seed) != 1:
            print(
                "[WARNING] Can only plot infections with single seed, plotting last seed loaded."
            )
    data = self.get_data(["inf_vector_sympt"], seed)
    vec_symptoms = data["inf_vector_sympt"][0]
    # Classify infections by symptomatic state of vector
    data_symp = {
        "mild symptomatic": np.sum(vec_symptoms == S.SYMPT_YES),
        "severe symptomatic": np.sum(vec_symptoms == S.SYMPT_SEVERE),
        "asymptomatic": np.sum(vec_symptoms == S.SYMPT_NO),
        "pre-symptomatic": np.sum(vec_symptoms == S.SYMPT_NYET),
    }
    Ninfections = np.sum(list(data_symp.values()))
    for k in data_symp.keys():
        data_symp[k] = data_symp[k] * 100 / np.max([Ninfections, 1.0])

    # Plot graphs
    title = title or "Infection source symptoms"
    self.start_plt(size=size, title=title)
    if pie:
        autotexts = self.plt.pie(
            data_symp.values(),
            labels=data_symp.keys(),
            colors=S.COLORS_SYMPT,
            autopct="%1.1f%%",
        )[2]
        self.plt.setp(autotexts, color="white")
    else:
        x = np.arange(len(data_symp))
        self.plt.bar(x, data_symp.values())  # ,
        self.plt.xticks(
            x, data_symp.keys(), rotation=45, horizontalalignment="right"
        )
    if close:
        self.stop_plt(filename=filename, tight_layout=True)

plot_inf_tree(self, filename=None, size=(20, 20), seed=-1, color=None, title=None, close=True)

Plots the infection tree. Can only plot one seed.

Available color markers: * placement: placement where the infection occurred.

Parameters:

Name Type Description Default
filename str

File name to save the graph, if not informed will only show the plot.

None
size tuple

Size for the plot. Defaults to (20, 20).

(20, 20)
seed str

Seed to be plotted, if None will plot last loaded.

-1
color str

A color marker. Defaults to None.

None
title str

Title for the plot. Defaults to None.

None
close bool

If False doesn't show, save or close the plot so that the user can add more information to plot using the plt attribute from the class. Defaults to False.

True
Source code in comorbuss/lab/analysis.py
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
def plot_inf_tree(
    self, filename=None, size=(20, 20), seed=-1, color=None, title=None, close=True
):
    """Plots the infection tree. Can only plot one seed.

    Available color markers:
    * `placement`: placement where the infection occurred.

    Args:
        filename (str, optional): File name to save the graph, if not informed will only show the plot.
        size (tuple, optional): Size for the plot. Defaults to (20, 20).
        seed (str, optional): Seed to be plotted, if None will plot last loaded.
        color (str, optional): A color marker. Defaults to None.
        title (str, optional): Title for the plot. Defaults to None.
        close (bool, optional): If False doesn't show, save or close the plot so that the user can add
            more information to plot using the plt attribute from the class. Defaults to False.
    """
    if type(seed) is list:
        if len(seed) != 1:
            print(
                "[WARNING] Can only plot time between histograms with single seed, plotting last seed loaded."
            )
    data_loaded = self.get_data(["inf_tree"], seed)
    inf_tree = data_loaded["inf_tree"][0]
    plt.figure(figsize=size)
    if title != None:
        plt.title(title)
    nodes = {}
    for node, data in inf_tree.nodes(data=True):
        if "time_exposed" in data:
            nodes[node] = data
    if color == "placement":
        colors_orign = sns.color_palette("bright")
        colors = []
        plc_colors = {}
        i_plc = 0
        for node, plc in inf_tree.nodes(data="inf_placement"):
            if node in nodes.keys():
                if plc in plc_colors.keys():
                    colors.append(plc_colors[plc])
                else:
                    if plc == None:
                        colors.append(colors_orign[-1])
                    else:
                        plc_colors[plc] = colors_orign[i_plc]
                        i_plc += 1
                        colors.append(plc_colors[plc])
        print(plc_colors)
    else:
        colors = "blue"
    pos = graphviz_layout(inf_tree, prog="twopi", args="-Goverlap=scalexy")
    nx.draw(
        inf_tree,
        pos,
        nodelist=nodes.keys(),
        node_size=100,
        font_color="white",
        font_size=4,
        node_color=colors,
        with_labels=True,
    )
    plt.tight_layout(pad=0.5)
    if close:
        if filename == None:
            plt.show()
        else:
            plt.savefig(filename)

plot_infection_placement(self, filename=None, seeds=None, size=(5, 4), skip=[], close=True, title=None)

Plot infection placement data.

Parameters:

Name Type Description Default
filename str

File name to save the graph, if not informed will only show the plot.

None
size tuple

Size to generate the plot. Defaults to (10, 4).

(5, 4)
title str

Title to be printed on the plot.

None
seeds list

List of seeds to plot, if None will plot all seeds available.

None
skip list

List of placements names to skip plotting.

[]
close bool

If False doesn't show, save or close the plot so that the user can add more information to plot using the plt attribute from the class. Defaults to False.

True
Source code in comorbuss/lab/analysis.py
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
def plot_infection_placement(
    self, filename=None, seeds=None, size=(5, 4), skip=[], close=True, title=None
):
    """Plot infection placement data.

    Args:
        filename (str, optional): File name to save the graph, if not informed will only show the plot.
        size (tuple, optional): Size to generate the plot. Defaults to (10, 4).
        title (str, optional): Title to be printed on the plot.
        seeds (list, optional): List of seeds to plot, if None will plot all seeds available.
        skip (list, optional): List of placements names to skip plotting.
        close (bool, optional): If False doesn't show, save or close the plot so that the user can add
            more information to plot using the plt attribute from the class. Defaults to False.
    """
    seeds = self.get_seeds(seeds)
    if len(seeds) == 1:
        self.plot_infection_placement_single_seed(
            filename, seeds, size, skip, close, title
        )
    else:
        self.plot_infection_placement_multi_seed(
            filename, seeds, size, skip, close, title
        )

plot_isolation_percentage(self, filename=None, size=(5, 4), seeds=None, dates=True, start_day=None, end_day=None, title=None, events=False, events_type=0)

Plot a isolation curve in time.

Parameters:

Name Type Description Default
filename str

File name to save the graph, if not informed will only show the plot.

None
size tuple

Size to generate the plot. Defaults to (5, 4).

(5, 4)
title str

Title to be printed on the plot.

None
seeds list

List of seeds to plot, if None will plot all seeds available.

None
dates bool

Use dates instead of days in the x axis. Defaults to True.

True
start_day float

Plot only the interval from start_day. Defaults to 0.

None
end_day float

Plot only the interval to end_day. Defaults to last day.

None
events bool

Overlay simulation events on the plot. Defaults to False.

False
events_type int

Type of logs to overlay as events. Defaults to S.MSG_EVENTS.

0
Source code in comorbuss/lab/analysis.py
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
def plot_isolation_percentage(
    self,
    filename=None,
    size=(5, 4),
    seeds=None,
    dates=True,
    start_day=None,
    end_day=None,
    title=None,
    events=False,
    events_type=0,
):
    """Plot a isolation curve in time.

    Args:
        filename (str, optional): File name to save the graph, if not informed will only show the plot.
        size (tuple, optional): Size to generate the plot. Defaults to (5, 4).
        title (str, optional): Title to be printed on the plot.
        seeds (list, optional): List of seeds to plot, if None will plot all seeds available.
        dates (bool, optional): Use dates instead of days in the x axis. Defaults to True.
        start_day (float, optional): Plot only the interval from start_day. Defaults to 0.
        end_day (float, optional): Plot only the interval to end_day. Defaults to last day.
        events (bool, optional): Overlay simulation events on the plot. Defaults to False.
        events_type (int, optional): Type of logs to overlay as events. Defaults to S.MSG_EVENTS.
    """
    # Prepare Data
    data = self.get_data(["isol_pct"], seeds)
    isol_ts = np.array(data["isol_pct"])
    Ndays = self.parameters["Ndays"]
    dt = self.parameters["dt"]
    t = np.arange(Ndays)
    interval = self.days_to_interval(start_day, end_day, dt)

    # Plot graphs
    self.start_plt(size=size, title=title)
    self.plot_line(t, isol_ts, color="red", label="isolated")
    if events:
        self.plot_events(seeds, events_type=events_type)
        self.plt.legend()
    dates_args = {"start_day": start_day, "end_day": end_day}
    self.stop_plt(
        filename=filename,
        xlabel="Days",
        ylabel="% Isolated",
        dates=dates,
        dates_args=dates_args,
    )

plot_quarantine(self, seeds=None, **plot_args)

Plots the number of encounters.

Important

This plot uses the do_plot method, see plot_args to see all available arguments.

Parameters:

Name Type Description Default
seeds list

List of seeds to plot, if None will plot all seeds available.

None
**plot_args kwargs

Arguments for the do_plot method (see plot_args).

{}
Source code in comorbuss/lab/analysis.py
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
def plot_quarantine(self, seeds=None, **plot_args):
    """Plots the number of encounters.

    !!! Important
        This plot uses the do_plot method, see [plot_args](#plot_args) to see all available arguments.

    Args:
        seeds (list, optional): List of seeds to plot, if None will plot all seeds available.
        **plot_args (kwargs): Arguments for the do_plot method (see [plot_args](#plot_args)).
    """
    data = self.get_data(["quarantined"], seeds)
    seeds = data["seeds"]
    quarantined = np.array(data["quarantined"])
    Nparticles = self.parameters["Nparticles"]
    data = {"All": None}
    for qrnt in self.parameters["quarantines"]:
        data[qrnt["name"]] = quarantined[:, int(qrnt["id"]), :] * 100 / Nparticles
        try:
            data["All"] = data["All"] + data[qrnt["name"]]
        except:
            data["All"] = data[qrnt["name"]]
    if len(self.parameters["quarantines"]) <= 1:
        del data["All"]
    Nsteps = self.parameters["Nsteps"]
    dt = self.parameters["dt"]
    t = dt * np.arange(Nsteps) / 24

    # Plot graphs
    def_plot_args = {
        "xlabel": "Days",
        "ylabel": "% population in quarantine",
        "legend_args": {"loc": "upper left"},
        "bands_legend_args": {"color": S.COLORS_LIST[0], "loc": "upper right"},
    }
    plot_args = self.args_parse(plot_args, def_plot_args)
    self.do_plot(t, dt, data, S.COLORS_LIST, seeds, **plot_args)

plot_secondary_infections_hist(self, filename=None, size=(5, 4), title=None, seed=-1, close=True)

Plot a secondary infections histogram. Can only plot one seed.

Parameters:

Name Type Description Default
filename str

File name to save the graph, if not informed will only show the plot.

None
size tuple

Size to generate the plot. Defaults to (5, 4).

(5, 4)
title str

Title to be printed on the plot.

None
seed str

Seed to be plotted, if None will plot last loaded.

-1
close bool

If False doesn't show, save or close the plot so that the user can add more information to plot using the plt attribute from the class. Defaults to False.

True
Source code in comorbuss/lab/analysis.py
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
def plot_secondary_infections_hist(
    self, filename=None, size=(5, 4), title=None, seed=-1, close=True
):
    """Plot a secondary infections histogram. Can only plot one seed.

    Args:
        filename (str, optional): File name to save the graph, if not informed will only show the plot.
        size (tuple, optional): Size to generate the plot. Defaults to (5, 4).
        title (str, optional): Title to be printed on the plot.
        seed (str, optional): Seed to be plotted, if None will plot last loaded.
        close (bool, optional): If False doesn't show, save or close the plot so that the user can add
            more information to plot using the plt attribute from the class. Defaults to False.
    """
    if type(seed) is list:
        if len(seed) != 1:
            print(
                "[WARNING] Can only plot secondary infections with single seed, plotting last seed loaded."
            )
    data = self.get_data(["inf_source", "states"], seed)
    [
        source_inf_ind,
        source_inf_count,
        nonzeropercent,
        infectiouspercent,
    ] = tools.get_source_inf_count(data["inf_source"][0], data["states"][0][-2, :])
    nbins = np.max(source_inf_count)

    # Plot graphs
    self.start_plt(size=size, title=title)
    self.plt.hist(source_inf_count, bins=nbins)
    self.plt.legend(
        ["Effective = {:.1f} of infectious".format(nonzeropercent * 100)]
    )
    if close:
        self.stop_plt(
            filename=filename,
            xlabel="Number of secondary infections",
            ylabel="Number of particles",
        )
    return source_inf_ind, source_inf_count, nonzeropercent, infectiouspercent

plot_service_infections(self, filename=None, seeds=None, size=(10, 4), skip=[], close=True, title=None)

Plots proportion of infections relating clients and workers inside each service

Returns:

Type Description

Three graphs, the first telling the proportion of infection derived from workers and clients, the second from workers to workers and clients, and the third from clients to workers and clients

PS: This code has been developed by Edmilson Roque - USP edmilson.roque.usp@gmail.com

Source code in comorbuss/lab/analysis.py
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
def plot_service_infections(
    self, filename=None, seeds=None, size=(10, 4), skip=[], close=True, title=None
):
    """Plots proportion of infections relating clients and workers inside each service

    Args:
        to do

    Returns:
        Three graphs, the first telling the proportion of infection derived from workers and clients, the second from workers to workers and clients, and the third from clients to workers and clients

    PS: This code has been developed by Edmilson Roque - USP <edmilson.roque.usp@gmail.com>
    """
    # Making sure uncertainties is installed
    try:
        from uncertainties import ufloat
        from uncertainties import unumpy as unp
    except Exception as e:
        print(
            e,
            "Please install package 'uncertainties' in order to compare simulations amongst each other",
        )

    colors_deep = sns.color_palette("muted")
    S.COLORS_DEEP = {
        "blue": colors_deep[0],
        "orange": colors_deep[1],
        "green": colors_deep[2],
        "red": colors_deep[3],
        "purple": colors_deep[4],
        "brown": colors_deep[5],
        "pink": colors_deep[6],
        "grey": colors_deep[7],
        "yellow": colors_deep[8],
        "teal": colors_deep[9],
    }
    """Colors for ploting graphs, less bright variant
    (available colors: blue, orange, green, red, purple, brown, pink,
     gray, yellow, teal)"""

    S.COLORS_DEEP_LIST = list(S.COLORS_DEEP.values())

    self.start_plt(size=size, title=title)
    fig, ax = self.plt.subplots(1, 3, dpi=300, figsize=size)  # , sharey=True)
    # fig.suptitle('Proportion of infections at service', fontsize=10)

    places = self.post_processed_data["service_labels"][1]
    num_srvc = len(places)

    mean_infs = np.mean(self.post_processed_data["num_infs"][1])
    std_infs = np.std(self.post_processed_data["num_infs"][1])
    mean_infs_from_w = np.mean(self.post_processed_data["infs_from_w"][1], axis=0)
    std_infs_from_w = np.std(self.post_processed_data["infs_from_w"][1], axis=0)
    mean_infs_wtow = np.mean(
        self.post_processed_data["infs_from_w_to_w"][1], axis=0
    )
    std_infs_wtow = np.std(self.post_processed_data["infs_from_w_to_w"][1], axis=0)
    mean_infs_wtoc = np.mean(
        self.post_processed_data["infs_from_w_to_c"][1], axis=0
    )
    std_infs_wtoc = np.std(self.post_processed_data["infs_from_w_to_c"][1], axis=0)
    mean_infs_from_c = np.mean(self.post_processed_data["infs_from_c"][1], axis=0)
    std_infs_from_c = np.std(self.post_processed_data["infs_from_c"][1], axis=0)
    mean_infs_ctow = np.mean(
        self.post_processed_data["infs_from_c_to_w"][1], axis=0
    )
    std_infs_ctow = np.std(self.post_processed_data["infs_from_c_to_w"][1], axis=0)
    mean_infs_ctoc = np.mean(
        self.post_processed_data["infs_from_c_to_c"][1], axis=0
    )
    std_infs_ctoc = np.std(self.post_processed_data["infs_from_c_to_c"][1], axis=0)

    infs = ufloat(mean_infs, std_infs)

    # Infections at service from workers/clients
    perc_infs_from_w = np.zeros(num_srvc)
    std_perc_infs_from_w = np.zeros(num_srvc)
    for ind, from_w in enumerate(unp.uarray(mean_infs_from_w, std_infs_from_w)):
        perc_infs_from_w[ind] = 100 * (from_w / infs).n
        std_perc_infs_from_w[ind] = 100 * (from_w / infs).s
    ax[0].bar(
        places,
        perc_infs_from_w,
        0.5,
        yerr=std_perc_infs_from_w,
        color=S.COLORS_DEEP_LIST[4],
        ecolor=S.COLORS_DEEP_LIST[2],
    )
    perc_infs_from_c = np.zeros(num_srvc)
    std_perc_infs_from_c = np.zeros(num_srvc)
    for ind, from_c in enumerate(unp.uarray(mean_infs_from_c, std_infs_from_c)):
        perc_infs_from_c[ind] = 100 * (from_c / infs).n
        std_perc_infs_from_c[ind] = 100 * (from_c / infs).s
    ax[0].bar(
        places,
        perc_infs_from_c,
        0.5,
        bottom=perc_infs_from_w,
        color=S.COLORS_DEEP_LIST[1],
        ecolor=S.COLORS_DEEP_LIST[9],
    )
    ax[0].set_xticks(np.arange(0, len(places), 1, dtype=int))
    ax[0].set_xticklabels(places, rotation=45, horizontalalignment="right")
    ax[0].set_title("Infs. derived from workers/clients", fontsize=8)
    ax[0].set_ylabel("% of infections w resp. to all new infections")
    ax[0].legend(["from workers", "from clients"])

    # Infections at service from workers to workers/clients
    perc_infs_wtow = np.zeros(num_srvc)
    std_perc_infs_wtow = np.zeros(num_srvc)
    for ind, (wtow, from_w) in enumerate(
        zip(
            unp.uarray(mean_infs_wtow, std_infs_wtow),
            unp.uarray(mean_infs_from_w, std_infs_from_w),
        )
    ):
        if from_w.n != 0:
            perc_infs_wtow[ind] = 100 * (wtow / from_w).n
            std_perc_infs_wtow[ind] = 100 * (wtow / from_w).s
        else:
            perc_infs_wtow[ind] = 0
            std_perc_infs_wtow[ind] = 0
    ax[1].bar(
        places,
        perc_infs_wtow,
        0.5,
        yerr=std_perc_infs_wtow,
        color="indigo",
        ecolor=S.COLORS_DEEP_LIST[2],
    )
    perc_infs_wtoc = np.zeros(num_srvc)
    std_perc_infs_wtoc = np.zeros(num_srvc)
    for ind, (wtoc, from_w) in enumerate(
        zip(
            unp.uarray(mean_infs_wtoc, std_infs_wtoc),
            unp.uarray(mean_infs_from_w, std_infs_from_w),
        )
    ):
        if from_w.n != 0:
            perc_infs_wtoc[ind] = 100 * (wtoc / from_w).n
            std_perc_infs_wtoc[ind] = 100 * (wtoc / from_w).s
        else:
            perc_infs_wtoc[ind] = 0
            std_perc_infs_wtoc[ind] = 0
    ax[1].bar(
        places,
        perc_infs_wtoc,
        0.5,
        bottom=perc_infs_wtow,
        color="darkorchid",
        ecolor=S.COLORS_DEEP_LIST[9],
    )
    # yerr=std_perc_infs_wtow,
    ax[1].hlines(
        50,
        -0.3,
        len(places) - 0.55,
        linestyles="dashed",
        colors=S.COLORS_DEEP_LIST[9],
    )
    ax[1].set_xticks(np.arange(0, len(places), 1, dtype=int))
    ax[1].set_xticklabels(places, rotation=45, horizontalalignment="right")
    ax[1].set_title("Infs. from workers to workers/clients", fontsize=8)
    ax[1].set_ylabel("% of infections w resp. to worker infections")
    ax[1].legend(["50%", "to workers", "to clients"])

    # Infections at service from clients to workers/clients
    perc_infs_ctow = np.zeros(num_srvc)
    std_perc_infs_ctow = np.zeros(num_srvc)
    for ind, (ctow, from_c) in enumerate(
        zip(
            unp.uarray(mean_infs_ctow, std_infs_ctow),
            unp.uarray(mean_infs_from_c, std_infs_from_c),
        )
    ):
        if from_c.n != 0:
            perc_infs_ctow[ind] = 100 * (ctow / from_c).n
            std_perc_infs_ctow[ind] = 100 * (ctow / from_c).s
        else:
            perc_infs_ctow[ind] = 0
            std_perc_infs_ctow[ind] = 0
    ax[2].bar(
        places,
        perc_infs_ctow,
        0.5,
        yerr=std_perc_infs_ctow,
        color="indigo",
        ecolor=S.COLORS_DEEP_LIST[2],
    )
    perc_infs_ctoc = np.zeros(num_srvc)
    std_perc_infs_ctoc = np.zeros(num_srvc)
    for ind, (ctoc, from_c) in enumerate(
        zip(
            unp.uarray(mean_infs_ctoc, std_infs_ctoc),
            unp.uarray(mean_infs_from_c, std_infs_from_c),
        )
    ):
        if from_c.n != 0:
            perc_infs_ctoc[ind] = 100 * (ctoc / from_c).n
            std_perc_infs_ctoc[ind] = 100 * (ctoc / from_c).s
        else:
            perc_infs_ctoc[ind] = 0
            std_perc_infs_ctoc[ind] = 0
    ax[2].bar(
        places,
        perc_infs_ctoc,
        0.5,
        bottom=perc_infs_ctow,
        color="darkorchid",
        ecolor=S.COLORS_DEEP_LIST[9],
    )
    # yerr=std_perc_infs_ctow,
    ax[2].hlines(
        50,
        -0.3,
        len(places) - 0.55,
        linestyles="dashed",
        colors=S.COLORS_DEEP_LIST[9],
    )
    ax[2].set_xticks(np.arange(0, len(places), 1, dtype=int))
    ax[2].set_xticklabels(places, rotation=45, horizontalalignment="right")
    ax[2].set_title("Infs. from clients to workers/clients", fontsize=8)
    ax[2].set_ylabel("% of infections w resp. to client infections")
    ax[2].legend(["50%", "to workers", "to clients"])

    if close:
        self.stop_plt(filename=filename)

plot_services_visitors(self, time_window='day', seeds=None, per_instance=False, **plot_args)

Plots the mean number of visitors on services in an week, whole simulation or a day window of time.

Important

This plot uses the do_plot method, see plot_args to see all available arguments.

Parameters:

Name Type Description Default
time_window str

"week", "day" or "simulation". Defaults to "day".

'day'
per_instance bool

If True will divide the number of visitors by the number of instances. Defaults to False.

False
seeds list

List of seeds to plot, if None will plot all seeds available.

None
Source code in comorbuss/lab/analysis.py
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
def plot_services_visitors(
    self, time_window="day", seeds=None, per_instance=False, **plot_args
):
    """Plots the mean number of visitors on services in an week, whole simulation or a day window of time.

    !!! Important
        This plot uses the do_plot method, see [plot_args](#plot_args) to see all available arguments.

    Args:
        time_window (str, optional): "week", "day" or "simulation". Defaults to "day".
        per_instance (bool, optional): If True will divide the number of visitors by the number of instances. Defaults to False.
        seeds (list, optional): List of seeds to plot, if None will plot all seeds available.
    """
    loaded_data = self.get_srvc_data(["visitors_count"], seeds=seeds)
    dt = self.parameters["dt"]
    seeds = loaded_data[0]["seeds"]
    Nsteps = self.parameters["Nsteps"]

    if time_window == "week":
        t_window = int(7 * 24 / dt)
    elif time_window == "day":
        t_window = int(24 / dt)
    elif time_window == "simulation":
        t_window = Nsteps
    else:
        self.raise_runtime(
            "Invalid time window {}, select week or day.".format(time_window)
        )

    data = {}
    for sid, srvc in enumerate(loaded_data):
        visits = np.zeros((len(seeds), t_window, 2))
        visitors_count = np.array(srvc["visitors_count"])
        if per_instance:
            visitors_count /= self.parameters["services"][sid]["number"]
        for s in range(len(seeds)):
            clk = clock(start_date=self.parameters["start_date"], dt=dt)
            for _ in range(self.parameters["Nsteps"]):
                if time_window == "week":
                    i = int(clk.dow * 24 / dt + clk.tod / dt)
                elif time_window == "day":
                    i = int(clk.tod / dt)
                elif time_window == "simulation":
                    i = clk.step
                if not (
                    time_window == "day"
                    and not self.parameters["services"][sid]["days"][clk.dow]
                ):
                    visits[s, i, 0] += visitors_count[s, clk.step]
                    visits[s, i, 1] += 1
                clk.tick()
        srvc_name = self.parameters["services"][sid]["name"]
        data["{} visitors".format(srvc_name)] = visits[:, :, 0] / visits[:, :, 1]
    if time_window == "simulation":
        t = dt * np.arange(Nsteps) / 24
    else:
        t = np.arange(t_window)
    colors = S.COLORS_LIST[: len(data)]

    def_plot_args = {
        "xlabel": "Hour of the {}".format(time_window),
        "ylabel": "Number of visitors",
        "legend_args": {"loc": "upper left"},
        "bands_legend_args": {"color": colors[0], "loc": "upper right"},
        "dates": time_window == "simulation",
    }
    if time_window == "simulation":
        def_plot_args["xlabel"] = "Date"
    if per_instance:
        def_plot_args["ylabel"] += " per instance"
    plot_args = self.args_parse(plot_args, def_plot_args)
    self.do_plot(t, dt, data, colors, seeds, **plot_args)

plot_symptomatic_states(self, seeds=None, **plot_args)

Plots the number of particles in each symptomatic state in time.

Important

This plot uses the do_plot method, see plot_args to see all available arguments.

Parameters:

Name Type Description Default
seeds list

List of seeds to plot, if None will plot all seeds available.

None
**plot_args kwargs

Arguments for the do_plot method (see plot_args).

{}
Source code in comorbuss/lab/analysis.py
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
def plot_symptomatic_states(self, seeds=None, **plot_args):
    """Plots the number of particles in each symptomatic state in time.

    !!! Important
        This plot uses the do_plot method, see [plot_args](#plot_args) to see all available arguments.

    Args:
        seeds (list, optional): List of seeds to plot, if None will plot all seeds available.
        **plot_args (kwargs): Arguments for the do_plot method (see [plot_args](#plot_args)).
    """
    # Prepare Data
    data = self.get_data(
        [
            "pre_symptomatic",
            "asymptomatic",
            "symptomatic",
            "severe_symptomatic",
            "exposed",
        ],
        seeds,
    )
    Nparticles = self.parameters["Nparticles"]
    seeds = data["seeds"]
    data = {
        "mild symp": np.array(data["symptomatic"]) * 100 / Nparticles,
        "severe symp": np.array(data["severe_symptomatic"]) * 100 / Nparticles,
        "asymptomatic": np.array(data["asymptomatic"]) * 100 / Nparticles,
        "pre-symptomatic": np.array(data["pre_symptomatic"]) * 100 / Nparticles,
        "incubating": np.array(data["exposed"]) * 100 / Nparticles,
    }
    dt = self.parameters["dt"]
    t = dt * np.arange(self.parameters["Nsteps"]) / 24

    # Plot graphs
    def_plot_args = {
        "xlabel": "Days",
        "ylabel": "% Population",
        "bands_legend_args": {"color": S.COLORS_SYMPT[0]},
    }
    plot_args = self.args_parse(plot_args, def_plot_args)
    self.do_plot(t, dt, data, S.COLORS_SYMPT, seeds, **plot_args)

plot_symptoms(self, seeds=None, **plot_args)

Plots the percentage of symptomatic and asymptomatic particles in time.

Important

This plot uses the do_plot method, see plot_args to see all available arguments.

Parameters:

Name Type Description Default
seeds list

List of seeds to plot, if None will plot all seeds available.

None
**plot_args kwargs

Arguments for the do_plot method (see plot_args).

{}
Source code in comorbuss/lab/analysis.py
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
def plot_symptoms(self, seeds=None, **plot_args):
    """Plots the percentage of symptomatic and asymptomatic particles in time.

    !!! Important
        This plot uses the do_plot method, see [plot_args](#plot_args) to see all available arguments.

    Args:
        seeds (list, optional): List of seeds to plot, if None will plot all seeds available.
        **plot_args (kwargs): Arguments for the do_plot method (see [plot_args](#plot_args)).
    """
    # Prepare Data
    data = self.get_data(["symptoms"], seeds)
    seeds = data["seeds"]
    symptoms = np.array(data["symptoms"])
    symptomatic_cumulative = np.sum(
        (symptoms > 0) & (symptoms != S.NO_INFEC), axis=2
    )
    asymptomatic_cumulative = np.sum(
        (symptoms < 0) & (symptoms != S.NO_INFEC), axis=2
    )
    data = {
        "symptomatic": 100
        * symptomatic_cumulative
        / np.maximum(1.0, symptomatic_cumulative + asymptomatic_cumulative),
        "asymptomatic": 100
        * asymptomatic_cumulative
        / np.maximum(1.0, symptomatic_cumulative + asymptomatic_cumulative),
    }
    Nsteps = self.parameters["Nsteps"]
    dt = self.parameters["dt"]
    t = dt * np.arange(Nsteps) / 24

    # Plot graphs
    def_plot_args = {
        "xlabel": "Days",
        "ylabel": "% Infected",
        "legend_args": {
            "labels": [
                "Prob(sympt.) = {:.3g} %".format(
                    (
                        100
                        * np.mean(symptomatic_cumulative[:, -1])
                        / (
                            np.mean(symptomatic_cumulative[:, -1])
                            + np.mean(asymptomatic_cumulative[:, -1])
                        )
                    )
                )
            ],
            "loc": "upper right",
        },
        "bands_legend_args": {"color": S.COLORS["red"]},
    }
    plot_args = self.args_parse(plot_args, def_plot_args)
    self.do_plot(
        t, dt, data, [S.COLORS["red"], S.COLORS["blue"]], seeds, **plot_args
    )

plot_time_between_hist(self, time_in=['time_infectious'], time_out=['time_recovered', 'time_dead'], bins=10, percentage=False, filename=None, size=(5, 4), title=None, seed=-1, close=True)

Plot a histogram of the duration between two times saved in the infection tree for all particles. Can only plot one seed.

Available times:

  • time_exposed
  • time_infectious
  • time_activated
  • time_recovered
  • time_deceased
  • time_vaccinated
  • time_immune
  • time_quarantined
  • time_released_quarantine

Parameters:

Name Type Description Default
time_in list

A list of times to be accepted as a start time, if a particle has more than one the first in the list will be used. Defaults to ["time_infectious"].

['time_infectious']
time_out list

A list of times to be accepted as a end time, if a particle has more than one the first in the list will be used. Defaults to ["time_recovered", "time_dead"].

['time_recovered', 'time_dead']
bins int

Number of bins in the histogram. Defaults to 10.

10
percentage bool

Y axis as a percentage. Defaults to False.

False
filename str

File name to save the graph, if not informed will only show the plot.

None
size tuple

Size for the plot. Defaults to (5, 4).

(5, 4)
title str

Title to be printed on the plot.

None
seed str

Seed to be plotted, if None will plot last loaded.

-1
close bool

If False doesn't show, save or close the plot so that the user can add more information to plot using the plt attribute from the class. Defaults to False.

True
Source code in comorbuss/lab/analysis.py
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
def plot_time_between_hist(
    self,
    time_in=["time_infectious"],
    time_out=["time_recovered", "time_dead"],
    bins=10,
    percentage=False,
    filename=None,
    size=(5, 4),
    title=None,
    seed=-1,
    close=True,
):
    """Plot a histogram of the duration between two times saved in the infection tree for all particles.
        Can only plot one seed.

    Available times:

    * `time_exposed`
    * `time_infectious`
    * `time_activated`
    * `time_recovered`
    * `time_deceased`
    * `time_vaccinated`
    * `time_immune`
    * `time_quarantined`
    * `time_released_quarantine`

    Args:
        time_in (list, optional): A list of times to be accepted as a start time, if a particle
            has more than one the first in the list will be used. Defaults to ["time_infectious"].
        time_out (list, optional): A list of times to be accepted as a end time, if a particle
            has more than one the first in the list will be used. Defaults to ["time_recovered", "time_dead"].
        bins (int, optional): Number of bins in the histogram. Defaults to 10.
        percentage (bool, optional): Y axis as a percentage. Defaults to False.
        filename (str, optional): File name to save the graph, if not informed will only show the plot.
        size (tuple, optional): Size for the plot. Defaults to (5, 4).
        title (str, optional): Title to be printed on the plot.
        seed (str, optional): Seed to be plotted, if None will plot last loaded.
        close (bool, optional): If False doesn't show, save or close the plot so that the user can add
            more information to plot using the plt attribute from the class. Defaults to False.
    """
    if type(seed) is list:
        if len(seed) != 1:
            print(
                "[WARNING] Can only plot time between histograms with single seed, plotting last seed loaded."
            )
    data_loaded = self.get_data(["inf_tree"], seed)
    inf_tree = data_loaded["inf_tree"][0]
    data = []
    time_in = [t.lower() for t in time_in]
    time_out = [t.lower() for t in time_out]
    for node in inf_tree.nodes:
        in_ok = False
        out_ok = False
        for time in time_in:
            for key in inf_tree.nodes[node].keys():
                if key.split("]")[-1] == time:
                    time_in_value = inf_tree.nodes[node][time]
                    in_ok = True
                    break
            if in_ok:
                break
        for time in time_out:
            for key in inf_tree.nodes[node].keys():
                if key.split("]")[-1] == time:
                    time_out_value = inf_tree.nodes[node][time]
                    out_ok = True
                    break
            if out_ok:
                break
        if in_ok and out_ok:
            data.append(time_out_value - time_in_value)

    self.start_plt(size=size, title=title)
    plt.hist(data, bins=bins)
    plt.xticks(rotation=45, horizontalalignment="right")
    if close:
        self.stop_plt(filename=filename, xlabel="Time", ylabel="Number")

plot_total_infections_hist(self, filename=None, title=None, seeds=None, size=(5, 4), close=True)

Plots a histogram of the total number of infections at the end of the simulation for all seeds.

Parameters:

Name Type Description Default
filename str

File name to save the graph, if not informed will only show the plot.

None
size tuple

Size for the plot. Defaults to (20, 20).

(5, 4)
seeds list

List of seeds to plot, if None will plot all seeds available.

None
title str

Title for the plot. Defaults to None.

None
close bool

If False doesn't show, save or close the plot so that the user can add more information to plot using the plt attribute from the class. Defaults to False.

True
Source code in comorbuss/lab/analysis.py
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
def plot_total_infections_hist(
    self, filename=None, title=None, seeds=None, size=(5, 4), close=True
):
    """Plots a histogram of the total number of infections at the end of the simulation for all seeds.

    Args:
        filename (str, optional): File name to save the graph, if not informed will only show the plot.
        size (tuple, optional): Size for the plot. Defaults to (20, 20).
        seeds (list, optional): List of seeds to plot, if None will plot all seeds available.
        title (str, optional): Title for the plot. Defaults to None.
        close (bool, optional): If False doesn't show, save or close the plot so that the user can add
            more information to plot using the plt attribute from the class. Defaults to False.
    """
    # Organize data
    data = self.get_data(["states"], seeds)
    if len(data["seeds"]) == 1:
        print(
            "[ERROR] Can only plot total infections histogram with more than one seed."
        )
        return None
    last_states = np.array(data["states"])[:, -1, :]  # [seed, step, particle]
    count_infected = np.sum((last_states != 0), axis=1)

    self.start_plt(size=size, title=title)
    self.plt.hist(count_infected)
    if close:
        self.stop_plt(
            filename=filename, xlabel="Number of infections", ylabel="Count"
        )