<jupyter_start><jupyter_text>Modeling and Predicting Shark Population  I.	Introduction The purpose of this simulation is to predict the influence of ocean pollution on the population decline of Shortfin Mako Sharks in Atlantic Canada. To achieve this goal, we made a model of shark population declination based on the data from 1970 to 2002, and predicted a correlated relationship between the increasing ocean pollution and the decrease in shark population. Furthermore, we made projections based on the correlation we found, and predicted the future trend of shark population with different pollution levels. In order to make the model more realistic, we introduced a normally-distributed decline rate.  II. Importing Python Libraries In the following essay, the libraries used include ModSim.py module, pandas (read_html), matplotlib.pyplot and numpy.<jupyter_code># Configure Jupyter so figures appear in the notebook
%matplotlib inline

# Configure Jupyter to display the assigned value after an assignment
%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'

# import functions from the modsim.py module
from modsim import *

from pandas import read_html
# Configure Jupyter to display the assigned value after an assignment
%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'

# import functions from the modsim.py module and additional functions for normal distributions
from modsim import *

from pandas import read_html

import matplotlib.pyplot as plt
import numpy as np
import random<jupyter_output><empty_output><jupyter_text>III. Importing Data In this part, we import the data of Shortfin Mako Sharks in Atlantic Canada from Canadian Science Advisory Secretariat, and the data of cumulative global plastics production, which is later converted into the pollution data used in the following model. We plot the graph of shark population as well as pollution against time, and generate a mathematical formula in Matlab to discribe the trend of them. It is clearly shown that the trend of population of shark slopes downwards as while pollution increases.<jupyter_code>#Import data as csv and then set columns as variables
table=pd.read_csv('data/FishDataRefined.csv')
year=table.Year
pollution=table.Pollution
sharks=table.Sharks
print(table)
# make a simple plot of sharks from the original data
plot(year,sharks,"ro")

decorate(xlabel='Year', 
             ylabel='Sharks per 100 hooks',
             title='Sharks over Time')

#find a regression equation for sharks
sharkModelExp=1.795*exp(-0.02435*((year-1970))) # regression equation
plot(year,sharks,"ro")

plot(year,sharkModelExp)
decorate(xlabel='Year', 
             ylabel='Sharks per 100 hooks',
             title='Sharks over Time',xlim=[1970,2005],ylim=[0,3])
# plot a simple graph of pollution over time
plot (year,pollution)
decorate(xlabel='Year', 
             ylabel='Plastic in Ocean (Million Tons)',
             title='Plastic in Ocean over Time')<jupyter_output><empty_output><jupyter_text>The graph below shows the growth rate per year of the shark population from 1970 to 2002<jupyter_code># plot growth rate of sharks as derivative of amount
sharkRateReg2=-29747643494751453184 *exp(-0.02435 *table.Year) #The derivative of the regression equation for sharks(From Matlab)
plot(year[0:31],(sharkRateReg2/sharks)[0:31],'*' ) #plot the rate of shark reproduction per shark, aka growth rate
decorate(xlabel='Year', 
             ylabel='Shark Net Growth Rate(New Sharks/Shark))',
             title='Shark Annual Net Growth Rate')<jupyter_output><empty_output><jupyter_text>Now the rate of pollution and sharks are graphed and fitted with linear aproximations<jupyter_code># create a function that finds the rate of change of a data set
def rate_finder(data):
    rate=[]
    for i in linrange(1, 32, 1):
        rate.append(data[i]-data[i-1])
    return rate

# run the function on the pollution data
pollutionRate=rate_finder(pollution)


plot(linrange(1, 32, 1)+1970,pollutionRate)     #Plot pollution rate and find a fit function for it
pollutionRateLin=(7000/30)*(linrange(1, 32, 1)) #the fit function
plot(linrange(1, 32, 1)+1970,pollutionRateLin)

decorate(xlabel='Year', 
             ylabel='Pollution Rate (million tons per year)',
             title='Plastic Pollution Rate (Linearized)')
# find a relationship between sark rate and pollution
plot(pollution[0:31],(sharkRateReg2/sharks)[0:31],'*' ) #plot initial data

plot(pollution[0:31],-.000000007*pollution[0:31]-.025)  #This is the final equation relating pollution to shark rates that can be put into the probability function.
decorate(xlabel='Pollution (Million Tons)', 
             ylabel='Net Shark Growth Rate',
             title='Shark rate per shark per pollution')<jupyter_output><empty_output><jupyter_text>V. Adding Randomness into the Model In this part, by applying the normal distribution function in numpy, we generated a probability curve of the shark population decline rate. The decline rate is normally distributed and randomly selected, which means the further the value deviates from mean value, the less possible for it to occur. The standard deviation of this normal distribution is generated from the standard diviation of decline rate from past data. The following graph shows the case when mean is chosen to be 0.4.<jupyter_code># define a normal distribution function
def norm(mu, sigma, size):
    s = np.random.normal(mu, sigma,size)
    return s

# set a variable s to this distribution
s = norm(0.4, 0.0034,1000)

