Ejemplo n.º 1
0
 def overlay_fov(self, tx=cartopy.crs.PlateCarree(), maxGate=75, rangeLimits=None, beamLimits=None,
         model="IS", fov_dir="front", fovColor=None, fovAlpha=0.2,
         fovObj=None, zorder=2, lineColor="k", lineWidth=1, ls="-"):
     """ Overlay radar FoV """
     self.maxGate = maxGate
     lcolor = lineColor
     from numpy import transpose, ones, concatenate, vstack, shape
     self.hdw = pydarn.read_hdw_file(self.rad)
     sgate = 0
     egate = self.hdw.gates if not maxGate else maxGate
     ebeam = self.hdw.beams
     if beamLimits is not None: sbeam, ebeam = beamLimits[0], beamLimits[1]
     else: sbeam = 0
     self.rad_fov = rad_fov.CalcFov(hdw=self.hdw, ngates=egate)
     xyz = self.projection.transform_points(tx, self.rad_fov.lonFull, self.rad_fov.latFull)
     x, y = xyz[:, :, 0], xyz[:, :, 1]
     contour_x = concatenate((x[sbeam, sgate:egate], x[sbeam:ebeam, egate],
         x[ebeam, egate:sgate:-1],
         x[ebeam:sbeam:-1, sgate]))
     contour_y = concatenate((y[sbeam, sgate:egate], y[sbeam:ebeam, egate],
         y[ebeam, egate:sgate:-1],
         y[ebeam:sbeam:-1, sgate]))
     self.plot(contour_x, contour_y, color=lcolor, zorder=zorder, linewidth=lineWidth, ls=ls)
     if fovColor:
         contour = transpose(vstack((contour_x, contour_y)))
         polygon = Polygon(contour)
         patch = PolygonPatch(polygon, facecolor=fovColor, edgecolor=fovColor, alpha=fovAlpha, zorder=zorder)
         self.add_patch(patch)
     return
Ejemplo n.º 2
0
 def overlay_radar_data(self, df, p_name = "v", tx=cartopy.crs.PlateCarree(), 
                        p_max=100, p_min=-100, p_step=10, p_ub=9999, p_lb=-9999,
                        cmap=matplotlib.pyplot.get_cmap("Spectral"), 
                        add_colorbar=True, colorbar_label="Velocity [m/s]", 
                        gflg_mask=True, **kwargs):
     """ 
         Adding radar data
         df: dataframe object
     """
     nbeam = np.max(np.max(dat["bmnum"])) + 1
     if self.maxGate: nrange = self.maxGate
     else: nrange = np.max(np.max(dat["slist"])) + 1
     hdw = pydarn.read_hdw_file(self.rad)
     rf = rad_fov.CalcFov(hdw=hdw, ngates=nrange, nbeams=nbeam)
     lons, lats = rf.lonFull, rf.latFull
     
     Xb, Yg, Px = utils.get_gridded_parameters(df, xparam="bmnum", yparam="slist", zparam=zparam)
     lons, lats = lons[Xb.ravel(), Yg.ravel()], lats[Xb.ravel(), Yg.ravel()]
     p_ranges = list(range(p_min, p_max + 1, p_step))
     p_ranges.insert(0, p_lb)
     p_ranges.append(p_ub)
     
     #Px, Gs = np.zeros((nbeam, nrange))*np.nan, np.zeros((nbeam, nrange))
     #idbs, idgs = dat["bmnum"], dat["slist"]
     #params, gflgs = dat[p_name], dat["gflg"]
     #for idb, idg, par, gflg in zip(idbs, idgs, params, gflgs):
     #    idb = np.array(idb)[np.array(idg) < nrange]
     #    par = np.array(par)[np.array(idg) < nrange]
     #    gflg = np.array(gflg)[np.array(idg) < nrange]
     #    idg = np.array(idg)[np.array(idg) < nrange]
     #    if len(par) > 0: 
     #        Px[idb, np.round(idg).astype(int)] = par
     #        Gs[idb, np.round(idg).astype(int)] = gflg
     if not gflg_mask: 
         Px = np.ma.masked_invalid(Px)
         self.pcolormesh(lons, lats, Px, transform=tx, cmap=cmap,
                       vmax=p_max, vmin=p_min, **kwargs)    
     else:
         Gs = Gs.astype(bool)
         Pi, Pg = np.ma.masked_invalid(np.ma.masked_where(Gs, Px)),\
                     np.ma.masked_invalid(np.ma.masked_where(np.logical_not(Gs), Px))
         self.pcolormesh(lons, lats, Pi, transform=tx, cmap=cmap,
                         vmax=p_max, vmin=p_min, **kwargs)
         gcmap = matplotlib.colors.ListedColormap(["0.6"])
         self.pcolormesh(lons, lats, Pg, transform=tx, cmap=gcmap,
                         vmax=p_max, vmin=p_min, **kwargs)
     if add_colorbar: 
         self._add_colorbar(p_ranges, cmap, label=colorbar_label)
         if gflg_mask: self._add_key_specific_colorbar(gcmap)
     return
