Exemplo n.º 1
0
 def get_injected_gps_time(self, site):
     if 'injected_%s_start_time' % site in self.__slots__:
         return LIGOTimeGPS(getattr(self, 'injected_%s_start_time' % site ), getattr(self, 'injected_%s_start_time_ns' % site))
     elif 'injected_%s_end_time' % site in self.__slots__:
         return LIGOTimeGPS(getattr(self, 'injected_%s_end_time' % site ), getattr(self, 'injected_%s_end_time_ns' % site))
     else:
         raise AttributeError, "could not find an injected_%s_start_time nor an injected_%s_end_time" %(site,site)
Exemplo n.º 2
0
 def get_recovered_gps_time(self):
     if 'recovered_start_time' in self.__slots__:
         return LIGOTimeGPS(self.recovered_start_time, self.recovered_start_time_ns)
     elif 'recovered_end_time' in self.__slots__:
         return LIGOTimeGPS(self.recovered_end_time, self.recovered_end_time_ns)
     else:
         raise AttributeError, "could not find a recovered_start_time or recovered_end_time"
Exemplo n.º 3
0
def get_delta_t_rss(pt, coinc, reference_frequency=None):
    """
  returns the rss timing error for a particular location in
  the sky (longitude,latitude)
  """
    latitude, longitude = pt
    earth_center = (0.0, 0.0, 0.0)
    tref = {}
    tgeo = {}
    for ifo in coinc.ifo_list:

        if reference_frequency:
            tFromRefFreq = get_signal_duration(ifo, coinc, reference_frequency)
            tref[ifo] = LIGOTimeGPS(int(tFromRefFreq),
                                    1.e9 * (tFromRefFreq - int(tFromRefFreq)))
        else:
            tref[ifo] = 0.0

        #compute the geocentric time from each trigger
        tgeo[ifo] = coinc.gps[ifo] - tref[ifo] - \
                    LIGOTimeGPS(0,1.0e9*date.XLALArrivalTimeDiff(detector_locations[ifo],\
                    earth_center,longitude,latitude,coinc.gps[ifo]))

    #compute differences in these geocentric times
    time = {}
    delta_t_rms = 0.0
    for ifos in coinc.ifo_coincs:
        time[ifos[0] + ifos[1]] = float(tgeo[ifos[0]] - tgeo[ifos[1]])
        delta_t_rms += time[ifos[0] + ifos[1]] * time[ifos[0] + ifos[1]]

    return sqrt(delta_t_rms)
Exemplo n.º 4
0
 def test__div__(self):
     self.assertEqual(LIGOTimeGPS(10), LIGOTimeGPS(20) / 2)
     self.assertEqual(LIGOTimeGPS(10), LIGOTimeGPS(5) / 0.5)
     self.assertEqual(LIGOTimeGPS(333333333, 333333333),
                      LIGOTimeGPS(1000000000) / 3)
     self.assertEqual(LIGOTimeGPS(666666666, 666666667),
                      LIGOTimeGPS(2000000000) / 3)
def InspiralNearCoincCompare(sim, inspiral):
    """
	Return False if the peak time of the sim is within 9 seconds of the inspiral event.
	"""
    return SnglInspiralUtils.CompareSnglInspiral(sim,
                                                 inspiral,
                                                 twindow=LIGOTimeGPS(9))
Exemplo n.º 6
0
def timeDelay(gpsTime, rightAscension, declination, unit, det1, det2):
    """
  timeDelay( gpsTime, rightAscension, declination, unit, det1, det2 )
  
  Calculates the time delay in seconds between the detectors
  'det1' and 'det2' (e.g. 'H1') for a sky location at (rightAscension
  and declination) which must be given in certain units
  ('radians' or 'degree'). The time is passes as GPS time.
  A positive time delay means the GW arrives first at 'det2', then at 'det1'.
    
  Example:
  antenna.timeDelay( 877320548.000, 355.084,31.757, 'degree','H1','L1')
  0.0011604683260994519

  Given these values, the signal arrives first at detector L1,
  and 1.16 ms later at H2
  """

    # check the input arguments
    if unit == 'radians':
        ra_rad = rightAscension
        de_rad = declination
    elif unit == 'degree':
        ra_rad = rightAscension / 180.0 * pi
        de_rad = declination / 180.0 * pi
    else:
        raise ValueError, "Unknown unit %s" % unit

    # check input values
    if ra_rad < 0.0 or ra_rad > 2 * pi:
        raise ValueError, "ERROR. right ascension=%f "\
              "not within reasonable range."\
              % (rightAscension)

    if de_rad < -pi or de_rad > pi:
        raise ValueError, "ERROR. declination=%f not within reasonable range."\
              % (declination)

    if det1 == det2:
        return 0.0

    gps = LIGOTimeGPS(gpsTime)

    # create detector-name map
    detMap = {
        'H1': 'LHO_4k',
        'H2': 'LHO_2k',
        'L1': 'LLO_4k',
        'G1': 'GEO_600',
        'V1': 'VIRGO',
        'T1': 'TAMA_300'
    }

    x1 = inject.cached_detector[detMap[det1]].location
    x2 = inject.cached_detector[detMap[det2]].location
    timedelay = date.XLALArrivalTimeDiff(list(x1), list(x2), ra_rad, de_rad,
                                         gps)

    return timedelay
