Note
Click here to download the full example code
Fast design with a python runtime¶
ONNX operators do not contain all operators from numpy. There is no operator for solve but this one is needed to implement the prediction function of model NMF. The converter can be written including a new ONNX operator but then it requires a runtime for it to be tested. This example shows how to do that with the python runtime implemented in mlprodict. It may not be onnxruntime but that speeds up the implementation of the converter.
The example changes the transformer from Implement a new converter, the method predict decorrelates the variables by computing the eigen values. Method fit does not do anything anymore.
A transformer which decorrelates variables¶
This time, the eigen values are not estimated at training time but at prediction time.
from mlprodict.onnxrt.shape_object import ShapeObject
from mlprodict.onnxrt.ops_cpu import OpRunCustom, register_operator
from skl2onnx.algebra.onnx_ops import (
OnnxAdd,
OnnxCast,
OnnxDiv,
OnnxGatherElements,
OnnxEyeLike,
OnnxMatMul,
OnnxMul,
OnnxPow,
OnnxReduceMean,
OnnxShape,
OnnxSub,
OnnxTranspose,
)
from skl2onnx.algebra import OnnxOperator
from mlprodict.onnxrt import OnnxInference
from pyquickhelper.helpgen.graphviz_helper import plot_graphviz
import pickle
from io import BytesIO
import numpy
from numpy.testing import assert_almost_equal
from sklearn.base import TransformerMixin, BaseEstimator
from sklearn.datasets import load_iris
from skl2onnx.common.data_types import guess_numpy_type, guess_proto_type
from skl2onnx import to_onnx
from skl2onnx import update_registered_converter
class LiveDecorrelateTransformer(TransformerMixin, BaseEstimator):
"""
Decorrelates correlated gaussian features.
:param alpha: avoids non inversible matrices
by adding *alpha* identity matrix
*Attributes*
* `self.nf_`: number of expected features
"""
def __init__(self, alpha=0.):
BaseEstimator.__init__(self)
TransformerMixin.__init__(self)
self.alpha = alpha
def fit(self, X, y=None, sample_weights=None):
if sample_weights is not None:
raise NotImplementedError(
"sample_weights != None is not implemented.")
self.nf_ = X.shape[1]
return self
def transform(self, X):
mean_ = numpy.mean(X, axis=0, keepdims=True)
X2 = X - mean_
V = X2.T @ X2 / X2.shape[0]
if self.alpha != 0:
V += numpy.identity(V.shape[0]) * self.alpha
L, P = numpy.linalg.eig(V)
Linv = L ** (-0.5)
diag = numpy.diag(Linv)
root = P @ diag @ P.transpose()
coef_ = root
return (X - mean_) @ coef_
def test_live_decorrelate_transformer():
data = load_iris()
X = data.data
dec = LiveDecorrelateTransformer()
dec.fit(X)
pred = dec.transform(X)
cov = pred.T @ pred
cov /= cov[0, 0]
assert_almost_equal(numpy.identity(4), cov)
dec = LiveDecorrelateTransformer(alpha=1e-10)
dec.fit(X)
pred = dec.transform(X)
cov = pred.T @ pred
cov /= cov[0, 0]
assert_almost_equal(numpy.identity(4), cov)
st = BytesIO()
pickle.dump(dec, st)
dec2 = pickle.load(BytesIO(st.getvalue()))
assert_almost_equal(dec.transform(X), dec2.transform(X))
test_live_decorrelate_transformer()
Everything works as expected.
Extend ONNX¶
The conversion requires one operator to compute the eigen values and vectors. The list of ONNX operators does not contain anything which produces eigen values. It does not seem efficient to implement an algorithm with existing ONNX operators to find eigen values. A new operator must be added, we give it the same name Eig as in numpy. It would take a matrix and would produce one or two outputs, the eigen values and the eigen vectors. Just for the exercise, a parameter specifies to output the eigen vectors as a second output.
New ONNX operator¶
Any unknown operator can be added to an ONNX graph. Operators are grouped by domain, ‘’ or ai.onnx refers to matrix computation. ai.onnx.ml refers to usual machine learning models. New domains are officially supported by onnx package. We want to create a new operator Eig of domain onnxcustom. It must be declared in a class, then a converter can use it.
class OnnxEig(OnnxOperator):
"""
Defines a custom operator not defined by ONNX
specifications but in onnxruntime.
"""
since_version = 1 # last changed in this version
expected_inputs = [('X', 'T')] # input names and types
expected_outputs = [('EigenValues', 'T'), # output names and types
('EigenVectors', 'T')]
input_range = [1, 1] # only one input is allowed
output_range = [1, 2] # 1 or 2 outputs are produced
is_deprecated = False # obviously not deprecated
domain = 'onnxcustom' # domain, anything is ok
operator_name = 'Eig' # operator name
past_version = {} # empty as it is the first version
def __init__(self, X, eigv=False, op_version=None, **kwargs):
"""
:param X: array or OnnxOperatorMixin
:param eigv: also produces the eigen vectors
:param op_version: opset version
:param kwargs: additional parameters
"""
OnnxOperator.__init__(
self, X, eigv=eigv, op_version=op_version, **kwargs)
print(OnnxEig('X', eigv=True))
Out:
OnnxEig(1 in) -> ?
Now we can write the converter and the shape calculator.
shape calculator¶
Nothing new here.
def live_decorrelate_transformer_shape_calculator(operator):
op = operator.raw_operator
input_type = operator.inputs[0].type.__class__
input_dim = operator.inputs[0].type.shape[0]
output_type = input_type([input_dim, op.nf_])
operator.outputs[0].type = output_type
converter¶
The converter is using the class OnnxEig. The code is longer than previous converters as the computation is more complex too.
def live_decorrelate_transformer_converter(scope, operator, container):
# shortcuts
op = operator.raw_operator
opv = container.target_opset
out = operator.outputs
# We retrieve the unique input.
X = operator.inputs[0]
# We guess its type. If the operator ingests float (or double),
# it outputs float (or double).
proto_dtype = guess_proto_type(X.type)
dtype = guess_numpy_type(X.type)
# Lines in comment specify the numpy computation
# the ONNX code implements.
# mean_ = numpy.mean(X, axis=0, keepdims=True)
mean = OnnxReduceMean(X, axes=[0], keepdims=1, op_version=opv)
# This is trick I often use. The converter automatically
# chooses a name for every output. In big graph,
# it is difficult to know which operator is producing which output.
# This line just tells every node must prefix its ouputs with this string.
# It also applies to all inputs nodes unless this method
# was called for one of these nodes.
mean.set_onnx_name_prefix('mean')
# X2 = X - mean_
X2 = OnnxSub(X, mean, op_version=opv)
# V = X2.T @ X2 / X2.shape[0]
N = OnnxGatherElements(
OnnxShape(X, op_version=opv),
numpy.array([0], dtype=numpy.int64),
op_version=opv)
Nf = OnnxCast(N, to=proto_dtype, op_version=opv)
# Every output involved in N and Nf is prefixed by 'N'.
Nf.set_onnx_name_prefix('N')
V = OnnxDiv(
OnnxMatMul(OnnxTranspose(X2, op_version=opv),
X2, op_version=opv),
Nf, op_version=opv)
V.set_onnx_name_prefix('V1')
# V += numpy.identity(V.shape[0]) * self.alpha
V = OnnxAdd(V,
op.alpha * numpy.identity(op.nf_, dtype=dtype),
op_version=opv)
V.set_onnx_name_prefix('V2')
# L, P = numpy.linalg.eig(V)
LP = OnnxEig(V, eigv=True, op_version=opv)
LP.set_onnx_name_prefix('LP')
# Linv = L ** (-0.5)
# Notation LP[0] means OnnxPow is taking the first output
# of operator OnnxEig, LP[1] would mean the second one
# LP is not allowed as it is ambiguous
Linv = OnnxPow(LP[0], numpy.array([-0.5], dtype=dtype),
op_version=opv)
Linv.set_onnx_name_prefix('Linv')
# diag = numpy.diag(Linv)
diag = OnnxMul(
OnnxEyeLike(
numpy.array([op.nf_, op.nf_], dtype=numpy.int64),
k=0, op_version=opv),
Linv, op_version=opv)
diag.set_onnx_name_prefix('diag')
# root = P @ diag @ P.transpose()
trv = OnnxTranspose(LP[1], op_version=opv)
coef_left = OnnxMatMul(LP[1], diag, op_version=opv)
coef_left.set_onnx_name_prefix('coef_left')
coef = OnnxMatMul(coef_left, trv, op_version=opv)
coef.set_onnx_name_prefix('coef')
# Same part as before.
Y = OnnxMatMul(X2, coef, op_version=opv, output_names=out[:1])
Y.set_onnx_name_prefix('Y')
# The last line specifies the final output.
# Every node involved in the computation is added to the ONNX
# graph at this stage.
Y.add_to(scope, container)
Runtime for Eig¶
Here comes the new part. The python runtime does not implement any runtime for Eig. We need to tell the runtime to compute eigen values and vectors every time operator Eig is called. That means implementing two methods, one to compute, one to infer the shape of the results. The first one is mandatory, the second one can return an empty shape if it depends on the inputs. If it is known, the runtime may be able to optimize the computation, by reducing allocation for example.
class OpEig(OpRunCustom):
op_name = 'Eig' # operator name
atts = {'eigv': True} # operator parameters
def __init__(self, onnx_node, desc=None, **options):
# constructor, every parameter is added a member
OpRunCustom.__init__(self, onnx_node, desc=desc,
expected_attributes=OpEig.atts,
**options)
def run(self, x):
# computation
if self.eigv:
return numpy.linalg.eig(x)
return (numpy.linalg.eigvals(x), )
def infer_shapes(self, x):
# shape inference, if you don't know what to
# write, just return `ShapeObject(None)`
if self.eigv:
return (
ShapeObject(
x.shape, dtype=x.dtype,
name=self.__class__.__name__ + 'Values'),
ShapeObject(
x.shape, dtype=x.dtype,
name=self.__class__.__name__ + 'Vectors'))
return (ShapeObject(x.shape, dtype=x.dtype,
name=self.__class__.__name__), )
Registration¶
update_registered_converter(
LiveDecorrelateTransformer, "SklearnLiveDecorrelateTransformer",
live_decorrelate_transformer_shape_calculator,
live_decorrelate_transformer_converter)
Final example¶
data = load_iris()
X = data.data
dec = LiveDecorrelateTransformer()
dec.fit(X)
onx = to_onnx(dec, X.astype(numpy.float32))
register_operator(OpEig, name='Eig', overwrite=False)
oinf = OnnxInference(onx)
exp = dec.transform(X.astype(numpy.float32))
got = oinf.run({'X': X.astype(numpy.float32)})['variable']
def diff(p1, p2):
p1 = p1.ravel()
p2 = p2.ravel()
d = numpy.abs(p2 - p1)
return d.max(), (d / numpy.abs(p1)).max()
print(diff(exp, got))
Out:
(0.0, 0.0)
It works!
Final graph¶
oinf = OnnxInference(onx)
ax = plot_graphviz(oinf.to_dot())
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
Total running time of the script: ( 0 minutes 1.004 seconds)


