result.py 25.1 KB
Newer Older
1
import os
2
from distutils.version import LooseVersion
MoritzThomasHuebner's avatar
MoritzThomasHuebner committed
3 4
from collections import OrderedDict

5
import numpy as np
6
import deepdish
7
import pandas as pd
8
import corner
9
import matplotlib
10
import matplotlib.pyplot as plt
11

12
from . import utils
13
from .utils import logger, infer_parameters_from_function
14
from .prior import PriorSet, DeltaFunction
15

16

17
def result_file_name(outdir, label):
18 19 20 21 22 23 24 25 26 27 28 29 30
    """ Returns the standard filename used for a result file

    Parameters
    ----------
    outdir: str
        Name of the output directory
    label: str
        Naming scheme of the output file

    Returns
    -------
    str: File name of the output file
    """
31 32 33
    return '{}/{}_result.h5'.format(outdir, label)


Gregory Ashton's avatar
Gregory Ashton committed
34 35 36 37 38 39 40 41 42 43
def read_in_result(outdir=None, label=None, filename=None):
    """ Read in a saved .h5 data file

    Parameters
    ----------
    outdir, label: str
        If given, use the default naming convention for saved results file
    filename: str
        If given, try to load from this filename

44 45
    Returns
    -------
Colm Talbot's avatar
Colm Talbot committed
46
    result: bilby.core.result.Result
47

Moritz Huebner's avatar
Moritz Huebner committed
48
    Raises
49 50
    -------
    ValueError: If no filename is given and either outdir or label is None
Colm Talbot's avatar
Colm Talbot committed
51
                If no bilby.core.result.Result is found in the path
Gregory Ashton's avatar
Gregory Ashton committed
52 53 54 55

    """
    if filename is None:
        filename = result_file_name(outdir, label)
56 57
    elif (outdir is None or label is None) and filename is None:
        raise ValueError("No information given to load file")
58 59 60
    if os.path.isfile(filename):
        return Result(deepdish.io.load(filename))
    else:
61
        raise ValueError("No result found")
62

63 64

class Result(dict):
65
    def __init__(self, dictionary=None):
66 67 68 69 70 71 72 73
        """ A class to save the results of the sampling run.

        Parameters
        ----------
        dictionary: dict
            A dictionary containing values to be set in this instance
        """

74 75 76 77
        # Set some defaults
        self.outdir = '.'
        self.label = 'no_name'

Moritz Huebner's avatar
Moritz Huebner committed
78
        dict.__init__(self)
79 80
        if type(dictionary) is dict:
            for key in dictionary:
81
                val = self._standardise_a_string(dictionary[key])
82
                setattr(self, key, val)
83

84 85 86
        if getattr(self, 'priors', None) is not None:
            self.priors = PriorSet(self.priors)

87
    def __add__(self, other):
88 89 90 91 92 93 94
        matches = ['sampler', 'search_parameter_keys']
        for match in matches:
            # The 1 and 0 here ensure that if either doesn't have a match for
            # some reason, a error will be thrown.
            if getattr(other, match, 1) != getattr(self, match, 0):
                raise ValueError(
                    "Unable to add results generated with different {}".format(match))
95 96 97 98 99

        self.samples = np.concatenate([self.samples, other.samples])
        self.posterior = pd.concat([self.posterior, other.posterior])
        return self

100 101 102 103 104 105
    def __dir__(self):
        """ Adds tab completion in ipython

        See: http://ipython.org/ipython-doc/dev/config/integrating.html

        """
Gregory Ashton's avatar
Gregory Ashton committed
106 107
        methods = ['plot_corner', 'save_to_file', 'save_posterior_samples']
        return self.keys() + methods
108

109 110 111 112 113 114
    def __getattr__(self, name):
        try:
            return self[name]
        except KeyError:
            raise AttributeError(name)

115 116 117
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__

118 119
    def __repr__(self):
        """Print a summary """
Gregory Ashton's avatar
Gregory Ashton committed
120
        if hasattr(self, 'posterior'):
