def generate(options, models):
    options['vic']['tmax'] = options['vic']['temperature']
    options['vic']['tmin'] = options['vic']['temperature']
    leadtime = 3
    db = dbio.connect(models.dbname)
    cur = db.cursor()
    name = models.name
    dt0 = date(models.startyear, models.startmonth, models.startday)
    dt1 = date(models.endyear, models.endmonth, models.endday)
    dtf = dt0 - relativedelta(months=1)  # forecast initialization date
    months = [(dt0 + relativedelta(months=t)).month for t in range(leadtime)]
    # check if forecast date exists in IRI data
    sql = "select count(*) from precip.iri where fdate=date '{0}-{1}-{2}'".format(
        dtf.year, dtf.month, dtf.day)
    cur.execute(sql)
    if bool(cur.rowcount):
        ptable = options['vic']['precip']
        # find resampled raster tables
        rtables = _getResampledTables(models.dbname, options, models.res)
        # resample climatology to IRI spatial resolution as a table
        _resampleClimatology(models.dbname, ptable, name, dt0)
        # calculate the annual accumulated precipitation using only the months
        # within the forecast period
        _deleteTableIfExists(models.dbname, 'public', 'iri_psum')
        sql = "create table iri_psum as (with f as (select distinct x,y,tile from precip.{0}_iri_xy) select x,y,date_part('year',fdate) as yr,sum(st_value(rast,x,y)) as psum,row_number() over (partition by x,y) as rid from f,precip.{0}_iri where rid=tile and ({1}) group by x,y,yr order by x,y,psum)".format(
            ptable, " or ".join(["date_part('month',fdate)={0}".format(m) for m in months]))
        cur.execute(sql)
        db.commit()
        # retrieve probabilities from IRI seasonal forecast
        _deleteTableIfExists(models.dbname, 'public', 'iri_probs')
        sql = "create table iri_probs as (with f as (select x,y,st_pixelaspoint(rast,x,y) as geom from precip.{0}_iri_xy,precip.{0}_iri where rid=tile and fdate=date'{1}-{2}-{3}') select x,y,st_value(rast,geom) as prob,tercile,leadtime from f,precip.iri where fdate=date'{4}-{5}-{6}')".format(
            ptable, dt0.year, dt0.month, dt0.day, dtf.year, dtf.month, dtf.day)
        cur.execute(sql)
        cur.execute("alter table iri_probs add column pg int")
        for ti, t in enumerate(['below', 'normal', 'above']):
            cur.execute(
                "update iri_probs set pg={0} where tercile='{1}'".format(ti + 1, t))
        db.commit()
        # get number of years in climatology
        cur.execute("select count(distinct(yr)) from iri_psum")
        nyears = int(cur.fetchone()[0])
        # assign probability weights to each year
        # FIXME: It seems like the IRI NetCDFs have null values for lead times
        # > 1 month. Just using lead time of 1 month for now
        _deleteTableIfExists(models.dbname, 'public', 'iri_pw')
        sql = "create table iri_pw as (with s as (select x,y,yr,psum,rid/({0}/3+1)+1 as pg from iri_psum) select s.x,s.y,s.yr,psum,1.0/{1}*prob/100.0 as weight from s inner join iri_probs as p on p.x=s.x and p.y=s.y and s.pg=p.pg where leadtime=1)".format(
            nyears, nyears / 3.0)
        cur.execute(sql)
        db.commit()
        # sample years based on probability weights
        _deleteTableIfExists(models.dbname, 'public', 'iri_years')
        sql = "create table iri_years as (with f as (select x,y,yr,sum(weight) over (partition by x,y order by psum) as w1, sum(weight) over (partition by x,y order by psum) - weight as w2 from iri_pw), r as (select n as ens,random() as s from generate_series(1,{0}) as x(n)) select x,y,yr,ens from f,r where s>=w2 and s<w1)".format(
            models.nens)
        cur.execute(sql)
        db.commit()
        # retrieve and write forcing data
        for e in range(models.nens):
            data = _getForcings(e, models.dbname, ptable,
                                rtables, name, dt0, dt1)
            models[e].writeForcings(data['precip'], data['tmax'], data[
                                    'tmin'], data['wind'])
    else:
        print(
            "WARNING! IRI forecast was not issued for requested date {0}.".format(dt0))
    # Clean-up temporary tables
    cur.execute("drop table precip.{0}_iri_xy".format(ptable))
    cur.execute("drop table iri_psum")
    cur.execute("drop table iri_probs")
    cur.execute("drop table iri_years")
    cur.close()
    db.close()
Generate meteorological forecast forcings by resampling fine-scale climatology.
dataset/ETHPy150Open nasa/RHEAS/src/datasets/iri.py/generate