pychemstation 0.4.7.dev2__py3-none-any.whl → 0.5.0__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,5 @@
1
1
  """
2
- Module to provide API for the remote control of the Agilent HPLC systems.
2
+ Module to provide API for the communication with Agilent HPLC systems.
3
3
 
4
4
  HPLCController sends commands to Chemstation software via a command file.
5
5
  Answers are received via reply file. On the Chemstation side, a custom
@@ -10,38 +10,29 @@ been processed.
10
10
  Authors: Alexander Hammer, Hessam Mehr, Lucy Hao
11
11
  """
12
12
 
13
- import logging
14
13
  import os
15
14
  import time
16
15
 
17
- import polling
18
-
19
- from ..utils.chromatogram import AgilentHPLCChromatogram
20
16
  from ..utils.constants import MAX_CMD_NO
21
17
  from ..utils.macro import *
22
18
  from ..utils.method_types import *
23
19
 
24
20
 
25
- class HPLCController:
21
+ class CommunicationController:
26
22
  """
27
- Class to control Agilent HPLC systems via Chemstation Macros.
23
+ Class that communicates with Agilent using Macros
28
24
  """
29
25
 
30
26
  def __init__(
31
27
  self,
32
28
  comm_dir: str,
33
- data_dir: str,
34
29
  cmd_file: str = "cmd",
35
30
  reply_file: str = "reply",
36
31
  ):
37
- """Initialize HPLC controller. The `hplc_talk.mac` macro file must be loaded in the Chemstation software.
38
- `comm_dir` must match the file path in the macro file.
39
-
40
- :param comm_dir: Name of directory for communication, where ChemStation will read and write from. Can be any existing directory.
41
- :param data_dir: Name of directory that ChemStation saves run data. Must be accessible by ChemStation.
32
+ """
33
+ :param comm_dir:
42
34
  :param cmd_file: Name of command file
43
35
  :param reply_file: Name of reply file
44
- :raises FileNotFoundError: If either `data_dir`, `method_dir` or `comm_dir` is not a valid directory.
45
36
  """
46
37
  if os.path.isdir(comm_dir):
47
38
  self.cmd_file = os.path.join(comm_dir, cmd_file)
@@ -51,75 +42,47 @@ class HPLCController:
51
42
  raise FileNotFoundError(f"comm_dir: {comm_dir} not found.")
52
43
  self._most_recent_hplc_status = None
53
44
 
54
- if os.path.isdir(data_dir):
55
- self.data_dir = data_dir
56
- else:
57
- raise FileNotFoundError(f"data_dir: {data_dir} not found.")
58
-
59
- self.spectra = {
60
- "A": AgilentHPLCChromatogram(self.data_dir),
61
- "B": AgilentHPLCChromatogram(self.data_dir),
62
- "C": AgilentHPLCChromatogram(self.data_dir),
63
- "D": AgilentHPLCChromatogram(self.data_dir),
64
- }
65
-
66
- self.data_files: list[str] = []
67
- self.internal_variables: list[dict[str, str]] = []
68
-
69
45
  # Create files for Chemstation to communicate with Python
70
46
  open(self.cmd_file, "a").close()
71
47
  open(self.reply_file, "a").close()
72
48
 
73
- self.logger = logging.getLogger("hplc_logger")
74
- self.logger.addHandler(logging.NullHandler())
75
-
76
49
  self.reset_cmd_counter()
77
50
 
78
- self.logger.info("HPLC Controller initialized.")
51
+ def get_status(self) -> list[Union[HPLCRunningStatus, HPLCAvailStatus, HPLCErrorStatus]]:
52
+ """Get device status(es).
53
+
54
+ :return: list of ChemStation's current status
55
+ """
56
+ self.send(Command.GET_STATUS_CMD)
57
+ time.sleep(1)
58
+
59
+ try:
60
+ parsed_response = self.receive().splitlines()[1].split()[1:]
61
+ recieved_status = [str_to_status(res) for res in parsed_response]
62
+ self._most_recent_hplc_status = recieved_status[0]
63
+ return recieved_status
64
+ except IOError:
65
+ return [HPLCErrorStatus.NORESPONSE]
66
+ except IndexError:
67
+ return [HPLCErrorStatus.MALFORMED]
79
68
 
80
- def _set_status(self):
69
+ def set_status(self):
81
70
  """Updates current status of HPLC machine"""
82
- self._most_recent_hplc_status = self.status()[0]
71
+ self._most_recent_hplc_status = self.get_status()[0]
83
72
 
84
- def _check_data_status(self) -> bool:
73
+ def _check_data_status(self, data_path: str) -> bool:
85
74
  """Checks if HPLC machine is in an available state, meaning a state that data is not being written.
86
75
 
