Skip to content

aux_classes.py

Auxiliary classes and functions for internal use.

RandomDistibution

Stores a random number generator and distribution parameters make and samples from it.

__init__(self, *args, *, distribution='uniform', lower_limit=None, upper_limit=None, **kwargs) special

Stores a random number generator and distribution parameters make and samples from it.

Parameters:

Name Type Description Default
*args

Arguments to be passed to the distribution on sample.

()
distribution str

Any distribution from numpy.random. Defaults to 'uniform'.

'uniform'
lower_limit float

Lower limit for samples. Samples below lower_limit will be replaced by it.

None
upper_limit float

Upper limit for samples. Samples above upper_limit will be replaced by it.

None
**kwargs

Keyword arguments to be passed to the distribution on sample.

{}
Source code in comorbuss/aux_classes.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
def __init__(
    self,
    *args,
    distribution="uniform",
    lower_limit=None,
    upper_limit=None,
    **kwargs
) -> None:
    """Stores a random number generator and distribution parameters make and samples from it.

    Args:
        *args: Arguments to be passed to the distribution on sample.
        distribution (str, optional): Any distribution from numpy.random. Defaults to 'uniform'.
        lower_limit (float): Lower limit for samples. Samples below lower_limit will be replaced by it.
        upper_limit (float): Upper limit for samples. Samples above upper_limit will be replaced by it.
        **kwargs: Keyword arguments to be passed to the distribution on sample.
    """
    self.dist = distribution
    self.args = args
    self.limits = (lower_limit, upper_limit)
    self.kwargs = kwargs

sample(self, rng, size=1)

Sample values from distribution.

Parameters:

Name Type Description Default
size int

Size to be sampled. Defaults to 1.

1

Returns:

Type Description
float

float: Samples.

Source code in comorbuss/aux_classes.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
def sample(self, rng, size: int = 1) -> float:
    """Sample values from distribution.

    Args:
        size (int, optional): Size to be sampled. Defaults to 1.

    Returns:
        float: Samples.
    """
    dist = getattr(rng, self.dist)
    samples = dist(size=size, *self.args, **self.kwargs)

    # Apply limits
    if self.limits[0] != None:
        samples[samples < self.limits[0]] = self.limits[0]
    if self.limits[1] != None:
        samples[samples > self.limits[1]] = self.limits[1]
    # Return values
    if size == 1:
        return samples[0]
    else:
        return samples

circularlist

__getitem__(self, key) special

Get element by index, relative to the current index

Source code in comorbuss/aux_classes.py
278
279
280
281
282
283
def __getitem__(self, key):
    """Get element by index, relative to the current index"""
    if len(self._data) == self.size:
        return self._data[(key + self.index) % self.size]
    else:
        return self._data[key]

__init__(self, size, data=[]) special

Initialization

Source code in comorbuss/aux_classes.py
264
265
266
267
268
def __init__(self, size, data=[]):
    """Initialization"""
    self.index = 0
    self.size = size
    self._data = list(data)[-size:]

__repr__(self) special

Return string representation

Source code in comorbuss/aux_classes.py
285
286
287
def __repr__(self):
    """Return string representation"""
    return self._data.__repr__() + " (" + str(len(self._data)) + " items)"

append(self, value)

Append an element

Source code in comorbuss/aux_classes.py
270
271
272
273
274
275
276
def append(self, value):
    """Append an element"""
    if len(self._data) == self.size:
        self._data[self.index] = value
    else:
        self._data.append(value)
    self.index = (self.index + 1) % self.size

clock

Provides a clock for the simulation.

Attributes:

Name Type Description
dt float

Time step in hours.

time float

Current time in hours since the start of the simulation.

step int

Number of steps since the start of the simulation.

tod float

Time of the day in the simulation.

today int

Number of days since the start of the simulation.

days floay

Time since the start of the simulation in days.

dow int

Current day of the week, varies from 0 to 6, where 0 is sunday and 6 saturday.

day_of_the_week str

Current day of the week in text.

at_time(self, time)

Returns True at or imediatly after the end time informed.

Parameters:

Name Type Description Default
end float

Time of the day to test.

required

Returns:

Type Description
bool

Result of the test.