Exemplo n.º 7
0
    def get_coincs_from_coinctable(self, files):
        """
    read data from coinc tables (xml format)
    
    FIXME: currently assumes one coinc per file!!!
    """
        for file in files:
            coinc = CoincData()
            xmldoc = utils.load_filename(file)
            sngltab = tab.get_table(xmldoc,
                                    lsctables.SnglInspiralTable.tableName)
            coinc.set_snr(dict((row.ifo, row.snr) for row in sngltab))
            coinc.set_gps(
                dict((row.ifo, LIGOTimeGPS(row.get_end())) for row in sngltab))
            #FIXME: this is put in place to deal with eff_distance = 0
            # needs to be fixed upstream in the pipeline
            effDs = list((row.ifo, row.eff_distance) for row in sngltab)
            for eD in effDs:
                if eD[1] == 0.:
                    effDs.append((eD[0], 1.))
                    effDs.remove(eD)
            coinc.set_effDs(dict(effDs))
            #      coinc.set_effDs(dict((row.ifo,row.eff_distance) for row in sngltab))
            coinc.set_masses(dict((row.ifo, row.mass1) for row in sngltab), \
                             dict((row.ifo, row.mass2) for row in sngltab))
            ctab = tab.get_table(xmldoc,
                                 lsctables.CoincInspiralTable.tableName)
            #FIXME: ignoring H2 for now, but should be dealt in a better way
            allifos = list(ctab[0].get_ifos())
            try:
                allifos.remove('H2')
            except ValueError:
                pass
            coinc.set_ifos(allifos)
            if ctab[0].false_alarm_rate is not None:
                coinc.set_FAR(ctab[0].false_alarm_rate)

            try:
                simtab = tab.get_table(xmldoc,
                                       lsctables.SimInspiralTable.tableName)
                row = siminsptab[0]
                effDs_inj = {}
                for ifo in coinc.ifo_list:
                    if ifo == 'H1':
                        effDs_inj[ifo] = row.eff_dist_h
                    elif ifo == 'L1':
                        effDs_inj[ifo] = row.eff_dist_l
                    elif ifo == 'V1':
                        effDs_inj[ifo] = row.eff_dist_v
                dist_inj = row.distance
                coinc.set_inj_params(row.latitude,row.longitude,row.mass1,row.mass2, \
                                     dist_inj,effDs_inj)
                coinc.is_injection = True
            #FIXME: name the exception!
            except:
                pass

            self.append(coinc)
Exemplo n.º 8
0
def CompareMultiInspiral(a, b, twindow=LIGOTimeGPS(0)):
    """
  Returns 0 if a and b are less than twindow appart.
  """
    tdiff = abs(a.get_end() - b.get_end())
    if tdiff < twindow:
        return 0
    else:
        return cmp(a.get_end(), b.get_end())
Exemplo n.º 9
0
 def test__init__(self):
     correct = LIGOTimeGPS(100, 500000000)
     tests = [
         (100.5, ),
         (100.500000000, ),
         (100.50000000000000000000000, ),
         ("100.5", ),
         ("100.500000000", ),
         ("100.50000000000000000000000", ),
         (0, 100500000000),
         (99, 1500000000),
         (-10, 110500000000),
     ]
     for num, test in enumerate(tests):
         try:
             self.assertEqual(correct, LIGOTimeGPS(*test))
         except AssertionError, e:
             raise AssertionError, "Test %d failed: " % (num) + str(e)
Exemplo n.º 10
0
    def set_dt(self, dt):
        """
		If an event's end time differs by more than this many
		seconds from the end time of another event then it is
		*impossible* for them to be coincident.
		"""
        # add 1% for safety, and pre-convert to LIGOTimeGPS to
        # avoid doing type conversion in loops
        self.dt = LIGOTimeGPS(dt * 1.01)
Exemplo n.º 11
0
 def get_gps_times( self ):
   """
   Return a dictionary of the GPS times associated with each
   trigger in the coincidence. The time is stored in LIGOTimeGPS format. 
   """
   gpstimes={}
   for ifo in ifos:
     if hasattr(self,ifo):
       gpstimes[ifo]= LIGOTimeGPS(getattr(self, ifo).end_time, getattr(self, ifo).end_time_ns)
   return gpstimes
Exemplo n.º 12
0
def cmp_sngl_sim(sim,
                 sngl,
                 get_sim_time,
                 get_sngl_time,
                 twindow=LIGOTimeGPS(9)):
    tdiff = abs(get_sngl_time(sngl) - get_sim_time(sim))
    if tdiff < twindow:
        return 0
    else:
        return cmp(get_sngl_time(sngl), get_sim_time(sim))
Exemplo n.º 13
0
    def get_time_delay(self, ifo1, ifo2, gpstime):
        """
        Return the time delay for this SkyPosition between arrival at ifo1
        relative to ifo2, for the given gpstime.
        """
        det1 = inject.cached_detector.get(inject.prefix_to_name[ifo1])
        det2 = inject.cached_detector.get(inject.prefix_to_name[ifo2])

        return date.XLALArrivalTimeDiff(det1.location, det2.location,\
                                        self.longitude, self.latitude,\
                                        LIGOTimeGPS(gpstime))
