Пример #1
0
def test_arr_parameter():
    """Raise an AttributeError if an array is not provided."""
    with pytest.raises(
        AttributeError, match="Input arr should be a numpy array"
    ):
        ep.plot_bands(arr=(1, 2))
    plt.close()
Пример #2
0
def NDVI(bands, year):
	"""Normalized Difference Vegetation Index (NDVI)"""

	#ndvi = es.normalized_diff(band4, band3)      # (band4-band3)/(band4+band3)
	ndvi = es.normalized_diff(bands[3], bands[2]) # (band4-band3)/(band4+band3)

	titles = ['Normalized Difference Vegetation Index (NDVI) Year: %s' %year]

	# Turn off bytescale scaling due to float values for NDVI
	ep.plot_bands(ndvi, cmap="RdYlGn", cols=1, title=titles, vmin=-1, vmax=1)

	# Create classes and apply to NDVI results
	ndvi_class_bins    = [-np.inf, 0, 0.25, 0.5, 0.75, np.inf]
	ndvi_landsat_class = np.digitize(ndvi, ndvi_class_bins)

	# Define color map and class names
	ndvi_colors = ListedColormap(['gray', 'y', 'yellowgreen', 'g', 'darkgreen'])
	ndvi_names = ['0.00 No Vegetation','0.25 Bare Area','0.50 Low Vegetation','0.75 Moderate Vegetation','1.00 High Vegetation']

	# Get list of classes
	classes = np.unique(ndvi_landsat_class).tolist()

	fig, ax = plt.subplots(figsize=(8, 8))
	im      = ax.imshow(ndvi_landsat_class, cmap=ndvi_colors)

	ep.draw_legend(im_ax=im, classes=classes, titles=ndvi_names)
	ax.set_title('Normalized Difference Vegetation Index (NDVI) Classes. \nYear: %s' %yr,fontsize=14)
	ax.set_axis_off(); plt.tight_layout()
	plt.show()
Пример #3
0
def plot_cropped_raster():
    # Plot your data
    ep.plot_bands(raster_crop[2],
                  extent=raster_extent,
                  cmap='Greys',
                  title="Cropped Raster Dataset",
                  scale=False)
    plt.show()
Пример #4
0
    def show_map(self):
        print("Huglin Index of combined Hemispheres")
        ep.plot_bands(self.south_huglin_dataset,
                      cmap='PiYG',
                      scale=False,
                      vmin=self.south_huglin_min,
                      vmax=self.south_huglin_max)

        return
Пример #5
0
def test_num_titles(image_array_2bands):
    """Test the number of titles.

    If a user provides two titles for a single band array, the function
    should raise an error OR if the title list is a different length than
    the array it should also raise an errors.
    """
    single_band = image_array_2bands[0]

    with pytest.raises(ValueError):
        ep.plot_bands(arr=single_band, title=["Title1", "Title2"])
    with pytest.raises(ValueError):
        ep.plot_bands(arr=image_array_2bands,
                      title=["Title1", "Title2", "Title3"])
Пример #6
0
def plot_crop_overlayed_on_raster():
    fig, ax = plt.subplots(figsize=(10, 8))

    ep.plot_bands(raster.read(1),
                  cmap='terrain',
                  extent=plotting_extent(raster),
                  ax=ax,
                  title="Raster Layer with Shapefile Overlayed",
                  cbar=False)

    crop_extent.plot(ax=ax, alpha=.8)
    ax.set_axis_off()

    plt.show()
Пример #7
0
def test_multi_panel_single_band(one_band_3dims):
    """Test that multi panel works with single band arr."""

    title1 = "Title axis one"
    title2 = "Title axis two"
    f, (ax1, ax2) = plt.subplots(2, 1)
    ep.plot_bands(one_band_3dims, title=title1, ax=ax1)
    ep.plot_bands(one_band_3dims, title=title2, ax=ax2)

    # get all axis subplot elements - note this returns subplots and axes
    all_axes = f.axes

    assert len(all_axes) == 4
    assert all_axes[0].get_title() == title1
    assert all_axes[1].get_title() == title2
