File: plot_objects.py

package info (click to toggle)
mmass 5.1.0-2
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 8,396 kB
  • sloc: python: 33,183; xml: 7,925; ansic: 1,722; makefile: 83; sh: 2
file content (1588 lines) | stat: -rw-r--r-- 54,038 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
# -------------------------------------------------------------------------
#     Copyright (C) 2005-2012 Martin Strohalm <www.mmass.org>

#     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 3 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.

#     Complete text of GNU GPL can be found in the file LICENSE.TXT in the
#     main directory of the program.
# -------------------------------------------------------------------------

# load libs
import wx
import numpy
import copy

# load modules
import mod_signal
import calculations


# MAIN PLOT OBJECTS
# -----------------

class container:
    """Container to hold plot objects."""
    
    def __init__(self, objects):
        self.objects = objects
    # ----
    
    
    def __additem__(self, obj):
        self.objects.append(obj)
    # ----
    
    
    def __delitem__(self, index):
        del self.objects[index]
    # ----
    
    
    def __setitem__(self, index, obj):
        self.objects[index] = obj
    # ----
    
    
    def __getitem__(self, index):
        return self.objects[index]
    # ----
    
    
    def __len__(self):
        return len(self.objects)
    # ----
    
    
    def getBoundingBox(self, minX=None, maxX=None, absolute=False):
        """Get bounding box coverring all visible objects."""
        
        # init values if no data in objects
        rect = [numpy.array([0, 0]), numpy.array([1, 1])]
        
        # get bouding boxes from objects
        have = False
        for obj in self.objects:
            if obj.properties['visible']:
                oRect = obj.getBoundingBox(minX, maxX, absolute)
                if have and oRect:
                    rect[0] = numpy.minimum(rect[0], oRect[0])
                    rect[1] = numpy.maximum(rect[1], oRect[1])
                elif oRect:
                    rect = oRect
                    have = True
        
        # check scale
        if rect[0][0] == rect[1][0]:
            rect[0][0] -= 0.5
            rect[1][0] += 0.5
        if rect[0][1] == rect[1][1]:
            rect[1][1] += 0.5
        
        return rect
    # ----
    
    
    def getLegend(self):
        """Get a list of legend names."""
        
        # get names
        names = []
        for obj in self.objects:
            if obj.properties['visible']:
                legend = obj.getLegend()
                if legend and legend[0] != '':
                    names.append(obj.getLegend())
            
        return names
    # ----
    
    
    def getPoint(self, obj, xPos, coord='screen'):
        """Get interpolated Y position for given X."""
        return self.objects[obj].getPoint(xPos, coord)
    # ----
    
    
    def countGels(self):
        """Get number of visible gels."""
        
        count = 0
        for obj in self.objects:
            if obj.properties['visible'] and obj.properties['showInGel']:
                count += 1
        
        return max(count,1)
    # ----
    
    
    def cropPoints(self, minX, maxX):
        """Crop points in all visible objects to selected X range."""
        
        for obj in self.objects:
            if obj.properties['visible']:
                obj.cropPoints(minX, maxX)
    # ----
    
    
    def scaleAndShift(self, scale, shift):
        """Scale and shift all visible objects."""
        
        for obj in self.objects:
            if obj.properties['visible']:
                obj.scaleAndShift(scale, shift)
    # ----
    
    
    def filterPoints(self, filterSize):
        """Filter points in all visible objects."""
        
        for obj in self.objects:
            if obj.properties['visible']:
                obj.filterPoints(filterSize)
    # ----
    
    
    def draw(self, dc, printerScale, overlapLabels, reverse):
        """Draw all visible objects."""
        
        # draw in reverse order
        if reverse:
            self.objects.reverse()
            
        # draw objects
        for obj in self.objects:
            if obj.properties['visible']:
                obj.draw(dc, printerScale)
        
        # draw object's labels
        self.drawLabels(dc, printerScale, overlapLabels)
        
        # reverse back order
        if reverse:
            self.objects.reverse()
    # ----
    
    
    def drawLabels(self, dc, printerScale, overlapLabels):
        """Draw labels for all visible objects."""
        
        # get labels from objects
        annots = []
        labels = []
        for obj in self.objects:
            if obj.properties['visible'] and isinstance(obj, annotations):
                annots += obj.makeLabels(dc, printerScale)
            elif obj.properties['visible']:
                labels += obj.makeLabels(dc, printerScale)
        
        # check labels
        if not annots and not labels:
            return
        
        # sort labels
        annots.sort()
        annots.reverse()
        labels.sort()
        labels.reverse()
        labels = annots + labels
        
        # preset font by first label
        font = labels[0][3]['labelFont']
        colour = labels[0][3]['labelColour']
        bgr = labels[0][3]['labelBgr']
        bgrColour = labels[0][3]['labelBgrColour']
        
        dc.SetFont(_scaleFont(font, printerScale['fonts']))
        dc.SetTextForeground(colour)
        dc.SetTextBackground(bgrColour)
        
        if bgr:
            dc.SetBackgroundMode(wx.SOLID)
        
        # draw labels
        occupied = []
        for label in labels:
            text = label[1]
            textCoords = label[2]
            properties = label[3]
            
            # check limits
            if abs(textCoords[1]) > 10000000:
                continue
            
            # check free space and draw label
            if overlapLabels or self._checkFreeSpace(textCoords, occupied):
                
                # check pen
                if properties['labelFont'] != font:
                    font = properties['labelFont']
                    dc.SetFont(_scaleFont(font, printerScale['fonts']))
                
                if properties['labelColour'] != colour:
                    colour = properties['labelColour']
                    dc.SetTextForeground(colour)
                
                #if properties['labelBgrColour'] != bgrColour:
                #    bgrColour = properties['labelBgrColour']
                #    dc.SetTextBackground(bgrColour)
                
                if properties['labelBgr'] != bgr:
                    bgr = properties['labelBgr']
                    if bgr:
                        dc.SetBackgroundMode(wx.SOLID)
                    else:
                        dc.SetBackgroundMode(wx.TRANSPARENT)
                
                # set angle
                angle = properties['labelAngle']
                if angle == 90 and properties['flipped']:
                    angle = -90
                
                # draw label
                dc.DrawRotatedText(text, textCoords[0], textCoords[1], angle)
                occupied.append(textCoords)
        
        dc.SetBackgroundMode(wx.TRANSPARENT)
    # ----
    
    
    def drawGel(self, dc, gelCoords, gelHeight, printerScale):
        """Draw gel for all allowed objects."""
        
        # draw objects
        for obj in self.objects:
            if obj.properties['visible'] and obj.properties['showInGel']:
                obj.drawGel(dc, gelCoords, gelHeight, printerScale)
                gelCoords[0] += gelHeight
    # ----
    
    
    def append(self, obj):
        self.objects.append(obj)
    # ----
    
    
    def empty(self):
        del self.objects[:]
    # ----
    
    
    def _checkFreeSpace(self, coords, occupied):
        """Check free space for label."""
        
        curX1, curY1, curX2, curY2 = coords
        
        # check occupied space
        for occX1, occY1, occX2, occY2 in occupied:
            if (curX1 < curX2) and ((occX1 <= curX1 <= occX2) or (occX1 <= curX2 <= occX2) or (curX1 <= occX1 and curX2 >= occX2)):
                if (occY2 <= curY1 <= occY1) or (occY2 <= curY2 <= occY1) or (curY1 >= occY1 and curY2 <= occY2):
                    return False
            elif (curX1 > curX2) and ((occX2 <= curX1 <= occX1) or (occX2 <= curX2 <= occX1) or (curX1 <= occX2 and curX2 >= occX1)):
                if (occY1 <= curY1 <= occY2) or (occY1 <= curY2 <= occY2) or (curY1 >= occY2 and curY2 <= occY1):
                    return False
        
        return True
    # ----
    