Ejemplo n.º 3
0
 def overlay_fitacfp_radar_data(self, dat, p_name = "v", tx=cartopy.crs.PlateCarree(), 
                        p_max=100, p_min=-100, p_step=10, p_ub=9999, p_lb=-9999,
                        cmap=matplotlib.pyplot.get_cmap("Spectral"), 
                        add_colorbar=True, colorbar_label="Velocity [m/s]", gflg_key="gflg", 
                        gflg_map={1:{"key":"gs", "col":"0.8"}, 2:{"key":"us", "col":"0.5"}}, **kwargs):
     """ 
         Adding radar data
         dat: dict()-> with "bmnum", "slist" and "v" or other parameter in list of list format
     """
     if len(dat["bmnum"]) == 0: return
     nbeam = np.max(np.max(dat["bmnum"])) + 1
     if self.maxGate: nrange = self.maxGate
     else: nrange = np.max(np.max(dat["slist"])) + 1
     hdw = pydarn.read_hdw_file(self.rad)
     rf = rad_fov.CalcFov(hdw=hdw, ngates=nrange, nbeams=nbeam)
     lons, lats = rf.lonFull, rf.latFull
     
     Xb, Yg, Px = utils.get_gridded_parameters(df, xparam="bmnum", yparam="slist", zparam=zparam)
     lons, lats = lons[Xb.ravel(), Yg.ravel()], lats[Xb.ravel(), Yg.ravel()]
     p_ranges = list(range(p_min, p_max + 1, p_step))
     p_ranges.insert(0, p_lb)
     p_ranges.append(p_ub)       
             
     #Px, Gs = np.zeros((nbeam, nrange))*np.nan, np.zeros((nbeam, nrange))
     #idbs, idgs = dat["bmnum"], dat["slist"]
     #params, gflgs = dat[p_name], dat[gflg_key]
     #for idb, idg, par, gflg in zip(idbs, idgs, params, gflgs):
     #    idb = np.array(idb)[np.array(idg) < nrange]
     #    par = np.array(par)[np.array(idg) < nrange]
     #    gflg = np.array(gflg)[np.array(idg) < nrange]
     #    idg = np.array(idg)[np.array(idg) < nrange]
     #    if len(par) > 0: 
     #        Px[idb, np.round(idg).astype(int)] = par
     #        Gs[idb, np.round(idg).astype(int)] = gflg
     unique = max(gflg_map.keys())
     for uq in range(int(unique) + 1):
         Puq = np.ma.masked_invalid(np.ma.masked_where(np.logical_not(Gs==uq), Px))
         if uq > 0: cmap = matplotlib.colors.ListedColormap([gflg_map[uq]["col"]])
         self.pcolormesh(lons, lats, Puq, transform=tx, cmap=cmap,
                     vmax=p_max, vmin=p_min, **kwargs)
         if add_colorbar:
             if uq==0: self._add_colorbar(p_ranges, cmap, label=colorbar_label)
             else: self._add_key_specific_colorbar(cmap, label=gflg_map[uq]["key"], idh=uq)
     return