Пример #8
0
def test_custom_plot_title(image_array_2bands):
    """Test that the custom title is applied for a 2 band array plot."""
    ax = ep.plot_bands(image_array_2bands, title=["Red Band", "Green Band"])
    num_plts = image_array_2bands.shape[0]
    all_titles = [ax[i].get_title() for i in range(num_plts)]
    assert all_titles == ["Red Band", "Green Band"]
    plt.close()
Пример #9
0
def test_norm_scale_unset(image_array_2bands):
    """Test that the norm param returns a plot with the correct norm boundaries."""
    norm_bounds = colors.BoundaryNorm([0, 1], 2)
    norm_ax = ep.plot_bands(image_array_2bands, cols=2, norm=norm_bounds)
    for axes in norm_ax:
        assert norm_bounds.boundaries[0] == axes.get_images()[0].norm.vmin
        assert norm_bounds.boundaries[1] == axes.get_images()[0].norm.vmax
Пример #10
0
def test_two_plot_title(image_array_2bands):
    """Test that the default title is provided for a 2 band array plot."""

    ax = ep.plot_bands(image_array_2bands)
    num_plts = image_array_2bands.shape[0]
    all_titles = [ax[i].get_title() for i in range(num_plts)]
    assert all_titles == ["Band 1", "Band 2"]
    plt.close()
Пример #11
0
def test_str_for_title(image_array_2bands):
    """Test that a single string title renders properly."""

    single_band = image_array_2bands[0]
    ax = ep.plot_bands(arr=single_band, title="my title")
    plot_title = ax.get_title()
    assert "my title" in plot_title
    plt.close()
Пример #12
0
def test_num_axes(image_array_2bands):
    """Test the number of axes.

    If provided with a 2 band array, plot_bands should return 3 axes.
    """
    f, ax = ep.plot_bands(image_array_2bands)
    assert len(f.axes) == 3
    plt.close(f)
Пример #13
0
def test_single_band_3dims(one_band_3dims):
    """Test single band plot with three dimensions.

    If you provide a single band array with 3 dimensions (shape[0]==1
    test that it still plots and only returns a single axis.
    """
    ax = ep.plot_bands(one_band_3dims)
    arr = ax.get_images()[0].get_array()
    assert arr.ndim == 2
    assert len(ax.get_images()) == 1
    plt.close()
Пример #14
0
def test_cbar_param(one_band_3dims):
    """Test that the colorbar param works for a single band arr"""
    one_band_2dims = one_band_3dims[0]
    ax = ep.plot_bands(one_band_2dims, scale=True)
    arr = ax.get_images()[0].get_array()
    c_bar = ax.images[0].colorbar

    # Return arr should be scaled by default between 0-255
    assert arr.min() == 0 and arr.max() == 255
    # A cbar should be drawn in this plot
    assert c_bar
    plt.close()
def tif_2index(file,output,vindex):
    naip_data = rxr.open_rasterio(file)

    # View shape of the data
    print(naip_data.shape)
    
    if naip_data.[3] is not None:
        NIR = naip_data[3]
    else:
        pass

    R = naip_data[0]
    G = naip_data[1]
    B = naip_data[2]



    if vindex == 'NDVI':
        naip_ndvi = NDVI_index(NIR, R)
    elif vindex == 'VARI' or 'RGBVI' or 'NGRDI':
        naip_ndvi = VARI_index(R,G,B,vindex)

    #Plot bands
    ep.plot_bands(naip_ndvi,
                cmap='PiYG',
                scale=False,
                vmin=-1, vmax=1,
                title=" Vegetation Index plot")
    plt.show()
    #Plot histogram
    # ep.hist(naip_ndvi.values,
    #         figsize=(12, 6),
    #         title=["NDVI: Distribution of pixels\n NAIP 2015 Cold Springs fire site"])

    # plt.show()

    type(naip_ndvi), naip_ndvi.dtype

    # Write your the ndvi raster object
    naip_ndvi.rio.to_raster(output)
