utils

Package

Modules

constants module

class Constants[source]

Bases: object

density = {'air': 1.225, 'water': 1000}
specificHeatCapacity = {'air': 1012, 'water': 4180}

deprecation module

deprecate_args(deprecated_args, new_args, positions, kwargs)[source]

dict_utils module

compare_dict_structure(dict1, dict2, path='')[source]

Compare the structure of two nested dictionaries.

This function checks that both dictionaries have the same keys at all nested levels, without requiring the actual values to match. It returns detailed information about any differences found.

Parameters:
  • dict1 (Dict[str, Any]) – First dictionary to compare

  • dict2 (Dict[str, Any]) – Second dictionary to compare

  • path (str) – Current path in the dictionary for error reporting

Returns:

  • ‘structures_match’: bool - True if structures match, False otherwise

  • ’missing_in_2’: set - keys in dict1 but not in dict2

  • ’missing_in_1’: set - keys in dict2 but not in dict1

Return type:

Dict containing comparison results

Example

>>> dict1 = {"a": {"b": 1, "c": 2}, "d": 3}
>>> dict2 = {"a": {"b": 10, "c": 20}, "d": 30}
>>> result = compare_dict_structure(dict1, dict2)
>>> result['structures_match']
True
>>> dict1 = {"a": {"b": 1, "c": 2}, "d": 3}
>>> dict2 = {"a": {"b": 10}, "e": 4}  # Missing "c" and "d", extra "e"
>>> result = compare_dict_structure(dict1, dict2)
>>> result['structures_match']
False
>>> result['missing_in_2']
{'d', 'a.c'}
>>> result['missing_in_1']
{'e'}
flatten_dict(nested_dict, obj)[source]

Flatten a nested dictionary into a list of tuples with (key, value) pairs.

This function recursively traverses nested dictionaries and creates flattened key-value pairs using only the final key names. Only final values (non-dictionary values) are included in the result.

Parameters:
  • nested_dict (Dict[str, Any]) – The nested dictionary to flatten

  • obj (Any) – The object to which the flattened dictionary belongs

Return type:

list[tuple[str, Any]]

Returns:

List of tuples containing (final_key, value) pairs

Example

>>> nested = {"a": {"b": 1, "c": {"d": 2, "e": 3}}, "f": 4}
>>> flatten_dict(nested)
[('b', 1), ('d', 2), ('e', 3), ('f', 4)]
>>> nested = {"user": {"profile": {"name": "John", "age": 30}}}
>>> flatten_dict(nested)
[('name', 'John'), ('age', 30)]
>>> flatten_dict({})  # Empty dict
[]
>>> flatten_dict({"a": None, "b": {"c": 0}})  # None and zero values
[('a', None), ('c', 0)]
get_dict_differences(dict1, dict2, path='')[source]

Get detailed differences between two nested dictionaries.

Parameters:
  • dict1 (Dict[str, Any]) – First dictionary to compare

  • dict2 (Dict[str, Any]) – Second dictionary to compare

  • path (str) – Current path in the dictionary for error reporting

Returns:

  • ‘missing_in_2’: keys in dict1 but not in dict2

  • ’missing_in_1’: keys in dict2 but not in dict1

  • ’structure_mismatch’: True if structures don’t match

  • ’differences’: nested dictionary with specific differences

Return type:

Dict containing information about differences

Example

>>> dict1 = {"a": {"b": 1, "c": 2}, "d": 3}
>>> dict2 = {"a": {"b": 10}, "e": 4}
>>> get_dict_differences(dict1, dict2)
{
    'missing_in_2': {'d', 'a.c'},
    'missing_in_1': {'e'},
    'structure_mismatch': True,
    'differences': {'a': {'missing_in_2': {'c'}}}
}
merge_dicts(dict1, dict2, prioritize=None)[source]

Merge two nested dictionaries.

