-
Notifications
You must be signed in to change notification settings - Fork 50
/
plots.py
2503 lines (2226 loc) · 123 KB
/
plots.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
from __future__ import absolute_import
from __future__ import print_function
import os
import copy
import matplotlib
import sys
import six
import warnings
matplotlib.use('Agg', warn=False)
from matplotlib import cm, rcParams
import matplotlib.pyplot as plt
import numpy as np
from paramgrid import gridconfig, batchjob
import getdist
from getdist import MCSamples, loadMCSamples, ParamNames, ParamInfo, IniFile
from getdist.paramnames import escapeLatex
from getdist.parampriors import ParamBounds
from getdist.densities import Density1D, Density2D
from getdist.gaussian_mixtures import MixtureND
import logging
"""Plotting scripts for GetDist outputs"""
def makeList(roots):
"""
Checks if the given parameter is a list, If not, Creates a list with the parameter as an item in it.
:param roots: The parameter to check
:return: A list containing the parameter.
"""
if isinstance(roots, (list, tuple)):
return roots
else:
return [roots]
class GetDistPlotError(Exception):
"""
An exception that is raised when there is an error plotting
"""
pass
class GetDistPlotSettings(object):
"""
Settings class (colors, sizes, font, styles etc.)
:ivar alpha_factor_contour_lines: alpha factor for adding contour lines between filled contours
:ivar alpha_filled_add: alpha for adding filled contours to a plot
:ivar auto_ticks: use matplotlib 2+ auto tick spacing/numbers (default: False, use own heuristics)
:ivar axis_marker_color: The color for a marker
:ivar axis_marker_ls: The line style for a marker
:ivar axis_marker_lw: The line width for a marker
:ivar colorbar_label_pad: padding for the colorbar labels
:ivar colorbar_label_rotation: angle to rotate colorbar label (set to zero if -90 default gives layout problem)
:ivar colorbar_rotation: angle to rotate colorbar tick labels
:ivar colormap: a `Matplotlib color map <http://www.scipy.org/Cookbook/Matplotlib/Show_colormaps>`_ for shading
:ivar colormap_scatter: a `Matplotlib color map <http://www.scipy.org/Cookbook/Matplotlib/Show_colormaps>`_ for 3D plots
:ivar default_dash_styles: dict mapping line styles to detailed dash styles, default: {'--': (3, 2), '-.': (4, 1, 1, 1)}
:ivar fig_width_inch: The width of the figure in inches
:ivar figure_legend_frame: draw box around figure legend
:ivar figure_legend_loc: The location for the figure legend
:ivar figure_legend_ncol: number of columns for figure legend
:ivar legend_fontsize: The font size for the legend
:ivar legend_frac_subplot_line: fraction of _subplot size to use per line for spacing figure legend
:ivar legend_frac_subplot_margin: fraction of _subplot size to use for spacing figure legend above plots
:ivar legend_frame: draw box around legend
:ivar legend_loc: The location for the legend
:ivar legend_position_config: recipe for positioning figure border (default 1)
:ivar legend_rect_border: whether to have black border around solid color boxes in legends
:ivar line_labels: True if you want to automatically add legends when adding more than one line to subplots
:ivar lineM: list of default line styles/colors (['-k','-r'...])
:ivar no_triangle_axis_labels: whether subplots in triangle plots should show axis labels if not at the edge
:ivar norm_prob_label: label for the y axis in normalized 1D density plots
:ivar num_plot_contours: number of contours to plot in 2D plots (up to number of contours in analysis settings)
:ivar num_shades: number of distinct colors to use for shading shaded 2D plots
:ivar param_names_for_labels: file name of .paramnames file to use for overriding parameter labels for plotting
:ivar plot_args: dict, or list of dicts, giving settings like color, ls, alpha, etc. to apply for a plot or each line added
:ivar plot_meanlikes: include mean likelihood lines in 1D plots
:ivar prob_label: label for the y axis in unnormalized 1D density plots
:ivar prob_y_ticks: show ticks on y axis for 1D density plots
:ivar progress: write out some status
:ivar shade_level_scale: shading contour colors are put at [0:1:spacing]**shade_level_scale
:ivar shade_meanlikes: 2D shading uses mean likelihoods rather than marginalized density
:ivar solid_colors: List of default colors for filled 2D plots. Each element is either a color, or a tuple of values for different contour levels.
:ivar solid_contour_palefactor: factor by which to make 2D outer filled contours paler when only specifying one contour colour
:ivar thin_long_subplot_ticks: if auto_tick=False, whether to thin out tick labels where they are long to try to prevent overlap (default: True)
:ivar tick_prune: None, 'upper' or 'lower' to prune ticks
:ivar tight_gap_fraction: fraction of plot width for closest tick to the edge
:ivar tight_layout: use tight_layout to lay out and remove white space
:ivar x_label_rotation: The rotation for the x label in degrees.
"""
def __init__(self, subplot_size_inch=2, fig_width_inch=None):
"""
If fig_width_inch set, fixed setting for fixed total figure size in inches.
Otherwise use subplot_size_inch to determine default font sizes etc.,
and figure will then be as wide as necessary to show all subplots at specified size.
:param subplot_size_inch: Determines the size of subplots, and hence default font sizes
:param fig_width_inch: The width of the figure in inches, If set, forces fixed total size.
"""
self.plot_meanlikes = False
self.shade_meanlikes = False
self.prob_label = None
# self.prob_label = 'Probability'
self.norm_prob_label = 'P'
self.prob_y_ticks = False
self.lineM = ['-k', '-r', '-b', '-g', '-m', '-c', '-y', '--k', '--r', '--b', '--g',
'--m'] # : line styles/colors
self.plot_args = None
self.solid_colors = ['#006FED', '#E03424', 'gray', '#009966', '#000866', '#336600', '#006633', 'm',
'r']
self.default_dash_styles = {'--': (3, 2), '-.': (4, 1, 1, 1)}
self.line_labels = True
self.x_label_rotation = 0
self.num_shades = 80
self.shade_level_scale = 1.8 # contour levels at [0:1:spacing]**shade_level_scale
self.fig_width_inch = fig_width_inch # if you want to force specific fixed width
self.progress = False
self.tight_layout = True
self.no_triangle_axis_labels = True
# see http://www.scipy.org/Cookbook/Matplotlib/Show_colormaps
self.colormap = "Blues"
self.colormap_scatter = "jet"
self.colorbar_rotation = None # e.g. -90
self.colorbar_label_pad = 0
self.colorbar_label_rotation = -90 # seems to cause problems with some versions, can set to zero
self.setWithSubplotSize(subplot_size_inch)
self.param_names_for_labels = None
self.tick_prune = None # 'lower' or 'upper'
self.tight_gap_fraction = 0.13 # space between ticks and the edge
self.legend_loc = 'best'
self.figure_legend_loc = 'upper center'
self.legend_frame = True
self.figure_legend_frame = True
self.figure_legend_ncol = 1
self.legend_rect_border = False
self.legend_position_config = 1
self.legend_frac_subplot_margin = 0.2
self.legend_frac_subplot_line = 0.1
self.legend_fontsize = None
self.num_plot_contours = 2
self.solid_contour_palefactor = 0.6
self.alpha_filled_add = 0.85
self.alpha_factor_contour_lines = 0.5
self.axis_marker_color = 'gray'
self.axis_marker_ls = '--'
self.axis_marker_lw = 0.5
self.auto_ticks = False
self.thin_long_subplot_ticks = True
def setWithSubplotSize(self, size_inch=3.5, size_mm=None):
"""
Sets the subplot's size, either in inches or in millimeters.
If both are set, uses millimeters.
:param size_inch: The size to set in inches; is ignored if size_mm is set.
:param size_mm: None if not used, otherwise the size in millimeters we want to set for the subplot.
"""
if size_mm: size_inch = size_mm * 0.0393700787
self.subplot_size_inch = size_inch
self.lab_fontsize = 7 + 2 * self.subplot_size_inch
self.axes_fontsize = 4 + 2 * self.subplot_size_inch
self.legend_fontsize = self.axes_fontsize
self.font_size = self.lab_fontsize
self.lw1 = self.subplot_size_inch / 3.0
self.lw_contour = self.lw1 * 0.6
self.lw_likes = self.subplot_size_inch / 6.0
self.scatter_size = 3
if size_inch > 4: self.scatter_size = size_inch * 2
self.colorbar_axes_fontsize = self.axes_fontsize
if self.colorbar_label_rotation: self.colorbar_label_pad = size_inch * 3
def rcSizes(self, axes_fontsize=None, lab_fontsize=None, legend_fontsize=None):
"""
Sets the font sizes by default from matplotlib.rcParams defaults
:param axes_fontsize: The font size for the plot axes tick labels (default: xtick.labelsize).
:param lab_fontsize: The font size for the plot's axis labels (default: axes.labelsize)
:param legend_fontsize: The font size for the plot's legend (default: legend.fontsize)
"""
self.font_size = rcParams['font.size']
self.legend_fontsize = legend_fontsize or rcParams['legend.fontsize']
self.lab_fontsize = lab_fontsize or rcParams['axes.labelsize']
self.axes_fontsize = axes_fontsize or rcParams['xtick.labelsize']
if isinstance(self.axes_fontsize, six.integer_types):
self.colorbar_axes_fontsize = self.axes_fontsize - 1
else:
self.colorbar_axes_fontsize = 'smaller'
defaultSettings = GetDistPlotSettings()
def getPlotter(**kwargs):
"""
Creates a new plotter and returns it
:param kwargs: arguments for :class:`~getdist.plots.GetDistPlotter`
:return: The :class:`GetDistPlotter` instance
"""
return GetDistPlotter(**kwargs)
def getSinglePlotter(ratio=3 / 4., width_inch=6, **kwargs):
"""
Get a :class:`~.plots.GetDistPlotter` for making a single plot of fixed width.
For a half-column plot for a paper use width_inch=3.464.
Use this or :func:`~getSubplotPlotter` to make a :class:`~.plots.GetDistPlotter` instance for making plots.
If you want customized sizes or styles for all plots, you can make a new module
defining these functions, and then use it exactly as a replacement for getdist.plots.
:param ratio: The ratio between height and width.
:param width_inch: The width of the plot in inches
:param kwargs: arguments for :class:`GetDistPlotter`
:return: The :class:`~.plots.GetDistPlotter` instance
"""
plotter = getPlotter(**kwargs)
plotter.settings.setWithSubplotSize(width_inch)
plotter.settings.fig_width_inch = width_inch
plotter.make_figure(1, xstretch=1. / ratio)
return plotter
def getSubplotPlotter(subplot_size=2, width_inch=None, **kwargs):
"""
Get a :class:`~.plots.GetDistPlotter` for making an array of subplots.
If width_inch is None, just makes plot as big as needed for given subplot_size, otherwise fixes total width
and sets default font sizes etc. from matplotlib's default rcParams.
Use this or :func:`~getSinglePlotter` to make a :class:`~.plots.GetDistPlotter` instance for making plots.
If you want customized sizes or styles for all plots, you can make a new module
defining these functions, and then use it exactly as a replacement for getdist.plots.
:param subplot_size: The size of each subplot in inches
:param width_inch: Optional total width in inches
:param kwargs: arguments for :class:`GetDistPlotter`
:return: The :class:`GetDistPlotter` instance
"""
plotter = getPlotter(**kwargs)
plotter.settings.setWithSubplotSize(subplot_size)
if width_inch:
plotter.settings.fig_width_inch = width_inch
if not kwargs.get('settings'): plotter.settings.rcSizes()
if subplot_size < 3 and kwargs.get('settings') is None and not width_inch:
plotter.settings.axes_fontsize += 2
plotter.settings.colorbar_axes_fontsize += 2
plotter.settings.legend_fontsize = plotter.settings.lab_fontsize + 1
return plotter
class SampleAnalysisGetDist(object):
# Old class to support pre-computed GetDist plot_data output
def __init__(self, plot_data):
self.plot_data = plot_data
self.newPlot()
self.paths = dict()
def newPlot(self):
self.single_samples = dict()
def get_density_grid(self, root, param1, param2, conts=2, likes=False):
res = self.load_2d(root, param1, param2)
if likes: res.likes = self.load_2d(root, param1, param2, '_likes', no_axes=True)
if res is None: return None
if conts > 0: res.contours = self.load_2d(root, param1, param2, '_cont', no_axes=True)[0:conts]
return res
def get_density(self, root, param, likes=False):
pts = self.load_1d(root, param)
if pts is None: return None
result = Density1D(pts[:, 0], pts[:, 1])
if likes: result.likes = self.load_1d(root, param, '.likes')[:, 1]
return result
def load_single_samples(self, root):
if not root in self.single_samples: self.single_samples[root] = np.loadtxt(
self.plot_data_file(root) + '_single.txt')[:, 2:]
return self.single_samples[root]
def paramsForRoot(self, root, labelParams=None):
names = ParamNames(self.plot_data_file(root) + '.paramnames')
if labelParams is not None: names.setLabelsAndDerivedFromParamNames(labelParams)
return names
def boundsForRoot(self, root):
return ParamBounds(self.plot_data_file(root) + '.bounds')
def plot_data_file(self, root):
# find first match to roots that exist in list of plot_data paths
if os.sep in root: return root
path = self.paths.get(root, None)
if path is not None: return path
for datadir in self.plot_data:
path = datadir + os.sep + root
if os.path.exists(path + '.paramnames'):
self.paths[root] = path
return path
return self.plot_data[0] + os.sep + root
def plot_data_file_1D(self, root, name):
return self.plot_data_file(root) + '_p_' + name
def plot_data_file_2D(self, root, name1, name2):
fname = self.plot_data_file(root) + '_2D_' + name2 + '_' + name1
if not os.path.exists(fname):
return self.plot_data_file(root) + '_2D_' + name1 + '_' + name2, True
else:
return fname, False
def load_1d(self, root, param, ext='.dat'):
fname = self.plot_data_file_1D(root, param.name) + ext
if not hasattr(param, 'plot_data'): param.plot_data = dict()
if not fname in param.plot_data:
if not os.path.exists(fname):
param.plot_data[fname] = None
else:
param.plot_data[fname] = np.loadtxt(fname)
return param.plot_data[fname]
def load_2d(self, root, param1, param2, ext='', no_axes=False):
fname, transpose = self.plot_data_file_2D(root, param1.name, param2.name)
if not os.path.exists(fname + ext): return None
pts = np.loadtxt(fname + ext)
if transpose: pts = pts.transpose()
if no_axes: return pts
x = np.loadtxt(fname + '_x')
y = np.loadtxt(fname + '_y')
if transpose:
return Density2D(y, x, pts)
else:
return Density2D(x, y, pts)
class RootInfo(object):
"""
Class to hold information about a set of samples loaded from file
"""
def __init__(self, root, path, batch=None):
"""
:param root: The root file to use.
:param path: The path the root file is in.
:param batch: optional batch object if loaded from a grid of results
"""
self.root = root
self.batch = batch
self.path = path
class MCSampleAnalysis(object):
"""
A class that loads and analyses samples, mapping root names to :class:`~.mcsamples.MCSamples` objects with caching.
Typically accessed as the instance stored in plotter.sampleAnalyser, for example to
get an :class:`~.mcsamples.MCSamples` instance from a root name being used by a plotter, use plotter.sampleAnalyser.samplesForRoot(name).
"""
def __init__(self, chain_locations, settings=None):
"""
:param chain_locations: either a directory or the path of a grid of runs;
it can also be a list of such, which is searched in order
:param settings: Either an :class:`~.inifile.IniFile` instance,
the name of an .ini file, or a dict holding sample analysis settings.
"""
self.chain_dirs = []
self.chain_locations = []
self.ini = None
if chain_locations is not None:
if isinstance(chain_locations, six.string_types):
chain_locations = [chain_locations]
for chain_dir in chain_locations:
self.addChainDir(chain_dir)
self.reset(settings)
def addChainDir(self, chain_dir):
"""
Adds a new chain directory or grid path for searching for samples
:param chain_dir: The directory to add
"""
if chain_dir in self.chain_locations: return
self.chain_locations.append(chain_dir)
isBatch = isinstance(chain_dir, batchjob.batchJob)
if isBatch or gridconfig.pathIsGrid(chain_dir):
if isBatch:
batch = chain_dir
else:
batch = batchjob.readobject(chain_dir)
self.chain_dirs.append(batch)
# this gets things like specific parameter limits etc. specific to the grid
# yuk, this should only be for old Planck grids. New ones don't need getdist_common
# should instead set custom settings in the grid setting file
if os.path.exists(batch.commonPath + 'getdist_common.ini'):
batchini = IniFile(batch.commonPath + 'getdist_common.ini')
if self.ini:
self.ini.params.update(batchini.params)
else:
self.ini = batchini
else:
self.chain_dirs.append(chain_dir)
def reset(self, settings=None):
"""
Resets the caches, starting afresh optionally with new analysis settings
:param settings: Either an :class:`~.inifile.IniFile` instance,
the name of an .ini file, or a dict holding sample analysis settings.
"""
self.analysis_settings = {}
if isinstance(settings, IniFile):
ini = settings
elif isinstance(settings, dict):
ini = IniFile(getdist.default_getdist_settings)
ini.params.update(settings)
else:
ini = IniFile(settings or getdist.default_getdist_settings)
if self.ini:
self.ini.params.update(ini.params)
else:
self.ini = ini
self.mcsamples = {}
# Dicts. 1st key is root; 2nd key is param
self.densities_1D = dict()
self.densities_2D = dict()
self.single_samples = dict()
def samplesForRoot(self, root, file_root=None, cache=True, settings=None):
"""
Gets :class:`~.mcsamples.MCSamples` from root name
(or just return root if it is already an MCSamples instance).
:param root: The root name (without path, e.g. my_chains)
:param file_root: optional full root path, by default searches in self.chain_dirs
:param cache: if True, return cached object if already loaded
:return: :class:`~.mcsamples.MCSamples` for the given root name
"""
if isinstance(root, MCSamples): return root
if os.path.isabs(root):
# deal with just-folder prefix
if root.endswith("/"):
root = os.path.basename(root[:-1]) + "/"
else:
root = os.path.basename(root)
if root in self.mcsamples and cache: return self.mcsamples[root]
jobItem = None
dist_settings = settings or {}
if not file_root:
for chain_dir in self.chain_dirs:
if hasattr(chain_dir, "resolveRoot"):
jobItem = chain_dir.resolveRoot(root)
if jobItem:
file_root = jobItem.chainRoot
if hasattr(chain_dir, 'getdist_options'):
dist_settings.update(chain_dir.getdist_options)
dist_settings.update(jobItem.dist_settings)
break
else:
name = os.path.join(chain_dir, root)
if os.path.exists(name + '_1.txt') or os.path.exists(name + '.txt'):
file_root = name
break
if not file_root:
raise GetDistPlotError('chain not found: ' + root)
self.mcsamples[root] = loadMCSamples(file_root, self.ini, jobItem, settings=dist_settings)
return self.mcsamples[root]
def addRoots(self, roots):
"""
A wrapper for addRoot that adds multiple file roots
:param roots: An iterable containing filenames or :class:`RootInfo` objects to add
"""
for root in roots:
self.addRoot(root)
def addRoot(self, file_root):
"""
Add a root file for some new samples
:param file_root: Either a file root name including path or a :class:`RootInfo` instance
:return: :class:`~.mcsamples.MCSamples` instance for given root file.
"""
if isinstance(file_root, RootInfo):
if file_root.batch:
return self.samplesForRoot(file_root.root)
else:
return self.samplesForRoot(file_root.root, os.path.join(file_root.path, file_root.root))
else:
return self.samplesForRoot(os.path.basename(file_root), file_root)
def removeRoot(self, file_root):
"""
Remove a given root file (does not delete it)
:param file_root: The file root to remove
"""
root = os.path.basename(file_root)
self.mcsamples.pop(root, None)
self.single_samples.pop(root, None)
self.densities_1D.pop(root, None)
self.densities_2D.pop(root, None)
def newPlot(self):
pass
def get_density(self, root, param, likes=False):
"""
Get :class:`~.densities.Density1D` for given root name and parameter
:param root: The root name of the samples to use
:param param: name of the parameter
:param likes: whether to include mean likelihood in density.likes
:return: :class:`~.densities.Density1D` instance with 1D marginalized density
"""
rootdata = self.densities_1D.get(root)
if rootdata is None:
rootdata = {}
self.densities_1D[root] = rootdata
if isinstance(param, ParamInfo):
name = param.name
else: #
name = param
samples = self.samplesForRoot(root)
key = (name, likes)
rootdata.pop((name, not likes), None)
density = rootdata.get(key)
if density is None:
density = samples.get1DDensityGridData(name, meanlikes=likes)
if density is None: return None
rootdata[key] = density
return density
def get_density_grid(self, root, param1, param2, conts=2, likes=False):
"""
Get 2D marginalized density for given root name and parameters
:param root: The root name for samples to use.
:param param1: x parameter
:param param2: y parameter
:param conts: number of contour levels (up to maximum calculated using contours in analysis settings)
:param likes: whether to include mean likelihoods
:return: :class:`~.densities.Density2D` instance with marginalized density
"""
rootdata = self.densities_2D.get(root)
if not rootdata:
rootdata = {}
self.densities_2D[root] = rootdata
key = (param1.name, param2.name, likes, conts)
density = rootdata.get(key)
if not density:
samples = self.samplesForRoot(root)
density = samples.get2DDensityGridData(param1.name, param2.name, num_plot_contours=conts, meanlikes=likes)
if density is None: return None
rootdata[key] = density
return density
def load_single_samples(self, root):
"""
Gets a set of unit weight samples for given root name, e.g. for making sample scatter plot
:param root: The root name to use.
:return: array of unit weight samples
"""
if not root in self.single_samples:
self.single_samples[root] = self.samplesForRoot(root).makeSingleSamples()
return self.single_samples[root]
def paramsForRoot(self, root, labelParams=None):
"""
Returns a :class:`~.paramnames.ParamNames` with names and labels for parameters used by samples with a given root name.
:param root: The root name of the samples to use.
:param labelParams: optional name of .paramnames file containing labels to use for plots, overriding default
:return: :class:`~.paramnames.ParamNames` instance
"""
if hasattr(root, 'paramNames'):
names = root.paramNames
else:
samples = self.samplesForRoot(root)
names = samples.getParamNames()
if labelParams is not None:
names.setLabelsAndDerivedFromParamNames(os.path.join(batchjob.getCodeRootPath(), labelParams))
return names
def boundsForRoot(self, root):
"""
Returns an object with getUpper and getLower to get hard prior bounds for given root name
:param root: The root name to use.
:return: object with getUpper() and getLower() functions
"""
if hasattr(root, 'getUpper'):
return root
else:
return self.samplesForRoot(root) # #defines getUpper and getLower, all that's needed
class GetDistPlotter(object):
"""
Main class for making plots from one or more sets of samples.
:ivar settings: a :class:`GetDistPlotSettings` instance with settings
:ivar subplots: a 2D array of :class:`~matplotlib:matplotlib.axes.Axes` for subplots
:ivar sampleAnalyser: a :class:`MCSampleAnalysis` instance for getting :class:`~.mcsamples.MCSamples`
and derived data from a given root name tag (e.g. sampleAnalyser.samplesForRoot('rootname'))
"""
def __init__(self, plot_data=None, chain_dir=None, settings=None, analysis_settings=None, mcsamples=True):
"""
:param plot_data: (deprecated) directory name if you have pre-computed plot_data/ directory from GetDist; None by default
:param chain_dir: Set this to a directory or grid root to search for chains (can also be a list of such, searched in order)
:param analysis_settings: The settings to be used by :class:`MCSampleAnalysis` when analysing samples
:param mcsamples: if True defaults to current method of using :class:`MCSampleAnalysis` instance to analyse chains on demand
"""
self.chain_dir = chain_dir
if settings is None:
self.settings = copy.deepcopy(defaultSettings)
else:
self.settings = settings
if chain_dir is None and plot_data is None: chain_dir = getdist.default_grid_root
if isinstance(plot_data, six.string_types):
self.plot_data = [plot_data]
else:
self.plot_data = plot_data
if chain_dir is not None or mcsamples and plot_data is None:
self.sampleAnalyser = MCSampleAnalysis(chain_dir, analysis_settings)
else:
self.sampleAnalyser = SampleAnalysisGetDist(self.plot_data)
self.newPlot()
def newPlot(self):
"""
Resets the given plotter to make a new empty plot.
"""
self.extra_artists = []
self.contours_added = []
self.lines_added = dict()
self.param_name_sets = dict()
self.param_bounds_sets = dict()
self.sampleAnalyser.newPlot()
self.fig = None
self.subplots = None
self.plot_col = 0
def show_all_settings(self):
"""
Prints settings and library versions
"""
print('Python version:', sys.version)
print('\nMatplotlib version:', matplotlib.__version__)
print('\nGetDist Plot Settings:')
print('GetDist version:', getdist.__version__)
sets = self.settings.__dict__
for key, value in list(sets.items()):
print(key, ':', value)
print('\nRC params:')
for key, value in list(matplotlib.rcParams.items()):
print(key, ':', value)
def _get_plot_args(self, plotno, **kwargs):
"""
Get plot arguments for the given plot line number
:param plotno: The index of the line added to a plot
:param kwargs: optional settings to override in the current ones
:return: The updated dict of arguments.
"""
if isinstance(self.settings.plot_args, dict):
args = self.settings.plot_args
elif isinstance(self.settings.plot_args, list):
if len(self.settings.plot_args) > plotno:
args = self.settings.plot_args[plotno]
if args is None: args = dict()
else:
args = {}
elif not self.settings.plot_args:
args = dict()
else:
raise GetDistPlotError(
'plot_args must be list of dictionaries or dictionary: %s' % self.settings.plot_args)
args.update(kwargs)
return args
def _get_dashes_for_ls(self, ls):
"""
Gets the dash style for the given line style.
:param ls: The line style
:return: The dash style.
"""
return self.settings.default_dash_styles.get(ls, None)
def _get_default_ls(self, plotno=0):
"""
Get default line style.
:param plotno: The number of the line added to the plot to get the style of.
:return: The default line style.
"""
try:
return self.settings.lineM[plotno]
except IndexError:
print('Error adding line ' + str(plotno) + ': Add more default line stype entries to settings.lineM')
raise
def _get_line_styles(self, plotno, **kwargs):
"""
Gets the styles of the line for the given line added to a plot
:param plotno: The number of the line added to the plot.
:param kwargs: Params for :func:`~GetDistPlotter._get_plot_args`.
:return: dict with ls, dashes, lw and color set appropriately
"""
args = self._get_plot_args(plotno, **kwargs)
if not 'ls' in args: args['ls'] = self._get_default_ls(plotno)[:-1]
if not 'dashes' in args:
dashes = self._get_dashes_for_ls(args['ls'])
if dashes is not None: args['dashes'] = dashes
if not 'color' in args:
args['color'] = self._get_default_ls(plotno)[-1]
if not 'lw' in args: args['lw'] = self.settings.lw1
return args
def _get_color(self, plotno, **kwargs):
"""
Get the color for the given line number
:param plotno: line number added to plot
:param kwargs: arguments for :func:`~GetDistPlotter._get_line_styles`
:return: The color.
"""
return self._get_line_styles(plotno, **kwargs)['color']
def _get_linestyle(self, plotno, **kwargs):
"""
Get line style for given plot line number.
:param plotno: line number added to plot
:param kwargs: arguments for :func:`~GetDistPlotter._get_line_styles`
:return: The line style for the given plot line.
"""
return self._get_line_styles(plotno, **kwargs)['ls']
def _get_alpha2D(self, plotno, **kwargs):
"""
Get the alpha for the given 2D contour added to plot
:param plotno: The index of contours added to the plot
:param kwargs: arguments for :func:`~GetDistPlotter._get_line_styles`,
These may also include: filled
:return: The alpha for the given plot contours
"""
args = self._get_plot_args(plotno, **kwargs)
if kwargs.get('filled') and plotno > 0:
default = self.settings.alpha_filled_add
else:
default = 1
return args.get('alpha', default)
def paramNamesForRoot(self, root):
"""
Get the parameter names and labels :class:`~.paramnames.ParamNames` instance for the given root name
:param root: The root name of the samples.
:return: :class:`~.paramnames.ParamNames` instance
"""
if not root in self.param_name_sets: self.param_name_sets[root] = self.sampleAnalyser.paramsForRoot(root,
labelParams=self.settings.param_names_for_labels)
return self.param_name_sets[root]
def paramBoundsForRoot(self, root):
"""
Get any hard prior bounds for the parameters with root file name
:param root: The root name to be used
:return: object with getUpper() and getLower() bounds functions
"""
if not root in self.param_bounds_sets: self.param_bounds_sets[root] = self.sampleAnalyser.boundsForRoot(root)
return self.param_bounds_sets[root]
def _check_param_ranges(self, root, name, xmin, xmax):
"""
Checks The upper and lower bounds are not outside hard priors
:param root: The root file to use.
:param name: The param name to check.
:param xmin: The lower bound
:param xmax: The upper bound
:return: The bounds (highest lower limit, and lowest upper limit)
"""
d = self.paramBoundsForRoot(root)
low = d.getLower(name)
if low is not None: xmin = max(xmin, low)
up = d.getUpper(name)
if up is not None: xmax = min(xmax, up)
return xmin, xmax
def _get_param_bounds(self, roots, name):
xmin, xmax = None, None
for root in roots:
d = self.paramBoundsForRoot(root)
low = d.getLower(name)
if low is not None:
if xmin is None:
xmin = low
else:
xmin = max(xmin, low)
up = d.getUpper(name)
if up is not None:
if xmax is None:
xmax = up
else:
xmax = min(xmax, up)
xmin, xmax = self._check_param_ranges(root, name, xmin, xmax)
return xmin, xmax
def add_1d(self, root, param, plotno=0, normalized=False, ax=None, **kwargs):
"""
Low-level function to add a 1D marginalized density line to a plot
:param root: The root name of the samples
:param param: The parameter name
:param plotno: The index of the line being added to the plot
:param normalized: True if areas under lines should match, False if normalized to unit maximum
:param ax: optional :class:`~matplotlib:matplotlib.axes.Axes` instance to add to (defaults to current plot)
:param kwargs: arguments for :func:`~matplotlib:matplotlib.pyplot.plot`
:return: min, max for the plotted density
"""
ax = ax or plt.gca()
param = self._check_param(root, param)
if isinstance(root, MixtureND):
density = root.density1D(param.name)
if not normalized: density.normalize(by='max')
else:
density = self.sampleAnalyser.get_density(root, param, likes=self.settings.plot_meanlikes)
if density is None: return None;
if normalized: density.normalize()
kwargs = self._get_line_styles(plotno, **kwargs)
self.lines_added[plotno] = kwargs
l, = ax.plot(density.x, density.P, **kwargs)
if kwargs.get('dashes'):
l.set_dashes(kwargs['dashes'])
if self.settings.plot_meanlikes:
kwargs['lw'] = self.settings.lw_likes
ax.plot(density.x, density.likes, **kwargs)
return density.bounds()
def add_2d_density_contours(self, density, **kwargs):
"""
Low-level function to add 2D contours to a plot using provided density
:param density: a :class:`.densities.Density2D` instance
:param kwargs: arguments for :func:`~GetDistPlotter.add_2d_contours`
:return: bounds (from :func:`.~densities.GridDensity.bounds`) of density
"""
return self.add_2d_contours(None, density=density, **kwargs)
def add_2d_contours(self, root, param1=None, param2=None, plotno=0, of=None, cols=None, contour_levels=None,
add_legend_proxy=True, param_pair=None, density=None, alpha=None, ax=None, **kwargs):
"""
Low-level function to add 2D contours to plot for samples with given root name and parameters
:param root: The root name of samples to use
:param param1: x parameter
:param param2: y parameter
:param plotno: The index of the contour lines being added
:param of: the total number of contours being added (this is line plotno of of)
:param cols: optional list of colors to use for contours, by default uses default for this plotno
:param contour_levels: levels at which to plot the contours, by default given by contours array in the analysis settings
:param add_legend_proxy: True if should add a proxy to the legend of this plot.
:param param_pair: an [x,y] parameter name pair if you prefer to provide this rather than param1 and param2
:param density: optional :class:`~.densities.Density2D` to plot rather than that computed automatically from the samples
:param alpha: alpha for the contours added
:param ax: optional :class:`~matplotlib:matplotlib.axes.Axes` instance to add to (defaults to current plot)
:param kwargs: optional keyword arguments:
- **filled**: True to make filled contours
- **color**: top color to automatically make paling contour colours for a filled plot
- kwargs for :func:`~matplotlib:matplotlib.pyplot.contour` and :func:`~matplotlib:matplotlib.pyplot.contourf`
:return: bounds (from :meth:`~.densities.GridDensity.bounds`) for the 2D density plotted
"""
ax = ax or plt.gca()
if density is None:
param1, param2 = self.get_param_array(root, param_pair or [param1, param2])
density = self.sampleAnalyser.get_density_grid(root, param1, param2,
conts=self.settings.num_plot_contours,
likes=self.settings.shade_meanlikes)
if density is None:
if add_legend_proxy: self.contours_added.append(None)
return None
if alpha is None: alpha = self._get_alpha2D(plotno, **kwargs)
if contour_levels is None:
if not hasattr(density, 'contours'):
contours = self.sampleAnalyser.ini.ndarray('contours')
if contours is not None: contours = contours[:self.settings.num_plot_contours]
density.contours = density.getContourLevels(contours)
contour_levels = density.contours
if add_legend_proxy:
proxyIx = len(self.contours_added)
self.contours_added.append(None)
elif None in self.contours_added and self.contours_added.index(None) == plotno:
proxyIx = plotno
else:
proxyIx = -1
if kwargs.get('filled'):
if cols is None:
color = kwargs.get('color')
if color is None:
if of is not None:
color = self.settings.solid_colors[of - plotno - 1]
else:
color = self.settings.solid_colors[plotno]
if isinstance(color, six.string_types):
cols = [matplotlib.colors.colorConverter.to_rgb(color)]
for _ in range(1, len(contour_levels)):
cols = [[c * (1 - self.settings.solid_contour_palefactor) +
self.settings.solid_contour_palefactor for c in cols[0]]] + cols
else:
cols = color
levels = sorted(np.append([density.P.max() + 1], contour_levels))
cont_args = dict(kwargs)
if 'color' in cont_args: del cont_args['color']
CS = ax.contourf(density.x, density.y, density.P, levels, colors=cols, alpha=alpha, **cont_args)
if proxyIx >= 0: self.contours_added[proxyIx] = (plt.Rectangle((0, 0), 1, 1, fc=CS.tcolors[-1][0]))
ax.contour(density.x, density.y, density.P, levels[:1], colors=CS.tcolors[-1],
linewidths=self.settings.lw_contour, alpha=alpha * self.settings.alpha_factor_contour_lines,
**cont_args)
else:
args = self._get_line_styles(plotno, **kwargs)
# if color is None: color = self._get_color(plotno, **kwargs)
# cols = [color]
# if ls is None: ls = self._get_linestyle(plotno, **kwargs)
linestyles = [args['ls']]
cols = [args['color']]
kwargs = self._get_plot_args(plotno, **kwargs)
kwargs['alpha'] = alpha
CS = ax.contour(density.x, density.y, density.P, sorted(contour_levels), colors=cols, linestyles=linestyles,
linewidths=self.settings.lw_contour, **kwargs)
dashes = args.get('dashes')
if dashes:
for c in CS.collections:
c.set_dashes([(0, dashes)])
if proxyIx >= 0:
line = plt.Line2D([0, 1], [0, 1], ls=linestyles[0], lw=self.settings.lw_contour, color=cols[0],
alpha=args.get('alpha'))
if dashes: line.set_dashes(dashes)
self.contours_added[proxyIx] = line
return density.bounds()
def add_2d_shading(self, root, param1, param2, colormap=None, density=None, ax=None, **kwargs):
"""
Low-level function to add 2D density shading to the given plot.
:param root: The root name of samples to use
:param param1: x parameter
:param param2: y parameter
:param colormap: color map, default to settings.colormap (see :class:`GetDistPlotSettings`)
:param density: optional user-provided :class:`~.densities.Density2D` to plot rather than
the auto-generated density from the samples
:param ax: optional :class:`~matplotlib:matplotlib.axes.Axes` instance to add to (defaults to current plot)
:param kwargs: keyword arguments for :func:`~matplotlib:matplotlib.pyplot.contourf`
"""
ax = ax or plt.gca()
param1, param2 = self.get_param_array(root, [param1, param2])
density = density or self.sampleAnalyser.get_density_grid(root, param1, param2,
conts=self.settings.num_plot_contours,
likes=self.settings.shade_meanlikes)
if density is None: return
if colormap is None: colormap = self.settings.colormap
scalarMap = cm.ScalarMappable(cmap=colormap)
cols = scalarMap.to_rgba(np.linspace(0, 1, self.settings.num_shades))
# make sure outside area white and nice fade
n = min(self.settings.num_shades // 3, 20)
white = np.array([1, 1, 1, 1])
# would be better to fade in alpha, but then the extra contourf fix doesn't work well
for i in range(n):
cols[i + 1] = (white * (n - i) + np.array(cols[i + 1]) * i) / float(n)
cols[0][3] = 0 # keep edges clear