Exemplo n.º 14
0
def ISOTimeDelayLine(ifos, ra, dec, gpstime=None, n=3):
    """
    Returns the n-point SkyPositionTable describing a line of constant time
    delay through the given ra and dec. for the given 2-tuple ifos.
    """

    if gpstime:
        gpstime = LIGOTimeGPS(gpstime)

    p = SkyPosition()
    p.longitude = ra
    p.latitude = dec
    p.system = 'equatorial'
    p.probability = None
    p.solid_angle = None
    if gpstime:
        p = EquatorialToGeographic(p, gpstime)
    cart = SphericalToCartesian(p)

    # get baseline
    detectors = [inject.cached_detector.get(inject.prefix_to_name[ifo])\
                 for ifo in ifos]
    baseline = detectors[0].location - detectors[1].location
    baseline = baseline / np.linalg.norm(baseline)

    # get angle to baseline
    angle = np.arccos(np.dot(cart, baseline))

    # get evenly spaced ring over north pole
    longitudes = np.linspace(0, lal.TWOPI, n, endpoint=False)
    latitudes = [lal.PI_2 - angle] * len(longitudes)
    # get axis and angle of rotation
    north = np.array([0, 0, 1])
    axis = np.cross(north, baseline)
    axis = axis / np.linalg.norm(axis)
    angle = np.arccos(np.dot(north, baseline))
    R = _rotation(axis, angle)

    # construct sky table
    iso = SkyPositionTable()
    for lon, lat in zip(longitudes, latitudes):
        e = SkyPosition()
        e.longitude = lon
        e.latitude = lat
        e.probability = None
        e.solid_angle = None
        e.system = 'geographic'
        e.normalize()
        e = e.rotate(R)
        if gpstime:
            e = GeographicToEquatorial(e, gpstime)
        iso.append(e)

    return iso
Exemplo n.º 15
0
    def get_coincs_from_coire(self, files, stat='snr'):
        """
    uses CoincInspiralUtils to get data from old-style (coire'd) coincs
    """
        coincTrigs = CoincInspiralUtils.coincInspiralTable()
        inspTrigs = SnglInspiralUtils.ReadSnglInspiralFromFiles(files, \
                                      mangle_event_id = True,verbose=None)
        statistic = CoincInspiralUtils.coincStatistic(stat, None, None)
        coincTrigs = CoincInspiralUtils.coincInspiralTable(
            inspTrigs, statistic)

        try:
            inspInj = SimInspiralUtils.ReadSimInspiralFromFiles(files)
            coincTrigs.add_sim_inspirals(inspInj)
        #FIXME: name the exception!
        except:
            pass

        #now extract the relevant information into CoincData objects
        for ctrig in coincTrigs:
            coinc = CoincData()
            coinc.set_ifos(ctrig.get_ifos()[1])
            coinc.set_gps(
                dict(
                    (trig.ifo, LIGOTimeGPS(trig.get_end())) for trig in ctrig))
            coinc.set_snr(
                dict((trig.ifo, getattr(ctrig, trig.ifo).snr)
                     for trig in ctrig))
            coinc.set_effDs(
                dict((trig.ifo, getattr(ctrig, trig.ifo).eff_distance)
                     for trig in ctrig))
            coinc.set_masses(dict((trig.ifo,getattr(ctrig,trig.ifo).mass1) for trig in ctrig), \
                             dict((trig.ifo,getattr(ctrig,trig.ifo).mass2) for trig in ctrig))

            try:
                effDs_inj = {}
                for ifo in coinc.ifo_list:
                    if ifo == 'H1':
                        effDs_inj[ifo] = getattr(ctrig, 'sim').eff_dist_h
                    elif ifo == 'L1':
                        effDs_inj[ifo] = getattr(ctrig, 'sim').eff_dist_l
                    elif ifo == 'V1':
                        effDs_inj[ifo] = getattr(ctrig, 'sim').eff_dist_v
                dist_inj = getattr(ctrig, 'sim').distance
                coinc.set_inj_params(getattr(ctrig,'sim').latitude,getattr(ctrig,'sim').longitude, \
                                     getattr(ctrig,'sim').mass1,getattr(ctrig,'sim').mass2,dist_inj,effDs_inj)
                coinc.is_injection = True
                #FIXME: name the exception!
            except:
                pass

            self.append(coinc)
Exemplo n.º 16
0
def parse_COMPLEX16FrequencySeries(elem):
	t, = elem.getElementsByTagName(ligolw.Time.tagName)
	a, = elem.getElementsByTagName(ligolw.Array.tagName)
	dims = a.getElementsByTagName(ligolw.Dim.tagName)
	f0 = ligolw_param.get_param(elem, u"f0")
	return COMPLEX16FrequencySeries(
		name = a.Name,
		# FIXME:  remove type cast when epoch can be a swig LIGOTimeGPS
		epoch = LIGOTimeGPS(str(t.pcdata)),
		f0 = f0.pcdata * float(LALUnit(f0.Unit) / LALUnit("s^-1")),
		deltaF = dims[0].Scale * float(LALUnit(dims[0].Unit) / LALUnit("s^-1")),
		sampleUnits = LALUnit(a.Unit),
		data = a.array[1] + 1j * a.array[2]
	)
