-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathdualscope.orig
executable file
·1138 lines (981 loc) · 39 KB
/
dualscope.orig
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
#!/usr/bin/env python
"""
Oscilloscope + spectrum analyser in Python for the NIOS server.
Modified version from the original code by R. Fearick.
- Read the output from the NIOS server through a program
named 'receive'. Source code included.
Giuseppe Venturini, July 2012-2013
Original copyright notice follows. The same license applies.
------------------------------------------------------------
Copyright (C) 2008, Roger Fearick, University of Cape Town
This program 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 2
of the License, or (at your option) any later version.
This program 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 this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
------------------------------------------------------------
Version 0.1
This code provides a two-channel oscilloscope and spectrum analyzer.
Dependencies:
Python 2.6+
numpy -- numerics, fft
PyQt4, PyQwt5 -- gui, graphics
Optional packages:
pyspectrum
ethc
The data is acquired through either:
- an external program 'receive', included in the package,
to be compiled through 'gcc -O2 -o receive ethc.c', which is then accessed
through the subprocess module.
- The python bindings to the 'ethc.c' file, generated with pybindgen.
Typically, a modification of the Python path and ld library is necessary,
like this:
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:.
export PYTHONPATH=$PYTHONPATH:.
- extending the package:
Any python module providing an interface:
myinstance.read(self, channel, nchunks, verbose=True)
where:
- the channel is either 1 or 2.
- nchunks is an integer specifying how many 350-samples chunks should
be read, where sampling is 25kHz.
can be used in place of the default one.
The code can be adjusted for different sampling rates and chunks lengths.
The interface, based on qwt, uses a familar 'knob based' layout so that it
approximates an analogue scope.
Traces can be averaged to reduce influence of noise.
A cross hair status display permits the reading of values off the screen.
Printing and exporting CSV and PDF files are provided.
FFT options
- by default we use the periogram algorithm from pyspectrum [1] - not
in Debian stable but available through pypi and easy_install.
[1] https://www.assembla.com/spaces/PySpectrum/wiki
- If 'pyspectrum' is not available, we fallback to using the FFT
method from numpy to compute the PSD.
- Using numpy to calculate the FFT can be forced setting:
USE_NUMPY_FFT = True
in the following code.
- additionally, it is possible to use matplotlib.psd().
-> you need to modify the sources to do so.
INSTALLING pyspectrum
The package pyspectrum can be installed with either:
'easy_install spectrum'
or
'pip install spectrum'
"""
import sys, struct, subprocess, time
from PyQt4 import Qt
from PyQt4 import Qwt5 as Qwt
from numpy import *
import numpy.fft as FFT
# part of this package -- csv interface and toolbar icons
import eth, csvlib, icons
# data setup
CHUNK = 350 # input buffer size in frames
CHANNELS = 2
RATE = 25000 # depends on the server (check for dropped packets)
# scope configuration
DEFAULT_TIMEBASE = 0.01
BOTH12=0
CH1=1
CH2=2
fftbuffersize=CHUNK
samplerate=float(RATE)
scopeheight=500
scopewidth=800
SELECTEDCH=BOTH12
TIMEPENWIDTH=1
FFTPENWIDTH=2
# FFT OPTIONS
# - by default we use the periogram algorithm from pyspectrum [1] - not
# in Debian stable but in pypi:
# Installable with either: 'easy_install spectrum' or 'pip spectrum'
# - If 'pyspectrum' is not available, we fall back to using the FFT
# method from numpy to coputer the PSD. This can be forced with
# USE_NUMPY_FFT = True
# - optionally, it is possible to force the use of matplotlib.psd.
# you need to modify the sources to do so.
# [1] https://www.assembla.com/spaces/PySpectrum/wiki
USE_NUMPY_FFT = False
# status messages
freezeInfo = 'Freeze: Press mouse button and drag'
cursorInfo = 'Cursor Pos: Press mouse button in plot region'
try:
import ethc
print "(II) NATIVE MODULE ethc FOUND"
ETHC_MODULE = True
except ImportError:
print "(WW) NATIVE MODULE ethc NOT FOUND - FALL BACK TO PIPING ./receive data output"
print "(WW) if ethc.py is in the running directory, you may start the scope with:"
print "(WW) LD_LIBRARY_PATH=$LD_LIBRARY_PATH:. ./dualscope.py"
print "(WW) Falling back to shell-piping the output of 'receive'"
ETHC_MODULE = False
try:
import spectrum
print "(II) spectrum MODULE FOUND"
SPECTRUM_MODULE = True
except ImportError:
print "(WW) PSD: spectrum MODULE NOT FOUND"
SPECTRUM_MODULE = False
if USE_NUMPY_FFT:
print "(WW) SPECTRUM MODULE DISABLED in source"
SPECTRUM_MODULE = False
if not SPECTRUM_MODULE:
print "(WW) PSD: using FFTs through NUMPY.fftpack"
# utility classes
class LogKnob(Qwt.QwtKnob):
"""
Provide knob with log scale
"""
def __init__(self, *args):
apply(Qwt.QwtKnob.__init__, (self,) + args)
self.setScaleEngine(Qwt.QwtLog10ScaleEngine())
def setRange(self,minR,maxR,step=.333333):
self.setScale(minR,maxR)
Qwt.QwtKnob.setRange(self, log10(minR), log10(maxR), step)
def setValue(self,val):
Qwt.QwtKnob.setValue(self,log10(val))
class LblKnob:
"""
Provide knob with a label
"""
def __init__(self, wgt, x,y, name, logscale=0):
if logscale:
self.knob=LogKnob(wgt)
else:
self.knob=Qwt.QwtKnob(wgt)
color=Qt.QColor(200,200,210)
self.knob.palette().setColor(Qt.QPalette.Active,
Qt.QPalette.Button,
color )
self.lbl=Qt.QLabel(name, wgt)
self.knob.setGeometry(x, y, 140, 100)
# oooh, eliminate this ...
if name[0]=='o': self.knob.setKnobWidth(40)
self.lbl.setGeometry(x, y+90, 140, 15)
self.lbl.setAlignment(Qt.Qt.AlignCenter)
def setRange(self,*args):
apply(self.knob.setRange, args)
def setValue(self,*args):
apply(self.knob.setValue, args)
def setScaleMaxMajor(self,*args):
apply(self.knob.setScaleMaxMajor, args)
class Scope(Qwt.QwtPlot):
"""
Oscilloscope display widget
"""
def __init__(self, *args):
apply(Qwt.QwtPlot.__init__, (self,) + args)
self.setTitle('Scope');
self.setCanvasBackground(Qt.Qt.white)
# grid
self.grid = Qwt.QwtPlotGrid()
self.grid.enableXMin(True)
self.grid.setMajPen(Qt.QPen(Qt.Qt.gray, 0, Qt.Qt.SolidLine))
self.grid.attach(self)
# axes
self.enableAxis(Qwt.QwtPlot.yRight);
self.setAxisTitle(Qwt.QwtPlot.xBottom, 'Time [s]');
self.setAxisTitle(Qwt.QwtPlot.yLeft, 'Amplitude []');
self.setAxisMaxMajor(Qwt.QwtPlot.xBottom, 10);
self.setAxisMaxMinor(Qwt.QwtPlot.xBottom, 0);
self.setAxisScaleEngine(Qwt.QwtPlot.yRight, Qwt.QwtLinearScaleEngine());
self.setAxisMaxMajor(Qwt.QwtPlot.yLeft, 10);
self.setAxisMaxMinor(Qwt.QwtPlot.yLeft, 0);
self.setAxisMaxMajor(Qwt.QwtPlot.yRight, 10);
self.setAxisMaxMinor(Qwt.QwtPlot.yRight, 0);
# curves for scope traces: 2 first so 1 is on top
self.curve2 = Qwt.QwtPlotCurve('Trace2')
self.curve2.setSymbol(Qwt.QwtSymbol(Qwt.QwtSymbol.Ellipse,
Qt.QBrush(2),
Qt.QPen(Qt.Qt.darkMagenta),
Qt.QSize(3, 3)))
self.curve2.setPen(Qt.QPen(Qt.Qt.magenta, TIMEPENWIDTH))
self.curve2.setYAxis(Qwt.QwtPlot.yRight)
self.curve2.attach(self)
self.curve1 = Qwt.QwtPlotCurve('Trace1')
self.curve1.setSymbol(Qwt.QwtSymbol(Qwt.QwtSymbol.Ellipse,
Qt.QBrush(2),
Qt.QPen(Qt.Qt.darkBlue),
Qt.QSize(3, 3)))
self.curve1.setPen(Qt.QPen(Qt.Qt.blue, TIMEPENWIDTH))
self.curve1.setYAxis(Qwt.QwtPlot.yLeft)
self.curve1.attach(self)
# default settings
self.triggerval=0.10
self.triggerCH=None
self.maxamp=100.0
self.maxamp2=100.0
self.freeze=0
self.average=0
self.autocorrelation=0
self.avcount=0
self.datastream = None
self.offset1=0.0
self.offset2=0.0
self.maxtime = 0.1
# set data
# NumPy: f, g, a and p are arrays!
self.dt=1.0/samplerate
self.f = arange(0.0, 10.0, self.dt)
self.a1 = 0.0*self.f
self.a2 = 0.0*self.f
self.curve1.setData(self.f, self.a1)
self.curve2.setData(self.f, self.a2)
# start self.timerEvent() callbacks running
self.timer_id = self.startTimer(self.maxtime*100+50)
# plot
self.replot()
# convenience methods for knob callbacks
def setMaxAmp(self, val):
self.maxamp=val
def setMaxAmp2(self, val):
self.maxamp2=val
def setMaxTime(self, val):
self.maxtime=val
def setOffset1(self, val):
self.offset1=val
def setOffset2(self, val):
self.offset2=val
def setTriggerLevel(self, val):
self.triggerval=val
def setTriggerCH(self, val):
self.triggerCH = val
# plot scope traces
def setDisplay(self):
l=len(self.a1)
if SELECTEDCH==BOTH12:
self.curve1.setData(self.f[0:l], self.a1[:l]+self.offset1*self.maxamp)
self.curve2.setData(self.f[0:l], self.a2[:l]+self.offset2*self.maxamp2)
elif SELECTEDCH==CH2:
self.curve1.setData([0.0,0.0], [0.0,0.0])
self.curve2.setData(self.f[0:l], self.a2[:l]+self.offset2*self.maxamp2)
elif SELECTEDCH==CH1:
self.curve1.setData(self.f[0:l], self.a1[:l]+self.offset1*self.maxamp)
self.curve2.setData([0.0,0.0], [0.0,0.0])
self.replot()
def getValue(self, index):
return self.f[index],self.a[index]
def setAverage(self, state):
self.average = state
self.avcount=0
def setAutoc(self, state):
self.autocorrelation = state
self.avcount=0
def setFreeze(self, freeze):
self.freeze = freeze
def setDatastream(self, datastream):
self.datastream = datastream
def updateTimer(self):
self.killTimer(self.timer_id)
self.timer_id = self.startTimer(self.maxtime*100 + 50)
# timer callback that does the work
def timerEvent(self,e): # Scope
global fftbuffersize
if self.datastream == None: return
if self.freeze==1: return
#print "Reading %d" % (CHUNK*8, )
print self.maxtime
points = ceil(self.maxtime*RATE)
if self.triggerCH or self.autocorrelation:
# we read twice as much data to be sure to be able to display data for all time points.
# independently of trigger point location.
nchunks = 2*ceil(points/CHUNK)
else:
nchunks = ceil(points/CHUNK)
fftbuffersize = nchunks*CHUNK + (4-(nchunks*CHUNK%4))%4
if SELECTEDCH==BOTH12 or SELECTEDCH==CH1:
channel = 1
print "Reading %d bytes (%d frames, %d chunks)" % (8*nchunks*CHUNK, CHUNK*nchunks, nchunks)
X = self.datastream.read(channel, nchunks, verbose)
if X is None or not len(X): return
if len(X) == 0: return
#P=array(X, dtype=int32)#/32768.0
#val=self.triggerval*self.maxamp
i=0
data_CH1=X
else:
data_CH1=zeros((points,))
if SELECTEDCH==BOTH12 or SELECTEDCH==CH2:
channel = 2
print "Reading %d bytes (%d frames, %d chunks)" % (8*nchunks*CHUNK, CHUNK*nchunks, nchunks)
X = self.datastream.read(channel, nchunks, verbose)
if X is None or not len(X): return
P=array(X, dtype=int32)#/32768.0
#val=self.triggerval*self.maxamp
data_CH2=X
else:
data_CH2=zeros((points,))
if self.triggerCH == 1 and (SELECTEDCH==BOTH12 or SELECTEDCH==CH1):
print "Waiting for CH1 trigger..."
zero_crossings = where(diff(sign(data_CH1[points/2:-points/2]-self.triggerval*self.maxamp)) > 0)[0]
if not len(zero_crossings): return
print "Triggering on sample", zero_crossings[0]
imin = zero_crossings[0]
imax = zero_crossings[0]+points
data_CH1 = data_CH1[imin:imax]
elif self.triggerCH == 2 and (SELECTEDCH==BOTH12 or SELECTEDCH==CH2):
print "Waiting for CH2 trigger..."
zero_crossings = where(diff(sign(data_CH2[points/2:-points/2]-self.triggerval*self.maxamp2)) > 0)[0]
if not len(zero_crossings): return
print "Triggering on sample", zero_crossings[0]
imin = zero_crossings[0]
imax = zero_crossings[0]+points
data_CH2 = data_CH2[imin:imax]
if self.autocorrelation:
if SELECTEDCH==BOTH12 or SELECTEDCH==CH1:
channel = 1
print "Reading %d bytes (%d frames, %d chunks)" % (8*nchunks*CHUNK, CHUNK*nchunks, nchunks)
X = self.datastream.read(channel, nchunks, verbose)
if X is None or not len(X): return
if len(X) == 0: return
data_CH1 = array(correlate(X[:2*points], X[:points], mode='full'), dtype='float_')[points:]
data_CH1 = data_CH1/data_CH1[0]
else:
data_CH1=zeros((points,))
if SELECTEDCH==BOTH12 or SELECTEDCH==CH2:
channel = 2
print "Reading %d bytes (%d frames, %d chunks)" % (8*nchunks*CHUNK, CHUNK*nchunks, nchunks)
X = self.datastream.read(channel, nchunks, verbose)
if X is None or not len(X): return
if len(X) == 0: return
data_CH2 = array(correlate(X[:points], X, mode='full'), dtype='float_')[points:]
data_CH2 = data_CH2/data_CH2[0]
else:
data_CH2=zeros((points,))
if self.average == 0:
self.a1=data_CH1
self.a2=data_CH2
else:
self.avcount+=1
if self.avcount==1:
self.sumCH1=array(data_CH1, dtype=float_)
self.sumCH2=array(data_CH2, dtype=float_)
else:
if SELECTEDCH==BOTH12:
assert len(data_CH1) == len(data_CH2)
lp=len(data_CH1)
if len(self.sumCH1) == lp and len(self.sumCH2) == lp:
self.sumCH1=self.sumCH1[:lp]+array(data_CH1[:lp], dtype=float_)
self.sumCH2=self.sumCH2[:lp]+array(data_CH2[:lp], dtype=float_)
else:
self.sumCH1=data_CH1
self.sumCH2=data_CH2
self.avcount=1
elif SELECTEDCH==CH1:
lp=len(data_CH1)
if len(self.sumCH1) == lp:
self.sumCH1=self.sumCH1[:lp]+array(data_CH1[:lp], dtype=float_)
else:
self.sumCH1=data_CH1
self.avcount=1
elif SELECTEDCH==CH2:
lp=len(data_CH2)
if len(self.sumCH2) == lp:
self.sumCH2=self.sumCH2[:lp]+array(data_CH2[:lp], dtype=float_)
else:
self.sumCH2=data_CH2
self.avcount=1
self.a1=self.sumCH1/self.avcount
self.a2=self.sumCH2/self.avcount
self.setDisplay()
inittime=0.01
initamp=100
class ScopeFrame(Qt.QFrame):
"""
Oscilloscope widget --- contains controls + display
"""
def __init__(self, *args):
apply(Qt.QFrame.__init__, (self,) + args)
# the following: setPal.. doesn't seem to work on Win
try:
self.setPaletteBackgroundColor( QColor(240,240,245))
except: pass
hknobpos=scopewidth+20
vknobpos=scopeheight+30
self.setFixedSize(scopewidth+150, scopeheight+150)
self.freezeState = 0
self.triggerComboBox = Qt.QComboBox(self)
self.triggerComboBox.setGeometry(hknobpos+10, 50, 100, 40)#"Channel: ")
self.triggerComboBox.addItem("Trigger off")
self.triggerComboBox.addItem("CH1")
self.triggerComboBox.addItem("CH2")
self.triggerComboBox.setCurrentIndex(0)
self.knbLevel = LblKnob(self,hknobpos,100,"Trigger level (%FS)")
self.knbTime = LblKnob(self,hknobpos, 240,"Time", 1)
self.knbSignal = LblKnob(self,150, vknobpos, "Signal1",1)
self.knbSignal2 = LblKnob(self,450, vknobpos, "Signal2",1)
self.knbOffset1=LblKnob(self,10, vknobpos,"offset1")
self.knbOffset2=LblKnob(self,310, vknobpos,"offset2")
self.knbTime.setRange(0.0001, 1.0)
self.knbTime.setValue(DEFAULT_TIMEBASE)
self.knbSignal.setRange(1, 1e6, 1)
self.knbSignal.setValue(100.0)
self.knbSignal2.setRange(1, 1e6, 1)
self.knbSignal2.setValue(100.0)
self.knbOffset2.setRange(-1.0, 1.0, 0.1)
self.knbOffset2.setValue(0.0)
self.knbOffset1.setRange(-1.0, 1.0, 0.1)
self.knbOffset1.setValue(0.0)
self.knbLevel.setRange(-1.0, 1.0, 0.1)
self.knbLevel.setValue(0.1)
self.knbLevel.setScaleMaxMajor(10)
self.plot = Scope(self)
self.plot.setGeometry(10, 10, scopewidth, scopeheight)
self.picker = Qwt.QwtPlotPicker(
Qwt.QwtPlot.xBottom,
Qwt.QwtPlot.yLeft,
Qwt.QwtPicker.PointSelection | Qwt.QwtPicker.DragSelection,
Qwt.QwtPlotPicker.CrossRubberBand,
Qwt.QwtPicker.ActiveOnly, #AlwaysOn,
self.plot.canvas())
self.picker.setRubberBandPen(Qt.QPen(Qt.Qt.green))
self.picker.setTrackerPen(Qt.QPen(Qt.Qt.cyan))
self.connect(self.knbTime.knob, Qt.SIGNAL("valueChanged(double)"),
self.setTimebase)
self.knbTime.setValue(0.01)
self.connect(self.knbSignal.knob, Qt.SIGNAL("valueChanged(double)"),
self.setAmplitude)
self.connect(self.knbSignal2.knob, Qt.SIGNAL("valueChanged(double)"),
self.setAmplitude2)
#self.knbSignal.setValue(0.1)
self.connect(self.knbLevel.knob, Qt.SIGNAL("valueChanged(double)"),
self.setTriggerlevel)
self.connect(self.knbOffset1.knob, Qt.SIGNAL("valueChanged(double)"),
self.plot.setOffset1)
self.connect(self.knbOffset2.knob, Qt.SIGNAL("valueChanged(double)"),
self.plot.setOffset2)
self.connect(self.triggerComboBox, Qt.SIGNAL('currentIndexChanged(int)'), self.setTriggerCH)
self.knbLevel.setValue(0.1)
self.plot.setAxisScale( Qwt.QwtPlot.xBottom, 0.0, 10.0*inittime)
self.plot.setAxisScale( Qwt.QwtPlot.yLeft, -initamp, initamp)
self.plot.setAxisScale( Qwt.QwtPlot.yRight, -initamp, initamp)
self.plot.show()
def _calcKnobVal(self,val):
ival=floor(val)
frac=val-ival
if frac >=0.9:
frac=1.0
elif frac>=0.66:
frac=log10(5.0)
elif frac>=log10(2.0):
frac=log10(2.0)
else: frac=0.0
dt=10**frac*10**ival
return dt
def setTimebase(self, val):
dt=self._calcKnobVal(val)
self.plot.setAxisScale( Qwt.QwtPlot.xBottom, 0.0, 10.0*dt)
self.plot.setMaxTime(dt*10.0)
self.plot.replot()
def setAmplitude(self, val):
dt=self._calcKnobVal(val)
self.plot.setAxisScale( Qwt.QwtPlot.yLeft, -dt, dt)
self.plot.setMaxAmp(dt)
self.plot.replot()
def setAmplitude2(self, val):
dt=self._calcKnobVal(val)
self.plot.setAxisScale( Qwt.QwtPlot.yRight, -dt, dt)
self.plot.setMaxAmp2(dt)
self.plot.replot()
def setTriggerlevel(self, val):
self.plot.setTriggerLevel(val)
self.plot.setDisplay()
def setTriggerCH(self, val):
if val == 0:
val = None
self.plot.setTriggerCH(val)
self.plot.setDisplay()
#--------------------------------------------------------------------
class FScope(Qwt.QwtPlot):
"""
Power spectrum display widget
"""
def __init__(self, *args):
apply(Qwt.QwtPlot.__init__, (self,) + args)
self.setTitle('Power spectrum');
self.setCanvasBackground(Qt.Qt.white)
# grid
self.grid = Qwt.QwtPlotGrid()
self.grid.enableXMin(True)
self.grid.setMajPen(Qt.QPen(Qt.Qt.gray, 0, Qt.Qt.SolidLine));
self.grid.attach(self)
# axes
self.setAxisTitle(Qwt.QwtPlot.xBottom, 'Frequency [Hz]');
self.setAxisTitle(Qwt.QwtPlot.yLeft, 'Power Spectrum [dBc/Hz]');
self.setAxisMaxMajor(Qwt.QwtPlot.xBottom, 10);
self.setAxisMaxMinor(Qwt.QwtPlot.xBottom, 0);
self.setAxisMaxMajor(Qwt.QwtPlot.yLeft, 10);
self.setAxisMaxMinor(Qwt.QwtPlot.yLeft, 0);
# curves
self.curve2 = Qwt.QwtPlotCurve('PSTrace2')
self.curve2.setPen(Qt.QPen(Qt.Qt.magenta,FFTPENWIDTH))
self.curve2.setYAxis(Qwt.QwtPlot.yLeft)
self.curve2.attach(self)
self.curve1 = Qwt.QwtPlotCurve('PSTrace1')
self.curve1.setPen(Qt.QPen(Qt.Qt.blue,FFTPENWIDTH))
self.curve1.setYAxis(Qwt.QwtPlot.yLeft)
self.curve1.attach(self)
self.triggerval=0.0
self.maxamp=100.0
self.maxamp2=100.0
self.freeze=0
self.average=0
self.avcount=0
self.logy=1
self.datastream=None
self.dt=1.0/samplerate
self.df=1.0/(fftbuffersize*self.dt)
self.f = arange(0.0, samplerate, self.df)
self.a1 = 0.0*self.f
self.a2 = 0.0*self.f
self.curve1.setData(self.f, self.a1)
self.curve2.setData(self.f, self.a2)
self.setAxisScale( Qwt.QwtPlot.xBottom, 0.0, 12.5*initfreq)
self.setAxisScale( Qwt.QwtPlot.yLeft, -120.0, 0.0)
self.startTimer(100)
self.replot()
def resetBuffer(self):
self.df=1.0/(fftbuffersize*self.dt)
self.f = arange(0.0, samplerate, self.df)
self.a1 = 0.0*self.f
self.a2 = 0.0*self.f
self.curve1.setData(self.curve1, self.f, self.a1)
self.curve1.setData(self.curve1, self.f, self.a2)
def setMaxAmp(self, val):
if val>0.6:
self.setAxisScale( Qwt.QwtPlot.yLeft, -120.0, 0.0)
self.logy=1
else:
self.setAxisScale( Qwt.QwtPlot.yLeft, 0.0, 10.0*val)
self.logy=0
self.maxamp=val
def setMaxTime(self, val):
self.maxtime=val
self.updateTimer()
def setTriggerLevel(self, val):
self.triggerval=val
def setDisplay(self):
n=fftbuffersize/2
if SELECTEDCH==BOTH12:
self.curve1.setData(self.f[0:n], self.a1[:n])
self.curve2.setData(self.f[0:n], self.a2[:n])
elif SELECTEDCH==CH2:
self.curve1.setData([0.0,0.0], [0.0,0.0])
self.curve2.setData(self.f[0:n], self.a2[:n])
elif SELECTEDCH==CH1:
self.curve1.setData(self.f[0:n], self.a1[:n])
self.curve2.setData([0.0,0.0], [0.0,0.0])
self.replot()
def getValue(self, index):
return self.f[index],self.a1[index]
def setAverage(self, state):
self.average = state
self.avcount=0
def setFreeze(self, freeze):
self.freeze = freeze
def setDatastream(self, datastream):
self.datastream = datastream
def timerEvent(self,e): # FFT
global fftbuffersize
if self.datastream == None: return
if self.freeze==1: return
nchunks = ceil(fftbuffersize/CHUNK)
if SELECTEDCH==BOTH12 or SELECTEDCH==CH1:
channel = 1
X=self.datastream.read(channel, nchunks, verbose)
if X is None or not len(X): return
data_CH1=X[:fftbuffersize]
else:
data_CH1=ones((fftbuffersize,))
if SELECTEDCH==BOTH12 or SELECTEDCH==CH2:
channel = 2
X=self.datastream.read(channel, nchunks, verbose)
if X is None or not len(X): return
data_CH2=X[:fftbuffersize]
else:
data_CH2=ones((fftbuffersize,))
self.df=1.0/(fftbuffersize*self.dt)
self.setAxisTitle(Qwt.QwtPlot.xBottom, 'Frequency [Hz] - Bin width %g Hz' % (self.df,))
self.f = arange(0.0, samplerate, self.df)
if not SPECTRUM_MODULE:
lenX = fftbuffersize
window=blackman(lenX)
sumw=sum(window*window)
A=FFT.fft(data_CH1*window) #lenX
B=(A*conjugate(A)).real
A=FFT.fft(data_CH2*window) #lenX
B2=(A*conjugate(A)).real
sumw*=2.0 # sym about Nyquist (*4); use rms (/2)
sumw/=self.dt # sample rate
B=B/sumw
B2=B2/sumw
else:
print "FFT buffer size: %d points" % (fftbuffersize,)
B = spectrum.Periodogram(array(data_CH1, dtype=float64), samplerate)
B.sides = 'onesided'
B.run()
B = B.get_converted_psd('onesided')
B2 = spectrum.Periodogram(array(data_CH2, dtype=float64), samplerate)
B2.sides = 'onesided'
B2.run()
B2 = B2.get_converted_psd('onesided')
if self.logy:
P1=log10(B)*10.0#+20.0#60.0
P2=log10(B2)*10.0#+20.0#60.0
P1 -= P1.max()
P2 -= P2.max()
else:
P1=B
P2=B2
if not self.average:
self.a1=P1
self.a2=P2
self.avcount = 0
else:
self.avcount+=1
if self.avcount==1:
self.sumP1=P1
self.sumP2=P2
else:
self.sumP1=self.sumP1+P1
self.sumP2=self.sumP2+P2
self.a1=self.sumP1/self.avcount
self.a2=self.sumP2/self.avcount
self.setDisplay()
initfreq=100.0
class FScopeFrame(Qt.QFrame):
"""
Power spectrum widget --- contains controls + display
"""
def __init__(self , *args):
apply(Qt.QFrame.__init__, (self,) + args)
vknobpos=scopeheight+30
hknobpos=scopewidth+10
# the following: setPal.. doesn't seem to work on Ein
try:
self.setPaletteBackgroundColor( QColor(240,240,245))
except: pass
self.setFixedSize(scopewidth+160, scopeheight+160)
self.freezeState = 0
self.knbSignal = LblKnob(self,160, vknobpos, "Signal",1)
self.knbTime = LblKnob(self,310, vknobpos,"Frequency", 1)
self.knbTime.setRange(1.0, 1250.0)
self.knbSignal.setRange(100, 1000000)
self.plot = FScope(self)
self.plot.setGeometry(12.5, 10, scopewidth+120, scopeheight)
self.picker = Qwt.QwtPlotPicker(
Qwt.QwtPlot.xBottom,
Qwt.QwtPlot.yLeft,
Qwt.QwtPicker.PointSelection | Qwt.QwtPicker.DragSelection,
Qwt.QwtPlotPicker.CrossRubberBand,
Qwt.QwtPicker.ActiveOnly, #AlwaysOn,
self.plot.canvas())
self.picker.setRubberBandPen(Qt.QPen(Qt.Qt.green))
self.picker.setTrackerPen(Qt.QPen(Qt.Qt.cyan))
self.connect(self.knbTime.knob, Qt.SIGNAL("valueChanged(double)"),
self.setTimebase)
self.knbTime.setValue(1000.0)
self.connect(self.knbSignal.knob, Qt.SIGNAL("valueChanged(double)"),
self.setAmplitude)
self.knbSignal.setValue(1000000)
self.plot.show()
def _calcKnobVal(self,val):
ival=floor(val)
frac=val-ival
if frac >=0.9:
frac=1.0
elif frac>=0.66:
frac=log10(5.0)
elif frac>=log10(2.0):
frac=log10(2.0)
else: frac=0.0
dt=10**frac*10**ival
return dt
def setTimebase(self, val):
dt=self._calcKnobVal(val)
self.plot.setAxisScale( Qwt.QwtPlot.xBottom, 0.0, 12.5*dt)
self.plot.replot()
def setAmplitude(self, val):
minp=self._calcKnobVal(val)
self.plot.setAxisScale(Qwt.QwtPlot.yLeft, -int(log10(minp)*20), 0.0)
self.plot.replot()
#---------------------------------------------------------------------
class FScopeDemo(Qt.QMainWindow):
"""
Application container widget
Contains scope and power spectrum analyser in tabbed windows.
Enables switching between the two.
Handles toolbar and status.
"""
def __init__(self, *args):
apply(Qt.QMainWindow.__init__, (self,) + args)
self.freezeState = 0
self.changeState = 0
self.averageState = 0
self.autocState = 0
self.scope = ScopeFrame(self)
self.current = self.scope
self.pwspec = FScopeFrame(self)
self.pwspec.hide()
self.stack=Qt.QTabWidget(self)
self.stack.addTab(self.scope,"scope")
self.stack.addTab(self.pwspec,"fft")
self.setCentralWidget(self.stack)
toolBar = Qt.QToolBar(self)
self.addToolBar(toolBar)
sb=self.statusBar()
sbfont=Qt.QFont("Helvetica",12)
sb.setFont(sbfont)
self.btnFreeze = Qt.QToolButton(toolBar)
self.btnFreeze.setText("Freeze")
self.btnFreeze.setIcon(Qt.QIcon(Qt.QPixmap(icons.stopicon)))
self.btnFreeze.setCheckable(True)
self.btnFreeze.setToolButtonStyle(Qt.Qt.ToolButtonTextUnderIcon)
toolBar.addWidget(self.btnFreeze)
self.btnSave = Qt.QToolButton(toolBar)
self.btnSave.setText("Save CSV")
self.btnSave.setIcon(Qt.QIcon(Qt.QPixmap(icons.save)))
self.btnSave.setToolButtonStyle(Qt.Qt.ToolButtonTextUnderIcon)
toolBar.addWidget(self.btnSave)
self.btnPDF = Qt.QToolButton(toolBar)
self.btnPDF.setText("Export PDF")
self.btnPDF.setIcon(Qt.QIcon(Qt.QPixmap(icons.pdf)))
self.btnPDF.setToolButtonStyle(Qt.Qt.ToolButtonTextUnderIcon)
toolBar.addWidget(self.btnPDF)
self.btnPrint = Qt.QToolButton(toolBar)
self.btnPrint.setText("Print")
self.btnPrint.setIcon(Qt.QIcon(Qt.QPixmap(icons.print_xpm)))
self.btnPrint.setToolButtonStyle(Qt.Qt.ToolButtonTextUnderIcon)
toolBar.addWidget(self.btnPrint)
self.btnMode = Qt.QToolButton(toolBar)
self.btnMode.setText("fft")
self.btnMode.setIcon(Qt.QIcon(Qt.QPixmap(icons.pwspec)))
self.btnMode.setCheckable(True)
self.btnMode.setToolButtonStyle(Qt.Qt.ToolButtonTextUnderIcon)
toolBar.addWidget(self.btnMode)
self.btnAvge = Qt.QToolButton(toolBar)
self.btnAvge.setText("average")
self.btnAvge.setIcon(Qt.QIcon(Qt.QPixmap(icons.avge)))
self.btnAvge.setCheckable(True)
self.btnAvge.setToolButtonStyle(Qt.Qt.ToolButtonTextUnderIcon)
toolBar.addWidget(self.btnAvge)
self.btnAutoc = Qt.QToolButton(toolBar)
self.btnAutoc.setText("autocorrelation")
self.btnAutoc.setIcon(Qt.QIcon(Qt.QPixmap(icons.avge)))
self.btnAutoc.setCheckable(True)
self.btnAutoc.setToolButtonStyle(Qt.Qt.ToolButtonTextUnderIcon)
toolBar.addWidget(self.btnAutoc)
#self.lstLabl = Qt.QLabel("Buffer:",toolBar)
#toolBar.addWidget(self.lstLabl)
#self.lstChan = Qt.QComboBox(toolBar)
#self.lstChan.insertItem(0,"8192")
#self.lstChan.insertItem(1,"16k")
#self.lstChan.insertItem(2,"32k")
#toolBar.addWidget(self.lstChan)
self.lstLR = Qt.QLabel("Channels:",toolBar)
toolBar.addWidget(self.lstLR)
self.lstLRmode = Qt.QComboBox(toolBar)
self.lstLRmode.insertItem(0,"1&2")
self.lstLRmode.insertItem(1,"CH1")
self.lstLRmode.insertItem(2,"CH2")
toolBar.addWidget(self.lstLRmode)
self.connect(self.btnPrint, Qt.SIGNAL('clicked()'), self.printPlot)
self.connect(self.btnSave, Qt.SIGNAL('clicked()'), self.saveData)
self.connect(self.btnPDF, Qt.SIGNAL('clicked()'), self.printPDF)
self.connect(self.btnFreeze, Qt.SIGNAL('toggled(bool)'), self.freeze)
self.connect(self.btnMode, Qt.SIGNAL('toggled(bool)'), self.mode)
self.connect(self.btnAvge, Qt.SIGNAL('toggled(bool)'), self.average)
self.connect(self.btnAutoc, Qt.SIGNAL('toggled(bool)'),
self.autocorrelation)
#self.connect(self.lstChan, Qt.SIGNAL('activated(int)'), self.fftsize)
self.connect(self.lstLRmode, Qt.SIGNAL('activated(int)'), self.channel)
self.connect(self.scope.picker,
Qt.SIGNAL('moved(const QPoint&)'),
self.moved)
self.connect(self.scope.picker,
Qt.SIGNAL('appended(const QPoint&)'),
self.appended)
self.connect(self.pwspec.picker,
Qt.SIGNAL('moved(const QPoint&)'),
self.moved)
self.connect(self.pwspec.picker,
Qt.SIGNAL('appended(const QPoint&)'),
self.appended)
self.connect(self.stack,
Qt.SIGNAL('currentChanged(int)'),
self.mode)
self.showInfo(cursorInfo)
#self.showFullScreen()
#print self.size()
def showInfo(self, text):
self.statusBar().showMessage(text)
def printPlot(self):
printer = Qt.QPrinter(Qt.QPrinter.HighResolution)
printer.setOutputFileName('scope-plot.ps')
printer.setCreator('Ethernet Scope')
printer.setOrientation(Qt.QPrinter.Landscape)
printer.setColorMode(Qt.QPrinter.Color)
docName = self.current.plot.title().text()
if not docName.isEmpty():
docName.replace(Qt.QRegExp(Qt.QString.fromLatin1('\n')), self.tr(' -- '))
printer.setDocName(docName)
dialog = Qt.QPrintDialog(printer)
if dialog.exec_():
# filter = Qwt.PrintFilter()
# if (Qt.QPrinter.GrayScale == printer.colorMode()):
# filter.setOptions(
# Qwt.QwtPlotPrintFilter.PrintAll
# & ~Qwt.QwtPlotPrintFilter.PrintBackground
# | Qwt.QwtPlotPrintFilter.PrintFrameWithScales)
self.current.plot.print_(printer)
#p = Qt.QPrinter()
#if p.setup():
# self.current.plot.printPlot(p)#, Qwt.QwtFltrDim(200));
def printPDF(self):
fileName = Qt.QFileDialog.getSaveFileName(
self,
'Export File Name',
'',
'PDF Documents (*.pdf)')
if not fileName.isEmpty():
printer = Qt.QPrinter()
printer.setOutputFormat(Qt.QPrinter.PdfFormat)
printer.setOrientation(Qt.QPrinter.Landscape)
printer.setOutputFileName(fileName)
printer.setCreator('Ethernet Scope')
self.current.plot.print_(printer)
# p = QPrinter()
# if p.setup():
# self.current.plot.printPlot(p)#, Qwt.QwtFltrDim(200));
def saveData(self):
fileName = Qt.QFileDialog.getSaveFileName(