markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
When we used these same parameters earlier, we saw the network with batch normalization reach 92% validation accuracy. This time we used different starting weights, initialized using the same standard deviation as before, and the network doesn't learn at all. (Remember, an accuracy around 10% is what the network gets i... | train_and_test(True, 2, tf.nn.relu) | batch-norm/Batch_Normalization_Lesson.ipynb | JasonNK/udacity-dlnd | mit |
When we trained with these parameters and batch normalization earlier, we reached 90% validation accuracy. However, this time the network almost starts to make some progress in the beginning, but it quickly breaks down and stops learning.
Note: Both of the above examples use extremely bad starting weights, along with ... | def fully_connected(self, layer_in, initial_weights, activation_fn=None):
"""
Creates a standard, fully connected layer. Its number of inputs and outputs will be
defined by the shape of `initial_weights`, and its starting weight values will be
taken directly from that same parameter. If `self.use_batch_... | batch-norm/Batch_Normalization_Lesson.ipynb | JasonNK/udacity-dlnd | mit |
This version of fully_connected is much longer than the original, but once again has extensive comments to help you understand it. Here are some important points:
It explicitly creates variables to store gamma, beta, and the population mean and variance. These were all handled for us in the previous version of the fun... | def batch_norm_test(test_training_accuracy):
"""
:param test_training_accuracy: bool
If True, perform inference with batch normalization using batch mean and variance;
if False, perform inference with batch normalization using estimated population mean and variance.
"""
weights = [np.ra... | batch-norm/Batch_Normalization_Lesson.ipynb | JasonNK/udacity-dlnd | mit |
In the following cell, we pass True for test_training_accuracy, which performs the same batch normalization that we normally perform during training. | batch_norm_test(True) | batch-norm/Batch_Normalization_Lesson.ipynb | JasonNK/udacity-dlnd | mit |
As you can see, the network guessed the same value every time! But why? Because during training, a network with batch normalization adjusts the values at each layer based on the mean and variance of that batch. The "batches" we are using for these predictions have a single input each time, so their values are the means... | batch_norm_test(False) | batch-norm/Batch_Normalization_Lesson.ipynb | JasonNK/udacity-dlnd | mit |
Now let's add a mesh dataset at a few different times so that we can see how the potentials affect the surfaces of the stars. | b.add_dataset('mesh', times=np.linspace(0,1,11), dataset='mesh01') | 2.3/tutorials/requiv.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
Relevant Parameters
The 'requiv' parameter defines the stellar surface to have a constant volume of 4./3 pi requiv^3. | print(b['requiv@component']) | 2.3/tutorials/requiv.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
Critical Potentials and System Checks
Additionally, for each detached component, there is an requiv_max Parameter which shows the critical value at which the Roche surface will overflow. Setting requiv to a larger value will fail system checks and raise a warning. | print(b['requiv_max@primary@component'])
print(b['requiv_max@primary@constraint'])
b.set_value('requiv@primary@component', 3) | 2.3/tutorials/requiv.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
At this time, if you were to call run_compute, an error would be thrown. An error isn't immediately thrown when setting requiv, however, since the overflow can be recitified by changing any of the other relevant parameters. For instance, let's change sma to be large enough to account for this value of rpole and you'l... | b.set_value('sma@binary@component', 10) | 2.3/tutorials/requiv.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
These logger warnings are handy when running phoebe interactively, but in a script its also handy to be able to check whether the system is currently computable /before/ running run_compute.
This can be done by calling run_checks which returns a boolean (whether the system passes all checks) and a message (a string des... | print(b.run_checks())
b.set_value('sma@binary@component', 5)
print(b.run_checks()) | 2.3/tutorials/requiv.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
CIFAR-10 Data Loading and Preprocessing | # Load the raw CIFAR-10 data.
cifar10_dir = 'cs231n/datasets/cifar-10-batches-py'
X_train, y_train, X_test, y_test = load_CIFAR10(cifar10_dir)
# As a sanity check, we print out the size of the training and test data.
print 'Training data shape: ', X_train.shape
print 'Training labels shape: ', y_train.shape
print 'Tes... | assignment1/svm.ipynb | srippa/nn_deep | mit |
SVM Classifier
Your code for this section will all be written inside cs231n/classifiers/linear_svm.py.
As you can see, we have prefilled the function compute_loss_naive which uses for loops to evaluate the multiclass SVM loss function. | # Evaluate the naive implementation of the loss we provided for you:
from cs231n.classifiers.linear_svm import svm_loss_naive
import time
# generate a random SVM weight matrix of small numbers
W = np.random.randn(10, 3073) * 0.0001
loss, grad = svm_loss_naive(W, X_train, y_train, 0.00001)
print 'loss: %f' % (loss, ) | assignment1/svm.ipynb | srippa/nn_deep | mit |
The grad returned from the function above is right now all zero. Derive and implement the gradient for the SVM cost function and implement it inline inside the function svm_loss_naive. You will find it helpful to interleave your new code inside the existing function.
To check that you have correctly implemented the gra... | # Once you've implemented the gradient, recompute it with the code below
# and gradient check it with the function we provided for you
# Compute the loss and its gradient at W.
loss, grad = svm_loss_naive(W, X_train, y_train, 0.0)
# Numerically compute the gradient along several randomly chosen dimensions, and
# comp... | assignment1/svm.ipynb | srippa/nn_deep | mit |
Inline Question 1:
It is possible that once in a while a dimension in the gradcheck will not match exactly. What could such a discrepancy be caused by? Is it a reason for concern? What is a simple example in one dimension where a gradient check could fail? Hint: the SVM loss function is not strictly speaking differenti... | # Next implement the function svm_loss_vectorized; for now only compute the loss;
# we will implement the gradient in a moment.
tic = time.time()
loss_naive, grad_naive = svm_loss_naive(W, X_train, y_train, 0.00001)
toc = time.time()
print 'Naive loss: %e computed in %fs' % (loss_naive, toc - tic)
from cs231n.classifi... | assignment1/svm.ipynb | srippa/nn_deep | mit |
Stochastic Gradient Descent
We now have vectorized and efficient expressions for the loss, the gradient and our gradient matches the numerical gradient. We are therefore ready to do SGD to minimize the loss. | # Now implement SGD in LinearSVM.train() function and run it with the code below
from cs231n.classifiers import LinearSVM
learning_rates = [1e-7, 5e-5]
regularization_strengths = [5e4, 1e5]
svm = LinearSVM()
tic = time.time()
loss_hist = svm.train(X_train, y_train, learning_rate=1e-5, reg=5e4,
n... | assignment1/svm.ipynb | srippa/nn_deep | mit |
Migrate evaluation
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/guide/migrate/evaluator">
<img src="https://www.tensorflow.org/images/tf_logo_32px.png" />
View on TensorFlow.org</a>
</td>
<td>
<a target="_blank" href="https://colab.rese... | import tensorflow.compat.v1 as tf1
import tensorflow as tf
import numpy as np
import tempfile
import time
import os
mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0 | site/en/guide/migrate/evaluator.ipynb | tensorflow/docs | apache-2.0 |
TensorFlow 1: Evaluating using tf.estimator.train_and_evaluate
In TensorFlow 1, you can configure a tf.estimator to evaluate the estimator using tf.estimator.train_and_evaluate.
In this example, start by defining the tf.estimator.Estimator and speciyfing training and evaluation specifications: | feature_columns = [tf1.feature_column.numeric_column("x", shape=[28, 28])]
classifier = tf1.estimator.DNNClassifier(
feature_columns=feature_columns,
hidden_units=[256, 32],
optimizer=tf1.train.AdamOptimizer(0.001),
n_classes=10,
dropout=0.2
)
train_input_fn = tf1.estimator.inputs.numpy_input_fn(
... | site/en/guide/migrate/evaluator.ipynb | tensorflow/docs | apache-2.0 |
Then, train and evaluate the model. The evaluation runs synchronously between training because it's limited as a local run in this notebook and alternates between training and evaluation. However, if the estimator is used distributedly, the evaluator will run as a dedicated evaluator task. For more information, check t... | tf1.estimator.train_and_evaluate(estimator=classifier,
train_spec=train_spec,
eval_spec=eval_spec) | site/en/guide/migrate/evaluator.ipynb | tensorflow/docs | apache-2.0 |
TensorFlow 2: Evaluating a Keras model
In TensorFlow 2, if you use the Keras Model.fit API for training, you can evaluate the model with tf.keras.utils.SidecarEvaluator. You can also visualize the evaluation metrics in TensorBoard which is not shown in this guide.
To help demonstrate this, let's first start by defining... | def create_model():
return tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(512, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10)
])
loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
model = create_mod... | site/en/guide/migrate/evaluator.ipynb | tensorflow/docs | apache-2.0 |
Then, evaluate the model using tf.keras.utils.SidecarEvaluator. In real training, it's recommended to use a separate job to conduct the evaluation to free up worker resources for training. | data = tf.data.Dataset.from_tensor_slices((x_test, y_test))
data = data.batch(64)
tf.keras.utils.SidecarEvaluator(
model=model,
data=data,
checkpoint_dir=log_dir,
max_evaluations=1
).start() | site/en/guide/migrate/evaluator.ipynb | tensorflow/docs | apache-2.0 |
$$
\pot_\cur = \sum_\prev \wcur \sigout\prev
$$
$$
\sigout\cur = \activfunc(\pot_\cur)
$$
$$
\weights = \begin{pmatrix}
\weight_{11} & \cdots & \weight_{1m} \
\vdots & \ddots & \vdots \
\weight_{n1} & \cdots & \weight_{nm}
\end{pmatrix}
$$
Divers
Le PMC peut approximer n'importe quelle fonction ... | %matplotlib inline
import nnfigs
# https://github.com/jeremiedecock/neural-network-figures.git
import nnfigs.core as nnfig
import matplotlib.pyplot as plt
fig, ax = nnfig.init_figure(size_x=8, size_y=4)
nnfig.draw_synapse(ax, (0, -6), (10, 0))
nnfig.draw_synapse(ax, (0, -2), (10, 0))
nnfig.draw_synapse(ax, (0, 2), ... | ai_ml_multilayer_perceptron_fr.ipynb | jdhp-docs/python-notebooks | mit |
Apprentissage
Mise à jours des poids
$$
\weights(\learnit + 1) = \weights(\learnit) \underbrace{- \learnrate \nabla \errfunc \left( \weights(\learnit) \right)}
$$
$- \learnrate \nabla \errfunc \left( \weights(\learnit) \right)$: descend dans la direction opposée au gradient (plus forte pente)
avec $\nabla \errfunc \lef... | fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(4, 4))
x = np.arange(10, 30, 0.1)
y = (x - 20)**2 + 2
ax.set_xlabel(r"Poids $" + STR_WEIGHTS + "$", fontsize=14)
ax.set_ylabel(r"Fonction objectif $" + STR_ERRFUNC + "$", fontsize=14)
# See http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.tick_params
ax.t... | ai_ml_multilayer_perceptron_fr.ipynb | jdhp-docs/python-notebooks | mit |
Apprentissage incrémentiel (ou partiel) (ang. incremental learning):
on ajuste les poids $\weights$ après la présentation d'un seul exemple
("ce n'est pas une véritable descente de gradient").
C'est mieux pour éviter les minimums locaux, surtout si les exemples sont
mélangés au début de chaque itération
Apprentissage d... | %matplotlib inline
import nnfigs
# https://github.com/jeremiedecock/neural-network-figures.git
import nnfigs.core as nnfig
import matplotlib.pyplot as plt
fig, ax = nnfig.init_figure(size_x=8, size_y=4)
nnfig.draw_synapse(ax, (0, -2), (10, 0))
nnfig.draw_synapse(ax, (0, 2), (10, 0), label=tex(STR_WEIGHT + "_{" + S... | ai_ml_multilayer_perceptron_fr.ipynb | jdhp-docs/python-notebooks | mit |
Plus de détail : calcul de $\errsig_\cur$
Dans l'exemple suivant on ne s'intéresse qu'aux poids $\weight_1$, $\weight_2$, $\weight_3$, $\weight_4$ et $\weight_5$ pour simplifier la demonstration. | %matplotlib inline
import nnfigs
# https://github.com/jeremiedecock/neural-network-figures.git
import nnfigs.core as nnfig
import matplotlib.pyplot as plt
fig, ax = nnfig.init_figure(size_x=8, size_y=4)
HSPACE = 6
VSPACE = 4
# Synapse #####################################
# Layer 1-2
nnfig.draw_synapse(ax, (0, V... | ai_ml_multilayer_perceptron_fr.ipynb | jdhp-docs/python-notebooks | mit |
Attention: $\weight_1$ influe $\pot_2$ et $\pot_3$ en plus de $\pot_1$ et $\pot_o$.
Calcul de $\frac{\partial \errfunc}{\partial \weight_4}$
rappel:
$$
\begin{align}
\errfunc &= \frac12 \left( \sigout_o - \sigoutdes_o \right)^2 \tag{1} \
\sigout_o &= \activfunc(\pot_o) \tag{2} \
\pot_o &= \sigout_2 \weight_4 + \si... | def sigmoid(x, _lambda=1.):
y = 1. / (1. + np.exp(-_lambda * x))
return y
%matplotlib inline
x = np.linspace(-5, 5, 300)
y1 = sigmoid(x, 1.)
y2 = sigmoid(x, 5.)
y3 = sigmoid(x, 0.5)
plt.plot(x, y1, label=r"$\lambda=1$")
plt.plot(x, y2, label=r"$\lambda=5$")
plt.plot(x, y3, label=r"$\lambda=0.5$")
plt.hline... | ai_ml_multilayer_perceptron_fr.ipynb | jdhp-docs/python-notebooks | mit |
Fonction dérivée :
$$
f'(x) = \frac{\lambda e^{-\lambda x}}{(1+e^{-\lambda x})^{2}}
$$
qui peut aussi être défini par
$$
\frac{\mathrm{d} y}{\mathrm{d} x} = \lambda y (1-y)
$$
où $y$ varie de 0 à 1. | def d_sigmoid(x, _lambda=1.):
e = np.exp(-_lambda * x)
y = _lambda * e / np.power(1 + e, 2)
return y
%matplotlib inline
x = np.linspace(-5, 5, 300)
y1 = d_sigmoid(x, 1.)
y2 = d_sigmoid(x, 5.)
y3 = d_sigmoid(x, 0.5)
plt.plot(x, y1, label=r"$\lambda=1$")
plt.plot(x, y2, label=r"$\lambda=5$")
plt.plot(x, y... | ai_ml_multilayer_perceptron_fr.ipynb | jdhp-docs/python-notebooks | mit |
Tangente hyperbolique | def tanh(x):
y = np.tanh(x)
return y
x = np.linspace(-5, 5, 300)
y = tanh(x)
plt.plot(x, y)
plt.hlines(y=0, xmin=-5, xmax=5, color='gray', linestyles='dotted')
plt.vlines(x=0, ymin=-2, ymax=2, color='gray', linestyles='dotted')
plt.title("Fonction tangente hyperbolique")
plt.axis([-5, 5, -2, 2]); | ai_ml_multilayer_perceptron_fr.ipynb | jdhp-docs/python-notebooks | mit |
Dérivée :
$$
\tanh '= \frac{1}{\cosh^{2}} = 1-\tanh^{2}
$$ | def d_tanh(x):
y = 1. - np.power(np.tanh(x), 2)
return y
x = np.linspace(-5, 5, 300)
y = d_tanh(x)
plt.plot(x, y)
plt.hlines(y=0, xmin=-5, xmax=5, color='gray', linestyles='dotted')
plt.vlines(x=0, ymin=-2, ymax=2, color='gray', linestyles='dotted')
plt.title("Fonction dérivée de la tangente hyperbolique")
... | ai_ml_multilayer_perceptron_fr.ipynb | jdhp-docs/python-notebooks | mit |
Fonction logistique
Fonctions ayant pour expression
$$
f(t) = K \frac{1}{1+ae^{-rt}}
$$
où $K$ et $r$ sont des réels positifs et $a$ un réel quelconque.
Les fonctions sigmoïdes sont un cas particulier de fonctions logistique avec $a > 0$.
Python implementation | # Define the activation function and its derivative
activation_function = tanh
d_activation_function = d_tanh
def init_weights(num_input_cells, num_output_cells, num_cell_per_hidden_layer, num_hidden_layers=1):
"""
The returned `weights` object is a list of weight matrices,
where weight matrix at index $i$... | ai_ml_multilayer_perceptron_fr.ipynb | jdhp-docs/python-notebooks | mit |
ProPublica Campaign Finance API
https://propublica.github.io/campaign-finance-api-docs/#candidates | # set key
key="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
# set base url
base_url="https://api.propublica.org/campaign-finance/v1/"
# set headers
headers = {'X-API-Key': key}
# set url parameters
cycle = "2014/"
method = "candidates/"
file_format = ".json"
# create a list of FEC IDs from http://www.fec.gov/data/DataCata... | 01_collect-data.ipynb | mathias-gibson/ps239t-final-project | mit |
ProPublica Congress API - list of all members
https://propublica.github.io/congress-api-docs/?shell#lists-of-members | # set key
key="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
# set base url
base_url="https://api.propublica.org/congress/v1/"
# set url parameters
congress = "114/" #102-114 for House, 80-114 for Senate
chamber = "senate" #house or senate
method="/members"
file_format = ".json"
#set headers
headers = {'X-API-Key': key}
#... | 01_collect-data.ipynb | mathias-gibson/ps239t-final-project | mit |
Create a grid with random elevation, set boundary conditions, and initialize components. | mg = RasterModelGrid((40, 40), 100)
z = mg.add_zeros('topographic__elevation', at='node')
z += np.random.rand(z.size)
outlet_id = int(mg.number_of_node_columns * 0.5)
mg.set_watershed_boundary_condition_outlet_id(outlet_id, z)
mg.at_node['topographic__elevation'][outlet_id] = 0
fr = FlowAccumulator(mg)
sp = Fastscape... | notebooks/tutorials/plotting/animate-landlab-output.ipynb | amandersillinois/landlab | mit |
Set model time and uplift parameters. | simulation_duration = 1e6
dt = 1000
n_timesteps = int(simulation_duration // dt) + 1
timesteps = np.linspace(0, simulation_duration, n_timesteps)
uplift_rate = 0.001
uplift_per_timestep = uplift_rate * dt | notebooks/tutorials/plotting/animate-landlab-output.ipynb | amandersillinois/landlab | mit |
Phase 1: Animate elevation change using imshow_grid
We first prepare the animation movie file. The model is run and the animation frames are captured together. | # Create a matplotlib figure for the animation.
fig, ax = plt.subplots(1, 1)
# Initiate an animation writer using the matplotlib module, `animation`.
# Set up to animate 6 frames per second (fps)
writer = animation.FFMpegWriter(fps=6)
# Setup the movie file.
writer.setup(fig, 'first_phase.mp4')
for t in timesteps:
... | notebooks/tutorials/plotting/animate-landlab-output.ipynb | amandersillinois/landlab | mit |
Finish the animation
The method, writer.finish completes the processing of the movie and saves then it. | writer.finish() | notebooks/tutorials/plotting/animate-landlab-output.ipynb | amandersillinois/landlab | mit |
This code loads the saved mp4 and presents it in a Jupyter Notebook. | HTML("""<div align="middle"> <video width="80%" controls loop>
<source src="first_phase.mp4" type="video/mp4"> </video></div>""") | notebooks/tutorials/plotting/animate-landlab-output.ipynb | amandersillinois/landlab | mit |
Phase 2: Animate multiple visualizations of elevation change over time
In the second model phase, we will create an animation similar to the one above, although with the following differences:
* The uplift rate is greater.
* The animation file format is gif.
* The figure has two subplots.
* The data of one of the subpl... | increased_uplift_per_timestep = 10 * uplift_per_timestep | notebooks/tutorials/plotting/animate-landlab-output.ipynb | amandersillinois/landlab | mit |
Run the second phase of the model
Here we layout the figure with a left and right subplot.
* The left subplot will be an animation of the grid similar to phase 1. We will recreate the image of this subplot for each animation frame.
* The right subplot will be a line plot of the mean elevation over time. We will layout ... | # Create a matplotlib figure for the animation.
fig2, axes = plt.subplots(1, 2, figsize=(9, 3))
fig2.subplots_adjust(top=0.85, bottom=0.25, wspace=0.4)
# Layout right subplot.
time = 0
line, = axes[1].plot(time, z.mean(), 'k')
axes[1].set_title('mean elevation over time')
axes[1].set_xlim([0, 1000])
axes[1].set_yli... | notebooks/tutorials/plotting/animate-landlab-output.ipynb | amandersillinois/landlab | mit |
This code loads the saved mp4 and presents it in a Jupyter Notebook. | Image(filename='second_phase.gif') | notebooks/tutorials/plotting/animate-landlab-output.ipynb | amandersillinois/landlab | mit |
Build up sensor to pvoutput model | from datetime import datetime,timedelta, time
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from data_helper_functions import *
from IPython.display import display
pd.options.display.max_columns = 999
%matplotlib inline
#iterate over datetimes:
mytime = datetime(2014, 4, 1, 13)
times = make_ti... | .ipynb_checkpoints/all-datasets-together-checkpoint.ipynb | scottlittle/solar-sensors | apache-2.0 |
...finally ready to model!
Random Forest | from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=99)
from sklearn.ensemble import RandomForestRegressor
rfr = RandomForestRegressor(oob_score = True)
rfr.fit(X_train,y_train)
y_pred = rfr.predict(X_test)
rfr.score(X_test,y_te... | .ipynb_checkpoints/all-datasets-together-checkpoint.ipynb | scottlittle/solar-sensors | apache-2.0 |
Linear model | #now do a linear model and compare:
from sklearn.linear_model import LinearRegression
lr = LinearRegression()
lr.fit(X_train,y_train)
lr.score(X_test,y_test)
sorted_mask = np.argsort(lr.coef_)
for i in zip(df_sensor.columns.values,lr.coef_[sorted_mask])[::-1]:
print i
df_sensor.ix[:,-15:-1].head() #selects photo... | .ipynb_checkpoints/all-datasets-together-checkpoint.ipynb | scottlittle/solar-sensors | apache-2.0 |
When only keeping the photometer data, random forest and linear model do pretty similar. When I added all of the sensor instruments to the fit, rfr scored 0.87 and lr scored negative!
Also, I threw away the mysterious "Research 2" sensor, that was probably just a solar panel! I asked NREL what it is, so we'll see. I... | import pandas as pd
import numpy as np
from sklearn.preprocessing import scale
from lasagne import layers
from lasagne.nonlinearities import softmax, rectify, sigmoid, linear, very_leaky_rectify, tanh
from lasagne.updates import nesterov_momentum, adagrad, momentum
from nolearn.lasagne import NeuralNet
import theano
f... | .ipynb_checkpoints/all-datasets-together-checkpoint.ipynb | scottlittle/solar-sensors | apache-2.0 |
Extra Trees! | from sklearn.ensemble import ExtraTreesRegressor
etr = ExtraTreesRegressor(oob_score=True, bootstrap=True,
n_jobs=-1, n_estimators=1000) #nj_obs uses all cores!
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=99)
etr.fit(X_train, y_train)
print etr.score... | .ipynb_checkpoints/all-datasets-together-checkpoint.ipynb | scottlittle/solar-sensors | apache-2.0 |
Save this thing and try it out on the simulated sensors! | from sklearn.externals import joblib
joblib.dump(etr, 'data/sensor-to-power-model/sensor-to-power-model.pkl')
np.savez_compressed('data/y.npz',y=y) #save y | .ipynb_checkpoints/all-datasets-together-checkpoint.ipynb | scottlittle/solar-sensors | apache-2.0 |
I have cloned the $\delta$a$\delta$i repository into '/home/claudius/Downloads/dadi' and have compiled the code. Now I need to add that directory to the PYTHONPATH variable: | sys.path.insert(0, '/home/claudius/Downloads/dadi')
sys.path | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
Now, I should be able to import $\delta$a$\delta$i | import dadi
dir(dadi)
import pylab
%matplotlib inline
x = pylab.linspace(0, 4*pylab.pi, 1000)
pylab.plot(x, pylab.sin(x), '-r')
%%sh
# this allows me to execute a shell command
ls | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
I have turned the 1D folded SFS's from realSFS into $\delta$d$\delta$i format by hand according to the description in section 3.1 of the manual. I have left out the masking line from the input file. | fs_ery = dadi.Spectrum.from_file('ERY.FOLDED.sfs.dadi_format')
fs_ery | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
$\delta$a$\delta$i is detecting that the spectrum is folded (as given in the input file), but it is also automatically masking the 0th and 18th count category. This is a not a good behaviour. | # number of segregating sites
fs_ery.data[1:].sum() | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
Single population statistics
$\pi$ | fs_ery.pi() | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
I have next added a masking line to the input file, setting it to '1' for the first position, i. e. the 0-count category. | fs_ery = dadi.Spectrum.from_file('ERY.FOLDED.sfs.dadi_format', mask_corners=False) | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
$\delta$a$\delta$i is issuing the following message when executing the above command:
WARNING:Spectrum_mod:Creating Spectrum with data_folded = True, but mask is not True for all entries which are nonsensical for a folded Spectrum. | fs_ery | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
I do not understand this warning from $\delta$a$\delta$i. The 18-count category is sensical for a folded spectrum with even sample size, so should not be masked. Anyway, I do not understand why $\delta$a$\delta$i is so reluctant to keep all positions, including the non-variable one. | fs_ery.pi() | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
The function that returns $\pi$ produces the same output with or without the last count category masked ?! I think that is because even if the last count class (966.62...) is masked, it is still included in the calculation of $\pi$. However, there is no obvious unmasking in the pi function. Strange!
There are (at least... | # Calcualting pi with the formula from Wakeley2009
n = 36 # 36 sequences sampled from 18 diploid individuals
pi_Wakeley = (sum( [i*(n-i)*fs_ery[i] for i in range(1, n/2+1)] ) * 2.0 / (n*(n-1)))/pylab.sum(fs_ery.data)
# note fs_ery.data gets the whole fs_ery list, including masked entries
pi_Wakeley | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
This is the value of $\pi_{site}$ that I calculated previously and included in the first draft of the thesis. | fs_ery.mask
fs_ery.data # gets all data, including the masked one
# Calculating pi with the formula from Gillespie:
n = 18
p = pylab.arange(0, n+1)/float(n)
p
# Calculating pi with the formula from Gillespie:
n / (n-1.0) * 2 * pylab.sum(fs_ery * p*(1-p)) | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
This is the same as the output of dadi's pi function on the same SFS. | # the sample size (n) that dadi stores in this spectrum object and uses as n in the pi function
fs_ery.sample_sizes[0]
# what is the total number of sites in the spectrum
pylab.sum(fs_ery.data) | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
So, 1.6 million sites went into the ery spectrum. | # pi per site
n / (n-1.0) * 2 * pylab.sum(fs_ery * p*(1-p)) / pylab.sum(fs_ery.data) | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
Apart from the incorrect small sample size correction by $\delta$a$\delta$i in case of folded spectra ($n$ refers to sampled sequences, not individuals), Gillespie's formula leads to a much higher estimate of $\pi_{site}$ than Wakeley's. Why is that? | # with correct small sample size correction
2 * n / (2* n-1.0) * 2 * pylab.sum(fs_ery * p*(1-p)) / pylab.sum(fs_ery.data)
# Calculating pi with the formula from Gillespie:
n = 18
p = pylab.arange(0, n+1)/float(n)
p = p/2 # with a folded spectrum, we are summing over minor allele freqs only
pi_Gillespie = 2*n / (2*n-... | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
As can be seen from the insignificant difference (must be due to numerical inaccuracies) between the $\pi_{Wakeley}$ and the $\pi_{Gillespie}$ estimates, they are equivalent with the calculation for folded spectra given above as well as the correct small sample size correction. Beware: $\delta$a$\delta$i does not handl... | fs_ery.folded | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
I think for now it would be best to import unfolded spectra from realSFS and fold them if necessary in dadi. | fs_par = dadi.Spectrum.from_file('PAR.FOLDED.sfs.dadi_format')
pylab.plot(fs_ery, 'r', label='ery')
pylab.plot(fs_par, 'g', label='par')
pylab.legend() | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
ML estimate of $\theta$ from 1D folded spectrum
I am trying to fit eq. 4.21 of Wakeley2009 to the oberseved 1D folded spectra.
$$
E[\eta_i] = \theta \frac{\frac{1}{i} + \frac{1}{n-i}}{1+\delta_{i,n-i}} \qquad 1 \le i \le \big[n/2\big]
$$
Each frequency class, $\eta_i$, provides an estimate of $\theta$. However, I would... | from scipy.optimize import least_squares
def model(theta, eta, n):
"""
theta: scaled population mutation rate parameter [scalar]
eta: the folded 1D spectrum, including 0-count cat. [list]
n: number of sampled gene copies, i. e. 2*num_ind [scalar]
returns a numpy array
"""
i = pylab.ar... | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
The counts in each frequency class should be Poisson distributed with rate equal to $E[\eta_i]$ as given above. The lowest frequency class has the highest rate and therefore also the highest variance | #?plt.ylabel
#print plt.rcParams
fs_ery[1:].max()
#?pylab
os.getcwd()
%%sh
ls | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
The following function will take the file name of a file containing the flat 1D folded frequency spectrum of one population and plots it together with the best fitting neutral expectation. | def plot_folded_sfs(filename, n, pop = ''):
# read in spectrum from file
data = open(filename, 'r')
sfs = pylab.array( data.readline().split(), dtype=float )
data.close() # should close connection to file
#return sfs
# get starting value for theta from Watterson's theta
S = sfs[1:].sum(... | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
Univariate function minimizers or 1D scalar minimisation
Since I only have one value to optimize, I can use a slightly simpler approach than used above: | from scipy.optimize import minimize_scalar
?minimize_scalar
# define cost function
def f(theta, eta, n):
"""
return sum of squared deviations between model and data
"""
return sum( (model(theta, eta, n) - eta[1:])**2 ) # see above for definition of the 'model' function | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
It would be interesting to know whether the cost function is convex or not. | theta = pylab.arange(0, fs_ery.data[1:].sum()) # specify range of theta
cost = [f(t, fs_ery.data, 36) for t in theta]
plt.plot(theta, cost, 'b-', label='ery')
plt.xlabel(r'$\theta$')
plt.ylabel('cost')
plt.title("cost function for ery")
plt.legend(loc='best')
?plt.legend | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
Within the specified bounds (the observed $\theta$, i. e. derived from the data, cannot lie outside these bounds), the cost function is convex. This is therefore an easy optimisation problem. See here for more details. | res = minimize_scalar(f, bounds = (0, fs_ery.data[1:].sum()), method = 'bounded', args = (fs_ery.data, 36))
res
# number of segregating sites
fs_par.data[1:].sum()
res = minimize_scalar(f, bounds = (0, fs_par.data[1:].sum()), method = 'bounded', args = (fs_par.data, 36))
res | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
The fitted values of $\theta$ are similar to the ones obtained above with the least_squares function. The estimates for ery deviate more than for par. | from sympy import *
x0 , x1 = symbols('x0 x1')
init_printing(use_unicode=True)
diff(0.5*(1-x0)**2 + (x1-x0**2)**2, x0)
diff(0.5*(1-x0)**2 + (x1-x0**2)**2, x1) | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
Wow! Sympy is a replacement for Mathematica. There is also Sage, which may include even more functionality. | from scipy.optimize import curve_fit | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
Curve_fit is another function that can be used for optimization. | ?curve_fit
def model(i, theta):
"""
i: indpendent variable, here minor SNP frequency classes
theta: scaled population mutation rate parameter [scalar]
returns a numpy array
"""
n = len(i)
delta = pylab.where(i == n-i, 1, 0)
return theta * 1/i + 1/(n-i) / (1 + delta)
i = pylab.aran... | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
I am not sure whether these standard errors (perr) are correct. It may be that it is assumed that errors are normally distributed, which they are not exactly in this case. They should be close to Poisson distributed (see Fu1995), which should be fairly similar to normal with such high expected values as here.
If the st... | %pwd
% ll
! cat ERY.FOLDED.sfs.dadi_format
fs_ery = dadi.Spectrum.from_file('ERY.FOLDED.sfs.dadi_format', mask_corners=False)
fs_ery
fs_ery.pop_ids = ['ery']
# get a Poisson sample from the observed spectrum
fs_ery_param_boot = fs_ery.sample()
fs_ery_param_boot
fs_ery_param_boot.data
%psource fs_ery.sample | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
There must be a way to get more than one bootstrap sample per call. | fs_ery_param_boot = pylab.array([fs_ery.sample() for i in range(100)])
# get the first 3 boostrap samples from the doubleton class
fs_ery_param_boot[:3, 2] | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
It would be good to get the 5% and 95% quantiles from the bootstrap samples of each frequency class and add those intervals to the plot of the observed frequency spectrum and the fitted neutral spectrum. This would require to find a quantile function and to find out how to add lines to a plot with matplotlib.
It would ... | # read in the flattened 2D SFS
EryPar_unfolded_2dsfs = dadi.Spectrum.from_file('EryPar.unfolded.2dsfs.dadi_format', mask_corners=True)
# check dimension
len(EryPar_unfolded_2dsfs[0,])
EryPar_unfolded_2dsfs.sample_sizes
# add population labels
EryPar_unfolded_2dsfs.pop_ids = ["ery", "par"]
EryPar_unfolded_2dsfs.pop_... | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
Marginalizing
$\delta$a$\delta$i offers a function to get the marginal spectra from multidimensional spectra. Note, that this marginalisation is nothing fancy. In R it would be taking either the rowSums or the colSums of the matrix. | # marginalise over par to get 1D SFS for ery
fs_ery = EryPar_unfolded_2dsfs.marginalize([1])
# note the argument is an array with dimensions, one can marginalise over more than one dimension at the same time,
# but that is only interesting for 3-dimensional spectra, which I don't have here
fs_ery
# marginalise over... | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
Note, that these marginalised 1D SFS's are not identical to the 1D SFS estimated directly with realSFS. This is because, for the estimation of the 2D SFS, realSFS has only taken sites that had data from at least 9 individuals in each population (see assembly.sh, lines 1423 onwards).
The SFS's of par and ery had conspic... | # plot 1D spectra for each population
pylab.plot(fs_par, 'g', label="par")
pylab.plot(fs_ery, 'r', label="ery")
pylab.legend() | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
These marginal unfolded spectra look similar in shape to the 1D folded spectra of each subspecies (see above). | fs_ery.pi() / pylab.sum(fs_ery.data)
fs_ery.data
n = 36 # 36 sequences sampled from 18 diploid individuals
pi_Wakeley = (sum( [i*(n-i)*fs_ery[i] for i in range(1, n)] ) * 2.0 / (n*(n-1)))
pi_Wakeley = pi_Wakeley / pylab.sum(fs_ery.data)
pi_Wakeley | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
$\delta$a$\delta$i's pi function seems to calculate the correct value of $\pi$ for this unfolded spectrum. However, it is worrying that $\pi$ from this marginal spectrum is about 20 times larger than the one calculated from the directly estimated 1D folded spectrum (see above the $\pi$ calculated from the folded 1D spe... | fs_par.pi() / pylab.sum(fs_par.data)
pylab.sum(fs_par.data)
pylab.sum(EryPar_unfolded_2dsfs.data) | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
<font color="red">The sum over the marginalised 1D spectra should be the same as the sum over the 2D spectrum !</font> | # from dadi's marginalise function:
fs_ery.data
sfs2d = EryPar_unfolded_2dsfs.copy()
# this should get the marginal spectrum for ery
ery_mar = [pylab.sum(sfs2d.data[i]) for i in range(0, len(sfs2d))]
ery_mar
# this should get the marginal spectrum for ery and then take the sum over it
sum([pylab.sum(sfs2d.data[i]) f... | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
So, during the marginalisation the masking of data in the fixed categories (0, 36) is the problem, producing incorrectly marginalised counts in those masked categories. This is shown in the following: | sfs2d[0]
pylab.sum(sfs2d[0])
# from dadi's marginalise function:
fs_ery.data
# dividing by the correct number of sites to get pi per site:
fs_ery.pi() / pylab.sum(sfs2d.data) | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
This is very close to the estimate of $\pi$ derived from the folded 1D spectrum of ery! (see above) | fs_par.pi() / pylab.sum(sfs2d.data) | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
This is also nicely close to the estimate of $\pi_{site}$ of par from its folded 1D spectrum.
Tajima's D | fs_ery.Watterson_theta() / pylab.sum(sfs2d.data)
fs_ery.Tajima_D()
fs_par.Tajima_D() | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
Now, I am calculating Tajima's D from the ery marginal spectrum by hand in order to check whether $\delta$a$\delta$i is doing the right thing. | n = 36
pi_Wakeley = (sum( [i*(n-i)*fs_ery.data[i] for i in range(1, n+1)] )
* 2.0 / (n*(n-1)))
#/ pylab.sum(sfs2d.data)
pi_Wakeley
# number of segregating sites
# this sums over all unmasked positions in the array
pylab.sum(fs_ery)
fs_ery.S()
S = pylab.sum(fs_ery)
theta_Watterson = S /... | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
$\delta$a$\delta$i seems to do the right thing. Note, that the estimate of Tajima's D from this marginal spectrum of ery is slightly different from the estimate derived from the folded 1D spectrum of ery (see /data3/claudius/Big_Data/ANGSD/SFS/SFS.Rmd). The folded 1D spectrum resulted in a Tajima's D estimate of $\sim$... | fs_par.Tajima_D() | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
My estimate from the folded 1D spectrum of par was -0.6142268 (see /data3/claudius/Big_Data/ANGSD/SFS/SFS.Rmd).
Multi-population statistics | EryPar_unfolded_2dsfs.S() | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
The 2D spectrum contains counts from 60k sites that are variable in par or ery or both. | EryPar_unfolded_2dsfs.Fst() | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
This estimate of $F_{ST}$ according to Weir and Cockerham (1984) is well below the estimate of $\sim$0.3 from ANGSD according to Bhatia/Hudson (2013). Note, however, that this estimate showed a positive bias of around 0.025 in 100 permutations of population labels of individuals. Taking the positive bias into account, ... | %psource EryPar_unfolded_2dsfs.scramble_pop_ids
# plot the scrambled 2D SFS
dadi.Plotting.plot_single_2d_sfs(EryPar_unfolded_2dsfs.scramble_pop_ids(), vmin=1) | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
So, this is how the 2D SFS would look like if ery and par were not genetically differentiated. | # get Fst for scrambled SFS
EryPar_unfolded_2dsfs.scramble_pop_ids().Fst() | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
The $F_{ST}$ from the scrambled SFS is much lower than the $F_{ST}$ of the observed SFS. That should mean that there is significant population structure. However, the $F_{ST}$ from the scrambled SFS is not 0. I don't know why that is. | # folding
EryPar_folded_2dsfs = EryPar_unfolded_2dsfs.fold()
EryPar_folded_2dsfs
EryPar_folded_2dsfs.mask | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
Plotting | dadi.Plotting.plot_single_2d_sfs(EryPar_unfolded_2dsfs, vmin=1)
dadi.Plotting.plot_single_2d_sfs(EryPar_folded_2dsfs, vmin=1) | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
The folded 2D spectrum is not a minor allele frequency spectrum as are the 1D folded spectra of ery and par. This is because an allele that is minor in one population can be the major allele in the other. What is not counted are the alleles that are major in both populations, i. e. the upper right corner.
For the 2D sp... | # unfolded spectrum from marginalisation of 2D unfolded spectrum
fs_ery
len(fs_ery)
fs_ery.fold() | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
Let's use the formula (1.2) from Wakeley2009 to fold the 1D spectrum manually:
$$
\eta_{i} = \frac{\zeta_{i} + \zeta_{n-i}}{1 + \delta_{i, n-i}} \qquad 1 \le i \le [n/2]
$$
$n$ is the number of gene copies sampled, i. e. haploid sample size. $[n/2]$ is the largest integer less than or equal to n/2 (to handle uneven sam... | fs_ery_folded = fs_ery.copy() # make a copy of the UNfolded spectrum
n = len(fs_ery)-1
for i in range(len(fs_ery)):
fs_ery_folded[i] += fs_ery[n-i]
if i == n/2.0:
fs_ery_folded[i] /= 2
fs_ery_folded[0:19]
isinstance(fs_ery_folded, pylab.ndarray)
mask = [True]
mask.extend([False] * 18)
mask.extend([Tr... | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
Here is how to flatten an array of arrays with list comprehension: | mask = [[True], [False] * 18, [True] * 18]
print mask
print [elem for a in mask for elem in a] | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
Set new mask for the folded spectrum: | fs_ery_folded.mask = mask
fs_ery_folded.folded = True
fs_ery_folded - fs_ery.fold() | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
The fold() function works correctly for 1D spectra, at least. How about 2D spectra?
$$
\eta_{i,j} = \frac{\zeta_{i,j} + \zeta_{n-i, m-j}}{1 + \delta_{i, n-i; j, m-j}}
\qquad 1 \le i+j \le \Big[\frac{n+m}{2}\Big]
$$ | EryPar_unfolded_2dsfs.sample_sizes
EryPar_unfolded_2dsfs._total_per_entry()
# copy the unfolded 2D spectrum for folding
import copy
sfs2d_folded = copy.deepcopy(EryPar_unfolded_2dsfs)
n = len(sfs2d_folded)-1
m = len(sfs2d_folded[0])-1
for i in range(n+1):
for j in range(m+1):
sfs2d_folded[i,j] += sfs2d_f... | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
I am going to go through every step in the fold function of dadi: | # copy the unfolded 2D spectrum for folding
import copy
sfs2d_unfolded = copy.deepcopy(EryPar_unfolded_2dsfs)
total_samples = pylab.sum(sfs2d_unfolded.sample_sizes)
total_samples
total_per_entry = dadi.Spectrum(sfs2d_unfolded._total_per_entry(), pop_ids=['ery', 'par'])
#total_per_entry.pop_ids = ['ery', 'par']
dadi.P... | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
With the variable length list of slice objects, one can generalise the reverse of arrays with any dimensions. | final_mask = pylab.logical_or(original_mask, dadi.Numerics.reverse_array(original_mask))
final_mask | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
Here, folding doesn't mask new cells. | ?pylab.where
pylab.where(matrix < 6, matrix, 0)
# this takes the part of the spectrum that is non-sensical if the derived allele is not known
# and sets the rest to 0
print pylab.where(where_folded_out, sfs2d_unfolded, 0)
# let's plot the bit of the spectrum that we are going to fold onto the rest:
dadi.Plotting.plo... | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
The transformation we have done with the upper-right diagonal 2D array above should be identical to projecting it across a vertical center line (creating an upper left triangular matrix) and then projecting it across a horizontal center line (creating the final lower left triangular matrix). Note, that this is not like... | # This shall now be added to the original unfolded 2D spectrum.
sfs2d_folded = pylab.ma.masked_array(sfs2d_unfolded.data + _reversed)
dadi.Plotting.plot_single_2d_sfs(dadi.Spectrum(sfs2d_folded), vmin=1)
sfs2d_folded.data
sfs2d_folded.data[where_folded_out] = 0
sfs2d_folded.data
dadi.Plotting.plot_single_2d_sfs(da... | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
SNP's with joint frequencies in the True cells are counted twice at the moment due to the folding and the fact that the sample sizes are even. | # this extracts the diagonal values from the UNfolded spectrum and sets the rest to 0
ambiguous = pylab.where(where_ambiguous, sfs2d_unfolded, 0)
dadi.Plotting.plot_single_2d_sfs(dadi.Spectrum(ambiguous), vmin=1) | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
These are the values in the diagonal before folding. | reversed_ambiguous = dadi.Numerics.reverse_array(ambiguous)
dadi.Plotting.plot_single_2d_sfs(dadi.Spectrum(reversed_ambiguous), vmin=1) | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
These are the values that got added to the diagonal during folding. Comparing with the previous plot, one can see for instance that the value in the (0, 36) class got added to the value in the (36, 0) class and vice versa. The two frequency classes are equivalent, since it is arbitrary which allele we call minor in the... | a = -1.0*ambiguous + 0.5*ambiguous + 0.5*reversed_ambiguous
b = -0.5*ambiguous + 0.5*reversed_ambiguous
a == b
sfs2d_folded += -0.5*ambiguous + 0.5*reversed_ambiguous
final_mask = pylab.logical_or(final_mask, where_folded_out)
final_mask
sfs2d_folded = dadi.Spectrum(sfs2d_folded, mask=final_mask, data_folded=True, p... | Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb | claudiuskerth/PhDthesis | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.