示例#1
0
文件: p90.py 项目: skmichaeldavis/iem
def plotter(fdict):
    """ Go """
    ctx = get_autoplot_context(fdict, get_description())
    # Covert datetime to UTC
    ctx['sdate'] = ctx['sdate'].replace(tzinfo=pytz.utc)
    ctx['edate'] = ctx['edate'].replace(tzinfo=pytz.utc)
    state = ctx['state']
    phenomena = ctx['phenomena']
    significance = ctx['significance']
    station = ctx['station'][:4]
    t = ctx['t']
    ilabel = (ctx['ilabel'] == 'yes')
    geo = ctx['geo']
    nt = NetworkTable("WFO")
    if geo == 'ugc':
        do_ugc(ctx)
    elif geo == 'polygon':
        do_polygon(ctx)

    subtitle = "based on IEM Archives %s" % (ctx.get('subtitle', ''), )
    if t == 'cwa':
        subtitle = "Plotted for %s (%s), %s" % (nt.sts[station]['name'],
                                                station, subtitle)
    else:
        subtitle = "Plotted for %s, %s" % (state_names[state], subtitle)
    m = MapPlot(sector=('state' if t == 'state' else 'cwa'),
                state=state,
                cwa=(station if len(station) == 3 else station[1:]),
                axisbg='white',
                title=('%s %s (%s.%s)') %
                (ctx['title'], vtec.get_ps_string(
                    phenomena, significance), phenomena, significance),
                subtitle=subtitle,
                nocaption=True,
                titlefontsize=16)
    if geo == 'ugc':
        cmap = plt.get_cmap('Paired')
        cmap.set_under('white')
        cmap.set_over('white')
        m.fill_ugcs(ctx['data'], ctx['bins'], cmap=cmap, ilabel=ilabel)
    else:
        cmap = plt.get_cmap('gist_ncar')
        cmap.set_under('white')
        cmap.set_over('black')
        res = m.pcolormesh(ctx['lons'],
                           ctx['lats'],
                           ctx['data'],
                           ctx['bins'],
                           cmap=cmap,
                           units='count')
        # Cut down on SVG et al size
        res.set_rasterized(True)
        if ctx['drawc'] == 'yes':
            m.drawcounties()

    return m.fig, ctx['df']
示例#2
0
def main():
    """Go Main Go."""
    years = 12.0  # 2008 - 2019
    pgconn = get_dbconn("idep")
    postgis = get_dbconn("postgis")

    # Get the initial geometries
    df = read_postgis(
        """
        SELECT ugc, name, geom from ugcs WHERE end_ts is null and
        substr(ugc, 1, 3) = 'IAC'
        """,
        postgis,
        index_col="ugc",
        crs="EPSG:4326",
    )
    scenario = 0
    df2 = read_sql(
        """WITH data as (
    SELECT r.huc_12,
    sum(avg_loss) * 4.163 / %s as detach,
    sum(avg_delivery) * 4.163 / %s as delivery,
    sum(avg_runoff) / 25.4 / %s as runoff
    from results_by_huc12 r
    , huc12 h WHERE r.huc_12 = h.huc_12 and h.states ~* 'IA'
    and r.scenario = %s and h.scenario = 0 and r.valid < '2020-01-01'
    and r.valid > '2008-01-01'
    GROUP by r.huc_12)

    SELECT ugc, avg(detach) as detach, avg(delivery) as delivery,
    avg(runoff) as runoff from data d JOIN huc12 h on (d.huc_12 = h.huc_12)
    WHERE h.scenario = 0 GROUP by ugc ORDER by delivery desc
    """,
        pgconn,
        params=(years, years, years, scenario),
        index_col="ugc",
    )
    newcols = {
        "detach": "det%s" % (0, ),
        "delivery": "del%s" % (0, ),
        "runoff": "run%s" % (0, ),
    }
    for key, val in newcols.items():
        df[val] = df2[key]
    df = df.sort_values("del0", ascending=False)
    print(df.head(10))

    mp = MapPlot(title="2008-2019 DEP Top 10 Erosive Counties",
                 logo="dep",
                 caption="")
    df2 = df.head(10)
    mp.fill_ugcs(df2["del0"].to_dict())
    mp.postprocess(filename="test.png")
示例#3
0
def plotter(fdict):
    """ Go """
    ctx = get_autoplot_context(fdict, get_description())
    # Covert datetime to UTC
    ctx["sdate"] = ctx["sdate"].replace(tzinfo=pytz.utc)
    ctx["edate"] = ctx["edate"].replace(tzinfo=pytz.utc)
    state = ctx["state"]
    phenomena = ctx["phenomena"]
    significance = ctx["significance"]
    station = ctx["station"][:4]
    t = ctx["t"]
    ilabel = ctx["ilabel"] == "yes"
    geo = ctx["geo"]
    if geo == "ugc":
        do_ugc(ctx)
    elif geo == "polygon":
        do_polygon(ctx)

    subtitle = "based on IEM Archives %s" % (ctx.get("subtitle", ""), )
    if t == "cwa":
        subtitle = "Plotted for %s (%s), %s" % (
            ctx["_nt"].sts[station]["name"],
            station,
            subtitle,
        )
    else:
        subtitle = "Plotted for %s, %s" % (state_names[state], subtitle)
    m = MapPlot(
        sector=("state" if t == "state" else "cwa"),
        state=state,
        cwa=(station if len(station) == 3 else station[1:]),
        axisbg="white",
        title=("%s %s (%s.%s)") % (
            ctx["title"],
            vtec.get_ps_string(phenomena, significance),
            phenomena,
            significance,
        ),
        subtitle=subtitle,
        nocaption=True,
        titlefontsize=16,
    )
    cmap = plt.get_cmap(ctx["cmap"])
    cmap.set_under("white")
    cmap.set_over("white")
    if geo == "ugc":
        m.fill_ugcs(ctx["data"], ctx["bins"], cmap=cmap, ilabel=ilabel)
    else:
        res = m.pcolormesh(
            ctx["lons"],
            ctx["lats"],
            ctx["data"],
            ctx["bins"],
            cmap=cmap,
            units="count",
        )
        # Cut down on SVG et al size
        res.set_rasterized(True)
        if ctx["drawc"] == "yes":
            m.drawcounties()

    return m.fig, ctx["df"]
