# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# # Determine Diversion Flows for a hypothetical Scenario

# + [markdown] tags=[]
#   Created on  1/12/2021                                                      
#   Designed for => Python 3.7.6, adapted for Jupyter notebook                
#   @author: <NAME>                                        
#   Email: <EMAIL>                                                                        
#   Last: modified ____________                                               
#
# #### Script looks at flow from station 401211A for the period of data 1968 to 2021 and determines:
#     
#     1) How many years during the period of record, can we divert the 100GL
#     target while complying with hypothetical flow thresholds and diversion
#     rules for this location
#     
#     2) How many days each year is there a flow excedent where water can be 
#        diverted
# -

# ### Import Packages

import pandas as pd
import os
import matplotlib.pyplot as plt
import numpy as np
# %matplotlib inline

# ### Specify the path to the data file and create an output folder to save the figures

# +
folder_path = os.getcwd() 
flow_file = "401211a_historical.csv"

# Change to the directory where the .dat file is located
os.chdir(folder_path)
fig_dir = 'figures'

# Create a folder to store the figures
if not os.path.exists("figures"):
    print("create figures folder")
    os.mkdir(fig_dir)
# -

# ### Read in the .csv file and create a dataframe

df = pd.read_csv(flow_file, index_col=0, header = 2, parse_dates=True)
df = df.iloc[2:]
df.dropna(how="all", inplace=True)
df["Discharge (ML/Day)"] = df["Discharge (ML/Day)"].astype(float)

# ### Specify the flow threshold and diversion rules to determine when and how much water can be diverted
#
# We have two conditions we need to follow:
#
#     We can't divert water if the flow is under 500 MG (ie. flow threshold)
#     If flow is above 500 MG we can only divert half of the excedent (ie. [flow - flow threshold] * 0.5)

# +
#Flow threshold (ML) under which NO water can be diverted 
flow_threshold = 500

# Diversion of flow allowed above threshold
diversion_rule = 0.5 

conditions = (df["Discharge (ML/Day)"] <= flow_threshold, 
              df["Discharge (ML/Day)"] > flow_threshold) 

div_values = (0, (df["Discharge (ML/Day)"] - flow_threshold) * diversion_rule)

#Create a new column with the calculated diversion values using the conditions above
df['Diversion (ML/Day)'] = np.select(conditions, div_values)
# -

# ### Resample the data to obtain yearly values of the total flows that can be diverted

# + tags=[]
df_yearly = df.resample('Y').sum()
              
# Rename columns units to ML/year
df_yearly.rename(columns={'Discharge (ML/Day)':"Discharge (ML/Year)",
                          "Diversion (ML/Day)" :'Diversion (ML/Year)'},
                 inplace=True)
# -

# Now we can determine how many years for this historical dataset we could have complied with the diversion target

# +
diversion_target = 100 #(GL)

conditions = ((df_yearly["Discharge (ML/Year)"]/1000) < flow_threshold,
              (df_yearly["Diversion (ML/Year)"]/1000) >= diversion_target) 

div_values = ("no", "yes")

# Create a column which tell us if the diversion target was met or not
df_yearly['target_met'] = (np.select(conditions, div_values))

# Calculate how many years do we meet the diversion target during these period of record
diversion_years = df_yearly['target_met'].value_counts()['yes']

# BONUS QUESTION: How many days during each year can we divert water (flows are above threshold)
no_divdays_year = (df["Diversion (ML/Day)" ] > 0).resample('Y').sum().astype(int)


# -

# ### The number of years from 1968 to 2021 that the diversion target is met is

print ((diversion_years))

# We can see how many days each year had flows above the diversion threshold

print(no_divdays_year)

# ### Create a couple of figures to sumarize the data

# + tags=[]
# Set up plotting specs
plt.rc("axes", linewidth=0.5)
plt.rcParams.update({'font.size': 12})
plt.rcParams.update({'legend.labelspacing':0.25})
plt.matplotlib.rc('font', **{'sans-serif' : 'Arial','family' : 'sans-serif'}) 
plt.rcParams['lines.linewidth'] = 1.0

# +
#----------Fig 1 Number of days per year where flow is above threshold

fig = plt.figure(figsize=(8, 9))
ax = fig.add_subplot(111)
plot1 = no_divdays_year.plot(ax=ax)

ax.set_xlabel('Date')
ax.set_ylabel('No. days above flow threshold per year')
ax.set_title("Station 401211A")  
plt.savefig(os.path.join(fig_dir, "Total_days_above_threshold(Y)" + '.png'),
            bbox_inches = "tight", dpi=300)

# +
#----------Fig 2 Years where the total amount of allowed diverted flows exceed 
#----------      the diversion target of 100 GL
fig = plt.figure(figsize=(8, 9))
ax = fig.add_subplot(111)
plot1 = df_yearly["Diversion (ML/Year)"].plot(ax=ax)

plt.axhline(y=(diversion_target*1000), color='r', linestyle='-')

props = dict(boxstyle='round', facecolor='wheat', alpha=0.95)

plt.text(0.405, 0.13, "Diversion Target = 100 GL", transform=ax.transAxes,
         fontsize=10,  bbox=props)

ax.set_xlabel('Date')
ax.set_ylabel('Total Yearly Allowed Diversion (ML)')
ax.set_title("Station 401211A")  
plt.savefig(os.path.join(fig_dir, "Yearly_allowed_diversion(MG)" + '.png'),
            bbox_inches = "tight", dpi=300)

# -



StarcoderdataJupyterScriptsDedupFiltered