121 122 123 124 125
            if hasattr(self, 'log_noise_evidence'):
                return ("nsamples: {:d}\n"
                        "log_noise_evidence: {:6.3f}\n"
                        "log_evidence: {:6.3f} +/- {:6.3f}\n"
                        "log_bayes_factor: {:6.3f} +/- {:6.3f}\n"
126
                        .format(len(self.posterior), self.log_noise_evidence, self.log_evidence,
127 128 129 130 131
                                self.log_evidence_err, self.log_bayes_factor,
                                self.log_evidence_err))
            else:
                return ("nsamples: {:d}\n"
                        "log_evidence: {:6.3f} +/- {:6.3f}\n"
132
                        .format(len(self.posterior), self.log_evidence, self.log_evidence_err))
133 134
        else:
            return ''
135

136 137
    @staticmethod
    def _standardise_a_string(item):
138 139 140 141 142 143 144 145 146 147
        """ When reading in data, ensure all strings are decoded correctly

        Parameters
        ----------
        item: str

        Returns
        -------
        str: decoded string
        """
148
        if type(item) in [bytes]:
149
            return item.decode()
150 151
        else:
            return item
152

153 154 155 156 157 158 159 160 161 162 163 164 165 166
    @staticmethod
    def _standardise_strings(item):
        """

        Parameters
        ----------
        item: list
            List of strings to be decoded

        Returns
        -------
        list: list of decoded strings in item

        """
167
        if type(item) in [list]:
Colm Talbot's avatar
Colm Talbot committed
168
            item = [Result._standardise_a_string(i) for i in item]
169 170
        return item

Colm Talbot's avatar
Colm Talbot committed
171 172 173 174 175 176 177 178 179 180
    def save_to_file(self, overwrite=False):
        """
        Writes the Result to a deepdish h5 file

        Parameters
        ----------
        overwrite: bool, optional
            Whether or not to overwrite an existing result file.
            default=False
        """
181
        file_name = result_file_name(self.outdir, self.label)
182
        utils.check_directory_exists_and_if_not_mkdir(self.outdir)
183
        if os.path.isfile(file_name):
Colm Talbot's avatar
Colm Talbot committed
184 185 186 187 188 189 190 191
            if overwrite:
                logger.debug('Removing existing file {}'.format(file_name))
                os.remove(file_name)
            else:
                logger.debug(
                    'Renaming existing file {} to {}.old'.format(file_name,
                                                                 file_name))
                os.rename(file_name, file_name + '.old')
192

Gregory Ashton's avatar
Gregory Ashton committed
193
        logger.debug("Saving result to {}".format(file_name))
194 195 196 197 198 199

        # Convert the prior to a string representation for saving on disk
        dictionary = dict(self)
        if dictionary.get('priors', False):
            dictionary['priors'] = {key: str(self.priors[key]) for key in self.priors}

200 201 202 203 204 205
        # Convert callable kwargs to strings to avoid pickling issues
        if hasattr(self, 'kwargs'):
            for key in self.kwargs:
                if hasattr(self.kwargs[key], '__call__'):
                    self.kwargs[key] = str(self.kwargs[key])

Gregory Ashton's avatar
Fix #49  
Gregory Ashton committed
206
        try:
207
            deepdish.io.save(file_name, dictionary)
Gregory Ashton's avatar
Fix #49  
Gregory Ashton committed
208
        except Exception as e:
Gregory Ashton's avatar
Gregory Ashton committed
209
            logger.error("\n\n Saving the data has failed with the "
MoritzThomasHuebner's avatar
MoritzThomasHuebner committed
210
                         "following message:\n {} \n\n".format(e))
Gregory Ashton's avatar
Gregory Ashton committed
211

212
    def save_posterior_samples(self):
213
        """Saves posterior samples to a file"""
214 215 216
        filename = '{}/{}_posterior_samples.txt'.format(self.outdir, self.label)
        self.posterior.to_csv(filename, index=False, header=True)

Gregory Ashton's avatar
Gregory Ashton committed
217
    def get_latex_labels_from_parameter_keys(self, keys):
218 219 220 221 222 223 224 225 226 227 228 229 230
        """ Returns a list of latex_labels corresponding to the given keys

        Parameters
        ----------
        keys: list
            List of strings corresponding to the desired latex_labels

        Returns
        -------
        list: The desired latex_labels

        """
        latex_labels = []
