def prior_from_config(cp, prior_section='prior'): """Loads a prior distribution from the given config file. Parameters ---------- cp : pycbc.workflow.WorkflowConfigParser The config file to read. sections : list of str, optional The sections to retrieve the prior from. If ``None`` (the default), will look in sections starting with 'prior'. Returns ------- distributions.JointDistribution The prior distribution. """ # Read variable and static parameters from the config file variable_params, _ = distributions.read_params_from_config( cp, prior_section=prior_section, vargs_section='variable_params', sargs_section='static_params') # Read constraints to apply to priors from the config file constraints = distributions.read_constraints_from_config(cp) # Get PyCBC distribution instances for each variable parameter in the # config file dists = distributions.read_distributions_from_config(cp, prior_section) # construct class that will return draws from the prior return distributions.JointDistribution(variable_params, *dists, **{"constraints": constraints})
def _init_args_from_config(cls, cp): """Helper function for loading parameters.""" section = "model" prior_section = "prior" vparams_section = 'variable_params' sparams_section = 'static_params' constraint_section = 'constraint' # check that the name exists and matches name = cp.get(section, 'name') if name != cls.name: raise ValueError("section's {} name does not match mine {}".format( name, cls.name)) # get model parameters variable_params, static_params = distributions.read_params_from_config( cp, prior_section=prior_section, vargs_section=vparams_section, sargs_section=sparams_section) # get prior prior = cls.prior_from_config(cp, variable_params, prior_section, constraint_section) args = { 'variable_params': variable_params, 'static_params': static_params, 'prior': prior } # get any other keyword arguments provided args.update(cls.extra_args_from_config(cp, section, skip_args=['name'])) return args
def __init__(self, config_file, random_seed): # Fix the seed for the random number generator np.random.seed(random_seed) # Read in the configuration file using a WorkflowConfigParser. # Note that the argument `configFiles` has to be a list here, # so we need to wrap the `config_file` argument accordingly... config_file = WorkflowConfigParser(configFiles=[config_file]) # Extract variable arguments and constraints # We don't need the static_args here, hence they do not get amended. self.var_args, _ = read_params_from_config(config_file) self.constraints = read_constraints_from_config(config_file) # Extract distributions dist = read_distributions_from_config(config_file) # Extract transformations self.trans = read_transforms_from_config(config_file) # Set up a joint distribution to sample from self.pval = JointDistribution(self.var_args, *dist, **{'constraints': self.constraints})
def prior_from_config(cp, prior_section='prior'): """Loads a prior distribution from the given config file. Parameters ---------- cp : pycbc.workflow.WorkflowConfigParser The config file to read. sections : list of str, optional The sections to retrieve the prior from. If ``None`` (the default), will look in sections starting with 'prior'. Returns ------- distributions.JointDistribution The prior distribution. """ # Read variable and static parameters from the config file variable_params, _ = distributions.read_params_from_config( cp, prior_section=prior_section, vargs_section='variable_params', sargs_section='static_params') # Read constraints to apply to priors from the config file constraints = distributions.read_constraints_from_config(cp) # Get PyCBC distribution instances for each variable parameter in the # config file dists = distributions.read_distributions_from_config(cp, prior_section) # construct class that will return draws from the prior return distributions.JointDistribution(variable_params, *dists, **{"constraints": constraints})
def setUp(self): # set random seed numpy.random.seed(1024) # path to example configuration file for testing config_path = "/".join([os.path.dirname(os.path.realpath(__file__)), "../examples/distributions/example.ini"]) # get a set of simulated command line options for # configuration file reading class Arguments(object): config_overrides = [] config_delete = [] config_files = [config_path] self.opts = Arguments() # read configuration files self.cp = WorkflowConfigParser.from_cli(self.opts) self.variable_args, self.static_args = \ distributions.read_params_from_config(self.cp) self.constraints = distributions.read_constraints_from_config(self.cp) # read distributions self.dists = distributions.read_distributions_from_config(self.cp) # check that all distriubtions will be tested for dname in distributions.distribs: dclass = distributions.distribs[dname] if (not numpy.any([isinstance(dist, dclass) for dist in self.dists]) and dname not in EXCLUDE_DIST_NAMES): raise ValueError("There is no test for {}".format(dname))
def __init__( self, config_files: Union[List[Union[str, os.PathLike]], Union[str, os.PathLike]], seed: Optional[int] = None, ): """Class to generate gravitational waveform parameters using PyCBC workflow and distribution packages. """ if seed is not None: raise NotImplementedError( "Reproducible random seed not yet implemented.") self.config_files = config_files if isinstance( config_files, list) else [config_files] self.config_parser = WorkflowConfigParser( configFiles=self.config_files) self.parameters, self.static_args = read_params_from_config( self.config_parser) self.constraints = read_constraints_from_config(self.config_parser) self.transforms = read_transforms_from_config(self.config_parser) self.distribution = JointDistribution( self.parameters, *read_distributions_from_config(self.config_parser), **{'constraints': self.constraints}) # ensure statistics match output of self.parameters self.statistics = compute_parameter_statistics({ parameter: self.distribution.bounds[parameter] for parameter in self.parameters })
def _init_args_from_config(cls, cp): """Helper function for loading parameters. This retrieves the prior, variable parameters, static parameterss, constraints, sampling transforms, and waveform transforms (if provided). Parameters ---------- cp : ConfigParser Config parser to read. Returns ------- dict : Dictionary of the arguments. Has keys ``variable_params``, ``static_params``, ``prior``, and ``sampling_transforms``. If waveform transforms are in the config file, will also have ``waveform_transforms``. """ section = "model" prior_section = "prior" vparams_section = 'variable_params' sparams_section = 'static_params' constraint_section = 'constraint' # check that the name exists and matches name = cp.get(section, 'name') if name != cls.name: raise ValueError("section's {} name does not match mine {}".format( name, cls.name)) # get model parameters variable_params, static_params = distributions.read_params_from_config( cp, prior_section=prior_section, vargs_section=vparams_section, sargs_section=sparams_section) # get prior prior = cls.prior_from_config(cp, variable_params, prior_section, constraint_section) args = { 'variable_params': variable_params, 'static_params': static_params, 'prior': prior } # try to load sampling transforms try: sampling_transforms = SamplingTransforms.from_config( cp, variable_params) except NoSectionError: sampling_transforms = None args['sampling_transforms'] = sampling_transforms # get any waveform transforms if any(cp.get_subsections('waveform_transforms')): logging.info("Loading waveform transforms") args['waveform_transforms'] = \ transforms.read_transforms_from_config( cp, 'waveform_transforms') return args
def _init_args_from_config(cls, cp): """Helper function for loading parameters. This retrieves the prior, variable parameters, static parameterss, constraints, sampling transforms, and waveform transforms (if provided). Parameters ---------- cp : ConfigParser Config parser to read. Returns ------- dict : Dictionary of the arguments. Has keys ``variable_params``, ``static_params``, ``prior``, and ``sampling_transforms``. If waveform transforms are in the config file, will also have ``waveform_transforms``. """ section = "model" prior_section = "prior" vparams_section = 'variable_params' sparams_section = 'static_params' constraint_section = 'constraint' # check that the name exists and matches name = cp.get(section, 'name') if name != cls.name: raise ValueError("section's {} name does not match mine {}".format( name, cls.name)) # get model parameters variable_params, static_params = distributions.read_params_from_config( cp, prior_section=prior_section, vargs_section=vparams_section, sargs_section=sparams_section) # get prior prior = cls.prior_from_config(cp, variable_params, prior_section, constraint_section) args = {'variable_params': variable_params, 'static_params': static_params, 'prior': prior} # try to load sampling transforms try: sampling_transforms = SamplingTransforms.from_config( cp, variable_params) except ValueError: sampling_transforms = None args['sampling_transforms'] = sampling_transforms # get any waveform transforms if any(cp.get_subsections('waveform_transforms')): logging.info("Loading waveform transforms") args['waveform_transforms'] = \ transforms.read_transforms_from_config( cp, 'waveform_transforms') return args
def _init_args_from_config(cls, cp): """Helper function for loading parameters. This retrieves the prior, variable parameters, static parameterss, constraints, and sampling transforms. Parameters ---------- cp : ConfigParser Config parser to read. Returns ------- dict : Dictionary of the arguments. Has keys ``variable_params``, ``static_params``, ``prior``, and ``sampling_transforms``. """ section = "model" prior_section = "prior" vparams_section = 'variable_params' sparams_section = 'static_params' constraint_section = 'constraint' # check that the name exists and matches name = cp.get(section, 'name') if name != cls.name: raise ValueError("section's {} name does not match mine {}".format( name, cls.name)) # get model parameters variable_params, static_params = distributions.read_params_from_config( cp, prior_section=prior_section, vargs_section=vparams_section, sargs_section=sparams_section) # get prior prior = cls.prior_from_config(cp, variable_params, prior_section, constraint_section) args = { 'variable_params': variable_params, 'static_params': static_params, 'prior': prior } # try to load sampling transforms try: sampling_transforms = SamplingTransforms.from_config( cp, variable_params) except ValueError: sampling_transforms = None args['sampling_transforms'] = sampling_transforms # get any other keyword arguments provided args.update(cls.extra_args_from_config(cp, section, skip_args=['name'])) return args
def read_ini_config(file_path): """ Read in a `*.ini` config file, which is used mostly to specify the waveform simulation (for example, the waveform model, the parameter space for the binary black holes, etc.) and return its contents. Args: file_path (str): Path to the `*.ini` config file to be read in. Returns: A tuple `(variable_arguments, static_arguments)` where * `variable_arguments` should simply be a list of all the parameters which get randomly sampled from the specified distributions, usually using an instance of :class:`utils.waveforms.WaveformParameterGenerator`. * `static_arguments` should be a dictionary containing the keys and values of the parameters that are the same for each example that is generated (i.e., the non-physical parameters such as the waveform model and the sampling rate). """ # Make sure the config file actually exists if not os.path.exists(file_path): raise IOError('Specified configuration file does not exist: ' '{}'.format(file_path)) # Set up a parser for the PyCBC config file workflow_config_parser = WorkflowConfigParser(configFiles=[file_path]) # Read the variable_arguments and static_arguments using the parser variable_arguments, static_arguments = \ read_params_from_config(workflow_config_parser) # Typecast and amend the static arguments static_arguments = typecast_static_args(static_arguments) static_arguments = amend_static_args(static_arguments) return variable_arguments, static_arguments
def draw_samples_from_config(path, num=1, seed=150914): r""" Generate sampling points from a standalone .ini file. Parameters ---------- path : str The path to the .ini file. num : int The number of samples. seed: int The random seed for sampling. Returns -------- samples : pycbc.io.record.FieldArray The parameter values and names of sample(s). Examples -------- Draw a sample from the distribution defined in the .ini file: >>> import numpy as np >>> from pycbc.distributions.utils import draw_samples_from_config >>> # A path to the .ini file. >>> CONFIG_PATH = "./pycbc_bbh_prior.ini" >>> random_seed = np.random.randint(low=0, high=2**32-1) >>> sample = draw_samples_from_config( >>> path=CONFIG_PATH, num=1, seed=random_seed) >>> # Print all parameters. >>> print(sample.fieldnames) >>> print(sample) >>> # Print a certain parameter, for example 'mass1'. >>> print(sample[0]['mass1']) """ np.random.seed(seed) # Initialise InterpolatingConfigParser class. config_parser = InterpolatingConfigParser() # Read the file file = open(path, 'r') config_parser.read_file(file) file.close() # Get the vairable arguments from the .ini file. variable_args, _ = distributions.read_params_from_config( config_parser, prior_section='prior', vargs_section='variable_params') constraints = distributions.read_constraints_from_config(config_parser) if any(config_parser.get_subsections('waveform_transforms')): waveform_transforms = transforms.read_transforms_from_config( config_parser, 'waveform_transforms') else: waveform_transforms = None # Get prior distribution for each variable parameter. dists = distributions.read_distributions_from_config(config_parser) # Construct class that will draw the samples. randomsampler = distributions.JointDistribution( variable_args, *dists, **{"constraints": constraints}) # Draw samples from prior distribution. samples = randomsampler.rvs(size=int(num)) # Apply parameter transformation. if waveform_transforms is not None: samples = transforms.apply_transforms(samples, waveform_transforms) else: pass return samples