コード例 #1
0
ファイル: waveforms.py プロジェクト: tanghyd/gravflows
def batch_project(
    detector: Detector,
    extrinsics: Union[np.recarray, Dict[str, np.ndarray]],
    waveforms: np.ndarray,
    static_args: Dict[str, Union[str,float]],
    sample_frequencies: Optional[np.ndarray]=None,
    distance_scale: bool=False,
    time_shift: bool=False,
):
    # get frequency bins (we handle numpy arrays rather than PyCBC arrays with .sample_frequencies attributes)
    if sample_frequencies is None:
        sample_frequencies = get_sample_frequencies(
            f_final=static_args['f_final'],
            delta_f=static_args['delta_f']
        )
    
    # check waveform matrix inputs
    assert waveforms.shape[1] == 2, "2nd dim in waveforms must be plus and cross polarizations."
    assert waveforms.shape[0] == len(extrinsics), "waveform batch and extrinsics length must match."

    if distance_scale:
        # scale waveform amplitude according to sample d_L parameter
        scale = static_args.get('distance', 1000)  / extrinsics['distance']  # default d_L = 1
        waveforms = np.array(waveforms) * scale[:, None, None]

    # calculate antenna pattern given arrays of extrinsic parameters
    fp, fc = detector.antenna_pattern(
        extrinsics['ra'], extrinsics['dec'], extrinsics['psi'],
        static_args.get('ref_time', 0.)
    )

    # batch project
    projections = fp[:, None]*waveforms[:, 0, :] + fc[:, None]*waveforms[:, 1, :]

    # if distance_scale:
    #     # scale waveform amplitude according to sample d_L parameter
    #     scale = static_args.get('distance', 1000)  / extrinsics['distance']  # default d_L = 1
    #     projections *= scale[:, None]
    
    if time_shift:    
        assert waveforms.shape[-1] == sample_frequencies.shape[0], "delta_f and fd_length do not match."
        
        # calculate geocentric time for the given detector
        dt = detector.time_delay_from_earth_center(extrinsics['ra'], extrinsics['dec'], static_args.get('ref_time', 0.))
    
        # Calculate time shift due to sampled t_c parameters
        dt += extrinsics['time'] - static_args.get('ref_time', 0.)  # default ref t_c = 0
        
        dt = dt.astype(match_precision(sample_frequencies, real=True))
        shift = np.exp(- 2j * np.pi * dt[:, None] * sample_frequencies[None, :])
        projections *= shift

    return projections
コード例 #2
0
ファイル: waveforms.py プロジェクト: tanghyd/gravflows
def project_onto_detector(
    detector: Detector,
    sample: Union[np.recarray, Dict[str, float]],
    hp: Union[np.ndarray, FrequencySeries],
    hc: Union[np.ndarray, FrequencySeries],
    static_args: Dict[str, Union[str, float]],
    sample_frequencies: Optional[np.ndarray]=None,
    as_pycbc: bool=True,
    time_shift: bool=False,
) -> Union[np.ndarray, FrequencySeries]:
    """Takes a plus and cross waveform polarization (i.e. generated by intrinsic parameters)
    and projects them onto a specified interferometer using a PyCBC.detector.Detector.
    """
    # input handling
    assert type(hp) == type(hc), "Plus and cross waveform types must match."
    if isinstance(hp, FrequencySeries):
        assert np.all(hp.sample_frequencies == hc.sample_frequencies), "FrequencySeries.sample_frequencies do not match."
        sample_frequencies = hp.sample_frequencies
    assert sample_frequencies is not None, "Waveforms not FrequencySeries type or frequency series array not provided."
    
    # project intrinsic waveform onto detector
    fp, fc = detector.antenna_pattern(sample['ra'], sample['dec'], sample['psi'], static_args.get('ref_time', 0.))
    h = fp*hp + fc*hc

    # scale waveform amplitude according to ratio to reference distance
    h *= static_args.get('distance', 1)  / sample['distance']  # default d_L = 1

    if time_shift:        
        # Calculate time shift at detector and add to geocentric time
        dt = detector.time_delay_from_earth_center(sample['ra'], sample['dec'], static_args.get('ref_time', 0.))
        dt += sample['time'] - static_args.get('ref_time', 0.)  # default ref t_c = 0
        dt = dt.astype(match_precision(sample_frequencies))
        h *= np.exp(- 2j * np.pi * dt * sample_frequencies).astype(match_precision(h, real=False))
        
    # output desired type
    if isinstance(h, FrequencySeries):
        if as_pycbc:
            return h
        else:
            return h.data
    else:
        if as_pycbc:
            return FrequencySeries(h, delta_f=static_args['delta_f'], copy=False)
        else:
            return h
