forked from Ulm-IQO/qudi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
national_instruments_x_series.py
2216 lines (1880 loc) · 92.8 KB
/
national_instruments_x_series.py
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
This file contains the Qudi Hardware module NICard class.
Qudi is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Qudi is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Qudi. If not, see <http://www.gnu.org/licenses/>.
Copyright (c) the Qudi Developers. See the COPYRIGHT.txt file at the
top-level directory of this distribution and at <https://github.com/Ulm-IQO/qudi/>
"""
import numpy as np
import re
import PyDAQmx as daq
from core.module import Base
from core.configoption import ConfigOption
from interface.slow_counter_interface import SlowCounterInterface
from interface.slow_counter_interface import SlowCounterConstraints
from interface.slow_counter_interface import CountingMode
from interface.odmr_counter_interface import ODMRCounterInterface
from interface.confocal_scanner_interface import ConfocalScannerInterface
class NationalInstrumentsXSeries(Base, SlowCounterInterface, ConfocalScannerInterface, ODMRCounterInterface):
""" A National Instruments device that can count and control microvave generators.
!!!!!! NI USB 63XX, NI PCIe 63XX and NI PXIe 63XX DEVICES ONLY !!!!!!
See [National Instruments X Series Documentation](@ref nidaq-x-series) for details.
stable: Kay Jahnke, Alexander Stark
Example config for copy-paste:
nicard_6343:
module.Class: 'national_instruments_x_series.NationalInstrumentsXSeries'
photon_sources:
- '/Dev1/PFI8'
# - '/Dev1/PFI9'
clock_channel: '/Dev1/Ctr0'
default_clock_frequency: 100 # optional, in Hz
counter_channels:
- '/Dev1/Ctr1'
counter_ai_channels:
- '/Dev1/AI0'
counter_voltage_range: [-10, 10]
default_scanner_clock_frequency: 100 # optional, in Hz
scanner_clock_channel: '/Dev1/Ctr2'
pixel_clock_channel: '/Dev1/PFI6'
scanner_ao_channels:
- '/Dev1/AO0'
- '/Dev1/AO1'
- '/Dev1/AO2'
- '/Dev1/AO3'
scanner_ai_channels:
- '/Dev1/AI1'
scanner_counter_channels:
- '/Dev1/Ctr3'
scanner_voltage_ranges:
- [-10, 10]
- [-10, 10]
- [-10, 10]
- [-10, 10]
scanner_position_ranges:
- [0e-6, 200e-6]
- [0e-6, 200e-6]
- [-100e-6, 100e-6]
- [-10, 10]
odmr_trigger_channel: '/Dev1/PFI7'
gate_in_channel: '/Dev1/PFI9'
default_samples_number: 50
max_counts: 3e7
read_write_timeout: 10
counting_edge_rising: True
"""
# config options
_photon_sources = ConfigOption('photon_sources', list(), missing='warn')
# slow counter
_clock_channel = ConfigOption('clock_channel', missing='error')
_default_clock_frequency = ConfigOption('default_clock_frequency', 100, missing='info')
_counter_channels = ConfigOption('counter_channels', missing='error')
_counter_ai_channels = ConfigOption('counter_ai_channels', list(), missing='info')
_counter_voltage_range = ConfigOption('counter_voltage_range', [-10, 10], missing='info')
# confocal scanner
_default_scanner_clock_frequency = ConfigOption('default_scanner_clock_frequency', 100, missing='info')
_scanner_clock_channel = ConfigOption('scanner_clock_channel', missing='warn')
_pixel_clock_channel = ConfigOption('pixel_clock_channel', None)
_scanner_ao_channels = ConfigOption('scanner_ao_channels', missing='error')
_scanner_ai_channels = ConfigOption('scanner_ai_channels', list(), missing='info')
_scanner_counter_channels = ConfigOption('scanner_counter_channels', list(), missing='warn')
_scanner_voltage_ranges = ConfigOption('scanner_voltage_ranges', missing='error')
_scanner_position_ranges = ConfigOption('scanner_position_ranges', missing='error')
# odmr
_odmr_trigger_channel = ConfigOption('odmr_trigger_channel', missing='error')
_odmr_trigger_line = ConfigOption('odmr_trigger_line', 'Dev1/port0/line0', missing='warn')
_odmr_switch_line = ConfigOption('odmr_switch_line', 'Dev1/port0/line1', missing='warn')
_gate_in_channel = ConfigOption('gate_in_channel', missing='error')
# number of readout samples, mainly used for gated counter
_default_samples_number = ConfigOption('default_samples_number', 50, missing='info')
# used as a default for expected maximum counts
_max_counts = ConfigOption('max_counts', default=3e7)
# timeout for the Read or/and write process in s
_RWTimeout = ConfigOption('read_write_timeout', default=10)
_counting_edge_rising = ConfigOption('counting_edge_rising', default=True)
def on_activate(self):
""" Starts up the NI Card at activation.
"""
# the tasks used on that hardware device:
self._counter_daq_tasks = list()
self._counter_analog_daq_task = None
self._clock_daq_task = None
self._scanner_clock_daq_task = None
self._scanner_ao_task = None
self._scanner_counter_daq_tasks = list()
self._line_length = None
self._odmr_length = None
self._gated_counter_daq_task = None
self._scanner_analog_daq_task = None
self._odmr_pulser_daq_task = None
self._oversampling = 0
self._lock_in_active = False
self._photon_sources = self._photon_sources if self._photon_sources is not None else list()
self._scanner_counter_channels = self._scanner_counter_channels if self._scanner_counter_channels is not None else list()
self._scanner_ai_channels = self._scanner_ai_channels if self._scanner_ai_channels is not None else list()
# handle all the parameters given by the config
self._current_position = np.zeros(len(self._scanner_ao_channels))
if len(self._scanner_ao_channels) < len(self._scanner_voltage_ranges):
self.log.error(
'Specify at least as many scanner_voltage_ranges as scanner_ao_channels!')
if len(self._scanner_ao_channels) < len(self._scanner_position_ranges):
self.log.error(
'Specify at least as many scanner_position_ranges as scanner_ao_channels!')
if len(self._scanner_counter_channels) + len(self._scanner_ai_channels) < 1:
self.log.error(
'Specify at least one counter or analog input channel for the scanner!')
# Analog output is always needed and it does not interfere with the
# rest, so start it always and leave it running
if self._start_analog_output() < 0:
self.log.error('Failed to start analog output.')
raise Exception('Failed to start NI Card module due to analog output failure.')
def on_deactivate(self):
""" Shut down the NI card.
"""
self._stop_analog_output()
# clear the task
try:
daq.DAQmxClearTask(self._scanner_ao_task)
self._scanner_ao_task = None
except:
self.log.exception('Could not clear AO Out Task.')
self.reset_hardware()
# =================== SlowCounterInterface Commands ========================
def get_constraints(self):
""" Get hardware limits of NI device.
@return SlowCounterConstraints: constraints class for slow counter
FIXME: ask hardware for limits when module is loaded
"""
constraints = SlowCounterConstraints()
constraints.max_detectors = 4
constraints.min_count_frequency = 1e-3
constraints.max_count_frequency = 10e9
constraints.counting_mode = [CountingMode.CONTINUOUS]
return constraints
def set_up_clock(self, clock_frequency=None, clock_channel=None, scanner=False, idle=False):
""" Configures the hardware clock of the NiDAQ card to give the timing.
@param float clock_frequency: if defined, this sets the frequency of
the clock in Hz
@param string clock_channel: if defined, this is the physical channel
of the clock within the NI card.
@param bool scanner: if set to True method will set up a clock function
for the scanner, otherwise a clock function for a
counter will be set.
@param bool idle: set whether idle situation of the counter (where
counter is doing nothing) is defined as
True = 'Voltage High/Rising Edge'
False = 'Voltage Low/Falling Edge'
@return int: error code (0:OK, -1:error)
"""
if not scanner and self._clock_daq_task is not None:
self.log.error('Another counter clock is already running, close this one first.')
return -1
if scanner and self._scanner_clock_daq_task is not None:
self.log.error('Another scanner clock is already running, close this one first.')
return -1
# Create handle for task, this task will generate pulse signal for
# photon counting
my_clock_daq_task = daq.TaskHandle()
# assign the clock frequency, if given
if clock_frequency is not None:
if not scanner:
self._clock_frequency = float(clock_frequency)
else:
self._scanner_clock_frequency = float(clock_frequency)
else:
if not scanner:
self._clock_frequency = self._default_clock_frequency
else:
self._scanner_clock_frequency = self._default_scanner_clock_frequency
# use the correct clock in this method
if scanner:
my_clock_frequency = self._scanner_clock_frequency * 2
else:
my_clock_frequency = self._clock_frequency * 2
# assign the clock channel, if given
if clock_channel is not None:
if not scanner:
self._clock_channel = clock_channel
else:
self._scanner_clock_channel = clock_channel
# use the correct clock channel in this method
if scanner:
my_clock_channel = self._scanner_clock_channel
else:
my_clock_channel = self._clock_channel
# check whether only one clock pair is available, since some NI cards
# only one clock channel pair.
if self._scanner_clock_channel == self._clock_channel:
if not ((self._clock_daq_task is None) and (self._scanner_clock_daq_task is None)):
self.log.error(
'Only one clock channel is available!\n'
'Another clock is already running, close this one first '
'in order to use it for your purpose!')
return -1
# Adjust the idle state if necessary
my_idle = daq.DAQmx_Val_High if idle else daq.DAQmx_Val_Low
try:
# create task for clock
task_name = 'ScannerClock' if scanner else 'CounterClock'
daq.DAQmxCreateTask(task_name, daq.byref(my_clock_daq_task))
# create a digital clock channel with specific clock frequency:
daq.DAQmxCreateCOPulseChanFreq(
# The task to which to add the channels
my_clock_daq_task,
# which channel is used?
my_clock_channel,
# Name to assign to task (NIDAQ uses by # default the physical channel name as
# the virtual channel name. If name is specified, then you must use the name
# when you refer to that channel in other NIDAQ functions)
'Clock Producer',
# units, Hertz in our case
daq.DAQmx_Val_Hz,
# idle state
my_idle,
# initial delay
0,
# pulse frequency, divide by 2 such that length of semi period = count_interval
my_clock_frequency / 2,
# duty cycle of pulses, 0.5 such that high and low duration are both
# equal to count_interval
0.5)
# Configure Implicit Timing.
# Set timing to continuous, i.e. set only the number of samples to
# acquire or generate without specifying timing:
daq.DAQmxCfgImplicitTiming(
# Define task
my_clock_daq_task,
# Sample Mode: set the task to generate a continuous amount of running samples
daq.DAQmx_Val_ContSamps,
# buffer length which stores temporarily the number of generated samples
1000)
if scanner:
self._scanner_clock_daq_task = my_clock_daq_task
else:
# actually start the preconfigured clock task
daq.DAQmxStartTask(my_clock_daq_task)
self._clock_daq_task = my_clock_daq_task
except:
self.log.exception('Error while setting up clock.')
return -1
return 0
def set_up_counter(self,
counter_channels=None,
sources=None,
clock_channel=None,
counter_buffer=None):
""" Configures the actual counter with a given clock.
@param list(str) counter_channels: optional, physical channel of the counter
@param list(str) sources: optional, physical channel where the photons
are to count from
@param str clock_channel: optional, specifies the clock channel for the
counter
@param int counter_buffer: optional, a buffer of specified integer
length, where in each bin the count numbers
are saved.
@return int: error code (0:OK, -1:error)
"""
if self._clock_daq_task is None and clock_channel is None:
self.log.error('No clock running, call set_up_clock before starting the counter.')
return -1
if len(self._counter_daq_tasks) > 0:
self.log.error('Another counter is already running, close this one first.')
return -1
my_counter_channels = counter_channels if counter_channels else self._counter_channels
my_photon_sources = sources if sources else self._photon_sources
my_clock_channel = clock_channel if clock_channel else self._clock_channel
if len(my_photon_sources) < len(my_counter_channels):
self.log.error('You have given {0} sources but {1} counting channels.'
'Please give an equal or greater number of sources.'
''.format(len(my_photon_sources), len(my_counter_channels)))
return -1
try:
for i, ch in enumerate(my_counter_channels):
# This task will count photons with binning defined by the clock_channel
task = daq.TaskHandle() # Initialize a Task
# Create task for the counter
daq.DAQmxCreateTask('Counter{0}'.format(i), daq.byref(task))
# Create a Counter Input which samples with Semi-Periodes the Channel.
# set up semi period width measurement in photon ticks, i.e. the width
# of each pulse (high and low) generated by pulse_out_task is measured
# in photon ticks.
# (this task creates a channel to measure the time between state
# transitions of a digital signal and adds the channel to the task
# you choose)
daq.DAQmxCreateCISemiPeriodChan(
# define to which task to connect this function
task,
# use this counter channel
ch,
# name to assign to it
'Counter Channel {0}'.format(i),
# expected minimum count value
0,
# Expected maximum count value
self._max_counts / 2 / self._clock_frequency,
# units of width measurement, here photon ticks
daq.DAQmx_Val_Ticks,
# empty extra argument
'')
# Set the Counter Input to a Semi Period input Terminal.
# Connect the pulses from the counter clock to the counter channel
daq.DAQmxSetCISemiPeriodTerm(
# The task to which to add the counter channel.
task,
# use this counter channel
ch,
# assign a named Terminal
my_clock_channel + 'InternalOutput')
# Set a Counter Input Control Timebase Source.
# Specify the terminal of the timebase which is used for the counter:
# Define the source of ticks for the counter as self._photon_source for
# the Scanner Task.
daq.DAQmxSetCICtrTimebaseSrc(
# define to which task to connect this function
task,
# counter channel
ch,
# counter channel to output the counting results
my_photon_sources[i])
# Configure Implicit Timing.
# Set timing to continuous, i.e. set only the number of samples to
# acquire or generate without specifying timing:
daq.DAQmxCfgImplicitTiming(
# define to which task to connect this function
task,
# Sample Mode: Acquire or generate samples until you stop the task.
daq.DAQmx_Val_ContSamps,
# buffer length which stores temporarily the number of generated samples
1000)
# Set the Read point Relative To an operation.
# Specifies the point in the buffer at which to begin a read operation.
# Here we read most recent recorded samples:
daq.DAQmxSetReadRelativeTo(
# define to which task to connect this function
task,
# Start reading samples relative to the last sample returned by the previously.
daq.DAQmx_Val_CurrReadPos)
# Set the Read Offset.
# Specifies an offset in samples per channel at which to begin a read
# operation. This offset is relative to the location you specify with
# RelativeTo. Here we set the Offset to 0 for multiple samples:
daq.DAQmxSetReadOffset(task, 0)
# Set Read OverWrite Mode.
# Specifies whether to overwrite samples in the buffer that you have
# not yet read. Unread data in buffer will be overwritten:
daq.DAQmxSetReadOverWrite(
task,
daq.DAQmx_Val_DoNotOverwriteUnreadSamps)
# add task to counter task list
self._counter_daq_tasks.append(task)
# Counter analog input task
if len(self._counter_ai_channels) > 0:
atask = daq.TaskHandle()
daq.DAQmxCreateTask('CounterAnalogIn', daq.byref(atask))
daq.DAQmxCreateAIVoltageChan(
atask,
', '.join(self._counter_ai_channels),
'Counter Analog In',
daq.DAQmx_Val_RSE,
self._counter_voltage_range[0],
self._counter_voltage_range[1],
daq.DAQmx_Val_Volts,
''
)
# Analog in channel timebase
daq.DAQmxCfgSampClkTiming(
atask,
my_clock_channel + 'InternalOutput',
self._clock_frequency,
daq.DAQmx_Val_Rising,
daq.DAQmx_Val_ContSamps,
int(self._clock_frequency * 5)
)
self._counter_analog_daq_task = atask
except:
self.log.exception('Error while setting up counting task.')
return -1
try:
for i, task in enumerate(self._counter_daq_tasks):
# Actually start the preconfigured counter task
daq.DAQmxStartTask(task)
if len(self._counter_ai_channels) > 0:
daq.DAQmxStartTask(self._counter_analog_daq_task)
except:
self.log.exception('Error while starting Counter')
try:
self.close_counter()
except:
self.log.exception('Could not close counter after error')
return -1
return 0
def get_counter_channels(self):
""" Returns the list of counter channel names.
@return tuple(str): channel names
Most methods calling this might just care about the number of channels, though.
"""
ch = self._counter_channels[:]
ch.extend(self._counter_ai_channels)
return ch
def get_counter(self, samples=None):
""" Returns the current counts per second of the counter.
@param int samples: if defined, number of samples to read in one go.
How many samples are read per readout cycle. The
readout frequency was defined in the counter setup.
That sets also the length of the readout array.
@return float [samples]: array with entries as photon counts per second
"""
if len(self._counter_daq_tasks) < 1:
self.log.error(
'No counter running, call set_up_counter before reading it.')
# in case of error return a lot of -1
return np.ones((len(self.get_counter_channels()), samples), dtype=np.uint32) * -1
if len(self._counter_ai_channels) > 0 and self._counter_analog_daq_task is None:
self.log.error(
'No counter analog input task running, call set_up_counter before reading it.')
# in case of error return a lot of -1
return np.ones((len(self.get_counter_channels()), samples), dtype=np.uint32) * -1
if samples is None:
samples = int(self._samples_number)
else:
samples = int(samples)
try:
# count data will be written here in the NumPy array of length samples
count_data = np.empty((len(self._counter_daq_tasks), 2 * samples), dtype=np.uint32)
# number of samples which were actually read, will be stored here
n_read_samples = daq.int32()
for i, task in enumerate(self._counter_daq_tasks):
# read the counter value: This function is blocking and waits for the
# counts to be all filled:
daq.DAQmxReadCounterU32(
# read from this task
task,
# number of samples to read
2 * samples,
# maximal timeout for the read process
self._RWTimeout,
# write the readout into this array
count_data[i],
# length of array to write into
2 * samples,
# number of samples which were read
daq.byref(n_read_samples),
# Reserved for future use. Pass NULL (here None) to this parameter
None)
# Analog channels
if len(self._counter_ai_channels) > 0:
analog_data = np.full(
(len(self._counter_ai_channels), samples), 111, dtype=np.float64)
analog_read_samples = daq.int32()
daq.DAQmxReadAnalogF64(
self._counter_analog_daq_task,
samples,
self._RWTimeout,
daq.DAQmx_Val_GroupByChannel,
analog_data,
len(self._counter_ai_channels) * samples,
daq.byref(analog_read_samples),
None
)
except:
self.log.exception(
'Getting samples from counter failed.')
# in case of error return a lot of -1
return np.ones((len(self.get_counter_channels()), samples), dtype=np.uint32) * -1
real_data = np.empty((len(self._counter_channels), samples), dtype=np.uint32)
# add up adjoint pixels to also get the counts from the low time of
# the clock:
real_data = count_data[:, ::2]
real_data += count_data[:, 1::2]
all_data = np.full((len(self.get_counter_channels()), samples), 222, dtype=np.float64)
# normalize to counts per second for counter channels
all_data[0:len(real_data)] = np.array(real_data * self._clock_frequency, np.float64)
if len(self._counter_ai_channels) > 0:
all_data[-len(self._counter_ai_channels):] = analog_data
return all_data
def close_counter(self, scanner=False):
""" Closes the counter or scanner and cleans up afterwards.
@param bool scanner: specifies if the counter- or scanner- function
will be excecuted to close the device.
True = scanner
False = counter
@return int: error code (0:OK, -1:error)
"""
error = 0
if scanner:
for i, task in enumerate(self._scanner_counter_daq_tasks):
try:
# stop the counter task
daq.DAQmxStopTask(task)
# after stopping delete all the configuration of the counter
daq.DAQmxClearTask(task)
except:
self.log.exception('Could not close scanner counter.')
error = -1
self._scanner_counter_daq_tasks = []
else:
for i, task in enumerate(self._counter_daq_tasks):
try:
# stop the counter task
daq.DAQmxStopTask(task)
# after stopping delete all the configuration of the counter
daq.DAQmxClearTask(task)
# set the task handle to None as a safety
except:
self.log.exception('Could not close counter.')
error = -1
self._counter_daq_tasks = []
if len(self._counter_ai_channels) > 0:
try:
# stop the counter task
daq.DAQmxStopTask(self._counter_analog_daq_task)
# after stopping delete all the configuration of the counter
daq.DAQmxClearTask(self._counter_analog_daq_task)
# set the task handle to None as a safety
except:
self.log.exception('Could not close counter analog channels.')
error = -1
self._counter_analog_daq_task = None
return error
def close_clock(self, scanner=False):
""" Closes the clock and cleans up afterwards.
@param bool scanner: specifies if the counter- or scanner- function
should be used to close the device.
True = scanner
False = counter
@return int: error code (0:OK, -1:error)
"""
if scanner:
my_task = self._scanner_clock_daq_task
else:
my_task = self._clock_daq_task
try:
# Stop the clock task:
daq.DAQmxStopTask(my_task)
# After stopping delete all the configuration of the clock:
daq.DAQmxClearTask(my_task)
# Set the task handle to None as a safety
if scanner:
self._scanner_clock_daq_task = None
else:
self._clock_daq_task = None
except:
self.log.exception('Could not close clock.')
return -1
return 0
# ================ End SlowCounterInterface Commands =======================
# ================ ConfocalScannerInterface Commands =======================
def reset_hardware(self):
""" Resets the NI hardware, so the connection is lost and other
programs can access it.
@return int: error code (0:OK, -1:error)
"""
retval = 0
chanlist = [
self._odmr_trigger_channel,
self._clock_channel,
self._scanner_clock_channel,
self._gate_in_channel
]
chanlist.extend(self._scanner_ao_channels)
chanlist.extend(self._photon_sources)
chanlist.extend(self._counter_channels)
chanlist.extend(self._scanner_counter_channels)
devicelist = []
for channel in chanlist:
if channel is None:
continue
match = re.match(
'^/(?P<dev>[0-9A-Za-z\- ]+[0-9A-Za-z\-_ ]*)/(?P<chan>[0-9A-Za-z]+)',
channel)
if match:
devicelist.append(match.group('dev'))
else:
self.log.error('Did not find device name in {0}.'.format(channel))
for device in set(devicelist):
self.log.info('Reset device {0}.'.format(device))
try:
daq.DAQmxResetDevice(device)
except:
self.log.exception('Could not reset NI device {0}'.format(device))
retval = -1
return retval
def get_scanner_axes(self):
""" Scanner axes depends on how many channels tha analog output task has.
"""
if self._scanner_ao_task is None:
self.log.error('Cannot get channel number, analog output task does not exist.')
return []
n_channels = daq.uInt32()
daq.DAQmxGetTaskNumChans(self._scanner_ao_task, n_channels)
possible_channels = ['x', 'y', 'z', 'a']
return possible_channels[0:int(n_channels.value)]
def get_scanner_count_channels(self):
""" Return list of counter channels """
ch = self._scanner_counter_channels[:]
ch.extend(self._scanner_ai_channels)
return ch
def get_position_range(self):
""" Returns the physical range of the scanner.
@return float [4][2]: array of 4 ranges with an array containing lower
and upper limit. The unit of the scan range is
meters.
"""
return self._scanner_position_ranges
def set_position_range(self, myrange=None):
""" Sets the physical range of the scanner.
@param float [4][2] myrange: array of 4 ranges with an array containing
lower and upper limit. The unit of the
scan range is meters.
@return int: error code (0:OK, -1:error)
"""
if myrange is None:
myrange = [[0, 1e-6], [0, 1e-6], [0, 1e-6], [0, 1e-6]]
if not isinstance(myrange, (frozenset, list, set, tuple, np.ndarray, )):
self.log.error('Given range is no array type.')
return -1
if len(myrange) != 4:
self.log.error(
'Given range should have dimension 4, but has {0:d} instead.'
''.format(len(myrange)))
return -1
for pos in myrange:
if len(pos) != 2:
self.log.error(
'Given range limit {1:d} should have dimension 2, but has {0:d} instead.'
''.format(len(pos), pos))
return -1
if pos[0]>pos[1]:
self.log.error(
'Given range limit {0:d} has the wrong order.'.format(pos))
return -1
self._scanner_position_ranges = myrange
return 0
def set_voltage_range(self, myrange=None):
""" Sets the voltage range of the NI Card.
@param float [n][2] myrange: array containing lower and upper limit
@return int: error code (0:OK, -1:error)
"""
n_ch = len(self.get_scanner_axes())
if myrange is None:
myrange = [[-10., 10.], [-10., 10.], [-10., 10.], [-10., 10.]][0:n_ch]
if not isinstance(myrange, (frozenset, list, set, tuple, np.ndarray)):
self.log.error('Given range is no array type.')
return -1
if len(myrange) != n_ch:
self.log.error(
'Given range should have dimension 2, but has {0:d} instead.'
''.format(len(myrange)))
return -1
for r in myrange:
if r[0] > r[1]:
self.log.error('Given range limit {0:d} has the wrong order.'.format(r))
return -1
self._scanner_voltage_ranges = myrange
return 0
def _start_analog_output(self):
""" Starts or restarts the analog output.
@return int: error code (0:OK, -1:error)
"""
try:
# If an analog task is already running, kill that one first
if self._scanner_ao_task is not None:
# stop the analog output task
daq.DAQmxStopTask(self._scanner_ao_task)
# delete the configuration of the analog output
daq.DAQmxClearTask(self._scanner_ao_task)
# set the task handle to None as a safety
self._scanner_ao_task = None
# initialize ao channels / task for scanner, should always be active.
# Define at first the type of the variable as a Task:
self._scanner_ao_task = daq.TaskHandle()
# create the actual analog output task on the hardware device. Via
# byref you pass the pointer of the object to the TaskCreation function:
daq.DAQmxCreateTask('ScannerAO', daq.byref(self._scanner_ao_task))
for n, chan in enumerate(self._scanner_ao_channels):
# Assign and configure the created task to an analog output voltage channel.
daq.DAQmxCreateAOVoltageChan(
# The AO voltage operation function is assigned to this task.
self._scanner_ao_task,
# use (all) scanner ao_channels for the output
chan,
# assign a name for that channel
'Scanner AO Channel {0}'.format(n),
# minimum possible voltage
self._scanner_voltage_ranges[n][0],
# maximum possible voltage
self._scanner_voltage_ranges[n][1],
# units is Volt
daq.DAQmx_Val_Volts,
# empty for future use
'')
except:
self.log.exception('Error starting analog output task.')
return -1
return 0
def _stop_analog_output(self):
""" Stops the analog output.
@return int: error code (0:OK, -1:error)
"""
if self._scanner_ao_task is None:
return -1
retval = 0
try:
# stop the analog output task
daq.DAQmxStopTask(self._scanner_ao_task)
except:
self.log.exception('Error stopping analog output.')
retval = -1
try:
daq.DAQmxSetSampTimingType(self._scanner_ao_task, daq.DAQmx_Val_OnDemand)
except:
self.log.exception('Error changing analog output mode.')
retval = -1
return retval
def set_up_scanner_clock(self, clock_frequency=None, clock_channel=None):
""" Configures the hardware clock of the NiDAQ card to give the timing.
@param float clock_frequency: if defined, this sets the frequency of
the clock
@param string clock_channel: if defined, this is the physical channel
of the clock
@return int: error code (0:OK, -1:error)
"""
# The clock for the scanner is created on the same principle as it is
# for the counter. Just to keep consistency, this function is a wrapper
# around the set_up_clock.
return self.set_up_clock(
clock_frequency=clock_frequency,
clock_channel=clock_channel,
scanner=True)
def set_up_scanner(self,
counter_channels=None,
sources=None,
clock_channel=None,
scanner_ao_channels=None):
""" Configures the actual scanner with a given clock.
The scanner works pretty much like the counter. Here you connect a
created clock with a counting task. That can be seen as a gated
counting, where the counts where sampled by the underlying clock.
@param list(str) counter_channels: this is the physical channel of the counter
@param list(str) sources: this is the physical channel where the photons are to count from
@param string clock_channel: optional, if defined, this specifies the clock for the counter
@param list(str) scanner_ao_channels: optional, if defined, this specifies
the analog output channels
@return int: error code (0:OK, -1:error)
"""
retval = 0
if self._scanner_clock_daq_task is None and clock_channel is None:
self.log.error('No clock running, call set_up_clock before starting the counter.')
return -1
my_counter_channels = counter_channels if counter_channels else self._scanner_counter_channels
my_photon_sources = sources if sources else self._photon_sources
self._my_scanner_clock_channel = clock_channel if clock_channel else self._scanner_clock_channel
if scanner_ao_channels is not None:
self._scanner_ao_channels = scanner_ao_channels
retval = self._start_analog_output()
if len(my_photon_sources) < len(my_counter_channels):
self.log.error('You have given {0} sources but {1} counting channels.'
'Please give an equal or greater number of sources.'
''.format(len(my_photon_sources), len(my_counter_channels)))
return -1
try:
# Set the Sample Timing Type. Task timing to use a sampling clock:
# specify how the Data of the selected task is collected, i.e. set it
# now to be sampled on demand for the analog output, i.e. when
# demanded by software.
daq.DAQmxSetSampTimingType(self._scanner_ao_task, daq.DAQmx_Val_OnDemand)
for i, ch in enumerate(my_counter_channels):
# create handle for task, this task will do the photon counting for the
# scanner.
task = daq.TaskHandle()
# actually create the scanner counting task
daq.DAQmxCreateTask('ScannerCounter{0}'.format(i), daq.byref(task))
# Create a Counter Input which samples with Semi Perides the Channel.
# set up semi period width measurement in photon ticks, i.e. the width
# of each pulse (high and low) generated by pulse_out_task is measured
# in photon ticks.
# (this task creates a channel to measure the time between state
# transitions of a digital signal and adds the channel to the task
# you choose)
daq.DAQmxCreateCISemiPeriodChan(
# The task to which to add the channels
task,
# use this counter channel
ch,
# name to assign to it
'Scanner Counter Channel {0}'.format(i),
# expected minimum value
0,
# Expected maximum count value
self._max_counts / self._scanner_clock_frequency,
# units of width measurement, here Timebase photon ticks
daq.DAQmx_Val_Ticks,
'')
# Set the Counter Input to a Semi Period input Terminal.
# Connect the pulses from the scanner clock to the scanner counter
daq.DAQmxSetCISemiPeriodTerm(
# The task to which to add the counter channel.
task,
# use this counter channel
ch,
# assign a Terminal Name
self._my_scanner_clock_channel + 'InternalOutput')
# Set a CounterInput Control Timebase Source.
# Specify the terminal of the timebase which is used for the counter:
# Define the source of ticks for the counter as self._photon_source for
# the Scanner Task.
daq.DAQmxSetCICtrTimebaseSrc(
# define to which task to# connect this function
task,
# counter channel to output the# counting results
ch,
# which channel to count
my_photon_sources[i])
self._scanner_counter_daq_tasks.append(task)
# Scanner analog input task
if self._scanner_ai_channels:
atask = daq.TaskHandle()
daq.DAQmxCreateTask('ScanAnalogIn', daq.byref(atask))
daq.DAQmxCreateAIVoltageChan(
atask,
', '.join(self._scanner_ai_channels),
'Scan Analog In',
daq.DAQmx_Val_RSE,
self._counter_voltage_range[0],
self._counter_voltage_range[1],
daq.DAQmx_Val_Volts,
''