cixerlab 1.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cixerlab/__init__.py +0 -0
- cixerlab/helpers/debug_helper.py +27 -0
- cixerlab/helpers/errors_helper.py +26 -0
- cixerlab/helpers/format_helpers.py +98 -0
- cixerlab/model/__init__.py +0 -0
- cixerlab/model/expr_analyzer.py +68 -0
- cixerlab/model/graph_wrapper.py +156 -0
- cixerlab/model/instancer_graph.py +150 -0
- cixerlab/model/solution.py +86 -0
- cixerlab/wrappers/__init__.py +0 -0
- cixerlab/wrappers/instancer_wrapper.py +37 -0
- cixerlab-1.0.1.dist-info/METADATA +79 -0
- cixerlab-1.0.1.dist-info/RECORD +15 -0
- cixerlab-1.0.1.dist-info/WHEEL +4 -0
- cixerlab-1.0.1.dist-info/licenses/LICENSE +21 -0
cixerlab/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def print_attributes(
|
|
5
|
+
names_to_values: dict[str, Any],
|
|
6
|
+
) -> None:
|
|
7
|
+
"""Print multiple named attributes and their values.
|
|
8
|
+
|
|
9
|
+
:param names_to_values: A map where each key is
|
|
10
|
+
the name associated with the value.
|
|
11
|
+
"""
|
|
12
|
+
for name, value in names_to_values.items():
|
|
13
|
+
print_attribute(name, value)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def print_attribute(name: str, value: Any) -> None:
|
|
17
|
+
"""Print an attribute name, value, and type.
|
|
18
|
+
|
|
19
|
+
:param name: The attribute name.
|
|
20
|
+
:param value: The attribute value.
|
|
21
|
+
"""
|
|
22
|
+
formatted_value_type = type(value).__name__
|
|
23
|
+
print(
|
|
24
|
+
f"[DEBUG] {name}:\n"
|
|
25
|
+
f"{value}\n"
|
|
26
|
+
f"Type: {formatted_value_type}\n"
|
|
27
|
+
)
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class TypeNotExpected(TypeError):
|
|
5
|
+
def __init__(
|
|
6
|
+
self,
|
|
7
|
+
current_value_name: str,
|
|
8
|
+
current_value: Any,
|
|
9
|
+
expected_type: type
|
|
10
|
+
) -> None:
|
|
11
|
+
"""Raise a TypeError describing a value with an unexpected type.
|
|
12
|
+
|
|
13
|
+
:param current_value_name: The name associated with the current value.
|
|
14
|
+
:param current_value: The value whose type is unexpected.
|
|
15
|
+
:param expected_type: The type expected for the value.
|
|
16
|
+
"""
|
|
17
|
+
self.current_value = current_value
|
|
18
|
+
self.expected_type = expected_type
|
|
19
|
+
self.current_value_type = type(current_value)
|
|
20
|
+
self.current_value_name = current_value_name
|
|
21
|
+
raise TypeError(
|
|
22
|
+
f"{self.current_value_name!r} with value "
|
|
23
|
+
f"{self.current_value!r} has an unexpected type.\n"
|
|
24
|
+
f"Current type: {self.current_value_type!r}\n"
|
|
25
|
+
f"Expected type: {self.expected_type!r}."
|
|
26
|
+
)
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import sympy as sp
|
|
2
|
+
import numpy as np
|
|
3
|
+
from typing import Iterable, MutableMapping, TypeAlias
|
|
4
|
+
|
|
5
|
+
from src.cixerlab.helpers.errors_helper import TypeNotExpected
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
SymbolLike: TypeAlias = str | sp.Symbol
|
|
9
|
+
MathematicalExpressionLike: TypeAlias = str | int | sp.Expr
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def format_math_exprs(
|
|
13
|
+
exprs: Iterable[MathematicalExpressionLike]
|
|
14
|
+
) -> set[sp.Expr]:
|
|
15
|
+
"""Format mathematical expressions as SymPy expressions.
|
|
16
|
+
|
|
17
|
+
:param exprs: Expressions to format.
|
|
18
|
+
:returns: A set that contains the formatted expressions.
|
|
19
|
+
"""
|
|
20
|
+
formatted_exprs = set()
|
|
21
|
+
for expr in exprs:
|
|
22
|
+
if isinstance(expr, sp.Expr):
|
|
23
|
+
formatted_exprs.add(expr)
|
|
24
|
+
else:
|
|
25
|
+
formatted_expr = sp.parse_expr(str(expr))
|
|
26
|
+
formatted_exprs.add(formatted_expr)
|
|
27
|
+
return formatted_exprs
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def format_known_symbol_map(
|
|
31
|
+
known_symbol_map: MutableMapping[
|
|
32
|
+
SymbolLike,
|
|
33
|
+
Iterable[MathematicalExpressionLike]]
|
|
34
|
+
) -> dict[sp.Symbol, np.ndarray]:
|
|
35
|
+
"""Format a mapping of symbols to their known values.
|
|
36
|
+
|
|
37
|
+
:param known_symbol_map: A mapping where each key is a SymbolLike
|
|
38
|
+
object and its value is an iterable of possible values.
|
|
39
|
+
The values are MathematicalExpressionLike objects.
|
|
40
|
+
:returns: The formatted mapping.
|
|
41
|
+
"""
|
|
42
|
+
formatted_symbol_map = {}
|
|
43
|
+
for symbol, values in known_symbol_map.items():
|
|
44
|
+
formatted_symbol = format_to_symbol(symbol)
|
|
45
|
+
formatted_values = format_to_value(values)
|
|
46
|
+
formatted_symbol_map[formatted_symbol] = formatted_values
|
|
47
|
+
return formatted_symbol_map
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def format_to_symbol(symbol: SymbolLike) -> sp.Symbol:
|
|
51
|
+
"""Format a single symbol.
|
|
52
|
+
|
|
53
|
+
:param symbol: A SymbolLike object.
|
|
54
|
+
:raises TypeNotExpected: If the provided symbol cannot be converted to a
|
|
55
|
+
SymPy Symbol.
|
|
56
|
+
:raises TypeError: If the provided symbol is not an ASCII string.
|
|
57
|
+
:return: A formatted SymPy Symbol object.
|
|
58
|
+
"""
|
|
59
|
+
if isinstance(symbol, str):
|
|
60
|
+
if symbol.isascii():
|
|
61
|
+
formatted_symbol = sp.symbols(symbol)
|
|
62
|
+
if isinstance(formatted_symbol, sp.Symbol):
|
|
63
|
+
return formatted_symbol
|
|
64
|
+
else:
|
|
65
|
+
raise TypeNotExpected(
|
|
66
|
+
"Formatted symbol",
|
|
67
|
+
formatted_symbol,
|
|
68
|
+
sp.Symbol
|
|
69
|
+
)
|
|
70
|
+
else:
|
|
71
|
+
raise TypeError(
|
|
72
|
+
f"The symbols need to be ASCII. "
|
|
73
|
+
f"The introduced symbol {symbol} is not ASCII."
|
|
74
|
+
)
|
|
75
|
+
else:
|
|
76
|
+
return symbol
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def format_to_value(
|
|
80
|
+
values: Iterable[MathematicalExpressionLike]
|
|
81
|
+
) -> np.ndarray:
|
|
82
|
+
"""Format values as objects readable by SymPy.
|
|
83
|
+
|
|
84
|
+
:param values: A homogeneous iterable of MathematicalExpressionLike
|
|
85
|
+
objects.
|
|
86
|
+
:return: A vector containing the values formatted as SymPy
|
|
87
|
+
expressions.
|
|
88
|
+
"""
|
|
89
|
+
formatted_values = []
|
|
90
|
+
print(values)
|
|
91
|
+
for val in values:
|
|
92
|
+
if isinstance(val, sp.Expr):
|
|
93
|
+
formatted_values.append(val)
|
|
94
|
+
elif isinstance(val, str):
|
|
95
|
+
formatted_values.append(sp.parse_expr(val))
|
|
96
|
+
else:
|
|
97
|
+
formatted_values.append(sp.parse_expr(str(val)))
|
|
98
|
+
return np.array(formatted_values)
|
|
File without changes
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import sympy as sp
|
|
2
|
+
import numpy as np
|
|
3
|
+
|
|
4
|
+
from src.cixerlab.model.solution \
|
|
5
|
+
import Solution
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ExpressionAnalyzer:
|
|
9
|
+
"""Analyze and solve a mathematical expression represented by SymPy."""
|
|
10
|
+
|
|
11
|
+
def __init__(
|
|
12
|
+
self,
|
|
13
|
+
expression: sp.Expr,
|
|
14
|
+
known_symbols_map: dict[sp.Symbol, np.ndarray],
|
|
15
|
+
) -> None:
|
|
16
|
+
"""Initialize an expression analyzer.
|
|
17
|
+
|
|
18
|
+
:param expression: The SymPy expression to analyze.
|
|
19
|
+
:param known_symbols_map: A mapping whose keys are known symbols and
|
|
20
|
+
whose values are vectors containing values compatible with SymPy
|
|
21
|
+
numbers.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
self.expr = expression
|
|
25
|
+
self.known_symbols_map = known_symbols_map
|
|
26
|
+
self.known_symbols = set(known_symbols_map)
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def unknown_symbols(self) -> set[sp.Symbol]:
|
|
30
|
+
"""
|
|
31
|
+
:return: A set with the symbols that do not have a defined value
|
|
32
|
+
"""
|
|
33
|
+
return self.symbols_in_expr.difference(self.known_symbols)
|
|
34
|
+
|
|
35
|
+
@property
|
|
36
|
+
def symbols_in_expr(self) -> set[sp.Symbol]:
|
|
37
|
+
"""
|
|
38
|
+
:return: A set that contains all symbols in the expression
|
|
39
|
+
"""
|
|
40
|
+
return set([
|
|
41
|
+
symbol
|
|
42
|
+
for symbol in self.expr.free_symbols
|
|
43
|
+
if isinstance(symbol, sp.Symbol)])
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def solution(self) -> Solution:
|
|
47
|
+
"""
|
|
48
|
+
:return: An instance of the Solution class initialized with
|
|
49
|
+
the known symbols.
|
|
50
|
+
"""
|
|
51
|
+
return Solution(self.expr, self.known_symbols)
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def formatted_symbol_to_dependency(self) \
|
|
55
|
+
-> dict[str, list[str]]:
|
|
56
|
+
"""
|
|
57
|
+
:return: A mapping where each key is a symbol and its value is a list
|
|
58
|
+
of dependencies. Each dependency is a string.
|
|
59
|
+
"""
|
|
60
|
+
formatted_symbol_to_dependency = {}
|
|
61
|
+
for symbol, dependencies in \
|
|
62
|
+
self.solution.symbol_to_dependencies.items():
|
|
63
|
+
symbol = str(symbol)
|
|
64
|
+
dependencies = [
|
|
65
|
+
str(dep) for dep in dependencies if dep in self.unknown_symbols
|
|
66
|
+
]
|
|
67
|
+
formatted_symbol_to_dependency[symbol] = dependencies
|
|
68
|
+
return formatted_symbol_to_dependency
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import sympy as sp
|
|
2
|
+
import numpy as np
|
|
3
|
+
import igraph as ig
|
|
4
|
+
|
|
5
|
+
from src.cixerlab.model.expr_analyzer \
|
|
6
|
+
import ExpressionAnalyzer, Solution
|
|
7
|
+
from src.cixerlab.helpers.errors_helper import TypeNotExpected
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class GraphWrapper:
|
|
11
|
+
"""Wraps graph-based expression analysis and substitution."""
|
|
12
|
+
def __init__(
|
|
13
|
+
self,
|
|
14
|
+
expr: sp.Expr,
|
|
15
|
+
known_symbols_map: dict[sp.Symbol, np.ndarray],
|
|
16
|
+
) -> None:
|
|
17
|
+
"""Initialize a graph wrapper.
|
|
18
|
+
|
|
19
|
+
:param expr: The SymPy expression that represents the program.
|
|
20
|
+
:param known_symbols_map: A mapping whose keys are SymPy symbols and
|
|
21
|
+
whose values are vectors with possible values. These
|
|
22
|
+
values must be compatible with SymPy's subs method and may
|
|
23
|
+
be Python primitives, NumPy values, or SymPy values.
|
|
24
|
+
"""
|
|
25
|
+
self.expr = expr
|
|
26
|
+
self.known_symbols_map = known_symbols_map
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def is_dag(self) -> bool:
|
|
30
|
+
"""Determine whether the graph is
|
|
31
|
+
a directed acyclic graph (DAG).
|
|
32
|
+
|
|
33
|
+
:return: True if the graph is a DAG;
|
|
34
|
+
False otherwise.
|
|
35
|
+
"""
|
|
36
|
+
if self.unknown_symbols:
|
|
37
|
+
self.source_graph \
|
|
38
|
+
= ig.Graph.ListDict(
|
|
39
|
+
self.formatted_symbol_to_dependency, directed=True
|
|
40
|
+
)
|
|
41
|
+
return self.source_graph.is_dag()
|
|
42
|
+
else:
|
|
43
|
+
return False
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def unknown_symbols(self) -> set[sp.Symbol]:
|
|
47
|
+
"""
|
|
48
|
+
:return: The symbols whose values are unknown.
|
|
49
|
+
"""
|
|
50
|
+
return self.expr_analyzer.unknown_symbols
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def solution(self) -> Solution:
|
|
54
|
+
"""
|
|
55
|
+
:return: Solution object produced by the expression analyzer.
|
|
56
|
+
"""
|
|
57
|
+
return self.expr_analyzer.solution
|
|
58
|
+
|
|
59
|
+
@property
|
|
60
|
+
def formatted_symbol_to_dependency(
|
|
61
|
+
self
|
|
62
|
+
) -> dict[str, list[str]]:
|
|
63
|
+
"""Return the formatted symbol-to-dependency mapping.
|
|
64
|
+
|
|
65
|
+
Each key is a symbol represented as a string, and each value is a list
|
|
66
|
+
of its dependencies, also represented as strings. These dependencies
|
|
67
|
+
are required to calculate the solution expression. The list is empty
|
|
68
|
+
when a symbol has no dependencies.
|
|
69
|
+
"""
|
|
70
|
+
return self.expr_analyzer.formatted_symbol_to_dependency
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def expr_analyzer(self) -> ExpressionAnalyzer:
|
|
74
|
+
"""
|
|
75
|
+
:return: Expression analyzer object used for this graph wrapper.
|
|
76
|
+
"""
|
|
77
|
+
return ExpressionAnalyzer(self.expr, self.known_symbols_map)
|
|
78
|
+
|
|
79
|
+
def known_symbols_setter(
|
|
80
|
+
self,
|
|
81
|
+
known_symbols_map: dict[sp.Symbol, np.ndarray]
|
|
82
|
+
) -> None:
|
|
83
|
+
"""Set the known-symbols mapping.
|
|
84
|
+
|
|
85
|
+
:param known_symbols_map: The new mapping of known symbols to values.
|
|
86
|
+
"""
|
|
87
|
+
self.known_symbols_map = known_symbols_map
|
|
88
|
+
|
|
89
|
+
def get_symbol_to_values(self) -> dict[sp.Symbol, np.ndarray]:
|
|
90
|
+
"""
|
|
91
|
+
Return symbol to value property adding exceptions for limit cases
|
|
92
|
+
of use.
|
|
93
|
+
|
|
94
|
+
:raises RuntimeError: The graph object is not a DAG
|
|
95
|
+
:raises RuntimeError: A general error in the substitution process
|
|
96
|
+
:return: A mapping from symbols to their possible values.
|
|
97
|
+
"""
|
|
98
|
+
if not self.is_dag:
|
|
99
|
+
raise RuntimeError("Cannot solve a non-DAG.")
|
|
100
|
+
if not self.unknown_symbols:
|
|
101
|
+
return {}
|
|
102
|
+
try:
|
|
103
|
+
return self.symbol_to_values
|
|
104
|
+
except Exception:
|
|
105
|
+
raise RuntimeError(
|
|
106
|
+
f"Failed to substitute values into expression {self.expr!r}."
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
@property
|
|
110
|
+
def symbol_to_values(self) -> dict[sp.Symbol, np.ndarray]:
|
|
111
|
+
"""
|
|
112
|
+
:return: A map where the key is a solved SymPy symbol
|
|
113
|
+
and its value is a vector of SymPy expressions
|
|
114
|
+
substituted which numerical value satisfy
|
|
115
|
+
the general solution in its isolated original expression.
|
|
116
|
+
"""
|
|
117
|
+
symbol_to_substitution = {}
|
|
118
|
+
for symbol, solutions in self.solution.symbol_to_solutions.items():
|
|
119
|
+
if symbol in self.known_symbols_map:
|
|
120
|
+
continue
|
|
121
|
+
|
|
122
|
+
all_substitutions = []
|
|
123
|
+
for solution_expr in solutions:
|
|
124
|
+
if not isinstance(solution_expr, sp.Expr):
|
|
125
|
+
raise TypeNotExpected(
|
|
126
|
+
"Solution expression",
|
|
127
|
+
solution_expr,
|
|
128
|
+
sp.Expr
|
|
129
|
+
)
|
|
130
|
+
substitutions = self._calc_substitutions(solution_expr)
|
|
131
|
+
for sub in substitutions:
|
|
132
|
+
all_substitutions.append(sub)
|
|
133
|
+
symbol_to_substitution[symbol] = np.array(all_substitutions)
|
|
134
|
+
return symbol_to_substitution
|
|
135
|
+
|
|
136
|
+
def _calc_substitutions(self, solution_expr) -> np.flatiter:
|
|
137
|
+
"""Calculate substitutions for a solution expression.
|
|
138
|
+
|
|
139
|
+
:param solution_expr: The solution expression to substitute values
|
|
140
|
+
into.
|
|
141
|
+
:return: A NumPy flat iterator containing all calculated substitutions.
|
|
142
|
+
"""
|
|
143
|
+
dependencies \
|
|
144
|
+
= list(self.solution.solution_to_dependencies[solution_expr])
|
|
145
|
+
subs_shape = [self.known_symbols_map[dep].size for dep in dependencies]
|
|
146
|
+
subs = np.empty(subs_shape, dtype=object)
|
|
147
|
+
for sub_idx in np.ndindex(subs.shape):
|
|
148
|
+
dependency_to_val = {}
|
|
149
|
+
for idx, size in enumerate(sub_idx):
|
|
150
|
+
dep = dependencies[idx]
|
|
151
|
+
dep_val = self.known_symbols_map[dep].flat[size]
|
|
152
|
+
dependency_to_val[dep] = dep_val
|
|
153
|
+
substitution = solution_expr.subs(dependency_to_val)
|
|
154
|
+
subs[sub_idx] = substitution
|
|
155
|
+
formatted_subs = subs.flat
|
|
156
|
+
return formatted_subs
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
from typing import Iterable
|
|
2
|
+
|
|
3
|
+
import sympy as sp
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
from src.cixerlab.model.graph_wrapper import GraphWrapper
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class InstancerGraph:
|
|
10
|
+
"""
|
|
11
|
+
Main graph that processes the global graph topological sorting, solving
|
|
12
|
+
and business logic.
|
|
13
|
+
"""
|
|
14
|
+
def __init__(
|
|
15
|
+
self,
|
|
16
|
+
known_symbols_map: dict[sp.Symbol, np.ndarray],
|
|
17
|
+
expressions: set[sp.Expr]
|
|
18
|
+
):
|
|
19
|
+
"""Initialize the graph with known symbol values and expressions.
|
|
20
|
+
|
|
21
|
+
:param expressions: A set of SymPy expressions.
|
|
22
|
+
:param known_symbols_map: A mapping whose keys are SymPy symbols and
|
|
23
|
+
whose values are vectors of possible values. These
|
|
24
|
+
values must be compatible with SymPy's solve function and may be
|
|
25
|
+
Python primitives, NumPy values, or SymPy values.
|
|
26
|
+
"""
|
|
27
|
+
self.known_symbols_map = known_symbols_map
|
|
28
|
+
self.expressions = expressions
|
|
29
|
+
self.solved_exprs = set()
|
|
30
|
+
|
|
31
|
+
def solve_solvable_symbols(self) -> None:
|
|
32
|
+
"""Find and solve unknown symbols in expressions whose graphs are DAGs.
|
|
33
|
+
|
|
34
|
+
Update the known-symbols mapping with each DAG's solutions. Then
|
|
35
|
+
repeatedly check adjacent graphs for newly solvable DAGs until no more
|
|
36
|
+
are found.
|
|
37
|
+
"""
|
|
38
|
+
if self.all_dags:
|
|
39
|
+
adjacent_to_dags = self._get_adjacent_to_dags()
|
|
40
|
+
for dag in self.all_dags:
|
|
41
|
+
self._update_instance(dag)
|
|
42
|
+
adjacent_dags = self._extract_dags(
|
|
43
|
+
adjacent_to_dags
|
|
44
|
+
)
|
|
45
|
+
while adjacent_dags:
|
|
46
|
+
for dag in adjacent_dags:
|
|
47
|
+
self._update_instance(dag)
|
|
48
|
+
adjacent_to_dags = self._get_adjacent_to_dags()
|
|
49
|
+
adjacent_dags = self._extract_dags(
|
|
50
|
+
adjacent_to_dags
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def all_dags(self) -> set[GraphWrapper]:
|
|
55
|
+
"""
|
|
56
|
+
:return: A set of all DAG instances
|
|
57
|
+
"""
|
|
58
|
+
all_dags = self._extract_dags(self.graph_wrappers)
|
|
59
|
+
return all_dags
|
|
60
|
+
|
|
61
|
+
def _extract_dags(
|
|
62
|
+
self,
|
|
63
|
+
graphs: Iterable[GraphWrapper]
|
|
64
|
+
) -> set[GraphWrapper]:
|
|
65
|
+
"""
|
|
66
|
+
Extract all DAGs in an iterable
|
|
67
|
+
|
|
68
|
+
:param graphs: An iterable of GraphWrapper elements
|
|
69
|
+
:return: A set with all DAGs in the iterable
|
|
70
|
+
"""
|
|
71
|
+
dags = set()
|
|
72
|
+
for graph in graphs:
|
|
73
|
+
graph.known_symbols_setter(self.known_symbols_map)
|
|
74
|
+
if graph.is_dag:
|
|
75
|
+
dags.add(graph)
|
|
76
|
+
return dags
|
|
77
|
+
|
|
78
|
+
def _get_adjacent_to_dags(self) -> set[GraphWrapper]:
|
|
79
|
+
"""
|
|
80
|
+
:return: A set of graphs adjacent to the currently solvable DAGs.
|
|
81
|
+
"""
|
|
82
|
+
adjacent_graphs = []
|
|
83
|
+
for graph_i in self.all_dags:
|
|
84
|
+
adjacent_graphs_expr_i \
|
|
85
|
+
= self.graph_expr_to_dependency[graph_i.expr]
|
|
86
|
+
adjacent_graphs_i = [
|
|
87
|
+
self.expr_to_graph[graph_expr]
|
|
88
|
+
for graph_expr in adjacent_graphs_expr_i
|
|
89
|
+
]
|
|
90
|
+
for graph in adjacent_graphs_i:
|
|
91
|
+
adjacent_graphs.append(graph)
|
|
92
|
+
return set(adjacent_graphs)
|
|
93
|
+
|
|
94
|
+
def _update_instance(self, dag: GraphWrapper) -> None:
|
|
95
|
+
"""Update the known symbols and solved expressions using a DAG's
|
|
96
|
+
solution.
|
|
97
|
+
|
|
98
|
+
:param dag: A GraphWrapper whose graph is a DAG.
|
|
99
|
+
"""
|
|
100
|
+
solved_symbols_map = dag.get_symbol_to_values()
|
|
101
|
+
self.known_symbols_map.update(solved_symbols_map)
|
|
102
|
+
self.solved_exprs.add(dag.expr)
|
|
103
|
+
|
|
104
|
+
@property
|
|
105
|
+
def expr_to_graph(self) -> dict[sp.Expr, GraphWrapper]:
|
|
106
|
+
"""
|
|
107
|
+
:return: Return a mapping from each expression to its GraphWrapper.
|
|
108
|
+
"""
|
|
109
|
+
expr_to_graph = {}
|
|
110
|
+
for graph in self.graph_wrappers:
|
|
111
|
+
expr_to_graph[graph.expr] = graph
|
|
112
|
+
return expr_to_graph
|
|
113
|
+
|
|
114
|
+
@property
|
|
115
|
+
def graph_wrappers(self) -> set[GraphWrapper]:
|
|
116
|
+
"""
|
|
117
|
+
:return: A a set of GraphWrapper instances, one for each expression.
|
|
118
|
+
"""
|
|
119
|
+
graph_wrappers = set()
|
|
120
|
+
for expr in self.expressions:
|
|
121
|
+
graph_wrapper = GraphWrapper(expr, self.known_symbols_map)
|
|
122
|
+
graph_wrappers.add(graph_wrapper)
|
|
123
|
+
return graph_wrappers
|
|
124
|
+
|
|
125
|
+
@property
|
|
126
|
+
def graph_expr_to_dependency(self) -> \
|
|
127
|
+
dict[sp.Expr, set[sp.Symbol]]:
|
|
128
|
+
"""
|
|
129
|
+
:return: A map where each key is an expression represented by a
|
|
130
|
+
GraphWrapper. Its value is the set of other expressions whose graphs
|
|
131
|
+
share at least one unknown
|
|
132
|
+
symbol with it.
|
|
133
|
+
"""
|
|
134
|
+
graph_expr_to_dependency = {}
|
|
135
|
+
for graph_wrapper_i in self.graph_wrappers:
|
|
136
|
+
graph_expr_i = graph_wrapper_i.expr
|
|
137
|
+
graph_expr_to_dependency[graph_expr_i] = set()
|
|
138
|
+
graph_expr_i_dependencies = graph_expr_to_dependency[graph_expr_i]
|
|
139
|
+
unknown_symbols_i: set = graph_wrapper_i.unknown_symbols
|
|
140
|
+
for graph_wrapper_j in self.graph_wrappers:
|
|
141
|
+
if graph_wrapper_i.expr == graph_wrapper_j.expr:
|
|
142
|
+
continue
|
|
143
|
+
graph_expr_j = graph_wrapper_j.expr
|
|
144
|
+
unknown_symbols_j: set = graph_wrapper_j.unknown_symbols
|
|
145
|
+
common_unknown_symbols = unknown_symbols_i.intersection(
|
|
146
|
+
unknown_symbols_j
|
|
147
|
+
)
|
|
148
|
+
if common_unknown_symbols:
|
|
149
|
+
graph_expr_i_dependencies.add(graph_expr_j)
|
|
150
|
+
return graph_expr_to_dependency
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import sympy as sp
|
|
2
|
+
|
|
3
|
+
from src.cixerlab.helpers.errors_helper import TypeNotExpected
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class Solution:
|
|
7
|
+
"""
|
|
8
|
+
Solve an expression for its unknown symbols.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
def __init__(
|
|
12
|
+
self,
|
|
13
|
+
expression: sp.Expr,
|
|
14
|
+
known_symbols: set[sp.Symbol],
|
|
15
|
+
):
|
|
16
|
+
"""Initialize a solution for an expression.
|
|
17
|
+
:param expression: The SymPy expression to solve.
|
|
18
|
+
:param known_symbols: The symbols whose values are already known.
|
|
19
|
+
"""
|
|
20
|
+
self.expression = expression
|
|
21
|
+
self.known_symbols = known_symbols
|
|
22
|
+
|
|
23
|
+
@property
|
|
24
|
+
def symbol_to_solutions(self) -> dict[sp.Symbol, list[sp.Expr]]:
|
|
25
|
+
"""Return the solutions for each unknown symbol.
|
|
26
|
+
|
|
27
|
+
:return: A mapping from each unknown symbol to a list of expressions
|
|
28
|
+
that solve the input expression for that symbol.
|
|
29
|
+
"""
|
|
30
|
+
symbol_to_solutions = {}
|
|
31
|
+
|
|
32
|
+
for symbol in self.expression.free_symbols:
|
|
33
|
+
if symbol in self.known_symbols:
|
|
34
|
+
continue
|
|
35
|
+
solutions = sp.solve(
|
|
36
|
+
self.expression,
|
|
37
|
+
symbol
|
|
38
|
+
)
|
|
39
|
+
symbol_to_solutions[symbol] = list(solutions)
|
|
40
|
+
return symbol_to_solutions
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def solution_to_dependencies(self) -> dict[sp.Expr, set[sp.Symbol]]:
|
|
44
|
+
"""Return the symbols used by each solution expression.
|
|
45
|
+
|
|
46
|
+
:return: A mapping from each solution expression to the set of symbols
|
|
47
|
+
on which it depends.
|
|
48
|
+
"""
|
|
49
|
+
solution_to_dependencies = {}
|
|
50
|
+
for solutions in self.symbol_to_solutions.values():
|
|
51
|
+
for solution in solutions:
|
|
52
|
+
if not isinstance(solution, sp.Expr):
|
|
53
|
+
raise TypeNotExpected(
|
|
54
|
+
"Solution",
|
|
55
|
+
solution,
|
|
56
|
+
sp.Expr
|
|
57
|
+
)
|
|
58
|
+
else:
|
|
59
|
+
dependencies = solution.free_symbols
|
|
60
|
+
solution_to_dependencies[solution] = dependencies
|
|
61
|
+
return solution_to_dependencies
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def symbol_to_dependencies(self) -> dict[sp.Expr, set[sp.Symbol]]:
|
|
65
|
+
"""Return the dependencies of each unknown symbol.
|
|
66
|
+
|
|
67
|
+
:return: A mapping from each unknown symbol to the set of symbols used
|
|
68
|
+
by its solution expressions.
|
|
69
|
+
"""
|
|
70
|
+
symbol_to_dependencies = {}
|
|
71
|
+
for symbol, solutions in self.symbol_to_solutions.items():
|
|
72
|
+
dependencies = set()
|
|
73
|
+
for solution in solutions:
|
|
74
|
+
if not isinstance(solution, sp.Expr):
|
|
75
|
+
raise TypeNotExpected(
|
|
76
|
+
"Solution",
|
|
77
|
+
solution,
|
|
78
|
+
sp.Expr
|
|
79
|
+
)
|
|
80
|
+
else:
|
|
81
|
+
dependencies \
|
|
82
|
+
= dependencies.union(
|
|
83
|
+
self.solution_to_dependencies[solution]
|
|
84
|
+
)
|
|
85
|
+
symbol_to_dependencies[symbol] = dependencies
|
|
86
|
+
return symbol_to_dependencies
|
|
File without changes
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import sympy as sp
|
|
2
|
+
from src.cixerlab.helpers import format_helpers as formatter
|
|
3
|
+
from typing import TypeAlias, Iterable, MutableMapping
|
|
4
|
+
|
|
5
|
+
from src.cixerlab.model.instancer_graph import InstancerGraph
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
SymbolLike: TypeAlias = str | sp.Symbol
|
|
9
|
+
MathematicalExpressionLike: TypeAlias = str | int | sp.Expr
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class InstancerWrapper(InstancerGraph):
|
|
13
|
+
"""Wrap an InstancerGraph with support for string and numeric inputs."""
|
|
14
|
+
def __init__(
|
|
15
|
+
self,
|
|
16
|
+
known_symbols_map:
|
|
17
|
+
MutableMapping[
|
|
18
|
+
SymbolLike,
|
|
19
|
+
Iterable[MathematicalExpressionLike]
|
|
20
|
+
],
|
|
21
|
+
math_exprs: Iterable[MathematicalExpressionLike]
|
|
22
|
+
) -> None:
|
|
23
|
+
"""Initialize the wrapper with known values and expressions.
|
|
24
|
+
|
|
25
|
+
:param known_symbols_map: A mapping from symbols, given as strings or
|
|
26
|
+
SymPy symbols, to iterables of possible values.
|
|
27
|
+
:param math_exprs: An iterable of expressions given as strings,
|
|
28
|
+
integers, or SymPy expressions.
|
|
29
|
+
"""
|
|
30
|
+
formatted_known_symbols \
|
|
31
|
+
= formatter.format_known_symbol_map(known_symbols_map)
|
|
32
|
+
formatted_math_exprs \
|
|
33
|
+
= formatter.format_math_exprs(math_exprs)
|
|
34
|
+
super().__init__(
|
|
35
|
+
formatted_known_symbols,
|
|
36
|
+
formatted_math_exprs
|
|
37
|
+
)
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cixerlab
|
|
3
|
+
Version: 1.0.1
|
|
4
|
+
Summary:
|
|
5
|
+
License-File: LICENSE
|
|
6
|
+
Author: Cixer
|
|
7
|
+
Author-email: cixer_dev@proton.me
|
|
8
|
+
Requires-Python: >=3.13
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
13
|
+
Requires-Dist: antlr4-python3-runtime (==4.11.1)
|
|
14
|
+
Requires-Dist: igraph (>=1.0.0,<2.0.0)
|
|
15
|
+
Requires-Dist: numpy (>=2.5.3,<3.0.0)
|
|
16
|
+
Requires-Dist: pytest (>=9.1.1,<10.0.0)
|
|
17
|
+
Requires-Dist: sympy (>=1.14.0,<2.0.0)
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
CixerLab is a mathematical computer algebra system (CAS) library that provides tools for inferring unknown variables and determining their values in a system of expressions. Given a system of expressions and the values of known symbols within that system, the library determines the possible values of the unknown symbols. To determine the order in which the system can be solved, CixerLab represents expressions as directed acyclic graphs (DAGs) and uses graph-theoretic algorithms to solve them sequentially, incorporating inferred values until the system is fully resolved.
|
|
21
|
+
|
|
22
|
+
# Why This Project Is Useful
|
|
23
|
+
|
|
24
|
+
CixerLab can be used for a range of mathematical and experimental applications. For example, when studying the motion of an object, you can provide a system of equations based on Newtonian mechanics together with known values, such as the initial and final positions, mass, and travel time. The library can then determine unknown quantities, such as acceleration, instantaneous velocity, and the force acting on the object.
|
|
25
|
+
|
|
26
|
+
You can also use mathematical constructs supported by the SymPy library, including limits, derivatives, integrals, trigonometric functions, and matrices. Because calculations are performed symbolically, this approach can avoid floating-point rounding errors and other numerical inaccuracies that may arise in numerical computation.
|
|
27
|
+
|
|
28
|
+
Researchers, software developers, and technology enthusiasts may also use this project as a reference implementation for software that uses a similar technical stack. See [`docs/tech_stack.md`](docs/tech_stack.md) for more information.
|
|
29
|
+
|
|
30
|
+
# How to Get This Project
|
|
31
|
+
|
|
32
|
+
## From Git
|
|
33
|
+
|
|
34
|
+
To build the project from Git, follow these steps:
|
|
35
|
+
|
|
36
|
+
1. Create a directory for the project and open it in your terminal.
|
|
37
|
+
|
|
38
|
+
2. Clone this repository into the directory:
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
git clone https://github.com/cixer-dev/CixerLab.git
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
3. If you have not already done so, install the Poetry dependency manager. See the official Poetry documentation for platform-specific recommendations: [https://python-poetry.org/docs/](https://python-poetry.org/docs/).
|
|
45
|
+
|
|
46
|
+
4. Install the project dependencies in a virtual environment by running:
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
poetry install
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Alternatively, you can install the dependencies manually using `pip` or another dependency-management tool and the [`requirements.txt`](requirements.txt) file:
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
pip install -r requirements.txt --no-deps
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
> **Warning:** When installing an exported `requirements.txt` file with `pip`, use the `--no-deps` flag. Poetry has already resolved the dependencies, and the exported file includes the direct and transitive requirements. Allowing `pip` to resolve them again is unnecessary and may cause conflicts.
|
|
59
|
+
|
|
60
|
+
> **Note:** For development, installing the project with Poetry is strongly recommended to help avoid compatibility issues.
|
|
61
|
+
|
|
62
|
+
# Project Documentation
|
|
63
|
+
|
|
64
|
+
The project documentation is currently under development and is not yet publicly available.
|
|
65
|
+
|
|
66
|
+
# How to Contribute
|
|
67
|
+
|
|
68
|
+
For guidance on the project's contribution standards and practices, see [`docs/CONTRIBUTING.md`](docs/CONTRIBUTING.md).
|
|
69
|
+
|
|
70
|
+
# Bibliography
|
|
71
|
+
|
|
72
|
+
> Csárdi, G., & Nepusz, T. (2006). The igraph software package for complex network research. *InterJournal, Complex Systems*, 1695. https://igraph.org
|
|
73
|
+
|
|
74
|
+
> Harris, C. R., Millman, K. J., van der Walt, S. J., Gommers, R., Virtanen, P., Cournapeau, D., Wieser, E., Taylor, J., Berg, S., Smith, N. J., Kern, R., Picus, M., Hoyer, S., van Kerkwijk, M. H., Brett, M., Haldane, A., Fernández del Río, J., Wiebe, M., Peterson, P., Gérard-Marchant, P., Sheppard, K., Reddy, T., Weckesser, W., Abbasi, H., Gohlke, C., & Oliphant, T. E. (2020). Array programming with NumPy. *Nature, 585*, 357–362. https://doi.org/10.1038/s41586-020-2649-2
|
|
75
|
+
|
|
76
|
+
> Meurer, A., Smith, C. P., Paprocki, M., Čertík, O., Kirpichev, S. B., Rocklin, M., Kumar, AMiT, Ivanov, S., Moore, J. K., Singh, S., Rathnayake, T., Vig, S., Granger, B. E., Muller, R. P., Bonazzi, F., Gupta, H., Vats, S., Johansson, F., Pedregosa, F., Curry, M. J., Terrel, A. R., Roučka, Š., Saboo, A., Fernando, I., Kulal, S., Cimrman, R., & Scopatz, A. (2017). SymPy: Symbolic computing in Python. *PeerJ Computer Science, 3*, e103. https://doi.org/10.7717/peerj-cs.103
|
|
77
|
+
|
|
78
|
+
> Wilson, R. J. (2010). *Introduction to graph theory* (5th ed.). Pearson.
|
|
79
|
+
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
cixerlab/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
cixerlab/helpers/debug_helper.py,sha256=9Ji9kgQJtP3SMvJJVxioMNACmrr72YsRJii9sPv_-58,699
|
|
3
|
+
cixerlab/helpers/errors_helper.py,sha256=-_PKpR2WaeaY9Clk9eDyG9gWjvZLpvZ6AYIJHiHp0qY,953
|
|
4
|
+
cixerlab/helpers/format_helpers.py,sha256=210r_YOnvm8WNrfEFFQjJa-_qtX1KZkr4-je_Z9v870,3182
|
|
5
|
+
cixerlab/model/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
cixerlab/model/expr_analyzer.py,sha256=QLyIe2fbOBUBL5k-WvAr6wxU1pt62VY4qYgexjGYx2U,2175
|
|
7
|
+
cixerlab/model/graph_wrapper.py,sha256=_qiEfGaZBO1vFGy2jfYcXXi6bLS1Flp9dT2JEhfLmM0,5689
|
|
8
|
+
cixerlab/model/instancer_graph.py,sha256=sVXe6VmDuiX4aNltS_x0wdXKfHqZYpMUtU8MoRu_f0c,5423
|
|
9
|
+
cixerlab/model/solution.py,sha256=qJEGT76HgLI_9XzQJsK3SB8PjsFnl7GL6aN9uEKczo8,2986
|
|
10
|
+
cixerlab/wrappers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
11
|
+
cixerlab/wrappers/instancer_wrapper.py,sha256=I-wp_CcFkBe05TlpXbDKe_sgtZzqu1Fi9B54gTVmnBw,1306
|
|
12
|
+
cixerlab-1.0.1.dist-info/METADATA,sha256=TCvgSl-IzhT9FmQDEVFnu16Wj-w5sBknWuCMwVzCgg0,4911
|
|
13
|
+
cixerlab-1.0.1.dist-info/WHEEL,sha256=L-WvLdSBvJWHXv5zrQxDvNRnIgoBzLUpcbuiw19KCuQ,88
|
|
14
|
+
cixerlab-1.0.1.dist-info/licenses/LICENSE,sha256=HR2JiCRnoTXF6Rrqn038wMl6t3RxTkN3ukEzUGuXY9k,1062
|
|
15
|
+
cixerlab-1.0.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Cixer
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|