Esempio n. 1
0
def frame(i, stack, ax, cmap, clim):
    # Create image
    im = ax.imshow(stack._datasets['data'][i],
                   extent=stack.hdr.extent,
                   cmap=cmap,
                   clim=clim)

    # Convert date from tdec to datestr
    datestr = ice.tdec2datestr(stack.tdec[i] + 2000)

    # Create title
    title = plt.text(0.5,
                     1.01,
                     datestr,
                     horizontalalignment='center',
                     verticalalignment='bottom',
                     transform=ax.transAxes)
    return [im, title]
Esempio n. 2
0
    # Therefore, we add integrated B-splines of various timescales where the
    # timescale is controlled by the 'nspl' value (this means to divide the time
    # vector into 'nspl' equally spaced spline center locations)
    for nspl in [128, 64, 32, 16, 8, 4]:
        collection.append(
            ispl(order=3, num=nspl, units='years', tmin=tstart, tmax=tend))

    # Done
    return collection


# Create an evenly spaced time array for time series predictions
t_grid = np.linspace(hel_stack.tdec[0], hel_stack.tdec[-1], 1000)

# First convert the time vectors to a list of datetime
dates = ice.tdec2datestr(hel_stack.tdec, returndate=True)
dates_grid = ice.tdec2datestr(t_grid, returndate=True)

# Build the collection
collection = build_collection(dates)

# Instantiate a model for inversion
model = ice.tseries.Model(dates, collection=collection)

# Instantiate a model for prediction
model_pred = ice.tseries.Model(dates_grid, collection=collection)

## Access the design matrix for plotting
G = model.G
# plt.plot(hel_stack.tdec, G)
# plt.xlabel('Year')
Esempio n. 3
0
 def animate(i):
     im.set_data(data[i] - data_ref)
     datestr = ice.tdec2datestr(stack.tdec[i])
     tx.set_text(args.title + ' ' + datestr)
Esempio n. 4
0
def main(args):
    # Load Stack
    stack = ice.Stack(args.stackfile)

    # Load reference SAR image
    if args.ref is not None:
        sar = ice.Raster(rasterfile=args.ref)
        if sar.hdr != stack.hdr:
            sar.resample(stack.hdr)
        db = 10.0 * np.log10(sar.data)
        low = np.percentile(db.ravel(), 5)
        high = np.percentile(db.ravel(), 99.9)
    else:
        db = None

    # Set up animation
    fig, ax = plt.subplots(figsize=args.figsize)
    data = stack._datasets[args.key]
    cmap = ice.get_cmap(args.cmap)

    # Add ref image if using
    if db is not None:
        ax.imshow(db,
                  aspect='auto',
                  cmap='gray',
                  vmin=low,
                  vmax=high,
                  extent=stack.hdr.extent)

    # Extract reference frame if index provided
    if args.rel_index is not None:
        data_ref = data[args.rel_index]
    else:
        data_ref = 0.0

    im = ax.imshow(data[0] - data_ref,
                   extent=stack.hdr.extent,
                   cmap=cmap,
                   clim=args.clim,
                   alpha=args.alpha)

    # Create title
    datestr = ice.tdec2datestr(stack.tdec[0])
    tx = ax.set_title(args.title + ' ' + datestr, fontweight='bold')

    ax.set_xlabel(args.xlabel)
    ax.set_ylabel(args.ylabel)

    # Add colorbar
    div = make_axes_locatable(ax)
    cax = div.append_axes('right', '5%', '5%')
    cb = fig.colorbar(im, cax=cax)
    cb.set_label(args.clabel)

    # Update the frame
    def animate(i):
        im.set_data(data[i] - data_ref)
        datestr = ice.tdec2datestr(stack.tdec[i])
        tx.set_text(args.title + ' ' + datestr)

    fig.set_tight_layout(True)

    print('Generating animation and saving to', args.save)
    interval = 1000 / args.fps  # Convert fps to interval in milliseconds
    anim = animation.FuncAnimation(fig,
                                   animate,
                                   interval=interval,
                                   frames=len(data),
                                   repeat=True)
    anim.save(args.save, dpi=args.dpi)

    if args.show:
        plt.show()
