示例#1
0
文件: huc12_map.py 项目: geogismx/dep
def main():
    """GO!"""
    pgconn = get_dbconn('idep')
    cursor = pgconn.cursor()

    scenario = int(sys.argv[1])
    mp = MapPlot(sector='iowa', axisbg='white', nologo=True,
                 subtitle='1 Jan 2014 thru 31 Dec 2014',
                 caption='Daily Erosion Project',
                 title=('Harvest Index 0.8 Change in 2014 Soil Delivery '
                        'from Baseline'))

    cursor.execute("""
    with baseline as (
        SELECT huc_12, sum(avg_delivery) * 4.463 as loss from results_by_huc12
        where valid between '2014-01-01' and '2015-01-01' and
        scenario = 0 GROUP by huc_12),
    scenario as (
        SELECT huc_12, sum(avg_delivery) * 4.463 as loss from results_by_huc12
        where valid between '2014-01-01' and '2015-01-01' and
        scenario = %s GROUP by huc_12),
    agg as (
        SELECT b.huc_12, b.loss as baseline_loss, s.loss as scenario_loss from
        baseline b LEFT JOIN scenario s on (b.huc_12 = s.huc_12))

     SELECT ST_Transform(simple_geom, 4326),
     (scenario_loss  - baseline_loss) / 1.0 as val, i.huc_12
     from huc12 i JOIN agg d on (d.huc_12 = i.huc_12)
     WHERE i.states ~* 'IA' ORDER by val DESC

    """, (scenario, ))

    # bins = np.arange(0, 101, 10)
    bins = [-5, -2, -1, -0.5, 0, 0.5, 1, 2, 5]
    cmap = plt.get_cmap("BrBG_r")
    cmap.set_under('purple')
    cmap.set_over('black')
    norm = mpcolors.BoundaryNorm(bins, cmap.N)

    for row in cursor:
        # print "%s,%s" % (row[2], row[1])
        polygon = loads(row[0].decode('hex'))
        arr = np.asarray(polygon.exterior)
        points = mp.ax.projection.transform_points(ccrs.Geodetic(),
                                                   arr[:, 0], arr[:, 1])
        val = float(row[1])
        # We have very small negative numbers that should just be near a
        # positive zero
        if val < 0 and val > -0.1:
            val = 0.001
        color = cmap(norm([val, ]))[0]
        poly = Polygon(points[:, :2], fc=color, ec='k', zorder=2, lw=0.1)
        mp.ax.add_patch(poly)

    mp.draw_colorbar(bins, cmap, norm, units='T/a/yr')

    mp.drawcounties()
    mp.postprocess(filename='test.png')
示例#2
0
def test_colorbar():
    """Run tests against the colorbar algorithm"""
    mp = MapPlot(sector='iowa', nocaption=True)
    cmap = plot.maue()
    cmap.set_under('white')
    clevs = list(range(0, 101, 10))
    norm = mpcolors.BoundaryNorm(clevs, cmap.N)
    mp.drawcities()
    mp.draw_colorbar(clevs, cmap, norm)
    return mp.fig
