I am working on the file "Example2.ipynb".
The first task is:
Now we will create our model. We will use a similar architecture to Example 1: a shallow fully-connected network with 500 hidden layer neurons, ReLU activations, and a Softmax classifier.
Since this network will be taking 28x28 images, its input dimension will be 28*28. We will use the Xavier scheme to initialize our parameters.
Can you write Python code for it?

opts = {
    'input_dim' : 28*28,
    'init_scheme' : 'xavier'
}


I am working on the file "Example2.ipynb".
The first task is:
Now, we train the model.
Can you write Python code for it?


I am working on the file "Example2.ipynb".
The first task is:
Now, we will set up the MNIST dataset.  This dataset consists of a training set of 60,000 28x28 images of handwritten digits, along with a test set of 10,000 different images of the same size.  We will use a built-in utility to import the data.
Since these images are 28x28 grayscale pixels, they will be stretched into single dimensional vectors of length 784.
Then, the training and test image sets are combined into one large matrix each, where each row is a single 784 image.
There are also two vectors of image classifications (lengths 60,000 and 10,000) which correspond to these two matrices.
Can you write Python code for it?

training_images, training_labels, test_images, test_labels = lml.utils.get_mnist()


I am working on the file "Example2.ipynb".
The first task is:
Now, we wrap our training and validation sets in a dictionary as usual, so that we may feed it to Learny McLearnface.
Can you write Python code for it?

data = {
    'X_train' : X_train,
    'y_train' : y_train,
    'X_val' : X_val,
    'y_val' : y_val
}


I am working on the file "Example3DvisualizationPyNoddyAndCSV2History.ipynb".
The first task is:
Create a history file from fault traces
Can you write Python code for it?

import pandas as pd
import pynoddy.history
#Read a csv file with the vertices of the faults
#see notes in the bottom of the notebook for instructions on how to generate such vertices files
csvfile = 'examples/FaultDataCSV/Scenario1_Vertices.csv'
CsvFaultData = pd.read_csv(csvfile).sort_values(['id'])

#how much does the fault slip relative to the fault length
SlipParam = 0.04

#the xyz origin of the model you will be generating
xy_origin=[317883,4379646, 1200-4000]

#Get information about each parameter in Noddy format
#The output from the function is a dictionary with lists of the fault parameters
noddyFormattedFaultData =  pynoddy.history.setUpFaultRepresentation(CsvFaultData,
                                                    xy_origin=xy_origin,
                                                    SlipParam=SlipParam)

#Create a dictionary with the stratigraphy information
StratDict = {}
StratDict['Heights'] = [2000, 2500, 3000, 3700]
StratDict['Names'] = ['Intrusive', 'Felsic', 'Mafic','Sed']
StratDict['Density'] =  [2.65, 2.5, 2.4, 2.3]
StratDict['MagSus'] = [0.0015, 0.0012, 0.0018, 0.001]

#Now make the history file
filename = 'sandbox/faultmodel.his'
noddyFormattedFaultData =  pynoddy.history.createPyNoddyHistoryFile(noddyFormattedFaultData, StratDict, filename=filename)


I am working on the file "Example3DvisualizationPyNoddyAndCSV2History.ipynb".
The first task is:
Plot a history file in 3D
Can you write Python code for it?

# Determine the path to the noddy file
#(comment the first line and uncomment the second to see the second model -
#which takes around a minute to generate)
modelfile = 'examples/strike_slip.his'
#modelfile = 'examples/Scenario3_MedResolution.his'

# Determine the path to the noddy executable
noddy_path = 'noddy.exe'
folder = os.getcwd()
noddy_path = folder+'/noddy.exe'

# Where you would like to place all your output files
outputfolder = 'sandbox/'

# choose what software to use for visualizing the model
#you can also choose to change to itkwidgets, k3d, False (popup), or panel
#you might need to install packages depending on what you choose
vtkP.settings.embedWindow('k3d')

# create a plot in vtkplotter
plot = vtkP.Plotter(axes=1, bg='white', interactive=1)

# call the plotting function
points = pynoddy.output.CalculatePlotStructure(modelfile, plot, noddy_path,
                                       outputfolder=outputfolder,
                                       LithologyOpacity=0.2, outputOption=0)

plot.show(viewup='z')


I am working on the file "ExampleNotebooks/AntidromicStimulationofMNandRC.ipynb".
The first task is:
The force produced.
Can you write Python code for it?


I am working on the file "ExampleNotebooks/AntidromicStimulationofMNandRC.ipynb".
The first task is:
The membrande potential at the soma of the first motorneuron.
Can you write Python code for it?

plt.figure()
plt.plot(t, RC_mV, '-')
plt.xlim((90,145))


I am working on the file "ExampleNotebooks/ImpedanceAnkle.ipynb".
The first task is:
The ankle joint angle is shown in Fig. \ref{fig:ankleAngleHill}.
Can you write Python code for it?

plt.figure()
plt.plot(t, ankle.ankleAngle_rad*180.0/np.pi, '-')
plt.xlabel('t (ms)')
plt.ylabel('Ankle angle (degree)')
plt.show()

%matplotlib notebook
plt.figure()
plt.plot(t, ankle.ankleTorque_Nm, '-')
plt.xlabel('t (ms)')
plt.ylabel('Ankle torque (N.m)')

torque  = (-ankle.ankleTorque_Nm[40000:int(29.5*20000)])
angle = (ankle.ankleAngle_rad[40000:int(29.5*20000)])

window = 160000
f, Sta = sc.signal.csd(np.transpose((angle)),np.transpose((torque)),fs = 20000, nperseg=window)
f, St = sc.signal.welch(np.transpose((torque)),fs = 20000, nperseg=window)
f, Sa = sc.signal.welch(np.transpose((angle)),fs = 20000, nperseg=window)
Z= Sta/Sa

plt.figure()
plt.plot(np.log10(f),20*np.log10(np.transpose(np.abs(Z))))
plt.xlim((-1,1.4))
#plt.ylim((-20,70))
plt.show()

plt.figure()
plt.plot(np.log10(f),(np.transpose(np.angle(Z)))*180/np.pi)
plt.xlim((-1,1.4))
plt.ylim((-0,180))
plt.show()

torquePassive = torque
anglePassive = angle

plt.figure()
plt.plot((f),(np.transpose(np.abs(St))))
plt.xlim((-0.5,21.5))
plt.show()

plt.figure()
plt.plot((f),(np.transpose(np.abs(Sa))))
plt.xlim((-1,20))
plt.show()

10**(27/20.0)/(np.pi)


I am working on the file "ExampleNotebooks/ImpedanceAnkle.ipynb".
The first task is:
The muscle length computed with the Hill-type model is shown in Fig.\ref{fig:lengthHill}.
Can you write Python code for it?

plt.figure()
plt.plot(t, pools[0].Muscle.length_m/pools[0].Muscle.optimalLength_m, '-')
plt.xlabel('t (ms)')
plt.ylabel('Muscle Length (m)')
plt.show()


I am working on the file "ExampleNotebooks/ImpedanceAnkle.ipynb".
The first task is:
The muscle velocity, computed by the Hill-type muscle model, is in Fig.\ref{fig:velocityHill}.
Can you write Python code for it?

plt.figure()
plt.plot(t, pools[0].Muscle.velocity_m_ms/pools[0].Muscle.optimalLength_m, '-')
plt.xlabel('t (ms)')
plt.ylabel('Muscle Velocity (m/ms)')
plt.show()


I am working on the file "ExampleNotebooks/ImpedanceAnkle.ipynb".
The first task is:
The spike times of the MNs along the 5000 ms of simulation are shown in Fig. \ref{fig:spikesMNHill}.
Can you write Python code for it?

plt.figure()
plt.plot(pools[0].poolTerminalSpikes[:, 0],
         pools[0].poolTerminalSpikes[:, 1]+1, '.')
plt.xlabel('t (ms)')
plt.ylabel('Motor Unit index')
plt.show()

plt.figure()
plt.plot(pools[2].poolTerminalSpikes[:, 0],
         pools[2].poolTerminalSpikes[:, 1]+1, '.')
plt.xlabel('t (ms)')
plt.ylabel('Afferent index')


I am working on the file "ExampleNotebooks/IsometricClosedLoop.ipynb".
The first task is:
The ankle joint angle is shown in Fig. \ref{fig:ankleAngleHill}.
Can you write Python code for it?

plt.figure()
plt.plot(t, ankle.ankleAngle_rad*180.0/np.pi, '-')
plt.xlabel('t (ms)')
plt.ylabel('Ankle angle (degree)')

plt.figure()
plt.plot(t, IaFR, '-')
plt.xlabel('t (ms)')
plt.ylabel('Ankle angle (degree)')

plt.figure()
plt.plot(t, ankle.ankleTorque_Nm, '-')
plt.xlabel('t (ms)')
plt.ylabel('Ankle angle (degree)')


I am working on the file "ExampleNotebooks/IsometricClosedLoop.ipynb".
The first task is:
The muscle force produced by the Hill-type model is shown in Fig.\ref{fig:forceHill}.
Can you write Python code for it?

plt.figure()
plt.plot(t, pools[0].Muscle.force, '-')
plt.xlabel('t (ms)')
plt.ylabel('Muscle Force (N)')


I am working on the file "ExampleNotebooks/IsometricClosedLoop.ipynb".
The first task is:
The muscle length computed with the Hill-type model is shown in Fig.\ref{fig:lengthHill}.
Can you write Python code for it?

plt.figure()
plt.plot(t, pools[0].Muscle.length_m/pools[0].Muscle.optimalLength_m, '-')
plt.xlabel('t (ms)')
plt.ylabel('Muscle Length (m)')


I am working on the file "ExampleNotebooks/MNPoolWithDescendingCommand.ipynb".
The first task is:
The membrane potential of the soma compartment in the last 300 ms is shown in Fig.\ref{fig:somaVLast}.
Can you write Python code for it?

plt.figure()
plt.plot(t[t>4700], somaV[t>4700], '-')
plt.xlabel('t (ms)')
plt.ylabel('Soma membrane potential (mV)')


I am working on the file "ExampleNotebooks/MNPoolWithDescendingCommand.ipynb".
The first task is:
The spike times of all descending commands along the 5000 ms of simulation is shown in Fig. \ref{fig:spikesDescMN}.
Can you write Python code for it?

pools[0].listSpikes()
pools[1].listSpikes()

plt.figure()
plt.plot(pools[1].poolTerminalSpikes[:, 0],
         pools[1].poolTerminalSpikes[:, 1]+1, '.')

plt.xlabel('t (ms)')
plt.ylabel('Descending Command index')


I am working on the file "ExampleNotebooks/MNPoolWithDescendingCommand.ipynb".
The first task is:
The spike times of all descending commands along the last 500 ms of simulation is shown in Fig. \ref{fig:spikesDescMNLast}.
Can you write Python code for it?

plt.figure()
plt.plot(pools[1].poolTerminalSpikes[pools[1].poolTerminalSpikes[:, 0]>4500, 0],
         pools[1].poolTerminalSpikes[pools[1].poolTerminalSpikes[:, 0]>4500, 1]+1, '.')
plt.xlabel('t (ms)')
plt.ylabel('Descending Command index')


I am working on the file "ExampleNotebooks/MNPoolWithRenshawCells-Copy1.ipynb".
The first task is:
The spike times of all descending commands along the 5000 ms of simulation is shown in Fig. \ref{fig:spikesDescRenshaw}.
Can you write Python code for it?

plt.figure()
plt.plot(pools[1].poolTerminalSpikes[:, 0],
         pools[1].poolTerminalSpikes[:, 1]+1, '.')
plt.xlabel('t (ms)')
plt.ylabel('Descending Command index')


I am working on the file "ExampleNotebooks/MNPoolWithRenshawCells-Copy1.ipynb".
The first task is:
The spike times of the Renshaw cells along the 5000 ms of simulation is shown in Fig. \ref{fig:spikesRenshawRenshaw}.
Can you write Python code for it?

plt.figure()
plt.plot(pools[2].poolSomaSpikes[:, 0],
         pools[2].poolSomaSpikes[:, 1]+1, '.')
plt.xlabel('t (ms)')
plt.ylabel('Renshaw cell index')