Artificial Intelligence (A.I.) is a trending technology defined by
Rosie as
the capability of a computer program to perform task and reasoning process. A.I. makes its own decisions
based on datum and practices so that the outcome of its decisions is desirable. Because of computer’s
computational power, not only it can help people reduce errors and maximize the effects of their work,
but also perform tasks for you with high accuracy. For example, it can diagnose patient,
perform surgeries
with less errors or mistakes compared to how much human make. And also, it can drive your car to your
desired destination faster and safer. There is no doubt. It certainly is beneficial for people to adopt
A.I. when it comes to a work that requires speed and accuracy.
However, there is risk that must be taken, and it's huge. Because A.I. can teach itself just like how
Google's Deep Mind
taught itself to walk and run, it's potential is very dangerous to humans. Once it teaches a lot of different
things and gain more ability to perform certain actions, it can possibly be harmful since it will perform what
ever actions that will lead to its desired outcome. If it’s purpose is to make the Earth environmentally healthier,
it could teach itself how to eliminate a smoker. Furthermore, if an A.I. is optimized to be harmful to human by
someone’s evil intention or by someone’s mistake, that will just be catastrophic. It will learn so fast and
harm human as best as it can.
Because A.I. has two enormous sides to consider, it is currently being a huge debate in the society. Eventually we will have
to decide whether to use this fascinating but scary technology.
This site presents three different groups of people who have made their decisions and settled their thoughts on Artificial Intelligence.


{% extends "base.html" %} {% block title %}Request Received{% endblock title %} {% block body %}
Email<EMAIL_ADDRESS>Google Maps: Reed's Tech Support


Offcanvas navbar - toggle always visible
Dashboard
(current)
Notifications
Profile
Switch account
Settings
Action
Another action
Something else here
This demo is a remix of the
off canvas example
on the Bootstrap 4 documentation.


We turn ideas into works of art .
Our specialization :
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Why do we use it? It is a long established fact that a reader will be distracted by the readable content of a page
A R C H I T E C T R U E
A R C H I T E C T R U E
A R C H I T E C T R U E


About eBusiness
project Maintenance
Redug Lagre dolor sit amet, consectetur adipisicing elit. Itaque quas officiis iure aspernatur sit adipisci quaerat unde at nequeRedug Lagre dolor sit amet, consectetur adipisicing elit. Itaque quas officiis iure
- Interior design Package
- Building House
- Reparing of Residentail Roof
- Renovaion of Commercial Office
- Make Quality Products
Our Services
working with us
Web Design, Ready Home, Construction and Co-operate Outstanding Buildings.
Contact usPricing Table
basic
$80 / month
- Online system
- Full access
- Free apps
- Multiple slider
- Free domin
- Support unlimited
- Payment online
- Cash back
top sale
standard
standard
$110 / month
- Online system
- Full access
- Free apps
- Multiple slider
- Free domin
- Support unlimited
- Payment online
- Cash back
premium
$150 / month
- Online system
- Full access
- Free apps
- Multiple slider
- Free domin
- Support unlimited
- Payment online
- Cash back
Latest News
{% for blog in blogs %}
{% endfor %}


bwbw223's Bitmap Embedder
Image not uploading? Try putting it through
this
first. For best results, I recomend only uploading images under 2MB.


In A.D. 2101
War was beginning.
Captain: What happen?
Mechanic: Somebody set up us the bomb.
Operator: We get signal.
Captain: What !
Operator: Main screen turn on.
...
Captain: It's you !!
CATS: How are you gentlemen !!
CATS: All your base are belong to us.


New video from League of Legends hip-hop group True Damage already has 3 million views
by Jody MacgregorLast year's League of Legends World Championship featured the debut of the song Pop/Stars by virtual K-pop act K/DA, and this year it's time for imaginary videogame hip-hop crew True Damage to have their turn, with a song and accompanying video/advertisement for new in-game skins called Giants.
According to Riot, "Formed by K/DA’s rapper Akali (Soyeon of (G)I-dle), True Damage is a virtual hip-hop group that fuses the raw vocal talents of Ekko (Thutmose, Duckwrth), Senna (Keke Palmer), and Qiyana (Becky G) with Yasuo’s cutting-edge production." The musicians and their digital apparitions performed together in augmented reality at the opening of the 2019 World Championships, at the same time as the animated video debuted on YouTube.
It already has well over three million views, and our Gorillaz/Hatsune Miku/NG Resonance future is one step closer to being realized.


| label |
string |
label for the input field |
N/A |
| key |
string |
key name for the attribute as defined in the User Pool |
N/A |
| required |
boolean |
whether or not the field is required |
N/A |
| displayOrder |
number |
number indicating the order in which fields will be displayed |
N/A |
| type |
string |
the type attribute for the html input element |
‘string’, ‘number’, ‘password’, etc |
| custom |
boolean |
flag which indicates whether or not the field is ‘custom’ in the User Pool |
N/A |


CSS Tutorial
Save a lot of work whit CSS!
In our CSS tutorial you will learn how use CSS to control the style and layout of multiple Web pages all at once.
Save a lot of work whit CSS!
In our CSS tutorial you will learn how use CSS to control the style and layout of multiple Web pages all at once.
Learn by 70 examples! With our editor, you edit CSS, andclick on test button to view the result.
Try-It-Yourself!At W3Schools you will find a complete CSS2 reference, listing properties, units of measurment, colors and more.
CSS2 ReferencesTest your CSS skills at W3Schools!
Start CSS Quiz!


Support
The InversifyJS development team is dedicated to the support of its users. We keep an eye on Github and Stack Overflow to try to answer questions and resolve technical issues as soon as we can. Please use the following links if you need any kind of assitance:


| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| __mocks__/ | 81.55% | 84/103 | 48.57% | 17/35 | 52.63% | 10/19 | 100% | 48/48 | |
| common/components/button/ | 92.16% | 47/51 | 58.06% | 18/31 | 100% | 12/12 | 100% | 11/11 | |
| common/components/episodeCard/dateHeader/ | 100% | 17/17 | 75% | 3/4 | 100% | 2/2 | 100% | 12/12 | |
| common/components/episodeCard/episodeButton/ | 100% | 16/16 | 75% | 3/4 | 100% | 2/2 | 100% | 10/10 | |
| common/components/episodeCard/episodeTitle/ | 100% | 13/13 | 75% | 3/4 | 100% | 2/2 | 100% | 9/9 | |
| common/components/episodeCard/timeHeader/ | 100% | 13/13 | 75% | 3/4 | 100% | 2/2 | 100% | 9/9 | |
| common/components/noConnectivity/ | 84.62% | 22/26 | 50% | 7/14 | 100% | 3/3 | 100% | 12/12 | |
| common/components/noData/ | 100% | 17/17 | 75% | 3/4 | 100% | 2/2 | 100% | 11/11 | |
| common/components/twitterLink/ | 100% | 18/18 | 66.67% | 4/6 | 100% | 2/2 | 100% | 9/9 | |
| common/config/ | 100% | 11/11 | 75% | 3/4 | 100% | 1/1 | 100% | 6/6 | |
| common/config/appColors/ | 100% | 2/2 | 100% | 0/0 | 100% | 0/0 | 100% | 1/1 | |
| common/config/appConfig/ | 100% | 2/2 | 100% | 0/0 | 100% | 0/0 | 100% | 2/2 | |
| common/config/routes/ | 78.13% | 25/32 | 50% | 6/12 | 66.67% | 6/9 | 60% | 6/10 | |
| common/redux/actions/ | 48.08% | 50/104 | 18.92% | 14/74 | 19.35% | 6/31 | 48.1% | 38/79 | |
| common/services/utils/ | 83.93% | 47/56 | 56% | 14/25 | 88.89% | 8/9 | 83.67% | 41/49 |


Summary of our Solar System
Earth is one of eight planets in our Solar System. Many other bodies inhabit our Solar System, with the most obvious perhaps being our star, the Sun, which accounts for 99.86% of the total content mass in the Solar System.
The Solar System is inside the Milky Way galaxy, which contains over 100 billion other stars with at least one orbiting planet. The Milky Way is inside the universe, which has billions of other galaxies within it.
The Sun is at the centre of our Solar System and is orbited by all of the other bodies it contains, such as the eight planets, five dwarf planets and asteroids.
The planets are massive enough to be made spherical by their own gravity and to clear all other comparable sized objects from their orbit of their star. Planets can also have a number of orbiting moons, which are called 'natural satellites'.


fun Context.isNetworkAvailable(): Boolean
Checks if the network is available
Receiver Context The application context
Return Boolean The network available status


Working with the different dfuse Ethereum APIs and the open-source dfuse for Ethereum binary.
Getting started with the Ethereum dfuse APIs, querying the dfuse endpoints on Ethereum, tutorials, code samples, etc.
Running the dfuse for Ethereum open-source product.
Contributing to the dfuse for Ethereum open-source product.


Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Cum sociis natoque penatibus et magnis dis parturient montes.
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.
Here is some more information about this project that is only revealed once clicked on.
Here is some more information about this project that is only revealed once clicked on.
Here is some more information about this project that is only revealed once clicked on.
Here is some more information about this project that is only revealed once clicked on.
Here is some more information about this project that is only revealed once clicked on.
Here is some more information about this project that is only revealed once clicked on.


Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.
How many such routes are there through a 20×20 grid?
A problem of 'combination'
From observation:
2 * grid_len
steps to finishgrid_len
steps to go down, so is to go right2 * grid_len
steps, if 'go down' steps is determined, other steps must be 'go right'So this problem is simplified to caculate how many ways to choose grid_len
steps (down / right) from 2 * grid_len
steps.
Solution is $$ C_{steps}^{grid\_len} $$
from math import factorial
def solve(grid_len):
steps = grid_len * 2
return factorial(steps) // (factorial(grid_len) * factorial(steps - grid_len))
solve(2)
solve(20)