Gregory Ashton's avatar
Gregory Ashton committed
231 232 233
        for k in keys:
            if k in self.search_parameter_keys:
                idx = self.search_parameter_keys.index(k)
234
                latex_labels.append(self.parameter_labels_with_unit[idx])
Gregory Ashton's avatar
Gregory Ashton committed
235
            elif k in self.parameter_labels:
236
                latex_labels.append(k)
Gregory Ashton's avatar
Gregory Ashton committed
237
            else:
238 239 240
                logger.info(
                    'key {} not a parameter label or latex label'.format(k))
                latex_labels.append(' '.join(k.split('_')))
241
        return latex_labels
Gregory Ashton's avatar
Gregory Ashton committed
242

Gregory Ashton's avatar
Gregory Ashton committed
243 244 245 246 247 248 249 250 251
    @property
    def covariance_matrix(self):
        """ The covariance matrix of the samples the posterior """
        samples = self.posterior[self.search_parameter_keys].values
        return np.cov(samples.T)

    @property
    def posterior_volume(self):
        """ The posterior volume """
Gregory Ashton's avatar
Gregory Ashton committed
252 253 254
        if self.covariance_matrix.ndim == 0:
            return np.sqrt(self.covariance_matrix)
        else:
MoritzThomasHuebner's avatar
MoritzThomasHuebner committed
255 256
            return 1 / np.sqrt(np.abs(np.linalg.det(
                1 / self.covariance_matrix)))
Gregory Ashton's avatar
Gregory Ashton committed
257

258 259
    @staticmethod
    def prior_volume(priors):
Gregory Ashton's avatar
Gregory Ashton committed
260 261 262 263 264 265
        """ The prior volume, given a set of priors """
        return np.prod([priors[k].maximum - priors[k].minimum for k in priors])

    def occam_factor(self, priors):
        """ The Occam factor,

266 267 268
        See Chapter 28, `Mackay "Information Theory, Inference, and Learning
        Algorithms" <http://www.inference.org.uk/itprnn/book.html>`_ Cambridge
        University Press (2003).
Gregory Ashton's avatar
Gregory Ashton committed
269 270 271 272

        """
        return self.posterior_volume / self.prior_volume(priors)

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
    def get_one_dimensional_median_and_error_bar(self, key, fmt='.2f',
                                                 quantiles=[0.16, 0.84]):
        """ Calculate the median and error bar for a given key

        Parameters
        ----------
        key: str
            The parameter key for which to calculate the median and error bar
        fmt: str, ('.2f')
            A format string
        quantiles: list
            A length-2 list of the lower and upper-quantiles to calculate
            the errors bars for.

        Returns
        -------
        string: str
            A string of latex-formatted text of the mean and 1-sigma quantiles

        """
        if len(quantiles) != 2:
            raise ValueError("quantiles must be of length 2")

        quants_to_compute = np.array([quantiles[0], 0.5, quantiles[1]])
        quants = np.percentile(self.posterior[key], quants_to_compute * 100)
        median = quants[1]
        upper = quants[2] - median
        lower = median - quants[0]

        fmt = "{{0:{0}}}".format(fmt).format
        string = r"${{{0}}}_{{-{1}}}^{{+{2}}}$"
        return string.format(fmt(median), fmt(lower), fmt(upper))

