<jupyter_start><jupyter_text>**Template OP on salish**<jupyter_code>%matplotlib inline

import sys
import xarray as xr
import numpy as np
import os
import math
from datetime import datetime, timedelta
from parcels import FieldSet, Field, VectorField, ParticleSet, JITParticle, ErrorCode, ParcelsRandom

sys.path.append('/home/jvalenti/MOAD/analysis-jose/notebooks/parcels')
from Kernels_biofilm import DeleteParticle, Buoyancy, AdvectionRK4_3D, Stokes_drift, Beaching, Unbeaching
from OP_functions_biofilm import *
# Define paths
local = 0 #Set to 0 when working on server
paths = path(local)
path_NEMO = make_prefix(datetime(2018, 1, 10), paths['NEMO'])
coord=xr.open_dataset(paths['coords'],decode_times=False)
WW3 = xr.open_dataset(get_WW3_path(datetime(2018, 1, 10)))
batt=xr.open_dataset(paths['mask'],decode_times=False)<jupyter_output><empty_output><jupyter_text>Define and save mask for distance to coast<jupyter_code>Dat=xr.open_dataset(paths['coords'],decode_times=False)
outf_lat=Dat['nav_lat'][445,304]
outf_lon=Dat['nav_lon'][445,304]
clon, clat = [float(outf_lon)],[float(outf_lat)]  # choose horizontal centre of the particle cloud
# #clat,clon = p_unidist(coord.gphif[0,:,:],coord.glamf[0,:,:],batt.mbathy[0,:,:],10,10)
# with open('clat.txt') as f:
#     clat = f.read()
#     clat= clat[1:-1]
#     clat0 = clat.split(",")
#     f.close()
# with open('clon.txt') as f:
#     clon = f.read()
#     clon=clon[1:-1]
#     clon0 = clon.split(",")
#     f.close()
    
# clat,clon=[],[]
# for i in range(len(clat0)):
#     clat.append(float(clat0[i]))
#     clon.append(float(clon0[i]))<jupyter_output><empty_output><jupyter_text>Definitions<jupyter_code>start = datetime(2020, 1, 1) #Start date
# Set Time length [days] and timestep [seconds]
length = 5
duration = timedelta(days=length)
dt = 90 #toggle between - or + to pick backwards or forwards
N = 1 # number of deploying locations
n = 1 # 1000   # number of particles per location
dmin = 68 #minimum depth
dd = 5 #max depth difference from dmin
x_offset, y_offset, zvals = p_deploy(N,n,dmin,dd)
from parcels import Variable

class MPParticle(JITParticle):        
    #ro = Variable('ro', initial = 1025)           
    #diameter = Variable('diameter', initial = 1.6e-5)
    #length = Variable('length', initial = 61e-5)
    Lb = Variable('Lb', initial = 0.23)  #days needed in days for particle to have 67% probability of beaching if in beaching zone (500m)
    Db = Variable('Db', initial = 33) #Distance at which particles can randomly beach.
    Ub = Variable('Ub', initial = 69)  #days to have 67% probability of unbeaching
    sediment = Variable('sediment', initial = 0)
    beached = Variable('beached', initial = 0)
    Ws = Variable('Ws', initial =  2.3e-3) #200m/dia
    tau = Variable('tau', initial =  0) # track age particle
lon = np.zeros([N,n])
lat = np.zeros([N,n])
for i in range(N):
    lon[i,:]=(clon[i] + x_offset[i,:])
    lat[i,:]=(clat[i] + y_offset[i,:])
z = zvals
#Set start date time and the name of the output file
name = 'fibreS2' #name output file
daterange = [start+timedelta(days=i) for i in range(length)]
fn =  name + '_'.join(d.strftime('%Y%m%d')+'_1n' for d in [start, start+duration]) + '.nc'
outfile = os.path.join(paths['out'], fn)
print(outfile)<jupyter_output>/home/jvalenti/MOAD/results/fibreS220200101_1n_20200106_1n.nc<jupyter_text>Simulation<jupyter_code>#Fill in the list of variables that you want to use as fields
varlist=['U','V','W','R']
filenames,variables,dimensions=filename_set(start,length,varlist,local)
field_set=FieldSet.from_nemo(filenames, variables, dimensions, allow_time_extrapolation=True)

varlist=['US','VS','WL']
filenames,variables,dimensions=filename_set(start,length,varlist,local)

us = Field.from_netcdf(filenames['US'], variables['US'], dimensions,allow_time_extrapolation=True)
vs = Field.from_netcdf(filenames['VS'], variables['VS'], dimensions,allow_time_extrapolation=True)
wl = Field.from_netcdf(filenames['WL'], variables['WL'], dimensions,allow_time_extrapolation=True)
field_set.add_field(us)
field_set.add_field(vs)
field_set.add_field(wl)
field_set.add_vector_field(VectorField("stokes", us, vs, wl))

filenames,variables,dimensions=filename_set(start,length,['Bathy'],local)
Bth = Field.from_netcdf(filenames['Bathy'], variables['Bathy'], dimensions,allow_time_extrapolation=True)
field_set.add_field(Bth)
# #Load Salish output as fields
#field_set = FieldSet.from_nemo(filenames, variables, dimensions, allow_time_extrapolation=True)
pset = ParticleSet.from_list(field_set, MPParticle, lon=lon, lat=lat, depth=z, repeatdt = timedelta(hours=1))

k_sink = pset.Kernel(Buoyancy)
k_waves = pset.Kernel(Stokes_drift)
k_beach = pset.Kernel(Beaching)
k_unbeach = pset.Kernel(Unbeaching)


pset.execute(AdvectionRK4_3D + k_sink + k_waves + k_beach + k_unbeach,
             runtime=duration, 
             dt=dt,
             output_file=pset.ParticleFile(name=outfile, outputdt=timedelta(hours=1)),
             recovery={ErrorCode.ErrorOutOfBounds: DeleteParticle})<jupyter_output>/home/jvalenti/conda_envs/parcels/lib/python3.9/site-packages/numpy/lib/arraysetops.py:270: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
  ar = np.asanyarray(ar)
INFO: Compiled ArrayMPParticleAdvectionRK4_3DBuoyancyStokes_driftBeachingUnbeaching ==> /tmp/parcels-2894/libd9b87ac9d4de7cd454acc58565b03391_0.so
INFO: Temporary output files are stored in /home/jvalenti/MOAD/results/out-ZQTYXTKL.
INFO: You can use "parcels_convert_npydir_to_netcdf /home/jvalenti/MOAD/results/out-ZQTYXTKL" to convert these to a NetCDF file during the run.
N/A% (0 of 432000.0) |                   | Elapsed Time: 0:00:00 ETA:  --:--:--
  5% (21600.0 of 432000.0) |             | Elapsed Time: 0:00:01 ETA:   0:00:32
{'fraction_non_alphanumeric': 0.13668459986550102, 'fraction_numerical': 0.03227975790181574, 'mean_word_length': 5.566225165562914, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 16, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '91311', 'license': 'Apache-2.0', 'n_tokens_mistral': 2341, 'n_tokens_neox': 2179, 'n_words': 470, 'path': 'notebooks/parcels/Remote/fibers/biofilm.ipynb', 'repo_name': 'SalishSeaCast/analysis-jose', 'size': '5948'}