def get_agg_cube(cube, agg):
    """Get the temporally aggregated data.

    Args:
      cube (iris.cube.Cube)
      agg (str)

    """

    coord_names = [coord.name() for coord in cube.dim_coords]
    assert coord_names[0] == 'time'

    if agg == 'trend':
        trend_data = timeseries.calc_trend(cube, per_yr=True)
        agg_cube = cube[0, ::].copy()
        agg_cube.data = trend_data
        try:
            agg_cube.units = str(cube.units) + ' yr-1'
        except ValueError:
            agg_cube.units = 'yr-1'
    elif agg == 'clim':
        agg_cube = cube.collapsed('time', iris.analysis.MEAN)
    agg_cube.remove_coord('time')

    return agg_cube
示例#2
0
def get_agg_cube(cube, agg, remove_outliers=False):
    """Get the temporally aggregated data.

    Args:
      cube (iris.cube.Cube)
      agg (str)

    """

    assert agg in ['trend', 'clim', 'monthly_clim']

    coord_names = [coord.name() for coord in cube.dim_coords]
    assert coord_names[0] == 'time'

    if agg == 'trend':
        trend_data = timeseries.calc_trend(cube, per_yr=True, remove_outliers=remove_outliers)
        agg_cube = cube[0, ::].copy()
        agg_cube.data = trend_data
        try:
            agg_cube.units = str(cube.units) + ' yr-1'
        except ValueError:
            agg_cube.units = 'yr-1'
    elif agg == 'clim':
        agg_cube = cube.collapsed('time', iris.analysis.MEAN)
        agg_cube.remove_coord('time') 
    elif agg == 'monthly_clim':
        iris.coord_categorisation.add_month(cube, 'time')
        agg_cube = cube.aggregated_by(['month'], iris.analysis.MEAN)
        agg_cube.remove_coord('month') 

    return agg_cube
def get_data(infile, var, agg_method, time_constraint, ohc=False, branch=None):
    """Read and temporally aggregate the data."""

    try:
        with iris.FUTURE.context(cell_datetime_objects=True):
            cube = iris.load_cube(infile, var & time_constraint)

            if branch:
                branch_time, nyears = branch
                cube = select_control_segment(cube, branch_time, nyears)

            if ohc:
                cube = calc_dohc_dt(cube)

            if agg_method == 'trend':
                value = timeseries.calc_trend(cube, per_yr=True)
            elif agg_method == 'climatology':
                value = float(cube.collapsed('time', iris.analysis.MEAN).data)

        if 'land' in var:
            color = 'green'
        elif 'ocean' in var:
            color = 'blue'
        else:
            color = 'black'
    except iris.exceptions.ConstraintMismatchError:
        value = 0
        color = '0.5'

    return value, color
def get_trend_cube(cube, xaxis='time'):
    """Get the trend data.
    Args:
      cube (iris.cube.Cube)
      xaxis (iris.cube.Cube)
    """

    coord_names = [coord.name() for coord in cube.dim_coords]
    assert coord_names[0] == 'time'

    if xaxis == 'time':
        trend_data = timeseries.calc_trend(cube, per_yr=True)
        trend_unit = ' yr-1'
    else:
        trend_data = numpy.ma.apply_along_axis(calc_linear_trend, 0, cube.data,
                                               xaxis.data)
        trend_data = numpy.ma.masked_values(trend_data, cube.data.fill_value)
        trend_unit = ' ' + str(xaxis.units) + '-1'

    trend_cube = cube[0, ::].copy()
    trend_cube.data = trend_data
    trend_cube.remove_coord('time')
    trend_cube.units = str(cube.units) + trend_unit

    return trend_cube
示例#5
0
def get_scale_factor(infile):
    """Get the scaling factor."""

    cube = iris.load_cube(infile,
                          'Surface Downwelling Net Radiation globe sum')
    trend = timeseries.calc_trend(cube, per_yr=True)

    return trend
def calc_trend_cube(cube):
    """Calculate trend and put into appropriate cube."""

    trend_array = timeseries.calc_trend(cube, per_yr=True)
    new_cube = cube[0, :].copy()
    new_cube.remove_coord('time')
    new_cube.data = trend_array

    return new_cube
def main(inargs):
    """Run the program."""
    
    # Read data
    try:
        time_constraint = gio.get_time_constraint(inargs.time)
    except AttributeError:
        time_constraint = iris.Constraint()

    with iris.FUTURE.context(cell_datetime_objects=True):
        ohc_3D_cube = iris.load_cube(inargs.infile, 'ocean heat content 3D' & time_constraint)  
        ohc_2D_cube = iris.load_cube(inargs.infile, 'ocean heat content 2D' & time_constraint)

    lons = ohc_3D_cube.coord('longitude').points
    lats = ohc_3D_cube.coord('latitude').points
    infile_history = ohc_3D_cube.attributes['history']
    
    # Calculate seasonal cycle
    running_mean = True
    if inargs.seasonal_cycle:
        ohc_3D_cube = timeseries.calc_seasonal_cycle(ohc_3D_cube) 
        ohc_2D_cube = timeseries.calc_seasonal_cycle(ohc_2D_cube)
        running_mean = False

    # Calculate trend
    ohc_3D_trend = timeseries.calc_trend(ohc_3D_cube, running_mean=running_mean,
                                         per_yr=False, remove_scaling=True)
    ohc_2D_trend = timeseries.calc_trend(ohc_2D_cube, running_mean=running_mean,
                                         per_yr=False, remove_scaling=True)

    # Plot
    fig = plt.figure(figsize=[15, 3])
    gs = gridspec.GridSpec(1, 2, width_ratios=[4, 1]) 

    cbar_tick_max, cbar_tick_step = inargs.ticks
    yticks = set_yticks(inargs.max_lat)
    plot_3D_trend(ohc_3D_trend, lons, lats, gs,
                  cbar_tick_max, cbar_tick_step, yticks)
    plot_2D_trend(ohc_2D_trend, lats, gs,
                  yticks)

    # Write output
    plt.savefig(inargs.outfile, bbox_inches='tight')
    gio.write_metadata(inargs.outfile, file_info={inargs.outfile:infile_history})
