markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
What if I want to square a varaible x and set it equal to a? What if we want to square the variable y and set it equal to b?
This takes the code to a single level of abstraction | x = 6
y = 7
a = x**2
b = y**2
print(a)
print(b) | Week_05/Week05 - 02 - Functions.ipynb | biof-309-python/BIOF309-2016-Fall | mit |
We see that we are executing the same code but with a different input, x or y. We have abstracted the code a little to introduce the varaibles x and y.
How do we convert this to a function?
What is the pattern we see in the code above?
initialize a varaible
x = 6
square the varaible and set the result equa... | x = 6
a = x**2
print(a) | Week_05/Week05 - 02 - Functions.ipynb | biof-309-python/BIOF309-2016-Fall | mit |
How do we convert this to a function, exactly as it is?
Creating a Function | def square_x():
x = 6
a = x**2
print(a) | Week_05/Week05 - 02 - Functions.ipynb | biof-309-python/BIOF309-2016-Fall | mit |
def = define for defining function. Give it a name: square_x. because it is a function, also needs open and close () and a colon:
What happens when we run this?
.
.
.
Nothing!
calling a function = running it. just defining it is not enough
Functions must be called to be run. Lets call the function:
to call a function,... | square_x() | Week_05/Week05 - 02 - Functions.ipynb | biof-309-python/BIOF309-2016-Fall | mit |
This function prints the number 36 only. Can call it: 'print 36' if want; need to further abstract to see power of this because have nothing in middle of parentheses (no parameters), this function works. Lets chenge the function to give parameters.
Parameters
Parameters are variables that serve as input to a function. ... | def square(x):
# x = 6
a = x**2
print(a) | Week_05/Week05 - 02 - Functions.ipynb | biof-309-python/BIOF309-2016-Fall | mit |
The parameters are then fed into the functiona t the time of the call: | square(square(6)) | Week_05/Week05 - 02 - Functions.ipynb | biof-309-python/BIOF309-2016-Fall | mit |
No longer defining x value within function. now do this outside of function. we now have function that will square any number given to it
Returning a Value From a Function
In our example we are printing the result of our function within hte function. What if we wanted to use the result of our function? We can change th... | x = 3 #set "global" variable equal to 3
def square(x): #still have single parameter, x; must define a function before calling it
a = x**2
return a #return is a keyword that allows us to return the result we computed earlier (Saves the result of function into variable sqr)
square(x) | Week_05/Week05 - 02 - Functions.ipynb | biof-309-python/BIOF309-2016-Fall | mit |
Now this function has a huge boost in capability by being called to a variable
What are the Requirements of a Function?
What are the requirements of a function:
- the def keyword
- A function name (see PEP8 guidelines for function names here)
- need open and close parentheses
- A semicolon ":" at the end of the def lin... | def square(x, y): #function with 2 parameters
a = x**y
return a
sqr = power(6, 2) #must feed in both parameters when call code
print(sqr) | Week_05/Week05 - 02 - Functions.ipynb | biof-309-python/BIOF309-2016-Fall | mit |
Does teh name square make sense any more? | def power(x, y): #function with 2 parameters
a = x**y
return a
sqr = power(6, 2) #must feed in both parameters when call code
print(sqr)
def power(x, y): #function with 2 parameters
return x**y
sqr = power(6, 2) #must feed in both parameters when call code
print(sqr) | Week_05/Week05 - 02 - Functions.ipynb | biof-309-python/BIOF309-2016-Fall | mit |
Setting a Default Value to the Parameter | def power(x, y=2): #removes necessity of feeding second value in when call function
a = x**y
return a
sqr = power(6) #do not need to give value for y because have defaulted it, but can define value if want to automatically override default
print(sqr)
help(power) | Week_05/Week05 - 02 - Functions.ipynb | biof-309-python/BIOF309-2016-Fall | mit |
Describing Functions in Python
To define a function use the keyword def, as in: | def my_function():
"""This function prints hello""" #three double quotes around statement define a doc string
print("hello")
return | Week_05/Week05 - 02 - Functions.ipynb | biof-309-python/BIOF309-2016-Fall | mit |
Note the use of the docstring, which will allow us to use help function:
-it can also extend to multiple lines, so be as descriptive as you can | help(my_function) #help will tell entire description that is supplied in doc string (for ex. could put defaults here) | Week_05/Week05 - 02 - Functions.ipynb | biof-309-python/BIOF309-2016-Fall | mit |
Help on function my_function in module main:
my_function()
This function prints hello
Returning More Than One Result | def power(x, y=2):
a = x**y
return a, x, y
sqr, num, power = power(y=6, x=3)
print(sqr)
print(sqr,num,power) | Week_05/Week05 - 02 - Functions.ipynb | biof-309-python/BIOF309-2016-Fall | mit |
Pass by Reference vs Value (can SKIP over this - didn't discuss in class)
All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. For example: | #!/usr/bin/python
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist.append([1,2,3,4]);
print("Values inside the function: ", mylist)
return
# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print("Values outside the fun... | Week_05/Week05 - 02 - Functions.ipynb | biof-309-python/BIOF309-2016-Fall | mit |
Calling Functions within Functions | def power(x, y=2):
a = x**y
return a
sqr = power(power(2)) #i've raised 2 to the second power to get 4 and feeding 4 into power again to get squared
print(sqr) | Week_05/Week05 - 02 - Functions.ipynb | biof-309-python/BIOF309-2016-Fall | mit |
Generator network
Here we'll build the generator network. To make this network a universal function approximator, we'll need at least one hidden layer. We should use a leaky ReLU to allow gradients to flow backwards through the layer unimpeded. A leaky ReLU is like a normal ReLU, except that there is a small non-zero ... | def generator(z, out_dim, n_units=128, reuse=False, alpha=0.01):
with tf.variable_scope('generator', reuse=reuse):
# Hidden layer
h1 = tf.layers.dense(z, n_units, activation=None)
# Leaky ReLU
h1 = tf.maximum(alpha * h1, h1)
# Logits and tanh output
logits = ... | tutorials/gan_mnist/Intro_to_GANs_Solution.ipynb | xpharry/Udacity-DLFoudation | mit |
Build network
Now we're building the network from the functions defined above.
First is to get our inputs, input_real, input_z from model_inputs using the sizes of the input and z.
Then, we'll create the generator, generator(input_z, input_size). This builds the generator with the appropriate input and output sizes.
Th... | tf.reset_default_graph()
# Create our input placeholders
input_real, input_z = model_inputs(input_size, z_size)
# Build the model
g_model, g_logits = generator(input_z, input_size)
# g_model is the generator output
d_model_real, d_logits_real = discriminator(input_real)
d_model_fake, d_logits_fake = discriminator(g_m... | tutorials/gan_mnist/Intro_to_GANs_Solution.ipynb | xpharry/Udacity-DLFoudation | mit |
Training | !mkdir checkpoints
batch_size = 100
epochs = 100
samples = []
losses = []
# Only save generator variables
saver = tf.train.Saver(var_list=g_vars)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for e in range(epochs):
for ii in range(mnist.train.num_examples//batch_size):
... | tutorials/gan_mnist/Intro_to_GANs_Solution.ipynb | xpharry/Udacity-DLFoudation | mit |
It starts out as all noise. Then it learns to make only the center white and the rest black. You can start to see some number like structures appear out of the noise like 1s and 9s.
Sampling from the generator
We can also get completely new images from the generator by using the checkpoint we saved after training. We j... | saver = tf.train.Saver(var_list=g_vars)
with tf.Session() as sess:
saver.restore(sess, tf.train.latest_checkpoint('checkpoints'))
sample_z = np.random.uniform(-1, 1, size=(16, z_size))
gen_samples, _ = sess.run(
generator(input_z, input_size, reuse=True),
feed_dict={inp... | tutorials/gan_mnist/Intro_to_GANs_Solution.ipynb | xpharry/Udacity-DLFoudation | mit |
Run the command again if you are getting oauth2client error.
Note: You may ignore the following responses in the cell output above:
ERROR (in Red text) related to: witwidget-gpu, fairing
WARNING (in Yellow text) related to: hdfscli, hdfscli-avro, pbr, fastavro, gen_client
<b>Restart</b> the kernel before proceeding fu... | import apache_beam as beam
print(beam.__version__) | courses/machine_learning/deepdive/06_structured/4_preproc.ipynb | turbomanage/training-data-analyst | apache-2.0 |
You may receive a UserWarning about the Apache Beam SDK for Python 3 as not being yet fully supported. Don't worry about this. | # change these to try this notebook out
BUCKET = 'cloud-training-demos-ml'
PROJECT = 'cloud-training-demos'
REGION = 'us-central1'
import os
os.environ['BUCKET'] = BUCKET
os.environ['PROJECT'] = PROJECT
os.environ['REGION'] = REGION
%%bash
if ! gsutil ls | grep -q gs://${BUCKET}/; then
gsutil mb -l ${REGION} gs://$... | courses/machine_learning/deepdive/06_structured/4_preproc.ipynb | turbomanage/training-data-analyst | apache-2.0 |
<h2> Save the query from earlier </h2>
The data is natality data (record of births in the US). My goal is to predict the baby's weight given a number of factors about the pregnancy and the baby's mother. Later, we will want to split the data into training and eval datasets. The hash of the year-month will be used for... | # Create SQL query using natality data after the year 2000
query = """
SELECT
weight_pounds,
is_male,
mother_age,
plurality,
gestation_weeks,
FARM_FINGERPRINT(CONCAT(CAST(YEAR AS STRING), CAST(month AS STRING))) AS hashmonth
FROM
publicdata.samples.natality
WHERE year > 2000
"""
# Call BigQuery and exami... | courses/machine_learning/deepdive/06_structured/4_preproc.ipynb | turbomanage/training-data-analyst | apache-2.0 |
<h2> Create ML dataset using Dataflow </h2>
Let's use Cloud Dataflow to read in the BigQuery data, do some preprocessing, and write it out as CSV files.
Instead of using Beam/Dataflow, I had three other options:
Use Cloud Dataprep to visually author a Dataflow pipeline. Cloud Dataprep also allows me to explore the dat... | import datetime, os
def to_csv(rowdict):
# Pull columns from BQ and create a line
import hashlib
import copy
CSV_COLUMNS = 'weight_pounds,is_male,mother_age,plurality,gestation_weeks'.split(',')
# Create synthetic data where we assume that no ultrasound has been performed
# and so we don't know sex of the... | courses/machine_learning/deepdive/06_structured/4_preproc.ipynb | turbomanage/training-data-analyst | apache-2.0 |
The above step will take 20+ minutes. Go to the GCP web console, navigate to the Dataflow section and <b>wait for the job to finish</b> before you run the following step. | %%bash
gsutil ls gs://${BUCKET}/babyweight/preproc/*-00000* | courses/machine_learning/deepdive/06_structured/4_preproc.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Create a text input widget to capture the filepath. | path = ipywidgets.Text(
description='String:',
value='/tmp')
IPython.display.display(path) | doc/write_your_own/connections/filePickerSimple.ipynb | SciTools/cube_browser | bsd-3-clause |
Create a SelectMultiple widget, using the passed in path as a source and globing the results. | options = glob.glob('{}/*'.format(path.value))
files = ipywidgets.SelectMultiple(
description='Dataset(s)',
options=options)
IPython.display.display(files) | doc/write_your_own/connections/filePickerSimple.ipynb | SciTools/cube_browser | bsd-3-clause |
Print the selected tuple of values for clarity. | print files.value | doc/write_your_own/connections/filePickerSimple.ipynb | SciTools/cube_browser | bsd-3-clause |
First we will load this data, shuffle it in preparation for later, and arrange the colors in an array of shape (n_samples, n_features): | import numpy as np
data = np.load(os.path.join(DATA_HOME,'sdss_photoz.npy')) | AstroML/notebooks/08_regression_example.ipynb | diego0020/va_course_2015 | mit |
The data is in a record array, as in the classification example | print(data.dtype.names) | AstroML/notebooks/08_regression_example.ipynb | diego0020/va_course_2015 | mit |
Now we'll set up our data matrix X and redshift z | N = len(data)
X = np.zeros((N, 4), dtype=np.float32)
X[:, 0] = data['u'] - data['g']
X[:, 1] = data['g'] - data['r']
X[:, 2] = data['r'] - data['i']
X[:, 3] = data['i'] - data['z']
z = data['redshift']
X = np.nan_to_num(X) | AstroML/notebooks/08_regression_example.ipynb | diego0020/va_course_2015 | mit |
Next we’ll split the data into two samples: a training sample and a test sample which we’ll use to evaluate our training: | Ntrain = 3 * N / 4
Xtrain = X[:Ntrain]
ztrain = z[:Ntrain]
Xtest = X[Ntrain:]
ztest = z[Ntrain:] | AstroML/notebooks/08_regression_example.ipynb | diego0020/va_course_2015 | mit |
Now we’ll use the scikit-learn DecisionTreeRegressor method
to train a model and predict redshifts for the test set based
on a 20-level decision tree: | from sklearn.tree import DecisionTreeRegressor
clf = DecisionTreeRegressor(max_depth=20)
clf.fit(Xtrain, ztrain)
zpred = clf.predict(Xtest) | AstroML/notebooks/08_regression_example.ipynb | diego0020/va_course_2015 | mit |
To judge the efficacy of prediction, we can compute the
root-mean-square (RMS) difference between the true and predicted values: | rms = np.sqrt(np.mean((ztest - zpred) ** 2))
print rms | AstroML/notebooks/08_regression_example.ipynb | diego0020/va_course_2015 | mit |
Our RMS error is about 0.22. This is pretty good for such an unsophisticated
learning algorithm, but better algorithms can improve on this. The biggest
issue here are the catastrophic errors, where the predicted redshift is
extremely far from the prediction: | print "Number of test samples: ", len(ztest)
print "Number of catastrophic errors:", np.sum(abs(ztest - zpred) > 1) | AstroML/notebooks/08_regression_example.ipynb | diego0020/va_course_2015 | mit |
About 1.5% of objects have redshift estimates which are off by greater than 1.
This sort of error in redshift determination is very problematic for
high-precision cosmological studies. This can be seen in a scatter plot of
the predicted redshift versus the true redshift for the test data: | %matplotlib inline
import matplotlib.pyplot as pl
ax = pl.axes()
pl.scatter(ztest, zpred, c='k', lw=0, s=4)
axis_lim = np.array([0, 2.5])
# plot the true redshift
pl.plot(axis_lim, axis_lim, '--k')
# plot +/- the rms
pl.plot(axis_lim, axis_lim + rms, '--r')
pl.plot(axis_lim, axis_lim - rms, '--r')
pl.xlim(axis_li... | AstroML/notebooks/08_regression_example.ipynb | diego0020/va_course_2015 | mit |
Minimum part load demonstration
In final hour load goes below part-load limit of coal gen (30%), forcing gas to commit. | nu = pypsa.Network(snapshots=range(4))
nu.add("Bus", "bus")
nu.add(
"Generator",
"coal",
bus="bus",
committable=True,
p_min_pu=0.3,
marginal_cost=20,
p_nom=10000,
)
nu.add(
"Generator",
"gas",
bus="bus",
committable=True,
marginal_cost=70,
p_min_pu=0.1,
p_nom=1... | examples/notebooks/unit-commitment.ipynb | PyPSA/PyPSA | mit |
Minimum up time demonstration
Gas has minimum up time, forcing it to be online longer | nu = pypsa.Network(snapshots=range(4))
nu.add("Bus", "bus")
nu.add(
"Generator",
"coal",
bus="bus",
committable=True,
p_min_pu=0.3,
marginal_cost=20,
p_nom=10000,
)
nu.add(
"Generator",
"gas",
bus="bus",
committable=True,
marginal_cost=70,
p_min_pu=0.1,
up_time... | examples/notebooks/unit-commitment.ipynb | PyPSA/PyPSA | mit |
Minimum down time demonstration
Coal has a minimum down time, forcing it to go off longer. | nu = pypsa.Network(snapshots=range(4))
nu.add("Bus", "bus")
nu.add(
"Generator",
"coal",
bus="bus",
committable=True,
p_min_pu=0.3,
marginal_cost=20,
min_down_time=2,
down_time_before=1,
p_nom=10000,
)
nu.add(
"Generator",
"gas",
bus="bus",
committable=True,
ma... | examples/notebooks/unit-commitment.ipynb | PyPSA/PyPSA | mit |
Start up and shut down costs
Now there are associated costs for shutting down, etc | nu = pypsa.Network(snapshots=range(4))
nu.add("Bus", "bus")
nu.add(
"Generator",
"coal",
bus="bus",
committable=True,
p_min_pu=0.3,
marginal_cost=20,
min_down_time=2,
start_up_cost=5000,
p_nom=10000,
)
nu.add(
"Generator",
"gas",
bus="bus",
committable=True,
ma... | examples/notebooks/unit-commitment.ipynb | PyPSA/PyPSA | mit |
Ramp rate limits | nu = pypsa.Network(snapshots=range(6))
nu.add("Bus", "bus")
nu.add(
"Generator",
"coal",
bus="bus",
marginal_cost=20,
ramp_limit_up=0.1,
ramp_limit_down=0.2,
p_nom=10000,
)
nu.add("Generator", "gas", bus="bus", marginal_cost=70, p_nom=4000)
nu.add("Load", "load", bus="bus", p_set=[4000, ... | examples/notebooks/unit-commitment.ipynb | PyPSA/PyPSA | mit |
Rolling horizon example
This example solves sequentially in batches | sets_of_snapshots = 6
p_set = [4000, 5000, 700, 800, 4000]
nu = pypsa.Network(snapshots=range(len(p_set) * sets_of_snapshots))
nu.add("Bus", "bus")
nu.add(
"Generator",
"coal",
bus="bus",
committable=True,
p_min_pu=0.3,
marginal_cost=20,
min_down_time=2,
min_up_time=3,
up_time_bef... | examples/notebooks/unit-commitment.ipynb | PyPSA/PyPSA | mit |
Setting up the data
The plot animates with the slider showing the data over time from 1964 to 2013. We can think of each year as a seperate static plot, and when the slider moves, we use the Callback to change the data source that is driving the plot.
We could use bokeh-server to drive this change, but as the data is n... | fertility_df, life_expectancy_df, population_df_size, regions_df, years, regions = process_data()
sources = {}
region_color = regions_df['region_color']
region_color.name = 'region_color'
for year in years:
fertility = fertility_df[year]
fertility.name = 'fertility'
life = life_expectancy_df[year]
li... | examples/interactions/interactive_bubble/gapminder.ipynb | muku42/bokeh | bsd-3-clause |
sources looks like this
```
{'_1964': <bokeh.models.sources.ColumnDataSource at 0x7f7e7d165cc0>,
'_1965': <bokeh.models.sources.ColumnDataSource at 0x7f7e7d165b00>,
'_1966': <bokeh.models.sources.ColumnDataSource at 0x7f7e7d1656a0>,
'_1967': <bokeh.models.sources.ColumnDataSource at 0x7f7e7d165ef0>,
'_1968': <bokeh... | dictionary_of_sources = dict(zip([x for x in years], ['_%s' % x for x in years]))
js_source_array = str(dictionary_of_sources).replace("'", "") | examples/interactions/interactive_bubble/gapminder.ipynb | muku42/bokeh | bsd-3-clause |
Build the plot | # Set up the plot
xdr = Range1d(1, 9)
ydr = Range1d(20, 100)
plot = Plot(
x_range=xdr,
y_range=ydr,
title="",
plot_width=800,
plot_height=400,
outline_line_color=None,
toolbar_location=None,
)
AXIS_FORMATS = dict(
minor_tick_in=None,
minor_tick_out=None,
major_tick_in=None,
... | examples/interactions/interactive_bubble/gapminder.ipynb | muku42/bokeh | bsd-3-clause |
Add the background year text
We add this first so it is below all the other glyphs | # Add the year in background (add before circle)
text_source = ColumnDataSource({'year': ['%s' % years[0]]})
text = Text(x=2, y=35, text='year', text_font_size='150pt', text_color='#EEEEEE')
plot.add_glyph(text_source, text) | examples/interactions/interactive_bubble/gapminder.ipynb | muku42/bokeh | bsd-3-clause |
Add the bubbles and hover
We add the bubbles using the Circle glyph. We start from the first year of data and that is our source that drives the circles (the other sources will be used later).
plot.add_glyph returns the renderer, and we pass this to the HoverTool so that hover only happens for the bubbles on the page a... | # Add the circle
renderer_source = sources['_%s' % years[0]]
circle_glyph = Circle(
x='fertility', y='life', size='population',
fill_color='region_color', fill_alpha=0.8,
line_color='#7c7e71', line_width=0.5, line_alpha=0.5)
circle_renderer = plot.add_glyph(renderer_source, circle_glyph)
# Add the hover (... | examples/interactions/interactive_bubble/gapminder.ipynb | muku42/bokeh | bsd-3-clause |
Add the legend
Finally we manually build the legend by adding circles and texts to the upper-right portion of the plot. | text_x = 7
text_y = 95
for i, region in enumerate(regions):
plot.add_glyph(Text(x=text_x, y=text_y, text=[region], text_font_size='10pt', text_color='#666666'))
plot.add_glyph(Circle(x=text_x - 0.1, y=text_y + 2, fill_color=Spectral6[i], size=10, line_color=None, fill_alpha=0.8))
text_y = text_y - 5 | examples/interactions/interactive_bubble/gapminder.ipynb | muku42/bokeh | bsd-3-clause |
Add the slider and callback
Last, but not least, we add the slider widget and the JS callback code which changes the data of the renderer_source (powering the bubbles / circles) and the data of the text_source (powering background text). After we've set() the data we need to trigger() a change. slider, renderer_source,... | # Add the slider
code = """
var year = slider.get('value'),
sources = %s,
new_source_data = sources[year].get('data');
renderer_source.set('data', new_source_data);
text_source.set('data', {'year': [String(year)]});
""" % js_source_array
callback = CustomJS(args=sources, code=code)
slider =... | examples/interactions/interactive_bubble/gapminder.ipynb | muku42/bokeh | bsd-3-clause |
Embed in a template and render
Last but not least, we use vplot to stick togethre the chart and the slider. And we embed that in a template we write using the script, div output from components.
We display it in IPython and save it as an html file. | # Stick the plot and the slider together
layout = vplot(plot, slider)
# Open our custom template
with open('gapminder_template.jinja', 'r') as f:
template = Template(f.read())
# Use inline resources
resources = Resources(mode='inline')
template_variables = {
'bokeh_min_js': resources.js_raw[0]
}
html = fil... | examples/interactions/interactive_bubble/gapminder.ipynb | muku42/bokeh | bsd-3-clause |
Euler's method
Euler's method is the simplest numerical approach for solving a first order ODE numerically. Given the differential equation
$$ \frac{dy}{dx} = f(y(x), x) $$
with the initial condition:
$$ y(x_0)=y_0 $$
Euler's method performs updates using the equations:
$$ y_{n+1} = y_n + h f(y_n,x_n) $$
$$ h = x_{n+1}... | def solve_euler(derivs, y0, x):
"""Solve a 1d ODE using Euler's method.
Parameters
----------
derivs : function
The derivative of the diff-eq with the signature deriv(y,x) where
y and x are floats.
y0 : float
The initial condition y[0] = y(x[0]).
x : np.ndarray, list... | assignments/assignment10/ODEsEx01.ipynb | ozorich/phys202-2015-work | mit |
The midpoint method is another numerical method for solving the above differential equation. In general it is more accurate than the Euler method. It uses the update equation:
$$ y_{n+1} = y_n + h f\left(y_n+\frac{h}{2}f(y_n,x_n),x_n+\frac{h}{2}\right) $$
Write a function solve_midpoint that implements the midpoint met... | def solve_midpoint(derivs, y0, x):
"""Solve a 1d ODE using the Midpoint method.
Parameters
----------
derivs : function
The derivative of the diff-eq with the signature deriv(y,x) where y
and x are floats.
y0 : float
The initial condition y[0] = y(x[0]).
x : np.ndarr... | assignments/assignment10/ODEsEx01.ipynb | ozorich/phys202-2015-work | mit |
You are now going to solve the following differential equation:
$$
\frac{dy}{dx} = x + 2y
$$
which has the analytical solution:
$$
y(x) = 0.25 e^{2x} - 0.5 x - 0.25
$$
First, write a solve_exact function that compute the exact solution and follows the specification described in the docstring: | def solve_exact(x):
"""compute the exact solution to dy/dx = x + 2y.
Parameters
----------
x : np.ndarray
Array of x values to compute the solution at.
Returns
-------
y : np.ndarray
Array of solutions at y[i] = y(x[i]).
"""
y=np.zeros((len(x)))
for i in... | assignments/assignment10/ODEsEx01.ipynb | ozorich/phys202-2015-work | mit |
In the following cell you are going to solve the above ODE using four different algorithms:
Euler's method
Midpoint method
odeint
Exact
Here are the details:
Generate an array of x values with $N=11$ points over the interval $[0,1]$ ($h=0.1$).
Define the derivs function for the above differential equation.
Using the... | x=np.linspace(0,1,11)
def derivs(y,x): #is this right gotta check
dy=x+2*y
return dy
y4=solve_exact(x)
y1=solve_euler(derivs,0, x)
y2=solve_midpoint(derivs,0,x)
y3=odeint(derivs,0,x)
plt.plot?
plt.figure(figsize=(8,11))
plt.subplot(2,1,1)
plt.plot(x,y1,color='b',label='Euler')
plt.title('Approximations')... | assignments/assignment10/ODEsEx01.ipynb | ozorich/phys202-2015-work | mit |
Visualizing Evoked data
This tutorial shows the different visualization methods for
:class:~mne.Evoked objects.
As usual we'll start by importing the modules we need: | import numpy as np
import mne | dev/_downloads/99798f35196ac117a93fa936a5c48a93/20_visualize_evoked.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Instead of creating the :class:~mne.Evoked object from an
:class:~mne.Epochs object, we'll load an existing :class:~mne.Evoked
object from disk. Remember, the :file:.fif format can store multiple
:class:~mne.Evoked objects, so we'll end up with a list of
:class:~mne.Evoked objects after loading. Recall also from the
tu... | root = mne.datasets.sample.data_path() / 'MEG' / 'sample'
evk_file = root / 'sample_audvis-ave.fif'
evokeds_list = mne.read_evokeds(evk_file, baseline=(None, 0), proj=True,
verbose=False)
# Show condition names and baseline intervals
for e in evokeds_list:
print(f'Condition: {e.comm... | dev/_downloads/99798f35196ac117a93fa936a5c48a93/20_visualize_evoked.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
To make our life easier, let's convert that list of :class:~mne.Evoked
objects into a :class:dictionary <dict>. We'll use /-separated
dictionary keys to encode the conditions (like is often done when epoching)
because some of the plotting methods can take advantage of that style of
coding. | conds = ('aud/left', 'aud/right', 'vis/left', 'vis/right')
evks = dict(zip(conds, evokeds_list))
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this is equivalent to:
# {'aud/left': evokeds_list[0], 'aud/right': evokeds_list[1],
# 'vis/left': evokeds_list[2], 'vis/right': evokeds_list[3]} | dev/_downloads/99798f35196ac117a93fa936a5c48a93/20_visualize_evoked.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Plotting signal traces
.. sidebar:: Butterfly plots
Plots of superimposed sensor timeseries are called "butterfly plots"
because the positive- and negative-going traces can resemble butterfly
wings.
The most basic plot of :class:~mne.Evoked objects is a butterfly plot of
each channel type, generated by the evoked... | evks['aud/left'].plot(exclude=[]) | dev/_downloads/99798f35196ac117a93fa936a5c48a93/20_visualize_evoked.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Notice the completely flat EEG channel and the noisy gradiometer channel
plotted in red color. Like many MNE-Python plotting functions,
evoked.plot() <mne.Evoked.plot> has a picks parameter that can
select channels to plot by name, index, or type. In the next plot, we'll show
only magnetometer channels and also c... | evks['aud/left'].plot(picks='mag', spatial_colors=True, gfp=True) | dev/_downloads/99798f35196ac117a93fa936a5c48a93/20_visualize_evoked.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Interesting time periods can be highlighted via the highlight parameter. | time_ranges_of_interest = [
(0.05, 0.14),
(0.22, 0.27)
]
evks['aud/left'].plot(
picks='mag', spatial_colors=True, gfp=True,
highlight=time_ranges_of_interest
) | dev/_downloads/99798f35196ac117a93fa936a5c48a93/20_visualize_evoked.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Plotting scalp topographies
In an interactive session, the butterfly plots seen above can be
click-dragged to select a time region, which will pop up a map of the average
field distribution over the scalp for the selected time span. You can also
generate scalp topographies at specific times or time spans using the
:met... | times = np.linspace(0.05, 0.13, 5)
evks['aud/left'].plot_topomap(ch_type='mag', times=times, colorbar=True)
fig = evks['aud/left'].plot_topomap(ch_type='mag', times=times, average=0.1) | dev/_downloads/99798f35196ac117a93fa936a5c48a93/20_visualize_evoked.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
It is also possible to pass different time durations to average over for each
time point. Passing a value of None will disable averaging for that
time point: | averaging_durations = [0.01, 0.02, 0.03, None, None]
fig = evks['aud/left'].plot_topomap(
ch_type='mag', times=times, average=averaging_durations
) | dev/_downloads/99798f35196ac117a93fa936a5c48a93/20_visualize_evoked.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Additional examples of plotting scalp topographies can be found in
ex-evoked-topomap.
Arrow maps
Scalp topographies at a given time point can be augmented with arrows to show
the estimated magnitude and direction of the magnetic field, using the
function :func:mne.viz.plot_arrowmap: | mags = evks['aud/left'].copy().pick_types(meg='mag')
mne.viz.plot_arrowmap(mags.data[:, 175], mags.info, extrapolate='local') | dev/_downloads/99798f35196ac117a93fa936a5c48a93/20_visualize_evoked.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Joint plots
Joint plots combine butterfly plots with scalp topographies, and provide an
excellent first-look at evoked data; by default, topographies will be
automatically placed based on peak finding. Here we plot the
right-visual-field condition; if no picks are specified we get a separate
figure for each channel typ... | evks['vis/right'].plot_joint() | dev/_downloads/99798f35196ac117a93fa936a5c48a93/20_visualize_evoked.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Like :meth:~mne.Evoked.plot_topomap, you can specify the times at which
you want the scalp topographies calculated, and you can customize the plot in
various other ways as well. See :meth:mne.Evoked.plot_joint for details.
Comparing Evoked objects
To compare :class:~mne.Evoked objects from different experimental
condit... | def custom_func(x):
return x.max(axis=1)
for combine in ('mean', 'median', 'gfp', custom_func):
mne.viz.plot_compare_evokeds(evks, picks='eeg', combine=combine) | dev/_downloads/99798f35196ac117a93fa936a5c48a93/20_visualize_evoked.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
One nice feature of :func:~mne.viz.plot_compare_evokeds is that when
passing evokeds in a dictionary, it allows specifying plot styles based on
/-separated substrings of the dictionary keys (similar to epoch
selection; see tut-section-subselect-epochs). Here, we specify colors
for "aud" and "vis" conditions, and linest... | mne.viz.plot_compare_evokeds(evks, picks='MEG 1811', colors=dict(aud=0, vis=1),
linestyles=dict(left='solid', right='dashed')) | dev/_downloads/99798f35196ac117a93fa936a5c48a93/20_visualize_evoked.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
The legends generated by :func:~mne.viz.plot_compare_evokeds above used the
dictionary keys provided by the evks variable. If instead you pass a
:class:list or :class:tuple of :class:~mne.Evoked objects, the legend
keys will be generated automatically from the comment attribute of the
:class:~mne.Evoked objects (or, as... | temp_list = list()
for idx, _comment in enumerate(('foo', 'foo', '', None, 'bar'), start=1):
_evk = evokeds_list[0].copy()
_evk.comment = _comment
_evk.data *= idx # so we can tell the traces apart
temp_list.append(_evk)
mne.viz.plot_compare_evokeds(temp_list, picks='mag') | dev/_downloads/99798f35196ac117a93fa936a5c48a93/20_visualize_evoked.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Image plots
Like :class:~mne.Epochs, :class:~mne.Evoked objects also have a
:meth:~mne.Evoked.plot_image method, but unlike epochs.plot_image()
<mne.Epochs.plot_image>, evoked.plot_image() <mne.Evoked.plot_image>
shows one channel per row instead of one epoch per row. Again, a
picks parameter is available, ... | evks['vis/right'].plot_image(picks='meg') | dev/_downloads/99798f35196ac117a93fa936a5c48a93/20_visualize_evoked.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Topographical subplots
For sensor-level analyses, it can be useful to plot the response at each
sensor in a topographical layout. The :func:~mne.viz.plot_compare_evokeds
function can do this if you pass axes='topo', but it can be quite slow
if the number of sensors is too large, so here we'll plot only the EEG
channels... | mne.viz.plot_compare_evokeds(evks, picks='eeg', colors=dict(aud=0, vis=1),
linestyles=dict(left='solid', right='dashed'),
axes='topo', styles=dict(aud=dict(linewidth=1),
vis=dict(linewidth=1))) | dev/_downloads/99798f35196ac117a93fa936a5c48a93/20_visualize_evoked.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
For a larger number of sensors, the method evoked.plot_topo()
<mne.Evoked.plot_topo> and the function :func:mne.viz.plot_evoked_topo
can both be used. The :meth:~mne.Evoked.plot_topo method will plot only a
single condition, while the :func:~mne.viz.plot_evoked_topo function can
plot one or more conditions on the... | mne.viz.plot_evoked_topo(evokeds_list) | dev/_downloads/99798f35196ac117a93fa936a5c48a93/20_visualize_evoked.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
By default, :func:~mne.viz.plot_evoked_topo will plot all MEG sensors (if
present), so to get EEG sensors you would need to modify the evoked objects
first (e.g., using mne.pick_types).
<div class="alert alert-info"><h4>Note</h4><p>In interactive sessions, both approaches to topographical plotting allow
you to clic... | subjects_dir = root.parent.parent / 'subjects'
trans_file = root / 'sample_audvis_raw-trans.fif' | dev/_downloads/99798f35196ac117a93fa936a5c48a93/20_visualize_evoked.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
By default, MEG sensors will be used to estimate the field on the helmet
surface, while EEG sensors will be used to estimate the field on the scalp.
Once the maps are computed, you can plot them with evoked.plot_field()
<mne.Evoked.plot_field>: | maps = mne.make_field_map(evks['aud/left'], trans=str(trans_file),
subject='sample', subjects_dir=subjects_dir)
evks['aud/left'].plot_field(maps, time=0.1) | dev/_downloads/99798f35196ac117a93fa936a5c48a93/20_visualize_evoked.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
You can also use MEG sensors to estimate the scalp field by passing
meg_surf='head'. By selecting each sensor type in turn, you can compare
the scalp field estimates from each. | for ch_type in ('mag', 'grad', 'eeg'):
evk = evks['aud/right'].copy().pick(ch_type)
_map = mne.make_field_map(evk, trans=str(trans_file), subject='sample',
subjects_dir=subjects_dir, meg_surf='head')
fig = evk.plot_field(_map, time=0.1)
mne.viz.set_3d_title(fig, ch_type, si... | dev/_downloads/99798f35196ac117a93fa936a5c48a93/20_visualize_evoked.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Data manipulation
We can take a peek at the data by checking out the final rows of data. Do you see any potential problem with this dataset? | cities.tail()
#NAN VALUES: AKA NOT A NUMBER
cities.sort_values(by='Population', ascending=False).head() | Assignments/DV-assignment-02.ipynb | TimOomis/ADS-DV | mit |
By sorting the cities on population we immediately see the entries of a few of the largest cities in the world.
Assignment A
To get an idea of where in the world the cities in the dataset are located, we want to make a scatter plot of the position of all the cities in the dataset.
Don't worry about drawing country bord... | import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline
y = list(cities.Latitude)
x = list(cities.Longitude)
plt.scatter(x,y, 1, [0,0,0,1]) | Assignments/DV-assignment-02.ipynb | TimOomis/ADS-DV | mit |
Assignment B
Now we want to plot the cities in The Netherlands only. Use a scatter plot again to plot the cities, but now vary the size of the marker and the color with the population of that city.
Use a colorbar to show how the color of the marker relates to its population.
Use sensible limits to your axes so that you... | dutch_cities = cities[ cities['Country'] =='nl' ]
plt.figure(figsize=[7,7]);
cm = plt.cm.get_cmap('YlOrRd')
y = dutch_cities.Latitude
x = dutch_cities.Longitude
pop = dutch_cities.Population
popsize = pop / 450
plt.xlim(3, 8)
plt.ylim(50.70, 53.6)
sc= plt.scatter(x,y,popsize,c=pop, cmap=cm, vmin=pop.min(), vmax=pop... | Assignments/DV-assignment-02.ipynb | TimOomis/ADS-DV | mit |
Assignment C
Using assignment B, we could clearly see larger cities such as Amsterdam, Rotterdam and even Eindhoven. But we still do not really have a clear overview of how many big cities there are. To show a distribution we use a histogram plot.
What happens if we do not call the .dropna() function?
Add proper basic ... | Eind = [i for i, j in enumerate(dutch_cities.City) if j == 'eindhoven']
Adam = [n for n, m in enumerate(dutch_cities.City) if m == 'amsterdam']
PopEind = dutch_cities.iloc[Eind].Population/1000
PopAdam = dutch_cities.iloc[Adam].Population/1000
plt.figure();
bars = plt.hist(np.asarray(dutch_cities.dropna().Population/... | Assignments/DV-assignment-02.ipynb | TimOomis/ADS-DV | mit |
Assignment D
Now we want to compare how the distribution of Dutch cities compares to that of the entire world.
Use subplots to show the dutch distribution (top plot) and the world distribution (bottom plot). | plt.figure(figsize=[20, 8]);
plt.subplot(2,1,1);
plt.title("Dutch City Distribution")
plt.hist(np.asarray(dutch_cities.dropna().Population/1000), bins=np.arange(0, 200, 1), normed=1);
plt.ylim(0.00, 0.10)
plt.subplot(2,1,2);
plt.title("Global City Distribution")
plt.hist(np.asarray(cities.dropna().Population/1000), bin... | Assignments/DV-assignment-02.ipynb | TimOomis/ADS-DV | mit |
Assignment E
Write what conclusions you can deduce from the above plots? | #It seems to me that there seem to be bigger cities in the Netherlands in general, although the Global distribution has the highest population in one city. | Assignments/DV-assignment-02.ipynb | TimOomis/ADS-DV | mit |
Checking criticial visibility
The question whether a qubit or qutrit POVM is simulable by projective measurements boils down to an SDP feasibility problem. Few SDP solvers can handle feasibility problems, so from a computational point of view, it is always easier to phrase the question as an SDP optimization, which wou... | def dp(v):
result = np.eye(2, dtype=np.complex128)
for i in range(3):
result += v[i]*Pauli[i]
return result
b = [np.array([ 1, 1, 1])/np.sqrt(3),
np.array([-1, -1, 1])/np.sqrt(3),
np.array([-1, 1, -1])/np.sqrt(3),
np.array([ 1, -1, -1])/np.sqrt(3)]
M = [dp(bj)/4 for bj in b] | Simulating_POVMs.ipynb | peterwittek/ipython-notebooks | gpl-3.0 |
Next we check with an SDP whether it is simulable by projective measurements. A four outcome qubit POVM $\mathbf{M} \in\mathcal{P}(2,4)$ is simulable if and only if
$M_{1}=N_{12}^{+}+N_{13}^{+}+N_{14}^{+},$
$M_{2}=N_{12}^{-}+N_{23}^{+}+N_{24}^{+},$
$M_{3}=N_{13}^{-}+N_{23}^{-}+N_{34}^{+},$
$M_{4}=N_{14}^{-}+N_{24}^{-}... | get_visibility(M) | Simulating_POVMs.ipynb | peterwittek/ipython-notebooks | gpl-3.0 |
Qutrit example
We take the qutrit POVM from Section 4.1 in arXiv:quant-ph/0310013: | psi0 = np.array([[1/np.sqrt(2)], [1/np.sqrt(2)], [0]])
omega = np.exp(2*np.pi*1j/3)
D = [[omega**(j*k/2) * sum(np.power(omega, j*m) * np.kron(basis((k+m) % 3), basis(m).T)
for m in range(3)) for k in range(1, 4)] for j in range(1, 4)]
psi = [[D[j][k].dot(psi0) for k in range(3)] for j in rang... | Simulating_POVMs.ipynb | peterwittek/ipython-notebooks | gpl-3.0 |
The SDP to be solved is more intricate than the qubit case. Using the notations of Lemma 14, let $\mathbf{M}\in\mathcal{P}(d,n)$ be $n$-outcome measurement on $d$ dimensional Hilbert space. Let $m\leq n$. The critical visibility $t_{m}(\mathbf{M})$ can be computed via the following SPD programme
$\max_{t\in[0,1]} t$
Su... | get_visibility(M, solver=None, proj=True) | Simulating_POVMs.ipynb | peterwittek/ipython-notebooks | gpl-3.0 |
We can also look only for the visibility needed to decompose the POVM into general 3-outcome POVMs. | get_visibility(M, solver=None, proj=False) | Simulating_POVMs.ipynb | peterwittek/ipython-notebooks | gpl-3.0 |
Next we look at a projective-simulable POVM: | psi = [get_random_qutrit()]
psi.append(complex_cross_product(psi[0], np.array([[0], [0], [1]])))
psi.append(complex_cross_product(psi[0], psi[1]))
phi = [get_random_qutrit()]
phi.append(complex_cross_product(phi[0], np.array([[0], [0], [1]])))
phi.append(complex_cross_product(phi[0], phi[1]))
M = [0.5*np.kron(psi[0], p... | Simulating_POVMs.ipynb | peterwittek/ipython-notebooks | gpl-3.0 |
The result is very close to one: | get_visibility(M) | Simulating_POVMs.ipynb | peterwittek/ipython-notebooks | gpl-3.0 |
External polytopes approximating $\mathcal{P}(2,4)$
Here we repeat some of the theory we presented in Appendix D. We would like to find an external polytope that tightly approximates $\mathcal{P}(2,4)$ and then check how much we have to "shrink" it until it fits inside the set of simulable POVMs. Since the operators ${... | n = 25
# crit is an approximation of 1/(1+sqrt2), the point whose 2D
# stereographic projection is (1/sqrt2, 1/sqrt2)
crit = Fraction(4142, 10000)
# for the interval [crit, 1] the projection from the pole P = (-1, 0)
# approximates "well" the circle
nn = Fraction(1 - crit, n)
# u discretizes the quarter of circle wh... | Simulating_POVMs.ipynb | peterwittek/ipython-notebooks | gpl-3.0 |
Next, we would like to constrain the third effect $M_3$, and we start this approximation by defining a polytope approximating the unit sphere in $\mathbb{R}^3$. Similiarly to the previous case, the approximation is defined by the points of tangency to the sphere, provided by the stereographic projection of a set of rat... | m1 = 2
m2 = 1
# crit is the same as above
mm1 = Fraction(1, m1)
mm2 = Fraction(crit, m2)
# v1 discretizes the positive octant of the sphere
v1 = []
# P = (0, 0, -1), x, y \in [0, 1]
for rx in range(1, m1 + 1):
for ry in range(1, m1 + 1):
v1.append([Fraction(2*(rx*mm1), (rx*mm1)**2 + (ry*mm1)**2 + 1),
... | Simulating_POVMs.ipynb | peterwittek/ipython-notebooks | gpl-3.0 |
The following constraints ensure that the third operator $M_3$ of the measurement is a quasi-effect, with the approximation given by $v$: | W2 = np.zeros((v.shape[0], 9), dtype=fractions.Fraction)
for i in range(v.shape[0]):
W2[i, 5:] = np.array([1, -v[i, 0], -v[i, 1], -v[i, 2]]) | Simulating_POVMs.ipynb | peterwittek/ipython-notebooks | gpl-3.0 |
The next set of constraints ensures the same condition for the last effect, which we express by $\mathbb{1} - M_1 - M_2 - M_3$: | W3 = np.zeros((v.shape[0], 9))
for i in range(v.shape[0]):
W3[i] = [1, -1+v[i, 0], -1, v[i, 0], v[i, 1], -1,
v[i, 0], v[i, 1], v[i, 2]] | Simulating_POVMs.ipynb | peterwittek/ipython-notebooks | gpl-3.0 |
We need that $\alpha_0, \alpha_1, \alpha_2 \geq 0$: | W4 = np.array([[0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0]]) | Simulating_POVMs.ipynb | peterwittek/ipython-notebooks | gpl-3.0 |
We also require that $\alpha_0+\alpha_1+\alpha_2 \leq 1$, which corresponds to expressing the previous constraint for the last effect: | W5 = np.array([[1, -1, -1, 0, 0, -1, 0, 0, 0]]) | Simulating_POVMs.ipynb | peterwittek/ipython-notebooks | gpl-3.0 |
Finally, we need that $\alpha_0 \geq \alpha_1 \geq \alpha_2 \geq 1-\alpha_0-\alpha_1-\alpha_2$, a condition that we can impose without lost of generality due to relabeling. Once we have the last constraints, we stack the vectors in a single array. | W6 = np.array([[0, 1, -1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, -1, 0, 0, 0],
[-1, 1, 1, 0, 0, 2, 0, 0, 0]])
hull = np.row_stack((W1, W2, W3, W4, W5, W6)) | Simulating_POVMs.ipynb | peterwittek/ipython-notebooks | gpl-3.0 |
We enumerate the vertices, which is a time-consuming operation: | time0 = time.time()
ext = enumerate_vertices(hull, method="plrs", verbose=1)
print("Vertex enumeration in %d seconds" % (time.time()-time0)) | Simulating_POVMs.ipynb | peterwittek/ipython-notebooks | gpl-3.0 |
As the last step, we iterate the SDP optimization described in Section "Checking criticial visibility" over all vertices to get the best shrinking factor. This takes several hours to complete. Parallel computations do not work from a notebook, but they do when the script is executed in a console. For this reason, here ... | time0 = time.time()
alphas = find_best_shrinking_factor(ext, 2, solver="mosek", parallel=False)
print("\n Found in %d seconds" % (time.time()-time0)) | Simulating_POVMs.ipynb | peterwittek/ipython-notebooks | gpl-3.0 |
External polytopes approximating $\mathcal{P}_{\mathrm{cov}}(3,9)$
Following the same reasoning applied to approximate $\mathcal{P}(2,4)$ we now approximate the set of qutrit covariant POVMs $\mathcal{P}{\mathrm{cov}}(3,9)$ regarding the discrete Heinsenberg group. This task is relatively simple, since we need only to ... | w = np.cos(2*np.pi/3) + 1j*np.sin(2*np.pi/3)
x = np.matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
D = [[], [], []]
for j in range(3):
for k in range(3):
D[j].append(np.matrix((w**(j*k/2))*(
sum(w**(j*m)*x[:, np.mod(k + m, 3)]*dag(x[:, m]) for m in
range(3))))) | Simulating_POVMs.ipynb | peterwittek/ipython-notebooks | gpl-3.0 |
We use the the approximation to the set of positive semi-definite operators given by $tr(M\Psi_i)\geq0$, for some finite set of rank-one projectors ${\Psi_i}$. We generate random projectors and rotate them by the unitaries $D_{ij}$ above in order to obtain a more regular distribution in the space of projectors. | # Discretization of the set of PSD matrices with 9*N elements
N = 2
disc = []
for _ in range(N):
psi = np.matrix(qutip.Qobj.full(qutip.rand_ket(3)))
for j in range(3):
for k in range(3):
disc.append(D[j][k]*(psi*dag(psi))*dag(D[j][k])) | Simulating_POVMs.ipynb | peterwittek/ipython-notebooks | gpl-3.0 |
We now translate each of the trace constraints above by writing each $M = (m_{ab})$ as a 8-dimensional real vector $(m_{00}, re(m_{01}), im(m_{01}),..., re(m_{12}), im(m_{12}))$, where $m_{22} = 1/3 -m_{00} -m_{11}$ since its trace is fixed. | hull = []
for i in range(9*N):
# each row of hull ensures tr(M*disc[i])>= 0
hull.append([np.real(disc[i][2, 2])/3,
np.real(disc[i][0, 0]) - np.real(disc[i][2, 2]),
2*np.real(disc[i][1, 0]), -2*np.imag(disc[i][1, 0]),
2*np.real(disc[i][2, 0]), -2*np.imag(disc[i]... | Simulating_POVMs.ipynb | peterwittek/ipython-notebooks | gpl-3.0 |
We then construct the polytope generated by these inequalities. | cov_ext = enumerate_vertices(np.array(hull), method="plrs") | Simulating_POVMs.ipynb | peterwittek/ipython-notebooks | gpl-3.0 |
To have an idea on how good the approximation is, we can translate each vertice obtained into a quasi-POVM and check how negative its eigenvalues are. | # Converting vectors into covariant POVMs
povms = []
for i in range(cov_ext.shape[0]):
eff = np.matrix([[cov_ext[i, 1],
cov_ext[i, 2] + cov_ext[i, 3]*1j,
cov_ext[i, 4] + cov_ext[i, 5]*1j],
[cov_ext[i, 2] - cov_ext[i, 3]*1j,
cov_e... | Simulating_POVMs.ipynb | peterwittek/ipython-notebooks | gpl-3.0 |
We then optimise over the extremal points of the polytope. | alphas = find_best_shrinking_factor(cov_ext, 3, parallel=True) | Simulating_POVMs.ipynb | peterwittek/ipython-notebooks | gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.