コード例 #3
0
# coding: utf-8

# In[4]:

from pycbc.detector import Detector

# In[5]:

det_h1 = Detector('H1')
det_l1 = Detector('L1')
det_v1 = Detector('V1')

# In[6]:

end_time = 1192529720
declination = 0.65
right_ascension = 4.67
polarization = 2.34

# In[7]:

det_h1.antenna_pattern(right_ascension, declination, polarization, end_time)
コード例 #4
0
def get_td_waveform_resp(params):
    """
    Generate time domain data of gw detector response

    This function will produce data of a gw detector response based on a
    numerical relativity waveform.

    Parameters
    ----------
    params: object
        The fields of this object correspond to the kwargs of the
        `pycbc.waveform.get_td_waveform()` method and the positional
        arguments of `pycbc.detector.Detector.antenna_pattern()`. For the later
        the fields should be supplied as `params.ra`, `.dec`, `.polarization`
        and `.geocentric_end_time`

    Returns
    -------
    h_plus: pycbc.Types.TimeSeries
    h_cross: pycbc.Types.TimeSeries
    pats: dictionary
        Dictionary containing 'H1' and 'L1' keys. Each key maps to an object
        of containing the field `.f_plus` and `.f_cross` corresponding to
        the plus and cross antenna patterns for the two ifos 'H1' and 'L1'.
    """

    # # construct waveform string that can be parsed by lalsimulation
    waveform_string = params.approximant
    if not pn_orders[params.order] == -1:
        waveform_string += params.order
    name, phase_order = legacy_approximant_name(waveform_string)

    # Populate additional fields of params object
    params.mchirp, params.eta = pnutils.mass1_mass2_to_mchirp_eta(
        params.mass1, params.mass2)
    params.waveform           = waveform_string
    params.approximant        = name
    params.phase_order        = phase_order

    # generate waveform
    h_plus, h_cross = get_td_waveform(params)

    # Generate antenna patterns for all ifos
    pats = {}
    for ifo in params.instruments:

        # get Detector instance for IFO
        det = Detector(ifo)

        # get antenna pattern
        f_plus, f_cross = det.antenna_pattern(
            params.ra,
            params.dec,
            params.polarization,
            params.geocentric_end_time)

        # Populate antenna patterns with new pattern
        pat         = type('AntennaPattern', (object,), {})
        pat.f_plus  = f_plus
        pat.f_cross = f_cross
        pats[ifo]   = pat

    return h_plus, h_cross, pats