Source code in comorbuss/aux_classes.py
378
379
380
381
382
383
384
385
386
387
def at_time(self, time):
    """Returns True at or imediatly after the end time informed.

    Args:
        end (float): Time of the day to test.

    Returns:
        bool: Result of the test.
    """
    return ((self.time - self.dt) < time) and (self.time >= time)

at_time_of_day(self, time)

Returns True at or imediatly after the time of the day informed.

Parameters:

Name Type Description Default
end float

Time of the day to test.

required

Returns:

Type Description
bool

Result of the test.

Source code in comorbuss/aux_classes.py
364
365
366
367
368
369
370
371
372
373
def at_time_of_day(self, time):
    """Returns True at or imediatly after the time of the day informed.

    Args:
        end (float): Time of the day to test.

    Returns:
        bool: Result of the test.
    """
    return ((self.tod - self.dt) < time) and (self.tod >= time)

between_hours(self, start, end)

Returns True if current time of the day is inside interval [start, end).

Parameters:

Name Type Description Default
start float

Start of the interval.

required
end float

End of the interval.

required

Returns:

Type Description
bool

Result of the test.

Source code in comorbuss/aux_classes.py
345
346
347
348
349
350
351
352
353
354
355
356
357
def between_hours(self, start, end):
    """Returns True if current time of the day is inside interval [start, end).

    Args:
        start (float): Start of the interval.
        end (float): End of the interval.

    Returns:
        bool: Result of the test.
    """
    return (self.tod >= start and self.tod < end and start < end) or (
        (self.tod >= start or self.tod < end) and start > end
    )

tick(self)

Advances internal clock by one time step dt.

Source code in comorbuss/aux_classes.py
333
334
335
336
337
338
339
340
341
342
343
def tick(self):
    """Advances internal clock by one time step dt."""
    self.time += self.dt
    self.step += 1
    self.tod = self.time % 24
    self.step_of_the_day = self.time_to_steps(self.tod)
    self.today = int(self.time / 24)
    self.days = self.time / 24
    self.dow = (self.today + self.first_dow) % 7
    self.week = int((self.today + self.first_dow) / 7)
    self.day_of_the_week = DAYS_OF_THE_WEEK[self.dow]

coefficient_container

__getattribute__(self, name) special

Gets an attribute, if it has coefficients applies them.

Parameters:

Name Type Description Default
name str

Attribute name.

required

Returns:

Type Description
Any

Any: Attribute value with coefficients applied.

Source code in comorbuss/aux_classes.py
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
def __getattribute__(self, name: str) -> Any:
    """Gets an attribute, if it has coefficients applies them.

    Args:
        name (str): Attribute name.

    Returns:
        Any: Attribute value with coefficients applied.
    """
    try:
        return super(coefficient_container, self).__getattribute__(
            name + CRRCT_MRKR
        )
    except AttributeError:
        return super(coefficient_container, self).__getattribute__(name)

add_coefficient(self, name, value, identifier)

Adds an attribute coefficient.

Parameters:

Name Type Description Default
name str

Attribute name.

required
value ndarray

Coefficient name (needs to have the same shape as the attribute).

required
identifier str

String identifier for the coefficient.

required

Exceptions:

Type Description
ValueError

Raises if type of attribute or coefficient is not np.nd.array, or if shapes do not match.

Source code in comorbuss/aux_classes.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
def add_coefficient(self, name: str, value: np.ndarray, identifier: str) -> None:
    """Adds an attribute coefficient.

    Args:
        name (str): Attribute name.
        value (np.ndarray): Coefficient name (needs to have the same shape as the attribute).
        identifier (str): String identifier for the coefficient.

    Raises:
        ValueError: Raises if type of attribute or coefficient is not np.nd.array, or
            if shapes do not match.
    """
    # Gets attribute to check coefficient shape and types
    attribute = getattr(self, name)
    # Check if attribute
    if type(attribute) is not np.ndarray:
        raise RuntimeError(
            "Tried to set an coefficient for {}.{} attribute that is not an np.ndarray.".format(
                self.__repr__(), name
            )
        )
    if type(value) is not np.ndarray:
        raise RuntimeError(
            "Tried to set an coefficient for {}.{} attribute, but coefficient not an np.ndarray.".format(
                self.__repr__(), name
            )
        )
    # Check shape
    if attribute.shape != value.shape:
        raise ValueError(
            "Tried to set a coefficient for {}.{} with shape {}, but coefficient shape is {}.".format(
                self.__repr__(), name, attribute.shape, value.shape
            )
        )

    # Stores coefficient
    if hasattr(self, name + COEFF_MRKR):
        coeff_dict = getattr(self, name + COEFF_MRKR)
    else:
        coeff_dict = {}
    coeff_dict[identifier] = value
    setattr(self, name + COEFF_MRKR, coeff_dict)
    self._update_values(name)