I am working on the file "ExampleNotebooks/MNPoolWithRenshawCells.ipynb".
The first task is:
The spike times of all descending commands along the 5000 ms of simulation is shown in Fig. \ref{fig:spikesDescRenshaw}.
Can you write Python code for it?


I am working on the file "ExampleNotebooks/MNPoolWithRenshawCells.ipynb".
The first task is:
The spike times of the MNs along the 5000 ms of simulation is shown in Fig. \ref{fig:spikesMNRenshaw}.
Can you write Python code for it?

plt.figure()
plt.plot(pools[0].poolTerminalSpikes[:, 0],
         pools[0].poolTerminalSpikes[:, 1]+1, '.')
plt.xlabel('t (ms)')
plt.ylabel('Motor Unit index')


I am working on the file "ExampleNotebooks/MuscleHillExample.ipynb".
The first task is:
The muscle force produced by the Hill-type model is shown in Fig.\ref{fig:forceHill}.
Can you write Python code for it?


I am working on the file "ExampleNotebooks/MuscleHillExample.ipynb".
The first task is:
The muscle length computed with the Hill-type model is shown in Fig.\ref{fig:lengthHill}.
Can you write Python code for it?

plt.figure()
plt.plot(t, pools[0].Muscle.length_m, '-')
plt.xlabel('t (ms)')
plt.ylabel('Muscle Length (m)')


I am working on the file "ExampleNotebooks/MuscleHillExample.ipynb".
The first task is:
The spike times of the MNs along the 5000 ms of simulation are shown in Fig. \ref{fig:spikesMNHill}.
Can you write Python code for it?

plt.figure()
plt.plot(pools[0].poolTerminalSpikes[:, 0],
    pools[0].poolTerminalSpikes[:, 1]+1, '.')
plt.xlabel('t (ms)')
plt.ylabel('Motor Unit index')


I am working on the file "ExampleNotebooks/NeuralTractSpikes.ipynb".
The first task is:
Below different statistics of the interspike intervals and firing rate are obtained.
Can you write Python code for it?

SD = np.std(ISI)
M = np.mean(ISI)
SK = scipy.stats.skew(ISI)
CV = SD / M

print 'ISI Mean = ' + str(M) + ' ms'
print 'ISI Standard deviation = ' + str(SD) + ' ms'
print 'ISI CV = ' + str(CV)

M_FR = 1000.0 / M
SD_FR = np.sqrt((SD**2) * 1000 / (M**3) + 1/6.0 + (SD**4) / (2*M**4) - SK/(3*M**3))

print 'Firing rate mean = ' + str(M_FR) + ' Hz'
print 'Firing rate standard deviation = ' + str(SD_FR) + ' Hz'

CV_FR = SD_FR / M_FR
print 'CV of Firing rate = ' + str(CV_FR)


I am working on the file "ExampleNotebooks/NeuralTractSpikes.ipynb".
The first task is:
The histogram of the interspike intevals of all the descending commands is shown in Fig. \ref{fig:hist}. Note that the peak is in the specified ISI at the beginning of the simulation.
Can you write Python code for it?

ISI = np.array([])
for i in xrange(0,len(pools[0].unit)):
    ISI = np.append(ISI, np.diff(np.reshape(np.array(pools[0].unit[i].terminalSpikeTrain), (-1,2))[:,0]))

plt.figure()
plt.hist(ISI)
plt.xlabel('ISI (ms)')
plt.ylabel('Counts')


I am working on the file "ExampleNotebooks/NeuralTractSpikes.ipynb".
The first task is:
The spike times of all descending commands along the 10000 ms of simulation is shown in Fig. \ref{fig:spikesDesc}.
Can you write Python code for it?

plt.figure()
plt.plot(pools[0].poolTerminalSpikes[:, 0],
         pools[0].poolTerminalSpikes[:, 1]+1, '.')
plt.xlabel('t (ms)')
plt.ylabel('Descending Command index')


I am working on the file "ExampleNotebooks/NeuralTractSpikes.ipynb".
The first task is:
The spike times of all descending commands during the last 1000 ms of the simulation is shown in Fig. \ref{fig:spikesDescLast}.
Can you write Python code for it?

plt.figure()
plt.plot(pools[0].poolTerminalSpikes[pools[0].poolTerminalSpikes[:, 0]>9000, 0],
         pools[0].poolTerminalSpikes[pools[0].poolTerminalSpikes[:, 0]>9000, 1]+1, '.')
plt.xlabel('t (ms)')
plt.ylabel('Descending Command index')


I am working on the file "ExampleNotebooks/Pulsatingaurora.ipynb".
The first task is:
Input Parameter Set Up
The following cell will set up the pulsating aurora input plasma parameters. The model of the parameters will be Ne(1+ehn_levsin(2pi*t/PT))
Can you write Python code for it?

# Pulsating aurora parameters
PT=30.# the period of pulsation in seconds.
ehn_lev=2. # level of enhancement.
pa_range=[250.,300.]# range of pulsation along altitude in km

# set up the time and space vectors
dt=1.
timevec=sp.arange(120.)*dt
timemat=sp.column_stack((timevec,(timevec/dt+1)*dt))
z = (50.+sp.arange(120)*5.)
nz = len(z)
coords = sp.column_stack((sp.zeros((nz,2)),z))
# Create the weighting for the pulsation
logar=sp.logical_and((z>=pa_range[0]),(z<pa_range[1]))
PA_weight=1+.5*(ehn_lev-1)*(1-sp.cos(2.*sp.pi*timevec/PT))
PA_weight_rep = sp.tile(PA_weight[sp.newaxis,:],[logar.sum(),1])

# Make a set of input parameters with a electron density modeled by a Chapman function and an electron and ion temperature
# modeled as shifted and scalled atan functions.
Icont1=MakeTestIonoclass(testv=False,testtemp=True,N_0=1e11,z_0=250.0,H_0=50.0,coords=coords,times=timemat)
# Apply windowing to the electron density
Icont1.Param_List[logar,:,-1,0]=PA_weight_rep*Icont1.Param_List[logar,:,-1,0]

# Create the starting point data for the fitter.
Icontstart = MakeTestIonoclass(testv=False,testtemp=False,N_0=1e11,z_0=250.0,H_0=50.0,
                               coords=coords,times =sp.array([[0,1e6]]))


I am working on the file "ExampleNotebooks/Pulsatingaurora.ipynb".
The first task is:
Set up for Simulation
Set up parameters for simulation like pulse length, pulse type, beam positions, etc. Also create a file structure to save the data at the different levels.
Can you write Python code for it?

# Make file tree if not already inplace.
curloc = Path.cwd()
testpath = curloc.parent.joinpath('Testdata','PulsatingNotebook')
testpath.mkdir(exist_ok=True,parents=True)
# Read in default config file.
defaultpath = curloc.parent.joinpath('Test')
defcon = defaultpath.joinpath('statsbase.yml')
(sensdict,simparams) = readconfigfile(str(defcon))

# Adjust config file for specific case.
simparams['Beamlist']=[64016.0]
tint = 10.
ratio1 = tint/simparams['Tint']
simparams['Tint']=ratio1 * simparams['Tint']
simparams['Fitinter'] = ratio1 * simparams['Fitinter']
simparams['TimeLim'] = tint+timevec[-1]
# Save configuration file.
simparams['startfile']='startfile.h5'
makeconfigfile(str(testpath.joinpath('stats.yml')),simparams['Beamlist'],sensdict['Name'],simparams)
# Save out input plasma parameters
finalpath = testpath.joinpath('Origparams')
finalpath.mkdir(exist_ok=True,parents=True)
finalfile = finalpath.joinpath('0 stats.h5')
Icont1.saveh5(str(finalfile))
Icontstart.saveh5(str(testpath.joinpath('startfile.h5')))


I am working on the file "ExampleNotebooks/SingleBeamExample.ipynb".
The first task is:
Make Input Data
This section will create a set of input parmeters that can be used to create ISR Data. It uses a function MakeTestIonoclass which will create a set of plasma parameters that varies with altitude depending on the the function inputs. This data is put into an ionocontainer class, which is used as a container class to move data between the radarData class, fitter class and plotting modules. It has a standard format so any radar data or plasma parameters for the simulator can be saved in this.
A start file is also made which will be used as the starting parameter values used in the fitter. The starting points for the fitter use a nearest neighbor in space to what is found in the start file.
Can you write Python code for it?

finalpath = os.path.join(testpath,'Origparams')
if not os.path.isdir(finalpath):
    os.mkdir(finalpath)
z = (50.+sp.arange(120)*5.)
nz = len(z)
coords = sp.column_stack((sp.zeros((nz,2)),z))
Icont1=MakeTestIonoclass(testv=False,testtemp=True,N_0=1e11,z_0=250.0,H_0=50.0,coords=coords,times =sp.array([[0,1e6]]))

Icontstart = MakeTestIonoclass(testv=False,testtemp=False,N_0=1e11,z_0=250.0,H_0=50.0,coords=coords,times =sp.array([[0,1e6]]))

finalfile = os.path.join(finalpath,'0 stats.h5')
Icont1.saveh5(finalfile)
Icontstart.saveh5(os.path.join(testpath,'startfile.h5'))


I am working on the file "ExampleNotebooks/SingleBeamExample.ipynb".
The first task is:
Run Simulation
The simulation is run through the submodule runsim and its main function, renamed in this as runsim. This function will call all of the neccesary classes and functions to run the simulator. It will save out the data based off of an internal set of file names.
This function must get a configuration file and a list of functionalities it is to perform. Below the runsim function will create spectra form the plasma parameters, create radar data and then fit it.
Can you write Python code for it?

functlist = ['spectrums','radardata','fitting']

config = os.path.join(testpath,'stats.ini')

runsim(functlist,testpath,config,True)


I am working on the file "ExampleNotebooks/SingleBeamExample.ipynb".
The first task is:
Set up Config Files
Setting up a configuration files and the directory needed to run the simulation. The simualtor assumes that for each simulation there is a dedicated directory to save out data along the different processing stages. The simulator also assumes that there is a configuration file which is created in the following cell using a default one that comes with the code base. The only parameter the user should have to set is the number of pulses.
Can you write Python code for it?

# set the number of pulses
npulses = 2000
curloc = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
testpath = os.path.join(os.path.split(curloc)[0],'Testdata','Notebookexample1')
if not os.path.isdir(testpath):
    os.mkdir(testpath)

defaultpath = os.path.join(os.path.split(curloc)[0],'Test')
defcon = os.path.join(defaultpath,'statsbase.ini')
(sensdict,simparams) = readconfigfile(defcon)

tint = simparams['IPP']*npulses
ratio1 = tint/simparams['Tint']
simparams['Tint']=ratio1 * simparams['Tint']
simparams['Fitinter'] = ratio1 * simparams['Fitinter']
simparams['TimeLim'] = tint

simparams['startfile']='startfile.h5'
makeconfigfile(os.path.join(testpath,'stats.ini'),simparams['Beamlist'],sensdict['Name'],simparams)


I am working on the file "ExampleNotebooks/SpecEstimator.ipynb".
The first task is:
Full ISR Data Creation and Estimator
The basics data creation and processing behind SimISR for this case for only one beam. The data is created along a set of samples by adding together a set of uncorrelated data sets together. These sets of pulses that are added together are uncorrelated because any spatial correlation of the electron density fluctuations are much smaller than a range gate. After that the ACFs are estimated they are plotted with the input ACF and spectra with the window applied.
Can you write Python code for it?

Xdata=sp.zeros((rep1,Nrg),dtype=sp.complex128)
Lint = int(L)
for i in range(int(Nrg-Lint)):
    Xdata[:,i:i+Lint] = MakePulseDataRepLPC(pulse,cur_spec,40,rep1,numtype = sp.complex128)+Xdata[:,i:i+Lint]

lagsData=CenteredLagProduct(Xdata,numtype=sp.complex128,pulse =pulse,lagtype='centered')/rep1
ptype='long'
ts = 1.
sumrule=makesumrule(ptype,L,ts,lagtype='centered')
minrg = -sumrule[0].min()
maxrg = Nrg-sumrule[1].max()
Nrng2 = maxrg-minrg
lagsDatasum = sp.zeros((Nrng2,Lint),dtype=sp.complex128)
for irngnew,irng in enumerate(sp.arange(minrg,maxrg)):
    for ilag in range(Lint):
        lagsDatasum[irngnew,ilag] = lagsData[irng+sumrule[0,ilag]:irng+sumrule[1,ilag]+1,ilag].sum(axis=0)