class annotations:
    """Base class for annotations drawing."""
    
    def __init__(self, points, **attr):
        
        # set default params
        self.properties = {
                            'visible': True,
                            'flipped': False,
                            'xOffset': 0,
                            'yOffset': 0,
                            'normalized': False,
                            'showInGel': False,
                            'exactFit': False,
                            'showPoints': True,
                            'showLabels': True,
                            'showXPos': True,
                            'pointColour': (0, 0, 255),
                            'pointSize': 3,
                            'labelAngle': 90,
                            'labelBgr': True,
                            'labelColour': (0, 0, 0),
                            'labelBgrColour': (255, 255, 255),
                            'labelFont': wx.Font(10, wx.SWISS, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0),
                            'labelMaxLength': 20,
                            'xPosDigits': 2,
                            }
        
        self.currentScale = (1., 1.)
        self.currentShift = (0., 0.)
        self.normalization = 1.0
        
        # get new attributes
        for name, value in attr.items():
            self.properties[name] = value
        
        # convert points to array
        self.points = numpy.array([[p[0], p[1]] for p in points])
        self.pointsCropped = self.points
        self.pointsScaled = self.pointsCropped
        if len(self.points):
            self.pointsBox = (numpy.minimum.reduce(self.points), numpy.maximum.reduce(self.points))
        
        # get labels
        self.labels = ['']*len(points)
        for x, point in enumerate(points):
            if len(point) > 2:
                self.labels[x] = point[2]
        self.labelsCropped = self.labels
        
        # calculate normalization
        self._normalization()
    # ----
    
    
    def setProperties(self, **attr):
        """Set object properties."""
        
        for name, value in attr.items():
            self.properties[name] = value
    # ----
    
    
    def setNormalization(self, value):
        """Force specified normalization to be used insted of calculated one."""
        self.normalization = value
    # ----
    
    
    def getBoundingBox(self, minX=None, maxX=None, absolute=False):
        """Get bounding box for whole data or X selection"""
        
        # use relevant data
        if minX != None and maxX != None:
            self.cropPoints(minX, maxX)
            data = self.pointsCropped
        else:
            data = self.points
        
        # check data
        if not len(data):
            return False
        
        # get range
        if minX != None and maxX != None:
            minXY = numpy.minimum.reduce(data)
            maxXY = numpy.maximum.reduce(data)
        else:
            minXY = [self.pointsBox[0][0], self.pointsBox[0][1]]
            maxXY = [self.pointsBox[1][0], self.pointsBox[1][1]]
        
        # extend values slightly to fit data
        if not absolute and not self.properties['exactFit']:
            xExtend = (maxXY[0] - minXY[0]) * 0.05
            yExtend = (maxXY[1] - minXY[1]) * 0.05
            minXY[0] -= xExtend
            maxXY[0] += xExtend
            minXY[1] -= yExtend
            maxXY[1] += yExtend
            
        # extend values to fit labels
        elif not absolute:
            if self.properties['showLabels'] and self.properties['labelAngle']==0:
                maxXY[1] += (maxXY[1] - minXY[1]) * 0.2
            elif self.properties['showLabels'] and self.properties['labelAngle']==90:
                maxXY[1] += (maxXY[1] - minXY[1]) * 0.4
            else:
                maxXY[1] += (maxXY[1] - minXY[1]) * 0.05
        
        # apply normalization
        if self.properties['normalized']:
            minXY[1] = minXY[1] / self.normalization
            maxXY[1] = maxXY[1] / self.normalization
        
        # apply offset
        minXY[0] += self.properties['xOffset']
        minXY[1] += self.properties['yOffset']
        maxXY[0] += self.properties['xOffset']
        maxXY[1] += self.properties['yOffset']
        
        # apply flipping
        if self.properties['flipped']:
            minY = -1 * maxXY[1]
            maxY = -1 * minXY[1]
            minXY[1] = minY
            maxXY[1] = maxY
        
        return [minXY, maxXY]
    # ----
    
    
    def getLegend(self):
        """Get legend."""
        return None
    # ----
    
    
    def cropPoints(self, minX, maxX):
        """Crop points to selected X range."""
        
        # apply offset
        minX -= self.properties['xOffset']
        maxX -= self.properties['xOffset']
        
        # get indexes of points in selection
        i1 = mod_signal.locate(self.points, minX)
        i2 = mod_signal.locate(self.points, maxX)
        
        # crop data
        self.pointsCropped = self.points[i1:i2]
        self.labelsCropped = self.labels[i1:i2]
    # ----
    
    
    def scaleAndShift(self, scale, shift):
        """Scale and shift points to screen coordinations."""
        
        self.pointsScaled = self.pointsCropped
        
        xScale = scale[0]
        yScale = scale[1]
        xShift = shift[0]
        yShift = shift[1]
        
        # apply flipping
        if self.properties['flipped']:
            yScale *= -1
        
        # apply normalization
        if self.properties['normalized']:
            yScale /= self.normalization
        
        # apply offset
        xShift += self.properties['xOffset'] * xScale
        yShift += self.properties['yOffset'] * yScale
        
        # recalculate data
        self.pointsScaled = _scaleAndShift(self.pointsCropped, xScale, yScale, xShift, yShift)
        
        self.currentScale = scale
        self.currentShift = shift
    # ----
    
    
    def filterPoints(self, filterSize):
        """Filter points for printing and exporting"""
        pass
    # ----
    
    
    def draw(self, dc, printerScale):
        """Draw object."""
        
        # check data
        if not len(self.pointsScaled):
            return
        
        # draw points
        if self.properties['showPoints']:
            pencolour = [max(x-70,0) for x in self.properties['pointColour']]
            pen = wx.Pen(pencolour, 1*printerScale['drawings'], wx.SOLID)
            brush = wx.Brush(self.properties['pointColour'], wx.SOLID)
            dc.SetPen(pen)
            dc.SetBrush(brush)
            for point in self.pointsScaled:
                dc.DrawCircle(point[0], point[1], self.properties['pointSize']*printerScale['drawings'])
    # ----
    
    
    def drawGel(self, dc, gelCoords, gelHeight, printerScale):
        """Draw gel."""
        pass
    # ----
    
    
    def makeLabels(self, dc, printerScale):
        """Get object labels."""
        
        # check labels
        if not self.properties['showLabels'] or not self.labelsCropped:
            return []
        
        # set font
        dc.SetFont(_scaleFont(self.properties['labelFont'], printerScale['fonts']))
        
        # prepare labels
        labels = []
        format = '%0.'+`self.properties['xPosDigits']`+'f - '
        for x, label in enumerate(self.labelsCropped):
            
            # check max length
            if len(label) > self.properties['labelMaxLength']:
                label = label[:self.properties['labelMaxLength']] + '...'
            
            # add X position
            if self.properties['showXPos']:
                label = (format % self.pointsCropped[x][0]) + label
            
            # get position
            xPos = self.pointsScaled[x][0]
            yPos = self.pointsScaled[x][1]
            
            # get text position
            textSize = dc.GetTextExtent(label)
            if self.properties['labelAngle'] == 90:
                if self.properties['flipped']:
                    textXPos = xPos + textSize[1]*0.5
                    textYPos = yPos + 5*printerScale['drawings']
                    textCoords = (textXPos, textYPos, textXPos-textSize[1], textYPos+textSize[0])
                else:
                    textXPos = xPos - textSize[1]*0.5
                    textYPos = yPos - 5*printerScale['drawings']
                    textCoords = (textXPos, textYPos, textXPos+textSize[1], textYPos-textSize[0])
            
            elif self.properties['labelAngle'] == 0:
                if self.properties['flipped']:
                    textXPos = xPos - textSize[0]*0.5
                    textYPos = yPos + 4*printerScale['drawings']
                    textCoords = (textXPos, textYPos, textXPos+textSize[0], textYPos-textSize[1])
                else:
                    textXPos = xPos - textSize[0]*0.5
                    textYPos = yPos - textSize[1] - 4*printerScale['drawings']
                    textCoords = (textXPos, textYPos, textXPos+textSize[0], textYPos-textSize[1])
            
            # add label and sort by intensity
            labels.append((self.pointsCropped[x][1], label, textCoords, self.properties))
            
        return labels
    # ----
    
    
    def _normalization(self):
        """Calculate normalization constants."""
        
        self.normalization = 1.0
        
        # check data
        if not len(self.points):
            return
        
        # get range
        minXY, maxXY = self.pointsBox
        
        # set normalization
        self.normalization = maxXY[1] / 100.
    # ----
    


