sapiopycommons 2025.2.11a427__py3-none-any.whl → 2025.2.11a430__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.

Potentially problematic release.


This version of sapiopycommons might be problematic. Click here for more details.

@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: sapiopycommons
3
- Version: 2025.2.11a427
3
+ Version: 2025.2.11a430
4
4
  Summary: Official Sapio Python API Utilities Package
5
5
  Project-URL: Homepage, https://github.com/sapiosciences
6
6
  Author-email: Jonathan Steck <jsteck@sapiosciences.com>, Yechen Qiao <yqiao@sapiosciences.com>
@@ -14,8 +14,6 @@ sapiopycommons/datatype/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG
14
14
  sapiopycommons/datatype/attachment_util.py,sha256=_l2swuP8noIGAl4bwzBUEhr6YlN_OVZl3-gi1XqFHYA,3364
15
15
  sapiopycommons/datatype/data_fields.py,sha256=C6HpqtEuF0KsxhlBUprfyv1XguaXql3EYWVbh8y-IFU,4064
16
16
  sapiopycommons/datatype/pseudo_data_types.py,sha256=6TG7aJxgmUZ8FQkWBcgmbK5oy7AFFNtKOPpi1w1OOYA,27657
17
- sapiopycommons/elain/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
18
- sapiopycommons/elain/tool_of_tools.py,sha256=yMuoaoo5OobIdSVX4M4FynVOIr27mpsHOqtL7x3gRJI,26877
19
17
  sapiopycommons/eln/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
20
18
  sapiopycommons/eln/experiment_handler.py,sha256=8hmR7sawDo9K6iBwB44QSoxlH1M91inor7dfuXQ4LKs,69323
21
19
  sapiopycommons/eln/experiment_report_util.py,sha256=EA2Iq8gW17bSEI6lPoHYQQ-fDvG4O28RWOoTPXpOlUw,36640
@@ -58,7 +56,7 @@ sapiopycommons/webhook/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3
58
56
  sapiopycommons/webhook/webhook_context.py,sha256=D793uLsb1691SalaPnBUk3rOSxn_hYLhdvkaIxjNXss,1909
59
57
  sapiopycommons/webhook/webhook_handlers.py,sha256=L0HetSm43NvA5KyW3xbLpGFh2DbAaeZJVtXIEl2fvV8,39689
60
58
  sapiopycommons/webhook/webservice_handlers.py,sha256=Y5dHx_UFWFuSqaoPL6Re-fsKYRuxvCWZ8bj6KSZ3jfM,14285