Пример #16
0
def test_single_band_2dims(one_band_3dims):
    """Test single band plot with two dimensions

    If you provide a single band array with 3 dimensions (shape[0] == 1)
    test that it still plots and only returns a single axis.
    """
    single_band_2dims = one_band_3dims[0]
    ax = ep.plot_bands(single_band_2dims)
    # Get array from mpl figure
    arr = ax.get_images()[0].get_array()
    assert arr.ndim == 2
    assert len(ax.get_images()) == 1
    plt.close()
Пример #17
0
def test_num_axes(image_array_2bands):
    """Test the number of axes.

    If provided with a 2 band array, plot_bands should return 3 axes.
    And 2 colorbars
    """
    ax = ep.plot_bands(image_array_2bands)
    ax = list(ax)
    cb = [a.images[0].colorbar for a in ax if a.images]

    assert len(ax) == 3
    assert len(cb) == 2
    plt.close()
Пример #18
0
def test_not_scaled_multi_band(image_array_2bands):
    """Test if the user turns off scaling for multi bands the data vals should remain intact.
    """

    im = image_array_2bands
    ax = ep.plot_bands(im, scale=False)

    # Get all arrays to be plotted
    all_arrs = [a.get_images()[0].get_array() for a in ax if a.get_images()]
    all_arrs_flat = np.concatenate(all_arrs, axis=0)

    # Return arr is unscaled for plotting
    assert all_arrs_flat.min() == im.min() and all_arrs_flat.max() == im.max()
    plt.close()
Пример #19
0
def test_vmin_vmax_single_band(one_band_3dims):
    """Test vmin and max apply properly

    If the data are scaled between -10 and 10 the cbar vals should reflect that.
    """

    one_band_2dims = one_band_3dims[0]
    vmin = 0
    vmax = 10
    ax = ep.plot_bands(one_band_2dims, vmin=vmin, vmax=vmax, scale=False)
    c_bar = ax.images[0].colorbar

    # Cbar should be scaled between the vmin and vmax vals
    assert c_bar.vmin == vmin and c_bar.vmax == vmax
    plt.close()
Пример #20
0
def main():
    all_landsat_post_bands = glob('AOI/cana_band*.tif')
    #'AOI/arroz_band*.tif')
    all_landsat_post_bands.sort()
    landsat_img = []
    landsat_data = []
    band_vectors = []
    cana_bottom_limits = [181, 243, 531, 339, 2281, 1339, 558]
    cana_top_limits = [567, 658, 960, 1081, 3812, 2644, 1982]
    arroz_bottom_limits = [27, 158, 354, 168, 696, 175, 115]
    arroz_top_limits = [720, 830, 1123, 1430, 4060, 3363, 2236]
    for i in range(len(all_landsat_post_bands)):
        landsat_img.append(Image.open(all_landsat_post_bands[i]))
        landsat_data.append(np.array(landsat_img[i]))
        #band_vectors.append(matrix2vector(landsat_data[i], cana_bottom_limits[i], cana_top_limits[i]))
        #band_vectors.append(matrix2vector(landsat_data[i], arroz_bottom_limits[i], arroz_top_limits[i]))

    NIR = matrix3D2matrix2D(landsat_data[3], cana_bottom_limits[3],
                            cana_top_limits[3])
    VIS = matrix3D2matrix2D(landsat_data[0], cana_bottom_limits[0],
                            cana_bottom_limits[0])
    naip_ndvi = es.normalized_diff(NIR, VIS)
    ep.plot_bands(naip_ndvi, cmap="PiYG", scale=False, vmin=-1, vmax=1)
    plt.show()
Пример #21
0
def test_not_scaled_single_band(one_band_3dims):
    """Test if user turns off scaling and cbar the data vals remain intact.

    Also if no cbar is specified it should not render.
    """
    one_band_2dims = one_band_3dims[0]

    ax = ep.plot_bands(one_band_2dims, cbar=False)
    arr = ax.get_images()[0].get_array()
    c_bar = ax.images[0].colorbar

    # Return arr is unscaled for plotting
    assert (arr.min() == one_band_2dims.min()
            and arr.max() == one_band_2dims.max())
    # A cbar should not be drawn in this plot
    assert not c_bar
    plt.close()