コード例 #5
0
def load_inject_condition_ccsn(t_i,
                               t_f,
                               t_inj,
                               ra,
                               dec,
                               pol,
                               hp,
                               hc,
                               local=False,
                               Tc=16,
                               To=2,
                               fw=2048,
                               window='tukey',
                               detector='H',
                               qtrans=False,
                               qsplit=False,
                               dT=2.0,
                               save=False,
                               data_path=None):
    """Fucntion to load a chunk, inject a waveform and condition, created to enable parallelizing.
	"""
    vmem = psutil.virtual_memory()
    free_mem = vmem.free >> 20
    avail_mem = vmem.available >> 20
    # if free_mem < 3e5:
    if avail_mem < 3e5:
        return

    if local:
        files = get_files(detector)
        try:
            data = TimeSeries.read(files,
                                   start=t_i,
                                   end=t_f,
                                   format='hdf5.losc')  # load data locally
        except:
            return

    else:
        # load data from losc
        try:
            data = TimeSeries.fetch_open_data(detector + '1',
                                              *(t_i, t_f),
                                              sample_rate=fw,
                                              verbose=False,
                                              cache=True)
        except:
            return

    if np.isnan(data.value).any():
        return

    det_obj = Detector(detector + '1')
    delay = det_obj.time_delay_from_detector(Detector('H1'), ra, dec, t_inj)
    t_inj += delay
    fp, fc = det_obj.antenna_pattern(ra, dec, pol, t_inj)

    # wfs_path = Path(git_path + '/shared/ccsn_wfs/' + ccsn_paper)
    # sim_data = [i.strip().split() for i in open(join(wfs_path, ccsn_file)).readlines()]
    # if ccsn_paper == 'radice':
    # 	line_s = 1
    # else:
    # 	line_s = 0

    # D = D_kpc *  3.086e+21 # cm
    # sim_times = np.asarray([float(dat[0]) for dat in sim_data[line_s:]])
    # hp = np.asarray([float(dat[1]) for dat in sim_data[line_s:]]) / D
    # if ccsn_paper == 'abdikamalov':
    # 	hc = np.zeros(hp.shape)
    # else:
    # 	hc = np.asarray([float(dat[2]) for dat in sim_data[line_s:]]) / D

    # dt = sim_times[1] - sim_times[0]
    h = fp * hp + fc * hc
    # h = TimeSeries(h, t0=sim_times[0], dt=dt)

    # h = h.resample(rate=fw, ftype = 'iir', n=20) # downsample to working frequency fw
    # h = h.highpass(frequency=11, filtfilt=True) # filter out frequencies below 20Hz
    # inj_window = scisig.tukey(M=len(h), alpha=0.08, sym=True)
    # h = h * inj_window

    # h = h.pad(int((fw * Tc - len(h)) / 2))

    wf_times = data.times.value

    shift = int((t_inj - (wf_times[0] + Tc / 2)) * fw)
    h = np.roll(h.value, shift)

    h = TimeSeries(h, t0=wf_times[0], dt=data.dt)
    try:
        h = h.taper()
    except:
        pass

    injected_data = data.inject(h)

    del data
    gc.collect()

    cond_data = condition_data(injected_data, To, fw, window, qtrans, qsplit,
                               dT)

    del injected_data
    gc.collect()

    x = []
    times = []

    for dat in cond_data:
        x.append(dat.values)
        times.append(dat.t0)

    del cond_data
    gc.collect()

    x = np.asarray(x)
    times = np.asarray(times)

    idx = find_closest_index(t_inj, times)

    x = x[idx]
    times = times[idx]
    return x, times
コード例 #6
0
def load_inject_condition(t_i,
                          t_f,
                          t_inj,
                          ra,
                          dec,
                          pol,
                          alpha,
                          inj_type,
                          inj_params=None,
                          local=False,
                          Tc=16,
                          To=2,
                          fw=2048,
                          window='tukey',
                          detector='H',
                          qtrans=False,
                          qsplit=False,
                          dT=2.0,
                          hp=None,
                          save=False,
                          data_path=None):
    """Fucntion to load a chunk, inject a waveform and condition, created to enable parallelizing.
	"""
    vmem = psutil.virtual_memory()
    free_mem = vmem.free >> 20
    avail_mem = vmem.available >> 20
    # if free_mem < 3e5:
    if avail_mem < 3e5:
        return

    if local:
        files = get_files(detector)
        try:
            data = TimeSeries.read(files,
                                   start=t_i,
                                   end=t_f,
                                   format='hdf5.losc')  # load data locally
        except:
            return

    else:
        # load data from losc
        try:
            data = TimeSeries.fetch_open_data(detector + '1',
                                              *(t_i, t_f),
                                              sample_rate=fw,
                                              verbose=False,
                                              cache=True)
        except:
            return

    if np.isnan(data.value).any():
        return

    det_obj = Detector(detector + '1')
    delay = det_obj.time_delay_from_detector(Detector('H1'), ra, dec, t_inj)
    t_inj += delay
    fp, fc = det_obj.antenna_pattern(ra, dec, pol, t_inj)

    wf_times = data.times.value

    hp, hc = gen_inject(wf_times, data.dt, t_inj, alpha, inj_type, inj_params,
                        Tc, fw)
    h = fp * hp + fc * hc
    injected_data = data.inject(h)

    del data
    gc.collect()

    cond_data = condition_data(injected_data, To, fw, window, qtrans, qsplit,
                               dT)

    del injected_data
    gc.collect()

    x = []
    times = []

    for dat in cond_data:
        x.append(dat.values)
        times.append(dat.t0)

    del cond_data
    gc.collect()

    x = np.asarray(x)
    times = np.asarray(times)

    idx = find_closest_index(t_inj, times)

    x = x[idx]
    times = times[idx]

    return x, times
