-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathScopePy_channel.py
More file actions
2159 lines (1466 loc) · 63.4 KB
/
ScopePy_channel.py
File metadata and controls
2159 lines (1466 loc) · 63.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
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 Tue Jun 3 14:50:25 2014
@author: john
ScopePy Channel definitions
===================================
ScopePy channels are a virtual version of an oscilloscope channel. They are
defined internally as a class.
Version
==============================================================================
$Revision:: 178 $
$Date:: 2016-08-06 07:46:28 -0400 (Sat, 0#$
$Author:: $
==============================================================================
"""
#==============================================================================
#%% License
#==============================================================================
"""
Copyright 2015 John Bainbridge
This file is part of ScopePy.
ScopePy 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.
ScopePy 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 ScopePy. If not, see <http://www.gnu.org/licenses/>.
"""
#======================================================================
#%% Imports
#======================================================================
import logging
import os
import inspect
from numpy.lib.recfunctions import stack_arrays
import bisect
from PyQt4.QtCore import *
from PyQt4.QtGui import *
# Custom widgets
import ScopePy_graphs as graph
from ScopePy_widgets import *
from ScopePy_utilities import import_module_from_file
#==============================================================================
#%% Logger
#==============================================================================
# create logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# Add do nothing handler
logger.addHandler(logging.NullHandler())
# create console handler and set level to debug
con = logging.StreamHandler()
con.setLevel(logging.DEBUG)
# create formatter
formatter = logging.Formatter('[%(asctime)s:%(name)s:%(levelname)s]: %(message)s')
# add formatter to ch
con.setFormatter(formatter)
# add ch to logger
logger.addHandler(con)
#======================================================================
#%% Constants
#======================================================================
DEBUG = False
# Define chunk mode constants
CHUNK_MODE_ALL = 'all'
CHUNK_MODE_LATEST = 'latest'
CHUNK_MODE_FIRST = 'first'
CHUNK_MODE_SELECTION = 'selection'
CHUNK_MODE_ROLLOVER = 'rollover'
CHUNK_MODES = [CHUNK_MODE_ALL,CHUNK_MODE_LATEST,CHUNK_MODE_FIRST,CHUNK_MODE_SELECTION,CHUNK_MODE_ROLLOVER]
# Functions for extracting the x and y columns (first & second) from a numpy
# structured array
Xdata = lambda array: array[array.dtype.names[0]]
Ydata = lambda array: array[array.dtype.names[1]]
#======================================================================
#%% plot linestyle class
#======================================================================
class plotLineStyle():
""" Container class for carrying all data for the visual appearance
of a plot:
line colour, marker type, marker colour, marker fill colour
This allows all these values to be passed around as one object
"""
def __init__(self,lineColour='#0000ff',lineDashStyle = Qt.SolidLine,marker='o', markerColour='#0000ff',markerFillColour = '#0000ff',markerSize=2):
# Plotting config
self.lineColour = lineColour
self.lineDashStyle = lineDashStyle
self.markerColour = markerColour
self.marker = marker
self.markerFillColour = markerFillColour
self.markerSize = markerSize
def __str__(self):
"""
Display line styles - for debugging
"""
txt = [
"Plot Linestyle:",
"-"*40,
"Line colour = %s" % self.lineColour,
"Marker = %s" % self.marker,
"Marker outline colour = %s" % self.markerColour,
"Marker fill colour = %s" % self.markerFillColour,
]
return "\n".join(txt)
def __repr__(self):
return self.__str__()
#======================================================================
#%% scopePyChannel class
#======================================================================
class ScopePyChannel(QObject):
"""
Virtual scope channel definition
ScopePy can have multiple channels they are stored in a dictionary
channel_dict in the main GUI. Each dictionary value is an object of
scopePyChannel class.
This class holds the data for each channel as well as the plot line styles.
It also has methods for controlling how the chunks are used.
"""
def __init__(self,channelLabel="Unknown",lineStyle=plotLineStyle()):
""" Create instance of a channel at the number specified
Input
-----
channelLabel = string
label for the channel - appears in channel tree view
lineStyle = plotLineStyle object -
see plotLineStyle and channelColours classes
"""
# Initialise object
# needs to be a QObject() to be able to emit signals
super(ScopePyChannel,self).__init__()
# Setup channel meta data
# --------------------------
self.name = channelLabel
# Overall min and max values
self.xMinValue = None
self.xMaxValue = None
self.yMinValue = None
self.yMaxValue = None
# x and y axis labels for referencing recarray columns
self.x_axis = ''
self.y_axis = ''
# Column names of all data in a chunk
self.column_names = []
# Plotting config
self.plot_lineStyle = lineStyle
# Channel data storage
# -------------------------
# Channel data is stored as a list or numpy recarrays
# these will also be known as chunks
self.data_list = []
# Number of chunks (= len(self.data_list))
self.chunks = 0
# Max number of chunks that can be used
# Used for Rollover chunk mode
self.rollover = np.inf
# Chunk mode
# How data is to be returned from chunks
self.chunkMode = CHUNK_MODE_ALL
# Data empty flag
# Use this as a quick way to determine if any data has been
# added yet. This is to avoid searching the data list
self.data_empty = True
# Channel plot items
# -------------------------------
# When a channel is plotted in a tab the plotDataItem is
# stored in this class so that it can be easily reached
# when updating.
# This allows changing the attributes of a channel
# and reflecting the change in every plot
self.plotDataItemList = []
def __str__(self):
"""
Display channel on command line
"""
txt = [
"ScopePy channel: %s" % self.name,
"="*40,
"x axis name = %s" % self.x_axis,
"y axis name = %s" % self.y_axis,
"Chunks = %i" % self.chunks,
"\n",
str(self.plot_lineStyle)
]
return "\n".join(txt)
def __repr__(self):
return self.__str__()
@property
def isEmpty(self):
"""
Check if a channel contains any data. Used for graph plotting
Output:
--------
isEmpty : bool
True if empty
"""
return self.data_list == []
def clearChannelData(self):
"""
Remove all data from channel and reset number of chunks
"""
self.data_list = []
self.data_empty = True
self.chunks = 0
def addData2Channel(self,recArray,update_signal=True):
""" Add a chunk of data to the channel
Check the data has the same column names as previous chunks
Add chunk to the list
Update min and max values
Inputs
------
recArray = numpy recarray with column names populated
update_signal : bool
Set to True to trigger an update signal (usually for plots)
Set to False not to trigger update signal (where speed is needed)
Outputs
--------
success = True or False
"""
# Get column names
column_names = recArray.dtype.names
# Add x and y axis names
x_axis = column_names[0]
y_axis = column_names[1]
# Create new array with a third column for transparency
newArray = np.zeros(len(recArray),
dtype = [(x_axis,float),
(y_axis,float),
('transparency',float)])
newArray[x_axis] = recArray[x_axis]
newArray[y_axis] = recArray[y_axis]
# Initalise transparency with chunk number
newArray['transparency'] = self.chunks
# Set the min and max
xmin = newArray[x_axis].min()
xmax = newArray[x_axis].max()
ymin = newArray[y_axis].min()
ymax = newArray[y_axis].max()
if not self.xMinValue or xmin < self.xMinValue:
self.xMinValue = xmin
if not self.xMaxValue or xmax > self.xMaxValue:
self.xMaxValue = xmax
if not self.yMinValue or ymin < self.yMinValue:
self.yMinValue = ymin
if not self.yMaxValue or ymax > self.yMaxValue:
self.yMaxValue = ymax
# Add new data
if self.data_empty:
# Set the axis names
self.x_axis = x_axis
self.y_axis = y_axis
# Add chunk of data to the list
self.data_list.append(newArray)
# Log the column names
self.column_names = column_names
# No longer empty so set the flag
self.data_empty = False
else:
# Check first two column names are the same
# note 0:2 is interpreted as 0:1 in Python
if self.column_names[0:2] == recArray.dtype.names:
self.data_list.append(newArray)
else:
# Don't add data if the column names
# don't match
return False
# Increment the number of chunks
self.chunks += 1
# Trigger any plot updates
if update_signal:
self.updatePlots()
# If we get here then everything worked so return True
return True
def setAxisName(self,axis,newName):
""" Set the name of an individual axis
Inputs
------
axis = 'x' or 'y'
newName = string name for axis
"""
axis = axis.lower()
# Check axis
if axis not in ['x','y']:
return
# The data is stored in recarrays. The axis names are stored in the
# recarray names field as a tuple. Can't change individual elements
# of a tuple so we have to replace the whole names field.
if axis == 'x':
newAxisNames = (newName,self.y_axis)
# update axis field in class
self.x_axis = newName
else:
newAxisNames = (self.x_axis,newName)
# update axis field in class
self.y_axis = newName
# Replace existing names in all chunks
for chunk in range(self.chunks):
self.data_list[chunk].dtype.names = newAxisNames
def data(self,chunkMode=None,chunkList = [0]):
"""
Return scope data according to the chunk mode specified.
Inputs
------------
chunkMode = string giving the policy type
chunkList = list of chunks to be returned
Outputs
-----------
dataArray = numpy recarray containing all the chunks specified in two
columns
"""
if DEBUG:
print("data function\n-----------------------------\n")
print("Chunk Policy = %s" % chunkMode)
print("Chunks available %d" % self.chunks)
if not chunkMode:
chunkMode = self.chunkMode
# Validate input policy
# =============================
if chunkMode not in CHUNK_MODES:
print("Policy is not in list - quit")
return
if self.chunks == 0:
# Empty channel do nothing
print("No chunks - quit")
return
# Select data according to the policy
# =====================================
if chunkMode == CHUNK_MODE_LATEST:
chunkList = [self.chunks-1]
elif chunkMode == CHUNK_MODE_FIRST:
chunkList = [0]
elif chunkMode == CHUNK_MODE_ALL:
chunkList = list(range(self.chunks))
elif chunkMode == CHUNK_MODE_ROLLOVER:
# In this mode we return a maximum number of chunks up to the value
# in self.rollover.
if self.chunks < self.rollover:
# Number of chunks is less than the rollover
chunkList = list(range(self.chunks))
else:
# More chunks than rollover value, return the latest chunks
chunkList = list(range(self.chunks-self.rollover,self.chunks))
elif chunkMode == CHUNK_MODE_SELECTION:
# Check chunkList is not empty
if not chunkList:
return
if chunkList == [-1]:
chunkList =[self.chunks-1]
if DEBUG:
print("Chunk list:",chunkList)
# Extract the specified chunks and return
return self.getDataFromChannel(chunkList)
def getDataFromChannel(self,chunkList):
"""
Basic extraction of data combining all specified chunks
into one recarray
Inputs
---------------
chunkList: list
list of numpy recarrays
"""
if DEBUG:
print("getDataFromChannel function\n-----------------------------\n")
print("Chunk List = ",chunkList)
# Exit if list is empty
if not chunkList:
return
# Extract all the selected chunks into a separate list
data2Return = []
for index in chunkList:
data2Return.append(self.data_list[index])
totalData = stack_arrays(data2Return, asrecarray=True, usemask=False)
if DEBUG:
print("Selected data")
print(totalData)
# Stack all the selected rearrays together
# and return
return totalData
@property
def x(self):
"""
Convenience function/property for getting all x data using the current
chunk mode
"""
return self.data()[self.x_axis]
@property
def y(self):
"""
Convenience function for getting all y data using the current
chunk mode
"""
return self.data()[self.y_axis]
def updatePlots(self):
"""
Trigger all plots that have this channel to update.
This is used when a new data chunk arrives
Sends the signal "updateChannelPlot" with channel name
"""
# Trigger update to any connected plots
self.emit(SIGNAL("updateChannelPlot"), self.name)
# -----------------------------------------------------------
# Importing/Exporting functions
# -----------------------------------------------------------
def to_dict(self):
"""
Export the channel to a dictionary.
This is useful for saving channels to files. It dumps the name, the
data and the line styles into a dictionary
Outputs
---------
channel_export : dict
Dictionary with the following keys:
'name' : channel name
'data' : all data as a list of chunks
'plotstyle' : line and marker colours and styles
"""
channel_export = {'name':self.name,
'data':self.data_list,
'plotstyle':self.plot_lineStyle
}
return channel_export
def from_dict(self,channel_import):
"""
Import channel from dictionary created by to_dict() method.
Used for loading channels from files
Input
------
channel_import : dict
Dictionary with the following keys:
'name' : channel name
'data' : all data as a list of chunks
'plotstyle' : line and marker colours and styles
Output
-------
success : bool
True = successfully imported
False = cannot import, dictionary probably doesn't have correct
format.
Example usage
--------------
>>> new_channel = ScopePyChannel()
>>> new_channel.from_dict(imported_channel_dict)
"""
# Validate input dictionary
# ---------------------------
if not all([x in channel_import for x in ['name','data','plotstyle']]):
logger.debug("ScopePyChannel:from_dict : Missing keys in import dict")
return False
if len(channel_import['data']) == 0:
logger.debug("ScopePyChannel:from_dict : No data in import dict")
return False
if not isinstance(channel_import['data'][0],np.ndarray):
logger.debug("ScopePyChannel:from_dict : Data in import dict is not numpy array")
return False
column_names = channel_import['data'][0].dtype.names
if len(column_names) < 2:
logger.debug("ScopePyChannel:from_dict : Data array in import dict has less than 2 columns")
return False
# Import data from dictionary into channel properties
# ----------------------------------------------------
# Read data into channel
self.name = channel_import['name']
self.data_list = channel_import['data']
self.plot_lineStyle = channel_import['plotstyle']
# Update chunks
self.chunks = len(self.data_list)
self.data_empty = False
# Update column names
self.x_axis = column_names[0]
self.y_axis = column_names[1]
return True
#======================================================================
#%% Group channel
#======================================================================
class GroupChannel(ScopePyChannel):
"""
Group channels are linked to data source tables. They represent two columns
from a table.
TODO : They will allow linking to the other columns in the table
"""
def __init__(self,datasourceTableWrapper,x_column_name,y_column_name,*args,**kwargs):
"""
Inputs
----------
datasourceTableWrapper : DatasourceTable object or derivative
"""
# Initialise as ScopePy channel
super(GroupChannel,self).__init__(*args,**kwargs)
# Check the input has the right methods
assert hasattr(datasourceTableWrapper,'getColumnByName'), 'GroupChannel: Initialisation with an object that is not a table wrapper'
assert hasattr(datasourceTableWrapper,'columnHeaders'), 'GroupChannel: Initialisation with an object that is not a table wrapper'
# Input validation
# ---------------------------
headers = datasourceTableWrapper.columnHeaders()
assert x_column_name in headers, 'GroupChannel: Datasource table does not have a column called %s' % x_column_name
assert y_column_name in headers, 'GroupChannel: Datasource table does not have a column called %s' % y_column_name
# Store links to data table
# ----------------------------
self.data_table = datasourceTableWrapper
self.x_axis = x_column_name
self.y_axis = y_column_name
# Set Chunk handling
# ------------------------------
# This channel type doesn't support chunks, so just set here and forget
# Number of chunks
self.chunks = 1
# Chunk mode
self.chunkMode = CHUNK_MODE_ALL
@property
def isEmpty(self):
"""
Check if a channel contains any data. Used for graph plotting
Note:
This is here for compatibility. A group channel should always have
data because it can only be created from an existing data set.
Output:
--------
isEmpty : bool
Always returns False
"""
return False
def data(self,**kwargs):
"""
Return data from table as numpy recarray
Outputs
---------
data_array : numpy recarray
Two column array
"""
# The input **kwargs is to be the same as the ScopePyChannel.data()
# function, no action is taken
# Get the two columns
# ------------------------
x_data = self.data_table.getColumnByName(self.x_axis)
y_data = self.data_table.getColumnByName(self.y_axis)
data_array = np.zeros(len(x_data),[(self.x_axis,float),(self.y_axis,float)])
data_array[self.x_axis] = x_data
data_array[self.y_axis] = y_data
return data_array
#======================================================================
#%% Math channel
#======================================================================
class MathChannel(ScopePyChannel):
"""
Math channels are derived from other channels, they apply a function
to the source channel and return a transformed version of the data
"""
def __init__(self,source_channels,math_function,*args,**kwargs):
"""
Inputs
----------
source_channels : list of ScopePyChannels
channel_function : MathFunction() class object
"""
# Initialise as ScopePy channel
super(MathChannel,self).__init__(*args,**kwargs)
# Store source channel and function
self.source = source_channels
self.mathFunction = math_function
# Copy axis labels from first source channel
self.x_axis = self.source[0].x_axis
self.y_axis = self.source[0].y_axis
# Copy data from source channel
self.updateFromSource()
# Link to source channels for updates
for channel in self.source:
self.connect(channel,SIGNAL("updateChannelPlot"),self.updateAll)
def updateFromSource(self):
"""
Update data from source channel.
this is usually triggered by the source channel
"""
logger.debug("MathFunction [%s]: Updating from source" % self.name)
self.chunks = self.source[0].chunks
# TODO : Chunks will need careful handling to make sure all channels
# have the same number.
def updateAll(self):
"""
Update from the source channel and then send the updatePlots signal
"""
self.updateFromSource()
self.updatePlots()
def data(self,**kwargs):
"""
Re-implementation of the data() function
Returns an array with the transformed x and y values
Output
-------
data_array : numpy structured array
data_array[x] = x_out
data_array[y] = y_out
"""
# Apply function to source channels
x_out,y_out = self.mathFunction(self.source)
dtype = [(self.x_axis,float),(self.y_axis,float)]
data_array = np.zeros(len(x_out),dtype)
data_array[self.x_axis] = x_out
data_array[self.y_axis] = y_out
return data_array
def getSourceData(self,**kwargs):
"""
Get the data from all source channels and put in a list
"""
source_data = []
for channel in self.source:
source_data.append(channel.data(**kwargs))
return source_data
@property
def isEmpty(self):
check_empty = [chan.isEmpty for chan in self.source]
return all(check_empty)
class MathFunction():
"""
Base class for MathChannel functions
Gives the basic methods and properties needed to define math functions
This class is used as the basis for any Math channel functions
Example usage for simple functions
-----------------------------------
>>> myFunc = MathFunction()
>>> myFunc.name = "func1"
>>> myFunc.description = "An example function"
>>> myFunc.function = lambda channel : (channel.x,channel.y**2)
For more complicated functions that have internal parameters then the class
can be inherited.
"""
# Define some validators for use in QLineEdits
numeric_only = r"[\.0-9\-\+e\*\/]+"
def __init__(self):
"""
Make a Math channel function with the specified name
"""
# Display name
self.name = 'no function'
# Description
self.description = 'No description'
# Function
# Must be of the form:
# x_out,y_out = f(list_of_channels)
# and it must be array friendly
self._function = None
self.function_inputs = None
self.number_function_inputs = 0
# For single inputs this sets whether it is a list of channels or just
# a single one
self.is_list_input = False
# Parameters
# Extra parameters that the function can use
# Dictionary of [parameter_name,parameter_value] pairs
self.parameters = {}
# Set default validator
self.validator = self.numeric_only
def __repr__(self):
return "<Math Channel function: %s>" % self.name
def __call__(self,channel_list):
"""
Execute the function on the list of source channels
Inputs
------
channel_list : list of ScopePy channels
"""
if self.is_list_input:
# Function requires list input
return self._function(channel_list)
else:
# function requires individual inputs
return self._function(*channel_list)
def getFunction(self):
"""
getter for the function
"""
return self._function
def setFunction(self,inputFunction):