jpipe-runner 2.0.0b27__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.
- jpipe_runner/GraphWorkflowVisualizer.py +284 -0
- jpipe_runner/__init__.py +0 -0
- jpipe_runner/__main__.py +4 -0
- jpipe_runner/enums.py +31 -0
- jpipe_runner/exceptions.py +30 -0
- jpipe_runner/framework/__init__.py +0 -0
- jpipe_runner/framework/context.py +232 -0
- jpipe_runner/framework/decorators/__init__.py +0 -0
- jpipe_runner/framework/decorators/contribution_decorator.py +25 -0
- jpipe_runner/framework/decorators/jpipe_decorator.py +200 -0
- jpipe_runner/framework/decorators/skip_decorator.py +23 -0
- jpipe_runner/framework/engine.py +726 -0
- jpipe_runner/framework/logger.py +52 -0
- jpipe_runner/framework/validators.py +674 -0
- jpipe_runner/runner.py +350 -0
- jpipe_runner/runtime.py +142 -0
- jpipe_runner/utils.py +87 -0
- jpipe_runner-2.0.0b27.dist-info/LICENSE +21 -0
- jpipe_runner-2.0.0b27.dist-info/METADATA +131 -0
- jpipe_runner-2.0.0b27.dist-info/RECORD +22 -0
- jpipe_runner-2.0.0b27.dist-info/WHEEL +4 -0
- jpipe_runner-2.0.0b27.dist-info/entry_points.txt +3 -0
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
import networkx as nx
|
|
2
|
+
|
|
3
|
+
try:
|
|
4
|
+
import tkinter as tk
|
|
5
|
+
import matplotlib.pyplot as plt
|
|
6
|
+
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
|
|
7
|
+
from matplotlib.patches import Patch
|
|
8
|
+
GUI_AVAILABLE = True
|
|
9
|
+
except ImportError:
|
|
10
|
+
GUI_AVAILABLE = False
|
|
11
|
+
tk = None
|
|
12
|
+
plt = None
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class GraphWorkflowVisualizer:
|
|
16
|
+
# Workflow steps
|
|
17
|
+
PARSE_CLI_ARGS = "Parse CLI arguments"
|
|
18
|
+
SET_LOGGER_LEVEL = "Set logger level"
|
|
19
|
+
INITIALIZE_RUNTIME = "Initialize runtime"
|
|
20
|
+
VALIDATE_ARGUMENTS_FILES = "Validate arguments files"
|
|
21
|
+
VALIDATE_JUSTIFICATION_FILE = "Validate justification file"
|
|
22
|
+
LOAD_CONFIGURATION = "Load configuration"
|
|
23
|
+
LOAD_JUSTIFICATION_FILE = "Load justification file"
|
|
24
|
+
PARSE_JUSTIFICATION_GRAPH = "Parse justification graph"
|
|
25
|
+
REGISTER_DECORATORS = "Register decorators"
|
|
26
|
+
VALIDATE_PIPELINE = "Validate pipeline"
|
|
27
|
+
EXECUTE_JUSTIFICATION = "Execute justification"
|
|
28
|
+
SUMMARIZE_RESULTS = "Summarize results"
|
|
29
|
+
EXPORT_OUTPUT = "Export output"
|
|
30
|
+
|
|
31
|
+
# Substeps VALIDATE_JUSTIFICATION_FILE
|
|
32
|
+
VALIDATE_STRUCTURE_ELEMENTS = "Validate structure of elements"
|
|
33
|
+
VALIDATE_RELATIONS_STRUCTURES = "Validate relations structure"
|
|
34
|
+
EXTRACTING_JUSTIFICATION_NAME = "Extracting justification name"
|
|
35
|
+
|
|
36
|
+
# PARSE_JUSTIFICATION_GRAPH
|
|
37
|
+
ADDING_NODE_TO_GRAPH = "Adding node to graph"
|
|
38
|
+
ADDING_EDGES_TO_GRAPH = "Adding edges to graph"
|
|
39
|
+
|
|
40
|
+
# EXECUTE_JUSTIFICATION
|
|
41
|
+
FETCH_EXECUTION_ORDER = "Fetch execution order"
|
|
42
|
+
CALL_FUNCTION = "Call function"
|
|
43
|
+
CHECK_RETURN_TYPE = "Check return type"
|
|
44
|
+
HANDLE_RESULT_STATUS = "Handle result status"
|
|
45
|
+
|
|
46
|
+
# EXPORT_OUTPUT
|
|
47
|
+
IMPORTING_PYGRAPHVIZ = "Importing pygraphviz"
|
|
48
|
+
PREPARE_OUTPUT_PATH = "Prepare output path"
|
|
49
|
+
PREPARE_STYLES = "Prepare styles"
|
|
50
|
+
CREATE_GRAPH = "Create graph"
|
|
51
|
+
STYLE_NODES = "Style nodes"
|
|
52
|
+
STYLE_EDGES = "Style edges"
|
|
53
|
+
DRAW_GRAPH = "Draw graph"
|
|
54
|
+
|
|
55
|
+
# Statuses
|
|
56
|
+
CURRENT = "current"
|
|
57
|
+
DONE = "done"
|
|
58
|
+
FAIL = "fail"
|
|
59
|
+
IDLE = "idle"
|
|
60
|
+
SKIP = "skip"
|
|
61
|
+
|
|
62
|
+
# Modes
|
|
63
|
+
GRAPH = "graph"
|
|
64
|
+
DETAIL = "detail"
|
|
65
|
+
|
|
66
|
+
workflow_nodes = [
|
|
67
|
+
PARSE_CLI_ARGS,
|
|
68
|
+
SET_LOGGER_LEVEL,
|
|
69
|
+
INITIALIZE_RUNTIME,
|
|
70
|
+
VALIDATE_ARGUMENTS_FILES,
|
|
71
|
+
VALIDATE_JUSTIFICATION_FILE,
|
|
72
|
+
LOAD_CONFIGURATION,
|
|
73
|
+
LOAD_JUSTIFICATION_FILE,
|
|
74
|
+
PARSE_JUSTIFICATION_GRAPH,
|
|
75
|
+
REGISTER_DECORATORS,
|
|
76
|
+
VALIDATE_PIPELINE,
|
|
77
|
+
EXECUTE_JUSTIFICATION,
|
|
78
|
+
SUMMARIZE_RESULTS,
|
|
79
|
+
EXPORT_OUTPUT
|
|
80
|
+
]
|
|
81
|
+
|
|
82
|
+
workflow_edges = [
|
|
83
|
+
(PARSE_CLI_ARGS, SET_LOGGER_LEVEL),
|
|
84
|
+
(SET_LOGGER_LEVEL, VALIDATE_ARGUMENTS_FILES),
|
|
85
|
+
(VALIDATE_ARGUMENTS_FILES, INITIALIZE_RUNTIME),
|
|
86
|
+
(INITIALIZE_RUNTIME, LOAD_CONFIGURATION),
|
|
87
|
+
(LOAD_CONFIGURATION, LOAD_JUSTIFICATION_FILE),
|
|
88
|
+
(LOAD_JUSTIFICATION_FILE, VALIDATE_JUSTIFICATION_FILE),
|
|
89
|
+
(VALIDATE_JUSTIFICATION_FILE, PARSE_JUSTIFICATION_GRAPH),
|
|
90
|
+
(PARSE_JUSTIFICATION_GRAPH, REGISTER_DECORATORS),
|
|
91
|
+
(REGISTER_DECORATORS, VALIDATE_PIPELINE),
|
|
92
|
+
(VALIDATE_PIPELINE, EXECUTE_JUSTIFICATION),
|
|
93
|
+
(EXECUTE_JUSTIFICATION, SUMMARIZE_RESULTS),
|
|
94
|
+
(SUMMARIZE_RESULTS, EXPORT_OUTPUT)
|
|
95
|
+
]
|
|
96
|
+
|
|
97
|
+
color_map = {
|
|
98
|
+
IDLE: "lightgray",
|
|
99
|
+
CURRENT: "#1E90FF",
|
|
100
|
+
DONE: "limegreen",
|
|
101
|
+
FAIL: "red",
|
|
102
|
+
SKIP: "gold"
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
def __init__(self, master):
|
|
106
|
+
if not GUI_AVAILABLE:
|
|
107
|
+
raise ImportError("GUI dependencies not available. Install with: pip install jpipe-runner[gui]")
|
|
108
|
+
print("Initializing GraphWorkflowVisualizer...")
|
|
109
|
+
self.master = master
|
|
110
|
+
self.master.title("Project Workflow Graph")
|
|
111
|
+
self.mode = GraphWorkflowVisualizer.GRAPH
|
|
112
|
+
self.current_node = None
|
|
113
|
+
self.current_path = []
|
|
114
|
+
|
|
115
|
+
self.G = nx.DiGraph()
|
|
116
|
+
self.G.add_nodes_from(GraphWorkflowVisualizer.workflow_nodes)
|
|
117
|
+
self.G.add_edges_from(GraphWorkflowVisualizer.workflow_edges)
|
|
118
|
+
self.pos = nx.spring_layout(self.G, seed=42, k=0.25)
|
|
119
|
+
|
|
120
|
+
self.fig, self.ax = plt.subplots(figsize=(9, 6))
|
|
121
|
+
self.canvas = FigureCanvasTkAgg(self.fig, master=self.master)
|
|
122
|
+
self.canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
|
|
123
|
+
|
|
124
|
+
self.status = {node: GraphWorkflowVisualizer.IDLE for node in GraphWorkflowVisualizer.workflow_nodes}
|
|
125
|
+
self.subgraphs = {}
|
|
126
|
+
self.substatus = {}
|
|
127
|
+
self.subgraph_nodes = {}
|
|
128
|
+
|
|
129
|
+
self.master.protocol("WM_DELETE_WINDOW", self.on_close)
|
|
130
|
+
|
|
131
|
+
self.fig.canvas.mpl_connect("button_press_event", self.on_click)
|
|
132
|
+
self.master.bind("<Escape>", lambda e: self.back_one_level())
|
|
133
|
+
|
|
134
|
+
self.close_button = tk.Button(master=self.master, text="Close", command=self.master.quit)
|
|
135
|
+
self.close_button.pack(side="bottom", pady=10)
|
|
136
|
+
|
|
137
|
+
self.detail_frame = None
|
|
138
|
+
|
|
139
|
+
self.draw_graph()
|
|
140
|
+
print("GraphWorkflowVisualizer initialized with nodes and edges.")
|
|
141
|
+
|
|
142
|
+
def draw_graph(self):
|
|
143
|
+
self.ax.clear()
|
|
144
|
+
node_colors = [GraphWorkflowVisualizer.color_map.get(self.status[n], "gray") for n in self.G.nodes()]
|
|
145
|
+
|
|
146
|
+
nx.draw(
|
|
147
|
+
self.G,
|
|
148
|
+
pos=self.pos,
|
|
149
|
+
with_labels=True,
|
|
150
|
+
node_color=node_colors,
|
|
151
|
+
node_size=2000,
|
|
152
|
+
font_size=9,
|
|
153
|
+
font_weight='bold',
|
|
154
|
+
arrows=True,
|
|
155
|
+
ax=self.ax
|
|
156
|
+
)
|
|
157
|
+
self.draw_legend()
|
|
158
|
+
self.ax.set_title("Project Workflow Execution", fontsize=14)
|
|
159
|
+
self.canvas.draw()
|
|
160
|
+
|
|
161
|
+
def mark_step(self, step_name: str, status: str = DONE):
|
|
162
|
+
if step_name in self.status:
|
|
163
|
+
self.status[step_name] = status
|
|
164
|
+
if self.mode == GraphWorkflowVisualizer.GRAPH:
|
|
165
|
+
self.draw_graph()
|
|
166
|
+
|
|
167
|
+
def mark_substep(self, node: str, substep_name: str, status: str):
|
|
168
|
+
if node not in self.subgraphs:
|
|
169
|
+
self.subgraphs[node] = nx.DiGraph()
|
|
170
|
+
self.substatus[node] = {}
|
|
171
|
+
|
|
172
|
+
G = self.subgraphs[node]
|
|
173
|
+
G.add_node(substep_name)
|
|
174
|
+
|
|
175
|
+
if self.substatus[node] and substep_name not in self.substatus[node]:
|
|
176
|
+
last_substep = list(self.substatus[node].keys())[-1]
|
|
177
|
+
G.add_edge(last_substep, substep_name)
|
|
178
|
+
|
|
179
|
+
self.substatus[node][substep_name] = status
|
|
180
|
+
|
|
181
|
+
if self.mode == GraphWorkflowVisualizer.DETAIL and self.current_node == node:
|
|
182
|
+
self.show_node_detail(node)
|
|
183
|
+
|
|
184
|
+
def mark_node_as_graph(self, parent_node: str, substep_name: str):
|
|
185
|
+
if parent_node not in self.subgraph_nodes:
|
|
186
|
+
self.subgraph_nodes[parent_node] = set()
|
|
187
|
+
self.subgraph_nodes[parent_node].add(substep_name)
|
|
188
|
+
|
|
189
|
+
def on_click(self, event):
|
|
190
|
+
if self.mode == GraphWorkflowVisualizer.GRAPH:
|
|
191
|
+
for node, (x, y) in self.pos.items():
|
|
192
|
+
x_disp, y_disp = self.ax.transData.transform((x, y))
|
|
193
|
+
dist = ((event.x - x_disp) ** 2 + (event.y - y_disp) ** 2) ** 0.5
|
|
194
|
+
if dist < 25:
|
|
195
|
+
self.show_node_detail(node)
|
|
196
|
+
break
|
|
197
|
+
elif self.mode == GraphWorkflowVisualizer.DETAIL:
|
|
198
|
+
subgraph = self.subgraphs.get(self.current_node)
|
|
199
|
+
if not subgraph:
|
|
200
|
+
return
|
|
201
|
+
|
|
202
|
+
pos = nx.spring_layout(subgraph, seed=3)
|
|
203
|
+
for node, (x, y) in pos.items():
|
|
204
|
+
x_disp, y_disp = self.ax.transData.transform((x, y))
|
|
205
|
+
dist = ((event.x - x_disp) ** 2 + (event.y - y_disp) ** 2) ** 0.5
|
|
206
|
+
if dist < 25:
|
|
207
|
+
if node in self.subgraph_nodes.get(self.current_node, set()):
|
|
208
|
+
self.show_node_detail(node, parent_path=self.current_path)
|
|
209
|
+
break
|
|
210
|
+
|
|
211
|
+
def show_node_detail(self, node, parent_path=None):
|
|
212
|
+
self.mode = GraphWorkflowVisualizer.DETAIL
|
|
213
|
+
self.current_node = node
|
|
214
|
+
|
|
215
|
+
if parent_path is None:
|
|
216
|
+
self.current_path = [node]
|
|
217
|
+
else:
|
|
218
|
+
self.current_path = parent_path + [node]
|
|
219
|
+
|
|
220
|
+
self.ax.clear()
|
|
221
|
+
|
|
222
|
+
subgraph = self.subgraphs.get(node)
|
|
223
|
+
substatus = self.substatus.get(node, {})
|
|
224
|
+
|
|
225
|
+
if subgraph:
|
|
226
|
+
pos = nx.spring_layout(subgraph, seed=3)
|
|
227
|
+
node_colors = []
|
|
228
|
+
for n in subgraph.nodes():
|
|
229
|
+
st = substatus.get(n, GraphWorkflowVisualizer.IDLE)
|
|
230
|
+
node_colors.append(GraphWorkflowVisualizer.color_map.get(st, 'gray'))
|
|
231
|
+
|
|
232
|
+
nx.draw(
|
|
233
|
+
subgraph, pos,
|
|
234
|
+
with_labels=True,
|
|
235
|
+
node_color=node_colors,
|
|
236
|
+
node_size=1200,
|
|
237
|
+
font_size=9,
|
|
238
|
+
font_weight='bold',
|
|
239
|
+
arrows=True,
|
|
240
|
+
ax=self.ax
|
|
241
|
+
)
|
|
242
|
+
self.draw_legend()
|
|
243
|
+
self.ax.set_title(f"Subgraph for: {' > '.join(self.current_path)}", fontsize=14)
|
|
244
|
+
else:
|
|
245
|
+
self.ax.set_title(f"No substeps defined for: {node}", fontsize=14)
|
|
246
|
+
|
|
247
|
+
self.canvas.draw()
|
|
248
|
+
|
|
249
|
+
if not self.detail_frame:
|
|
250
|
+
self.detail_frame = tk.Frame(self.master)
|
|
251
|
+
self.detail_frame.pack(pady=10)
|
|
252
|
+
back_btn = tk.Button(self.detail_frame, text="⬅ Back", command=self.back_one_level)
|
|
253
|
+
back_btn.pack()
|
|
254
|
+
|
|
255
|
+
def back_to_graph(self):
|
|
256
|
+
self.mode = GraphWorkflowVisualizer.GRAPH
|
|
257
|
+
self.current_node = None
|
|
258
|
+
if self.detail_frame:
|
|
259
|
+
self.detail_frame.pack_forget()
|
|
260
|
+
self.detail_frame = None
|
|
261
|
+
self.draw_graph()
|
|
262
|
+
|
|
263
|
+
def back_one_level(self):
|
|
264
|
+
if len(self.current_path) <= 1:
|
|
265
|
+
self.current_path = []
|
|
266
|
+
self.back_to_graph()
|
|
267
|
+
else:
|
|
268
|
+
self.current_path.pop() # Remove current
|
|
269
|
+
prev_node = self.current_path[-1]
|
|
270
|
+
self.show_node_detail(prev_node, parent_path=self.current_path[:-1])
|
|
271
|
+
|
|
272
|
+
def draw_legend(self):
|
|
273
|
+
legend_elements = [
|
|
274
|
+
Patch(facecolor='lightgray', label='Idle'),
|
|
275
|
+
Patch(facecolor='#1E90FF', label='Current'),
|
|
276
|
+
Patch(facecolor='limegreen', label='Done'),
|
|
277
|
+
Patch(facecolor='red', label='Fail'),
|
|
278
|
+
Patch(facecolor='gold', label='Skipped'),
|
|
279
|
+
]
|
|
280
|
+
self.ax.legend(handles=legend_elements, loc='lower right')
|
|
281
|
+
|
|
282
|
+
def on_close(self):
|
|
283
|
+
self.master.quit()
|
|
284
|
+
self.master.destroy()
|
jpipe_runner/__init__.py
ADDED
|
File without changes
|
jpipe_runner/__main__.py
ADDED
jpipe_runner/enums.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""
|
|
2
|
+
jpipe_runner.enums
|
|
3
|
+
~~~~~~~~~~~~~~~~~~
|
|
4
|
+
|
|
5
|
+
This module contains the enums of Justification Diagram.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from enum import Enum
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class ClassType(Enum):
|
|
12
|
+
"""justification / pattern / composition"""
|
|
13
|
+
JUSTIFICATION = "justification"
|
|
14
|
+
PATTERN = "pattern"
|
|
15
|
+
COMPOSITION = "composition"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class VariableType(Enum):
|
|
19
|
+
"""evidence / strategy / sub-conclusion / conclusion / @support"""
|
|
20
|
+
EVIDENCE = "evidence"
|
|
21
|
+
STRATEGY = "strategy"
|
|
22
|
+
SUB_CONCLUSION = "sub-conclusion"
|
|
23
|
+
CONCLUSION = "conclusion"
|
|
24
|
+
SUPPORT = "@support"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class StatusType(Enum):
|
|
28
|
+
"""PASS / FAIL / SKIP"""
|
|
29
|
+
PASS = "PASS"
|
|
30
|
+
FAIL = "FAIL"
|
|
31
|
+
SKIP = "SKIP"
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""
|
|
2
|
+
jpipe_runner.exceptions
|
|
3
|
+
~~~~~~~~~~~~~~~~~~~~~~~
|
|
4
|
+
|
|
5
|
+
This module contains the set of jPipe Runner's exceptions.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class RunnerException(Exception):
|
|
10
|
+
"""There was an ambiguous exception that occurred while running the runner."""
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class SyntaxException(SyntaxError, RunnerException):
|
|
14
|
+
"""A syntax error occurred."""
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class InvalidJustificationException(RunnerException):
|
|
18
|
+
"""An invalid justification error occurred."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class JustificationTraverseException(RunnerException):
|
|
22
|
+
"""A justification layered traverse error occurred."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class RuntimeException(RuntimeError, RunnerException):
|
|
26
|
+
"""A runtime error of jpipe runner occurred."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class FunctionException(RunnerException):
|
|
30
|
+
"""A justification function error occurred."""
|
|
File without changes
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
from typing import Any, Dict, List
|
|
2
|
+
|
|
3
|
+
from jpipe_runner.framework.logger import GLOBAL_LOGGER
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class RuntimeContext:
|
|
7
|
+
"""
|
|
8
|
+
RuntimeContext manages variables produced and consumed by pipeline functions.
|
|
9
|
+
|
|
10
|
+
It maintains an internal mapping (`self._vars`) from function keys (names or identifiers)
|
|
11
|
+
to dictionaries of produced and consumed variables. Each function key maps to a dict
|
|
12
|
+
where keys RuntimeContext.PRODUCE and RuntimeContext.CONSUME map to dicts of variable names
|
|
13
|
+
to their values.
|
|
14
|
+
|
|
15
|
+
Attributes:
|
|
16
|
+
_vars (dict): Main context mapping. Structure:
|
|
17
|
+
{
|
|
18
|
+
<function_key>: {
|
|
19
|
+
RuntimeContext.PRODUCE: { <var_name>: <value>, ... },
|
|
20
|
+
RuntimeContext.CONSUME: { <var_name>: <value>, ... },
|
|
21
|
+
RuntimeContext.SKIP: {
|
|
22
|
+
'value': <bool>, # True if the function should be skipped
|
|
23
|
+
'reason': <str> # Reason for skipping
|
|
24
|
+
},
|
|
25
|
+
RuntimeContext.CONTRIBUTION: {
|
|
26
|
+
RuntimeContext.POSITIVE: [<var_name>, ...], # Positive contributions
|
|
27
|
+
RuntimeContext.NEGATIVE: [<var_name>, ...], # Negative contributions
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
...
|
|
31
|
+
}
|
|
32
|
+
"""
|
|
33
|
+
PRODUCE = '_produce'
|
|
34
|
+
CONSUME = '_consume'
|
|
35
|
+
SKIP = '_skip'
|
|
36
|
+
CONTRIBUTION = '_contribution'
|
|
37
|
+
POSITIVE = '_positive'
|
|
38
|
+
NEGATIVE = '_negative'
|
|
39
|
+
|
|
40
|
+
def __init__(self):
|
|
41
|
+
"""
|
|
42
|
+
Initialize a new RuntimeContext with an empty variable mapping.
|
|
43
|
+
"""
|
|
44
|
+
self._vars = {}
|
|
45
|
+
|
|
46
|
+
def get(self, key) -> Any:
|
|
47
|
+
"""
|
|
48
|
+
Retrieve the values of a given variable across all functions that have it in their context.
|
|
49
|
+
|
|
50
|
+
Scans through all registered function entries in self._vars, and for each function
|
|
51
|
+
where `key` exists (either in its PRODUCE or CONSUME dict), collects the corresponding value.
|
|
52
|
+
|
|
53
|
+
:param key: The variable name to retrieve.
|
|
54
|
+
:type key: str
|
|
55
|
+
:return: A list of values associated with `key` across functions that have it.
|
|
56
|
+
If no function has this key, return an empty list.
|
|
57
|
+
:rtype: Any
|
|
58
|
+
"""
|
|
59
|
+
GLOBAL_LOGGER.debug(f"Context: {self._vars}")
|
|
60
|
+
for func in self._vars:
|
|
61
|
+
for decorator in (self.PRODUCE, self.CONSUME):
|
|
62
|
+
if key in self._vars[func].get(decorator, {}):
|
|
63
|
+
value = self._vars[func][decorator][key]
|
|
64
|
+
GLOBAL_LOGGER.debug(f"Retrieved variable '{key}' with value '{value}' from function '{func}'")
|
|
65
|
+
return value
|
|
66
|
+
return None
|
|
67
|
+
|
|
68
|
+
def _set(self, func, key, value, decorator):
|
|
69
|
+
"""
|
|
70
|
+
Register or update a variable in the context for a specific function.
|
|
71
|
+
|
|
72
|
+
If the function key does not exist in self._vars, initializes its entry.
|
|
73
|
+
Then, under the given decorator type (RuntimeContext.PRODUCE or CONSUME),
|
|
74
|
+
sets the variable `key` to `value`.
|
|
75
|
+
|
|
76
|
+
This is typically called by the Consume/Produce decorators to initialize
|
|
77
|
+
variables with None before actual runtime assignment.
|
|
78
|
+
|
|
79
|
+
:param func: Function name or identifier under which to register the variable.
|
|
80
|
+
:type func: str
|
|
81
|
+
:param key: Variable name to set.
|
|
82
|
+
:type key: str
|
|
83
|
+
:param value: Initial value for the variable (often None when first declared).
|
|
84
|
+
:type value: object
|
|
85
|
+
:param decorator: Either RuntimeContext.PRODUCE or RuntimeContext.CONSUME,
|
|
86
|
+
indicating whether this variable is produced or consumed.
|
|
87
|
+
:type decorator: str
|
|
88
|
+
"""
|
|
89
|
+
if func not in self._vars:
|
|
90
|
+
self._vars[func] = {}
|
|
91
|
+
if decorator not in self._vars[func]:
|
|
92
|
+
self._vars[func][decorator] = {}
|
|
93
|
+
self._vars[func][decorator][key] = value
|
|
94
|
+
GLOBAL_LOGGER.info(f"Set variable '{key}' to '{value}' in function '{func}' under decorator '{decorator}'")
|
|
95
|
+
GLOBAL_LOGGER.debug(f"Set variable '{key}' to '{value}' in function '{func}' under decorator '{decorator}'")
|
|
96
|
+
GLOBAL_LOGGER.debug(f"Updated context: {self._vars[func]}")
|
|
97
|
+
|
|
98
|
+
def set(self, key, value):
|
|
99
|
+
"""
|
|
100
|
+
Set the value of a variable in the context for the first function that has declared it.
|
|
101
|
+
|
|
102
|
+
Iterates through all function entries in self._vars; if a function context contains
|
|
103
|
+
`key` (in either its PRODUCE or CONSUME map), sets that entry to `value` and returns.
|
|
104
|
+
If multiple functions declare the same key, only the first encountered is updated.
|
|
105
|
+
|
|
106
|
+
:param key: The variable name to set.
|
|
107
|
+
:type key: str
|
|
108
|
+
:param value: The value to assign to the variable.
|
|
109
|
+
:type value: object
|
|
110
|
+
"""
|
|
111
|
+
for func in self._vars:
|
|
112
|
+
for decorator in (self.PRODUCE, self.CONSUME):
|
|
113
|
+
if key in self._vars[func].get(decorator, {}):
|
|
114
|
+
self._vars[func][decorator][key] = value
|
|
115
|
+
GLOBAL_LOGGER.debug(f"Set variable '{key}' to '{value}' in function '{func}'")
|
|
116
|
+
GLOBAL_LOGGER.debug(f"Updated context: {self._vars[func]}")
|
|
117
|
+
return
|
|
118
|
+
|
|
119
|
+
def has(self, func, key):
|
|
120
|
+
"""
|
|
121
|
+
Check if a variable exists in the context for any registered function.
|
|
122
|
+
|
|
123
|
+
Returns True if any function's context (either PRODUCE or CONSUME) contains `key`.
|
|
124
|
+
|
|
125
|
+
:param func: Function name or identifier to check.
|
|
126
|
+
:type func: Any
|
|
127
|
+
:param key: Variable name to check.
|
|
128
|
+
:type key: str
|
|
129
|
+
:return: True if the variable is declared in any function's context, False otherwise.
|
|
130
|
+
:rtype: bool
|
|
131
|
+
"""
|
|
132
|
+
if func not in self._vars:
|
|
133
|
+
return False
|
|
134
|
+
return key in self._vars[func].get(self.PRODUCE, {}) or key in self._vars[func].get(self.CONSUME, {})
|
|
135
|
+
|
|
136
|
+
def set_from_config(self, key, value, decorator=CONSUME):
|
|
137
|
+
"""
|
|
138
|
+
Set a variable in the context for the first function that has declared it.
|
|
139
|
+
|
|
140
|
+
This is a convenience method to set a variable without specifying the function name.
|
|
141
|
+
It will find the first function that has declared this variable and set its value.
|
|
142
|
+
|
|
143
|
+
:param key: The variable name to set.
|
|
144
|
+
:type key: str
|
|
145
|
+
:param value: The value to assign to the variable.
|
|
146
|
+
:type value: object
|
|
147
|
+
:param decorator: Either RuntimeContext.PRODUCE or RuntimeContext.CONSUME,
|
|
148
|
+
indicating whether this variable is produced or consumed.
|
|
149
|
+
:type decorator: str
|
|
150
|
+
"""
|
|
151
|
+
GLOBAL_LOGGER.info(f"Setting variable '{key}' to '{value}' with decorator '{decorator}'")
|
|
152
|
+
for func in self._vars:
|
|
153
|
+
if decorator not in self._vars[func]:
|
|
154
|
+
continue
|
|
155
|
+
if key in self._vars[func][decorator]:
|
|
156
|
+
self._vars[func][decorator][key] = value
|
|
157
|
+
GLOBAL_LOGGER.debug(f"Set variable '{key}' to '{value}' in function '{func}'")
|
|
158
|
+
GLOBAL_LOGGER.debug(f"Updated context: {self._vars[func]}")
|
|
159
|
+
|
|
160
|
+
def set_skip(self, func, value: bool, reason: str = "Skipped by condition"):
|
|
161
|
+
"""
|
|
162
|
+
Set the skip status for a function in the context.
|
|
163
|
+
|
|
164
|
+
This method allows marking a function as skipped based on a condition.
|
|
165
|
+
It updates the context to reflect whether the function should be skipped.
|
|
166
|
+
|
|
167
|
+
:param func: The function name or identifier to set the skip status for.
|
|
168
|
+
:type func: str
|
|
169
|
+
:param value: True if the function should be skipped, False otherwise.
|
|
170
|
+
:type value: bool
|
|
171
|
+
:param reason: The reason for skipping the function.
|
|
172
|
+
:type reason: str
|
|
173
|
+
"""
|
|
174
|
+
if func not in self._vars:
|
|
175
|
+
self._vars[func] = {}
|
|
176
|
+
self._vars[func][self.SKIP] = {
|
|
177
|
+
'value': value,
|
|
178
|
+
'reason': reason
|
|
179
|
+
}
|
|
180
|
+
GLOBAL_LOGGER.debug(f"Set skip status for function '{func}' to {value} with reason: {reason}")
|
|
181
|
+
|
|
182
|
+
def set_contribution(self, func, contribution_type: str, variables: list[str]):
|
|
183
|
+
"""
|
|
184
|
+
Set the contribution type for a function in the context.
|
|
185
|
+
|
|
186
|
+
This method allows marking a function's contribution as either positive or negative.
|
|
187
|
+
It updates the context to reflect the contribution type and associated variables.
|
|
188
|
+
|
|
189
|
+
:param func: The function name or identifier to set the contribution for.
|
|
190
|
+
:type func: str
|
|
191
|
+
:param contribution_type: Either RuntimeContext.POSITIVE or RuntimeContext.NEGATIVE,
|
|
192
|
+
indicating the type of contribution.
|
|
193
|
+
:type contribution_type: str
|
|
194
|
+
:param variables: A list of variable names that contribute to this type.
|
|
195
|
+
:type variables: list[str]
|
|
196
|
+
"""
|
|
197
|
+
if func not in self._vars:
|
|
198
|
+
self._vars[func] = {}
|
|
199
|
+
if self.CONTRIBUTION not in self._vars[func]:
|
|
200
|
+
self._vars[func][self.CONTRIBUTION] = {
|
|
201
|
+
self.POSITIVE: [],
|
|
202
|
+
self.NEGATIVE: []
|
|
203
|
+
}
|
|
204
|
+
self._vars[func][self.CONTRIBUTION][contribution_type].extend(variables)
|
|
205
|
+
GLOBAL_LOGGER.debug(f"Set {contribution_type} contribution for function '{func}' with variables: {variables}")
|
|
206
|
+
|
|
207
|
+
def get_contributions(self, func: str) -> Dict[str, List[str]]:
|
|
208
|
+
"""
|
|
209
|
+
Retrieves positive and negative contributions for a given function.
|
|
210
|
+
|
|
211
|
+
Args:
|
|
212
|
+
func (str): Function name.
|
|
213
|
+
|
|
214
|
+
Returns:
|
|
215
|
+
dict: {'_positive': [...], '_negative': [...]} — lists may be empty.
|
|
216
|
+
"""
|
|
217
|
+
return self._vars.get(func, {}).get(RuntimeContext.CONTRIBUTION, {
|
|
218
|
+
self.POSITIVE: [],
|
|
219
|
+
self.NEGATIVE: []
|
|
220
|
+
})
|
|
221
|
+
|
|
222
|
+
def __repr__(self):
|
|
223
|
+
"""
|
|
224
|
+
String representation of the RuntimeContext, showing all registered variables.
|
|
225
|
+
|
|
226
|
+
:return: A string representation of the context's variable mapping.
|
|
227
|
+
:rtype: str
|
|
228
|
+
"""
|
|
229
|
+
return f"RuntimeContext(vars={self._vars})"
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
ctx = RuntimeContext()
|
|
File without changes
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
from functools import wraps
|
|
2
|
+
from typing import Optional, List
|
|
3
|
+
|
|
4
|
+
from jpipe_runner.framework.context import ctx, RuntimeContext
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def contribution(positive: Optional[List[str]] = None, negative: Optional[List[str]] = None):
|
|
8
|
+
"""
|
|
9
|
+
Decorator to declare contributions of an evidence or strategy to a goal.
|
|
10
|
+
|
|
11
|
+
:param positive: List of variable names that contribute positively to the goal.
|
|
12
|
+
:param negative: List of variable names that contribute negatively to the goal.
|
|
13
|
+
:return: A function decorator.
|
|
14
|
+
"""
|
|
15
|
+
positive = positive or []
|
|
16
|
+
negative = negative or []
|
|
17
|
+
|
|
18
|
+
def decorator(func):
|
|
19
|
+
ctx.set_contribution(func.__name__, RuntimeContext.NEGATIVE, negative)
|
|
20
|
+
ctx.set_contribution(func.__name__, RuntimeContext.POSITIVE, positive)
|
|
21
|
+
@wraps(func)
|
|
22
|
+
def wrapper(*args, **kwargs):
|
|
23
|
+
return func(*args, **kwargs)
|
|
24
|
+
return wrapper
|
|
25
|
+
return decorator
|