306 307 308
    def plot_corner(self, parameters=None, priors=None, titles=True, save=True,
                    filename=None, dpi=300, **kwargs):
        """ Plot a corner-plot
Gregory Ashton's avatar
Gregory Ashton committed
309 310 311

        Parameters
        ----------
312 313 314
        parameters: (list, dict), optional
            If given, either a list of the parameter names to include, or a
            dictionary of parameter names and their "true" values to plot.
Colm Talbot's avatar
Colm Talbot committed
315
        priors: {bool (False), bilby.core.prior.PriorSet}
316 317 318
            If true, add the stored prior probability density functions to the
            one-dimensional marginal distributions. If instead a PriorSet
            is provided, this will be plotted.
319 320 321 322 323
        titles: bool
            If true, add 1D titles of the median and (by default 1-sigma)
            error bars. To change the error bars, pass in the quantiles kwarg.
            See method `get_one_dimensional_median_and_error_bar` for further
            details). If `quantiles=None` is passed in, no title is added.
324 325 326 327 328 329
        save: bool, optional
            If true, save the image using the given label and outdir
        filename: str, optional
            If given, overwrite the default filename
        dpi: int, optional
            Dots per inch resolution of the plot
330 331 332 333
        **kwargs:
            Other keyword arguments are passed to `corner.corner`. We set some
            defaults to improve the basic look and feel, but these can all be
            overridden.
Gregory Ashton's avatar
Gregory Ashton committed
334

335 336 337 338 339 340
        Notes
        -----
            The generation of the corner plot themselves is done by the corner
            python module, see https://corner.readthedocs.io for more
            information.

Gregory Ashton's avatar
Gregory Ashton committed
341 342 343 344
        Returns
        -------
        fig:
            A matplotlib figure instance
345

Gregory Ashton's avatar
Gregory Ashton committed
346
        """
347 348

        # If in testing mode, not corner plots are generated
349 350
        if utils.command_line_args.test:
            return
Gregory Ashton's avatar
Gregory Ashton committed
351

Colm Talbot's avatar
Colm Talbot committed
352
        # bilby default corner kwargs. Overwritten by anything passed to kwargs
353 354 355
        defaults_kwargs = dict(
            bins=50, smooth=0.9, label_kwargs=dict(fontsize=16),
            title_kwargs=dict(fontsize=16), color='#0072C1',
356
            truth_color='tab:orange', quantiles=[0.16, 0.84],
MoritzThomasHuebner's avatar
MoritzThomasHuebner committed
357
            levels=(1 - np.exp(-0.5), 1 - np.exp(-2), 1 - np.exp(-9 / 2.)),
358
            plot_density=False, plot_datapoints=True, fill_contours=True,
359 360 361 362 363 364
            max_n_ticks=3)

        if LooseVersion(matplotlib.__version__) < "2.1":
            defaults_kwargs['hist_kwargs'] = dict(normed=True)
        else:
            defaults_kwargs['hist_kwargs'] = dict(density=True)
365

366 367 368 369
        if 'lionize' in kwargs and kwargs['lionize'] is True:
            defaults_kwargs['truth_color'] = 'tab:blue'
            defaults_kwargs['color'] = '#FF8C00'

370 371 372
        defaults_kwargs.update(kwargs)
        kwargs = defaults_kwargs

373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
        # Handle if truths was passed in
        if 'truth' in kwargs:
            kwargs['truths'] = kwargs.pop('truth')
        if kwargs.get('truths'):
            truths = kwargs.get('truths')
            if isinstance(parameters, list) and isinstance(truths, list):
                if len(parameters) != len(truths):
                    raise ValueError(
                        "Length of parameters and truths don't match")
            elif isinstance(truths, dict) and parameters is None:
                parameters = kwargs.pop('truths')
            else:
                raise ValueError(
                    "Combination of parameters and truths not understood")

Gregory Ashton's avatar
Gregory Ashton committed
388 389 390 391 392 393 394 395
        # If injection parameters where stored, use these as parameter values
        # but do not overwrite input parameters (or truths)
        cond1 = getattr(self, 'injection_parameters', None) is not None
        cond2 = parameters is None
        if cond1 and cond2:
            parameters = {key: self.injection_parameters[key] for key in
                          self.search_parameter_keys}

396 397 398 399 400 401 402 403 404
        # If parameters is a dictionary, use the keys to determine which
        # parameters to plot and the values as truths.
        if isinstance(parameters, dict):
            plot_parameter_keys = list(parameters.keys())
            kwargs['truths'] = list(parameters.values())
        elif parameters is None:
            plot_parameter_keys = self.search_parameter_keys
        else:
            plot_parameter_keys = list(parameters)
405

406
        # Get latex formatted strings for the plot labels
407 408
        kwargs['labels'] = kwargs.get(
            'labels', self.get_latex_labels_from_parameter_keys(
409
                plot_parameter_keys))
410

