Skip to content

Tools#

The tools module provides utility functions and statistics for the CHEERSafe package.

Class Diagram#

classDiagram
    class Utils {
        +from_json()
        +to_json()
        +filter_column_values_df()
    }

    class Sampling {
        +generate_lhs_samples_norm()
        +generate_lhs_samples_general()
    }

    class Covariance {
        +create_cov_matrix()
    }

Statistics#

stats #

Classes:

Name Description
Covariance

This class provides methods for creating covariance matrices.

Sampling

This class provides methods for generating Latin Hypercube Samples.

Covariance #

This class provides methods for creating covariance matrices.

The covariance matrix is computed based on the specified number of components, their mean temperatures, coefficient of variation (CV), and the inter- and intra-correlation values.

Methods:

Name Description
create_cov_matrix

Computes the covariance matrix for a set of components based on their temperature characteristics and correlation parameters.

create_cov_matrix staticmethod #

create_cov_matrix(
    num_component,
    temp_mean,
    temp_cv,
    inter_correlation=0.2,
    intra_correlation=0.4,
) -> ndarray

Computes the covariance matrix for a set of components.

This method calculates a covariance matrix based on the number of components, their mean values, and coefficient of variation (CV). It considers both inter-component and intra-component correlations.

Parameters:

Name Type Description Default
num_component list[int]

Number of elements in each component.

required
temp_mean ndarray

Mean values for each element.

required
temp_cv ndarray

Coefficient of variation for each element.

required
inter_correlation float

Correlation coefficient between elements of different components. Defaults to 0.2.

0.2
intra_correlation float

Correlation coefficient between elements of the same component. Defaults to 0.4.

0.4

Returns:

Type Description
ndarray

Covariance matrix of the components.

Outputs

None beyond the returned value.

Sampling #

This class provides methods for generating Latin Hypercube Samples.

Methods:

Name Description
generate_lhs_samples_norm

Generates n Latin Hypercube Samples with a normal distribution, given mean and covariance matrix.

generate_lhs_samples_general

Generates Latin Hypercube samples for specified distributions, incorporating the given mean and covariance matrix.

uniform

Draws an array of uniform samples in [0, 1) from the centralized RNG surface.

create_rng staticmethod #

create_rng(seed=None) -> Generator

Create a fresh NumPy random generator using the project seed policy.

Outputs

None beyond the returned value.

Returns:

Type Description
Generator

np.random.Generator: A generator resolved from the supplied seed or RNG-like object.

derive_seed staticmethod #

derive_seed(label, *parts, seed=None) -> int

Derive a deterministic independent seed from a label and parts.

Outputs

None beyond the returned value.

Returns:

Name Type Description
int int

A deterministic 32-bit seed.

generate_lhs_samples_general staticmethod #

generate_lhs_samples_general(
    n, distributions_details, mean, covariance, seed=None
) -> ndarray

Generates Latin Hypercube samples for specified distributions.

Parameters:

Name Type Description Default
n int

The number of samples to generate.

required
distributions_details list[dict]

A list of dictionaries specifying the distribution types and parameters for each variable. Each dictionary should have a 'type' key indicating the distribution type (e.g., 'norm', 'lognorm'), and may include additional keys for distribution parameters.

required
mean list[float]

Mean values for the distributions.

required
covariance list[list[float]]

Covariance matrix for the distributions.

required
seed int

Seed for reproducibility. Defaults to None.

None

Returns:

Type Description
ndarray

An array of generated Latin Hypercube samples.

Examples:

Example usage for specifying different distributions and parameters#

Option 1: distributions_details = [ {'type': 'norm'}, {'type': 'lognorm'}, {'type': 'lognorm', 's': 1.2} ] mean = [3, 4, 2] covariance = [[1, 0.5, 0.3], [0.5, 1, 0.2], [0.3, 0.2, 1]]

Option 2: distributions_details = [{'type': 'norm'}] # All variables use the 'norm' distribution mean = [3, 4, 2] covariance = [[1, 0.5, 0.3], [0.5, 1, 0.2], [0.3, 0.2, 1]]

samples = cls.generate_lhs_samples_general(100, distributions_details, mean, covariance, seed=42, workers=4)
print(samples)
Outputs

None beyond the returned value.

generate_lhs_samples_norm staticmethod #

generate_lhs_samples_norm(
    n, mean, covariance, seed=None
) -> ndarray

Generates n Latin Hypercube Samples with a given mean and covariance matrix.

Parameters:

Name Type Description Default
n int

The number of samples to generate.

required
mean array - like

An array of means for each variable.

required
covariance array - like

The covariance matrix of the variables.

required
seed (optional, int)

A seed for the random number generator. Defaults to None.

None

Returns:

Type Description
ndarray

np.ndarray: An array of shape (n, len(mean)) with the generated samples.

