forked from AlistairCurd/PERPL-Python3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdna_paint_data_fitting.py
1205 lines (1042 loc) · 45.8 KB
/
dna_paint_data_fitting.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
"""
dna_paint_data_fitting.py
Library of functions for fitting model relative position distributions (RPDs)
to relative positions obtained from localisations appearing to be arranged
on a relatively simple geometric pattern, i.e. polyhedra.
Created on Mon Jul 29 15:41:31 2019
Alistair Curd
University of Leeds
30 July 2018
Software Engineering practices applied
Joanna Leng (an EPSRC funded Research Software Engineering Fellow (EP/R025819/1)
University of Leeds
January 2019
---
Copyright 2018 Peckham Lab
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
"""
from scipy.optimize import curve_fit
import numpy as np
import matplotlib.pyplot as plt
import polyhedramodelling as poly
import modelstats as stats
import modelling_general as models
from modelling_general import ModelWithFitSettings
from modelling_general import stdev_of_model
def create_default_fitting_params_dicts():
"""Create lists for initial guesses and bounds for parameters during
fitting. Sets the defaults for scipy.optimise.curve_fit
Returns:
lower_bound_dict (dict):
Dictionary of default lower bound options for parameter values.
upper_bound_dict (dict):
Dictionary of default upper bound options for parameter values.
initial_params_dict (dict):
Dictionary of default initial parameter value options.
"""
lower_bound_dict = {'side_1': 0,
'side_2': 0,
'side_3': 0,
'loc_prec_sd': 0,
'loc_prec_amp': 0,
'vertices_amp': 0,
'vertices_sd': 0,
'substruct_amp': 0,
'substruct_sd': 0,
'square_grid_spacing': 0,
'square_grid_amp': 0,
'square_grid_sd': 0,
'bg_slope': 0,
}
upper_bound_dict = {'side_1': 200,
'side_2': 200,
'side_3': 200,
'loc_prec_sd': 100,
'loc_prec_amp': 100,
'vertices_amp': 100,
'vertices_sd': 100,
'substruct_amp': 100,
'substruct_sd': 100,
'square_grid_spacing': 400,
'square_grid_amp': 1000,
'square_grid_sd': 100,
'bg_slope': 0.1,
}
initial_params_dict = {'side_1': 100,
'side_2': 100,
'side_3': 100,
'loc_prec_sd': 10,
'loc_prec_amp': 10,
'vertices_amp': 10,
'vertices_sd': 10,
'substruct_amp': 10,
'substruct_sd': 10,
'square_grid_spacing': 200,
'square_grid_amp': 100,
'square_grid_sd': 10,
'bg_slope': 0.001,
}
return lower_bound_dict, upper_bound_dict, initial_params_dict
def set_up_tri_prism_on_grid_1_length_2disobg_substruct_with_fit_info():
"""Set up the RPD model with fitting settings,
for a rotationally symmetric model with spread due to repeated
localisations and spread to unresolvable substructure.
The fitting settings are to pass to scipy's
curve_fit, and the vector-input version of the model is for
differentiation and error propagation with numdifftools.
Args:
None
Returns:
A ModelWithFitSettings object containing:
model_rpd (function name):
Relative position density as a function of separation
between localisations.
initial_params (list):
Starting guesses for the parameter values by
scipy.optimize.curve_fit
lower_bounds (list), upper_bounds (list):
The bounds on allowable parameter values as
scipy.optimize.curve_fit runs.
"""
model_with_info = (
ModelWithFitSettings(
model_rpd=poly.tri_prism_on_grid_1_length_2disobg_substruct_rpd
)
)
# Add fitting parameters to ModelWithFitSettings object
(lower_bound_dict,
upper_bound_dict,
initial_params_dict) = create_default_fitting_params_dicts()
# Can optionally modify these dictionaries here:
initial_params = [initial_params_dict['side_1'],
initial_params_dict['loc_prec_amp'],
initial_params_dict['loc_prec_sd'],
initial_params_dict['vertices_amp'],
initial_params_dict['vertices_sd'],
initial_params_dict['substruct_amp'],
initial_params_dict['substruct_sd'],
initial_params_dict['square_grid_spacing'],
initial_params_dict['square_grid_amp'],
initial_params_dict['square_grid_sd'],
initial_params_dict['bg_slope']
]
lower_bounds = [lower_bound_dict['side_1'],
lower_bound_dict['loc_prec_amp'],
lower_bound_dict['loc_prec_sd'],
lower_bound_dict['vertices_amp'],
lower_bound_dict['vertices_sd'],
lower_bound_dict['substruct_amp'],
lower_bound_dict['substruct_sd'],
lower_bound_dict['square_grid_spacing'],
lower_bound_dict['square_grid_amp'],
lower_bound_dict['square_grid_sd'],
lower_bound_dict['bg_slope']
]
upper_bounds = [upper_bound_dict['side_1'],
upper_bound_dict['loc_prec_amp'],
upper_bound_dict['loc_prec_sd'],
upper_bound_dict['vertices_amp'],
upper_bound_dict['vertices_sd'],
upper_bound_dict['substruct_amp'],
upper_bound_dict['substruct_sd'],
upper_bound_dict['square_grid_spacing'],
upper_bound_dict['square_grid_amp'],
upper_bound_dict['square_grid_sd'],
upper_bound_dict['bg_slope']
]
bounds = (lower_bounds, upper_bounds)
model_with_info.initial_params = (
initial_params
)
model_with_info.param_bounds = (
bounds
)
model_with_info.vector_input_model = (
poly.tri_prism_on_grid_1_length_2disobg_substruct_rpd_vectorargs
)
return model_with_info
def set_up_tri_prism_on_grid_1_length_substruct_with_fit_info():
"""Set up the RPD model with fitting settings,
for a rotationally symmetric model with spread due to repeated
localisations and spread to unresolvable substructure.
The fitting settings are to pass to scipy's
curve_fit, and the vector-input version of the model is for
differentiation and error propagation with numdifftools.
Args:
None
Returns:
A ModelWithFitSettings object containing:
model_rpd (function name):
Relative position density as a function of separation
between localisations.
initial_params (list):
Starting guesses for the parameter values by
scipy.optimize.curve_fit
lower_bounds (list), upper_bounds (list):
The bounds on allowable parameter values as
scipy.optimize.curve_fit runs.
"""
model_with_info = (
ModelWithFitSettings(
model_rpd=poly.tri_prism_on_grid_1_length_substructure_rpd
)
)
# Add fitting parameters to ModelWithFitSettings object
(lower_bound_dict,
upper_bound_dict,
initial_params_dict) = create_default_fitting_params_dicts()
# Can optionally modify these dictionaries here:
initial_params = [initial_params_dict['side_1'],
initial_params_dict['loc_prec_amp'],
initial_params_dict['loc_prec_sd'],
initial_params_dict['vertices_amp'],
initial_params_dict['vertices_sd'],
initial_params_dict['substruct_amp'],
initial_params_dict['substruct_sd'],
initial_params_dict['square_grid_spacing'],
initial_params_dict['square_grid_amp'],
initial_params_dict['square_grid_sd'],
]
lower_bounds = [lower_bound_dict['side_1'],
lower_bound_dict['loc_prec_amp'],
lower_bound_dict['loc_prec_sd'],
lower_bound_dict['vertices_amp'],
lower_bound_dict['vertices_sd'],
lower_bound_dict['substruct_amp'],
lower_bound_dict['substruct_sd'],
lower_bound_dict['square_grid_spacing'],
lower_bound_dict['square_grid_amp'],
lower_bound_dict['square_grid_sd'],
]
upper_bounds = [upper_bound_dict['side_1'],
upper_bound_dict['loc_prec_amp'],
upper_bound_dict['loc_prec_sd'],
upper_bound_dict['vertices_amp'],
upper_bound_dict['vertices_sd'],
upper_bound_dict['substruct_amp'],
upper_bound_dict['substruct_sd'],
upper_bound_dict['square_grid_spacing'],
upper_bound_dict['square_grid_amp'],
upper_bound_dict['square_grid_sd'],
]
bounds = (lower_bounds, upper_bounds)
model_with_info.initial_params = (
initial_params
)
model_with_info.param_bounds = (
bounds
)
#model_with_info.vector_input_model = (
# poly.tri_prism_on_grid_1_length_2disobg_substruct_rpd_vectorargs
# )
return model_with_info
def set_up_tri_prism_on_grid_1_length_3disobg_substruct_with_fit_info():
"""Set up the RPD model with fitting settings,
for a rotationally symmetric model with spread due to repeated
localisations and spread to unresolvable substructure.
The fitting settings are to pass to scipy's
curve_fit, and the vector-input version of the model is for
differentiation and error propagation with numdifftools.
Args:
None
Returns:
A ModelWithFitSettings object containing:
model_rpd (function name):
Relative position density as a function of separation
between localisations.
initial_params (list):
Starting guesses for the parameter values by
scipy.optimize.curve_fit
lower_bounds (list), upper_bounds (list):
The bounds on allowable parameter values as
scipy.optimize.curve_fit runs.
"""
model_with_info = (
ModelWithFitSettings(
model_rpd=poly.tri_prism_on_grid_1_length_3disobg_substruct_rpd
)
)
# Add fitting parameters to ModelWithFitSettings object
(lower_bound_dict,
upper_bound_dict,
initial_params_dict) = create_default_fitting_params_dicts()
# Can optionally modify these dictionaries here:
initial_params = [initial_params_dict['side_1'],
initial_params_dict['loc_prec_amp'],
initial_params_dict['loc_prec_sd'],
initial_params_dict['vertices_amp'],
initial_params_dict['vertices_sd'],
initial_params_dict['substruct_amp'],
initial_params_dict['substruct_sd'],
initial_params_dict['square_grid_spacing'],
initial_params_dict['square_grid_amp'],
initial_params_dict['square_grid_sd'],
initial_params_dict['bg_slope'] # Use this as the bg_scale
]
lower_bounds = [lower_bound_dict['side_1'],
lower_bound_dict['loc_prec_amp'],
lower_bound_dict['loc_prec_sd'],
lower_bound_dict['vertices_amp'],
lower_bound_dict['vertices_sd'],
lower_bound_dict['substruct_amp'],
lower_bound_dict['substruct_sd'],
#lower_bound_dict['square_grid_spacing'],
200.,
lower_bound_dict['square_grid_amp'],
lower_bound_dict['square_grid_sd'],
lower_bound_dict['bg_slope'] # Use this as the bg_scale
]
upper_bounds = [upper_bound_dict['side_1'],
upper_bound_dict['loc_prec_amp'],
upper_bound_dict['loc_prec_sd'],
upper_bound_dict['vertices_amp'],
upper_bound_dict['vertices_sd'],
upper_bound_dict['substruct_amp'],
upper_bound_dict['substruct_sd'],
upper_bound_dict['square_grid_spacing'],
upper_bound_dict['square_grid_amp'],
upper_bound_dict['square_grid_sd'],
upper_bound_dict['bg_slope'] # Use this as the bg_scale
]
bounds = (lower_bounds, upper_bounds)
model_with_info.initial_params = (
initial_params
)
model_with_info.param_bounds = (
bounds
)
#model_with_info.vector_input_model = (
# poly.tri_prism_on_grid_1_length_2disobg_substruct_rpd_vectorargs
# )
return model_with_info
def set_up_tri_prism_1_length_3disobg_substruct_with_fit_info():
"""Set up the RPD model with fitting settings,
for a rotationally symmetric model with spread due to repeated
localisations and spread to unresolvable substructure.
The fitting settings are to pass to scipy's
curve_fit, and the vector-input version of the model is for
differentiation and error propagation with numdifftools.
Args:
None
Returns:
A ModelWithFitSettings object containing:
model_rpd (function name):
Relative position density as a function of separation
between localisations.
initial_params (list):
Starting guesses for the parameter values by
scipy.optimize.curve_fit
lower_bounds (list), upper_bounds (list):
The bounds on allowable parameter values as
scipy.optimize.curve_fit runs.
"""
model_with_info = (
ModelWithFitSettings(
model_rpd=poly.tri_prism_1_length_3disobg_substruct_rpd
)
)
# Add fitting parameters to ModelWithFitSettings object
(lower_bound_dict,
upper_bound_dict,
initial_params_dict) = create_default_fitting_params_dicts()
# Can optionally modify these dictionaries here:
initial_params = [initial_params_dict['side_1'],
initial_params_dict['loc_prec_amp'],
initial_params_dict['loc_prec_sd'],
initial_params_dict['vertices_amp'],
initial_params_dict['vertices_sd'],
initial_params_dict['substruct_amp'],
initial_params_dict['substruct_sd'],
initial_params_dict['bg_slope'] # Use this as the bg_scale
]
lower_bounds = [lower_bound_dict['side_1'],
lower_bound_dict['loc_prec_amp'],
lower_bound_dict['loc_prec_sd'],
lower_bound_dict['vertices_amp'],
lower_bound_dict['vertices_sd'],
lower_bound_dict['substruct_amp'],
lower_bound_dict['substruct_sd'],
lower_bound_dict['bg_slope'] # Use this as the bg_scale
]
upper_bounds = [upper_bound_dict['side_1'],
upper_bound_dict['loc_prec_amp'],
upper_bound_dict['loc_prec_sd'],
upper_bound_dict['vertices_amp'],
upper_bound_dict['vertices_sd'],
upper_bound_dict['substruct_amp'],
upper_bound_dict['substruct_sd'],
upper_bound_dict['bg_slope'] # Use this as the bg_scale
]
bounds = (lower_bounds, upper_bounds)
model_with_info.initial_params = (
initial_params
)
model_with_info.param_bounds = (
bounds
)
#model_with_info.vector_input_model = (
# poly.tri_prism_on_grid_1_length_2disobg_substruct_rpd_vectorargs
# )
return model_with_info
def set_up_model_tri_prism_on_grid_2disobg_substructure_with_fit_info():
"""Set up the RPD model with fitting settings,
for a rotationally symmetric model with spread due to repeated
localisations and spread to unresolvable substructure.
The fitting settings are to pass to scipy's
curve_fit, and the vector-input version of the model is for
differentiation and error propagation with numdifftools.
Args:
None
Returns:
A ModelWithFitSettings object containing:
model_rpd (function name):
Relative position density as a function of separation
between localisations.
initial_params (list):
Starting guesses for the parameter values by
scipy.optimize.curve_fit
lower_bounds (list), upper_bounds (list):
The bounds on allowable parameter values as
scipy.optimize.curve_fit runs.
"""
model_with_info = (
ModelWithFitSettings(
model_rpd=poly.tri_prism_on_grid_2disobg_substructure_rpd
)
)
# Add fitting parameters to ModelWithFitSettings object
(lower_bound_dict,
upper_bound_dict,
initial_params_dict) = create_default_fitting_params_dicts()
# Can optionally modify these dictionaries here:
initial_params = [initial_params_dict['side_1'],
initial_params_dict['side_2'],
initial_params_dict['loc_prec_amp'],
initial_params_dict['loc_prec_sd'],
initial_params_dict['vertices_amp'],
initial_params_dict['vertices_sd'],
initial_params_dict['substruct_amp'],
initial_params_dict['substruct_sd'],
initial_params_dict['square_grid_spacing'],
initial_params_dict['square_grid_amp'],
initial_params_dict['square_grid_sd'],
initial_params_dict['bg_slope']
]
lower_bounds = [lower_bound_dict['side_1'],
lower_bound_dict['side_2'],
lower_bound_dict['loc_prec_amp'],
lower_bound_dict['loc_prec_sd'],
lower_bound_dict['vertices_amp'],
lower_bound_dict['vertices_sd'],
lower_bound_dict['substruct_amp'],
lower_bound_dict['substruct_sd'],
lower_bound_dict['square_grid_spacing'],
lower_bound_dict['square_grid_amp'],
lower_bound_dict['square_grid_sd'],
lower_bound_dict['bg_slope']
]
upper_bounds = [upper_bound_dict['side_1'],
upper_bound_dict['side_2'],
upper_bound_dict['loc_prec_amp'],
upper_bound_dict['loc_prec_sd'],
upper_bound_dict['vertices_amp'],
upper_bound_dict['vertices_sd'],
upper_bound_dict['substruct_amp'],
upper_bound_dict['substruct_sd'],
upper_bound_dict['square_grid_spacing'],
upper_bound_dict['square_grid_amp'],
upper_bound_dict['square_grid_sd'],
upper_bound_dict['bg_slope']
]
bounds = (lower_bounds, upper_bounds)
model_with_info.initial_params = (
initial_params
)
model_with_info.param_bounds = (
bounds
)
model_with_info.vector_input_model = (
poly.tri_prism_on_grid_2disobg_substructure_rpd_vectorargs
)
return model_with_info
def set_up_model_cuboid_on_grid_2disobg_substructure_with_fit_info():
"""Set up the RPD model with fitting settings,
for a rotationally symmetric model with spread due to repeated
localisations and spread to unresolvable substructure.
The fitting settings are to pass to scipy's
curve_fit, and the vector-input version of the model is for
differentiation and error propagation with numdifftools.
Args:
None
Returns:
A ModelWithFitSettings object containing:
model_rpd (function name):
Relative position density as a function of separation
between localisations.
initial_params (list):
Starting guesses for the parameter values by
scipy.optimize.curve_fit
lower_bounds (list), upper_bounds (list):
The bounds on allowable parameter values as
scipy.optimize.curve_fit runs.
"""
model_with_info = (
ModelWithFitSettings(
model_rpd=poly.cuboid_on_grid_2disobg_substructure_rpd
)
)
# Add fitting parameters to ModelWithFitSettings object
(lower_bound_dict,
upper_bound_dict,
initial_params_dict) = create_default_fitting_params_dicts()
# Can optionally modify these dictionaries here:
initial_params = [initial_params_dict['side_1'],
initial_params_dict['side_2'],
initial_params_dict['side_3'],
initial_params_dict['loc_prec_amp'],
initial_params_dict['loc_prec_sd'],
initial_params_dict['vertices_amp'],
initial_params_dict['vertices_sd'],
initial_params_dict['substruct_amp'],
initial_params_dict['substruct_sd'],
initial_params_dict['square_grid_spacing'],
initial_params_dict['square_grid_amp'],
initial_params_dict['square_grid_sd'],
initial_params_dict['bg_slope']
]
lower_bounds = [lower_bound_dict['side_1'],
lower_bound_dict['side_2'],
lower_bound_dict['side_3'],
lower_bound_dict['loc_prec_amp'],
lower_bound_dict['loc_prec_sd'],
lower_bound_dict['vertices_amp'],
lower_bound_dict['vertices_sd'],
lower_bound_dict['substruct_amp'],
lower_bound_dict['substruct_sd'],
lower_bound_dict['square_grid_spacing'],
lower_bound_dict['square_grid_amp'],
lower_bound_dict['square_grid_sd'],
lower_bound_dict['bg_slope']
]
upper_bounds = [upper_bound_dict['side_1'],
upper_bound_dict['side_2'],
upper_bound_dict['side_3'],
upper_bound_dict['loc_prec_amp'],
upper_bound_dict['loc_prec_sd'],
upper_bound_dict['vertices_amp'],
upper_bound_dict['vertices_sd'],
upper_bound_dict['substruct_amp'],
upper_bound_dict['substruct_sd'],
upper_bound_dict['square_grid_spacing'],
upper_bound_dict['square_grid_amp'],
upper_bound_dict['square_grid_sd'],
upper_bound_dict['bg_slope']
]
bounds = (lower_bounds, upper_bounds)
model_with_info.initial_params = (
initial_params
)
model_with_info.param_bounds = (
bounds
)
# model_with_info.vector_input_model = (
# poly.tri_prism_on_grid_2disobg_substructure_rpd_vectorargs
# )
return model_with_info
def set_up_model_tri_pyramid_on_grid_2disobg_substructure_with_fit_info():
"""Set up the RPD model with fitting settings,
for a rotationally symmetric model with spread due to repeated
localisations and spread to unresolvable substructure.
The fitting settings are to pass to scipy's
curve_fit, and the vector-input version of the model is for
differentiation and error propagation with numdifftools.
Args:
None
Returns:
A ModelWithFitSettings object containing:
model_rpd (function name):
Relative position density as a function of separation
between localisations.
initial_params (list):
Starting guesses for the parameter values by
scipy.optimize.curve_fit
lower_bounds (list), upper_bounds (list):
The bounds on allowable parameter values as
scipy.optimize.curve_fit runs.
"""
model_with_info = (
ModelWithFitSettings(
model_rpd=poly.tri_pyramid_on_grid_2disobg_substructure_rpd
)
)
# Add fitting parameters to ModelWithFitSettings object
(lower_bound_dict,
upper_bound_dict,
initial_params_dict) = create_default_fitting_params_dicts()
# Can optionally modify these dictionaries here:
initial_params = [initial_params_dict['side_1'],
initial_params_dict['side_2'],
initial_params_dict['loc_prec_amp'],
initial_params_dict['loc_prec_sd'],
initial_params_dict['vertices_amp'],
initial_params_dict['vertices_sd'],
initial_params_dict['substruct_amp'],
initial_params_dict['substruct_sd'],
initial_params_dict['square_grid_spacing'],
initial_params_dict['square_grid_amp'],
initial_params_dict['square_grid_sd'],
initial_params_dict['bg_slope']
]
lower_bounds = [lower_bound_dict['side_1'],
lower_bound_dict['side_2'],
lower_bound_dict['loc_prec_amp'],
lower_bound_dict['loc_prec_sd'],
lower_bound_dict['vertices_amp'],
lower_bound_dict['vertices_sd'],
lower_bound_dict['substruct_amp'],
lower_bound_dict['substruct_sd'],
lower_bound_dict['square_grid_spacing'],
lower_bound_dict['square_grid_amp'],
lower_bound_dict['square_grid_sd'],
lower_bound_dict['bg_slope']
]
upper_bounds = [upper_bound_dict['side_1'],
upper_bound_dict['side_2'],
upper_bound_dict['loc_prec_amp'],
upper_bound_dict['loc_prec_sd'],
upper_bound_dict['vertices_amp'],
upper_bound_dict['vertices_sd'],
upper_bound_dict['substruct_amp'],
upper_bound_dict['substruct_sd'],
upper_bound_dict['square_grid_spacing'],
upper_bound_dict['square_grid_amp'],
upper_bound_dict['square_grid_sd'],
upper_bound_dict['bg_slope']
]
bounds = (lower_bounds, upper_bounds)
model_with_info.initial_params = (
initial_params
)
model_with_info.param_bounds = (
bounds
)
# model_with_info.vector_input_model = (
# poly.tri_prism_on_grid_2disobg_substructure_rpd_vectorargs
# )
return model_with_info
def fitmodel_to_hist(
distancehist,
model=poly.tri_prism_on_grid_1_length_2disobg_substruct_rpd,
fitlength=400.):
"""Fit model RPD to distance histogram. Designed to allow user editting of
parameter guesses and bounds for models of RPDs for simple polyhedra,
as in polyhedramodelling.py.
Args:
distancehist (numpy array):
An array of Euclidean distances between localisations.
model:
The model RPD to be fitted.
fitlength:
The maximum distance between localisations used for the fit.
Returns:
popt:
perr
"""
params_optimised, params_covar = curve_fit(
model, np.arange(fitlength) + 0.5, distancehist,
p0=(100., 100., #100., # a, b, c
10., 10., # locamp, locprec
10., 10., # structamp, spread
10., 10., # substructamp, substructspread
200., 100., 10., # gridspace, gridamp, gridspread
0.001), # bgslope
bounds=(
[0., 0., #0., # a, b, c
0., 0., # locamp, locprec
0., 0., # structamp, spread
0., 0., # substructamp, substructspread
0., 0., 0., # gridspace, gridamp, gridspread
0.], # bgslope
[200., 200., #200., # a, b, c
100., 100., # locamp, locprec
100., 100., # structamp, spread
100., 100., # substructamp, substructspread
400., 1000., 100., # gridspace, gridamp, gridspread
0.1]) # bgslope
)
# plt.plot(np.arange(fitlength) + 0.5,
# model(np.arange(fitlength) + 0.5, *params_optimised))
params_1sd_error = np.sqrt(np.diag(params_covar))
params_table = np.column_stack((params_optimised, params_1sd_error))
print(params_table)
# No. free parameters, including var. of residuals for least squares fit.
k = float(len(params_optimised) + 1)
# Calculate AICc
ssr = np.sum((model(np.arange(fitlength) + 0.5, *params_optimised) -
distancehist) ** 2)
aic = fitlength * np.log(ssr / fitlength) + 2 * k
aiccorr = aic + 2 * k * (k + 1) / (fitlength - k - 1)
print('SSR =', ssr)
print('AIC =', aic)
print('AICcorr =', aiccorr)
return params_optimised, params_covar, params_1sd_error
def plot_xyz_distance_histogram(distances, fitlength, color='gray'):
"""Plot histogram of experimental distances, with 1 nm bins.
Scales counts, so that mean = 1, to suit scipy.optimize.curve_fit
Args:
distances (numpy array-like):
Set of distances (nm) to plot.
fitlength (float):
The distance upto which the histogram will be calculated.
color (string):
Colour for the matplotlib histogram.
Returns:
hist_values (numpy array):
Histogram bin values.
bin_edges (numpy array):
Histogram bin edge positions.
"""
# Histogram figure with 1-nm bins
histfig = plt.figure()
histaxes = histfig.add_subplot(111)
hist_values, bin_edges = histaxes.hist(
distances,
bins=np.arange(fitlength + 1),
weights=np.repeat(float(fitlength) / len(distances),
len(distances)
),
color=color, alpha=0.5
)[0:2] # 2 not required
histaxes.set_xlim([0, fitlength])
histaxes.set_title('Histogram')
histaxes.set_xlabel(r'$\Delta$XYZ (nm)')
histaxes.set_ylabel('Counts (scaled: mean = 1)')
return hist_values, bin_edges
def plot_distance_hist_and_fit(distances,
fitlength,
params_optimised,
params_covar,
model_with_info,
plot_95ci=False,
color='xkcd:red'):
# Use only distances within fitlength
distances = distances[distances <= fitlength]
fig = plt.figure()
axes = plt.subplot(111)
histogram_output = axes.hist(distances,
bins=np.arange(fitlength + 1),
weights=np.repeat(float(fitlength)
/ len(distances),
len(distances)
),
color='gray', alpha=0.5
)
bin_edges = histogram_output[1]
bin_centres = (bin_edges[0:(len(bin_edges) - 1)] + bin_edges[1:]) / 2
axes.plot(distances,
model_with_info.model_rpd(distances, *params_optimised),
color=color,
lw=0.75
)
axes.set_xlim([0, fitlength])
axes.set_xlabel(r'$\Delta$XYZ (nm)')
axes.set_ylabel('Counts (scaled: mean = 1)')
axes.set_title('Model: ' +model_with_info.model_rpd.__name__)
# Get 1 SD uncertainty on model result from uncertainty on parameters
# and plot 95% CI.
if plot_95ci is True:
stdev = stdev_of_model(bin_centres,
params_optimised,
params_covar,
model_with_info.vector_input_model
)
axes.fill_between(bin_centres,
model_with_info.model_rpd(bin_centres,
*params_optimised)
- stdev * 1.96,
model_with_info.model_rpd(bin_centres,
*params_optimised)
+ stdev * 1.96,
facecolor=color,
alpha=0.25
)
return fig, axes
def plot_model_components_tri_prism(fitlength,
side_length,
locamp, locprec,
structamp, spread,
substructamp, substructspread,
gridspace, gridamp, gridspread,
bgslope):
"""
fitlength: distance upto to which the model fit was performed
side_length: side length of the triangular prism (all sides equal)
locamp: Amplitude of sinlge molecule localisation precision component
locprec: Average single molecule localisation precision
structamp: Amplitude of components reflecting the structural features
of the complex.
spread: Spread owing to unresolvable complexity or inhomogeneity between
complexes.
substructamp: Amplitude of component reflecting unresolvable substructure
at one vertex.
substructspread: Spread in localisations at one vertex, as a result of
unresolvable substructure there.
gridspace: The spacing of a square grid the complexes are found on.
gridamp: Amplitude of components reflecting the nieghbouring complexes at
nearby grid points.
gridspread: Spread owing to different orientation at different grid points.
bgslope: Approximate background to 2D (relatively flat); this is the
linear slope.
"""
distance_values = np.arange(0, fitlength + 1, 1)
fig = plt.figure()
axes = plt.subplot(111)
axes.set_xlim([0, fitlength])
axes.set_xlabel(r'$\Delta$XYZ (nm)')
axes.set_ylabel('Counts (scaled: mean = 1)')
axes.set_title('Model: Triangular pyramid, equal side lengths')
# Background term
bg_term = distance_values * bgslope
plt.plot(distance_values, bg_term)
# Repeated localisations term
rep_locs_term = (locamp
* models.pairwise_correlation_3d(distance_values,
0.,
np.sqrt(2) * locprec
)
)
plt.plot(distance_values, rep_locs_term)
# Plot substructure term
substructure_term = (substructamp
* models.pairwise_correlation_3d(distance_values,
0.,
np.sqrt(2) * locprec
)
)
plt.plot(distance_values, substructure_term)
# Triangular prism peaks:
# Set up triangular prism
verts = poly.tri_prism_vertices(side_length, side_length)
relpos = poly.get_1d_relpos_no_filter(verts)
# Get unique distances
xyz_distances = np.sqrt(relpos[:, 0] ** 2 + relpos[:, 1] ** 2 + relpos[:, 2] ** 2)
xyz_distances = np.unique(xyz_distances)
# Two peaks:
# 3 x shorter distance x 6 vertices
tri_prism_peak_1 = (18 * structamp
* models.pairwise_correlation_3d(distance_values,
xyz_distances[0],
spread
)
)
plt.plot(distance_values, tri_prism_peak_1)
# 2 x longer distance x 6 vertices
tri_prism_peak_2 = (12 * structamp
* models.pairwise_correlation_3d(distance_values,
xyz_distances[1],
spread
)
)
plt.plot(distance_values, tri_prism_peak_2)
# Plot square grid componenet
square_grid_component = (
gridamp * models.pairwise_correlation_2d(distance_values,
gridspace,
gridspread
)
+ gridamp * models.pairwise_correlation_2d(distance_values,
gridspace * np.sqrt(2),
gridspread
)
)
plt.plot(distance_values, square_grid_component)
# Plot total model
total_model = (bg_term