示例#4
0
def plotter(fdict):
    """ Go """
    pgconn = get_dbconn("postgis")
    ctx = get_autoplot_context(fdict, get_description())
    utcvalid = ctx.get("valid")
    wfo = ctx["wfo"]
    tzname = ctx["_nt"].sts[wfo]["tzname"]
    p1 = ctx["phenomenav"][:2]
    s1 = ctx["significancev"][:1]
    etn = int(ctx["etn"])
    year = int(ctx["year"])

    table = "warnings_%s" % (year, )
    df = read_postgis(
        """
        SELECT w.ugc, simple_geom, u.name,
        issue at time zone 'UTC' as issue,
        expire at time zone 'UTC' as expire,
        init_expire at time zone 'UTC' as init_expire,
        1 as val,
        status
        from """ + table + """ w JOIN ugcs u on (w.gid = u.gid)
        WHERE w.wfo = %s and eventid = %s and significance = %s and
        phenomena = %s ORDER by issue ASC
    """,
        pgconn,
        params=(wfo[-3:], etn, s1, p1),
        index_col="ugc",
        geom_col="simple_geom",
    )
    if df.empty:
        raise NoDataFound("VTEC Event was not found, sorry.")
    table = "sbw_%s" % (year, )
    sbwdf = read_postgis(
        """
        SELECT status, geom,
        polygon_begin at time zone 'UTC' as polygon_begin,
        polygon_end at time zone 'UTC' as polygon_end
        from """ + table + """
        WHERE wfo = %s and eventid = %s and significance = %s and
        phenomena = %s ORDER by polygon_begin ASC
    """,
        pgconn,
        params=(wfo[-3:], etn, s1, p1),
        geom_col="geom",
    )

    if utcvalid is None:
        utcvalid = df["issue"].max()
    else:
        # hack for an assumption below
        utcvalid = pd.Timestamp(utcvalid.replace(tzinfo=None))

    def m(valid):
        """Convert to our local timestamp."""
        return (valid.tz_localize(pytz.UTC).astimezone(
            pytz.timezone(tzname)).strftime(TFORMAT))

    df["color"] = vtec.NWS_COLORS.get("%s.%s" % (p1, s1), "#FF0000")
    if not sbwdf.empty:
        df["color"] = "tan"
    bounds = df["simple_geom"].total_bounds
    buffer = 0.4
    mp = MapPlot(
        subtitle="Map Valid: %s, Event: %s to %s" %
        (m(utcvalid), m(df["issue"].min()), m(df["expire"].max())),
        title="%s %s %s %s (%s.%s) #%s" % (
            year,
            wfo,
            vtec.VTEC_PHENOMENA.get(p1, p1),
            vtec.VTEC_SIGNIFICANCE.get(s1, s1),
            p1,
            s1,
            etn,
        ),
        sector="custom",
        west=bounds[0] - buffer,
        south=bounds[1] - buffer,
        east=bounds[2] + buffer,
        north=bounds[3] + buffer,
        nocaption=True,
    )
    mp.sector = "cwa"
    mp.cwa = wfo[-3:]
    # CAN statements come here with time == expire :/
    df2 = df[(df["issue"] <= utcvalid) & (df["expire"] > utcvalid)]
    if df2.empty:
        mp.ax.text(
            0.5,
            0.5,
            "Event No Longer Active",
            zorder=1000,
            transform=mp.ax.transAxes,
            fontsize=24,
            ha="center",
        )
    else:
        mp.fill_ugcs(
            df2["val"].to_dict(),
            color=df2["color"].to_dict(),
            nocbar=True,
            labels=df2["name"].to_dict(),
            missingval="",
            ilabel=(len(df2.index) <= 10),
            labelbuffer=5,
        )
    if not sbwdf.empty:
        color = vtec.NWS_COLORS.get("%s.%s" % (p1, s1), "#FF0000")
        poly = sbwdf.iloc[0]["geom"]
        df2 = sbwdf[(sbwdf["polygon_begin"] <= utcvalid)
                    & (sbwdf["polygon_end"] > utcvalid)]
        if not df2.empty:
            # draw new
            mp.ax.add_geometries(
                [poly],
                ccrs.PlateCarree(),
                facecolor="None",
                edgecolor="k",
                zorder=Z_OVERLAY2 - 1,
            )
            poly = df2.iloc[0]["geom"]
        mp.ax.add_geometries(
            [poly],
            ccrs.PlateCarree(),
            facecolor=color,
            alpha=0.5,
            edgecolor="k",
            zorder=Z_OVERLAY2,
        )
    if len(df.index) > 10:
        mp.drawcities()
    return mp.fig, df.drop("simple_geom", axis=1)