-
Notifications
You must be signed in to change notification settings - Fork 0
/
pyEM.py
executable file
·2434 lines (1815 loc) · 71.8 KB
/
pyEM.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
# -*- coding: utf-8 -*-
# pyEM.py
# Copyright (c) 2020, Martin Schorb
# Copyright (c) 2020, European Molecular Biology Laboratory
# Produced at the EMBL
# All rights reserved.
""" 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.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
# Python module for interpreting and modifying Navigator files created using SerialEM. For detailed information,
# see https://doi.org/10.1038/s41592-019-0396-9
# Information and documentation of the individual functions can be found in Readme.md
# dependencies
#
import os
import os.path
import sys
import numpy
import skimage.transform as tf
import copy
from skimage import io
import re
import mrcfile as mrc
import time
from operator import itemgetter
import fnmatch
from subprocess import Popen, PIPE
import xml.etree.ElementTree as ET
import xml.dom.minidom
mrcext = ('.st', '.mrc', '.map', '.rec', '.ali', '.preali')
# get python version
py_ver = sys.version_info
my_env = os.environ.copy()
# get IMOD version
p1 = Popen("imodinfo", shell=True, stdout=PIPE)
o = list()
for imodline in p1.stdout:
o.append(imodline)
if o == []:
print('Warning! - No IMOD installation found')
imod_ver = [0, 0, 0]
else:
o1 = str(o[0]).split(' ')
imod_ver = list(map(int, o1[o1.index('Version') + 1].split('.')))
# define functions
# %%
def loadtext(fname):
"""
Reads a text file and returns the lines.
Parameters
----------
fname : str
input path of a text file, such as nav (adoc or XML) or adoc
Returns
-------
list of str
"""
# check if file exists
if not os.path.exists(fname):
raise FileNotFoundError('ERROR: ' + fname + ' does not exist! Exiting' + '\n')
f = open(fname, "r")
lines = list()
for line in f.readlines():
lines.append(line.strip())
f.close()
return lines
# -------------------------------
# %%
def nav_item(inlines, label):
"""
Extracts the content block of a single navItem of given label.
Reads and parses navigator adoc files version >2, also in XML format !!
Returns the first item found as a dictionary and the remaining list with that item removed.
This is useful when multiple items have the exact same label and the function is called \\
from within a loop to retrieve them all.
Parameters
----------
inlines : list of str
input navigator file lines
label : str
the navigator label to extract
Returns
-------
dict
"""
#
lines = inlines[:]
if lines[0] == '<?xml version="1.0" encoding="utf-8"?>':
# load XML
root = ET.fromstringlist(lines)
el = root.findall('*[@name="%s"]' % label)
if el == []:
print('ERROR: Navigator Item ' + label + ' not found!')
result = []
else:
root.remove(el[0])
newroot = ET.Element('navigator')
newroot.append(el[0])
result = xmltonav(ET.tostringlist(newroot, encoding='unicode'))[0]
lines = ET.tostring(root)
lines = xml.dom.minidom.parseString(lines).toprettyxml().replace('\t', '').split('\n')
else:
if lines[-1] != '':
lines = lines + ['']
# search for a navigator item of given label
searchstr = '[Item = ' + label + ']'
if searchstr not in lines:
print('ERROR: Navigator Item ' + label + ' not found!')
result = []
else:
itemstartline = lines.index(searchstr) + 1
itemendline = lines[itemstartline:].index('')
item = lines[itemstartline:itemstartline + itemendline]
result = parse_adoc(item)
# create a dictionary entry that contains the label. Comment # is given in case it is exported directly.
result['# Item'] = lines[itemstartline - 1][lines[itemstartline - 1].find(' = ') + 3:-1]
lines[itemstartline - 1:itemstartline + itemendline + 1] = []
return result, lines
# -------------------------------
# %%
def adoc_items(lines1, search, header=False):
"""
Extracts the content block of an item of given label in an adoc file and \\
returns it as a list of dictionaries
Parameters
----------
lines1 : list of str
input adoc file lines
search : str
the search string
header : bool
if True, returns the header of the file instead.
Returns
-------
list of dict
"""
result = []
if lines1[-1] != '':
lines = lines1 + ['']
else:
lines = lines1
if header:
item = lines[:lines.index('')]
result.append(parse_adoc(item))
else:
pattern = '*' + search + '*'
matching = fnmatch.filter(lines, pattern)
if len(matching) == 0:
print('ERROR: String ' + search + ' not found!')
# search for mdoc key item with the given label
for searchstr in matching:
if searchstr not in lines:
print('ERROR: String ' + search + ' not found!')
elif '=' in searchstr[:searchstr.index(search)]:
print('ERROR: String ' + search + ' not found in labels!')
else:
itemstartline = lines.index(searchstr) + 1
itemendline = lines[itemstartline:].index('')
item = lines[itemstartline:itemstartline + itemendline]
itemdict = parse_adoc(item)
itemdict['# ' + searchstr] = lines[itemstartline - 1][
lines[itemstartline - 1].find(' = ') + 2:-1].lstrip(' ')
result.append(itemdict)
return result
# -------------------------------
# %%
def mdoc_item(lines1, label, header=False):
"""
Extracts the content block of an item of given label in a mdoc file and \\
returns it as a dictionary
Parameters
----------
lines1 : list of str
input mdoc file lines
label : str
the mdoc label to search for
header : bool
if True, returns the header of the file instead.
Returns
-------
list of dict
"""
if lines1[-1] != '':
lines = lines1 + ['']
else:
lines = lines1
if header:
item = lines[:lines.index('')]
else:
# search for mdoc key item with the given label
searchstr = '[' + label + ']'
if searchstr not in lines:
print('ERROR: Item ' + label + ' not found!')
item = []
else:
itemstartline = lines.index(searchstr) + 1
itemendline = lines[itemstartline:].index('')
item = lines[itemstartline:itemstartline + itemendline]
result = parse_adoc(item)
return result
# -------------------------------
# %%
def parse_adoc(lines):
"""
Converts an adoc-format string list into a dictionary.
Parameters
----------
lines1 : list of str
input adoc file lines
Returns
-------
dict
"""
#
output = {}
for line in lines:
entry = line.split()
if entry:
output.update({entry[0]: entry[2:]})
return output
# -------------------------------
# %%
def map_file(mapitem):
"""
Extracts map file name from navigator and checks for existance.
Checks all sub-directories if file is not present in the root (navigator location).
Parameters
----------
mapitem : dict
a Map Item dict from the Navigator
Returns
-------
str
"""
# get string from navigator item
mapfile = ' '.join(mapitem['MapFile'])
cdir = os.getcwd()
if os.path.exists(mapfile):
return mapfile
# print('current map: ' + mapfile)
else:
# print('Warning: ' + mapfile + ' does not exist!' + '\n')
mapfile1 = mapfile[mapfile.rfind('\\') + 1:]
dir1 = mapfile[:mapfile.rfind('\\')]
dir2 = dir1[dir1.rfind('\\') + 1:]
# print('will try ' + mapfile1 + ' in current directory or subdirectories.' + '\n')
# check subdirectories recursively
mapfile2 = None
for path, directories, files in os.walk(cdir):
if mapfile1 in files:
mapfile = os.path.join(path, mapfile1)
if path == os.path.join(cdir, dir2):
return mapfile
else:
mapfile2 = mapfile
if mapfile2 is None:
raise FileNotFoundError('ERROR: ' + mapfile1 + ' does not exist! Exiting.')
else:
return mapfile2
# -------------------------------
# %%
# def findfile(searchstr, searchdir):
# # will find files that match a search string in subfolders of the provided search directory
# output = list()
# for rootdir, dirs, files in os.walk(searchdir):
# for file in files:
# if fnmatch.fnmatch(file, searchstr):
# output.append(os.path.join(rootdir, file))
# return output
# -------------------------------
# %%
def map_header(m):
"""
Extrracts the header of a map file.
Parameters
----------
m : str or dict or mrc.mrcfile.MrcFile
A map file, map dictionary or MRC object
Returns
-------
dict
"""
header = {}
if (type(m) is mrc.mrcfile.MrcFile) | (type(m) is mrc.mrcmemmap.MrcMemmap):
# extracts MRC header information for a given mrc.object (legacy from reading mrc headers)
header['xsize'] = int(m.header.nx)
header['ysize'] = int(m.header.ny)
header['stacksize'] = int(m.header.nz)
# determine the scale
header['pixelsize'] = m.voxel_size.x / 10000 # in um
elif type(m) is dict:
if "MapFile" in m.keys():
merge = mergemap(m)# THERE IS A BUG!!!!!, blendmont=False)
header = merge['mapheader']
elif type(m) is str:
if os.path.exists(m):
if os.path.splitext(m)[1] in mrcext:
header = map_header(mrc.mmap(m, permissive='True'))
return header
# -------------------------------
# %%
def itemtonav(item, name):
"""
Converts a dictionary autodoc item variable into text list suitable for export into navigator format.
Parameters
----------
item : dict
Navigator Item
name : str
Item label name
Returns
-------
list of str
"""
dlist = list()
dlist.append('[Item = ' + name + ']')
# Python 2
if py_ver[0] < 3:
for key, value in item.iteritems():
if not key == '# Item':
dlist.append(key + ' = ' + " ".join(value))
else:
# Python 3+
for key, value in item.items():
if not key == '# Item':
dlist.append(key + ' = ' + " ".join(value))
dlist.append('')
return dlist
# -------------------------------
# %%
def write_navfile(filename, outitems, xml=False):
"""
Creates a new navigator file from a list of navItems (default is mdoc format)
Parameters
----------
filename : str
File name to ouput (needs to be writable.)
outitems : list of dict
A list of items to be written.
xml : bool
If true, write Navigator in XML format.
"""
allitems = copy.deepcopy(outitems)
if xml:
root = ET.Element('navigator')
pd = ET.SubElement(root, 'PreData')
adv = ET.SubElement(pd, 'AdocVersion')
adv.text = '2.00'
lsa = ET.SubElement(pd, 'LastSavedAs')
lsa.text = filename
for item in allitems:
print(item)
print(item['# Item'])
ci = ET.SubElement(root, 'Item')
ci.set('name', item['# Item'])
for key, val in item.items():
if not key == '# Item':
cp = ET.SubElement(ci, key)
cp.text = ' '.join(val)
indent_xml(root)
tree = ET.ElementTree(root)
tree.write(filename, encoding="utf-8", xml_declaration=True)
else:
# MDOC format
head0 = 'AdocVersion = 2.00'
head1 = 'LastSavedAs = ' + filename
nnf = open(filename, 'w')
nnf.write("%s\n" % head0)
nnf.write("%s\n" % head1)
nnf.write("\n")
# fill the new file
for nitem in allitems:
out = itemtonav(nitem, nitem['# Item'])
for item in out:
nnf.write("%s\n" % item)
nnf.close()
# -------------------------------
# pretty print xml, from:
# http://effbot.org/zone/element-lib.htm#prettyprint
def indent_xml(elem, level=0):
i = "\n" + level * " "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
indent_xml(elem, level + 1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
# ------------------------------
# %%
def newID(allitems, startid):
"""
Checks if provided item ID already exists in a navigator and gives the next unique ID.
Parameters
----------
allitems : list of dict
list of all items in a Navigator (<-fullnav)
startid : int
starting ID
Returns
-------
int
"""
newid = startid
for item in allitems:
if 'MapID' in item:
if str(startid) == item['MapID'][0]:
newid = newID(allitems, startid + 1)
return newid
# -------------------------------
# %%
def newreg(navitems):
"""
Returns the next available registration for the input set of navigator items
Parameters
----------
navitems : list of dict
list of Navigator items
Returns
-------
int
"""
#
reg = list()
for item in navitems:
reg.append(int(item['Regis'][0]))
return max(reg) + 1
# -------------------------------
# %%
def fullnav(inlines, header=False):
"""
Parses a full nav file and returns a list of dictionaries.
Parameters
----------
inlines : list of str
input navigator file lines
header : bool
if True, returns the header of the file instead.
Returns
-------
list of dict
"""
navlines = inlines[:]
if '<?xml version=' in navlines[0]:
# load XML
c = xmltonav(navlines)
else:
# mdoc format
c = []
for index, item in enumerate(navlines):
if item.find('[Item') > -1:
if header:
return inlines[:index - 1]
(b, navlines) = nav_item(navlines, item[item.find(' = ') + 3:-1])
b['# Item'] = item[item.find(' = ') + 3:-1]
c.append(b)
return c
# -------------------------------
# %%
def xmltonav(navlines):
"""
Parses a XML block and returns the contents as a list of dictionaries.
Parameters
----------
inlines : list of str
input XML file lines
Returns
-------
list of dict
"""
if not navlines[0].lstrip(' ').startswith('<'):
raise ValueError('Input string list not in XML format!')
root = ET.fromstringlist(navlines)
c = []
for child in root:
if child.tag == 'Item':
item = dict({'# Item': child.attrib['name']})
for prop in child:
item[prop.tag] = prop.text.split(' ')
c.append(item)
return c
# -------------------------------
# %%
def navlabel_match(navitems, searchstr):
"""
Identifies navigator items whose labels contain the given string
Parameters
----------
navitems : list of dict
List of Navigator items
searchstr : str
String to be searched
Returns
-------
list of dict
"""
r = re.compile(r'.*' + searchstr + '.*')
return list(filter(lambda item: r.match(item['# Item']), navitems))
# -------------------------------
# %%
def duplicate_items(navitems, labels=None, prefix='', reg=True, maps=False):
"""
Duplicates a set of Navigator items. Adds the duplicates to the original Navigator list.
Parameters
----------
navitems : list of dict
List of Navigator items
labels : bool
list of labels of the items to duplicate
prefix : str
prefix to be added to the label of the created duplicates
reg : bool
determines whether the registration of duplicate items should be changed (default:yes)
maps :bool
if True, all maps that contain the label of the selected items or that were used to draw \\
these are duplicated as well.
Returns
-------
list of dict
"""
if labels is None:
labels = []
outitems = copy.deepcopy(navitems)
if labels == []:
dupitems = nav_selection(navitems)
for item in dupitems:
item['Acquire'] = ['0']
else:
dupitems = nav_selection(navitems, labels, False)
if reg:
new_reg = [str(newreg(dupitems))]
else:
new_reg = dupitems[0]['Regis']
for item in dupitems:
newitem = copy.deepcopy(item)
newitem['Regis'] = new_reg
newitem['# Item'] = prefix + item['# Item']
newitem['MapID'] = [str(newID(outitems, int(newitem['MapID'][0])))]
if maps:
drawnmap = realign_map(newitem, navitems)
newmapID = newID(outitems, int(drawnmap['MapID'][0])) + 1
if not drawnmap == []:
dupdrawn = copy.deepcopy(drawnmap)
dupdrawn['# Item'] = prefix + drawnmap['# Item']
dupdrawn['Regis'] = new_reg
existingmaps = nav_find(outitems, '# Item', val=dupdrawn['# Item'])
existingdupmaps = nav_find(existingmaps, 'Regis', val=dupdrawn['Regis'])
dupdrawn['MapID'] = [str(newmapID)]
if len(existingdupmaps) == 0:
othermaps = navlabel_match(navitems, dupdrawn['# Item'])
othermaps.pop(othermaps.index(nav_selection(othermaps, sel=dupdrawn['# Item'], acquire=False)[0]))
outitems.append(dupdrawn)
newitem['DrawnID'] = dupdrawn['MapID']
outitems.append(newitem)
return outitems
# -------------------------------------
def map_matrix(mapitem):
"""
Extracts the matrix relating pixel and stage coordinates from a Map Item
Parameters
----------
mapitem : dict
Navigator map item
Returns
-------
numpy.array
"""
return numpy.array(list(map(float, mapitem['MapScaleMat']))).reshape(2, 2) * (
int(mapitem['MapBinning'][0]) / int(mapitem['MontBinning'][0]))
# -------------------------------
# %%
def mergemap(mapitem, crop=False, black=False,
blendmont=True, bigstitch=False, mapfile=None, mapsection=0):
# %%
# processes a map item and merges the mosaic using IMOD
# generates a dictionary with metadata for this procedure
# if crop is selected, a 3dmod session will be opened and the user needs to draw a model of the desired region.
# The script continues after saving the model file and closing 3dmod.
# black option will fill the empty spaces between tiles with 0
# blendmont will use blendmont to merge the montage.
# If disabled individual tile information is stored in the merge dict nevertheless.
blend_in = blendmont
m = dict()
m['Sloppy'] = False
# check if function is called with only a map file without navigator
if mapfile is None:
# extract map properties
mat = map_matrix(mapitem)
# find map file
mapfile = map_file(mapitem)
# print('processing mapitem '+mapitem['# Item']+' - file: '+mapfile)
mapsection = list(map(int, mapitem['MapSection']))[0]
m['frames'] = list(map(int, mapitem['MapFramesXY']))
else:
mat = numpy.eye(2)
callcmd = 'extractpieces ' + mapfile + ' -ou ' + mapfile + '.pcs'
os.system(callcmd)
pxpos = loadtext(mapfile + '.pcs')
tilepx = numpy.array([re.split(' +', line) for line in pxpos])
frames = numpy.unique(tilepx[:, 0:2], axis=0)
m['frames'] = [frames.shape[0], 1]
montage_tiles = numpy.prod(m['frames'])
tileidx_offset = 0
mbase = os.path.splitext(mapfile)[0]
mergebase = mbase + '_merged' + '_s' + str(mapsection)
if os.path.splitext(mapfile)[1] not in mrcext:
# not an mrc file
mergeheader = {}
# mergeheader['stacksize'] = 1
if '.idoc' in mapfile:
# List of tif files with additional metadata
idoctxt = loadtext(mapfile)
tilepos = list()
tilepx = list()
tilepx1 = list()
# find the stack size from the last index of the file list (idoc)
testlast = idoctxt.copy()
testlast.reverse()
lastitem = testlast[0]
for index, item in enumerate(testlast):
if item.strip() == '':
lastitem = testlast[index - 1]
if 'Image = ' in lastitem:
break
prefix = os.path.basename(mbase) # [:mbase.find('.idoc')]
stacksize = int(lastitem[lastitem.find(prefix) + len(prefix):-5]) + 1
mergeheader['stacksize'] = stacksize
maphead0 = mdoc_item(idoctxt, [], header=True)
im = list()
if montage_tiles == 0:
# stack of single images
mergefile = mapfile[:mapfile.find('.idoc')] + '{:04d}'.format(mapsection) + '.tif'
mergeheader['stacksize'] = 0
tilepos = mapitem['StageXYZ'][0:2]
tilepx = '0'
tilepx = numpy.array([[tilepx, tilepx, mapsection], [tilepx, tilepx, mapsection]])
tilepx1 = tilepx
m['Sloppy'] = 'NoMont'
im = io.imread(mergefile)
mergeheader['xsize'] = numpy.array(im.shape)[0]
mergeheader['ysize'] = numpy.array(im.shape)[1]
mapheader = mergeheader.copy()
pixelsize = float(maphead0['PixelSpacing'][0]) / 10000
else:
if mdoc_item(idoctxt, 'MontSection = 0') == []: # older mdoc file format, created before SerialEM 3.7x
print('Warning - item' + mapitem[
'# Item'] + ': Series of tif images without montage information.'
' Assume pixel size is consistent for all sections.')
pixelsize = float(maphead0['PixelSpacing'][0]) / 10000 # in um
else:
mont_item = mdoc_item(idoctxt, 'MontSection = ' + str(mapsection))
pixelsize = float(mont_item['PixelSpacing'][0]) / 10000 # in um
for i in range(0, numpy.min([montage_tiles, stacksize])):
tilefile = mapfile[:mapfile.find('.idoc')] + '{:04d}'.format(mapsection + i) + '.tif'
im.append(tilefile)
tile = mdoc_item(idoctxt, 'Image = ' + os.path.basename(tilefile))
tilepos.append(tile['StagePosition'])
tilepx1.append(tile['PieceCoordinates'])
if 'AlignedPieceCoordsVS' in tile:
m['Sloppy'] = True
tilepx.append(tile['AlignedPieceCoordsVS'])
else:
tilepx.append(tile['AlignedPieceCoords'])
mergeheader['pixelsize'] = pixelsize
mapheader = mergeheader.copy()
mapheader['ysize'] = int(maphead0['ImageSize'][1])
mapheader['xsize'] = int(maphead0['ImageSize'][0])
imsz_x = int(maphead0['ImageSize'][0])
imsz_y = int(maphead0['ImageSize'][1])
#
# overlapx = imsz_x - mapheader['xsize']
# overlapy = imsz_y - mapheader['ysize']
# check if idoc is supported in IMOD (blendmont)
imod_vercheck = (imod_ver[0] >= 4 or (imod_ver[0] == 4 and imod_ver[1] >= 10))
if blendmont:
mergebase = mbase + '_merged' + '_s' + str(mapsection)
mergefile = mergebase + '.mrc'
if not os.path.exists(mergefile):
if imod_vercheck:
call_blendmont(mapfile, mergebase, mapsection)
merge_mrc = mrc.mmap(mergefile, permissive='True')
im = merge_mrc.data
mergeheader = map_header(merge_mrc)
else:
print('Please update IMOD to > 4.10.42 for merging idoc montages!')
mergeheader['xsize'] = int(tilepx[-1][0]) + mapheader['xsize']
mergeheader['ysize'] = int(tilepx[-1][1]) + mapheader['ysize']
mergefile = mapfile
else:
merge_mrc = mrc.mmap(mergefile, permissive='True')
im = merge_mrc.data
mergeheader = map_header(merge_mrc)
else:
mergeheader['xsize'] = int(tilepx[-1][0]) + mapheader['xsize']
mergeheader['ysize'] = int(tilepx[-1][1]) + mapheader['ysize']
mergefile = mapfile
else:
print('Warning: ' + mapfile + ' is not an MRC file!' + '\n')
print('Assuming it is a single tif file or a stitched montage.' + '\n')
mergefile = mapfile
pixelsize = 1. / numpy.sqrt(abs(numpy.linalg.det(mat)))
mergeheader['stacksize'] = 0
tilepos = mapitem['StageXYZ'][0:2]
tilepx = '0'
tilepx = numpy.array([[tilepx, tilepx, tilepx], [tilepx, tilepx, tilepx]])
tilepx1 = tilepx
m['Sloppy'] = 'NoMont'
im = io.imread(mergefile)
mergeheader['xsize'] = numpy.array(im.shape)[0]
mergeheader['ysize'] = numpy.array(im.shape)[1]
mapheader = mergeheader.copy()
mappxcenter = numpy.array([mergeheader['ysize'], mergeheader['xsize']]) / 2
else:
# map is mrc file
mf = mrc.mmap(mapfile, permissive='True')
mapheader = map_header(mf)
pixelsize = mapheader['pixelsize']
mergeheader = mapheader.copy()
# determine if file contains multiple montages stored in one MRC stack
mappxcenter = [mapheader['xsize'] / 2, mapheader['ysize'] / 2]
mdocname = mapfile + '.mdoc'
if m['frames'] == [0, 0]:
mapheader['stacksize'] = 0
tileidx_offset = 0
# tilepos = [0, 0]
if os.path.exists(mdocname):
mdoclines = loadtext(mdocname)
pixelsize = float(
mdoc_item(mdoclines, 'ZValue = ' + str(mapsection))['PixelSpacing'][0]) / 10000 # in um
# extract center positions of individual map tiles
if mapheader['stacksize'] > 1:
if os.path.exists(mdocname):
mdoclines = loadtext(mdocname)
if mapheader['stacksize'] > montage_tiles:
# multiple same-dimension montages in one MRC stack
tileidx_offset = mapsection * montage_tiles
elif mapheader['stacksize'] == montage_tiles:
# single montage without empty tiles (polygon)
tileidx_offset = 0
elif mapheader['stacksize'] < montage_tiles:
# polygon fit montage with empty tiles
tileidx_offset = 0
tilepos = list()