# divide off the gain from the pulse stacking
lagsDatasum = lagsDatasum/L


I am working on the file "ExampleNotebooks/SpecEstimator.ipynb".
The first task is:
IS Spectra
This will create an example ISR spectra that will be used.
Can you write Python code for it?

# Make spectrum
ISpec_ion = ISRSpectrum(centerFrequency=f_c, nspec=nspec, sampfreq=spfreq, dFlag=False)
f,cur_spec,rcs = ISpec_ion.getspecsep(databloc,species,rcsflag=True)
specsum = sp.absolute(cur_spec).sum()
cur_spec = len(cur_spec)*cur_spec*rcs/specsum
tau,acf=spect2acf(f,cur_spec)

fig,ax = plt.subplots(1,2,sharey=False, figsize=(8,4),facecolor='w')
rp,imp=ax[0].plot(tau*1e3,acf.real,tau*1e3,acf.imag)
ax[0].legend([rp,imp],['Real','Imag'])
ax[0].set_ylabel('Amplitude')
ax[0].set_title('ACF')
ax[0].set_xlabel(r'$\tau$ in ms')

ax[1].plot(f*1e-3,cur_spec.real)
ax[1].set_ylabel('Amplitude')
ax[1].set_title('Spectrum')
ax[1].set_xlabel(r'f in kHz')
fig.tight_layout()


I am working on the file "ExampleNotebooks/SpecEstimator.ipynb".
The first task is:
Plotting and Normalization of Input Spectra
Need to apply window function to spectrum.
Can you write Python code for it?

dt=tau[1]-tau[0]
f1,spec_all=acf2spect(l*dt,lagsDatasum,n_s=nspec)
acf_single = lagsDatasum[50]
spec_single = spec_all[50]

# Apply weighting and integrations from gain from pulse stacking
acf_act=scfft.ifftshift(acf)[:Lint]*W
feh,spec_act=acf2spect(l*dt,acf_act,n_s=nspec)

fig5,ax5 = plt.subplots(1,2,sharey=False, figsize=(8,4),facecolor='w')
rp,imp,act_acf=ax5[0].plot(l*dt*1e6,acf_single.real,l*dt*1e6,acf_single.imag,l*dt*1e6,acf_act.real)
ax5[0].legend([rp,imp,act_acf],['Real','Imag','Actual'])
ax5[0].set_ylabel('Amplitude')
ax5[0].set_title('ACF')
ax5[0].set_xlabel(r'$\tau$ in $\mu$s')

est1,act_spec=ax5[1].plot(f*1e-3,spec_single.real,f*1e-3,spec_act.real)
ax5[1].legend([est1,act_spec],['Estimated','Actual'])
ax5[1].set_ylabel('Amplitude')
ax5[1].set_title('Spectrum')
ax5[1].set_xlabel(r'f in kHz')
fig5.tight_layout()


I am working on the file "ExampleNotebooks/SpecEstimator.ipynb".
The first task is:
White Noise
A periodogram is applied to complex white Gaussian Noise. This is here in order to show that the output of the scipy random number generator outputs uncorrelated random variables.
Can you write Python code for it?

xin =sp.power(2,-.5)*(sp.random.randn(rep1,nspec)+1j*sp.random.randn(rep1,nspec))

Xfft=sp.power(nspec,-.5)*scfft.fftshift(scfft.fft(xin,axis=-1),axes=-1)
Xperiod=sp.power(Xfft.real,2).mean(0) +sp.power(Xfft.imag,2).mean(0)
tau2,acfperiod=spect2acf(f,Xperiod*nspec)

fig2,ax2 = plt.subplots(1,2,sharey=False, figsize=(8,4),facecolor='w')
rp,imp=ax2[0].plot(tau2*1e6,acfperiod.real,tau2*1e6,acfperiod.imag)
ax2[0].legend([rp,imp],['Real','Imag'])
ax2[0].set_ylabel('Amplitude')
ax2[0].set_title('ACF')
ax2[0].set_xlabel(r'$\tau$ in $\mu$s')

ax2[1].plot(f*1e-3,Xperiod.real)
ax2[1].set_ylabel('Amplitude')
ax2[1].set_title('Spectrum')
ax2[1].set_xlabel(r'f in kHz')
ax2[1].set_ylim([0.,1.5])
fig2.tight_layout()


I am working on the file "Example_01.ipynb".
The first task is:
Enters the PyTreeReader
This is how we use for the first time the PyTreeReader and how we benchmark it. The only difference within the loop body consists in invoking functions called as the branches rather than data members called as the branches themselves. Even for this trivial tree, the difference is impressive.
Actually, having little read, decompression and deserialisation is better: the difference in time is really due to the superior performance of the PyTreeReader.
Can you write Python code for it?

%%timeit -n 1 -r 1
for event in PyTreeReader(tree):
    fill(event.px()*event.py()*event.pz()*event.random())


I am working on the file "Example_01.ipynb".
The first task is:
Loop on the cached values
Can you write Python code for it?

%%timeit -n 1 -r 1
for event in ptr:
    fill(event.px()*event.py()*event.pz()*event.random())


I am working on the file "Example_01.ipynb".
The first task is:
Pattern is indeed the pattern to match the desired branches by name (fnmatch is used). Its default value is simple, "*";
Accessing a vector of cached values
Caching values in memory has a price but once this step has been accomplished, more flexibility is available. For example, all the values of a particular branch can be retrieved in bulk:
Can you write Python code for it?

for py in ptr.py_array()[:10]: print py # Better stopping after a few of them :)


I am working on the file "Example_01.ipynb".
The first task is:
Selecting only some branches
It can be inconvenient to construct methods to access all the branches, even more to cache all of their contents by default. This is the reason why PyTreeReader provides the pattern constructor argument. For example, in order to consider only branches whose names start with "p", one can do:
Can you write Python code for it?

%%timeit -n 1 -r 1
ptr = PyTreeReader(tree, cache=True, pattern="p[*]")


I am working on the file "Example_01.ipynb".
The first task is:
This is to create an histogram and read a tree.
Can you write Python code for it?

h = ROOT.TH1F("h","h",1024,-256,256)
fill = h.Fill

f = ROOT.TFile(ROOT.gROOT.GetTutorialsDir()+"/hsimple.root")
tree = f.ntuple


I am working on the file "Example_01.ipynb".
The first task is:
Traditional looping
Now we establish the baseline: banchmark of the old way for looping.
Can you write Python code for it?

%%timeit -n 1 -r 1
for event in tree:
    fill(event.px*event.py*event.pz*event.random)


I am working on the file "Example_Assessment.ipynb".
The first task is:
Data Comparison
Can you write Python code for it?

fig, caption = analysis.plot_mol_graphs(gtype='dos', max_cols=3,
                                        lbound=-20, ubound=10, legend_size=0,
                                        band_gap_value=False,
                                   info_columns=['Cation', 'Anion', 'Initial'])
print caption


I am working on the file "Example_Assessment.ipynb".
The first task is:
Documentation (MS Word)
After analysing the computations, it would be reasonable to want to document some of our findings. This can be achieved by outputting individual figure or table images via the folder object.
Can you write Python code for it?

file_path = folder.save_ipyimg(vdw, 'image_of_molecule')
Image(file_path)


I am working on the file "Example_Assessment.ipynb".
The first task is:
Energetics and Frequency Analysis
Can you write Python code for it?

print('Optimised? {0}, Conformer? {1}, Energy = {2} a.u.'.format(
    mol.is_optimised(), mol.is_conformer(),
    round(mol.get_opt_energy(units='hartree'),3)))
ax = mol.plot_opt_energy(units='hartree')
ax.get_figure().set_size_inches(3, 2)
ax = mol.plot_freq_analysis()
ax.get_figure().set_size_inches(4, 2)


I am working on the file "Example_Assessment.ipynb".
The first task is:
Molecular Comparison
Can you write Python code for it?

fig, caption = analysis.plot_mol_images(mtype='optimised', max_cols=3,
                        info_columns=['Cation', 'Anion', 'Initial'],
                        rotations=[[0,0,90]])
print caption


I am working on the file "Example_Assessment.ipynb".
The first task is:
Multi-Variate Analysis
RadViz is a way of visualizing multi-variate data.
Can you write Python code for it?

ax = analysis.plot_radviz_comparison('Anion', columns=range(4, 10))


I am working on the file "Example_Assessment.ipynb".
The first task is:
Multiple Computations Analysis
Multiple computations, for instance of different starting conformations, can be grouped into an Analysis class and anlaysed collectively.
Can you write Python code for it?

analysis = pg.Analysis(folder_obj=folder)
errors = analysis.add_runs(headers=['Cation', 'Anion', 'Initial'],
                               values=[['emim'], ['cl'],
                                       ['B', 'BE', 'BM', 'F', 'FE']],
            init_pattern='*{0}-{1}_{2}_init.com',
            opt_pattern='*{0}-{1}_{2}_6-311+g-d-p-_gd3bj_opt*unfrz.log',
            freq_pattern='*{0}-{1}_{2}_6-311+g-d-p-_gd3bj_freq*.log',
            nbo_pattern='*{0}-{1}_{2}_6-311+g-d-p-_gd3bj_pop-nbo-full-*.log',
            alignto=[3,2,1], atom_groups={'emim':range(1,20), 'cl':[20]},
            ipython_print=True)


I am working on the file "Example_Assessment.ipynb".
The first task is:
Partial Charge Analysis
using Natural Bond Orbital (NBO) analysis
Can you write Python code for it?

print '+ve charge centre polar coords from aromatic ring: ({0} {1},{2})'.format(
    *[round(i, 2) for i in mol.calc_nbo_charge_center(3, 2, 1)])
display(mol.show_nbo_charges(represent='ball_stick', axis_length=0.4,
                              rotations=[[0,0,90], [-90, 90, 0]]))


I am working on the file "Example_Assessment.ipynb".
The first task is:
Potential Energy Scan analysis of geometric conformers...
Can you write Python code for it?

mol2 = pg.molecule.Molecule(folder_obj=folder, alignto=[3,2,1],
            pes_fname=['CJS_emim_6311_plus_d3_scan.log',
                       'CJS_emim_6311_plus_d3_scan_bck.log'])
ax, data = mol2.plot_pes_scans([1,4,9,10], rotation=[0,0,90], img_pos='local_maxs', zoom=0.5)
ax.set_title('Ethyl chain rotational conformer analysis')
ax.get_figure().set_size_inches(7, 3)


I am working on the file "Example_Assessment.ipynb".
The first task is:
The methods mentioned for indivdiual molecules can be applied to all or a subset of these computations.
Can you write Python code for it?

analysis.add_mol_property_subset('Opt', 'is_optimised', rows=[2,3])
analysis.add_mol_property('Energy (au)', 'get_opt_energy', units='hartree')
analysis.add_mol_property('Cation chain, $\\psi$', 'calc_dihedral_angle', [1, 4, 9, 10])
analysis.add_mol_property('Cation Charge', 'calc_nbo_charge', 'emim')
analysis.add_mol_property('Anion Charge', 'calc_nbo_charge', 'cl')
analysis.add_mol_property(['Anion-Cation, $r$', 'Anion-Cation, $\\theta$', 'Anion-Cation, $\\phi$'],
                               'calc_polar_coords_from_plane', 3, 2, 1, 20)
analysis.add_mol_property('Anion-Cation h-bond', 'calc_hbond_energy',
                          eunits='kJmol-1', atom_groups=['emim', 'cl'])
analysis.get_table(row_index=['Anion', 'Cation', 'Initial'],
                   column_index=['Cation', 'Anion', 'Anion-Cation'])


I am working on the file "Example_Assessment.ipynb".
The first task is:
The test folder has a number of example Gaussian outputs to play around with.
Can you write Python code for it?

folder = pg.get_test_folder()
len(folder.list_files())


I am working on the file "Example_Assessment.ipynb".
The first task is:
There is also an option (requiring pdflatex and ghostscript+imagemagik) to output the tables as a latex formatted image.
Can you write Python code for it?

analysis.get_table(row_index=['Anion', 'Cation', 'Initial'],
                   column_index=['Cation', 'Anion', 'Anion-Cation'],
                   as_image=True, font_size=12)