61
- sapiopycommons-2025.2.11a427.dist-info/METADATA,sha256=4nMCVSCItqvtbS5TRc8ySKFNhLhYzopB0bIZmX2_RAY,3143
62
- sapiopycommons-2025.2.11a427.dist-info/WHEEL,sha256=C2FUgwZgiLbznR-k0b_5k3Ai_1aASOXDss3lzCUsUug,87
63
- sapiopycommons-2025.2.11a427.dist-info/licenses/LICENSE,sha256=HyVuytGSiAUQ6ErWBHTqt1iSGHhLmlC8fO7jTCuR8dU,16725
64
- sapiopycommons-2025.2.11a427.dist-info/RECORD,,
59
+ sapiopycommons-2025.2.11a430.dist-info/METADATA,sha256=3Vp8E2-pJqz7PiRb3fIZA0ROjzsFKNFXKJm-rZYuUK0,3143
60
+ sapiopycommons-2025.2.11a430.dist-info/WHEEL,sha256=C2FUgwZgiLbznR-k0b_5k3Ai_1aASOXDss3lzCUsUug,87
61
+ sapiopycommons-2025.2.11a430.dist-info/licenses/LICENSE,sha256=HyVuytGSiAUQ6ErWBHTqt1iSGHhLmlC8fO7jTCuR8dU,16725
62
+ sapiopycommons-2025.2.11a430.dist-info/RECORD,,
File without changes
@@ -1,535 +0,0 @@
1
- import base64
2
- import math
3
- from typing import Final, Mapping, Any
4
-
5
- from pandas import DataFrame
6
- from sapiopylib.rest.DataRecordManagerService import DataRecordManager
7
- from sapiopylib.rest.ELNService import ElnManager
8
- from sapiopylib.rest.User import SapioUser
9
- from sapiopylib.rest.pojo.DataRecord import DataRecord
10
- from sapiopylib.rest.pojo.chartdata.DashboardDefinition import GaugeChartDefinition
11
- from sapiopylib.rest.pojo.chartdata.DashboardEnums import ChartGroupingType, ChartOperationType
12
- from sapiopylib.rest.pojo.chartdata.DashboardSeries import GaugeChartSeries
13
- from sapiopylib.rest.pojo.datatype.FieldDefinition import AbstractVeloxFieldDefinition, FieldType
14
- from sapiopylib.rest.pojo.eln.ElnExperiment import ElnExperiment
15
- from sapiopylib.rest.pojo.eln.ExperimentEntry import ExperimentEntry
16
- from sapiopylib.rest.pojo.eln.ExperimentEntryCriteria import ElnEntryCriteria, ElnFormEntryUpdateCriteria, \
17
- ElnDashboardEntryUpdateCriteria, ElnTextEntryUpdateCriteria
18
- from sapiopylib.rest.pojo.eln.SapioELNEnums import ElnEntryType, ElnBaseDataType
19
- from sapiopylib.rest.pojo.eln.eln_headings import ElnExperimentTabAddCriteria, ElnExperimentTab
20
- from sapiopylib.rest.pojo.eln.field_set import ElnFieldSetInfo
21
- from sapiopylib.rest.utils.ProtocolUtils import ELNStepFactory
22
- from sapiopylib.rest.utils.Protocols import ElnEntryStep, ElnExperimentProtocol
23
-
24
- from sapiopycommons.callbacks.field_builder import FieldBuilder
25
- from sapiopycommons.general.aliases import AliasUtil, SapioRecord
26
- from sapiopycommons.general.exceptions import SapioException
27
- from sapiopycommons.general.time_util import TimeUtil
28
-
29
- CREDENTIALS_HEADER: Final[str] = "SAPIO_APP_API_KEY"
30
- API_URL_HEADER: Final[str] = "SAPIO_APP_API_URL"
31
- EXP_ID_HEADER: Final[str] = "EXPERIMENT_ID"
32
- TAB_PREFIX_HEADER: Final[str] = "TAB_PREFIX"
33
-
34
-
35
- # FR-47422: Create utility methods to assist the tool of tools.
36
- def create_tot_headers(url: str, username: str, password: str, experiment_id: int, tab_prefix: str) \
37
- -> tuple[str, dict[str, str]]:
38
- """
39
- Create the headers to be passed to a tool of tools endpoint.
40
-
41
- :param url: The webservice URL of the system to make the changes in.
42
- :param username: The username of the user making the changes.
43
- :param password: The password of the user making the changes.
44
- :param experiment_id: The ID of the experiment to make the changes in.
45
- :param tab_prefix: The prefix to use for the tab name that will be created by the tool.
46
- :return: The encoded credentials and the headers to be passed to the endpoint.
47
- """
48
- # Combine the credentials into the format "username:password"
49
- credentials: str = f"{username}:{password}"
50
- # Encode the credentials to bytes, then encode them using base64,
51
- # and finally convert the result back into a string.
52
- encoded_credentials: str = base64.b64encode(credentials.encode('utf-8')).decode('utf-8')
53
- headers: dict[str, str] = {
54
- CREDENTIALS_HEADER: f"Basic {encoded_credentials}",
55
- API_URL_HEADER: url,
56
- EXP_ID_HEADER: str(experiment_id),
57
- TAB_PREFIX_HEADER: tab_prefix
58
- }
59
- return encoded_credentials, headers
60
-
61
-
62
- def create_user_from_tot_headers(headers: Mapping[str, str]) -> SapioUser:
63
- """
64
- Create a SapioUser object from the headers passed to a tool of tools endpoint.
65
-
66
- :param headers: The headers that were passed to the endpoint.
67
- :return: A SapioUser object created from the headers that can be used to communicate with the Sapio server.
68
- """
69
- headers: dict[str, str] = format_tot_headers(headers)
70
- credentials = (base64.b64decode(headers[CREDENTIALS_HEADER.lower()].removeprefix("Basic "))
71
- .decode("utf-8").split(":", 1))
72
- return SapioUser(headers[API_URL_HEADER.lower()], username=credentials[0], password=credentials[1])
73
-
74
-
75
- def format_tot_headers(headers: Mapping[str, str]) -> dict[str, str]:
76
- """
77
- Format the headers passed to a tool of tools endpoint to guarantee that the keys are lowercase.
78
-
79
- :param headers: The headers that were passed to the endpoint.
80
- :return: The headers with all keys converted to lowercase. (Conflicting keys will cause one to overwrite the other,
81
- but there should not be any conflicting keys in the headers passed to a tool of tools endpoint.)
82
- """
83
- return {k.lower(): v for k, v in headers.items()}
84
-
85
-
86
- def create_experiment_details_from_data_frame(user: SapioUser,
87
- exp_id: int,
88
- entry_name: str,
89
- tab: ElnExperimentTab,
90
- df: DataFrame) -> ExperimentEntry | None:
91
- """
92
- Create an experiment detail entry from a DataFrame.
93
-
94
- :param user: The user to send the request from.
95
- :param exp_id: The ID of the experiment to create the entry in.
96
- :param entry_name: The name of the entry.
97
- :param tab: The tab that the entry should be added to.
98
- :param df: The DataFrame to create the entry from.
99
- :return: The created entry object.
100
- """
101
- json_list: list[dict[str, Any]] = []
102
- for _, row in df.iterrows():
103
- json_list.append(row.to_dict())
104
- return create_experiment_details_from_json(user, exp_id, entry_name, tab, json_list)
105
-
106
-
107
- def create_experiment_details_from_json(user: SapioUser,
108
- exp_id: int,
109
- entry_name: str,
110
- tab: ElnExperimentTab,
111
- json_list: list[dict[str, Any]]) -> ExperimentEntry | None:
112
- """
113
- Create an experiment detail entry from a list of JSON dictionaries.
114
-
115
- :param user: The user to send the request from.
116
- :param exp_id: The ID of the experiment to create the entry in.
117
- :param entry_name: The name of the entry.
118
- :param tab: The tab that the entry should be added to.
119
- :param json_list: The list of JSON dictionaries to create the entry from. Each dictionary is expected to have the
120
- same keys.
121
- :return: The created entry object.
122
- """
123
- if not json_list:
124
- return None
125
-
126
- # Determine which fields in the JSON can be used to create field definitions.
127
- fb = FieldBuilder()
128
- fields: list[AbstractVeloxFieldDefinition] = []
129
- fields_by_name: dict[str, AbstractVeloxFieldDefinition] = {}
130
- for key, value in json_list[0].items():
131
- field_name: str = key.replace(" ", "_")
132
- if isinstance(value, str):
133
- field = fb.string_field(field_name, display_name=key)
134
- fields.append(field)
135
- fields_by_name[key] = field
136
- elif isinstance(value, (int, float)):
137
- field = fb.double_field(field_name, display_name=key, precision=3)
138
- fields.append(field)
139
- fields_by_name[key] = field
140
-
141
- # Extract the valid field values from the JSON.
142
- field_maps: list[dict[str, Any]] = []
143
- for json_dict in json_list:
144
- field_map: dict[str, Any] = {}
145
- for key, field in fields_by_name.items():
146
- # Watch out for NaN values or other special values.
147
- val: Any = json_dict.get(key)
148
- if (field.data_field_type == FieldType.DOUBLE
149
- and (not isinstance(val, (int, float))) or (isinstance(val, float) and math.isnan(val))):
150
- val = None
151
- field_map[field.data_field_name] = val
152
- field_maps.append(field_map)
153
-
154
- detail_entry = ElnEntryCriteria(ElnEntryType.Table, entry_name,
155
- ElnBaseDataType.EXPERIMENT_DETAIL.data_type_name,
156
- tab_next_entry_order(user, exp_id, tab),
157
- notebook_experiment_tab_id=tab.tab_id,
158
- field_definition_list=fields)
159
- entry = ElnManager(user).add_experiment_entry(exp_id, detail_entry)
160
- DataRecordManager(user).add_data_records_with_data(entry.data_type_name, field_maps)
161
-
162
-
163
- def tab_next_entry_order(user: SapioUser, exp_id: int, tab: ElnExperimentTab) -> int:
164
- max_order: int = 0
165
- for step in ElnExperimentProtocol(ElnExperiment(exp_id, "", 0), user).get_sorted_step_list():
166
- if step.eln_entry.notebook_experiment_tab_id == tab.tab_id and step.eln_entry.order > max_order:
167
- max_order = step.eln_entry.order
168
- return max_order + 1
169
-
170
-
171
- def set_text_entry(timestamp: str, description: str, text_entry: ExperimentEntry, exp_id: int, user: SapioUser) -> None:
172
- """
173
- Set the text of a text entry.
174
-
175
- :param timestamp: The timestamp to display at the top of the text entry.
176
- :param description: The description to display in the text entry.
177
- :param text_entry: The text entry to set the text of.
178
- :param exp_id: The ID of the experiment that the text entry is in.
179
- :param user: The user to send the request from.
180
- """
181
- description: str = f"""<p><span style="color: rgb(35, 111, 161); font-size: 12pt; font-weight:500;">{timestamp}</span>
182
- <br><span style="font-size: 15pt;">{description}</span></p>"""
183
- protocol = ElnExperimentProtocol(ElnExperiment(exp_id, "", 0), user)
184
- step = ElnEntryStep(protocol, text_entry)
185
- text_record: DataRecord = step.get_records()[0]
186
- text_record.set_field_value(ElnBaseDataType.get_text_entry_data_field_name(), description)
187
- DataRecordManager(user).commit_data_records([text_record])
188
-
189
-
190
- def add_to_text_entry(description: str, text_entry: ExperimentEntry, exp_id: int, user: SapioUser) -> None:
191
- """
192
- Add to the text of a text entry.
193
-
194
- :param description: The text to add to the text entry.
195
- :param text_entry: The text entry to add the text to.
196
- :param exp_id: The ID of the experiment that the text entry is in.
197
- :param user: The user to send the request from.
198
- """
199
- protocol = ElnExperimentProtocol(ElnExperiment(exp_id, "", 0), user)
200
- step = ElnEntryStep(protocol, text_entry)
201
- text_record: DataRecord = step.get_records()[0]
202
- update: str = text_record.get_field_value(ElnBaseDataType.get_text_entry_data_field_name())
203
- update += f"""<p style="padding-top: 10px;"><span style="font-size: 15pt;">{description}</span></p>"""
204
- text_record.set_field_value(ElnBaseDataType.get_text_entry_data_field_name(), update)
205
- DataRecordManager(user).commit_data_records([text_record])
206
-
207
-
208
- class ToolOfToolsHelper:
209
- """
210
- A class with helper methods utilized by the Tool of Tools for the creation and updating of experiment tabs that
211
- track a tool's progress and results.
212
- """
213
- # Contextual info.
214
- user: SapioUser
215
- tab_prefix: str
216
- exp_id: int
217
- _protocol: ElnExperimentProtocol
218
-
219
- # Tool info.
220
- name: str
221
- description: str
222
- results_data_type: str | None
223
-
224
- # Managers.
225
- eln_man: ElnManager
226
- dr_man: DataRecordManager
227
-
228
- # Stuff created by this helper.
229
- _initialized: bool
230
- """Whether a tab for this tool has been initialized."""
231
- tab: ElnExperimentTab
232
- """The tab that contains the tool's entries."""
233
- description_entry: ElnEntryStep | None
234
- """The text entry that displays the description of the tool."""
235
- description_record: DataRecord | None
236
- """The record that stores the description of the tool."""
237
- progress_entry: ElnEntryStep | None
238
- """A hidden entry for tracking the progress of the tool."""
239
- progress_record: DataRecord | None
240
- """The record that stores the progress of the tool."""
241
- progress_gauge_entry: ElnEntryStep | None
242
- """A chart entry that displays the progress of the tool using the hidden progress entry."""
243
- results_entry: ElnEntryStep | None
244
- """An entry for displaying the results of the tool. If None, the tool does not produce result records."""
245
-
246
- def __init__(self, headers: Mapping[str, str], name: str, description: str,
247
- results_data_type: str | None = None):
248
- """
249
- :param headers: The headers that were passed to the endpoint.
250
- :param name: The name of the tool.
251
- :param description: A description of the tool.
252
- :param results_data_type: The data type name for the results of the tool. If None, the tool does not produce
253
- result records.
254
- """
255
- headers: dict[str, str] = format_tot_headers(headers)
256
- self.user = create_user_from_tot_headers(headers)
257
- self.exp_id = int(headers[EXP_ID_HEADER.lower()])
258
- self.tab_prefix = headers[TAB_PREFIX_HEADER.lower()]
259
- # The experiment name and record ID aren't necessary to know.
260
- self._protocol = ElnExperimentProtocol(ElnExperiment(self.exp_id, "", 0), self.user)
261
-
262
- self.name = name
263
- self.description = description
264
- self.results_data_type = results_data_type
265
-
266
- self.eln_man = ElnManager(self.user)
267
- self.dr_man = DataRecordManager(self.user)
268
-
269
- self._initialized = False
270
-
271
- def initialize_tab(self) -> ElnExperimentTab:
272
- if self._initialized:
273
- return self.tab
274
- self._initialized = True
275
-
276
- # Determine if a previous call to this endpoint already created a tab for these results. If so, grab the entries
277
- # from that tab.
278
- tab_name: str = f"{self.tab_prefix.strip()} {self.name.strip()}"
279
- tabs: list[ElnExperimentTab] = self.eln_man.get_tabs_for_experiment(self.exp_id)
280
- for tab in tabs:
281
- if tab.tab_name != tab_name:
282
- continue
283
-
284
- for entry in self._protocol.get_sorted_step_list():
285
- if entry.eln_entry.notebook_experiment_tab_id != tab.tab_id:
286
- continue
287
-
288
- dt: str = entry.get_data_type_names()[0] if entry.get_data_type_names() else None
289
- if (entry.eln_entry.entry_type == ElnEntryType.Form
290
- and ElnBaseDataType.get_base_type(dt) == ElnBaseDataType.EXPERIMENT_DETAIL
291
- and not hasattr(self, "progress_entry")):
292
- self.progress_entry = entry
293
- self.progress_record = entry.get_records()[0]
294
- elif (entry.eln_entry.entry_type == ElnEntryType.Dashboard
295
- and not hasattr(self, "progress_gauge_entry")):
296
- self.progress_gauge_entry = entry
297
- elif (entry.eln_entry.entry_type == ElnEntryType.Text
298
- and not hasattr(self, "description_entry")):
299
- self.description_entry = entry
300
- self.description_record = entry.get_records()[0]
301
- elif (entry.eln_entry.entry_type == ElnEntryType.Table
302
- and dt == self.results_data_type
303
- and not hasattr(self, "results_entry")):
304
- self.results_entry = entry
305
-
306
- if not hasattr(self, "progress_entry"):
307
- self.progress_entry = None
308
- self.progress_record = None
309
- if not hasattr(self, "progress_gauge_entry"):
310
- self.progress_gauge_entry = None
311
- if not hasattr(self, "description_entry"):
312
- self.description_entry = None
313
- self.description_record = None
314
- if not hasattr(self, "results_entry"):
315
- self.results_entry = None
316
-
317
- self.tab = tab
318
- return tab
319
-
320
- # Otherwise, create the tab for the tool progress and results.
321
- tab_crit = ElnExperimentTabAddCriteria(tab_name, [])
322
- tab: ElnExperimentTab = self.eln_man.add_tab_for_experiment(self.exp_id, tab_crit)
323
- self.tab = tab
324
-
325
- # Create a hidden entry for tracking the progress of the tool.
326
- field_sets: list[ElnFieldSetInfo] = self.eln_man.get_field_set_info_list()
327
- progress_field_set: list[ElnFieldSetInfo] = [x for x in field_sets if
328
- x.field_set_name == "Tool of Tools Progress"]
329
- if not progress_field_set:
330
- raise SapioException("Unable to locate the field set for the Tool of Tools progress.")
331
- progress_entry_crit = ElnEntryCriteria(ElnEntryType.Form, f"ELaiN: {self.name} Progress",
332
- ElnBaseDataType.EXPERIMENT_DETAIL.data_type_name, 1,
333
- notebook_experiment_tab_id=tab.tab_id,
334
- enb_field_set_id=progress_field_set[0].field_set_id)
335
- progress_entry = ElnEntryStep(self._protocol,
336
- self.eln_man.add_experiment_entry(self.exp_id, progress_entry_crit))
337
- self.progress_entry = progress_entry
338
- self.progress_record = progress_entry.get_records()[0]
339
-
340
- # Hide the progress entry.
341
- form_update_crit = ElnFormEntryUpdateCriteria()
342
- form_update_crit.is_hidden = True
343
- self.eln_man.update_experiment_entry(self.exp_id, self.progress_entry.get_id(), form_update_crit)
344
-
345
- # Create the text entry that displays the description of the tool. Include the timestamp of when the
346
- # tool started and format the description so that the text isn't too small to read.
347
- # TODO: Get the UTC offset in seconds from the header once that's being sent.
348
- now: str = TimeUtil.now_in_format("%Y-%m-%d %H:%M:%S UTC", "UTC")
349
- description: str = f"""<p><span style="color: rgb(35, 111, 161); font-size: 12pt; font-weight:500;">{now}</span>
350
- <br><span style="font-size: 15pt;">{self.description}</span></p>"""
351
- text_entry: ElnEntryStep = ELNStepFactory.create_text_entry(self._protocol, description)
352
- self.description_entry = text_entry
353
- self.description_record = text_entry.get_records()[0]
354
-
355
- # Shrink the text entry by one column.
356
- text_update_crit = ElnTextEntryUpdateCriteria()
357
- text_update_crit.column_span = 2
358
- self.eln_man.update_experiment_entry(self.exp_id, self.description_entry.get_id(), text_update_crit)
359
-
360
- # Create a gauge entry to display the progress.
361
- gauge_entry: ElnEntryStep = self._create_gauge_chart(self._protocol, progress_entry,
362
- f"{self.name} Progress", "Progress", "StatusMsg")
363
- self.progress_gauge_entry = gauge_entry
364
-
365
- # Make sure the gauge entry isn't too big and stick it to the right of the text entry.
366
- dash_update_crit = ElnDashboardEntryUpdateCriteria()
367
- dash_update_crit.entry_height = 250
368
- dash_update_crit.column_span = 2
369
- dash_update_crit.column_order = 2
370
- self.eln_man.update_experiment_entry(self.exp_id, self.progress_gauge_entry.get_id(), dash_update_crit)
371
-
372
- # TODO: Bulk updates aren't working?
373
- # self.eln_man.update_experiment_entries(self.exp_id, {
374
- # self.progress_entry.get_id(): form_update_crit,
375
- # self.progress_gauge_entry.get_id(): dash_update_crit,
376
- # self.description_entry.get_id(): text_update_crit
377
- # })
378
-
379
- # Create a results entry if this tool produces result records.
380
- if self.results_data_type:
381
- results_entry = ELNStepFactory.create_table_step(self._protocol, f"{self.name} Results",
382
- self.results_data_type)
383
- self.results_entry = results_entry
384
- else:
385
- self.results_entry = None
386
-
387
- return tab
388
-
389
- def add_to_description(self, description: str) -> None:
390
- """
391
- Add to the description entry of the tool.
392
-
393
- :param description: The text to add to the description.
394
- """
395
- if not self._initialized:
396
- raise SapioException("The tab for this tool has not been initialized.")
397
- field: str = ElnBaseDataType.get_text_entry_data_field_name()
398
- update: str = self.description_record.get_field_value(field)
399
- update += f"""<p style="padding-top: 10px;"><span style="font-size: 15pt;">{description}</span></p>"""
400
- self.description_record.set_field_value(field, update)
401
- self.dr_man.commit_data_records([self.description_record])
402
-
403
- def update_progress(self, progress: float, status_msg: str | None = None) -> None:
404
- """
405
- Updates the progress of the tool.
406
-
407
- :param progress: A value between 0 and 100 representing the progress of the tool.
408
- :param status_msg: A status message to display to the user alongside the progress gauge.
409
- """
410
- if not self._initialized:
411
- raise SapioException("The tab for this tool has not been initialized.")
412
- self.progress_record.set_field_value("Progress", progress)
413
- self.progress_record.set_field_value("StatusMsg", status_msg)
414
- self.dr_man.commit_data_records([self.progress_record])
415
-
416
- def add_results(self, results: list[SapioRecord]) -> None:
417
- """
418
- Add the results of the tool to the results entry.
419
-
420
- :param results: The result records to add to the results entry.
421
- """
422
- if not self._initialized:
423
- raise SapioException("The tab for this tool has not been initialized.")
424
- self.results_entry.add_records(AliasUtil.to_data_records(results))
425
-
426
- def add_results_bar_chart(self, x_axis: str, y_axis: str) -> ExperimentEntry:
427
- """
428
- Create a bar chart entry for the results of the tool.
429
-
430
- :param x_axis: The data field to use for the x-axis of the chart.
431
- :param y_axis: The data field to use for the y-axis of the chart.
432
- :return: The newly created chart entry.
433
- """
434
- if not self._initialized:
435
- raise SapioException("The tab for this tool has not been initialized.")
436
- if not self.results_entry:
437
- raise SapioException("This tool does not produce result records.")
438
- return ELNStepFactory.create_bar_chart_step(self._protocol, self.results_entry, f"{self.name} Results Chart",
439
- x_axis, y_axis)[0].eln_entry
440
-
441
- def add_attachment_entry(self, file_name: str, file_data: str | bytes, entry_name: str,
442
- tab: ElnExperimentTab | None = None) -> ExperimentEntry:
443
- """
444
- Add a new attachment entry to the experiment with the provided attachment data.
445
-
446
- :param file_name: The name of the attachment.
447
- :param file_data: The data of the attachment. This can be a string or bytes.
448
- :param entry_name: Name of the attachment entry to create in the experiment.
449
- :param tab: The tab where the attachment will be added. If not provided, the tab initialized by this helper
450
- will be used.
451
- :return: The created entry object.
452
- """
453
- # Check if the tab has been initialized or a tab has been provided.
454
- if not self._initialized and tab is None:
455
- raise SapioException("The tab for this tool has not been initialized. Either initialize a tab for this "
456
- "tool or provide the tab to this function to add the attachment entry to.")
457
- tab_id: int = self.tab.tab_id if tab is None else tab.tab_id
458
-
459
- # Encode the file contents in base64.
460
- if isinstance(file_data, str):
461
- file_data: bytes = file_data.encode("utf-8")
462
- base64_encoded: str = base64.b64encode(file_data).decode("utf-8")
463
-
464
- # Crete an attachment entry with the provided data.
465
- attachment_entry = self.eln_man.add_experiment_entry(
466
- self.exp_id,
467
- ElnEntryCriteria(ElnEntryType.Attachment, entry_name, "Attachment", order=2,
468
- notebook_experiment_tab_id=tab_id, attachment_file_name=file_name,
469
- attachment_data_base64=base64_encoded)
470
- )
471
-
472
- # Return the entry object for further use.
473
- return attachment_entry
474
-
475
- def add_attachment_entry_from_file_system(self, file_path: str, entry_name: str,
476
- tab: ElnExperimentTab | None = None) -> ExperimentEntry:
477
- """
478
- Add a new attachment entry to the experiment with the provided file path to a file in the file system.
479
-
480
- :param file_path: The path to a file in the system to attach to the experiment.
481
- :param entry_name: Name of the attachment entry to create in the experiment.
482
- :param tab: The tab where the attachment will be added. If not provided, the tab initialized by this helper
483
- will be used.
484
- :return: The created entry object.
485
- """
486
- # Check if the tab has been initialized or a tab has been provided.
487
- # This is redundant with the same check in the add_attachment_entry function, but it's duplicated here as to
488
- # not read the provided file and then find out we can't do anything with it anyway.
489
- if not self._initialized and tab is None:
490
- raise SapioException("The tab for this tool has not been initialized. Either initialize a tab for this "
491
- "tool or provide the tab to this function to add the attachment entry to.")
492
-
493
- with open(file_path, 'rb') as f:
494
- file_contents: bytes = f.read()
495
- return self.add_attachment_entry(file_path, file_contents, entry_name, tab)
496
-
497
- # TODO: Remove this once pylib's gauge chart definition is up to date.
498
- @staticmethod
499
- def _create_gauge_chart(protocol: ElnExperimentProtocol, data_source_step: ElnEntryStep, step_name: str,
500
- field_name: str, status_field: str, group_by_field_name: str = "DataRecordName") \
501
- -> ElnEntryStep:
502
- """
503
- Create a gauge chart step in the experiment protocol.
504
- """
505
- if not data_source_step.get_data_type_names():
506
- raise ValueError("The data source step did not declare a data type name.")
507
- data_type_name: str = data_source_step.get_data_type_names()[0]
508
- series = GaugeChartSeries(data_type_name, field_name)
509
- series.operation_type = ChartOperationType.VALUE
510
- chart = _GaugeChartDefinition()
511
- chart.main_data_type_name = data_type_name
512
- chart.status_field = status_field
513
- chart.minimum_value = 0.
514
- chart.maximum_value = 100.
515
- chart.series_list = [series]
516
- chart.grouping_type = ChartGroupingType.GROUP_BY_FIELD
517
- chart.grouping_type_data_type_name = data_type_name
518
- chart.grouping_type_data_field_name = group_by_field_name
519
- dashboard, step = ELNStepFactory._create_dashboard_step_from_chart(chart, data_source_step, protocol, step_name,
520
- None)
521
- protocol.invalidate()
522
- return step
523
-
524
-
525
- # TODO: Using this to set the new status field setting.
526
- class _GaugeChartDefinition(GaugeChartDefinition):
527
- status_field: str
528
-
529
- def to_json(self) -> dict[str, Any]:
530
- result = super().to_json()
531
- result["statusValueField"] = {
532
- "dataTypeName": self.main_data_type_name,
533
- "dataFieldName": self.status_field
534
- }
535
- return result