Beispiel #1
0
 def read_catalog(self, filename, delimiter=',', append=True):
     """
     Given a filename where the first line is a descriptor
     of the columns for eg:
      NAME,        RA,         Dec,     RA_REF,     Dec_REF,    VLSR,  EPOCH
     this function will read all the lines and convert to XEphem
     format catalog format, and append to bodies object if append=True
     If append=False, will create a new dictionary of bodies
     """
     if not append:
         self.bodies = {}
     if not os.path.exists(filename):
         raise DreampyGeneralError(
             "No Such File", "Cannot find catalog filename %s" % filename)
     #now open and read first line
     fp = open(filename, 'r')
     first = fp.readline()
     colnames = [
         col.strip().lower() for col in first.strip().split(delimiter)
     ]
     colname_index = {}
     for col in ('name', 'ra', 'dec', 'epoch'):
         try:
             colname_index[col] = colnames.index(col)
         except ValueError:
             raise DreampyGeneralError(
                 "No col %s" % col,
                 "Catalog Filename %s does not contain column name %s; it is needed!"
                 % (filename, col))
     numbodies = 0
     for line in fp.readlines():
         #print line
         if line[0] == '#' or line[0] == ' ':
             #comment line or empty line
             continue
         try:
             columns = [
                 col.strip() for col in line.strip().split(delimiter)
             ]
             name = columns[colname_index['name']]
             ra = columns[colname_index['ra']]
             dec = columns[colname_index['dec']]
             epoch = columns[colname_index['epoch']]
             # see http://www.mmto.org/obscats/edb.html for XEphem format
             body = ephem.readdb('%s,f|J,%s,%s,,%s' %
                                 (name, ra, dec, epoch))
             numbodies += 1
             self.bodies[name] = body
             print("Read in %s" % name)
         except:
             continue
     print("Read %d bodies from catalog file %s" % (numbodies, filename))
     fp.close()
Beispiel #2
0
 def report_body(self, name):
     """
     Given a source name which has already been read in using read_catalog
     report_body will produce a simple summary of current az and elevation
     and rise_time, set_time and transit_time all in localtime
     """
     if not self.bodies.has_key(name):
         raise DreampyGeneralError(
             "No such Source",
             "The current catalog does not have source with name %s" % name)
     body = self.bodies[name]
     self.set_time_now()
     body.compute(self)
     if type(body) == ephem.FixedBody:
         rstr = 'Source: %s; Ra: %s, Dec: %s\n' % (name, body._ra,
                                                   body._dec)
     else:
         rstr = 'Source: %s; Ra: %s, Dec: %s\n' % (name, body.ra, body.dec)
     rstr += 'Current time: %s\n' % (datetime.datetime.now())
     rstr += 'Current Az: %s, El: %s\n' % (body.az, body.alt)
     rstr += 'Prev Rise Time: %s\n' % (ephem.localtime(
         self.previous_rising(body)))
     rstr += 'Next Rise Time: %s\n' % (ephem.localtime(
         self.next_rising(body)))
     rstr += 'Next Transit Time: %s\n' % (ephem.localtime(
         self.next_transit(body)))
     rstr += 'Next Set Time: %s\n' % (ephem.localtime(
         self.next_setting(body)))
     print(rstr)
Beispiel #3
0
 def check_alive(self):
     """A simple routine that checks if the plot window is still alive
     """
     if not self.alive:
         raise DreampyGeneralError(
             "PlotWindow",
             "Plot window has been killed, restart plot window")
Beispiel #4
0
def read_lmt_cat(filename, delimiter=','):
    """
    Given a filename where the first line is a descriptor
    of the columns for eg:
    NAME,        RA,         Dec,     RA_REF,     Dec_REF,    VLSR,  EPOCH
    this function will read all the lines and convert to XEphem
    format catalog format and return source dictionary
    """
    if not os.path.exists(filename):
        raise DreampyGeneralError("No Such File",
                                  "Cannot find catalog filename %s" % filename)
    #now open and read first line
    fp = open(filename, 'r')
    first = fp.readline()
    colnames = [col.strip().lower() for col in first.strip().split(delimiter)]
    colname_index = {}
    for col in ('name', 'ra', 'dec', 'epoch'):
        try:
            colname_index[col] = colnames.index(col)
        except ValueError:
            raise DreampyGeneralError(
                "No col %s" % col,
                "Catalog Filename %s does not contain column name %s; it is needed!"
                % (filename, col))
    numbodies = 0
    sdic = {}
    for line in fp.readlines():
        #print line
        if line[0] == '#' or line[0] == ' ':
            #comment line or empty line
            continue
        try:
            columns = [col.strip() for col in line.strip().split(delimiter)]
            source = Source()
            source.name = columns[colname_index['name']]
            source.RA = columns[colname_index['ra']]
            source.Dec = columns[colname_index['dec']]
            source.VLSR = 0.0
            source.epoch = columns[colname_index['epoch']]
            sdic[source.name] = source.ephem_db()
            numbodies += 1
        except:
            continue
    fp.close()
    print("Read %d bodies from catalog file %s" % (numbodies, filename))
    return sdic
