Ejemplo n.º 1
0
def project_year(model, model_dir, what, scenario, year):
    print("projecting %s for %d using %s" % (what, year, scenario))

    models = select_models(model, model_dir)
    # Read Sam's abundance model (forested and non-forested)
    modf = modelr.load(models[0])
    intercept_f = modf.intercept
    predicts.predictify(modf)

    modn = modelr.load(models[1])
    intercept_n = modn.intercept
    predicts.predictify(modn)

    # Open forested/non-forested mask layer
    fstnf = rasterio.open(utils.luh2_static('fstnf'))

    # Import standard PREDICTS rasters
    rastersf = predicts.rasterset('luh2', scenario, year, 'f')
    rsf = RasterSet(rastersf, mask=fstnf, maskval=0.0)
    rastersn = predicts.rasterset('luh2', scenario, year, 'n')
    rsn = RasterSet(rastersn, mask=fstnf, maskval=1.0)
    #rsn = RasterSet(rastersn)

    if what == 'bii':
        vname = 'bii'
        rsf[vname] = SimpleExpr(
            vname, 'exp(%s) / exp(%f)' % (modf.output, intercept_f))
        rsn[vname] = SimpleExpr(
            vname, 'exp(%s) / exp(%f)' % (modn.output, intercept_n))
        rsf[modf.output] = modf
        rsn[modn.output] = modn
    else:
        vname = modf.output
        assert modf.output == modn.output
        rsf[vname] = modf
        rsn[vname] = modn

    if what not in rsf:
        print('%s not in rasterset' % what)
        print(', '.join(sorted(rsf.keys())))
        sys.exit(1)

    stime = time.time()
    datan, meta = rsn.eval(what, quiet=False)
    dataf, _ = rsf.eval(what, quiet=True)
    data_vals = dataf.filled(0) + datan.filled(0)
    data = data_vals.view(ma.MaskedArray)
    data.mask = np.logical_and(dataf.mask, datan.mask)
    #data = datan
    etime = time.time()
    print("executed in %6.2fs" % (etime - stime))
    oname = '%s/luh2/%s-%s-%d.tif' % (utils.outdir(), scenario, what, year)
    with rasterio.open(oname, 'w', **meta) as dst:
        dst.write(data.filled(meta['nodata']), indexes=1)
    if None:
        fig = plt.figure(figsize=(8, 6))
        ax = plt.gca()
        show(data, cmap='viridis', ax=ax)
        plt.savefig('luh2-%s-%d.png' % (scenario, year))
    return
Ejemplo n.º 2
0
def project(year):
    print("projecting %d" % year)
    # Open the mask shape file
    shp_file = 'c:/data/from-adriana/tropicalforests.shp'
    shapes = fiona.open(shp_file)

    # Read Adriana's abundance model (mainland)
    mod = modelr.load('../tropical-bii/simplifiedAbundanceModel.rds')
    predicts.predictify(mod)

    # Import standard PREDICTS rasters
    rasters = predicts.rasterset('1km', '', year, 'medium')
    rasters['primary_lightintense'] = SimpleExpr(
        'primary_lightintense', 'primary_light + primary_intense')
    rasters['cropland_lightintense'] = SimpleExpr(
        'cropland_lightintense', 'cropland_light + cropland_intense')
    rasters['pasture_lightintense'] = SimpleExpr(
        'pasture_lightintense', 'pasture_light + pasture_intense')
    rasters['rd_dist'] = Raster('rd_dist', '/out/1km/roads-adrid.tif')
    rasters['hpd'] = Raster(
        'hpd', '/vsizip//data/from-adriana/HPD01to12.zip/yr%d/hdr.adf' % year)

    rs = RasterSet(rasters, shapes=shapes, crop=True, all_touched=True)

    what = 'LogAbund'
    rs[what] = mod
    stime = time.time()
    rs.write(what, utils.outfn('1km', 'adrid-%d.tif' % year))
    etime = time.time()
    print("executed in %6.2fs" % (etime - stime))