示例#3
0
def main(argv):
    """Do Great Things"""
    year = int(argv[1])
    pgconn = psycopg2.connect(database='idep',
                              host='localhost',
                              port=5555,
                              user='******')
    cursor = pgconn.cursor()

    mp = MapPlot(continentalcolor='white',
                 nologo=True,
                 sector='custom',
                 south=36.8,
                 north=45.0,
                 west=-99.2,
                 east=-88.9,
                 subtitle='Assumes 56 lb test weight',
                 title=('%s Corn Yield HUC12 Average') % (year, ))

    cursor.execute(
        """
    with hucs as (
        select huc_12, ST_Transform(simple_geom, 4326) as geo
        from huc12),
    data as (
        SELECT huc12, avg(yield_kgm2) * 8921.8 / 56. as val from harvest
        where crop = 'Corn' and valid between %s and %s
        GROUP by huc12
    )

    SELECT geo, huc12, val from hucs h JOIN data d on (h.huc_12 = d.huc12)
    """, (datetime.date(year, 1, 1), datetime.date(year, 12, 31)))

    bins = np.arange(0, 310, 30)
    cmap = nwsprecip()
    cmap.set_under('white')
    cmap.set_over('black')
    norm = mpcolors.BoundaryNorm(bins, cmap.N)

    for row in cursor:
        polygon = loads(row[0].decode('hex'))
        arr = np.asarray(polygon.exterior)
        points = mp.ax.projection.transform_points(ccrs.Geodetic(), arr[:, 0],
                                                   arr[:, 1])
        color = cmap(norm([
            float(row[2]),
        ]))[0]
        poly = Polygon(points[:, :2], fc=color, ec='None', zorder=2, lw=.1)
        mp.ax.add_patch(poly)

    mp.draw_colorbar(bins, cmap, norm, units='bu/acre')

    # mp.drawcounties()
    mp.postprocess(filename='test.png')
示例#4
0
def test_colorbar3():
    """draw another colorbar"""
    mp = MapPlot(sector='iowa', nocaption=True)
    cmap = plot.maue()
    cmap.set_over('black')
    clevs = [0, 100, 250, 500, 1000, 2000, 20000]
    norm = mpcolors.BoundaryNorm(clevs, cmap.N)
    mp.draw_colorbar(
        clevs, cmap, norm, title="Erosion $kg/m^2$", spacing='uniform'
    )
    return mp.fig
示例#5
0
def test_colorbar2():
    """draw a colorbar"""
    mp = MapPlot(sector='iowa', nocaption=True)
    cmap = plot.maue()
    clevs = list(range(0, 101, 10))
    clevlabels = ["One", "Three", "Blahh", "Longest", "Five",
                  "Six", "Ten", "Fourty", 100000, "Hi\nHo", 100]
    norm = mpcolors.BoundaryNorm(clevs, cmap.N)
    mp.draw_colorbar(
        clevs, cmap, norm, clevlabels=clevlabels
    )
    return mp.fig
示例#6
0
def main():
    pgconn = psycopg2.connect(database='idep')
    cursor = pgconn.cursor()

    mp = MapPlot(continentalcolor='white',
                 nologo=True,
                 sector='custom',
                 south=36.8,
                 north=45.0,
                 west=-99.2,
                 east=-88.9,
                 title=("HUC12 Frequency of Flowpaths with 1+ segment with "
                        "'T' management"))

    cursor.execute("""
    with data as (
        select distinct flowpath from flowpath_points
        where (lu2007 || lu2008 || lu2009 || lu2010 || lu2011 || lu2012
        || lu2013 || lu2014 || lu2015 || lu2016 || lu2017) ~* 'T'
        and scenario = 0),
    agg as (select huc_12, count(*) from flowpaths f JOIn data d
    on (f.fid = d.flowpath) GROUP by huc_12)

    SELECT ST_Transform(geom, 4326), h.huc_12,
    coalesce(a.count, 0) from huc12 h
    LEFT JOIN agg a on (h.huc_12 = a.huc_12) WHERE h.scenario = 0
    ORDER by count DESC
    """)

    bins = np.arange(1, 45, 4)
    cmap = james2()
    cmap.set_under('tan')
    cmap.set_over('black')
    norm = mpcolors.BoundaryNorm(bins, cmap.N)
    for row in cursor:
        if row[2] > 30:
            print("%s %s" % (row[1], row[2]))
        multipoly = loads(row[0].decode('hex'))
        for polygon in multipoly:
            arr = np.asarray(polygon.exterior)
            points = mp.ax.projection.transform_points(ccrs.Geodetic(),
                                                       arr[:, 0], arr[:, 1])
            color = cmap(norm([
                float(row[2]),
            ]))[0]
            poly = Polygon(points[:, :2], fc=color, ec='None', zorder=2, lw=.1)
            mp.ax.add_patch(poly)

    mp.draw_colorbar(bins, cmap, norm, units='count')

    mp.drawcounties()
    mp.postprocess(filename='test.png')