示例#8
0
def load_data(infile, var, time_constraint):
    """Load the data"""

    with iris.FUTURE.context(cell_datetime_objects=True):
        cube = iris.load_cube(infile,
                              gio.check_iris_var(var) & time_constraint)
        cube.data = cube.data * 100
    model, experiment, rip, physics = get_run_details(cube)
    trend = timeseries.calc_trend(cube, per_yr=True)

    return cube, trend, model, experiment, rip
示例#9
0
def calc_zonal_stats(cube, basin_array, basin_name):
    """Calculate the zonal mean climatology and trend for a given ocean basin."""

    cube.data.mask = numpy.where(
        (cube.data.mask == False) & (basin_array == basins[basin_name]), False,
        True)

    zonal_mean_cube = cube.collapsed('longitude', iris.analysis.MEAN)
    zonal_mean_cube.remove_coord('longitude')

    zonal_climatology = zonal_mean_cube.collapsed('time', iris.analysis.MEAN)
    zonal_trend = timeseries.calc_trend(zonal_mean_cube,
                                        running_mean=True,
                                        per_yr=True,
                                        remove_scaling=False)

    return zonal_climatology.data, zonal_trend * 50
def load_data(infile, var_list, time_constraint):
    """Load the data"""

    trend_list = []
    for var in var_list:
        cube = iris.load_cube(infile,
                              gio.check_iris_var(var) & time_constraint)
        model, experiment, rip, physics = get_run_details(cube)
        trend = timeseries.calc_trend(cube, per_yr=True)
        trend = check_sign(trend, var)
        trend_list.append(trend)

    if len(trend_list) == 2:
        print('dividing y vars')
        out_trend = trend_list[0] / trend_list[1]
    else:
        out_trend = trend_list[0]

    return out_trend, cube, model, experiment, rip
def main(inargs):
    """Run the program."""

    time_constraint = gio.get_time_constraint(inargs.time)

    trend_dict = {}
    models = []
    for infile in inargs.infiles:
        with iris.FUTURE.context(cell_datetime_objects=True):
            cube = iris.load_cube(infile, 'air_temperature' & time_constraint)
            experiment, model, metric_name = get_file_info(infile)
            trend_dict[(model,
                        experiment)] = timeseries.calc_trend(cube, per_yr=True)
        models.append(model)

    models = sort_list(models)
    hist_data, ghg_data, aa_data = order_data(trend_dict, models)
    ant_data = numpy.array(ghg_data) + numpy.array(aa_data)

    ind = numpy.arange(len(hist_data))  # the x locations for the groups
    width = 0.2  # the width of the bars

    fig, ax = plt.subplots(figsize=(20, 8))
    rects1 = ax.bar(ind, ghg_data, width, color='red')
    rects2 = ax.bar(ind + width, aa_data, width, color='blue')
    rects3 = ax.bar(ind + 2 * width, ant_data, width, color='purple')
    rects4 = ax.bar(ind + 3 * width, hist_data, width, color='green')

    ax.set_ylabel('$K yr^{-1}$')

    start_year = inargs.time[0].split('-')[0]
    end_year = inargs.time[1].split('-')[0]
    ax.set_title('Trend in %s, %s-%s' % (metric_name, start_year, end_year))

    ax.set_xticks(ind + 1.5 * width)
    ax.set_xticklabels(models)
    ax.legend((rects1[0], rects2[0], rects3[0], rects4[0]),
              ('historicalGHG', 'historicalAA', 'GHG + AA', 'historical'),
              loc=1)

    plt.savefig(inargs.outfile, bbox_inches='tight')
    gio.write_metadata(inargs.outfile,
                       file_info={infile: cube.attributes['history']})
示例#12
0
def get_regional_trends(infile, variable, time_constraints):
    """Calculate regional trends for a given variable"""

    if 'rcp' in infile:
        time_constraint = time_constraints['rcp']
    else:
        time_constraint = time_constraints['historical']

    trend_values = []
    for region in ['ssubpolar', 'stropics', 'ntropics', 'nsubpolar', 'arctic']:
        full_var = '%s %s ocean sum' % (variable, region)
        with iris.FUTURE.context(cell_datetime_objects=True):
            cube = iris.load_cube(infile, full_var & time_constraint)
        trend_values.append(timeseries.calc_trend(cube, per_yr=True))

    history = cube.attributes['history']
    model = cube.attributes['model_id']
    experiment = cube.attributes['experiment_id']
    if experiment == 'historicalMisc':
        experiment = 'historicalAA'
    run = 'r' + str(cube.attributes['realization'])

    return trend_values, history, model, experiment, run