markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Fourier transform | from larch.xafs import xftf
xftf(feo, kweight=2, kmin=2, kmax=13.0, dk=5, kwindow='Kaiser-Bessel') | notebooks/larch.ipynb | maurov/xraysloth | bsd-3-clause |
Basic plots can be done directly with matplotlib. The command %matplotlib inline permits in-line plots, that is, images are saved in the notebook. This means that the figures are visible when the notebook is open, even without execution. | %matplotlib inline
import matplotlib.pyplot as plt
plt.plot(feo.energy, feo.mu)
from larch.wxlib import plotlabels as plab
plt.plot(feo.k, feo.chi*feo.k**2)
plt.xlabel(plab.k)
plt.ylabel(plab.chikw.format(2))
plt.plot(feo.k, feo.chi*feo.k**2, label='chi(k)')
plt.plot(feo.k, feo.kwin, label='window')
plt.xlabel(plab.k... | notebooks/larch.ipynb | maurov/xraysloth | bsd-3-clause |
A work-in-progress utility is available in sloth.utils.xafsplotter. It is simply a wrapper on top of the wonderful plt.subplots(). The goal of this utility is to produce in-line nice figures with standard layouts ready for reporting your analysis to colleagues. With little effort/customization, those plots could be con... | from sloth.utils.xafsplotter import XAFSPlotter
p = XAFSPlotter(ncols=2, nrows=2, dpi=150, figsize=(6, 4))
p.plot(feo.energy, feo.mu, label='raw', win=0)
p.plot(feo.energy, feo.i0, label='i0', win=0, side='right')
p.plot(feo.energy, feo.norm, label='norm', win=1)
p.plot(feo.k, feo.chi*feo.k**2, label='chi2', win=2)
p.p... | notebooks/larch.ipynb | maurov/xraysloth | bsd-3-clause |
Test interactive plot with wxmplot.interactive
With the following commands is possible to open an external plotting window (based on Wxpython) permitting interactive tasks. | from wxmplot.interactive import plot
plot(feo.energy, feo.mu, label='mu', xlabel='Energy', ylabel='mu', show_legend=True) | notebooks/larch.ipynb | maurov/xraysloth | bsd-3-clause |
Building the graph
From Chris McCormick's blog, we can see the general structure of our network.
The input words are passed in as one-hot encoded vectors. This will go into a hidden layer of linear units, then into a softmax layer. We'll use the softmax layer to make a prediction like normal.
The idea here is to train... | train_graph = tf.Graph()
with train_graph.as_default():
inputs = tf.placeholder(tf.int32, [None, None])
labels = tf.placeholder(tf.int32, [None, 1]) | embeddings/Skip-Gram word2vec.ipynb | tkurfurst/deep-learning | mit |
Embedding
The embedding matrix has a size of the number of words by the number of neurons in the hidden layer. So, if you have 10,000 words and 300 hidden units, the matrix will have size $10,000 \times 300$. Remember that we're using one-hot encoded vectors for our inputs. When you do the matrix multiplication of the ... | n_vocab = len(int_to_vocab)
n_embedding = 200 # Number of embedding features
with train_graph.as_default():
embedding = tf.variable(tf.truncated_normal(n_vocab, n_embedding)) # create embedding weight matrix here
embed = tf.nn.embedding_lookup(embedding, inputs) # use tf.nn.embedding_lookup to get the hidden ... | embeddings/Skip-Gram word2vec.ipynb | tkurfurst/deep-learning | mit |
Negative sampling
For every example we give the network, we train it using the output from the softmax layer. That means for each input, we're making very small changes to millions of weights even though we only have one true example. This makes training the network very inefficient. We can approximate the loss from th... | # Number of negative labels to sample
n_sampled = 100
with train_graph.as_default():
softmax_w = tf.variable(tf.truncated_normal(n_embedding,n_vocab, stdev=0.1) # create softmax weight matrix here
softmax_b = tf.variable(tf.zeros(n_vocab)) # create softmax biases here
# Calculate the loss using negativ... | embeddings/Skip-Gram word2vec.ipynb | tkurfurst/deep-learning | mit |
Load data and define functions
The rainfall and reference evaporation are read from file and truncated for the period 1980 - 2000. The rainfall and evaporation series are taken from KNMI station De Bilt. The reading of the data is done using Pastas.
Heads are generated with a Gamma response function which is defined be... | rain = ps.read.read_knmi('data_notebook_5/etmgeg_260.txt', variables='RH').series
evap = ps.read.read_knmi('data_notebook_5/etmgeg_260.txt', variables='EV24').series
rain = rain['1980':'1999']
evap = evap['1980':'1999']
def gamma_tmax(A, n, a, cutoff=0.99):
return gammaincinv(n, cutoff) * a
def gamma_step(A, n, a... | examples/notebooks/8_pastas_synthetic.ipynb | gwtsa/gwtsa | mit |
The Gamma response function requires 3 input arguments; A, n and a. The values for these parameters are defined along with the parameter d, the base groundwater level. The response function is created using the functions defined above. | Atrue = 800
ntrue = 1.1
atrue = 200
dtrue = 20
h = gamma_block(Atrue, ntrue, atrue) * 0.001
tmax = gamma_tmax(Atrue, ntrue, atrue)
plt.plot(h)
plt.xlabel('Time (days)')
plt.ylabel('Head response (m) due to 1 mm of rain in day 1')
plt.title('Gamma block response with tmax=' + str(int(tmax))); | examples/notebooks/8_pastas_synthetic.ipynb | gwtsa/gwtsa | mit |
Create Pastas model
The next step is to create a Pastas model. The head generated using the Gamma response function is used as input for the Pastas model.
A StressModel instance is created and added to the Pastas model. The StressModel intance takes the rainfall series as input aswell as the type of response function,... | ml = ps.Model(head)
sm = ps.StressModel(rain, ps.Gamma, name='recharge', settings='prec')
ml.add_stressmodel(sm)
ml.solve(noise=False)
ml.plots.results(); | examples/notebooks/8_pastas_synthetic.ipynb | gwtsa/gwtsa | mit |
Differences Between Linear Classifier and Linear Regression
We start with loading a data that was created for this discussion and talk a about the differences between linear regression and linear classifier. | lc2_data = np.genfromtxt('./lc2_data.txt', delimiter=None)
X, Y = lc2_data[:, :-1], lc2_data[:, -1]
f, ax = plt.subplots(1, 2, figsize=(20, 8))
mask = Y == -1
ax[0].scatter(X[mask, 0], X[mask, 1], s=120, color='blue', marker='s', alpha=0.75)
ax[0].scatter(X[~mask, 0], X[~mask, 1], s=340, color='red', marker='*', alp... | week3/lc_and_perceptron.ipynb | sameersingh/ml-discussions | apache-2.0 |
Some of the questions that were asked in class by me or by the students. Make sure you know how to answer all of them :)
If it's a linear classifier, and the blue and red are the differenc classes, how many features do we have here?
How would a classifier line will look like if I plot it here?
Give me a real life exam... | theta = np.array([-6., 0.5, 1.]) | week3/lc_and_perceptron.ipynb | sameersingh/ml-discussions | apache-2.0 |
Notice the '.'s. This will make sure it's a float and not integer which can casue problems later down the line.
$\theta$ has three features that will correspond to the constant (also known as the 'bias' or 'intercept') and two for the two features of X. So first we will add a constant to all the X data.
Do not use the... | def add_const(X):
return np.hstack([np.ones([X.shape[0], 1]), X])
Xconst = add_const(X)
x_j, y_j = Xconst[90], Y[90] | week3/lc_and_perceptron.ipynb | sameersingh/ml-discussions | apache-2.0 |
Response Value
The first step in the preceptron is to compute the response value. It's comptued as the inner product $\theta x^j$. The simple intuative way to do that is to simply use a for loop. | x_theta = 0
for i in range(x_j.shape[0]):
x_theta += x_j[i] * theta[i]
print x_theta | week3/lc_and_perceptron.ipynb | sameersingh/ml-discussions | apache-2.0 |
This is a VERY inefficient way to do that. Luckily for us, numpy has the answer in the form of np.dot(). | print np.dot(x_j, theta) | week3/lc_and_perceptron.ipynb | sameersingh/ml-discussions | apache-2.0 |
Classification Decision
Now let's compute the decision classification $T[\theta x^j]$. One option is to use the np.sign method. This will not a a good solution because np.sign(0) = 0.
One way of solving it is to use epsilon. | eps = 1e-200
def sign(vals):
"""Returns 1 if val >= 0 else -1"""
return np.sign(vals + eps) | week3/lc_and_perceptron.ipynb | sameersingh/ml-discussions | apache-2.0 |
Predict function
So now with the the decision value and my_sign we can write the predict function | def predict(x_j, theta):
"""Returns the class prediction of a single point x_j"""
return sign(np.dot(x_j, theta))
print predict(x_j, theta) | week3/lc_and_perceptron.ipynb | sameersingh/ml-discussions | apache-2.0 |
Predict multiple
During the discussions I brought up that for some methods of computing the inner product (such as np.sum()) will not work for multiple points at the same time unless you take steps to make it work. | def predict_with_np_sum(X, theta):
"""Predicts the class value for multiple points or a single point at the same time. """
X = np.atleast_2d(X)
return np.sum(theta * X, axis=1) | week3/lc_and_perceptron.ipynb | sameersingh/ml-discussions | apache-2.0 |
Computing the Prediction Error
Using the predict function, we can now compute the prediction error: $$J^j = (y^j - \hat{y}^j)$$ | def pred_err(X, Y, theta):
"""Predicts that class for X and returns the error rate. """
Yhat = predict(X, theta)
return np.mean(Yhat != Y)
print pred_err(x_j, y_j, theta) | week3/lc_and_perceptron.ipynb | sameersingh/ml-discussions | apache-2.0 |
Learning Update
Using the error we can now even do the update step in the learning algorithm: $$\theta = \theta + \alpha * (y^j - \hat{y}^j)x^j$$ | a = 0.1
y_hat_j = predict(x_j, theta)
print theta + a * (y_j - y_hat_j) * x_j | week3/lc_and_perceptron.ipynb | sameersingh/ml-discussions | apache-2.0 |
Train method
Using everything we coded so far, we can fully create the train method | def train(X, Y, a=0.01, stop_tol=1e-8, max_iter=1000):
# Start by adding a const
Xconst = add_const(X)
m, n = Xconst.shape
# Initializing theta
theta = np.array([-6., 0.5, 1.])
# The update loops
J_err = [np.inf]
for i in range(1, max_iter + 1):
for j in range(m):
... | week3/lc_and_perceptron.ipynb | sameersingh/ml-discussions | apache-2.0 |
Creating a Perceptron Classifier
Now let's use all the code that we wrote and create a Python class Perceptron that can plug in to the mltools package.
In order to do that, the Prceptron class has to inherit the object mltools.base.classifier
In case you haven't looked at the actual code in the mltools, now will probab... | from mltools.base import classifier | week3/lc_and_perceptron.ipynb | sameersingh/ml-discussions | apache-2.0 |
In order to crete an object, we'll have to add self to all the methods. | class Perceptron(classifier):
def __init__(self, theta=None):
self.theta = theta
def predict(self, X):
"""Retruns class prediction for either single point or multiple points. """
# I'm addiing this stuff here so it could work with the plotClassify2D method.
Xconst = np.atlea... | week3/lc_and_perceptron.ipynb | sameersingh/ml-discussions | apache-2.0 |
Creating a model, training and plotting predictions
First let's create the model with some initialized theta and plot the decision bounderies. For the plotting we can use the mltools plotClassify2D !!! wowowowo!!!! | model = Perceptron()
model.theta = np.array([-6., 0.5, 1])
ml.plotClassify2D(model, X, Y) | week3/lc_and_perceptron.ipynb | sameersingh/ml-discussions | apache-2.0 |
Next, let's actually train the model and plot the new decision boundery. | model.train(X, Y)
ml.plotClassify2D(model, X, Y) | week3/lc_and_perceptron.ipynb | sameersingh/ml-discussions | apache-2.0 |
Gilles.py is the file that contains the important functions, we will go through it to understand the main differences between the deterministic and stochastic solution, but first let's see some examples! | %run Gilles.py | ReAct/Python/ReAct_Notebook.ipynb | manulera/ModellingCourse | gpl-3.0 |
Here we can see some examples for the use of ReAct | %run 'Example1_oscillations.py'
PrintPythonFile('Example1_oscillations.py') | ReAct/Python/ReAct_Notebook.ipynb | manulera/ModellingCourse | gpl-3.0 |
Is this oscilatory effect only? If we change the number of molecules of A from 100 to 1000 what do we see? How could we quantify the relevance of this oscilations with respect to the equilibrium? | %run 'Example2_Ask4Oscillations.py'
PrintPythonFile('Example2_Ask4Oscillations.py') | ReAct/Python/ReAct_Notebook.ipynb | manulera/ModellingCourse | gpl-3.0 |
You can copy the content of the file into a new cell, and change the values, explore how the parameters affect the outcome using the cell below. | # Initial conditions
user_input = ['A', 100,
'B', 0]
# Constants (this is not necessary, they could be filled up already in the reaction tuple)
k = (12,8)
# Reaction template ((stoch_1,reactant_1,stoch_2,reactant_2),(stoch_1,product_1,stoch_2,product_2),k)
reactions = (
(1,'A'),(1,'B'),k[0],
(1,'... | ReAct/Python/ReAct_Notebook.ipynb | manulera/ModellingCourse | gpl-3.0 |
Now, let's look at a maybe more relevant situation for biologists, the already mentioned MAP kinase cascade.
<img src="Images/miniMAP.png" style="width: 200px;"/>
Kinase cascades are known for amplifying the signal: a minor change in the cell, for example, a transient activation of a small number of receptors, is ampli... | %run 'Example3_KyneticCascade.py'
PrintPythonFile('Example3_KyneticCascade.py') | ReAct/Python/ReAct_Notebook.ipynb | manulera/ModellingCourse | gpl-3.0 |
Explore how the parameters (initial concentrations and kynetic constants) affect the outcome of the response in the cell below. Try to find a link with the explained role of kinase cascades. | import numpy as np
from Gilles import *
import matplotlib.pyplot as plt
# Initial conditions
user_input = ['Rec', 10,
'1M3', 10,
'1M3P', 0,
'1M2', 20,
'1M2P', 0,
'1M1', 30,
'1M1P', 0]
# Constants (this is not necessary, they could be ... | ReAct/Python/ReAct_Notebook.ipynb | manulera/ModellingCourse | gpl-3.0 |
The predator-pray model
Also known as Lotka–Volterra equations:
<img src="Images/Lotka_volterra.svg" style="width: 150px;"/>
Where, x is the number of preys , and y is the number of predators. Before looking at the next cell, how would you write these equations as a chemical reaction?
What does each reaction represent | %run 'Example_PredatorPray.py'
PrintPythonFile('Example_PredatorPray.py') | ReAct/Python/ReAct_Notebook.ipynb | manulera/ModellingCourse | gpl-3.0 |
2. Create Groups (named variables that hold your replicates of each sample)
You must assign your raw files into experimental groups for analysis. These are used for downstream statistics and for selection of specific groups for filtering to subsets of files for analysis (Ex. just pos or just neg).
The groups are creat... | files = dp.get_metatlas_files(experiment = '%ENTERSTRING%',name = '%ENTERSTRING%',most_recent = True)
# ^ edit the text string in experiment and name fields
df = metob.to_dataframe(files)
df[['experiment','name','username','acquisition_time']]
len(files) | notebooks/reference/Workflow_Notebook_Metatlas_Stable_v0.1.0_20210303.ipynb | metabolite-atlas/metatlas | bsd-3-clause |
OPTION A: Automated Group Maker
This will attempt to create groups in an automated fashion (rather than filling out a spreadsheet with a list of files and group names). If your files are all in one folder at nersc, you can use this options. If not, use option B below.
A long group name consisting of the common header... | #STEP 1: View the groups
files = metob.retrieve('lcmsruns',experiment='%ENTERSTRING%',username='*')
controlled_vocab = ['QC','InjBl','ISTD'] #add _ to beginning. It will be stripped if at begining
version_identifier = 'vs1'
exclude_files = [] # Exclude files containing a substring (list) Eg., ['peas']
file_dict = {}
... | notebooks/reference/Workflow_Notebook_Metatlas_Stable_v0.1.0_20210303.ipynb | metabolite-atlas/metatlas | bsd-3-clause |
Make data frame of short filenames and samplenames
Uncomment the below 2 blocks to make short file names and smaple names.<br>
This creates a dataframe and a csv file which can be edited, exported and imported. | # Make short_filename and short_samplename
files = metob.retrieve('lcmsruns',experiment='%ENTERSTRING%',username='*')
short_filename_delim_ids = [0,2,4,5,7,9,14]
short_samplename_delim_ids = [9,12,13,14]
short_names_df = pd.DataFrame(columns=['sample_treatment','short_filename','short_samplename'])
ctr = 0
for f in fi... | notebooks/reference/Workflow_Notebook_Metatlas_Stable_v0.1.0_20210303.ipynb | metabolite-atlas/metatlas | bsd-3-clause |
3. Select groups of files to operate on
Here, you will assign your database groups to a local variable which will be used downstream in the notebook for analyzing your data with an atlas.
in block below, fill out the fields for name, include_list and exclude_list using text strings from the group names you created in ... | polarity = 'POS' #IMPORTANT: Please make sure you set the correct polarity for the analysis
groups = dp.select_groups_for_analysis(name = '%ENTERSEARCHSTRING%', # <- edit text search string here
most_recent = True,
remove_empty = True,
... | notebooks/reference/Workflow_Notebook_Metatlas_Stable_v0.1.0_20210303.ipynb | metabolite-atlas/metatlas | bsd-3-clause |
4. Create new Atlas entries in the Metatlas database from a csv file
QC, IS, and EMA template atlases are available on the google drive.
Create your atlas as a csv file, check that it looks correct (has all the correct headers and no blank values in rows; all columns are the correct data type
Save it with the type of ... | atlasfilename='%ENTERSTRING%' # <- enter the exact name of your csv file without the file extension
names = dp.make_atlas_from_spreadsheet('%s%s%s' % (pathtoatlas,atlasfilename,'.csv'), # <- DO NOT EDIT THIS LINE
atlasfilename,
filetype='c... | notebooks/reference/Workflow_Notebook_Metatlas_Stable_v0.1.0_20210303.ipynb | metabolite-atlas/metatlas | bsd-3-clause |
POSITIVE MODE ATLAS UPLOAD | atlasfilename='%ENTERSTRING%' # <- enter the exact name of your csv file without the file extension
names = dp.make_atlas_from_spreadsheet('%s%s%s' % (pathtoatlas,atlasfilename,'.csv'), # <- DO NOT EDIT THIS LINE
atlasfilename,
filetype='... | notebooks/reference/Workflow_Notebook_Metatlas_Stable_v0.1.0_20210303.ipynb | metabolite-atlas/metatlas | bsd-3-clause |
5. Select Atlas to use
The first block will retrieve a list of atlases matching the 'name' string that you enter. Also, you must enter your username.
The next block will select one from the list, using the index number. Make sure to enter the index number for the atlas you want to use for your analysis by setting in... | atlases = metob.retrieve('Atlas',name='%ENTERSTRING%',username='YOUR-NERSC-USERNAME')
names = []
for i,a in enumerate(atlases):
print(i,a.name,pd.to_datetime(a.last_modified,unit='s'))#len(a.compound_identifications)
my_atlas = atlases[-1]
atlas_df = ma_data.make_atlas_df(my_atlas)
atlas_df['label'] = [cid.name fo... | notebooks/reference/Workflow_Notebook_Metatlas_Stable_v0.1.0_20210303.ipynb | metabolite-atlas/metatlas | bsd-3-clause |
6. Get EICs and MSMS for all files in your groups, using all compounds in your atlas.
This block builds the metatlas_dataset variable. This holds your EIC data (mz, rt, intensity values within your mz and rt ranges).
The EIC data contains mz, intensity and RT values across your RT range. There are two parameters that... | all_files = []
for my_group in groups:
for my_file in my_group.items:
extra_time = 0.75 # NOTE: 0.75 for the first run, 0.5 for final
extra_mz = 0.00
all_files.append((my_file,my_group,atlas_df,my_atlas,extra_time,extra_mz))
pool = mp.Pool(processes=min(4, len(all_files)))
t0 = tim... | notebooks/reference/Workflow_Notebook_Metatlas_Stable_v0.1.0_20210303.ipynb | metabolite-atlas/metatlas | bsd-3-clause |
6b Optional: Filter atlas for compounds with no or low signals
Uncomment the below 3 blocks to filter the atlas.
Please ensure that correct polarity is used for the atlases. | # dp = reload(dp)
# num_data_points_passing = 5
# peak_height_passing = 4e5
# atlas_df_passing = dp.filter_atlas(atlas_df=atlas_df, input_dataset=metatlas_dataset, num_data_points_passing = num_data_points_passing, peak_height_passing = peak_height_passing)
# print("# Compounds in Atlas: "+str(len(atlas_df)))
# print("... | notebooks/reference/Workflow_Notebook_Metatlas_Stable_v0.1.0_20210303.ipynb | metabolite-atlas/metatlas | bsd-3-clause |
Create new atlas and store in database
This block creates a filtered atlas with a new name !!
Automatically selects this atlas for processing.
Make sure to use this atlas for downstream analyses. (NOTE: If you restart kernel or come back to the analysis, you need to reselect this newly created filtered atlas for proce... | # atlas_passing = my_atlas.name+'_filteredby-datapnts'+str(num_data_points_passing)+'-pkht'+str(peak_height_passing)
# myAtlas_passing = dp.make_atlas_from_spreadsheet(atlas_df_passing,
# atlas_passing,
# filetype='dataframe',
# sheetname='',... | notebooks/reference/Workflow_Notebook_Metatlas_Stable_v0.1.0_20210303.ipynb | metabolite-atlas/metatlas | bsd-3-clause |
One of the two blocks below builds the hits variable. This holds your MSMS spectra (from within your mz, and rt ranges, and within the extra time indicated above).
There are two options for generating the hits variable:
1. block A: use when your files have msms. It create the hits variable and also saves a binary (pic... | ##BLOCK A
import warnings; warnings.simplefilter('ignore')
t0 = time.time()
hits=dp.get_msms_hits(metatlas_dataset,extra_time=True,keep_nonmatches=True, frag_mz_tolerance=0.01, ref_loc='/global/project/projectdirs/metatlas/projects/spectral_libraries/msms_refs_v3.tab')
pickle.dump(hits, open(os.path.join(output_dir,po... | notebooks/reference/Workflow_Notebook_Metatlas_Stable_v0.1.0_20210303.ipynb | metabolite-atlas/metatlas | bsd-3-clause |
7. Adjust Retention Times.
This block creates an interactive plot. The top panel displays MSMS from within the two green RT bounds selected below (rt min and max, initially set in atlas). When the database holds reference spectra, mirror plots are generated with the reference spectra inverted below the sample spectra... | ###STEP 1: Set the peak flag radio buttons using one of the two lines below, for custom flags or default flags
import warnings; warnings.simplefilter('ignore')
peak_flag_list=('','L1+ - 1 pk, good RT&MSMS','L1+ - known isomer overlap','L1+ - 1 pk, good RT, MSMS ok (coisolated mz/partial match/low int)','L1+ - 1 pk, goo... | notebooks/reference/Workflow_Notebook_Metatlas_Stable_v0.1.0_20210303.ipynb | metabolite-atlas/metatlas | bsd-3-clause |
8. Create filtered atlas excluding compounds marked removed
Re-run the following before filtering atlas
1. Get Groups (include InjBl)
2. Get Atlas
3. Get Data
4. Get MSMS Hits | dp=reload(dp)
(atlas_kept, atlas_removed) = dp.filter_by_remove(atlas_df, metatlas_dataset)
print("# Compounds Total: "+str(len(atlas_df)))
print("# Compounds Kept: "+str(len(atlas_kept)))
print("# Compounds Removed: "+str(len(atlas_removed)))
atlasfilename=my_atlas.name+'_kept' # <- enter the name of the atlas to be... | notebooks/reference/Workflow_Notebook_Metatlas_Stable_v0.1.0_20210303.ipynb | metabolite-atlas/metatlas | bsd-3-clause |
Re-run the following before filtering atlas
Restart kernel
Get Groups
Get Atlas (look for the *_kept atlas)
Get Data
Get MSMS Hits
9. Export results files
Export Atlas to a Spreadsheet
The peak flags that you set and selected from the rt adjuster radio buttons will be saved in a column called id_notes | atlas_identifications = dp.export_atlas_to_spreadsheet(my_atlas,os.path.join(output_dir,'%s_%s%s.csv' % (polarity,my_atlas.name,"export")))
print(my_atlas.name)
| notebooks/reference/Workflow_Notebook_Metatlas_Stable_v0.1.0_20210303.ipynb | metabolite-atlas/metatlas | bsd-3-clause |
Export MSMS match scores, stats sheets, and final identification table
This block creates a number of files:
compound_scores.csv
stats_table.tab
filtered and unfiltered peak heights, areas, msms scores, mz centroid, mz ppm error, num of fragment matches, rt delta, rt peak
final identification sheet that is formatted f... | kwargs = {'min_intensity': 1e4, # strict = 1e5, loose = 1e3
'rt_tolerance': .5, #>= shift of median RT across all files for given compound to reference
'mz_tolerance': 20, # strict = 5, loose = 25; >= ppm of median mz across all files for given compound relative to reference
'min... | notebooks/reference/Workflow_Notebook_Metatlas_Stable_v0.1.0_20210303.ipynb | metabolite-atlas/metatlas | bsd-3-clause |
Export EIC chromatograms as individual pdfs for each compound
There are three options for formatting your EIC output using the "group =" line below:
'page' will print each sample group on a new page of a pdf file
'index' will label each group with a letter
None will print all of the groups on one page with very small ... | group = 'index' # 'page' or 'index' or None
save = True
share_y = True
dp.make_chromatograms(input_dataset=metatlas_dataset, include_lcmsruns = [],exclude_lcmsruns = ['InjBl','QC','Blank','blank'], group=group, share_y=share_y, save=save, output_loc=output_dir, short_names_df=short_names_df, short_names_header='short_... | notebooks/reference/Workflow_Notebook_Metatlas_Stable_v0.1.0_20210303.ipynb | metabolite-atlas/metatlas | bsd-3-clause |
Export MSMS mirror plots as individual pdfs for each compound
use_labels = True will use the compound names you provided in your atlas, if you set it to false, the compounds will be named with the first synonym available from pubchem which could be a common name, iupac name, cas number, vendor part number, etc.
The i... | dp.make_identification_figure_v2(input_dataset = metatlas_dataset, msms_hits=hits, use_labels=True, include_lcmsruns = [],exclude_lcmsruns = ['InjBl','QC','Blank','blank'], output_loc=output_dir, short_names_df=short_names_df, polarity=polarity) | notebooks/reference/Workflow_Notebook_Metatlas_Stable_v0.1.0_20210303.ipynb | metabolite-atlas/metatlas | bsd-3-clause |
Table of Contents
1.- About Optimization
2.- Time Profiling
3.- Memory Profiling
4.- Application: K-means Clustering Algorithm
<div id='about' />
1.- About Optimization
"The real problem is that programmers have spent far too much time worrying about efficiency in the wrong places and at the wrong times; premature op... | n = 100000 | 06_profiling/06_profiling.ipynb | mavillan/SciProg | gpl-3.0 |
Let's time this computation in pure Python (Using list comprehensions) | t1 = %timeit -o -n 100 sum([1. / i**2 for i in range(1, n)]) | 06_profiling/06_profiling.ipynb | mavillan/SciProg | gpl-3.0 |
Now, let's use the %%timeit cell magic to time the same computation written on two lines: | %%timeit s=0.
for i in range(1, n):
s += 1./i**2 | 06_profiling/06_profiling.ipynb | mavillan/SciProg | gpl-3.0 |
Finally, let's time the NumPy version of this computation: | t2 = %timeit -o -n 100 np.sum(1./np.arange(1., n) ** 2) | 06_profiling/06_profiling.ipynb | mavillan/SciProg | gpl-3.0 |
The object returned by timeit contains information about the time measurements: | print("Type:")
print(type(t1))
print("\nTime of all runs:")
print(t1.all_runs)
print("\nBest measured time:")
print(t1.best)
print("\nWorst measured time:")
print(t1.worst)
print("\nCompilation time:")
print(t1.compile_time) | 06_profiling/06_profiling.ipynb | mavillan/SciProg | gpl-3.0 |
And we can compare the performance improvement with the quotient between the best measured times: | print("Performance improvement:")
print(t1.best/t2.best) | 06_profiling/06_profiling.ipynb | mavillan/SciProg | gpl-3.0 |
2.2- Function Profiling: cProfile
The %timeit magic command is often helpful, yet a bit limited when you need detailed information about what takes most of the execution time in your code. This magic command is meant for benchmarking rather than profiling.
Python includes a profiler named cProfile that breaks down the ... | def step(*shape):
# Create a random n-vector with +1 or -1 values.
return 2 * (np.random.random_sample(shape) < .5) - 1 | 06_profiling/06_profiling.ipynb | mavillan/SciProg | gpl-3.0 |
Now, let's write the simulation code in a cell starting with %%prun in order to profile the entire simulation. The various options allow us to save the report in a file and to sort the first 10 results by cumulative time.
Python's profiler creates a detailed report of the execution time of our code, function by funct... | a = np.array([1,2,3,4,5,6])
np.cumsum(a)
%%prun -s cumulative -q -l 15 -T prun0
n = 10000
iterations = 500
x = np.cumsum(step(iterations, n), axis=0)
bins = np.arange(-30, 30, 1)
y = np.vstack([np.histogram(x[i,:], bins)[0] for i in range(iterations)]) | 06_profiling/06_profiling.ipynb | mavillan/SciProg | gpl-3.0 |
In the example, -s allows us to sort the report by a particular column, -q to suppress the pager output, -l to limit the number of lines displayed or to filter the results by function name, and -T to save the report
in a text file. . This database-like object contains all information about the profiling and can be ana... | print(open('prun0', 'r').read())
def plot_helper(y, i, n):
plt.figure(figsize=(10,7))
plt.plot(np.arange(-30,29), y[i], 'ro-')
plt.title("Distribution of {0} simultaneous random walks at iteration {1}".format(n,i))
plt.show()
interact(plot_helper, y=fixed(y), i=(0,500), n=fixed(10000)) | 06_profiling/06_profiling.ipynb | mavillan/SciProg | gpl-3.0 |
2.3- Line Profiling: line_profiler
Python's native cProfile module and the corresponding %prun magic break down the execution time of code function by function. Sometimes, we may need an even more fine- grained analysis of code performance with a line-by-line report.
To profile code line-by-line, we need an external Py... | %load_ext line_profiler | 06_profiling/06_profiling.ipynb | mavillan/SciProg | gpl-3.0 |
This IPython extension module provides a %lprun magic command to profile a Python function line-by-line.
Note: It works best when the function is defined in a file and not in the interactive namespace or in the notebook.
Therefore, here we write our code in a Python script using the %%writefile cell magic: | %%writefile simulation.py
import numpy as np
def step(*shape):
# Create a random n-vector with +1 or -1 values.
return (2 * (np.random.random_sample(shape) < .5) - 1)
def simulate(iterations, n=10000):
s = step(iterations, n)
x = np.cumsum(s, axis=0)
bins = np.arange(-30, 30, 1)
y = np.vstack([... | 06_profiling/06_profiling.ipynb | mavillan/SciProg | gpl-3.0 |
Now, let's import this script into the interactive namespace so that we can execute and profile our code.
The functions to be profiled need to be explicitly specified in the %lprun magic command. We also save the report in a file, lprof0: | import simulation
%lprun -T lprof0 -f simulation.simulate simulation.simulate(500) | 06_profiling/06_profiling.ipynb | mavillan/SciProg | gpl-3.0 |
Let's display the report: | print(open('lprof0', 'r').read()) | 06_profiling/06_profiling.ipynb | mavillan/SciProg | gpl-3.0 |
To see all the possible arguments run %lprun?.
<div id='memory' />
3.- Memory Profiling
The methods described in the previous recipe were about CPU time profiling. However, memory is also a critical factor.
Writing memory-optimized code is not trivial and can really make your program faster. This is particularly impor... | %load_ext memory_profiler | 06_profiling/06_profiling.ipynb | mavillan/SciProg | gpl-3.0 |
The memory_profiler package checks the memory usage of the interpreter at every line. The increment column allows us to spot those places in the code where large amounts of memory are allocated.
Now, let's run the code under the control of the memory profiler: | %mprun -T mprof0 -f simulation.simulate simulation.simulate(1500) | 06_profiling/06_profiling.ipynb | mavillan/SciProg | gpl-3.0 |
Let's show the results: | print(open('mprof0', 'r').read()) | 06_profiling/06_profiling.ipynb | mavillan/SciProg | gpl-3.0 |
The memory_profiler IPython extension also comes with a %memit magic command that lets us benchmark the memory used by a single Python statement. Here is a simple example: | %memit np.random.randn(2000, 10000) | 06_profiling/06_profiling.ipynb | mavillan/SciProg | gpl-3.0 |
<div id='Application' />
4.- Application: K-Means Clustering Algorithm
This is an algorithm that find structure over unlabeled data, i.e, it is an unsupervised learning algorithm. It is very simple, and works as follows:
initialize $k$ cluster centroids
Repeat the following:
2.1.- For each point, compute which centro... | points = np.vstack(((np.random.randn(150, 2) * 0.75 + np.array([1, 0])),
(np.random.randn(50, 2) * 0.25 + np.array([-0.5, 0.5])),
(np.random.randn(50, 2) * 0.5 + np.array([-0.5, -0.5]))))
points.shape
plt.figure(figsize=(7,7))
plt.scatter(points[:, 0], points[:, 1])
plt.grid()
plt.... | 06_profiling/06_profiling.ipynb | mavillan/SciProg | gpl-3.0 |
And lest visualize the choosen (initial) centroids: | centroids = initialize_centroids(points, 3)
plt.figure(figsize=(7,7))
plt.scatter(points[:, 0], points[:, 1])
plt.scatter(centroids[:, 0], centroids[:, 1], c='r', s=100)
plt.grid()
plt.show() | 06_profiling/06_profiling.ipynb | mavillan/SciProg | gpl-3.0 |
The following function computes which is the closest centroid for each point in the dataset | def closest_centroid(points,centroids):
"""returns an array containing the index to the nearest centroid for each point"""
# computation of distance matrix
m = points.shape[0]
n = centroids.shape[0]
D = np.zeros((m,n))
for i in range(m):
for j in range(n):
D[i,j] = np.sqrt( n... | 06_profiling/06_profiling.ipynb | mavillan/SciProg | gpl-3.0 |
And the next function move/update the centroids according to the mean position of the cluster of points | def move_centroids(points, closest, centroids):
"""returns the new centroids assigned from the points closest to them"""
return np.array([points[closest==k].mean(axis=0) for k in range(centroids.shape[0])])
move_centroids(points, closest, centroids)
plt.subplot(121)
plt.scatter(points[:, 0], points[:, 1])
plt... | 06_profiling/06_profiling.ipynb | mavillan/SciProg | gpl-3.0 |
Now let's profile the execution of this funcion and its sub-functions calls. We use a set of $10000$ points now: | points = np.vstack(((np.random.randn(5000, 2) * 0.75 + np.array([1, 0])),
(np.random.randn(2500, 2) * 0.25 + np.array([-0.5, 0.5])),
(np.random.randn(2500, 2) * 0.5 + np.array([-0.5, -0.5]))))
%%prun -s cumulative -q -l 15 -T prun1
main_loop(points, centroids, 1000)
print(open('pru... | 06_profiling/06_profiling.ipynb | mavillan/SciProg | gpl-3.0 |
Clearly the problem is the closest_centroid function!. Now that we have isolated the problem, we do a line profile of this single function: | %lprun -T lprof2 -f closest_centroid closest_centroid(points, centroids)
print(open('lprof2', 'r').read()) | 06_profiling/06_profiling.ipynb | mavillan/SciProg | gpl-3.0 |
As you should suspect, the problem is that NumPy arrays are not meant to be iterated by Python, but we have to implement this algorithm in a vectorial way (or make it faster with Numba/Cython).
The next is a re-implementation of the algorithm, using native NumPy functions: | def closest_centroid(points, centroids):
"""returns an array containing the index to the nearest centroid for each point"""
px = points[:,0].reshape((-1,1))
py = points[:,1].reshape((-1,1))
Dx = px - centroids[:,0].reshape((1,-1))
Dy = py - centroids[:,1].reshape((1,-1))
# distance matrix
D ... | 06_profiling/06_profiling.ipynb | mavillan/SciProg | gpl-3.0 |
Let's profile again: | %%prun -s cumulative -q -l 15 -T prun2
main_loop(points, centroids, 1000)
print(open('prun2', 'r').read()) | 06_profiling/06_profiling.ipynb | mavillan/SciProg | gpl-3.0 |
Init | import glob
import pyfasta
import numpy as np
import pandas as pd
from collections import Counter
import matplotlib.pyplot as plt
import scipy.stats as ss
from fitter import Fitter
from functools import partial
%matplotlib inline
%load_ext rpy2.ipython
%%R
library(dplyr)
library(tidyr)
library(ggplot2)
if not o... | ipynb/bac_genome/SSU_genes_per_ng_DNA.ipynb | nick-youngblut/SIPSim | mit |
Size distribution of bacterial genomes | p = os.path.join(genomeDir, '*.fasta')
genomeFiles = glob.glob(p)
print 'Number of genome files: {}'.format(len(genomeFiles)) | ipynb/bac_genome/SSU_genes_per_ng_DNA.ipynb | nick-youngblut/SIPSim | mit |
Distribution of 16S gene copies per genome | total_seq_len = lambda x: sum([len(y) for y in x.values()])
def total_genome_lens(genome_files):
genome_lens = {}
for fasta in genome_files:
name = os.path.split(fasta)[-1]
name = os.path.splitext(name)[0]
pyf = pyfasta.Fasta(fasta)
genome_lens[name] = [total_seq_len(pyf)]
... | ipynb/bac_genome/SSU_genes_per_ng_DNA.ipynb | nick-youngblut/SIPSim | mit |
Fitting distribution | fo = Fitter(df_genome_len.ix[:,0])
fo.fit()
fo.summary()
genome_len_best_fit = fo.fitted_param['rayleigh']
genome_len_best_fit
# test of distribution
x = ss.rayleigh.rvs(*genome_len_best_fit, size=10000)
fig = plt.figure()
ax = plt.subplot(111)
ax.hist(x, bins=50)
fig.show() | ipynb/bac_genome/SSU_genes_per_ng_DNA.ipynb | nick-youngblut/SIPSim | mit |
Distribution of 16S gene copies per genome
rnammer run | %%bash -s "$genomeDir" "$rnammerDir"
find $1 -name "*fasta" | \
perl -pe 's/.+\/|\.fasta//g' | \
xargs -n 1 -I % -P 30 bash -c \
"rnammer -S bac -m ssu -gff $2/%_rrn.gff -f $2/%_rrn.fna -xml $2/%_rrn.xml < $1/%.fasta"
## Summarizing the results
!cd $rnammerDir; \
egrep -v "^#" *.gff | \
grep "16s... | ipynb/bac_genome/SSU_genes_per_ng_DNA.ipynb | nick-youngblut/SIPSim | mit |
Fitting distribution | fo = Fitter(ssu_count.values())
fo.fit()
fo.summary()
ssu_ray_fit = fo.fitted_param['rayleigh']
ssu_ray_fit
# test of distribution
x = ss.rayleigh.rvs(*ssu_ray_fit, size=10000)
fig = plt.figure()
ax = plt.subplot(111)
ax.hist(x, bins=50)
fig.show()
ssu_beta_fit = fo.fitted_param['beta']
ssu_beta_fit
# test of dist... | ipynb/bac_genome/SSU_genes_per_ng_DNA.ipynb | nick-youngblut/SIPSim | mit |
Notes
Using rayleigh distribution
Monte Carlo estimation of 16S gene copies per ng of DNA
M.W. of dsDNA = (# nucleotides x 607.4) + 157.9 | # example of calculations
gradient_DNA_conc = 1e-9 # g of DNA
avogadro = 6.022e23 # molecules/mole
genome_len = 4000000
mw_genome = genome_len * 607.4 + 157.9
n_genomes = gradient_DNA_conc / mw_genome * avogadro
ssu_copy_per_genome = 4
n_genomes * ssu_copy_per_genome
def SSU_copies_in_ng_DNA(DNA_conc, g... | ipynb/bac_genome/SSU_genes_per_ng_DNA.ipynb | nick-youngblut/SIPSim | mit |
Exercise: Now suppose you draw an M&M from bag2 and it's blue. What does that mean? Run the update to see what happens. | # Solution goes here | code/chap02.ipynb | NathanYee/ThinkBayes2 | gpl-2.0 |
Exercises
Exercise: This one is from one of my favorite books, David MacKay's "Information Theory, Inference, and Learning Algorithms":
Elvis Presley had a twin brother who died at birth. What is the probability that Elvis was an identical twin?"
To answer this one, you need some background information: According to... | # Solution goes here
# Solution goes here | code/chap02.ipynb | NathanYee/ThinkBayes2 | gpl-2.0 |
The sex and race columns contain potentially interesting information on how gun deaths in the US vary by gender and race. Exploring both of these columns can be done with a similar dictionary counting technique to what we did earlier. | sex_counts = {}
race_counts = {}
for each in data:
sex = each[5]
if sex in sex_counts:
sex_counts[sex] += 1
else:
sex_counts[sex] = 1
for each in data:
race = each[7]
if race in race_counts:
race_counts[race] += 1
else:
race_counts[race] = 1
print(race_counts)
p... | 1. Python (Intermediate) Exploring Gun Deaths in the US/Basics.ipynb | Fetisoff/Portfolio | apache-2.0 |
However, our analysis only gives us the total number of gun deaths by race in the US. Unless we know the proportion of each race in the US, we won't be able to meaningfully compare those numbers.
I want to get is a rate of gun deaths per 100000 people of each race | f = open ('census.csv', 'r')
census = list(csv.reader(f))
census
mapping = {
'Asian/Pacific Islander': int(census[1][14]) + int(census[1][15]),
'Black': int(census[1][12]),
'Native American/Native Alaskan': int(census[1][13]),
'Hispanic': int(census[1][11]),
'White': int(census[1][10])
}
race_per_h... | 1. Python (Intermediate) Exploring Gun Deaths in the US/Basics.ipynb | Fetisoff/Portfolio | apache-2.0 |
Finding
I have founded out, that some racial categories in USA have higher gun-related homicide rate than other races. For example, at least as evidenced by the statics, that people of Black rice commit gun-related homicide 10 times more people of White race or 4 times more people of Hispanic race.
Are the any link bet... | month_homicide_rate = {}
months = [int(each[2]) for each in data]
for i, each in enumerate(months):
if intents[i] == 'Homicide':
if each not in month_homicide_rate:
month_homicide_rate[each] = 0
else:
month_homicide_rate[each] += 1
month_homicide_rate
def months_diff(... | 1. Python (Intermediate) Exploring Gun Deaths in the US/Basics.ipynb | Fetisoff/Portfolio | apache-2.0 |
VA Top 15 violations by total revenue (revenue and total) | dc_df = df[(df.rp_plate_state.isin(['VA']))]
dc_fines = dc_df.groupby(['violation_code']).fine.sum().reset_index('violation_code')
fine_codes_15 = dc_fines.sort_values(by='fine', ascending=False)[:15]
top_codes = dc_df[dc_df.violation_code.isin(fine_codes_15.violation_code)]
top_violation_by_state = top_codes.groupby... | notebooks/Top 15 Violations by Revenue And Total for VA.ipynb | ndanielsen/dc_parking_violations_data | mit |
VA Top 15 violations by total tickets (revenue and total) | dc_df = df[(df.rp_plate_state.isin(['VA']))]
dc_fines = dc_df.groupby(['violation_code']).counter.sum().reset_index('violation_code')
fine_codes_15 = dc_fines.sort_values(by='counter', ascending=False)[:15]
top_codes = dc_df[dc_df.violation_code.isin(fine_codes_15.violation_code)]
top_violation_by_state = top_codes.g... | notebooks/Top 15 Violations by Revenue And Total for VA.ipynb | ndanielsen/dc_parking_violations_data | mit |
Convolution and Max Pooling Layer
Convolution layers have a lot of success with images. For this code cell, you should implement the function conv2d_maxpool to apply convolution then max pooling:
* Create the weight and bias using conv_ksize, conv_num_outputs and the shape of x_tensor.
* Apply a convolution to x_tensor... | def conv2d_maxpool(x_tensor, conv_num_outputs, conv_ksize, conv_strides, pool_ksize, pool_strides):
"""
Apply convolution then max pooling to x_tensor
:param x_tensor: TensorFlow Tensor
:param conv_num_outputs: Number of outputs for the convolutional layer
:param conv_strides: Stride 2-D Tuple for c... | image-classification/.ipynb_checkpoints/dlnd_image_classification-checkpoint.ipynb | elenduuche/deep-learning | mit |
Fully-Connected Layer
Implement the fully_conn function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). You can use TensorFlow Layers or TensorFlow Layers (contrib) for this layer. | def fully_conn(x_tensor, num_outputs):
"""
Apply a fully connected layer to x_tensor using weight and bias
: x_tensor: A 2-D tensor where the first dimension is batch size.
: num_outputs: The number of output that the new tensor should be.
: return: A 2-D tensor where the second dimension is num_out... | image-classification/.ipynb_checkpoints/dlnd_image_classification-checkpoint.ipynb | elenduuche/deep-learning | mit |
Output Layer
Implement the output function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). You can use TensorFlow Layers or TensorFlow Layers (contrib) for this layer.
Note: Activation, softmax, or cross entropy shouldn't be applied to this. | def output(x_tensor, num_outputs):
"""
Apply a output layer to x_tensor using weight and bias
: x_tensor: A 2-D tensor where the first dimension is batch size.
: num_outputs: The number of output that the new tensor should be.
: return: A 2-D tensor where the second dimension is num_outputs.
"""... | image-classification/.ipynb_checkpoints/dlnd_image_classification-checkpoint.ipynb | elenduuche/deep-learning | mit |
Create Convolutional Model
Implement the function conv_net to create a convolutional neural network model. The function takes in a batch of images, x, and outputs logits. Use the layers you created above to create this model:
Apply 1, 2, or 3 Convolution and Max Pool layers
Apply a Flatten Layer
Apply 1, 2, or 3 Full... | def conv_net(x, keep_prob):
"""
Create a convolutional neural network model
: x: Placeholder tensor that holds image data.
: keep_prob: Placeholder tensor that hold dropout keep probability.
: return: Tensor that represents logits
"""
# TODO: Apply 1, 2, or 3 Convolution and Max Pool layers
... | image-classification/.ipynb_checkpoints/dlnd_image_classification-checkpoint.ipynb | elenduuche/deep-learning | mit |
Reading the data | def loadContributions(file, withsexe=False):
contributions = pd.read_json(path_or_buf=file, orient="columns")
rows = [];
rindex = [];
for i in range(0, contributions.shape[0]):
row = {};
row['id'] = contributions['id'][i]
rindex.append(contributions['id'][i])
if (withsexe... | exploitation/analyse_quanti_theme2.ipynb | regardscitoyens/consultation_an | agpl-3.0 |
Permutation t-test on source data with spatio-temporal clustering
This example tests if the evoked response is significantly different between
two conditions across subjects. Here just for demonstration purposes
we simulate data from multiple subjects using one subject's data.
The multiple comparisons problem is addres... | # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Eric Larson <larson.eric.d@gmail.com>
# License: BSD-3-Clause
import os.path as op
import numpy as np
from numpy.random import randn
from scipy import stats as stats
import mne
from mne.epochs import equalize_epoch_counts
from mne.stats import (s... | 0.24/_downloads/ca1574468d033ed7a4e04f129164b25b/20_cluster_1samp_spatiotemporal.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Transform to common cortical space
Normally you would read in estimates across several subjects and morph
them to the same cortical space (e.g. fsaverage). For example purposes,
we will simulate this by just having each "subject" have the same
response (just noisy in source space) here.
<div class="alert alert-info"><h... | n_vertices_sample, n_times = condition1.data.shape
n_subjects = 6
print('Simulating data for %d subjects.' % n_subjects)
# Let's make sure our results replicate, so set the seed.
np.random.seed(0)
X = randn(n_vertices_sample, n_times, n_subjects, 2) * 10
X[:, :, :, 0] += condition1.data[:, :, np.newaxis]
X[:, :, :,... | 0.24/_downloads/ca1574468d033ed7a4e04f129164b25b/20_cluster_1samp_spatiotemporal.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Vorbereitung
Auswahl Vorbeifahrt und Abschnitt
Auswahl der Vorbeifahrt. Insgesamt haben wir die folgende passby IDs: | print('passby IDs:', list(passby.keys())) | DSP/auswertungLS.ipynb | e-sr/SDWirkungNi | cc0-1.0 |
Auswahl einer Abschnitt mit Lichtschranke:
Q1, Q4 | E = passby['14']['Q4']
#
print('Signal ID(with corresponding .mat file):', E['ID'])
LSignals = {'LS':E['signals']['LS']} | DSP/auswertungLS.ipynb | e-sr/SDWirkungNi | cc0-1.0 |
Detektion der Durchfahrtszeiten (tPeaks) jedes Drehgestell
Wenn die LS vom Rad abgedunket wird entsteht im Signal ein Peak. Damit lassen sich die Durchfahrtszeiten jedes drehgestell abschätzen. Die Funktion detect_weel_times implementiert die Berechnung. | tPeaks = detect_weel_times(LSignals['LS'], decimation = 8 ) | DSP/auswertungLS.ipynb | e-sr/SDWirkungNi | cc0-1.0 |
das Resultat ist in den nächsten Bild zu sehen | f,ax = plt.subplots()
LSignals['LS'].plot(ax=ax)
for tp in tPeaks:
ax.axvline(tp,color='red',alpha=0.5)
ax.set_xbound(tPeaks.min()-0.1, tPeaks.max()+0.1) | DSP/auswertungLS.ipynb | e-sr/SDWirkungNi | cc0-1.0 |
Mittelere und Änderung der Vorbeifahrtsgeschwindigkeit
Die Abschätzung erfolgt in zwei schritte und ist im train_speed funktion implementiert:
aus tPeaks lässt sich mithilfe der Abstand der Axen im Drehgestell die Geschwindigkeit jeder Drehgestell abschätzen.
Dann kann man mittels eine regression (robuste regression... | _,_,_ = train_speed(tPeaks, axleDistance=2, plot=True) | DSP/auswertungLS.ipynb | e-sr/SDWirkungNi | cc0-1.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.