示例#7
0
def main():
    pgconn = get_dbconn('idep')
    cursor = pgconn.cursor()

    mp = MapPlot(continentalcolor='white', nologo=True, # sector='custom',
                 # south=36.8, north=45.0, west=-99.2, east=-88.9,
                 caption='Daily Erosion Project',
                 subtitle='HUC12 Areal Averaged',
                 title=("Est. Hillslope Soil Loss between 12 April "
                        "2008 and 12 June 2008 (inclusive)"))

    cursor.execute("""
    with agg as (
        select huc_12, sum(avg_delivery) * 4.463 as runoff from results_by_huc12
        WHERE valid >= '2008-04-12' and valid <= '2008-06-12' and scenario = 0
        GROUP by huc_12)

    SELECT ST_Transform(geom, 4326), h.huc_12,
    coalesce(a.runoff, 0) as runoff from huc12 h
    LEFT JOIN agg a on (h.huc_12 = a.huc_12) WHERE h.scenario = 0
    and h.states ~* 'IA'
    ORDER by runoff DESC
    """)

    #bins = np.arange(0, 26, 2)
    bins = [0.05, 0.25, 0.5, 1, 1.5, 2, 3, 5, 7, 10, 15, 20]
    cmap = plt.get_cmap("plasma_r")
    cmap.set_under('white')
    cmap.set_over('black')
    norm = mpcolors.BoundaryNorm(bins, cmap.N)
    for row in cursor:
        # val = distance(row[2], 'MM').value('IN')
        val = row[2]
        if val > 30:
            print("%s %s" % (row[1], val))
        multipoly = loads(row[0].decode('hex'))
        for polygon in multipoly:
            arr = np.asarray(polygon.exterior)
            points = mp.ax.projection.transform_points(ccrs.Geodetic(),
                                                       arr[:, 0], arr[:, 1])
            color = cmap(norm([val, ]))[0]
            poly = Polygon(points[:, :2], fc=color, ec='None', zorder=2, lw=.1)
            mp.ax.add_patch(poly)

    mp.draw_colorbar(bins, cmap, norm, units='tons/acre')

    mp.drawcounties()
    plt.savefig('test.pdf')
示例#8
0
def test_issue98_labelbar():
    """Sometimes our label bar sucks."""
    mp = MapPlot(
        title='Proportional Colorbar with some rotation',
        sector='iowa', nocaption=True)
    cmap = plot.maue()
    cmap.set_under('white')
    cmap.set_over('black')
    clevs = np.arange(0, 1., 0.1)
    clevs[-1] = 3.987654
    norm = mpcolors.BoundaryNorm(clevs, cmap.N)
    mp.plot_values(
        [-94, -92, -91, -92], [42, 41, 43, 42.4],
        ['0.5', '0.25', '1.0', '5.0'], color=cmap(norm([0.5, 0.25, 1.0, 5.0])),
        showmarker=True
    )
    mp.draw_colorbar(clevs, cmap, norm, spacing='proportional')
    return mp.fig
示例#9
0
def main(argv):
    """Do Great Things"""
    pgconn = get_dbconn('idep')
    cursor = pgconn.cursor()

    mp = MapPlot(
        continentalcolor='#EEEEEE',
        nologo=True,
        # sector='custom',
        # south=36.8, north=45.0, west=-99.2, east=-88.9,
        subtitle='',
        title=('DEP MLRA identifier assignment using HUC12 Centroid'))

    cursor.execute("""
    select st_transform(geom, 4326), mlra_id from huc12 where scenario = 0
    """)

    bins = [
        106, 107, 108, 109, 121, 137, 150, 155, 166, 175, 176, 177, 178, 179,
        181, 182, 186, 187, 188, 196, 197, 204, 205
    ]
    cmap = plt.get_cmap('terrain')
    cmap.set_under('white')
    cmap.set_over('black')
    norm = mpcolors.BoundaryNorm(bins, cmap.N)

    for row in cursor:
        for polygon in loads(row[0].decode('hex')):
            arr = np.asarray(polygon.exterior)
            points = mp.ax.projection.transform_points(ccrs.Geodetic(),
                                                       arr[:, 0], arr[:, 1])
            color = cmap(norm([
                float(row[1]),
            ]))[0]
            poly = Polygon(points[:, :2], fc=color, ec='None', zorder=2, lw=.1)
            mp.ax.add_patch(poly)

    mp.draw_colorbar(bins, cmap, norm, units='MLRA ID')

    # mp.drawcounties()
    mp.postprocess(filename='test.png')
