markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
For more control over the output function, including the __doc__, __name__, and __signature__ attributes used by the help function, let's revisit the Block class to wrap the functionality seen so far. All together now As we've seen, all the information is available for a more informative way to manipulate and evaluate ...
b2 = Block('''c = cos(theta) s = sin(theta) x' = x*c - y*s y' = x*s + y*c ''', '2-D Rotate', 'x y theta', "x' y'") print('\n',vars(b2))
files/Process.ipynb
jimaples/jimaples.github.io
mit
When it comes to function arguments, Python 3.5 has had a lot of development beyond Python 2.7. Since the Block code was originally developed in Python 2.7, let's replace those _Dummy arguments from sympy.lambdify.
f = b2.lambdify() help(f["x'"]) # All lambdify calls are made with the full set of inputs p = [] # Update the signatures for each compiled expression for k in f.keys(): sig=inspect.signature(f[k]) if len(p) == 0: for i,s in zip(sig.parameters.values(), map(str, b2.ins)): p.append(i.replace...
files/Process.ipynb
jimaples/jimaples.github.io
mit
And since it's coming up, let's go ahead and improve the Block.eval function used to call the various lambdify functions. Extra credit to anyone who figures out why I couldn't do the same sort of __signature__ update without getting a NameError exception.
help(b2._eval) help(b2.eval) # Backup the old functions b2._eval_save = b2.eval Block._wrap_eval_save = Block._wrap_eval # instead of wrapping _eval, just update its help info def wrap_eval(self): '''create _eval() wrapper function with useful docstring''' def tuple_repr(i): if type(i) == tuple: ...
files/Process.ipynb
jimaples/jimaples.github.io
mit
The outputs were specified when the Block instance was created, so lambdify all of those.
f = b2.lambdify() f, b2.lambdas help(f["x'"])
files/Process.ipynb
jimaples/jimaples.github.io
mit
The functions were made using sympy.lambdify, so they get all the benefits like support for NumPy arrays. The Block class also has an eval function to use that calls all the lambdify results.
out = f["x'"](1,0,np.linspace(0, np.pi, 8+1)) print(out, type(out)) help(b2.eval) b2.eval(1,0,np.linspace(0, np.pi, 8+1))
files/Process.ipynb
jimaples/jimaples.github.io
mit
Potential Updates: Set of 2 or more blocks with interconnects Solve for selected outputs Solve for selected inputs Draw interconnect diagram Create interface tables Unnecessary Pictures Because figures are fun. Using the 2-D rotation, we can rotate a constellation of points to best match expectations. Links: Top Int...
from matplotlib import pyplot as plt from matplotlib import cm from matplotlib import colors # for IPython plotting %pylab inline # random (x,y) points xy1 = np.random.normal(0,0.5,(8,2)) x,y = np.hsplit(xy1,2) # rotate points on a log-scale a = [0]+np.logspace(-2,1,20,base=5) b2.verbose = False xy2 = b2.eval(x,y,a) ...
files/Process.ipynb
jimaples/jimaples.github.io
mit
More Information SymPy Help Links: Top Intro Text LaTeX Solver Evaluating Designs Help sympy.*.subs(*args, **kwargs) sympy.lambdify(args, expr, modules=None)
print(type(b.eqn[0]),'\n') help(b.eqn[0].subs) help(sympy.lambdify)
files/Process.ipynb
jimaples/jimaples.github.io
mit
Upgrading Code to Python 3 I originally made this notebook using Python 2.7. Fortunately, there's a Python library for that too lib2to3, although the canned 2to3 application worked just fine for me. Although this doesn't usually change functionality, there may be some slight changes as seen when running help on the s...
%%file process.py import sympy import numpy as np def parseExpr(expr=''): '''Helper function to iterate through a list of equations''' err = 'Malformed expression! Does not match "y = f(x)"\n {0:s}' for s in expr.strip().split('\n'): # Parse anything that looks like an equation and isn't commented...
files/Process.ipynb
jimaples/jimaples.github.io
mit
Let's test the conversion of the rewritten Python 2.7 code
!2to3 -w process.py
files/Process.ipynb
jimaples/jimaples.github.io
mit
Success!
from process import * for s in (parseExpr, Block): help(s)
files/Process.ipynb
jimaples/jimaples.github.io
mit
Interesting Links / References Python and Jupyter Notebooks SymPy and LaTeX SciPy and matplotlib Python and Jupyter Notebooks Markdown syntax Notebook reveal-based slideshow tutorial A brief tour of the IPython notebook: Same presentation, just later on 2to3 - Automated Python 2 to 3 code translation But do I really ...
%%file slides.bat jupyter nbconvert --to slides Process.ipynb --post serve
files/Process.ipynb
jimaples/jimaples.github.io
mit
First, we'll load the dataset from scikit-learn. The Iris Dataset contains 3 classes for each of the iris species (iris setosa, iris virginica, and iris versicolor). It has 50 samples per class with 150 samples in total, making it a very balanced dataset. Each sample is characterized by four features (or dimensions): s...
data = load_iris() # Store the features as X and the labels as y X = data.data y = data.target
docs/examples/usecases/train_neural_network.ipynb
ljvmiranda921/pyswarms
mit
Constructing a custom objective function Recall that neural networks can simply be seen as a mapping function from one space to another. For now, we'll build a simple neural network with the following characteristics: * Input layer size: 4 * Hidden layer size: 20 (activation: $\tanh(x)$) * Output layer size: 3 (activat...
n_inputs = 4 n_hidden = 20 n_classes = 3 num_samples = 150 def logits_function(p): """ Calculate roll-back the weights and biases Inputs ------ p: np.ndarray The dimensions should include an unrolled version of the weights and biases. Returns ------- numpy.ndarra...
docs/examples/usecases/train_neural_network.ipynb
ljvmiranda921/pyswarms
mit
Now that we have a method to do forward propagation for one particle (or for one set of dimensions), we can then create a higher-level method to compute forward_prop() to the whole swarm:
def f(x): """Higher-level method to do forward_prop in the whole swarm. Inputs ------ x: numpy.ndarray of shape (n_particles, dimensions) The swarm that will perform the search Returns ------- numpy.ndarray of shape (n_particles, ) The computed loss for eac...
docs/examples/usecases/train_neural_network.ipynb
ljvmiranda921/pyswarms
mit
Performing PSO on the custom-function Now that everything has been set-up, we just call our global-best PSO and run the optimizer as usual. For now, we'll just set the PSO parameters arbitrarily.
%%time # Initialize swarm options = {'c1': 0.5, 'c2': 0.3, 'w':0.9} # Call instance of PSO dimensions = (n_inputs * n_hidden) + (n_hidden * n_classes) + n_hidden + n_classes optimizer = ps.single.GlobalBestPSO(n_particles=100, dimensions=dimensions, options=options) # Perform optimization cost, pos = optimizer.optim...
docs/examples/usecases/train_neural_network.ipynb
ljvmiranda921/pyswarms
mit
Checking the accuracy We can then check the accuracy by performing forward propagation once again to create a set of predictions. Then it's only a simple matter of matching which one's correct or not. For the logits, we take the argmax. Recall that the softmax function returns probabilities where the whole vector sums ...
def predict(pos): """ Use the trained weights to perform class predictions. Inputs ------ pos: numpy.ndarray Position matrix found by the swarm. Will be rolled into weights and biases. """ logits = logits_function(pos) y_pred = np.argmax(logits, axis=1) return y_...
docs/examples/usecases/train_neural_network.ipynb
ljvmiranda921/pyswarms
mit
And from this we can just compute for the accuracy. We perform predictions, compare an equivalence to the ground-truth value y, and get the mean.
(predict(pos) == y).mean()
docs/examples/usecases/train_neural_network.ipynb
ljvmiranda921/pyswarms
mit
In order account for initial out-of-straightness and partial yielding, notional lateral loads equal to 0.005 times the factored gravity loads contributed by each level are added to each level (CSA S16-09 8.4.1). At node H that will be $45 \times (10+10.5+10) \times 0.005 = 6.9\ kN$ and at node G it is $55 \times (10+1...
frame = f2d.Frame2D() frame.read_data('KG82') # read the CSV files in directory 'KG82.d' %matplotlib inline frame.plot() frame.doall() frame.saveStructuralData(frame.dsname)
Devel/Old/frame2d-v03/example-KG82.ipynb
nholtz/structural-analysis
cc0-1.0
The above are the results of a first-order analysis and should be compared with those shown in the following figure from Kulak & Grondin: Compare book values (end bending moments)
import pandas as pd BM = [('AB',44.2,-57.5), # values given on figure, above ('BC',-232.,-236.), ('DE',181.,227.), ('EF',287.,330.), ('BE',290.,-515.), ('CF',236.,-330.)] BOOK = pd.DataFrame({m:{'MZJ':a,'MZK':b} for m,a,b in BM}).T BOOK R = frame.get_mefs() # get our member end...
Devel/Old/frame2d-v03/example-KG82.ipynb
nholtz/structural-analysis
cc0-1.0
% Difference in End Moments
m = R[['MZJ','MZK']]*1E-6 (100*(m - BOOK[['MZJ','MZK']])/m).round(2)
Devel/Old/frame2d-v03/example-KG82.ipynb
nholtz/structural-analysis
cc0-1.0
Max. difference is 5.5%, which I think is a little large.
frame.get_reactions()[['FY']]*1E-3
Devel/Old/frame2d-v03/example-KG82.ipynb
nholtz/structural-analysis
cc0-1.0
The reactions agree very closely. $P-\Delta$ Analysis
frame.doall(pdelta=True,showinput=False)
Devel/Old/frame2d-v03/example-KG82.ipynb
nholtz/structural-analysis
cc0-1.0
The above are the results of a second-order ($P-\Delta$) analysis and should be compared with the following figure from Kulak & Grondin:
import pandas as pd BM = [('AB',64.0,-39.2), # values given on gigure, above ('BC',-236.,-237.), ('DE',207.,244.), ('EF',301.,347.), ('BE',276.,-544.), ('CF',237.,-347.)] BOOK = pd.DataFrame({m:{'MZJ':a,'MZK':b} for m,a,b in BM}).T BOOK R = frame.get_mefs() # get our member end...
Devel/Old/frame2d-v03/example-KG82.ipynb
nholtz/structural-analysis
cc0-1.0
Request the open events from the Meetup.com API.
r = requests.get("https://api.meetup.com/2/open_events", params={'topic': TOPIC, 'key': API_KEY}) r.raise_for_status() df = pd.DataFrame(r.json()['results'])
notebooks/document.ipynb
ibm-et/defrag2015
mit
Convert the times since epoch in $\mu s$ to datetime objects, accounting for timezone offset. Hereafter, the times will be local to the meetup venue.
df['localtime'] = pd.to_datetime(df.time+df.utc_offset, unit='ms')
notebooks/document.ipynb
ibm-et/defrag2015
mit
Create a human readable description of the location down to the city level, if possible.
def text_location(venue): ''' Return city, state, country, omitting any piece that isn't available. ''' loc = [] if pd.isnull(venue): return '' if 'city' in venue: loc.append(venue['city']) if 'state' in venue: loc.append(venue['state']) if 'country' in venue: loc...
notebooks/document.ipynb
ibm-et/defrag2015
mit
Turn the event name into a link to its page on meetup.com.
df['link_name'] = df.apply(lambda row: '<a href="{row[event_url]}" target="_blank">{row[name]}</a>'.format(row=row), axis=1)
notebooks/document.ipynb
ibm-et/defrag2015
mit
Use the HTML output feature instead of static markup so that the topic name appears.
HTML('<h2>Table of Upcoming <em>{}</em> Meetups</h2>'.format(TOPIC)) HTML(df[['link_name', 'localtime', 'location', 'yes_rsvp_count']].to_html(escape=False)) HTML('<h2>Map of Upcoming <em>{}</em> Meetups</h2>'.format(TOPIC)) def map_marker(row): ''' Returns a dictionary with the lat/long location of an event...
notebooks/document.ipynb
ibm-et/defrag2015
mit
Idea: We might want show the venues of RSVPs in realtime on a map along with the locations of our meetups.
HTML('<iframe srcdoc="{srcdoc}" style="width: 100%; height: 510px; border: none"></iframe>'.format(srcdoc=m.HTML.replace('"', '&quot;')))
notebooks/document.ipynb
ibm-et/defrag2015
mit
Filling the Swear Jar A tale of three languages Alec Reiter (@justanr) Brainfuck Urban Mueller, 1993 Turning ~~Complete~~ Tarpit 8 commands Tape, Tape Pointer, Instruction Pointer ++++++++[&gt;++++[&gt;++&gt;+++&gt;+++&gt;+&lt;&lt;&lt;&lt;-]&gt;+&gt;+&gt;-&gt;&gt;+[&lt;]&lt;-]&gt;&gt;.&gt;---.+++++++..+++.&gt;&gt;.&l...
def run(prog: str, stdin: str="") -> StringIO: stdout = StringIO() memory = [0] * 30_000 memptr = 0 instrptr = 0 progsize = len(prog) # stores the location of the last [ s we encountered brackets = [] while instrptr < progsize: op = progsize[instrptr] instrptr += 1 ...
fillingtheswearjar.ipynb
justanr/notebooks
mit
Pros Very simple Jumping back is easy Cons Very naive Jumping forward isn't easy Incorrect programs not detected Parsing
class BFToken(Enum): Incr = '+' Decr = '-' MoveL = '<' MoveR = '>' StdIn = ',' StdOut = '.' JumpF = '[' JumpB = ']' partners = { BFToken.Incr: BFToken.Decr, BFToken.Decr: BFToken.Incr, BFToken.MoveL: BFToken.MoveR, BFToken.MoveR: BFToken.MoveL } def _parse(prog: str) ->...
fillingtheswearjar.ipynb
justanr/notebooks
mit
Optimizing Jump table Combine like tokens
def collapse(prog: List[BFToken]) -> List[BFToken]: program = [] for token in prog: ... # uh wait a second
fillingtheswearjar.ipynb
justanr/notebooks
mit
Missing Something
class IRToken(NamedTuple): token: BFToken amount: int def collapse(prog: List[BFToken]) -> List[IRToken]: program: List[IRToken] = [] for token in prog: if len(program) == 0 or token not in partners: program.append(IRToken(token, 1)) continue previo...
fillingtheswearjar.ipynb
justanr/notebooks
mit
Where are we spending time? [ I-1 ] 26_000_000 [ M1 I10 [ I-1 ] M-1 I-1 ] -&gt; 2_600_000 [ M1 I10 [ M1 I10 [ I-1 ] M-1 I-1 ] M-1 I-1 ] -&gt; 260_000 [ M1 I10 [ M1 I10 [ M1 I10 [ I-1 ] M-1 I-1 ] M-1 I-1 ] M-1 I-1 ] -&gt; 26_000 [ M1 I10 [ M1 I10 [ M1 I10 [ M1 I10 [ I-1 ] M-1 I-1 ] M-1 I-1 ] M-1 I-1 ] M-1 I-1 ] -&gt; 2_...
def handle_clear(tokens: List[BFToken]) -> List[BFToken]: program: List[BFToken] = [] clear = [BFToken.JumpF, BFToken.Decr, BFToken.JumpB] for token in tokens: program.append(token) if len(program) < 3: continue last_three = program[-3:] ...
fillingtheswearjar.ipynb
justanr/notebooks
mit
38min 34s Python isn't known for being fast Cython, numba, etc can help but... Rust 🎺🎺🎺 insert hype here But seriously Opt-in mutability Algebraic Data Types Functional + Imperative High level but fast Representation rust enum BrainFuckToken { Move(isize), JumpF(usize), JumpB(usize), Incr(i32) ...
%%bash time ./bf triangle.bf > /dev/null %%bash time ./bf ZtoA.bf > /dev/null %%bash time ./bf mandel.bf > /dev/null
fillingtheswearjar.ipynb
justanr/notebooks
mit
We can clear the output by either using IPython.display.clear_output within the context manager, or we can call the widget's clear_output method directly.
out.clear_output()
docs/source/examples/Output Widget.ipynb
jupyter-widgets/ipywidgets
bsd-3-clause
Interacting with output widgets from background threads Jupyter's display mechanism can be counter-intuitive when displaying output produced by background threads. A background thread's output is printed to whatever cell the main thread is currently writing to. To see this directly, create a thread that repeatedly prin...
import threading from IPython.display import display, HTML import ipywidgets as widgets import time def thread_func(something, out): for i in range(1, 5): time.sleep(0.3) out.append_stdout('{} {} {}\n'.format(i, '**'*i, something)) out.append_display_data(HTML("<em>All done!</em>")) display('D...
docs/source/examples/Output Widget.ipynb
jupyter-widgets/ipywidgets
bsd-3-clause
Vertex client library: Local text binary classification model for online prediction <table align="left"> <td> <a href="https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/master/notebooks/community/gapic/custom/showcase_local_text_binary_classification_online.ipynb"> <img src...
import os import sys # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install -U google-cloud-aiplatform $USER_FLAG
notebooks/community/gapic/custom/showcase_local_text_binary_classification_online.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Tutorial Now you are ready to start locally training a custom model IMDB Movie Reviews, and then deploy the model to the cloud. Set up clients The Vertex client library works as a client/server model. On your side (the Python script) you will create a client that sends requests and receives responses from the Vertex se...
# client options same for all services client_options = {"api_endpoint": API_ENDPOINT} def create_model_client(): client = aip.ModelServiceClient(client_options=client_options) return client def create_endpoint_client(): client = aip.EndpointServiceClient(client_options=client_options) return client...
notebooks/community/gapic/custom/showcase_local_text_binary_classification_online.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Train a model locally In this tutorial, you train a IMDB Movie Reviews model locally. Set location to store trained model You set the variable MODEL_DIR for where in your Cloud Storage bucket to save the model in TensorFlow SavedModel format. Also, you create a local folder for the training script.
MODEL_DIR = BUCKET_NAME + "/imdb" model_path_to_deploy = MODEL_DIR ! rm -rf custom ! mkdir custom ! mkdir custom/trainer
notebooks/community/gapic/custom/showcase_local_text_binary_classification_online.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
通常,所有的权重都是可以训练的权重。keras自动的layer中只有BatchNormalization有不可训练的权重。BatchNormalization使用不可训练的权重来跟踪训练过程中输入的mean和variance。 学习在自定义layers,如何使用不可训练权重,请看 guide to writing new layers from scratch. In general, all weights are trainable weights. The only built-in layer that has non-trainable weights is the BatchNormalization layer. It...
layer = keras.layers.BatchNormalization() layer.build((None, 4)) # Create the weights print("weights:", len(layer.weights)) print("trainable_weights:", len(layer.trainable_weights)) print("non_trainable_weights:", len(layer.non_trainable_weights))
tensorflow_learning/tf2/notebooks/.ipynb_checkpoints/transfer_learning-中文-checkpoint-checkpoint.ipynb
jeffzhengye/pylearn
unlicense
Find a genome and download the annotations You need to find your genome in PATRIC and download the annotations. Once you have identified the genome you would like to build the model for, choose Feature Table from the menu bar: <img src="img/patric_ft.png"> Next, choose Download and save as a text file (.txt). <img src...
assigned_functions = {} with open(os.path.join('workspace/Citrobacter_sedlakii_genome_features.txt'), 'r') as f: for l in f: p=l.strip().split("\t") assigned_functions[p[3]]=PyFBA.parse.roles_of_function(p[19]) roles = set([i[0] for i in [list(j) for j in assigned_functions.values()]]) print("There ...
iPythonNotebooks/PATRIC to FBA.ipynb
linsalrob/PyFBA
mit
Next, we convert those roles to reactions. We start with a dict of roles and reactions, but we only need a list of unique reactions, so we convert the keys to a set.
roles_to_reactions = PyFBA.filters.roles_to_reactions(roles, organism_type="Gram_Negative", verbose=False)
iPythonNotebooks/PATRIC to FBA.ipynb
linsalrob/PyFBA
mit
If you toggle verbose=True, you will see that there are a lot of roles that we skip, even though we have an EC number for them: for whatever reason, the annotation is not quite right. We can check for those too, because our model seed parsed data has EC numbers with reactions.
# ecr2r = PyFBA.filters.roles_to_ec_reactions(roles, organism_type="Gram_Negative", verbose=False) ecr2r = set()
iPythonNotebooks/PATRIC to FBA.ipynb
linsalrob/PyFBA
mit
We combine roles_to_reactions and ecr2r and figure out what the unique set of reactions is for our genome.
roles_to_reactions.update(ecr2r) reactions_to_run = set() for role in roles_to_reactions: reactions_to_run.update(roles_to_reactions[role]) print("There are {}".format(len(reactions_to_run)) + " unique reactions associated with this genome".format(len(reactions_to_run)))
iPythonNotebooks/PATRIC to FBA.ipynb
linsalrob/PyFBA
mit
Read all the reactions and compounds in our database We read all the reactions, compounds, and enzymes in the ModelSEEDDatabase into three data structures. Note, the first time you call this it is a bit slow as it has to parse the files, but if we've parsed them once, we don't need to do it again! We modify the reactio...
compounds, reactions, enzymes = \ PyFBA.parse.model_seed.compounds_reactions_enzymes('gramnegative') print(f"There are {len(compounds):,} compounds, {len(reactions):,} reactions, and {len(enzymes):,} enzymes in total") for r in reactions: for c in reactions[r].all_compounds(): if c.uptake_secretion: ...
iPythonNotebooks/PATRIC to FBA.ipynb
linsalrob/PyFBA
mit
Update reactions to run, making sure that all reactions are in the list! There are some reactions that come from functional roles that do not appear in the reactions list. We're working on tracking these down, but for now we just check that all reaction IDs in reactions_to_run are in reactions, too.
tempset = set() for r in reactions_to_run: if r in reactions: tempset.add(r) else: sys.stderr.write("Reaction ID {} is not in our reactions list. Skipped\n".format(r)) reactions_to_run = tempset
iPythonNotebooks/PATRIC to FBA.ipynb
linsalrob/PyFBA
mit
Test whether these reactions grow on ArgonneLB media We can test whether this set of reactions grows on ArgonneLB media. The media is the same one we used above, and you can download the ArgonneLB.txt and text file and put it in the same directory as this iPython notebook to run it. (Note: we don't need to convert the ...
media = PyFBA.parse.read_media_file("/home/redwards/test_media/ArgonneLB.txt") print("Our media has {} components".format(len(media)))
iPythonNotebooks/PATRIC to FBA.ipynb
linsalrob/PyFBA
mit
Define a biomass equation The biomass equation is the part that says whether the model will grow! This is a metabolism.reaction.Reaction object.
biomass_equation = PyFBA.metabolism.biomass_equation() biomass_equation.equation with open('rbad.txt', 'w') as out: for r in reactions_to_run: out.write(f"{r}\n")
iPythonNotebooks/PATRIC to FBA.ipynb
linsalrob/PyFBA
mit
Run the FBA With the reactions, compounds, reactions_to_run, media, and biomass model, we can test whether the model grows on this media.
print(f"Before running FBA there are {len(reactions)} reactions") status, value, growth = PyFBA.fba.run_fba(compounds, reactions, reactions_to_run, media, biomass_equation) print(f"After running FBA there are {len(reactions)} reactions") print("Initial run has a biomass flux va...
iPythonNotebooks/PATRIC to FBA.ipynb
linsalrob/PyFBA
mit
Will gap filling work? These are the reactions from the C. sedlakii SBML file, and so if we add these, we should get growth!
sbml_addnl = {'rxn00868', 'rxn01923', 'rxn02268', 'rxn10215', 'rxn10219', 'rxn08089', 'rxn10212', 'rxn08083', 'rxn10214', 'rxn10211', 'rxn10218', 'rxn08086', 'rxn10217', 'rxn08087', 'rxn08088', 'rxn08085', 'rxn10216', 'rxn08084', 'rxn10213', 'rxn05572', 'rxn05565', 'rxn00541', 'rxn10155', 'rxn10157', 'rxn05536', 'rxn05...
iPythonNotebooks/PATRIC to FBA.ipynb
linsalrob/PyFBA
mit
it is the biomass model that is the problem Lets take the biomass model from the SBML and see if this work.
sbml_equation = '(0.00778132482043096) cpd00063: Ca2 (location: c) + (0.352889948968272) cpd00156: L_Valine (location: e) + (0.00778132482043096) cpd00030: Mn2 (location: e) + (0.00778132482043096) cpd00205: K (location: c) + (0.428732289454499) cpd00035: L_Alanine (location: e) + (0.128039715997337) cpd00060: L_M...
iPythonNotebooks/PATRIC to FBA.ipynb
linsalrob/PyFBA
mit
Add the missing reactions
all_reactions = {'rxn00868', 'rxn01923', 'rxn02268', 'rxn10215', 'rxn10219', 'rxn08089', 'rxn10212', 'rxn08083', 'rxn10214', 'rxn10211', 'rxn10218', 'rxn08086', 'rxn10217', 'rxn08087', 'rxn08088', 'rxn08085', 'rxn10216', 'rxn08084', 'rxn10213', 'rxn05572', 'rxn05565', 'rxn00541', 'rxn10155', 'rxn10157', 'rxn05536', 'rx...
iPythonNotebooks/PATRIC to FBA.ipynb
linsalrob/PyFBA
mit
Media import reactions We need to make sure that the cell can import everything that is in the media... otherwise it won't be able to grow. Be sure to only do this step if you are certain that the cell can grow on the media you are testing.
update_type = 'media' new_reactions = PyFBA.gapfill.suggest_from_media(compounds, reactions, reactions_to_run, media, verbose=True) added_reactions.append((update_type, new_reactions)) print(f"Before adding {update_type} reactions, we had {len(reactions_to_run)} react...
iPythonNotebooks/PATRIC to FBA.ipynb
linsalrob/PyFBA
mit
Essential reactions There are ~100 reactions that are in every model we have tested, and we construe these to be essential for all models, so we typically add these next!
update_type = 'essential' new_reactions = PyFBA.gapfill.suggest_essential_reactions() added_reactions.append((update_type, new_reactions)) print(f"Before adding {update_type} reactions, we had {len(reactions_to_run)} reactions.") reactions_to_run.update(new_reactions) print(f"After adding {update_type} reactions, we ha...
iPythonNotebooks/PATRIC to FBA.ipynb
linsalrob/PyFBA
mit
Subsystems The reactions connect us to subsystems (see Overbeek et al. 2014), and this test ensures that all the subsystems are complete. We add reactions required to complete the subsystem.
update_type = 'subsystems' new_reactions = \ PyFBA.gapfill.suggest_reactions_from_subsystems(reactions, reactions_to_run, threshold=0.5) added_reactions.append((update_type, new_reactions)) print(f"Before adding ...
iPythonNotebooks/PATRIC to FBA.ipynb
linsalrob/PyFBA
mit
Orphan compounds Orphan compounds are those compounds which are only associated with one reaction. They are either produced, or trying to be consumed. We need to add reaction(s) that complete the network of those compounds. You can change the maximum number of reactions that a compound is in to be considered an orphan ...
update_type = 'orphan compounds' new_reactions = PyFBA.gapfill.suggest_by_compound(compounds, reactions, reactions_to_run, max_reactions=1) added_reactions.append((update_type, new_reactions)) print(f"Before adding...
iPythonNotebooks/PATRIC to FBA.ipynb
linsalrob/PyFBA
mit
Trimming the model Now that the model has been shown to grow on ArgonneLB media after several gap-fill iterations, we should trim down the reactions to only the required reactions necessary to observe growth.
reqd_additional = set() # Begin loop through all gap-filled reactions while added_reactions: ori = copy.copy(original_reactions_to_run) ori.update(reqd_additional) # Test next set of gap-filled reactions # Each set is based on a method described above how, new = added_reactions.pop() sys.stderr...
iPythonNotebooks/PATRIC to FBA.ipynb
linsalrob/PyFBA
mit
3. Reading a CSV file and doing common Pandas operations
regiones_file='data/chile_regiones.csv' provincias_file='data/chile_provincias.csv' comunas_file='data/chile_comunas.csv' regiones=pd.read_csv(regiones_file, header=0, sep=',') provincias=pd.read_csv(provincias_file, header=0, sep=',') comunas=pd.read_csv(comunas_file, header=0, sep=',') print('regiones table: ', reg...
clase_1/02 - Lectura de datos con Pandas.ipynb
rpmunoz/topicos_ingenieria_1
gpl-3.0
4. Loading ful dataset
data_file='data/chile_demographic.csv' data=pd.read_csv(data_file, header=0, sep=',') data data.sort_values('Poblacion') data.sort_values('Poblacion', ascending=False) (data.groupby(['Region'])['Poblacion','Superficie'].sum()) (data.groupby(['Region'])['Poblacion','Superficie'].sum()).sort_values('Poblacion', ascen...
clase_1/02 - Lectura de datos con Pandas.ipynb
rpmunoz/topicos_ingenieria_1
gpl-3.0
pandas will let us read the data. scikit-learn is the machine learning library matplotlib will let us visualize our model and data Read the Data
# read data dataframe = pd.read_fwf('brain_body.txt') x_values = dataframe[['Brain']] y_values = dataframe[['Body']]
01.neural_network/01.first_neural_net-linear_regression_1/01.linear_regression_1.ipynb
hadibakalim/deepLearning
mit
Train model on the Data
body_reg = linear_model.LinearRegression() body_reg.fit(x_values, y_values)
01.neural_network/01.first_neural_net-linear_regression_1/01.linear_regression_1.ipynb
hadibakalim/deepLearning
mit
Visualize results
plt.scatter(x_values, y_values) plt.plot(x_values, body_reg.predict(x_values)) plt.show()
01.neural_network/01.first_neural_net-linear_regression_1/01.linear_regression_1.ipynb
hadibakalim/deepLearning
mit
&larr; Back to Index Autocorrelation The autocorrelation of a signal describes the similarity of a signal against a time-shifted version of itself. For a signal $x$, the autocorrelation $r$ is: $$ r(k) = \sum_n x(n) x(n-k) $$ In this equation, $k$ is often called the lag parameter. $r(k)$ is maximized at $k = 0$ and is...
x, sr = librosa.load('audio/c_strum.wav') ipd.Audio(x, rate=sr) plt.figure(figsize=(14, 5)) librosa.display.waveplot(x, sr)
autocorrelation.ipynb
stevetjoa/stanford-mir
mit
numpy.correlate There are two ways we can compute the autocorrelation in Python. The first method is numpy.correlate:
# Because the autocorrelation produces a symmetric signal, we only care about the "right half". r = numpy.correlate(x, x, mode='full')[len(x)-1:] print(x.shape, r.shape)
autocorrelation.ipynb
stevetjoa/stanford-mir
mit
Plot the autocorrelation:
plt.figure(figsize=(14, 5)) plt.plot(r[:10000]) plt.xlabel('Lag (samples)') plt.xlim(0, 10000)
autocorrelation.ipynb
stevetjoa/stanford-mir
mit
librosa.autocorrelate The second method is librosa.autocorrelate:
r = librosa.autocorrelate(x, max_size=10000) print(r.shape) plt.figure(figsize=(14, 5)) plt.plot(r) plt.xlabel('Lag (samples)') plt.xlim(0, 10000)
autocorrelation.ipynb
stevetjoa/stanford-mir
mit
librosa.autocorrelate conveniently only keeps one half of the autocorrelation function, since the autocorrelation is symmetric. Also, the max_size parameter prevents unnecessary calculations. Pitch Estimation The autocorrelation is used to find repeated patterns within a signal. For musical signals, a repeated pattern ...
x, sr = librosa.load('audio/oboe_c6.wav') ipd.Audio(x, rate=sr)
autocorrelation.ipynb
stevetjoa/stanford-mir
mit
Compute and plot the autocorrelation:
r = librosa.autocorrelate(x, max_size=5000) plt.figure(figsize=(14, 5)) plt.plot(r[:200])
autocorrelation.ipynb
stevetjoa/stanford-mir
mit
The autocorrelation always has a maximum at zero, i.e. zero lag. We want to identify the maximum outside of the peak centered at zero. Therefore, we might choose only to search within a range of reasonable pitches:
midi_hi = 120.0 midi_lo = 12.0 f_hi = librosa.midi_to_hz(midi_hi) f_lo = librosa.midi_to_hz(midi_lo) t_lo = sr/f_hi t_hi = sr/f_lo print(f_lo, f_hi) print(t_lo, t_hi)
autocorrelation.ipynb
stevetjoa/stanford-mir
mit
Set invalid pitch candidates to zero:
r[:int(t_lo)] = 0 r[int(t_hi):] = 0 plt.figure(figsize=(14, 5)) plt.plot(r[:1400])
autocorrelation.ipynb
stevetjoa/stanford-mir
mit
Find the location of the maximum:
t_max = r.argmax() print(t_max)
autocorrelation.ipynb
stevetjoa/stanford-mir
mit
Finally, estimate the pitch in Hertz:
float(sr)/t_max
autocorrelation.ipynb
stevetjoa/stanford-mir
mit
Indeed, that is very close to the true frequency of C6:
librosa.midi_to_hz(84)
autocorrelation.ipynb
stevetjoa/stanford-mir
mit
cost <img style="float: left;" src="../img/linear_cost.png">
theta = np.ones(X.shape[1]) lr.cost(theta, X, y)
ex5-bias vs variance/2- regularization of linear regression.ipynb
icrtiou/coursera-ML
mit
regularized cost <img style="float: left;" src="../img/linear_reg_cost.png">
lr.regularized_cost(theta, X, y)
ex5-bias vs variance/2- regularization of linear regression.ipynb
icrtiou/coursera-ML
mit
gradient <img style="float: left;" src="../img/linear_gradient.png">
lr.gradient(theta, X, y)
ex5-bias vs variance/2- regularization of linear regression.ipynb
icrtiou/coursera-ML
mit
regularized gradient <img style="float: left;" src="../img/linear_reg_gradient.png">
lr.regularized_gradient(theta, X, y)
ex5-bias vs variance/2- regularization of linear regression.ipynb
icrtiou/coursera-ML
mit
fit the data regularization term $\lambda=0$
theta = np.ones(X.shape[0]) final_theta = lr.linear_regression_np(X, y, l=0).get('x') b = final_theta[0] # intercept m = final_theta[1] # slope plt.scatter(X[:,1], y, label="Training data") plt.plot(X[:, 1], X[:, 1]*m + b, label="Prediction") plt.legend(loc=2)
ex5-bias vs variance/2- regularization of linear regression.ipynb
icrtiou/coursera-ML
mit
The global collection of tide gauge records at the PSMSL is used to access the data. The other way to access the data is to ask the service desk data at Rijkswaterstaat. There are two types of datasets the "Revised Local Reference" and "Metric". For the Netherlands the difference is that the "Revised Local Reference" u...
urls = { 'metric_monthly': 'http://www.psmsl.org/data/obtaining/met.monthly.data/met_monthly.zip', 'rlr_monthly': 'http://www.psmsl.org/data/obtaining/rlr.annual.data/rlr_monthly.zip', 'rlr_annual': 'http://www.psmsl.org/data/obtaining/rlr.annual.data/rlr_annual.zip' } dataset_name = 'rlr_annual' # these c...
sealevelmonitor.ipynb
openearth/notebooks
gpl-3.0
Now that we have defined which tide gauges we are monitoring we can start downloading the relevant data.
# each station has a number of files that you can look at. # here we define a template for each filename # stations that we are using for our computation # define the name formats for the relevant files names = { 'datum': '{dataset}/RLR_info/{id}.txt', 'diagram': '{dataset}/RLR_info/{id}.png', 'url': 'http...
sealevelmonitor.ipynb
openearth/notebooks
gpl-3.0
Now that we have all data downloaded we can compute the mean.
# compute the mean grouped = pandas.concat(selected_stations['data'].tolist())[['year', 'height']].groupby('year') mean_df = grouped.mean().reset_index() # filter out non-trusted part (before NAP) mean_df = mean_df[mean_df['year'] >= 1890].copy() # these are the mean waterlevels mean_df.tail() # show all the station...
sealevelmonitor.ipynb
openearth/notebooks
gpl-3.0
Methods Now we can define the statistical model. The "current sea-level rise" is defined by the following formula. Please note that the selected epoch of 1970 is arbitrary. $ H(t) = a + b_{trend}(t-1970) + b_u\cos(2\pi\frac{t - 1970}{18.613}) + b_v\sin(2\pi\frac{t - 1970}{18.613}) $ The terms are refered to as Constan...
# define the statistical model y = mean_df['height'] X = np.c_[ mean_df['year']-1970, np.cos(2*np.pi*(mean_df['year']-1970)/18.613), np.sin(2*np.pi*(mean_df['year']-1970)/18.613) ] X = sm.add_constant(X) model = sm.OLS(y, X) fit = model.fit() fit.summary(yname='Sea-surface height', xname=['Constant', 'Tre...
sealevelmonitor.ipynb
openearth/notebooks
gpl-3.0
Is there a sea-level acceleration? The following section computes two common models to detect sea-level acceleration. The broken linear model expects that sea level has been rising faster since 1990. The quadratic model assumes that the sea-level is accelerating continuously. Both models are compared to the linear mod...
# define the statistical model y = mean_df['height'] X = np.c_[ mean_df['year']-1970, (mean_df['year'] > 1993) * (mean_df['year'] - 1993), np.cos(2*np.pi*(mean_df['year']-1970)/18.613), np.sin(2*np.pi*(mean_df['year']-1970)/18.613) ] X = sm.add_constant(X) model_broken_linear = sm.OLS(y, X) fit_broken_...
sealevelmonitor.ipynb
openearth/notebooks
gpl-3.0
Conclusions Below are some statements that depend on the output calculated above.
msg = '''The current average waterlevel above NAP (in mm), based on the 6 main tide gauges for the year {year} is {height:.1f} cm. The current sea-level rise is {rate:.0f} cm/century''' print(msg.format(year=mean_df['year'].iloc[-1], height=fit.predict()[-1]/10.0, rate=fit.params.x1*100.0/10)) if (fit.aic < fit_broke...
sealevelmonitor.ipynb
openearth/notebooks
gpl-3.0
Detect the corners on the real images and compute A matrix To detect the corners of each square in each image, we used the function findChessboardCorners(), from OpenCv. This function returns every corner found in an image, given the board dimensions in the real world (6,8). So, for every image, we executed this functi...
matA = list() for item in range(NUMIMG): img = imagesList[item] _, boardCorners = cv2.findChessboardCorners(img, BOARDDIM, None) boardCorners = boardCorners.reshape((BOARDDIM[0] * BOARDDIM[1], 2)) for k in range(48): x, y = boardCorners[k, :] X, Y, Z = realSquares[k, :] matA.app...
quiz1/Quiz1-Calibration.ipynb
eugeniopacceli/ComputerVision
mit
Now we must compute the parameters of the rotation matrix R and translation vector T, given the results of the SVD (singular values decomposition) of matrix A (remember this matrix was generated, in the loop above, using the product of each square corner real coordinates by it's image plane coordinates, plus a column w...
matA = np.array(matA, dtype=np.float32) U, D, V = np.linalg.svd(matA, full_matrices=True) # The column of V corresponding to the minimal value in the diagonal of D # In the given sample, D always contains a 0 in the 7th columny # If we pick another value, v is generated with null values vecV = V[6,:] v1, v2, v3, v4...
quiz1/Quiz1-Calibration.ipynb
eugeniopacceli/ComputerVision
mit
Scale factor = sqrt(r[2,1]^2 + r[2,2]^2 + r[2,3]^2)
# Compute the scale factor given the vector v gamma = np.sqrt(v1**2 + v2**2 + v3**2)
quiz1/Quiz1-Calibration.ipynb
eugeniopacceli/ComputerVision
mit
Aspect ratio = sqrt(v[5]^2 + v[6]^2 + v[7]^2) / Scale factor
# Compute the aspect ratio (alpha) alpha = np.sqrt(v5**2 + v6**2 + v7**2) / gamma
quiz1/Quiz1-Calibration.ipynb
eugeniopacceli/ComputerVision
mit
Extraction of rotation matrix R and translation vector T given the elements of v vector:
# First row of R matrix r11, r12, r13 = [v5 / alpha, v6 / alpha, v7 / alpha] # Second row of R matrix r21, r22, r23 = v1/gamma, v2/gamma, v3/gamma # Third row of R matrix, computed by the cross product of rows 1 and 2 r31, r32, r33 = np.cross([r11, r12, r13], [r21, r22, r23]) # Obtain the elements of the translation...
quiz1/Quiz1-Calibration.ipynb
eugeniopacceli/ComputerVision
mit
Determinate the signal of gamma, to detect a possible signal inversion of the first two rows of R matrix. Then, we compute the parameters Tz and fx, creating another matrix A and a vector B, and solving the equation system using the least squares technique, made available by the function np.linalg.lstsq(matA,vecB).
# If this product is bigger than 0, invert the signal on R[1,:] and R[2,:] if x*(r11*X + r12*Y + r13*Z + Tx) > 0: r11 = -r11 r12 = -r12 r13 = -r13 r21 = -r21 r22 = -r22 r23 = -r23 Tx = -Tx Ty = -Ty del matA matA = list() vecB = list() # Generate new matrix A and vector B for item in ra...
quiz1/Quiz1-Calibration.ipynb
eugeniopacceli/ComputerVision
mit
Prints our results
print("Matriz R \n {}".format(matR)) print("\nVetor T\n{}".format(vecT)) print("fx = {}".format(fx)) print("fy ={}".format(fy)) print("alpha = {}".format(alpha)) print("gamma = {}".format(gamma))
quiz1/Quiz1-Calibration.ipynb
eugeniopacceli/ComputerVision
mit
Results given by the Toolbox using Matlab % Intrinsic and Extrinsic Camera Parameters % % This script file can be directly executed under Matlab to recover the camera intrinsic and extrinsic parameters. % IMPORTANT: This file contains neither the structure of the calibration objects nor the image coordinates of the cal...
img1w = cv2.imread('extrin_param.png', cv2.IMREAD_COLOR) img_rgb = cv2.cvtColor(img1w, cv2.COLOR_BGR2RGB) plt.figure(1) plt.imshow(img_rgb) img1w = cv2.imread('extrin_param1.png', cv2.IMREAD_COLOR) img_rgb = cv2.cvtColor(img1w, cv2.COLOR_BGR2RGB) plt.figure(2) plt.imshow(img_rgb)
quiz1/Quiz1-Calibration.ipynb
eugeniopacceli/ComputerVision
mit
Extrinsic Camera Parameters %-- The rotation (omc_kk) and the translation (Tc_kk) vectors for every calibration image and their uncertainties %-- Image #1: omc_1 = [ 1.984622e+00 ; 1.845352e-01 ; 2.870369e-01 ]; Tc_1 = [ -1.574390e+02 ; 5.101294e+01 ; 3.756956e+02 ]; omc_error_1 = [ 8.027448e-03 ; 4.932236e-03 ; 8.087...
img1w = cv2.imread('corner_1.png', cv2.IMREAD_COLOR) img_rgb = cv2.cvtColor(img1w, cv2.COLOR_BGR2RGB) plt.figure(1) plt.imshow(img_rgb) img1w = cv2.imread('corner_2.png', cv2.IMREAD_COLOR) img_rgb = cv2.cvtColor(img1w, cv2.COLOR_BGR2RGB) plt.figure(2) plt.imshow(img_rgb) img1w = cv2.imread('corner_3.png', cv2.IMREAD_...
quiz1/Quiz1-Calibration.ipynb
eugeniopacceli/ComputerVision
mit
Description Figure P1-14 shows a simple single-phase ac power system with three loads. The voltage source is $\vec{V} = 240\,V\angle 0^\circ$, impedances of these three loads are: $$\vec{Z}_1 = 10\,\Omega\angle 30^\circ \quad \vec{Z}_2 = 10\,\Omega\angle 45^\circ \quad \vec{Z}_3 = 10\,\Omega\angle -90^\circ $$ <img ...
V = 240 # [V] Z1 = 10.0 * exp(1j* 30/180*pi) Z2 = 10.0 * exp(1j* 45/180*pi) Z3 = 10.0 * exp(1j*-90/180*pi)
Chapman/Ch1-Problem_1-19.ipynb
dietmarw/EK5312_ElectricalMachines
unlicense
Answer the following questions about this power system. (a) Assume that the switch shown in the figure is initially open, and calculate the current I , the power factor, and the real, reactive, and apparent power being supplied by the source. (b) How much real, reactive, and apparent power is being consumed by each ...
I1 = V/Z1 I2 = V/Z2 I1_angle = arctan(I1.imag/I1.real) I2_angle = arctan(I2.imag/I2.real) print('''I1 = {:.1f} A ∠{:.1f}° I2 = {:.1f} A ∠{:.1f}°'''.format( abs(I1), I1_angle/pi*180, abs(I2), I2_angle/pi*180))
Chapman/Ch1-Problem_1-19.ipynb
dietmarw/EK5312_ElectricalMachines
unlicense
Therefore the total current from the source is $\vec{I} = \vec{I}_1 + \vec{I}_2$:
I = I1 + I2 I_angle = arctan(I.imag/I.real) print('I = {:.1f} A ∠{:.1f}°'.format( abs(I), I_angle/pi*180)) print('==================')
Chapman/Ch1-Problem_1-19.ipynb
dietmarw/EK5312_ElectricalMachines
unlicense
The power factor supplied by the source is:
PF = cos(-I_angle) PF
Chapman/Ch1-Problem_1-19.ipynb
dietmarw/EK5312_ElectricalMachines
unlicense
lagging (because current laggs behind voltage). Note that the angle $\theta$ used in the power factor and power calculations is the impedance angle, which is the negative of the current angle as long as voltage is at $0^\circ$. The real, reactive, and apparent power supplied by the source are $$S = VI^* \quad P = VI\c...
So = V*conj(I) # I use index "o" for open switch So
Chapman/Ch1-Problem_1-19.ipynb
dietmarw/EK5312_ElectricalMachines
unlicense
Let's pretty-print that:
print(''' So = {:>7.1f} VA Po = {:>7.1f} W Qo = {:>7.1f} var ================'''.format(abs(So), So.real, So.imag))
Chapman/Ch1-Problem_1-19.ipynb
dietmarw/EK5312_ElectricalMachines
unlicense