411 412
        # Create the data array to plot and pass everything to corner
        xs = self.posterior[plot_parameter_keys].values
413
        fig = corner.corner(xs, **kwargs)
414
        axes = fig.get_axes()
415 416 417

        #  Add the titles
        if titles and kwargs.get('quantiles', None) is not None:
418 419
            for i, par in enumerate(plot_parameter_keys):
                ax = axes[i + i * len(plot_parameter_keys)]
420 421 422 423 424 425
                if ax.title.get_text() == '':
                    ax.set_title(self.get_one_dimensional_median_and_error_bar(
                        par, quantiles=kwargs['quantiles']),
                        **kwargs['title_kwargs'])

        #  Add priors to the 1D plots
426 427 428
        if priors is True:
            priors = getattr(self, 'priors', False)
        if isinstance(priors, dict):
429 430
            for i, par in enumerate(plot_parameter_keys):
                ax = axes[i + i * len(plot_parameter_keys)]
431 432
                theta = np.linspace(ax.get_xlim()[0], ax.get_xlim()[1], 300)
                ax.plot(theta, priors[par].prob(theta), color='C2')
433 434 435 436
        elif priors in [False, None]:
            pass
        else:
            raise ValueError('Input priors={} not understood'.format(priors))
437

438
        if save:
439 440 441
            if filename is None:
                utils.check_directory_exists_and_if_not_mkdir(self.outdir)
                filename = '{}/{}_corner.png'.format(self.outdir, self.label)
Gregory Ashton's avatar
Gregory Ashton committed
442
            logger.debug('Saving corner plot to {}'.format(filename))
443
            fig.savefig(filename, dpi=dpi)
444

445
        return fig
446

Gregory Ashton's avatar
Gregory Ashton committed
447
    def plot_walkers(self, **kwargs):
MoritzThomasHuebner's avatar
A typo  
MoritzThomasHuebner committed
448
        """ Method to plot the trace of the walkers in an ensemble MCMC plot """
449
        if hasattr(self, 'walkers') is False:
Gregory Ashton's avatar
Gregory Ashton committed
450
            logger.warning("Cannot plot_walkers as no walkers are saved")
451
            return
452 453 454

        if utils.command_line_args.test:
            return
455 456 457

        nwalkers, nsteps, ndim = self.walkers.shape
        idxs = np.arange(nsteps)
MoritzThomasHuebner's avatar
MoritzThomasHuebner committed
458
        fig, axes = plt.subplots(nrows=ndim, figsize=(6, 3 * ndim))
459 460
        walkers = self.walkers[:, :, :]
        for i, ax in enumerate(axes):
MoritzThomasHuebner's avatar
MoritzThomasHuebner committed
461
            ax.plot(idxs[:self.nburn + 1], walkers[:, :self.nburn + 1, i].T,
462 463 464 465 466 467 468 469 470 471
                    lw=0.1, color='r')
            ax.set_ylabel(self.parameter_labels[i])

        for i, ax in enumerate(axes):
            ax.plot(idxs[self.nburn:], walkers[:, self.nburn:, i].T, lw=0.1,
                    color='k')
            ax.set_ylabel(self.parameter_labels[i])

        fig.tight_layout()
        filename = '{}/{}_walkers.png'.format(self.outdir, self.label)
Gregory Ashton's avatar
Gregory Ashton committed
472
        logger.debug('Saving walkers plot to {}'.format('filename'))
473
        utils.check_directory_exists_and_if_not_mkdir(self.outdir)
474 475
        fig.savefig(filename)

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
    def plot_with_data(self, model, x, y, ndraws=1000, npoints=1000,
                       xlabel=None, ylabel=None, data_label='data',
                       data_fmt='o', draws_label=None, filename=None,
                       maxl_label='max likelihood', dpi=300):
        """ Generate a figure showing the data and fits to the data

        Parameters
        ----------
        model: function
            A python function which when called as `model(x, **kwargs)` returns
            the model prediction (here `kwargs` is a dictionary of key-value
            pairs of the model parameters.
        x, y: np.ndarray
            The independent and dependent data to plot
        ndraws: int
            Number of draws from the posterior to plot
        npoints: int
            Number of points used to plot the smoothed fit to the data
        xlabel, ylabel: str
            Labels for the axes
        data_label, draws_label, maxl_label: str
            Label for the data, draws, and max likelihood legend
        data_fmt: str
            Matpltolib fmt code, defaults to `'-o'`
        dpi: int
            Passed to `plt.savefig`
        filename: str
            If given, the filename to use. Otherwise, the filename is generated
            from the outdir and label attributes.

        """