示例#10
0
def main(argv):
    """Go Main Go"""
    v = argv[1]
    agg = argv[2]
    ts = datetime.date(2008, 1, 1)
    ts2 = datetime.date(2017, 12, 31)
    scenario = 0

    # suggested for runoff and precip
    if V2UNITS[v] in ['mm', 'inches']:
        colors = ['#ffffa6', '#9cf26d', '#76cc94', '#6399ba', '#5558a1']
    # suggested for detachment
    elif v in ['avg_loss', 'avg_loss_metric']:
        colors = ['#cbe3bb', '#c4ff4d', '#ffff4d', '#ffc44d', '#ff4d4d',
                  '#c34dee']
    # suggested for delivery
    elif v in ['avg_delivery', 'avg_delivery_metric']:
        colors = ['#ffffd2', '#ffff4d', '#ffe0a5', '#eeb74d', '#ba7c57',
                  '#96504d']
    cmap = mpcolors.ListedColormap(colors, 'james')
    cmap.set_under('white')
    cmap.set_over('black')

    pgconn = get_dbconn('idep')

    title = "for %s" % (ts.strftime("%-d %B %Y"),)
    if ts != ts2:
        title = "between %s and %s" % (ts.strftime("%-d %b %Y"),
                                       ts2.strftime("%-d %b %Y"))
    mp = MapPlot(axisbg='#EEEEEE', nologo=True, sector='iowa',
                 nocaption=True,
                 title=("DEP %s %s %s"
                        ) % (V2NAME[v.replace("_metric", "")],
                             "Yearly Average" if agg == 'avg' else 'Total',
                             title),
                 caption='Daily Erosion Project')

    df = read_postgis("""
    WITH data as (
      SELECT huc_12, extract(year from valid) as yr,
      sum(""" + v.replace("_metric", "") + """)  as d from results_by_huc12
      WHERE scenario = %s and valid >= %s and valid <= %s
      GROUP by huc_12, yr),

    agg as (
      SELECT huc_12, """ + agg + """(d) as d from data GROUP by huc_12)

    SELECT ST_Transform(simple_geom, 4326) as geo, coalesce(d.d, 0) as data
    from huc12 i LEFT JOIN agg d
    ON (i.huc_12 = d.huc_12) WHERE i.scenario = %s and i.states ~* 'IA'
    """, pgconn, params=(scenario, ts, ts2, scenario), geom_col='geo',
                      index_col=None)
    df['data'] = df['data'] * V2MULTI[v]
    if df['data'].max() < 0.01:
        bins = [0.01, 0.02, 0.03, 0.04, 0.05]
    else:
        bins = np.array(V2RAMP[v]) * (10. if agg == 'sum' else 1.)
    norm = mpcolors.BoundaryNorm(bins, cmap.N)

    # m.ax.add_geometries(df['geo'], ccrs.PlateCarree())
    for _, row in df.iterrows():
        c = cmap(norm([row['data'], ]))[0]
        arr = np.asarray(row['geo'].exterior)
        points = mp.ax.projection.transform_points(ccrs.Geodetic(),
                                                   arr[:, 0], arr[:, 1])
        p = Polygon(points[:, :2], fc=c, ec='k', zorder=2, lw=0.1)
        mp.ax.add_patch(p)

    mp.drawcounties()
    mp.drawcities()
    lbl = [round(_, 2) for _ in bins]
    u = "%s, Avg: %.2f" % (V2UNITS[v], df['data'].mean())
    mp.draw_colorbar(bins, cmap, norm,
                     clevlabels=lbl, units=u,
                     title="%s :: %s" % (V2NAME[v], V2UNITS[v]))
    plt.savefig('%s_%s_%s%s.png' % (ts.year, ts2.year, v,
                                    "_sum" if agg == 'sum' else ''))