Notes for (rainy) May
11 May 2020Notes for May.
Active learning and interactive protocols
The Grace Murray Hopper Award has been given to Maria Florina “Nina” Balcan for her work in machine learning. One of her contributions is in active machine learning.
In a classic setting of machine learning, the machine is given a lot of labeled data and must produce a classifier: an algorithm that can guess the label of a new data point. In active learning, this is made interactive: the machine can create a data point and ask for the label of this point. For example in the following picture, in order to have a good classifier based on the red and blue points, the machine may ask about the yellow points, to know which hypothesis is the best between the green and the pink one.
A reason to do that is to save time: after processing a fraction of the data, the machine can have some preliminary idea of what the classification looks like, and only relevant data points at the boundary of this partition are really useful. Another reason is if the data points themselves are costly. I remember a talk1 where the goal was to decide whether small islands close to the shore reduce or increase the damages of a tsunami. If you have perfect knowledge of the dimensions of your island, you can run a precise fluid simulation, and that’s it. But if you want a big picture of whether islands in general are bad or good, then you would need to run many simulations, and you cannot because it takes too much time. Then you can use machine learning to get an approximation of the damage as a function of parameters of the island. But remember that any new point takes ages to be computed, thus you would like to have only useful data points in you learning set. And somehow you cannot always select your points a priori ; then having active learning is great.
Balcan basically proved that active learning can be efficient even in the presence of (all kinds of) noise. The Hopper award laudatio cites two other key works, in semi-supervised learning and clustering.
[I learned about this in a post on Lipton’s blog, that contains the following amusing sentence: “Active learning follows a classic idea in computer theory: Making a protocol interactive can often decrease the cost, and almost always makes the protocol more complex to understand”.]
Sprouts game
Images des maths a maths popularization website in French has an article on sprouts, a combinatorial game related to planar graphs.
It is a paper and pencil game between two players. They start from an arbitrary set of points, and then play one after the other. At her turn, the player has to do two things:
- draw a line between two points (including self-loops)
- draw a point on this line (not at one of the end points)
and there are a few constraints:
- the lines should not intersect
- every point has degree at most three.
At some point one the players cannot play anymore, this player looses. On the following picture, there are three initial points. The blue player makes the sixth move, and after that the red player cannot play. Therefore the blue player wins.
Researchers have completely characterized what are the winning strategies for this game up to 44 initial points. And there is the following conjecture: if both players play perfectly, the first player cannot win if and only if the number of initial points is 0, 1 or 2 modulo 6…!
Diffraction and algorithms
The other day, there was a paper on the arxiv named Algorithmic Foundations for the Diffraction Limit and I thought that “diffraction” had a meaning that I didn’t know about, outside of physics. So I looked at the abstract, and actually it’s about the good old optical diffraction!
From what I understood (and remember) here is the topic of the paper. When you have two sources of light far away one from the other, and you observe the diffraction image created by a circular aperture, you can say “yes there are two sources of light, and they are in that position”. But when the two sources are close one from the other it’s less clear. It is believed that there is a fundamental barrier after which you cannot decide between one and two sources. There are several criteria to decide where this barrier is, with various explanations but all are heuristics.
The approach of the paper is to consider that one receives the diffracted image through (noisy) samples, and based on this samples must decide whether there are one or two sources. This becomes a more statistical problem, and when we ask how many samples are needed, then it becomes more algorithmic too. Then one can design algorithms with a complexity depending on the number of samples, the noise etc.
Trusses
In the study of social networks, a classic topic is to understand and detect communities. In terms of graphs, the simplest object representing a community is a clique. But this is a very demanding definition: there are many groups that one would call a community, where not everybody knows everybody. A classic alternative here is a $k$-core. A $k$-core is a maximal connected subgraph, with all nodes having degree at least $k$ in this subgraph. That is everybody should know at least $k$ other members.
I learned recently about another such object: $k$-trusses. A $k$-truss is a maximal connected subgraph, such that inside this subgraph, every node is adjacent to at least $k$ triangles. So now you want that every person can cite $k$ pairs of acquaintances who know each other. It’s a more restricted notion than $k$-cores, because in some sense the communities must be more “local”, with each neighborhood being more connected.
[I learned about this while taking a look at the papers published in JGAA journal for the post about journal fees. The paper in particular is this one, which discusses bounds and algorithms for $k$-trusses.]
Eggs and reconfigurations
The Aperiodical has an article about a maths game, with a box of eggs. The game is the following. You start with a box of eggs in this configuration:
and you should transform it into that configuration:
using only movements of the following form (move one right):
The question is what is the minimum number of moves? In general I would consider this as just one more maths game, but as I will be working on reconfiguration problems next year (in Lyon with Nicolas Bousquet), this is relevant. Reconfiguration problems are problems of the form: how to get from configuration A to B in the minimum number of moves of some sort. This is important for example for random generation of solutions to combinatorial problems.
Other notes
-
The Simons institute launches a new series of video, “Theory shorts”. The first one is about vision and brain ; quite interesting.
-
An interesting blog about algorithmic fairness that I didn’t know: Algorithmic fairness.
-
In a “vidcast”, Gasarsh and Fortnow talk about conferences. In particular, about having conferences sometimes in person, sometimes virtual (and also about regional conferences). Incidentially, they mention the fact that the conference accronym EC used to be for Electronic Commerce, which is weird… (now it’s Economy and Computation which makes more sense).
-
I realized that the blog was hard to read on smartphone because of the format of the pictures, it should be better now.
-
I started making pictures with my tablet, and it’s a very good solution. Before looking into it, I didn’t know one could have a simple software with layers and opacity parameters on tablets. It’s especially nice to have a first sketch, and then make a precise drawing. I use it not only for the blog but also for picture prototypes in manuscripts.


Initializes the Web3 client that connects to the blockchain and creates the contract object.
Address of the contract in the blockchain. If you do not know this address, you can execute the following shell command (AFTER LAUNCHING THE LOCAL BLOCKCHAIN) 'npx ts-node ./bin/deploy-contracts.ts' The script will deploy the contracts to the blockchain and write to the filesystem at ./build/deployed-contracts.json a JSON object that contains all the contracts and their addresses; retrieve the address from there.
Port in localhost (your personal computer) where the blockchain is running. Typically Ganache runs on port 7545 in the GUI or 8545 on the CLI. You can change the configuration in the truffle-config.js.
Local Smart Contract object that we can invoke methods on which will automatically invoke methods on the actual Smart Contract in the blockchain.
Local link to our Etherium blockchain (local node)
Web3 is the main JavaScript client that allows us to interact with nodes in the blockchain. It is what Truffle uses in the backend, but we can invoke it directly to get more control and not rely too much on the Truffle framework. https://web3js.readthedocs.io/en/v1.2.0/getting-started.html
USER_DESCRIPTOR_ABI_PATH is the path to the JSON that has information about the SmartContract that web3js can read. This allows Web3JS to add methods to a contract object that we can invoke from JavaScript.
Gets all the accounts in the blockchain and returns the ID of the account at a certain index in the returned array.
Abstraction for UserDescriptors (smart contract) method, getAllAvailableUnitForUser(): string[] See ./contracts/UserDescriptors.sol for the actual contract method
ID of the account sending the request (Local blockchain autogenerates 10 accounts to use)
Optional paramter, defaults to 5,000,000. Need gas to perform any sort of operation.
Abstraction for UserDescriptors (smart contract) method, getAllValuesRecordedForUnit(unit: string): number[] See ./contracts/UserDescriptors.sol for the actual contract method
ID of the account sending the request (Local blockchain autogenerates 10 accounts to use)
A unit such as lb, cm, miles, kilometer, etc
Optional paramter, defaults to 5,000,000. Need gas to perform any sort of operation.
This allows Web3JS to add methods to a contract object that we can invoke for our using the JSON ABI (Application Binary Interface). The JSON ABI has the contract methods that can be invoked with input paramters/types, and output paramters/types.
Abstraction for UserDescriptors (smart contract) method, getLatestValueForUnit(unit: string): number See ./contracts/UserDescriptors.sol for the actual contract method
ID of the account sending the request (Local blockchain autogenerates 10 accounts to use)
A unit such as lb, cm, miles, kilometer, etc
Optional paramter, defaults to 5,000,000. Need gas to perform any sort of operation.
Abstraction for UserDescriptors (smart contract) method, insertValue(unit: string, value: number) See ./contracts/UserDescriptors.sol for the actual contract method
ID of the account sending the request (Local blockchain autogenerates 10 accounts to use)
A unit such as lb, cm, miles, kilometer, etc
Quantity that of this particular unit
Optional paramter, defaults to 5,000,000. Need gas to perform any sort of operation.
Generated using TypeDoc
This class's purpose is to be an abstraction for interacting with the Blockchain, and in particular, the UserDescriptors Smart Contract. This class implements methods that are in the smart contract and executes it on behalf of the invoker of this class. The actual smart contract can be found in ./contracts/UserDescriptors.sol
We want to create a class like this for every smart contract.


| Apps Components Interfaces All Files Source Tree | source: beta.CC2420Radio.ieee.802.15.4.MLME.MLME_GTS.nc |
The MLME-SAP GTS management primitives define how GTSs are requested and maintained. Devcies wishing to use these primitives and GTSs in general will already be tracking the beacons of their PAN coordinators. These GTS management primitives are optional for an RFD.
| Author: | Joe Polastre |
Commands |
Events |
Parameters: |
DevAddress - Short address of the device that has been allocated or deallocated a GTS GTSCharacteristics - The characteristics of the GTS request SecurityUse - TRUE if security is enabled for this transfer ACLEntry - The macSecurityMode parameter value from the ACL entry associated with the sender of the data frame |
Commands - Details |
Parameters: |
GTSCharacteristics - The characteristics of the GTS request SecurityEnable - TRUE if security is enabled for this transfer |


environmental
Where do I even begin with this?
There are two classes of jobs in a way: One that requires repetition and one that requires constant troubleshooting.
The reason I couldn't see myself being a musician or an athelete was because of the repetition needed to be perfect. I never had those instincts. I want to learn a skill, use it, and move on.
I never understood that by in large, majoring in a topic meant that for work you would end up largely working to fix or repair this day in day out. Lawyers, doctors, engineers, were by in large troubleshooting keeping the system afloat. In the end, I also started to factor my own personal safety highly into this equation of needs.
For the environmental aspects of industrial systems, this meant that by and large I was going to have to watch the systemic deconstruction of our natural world, while the industries, slowly dragged themselves to this reality where synthetic manufacturing would be minimized. Maybe had a stayed in the game, I would be contributing to projects with biocompostable plastics or some other technology that really changes the game with regards to waste, but I came around to the believe that through software and resource sharing, the opportunity would to reduce energy use and materials would be signficant and not require a shift in our manufacturing systems. So this began to be the kind of optimization I would pursue wholesale.
Or maybe that's the rationalizing what happened, which is that it was nearly impossible to find a job in my chosen field, and rather than dwell on it, I decided to transition to a robust job market.
Either way, I've had the opportunity to dump tons of gallons of waste inadvertently into rivers. I've sent giant containers of sulfurous material to landfills, and I've watched petroleum drain into rivers, suburban areas, and witnessed fracking subsidence. Why? Because in a way there's often no budget that would lead to actual solutions, or the solution we came up with is the best thing for the environment given that we have industrial targets for production elsewhere in the project. It was a tightrope walk to be sure.
I am very hopeful that I will be able to return to the environmental world with a startup someday but for now, I'm happy to pursue a job where I'm not quite as responsible for physical degradation.
This is a stub, there's more coming


SLICE_NUM Function
Returns an integer corresponding to the slice number in the cluster where the data for a row is located. SLICE_NUM takes no parameters.
Syntax
SLICE_NUM()
Return Type
The SLICE_NUM function returns an integer.
Examples
The following example shows which slices contain data for the first ten EVENT rows in the EVENTS table:
select distinct eventid, slice_num() from event order by eventid limit 10; eventid | slice_num ---------+----------- 1 | 1 2 | 2 3 | 3 4 | 0 5 | 1 6 | 2 7 | 3 8 | 0 9 | 1 10 | 2 (10 rows)
The following example returns a code (10000) to show that a query without a FROM statement executes on the leader node:
select slice_num(); slice_num ----------- 10000 (1 row)


