Ejemplo n.º 1
0
Archivo: dict.py Proyecto: k-ship/bilby
 def from_dictionary(self, dictionary):
     eval_dict = dict(inf=np.inf)
     for key, val in iteritems(dictionary):
         if isinstance(val, Prior):
             continue
         elif isinstance(val, (int, float)):
             dictionary[key] = DeltaFunction(peak=val)
         elif isinstance(val, str):
             cls = val.split('(')[0]
             args = '('.join(val.split('(')[1:])[:-1]
             try:
                 dictionary[key] = DeltaFunction(peak=float(cls))
                 logger.debug("{} converted to DeltaFunction prior".format(key))
                 continue
             except ValueError:
                 pass
             if "." in cls:
                 module = '.'.join(cls.split('.')[:-1])
                 cls = cls.split('.')[-1]
             else:
                 module = __name__.replace(
                     '.' + os.path.basename(__file__).replace('.py', ''), ''
                 )
             cls = getattr(import_module(module), cls, cls)
             if key.lower() in ["conversion_function", "condition_func"]:
                 setattr(self, key, cls)
             elif isinstance(cls, str):
                 if "(" in val:
                     raise TypeError("Unable to parse prior class {}".format(cls))
                 else:
                     continue
             elif (cls.__name__ in ['MultivariateGaussianDist',
                                    'MultivariateNormalDist']):
                 if key not in eval_dict:
                     eval_dict[key] = eval(val, None, eval_dict)
             elif (cls.__name__ in ['MultivariateGaussian',
                                    'MultivariateNormal']):
                 dictionary[key] = eval(val, None, eval_dict)
             else:
                 try:
                     dictionary[key] = cls.from_repr(args)
                 except TypeError as e:
                     raise TypeError(
                         "Unable to parse prior, bad entry: {} "
                         "= {}. Error message {}".format(key, val, e)
                     )
         elif isinstance(val, dict):
             logger.warning(
                 'Cannot convert {} into a prior object. '
                 'Leaving as dictionary.'.format(key))
         else:
             raise TypeError(
                 "Unable to parse prior, bad entry: {} "
                 "= {} of type {}".format(key, val, type(val))
             )
     self.update(dictionary)
Ejemplo n.º 2
0
Archivo: dict.py Proyecto: k-ship/bilby
 def convert_floats_to_delta_functions(self):
     """ Convert all float parameters to delta functions """
     for key in self:
         if isinstance(self[key], Prior):
             continue
         elif isinstance(self[key], float) or isinstance(self[key], int):
             self[key] = DeltaFunction(self[key])
             logger.debug(
                 "{} converted to delta function prior.".format(key))
         else:
             logger.debug(
                 "{} cannot be converted to delta function prior."
                 .format(key))
Ejemplo n.º 3
0
    def from_file(self, filename):
        """ Reads in a prior from a file specification

        Parameters
        ----------
        filename: str
            Name of the file to be read in

        Notes
        -----
        Lines beginning with '#' or empty lines will be ignored.
        Priors can be loaded from:
            bilby.core.prior as, e.g.,    foo = Uniform(minimum=0, maximum=1)
            floats, e.g.,                 foo = 1
            bilby.gw.prior as, e.g.,      foo = bilby.gw.prior.AlignedSpin()
            other external modules, e.g., foo = my.module.CustomPrior(...)
        """

        comments = ['#', '\n']
        prior = dict()
        mvgdict = dict(inf=np.inf)  # evaluate inf as np.inf
        with ioopen(filename, 'r', encoding='unicode_escape') as f:
            for line in f:
                if line[0] in comments:
                    continue
                line.replace(' ', '')
                elements = line.split('=')
                key = elements[0].replace(' ', '')
                val = '='.join(elements[1:]).strip()
                cls = val.split('(')[0]
                args = '('.join(val.split('(')[1:])[:-1]
                try:
                    prior[key] = DeltaFunction(peak=float(cls))
                    logger.debug(
                        "{} converted to DeltaFunction prior".format(key))
                    continue
                except ValueError:
                    pass
                if "." in cls:
                    module = '.'.join(cls.split('.')[:-1])
                    cls = cls.split('.')[-1]
                else:
                    module = __name__.replace(
                        '.' + os.path.basename(__file__).replace('.py', ''),
                        '')
                cls = getattr(import_module(module), cls, cls)
                if key.lower() in ["conversion_function", "condition_func"]:
                    setattr(self, key, cls)
                elif (cls.__name__ in [
                        'MultivariateGaussianDist', 'MultivariateNormalDist'
                ]):
                    if key not in mvgdict:
                        mvgdict[key] = eval(val, None, mvgdict)
                elif (cls.__name__
                      in ['MultivariateGaussian', 'MultivariateNormal']):
                    prior[key] = eval(val, None, mvgdict)
                else:
                    try:
                        prior[key] = cls.from_repr(args)
                    except TypeError as e:
                        raise TypeError(
                            "Unable to parse dictionary file {}, bad line: {} "
                            "= {}. Error message {}".format(
                                filename, key, val, e))
        self.update(prior)