Beispiel #5
0
 def _estimate(self, data):
     # guess some fit parameters
     peak = numpy.nanmax(self.z)
     mux = (self.z * self.x).sum() / self.z.sum()
     muy = numpy.sum(self.z * self.y) / numpy.sum(self.z)
     sigmax = (self.z * (self.x - mux)**2.).sum() / numpy.abs(self.z.sum())
     sigmay = (self.z * (self.y - muy)**2.).sum() / numpy.abs(self.z.sum())
     if sigmax < 0.0:
         print('No signal to estimate 2nd x moment')
         raise DreampyGeneralError("No Signal",
                                   "No signal to estimate 2nd moment")
     if sigmay < 0.0:
         print('No signal to estimate 2nd y moment')
         raise DreampyGeneralError("No Signal",
                                   "No signal to estimate 2nd moment")
     p0 = numpy.array(
         [peak, mux, muy,
          math.sqrt(sigmax),
          math.sqrt(sigmay)])
     print(p0)
     return p0
Beispiel #6
0
 def set_time(self, dt):
     """
     dt should be a datetime object
     if not timezone aware we will assume that it is in
     the local timezone of the location and then convert to utc
     """
     if type(dt) != datetime.datetime:
         # use a parser
         try:
             dt = parse(dt)
         except ValueError:
             raise DreampyGeneralError("Malformed Datetime",
                                       "Cannot parse datetime %s" % dt)
     if dt.tzinfo is None:
         #make it localtime first
         dt = dt.replace(tzinfo=self.tzone)
     self.date = dt.astimezone(pytz.utc)
Beispiel #7
0
 def _estimate(self, data):
     x = data.x
     z = data.y
     # guess some fit parameters
     if self.peak is None:
         self.peak = numpy.max(z)
     if self.mu is None:
         self.mu = numpy.sum(z * x) / numpy.sum(z)
     if self.sigma is None:
         self.sigma = numpy.sqrt(
             numpy.abs(numpy.sum(z * (x - self.mu)**2.) / numpy.sum(z)))
     if self.sigma < 0.0:
         print('No signal to estimate 2nd moment')
         raise DreampyGeneralError("No Signal",
                                   "No signal to estimate 2nd moment")
     #print peak, mu, math.sqrt(sigma)
     return numpy.array([self.peak, self.mu, math.sqrt(self.sigma)])
 def set(self, item, value, nc=None, dtype=None, dimensions=()):
     """
     Given an item such as Dcs.Receiver and an appropriate
     value, an existing NetCDF variable is modified by the
     new value, or else a new NetCDF variable is created.
     """
     #first find out if item exists
     create = False
     if item.find('.'):
         header_tree = item.split('.')
         var = self  #.copy()
         for i, h in enumerate(header_tree):
             if not h in var:
                 #raise DreampyGeneralError("No Such item", "Item %s is not found in header" % h)
                 print("Creating item %s in header" % h)
                 if i < len(header_tree) - 1:
                     var[h] = OrderedNetCDFDict()
                     var = var.__getitem__(h)
                 else:
                     var[h] = None
                 create = True
             else:
                 var = var.__getitem__(h)
     else:
         #no dots
         var = self  #.copy()
         if not item in var:
             print("Creating item %s in header" % item)
             create = True
             h = item
             var[h] = None
             #var[item] = OrderedNetCDFDict()
         else:
             var = self.__getitem__(item)
     if not create:
         #existing variable is to be modified
         #shape = var.shape
         dimensions = var.dimensions
         dtype = var.dtype
         if isinstance(value, (type(None), str, int, float, bool)):
             #this is a scalar value
             if var.size == 1:
                 #var is also a scalar
                 var[:] = value
             else:
                 raise DreampyArgumentError(
                     "Wrong Size",
                     "Variable %s has size %d, not the same as value given %s"
                     % (item, len(var), value))
         else:
             if len(var) != len(value):
                 raise DreampyArgumentError(
                     "Wrong Size",
                     "Variable %s has size %d, not the same as size of value given %s"
                     % (item, len(var), value))
             if var.shape != value.shape:
                 raise DreampyArgumentError(
                     "Wrong Shape",
                     "Variable %s has shape %s, not the same as shape of value given by %s"
                     % (item, var.shape, value.shape))
             var[:] = value
         print("Item %s updated to %s" % (item, self.get(item)))
     else:
         #create a brand new variable
         if nc is None:
             raise DreampyGeneralError(
                 "Create Error",
                 "New NetCDF variable is to be created. Please make sure to pass the netCDF dataset instance in nc"
             )
         new_var = nc.createVariable("Header.%s" % item,
                                     dtype,
                                     dimensions=dimensions)
         new_var[:] = value
         var[h] = new_var