I am working on the file "Example_Code.ipynb".
The first task is:
Let's have a look, how they look like:
Can you write Python code for it?

fig, ax = plt.subplots(figsize=[16, 12])
ax.plot(data)


I am working on the file "Example_Code.ipynb".
The first task is:
Offline Changepoint Detection
Lets compute the probability of changepoints at each time step. We need two things for that. First a prior of how probable is it to have two successive changepoints with the distance t. The second thing is a model of the likelihood of data in a sequence [s, t] of the data, given that in this sequence there is no changepoint.
For this example we assume a uniform prior over the length of sequences (const_prior) and a piecewise gaussian model (gaussian_obs_log_likelihood).
Can you write Python code for it?

from bayesian_changepoint_detection.priors import const_prior
from functools import partial

prior_function = partial(const_prior, p=1/(len(data) + 1))

from bayesian_changepoint_detection.bayesian_models import offline_changepoint_detection
import bayesian_changepoint_detection.offline_likelihoods as offline_ll

Q, P, Pcp = offline_changepoint_detection(data, prior_function ,offline_ll.StudentT(),truncate=-40)


I am working on the file "Example_Code.ipynb".
The first task is:
That works pretty well, but is somewhat slow. It's possible to speed that up by truncating a sum in the algorithm. However that sometimes leeds to $\infty$ values. Set the truncate parameter to e.g. -10 to test that out.
To understand, what is happening have a look at the following papers:
[1] Paul Fearnhead, Exact and Efficient Bayesian Inference for Multiple
Changepoint problems, Statistics and computing 16.2 (2006), pp. 203--213
[2] Xuan Xiang, Kevin Murphy, Modeling Changing Dependency Structure in
Multivariate Time Series, ICML (2007), pp. 1055--1062
Online Changepoint Detection
Let's assume the data points come in one after another and not as these nice batches. During the process you want to know if the new point has the same hyperparameter or different ones. You need an online changepoint detection.
Happily there is one, although it's interface is kind of suboptimal so far, in that it expects batches of data still and just assumes they drop in over time... I will change that at some point.
Can you write Python code for it?

from bayesian_changepoint_detection.hazard_functions import constant_hazard
hazard_function = partial(constant_hazard, 250)

from bayesian_changepoint_detection.bayesian_models import online_changepoint_detection
import bayesian_changepoint_detection.online_likelihoods as online_ll

R, maxes = online_changepoint_detection(
    data, hazard_function, online_ll.StudentT(alpha=0.1, beta=.01, kappa=1, mu=0)
)


I am working on the file "Example_Code.ipynb".
The first task is:
The offline_changepoint_detection() function returns three things: Q[t], the log-likelihood of data [t, n], P[t, s], the log-likelihood of a datasequence [t, s], given there is no changepoint between t and s and Pcp[i, t], the log-likelihood that the i-th changepoint is at time step t. To actually get the probility of a changepoint at time step t sum the probabilities.
How does that look like for our toy-data?
Can you write Python code for it?

fig, ax = plt.subplots(2, figsize=[18, 16], sharex=True)
ax[0].plot(data[:])
ax[1].plot(np.exp(Pcp).sum(0))


I am working on the file "Example_Code.ipynb".
The first task is:
Well, not bad, considering how much faster it is (if you can afford waiting for that extra Nw samples). To understand the whole algorithm look at
[1] Ryan P. Adams, David J.C. MacKay, Bayesian Online Changepoint Detection,
arXiv 0710.3742 (2007)
There you also find a Matlab version, which this code is based on.
Can you write Python code for it?

partition, data = generate_normal_time_series(7, 50, 200)

%timeit Q, P, Pcp = offline_changepoint_detection(data, prior_function, offline_ll.StudentT(), truncate=-40)

%timeit R, maxes = online_changepoint_detection(data, hazard_function, online_ll.StudentT(10, .03, 1, 0))


I am working on the file "Example_EN.ipynb".
The first task is:
And this is the data:
Can you write Python code for it?


I am working on the file "Example_EN.ipynb".
The first task is:
At last a correlation is easily calculated because of pandas:
Can you write Python code for it?


I am working on the file "Example_EN.ipynb".
The first task is:
Download of timeseries with uuid 867b166a-fa39-457d-a9e9-4bcb2ff04f61 From December 31st 1999 untill Februari 14th 2018.
This is the metadata:
Can you write Python code for it?

queryparams = {
    "end":1518631200000,
    "start":946681200000,
    "window":"month"
}
result = cli.timeseries.get(uuid="867b166a-fa39-457d-a9e9-4bcb2ff04f61", **queryparams)
result.metadata


I am working on the file "Example_EN.ipynb".
The first task is:
Now we can search for other timeseries based on the metadata. We are going to look at the correlation between precipitation, evaporation and windspeed. First the observation type metadata:
Can you write Python code for it?

location__uuid = result.metadata['location__uuid'][0]
metadata_multiple, events_multiple = cli.timeseries.get(location__uuid=location__uuid, **queryparams)
columns = [x for x in metadata_multiple.columns if "observation_type" in x or  "uuid" in x]
metadata_multiple[columns]


I am working on the file "Example_EN.ipynb".
The first task is:
The connection with Lizard is made. Above all endpoints are shown
Now we collect the metadata for a first timeseries with uuid 867b166a-fa39-457d-a9e9-4bcb2ff04f61:
Can you write Python code for it?

result = cli.timeseries.get(uuid="867b166a-fa39-457d-a9e9-4bcb2ff04f61")
result.metadata


I am working on the file "Example_EN.ipynb".
The first task is:
The data has different lengths. We cannot correlate the data unless we slice the data. Here we make sure the data is of the same length. Because one of our queryparameters was {"window":"month"} we already resampled the data.
Can you write Python code for it?

indexed_events = [e.set_index('timestamp') for e in events_multiple if 'timestamp' in e.columns]
first = max([indexed.index[0] for indexed in indexed_events])
last = min([indexed.index[-1] for indexed in indexed_events])
print(first, last)
indexed_events_ranged = [e[first:last] for e in indexed_events]
[e.shape for e in indexed_events_ranged]


I am working on the file "Example_EN.ipynb".
The first task is:
We can see the data has the same length. Now we select the max for the different timeseries:
Can you write Python code for it?

observation_types = metadata_multiple['observation_type__parameter'].tolist()
max_weerdata = pd.DataFrame({observation_type: events['max'] for observation_type, events in zip(observation_types, indexed_events_ranged)})
max_weerdata


I am working on the file "Example_Faces.ipynb".
The first task is:
Custering
Can you write Python code for it?

import time
from sklearn.cluster import AgglomerativeClustering
from rena import recursive_nearest_agglomeration

n_clusters = 150

ward = AgglomerativeClustering(n_clusters=n_clusters,
                               connectivity=connectivity_ward,
                               linkage='ward')
ti_ward = time.clock()
ward.fit(X.T)
to_ward = time.clock() - ti_ward

labels_ward = ward.labels_

ti_rena = time.clock()
labels_rena = recursive_nearest_agglomeration(X, connectivity_rena,
                                              n_clusters=n_clusters)
to_rena = time.clock() - ti_rena

print('Time Ward: %0.3f, Time ReNA: %0.3f' % (to_ward, to_rena))

from rena import reduce_data, approximate_data

X_red_rena = reduce_data(X, labels_rena)
X_red_ward = reduce_data(X, labels_ward)

X_approx_rena = approximate_data(X_red_rena, labels_rena)
X_approx_ward = approximate_data(X_red_ward, labels_ward)


I am working on the file "Example_Faces.ipynb".
The first task is:
Results visualization
Can you write Python code for it?

%matplotlib inline
import matplotlib.pyplot as plt

fig, axx = plt.subplots(3, 4, **{'figsize': (10, 5)})
plt.gray()

for i in range(4):
    axx[0, i].imshow(X[i + 30].reshape(n_x, n_y))
    axx[0, i].set_axis_off()
    axx[0, 0].set_title('Original')
    axx[1, i].imshow(X_approx_ward[i + 30].reshape(n_x, n_y))
    axx[1, i].set_axis_off()
    axx[1, 0].set_title('Ward: approximated')
    axx[2, i].imshow(X_approx_rena[i + 30].reshape(n_x, n_y))
    axx[2, i].set_axis_off()
    axx[2, 0].set_title('ReNA: approximated')

# saving results
fig.savefig('figures/faces.png', bbox_to_inches='tight')


I am working on the file "Example_Neuroimaging.ipynb".
The first task is:
Custering
Can you write Python code for it?

from rena import reduce_data, approximate_data

X_red_rena = reduce_data(X_masked, labels_rena)
X_red_ward = reduce_data(X_masked, labels_ward)

X_approx_rena = approximate_data(X_red_rena, labels_rena)
X_approx_ward = approximate_data(X_red_ward, labels_ward)


I am working on the file "Example_Neuroimaging.ipynb".
The first task is:
Get the connectivity (spatial structure)
Can you write Python code for it?

from sklearn.feature_extraction.image import grid_to_graph
from rena import weighted_connectivity_graph

connectivity_ward = grid_to_graph(n_x=n_x, n_y=n_y, n_z=n_z, mask=mask)

connectivity_rena = weighted_connectivity_graph(X_data,
                                                n_features=X_masked.shape[1],
                                                mask=mask)

import time
from sklearn.cluster import AgglomerativeClustering
from rena import recursive_nearest_agglomeration

n_clusters = 2000

ward = AgglomerativeClustering(n_clusters=n_clusters,
                               connectivity=connectivity_ward,
                               linkage='ward')

ti_ward = time.clock()
ward.fit(X_masked.T)
to_ward = time.clock() - ti_ward
labels_ward = ward.labels_

ti_rena = time.clock()
labels_rena = recursive_nearest_agglomeration(X_masked, connectivity_rena,
                                              n_clusters=n_clusters)
to_rena = time.clock() - ti_rena

print('Time Ward: %0.3f, Time ReNA: %0.3f' % (to_ward, to_rena))


I am working on the file "Example_PmagPy_Notebook.ipynb".
The first task is:
A similar plot showing the Fisher means of the site means calculated above and their associated $\alpha_{95}$ confidence ellipses can be generated using the ipmag.plot_di_mean function.
Can you write Python code for it?

plt.figure(num=1,figsize=(4,4))
ipmag.plot_net(fignum=1)
ipmag.plot_di_mean(Halls1974_r_tc_mean['dec'],
                   Halls1974_r_tc_mean['inc'],
                   Halls1974_r_tc_mean['alpha95'],'b',
                   label='Halls (1974) tilt-corrected mean')
ipmag.plot_di_mean(Halls1974_r_is_mean['dec'],
                   Halls1974_r_is_mean['inc'],
                   Halls1974_r_is_mean['alpha95'],'r',
                   label='Halls (1974) insitu mean')
plt.legend(loc=9)
plt.show()


I am working on the file "Example_PmagPy_Notebook.ipynb".
The first task is:
And now the same for the Halls1974 data table.
Can you write Python code for it?

Halls1974_upperR_dec_is = Halls1974_sites_r_is['site_dec'].tolist()
Halls1974_upperR_inc_is = Halls1974_sites_r_is['site_inc'].tolist()
Halls1974_upperR_dec_tc = Halls1974_sites_r_tc['site_dec'].tolist()
Halls1974_upperR_inc_tc = Halls1974_sites_r_tc['site_inc'].tolist()


I am working on the file "Example_PmagPy_Notebook.ipynb".
The first task is:
Calculating Fisher means
Fisher means for the data can be calculated with the function ipmag.fisher_mean. This function takes in a list of declination values, a list of inclination values and returns a dictionary that gives the Fisher mean and associated statistical parameters. This dictionary is printed out for the mean of the tilt-corrected data within the first code block. These dictionary objects are given names such that we can subsequently access the values. The second code block uses the ipmag.print_direction_mean to print out a formatted version of these same results.
Can you write Python code for it?

Halls1974_r_is_mean = ipmag.fisher_mean(Halls1974_sites_r_is.site_dec.tolist(),
                                        Halls1974_sites_r_is.site_inc.tolist())
Halls1974_r_tc_mean = ipmag.fisher_mean(Halls1974_sites_r_tc.site_dec.tolist(),
                                        Halls1974_sites_r_tc.site_inc.tolist())