Exemplo n.º 17
0
    def parseTimeDelayDegeneracy(self, ifos, gpstime=lal.GPSTimeNow(),\
                                 dt=0.0005):

        # get detectors
        detectors = [inject.cached_detector.get(inject.prefix_to_name[ifo])\
                         for ifo in ifos]

        timeDelays = []
        degenerate = []

        new = table.new_from_template(self)
        for n, row in enumerate(self):
            # get all time delays for this point
            timeDelays.append([])
            for i in xrange(len(ifos)):
                for j in xrange(i + 1, len(ifos)):
                    timeDelays[n].append(date.XLALArrivalTimeDiff(\
                                             detectors[i].location,\
                                             detectors[j].location,\
                                             row.longitude,\
                                             row.latitude,\
                                             LIGOTimeGPS(gpstime)))
            # skip the first point
            if n == 0:
                degenerate.append(False)
                new.append(row)
                continue
            else:
                degenerate.append(True)
            # test this point against all others
            for i in xrange(0, n):
                # if check point is degenerate, skip
                if degenerate[i]:
                    continue
                # check each time delay individually
                for j in xrange(0, len(timeDelays[n])):
                    # if this time delay is non-degenerate the point is valid
                    if np.fabs(timeDelays[i][j] - timeDelays[n][j]) >= dt:
                        degenerate[n] = False
                        break
                    else:
                        degenerate[n] = True
                if degenerate[n]:
                    break

            if not degenerate[n]:
                new.append(row)

        return new
Exemplo n.º 18
0
def MaxTimeDelayLine3(ifo1, ifo2, ra, dec, gpstime=None, n=3):
    """
        Alternative implementation of MaxTimeDelayLine.
    """

    if gpstime:
        gpstime = LIGOTimeGPS(gpstime)

    p = SkyPosition()
    p.longitude = ra
    p.latitude = dec
    p.system = 'equatorial'
    p.probability = None
    p.solid_angle = None
    if gpstime:
        p = EquatorialToGeographic(p, gpstime)
    cart = SphericalToCartesian(p)

    # get baseline
    detectors = [inject.cached_detector.get(inject.prefix_to_name[ifo])\
                 for ifo in [ifo1,ifo2]]
    baseline = detectors[0].location - detectors[1].location
    baseline = baseline / np.linalg.norm(baseline)

    # get angular spacing
    dtheta = lal.TWOPI / n

    # get axis and angle of rotation
    north = np.array([0, 0, 1])
    axis = np.cross(cart, baseline)
    axis = axis / np.linalg.norm(axis)
    R = _rotation(axis, dtheta)

    # set up list
    l = SkyPositionTable()
    # append central point
    l.append(p)

    for i in xrange(1, n):
        l.append(l[i - 1].rotate(R))

    if gpstime:
        for i, p in enumerate(l):
            l[i] = GeographicToEquatorial(p, gpstime)
    return l
Exemplo n.º 19
0
def get_sitelocaltime_from_gps(ifo, gpstime):
    # get the utc time in datetime.datetime format
    utctime = XLALGPSToUTC(LIGOTimeGPS(gpstime, 0))
    utctime = datetime.datetime(utctime[0],utctime[1],utctime[2],utctime[3],utctime[4],utctime[5],utctime[6])
    # figure out if daylight savings time was on or not
    dst_start, dst_end = get_dst_start_end(ifo, utctime.year)
    # figure out the appropriate time offset
    if "H" in ifo:
        toffset = datetime.timedelta(hours=-7)
    elif "L" in ifo:
        toffset = datetime.timedelta(hours=-5)
    elif ("V" in ifo or "G" in ifo):
        toffset = datetime.timedelta(hours=+2)
    # apply the dst time offset to see if daylight savings was on; if not, adjust the toffset
    if not (utctime + toffset >= dst_start and utctime + toffset < dst_end):
        toffset = toffset + datetime.timedelta(hours=-1)

    return utctime + toffset
Exemplo n.º 20
0
def format_end_time_in_utc(gps_sec):
    return time.strftime("%a %d %b %Y %H:%M:%S", XLALGPSToUTC(LIGOTimeGPS(gps_sec, 0)))
 def is_in_on_time(gps_time, gps_time_ns):
     return LIGOTimeGPS(gps_time, gps_time_ns) in on_times
Exemplo n.º 22
0
 def get_gps(self):
     return LIGOTimeGPS(self.gps, self.gps_ns)
