-
Notifications
You must be signed in to change notification settings - Fork 8
/
PositionList.py
1560 lines (1290 loc) · 65.2 KB
/
PositionList.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
#===============================================================================
#
# License: GPL
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License 2
# as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
#===============================================================================
from Settings import MosaicSettings, CameraSettings, SmartSEMSettings,MosaicSettingsSchema, CameraSettingsSchema
import numpy as np
from numpy import sin, pi, cos, arctan, sin, tan, sqrt
import csv
from Point import Point
import matplotlib.patches
import matplotlib.transforms
from matplotlib import path
from matplotlib.lines import Line2D
from matplotlib.quiver import Quiver
#from matplotlib.nxutils import points_inside_poly
from CenterRectangle import CenterRectangle
import os
from scipy.interpolate import griddata
import lxml.etree as ET
import json
import marshmallow as mm
class NumberDisplaySettingsSchema(mm.Schema):
shownumbers = mm.fields.Bool(required=True)
color = mm.fields.Str(required=True)
horizontalAlignment = mm.fields.Str(required=True)
verticalAlignment = mm.fields.Str(required=True)
class NumberDisplaySettings(object):
def __init__(self,shownumbers=False,color='darkorange',horizontalAlignment='right',verticalAlignment='top'):
self.shownumbers = shownumbers
self.color=color
self.horizontalAlignment = horizontalAlignment
self.verticalAlignment = verticalAlignment
class slicePositionSchema(mm.Schema):
x = mm.fields.Float(required=True)
y = mm.fields.Float(required=True)
angle = mm.fields.Float(required=True)
showAngle = mm.fields.Bool(required=False,default=True)
selected = mm.fields.Bool(required=False,default=False)
activated = mm.fields.Bool(required=False,default=True)
withpoint = mm.fields.Bool(required=False,default=True)
number = mm.fields.Int(required=True)
numberDisplaySettings = mm.fields.Nested(NumberDisplaySettingsSchema)
frameList = mm.fields.Nested('posListSchema')
class posListSchema(mm.Schema):
mosaic_settings = mm.fields.Nested(MosaicSettingsSchema,required=True)
camera_settings = mm.fields.Nested(CameraSettingsSchema,required=True)
slicePositions = mm.fields.Nested(slicePositionSchema,many=True)
dosort = mm.fields.Bool(required=False,default=True)
numberDisplaySettings = mm.fields.Nested(NumberDisplaySettingsSchema)
class posList():
"""class for holding, altering, and plotting the position list"""
def __init__(self,axis,mosaic_settings=MosaicSettings(),camera_settings=CameraSettings(),
numberDisplaySettings=NumberDisplaySettings(),dosort=True):
"""initialization function
keywords)
axis:matplotlib axis to plot the position list in
mosaic_settings:MosaicSettings for initialization purposes, defaults to default for class
camera_settings:CameraSettins for initialization purposes, defaults to default for class
"""
self.mosaic_settings=mosaic_settings
self.camera_settings=camera_settings
self.slicePositions=[]
self.axis=axis
#start with point1 and 2 not defined
self.pos1=None
self.pos2=None
self.dosort=dosort
self.numberDisplaySettings=numberDisplaySettings
def get_next_pos(self,pos):
self.__sort_points()
myindex=self.slicePositions.index(pos)
if (myindex)==len(self.slicePositions)-1:
return None
return self.slicePositions[myindex+1]
def get_prev_pos(self,pos):
#self.__sort_points()
myindex=self.slicePositions.index(pos)
if (myindex)==0:
return None
return self.slicePositions[myindex-1]
def set_pos1_near(self,x,y):
"""sets point1 to be the position nearest an x,y point
keywords)
x:x position in microns to select nearest
y:y position in microns to select nearest
"""
#slicePosition nearest x,y
near_pos=self.get_position_nearest(x, y)
self.set_pos1(near_pos)
def set_pos2_near(self,x,y):
"""sets point2 to be the position nearest an x,y point
keywords)
x:x position in microns to select nearest
y:y position in microns to select nearest
"""
#slicePosition nearest x,y
near_pos=self.get_position_nearest(x, y)
self.set_pos2(near_pos)
def set_pos1(self,newpos):
"""makes a position be position 1 if possible"""
#if the position has a label already do nothing
if newpos.label == None:
#if pos1 is defined, remove it
if self.pos1 != None:
self.pos1.removeLabel()
newpos.addLabel(" 1")
self.pos1=newpos
def set_pos2(self,newpos):
"""makes a position be position 2 if possible"""
#if the position has a label already do nothing
if newpos.label == None:
if self.pos2 != None:
self.pos2.removeLabel()
newpos.addLabel(" 2")
self.pos2=newpos
def new_position_after_step(self):
"""add a new position to the list, by calculate the vector between pos1 and pos2, and adding that vector to pos2
if pos1 and pos2 are not defined, return None, otherwise return the newly added slicePosition
also redefines pos1 to be pos2 and pos2 to be the new point"""
if (self.pos1 == None or self.pos2==None):
return None
else:
dx=self.pos2.x-self.pos1.x
dy=self.pos2.y-self.pos1.y
#add the new position using the add_position function
newpos=self.add_position(self.pos2.x+dx,self.pos2.y+dy)
#redefine pos1 and pos2 such that the new point is pos2 and the old pos2 is pos1
oldpos2=self.pos2
self.set_pos2(newpos)
self.set_pos1(oldpos2)
return newpos
def set_select_all(self,selected):
"""set the selected attribute in all the slicePositions to be equal to selected
and updates the appropriate drawn attributes accordingly via set_selected
keywords:
selected)boolean as to whether the selected should be selected or unselected
"""
for pos in self.slicePositions:
pos.set_selected(selected)
def set_mosaic_settings(self,mosaic_settings):
"""sets the mosaic settings, and updates all the necessary properties of the slice positions using their update_mosaic_settings() function
keywords:
mosaic_settings)the MosaicSettings class to make be the current mosaic settings"""
self.mosaic_settings=mosaic_settings
for pos in self.slicePositions:
pos.update_mosaic_settings()
def set_camera_settings(self,camera_settings):
"""sets the camera_settings attribute, and updates all the necessary properties of the slice positions using their update_mosaic_settings() function
keywords:
camera_settings)the CameraSettings class to make be the current camera_settings"""
self.camera_settings=camera_settings
for pos in self.slicePositions:
pos.update_mosaic_settings()
def set_mosaic_visible(self,visible):
"""sets visibility of the mosaic boxes on each of the slicePositions to be equal to visible
keywords:
visible)Boolean describing whether the rectangular boxes should be visible or not
"""
self.mosaic_settings.show_box=visible
for pos in self.slicePositions:
pos.set_box_visible(visible)
def set_frames_visible(self,visible):
"""sets visibility of the frames boxes on each of the slicePositions to be equal to visible
keywords:
visible)Boolean describing whether the frame boxes should be visible or not
"""
self.mosaic_settings.show_frames=visible
for pos in self.slicePositions:
#if no frames exist, and we are trying to make them visible, create them
if pos.frameList==None and visible:
pos.paintFrames()
#if the frames already exist, use the set_mosaic_visible function to make them visible/invisible
#as frameList is a posList class.. low and behold fancy recursive META logic
if not pos.frameList==None:
pos.frameList.set_mosaic_visible(visible)
def select_points_inside(self,verts):
"""select all the points inside the vertices created by the Lasso widget callback function
recursively calls the select_if_inside function of all slicePositions in the list"""
for pos in self.slicePositions:
pos.select_if_inside(verts)
def select_all(self):
for pos in self.slicePositions:
pos.set_selected(True)
def shift_selected(self,dx,dy):
"""shift all the points which are selected by dx,dy
keywords:
dx,dy) the shift in microns to move each point
"""
for pos in self.slicePositions:
if pos.selected:
pos.shiftPosition(dx,dy)
def shift_all(self,dx,dy):
"""shift all the slicePositions in the position list by dx,dy
keywords:
dx,dy) the shift in microns to move each point
"""
for pos in self.slicePositions:
pos.shiftPosition(dx,dy)
def unrotate_boxes(self):
"""set the angle attribute on each slicePosition to be 0 and update the drawing properties appropriately"""
for pos in self.slicePositions:
pos.setAngle(0)
def rotate_boxes(self):
"""calculate the tangent angle of the ribbon at each point using the calcAngles function and then set the angle
attribute of each slice position using setAngle"""
theta=self.calcAngles()
for index, pos in enumerate(self.slicePositions):
pos.setAngle(theta[index])
def rotate_boxes_angle(self):
"""use angle from loaded JSON position list and then set the angle
attribute of each slice position using setAngle"""
for index, pos in enumerate(self.slicePositions):
pos.setAngle(pos.angle)
def rotate_selected(self,dtheta):
"""
Args:
dtheta: angle in radians to rotate all selected positions
Returns:None
"""
for index, pos in enumerate(self.slicePositions):
if pos.selected:
pos.rotateAngle(dtheta)
def shift_selected_curve(self,dx,dy):
"""shift all the selected points by dx,dy in coordinates that are rotated according the curvature of the ribbon,
making use of calcAngles to determine the angle
keywords:
dx,dy) the shift in microns to move each point
"""
theta=[pos.angle for pos in self.slicePositions]
#use a rotation matrix to determine the right dx,dy in absolute coordinates
dx_rot=dx*cos(theta)+dy*sin(theta)
dy_rot=(dx*sin(theta)-dy*cos(theta))
for index, pos in enumerate(self.slicePositions):
if pos.selected:
pos.shiftPosition(dx_rot[index],dy_rot[index])
def get_position_nearest(self,x,y):
"""return the slicePosition nearest an x,y point
keywords:
x)the x coordinate in microns to get the nearest point
y)the y coordinate in microns to get the nearest point
returns newpos
the slicePosition from the list which is closest to the input point
"""
(xpos,ypos,select)=self.__getXYS()
dx=(xpos-x)
dy=(ypos-y)
dist=np.sqrt(dx*dx+dy*dy)
min_index=dist.argmin()
return self.slicePositions[min_index]
def get_nearest_position_index(self,x,y):
"""return the slicePosition index nearest an x,y point
keywords:
x)the x coordinate in microns to get the nearest point
y)the y coordinate in microns to get the nearest point
returns index
the slicePosition index from the list which is closest to the input point
"""
(xpos,ypos,select)=self.__getXYS()
dx=(xpos-x)
dy=(ypos-y)
dist=np.sqrt(dx*dx+dy*dy)
min_index=dist.argmin()
return min_index
def calcAngles(self):
"""calculate the angle tangent to each point on the position list
makes sure to calculate the angle only using points on the ribbon which are selected to deal with breaks in the ribbon"""
#calculate the delta x and delta y vector along line
#using pointLine2D to the right, except for the last one, use the pointLine2D to the left
#get the positions and selected attributes as numpy vectors
#first sort the points to make them in order
self.__sort_points()
(xpos,ypos,select)=self.__getXYS()
if (len(xpos)<2):
return np.zeros(len(xpos))
delx=np.diff(xpos)
delx=np.append(delx,delx[len(delx)-1])
dely=np.diff(ypos)
dely=np.append(dely,dely[len(dely)-1])
#calculate the angle from this vector, fixing up small changes in x
theta=arctan(dely/delx)
theta[np.isnan(theta)]=pi/2
#when we are selecting a subset of points, we want the slope to be
#defined WITHIN the selection when possible, so fix up the right
#most points of streaks of selection to use the slope the left
#this won't be possible for singulatons, but who cares
#conver the true/false into 1.0/0.0 binary
#binary=self.selected*1.0
#the ones to fix are located at the downticks of the diff
badones,=np.where(np.diff(select)==-1)
#if the first pointLine2D is a downtick, there is no pointLine2D to the left
#so remove it from the list
if (len(badones)>0):
if (badones[0]==0):
badones=badones[1:]
#use the slope to the left for these points we are fixing up
theta[badones]=theta[badones-1]
#for i,pos in enumerate(self.slicePositions):
# pos.setAngle(theta[i])
return theta
def getXYZ(self):
xpos=[]
ypos=[]
zpos=[]
for pos in self.slicePositions:
xpos.append(pos.x)
ypos.append(pos.y)
zpos.append(pos.z)
return (np.array(xpos),np.array(ypos),np.array(zpos))
def __getXYS(self):
"""get the current position list as a series of numpy vectors
returns (xpos,ypos,select)
xpos)a N element long numpy vector of the x coordinate in microns
ypos)a N element long numpy vector of the y coordinate in microns
select)a N element long numpy vector where 1.0 means it is selected and 0.0 means it is not selected"""
xpos=[]
ypos=[]
select=[]
for pos in self.slicePositions:
xpos.append(pos.x)
ypos.append(pos.y)
if pos.selected:
select.append(1.0)
else:
select.append(0.0)
return (np.array(xpos),np.array(ypos),np.array(select))
def getXYpoints(self):
"""get the current position list (x,y) as a series of numpy vectors
returns (xpos,ypos,select)
xpos)a N element long numpy vector of the x coordinate in microns
ypos)a N element long numpy vector of the y coordinate in microns"""
points=[]
for pos in self.slicePositions:
points.append(Point(pos.x,pos.y));
return points
def add_position(self,x,y,edgecolor='g',withpoint=True,selected=False,z=None):
"""add a new position to the position list
keywords:
x) the x coordinate of the new position in microns
y) the y coordinate of the new position in microns
edgecolor) matplotlib color string describing the color of the mosaic box to draw around this position (default='g')
withpoint) boolean whether to draw the point as a blue X where this point is (default=True)
"""
newPosition=slicePosition(axis=self.axis,pos_list=self,x=x,y=y,z=z,edgecolor=edgecolor,withpoint=withpoint,
numberDisplaySettings = self.numberDisplaySettings,selected=selected)
self.slicePositions.append(newPosition)
if self.dosort:
self.__sort_points()
self.updateNumbers()
return newPosition
def delete_position(self,i):
assert (i>=0)
assert (i<len(self.slicePositions))
pos=self.slicePositions.pop(i)
pos.destroy()
del pos
def delete_selected(self):
"""delete all the points from the position list that are currently selected"""
#accomplish this by making a new list, and copying over the points you are saving from the old list, then replacing the old attribute
newPositions=[]
if not self.pos1==None:
if self.pos1.selected:
self.pos1=None
if not self.pos2==None:
if self.pos2.selected:
self.pos2=None
for pos in self.slicePositions:
if pos.selected:
pos.destroy()
del pos
else:
newPositions.append(pos)
self.slicePositions=newPositions
self.updateNumbers()
def LoadFromFile(self,file,format):
if format=='AxioVision':
self.add_from_file(file)
elif format=='OMX':
self.add_from_file_OMX(file)
elif format=='SmartSEM':
SEMsetting=self.add_from_file_SmartSEM(file)
self.SmartSEMSettings=SEMsetting
elif format=='JSON': #MultiRibbons
self.add_from_file_JSON(file)
def add_from_posList(self,posList):
for pos in posList.slicePositions:
newPosition=slicePosition(axis=self.axis,pos_list=self,x=pos.x,y=pos.y,z=pos.z,
numberDisplaySettings=self.numberDisplaySettings,edgecolor=pos.edgecolor,withpoint=pos.withpoint,
selected=pos.selected,number=pos.number)
self.slicePositions.append(newPosition)
def add_from_file(self,filename):
"""add points to the position list from a file, currently only implementing axiovision positionlist format
keywords:
filename)a string containing the path of the file to load
"""
print "adding from file"
ifile = open(filename, "rb")
reader = csv.reader(open(filename, 'rb'), delimiter=',')
rownum = 0
row_count = sum(1 for row in csv.reader(open(filename, 'rb'), delimiter=',') )
headerrows=7
self.xpos=np.zeros(row_count-headerrows)
self.ypos=np.zeros(row_count-headerrows)
self.selected=np.zeros(row_count-headerrows,dtype=bool)
self.p1=-1
self.p2=-1
for row in reader:
if rownum >headerrows-1:
if len(row)>0:
z=row[3]
if len(z)==0:
z=None
else:
z=float(z)
newPosition=slicePosition(axis=self.axis,pos_list=self,x=float(row[1]),y=float(row[2]),
z=z,numberDisplaySettings=self.numberDisplaySettings)
self.slicePositions.append(newPosition)
rownum += 1
ifile.close()
self.updateNumbers()
def add_from_file_OMX(self,filename):
"""add points to the position list from an OMX position list file
keywords:
filename)a string containing the path of the file to load
"""
print "adding from file"
ifile = open(filename, "rb")
reader = csv.reader(open(filename, 'rb'), delimiter=',')
rownum = 0
row_count = sum(1 for row in csv.reader(open(filename, 'rb'), delimiter=',') )
headerrows=0
self.xpos=np.zeros(row_count-headerrows)
self.ypos=np.zeros(row_count-headerrows)
self.selected=np.zeros(row_count-headerrows,dtype=bool)
self.p1=-1
self.p2=-1
for row in reader:
if rownum >headerrows-1:
if len(row)>0:
(label_and_x,Y,Z)=row
(label,X)=label_and_x.split(': ')
newPosition=slicePosition(axis=self.axis,pos_list=self,x=float(X),y=float(Y),
numberDisplaySettings=self.numberDisplaySettings)
self.slicePositions.append(newPosition)
rownum += 1
ifile.close()
self.updateNumbers()
def add_from_file_ZEN(self,filename):
"""add points to the position list from an OMX position list file
keywords:
filename)a string containing the path of the file to load
"""
print "adding from file"
ifile = open(filename, "rb")
reader = csv.reader(open(filename, 'rb'), delimiter=',')
rownum = 0
row_count = sum(1 for row in csv.reader(open(filename, 'rb'), delimiter=',') )
headerrows=1
self.xpos=np.zeros(row_count-headerrows)
self.ypos=np.zeros(row_count-headerrows)
self.selected=np.zeros(row_count-headerrows,dtype=bool)
self.p1=-1
self.p2=-1
for row in reader:
if rownum >headerrows-1:
if len(row)>0:
newPosition=slicePosition(axis=self.axis,pos_list=self,x=float(row[1]),y=float(row[2]),
numberDisplaySettings= self.numberDisplaySettings,z=float(row[3]))
self.slicePositions.append(newPosition)
rownum += 1
ifile.close()
self.updateNumbers()
def add_from_file_SmartSEM(self,filename):
"""add points to the position list from a Smart SEM position list file
keywords:
filename)a string containing the path of the file to load
"""
ifile = open(filename, "rb")
reader = csv.reader(open(filename, 'rb'), delimiter=',')
rownum = 0
row_count = sum(1 for row in csv.reader(open(filename, 'rb'), delimiter=',') )
headerrows=4
self.xpos=np.zeros(row_count-headerrows)
self.ypos=np.zeros(row_count-headerrows)
self.selected=np.zeros(row_count-headerrows,dtype=bool)
self.p1=-1
self.p2=-1
for row in reader:
if rownum >headerrows-1:
(Label,X,Y,Z,T,R,M,Mag,WD)=row
newPosition=slicePosition(axis=self.axis,pos_list=self,x=float(X),y=float(Y),
numberDisplaySettings=self.numberDisplaySettings)
self.slicePositions.append(newPosition)
rownum += 1
ifile.close()
SEMSetting=SmartSEMSettings(mag=float(Mag),tilt=float(T),rot=float(R),Z=float(Z),WD=float(WD))
self.updateNumbers()
return SEMSetting
def add_from_file_JSON(self,filename): #MultiRibbons
"""add points to the position list from a JSON file
keywords:
filename)a string containing the path of the file to load
"""
print "adding from file"
ifile = open(filename, "rb")
thestring = ifile.read()
thedict = json.JSONDecoder().decode(thestring)
print thedict
self.xpos=np.zeros(len(thedict["POSITIONS"]))
self.ypos=np.zeros(len(thedict["POSITIONS"]))
self.selected=np.zeros(len(thedict["POSITIONS"]),dtype=bool)
self.p1=-1
self.p2=-1
for i in range(len(thedict["POSITIONS"])):
newPosition=slicePosition(axis=self.axis,pos_list=self,x=thedict["POSITIONS"][i]["X"],\
y=thedict["POSITIONS"][i]["Y"],z=None,angle=thedict["POSITIONS"][i]["ANGLE"],numberDisplaySettings=self.numberDisplaySettings)
self.slicePositions.append(newPosition)
self.mosaic_settings.mx = thedict["MOSAIC"]["MOSAICX"]
self.mosaic_settings.my = thedict["MOSAIC"]["MOSAICY"]
self.mosaic_settings.overlap = thedict["MOSAIC"]["OVERLAP"]
self.set_mosaic_settings(self.mosaic_settings)
ifile.close()
self.updateNumbers()
def load_frame_state_table(self,filename):
filename, formattype = filename.split('.')
filename = filename + 'frame_state_table.json'
if os.path.exists(filename):
ifile = open(filename,'rb')
thedict = json.load(ifile)
for i,item in enumerate(sorted(thedict)):
self.slicePositions[i].update_framestates(thedict[item])
else:
pass
def save_position_list(self,filename,trans=None):
"""save the positionlist to a axiovision position list format, csv format
keywords:
filename)a string containing the path of the file to save list into
trans)an optional transform object which will cause the points to be saved to the file, not with their original
coordinates, but with the coordinates run through the trans.transform(x,y) method
"""
self.__sort_points()
writer = csv.writer(open(filename, 'wb'), delimiter=',',quoting=csv.QUOTE_NONNUMERIC)
writer.writerow(["Slide","","","","",""])
writer.writerow(["Name","Width","Height","Description",'',''])
writer.writerow(["Slide 1A Ribbon 1 Site 1",76000.000000,24000.000000,"Slide - 76 mm x 24 mm (3 x 1)",'',''])
writer.writerow(['','','','','',''])
writer.writerow(['','','','','',''])
writer.writerow(["Positions",'','','','',''])
writer.writerow(["Comments","PositionX","PositionY","PositionZ","Color","Classification"])
for index,pos in enumerate(self.slicePositions):
#"Comments","PositionX","PositionY","PositionZ","Color","Classification"
#"1000000",-29541.755,6144.1,0.000000," blue "," blue"
if trans == None:
writer.writerow(["%d"%(100000+index),pos.x,pos.y,pos.z," blue "," blue "])
else:
(xt,yt)=trans.transform(pos.x,pos.y)
writer.writerow(["%d"%(100000+index),xt,yt,pos.z," blue "," blue "])
def save_position_list_uM(self,filename,trans=None):
self.__sort_points()
points=np.array([[pos.x,pos.y] for pos in self.slicePositions])
poslist=[]
for index,pos in enumerate(self.slicePositions):
#"Comments","PositionX","PositionY","PositionZ","Color","Classification"
#"1000000",-29541.755,6144.1,0.000000," blue "," blue"
if trans == None:
posdict={"GRID_COL": 0,"DEVICES": [{"DEVICE": "XYStage","AXES": 2,"Y": pos.y,"X": -pos.x,"Z": 0}],"PROPERTIES": {},"DEFAULT_Z_STAGE": "ZStage","LABEL": "p%03.3d"%(index),"GRID_ROW": 0,"DEFAULT_XY_STAGE": "XYStage"}
else:
(xt,yt)=trans.transform(pos.x,pos.y)
posdict={"GRID_COL": 0,"DEVICES": [{"DEVICE": "XYStage","AXES": 2,"Y": yt,"X": -xt,"Z": 0}],"PROPERTIES": {},"DEFAULT_Z_STAGE": "ZStage","LABEL": "p%03.3d"%(index),"GRID_ROW": 0,"DEFAULT_XY_STAGE": "XYStage"}
poslist.append(posdict)
dict={"VERSION": 3,
"ID": "Micro-Manager XY-position list",
"POSITIONS":poslist}
thestring=json.JSONEncoder().encode(dict)
file = open(filename,'w')
file.write(thestring)
file.close()
def save_position_list_SmartSEM(self,filename,SEMS=SmartSEMSettings(),trans=None):
self.__sort_points()
writer = csv.writer(open(filename, 'wb'), delimiter=',')
writer.writerow(["Leo Points List"])
writer.writerow(["Absolute"])
writer.writerow(["Label","X","Y","Z","T","R","M","Mag","WD"])
writer.writerow(["%d"%len(self.slicePositions)])
for index,pos in enumerate(self.slicePositions):
#"Comments","PositionX","PositionY","PositionZ","Color","Classification"
#"1000000",-29541.755,6144.1,0.000000," blue "," blue"
if trans == None:
writer.writerow(["%03d"%(index),pos.x,pos.y,SEMS.Z,SEMS.tilt,SEMS.rot,0.00,SEMS.mag,SEMS.WD])
else:
(xt,yt)=trans.transform(pos.x,pos.y)
writer.writerow(["%03d"%(index),xt,yt,SEMS.Z,SEMS.tilt,SEMS.rot,0.00,SEMS.mag,SEMS.WD])
def save_position_list_ZEN(self,filename,trans=None,planePoints=None,zoffset=47.33-34.79):
self.__sort_points()
writer = csv.writer(open(filename, 'wb'), delimiter=',')
writer.writerow(["Name","X","Y","Z","Width","Height","ContourType"])
points=np.array([[pos.x,pos.y] for pos in self.slicePositions])
print points.shape
print points
if planePoints is not None:
newZ=griddata(planePoints[:,0:2],planePoints[:,2],points,'nearest')
else:
newZ=np.zeros(len(self.slicePositions));
for index,pos in enumerate(self.slicePositions):
if pos.Z is not None:
newZ[index]=pos.Z-zoffset
for index,pos in enumerate(self.slicePositions):
#"Comments","PositionX","PositionY","PositionZ","Color","Classification"
#"1000000",-29541.755,6144.1,0.000000," blue "," blue"
if trans == None:
writer.writerow(["p%03.3d"%(index),pos.x,pos.y,newZ[index]+zoffset,'','',''])
else:
(xt,yt)=trans.transform(pos.x,pos.y)
writer.writerow(["p%03.3d"%(index),xt,yt,newZ[index]+zoffset,'','',''])
def write_position_ZENczsh(self,SingleTileRegions,index,x,y,z):
SingleTileRegion=ET.SubElement(SingleTileRegions,"SingleTileRegion")
SingleTileRegion.set("Name","p%03d"%index)
SingleTileRegion.set("Id","%d"%(1000000+index))
X=ET.SubElement(SingleTileRegion,"X")
Y=ET.SubElement(SingleTileRegion,"Y")
Z=ET.SubElement(SingleTileRegion,"Z")
X.text = "%5.3f"%x
Y.text = "%5.3f"%y
Z.text = "%5.3f"%z
IsUsedForAcquisition=ET.SubElement(SingleTileRegion,"IsUsedForAcquisition")
IsUsedForAcquisition.text = "true"
return SingleTileRegions
def save_position_list_ZENczsh(self,filename,trans=None,planePoints=None,zoffset=47.33-34.79):
self.__sort_points()
root = ET.Element("SampleHolder")
#overlap=ET.SubElement(root,"Overlap")
#overlap.text = 0.05
#ScanMode=ET.SubElement(root,"ScanMode")
#ScanMode.text = "Comb"
#IsConstantTiles=ET.SubElement(root,"IsConstantTiles")
#IsConstantTiles.text = "false"
#TileRegionAnchorMode=ET.SubElement(root,"TileRegionAnchorMode")
#TileRegionAnchorMode.text = "BottomRight"
TileRegions=ET.SubElement(root,"TileRegions")
#overlap.text = 0.05
#writer.writerow([" <TileRegions />"])
#writer.writerow(["<SingleTileRegions>"])
TileRegions=ET.SubElement(root,"TileRegions")
SingleTileRegions=ET.SubElement(root,"SingleTileRegions")
points=np.array([[pos.x,pos.y] for pos in self.slicePositions])
print points.shape
print points
if planePoints is not None:
newZ=griddata(planePoints[:,0:2],planePoints[:,2],points,'nearest')
else:
newZ=np.zeros(len(self.slicePositions));
for index,pos in enumerate(self.slicePositions):
if pos.Z is not None:
newZ[index]=pos.Z-zoffset
for index,pos in enumerate(self.slicePositions):
#"Comments","PositionX","PositionY","PositionZ","Color","Classification"
#"1000000",-29541.755,6144.1,0.000000," blue "," blue"
if trans == None:
self.write_position_ZENczsh(SingleTileRegions,index,pos.x,pos.y,newZ[index]+zoffset)
else:
(xt,yt)=trans.transform(pos.x,pos.y)
self.write_position_ZENczsh(SingleTileRegions,index,xt,yt,newZ[index]+zoffset)
tree = ET.ElementTree(root)
tree.write(filename,pretty_print=True,xml_declaration=True)
def save_position_list_OMX(self,filename,trans=None,Z=13235.0):
self.__sort_points()
writer = csv.writer(open(filename, 'wb'), delimiter=',')
count=0;
for index,pos in enumerate(self.slicePositions):
count=count+1;
if trans==None:
writer.writerow(['%03d: %f'%(index,pos.x),pos.y,Z])
else:
(xt,yt)=trans.transform(pos.x,pos.y)
writer.writerow(['%03d: %f'%(index,xt),yt,Z])
def save_position_list_JSON(self,filename,trans=None): #MultiRibbons
#save the positionlist to JSON format, include position x, y, angle, mosaic settings, channel settings
self.__sort_points()
poslist=[]
for index,pos in enumerate(self.slicePositions):
if trans == None:
posdict={"SECTION": "%d"%(100000+index),"X": pos.x,"Y": pos.y,"ANGLE": pos.angle}
else:
(xt,yt)=trans.transform(pos.x,pos.y)
posdict={"SECTION": "%d"%(100000+index),"X": xt,"Y": yt,"ANGLE": pos.angle}
poslist.append(posdict)
dict={"MOSAIC": {"MOSAICX": self.mosaic_settings.mx,"MOSAICY": self.mosaic_settings.my,"OVERLAP": self.mosaic_settings.overlap},
"CHANNELS": {},
"POSITIONS":poslist}
thestring=json.JSONEncoder().encode(dict)
file = open(filename,'w')
file.write(thestring)
file.close()
def on_save_frame_state_table(self,filepath):
filename, formattype = filepath.split('.')
filename = filename + 'frame_state_table.json'
statetable_dict = {}
for i in range(len(self.slicePositions)):
section_num, frame_statelist = self.slicePositions[i].create_frame_state_list()
statetable_dict[section_num] = frame_statelist
thestring = json.JSONEncoder().encode(statetable_dict)
with open(filename,'w') as file:
file.write(thestring)
file.close()
def save_frame_list_OMX(self,filename,trans=None,Z=13235.0):
"""save the positionlist to a SmartSEM position list csv format, where each frame of the mosaic is its own position
keywords:
filename)a string containing the path of the file to save list into
trans)an optional transform object which will cause the points to be saved to the file, not with their original
coordinates, but with the coordinates run through the trans.transform(x,y) method
"""
if self.dosort:
self.__sort_points()
writer = csv.writer(open(filename, 'wb'), delimiter=',')
count=0;
for index,pos in enumerate(self.slicePositions):
#pos.frameList.__sort_points(vertsort=True)
for frameindex,framepos in enumerate(pos.frameList.slicePositions):
count=count+1;
if trans==None:
writer.writerow(["S%03d_F%03d: %f"%(index,frameindex,framepos.x),framepos.y,Z])
else:
(xt,yt)=trans.transform(framepos.x,framepos.y)
writer.writerow(["S%03d_F%03d: %f"%(index,frameindex,xt),yt,Z])
def save_frame_list_SmartSEM(self,filename,SEMS=SmartSEMSettings(),trans=None):
"""save the positionlist to a SmartSEM position list csv format, where each frame of the mosaic is its own position
keywords:
filename)a string containing the path of the file to save list into
trans)an optional transform object which will cause the points to be saved to the file, not with their original
coordinates, but with the coordinates run through the trans.transform(x,y) method
"""
self.__sort_points()
writer = csv.writer(open(filename, 'wb'), delimiter=',')
writer.writerow(["Leo Points List"])
writer.writerow(["Absolute"])
writer.writerow(["Label","X","Y","Z","T","R","M","Mag","WD"])
count=0
for index,pos in enumerate(self.slicePositions):
for frameindex,framepos in enumerate(pos.frameList.slicePositions):
count=count+1
writer.writerow(["%d"%count])
for index,pos in enumerate(self.slicePositions):
pos.frameList.__sort_points(vertsort=True)
for frameindex,framepos in enumerate(pos.frameList.slicePositions):
if trans==None:
writer.writerow(["S%03d_F%03d"%(index,frameindex),framepos.x,framepos.y,SEMS.Z,SEMS.tilt,SEMS.rot,0.00,SEMS.mag,SEMS.WD])
else:
(xt,yt)=trans.transform(framepos.x,framepos.y)
writer.writerow(["S%03d_F%03d"%(index,frameindex),xt,yt,SEMS.Z,SEMS.tilt,SEMS.rot,0.00,SEMS.mag,SEMS.WD])
def save_frame_list(self,filename,trans=None):
"""save the positionlist to a axiovision position list format, csv format, where each frame of the mosaic is its own position
keywords:
filename)a string containing the path of the file to save list into
trans)an optional transform object which will cause the points to be saved to the file, not with their original
coordinates, but with the coordinates run through the trans.transform(x,y) method
"""
if self.dosort:
self.__sort_points()
writer = csv.writer(open(filename, 'wb'), delimiter=',',quoting=csv.QUOTE_NONNUMERIC)
writer.writerow(["Slide","","","","",""])
writer.writerow(["Name","Width","Height","Description",'',''])
writer.writerow(["Slide 1A Ribbon 1 Site 1",76000.000000,24000.000000,"Slide - 76 mm x 24 mm (3 x 1)",'',''])
writer.writerow(['','','','','',''])
writer.writerow(['','','','','',''])
writer.writerow(["Positions",'','','','',''])
writer.writerow(["Comments","PositionX","PositionY","PositionZ","Color","Classification"])
for index,pos in enumerate(self.slicePositions):
#pos.frameList.__sort_points(vertsort=True)
for frameindex,framepos in enumerate(pos.frameList.slicePositions):
if trans==None:
writer.writerow(["S%03d_F%03d"%(index,frameindex),framepos.x,framepos.y,0," blue "," blue "])
else:
(xt,yt)=trans.transform(framepos.x,framepos.y)
writer.writerow(["S%03d_F%03d"%(index,frameindex),xt,yt,0," blue "," blue "])
def __sort_points(self,vertsort=False):
"""sort the slicePositions in the list according to their x value"""
if self.dosort:
if vertsort:
self.slicePositions.sort(key=lambda pos: pos.y, reverse=False)
else:
self.slicePositions.sort(key=lambda pos: pos.x, reverse=False)
def updateNumbers(self):
for index,pos in enumerate(self.slicePositions):
pos.setNumber(index)
def setNumberVisibility(self,isvisible):
self.shownumbers=isvisible
for index,pos in enumerate(self.slicePositions):
pos.set_number_visible(isvisible)
def calcFrameSize(self):
"""calculate the size of a single frame of the camera given the current camera_settings and magnification from mosaic_settings
returns (frameheight,framewidth)
the size of the frame in microns
"""
framewidth=self.camera_settings.sensor_width*self.camera_settings.pix_width/self.mosaic_settings.mag
frameheight=self.camera_settings.sensor_height*self.camera_settings.pix_height/self.mosaic_settings.mag
return (frameheight,framewidth)
def calcMosaicSize(self):
"""calculates the size of the mosaic given the current camera_settings and mosaic settings
returns (mosaicheight,mosaicwidth)
the size of the mosaic in microns
"""
mx=self.mosaic_settings.mx
my=self.mosaic_settings.my
overlap=self.mosaic_settings.overlap
(frameheight,framewidth)=self.calcFrameSize()
totalwidth=framewidth*mx-((overlap*1.0)/100)*framewidth*(mx-1)
totalheight=frameheight*my-((overlap*1.0)/100)*frameheight*(my-1)
return (totalheight,totalwidth)