signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def __init__(self, pnOrder, fLow, fUpper, deltaF, f0=<NUM_LIT>,<EOL>write_metric=False):
self.pnOrder=pnOrder<EOL>self.fLow=fLow<EOL>self.fUpper=fUpper<EOL>self.deltaF=deltaF<EOL>self.f0=f0<EOL>self._moments=None<EOL>self.write_metric=write_metric<EOL>
Initialize an instance of the metricParameters by providing all options directly. See the help message associated with any code that uses the metric options for more details of how to set each of these, e.g. pycbc_aligned_stoch_bank --help
f15981:c1:m0
@classmethod<EOL><INDENT>def from_argparse(cls, opts):<DEDENT>
return cls(opts.pn_order, opts.f_low, opts.f_upper, opts.delta_f,f0=opts.f0, write_metric=opts.write_metric)<EOL>
Initialize an instance of the metricParameters class from an argparse.OptionParser instance. This assumes that insert_metric_calculation_options and verify_metric_calculation_options have already been called before initializing the class.
f15981:c1:m1
@property<EOL><INDENT>def psd(self):<DEDENT>
if not self._psd:<EOL><INDENT>errMsg = "<STR_LIT>"<EOL>errMsg += "<STR_LIT>"<EOL>raise ValueError(errMsg)<EOL><DEDENT>return self._psd<EOL>
A pyCBC FrequencySeries holding the appropriate PSD. Return the PSD used in the metric calculation.
f15981:c1:m2
@property<EOL><INDENT>def moments(self):<DEDENT>
return self._moments<EOL>
Moments structure This contains the result of all the integrals used in computing the metrics above. It can be used for the ethinca components calculation, or other similar calculations. This is composed of two compound dictionaries. The first entry indicates which moment is being calculated and the second entry indica...
f15981:c1:m4
@property<EOL><INDENT>def evals(self):<DEDENT>
if self._evals is None:<EOL><INDENT>errMsg = "<STR_LIT>"<EOL>errMsg += "<STR_LIT>"<EOL>raise ValueError(errMsg)<EOL><DEDENT>return self._evals<EOL>
The eigenvalues of the parameter space. This is a Dictionary of numpy.array Each entry in the dictionary corresponds to the different frequency ranges described in vary_fmax. If vary_fmax = False, the only entry will be f_upper, this corresponds to integrals in [f_low,f_upper). This entry is always present. Each other ...
f15981:c1:m6
@property<EOL><INDENT>def evecs(self):<DEDENT>
if self._evecs is None:<EOL><INDENT>errMsg = "<STR_LIT>"<EOL>errMsg += "<STR_LIT>"<EOL>raise ValueError(errMsg)<EOL><DEDENT>return self._evecs<EOL>
The eigenvectors of the parameter space. This is a Dictionary of numpy.matrix Each entry in the dictionary is as described under evals. Each numpy.matrix contains the eigenvectors which, with the eigenvalues in evals, are needed to rotate the coordinate system to one in which the metric is the identity matrix.
f15981:c1:m8
@property<EOL><INDENT>def metric(self):<DEDENT>
if self._metric is None:<EOL><INDENT>errMsg = "<STR_LIT>"<EOL>errMsg += "<STR_LIT>"<EOL>raise ValueError(errMsg)<EOL><DEDENT>return self._metric<EOL>
The metric of the parameter space. This is a Dictionary of numpy.matrix Each entry in the dictionary is as described under evals. Each numpy.matrix contains the metric of the parameter space in the Lambda_i coordinate system.
f15981:c1:m10
@property<EOL><INDENT>def time_unprojected_metric(self):<DEDENT>
if self._time_unprojected_metric is None:<EOL><INDENT>err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL><DEDENT>return self._time_unprojected_metric<EOL>
The metric of the parameter space with the time dimension unprojected. This is a Dictionary of numpy.matrix Each entry in the dictionary is as described under evals. Each numpy.matrix contains the metric of the parameter space in the Lambda_i, t coordinate system. The time components are always in the last [-1] positio...
f15981:c1:m12
@property<EOL><INDENT>def evecsCV(self):<DEDENT>
if self._evecsCV is None:<EOL><INDENT>errMsg = "<STR_LIT>"<EOL>errMsg += "<STR_LIT>"<EOL>raise ValueError(errMsg)<EOL><DEDENT>return self._evecsCV<EOL>
The eigenvectors of the principal directions of the mu space. This is a Dictionary of numpy.matrix Each entry in the dictionary is as described under evals. Each numpy.matrix contains the eigenvectors which, with the eigenvalues in evals, are needed to rotate the coordinate system to one in which the metric is the iden...
f15981:c1:m14
def __init__(self, minMass1, maxMass1, minMass2, maxMass2,<EOL>maxNSSpinMag=<NUM_LIT:0>, maxBHSpinMag=<NUM_LIT:0>, maxTotMass=None,<EOL>minTotMass=None, maxEta=None, minEta=<NUM_LIT:0>, <EOL>max_chirp_mass=None, min_chirp_mass=None, <EOL>ns_bh_boundary_mass=None, nsbhFlag=False,<EOL>remnant_mass_threshold=None, ns_eos=...
self.minMass1=minMass1<EOL>self.maxMass1=maxMass1<EOL>self.minMass2=minMass2<EOL>self.maxMass2=maxMass2<EOL>self.maxNSSpinMag=maxNSSpinMag<EOL>self.maxBHSpinMag=maxBHSpinMag<EOL>self.minTotMass = minMass1 + minMass2<EOL>if minTotMass and (minTotMass > self.minTotMass):<EOL><INDENT>self.minTotMass = minTotMass<EOL><DEDE...
Initialize an instance of the massRangeParameters by providing all options directly. See the help message associated with any code that uses the metric options for more details of how to set each of these. For e.g. pycbc_aligned_stoch_bank --help
f15981:c2:m0
@classmethod<EOL><INDENT>def from_argparse(cls, opts, nonSpin=False):<DEDENT>
if nonSpin:<EOL><INDENT>return cls(opts.min_mass1, opts.max_mass1, opts.min_mass2,<EOL>opts.max_mass2, maxTotMass=opts.max_total_mass,<EOL>minTotMass=opts.min_total_mass, maxEta=opts.max_eta,<EOL>minEta=opts.min_eta, max_chirp_mass=opts.max_chirp_mass,<EOL>min_chirp_mass=opts.min_chirp_mass,<EOL>remnant_mass_threshold=...
Initialize an instance of the massRangeParameters class from an argparse.OptionParser instance. This assumes that insert_mass_range_option_group and verify_mass_range_options have already been called before initializing the class.
f15981:c2:m1
def is_outside_range(self, mass1, mass2, spin1z, spin2z):
<EOL>if mass1 * <NUM_LIT> < self.minMass1:<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>if mass1 > self.maxMass1 * <NUM_LIT>:<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>if mass2 * <NUM_LIT> < self.minMass2:<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>if mass2 > self.maxMass2 * <NUM_LIT>:<EOL><INDENT>return <NUM_LIT:1><EOL...
Test if a given location in mass1, mass2, spin1z, spin2z is within the range of parameters allowed by the massParams object.
f15981:c2:m2
def __init__(self, pnOrder, cutoff, freqStep, fLow=None, full_ethinca=False,<EOL>time_ethinca=False):
self.full_ethinca=full_ethinca<EOL>self.time_ethinca=time_ethinca<EOL>self.doEthinca= self.full_ethinca or self.time_ethinca<EOL>self.pnOrder=pnOrder<EOL>self.cutoff=cutoff<EOL>self.freqStep=freqStep<EOL>self.fLow=fLow<EOL>if self.full_ethinca and self.time_ethinca:<EOL><INDENT>err_msg = "<STR_LIT>"<EOL>err_msg += "<ST...
Initialize an instance of ethincaParameters by providing all options directly. See the insert_ethinca_metric_options() function for explanation or e.g. run pycbc_geom_nonspinbank --help
f15981:c3:m0
@classmethod<EOL><INDENT>def from_argparse(cls, opts):<DEDENT>
return cls(opts.ethinca_pn_order, opts.filter_cutoff,<EOL>opts.ethinca_frequency_step, fLow=None,<EOL>full_ethinca=opts.calculate_ethinca_metric,<EOL>time_ethinca=opts.calculate_time_metric_components)<EOL>
Initialize an instance of the ethincaParameters class from an argparse.OptionParser instance. This assumes that insert_ethinca_metric_options and verify_ethinca_metric_options have already been called before initializing the class.
f15981:c3:m1
def estimate_mass_range(numPoints, massRangeParams, metricParams, fUpper,covary=True):
vals_set = get_random_mass(numPoints, massRangeParams)<EOL>mass1 = vals_set[<NUM_LIT:0>]<EOL>mass2 = vals_set[<NUM_LIT:1>]<EOL>spin1z = vals_set[<NUM_LIT:2>]<EOL>spin2z = vals_set[<NUM_LIT:3>]<EOL>if covary:<EOL><INDENT>lambdas = get_cov_params(mass1, mass2, spin1z, spin2z, metricParams,<EOL>fUpper)<EOL><DEDENT>else:<E...
This function will generate a large set of points with random masses and spins (using pycbc.tmpltbank.get_random_mass) and translate these points into the xi_i coordinate system for the given upper frequency cutoff. Parameters ---------- numPoints : int Number of systems to simulate massRangeParams : massRangePara...
f15982:m0
def get_random_mass_point_particles(numPoints, massRangeParams):
<EOL>mass = numpy.random.random(numPoints) *(massRangeParams.minTotMass**(-<NUM_LIT>/<NUM_LIT>)- massRangeParams.maxTotMass**(-<NUM_LIT>/<NUM_LIT>))+ massRangeParams.maxTotMass**(-<NUM_LIT>/<NUM_LIT>)<EOL>mass = mass**(-<NUM_LIT>/<NUM_LIT>)<EOL>maxmass2 = numpy.minimum(mass/<NUM_LIT>, massRangeParams.maxMass2)<EOL>minm...
This function will generate a large set of points within the chosen mass and spin space. It will also return the corresponding PN spin coefficients for ease of use later (though these may be removed at some future point). Parameters ---------- numPoints : int Number of systems to simulate massRangeParams : massRan...
f15982:m1
def get_random_mass(numPoints, massRangeParams):
<EOL>if massRangeParams.remnant_mass_threshold is None:<EOL><INDENT>mass1, mass2, spin1z, spin2z =get_random_mass_point_particles(numPoints, massRangeParams)<EOL><DEDENT>else:<EOL><INDENT>_, max_ns_g_mass = load_ns_sequence(massRangeParams.ns_eos)<EOL>if not os.path.isfile('<STR_LIT>'):<EOL><INDENT>logging.info("""<STR...
This function will generate a large set of points within the chosen mass and spin space, and with the desired minimum remnant disk mass (this applies to NS-BH systems only). It will also return the corresponding PN spin coefficients for ease of use later (though these may be removed at some future point). Parameters -...
f15982:m2
def get_cov_params(mass1, mass2, spin1z, spin2z, metricParams, fUpper,<EOL>lambda1=None, lambda2=None, quadparam1=None,<EOL>quadparam2=None):
<EOL>mus = get_conv_params(mass1, mass2, spin1z, spin2z, metricParams, fUpper,<EOL>lambda1=lambda1, lambda2=lambda2,<EOL>quadparam1=quadparam1, quadparam2=quadparam2)<EOL>xis = get_covaried_params(mus, metricParams.evecsCV[fUpper])<EOL>return xis<EOL>
Function to convert between masses and spins and locations in the xi parameter space. Xi = Cartesian metric and rotated to principal components. Parameters ----------- mass1 : float Mass of heavier body. mass2 : float Mass of lighter body. spin1z : float Spin of body 1. spin2z : float Spin of body 2. m...
f15982:m3
def get_conv_params(mass1, mass2, spin1z, spin2z, metricParams, fUpper,<EOL>lambda1=None, lambda2=None, quadparam1=None,<EOL>quadparam2=None):
<EOL>lambdas = get_chirp_params(mass1, mass2, spin1z, spin2z,<EOL>metricParams.f0, metricParams.pnOrder,<EOL>lambda1=lambda1, lambda2=lambda2,<EOL>quadparam1=quadparam1, quadparam2=quadparam2)<EOL>mus = get_mu_params(lambdas, metricParams, fUpper)<EOL>return mus<EOL>
Function to convert between masses and spins and locations in the mu parameter space. Mu = Cartesian metric, but not principal components. Parameters ----------- mass1 : float Mass of heavier body. mass2 : float Mass of lighter body. spin1z : float Spin of body 1. spin2z : float Spin of body 2. metricP...
f15982:m4
def get_mu_params(lambdas, metricParams, fUpper):
lambdas = numpy.array(lambdas, copy=False)<EOL>if len(lambdas.shape) == <NUM_LIT:1>:<EOL><INDENT>resize_needed = True<EOL>lambdas = lambdas[:,None]<EOL><DEDENT>else:<EOL><INDENT>resize_needed = False<EOL><DEDENT>evecs = metricParams.evecs[fUpper]<EOL>evals = metricParams.evals[fUpper]<EOL>evecs = numpy.array(evecs, cop...
Function to rotate from the lambda coefficients into position in the mu coordinate system. Mu = Cartesian metric, but not principal components. Parameters ----------- lambdas : list of floats or numpy.arrays Position of the system(s) in the lambda coefficients metricParams : metricParameters instance Structure...
f15982:m5
def get_covaried_params(mus, evecsCV):
mus = numpy.array(mus, copy=False)<EOL>if len(mus.shape) == <NUM_LIT:1>:<EOL><INDENT>resize_needed = True<EOL>mus = mus[:,None]<EOL><DEDENT>else:<EOL><INDENT>resize_needed = False<EOL><DEDENT>xis = ((mus.T).dot(evecsCV)).T<EOL>if resize_needed:<EOL><INDENT>xis = numpy.ndarray.flatten(xis)<EOL><DEDENT>return xis<EOL>
Function to rotate from position(s) in the mu_i coordinate system into the position(s) in the xi_i coordinate system Parameters ----------- mus : list of floats or numpy.arrays Position of the system(s) in the mu coordinate system evecsCV : numpy.matrix This matrix is used to perform the rotation to the xi_i ...
f15982:m6
def rotate_vector(evecs, old_vector, rescale_factor, index):
temp = <NUM_LIT:0><EOL>for i in range(len(evecs)):<EOL><INDENT>temp += (evecs[i,index] * rescale_factor) * old_vector[i]<EOL><DEDENT>return temp<EOL>
Function to find the position of the system(s) in one of the xi_i or mu_i directions. Parameters ----------- evecs : numpy.matrix Matrix of the eigenvectors of the metric in lambda_i coordinates. Used to rotate to a Cartesian coordinate system. old_vector : list of floats or numpy.arrays The position of th...
f15982:m7
def get_point_distance(point1, point2, metricParams, fUpper):
aMass1 = point1[<NUM_LIT:0>]<EOL>aMass2 = point1[<NUM_LIT:1>]<EOL>aSpin1 = point1[<NUM_LIT:2>]<EOL>aSpin2 = point1[<NUM_LIT:3>]<EOL>bMass1 = point2[<NUM_LIT:0>]<EOL>bMass2 = point2[<NUM_LIT:1>]<EOL>bSpin1 = point2[<NUM_LIT:2>]<EOL>bSpin2 = point2[<NUM_LIT:3>]<EOL>aXis = get_cov_params(aMass1, aMass2, aSpin1, aSpin2, me...
Function to calculate the mismatch between two points, supplied in terms of the masses and spins, using the xi_i parameter space metric to approximate the mismatch of the two points. Can also take one of the points as an array of points and return an array of mismatches (but only one can be an array!) point1 : List of...
f15982:m8
def calc_point_dist(vsA, entryA):
chi_diffs = vsA - entryA<EOL>val = ((chi_diffs)*(chi_diffs)).sum()<EOL>return val<EOL>
This function is used to determine the distance between two points. Parameters ---------- vsA : list or numpy.array or similar An array of point 1's position in the \chi_i coordinate system entryA : list or numpy.array or similar An array of point 2's position in the \chi_i coordinate system MMdistA : float ...
f15982:m9
def calc_point_dist_vary(mus1, fUpper1, mus2, fUpper2, fMap, norm_map, MMdistA):
f_upper = min(fUpper1, fUpper2)<EOL>f_other = max(fUpper1, fUpper2)<EOL>idx = fMap[f_upper]<EOL>vecs1 = mus1[idx]<EOL>vecs2 = mus2[idx]<EOL>val = ((vecs1 - vecs2)*(vecs1 - vecs2)).sum()<EOL>if (val > MMdistA):<EOL><INDENT>return False<EOL><DEDENT>norm_fac = norm_map[f_upper] / norm_map[f_other]<EOL>val = <NUM_LIT:1> - ...
Function to determine if two points, with differing upper frequency cutoffs have a mismatch < MMdistA for *both* upper frequency cutoffs. Parameters ---------- mus1 : List of numpy arrays mus1[i] will give the array of point 1's position in the \chi_j coordinate system. The i element corresponds to varying val...
f15982:m11
def find_max_and_min_frequencies(name, mass_range_params, freqs):
cutoff_fns = pnutils.named_frequency_cutoffs<EOL>if name not in cutoff_fns.keys():<EOL><INDENT>err_msg = "<STR_LIT>" %name<EOL>err_msg += "<STR_LIT>" + "<STR_LIT:U+0020>".join(cutoff_fns.keys())<EOL>raise ValueError(err_msg)<EOL><DEDENT>total_mass_approxs = {<EOL>"<STR_LIT>": pnutils.f_SchwarzISCO,<EOL>"<STR_LIT>" : p...
ADD DOCS
f15982:m12
def return_nearest_cutoff(name, mass_dict, freqs):
<EOL>if len(freqs) == <NUM_LIT:1>:<EOL><INDENT>return numpy.zeros(len(mass_dict['<STR_LIT>']), dtype=float) + freqs[<NUM_LIT:0>]<EOL><DEDENT>cutoff_fns = pnutils.named_frequency_cutoffs<EOL>if name not in cutoff_fns.keys():<EOL><INDENT>err_msg = "<STR_LIT>" %name<EOL>err_msg += "<STR_LIT>" + "<STR_LIT:U+0020>".join(cut...
Given an array of total mass values and an (ascending) list of frequencies, this will calculate the specified cutoff formula for each mtotal and return the nearest frequency to each cutoff from the input list. Currently only supports cutoffs that are functions of the total mass and no other parameters (SchwarzISCO, Lig...
f15982:m13
def find_closest_calculated_frequencies(input_freqs, metric_freqs):
try:<EOL><INDENT>refEv = numpy.zeros(len(input_freqs),dtype=float)<EOL><DEDENT>except TypeError:<EOL><INDENT>refEv = numpy.zeros(<NUM_LIT:1>, dtype=float)<EOL>input_freqs = numpy.array([input_freqs])<EOL><DEDENT>if len(metric_freqs) == <NUM_LIT:1>:<EOL><INDENT>refEv[:] = metric_freqs[<NUM_LIT:0>]<EOL>return refEv<EOL><...
Given a value (or array) of input frequencies find the closest values in the list of frequencies calculated in the metric. Parameters ----------- input_freqs : numpy.array or float The frequency(ies) that you want to find the closest value in metric_freqs metric_freqs : numpy.array The list of frequencies ...
f15982:m14
def outspiral_loop(N):
<EOL>X,Y = numpy.meshgrid(numpy.arange(-N,N+<NUM_LIT:1>), numpy.arange(-N,N+<NUM_LIT:1>))<EOL>X = numpy.ndarray.flatten(X)<EOL>Y = numpy.ndarray.flatten(Y)<EOL>X = numpy.array(X, dtype=int)<EOL>Y = numpy.array(Y, dtype=int)<EOL>G = numpy.sqrt(X**<NUM_LIT:2>+Y**<NUM_LIT:2>)<EOL>out_arr = numpy.array([X,Y,G])<EOL>sorted_...
Return a list of points that will loop outwards in a 2D lattice in terms of distance from a central point. So if N=2 this will be [0,0], [0,1], [0,-1],[1,0],[-1,0],[1,1] .... This is useful when you want to loop over a number of bins, but want to start in the center and work outwards.
f15982:m15
def return_empty_sngl(nones=False):
sngl = lsctables.SnglInspiral()<EOL>cols = lsctables.SnglInspiralTable.validcolumns<EOL>if nones:<EOL><INDENT>for entry in cols:<EOL><INDENT>setattr(sngl, entry, None)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for entry in cols.keys():<EOL><INDENT>if cols[entry] in ['<STR_LIT>','<STR_LIT>']:<EOL><INDENT>setattr(sngl,entry,...
Function to create a SnglInspiral object where all columns are populated but all are set to values that test False (ie. strings to '', floats/ints to 0, ...). This avoids errors when you try to create a table containing columns you don't care about, but which still need populating. NOTE: This will also produce a proces...
f15983:m0
def return_search_summary(start_time=<NUM_LIT:0>, end_time=<NUM_LIT:0>, nevents=<NUM_LIT:0>,<EOL>ifos=None, **kwargs):
if ifos is None:<EOL><INDENT>ifos = []<EOL><DEDENT>search_summary = lsctables.SearchSummary()<EOL>cols = lsctables.SearchSummaryTable.validcolumns<EOL>for entry in cols.keys():<EOL><INDENT>if cols[entry] in ['<STR_LIT>','<STR_LIT>']:<EOL><INDENT>setattr(search_summary,entry,<NUM_LIT:0.>)<EOL><DEDENT>elif cols[entry] ==...
Function to create a SearchSummary object where all columns are populated but all are set to values that test False (ie. strings to '', floats/ints to 0, ...). This avoids errors when you try to create a table containing columns you don't care about, but which still need populating. NOTE: This will also produce a proce...
f15983:m1
def convert_to_sngl_inspiral_table(params, proc_id):
sngl_inspiral_table = lsctables.New(lsctables.SnglInspiralTable)<EOL>col_names = ['<STR_LIT>','<STR_LIT>','<STR_LIT>','<STR_LIT>']<EOL>for values in params:<EOL><INDENT>tmplt = return_empty_sngl()<EOL>tmplt.process_id = proc_id<EOL>for colname, value in zip(col_names, values):<EOL><INDENT>setattr(tmplt, colname, value)...
Convert a list of m1,m2,spin1z,spin2z values into a basic sngl_inspiral table with mass and spin parameters populated and event IDs assigned Parameters ----------- params : iterable Each entry in the params iterable should be a sequence of [mass1, mass2, spin1z, spin2z] in that order proc_id : ilwd char Pr...
f15983:m2
def calculate_ethinca_metric_comps(metricParams, ethincaParams, mass1, mass2,<EOL>spin1z=<NUM_LIT:0.>, spin2z=<NUM_LIT:0.>, full_ethinca=True):
if (float(spin1z) != <NUM_LIT:0.> or float(spin2z) != <NUM_LIT:0.>) and full_ethinca:<EOL><INDENT>raise NotImplementedError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>f0 = metricParams.f0<EOL>if f0 != metricParams.fLow:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if ethincaParams.fLow is not Non...
Calculate the Gamma components needed to use the ethinca metric. At present this outputs the standard TaylorF2 metric over the end time and chirp times \tau_0 and \tau_3. A desirable upgrade might be to use the \chi coordinates [defined WHERE?] for metric distance instead of \tau_0 and \tau_3. The lower frequency cutof...
f15983:m3
def output_sngl_inspiral_table(outputFile, tempBank, metricParams,<EOL>ethincaParams, programName="<STR_LIT>", optDict = None,<EOL>outdoc=None, **kwargs):
if optDict is None:<EOL><INDENT>optDict = {}<EOL><DEDENT>if outdoc is None:<EOL><INDENT>outdoc = ligolw.Document()<EOL>outdoc.appendChild(ligolw.LIGO_LW())<EOL><DEDENT>ifos = []<EOL>if '<STR_LIT>' in optDict.keys():<EOL><INDENT>if optDict['<STR_LIT>'] is not None:<EOL><INDENT>ifos = [optDict['<STR_LIT>'][<NUM_LIT:0>:<N...
Function that converts the information produced by the various pyCBC bank generation codes into a valid LIGOLW xml file containing a sngl_inspiral table and outputs to file. Parameters ----------- outputFile : string Name of the file that the bank will be written to tempBank : iterable Each entry in the tempBa...
f15983:m4
def generate_mapping(order):
mapping = {}<EOL>mapping['<STR_LIT>'] = <NUM_LIT:0><EOL>if order == '<STR_LIT>':<EOL><INDENT>return mapping<EOL><DEDENT>mapping['<STR_LIT>'] = <NUM_LIT:1><EOL>if order == '<STR_LIT>':<EOL><INDENT>return mapping<EOL><DEDENT>mapping['<STR_LIT>'] = <NUM_LIT:2><EOL>if order == '<STR_LIT>':<EOL><INDENT>return mapping<EOL><D...
This function will take an order string and return a mapping between components in the metric and the various Lambda components. This must be used (and consistently used) when generating the metric *and* when transforming to/from the xi_i coordinates to the lambda_i coordinates. NOTE: This is not a great way of doing ...
f15984:m0
def generate_inverse_mapping(order):
mapping = generate_mapping(order)<EOL>inv_mapping = {}<EOL>for key,value in mapping.items():<EOL><INDENT>inv_mapping[value] = key<EOL><DEDENT>return inv_mapping<EOL>
Genereate a lambda entry -> PN order map. This function will generate the opposite of generate mapping. So where generate_mapping gives dict[key] = item this will give dict[item] = key. Valid PN orders are: {} Parameters ---------- order : string A string containing a PN order. Val...
f15984:m1
def get_ethinca_orders():
ethinca_orders = {"<STR_LIT>" : <NUM_LIT:0>,<EOL>"<STR_LIT>" : <NUM_LIT:2>,<EOL>"<STR_LIT>" : <NUM_LIT:3>,<EOL>"<STR_LIT>" : <NUM_LIT:4>,<EOL>"<STR_LIT>" : <NUM_LIT:5>,<EOL>"<STR_LIT>" : <NUM_LIT:6>,<EOL>"<STR_LIT>" : <NUM_LIT:7><EOL>}<EOL>return ethinca_orders<EOL>
Returns the dictionary mapping TaylorF2 PN order names to twice-PN orders (powers of v/c)
f15984:m2
def ethinca_order_from_string(order):
if order in get_ethinca_orders().keys():<EOL><INDENT>return get_ethinca_orders()[order]<EOL><DEDENT>else: raise ValueError("<STR_LIT>"+str(order)+"<STR_LIT>"<EOL>"<STR_LIT>"+<EOL>str(get_ethinca_orders().keys()))<EOL>
Returns the integer giving twice the post-Newtonian order used by the ethinca calculation. Currently valid only for TaylorF2 metric Parameters ---------- order : string Returns ------- int
f15984:m3
def get_chirp_params(mass1, mass2, spin1z, spin2z, f0, order,<EOL>quadparam1=None, quadparam2=None, lambda1=None,<EOL>lambda2=None):
<EOL>sngl_inp = False<EOL>try:<EOL><INDENT>num_points = len(mass1)<EOL><DEDENT>except TypeError:<EOL><INDENT>sngl_inp = True<EOL>mass1 = numpy.array([mass1])<EOL>mass2 = numpy.array([mass2])<EOL>spin1z = numpy.array([spin1z])<EOL>spin2z = numpy.array([spin2z])<EOL>if quadparam1 is not None:<EOL><INDENT>quadparam1 = num...
Take a set of masses and spins and convert to the various lambda coordinates that describe the orbital phase. Accepted PN orders are: {} Parameters ---------- mass1 : float or array Mass1 of input(s). mass2 : float or array Mass2 of input(s). spin1z : float or array Parallel spin component(s) of body 1. sp...
f15984:m4
def __init__(self, mass_range_params, metric_params, ref_freq,<EOL>bin_spacing, bin_range_check=<NUM_LIT:1>):
<EOL>self.spin_warning_given = False<EOL>self.mass_range_params = mass_range_params<EOL>self.metric_params = metric_params<EOL>self.ref_freq = ref_freq<EOL>self.bin_spacing = bin_spacing<EOL>vals = coord_utils.estimate_mass_range(<NUM_LIT>, mass_range_params,<EOL>metric_params, ref_freq, covary=True)<EOL>chi1_max = val...
Set up the partitioned template bank class. The combination of the reference frequency, the bin spacing and the metric dictates how the parameter space will be partitioned. Parameters ----------- mass_range_params : massRangeParameters object An initialized massRangeParameters object holding the details of the...
f15985:c0:m0
def get_point_from_bins_and_idx(self, chi1_bin, chi2_bin, idx):
mass1 = self.massbank[chi1_bin][chi2_bin]['<STR_LIT>'][idx]<EOL>mass2 = self.massbank[chi1_bin][chi2_bin]['<STR_LIT>'][idx]<EOL>spin1z = self.massbank[chi1_bin][chi2_bin]['<STR_LIT>'][idx]<EOL>spin2z = self.massbank[chi1_bin][chi2_bin]['<STR_LIT>'][idx]<EOL>return mass1, mass2, spin1z, spin2z<EOL>
Find masses and spins given bin numbers and index. Given the chi1 bin, chi2 bin and an index, return the masses and spins of the point at that index. Will fail if no point exists there. Parameters ----------- chi1_bin : int The bin number for chi1. chi2_bin ...
f15985:c0:m1
def get_freq_map_and_normalizations(self, frequency_list,<EOL>upper_freq_formula):
self.frequency_map = {}<EOL>self.normalization_map = {}<EOL>self.upper_freq_formula = upper_freq_formula<EOL>frequency_list.sort()<EOL>for idx, frequency in enumerate(frequency_list):<EOL><INDENT>self.frequency_map[frequency] = idx<EOL>self.normalization_map[frequency] =(self.metric_params.moments['<STR_LIT>'][frequenc...
If using the --vary-fupper capability we need to store the mapping between index and frequencies in the list. We also precalculate the normalization factor at every frequency, which is used when estimating overlaps to account for abrupt changes in termination frequency. Parameters ----------- frequency_list : array of...
f15985:c0:m2
def find_point_bin(self, chi_coords):
<EOL>chi1_bin = int((chi_coords[<NUM_LIT:0>] - self.chi1_min) // self.bin_spacing)<EOL>chi2_bin = int((chi_coords[<NUM_LIT:1>] - self.chi2_min) // self.bin_spacing)<EOL>self.check_bin_existence(chi1_bin, chi2_bin)<EOL>return chi1_bin, chi2_bin<EOL>
Given a set of coordinates in the chi parameter space, identify the indices of the chi1 and chi2 bins that the point occurs in. Returns these indices. Parameters ----------- chi_coords : numpy.array The position of the point in the chi coordinates. Returns -------- chi1_bin : int Index of the chi_1 bin. chi2_...
f15985:c0:m3
def check_bin_existence(self, chi1_bin, chi2_bin):
bin_range_check = self.bin_range_check<EOL>if ( (chi1_bin < self.min_chi1_bin+bin_range_check) or<EOL>(chi1_bin > self.max_chi1_bin-bin_range_check) or<EOL>(chi2_bin < self.min_chi2_bin+bin_range_check) or<EOL>(chi2_bin > self.max_chi2_bin-bin_range_check) ):<EOL><INDENT>for temp_chi1 in xrange(chi1_bin-bin_range_check...
Given indices for bins in chi1 and chi2 space check that the bin exists in the object. If not add it. Also check for the existence of all bins within +/- self.bin_range_check and add if not present. Parameters ----------- chi1_bin : int The index of the chi1_bin to check chi2_bin : int The index of the chi2_bi...
f15985:c0:m4
def calc_point_distance(self, chi_coords):
chi1_bin, chi2_bin = self.find_point_bin(chi_coords)<EOL>min_dist = <NUM_LIT><EOL>indexes = None<EOL>for chi1_bin_offset, chi2_bin_offset in self.bin_loop_order:<EOL><INDENT>curr_chi1_bin = chi1_bin + chi1_bin_offset<EOL>curr_chi2_bin = chi2_bin + chi2_bin_offset<EOL>for idx, bank_chis inenumerate(self.bank[curr_chi1_b...
Calculate distance between point and the bank. Return the closest distance. Parameters ----------- chi_coords : numpy.array The position of the point in the chi coordinates. Returns -------- min_dist : float The smallest **SQUARED** metric distance between the test point and the bank. indexes : The chi1_b...
f15985:c0:m5
def calc_point_distance_vary(self, chi_coords, point_fupper, mus):
chi1_bin, chi2_bin = self.find_point_bin(chi_coords)<EOL>min_dist = <NUM_LIT><EOL>indexes = None<EOL>for chi1_bin_offset, chi2_bin_offset in self.bin_loop_order:<EOL><INDENT>curr_chi1_bin = chi1_bin + chi1_bin_offset<EOL>curr_chi2_bin = chi2_bin + chi2_bin_offset<EOL>curr_bank = self.massbank[curr_chi1_bin][curr_chi2_b...
Calculate distance between point and the bank allowing the metric to vary based on varying upper frequency cutoff. Slower than calc_point_distance, but more reliable when upper frequency cutoff can change a lot. Parameters ----------- chi_coords : numpy.array The position of the point in the chi coordinates. point...
f15985:c0:m7
def add_point_by_chi_coords(self, chi_coords, mass1, mass2, spin1z, spin2z,<EOL>point_fupper=None, mus=None):
chi1_bin, chi2_bin = self.find_point_bin(chi_coords)<EOL>self.bank[chi1_bin][chi2_bin].append(copy.deepcopy(chi_coords))<EOL>curr_bank = self.massbank[chi1_bin][chi2_bin]<EOL>if curr_bank['<STR_LIT>'].size:<EOL><INDENT>curr_bank['<STR_LIT>'] = numpy.append(curr_bank['<STR_LIT>'],<EOL>numpy.array([mass1]))<EOL>curr_bank...
Add a point to the partitioned template bank. The point_fupper and mus kwargs must be provided for all templates if the vary fupper capability is desired. This requires that the chi_coords, as well as mus and point_fupper if needed, to be precalculated. If you just have the masses and don't want to worry about translat...
f15985:c0:m9
def add_point_by_masses(self, mass1, mass2, spin1z, spin2z,<EOL>vary_fupper=False):
<EOL>if mass2 > mass1:<EOL><INDENT>if not self.spin_warning_given:<EOL><INDENT>warn_msg = "<STR_LIT>"<EOL>warn_msg += "<STR_LIT>"<EOL>warn_msg += "<STR_LIT>"<EOL>warn_msg += "<STR_LIT>"<EOL>logging.warn(warn_msg)<EOL>self.spin_warning_given = True<EOL><DEDENT><DEDENT>if self.mass_range_params.is_outside_range(mass1, ma...
Add a point to the template bank. This differs from add point to bank as it assumes that the chi coordinates and the products needed to use vary_fupper have not already been calculated. This function calculates these products and then calls add_point_by_chi_coords. This function also carries out a number of sanity chec...
f15985:c0:m10
def add_tmpltbank_from_xml_table(self, sngl_table, vary_fupper=False):
for sngl in sngl_table:<EOL><INDENT>self.add_point_by_masses(sngl.mass1, sngl.mass2, sngl.spin1z,<EOL>sngl.spin2z, vary_fupper=vary_fupper)<EOL><DEDENT>
This function will take a sngl_inspiral_table of templates and add them into the partitioned template bank object. Parameters ----------- sngl_table : sngl_inspiral_table List of sngl_inspiral templates. vary_fupper : False If given also include the additional information needed to compute distances with a...
f15985:c0:m11
def add_tmpltbank_from_hdf_file(self, hdf_fp, vary_fupper=False):
mass1s = hdf_fp['<STR_LIT>'][:]<EOL>mass2s = hdf_fp['<STR_LIT>'][:]<EOL>spin1zs = hdf_fp['<STR_LIT>'][:]<EOL>spin2zs = hdf_fp['<STR_LIT>'][:]<EOL>for idx in xrange(len(mass1s)):<EOL><INDENT>self.add_point_by_masses(mass1s[idx], mass2s[idx], spin1zs[idx],<EOL>spin2zs[idx], vary_fupper=vary_fupper)<EOL><DEDENT>
This function will take a pointer to an open HDF File object containing a list of templates and add them into the partitioned template bank object. Parameters ----------- hdf_fp : h5py.File object The template bank in HDF5 format. vary_fupper : False If given also include the additional information needed to c...
f15985:c0:m12
def output_all_points(self):
mass1 = []<EOL>mass2 = []<EOL>spin1z = []<EOL>spin2z = []<EOL>for i in self.massbank.keys():<EOL><INDENT>for j in self.massbank[i].keys():<EOL><INDENT>for k in xrange(len(self.massbank[i][j]['<STR_LIT>'])):<EOL><INDENT>curr_bank = self.massbank[i][j]<EOL>mass1.append(curr_bank['<STR_LIT>'][k])<EOL>mass2.append(curr_ban...
Return all points in the bank. Return all points in the bank as lists of m1, m2, spin1z, spin2z. Returns ------- mass1 : list List of mass1 values. mass2 : list List of mass2 values. spin1z : list List of spin1z values. spin2z...
f15985:c0:m13
def generate_hexagonal_lattice(maxv1, minv1, maxv2, minv2, mindist):
if minv1 > maxv1:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if minv2 > maxv2:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>v1s = [minv1]<EOL>v2s = [minv2]<EOL>initPoint = [minv1,minv2]<EOL>initLine = [initPoint]<EOL>tmpv1 = minv1<EOL>while (tmpv1 < maxv1):<EOL><INDENT>tmpv1 = tmpv1 + (<NUM_LIT:3> *...
This function generates a 2-dimensional lattice of points using a hexagonal lattice. Parameters ----------- maxv1 : float Largest value in the 1st dimension to cover minv1 : float Smallest value in the 1st dimension to cover maxv2 : float Largest value in the 2nd dimension to cover minv2 : float Smalle...
f15986:m0
def generate_anstar_3d_lattice(maxv1, minv1, maxv2, minv2, maxv3, minv3,mindist):
<EOL>try:<EOL><INDENT>import lalpulsar<EOL><DEDENT>except:<EOL><INDENT>raise ImportError("<STR_LIT>")<EOL><DEDENT>tiling = lalpulsar.CreateLatticeTiling(<NUM_LIT:3>)<EOL>lalpulsar.SetLatticeTilingConstantBound(tiling, <NUM_LIT:0>, minv1, maxv1)<EOL>lalpulsar.SetLatticeTilingConstantBound(tiling, <NUM_LIT:1>, minv2, max...
This function calls into LAL routines to generate a 3-dimensional array of points using the An^* lattice. Parameters ----------- maxv1 : float Largest value in the 1st dimension to cover minv1 : float Smallest value in the 1st dimension to cover maxv2 : float Largest value in the 2nd dimension to cover min...
f15986:m1
def get_physical_covaried_masses(xis, bestMasses, bestXis, req_match,<EOL>massRangeParams, metricParams, fUpper,<EOL>giveUpThresh = <NUM_LIT>):
<EOL>origScaleFactor = <NUM_LIT:1><EOL>xi_size = len(xis)<EOL>scaleFactor = origScaleFactor<EOL>bestChirpmass = bestMasses[<NUM_LIT:0>] * (bestMasses[<NUM_LIT:1>])**(<NUM_LIT>/<NUM_LIT>)<EOL>count = <NUM_LIT:0><EOL>unFixedCount = <NUM_LIT:0><EOL>currDist = <NUM_LIT><EOL>while(<NUM_LIT:1>):<EOL><INDENT>if count:<EOL><IN...
This function takes the position of a point in the xi parameter space and iteratively finds a close point in the physical coordinate space (masses and spins). Parameters ----------- xis : list or array Desired position of the point in the xi space. If only N values are provided and the xi space's dimension is ...
f15988:m0
def get_mass_distribution(bestMasses, scaleFactor, massRangeParams,<EOL>metricParams, fUpper,<EOL>numJumpPoints=<NUM_LIT:100>, chirpMassJumpFac=<NUM_LIT>,<EOL>etaJumpFac=<NUM_LIT>, spin1zJumpFac=<NUM_LIT>,<EOL>spin2zJumpFac=<NUM_LIT>):
<EOL>bestChirpmass = bestMasses[<NUM_LIT:0>]<EOL>bestEta = bestMasses[<NUM_LIT:1>]<EOL>bestSpin1z = bestMasses[<NUM_LIT:2>]<EOL>bestSpin2z = bestMasses[<NUM_LIT:3>]<EOL>chirpmass = bestChirpmass * (<NUM_LIT:1> - (numpy.random.random(numJumpPoints)-<NUM_LIT:0.5>)* chirpMassJumpFac * scaleFactor )<EOL>etaRange = massRang...
Given a set of masses, this function will create a set of points nearby in the mass space and map these to the xi space. Parameters ----------- bestMasses : list Contains [ChirpMass, eta, spin1z, spin2z]. Points will be placed around tjos scaleFactor : float This parameter describes the radius away from be...
f15988:m1
def stack_xi_direction_brute(xis, bestMasses, bestXis, direction_num,<EOL>req_match, massRangeParams, metricParams, fUpper,<EOL>scaleFactor=<NUM_LIT>, numIterations=<NUM_LIT>):
<EOL>ximin = find_xi_extrema_brute(xis, bestMasses, bestXis, direction_num,req_match, massRangeParams, metricParams,fUpper, find_minimum=True,scaleFactor=scaleFactor,numIterations=numIterations)<EOL>ximax = find_xi_extrema_brute(xis, bestMasses, bestXis, direction_num,req_match, massRangeParams, metricParams,fUpper, fi...
This function is used to assess the depth of the xi_space in a specified dimension at a specified point in the higher dimensions. It does this by iteratively throwing points at the space to find maxima and minima. Parameters ----------- xis : list or array Position in the xi space at which to assess the depth. Th...
f15988:m2
def find_xi_extrema_brute(xis, bestMasses, bestXis, direction_num, req_match,massRangeParams, metricParams, fUpper,find_minimum=False, scaleFactor=<NUM_LIT>,numIterations=<NUM_LIT>):
<EOL>xi_size = len(xis)<EOL>bestChirpmass = bestMasses[<NUM_LIT:0>] * (bestMasses[<NUM_LIT:1>])**(<NUM_LIT>/<NUM_LIT>)<EOL>if find_minimum:<EOL><INDENT>xiextrema = <NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>xiextrema = -<NUM_LIT><EOL><DEDENT>for _ in range(numIterations):<EOL><INDENT>totmass, eta, spin1z, spin2z, _, _, ne...
This function is used to find the largest or smallest value of the xi space in a specified dimension at a specified point in the higher dimensions. It does this by iteratively throwing points at the space to find extrema. Parameters ----------- xis : list or array Position in the xi space at which to assess the d...
f15988:m3
def determine_eigen_directions(metricParams, preserveMoments=False,<EOL>vary_fmax=False, vary_density=None):
evals = {}<EOL>evecs = {}<EOL>metric = {}<EOL>unmax_metric = {}<EOL>if not (metricParams.moments and preserveMoments):<EOL><INDENT>get_moments(metricParams, vary_fmax=vary_fmax,<EOL>vary_density=vary_density)<EOL><DEDENT>list = metricParams.moments['<STR_LIT>'].keys()<EOL>for item in list:<EOL><INDENT>Js = {}<EOL>for i...
This function will calculate the coordinate transfomations that are needed to rotate from a coordinate system described by the various Lambda components in the frequency expansion, to a coordinate system where the metric is Cartesian. Parameters ----------- metricParams : metricParameters instance Structure holdin...
f15989:m0
def get_moments(metricParams, vary_fmax=False, vary_density=None):
<EOL>psd_amp = metricParams.psd.data<EOL>psd_f = numpy.arange(len(psd_amp), dtype=float) * metricParams.deltaF<EOL>new_f, new_amp = interpolate_psd(psd_f, psd_amp, metricParams.deltaF)<EOL>funct = lambda x,f0: <NUM_LIT:1><EOL>I7 = calculate_moment(new_f, new_amp, metricParams.fLow,metricParams.fUpper, metricParams.f0, ...
This function will calculate the various integrals (moments) that are needed to compute the metric used in template bank placement and coincidence. Parameters ----------- metricParams : metricParameters instance Structure holding all the options for construction of the metric. vary_fmax : boolean, optional (defaul...
f15989:m1
def interpolate_psd(psd_f, psd_amp, deltaF):
<EOL>new_psd_f = []<EOL>new_psd_amp = []<EOL>fcurr = psd_f[<NUM_LIT:0>]<EOL>for i in range(len(psd_f) - <NUM_LIT:1>):<EOL><INDENT>f_low = psd_f[i]<EOL>f_high = psd_f[i+<NUM_LIT:1>]<EOL>amp_low = psd_amp[i]<EOL>amp_high = psd_amp[i+<NUM_LIT:1>]<EOL>while(<NUM_LIT:1>):<EOL><INDENT>if fcurr > f_high:<EOL><INDENT>break<EOL...
Function to interpolate a PSD to a different value of deltaF. Uses linear interpolation. Parameters ---------- psd_f : numpy.array or list or similar List of the frequencies contained within the PSD. psd_amp : numpy.array or list or similar List of the PSD values at the frequencies in psd_f. deltaF : float ...
f15989:m2
def calculate_moment(psd_f, psd_amp, fmin, fmax, f0, funct,<EOL>norm=None, vary_fmax=False, vary_density=None):
<EOL>psd_x = psd_f / f0<EOL>deltax = psd_x[<NUM_LIT:1>] - psd_x[<NUM_LIT:0>]<EOL>mask = numpy.logical_and(psd_f > fmin, psd_f < fmax)<EOL>psdf_red = psd_f[mask]<EOL>comps_red = psd_x[mask] ** (-<NUM_LIT>/<NUM_LIT>) * funct(psd_x[mask], f0) * deltax /psd_amp[mask]<EOL>moment = {}<EOL>moment[fmax] = comps_red.sum()<EOL>i...
Function for calculating one of the integrals used to construct a template bank placement metric. The integral calculated will be \int funct(x) * (psd_x)**(-7./3.) * delta_x / PSD(x) where x = f / f0. The lower frequency cutoff is given by fmin, see the parameters below for details on how the upper frequency cutoff i...
f15989:m3
def calculate_metric(Js, logJs, loglogJs, logloglogJs, loglogloglogJs,mapping):
<EOL>maxLen = len(mapping.keys())<EOL>metric = numpy.matrix(numpy.zeros(shape=(maxLen,maxLen),dtype=float))<EOL>unmax_metric = numpy.matrix(numpy.zeros(shape=(maxLen+<NUM_LIT:1>,maxLen+<NUM_LIT:1>),<EOL>dtype=float))<EOL>for i in range(<NUM_LIT:16>):<EOL><INDENT>for j in range(<NUM_LIT:16>):<EOL><INDENT>calculate_metri...
This function will take the various integrals calculated by get_moments and convert this into a metric for the appropriate parameter space. Parameters ----------- Js : Dictionary The list of (log^0 x) * x**(-i/3) integrals computed by get_moments() The index is Js[i] logJs : Dictionary The list of (log^1 x...
f15989:m4
def calculate_metric_comp(gs, unmax_metric, i, j, Js, logJs, loglogJs,<EOL>logloglogJs, loglogloglogJs, mapping):
<EOL>unmax_metric[-<NUM_LIT:1>,-<NUM_LIT:1>] = (Js[<NUM_LIT:1>] - Js[<NUM_LIT:4>]*Js[<NUM_LIT:4>])<EOL>if '<STR_LIT>'%i in mapping and '<STR_LIT>'%j in mapping:<EOL><INDENT>gammaij = Js[<NUM_LIT>-i-j] - Js[<NUM_LIT:12>-i]*Js[<NUM_LIT:12>-j]<EOL>gamma0i = (Js[<NUM_LIT:9>-i] - Js[<NUM_LIT:4>]*Js[<NUM_LIT:12>-i])<EOL>gamm...
Used to compute part of the metric. Only call this from within calculate_metric(). Please see the documentation for that function.
f15989:m5
def ISCO_eq(r, chi):
return (r*(r-<NUM_LIT:6>))**<NUM_LIT:2>-chi**<NUM_LIT:2>*(<NUM_LIT:2>*r*(<NUM_LIT:3>*r+<NUM_LIT>)-<NUM_LIT:9>*chi**<NUM_LIT:2>)<EOL>
Polynomial that enables the calculation of the Kerr inntermost stable circular orbit (ISCO) radius via its roots. Parameters ----------- r: float the radial coordinate in BH mass units chi: float the BH dimensionless spin parameter Returns ---------- float (r*(r-6))**2-chi**2*(2*r*(3*r+14)-9*chi**2)
f15990:m0
def ISCO_eq_chi_first(chi,r):
return -ISCO_eq(r, chi)<EOL>
Polynomial that enables the calculation of the Kerr inntermost stable circular orbit (ISCO) radius via its roots. The arguments of the function and the sign of the polynomial are inverted with respect to ISCO_eq: this facilitates the job of the root-finder that calls this function. Parameters ----------- chi: float ...
f15990:m1
def ISSO_eq_at_pole(r, chi):
return r**<NUM_LIT:3>*(r**<NUM_LIT:2>*(r-<NUM_LIT:6>)+chi**<NUM_LIT:2>*(<NUM_LIT:3>*r+<NUM_LIT:4>))+chi**<NUM_LIT:4>*(<NUM_LIT:3>*r*(r-<NUM_LIT:2>)+chi**<NUM_LIT:2>)<EOL>
Polynomial that enables the calculation of the Kerr polar (inclination = +/- pi/2) innermost stable spherical orbit (ISSO) radius via its roots. Physical solutions are between 6 and 1+sqrt[3]+sqrt[3+2sqrt[3]]. Parameters ----------- r: float the radial coordinate in BH mass units chi: float the BH dimensionle...
f15990:m2
def PG_ISSO_eq(r, chi, ci):
X=chi**<NUM_LIT:2>*(chi**<NUM_LIT:2>*(<NUM_LIT:3>*chi**<NUM_LIT:2>+<NUM_LIT:4>*r*(<NUM_LIT:2>*r-<NUM_LIT:3>))+r**<NUM_LIT:2>*(<NUM_LIT:15>*r*(r-<NUM_LIT:4>)+<NUM_LIT>))-<NUM_LIT:6>*r**<NUM_LIT:4>*(r**<NUM_LIT:2>-<NUM_LIT:4>)<EOL>Y=chi**<NUM_LIT:4>*(chi**<NUM_LIT:4>+r**<NUM_LIT:2>*(<NUM_LIT:7>*r*(<NUM_LIT:3>*r-<NUM_LIT:...
Polynomial that enables the calculation of a generic innermost stable spherical orbit (ISSO) radius via its roots. Physical solutions are between the equatorial ISSO (aka the ISCO) radius and the polar ISSO radius. [See Stone, Loeb, Berger, PRD 87, 084053 (2013)] Parameters ----------- r: float the radial coordin...
f15990:m3
def PG_ISSO_solver(chi,incl):
<EOL>ci=math.cos(incl)<EOL>sgnchi = np.sign(ci)*chi<EOL>if sgnchi > <NUM_LIT>:<EOL><INDENT>initial_guess = <NUM_LIT:2> <EOL><DEDENT>elif sgnchi < <NUM_LIT:0>:<EOL><INDENT>initial_guess = <NUM_LIT:9><EOL><DEDENT>else:<EOL><INDENT>initial_guess = <NUM_LIT:5> <EOL><DEDENT>rISCO_limit = scipy.optimize.fsolve(ISCO_eq, initi...
Function that determines the radius of the innermost stable spherical orbit (ISSO) for a Kerr BH and a generic inclination angle between the BH spin and the orbital angular momentum. This function finds the appropriat root of PG_ISSO_eq. Parameters ----------- chi: float the BH dimensionless spin parameter incl: f...
f15990:m4
def pos_branch(incl, chi):
if incl == <NUM_LIT:0>:<EOL><INDENT>chi_eff = chi<EOL><DEDENT>else:<EOL><INDENT>rISSO = PG_ISSO_solver(chi,incl)<EOL>chi_eff = scipy.optimize.fsolve(ISCO_eq_chi_first, <NUM_LIT:1.0>, args=(rISSO))<EOL><DEDENT>return chi_eff<EOL>
Determines the effective [as defined in Stone, Loeb, Berger, PRD 87, 084053 (2013)] aligned dimensionless spin parameter of a NS-BH binary with tilted BH spin. This means finding the root chi_eff of ISCO_eq_chi_first(chi_eff, PG_ISSO_solver(chi,incl)). The result returned by this function belongs to the branch of the g...
f15990:m5
def bh_effective_spin(chi,incl):
if incl == <NUM_LIT:0>:<EOL><INDENT>chi_eff = chi<EOL><DEDENT>else:<EOL><INDENT>rISSO = PG_ISSO_solver(chi,incl)<EOL>incl_flip = scipy.optimize.fmin(pos_branch, math.pi/<NUM_LIT:4>, args=tuple([chi]), full_output=False, disp=False)[-<NUM_LIT:1>]<EOL>if incl>incl_flip:<EOL><INDENT>initial_guess = -<NUM_LIT><EOL><DEDENT>...
Determines the effective [as defined in Stone, Loeb, Berger, PRD 87, 084053 (2013)] aligned dimensionless spin parameter of a NS-BH binary with tilted BH spin. This means finding the root chi_eff of ISCO_eq_chi_first(chi_eff, PG_ISSO_solver(chi,incl)) with the correct sign. Parameters ----------- chi: float the BH...
f15990:m6
def load_ns_sequence(eos_name):
ns_sequence = []<EOL>if eos_name == '<STR_LIT>':<EOL><INDENT>ns_sequence_path = os.path.join(pycbc.tmpltbank.NS_SEQUENCE_FILE_DIRECTORY, '<STR_LIT>')<EOL>ns_sequence = np.loadtxt(ns_sequence_path)<EOL><DEDENT>else:<EOL><INDENT>print('<STR_LIT>')<EOL>print('<STR_LIT>')<EOL>print('<STR_LIT>')<EOL>raise Exception('<STR_LI...
Load the data of an NS non-rotating equilibrium sequence generated using the equation of state (EOS) chosen by the user. [Only the 2H 2-piecewise polytropic EOS is currently supported. This yields NSs with large radiss (15-16km).] Parameters ----------- eos_name: string NS equation of state label ('2H' is the on...
f15990:m7
def ns_g_mass_to_ns_b_mass(ns_g_mass, ns_sequence):
x = ns_sequence[:,<NUM_LIT:0>]<EOL>y = ns_sequence[:,<NUM_LIT:1>]<EOL>f = scipy.interpolate.interp1d(x, y)<EOL>return f(ns_g_mass)<EOL>
Determines the baryonic mass of an NS given its gravitational mass and an NS equilibrium sequence. Parameters ----------- ns_g_mass: float NS gravitational mass (in solar masses) ns_sequence: 3D-array contains the sequence data in the form NS gravitational mass (in solar masses), NS baryonic mass (in sola...
f15990:m8
def ns_g_mass_to_ns_compactness(ns_g_mass, ns_sequence):
x = ns_sequence[:,<NUM_LIT:0>]<EOL>y = ns_sequence[:,<NUM_LIT:2>]<EOL>f = scipy.interpolate.interp1d(x, y)<EOL>return f(ns_g_mass)<EOL>
Determines the compactness of an NS given its gravitational mass and an NS equilibrium sequence. Parameters ----------- ns_g_mass: float NS gravitational mass (in solar masses) ns_sequence: 3D-array contains the sequence data in the form NS gravitational mass (in solar masses), NS baryonic mass (in solar ...
f15990:m9
def xi_eq(x, kappa, chi_eff, q):
return x**<NUM_LIT:3>*(x**<NUM_LIT:2>-<NUM_LIT:3>*kappa*x+<NUM_LIT:2>*chi_eff*kappa*math.sqrt(kappa*x))-<NUM_LIT:3>*q*(x**<NUM_LIT:2>-<NUM_LIT:2>*kappa*x+(chi_eff*kappa)**<NUM_LIT:2>)<EOL>
The roots of this equation determine the orbital radius at the onset of NS tidal disruption in a nonprecessing NS-BH binary [(7) in Foucart PRD 86, 124007 (2012)] Parameters ----------- x: float orbital separation in units of the NS radius kappa: float the BH mass divided by the NS radius chi_eff: float th...
f15990:m10
def remnant_mass(eta, ns_g_mass, ns_sequence, chi, incl, shift):
<EOL>if not (eta><NUM_LIT:0.> and eta<=<NUM_LIT> and abs(chi)<=<NUM_LIT:1>):<EOL><INDENT>print('<STR_LIT>')<EOL>print('<STR_LIT>'.format(ns_g_mass, eta, chi, incl))<EOL>raise Exception('<STR_LIT>')<EOL><DEDENT>q = (<NUM_LIT:1>+math.sqrt(<NUM_LIT:1>-<NUM_LIT:4>*eta)-<NUM_LIT:2>*eta)/eta*<NUM_LIT:0.5><EOL>ns_compactness ...
Function that determines the remnant disk mass of an NS-BH system using the fit to numerical-relativity results discussed in Foucart PRD 86, 124007 (2012). Parameters ----------- eta: float the symmetric mass ratio of the binary ns_g_mass: float NS gravitational mass (in solar masses) ns_sequence: 3D-array ...
f15990:m11
def remnant_mass_ulim(eta, ns_g_mass, bh_spin_z, ns_sequence, max_ns_g_mass, shift):
<EOL>if not (eta > <NUM_LIT:0.> and eta <=<NUM_LIT> and abs(bh_spin_z)<=<NUM_LIT:1>):<EOL><INDENT>raise Exception("""<STR_LIT>""".format(eta, bh_spin_z))<EOL><DEDENT>bh_spin_magnitude = <NUM_LIT:1.><EOL>default_remnant_mass = <NUM_LIT><EOL>if not ns_g_mass > max_ns_g_mass:<EOL><INDENT>bh_spin_inclination = np.arccos(bh...
Function that determines the maximum remnant disk mass for an NS-BH system with given symmetric mass ratio, NS mass, and BH spin parameter component along the orbital angular momentum. This is a wrapper to the function remnant_mass. Maximization is achieved by setting the BH dimensionless spin magntitude to unity. An...
f15990:m12
def find_em_constraint_data_point(mNS, sBH, eos_name, threshold, eta_default):
ns_sequence, max_ns_g_mass = load_ns_sequence(eos_name)<EOL>if mNS > max_ns_g_mass:<EOL><INDENT>eta_sol = eta_default<EOL><DEDENT>else:<EOL><INDENT>eta_min = <NUM_LIT> <EOL>disk_mass_down = remnant_mass_ulim(eta_min, mNS, sBH, ns_sequence, max_ns_g_mass, threshold)<EOL>eta_max = <NUM_LIT> <EOL>disk_mass_up = remnant_ma...
Function that determines the minimum symmetric mass ratio for an NS-BH system with given NS mass, BH spin parameter component along the orbital angular momentum, and NS equation of state (EOS), required for the remnant disk mass to exceed a certain threshold value specified by the user. A default value specified by th...
f15990:m13
def generate_em_constraint_data(mNS_min, mNS_max, delta_mNS, sBH_min, sBH_max, delta_sBH, eos_name, threshold, eta_default):
<EOL>mNS_nsamples = complex(<NUM_LIT:0>,int(np.ceil((mNS_max-mNS_min)/delta_mNS)+<NUM_LIT:1>))<EOL>sBH_nsamples = complex(<NUM_LIT:0>,int(np.ceil((sBH_max-sBH_min)/delta_sBH)+<NUM_LIT:1>))<EOL>mNS_vec, sBH_vec = np.mgrid[mNS_min:mNS_max:mNS_nsamples, sBH_min:sBH_max:sBH_nsamples] <EOL>mNS_locations = np.array(mNS_vec[:...
Wrapper that calls find_em_constraint_data_point over a grid of points to generate the bh_spin_z x ns_g_mass x eta surface above which NS-BH binaries yield a remnant disk mass that exceeds the threshold required by the user. The user must also specify the default symmetric mass ratio value to be assigned to points for...
f15990:m14
def min_eta_for_em_bright(bh_spin_z, ns_g_mass, mNS_pts, sBH_pts, eta_mins):
f = scipy.interpolate.RectBivariateSpline(mNS_pts, sBH_pts, eta_mins, kx=<NUM_LIT:1>, ky=<NUM_LIT:1>)<EOL>if isinstance(bh_spin_z, np.ndarray):<EOL><INDENT>eta_min = np.empty(len(bh_spin_z))<EOL>for i in range(len(bh_spin_z)):<EOL><INDENT>eta_min[i] = f(ns_g_mass[i], bh_spin_z[i])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>...
Function that uses the end product of generate_em_constraint_data to swipe over a set of NS-BH binaries and determine the minimum symmetric mass ratio required by each binary to yield a remnant disk mass that exceeds a certain threshold. Each binary passed to this function consists of a NS mass and a BH spin parameter...
f15990:m15
def get_common_cbc_transforms(requested_params, variable_args,<EOL>valid_params=None):
variable_args = set(variable_args) if not isinstance(variable_args, set)else variable_args<EOL>new_params = []<EOL>for opt in requested_params:<EOL><INDENT>s = "<STR_LIT>"<EOL>for ch in opt:<EOL><INDENT>s += ch if ch.isalnum() or ch == "<STR_LIT:_>" else "<STR_LIT:U+0020>"<EOL><DEDENT>new_params += s.split("<STR_LIT:U+...
Determines if any additional parameters from the InferenceFile are needed to get derived parameters that user has asked for. First it will try to add any base parameters that are required to calculate the derived parameters. Then it will add any sampling parameters that are required to calculate the ba...
f15991:m0
def apply_transforms(samples, transforms, inverse=False):
if inverse:<EOL><INDENT>transforms = transforms[::-<NUM_LIT:1>]<EOL><DEDENT>for t in transforms:<EOL><INDENT>try:<EOL><INDENT>if inverse:<EOL><INDENT>samples = t.inverse_transform(samples)<EOL><DEDENT>else:<EOL><INDENT>samples = t.transform(samples)<EOL><DEDENT><DEDENT>except NotImplementedError:<EOL><INDENT>continue<E...
Applies a list of BaseTransform instances on a mapping object. Parameters ---------- samples : {FieldArray, dict} Mapping object to apply transforms to. transforms : list List of BaseTransform instances to apply. Nested transforms are assumed to be in order for forward transform...
f15991:m1
def compute_jacobian(samples, transforms, inverse=False):
j = <NUM_LIT:1.><EOL>if inverse:<EOL><INDENT>for t in transforms:<EOL><INDENT>j *= t.inverse_jacobian(samples)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for t in transforms:<EOL><INDENT>j *= t.jacobian(samples)<EOL><DEDENT><DEDENT>return j<EOL>
Computes the jacobian of the list of transforms at the given sample points. Parameters ---------- samples : {FieldArray, dict} Mapping object specifying points at which to compute jacobians. transforms : list List of BaseTransform instances to apply. Nested transforms are assumed ...
f15991:m2
def order_transforms(transforms):
<EOL>outputs = set().union(*[t.outputs for t in transforms])<EOL>out = []<EOL>remaining = [t for t in transforms]<EOL>while remaining:<EOL><INDENT>leftover = []<EOL>for t in remaining:<EOL><INDENT>if t.inputs.isdisjoint(outputs):<EOL><INDENT>out.append(t)<EOL>outputs -= t.outputs<EOL><DEDENT>else:<EOL><INDENT>leftover....
Orders transforms to ensure proper chaining. For example, if `transforms = [B, A, C]`, and `A` produces outputs needed by `B`, the transforms will be re-rorderd to `[A, B, C]`. Parameters ---------- transforms : list List of transform instances to order. Outputs ------- list :...
f15991:m3
def read_transforms_from_config(cp, section="<STR_LIT>"):
trans = []<EOL>for subsection in cp.get_subsections(section):<EOL><INDENT>name = cp.get_opt_tag(section, "<STR_LIT:name>", subsection)<EOL>t = transforms[name].from_config(cp, section, subsection)<EOL>trans.append(t)<EOL><DEDENT>return order_transforms(trans)<EOL>
Returns a list of PyCBC transform instances for a section in the given configuration file. If the transforms are nested (i.e., the output of one transform is the input of another), the returned list will be sorted by the order of the nests. Parameters ---------- cp : WorflowConfigParser ...
f15991:m4
def transform(self, maps):
raise NotImplementedError("<STR_LIT>")<EOL>
This function transforms from inputs to outputs.
f15991:c0:m2
def inverse_transform(self, maps):
raise NotImplementedError("<STR_LIT>")<EOL>
The inverse conversions of transform. This function transforms from outputs to inputs.
f15991:c0:m3
def jacobian(self, maps):
raise NotImplementedError("<STR_LIT>")<EOL>
The Jacobian for the inputs to outputs transformation.
f15991:c0:m4
def inverse_jacobian(self, maps):
raise NotImplementedError("<STR_LIT>")<EOL>
The Jacobian for the outputs to inputs transformation.
f15991:c0:m5
@staticmethod<EOL><INDENT>def format_output(old_maps, new_maps):<DEDENT>
<EOL>if isinstance(old_maps, record.FieldArray):<EOL><INDENT>keys = new_maps.keys()<EOL>values = [new_maps[key] for key in keys]<EOL>for key, vals in zip(keys, values):<EOL><INDENT>try:<EOL><INDENT>old_maps = old_maps.add_fields([vals], [key])<EOL><DEDENT>except ValueError:<EOL><INDENT>old_maps[key] = vals<EOL><DEDENT>...
This function takes the returned dict from `transform` and converts it to the same datatype as the input. Parameters ---------- old_maps : {FieldArray, dict} The mapping object to add new maps to. new_maps : dict A dict with key as parameter name and valu...
f15991:c0:m6
@classmethod<EOL><INDENT>def from_config(cls, cp, section, outputs, skip_opts=None,<EOL>additional_opts=None):<DEDENT>
tag = outputs<EOL>if skip_opts is None:<EOL><INDENT>skip_opts = []<EOL><DEDENT>if additional_opts is None:<EOL><INDENT>additional_opts = {}<EOL><DEDENT>else:<EOL><INDENT>additional_opts = additional_opts.copy()<EOL><DEDENT>outputs = set(outputs.split(VARARGS_DELIM))<EOL>special_args = ['<STR_LIT:name>'] + skip_opts + a...
Initializes a transform from the given section. Parameters ---------- cp : pycbc.workflow.WorkflowConfigParser A parsed configuration file that contains the transform options. section : str Name of the section in the configuration file. outputs : str ...
f15991:c0:m7
def _createscratch(self, shape=<NUM_LIT:1>):
self._scratch = record.FieldArray(shape, dtype=[(p, float)<EOL>for p in self.inputs])<EOL>
Creates a scratch FieldArray to use for transforms.
f15991:c1:m1
def _copytoscratch(self, maps):
try:<EOL><INDENT>for p in self.inputs:<EOL><INDENT>self._scratch[p][:] = maps[p]<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>invals = maps[list(self.inputs)[<NUM_LIT:0>]]<EOL>if isinstance(invals, numpy.ndarray):<EOL><INDENT>shape = invals.shape<EOL><DEDENT>else:<EOL><INDENT>shape = len(invals)<EOL><DEDENT>self....
Copies the data in maps to the scratch space. If the maps contain arrays that are not the same shape as the scratch space, a new scratch space will be created.
f15991:c1:m2
def _getslice(self, maps):
invals = maps[list(self.inputs)[<NUM_LIT:0>]]<EOL>if not isinstance(invals, (numpy.ndarray, list)):<EOL><INDENT>getslice = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>getslice = slice(None, None)<EOL><DEDENT>return getslice<EOL>
Determines how to slice the scratch for returning values.
f15991:c1:m3
def transform(self, maps):
if self.transform_functions is None:<EOL><INDENT>raise NotImplementedError("<STR_LIT>")<EOL><DEDENT>self._copytoscratch(maps)<EOL>getslice = self._getslice(maps)<EOL>out = {p: self._scratch[func][getslice]<EOL>for p,func in self.transform_functions.items()}<EOL>return self.format_output(maps, out)<EOL>
Applies the transform functions to the given maps object. Parameters ---------- maps : dict, or FieldArray Returns ------- dict or FieldArray A map object containing the transformed variables, along with the original variables. The type of the ou...
f15991:c1:m4
@classmethod<EOL><INDENT>def from_config(cls, cp, section, outputs):<DEDENT>
tag = outputs<EOL>outputs = set(outputs.split(VARARGS_DELIM))<EOL>inputs = map(str.strip,<EOL>cp.get_opt_tag(section, '<STR_LIT>', tag).split('<STR_LIT:U+002C>'))<EOL>transform_functions = {}<EOL>for var in outputs:<EOL><INDENT>func = cp.get_opt_tag(section, var, tag)<EOL>transform_functions[var] = func<EOL><DEDENT>s =...
Loads a CustomTransform from the given config file. Example section: .. code-block:: ini [{section}-outvar1+outvar2] name = custom inputs = inputvar1, inputvar2 outvar1 = func1(inputs) outvar2 = func2(inputs) jacobian = func(inpu...
f15991:c1:m6
def transform(self, maps):
out = {}<EOL>out[parameters.mass1] = conversions.mass1_from_mchirp_q(<EOL>maps[parameters.mchirp],<EOL>maps[parameters.q])<EOL>out[parameters.mass2] = conversions.mass2_from_mchirp_q(<EOL>maps[parameters.mchirp],<EOL>maps[parameters.q])<EOL>return self.format_output(maps, out)<EOL>
This function transforms from chirp mass and mass ratio to component masses. Parameters ---------- maps : a mapping object Examples -------- Convert a dict of numpy.array: >>> import numpy >>> from pycbc import transforms >>> t = transfo...
f15991:c2:m0
def inverse_transform(self, maps):
out = {}<EOL>m1 = maps[parameters.mass1]<EOL>m2 = maps[parameters.mass2]<EOL>out[parameters.mchirp] = conversions.mchirp_from_mass1_mass2(m1, m2)<EOL>out[parameters.q] = m1 / m2<EOL>return self.format_output(maps, out)<EOL>
This function transforms from component masses to chirp mass and mass ratio. Parameters ---------- maps : a mapping object Examples -------- Convert a dict of numpy.array: >>> import numpy >>> from pycbc import transforms >>> t = transfo...
f15991:c2:m1
def jacobian(self, maps):
mchirp = maps[parameters.mchirp]<EOL>q = maps[parameters.q]<EOL>return mchirp * ((<NUM_LIT:1.>+q)/q**<NUM_LIT>)**(<NUM_LIT>/<NUM_LIT:5>)<EOL>
Returns the Jacobian for transforming mchirp and q to mass1 and mass2.
f15991:c2:m2
def inverse_jacobian(self, maps):
m1 = maps[parameters.mass1]<EOL>m2 = maps[parameters.mass2]<EOL>return conversions.mchirp_from_mass1_mass2(m1, m2)/m2**<NUM_LIT><EOL>
Returns the Jacobian for transforming mass1 and mass2 to mchirp and q.
f15991:c2:m3
def transform(self, maps):
out = {}<EOL>out[parameters.mass1] = conversions.mass1_from_mchirp_eta(<EOL>maps[parameters.mchirp],<EOL>maps[parameters.eta])<EOL>out[parameters.mass2] = conversions.mass2_from_mchirp_eta(<EOL>maps[parameters.mchirp],<EOL>maps[parameters.eta])<EOL>return self.format_output(maps, out)<EOL>
This function transforms from chirp mass and symmetric mass ratio to component masses. Parameters ---------- maps : a mapping object Examples -------- Convert a dict of numpy.array: >>> import numpy >>> from pycbc import transforms >>> t...
f15991:c3:m0