Exemplo n.º 23
0
    def __init__(self, xmldoc, bbdef, sbdef, scedef, scndef, process,
                 end_time_bisect_window):
        #
        # store the process row
        #

        self.process = process

        #
        # locate the sngl_inspiral and sim_inspiral tables
        #

        self.snglinspiraltable = lsctables.SnglInspiralTable.get_table(xmldoc)
        self.siminspiraltable = lsctables.SimInspiralTable.get_table(xmldoc)

        #
        # get the offset vectors from the document
        #

        self.offsetvectors = lsctables.TimeSlideTable.get_table(
            xmldoc).as_dict()

        #
        # get out segment lists for programs that generated
        # triggers (currently only used for time_slide vector
        # construction)
        #

        seglists = lsctables.SearchSummaryTable.get_table(
            xmldoc).get_out_segmentlistdict(
                set(self.snglinspiraltable.getColumnByName(
                    "process_id"))).coalesce()

        #
        # construct the zero-lag time slide needed to cover the
        # instruments listed in all the triggers, then determine
        # its ID (or create it if needed)
        #
        # FIXME:  in the future, the sim_inspiral table should
        # indicate time slide at which the injection was done
        #

        self.tisi_id = ligolw_time_slide.get_time_slide_id(xmldoc, {}.fromkeys(
            seglists, 0.0),
                                                           create_new=process)

        #
        # get coinc_definer row for sim_inspiral <--> sngl_inspiral
        # coincs; this creates a coinc_definer table if the
        # document doesn't have one
        #

        self.sb_coinc_def_id = ligolw_coincs.get_coinc_def_id(
            xmldoc,
            sbdef.search,
            sbdef.search_coinc_type,
            create_new=True,
            description=sbdef.description)

        #
        # get coinc_def_id's for sngl_inspiral <--> sngl_inspiral, and
        # both kinds of sim_inspiral <--> coinc_event coincs.  set all
        # to None if this document does not contain any sngl_inspiral
        # <--> sngl_inspiral coincs.
        #

        try:
            ii_coinc_def_id = ligolw_coincs.get_coinc_def_id(
                xmldoc,
                bbdef.search,
                bbdef.search_coinc_type,
                create_new=False)
        except KeyError:
            ii_coinc_def_id = None
            self.sce_coinc_def_id = None
            self.scn_coinc_def_id = None
        else:
            self.sce_coinc_def_id = ligolw_coincs.get_coinc_def_id(
                xmldoc,
                scedef.search,
                scedef.search_coinc_type,
                create_new=True,
                description=scedef.description)
            self.scn_coinc_def_id = ligolw_coincs.get_coinc_def_id(
                xmldoc,
                scndef.search,
                scndef.search_coinc_type,
                create_new=True,
                description=scndef.description)

        #
        # get coinc table, create one if needed
        #

        try:
            self.coinctable = lsctables.CoincTable.get_table(xmldoc)
        except ValueError:
            self.coinctable = lsctables.New(lsctables.CoincTable)
            xmldoc.childNodes[0].appendChild(self.coinctable)
        self.coinctable.sync_next_id()

        #
        # get coinc_map table, create one if needed
        #

        try:
            self.coincmaptable = lsctables.CoincMapTable.get_table(xmldoc)
        except ValueError:
            self.coincmaptable = lsctables.New(lsctables.CoincMapTable)
            xmldoc.childNodes[0].appendChild(self.coincmaptable)

        #
        # index the document
        #
        # FIXME:  inspiral<-->inspiral coincs should be organized by time
        # slide ID, but since injections are only done at zero lag
        # for now this is ignored.
        #

        # index the sngl_inspiral table
        index = dict((row.event_id, row) for row in self.snglinspiraltable)
        # find IDs of inspiral<-->inspiral coincs
        self.sngls = dict((row.coinc_event_id, []) for row in self.coinctable
                          if row.coinc_def_id == ii_coinc_def_id)
        # construct event list for each inspiral<-->inspiral coinc
        for row in self.coincmaptable:
            try:
                self.sngls[row.coinc_event_id].append(index[row.event_id])
            except KeyError:
                pass
        del index
        # construct a sngl-->coincs look-up table
        self.coincs = dict((event.event_id, set())
                           for events in self.sngls.values()
                           for event in events)
        for row in self.coincmaptable:
            if row.event_id in self.coincs and row.coinc_event_id in self.sngls:
                self.coincs[row.event_id].add(row.coinc_event_id)
        # create a coinc_event_id to offset vector look-up table
        self.coincoffsets = dict(
            (row.coinc_event_id, self.offsetvectors[row.time_slide_id])
            for row in self.coinctable if row.coinc_def_id == ii_coinc_def_id)

        #
        # sort sngl_inspiral table by end time, and sort the coincs
        # list by the end time of the first (earliest) event in
        # each coinc (recall that the event tuple for each coinc
        # has been time-ordered)
        #

        self.snglinspiraltable.sort(lambda a, b: cmp(a.end_time, b.end_time) or
                                    cmp(a.end_time_ns, b.end_time_ns))

        #
        # set the window for inspirals_near_endtime().  this window
        # is the amount of time such that if an injection's end
        # time and a inspiral event's end time differ by more than
        # this it is *impossible* for them to match one another.
        #

        self.end_time_bisect_window = LIGOTimeGPS(end_time_bisect_window)
Exemplo n.º 24
0
 def get_start(self):
     return LIGOTimeGPS(self.start_time, self.start_time_ns)