Ejemplo n.º 3
0
def project_year(model, model_dir, what, scenario, year):
    print("projecting %s for %d using %s" % (what, year, scenario))

    models = select_models(model, model_dir)
    # Read Sam's abundance model (forested and non-forested)
    mod = modelr.load(models[0])
    predicts.predictify(mod)

    # Import standard PREDICTS rasters
    by_age = 'young_secondary' in mod.syms
    print('by_age: %s' % str(by_age))
    rasters = predicts.rasterset('luh5', scenario, year, by_age)
    rs = RasterSet(rasters)

    if what == 'bii':
        vname = 'bii'
        rs[vname] = SimpleExpr(vname, '%s / %f' % (mod.output, intercept))
    else:
        vname = mod.output
    rs[vname] = mod

    if what not in rs:
        print('%s not in rasterset' % what)
        print(', '.join(sorted(rs.keys())))
        sys.exit(1)

    stime = time.time()
    data, meta = rs.eval(what, quiet=False)
    etime = time.time()
    print("executed in %6.2fs" % (etime - stime))
    oname = os.path.join(os.environ['OUTDIR'],
                         'luh5/%s-%s-%d.tif' % (scenario, what, year))
    #hpd, _ = rs.eval('hpd', quiet=False)
    #hpd_max, meta2 = rs.eval('hpd_max', quiet=False)
    with rasterio.open(oname, 'w', **meta) as dst:
        #bb = dst.bounds
        #ul = map(int, ~meta2['affine'] * (bb[0], bb[3]))
        #lr = map(int, ~meta2['affine'] * (bb[2], bb[1]))
        #cap = ma.where(hpd > hpd_max[ul[1]:lr[1], ul[0]:lr[0]], True, False)
        #show(hpd, norm=colors.PowerNorm(gamma=0.2))
        #show(cap * 1)
        #data.mask = np.logical_or(data.mask, cap)
        dst.write(data.filled(meta['nodata']), indexes=1)
    if None:
        fig = plt.figure(figsize=(8, 6))
        ax = plt.gca()
        show(data, cmap='viridis', ax=ax)
        plt.savefig('luh2-%s-%d.png' % (scenario, year))
    return
Ejemplo n.º 4
0
def project_year(model, model_dir, scenario, year):
    """Run a projection for a single year.  Can be called in parallel when
projecting a range of years.

  """

    print("projecting %s for %d using %s" % (model, year, scenario))

    # Import standard PREDICTS rasters
    rasters = predicts.rasterset('luh2', scenario, year)
    rs = RasterSet(rasters)

    what, model = select_model(model, model_dir)
    # Read Sam's models
    if model:
        mod = modelr.load(model)
        predicts.predictify(mod)
        rs[mod.output] = mod

    if what in ('CompSimAb', 'CompSimSR', 'Abundance', 'Richness'):
        if what in ('CompSimAb', 'CompSimSR'):
            expr = '(inv_logit(%s) - 0.01) / (inv_logit(%f) - 0.01)'
        else:
            expr = '(exp(%s) / exp(%f))'
        rs[what] = SimpleExpr(what, expr % (mod.output, mod.intercept))

    if what not in rs:
        print('%s not in rasterset' % what)
        print(', '.join(sorted(rs.keys())))
        sys.exit(1)

    stime = time.time()
    data, meta = rs.eval(what, quiet=True)
    etime = time.time()
    print("executed in %6.2fs" % (etime - stime))
    oname = '%s/luh2/%s-%s-%04d.tif' % (utils.outdir(), scenario, what, year)
    with rasterio.open(oname, 'w', **meta) as dst:
        dst.write(data.filled(meta['nodata']), indexes=1)
    if None:
        fig = plt.figure(figsize=(8, 6))
        show(data, cmap='viridis', ax=plt.gca())
        fig.savefig('luh2-%s-%d.png' % (scenario, year))
    return
