-
Notifications
You must be signed in to change notification settings - Fork 0
/
ucsftool.py
executable file
·1970 lines (1814 loc) · 73.3 KB
/
ucsftool.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
# -----------------------------------------------------------------------------
# UCSF tool
#
# -----------------------------------------------------------------------------
#
# Developed by Woonghee Lee
# e-mail: [email protected]
# Department of Chemistry, University of Colorado Denver
#
# Last updated: December 26, 2020
#
# This tool is to read, write and transform ucsf files
#
# Developed since July, 2018
#
# Python 3 Ported by Mehdi Rahimi
#
# -----------------------------------------------------------------------------
#
# e.g. Use help() function to see what this does
# import sys
# sys.path.append("/home/samic/Desktop/wlee_group/source/rahimi/ucsfTool")
# import ucsftool
# ut = ucsftool.ucsfTool()
# ut.help()
#
# e.g. Simple pseudo-3D split to multiple 2D example
# import ucsftool
# ut = ucsftool.ucsfTool()
# ut.ucsf_open('HNCACB.ucsf')
# ut.write_planes('relax')
#
# e.g. Make 2D projection
# import ucsftool
# ut = ucsftool.ucsfTool()
# ut.ucsf_open('my3d.ucsf')
# ut.write_projection('my2d.ucsf',dim=2)
# e.g. Automated peak picking
# import os, sys, ucsftool
# in_filename='C105A_2A_CBCACONH.ucsf'
# pre, ext = os.path.splitext(in_filename)
# out_filename= pre + '.list'
# ut = ucsftool.ucsfTool()
# ut.ucsf_open(in_filename)
# ut.auto_pick_peaks(out_filename)
#
#
# BSD 2-Clause License
#
# Copyright (c) 2020, Woonghee Lee ([email protected])
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from __future__ import print_function
import os, sys, struct
import itertools
import random
random.seed()
import time, datetime
import multiprocessing
import tempfile
tile_count_buffer = 256 # we will hold tile max 256 in memory (approx. 8mb)
#tile_count_buffer = 4096 # 128mb # we will hold tile max 512 in memory (approx. 16mb)
unpack_float = struct.Struct('>f').unpack
unpack_byte = struct.Struct('>B').unpack
unpack_int = struct.Struct('>I').unpack
pack_float = struct.Struct('>f').pack
OS_WINDOWS = False
if ((sys.platform == 'win32') or (sys.platform == 'cygwin')):
OS_WINDOWS = True
def print_log(*args):
msg = ''
for s in args:
try:
msg += str(s)
except:
msg += '! Could not convert to String'
f = open(os.path.join(tempfile.gettempdir(), 'process.log'), 'a')
f.write(msg + '\n')
f.close()
print(*args)
def interpolation(f1, f2, f3):
a0 = f1
a1 = -1.5 * f1 + 2.0 * f2 - 0.5 * f3
a2 = 0.5 * f1 - f2 + 0.5 * f3
if a2 == 0:
return 1., f2
x = -0.5 * a1 / a2
value = a2 * x * x + a1 * x + a0
return x, value
def lastabs(elem):
return abs(elem[-1])
def mean(data):
"""Return the sample arithmetic mean of data."""
n = len(data)
if n < 1:
raise ValueError('mean requires at least one data point')
return sum(data)/n # in Python 2 use sum(data)/float(n)
def _ss(data):
"""Return sum of square deviations of sequence data."""
c = mean(data)
ss = sum((x-c)**2 for x in data)
return ss
def stddev(data, ddof=0):
"""Calculates the population standard deviation
by default; specify ddof=1 to compute the sample
standard deviation."""
n = len(data)
if n < 2:
raise ValueError('variance requires at least two data points')
ss = _ss(data)
pvar = ss/(n-ddof)
return pvar**0.5
def get_memsize():
if OS_WINDOWS:
process = os.popen('wmic memorychip get capacity')
result = process.read()
process.close()
totalMem = 0
for m in result.split(" \r\n")[1:-1]:
totalMem += int(m)
elif sys.platform == 'darwin':
totalMem = int(os.popen('sysctl hw.memsize').read().split()[1])
else:
totalMem = int(os.popen('free -tb').readlines()[1].split()[3])
return totalMem
class ucsfTool:
# ---------------------------------------------------------------------------
# Creator
#
def __init__(self):
self.is_opened = 0
self.file_size = 0
self.nproc = 1
self.file_name = ''
self.file_object = None
self.file_header = self.dummy_file_header()
self.axis_header_list = []
self.tile_list = []
self.pixel_size = []
self.min_heights = None
self.cache_data = None
# ---------------------------------------------------------------------------
# Close file and init class
#
def ucsf_close(self):
if self.file_object != None:
for i in range(len(self.file_object)):
self.file_object[i].close()
self.file_object = None
self.file_size = 0
if self.min_heights != None:
self.min_heights = []
self.file_name = ''
self.file_header = self.dummy_file_header()
self.axis_header_list = []
self.tile_list = []
self.pixel_size = []
self.is_opened = 0
self.cache_data = None
# ---------------------------------------------------------------------------
# Destructor
#
def __del__(self):
self.ucsf_close()
# ---------------------------------------------------------------------------
# Help
#
def help(self):
print_log("""
ucsf_open(optional: filename)
ucsf_close()
dummy_file_header()
dummy_axis_header()
dummy_tile()
copy_file_header(template_file_header)
copy_axis_header(template_axis_header)
set_filename(filename)
get_filename()
read_file_header()
read_axis_header()
print_file_info()
calculate_pixel_size()
read_tile_data(tile_indices)
grid_to_tile_and_remain_indices(grid_pt)
optimize_tile_size(axis_header_list)
tile_and_remain_indices_to_grid(tile_pt, index_pt)
remain_indices_to_remain_index(indices)
shift_to_grid(shift, dim)
shifts_to_grids(shifts):
peaks_to_points(peaks):
grid_to_shift(grid, dim)
grids_to_shifts(grids):
points_to_peaks(points):
get_data(grid_pt)
get_data_by_shifts(shift_pt)
get_interpolated_data(grid_pt, noise_level=None)
get_interpolated_data_by_shifts(grid_pt)
get_interpolated_data_by_peaks(peaks)
sample_noise(sample_count=30)
filter_peaks_by_count(grid_peaks, heights, max_count)
filter_peaks_by_height(grid_peaks, heights, max_height)
is_local_maxima(grid_pt, grid_buffers, sign=1)
is_local_maxima_by_shifts(shift_pt, shift_buffers, sign=1)
find_peaks(noise_level, sign=1, shift_restraint = None)
find_fit_peaks(grid_pt, grid_buffers, sign=1, mode='gaussian')
find_fit_peaks_by_shifts(shift_pt, shift_buffers, sign=1, mode='gaussian')
auto_pick_peaks(out_filename=None, grid_buffers=None, sign=0, max_count=None,
noise_filter = 8., shift_restraint = None, write_peaks=True)
write_sparky_peaks(out_filename, peaks, heights=None)
write_transform(out_filename, transform_mode, transform_factor,
transform_factor2, overwrite=0)
write_projection(out_filename, proj_dim, proj_mode = 'avg', overwrite=0)
write_planes(out_prefix, dim=0, reverse=1, init=1, gap=1, overwrite=0)
write_swapped_axis(out_filename, dimension 1, dimension 2, overwrite=0)
write_shifted(out_filename, shift dimension, amount,
unit='ppm', overwrite=0)
write_ucsf_file_header(file_object, file_header)
write_ucsf_axis_header(file_object, axis_header)
write_concatenated (not yet implemented)
""")
# ---------------------------------------------------------------------------
# Init file header
#
def dummy_file_header(self):
file_header = {'FileType':'None',
'DimCount':0,
'DataCompCount':0,
'FileVersion':'None'}
return file_header
# ---------------------------------------------------------------------------
# Copy file header
#
def copy_file_header(self, template_file_header):
file_header = {'FileType': template_file_header['FileType'],
'DimCount': template_file_header['DimCount'],
'DataCompCount': template_file_header['DataCompCount'],
'FileVersion': template_file_header['FileVersion']}
return file_header
# ---------------------------------------------------------------------------
# Init axis header and return instance
#
def dummy_axis_header(self):
axis_header = {'AtomName':'None',
'DataPointCount':0,
'FillPointCount':0,
'TileSize':0,
'TileCount':0,
'SpecFreq':0.0,
'SpecWidth':0.0,
'Center':0.0,
'MarginalPoint':0,
'MarginalFreq':0.0,
'FreqMin':0.0,
'FreqMax':0.0}
return axis_header
# ---------------------------------------------------------------------------
# Copy axis header and return instance
#
def copy_axis_header(self, template_axis_header):
axis_header = {'AtomName': template_axis_header['AtomName'],
'DataPointCount': template_axis_header['DataPointCount'],
'FillPointCount': template_axis_header['FillPointCount'],
'TileSize': template_axis_header['TileSize'],
'TileCount': template_axis_header['TileCount'],
'SpecFreq': template_axis_header['SpecFreq'],
'SpecWidth': template_axis_header['SpecWidth'],
'Center': template_axis_header['Center'],
'MarginalPoint': template_axis_header['MarginalPoint'],
'MarginalFreq': template_axis_header['MarginalFreq'],
'FreqMin': template_axis_header['FreqMin'],
'FreqMax': template_axis_header['FreqMax'],}
return axis_header
# ---------------------------------------------------------------------------
# Init tile data and return instance
#
def dummy_tile(self):
tile_data = {'TilePos': (),
'Values': ()}
return tile_data
# ---------------------------------------------------------------------------
# Set ucsf file name to access
#
def set_filename(self, file_name):
if self.is_opened == 1:
print_log('Error in ucsfTool:set_filename()- file name is already assigned')
return 0
self.file_name = file_name
return 1
# ---------------------------------------------------------------------------
# Get ucsf file name set previously
#
def get_filename(self):
return self.file_name
# ---------------------------------------------------------------------------
# open ucsf instances and read header and check validity
#
def ucsf_open(self, in_filename=None, nproc=1, cache_mode=True):
if self.is_opened == 1:
print_log('Error in ucsfTool:ucsf_open()- file is already opened')
return 0
if in_filename != None:
self.set_filename(in_filename)
if not os.path.exists(self.file_name):
print_log('Error in ucsfTool:ucsf_open()- file(%s) does not exist' \
% (self.file_name))
return 0
if OS_WINDOWS:
self.file_object = map(lambda x: open(self.file_name, 'rb'), range(nproc))
else:
self.file_object = map(lambda x: open(self.file_name, 'rb', os.O_NONBLOCK), range(nproc))
self.file_object[0].seek(0, 2) # seek_end
self.file_size = self.file_object[0].tell()
if self.file_size < 180 + 128*2: # 180: file header, 128: axis header
print_log('Error in ucsfTool:ucsf_open()- file size too small (%d)' \
% (self.file_size))
self.ucsf_close()
return 0
self.min_heights = map(lambda x: 10**10, range(nproc))
self.is_opened = 1
if self.read_file_header() == 0:
self.ucsf_close()
return 0
self.fd_divider = None
self.nproc = nproc
if self.read_axis_header() == 0:
self.ucsf_close()
return 0
self.ndim = len(self.axis_header_list)
self.calculate_pixel_size()
self.init_pos = 180 + 128 * self.ndim
self.tile_list = map(lambda x: [], range(nproc))
self.cube_size = 1 # cube, tile, or 4D cube whatever the size is...
for i in range(self.ndim):
self.cube_size *= self.axis_header_list[i]['TileSize']
self.cube_float_size = self.cube_size * 4 # cube size in float point size
self.unpack_cube_float = struct.Struct('>%df' % (self.cube_size)).unpack
# If memory is enough, load all the data first.
# This will be significantly fast when multiprocessing is activated
try:
free_mem = get_memsize()
print('Memory check %d.' % (free_mem))
if self.file_size * 3 < free_mem and cache_mode:
self.file_object[0].seek(0, 0)
self.cache_data = bytes(self.file_object[0].read())
except:
print('Memory check failed.')
# read a whole thing if lower than 1GB
if self.file_size < 1024**3 and cache_mode:
self.file_object[0].seek(0, 0)
self.cache_data = bytes(self.file_object[0].read())
pass
# ---------------------------------------------------------------------------
# Read file header
#
def read_file_header(self):
if self.is_opened == 0:
print_log('Error in ucsfTool:read_file_header()- file is not opened')
return 0
self.file_object[0].seek(0)
temp = self.file_object[0].read(16)
if temp[0:8] != 'UCSF NMR':
print_log('Error in ucsfTool:read_file_header()- UCSF NMR tag not found')
return 0
self.file_header['FileType'] = temp[0:8]
try:
self.file_header['DimCount'] = unpack_byte(temp[10])[0]
except:
print_log('Error in ucsfTool:read_file_header()- dimension is incorrect')
return 0
try:
self.file_header['DataCompCount'] = unpack_byte(temp[11])[0]
except:
print_log('Error in ucsfTool:read_file_header()- data component is incorrect')
return 0
try:
self.file_header['FileVersion'] = unpack_byte(temp[13])[0]
except:
print_log('Error in ucsfTool:read_file_header()- file version is incorrect')
return 0
return 1
# ---------------------------------------------------------------------------
# Read axis header
#
def read_axis_header(self):
if self.is_opened == 0:
print_log('Error in ucsfTool:read_axis_header()- file is not opened')
return 0
try:
self.axis_header_list = []
self.file_object[0].seek(180)
for i in range(self.file_header['DimCount']):
dah = self.dummy_axis_header()
temp = self.file_object[0].read(128)
nuc = struct.unpack('6s',temp[0:6])[0]
dah['AtomName'] = nuc.replace('\x00', '')
dah['DataPointCount'] = unpack_int(temp[8:12])[0]
dah['TileSize'] = unpack_int(temp[16:20])[0]
dah['TileCount'] = dah['DataPointCount'] / dah['TileSize']
if dah['DataPointCount'] % dah['TileSize'] != 0:
dah['TileCount'] = dah['TileCount'] + 1
dah['FillPointCount'] = dah['TileSize'] * dah['TileCount']
dah['SpecFreq'] = unpack_float(temp[20:24])[0]
dah['SpecWidth'] = unpack_float(temp[24:28])[0]
dah['Center'] = unpack_float(temp[28:32])[0]
dah['MarginalPoint'] = dah['TileSize'] * dah['TileCount'] \
- dah['DataPointCount']
dah['MarginalFreq'] = float(dah['MarginalPoint']) \
/ float(dah['DataPointCount']) \
* dah['SpecWidth'] / dah['SpecFreq']
dah['FreqMin'] = dah['Center'] - dah['SpecWidth'] \
/ dah['SpecFreq'] / 2.0
dah['FreqMax'] = dah['Center'] + dah['SpecWidth'] \
/ dah['SpecFreq'] / 2.0
self.axis_header_list.append(dah)
# convert to tuple for performance
self.axis_header_list = tuple(self.axis_header_list)
#self.fd_divider = int(float(self.axis_header_list[0]['DataPointCount']) / \
# float(self.nproc))+1
self.fd_divider = float(self.axis_header_list[0]['DataPointCount']) / \
float(self.nproc)
if self.nproc != 1:
print_log('X axis data points: %d' % \
(self.axis_header_list[0]['DataPointCount']))
#print 'fd_divider set to: %d' % (self.fd_divider)
print_log('fd_divider set to: %f' % (self.fd_divider))
fd = []
for i in range(self.nproc):
fd.append([i, list(range(int(self.fd_divider * i),
int(self.fd_divider * (i+1))))])
self.fd_dict = dict(fd)
except:
msg = 'Error in ucsfTool:read_axis_header()- processing dimension '
msg = msg + '%d failed' % (i+1)
print_log(msg)
return 0
# make tuples for performance
self.tile_count = ()
self.data_point_count = ()
self.tile_size = ()
self.fill_point_count = ()
for i in range(self.file_header['DimCount']):
self.data_point_count += (self.axis_header_list[i]['DataPointCount'],)
self.tile_size += (self.axis_header_list[i]['TileSize'],)
self.tile_count += (self.axis_header_list[i]['TileCount'],)
self.fill_point_count += (self.axis_header_list[i]['FillPointCount'],)
return 1
# ---------------------------------------------------------------------------
# Print file information
#
def print_file_info(self):
if self.is_opened == 0:
print_log('Error in ucsfTool:read_axis_header()- file is not opened')
return 0
ahl = self.axis_header_list
line = '%-20s' % ('axis')
for i in range(self.ndim):
ah = ahl[i]
line = line + '%11s%d' % ('w',i+1)
print_log(line)
line = '%-20s' % ('nucleus')
for ah in ahl:
line = line + '%12s' % (ah['AtomName'])
print_log(line)
for col, head in [['matrix size', 'DataPointCount'],
['block size', 'TileSize']]:
line = '%-20s' % (col)
for ah in ahl:
line = line + '%12d' % (ah[head])
print_log(line)
for col, head in [['upfield ppm', 'FreqMin'],
['downfield ppm', 'FreqMax'],
['spectrum frequency','SpecFreq'],
['spectrum width', 'SpecWidth']]:
line = '%-20s' % (col)
for ah in ahl:
line = line + '%12.3f' % (ah[head])
print_log(line)
# ---------------------------------------------------------------------------
# show the raw header data
#
def get_raw_header(self):
if self.is_opened == 0:
print_log('Error in ucsfTool:read_axis_header()- file is not opened')
return 0
print_log(self.axis_header_list)
# ---------------------------------------------------------------------------
# dump all data points
#
def dump_data_2d(self):
if self.is_opened == 0:
print_log('Error in ucsfTool:read_axis_header()- file is not opened')
return 0
ahl = self.axis_header_list
x = ahl[0]['DataPointCount']
y = ahl[1]['DataPointCount']
for i in range(x):
for j in range(y - 1):
#print_log('{},'.format(self.get_data([i, j])), end='')
print_log('{},'.format(self.get_data([i, j]))),
print_log(self.get_data([i, j + 1]))
# ---------------------------------------------------------------------------
# Calculate pixel size for a grid
def calculate_pixel_size(self):
if self.is_opened == 0:
print_log('Error in ucsfTool:calculate_pixel_size()- file is not opened')
return None
self.pixel_size = ()
for i in range(self.ndim):
self.pixel_size += (self.axis_header_list[i]['SpecWidth'] \
/ self.axis_header_list[i]['DataPointCount'] \
/ self.axis_header_list[i]['SpecFreq'], )
# ---------------------------------------------------------------------------
# Get Tile Block
#
def read_tile_data(self, tile_indices, fd=0):
# browse tile list if already read in the memory
for i in range(len(self.tile_list[fd])):
if self.tile_list[fd][i]['TilePos'] == tile_indices:
# move this tile to the top priority
if i != 0:
self.tile_list[fd].insert(0, self.tile_list[fd].pop(i))
return self.tile_list[fd][0]
# start finding block position for the tile_indices
sum_size = 0
for i in range(self.ndim):
mult_size = tile_indices[i]
for j in range(i+1, self.ndim):
mult_size *= self.tile_count[j]
sum_size += mult_size
tile_pos = self.init_pos + self.cube_float_size * sum_size
# read by tile
# could not find. read from file
dt = self.dummy_tile()
dt['TilePos'] = tile_indices
dt['Values'] = [0] * self.cube_size
# not outlier
if tile_pos + self.cube_float_size < self.file_size+1 and tile_pos > 0:
if self.cache_data == None:
self.file_object[fd].seek(tile_pos, 0)
temp = self.file_object[fd].read(self.cube_float_size)
else:
temp = self.cache_data[tile_pos:tile_pos+self.cube_float_size]
dt['Values'] = self.unpack_cube_float(temp)
dt['Values'] = tuple(dt['Values'])
#dt['Values'] = tuple(self.unpack_cube_float(temp))
# make this tile top priority
self.tile_list[fd].insert(0, dt)
# if buffer overflowing, remove last one.
if len(self.tile_list[fd]) > tile_count_buffer:
self.tile_list[fd].pop(tile_count_buffer)
return dt
# ---------------------------------------------------------------------------
# Grid to Tile and Index
#
def grid_to_tile_and_remain_indices(self, grid_pt):
if self.is_opened == 0:
print_log('Error in ucsfTool:grid_to_tile_and_indices()- file is not opened')
return None
tile_pt = ()
remain_pt = ()
for i in range(self.ndim):
tile_pt += (grid_pt[i] / self.axis_header_list[i]['TileSize'],)
remain_pt += (grid_pt[i] % self.axis_header_list[i]['TileSize'],)
return (tile_pt, remain_pt)
# ---------------------------------------------------------------------------
# Optimize tile size
#
def optimize_tile_size(self, axis_header_list):
for i in range(self.ndim):
axis_header_list[i]['TileSize'] = axis_header_list[i]['DataPointCount'] \
/ 2 # initial starting size
# estimate new tile size
while True:
# current size?
temp_size = 4
max_dim = 0
max_tilesize = 0
for i in range(self.ndim):
ts = axis_header_list[i]['TileSize']
if ts > max_tilesize:
ts = max_tilesize
max_dim = i
temp_size = temp_size * ts
# check if temp_size <= 32kb
if temp_size < 32*1024: break
# reduce the largest dimension
axis_header_list[max_dim]['TileSize'] \
= axis_header_list[max_dim]['TileSize'] / 2
# readjust TileCount, FillPointCount, and write axis header
for i in range(self.ndim):
ts = axis_header_list[i]['TileSize']
axis_header_list[i]['TileCount'] \
= axis_header_list[i]['DataPointCount'] / ts
if axis_header_list[i]['DataPointCount'] % ts != 0:
axis_header_list[i]['TileCount'] = axis_header_list[i]['TileCount'] + 1
axis_header_list[i]['FillPointCount'] = ts \
* axis_header_list[i]['TileCount']
# ---------------------------------------------------------------------------
# Tile and Index to Grid
#
def tile_and_remain_indices_to_grid(self, tile_pt, index_pt):
if self.is_opened == 0:
print_log('Error in ucsfTool:tile_and_indices_to_grid()- file is not opened')
return None
grid_pt = []
for i in range(self.ndim):
grid_pt.append(tile_pt[i] * self.axis_header_list[i]['TileSize'] \
+ index_pt[i])
return grid_pt
# ---------------------------------------------------------------------------
# Remain indices to remain index
#
def remain_indices_to_remain_index(self, indices):
if self.is_opened == 0:
msg = 'Error in ucsfTool:remain_indices_to_remain_index()- '
msg = msg + 'file is not opened'
print_log(msg)
return None
sum_size = 0
for i in range(self.ndim):
mult_size = indices[i]
for j in range(i+1, self.ndim):
mult_size *= self.axis_header_list[j]['TileSize']
sum_size += mult_size
return sum_size
# ---------------------------------------------------------------------------
# Shift to grid
#
def shift_to_grid(self, shift, dim):
ah = self.axis_header_list[dim-1]
temp = ah['SpecWidth'] / float(ah['DataPointCount']) / ah['SpecFreq']
temp2 = ah['Center'] + (ah['SpecWidth'] / ah['SpecFreq'] / 2.0)
return int((temp2 - shift) / temp + 0.5)
# all dimension
def shifts_to_grids(self, shifts):
grid_list = []
for i in range(self.ndim):
grid_list.append(self.shift_to_grid(shifts[i], i+1))
return grid_list
# multiple peaks
def peaks_to_points(self, peaks):
point_list = []
for i in range(len(peaks)):
point_list.append(self.shifts_to_grids(peaks[i]))
return point_list
# ---------------------------------------------------------------------------
# Grid to shift
#
def grid_to_shift(self, grid, dim):
ah = self.axis_header_list[dim-1]
temp = ah['SpecWidth'] / float(ah['DataPointCount']) / ah['SpecFreq']
temp2 = ah['Center'] + (ah['SpecWidth'] / ah['SpecFreq'] / 2.0)
return temp2 - temp * float(grid)
def grids_to_shifts(self, grids):
shift_list = ()
for i in range(self.ndim):
shift_list += (self.grid_to_shift(grids[i], i+1), )
return shift_list
def points_to_peaks(self, points):
peak_list = ()
for i in range(len(points)):
peak_list += (self.grids_to_shifts(points[i]),)
return peak_list
# ---------------------------------------------------------------------------
# Get File Descripter by Grid Points
#
def get_fdidx(self, grid_idx):
for i in range(self.nproc):
if grid_idx in self.fd_dict[i]:
return i
return None
# ---------------------------------------------------------------------------
# Get Data Value by Grid Points
#
def get_data(self, grid_pt):
if self.is_opened == 0:
print_log('Error in ucsfTool:get_data()- file is not opened')
return None
tile_indices, remain_pt = self.grid_to_tile_and_remain_indices(grid_pt)
#fdidx = self.get_fdidx(grid_pt[0])
#if fdidx == None:
# return 0.
fdidx = min(int(float(grid_pt[0]) / self.fd_divider), self.nproc-1)
remain_index = self.remain_indices_to_remain_index(remain_pt)
#if self.cache_data == None:
tile_data = self.read_tile_data(tile_indices, fd=fdidx)
hts = tile_data['Values'][remain_index]
#else:
# return self.get_point_data(tile_indices, remain_index)
return hts
# ---------------------------------------------------------------------------
def get_point_data(self, tile_indices, remain_index):
sum_size = 0
for i in range(self.ndim):
mult_size = tile_indices[i]
for j in range(i+1, self.ndim):
mult_size *= self.tile_count[j]
sum_size += mult_size
tile_pos = self.init_pos + self.cube_float_size * sum_size
grid_pos = tile_pos + remain_index * 4
try:
temp = float(self.cache_data[grid_pos:grid_pos + 4])
temp = unpack_float(self.cache_data[grid_pos:grid_pos + 4])[0]
except:
return 0
return temp
# ---------------------------------------------------------------------------
# Get Data Value by Shifts
#
def get_data_by_shifts(self, shift_pt):
if self.is_opened == 0:
print_log('Error in ucsfTool:get_data_shifts()- file is not opened')
return None
# shifts to grids
grid_pt = ()
for i in range(len(shift_pt)):
grid_pt += (self.shift_to_grid(shift_pt[i], i+1), )
return self.get_data(grid_pt)
# ---------------------------------------------------------------------------
# Get Interpolated Shift Position and Data Value by Grid Points
#
def get_interpolated_data(self, grid_pt, noise_level=None):
if self.is_opened == 0:
print_log('Error in ucsfTool:get_interpolated_data()- file is not opened')
return None, None
shifts = [0.0] * len(grid_pt)
d2 = self.get_data(grid_pt)
if noise_level:
if abs(d2) < abs(noise_level):
return None, None
#print(d2)
for i in range(len(grid_pt)):
prev_grid_pt = list(grid_pt)
next_grid_pt = list(grid_pt)
prev_grid_pt[i] = grid_pt[i]-1
next_grid_pt[i] = grid_pt[i]+1
d1 = self.get_data(prev_grid_pt)
d3 = self.get_data(next_grid_pt)
#print(d1, d2, d3)
pos, value = interpolation(d1, d2, d3)
if pos < 0 or pos > 2: # extrapolated- use just middle
pos = 1.
value = d2
shifts[i] = self.grid_to_shift(grid_pt[i]+pos-1.0, i+1)
return shifts, value
# ---------------------------------------------------------------------------
# Get Interpolated Shift Position and Data Value by Shifts
#
def get_interpolated_data_by_shifts(self, shift_pt):
if self.is_opened == 0:
msg = 'Error in ucsfTool:get_interpolated_data_by_shifts()- '
msg = msg + 'file is not opened'
print_log(msg)
return None
# shifts to grids
grid_pt = []
for i in range(len(shift_pt)):
grid_pt.append(self.shift_to_grid(shift_pt[i], i+1))
return self.get_interpolated_data(grid_pt)
# ---------------------------------------------------------------------------
# Interpolation for peaks
def get_interpolated_data_by_peaks(self, peaks):
adj_peaks, adj_hts = [], []
for i in range(len(peaks)):
interpolated = self.get_interpolated_data_by_shifts(peaks[i])
adj_peaks.append(interpolated[0])
adj_hts.append(interpolated[1])
return adj_peaks, adj_hts
# ---------------------------------------------------------------------------
# Take the median value of randomly sampled data absolute values.
#
def sample_noise(self, sample_count=30):
ahl = self.axis_header_list
ht_list = []
for i in range(sample_count):
grid_pt = []
for j in range(len(ahl)):
grid_pt.append(random.randrange(0, ahl[j]['DataPointCount']))
ht_list.append(abs(self.get_data(grid_pt)))
sorted_ht_list = sorted(ht_list)
return sorted_ht_list[sample_count/2]
# ---------------------------------------------------------------------------
# Check if this grid is the maximum
#
def is_local_maxima(self, grid_pt, grid_buffers, sign = 1, ref_ht = None,
simple=True):
if ref_ht == None: std_ht = self.get_data(grid_pt)
else: std_ht = ref_ht
if std_ht * sign < 0:
return False, std_ht
astd_ht = abs(std_ht)
ndim = len(grid_pt)
if not simple:
if ndim == 2:
it = itertools.product(range(grid_pt[0]-grid_buffers[0],
grid_pt[0]+grid_buffers[0]+1),
range(grid_pt[1]-grid_buffers[1],
grid_pt[1]+grid_buffers[1]+1))
elif ndim == 3:
it = itertools.product(range(grid_pt[0]-grid_buffers[0],
grid_pt[0]+grid_buffers[0]+1),
range(grid_pt[1]-grid_buffers[1],
grid_pt[1]+grid_buffers[1]+1),
range(grid_pt[2]-grid_buffers[2],
grid_pt[2]+grid_buffers[2]+1))
elif ndim == 4:
it = itertools.product(range(grid_pt[0]-grid_buffers[0],
grid_pt[0]+grid_buffers[0]+1),
range(grid_pt[1]-grid_buffers[1],
grid_pt[1]+grid_buffers[1]+1),
range(grid_pt[2]-grid_buffers[2],
grid_pt[2]+grid_buffers[2]+1),
range(grid_pt[3]-grid_buffers[3],
grid_pt[3]+grid_buffers[3]+1))
pt_list = tuple(it)
else:
pt = list(grid_pt)
for i in range(ndim):
for j in range(1, grid_buffers[i] + 1):
pt[i] = grid_pt[i] - j
temp_ht = self.get_data(pt)
if (temp_ht > std_ht and sign == 1) or (temp_ht < std_ht and sign == -1) \
or (abs(temp_ht) > astd_ht and sign == 0) or temp_ht == 0.0:
return False, std_ht
pt[i] = grid_pt[i] + j
temp_ht = self.get_data(pt)
if (temp_ht > std_ht and sign == 1) or (temp_ht < std_ht and sign == -1) \
or (abs(temp_ht) > astd_ht and sign == 0) or temp_ht == 0.0:
return False, std_ht
pt[i] = grid_pt[i]
return True, std_ht
for pt in pt_list:
if grid_pt == pt: continue
temp_ht = self.get_data(pt)
if (temp_ht > std_ht and sign == 1) or (temp_ht < std_ht and sign == -1) \
or (abs(temp_ht) > astd_ht and sign == 0):
return False, std_ht
return True, std_ht
# ---------------------------------------------------------------------------
# Check if this shift is the maximum
#
def is_local_maxima_by_shifts(self, shift_pt, shift_buffers, sign = 1,
ref_ht = None):
grid_pt = []
grid_buffers = []
for i in range(len(shift_buffers)):
grid_buffers.append(shift_buffers[i] / self.pixel_size[i] + 1)
grid_pt.append(self.shift_to_grid(shift_pt[i], i+1))
return self.is_local_maxima(grid_pt, grid_buffers, sign, ref_ht)
# ---------------------------------------------------------------------------
#
# Use slope to cut the value
def filter_peaks_by_slope(self, grid_peaks, heights, min_slope):
pass
def filter_peaks_by_sign_ratio(self, grid_peaks, heights, min_ratio):
pass
def filter_peaks_by_height(self, grid_peaks, heights, max_height):
peaks2, heights2 = [], []
for i in range(len(grid_peaks)):
hts = heights[i]
if abs(hts) >= abs(max_height):
peaks2.append(grid_peaks[i])
heights2.append(hts)
return peaks2, heights2
def filter_peaks_by_count(self, grid_peaks, heights, max_count):
temp_list = []
for i in range(len(grid_peaks)):
temp_list.append([grid_peaks[i], heights[i]])
temp_list.sort(key=lastabs, reverse = True)
grid_peaks2, heights2 = [], []
for i in range(min(max_count, len(temp_list))):
peak = temp_list[i][0]
hts = temp_list[i][1]
grid_peaks2.append(peak)
heights2.append(hts)
return grid_peaks2, heights2
# ---------------------------------------------------------------------------
# change user shift restraint to grid restraint
# [[125.6,130.4,..],[7.4,7.8,...],[]]
def shift_restraint_to_grid_restraint(self, shift_restraint, shift_grid_buffers):
if shift_restraint == None: return None
ahl = self.axis_header_list
grid_restraint = []
for i in range(len(ahl)):
grid_restraint.append(list(map(lambda x: x,
range(ahl[i]['DataPointCount']))))
if shift_restraint == None:
return grid_restraint
for i in range(len(ahl)):
if i >= len(shift_restraint): break
shift_list = shift_restraint[i]
if len(shift_list) == 0: continue
grid_restraint[i] = []
for shift in shift_list:
idx = self.shift_to_grid(shift, i+1)
for j in range(idx-shift_grid_buffers[i], idx+shift_grid_buffers[i]+1):
grid_restraint[i].append(j)
grid_restraint[i] = list(set(grid_restraint[i]))
return grid_restraint
# ---------------------------------------------------------------------------
# Find peaks in entire spectrum
def find_peaks(self, noise_level, grid_buffers, sign=1,
shift_restraint=None, shift_grid_buffers=None,
max_count=None, verbose=True):
ahl = self.axis_header_list
if shift_grid_buffers == None: shift_grid_buffers = grid_buffers
grid_restraint = self.shift_restraint_to_grid_restraint(shift_restraint,
shift_grid_buffers)
range_list = []
if grid_restraint != None:
for i in range(grid_restraint):
if len(grid_restraint[i]) != 0: