pychemstation 0.5.3.dev1__py3-none-any.whl → 0.5.5__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.
@@ -1,5 +1,4 @@
1
1
  """
2
2
  .. include:: README.md
3
3
  """
4
- from .comm import CommunicationController
5
4
  from .hplc import HPLCController
@@ -86,17 +86,18 @@ class CommunicationController:
86
86
 
87
87
  def set_status(self):
88
88
  """Updates current status of HPLC machine"""
89
- self._most_recent_hplc_status = self.get_status()[0]
89
+ self._most_recent_hplc_status = self.get_status()
90
90
 
91
- def check_if_running(self, data_path: str) -> bool:
91
+ def check_if_running(self) -> bool:
92
92
  """Checks if HPLC machine is in an available state, meaning a state that data is not being written.
93
93
 
94
94
  :return: whether the HPLC machine is in a safe state to retrieve data back."""
95
95
  self.set_status()
96
- file_exists = os.path.exists(data_path)
97
96
  hplc_avail = isinstance(self._most_recent_hplc_status, HPLCAvailStatus)
98
- done_writing_data = hplc_avail and file_exists
99
- return done_writing_data
97
+ time.sleep(30)
98
+ self.set_status()
99
+ hplc_actually_avail = isinstance(self._most_recent_hplc_status, HPLCAvailStatus)
100
+ return hplc_avail and hplc_actually_avail
100
101
 
101
102
  def _send(self, cmd: str, cmd_no: int, num_attempts=5) -> None:
102
103
  """Low-level execution primitive. Sends a command string to HPLC.
@@ -170,6 +171,9 @@ class CommunicationController:
170
171
  cmd_to_send: str = cmd.value if isinstance(cmd, Command) else cmd
171
172
  self.cmd_no += 1
172
173
  self._send(cmd_to_send, self.cmd_no)
174
+ f = open("out.txt", "a")
175
+ f.write(cmd_to_send + "\n")
176
+ f.close()
173
177
 
174
178
  def receive(self) -> Result[Response, str]:
175
179
  """Returns messages received in reply file.