Exemplo n.º 25
0
def ThreeSiteSkyGrid(ifos, gpstime, dt=0.0005, tiling='square', sky='half'):
    """
    Generates a SkyPositionTable for a three-site all-sky grid, covering either
    a hemisphere (sky='half') or full sphere (sky='full'), using either
    'square' or 'hexagonal tiling.
    """

    # remove duplicate site references
    pop = []
    for i, ifo in enumerate(ifos):
        if i == 0: continue
        site = ifo[0]
        if site in [x[0] for x in ifos[0:i]]:
            sys.stderr.write("Duplicate site reference, ignoring %s.\n" % ifo)
            pop.append(i)
    for p in pop[::-1]:
        ifos.pop(p)

    assert len(ifos) == 3

    detectors = []
    T = []
    baseline = []

    # load detectors
    for i, ifo in enumerate(ifos):
        detectors.append(inject.cached_detector.get(
            inject.prefix_to_name[ifo]))
        # get light travel time and baseline for other detectors to first
        if i >= 1:
            T.append(inject.light_travel_time(ifos[0], ifos[i]))
            baseline.append(detectors[i].location - detectors[0].location)
            baseline[i - 1] /= np.linalg.norm(baseline[i - 1])

    # get angle between baselines
    angle = np.arccos(np.dot(baseline[0], baseline[1]))

    #
    # construct tiling vectors
    #

    tiling = tiling.lower()
    t = np.zeros(len(baseline))
    tdgrid = []

    # square grid
    dx = np.array([1, 0])
    dy = np.array([0, 1])
    nx = int(np.floor(T[0] / dt))
    ny = int(np.floor(T[1] / dt))

    # hexagonal grid
    if tiling == 'square':
        dm = dx
        dn = dy
        nm = nx
        nn = ny
        x = np.linspace(-nx, nx, 2 * nx + 1)
        y = np.linspace(-ny, ny, 2 * ny + 1)
        grid = np.array([[i, j] for i in x for j in y])
    # hexagonal grid
    elif re.match('hex', tiling):
        dm = (2 * dx + dy)
        dn = (-dx + dy)
        dx = dm - dn
        # tile grid so that origin gets tiled
        grid = []
        orig = np.array([0, 0])

        # find bottom left point on grid
        while orig[1] >= -ny:
            orig -= dn

        # loop over y
        for y in xrange(-ny, ny + 1):
            orig[0] = orig[0] % dx[0]
            # work out minimal x value
            minx = -nx
            while minx % 3 != orig[0]:
                minx += 1
            # tile x
            x = np.arange(minx, nx + 1, dx[0])
            # append to grid
            grid.extend([[i, y] for i in x])
            orig += dn
            orig[0] = orig[0] % dx[0]
        grid = np.asarray(grid)

    #
    # Following Rabaste, Chassande-Motin, Piran (2009), construct an ellipse
    # of physical values in 2D time-delay space for 3 detectors
    #

    #
    # (theta, phi) coordinate system is as follows:
    # detector 1 is origin
    # z-axis joins positively to detector 2
    # x-axis is orthogonal to z-axis in plane joining D1, D2, and D3
    # y-axis forms a right-handed coordinate system
    #

    # so need to rotate from Rabaste network coordinates into
    # earth-fixed coordinates at the end

    # set z-axis in Rabaste frame
    zaxis = baseline[0]

    # work out y-axis in Rabaste frame
    yaxis = np.cross(zaxis, baseline[1])
    yaxis /= np.linalg.norm(yaxis)

    # work out x-axis in Rabaste frame
    xaxis = np.cross(yaxis, zaxis)
    xaxis /= np.linalg.norm(xaxis)

    # work out lines of nodes
    north = np.array([0, 0, 1])
    lineofnodes = np.cross(baseline[0], north)
    lineofnodes /= np.linalg.norm(lineofnodes)

    # work out Euler angles
    alpha = np.arccos(np.dot(xaxis, lineofnodes))
    beta = np.arccos(np.dot(baseline[0], north))
    gamma = np.arccos(np.dot(lineofnodes, [1, 0, 0]))

    # construct rotation
    R = _rotation_euler(alpha, beta, gamma)

    #
    # construct sky position table
    #

    l = SkyPositionTable()
    # loop over time-delay between D1 and D2
    k = 0
    for i in grid:
        t = dt * i
        # construct coefficients of elliptical equation in quadratic form
        A = -T[1] / T[0] * t[0] * np.cos(angle)
        B = T[1]**2 * ((t[0] / T[0])**2 - np.sin(angle)**2)
        # test condition for inside ellipse and place point
        condition = t[1]**2 + 2 * A * t[1] + B
        if condition <= 0:
            ntheta = np.arccos(-t[0] / T[0])
            nphi   = np.arccos(-(T[0]*t[1]-T[1]*t[0]*np.cos(angle))/\
                                (T[1]*np.sqrt(T[0]**2-t[0]**2)*np.sin(angle)))
            p = SkyPosition()
            p.system = 'geographic'
            p.longitude = nphi
            p.latitude = lal.PI_2 - ntheta
            p.probability = None
            p.solid_angle = None
            p.normalize()
            p = p.rotate(R)
            p = GeographicToEquatorial(p, LIGOTimeGPS(gpstime))
            l.append(p)
            if sky == 'full':
                p2 = SkyPosition()
                p2.longitude = p.longitude
                p2.latitude = p.latitude + lal.PI
                p2.system = 'equatorial'
                p2.normalize()
                l.append(p2)

    return l