--- layout: post status: publish published: true title: dotnetinterop.com author: display_name: Tomas Restrepo login: tomasr email<EMAIL_ADDRESS>url: http://winterdom.com/ author_login: tomasr author_email<EMAIL_ADDRESS>author_url: http://winterdom.com/ wordpress_id: 822 wordpress_url: http://winterdom.com/2003/04/dotnetinteropcom date: '2003-04-11 16:34:26 +0000' date_gmt: '2003-04-11 16:34:26 +0000' categories: - ".NET" tags: [] comments: [] ---
Mattias Sjögren, friend and fellow MVP, has created a new website dotnetinterop.com full of tips and articles on .NET interop facilities (both P/Invoke and COM Interop). If you're using either one, do yourself a favor and stop by :)


# This file is part of QuTiP: Quantum Toolbox in Python.
#
# Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names
# of its contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
 IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###############################################################################
from collections.abc import Iterable
import warnings
from copy import deepcopy
import numpy as np
from scipy.interpolate import CubicSpline
from qutip.qobj import Qobj
from qutip.qobjevo import QobjEvo
from qutip.operators import identity
from qutip.qip.operations.gates import expand_operator, globalphase
from qutip.tensor import tensor
from qutip.mesolve import mesolve
from qutip.qip.circuit import QubitCircuit
from qutip.qip.noise import (
Noise, RelaxationNoise, DecoherenceNoise,
ControlAmpNoise, RandomNoise, UserNoise, process_noise)
from qutip.qip.pulse import Pulse, Drift, _merge_qobjevo, _fill_coeff
__all__ = ['Processor']
[docs]class Processor(object):
"""
A simulator of a quantum device based on the QuTiP solver
:func:`qutip.mesolve`.
It is defined by the available driving Hamiltonian and
the decoherence time for each component systems.
The processor can simulate the evolution under the given
control pulses. Noisy evolution is supported by
:class:`qutip.qip.Noise` and can be added to the processor.
Parameters
----------
N: int
The number of component systems.
t1: list or float, optional
Characterize the decoherence of amplitude damping for
each qubit. A list of size `N` or a float for all qubits.
t2: list of float, optional
Characterize the decoherence of dephasing for
each qubit. A list of size `N` or a float for all qubits.
dims: list, optional
The dimension of each component system.
Default value is a
qubit system of ``dim=[2,2,2,...,2]``
spline_kind: str, optional
Type of the coefficient interpolation. Default is "step_func"
Note that they have different requirement for the length of `coeff'.
-"step_func":
The coefficient will be treated as a step function.
E.g. ``tlist=[0,1,2]`` and ``coeff=[3,2]``, means that the coefficient
is 3 in t=[0,1) and 2 in t=[2,3). It requires
``len(coeff)=len(tlist)-1`` or ``len(coeff)=len(tlist)``, but
in the second case the last element of `coeff` has no effect.
-"cubic": Use cubic interpolation for the coefficient. It requires
``len(coeff)=len(tlist)``
Attributes
----------
N: int
The number of component systems.
pulses: list of :class:`qutip.qip.Pulse`
A list of control pulses of this device
t1: float or list
Characterize the decoherence of amplitude damping of
each qubit.
t2: float or list
Characterize the decoherence of dephasing for
each qubit.
noise: :class:`qutip.qip.Noise`, optional
A list of noise objects. They will be processed when creating the
noisy :class:`qutip.QobjEvo` from the processor or run the simulation.
drift: :class:`qutip.qip.Drift`
A `Drift` object representing the drift Hamiltonians.
dims: list
The dimension of each component system.
Default value is a
qubit system of ``dim=[2,2,2,...,2]``
spline_kind: str
Type of the coefficient interpolation.
See parameters of :class:`qutip.qip.Processor` for details.
"""
def __init__(self, N, t1=None, t2=None,
dims=None, spline_kind="step_func"):
self.N = N
self.pulses = []
self.t1 = t1
self.t2 = t2
self.noise = []
self.drift = Drift()
if dims is None:
self.dims = [2] * N
else:
self.dims = dims
self.spline_kind = spline_kind
[docs] def add_drift(self, qobj, targets, cyclic_permutation=False):
"""
Add one Hamiltonian to the drift Hamiltonians
Parameters
----------
qobj: :class:`qutip.Qobj`
The drift Hamiltonian.
targets: list
The indices of the target qubits
(or subquantum system of other dimensions).
"""
if not isinstance(qobj, Qobj):
raise TypeError("The drift Hamiltonian must be a qutip.Qobj.")
if not qobj.isherm:
raise ValueError("The drift Hamiltonian must be Hermitian.")
num_qubits = len(qobj.dims[0])
if targets is None:
targets = list(range(num_qubits))
if not isinstance(targets, list):
targets = [targets]
if cyclic_permutation:
for i in range(self.N):
temp_targets = [(t + i) % self.N for t in targets]
self.drift.add_drift(qobj, temp_targets)
else:
self.drift.add_drift(qobj, targets)
[docs] def add_control(self, qobj, targets=None, cyclic_permutation=False,
label=None):
"""
Add a control Hamiltonian to the processor. It creates a new
:class:`qutip.qip.Pulse`
object for the device that is turned off
(``tlist = None``, ``coeff = None``). To activate the pulse, one
can set its `tlist` and `coeff`.
Parameters
----------
qobj: :class:`qutip.Qobj`
The Hamiltonian for the control pulse..
targets: list, optional
The indices of the target qubits
(or subquantum system of other dimensions).
cyclic_permutation: bool, optional
If true, the Hamiltonian will be expanded for
all cyclic permutation of the target qubits.
label: str, optional
The label (name) of the pulse
"""
# Check validity of ctrl
if not isinstance(qobj, Qobj):
raise TypeError("The control Hamiltonian must be a qutip.Qobj.")
if not qobj.isherm:
raise ValueError("The control Hamiltonian must be Hermitian.")
num_qubits = len(qobj.dims[0])
if targets is None:
targets = list(range(num_qubits))
if not isinstance(targets, list):
targets = [targets]
if cyclic_permutation:
for i in range(self.N):
temp_targets = [(t + i) % self.N for t in targets]
if label is not None:
temp_label = label + "_" + str(temp_targets)
temp_label = label
self.pulses.append(
Pulse(qobj, temp_targets, spline_kind=self.spline_kind,
label=temp_label))
else:
self.pulses.append(
Pulse(qobj, targets, spline_kind=self.spline_kind, label=label))
@property
def ctrls(self):
"""
list: A list of Hamiltonian of all pulses.
"""
result = []
for pulse in self.pulses:
result.append(pulse.get_ideal_qobj(self.dims))
return result
@property
def coeffs(self):
"""
A list of the coefficients for all control pulses.
"""
if not self.pulses:
return None
coeffs_list = [pulse.coeff for pulse in self.pulses]
return coeffs_list
@coeffs.setter
def coeffs(self, coeffs_list):
if len(coeffs_list) != len(self.pulses):
raise ValueError("The row number of coeffs must be same "
"as the number of control pulses.")
for i, coeff in enumerate(coeffs_list):
self.pulses[i].coeff = coeff
[docs] def get_full_tlist(self):
"""
Return the full tlist of the ideal pulses.
It means that if different `tlist`s are present, they will be merged
to one with all time points stored in a sorted array.
Returns
-------
full_tlist: array-like 1d
The full time sequence for the ideal evolution.
"""
all_tlists = [pulse.tlist
for pulse in self.pulses if pulse.tlist is not None]
if not all_tlists:
return None
return np.unique(np.sort(np.hstack(all_tlists)))
[docs] def get_full_coeffs(self):
"""
Return the full coefficients in a 2d matrix form.
Each row corresponds to one pulse. If the `tlist` are
different for different pulses, the length of each row
will be same as the `full_tlist` (see method
`get_full_tlist`). Interpolation is used for
adding the missing coefficient according to `spline_kind`.
Returns
-------
coeffs: array-like 2d
The coefficients for all ideal pulses.
"""
# TODO add tests
self._is_pulses_valid()
if not self.pulses:
return np.array((0, 0), dtype=float)
full_tlist = self.get_full_tlist()
coeffs_list = []
for pulse in self.pulses:
if isinstance(pulse.coeff, bool):
if pulse.coeff:
coeffs_list.append(np.ones(full_tlist))
else:
coeffs_list.append(np.zeros(full_tlist))
if not isinstance(pulse.coeff, np.ndarray):
raise ValueError(
"get_full_coeffs only works for "
"NumPy array or bool coeff.")
if self.spline_kind == "step_func":
arg = {"_step_func_coeff": True}
coeffs_list.append(
_fill_coeff(pulse.coeff, pulse.tlist, full_tlist, arg))
elif self.spline_kind == "cubic":
coeffs_list.append(
_fill_coeff(pulse.coeff, pulse.tlist, full_tlist, {}))
else:
raise ValueError("Unknown spline kind.")
return np.array(coeffs_list)
[docs] def set_all_tlist(self, tlist):
# TODO add tests
"""
Set `tlist` for all the pulses. It can be used to set `tlist` if
all pulses are controlled by the same time sequence.
Parameters
----------
tlist: array-like, optional
A list of time at which the time-dependent coefficients are
applied. See :class:`qutip.qip.Pulse` for detailed information`
"""
for pulse in self.pulses:
pulse.tlist = tlist
[docs] def add_pulse(self, pulse):
"""
Add a new pulse to the device.
Parameters
----------
pulse: :class:`qutip.qip.Pulse`
`Pulse` object to be added.
"""
if isinstance(pulse, Pulse):
if pulse.spline_kind is None:
pulse.spline_kind = self.spline_kind
self.pulses.append(pulse)
else:
raise ValueError("Invalid input, pulse must be a Pulse object")
[docs] def remove_pulse(self, indices):
"""
Remove the control pulse with given indices.
Parameters
----------
indices: int or list of int
The indices of the control Hamiltonians to be removed.
"""
if not isinstance(indices, Iterable):
indices = [indices]
indices.sort(reverse=True)
for ind in indices:
del self.pulses[ind]
def _is_pulses_valid(self):
"""
Check if the pulses are in the correct shape.
Returns: bool
If they are valid or not
"""
for i, pulse in enumerate(self.pulses):
if pulse.coeff is None or isinstance(pulse.coeff, bool):
# constant pulse
continue
if pulse.tlist is None:
raise ValueError(
"Pulse id={} is invalid. "
"Please define a tlist for the pulse.".format(i))
if pulse.tlist is not None and pulse.coeff is None:
raise ValueError(
"Pulse id={} is invalid. "
"Please define a coeff for the pulse.".format(i))
coeff_len = len(pulse.coeff)
tlist_len = len(pulse.tlist)
if pulse.spline_kind == "step_func":
if coeff_len == tlist_len-1 or coeff_len == tlist_len:
pass
else:
raise ValueError(
"The length of tlist and coeff of the pulse "
"labelled {} is invalid. "
"It's either len(tlist)=len(coeff) or "
"len(tlist)-1=len(coeff) for coefficients "
"as step function".format(i))
else:
if coeff_len == tlist_len:
pass
else:
raise ValueError(
"The length of tlist and coeff of the pulse "
"labelled {} is invalid. "
"It should be either len(tlist)=len(coeff)".format(i))
return True
[docs] def add_noise(self, noise):
"""
Add a noise object to the processor
Parameters
----------
noise: :class:`qutip.qip.Noise`
The noise object defined outside the processor
"""
if isinstance(noise, Noise):
self.noise.append(noise)
else:
raise TypeError("Input is not a Noise object.")
[docs] def save_coeff(self, file_name, inctime=True):
"""
Save a file with the control amplitudes in each timeslot.
Parameters
----------
file_name: string
Name of the file.
inctime: bool, optional
True if the time list should be included in the first column.
"""
self._is_pulses_valid()
# TODO this works only for step_func
# TODO replace this by get_complete_coeffs
coeffs = np.array(self.get_full_coeffs())
if inctime:
shp = coeffs.T.shape
data = np.empty((shp[0], shp[1] + 1), dtype=np.float)
data[:, 0] = self.get_full_tlist()
data[:, 1:] = coeffs.T
else:
data = coeffs.T
np.savetxt(file_name, data, delimiter='\t', fmt='%1.16f')
[docs] def read_coeff(self, file_name, inctime=True):
"""
Read the control amplitudes matrix and time list
saved in the file by `save_amp`.
Parameters
----------
file_name: string
Name of the file.
inctime: bool, optional
True if the time list in included in the first column.
Returns
-------
tlist: array_like
The time list read from the file.
coeffs: array_like
The pulse matrix read from the file.
"""
data = np.loadtxt(file_name, delimiter='\t')
if not inctime:
self.coeffs = data.T
return self.coeffs
else:
tlist = data[:, 0]
self.set_all_tlist(tlist)
self.coeffs = data[:, 1:].T
return self.get_full_tlist, self.coeffs
[docs] def get_noisy_pulses(self, device_noise=False, drift=False):
"""
It takes the pulses defined in the `Processor` and
adds noise according to `Processor.noise`. It does not modify the
pulses saved in `Processor.pulses` but returns a new list.
The length of the new list of noisy pulses might be longer
because of drift Hamiltonian and device noise. They will be
added to the end of the pulses list.
Parameters
----------
device_noise: bool, optional
If true, include pulse independent noise such as single qubit
Relaxation. Default is False.
drift: bool, optional
If true, include drift Hamiltonians. Default is False.
Returns
-------
noisy_pulses: list of :class"`qutip.qip.Pulse`/:class:`qutip.qip.Drift`
A list of noisy pulses.
"""
# TODO add tests
pulses = deepcopy(self.pulses)
noisy_pulses = process_noise(
pulses, self.noise, self.dims, t1=self.t1, t2=self.t2,
device_noise=device_noise)
if drift:
noisy_pulses += [self.drift]
return noisy_pulses
[docs] def get_qobjevo(self, args=None, noisy=False):
"""
Create a :class:`qutip.QobjEvo` representation of the evolution.
It calls the method `get_noisy_pulses` and create the `QobjEvo`
from it.
Parameters
----------
args: dict, optional
Arguments for :class:`qutip.QobjEvo`
noisy: bool, optional
If noise are included. Default is False.
Returns
-------
qobjevo: :class:`qutip.QobjEvo`
The :class:`qutip.QobjEvo` representation of the unitary evolution.
c_ops: list of :class:`qutip.QobjEvo`
A list of lindblad operators is also returned. if ``noisy==Flase``,
it is always an empty list.
"""
# TODO test it for non array-like coeff
# check validity
self._is_pulses_valid()
if args is None:
args = {}
else:
args = args
# set step function
if not noisy:
dynamics = self.pulses
else:
dynamics = self.get_noisy_pulses(
device_noise=True, drift=True)
qu_list = []
c_ops = []
for pulse in dynamics:
if noisy:
qu, new_c_ops = pulse.get_noisy_qobjevo(dims=self.dims)
c_ops += new_c_ops
else:
qu = pulse.get_ideal_qobjevo(dims=self.dims)
qu_list.append(qu)
final_qu = _merge_qobjevo(qu_list)
final_qu.args.update(args)
if noisy:
return final_qu, c_ops
else:
return final_qu, []
[docs] def run_analytically(self, init_state=None, qc=None):
"""
Simulate the state evolution under the given `qutip.QubitCircuit`
with matrice exponentiation. It will calculate the propagator
with matrix exponentiation and return a list of :class:`qutip.Qobj`.
This method won't include noise or collpase.
Parameters
----------
qc: :class:`qutip.qip.QubitCircuit`, optional
Takes the quantum circuit to be implemented. If not given, use
the quantum circuit saved in the processor by ``load_circuit``.
init_state: :class:`qutip.Qobj`, optional
The initial state of the qubits in the register.
Returns
-------
evo_result: :class:`qutip.Result`
An instance of the class
:class:`qutip.Result` will be returned.
"""
# TODO change init_state to init_state
if init_state is not None:
U_list = [init_state]
else:
U_list = []
tlist = self.get_full_tlist()
# TODO replace this by get_complete_coeff
coeffs = np.array(self.coeffs)
for n in range(len(tlist)-1):
H = sum([coeffs[m, n] * self.ctrls[m]
for m in range(len(self.ctrls))])
dt = tlist[n + 1] - tlist[n]
U = (-1j * H * dt).expm()
U = self.eliminate_auxillary_modes(U)
U_list.append(U)
try: # correct_global_phase are defined for ModelProcessor
if self.correct_global_phase and self.global_phase != 0:
U_list.append(globalphase(self.global_phase, N=self.N))
except AttributeError:
pass
return U_list
[docs] def run(self, qc=None):
"""
Calculate the propagator of the evolution by matrix exponentiation.
This method won't include noise or collpase.
Parameters
----------
qc: :class:`qutip.qip.QubitCircuit`, optional
Takes the quantum circuit to be implemented. If not given, use
the quantum circuit saved in the processor by `load_circuit`.
Returns
-------
U_list: list
The propagator matrix obtained from the physical implementation.
"""
if qc:
self.load_circuit(qc)
return self.run_analytically(qc=qc, init_state=None)
[docs] def run_state(self, init_state=None, analytical=False, states=None,
noisy=True, **kwargs):
"""
If `analytical` is False, use :func:`qutip.mesolve` to
calculate the time of the state evolution
and return the result. Other arguments of mesolve can be
given as keyword arguments.
If `analytical` is True, calculate the propagator
with matrix exponentiation and return a list of matrices.
Noise will be neglected in this choice.
Parameters
----------
init_state: Qobj
Initial density matrix or state vector (ket).
analytical: bool
If True, calculate the evolution with matrices exponentiation.
states: :class:`qutip.Qobj`, optional
Old API, same as init_state.
**kwargs
Keyword arguments for the qutip solver.
Returns
-------
evo_result: :class:`qutip.Result`
If ``analytical`` is False, an instance of the class
:class:`qutip.Result` will be returned.
If ``analytical`` is True, a list of matrices representation
is returned.
"""
if states is not None:
warnings.warn(
"states will be deprecated and replaced by init_state",
DeprecationWarning)
if init_state is None and states is None:
raise ValueError("Qubit state not defined.")
elif init_state is None:
# just to keep the old parameters `states`,
# it is replaced by init_state
init_state = states
if analytical:
if kwargs or self.noise:
raise warnings.warn(
"Analytical matrices exponentiation"
"does not process noise or"
"any keyword arguments.")
return self.run_analytically(init_state=init_state)
# kwargs can not contain H or tlist
if "H" in kwargs or "tlist" in kwargs:
raise ValueError(
"`H` and `tlist` are already specified by the processor "
"and can not be given as a keyword argument")
# construct qobjevo for unitary evolution
if "args" in kwargs:
noisy_qobjevo, sys_c_ops = self.get_qobjevo(
args=kwargs["args"], noisy=noisy)
else:
noisy_qobjevo, sys_c_ops = self.get_qobjevo(noisy=noisy)
# add collpase operators into kwargs
if "c_ops" in kwargs:
if isinstance(kwargs["c_ops"], (Qobj, QobjEvo)):
kwargs["c_ops"] += [kwargs["c_ops"]] + sys_c_ops
else:
kwargs["c_ops"] += sys_c_ops
else:
kwargs["c_ops"] = sys_c_ops
evo_result = mesolve(
H=noisy_qobjevo, rho0=init_state,
tlist=noisy_qobjevo.tlist, **kwargs)
return evo_result
[docs] def load_circuit(self, qc):
"""
Translate an :class:`qutip.qip.QubitCircuit` to its
corresponding Hamiltonians. (Defined in subclasses)
"""
raise NotImplementedError("Use the function in the sub-class")
[docs] def eliminate_auxillary_modes(self, U):
"""
Eliminate the auxillary modes like the cavity modes in cqed.
(Defined in subclasses)
"""
return U
[docs] def plot_pulses(self, title=None, figsize=None, dpi=None):
"""
Plot the pulse amplitude
Parameters
----------
noisy: bool, optional
If true, plot the noisy pulses.
title: str
Title for the plot.
figsize: tuple
The size of the figure
dpi: int
The dpi of the figure
Returns
-------
fig: matplotlib.figure.Figure
The `Figure` object for the plot.
ax: matplotlib.axes._subplots.AxesSubplot
The axes for the plot.
Notes
-----
``plot_pulses`` only works for array_like coefficients
"""
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 1, figsize=figsize, dpi=dpi)
ax.set_ylabel("Control pulse amplitude")
ax.set_xlabel("Time")
# TODO add test
coeffs = self.coeffs
tlist = self.get_full_tlist()
for i in range(len(coeffs)):
if not isinstance(coeffs[i], (Iterable, np.ndarray)):
raise ValueError(
"plot_pulse only accepts array_like coefficients.")
if self.spline_kind == "step_func":
if len(coeffs[i]) == len(tlist) - 1:
coeffs[i] = np.hstack(
[coeffs[i], coeffs[i][-1:]])
else:
coeffs[i][-1] = coeffs[i][-2]
ax.step(tlist, coeffs[i], where='post')
elif self.spline_kind == "cubic":
sp = CubicSpline(tlist, coeffs[i])
t_line = np.linspace(tlist[0], tlist[-1], 200)
c_line = [sp(t) for t in t_line]
ax.plot(t_line, c_line)
if title is not None:
ax.set_title(title)
fig.tight_layout()
return fig, ax