Outputs

None beyond the returned value.

permutation staticmethod #

permutation(n, rng=None) -> ndarray

Return a permutation from the centralized RNG surface.

Outputs

Advances the supplied or created random number generator.

Returns:

Type Description
ndarray

np.ndarray: A permutation of np.arange(n).

random staticmethod #

random(rng=None) -> float

Draw a uniform random value from the centralized RNG surface.

Outputs

Advances the supplied or created random number generator.

Returns:

Name Type Description
float float

A uniform random value in the interval [0, 1).

resolve_seed staticmethod #

resolve_seed(seed=None) -> int

Return the project default seed when a caller does not provide one.

Outputs

None beyond the returned value.

Returns:

Name Type Description
int int

The caller-provided seed or Config.RANDOM_SEED.

uniform staticmethod #

uniform(
    size: Union[int, Tuple[int, ...]],
    rng: Optional[object] = None,
) -> ndarray

Draw an array of uniform random values from the centralized RNG surface.

Parameters:

Name Type Description Default
size Union[int, Tuple[int, ...]]

Output shape, as an int or a tuple of ints.

required
rng Optional[object]

Optional generator, RNG-like object, or integer seed. Defaults to a generator seeded with Config.RANDOM_SEED.

None
Outputs

Advances the supplied or created random number generator.

Returns:

Type Description
ndarray

np.ndarray: Uniform random values in the interval [0, 1) with shape size.

weibull_min staticmethod #

weibull_min(shape, scale, rng=None) -> float

Draw from a Weibull-min distribution with zero location.

Outputs

Advances the supplied or created random number generator.

Returns:

Name Type Description
float float

A Weibull-min sample scaled by scale.

Notes

scale is applied as NumPy's scale parameter, so the mean of the draw is scale * gamma(1 + 1/shape). Callers that pass an FPHLM rate parameter should be aware that the two conventions differ; see the note at the call site in damage_ratio_calculation.implicit_damage_ratio.

Utilities#

utils #

Classes:

Name Description
Utils

Utility methods for JSON data and DataFrame filtering.

Utils #

Utility methods for JSON data and DataFrame filtering.

This class keeps the lightweight file helpers used by CHEERSafe runtime code and a method for filtering values from pandas DataFrames.

Methods:

Name Description
from_json

Reads data from a JSON file and returns it as a numpy array or dictionary.

to_json

Writes JSON-serializable data, including numpy values, to a JSON file.

filter_column_values_df

Filters a pandas DataFrame based on the conditions provided in the keyword arguments, selects a specified column, and returns it as a numpy array.

filter_column_values_df classmethod #

filter_column_values_df(
    df: DataFrame, column_name: str, **kwargs
) -> ndarray

Filters a pandas DataFrame based on the conditions provided in the keyword arguments, selects a specified column, and returns it as a numpy array.

This method allows for dynamic filtering of a DataFrame based on multiple conditions. Each condition is applied to a specified column, and the results are used to filter the DataFrame. After filtering, values from a specified column are extracted and returned as a numpy array.

Parameters:

Name Type Description Default
df DataFrame

The DataFrame to be filtered.

required
column_name str

The name of the column to be selected after filtering.

required
**kwargs dict

Variable length keyword arguments, where each keyword represents a column in the DataFrame and the corresponding value represents the condition for filtering. Conditions should be provided in a way that they can be evaluated directly in a query.

{}

Returns:

Type Description
ndarray

np.ndarray: The selected column values after filtering, converted to a numpy array.

Outputs

None beyond the returned value.

from_json classmethod #

from_json(
    path_to_file: str, dict_key: str = None
) -> Union[ndarray, Dict[str, Any]]

Reads data from a JSON file and returns it as a numpy array or dictionary.

This method opens and reads a JSON file specified by path_to_file. If the JSON contains a list, it returns a numpy array of that list. If the JSON contains a dictionary and dict_key is specified, it returns a numpy array of the data associated with dict_key. If dict_key is not specified, it returns the entire dictionary.

Parameters:

Name Type Description Default
path_to_file str

Path to the location of the JSON file.

required
dict_key str

The specific key to extract data from within the JSON file. If not provided and the JSON is a dictionary, the entire dictionary is returned.

None

Returns:

Type Description
Union[ndarray, Dict[str, Any]]

Union[np.ndarray, dict]: Depending on the structure of the JSON and the presence of dict_key, returns either a numpy array or a dictionary containing the JSON file data.

to_json classmethod #

to_json(data: Any, path_to_file: str) -> None

Writes data to a JSON file.

Numpy arrays and scalar values are converted to native Python values before writing so model outputs can be serialized with the standard JSON library.

Parameters:

Name Type Description Default
data Any

Data to write.

required
path_to_file str

Path where the JSON file will be saved.

required

Returns:

Type Description
None

None