87
76
  :return: whether the HPLC machine is in a safe state to retrieve data back."""
88
77
  old_status = self._most_recent_hplc_status
89
- self._set_status()
90
- file_exists = os.path.exists(self.data_files[-1]) if len(self.data_files) > 0 else False
78
+ self.set_status()
79
+ file_exists = os.path.exists(data_path)
91
80
  done_writing_data = isinstance(self._most_recent_hplc_status,
92
81
  HPLCAvailStatus) and old_status != self._most_recent_hplc_status and file_exists
93
82
  return done_writing_data
94
83
 
95
- def check_hplc_ready_with_data(self) -> bool:
96
- """Checks if ChemStation has finished writing data and can be read back.
97
-
98
- :param method: if you are running a method and want to read back data, the timeout period will be adjusted to be longer than the method's runtime
99
-
100
- :return: Return True if data can be read back, else False.
101
- """
102
- self._set_status()
103
-
104
- timeout = 10 * 60
105
- hplc_run_done = polling.poll(
106
- lambda: self._check_data_status(),
107
- timeout=timeout,
108
- step=30
109
- )
110
-
111
- return hplc_run_done
112
-
113
- def get_spectrum(self):
114
- """ Load last chromatogram for any channel in spectra dictionary."""
115
- last_file = self.data_files[-1] if len(self.data_files) > 0 else None
116
-
117
- if last_file is None:
118
- raise IndexError
119
-
120
- for channel, spec in self.controller.spectra.items():
121
- spec.load_spectrum(data_path=last_file, channel=channel)
122
- self.logger.info("%s chromatogram loaded.", channel)
84
+ def check_data(self, data_path: str) -> bool:
85
+ return self._check_data_status(data_path)
123
86
 
124
87
  def _send(self, cmd: str, cmd_no: int, num_attempts=5) -> None:
125
88
  """Low-level execution primitive. Sends a command string to HPLC.
@@ -137,10 +100,8 @@ class HPLCController:
137
100
  cmd_file.write(f"{cmd_no} {cmd}")
138
101
  except IOError as e:
139
102
  err = e
140
- self.logger.warning("Failed to send command; trying again.")
141
103
  continue
142
104
  else:
143
- self.logger.info("Sent command #%d: %s.", cmd_no, cmd)
144
105
  return
145
106
  else:
146
107
  raise IOError(f"Failed to send command #{cmd_no}: {cmd}.") from err
@@ -162,7 +123,6 @@ class HPLCController:
162
123
  response = reply_file.read()
163
124
  except OSError as e:
164
125
  err = e
165
- self.logger.warning("Failed to read from reply file; trying again.")
166
126
  continue
167
127
 
168
128
  try:
@@ -170,19 +130,12 @@ class HPLCController:
170
130
  response_no = int(first_line.split()[0])
171
131
  except IndexError as e:
172
132
  err = e
173
- self.logger.warning("Malformed response %s; trying again.", response)
174
133
  continue
175
134
 
176
135
  # check that response corresponds to sent command
177
136
  if response_no == cmd_no:
178
- self.logger.info("Reply: \n%s", response)
179
137
  return response
180
138
  else:
181
- self.logger.warning(
182
- "Response #: %d != command #: %d; trying again.",
183
- response_no,
184
- cmd_no,
185
- )
186
139
  continue
187
140
  else:
188
141
  raise IOError(f"Failed to receive reply to command #{cmd_no}.") from err
@@ -217,60 +170,6 @@ class HPLCController:
217
170
  self._receive(cmd_no=MAX_CMD_NO + 1)
218
171
  self.cmd_no = 0
219
172
 
220
- self.logger.debug("Reset command counter")
221
-
222
- def sleep(self, seconds: int):
223
- """Tells the HPLC to wait for a specified number of seconds.
224
-
225
- :param seconds: number of seconds to wait
226
- """
227
- self.send(Command.SLEEP_CMD.value.format(seconds=seconds))
228
- self.logger.debug("Sleep command sent.")
229
-
230
- def standby(self):
231
- """Switches all modules in standby mode. All lamps and pumps are switched off."""
232
- self.send(Command.STANDBY_CMD)
233
- self.logger.debug("Standby command sent.")
234
-
235
- def preprun(self):
236
- """ Prepares all modules for run. All lamps and pumps are switched on."""
237
- self.send(Command.PREPRUN_CMD)
238
- self.logger.debug("PrepRun command sent.")
239
-
240
- def status(self) -> list[Union[HPLCRunningStatus, HPLCAvailStatus, HPLCErrorStatus]]:
241
- """Get device status(es).
242
-
243
- :return: list of ChemStation's current status
244
- """
245
- self.send(Command.GET_STATUS_CMD)
246
- time.sleep(1)
247
-
248
- try:
249
- parsed_response = self.receive().splitlines()[1].split()[1:]
250
- except IOError:
251
- return [HPLCErrorStatus.NORESPONSE]
252
- except IndexError:
253
- return [HPLCErrorStatus.MALFORMED]
254
- recieved_status = [str_to_status(res) for res in parsed_response]
255
- self._most_recent_hplc_status = recieved_status[0]
256
- return recieved_status
257
-
258
173
  def stop_macro(self):
259
174
  """Stops Macro execution. Connection will be lost."""
260
175
  self.send(Command.STOP_MACRO_CMD)
261
-
262
- def lamp_on(self):
263
- """Turns the UV lamp on."""
264
- self.send(Command.LAMP_ON_CMD)
265
-
266
- def lamp_off(self):
267
- """Turns the UV lamp off."""
268
- self.send(Command.LAMP_OFF_CMD)
269
-
270
- def pump_on(self):
271
- """Turns on the pump on."""
272
- self.send(Command.PUMP_ON_CMD)
273
-
274
- def pump_off(self):
275
- """Turns the pump off."""
276
- self.send(Command.PUMP_OFF_CMD)