示例#11
0
if df["data"].max() < 0.01:
    bins = [0.01, 0.02, 0.03, 0.04, 0.05]
else:
    bins = V2RAMP[v]
norm = mpcolors.BoundaryNorm(bins, cmap.N)

patches = []
# m.ax.add_geometries(df['geo'], ccrs.PlateCarree())
for i, row in df.iterrows():
    c = cmap(norm([row["data"]]))[0]
    arr = np.asarray(row["geo"].exterior)
    points = m.ax.projection.transform_points(
        ccrs.Geodetic(), arr[:, 0], arr[:, 1]
    )
    p = Polygon(points[:, :2], fc=c, ec="k", zorder=2, lw=0.1)
    m.ax.add_patch(p)

# m.ax.add_collection(PatchCollection(patches, match_original=True))
m.drawcounties()
m.drawcities()
lbl = [round(_, 2) for _ in bins]
u = "%s, Avg: %.2f" % (V2UNITS[v], df["data"].mean())
m.draw_colorbar(
    bins,
    cmap,
    norm,
    clevlabels=lbl,
    title="%s :: %s" % (V2NAME[v], V2UNITS[v]),
)
plt.savefig("%s_%s.png" % (year, v))
示例#12
0
#cmap = cm.get_cmap('BrBG')
#cmap.set_under('orange')
#cmap.set_over('black')
cmap = james()
cmap.set_under('white')
cmap.set_over('black')
norm = mpcolors.BoundaryNorm(bins, cmap.N)
patches = []
for row in cursor:
    #print "%s,%s" % (row[2], row[1])
    geom = loads(row[0].decode('hex'))
    for polygon in geom:
        a = np.asarray(polygon.exterior)
        x, y = m.map(a[:, 0], a[:, 1])
        a = zip(x, y)
        #c = cmap( norm([float(row[1]),]) )[0]
        diff = data.get(row[1], 0) - data1.get(row[1], 0)
        print '%10s 1:%5.2f 2:%5.2f' % (row[1], data1.get(
            row[1], 0), data.get(row[1], 0))
        diff = data.get(row[1], 0)
        c = cmap(norm([
            float(diff),
        ]))[0]
        p = Polygon(a, fc=c, ec='None', zorder=2, lw=.1)
        patches.append(p)

m.ax.add_collection(PatchCollection(patches, match_original=True))
m.draw_colorbar(bins, cmap, norm, units='%')

m.drawcounties()
m.postprocess(filename='test.png')
示例#13
0
from huc12 i LEFT JOIN data d
ON (i.huc_12 = d.huc_12) WHERE i.scenario = %s and i.states ~* 'IA'
""", pgconn, params=(scenario, ts, ts2, scenario), geom_col='geo',
                  index_col=None)
df['data'] = df['data'] * V2MULTI[v]
if df['data'].max() < 0.01:
    bins = [0.01, 0.02, 0.03, 0.04, 0.05]
else:
    bins = V2RAMP[v]
norm = mpcolors.BoundaryNorm(bins, cmap.N)

patches = []
#m.ax.add_geometries(df['geo'], ccrs.PlateCarree())
for i, row in df.iterrows():
    c = cmap(norm([row['data'], ]))[0]
    arr = np.asarray(row['geo'].exterior)
    points = m.ax.projection.transform_points(ccrs.Geodetic(),
                                              arr[:, 0], arr[:, 1])
    p = Polygon(points[:, :2], fc=c, ec='k', zorder=2, lw=0.1)
    m.ax.add_patch(p)

#print len(patches)
#m.ax.add_collection(PatchCollection(patches, match_original=True))
m.drawcounties()
m.drawcities()
lbl = [round(_, 2) for _ in bins]
u = "%s, Avg: %.2f" % (V2UNITS[v], df['data'].mean())
m.draw_colorbar(bins, cmap, norm,
                clevlabels=lbl, title="%s :: %s" % (V2NAME[v], V2UNITS[v]))
plt.savefig('%s_%s.png' % (year, v))
    JOIN hrap_polygons p on (p.hrap_i = foo.hrap_i)

    --- select ST_Transform(the_geom,4326), total from 
    ---
    ---(SELECT model_twp, sum(avg_loss) * 4.463 as total from results_by_twp WHERE
    ---valid between '%s-01-01' and '%s-01-01' GROUP by model_twp) as foo
    ---
    ---JOIN iatwp t on (t.model_twp = foo.model_twp) ORDER by total DESC
    """ % (yr, yr, yr+1))