Exemplo n.º 26
0
def TwoSiteSkyGrid(ifos, gpstime, dt=0.0005, sky='half', point=None):
    """
    Generates a SkyPositionTable for a two-site all-sky grid, covering either
    a hemisphere (sky='half') or full sphere (sky='full').

    The grid can be forced to pass through the given SkyPosition point if
    required.
    """

    # remove duplicate site references
    ifos = parse_sites(ifos)
    assert len(ifos) == 2, "More than two sites in given list of detectors"

    # get detectors
    detectors = [inject.cached_detector.get(inject.prefix_to_name[ifo])\
                 for ifo in ifos]

    # get light travel time
    ltt = inject.light_travel_time(ifos[0], ifos[1])

    # get number of points
    max = int(np.floor(ltt / dt))

    # get baseline
    baseline = detectors[1].location - detectors[0].location
    baseline /= np.linalg.norm(baseline)

    #
    # construct rotation
    #

    # xaxis points overhead of detector 1 or given point
    # zaxis is baseline, or something else
    if point:
        xaxis = SphericalToCartesian(point)
        xaxis /= np.linalg.norm(xaxis)
        zaxis = np.cross(xaxis, baseline)
        zaxis /= np.linalg.norm(zaxis)
    else:
        xaxis = detectors[0].location
        xaxis /= np.linalg.norm(xaxis)
        zaxis = baseline
        yaxis = np.cross(zaxis, xaxis)
        yaxis /= np.linalg.norm(yaxis)

    yaxis = np.cross(xaxis, zaxis)
    yaxis /= np.linalg.norm(yaxis)

    # construct Euler rotation
    lineofnodes = np.cross([0, 0, 1], zaxis)
    lineofnodes /= np.linalg.norm(lineofnodes)

    # work out Euler angles
    alpha = np.arccos(np.dot([1, 0, 0], lineofnodes))
    beta = np.arccos(np.dot([0, 0, 1], zaxis))
    gamma = np.arccos(np.dot(lineofnodes, xaxis))

    # get rotation
    R = _rotation_euler(alpha, beta, gamma)

    # construct sky table
    l = SkyPositionTable()
    if sky == 'half': longs = [0]
    elif sky == 'full': longs = [0, lal.PI]
    else:
        raise AttributeError("Sky type \"%s\" not recognised, please use "
                             "'half' or 'full'" % sky)

    for long in longs:
        for i in xrange(-max, max + 1):
            # get time-delay
            t = i * dt
            # if time-delay greater that light travel time, skip
            if abs(t) >= ltt: continue
            # construct object
            e = SkyPosition()
            e.system = 'geographic'
            # project time-delay onto prime meridian
            e.longitude = long
            e.latitude = lal.PI_2 - np.arccos(-t / ltt)
            e.probability = None
            e.solid_angle = None
            e.normalize()
            e = e.rotate(R)
            e = GeographicToEquatorial(e, LIGOTimeGPS(gpstime))
            if e not in l:
                l.append(e)

    return l
Exemplo n.º 27
0
def SkyPatch(ifos, ra, dec, radius, gpstime, dt=0.0005, sigma=1.65,\
             grid='circular'):
    """
    Returns a SkyPositionTable of circular rings emanating from a given
    central ra and dec. out to the maximal radius.
    """

    # form centre point
    p = SkyPosition()
    p.longitude = ra
    p.latitude = dec

    # get detectors
    ifos.sort()
    detectors = []
    for ifo in ifos:
        if ifo not in inject.prefix_to_name.keys():
            raise ValueError("Interferometer '%s' not recognised." % ifo)
        detectors.append(inject.cached_detector.get(\
                             inject.prefix_to_name[ifo]))

    alpha = 0
    for i in xrange(len(ifos)):
        for j in xrange(i + 1, len(ifos)):
            # get opening angle
            baseline = date.XLALArrivalTimeDiff(detectors[i].location,\
                                                detectors[j].location,\
                                                ra, dec, LIGOTimeGPS(gpstime))
            ltt = inject.light_travel_time(ifos[i], ifos[j])
            angle = np.arccos(baseline / ltt)

            # get window
            lmin = angle - radius
            lmax = angle + radius
            if lmin < lal.PI_2 and lmax > lal.PI_2:
                l = lal.PI_2
            elif np.fabs(lal.PI_2-lmin) <\
                     np.fabs(lal.PI_2-lmax):
                l = lmin
            else:
                l = lmax

            # get alpha
            dalpha = ltt * np.sin(l)
            if dalpha > alpha:
                alpha = dalpha

    # get angular resolution
    angRes = 2 * dt / alpha

    # generate grid
    if grid.lower() == 'circular':
        grid = CircularGrid(angRes, radius)
    else:
        raise RuntimeError("Must use grid='circular', others not coded yet")

    #
    # Need to rotate grid onto (ra, dec)
    #

    # calculate opening angle from north pole
    north = [0, 0, 1]
    angle = np.arccos(np.dot(north, SphericalToCartesian(p)))
    #angle = north.opening_angle(p)

    # get rotation axis
    axis = np.cross(north, SphericalToCartesian(p))
    axis = axis / np.linalg.norm(axis)

    # rotate grid
    R = _rotation(axis, angle)
    grid = grid.rotate(R)

    #
    # calculate probability density function
    #

    # assume Fisher distribution in angle from centre
    kappa = (0.66 * radius / sigma)**(-2)

    # compute probability
    for p in grid:
        overlap = np.cos(p.opening_angle(grid[0]))
        p.probability = np.exp(kappa * (overlap - 1))

    probs = [p.probability for p in grid]
    for p in grid:
        p.probability = p.probability / max(probs)

    return grid