Parameters:
  • dict1 (Dict[str, Any]) – First dictionary

  • dict2 (Dict[str, Any]) – Second dictionary to merge into dict1

  • prioritize (Optional[str]) – If ‘dict1’, prioritize dict1 values (only overwrite if dict1 value is None) If ‘dict2’, prioritize dict2 values (only overwrite if dict2 value is None) If None, use standard merge behavior (dict2 overwrites dict1)

Return type:

Dict[str, Any]

Returns:

Merged dictionary

Example

>>> dict1 = {"a": {"b": 1, "c": 2}, "d": 3}
>>> dict2 = {"a": {"b": 10, "e": 4}, "f": 5}
>>> merge_dicts(dict1, dict2)  # Standard merge
{"a": {"b": 10, "c": 2, "e": 4}, "d": 3, "f": 5}
>>> dict1 = {"a": {"b": 1, "c": None}, "d": None}
>>> dict2 = {"a": {"b": 10, "c": 20}, "d": 30, "e": 40}
>>> merge_dicts(dict1, dict2, prioritize='dict1')
{"a": {"b": 1, "c": 20}, "d": 30}

do_nothing module

do_nothing(*args, **kwargs)[source]

get_main_dir module

exception MainPathNotFound[source]

Bases: Warning

get_main_dir()[source]

Get the main directory of the project. Cannot be used with multiprocessing.

get_object_attributes module

get_object_attributes(obj)[source]

get_object_properties module

get_object_properties(object_)[source]

isnumeric module

isnumeric(x)[source]

istype module

istype(instance, type_tuple)[source]

mkdir_in_root module

mkdir_in_root(folder_list, filename=None, root=None)[source]

print_progress module

class PrintProgress[source]

Bases: object

add_level()[source]
remove_level()[source]

rdelattr module

rdelattr(obj, attr)[source]

Recursively delete an attribute using dot notation.

Parameters:
  • obj – The object to delete the attribute from

  • attr – The attribute path using dot notation (e.g., ‘a.b.c’)

Example

rdelattr(obj, ‘layer.weight.data’) # deletes obj.layer.weight.data

rgetattr module

rgetattr(obj, attr, *args)[source]

rhasattr module

rhasattr(obj, attr, *args)[source]

rsetattr module

rsetattr(obj, attr, val)[source]

simple_cycle module

Graph algorithms for finding cycles and strongly connected components.

Mathematical Formulation:

  1. Simple Cycles: A simple cycle in a directed graph \(G = (V, E)\) is a path \(v_1, v_2, ..., v_k\) where: - \(v_1 = v_k\) - All other vertices are distinct - \((v_i, v_{i+1}) \in E \forall i \in \{1, ..., k-1\}\)

  2. Strongly Connected Components (SCC): A strongly connected component of a directed graph \(G = (V, E)\) is a maximal subset \(C \subseteq V\) where:

    • For any two vertices \(u, v \in C\), there exists a path from \(u\) to \(v\)

    • For any two vertices \(u \in C, v \notin C\), either:
      • There is no path from \(u\) to \(v\), or

      • There is no path from \(v\) to \(u\)

  3. Tarjan’s Algorithm: For each vertex \(v \in V\), we maintain:

    • \(index[v]\): The order in which \(v\) was discovered

    • \(lowlink[v]\): The smallest index of any vertex reachable from \(v\) through a back edge

    A vertex \(v\) is the root of an SCC if and only if:

    \[lowlink[v] = index[v]\]
remove_node(G, target)[source]
simple_cycles(G)[source]
strongly_connected_components(graph)[source]
subgraph(G, vertices)[source]

test_notebook module

test_notebook(notebook_path)[source]

Execute a notebook and return True if it runs without errors, False otherwise. Prints detailed error information if an exception occurs.

Parameters:

notebook_path – str, path to the notebook file

Returns:

bool, True if notebook executes without errors, False otherwise

types module

class Parameter(data, min_value=None, max_value=None, requires_grad=True)[source]

Bases: Parameter

A custom nn.Parameter implementation that normalizes the data between 0 and 1 to stabilize gradients in physical systems where the parameters scales can be different. This makes it possible to use torch.optim.Optimizer to optimize the parameters.