bins = np.array([0,0.1,0.5,0.75,1,2,3,4,5,7,10,15,20,25])
bins = np.arange(0,6.1,0.5)
cmap = cm.get_cmap('jet') #james2()
norm = mpcolors.BoundaryNorm(bins, cmap.N)
patches = []
for row in cursor:
    geom = loads( row[0].decode('hex') )
    for polygon in geom:
        a = np.asarray(polygon.exterior)
        x,y = m.map(a[:,0], a[:,1])
        a = zip(x,y)
        c = cmap( norm([float(row[1]),]) )[0]
        p = Polygon(a,fc=c,ec='None',zorder=2, lw=.1)
        patches.append(p)

          
m.ax.add_collection(PatchCollection(patches,match_original=True))
m.draw_colorbar(bins, cmap, norm, units='inches per hour')

m.drawcounties()
m.postprocess(filename='%srainfall.png' % (yr,))
示例#15
0
def main(argv):
    """Go Main Go"""
    v = argv[1]
    agg = argv[2]
    ts = datetime.date(2008, 1, 1)
    ts2 = datetime.date(2016, 12, 31)
    scenario = 0

    # suggested for runoff and precip
    if v in ['qc_precip', 'avg_runoff']:
        colors = ['#ffffa6', '#9cf26d', '#76cc94', '#6399ba', '#5558a1']
    # suggested for detachment
    elif v in ['avg_loss']:
        colors = ['#cbe3bb', '#c4ff4d', '#ffff4d', '#ffc44d', '#ff4d4d',
                  '#c34dee']
    # suggested for delivery
    elif v in ['avg_delivery']:
        colors = ['#ffffd2', '#ffff4d', '#ffe0a5', '#eeb74d', '#ba7c57',
                  '#96504d']
    cmap = mpcolors.ListedColormap(colors, 'james')
    cmap.set_under('white')
    cmap.set_over('black')

    pgconn = psycopg2.connect(database='idep', host='localhost', port=5555,
                              user='******')

    title = "for %s" % (ts.strftime("%-d %B %Y"),)
    if ts != ts2:
        title = "between %s and %s" % (ts.strftime("%-d %b %Y"),
                                       ts2.strftime("%-d %b %Y"))
    mp = MapPlot(axisbg='#EEEEEE', nologo=True, sector='iowa',
                 nocaption=True,
                 title=("DEP %s %s %s"
                        ) % (V2NAME[v],
                             "Yearly Average" if agg == 'avg' else 'Total',
                             title),
                 caption='Daily Erosion Project')

    df = read_postgis("""
    WITH data as (
      SELECT huc_12, extract(year from valid) as yr,
      sum("""+v+""")  as d from results_by_huc12
      WHERE scenario = %s and valid >= %s and valid <= %s
      GROUP by huc_12, yr),

    agg as (
      SELECT huc_12, """ + agg + """(d) as d from data GROUP by huc_12)

    SELECT ST_Transform(simple_geom, 4326) as geo, coalesce(d.d, 0) as data
    from huc12 i LEFT JOIN agg d
    ON (i.huc_12 = d.huc_12) WHERE i.scenario = %s and i.states ~* 'IA'
    """, pgconn, params=(scenario, ts, ts2, scenario), geom_col='geo',
                      index_col=None)
    df['data'] = df['data'] * V2MULTI[v]
    if df['data'].max() < 0.01:
        bins = [0.01, 0.02, 0.03, 0.04, 0.05]
    else:
        bins = np.array(V2RAMP[v]) * (10. if agg == 'sum' else 1.)
    norm = mpcolors.BoundaryNorm(bins, cmap.N)

    # m.ax.add_geometries(df['geo'], ccrs.PlateCarree())
    for _, row in df.iterrows():
        c = cmap(norm([row['data'], ]))[0]
        arr = np.asarray(row['geo'].exterior)
        points = mp.ax.projection.transform_points(ccrs.Geodetic(),
                                                   arr[:, 0], arr[:, 1])
        p = Polygon(points[:, :2], fc=c, ec='k', zorder=2, lw=0.1)
        mp.ax.add_patch(p)

    mp.drawcounties()
    mp.drawcities()
    lbl = [round(_, 2) for _ in bins]
    u = "%s, Avg: %.2f" % (V2UNITS[v], df['data'].mean())
    mp.draw_colorbar(bins, cmap, norm,
                     clevlabels=lbl, units=u,
                     title="%s :: %s" % (V2NAME[v], V2UNITS[v]))
    plt.savefig('%s_%s_%s%s.eps' % (ts.year, ts2.year, v,
                                    "_sum" if agg == 'sum' else ''))
