markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Comments:<br><br>
There are 4208 mushroom instances identified as etable and 3916 instances as poisonous. The distribution between my two target classes is approximately the same, which is good - we won't have a selection bias tending towards one category just due to its overrepresentation in the dataset. <br>
I will e... | tbl = pd.crosstab(index=df['classif'], columns=df['cap_colour'])
print(tbl)
#Create stacked chart and normal box chart to display the distribution of different cap colors by classification
fig, axes = plt.subplots(nrows=1, ncols=2)
tbl.plot(kind="bar",stacked=False, ax=axes[0], color=['#f0dc82', '#D2691E', '#990000',
... | examples/dulybina/1_exploratory_analysis.ipynb | georgetown-analytics/machine-learning | mit |
Comment:
Suprisingly, the cap color is not the great predictor of etability of a mushroom. Different colors have varied distributions among both classes. Just a few species with red and yellow caps tend to be poisonous more often, while brown, gray and white caps are more prevailant among etable mushrooms. However, one... | gills = pd.crosstab(index=df['classif'], columns=df["gill_color"])
print(gills)
#gill-color: black=k,brown=n,buff=b,chocolate=h,gray=g,green=r,orange=o,pink=p,purple=u,red=e, white=w,yellow=y
s1 = pd.crosstab(index=df['classif'], columns = df['gill_size'])
print(s1) | examples/dulybina/1_exploratory_analysis.ipynb | georgetown-analytics/machine-learning | mit |
<table cellpadding="0" cellspacing="0" border="0" width = 100%>
<tbody>
<tr>
<td style="text-align:right; width:150px" colspan ="1"><p style="text-align:left"><b>Comments:</b><br><br>Gill sizes seem to be equally distributed among poisonous mushrooms, although we can see that the majority of mushrooms that are etab... | fig, axes = plt.subplots(nrows=1, ncols=2)
plt.tight_layout()
gills.plot(kind="bar",stacked=True, ax=axes[1], color=['#f0dc82','#990000','#696969','#4E2E28','#000000',
'#49311c','#FFA500','#ff69b4','#007f00','#800080',
... | examples/dulybina/1_exploratory_analysis.ipynb | georgetown-analytics/machine-learning | mit |
Comments:<br>
Odor seems to be very important in differentiating between posonous and not-poisonous mushrooms in our dataset. If the mushroom smells like almond or like anise - it is indeed etable. If there is no smell at all - the mushroom will be most likely etable, but you cannot be sure: out of all mushrooms that d... | veils = pd.crosstab(index=df['classif'], columns=df["veil_color"])
print(veils)
spores = pd.crosstab(index=df['classif'], columns=df["spore_print_color"])
print(spores)
fig, axes = plt.subplots(nrows=1, ncols=2)
veils.plot(kind="bar",stacked=True, ax=axes[0], color=['#49311c','#ffa500','#ffffff','#ffff00']);
axes[0].l... | examples/dulybina/1_exploratory_analysis.ipynb | georgetown-analytics/machine-learning | mit |
<table cellpadding="0" cellspacing="0" border="0" width = 100%>
<tbody>
<tr>
<td style="text-align:right; width:150px" colspan ="1"><p style="text-align:left"><b>Comments:</b><br><br>Only etable mushrooms have veils of brown or orange color - you can safely eat those. However, both etable and poisonous mushrooms ha... | stalk_above = pd.crosstab(index=df['classif'], columns=df["stalk_color_above_ring"])
print(stalk_above)
stalk_below = pd.crosstab(index=df['classif'], columns=df["stalk_color_below_ring"])
print(stalk_below) | examples/dulybina/1_exploratory_analysis.ipynb | georgetown-analytics/machine-learning | mit |
Comemnts:<br>
Stalk colors above and below vary vetween etable and poisonous mushrooms, however, there are rules one can follow to certainly distinguish them using stalk color features. If the stalk color (both above and below the ring) is buff, yellow or cinnamon in color - the mushrom has to be poisonous. All mushroo... | fig, axes = plt.subplots(nrows=1, ncols=2)
stalk_above.plot(kind="bar",stacked=True, ax=axes[0], color=['#f0dc82','#D2691E', '#990000','#696969',
'#49311c','#ffa500','#ff69b4','#ffffff','#ffff00']);
axes[0].legend_.remove()
stalk_below.plot(kind="bar",stacke... | examples/dulybina/1_exploratory_analysis.ipynb | georgetown-analytics/machine-learning | mit |
<table cellpadding="0" cellspacing="0" border="0" width = 100%>
<tbody>
<tr>
<td style="text-align:right; width:150px" colspan ="1"><p style="text-align:left"><b>Comments:</b><br><br>Well, regarding habitat feature, the "good" news ia that no poisonous mushrooms grow in waste. Also, a large proportion of poisonous spec... | ring = pd.crosstab(index=df['classif'], columns=df["ring_type"])
print(ring)
r = ring.plot(kind='bar', cmap=plt.cm.RdYlGn)
r.set_xlabel('classification')
r.set_ylabel('count')
r.set_title("By Ring Type")
r.legend(['Evanescent','Flaring','Large','None','Pendant'])
plt.show() | examples/dulybina/1_exploratory_analysis.ipynb | georgetown-analytics/machine-learning | mit |
<table cellpadding="0" cellspacing="0" border="0" width = 100%>
<tbody>
<tr>
<td style="text-align:right; width:150px" colspan ="1"><p style="text-align:left"><b>Comments:</b><br><br>There are less different ring types observed in the sample dataset comparing with metadata information. However, this feature might be im... | #gill-spacing: close=c,crowded=w,distant=d
gsp = pd.crosstab(index=df['classif'], columns=df["gill_space"])
print(gsp)
r = gsp.plot(kind='bar', cmap=plt.cm.RdYlGn)
r.set_xlabel('classification')
r.set_ylabel('count')
r.set_title("By Gill Spacing")
r.legend(['Close','Crowded'])
plt.show() | examples/dulybina/1_exploratory_analysis.ipynb | georgetown-analytics/machine-learning | mit |
<table cellpadding="0" cellspacing="0" border="0" width = 100%>
<tbody>
<tr>
<td style="text-align:right; width:150px" colspan ="1"><p style="text-align:left"><b>Comments:</b><br><br>Metadata defined 3 categories but we have only 2 types of gill spacing observed: close and distant. This feature might be important as th... | df['population'].replace(['a','c','n','s','v','y'],['Abundant','Clustered','Numerous',
'Scattered','Several','Solitary'],inplace=True)
df['habitat'].replace(['d','g','l','m','p','u','w'],['Woods','Grasses','Leaves',
... | examples/dulybina/1_exploratory_analysis.ipynb | georgetown-analytics/machine-learning | mit |
Missing values in stalk_root feature
There are 2480 missing values under the feature stalk_root. I will drop the feature from the beginning to avoid droping samples associated with those missing values.
Alternatively, it is possible to keep the feature and drop all observations where the value is missing:
df = df.drop(... | df['stalk_root'].value_counts() | examples/dulybina/1_exploratory_analysis.ipynb | georgetown-analytics/machine-learning | mit |
The crosstab display doesn't demonstrate a type a stalk_root that would be prevailent in poisonous mushrooms. If it was the case, I would assign all the missing values with that stalk root type to avoid risks of classifying poisonous mushroom as etable based on tha feature. Another option could be to assign the values ... | sr = pd.crosstab(index=df['classif'], columns=df["stalk_root"])
print(sr)
df.drop('stalk_root', axis=1, inplace=True) | examples/dulybina/1_exploratory_analysis.ipynb | georgetown-analytics/machine-learning | mit |
Save data to csv | df.to_csv('/Users/dariaulybina/Desktop/georgetown/ml_practice/data/data.csv') | examples/dulybina/1_exploratory_analysis.ipynb | georgetown-analytics/machine-learning | mit |
Implement Preprocessing Functions
The first thing to do to any dataset is preprocessing. Implement the following preprocessing functions below:
- Lookup Table
- Tokenize Punctuation
Lookup Table
To create a word embedding, you first need to transform the words to ids. In this function, create two dictionaries:
- Dict... | import numpy as np
import problem_unittests as tests
from collections import Counter
def create_lookup_tables(text):
"""
Create lookup tables for vocabulary
:param text: The text of tv scripts split into words
:return: A tuple of dicts (vocab_to_int, int_to_vocab)
"""
# TODO: Implement Function
... | tv-script-generation/dlnd_tv_script_generation.ipynb | gaoshuming/udacity | mit |
Tokenize Punctuation
We'll be splitting the script into a word array using spaces as delimiters. However, punctuations like periods and exclamation marks make it hard for the neural network to distinguish between the word "bye" and "bye!".
Implement the function token_lookup to return a dict that will be used to token... | def token_lookup():
"""
Generate a dict to turn punctuation into a token.
:return: Tokenize dictionary where the key is the punctuation and the value is the token
"""
# TODO: Implement Function
return {'.':'||Period||',
',':'||Comma||',
'"':'||QuotationMark||',
... | tv-script-generation/dlnd_tv_script_generation.ipynb | gaoshuming/udacity | mit |
Input
Implement the get_inputs() function to create TF Placeholders for the Neural Network. It should create the following placeholders:
- Input text placeholder named "input" using the TF Placeholder name parameter.
- Targets placeholder
- Learning Rate placeholder
Return the placeholders in the following tuple (Inpu... | import tensorflow as tf
def get_inputs():
"""
Create TF Placeholders for input, targets, and learning rate.
:return: Tuple (input, targets, learning rate)
"""
# TODO: Implement Function
inputs = tf.placeholder(dtype=tf.int32,shape=[None,None],name='input')
target = tf.placeholder(dtype=tf.in... | tv-script-generation/dlnd_tv_script_generation.ipynb | gaoshuming/udacity | mit |
Build RNN Cell and Initialize
Stack one or more BasicLSTMCells in a MultiRNNCell.
- The Rnn size should be set using rnn_size
- Initalize Cell State using the MultiRNNCell's zero_state() function
- Apply the name "initial_state" to the initial state using tf.identity()
Return the cell and initial state in the follo... | def get_init_cell(batch_size, rnn_size):
"""
Create an RNN Cell and initialize it.
:param batch_size: Size of batches
:param rnn_size: Size of RNNs
:return: Tuple (cell, initialize state)
"""
# TODO: Implement Function
cell = tf.contrib.rnn.MultiRNNCell([tf.contrib.rnn.BasicLSTMCell(rnn_... | tv-script-generation/dlnd_tv_script_generation.ipynb | gaoshuming/udacity | mit |
Build RNN
You created a RNN Cell in the get_init_cell() function. Time to use the cell to create a RNN.
- Build the RNN using the tf.nn.dynamic_rnn()
- Apply the name "final_state" to the final state using tf.identity()
Return the outputs and final_state state in the following tuple (Outputs, FinalState) | def build_rnn(cell, inputs):
"""
Create a RNN using a RNN Cell
:param cell: RNN Cell
:param inputs: Input text data
:return: Tuple (Outputs, Final State)
"""
# TODO: Implement Function
output, final_state = tf.nn.dynamic_rnn(cell, inputs, dtype=tf.float32)
final_state = tf.identity(f... | tv-script-generation/dlnd_tv_script_generation.ipynb | gaoshuming/udacity | mit |
Batches
Implement get_batches to create batches of input and targets using int_text. The batches should be a Numpy array with the shape (number of batches, 2, batch size, sequence length). Each batch contains two elements:
- The first element is a single batch of input with the shape [batch size, sequence length]
- Th... | def get_batches(int_text, batch_size, seq_length):
"""
Return batches of input and target
:param int_text: Text with the words replaced by their ids
:param batch_size: The size of batch
:param seq_length: The length of sequence
:return: Batches as a Numpy array
"""
# TODO: Implement Func... | tv-script-generation/dlnd_tv_script_generation.ipynb | gaoshuming/udacity | mit |
Neural Network Training
Hyperparameters
Tune the following parameters:
Set num_epochs to the number of epochs.
Set batch_size to the batch size.
Set rnn_size to the size of the RNNs.
Set embed_dim to the size of the embedding.
Set seq_length to the length of sequence.
Set learning_rate to the learning rate.
Set show_e... | # Number of Epochs
num_epochs = 100
# Batch Size
batch_size = 128
# RNN Size
rnn_size = 256
# Embedding Dimension Size
embed_dim = 200
# Sequence Length
seq_length = 25
# Learning Rate
learning_rate = 0.02
# Show stats for every n number of batches
show_every_n_batches = 50
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT ... | tv-script-generation/dlnd_tv_script_generation.ipynb | gaoshuming/udacity | mit |
Choose Word
Implement the pick_word() function to select the next word using probabilities. | def pick_word(probabilities, int_to_vocab):
"""
Pick the next word in the generated text
:param probabilities: Probabilites of the next word
:param int_to_vocab: Dictionary of word ids as the keys and words as the values
:return: String of the predicted word
"""
# TODO: Implement Function
... | tv-script-generation/dlnd_tv_script_generation.ipynb | gaoshuming/udacity | mit |
Remember that the form of data we will use always is
with the "response" as a plain array
[1,1,0,0,0,1,0,1,0....].
Your turn:
Create a scatter plot of Weight vs. Height
Color the points differently by Gender | #your turn
plt.scatter(dflog.Weight, dflog.Height, c=[cmap_bold.colors[i] for i in dflog.Gender=="Male"], alpha=0.1); | logistic_regression/Mini_Project_Logistic_Regression.ipynb | farfan92/SpringBoard- | mit |
In the Linear Regression Mini Project, the last (extra credit) exercise was to write a K-Fold cross-validation. Feel free to use that code below, or just use the cv_score function we've provided. | from sklearn.model_selection import KFold
from sklearn.metrics import accuracy_score
def cv_score(clf, x, y, score_func=accuracy_score):
result = 0
nfold = 5
kf = KFold(shuffle =False, n_splits= nfold)
for train, test in kf.split(x):# split data into train/test groups, 5 times
clf.fit(x[train],... | logistic_regression/Mini_Project_Logistic_Regression.ipynb | farfan92/SpringBoard- | mit |
While this looks like a pretty great model, we would like to ensure two things:
We have found the best model (in terms of model parameters).
The model is highly likely to generalize i.e. perform well on unseen data.
For tuning your model, you will use a mix of cross-validation and grid search. In Logistic Regression,... | #the grid of parameters to search over
Cs = [0.001, 0.01, 0.1, 1, 10, 100]
score_array = []
#your turn
for reg_param in Cs:
clf = LogisticRegression(C=reg_param)
score = cv_score(clf,Xlr,ylr)
score_array.append(score)
#score2 =
max_score = max(score_array)
max_idx = score_array.index(max(score_array))
... | logistic_regression/Mini_Project_Logistic_Regression.ipynb | farfan92/SpringBoard- | mit |
Things to think about
You may notice that this particular value of C may or may not do as well as simply running the default model on a random train-test split.
Do you think that's a problem?
Why do we need to do this whole cross-validation and grid search stuff anyway?
Not neccesarily. The goal in cross validation... | #your turn
from sklearn.model_selection import GridSearchCV
clf2 = LogisticRegression()
parameters = {"C": [0.0001, 0.001, 0.01, 0.1, 1, 10, 100]}
grid_fit = GridSearchCV(clf2,param_grid=parameters,cv=5, scoring="accuracy")
grid_fit.fit(Xlr,ylr)
print("Best parameter is: ", grid_fit.best_params_)
clf2 = LogisticRegress... | logistic_regression/Mini_Project_Logistic_Regression.ipynb | farfan92/SpringBoard- | mit |
We do not obtain the same value of $C$. Here we get that $C=0.001$ is the highest scoring choice. This time we find that the choices from C=1 and upwards score the exact same.
Using the gridSearchCV tool, we now get a higher accuracy score using $C=0.001$ at $0.9256$, instead of our previous value of $0.9252$ for $C=0.... | def cv_optimize(clf, parameters, Xtrain, ytrain, n_folds=5):
gs = GridSearchCV(clf, param_grid=parameters, cv=n_folds)
gs.fit(Xtrain, ytrain)
print "BEST PARAMS", gs.best_params_
best = gs.best_estimator_
return best | logistic_regression/Mini_Project_Logistic_Regression.ipynb | farfan92/SpringBoard- | mit |
We then use this best classifier to fit the entire training set. This is done inside the do_classify function which takes a dataframe indf as input. It takes the columns in the list featurenames as the features used to train the classifier. The column targetname sets the target. The classification is done by setting th... | from sklearn.cross_validation import train_test_split
def do_classify(clf, parameters, indf, featurenames, targetname, target1val, standardize=False, train_size=0.8):
subdf=indf[featurenames]
if standardize:
subdfstd=(subdf - subdf.mean())/subdf.std()
else:
subdfstd=subdf
X=subdfstd.valu... | logistic_regression/Mini_Project_Logistic_Regression.ipynb | farfan92/SpringBoard- | mit |
Start with initializing a euclidean N-dimensional algebra and assign our pseudoscalar to $I$, pretty standard. | from clifford import Cl
from math import *
l,b = Cl(3) # returns (layout,blades). you can change dimesion here
I = l.pseudoScalar | docs/tutorials/MatrixRepresentationsOfGeometricFunctions.ipynb | arsenovic/clifford | bsd-3-clause |
Anti-symmetric
This is so easy,
$$x \rightarrow x\cdot B$$ | B = l.randomIntMV()(2) # we use randIntMV because its easier to read
f = lambda x:x|B
func2Mat(f,I=I) | docs/tutorials/MatrixRepresentationsOfGeometricFunctions.ipynb | arsenovic/clifford | bsd-3-clause |
Whats the B? you can read its values straight off the matrix. | B | docs/tutorials/MatrixRepresentationsOfGeometricFunctions.ipynb | arsenovic/clifford | bsd-3-clause |
Diagonal ( Directional Scaling)
A bit awkward this one, but its made by projection onto each basis vector, then scaling the component by some amount.
$$ x \rightarrow \sum{\lambda_i (x\cdot e_i) e_i} $$ |
ls = range(1,len(I.basis())+1) # some dilation values (eigenvalues)
A = I.basis()
d = lambda x: sum([(x|a)/a*l for a,l in zip(A,ls)])
func2Mat(d,I=I) | docs/tutorials/MatrixRepresentationsOfGeometricFunctions.ipynb | arsenovic/clifford | bsd-3-clause |
Orthgonal, Rotation
$$ x\rightarrow Rx\tilde{R}$$
where
$$R=e^{B/2}$$ | B = l.randomMV()(2)
R = e**(B/2)
r = lambda x: R*x*~R
func2Mat(r,I=I) | docs/tutorials/MatrixRepresentationsOfGeometricFunctions.ipynb | arsenovic/clifford | bsd-3-clause |
The inverse of this is ,
$$ x\rightarrow \tilde{R}xR $$ | rinv = lambda x: ~R*x*R # the inverse rotation
func2Mat(rinv,I=I) | docs/tutorials/MatrixRepresentationsOfGeometricFunctions.ipynb | arsenovic/clifford | bsd-3-clause |
Orthogonal, Reflection
$$ x \rightarrow -axa^{-1} $$ | a = l.randomIntMV()(1)
n = lambda x: -a*x/a
func2Mat(n,I=I)
a | docs/tutorials/MatrixRepresentationsOfGeometricFunctions.ipynb | arsenovic/clifford | bsd-3-clause |
Notice the determinant for reflection is -1, and for rotation is +1. | from numpy.linalg import det
det(func2Mat(n,I=I)), det(func2Mat(r,I=I)) | docs/tutorials/MatrixRepresentationsOfGeometricFunctions.ipynb | arsenovic/clifford | bsd-3-clause |
Symmetric
This can be built up from the functions we just defined ie Rotation*Dilation/Rotation
$$ x \rightarrow r(d(r^{-1}(x)) $$
which if you write it out, looks kind of dumb
$$ x \rightarrow R[\sum{\lambda_i (\tilde{R}x R\cdot e_i) e_i]R} $$
So, the antisymmetric matrix is interpreted as a set dilations about a som... |
g = lambda x: r(d(rinv(x)))
func2Mat(g,I=I) | docs/tutorials/MatrixRepresentationsOfGeometricFunctions.ipynb | arsenovic/clifford | bsd-3-clause |
Eigen stuffs
By definition the eigen-stuff is the invariants of the transformation, sometimes this is a vector, and other times it is a plane.
Rotation
The eigen blades of a rotation are really the axis and plane of rotation. | from numpy.linalg import eig
vals, vecs = eig(func2Mat(r,I=I))
np.round(vecs,3) | docs/tutorials/MatrixRepresentationsOfGeometricFunctions.ipynb | arsenovic/clifford | bsd-3-clause |
If you checkout the real column, and compare this to the bivector which generated this rotation (aka the generator), after its been normalized | B/(abs(B))
B
vals
cos(abs(B)), sin(abs(B)) | docs/tutorials/MatrixRepresentationsOfGeometricFunctions.ipynb | arsenovic/clifford | bsd-3-clause |
Symmetric
For the symmetric matrix, the invariant thing the orthonormal frame along which the dilations take place | vals, vecs = eig(func2Mat(g,I=I))
np.round(vecs,5).T | docs/tutorials/MatrixRepresentationsOfGeometricFunctions.ipynb | arsenovic/clifford | bsd-3-clause |
This is easily found by using the rotation part of the symmetric operator, | [R*a*~R for a in I.basis()] | docs/tutorials/MatrixRepresentationsOfGeometricFunctions.ipynb | arsenovic/clifford | bsd-3-clause |
Primitive Visualization in 2D | from pylab import linspace, plot,axis,legend
def plot_ps(ps,**kw):
x = [p[e1] for p in ps]
y = [p[e2] for p in ps]
plot(x,y, marker='o',ls='',**kw)
l,b = Cl(2)
locals().update(b)
I = l.pseudoScalar
## define function of interest
B = l.randomMV()(2)
R = e**(B/2)
f = lambda x: R*x*~R
## loop though... | docs/tutorials/MatrixRepresentationsOfGeometricFunctions.ipynb | arsenovic/clifford | bsd-3-clause |
Simple UAV drag curves
We are going to compute induced and parasite drag (in a very basic way) as an example to introduce scripting.
\begin{align}
q&= \frac{1}{2} \rho V_\infty^2 \
D_i &= \frac{L^2}{q \pi b^2 e} \
D_p &= {C_D}_p q S
\end{align}
The first few lines make some imports. The first line is only for Jupyter ... | from math import pi
# all in standard English units
# atmosphere
rho = 0.0024 # air density
# geometry
b = 8.0 # wing span
chord = 1.0
# mass properties
W = 2.4 # total weight of aircraft
# other parameters
e = 0.9 # Oswald efficiency factor
CDp = 0.02 # could compute but just input for simplicity
# an array... | onboarding/PythonPrimer.ipynb | BYUFLOWLab/BYUFLOWLab.github.io | mit |
Try it yourself. Let's do the same calculation, but with reusable functions. In Python functions are easy to define. A simple example is below (note that unlike Matlab, you can have as many functions as you want in a file.) | def func(x, y):
add = x + y
mult = x * y
return add, mult
a, m = func(1.0, 3.0)
print 'a =', a, 'm =', m
a, m = func(2.0, 7.0)
print 'a =', a, 'm =', m
def induced_drag():
pass
def parasite_drag():
pass
# atmosphere
rho = 0.0024 # air density
# geometry
b = 8.0 # wing span
chord = ... | onboarding/PythonPrimer.ipynb | BYUFLOWLab/BYUFLOWLab.github.io | mit |
Finally, let's do it once more, but in an object-oriented style. |
class UAV(object):
def __init__(self, b, chord, W, rho):
self.b = b
self.S = b*chord
self.L = W
self.rho = rho
def induced_drag(self, V, e):
q = 0.5*self.rho*V**2
Di = self.L**2/(q*pi*self.b**2*e)
return Di
def parasite_drag(self, V, CD... | onboarding/PythonPrimer.ipynb | BYUFLOWLab/BYUFLOWLab.github.io | mit |
Wrapping Fortran/C
This next example is going to solve Laplace's equation on a grid. First, we will do it in pure Python, then we will rewrite a portion of the code in Fortran and call it in Python for improved speed. Recall Laplace's equation:
$$ \nabla^2 \phi = 0 $$
where $\phi is some scalar. For a regular rectan... | from math import fabs
def laplace_grid_python(n, top, bottom, left, right, tol, iter_max):
# initialize
phi = np.zeros((n+1, n+1))
iters = 0 # number of iterations
err_max = 1e6 # maximum error in grid (start at some arbitrary number just to enter loop)
# set boundary conditions
... | onboarding/PythonPrimer.ipynb | BYUFLOWLab/BYUFLOWLab.github.io | mit |
In our implementation below we are adding the IPython flag %%timeit at the top. This will run the whole block some number of times and report the best time back.
Adding some blank space below just to visually separate the answer.
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>... | %%timeit
from math import fabs
def laplace_grid_python(n, top, bottom, left, right, tol, iter_max):
# initialize
phi = np.zeros((n+1, n+1))
iters = 0 # number of iterations
err_max = 1e6 # maximum error in grid (start at some arbitrary number just to enter loop)
# set boundary conditions
... | onboarding/PythonPrimer.ipynb | BYUFLOWLab/BYUFLOWLab.github.io | mit |
This takes a while. Let's move the double for loop computation to Fortran. I've supplied a file called laplace.f90 where I've done this for you. We just need to build this as a shared library so we can call it from Python. Open a terminal (you can do this in try.jupyter.org as well). We will compile the fortran co... | %%timeit
from _laplace import laplacegridfortran
n = 50
top = 0.0
bottom = 1.0
left = 1.0
right = 0.0
tol = 1e-5
iter_max = 10000
phi, err_max, iters = laplacegridfortran(n, top, bottom, left, right, tol, iter_max)
# plot it
x = np.linspace(0, 1, n+1)
y = np.linspace(0, 1, n+1)
[X, Y] = np.meshgrid(x, y)
plt.figure... | onboarding/PythonPrimer.ipynb | BYUFLOWLab/BYUFLOWLab.github.io | mit |
Loading mesh. This mesh is rotated, so we use default values. If your mesh is rotated don't forget to use abg parameter. | meshpath ='/mnt/lustre01/work/ab0995/a270088/data/core_mesh/'
mesh = pf.load_mesh(meshpath, usepickle=False, usejoblib=True) | notebooks/big_data_processing.ipynb | FESOM/pyfesom | mit |
Open multiple files at once. Please have a look at this page to understand what chinks are for. | data = xr.open_mfdataset('/work/ab0995/a270067/fesom_echam/core/cpl_output_02/fesom.200?.oce.mean.nc',
chunks={'time': 12}) | notebooks/big_data_processing.ipynb | FESOM/pyfesom | mit |
Now you have a Dataset that have all the data in. | data | notebooks/big_data_processing.ipynb | FESOM/pyfesom | mit |
You can see that in this version of fesom output there is a bug with shifter time stemps (times starts from '2000-02-01'). We are giong to fix it. Create time stamps with pandas: | dates = pd.date_range('2000','2010', freq='M', )
dates | notebooks/big_data_processing.ipynb | FESOM/pyfesom | mit |
Note, that you have to put one year more in this case since the right boundary is not included. Now replace time stamps in the data by the right ones: | data.time.data = dates
data | notebooks/big_data_processing.ipynb | FESOM/pyfesom | mit |
Good, we now have right time stamps and can work with time.
Time mean
The time mean over the whole time period is simple: | temp_mean = data.temp.mean(dim='time') | notebooks/big_data_processing.ipynb | FESOM/pyfesom | mit |
Here we select temp variable and apply mean to it. You also have to specify the dimention (dim) that you want to make a mean over. You probably noticed that "computation" was performed very quickly. This is because there were now computation at all, just preparation for it. To actually do computation do: | temp_mean = temp_mean.compute()
temp_mean | notebooks/big_data_processing.ipynb | FESOM/pyfesom | mit |
Mean over time slice
One can use slices to select data over some time period: | data.temp.sel(time=slice('2000-01-01', '2003-12-31')).time | notebooks/big_data_processing.ipynb | FESOM/pyfesom | mit |
Mean over this slice will look like this: | temp_mean_3years = data.temp.sel(time=slice('2000-01-01', '2003-12-31')).mean(dim='time')
temp_mean_3years = temp_mean_3years.compute() | notebooks/big_data_processing.ipynb | FESOM/pyfesom | mit |
Mean over specific month
!!! PLESE READ THIS TO GET MORE INFORMATION !!!
Our data are monthly: | data.time[:14] | notebooks/big_data_processing.ipynb | FESOM/pyfesom | mit |
The sel allows to provide explicit time steps, so if we just select only March values: | data.time[2::12] | notebooks/big_data_processing.ipynb | FESOM/pyfesom | mit |
we can provide this values directly to sel. We also make a mean over the selected time and do the computation: | temp_march_mean = data.temp.sel(time=data.time[2::12]).mean(dim='time')
temp_march_mean = temp_march_mean.compute() | notebooks/big_data_processing.ipynb | FESOM/pyfesom | mit |
The xarray have more explicit syntax to select months (returns array that show which record in your array corespond to each month): | data['time.month'] | notebooks/big_data_processing.ipynb | FESOM/pyfesom | mit |
Using this sysntax you can easily select March: | data.temp[data['time.month']==3] | notebooks/big_data_processing.ipynb | FESOM/pyfesom | mit |
And make a mean over this month: | temp_march_mean = data.temp[data['time.month']==3].mean(dim='time')
temp_march_mean = temp_march_mean.compute() | notebooks/big_data_processing.ipynb | FESOM/pyfesom | mit |
Please have a look at this page to see what "datetime components" are supported. At the time of this writing the list contains: “year”, “month”, “day”, “hour”, “minute”, “second”, “dayofyear”, “week”, “dayofweek”, “weekday” and “quarter”. Additional xarray component is season. You can select winter temperature values ... | temp_DJF_mean = data.temp[data['time.season']=='DJF'].mean(dim='time')
temp_DJF_mean = temp_DJF_mean.compute() | notebooks/big_data_processing.ipynb | FESOM/pyfesom | mit |
Resampling
Once again, please read this page to get more information. If we would like to resample our data, making yearly means, the way to do it is: | yearly_data = data.resample(time='1A').mean(dim='time')
yearly_data
yearly_data = yearly_data.compute() | notebooks/big_data_processing.ipynb | FESOM/pyfesom | mit |
Migrating tf.summary usage to TF 2.x
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/tensorboard/migrate"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a>
</td>
<td>
<a target="_blank" href="https://colab.... | import tensorflow as tf | site/en-snapshot/tensorboard/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
TensorFlow 2.x includes significant changes to the tf.summary API used to write summary data for visualization in TensorBoard.
What's changed
It's useful to think of the tf.summary API as two sub-APIs:
A set of ops for recording individual summaries - summary.scalar(), summary.histogram(), summary.image(), summary.aud... | writer = tf.summary.create_file_writer("/tmp/mylogs/eager")
with writer.as_default():
for step in range(100):
# other model code would go here
tf.summary.scalar("my_metric", 0.5, step=step)
writer.flush()
ls /tmp/mylogs/eager | site/en-snapshot/tensorboard/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
Example usage with tf.function graph execution: | writer = tf.summary.create_file_writer("/tmp/mylogs/tf_function")
@tf.function
def my_func(step):
with writer.as_default():
# other model code would go here
tf.summary.scalar("my_metric", 0.5, step=step)
for step in tf.range(100, dtype=tf.int64):
my_func(step)
writer.flush()
ls /tmp/mylogs/tf_function | site/en-snapshot/tensorboard/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
Example usage with legacy TF 1.x graph execution: | g = tf.compat.v1.Graph()
with g.as_default():
step = tf.Variable(0, dtype=tf.int64)
step_update = step.assign_add(1)
writer = tf.summary.create_file_writer("/tmp/mylogs/session")
with writer.as_default():
tf.summary.scalar("my_metric", 0.5, step=step)
all_summary_ops = tf.compat.v1.summary.all_v2_summary_... | site/en-snapshot/tensorboard/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
Converting your code
Converting existing tf.summary usage to the TF 2.x API cannot be reliably automated, so the tf_upgrade_v2 script just rewrites it all to tf.compat.v1.summary and will not enable the TF 2.x behaviors automatically.
Partial Migration
To make migration to TF 2.x easier for users of model code that sti... | # Enable eager execution.
tf.compat.v1.enable_v2_behavior()
# A default TF 2.x summary writer is available.
writer = tf.summary.create_file_writer("/tmp/mylogs/enable_v2_in_v1")
# A step is set for the writer.
with writer.as_default(step=0):
# Below invokes `tf.summary.scalar`, and the return value is an empty bytes... | site/en-snapshot/tensorboard/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
Set up
Set the number of points desired for the averaging and length of spectra. Also set up seaborn formats. | # Processings parameters
spfreq=50e3 # Bandwidth
nspec=256 # length of spectrum
rep1=10000 # number of pulses
L=24. # Length of pulse in standard processings
pulse=sp.ones(int(L)) # Pulse for standard processing
pulse_pergram=sp.ones(nspec) # For periodogram
Nrg=128 # Number of Range gates for data
# Parameters for sp... | ExampleNotebooks/SpecEstimator.ipynb | jswoboda/SimISR | mit |
IS Spectra
This will create an example ISR spectra that will be used. | # 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... | ExampleNotebooks/SpecEstimator.ipynb | jswoboda/SimISR | mit |
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. | 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,... | ExampleNotebooks/SpecEstimator.ipynb | jswoboda/SimISR | mit |
Shaped Noise
A set of shaped noise is created using the IS spectrum formed earlier. Using linear pridictive coding to apply the spectrum to the noise through the MakePulseDataRepLPC function. This is similar to the method used by vocoders to encode human speech. To show the effect of the LPC coloring a periodogram esit... | Xdata = MakePulseDataRepLPC(pulse_pergram,cur_spec,30,rep1,numtype = sp.complex128)
Xfftd=sp.power(nspec,-.5)*scfft.fftshift(scfft.fft(Xdata,axis=-1),axes=-1)
Xperiodd=sp.power(Xfftd.real,2).mean(0) +sp.power(Xfftd.imag,2).mean(0)
tau3,acfperiodd=spect2acf(f,Xperiodd*nspec)
fig3,ax3 = plt.subplots(1,2,sharey=False, f... | ExampleNotebooks/SpecEstimator.ipynb | jswoboda/SimISR | mit |
Window Function
When a long pulse is used in ISR the ACF is esitmated instead of the spectrum directly through the periodogram estimator. The estimation is a two step process, first estimate the lags and then do a summation rule. This leads to a windowing of the ACF shown in this. The window is also shown in the freque... | v=1
l=sp.arange(L)
W=-l**2/(L*v) + (L-v)*l/L/v+1
Wp=sp.pad(W,(int(sp.ceil(float(nspec-L)/2)),int(sp.floor(float(nspec-L)/2))),'constant',constant_values=0)
wfft=scfft.fftshift(scfft.fft(W,n=nspec))
fig4,ax4 = plt.subplots(1,2,sharey=False, figsize=(8,4),facecolor='w')
ax4[0].plot(l,W)
ax4[0].set_ylabel('Weighting')
... | ExampleNotebooks/SpecEstimator.ipynb | jswoboda/SimISR | mit |
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 correlatio... | 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.
su... | ExampleNotebooks/SpecEstimator.ipynb | jswoboda/SimISR | mit |
Plotting and Normalization of Input Spectra
Need to apply window function to spectrum. | 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, fi... | ExampleNotebooks/SpecEstimator.ipynb | jswoboda/SimISR | mit |
Create lookup table
Let's create a lookup table of embeddings. We'll use the comments field of a storm reports table from NOAA.
This is an example of the Feature Store design pattern. | %%bigquery
CREATE OR REPLACE TABLE advdata.comments_embedding AS
SELECT
output_0 as comments_embedding,
comments
FROM ML.PREDICT(MODEL advdata.swivel_text_embed,(
SELECT comments, LOWER(comments) AS sentences
FROM `bigquery-public-data.noaa_preliminary_severe_storms.wind_reports`
)) | 02_data_representation/text_embeddings.ipynb | GoogleCloudPlatform/ml-design-patterns | apache-2.0 |
Modeling the data
The data appears to follow very closely a sigmoid function (S-shaped curve). Logically, it makes sense: by the time the outbreak is discovered, there are many undiagnosed (and even asymptomatic) cases which lead to very rapid initial growth; later on, after a combination of aggressive measures to avoi... | import math
import numpy as np
from scipy import optimize
def logistic_function(x: float, a: float, b: float, c: float):
''' 1 / (1 + e^-x) '''
return a / (1.0 + np.exp(-b * (x - c)))
X, y = list(range(len(df))), df['total_confirmed'].tolist()
# Providing a reasonable initial guess is crucial for this model
p... | examples/logistic_modeling.ipynb | GoogleCloudPlatform/covid-19-open-data | apache-2.0 |
Gompertz function
While the simple logistic function provides a reasonably good fit, it appears to under-estimate the growth rate after the initial outbreak. A better fit might be Gompertz function which is an asymmetric logistic function that has a slower growth decay until the curve goes flat over time. Let's take a ... | def logistic_function(x: float, a: float, b: float, c: float):
''' a * e^(-b * e^(-cx)) '''
return a * np.exp(-b * np.exp(-c * x))
X, y = list(range(len(df))), df['total_confirmed'].tolist()
# Providing a reasonable initial guess is crucial for this model
params, _ = optimize.curve_fit(logistic_function, X, y,... | examples/logistic_modeling.ipynb | GoogleCloudPlatform/covid-19-open-data | apache-2.0 |
Evaluating the model
That curve looks like a very good fit! Traditional epidemiology models generally capture a number of different parameters representing biology and social factors; however, the COVID-19 pandemic might be very challenging to fit for traditional models for a number of reasons:
* It's a completely new ... | params_validate, _ = optimize.curve_fit(logistic_function, X[:-ESTIMATE_DAYS], y[:-ESTIMATE_DAYS])
# Project zero for all values except for the last ESTIMATE_DAYS
projected = [0] * len(X[:-ESTIMATE_DAYS]) + [logistic_function(x, *params_validate) for x in X[-ESTIMATE_DAYS:]]
projected = pd.Series(projected, index=df.i... | examples/logistic_modeling.ipynb | GoogleCloudPlatform/covid-19-open-data | apache-2.0 |
Projecting future data
It looks like our logistic model slightly underestimates the confirmed cases. This indicates that the model is optimistic about the slowdown of new cases being reported. A number of factors could affect this, like wider availability of tests.
Ultimately, it is also possible that the logistic mod... | import datetime
# Append N new days to our indices
date_format = '%Y-%m-%d'
date_range = [datetime.datetime.strptime(date, date_format) for date in df.index]
for _ in range(ESTIMATE_DAYS): date_range.append(date_range[-1] + datetime.timedelta(days=1))
date_range = [datetime.datetime.strftime(date, date_format) for dat... | examples/logistic_modeling.ipynb | GoogleCloudPlatform/covid-19-open-data | apache-2.0 |
Getting a Single Graph
Using NetworkX | %%time
graph_by_network_id = m.get_graph_by_id(11)
print_summary(graph_by_network_id) | Database Comparison - Blobs versus Edge Store.ipynb | pybel/pybel-notebooks | apache-2.0 |
Using SQL | def get_graph_by_network_edges(manager, network_id, **kwargs):
network = manager.get_network_by_id(network_id)
edges = network.edges
graph = BELGraph(**kwargs)
for edge in edges:
edge.insert_into_graph(graph)
return graph
%%time
graph_by_edges = get_graph_by_network_... | Database Comparison - Blobs versus Edge Store.ipynb | pybel/pybel-notebooks | apache-2.0 |
This query works, but needs serious optimization to be generally useful, especially since this kind of query automatically eliminates the need to do in-memory graph join operations.
Getting Multiple Graphs
Using NetworkX | network_ids = [10, 2, 9]
%%time
graph_by_network_ids = m.get_graph_by_ids(network_ids)
print_summary(graph_by_network_ids) | Database Comparison - Blobs versus Edge Store.ipynb | pybel/pybel-notebooks | apache-2.0 |
Using SQL | def get_graph_by_networks_edges(manager, network_ids, **kwargs):
edges = manager.session.query(Edge).join(network_edge).filter(network_edge.c.network_id.in_(network_ids))
graph = BELGraph(**kwargs)
for edge in edges:
edge.insert_into_graph(graph)
return graph
%%time
graph_by_... | Database Comparison - Blobs versus Edge Store.ipynb | pybel/pybel-notebooks | apache-2.0 |
Getting Edges Matching an Annotation | graph =
def get_graph_by_annotation(manager, keyword, value, **kwargs):
edges = manager.session.query(Edge).\
join(network_edge).join(edge_annotation).join(AnnotationEntry)\
filter(_and(network_edge.c.network_id.in_(network_ids),
edge_annotation.c.annotation_id == annotation_id... | Database Comparison - Blobs versus Edge Store.ipynb | pybel/pybel-notebooks | apache-2.0 |
Discovering Driver Nodes / Control Nodes | display(HTML('<h3>Control State Transition Graph (CSTG)</h3>'))
# THIS MIGHT TAKE A LONG TIME, it is here for demo purposes.
driver_nodes = N.attractor_driver_nodes(min_dvs=1, max_dvs=6, verbose=True)
print(N.get_node_name(driver_nodes))
#> ['AP2', 'EMF1', 'LFY', 'TFL1', 'UFO', 'WUS'], ['AG', 'EMF1', 'LFY', 'TFL1', 'UF... | tutorials/Control - Thaliana.ipynb | rionbr/CANA | mit |
Differences between the Control Methods | # Control via State Transition Graph (CSTG)
CSTGs = [['AP2', 'EMF1', 'LFY', 'TFL1', 'UFO', 'WUS'],
['AG', 'EMF1', 'LFY', 'TFL1', 'UFO', 'WUS']
]
# Pinning Control
PCs = [['AP3', 'UFO', 'AP1', 'LFY', 'WUS', 'AG'],
['AP3', 'UFO', 'EMF1', 'WUS', 'AG', 'TFL1'],
['AP3', 'UFO', 'LFY', 'WUS', '... | tutorials/Control - Thaliana.ipynb | rionbr/CANA | mit |
Upsampling Minority Class To Match Majority | # Indicies of each class' observations
i_class0 = np.where(y == 0)[0]
i_class1 = np.where(y == 1)[0]
# Number of observations in each class
n_class0 = len(i_class0)
n_class1 = len(i_class1)
# For every observation in class 1, randomly sample from class 0 with replacement
i_class0_upsampled = np.random.choice(i_class0... | machine-learning/handling_imbalanced_classes_with_upsampling.ipynb | tpin3694/tpin3694.github.io | mit |
Exponential, geometric, and polynomial growth
Exercise: Suppose there are two banks across the street from each other, The First Geometric Bank (FGB) and Exponential Savings and Loan (ESL). They offer the same interest rate on checking accounts, 3%, but at FGB, they compute and pay interest at the end of each year, a... | # Solution
p_0 = 1000
alpha = 0.03
# Solution
ts = linrange(11)
# Solution
geometric = p_0 * (1 + alpha) ** ts
# Solution
exponential = p_0 * exp(alpha * ts)
# Solution
alpha2 = exp(alpha) - 1
# Solution
geometric = p_0 * (1 + alpha2) ** ts
# Solution
plot(ts, exponential, '-', label='Exponential')
plot(ts... | soln/interest.ipynb | AllenDowney/ModSimPy | mit |
Exercise: Suppose a new bank opens called the Polynomial Credit Union (PCU). In order to compete with First Geometric Bank and Exponential Savings and Loan, PCU offers a parabolic savings account where the balance is a polynomial function of time:
$ x(t) = p_0 + \beta_1 t + \beta_2 t^2 $
As a special deal, they offer ... | # Solution
number_of_years = 100
ts = linrange(number_of_years+1)
geometric = p_0 * (1 + alpha2) ** ts
exponential = p_0 * exp(alpha * ts)
None
# Solution
beta1 = 30
beta2 = 0.5
parabolic = p_0 + beta1 * ts + beta2 * ts**2
None
# Solution
def plot_results():
plot(ts, exponential, '-', label='Exponential')
... | soln/interest.ipynb | AllenDowney/ModSimPy | mit |
This will populate the structcol namespace with a few functions and classes. You will probably find it easiest to keep all your calculations within a Jupyter notebook like this one. The package itself contains only generic functions and classes (that is, it doesn't include any specific calculations of structural colo... | %matplotlib inline
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate
# require seaborn (not installed by default in Anaconda; comment out if not installed)
import seaborn as sns | tutorial.ipynb | manoharan-lab/structural-color | gpl-3.0 |
Using quantities with units
The structural-color package uses the pint package to keep track of units and automatically convert them. To define a quantity with units, use the structcol.Quantity constructor. For example, to define a wavelength of 0.45 $\mu$m: | wavelen = sc.Quantity('0.45 um')
print(wavelen)
print(wavelen.dimensionality) | tutorial.ipynb | manoharan-lab/structural-color | gpl-3.0 |
Converting between units: | print(wavelen.to('m')) | tutorial.ipynb | manoharan-lab/structural-color | gpl-3.0 |
Units work in numpy arrays, too: | wavelens = sc.Quantity(np.arange(450.0, 800.0, 10.0), 'nm')
print(wavelens.to('um')) | tutorial.ipynb | manoharan-lab/structural-color | gpl-3.0 |
Refractive index module
To use the refractive index module: | import structcol.refractive_index as ri | tutorial.ipynb | manoharan-lab/structural-color | gpl-3.0 |
This module contains dispersion relations for a number of materials. For example, to get the index of polystyrene at 500 nm, you can call | ri.n('polystyrene', sc.Quantity('500 nm')) | tutorial.ipynb | manoharan-lab/structural-color | gpl-3.0 |
You must give this function a quantity with units as the second argument. If you give it a number, it will throw an error, rather than trying to guess what units you're thinking of. You can also calculate the refractive index at several different wavelengths simultaneously, like this (using wavelens array from above)... | n_particle = ri.n('polystyrene', wavelens)
plt.plot(wavelens, n_particle)
plt.ylabel('$n_\mathrm{PS}$')
plt.xlabel('wavelength (nm)') | tutorial.ipynb | manoharan-lab/structural-color | gpl-3.0 |
You can use complex refractive indices by adding the imaginary component of the index. Note that in python the imaginary number $i$ is denoted by $j$. You can choose to use the values from literature or from experimental measurement: | ri.n('polystyrene', sc.Quantity('500 nm'))+0.0001j | tutorial.ipynb | manoharan-lab/structural-color | gpl-3.0 |
Importing your own refractive index data
You can input your own refractive index data (which can be real or complex) by calling the material $\textbf{'data'}$ and specifying the optional parameters $\textbf{'index_data'}$, $\textbf{'wavelength_data'}$, and $\textbf{'kind'}$.
index_data: refractive index data from lite... | wavelength_values = sc.Quantity(np.array([400,500,600]), 'nm')
index_values= sc.Quantity(np.array([1.5,1.55,1.6]), '')
wavelength = sc.Quantity(np.arange(400, 600, 1), 'nm')
n_data = ri.n('data', wavelength, index_data=index_values, wavelength_data=wavelength_values)
plt.plot(wavelength, n_data, '--', label='fit')
pl... | tutorial.ipynb | manoharan-lab/structural-color | gpl-3.0 |
Calculating a reflection spectrum
With the tools above we can calculate a reflection spectrum using the single-scattering model described in Magkiriadou, S., Park, J.-G., Kim, Y.-S., and Manoharan, V. N. “Absence of Red Structural Color in Photonic Glasses, Bird Feathers, and Certain Beetles” Physical Review E 90, no. ... | # uncomment the line below to time how long this calculation takes
# %%timeit
from structcol import model
# parameters for our colloidal sample
volume_fraction = sc.Quantity(0.64, '')
radius = sc.Quantity('125 nm')
# wavelengths of interest
wavelength = sc.Quantity(np.arange(400., 800., 10.0), 'nm')
# calculate ref... | tutorial.ipynb | manoharan-lab/structural-color | gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.