Пример #22
0
def test_extent(one_band_3dims):
    """Test that extent param returns a plot with the correct extent."""

    one_band_2dims = one_band_3dims[0]
    # shift extents by 10
    xmin = one_band_2dims.shape[1]
    xmax = one_band_2dims.shape[1] + xmin
    ymin = one_band_2dims.shape[0]
    ymax = one_band_2dims.shape[0] + ymin
    ext = [xmin, xmax, ymin, ymax]

    ax = ep.plot_bands(one_band_2dims, extent=ext)
    pl_extent = list(ax.get_xlim() + ax.get_ylim())

    # Cbar should be scaled between the vmin and vmax vals
    assert pl_extent == ext
    plt.close()
Пример #23
0
def test_vmin_vmax_multi_band(image_array_2bands):
    """Test vmin and max apply properly in multi band images

    If the data are scaled between -10 and 10 the cbar vals should reflect that.
    """

    one_band_2dims = image_array_2bands
    vmin = -10
    vmax = 10
    ax = ep.plot_bands(one_band_2dims, vmin=vmin, vmax=vmax, scale=False)

    # Get all cbars - the min and max vals for all cbars should be -10 and 10
    cb_max = [a.images[0].colorbar.vmax for a in ax if a.images]
    cb_min = [a.images[0].colorbar.vmin for a in ax if a.images]

    assert all(map(lambda x: x == vmin, cb_min))
    assert all(map(lambda x: x == vmax, cb_max))
    plt.close()
Пример #24
0
landsat_path.sort()
array_stack, meta_data = es.stack(landsat_path, nodata=-9999)

###############################################################################
# Plot All Bands in a Stack
# --------------------------
#
# When you give ``ep.plot_bands()`` a three dimensional numpy array,
# it will plot all layers in the numpy array. You can create unique titles for
# each image by providing a list of titles using the ``title=`` parameter.
# The list must contain the same number of strings as there are bands in the
# stack.

titles = ["Ultra Blue", "Blue", "Green", "Red", "NIR", "SWIR 1", "SWIR 2"]
# sphinx_gallery_thumbnail_number = 1
ep.plot_bands(array_stack, title=titles)
plt.show()

###############################################################################
# Plot One Band in a Stack
# ------------------------
#
# If you give ``ep.plot_bands()`` a one dimensional numpy array,
# it will only plot that single band. You can turn off the
# colorbar using the ``cbar`` parameter (``cbar=False``).

ep.plot_bands(array_stack[4], cbar=False)
plt.show()

###############################################################################
# Turn On Scaling
Пример #25
0
fileopen = netCDF4.Dataset(ds, "r")
#Finds the group for data
science = fileopen.groups["science_data"]
#Opens variables for red and blue bands
arr_blue = science.variables["sci_blue"]
arr = science.variables["sci_red"]
#transforms the lists into np arrays for better library functions
arr = np.array(arr)
#Transposes array, from (X, Band, Y) to (Band, X, Y)
arr = arr.transpose(1, 0, 2)
arr_blue = np.array(arr_blue)
arr_blue = arr_blue.transpose(1, 0, 2)

#Plot tool used for debugging and viewing data
fig, ax = plt.subplots(figsize=(6, 6))
ep.plot_bands(arr[10], cmap="Spectral", ax=ax)

#Varaible Initialization
xaxis = list(range(0, fileopen.dimensions["red_bands"].size))
bmean = []
bstd = []
bmin = []
bmax = []
brange = []
mean = []
std = []
mini = []
maxi = []
rrange = []

#Goes through each red band, and computes the values  for each measure, then adds it to array.
Пример #26
0
print(("\nNow doing some data science (running PCA, "
       "then finding your city's nearest neighbors)...\n"))
pca = PCA(n_components=19)
pcs = pca.fit_transform(bioclim_data)

# find nearest neighbor of last row (i.e. target city)
kdt = KDTree(pcs[:-1, ], leaf_size=30, metric='euclidean')
analog_idxs = kdt.query(pcs[-1].reshape((1, pcs.shape[1])), k=50)[1].ravel()
analogs = cities.iloc[analog_idxs][['CITY_NAME', 'CNTRY_NAME']]
print("Here are your top 50 climate sister cities:\n")
print(analogs)