print Halls1974_r_tc_mean

print 'The mean for the tilt-corrected Halls (1974) Osler directions is:'
ipmag.print_direction_mean(Halls1974_r_tc_mean)


I am working on the file "Example_PmagPy_Notebook.ipynb".
The first task is:
Combining and plotting the Halls (1974) and Swanson-Hysell et al. (2014) data
First, let's read in the data from the pmag_results.txt table from the Swanson-Hysell et al., (2014) study into a Pandas dataframe.
Can you write Python code for it?

SH2014_sites = pd.read_csv('./Data/Swanson-Hysell2014/pmag_results.txt',
                           sep='\t',skiprows=1)
SH2014_sites.head(1)


I am working on the file "Example_PmagPy_Notebook.ipynb".
The first task is:
Conducting a common mean test
The question "are the data sets consistent with being drawn from a common mean?" can be addressed utilizing the ipmag.watson_common_mean function. This function calculates Watson's V statistic from input data through Monte Carlo simulation in order to test whether two populations of directional data could have been drawn from a common mean. The critical angle between the two sample mean directions and the corresponding McFadden and McElhinny (1990) classification is also printed. A plot can be shown of the cumulative distribution of the Watson V statistic as calculated during the Monte Carlo simulations, as suggested by Tauxe et al. (2010).
Can you write Python code for it?


I am working on the file "Example_PmagPy_Notebook.ipynb".
The first task is:
Data analysis and visualization
The data can be analyzed and visualized using PmagPy functions. We will first create a directory called 'Example_Notebook_Output'  from within the notebook (using the initial ! before the command invokes a command as if typed on the command line from within a notebook) so that we have a place to put saved figures.  You can do this outside of the notebook if you prefer.
Can you write Python code for it?


I am working on the file "Example_PmagPy_Notebook.ipynb".
The first task is:
Developing a mean paleomagnetic pole
The virtual geomagnetic poles (VGPs) calculated from the Halls (1974) and Swanson-Hysell (2014) site means can be combined into a single paleomagnetic pole for the upper portion of the reversed polarity Osler Volcanic Group flows. Developing such a combined pole makes sense from a stratigraphic perspective given that the data come from a similar portion of the Osler Volcanic Group stratigraphy. We can test whether or not this combination makes sense from the data themselves by posing the question: are the data sets consistent with being drawn from a common mean?
First, the VGP longitudes and latitudes for the Halls (1974) data can be accessed from the pmag_results table. The results need to be filtered so that individual VGPs are being used (rather than mean poles) and that the reversed poles are being used (rather than the normal ones).
Can you write Python code for it?

Halls1974_results = pd.read_csv('./Data/Halls1974/pmag_results.txt',sep='\t',skiprows=1)

#filter so that individual results are shown filtering out mean poles
Halls1974_results_i = Halls1974_results.ix[Halls1974_results['data_type']=='i']

#filter so that reversed poles are included rather than normal poles
Halls1974_results_r = Halls1974_results_i.ix[Halls1974_results['er_location_names']=='Osler Volcanics, Nipigon Strait, Lower Reversed']

Halls1974_results_r.head()


I am working on the file "Example_PmagPy_Notebook.ipynb".
The first task is:
Fold test on the site mean directions
In the above plot, the blue directions that have been corrected for tilting have a higher precision than the red values that are uncorrected for tilting. The ratio of the precision parameter from before and after tilt-correction ($k_2$/$k_1$) is 2.2 (see output of code above). Calculating this ratio provides a way to qualitatively assess whether there is improvement in the precision of the data such that the magnetization was likely acquired prior to tilting. This ratio was at the heart of the McElhinny (1964; doi:10.1111/j.1365-246X.1964.tb06300.x) fold test (in which this would constitute of a positive test). However, that test has been shown to not be meaningful as summarized by McFadden (1990; doi:10.1111/j.1365-246X.1990.tb01761.x).
Halls (1974) noted that the precision increases with structural correction in the Osler dataset, but did not report the values of a statistical fold test. Swanson-Hysell et al. (2014) included all of these data, but did not report the results of the fold test. Here we conduct a Tauxe and Watson (1994; doi:10.1016/0012-821X(94)90006-X) bootstrap fold test on these data that reveals that the tightest grouping of vectors is achieved upon correction for bedding tilt thereby constituting a positive fold test.
Before we can do that, we must wrangle the data into the format expected by the fold test program.  We can start with the in situ directions from the pmag_results.txt files and pair them with the bedding orientations in the er_sites.txt files for each of the studies.
The in situ (geographic coordinates) for the reverse sites from Halls (1974) were read in from the pmag_sites table into Halls1974_sites_r_is.   We read the data from the Swanson-Hysell 2014 data from pmag_results table, so the column headers are different.  Both of these data sets must be paired with the bedding information in the er_sites tables for each study and put into the format expected by the function ipmag.bootstrap_fold_test which expects an array of...
Can you write Python code for it?


I am working on the file "Example_PmagPy_Notebook.ipynb".
The first task is:
Let's fish out the declinations and inclinations in geographic (in situ) coordinates (is) and those in tilt-corrected coordinates (tc) from the pmag_results table from the Swanson-Hysell2014 dataset and convert them from a dataframe object to a python list object.  We can see what happened with a print command.
Can you write Python code for it?

SH2014_upperR_dec_is = SH2014_OslerR_upper['tilt_dec_uncorr'].tolist()
SH2014_upperR_inc_is = SH2014_OslerR_upper['tilt_inc_uncorr'].tolist()
SH2014_upperR_dec_tc = SH2014_OslerR_upper['tilt_dec_corr'].tolist()
SH2014_upperR_inc_tc = SH2014_OslerR_upper['tilt_inc_corr'].tolist()
print SH2014_upperR_inc_tc


I am working on the file "Example_PmagPy_Notebook.ipynb".
The first task is:
Let's start with the Halls (1974) data set in Halls1974_sites_r_is. It is handier for the MagIC data tables in this exercise to have a list of dictionaries instead of a Pandas data frame.  So let's convert the Halls 1974 filtered dataframe to a list of dictionaries called Halls1974.
Can you write Python code for it?


I am working on the file "Example_PmagPy_Notebook.ipynb".
The first task is:
Loading the unpacked data into Pandas Dataframes
With the results unpacked from MagIC, the data can now be analyzed within the notebook. The data from the Halls1974/pmag_sites.txt table can be imported in order to look at the directions from each site. A nice way to deal with data within Python is using the dataframe structure of the pandas package. The code block below uses the pd.read_csv function to create a dataframe from the pmag_sites.txt file. All MagIC formatted files are tab delimited (sep='\t') with two header lines, one with the type of delimiter and MagIC table and one with the MagIC database column names. To see the formats for MagIC tables, go to http://earthref.org/MAGIC/metadata.htm.
To skip the first header line in a particular file when importing it to a DataFrame, set skiprows=1.  The data_frame_name.head(X) function allows us to inspect the first X rows of the dataframe (in this case 4).
Can you write Python code for it?

Halls1974_sites = pd.read_csv('./Data/Halls1974/pmag_sites.txt',
                              sep='\t',skiprows=1)
Halls1974_sites.head(4)


I am working on the file "Example_PmagPy_Notebook.ipynb".
The first task is:
Now all we have to do is make a numpy array out of the OslerR_upper_diddd and send it to the ipmag.bootstrap_fold_test function.
Can you write Python code for it?

diddd=np.array(OslerR_upper_diddd)
ipmag.bootstrap_fold_test(diddd,num_sims=100, min_untilt=0, max_untilt=140)


I am working on the file "Example_PmagPy_Notebook.ipynb".
The first task is:
Now we can plot the data!
Can you write Python code for it?

plt.figure(num=1,figsize=(4,4))
ipmag.plot_net(fignum=1)
ipmag.plot_di(combined_upperR_dec_is,
              combined_upperR_inc_is,color='r', label='insitu directions')
ipmag.plot_di(combined_upperR_dec_tc,
              combined_upperR_inc_tc,color='b', label='tilt-corrected directions')
plt.legend()
plt.show()