denormalize(v)[source]
get()[source]

Get the denormalized value.

normalize(v, min_value=None, max_value=None)[source]
set(value, normalized=True)[source]

Set the parameter value (will be normalized internally).

property max_value
property min_value
class Scalar(scalar=None, log_history=True, is_leaf=False, do_normalization=False, optional=False)[source]

Bases: object

A custom scalar implementation with operator overloading.

This class wraps a single scalar value and provides arithmetic operations compatibility with other Scalar instances, numeric types, and numpy arrays. Implements total ordering through the @functools.total_ordering decorator.

scalar

The wrapped scalar value.

copy()[source]
denormalize(v)[source]
get()[source]

Get the scalar value.

Returns:

Scalar value.

Return type:

float

get_float()[source]

Get the scalar value as a float.

Returns:

Scalar value.

Return type:

float

initialize(start_time=None, end_time=None, step_size=None, simulator=None, values=None, force=False)[source]
normalize(v=None)[source]
reset()[source]
set(v=None, stepIndex=None, apply=None)[source]

Set the scalar value.

Parameters:

v (Union[Scalar, float]) – Value to set.

Return type:

None

set_requires_grad(requires_grad)[source]
update(group_id=None)[source]
property do_normalization
property history
property is_leaf
property log_history
property normalized_history
property optional
property scalar
class TensorParameter(tensor, min_value=None, max_value=None, normalized=True)[source]

Bases: object

A custom nn.Parameter implementation that normalizes the data between 0 and 1 to stabilize gradients in physical systems where the parameters scales can be different.

This class is used to represent model parameters as a Tensor when we calculate the Jacobian analytically as the jac = torch.nn.functional.Jacobian() has the signature jac(f: callable, input: Tensor) -> Tensor.

denormalize(v)[source]
get()[source]

Get the denormalized value.

normalize(v, min_value=None, max_value=None)[source]
set(value, normalized=True)[source]

Set the parameter value (will be normalized internally).

property max_value
property min_value
class Vector(tensor=None, size=None, optional=False)[source]

Bases: object

A custom vector implementation with mapping capabilities.

This class implements a vector (1D array) with additional functionality to map between indices and group IDs. It maintains internal mappings and provides methods for initialization, updates, and value access.

size

Current size of the vector.

Type:

int

id_map

Maps vector indices to group IDs.

Type:

Dict[int, int]

id_map_reverse

Maps group IDs to vector indices.

Type:

Dict[int, int]

tensor

The underlying tensor storing vector values.

Type:

torch.Tensor

current_idx

Current index pointer for setting values.

Type:

int

sorted_id_indices

Indices that sort the vector by group IDs.

Type:

torch.Tensor

copy()[source]

Create a copy of the vector.

Returns:

A new Vector instance with the same data.

Return type:

Vector

get()[source]

Get vector values sorted by group ID.

Returns:

Tensor of values sorted by group ID.

Return type:

torch.Tensor

increment(v=1)[source]

Increment the vector size.

Parameters:

v (int, optional) – Amount to increment by. Defaults to 1.

Return type:

None

initialize(start_time=None, end_time=None, step_size=None, simulator=None)[source]

Initialize the vector tensor and sorting indices.

Creates the underlying torch tensor and computes indices for sorted access by group ID.

Return type:

None

make_pickable()[source]
reset()[source]

Reset the vector to initial state.

Return type:

None

set(v, stepIndex=None)[source]

Set the next value in the vector.

Parameters:

v (float) – Value to set at current index.

Return type:

None

update(group_id=None)[source]

Update the vector with a new group ID.

Parameters:

group_id (Optional[int]) – Group ID to add. If None, uses current size.

Return type:

None

property optional
parameter_get(self)[source]

Get the parameter value (fallback for regular nn.Parameter objects).

test()[source]

uppath module

uppath(_path, n)[source]

Returns the absolute path of “_path” where n levels are removed. E.g. uppath(“C:/Example/test/path/file”, 2) gives “C:/Example/test”