Ejemplo n.º 4
0
    def print_fit_record(self):
        """
        Print fit level records
        """
        fname = None
        if self.beams is not None and len(self.beams) > 0:
            fname = self.out_file_dir + "{rad}.{dn}.{start}.{end}.txt".format(
                rad=self.rad,
                dn=self.start_date.strftime("%Y%m%d"),
                start=self.start_date.strftime("%H%M"),
                end=self.end_date.strftime("%H%M"))
            f = open(fname, "w")
            print("\n Working through: ", self.rad)
            hdw = pydarn.read_hdw_file(self.rad)
            fov_obj = rad_fov.CalcFov(hdw=hdw, rsep=self.beams[0].rsep,\
                                      ngates=self.beams[0].nrang, altitude=300.)
            for b in self.beams:
                f.write(b.time.strftime("%Y-%m-%d  "))
                f.write(b.time.strftime("%H:%M:%S  "))
                f.write(self.rad + " ")
                f.write(self.file_type + "\n")
                f.write("bmnum = " + str(b.bmnum))
                f.write("  tfreq = " + str(b.tfreq))
                f.write("  sky_noise_lev = " +
                        str(round(getattr(b, "noise.sky"))))
                f.write("  search_noise_lev = " +
                        str(round(getattr(b, "noise.search"))))
                f.write("  xcf = " + str(getattr(b, "xcf")))
                f.write("  scan = " + str(getattr(b, "scan")) + "\n")
                f.write("npnts = " + str(len(getattr(b, "slist"))))
                f.write("  nrang = " + str(getattr(b, "nrang")))
                f.write("  channel = " + str(getattr(b, "channel")))
                f.write("  cpid = " + str(getattr(b, "cp")) + "\n")

                # Write the table column header
                f.write("{0:>4s} {13:>5s} {1:>5s} / {2:<5s} {3:>8s} {4:>3s} "
                        "{5:>8s} {6:>8s} {7:>8s} {8:>8s} {9:>8s} {10:>8s} "
                        "{11:>8s} {12:>8s}\n".format("gate", "pwr_0", "pwr_l",
                                                     "vel", "gsf", "vel_err",
                                                     "width_l", "geo_lat",
                                                     "geo_lon", "geo_azm",
                                                     "mag_lat", "mag_lon",
                                                     "mag_azm", "range"))

                # Cycle through each range gate identified as having scatter in
                # the slist
                for i, s in enumerate(b.slist):
                    lat_full = fov_obj.latFull[b.bmnum]
                    lon_full = fov_obj.lonFull[b.bmnum]

                    d = geoPack.calcDistPnt(lat_full[s],
                                            lon_full[s],
                                            300,
                                            distLat=lat_full[s + 1],
                                            distLon=lon_full[s + 1],
                                            distAlt=300)
                    gazm = d["az"]
                    # get aacgm_coords
                    mlat, mlon, alt = aacgmv2.convert_latlon(lat_full[s],
                                                             lon_full[s],
                                                             300.,
                                                             b.time,
                                                             method_code="G2A")
                    mlat2, mlon2, alt2 = aacgmv2.convert_latlon(
                        lat_full[s + 1],
                        lon_full[s + 1],
                        300.,
                        b.time,
                        method_code="G2A")
                    d = geoPack.calcDistPnt(mlat,
                                            mlon,
                                            300,
                                            distLat=mlat2,
                                            distLon=mlon2,
                                            distAlt=300)
                    mazm = d["az"]

                    f.write(
                        "{0:4d} {13:5d} {1:>5.1f} / {2:<5.1f} {3:>8.1f} "
                        "{4:>3d} {5:>8.1f} {6:>8.1f} {7:>8.2f} {8:>8.2f} "
                        "{9:>8.2f} {10:>8.2f} {11:>8.2f} {12:>8.2f}\n".format(
                            s,
                            getattr(b, "pwr0")[i],
                            getattr(b, "p_l")[i],
                            getattr(b, "v")[i],
                            getattr(b, "gflg")[i],
                            getattr(b, "v_e")[i],
                            getattr(b, "w_l")[i], lat_full[s], lon_full[s],
                            gazm, mlat, mlon, mazm,
                            getattr(b, "frang") + s * getattr(b, "rsep")))
                f.write("\n")
        f.close()
        return {"fname": fname}
