utils
Package
Modules
constants module
deprecation module
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 comparedict2 (
Dict[str,Any]) – Second dictionary to comparepath (
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 flattenobj (
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 comparedict2 (
Dict[str,Any]) – Second dictionary to comparepath (
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 dictionarydict2 (
Dict[str,Any]) – Second dictionary to merge into dict1prioritize (
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
get_main_dir module
get_object_attributes module
get_object_properties module
isnumeric module
istype module
mkdir_in_root module
print_progress module
rdelattr module
rgetattr module
rhasattr module
rsetattr module
simple_cycle module
Graph algorithms for finding cycles and strongly connected components.
Mathematical Formulation:
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\}\)
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\)
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]\]
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:
ParameterA 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.
- property max_value
- property min_value
- class Scalar(scalar=None, log_history=True, is_leaf=False, do_normalization=False, optional=False)[source]
Bases:
objectA 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.
- initialize(start_time=None, end_time=None, step_size=None, simulator=None, values=None, force=False)[source]
- set(v=None, stepIndex=None, apply=None)[source]
Set the scalar value.
- Parameters:
v (Union[Scalar, float]) – Value to set.
- Return type:
None
- 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:
objectA 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.
- property max_value
- property min_value
- class Vector(tensor=None, size=None, optional=False)[source]
Bases:
objectA 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:
- 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
- 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