cv19gm.utils package
Submodules
cv19gm.utils.cv19errors module
- cv19gm.utils.cv19errors.LCE(sim, data, t_data=None)[source]
Local Cummulative Error To do :param sim: Simulation data :type sim: list :param data: Data to compare :type data: list :param t_data: _description_. Defaults to None. :type t_data: list, optional
- Returns:
accumulative error
- Return type:
list
- cv19gm.utils.cv19errors.LRCE(sim, data, t_data=None)[source]
Local Relative Cummulative Error To do :param sim: Simulation data :type sim: list :param data: Data to compare :type data: list :param t_data: _description_. Defaults to None. :type t_data: list, optional
- Returns:
accumulative error
- Return type:
list
cv19gm.utils.cv19files module
cv19gm.utils.cv19functions module
- cv19gm.utils.cv19functions.build(input)[source]
Build a function for using it as a dynamical paraeter.
- Parameters:
input (str,dic,func,tuple,list,bool) –
- Returns:
cv19gm function for dynamic parameters
- Return type:
function(t)
- cv19gm.utils.cv19functions.build_add(*input)[source]
Creates a function Build a functions and adds t # Construir funcion que sume multiples funciones
- cv19gm.utils.cv19functions.build_metapopulation(input)[source]
Function builder for metapopulation models.
- Parameters:
input – Arg to be transformed into a function
- Returns:
cv19gm function for dynamic parameters
- Return type:
function
- cv19gm.utils.cv19functions.data_function(data, future)[source]
Creates a function that returns the data during its length
- Parameters:
data (list| np.array|pd.Series|pd.DataFrame) – Data
future ([type]) – [description]
- cv19gm.utils.cv19functions.events(values, days, default=0, *functions)[source]
Event creator function. Create a time dependent function that returns the values (or functions) given in the values vector for the intervals specified in the days vector.
- Parameters:
values (list) – list with the values for the different intervals
days (list) – list of lists of len == 2 with the values for the function on that v.
default (float, optional) – value that the function takes in undefined intervals. Defaults to 0
functions – extra functions to add with no interval definition
- Returns:
function created
- Return type:
out (function)
- cv19gm.utils.cv19functions.events_append(values, days, new_val, new_days=None, default=0)[source]
_summary_
- Parameters:
values (_type_) – _description_
days (_type_) – _description_
new_val (_type_) – _description_
new_days (_type_, optional) – _description_. Defaults to None.
default (int, optional) – _description_. Defaults to 0.
- Returns:
_description_
- Return type:
_type_
- cv19gm.utils.cv19functions.func_add(*functions)[source]
Creates the function that results adding the functions received. Receives a list where each element is a function that receives 1 argument
- cv19gm.utils.cv19functions.interpolate_data(data)[source]
Interpolates the data in order to have a daily array of data
- Parameters:
data ([type]) – [description]
- Returns:
[description]
- Return type:
[type]
- cv19gm.utils.cv19functions.linear_transition(t_init, t_end, initvalue=0, endvalue=1)[source]
linearTransition Creates a function which performs a linear transition from initvalue to endvalue between t_init and t_end. :param t_init: Transition beginningt_init :type t_init: int :param t_end: Transition end :type t_end: int :param initvalue: Initial value. Defaults to 0. :type initvalue: int, optional :param endvalue: End value. Defaults to 1. :type endvalue: int, optional
- Returns:
function that performs the linear transition
- Return type:
function
- cv19gm.utils.cv19functions.piecewise(values, limits=[-inf])[source]
Piecewise creator function. Create a smooth time dependent function that returns the values (or functions) given in the values vector for the intervals specified through the limits vector. In order to make this function differentiable, we use a sigmoid to have a smooth change between values. This produces that the value at the limit is equal to the mean between both sides.
- f(x) = {v0 for t in ]-inf,limits[0][
v1 for t in ]limits[0],limits[1][ … vn for t in ]limits[n-1], inf[
} f(limit[0]) = (v0+v1)/2
- Parameters:
values (list) – list with the values for the different intervals
limits (list) – list of days where the function takes the next value. len(limits)=len(values)-1
- Returns:
function created
- Return type:
out (function)
- cv19gm.utils.cv19functions.polyfit(values, time=None, degree=4, endvalue_index=-5)[source]
polyfit: Function data fits real data with a polynom of a given degree, and then projects the future values with it. values: values to fit time: time array from data to fit. If no time array given, daily data is assumed degree: polynom degree
- cv19gm.utils.cv19functions.quadratic_transition(t_init, t_end, initvalue=0, endvalue=1, concavity=0)[source]
quadraticTransition Creates a function which performs a quadratic transition from initvalue to endvalue between t_init and t_end.
- Parameters:
t_init (int) – Transition beginning
t_end (int) – Transition end
initvalue (int, optional) – Initial value. Defaults to 0.
endvalue (int, optional) – End value. Defaults to 1.
concavity (int, optional) – Function’s concavity. 0: convex, 1: concave. Defaults to convex.
- Returns:
function that performs the quadratic transition
- Return type:
function
- cv19gm.utils.cv19functions.saturation(upperlimit)[source]
Function that builds binary functions which indicates when the sum of the arguments are bigger than the saturation function.
- Parameters:
upperlimit (function or cv19function builder arg) – Upper limit function
- Returns:
- binary function with time multiple arguments that returns 1 when the arguments addition function
- Args:
t (float): time value *args: multiple arguments which are added and then compared with the saturation value at time t
- Returns:
- int:
0 when the functions given are smaller than the saturation function 1 when they are bigger or equal
- Return type:
saturationfunction (function)
- cv19gm.utils.cv19functions.sawtooth(min_val=0, max_val=1, period=14, t_init=0, t_end=1000, default=0, initphase=0, width=1)[source]
- cv19gm.utils.cv19functions.sigmoidal_transition(t_init, t_end, initvalue=0, endvalue=1, gw=8)[source]
Sigmoidal Transition Creates a function which performs a sigmoidal transition from initvalue to endvalue between t_init and t_end.
- Parameters:
t_init (int) – Transition beginning
t_end (int) – Transition end
initvalue (int, optional) – Initial value. Defaults to 0.
endvalue (int, optional) – End value. Defaults to 1.
gw (float, optional) – Gain weight. Calibrates the “strength” of the sigmoid change
- Returns:
function that performs the sigmoidal transition
- Return type:
function
- cv19gm.utils.cv19functions.sine(min_val=0, max_val=1, period=14, t_init=0, t_end=1000, default=0, initphase=0)[source]
- cv19gm.utils.cv19functions.square(min_val=0, max_val=1, period=14, t_init=0, t_end=1000, default=0, initphase=0, duty=0.5)[source]
- cv19gm.utils.cv19functions.transition(t_init, t_end, ftype='linear', initvalue=0, endvalue=1, concavity=0, gw=8)[source]
Transition
- Parameters:
t_init (int) – Transition beginning
t_end (int) – Transition end
ftype (str or int, optional) – Transition function type. Defaults to ‘linear’. 0 or “linear”, 1 or “quadratic”, 2 or “sigmoidal”
initvalue (int, optional) – _description_. Defaults to 0.
endvalue (int, optional) – _description_. Defaults to 1.
concavity (int, optional) – Quadratic Function’s concavity. 0: convex, 1: concave. Defaults to convex.
gw (float, optional) – Gain weight. Calibrates the “strength” of the sigmoid change. Defaults to 8.
cv19gm.utils.cv19mobility module
- cv19gm.utils.cv19mobility.create_dynamic_mobility(mobility_model, dynamic_pattern, populations, distances=None, **kwargs)[source]
Create a dynamic mobility matrix function based on the specified mobility model and dynamic pattern.
- Parameters:
mobility_model (str) – Mobility model to be used (‘gravity’, ‘radiation’, or ‘random’)._
dynamic_pattern (str) – Dynamic pattern to be used (‘sinusoidal’, ‘rush_hour’, or ‘piecewise_linear’).
populations (np.array) – Array of populations for each region.
distances (np.array, optional) – Matrix of distances between regions. Defaults to None, which generates a random distance matrix.
**kwargs (dict) – Additional parameters for the specific mobility models and dynamic patterns.
- Raises:
ValueError – Error when an unsupported dynamic pattern is specified.
- Returns:
Dynamic mobility matrix function.
- Return type:
function
- cv19gm.utils.cv19mobility.create_mobility_matrix(populations, distances=None, model='gravity', **kwargs)[source]
Creates mobility matrix based on the specified model and parameters.
- Parameters:
populations (np.array) – Array of populations for each region.
distances (np.array, optional) – Matrix of distances between regions. Defaults to None.
model (str, optional) – Mobility model to be used (‘gravity’, ‘radiation’, or ‘random’). Defaults to ‘gravity’.
**kwargs (dict) – Additional parameters for the specific mobility models.
- Raises:
ValueError – Error when an unsupported model is specified.
- Returns:
Static mobility matrix.
- Return type:
np.array
- cv19gm.utils.cv19mobility.create_random_distances_matrix(size, min_distance=50, max_distance=500, seed=None)[source]
Create a random symmetric distance matrix.
- Parameters:
size (int) – The number of nodes (regions) in the distance matrix.
max_distance (float) – The maximum distance between any two nodes (regions).
seed (int, optional) – Seed for the random number generator.
- Returns:
A symmetric distance matrix.
- Return type:
np.array
- cv19gm.utils.cv19mobility.gravity_model(populations, distances, alpha=1, beta=1, fraction=0.02, **kwargs)[source]
Calculate the gravity model mobility matrix. The gravity model, inspired by Newton’s law of gravitation, is a widely used spatial interaction model in various fields, such as transportation, human migration, and trade. The model assumes that the interaction between two regions (e.g., the number of people moving between them) is directly proportional to the product of their populations (or other attributes, like economic size) and inversely proportional to some power of the distance between them.
- Parameters:
populations (np.array) – Array of populations for each region.
distances (np.array) – Matrix of distances between regions.
alpha (int, optional) – Parameter to control the effect of population sizes. Defaults to 1.
beta (int, optional) – Parameter to control the effect of distances.. Defaults to 1.
fraction (float, optional) – Fraction of the population that travels per day. Defaults to 0.5.
- Returns:
Mobility matrix based on the gravity model.
- Return type:
np.array
- cv19gm.utils.cv19mobility.piecewise_linear_mobility_pattern(mobility_matrix, intervals, slopes, **kwargs)[source]
Create a time-varying mobility matrix function using a piecewise linear pattern.
- Parameters:
mobility_matrix (np.array) – Static mobility matrix
intervals (list of tuples) – List of time intervals represented as (start, end) tuples.
slopes (list of float) – List of slopes for each time interval.
- Returns:
Time-varying mobility matrix function.
- Return type:
function
- cv19gm.utils.cv19mobility.radiation_model(populations, distances, fraction=0.02, **kwargs)[source]
Calculate the radiation model mobility matrix.
- Parameters:
populations (np.array) – Array of populations for each region.
distances (np.array) – Matrix of distances between regions.
fraction (float, optional) – Fraction of the population that travels per day. Defaults to 0.5.
- Returns:
Mobility matrix based on the radiation model.
- Return type:
np.array
- cv19gm.utils.cv19mobility.random_mobility_model(population, fraction=0.02, seed=None, **kwargs)[source]
Generate a random flux matrix that moves the specified fraction of the population. This method uses the dirichlet distribution in order to distribute the population maintaining the total.
- Parameters:
population (array) – array with the population of each town that makes part of this meta-population system.
fraction (float, array, optional) – Population fraction that travels per day. This can also be an array that specifies a different fraction per population. Defaults to 0.5.
- Returns:
Flux matrix with 0 diagonals
- Return type:
np.array
- cv19gm.utils.cv19mobility.rush_hour_mobility_pattern(mobility_matrix, peak_amplitude=0.5, off_peak_amplitude=-0.5, peak_start=0.2916666666666667, peak_end=0.375, evening_start=0.7083333333333334, evening_end=0.7916666666666666, period=1, **kwargs)[source]
Create a time-varying mobility matrix function using a rush hour pattern.
- Parameters:
mobility_matrix (np.array) – Static mobility matrix.
peak_amplitude (float, optional) – Amplitude during peak hours. Defaults to 0.5.
off_peak_amplitude (float, optional) – Amplitude during off-peak hours. Defaults to -0.5.
peak_start (float, optional) – Start time of morning peak hours. Defaults to 7/24.
peak_end (float, optional) – End time of morning peak hours. Defaults to 9/24.
evening_start (float, optional) – Start time of evening peak hours. Defaults to 17/24.
evening_end (float, optional) – End time of evening peak hours. Defaults to 19/24.
- Returns:
Time-varying mobility matrix function.
- Return type:
function
- cv19gm.utils.cv19mobility.sinusoidal_mobility_pattern(mobility_matrix, amplitude=0.5, phase_shift=0, **kwargs)[source]
Create a time-varying mobility matrix function using a daily sinusoidal pattern. :param mobility_matrix: Static mobility matrix. :type mobility_matrix: np.array :param amplitude: Amplitude of the sinusoidal pattern. Defaults to 0.5. :type amplitude: float, optional :param period: Period of the sinusoidal pattern. Defaults to 1 day. :type period: int, optional :param phase_shift: Phase shift of the sinusoidal pattern. Defaults to 0. :type phase_shift: int, optional
- Returns:
Time-varying mobility matrix function.
- Return type:
function
- cv19gm.utils.cv19mobility.symmetric_mobility_pattern(mobility_matrix, transposed=False, **kwargs)[source]
Create a time-varying mobility matrix function using using a daily symmetric pattern, in order to conserve the population throughout the day, avoiding long-term mass migrations
- Parameters:
mobility_matrix (np.array) – Base flux matrix
transposed (bool, optional) – Returns the transposed matrix
- Returns:
Time symmetric flux function
- Return type:
function
cv19gm.utils.cv19paramfit module
- class cv19gm.utils.cv19paramfit.BETAMU_FIT(cfg, bounds, I_d_data, t_data=None, error='ITWE', rho=1, **kwargs)[source]
Bases:
objectOptimizador de beta con Inverse Time Weighted Error
Se deben encontrar las condiciones iniciales para todas las variables
Elegir qué variable se utilizará en el fitness. Voy a partir con I_d
- class cv19gm.utils.cv19paramfit.BETA_FIT(I_d, t, cfg, bounds, error='RMSE', alpha=1, **kwargs)[source]
Bases:
objectOptimizador de beta con Inverse Time Weighted Error
Se deben encontrar las condiciones iniciales para todas las variables
Elegir qué variable se utilizará en el fitness. Voy a partir con I_d
- class cv19gm.utils.cv19paramfit.BETA_PIECEWISE_FIT(cfg, bounds, I_d_data, t_data=None, beta_values=[], beta_days=[-inf], error='RMSE', **kwargs)[source]
Bases:
object_summary_ # beta_days includes the last transition date, the objetive of this method is to find the best value for this transition.
- class cv19gm.utils.cv19paramfit.CV19PARAMFIT(cfg, method='interval_fit', I_d_data=None, t_data=None, dates_data=None, tstate=None, initdate=None, cv19gmdata=None, verbose=False, nintervals=3, gen=200, vartofit='I_d', **kwargs)[source]
Bases:
object
- class cv19gm.utils.cv19paramfit.INTERVAL_FIT(I_d_data, t_data, bounds, cfg, error='RMSE', nintervals=10, **kwargs)[source]
Bases:
objectData Fit Developed by A. Bernardin, modified by S. Ropert
- class cv19gm.utils.cv19paramfit.SEQUENTIAL_FIT(cfg, I_d_data=None, t_data=None, dates_data=None, tstate=None, initdate=None, cv19gmdata=None, global_errortol=100, local_errortol=100, global_errfunct=<function RMSE>, local_errfunct=<function LAE>, intervalsize=10, maxintervals=5, bounds_beta=[0, 1], bounds_mu=[0, 4], inputdata=None, paramtol=0.05, **kwargs)[source]
Bases:
objectSequential fit optimization method 1. We aply betamu_fit for fiting the initial parameters using a truncated part of the data 2. We calculate a global error function and check if we are under the error tolerance. If not we continue with the following points 3. Using tendency_change we look for the tendency change day. 4. We optimize with beta_fit from the day found in (2). 5. We iterate points 2, 3 and 4 until we reach the end of the data or we reduce the error below the tolerance
- cv19gm.utils.cv19paramfit.beta_fit(bounds, cfg, I_d_data, t_data, beta_values=[], beta_days=[-inf], actualidx=-1, debug=True, global_errfunct=<function RMSE>, **kwargs)[source]