I am working on the file "Examples/MD02-2515.McClymont.2012.Spectral.ipynb".
The first task is:
Bchron Run
Can you write Python code for it?

# Let Python and R communicate with each other

%load_ext rpy2.ipython


I am working on the file "Examples/MD02-2515.McClymont.2012.Spectral.ipynb".
The first task is:
Programmer's corner
Use the cell below to have a look at the data and variables in the workspace
Can you write Python code for it?

whos

np.array([[depth[nan_index]],[age_nan]])

age


I am working on the file "Examples/MD02-2515.McClymont.2012.Spectral.ipynb".
The first task is:
Reservoir Age Correction
Apply a reservoir age correction on top of the standard correction to the measured radiocarbon. The radiocarbon data for the local correction ΔR is taken from the 14CHRONO website and using the mean and standard error of the mean as the reservoir age correction and associated error.
Can you write Python code for it?

# Get the latitude and longitude from the metadata

print("Latitude: " + str(lipd_m.get('geo').get('geometry').get('coordinates')[0]))
print("Longitude: " + str(lipd_m.get('geo').get('geometry').get('coordinates')[1]))


I am working on the file "Examples/MD02-2515.McClymont.2012.Spectral.ipynb".
The first task is:
Set-up
Get the data and metadata
Can you write Python code for it?

import sys

# Get the metadata (To display lat/lon)

lipd_m = getMetadata("MD02-2515.McClymont.2012.lpd")

if not 'properties' in lipd_m['geo']:
    record = input("Enter the name of your record: ")
else:
    record = lipd_m['geo']['properties']['siteName']

# Get the paleodata in a Panda DataFrame for ease of use

df_data_dict = filter_dfs("paleo measurement")
table_instance = 0
for  key, value in df_data_dict.items():
    if "measurement" in key:
        table_instance += 1
if table_instance == 1:
    for  key, value in df_data_dict.items():
        if "measurement" in key:
            df_data_l = value
            table_name = key
elif table_instance == 0:
    sys.exit("No DataMeasurementTable available.")
else:
    print("There is more than one PaleoMeasurementTable available for this record.")
    for key, value in df_data_dict.items():
        if "measurement" in key:
            print(key)
            print(value)
    print("Which Table would you like to use?")
    for key, value in df_data_dict.items():
        if "measurement" in key:
            print(key)
    table_name = input("Enter the table name: ")
    df_data_l = df_data_dict[table_name]

# Get the chrondata in a panda dataframe for ease of use

df_data_dict = filter_dfs("chron measurement")
table_instance = 0
for  key, value in df_data_dict.items():
    if "measurement" in key:
        df_chron_l = value
        table_instance += 1
if table_instance == 1:
    for  key, value in df_data_dict.items():
        if "measurement" in key:
            df_chron_l = value
elif table_instance == 0:
    sys.exit("No ChronMeasurementTable available.")
