-
Notifications
You must be signed in to change notification settings - Fork 0
/
mda.py
executable file
·2461 lines (2110 loc) · 89 KB
/
mda.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
#!/usr/bin/python
"""This program performs a multipole decomposition analysis of the data and
options given in the configuration file. First it finds starting points using
the BFGS algorithm from a variety of starting positions given in the config
file. Then it takes those starting points, refines them and finds parameter
errors using the Markov Chain Monte Carlo technique, specifically the python
implementation of Goodman & Weare's Affine Invariant MCMC ensemble sampler
which is in the emcee package
This program can be invoked with:
./mda.py configuration_file
or
python mda.py configuration_file
Parameters
----------
config_file : string
This is the file that fills out the configuration and run details of the
MCMC that needs to be run. For details of what needs to be in the config
file, see config_example.py, which came with the repository, for more
information
Returns
-------
"""
import os
import ctypes as ct
import multiprocessing
import sys
import math
import copy
import emcee
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import corner
import numpy as np
from scipy import interpolate
from scipy import optimize
# firsts we check the command line and grab the module name
if len(sys.argv) != 2:
print "\nUsage:\n\t./mda.py configuration_file\n\t or"
print "\tpython mda.py configuration_file\n"
sys.exit()
# now we test for file existence
if not os.path.exists(sys.argv[1]):
print "Error: File {0:s} does not exist".format(sys.argv[1])
sys.exit()
# now set up and use the execfile function to read the parameters
TEMP_PARAMS = {}
execfile(sys.argv[1], TEMP_PARAMS)
CONFIG = TEMP_PARAMS["CONFIG"]
FLOAT_EPSILON = 1.0e-7
PLOT_FORMAT_LIST = ["svg", "svgz", "pdf", "ps", "eps", "png"]
def main():
"""performs sanity checks on the configuration data and then calls the
functions that do the work
Parameters
----------
Global Parameters
-----------------
CONFIG : dictionary
This uses the CONFIG global dictionary that was read in at program
start. It uses the 'Number of Threads', 'Sample Points',
'Burn-in Points', 'Confidence Interval', 'Number of Walkers',
'Maximum L', 'EWSR Fractions', 'Start Pts a%d',
'Number Walker Generators', and 'Plot Format', keys
Returns
-------
"""
# check that the user gave sane information
# check that they are not requesting greater concurrency than the
# system supports
cpu_count = multiprocessing.cpu_count()
if CONFIG["Number of Threads"] > cpu_count:
print "\nInvalid number of threads, on this machine it must be: "
print 'CONFIG["Number of Threads"] <= {0:d}\n'.format(cpu_count)
sys.exit()
# check if the user set the sampling high enough for the error bars wished
num_samples = ((CONFIG["Sample Points"] - CONFIG["Burn-in Points"]) *
CONFIG["Number of Walkers"])
samples_needed = int(math.ceil(10.0 /
((1.0 - CONFIG["Confidence Interval"]) /
2.0)))
if samples_needed > num_samples:
print SAMPLES_ERROR.format(num_samples, CONFIG["Sample Points"],
CONFIG["Burn-in Points"],
CONFIG["Number of Walkers"], samples_needed,
CONFIG["Confidence Interval"])
sys.exit()
# make sure that the number of walkers for time series plots does not
# exceed the number of walkers
if CONFIG["Number of Walkers"] < CONFIG["Walker Plot Count"]:
print 'CONFIG["Number of Walkers"] must exceed '\
'CONFIG["Walker Plot Count"]'
sys.exit()
# make certain the user gave enough EWSR fractions for the max L
num_dists = (1 + CONFIG["Maximum L"])
if len(CONFIG["EWSR Fractions"]) > num_dists:
print TOO_MANY_EWSR_ERROR.format(num_dists,
len(CONFIG["EWSR Fractions"]))
sys.exit()
elif len(CONFIG["EWSR Fractions"]) < num_dists:
print TOO_FEW_EWSR_ERROR.format(num_dists,
len(CONFIG["EWSR Fractions"]))
sys.exit()
# make sure as many corner plot bins as fit params were supplied
if len(CONFIG["Corner Plot Bins"]) > num_dists:
print TOO_MANY_BINS_ERROR.format(num_dists,
len(CONFIG["Corner Plot Bins"]))
sys.exit()
elif len(CONFIG["Corner Plot Bins"]) < num_dists:
print TOO_FEW_BINS_ERROR.format(num_dists,
len(CONFIG["Corner Plot Bins"]))
sys.exit()
# check to make certain that there are at least 10 start points
len_array = [len(CONFIG["Start Pts a{0:d}".format(i)]) for i in
range(num_dists)]
num_cells = 1
for size in len_array:
num_cells *= size
if num_cells < CONFIG["Number Walker Generators"]:
out_str = NUM_STARTS_ERROR.format(CONFIG["Number Walker Generators"])
print out_str
sys.exit()
# check to make certain that the given file format is one of the
# supported formats
if not CONFIG["Plot Format"] in PLOT_FORMAT_LIST:
print "\nThe chosen plot output format is not supported."
print "The supported values for this option are:"
print PLOT_FORMAT_LIST, "\n"
sys.exit()
# call the function that calls everything else
initialize_mda()
def initialize_mda():
"""does the work of the program, reads in all the data and distributions
subtracts all the ivgdr components if needed then calls the functions
that do the initial fitting and then the sampling
Parameters
----------
Global Parameters
-----------------
CONFIG : dictionary
This uses the CONFIG global dictionary that was read in at program
start. It uses the 'Maximum L', and 'Number of Threads' keys
Returns
-------
"""
print STARTUP_MSG
# read the raw data
(exp_data, plot_data) = read_row_cs_data_file()
# now read and subtract the IVGDR data
ivgdr_info = handle_ivgdr(exp_data)
# sub_data = ivgdr_info[2]
# print ivgdr_dists[0], '\n', ivgdr_ewsr[0], '\n', ivgdr_info[2][0]
# now read the distributions that are used to fit the data
dists = [[read_dist(elem[0], i) for i in range(CONFIG["Maximum L"] + 1)]
for elem in exp_data]
print "Distributions read in"
# now interpolate the distributions to get the values at the angles in data
interp_dists = interp_all_dists(dists, exp_data)
print "Distributions interpolated and prepared for fitting"
# now get the data divided by errors without angle values
fit_data = [(exp_en[1][:, 1]/exp_en[1][:, 2]) for exp_en in ivgdr_info[2]]
print "Experimental data prepared for fitting"
# calculate the starting parameter sets for initial searches
start_params = calc_start_params()
print "Finished calculating parameter starting point list"""
# now interleave things so we are ready to use pool.map across everything
interleaved_data = [(exp_data[i][0], fit_data[i], interp_dists[i],
start_params) for i in range(len(fit_data))]
print "Data is interleaved"
generate_output_dirs()
mp_pool = multiprocessing.Pool(processes=CONFIG["Number of Threads"])
print MDA_START_MSG.format(CONFIG["Number of Threads"])
fitted_data = mp_pool.map(fit_and_mcmc, interleaved_data)
# single threaded version for debugging
# fitted_data = map(fit_and_mcmc, interleaved_data)
# write the individual fits to csv files
parameters = [dat[0] for dat in fitted_data]
diag_data = [dat[1] for dat in fitted_data]
if CONFIG["Generate Fit CSVs"]:
print "Writing fit files"
write_fits(plot_data, dists, parameters, ivgdr_info)
else:
print "Skipping fit files"
# make the fit plots
if CONFIG["Generate Fit Plots"]:
print "Writing fit plots"
make_fit_plots(plot_data, dists, parameters, ivgdr_info)
else:
print "Skipping fit plots"
# write the two parameter sets
energy_set = [val[0] for val in exp_data]
print "Writing parameter sets"
write_param_sets(parameters, energy_set)
# write the parameter plots
if CONFIG["Generate Parameter Plots"]:
print "Writing parameter plots"
write_param_plots(parameters, energy_set)
else:
print "Skipping parameter plots"
# write the diagnostic information
print "Writing diagnostic information"
write_diagnostic_csv(diag_data, exp_data)
# and now we are completely done
print "MDA and output complete"
def write_diagnostic_csv(diag_data, exp_dat):
"""This function takes the diagnostic data generated in the fit process and
writes it to a csv for assessment
Parameters
----------
diag_data : list
The a list of the diagnostic data for each fit
exp_dat : list
The experimental data for each energy that was fitted
Global Parameters
-----------------
CONFIG : dictionary
This uses the CONFIG global dictionary that was read in at program
start. It uses the 'Maximum L', 'Calc AutoCorr', and 'Target A' keys
Returns
-------
"""
num_params = CONFIG["Maximum L"] + 1
# for each angular distribution, calculate how many points there are
num_pts = [len(dat[1]) for dat in exp_dat]
# generate the output file
file_name = "A{0:d}_diagnostics.csv".format(CONFIG["Target A"])
file_path = os.path.join(CONFIG["Parameter Files Directory"], file_name)
outfile = open(file_path, 'w')
# now write the csv header
outfile.write("Ex Energy, , Percentile Chi^2, Peak Chi^2, Num Fitted ")
outfile.write("Data Points, Num Params, Num DoF, , Acceptance Fraction")
if CONFIG['Calc AutoCorr']:
outfile.write(', , NumIndSamples, Dist Error, ')
for i in range(num_params):
outfile.write(", a{0:d} AutoCorr Time".format(i))
outfile.write('\n')
num_samps = CONFIG["Number of Walkers"]*(CONFIG["Sample Points"] -
CONFIG["Burn-in Points"])
# now move through the fit data and write out all the columns
# (acor_time, chis, accept_frac)
for i, diag in enumerate(diag_data):
outfile.write('{0:f}, , {1:f}, {2:f}'.format(exp_dat[i][0], diag[1][0],
diag[1][1]))
dof = (num_pts[i] - num_params)
outfile.write(', {0:d}, {1:d}, {2:d}'.format(num_pts[i], num_params,
dof))
outfile.write(', , {0:f}'.format(diag[2]))
if CONFIG['Calc AutoCorr']:
indsamps = float(num_samps)/max(diag[0])
err = 1.0/math.sqrt(indsamps)
outfile.write(', {0:f}, {1:f}, '.format(indsamps, err))
for accfrac in diag[0]:
outfile.write(", {0:f}".format(accfrac))
outfile.write('\n')
outfile.close()
def write_param_plots(parameters, energy_set):
"""This function takes the generated parameters and makes the plots for
each L of the parameters
Parameters
----------
parameters : list
The full set of parameter sets, for all the runs, from both parameter
set finding methodologies
energy_set : list of floats
The list of excitation energies for each run
Global Parameters
-----------------
CONFIG : dictionary
This uses the CONFIG global dictionary that was read in at program
start. It uses the 'Maximum L', 'Param Plot Dirs', 'Target A', and
'Plot Format' keys
Returns
-------
"""
# loop through each set of parameters
for i in range((CONFIG["Maximum L"]+1)):
# first split the data into the two types
perc_data = [pset[0][i] for pset in parameters]
peak_data = [pset[1][i] for pset in parameters]
# calculate the two file names
fmt_str = "A{0:d}_L{1:d}_{2:s}_parameters.{3:s}"
file_name = fmt_str.format(CONFIG["Target A"], i, "percentile",
CONFIG["Plot Format"])
perc_path = os.path.join(CONFIG["Param Plot Dirs"][0], file_name)
file_name = fmt_str.format(CONFIG["Target A"], i, "peak",
CONFIG["Plot Format"])
peak_path = os.path.join(CONFIG["Param Plot Dirs"][1], file_name)
make_param_plot(perc_path, perc_data, energy_set, i)
make_param_plot(peak_path, peak_data, energy_set, i)
def make_param_plot(path, params, energy_set, l_value):
"""This takes a set of parameters for a given L, the energies they are from
and generates a plot of those parameters. It then writes that plot to the
specified path
Parameters
----------
path : string
The file path for this plot
params : list of floats
One set of parameters for each run
energy_set : list of floats
The list of excitation energies for each run
l_value : int
The orbital angular momentum of the GR this plot is for
Global Parameters
-----------------
CONFIG : dictionary
This uses the CONFIG global dictionary that was read in at program
start. It uses the 'Plot Height', 'Plot Width', and 'Plot DPI' keys
FLOAT_EPSILON : float
A very small value that is the threshold for "two float are the same"
Returns
-------
"""
pt_x_vals = np.array(energy_set)
param_array = np.array(params)
pt_y_vals = param_array[:, 0]
pt_e_vals = [param_array[:, 1], param_array[:, 2]]
hi_vals = pt_y_vals + pt_e_vals[0]
# make the figure and stuff
fig, axes = plt.subplots()
# set up the axes
axes.set_yscale('linear')
axes.set_xscale('linear')
# plot the data
axes.errorbar(pt_x_vals, pt_y_vals, yerr=pt_e_vals, fmt="ko",
label=r"$Exp$", markersize=2.0)
# set the axis limits
axes.set_xlim((pt_x_vals.min() - 1.0), (pt_x_vals.max() + 1.0))
y_max = 1.2 * hi_vals.max()
if y_max < FLOAT_EPSILON:
y_max = 0.01
axes.set_ylim(0.0, y_max)
# label the axes
axes.set_xlabel('Excitation Energy (MeV)')
axes.set_ylabel(r'$a_{{{0:d}}}$'.format(l_value))
fig.suptitle(r'MDA Results for L={0:d}'.format(l_value))
# make the legend
# legend = axes.legend(loc='right', bbox_to_anchor=(1.2, 0.5), ncol=1)
legend = axes.legend(loc='upper left', ncol=1)
legend.get_frame().set_facecolor("white")
# save and close the figure
fig.set_size_inches(CONFIG["Plot Height"], CONFIG["Plot Width"])
# fig.savefig(path, additional_artists=[legend], bbox_inches='tight')
fig.savefig(path, bbox_inches='tight', dpi=CONFIG["Plot DPI"])
plt.close(fig)
def write_param_sets(parameters, energy_set):
"""This function takes the generated parameters and writes the sets from
percentiles and the sets from peak find to seperate files
Parameters
----------
parameters : list
Both types of parameter sets from each run and their associated errors
energy_set : list of floats
The list of excitation energies for each run
Global Parameters
-----------------
CONFIG : dictionary
This uses the CONFIG global dictionary that was read in at program
start. It uses the 'Parameter Files Directory' and 'Target A' keys
Returns
-------
"""
# first split the data into the two types
perc_data = [pset[0] for pset in parameters]
peak_data = [pset[1] for pset in parameters]
# generate the file names
fmt_str = "A{0:d}_{1:s}_parameters.csv"
file_name = fmt_str.format(CONFIG["Target A"], "percentile")
perc_path = os.path.join(CONFIG["Parameter Files Directory"], file_name)
file_name = fmt_str.format(CONFIG["Target A"], "peak")
peak_path = os.path.join(CONFIG["Parameter Files Directory"], file_name)
# now call the function that writes a parameter set
write_horizontal_param_file(perc_path, perc_data, energy_set, "percentile")
write_horizontal_param_file(peak_path, peak_data, energy_set, "peak find")
def write_horizontal_param_file(path, params, energy_set, ptype):
"""This function takes a set of parameters and their corresponding energies
and writes the data to the specified path
Parameters
----------
path : string
The file path for this csv
params : list of floats
A parameter set and its errors
energy_set : list of floats
The list of excitation energies for each run
ptype : string
The type of fit used to extract the parameter values
Global Parameters
-----------------
Returns
-------
"""
# open the file for writing
out_file = open(path, 'w')
# write the header
out_file.write(generate_param_file_header(ptype))
# write each line of parameters and energies
for i, param in enumerate(params):
out_file.write(gen_param_file_line(energy_set[i], param))
# close the file we wrote
out_file.close()
def gen_param_file_line(energy, params):
"""This function takes the excitation energy and the parameters for that
energy and generates the string to be written to the file
Parameters
----------
energy : float
The excitation energy of the parameter set
params : list of floats
A parameter set and its errors
Global Parameters
-----------------
CONFIG : dictionary
This uses the CONFIG global dictionary that was read in at program
start. It uses the 'Maximum L' key
Returns
-------
out_str : string
line of parameters written out in the csv format
"""
out_str = ("{0:f}, , ".format(energy))
for i in range((CONFIG["Maximum L"]+1)):
out_str += "{0:f}, {1:f}, {2:f}, , ".format(*params[i])
out_str += "\n"
return out_str
def generate_param_file_header(ptype):
"""This function uses config information to generate an appropriate header
for the parameter file
Parameters
----------
ptype : string
The type of fit used to extract the parameter values
Global Parameters
-----------------
CONFIG : dictionary
This uses the CONFIG global dictionary that was read in at program
start. It uses the 'Maximum L' key
Returns
-------
out_str : string
Header for the CSV file that will be output for the summary of param
values
"""
out_str = "MDA parameters extracted with {0:s} techniques\n".format(ptype)
hrow1 = "Excitation, , "
hrow2 = "Energy, , "
for i in range((CONFIG["Maximum L"]+1)):
hrow1 += "a{0:d}, a{0:d}, a{0:d}, , ".format(i)
hrow2 += "Value, Pos. Err, Neg. Err., , "
out_str += hrow1
out_str += "\n"
out_str += hrow2
out_str += "\n"
return out_str
def make_fit_plots(data, dists, parameters, ivgdr_info):
"""This function takes everything and generates the plots for individual
fits at each energy
Parameters
----------
data : list of lists
List of excitation energies and associated experimental data for each
run
dists : list of lists of numpy arrays
List of DWBA distributions for each run
parameters : list of lists of floats
List of parameter sets derived with both methods for each run
ivgdr_info : list of lists
List of IVGDR distributions and ewsr fractions for each run
Global Parameters
-----------------
CONFIG : dictionary
This uses the CONFIG global dictionary that was read in at program
start. It uses the 'Subtract IVGDR', 'Fit Plot Dirs', 'Target A',
'Plot Format', 'Fit Plot L Limit', and 'Plot IVGDR in Fits' keys
Returns
-------
"""
# first make the directory names
legend = [r"$Fit$"]
for i in range(len(parameters[0][0])):
legend.append(r"$l_{{{0:d}}}$".format(i))
# loop through each set of data and distributions
for i, dat in enumerate(data):
# extract the things pertinet to this set from the arguments
energy = dat[0]
dist_set = copy.deepcopy(dists[i])
param_set = list(copy.deepcopy(parameters[i]))
exp_points = dat[1]
# handle ivgdr
if CONFIG["Subtract IVGDR"]:
dist_set.append(ivgdr_info[0][i])
param_set.append((ivgdr_info[1][i], 0.0, 0.0))
legend.append(r"$l_{-1}$")
# loop through the plots to generate
for ind in range(2): # peaks or percentiles?
# choose our parameter set and generate the three sets of fits
pset = gen_param_sets_for_fit_plot(param_set[ind])
for k in range(3): # params-lo_errs, params, params+hi_errs
sc_dists = gen_fit_dists(pset[k], dist_set)
for j in range(2): # full or limitted
fmt_str = "A{0:d}_E{1:05.2f}.{2:s}"
file_name = fmt_str.format(CONFIG["Target A"], energy,
CONFIG["Plot Format"])
dind = 6 * ind + 3 * j + k
plt_path = os.path.join(CONFIG["Fit Plot Dirs"][dind],
file_name)
# now decide how much of the distributions to call the
# gen fit plot function on
if j == 1:
gen_fit_plot(exp_points, energy,
sc_dists[:(CONFIG["Fit Plot L Limit"]+2)],
legend[:(CONFIG["Fit Plot L Limit"]+2)],
plt_path)
elif (CONFIG["Subtract IVGDR"] and
not CONFIG["Plot IVGDR in Fits"]):
gen_fit_plot(exp_points, energy,
sc_dists[:(len(sc_dists)-1)],
legend[:(len(sc_dists)-1)],
plt_path)
else:
gen_fit_plot(exp_points, energy,
sc_dists[:len(sc_dists)],
legend[:len(sc_dists)],
plt_path)
def gen_param_sets_for_fit_plot(params):
"""This function takes a single set of parameters and generates three sets
of parameters, the first, decreased by the lower error bar, the second
equal to the parameter fit value, and the third, increased by the upper
error bar
Parameters
----------
params : list of tuples
This is the list of parameter values of their errors bars, either
derived from the peak method or the quantile method
Global Parameters
-----------------
Returns
-------
parameter_bounds : list of tuples
This is a list of three parameter sets, the first is all params reduced
by one error bar, the second is the params, the third is the params
increased by one error bar
"""
temp = [[(vals[0] - vals[2]) for vals in params],
[vals[0] for vals in params],
[(vals[0] + vals[1]) for vals in params]]
for pset in temp:
for param in pset:
if param < 0.0:
print "Got a negative parameter when subtracting errors from"
print "parameters for fit plots, this should not be possible"
sys.exit()
param = 0.0
return temp
def gen_fit_plot(points, energy, dists, legends, plot_name):
"""This function takes the list of points with errors in the points var
and the list of distributions to plot in the dists var and generates a
nicely formatted matplotlib plot displaying them
Parameters
----------
points : list of floats
Experimental data for one energy
energy : float
Excitation energy of the data
dists : list of numpy arrays
List of dwba distributions
legends : list of strings
List of names of the points and distributions
plot_name : string
output path of the plot
Global Parameters
-----------------
CONFIG : dictionary
This uses the CONFIG global dictionary that was read in at program
start. It uses the 'Subtract IVGDR', 'Fit Plot Dirs', 'Target A',
'Plot Format', 'Fit Plot L Limit''Plot Height', 'Plot Width',
'Plot DPI', and 'Plot IVGDR in Fits' keys
Returns
-------
"""
# since the first distribution is always the plot then the first style will
# always be a solid red line, no other distribution is red and solid
line_styles = ["r-", "b--", "g-.", "c:", "m--", "y-.", "b:", "g--", "c-.",
"m:", "y--", "b-.", "g:", "c--", "m-.", "y:"]
pt_x_vals = points[:, 0]
pt_y_vals = points[:, 1]
pt_e_vals = points[:, 2]
fig, axes = plt.subplots()
axes.set_yscale('log', subsy=[2, 3, 4, 5, 6, 7, 8, 9])
axes.set_xscale('linear')
# plot the points
axes.errorbar(pt_x_vals, pt_y_vals, yerr=pt_e_vals, fmt="ko",
label=r"$Exp$", markersize=2.0)
# plot the distributions
for i, dis in enumerate(dists):
axes.plot(dis[:, 0], dis[:, 1],
line_styles[i % len(line_styles)], label=legends[i])
# set the scale of the x axis
axes.set_xlim(0.0, math.ceil(pt_x_vals.max()))
# set the scale of the y axis
(ymin_val, ymax_val) = find_y_extrema(pt_y_vals.max(), dists,
math.ceil(pt_x_vals.max()))
axes.set_ylim(ymin_val, ymax_val)
# label the axes
axes.set_xlabel(r'Lab Angle $(^{\circ{}})$')
axes.set_ylabel(r'$(\partial^2 \sigma)/(\partial \Omega \partial E)$'
' ($mb/(sr*MeV)$)')
fig.suptitle(r"MDA Fit for E$_x$={0:4.2f} MeV".format(energy))
# make the legend
legend = axes.legend(loc='right', bbox_to_anchor=(1.2, 0.5), ncol=1)
legend.get_frame().set_facecolor("white")
# save and close the figure
fig.set_size_inches(CONFIG["Plot Height"], CONFIG["Plot Width"])
fig.savefig(plot_name, additional_artists=[legend], bbox_inches='tight',
dpi=CONFIG["Plot DPI"])
plt.close(fig)
def find_y_extrema(data_max, dists, xmax):
"""This function scans the distributions provided searching for the minimum
value with angle less than xmax, it also looks to find the maximum value
(be it in a distribution or the data maximum it then returns
(10^(floor(log(ymin))), 10^(ceiling(log(ymax)))
Parameters
----------
data_max : float
The maximum cross-section in the experimental data
dists : list of numpy arrays
The set of distributions for this MCMC
xmax : float
the maximum angle that will be plotted
Global Parameters
-----------------
Returns
-------
plot_min : float
A suggested minimum value for plot y axes
plot_max : float
A suggested maximum value for plot y axes
"""
current_min = 100000000000.0
current_max = data_max
for dist in dists:
for point in dist:
if point[0] > xmax:
break
if point[1] < current_min and point[1] > 0.0:
current_min = point[1]
elif point[1] > current_max:
current_max = point[1]
log_min = math.floor(2.0*math.log10(current_min))/2.0
log_max = math.ceil(2.0*math.log10(current_max))/2.0
return (math.pow(10.0, log_min), math.pow(10.0, log_max))
def write_fits(data, dists, parameters, ivgdr_info):
"""This function takes the parameters, distributions, and data, and writes
them to a nicely formatted csv file for usage later
Parameters
----------
data : list of lists
Each element of the list is one MCMC run, each sublist has the ex
energy as the first element, the set of experimental data points as the
second element
dists : list of lists
Each sub list contains the numpy arrays with dwba distributions for one
run of the MCMC
parameters : list of lists
Each sub list contains two lists. The first list in the sublist is the
parameters and their errors as derived from the pure percentile method,
the second is the parameters and their errors as derived from the peak
method
ivgdr_info : list of lists
Each sub list is from one run and contains the following: the IVGDR
distribution as its first element, and the ivgdr EWSR weight as its
second
Global Parameters
-----------------
CONFIG : dictionary
This uses the CONFIG global dictionary that was read in at program
start. It uses the 'Subtract IVGDR', 'Fit Csv Dirs', and 'Target A'
keys
Returns
-------
"""
# first split the data up into individual runs
for i, dat in enumerate(data):
energy = copy.deepcopy(dat[0])
points = copy.deepcopy(dat[1])
dist_set = copy.deepcopy(dists[i])
perc_set = copy.deepcopy(parameters[i][0])
peak_set = copy.deepcopy(parameters[i][1])
# test if we are subtracting the IVGDR
if CONFIG["Subtract IVGDR"]:
dist_set.append(ivgdr_info[0][i])
perc_set.append((ivgdr_info[1][i], 0.0, 0.0))
peak_set.append((ivgdr_info[1][i], 0.0, 0.0))
# calculate the file names
file_name = "A{0:d}_E{1:5.2f}.csv".format(CONFIG["Target A"], energy)
file_paths = [os.path.join(CONFIG["Fit Csv Dirs"][0], file_name),
os.path.join(CONFIG["Fit Csv Dirs"][1], file_name)]
# write the percentile fit
write_fit_csv(file_paths[0], points, perc_set, dist_set, energy)
# write the peak find fit
write_fit_csv(file_paths[1], points, peak_set, dist_set, energy)
def write_fit_csv(path, points, pset, dist_set, energy):
"""This function takes a file path, a set of experimental data, a parameter
set, a set of distributions and the ex energy of the distribution and
writes a nicely formated csv file with all the information in it
Parameters
----------
path : string
the path to the file that will hold this csv data
points : list of floats
the experimental data the MCMC was performed on
pset : list of floats
the parameter set and their errs (be it from peak finding or quantiles)
dist_set : list of numpy arrays
The set of dwba distributions that were scaled and fit to the exp data
when the MCMC was performed
energy : float
The excitation energy of the nucleus that the MCMC was run for
Global Parameters
-----------------
Returns
-------
"""
# first open the file to be written
out_file = open(path, 'w')
# next generate the title and column headings for the file
out_file.write(gen_csv_title_and_headings(energy))
# construct the list of lines in the file
num_lines = len(dist_set[0])
if num_lines < len(points):
num_lines = len(points)
if num_lines < len(pset):
num_lines = len(pset)
csv_list = []
for _ in range(num_lines):
csv_list.append("")
# append the exp data
append_exp_data_to_fit_csv(points, csv_list)
# append a blank column
append_str_to_fit_csv(", ", csv_list)
# append the parameter data
append_parameters_to_fit_csv(pset, csv_list)
# append a blank column
append_str_to_fit_csv(", ", csv_list)
# calculate the scaled distributions
params = [param[0] for param in pset]
scaled_dists = gen_fit_dists(params, dist_set)
# append the distribution angles
append_data_column_to_fit_csv(dist_set[0][:, 0], csv_list)
# append each distribution, and scaled distribution
for i, dis in enumerate(dist_set):
append_data_column_to_fit_csv(dis[:, 1], csv_list)
append_data_column_to_fit_csv(scaled_dists[i+1][:, 1], csv_list)
# append a blank column
append_str_to_fit_csv(", ", csv_list)
# append the fit distribution
append_data_column_to_fit_csv(scaled_dists[0][:, 1], csv_list)
# append the newline characters
append_str_to_fit_csv("\n", csv_list)
# write the csv list
for line in csv_list:
out_file.write(line)
# close the output file
out_file.close()
def append_data_column_to_fit_csv(data, csv_list):
"""This function takes a column of data and appends it to the csv list
Parameters
----------
data : list of floats
the set of data, be it angles, distribution values, etc to append to
the ends of the csv lines
csv_list : list of strings
The list of strings that when complete and written to a file produces
a csv with the appropriate formatting
Global Parameters
-----------------
Returns
-------
"""
for i, sub_csv_list in enumerate(csv_list):
if i < len(data):
sub_csv_list += "{0:f}, ".format(data[i])
else:
sub_csv_list += ", "
def append_parameters_to_fit_csv(pset, csv_list):
"""This function appends a parameter set to the csv list
Parameters
----------
pset : list of floats
the parameter set to append to the lines of the fit csv
csv_list : list of strings
The list of strings that when complete and written to a file produces
a csv with the appropriate formatting
Global Parameters
-----------------
Returns
-------
"""
# first generate the list of names
name_list = []
for i in range(len(pset)):
if CONFIG["Subtract IVGDR"] and i == (len(pset)-1):
name_list.append("a-1")
else:
name_list.append("a{0:d}".format(i))
# now append the names and error bars
fmt_str = "{0:s}, {1:f}, {2:f}, {3:f}, "
for i, csv_sublist in enumerate(csv_list):
if i < len(pset):
csv_sublist += fmt_str.format(name_list[i], pset[i][0],
pset[i][1], pset[i][2])
else:
csv_sublist += ", , , , "
def append_str_to_fit_csv(str_to_append, csv_list):
"""This function appends the given string to the csv_list
Parameters
----------
str_to_append : string
the string to append to every string in the csv_list
csv_list : list of strings
The list of strings that when complete and written to a file produces
a csv with the appropriate formatting
Global Parameters
-----------------
Returns
-------
"""
for csv_sublist in csv_list:
csv_sublist += str_to_append
def append_exp_data_to_fit_csv(points, csv_list):
"""This function takes an experimental data set and the csv list and writes
the data to the csv list along with a set of appropriately blank lines
Parameters
----------
points : list of floats
the list of angles, data, and erroros to be appended to each of the
lines in csv_list
csv_list : list of strings
The list of strings that when complete and written to a file produces
a csv with the appropriate formatting
Global Parameters
-----------------
Returns
-------
"""
fmt_str = "{0:f}, {1:f}, {2:f}, "
for i, csv_sublist in enumerate(csv_list):
if i < len(points):
csv_sublist += fmt_str.format(points[i][0], points[i][1],
points[i][2])
else:
csv_sublist += " , , , "
def gen_csv_title_and_headings(energy):
"""This function takes the excitation energy and returns a string with the
csv title, and column headings
Parameters
----------
energy : float
The excitation energy at which this decomposition was performed
Global Parameters
-----------------
CONFIG : dictionary
This uses the CONFIG global dictionary that was read in at program
start. It uses the 'Maximum L' key