-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspectramax.py
More file actions
470 lines (382 loc) · 14.4 KB
/
spectramax.py
File metadata and controls
470 lines (382 loc) · 14.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
"""
Spectramax Plate Reader Controller
Python interface for controlling Molecular Devices SpectraMax plate readers
via the SoftMax Pro Software Automation API
"""
import sys
import threading
from typing import Optional, Callable, Dict
# Add .NET assemblies path - adjust this path according to your installation
# Default paths from the documentation:
# 32-bit: C:\Program Files\Molecular Devices\SoftMax Pro 7.0 Automation SDK
# 64-bit: C:\Program Files (x86)\Molecular Devices\SoftMax Pro 7.0 Automation SDK
AUTOMATION_SDK_PATH = (
r"C:\Program Files (x86)\Molecular Devices\SoftMax Pro 7.0 Automation SDK"
)
try:
import clr
# Add reference to the automation assemblies
clr.AddReference("System")
sys.path.append(AUTOMATION_SDK_PATH)
clr.AddReference("SoftMaxPro.AutomationClient")
clr.AddReference("SoftMaxPro.AutomationInterface")
clr.AddReference("SoftMaxPro.AutomationExtensions")
# Import the automation client
from SoftMaxPro.AutomationClient import SMPAutomationClient
print("Successfully loaded SoftMax Pro automation assemblies")
except ImportError as e:
print(f"Error importing .NET assemblies: {e}")
print("Make sure pythonnet is installed: pip install pythonnet")
print(f"And verify the automation SDK path: {AUTOMATION_SDK_PATH}")
sys.exit(1)
class Spectramax:
"""
Python wrapper for SoftMax Pro Automation API
Provides high-level control of SpectraMax plate readers
"""
def __init__(self, server: str = "localhost", port: int = 9000):
"""
Initialize the Spectramax controller
Args:
server: SoftMax Pro server address (default: localhost)
port: Server port (default: 9000)
"""
self.server = server
self.port = port
self.client = None
self.connected = False
self.command_callbacks: Dict[int, Callable] = {}
self.last_command_id = -1
# Event flags
self.command_completed_event = threading.Event()
self.instrument_status = "UNKNOWN"
def initialize(self) -> bool:
"""
Initialize connection to SoftMax Pro software
Returns:
bool: True if connection successful, False otherwise
"""
try:
self.client = SMPAutomationClient()
# Subscribe to events before initializing
self.client.CommandCompleted += self._on_command_completed
self.client.ErrorReport += self._on_error_report
self.client.InstrumentStatusChanged += self._on_instrument_status_changed
# Initialize connection
if self.port != 9000:
self.connected = self.client.Initialize(self.server, self.port)
else:
self.connected = self.client.Initialize(self.server)
if self.connected:
print(
f"Successfully connected to SoftMax Pro at {self.server}:{self.port}"
)
else:
print("Failed to connect to SoftMax Pro")
return self.connected
except Exception as e:
print(f"Connection error: {e}")
return False
def disconnect(self):
"""Disconnect from SoftMax Pro and clean up resources"""
if self.client and self.connected:
try:
# Unsubscribe from events
self.client.CommandCompleted -= self._on_command_completed
self.client.ErrorReport -= self._on_error_report
self.client.InstrumentStatusChanged -= (
self._on_instrument_status_changed
)
# Dispose the client
self.client.Dispose()
print("Disconnected from SoftMax Pro")
except Exception as e:
print(f"Error during disconnect: {e}")
finally:
self.connected = False
self.client = None
def _on_command_completed(self, sender, e):
"""Handle command completion events"""
print(f"Command {e.QueueID} completed")
if e.StringResult:
print(f"Result: {e.StringResult}")
if e.IntResult != 0:
print(f"Int Result: {e.IntResult}")
if hasattr(e, "DoubleResult") and e.DoubleResult != 0:
print(f"Double Result: {e.DoubleResult}")
# Call registered callback if exists
if e.QueueID in self.command_callbacks:
callback = self.command_callbacks.pop(e.QueueID)
callback(e)
self.last_command_id = e.QueueID
self.command_completed_event.set()
if e.QueueEmpty:
print("Command queue is empty")
def _on_error_report(self, sender, e):
"""Handle error events"""
print(f"ERROR - Command {e.QueueID}: {e.Error}")
def _on_instrument_status_changed(self, sender, e):
"""Handle instrument status change events"""
self.instrument_status = e.Status
print(f"Instrument status changed to: {e.Status}")
def _wait_for_command(self, timeout: float = 30.0) -> bool:
"""
Wait for the last command to complete
Args:
timeout: Maximum time to wait in seconds
Returns:
bool: True if command completed, False if timeout
"""
self.command_completed_event.clear()
return self.command_completed_event.wait(timeout)
def open_drawer(self) -> bool:
"""
Open the plate drawer
Returns:
bool: True if operation successful
"""
if not self.connected:
print("Not connected to SoftMax Pro")
return False
try:
self.client.OpenDrawer()
print("Opening drawer...")
self._wait_for_command()
return True
except Exception as e:
print(f"Error opening drawer: {e}")
return False
def close_drawer(self) -> bool:
"""
Close the plate drawer
Returns:
bool: True if operation successful
"""
if not self.connected:
print("Not connected to SoftMax Pro")
return False
try:
self.client.CloseDrawer()
print("Closing drawer...")
self._wait_for_command()
return True
except Exception as e:
print(f"Error closing drawer: {e}")
return False
def read_UVVis(self, method: str, results: str) -> bool:
"""
Perform a UV-Vis read using the specified method and save results
Args:
method: File path to the method file (.spr protocol file)
results: Base file path for results (without extension)
Returns:
bool: True if read and save operations successful
"""
if not self.connected:
print("Not connected to SoftMax Pro")
return False
try:
print(f"Starting UV-Vis read with method: {method}")
print(f"Results will be saved to: {results}")
# Step 1: Close drawer
print("Closing drawer...")
self.client.CloseDrawer()
self._wait_for_command()
# Step 2: Close all documents
print("Closing all documents...")
self.client.CloseAllDocuments()
self._wait_for_command()
# Step 3: Open the method file
print(f"Opening method file: {method}")
self.client.OpenFile(method)
self._wait_for_command()
# Step 4: Start the read
print("Starting read operation...")
command_id = self.client.StartRead()
print(f"Read started (Command ID: {command_id})")
self._wait_for_command(
timeout=120.0
) # Extended timeout for read operations
# Step 5: Save as .sda file
saveas_spr = results + ".sda"
print(f"Saving as SoftMax Pro data file: {saveas_spr}")
self.client.SaveAs(saveas_spr)
self._wait_for_command()
# Step 6: Export as CSV (COLUMNS format)
saveas_csv = results + ".csv"
print(f"Exporting as CSV: {saveas_csv}")
self.client.ExportAs(saveas_csv, SMPAutomationClient.ExportAsFormat.COLUMNS)
self._wait_for_command()
# Step 7: Export as XML
saveas_xml = results + ".xml"
print(f"Exporting as XML: {saveas_xml}")
self.client.ExportAs(saveas_xml, SMPAutomationClient.ExportAsFormat.XML)
self._wait_for_command()
print("UV-Vis read completed successfully")
print("Files saved:")
print(f" - Data file: {saveas_spr}")
print(f" - CSV export: {saveas_csv}")
print(f" - XML export: {saveas_xml}")
return True
except Exception as e:
print(f"Error during UV-Vis read: {e}")
return False
# Additional utility methods
def setup_reader(
self,
port: str = "Offline",
instrument: str = "SPECTRAmax M5",
simulation: bool = True,
) -> bool:
"""
Configure the plate reader
Args:
port: Communication port (e.g., "COM1" or "Offline")
instrument: Instrument model name
simulation: Enable simulation mode
Returns:
bool: True if setup successful
"""
if not self.connected:
print("Not connected to SoftMax Pro")
return False
try:
# Set reader type
self.client.SetReader(port, instrument)
self._wait_for_command()
# Enable/disable simulation mode
self.client.SetSimulationMode(simulation)
self._wait_for_command()
print(
f"Reader setup complete: {instrument} on {port}, simulation={simulation}"
)
return True
except Exception as e:
print(f"Reader setup error: {e}")
return False
def create_new_document(self) -> bool:
"""Create a new SoftMax Pro document"""
if not self.connected:
return False
try:
self.client.NewDocument()
self._wait_for_command()
print("New document created")
return True
except Exception as e:
print(f"Error creating document: {e}")
return False
def select_plate_section(self, section_name: str = "Plate1") -> bool:
"""
Select a plate section for reading
Args:
section_name: Name of the plate section
Returns:
bool: True if selection successful
"""
if not self.connected:
return False
try:
self.client.SelectSection(section_name)
self._wait_for_command()
print(f"Selected section: {section_name}")
return True
except Exception as e:
print(f"Error selecting section: {e}")
return False
def get_data(self) -> Optional[str]:
"""
Get the current plate data
Returns:
str: Plate data as tab-delimited string, or None if error
"""
if not self.connected:
return None
try:
# Store result in a container we can access from callback
result_container = {"data": None}
def data_callback(e):
result_container["data"] = e.StringResult
command_id = self.client.GetDataCopy()
self.command_callbacks[command_id] = data_callback
if self._wait_for_command():
return result_container["data"]
else:
print("Timeout waiting for data")
return None
except Exception as e:
print(f"Get data error: {e}")
return None
def set_temperature(self, temperature: float) -> bool:
"""
Set the incubator temperature
Args:
temperature: Temperature in Celsius (0 to turn off)
Returns:
bool: True if successful
"""
if not self.connected:
return False
try:
self.client.SetTemperature(temperature)
self._wait_for_command()
print(f"Temperature set to {temperature}°C")
return True
except Exception as e:
print(f"Temperature setting error: {e}")
return False
def get_instrument_status(self) -> str:
"""
Get current instrument status
Returns:
str: Current instrument status
"""
return self.instrument_status
def save_data(self, file_path: str) -> bool:
"""
Save the current document
Args:
file_path: Full path for saving (use .sda extension for data files)
Returns:
bool: True if save successful
"""
if not self.connected:
return False
try:
self.client.SaveAs(file_path)
self._wait_for_command()
print(f"Data saved to: {file_path}")
return True
except Exception as e:
print(f"Save error: {e}")
return False
def export_data(self, file_path: str, format_type: str = "XML") -> bool:
"""
Export data in specified format
Args:
file_path: Full path for export
format_type: Export format ("XML", "PLATE", "COLUMNS")
Returns:
bool: True if export successful
"""
if not self.connected:
return False
try:
# Map format strings to enum values
format_map = {
"XML": SMPAutomationClient.ExportAsFormat.XML,
"PLATE": SMPAutomationClient.ExportAsFormat.PLATE,
"COLUMNS": SMPAutomationClient.ExportAsFormat.COLUMNS,
"TIME": SMPAutomationClient.ExportAsFormat.TIME,
}
export_format = format_map.get(format_type.upper())
if export_format is None:
print(f"Invalid format: {format_type}")
return False
self.client.ExportAs(file_path, export_format)
self._wait_for_command()
print(f"Data exported to: {file_path}")
return True
except Exception as e:
print(f"Export error: {e}")
return False