pychemstation 0.8.3__py3-none-any.whl → 0.10.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.
Files changed (55) hide show
  1. pychemstation/analysis/__init__.py +4 -0
  2. pychemstation/analysis/base_spectrum.py +9 -9
  3. pychemstation/analysis/process_report.py +13 -7
  4. pychemstation/analysis/utils.py +1 -3
  5. pychemstation/control/__init__.py +4 -0
  6. pychemstation/control/comm.py +206 -0
  7. pychemstation/control/controllers/__init__.py +6 -0
  8. pychemstation/control/controllers/comm.py +12 -5
  9. pychemstation/control/controllers/devices/column.py +12 -0
  10. pychemstation/control/controllers/devices/dad.py +0 -0
  11. pychemstation/control/controllers/devices/device.py +10 -7
  12. pychemstation/control/controllers/devices/injector.py +18 -84
  13. pychemstation/control/controllers/devices/pump.py +43 -0
  14. pychemstation/control/controllers/method.py +338 -0
  15. pychemstation/control/controllers/sequence.py +190 -0
  16. pychemstation/control/controllers/table_controller.py +266 -0
  17. pychemstation/control/controllers/tables/method.py +35 -13
  18. pychemstation/control/controllers/tables/sequence.py +46 -37
  19. pychemstation/control/controllers/tables/table.py +46 -30
  20. pychemstation/control/hplc.py +27 -11
  21. pychemstation/control/table/__init__.py +3 -0
  22. pychemstation/control/table/method.py +274 -0
  23. pychemstation/control/table/sequence.py +210 -0
  24. pychemstation/control/table/table_controller.py +201 -0
  25. pychemstation/generated/dad_method.py +1 -1
  26. pychemstation/generated/pump_method.py +1 -1
  27. pychemstation/utils/chromatogram.py +2 -5
  28. pychemstation/utils/injector_types.py +1 -1
  29. pychemstation/utils/macro.py +3 -3
  30. pychemstation/utils/method_types.py +2 -2
  31. pychemstation/utils/num_utils.py +65 -0
  32. pychemstation/utils/parsing.py +1 -0
  33. pychemstation/utils/sequence_types.py +3 -3
  34. pychemstation/utils/spec_utils.py +304 -0
  35. {pychemstation-0.8.3.dist-info → pychemstation-0.10.0.dist-info}/METADATA +19 -8
  36. pychemstation-0.10.0.dist-info/RECORD +62 -0
  37. {pychemstation-0.8.3.dist-info → pychemstation-0.10.0.dist-info}/WHEEL +2 -1
  38. pychemstation-0.10.0.dist-info/top_level.txt +2 -0
  39. tests/__init__.py +0 -0
  40. tests/constants.py +134 -0
  41. tests/test_comb.py +136 -0
  42. tests/test_comm.py +65 -0
  43. tests/test_inj.py +39 -0
  44. tests/test_method.py +99 -0
  45. tests/test_nightly.py +80 -0
  46. tests/test_offline_stable.py +69 -0
  47. tests/test_online_stable.py +275 -0
  48. tests/test_proc_rep.py +52 -0
  49. tests/test_runs_stable.py +225 -0
  50. tests/test_sequence.py +125 -0
  51. tests/test_stable.py +276 -0
  52. pychemstation/control/README.md +0 -124
  53. pychemstation/control/controllers/README.md +0 -1
  54. pychemstation-0.8.3.dist-info/RECORD +0 -37
  55. {pychemstation-0.8.3.dist-info → pychemstation-0.10.0.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,210 @@
1
+ from typing import Any
2
+
3
+ from copy import deepcopy
4
+
5
+ import os
6
+ import time
7
+
8
+ from .table_controller import TableController
9
+ from ...control import CommunicationController
10
+ from ...utils.chromatogram import SEQUENCE_TIME_FORMAT, AgilentHPLCChromatogram
11
+ from ...utils.macro import Command
12
+ from ...utils.sequence_types import SequenceTable, SequenceEntry, SequenceDataFiles, InjectionSource, SampleType
13
+ from ...utils.table_types import TableOperation, RegisterFlag, Table
14
+ from ...utils.tray_types import TenColumn
15
+
16
+
17
+ class SequenceController(TableController):
18
+ """
19
+ Class containing sequence related logic
20
+ """
21
+
22
+ def __init__(self, controller: CommunicationController, src: str, data_dir: str, table: Table, method_dir: str):
23
+ self.method_dir = method_dir
24
+ super().__init__(controller, src, data_dir, table)
25
+
26
+ def load(self) -> SequenceTable:
27
+ rows = self.get_num_rows()
28
+ self.send(Command.GET_SEQUENCE_CMD)
29
+ seq_name = self.receive()
30
+
31
+ if rows.is_ok() and seq_name.is_ok():
32
+ return SequenceTable(
33
+ name=seq_name.ok_value.string_response.partition(".S")[0],
34
+ rows=[self.get_row(r + 1) for r in range(int(rows.ok_value.num_response))])
35
+ raise RuntimeError(rows.err_value)
36
+
37
+ def get_row(self, row: int) -> SequenceEntry:
38
+ sample_name = self.get_text(row, RegisterFlag.NAME)
39
+ vial_location = int(self.get_num(row, RegisterFlag.VIAL_LOCATION))
40
+ method = self.get_text(row, RegisterFlag.METHOD)
41
+ num_inj = int(self.get_num(row, RegisterFlag.NUM_INJ))
42
+ inj_vol = int(self.get_text(row, RegisterFlag.INJ_VOL))
43
+ inj_source = InjectionSource(self.get_text(row, RegisterFlag.INJ_SOR))
44
+ sample_type = SampleType(self.get_num(row, RegisterFlag.SAMPLE_TYPE))
45
+ return SequenceEntry(sample_name=sample_name,
46
+ vial_location=vial_location,
47
+ method=None if len(method) == 0 else method,
48
+ num_inj=num_inj,
49
+ inj_vol=inj_vol,
50
+ inj_source=inj_source,
51
+ sample_type=sample_type, )
52
+
53
+ def switch(self, seq_name: str):
54
+ """
55
+ Switch to the specified sequence. The sequence name does not need the '.S' extension.
56
+
57
+ :param seq_name: The name of the sequence file
58
+ """
59
+ self.send(f'_SeqFile$ = "{seq_name}.S"')
60
+ self.send(f'_SeqPath$ = "{self.src}"')
61
+ self.send(Command.SWITCH_SEQUENCE_CMD)
62
+ time.sleep(2)
63
+ self.send(Command.GET_SEQUENCE_CMD)
64
+ time.sleep(2)
65
+ parsed_response = self.receive().value.string_response
66
+
67
+ assert parsed_response == f"{seq_name}.S", "Switching sequence failed."
68
+
69
+ def edit(self, sequence_table: SequenceTable):
70
+ """
71
+ Updates the currently loaded sequence table with the provided table. This method will delete the existing sequence table and remake it.
72
+ If you would only like to edit a single row of a sequence table, use `edit_sequence_table_row` instead.
73
+
74
+ :param sequence_table:
75
+ """
76
+
77
+ rows = self.get_num_rows()
78
+ if rows.is_ok():
79
+ existing_row_num = rows.value.num_response
80
+ wanted_row_num = len(sequence_table.rows)
81
+ while existing_row_num != wanted_row_num:
82
+ if wanted_row_num > existing_row_num:
83
+ self.add_row()
84
+ elif wanted_row_num < existing_row_num:
85
+ self.delete_row(int(existing_row_num))
86
+ self.send(Command.SAVE_SEQUENCE_CMD)
87
+ existing_row_num = self.get_num_rows().ok_value.num_response
88
+ self.send(Command.SWITCH_SEQUENCE_CMD)
89
+
90
+ for i, row in enumerate(sequence_table.rows):
91
+ self.edit_row(row=row, row_num=i + 1)
92
+ self.sleep(1)
93
+ self.send(Command.SAVE_SEQUENCE_CMD)
94
+ self.send(Command.SWITCH_SEQUENCE_CMD)
95
+
96
+ def edit_row(self, row: SequenceEntry, row_num: int):
97
+ """
98
+ Edits a row in the sequence table. If a row does NOT exist, a new one will be created.
99
+
100
+ :param row: sequence row entry with updated information
101
+ :param row_num: the row to edit, based on 1-based indexing
102
+ """
103
+ num_rows = self.get_num_rows()
104
+ if num_rows.is_ok():
105
+ while num_rows.ok_value.num_response < row_num:
106
+ self.add_row()
107
+ self.send(Command.SAVE_SEQUENCE_CMD)
108
+ num_rows = self.get_num_rows()
109
+
110
+ table_register = self.table.register
111
+ table_name = self.table.name
112
+
113
+ if row.vial_location:
114
+ loc = row.vial_location
115
+ if isinstance(row.vial_location, InjectionSource):
116
+ loc = row.vial_location.value
117
+ self.sleepy_send(TableOperation.EDIT_ROW_VAL.value.format(register=table_register,
118
+ table_name=table_name,
119
+ row=row_num,
120
+ col_name=RegisterFlag.VIAL_LOCATION,
121
+ val=loc))
122
+ if row.method:
123
+ possible_path = os.path.join(self.method_dir, row.method) + ".M\\"
124
+ method = row.method
125
+ if os.path.exists(possible_path):
126
+ method = os.path.join(self.method_dir, row.method)
127
+ self.sleepy_send(TableOperation.EDIT_ROW_TEXT.value.format(register=table_register,
128
+ table_name=table_name,
129
+ row=row_num,
130
+ col_name=RegisterFlag.METHOD,
131
+ val=method))
132
+
133
+ if row.num_inj:
134
+ self.sleepy_send(TableOperation.EDIT_ROW_VAL.value.format(register=table_register,
135
+ table_name=table_name,
136
+ row=row_num,
137
+ col_name=RegisterFlag.NUM_INJ,
138
+ val=row.num_inj))
139
+
140
+ if row.inj_vol:
141
+ self.sleepy_send(TableOperation.EDIT_ROW_TEXT.value.format(register=table_register,
142
+ table_name=table_name,
143
+ row=row_num,
144
+ col_name=RegisterFlag.INJ_VOL,
145
+ val=row.inj_vol))
146
+
147
+ if row.inj_source:
148
+ self.sleepy_send(TableOperation.EDIT_ROW_TEXT.value.format(register=table_register,
149
+ table_name=table_name,
150
+ row=row_num,
151
+ col_name=RegisterFlag.INJ_SOR,
152
+ val=row.inj_source.value))
153
+
154
+ if row.sample_name:
155
+ self.sleepy_send(TableOperation.EDIT_ROW_TEXT.value.format(register=table_register,
156
+ table_name=table_name,
157
+ row=row_num,
158
+ col_name=RegisterFlag.NAME,
159
+ val=row.sample_name))
160
+ self.sleepy_send(TableOperation.EDIT_ROW_TEXT.value.format(register=table_register,
161
+ table_name=table_name,
162
+ row=row_num,
163
+ col_name=RegisterFlag.DATA_FILE,
164
+ val=row.sample_name))
165
+ if row.sample_type:
166
+ self.sleepy_send(TableOperation.EDIT_ROW_VAL.value.format(register=table_register,
167
+ table_name=table_name,
168
+ row=row_num,
169
+ col_name=RegisterFlag.SAMPLE_TYPE,
170
+ val=row.sample_type.value))
171
+
172
+ self.send(Command.SAVE_SEQUENCE_CMD)
173
+
174
+ def run(self):
175
+ """
176
+ Starts the currently loaded sequence, storing data
177
+ under the <data_dir>/<sequence table name> folder.
178
+ Device must be ready.
179
+ """
180
+ timestamp = time.strftime(SEQUENCE_TIME_FORMAT)
181
+ seq_table = self.load()
182
+ self.send(Command.RUN_SEQUENCE_CMD.value)
183
+
184
+ if self.check_hplc_is_running():
185
+ folder_name = f"{seq_table.name} {timestamp}"
186
+ self.data_files.append(SequenceDataFiles(dir=folder_name,
187
+ sequence_name=seq_table.name))
188
+
189
+ run_completed = self.check_hplc_done_running(sequence=seq_table)
190
+
191
+ if run_completed.is_ok():
192
+ self.data_files[-1].dir = run_completed.value
193
+ else:
194
+ raise RuntimeError("Run error has occured.")
195
+
196
+ def retrieve_recent_data_files(self):
197
+ sequence_data_files: SequenceDataFiles = self.data_files[-1]
198
+ return sequence_data_files.dir
199
+
200
+ def get_data(self) -> list[dict[str, AgilentHPLCChromatogram]]:
201
+ parent_dir = self.data_files[-1].dir
202
+ subdirs = [x[0] for x in os.walk(self.data_dir)]
203
+ potential_folders = sorted(list(filter(lambda d: parent_dir in d, subdirs)))
204
+ self.data_files[-1].child_dirs = [f for f in potential_folders if parent_dir in f and ".M" not in f and ".D" in f]
205
+
206
+ spectra: list[dict[str, AgilentHPLCChromatogram]] = []
207
+ for row in self.data_files[-1].child_dirs:
208
+ self.get_spectrum(row)
209
+ spectra.append(deepcopy(self.spectra))
210
+ return spectra
@@ -0,0 +1,201 @@
1
+ """
2
+ Abstract module containing shared logic for Method and Sequence tables.
3
+
4
+ Authors: Lucy Hao
5
+ """
6
+
7
+ import abc
8
+ import os
9
+ import time
10
+ from typing import Union, Optional
11
+
12
+ import polling
13
+ from result import Result, Ok, Err
14
+
15
+ from ...control.controllers.comm import CommunicationController
16
+ from ...utils.chromatogram import AgilentHPLCChromatogram, AgilentChannelChromatogramData
17
+ from ...utils.macro import Command, HPLCRunningStatus, Response
18
+ from ...utils.method_types import MethodTimetable
19
+ from ...utils.sequence_types import SequenceDataFiles, SequenceTable
20
+ from ...utils.table_types import Table, TableOperation, RegisterFlag
21
+
22
+
23
+ class TableController(abc.ABC):
24
+
25
+ def __init__(self, controller: CommunicationController, src: str, data_dir: str, table: Table):
26
+ self.controller = controller
27
+ self.table = table
28
+
29
+ if os.path.isdir(src):
30
+ self.src: str = src
31
+ else:
32
+ raise FileNotFoundError(f"dir: {src} not found.")
33
+
34
+ if os.path.isdir(data_dir):
35
+ self.data_dir: str = data_dir
36
+ else:
37
+ raise FileNotFoundError(f"dir: {data_dir} not found.")
38
+
39
+ self.spectra: dict[str, AgilentHPLCChromatogram] = {
40
+ "A": AgilentHPLCChromatogram(self.data_dir),
41
+ "B": AgilentHPLCChromatogram(self.data_dir),
42
+ "C": AgilentHPLCChromatogram(self.data_dir),
43
+ "D": AgilentHPLCChromatogram(self.data_dir),
44
+ }
45
+
46
+ self.data_files: Union[list[SequenceDataFiles], list[str]] = []
47
+
48
+ def receive(self) -> Result[Response, str]:
49
+ for _ in range(10):
50
+ try:
51
+ return self.controller.receive()
52
+ except IndexError:
53
+ continue
54
+ return Err("Could not parse response")
55
+
56
+ def send(self, cmd: Union[Command, str]):
57
+ self.controller.send(cmd)
58
+
59
+ def sleepy_send(self, cmd: Union[Command, str]):
60
+ self.controller.sleepy_send(cmd)
61
+
62
+ def sleep(self, seconds: int):
63
+ """
64
+ Tells the HPLC to wait for a specified number of seconds.
65
+
66
+ :param seconds: number of seconds to wait
67
+ """
68
+ self.send(Command.SLEEP_CMD.value.format(seconds=seconds))
69
+
70
+ def get_num(self, row: int, col_name: RegisterFlag) -> float:
71
+ return self.controller.get_num_val(TableOperation.GET_ROW_VAL.value.format(register=self.table.register,
72
+ table_name=self.table.name,
73
+ row=row,
74
+ col_name=col_name.value))
75
+
76
+ def get_text(self, row: int, col_name: RegisterFlag) -> str:
77
+ return self.controller.get_text_val(TableOperation.GET_ROW_TEXT.value.format(register=self.table.register,
78
+ table_name=self.table.name,
79
+ row=row,
80
+ col_name=col_name.value))
81
+
82
+ @abc.abstractmethod
83
+ def get_row(self, row: int):
84
+ pass
85
+
86
+ def delete_row(self, row: int):
87
+ self.sleepy_send(TableOperation.DELETE_ROW.value.format(register=self.table.register,
88
+ table_name=self.table.name,
89
+ row=row))
90
+
91
+ def add_row(self):
92
+ """
93
+ Adds a row to the provided table for currently loaded method or sequence.
94
+ Import either the SEQUENCE_TABLE or METHOD_TIMETABLE from hein_analytical_control.constants.
95
+ You can also provide your own table.
96
+
97
+ :param table: the table to add a new row to
98
+ """
99
+ self.sleepy_send(TableOperation.NEW_ROW.value.format(register=self.table.register,
100
+ table_name=self.table.name))
101
+
102
+ def delete_table(self):
103
+ """
104
+ Deletes the table for the current loaded method or sequence.
105
+ Import either the SEQUENCE_TABLE or METHOD_TIMETABLE from hein_analytical_control.constants.
106
+ You can also provide your own table.
107
+
108
+ :param table: the table to delete
109
+ """
110
+ self.sleepy_send(TableOperation.DELETE_TABLE.value.format(register=self.table.register,
111
+ table_name=self.table.name))
112
+
113
+ def new_table(self):
114
+ """
115
+ Creates the table for the currently loaded method or sequence. Import either the SEQUENCE_TABLE or
116
+ METHOD_TIMETABLE from hein_analytical_control.constants. You can also provide your own table.
117
+
118
+ :param table: the table to create
119
+ """
120
+ self.send(TableOperation.CREATE_TABLE.value.format(register=self.table.register,
121
+ table_name=self.table.name))
122
+
123
+ def get_num_rows(self) -> Result[int, str]:
124
+ self.send(TableOperation.GET_NUM_ROWS.value.format(register=self.table.register,
125
+ table_name=self.table.name,
126
+ col_name=RegisterFlag.NUM_ROWS))
127
+ self.send(Command.GET_ROWS_CMD.value.format(register=self.table.register,
128
+ table_name=self.table.name,
129
+ col_name=RegisterFlag.NUM_ROWS))
130
+ res = self.controller.receive()
131
+
132
+ if res.is_ok():
133
+ self.send("Sleep 0.1")
134
+ self.send('Print Rows')
135
+ return res
136
+ else:
137
+ return Err("No rows could be read.")
138
+
139
+ def check_hplc_is_running(self) -> bool:
140
+ started_running = polling.poll(
141
+ lambda: isinstance(self.controller.get_status(), HPLCRunningStatus),
142
+ step=5,
143
+ max_tries=100)
144
+ return started_running
145
+
146
+ def check_hplc_done_running(self,
147
+ method: Optional[MethodTimetable] = None,
148
+ sequence: Optional[SequenceTable] = None) -> Result[str, str]:
149
+ """
150
+ Checks if ChemStation has finished running and can read data back
151
+
152
+ :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
153
+ :return: Return True if data can be read back, else False.
154
+ """
155
+ timeout = 10 * 60
156
+ if method:
157
+ timeout = ((method.first_row.maximum_run_time + 2) * 60)
158
+ if sequence:
159
+ timeout *= len(sequence.rows)
160
+
161
+ most_recent_folder = self.retrieve_recent_data_files()
162
+ finished_run = polling.poll(
163
+ lambda: self.controller.check_if_running(),
164
+ timeout=timeout,
165
+ step=12
166
+ )
167
+
168
+ if finished_run:
169
+ if os.path.exists(most_recent_folder):
170
+ return Ok(most_recent_folder)
171
+ else:
172
+ return self.fuzzy_match_most_recent_folder(most_recent_folder)
173
+ else:
174
+ return Err("Run did not complete as expected")
175
+
176
+ def fuzzy_match_most_recent_folder(self, most_recent_folder) -> Result[str, str]:
177
+ subdirs = [x[0] for x in os.walk(self.data_dir)]
178
+ potential_folders = sorted(list(filter(lambda d: most_recent_folder in d, subdirs)))
179
+ parent_dirs = []
180
+ for folder in potential_folders:
181
+ path = os.path.normpath(folder)
182
+ split_folder = path.split(os.sep)
183
+ if most_recent_folder in split_folder[-1]:
184
+ parent_dirs.append(folder)
185
+ parent_dir = sorted(parent_dirs, reverse=True)[0]
186
+ return Ok(parent_dir)
187
+
188
+ @abc.abstractmethod
189
+ def retrieve_recent_data_files(self):
190
+ pass
191
+
192
+ @abc.abstractmethod
193
+ def get_data(self) -> Union[list[AgilentChannelChromatogramData], AgilentChannelChromatogramData]:
194
+ pass
195
+
196
+ def get_spectrum(self, data_file: str):
197
+ """
198
+ Load chromatogram for any channel in spectra dictionary.
199
+ """
200
+ for channel, spec in self.spectra.items():
201
+ spec.load_spectrum(data_path=data_file, channel=channel)
@@ -1,5 +1,5 @@
1
1
  from dataclasses import dataclass, field
2
- from typing import Optional, List
2
+ from typing import List, Optional
3
3
 
4
4
 
5
5
  @dataclass
@@ -1,5 +1,5 @@
1
1
  from dataclasses import dataclass, field
2
- from typing import Optional, List
2
+ from typing import List, Optional
3
3
  from xml.etree.ElementTree import QName
4
4
 
5
5
 
@@ -6,16 +6,13 @@ from dataclasses import dataclass
6
6
 
7
7
  import numpy as np
8
8
 
9
- from .parsing import CHFile
10
9
  from ..analysis import AbstractSpectrum
11
-
12
- # standard filenames for spectral data
13
- CHANNELS = {"A": "01", "B": "02", "C": "03", "D": "04"}
10
+ from .parsing import CHFile
14
11
 
15
12
  ACQUISITION_PARAMETERS = "acq.txt"
16
13
 
17
14
  # format used in acquisition parameters
18
- TIME_FORMAT = "%Y-%m-%d-%H-%M-%S"
15
+ TIME_FORMAT = "%Y-%m-%d %H-%M-%S"
19
16
  SEQUENCE_TIME_FORMAT = "%Y-%m-%d %H-%M"
20
17
 
21
18
 
@@ -1,6 +1,6 @@
1
1
  from dataclasses import dataclass
2
2
  from enum import Enum
3
- from typing import Union, Optional, List
3
+ from typing import List, Optional, Union
4
4
 
5
5
  from pychemstation.utils.tray_types import Tray
6
6
 
@@ -1,8 +1,8 @@
1
1
  from __future__ import annotations
2
2
 
3
- from enum import Enum
4
- from typing import Union
5
3
  from dataclasses import dataclass
4
+ from enum import Enum
5
+ from typing import Union, Any, Type
6
6
 
7
7
 
8
8
  @dataclass
@@ -87,7 +87,7 @@ class HPLCErrorStatus(Enum):
87
87
  MALFORMED = "MALFORMED"
88
88
 
89
89
 
90
- def str_to_status(status: str) -> Union[HPLCAvailStatus, HPLCErrorStatus, HPLCRunningStatus]:
90
+ def str_to_status(status: str) -> Type[HPLCRunningStatus[Any] | HPLCErrorStatus[Any] | HPLCAvailStatus[Any]]:
91
91
  if HPLCErrorStatus.has_member_key(status):
92
92
  return HPLCErrorStatus[status]
93
93
  if HPLCRunningStatus.has_member_key(status):
@@ -2,11 +2,11 @@ from __future__ import annotations
2
2
 
3
3
  from dataclasses import dataclass
4
4
  from enum import Enum
5
- from typing import Union, Any, Optional
5
+ from typing import Any, Optional, Union
6
6
 
7
+ from ..generated import Signal
7
8
  from .injector_types import InjectorTable
8
9
  from .table_types import RegisterFlag
9
- from ..generated import Signal
10
10
 
11
11
 
12
12
  class PType(Enum):
@@ -0,0 +1,65 @@
1
+ from typing import Tuple
2
+
3
+ import numpy as np
4
+
5
+
6
+ def find_nearest_value_index(array, value) -> Tuple[float, int]:
7
+ """Returns closest value and its index in a given array.
8
+
9
+ :param array: An array to search in.
10
+ :type array: np.array(float)
11
+ :param value: Target value.
12
+ :type value: float
13
+
14
+ :returns: Nearest value in array and its index.
15
+ """
16
+
17
+ index_ = np.argmin(np.abs(array - value))
18
+ return array[index_], index_
19
+
20
+
21
+ def interpolate_to_index(array, ids, precision: int = 100) -> np.array:
22
+ """Find value in between arrays elements.
23
+
24
+ Constructs linspace of size "precision" between index+1 and index to
25
+ find approximate value for array[index], where index is float number.
26
+ Used for 2D data, where default scipy analysis occurs along one axis only,
27
+ e.g. signal.peak_width.
28
+
29
+ Rough equivalent of array[index], where index is float number.
30
+
31
+ :param array: Target array.
32
+ :type array: np.array(float)
33
+ :param ids: An array with "intermediate" indexes to interpolate to.
34
+ :type ids: np.array[float]
35
+ :param precision: Desired presion.
36
+
37
+ :returns: New array with interpolated values according to provided indexes "ids".
38
+
39
+ Example:
40
+ >>> interpolate_to_index(np.array([1.5]), np.array([1,2,3], 100))
41
+ array([2.50505051])
42
+ """
43
+
44
+ # breaking ids into fractional and integral parts
45
+ prec, ids = np.modf(ids)
46
+
47
+ # rounding and switching type to int
48
+ prec = np.around(prec * precision).astype("int32")
49
+ ids = ids.astype("int32")
50
+
51
+ # linear interpolation for each data point
52
+ # as (n x m) matrix where n is precision and m is number of indexes
53
+ space = np.linspace(array[ids], array[ids + 1], precision)
54
+
55
+ # due to rounding error the index may become 100 in (100, ) array
56
+ # as a consequence raising IndexError when such array is indexed
57
+ # therefore index 100 will become the last (-1)
58
+ prec[prec == 100] = -1
59
+
60
+ # precise slicing
61
+ true_values = np.array(
62
+ [space[:, index[0]][value] for index, value in np.ndenumerate(prec)]
63
+ )
64
+
65
+ return true_values
@@ -13,6 +13,7 @@ I use it for file with version 130, genereted by an Agilent LC.
13
13
 
14
14
  import struct
15
15
  from struct import unpack
16
+
16
17
  import numpy as np
17
18
 
18
19
  # Constants used for binary file parsing
@@ -2,16 +2,16 @@ from __future__ import annotations
2
2
 
3
3
  from dataclasses import dataclass
4
4
  from enum import Enum
5
- from typing import Optional, Union
5
+ from typing import Optional, List
6
6
 
7
- from pychemstation.utils.tray_types import TenVialColumn, Tray
7
+ from pychemstation.utils.tray_types import Tray
8
8
 
9
9
 
10
10
  @dataclass
11
11
  class SequenceDataFiles:
12
12
  sequence_name: str
13
13
  dir: str
14
- child_dirs: Optional[list[str]] = None
14
+ child_dirs: Optional[List[str]] = None
15
15
 
16
16
 
17
17
  class SampleType(Enum):