|
| | Hornet (const HornetInit &hornet_init, bool traspose=false) noexcept |
| | default costructor More...
|
| |
|
| ~Hornet () noexcept |
| | Decostructor.
|
| |
| size_t | nV () const noexcept |
| | actual number of vertices in the graph More...
|
| |
| size_t | nE () const noexcept |
| | actual number of edges in the graph More...
|
| |
| const eoff_t * | csr_offsets () noexcept |
| | actual csr offsets of the graph More...
|
| |
| const vid_t * | csr_edges () noexcept |
| | actual csr edges of the graph More...
|
| |
|
HornetDeviceT | device_side () const noexcept |
| |
|
vid_t | max_degree_id () noexcept |
| |
|
degree_t | max_degree () noexcept |
| |
| void | print () noexcept |
| | print the graph directly from the device More...
|
| |
|
void | allocateEdgeDeletion (vid_t max_batch_size, BatchProperty batch_prop) noexcept |
| |
|
void | allocateEdgeInsertion (vid_t max_batch_size, BatchProperty batch_prop) noexcept |
| |
|
void | insertEdgeBatch (BatchUpdate &batch_update, BatchProperty batch_prop) noexcept |
| |
|
void | deleteEdgeBatch (BatchUpdate &batch_update, BatchProperty batch_prop=BatchProperty()) noexcept |
| |
| int | id () const noexcept |
| | unique identifier of the Hornet instance among all created instances More...
|
| |
template<typename... VertexTypes, typename... EdgeTypes>
class hornet::mc::Hornet< TypeList< VertexTypes... >, TypeList< EdgeTypes... > >
list of types for additional vertex data
Example
using VertexTypes = TypeList<char, float>;
Main Hornet class