I am working on the file "Example_PmagPy_Notebook.ipynb".
The first task is:
Now we can read in the data from the er_sites.txt table (with the bedding attitudes) using the function pmag.magic_read which reads in magic tables into a list of dictionaries.  Then we will step through the records and pair each site with its bedding orientations using a handy function get_dict_item from the pmag module that will find correct site record. The function expects a list of dictionaries (Halls1974_sites), a key to filter on ('er_site_name'), the value of the key (pmag.magic_read reads things in as strings but because the names are numbers, pandas converted them to integers, hence the str(site['er_site_name']), and whether the two must be equal ('T'), not equal ('F'), contain ('has') or not contain ('not').   After finding the correct orientation record for the site, we can put the directions and bedding orientations together into the list OslerR_upper_diddd.
Can you write Python code for it?

Halls1974_sites,filetype=pmag.magic_read('./Data/Halls1974/er_sites.txt') # reads in the data
for site in Halls1974:
    orientations=pmag.get_dictitem(Halls1974_sites,'er_site_name',
                                       str(site['er_site_name']),'T')
    if len(orientations)>0: # record found
        OslerR_upper_diddd.append([site['site_dec'],site['site_inc'],
                        float(orientations[0]['site_bed_dip_direction']),
                                   float(orientations[0]['site_bed_dip'])])
    else:
        print 'no orientations found for site, ',site['er_site_name']


I am working on the file "Example_PmagPy_Notebook.ipynb".
The first task is:
Plotting VGPs and the mean pole
The code below uses the ipmag.plot_vgp function to plot the virtual geomagnetic poles and the ipmag.plot_pole function to plot the calculated mean pole along with its $A_{95}$ confidence ellipse.
The plot is developed using the Basemap package which enables the plotting of data on a variety of geographic projections. Basemap is not a standard part of most scientific python distributions so you may need to take extra steps to install it. If using the Anaconda distribution, you can type conda install basemap at the command line. The Enthought Canopy distribution has a GUI package manager that you can use for installing the package although a Canopy subscription (free for academic users) may be necessary for installation.
The plot is saved to the Output_files folder as an .svg file.
Can you write Python code for it?

from mpl_toolkits.basemap import Basemap

m = Basemap(projection='ortho',lat_0=35,lon_0=200,resolution='c',area_thresh=50000)
plt.figure(figsize=(6, 6))
m.drawcoastlines(linewidth=0.25)
m.fillcontinents(color='bisque',zorder=1)
m.drawmeridians(np.arange(0,360,30))
m.drawparallels(np.arange(-90,90,30))

ipmag.plot_vgp(m,SH2014_OslerR_upper['vgp_lon'].tolist(),
               SH2014_OslerR_upper['vgp_lat'].tolist(),
               marker='o')

ipmag.plot_vgp(m,Halls1974_results_r['vgp_lon'].tolist(),
               Halls1974_results_r['vgp_lat'].tolist(),
               marker='o',label='Osler upper reversed VGPs')

ipmag.plot_pole(m,Osler_upperR_pole['dec'],
             Osler_upperR_pole['inc'],
             Osler_upperR_pole['alpha95'],
             marker='s',label='Osler upper reversed pole')

plt.legend()
plt.savefig('Output_files/pole_plot.svg')
plt.show()


I am working on the file "Example_PmagPy_Notebook.ipynb".
The first task is:
Plotting the Halls (1974) results
The code block below creates a figure with an equal area stereonet and uses the ipmag.plot_di function to plot the data both in tilt-corrected and in situ coordinates. The figure can be saved out of the notebook using the plt.savefig() function. The saved figure file type can be .png, .eps, .svg among others. Saved figures can be used as is for publication or, if necessary, exported vector graphics (e.g. .eps and .svg files) can be edited with software such as Adobe Illustrator or Inkscape.
Can you write Python code for it?

plt.figure(num=1,figsize=(4,4))
ipmag.plot_net(fignum=1)
ipmag.plot_di(Halls1974_sites_r_is.site_dec.tolist(),
              Halls1974_sites_r_is.site_inc.tolist(),color='r',
              label='Halls (1974) site means (in situ)')
ipmag.plot_di(Halls1974_sites_r_tc.site_dec.tolist(),
              Halls1974_sites_r_tc.site_inc.tolist(),color='b',
             label='Halls (1974) site means (tilt-corrected)')
plt.legend(loc=9)
plt.savefig('Output_files/Halls_1974_sites.svg')


I am working on the file "Example_PmagPy_Notebook.ipynb".
The first task is:
Swanson-Hysell et al. (2014) argued that data from the upper third of the Simpson Island stratigraphy should be compared with the reverse data from the Halls (1974) Nipigon Strait region study. The dataframe can be filtered using the average_height value from the pmag_results table.
Can you write Python code for it?

SH2014_OslerR_upper = SH2014_sites.ix[SH2014_sites.average_height>2082]
SH2014_OslerR_upper.reset_index(inplace=True)
SH2014_OslerR_upper.head()


I am working on the file "Example_PmagPy_Notebook.ipynb".
The first task is:
The combined means can be calculated with the ipmag.fisher_mean function and printed out with some formatting with the ipmag.print_direction_mean function.
Can you write Python code for it?

OslerUpper_is_mean = ipmag.fisher_mean(combined_upperR_dec_is,
                                       combined_upperR_inc_is)
print "The Fisher mean of the insitu upper Osler R directions:"
ipmag.print_direction_mean(OslerUpper_is_mean)
print ''
OslerUpper_tc_mean = ipmag.fisher_mean(combined_upperR_dec_tc,
                                      combined_upperR_inc_tc)
print "The Fisher mean of the tilt-corrected upper Osler R directions:"
ipmag.print_direction_mean(OslerUpper_tc_mean)
print ''
print 'The k_2/k_1 ratio is:'
print OslerUpper_tc_mean['k']/OslerUpper_is_mean['k']


I am working on the file "Example_PmagPy_Notebook.ipynb".
The first task is:
The means that have been calculated are now dictionaries that can be made into a new dataframe to present the results. A table like this can be exported into a variety of formats (e.g. LaTeX, html, csv) for inclusion in a publication.
Can you write Python code for it?

Halls1974_r_is_mean = ipmag.fisher_mean(Halls1974_sites_r_is.site_dec.tolist(),
                                        Halls1974_sites_r_is.site_inc.tolist())
Halls1974_r_tc_mean = ipmag.fisher_mean(Halls1974_sites_r_tc.site_dec.tolist(),
                                        Halls1974_sites_r_tc.site_inc.tolist())
means = pd.DataFrame([Halls1974_r_is_mean,Halls1974_r_tc_mean],
                     index=['Halls 1974 Osler R (insitu)','Halls 1974 Osler R (tilt-corrected)'])
means


I am working on the file "Example_PmagPy_Notebook.ipynb".
The first task is:
There are three other important Python libraries (which are bundled with the Canopy and Anaconda installations of Python) that come in quite handy and are used within this notebook:  numpy for data analysis using arrays, pandas for data manipulation within dataframes and matplotlib for plotting. The call %matplotlib inline results in the plots being shown within this notebook rather than coming up in external windows.
Can you write Python code for it?

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
%config InlineBackend.figure_formats = {'svg',}


I am working on the file "Example_PmagPy_Notebook.ipynb".
The first task is:
We can do the same for the filtered upper Osler sequence of Swanson-Hysell et al. (2014).  These have slightly different keys, but the general idea is the same.  In the cell below, we convert the dataframe to a list of dictionaries, fish out the bedding orientations and attach them to the same list as before (OslerR_upper_diddd).
Can you write Python code for it?

SH2014=SH2014_OslerR_upper.T.to_dict().values()
SH2014_sites,filetype=pmag.magic_read('./Data/Swanson-Hysell2014/er_sites.txt')
for site in SH2014:
    orientations=pmag.get_dictitem(SH2014_sites,'er_site_name',
                                   str(site['er_site_names']),'T')
    if len(orientations)>0: # record found
        OslerR_upper_diddd.append([site['tilt_dec_uncorr'],site['tilt_inc_uncorr'],
                        float(orientations[0]['site_bed_dip_direction']),
                                   float(orientations[0]['site_bed_dip'])])
    else:
        print 'no orientations found for site, ',site['er_site_names']


I am working on the file "Examples.ipynb".
The first task is:
After appplying FastICA algorithm, we visualize each independent component in the following plot
Can you write Python code for it?

ica_fMRI = fastICA_ne(fMRI,f = "logcosh", alpha = 1,maxit = 200, tol = 0.0001)
S_fMRI = ica_fMRI['S']
fig = plt.figure(figsize=(10,6))
for i in range(20):
    ax = plt.subplot(5,4,i+1)
    plt.plot(np.arange(30000)+1, S_fMRI[:,i])
    plt.xticks([])
    plt.yticks([])
fig.suptitle('Visualization of the Independent Components by ICA', fontsize=20)
pass


I am working on the file "Examples.ipynb".
The first task is:
Comparative Analysis
Here we follow the example from http://scikit-learn.org/stable/auto_examples/decomposition/plot_ica_blind_source_separation.html
Can you write Python code for it?

%%writefile Test/comparedata.py

# Generate observation data
import numpy as np
from scipy import signal

np.random.seed(0)
n_samples = 2000
time = np.linspace(0, 8, n_samples)

s1 = np.sin(2 * time)                   # Signal 1 : sinusoidal signal
s2 = np.sign(np.sin(3 * time))          # Signal 2 : square signal
s3 = signal.sawtooth(2 * np.pi * time)  # Signal 3: saw tooth signal

S_compare = np.c_[s1, s2, s3]
S_compare += 0.2 * np.random.normal(size=S_compare.shape)  # Add noise

S_compare /= S_compare.std(axis=0)                      # Standardize data
# Mix data
A = np.array([[1, 1, 1], [0.5, 2, 1.0], [1.5, 1.0, 2.0]])  # Mixing matrix
X_compare = np.dot(S_compare, A.T)

%run Test/comparedata.py

S_ica = fastICA_ne(X_compare,f = "logcosh", alpha = 1,maxit = 200, tol = 0.0001)['S']

%%writefile Test/plot_compare.py

from sklearn.decomposition import PCA
from sklearn.decomposition import FactorAnalysis
import matplotlib.pyplot as plt

def plot_compare(X_compare,S_compare,S_ica):

    pca = PCA(n_components=3)
    S_pca = pca.fit_transform(X_compare)

    fa = FactorAnalysis(n_components=3)
    S_fa= fa.fit_transform(X_compare)

    models = [X_compare, S_compare,S_ica, S_pca, S_fa]
    names = ['Observations (mixed signal)',
             'True Sources',
             'FastICA recovered IC signals',
             'PCA recovered IC signals',
            'Factor Analysis recovered IC signals']
    colors = ['red', 'steelblue', 'orange']

    plt.figure(figsize=(10,6))
    for ii, (model, name) in enumerate(zip(models, names), 1):  # enumerate starts from 1
        plt.subplot(5, 1, ii)
        plt.title(name)
        for sig, color in zip(model.T, colors):
            plt.plot(sig, color=color)
            plt.xticks([])
            plt.yticks([])
    plt.subplots_adjust(0.09, 0.09, 0.94, 0.94, 0.5, 1)

%run Test/plot_compare.py

plot_compare(X_compare,S_compare,S_ica)


I am working on the file "Examples.ipynb".
The first task is:
Define what you need
Can you write Python code for it?

# Configuration
input_file = "input/test/test_annovar.hg19.tsv"
conf.add_field("Chr")
conf.add_field("Start")
conf.add_field("End")


I am working on the file "Examples.ipynb".
The first task is:
Design is to print results to the screen with no output being available. However, new usages have highlighted the need to enable outputs and hide printing. Thus the addition of the print_out boolean to turn off printing but instead return an output.
Can you write Python code for it?

A = np.array([[1.23456, 23.45678],[456.23+1j, 8.239521]])
latex_code = a2l.to_ltx(A, frmt = '{:.2f}', arraytype = 'array', mathform = True, print_out=False)


I am working on the file "Examples.ipynb".
The first task is:
First we'll use a Metropolis-Hastings sampler. Each sampler requires a $\log{P(\theta)}$ function and a starting state. We have included a function to calculate the maximum a posteriori (MAP) to find the peak of the distribution for use as the starting state. Then you call the sample method and a chain of samples is returned.
Can you write Python code for it?

start = smp.find_MAP(logp, {'x':1.})
metro = smp.Metropolis(logp, start)
chain = metro.sample(10000, burn=2000, thin=4)


I am working on the file "Examples.ipynb".
The first task is:
Here is that function in action.
Can you write Python code for it?

docs = [
    "Sehr hilfreich und macht sogar Spaß!",
    "Der Prozess ist langsam und kostet einen viele Nerven."
]

for doc in get_sentiment(docs):
    print('Text: {}'.format(doc["text"]))
    print('Score: {:.3f}'.format(doc["score"]))
    print()


I am working on the file "Examples.ipynb".
The first task is:
Here we have sampled from a normal distribution with a mean of 3, indicated with the dashed vertical line.
There is also a No-U-Turn Sampler (NUTS), which avoids the random-walk nature of Metropolis samplers. NUTS uses the gradient of $\log{P(\theta)}$ to make intelligent state proposals. You'll notice here that we don't pass in any information about the gradient. Instead, it is calculated automatically with autograd.
Can you write Python code for it?

nuts = smp.NUTS(logp, start)
chain = nuts.sample(2100, burn=100)

plt.plot(chain)

_ = plt.hist(chain.x, bins=30)
_ = plt.vlines(mu, 0, 250, linestyles='--')


I am working on the file "Examples.ipynb".
The first task is:
Let's create an array and output it as $\LaTeX$. We are going to use Python 3.0 string formatting
The following shows a float style output with 2 decimal places.
Can you write Python code for it?


I am working on the file "Examples.ipynb".
The first task is:
Let's put it in exponential form.
Can you write Python code for it?

a2l.to_ltx(A, frmt = '{:.2e}', arraytype = 'array', mathform=False)


I am working on the file "Examples.ipynb".
The first task is:
Let's try something a little more complicated. Let's say you run a business and you put an advertisement in the paper. Then, to judge the effectiveness of the ad, you want to compare the number of incoming phone calls per hour before and after the placement of the add. Then we can build a Bayesian model using a Poisson likelihood with exponential priors for $\lambda_1$ and $\lambda_2$.
\begin{align}
P(\lambda_1, \lambda_2 \mid D) &\propto P( D \mid \lambda_1, \lambda_2)\, P(\lambda_1)\, P(\lambda_2) \
P( D \mid \lambda_1, \lambda_2) &\sim \mathrm{Poisson}(D\mid\lambda_1)\,\mathrm{Poisson}(D\mid\lambda_2) \
P(\lambda_1) &\sim \mathrm{Exp}(1) \
P(\lambda_2) &\sim \mathrm{Exp}(1)
\end{align}
This analysis method is known as Bayesian inference or Bayesian estimation. We want to know likely values for $\lambda_1$ and $\lambda_2$. This information is contained in the posterior distribution $P(\lambda_1, \lambda_2 \mid D)$. To infer values for $\lambda_1$ and $\lambda_2$, we can sample from the posterior using our MCMC samplers.
Can you write Python code for it?

# Fake data for the day before and after placing the ad.
# We'll make the calls increase by 2 an hour. Record data for each
# hour over two work days.
before = np.random.poisson(7, size=16)
after = np.random.poisson(9, size=16)

# Define the log-P function here
def logp(lam1, lam2):
    # Rates for Poisson must be > 0
    if lam1 <= 0 or lam2 <=0:
        return -np.inf
    else:
        # logps for likelihoods
        llh1 = np.sum(before*np.log(lam1)) - before.size*lam1
        llh2 = np.sum(after*np.log(lam2)) - after.size*lam2

        # Exponential priors for lams
        lam1_prior = -lam1
        lam2_prior = -lam2
        return llh1 + llh2 + lam1_prior + lam2_prior

start = smp.find_MAP(logp, {'lam1':1., 'lam2':1.})
metro = smp.Metropolis(logp, start)
trace = metro.sample(10000, burn=2000, thin=4)


I am working on the file "Examples.ipynb".
The first task is:
Now to see if there is a significant difference between the two days. We can find the difference $\delta =  \lambda_2 - \lambda_1$, then find the probability that $\delta > 0$.
Can you write Python code for it?

delta = trace.lam2 - trace.lam1
_ = plt.hist(delta, bins=30)
_ = plt.vlines(2, 0, 250, linestyle='--')

p = np.mean(delta > 0)
effect = np.mean(delta)
CR = np.percentile(delta, (2.5, 97.5))
print("{:.3f} probability the rate of phone calls increased".format(p))
print("delta = {:.3f}, 95% CR = {{{:.3f} {:.3f}}}".format(effect, *CR))


I am working on the file "Examples.ipynb".
The first task is:
One can use a number before the decimal place. This defines the minimum width to use for the number, padding with spaces at the beginning.
Since the largest number needs 6 characters (3 before the decimal, the decimal, and 2 after), putting a 6 in this location makes everything line up nicely. This would also be a nice default to code up.
Can you write Python code for it?


I am working on the file "Examples.ipynb".
The first task is:
Panda DataFrames
You can also produce tables or math arrays from Panda DataFrames.
Can you write Python code for it?

df = pd.DataFrame(np.random.randint(low=0, high=10, size=(5, 5)),
...                    columns=['a', 'b', 'c', 'd', 'e'])

df

np.array(df)

a2l.to_ltx(df, arraytype='bmatrix')

a2l.to_ltx(df, arraytype='tabular')

df2 = pd.DataFrame(['cat', 'dog', 'bird', 'snake', 'honey badger'], columns=['pets'])
df2

df_mixed = df.join(df2)
df_mixed

a2l.to_ltx(df_mixed, arraytype='tabular')

A = np.array([[1.23456, 23.45678],[456.23, 8.239521]])
a2l.to_ltx(A, frmt = '{:6.2f}', arraytype = 'array')

A = np.array([[1.23456, 23.45678],[456.72+392.71j, 8.239521]])


I am working on the file "Examples.ipynb".
The first task is:
Real World Data
fMRI
This is a subsample of real fMRI data from the 1000 Connectome Project.
Can you write Python code for it?


I am working on the file "Examples.ipynb".
The first task is:
Sampling returns a numpy record array which you can use to access samples by name. Variable names are taken directly from the argument list of logp.
Can you write Python code for it?

print(metro.var_names)

plt.plot(trace.lam1)
plt.plot(trace.lam2)


I am working on the file "Examples.ipynb".
The first task is:
The result is an array with all rows parsed.
This print is limited to the first 4 elements.
Can you write Python code for it?


I am working on the file "Examples.ipynb".
The first task is:
There true difference in rates is two per hour, marked with the dashed line. Our posterior is showing an effect, but our best estimate is that the rate increased by only one call per hour. The 95% credible region is {-0.865 2.982} which idicates that there is a 95% probability that the true effect lies with the region, as it indeed does.
We can alo use NUTS to sample from the posterior.
Can you write Python code for it?

nuts = smp.NUTS(logp, start)
trace = nuts.sample(2100, burn=100)
_ = plt.plot(trace.lam1)
_ = plt.plot(trace.lam2)

delta = trace.lam2 - trace.lam1
_ = plt.hist(delta, bins=30)
_ = plt.vlines(2, 0, 250, linestyle='--')
p = np.mean(delta > 0)
effect = np.mean(delta)
CR = np.percentile(delta, (2.5, 97.5))
print("{:.3f} probability the rate of phone calls increased".format(p))
print("delta = {:.3f}, 95% CR = {{{:.3f} {:.3f}}}".format(effect, *CR))


I am working on the file "Examples.ipynb".
The first task is:
True Source Components
Can you write Python code for it?


I am working on the file "Examples.ipynb".
The first task is:
We can still print the returned formatted latex code:
Can you write Python code for it?


I am working on the file "Examples.ipynb".
The first task is:
We can use the lambda function method to create a function with personalized defaults. This makes for a much more compact call, and one that can be adjusted for an entire session.
Can you write Python code for it?

to_tex = lambda A : a2l.to_ltx(A, frmt = '{:6.2e}', arraytype = 'array', mathform=True)
to_tex(A)

to_tex = lambda A : a2l.to_ltx(A, frmt = '{:6.2f}', arraytype = 'array', mathform=True)
to_tex(A)


I am working on the file "Examples/.ipynb_checkpoints/Combining Pseudorange and Phase-checkpoint.ipynb".
The first task is:
This plot is uncorrected, it is a remake of the plot in Anthea's email on Wed, Jun 15, 2016 at 7:06 AM. The phase calculated TEC appears to match the pseudorange calculated TEC in parts, but other parts are offset by a bias. The next script and plot shows how the phase data can be shifted to line up with the average of the pseudorange data. It does so according to how large the slice value is. Basically it slices up the whole data set into a specifiable range of points and does the averaging on each range of points individually in order to fix phase lock cycle slips. This isn't the best way of doing it, the program should check for loss of lock and shift the phase data in chunks based on that. I am going to read more about cycle slips now.
Can you write Python code for it?

sl=200
plt.figure(figsize=(15,15))
ax1=plt.subplot(211)
ax1.xaxis.set_major_formatter(fmt)

plt.plot(2.85E9*(poop[:,23,'P2','data']/3.0E8
                 -poop[:,23,'C1','data']/3.0E8),'b.',label='prtec',markersize=3)

for i in range(int(len(poop[:,23,'L1','data'])/sl)):

    phtec = 2.85E9*(poop[poop.labels[sl*i:sl*(i+1)],23,'L1','data']/f1
                   -poop[poop.labels[sl*i:sl*(i+1)],23,'L2','data']/f2)

    prtec = 2.85E9*(poop[poop.labels[sl*i:sl*(i+1)],23,'P2','data']/3.0E8
                   -poop[poop.labels[sl*i:sl*(i+1)],23,'C1','data']/3.0E8)

    b = np.average((phtec-prtec)[np.logical_not(np.isnan(phtec-prtec))])
    plt.plot(phtec-b,'r-',linewidth=3,label='')

plt.axis([poop.labels[10],poop.labels[10000],-50,50])
plt.title('bias corrected phase data')
plt.xlabel('time')
plt.ylabel('TECu')
plt.grid()
plt.legend()
plt.show()


I am working on the file "Examples/.ipynb_checkpoints/Combining Pseudorange and Phase-checkpoint.ipynb".
The first task is:
try some stuff out from "An Automatic Editing Algorith for GPS Data" by Blewitt
Can you write Python code for it?

f1 = 1575.42E6
f2 = 1227.6E6

svn = 23
L1 = -1*3.0E8*poop[:,svn,'L1','data']/f1  #(1a)
L2 = -1*3.0E8*poop[:,svn,'L2','data']/f2  #(1b)
P1 = poop[:,svn,'C1','data']              #(1c)
P2 = poop[:,svn,'P2','data']              #(1d)

#wide lane combination
wld = 3.0E8/(f1-f2)
Ld = (f1*L1-f2*L2)/(f1-f2)                #(3)
prd = (f1*P1+f2*P2)/(f1+f2)               #(4)
bd = (Ld-prd)/wld                         #(5)

#wide lane cycle slip detection
bdmean = bd[1]
rms = 0

g=np.empty((bd.shape))
g[:]=np.nan
p=np.empty((bd.shape))
p[:]=np.nan

for i in range(2,len(bd)):
    if not np.isnan(bd[i]):
        g[i] = abs(bd[i]-bdmean)
        p[i] = np.sqrt(rms)
        rms = rms+((bd[i]-bdmean)**2-rms)/(i-1) #(8b)
        bdmean = bdmean+(bd[i]-bdmean)/(i-1)    #(8a)

plt.figure(figsize=(12,12))
plt.subplot(211).xaxis.set_major_formatter(fmt)
plt.plot(bd.keys(),g,label='bd[i]-bias average')
plt.plot(bd.keys(),4*p,label='rms')
plt.legend()
plt.grid()
plt.title('if current bd>4*rms then it is a wide-lane cycle slip')
plt.ylabel('cycles')
plt.xlabel('time')
plt.show()

#ionospheric combination
LI = L1-L2      #(6)
PI = P2-P1      #(7)

#ionospheric cycle slip detection

plt.figure(figsize=(10,10))
# get x and y vectors
mask=~np.isnan(PI)
x = np.arange(len(PI[mask]))
y = PI[mask]

# calculate polynomial
z = np.polyfit(x, y, 6)
f = np.poly1d(z)

# calculate new x's and y's
x_new = np.linspace(x[0], x[-1], len(x))
Q = f(x_new)

residual = LI[mask]-Q
plt.plot(residual[1:])
plt.show()
for i in range(1,len(residual)):
    if(residual[i]-residual[i-1]>1):
        print(i,residual[i]-residual[i-1])


I am working on the file "Examples/.ipynb_checkpoints/ReadRinex Demo-checkpoint.ipynb".
The first task is:
So the TEC is off by a large factor on the pseudorange graph, I'm not sure where that's coming from right now, I followed the equation from the thesis. The difference in pseudorange between the frequencies is very small, is that how its supposed to be and it needs to be multiplied by a constant? or is the data off? The file I used doesn't have P1 and P2, only P2, but I compared P2 to C2 and it is the same, so C1, C2 and C5 should work the same.
Can you write Python code for it?

fig2 = plt.figure(figsize = (10,10))

ax = plt.subplot()
ax.xaxis.set_major_formatter(fmt)
ax.autoscale_view()

plt.xlabel('time')
plt.ylabel('pseudorange (m)')
plt.title('comparison of C2 and P2')

plt.plot(data[:,sv_of_interest,'P2','data'])
plt.plot(data[:,sv_of_interest,'C2','data'])
plt.show()


I am working on the file "Examples/.ipynb_checkpoints/Rideout method TEC plots-checkpoint.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()


I am working on the file "Examples/.ipynb_checkpoints/Rideout method TEC plots-checkpoint.ipynb".
The first task is:
This script filters the data from the rinex file to look at only the first tlim points, which in this case turns out to be from about 6-7 UTC. It then further filters the points to only include satellites with a minimum of minpoints L1, L2, C1, and C2 values that aren't Nan. Finally only points with TEC values between 0 and 200 (in TECu, I believe) are included in the final dataframe, interesting_data. TEC is calculated according to the method in Bill Rideout's program, tec.py. NOTE: in his program, he only plots short blocks of data, about 30 seconds in length according to him, at a time, where there are no large (>1 TECu) jumps in TEC. I included all the data from 6-7 UTC and it is pretty messy.
Can you write Python code for it?

fig = plt.figure(figsize=(14,14))
tlim = 4000
minpoints = 3000

svs_with_pts_in_range = [i for i in data.items if(np.sum(np.logical_and.reduce(
                (data[data.labels[:tlim],i,'L1','data']>0,
                 data[data.labels[:tlim],i,'L2','data']>0,
                 data[data.labels[:tlim],i,'C1','data']>0,
                 data[data.labels[:tlim],i,'C2','data']>0)))>minpoints)]

#Bill's Calculation:
convertL1ToMeters = 3.0E8/(154.0*10.23E6)
convertL2ToMeters = 3.0E8/(120.0*10.23E6)
f2f1Factor = 1.545727
convertMetersToTEC = 6.158

interesting_data = DataFrame()

for sv in svs_with_pts_in_range:
    diffrange = data[data.labels[:tlim],sv,'C2','data']-data[data.labels[:tlim],sv,'C1','data']
    diffrange = diffrange*convertMetersToTEC*f2f1Factor
    phase = f2f1Factor*(convertL1ToMeters*data[data.labels[:tlim],sv,'L1','data']
                        -convertL2ToMeters*data[data.labels[:tlim],sv,'L2','data'])

    phase = phase*convertMetersToTEC
    median = sorted(list(phase-diffrange))[int(len(diffrange)/2)]
    TEC = phase-median
    interesting_data[sv]=TEC[np.logical_and(TEC<200,TEC>0)]

    print("SVN: {}, Pts above 200: {}, Pts below zero: {}, NaNs: {}".format(sv,
                                                                            np.sum(TEC>200),
                                                                            np.sum(TEC<0),
                                                                            np.sum(np.isnan(TEC))))

fig = plt.figure(figsize=(16,16))
ax1 = plt.subplot(211)
fmt = DateFormatter('%H:%M:%S')
ax1.xaxis.set_major_formatter(fmt)
ax1.autoscale_view()
plt.xlabel('Time')
plt.ylabel('TECu')
plt.title("Rideout's TEC Method")

lines = plt.plot(interesting_data)
plt.legend(lines,interesting_data.columns)
plt.grid()

plt.show()


I am working on the file "Examples/.ipynb_checkpoints/Welcome LiPD - Quickstart-checkpoint.ipynb".
The first task is:
DOI Updater

The DOI updater will take your LiPD files and update them with the most recent information provided by doi.org. The updater will run once per LiPD, and will skip any LiPD files that were updated previously.

**NOTE**

 `doi()` will update each LiPD file loaded after `readLipds()`

Can you write Python code for it?


I am working on the file "Examples/.ipynb_checkpoints/Welcome LiPD - Quickstart-checkpoint.ipynb".
The first task is:
Library Data (example)

Library data holds many datasets that are sorted by name. Below is an example of what the library looks like. There are three files in this library, and one file is expanded to show its contents.
Can you write Python code for it?


I am working on the file "Examples/.ipynb_checkpoints/Welcome LiPD - Quickstart-checkpoint.ipynb".
The first task is:
Library Data

All LiPD Library data is stored in Python "objects" that allow us to manage and manipulate the data more easily. However, storing and pickling the data in this structure is not ideal for most situations. The JSON format is recommended as it is universal and easier to share.
getLibrary()

* Returns: dictionary
* Retrieves the LiPD Library as a Python dictionary.

Can you write Python code for it?


I am working on the file "Examples/.ipynb_checkpoints/Welcome LiPD - Quickstart-checkpoint.ipynb".
The first task is:
NOAA Converter

National Oceanic and Atmospheric Administration (NOAA) text files must be converted to LiPD before any LiPD functions can be used. The converter is designed to parse data from the NOAA text template. Please insert your data in this template format to ensure a complete and accurate conversion to LiPD. Use the example file as a reference for correct formatting.
LPD to NOAA:

Converts all LiPD files into NOAA text files. Creates one NOAA text file for each data table found in the LiPD file. The LiPD file is updated to include the WDC URL that links to the corresponding NOAA dataset that it creates.

NOAA to LPD:

Converts NOAA text file into a LiPD file.

NOAA text template:

NOAA template
Example File:

khider2011b.txt

**NOTE**

 The NOAA converter will run for every `.txt` file currently loaded.

These conversions are both potentially lossy conversions. We have worked hard to map data between formats, but there are some keys that remain unmapped and will not be transferred to the new file format.

Can you write Python code for it?

# Run the function
lipd.noaa()

# Choose a conversion
Which conversion?
1. LPD to NOAA
2. NOAA to LPD


I am working on the file "Examples/.ipynb_checkpoints/Welcome LiPD - Quickstart-checkpoint.ipynb".
The first task is:
Pickling Data

The Pickle module is a python core module allows us to share LiPD data with python 2.7 users. It won't have the support or functions of LiPD Utilities, but it will give access to the data.
A Pickle file (.pklz) is a compressed archive file. It's small size makes sharing easy.
Can you write Python code for it?

import pickle
import gzip

# Read a pickle file
f = gzip.open('filename.pklz','rb')
newData = pickle.load(f)
f.close()

# Write a pickle file
yourData = {'a':'blah','b':range(10)}
f = gzip.open('filename.pklz','wb')
pickle.dump(yourData,f)
f.close()


I am working on the file "Examples/.ipynb_checkpoints/Welcome LiPD - Quickstart-checkpoint.ipynb".
The first task is:
Quitting
Quitting the session is important. This will perform cleanup functions and reclaim the space of opened LiPD files on your computer

Can you write Python code for it?


I am working on the file "Examples/.ipynb_checkpoints/Welcome LiPD - Quickstart-checkpoint.ipynb".
The first task is:
Removing LiPDs

removeLipd(filename)
* Remove one dataset from the LiPD Library
removeLipds()
* Remove all datasets from the LiPD Library
Can you write Python code for it?


I am working on the file "Examples/.ipynb_checkpoints/Welcome LiPD - Quickstart-checkpoint.ipynb".
The first task is:
TimeSeries

TimeSeries functions are useful creating, filtering, and exporting TimeSeries from the LiPD data in the workspace.
extractTs()

* Returns: dictionary
* Creates a time series from the data in the workspace.

collapseTs(time_series)

* Returns: none
* Puts time series data back into the workspace data.

find(expression, time_series)

* Returns: List, all objects that matched the expression
* Find all time series objects that match a certain criteria.

**WARNING**

`collapseTs()` will overwrite the contents of the LiPD Library

TimeSeries Object (example)

A time series holds many time series objects. Below is an example of what the contents of a time series object look like.
Can you write Python code for it?

%%html

time_series = lipd.extractTs()

new_time_series = lipd.find("archiveType is marine sediment", time_series)

new_time_series = lipd.find("geo_meanElev <= -1000 && geo_meanElev > -1100", time_series)

lipd.collapseTs(time_series)


I am working on the file "Examples/.ipynb_checkpoints/demo-checkpoint.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/.ipynb_checkpoints/demo-checkpoint.ipynb".
The first task is:
Clearly the SVR method is quite capable of reproducing the time constants simulated data using very simple to calculate features. We observe some lower limit to the model's ability to calculate time constants, which is quite interesting. However, this lower limit appears below 100 nanoseconds, a time-scale that is seldom seen in the real world. This could be quite useful for extracting time constant data!
Analyzing a Real Image
The Data
In order to assess the ability of the model to apply to real images, I have taken a trEFM image of an MDMO photovoltaic material. There are large aggregates of acceptor material that should show a nice contrast in the way that they generate and hold charge. Each pixel of this image has been pre-averaged before being saved with this demo program. Each pixel is a measurement of the AFM cantilever position as a function of time.
The Process
Our mission is to extract the time constant out of this signal using the SVR fit of our simulated data. We accomplish this by importing and calling the "process_image" function.
Can you write Python code for it?


I am working on the file "Examples/.ipynb_checkpoints/demo-checkpoint.ipynb".
The first task is:
Simulation
You can create an array of time constants that you would like to simulate the data for. This array can then be input into the simulation function which simulates the data as well as fits it using standard vector regression. This function can take a few minutes dpending on the number of time constants you provide. Run this cell and wait for the function to complete. There may be an error that occurs, don't fret as this has no effect.
Can you write Python code for it?

tau_array = np.logspace(-8, -5, 100)

fit_object, fit_tau = data_sim.sim_fit(tau_array)


I am working on the file "Examples/.ipynb_checkpoints/demo-checkpoint.ipynb".
The first task is:
The image processing function needs two inputs. First we show the function the path to the provided image data. We then provide the function with the SVR object that was previously generated using the simulated cantilever data. Processing this image should only take 15 to 30 seconds.
Can you write Python code for it?

tau_img, real_sum_img, fft_sum_img, amp_diff_img = process_image.analyze_image('.\\image data\\', fit_object)


I am working on the file "Examples/.ipynb_checkpoints/demo-checkpoint.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')
axs[2].set_
plt.tight_layout()
plt.show()


I am working on the file "Examples/12_tacticities/polycarboxybetaine/scripts/rnd_walk.pilot_tutorial.ipynb".
The first task is:
Finally, let's check the tacticity of the created oligomer.
The check_tacticity() method of the random_walk application analyzes the local geometry of atoms for polymers which can have tacticity. The method returns the distribution of meso/racemo diads along the backbone of the macromolecule (see the image).
Can you write Python code for it?


I am working on the file "Examples/12_tacticities/polycarboxybetaine/scripts/rnd_walk.pilot_tutorial.ipynb".
The first task is:
Functions to draw results
Method that plots ratio of meso/racemo diads in the system as calculated by the pysimm.apps.random_walk.check_tacticity()
Can you write Python code for it?

def display_diad_distrib(data, canvas):
    canvas.hist(list(map(int, data)), bins=[-0.5, 0.5, 1.5], rwidth=0.2,
                range=(-0.5, 1.5), density=False);
    mplp.xticks(ticks=[0, 1], labels=['Racemo', 'Meso'], fontsize=16)
    canvas.set_ylabel('Number of diads', fontsize=18)
    canvas.set_xlabel('Diad type', fontsize=18)
    return canvas


I am working on the file "Examples/12_tacticities/polycarboxybetaine/scripts/rnd_walk.pilot_tutorial.ipynb".
The first task is:
Here is an example of definition of head and tail atoms in the CBMA repetitive unit.
As shown above, the undercoordinated carbon atoms (carbons with incomplete valency) have the indices 1 and 2. They will be the head (the atom with which the current repeating unit connects to the previous repeating unit) and the tail (the atom to which the next repeating unit connects to) during the pysimm polymerization process
Can you write Python code for it?

display.Image('../figures/figure2.png', embed=True, retina=True)

lnkr_atoms = {'head': 1, 'tail': 2}

for itm, nm in lnkr_atoms.items():
    sst.particles[nm].linker = itm


I am working on the file "Examples/12_tacticities/polycarboxybetaine/scripts/rnd_walk.pilot_tutorial.ipynb".
The first task is:
Let's type the repetitive unit with basic pysimm CGenFF automatic typing tool.
The partial charges of all particles were read from the .str file, so there is no need to reassign them (in principle PySIMM can do it using Gasteiger method)
Can you write Python code for it?

ff = forcefield.Charmm()
sst.apply_forcefield(ff, charges=None)


I am working on the file "Examples/12_tacticities/polycarboxybetaine/scripts/rnd_walk.pilot_tutorial.ipynb".
The first task is:
Method draws a PySIMM molecular system by creating a temporary .PDB file and using means of NGLView to show it on the notebook canvas.
If the fname file name is set will also save the temporary .pdb file under that name.
Can you write Python code for it?

try:
    import nglview
except ImportError as err:
    print('No NGL|View module installed for this Python kernell')

def display_system(sstm, fname=None, labels_on=False):
    is_temp = False
    if not fname:
        fname = 'tmp_file.pdb'
        is_temp = True

    sstm.write_pdb(fname)

    if 'nglview' in sys.modules.keys():
        view = nglview.show_structure_file(fname)
        if labels_on:
            view.add_label(color='black', scale=1.3, labelType='text',
                           labelText = [str(pt.tag) for pt in sstm.particles],
                           zOffset=2.0, attachment='middle_center')
    if is_temp:
        os.remove(fname)

    return view


I am working on the file "Examples/12_tacticities/polycarboxybetaine/scripts/rnd_walk.pilot_tutorial.ipynb".
The first task is:
Now let's do the same but with the forcefield optimization turned on, and see how many diads will be reconfigured from racemo- to meso- geometry.
Can you write Python code for it?

polymer = random_walk_tacticity(new_sst, 15, forcefield=ff, tacticity=0.0, )

display_system(polymer, 'some_chain.pdb')

tacticity_stat = check_tacticity(polymer, [1, 2, 8, 10], len(sst.particles))

fig, ax = mplp.subplots(1, 1, figsize=(8, 4))
display_diad_distrib(tacticity_stat[1], ax);


I am working on the file "Examples/12_tacticities/polycarboxybetaine/scripts/rnd_walk.pilot_tutorial.ipynb".
The first task is:
Once the built is sucsessesfull, let's visualise the oligomer chain we built.
Can you write Python code for it?


I am working on the file "Examples/12_tacticities/polycarboxybetaine/scripts/rnd_walk.pilot_tutorial.ipynb".
The first task is:
So far, the oligomer chain is uncapped. There are two backbone atoms in the system that are undercoordinated. Let's use the method that is set in appendix to connect methyl groups to those undercoordinated atoms.
Can you write Python code for it?

oligomer = sngl_chain.copy()
cap_with_methyls(oligomer, ff)
oligomer.center(what='particles', at=[0.0, 0.0, 0.0], move_both=False)

display_system(oligomer, 'oligomer.15unts.capped.vacuum.pdb')


I am working on the file "Examples/12_tacticities/polycarboxybetaine/scripts/rnd_walk.pilot_tutorial.ipynb".
The first task is:
Step II: Making the polymer and checking its tacticity
Once the forcefield types and charges are defined, one can use the forcefield-assisted random walk method. Let's built a short (15 rep. units) chain.
Can you write Python code for it?

sngl_chain = random_walk(sst, 15,
                         forcefield=ff, density=0.01,
                         print_to_screen='false', traj=False, unwrap=True)