示例#16
0
文件: huc12_map.py 项目: akrherz/idep
 SELECT ST_Transform(simple_geom, 4326),
 (scenario_loss  - baseline_loss) / 8.0 as val, i.huc_12
 from huc12 i JOIN agg d on (d.huc_12 = i.huc_12)
 WHERE i.states ~* 'IA' ORDER by val DESC

""", (scenario, ))

# bins = np.arange(0, 101, 10)
bins = [-25, -10, -5, -2, 0, 2, 5, 10, 25]
cmap = plt.get_cmap("BrBG_r")
cmap.set_under('purple')
cmap.set_over('black')
norm = mpcolors.BoundaryNorm(bins, cmap.N)
patches = []

for row in cursor:
    # print "%s,%s" % (row[2], row[1])
    polygon = loads(row[0].decode('hex'))
    a = np.asarray(polygon.exterior)
    x, y = m.map(a[:, 0], a[:, 1])
    a = zip(x, y)
    c = cmap(norm([float(row[1]), ]))[0]
    p = Polygon(a, fc=c, ec='None', zorder=2, lw=.1)
    patches.append(p)

m.ax.add_collection(PatchCollection(patches, match_original=True))
m.draw_colorbar(bins, cmap, norm, units='T/a')

m.drawcounties()
m.postprocess(filename='test.png')
示例#17
0
""")

bins = np.arange(0, 18, 2)
# cmap = cm.get_cmap('BrBG')
# cmap.set_under('orange')
# cmap.set_over('black')
cmap = james()
cmap.set_under("white")
cmap.set_over("black")
norm = mpcolors.BoundaryNorm(bins, cmap.N)
patches = []
for row in cursor:
    geom = loads(row[0].decode("hex"))
    for polygon in geom:
        a = np.asarray(polygon.exterior)
        x, y = m.map(a[:, 0], a[:, 1])
        a = zip(x, y)
        # c = cmap( norm([float(row[1]),]) )[0]
        diff = data.get(row[1], 0) - data1.get(row[1], 0)
        diff = data.get(row[1], 0)
        c = cmap(norm([float(diff)]))[0]
        p = Polygon(a, fc=c, ec="None", zorder=2, lw=0.1)
        patches.append(p)

m.ax.add_collection(PatchCollection(patches, match_original=True))
m.draw_colorbar(bins, cmap, norm, units="%")

