-
Notifications
You must be signed in to change notification settings - Fork 589
/
layers.py
2779 lines (2372 loc) 路 109 KB
/
layers.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
import collections
import operator
import vaex.vaexfast
import threading
import matplotlib
import numpy as np
import scipy.ndimage
import matplotlib.colors
import traceback
import vaex
import vaex.delayed
import vaex.ui.storage
import vaex.ui.undo
import vaex.ui.colormaps
import vaex.grids
from vaex.ui.icons import iconfile
import vaex.utils
import vaex.promise
import vaex.ui.qt as dialogs
__author__ = 'maartenbreddels'
import copy
import functools
import time
from vaex.ui.qt import *
import logging
import astropy.units
try:
import healpy
except:
healpy = None
#from attrdict import AttrDict
from .plot_windows import AttrDict
logger = logging.getLogger("vaex.ui.layer")
storage_expressions = vaex.ui.storage.Storage("expressions")
class multilayer_attrsetter(object):
def __init__(self, layer, name):
self.layer = layer
self.name = name
def __call__(self, value):
if QtGui.QApplication.keyboardModifiers() == QtCore.Qt.ShiftModifier:
for layer in self.layer.plot_window.layers:
setattr(layer, self.name, value)
else:
setattr(self.layer, self.name, value)
#options.define_options("grid_size", int, validator=options.is_power_of_two)
class LinkButton(QtGui.QToolButton):
def __init__(self, title, dataset, axis_index, parent):
super(LinkButton, self).__init__(parent)
self.setToolTip("link this axes with others (experimental and unstable)")
self.plot = parent
self.dataset = dataset
self.axis_index = axis_index
self.setText(title)
#self.setAcceptDrops(True)
#self.disconnect_icon = QtGui.QIcon(iconfile('network-disconnect-2'))
#self.connect_icon = QtGui.QIcon(iconfile('network-connect-3'))
self.disconnect_icon = QtGui.QIcon(iconfile('link_break'))
self.connect_icon = QtGui.QIcon(iconfile('link'))
#self.setIcon(self.disconnect_icon)
#self.action_link_global = QtGui.QAction(self.connect_icon, '&Global link', self)
#self.action_unlink = QtGui.QAction(self.connect_icon, '&Unlink', self)
#self.menu = QtGui.QMenu()
#self.menu.addAction(self.action_link_global)
#self.menu.addAction(self.action_unlink)
#self.action_link_global.triggered.connect(self.onLinkGlobal)
self.setToolTip("Link or unlink axis. When an axis is linked, changing an axis (like zooming) will update all axis of plots that have the same (and linked) axis.")
self.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly)
self.setIcon(self.disconnect_icon)
#self.setDefaultAction(self.action_link_global)
self.setCheckable(True)
self.setChecked(False)
self.clicked.connect(self.onToggleLink)
#self.setMenu(self.menu)
self.link = None
def onToggleLink(self):
if self.isChecked():
logger.debug("connected link")
self.link = self.dataset.link(self.plot.expressions[self.axis_index], self)
self.setIcon(self.connect_icon)
else:
logger.debug("disconnecting link")
self.dataset.unlink(self.link, self)
self.link = None
self.setIcon(self.disconnect_icon)
def onLinkGlobal(self):
self.link = self.dataset.link(self.plot.expressions[self.axis_index], self)
logger.debug("made global link: %r" % self.link)
#self.parent.links[self.axis_index] = self.linkHandle
def onChangeRangeShow(self, range_):
logger.debug("received range show change for plot=%r, axis_index %r, range=%r" % (self.plot, self.axis_index, range_))
self.plot.ranges_show[self.axis_index] = range_
def onChangeRange(self, range_):
logger.debug("received range change for plot=%r, axis_index %r, range=%r" % (self.plot, self.axis_index, range_))
self.plot.ranges[self.axis_index] = range_
def onCompute(self):
logger.debug("received compute for plot=%r, axis_index %r" % (self.plot, self.axis_index))
self.plot.compute()
def onPlot(self):
logger.debug("received plot command for plot=%r, axis_index %r" % (self.plot, self.axis_index))
self.plot.plot()
def onLinkLimits(self, min, max):
self.plot.expressions[self.axis_index] = expression
def onChangeExpression(self, expression):
logger.debug("received change expression for plot=%r, axis_index %r, expression=%r" % (self.plot, self.axis_index, expression))
self.plot.expressions[self.axis_index] = expression
self.plot.axisboxes[self.axis_index].lineEdit().setText(expression)
def _dragEnterEvent(self, e):
print(e.mimeData())
print(e.mimeData().text())
if e.mimeData().hasFormat('text/plain'):
e.accept()
else:
e.ignore()
def dropEvent(self, e):
position = e.pos()
#self.button.move(position)
print("do", e.mimeData().text())
e.setDropAction(QtCore.Qt.MoveAction)
e.accept()
def _mousePressEvent(self, e):
super(LinkButton, self).mousePressEvent(e)
if e.button() == QtCore.Qt.LeftButton:
print('press')
def _mouseMoveEvent(self, e):
if e.buttons() != QtCore.Qt.LeftButton:
return
mimeData = QtCore.QMimeData()
drag = QtGui.QDrag(self)
drag.setMimeData(mimeData)
drag.setHotSpot(e.pos() - self.rect().topLeft())
mimeData.setText("blaat")
dropAction = drag.start(QtCore.Qt.MoveAction)
import vaex.dataset
class LayerTable(object):
def __init__(self, plot_window, name, dataset, expressions, axis_names, options, figure, canvas, ranges_grid=None):
"""
:type tasks: list[Task]
:type dataset: Dataset
:type plot_window: PlotDialog
"""
self.plot_window = plot_window
self.name = name
self.dataset = dataset
self.axis_names = axis_names
self.state = AttrDict()
self.state.ranges_grid = ranges_grid
self.state.title = options.get("title")
self.range_level = None
self.options = options
self.state.expressions = expressions
self.dimensions = len(self.state.expressions)
self.state.vector_expressions = [None,] * (1 if self.dimensions == 1 else 3)
self.figure = figure
self.canvas = canvas
self.widget_build = False
self.grid_vector = None
self._can_plot = False # when every process went though ok, this is True
self._needs_update = True
self.widget = None # each layer has a widget, atm only a qt widget is implemented
self.reset_progressbar()
self.state.weight = self.options.get("weight", self.dataset.get_column_names()[0])
self.state.statistic = self.options.get("statistic", "count")
self.state.weight_count = self.options.get("weight_count", "*")
self.state.amplitudes = {}
self.state.amplitudes["count"] = "log10(grid)"
self.state.amplitudes["mean"] = "grid"
self.state.amplitudes["sum"] = "grid"
self.state.amplitudes["std"] = "grid"
self.state.amplitudes["var"] = "grid"
self.state.amplitudes["min"] = "grid"
self.state.amplitudes["max"] = "grid"
self.state.show_disjoined = False
self.state.dataset_path = self.dataset.path
self.state.name = self.dataset.name
self.compute_counter = 0
self.sequence_index = 0
self.state.alpha = float(self.options.get("alpha", "1."))
self.state.style = options.get("style", "histogram")
#self.color = self.options.get("color")
self.level_min = 0.
self.level_max = 1.
#self.use_intensity = bool(self.options.get("use_intensity", True))
self.coordinates_picked_row = None
self.layer_slice_source = None # the layer we link to for slicing
self.slice_axis = [] # list of booleans, which axis we listen to
# we keep a list of vaex.dataset.Task, so that we can cancel, listen
# to progress etc
self.tasks = []
self._task_signals = []
self._histogram_counter = 0 # TODO: until we can cancel the server, we have to fix it with a counter
self.state.colormap = "PaulT_plusmin" #"binary"
self.state.colormap_vector = "binary"
if "lim" in self.options:
for i in range(self.dimensions):
self.state.ranges_grid[i] = eval(self.options["lim"])
if "ranges" in self.options:
ranges = self.options["ranges"]
if isinstance(self.options["ranges"], str):
ranges = eval(ranges)
for i in range(self.dimensions):
self.state.ranges_grid[i] = ranges[i]
if "xlim" in self.options:
self.state.ranges_grid[0] = eval(self.options["xlim"])
if "ylim" in self.options:
self.state.ranges_grid[1] = eval(self.options["ylim"])
if "zlim" in self.options:
self.state.ranges_grid[2] = eval(self.options["zlim"])
if "aspect" in self.options:
self.aspect = eval(self.options["aspect"])
self.action_aspect_lock_one.setChecked(True)
if "compact" in self.options:
value = self.options["compact"]
if value in ["ultra", "+"]:
self.action_mini_mode_ultra.trigger()
else:
self.action_mini_mode_normal.trigger()
self.first_time = True
self.state.show_disjoined = False # show p(x,y) as p(x)p(y)
if self.state.ranges_grid is None:
self.submit_job_minmax()
#self.dataset.mask_listeners.append(self.onSelectMask)
self.dataset.signal_selection_changed.connect(self.on_selection_changed)
self.dataset.signal_column_changed.connect(self.on_column_changed)
self.dataset.signal_variable_changed.connect(self.on_variable_changed)
#self.dataset.signal_selection_changed.
#self.dataset.row_selection_listeners.append(self.onSelectRow)
self.dataset.signal_pick.connect(self.on_pick)
self.dataset.signal_sequence_index_change.connect(self.on_sequence_changed)
#self.dataset.serie_index_selection_listeners.append(self.onSerieIndexSelect)
self.plot_density = self.plot_density_imshow
self.signal_expression_change = vaex.events.Signal("expression_change")
self.signal_plot_dirty = vaex.events.Signal("plot_dirty")
self.signal_plot_update = vaex.events.Signal("plot_update")
self.signal_needs_update = vaex.events.Signal("needs update")
#self.dataset.signal_pick.connect(self.on)
def __repr__(self):
classname = self.__class__.__module__ + "." +self.__class__.__name__
return "<%s(name=%r, expressions=%r)> instance at 0x%x" % (classname, self.name, self.state.expressions, id(self))
def amplitude_label(self):
unit_expression = None
what_units = None
statistics = self.statistic
if statistics in ["mean", "sum", "std", "min", "max", "median"]:
unit_expression = self.weight
if statistics in ["var"]:
unit_expression = "(%s) * (%s)" % (self.weight, self.weight)
if unit_expression:
unit = self.dataset.unit(unit_expression)
if unit:
what_units = unit.to_string('latex_inline')
label = "%s(%s)" % (self.statistic, self.weight if self.statistic is not "count" else self.weight_count)
label = self.amplitude.replace("grid", label)
if what_units:
label += " (%s)" % what_units
return label
def restore_state(self, state):
logger.debug("restoring layer %r to state %r ", self, state)
self.state = AttrDict(state)
for dim in range(self.dimensions):
logger.debug("set expression[%i] to %s", dim, self.state.expressions[dim])
self.set_expression(self.state.expressions[dim], dim)
for dim in range(self.vector_dimensions):
logger.debug("set vector expression[%i] to %s", dim, self.state.vector_expressions[dim])
self.set_vector_expression(self.state.vector_expressions[dim], dim)
#logger.debug("set weight expression to %s", dim, self.state.weight_expression)
#self.set_weight_expression(self.state.weight_expression)
#
# make sure it's refected in the gui
self.amplitude = self.amplitude
self.weight = self.weight
self.weight_count = self.weight_count
self.statistic = self.statistic
self.colorbar_checkbox.set_value(self.state.colorbar)
for dim in range(self.dimensions):
self.option_output_unit[dim].set_value(self.state.output_units[dim])
self.option_label_x.set_value(self.state.labels[0])
self.option_label_y.set_value(self.state.labels[1])
logger.debug("remove history change")
self.plot_window.queue_history_change(None)
def flag_needs_update(self):
self._needs_update = True
self.signal_needs_update.emit()
def get_needs_update(self):
return self._needs_update
@property
def x(self):
"""x expression"""
return self.state.expressions[0]
@x.setter
def x(self, value):
logger.debug("setting self.state.expressions[0] to %s" % value)
self.set_expression(value, 0)
@property
def y(self):
"""y expression"""
return self.state.expressions[1]
@y.setter
def y(self, value):
logger.debug("setting self.state.expressions[1] to %s" % value)
self.set_expression(value, 1)
@property
def z(self):
"""y expression"""
return self.state.expressions[2]
@y.setter
def z(self, value):
logger.debug("setting self.state.expressions[2] to %s" % value)
self.set_expression(value, 2)
@property
def vx(self):
"""vector x expression"""
return self.state.vector_expressions[0]
@vx.setter
def vx(self, value):
logger.debug("setting self.state.vector_expressions[0] to %s" % value)
self.set_vector_expression(value, 0)
@property
def vy(self):
"""vector y expression"""
return self.state.vector_expressions[1]
@vy.setter
def vy(self, value):
logger.debug("setting self.state.vector_expressions[1] to %s" % value)
self.set_vector_expression(value, 1)
@property
def vz(self):
"""vector z expression"""
return self.state.vector_expressions[2]
@vz.setter
def vz(self, value):
logger.debug("setting self.state.vector_expressions[2] to %s" % value)
self.set_vector_expression(value, 2)
@property
def statistic(self):
"""vector z expression"""
return self.state.statistic
@statistic.setter
def statistic(self, value):
logger.debug("setting self.state.statistic to %s" % value)
self.state.statistic = value
if self.option_statistic.combobox.currentText() != value:
self.option_statistic.set_value(value)
self.check_statistics_weights()
self.amplitude = self.amplitude # trigger setting the right text
self.plot_window.queue_history_change("changed statistic to %s" % (value))
@property
def amplitude(self):
"""amplitude expression"""
#return self.amplitude
return self.state.amplitudes[self.statistic]
@amplitude.setter
def amplitude(self, value):
logger.debug("setting self.amplitude to %s" % value)
self.state.amplitudes[self.statistic] = value
self.amplitude_box.lineEdit().setText(value)
#self.plot_window.queue_update()
self.signal_plot_dirty.emit()
self.plot_window.queue_history_change("changed amplitude to %s" % (value))
def set_range(self, min, max, dimension=0):
#was_equal = list(self.plot_window.state.ranges_viewport[dimension]) == [min, max]
if min is None or max is None:
self.state.ranges_grid[dimension] = None
else:
self.state.ranges_grid[dimension] = [min, max]
#self.plot_window.state.ranges_viewport[dimension] = list(self.state.ranges_grid[dimension])
#self.plot_window.set_range(min, max, dimension=dimension)
if dimension == 0:
self.option_xrange.set_value((min, max), update=False)
if dimension == 1:
self.option_yrange.set_value((min, max), update=False)
if dimension == 2:
self.option_zrange.set_value((min, max), update=False)
#return not was_equal
def get_range(self, dimension=0):
return list(self.state.ranges_grid[dimension]) if self.state.ranges_grid[dimension] is not None else None
@property
def xlim(self):
"""vector z expression"""
return self.get_range(0)
@xlim.setter
def xlim(self, value):
vmin, vmax = value
self.plot_window.set_range(vmin, vmax, 0)
self.update()
@property
def ylim(self):
"""vector z expression"""
return self.get_range(1)
@ylim.setter
def ylim(self, value):
vmin, vmax = value
self.plot_window.set_range(vmin, vmax, 1)
self.update()
@property
def zlim(self):
"""vector z expression"""
return self.get_range(2)
@xlim.setter
def zlim(self, value):
vmin, vmax = value
self.plot_window.set_range(vmin, vmax, 2)
self.update()
@property
def weight_count(self):
return self.state.weight_count
@weight_count.setter
def weight_count(self, expression):
if expression is not None:
expression = expression.strip()
if expression == "":
expression = None
widget = self.option_weight_count.combobox
if expression:
if expression != "*": # * is special
try:
self.dataset.validate_expression(expression)
except Exception as e:
self.error_in_field(widget, "weight", e)
return
self.state.weight_count = expression
self.plot_window.queue_history_change("changed weight expression to %s" % (expression))
if widget.currentText() != expression:
widget.setCurrentIndex(self.option_weight_count.options.index(expression))
self.range_level = None
self.plot_window.range_level_show = None
self.update()
@property
def weight(self):
return self.state.weight
@weight.setter
def weight(self, expression):
if expression is not None:
expression = expression.strip()
if expression == "":
expression = None
widget = self.option_weight_statistic.combobox
if expression:
try:
self.dataset.validate_expression(expression)
except Exception as e:
self.error_in_field(widget, "weight", e)
return
self.state.weight = expression
self.plot_window.queue_history_change("changed weight expression to %s" % (expression))
if widget.currentText() != expression:
widget.lineEdit().setText(expression)
self.range_level = None
self.plot_window.range_level_show = None
self.update()
def removed(self):
#self.dataset.mask_listeners.remove(self.onSelectMask)
self.dataset.signal_selection_changed.disconnect(self.on_selection_changed)
self.dataset.signal_pick.disconnect(self.on_pick)
self.dataset.signal_sequence_index_change.disconnect(self.on_sequence_changed)
#self.dataset.row_selection_listeners.remove(self.onSelectRow)
#self.dataset.serie_index_selection_listeners.remove(self.onSerieIndexSelect)
for plugin in self.plugins:
plugin.clean_up()
def create_grid_map(self, gridsize, use_selection):
return {"counts":self.temp_grid, "weighted":None, "weightx":None, "weighty":None, "weightz":None}
def create_grid_map_(self, gridsize, use_selection):
locals = {}
for name in list(self.grids.grids.keys()):
grid = self.grids.grids[name]
if name == "counts" or (grid.weight_expression is not None and len(grid.weight_expression) > 0):
if grid.max_size >= gridsize:
locals[name] = grid.get_data(gridsize, use_selection=use_selection, disjoined=self.plot_window.show_disjoined)
#import vaex.kld
#print("Mutual information", name, gridsize, self.state.expressions, vaex.kld.mutual_information(locals[name]))
else:
locals[name] = None
for d, name in zip(list(range(self.dimensions)), "xyzw"):
width = self.state.ranges_grid[d][1] - self.state.ranges_grid[d][0]
offset = self.state.ranges_grid[d][0]
x = (np.arange(0, gridsize)+0.5)/float(gridsize) * width + offset
locals[name] = x
return locals
def eval_amplitude(self, expression, locals):
amplitude = None
locals = dict(locals)
if "gf" not in locals:
locals["gf"] = scipy.ndimage.gaussian_filter
counts = locals["counts"]
if self.dimensions == 2:
peak_columns = np.apply_along_axis(np.nanmax, 1, counts)
peak_columns[peak_columns==0] = 1.
peak_columns = peak_columns.reshape((1, -1))#.T
locals["peak_columns"] = peak_columns
sum_columns = np.apply_along_axis(np.nansum, 1, counts)
sum_columns[sum_columns==0] = 1.
sum_columns = sum_columns.reshape((1, -1))#.T
locals["sum_columns"] = sum_columns
peak_rows = np.apply_along_axis(np.nanmax, 0, counts)
peak_rows[peak_rows==0] = 1.
peak_rows = peak_rows.reshape((-1, 1))#.T
locals["peak_rows"] = peak_rows
sum_rows = np.apply_along_axis(np.nansum, 0, counts)
sum_rows[sum_rows==0] = 1.
sum_rows = sum_rows.reshape((-1, 1))#.T
locals["sum_rows"] = sum_rows
weighted = locals["weighted"]
if weighted is None:
locals["average"] = None
else:
average = weighted/counts
average[counts==0] = np.nan
locals["average"] = average
globals = np.__dict__
amplitude = eval(expression, globals, locals)
return amplitude
def error_dialog(self, widget, name, exception):
dialogs.dialog_error(widget, "Error", "%s: %r" % (name, exception))
def error_in_field(self, widget, name, exception):
dialogs.dialog_error(widget, "Error in expression", "Invalid expression for field %s: %r" % (name, exception))
#self.current_tooltip = QtGui.QToolTip.showText(widget.mapToGlobal(QtCore.QPoint(0, 0)), "Error: " + str(exception), widget)
#self.current_tooltip = QtGui.QToolTip.showText(widget.mapToGlobal(QtCore.QPoint(0, 0)), "Error: " + str(exception), widget)
def plot_scatter(self, axes_list):
for ax in axes_list:
# TODO: support multiple axes with the axis index
x = self.dataset.evaluate(self.x)
y = self.dataset.evaluate(self.y)
ax.scatter(x, y, alpha=self.state.alpha, color=self.color)
row = self.dataset.get_current_row()
if row is not None:
ax.scatter([x[row]], [y[row]], alpha=self.state.alpha, color=self.color_alt)
def plot_schlegel(self, axes_list, stack_image):
if not hasattr(self, "schlegel_map"):
self.schlegel_map = healpy.read_map('data/lambda_sfd_ebv.fits', nest=False)
xlim, ylim = self.plot_window.state.ranges_viewport
phis = np.linspace(np.deg2rad(xlim[0]), np.deg2rad(xlim[1]), self.plot_window.state.grid_size)# + np.pi/2.
thetas = np.pi-np.linspace(np.deg2rad(ylim[1]) + np.pi/2., np.deg2rad(ylim[0]) + np.pi/2., self.plot_window.state.grid_size)
#phis = (np.linspace(0, 2*np.pi, 256) - np.pi) % (2*np.pi)
thetas, phis = np.meshgrid(thetas, phis)
pix = healpy.ang2pix(512, thetas, phis)
I = self.schlegel_map[pix].T[::-1,:]
I = self._normalize_values(np.log(I))
self.schlegel_projected = I
rgb = self._to_rgb(I, color=self.color)
axes_list[0].rgb_images.append(rgb)
#print "SCHL" * 1000
#pylab.imshow(np.log(schlegel_map[pix].T))
def plot(self, axes_list, stack_image):
if self._can_plot:
logger.debug("begin plot: %r, style: %r", self, self.state.style)
else:
logger.debug("cannot plot layer: %r" % self)
return
if not self.visible:
return
if self.state.style == "scatter":
self.plot_scatter(axes_list)
return
#return
logger.debug("total sum of amplitude grid: %s", np.nansum(self.amplitude_grid_view))
if self.dimensions == 1:
mask = ~(np.isnan(self.amplitude_grid_view) | np.isinf(self.amplitude_grid_view))
if np.sum(mask) == 0:
self.range_level = None
else:
values = self.amplitude_grid_view * 1.
#def nancumsum()
if self._cumulative:
values[~mask] = 0
values = np.cumsum(values)
if self._normalize:
if self._cumulative:
values /= values[-1]
else:
values /= np.sum(values[mask]) # TODO: take dx into account?
if self.dataset.has_selection():
mask_selected = ~(np.isnan(self.amplitude_grid_selection_view) | np.isinf(self.amplitude_grid_selection_view))
values_selected = self.amplitude_grid_selection_view * 1.
if self._cumulative:
values_selected[~mask_selected] = 0
values_selected = np.cumsum(values_selected)
if self._normalize:
if self._cumulative:
values_selected /= values_selected[-1]
else:
values_selected /= np.sum(values_selected[mask_selected]) # TODO: take dx into account?
width = self.state.ranges_grid[0][1] - self.state.ranges_grid[0][0]
x = np.arange(0, self.plot_window.state.grid_size)/float(self.plot_window.state.grid_size) * width + self.state.ranges_grid[0][0]# + width/(Nvector/2.)
delta = x[1] - x[0]
for axes in axes_list:
if self.show in ["total+selection", "total"]:
if self.display_type == "bar":
axes.bar(x, values, width=delta, align='center', alpha=self.state.alpha, color=self.color)
else:
dx = x[1] - x[0]
x2 = list(np.ravel(list(zip(x,x+dx))))
x2p = [x[0]] + x2 + [x[-1]+dx]
y = values
y2 = list(np.ravel(list(zip(y,y))))
y2p = [0] + y2 + [0]
axes.plot(x2p, y2p, alpha=self.state.alpha, color=self.color)
if self.show in ["total+selection", "selection"]:
if self.dataset.has_selection():
if self.display_type == "bar":
axes.bar(x, values_selected, width=delta, align='center', color=self.color_alt, alpha=0.6*self.state.alpha)
else:
dx = x[1] - x[0]
x2 = list(np.ravel(list(zip(x,x+dx))))
x2p = [x[0]] + x2 + [x[-1]+dx]
y = values_selected
y2 = list(np.ravel(list(zip(y,y))))
y2p = [0] + y2 + [0]
axes.plot(x2p, y2p, drawstyle="steps-mid", alpha=self.state.alpha, color=self.color_alt)
#3if self.coordinates_picked_row is not None:
index = self.dataset.get_current_row()
logger.debug("current row: %r" % index)
if index is not None:
x = self.subspace.row(index)
axes.axvline(x[axes.xaxis_index], color="red")
#if self.dimensions == 2:
# #for axes in axes_list:
# assert len(axes_list) == 1
# self.plot_density(axes_list[0], self.amplitude_grid, self.amplitude_grid_selection, stack_image)
if self.dimensions >= 2:
# for vector we only use the selected map, maybe later also show the full dataset
#grid_map_vector = self.create_grid_map(self.plot_window.state.vector_grid_size, use_selection)
self.vector_grid = None
if 1: #any(self.state.vector_expressions):
grid_vector = self.grid_vector
if self.layer_slice_source:
grid_vector = grid_vector.slice(self.slice_selection_grid)
vector_grids = None
if any(self.state.vector_expressions):
vector_counts = grid_vector.evaluate("countx") # TODO: what should the mask be..
vector_mask = vector_counts > 0
if grid_vector.evaluate("sumx") is not None:
vector_x = grid_vector.evaluate("x")
vx = grid_vector.evaluate("sumx/countx")
if self.vectors_subtract_mean:
vx -= vx[vector_mask].mean()
else:
vector_x = None
vx = None
if grid_vector.evaluate("sumy") is not None:
vector_y = grid_vector.evaluate("y")
vy = grid_vector.evaluate("sumy/county")
if self.vectors_subtract_mean:
vy -= vy[vector_mask].mean()
else:
vector_y = None
vy = None
if grid_vector.evaluate("sumz") is not None:
if self.dimensions >= 3:
vector_z = grid_vector.evaluate("z")
else:
vector_z = None
vz = grid_vector.evaluate("sumz/countz")
if self.vectors_subtract_mean:
vz -= vz[vector_mask].mean()
else:
vector_z = None
vz = None
logger.debug("vx=%s vy=%s vz=%s", vx, vy, vz)
if vx is not None and vy is not None and vz is not None:
self.vector_grid = np.zeros((4, ) + ((vx.shape[0],) * 3), dtype=np.float32)
self.vector_grid[0] = vx.T
self.vector_grid[1] = vy.T
self.vector_grid[2] = vz.T
self.vector_grid[3] = vector_counts.T
self.vector_grid = np.swapaxes(self.vector_grid, 0, 3)
self.vector_grid = self.vector_grid * 1.
self.vector_grids = vector_grids = [vx, vy, vz]
vector_positions = [vector_x, vector_y, vector_z]
for axes in axes_list:
#if 0:
# create marginalized grid
all_axes = list(range(self.dimensions))
# all_axes.remove(self.dimensions-1-axes.xaxis_index)
# all_axes.remove(self.dimensions-1-axes.yaxis_index)
all_axes.remove(axes.xaxis_index)
all_axes.remove(axes.yaxis_index)
#if 1:
#grid_map_2d = {key:None if grid is None else (grid if grid.ndim != 3 else vaex.utils.multisum(grid, all_axes)) for key, grid in list(grid_map.items())}
#grid_context = self.grid_vector
#amplitude = grid_context(self.amplitude, locals=grid_map_2d)
#grid = self.grid_main.marginal2d(self.dimensions-1-axes.xaxis_index, self.dimensions-1-axes.yaxis_index)
grid = self.grid_main.marginal2d(axes.xaxis_index, axes.yaxis_index)
if self.state.show_disjoined:
grid = grid.disjoined()
try:
amplitude = grid.evaluate(self.amplitude)
except Exception as e:
self.error_in_field(self.amplitude_box, "amplitude of layer %s" % self.name, e)
return
if self.dataset.has_selection():
#grid_map_selection_2d = {key:None if grid is None else (grid if grid.ndim != 3 else vaex.utils.multisum(grid, all_axes)) for key, grid in list(grid_map_selection.items())}
#grid_selection = self.grid_main_selection.marginal2d(self.dimensions-1-axes.xaxis_index, self.dimensions-1-axes.yaxis_index)
grid_selection = self.grid_main_selection.marginal2d(axes.xaxis_index, axes.yaxis_index)
if self.state.show_disjoined:
grid_selection = grid_selection.disjoined()
amplitude_selection = grid_selection.evaluate(self.amplitude)
else:
amplitude_selection = None
#print("total amplit")
self.plot_density(axes, amplitude, amplitude_selection, stack_image)
if len(all_axes) > 2:
other_axis = all_axes[0]
assert len(all_axes) == 1, ">3d not supported"
else:
other_axis = 2
if vector_grids:
#vector_grids[vector_grids==np.inf] = np.nan
U = vector_grids[axes.xaxis_index]
V = vector_grids[axes.yaxis_index]
W = vector_grids[other_axis]
vx = None if U is None else vaex.utils.multisum(U, all_axes)
vy = None if V is None else vaex.utils.multisum(V, all_axes)
vz = None if W is None else vaex.utils.multisum(W, all_axes)
vector_counts_2d = vaex.utils.multisum(vector_counts, all_axes)
if vx is not None and vy is not None:
count_max = vector_counts_2d.max()
mask = (vector_counts_2d > (self.vector_level_min * count_max)) & \
(vector_counts_2d <= (self.vector_level_max * count_max))
x = vector_positions[axes.xaxis_index]
y = vector_positions[axes.yaxis_index]
x2d, y2d = np.meshgrid(x, y)
#x2d, y2d = x2d.T, y2d.T
#mask = mask.T
colors, colormap = None, None
if True:
if self.vector_auto_scale:
length = np.nanmean(np.sqrt(vx[mask]**2 + vy[mask]**2))# / 1.5
logger.debug("auto scaling using length: %r", length)
vx[mask] /= length
vy[mask] /= length
scale = self.plot_window.state.vector_grid_size / self.vector_scale
width = self.vector_head_width * 0.1/self.plot_window.state.vector_grid_size
xsign = 1 if self.state.ranges_grid[0][0] <= self.state.ranges_grid[0][1] else -1
ysign = 1 if self.state.ranges_grid[1][0] <= self.state.ranges_grid[1][1] else -1
if vz is not None and self.vectors_color_code_3rd:
colors = vz
colormap = self.state.colormap_vector
axes.quiver(x2d[mask.T], y2d[mask.T], vx.T[mask.T] * xsign, vy.T[mask.T] * ysign, colors[mask], cmap=colormap, scale_units="width", scale=scale, width=width)
else:
axes.quiver(x2d[mask.T], y2d[mask.T], vx.T[mask.T] * xsign, vy.T[mask.T] * ysign, color=self.color, scale_units="width", scale=scale, width=width)
logger.debug("quiver: %s", self.vector_scale)
colors = None
if 0: #if self.coordinates_picked_row is not None:
if self.dimensions >= 2:
for axes in axes_list:
axes.scatter([self.coordinates_picked_row[axes.xaxis_index]], [self.coordinates_picked_row[axes.yaxis_index]], color='red')
if self.dimensions >= 2:
for axes in axes_list:
index = self.dataset.get_current_row()
logger.debug("current row: %r" % index)
if index is not None:
x = self.subspace.row(index)
axes.scatter([x[axes.xaxis_index]], [x[axes.yaxis_index]], color='red')
def getVariableDict(self):
return {} # TODO: remove this? of replace
def _normalize_values(self, amplitude):
I = amplitude*1.#self.contrast(amplitude)
# scale to [0,1]
mask = ~(np.isnan(I) | np.isinf(I))
if np.sum(mask) == 0:
return np.zeros(I.shape, dtype=np.float64)
I -= I[mask].min()
I /= I[mask].max()
return I
def _to_rgb(self, intensity, color, pre_alpha=1.):
I = intensity
mask = ~(np.isnan(I) | np.isinf(I))
if np.sum(mask) == 0:
return np.zeros(I.shape + (4,), dtype=np.float64)
minvalue = I[mask].min()
maxvalue = I[mask].max()
if minvalue == maxvalue:
return np.zeros(I.shape + (4,), dtype=np.float64)
I -= minvalue
I /= maxvalue
# scale [min, max] to [0, 1]
I -= self.level_min
I /= (self.level_max - self.level_min)
#if self.color is not None:
alpha_mask = (mask) & (I > 0)
if self.display_type == "solid":
color_tuple = matplotlib.colors.colorConverter.to_rgb(color)
rgba = np.zeros(I.shape + (4,), dtype=np.float64)
rgba[alpha_mask,0:3] = np.array(color_tuple)
else:
cmap = matplotlib.cm.cmap_d[self.state.colormap]
rgba = cmap(I * 1.00)
rgba[...,3] = (np.clip((I**1.0) * self.state.alpha, 0, 1))
if self.transparancy == "intensity":
rgba[...,3] = (np.clip((I**1.0) * self.state.alpha, 0, 1)) * self.state.alpha * pre_alpha
elif self.transparancy == "constant":
rgba[alpha_mask,3] = 1. * self.state.alpha * pre_alpha
rgba[~alpha_mask,3] = 0
elif self.transparancy == "none":
rgba[...,3] = pre_alpha
else:
raise NotImplemented
return rgba
def plot_density_imshow(self, axes, amplitude, amplitude_selection, stack_image):
if not self.visible:
return
ranges = []
for minimum, maximum in self.state.ranges_grid:
ranges.append(minimum)
ranges.append(maximum)
use_selection = amplitude_selection is not None
#if isinstance(self.state.colormap, basestring):
levels = (np.arange(self.contour_count) + 1. ) / (self.contour_count + 1)
levels = np.linspace(self.level_min, self.level_max, self.contour_count)
ranges = list(self.state.ranges_grid[0]) + list(self.state.ranges_grid[1])
amplitude_marginalized = amplitude
amplitude_marginalized_selected = amplitude_selection
mask = ~(np.isnan(amplitude_marginalized) | np.isinf(amplitude_marginalized))
if np.sum(mask) == 0: # if nothing to show
vmin, vmax = 0, 1
else:
vmin, vmax = amplitude_marginalized[mask].min(), amplitude_marginalized[mask].max()
self.level_ranges = [vmin + self.level_min * (vmax - vmin), vmin + self.level_max * (vmax - vmin)]
logger.debug("level ranges: %r" % self.level_ranges)
if self.display_type == "contour":
if self.contour_count > 0:
if self.show == "total+selection":
if use_selection and self.show:
axes.contour(self._normalize_values(amplitude_marginalized).T, origin="lower", extent=ranges, levels=levels, linewidths=1, colors=self.color, alpha=0.4*self.state.alpha)
axes.contour(self._normalize_values(amplitude_marginalized_selected).T, origin="lower", extent=ranges, levels=levels, linewidths=1, colors=self.color_alt, alpha=self.state.alpha)
else:
axes.contour(self._normalize_values(amplitude_marginalized).T, origin="lower", extent=ranges, levels=levels, linewidths=1, colors=self.color, alpha=self.state.alpha)
elif self.show == "total":
axes.contour(self._normalize_values(amplitude_marginalized).T, origin="lower", extent=ranges, levels=levels, linewidths=1, colors=self.color, alpha=self.state.alpha)
elif self.show == "selection":
axes.contour(self._normalize_values(amplitude_marginalized_selected).T, origin="lower", extent=ranges, levels=levels, linewidths=1, colors=self.color_alt, alpha=self.state.alpha)
else:
if self.show == "total+selection":
I = self._normalize_values(amplitude_marginalized)
axes.rgb_images.append(self._to_rgb(I, color=self.color, pre_alpha=0.4 if use_selection else 1.0))
if use_selection:
I = self._normalize_values(amplitude_marginalized_selected)
axes.rgb_images.append(self._to_rgb(I, color=self.color_alt))
elif self.show == "total":
I = self._normalize_values(amplitude_marginalized)
axes.rgb_images.append(self._to_rgb(I, color=self.color))
elif self.show == "selection" and amplitude_marginalized_selected is not None:
I = self._normalize_values(amplitude_marginalized_selected)
axes.rgb_images.append(self._to_rgb(I, color=self.color_alt))
def on_selection_changed(self, dataset):
self.check_selection_undo_redo()
#self.plot_window.queue_update(layer=self)
self.update()
#self.add_jobs()
#self.label_selection_info_update()
#self.plot()