class points:
    """Base class for polypoints and polylines drawing."""
    
    def __init__(self, points, **attr):
        
        # set default params
        self.properties = {
                            'legend': '',
                            'visible': True,
                            'flipped': False,
                            'xOffset': 0,
                            'yOffset': 0,
                            'normalized': False,
                            'showInGel': False,
                            'exactFit': False,
                            'showPoints': True,
                            'pointColour': (0, 0, 255),
                            'pointSize': 3,
                            'showLines': True,
                            'lineColour': (0, 0, 255),
                            'lineWidth': 1,
                            'lineStyle': wx.SOLID,
                            'xOffsetDigits': 2,
                            'yOffsetDigits': 0,
                            }
        
        
        self.currentScale = (1., 1.)
        self.currentShift = (0., 0.)
        self.normalization = 1.0
        
        # get new attributes
        for name, value in attr.items():
            self.properties[name] = value
        
        # convert points to array
        self.points = numpy.array(points)
        self.cropped = self.points
        self.scaled = self.cropped
        if len(self.points):
            self.pointsBox = (numpy.minimum.reduce(self.points), numpy.maximum.reduce(self.points))
        
        # calculate normalization
        self._normalization()
    # ----
    
    
    def setProperties(self, **attr):
        """Set object properties."""
        
        for name, value in attr.items():
            self.properties[name] = value
    # ----
    
    
    def setNormalization(self, value):
        """Force specified normalization to be used insted of calculated one."""
        self.normalization = value
    # ----
    
    
    def getBoundingBox(self, minX=None, maxX=None, absolute=False):
        """Get bounding box for whole data or X selection"""
        
        # use relevant data
        if minX != None and maxX != None:
            self.cropPoints(minX, maxX)
            data = self.cropped
        else:
            data = self.points
        
        # check data
        if not len(data):
            return False
        
        # get range
        if minX != None and maxX != None:
            minXY = numpy.minimum.reduce(data)
            maxXY = numpy.maximum.reduce(data)
        else:
            minXY = [self.pointsBox[0][0], self.pointsBox[0][1]]
            maxXY = [self.pointsBox[1][0], self.pointsBox[1][1]]
        
        # extend values slightly to fit data
        if not absolute and not self.properties['exactFit']:
            xExtend = (maxXY[0] - minXY[0]) * 0.05
            yExtend = (maxXY[1] - minXY[1]) * 0.05
            minXY[0] -= xExtend
            maxXY[0] += xExtend
            minXY[1] -= yExtend
            maxXY[1] += yExtend
        
        # apply normalization
        if self.properties['normalized']:
            minXY[1] = minXY[1] / self.normalization
            maxXY[1] = maxXY[1] / self.normalization
        
        # apply offset
        minXY[0] += self.properties['xOffset']
        minXY[1] += self.properties['yOffset']
        maxXY[0] += self.properties['xOffset']
        maxXY[1] += self.properties['yOffset']
        
        # apply flipping
        if self.properties['flipped']:
            minY = -1 * maxXY[1]
            maxY = -1 * minXY[1]
            minXY[1] = minY
            maxXY[1] = maxY
        
        return [minXY, maxXY]
    # ----
    
    
    def getLegend(self):
        """Get legend."""
        
        # get legend
        legend = self.properties['legend']
        offset = ''
        
        # add current offset
        if not self.properties['normalized']:
            if self.properties['xOffset']:
                format = ' X%0.'+`self.properties['xOffsetDigits']`+'f'
                offset += format % self.properties['xOffset']
            if self.properties['yOffset']:
                format = ' Y%0.'+`self.properties['yOffsetDigits']`+'f'
                offset += format % self.properties['yOffset']
            if legend and offset:
                legend += ' (Offset%s)' % offset
        
        # set colour
        if self.properties['showPoints']:
            return (legend, self.properties['pointColour'])
        else:
            return (legend, self.properties['lineColour'])
    # ----
    
    
    def cropPoints(self, minX, maxX):
        """Crop points to selected X range."""
        
        # apply offset
        minX -= self.properties['xOffset']
        maxX -= self.properties['xOffset']
        
        # crop line
        if self.properties['showLines']:
            self.cropped = mod_signal.crop(self.points, minX, maxX)
        
        # crop points
        else:
            i1 = mod_signal.locate(self.points, minX)
            i2 = mod_signal.locate(self.points, maxX)
            self.cropped = self.points[i1:i2]
    # ----
    
    
    def scaleAndShift(self, scale, shift):
        """Scale and shift points to screen coordinations."""
        
        self.scaled = self.cropped
        
        xScale = scale[0]
        yScale = scale[1]
        xShift = shift[0]
        yShift = shift[1]
        
        # apply flipping
        if self.properties['flipped']:
            yScale *= -1
        
        # apply normalization
        if self.properties['normalized']:
            yScale /= self.normalization
        
        # apply offset
        xShift += self.properties['xOffset'] * xScale
        yShift += self.properties['yOffset'] * yScale
        
        # recalculate data
        if len(self.cropped):
            self.scaled = _scaleAndShift(self.cropped, xScale, yScale, xShift, yShift)
        
        self.currentScale = scale
        self.currentShift = shift
    # ----
    
    
    def filterPoints(self, filterSize):
        """Filter points for printing and exporting"""
        
        # filter data
        if len(self.scaled) and self.properties['showLines']:
            self.scaled = _filterPoints(self.scaled, filterSize)
    # ----
    
    
    def draw(self, dc, printerScale):
        """Draw object."""
        
        # check data
        if not len(self.scaled):
            return
        
        # draw lines
        if self.properties['showLines'] and len(self.scaled) > 1:
            pen = wx.Pen(self.properties['lineColour'], self.properties['lineWidth']*printerScale['drawings'], self.properties['lineStyle'])
            brush = wx.Brush(self.properties['lineColour'], wx.SOLID)
            dc.SetPen(pen)
            dc.SetBrush(brush)
            dc.DrawLines(self.scaled)
        
        # draw points
        if self.properties['showPoints']:
            pencolour = [max(x-70,0) for x in self.properties['pointColour']]
            pen = wx.Pen(pencolour, self.properties['lineWidth']*printerScale['drawings'], wx.SOLID)
            brush = wx.Brush(self.properties['pointColour'], wx.SOLID)
            dc.SetPen(pen)
            dc.SetBrush(brush)
            for point in self.scaled:
                dc.DrawCircle(point[0], point[1], self.properties['pointSize']*printerScale['drawings'])
    # ----
    
    
    def drawGel(self, dc, gelCoords, gelHeight, printerScale):
        """Draw gel."""
        pass
    # ----
    
    
    def makeLabels(self, dc, printerScale):
        """Get object labels."""
        return []
    # ----
    
    
    def _normalization(self):
        """Calculate normalization constants."""
        
        self.normalization = 1.0
        
        # check data
        if not len(self.points):
            return
        
        # get range
        minXY, maxXY = self.pointsBox
        
        # set normalization
        self.normalization = maxXY[1] / 100.
    # ----
    