コード例 #7
0
ファイル: ant.py プロジェクト: bhooshan-gadre/pycbc
from pycbc.detector import Detector
from pycbc.waveform import get_td_waveform

# Time, orientation and location of the source in the sky
ra = 1.7
dec = 1.7
pol = 0.2
inc = 0
time = 1000000000

# We can calcualate the antenna pattern for Hanford at
# the specific sky location
d = Detector("H1")

# We get back the fp and fc antenna pattern weights.
fp, fc = d.antenna_pattern(ra, dec, pol, time)
print("fp={}, fc={}".format(fp, fc))

# These factors allow us to project a signal into what the detector would
# observe

## Generate a waveform
hp, hc = get_td_waveform(approximant="IMRPhenomD", mass1=10, mass2=10,
                         f_lower=30, delta_t=1.0/4096, inclination=inc,
                         distance=400)

## Apply the factors to get the detector frame strain
ht = fp * hp + fc * hc


# The projection process can also take into account the rotation of the
コード例 #8
0
def load_inject_condition_ccsn_multi_scale(t_i,
                                           t_f,
                                           t_inj,
                                           ra,
                                           dec,
                                           pol,
                                           hp,
                                           hc,
                                           local=False,
                                           Tc=16,
                                           To=2,
                                           fw=2048,
                                           window='tukey',
                                           detector='H',
                                           input_shape=(299, 299),
                                           scales=[0.5, 1.0, 2.0],
                                           frange=(10, 2048),
                                           qrange=(4, 100),
                                           save=False,
                                           data_path=None):
    """Fucntion to load a chunk, inject a waveform and condition, created to enable parallelizing.
	"""
    vmem = psutil.virtual_memory()
    free_mem = vmem.free >> 20
    avail_mem = vmem.available >> 20
    # if free_mem < 3e5:
    if avail_mem < 3e5:
        return

    if local:
        files = get_files(detector)
        try:
            data = TimeSeries.read(files,
                                   start=t_i,
                                   end=t_f,
                                   format='hdf5.losc')  # load data locally
        except:
            return

    else:
        # load data from losc
        try:
            data = TimeSeries.fetch_open_data(detector + '1',
                                              *(t_i, t_f),
                                              sample_rate=fw,
                                              verbose=False,
                                              cache=True)
        except:
            return

    if np.isnan(data.value).any():
        return

    det_obj = Detector(detector + '1')
    delay = det_obj.time_delay_from_detector(Detector('H1'), ra, dec, t_inj)
    t_inj += delay
    fp, fc = det_obj.antenna_pattern(ra, dec, pol, t_inj)

    h = fp * hp + fc * hc
    wf_times = data.times.value

    shift = int((t_inj - (wf_times[0] + Tc / 2)) * fw)
    h = np.roll(h.value, shift)

    h = TimeSeries(h, t0=wf_times[0], dt=data.dt)
    try:
        h = h.taper()
    except:
        pass

    injected_data = data.inject(h)

    del data
    gc.collect()

    # cond_data = condition_data(injected_data, To, fw, window, qtrans, qsplit, dT)
    cond_data = condition_data(injected_data, To, fw, window, qtrans=False)

    del injected_data
    gc.collect()

    # x = []
    # times = []

    # for dat in cond_data:
    # 	x.append(dat.values)
    # 	times.append(dat.t0)
    x, times = qsplit_multi_scale(cond_data,
                                  t_i,
                                  t_f,
                                  To=To,
                                  frange=frange,
                                  qrange=qrange,
                                  input_shape=input_shape,
                                  scales=scales)

    del cond_data
    gc.collect()

    x = np.asarray(x)
    times = np.asarray(times)

    # idx = find_closest_index(t_inj, times)
    idx = find_closest_index(t_inj, times - min(scales) / 2)

    x = x[idx]
    times = times[idx]
    return x, times