-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMScan.py
2849 lines (2342 loc) · 122 KB
/
MScan.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 -*-
"""
Created on Wed Oct 7 12:22:44 2015
@author: OHNS
"""
import OCTCommon
from DebugLog import DebugLog
import VolumeScan
import AudioHardware
import BScan
import JSOraw
# import OCTFPGAProcessingInterface as octfpga
from PyQt4 import QtCore, QtGui, uic
from ROIImageGraphicsView import *
from OCTProtocolParams import *
from DebugLog import DebugLog
import PIL
import copy
import traceback
import sys
import os
import tifffile
import struct
import time
import pickle
import multiprocessing as mproc
import queue
from OCTProtocolParams import *
import scipy.signal
import ctypes
import re
# Mscan processing options
class MscanProcOpts:
def __init__(self):
self.FFTZeroPadFactor = 5
self.singlePt_zROI_indices = [0] # for single point or points list mscans the Z point and spread at which to
self.singlePt_zROI_spread = 0 # calculate TD and FFT (looking for max SNR in this region )
# singlePt_zROIidx could be array in cae of points list scan types
self.noiseBandwidth = 100 # bandwidth for noise calculations in Hz
self.spikeRemoval = False # remove spikes from time domain signal
self.spikeThreshold_nm = 50 # remove spikes from time domain signal
# self.FFTindex = 0
self.zRes = 0 # z resolution in microns (this 0 value will be changed to what is imported from oct.txt)
self.correctAspectRatio = True # whether to correct the aspect ratio in the image
self.logAline = True
self.bscanNormLow = 20 # range to normalize bscan after taking 20*log10 of magnitude
self.bscanNormHigh = 150
self.refractiveIndex = 0 # changed based on oct.txt
self.centerWavelength = 0 # center wavelength in nm; changed based on oct.txt
# [1.0590e-06 -1.0900e-10 4.4570e-15 -1.9210e-18]
def __repr__(self):
d = self.__dict__
s = ''
for k in d.keys():
# print("k= ", k ", d[k]= ", repr(d[k]))
s = s + k + '= ' + str(d[k])
s = s + '\n'
return s
class MScanData:
def __init__(self):
self.avgAline = None # average of aline data
self.posLenStep = None # scan pos step
self.posWidthStep = None # scan width step
self.stimFreqIdx = None # sound stimulation frequency index in AudioOutputParams frequency arrray
self.stimAmpIdx = None # sound stimulation amplitude index in AudioOutputParams frequency arrray
self.trialTime = None # time of trial
self.mscanTD = None # the mscan in time domain, at desired point (1D array)
self.mscanFFT = None # FFT of time doamin, at desired point (1D array)
self.maxFFTFreq = None
self.mscanSampleRate = None # effective sample rate of mscan
self.stimRespMag = None # magnitude resposne at stimulus frequency
self.stimRespPhase = None # phase resposne at stimulus frequency
self.F1RespMag = None # magnitude resposne at stimulus frequency
self.F1RespPhase = None # phase resposne at stimulus frequency
self.DPRespMag = None # magnitude resposne at stimulus frequency
self.DPRespPhase = None # phase resposne at stimulus frequency
self.F1freq = None
self.DPfreq = None
self.TDnoiseSD = None # time domain (TD) noise
self.FDnoiseAboveStimFreqMean = None # noise calculations for FFT noise (FD = Fourier domain) above and below stim frequency
self.FDnoiseAboveStimFreqSD = None # Mean= mean noise, SD = standard deviation
self.FDnoiseBelowStimFreqMean = None # num pts is deermined by noise bandiwth in mscan processing opts
self.FDnoiseBelowStimFreqSD = None
self.frameNum = -1
# aggregate tuning curve at single point
class MscanTuningCurve:
def __init__(self, audioParams):
self.freq = audioParams.freq[0, :]
self.amp = audioParams.amp # stim amp array (db SPL)
numFreq = audioParams.getNumFrequencies()
numAmp = len(self.amp)
self.magResp = np.zeros((numFreq, numAmp))
self.magResp[:, :] = np.NaN
self.phaseResp = np.zeros((numFreq, numAmp))
self.phaseResp[:, :] = np.NaN
self.phaseRespUnwrapped = np.zeros((numFreq, numAmp))
self.phaseRespUnwrapped[:, :] = np.NaN
self.TDnoise = np.zeros((numFreq, numAmp))
self.TDnoise[:, :] = np.NaN
self.FDnoiseAboveStimFreqMean = np.zeros((numFreq, numAmp))
self.FDnoiseAboveStimFreqMean[:, :] = np.NaN
self.FDnoiseAboveStimFreqSD = np.zeros((numFreq, numAmp))
self.FDnoiseAboveStimFreqSD[:, :] = np.NaN
self.FDnoiseBelowStimFreqMean = np.zeros((numFreq, numAmp))
self.FDnoiseBelowStimFreqMean[:, :] = np.NaN
self.FDnoiseBelowStimFreqSD = np.zeros((numFreq, numAmp))
self.FDnoiseBelowStimFreqSD[:, :] = np.NaN
self.DPResp = np.zeros((numFreq, numAmp))
self.DPResp[:, :] = np.NaN
self.DPphaseResp = np.zeros((numFreq, numAmp))
self.DPphaseResp[:, :] = np.NaN
self.DPphaseRespUnwrapped = np.zeros((numFreq, numAmp))
self.DPphaseRespUnwrapped[:, :] = np.NaN
self.F1Resp = np.zeros((numFreq, numAmp))
self.F1Resp[:, :] = np.NaN
self.F1phaseResp = np.zeros((numFreq, numAmp))
self.F1phaseResp[:, :] = np.NaN
self.F1phaseRespUnwrapped = np.zeros((numFreq, numAmp))
self.F1phaseRespUnwrapped[:, :] = np.NaN
# aggregate data for mscan over a fairly region (B Mscan, Volume Mscan with possible ROI mask)
class MscanRegionData:
def __init__(self, audioParams, scanParams, procOpts, numZPts):
hsl = scanParams.length/2
hsw = scanParams.width/2
numFreq = audioParams.getNumFrequencies()
numAmp = len(audioParams.amp)
len_steps = scanParams.lengthSteps
width_steps = scanParams.widthSteps
self.posLen = np.linspace(-hsl, hsl, len_steps) # 1D array of length positions
self.posWidth = np.linspace(-hsw, hsw, width_steps) # 1D array of width positions
# numZPts = (procOpts.zROIend - procOpts.zROIstart + 1)
maxZ =procOpts.zRes*numZPts
self.posDepth = np.linspace(0, maxZ, numZPts) # 1D array of depth positions
self.audioOutputParams = audioParams # audio output data for this Mscan
self.scanParams = scanParams
# 5D array of mscan magnitude data (pos z, pos x, pos y, freq, amplitude)
self.magResp = np.zeros((numZPts, width_steps, len_steps, numFreq, numAmp))
self.magResp[:, :, :, :, :] = np.NaN
# 5D array of mscan phase data
self.phaseResp = np.zeros((numZPts, width_steps, len_steps, numFreq, numAmp))
self.phaseResp[:, :, :, :, :] = np.NaN
# noise calculations for FFT noise (FD = Fourier domain) above and below stim frequency
# Mean= mean noise, SD = standard deviation
# num pts is deermined by noise bandiwth in mscan processing opts
self.FDnoiseAboveStimFreqMean = np.zeros((numZPts, width_steps, len_steps, numFreq, numAmp))
self.FDnoiseAboveStimFreqMean[:, :, :, :, :] = np.NaN
self.FDnoiseAboveStimFreqSD = np.zeros((numZPts, width_steps, len_steps, numFreq, numAmp))
self.FDnoiseAboveStimFreqSD[:, :, :, :, :] = np.NaN
self.FDnoiseBelowStimFreqMean = np.zeros((numZPts, width_steps, len_steps, numFreq, numAmp))
self.FDnoiseBelowStimFreqMean[:, :, :, :, :] = np.NaN
self.FDnoiseBelowStimFreqSD = np.zeros((numZPts, width_steps, len_steps, numFreq, numAmp))
self.FDnoiseBelowStimFreqSD[:, :, :, :, :] = np.NaN
# last valid indeixes
self.freqIdx = -1
self.ampIdx = -1
self.widthStep = -1
self.lengthStep = -1
self.xRes = np.NaN
self.yRes = np.NaN
self.zRes = np.NaN
# class reprenesenting the psoition, frequency and intensity of the mscan
class MscanPosAndStim:
def __init__(self):
self.posLenStep = 0 # the length position, in step #
self.posWidthStep = 0 # the width position, in step #
self.freqIdx = 0 # index of stimulus frequency in audio paras frequency array
self.ampIdx = 0 # index of stimlus amplitude in audio paras amltide array
self.stimFreq = 1e3 # stimulus frequency
self.numFreq = 0
self.numAmp = 0
self.stimFreq2 = 1e3 # second stimulus frequency (F1 for DP)
# spke removal for mscan
def spikeRemoval(mscanTD, spikeThresh):
td_diff = np.diff(mscanTD)
spike_idx = np.where(np.abs(td_diff) > spikeThresh)
spike_idx2 = spike_idx[0][:] + 1
spike_corr = np.zeros(len(mscanTD))
spike_corr[spike_idx2] = -td_diff[spike_idx]
spike_corr_cum = np.cumsum(spike_corr)
mscanTD = mscanTD + spike_corr_cum
return mscanTD
# process mscna data give
# oct_data: 3D array of complex FFT indiexed by (trigger, zpos, trial)
def processMscanData(oct_data, mscanPosAndStim, scanParams, audioParams, procOpts, OCTtrigRate, mscanTuningCurveList, mscanRegionData, volData):
scanP = scanParams
mag = None
phase = None
rawdata = oct_data
shp = rawdata.shape
# rawdata = trigsPerPt = np.ceil(galv.settleTime * OCTtriggerRate)
numTrigs = shp[0]
numZPts = shp[1]
numTrials = shp[2]
mscan = MScanData()
if DebugLog.isLogging:
DebugLog.log("Mscan.processMscanData(): numTrigs %d numTrials= %d OCTtrigRate= %g" % (numTrigs, numTrials, OCTtrigRate))
t1 = time.time()
if mag is None:
mag = np.abs(rawdata)
mag = np.clip(mag, 1, np.inf)
mag = 20*np.log10(mag)
if DebugLog.isLogging:
DebugLog.log("Mscan.processMscanData(): (before averaging) mag.shape= " + repr(mag.shape))
# average all trials
mag = np.mean(mag, 2)
# average all triggers
mag = np.mean(mag, 0)
avgAlineTime = time.time() - t1
if DebugLog.isLogging:
DebugLog.log("Mscan.processMscanData(): (after averaging) avg aline time= %0.4f mag.shape= %s" % (avgAlineTime, repr(mag.shape)))
mscan.avgAline = mag
mscan.posLenStep = mscanPosAndStim.posLenStep
mscan.posWidthStep = mscanPosAndStim.posWidthStep
freqIdx = mscanPosAndStim.freqIdx
ampIdx = mscanPosAndStim.ampIdx
# if single pt mscan, then select pt of maximum SNR to perform FFT
DebugLog.log("Mscan.processMscanData(): posLenStep= %d posWidthStep= %d freqIdx= %d ampIdxs= %d" % (mscan.posLenStep, mscan.posWidthStep, freqIdx, ampIdx))
mscan.stimFreqIdx = freqIdx
mscan.stimAmpIdx = ampIdx
trigRate = OCTtrigRate
mscan.trialTime = numTrigs / trigRate
mscan.mscanSampleRate = trigRate
mscan.maxFFTFreq = trigRate/2
zeroPad = procOpts.FFTZeroPadFactor
numfftpts = int(2 ** np.round(np.log2(numTrigs*zeroPad)))
numfftpts_2 = numfftpts // 2
winfcn = np.hanning(numTrigs)
stimFreq = mscanPosAndStim.stimFreq
stimFreq2 = mscanPosAndStim.stimFreq2
mscan.stimFreq = stimFreq
mscan.stimFreq2 = stimFreq2
mscan.DPFreq = None
if stimFreq2 is not None:
mscan.F1freq = stimFreq2
mscan.DPfreq = 2*stimFreq2 - stimFreq # DP frequency = 2F1 - F2
rad_to_nm = procOpts.centerWavelength / (4 * np.pi * procOpts.refractiveIndex)
win_magcorr = 2
scanP = scanParams
# scanP.ptList=None
# initialize aggregate data if necesary
if (scanP.lengthSteps == 1) and (scanP.widthSteps == 1) or scanP.pattern == ScanPattern.ptsList:
if mscanTuningCurveList is None: # initialize list of tuning curves
# points list mscan
audioP = audioParams
tcurves = []
if scanP.ptList is None:
numPts = 1
else:
numPts = len(scanP.ptList)
numPts = max((numPts, 1))
for n in range(0, numPts):
tcurves.append(MscanTuningCurve(audioP))
mscanTuningCurveList = tcurves
# volume or B mscan
else:
if volData is None:
mscanRegionData = MscanRegionData(audioParams, scanParams, procOpts, numZPts)
volData = VolumeScan.VolumeData()
volData.scanParams = scanParams
volData.volumeImg = np.zeros((scanP.widthSteps, numZPts, scanP.lengthSteps))
volData.xPixSize = 1e3*scanP.length/scanP.lengthSteps
volData.yPixSize = 1e3*scanP.width/scanP.widthSteps
volData.zPixSize = procOpts.zRes
volData.zPixSize_corr = volData.zPixSize
volData.xPixSize_corr = volData.zPixSize_corr
volData.yPixSize_corr = volData.zPixSize_corr
lenSteps_corr = round(scanP.length/volData.xPixSize_corr)
widthteps_corr = round(scanP.width/volData.yPixSize_corr)
volData.volumeImg_corr_aspect = np.zeros((widthteps_corr, numZPts, lenSteps_corr))
if ((scanP.lengthSteps == 1) and (scanP.widthSteps == 1)) or (scanP.pattern == ScanPattern.ptsList):
zroi_indices = procOpts.singlePt_zROI_indices
sprd = procOpts.singlePt_zROI_spread
scanPtNum = mscanPosAndStim.posLenStep
if len(zroi_indices) > 1:
idx = zroi_indices[scanPtNum]
else:
idx = zroi_indices[0]
DebugLog.log("Mscan.processMscanData(): idx= %s" % repr(idx))
# find the z point where the magnitude response is maximum (max SNR)
idx1 = max(idx - sprd, 0)
idx2 = min(idx + sprd, len(mag) - 1)
DebugLog.log("Mscan.processMscanData(): idx1= %d idx2= %d" % (idx1, idx2))
maxSNRidx = np.argmax(mag[idx1:idx2])
mscan.zROIidx = (idx1, idx2)
mscan.maxSNR_Zidx = idx1 + maxSNRidx
# calculate time domain phase
if phase is None:
dataRgn = rawdata[:, idx1 + maxSNRidx, :]
ph = np.angle(dataRgn)
if DebugLog.isLogging:
DebugLog.log("Mscan.processMscanData(): dataRgn.shape= " + repr(dataRgn.shape) + " ph.shape= " + repr(ph.shape) + " maxSNRidx= " + repr(maxSNRidx))
else:
ph = phase[:, idx1 + maxSNRidx, :]
ph = ph / (2*np.pi)
if DebugLog.isLogging:
DebugLog.log("Mscan.processMscanData(): ph.shape= " + repr(ph.shape) + " maxSNRidx= " + repr(maxSNRidx))
# unwrap
#plt.plot(np.real(dataRgn[:, 0]), '-b', np.imag(dataRgn[:, 0]), '-r')
#plt.show()
unwrapThreshold = np.pi
ph = np.unwrap(ph, discont=unwrapThreshold, axis=0)
if DebugLog.isLogging:
DebugLog.log("Mscan.processMscanData(): ph.shape= " + repr(ph.shape))
#plt.plot(ph)
#plt.show()
if audioParams.stimOffset > 0:
i1 = int(trigRate*audioParams.stimOffset*1e-3)
i2 = idx1 + int(trigRate*audioParams.stimDuration*1e-3)
ph = ph[i1:i2, :]
# remove DC/LF components by subtracting from mean
ph_mean = np.mean(ph, 0)
shp = ph.shape
ph_mean = np.tile(ph_mean, (shp[0], 1))
# ph_mean = np.transpose(ph_mean)
if DebugLog.isLogging:
DebugLog.log("Mscan.processMscanData(): ph.shape= %s ph_mean.shape= %s " % (repr(ph.shape), repr(ph_mean.shape)))
mscan.phaseAllTrials = copy.copy(ph) * rad_to_nm
# average all trials
ph = np.mean(ph, 1)
mscan.TDnoiseSD = np.std(ph)
# convert to nanometers
ph = ph * rad_to_nm
if DebugLog.isLogging:
DebugLog.log("Mscan.processMscanData(): ph.shape= " + repr(ph.shape))
if procOpts.spikeRemoval:
ph = spikeRemoval(ph, procOpts.spikeThreshold_nm)
# take the FFT
mscan_fft = np.fft.fft(ph * winfcn, numfftpts)
mscan_fft = 2*mscan_fft[0:numfftpts_2] * win_magcorr / numTrigs
if DebugLog.isLogging:
DebugLog.log("Mscan.processMscanData(): numfftpts= %d mscan_fft.shape= %s " % (numfftpts, repr(mscan_fft.shape)))
fftmag = np.abs(mscan_fft)
fftphase = np.angle(mscan_fft)
# find the magnitude and phase response at the stimulus frequency
idx = np.floor(numfftpts*stimFreq/trigRate)
i1 = idx - 2*zeroPad
i1 = max(i1, 0)
i2 = idx + 2*zeroPad
i2 = min(i2, len(fftmag))
if DebugLog.isLogging:
DebugLog.log("Mscan.processMscanData(): i1= %d i2= %d maxIdx= " % (i1, i2))
maxIdx = np.argmax(fftmag[i1:i2])
if DebugLog.isLogging:
DebugLog.log("Mscan.processMscanData(): i1= %d i2= %d maxIdx= %d" % (i1, i2, maxIdx))
mscan.stimRespMag = fftmag[i1 + maxIdx]
mscan.stimRespPhase = fftphase[i1 + maxIdx]
if stimFreq2 is not None:
idx = np.floor(numfftpts*stimFreq2/trigRate)
i1 = idx - 2*zeroPad
i1 = max(i1, 0)
i2 = idx + 2*zeroPad
i2 = min(i2, len(fftmag))
maxIdx = np.argmax(fftmag[i1:i2])
if DebugLog.isLogging:
DebugLog.log("Mscan.processMscanData(): i1= %d i2= %d maxIdx= %d" % (i1, i2, maxIdx))
mscan.F1RespMag = fftmag[i1 + maxIdx]
mscan.F1RespPhase = fftphase[i1 + maxIdx]
idx = np.floor(numfftpts*mscan.DPfreq/trigRate)
i1 = idx - 2*zeroPad
i1 = max(i1, 0)
i2 = idx + 2*zeroPad
i2 = min(i2, len(fftmag))
maxIdx = np.argmax(fftmag[i1:i2])
if DebugLog.isLogging:
DebugLog.log("Mscan.processMscanData(): i1= %d i2= %d maxIdx= %d" % (i1, i2, maxIdx))
mscan.DPRespMag = fftmag[i1 + maxIdx]
mscan.DPRespPhase = fftphase[i1 + maxIdx]
# calculate noise
noisePts = np.ceil(numTrigs * procOpts.noiseBandwidth / trigRate)
noisePts = noisePts*zeroPad
noiseRgn = fftmag[i2:(i2 + noisePts)]
mscan.FDnoiseAboveStimFreqMean = np.mean(noiseRgn)
mscan.FDnoiseAboveStimFreqSD = np.std(noiseRgn)
noiseRgn = fftmag[(i1 - noisePts):i1]
mscan.FDnoiseBelowStimFreqMean = np.mean(noiseRgn)
mscan.FDnoiseBelowStimFreqSD = np.std(noiseRgn)
# fill in aggregate data
scanPtNum = mscanPosAndStim.posLenStep
tcurve = mscanTuningCurveList[scanPtNum]
tcurve.magResp[freqIdx, ampIdx] = mscan.stimRespMag
tcurve.phaseResp[freqIdx, ampIdx] = mscan.stimRespPhase
tcurve.phaseRespUnwrapped[freqIdx, ampIdx] = mscan.stimRespPhase
tcurve.phaseRespUnwrapped[:, ampIdx] = np.unwrap(tcurve.phaseRespUnwrapped[:, ampIdx], axis=0)
if stimFreq2 is not None:
tcurve.F1Resp[freqIdx, ampIdx] = mscan.F1RespMag
tcurve.F1phaseResp[freqIdx, ampIdx] = mscan.F1RespPhase
tcurve.F1phaseRespUnwrapped[freqIdx, ampIdx] = mscan.F1RespPhase
tcurve.F1phaseRespUnwrapped[:, ampIdx] = np.unwrap(tcurve.F1phaseRespUnwrapped[:, ampIdx], axis=0)
tcurve.DPResp[freqIdx, ampIdx] = mscan.DPRespMag
tcurve.DPphaseResp[freqIdx, ampIdx] = mscan.DPRespPhase
tcurve.DPphaseRespUnwrapped[freqIdx, ampIdx] = mscan.DPRespPhase
tcurve.DPphaseRespUnwrapped[:, ampIdx] = np.unwrap(tcurve.DPphaseRespUnwrapped[:, ampIdx], axis=0)
tcurve.FDnoiseAboveStimFreqMean[freqIdx, ampIdx] = mscan.FDnoiseAboveStimFreqMean
tcurve.FDnoiseAboveStimFreqSD[freqIdx, ampIdx] = mscan.FDnoiseAboveStimFreqSD
tcurve.FDnoiseBelowStimFreqMean[freqIdx, ampIdx] = mscan.FDnoiseBelowStimFreqMean
tcurve.FDnoiseBelowStimFreqSD[freqIdx, ampIdx] = mscan.FDnoiseBelowStimFreqSD
if stimFreq2 is not None:
tcurve.F1phaseRespUnwrapped[:, ampIdx] = np.unwrap(tcurve.F1phaseRespUnwrapped[:, ampIdx], axis=0)
tcurve.DPphaseRespUnwrapped[:, ampIdx] = np.unwrap(tcurve.DPphaseRespUnwrapped[:, ampIdx], axis=0)
else: # B mscan or Volume M scan
# calculate time domain phase
t1 = time.time()
if phase is None:
ph = np.angle(rawdata)
if DebugLog.isLogging:
DebugLog.log("Mscan.processMscanData(): rawdata.shape= " + repr(rawdata.shape) + " ph.shape= " + repr(ph.shape))
else:
ph = phase / (2 * np.pi)
if DebugLog.isLogging:
DebugLog.log("Mscan.processMscanData(): ph.shape= " + repr(ph.shape))
phaseCalcTime= time.time() - t1
# unwrap
#plt.plot(np.real(dataRgn[:, 0]), '-b', np.imag(dataRgn[:, 0]), '-r')
#plt.show()
unwrapThreshold = np.pi
t1 = time.time()
ph = np.unwrap(ph, discont=unwrapThreshold, axis=0)
unwrapTime = time.time() - t1
if DebugLog.isLogging:
DebugLog.log("Mscan.processMscanData(): unwrap time=%0.4f ph.shape= %s" % (unwrapTime, repr(ph.shape)))
#plt.plot(ph)
#plt.show()
# remove DC/LF components by subtracting from mean
t1 = time.time()
ph_mean = np.mean(ph, 0)
if DebugLog.isLogging:
DebugLog.log("Mscan.processMscanData(): ph_mean.shape= " + repr(ph_mean.shape))
ph_mean = np.tile(ph_mean, (numTrigs, 1, 1))
if DebugLog.isLogging:
DebugLog.log("Mscan.processMscanData(): ph_mean.shape= " + repr(ph_mean.shape))
ph = ph - ph_mean
if DebugLog.isLogging:
DebugLog.log("Mscan.processMscanData(): ph.shape= " + repr(ph.shape))
# average all trials
ph = np.mean(ph, 2)
phaseMeanSubTime = time.time() - t1
mscan.TDnoiseSD = np.std(ph)
# convert to nanometers
ph = ph * rad_to_nm
#if procOpts.mscan.spikeRemoval:
# ph = spikeRemoval(ph, procOpts.mscan.spikeThreshold_nm)
# take the FFT
t1 = time.time()
winfcn = np.tile(winfcn, (numZPts, 1))
winfcn = np.transpose(winfcn)
win_ph = ph * winfcn
winFcnTime = time.time() - t1
if DebugLog.isLogging:
DebugLog.log("Mscan.processMscanData(): ph.shape= %s winfcn.shape= %s win_ph.dtype= %s" % (repr(ph.shape), repr(winfcn.shape), repr(win_ph.dtype)))
#mscan_fft = np.fft.fft(win_ph, numfftpts, 0)
#mscan_fft = mscan_fft[0:numfftpts_2, :] * win_magcorr / numTrigs
# preallocate result array, this makes a HUGE speed diffrence when using multiprocesing
fft_output_pts = numfftpts // 2
if numfftpts % 2 == 0:
fft_output_pts += 1
mscan_fft = np.zeros((fft_output_pts, win_ph.shape[1]), dtype=np.complex)
t1 = time.time()
mscan_fft[:, :] = np.fft.rfft(win_ph, n=numfftpts, axis=0)
fftTime = time.time() - t1
if DebugLog.isLogging:
DebugLog.log("Mscan.processMscanData(): fft time= %0.4f numfftpts= %d mscan_fft.shape= %s " % (fftTime, numfftpts, repr(mscan_fft.shape)))
mscan_fft = 2 * mscan_fft * win_magcorr / numTrigs
t1 = time.time()
#fftmag = np.abs(mscan_fft)
#fftphase = np.angle(mscan_fft)
magPhaseCalcTime = time.time() - t1
# find the magnitude and phase response at the stimulus frequency
t1 = time.time()
idx = np.floor(numfftpts*stimFreq/trigRate)
i1 = idx - 2*zeroPad
i1 = max(i1, 0)
i2 = idx + 2*zeroPad
#i2 = min(i2, fftmag.shape[0])
i2 = min(i2, mscan_fft.shape[0])
if DebugLog.isLogging:
DebugLog.log("Mscan.processMscanData(): i1= %d i2= %d " % (i1, i2))
numZ = mscan_fft.shape[1]
mscan.stimRespMag = np.zeros(numZ)
mscan.stimRespPhase = np.zeros(numZ)
for n in range(0, numZ):
fftmag = np.abs(mscan_fft[i1:i2, n])
#maxIdx = np.argmax(fftmag[i1:i2, n], 0)
maxIdx = np.argmax(fftmag, 0)
# DebugLog.log("MscanProtocol.processData(): i1= %d i2= %d maxIdx= %d" % (i1, i2, maxIdx))
mscan.stimRespMag[n] = fftmag[maxIdx]
mscan.stimRespPhase[n] = np.angle(mscan_fft[i1+maxIdx, n])
maxMagCalcTime = time.time() - t1
if DebugLog.isLogging:
DebugLog.log("Mscan.processMscanData(): mscan.stimRespMag.shape= %s time= %0.4f" % (repr(mscan.stimRespMag.shape), maxMagCalcTime))
# calculate noise
t1 = time.time()
noisePts = np.ceil(numTrigs * procOpts.noiseBandwidth / trigRate)
noisePts = noisePts*zeroPad
#noiseRgn = fftmag[i2:(i2 + noisePts), :]
noiseRgn = np.abs(mscan_fft[i2:(i2 + noisePts), :])
mscan.FDnoiseAboveStimFreqMean = np.mean(noiseRgn, 0)
mscan.FDnoiseAboveStimFreqSD = np.std(noiseRgn, 0)
#noiseRgn = fftmag[(i1 - noisePts):i1, :]
noiseRgn = np.abs(mscan_fft[(i1 - noisePts):i1, :])
mscan.FDnoiseBelowStimFreqMean = np.mean(noiseRgn, 0)
mscan.FDnoiseBelowStimFreqSD = np.std(noiseRgn, 0)
noiseCalcTime = time.time() - t1
if DebugLog.isLogging:
DebugLog.log("Mscan.processMscanData(): mscan.stimRespMag.FDnoiseAboveStimFreqMean= %s" % (repr(mscan.FDnoiseAboveStimFreqMean.shape)))
t1 = time.time()
rgnData = mscanRegionData
# rgnData = self.aggregateData.mscanRegionData
posWidthStep = mscan.posWidthStep
posLenStep = mscan.posLenStep
freqIdx = mscan.stimFreqIdx
ampIdx = mscan.stimAmpIdx
rgnData.magResp[:, posWidthStep, posLenStep, freqIdx, ampIdx] = mscan.stimRespMag
rgnData.phaseResp[:, posWidthStep, posLenStep, freqIdx, ampIdx] = mscan.stimRespPhase
rgnData.FDnoiseAboveStimFreqMean[:, posWidthStep, posLenStep, freqIdx, ampIdx] = mscan.FDnoiseAboveStimFreqMean
rgnData.FDnoiseAboveStimFreqSD[:, posWidthStep, posLenStep, freqIdx, ampIdx] = mscan.FDnoiseAboveStimFreqSD
rgnData.FDnoiseBelowStimFreqMean[:, posWidthStep, posLenStep, freqIdx, ampIdx] = mscan.FDnoiseBelowStimFreqMean
rgnData.FDnoiseBelowStimFreqSD[:, posWidthStep, posLenStep, freqIdx, ampIdx] = mscan.FDnoiseBelowStimFreqSD
rgnData.freqIdx = freqIdx
rgnData.ampIdx = ampIdx
rgnData.widthStep = posWidthStep
rgnData.lengthStep = posLenStep
rgnData.xRes = 1e3*scanP.length/scanP.lengthSteps
rgnData.yRes = 1e3*scanP.width/scanP.widthSteps
rgnData.zRes = procOpts.zRes
nL = procOpts.bscanNormLow
nH = procOpts.bscanNormHigh
nRng = nH - nL
dataAssignTime = time.time() - t1
if DebugLog.isLogging:
DebugLog.log("Mscan.processMscanData(): nL= %g nH=%g nRng= %g" % (nL, nH, nRng))
t1 = time.time()
# remap range to 0...1
aline = (mscan.avgAline - nL)/nRng
# remap range to 0 ... to 2^16 - 1
aline16b = aline*65535
aline16b = np.clip(aline16b, 0, 65535)
aline16b = np.require(aline16b, 'uint16')
volData.volumeImg[posWidthStep, :, posLenStep] = aline16b
alineCalcTime = time.time() - t1
if DebugLog.isLogging:
DebugLog.log("Mscan.processMscanData(): \n\tavgAlineTime= %0.4f \n\tphaseCalcTime= %0.4f \n\tphaseMeanSubTime= %0.4f" % (avgAlineTime, phaseCalcTime, phaseMeanSubTime))
DebugLog.log("\tunwrapTime= %0.4f winFcnTime= %0.4f \n\tFFTtime= %0.4f \n\tmagPhaseCalcTime= %0.4f" % (unwrapTime, winFcnTime, fftTime, magPhaseCalcTime))
DebugLog.log("\tmaxMagCalcTime= %0.4f noiseCalcTime= %0.4f \n\tdataAssignTime= %0.4f \n\talineCalcTime= %0.4f" % (maxMagCalcTime, noiseCalcTime, dataAssignTime, alineCalcTime))
mscan.mscanTD = ph
mscan.mscanFFT = mscan_fft
return mscan, mscanTuningCurveList, mscanRegionData, volData
def makeVolMScanBoxROIScanParams(appObj):
xyScanP = appObj.volDataLast.scanParams
DebugLog.log("makeVolMScanBoxROIScanParams: xyScanP= %s" % (repr(xyScanP)))
ul = appObj.vol_plane_proj_gv.ROIBox_pt1 # upper left point
lr = appObj.vol_plane_proj_gv.ROIBox_pt2 # lower right point
# exchange box points if necessary
if ul[1] > lr[1]:
tmp = ul
ul = lr
lr = tmp
DebugLog.log("makeVolMScanBoxROIScanParams: ul= %s lr= %s" % (repr(ul), repr(lr)))
if ul is not None and lr is not None:
roi_dw = np.abs(lr[0] - ul[0]) # roi delta width
roi_dh = np.abs(lr[1] - ul[1]) # roi delta height
roi_ow = ul[0] + (roi_dw / 2)
roi_oh = ul[1] + (roi_dh / 2)
else:
return None
(img_w, img_h) = appObj.vol_plane_proj_gv.getImageWidthHeight()
DebugLog.log("makeVolMScanBoxROIScanParams: img_w= %d img_h= %d roi_ow= %0.3g roi_oh= %0.3g" % (img_w, img_h, roi_ow, roi_oh))
scanP = ScanParams()
scanP.length = roi_dw * xyScanP.length / img_w
scanP.width = roi_dh * xyScanP.width / img_h
rotAng = xyScanP.rotation_Z*np.pi/180
scanP.lengthOffset = xyScanP.lengthOffset + roi_ow * xyScanP.length / img_w
scanP.widthOffset = xyScanP.widthOffset + roi_oh * xyScanP.width / img_h
#scanP.lengthOffset = xyScanP.lengthOffset + np.cos(rotAng)*roi_ow * xyScanP.length / img_w
#scanP.widthOffset = xyScanP.widthOffset +np.sin(rotAng)* roi_oh * xyScanP.width / img_h
scanP.rotation_Z = xyScanP.rotation_Z
xyRes = appObj.volMscan_sampling_dblSpinBox.value()*1e-3
scanP.lengthSteps = int(round(scanP.length / xyRes))
scanP.widthSteps = int(round(scanP.width / xyRes))
DebugLog.log("makeVolMScanBoxROIScanParams: lengthSteps= %d widthSteps= %d" % (scanP.lengthSteps, scanP.widthSteps))
scanP.continuousScan = False
return scanP
def makeVolMScanPolyROIScanParams(appObj, poly = None):
scanP = ScanParams()
if poly is None:
poly = appObj.vol_plane_proj_gv.ROI_poly
DebugLog.log("makeVolMScanPolyROIScanParams: poly= ")
for n in range(0, poly.count()):
pt = poly.at(n)
DebugLog.log("\t(%0.3g, %0.3g)" % (pt.x(), pt.y()))
rect = poly.boundingRect() # get the bounding rectangle of the polygon
ul = rect.topLeft()
lr = rect.bottomRight()
DebugLog.log("makeVolMScanPolyROIScanParams: ul= %s lr= %s" % (repr(ul), repr(lr)))
# exchange box points if necessary
if ul.y() > lr.y():
tmp = ul
ul = lr
lr = tmp
DebugLog.log("makeVolMScanPolyROIScanParams: (after exchange) ul= %s lr= %s" % (repr(ul), repr(lr)))
if ul is not None and lr is not None:
roi_dw = np.abs(lr.x() - ul.x()) # roi delta width
roi_dh = np.abs(lr.y() - ul.y()) # roi delta height
roi_ow = ul.x() + (roi_dw / 2)
roi_oh = ul.y() + (roi_dh / 2)
else:
return None
xyScanP = appObj.volDataLast.scanParams
(img_w, img_h) = appObj.vol_plane_proj_gv.getImageWidthHeight()
DebugLog.log("makeVolMScanBoxROIScanParams: img_w= %d img_h= %d roi_ow= %0.3g roi_oh= %0.3g" % (img_w, img_h, roi_ow, roi_oh))
scanP = ScanParams()
scanP.length = roi_dw * xyScanP.length / img_w
scanP.width = roi_dh * xyScanP.width / img_h
rotAng = xyScanP.rotation_Z*np.pi/180
scanP.lengthOffset = xyScanP.lengthOffset + roi_ow * xyScanP.length / img_w
scanP.widthOffset = xyScanP.widthOffset + roi_oh * xyScanP.width / img_h
# scanP.lengthOffset = xyScanP.lengthOffset + np.cos(rotAng)*roi_ow * xyScanP.length / img_w
# scanP.widthOffset = xyScanP.widthOffset +np.sin(rotAng)* roi_oh * xyScanP.width / img_h
scanP.rotation_Z = xyScanP.rotation_Z
xyRes = appObj.volMscan_sampling_dblSpinBox.value()*1e-3
len_steps = int(round(scanP.length / xyRes))
width_steps = int(round(scanP.width / xyRes))
scanP.lengthSteps = len_steps
scanP.widthSteps = width_steps
DebugLog.log("makeVolMScanPolyROIScanParams: lengthSteps= %d widthSteps= %d" % (scanP.lengthSteps, scanP.widthSteps))
scanP.continuousScan = False
# create ROI mask
shp = (len_steps, width_steps)
scanP.boxROIMaskXY = np.zeros(shp, np.bool)
for w in range(0, width_steps):
for l in range(0, len_steps):
# calculate the point based on the upper-left corner
# the X direction is negative in the left, positive to the right
# the y direction is negative in the top, positive in the bottom
x = ul.x() + roi_dw * l / len_steps
y = ul.y() + roi_dh * w / width_steps
ptf = QtCore.QPointF(x, y)
isInside = poly.containsPoint(ptf, QtCore.Qt.OddEvenFill)
DebugLog.log("makeVolMScanPolyROIScanParams: x= %0.3g y %0.3g isInside= %s" % (x, y, isInside))
scanP.boxROIMaskXY[l, w] = isInside
return scanP
def makeVolMScanFreeROIScanParams(appObj):
# since the free draw ROI also consists of a polygon, we can use same method
# as the polygon ROI
poly = appObj.vol_plane_proj_gv.freedraw_poly
scanP = makeVolMScanPolyROIScanParams(appObj, poly)
return scanP
def makeMultiPtMScanParams(appObj):
scanP = ScanParams()
ptsList = appObj.mscanPtsList
scanP.lengthSteps = len(ptsList)
scanP.widthSteps = 1
xyScanP = appObj.volDataLast.scanParams
zROI = appObj.volDataLast.zROI
shp = appObj.vol_bscan_gv.imgData.shape
dzroi = zROI[1] - zROI[0]
dz = shp[0]
dx = shp[1]
print("makeMultiPtMScanParams: dx= %d dz= %d" % (dx, dz))
zROIIndices = []
scanP.ptList = []
widthSteps = xyScanP.widthSteps
scanP.rotation_Z = xyScanP.rotation_Z
scanP.lengthOffset = xyScanP.lengthOffset
scanP.widthOffset = xyScanP.widthOffset
scanP.pattern = ScanPattern.ptsList
print("makeMultiPtMScanParams: ptsList= ")
for pt in ptsList:
wStep = pt[0]
w = xyScanP.width * (wStep - (widthSteps / 2)) / widthSteps
l = xyScanP.length * pt[1]/dx
scanP.ptList.append((w, l))
#z = round(dzroi*(pt[2] + (dz / 2)/dz))
z = round(dzroi*(pt[2] + (dz/2))/dz)
zROIIndices.append(z)
print("makeMultiPtMScanParams: pt= (%0.3f, %0.3f)" % (pt[0], pt[1]), " w= %0.3f" % w, " l= %0.3f" % l, " z=", z)
return scanP, zROIIndices
def makeMscanScanParamsAndZROI(appObj):
scanP = ScanParams()
zROIIndices = []
zROIspread = appObj.mscan_zROIlspread_spinBox.value()
roiBegin = -1
roiEnd = -1
if appObj.mscan_single_pt_button.isChecked():
scanP.length = 0
scanP.width = 0
scanP.lengthSteps = 1
scanP.widthSteps = 1
imgScanP = appObj.imgDataScanParams
DebugLog.log ("makeMscanScanParamsAndZROI imgScanP= %s" % (repr(imgScanP)))
# pt = self.bscan_img_gv.ptsList[0]
pt = appObj.bscan_img_gv.singlePt
img_w = appObj.imgdata_8b.shape[1]
img_h = appObj.imgdata_8b.shape[0]
DebugLog.log ("makeMscanScanParamsAndZROI pt= %s img_w=%d img_h= %d " % (repr(pt), img_w, img_h))
scanP.lengthOffset = (pt[0] - (img_w / 2) ) * imgScanP.length / img_w + imgScanP.lengthOffset
scanP.widthOffset = imgScanP.widthOffset
scanP.rotation_Z = imgScanP.rotation_Z
roiBegin = appObj.imgdata_zROI[0]
roiEnd = appObj.imgdata_zROI[1]
zROIIndices.append(pt[1])
elif appObj.vol_mscan_multipt_button.isChecked(): # multi-point mscan
DebugLog.log ("makeMscanScanParamsAndZROI multi point scan")
scanP, zROIIndices = makeMultiPtMScanParams(appObj)
zROI = appObj.volDataLast.zROI
roiBegin = zROI[0]
roiEnd = zROI[1]
elif appObj.bmscan_box_region_button.isChecked():
imgScanP = appObj.imgDataScanParams
DebugLog.log ("makeMscanScanParamsAndZROI imgScanP= %s" % (repr(imgScanP)))
#pt1 = self.bscan_img_gv.ROIBox_pt1
#pt2 = self.bscan_img_gv.ROIBox_pt2
(pt1, pt2) = appObj.bmscan_box_rgn
# calculate (x1, y1) as upper left corner and (x2, y2) as lower right corner (with (0,0) being top left corner)
x1 = min(pt1[0], pt2[0])
x2 = max(pt1[0], pt2[0])
y1 = min(pt1[1], pt2[1])
y2 = max(pt1[1], pt2[1])
img_w = appObj.imgdata_8b.shape[1]
img_h = appObj.imgdata_8b.shape[0]
DebugLog.log ("makeMscanScanParamsAndZROI pt1= %s pt2= %s img_w=%d img_h= %d " % (repr(pt1), repr(pt2), img_w, img_h))
scanP.width = 0
# scanP.lengthSteps = int(x2 - x1)
scanP.lengthSteps = appObj.BMscan_numSteps_spinBox.value()
scanP.widthSteps = 1
dw = np.abs(x2 - x1)
scanP.length = imgScanP.length*dw/img_w
x_mid = (x1 + x2)/2
scanP.lengthOffset = (x_mid - (img_w / 2) ) * imgScanP.length / img_w + imgScanP.lengthOffset
scanP.widthOffset = imgScanP.widthOffset
scanP.rotation_Z = imgScanP.rotation_Z
roiBegin = appObj.imgdata_zROI[0]
roiEnd = appObj.imgdata_zROI[1]
else:
volBox = appObj.vol_boxROI_pushButton.isChecked()
volPoly = appObj.vol_polyROI_pushButton.isChecked()
volFree = appObj.vol_freeROI_pushButton.isChecked()
if volBox:
scanP = makeVolMScanBoxROIScanParams(appObj)
elif volPoly:
scanP = makeVolMScanPolyROIScanParams(appObj)
elif volFree:
scanP = makeVolMScanFreeROIScanParams(appObj)
else:
scanP = None # this case indicates that no valid region has been selected
roiBegin = appObj.imgdata_zROI[0]
roiEnd = appObj.imgdata_zROI[1]
roiSize = roiEnd - roiBegin
# ensure ROI is aligned to multiple of 4
# this is required if data is 16-bit
if roiSize % 4 != 0:
roiEnd += 4 - roiSize % 4
DebugLog.log ("makeMscanScanParamsAndZROI scanP= %s" % (repr(scanP)))
DebugLog.log ("makeMscanScanParamsAndZROI roiBegin= %d roiEnd= %d zROIindices= %s" % (roiBegin, roiEnd, repr(zROIIndices)))
return (scanP, roiBegin, roiEnd, zROIIndices, zROIspread)
def getXYPos(lenStep, widthStep, scanParams):
scanP = scanParams
rotRad = np.pi*scanP.rotation_Z/180
# rotation effect on the length offset
cos_rot = np.cos(rotRad)
sin_rot = np.sin(rotRad)
# rotation effect on the width offset
wo_rot = rotRad + np.pi/2
wo_cos_rot = np.cos(wo_rot)
wo_sin_rot = np.sin(wo_rot)
if scanP.pattern == ScanPattern.ptsList:
pt = scanP.ptList[lenStep]
if scanP.lengthSteps == 1: # single point scan
xPos = pt[0]
yPos = pt[1]
else: # multi point scan
w = pt[0]
l = pt[1]
# where scan is along the length before accounting for offset and rotation
len_offset = l + scanP.lengthOffset
# x and y offsets contributing by the length step
len_xOffset = l*cos_rot
len_yOffset = l*sin_rot
# where scan is along the width before accounting for offset and rotation
width_offset = w + scanP.widthOffset
# x and y offsets contributing by the width step
width_xOffset = w*wo_cos_rot
width_yOffset = w*wo_sin_rot
xPos = len_xOffset + width_xOffset
yPos = len_yOffset + width_yOffset
else: # region mscan
hsl = scanP.length / 2 # half scan length
hsw = scanP.width / 2 # half scan width
# where scan is along the length before accounting for offset and rotation
len_offset = -hsl + lenStep * scanP.length / scanP.lengthSteps
# x and y offsets contributing by the length step
len_xOffset = len_offset*cos_rot + scanP.lengthOffset*cos_rot
len_yOffset = len_offset*sin_rot + scanP.lengthOffset*sin_rot
# where scan is along the width before accounting for offset and rotation
width_offset = -hsw + widthStep * scanP.width / scanP.widthSteps
# x and y offsets contributing by the width step
width_xOffset = width_offset*wo_cos_rot + scanP.widthOffset*wo_cos_rot
width_yOffset = width_offset*wo_sin_rot + scanP.widthOffset*wo_sin_rot
xPos = len_xOffset + width_xOffset
yPos = len_yOffset + width_yOffset
return (xPos, yPos)
def makeAudioOutput(audioParams, audioHW, spkNum, f, a, freqStep, ampStep, freq2=None):
outputRate = audioHW.DAQOutputRate
trialDur = 1e-3*audioParams.getTrialDuration(a)
trialPts = np.ceil(trialDur * outputRate)
spkOut = None
DebugLog.log("makeAudioOutput: spkNum=%d trialDur=%f trialPts=%d stimType= %s" % (spkNum, trialDur, trialPts, audioParams.stimType))
if audioParams.stimType == AudioStimType.CUSTOM_SCRIPT:
exec('import %s' % audioParams.customScript)
spkOut, attenLvl = eval('%s.makeAudioOutput(audioParams, audioHW, spkNum, f, a, freqStep, ampStep)' % audioParams.customScript)
else:
if spkNum == 1 and (audioParams.stimType == AudioStimType.TONE_LASER):
spkOut = np.zeros((trialPts))
laserStimDur = audioParams.stimDuration*1e-3
stimPts = int(np.ceil(laserStimDur * outputRate ))
DebugLog.log("makeAudioOutput: laserStimDurr=%f stimPts=%d" % (laserStimDur, stimPts))
i1 = int(np.ceil(outputRate*1e-3*audioParams.stimOffset))