class spectrum:
    """Base class for spectrum drawing."""
    
    def __init__(self, scan, **attr):
        
        # set default params
        self.properties = {
                            'legend': '',
                            'visible': True,
                            'flipped': False,
                            'xOffset': 0,
                            'yOffset': 0,
                            'normalized': False,
                            'showInGel': True,
                            'showSpectrum': True,
                            'showPoints': True,
                            'showLabels': True,
                            'showIsotopicLabels': True,
                            'showTicks': True,
                            'showGelLegend': True,
                            'spectrumColour': (0, 0, 255),
                            'spectrumWidth': 1,
                            'spectrumStyle': wx.SOLID,
                            'labelAngle': 90,
                            'labelDigits': 2,
                            'labelCharge': False,
                            'labelGroup': False,
                            'labelBgr': True,
                            'labelColour': (0, 0, 0),
                            'labelBgrColour': (255, 255, 255),
                            'labelFont': wx.Font(10, wx.SWISS, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0),
                            'tickColour': (200, 200, 200),
                            'isotopeColour': None,
                            'msmsColour': None,
                            'tickWidth': 1,
                            'tickStyle': wx.SOLID,
                            'xOffsetDigits': 2,
                            'yOffsetDigits': 0,
                            }
        
        self.currentScale = (1., 1.)
        self.currentShift = (0., 0.)
        self.normalization = 1.0
        
        # get new attributes
        for name, value in attr.items():
            self.properties[name] = value
        
        # convert spectrum points to array
        self.spectrumPoints = numpy.array(scan.profile)
        self.spectrumCropped = self.spectrumPoints
        self.spectrumScaled = self.spectrumCropped
        if len(self.spectrumPoints):
            self.spectrumBox = (numpy.minimum.reduce(self.spectrumPoints), numpy.maximum.reduce(self.spectrumPoints))
        
        # convert peaklist points to array
        self.peaklist = copy.deepcopy(scan.peaklist)
        self.peaklistPoints = numpy.array([[peak.mz, peak.ai, peak.base] for peak in scan.peaklist])
        self.peaklistCropped = self.peaklistPoints
        self.peaklistScaled = self.peaklistCropped
        self.peaklistCroppedPeaks = self.peaklist[:]
        if len(self.peaklistPoints):
            self.peaklistBox = (numpy.minimum.reduce(self.peaklistPoints), numpy.maximum.reduce(self.peaklistPoints))
        
        # calculate normalization
        self._normalization()
    # ----
    
    
    def setProperties(self, **attr):
        """Set object properties."""
        
        for name, value in attr.items():
            self.properties[name] = value
    # ----
    
    
    def setNormalization(self, value):
        """Force specified normalization to be used insted of calculated one."""
        self.normalization = value
    # ----
    
    
    def getBoundingBox(self, minX=None, maxX=None, absolute=False):
        """Get bounding box for whole data or X selection."""
        
        spectrumBox = None
        peaklistBox = None
        
        # use relevant data
        if minX != None and maxX != None:
            self.cropPoints(minX, maxX)
            spectrumData = self.spectrumCropped
            peaklistData = self.peaklistCropped
        else:
            spectrumData = self.spectrumPoints
            peaklistData = self.peaklistPoints
        
        # calculate bounding box for spectrum
        if len(spectrumData) and self.properties['showSpectrum']:
            if minX != None and maxX != None:
                minXY = numpy.minimum.reduce(spectrumData)
                maxXY = numpy.maximum.reduce(spectrumData)
            else:
                minXY = [self.spectrumBox[0][0], self.spectrumBox[0][1]]
                maxXY = [self.spectrumBox[1][0], self.spectrumBox[1][1]]
            
            if not absolute:
                maxXY[1] += (maxXY[1] - minXY[1]) * 0.05
            
            spectrumBox = [minXY, maxXY]
        
        # calculate bounding box for peaklist
        if len(peaklistData) and (self.properties['showSpectrum'] or self.properties['showLabels'] or self.properties['showTicks']):
            if minX != None and maxX != None:
                minXY = numpy.minimum.reduce(peaklistData)
                maxXY = numpy.maximum.reduce(peaklistData)
            else:
                minXY = [self.peaklistBox[0][0], self.peaklistBox[0][1], self.peaklistBox[0][2]]
                maxXY = [self.peaklistBox[1][0], self.peaklistBox[1][1], self.peaklistBox[1][2]]
            
            minXY = [minXY[0], min(minXY[1:])]
            maxXY = [maxXY[0], max(maxXY[1:])]
            
            # extend values to fit labels
            if not absolute:
                xExtend = (maxXY[0] - minXY[0]) * 0.02
                minXY[0] -= xExtend
                maxXY[0] += xExtend
                
                if self.properties['showLabels'] and self.properties['labelAngle']==0:
                    maxXY[1] += (maxXY[1] - minXY[1]) * 0.2
                elif self.properties['showLabels'] and self.properties['labelAngle']==90:
                    maxXY[1] += (maxXY[1] - minXY[1]) * 0.4
                else:
                    maxXY[1] += (maxXY[1] - minXY[1]) * 0.05
            
            peaklistBox = [minXY, maxXY]
        
        # use both
        if spectrumBox and peaklistBox:
            minXY, maxXY = [numpy.minimum(spectrumBox[0], peaklistBox[0]), numpy.maximum(spectrumBox[1], peaklistBox[1])]
        elif spectrumBox:
            minXY, maxXY = spectrumBox
        elif peaklistBox:
            minXY, maxXY = peaklistBox
        else:
            return False
        
        # apply normalization
        if self.properties['normalized']:
            minXY[1] = minXY[1] / self.normalization
            maxXY[1] = maxXY[1] / self.normalization
        
        # apply offset
        if not self.properties['normalized']:
            minXY[0] += self.properties['xOffset']
            minXY[1] += self.properties['yOffset']
            maxXY[0] += self.properties['xOffset']
            maxXY[1] += self.properties['yOffset']
        
        # apply flipping
        if self.properties['flipped']:
            minY = -1 * maxXY[1]
            maxY = -1 * minXY[1]
            minXY[1] = minY
            maxXY[1] = maxY
        
        return [minXY, maxXY]
    # ----
    
    
    def getLegend(self):
        """Get legend."""
        
        # get legend
        legend = self.properties['legend']
        offset = ''
        
        # add current offset
        if not self.properties['normalized']:
            if self.properties['xOffset']:
                format = ' X%0.'+`self.properties['xOffsetDigits']`+'f'
                offset += format % self.properties['xOffset']
            if self.properties['yOffset']:
                format = ' Y%0.'+`self.properties['yOffsetDigits']`+'f'
                offset += format % self.properties['yOffset']
            if legend and offset:
                legend += ' (Offset%s)' % offset
        
        # set colour
        if len(self.spectrumPoints) and self.properties['showSpectrum']:
            return (legend, self.properties['spectrumColour'])
        else:
            return (legend, self.properties['tickColour'])
    # ----
    
    
    def getPoint(self, xPos, coord='screen'):
        """Get interpolated Y position for given X."""
        
        # get relevant data
        if coord == 'user':
            points = self.spectrumCropped
        else:
            points = self.spectrumScaled
        
        # check data
        if not len(points):
            return None
        
        # get xPos index
        index = mod_signal.locate(points, xPos)
        if index == 0 or index == len(points):
            return None
        
        # get yPos
        yPos = mod_signal.interpolate(points[index-1], points[index], x=xPos)
        
        return [xPos, yPos]
    # ----
    
    
    def cropPoints(self, minX, maxX):
        """Crop points to selected X range."""
        
        # apply offset
        minX -= self.properties['xOffset']
        maxX -= self.properties['xOffset']
        
        # crop spectrum data
        if self.properties['showSpectrum']:
            self.spectrumCropped = mod_signal.crop(self.spectrumPoints, minX, maxX)
        
        # crop peaklist data
        if self.properties['showSpectrum'] or self.properties['showLabels'] or self.properties['showTicks']:
            i1 = mod_signal.locate(self.peaklistPoints, minX)
            i2 = mod_signal.locate(self.peaklistPoints, maxX)
            self.peaklistCropped = self.peaklistPoints[i1:i2]
            self.peaklistCroppedPeaks = self.peaklist[i1:i2]
    # ----
    
    
    def scaleAndShift(self, scale, shift):
        """Scale and shift points to screen coordinations."""
        
        self.spectrumScaled = self.spectrumCropped
        self.peaklistScaled = self.peaklistCropped
        
        xScale = scale[0]
        yScale = scale[1]
        xShift = shift[0]
        yShift = shift[1]
        
        # apply flipping
        if self.properties['flipped']:
            yScale *= -1
        
        # apply normalization
        if self.properties['normalized']:
            yScale /= self.normalization
        
        # apply offset
        if not self.properties['normalized']:
            xShift += self.properties['xOffset'] * xScale
            yShift += self.properties['yOffset'] * yScale
        
        # scale and shift spectrum data
        if len(self.spectrumCropped):
            self.spectrumScaled = _scaleAndShift(self.spectrumCropped, xScale, yScale, xShift, yShift)
        
        # scale and shift peaklist data
        if len(self.peaklistCropped):
            self.peaklistScaled = numpy.array((xScale, yScale, yScale)) * self.peaklistCropped + numpy.array((xShift, yShift, yShift))
        
        self.currentScale = scale
        self.currentShift = shift
    # ----
    
    
    def filterPoints(self, filterSize):
        """Filter spectrum points invisible in current resolution."""
        
        # filter spectrum data
        if len(self.spectrumScaled) and self.properties['showSpectrum']:
            self.spectrumScaled = _filterPoints(self.spectrumScaled, filterSize)
    # ----
    
    
    def draw(self, dc, printerScale):
        """Draw object."""
        
        # draw line spectrum
        if len(self.spectrumScaled) > 2 and self.properties['showSpectrum']:
            self._drawSpectrum(dc, printerScale)
        
        # draw peaklist ticks
        if len(self.peaklistScaled) and (self.properties['showTicks'] or not len(self.spectrumPoints)):
            self._drawPeaklist(dc, printerScale)
    # ----
    
    
    def drawGel(self, dc, gelCoords, gelHeight, printerScale):
        """Draw gel."""
        
        # draw line spectrum gel
        if len(self.spectrumScaled) > 2 and self.properties['showSpectrum']:
            self._drawSpectrumGel(dc, gelCoords, gelHeight, printerScale)
        
        # draw peaklist gel
        elif len(self.peaklistScaled) and (self.properties['showSpectrum'] or self.properties['showLabels'] or self.properties['showTicks']):
            self._drawPeaklistGel(dc, gelCoords, gelHeight, printerScale)
        
        # draw gel legend
        self._drawGelLegend(dc, gelCoords, gelHeight, printerScale)
    # ----
    
    
    def makeLabels(self, dc, printerScale):
        """Get object labels."""
        
        # check labels
        if not self.properties['showLabels'] or not len(self.peaklistScaled):
            return []
        
        # set font
        dc.SetFont(_scaleFont(self.properties['labelFont'], printerScale['fonts']))
        
        # prepare labels
        labels = []
        format = '%0.'+`self.properties['labelDigits']`+'f'
        for x, peak in enumerate(self.peaklistScaled):
            
            # skip isotopes
            if not self.properties['showIsotopicLabels'] and self.peaklistCroppedPeaks[x].isotope != 0:
                continue
            
            # get position
            xPos = peak[0]
            yPos = peak[1]
            
            # get label
            label = format % self.peaklistCroppedPeaks[x].mz
            
            # add charge to label
            if self.properties['labelCharge'] and self.peaklistCroppedPeaks[x].charge != None:
                label += ' (%d)' % self.peaklistCroppedPeaks[x].charge
            
            # add group to label
            if self.properties['labelGroup'] and self.peaklistCroppedPeaks[x].group:
                label += ' [%s]' % self.peaklistCroppedPeaks[x].group
            
            # get text position
            textSize = dc.GetTextExtent(label)
            if self.properties['labelAngle'] == 90:
                if self.properties['flipped']:
                    textXPos = xPos + textSize[1]*0.5
                    textYPos = yPos + 5*printerScale['drawings']
                    textCoords = (textXPos, textYPos, textXPos-textSize[1], textYPos+textSize[0])
                else:
                    textXPos = xPos - textSize[1]*0.5
                    textYPos = yPos - 5*printerScale['drawings']
                    textCoords = (textXPos, textYPos, textXPos+textSize[1], textYPos-textSize[0])
            
            elif self.properties['labelAngle'] == 0:
                if self.properties['flipped']:
                    textXPos = xPos - textSize[0]*0.5
                    textYPos = yPos + 4*printerScale['drawings']
                    textCoords = (textXPos, textYPos, textXPos+textSize[0], textYPos-textSize[1])
                else:
                    textXPos = xPos - textSize[0]*0.5
                    textYPos = yPos - textSize[1] - 4*printerScale['drawings']
                    textCoords = (textXPos, textYPos, textXPos+textSize[0], textYPos-textSize[1])
            
            # add label and sort by intensity
            labels.append((self.peaklistCroppedPeaks[x].ai, label, textCoords, self.properties))
            
        return labels
    # ----
    
    
    def _drawSpectrum(self, dc, printerScale):
        """Draw spectrum lines."""
        
        # set pen and brush
        pen = wx.Pen(self.properties['spectrumColour'], self.properties['spectrumWidth']*printerScale['drawings'], self.properties['spectrumStyle'])
        brush = wx.Brush(self.properties['spectrumColour'], wx.SOLID)
        dc.SetPen(pen)
        dc.SetBrush(brush)
        
        # draw lines
        dc.DrawLines(self.spectrumScaled)
        
        # draw points if it makes sense
        count = len(self.spectrumScaled)
        if self.properties['showPoints'] \
            and count > 2 \
            and (self.spectrumScaled[2][0] - self.spectrumScaled[1][0]) > (6*printerScale['drawings']) \
            and ((self.spectrumScaled[-1][0] - self.spectrumScaled[0][0]) / count) > (6*printerScale['drawings']):
            
            for point in self.spectrumScaled:
                try: dc.DrawCircle(point[0], point[1], 2*printerScale['drawings'])
                except OverflowError: pass
    # ----
    
    
    def _drawSpectrumGel(self, dc, gelCoords, gelHeight, printerScale):
        """Draw spectrum gel."""
        
        # get plot coordinates
        gelY1, plotX1, plotY1, plotX2, plotY2, zeroY = gelCoords
        
        # correct zero
        if self.properties['flipped'] and (plotY1 < zeroY < plotY2):
            plotY1 = zeroY
            shift = zeroY
        elif (plotY1 < zeroY < plotY2):
            plotY2 = zeroY
            shift = plotY1
        else:
            shift = plotY1
        
        # set color step
        step = (plotY2 - plotY1) / 255
        if step == 0:
            return False
        
        # init brush
        dc.SetPen(wx.TRANSPARENT_PEN)
        brush = wx.Brush((255,255,255), wx.SOLID)
        dc.SetBrush(brush)
        
        # get first point and color
        lastX = round(self.spectrumScaled[0][0])
        lastY = 255
        previousX = lastX
        previousY = lastY
        maxY = 255
        
        # draw gel
        for point in self.spectrumScaled:
            
            # get point
            xPos = round(point[0])
            intens = round((point[1] - shift)/step)
            intens = min(intens, 255)
            intens = max(intens, 0)
            
            # reverse color for flipped spectra
            if self.properties['flipped']:
                intens = 255 - intens
            
            # filter points
            if xPos-lastX >= printerScale['drawings']:
                
                # set color if different
                if lastY != maxY:
                    brush.SetColour((maxY, maxY, maxY))
                    dc.SetBrush(brush)
                    
                # draw point rectangle
                try: dc.DrawRectangle(lastX, gelY1, xPos-lastX, gelHeight)
                except: pass
                
                # empty space
                if maxY < previousY and xPos-previousX > printerScale['drawings']:
                    maxY = previousY
                    brush.SetColour((maxY, maxY, maxY))
                    dc.SetBrush(brush)
                    try: dc.DrawRectangle(lastX+printerScale['drawings'], gelY1, xPos-(lastX+printerScale['drawings']), gelHeight)
                    except: pass
                
                # save last
                lastX = xPos
                lastY = maxY
                maxY = intens
            
            # remember previous
            previousX = xPos
            previousY = intens
                
            # get highest intensity
            maxY = min(intens, maxY)
    # ----
    
    
    def _drawPeaklist(self, dc, printerScale):
        """Draw peaklist ticks."""
        
        # set pen params
        peakPen = wx.Pen(self.properties['tickColour'], self.properties['tickWidth']*printerScale['drawings'], self.properties['tickStyle'])
        isotopePen = wx.Pen(self.properties['tickColour'], self.properties['tickWidth']*printerScale['drawings'], self.properties['tickStyle'])
        peakBrush = wx.Brush(self.properties['tickColour'], wx.SOLID)
        msmsBrush = wx.Brush(self.properties['tickColour'], wx.SOLID)
        
        if self.properties['isotopeColour']:
            isotopePen.SetColour(self.properties['isotopeColour'])
        if self.properties['msmsColour']:
            msmsBrush.SetColour(self.properties['msmsColour'])
        
        # draw isotopes
        dc.SetPen(isotopePen)
        for x, peak in enumerate(self.peaklistScaled):
            if self.peaklistCroppedPeaks[x].isotope != 0:
                try:
                    dc.DrawLine(peak[0], peak[2], peak[0], peak[1])
                    dc.DrawLine(peak[0]-3*printerScale['drawings'], peak[2], peak[0]+3*printerScale['drawings'], peak[2])
                except OverflowError:
                    pass
        
        # draw peaks
        dc.SetPen(peakPen)
        dc.SetBrush(peakBrush)
        for x, peak in enumerate(self.peaklistScaled):
            if self.peaklistCroppedPeaks[x].isotope == 0:
                try:
                    dc.DrawLine(peak[0], peak[2], peak[0], peak[1])
                    dc.DrawLine(peak[0]-3*printerScale['drawings'], peak[2], peak[0]+3*printerScale['drawings'], peak[2])
                    dc.DrawRectangle(peak[0]-1*printerScale['drawings'], peak[1]-1*printerScale['drawings'], 3*printerScale['drawings'], 3*printerScale['drawings'])
                except OverflowError:
                    pass
        
        # draw fragmentation mark
        dc.SetPen(wx.TRANSPARENT_PEN)
        dc.SetBrush(msmsBrush)
        for x, peak in enumerate(self.peaklistScaled):
            if self.peaklistCroppedPeaks[x].childScanNumber != None:
                try: dc.DrawCircle(peak[0], peak[1], 3*printerScale['drawings'])
                except OverflowError: pass
    # ----
    
    
    def _drawPeaklistGel(self, dc, gelCoords, gelHeight, printerScale):
        """Draw peaklist gel."""
        
        # get plot coordinates
        gelY1, plotX1, plotY1, plotX2, plotY2, zeroY = gelCoords
        
        # correct zero
        if self.properties['flipped'] and (plotY1 < zeroY < plotY2):
            plotY1 = zeroY
            shift = zeroY
        elif (plotY1 < zeroY < plotY2):
            plotY2 = zeroY
            shift = plotY1
        else:
            shift = plotY1
        
        # set color step
        step = (plotY2 - plotY1) / 255
        if step == 0:
            return False
        
        # init brush
        dc.SetPen(wx.TRANSPARENT_PEN)
        brush = wx.Brush((255,255,255), wx.SOLID)
        dc.SetBrush(brush)
        
        # get first point and color
        lastX = round(self.peaklistScaled[0][0])
        lastY = 255
        maxY = 255
        
        # draw rectangles
        last = len(self.peaklistScaled)-1
        for x, point in enumerate(self.peaklistScaled):
            
            # get intensity colour
            xPos = round(point[0])
            intens = round((point[1] - shift)/step)
            intens = min(intens, 255)
            intens = max(intens, 0)
            
            # reverse color for flipped spectra
            if self.properties['flipped']:
                intens = 255 - intens
            
            # draw first
            if x==0:
                brush.SetColour((intens, intens, intens))
                dc.SetBrush(brush)
                try: dc.DrawRectangle(xPos, gelY1, printerScale['drawings'], gelHeight)
                except: pass
                lastY = maxY
                maxY = intens
            
            # filter points
            if xPos-lastX >= printerScale['drawings']:
                
                # set color if different
                if lastY != maxY:
                    brush.SetColour((maxY, maxY, maxY))
                    dc.SetBrush(brush)
                    
                # draw peak line
                try: dc.DrawRectangle(lastX, gelY1, printerScale['drawings'], gelHeight)
                except: pass
                
                # save last
                lastX = xPos
                lastY = maxY
                maxY = intens
                
                # draw last
                if x==last:
                    brush.SetColour((maxY, maxY, maxY))
                    dc.SetBrush(brush)
                    try: dc.DrawRectangle(xPos, gelY1, printerScale['drawings'], gelHeight)
                    except: pass
                
                continue
                
            # get highest intensity
            maxY = min(intens, maxY)
    # ----
    
    
    def _drawGelLegend(self, dc, gelCoords, gelHeight, printerScale):
        """docstring for _drawGelLegend"""
        
        # get plot coordinates
        gelY1, plotX1, plotY1, plotX2, plotY2, zeroY = gelCoords
        
        # get colour
        if len(self.spectrumPoints) and self.properties['showSpectrum']:
            colour = self.properties['spectrumColour']
        else:
            colour = self.properties['tickColour']
        
        # set dc
        pencolour = [max(i-70,0) for i in colour]
        pen = wx.Pen(pencolour, 1*printerScale['drawings'], wx.SOLID)
        dc.SetPen(pen)
        dc.SetTextForeground(colour)
        dc.SetBrush(wx.Brush(colour, wx.SOLID))
        
        # draw legend circle
        x = plotX2 - 9 * printerScale['drawings']
        y = gelY1 + (gelHeight)/2
        dc.DrawCircle(x, y, 3*printerScale['drawings'])
        
        # draw legend text
        if self.properties['showGelLegend'] and self.properties['legend']:
            textSize = dc.GetTextExtent(self.properties['legend'])
            x = plotX2 - textSize[0] - 17*printerScale['drawings']
            y = gelY1 + gelHeight/2 - textSize[1]/2
            dc.DrawText(self.properties['legend'], x, y)
    # ----
    
    
    def _normalization(self):
        """Calculate normalization constants."""
        
        # get range from points and peaklist
        if len(self.spectrumPoints) and len(self.peaklistPoints):
            spectrumMinXY, spectrumMaxXY = self.spectrumBox
            peaklistMinXY, peaklistMaxXY = self.peaklistBox
            self.normalization = max(spectrumMaxXY[1], peaklistMaxXY[1]) / 100.
        
        # get range from points only
        elif len(self.spectrumPoints):
            minXY, maxXY = self.spectrumBox
            self.normalization = maxXY[1] / 100.
        
        # get range from peaklist only
        elif len(self.peaklistPoints):
            minXY, maxXY = self.peaklistBox
            self.normalization = maxXY[1] / 100.
    # ----
    
    


