-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCorMapAnalysis.py
More file actions
executable file
·1663 lines (1473 loc) · 75.8 KB
/
CorMapAnalysis.py
File metadata and controls
executable file
·1663 lines (1473 loc) · 75.8 KB
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
"""CorMap class implementing analyis of results from the ATSAS suite program
DATCMP.
"""
import glob
import subprocess
import re
import os
import shutil
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import pandas as pd
import seaborn as sns
class ScatterAnalysis(object):
"""
Scatter curve similarity analysis class.
CorMap class implementing analysis of data output from a run of the
ATSAS suite program DATCMP.
"""
# ----------------------------------------------------------------------- #
# CLASS VARIABLES #
# ----------------------------------------------------------------------- #
PLOT_LABEL = {'family': 'serif',
'weight': 'normal',
'size': 16}
mpl.rc('font', family='serif', weight='normal', size=12)
PLOT_NUM = 0
# ----------------------------------------------------------------------- #
# CONSTRUCTOR METHOD #
# ----------------------------------------------------------------------- #
def __init__(self, intensities, scattering_angles, datcmp_data,
x_axis_vec=[], x_metric="", x_units=""):
"""
Create a ScatterAnalysis object.
Constructor method to create ScatterAnalysis object which exposes a
simple API for analysing the DATCMP data.
Parameters
----------
intensities : 2D numpy array
Array of intensity values where each column represents the
intensity values for a single frame and each row represents the
intensity at a particular scattering angle.
scattering_angles : 1D numpy array
Array of scattering angles measured for the SAXS run.
datcmp_data : dictionary
dictionary containing all of the data from the DATCMP output. The
key type is a string of image pairs and the value type is a list of
the pairwise correlation results from the analysis between the
image pairs.
x_axis_vec : numpy array, optional (default=[])
Vector of values to use on the x-axis of plots. This can be things
like dose values for example. If not specified then frame number is
used as a default.
x_metric : str, optional (default="")
String specifying the type of metric used for the x-axis. An
example would be "Dose". If not specified then the default metric
used on the x-axis is "Frame Number"
x_units : str, optional (default="")
String specifying the units used for the x-axis metric. For example
if the x-axis metric was the 'dose', then x_units may be specified
as "kGy".
"""
self.I = intensities
self.q = scattering_angles
self.datcmp_data = datcmp_data
self.x_axis = x_axis_vec
self.x_metric = x_metric
self.x_units = x_units
# ----------------------------------------------------------------------- #
# CLASS METHODS #
# ----------------------------------------------------------------------- #
# Note that class methods can access class attributes but not instance
# attributes.
@classmethod
def from_1d_curves(cls, scat_curve_location, x_axis_vec=[], metric="",
units="", first=-1, last=-1, smin=-1, smax=-1):
"""
Create a ScatterAnalysis object from .
Method to create ScatterAnalysis object from a set of 1D scattering
curve files.
Parameters
----------
scattering_curve_location : str
Location of the scattering curves for the dataset.
x_axis : numpy array, optional (default=[])
Vector of values to use on the x-axis of plots. This can be things
like dose values for example. If not specified then frame number is
used as a default.
x_metric : str, optional (default="")
String specifying the type of metric used for the x-axis. An
example would be "Dose". If not specified then the default metric
used on the x-axis is "Frame Number"
x_units : str, optional (default="")
String specifying the units used for the x-axis metric. For example
if the x-axis metric was the 'dose', then x_units may be specified
as "kGy".
first : int, optional (default=-1)
Index of the first point to be kept. This is mutually exclusive
with argument parameter 'smin'. Default value is -1. This will
ultimately result in the method not using this value.
last : int, optional (default=-1)
Index of the last point to be kept. This is mutually exclusive with
argument parameter 'smax'. Default value is -1. This will
ultimately result in the method not using this value.
smin : float, optional (Default=-1)
Minimal scattering angle value to be kept. This is mutually
exclusive with argument parameter 'first'. Default value is -1.
This will ultimately result in the method not using this value.
smax : float, optional (Default=-1)
Maximal scattering angle value to be kept. This is mutually
exclusive with argument parameter 'last'. Default value is -1.
This will ultimately result in the method not using this value.
Returns
-------
ScatterAnalysis
The ScatterAnalysis object
Examples
--------
To create a ScatterAnalysis object that will plot only against frame
numbers then the only input required is the location of the set of
files:
>>> scat_obj = ScatterAnalysis.from_1d_curves("saxs_files.00*.dat")
If you want to plot an x-axis that is different from the frame number,
e.g. the dose, then we would specify something like:
>>> scat_obj = ScatterAnalysis.from_1d_curves("saxs_files.00*.dat", np.array([10, 20, 30, 40]), "Dose", "kGy")
If you don't want to compare the entire range of the SAXS curve (this
may be the case where there are sections of the 1D curves that are
noisy) then there is the option to crop the curves before running the
CorMap test to create the ScatterAnalysis object.
In the example below we create a ScatterAnalysis object where we crop
the first 99 frames and use data up to a scattering angle of 3 nm^{-1}.
>>> scat_obj = ScatterAnalysis.from_1d_curves("saxs_files.00*.dat", first=99, smax=3.0)
Note
----
The x_axis_vec array needs to be the same length as the total number of
frames in the dataset otherwise the frame number will be used on the
x-axis by default
"""
# Go through files and extract the frame data.
file_list = glob.glob(scat_curve_location)
file_list = sorted(file_list)
#print(file_list)
num_frames = len(file_list)
# Decide whether the frames need to be cropped first.
if (first < 0) and (last < 0) and (smin < 0) and (smax < 0):
# Run DATCMP to get pairwise comparison information.
datcmp_data = ScatterAnalysis.get_datcmp_info(scat_curve_location)
scattering_angles = parse_saxs_dat_file(file_list[0], "scattering angle")
intensities = np.zeros([len(scattering_angles), num_frames])
num_data_points_per_curve = len(scattering_angles)
print("Number of data points on resulting scattering profile: {}".format(num_data_points_per_curve))
for i, file in enumerate(file_list):
intensities[:, i] = parse_saxs_dat_file(file, "intensity", num_data_points_per_curve)
else:
if last > 0 and smax > 0:
print("**************** WARNING ******************")
print("Both 'last' and 'smax' are defined but they are mutually exclusive.")
print("Only 'last' is being used!!!")
if first > 0 and smin > 0:
print("**************** WARNING ******************")
print("Both 'first' and 'smin' are defined but they are mutually exclusive.")
print("Only 'first' is being used!!!")
temp_dir_name = "Temp_dir"
temp_file_prefix = "temp"
os.mkdir(temp_dir_name)
crop_saxs_files(file_list, temp_dir_name, temp_file_prefix, first, last, smin, smax)
# Run DATCMP to get pairwise comparison information.
new_scat_curve_location = "{}/{}*".format(temp_dir_name,
temp_file_prefix)
new_file_list = glob.glob(new_scat_curve_location)
print("Number of files = {}".format(len(new_file_list)))
datcmp_data = ScatterAnalysis.get_datcmp_info(new_scat_curve_location)
scattering_angles = parse_saxs_dat_file(new_file_list[0],
"scattering angle")
num_data_points_per_curve = len(scattering_angles)
print("Number of data points on resulting scattering profile: {}".format(num_data_points_per_curve))
intensities = np.zeros([num_data_points_per_curve,
len(new_file_list)])
for i, filename in enumerate(new_file_list):
intensities[:, i] = parse_saxs_dat_file(filename, "intensity", num_data_points_per_curve)
# Remove temporary directory if it still exists
if os.path.exists(temp_dir_name):
shutil.rmtree(temp_dir_name)
# Organise the x-axis used for the plots. Default will be the frame
# number.
if not isinstance(x_axis_vec, list):
if len(x_axis_vec) == num_frames:
x_axis = x_axis_vec
else:
print("x_axis_vec is not the same length as the number of")
print("frames. Using frame numbers instead.")
x_axis = np.linspace(1, num_frames, num_frames)
else:
x_axis = np.linspace(1, num_frames, num_frames)
if metric and units:
x_metric = metric
x_units = units
else:
x_metric = "Frame number"
x_units = ""
return cls(intensities, scattering_angles, datcmp_data, x_axis,
x_metric, x_units)
@classmethod
def get_datcmp_info(self, scattering_curve_files):
"""
Extract the data produced by DATCMP.
This method is used by the constructor method of the ScatterAnalysis
class. It runs the DATCMP program on the dataset and returns a
dictionary containing the main results from the DATCMP run.
Parameters
----------
scattering_curve_files : str
Location of the scattering curves for the dataset.
Returns
-------
dict(str, numpy.array)
Dictionary containing the results of the DATCMP run. The dictionary
key is a string (with no spaces) denoting the pair of frames that
were compared e.g. "1,2" would be frames 1 and 2. The dictionary
value is an array of DATCMP results for the corresponding pairwise
comparison.
Examples
--------
>>> datcmp_data = scat_obj.get_datcmp_info("saxs_files.00*.dat")
"""
cmd = "datcmp {}".format(scattering_curve_files)
log = run_system_command(cmd)
#log = run_system_command(cmd)
all_lines = log.splitlines()
all_lines_str = []
for this_line in all_lines:
all_lines_str.append(this_line.decode("utf-8"))
#print(len(str(log.splitlines())))
# define a dictionary to store the data produced from DATCMP - this
# value will be overwritten.
data_dict = {"1,2": 0}
for i, line in enumerate(all_lines_str):
match_obj = re.match(r'\s* \d{1,} vs', line)
if match_obj:
data = line.split()
if "*" in data[5]:
data[5] = data[5][:-1]
data_dict["{},{}".format(data[0], data[2])] = [int(float(data[3])),
float(data[4]),
float(data[5])]
#print(data_dict)
return data_dict
# ----------------------------------------------------------------------- #
# INSTANCE METHODS #
# ----------------------------------------------------------------------- #
def find_diff_frames(self, frame=1, P_threshold=0.01, P_type="adjP"):
"""
List all statistically dissimilar frames.
This method finds all statistically dissimilar frames to any given
frame using the CorMap test as outlined in Daniel Franke, Cy M Jeffries
& Dmitri I Svergun (2015). The user can set the significance threshold
as well as whether to use the Bonferroni corrected P values or not.
(we recommend that you should use the Bonferroni corrected P values).
Parameters
----------
frame : int, optional (default=1)
The frame that every other frame in the dataset is compared with.
If not specified then all frames are compared to the first frame.
P_threshold : float, optional (default=0.01)
The significance threshold of the test. If it's not given then the
default value is 1%.
P_type : str, optional (default="adjP")
String denoting whether to use the Bonferroni corrected P value
(input string="adjP") or the ordinary P value (input string="P").
Default is to use the Bonferroni corrected P value.
Returns
-------
List
A list of integers corresponding to all of the dissimilar frames
Examples
--------
Find all frames that are dissimilar to frame 10
>>> diff_frames = scat_obj.find_diff_frames(frame=10)
"""
if P_type == "adjP":
p_col = 2
elif P_type == "P":
p_col = 1
else:
print("********************** ERROR ***************************")
print("P_type '{}' Is not recognised".format(P_type))
print("P_type can only take the values 'adjP' (default) or 'P'.")
if frame <= self.I.shape[1]:
diff_frames = []
for i in range(0, self.I.shape[1]):
if i+1 < frame:
key = "{},{}".format(i+1, frame)
elif i+1 > frame:
key = "{},{}".format(frame, i+1)
else:
continue
print(self.datcmp_data)
significance_val = self.datcmp_data[key][p_col]
if significance_val < P_threshold:
diff_frames.append(i+1)
return diff_frames
else:
print("********************** ERROR ***************************")
print("FRAME '{}' DOES NOT EXIST".format(frame))
print("Use different frame numbers between 1 and {}".format(self.I.shape[1]))
def find_first_n_diff_frames(self, n=1, frame=1, P_threshold=0.01,
P_type="adjP"):
"""
Find the first of n consecutive dissimilar frames.
Return the first frame, F, where there are n-1 consecutive frames
after F that are also statistically dissimilar from the chosen frame.
Parameters
----------
n : int, optional (default=1)
The number of consecutive dissimilar frames to be considered
significant.
frame : int, optional (default=1)
The frame that every other frame in the dataset is compared with.
If not specified then all frames are compared to the first frame.
P_threshold : float, optional (default=0.01)
The significance threshold of the test. If it's not given then the
default value is 1%.
P_type : str, optional (default="adjP")
string denoting whether to use the Bonferroni corrected P value
(input string="adjP") or the ordinary P value (input string="P").
Default is to use the Bonferroni corrected P value.
Returns
-------
int
Frame number of the first of n consecutive dissimilar frames.
Examples
--------
Get the frame number that is the first of 3 consecutive dissimilar
frames to frame 10.
>>> first_diff_frames = scat_obj.find_first_n_diff_frames(n=3, frame=10)
"""
# Get list frames that are different
list_of_diff_frames = self.find_diff_frames(frame, P_threshold, P_type)
if n == 1:
# If only looking for one frame then return the first value in
# list of different frames.
return list_of_diff_frames[0]
elif n > 1:
# If we're looking for more than one consecutive frame then we need
# to keep track of the number of consecutive frames that we've
# iterated through.
consec_count = 0
max_consec_count = 0
fr_max_count = 0
for i, curr_fr in enumerate(list_of_diff_frames):
if i == 0:
prev_fr = curr_fr
consec_count = 1
else:
if curr_fr == prev_fr + 1:
consec_count += 1
else:
consec_count = 1
prev_fr = curr_fr
if consec_count == n:
return curr_fr - n + 1
if consec_count > max_consec_count:
max_consec_count = consec_count
fr_max_count = curr_fr - max_consec_count + 1
print("************************ WARNING **************************")
print("{} consecutive frames not reached!".format(n))
print("The max number of consecutive frames was {}".format(max_consec_count))
print("The initial frame for that run was frame {}.".format(fr_max_count))
else:
print("********************** ERROR ***************************")
print("n MUST BE A POSITVE INTEGER VALUE")
print("User chose n = {}.".format(n))
print("Please choose a positve integer value for n.")
def similar_frames(self, frame=1, P_threshold=0.01, P_type="adjP"):
"""
List all statistically similar frames.
This method finds all statistically similar frames to any given
frame using the CorMap test as outlined in Daniel Franke, Cy M Jeffries
& Dmitri I Svergun (2015). The user can set the significance threshold
as well as whether to use the Bonferroni corrected P values or not.
(we recommend that you should use the Bonferroni corrected P values).
Parameters
----------
frame : int, optional (default=1)
The frame that every other frame in the dataset is compared with.
If not specified then all frames are compared to the first frame.
P_threshold : float, optional (default=0.01)
The significance threshold of the test. If it's not given then the
default value is 1%.
P_type : str, optional (default="adjP")
string denoting whether to use the Bonferroni corrected P value
(input string="adjP") or the ordinary P value (input string="P").
Default is to use the Bonferroni corrected P value.
Returns
-------
List
A list of integers corresponding to all of the similar frames
Examples
--------
Find all frames that are similar to frame 10
>>> similar_frames = scat_obj.similar_frames(frame=10)
"""
list_of_diff_frames = self.find_diff_frames(frame, P_threshold, P_type)
return [i+1 for i in range(0, self.I.shape[1]) if i+1 not in list_of_diff_frames]
def get_pw_data(self, frame1, frame2, datcmp_data_type="adj P(>C)"):
"""
Get the CorMap results for a given pair of frames.
Return C, P(>C) or Bonferroni adjusted P(>C) value from the DATCMP
output.
Parameters
----------
frame1 : int
number of the 1st frame used for the pairwise analyis
frame2 : int
number of the 2nd frame used for the pairwise analyis
datcmp_data_type: str, optional (default="adj P(>C)")
String specifying the pairwise result to be returned.
The input options are:
1) 'C' - This will return the C value i.e. the max observed patch
of continuous runs of -1 or 1
2) 'P(>C)' - This will return the P value of observing a patch of
continuous runs of -1 or 1 bigger than the corresponding C value.
3) 'adj P(>C)' - This will return the Bonferroni adjusted P value
of observing a patch of continuous runs of -1 or 1 bigger than the
corresponding C value.
Returns
-------
int or float
A value specifying the largest number of consecutive positive or
negative values in a row, C, or the probability value (either
standard P or Bonferroni corrected) the we observed more than C
positive or negative values in a row.
Examples
--------
Get the number of the longest run of positive or negative values in a
row between frames 1 and 2
>>> C = scat_obj.get_pw_data(1, 2, datcmp_data_type='C')
Get the Bonferroni corrected probability that we would observed a run
of positive or negative values greater than C
>>> C = scat_obj.get_pw_data(1, 2, datcmp_data_type='adj P(>C)')
"""
if datcmp_data_type == "C" or datcmp_data_type == 0:
dat_type = 0
elif datcmp_data_type == "P(>C)":
dat_type = 1
elif datcmp_data_type == "adj P(>C)":
dat_type = 2
else:
print("********************** ERROR ***************************")
print("INVALID DATCMP DATA TYPE CHOSEN: '{}' DOES NOT EXIST".format(datcmp_data_type))
print("Please choose either 'C', 'P(>C)' or 'adj P(>C)'.")
if frame1 < frame2:
datcmp_key = "{},{}".format(frame1, frame2)
elif frame2 < frame1:
datcmp_key = "{},{}".format(frame2, frame1)
if datcmp_key in self.datcmp_data:
return self.datcmp_data[datcmp_key][dat_type]
else:
print("********************** ERROR ***************************")
print("KEY '{}' DOES NOT EXIST".format(datcmp_key))
print("Use different frame numbers between 1 and {}".format(self.I.shape[1]))
def calc_cormap(self):
"""
Calculate correlation map.
Method to calculate the full correlation map for entire dataset.
Parameters
----------
N/A
Returns
-------
numpy 2D array
2D matrix of correlations for all SAXS frames
Examples
--------
>>> correlation_matrix = scat_obj.calc_cormap()
"""
return np.corrcoef(self.I)
def calc_pwcormap(self, frame1, frame2):
"""
Calculate pairwise correlation map between two frames.
Calculation of the pairwise correlation map between two chosen frames.
Parameters
----------
frame1 : int
Number of the 1st frame used for the pairwise analyis
frame2 : int
Number of the 2nd frame used for the pairwise analyis
Returns
-------
2D Numpy array
Array with the correlation between two frames.
Examples
--------
Get the correlation map between frames 1 and 10.
>>> pairwise_corr_map = scat_obj.calc_pwcormap(1, 10)
"""
pw_I = np.column_stack([self.I[:, frame1-1], self.I[:, frame2-1]])
return np.corrcoef(pw_I)
def get_pw_data_array(self, frame=0, delete_zero_row=True):
"""
Get C, P(>C) and Bonferroni corrected P(>C) values for a given frame.
Return an array of all C, P(>C) and Bonferroni adjusted P(>C) values
from the DATCMP output for the requested frame. E.g. if you choose
frame 1 then this means that the method with return an array of C,
P(>C) and Bonferroni adjusted P(>C) values calculated between frame 1
and all other frames.
Parameters
----------
frame : int, optional (default=0)
The frame that every other frame in the dataset is compared with.
If not specified then ALL data from the DATCMP results are
returned.
delete_zero_row : bool, optional (default=True)
Choose whether to include a row where the chosen frame would've
been compared with itself - although this row is filled with zero.
This makes sure that you'll return an array whose number of rows
is the same as the number of frames. By default this is set to
false.
Returns
-------
2D Numpy array
Array of all C, P(>C) and Bonferroni adjusted P(>C) values from the
DATCMP results for the requested frame.
Examples
--------
Get all DATCMP data for when all other frames are compared with frame
10
>>> datcmp_data = scat_obj.get_pw_data_array(frame=10)
"""
if frame == 0:
pw_data = np.zeros([len(self.datcmp_data), 3])
for i, values in enumerate(self.datcmp_data.itervalues()):
pw_data[i, :] = np.asarray(values)
elif 1 <= frame <= self.I.shape[1]:
pw_data = np.zeros([self.I.shape[1], 3])
for i in range(0, self.I.shape[1]):
if i+1 < frame:
key = "{},{}".format(i+1, frame)
elif i+1 > frame:
key = "{},{}".format(frame, i+1)
else:
continue
pw_data[i, :] = np.asarray(self.datcmp_data[key])
else:
print("********************** ERROR ***************************")
print("FRAME '{}' DOES NOT EXIST".format(frame))
print("Use a frame number between 1 and {}".format(self.I.shape[1]))
if delete_zero_row and frame > 0:
return np.delete(pw_data, (frame-1), axis=0)
else:
return pw_data
# ----------------------------------------------------------------------- #
# PLOT THE CORRELATION MAP #
# ----------------------------------------------------------------------- #
def plot_cormap(self, colour_scheme="gray", display=True, save=False,
filename="", directory=""):
"""
Plot the full correlation map.
Plot the correlation map of all frames in the dataset.
Parameters
----------
colour_scheme : str, optional (default="gray")
The colour scheme used to plot the correlation map. The list of
schemes can be found on the relevant matplotlib webpage:
http://matplotlib.org/examples/color/colormaps_reference.html
display : bool, optional (default=True)
Choose whether to display the plot. By default it is displayed.
save : bool, optional (default=True)
Choose whether to save the plot. By default the plot is not saved.
filename : str, optional (default="")
Choose a filename for the plot that you want to save. This includes
the file extension.
directory : str, optional (default="")
Select the directory in which you want the plot to be saved.
Examples
--------
Plot the full correlation map
>>> scat_obj.plot_cormap()
Save the correlation map in the current working directory without
displaying it
>>> scat_obj.plot_cormap(display=False, save=True, filename="MyPlot.png")
"""
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
# SET PLOT PARAMS #
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
min_q = min(self.q)
max_q = max(self.q)
self.PLOT_NUM += 1
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
# PLOT CORMAP #
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
plt.figure(self.PLOT_NUM)
plt.gca().xaxis.grid(False)
plt.gca().yaxis.grid(False)
cormap = plt.imshow(self.calc_cormap(), cmap=colour_scheme,
extent=[min_q, max_q, min_q, max_q])
plt.xlabel(r'Scattering Vector, q (nm$^{-1}$)',
fontdict=self.PLOT_LABEL)
plt.ylabel(r'Scattering Vector, q (nm$^{-1}$)',
fontdict=self.PLOT_LABEL)
plt.colorbar(cormap)
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
# SAVE AND/OR DISPLAY #
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
if save and filename:
if directory:
plot_path = "{}/{}".format(directory, filename)
else:
plot_path = filename
plt.savefig(plot_path)
elif save and not filename:
print("********************** ERROR ***************************")
print("COULD NOT SAVE PLOT")
print("No filename specified. Please specify a filename if you")
print("would like to save the plot.")
if display:
plt.show()
# ----------------------------------------------------------------------- #
# PLOT THE PAIRWISE CORRELATION MAP #
# ----------------------------------------------------------------------- #
def plot_pwcormap(self, fr1, fr2, colour_scheme="gray", display=True,
save=False, filename="", directory=""):
"""
Plot the pairwise correlation map between two chosen frames.
Plot the pairwise correlation map between two frames fr1 and fr2.
Parameters
----------
fr1 : int
Number of the 1st frame used for the pairwise analyis
fr2 : int
Number of the 2nd frame used for the pairwise analyis
colour_scheme : str, optional (default="gray")
The colour scheme used to plot the correlation map. The list of
schemes can be found on the relevant matplotlib webpage:
http://matplotlib.org/examples/color/colormaps_reference.html
display : bool, optional (default=True)
Choose whether to display the plot. By default it is displayed.
save : bool, optional (default=True)
Choose whether to save the plot. By default the plot is not saved.
filename : str, optional (default="")
Choose a filename for the plot that you want to save. This includes
the file extension.
directory : str, optional (default="")
Select the directory in which you want the plot to be saved.
Examples
--------
Plot the pairwise correlation map between frame 1 and frame 2
>>> scat_obj.plot_pwcormap(1, 2)
Save the pairwise correlation map in the current working directory
without displaying it
>>> scat_obj.plot_pwcormap(1, 2, display=False, save=True, filename="MyPlot.png")
"""
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
# SET PLOT PARAMS #
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
min_q = min(self.q)
max_q = max(self.q)
self.PLOT_NUM += 1
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
# PLOT PAIRWISE CORMAP #
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
fig = plt.figure(self.PLOT_NUM)
plt.gca().xaxis.grid(False)
plt.gca().yaxis.grid(False)
cormap = plt.imshow(self.calc_pwcormap(frame1=fr1, frame2=fr2),cmap=colour_scheme,extent=[min_q, max_q, max_q, min_q])
#cormap = plt.imshow(self.calc_pwcormap(frame1=fr1, frame2=fr2),cmap=colour_scheme)
plt.xlabel(r'Scattering Vector, q (nm$^{-1}$)',
fontdict=self.PLOT_LABEL)
plt.ylabel(r'Scattering Vector, q (nm$^{-1}$)',
fontdict=self.PLOT_LABEL)
plt.colorbar(cormap, ticks=[1, -1])
adjP = self.get_pw_data(fr1, fr2, "adj P(>C)")
C = self.get_pw_data(fr1, fr2, "C")
if self.x_units:
change_in_x = abs(self.x_axis[fr1-1] - self.x_axis[fr2-1])
plt.title(r'PW CorMap: frame {} vs {}.C = {}, adj P(>C) = {}, $\Delta${} = {:.2f} {}'.format(fr1, fr2, C, adjP, self.x_metric, change_in_x, self.x_units), ha='center')
else:
plt.title(r'Pairwise CorMap: frame {} vs {}. C = {}, adj P(>C) = {}'.format(fr1, fr2, C, adjP), ha='center')
fig.canvas.mpl_connect('draw_event', on_draw)
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
# SAVE AND/OR DISPLAY #
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
if save and filename:
if directory:
plot_path = "{}/{}".format(directory, filename)
else:
plot_path = filename
plt.savefig(plot_path)
elif save and not filename:
print("********************** ERROR ***************************")
print("COULD NOT SAVE PLOT")
print("No filename specified. Please specify a filename if you")
print("would like to save the plot.")
if display:
plt.show()
# ----------------------------------------------------------------------- #
# PLOT THE HISTOGRAM OF PAIRWISE DATA #
# ----------------------------------------------------------------------- #
def plot_histogram(self, frame=0, datcmp_data_type="C", display=True,
save=False, filename="", directory="", num_bins=20):
"""
Plot the histogram of the DATCMP data.
For any chosen frame this methods plots a histogram of the DATCMP data
for all pairwise comparisons with that frame. If no frames are chosen
then the method plots all pairwise frame comparison data.
Parameters
----------
frame : int, optional (default=0)
Number of the frame for which all pairwise comparison data is
plotted. If not specified then all pairwise frame comparison data
is shown.
datcmp_data_type : str, optional (default="C")
The data type from the DATCMP results that is plotted.
The input options are:
1) 'C' - This will return the C value i.e. the max observed patch
of continuous runs of -1 or 1
2) 'P(>C)' - This will return the P value of observing a patch of
continuous runs of -1 or 1 bigger than the corresponding C value.
3) 'adj P(>C)' - This will return the Bonferroni adjusted P value
of observing a patch of continuous runs of -1 or 1 bigger than the
corresponding C value.
display : bool, optional (default=True)
Choose whether to display the plot. By default it is displayed.
save : bool, optional (default=True)
Choose whether to save the plot. By default the plot is not saved.
filename : str, optional (default="")
Choose a filename for the plot that you want to save. This includes
the file extension.
directory : str, optional (default="")
Select the directory in which you want the plot to be saved.
num_bins : int, optional (default=20)
Number of bins used to plot in the histogram.
Examples
--------
Plot histogram of all of the DATCMP data with data type "C" (as defined
above)
>>> scat_obj.plot_histogram()
Plot histogram of all of Bonferroni corrected P values with all frames
compared to frame 10.
>>> scat_obj.plot_histogram(frame=10, datcmp_data_type="adj P(>C)")
Save the histogram in the current working directory without displaying
it
>>> scat_obj.plot_histogram(display=False, save=True, filename="MyPlot.png")
"""
if datcmp_data_type == "C" or datcmp_data_type == 0:
dat_type = 0
elif datcmp_data_type == "P(>C)":
dat_type = 1
elif datcmp_data_type == "adj P(>C)":
dat_type = 2
else:
print("********************** ERROR ***************************")
print("INVALID DATCMP DATA TYPE CHOSEN: '{}' DOES NOT EXIST".format(datcmp_data_type))
print("Please choose either 'C', 'P(>C)' or 'adj P(>C)'.")
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
# SET PLOT PARAMS #
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
self.PLOT_NUM += 1
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
# PLOT HISTOGRAM #
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
plt.figure(self.PLOT_NUM)
plt.hist(self.get_pw_data_array(frame)[:, dat_type], bins=num_bins)
plt.xlabel("{}".format(datcmp_data_type), fontdict=self.PLOT_LABEL)
plt.ylabel(r'Frequency', fontdict=self.PLOT_LABEL)
if frame == 0:
plt.title("{} values for all pairwise comparisons".format(datcmp_data_type))
else:
plt.title("{} values for all pairwise comparisons with frame {}".format(datcmp_data_type, frame))
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
# SAVE AND/OR DISPLAY #
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
if save and filename:
if directory:
plot_path = "{}/{}".format(directory, filename)
else:
plot_path = filename
plt.savefig(plot_path)
elif save and not filename:
print("********************** ERROR ***************************")
print("COULD NOT SAVE PLOT")
print("No filename specified. Please specify a filename if you")
print("would like to save the plot.")
if display:
plt.show()
# ----------------------------------------------------------------------- #
# SCATTER PLOT OF PAIRWISE DATA #
# ----------------------------------------------------------------------- #
def plot_scatter(self, frame=1, P_threshold=0.01, markersize=60,
display=True, save=False, filename="", directory="",
legend_loc="upper left", x_change=False, use_adjP=True,
xaxis_frame_num=False,
colours=["#0072B2", "#009E73", "#D55E00"],
markers=["o", "o", "o"]):
"""
Create scatter plot of the frame similarity data.
For any chosen frame this methods creates a scatter plot of the C
values - the maximum observed patch of continuous runs of -1 or 1 - for
a chosen frame against all other frames. The probabilities of those C
values occuring by chance are also coloured accordingly, and this can
be changed by the user.
Parameters
----------
frame : int, optional (default=0)
Number of the frame for which all pairwise comparison data is
plotted. If not specified then all pairwise frame comparison data
against frame 1 is plotted.
P_threshold : float, optional (default=0.01)
The significance level for the data. If the probability is below
this value then the current frame is considered dissimilar to the
frame to which it is being compared. Default significance level is
0.01.
markersize : float, optional (default=60)
Change the size of the markers on the plot. Default value is 60.
display : bool, optional (default=True)
Choose whether to display the plot. By default it is displayed.
save : bool, optional (default=True)
Choose whether to save the plot. By default the plot is not saved.
filename : str, optional (default="")
Choose a filename for the plot that you want to save. This includes
the file extension.
directory : str, optional (default="")
Select the directory in which you want the plot to be saved.
legend_loc : str or int, optional (default="upper left")
Set the location of the legend in the figure. All possible values
can be found in the Matplotlib Legend API documentation:
http://matplotlib.org/api/legend_api.html. Default is set to the
upper left of the figure.
x_change : bool, optional (default=False)
This option changes whether the x-axis is plotted with absolute
values (x_change=True) or if it's plotted with differences between
the x-axis values (x_change=False). For example if we compare
choose the reference frame to be frame 10 (frame=10) then compare
this with frame 30 then setting x_change=True will put the relevant
point at frame 30. However if we set x_change=False this will put
the relevant point to be at abs(10 - 30) = 20. This option allows
you to determine if the dissimilar frames are frames that are
collected far from the current frame. Default is set to
x_change=True.
use_adjP : bool, optional (default=True)
Choose whether to use the Bonferroni corrected P values or to use
the unadjusted P values. Default is to use the Bonferroni corrected
P values.
xaxis_frame_num : bool, optional (default=True)
Choose whether to plot the x-axis with the frame number or whether
to use the custom x-axis metric values that may (or may not) have
been defined when the ScatterAnalysis object was constructed.
Default is to use the custom metric (if it was defined).
colours : list, optional (default=["#0072B2", "#009E73", "#D55E00"])
Choose the colour scheme for the markers in the scatter plot, which
is differentiated by the P value.
markers : list, optional (default=["o", "o", "o"])
Choose the markers used for the markers in the scatter plot, which
is differentiated by the P value. A list of the markers that can be
used can be found on the Matplotlib Markers API webpage:
http://matplotlib.org/api/markers_api.html
Examples
--------
Create the scatter plot of the data compared against frame 1
>>> scat_obj.plot_scatter()
Create scatter plot where all frames are compared against frame 30 and
the x axis plots the difference in frame number from frame 30.
>>> scat_obj.plot_scatter(frame=30, x_change=True)
Save the scatter plot in the current working directory without
displaying it.
>>> scat_obj.plot_scatter(display=False, save=True, filename="MyPlot.png")
"""
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
# SET PLOT PARAMS #
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
self.PLOT_NUM += 1
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
# SCATTER PLOT #
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
pwframe_data = self.get_pw_data_array(frame=frame,
delete_zero_row=False)
if xaxis_frame_num:
x_axis = np.linspace(1, self.I.shape[1], self.I.shape[1])
else:
x_axis = self.x_axis