Parametric studies on the REPEAT VISION platform#

Added in version 1.0.0.

The repeat package module is designed to prepare values of global variables of the REPEAT VISION model for the purpose of performing parametric studies.

Using the parametric_study module of the repeat package allows parametric studies to be performed, reducing the labor intensity of preparing Python programs, since the engineer does not need to use nested loops when iterating over values for any number of global variables.

This module contains the main functions for preparing variable values:

  1. get_cartesian_product - Function for preparing a set of values of global variables using the Cartesian product method in order to obtain the results of calculating the REPEAT VISION model on a grid of values of global variables;

  2. get_latin_hypercube - Function for preparing a sparse set of values of global variables using the Latin hypercube method for computationally expensive cases of parametric studies.

repeat.parametric_study.get_cartesian_product(model: ExplorationModel, variable_values: dict[str, pandas.Series | ndarray]) → pandas.DataFrame#

The function returns the Cartesian product for a set of values of global variables for the purpose of performing parametric studies of the REPEAT VISION model.

For example, for the case of two variables diameter = np.array([0.05, 0.1]) and pressure = np.array([1e4, 2e4]) the function will return a pandas DataFrame table of the following form.

0

0.05

10000.0

1

0.10

10000.0

2

0.05

20000.0

3

0.10

20000.0

The algorithm generates a set of calculation cases with a quantity equal to the product of the lengths of the value vectors of all global variables specified in the variable_values argument. For the example given above, the length of the value vector diameter = 2 and the length of the vector pressure = 2. Accordingly, the algorithm will prepare a set including 4 calculation cases to perform 4 parametric studies of the REPEAT VISION model.

Parameters:
modelrepeat.repeat_model.ExplorationModel.

Экземпляр класса repeat.repeat_model.ExplorationModel.

variable_valuesdict[str, pd.Series | np.ndarray]

A dictionary with sets of global variable values. The dictionary keys must be string values of global variable names. Each dictionary key must have a corresponding pd.Series or np.ndarray value containing the set of raw data for the corresponding global variable name. For example, variable_values = {"pressure" : np.linspace(1e4, 1e6, num = 4)}

Returns:
design_casespd.DataFrame

A table of global variable values, in which the columns correspond to the names of the global variables and the number of rows corresponds to the number of parametric studies that will need to be performed later.

Examples

>>> import pandas as pd
>>> import numpy as np
>>> import repeat as rp 
>>> import repeat.parametric_study as ps
>>>
>>> user = rp.User(token = 'уникальный токен из кабинета пользователя REPEAT VISION')
>>> app = rp.Application(user)
>>> t_interval = rp.TimeInterval(start = 900, end = 1000)
>>> project = "21425d1a-70f9-4bke-8140-81bd312bd91b"
>>> # Создаётся набор глобальных переменных с множествами значений,
>>> # по которым необходимо будет выполнить параметрическое исследование
>>> # на декартовом произведении значений параметров
>>> variable_values = dict(
>>>     # Требуется выполнить параметрическое исследование при изменении
>>>     # параметра hole_area модели REPEAT VISION
>>>     hole_area = np.linspace(1e-7, 0.031415, num = 2),
>>>     # В примере параметрического исследования не требуется учитывать 
>>>     # параметр pipe_diameter
>>>     pipe_diameter = np.array([0.2]),
>>>     pressure = np.linspace(1e4, 1e6, num = 4),
>>>  )
>>> model = app.get_exploration_model(project, t_interval)
>>> # Создаётся таблица с множеством значений глобальных переменных 
>>> input_data = ps.get_cartesian_product(
>>>     model, 
>>>     variable_values
>>>  )
>>> # Создаётся таблица для сохранения исходных данных 
>>> # и результатов расчёта 
>>> design_cases = input_data.copy(deep = True)
>>> design_cases['flowrate'] = pd.NA 
>>> # Цикл расчётов для параметрических исследований
>>> for i, variables in input_data.iterrows():
>>>     with model as md:
>>>         md.run(variables)
>>>         design_cases.loc[i, 'flowrate'] = md.get_results('flowrate').iloc[-1]
>>> 
>>> axis = design_cases.plot(x = 'pressure', y = 'flowrate')
repeat.parametric_study.get_latin_hypercube(model: ExplorationModel, variable_bounds: dict[str, list | float], sample_size: int, seed: int = None, optimization: str = None, strength: int = 1) → pandas.DataFrame#

The function returns a sparse set of global variable values using the Latin hypercube method for the purpose of performing parametric explorations of the REPEAT VISION model.