Ejemplo n.º 5
0
def geolocate_radar_fov(rad, time=None):
    """ 
    Geolocate each range cell 
    Input parameters
    ----------------
    rad <str>: Radar code
    time <datetime> (optional): datetime object to calculate magnetic cordinates
    
    Return parameters
    -----------------
    _dict_ {
            beams <list(int)>: Beams
            gates <list(int)>: Gates
            glat [beams, gates] <np.float>: Geogarphic latitude
            glon [beams, gates] <np.float>: Geogarphic longitude
            azm [beams, gates] <np.float>: Geogarphic azimuth of ray-bearing
            mlat [beams, gates] <np.float>: Magnetic latitude
            mlon [beams, gates] <np.float>: Magnetic longitude
            mazm [beams, gates] <np.float>: Magnetic azimuth of ray-bearing
           }
    
    Calling sequence
    ----------------
    from geopos import geolocate_radar_fov
    _dict_ = geolocate_radar_fov("bks")
    """
    logger.info(f"Geolocate radar ({rad}) FoV")
    hdw = pydarn.read_hdw_file(rad)
    fov_obj = rad_fov.CalcFov(hdw=hdw, altitude=300.)
    blen, glen = hdw.beams, hdw.gates
    if glen >= 110: glen = 110
    glat, glon, azm = np.zeros((blen, glen)), np.zeros((blen, glen)), np.zeros(
        (blen, glen))
    mlat, mlon, mazm = np.zeros((blen, glen)) * np.nan, np.zeros(
        (blen, glen)) * np.nan, np.zeros((blen, glen)) * np.nan
    for i, b in enumerate(range(blen)):
        for j, g in enumerate(range(glen)):
            if j < 110:
                glat[i,
                     j], glon[i,
                              j] = fov_obj.latCenter[b,
                                                     g], fov_obj.lonCenter[b,
                                                                           g]
                d = geoPack.calcDistPnt(fov_obj.latFull[b, g],
                                        fov_obj.lonFull[b, g],
                                        300,
                                        distLat=fov_obj.latFull[b, g + 1],
                                        distLon=fov_obj.lonFull[b, g + 1],
                                        distAlt=300)
                azm[i, j] = d["az"]

                if time is not None:
                    mlat[i, j], mlon[i, j], _ = aacgmv2.convert_latlon(
                        fov_obj.latFull[b, g],
                        fov_obj.lonFull[b, g],
                        300.,
                        time,
                        method_code="G2A")
                    mlat2, mlon2, _ = aacgmv2.convert_latlon(
                        fov_obj.latFull[b, g + 1],
                        fov_obj.lonFull[b, g + 1],
                        300.,
                        time,
                        method_code="G2A")
                    d = geoPack.calcDistPnt(mlat[i, j],
                                            mlon[i, j],
                                            300,
                                            distLat=mlat2,
                                            distLon=mlon2,
                                            distAlt=300)
                    mazm[i, j] = d["az"]
    _dict_ = {
        "beams": range(blen),
        "gates": range(glen),
        "glat": glat,
        "glon": glon,
        "azm": azm,
        "mlat": mlat,
        "mlon": mlon,
        "mazm": mazm
    }
    return _dict_