507 508 509 510 511 512

        # Determine model_posterior, the subset of the full posterior which
        # should be passed into the model
        model_keys = infer_parameters_from_function(model)
        model_posterior = self.posterior[model_keys]

513 514 515 516
        xsmooth = np.linspace(np.min(x), np.max(x), npoints)
        fig, ax = plt.subplots()
        logger.info('Plotting {} draws'.format(ndraws))
        for _ in range(ndraws):
517
            s = model_posterior.sample().to_dict('records')[0]
518 519 520 521
            ax.plot(xsmooth, model(xsmooth, **s), alpha=0.25, lw=0.1, color='r',
                    label=draws_label)
        if all(~np.isnan(self.posterior.log_likelihood)):
            logger.info('Plotting maximum likelihood')
522
            s = model_posterior.ix[self.posterior.log_likelihood.idxmax()]
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
            ax.plot(xsmooth, model(xsmooth, **s), lw=1, color='k',
                    label=maxl_label)

        ax.plot(x, y, data_fmt, markersize=2, label=data_label)

        if xlabel is not None:
            ax.set_xlabel(xlabel)
        if ylabel is not None:
            ax.set_ylabel(ylabel)

        handles, labels = plt.gca().get_legend_handles_labels()
        by_label = OrderedDict(zip(labels, handles))
        plt.legend(by_label.values(), by_label.keys())
        ax.legend(numpoints=3)
        fig.tight_layout()
        if filename is None:
            filename = '{}/{}_plot_with_data'.format(self.outdir, self.label)
        fig.savefig(filename, dpi=dpi)

542 543
    def samples_to_posterior(self, likelihood=None, priors=None,
                             conversion_function=None):
544
        """
545
        Convert array of samples to posterior (a Pandas data frame).
546

547 548
        Parameters
        ----------
Colm Talbot's avatar
Colm Talbot committed
549
        likelihood: bilby.likelihood.GravitationalWaveTransient, optional
550 551
            GravitationalWaveTransient likelihood used for sampling.
        priors: dict, optional
552
            Dictionary of prior object, used to fill in delta function priors.
553
        conversion_function: function, optional
554 555
            Function which adds in extra parameters to the data frame,
            should take the data_frame, likelihood and prior as arguments.
556
        """
557 558 559
        if hasattr(self, 'posterior') is False:
            data_frame = pd.DataFrame(
                self.samples, columns=self.search_parameter_keys)
560
            for key in priors:
561
                if isinstance(priors[key], DeltaFunction):
562
                    data_frame[key] = priors[key].peak
563 564 565 566 567
                elif isinstance(priors[key], float):
                    data_frame[key] = priors[key]
            data_frame['log_likelihood'] = getattr(
                self, 'log_likelihood_evaluations', np.nan)
            # remove the array of samples
568 569 570
            del self.samples
        else:
            data_frame = self.posterior
571
        if conversion_function is not None:
572
            data_frame = conversion_function(data_frame, likelihood, priors)
573
        self.posterior = data_frame
Gregory Ashton's avatar
Gregory Ashton committed
574

Colm Talbot's avatar
Colm Talbot committed
575
    def calculate_prior_values(self, priors):
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
        """
        Evaluate prior probability for each parameter for each sample.

        Parameters
        ----------
        priors: dict, PriorSet
            Prior distributions
        """
        self.prior_values = pd.DataFrame()
        for key in priors:
            if key in self.posterior.keys():
                if isinstance(priors[key], DeltaFunction):
                    continue
                else:
                    self.prior_values[key]\
                        = priors[key].prob(self.posterior[key].values)

593
    def check_attribute_match_to_other_object(self, name, other_object):