else:
    print("There is more than one ChronMeasurementTable available for this record.")
    for key, value in df_data_dict.items():
        if "measurement" in key:
            print(key)
            print(value)
    print("Which Table would you like to use?")
    for key, value in df_data_dict.items():
        if "measurement" in key:
            print(key)
    table_name = input("Enter the...


I am working on the file "Examples/MD02-2515.McClymont.2012.Spectral.ipynb".
The first task is:
Setup some of Bchron optional arguments. Set the collection age of the core if known and the number of simulations to 10000 to get 1000 age model samples back
Can you write Python code for it?

iter = 10000
max_t = -52

# Pass the needed variable into R

%R -i iter
%R -i dir
%R -i radio_text
%R -i depth_text
%R -i max_t
%R -i record


I am working on the file "Examples/MD02-2515.McClymont.2012.Spectral.ipynb".
The first task is:
Spectral Analysis
Use the Lomb-Scargle periodogram for unevenly-spaced time series from the scipy package.
Can you write Python code for it?

# Remove missing values for further analysis

if len([list(df_data_l).index(header) for header in list(df_data_l) if 'uk37' in header.lower()]) > 1:
    print("Too many proxy columns, refine the search")
    for header in list(df_data_l):
        if 'uk37' in header.lower():
            print(header)
    y_axis_column = input("Enter the name of the proxy column of interest: ")
else:
    y_axis_column = [header for header in list(df_data_l) if 'mg/ca' in header.lower()][0]

print("Missing values are indicated by " + str(lipd_m['paleoData']['paleo']['paleoMeasurementTable']
      [[substring for substring in table_name.split('.') if 'table' in substring.lower()][0]]['missingValue']) + '.')
print("Adapt the code in the cell below to filter the values out.")

# Get the index of the actual values if Holocene
nan_index = []
for n,i in enumerate (df_data_l[y_axis_column]):
    if i > 0 and chronQ[1,n]<=10000:
        nan_index.append(n)

# Get the y values
y_values  = df_data_l[y_axis_column].iloc[nan_index]
# Get the x values
chronQ_nan = chronQ[:,nan_index]
age_nan = age[:,nan_index]

# Detrend and standardize the data
import scipy.signal as signal
y_values_detrended = signal.detrend(y_values)
y_values_std = (y_values_detrended-np.mean(y_values_detrended))/np.std(y_values_detrended)

# Define the array of frequencies for which to compute the periodogam

print('Warning! This cell takes 15-20 minutes to run depending on the length of the dataset')

ofac = 4 # oversampling value
hifac = 1 # highest frequency that can be analyzed/Nyquist frequency
int = np.nanmean(np.diff(mquantiles(age_nan, prob=[0.5], axis=0)))
step = ((2*int)**(-1))/(age_nan.shape[1]*ofac) # step size for the frequency verctor
f = np.arange(2*np.pi*step, 2*np.pi*(hifac*(2*int)**(-1)), step)

# compute the periodogram for each age model realization

pgram = np.zeros((age_nan.shape[0],f.shape[0])) # pre-allocate the space

for index in np.arange(0,age_nan.shape[0],1):
    pgram[index,:] =...


I am working on the file "Examples/MD02-2515.McClymont.2012.Spectral.ipynb".
The first task is:
Summary
Summarize the results below and export various csv file for further use
Can you write Python code for it?

# Find the peaks for each Monte-Carlo age models and the percent variance in each band of interest
from detect_peaks import detect_peaks
from scipy.integrate import simps

# initiate the matrices
peak_sub1 = np.zeros(age_nan.shape[0])
peak_sub2 = np.zeros(age_nan.shape[0])
peak_sub3 = np.zeros(age_nan.shape[0])

percent_var1 = np.zeros(age_nan.shape[0])
percent_var2 = np.zeros(age_nan.shape[0])
percent_var3 = np.zeros(age_nan.shape[0])

for index in np.arange(0,age_nan.shape[0],1): #step over all the possible spectres
    # Concentrate on the 900-1200 yr band
    pgram_sub1 = pgram_norm[index , np.min(np.where(2*np.pi/f<1200)):np.max(np.where(2*np.pi/f>900))]
    f_sub1 = f[np.min(np.where(2*np.pi/f<1200)):np.max(np.where(2*np.pi/f>900))]
    ind_sub1 = detect_peaks(pgram_sub1, show = False, mpd = pgram_sub1.shape[0])
    if not ind_sub1:
        peak_sub1[index] = np.nan
        percent_var1[index]= np.nan
    else:
        peak_sub1[index] = 2*np.pi/f_sub1[ind_sub1]
        percent_var1[index] = simps(pgram_sub1,f_sub1)/simps(pgram_norm[index,:], f)

    # Concentrate on the 1200-2000 yr band
    pgram_sub2 = pgram_norm[index , np.min(np.where(2*np.pi/f<2000)):np.max(np.where(2*np.pi/f>1200))]
    f_sub2 = f[np.min(np.where(2*np.pi/f<2000)):np.max(np.where(2*np.pi/f>1200))]
    ind_sub2 = detect_peaks(pgram_sub2, show = False, mpd = pgram_sub2.shape[0])
    if not ind_sub2:
        peak_sub2[index] = np.nan
        percent_var2[index]= np.nan
    else:
        peak_sub2[index] = 2*np.pi/f_sub2[ind_sub2]
        percent_var2[index] = simps(pgram_sub2,f_sub2)/simps(pgram_norm[index,:], f)

    # Concentrate on the 2000-3000 yr band
    pgram_sub3 = pgram_norm[index , np.min(np.where(2*np.pi/f<3000)):np.max(np.where(2*np.pi/f>2000))]
    f_sub3 = f[np.min(np.where(2*np.pi/f<3000)):np.max(np.where(2*np.pi/f>2000))]
    ind_sub3 = detect_peaks(pgram_sub3, show = False, mpd = pgram_sub3.shape[0])
    if not ind_sub3:
        peak_sub3[index] = np.nan
        percent_var3[index]= np.nan
    else:
    ...


I am working on the file "Examples/MMSP/micromechanics_examples/micro_examples1.ipynb".
The first task is:
Answer to question 1
Can you write Python code for it?

T_Al2O3 = inv(I+np.dot(S,np.dot(M_Al,L_Al2O3-L_Al)))
sumT = c*T_Al2O3+(1-c)*I;
invsumT = inv(sumT);

A_Al = np.dot(I,invsumT)
A_Al2O3= np.dot(T_Al2O3,invsumT)

print np.array_str(A_Al2O3, precision=4)


I am working on the file "Examples/MMSP/micromechanics_examples/micro_examples1.ipynb".
The first task is:
Answer to question 2
Can you write Python code for it?

L_eff = (1-c)*np.dot(L_Al,A_Al) + c*np.dot(L_Al2O3,A_Al2O3)
print np.array_str(L_eff, precision=2)


I am working on the file "Examples/MMSP/micromechanics_examples/micro_examples1.ipynb".
The first task is:
Validation using simmit
Can you write Python code for it?

path_data = dir + '/data'
nstatev = 0

psi_rve = 0.
theta_rve = 0.
phi_rve = 0.

umat_name = 'MIMTN'
#Props
nphases = 2 #The number of phases
num_file = 0 #The num of the file that contains the subphases
int1 = 50
int2 = 50
n_matrix = 0

props = np.array([nphases, num_file, int1, int2, n_matrix])
L_eff = sim.L_eff(umat_name, props, nstatev, psi_rve, theta_rve, phi_rve, path_data)
print np.array_str(L_eff, precision=3)
d = sim.L_iso_props(L_eff)
print d[0]
print d[1]


I am working on the file "Examples/MMSP/parametric_analysis/fibre_angle.ipynb".
The first task is:
We need to import here the data, modify them if needed and proceed
Can you write Python code for it?

umat_name = 'MIMTN' #This is the 5 character code for the Mori-Tanaka homogenization for composites with a matrix and ellipsoidal reinforcments
nstatev = 0

nphases = 2 #The number of phases
num_file = 0 #The num of the file that contains the subphases
int1 = 50
int2 = 50
n_matrix = 0

props = np.array([nphases, num_file, int1, int2, n_matrix])

NPhases_file = dir + '/keys/Nellipsoids0.dat'
NPhases = pd.read_csv(NPhases_file, delimiter=r'\s+', index_col=False, engine='python')
NPhases[::]

path_data = dir + '/data'
path_keys = dir + '/keys'
pathfile = 'path.txt'
outputfile = 'results_PLN.txt'

nparams = 4

param_list = iden.read_parameters(nparams)

psi_rve = 0.
theta_rve = 0.
phi_rve = 0.

alpha = np.arange(0.,91.,1)
param_list[1].value = 100
param_list[2].value = 0.4
param_list[3].value = 1.0 - param_list[2].value

E_L = np.zeros(len(alpha))
fig = plt.figure()

umat_name = 'MIMTN' #This is the 5 character code for the Mori-Tanaka homogenization for composites with a matrix and ellipsoidal reinforcments
for i, x in enumerate (alpha):

    param_list[0].value = x

    iden.copy_parameters(param_list, path_keys, path_data)
    iden.apply_parameters(param_list, path_data)

    L = sim.L_eff(umat_name, props, nstatev, psi_rve, theta_rve, phi_rve, path_data)
    p = sim.L_ortho_props(L)
    E_L[i] = p[0]

plt.plot(alpha,E_L, c='black')
np.savetxt('E_L-angle_MT.txt', np.transpose([alpha,E_L]), fmt='%1.8e')

umat_name = 'MISCN' #This is the 5 character code for the Mori-Tanaka homogenization for composites with a matrix and ellipsoidal reinforcments
for i, x in enumerate (alpha):

    param_list[0].value = x

    iden.copy_parameters(param_list, path_keys, path_data)
    iden.apply_parameters(param_list, path_data)

    L = sim.L_eff(umat_name, props, nstatev, psi_rve, theta_rve, phi_rve, path_data)
    p = sim.L_ortho_props(L)
    E_L[i] = p[0]

plt.plot(alpha,E_L, c='red')
np.savetxt('E_L-angle_SC.txt', np.transpose([alpha,E_L]), fmt='%1.8e')

plt.show()


I am working on the file "Examples/MadrigalExample1.ipynb".
The first task is:
Range vs Parameter Plots
Now ploting data from a single time.
Can you write Python code for it?

fig2,axmat2 =plt.subplots(2,2,figsize = (12,9),sharey=True,sharex=False)
axvec2 = axmat2.flatten()
paramlist = ['ne','te','ti','vo']
time1=335
handvec = []
pbounds = [[1e10,8e11],[200.,3500.],[200.,3500.],[-100.,100.]]
for inum, iax in enumerate(axvec2):
    ploth = rangevsparam(data1,desired_beam,time1,gkey=paramlist[inum],gkeyerr='d'+paramlist[inum],fig=fig1,ax=iax,it=False)
    iax.grid(True)
    iax.set_xlim(pbounds[inum])
    handvec.append(ploth)
plt.tight_layout()


I am working on the file "Examples/MadrigalExample1.ipynb".
The first task is:
Read in Data
The first step is to read the data into the GeoData format. The user does this by creating a GeoData instance, as input it takes the read function, in this case readMad_hdf5, and a list of inputs. The subsequent lines are taking the log scaled electron density and putting them in a linear scale.
Can you write Python code for it?

madfile = os.path.join( 'pfa140105.004.hdf5')
data1 = GeoData(readMad_hdf5,[madfile,['nel','te','ti','vo','dnel','dte','dti','dvo']])
data1.data['ne']=sp.power(10.,data1.data['nel'])
data1.data['dne']=sp.power(10.,data1.data['dnel'])


I am working on the file "Examples/MergeAdjacentImages/MergeAdjacentImages.ipynb".
The first task is:
... and check if the output image /tmp/merged.mha was actually written to disk:
Can you write Python code for it?


I am working on the file "Examples/MergeAdjacentImages/MergeAdjacentImages.ipynb".
The first task is:
If ITK is not installed in your python environment, you need to define the environment variable ITK_BUILD_DIR that contains the path to where ITK was built.
Can you write Python code for it?

try:
    import itk
except:
    ITK_BUILD_DIR = None
    if 'ITK_BUILD_DIR' in os.environ:
        ITK_BUILD_DIR = os.environ['ITK_BUILD_DIR']
    else:
        print('ITK_BUILD_DIR not found!')
        print('  Set environment variable')
        sys.exit( 1 )

    if not os.path.exists(ITK_BUILD_DIR):
        print('ITK_BUILD_DIR set but directory not found!')
        print('  ITK_BUIDL_DIR = ' + ITK_BUILD_DIR )
        sys.exit(1)
    # Append ITK libs
    sys.path.append(os.path.join(ITK_BUILD_DIR, 'Wrapping/Generators/Python'))
    sys.path.append(os.path.join(ITK_BUILD_DIR, 'lib'))

    # Append TubeTK libs
    sys.path.append(os.path.join(TubeTK_BUILD_DIR, 'TubeTK-build/lib/TubeTK'))
    import itk

from itk import TubeTKITK as itktube

import matplotlib.pyplot as plt
from matplotlib import cm

%matplotlib inline


I am working on the file "Examples/MergeAdjacentImages/MergeAdjacentImages.ipynb".
The first task is:
Let's check if the spacing and direction are compatible:
Can you write Python code for it?

im0.GetSpacing() == im1.GetSpacing() and im0.GetDirection() == im1.GetDirection()


I am working on the file "Examples/MergeAdjacentImages/MergeAdjacentImages.ipynb".
The first task is:
Let's do the same for the second image:
Can you write Python code for it?

input_image0 = os.path.join(TubeTK_BUILD_DIR, 'MIDAS_Data/ES0015_Large_Wo_offset.mha')
print("Image file path:%s"%input_image0)
reader1 = itk.ImageFileReader.New(FileName=input_image0)
reader1.Update()
im1=reader1.GetOutput()
print im1.GetOrigin()
print im1.GetSpacing()
print im1.GetDirection()

im_np1 = itk.PyBuffer[ImageType].GetArrayFromImage(im1)

plt.imshow(im_np1, cm.gray)


I am working on the file "Examples/MergeAdjacentImages/MergeAdjacentImages.ipynb".
The first task is:
Let's execute that command (via the subprocess module):
Can you write Python code for it?


I am working on the file "Examples/MergeAdjacentImages/MergeAdjacentImages.ipynb".
The first task is:
Next, we load the first input image and show it's origin, spacing, etc.:
Can you write Python code for it?

input_image1 = os.path.join(TubeTK_BUILD_DIR, 'MIDAS_Data/ES0015_Large.mha')
print("Image File path: %s"%input_image1)
reader0 = itk.ImageFileReader.New(FileName=input_image1)
reader0.Update()
im0=reader0.GetOutput()
print im0.GetOrigin()
print im0.GetSpacing()
print im0.GetDirection()


I am working on the file "Examples/MergeAdjacentImages/MergeAdjacentImages.ipynb".
The first task is:
We are now ready to visualize the result:
Can you write Python code for it?

output_reader = itk.ImageFileReader.New(FileName=output_image)
output_reader.Update()
out_im=output_reader.GetOutput()
print out_im.GetOrigin()
print out_im.GetSpacing()
print out_im.GetLargestPossibleRegion().GetSize()

plt.imshow(itk.PyBuffer[ImageType].GetArrayFromImage(out_im), cm.gray)


I am working on the file "Examples/MergeAdjacentImages/MergeAdjacentImages.ipynb".
The first task is:
We see that the output image is larger by 212 pixel in both dimensions, since the second image's origin was at (200, 200) and the
image size of both images was 512 times 512 pixel.
Merging - Example 2
We can also add some padding (e.g., 50 pixel on each side). For that we modify cmd as follows:
Can you write Python code for it?

output_image = os.path.join(TubeTK_BUILD_DIR, 'Temporary/Python.MergeAdjacentImages-Ex2.mha')

cmd = [os.path.join(TubeTK_BUILD_DIR, 'bin/MergeAdjacentImages'),
       '-i 0', # Number of iterations ... here i=0, which means no registration,
       '-b 50,50', # This adds a white border around the second image (50 pixel each side)
       input_image0,
       input_image1,
       output_image
      ]

subprocess.call(cmd)

reader=itk.ImageFileReader.New(FileName=output_image)
reader.Update()
plt.imshow(itk.PyBuffer[ImageType].GetArrayFromImage(reader.GetOutput()), cm.gray)


I am working on the file "Examples/ODF/.ipynb_checkpoints/ODF-checkpoint.ipynb".
The first task is:
In the previous graph we can see a multi-peak ODF (peaks are modeled using PEARSONVII functions). It actually represent quite well the microstructure of injected plates.
The next step is to discretize the ODF into phases.
The file containing the initial 2-phase microstructure contains the following informations
Can you write Python code for it?

NPhases_file = dir + '/data/Nellipsoids0.dat'
NPhases = pd.read_csv(NPhases_file, delimiter=r'\s+', index_col=False, engine='python')
NPhases[::]

umat_name = 'MIMTN' #This is the 5 character code for the Mori-Tanaka homogenization for composites with a matrix and ellipsoidal reinforcments
nstatev = 0

rho = 1.12 #The density of the material (overall)
c_p = 1.64 #The specific heat capacity (overall)

nphases = 2 #The number of phases
num_file = 0 #The num of the file that contains the subphases
int1 = 20
int2 = 20

psi_rve = 0.
theta_rve = 0.
phi_rve = 0.

props = np.array([nphases, num_file, int1, int2, 0])

path_data = 'data'
path_results = 'results'
Nfile_init = 'Nellipsoids0.dat'
Nfile_disc = 'Nellipsoids1.dat'

nphases_rve = 36
num_phase_disc = 1

sim.ODF_discretization(nphases_rve, num_phase_disc, 0., 180., umat_name, props, path_data, peak_file, Nfile_init, Nfile_disc, 1)

NPhases_file = dir + '/data/Nellipsoids1.dat'
NPhases = pd.read_csv(NPhases_file, delimiter=r'\s+', index_col=False, engine='python')

#We plot here the five first phases
NPhases[:5]

#Plot the concentration and the angle
c, angle = np.loadtxt(NPhases_file, usecols=(4,5), skiprows=2, unpack=True)

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()

# the histogram of the data
xs = np.arange(0,180,5)
rects1 = ax1.bar(xs, c, width=5, color='r', align='center')

ax2.plot(x, y, 'b-')

ax1.set_xlabel('X data')
ax1.set_ylabel('Y1 data', color='g')
ax2.set_ylabel('Y2 data', color='b')

ax1.set_ylim([0,0.025])
ax2.set_ylim([0,0.25])

plt.show()

#plt.grid(True)
#plt.plot(angle,c, c='black')
plt.show()

#Run the simulation
pathfile = 'path.txt'
nphases = 37 #The number of phases
num_file = 1 #The num of the file that contains the subphases
props = np.array([nphases, num_file, int1, int2])
outputfile = 'results_MTN.txt'
sim.solver(umat_name, props, nstatev, psi_rve, theta_rve, phi_rve, path_data, path_results, pathfile, outputfile)

fig = plt.figure()
outputfile_macro =  dir + '/' + path_results + '/results_MTN_global-0.txt'
e11, e22, e33, e12,...


I am working on the file "Examples/ODF/.ipynb_checkpoints/ODF-checkpoint.ipynb".
The first task is:
In this Python Notebook we will show how to properly run a simulation of a composite material, providing the ODF (orientation density function) of the reinforcments.
Such identification procedure require:
1. Proper ODF peak data
1. Proper composite properties
2. A proper numerical model (here a composite model for laminate constitutive model)
Can you write Python code for it?

x = np.arange(0,182,2)
path_data = dir + '/data/'
peak_file = 'Npeaks0.dat'

y = sim.get_densities(x, path_data, peak_file, False)
fig = plt.figure()

plt.grid(True)
plt.plot(x,y, c='black')


I am working on the file "Examples/ODF/.ipynb_checkpoints/ODF_iden-checkpoint.ipynb".
The first task is:
In the previous graph we can see a multi-peak ODF (peaks are modeled using PEARSONVII functions). It actually represent quite well the microstructure of injected plates.
The next step is to discretize the ODF into phases.
The file containing the initial 2-phase microstructure contains the following informations
Can you write Python code for it?

NPhases_file = dir + '/data/Nellipsoids0.dat'
NPhases = pd.read_csv(NPhases_file, delimiter=r'\s+', index_col=False, engine='python')
NPhases[::]

#Number_of_parameters
n_param = 6
#Number_of_consts
n_consts = 0
#Number_of_files
nfiles = 1

#Number_of_generations
ngen =  200
#Aleatory/Mesh space population : 0=mesh 1=meshlimit 2=random 3=defined
aleaspace = 2
#Space or aleatory population : apop in case of aleatory, spop in case of mesh
apop = 200
#Number of "doped" individual
ngboys = 1
#Max population per subgeneration
maxpop = 50
#stationnarity condition
station_nb = 20

path_data = dir + '/data'
path_keys = dir + '/keys'
path_results = dir + '/results'
outputfile = 'id_params.txt'
materialfile = 'material.dat'
simul_type = 'ODF'

iden.identification(simul_type,n_param,n_consts,nfiles,ngen,aleaspace,apop,ngboys,maxpop,station_nb,path_data,path_keys,path_results,materialfile,outputfile)

#Plot the concentration and the angle
c, angle = np.loadtxt(NPhases_file, usecols=(4,5), skiprows=2, unpack=True)

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()

# the histogram of the data
xs = np.arange(0,180,5)
rects1 = ax1.bar(xs, c, width=5, color='r', align='center')

ax2.plot(x, y, 'b-')

ax1.set_xlabel('X data')
ax1.set_ylabel('Y1 data', color='g')
ax2.set_ylabel('Y2 data', color='b')

ax1.set_ylim([0,0.025])
ax2.set_ylim([0,0.25])

plt.show()

#plt.grid(True)
#plt.plot(angle,c, c='black')
plt.show()

#Run the simulation
pathfile = 'path.txt'
nphases = 37 #The number of phases
num_file = 1 #The num of the file that contains the subphases
props = np.array([nphases, num_file, int1, int2])
outputfile = 'results_MTN.txt'
sim.solver(umat_name, props, nstatev, psi_rve, theta_rve, phi_rve, path_data, path_results, pathfile, outputfile)

fig = plt.figure()
outputfile_macro =  dir + '/' + path_results + '/results_MTN_global-0.txt'
e11, e22, e33, e12, e13, e23, s11, s22, s33, s12, s13, s23 = np.loadtxt(outputfile_macro, usecols=(8,9,10,11,12,13,14,15,16,17,18,19), unpack=True)
plt.grid(True)
plt.plot(e11,s11, c='black')

for...


I am working on the file "Examples/ODF/discretization/.ipynb_checkpoints/ODF-checkpoint.ipynb".
The first task is:
In the previous graph we can see a multi-peak ODF (peaks are modeled using PEARSONVII functions). It actually represent quite well the microstructure of injected plates.
The next step is to discretize the ODF into phases.
The file containing the initial 2-phase microstructure contains the following informations
Can you write Python code for it?

NPhases_file = dir + '/data/Nellipsoids0.dat'
NPhases = pd.read_csv(NPhases_file, delimiter=r'\s+', index_col=False, engine='python')
NPhases[::]

umat_name = 'MIMTN' #This is the 5 character code for the Mori-Tanaka homogenization for composites with a matrix and ellipsoidal reinforcments
nstatev = 0

nphases = 2 #The number of phases
num_file = 0 #The num of the file that contains the subphases
int1 = 20
int2 = 20

psi_rve = 0.
theta_rve = 0.
phi_rve = 0.

props = np.array([nphases, num_file, int1, int2, 0])

path_data = 'data'
path_results = 'results'
Nfile_init = 'Nellipsoids0.dat'
Nfile_disc = 'Nellipsoids1.dat'

nphases_rve = 36
num_phase_disc = 1

sim.ODF_discretization(nphases_rve, num_phase_disc, 0., 180., umat_name, props, path_data, peak_file, Nfile_init, Nfile_disc, 1)

NPhases_file = dir + '/data/Nellipsoids1.dat'
NPhases = pd.read_csv(NPhases_file, delimiter=r'\s+', index_col=False, engine='python')

#We plot here the five first phases
NPhases[:5]

#Plot the concentration and the angle
c, angle = np.loadtxt(NPhases_file, usecols=(4,5), skiprows=2, unpack=True)

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()

# the histogram of the data
xs = np.arange(0,180,5)
rects1 = ax1.bar(xs, c, width=5, color='r', align='center')

ax2.plot(x, y, 'b-')

ax1.set_xlabel('X data')
ax1.set_ylabel('Y1 data', color='g')
ax2.set_ylabel('Y2 data', color='b')

ax1.set_ylim([0,0.025])
ax2.set_ylim([0,0.25])

plt.show()

#plt.grid(True)
#plt.plot(angle,c, c='black')
plt.show()

#Run the simulation
pathfile = 'path.txt'
nphases = 37 #The number of phases
num_file = 1 #The num of the file that contains the subphases
props = np.array([nphases, num_file, int1, int2])
outputfile = 'results_MTN.txt'
sim.solver(umat_name, props, nstatev, psi_rve, theta_rve, phi_rve, path_data, path_results, pathfile, outputfile)

fig = plt.figure()
outputfile_macro =  dir + '/' + path_results + '/results_MTN_global-0.txt'
e11, e22, e33, e12, e13, e23, s11, s22, s33, s12, s13, s23 = np.loadtxt(outputfile_macro,...


I am working on the file "Examples/ODF/discretization/.ipynb_checkpoints/ODF-checkpoint.ipynb".
The first task is:
In this Python Notebook we will show how to properly run a simulation of a composite material, providing the ODF (orientation density function) of the reinforcments.
Such identification procedure require:
1. Proper ODF peak data
1. Proper composite properties
2. A proper numerical model (here a composite model for laminate constitutive model)
Can you write Python code for it?


I am working on the file "Examples/ODF/discretization/ODF.ipynb".
The first task is:
In the previous graph we can see a multi-peak ODF (peaks are modeled using PEARSONVII functions). It actually represent quite well the microstructure of injected plates.
The next step is to discretize the ODF into phases.
The file containing the initial 2-phase microstructure contains the following informations
Can you write Python code for it?


I am working on the file "Examples/ODF/discretization/ODF.ipynb".
The first task is:
In this Python Notebook we will show how to properly run a simulation of a composite material, providing the ODF (orientation density function) of the reinforcments.
Such identification procedure require:
1. Proper ODF peak data
1. Proper composite properties
2. A proper numerical model (here a composite model for laminate constitutive model)
Can you write Python code for it?


I am working on the file "Examples/PrePara_Altavista_AguasAbajo.ipynb".
The first task is:
Alta Vista Aguas Arriba
Se va a simular con casi todo en tipo no lineal, excepto el flujo base.
Can you write Python code for it?

cu = wmf.SimuBasin(0,0,0,0, rute='/media/nicolas/discoGrande/01_SIATA/nc_cuencas/AltaVista_abajo.nc')


I am working on the file "Examples/PrePara_Altavista_AguasAbajo.ipynb".
The first task is:
Figura EVP: Evaporacion estimada cada 5 min en las 8 horas de luz efectiva para la EVP
Can you write Python code for it?

#Lectura de la profunidad de raiz
Z,p = wmf.read_map_raster('/media/nicolas/discoGrande/01_SIATA/raster/Prof_raiz_cm.tif')
Z = cu.Transform_Map2Basin(Z,p)
Z[Z == -9999] = 40.0
Z[Z==0]=40
#Profundidad por geomorfologia
Zg = np.zeros(cu.ncells)
Zg[cu.CellSlope<0.25]=0.6
Zg[(cu.CellSlope>=0.25)&(cu.CellSlope<0.30)]=1.0
Zg[(cu.CellSlope>=0.30)&(cu.CellSlope<0.50)]=0.3
Zg[cu.CellSlope>=0.5] = 0.2
#plot de la profundidad
cu.Plot_basin(Zg,ruta=ruta + 'ParamCuencas/Prof_suelo_AltaVistaAbajo.png')

Tetas = {}
for i in ['Teta_pmp','Teta_cp','Teta_sat']:
    te,p = wmf.read_map_raster('/media/nicolas/discoGrande/01_SIATA/raster/'+i+'.tif')
    te = cu.Transform_Map2Basin(te,p)
    te[te == -9999] = te[te>0].mean()
    te[te == 0] = te[te>0].mean()
    Tetas.update({i:te})
# Valores de Hu y Hg calculados en metros
Hu  = Zg * (Tetas['Teta_cp']-Tetas['Teta_pmp'])*10
Hg  = Zg * (Tetas['Teta_sat']-Tetas['Teta_cp'])*10
Hu[Z == 2] = 2
cu.Plot_basin(Hg,lines_spaces=0.08,ruta=ruta + 'ParamCuencas/Hg_AltaVista_Abajo.png')

# Cionductividad hidraulica saturada
Ks, p = wmf.read_map_raster('/media/nicolas/discoGrande/01_SIATA/raster/'+'Ks_mm_h.tif')
Ks = cu.Transform_Map2Basin(Ks,p)
#Conductivdad Nivel freatico
Ks[Ks == -9999] = Ks[Ks>0].mean()
Ks[Ks == 0] = Ks[Ks>0].mean()
Kp = np.copy(Ks) / 100.0
#Coeficiente kubota y sivapalan
ksh=((Ks/3600000.0)*cu.CellSlope*(30.0**2.0))/(3*(Hg*0.9/1000.0)**2)
cu.Plot_basin(ksh)

# Rugosidad
man,p = wmf.read_map_raster('/media/nicolas/discoGrande/01_SIATA/raster/n_man.asc')
man = cu.Transform_Map2Basin(man,p)
#Flujo por pequenos surcos
CoefLad = (0.5/man)*(cu.CellSlope**(1.0/2.0))
ExpLad = (2.0/3.0)*0.64
cu.Plot_basin(CoefLad)
print ExpLad

#Coeficiente de cauces
area = cu.CellAcum * (12.7**2)/1e6 #Tamaño de celda al cuadrado
CoefOCG,ExpOCG = wmf.OCG_param(pend = cu.CellSlope, area = area)
cu.Plot_basin(CoefOCG)
print ExpOCG


I am working on the file "Examples/PrePara_Altavista_AguasAbajo.ipynb".
The first task is:
Montaje de los almacenamientos maximos en la cuenca
Can you write Python code for it?

cu.set_PhysicVariables('capilar', Hu, 0)
cu.set_PhysicVariables('gravit', Hg, 1)


I am working on the file "Examples/PrePara_Altavista_AguasAbajo.ipynb".
The first task is:
montaje de los parametros verticales de la cuenca
Can you write Python code for it?

# Evaporacion, infiltracion, percolacion y perdidas
cu.set_PhysicVariables('v_coef',Evp,0)
#Infiltracion, se hace impermeable la ciudad, se pasa a [mm/seg]
KsForMap = np.copy(Ks)/3600.0
KsForMap.min()
KsForMap[Z==2] = 0.0001
cu.set_PhysicVariables('v_coef',KsForMap,1)
#Percolacion se pasa a [mm/seg]
cu.set_PhysicVariables('v_coef',Kp/3600.0,2)
#Se asume perdidas del sistema iguales a cero
cu.set_PhysicVariables('v_coef',0,3)


I am working on the file "Examples/ReadRinex Demo.ipynb".
The first task is:
Plotting
according to the Andrew Hansen's thesis equations (2.15) and (2.16):
$TEC = (P2-P1)/(f1^2/f2^2 - 1)$
ans
$TEC = -(L2-L1)/(f1^2/f^2 - 1)$
theoretically they should be the same
Can you write Python code for it?

# sattelites in file
data.items

# parameters in the file
# https://igscb.jpl.nasa.gov/igscb/data/format/rinex211.txt
# section 10.1.1 says what the letters mean
data.major_axis

f1 = 1575.42E6 #MHz
f2 = 1227.6E6  #MHz
f5 = 1176.45E6 #MHz

sv_of_interest = 30

fig = plt.figure(figsize=(15,15))
ax1 = plt.subplot(311)
fmt = DateFormatter('%H:%M:%S')
ax1.xaxis.set_major_formatter(fmt)

bias = data[:,sv_of_interest,'L1','data']*(3.0E8/f1)-data[:,sv_of_interest,'C1','data']

plt.plot(data[:,sv_of_interest,'C1','data'],'.',label='c1')
plt.plot(data[:,sv_of_interest,'L1','data']*(3.0E8/f1),'.',label='l1')
plt.plot(bias,'.',label='bias')

abias=np.average(bias[np.logical_not(np.isnan(bias))])
print(abias)

ax2=plt.subplot(312)
plt.plot(data[:,sv_of_interest,'L1','data'][6999:7006]*(3.0E8/f1)-abias,'.',label='corrected L1')
plt.plot(data[:,sv_of_interest,'C1','data'][6999:7006],'.',label='c1')
plt.plot(data[:,sv_of_interest,'L1','data'][6999:7006]*(3.0E8/f1),'.',label='uncorrected L1')

ax3=plt.subplot(313)
plt.plot(data[:,sv_of_interest,'L1','data']*(3.0E8/f1)-abias,'.',label='corrected L1')
plt.plot(data[:,sv_of_interest,'C1','data'],'.',label='c1')
plt.plot(data[:,sv_of_interest,'L1','data']*(3.0E8/f1),'.',label='uncorrected L1')

plt.legend()
plt.grid()
plt.show()


I am working on the file "Examples/Rideout method TEC plots.ipynb".
The first task is:
Below I explored the loss of lock indicator. If the 0 bit is set in the lli (loss of lock indicator), that means that the receiver thinks it lost lock on the previous measurement. I made a mask of all the points where lock was lost across all four relevant parameters (L1,L2,C1,P2 in this case), and plotted those as red x's on top of the TEC plot. Underneath is the SNR (S1 and S2). As you can see, in this case, the lli looks pretty good but the SNR doesn't appear to show anything. Underneath all that is the signal strength indicator which maps the signal strength a value from 0 to 9. In this case it doesn't appear to show anything either.
SVN = 23
Can you write Python code for it?

svn = 23
tlim2 = 8000

lli = data[data.labels[:tlim2],svn,['L1','L2','C1','P2'],'lli']
lli[np.isnan(lli)]=0
lli=lli.astype(int)
llimask = np.logical_or.reduce(lli%2)

fig2 = plt.figure(figsize=(15,15))
ax1 = plt.subplot(311)
ax1.xaxis.set_major_formatter(fmt)
plt.ylabel('TECu')
plt.title('TEC w/ Loss of Lock Indicated')
plt.grid()

diffrange = data[data.labels[:tlim2],svn,'P2','data']-data[data.labels[:tlim2],svn,'C1','data']
diffrange = diffrange*convertMetersToTEC*f2f1Factor
phase = f2f1Factor*(convertL1ToMeters*data[data.labels[:tlim2],svn,'L1','data']
                    -convertL2ToMeters*data[data.labels[:tlim2],svn,'L2','data'])

phase = phase*convertMetersToTEC
median = sorted(list(phase-diffrange))[int(len(diffrange)/2)]
TEC = phase-median

plt.plot(TEC[TEC<200])
plt.plot(TEC[llimask][TEC[llimask]<200],'rx')

ax2 = plt.subplot(312, sharex=ax1)
plt.plot(data[data.labels,svn,'S1','data'][:tlim2])
plt.plot(data[data.labels,svn,'S2','data'][:tlim2])
plt.grid()
plt.legend(['S1','S2'])
plt.title('Signal to Noise')
plt.yticks(np.arange(0,60,10))

ax3 = plt.subplot(313, sharex=ax1)
[plt.plot(data[data.labels[:tlim2],svn,a,'ssi']) for a in ['L1','L2','C1','P2']]
plt.legend(['L1','L2','C1','P2'],bbox_to_anchor=(1.1, 1.05))
plt.yticks(np.arange(10))
plt.grid()
plt.title("Signal Strength Indicator")

plt.show()

from datetime import datetime
start = datetime(year=2015,month=10,day=7,hour=6,minute=0,second=49)
end = datetime(year=2015,month=10,day=7,hour=7,minute=7,second=30)
data[end]


I am working on the file "Examples/Simula_Salgar_Celdas.ipynb".
The first task is:
A continuación se presentan los valores que tendrían los 3 tanques lineales en el modelo para el caso en que se usen los coeficientes de calibración R[5] = 1.0, R[6] = 1000 y R[7] = 1800
Can you write Python code for it?

#Si uno calcula los coeficientes lineales de salida de cada tanque
calib = [0.1, 100, 1800]
hflux=[]
for c,v in zip(calib,Lista):
    hflux.append(1.0 - (wmf.models.hill_long/(c*v*300 + wmf.models.hill_long)) )
for h in hflux:
    utils.plot_basin_map(cuSalgar.structure,h,cuSalgar.ncells)
    print 'Tasa transferencia Media [%]: ' + str(h.mean())


I am working on the file "Examples/Simula_Salgar_Celdas.ipynb".
The first task is:
A cotninuación se pasan las velocidades que se encuentran en forma de celda a forma de ladera
Can you write Python code for it?

ListaHills=[]
for var in Lista:
    ListaHills.append(cuSalgar.Transform_Basin2Hills(var))


I am working on the file "Examples/Simula_Salgar_Celdas.ipynb".
The first task is:
Ahora se calcula como sería la cantidad de agua transportada por cada ladera con esas velocidades (asumiendo un omportamiento lineal):
Can you write Python code for it?

#Si uno calcula los coeficientes lineales de salida de cada tanque
calib = [0.5, 500, 108000]
hflux=[]
for c,v in zip(calib,ListaHills):
    hflux.append(1.0 - (wmf.models.hill_long/(c*v*300 + wmf.models.hill_long)) )
for h in hflux:
    hBasin = cuSalgar.Transform_Hills2Basin(h[0])
    cuSalgar.Plot_basin_fast(hBasin)
    print 'Tasa transferencia Media [%]: ' + str(h.mean())


I am working on the file "Examples/Simula_Salgar_Celdas.ipynb".
The first task is:
Ejecucion del modelo en ladera
A continuación se realiza un primer ensayo de la ejecución del modelo en su versión de ladera, esta es puramente experimental.
La calibración se compone de 10 parámetros escalares, los cuales son:
- R[1] : Evaporación.
- R[2] : Infiltración.
- R[3] : Percolación.
- R[4] : Pérdidas.
- R[5] : Vel Superficial.
- R[6] : Vel Sub-superficial.
- R[7] : Vel Subterranea.
- R[8] : Vel Cauces.
- R[9] : Alm capilar maximo.
- R[10] : Alm gravitacional maximo.
Can you write Python code for it?

Calibracion = [0.8, 100, 100, 0.0, 20, 90, 50, 0.3, 1, 1]
ruta_lluvia = 'lluvia/lluvia_lad_201505010000_201505312355.bin'
Res = cuSalgar.run_shia(Calibracion,ruta_lluvia,2000,1500)

pl.plot(Res['Qsim'][0])
print Res['Qsim'][0][800:1000].mean()

for i in range(4):
    cuSalgar.set_storage(Res['Storage'][i],i)

pos = 3
s = cuSalgar.Transform_Hills2Basin(Res['Storage'][pos])
cuSalgar.Plot_basin_fast(s)
pl.hist(Res['Storage'][pos])
print np.percentile(Res['Qsim'][0],25)

Kp


I am working on the file "Examples/Simula_Salgar_Celdas.ipynb".
The first task is:
Modelo por laderas
A continuación se realiza un ensayo similar pero simulando por laderas, este ejercicio pretende ejecutar por privera ves el modelo en un esquema de laderas y canales y no de celdas.
Variaciones a resaltar:
En el modelo de ladar cabe destacar las siguientes distinciones
Laderas:

La ecuación de continuidad en laderas es afectada, de manera que:
$E_{i} = \left(1- \frac{L_{ladera}}{L_{ladera} + v_{i} \Delta t } \right) S_{i,t}$, para $i$ en tanques 2, 3 y 4.

Canales:

La ecuación en los canales queda descrita de la siguiente manera:
$A_{sec,i,t} = \frac{S_{5,t}F_{conv}}{L_{canal}+v_{5,t}\Delta t}$, donde $F_{conv} = W_{canal} L_{canal} / 1000 [m^2/mm]$
El ancho del canal esta dado en función del área acumulada.

En General:

Todos los elementos de la cuenca se identifican como elementos con un cauce interior por lo tanto todos son elementos tipo 3 [models.unit_type=3].
Can you write Python code for it?

# Trazado de la cuenca
cuSalgar = wmf.SimuBasin(-75.9808, 5.9647, DEM, DIR, name='Liboriana',
    dt = 300, modelType = 'hills',umbral=500)
cuSalgar.GetGeo_Cell_Basics()


I am working on the file "Examples/Simula_Salgar_Celdas.ipynb".
The first task is:
Obtención del ancho en función del Qmed.
Para obtener el ancho de cada canal este se calcula en función del caudal medio (Leopold y Maddok, 1953). Se puede usar la siguiente expresión:

1 $W = c Q^\varepsilon$
2 $Q_b = k \Lambda ^{\varphi}$

Por lo tanto se puede aproximar el ancho de la siguiente manera:

3 $W = c k \Lambda ^{\varphi \varepsilon}$ Tomado de Vélez, 2001.
4 $W = K_{w} \Lambda ^{\varphi (\varepsilon_1 - \varepsilon_2)} Q^{\varepsilon_2}$

Para la ecuación 1, Mejía y Posada (2002) encuentran que el valor más acertado de exponente para la región andina es $0.46$, Leopold (1953) indica que este valor puede oscilar entre $0.42$ y $0.55$, como coeficiente encuentran un valor igual a $2.261$, de esta forma la ecuación queda:

5 $W = 2.261 Q ^{0.46}$, con un error del $18\%$
Can you write Python code for it?

#Calcula el caudal medio
cuSalgar.GetQ_Balance(3000,Tipo_ETR=1)
#Basado en el Q medio calcula el ancho
W = 2.261*cuSalgar.CellQmed**0.46
#Obtiene los parametros geomorfo
cuSalgar.set_Geomorphology(stream_width=W,umbrales=[30, 500])
# Inclusión de los parámetros en el modelo
Lista=[Evp,Ks,Kp,Kpp]
for pos,var in enumerate(Lista):
    cuSalgar.set_PhysicVariables('v_coef',var,pos)


I am working on the file "Examples/Simula_Salgar_Celdas.ipynb".
The first task is:
Parametros de flujo horizontal en el cause
Preparación parámetros en el cauce
para preparar los parámetros del cauce se deben calcular el coeficiente y el exponente que tienen que ser resueltos para obtener el flujo.
Can you write Python code for it?

#Calcula variable para el coeficiente horizontal
area = cuSalgar.CellAcum * (30**2)
var,w1 = wmf.OCG_param(pend = cuSalgar.CellSlope, area = area)
cuSalgar.set_PhysicVariables('h_coef',var,3,mask=cuSalgar.CellCauce)
#Variable del exponente horizontal
cuSalgar.set_PhysicVariables('h_exp',w1,3,mask=cuSalgar.CellCauce)

a = cuSalgar.Transform_Hills2Basin(wmf.models.h_coef[3])
cuSalgar.Plot_basin_fast(a)
cuSalgar.Plot_basin_fast(var)


I am working on the file "Examples/Simula_Salgar_Celdas.ipynb".
The first task is:
Parámetros físicos.
Los parámetros físicos del modelo se dividen en velocidades verticales y vel horizontales,  las cuales a su ves se dividen en versiones lineales y no lineales de las mismas, en el caso de las velocidades verticales todas las relaciones son lineales, a continuación se describen las variables relacionadas con los flujos que se encuentran en el modelo:

Velocidades Verticales:

Tanque 1 a exterior (evaporacion): controlado por $EVP$, en el modelo se representa como vspeed(1,:) = v_coef(1,:)R[1]dt
Tanque 1 a Tanque 2 (Sat del capilar): controlado por $H_u$ y por la precipitación $P_{t}$.
Tanque 2 a Tanque 3 (infiltracion): controlado por $k_s$, el cual en el modelo se representa mediante vspeed(2,:) = v_coef(2,:)R[2]dt
Tanque 3 a Tanque 4 (percolación): controlado por $k_p$ el cual en el modelo se representa mediante vspeed(3,:) = v_coef(3,:)R[3]dt
Tanque 4 a Perdidas (perdidas); controlado por $k_{pp}$ en el modelo se presenta como vspeed(4,:) = v_coef(4,:)R[4]dt

Velocidades Horizontales:

Salida Tanque 2: Se representa como $v_2$ y en el modelo esta atada a: hspeed(1,:) = h_coef(1,:)R[5] en el caso lineal, y en el no lineal se involucra el termino h_exp(1,:)
Salida Tanque 3: Se representa como $k_{sh}$ o $v_{3}$ en el modelo se muestra commo: hspeed(2,:) = h_coef(2,:)R[6], enn el caso no lineal el termino h_exp(2,:) entra.
Salida Tanque 4: Se representa como $k_{ph}$ o $v_{4}$ en el modelo se muestra commo: hspeed(3,:) = h_coef(3,:)R[7], en el caso no lineal el término h_exp(3,:) se tiene en cuenta.
Salida Tanque 5: Se representa como $v_{5}$, el modelo esta atado a h_coef(4,:) y a h_exp(4,:), siempre es no lineal, en calibración el parámetro R[8] es el responsable.

Almacenamientos:

Almacenamiento capilar: H(1,:) = Max_capilar(1,:) R[9]
Almacenamiento gravitacional: H(2,:) = Max_gravita(1,:) R[10]

La calibración se compone de 10 parámetros escalares, los cuales son:
- R[1] : Evaporación.
- R[2] : Infiltración.
- R[3] : Percolación.
- R[4] : Pérdidas.
- R[5] : Vel Superficial.
-...
Can you write Python code for it?

# Evaporación en la cuenca estimada por Turc.
Evp=4.658*np.exp(-0.0002*cuSalgar.CellHeight)/288.0
# Infiltración Ks
Ks = 0.00028
# Percolación
Kp = Ks/100.0
# Perdidas se asumen iguales a cero
Kpp = 0.0
# Inclusión de los parámetros en el modelo
Lista=[Evp,Ks,Kp,Kpp]
for pos,var in enumerate(Lista):
    cuSalgar.set_PhysicVariables('v_coef',var,pos)


I am working on the file "Examples/Simula_Salgar_Celdas.ipynb".
The first task is:
Preparación parámetros en el cauce
para preparar los parámetros del cauce se deben calcular el coeficiente y el exponente que tienen que ser resueltos para obtener el flujo.
Can you write Python code for it?

#Calcula variable para el coeficiente horizontal
area = cuSalgar.CellAcum * (30**2)
var,w1 = wmf.OCG_param(pend = cuSalgar.CellSlope, area = area)
cuSalgar.set_PhysicVariables('h_coef',var,3)
#Variable del exponente horizontal
cuSalgar.set_PhysicVariables('h_exp',w1,3)


I am working on the file "Examples/Simula_Salgar_Celdas.ipynb".
The first task is:
Preparación parámetros horizontales

v2: velocidad superficial se asume igual a 0.1 m/seg.
v3: velocidad sub-superficial se asume igual a $k_s$.
v4: velocidad subterranea asumida igual a $k_p$.
Can you write Python code for it?

# Velocidades superficial, sub-super, y subte.
v2 = 1.4 * cuSalgar.CellSlope**0.5
v3 = Ks * cuSalgar.CellSlope**0.5
v4 = Kp * cuSalgar.CellSlope**0.5
Lista=[v2,v3,v4]
for pos,var in enumerate(Lista):
    cuSalgar.set_PhysicVariables('h_coef',var,pos)

v2.mean()


I am working on the file "Examples/Specslider.ipynb".
The first task is:
ACF and Spectra
This will show a plot of the spectra and ACF with sliders for the electron and ion temperatures. The frequency of the radar is 440 MHz carrier frequency (UHF).
Can you write Python code for it?

slideTi = ipywidgets.FloatSlider(
    value=1000.,
    min=500.,
    max=5000.,
    step=500.,
    description='Ti in K:',
    disabled=False,
    continuous_update=False,
    orientation='horizontal',
    readout=True,
    readout_format='.1f',
    slider_color='white'
)
slideTe = ipywidgets.FloatSlider(
    value=1000.,
    min=500.,
    max=5000.,
    step=500.,
    description='Te in K:',
    disabled=False,
    continuous_update=False,
    orientation='horizontal',
    readout=True,
    readout_format='.1f',
    slider_color='white'
)

w=ipywidgets.interactive(plot1dspec,Ti=slideTi,Te=slideTe)
output = w.children[-1]
output.layout.height = '800px'
output.layout.width= '100%'
display(w)


I am working on the file "Examples/Surrogate Modeling with Scikit SVM and RBF-checkpoint.ipynb".
The first task is:
Higher-Dimensional Data Sets
Let's generalize this to a higher dimensional dataset. We'll try to model a 2-parameter input 1-parameter output surface using RBF SVR.
Can you write Python code for it?

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm

N = 200
X = np.random.random((N,2))
def f(x,y):
    return np.sin(x) + np.sin(y)
Y = [f(x,y) for x, y in X]

# Create an SVR instance using an RBF kernel
C_param = 1e4
gamma_param = 0.1
svr = SVR(kernel='rbf', C=C_param, gamma=gamma_param)

# Train the svr on the data and predict it over the same inputs.
rbf_model = svr.fit(X, Y)
y_rbf = rbf_model.predict(X)

fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X[:,0], X[:,1], Y, cmap=cm.coolwarm)
fig.colorbar(surf)
print np.shape(X)
#plt.scatter(X[:,0], X[:,1], c = Y)
#plt.scatter(X[:,0], X[:,1], c = y_rbf)
plt.show()


I am working on the file "Examples/Surrogate Modeling with Scikit SVM and RBF-checkpoint.ipynb".
The first task is:
So for the simple 2D case where we're trying to model a Sine function, SVM RBF regression works pretty well (at least over the domain of the inputs we trained the SVM on). What happens if we take our SVM and use it to predict values across a domain we didn't train on?
Can you write Python code for it?

Xnew = np.sort(8*PI * np.random.random((N*100,1)), 0)
y_pred = rbf_model.predict(Xnew)

f = plt.figure(figsize=fsize)
plt.scatter(X, Y, marker = 'x', label = 'data')
plt.plot(Xnew, y_pred, c = 'r', marker = '+', label = 'RBF Surrogate Model')
plt.plot(Xnew, np.sin(Xnew), label = 'Sine Function')

plt.xlabel('data')
plt.ylabel('outputs')
plt.legend(loc='lower right')
plt.show()


I am working on the file "Examples/Surrogate Modeling with Scikit SVM and RBF-checkpoint.ipynb".
The first task is:
We can use sklearn.cross_validation to make predictions from our model as well
Can you write Python code for it?

predicted = cross_validation.cross_val_predict(svr, X, Y,
                                               cv=cross_validation.LeaveOneOut(N))

fig, (ax1, ax2) = plt.subplots(1, 2)

ax1.plot(np.sort(X, axis=0), predicted, c='r')
ax1.plot(np.sort(X, axis=0), np.sin(X), c='b')

ax1.set_xlabel('data')
ax1.set_ylabel('predicted values')
ax2.scatter(Y, predicted)
ax2.plot([np.amin(Y), np.amax(Y)], [np.amin(Y), np.amax(Y)], 'k--' )
plt.show()


I am working on the file "Examples/TimeSeries_RetrieveVisualize.ipynb".
The first task is:
Connect to the ODM2 SQLite Database
This example uses an ODM2 SQLite database file loaded with a sensor-based, high-frequency temperature time series from a site in the Little Bear River, in Logan, Utah, from Utah State University. The database (USU_LittleBearRiver_timeseriesresults_ODM2.sqlite) contains "timeSeriesCoverage"-type results.
The example database is located in the data sub-directory.
Can you write Python code for it?

# Assign directory paths and SQLite file name
dbname_sqlite = "USU_LittleBearRiver_timeseriesresults_ODM2.sqlite"

sqlite_pth = os.path.join("data", dbname_sqlite)

try:
    session_factory = dbconnection.createConnection('sqlite', sqlite_pth)
    read = odm2rs.ReadODM2(session_factory)
    print("Database connection successful!")
except Exception as e:
    print("Unable to establish connection to the database: ", e)


I am working on the file "Examples/TimeSeries_RetrieveVisualize.ipynb".
The first task is:
Get a Result and its Attributes
Because all of the objects are returned in a nested form, if you retrieve a result, you can interrogate it to get all of its related attributes. When a Result object is returned, it includes objects that contain information about Variable, Units, ProcessingLevel, and the related Action that created that Result.
Can you write Python code for it?

print("------- Example of Retrieving Attributes of a Result -------")
try:
    firstResult = read.getResults()[0]
    frfa = firstResult.FeatureActionObj
    print("The following are some of the attributes for the Result retrieved: ")
    print("ResultID: {}".format(firstResult.ResultID))
    print("ResultTypeCV: {}".format(firstResult.ResultTypeCV))
    print("ValueCount: {}".format(firstResult.ValueCount))
    print("ProcessingLevel: {}".format(firstResult.ProcessingLevelObj.Definition))
    print("SampledMedium: {}".format(firstResult.SampledMediumCV))
    print("Variable: {}: {}".format(firstResult.VariableObj.VariableCode,
                                    firstResult.VariableObj.VariableNameCV))
    print("AggregationStatisticCV: {}".format(firstResult.AggregationStatisticCV))
    print("Units: {}".format(firstResult.UnitsObj.UnitsName))
    print("SamplingFeatureID: {}".format(frfa.SamplingFeatureObj.SamplingFeatureID))
    print("SamplingFeatureCode: {}".format(frfa.SamplingFeatureObj.SamplingFeatureCode))
except Exception as e:
    print("Unable to demo example of retrieving Attributes of a Result: {}".format(e))


I am working on the file "Examples/TimeSeries_RetrieveVisualize.ipynb".
The first task is:
Now plot the time series
First as a very quick and easy plot using the Pandas Dataframe plot method with default settings. Then with fancier matplotlib customizations of the axes and figure size.
Can you write Python code for it?

tsValues['DataValue'].plot()

fig, ax = plt.subplots(figsize=(12, 4))
tsValues['DataValue'].plot(ax=ax)

ax.set_ylabel('{} ({})'.format(
    tsResult.VariableObj.VariableNameCV,
    tsResult.UnitsObj.UnitsAbbreviation))
ax.set_xlabel('')

ax.xaxis.set_minor_locator(mpl.dates.MonthLocator())
ax.xaxis.set_minor_formatter(mpl.dates.DateFormatter('%b'))
ax.xaxis.set_major_locator(mpl.dates.YearLocator())
ax.xaxis.set_major_formatter(mpl.dates.DateFormatter('\n%Y'))


I am working on the file "Examples/TimeSeries_RetrieveVisualize.ipynb".
The first task is:
Retrieve Attributes of a Time Series Result using a ResultID
Use the ResultID (1) from the above result to issue a filtered query.
Can you write Python code for it?

# Filering on a single ResultID will invariably return a single result;
# so, get the single element in the returned list
tsResult = read.getResults(ids=[1])[0]

# Examine the object type and content
type(tsResult), vars(tsResult)


I am working on the file "Examples/TimeSeries_RetrieveVisualize.ipynb".
The first task is:
Run Some Basic Queries on the ODM2 Database
This section shows some examples of how to use the API to run both simple and more advanced queries on the ODM2 database, as well as how to examine the query output in convenient ways thanks to Python tools. The notebook WaterQualityMeasurements_RetrieveVisualize.ipynb includes more extensive examples of odm2api-based querying and examinations of the information that is returned.
Simple query functions like getVariables( ) return objects similar to the entities in ODM2, and individual attributes can then be retrieved from the objects returned.
Can you write Python code for it?

allVars = read.getVariables()

for x in allVars:
    print('{}: {}'.format(x.VariableCode, x.VariableNameCV))


I am working on the file "Examples/TimeSeries_RetrieveVisualize.ipynb".
The first task is:
odm2api version used to run this notebook:
Can you write Python code for it?


I am working on the file "Examples/Validation/sphere_concentration.ipynb".
The first task is:
We need to import here the data, modify them if needed and proceed
Can you write Python code for it?

umat_name = 'MIPLN' #This is the 5 character code for the periodic homogenization for multlayered composite
nstatev = 0 #The number of scalar variables required, everything is stored in sub-phases statevs

rho = 1.12 #The density of the material (overall)
c_p = 1.64 #The specific heat capacity (overall)

nphases = 2 #The number of phases
num_file = 0 #The num of the file that contains the subphases

psi_rve = 0.
theta_rve = 0.
phi_rve = 0.

props = np.array([nphases, num_file])

NPhases_file = dir + '/data/Nlayers0.dat'
NPhases = pd.read_csv(NPhases_file, delimiter=r'\s+', index_col=False, engine='python')
NPhases[::]

path_data = 'data'
path_results = 'results'
pathfile = 'path.txt'
outputfile = 'results_PLN.txt'
sim.solver(umat_name, props, nstatev, psi_rve, theta_rve, phi_rve, rho, c_p, path_data, path_results, pathfile, outputfile)

outputfile_macro =  dir + '/' + path_results + '/results_PLN_global-0.txt'
outputfile_micro1 =  dir + '/' + path_results + '/results_PLN_global-0-0.txt'
outputfile_micro2 =  dir + '/' + path_results + '/results_PLN_global-0-1.txt'

fig = plt.figure()

e11, e22, e33, e12, e13, e23, s11, s22, s33, s12, s13, s23 = np.loadtxt(outputfile_macro, usecols=(8,9,10,11,12,13,14,15,16,17,18,19), unpack=True)
plt.grid(True)
plt.plot(e11,s11, c='black')

e11, e22, e33, e12, e13, e23, s11, s22, s33, s12, s13, s23 = np.loadtxt(outputfile_micro1, usecols=(8,9,10,11,12,13,14,15,16,17,18,19), unpack=True)
plt.grid(True)
plt.plot(e11,s11, c='red')

e11, e22, e33, e12, e13, e23, s11, s22, s33, s12, s13, s23 = np.loadtxt(outputfile_micro2, usecols=(8,9,10,11,12,13,14,15,16,17,18,19), unpack=True)
plt.grid(True)
plt.plot(e11,s11, c='blue')

plt.xlabel('Strain')
plt.ylabel('Stress (MPa)')

plt.show()


I am working on the file "Examples/WaterQualityMeasurements_RetrieveVisualize.ipynb".
The first task is:
9/23/2018. NOTE CURRENT ISSUE REGARDING ValueDateTime RETURNED BY read.getResultValues. There seems to be a problem with the data type returned for ValueDateTime for SQLite databases. It should be a datetime, but it's currently a string. This is being investigated. For now, the x-axis in this plot and the one below do not show proper datetime values, as expected. Refer to the original notebook to see what the axis should look like. This problem wasn't present in Nov. 2017.
End with a fancier plot, facilitated via a function
If I'm going to reuse a series of steps, it's always helpful to write little generic functions that can be called to quickly and consistently get what we need. To conclude this demo, here's one such function that encapsulates the VariableID, getResults and getResultValues queries we showed above. Then we leverage it to create a nice 2-variable (2-axis) plot of TP and TN vs time, and conclude with a reminder that we have ready access to related metadata about analytical lab methods and such.
Can you write Python code for it?

def get_results_and_values(siteid, variablecode):
    v = variables_df[variables_df['VariableCode'] == variablecode]
    variableID = v.index[0]

    results = read.getResults(siteid=siteid, variableid=variableID, restype="Measurement")
    resultIDList = [x.ResultID for x in results]
    resultValues = read.getResultValues(resultids=resultIDList, lowercols=False)

    return resultValues, results


I am working on the file "Examples/WaterQualityMeasurements_RetrieveVisualize.ipynb".
The first task is:
A site has a SiteTypeCV. Let's examine the site type distribution, and use that information to create a new GeoDataFrame column to specify a map marker color by SiteTypeCV.
Can you write Python code for it?

gdf['SiteTypeCV'].value_counts()

gdf["color"] = gdf.apply(lambda feat: 'green' if feat['SiteTypeCV'] == 'Stream' else 'red', axis=1)


I am working on the file "Examples/WaterQualityMeasurements_RetrieveVisualize.ipynb".
The first task is:
Add a new Sampling Feature
Just to llustrate how to add a new entry. We won't "commit" (save) the sampling feature to the database.
Can you write Python code for it?

sitesf0 = siteFeatures[0]

try:
    newsf = SamplingFeatures()
    session = session_factory.getSession()
    newsf.FeatureGeometryWKT = "POINT(-111.946 41.718)"
    newsf.Elevation_m = 100
    newsf.ElevationDatumCV = sitesf0.ElevationDatumCV
    newsf.SamplingFeatureCode = "TestSF"
    newsf.SamplingFeatureDescription = "this is a test to add a sampling feature"
    newsf.SamplingFeatureGeotypeCV = "Point"
    newsf.SamplingFeatureTypeCV = sitesf0.SamplingFeatureTypeCV
    newsf.SamplingFeatureUUID = sitesf0.SamplingFeatureUUID+"2"
    session.add(newsf)
    # To save the new sampling feature, do session.commit()
    print("New sampling feature created, but not saved to database.\n")
    print(newsf)
except Exception as e :
    print("error adding a sampling feature: {}".format(e))


I am working on the file "Examples/WaterQualityMeasurements_RetrieveVisualize.ipynb".
The first task is:
Connect to the ODM2 SQLite Database
This example uses an ODM2 SQLite database file loaded with water quality sample data from multiple monitoring sites in the iUTAH Gradients Along Mountain to Urban Transitions (GAMUT) water quality monitoring network. Water quality samples have been collected and analyzed for nitrogen, phosphorus, total coliform, E-coli, and some water isotopes. The database (iUTAHGAMUT_waterquality_measurementresults_ODM2.sqlite) contains "measurement"-type results.
The example database is located in the data sub-directory.
Can you write Python code for it?

# Assign directory paths and SQLite file name
dbname_sqlite = "iUTAHGAMUT_waterquality_measurementresults_ODM2.sqlite"

sqlite_pth = os.path.join("data", dbname_sqlite)

try:
    session_factory = dbconnection.createConnection('sqlite', sqlite_pth)
    read = odm2rs.ReadODM2(session_factory)
    print("Database connection successful!")
except Exception as e:
    print("Unable to establish connection to the database: ", e)


I am working on the file "Examples/WaterQualityMeasurements_RetrieveVisualize.ipynb".
The first task is:
Fancy plotting, leveraging the Pandas plot method and matplotlib.
Can you write Python code for it?

# Plot figure and axis set up (just *one* subplot, actually)
f, ax = plt.subplots(1, figsize=(13, 6))

# First plot (left axis)
VariableCode = 'TP'
resultValues_TP, results_TP = get_results_and_values(siteID, VariableCode)
resultValues_TP.plot(x='ValueDateTime', y='DataValue', label=VariableCode,
                     style='o-', kind='line', ax=ax)
ax.set_ylabel("{0}: {1} ({2})".format(VariableCode, results_TP[0].VariableObj.VariableNameCV,
                                      results_TP[0].UnitsObj.UnitsAbbreviation))

# Second plot (right axis)
VariableCode = 'TN'
resultValues_TN, results_TN = get_results_and_values(siteID, VariableCode)
resultValues_TN.plot(x='ValueDateTime', y='DataValue', label=VariableCode,
                     style='^-', kind='line', ax=ax,
                     secondary_y=True)
ax.right_ax.set_ylabel("{0}: {1} ({2})".format(VariableCode, results_TN[0].VariableObj.VariableNameCV,
                                               results_TN[0].UnitsObj.UnitsAbbreviation))

# Tweak the figure
ax.legend(loc='upper left')
ax.right_ax.legend(loc='upper right')

ax.grid(True)
ax.set_xlabel('')
ax.set_title(relatedSite.SamplingFeatureName);


I am working on the file "Examples/WaterQualityMeasurements_RetrieveVisualize.ipynb".
The first task is:
Finally, let's show some useful metadata. Use the Results records and their relationship to Actions (via FeatureActions) to extract and print out the Specimen Analysis methods used for TN and TP. Or at least for the first result for each of the two variables; methods may have varied over time, but the specific method associated with each result is stored in ODM2 and available.
Can you write Python code for it?

results_faam = lambda results, i: results[i].FeatureActionObj.ActionObj.MethodObj

print("TP METHOD:  {0} ({1})".format(results_faam(results_TP, 0).MethodName,
                                     results_faam(results_TP, 0).MethodDescription))
print("TN METHOD:  {0} ({1})".format(results_faam(results_TN, 0).MethodName,
                                     results_faam(results_TN, 0).MethodDescription))


I am working on the file "Examples/WaterQualityMeasurements_RetrieveVisualize.ipynb".
The first task is:
Get a Result and its Attributes
Because all of the objects are returned in a nested form, if you retrieve a result, you can interrogate it to get all of its related attributes. When a Result object is returned, it includes objects that contain information about Variable, Units, ProcessingLevel, and the related Action that created that Result.
Can you write Python code for it?

print("------- Example of Retrieving Attributes of a Result -------")
try:
    firstResult = read.getResults()[0]
    frfa = firstResult.FeatureActionObj
    print("The following are some of the attributes for the Result retrieved: ")
    print("ResultID: {}".format(firstResult.ResultID))
    print("ResultTypeCV: {}".format(firstResult.ResultTypeCV))
    print("ValueCount: {}".format(firstResult.ValueCount))
    print("ProcessingLevel: {}".format(firstResult.ProcessingLevelObj.Definition))
    print("SampledMedium: {}".format(firstResult.SampledMediumCV))
    print("Variable: {}: {}".format(firstResult.VariableObj.VariableCode,
                                    firstResult.VariableObj.VariableNameCV))
    print("Units: {}".format(firstResult.UnitsObj.UnitsName))
    print("SamplingFeatureID: {}".format(frfa.SamplingFeatureObj.SamplingFeatureID))
    print("SamplingFeatureCode: {}".format(frfa.SamplingFeatureObj.SamplingFeatureCode))
except Exception as e:
    print("Unable to demo example of retrieving Attributes of a Result: ", e)


I am working on the file "Examples/WaterQualityMeasurements_RetrieveVisualize.ipynb".
The first task is:
Get all People
Another simple query.
Can you write Python code for it?

allPeople = read.getPeople()
pd.DataFrame.from_records([vars(person) for person in allPeople]).head()


I am working on the file "Examples/WaterQualityMeasurements_RetrieveVisualize.ipynb".
The first task is:
Make a Connection to the ODM2 SQLite Database
This example uses an ODM2 SQLite database loaded with water quality sample data from multiple monitoring sites in the iUTAH Gradients Along Mountain to Urban Transitions (GAMUT) water quality monitoring network. Water quality samples have been collected and analyzed for nitrogen, phosphorus, total coliform, E-coli, and some water isotopes. The database (iUTAHGAMUT_waterquality_measurementresults_ODM2.sqlite) contains "measurement"-type results.
The example database is located in the data sub-directory.
Can you write Python code for it?

# Assign directory paths and SQLite file name
dbname_sqlite = "iUTAHGAMUT_waterquality_measurementresults_ODM2.sqlite"

sqlite_pth = os.path.join("data", dbname_sqlite)

try:
    session_factory = dbconnection.createConnection('sqlite', sqlite_pth, 2.0)
    read = odm2rs.ReadODM2(session_factory)
    print("Database connection successful!")
except Exception as e:
    print("Unable to establish connection to the database: ", e)


I am working on the file "Examples/WaterQualityMeasurements_RetrieveVisualize.ipynb".
The first task is:
Note: While the database holds a copy of the ODM2 Controlled Vocabularies, the complete description of each CV term is available from a web request to the CV API at http://vocabulary.odm2.org. Want to know more about how a "spring" is defined? Here's one simple way, using Pandas to access and parse the CSV web service response.
Can you write Python code for it?

sitetype = 'spring'
pd.read_csv("http://vocabulary.odm2.org/api/v1/sitetype/{}/?format=csv".format(sitetype))


I am working on the file "Examples/WaterQualityMeasurements_RetrieveVisualize.ipynb".
The first task is:
Now we'll create an interactive and helpful Folium map of the sites. This map features:
- Automatic panning to the location of the sites (no hard wiring, except for the zoom scale), based on GeoPandas functionality and information from the ODM2 Site Sampling Features
- Color coding by SiteTypeCV
- Marker clustering
- Simple marker pop ups with content from the ODM2 Site Sampling Features
Can you write Python code for it?

c = gdf.unary_union.centroid
m = folium.Map(location=[c.y, c.x], tiles='CartoDB positron', zoom_start=11)

marker_cluster = MarkerCluster().add_to(m)
for idx, feature in gdf.iterrows():
    folium.Marker(location=[feature.geometry.y, feature.geometry.x],
                  icon=folium.Icon(color=feature['color']),
                  popup="{0} ({1}): {2}".format(
                      feature['SamplingFeatureCode'], feature['SiteTypeCV'],
                      feature['SamplingFeatureName'])
                 ).add_to(marker_cluster)

# Done with setup. Now render the map
m


I am working on the file "Examples/WaterQualityMeasurements_RetrieveVisualize.ipynb".
The first task is:
Retrieve the Result (Data) Values, Then Create a Quick Time Series Plot of the Data
Now I can retrieve all of the data values associated with the list of Results I just retrieved. In ODM2, water chemistry measurements are stored as "Measurement" results. Each "Measurement" Result has a single data value associated with it. So, for convenience, the getResultValues( ) function allows you to pass in a list of ResultIDs so you can get the data values for all of them back in a Pandas data frame object, which is easier to work with. Once I've got the data in a Pandas data frame object, I can use the plot( ) function directly on the data frame to create a quick visualization.
Can you write Python code for it?

# Get all of the data values for the Results in the list created above
# Call getResultValues, which returns a Pandas Data Frame with the data
resultValues = read.getResultValues(resultids=resultIDList, lowercols=False)
resultValues.head()

# Plot the time sequence of Measurement Result Values
ax = resultValues.plot(x='ValueDateTime', y='DataValue', title=relatedSite.SamplingFeatureName,
                       kind='line', use_index=True, linestyle='solid', style='o')
ax.set_ylabel("{0} ({1})".format(results[0].VariableObj.VariableNameCV,
                                 results[0].UnitsObj.UnitsAbbreviation))
ax.set_xlabel('Date/Time')
ax.grid(True)
ax.legend().set_visible(False)


I am working on the file "Examples/WaterQualityMeasurements_RetrieveVisualize.ipynb".
The first task is:
Return Results and Data Values for a Particular Site/Variable
From the list of Variables returned above and the information about the SamplingFeature I queried above, I know that VariableID = 2 for Total Phosphorus and SiteID = 1 for the Red Butte Creek site at 1300E. I can use the getResults( ) function to get all of the Total Phosphorus results for this site by passing in the VariableID and the SiteID.
Can you write Python code for it?

siteID = 1  # Red Butte Creek at 1300 E (obtained from the getRelatedSamplingFeatures query)

v = variables_df[variables_df['VariableCode'] == 'TP']
variableID = v.index[0]

results = read.getResults(siteid=siteID, variableid=variableID, restype="Measurement")
# Get the list of ResultIDs so I can retrieve the data values associated with all of the results
resultIDList = [x.ResultID for x in results]
len(resultIDList)


I am working on the file "Examples/WaterQualityMeasurements_RetrieveVisualize.ipynb".
The first task is:
Site Sampling Features: pass arguments to the API query
Some of the API functions accept arguments that let you subset what is returned. For example, I can query the database using the getSamplingFeatures( ) function and pass it a SamplingFeatureType of "Site" to return a list of those SamplingFeatures that are Sites.
Can you write Python code for it?

# Get all of the SamplingFeatures from the ODM2 database that are Sites
siteFeatures = read.getSamplingFeatures(sftype='Site')

# Read Sites records into a Pandas DataFrame
# "if sf.Latitude" is used only to instantiate/read Site attributes)
df = pd.DataFrame.from_records([vars(sf) for sf in siteFeatures if sf.Latitude])


I am working on the file "Examples/WaterQualityMeasurements_RetrieveVisualize.ipynb".
The first task is:
The last block of code returns a particular Measurement Result. From that I can get the SamplingFeaureID (in this case 26) for the Specimen from which the Result was generated. But, if I want to figure out which Site the Specimen was collected at, I need to query the database to get the related Site SamplingFeature.  I can use getRelatedSamplingFeatures( ) for this.  Once I've got the SamplingFeature for the Site, I could get the rest of the SamplingFeature attributes.
Retrieve the "Related" Site at which a Specimen was collected
Can you write Python code for it?

# Pass the Sampling Feature ID of the specimen, and the relationship type
relatedSite = read.getRelatedSamplingFeatures(sfid=26, relationshiptype='Was Collected at')[0]

vars(relatedSite)


I am working on the file "Examples/WaterQualityMeasurements_RetrieveVisualize.ipynb".
The first task is:
You can also drill down and get objects linked by foreign keys. The API returns related objects in a nested hierarchy so they can be interrogated in an object oriented way. So, if I use the getResults( ) function to return a Result from the database (e.g., a "Measurement" Result), I also get the associated Action that created that Result (e.g., a "Specimen analysis" Action).
Can you write Python code for it?

try:
    # Call getResults, but return only the first Result
    firstResult = read.getResults()[0]
    frfa = firstResult.FeatureActionObj
    frfaa = firstResult.FeatureActionObj.ActionObj
    print("The FeatureAction object for the Result is: ", frfa)
    print("The Action object for the Result is: ", frfaa)

    # Print some Action attributes in a more human readable form
    print("\nThe following are some of the attributes for the Action that created the Result: ")
    print("ActionTypeCV: {}".format(frfaa.ActionTypeCV))
    print("ActionDescription: {}".format(frfaa.ActionDescription))
    print("BeginDateTime: {}".format(frfaa.BeginDateTime))
    print("EndDateTime: {}".format(frfaa.EndDateTime))
    print("MethodName: {}".format(frfaa.MethodObj.MethodName))
    print("MethodDescription: {}".format(frfaa.MethodObj.MethodDescription))
except Exception as e:
    print("Unable to demo Foreign Key Example: {}".format(e))


I am working on the file "Examples/WaterQualityMeasurements_RetrieveVisualize.ipynb".
The first task is:
odm2api version used to run this notebook:
Can you write Python code for it?


I am working on the file "Examples/demo.ipynb".
The first task is:
Awesome. That was pretty quick huh? Without this machine learning method, the exact same image we just analyzed takes over 8 minutes to run. Yes! Now let's take a look at what we get.
Can you write Python code for it?

# Something went wrong in the data on the first line. Let's skip it.
tau_img = tau_img[1:]
real_sum_img = real_sum_img[1:]
fft_sum_img = fft_sum_img[1:]
amp_diff_img = amp_diff_img[1:]

plt.figure()
upper_lim = (tau_img.mean() + 2*tau_img.std())
lower_lim = (tau_img.mean() - 2*tau_img.std())
plt.imshow(tau_img,vmin=lower_lim, vmax=upper_lim,cmap = 'cubehelix')
plt.show()


I am working on the file "Examples/demo.ipynb".
The first task is:
Neato!
Looks like that function is all done. We now have an SVR Object called "fit_object" as well as a result of the fit called "fit_tau". Let's take a look at the result of the fit by comparing it to the actual input tau.
Can you write Python code for it?

plt.figure()
plt.title('Fit Time Constant vs. Actual')
plt.plot(fit_tau, 'bo')
plt.plot(tau_array,'g')
plt.ylabel('Tau (s)')
plt.yscale('log')
plt.show()

# Calculate the error at each measurement.
error = (tau_array - fit_tau) / tau_array

plt.figure()
plt.title('Error Signal')
plt.plot(tau_array, error)
plt.ylabel('Error (%)')
plt.xlabel('Time Constant (s)')
plt.xscale('log')
plt.show()


I am working on the file "Examples/demo.ipynb".
The first task is:
You can definitely begin to make out some of the structure that is occuring in the photovoltaic performance of this device. This image looks great, but there are still many areas of improvement. For example, I will need to extensively prove that this image is not purely a result of topographical cross-talk. If this image is correct, this is a significant improvement on our current imaging technique.
The Features
In the next cell we show an image of the various features that were calculated from the raw deflection signal. Some features more clearly matter than others and indicate that the search for better and more representative features is desirable. However, I think this is a great start to a project I hope to continue developing in the future.
Can you write Python code for it?

fig, axs = plt.subplots(nrows=3)
axs[0].imshow(real_sum_img ,'hot')
axs[0].set_title('Total Signal Sum')

axs[1].imshow(fft_sum_img, cmap='hot')
axs[1].set_title('Sum of the FFT Power Spectrum')

axs[2].imshow(amp_diff_img, cmap='hot')
axs[2].set_title('Difference in Amplitude After Trigger')
plt.tight_layout()
plt.show()


I am working on the file "Examples/etopo_fast/etopo.ipynb".
The first task is:
Running pyBadlands
We can run the model for a given period. The end time in the XmL input file is set to 500k years but you might want to run the model for a coupled of iterations and check the output before running the model for the entire simulation time. This is done by putting the time in the run_to_time function.
Here we go for the full time directly... it should take less than 10 minutes on a single processor if you keep the initial setting unchanged. By changing the resfactor in the XmL input file you will change both the resolution and the computation time.
Can you write Python code for it?

# Run model for 500k years. This takes a few minutes.
model.run_to_time(500000)


I am working on the file "Examples/immune/Analyse_pMHC.ipynb".
The first task is:
Import required libraries
Can you write Python code for it?

%matplotlib notebook
import matplotlib.pyplot as plt
import numpy as np
from  ipywidgets import widgets
from ipywidgets import interact, interactive, fixed
from IPython.display import display,HTML,clear_output

HTML('''<script>code_show=true;function code_toggle() {if (code_show){$('div.input').hide();} else {$('div.input').show();} code_show = !code_show} $( document ).ready(code_toggle);</script><form action="javascript:code_toggle()"><input type="submit" value="Click here to toggle on/off the raw code."></form>''')
from  Immune import Add_ons_pMHC
import phievo.AnalysisTools as AT
from  phievo.AnalysisTools.Notebook import Notebook

notebook = Notebook()
notebook.run_dynamics_pMHC = Add_ons_pMHC.Run_Dynamics_pMHC(notebook)
notebook.plot_pMHC = Add_ons_pMHC.Plot_pMHC(notebook)
notebook.plot_layout_immune = Add_ons_pMHC.Plot_Layout_Immune(notebook)


I am working on the file "Examples/immune/Analyse_pMHC.ipynb".
The first task is:
Plot Response function
The response function for Immune displays the concentration of all species at the end of simulation as a function of the number of ligands presented. The output is the solid line. Left column is for binding time $\tau=3s$, right column for binding time $\tau=10s$. The ideal case such as ``adaptive sorting" corresponds to horizontal lines for the Output, at different levels for different the $\tau$ s
Can you write Python code for it?


I am working on the file "Examples/immune/Analyse_pMHC.ipynb".
The first task is:
Plot observable
For our immune simulations, the fitness is the mutual information between output concentrations (taken as a probability distribution) and binding time. An ideal fitness is $-1$.
Can you write Python code for it?


I am working on the file "Examples/immune/Analyse_pMHC.ipynb".
The first task is:
Run Dynamics
Can you write Python code for it?


I am working on the file "Examples/immune/Analyse_pMHC.ipynb".
The first task is:
Select Generation
Can you write Python code for it?


I am working on the file "Examples/immune/Analyse_pMHC.ipynb".
The first task is:
Select Seed
Can you write Python code for it?


I am working on the file "Examples/immune/Analyse_pMHC.ipynb".
The first task is:
Select the Project
Can you write Python code for it?


I am working on the file "Examples/jupyter_notebooks/00_Enhancing_the_ZOS_API_Interface.ipynb".
The first task is:
2. Single-step initialization of ZOS API Interface and instantiation of an Optical System
The first enhancement is the complete elimination of boiler-plate code to get create and initialize an optical system object and get started. We just need to create an instance of a PyZOS OpticalSystem to get started. The optical system can be either a sequential or a non-sequential system.
Can you write Python code for it?

if USE_PYZOS:
    osys = zos.OpticalSystem()     # Directly get the Primary Optical system
else:
    # using ZOS API directly with pywin32
    EnsureModule('ZOSAPI_Interfaces', 0, 1, 0)
    connect = EnsureDispatch('ZOSAPI.ZOSAPI_Connection')
    app = connect.CreateNewApplication() # The Application
    osys = app.PrimarySystem             # Optical system (primary)

# common
osys.New(False)


I am working on the file "Examples/jupyter_notebooks/00_Enhancing_the_ZOS_API_Interface.ipynb".
The first task is:
3.  Introspection of properties of ZOS objects on Tab press
Because of the way property attributes are mapped by the PyWin32 library, the properties are not introspectable (visible) on Tab press in smart editors such as IPython. Only the methods are shown upon pressing the Tab button (see figure below). Note that although the properties are not "visible" they are still accessible.
PyZOS enhances the user experience by showing both the method and the properties of the ZOS object (by creating a wrapped object and delegating the attribute access to the underlying ZOS API COM objects). In addition, the properties are easily identified by the prefix p in front of the property attribute names.
Can you write Python code for it?

Image('./images/00_01_property_attribute.png')

if USE_PYZOS:
    sdir = osys.pTheApplication.pSamplesDir
else:
    sdir = osys.TheApplication.SamplesDir

sdir


I am working on the file "Examples/jupyter_notebooks/00_Enhancing_the_ZOS_API_Interface.ipynb".
The first task is:
6. Ability to add custom methods and properties to any ZOS API object
PyZOS allows us to easily extend the functionality of any ZOS API object by adding custom methods and properties, supporting the idea of developing a useful library over time. In the following block of codes we have added custom methods zInsertNewSurfaceAt() and zSetSurfaceData() to the OpticalSystem ojbect.
(Please note there is no implication that one cannot build a common set of functions without using PyZOS. Here, we only show that PyZOS allows us to add methods to the ZOS objects. How to add new methods PyZOS objects will be explained later.)
Can you write Python code for it?

# Set Lens data Editor
if USE_PYZOS:
    osys.zInsertNewSurfaceAt(1)
    osys.zInsertNewSurfaceAt(1)
    osys.zSetSurfaceData(1, thick=10, material='N-BK7', comment='front of lens')
    osys.zSetSurfaceData(2, thick=50, comment='rear of lens')
    osys.zSetSurfaceData(3, thick=350, comment='Stop is free to move')
else:
    lde = osys.LDE
    lde.InsertNewSurfaceAt(1)
    lde.InsertNewSurfaceAt(1)
    surf1 = lde.GetSurfaceAt(1)
    surf2 = lde.GetSurfaceAt(2)
    surf3 = lde.GetSurfaceAt(3)
    surf1.Thickness = 10.0
    surf1.Comment = 'front of lens'
    surf1.Material = 'N-BK7'
    surf2.Thickness = 50.0
    surf2.Comment = 'rear of lens'
    surf3.Thickness = 350.0
    surf3.Comment = 'Stop is free to move'


I am working on the file "Examples/jupyter_notebooks/00_Enhancing_the_ZOS_API_Interface.ipynb".
The first task is:
Create a second optical system to load a standard lens for FFT MTF analysis
Can you write Python code for it?

%matplotlib inline

osys2 = zos.OpticalSystem()

# load a lens into the Optical System
lens = 'Cooke 40 degree field.zmx'
zfile = os.path.join(sdir, 'Sequential', 'Objectives', lens)
osys2.LoadFile(zfile, False)

osys2.pSystemName

# check the aperture
osys2.pSystemData.pAperture.pApertureValue

# a more detailed information about the pupil
osys2.pLDE.GetPupil()

# Thickness of a surface
surf6 = osys2.pLDE.GetSurfaceAt(6)
surf6.pThickness

# Thickness of surface through custom added method
osys2.zGetSurfaceData(6).thick

# Open Analysis windows in the system currently
num_analyses = osys2.pAnalyses.pNumberOfAnalyses
for i in range(num_analyses):
    print(osys2.pAnalyses.Get_AnalysisAtIndex(i+1).pGetAnalysisName)

#mtf analysis
fftMtf = osys2.pAnalyses.New_FftMtf() # open a new FFT MTF window
fftMtf

fftMtf_settings = fftMtf.GetSettings()
fftMtf_settings

# Set the maximum frequency to 160 lp/mm
fftMtf_settings.pMaximumFrequency = 160.0

# run the analysis
fftMtf.ApplyAndWaitForCompletion()

# results
fftMtf_results = fftMtf.GetResults() # returns an <pyzos.zosutils.IAR_ object

# info about the result data
print('Number of data grids:', fftMtf_results.pNumberOfDataGrids)
print('Number of data series:', fftMtf_results.pNumberOfDataSeries)

ds = fftMtf_results.GetDataSeries(1)

ds.pDescription

ds.pNumSeries

ds.pSeriesLabels


I am working on the file "Examples/jupyter_notebooks/00_Enhancing_the_ZOS_API_Interface.ipynb".
The first task is:
Enhancements and capabilities provided by PyZOS

Visible user-interface for the headless standalone ZOS-API COM application
Single-step initialization of ZOS API Interface and instantiation of an Optical System
Introspection of properties of ZOS objects on Tab press
Ability to override methods of existing ZOS objects
Tab completion and introspection of API constants
Ability to add custom methods and properties to any ZOS-API object

1. Visible user-interface for the headless standalone ZOS-API COM application
The PyZOS library provides three functions (instance methods of OpticalSystem) for the sync-with-ui mechanism.
The sync-with-ui mechanism may be turned on during the instantiation of the OpticalSystem object using the parameter sync_ui set to True (see the screen-shot video below) or using the method zSyncWithUI() of the OpticalSystem instance at other times.
The other two functions

zPushLens() -- for copying a lens from the headless ZOS COM server (invisible) to a running user-interface application (visible)
zGetRefresh()-- for copying a lens from the running user-interface application (visible) to the headless ZOS COM server (invisible).

enable the user to interact with a running OpticStudio user-interface and observe the changes made through the API instantly in the user-interface.
(If you cannot see the video in the frame below, or if the resolution is not good enough within this notebook, here is a direct link to the Youtube video: https://www.youtube.com/watch?v=ot5CrjMXc_w&feature=youtu.be)
Can you write Python code for it?

# a screenshot video of the feature:
display(YouTubeVideo("ot5CrjMXc_w?t", width=900, height=600))


I am working on the file "Examples/jupyter_notebooks/00_Enhancing_the_ZOS_API_Interface.ipynb".
The first task is:
Here we can demonstrate another strong reason why we may require to add methods to ZOS objects when using the ZOS API with pywin32 library. The problem is illustrated in the figure below. According to the ZOS API manual, the MFE object (IMeritFunctionEditor) should have the methods AddRow(), DeleteAllRows(), DeleteRowAt(), DeleteRowsAt(), InsertRowAt() and GetRowAt() that it inherits from IEditor object. However, due to the way pywin32 handles inheritence, these methods (defined in the base class) are apparently not available to the derived class object [1].
Can you write Python code for it?


I am working on the file "Examples/jupyter_notebooks/00_Enhancing_the_ZOS_API_Interface.ipynb".
The first task is:
It may seem that if we are using PyZOS, then the application is not available. In fact, it is available through a property of the PyZOS OpticalSystem object:
Can you write Python code for it?

if USE_PYZOS:
    print(osys.pTheApplication)


I am working on the file "Examples/jupyter_notebooks/00_Enhancing_the_ZOS_API_Interface.ipynb".
The first task is:
Since these objects has not been wrapped (at the time of this writing), we will wrap them first
Can you write Python code for it?

dsXdata = ds.pXData
dsYdata = ds.pYData

freq = np.array(dsXdata.pData)
mtf = np.array(dsYdata.pData) # shape = (len(freq) , ds.pNumSeries)

# build a function to plot the FFTMTF
def plot_FftMtf(optical_system, max_freq=160.0):
    fftMtf = optical_system.pAnalyses.New_FftMtf()
    fftMtf.GetSettings().pMaximumFrequency = max_freq
    fftMtf.ApplyAndWaitForCompletion()
    fftMtf_results = fftMtf.GetResults()

    fig, ax = plt.subplots(1,1, figsize=(8,6))
    num_dataseries = fftMtf_results.pNumberOfDataSeries
    col = ['#0080FF', '#F52080', '#00CC60', '#B96F20', '#1f77b4',
           '#ff7f0e', '#2ca02c', '#8c564b', '#00BFFF', '#FF8073']

    for i in range(num_dataseries):
        ds = fftMtf_results.GetDataSeries(i)
        dsXdata = ds.pXData
        dsYdata = ds.pYData
        freq = np.array(dsXdata.pData)
        mtf = np.array(dsYdata.pData) # shape = (len(freq) , ds.pNumSeries)
        ax.plot(freq[::5], mtf[::5, 0], color=col[i], lw=1.5, label=ds.pDescription) # tangential
        ax.plot(freq[::5], mtf[::5, 1], '--', color=col[i], lw=2) # sagittal
        ax.set_xlabel('Spatial Frequency (lp/mm)')
        ax.set_ylabel('FFT MTF')
        ax.legend()
    plt.text(0.85, -0.1,u'\u2014 {}'.format(ds.pSeriesLabels[0]), transform=ax.transAxes)
    plt.text(0.85, -0.15,'-- {}'.format(ds.pSeriesLabels[1]), transform=ax.transAxes)
    plt.grid()
    plt.show()

# FFT MTF of Optical System 2
plot_FftMtf(osys2)

# FFT MTF of Optical System 1
plot_FftMtf(osys, 100)

# Close the application
if USE_PYZOS:
    app = osys.pTheApplication
app.CloseApplication()
del app


I am working on the file "Examples/jupyter_notebooks/00_Enhancing_the_ZOS_API_Interface.ipynb".
The first task is:
The custom functions are introspectable, and they are identified by the prefix z to their names as shown in the following figure.
Can you write Python code for it?

Image('./images/00_03_extendiblity_custom_functions.png')

# Setting solves - Make thickness and radii variable
# nothing to demonstrate in particular in this block of code

if USE_PYZOS:
    osys.pLDE.GetSurfaceAt(1).pRadiusCell.MakeSolveVariable()
    osys.pLDE.GetSurfaceAt(1).pThicknessCell.MakeSolveVariable()
    osys.pLDE.GetSurfaceAt(2).pRadiusCell.MakeSolveVariable()
    osys.pLDE.GetSurfaceAt(2).pThicknessCell.MakeSolveVariable()
    osys.pLDE.GetSurfaceAt(3).pThicknessCell.MakeSolveVariable()
else:
    surf1.RadiusCell.MakeSolveVariable()
    surf1.ThicknessCell.MakeSolveVariable()
    surf2.RadiusCell.MakeSolveVariable()
    surf2.ThicknessCell.MakeSolveVariable()
    surf3.ThicknessCell.MakeSolveVariable()

# Setting up the default merit function
# this code block again shows that we can create add custom methods
# based on our requirements
if USE_PYZOS:
    osys.zSetDefaultMeritFunctionSEQ(ofType=0, ofData=1, ofRef=0, rings=2, arms=0, grid=0,
                                     useGlass=True, glassMin=3, glassMax=15, glassEdge=3,
                                     useAir=True, airMin=0.5, airMax=1000, airEdge=0.5)
else:
    mfe = osys.MFE
    wizard = mfe.SEQOptimizationWizard
    wizard.Type = 0          # RMS
    wizard.Data = 1          # Spot Radius
    wizard.Reference = 0     # Centroid
    wizard.Ring = 2          # 3 Rings
    wizard.Arm = 0           # 6 Arms
    wizard.IsGlassUsed = True
    wizard.GlassMin = 3
    wizard.GlassMax = 15
    wizard.GlassEdge = 3
    wizard.IsAirUsed = True
    wizard.AirMin = 0.5
    wizard.AirMax = 1000
    wizard.AirEdge = 0.5
    wizard.IsAssumeAxialSymmetryUsed = True
    wizard.CommonSettings.OK()


I am working on the file "Examples/mountain/Hydrometrics.ipynb".
The first task is:
1. Load catchments parameters
We first have to define the path to the Badlands outputs we want to analyse. In addition Badlands is creating several files for each processors that have been used, you need to specify this number in the ncpus variable.
We then need to provide a point coordinates (X,Y) contained in the catchment of interest. This point doesn't need to be the outlet of the catchment.
For more information regarding the function uncomment the following line.
Can you write Python code for it?

#help(hydr.hydroGrid.__init__)

hydro1 = hydr.hydroGrid(folder='output/h5', ncpus=1, \
                          ptXY = [40599,7656.65])

hydro2 = hydr.hydroGrid(folder='output/h5', ncpus=1, \
                          ptXY = [33627.6,30672.9])


I am working on the file "Examples/mountain/Hydrometrics.ipynb".
The first task is:
3. Extract catchment main stream
We now extract the main stream for the considered catchment based on flow
discharge values.
Can you write Python code for it?

#help(hydro.extractMainstream)

hydro1.extractMainstream()
hydro2.extractMainstream()


I am working on the file "Examples/mountain/Hydrometrics.ipynb".
The first task is:
5. River profile through time
Using the same functions as before we can now create the river profile evolution through time and plot it on a single graph.
Can you write Python code for it?

#help(hydro.timeProfiles)

hydro0 = hydr.hydroGrid(folder='output/h5', ncpus=1, \
                          ptXY = [40599,7656.65])

timeStp = [20,40,60,80,100,120,140,160,180,200]
timeMA = map(lambda x: x * 0.25, timeStp)
print 'Profile time in Ma:',timeMA
dist = []
elev = []
for t in range(len(timeStp)):
    hydro0.getCatchment(timestep=timeStp[t])
    hydro0.extractMainstream()
    hydro0.computeParams(kd=8.e-1, kc=5.e-6, m=0.5, n=1., num=1000)
    dist.append(hydro0.dist)
    elev.append(hydro0.Zdata)

hydro0.timeProfiles(pData = elev, pDist = dist, width = 1000, height = 600, linesize = 3,
                    title = 'River profile through time')

hydro00 = hydr.hydroGrid(folder='output/h5', ncpus=1, \
                          ptXY = [33627.6,30672.9])

timeStp = [20,40,60,80,100,120,140,160,180,200]
timeMA = map(lambda x: x * 0.25, timeStp)
print 'Profile time in Ma:',timeMA
dist = []
elev = []
for t in range(len(timeStp)):
    hydro00.getCatchment(timestep=timeStp[t])
    hydro00.extractMainstream()
    hydro00.computeParams(kd=8.e-1, kc=5.e-6, m=0.5, n=1., num=50)
    dist.append(hydro00.dist)
    elev.append(hydro00.Zdata)

hydro00.timeProfiles(pData = elev, pDist = dist, width = 1000, height = 600, linesize = 3,
                    title = 'River profile through time')


I am working on the file "Examples/mountain/Hydrometrics.ipynb".
The first task is:
As for the global stream network, you can use the viewStream function to visualise the main stream dataset.
Can you write Python code for it?

#help(hydro.viewStream)

hydro1.viewStream(linePlot = False, lineWidth = 1, markerSize = 7,
                 val = 'Z', width = 300, height = 500, colorMap = cm.jet,
                 colorScale = 'Jet', reverse = False,
                 title = '
Stream network graph 1')

hydro2.viewStream(linePlot = True, lineWidth = 1, markerSize = 7,
                 val = 'Z', width = 300, height = 500, colorMap = cm.jet,
                 colorScale = 'Jet', reverse = False,
                 title = '
Stream network graph 2')


I am working on the file "Examples/mountain/Hydrometrics.ipynb".
The first task is:
We can visualise the stream network using the viewNetwork function. The following paramters can be displayed:
- $\chi$ paramater 'chi',
- elevation 'Z',
- discharge 'FA' (logarithmic values)
Can you write Python code for it?

#help(hydro.viewNetwork)

hydro1.viewNetwork(markerPlot = False, linePlot = True, lineWidth = 2, markerSize = 15,
                 val = 'chi', width = 300, height = 500, colorMap = cm.viridis,
                 colorScale = 'Viridis', reverse = False,
                 title = '
Stream network graph 1')

hydro2.viewNetwork(markerPlot = False, linePlot = True, lineWidth = 2, markerSize = 15,
                 val = 'chi', width = 300, height = 500, colorMap = cm.viridis,
                 colorScale = 'Viridis', reverse = False,
                 title = '
Stream network graph 2')

hydro1.viewNetwork(markerPlot = True, linePlot = True, lineWidth = 3, markerSize = 3,
                 val = 'FA', width = 300, height = 500, colorMap = cm.Blues,
                 colorScale = 'Blues', reverse = True,
                 title = '
Stream network graph 1')

hydro2.viewNetwork(markerPlot = True, linePlot = True, lineWidth = 3, markerSize = 3,
                 val = 'FA', width = 300, height = 500, colorMap = cm.Blues,
                 colorScale = 'Blues', reverse = True,
                 title = '
Stream network graph 2')


I am working on the file "Examples/mountain/Morphometrics.ipynb".
The first task is:
1. Define analyse bounding box
We first have to define the path to the Badlands outputs we want to analyse. In addition Badlands is creating several files for each processors that have been used, you need to specify this number in the ncpus variable.
We then need to provide the extent of the area we want to perform morphometrics analysis on using the bbox parameters which is numpy array containing the extent in the following order [xlow,ylow,xup,yup].
Finally you need to specify the resolution you want to work on. Usually Badlands model are ran on resolution of several hundred of metres but you might want to extract the morphemetrics attributes at a much higher resolution. This is done using the dx parameter which is in metres.
For more information regarding the function uncomment the following line.
Can you write Python code for it?

#help(morph.morphoGrid.__init__)

morpho = morph.morphoGrid(folder='output/h5', \
                          ncpus=1, bbox = [20000,0,60000,40000], \
                          dx=50)


I am working on the file "Examples/mountain/Morphometrics.ipynb".
The first task is:
2. Interpolation of TIN data
We now interpolate the data from a particular time step (timestep) from the TIN to the regular grid, which extent and resolution have been specified in previous function.
Note
If you are interested in making some morphometric comparisons between different time steps you could create multiple instances of the morphometrics python class each of them associated to a given time step.
Can you write Python code for it?


I am working on the file "Examples/mountain/Morphometrics.ipynb".
The first task is:
3. Cross-sections analyses
The last function provided here helps you to create a cross-section from 2 points (xo,yo) and (xm,ym). The create section will interpolate the attributes over the desired slice using a bivariate spline method.
The resulting section is then plotted as a 2D scatter and line graph using plotly library.
Can you write Python code for it?

# Number of cross-sections
nbCS = 40
# Number of points per cross-section
nbPts = 401
# Extent of the cross-section along Y-axis
ymin = 0.
ymax = 40000.
# Extent of the cross-section along X-axis
xmin = 24000.
xmax = 57000.
# Define timestep and according time interval based on display time in the XML input file
timeStp = [20,40,60,80,100,120,140,160,180,200]
timeMA = map(lambda x: x * 0.25, timeStp)


I am working on the file "Examples/mountain/Morphometrics.ipynb".
The first task is:
4. Time evolution
We can then visualise the averaged profiles through time on a single graph:
Can you write Python code for it?

#help(morpho.timeProfiles)

morpho.timeProfiles(pData = zmean, pDist = dist, width = 1000, height = 600, linesize = 3,
                    title = 'Profiles evolution with time')


I am working on the file "Examples/mountain/Morphometrics.ipynb".
The first task is:
4.1. Evolution of profile elevation with time
We can create other plots for example the evolution of the maximum value of the min, mean, & max profile through time.
Can you write Python code for it?

zz = np.zeros((3,len(timeStp)))

zz[0,:] = np.amax(zmin, axis=1)
zz[1,:] = np.amax(zmean, axis=1)
zz[2,:] = np.amax(zmax, axis=1)

morpho.timeProfiles(pData = zz, pDist = timeMA, width = 800, height = 500, linesize = 3,
                    title = 'Averaged Evolution through Time')


I am working on the file "Examples/mountain/Morphometrics.ipynb".
The first task is:
4.2. Position of maximum profiles along an axis
Or the position of a given value from the different profiles with time.
Can you write Python code for it?

zpos = np.zeros((3,len(timeStp)))
zpos[0,:] = dist[np.argmax(zmin, axis=1)] / (ymax-ymin)
zpos[1,:] = dist[np.argmax(zmean, axis=1)] / (ymax-ymin)
zpos[2,:] = dist[np.argmax(zmax, axis=1)] / (ymax-ymin)

morpho.timeProfiles(pData = zpos, pDist = timeMA, width = 1000, height = 600, linesize = 3,
                    title = 'Position of min, mean & max profile through Time')


I am working on the file "Examples/regridInput.ipynb".
The first task is:
1. Load python class and set required resolution
Can you write Python code for it?

#help(resize.resizeInput.__init__)

newRes = resize.resizeInput(requestedSpacing = 40)


I am working on the file "Examples/regridInput.ipynb".
The first task is:
2. Regrid DEM file
Can you write Python code for it?


I am working on the file "Examples/regridInput.ipynb".
The first task is:
3. Regrid Rain file
Can you write Python code for it?


I am working on the file "Examples/regridInput.ipynb".
The first task is:
3D displacements file
Can you write Python code for it?


I am working on the file "Exams/Exam3-Sp20-soln.ipynb".
The first task is:
1.4 (3 pts) All the halogens exist as dimers in their elemental state (F$_2$, Cl$_2$, ...). Rank the dimeric elements according to increasing boiling point.
Can you write Python code for it?


I am working on the file "Exams/Exam3-Sp20-soln.ipynb".
The first task is:
1.5 (3 pts) The halogen dimers all have a bond order of 1.  Do they all have the same bond energy?  If not, which do you think will have the strongest bond?
Can you write Python code for it?

print('No. They have different bond energies. I (WFS) would have guessed F-F would have strongest bond. In fact, it is the weakest. The other three have similar energies.')


I am working on the file "Exams/Exam3-Sp20-soln.ipynb".
The first task is:
2.3.4 (3 pts) $$\hat{v}_\text{exchange}$$
Can you write Python code for it?

print('Accounts for electron indistinguishability (Pauli principle for fermions).')
print('Decreases Coulomb repulsion because electrons of like spin intrinsically avoid one another. Negative')


I am working on the file "Exams/Exam3-Sp20-soln.ipynb".
The first task is:
| Dimer| Bond energy|
|----|------------|
| F2 | 158 kJ/mol |
| Cl2| 242 |
| Br2 | 224 |
| I2 | 214 |
2.Tunneling will bring us together (53 pts)
Applications of the Schrödinger equation to molecules is complicated by the many interactions between electrons and nuclei.  Here we'll look at the simplest possible case, H$_2$.
2.1 (2 pts) How many of what types of particles make up an H$_2$ molecule?
Can you write Python code for it?

print('Two nuclei and two electrons make up an H2 molecule')


I am working on the file "Excel Data.ipynb".
The first task is:
not tested...
writer = pd.ExcelWriter('nd_out.xlsx')
nd.to_excel(writer,'Sheet1')
writer.save()
Can you write Python code for it?