del_coefficient(self, name, identifier)

Deletes an attribute coefficient if it exists.

Parameters:

Name Type Description Default
name str

Attribute name.

required
identifier str

String identifier for the coefficient.

required
Source code in comorbuss/aux_classes.py
142
143
144
145
146
147
148
149
150
151
152
def del_coefficient(self, name: str, identifier: str) -> None:
    """Deletes an attribute coefficient if it exists.

    Args:
        name (str): Attribute name.
        identifier (str): String identifier for the coefficient.
    """
    if hasattr(self, name + COEFF_MRKR):
        coeff_dict = getattr(self, name + COEFF_MRKR)
        del coeff_dict[identifier]
        setattr(self, name + COEFF_MRKR, coeff_dict)

get_coefficient(self, name, identifier)

Returns a coefficient.

Parameters:

Name Type Description Default
name str

Attribute name.

required
identifier str

String identifier for the coefficient.

required

Returns:

Type Description
ndarray

np.ndarray: Coefficient array.

Source code in comorbuss/aux_classes.py
154
155
156
157
158
159
160
161
162
163
164
def get_coefficient(self, name: str, identifier: str) -> np.ndarray:
    """Returns a coefficient.

    Args:
        name (str): Attribute name.
        identifier (str): String identifier for the coefficient.

    Returns:
        np.ndarray: Coefficient array.
    """
    return getattr(self, name + COEFF_MRKR)[identifier]

set_coefficient(self, name, value, identifier)

Sets a coefficient.

Parameters:

Name Type Description Default
name str

Attribute name.

required
value ndarray

Coefficient name (needs to have the same shape as the attribute).

required
identifier str

String identifier for the coefficient.

required
Source code in comorbuss/aux_classes.py
166
167
168
169
170
171
172
173
174
def set_coefficient(self, name: str, value: np.ndarray, identifier: str) -> None:
    """Sets a coefficient.

    Args:
        name (str): Attribute name.
        value (np.ndarray): Coefficient name (needs to have the same shape as the attribute).
        identifier (str): String identifier for the coefficient.
    """
    return self.add_coefficient(name, value, identifier)

empty_module

__init__(self, parameters, comm, name='empty_module') special

Initialization method for a COMORBUSS module.

parameters and comm will be passed to your module at initialization.

Parameters:

Name Type Description Default
parameters dict

Parameters for this module.

required
comm comorbuss.community

Community object.

required
name str

[description]. Defaults to "empty_module".

'empty_module'
Source code in comorbuss/aux_classes.py
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
def __init__(self, parameters, comm, name="empty_module"):
    """Initialization method for a COMORBUSS module.

    parameters and comm will be passed to your module at initialization.

    Args:
        parameters (dict): Parameters for this module.
        comm (comorbuss.community): Community object.
        name (str, optional): [description]. Defaults to "empty_module".
    """
    self.name = name

    self.comm = comm
    self.pop = comm.pop
    self.clk = comm.clk
    self.event_log = lambda msg, type: comm.event_log(
        "[{}] {}".format(name, msg), type
    )
    self.rng = np.random.default_rng(comm.random_seed)
    self.parameters = parameters

log_results(self)

Logs results related to this module.

Source code in comorbuss/aux_classes.py
210
211
212
def log_results(self):
    """Logs results related to this module."""
    pass

run_after_init(self)

Method to be run at the end of the community's initialization.

Source code in comorbuss/aux_classes.py
206
207
208
def run_after_init(self):
    """Method to be run at the end of the community's initialization."""
    pass