594 595 596 597 598 599 600 601 602 603 604 605 606 607
        """ Check attribute name exists in other_object and is the same

        Parameters
        ----------
        name: str
            Name of the attribute in this instance
        other_object: object
            Other object with attributes to compare with

        Returns
        -------
        bool: True if attribute name matches with an attribute of other_object, False otherwise

        """
608
        A = getattr(self, name, False)
609
        B = getattr(other_object, name, False)
Gregory Ashton's avatar
Gregory Ashton committed
610
        logger.debug('Checking {} value: {}=={}'.format(name, A, B))
611 612 613 614 615
        if (A is not False) and (B is not False):
            typeA = type(A)
            typeB = type(B)
            if typeA == typeB:
                if typeA in [str, float, int, dict, list]:
Gregory Ashton's avatar
Gregory Ashton committed
616 617 618 619
                    try:
                        return A == B
                    except ValueError:
                        return False
620 621 622
                elif typeA in [np.ndarray]:
                    return np.all(A == B)
        return False
623 624 625


def plot_multiple(results, filename=None, labels=None, colours=None,
626
                  save=True, evidences=False, **kwargs):
627 628 629 630 631
    """ Generate a corner plot overlaying two sets of results

    Parameters
    ----------
    results: list
Colm Talbot's avatar
Colm Talbot committed
632
        A list of `bilby.core.result.Result` objects containing the samples to
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
        plot.
    filename: str
        File name to save the figure to. If None (default), a filename is
        constructed from the outdir of the first element of results and then
        the labels for all the result files.
    labels: list
        List of strings to use when generating a legend. If None (default), the
        `label` attribute of each result in `results` is used.
    colours: list
        The colours for each result. If None, default styles are applied.
    save: bool
        If true, save the figure
    kwargs: dict
        All other keyword arguments are passed to `result.plot_corner`.
        However, `show_titles` and `truths` are ignored since they would be
        ambiguous on such a plot.
649 650 651
    evidences: bool, optional
        Add the log-evidence calculations to the legend. If available, the
        Bayes factor will be used instead.
652 653 654 655 656 657 658 659 660 661 662 663

    Returns
    -------
    fig:
        A matplotlib figure instance

    """

    kwargs['show_titles'] = False
    kwargs['truths'] = None

    fig = results[0].plot_corner(save=False, **kwargs)
Gregory Ashton's avatar
Gregory Ashton committed
664
    default_filename = '{}/{}'.format(results[0].outdir, 'combined')
665 666 667 668 669 670 671
    lines = []
    default_labels = []
    for i, result in enumerate(results):
        if colours:
            c = colours[i]
        else:
            c = 'C{}'.format(i)
Gregory Ashton's avatar
Gregory Ashton committed
672 673
        hist_kwargs = kwargs.get('hist_kwargs', dict())
        hist_kwargs['color'] = c
674 675 676 677 678
        fig = result.plot_corner(fig=fig, save=False, color=c, **kwargs)
        default_filename += '_{}'.format(result.label)
        lines.append(matplotlib.lines.Line2D([0], [0], color=c))
        default_labels.append(result.label)

Gregory Ashton's avatar
Gregory Ashton committed
679 680 681 682 683
    # Rescale the axes
    for i, ax in enumerate(fig.axes):
        ax.autoscale()
    plt.draw()

684 685 686
    if labels is None:
        labels = default_labels

687 688
    if evidences:
        if np.isnan(results[0].log_bayes_factor):
689
            template = ' $\mathrm{{ln}}(Z)={lnz:1.3g}$'
690
        else:
691 692 693 694
            template = ' $\mathrm{{ln}}(B)={lnbf:1.3g}$'
        labels = [template.format(lnz=result.log_evidence,
                                  lnbf=result.log_bayes_factor)
                  for ii, result in enumerate(results)]
695

696 697
    axes = fig.get_axes()
    ndim = int(np.sqrt(len(axes)))
MoritzThomasHuebner's avatar
MoritzThomasHuebner committed
698
    axes[ndim - 1].legend(lines, labels)
699 700 701 702 703 704 705

    if filename is None:
        filename = default_filename

    if save:
        fig.savefig(filename)
    return fig