# HELPERS
# -------

def _scaleFont(font, scale):
    """Scale font."""
    
    # check printerScale
    if scale == 1:
        return font
    
    # get font
    pointSize = font.GetPointSize()
    family = font.GetFamily()
    style = font.GetStyle()
    weight = font.GetWeight()
    underline = font.GetUnderlined()
    faceName = font.GetFaceName()
    encoding = font.GetDefaultEncoding()
    
    # scale pointSize
    pointSize = pointSize * scale * 1.3
    
    # make print font
    printerFont = wx.Font(pointSize, family, style, weight, underline, faceName, encoding)
    
    return printerFont
# ----


def _scaleAndShift(points, scaleX, scaleY, shiftX, shiftY):
    """Scale and shift signal points used by plot. New array is returned.
        points (numpy array) - data points
        scaleX (float) - x-axis scale
        scaleY (float) - y-axis scale
        shiftX (float) - x-axis shift
        shiftY (float) - y-axis shift
    """
    
    # check signal type
    if not isinstance(points, numpy.ndarray):
        raise TypeError, "Signal points must be NumPy array!"
    if points.dtype.name != 'float64':
        raise TypeError, "Signal points must be float64!"
    
    # check signal data
    if len(points) == 0:
        return numpy.array([])
    
    # scale and shift signal
    return calculations.signal_rescale(points, float(scaleX), float(scaleY), float(shiftX), float(shiftY))
# ----


def _filterPoints(points, resolution):
    """Filter signal points according to resolution. New array is returned.
        points (numpy array) - data points
        resolution (float) - resolution point size
    """
    
    # check signal type
    if not isinstance(points, numpy.ndarray):
        raise TypeError, "Signal points must be NumPy array!"
    if points.dtype.name != 'float64':
        raise TypeError, "Signal points must be float64!"
    
    # check signal data
    if len(points) == 0:
        return numpy.array([])
    
    # filter signal
    return calculations.signal_filter(points, float(resolution))
# ----