# plot a histogram of the data
count, bins, ignored = plt.hist(s, 30, density=True)

# plot a bell curve of histogram
def plot_norm(mean, sd):
    plot(bins, 1/(sd * np.sqrt(2 * np.pi)) * np.exp( - (bins - mean)**2 / (2 * sd**2) ), linewidth=3, color='y')

    decorate(xlabel='Growth Rate', 
             ylabel='Number of occurences',
             title='Normal Distribution Curve Histogram')

plot_norm(0.4, 0.0034)<jupyter_output><empty_output><jupyter_text>VI. Projection of Shark Population In the following part, we generated a projection based on the formula we got in the parts above. We run the simulation for three different pollution rates and plot the results to show the influence of pollution rate to shark population.<jupyter_code># define a simulation that will plot shark rates into the future based on plastic input

def Simulation(a):
    # define series
    pollutionRate=TimeSeries()
    SharkRate=TimeSeries()
    sharksnumber=TimeSeries()
    
    # define initial conditions
    pollutionRate[1971]=700/3
    sharksnumber[1971]=1.63
    pollution[1971]=9866.8878
    SharkRate[1971]=-.00000007*pollution[1971]-.02
    
    # run loop from 1971 to 2102
    for i in linrange(1971,2102):
        pollutionRate[i]=a*(i-1970)
        pollution[i+1] = pollution[i]+pollutionRate[i]
        SharkRate[i+1]= random.choice(norm(-.0000000007*pollution[i]-.001, .0034,1))
        sharksnumber[i+1]= sharksnumber[i]+sharksnumber[i]*SharkRate[i]
    return sharksnumber
    
    
# run the simulation for three different pollution rates and plot the results
sharkProjection=Simulation(700/3) #keep polluting
sharkProjection2=Simulation(0) #stop polluting
sharkProjection3=Simulation(-700/3) #clean pollution
plot(sharkProjection,label = 'current pollution rate')
plot(sharkProjection2,label = 'stop polltution immediately')
plot(sharkProjection3, label = 'start cleaning up pollution')

decorate(xlabel='Year', 
             ylabel='Sharks per 100 hooks',
             title='Shark Projection until 2102', xlim=[1971,2102])<jupyter_output>C:\Miniconda3\lib\site-packages\ipykernel_launcher.py:12: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  if sys.path[0] == '':<jupyter_text>We also create a new simulation to show the shark population at the mean and at +- 1 standard deviation.<jupyter_code># run a simulation to show shark amounts at the mean and at +- 1 standard deviations from it

def Simulation(a,b):
    # define series
    pollutionRate=TimeSeries()
    SharkRate=TimeSeries()
    sharksnumber=TimeSeries()
    
    # define initial conditions
    pollutionRate[1971]=700/3
    sharksnumber[1971]=1.63
    pollution[1971]=9866.8878
    SharkRate[1971]=-.00000007*pollution[1971]-.02
    
    # run loop
    for i in linrange(1971,2102):
        pollutionRate[i]=a*(i-1970)
        pollution[i+1] = pollution[i]+pollutionRate[i]
        SharkRate[i+1]= b+(-.0000000007*pollution[i]-.001)
        sharksnumber[i+1]= sharksnumber[i]+sharksnumber[i]*SharkRate[i]
    return sharksnumber
    
# plot three graphs for each pollution condition (mean, +1 sd, -1 sd)
sharkProjection=Simulation(700/3,.0034)
sharkProjection2=Simulation(700/3,-.0034)
sharkProjection3=Simulation(0,.0034)
sharkProjection4=Simulation(0,-.0034)
sharkProjection5=Simulation(-700/3,.0034)
sharkProjection6=Simulation(-700/3,-.0034)
sharkProjection7=Simulation(700/3,0)
sharkProjection8=Simulation(0,0)
sharkProjection9=Simulation(-700/3,0)

plot(sharkProjection,':',label = 'current pollution rate', color='b')
plot(sharkProjection2,':', color='b')
plot(sharkProjection7, color='b')
plot(sharkProjection3,':',label = 'stop polluting', color='y')
plot(sharkProjection4,':', color='y')
plot(sharkProjection8, color='y')
plot(sharkProjection5,':',label = 'clean up pollution', color='g')
plot(sharkProjection6,':', color='g')
plot(sharkProjection9, color='g')

decorate(xlabel='Year', 
             ylabel='Sharks per 100 hooks',
             title='Shark Projection until 2102 (+-1 sd)', xlim=[1971,2102])<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.09404872032069071, 'fraction_numerical': 0.04573954157672937, 'mean_word_length': 4.812425328554361, 'pattern_counts': {'":': 0, '<': 28, '<?xml version=': 0, '>': 28, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 5, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '139391', 'license': 'MIT', 'n_tokens_mistral': 3184, 'n_tokens_neox': 2849, 'n_words': 980, 'path': 'code/SharkProjectNew.ipynb', 'repo_name': 'colinmsnow/ModSimPy', 'size': '9729'}