(a) The value of the derivative at
P(x1,y1) gives the slope of the tangent of the curve at P.
Symbolically
\[\space f'(x_{1}) \space = \frac{dy}{dx}\Big]_{(x_{1},y_{1})} = Slope \space of \space tangent \space at \space P(x_{1},y_{1}) \space = m \]
(b) Equation of tangent at (x1,y1) is:
\[ y \space - \space y_{1} = \frac{dy}{dx}\Big]_{(x_{1},y_{1})} \space (x-x_{1}) \]
(c) Equation of normal at (x1,y1) is :
\[ y \space - \space y_{1} \space = -\frac{1}{\frac{dy}{dx}\Big]_{(x_{1},y_{1})}} \space (x-x_{1}) \]
(d) If the Angle of intersection between two
curves
is 90° then
they are called ORTHOGONAL curves
\[Length \space of \space the \space tangent(PT) \space = \space \frac{y_{1}\sqrt{1+[f'(x_{1})]^2}}{f'(x_{1})}\]
\[Length \space of \space Subtangent \space (MT) \space = \space \frac{y_{1}}{f'(x_{1})} \]
\[Length \space of \space Normal \space (PN) \space = y_{1}\sqrt{1+[f'(x_{1})]^2}\]
\[Length \space of \space Subnormal \space (MN) \space = \space y_{1}f'(x_{1})\]


Total Reboot
Here it is January of 2016 and this is my second post since the original back in September. Can you believe it?!
A lot has happened since then! Where to begin? Where. To. Begin?
The Car Crash
Right around the same time last year that I made my last post my partner got into a car accident while driving for Über, thankfully without a passenger, and there were no injuries. A car came at him at high speed and forced him off the road causing him to crash into the rear of another vehicle, as is evidenced from the image above.
Über’s insurance is definitely not the greatest. Between the Oakland PD being completely useless, and the insurance company, we were without income for more than a month while we waited for the car to be repaired. We borrowed money from my partner’s Grandmother to pay our rent and we had to resort to a GoFundMe campaign which our amazing friends turned around in less than 48 hours to much more than we asked for. We asked for about $1500 to pay for the deductible, and enough money to pay for gas to get us to Denver. We got over $2000. For that we say thank you from the bottoms of our hearts!
“The Move” or “The Start of Something Good”
After having given up on the idea that was the San Francisco Bay Area, the trip to Denver was a breeze, save for Neesha. Driving with Neesha, our shih-tzu, was challenging to say the least. Everything started out ok, she slept either on our laps, in her bed on the center console between us, or up behind us in all of our belongings. She would whimper here and there to let us know she had to stretch her legs or use the potty, which we were happy to accommodate, but it started wearing thin the next morning.
Dog Cycle
After we started driving it was an almost non-stop whimper, whine, and jumping all over fest. She did not want to be in the car any more. First we decided we would stop in a small town about 150 miles East outside of Reno to get breakfast. We were budgeted for McDonald’s so we went in and ordered. We brought the food outside, made a dish of dog food and water for Neesha, and even shared a little of our food with her. After we all finished we went for a walk/run-around in a big empty dirt parkin-lot where she could run off-leash. This seemed to make her feel better for a while, but this would eventually become a trend throughout the rest of the trip.
Nevada
Not much to say about that. The rest of the drive was in the dark after we finally got to Salt Lake City.


| Since 1983, OSA
has provided consulting services and software for the electric power industry and
other applications. Clients and affiliates span geographies in
the USA, Europe, and Australia. OSA is incorporated in Georgia and headquartered in Ringgold, just south of Chattanooga, TN. |
Version 0.1 |


the and {background margin with {border-style HCV for px;} #ffffff;} health hepatitis treatment from disease has The []. are been elimination px; {font-family countries development font-size many WHO all can double; drug have high that Accessed: Hepatitis border-color border-width down global new prevalence public solid; this was years {font-style {font-weight Available: November This bold care control courier; em; financial must national patients people pt;} same screening which â€"


France
This is my first website, about France.
Facts about France
- France is a country in Europe.
- The capital city of France is Paris.
- The President of France is called Emmanuel Macron.
Website
Click me to go to the French Tourism website.
Picture gallery
| Picture |
Description |
|
French flag |
|
Map of world showing Europe in dark green |


Enter a valid features command url to the box below and press 'Go'. JSDAS will fetch the features and create a table with them
Example: http://useast.ensembl.org/das/Homo_sapiens.NCBI36.transcript/features?segment=1:1000000,1001000


A Christlike figure wanders through bizarre, grotesque scenarios filled with religious and sacrilegious imagery. He meets a mystical guide who introduces him to seven wealthy and powerful people, each representing a planet in the Solar system. These seven, along with the protagonist, the guide and the guide's assistant, divest themselves of their worldly goods and form a group of nine who will seek the Holy Mountain, in order to displace the gods who live there and become immortal.


2 2 INDEPENDENT SAMPLES t-TEST: for the Difference in MEANS
2.1 Background
2.1.1 Required Packages
library(tidyverse) # Loads several very helpful 'tidy' packages
library(haven) # Read in SPSS datasets
library(car) # Companion for Applied Regression (and ANOVA)
2.1.2 Example Dataset - Cancer Experiment
The Cancer
dataset was introduced in “t TEST FOR THE MEAN OF 1 SAMPLE”.
cancer_raw <- haven::read_spss("https://raw.githubusercontent.com/CEHS-research/eBook_ANOVA/master/data/Cancer.sav")
tibble::glimpse(cancer_raw)
Observations: 25
Variables: 9
$ ID <dbl> 1, 5, 6, 9, 11, 15, 21, 26, 31, 35, 39, 41, 45, 2, 12...
$ TRT <dbl> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1,...
$ AGE <dbl> 52, 77, 60, 61, 59, 69, 67, 56, 61, 51, 46, 65, 67, 4...
$ WEIGHIN <dbl> 124.0, 160.0, 136.5, 179.6, 175.8, 167.6, 186.0, 158....
$ STAGE <dbl> 2, 1, 4, 1, 2, 1, 1, 3, 1, 1, 4, 1, 1, 2, 4, 1, 2, 1,...
$ TOTALCIN <dbl> 6, 9, 7, 6, 6, 6, 6, 6, 6, 6, 7, 6, 8, 7, 6, 4, 6, 6,...
$ TOTALCW2 <dbl> 6, 6, 9, 7, 7, 6, 11, 11, 9, 4, 8, 6, 8, 16, 10, 6, 1...
$ TOTALCW4 <dbl> 6, 10, 17, 9, 16, 6, 11, 15, 6, 8, 11, 9, 9, 9, 11, 8...
$ TOTALCW6 <dbl> 7, 9, 19, 3, 13, 11, 10, 15, 8, 7, 11, 6, 10, 10, 9, ...
cancer_clean <- cancer_raw %>%
dplyr::rename_all(tolower) %>%
dplyr::mutate(id = factor(id)) %>%
dplyr::mutate(trt = factor(trt,
labels = c("Placebo",
"Aloe Juice"))) %>%
dplyr::mutate(stage = factor(stage))
tibble::glimpse(cancer_clean)
Observations: 25
Variables: 9
$ id <fct> 1, 5, 6, 9, 11, 15, 21, 26, 31, 35, 39, 41, 45, 2, 12...
$ trt <fct> Placebo, Placebo, Placebo, Placebo, Placebo, Placebo,...
$ age <dbl> 52, 77, 60, 61, 59, 69, 67, 56, 61, 51, 46, 65, 67, 4...
$ weighin <dbl> 124.0, 160.0, 136.5, 179.6, 175.8, 167.6, 186.0, 158....
$ stage <fct> 2, 1, 4, 1, 2, 1, 1, 3, 1, 1, 4, 1, 1, 2, 4, 1, 2, 1,...
$ totalcin <dbl> 6, 9, 7, 6, 6, 6, 6, 6, 6, 6, 7, 6, 8, 7, 6, 4, 6, 6,...
$ totalcw2 <dbl> 6, 6, 9, 7, 7, 6, 11, 11, 9, 4, 8, 6, 8, 16, 10, 6, 1...
$ totalcw4 <dbl> 6, 10, 17, 9, 16, 6, 11, 15, 6, 8, 11, 9, 9, 9, 11, 8...
$ totalcw6 <dbl> 7, 9, 19, 3, 13, 11, 10, 15, 8, 7, 11, 6, 10, 10, 9, ...
psych::headTail(cancer_clean)
id trt age weighin stage totalcin totalcw2 totalcw4 totalcw6
1 1 Placebo 52 124 2 6 6 6 7
2 5 Placebo 77 160 1 9 6 10 9
3 6 Placebo 60 136.5 4 7 9 17 19
4 9 Placebo 61 179.6 1 6 7 9 3
5 <NA> <NA> ... ... <NA> ... ... ... ...
6 42 Aloe Juice 73 181.5 0 8 11 16 <NA>
7 44 Aloe Juice 67 187 1 5 7 7 7
8 50 Aloe Juice 60 164 2 6 8 16 <NA>
9 58 Aloe Juice 54 172.8 4 7 8 10 8
2.2 Exploratory Data Analysis: i.e. the eyeball method
Do the two groups, treatment and control, have different oral conditions at initial observation? What about four weeks later?
Judge any difference in centers (means) within the context of the within group spread (stadard deviation/variance)
2.2.1 Means and SDs
cancer_clean %>%
dplyr::group_by(trt) %>%
furniture::table1(totalcin, totalcw4,
na.rm = FALSE)
--------------------------------
trt
Placebo Aloe Juice
n = 14 n = 11
totalcin
6.6 (0.9) 6.5 (2.1)
totalcw4
10.1 (3.6) 10.6 (3.5)
--------------------------------
2.2.2 Stacked Histograms
<IP_ADDRESS> Baseline Oral Condition
cancer_clean %>%
ggplot(aes(totalcin)) +
geom_histogram(bins = 10) +
facet_grid(trt ~ .)
<IP_ADDRESS> Four Weeks Oral Condition
cancer_clean %>%
ggplot(aes(totalcw4)) +
geom_histogram(bins = 10) +
facet_grid(trt ~ .)
2.2.3 Side-by-Side Boxplots
<IP_ADDRESS> Baseline Oral Condition
cancer_clean %>%
ggplot(aes(x = trt,
y = totalcin)) +
geom_boxplot()
<IP_ADDRESS> Four Weeks Oral Condition
cancer_clean %>%
ggplot(aes(x = trt,
y = totalcw4)) +
geom_boxplot()
2.3 Assumptions
2.3.1 Independence
BOTH Samples were drawn INDEPENDENTLY at random (at least as representative as possible)
- Nothing can be done to fix NON-representative samples!
- Can not for with any statistically test
- If idenpendence is violated, you may want to use a paired-samples t-test
2.3.2 Normality
A variable is said to follow the normal distribution if it resembles the normal curve. Specifically it is symetrical, unimodal, and bell shaped.
The continuous variable has a NORMAL distribution in BOTH populations
- Not as important if the sample is large (Central Limit Theorem)
- IF the sample is far from normal &/or small, might want to use a different method
Options to judging normality:
- Visualization of each sample’s distribution
- Stacked histograms, but is sensitive to binning choices (number or width)
- Side-by-side boxplots, shows median instead of mean as central line
- Seperate QQ plots (straight \(45^\circ\) line), but is sensitive to outliers!
- Calculate Skewness and Kurtosis, within each group
- Divided each value by its standard error (SE)
- A result \(\gt \pm 2\) indicates issues
- Divided each value by its standard error (SE)
- Formal Inferencial Tests for Normality, on each group
- Null-hypothesis: population is normally distributed
- A \(p \lt .05\) ???indicate snon-normality
- For smaller samples, use Shapiro-Wilk’s Test
- For larger samples, use Kolmogorov-Smirnov’s Test
<IP_ADDRESS> Baseline Oral Condition
cancer_clean %>%
ggplot(aes(sample = totalcin)) + # make sure to include "sample = "
geom_qq() + # layer on the dots
stat_qq_line() + # layer on the line
facet_grid(. ~ trt) # panel by group
cancer_clean %>%
dplyr::filter(trt == "Placebo") %>% # select one group
dplyr::pull(totalcin) %>% # extract the continuous variable
shapiro.test() # test for normality
Shapiro-Wilk normality test
data: .
W = 0.6807, p-value = 0.0002349
cancer_clean %>%
dplyr::filter(trt == "Aloe Juice") %>% # select one group
dplyr::pull(totalcin) %>% # extract the continuous variable
shapiro.test() # test for normality
Shapiro-Wilk normality test
data: .
W = 0.78534, p-value = 0.006034
Shapiro-Wilk’s tests yield evidence that baseline oral condition is NOT normally distributed in the placebo group, W = .681, p <.001, nor the treatment group, W = .785, p = .006. Visual inspection suggests that violatioins may by more extreme in the placebo group.
<IP_ADDRESS> Four Weeks Oral Condition
cancer_clean %>%
ggplot(aes(sample = totalcw4)) + # make sure to include "sample = "
geom_qq() + # layer on the dots
stat_qq_line() + # layer on the line
facet_grid(. ~ trt) # panel by group
cancer_clean %>%
dplyr::filter(trt == "Placebo") %>% # select one group
dplyr::pull(totalcw4) %>% # extract the continuous variable
shapiro.test() # test for normality
Shapiro-Wilk normality test
data: .
W = 0.88272, p-value = 0.06356
cancer_clean %>%
dplyr::filter(trt == "Aloe Juice") %>% # select one group
dplyr::pull(totalcw4) %>% # extract the continuous variable
shapiro.test() # test for normality
Shapiro-Wilk normality test
data: .
W = 0.92906, p-value = 0.4014
Shapiro-Wilk’s tests yielded no evidence that oral condition is NOT normally distributed four weeks after baseline in the placebo group, \(W = .883, p = .064\), and the treatment group, \(W = .929, p = .401\).
2.3.3 HOV
Two Populations exhibit Homogeneity of Variance (HOV), i.e. have about the same amount of spread
Before performing the \(t\) test, check to see if the assumption of homogeneity of variance is met using Levene’s Test. For a independent samples t
-test for means, the groups need to have the same amount of spread (SD) in the measure of interest.
Use the car:leveneTest()
function tests the HOV assumtion.
Inside the funtion you need to specify at least three options (sepearated by commas):
-
the formula:
continuous_var ~ grouping_var
(replace with your variable names) -
the dataset:
data = .
to pipe it from above -
the center:
center = “mean”
since we are comparing means
<IP_ADDRESS> Baseline Oral Condition
Do the participants in the treatment and control groups have the same spread in oral condition at BASELINE?
cancer_clean %>%
car::leveneTest(totalcin ~ trt, # formula: continuous_var ~ grouping_var
data = ., # pipe in the dataset
center = "mean") # The default is "median"
Levene's Test for Homogeneity of Variance (center = "mean")
Df F value Pr(>F)
group 1 2.2103 0.1507
23
No violations of homogeneity were detected, \(F(1, 23) = 2.210, p = .151\).
<IP_ADDRESS> Four Weeks Oral Condition
Do the participants in the treatment and control groups have the same spread in oral condition at the FOURTH WEEK?
cancer_clean %>%
car::leveneTest(totalcw4 ~ trt, # formula: continuous_var ~ grouping_var
data = ., # pipe in the dataset
center = "mean") # The default is "median"
Levene's Test for Homogeneity of Variance (center = "mean")
Df F value Pr(>F)
group 1 0 0.995
23
No violations of homogeneity were detected, \(F(1, 23) = 0, p = .995\).
2.4 Inference
Formal Statistical Test: t-Test for Difference in Independent Group Means
Use the same t.test()
funtion we have used for a single sample, but speficy a few more options.
Inside the funtion you need to specify at least three options (sepearated by commas):
-
the formula:
continuous_var ~ grouping_var
(replace with your variable names)
-
the dataset:
data = .
to pipe it from above
You MAY need/want to specify some or all of the following options you may way to leave as the default or override:
-
HOV assumed:
-
var.equal = FALSE
Default Seperate-Variance test using Welch’s df
-
var.equal = TRUE
Pooled-Variance test (if HOV is NOT violated)
-
-
Number of tails:
-
alternative = “two.sided”
Default Allows for a 2-sided alternative -
alternative = “less”
Only Allows: group 1 < group 2 -
alternative = “more”
Only Allows: group 1 > group 2
-
-
Independent vs. paired:
-
paired = FALSE
Default Conducts an INDEOENDENT groups t-Test
-
paired = TRUE
Conducts a PAIRED meausres t-Test
-
-
Confidence level:
-
conf.level = 0.95
Default Computes the 95% confidence inverval
-
conf.level = 0.90
Changes to a 90% confidence interval
-
2.4.1 Pooled Variance Test
Use when there are no violations of HOV
<IP_ADDRESS> Baseline Oral Condition
Do the participants in the treatment group have a different average oral condition at BASELINE, compared to the control group?
# Minimal syntax
cancer_clean %>%
t.test(totalcin ~ trt, # formula: continuous_var ~ grouping_var
data = ., # pipe in the dataset
var.equal = TRUE) # HOV was violated (option = TRUE)
Two Sample t-test
data: totalcin by trt
t = 0.18566, df = 23, p-value = 0.8543
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
-1.185479 1.419245
sample estimates:
mean in group Placebo mean in group Aloe Juice
6.571429 6.454545
No evidence of a differnece in mean oral condition at baseline, \(t(23) = 0.186, p = .854\). Note: this test may be unreliable due to the non-normality of the samll samples.
<IP_ADDRESS> Four Weeks Oral Condition
Do the participants in the treatment group have a different average oral condition at the FOURTH WEEK, compared to the control group?
# Fully specified function
cancer_clean %>%
t.test(totalcw4 ~ trt, # formula: continuous_var ~ grouping_var
data = ., # pipe in the dataset
var.equal = TRUE, # default: HOV was violated (option = TRUE)
alternative = "two.sided", # default: 2 sided (options = "less", "greater")
paired = FALSE, # default: independent (option = TRUE)
conf.level = .95) # default: 95% (option = .9, .90, ect.)
Two Sample t-test
data: totalcw4 by trt
t = -0.34598, df = 23, p-value = 0.7325
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
-3.444215 2.457202
sample estimates:
mean in group Placebo mean in group Aloe Juice
10.14286 10.63636
No evidence of a differnece in mean oral condition at the fourth week, \(t(23) = -0.350, p = .733\).
2.4.2 Seperate Variance Test
Use if there are violations of HOV or the samples are difference sizes


CTA announce goaline technology in the Supercup and defends VAR
by BeSoccerThe Technical Committee of Referees (CTA), which is led by ex referee Carlos Velasco Carballo, has announced new features and defended VAR
For the first time, a national competition will have goal-line technology. This tool allows for ghost goals not to be given. This will be debut in the Spanish Supercup.
"Referees will have goal-line technology for the first time in the Spanish Supercup," Velasco Carballo said, who detailed how it works.
Featured links
- BREAKING NEWS: Mourinho replaces Pochettino at Tottenham
- The latest football transfers news and rumours
- Wales, golf, Madrid... in that order
- Luis Enrique returns to Spain national team
"The system consists of 14 cameras on the playing field. A high-resolution camera will be on the goal line. This system is connected to the referees and in less than a second the referees hear the word goal three times and the clock vibrates to indicate it. This is historic," he declared.
Velasco Carballo also defended VAR. "VAR, in technology, has failed zero times. Not once. The system has never stopped being available. In 305 games there are more than 3,000 incidents and all of them have been checked and there has been no problem. Yes, there were technological incidents, but then the support systems worked. All the passages of play could be checked," he said.


|
|
Something, that contains TreeWrapper and data that can be retrieved by quantity keys. More...
#include <Data.h>
Public Types | |
| typedef DataGroup< DT, G > | datagroup_t |
| typedef DT | data_t |
| typedef DT::datatype_t | datatype_t |
| typedef std::map< std::string, DT > | map_t |
| Public Types inherited from TreeWrapper< DT::datatype_t > | |
| typedef DT | datatype_t |
| typedef DT::tree_t | tree_t |
| typedef DT::tree_iter_t | tree_iter_t |
Public Member Functions | |
| DataGroup (typename DT::tree_t &tree, const drain::RegExp &quantityRegExp=drain::RegExp()) | |
Given a dataset subtree, like tree["dataset3"], constructs a data map of desired quantities. | |
| DataGroup (const datagroup_t &src) | |
| bool | has (const std::string &quantity) const |
| const data_t & | getData (const std::string &quantity) const |
| data_t & | getData (const std::string &quantity) |
| const data_t & | getData (const drain::RegExp ®Exp) const |
| data_t & | create (const std::string &quantity, const std::string &templateQuantity, const std::string &encodingParams) |
Creates (or overrides) data array for quantity and scales it. More... | |
| data_t & | getFirstData () |
| const data_t & | getFirstData () const |
| data_t & | getLastData () |
| const data_t & | getLastData () const |
| Public Member Functions inherited from TreeWrapper< DT::datatype_t > | |
| const drain::VariableMap & | getWhat () const |
| drain::VariableMap & | getWhat () |
| const drain::VariableMap & | getWhere () const |
| drain::VariableMap & | getWhere () |
| const drain::VariableMap & | getHow () const |
| drain::VariableMap & | getHow () |
| void | setNoSave (bool noSave=true) |
| virtual const tree_t & | getTree () const |
| virtual tree_t & | getTree () |
Static Protected Member Functions | |
| static const data_t & | getEmpty () |
| static DT::tree_t & | init (typename DT::tree_t &t, datagroup_t &dst, const drain::RegExp &quantityRegExp=drain::RegExp()) |
Given a dataset h5 subtree, like tree["dataset3"], collects all (or desired) quantities to a data object. More... | |
| static DT::tree_t & | adapt (const datagroup_t &src, datagroup_t &dst) |
Additional Inherited Members | |
| Protected Member Functions inherited from TreeWrapper< DT::datatype_t > | |
| TreeWrapper (tree_t &tree) | |
| TreeWrapper (const TreeWrapper &d) | |
| const drain::VariableMap & | getAttr () const |
| drain::VariableMap & | getAttr () |
| Protected Attributes inherited from TreeWrapper< DT::datatype_t > | |
| tree_t & | tree |
| General HDF5 data structure. | |
Something, that contains TreeWrapper and data that can be retrieved by quantity keys.
So, data4/ or quality2/ for example.
| DT | - data object type: PlainData<...> or Data<...> |
| G | - the path element of children: ODIMPathElem:: DATASET, DATA, or QUALITY |
Applications: see SweepSrc and ProductDst below.
|
inline |
Creates (or overrides) data array for quantity
and scales it.
| quantity | - |
| templateQuantity | - predefined quantity the scaling of which is used in initialisation |
| encodingParams | (optional) - parameters overriding those of template quantity |
|
inlinestaticprotected |
Given a dataset
h5 subtree, like tree["dataset3"], collects all (or desired) quantities to a data object.
| t | - target data tree |
| dst | - odim wrapper for the data tree |
| quantityRegExp | - optional quantity filter, if only a subset is desired. |
Accept groups of type G only


Hello,
Bagas Kurniawan
Hello,
Bagas Kurniawan
Order
Edit Your Profile
Order History
Logout
Where would you like to go?
Fare: Rp 99.9999
Book
Walking


👋🏼 My name is Ryan.
I'm a software engineer/architect. This is my blog.
Articles:
Nov 2022 - Why Comments
This blog was made with ♥ using
only html
.


A client that uses SOAP messages to communicate with the underlying cloud platform (here, AppScale). This client is similar to that used in the AppScale Tools, but with non-Neptune SOAP calls removed.
The SOAP client that we use to communicate with the AppController.
The IP address of the AppController that we will be connecting to.
The secret string that is used to authenticate this client with AppControllers. It is initially generated by appscale-run-instances and can be found on the machine that ran that tool, or on any AppScale machine.
A constructor that requires both the IP address of the machine to communicate with as well as the secret (string) needed to perform communication. AppControllers will reject SOAP calls if this secret (basically a password) is not present - it can be found in the user’s .appscale directory, and a helper method is usually present to fetch this for us.
# File AppController/lib/app_controller_client.rb, line 58 def initialize(ip, secret) @ip = ip @secret = secret @conn = SOAP::RPC::Driver.new("https://#{@ip}:17443") @conn.add_method("set_parameters", "djinn_locations", "database_credentials", "app_names", "secret") @conn.add_method("set_apps", "app_names", "secret") @conn.add_method("status", "secret") @conn.add_method("get_stats", "secret") @conn.add_method("update", "app_names", "secret") @conn.add_method("stop_app", "app_name", "secret") @conn.add_method("get_all_public_ips", "secret") @conn.add_method("is_done_loading", "secret") @conn.add_method("is_done_initializing", "secret") @conn.add_method("add_role", "new_role", "secret") @conn.add_method("remove_role", "old_role", "secret") @conn.add_method("get_queues_in_use", "secret") end
# File AppController/lib/app_controller_client.rb, line 214 def add_role(role) make_call(NO_TIMEOUT, RETRY_ON_FAIL, "add_role") { @conn.add_role(role, @secret) } end
# File AppController/lib/app_controller_client.rb, line 210 def get_all_public_ips() make_call(30, RETRY_ON_FAIL, "get_all_public_ips") { @conn.get_all_public_ips(@secret) } end
# File AppController/lib/app_controller_client.rb, line 268 def get_queues_in_use() make_call(NO_TIMEOUT, RETRY_ON_FAIL, "get_queues_in_use") { @conn.get_queues_in_use(@secret) } end
# File AppController/lib/app_controller_client.rb, line 190 def get_stats(ok_to_fail=false) make_call(10, !ok_to_fail, "get_stats", ok_to_fail) { @conn.get_stats(@secret) } end
# File AppController/lib/app_controller_client.rb, line 176 def get_status(ok_to_fail=false) if !HelperFunctions.is_port_open?(@ip, 17443) if ok_to_fail return false else abort("AppController to contact is not running") end end make_call(10, !ok_to_fail, "get_status", ok_to_fail) { @conn.status(@secret) } end
# File AppController/lib/app_controller_client.rb, line 123 def get_userappserver_ip(verbose_level="low") userappserver_ip, status, state, new_state = "", "", "", "" loop { status = get_status() new_state = status.scan(%rCurrent State: ([\w\s\d\.,]+)\n/).flatten.to_s.chomp if verbose_level == "high" and new_state != state puts new_state state = new_state end if status == "false: bad secret" abort("\nWe were unable to verify your secret key with the head node specified in your locations file. Are you sure you have the correct secret key and locations file?\n\nSecret provided: [#{@secret}]\nHead node IP address: [#{@ip}]\n") end if status =~ %rDatabase is at (#{IP_OR_FQDN})/ and $1 != "not-up-yet" userappserver_ip = $1 break end sleep(10) } return userappserver_ip end
# File AppController/lib/app_controller_client.rb, line 202 def is_done_initializing?() make_call(30, RETRY_ON_FAIL, "is_done_initializing", ok_to_fail=true) { @conn.is_done_initializing(@secret) } end
# File AppController/lib/app_controller_client.rb, line 206 def is_done_loading?() make_call(30, RETRY_ON_FAIL, "is_done_loading", ok_to_fail=true) { @conn.is_done_loading(@secret) } end
A helper method that makes SOAP calls for us. This method is mainly here to reduce code duplication: all SOAP calls expect a certain timeout and can tolerate certain exceptions, so we consolidate this code into this method. Here, the caller specifies the timeout for the SOAP call (or NO_TIMEOUT if an infinite timeout is required) as well as whether the call should be retried in the face of exceptions. Exceptions can occur if the machine is not yet running or is too busy to handle the request, so these exceptions are automatically retried regardless of the retry value. Typically callers set this to false to catch ‘Connection Refused’ exceptions or the like. Finally, the caller must provide a block of code that indicates the SOAP call to make: this is really all that differs between the calling methods. The result of the block is returned to the caller.
# File AppController/lib/app_controller_client.rb, line 91 def make_call(time, retry_on_except, callr, ok_to_fail=false) refused_count = 0 max = 5 begin Timeout::timeout(time) { yield if block_given? } rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH if refused_count > max return false if ok_to_fail abort("Connection was refused. Is the AppController running?") else refused_count += 1 sleep(1) retry end rescue Timeout::Error return false if ok_to_fail retry rescue OpenSSL::SSL::SSLError, NotImplementedError, Errno::EPIPE, Errno::ECONNRESET retry rescue Exception => except if retry_on_except retry else abort("[#{callr}] We saw an unexpected error of the type #{except.class} with the following message:\n#{except}.") end end end
CGB - removed timeout here - removing cassandra slave requires it to port the data it owns to somebody else, which takes ~30 seconds in the trivial case
# File AppController/lib/app_controller_client.rb, line 221 def remove_role(role) make_call(NO_TIMEOUT, RETRY_ON_FAIL, "remove_role") { @conn.remove_role(role, @secret) } end
# File AppController/lib/app_controller_client.rb, line 225 def run_neptune_job(nodes, job_data) type = "" if job_data.class == Array type = job_data[0]["@type"] else type = job_data["@type"] end Djinn.log_debug("neptune job type is #{type}") if NEPTUNE_JOBS.include?(type) method_to_call = "neptune_#{type}_run_job" @conn.add_method(method_to_call, "nodes", "jobs", "secret") make_call(30, RETRY_ON_FAIL, "run_neptune_job") { @conn.send(method_to_call.to_sym, nodes, job_data, @secret) } else not_supported_message = "The job type you specified, '#{type}', is " + "not supported. Supported jobs are #{NEPTUNE_JOBS.join(', ')}." abort(not_supported_message) end end
# File AppController/lib/app_controller_client.rb, line 157 def set_apps(app_names) result = "" make_call(10, ABORT_ON_FAIL, "set_apps") { result = conn.set_apps(app_names, @secret) } abort(result) if result =~ %rError:/ end
# File AppController/lib/app_controller_client.rb, line 149 def set_parameters(locations, creds, apps_to_start) result = "" make_call(10, ABORT_ON_FAIL, "set_parameters") { result = conn.set_parameters(locations, creds, apps_to_start, @secret) } abort(result) if result =~ %rError:/ end
# File AppController/lib/app_controller_client.rb, line 165 def status(print_output=true) status = get_status() if print_output puts "Status of node at #{ip}:" puts "#{status}" end return status end
# File AppController/lib/app_controller_client.rb, line 194 def stop_app(app_name) make_call(30, RETRY_ON_FAIL, "stop_app") { @conn.stop_app(app_name, @secret) } end
# File AppController/lib/app_controller_client.rb, line 198 def update(app_names) make_call(30, RETRY_ON_FAIL, "update") { @conn.update(app_names, @secret) } end
# File AppController/lib/app_controller_client.rb, line 245 def wait_for_node_to_be(new_roles) roles = new_roles.split(":") loop { ready = true status = get_status Djinn.log_debug("ACC: Node at #{@ip} said [#{status}]") roles.each { |role| if status =~ %r#{role}/ Djinn.log_debug("ACC: Node is #{role}") else ready = false Djinn.log_debug("ACC: Node is not yet #{role}") end } break if ready } Djinn.log_debug("ACC: Node at #{@ip} is now #{new_roles}") return end