<jupyter_start><jupyter_text>Table of Contents1&nbsp;&nbsp;Introduction2&nbsp;&nbsp;Get bands 3, 4, 5 fullsize (green, red, near-ir)3&nbsp;&nbsp;This cell reads in your affine transform, metadata and profile4&nbsp;&nbsp;This cell gets the right reflection function for your satellite5&nbsp;&nbsp;Define a subscene window and a transform6&nbsp;&nbsp;Read only the window pixels from the band 3, 4, 5 files7&nbsp;&nbsp;In the next cell calculate your ndvi8&nbsp;&nbsp;In the next cell plot a mapped ndvi image with a red dot in your ul corner and a white dot in your lr corner  IntroductionThere are 4 cells that ask for changes below, the rest should run as long as youuse the variable names I ask for in the questions.<jupyter_code>import rasterio
import a301
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.colors import Normalize
from a301.landsat.landsat_metadata import landsat_metadata
import cartopy
from rasterio.windows import Window
from pyproj import transform as proj_transform
from pyproj import Proj
from a301.landsat.toa_reflectance import calc_reflc_8
import pprint
from a301.utils.data_read import download
from pathlib import Path
from affine import Affine
from IPython.display import Image
from a301.landsat.toa_reflectance import calc_refl_457, calc_reflc_8
from mpl_toolkits.axes_grid1 import make_axes_locatable<jupyter_output><empty_output><jupyter_text>Get bands 3, 4, 5 fullsize (green, red, near-ir)At the end of this cell you shiould have the following path objects for your spring scene:meta_bigfile, band3_bigfile, band4_bigfile, band5_bigfilethat point to your landsat TIF and mtl.txt files.<jupyter_code>### BEGIN SOLUTION
band_tifs=['B5.TIF','B4.TIF','B3.TIF','MTL.txt']
dict_keys=['band5','band4','band3','mtl']
landsat8=False
if landsat8:
    root="LC08_L1TP_047026_20150614_20180131_01_T1_"
    prefix_download=Path('landsat_scenes/l8_vancouver')
    prefix_local=Path("landsat8/vancouver")
else:
    root="LE07_L1TP_047026_20180513_20180610_01_T1_"
    prefix_download=Path('landsat_scenes/l7_vancouver')
    prefix_local=Path("landsat7/vancouver")
    
name_dict=dict()
for key,tiff_string in zip(dict_keys,band_tifs):
    name_dict[key]=f"{root}{tiff_string}"
    
dest_folder=a301.data_dir / prefix_local
dest_folder.mkdir(parents=True, exist_ok=True)

for key, the_file in name_dict.items():
    landsat_tif = prefix_download / Path(the_file)
    download(str(landsat_tif),dest_folder=dest_folder)
    

band5_bigfile=list(dest_folder.glob(name_dict['band5']))[0]    
band4_bigfile=list(dest_folder.glob(name_dict['band4']))[0]    
band3_bigfile=list(dest_folder.glob(name_dict['band3']))[0]
meta_bigfile=list(dest_folder.glob(name_dict['mtl']))[0]
### END SOLUTION<jupyter_output>trying https://clouds.eos.ubc.ca/~phil/courses/atsc301/downloads/landsat_scenes/l7_vancouver/LE07_L1TP_047026_20180513_20180610_01_T1_B5.TIF
writing to: /Users/phil/repos/a301_code/data/landsat7/vancouver/LE07_L1TP_047026_20180513_20180610_01_T1_B5.TIF

LE07_L1TP_047026_20180513_20180610_01_T1_B5.TIF already exists
and is 61402888 bytes
will not overwrite

trying https://clouds.eos.ubc.ca/~phil/courses/atsc301/downloads/landsat_scenes/l7_vancouver/LE07_L1TP_047026_20180513_20180610_01_T1_B4.TIF
writing to: /Users/phil/repos/a301_code/data/landsat7/vancouver/LE07_L1TP_047026_20180513_20180610_01_T1_B4.TIF

LE07_L1TP_047026_20180513_20180610_01_T1_B4.TIF already exists
and is 61402888 bytes
will not overwrite

trying https://clouds.eos.ubc.ca/~phil/courses/atsc301/downloads/landsat_scenes/l7_vancouver/LE07_L1TP_047026_20180513_20180610_01_T1_B3.TIF
writing to: /Users/phil/repos/a301_code/data/landsat7/vancouver/LE07_L1TP_047026_20180513_20180610_01_T1_B3.TIF

LE07_L1TP_047026_20180513_20[...]<jupyter_text>This cell reads in your affine transform, metadata and profileUsing band4_bigfile (arbitrary)<jupyter_code>metadata=landsat_metadata(meta_bigfile)
with rasterio.open(band4_bigfile) as raster:
    big_transform=raster.transform
    big_profile=raster.profile