def main():
    stack_path = './data/stacks/'
    stack_fname = 'joughin_v_stack.hdf5'
    transect_fname = 'landsat_transect.npy'

    print('Loading data and building model ..................................')
    # Load transect coordinates and Stack
    x, y = np.load(stack_path + transect_fname)
    x, y = ice.transform_coordinates(x, y, 32606, 3413)
    stack = ice.Stack(stack_path + stack_fname)

    # Convert time vector to list of datetimes
    t = ice.tdec2datestr(stack.tdec, returndate=True)
    transect_velocities = np.array([stack.timeseries(xy=[x[i], y[i]], win_size=1) for i in range(len(x))])
    # Create model
    model = ice.tseries.build_temporal_model(t, poly=2, isplines=[])

    # Create temporally coherent (smooth) G over entire timespan of data
    stdec = ice.generateRegularTimeArray(min(stack.tdec), max(stack.tdec))
    st = ice.tdec2datestr(stdec, returndate=True)
    sG = ice.tseries.build_temporal_model(st, poly=2, isplines=[]).G

    # Create image displaying found seasonal and secular variation along transect
    print('Solving regression along transect ................................')
    
    # Store the timeseries fit for each point along the transect
    data = {
        'total' : transect_velocities,
        'seasonal' : [],
        'secular' : []
    }
    fit = {
        'seasonal' : [],
        'secular' : []
    }
    transect_amp = []
    transect_phase = []
    mean_vel = []
    transect_sec_phase = []
    transect_sec_min = []
    
    for tseries in transect_velocities:
        tseries[tseries < 0] = np.nan
        solver = ice.tseries.select_solver('ridge', reg_indices=model.itransient, penalty=0.25)
        _, m, _ = solver.invert(model.G, tseries)

        amp, phase = compute_seasonal_amp_phase(m, model)
        transect_amp.append(amp)
        transect_phase.append(phase)

        a, b, c = m[model.isecular] # y = a + bx + cx**2
        transect_sec_phase.append(-b/(2*c))
        transect_sec_min.append(a - b**2/(4*c))

        if m is None:
            continue

        seasonal_tseries = np.dot(sG[:,model.iseasonal], m[model.iseasonal])
        secular_tseries = np.dot(sG[:,model.isecular], m[model.isecular])

        mean_vel.append(np.nanmean(tseries))
        # mean_vel.append(np.nanmedian(seasonal_tseries + secular_tseries))

        fit['seasonal'].append(seasonal_tseries)
        fit['secular'].append(secular_tseries)

        seasonal_data = np.dot(model.G[:,model.iseasonal], m[model.iseasonal])
        secular_data = np.dot(model.G[:,model.isecular], m[model.isecular])

        data['seasonal'].append(tseries - secular_data)
        data['secular'].append(tseries - seasonal_data)

    # Calculate path length along the glacier in m
    path_len = ice.compute_path_length(x, y)

    # Get temporal extent of dataset
    extent = [stack.tdec[0], stack.tdec[-1], 0, path_len[-1]]

    # Generate plots
    # plot_timeseries_fit(int(0.20*len(transect_velocities)), data, stack.tdec, fit, stdec)
    # plot_transect_signal(fit, extent)

    # Smooth amp/phase
    smooth = True
    if smooth:
        win = 11
        poly = 2
        smooth_amp = savgol_filter(transect_amp, win, poly)
        smooth_phase = savgol_filter(transect_phase, win, poly)
        smooth_vel = savgol_filter(mean_vel, win, poly)
        smooth_sec_phase = savgol_filter(transect_sec_phase, win, poly)
        smooth_sec_min = savgol_filter(transect_sec_min, win, poly)
        plot_transect_amp_phase(smooth_amp, smooth_phase, smooth_vel, path_len)
        plot_transect_secular(smooth_sec_phase, smooth_phase, smooth_sec_min, smooth_vel, path_len)
    else:
        plot_transect_amp_phase(transect_amp, transect_phase, mean_vel, path_len)
    

    # Close fd
    stack.fid.close()
    collection.append(periodic(tref=tstart, units='years', period=1.0,
                               tmin=tstart, tmax=tend))
    
    # Integrated B-slines for transient signals
    # In general, we don't know the timescales of transients a prior
    # Therefore, we add integrated B-splines of various timescales where the
    # timescale is controlled by the 'nspl' value (this means to divide the time
    # vector into 'nspl' equally spaced spline center locations)
    for nspl in [128, 64, 32, 16, 8, 4]:
        collection.append(ispl(order=3, num=nspl, units='years', tmin=tstart, tmax=tend))
    
    # Done
    return collection

# First convert the time vector to a list of datetime
dates = ice.tdec2datestr(hel_stack.tdec, returndate=True)

# Build the collection
collection = build_collection(dates)

# Instantiate a model
model = ice.tseries.Model(dates, collection=collection)

# Create lasso regression solvers (see time_series_inversion.ipynb for ridge vs lasso performance)
lasso = ice.tseries.select_solver('lasso', reg_indices=model.itransient, penalty=0.2)

## Perform inversion for each time series extracted
decomps = []
for ser in series:    
    SUCCESS, m_lasso, Cm = lasso.invert(model.G, ser)
    pred = model.predict(m_lasso)