Beispiel #9
0
    def plot_uptimes(self,
                     catalog_fname=None,
                     delimiter=',',
                     day=None,
                     add_planets=True,
                     sources=[],
                     loc=LMT,
                     **kwargs):
        #utcoffset=5.0, **kwargs):
        """plot uptimes for a catalog filename that is based on
        the LMT catalog format. If catalog filename is None,
        then only planets are plotted. If day is None, today's date is assumed.
        day can be a datetime.date instance or a string like 'May 21, 2011',
        or '2011-05-30', etc.
        If sources is a non-empty list, only objects in that list are plotted
        """
        from matplotlib.pyplot import setp

        self.clear()
        if catalog_fname is None:
            only_planets = True
        else:
            only_planets = False
            if not os.path.exists(catalog_fname):
                raise DreampyGeneralError(
                    "Plot Uptimes", "File %s does not exist" % catalog_fname)
            sdic = read_lmt_cat(catalog_fname, delimiter=delimiter)
            if sources:
                rsdic = {}
                for source in sources:
                    if sdic.has_key(source):
                        rsdic[source] = sdic[source]
                    else:
                        print("Source %s is not in catalog %s. Skipping.." %
                              (source, catalog_fname))
                if not rsdic:
                    #empty
                    raise DreampyGeneralError(
                        "Plot Uptimes",
                        "No sources in %s found in catalog %s" %
                        (sources, catalog_fname))
                else:
                    print("Plotting only sources: %s" % rsdic.keys())
                sdic = rsdic

        if day is not None:
            try:
                day = parser.parse(day)
            except:
                day = None
        if day is None:
            daydate = datetime.datetime.today()
        else:
            daydate = day
        if only_planets:
            localtime, uttime, selev = planetary_uptimes(
                day=day, add_planets=add_planets, loc=loc)
            #utcoffset=utcoffset)
        else:
            localtime, uttime, selev = source_uptimes(sdic,
                                                      day=day,
                                                      add_planets=add_planets,
                                                      loc=loc)

        formatter = DateFormatter('%H:%M:%S')
        for i, src in enumerate(selev.keys()):
            yval = (i + 1) * 2
            source_yval = yval * numpy.ones(len(localtime))
            ind = numpy.where(selev[src] < 20.)
            source_yval[ind] = numpy.nan
            idx = numpy.where(selev[src] == selev[src].max())
            self.plot_date(localtime, source_yval, '-', label=src)
            self.set_text(localtime[idx[0][0]],
                          yval + 0.5,
                          src,
                          fontdict={'size': "xx-small"})

        ax, kw = self.plotobj._get_current_axes(**kwargs)
        ax.xaxis.set_major_formatter(formatter)
        labels = ax.get_xticklabels()
        setp(labels, rotation=30, fontsize=8)
        ymax = (((len(selev.keys()) + 1) * 2) / 10) * 10 + 10
        self.set_ylim(0, ymax)
        #self.plotobj.f.autofmt_xdate()
        if only_planets:
            self.set_subplot_title('Planet Uptimes at %s for Date: %s' %
                                   (loc.name, daydate.strftime('%m-%d-%y')))
        else:
            self.set_subplot_title(
                'Source Uptimes at %s for %s, Date: %s' %
                (loc.name, catalog_fname, daydate.strftime('%m-%d-%y')))
        self.set_xlabel('Localtime')
        self.redraw_plot()