The Latin hypercube method is used in the following cases:

  1. The model requires a significant amount of time to perform each calculation with limited overall time to perform the research;

  2. High dimensionality of the parametric research problem, containing a large number of variable variables, which leads to significant time costs for performing parametric research.

Parameters:
modelrepeat.repeat_model.ExplorationModel

Экземпляр класса repeat.repeat_model.ExplorationModel.

variable_boundsdict[str, list | float]

A dictionary with sets of upper and lower bounds for the values of global variables. The dictionary keys must be string values of the names of the global variables. Each dictionary key must have a list containing the lower and upper bound values for the corresponding global variable name. If the value of a global variable in the framework of parametric studies does not need to be taken into account (its value must be constant), then the dictionary key must correspond to one real value. For example, variable_bounds = {"pressure" : [1e4, 1e6], "diameter" : 0.1}

sample_sizeint

The size of the set of global variable values, equal to the number of parametric studies that will need to be performed later.

seedint, optional

A positive integer value to ensure repeatability of the random set of global variable values. The default value is None.

optimizationstr, optional

Additional optimization of global variable values to improve the uniformity of filling the variable value space. The default value is None. The argument can take the following values:

  • "random-cd" Randomly change the values of variables when other variables have close values;

  • "lloyd" Changes the values of variables using the modified Lloyd-Max algorithm.

strengthint, optional

The way to fill the value space of global variables. An integer that takes the value 1 or 2. The default value is 1.

  • In the case of strength = 1, the function fills the value space so that there are no repetitions of the values of global variables in the sets of calculated cases.

  • In the case of strength = 2, the function ensures uniformity of the density of the variable value space. The following restrictions are imposed on the sample_size argument when strength = 2: sample_size must be a square of a prime number, sample_size = p**2, where p is a prime number [1, 2, 3, 4]. Then sample_size = 1, 4, 9, 16, etc., while the number of variable global variables (containing the upper and lower values) in variable_bounds must be <= p + 1.

Returns:
design_casespd.DataFrame

A table of global variable values, in which the columns correspond to the names of the global variables, and the number of rows equal to sample_size corresponds to the number of parametric studies that will need to be performed later.

Notes

function uses the LatinHypercube class of the SciPy package to prepare a sparse set of global variable values.

Examples

>>> import pandas as pd
>>> import numpy as np
>>> import repeat as rp 
>>> import repeat.parametric_study as ps
>>>
>>> user = rp.User(token = 'уникальный токен из кабинета пользователя REPEAT VISION')
>>> app = rp.Application(user)
>>> t_interval = rp.TimeInterval(start = 900, end = 1000)
>>> project = "21425d1a-70f9-4bke-8140-81bd312bd91b"
>>> # Создаётся набор глобальных переменных с нижними и верхними значениями,
>>> # по которым необходимо будет выполнить параметрическое исследование
>>> # на пространстве значений переменных, полученного по методу 
>>> # латинского гиперкуба
>>> variable_values = dict(
>>>     # Требуется выполнить параметрическое исследование при изменении
>>>     # параметра hole_area модели REPEAT VISION
>>>     hole_area = [1e-7, 0.031415],
>>>     # В примере параметрического исследования не требуется учитывать 
>>>     # параметр pipe_diameter
>>>     pipe_diameter = 0.2,
>>>     pressure = [1e4, 1e6],
>>>  )
>>> model = app.get_exploration_model(project, t_interval)
>>> # Создаётся пространство значений переменных по методу
>>> # латинского гиперкуба
>>> input_data = ps.get_latin_hypercube(
>>>     model, 
>>>     variable_values,
>>>     seed = 5, # Обеспечивается повторяемость случайного набора значений
>>>     sample_size = 9, # Требуется 9 расчётных случаев
>>>     # Обеспечивается равномерность заполнения пространства значений 
>>>     strength = 2,
>>>     optimization = "random-cd"
>>>  )
>>> # Создаётся таблица для сохранения исходных данных 
>>> # и результатов расчёта 
>>> design_cases = input_data.copy(deep = True)
>>> design_cases['flowrate'] = pd.NA 
>>> # Цикл расчётов для параметрических исследований
>>> for i, variables in input_data.iterrows():
>>>     with model as md:
>>>         md.run(variables)
>>>         design_cases.loc[i, 'flowrate'] = md.get_results('flowrate').iloc[-1]
>>> 
>>> axis = design_cases.plot(x = 'pressure', y = 'flowrate')