def frominjectionfile(file, type, ifo=None, start=None, end=None):
  
  """
    Read generic injection file object file containing injections of the given
    type string. Returns an 'Sim' lsctable of the corresponding type.

    Arguments:
   
      file : file object
      type : [ "inspiral" | "burst" | "ringdown" ]

    Keyword arguments:

      ifo : [ "G1" | "H1" | "H2" | "L1" | "V1" ]
  """

  # read type
  type = type.lower()

  # read injection xml
  xml = re.compile('(xml$|xml.gz$)')
  if re.search(xml,file.name):
    xmldoc,digest = utils.load_fileobj(file)
    injtable = table.get_table(xmldoc,'sim_%s:table' % (type))

  # read injection txt
  else:
    cchar = re.compile('[#%<!()_\[\]{}:;\'\"]+')

    #== construct new Sim{Burst,Inspiral,Ringdown}Table
    injtable = lsctables.New(lsctables.__dict__['Sim%sTable' % (type.title())])
    if type=='inspiral':
      columns = ['geocent_end_time.geocent_end_time_ns',\
                 'h_end_time.h_end_time_ns',\
                 'l_end_time.l_end_time_ns',\
                 'v_end_time.v_end_time_ns',\
                 'distance'] 
      for line in file.readlines():
        if re.match(cchar,line):
          continue
        # set up siminspiral object
        inj = lsctables.SimInspiral()
        # split data
        sep = re.compile('[\s,=]+')
        data = sep.split(line)
        # set attributes
        inj.geocent_end_time    = int(data[0].split('.')[0])
        inj.geocent_end_time_ns = int(data[0].split('.')[1])
        inj.h_end_time          = int(data[1].split('.')[0])
        inj.h_end_time_ns       = int(data[1].split('.')[1])
        inj.l_end_time          = int(data[2].split('.')[0])
        inj.l_end_time_ns       = int(data[2].split('.')[1])
        inj.v_end_time          = int(data[3].split('.')[0])
        inj.v_end_time_ns       = int(data[3].split('.')[1])
        inj.distance            = float(data[4])

        injtable.append(inj)

    if type=='burst':
      if file.readlines()[0].startswith('filestart'):
        # if given parsed burst file
        file.seek(0)

        snrcol = { 'G1':23, 'H1':19, 'L1':21, 'V1':25 }

        for line in file.readlines():
          inj = lsctables.SimBurst()
          # split data
          sep = re.compile('[\s,=]+')
          data = sep.split(line)
          # set attributes

          # gps time
          if 'burstgps' in data:
            idx = data.index('burstgps')+1
            geocent = LIGOTimeGPS(data[idx])

            inj.time_geocent_gps    = geocent.seconds
            inj.time_geocent_gps_ns = geocent.nanoseconds
          else:
            continue


          #inj.waveform            = data[4]
          #inj.waveform_number     = int(data[5])

          # frequency
          if 'freq' in data:
            idx = data.index('freq')+1
            inj.frequency = float(data[idx])
          else:
            continue

          # SNR a.k.a. amplitude
          if ifo and 'snr%s' % ifo in data:
            idx = data.index('snr%s' % ifo)+1
            inj.amplitude = float(data[idx])
          elif 'rmsSNR' in data:
            idx = data.index('rmsSNR')+1
            inj.amplitude = float(data[idx])
          else:
            continue

          if 'phi' in data:
            idx = data.index('phi' )+1
            inj.ra = float(data[idx])*24/(2*math.pi)       

          if 'theta' in data:
            idx = data.index('theta' )+1 
            inj.ra = 90-(float(data[idx])*180/math.pi)

          if ifo and 'hrss%s' % ifo in data:
            idx = data.index('hrss%s' % ifo)+1
            inj.hrss = float(data[idx])
          elif 'hrss' in data:
            idx = data.index('hrss')+1
            inj.hrss = float(data[idx])

          # extra columns to be added when I know how
          #inj.q = 0
          #inj.q                   = float(data[11])
          #h_delay = LIGOTimeGPS(data[41])
          #inj.h_peak_time         = inj.time_geocent_gps+h_delay.seconds
          #inj.h_peak_time_ns      = inj.time_geocent_gps_ns+h_delay.nanoseconds
          #l_delay = LIGOTimeGPS(data[43])
          #inj.l_peak_time         = inj.time_geocent_gps+l_delay.seconds
          #inj.l_peak_time_ns      = inj.time_geocent_gps_ns+l_delay.nanoseconds
          #v_delay = LIGOTimeGPS(data[43])
          #inj.v_peak_time         = inj.time_geocent_gps+v_delay.seconds
          #inj.v_peak_time_ns      = inj.time_geocent_gps_ns+v_delay.nanoseconds

          injtable.append(inj)

      else:
        # if given parsed burst file
        file.seek(0)
        for line in file.readlines():
          inj = lsctables.SimBurst()
          # split data
          sep = re.compile('[\s,]+')
          data = sep.split(line)
          # set attributes
          geocent = LIGOTimeGPS(data[0])
          inj.time_geocent_gps    = geocent.seconds
          inj.time_geocent_gps_ns = geocent.nanoseconds

          injtable.append(inj)

  injections = table.new_from_template(injtable)
  if not start:  start = 0
  if not end:    end   = 9999999999
  span = segments.segmentlist([ segments.segment(start, end) ])
  get_time = dqTriggerUtils.def_get_time(injections.tableName)
  injections.extend(inj for inj in injtable if get_time(inj) in span)

  return injections
Exemplo n.º 29
0
 def get_end(self):
     return LIGOTimeGPS(self.end_time, self.end_time_ns)
Exemplo n.º 30
0
def get_daily_ihope_page(gpstime, pages_location = "https://ldas-jobs.ligo.caltech.edu/~cbc/ihope_daily"):
    utctime = XLALGPSToUTC(LIGOTimeGPS(gpstime, 0))
    return "%s/%s/%s/" %(pages_location, time.strftime("%Y%m", utctime), time.strftime("%Y%m%d", utctime))