Ejemplo n.º 5
0
def plot(model, title, save, adjust):
    """Plot response curve of CS model versus HPD."""
    mod = modelr.load(model)
    df = pd.DataFrame(columns=tuple(luh2.LU.keys()))
    for col in df.columns:
        s = pd.Series(
            mod.partial({
                'LogHPD_s2': np.linspace(0, 11, 13),
                'LogHPD_diff': np.linspace(0, -11, 13),
                col: np.full((13), 1)
            }))
        df[col] = (inv_logit(s) - adjust) / (1 - 2 * adjust)

    df.plot()
    ax = plt.gca()
    ax.set_title(title)
    ax.set_xlabel('log(HPD + 1)')
    ax.set_ylabel('CompSim')
    if save:
        plt.savefig(save, transparent=True, bbox_inches="tight", pad_inches=0)
    plt.show()
import projections.predicts as predicts
import projections.r2py.modelr as modelr
import projections.utils as utils

scenarios = ['historical', 'ssp1_rcp2.6_image', 'ssp5_rcp8.5_remind-magpie']
models = ['ab_model.rds', 'sr_model.rds']

for model in models:

    if model == 'ab_model.rds':
        what = "abundance"
    else:
        what = "sprich"

    # Read in the model
    mod = modelr.load('D:/victoria_projections/' + model)
    predicts.predictify(mod)

    for scenario in scenarios:

        if scenario == 'historical':
            years = range(1970, 2015)
            hpdtrend = 'wpp'

        else:
            years = range(2015, 2101)
            hpdtrend = 'medium'

        for year in years:

            rasters = predicts.rasterset('luh2',
Ejemplo n.º 7
0
args = parser.parse_args()

if args.mainland:
    ISLMAIN = 1
    mask_file = os.path.join(utils.data_root(),
                             '1km/mainland-from-igor-edited-at.tif')
else:
    ISLMAIN = 0
    mask_file = os.path.join(utils.data_root(),
                             '1km/islands-from-igor-edited-at.tif')

# Open the mask raster file (Mainlands)
mask_ds = rasterio.open(mask_file)

# Read Katia's abundance model
mod = modelr.load('/home/vagrant/katia/models/best_model_abund.rds')
predicts.predictify(mod)

# Import standard PREDICTS rasters
rasters = predicts.rasterset('1km', 'medium', year=2005)

# create an ISL_MAINL raster
# set it to Mainlands this time round (set Mainlands to 1 and Islands to 0)
rasters['ISL_MAINLMAINLAND'] = SimpleExpr('ISL_MAINLMAINLAND', ISLMAIN)

# specify the plantation forest maps as 0
# not sure why it's plantations_pri rather than plantation, but hey ho
rasters['plantation_pri'] = SimpleExpr('plantation_pri', 0)
rasters['plantation_pri_minimal'] = SimpleExpr('plantation_pri_minimal', 0)
rasters['plantation_pri_light'] = SimpleExpr('plantation_pri_light', 0)
rasters['plantation_pri_intense'] = SimpleExpr('plantation_pri_intense', 0)
Ejemplo n.º 8
0
import rasterio
from rasterio.plot import show, show_hist

from projections.rasterset import RasterSet, Raster
from projections.simpleexpr import SimpleExpr
import projections.predicts as predicts
import projections.r2py.modelr as modelr
import projections.utils as utils

# Open the mask raster file
mask_file = os.path.join(utils.data_root(),
                         '1km/mainland-from-igor-edited.tif')
mask_ds = rasterio.open(mask_file)

# Richness compositional similarity model with updated PriMin-Urb coefficient
mod = modelr.load('/home/vagrant/katia/models/updated_compsim_rich.rds')
predicts.predictify(mod)

# Import standard PREDICTS rasters
rasters = predicts.rasterset('1km', 'medium', year=2005)

# create an ISL_MAINL raster
# set it to Mainlands this time round (set Mainlands to 1 and Islands to 0)
rasters['ISL_MAINMAINLAND'] = SimpleExpr('ISL_MAINMAINLAND', '2')
rasters['ISL_MAINISLAND'] = SimpleExpr('ISL_MAINISLAND', '0')

rasters['adjGeogDist'] = SimpleExpr('adjGeogDist', '0')
rasters['cubeRtEnvDist'] = SimpleExpr('cubeRtEnvDist', '0')

# set up the rasterset, cropping to mainlands
rs = RasterSet(rasters, mask=mask_ds, maskval=0, crop=True)
Ejemplo n.º 9
0
import time

from rasterio.plot import show
import matplotlib.pyplot as plt

from projections.rasterset import RasterSet, Raster
import projections.predicts as predicts
import projections.r2py.modelr as modelr

# Open the mask shape file
shp_file = os.path.join(os.environ['DATA_ROOT'],
                        'from-adriana/tropicalforests.shp')
shapes = fiona.open(shp_file)

# Read Adriana's abundance model (mainland)
mod = modelr.load(os.path.join(os.environ['MODEL_DIR'], 'ab-model.rds'))
predicts.predictify(mod)

# Import standard PREDICTS rasters
rasters = predicts.rasterset('luh5', 'historical', 1990, True)
rs = RasterSet(rasters, shapes=shapes, all_touched=True)

what = mod.output
rs[mod.output] = mod
stime = time.time()
data1, meta_data1 = rs.eval(what)
etime = time.time()
print("executed in %6.2fs" % (etime - stime))
show(data1)

##
Ejemplo n.º 10
0
import projections.utils as utils

RD_DIST_MIN = 0
RD_DIST_MAX = 195274.3
HPD_MIN = 0
HPD_MAX = 22490

CLIP = True  # False

# Open the mask raster file (Mainlands)
mask_file = os.path.join(utils.data_root(),
                         '1km/mainland-from-igor-edited.tif')
mask_ds = rasterio.open(mask_file)

# Read Katia's richness model
mod = modelr.load('/home/vagrant/katia/models/best_model_rich.rds')
predicts.predictify(mod)

# Import standard PREDICTS rasters
rasters = predicts.rasterset('1km', 'medium', year=2005)

# create an ISL_MAINL raster
# set it to Mainlands this time round (set Mainlands to 1 and Islands to 0)
rasters['ISL_MAINLMAINLAND'] = SimpleExpr('ISL_MAINLMAINLAND', '2')
rasters['ISL_MAINLISLAND'] = SimpleExpr('ISL_MAINLISLAND', '0')

# specify the plantation forest maps as 0
# not sure why it's plantations_pri rather than plantation, but hey ho
rasters['plantation_pri'] = SimpleExpr('plantation_pri', '0')
rasters['plantation_pri_minimal'] = SimpleExpr('plantation_pri_minimal', '0')
rasters['plantation_pri_light'] = SimpleExpr('plantation_pri_light', '0')
Ejemplo n.º 11
0
# specify the model version
fldr = ['v1', 'v2', 'v3']

# Open the mask shape file
shp_file = 'c:/data/from-adriana/tropicalforests.shp'
shapes = fiona.open(shp_file)

# for each model version
for version in fldr:

    # get the model name
    mod_name = 'simplifiedAbundanceModel_' + version + '.rds'

    # Read in the model
    mod = modelr.load('C:/data/from-adriana/ModelsForProjections/' + mod_name)
    predicts.predictify(mod)

    # pull out the reference value for this model
    df = pandas.read_csv(
        'C:/data/from-adriana/ValuesForProjections/abData.csv')
    value_name = 'reference_' + version
    ref = float(df[df['Value'] == value_name]['zeroValue'])

    # for each year
    for year in range(2001, 2013):

        # This line imports standard PREDICTS rasters
        #rasters = predicts.rasterset('1km', 'version3.3', year, 'medium')
        # we don't need this anymore as we're importing our own data