> For the complete documentation index, see [llms.txt](https://hydrosense.gitbook.io/ildas/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hydrosense.gitbook.io/ildas/tutorials/validating-streamflow.md).

# Validating Streamflow

The tutorial contains python code required to validate streamflow at a given location (lat/lon)

Load the required libraries

````
```
import xarray as xr
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.ticker import FormatStrFormatter
import scienceplots
plt.style.use(['science','no-latex'])
plt.rc('font', weight='heavy')
plt.rcParams['text.latex.preamble'] = r'\usepackage{sfmath} \boldmath'
```
````

A utility function to reformat grid to lat/lon in ILDAS outputs

````
```
def reformatData(lisFile):
    """Reformats dimensions of LIS outputs for easier handling and updates global attributes
    Parameters: 
        lisFile: LIS output xarray dataset with NS/EW dimensions
    Returns: 
        LIS output netCDF file with lat/lon dimensions
        And Modified Attributes
    """
    xmin=lisFile.attrs['SOUTH_WEST_CORNER_LON']
    ymin=lisFile.attrs['SOUTH_WEST_CORNER_LAT']
    dx=lisFile.attrs['DX']
    dy=lisFile.attrs['DY']
    nx=lisFile.dims['east_west']
    ny=lisFile.dims['north_south']

    lonarr=np.arange(xmin, xmin + dx * nx, dx) #Creates latitude array
    latarr=np.arange(ymin, ymin + dy * ny, dy) #Creates longitude array

    refLIS=lisFile.rename({'north_south':'lat', 'east_west':'lon'}) 
    refLIS=refLIS.assign_coords({"lon": lonarr, 
                                "lat": latarr})
    return(refLIS)
```
````

Load and reformat ILDAS "ROUTING" netcdf data for "n" months

````python
```
lisData_raw = xr.open_mfdataset('./ildas_data/ROUTING/2014*/*HIST*',combine='by_coords')
lisData_formatted = reformatData(lisData_raw)
```
````

Extract streamflow time-series at given lat/lon in a pandas dataframe (or series)

````
```
latitude = 22.9158
longitude = 78.3475
stationName = 'Sandia'
basinName = 'Narmada'
sim_streamflow = lisData_formatted['Streamflow_tavg'].sel(lat=latitude,lon=longitude,method='nearest').to_dataframe()
```
````

Load observed streamflow data and clip to simulated timeseries start and end dates

```python
sim_start_date = pd.to_datetime('2014-01-01')
sim_end_date = pd.to_datetime('2014-12-31')
obs_streamflow = pd.read_csv('./observed_data/sandia_Narmada.csv',index_col="Date")
obs_streamflow.index = pd.to_datetime(obs_streamflow.index)
obs_streamflow = obs_streamflow[(obs_streamflow.index >= sim_start_date)& (obs_streamflow.index<=sim_end_date)]
```

Plot an observed vs simulated hydrograph

````
```
fig, ax = plt.subplots(1, 1, figsize=(5, 3),facecolor='white',dpi = 600,constrained_layout=True)
ax.plot(obs_streamflow.index, obs_streamflow['Streamflow (cumecs)'],label = 'Observed',alpha=1,color='red',linestyle='-',linewidth=1)
ax.plot(sim_streamflow.index, sim_streamflow['Streamflow_tavg'],label = f'Simulated',alpha=1,color='blue',linestyle="-",linewidth=1)
ax.set_title(f'Gauge Station:{stationName}, River Basin:{basinName}',weight='bold')
ax.set_ylabel('Daily Streamflow ($\mathregular{m^{3}s^{-1}}$)',weight='bold')
ax.legend( loc='upper left',fontsize=8)
ax.tick_params('x', labelrotation=45)
ax.xaxis.set_tick_params(which='both', bottom=True, top=False)
ax.yaxis.set_tick_params(which='both', left=True, right=False)
```
````

<figure><img src="https://3805975816-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVenhYSMRvvQyeJkqAwbc%2Fuploads%2FcEOm5RHdwSw622prdtOY%2Fimage.png?alt=media&amp;token=2dfdd2e3-4dfb-481e-a2fa-64ae4b332a6a" alt=""><figcaption></figcaption></figure>