m.drawcounties()
m.postprocess(filename="test.png")
示例#18
0
def main(argv):
    """Go Main Go"""
    v = argv[1]
    agg = argv[2]
    ts = datetime.date(2008, 1, 1)
    ts2 = datetime.date(2017, 12, 31)
    scenario = 0

    # suggested for runoff and precip
    if V2UNITS[v] in ["mm", "inches"]:
        colors = ["#ffffa6", "#9cf26d", "#76cc94", "#6399ba", "#5558a1"]
    # suggested for detachment
    elif v in ["avg_loss", "avg_loss_metric"]:
        colors = [
            "#cbe3bb",
            "#c4ff4d",
            "#ffff4d",
            "#ffc44d",
            "#ff4d4d",
            "#c34dee",
        ]
    # suggested for delivery
    elif v in ["avg_delivery", "avg_delivery_metric"]:
        colors = [
            "#ffffd2",
            "#ffff4d",
            "#ffe0a5",
            "#eeb74d",
            "#ba7c57",
            "#96504d",
        ]
    cmap = mpcolors.ListedColormap(colors, "james")
    cmap.set_under("white")
    cmap.set_over("black")

    pgconn = get_dbconn("idep")

    title = "for %s" % (ts.strftime("%-d %B %Y"), )
    if ts != ts2:
        title = "between %s and %s" % (
            ts.strftime("%-d %b %Y"),
            ts2.strftime("%-d %b %Y"),
        )
    mp = MapPlot(
        axisbg="#EEEEEE",
        nologo=True,
        sector="iowa",
        nocaption=True,
        title=("DEP %s %s %s") % (
            V2NAME[v.replace("_metric", "")],
            "Yearly Average" if agg == "avg" else "Total",
            title,
        ),
        caption="Daily Erosion Project",
    )

    df = read_postgis(
        """
    WITH data as (
      SELECT huc_12, extract(year from valid) as yr,
      sum(""" + v.replace("_metric", "") + """)  as d from results_by_huc12
      WHERE scenario = %s and valid >= %s and valid <= %s
      GROUP by huc_12, yr),

    agg as (
      SELECT huc_12, """ + agg + """(d) as d from data GROUP by huc_12)

    SELECT ST_Transform(simple_geom, 4326) as geo, coalesce(d.d, 0) as data
    from huc12 i LEFT JOIN agg d
    ON (i.huc_12 = d.huc_12) WHERE i.scenario = %s and i.states ~* 'IA'
    """,
        pgconn,
        params=(scenario, ts, ts2, scenario),
        geom_col="geo",
        index_col=None,
    )
    df["data"] = df["data"] * V2MULTI[v]
    if df["data"].max() < 0.01:
        bins = [0.01, 0.02, 0.03, 0.04, 0.05]
    else:
        bins = np.array(V2RAMP[v]) * (10.0 if agg == "sum" else 1.0)
    norm = mpcolors.BoundaryNorm(bins, cmap.N)

    # m.ax.add_geometries(df['geo'], ccrs.PlateCarree())
    for _, row in df.iterrows():
        c = cmap(norm([row["data"]]))[0]
        arr = np.asarray(row["geo"].exterior)
        points = mp.ax.projection.transform_points(ccrs.Geodetic(), arr[:, 0],
                                                   arr[:, 1])
        p = Polygon(points[:, :2], fc=c, ec="k", zorder=2, lw=0.1)
        mp.ax.add_patch(p)

    mp.drawcounties()
    mp.drawcities()
    lbl = [round(_, 2) for _ in bins]
    u = "%s, Avg: %.2f" % (V2UNITS[v], df["data"].mean())
    mp.draw_colorbar(
        bins,
        cmap,
        norm,
        clevlabels=lbl,
        units=u,
        title="%s :: %s" % (V2NAME[v], V2UNITS[v]),
    )
    plt.savefig("%s_%s_%s%s.png" %
                (ts.year, ts2.year, v, "_sum" if agg == "sum" else ""))