zone = metadata.UTM_ZONE  
crs = cartopy.crs.UTM(zone, southern_hemisphere=False)
p_utm=Proj(crs.proj4_init)
p_lonlat=Proj(proj='latlong',datum='WGS84')<jupyter_output>Scene LE70470262018133EDC00 center time is 2018-05-13 19:01:40<jupyter_text>This cell gets the right reflection function for your satellite<jupyter_code>refl_dict={'LANDSAT_7':calc_refl_457,'LANDSAT_8':calc_reflc_8}         
satellite=metadata.SPACECRAFT_ID
refl_fun=refl_dict[satellite]<jupyter_output><empty_output><jupyter_text>Define a subscene window and a transformIn the cell below, get the upper left col,row (ul_col,ul_row) and upper left and lowerright x,y (ul_x,ul_y,lr_x,lr_y)coordinates the upper left corner of your subscene as in the image_zoom notebook.  Use ul_col, ul_row, ul_x, ul_y plus your subscenewidth and height to make a rasterio window and new transform.    window=Window(ul_col, ul_row, small_width, small_height)    new_affine=Affine(30.,0.,ul_x,0.,-30.,ul_y)    extent = [ul_x,lr_x,lr_y,ul_y]<jupyter_code>### BEGIN SOLUTION
ubc_lon = -123.2460
ubc_lat = 49.2606
ubc_x, ubc_y =proj_transform(p_lonlat,p_utm,ubc_lon, ubc_lat) 
ubc_col, ubc_row = ~big_transform*(ubc_x,ubc_y)
ubc_col, ubc_row = int(ubc_col), int(ubc_row)
l_col_offset= -100
t_row_offset= -100
width=200
height=200
ul_col=ubc_col + l_col_offset
ul_row=ubc_row + t_row_offset
ul_x,ul_y = big_transform*(ul_col,ul_row)
lr_x,lr_y = big_transform*(ul_col + width, ul_row + height)
small_window=Window(ul_col, ul_row, width, height)
new_affine=Affine(30.,0.,ul_x,0.,-30.,ul_y)
extent = [ul_x,lr_x,lr_y,ul_y]
### END SOLUTION<jupyter_output><empty_output><jupyter_text>Read only the window pixels from the band 3, 4, 5 files<jupyter_code>metadata=str(meta_bigfile)
refl_dict=dict()
for bandnum,filepath in zip([3,4,5],[band3_bigfile,band4_bigfile,band5_bigfile]):
    with rasterio.open(filepath) as src:
        counts = src.read(1, window=small_window)
        counts=counts.astype(np.float32)
        counts[counts==0.]=np.nan
        #counts = src.read(1)
        refl_vals = refl_fun(counts,bandnum,metadata)
        refl_dict[bandnum]=refl_vals
metadata=landsat_metadata(meta_bigfile)
plt.hist(counts[~np.isnan(counts)].flat);
plt.imshow(refl_dict[4])<jupyter_output><empty_output><jupyter_text>In the next cell calculate your ndviSave it in a variable called ndvi<jupyter_code>### BEGIN SOLUTION
ndvi = (refl_dict[5] - refl_dict[4])/(refl_dict[5] + refl_dict[4])
### END SOLUTION
plt.hist(ndvi[~np.isnan(ndvi)].flat);
plt.hist(ndvi[~np.isnan(ndvi)].flat);
plt.title('spring ndvi')
plt.savefig('spring_ndvi.png')<jupyter_output><empty_output><jupyter_text>In the next cell plot a mapped ndvi image with a red dot in your ul corner and a white dot in your lr cornerAdjust this plot to fit your image.  Just delete the bottom line and work with the provided commands<jupyter_code>vmin=0.0
vmax=0.8
the_norm=Normalize(vmin=vmin,vmax=vmax,clip=False)
palette='viridis'
pal = plt.get_cmap(palette)
pal.set_bad('0.75') #75% grey for out-of-map cells
pal.set_over('w')  #color cells > vmax red
pal.set_under('k')  #color cells < vmin black
fig, ax = plt.subplots(1, 1,figsize=[10,15],
                       subplot_kw={'projection': crs})
col=ax.imshow(ndvi,origin="upper",
         extent=extent,transform=crs)
ax.plot(ul_x,ul_y,'ro',markersize=50)
ax.plot(lr_x,lr_y,'wo',markersize=50)
ax.set(title="spring ndvi")
cbar_ax = fig.add_axes([0.95, 0.2, 0.05, 0.6])
cbar=ax.figure.colorbar(col,extend='both',cax=cbar_ax,orientation='vertical')
cbar.set_label('ndvi index')
### BEGIN SOLUTION
#your plot should appear below
### END SOLUTION<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10727367870225013, 'fraction_numerical': 0.0706436420722135, 'mean_word_length': 6.91407867494824, 'pattern_counts': {'":': 0, '<': 32, '<?xml version=': 0, '>': 32, 'https://': 3, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '412334', 'license': 'MIT', 'n_tokens_mistral': 3300, 'n_tokens_neox': 2966, 'n_words': 571, 'path': 'notebooks/multichan_assignment.ipynb', 'repo_name': 'Pearl-Ayem/ATSC_Course_Work', 'size': '7644'}