@@ -0,0 +1,4 @@
1
+ from .method import MethodController
2
+ from .sequence import SequenceController
3
+ from .table_controller import TableController
4
+ from .comm import CommunicationController
@@ -0,0 +1,206 @@
1
+ """
2
+ Module to provide API for the communication with Agilent HPLC systems.
3
+
4
+ HPLCController sends commands to Chemstation software via a command file.
5
+ Answers are received via reply file. On the Chemstation side, a custom
6
+ Macro monitors the command file, executes commands and writes to the reply file.
7
+ Each command is given a number (cmd_no) to keep track of which commands have
8
+ been processed.
9
+
10
+ Authors: Alexander Hammer, Hessam Mehr, Lucy Hao
11
+ """
12
+
13
+ import os
14
+ import time
15
+
16
+ from result import Result, Ok, Err
17
+
18
+ from ...utils.macro import *
19
+
20
+
21
+ class CommunicationController:
22
+ """
23
+ Class that communicates with Agilent using Macros
24
+ """
25
+
26
+ # maximum command number
27
+ MAX_CMD_NO = 255
28
+
29
+ def __init__(
30
+ self,
31
+ comm_dir: str,
32
+ cmd_file: str = "cmd",
33
+ reply_file: str = "reply",
34
+ ):
35
+ """
36
+ :param comm_dir:
37
+ :param cmd_file: Name of command file
38
+ :param reply_file: Name of reply file
39
+ """
40
+ if os.path.isdir(comm_dir):
41
+ self.cmd_file = os.path.join(comm_dir, cmd_file)
42
+ self.reply_file = os.path.join(comm_dir, reply_file)
43
+ self.cmd_no = 0
44
+ else:
45
+ raise FileNotFoundError(f"comm_dir: {comm_dir} not found.")
46
+ self._most_recent_hplc_status = None
47
+
48
+ # Create files for Chemstation to communicate with Python
49
+ open(self.cmd_file, "a").close()
50
+ open(self.reply_file, "a").close()
51
+
52
+ self.reset_cmd_counter()
53
+
54
+ def get_num_val(self, cmd: str) -> Union[int, float, Err]:
55
+ self.send(Command.GET_NUM_VAL_CMD.value.format(cmd=cmd))
56
+ res = self.receive()
57
+ if res.is_ok():
58
+ return res.ok_value.num_response
59
+ else:
60
+ raise RuntimeError("Failed to get number.")
61
+
62
+ def get_text_val(self, cmd: str) -> str:
63
+ self.send(Command.GET_TEXT_VAL_CMD.value.format(cmd=cmd))
64
+ res = self.receive()
65
+ if res.is_ok():
66
+ return res.ok_value.string_response
67
+ else:
68
+ raise RuntimeError("Failed to get string")
69
+
70
+ def get_status(self) -> Union[HPLCRunningStatus, HPLCAvailStatus, HPLCErrorStatus]:
71
+ """Get device status(es).
72
+
73
+ :return: list of ChemStation's current status
74
+ """
75
+ self.send(Command.GET_STATUS_CMD)
76
+ time.sleep(1)
77
+
78
+ try:
79
+ parsed_response = self.receive().value.string_response
80
+ self._most_recent_hplc_status = str_to_status(parsed_response)
81
+ return self._most_recent_hplc_status
82
+ except IOError:
83
+ return HPLCErrorStatus.NORESPONSE
84
+ except IndexError:
85
+ return HPLCErrorStatus.MALFORMED
86
+
87
+ def set_status(self):
88
+ """Updates current status of HPLC machine"""
89
+ self._most_recent_hplc_status = self.get_status()
90
+
91
+ def check_if_running(self) -> bool:
92
+ """Checks if HPLC machine is in an available state, meaning a state that data is not being written.
93
+
94
+ :return: whether the HPLC machine is in a safe state to retrieve data back."""
95
+ self.set_status()
96
+ hplc_avail = isinstance(self._most_recent_hplc_status, HPLCAvailStatus)
97
+ time.sleep(30)
98
+ self.set_status()
99
+ hplc_actually_avail = isinstance(self._most_recent_hplc_status, HPLCAvailStatus)
100
+ return hplc_avail and hplc_actually_avail
101
+
102
+ def _send(self, cmd: str, cmd_no: int, num_attempts=5) -> None:
103
+ """Low-level execution primitive. Sends a command string to HPLC.
104
+
105
+ :param cmd: string to be sent to HPLC
106
+ :param cmd_no: Command number
107
+ :param num_attempts: Number of attempts to send the command before raising exception.
108
+ :raises IOError: Could not write to command file.
109
+ """
110
+ err = None
111
+ for _ in range(num_attempts):
112
+ time.sleep(1)
113
+ try:
114
+ with open(self.cmd_file, "w", encoding="utf8") as cmd_file:
115
+ cmd_file.write(f"{cmd_no} {cmd}")
116
+ except IOError as e:
117
+ err = e
118
+ continue
119
+ else:
120
+ return
121
+ else:
122
+ raise IOError(f"Failed to send command #{cmd_no}: {cmd}.") from err
123
+
124
+ def _receive(self, cmd_no: int, num_attempts=100) -> Result[str, str]:
125
+ """Low-level execution primitive. Recives a response from HPLC.
126
+
127
+ :param cmd_no: Command number
128
+ :param num_attempts: Number of retries to open reply file
129
+ :raises IOError: Could not read reply file.
130
+ :return: Potential ChemStation response
131
+ """
132
+ err = None
133
+ for _ in range(num_attempts):
134
+ time.sleep(1)
135
+
136
+ try:
137
+ with open(self.reply_file, "r", encoding="utf_16") as reply_file:
138
+ response = reply_file.read()
139
+ except OSError as e:
140
+ err = e
141
+ continue
142
+
143
+ try:
144
+ first_line = response.splitlines()[0]
145
+ response_no = int(first_line.split()[0])
146
+ except IndexError as e:
147
+ err = e
148
+ continue
149
+
150
+ # check that response corresponds to sent command
151
+ if response_no == cmd_no:
152
+ return Ok(response)
153
+ else:
154
+ continue
155
+ else:
156
+ return Err(f"Failed to receive reply to command #{cmd_no} due to {err}.")
157
+
158
+ def sleepy_send(self, cmd: Union[Command, str]):
159
+ self.send("Sleep 0.1")
160
+ self.send(cmd)
161
+ self.send("Sleep 0.1")
162
+
163
+ def send(self, cmd: Union[Command, str]):
164
+ """Sends a command to Chemstation.
165
+
166
+ :param cmd: Command to be sent to HPLC
167
+ """
168
+ if self.cmd_no == self.MAX_CMD_NO:
169
+ self.reset_cmd_counter()
170
+
171
+ cmd_to_send: str = cmd.value if isinstance(cmd, Command) else cmd
172
+ self.cmd_no += 1
173
+ self._send(cmd_to_send, self.cmd_no)
174
+ f = open("out.txt", "a")
175
+ f.write(cmd_to_send + "\n")
176
+ f.close()
177
+
178
+ def receive(self) -> Result[Response, str]:
179
+ """Returns messages received in reply file.
180
+
181
+ :return: ChemStation response
182
+ """
183
+ num_response_prefix = "Numerical Responses:"
184
+ str_response_prefix = "String Responses:"
185
+ possible_response = self._receive(self.cmd_no)
186
+ if Ok(possible_response):
187
+ lines = possible_response.value.splitlines()
188
+ for line in lines:
189
+ if str_response_prefix in line and num_response_prefix in line:
190
+ string_responses_dirty, _, numerical_responses = line.partition(num_response_prefix)
191
+ _, _, string_responses = string_responses_dirty.partition(str_response_prefix)
192
+ return Ok(Response(string_response=string_responses.strip(),
193
+ num_response=float(numerical_responses.strip())))
194
+ return Err(f"Could not retrieve HPLC response")
195
+ else:
196
+ return Err(f"Could not establish response to HPLC: {possible_response}")
197
+
198
+ def reset_cmd_counter(self):
199
+ """Resets the command counter."""
200
+ self._send(Command.RESET_COUNTER_CMD.value, cmd_no=self.MAX_CMD_NO + 1)
201
+ self._receive(cmd_no=self.MAX_CMD_NO + 1)
202
+ self.cmd_no = 0
203
+
204
+ def stop_macro(self):
205
+ """Stops Macro execution. Connection will be lost."""
206
+ self.send(Command.STOP_MACRO_CMD)
@@ -0,0 +1,274 @@
1
+ import os
2
+ import time
3
+ from typing import Optional
4
+
5
+ from xsdata.formats.dataclass.parsers import XmlParser
6
+
7
+ from ...control.controllers.table_controller import TableController
8
+ from ...control.controllers.comm import CommunicationController
9
+ from ...generated import PumpMethod, DadMethod, SolventElement
10
+ from ...utils.chromatogram import TIME_FORMAT, AgilentChannelChromatogramData
11
+ from ...utils.macro import Command
12
+ from ...utils.method_types import PType, TimeTableEntry, Param, MethodTimetable, HPLCMethodParams
13
+ from ...utils.table_types import RegisterFlag, TableOperation, Table
14
+
15
+
16
+ class MethodController(TableController):
17
+ """
18
+ Class containing method related logic
19
+ """
20
+
21
+ def __init__(self, controller: CommunicationController, src: str, data_dir: str, table: Table):
22
+ super().__init__(controller, src, data_dir, table)
23
+
24
+ def get_method_params(self) -> HPLCMethodParams:
25
+ return HPLCMethodParams(organic_modifier=self.controller.get_num_val(
26
+ cmd=TableOperation.GET_OBJ_HDR_VAL.value.format(
27
+ register=self.table.register,
28
+ register_flag=RegisterFlag.SOLVENT_B_COMPOSITION
29
+ )
30
+ ),
31
+ flow=self.controller.get_num_val(
32
+ cmd=TableOperation.GET_OBJ_HDR_VAL.value.format(
33
+ register=self.table.register,
34
+ register_flag=RegisterFlag.FLOW
35
+ )
36
+ ),
37
+ maximum_run_time=self.controller.get_num_val(
38
+ cmd=TableOperation.GET_OBJ_HDR_VAL.value.format(
39
+ register=self.table.register,
40
+ register_flag=RegisterFlag.MAX_TIME
41
+ )
42
+ ),
43
+ )
44
+
45
+ def get_row(self, row: int) -> TimeTableEntry:
46
+ return TimeTableEntry(start_time=self.get_num(row, RegisterFlag.TIME),
47
+ organic_modifer=self.get_num(row, RegisterFlag.TIMETABLE_SOLVENT_B_COMPOSITION),
48
+ flow=None)
49
+
50
+ def load(self) -> MethodTimetable:
51
+ rows = self.get_num_rows()
52
+ if rows.is_ok():
53
+ timetable_rows = [self.get_row(r + 1) for r in range(int(rows.ok_value.num_response))]
54
+ return MethodTimetable(
55
+ first_row=self.get_method_params(),
56
+ subsequent_rows=timetable_rows)
57
+ else:
58
+ raise RuntimeError(rows.err_value)
59
+
60
+ def current_method(self, method_name: str):
61
+ """
62
+ Checks if a given method is already loaded into Chemstation. Method name does not need the ".M" extension.
63
+
64
+ :param method_name: a Chemstation method
65
+ :return: True if method is already loaded
66
+ """
67
+ self.send(Command.GET_METHOD_CMD)
68
+ parsed_response = self.receive()
69
+ return method_name in parsed_response
70
+
71
+ def switch(self, method_name: str):
72
+ """
73
+ Allows the user to switch between pre-programmed methods. No need to append '.M'
74
+ to the end of the method name. For example. for the method named 'General-Poroshell.M',
75
+ only 'General-Poroshell' is needed.
76
+
77
+ :param method_name: any available method in Chemstation method directory
78
+ :raise IndexError: Response did not have expected format. Try again.
79
+ :raise AssertionError: The desired method is not selected. Try again.
80
+ """
81
+ self.send(Command.SWITCH_METHOD_CMD.value.format(method_dir=self.src,
82
+ method_name=method_name))
83
+
84
+ time.sleep(2)
85
+ self.send(Command.GET_METHOD_CMD)
86
+ time.sleep(2)
87
+ res = self.receive()
88
+ if res.is_ok():
89
+ parsed_response = res.ok_value.string_response
90
+ assert parsed_response == f"{method_name}.M", "Switching Methods failed."
91
+
92
+ def load_from_disk(self, method_name: str) -> MethodTimetable:
93
+ """
94
+ Retrieve method details of an existing method. Don't need to append ".M" to the end. This assumes the
95
+ organic modifier is in Channel B and that Channel A contains the aq layer. Additionally, assumes
96
+ only two solvents are being used.
97
+
98
+ :param method_name: name of method to load details of
99
+ :raises FileNotFoundError: Method does not exist
100
+ :return: method details
101
+ """
102
+ method_folder = f"{method_name}.M"
103
+ method_path = os.path.join(self.src, method_folder, "AgilentPumpDriver1.RapidControl.MethodXML.xml")
104
+ dad_path = os.path.join(self.src, method_folder, "Agilent1200erDadDriver1.RapidControl.MethodXML.xml")
105
+
106
+ if os.path.exists(os.path.join(self.src, f"{method_name}.M")):
107
+ parser = XmlParser()
108
+ method = parser.parse(method_path, PumpMethod)
109
+ dad = parser.parse(dad_path, DadMethod)
110
+
111
+ organic_modifier: Optional[SolventElement] = None
112
+ aq_modifier: Optional[SolventElement] = None
113
+
114
+ if len(method.solvent_composition.solvent_element) == 2:
115
+ for solvent in method.solvent_composition.solvent_element:
116
+ if solvent.channel == "Channel_A":
117
+ aq_modifier = solvent
118
+ elif solvent.channel == "Channel_B":
119
+ organic_modifier = solvent
120
+
121
+ return MethodTimetable(
122
+ first_row=HPLCMethodParams(
123
+ organic_modifier=organic_modifier.percentage,
124
+ flow=method.flow,
125
+ maximum_run_time=method.stop_time,
126
+ temperature=-1),
127
+ subsequent_rows=[
128
+ TimeTableEntry(
129
+ start_time=tte.time,
130
+ organic_modifer=tte.percent_b,
131
+ flow=method.flow
132
+ ) for tte in method.timetable.timetable_entry
133
+ ],
134
+ dad_wavelengthes=dad.signals.signal,
135
+ organic_modifier=organic_modifier,
136
+ modifier_a=aq_modifier
137
+ )
138
+ else:
139
+ raise FileNotFoundError
140
+
141
+ def edit(self, updated_method: MethodTimetable, save: bool):
142
+ """Updated the currently loaded method in ChemStation with provided values.
143
+
144
+ :param updated_method: the method with updated values, to be sent to Chemstation to modify the currently loaded method.
145
+ """
146
+ initial_organic_modifier: Param = Param(val=updated_method.first_row.organic_modifier,
147
+ chemstation_key=RegisterFlag.SOLVENT_B_COMPOSITION,
148
+ ptype=PType.NUM)
149
+ max_time: Param = Param(val=updated_method.first_row.maximum_run_time,
150
+ chemstation_key=RegisterFlag.MAX_TIME,
151
+ ptype=PType.NUM)
152
+ flow: Param = Param(val=updated_method.first_row.flow,
153
+ chemstation_key=RegisterFlag.FLOW,
154
+ ptype=PType.NUM)
155
+
156
+ # Method settings required for all runs
157
+ self.delete_table()
158
+ self._update_param(initial_organic_modifier)
159
+ self._update_param(flow)
160
+ self._update_param(Param(val="Set",
161
+ chemstation_key=RegisterFlag.STOPTIME_MODE,
162
+ ptype=PType.STR))
163
+ self._update_param(max_time)
164
+ self._update_param(Param(val="Off",
165
+ chemstation_key=RegisterFlag.POSTIME_MODE,
166
+ ptype=PType.STR))
167
+
168
+ self.send("DownloadRCMethod PMP1")
169
+
170
+ self._update_method_timetable(updated_method.subsequent_rows)
171
+
172
+ if save:
173
+ self.send(Command.SAVE_METHOD_CMD.value.format(
174
+ commit_msg=f"saved method at {str(time.time())}"
175
+ ))
176
+
177
+ def _update_method_timetable(self, timetable_rows: list[TimeTableEntry]):
178
+ self.sleepy_send('Local Rows')
179
+ self.get_num_rows()
180
+
181
+ self.sleepy_send('DelTab RCPMP1Method[1], "Timetable"')
182
+ res = self.get_num_rows()
183
+ while not res.is_err():
184
+ self.sleepy_send('DelTab RCPMP1Method[1], "Timetable"')
185
+ res = self.get_num_rows()
186
+
187
+ self.sleepy_send('NewTab RCPMP1Method[1], "Timetable"')
188
+ self.get_num_rows()
189
+
190
+ for i, row in enumerate(timetable_rows):
191
+ if i == 0:
192
+ self.send('Sleep 1')
193
+ self.sleepy_send('InsTabRow RCPMP1Method[1], "Timetable"')
194
+ self.send('Sleep 1')
195
+
196
+ self.sleepy_send('NewColText RCPMP1Method[1], "Timetable", "Function", "SolventComposition"')
197
+ self.sleepy_send(f'NewColVal RCPMP1Method[1], "Timetable", "Time", {row.start_time}')
198
+ self.sleepy_send(
199
+ f'NewColVal RCPMP1Method[1], "Timetable", "SolventCompositionPumpChannel2_Percentage", {row.organic_modifer}')
200
+
201
+ self.send('Sleep 1')
202
+ self.sleepy_send("DownloadRCMethod PMP1")
203
+ self.send('Sleep 1')
204
+ else:
205
+ self.sleepy_send('InsTabRow RCPMP1Method[1], "Timetable"')
206
+ self.get_num_rows()
207
+
208
+ self.sleepy_send(
209
+ f'SetTabText RCPMP1Method[1], "Timetable", Rows, "Function", "SolventComposition"')
210
+ self.sleepy_send(
211
+ f'SetTabVal RCPMP1Method[1], "Timetable", Rows, "Time", {row.start_time}')
212
+ self.sleepy_send(
213
+ f'SetTabVal RCPMP1Method[1], "Timetable", Rows, "SolventCompositionPumpChannel2_Percentage", {row.organic_modifer}')
214
+
215
+ self.send("Sleep 1")
216
+ self.sleepy_send("DownloadRCMethod PMP1")
217
+ self.send("Sleep 1")
218
+ self.get_num_rows()
219
+
220
+ def _update_param(self, method_param: Param):
221
+ """Change a method parameter, changes what is visibly seen in Chemstation GUI.
222
+ (changes the first row in the timetable)
223
+
224
+ :param method_param: a parameter to update for currently loaded method.
225
+ """
226
+ register = self.table.register
227
+ setting_command = TableOperation.UPDATE_OBJ_HDR_VAL if method_param.ptype == PType.NUM else TableOperation.UPDATE_OBJ_HDR_TEXT
228
+ if isinstance(method_param.chemstation_key, list):
229
+ for register_flag in method_param.chemstation_key:
230
+ self.send(setting_command.value.format(register=register,
231
+ register_flag=register_flag,
232
+ val=method_param.val))
233
+ else:
234
+ self.send(setting_command.value.format(register=register,
235
+ register_flag=method_param.chemstation_key,
236
+ val=method_param.val))
237
+ time.sleep(2)
238
+
239
+ def stop(self):
240
+ """
241
+ Stops the method run. A dialog window will pop up and manual intervention may be required.\
242
+ """
243
+ self.send(Command.STOP_METHOD_CMD)
244
+
245
+ def run(self, experiment_name: str):
246
+ """
247
+ This is the preferred method to trigger a run.
248
+ Starts the currently selected method, storing data
249
+ under the <data_dir>/<experiment_name>.D folder.
250
+ The <experiment_name> will be appended with a timestamp in the '%Y-%m-%d-%H-%M' format.
251
+ Device must be ready.
252
+
253
+ :param experiment_name: Name of the experiment
254
+ """
255
+ timestamp = time.strftime(TIME_FORMAT)
256
+ self.send(Command.RUN_METHOD_CMD.value.format(data_dir=self.data_dir,
257
+ experiment_name=experiment_name,
258
+ timestamp=timestamp))
259
+
260
+ if self.check_hplc_is_running():
261
+ folder_name = f"{experiment_name}_{timestamp}.D"
262
+ self.data_files.append(os.path.join(self.data_dir, folder_name))
263
+
264
+ run_completed = self.check_hplc_done_running()
265
+
266
+ if not run_completed.is_ok():
267
+ raise RuntimeError("Run did not complete as expected")
268
+
269
+ def retrieve_recent_data_files(self) -> str:
270
+ return self.data_files[-1]
271
+
272
+ def get_data(self) -> AgilentChannelChromatogramData:
273
+ self.get_spectrum(self.data_files[-1])
274
+ return AgilentChannelChromatogramData(**self.spectra)