# plot
fig, ax = plt.subplots(figsize=(10, 10))
ep.plot_bands(clim[0, :, :],
              extent=plotting_extent(clim_src),
              cmap='Greys',
              title='%s and its climate sister cities' % target,
              scale=False,
              ax=ax)
cities.iloc[analog_idxs, :].plot(ax=ax,
                                 marker='o',
                                 markersize=100,
                                 cmap='YlGn_r')
cities[cities.CITY_NAME == target].plot(ax=ax,
                                        marker='*',
                                        markersize=100,
                                        color='purple')
ax.set_axis_off()
plt.show()
Пример #27
0
def test_alpha(image_array_2bands):
    """Test that the alpha param returns a plot with the correct alpha."""
    alpha_val = 0.5
    alpha_ax = ep.plot_bands(image_array_2bands, cols=2, alpha=alpha_val)
    for i in range(len(alpha_ax)):
        assert alpha_ax[i].get_images()[0].get_alpha() == alpha_val
Пример #28
0
# Set the home directory and get the data for the exercise
os.chdir(os.path.join(et.io.HOME, "earth-analytics"))
dtm = "data/vignette-elevation/pre_DTM.tif"

# Open the DEM with Rasterio
with rio.open(dtm) as src:
    elevation = src.read(1)
    # Set masked values to np.nan
    elevation[elevation < 0] = np.nan

# Plot the data
ep.plot_bands(
    elevation,
    scale=False,
    cmap="gist_earth",
    title="DTM Without Hillshade",
    figsize=(10, 6),
)
plt.show()

####################################################################################
# Create the Hillshade
# --------------------
# Once the DEM is read in, call ``es.hillshade()`` to create the hillshade.

# Create and plot the hillshade with earthpy
hillshade = es.hillshade(elevation)

ep.plot_bands(
    hillshade,
Пример #29
0
import rasterio as rio
import geopandas as gpd
import earthpy as et
import earthpy.spatial as es
import earthpy.plot as ep

# Download data and set working directory
data = et.data.get_data('cold-springs-fire')
os.chdir(os.path.join(et.io.HOME, 'earth-analytics'))

naip_data_path = os.path.join("data", "cold-springs-fire", "naip",
                              "m_3910505_nw_13_1_20150919", "crop",
                              "m_3910505_nw_13_1_20150919_crop.tif")

with rio.open(naip_data_path) as src:
    naip_data = src.read()

# View shape of the data
naip_data.shape

naip_ndvi = es.normalized_diff(naip_data[3], naip_data[0])

ep.plot_bands(
    naip_ndvi,
    cmap='PiYG',
    scale=False,
    vmin=-1,
    vmax=1,
    title="NAIP Derived NDVI\n 19 September 2015 - Cold Springs Fire, Colorado"
)
plt.show()
#should line up to World Geodetic System (WGS) 1984 (EPSG: 4326), since I did not reproject this to another project system

# converting the ESPG string over to a proj4 string:
proj4 = et.epsg['4326']
print(proj4) #confirms that this is a WGS84 DEM (straight from STRM, prior to reprojection)

#raster resolution:
src.res #should show(0.0008333333333333333, 0.0008333333333333332), which reflects the number of DEGREES shown in each raster cell

# Plotting the Rasters in Different Ways
# 
# First, plotting the normal raster!

ep.plot_bands(lidar_dem_im,
              cmap='Greys',
              extent=spatial_extent,
              title="Digital Elevation Model (DEM), \n Shuttle Radar Topography Mission (SRTM), NASA \n  Western Uganda",
              cbar=False) #think about removing cmap statement and plotting straight black-white raster

plt.show()

#similar plot, using both matplotlib and earthpy, to create an extra color bar and adding extra titles

fig, ax = plt.subplots(figsize=(12, 10))
ep.plot_bands(lidar_dem_im,
              cmap='Greys',
              extent=spatial_extent,
              scale=False,
              ax=ax)
ax.set_title("Digital Elevation Model \n Shuttle Radar Topography Mission (SRTM), NASA \n , Western Uganda", fontsize=24)
plt.show()