text:
# Math Help - Dot and Scalar Product

1. ## Dot and Scalar Product

I have been lost in this forever due to missing the lecture, but does anybody know how to do this? Thank you for the help if you can.
a=3.0i+3.0j-2.0k
b=-1.0i-4.0j+2.0k
c=2.0i+2.0j+1.0k
The question is: a(dot)(axb)=?

Any help would be appreciated.

2. Originally Posted by Elite_Guard89
I have been lost in this forever due to missing the lecture, but does anybody know how to do this? Thank you for the help if you can.
a=3.0i+3.0j-2.0k
b=-1.0i-4.0j+2.0k
c=2.0i+2.0j+1.0k
The question is: a(dot)(axb)=?

Any help would be appreciated.
What you are asked to evaluate here is what is know as the scalar triple product.

$\bold a\cdot\left(\bold b\times\bold c\right)=\left|\begin{array}{ccc}a_x&a_y&a_z\\b_x& b_y&b_z\\c_x&c_y&c_z\end{array}\right|$

Try to evaluate $\left|\begin{array}{ccc}3&3&-2\\-1&-4&2\\2&2&1\end{array}\right|$

This will give you the desired answer.

I hope this helps!

--Chris

3. Okay, then how would you do a(dot)(b+c)?

4. Add the vectors b and c to get b + c. Then take the dot product of a and what you found?

5. I understand the b+c part, but I'm not sure on how you find the dot product of a and what (b+c) creates.

6. Originally Posted by Elite_Guard89
I understand the b+c part, but I'm not sure on how you find the dot product of a and what (b+c) creates.
When you take the dot product of a and this new vector (b+c), we get a scalar value. You multiply the like components together, and then add them all together. Note that $\bold i\cdot\bold i=\bold j\cdot\bold j=\bold k\cdot\bold k=1$

I hope this helps!

--Chris

7. Why not?

$\bold{b} + \bold{c} = (-1.0 + 2.0) \bold{i} + (- 4.0 + 2.0) \bold{j} + (2.0 + 1.0) \bold{k} = 1.0 \bold{i} - 2.0 \bold{j} + 3.0\bold{k}$

So: $\bold{a} \cdot (\bold{b} + \bold{c}) = (3.0 \bold{i} + 3.0 \bold{j} - 2.0 \bold{k}) \cdot (1.0 \bold{i} - 2.0 \bold{j} + 3.0\bold{k})$

Surely you can take the dot product of two vectors?

8. I would if I knew what a dot product was lol.

9. Originally Posted by Elite_Guard89
I would if I knew what a dot product was lol.
The definition of the dot product:

If $\bold a=\left$ and $\bold b=\left$, the the dot product of a and b is:

$\bold a\cdot\bold b=a_xb_x+a_yb_y+a_zb_z$

I hope this helps!

--Chris

w00t!!! My 8th post!!


text:
5

# Write mechanisms for the following reactions using arrows to show the electron movement for each step of the reaction_ Show all steps, including proton transfers as...

## Question

###### Write mechanisms for the following reactions using arrows to show the electron movement for each step of the reaction_ Show all steps, including proton transfers as separate steps; balance all equations_ Use Kekule-Lewis structures (bonding lectrons a5 lines, lone pairs as dots, show all formal charges).Cl CIz C#z CI (cch FoF PrEetel hy 22) (b) fEce Ch;-e-O-Ch; cha-Cro-c_CHz (all stees ) chfhoh

Write mechanisms for the following reactions using arrows to show the electron movement for each step of the reaction_ Show all steps, including proton transfers as separate steps; balance all equations_ Use Kekule-Lewis structures (bonding lectrons a5 lines, lone pairs as dots, show all formal charges). Cl CIz C#z CI (cch FoF PrEetel hy 22) (b) fEce Ch;-e-O-Ch; cha-Cro-c_CHz (all stees ) chfhoh

#### Similar Solved Questions

##### How would you interpret confidence level of 88% when n = 300 and you are estimating u?If you construct 6000 887 C,I.'s, how many of those intervals would contain the true value of u?Ans 4b
How would you interpret confidence level of 88% when n = 300 and you are estimating u? If you construct 6000 887 C,I.'s, how many of those intervals would contain the true value of u? Ans 4b...
##### Consider the set of all vectors (2,w) â‚¬ C2 such that z w = 1. Then A itis a linear space because any linear combination of tWo vectors in the set is also in the set B itis a linear space because itis subset of C2 C. itis not a linear space because (0,0) is not in the set (ANS} Ditis not linear space because (1,1) is not in the setA. itis linear space because itis subset ofC?_B.itis not a linear space because (1,1) is notin the setC.itis not a linear space because (0, 0) is not in the setD. iti
Consider the set of all vectors (2,w) â‚¬ C2 such that z w = 1. Then A itis a linear space because any linear combination of tWo vectors in the set is also in the set B itis a linear space because itis subset of C2 C. itis not a linear space because (0,0) is not in the set (ANS} Ditis not linear...
##### Determine the area under the standard nomrlal cuve tniat lies to the leit of az= 64, (b)z = 06, ()z=0.47, and (d)z=The area to the leit of z = 1.64i5(Round to four decimal places as needed )Enter your answer in the answer box and then click Check Answer3 Peraining partsClear AIl
Determine the area under the standard nomrlal cuve tniat lies to the leit of az= 64, (b)z = 06, ()z=0.47, and (d)z= The area to the leit of z = 1.64i5 (Round to four decimal places as needed ) Enter your answer in the answer box and then click Check Answer 3 Peraining parts Clear AIl...
##### Accojdinelolkanng rraction ot Al Molctcarbon diehkcillramnlenamsahlarmEcose atenCOlg) B,0(4) - cO-() Es(g)mol crbon dipatr
Accojdine lolkanng rraction ot Al Molct carbon diehkcill ramnlen ams ahlarm Ecose aten COlg) B,0(4) - cO-() Es(g) mol crbon dipatr...
##### 8.65 Explain the selectivity observed in the following reactions.<smiles>O=C1OC2CCCCC2C1(Br)Br</smiles> $mathrm{CH}_{3} mathrm{O}^{-}$
8.65 Explain the selectivity observed in the following reactions. <smiles>O=C1OC2CCCCC2C1(Br)Br</smiles> $mathrm{CH}_{3} mathrm{O}^{-}$...

format: plain


text:
Documentation

### This is machine translation

Translated by
Mouseover text to see original. Click the button below to return to the English version of the page.

## Vector Autoregression (VAR) Models

### Types of Multivariate Time Series Models

The basic multivariate time series models based on linear autoregressive, moving average models are:

Model NameAbbreviationEquation
Vector Autoregression VAR(p)

`${y}_{t}=c+\sum _{i=1}^{p}{\Phi }_{i}{y}_{t-i}+{\epsilon }_{t}$`

Vector Moving Average VMA(q)

`${y}_{t}=c+\sum _{j=1}^{q}{\Theta }_{j}{\epsilon }_{t-j}+{\epsilon }_{t}$`

Vector Autoregression Moving Average VARMA(p, q)

`${y}_{t}=c+\sum _{i=1}^{p}{\Phi }_{i}{y}_{t-i}+\sum _{j=1}^{q}{\Theta }_{j}{\epsilon }_{t-j}+{\epsilon }_{t}$`

Vector Autoregression Moving Average with a linear time trendVARMA(p, q)

`${y}_{t}=c+\delta t+\sum _{i=1}^{p}{\Phi }_{i}{y}_{t-i}+\sum _{j=1}^{q}{\Theta }_{j}{\epsilon }_{t-j}+{\epsilon }_{t}$`

Vector Autoregression Moving Average with eXogenous inputs VARMAX(p, q)

`${y}_{t}=c+\beta {x}_{t}+\sum _{i=1}^{p}{\Phi }_{i}{y}_{t-i}+\sum _{j=1}^{q}{\Theta }_{j}{\epsilon }_{t-j}+{\epsilon }_{t}$`

Structural Vector Autoregression Moving AverageSVARMA(p, q)

`${\Phi }_{0}{y}_{t}=c+\sum _{i=1}^{p}{\Phi }_{i}{y}_{t-i}+\sum _{j=1}^{q}{\Theta }_{j}{\epsilon }_{t-j}+{\Theta }_{0}{\epsilon }_{t}$`

The following variables appear in the equations:

• yt is the vector of response time series variables at time t. yt has n elements.

• c is a constant vector of offsets, with n elements.

• Φi are n-by-n matrices for each i. The Φi are autoregressive matrices. There are p autoregressive matrices, and some can be entirely composed of zeros.

• εt is a vector of serially uncorrelated innovations, vectors of length n. The εt are multivariate normal random vectors with a covariance matrix Σ.

• Θj are n-by-n matrices for each j. The Θj are moving average matrices. There are q moving average matrices, and some can be entirely composed of zeros.

• δ is a constant vector of linear time trend coefficients, with n elements.

• xt is an r-by-1 vector representing exogenous terms at each time t. r is the number of exogenous series. Exogenous terms are data (or other unmodeled inputs) in addition to the response time series yt. Each exogenous series appears in all response equations.

• β is an n-by-r constant matrix of regression coefficients of size r. So the product βxt is a vector of size n.

Generally, the time series yt and xt are observable. In other words, if you have data, it represents one or both of these series. You do not always know the offset c, trend coefficient δ, coefficient β, autoregressive matrices Φi, and moving average matrices Θj. You typically want to fit these parameters to your data. See `estimate` for ways to estimate unknown parameters. The innovations εt are not observable, at least in data, though they can be observable in simulations.

Econometrics Toolbox™ supports the creation and analysis of the VAR(p) model using `varm` and associated methods.

### Lag Operator Representation

There is an equivalent representation of the linear autoregressive equations in terms of lag operators. The lag operator L moves the time index back by one: Lyt = yt–1. The operator Lm moves the time index back by m: Lmyt = ytm.

In lag operator form, the equation for a SVARMAX(p, q) model becomes

`$\left({\Phi }_{0}-\sum _{i=1}^{p}{\Phi }_{i}{L}^{i}\right){y}_{t}=c+\beta {x}_{t}+\left({\Theta }_{0}+\sum _{j=1}^{q}{\Theta }_{j}{L}^{j}\right){\epsilon }_{t}.$`

This equation can be written as

`$\Phi \left(L\right){y}_{t}=c+\beta {x}_{t}+\Theta \left(L\right){\epsilon }_{t},$`

where

`$\Theta \left(L\right)={\Theta }_{0}-\sum _{i=1}^{p}{\Theta }_{i}{L}^{i}$`

and

`$\Theta \left(L\right)={\Theta }_{0}+\sum _{j=1}^{q}{\Theta }_{j}{L}^{j}.$`

### Stable and Invertible Models

A VAR model is stable if

This condition implies that, with all innovations equal to zero, the VAR process converges to c as time goes on. See Lütkepohl [80] Chapter 2 for a discussion.

A VMA model is invertible if

This condition implies that the pure VAR representation of the process is stable. See Lütkepohl [80] Chapter 11 for a discussion of invertible VMA models.

A VARMA model is stable if its VAR polynomial is stable. Similarly, a VARMA model is invertible if its VMA polynomial is invertible.

There is no well-defined notion of stability or invertibility for models with exogenous inputs (e.g., VARMAX models). An exogenous input can destabilize a model.

### Building VAR Models

To understand a multiple time series model, or multiple time series data, you generally perform the following steps:

1. Import and preprocess data.

2. Specify a model.

1. Creating VAR Models to set up a model using `varm`:

2. Determining an Appropriate Number of Lags to determine an appropriate number of lags for your model

3. Fit the model to data. See Fitting Models to Data to use `estimate` to estimate the unknown parameters in your models.

4. Analyze and forecast using the fitted model. This can involve:

1. Examining the Stability of a Fitted Model to determine whether your model is stable.

2. VAR Model Forecasting to forecast directly from models or to forecast using a Monte Carlo simulation.

3. Calculating Impulse Responses to calculate impulse responses, which give forecasts based on an assumed change in an input to a time series.

4. Compare the results of your model's forecasts to data held out for forecasting. For an example, see VAR Model Case Study.

Your application need not involve all of the steps in this workflow. For example, you might not have any data, but want to simulate a parameterized model. In that case, you would perform only steps 2 and 4 of the generic workflow.

You might iterate through some of these steps.


text:
# Cattle problem — all solutions in $\mathbb{Z}$

There is an ancient problem, I remember reading once in a book while I was a kid, that says: there was a father who had $N$ sons and $T$ cows. He divided the cows among the sons in the following order: for the first son, $1 + 1/7$ of the remaining; for the second son $2+ 1/7$ of the remaining; ..., for the $i$'th son $i+1/7$ of the remaining... the question asked for the numbers T and N. In fact $N=6$ and $T=36$ is a solution. I found that it can be generalized to any given ratio $1/M$ and $N=M-1$ and $T=N^2$ is a solution. I was wondering if there is any other solution to the general problem in $\mathbb{Z}$. I have formalized the problem as following:

We have a system of equations described by the following $N+1$ equations defined in $\mathbb{Z}$: \begin{align*} n_1 &= 1+ \frac{T-1}{M}\\ n_2 &= 2+ \frac{T-2-n_1}{M}\\ &\vdots\\ n_i &= i+ \frac{T-i-\sum\limits_{j=1}^{i-1} n_j}{M}\\ T&=\sum\limits_{i=1}^{N} n_i. \end{align*}

One set of solutions is given by: \begin{align*} T &= N^2\\ n_i&=N\\ M&=N+1 \end{align*}

For example, when $N=6$, $T=36$, $n_1 = n_2 = \cdots = n_6 = 6$ is a solution.

I'm wondering if there is any other non-trivial integer solutions to the above system of equations.

Thanks,

MG

-

Are you interested in solutions in $\mathbb{Z}$ or solutions in $\mathbb{Z}^+$?

Another trivial solution in integers is $$M=1$$ $$n_1=T$$ $$n_i = 0, \forall i \neq 1$$

So setting $M=1$, you can choose $T$ to be any integer and you will get only integer solutions since the condition $T = \displaystyle \sum_{i=1}^N n_i$ is trivially satisfied and $n_i$ are defined recursively as integer combinations of previous $n_i$'s and $T$ with $n_1 = T$.

EDIT: Lets analyze further to see other possible integer solutions. (My analysis is incomplete will try to do this later tonight/tomorrow.)

$$n_N = N + \frac{T-N - \displaystyle \sum_{j=1}^{N-1} n_j}{M}$$

From the constraint, $T = \displaystyle \sum_{j=}^N n_j$, we get $n_N = T - \displaystyle \sum_{j=1}^{N-1} n_j$ and hence

$$n_N = N + \frac{n_N - N}{M}$$ $$\left( n_N-N \right) \left(1-\frac{1}{M} \right) = 0$$ which gives us that $$n_N = N \text{ or } M=1$$

If $M=1$, then we already have the solution $$n_1 = T \text{ and } n_i = 0 \text{ } \forall \text{ }i>1$$

If $M \neq 1$, then $n_N = N$, and we have $$n_{N-1} = N-1 + \frac{T-(N-1) - (n_1+n_2+ \cdots n_{N-2})}{M} = N - 1 + \frac{N + n_{N-1}-(N-1)}{M}$$

$$(n_{N-1} - N + 1)(M-1) = N$$

From which we get that $M \neq 1$ and since we are interested only in integer solutions we have $(M-1)|N$ i.e. $M = 1 + a$ where $a|N$. Then $n_{N-1} = N + \frac{N}{a} - 1$

$$n_{N-2} = N-2 + \frac{n_N + n_{N-1} + n_{N-2} - (N-2)}{1+a}$$

$$n_{N-2} - (N-2) - \frac{n_{N-2} - (N-2)}{1+a} = \frac{N + N + \frac{N}{a}-1}{1+a}$$

$$a(n_{N-2} - (N-2)) = 2N + \frac{N}{a} - 1$$

-


text:
# Describe the zero vector (the additive identity) of the vector space.

– Given Vector Space:

$\mathbb{R}^4$

Additive Identity is defined as the value that if added or subtracted from a second value, does not change it. For example, if we add $0$ to any real numbers, it does not change the value of the given real numbers. We can call Zero $0$ the Additive Identity of the Real Numbers.

If we consider $R$ as a real number and $I$ as an Additive Identity, then as per Additive Identity Law:

$R+I=I+R=R$

A Vector Space is defined as a Set comprising of one or more vector elements and it is represented by $\mathbb{R}^n$ where $n$ represents the number of elements in the given vector space.

Given that:

Vector Space $=\mathbb{R}^4$

This shows that $\mathbb{R}^4$ has $4$ vector elements.

Let us represent $\mathbb{R}^4$ as follows:

$\mathbb{R}^4 =\ (R_1,\ R_2,\ R_3,\ R_4)$

Let us suppose that:

Additive Identity $=\mathbb{I}^4$

Let us represent $= \mathbb{I}^4$ as follows:

$\mathbb{I}^4 = (I_1,\ I_2,\ I_3,\ I_4)$

$\mathbb{R}^4\ +\mathbb{I}^4\ =\mathbb{I}^4\ +\mathbb{R}^4\ =\ \mathbb{R}^4$

Substituting the values:

$(R_1,\ R_2,\ R_3,\ R_4)\ +\ (I_1,\ I_2,\ I_3,\ I_4)\ =\ (R_1,\ R_2,\ R_3,\ R_4)$

$(R_1\ +\ I_1,\ R_2\ +{\ I}_2,\ R_3\ +{\ I}_3,\ R_4{\ +\ I}_4)\ =\ (R_1,\ R_2,\ R_3,\ R_4)$

Comparing element by element:

First Element:

$R_1\ +{\ I}_1\ =\ R_1$

$I_1\ =\ R_1\ -{\ R}_1$

$I_1\ =\ 0$

Second Element:

$R_2\ +\ I_2\ ={\ R}_2$

$I_2\ ={\ R}_2\ -{\ R}_2$

$I_2\ =\ 0$

Third Element:

$R_3\ +\ I_3\ =\ R_3$

$I_3\ =\ R_3\ -\ R_3$

$I_3\ =\ 0$

Fourth Element:

$R_4\ +\ I_4\ ={\ R}_4$

$I_4\ =\ R_4\ -\ R_4$

$I_4\ =\ 0$

Hence from the above equations, it is proved that the Additive Identity is as follows:

$(I_1,\ I_2,\ I_3,\ I_4)\ =\ (0,\ 0,\ 0,\ 0)$

$\mathbb{I}^4\ =\ (0,\ 0,\ 0,\ 0)$

## Numerical Result

The Additive Identity or Zero Vector $\mathbb{I}^4$ of $\mathbb{R}^4$ is:

$\mathbb{I}^4\ =\ (0,\ 0,\ 0,\ 0)$

## Example

For the given vector space $\mathbb{R}^2$, find the zero vector or additive identity.

Solution

Given that:

Vector Space $= \mathbb{R}^2$

This shows that $\mathbb{R}^2$ has $2$ vector elements.

Let us represent $\mathbb{R}^2$ as follows:

$\mathbb{R}^2\ =\ (R_1,\ R_2)$

Let us suppose that:

Additive Identity $= \mathbb{I}^2$

Let us represent $= \mathbb{I}^2$ as follows:

$\mathbb{I}^2\ =\ (I_1,\ I_2)$

$\mathbb{R}^2\ +\ \mathbb{I}^2\ =\ \mathbb{I}^2\ +\ \mathbb{R}^2\ =\ \mathbb{R}^2$

Substituting the values:

$(R_1,\ {\ R}_2)\ +\ (I_1,\ \ I_2)\ =\ (R_1,\ R_2)$

$(R_1\ +{\ I}_1,\ \ R_2\ +\ I_2)\ =\ (R_1,\ R_2)$

Comparing element by element:

First Element:

$R_1\ +{\ I}_1\ =\ {\ R}_1$

$I_1\ ={\ R}_1\ -{\ R}_1$

$I_1\ =\ 0$

Second Element:

$R_2\ +\ I_2\ ={\ R}_2$

$I_2\ ={\ R}_2\ -{\ R}_2$

$I_2\ =\ 0$

Hence from the above equations, it is proved that the Additive Identity is as follows:

$(I_1,\ {\ I}_2)\ =\ (0,\ 0)$

$\mathbb{I}^2\ =\ (0,\ 0)$


text:
# patternFromSlices

Reconstruct approximate 3-D radiation pattern from two orthogonal slices

## Description

example

patternFromSlices(vertislice,theta,horizslice,phi) plots the approximate 3-D pattern reconstructed from the input data containing the 2-D pattern along the vertical and horizontal plane as well as the polar and azimuthal angles in the spherical coordinates.

example

patternFromSlices(vertislice,theta,horizslice) plots the approximate 3-D pattern with the horizontal slice provided as a real-valued scalar. The syntax assumes that the antenna is omnidirectional with symmetry about the Z-axis.

patternFromSlices(vertislice,theta) plots the approximate 3-D pattern reconstructed from only vertical pattern data, assuming of azimuthal omni directionality and that horizontal pattern data is equal to maximum value of vertical pattern data.

[pat3D,thetaout,phiout] = patternFromSlices(___) returns the reconstructed pattern as a matrix with the vectors of phi and theta.

[___] = patternFromSlices(___,Name,Value) specifies options using one or more name-value pair arguments in addition to any of the input argument combinations in previous syntaxes. For example, you can specify the customization and tuning options to the pattern reconstruction method.

## Examples

collapse all

Load the MAT file containing the data of the dipole pattern.

Reconstruct the pattern from the data provided using the CrossWeighted algorithm and pattern plot options.

p = PatternPlotOptions('Transparency',0.6);
patternFromSlices(vertSlice,theta,horizSlice,phi,'Method','CrossWeighted','PatternOptions',p)

Load the MAT file containing the data of the sector antenna pattern.

Reconstruct the pattern from the data provided using the Summing algorithm.

patternFromSlices(vertSlice,theta,horizSlice,phi,'Method','Summing')

[pat3D,thetaout,phiout] = patternFromSlices(vertSlice,theta,horizSlice,phi,'Method','Summing');
pat3D = pat3D(1:5)
pat3D = 1×5

-23.2025  -23.2071  -23.2224  -23.2485  -23.2854

thetaout = thetaout(1:5)
thetaout = 1×5

180   179   178   177   176

phiout = phiout(1:5)
phiout = 1×5

-180  -179  -178  -177  -176

## Input Arguments

collapse all

Required Input Arguments

2-D pattern slice data along the vertical or the elevation plane, specified as a real-valued vector with each element unit in dBi. This parameter need not be normalized. numel(vertislice) must be equal to numel(theta).

Data Types: double

Polar or inclination angles in spherical coordinates, specified as a real-valued vector with each element unit in degrees.

Note

$\theta =90-el$

el is the elevation angle.

Data Types: double

Optional Input Arguments

2-D pattern slice data along the horizontal or the azimuthal plane, specified as a real-valued scalar in dBi or a real-valued vector with each element unit in dBi.

• If the value is a vector, then numel(horizslice) must be equal to numel(phi).

• If the value is a scalar, then the antenna is omnidirectional if the scalar value is used for all angles in the azimuthal plane.

• If no value is provided, then the antenna is omnidirectional and the default value (for the entire azimuthal slice) is set equal to the maximum directivity or gain of the elevation slice.

Data Types: double

Azimuthal angles in the spherical coordinates, specified as a real-valued vector with each element unit in degrees. If this argument is not provided:

• The antenna is assumed omnidirectional with symmetry about the Z-axis or azimuthal symmetry.

• The default values used are: phi = 0:5:360.

Data Types: double

### Name-Value Arguments

Example: 'Method', 'Summing'

Specify optional comma-separated pairs of Name,Value pair arguments. Name is the argument name and Value is the corresponding value. Name must appear inside single quotes (''). You can specify several name and value pair arguments in any order as Name1, Value1, ..., NameN, ValueN.

Approximate interpolation algorithm to perform reconstruction, specified as the comma-separated pair consisting of 'Method' and 'Summing' or 'CrossWeighted'.

Example: 'Method', 'CrossWeighted'

Data Types: char

Normalization parameter for cross-weighted summing method, specified as a comma-separated pair consisting of 'CrossWeightedNormalization' and a real-valued positive scalar. As this parameter increases, the pattern reconstruction becomes a pessimistic approximation of the estimated directivity or gain. As this parameter decreases, the pattern reconstruction becomes an optimistic approximation of the estimated directivity or gain.

Example: 'CrossWeightedNormalization',2

Data Types: double

Parameter to change pattern plot properties, specified as the comma-separated pair consisting of 'PatternOptions' and a PatternPlotOptions output. The properties that you can vary are:

• Transparency

• MagnitudeScale

Other properties used in the 'PatternOptions' for the inset figure are ignored in patternCustom.

Data Types: double

## Output Arguments

collapse all

Matrix of reconstructed 3-D pattern, returned as an N-by-M real-valued array. The number of rows in the matrix corresponds to the number of phi elements in dBi. The number of columns in the matrix corresponds to the number of theta elements in dBi.

Polar inclination angle, returned as an M-element real-valued vector in degrees. The returned value is for the subset of input data for the chosen reconstructed method.

Azimuthal angle, returned as an N-element real-valued vector in degrees. The returned value is for the subset of input data for the chosen reconstructed method.

## Limitations

• The summing method does not always reliably approximate the 3-D pattern in the backplane. It works effectively for the azimuthally omnidirectional patterns, as the front plane and the backplane are symmetrical about the z-axis.

• The cross-weighted method can be used to approximate the 3-D pattern in both the front plane and backplane, but the accuracy or robustness is typically best for the main radiation lobe in the front plane.

• Both the summing and the cross-weighted methods do not utilize vertical pattern slice data from the backplane (that is theta ≥ 180°). If you provide backplane vertical slice and theta data, the patternFromSlices function discards it. However, the patternFromSlices function uses all the horizontal pattern and front plane vertical pattern slice data.

collapse all

### Summing

The summing approximation or interpolation algorithm performs:

$G\left(\varphi ,\theta \right)={G}_{H}\left(\varphi \right)+{G}_{V}\left(\theta \right)$

where, GH(ϕ) and GV(θ) are the normalized 2-D pattern cut data in dBi.

### Cross-Weighted

The cross-weighted approximation or interpolation algorithm performs:

${G}_{H}\left(\varphi ,\theta \right)=\frac{{G}_{H}\left(\varphi \right)•{w}_{1}+{G}_{V}\left(\theta \right)•{w}_{2}}{\sqrt[k]{{w}_{1}^{k}+{w}_{2}^{k}}}$

where,

• $\left\{\begin{array}{l}{w}_{1}\left(\varphi ,\theta \right)=\text{vert}\left(\theta \right)•\left[1-\text{hor}\left(\varphi \right)\right]\\ {w}_{2}\left(\varphi ,\theta \right)=\text{hor}\left(\varphi \right)•\left[1-\text{vert}\left(\theta \right)\right]\end{array}$

• GH(ϕ) and GV(θ) are normalized 2-D pattern cut data in dBi.

• hor(ϕ) and vert(θ) are normalized in linear units.

• k is the normalization parameter.

## References

[1] Makarov, Sergey N. Antenna and Em Modeling in MATLAB. Chapter3, Sec 3.4 3.8. Wiley Inter-Science.

[2] Balanis, C.A. Antenna Theory, Analysis and Design, Chapter 2, sec 2.3-2.6, Wiley.

[3] T. G. Vasiliadis, A. G. Dimitriou and G. D. Sergiadis, "A novel technique for the approximation of 3-D antenna radiation patterns," in IEEE Transactions on Antennas and Propagation, July 2005, vol. 53, no. 7: pp. 2212-2219.

[4] N. R. Leonor, R. F. S. Caldeirinha, M. G. Sánchez and T. R. Fernandes, "A Three-Dimensional Directive Antenna Pattern Interpolation Method," in IEEE Antennas and Wireless Propagation Letters, 2016, vol. 15, pp. 881-884.

## Version History

Introduced in R2019a


text:
## Lesson 8

In this lesson, we will further familiarise ourselves with games involving numbers. At the end of the lesson, we will encounter our first positive infinitesimal: the “up” ↑. Here, an infinitesimal is a value which is strictly between –r and r for any positive (dyadic) rational number r. We saw in the last lesson that *n is an infinitesimal for any n, but these are fuzzy games. The game ↑ is positive, i.e. 0 < ↑ < r for any positive rational r.

Here’s an interesting game which can be analysed effectively using numbers. Without CGT, such a detailed analysis of the game would be difficult!

The game of Toads-and-Frogs is played on several rows of squares as above, where each square contains at most one creature. Each creature can only move in the direction it’s facing. E.g. in the first row, the toads in the first and third square can only go right, and the frog in the fourth square can only go left. By convention, player Left controls the TOads which go from Left to Right, while player Right controls the FROgs which go from Right to Left.

At each player’s turn, he may pick up one of his creatures and perform one and only one of the following moves:

• move one square in its direction and land on an empty square; or
• jump over an opponent‘s creature and land onto an empty square.

Play proceeds until a player loses for having no available moves.

Stop and think : how do we get the negative of a Toads-and-Frogs game? [ Answer (highlight to read) : we reflect the row about a vertical axis, so that all the toads facing right become frogs facing left, and vice versa. ]

In the case where there’s one toad and one frog in a row, the solution is usually a number or a * so analysis is quite easy. However, if there’s more than one frog / toad, the situation can become rather complicated.

For starters, consider the following configurations:

Instead of tracing through the whole game tree of each configuration, it is much more efficient to systematically consider a row with a single toad and a single frog. For a row in which the animals have already jumped past each other, it is easy to compute the value. Next, we start from the case where the frog and toad are side-by-side facing each other.

Examples

1. For the first row, if Right starts, he has no move available. On the other hand, if Left starts, the resulting configuration has 3 free moves for Left and 1 free move for Right. Thus, the first row = {3-1 | } = {2 | } = 3 by the Simplicity Rule.
2. For the second row, if Right starts, the resulting configuration has 4 free moves for Left and no move for Right. On the other hand, if Left starts, the resulting configuration has 2 free moves for Left and 2 free moves for Right. Thus, the second row = {2-2 | 4} = {0 | 4} = 1 by Simplicity Rule.

Next consider the case where there’s an empty space between them.

E.g. let’s consider the first row. If Left starts, the resulting game is 1, as we saw above. If Right starts, the resulting game is 3. Thus the overall game is {1 | 3} = 2. Now we’ll leave it to the reader to fill in the remaining entries…

Next we consider the case where there are exactly two toads (going Left to right) and two frogs (going Right to left). There are altogether 30 such configurations. Compute and simplify them as much as you can. [ Hint: recall that a game where the second player wins is a zero game. ]  For the answer, click here.

### A Positive Infinitesimal Game

The last 3 games are of particular interest to us. Let’s label

$\uparrow = \{0\ |\ *\}$ and $\downarrow = - \uparrow = \{-*\ |\ -0\} = \{*\ |\ 0\}$.

The final game in the diagram is then equal to $\{ \uparrow\ |\ \downarrow\}$. In a later lesson, we will learn another simplification rule, which will enable us to show that this is equal to *.

For now, let’s look at ↑ = {0 | *}. The interesting thing is that this game is positive, yet it is less than any positive number. The first claim is easy; as for the second claim, let us use the following useful comparison tool.

Theorem: Consider two games

$G = \{A, B, \ldots | X, Y, \ldots\}$ and $H = \{A', B, \ldots | X, Y, \ldots\}$,

where all options are identical except A and A’, where A ≥ A’. Then we must have G ≥ H.

Similarly, if we replace Right option X by X’ where X ≥ X’, then the resulting game H also satisfies G ≥ H.

Proof:  We need to show that in GH, if Right starts then Left wins. The strategy for Left is simple: whatever his opponent does in one component, he just mirrors in the other. The only problem occurs when Right tries moving (-H) to (-A’). To counter this, Left just moves G to A, thus leaving AA’ for Right. Since this game ≥ 0 and Right goes next, Left wins. ♦

Warning : If A > A’, it does not follow that G > H (see exercise 1).

Now we can show that:

For any n > 0, we have 0 < ↑ < 1/2n.

Indeed, recall that we have * <  1/2n for any positive integer n. Hence, we have ↑ = {0 | *} ≤ {0 | 1/2n} = 1/2n+1 < 1/2n. In fact, it turns out that any finite number copies of ↑ is smaller than 1/2n (see exercise 2).

Finally, we have the following result:

↑ is confused with *, i.e. ↑* is a first-player win.

For other Nim values however, we have:

↑ is larger than *2, *3, *4, … .

Also, for more copies of ↑, we have:

If m > 1 and n ≥ 0, then m↑ is larger than *n, where m↑ refers to the sum of m copies of ↑.

The proofs of all these results are in exercises 3 and 4. Finally since ↓ = -↑ , we also have the corresponding statements for the “down” game ↓.

• For any n > 0, we have 0 > ↓ > -1/2n.
• On the other hand, ↓ is confused with *.
• But ↓ is smaller than *2, *3, *4, … .
• Finally, for each m > 1 and n ≥ 0, m↓ is smaller than *n.

### Exercises

1. Find games A, A’, B, such that A < A’ and {A | B} = {A’ | B}.
2. We already know that 0 < ↑ < 1/2n for any positive n. Use this to prove that for any positive integer m and integer n ≥ 0, we have m↑ + *n < 1/2n.
3. Prove that if n = 1, then ↑ + *n is a first-player win, and that if n > 1, then ↑ + *n is positive.
4. Prove that ↑ + ↑ + *n is positive for any n ≥ 0. Hence, prove that for any m > 1, and non-negative integer n, the game m↑ + *n is positive.
5. Compare the following: is the first expression greater than / less than / confused with / equal to the second expression?
• -1 + 3↑ and -5/4 + 100↑
• -2 + 100↓ + *2 and -1
• -1 + ↑ and -1 + *
• 2 + ↑ and 2 + ↓ + *
• 2 + ↓ + (*7) and 2 + ↑ + (*8)
• -1/2 + 10↑ + (*3) and -1/2 + 11↑ + (*2)
• -1/2 + 10↑ + (*8) and -1/2 + 11↑ + (*7)
6. State a general method of determining whether a + b↑ + (*c) is positive, negative, fuzzy or zero.
7. Decide the status of the following Toads-and-Frogs game. For each player, find his best move if he were to go first.

This entry was posted in Notes and tagged , , , , , , , . Bookmark the permalink.


text:
Volume of a Triangular Prism Online Quiz

Following quiz provides Multiple Choice Questions (MCQs) related to Volume of a Triangular Prism. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz.

Explanation

Step 1:

Volume of a triangular prism = Areas of base triangle × height of prism

Step 2:

Volume of given prism V = $\frac{1}{2}$ × 7 × 3 × 5

= 52.5 cubic meter

Explanation

Step 1:

Volume of a triangular prism = Areas of base triangle × height of prism

Step 2:

Volume of given prism V = $\frac{1}{2}$ × 13 × 11 × 15

= 1072.5 cubic feet

Q 3 - Find the volume of the following triangular prism.

Explanation

Step 1:

Volume of a triangular prism = Areas of base triangle × height of prism

Step 2:

Volume of given prism V = $\frac{1}{2}$ × 14 × 8 × 10

= 560 cubic feet

Q 4 - Find the volume of the following triangular prism.

Explanation

Step 1:

Volume of a triangular prism = Areas of base triangle × height of prism

Step 2:

Volume of given prism V = $\frac{1}{2}$ × 6 × 4 × 12

= 144 cubic in

Explanation

Step 1:

Volume of a triangular prism = Areas of base triangle × height of prism

Step 2:

Volume of given prism V = $\frac{1}{2}$ × 14 × 8 × 6

= 336 cubic ft

Q 6 - Find the volume of the following triangular prism.

Explanation

Step 1:

Volume of a triangular prism = Areas of base triangle × height of prism

Step 2:

Volume of given prism V = $\frac{1}{2}$ × 3 × 8 × 3

= 36 cubic in

Q 7 - Find the volume of the following triangular prism.

Explanation

Step 1:

Volume of a triangular prism = Areas of base triangle × height of prism

Step 2:

Volume of given prism V = $\frac{1}{2}$ × 6 × 6 × 2

= 36 cubic in

Q 8 - Find the volume of the following triangular prism.

Explanation

Step 1:

Volume of a triangular prism = Areas of base triangle × height of prism

Step 2:

Volume of given prism V = $\frac{1}{2}$ × 7 × 5 × 13

= 227.5 cubic in

Q 9 - Find the volume of the following triangular prism.

Explanation

Step 1:

Volume of a triangular prism = Areas of base triangle × height of prism

Step 2:

Volume of given prism V = $\frac{1}{2}$ × 4 × 11 × 6

= 132 cubic feet

Q 10 - Find the volume of the following triangular prism.

Explanation

Step 1:

Volume of a triangular prism = Areas of base triangle × height of prism

Step 2:

Volume of given prism V = $\frac{1}{2}$ × 3 × 3 × 6

= 27 cubic ft

volume_of_triangular_prism.htm


text:
# Marginal distribution from conditional distribution in Multivariate Normal

Let $Y|X=x\sim N_p(Ax+B,\Sigma)$ and $X\sim N_p(\mu,\Psi)$ verify that $$Y\sim N_p(A\mu+B,A\Psi A^T+\Sigma)$$ where $A$ and $B$ are matrix of constant terms.

I know that $$E[Y]=E[E[Y|X]]=E[AX+B]=A\mu+B$$ $$Var(Y)=E[Var(Y|X)]+Var(E[Y|X])=\Sigma+Var(AX+B)=\Sigma+A\Psi A^T$$ the law of variance total and this conditional expectation property is also valid in the multivariate case?

If the conditional distribution is normal and $X$ too, I can assume that $Y$ is normal?

I know that I could try to work with the joint distribution, but it is a lot of work. Is there another way if the above is not true?

• I don't see how else you could do this other than multiplying $f_{Y \mid X}$ and $f_{X}$ together, rewriting the product so that you get a multivariate normal density. – Clarinetist Oct 18 '17 at 13:27
• it really just depends on what you're able to cite as being "known" vs what you need to prove yourself. If you have to show everything, then I don't think there's any way around directly showing it like Clarinetist suggests. But if you can use as a theorem the fact that marginals of a MV gaussian are gaussian, then you just need to show $(X, Y)$ is gaussian. And etc – jld Oct 18 '17 at 14:14


text:
4
views
0
recommends
+1 Recommend
0 collections
0
shares
• Record: found
• Abstract: found
• Article: found
Is Open Access

# Hawking Radiation: A Comparison of Pure-state and Thermal Descriptions

Preprint

Bookmark
There is no author summary for this article yet. Authors can add summaries to their articles on ScienceOpen to make them more accessible to a non-specialist audience.

### Abstract

The cases of the Hawking radiation field being described by a pure state and by the usual thermal state are compared within the CGHS dilaton gravity model. The field-strength fluctuations of the Fourier modes are computed, showing a discrepancy in the low-energy regime, while coinciding at high energies. Then by defining a distance for density operators and evaluating it for the cases concerned, the difference between the pure and thermal descriptions is quantified and found to be exponentially small with respect to the Hawking temperature. Possible physical interpretations are discussed.

### Most cited references14

• Record: found
• Abstract: found
• Article: found
Is Open Access

### The Black Hole in Three Dimensional Space Time

(1992)
The standard Einstein-Maxwell equations in 2+1 spacetime dimensions, with a negative cosmological constant, admit a black hole solution. The 2+1 black hole -characterized by mass, angular momentum and charge, defined by flux integrals at infinity- is quite similar to its 3+1 counterpart. Anti-de Sitter space appears as a negative energy state separated by a mass gap from the continuous black hole spectrum. Evaluation of the partition function yields that the entropy is equal to twice the perimeter length of the horizon.
Bookmark
• Record: found
• Abstract: found
• Article: found
Is Open Access

### The foundations of statistical mechanics from entanglement: Individual states vs. averages

(2005)
We consider an alternative approach to the foundations of statistical mechanics, in which subjective randomness, ensemble-averaging or time-averaging are not required. Instead, the universe (i.e. the system together with a sufficiently large environment) is in a quantum pure state subject to a global constraint, and thermalisation results from entanglement between system and environment. We formulate and prove a "General Canonical Principle", which states that the system will be thermalised for almost all pure states of the universe, and provide rigorous quantitative bounds using Levy's Lemma.
Bookmark
• Record: found
• Abstract: found
• Article: found
Is Open Access

### Evanescent Black Holes

(1991)
A renormalizable theory of quantum gravity coupled to a dilaton and conformal matter in two space-time dimensions is analyzed. The theory is shown to be exactly solvable classically. Included among the exact classical solutions are configurations describing the formation of a black hole by collapsing matter. The problem of Hawking radiation and backreaction of the metric is analyzed to leading order in a $$1/N$$ expansion, where $$N$$ is the number of matter fields. The results suggest that the collapsing matter radiates away all of its energy before an event horizon has a chance to form, and black holes thereby disappear from the quantum mechanical spectrum. It is argued that the matter asymptotically approaches a zero-energy bound state'' which can carry global quantum numbers and that a unitary $$S$$-matrix including such states should exist.
Bookmark

### Author and article information

###### Journal
2017-03-15
###### Article
1703.05373


text:
# Fine-tuning Language Models over Slow Networks using Activation Compression with Guarantees

Communication compression is a crucial technique for modern distributed learning systems to alleviate their communication bottlenecks over slower networks. Despite recent intensive studies of gradient compression for data parallel-style training, compressing the activations for models trained with pipeline parallelism is still an open problem. In this paper, we propose AC-SGD, a novel activation compression algorithm for communication-efficient pipeline parallelism training over slow networks. Different from previous efforts in activation compression, instead of compressing activation values directly, AC-SGD compresses the changes of the activations. This allows us to show, to the best of our knowledge for the first time, that one can still achieve $O(1/\sqrt{T})$ convergence rate for non-convex objectives under activation compression, without making assumptions on gradient unbiasedness that do not hold for deep learning models with non-linear activation functions.We then show that AC-SGD can be optimized and implemented efficiently, without additional end-to-end runtime overhead.We evaluated AC-SGD to fine-tune language models with up to 1.5 billion parameters, compressing activations to 2-4 bits.AC-SGD provides up to 4.3X end-to-end speed-up in slower networks, without sacrificing model quality. Moreover, we also show that AC-SGD can be combined with state-of-the-art gradient compression algorithms to enable "end-to-end communication compression: All communications between machines, including model gradients, forward activations, and backward gradients are compressed into lower precision.This provides up to 4.9X end-to-end speed-up, without sacrificing model quality.

PDF Abstract

## Datasets

Add Datasets introduced or used in this paper

## Results from the Paper Edit

Submit results from this paper to get state-of-the-art GitHub badges and help the community compare results to other papers.


text:
# 1 Partial Pooling in epidemia

We describe how to partially pool parameters underlying the reproduction numbers. This is done using a special operator in the formula passed to epirt(). If you have previously used any of the lme4, nlmer, gamm4, glmer or rstanarm packages then this syntax will be familiar.

A general R formula is written as y ~ model, where y is the response that is modeled as some function of the linear predictor which is symbolically represented by model. model is made up of a series of terms separated by +. In epidemia, as in many other packages, parameters can be partially pooled by using terms of the form (expr | factor), where both expr and factor are R expressions. expr is a standard linear model (i.e. treated the same as model), and is parsed to produce a model matrix. The syntax (expr | factor) makes explicit that columns in this model matrix have separate effects for different levels of the factor variable.

Of course, separate effects can also be specified using the standard interaction operator :. This however corresponds to no pooling, in that parameters at different levels are given separate priors. The | operator, on the other hand, ensures that effects for different levels are given a common prior. This common prior itself has parameters which are given hyperpriors. This allows information to be shared between different levels of the factor. To be concrete, suppose that the model matrix parsed from expr has $$p$$ columns, and that factor has $$L$$ levels. The $$p$$-dimensional parameter vector for the $$l$$th group can be denoted by $$\theta_l$$. In epidemia, this vector is modeled as multivariate normal with an unknown covariance matrix. Specifically, $$$\theta_{l} \sim N(0, \Sigma),$$$ where the covariance $$\Sigma$$ is given a prior. epidemia offers the same priors for covariance matrices as rstanarm; in particular the decov() and lkj() priors from rstanarm can be used. Note that $$\Sigma$$ is not assumed diagonal, i.e.  the effects within each level may be correlated.

If independence is desired for parameters in $$\theta_l$$, we can simply replace (expr | factor) with (expr || factor). This latter term effectively expands into $$p$$ terms of the form (expr_1 | factor), $$\ldots$$, (expr_p | factor), where expr_1 produces the first column of the model matrix given by expr, and so on. From the above discussion, the effects are independent across terms, and essentially $$\Sigma$$ is replaced by $$p$$ one-dimensional covariance matrices (i.e. variances).

## 1.1 Example Formulas

The easiest way to become familiar with how the | operator works is to see a multitude of examples. Here, we give many examples, their interpretations, and where possible we compare the models to the no pooling and full pooling equivalents. For a comprehensive reference on mixed model formulas, please see Bates et al. (2015).

There are many possible ways to specify intercepts. Table 1.1 demonstrates some of these, including fully pooled, partially pooled and unpooled. Effects may also be partially pooled. This is shown in Table 1.2.

Table 1.1: Different intercept specifications. The intercept often has an interpretation as setting $$R_0$$ in each region. The left hand side of each formula is assumed to take the form R(region, date).
Formula R.H.S. Interpretation
1 + ... Full pooling, common intercept for all regions.
region + ... Separate intercepts for each region, not pooled.
(1 | region) + ... Separate intercepts for each region which are partially pooled.
(1 | continent) + ... Separate intercepts based on a factor other than region, partially pooled.
Table 1.2: Different covariate specifications. Here NPI refers to some non-pharamceutical intervention. The left hand side of each formula is assumed to take the form R(region, date).
Formula R.H.S. Interpretation
1 + npi + ... Full pooling. Effect of NPI the same across all regions.
1 + npi:region + ... No pooling. Separate effect in each region.
1 + (0 + npi|region) + ... Partial pooling. Separate effects in each region.
1 + (npi|region) + ... Right hand side expands to 1 + (1 + npi|region), and so both the intercept and effect are partially pooled.

The final example in Table 1.2 shows that it is important to remember that to parse the term (expr | factor), epim() first parses expr into a model matrix in the same way as functions like lm() and glm() parse models. In this case, the intercept term is implicit. Therefore, if this is to be avoided, we must explicitly use either (0 + npi | region) or (-1 + npi | region).

### 1.1.1 Independent Effects

By default, the vector of partially pooled intercepts and slopes for each region are correlated. The || operator can be used to specify independence. For example, consider a formula of the form

R(region, date) ~ npi + (npi || region) + ...

The right hand side expands to 1 + npi + (1 | region) + (npi | region) + .... Separate intercepts and effects for each region which are partially pooled. The intercept and NPI effect are assumed independent within regions.

### 1.1.2 Nested Groupings

Often groupings that are nested. For example, suppose we wish to model an epidemic at quite a fine scale, say at the level of local districts. Often there will be little data for any given district, and so no pooling will give highly variable estimates of reproduction numbers. Nonetheless, pooling at a broad scale, say at the country level may hide region specific variations.

If we have another variable, say county, which denotes the county to which each district belongs, we can in theory use a formula of the form

R(district, date) ~ (1 | county / district) + ...

The right hand side expands to (1 | county) + (1 | county:district). There is a county level intercept, which is partially pooled across different counties. There are also district intercepts which are partially pooled within each county.

# 2 References

Bates, Douglas, Martin Mächler, Ben Bolker, and Steve Walker. 2015. “Fitting Linear Mixed-Effects Models Using Lme4.” Journal of Statistical Software 67 (1): 1–48. https://doi.org/10.18637/jss.v067.i01.


text:
# Call payoff diagram

## Video transcript

Payoff diagrams are a way of depicting what an option or set of options or options combined with other securities are worth at option expiration. What you do is you plot it based on the value of the underlying stock price. And I have two different plots here, one that you might see more in an academic setting or a textbook, and one that you might see more if you look up payoff diagrams on the internet, or people actually trading options. But they're very similar. This one just worries about the actual value of the options at expiration. This worries about the profit and loss. So this will incorporate what you paid for the option, this will not. This just says what it is worth. So with that said, we have company ABCD trading at 50 dollars per share, and then we have a call option with a $50 strike price or a$50 exercise price trading at $10. Which tells us that the owner of that option has the right but not the obligation to buy company ABCD stock at$50 per share up to expiration, assuming it's an American option. If it was a European option, it would be on expiration. So what is the value of this option at expiration? So this is value at expiration. So if the stock is worth less than $50, the owner wouldn't execute it, they wouldn't exercise the option. So the option would be worthless. It would be worthless. They would just let it expire. No reason to actually exercise the option. Now, if the underlying stock price is worth more than$50, if it's $51, then you would exercise it, because it's now-- the option is worth$1. You can buy something for $50 and sell it for$51, so it's now worth $1. If the underlying stock price is$60, of course, you would exercise it, it's now worth $10. Because you can buy something for$50, and you can immediately sell it at $60. We're saying that the underlying stock price is$60. So it would be worth $10. And so you have a payoff diagram that looks something like this. It kind of hockey sticks. Below$50, it's worthless, and then above $50, all of a sudden, it becomes worth something. Now, if you do it in the profit and loss model, all you have to do is incorporate what you actually paid for the option. So in this situation, below$50, you still would not actually exercise your option. Because why would you pay $50 for something that's actually trading for less than$50? But you would say, hey, I would have had to take a $10 loss, because I paid$10 for that option. So up until $50, your profit is negative$10. You have lost $10. You have lost the price of the option because you wouldn't exercise it. Then all of a sudden if the stock price goes above$50, you would exercise it, but you would still have a negative profit, because you still haven't made up the price of the option. All the way up until $60. At$60 per share for the underlying stock price, you could exercise the option, buy the stock at $50, sell it at$60. You would make $10 doing that, but, of course, you have to spend$10 on the option. So there you are break even. But then as you get above a \$60 stock price at maturity, then all of a sudden you start to make money. So these are both legitimate payoff diagrams for a call option, for this call option right over here. They're just different ways of viewing it. This is the value of the option. This incorporates the actual cost of it.


text:
Testing a Small Query Language in Python with Hypothesis

This entry was intended to be cross-posted to the CERN Databases blog, but is currently pending review. Consider it a pre-release version.

Hypothesis is an implementation of Property-based testing for Python, similar to QuickCheck in Haskell/Erlang and test.check in Clojure (among others). Basically, it allows the programmer to formulate invariants about their programs, and have an automated system attempt to generate counter-examples that invalidates them.

A Small Query Language

During my internship at CERN, I am developing a small (partial) two-way monitoring system to propagate alerts from filers to CERN’s incident management system. In the course of developing this monitor, I decided to invent a very minimal query/filtering language for logging events. It maps directly against Python objects using regular expressions (basically: “does object x have a property y matching regex z”?). The following is its grammar (written for the Grako parser-generator):

start = expression ;

expression
=
'(' expression ')' binary_operator '(' expression ')'
| unary_operator '(' expression ')'
| statement
;

binary_operator = 'AND' | 'OR';
unary_operator = 'NOT';
statement = field ':' "'" regex "'";
field =
/[0-9A-Za-z_]+/
;

regex
= /([^'])*/
;

An example (from a test configuration file) could be event_type:'disk.failed' (disk failures) or (source_type:'(?i)Aggregate') AND (NOT(source_name:'aggr0')) (log events from aggregates, but not aggr0).

The following invariants should hold, where q is any valid query:

• NOT(NOT(q))q
• (q) AND (q)q
• (q) OR (q)q
• (q) OR (NOT(q)) is always True

In addition, the following properties should also hold:

• key:'value' matches every object containing a property key with exact value value for any valid values of key and value (that is, valid Python variable names for key and more or less any string for value)
• key:'' matches every object that has an attribute key regardless of its value

Generating Examples

There are several types of inputs we need to generate to test the system. Let’s break them down:

• objects with various fields
• regular expressions
• valid statements
• valid queries

Let’s start from the top. As Python is a dynamic language, we can do crazy things, like dynamically generating objects from dictionaries. The following is a fairly common hack:

class objectview(object):
def __init__(self, d):
self.__dict__ = d

def __repr__(self):
return str(self.__dict__)

def __str__(self):
return str(self.__dict__)

This allows us to instantiate an object with (almost) arbitrary fields:

cat = objectview({'colour': 'red', 'fav_food_barcode': '1941230190'})
>>> cat.colour
'red'
>>> cat.fav_food_barcode
'1941230190'

Given this, we can just generate valid objects using the @composite decorator in Hypothesis:

@composite
def objects(draw):
ds = draw(dictionaries(keys=valid_properties,
values=valid_values,
min_size=1))

return objectview(ds)

Generating valid values is much simpler:

valid_values = text()

Any text string is a valid string value. Of course! Properties are a bit trickier though:

valid_properties = (characters(max_codepoint=91,
whitelist_categories=["Ll", "Lu", "Nd"])
.filter(lambda s: not s[0].isdigit()))

Variable names can’t start with a number, and has to be basically mostly ASCII, so we slightly modify and filter the characters strategy.

Statements can be generated in much the same way, using composite strategies:

@composite
def statements(draw):
# any valid key followed by a valid regex
key = draw(valid_properties)
regex = draw(regexes)

return u"{key}:'{regex}'".format(key=key, regex=regex)

However, how do we produce regular expressions? Let’s start with some valid candidates:

regex_string_candidates = characters(blacklist_characters=[u'?', u'\\', u"'"])

Then we can generate regular expressions using Hypothesis’ back-tracking functionality through assume(), which causes it to discard bad examples (in this instance is_valid_regex() simply tries to compile the string as a Python regular expression, and returns False if it fails):

@composite
def regex_strings(draw):
maybe_regex = draw(regex_string_candidates)
assume(is_valid_regex(maybe_regex))
return maybe_regex

But we can also use recursive generation strategies to produce more complex regular expressions:

regexes = recursive(regex_strings(), lambda subexps:
# match one or more
subexps.map(lambda re: u"({re})+".format(re=re)) |

# match zero or more
subexps.map(lambda re: u"({re})*".format(re=re)) |

# Append "match any following"
subexps.map(lambda re: u"{re}.*".format(re=re)) |

# Prepend "match any following"
subexps.map(lambda re: u".*{re}".format(re=re)) |

# Prepend start of string
subexps.map(lambda re: u"^{re}".format(re=re)) |

# Append end of string
subexps.map(lambda re: u"{re}\$".format(re=re)) |

# Append escaped backslash
subexps.map(lambda re: u"{re}\\\\".format(re=re)) |

# Append escaped parenthesis
subexps.map(lambda re: u"{re}\(".format(re=re)) |

# Append dot
subexps.map(lambda re: u"{re}.".format(re=re)) |

# Match zero or one
subexps.map(lambda re: u"({re})?".format(re=re)) |

# Match five to six occurrences
subexps.map(lambda re: (u"({re})"
.format(re=re)) + u"{5,6}") |

# concatenate two regexes
tuples(subexps, subexps).map(lambda res: u"%s%s" % res) |

# OR two regexes
tuples(subexps, subexps).map(lambda res: u"%s|%s" % res))

The same strategy also works for the highly recursive structure of the query language:

queries = recursive(statements(),
lambda subqueries:
subqueries.map(negated_query) |
tuples(subqueries, subqueries).map(ored_queries) |
tuples(subqueries, subqueries).map(anded_queries))

Read as: “a valid query is any statement, or a any valid query negated, or two valid queries AND:ed or OR:ed”.

Making Assertions

To finally assert properties, we assert things similarly to how we would in normal unit tests. For example, let’s verify that the empty regular expression matches anything:

@given(target=objects(), key=valid_properties)
def test_query_for_empty_regex_always_matches(target, key):
q = "{key}:''".format(key=key)
assert query.matches_object(q, target)

Hypothesis immediately finds a counter-example:  > assert query.matches_object(q, target) E assert False E + where False = <function matches_object at 0x7fa76dc6f5f0>(“A:’’”, {u’B’: u’’}) E + where <function matches_object at 0x7fa76dc6f5f0> = query.matches_object

key = ‘A’ q = “A:’’” target = {u’B’: u’’}

syncd/eql/test/test_hypothesis.py:188: AssertionError ———- Hypothesis ——— Falsifying example: test_query_for_empty_regex_always_matches(target={u’B’: u’’}, key=u’A’)

An object which doesn’t have the specified property will not match the query, even if the query is looking for the empty string. Ok, so that’s a bad example depending on how we want to treat this edge-case. If we really did want the empty regular expression to match even objects which does not have their keys, this would have been a proper bug in the implementation. However, it makes more sense to require the object to have the property checked for, and so this is a bad counter-example. We can exclude it by adding assume(hasattr(target, key)) to the test, causing it to back-track on any examples where the target object does not have the key:

@given(target=objects(), key=valid_properties)
def test_query_for_empty_regex_always_matches(target, key):
assume(hasattr(target, key))

q = "{key}:''".format(key=key)

assert query.matches_object(q, target)

And now, the test passes.

The image is from “Chemistry: general, medical and pharmaceutical…” from 1894, courtesy of the Internet Archive Book Images

Shipping Out: One Month Later

This September, I started a one-year internship at CERN’s Database department (more specifically the IT-DB-IMS department, as they are clearly very fond of hierarchies). My assignment is related to logging and storage monitoring, and my primary task will be to provide a solution for automatic propagation and reporting of storage-related errors (think dead hard drives, power failures etc).

Shipping Out

Early morning August the 27th, I started my journey. Split between a suitcase and two backpacks, I brought the following with me on the plane:

• Soft-shell jacket and rain gear
• Clothes for at least ten days, vacuum packed (*)
• Micro-fibre towel
• Sleeping bag + ultra-light sleeping pad
• Various toiletries
• Computer with charger
• 6 USB chargers with cables
• Spare AA cells
• Bluetooth keyboard
• Running gear for at least two weeks
• Swimming trunks and goggles
• 3 single-board computers (two CHIPs, one Raspberry Pi)
• Stuffed tiger, vacuum packed
• USB microphone
• A few USB thumb drives
• External disk drive (for back-ups)
• Various tools (including lock-picks, various special-purpose screwdrivers and a side cutter)
• Thermos mug
• Pyjamas
• Mountaineering/hiking boots

(*) this turned out to be largely false – perhaps ten normal days, but not ten really hot days.

After an uneventful (and very WiFi-less) flight of about two hours, I landed in Geneva, found my luggage after walking an impressive number of hallways, each one plastered with advertisements for luxury watches, various banking services, perfumes etc, and proceeded to board the bus to Ferney-Voltaire, the small French village near the Swiss border where I would be staying.

The process involved much frustration and about one hour of pacing the arrivals hall trying to find someone who could help me buy a ticket from the vending machine. It turned out the Right Thing To Do was to buy a ticket in the machine for a different company than the one who operated the bus I ended up taking. From there, the rest of the trip was mostly uncomplicated, as I had practised walking most of the way from the bus stop to the place I would be staying at on Google Maps in advance. Something which, I suppose, is evidence of the same combination of absolute neuroticism and ruthless pragmatism as vacuum-packing one’s stuffed animal for the journey.

During the first month of my stay, I was living without a mobile data plan. The experience reminds me of Cory Doctorow’s short story After the Siege (available online as part of Overclocked). Everything works mostly as normal (only worse) – until I leave the apartment. Then everything immediately stops working. Accidentally closed an email attachment when trying to read the email that contained it? Sorry, it’s now unavailable. The song I just added to my playlist? Gone. Too bad the EU hasn’t succeeded in outlawing roaming fees yet.

On the Betrayal of Things

Living in another country for any longer duration is a lot like being at the wrong end of a set of really evil unit tests. In life in general, as in programming, at any given point in time one holds a lot of preconceptions about how the world works – unreflected habits and assumptions. Living in another country immediately invalidates a non-empty, randomly selected set of these assumptions. It is precisely the experience that Foucault describes in the Preface to Les mots de choses of the “laugh that shatters”; at first one laughs at the three different positions of dried beans in the supermarket, the consistent placement of the potato crisps next to the hard liquor, or the three different, non-consecutive candy aisles – until one realises that categories such as “baking supplies”, “candy”, etc are entirely arbitrary, and just took on an air of ontological truths by virtue of being a widely accepted convention. There are, after all, several ways to skin a cat.

Ils sont fous ces gaules

The culture shock I experience with the French culture is admittedly a very mild one, but there are definitely subtle but unsettling differences. Milk typically comes high-temperature-pasteurised, which gives it a different flavour than fresh milk. And everything is perfumed and/or tinted pink; toilet paper (!), trash bags – everything. Loose-leaf tea is not available anywhere, except in gift tin boxes without any option for refills. Muesli is hard to come by, and the “healthy” granola/muesli mixes “without added sugar” contains little chocolate drops. Not to mention the entire pastries-for-breakfast thing. I’m still not over that.

If anything, French administrative culture is a confusing jumble of obstinate strictness and unregulated chaos. Applying for a bank account? Sign 200 papers and prove your residence with a phone or utilities bill, which is apparently the standard way of doing it. Going for a swim? Well, certain types of swimming trunks are forbidden but there is no standardised vocabulary for describing swimming trunks so you just have to figure out which ones are ok through trial and error. But at least they gave me the rebate for residents after I dutifully showed my phone bill at the reception (the de facto standard proof of residence). I may also have slammed my swimwear at the desk and asked “CECI SONT INTERDITS?!”. Lucky me, they weren’t.

How’s Work?

I have never seen anyone suffer so badly from NIH syndrome as CERN does. For almost every given task, they have their own, subtly different solution from the industry standard; Mattermost in stead of Slack, Terrible Exchange Web Mail That Probably Escaped From 2007 in stead of Google Apps (the only instance where I wish they’d have had more NIH and just gone with their own solution), self-hosted GitLab in stead of Github, and a customized variant of Dropbox called “CERNBox”. Oh, and they have their own GNU/Linux distros. Two of them. And they are both RPM-based.

From an economical standpoint this makes sense. They are already running operations on huge server farms. Adding a few extra services is probably very cheap, both in terms of labour and other resources, especially compared to paying for a service offered by someone else. And in the long run, their involvement in several FLOSS replacements for common industry applications is most likely greatly improving them. I just wish they would have put more effort into the UX on some of these apps, so that they didn’t all suffer from flakiness and the general “a cheaper copy of X” look and feel (well-known from Libre/OpenOffice, which somehow manages to look even worse than their proprietary counterparts – all things considered no small feat). Frankly, I like my FLOSS implementations as I like my tech products in general – either better or at least as good as the things they are replacing, or nonexistent.

Other than that, the work is interesting, if a bit mundane. I learn a lot every day, but it is really hard to muster any real enthusiasm for a small python daemon with the task of basically carting data from one API to another. The only real challenges I have found so far is to implement a query language and to test things really, really well, about which I might go into some detail in the future.

Scheduling Periodic Cleaning in macOS

On most of my machines, I treat the default Downloads folder as a staging area: it’s where things arrive before being filed away wherever they belong. Most files, however, are only useful for a very brief period of time and belong nowhere really. Therefore, the Downloads folders on my systems tend to accumulate all sorts of meaningless gunk, as sorting and taking out the digital trash is precisely the sort of menial task we built computers to avoid having to do. Or, they did before I automated the process of taking out the trash. Here’s how.

Begin by setting up an Automator workflow to do the actual cleaning. You might be tempted to choose a workflow along the lines of “if file creation date is not within…”, but that will – for some reason – exclude files created today. The proper way of doing it is to set up a NOT-AND criterion: if a file is not created today and not created within the last 60 days, move it to Trash as seen below.

Change the path to your Automator workflow file below (mine is in ~/Documents and is called clean-downloads.workflow). It may be a good idea to avoid spaces in the file name. Save the Launchd configuration file in ~/Library/LaunchAgents/com.orgname.scriptname.plist (as you can see below, i used org.albin and cleandownloads for organisation name and script/agent name respectively).

Once you are done, you may or may not need to load the script using launchctl load <path-to-script>, e.g. launchctl load ~/Library/LaunchAgents/org.albin.cleandownloads.plist.

If you want to do more in-depth editing of the Launchd script, I’d recommend using LaunchControl. See also this StackOverflow thread on creating Launchd tasks and where to place them. It also contains other ways of scheduling periodic tasks under macOS.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<key>ProgramArguments</key>
<array>
<string>automator</string>
</array>
<true/>
<key>StartCalendarInterval</key>
<dict>
<key>Minute</key>
<integer>0</integer>
</dict>
</dict>
</plist>

Please note that this script (for security reasons) doesn’t actually delete anything, it just moves them to the Trash. But it pairs excellently with macOS Sierra’s feature for automatically purging Trash of old files!

Shoebox Time Machine backup server with Raspberry Pi ("poor man's Time Capsule")

It is possible and fairly easy to build an acceptable Time Machine backup server using a Raspberry Pi and a spare USB drive. Basically, the process is as follows:

1. Install dependencies
2. Format and set up the drive
4. Configure netatalk

1. Install dependencies

Just do  sudo apt-get install build-essential libevent-dev libssl-dev libgcrypt-dev libkrb5-dev libpam0g-dev libwrap0-dev libdb-dev libtdb-dev libmysqlclient-dev avahi-daemon libavahi-client-dev libacl1-dev libldap2-dev libcrack2-dev systemtap-sdt-dev libdbus-1-dev libdbus-glib-1-dev libglib2.0-dev libio-socket-inet6-perl tracker libtracker-sparql-0.16-dev libtracker-miner-0.16-dev libgcrypt20-dev

2. Format and set up the drive

Some guides call for using a hfsplus-formatted drive. If you have one that you previously used with macOS, by any means – use it. If not, I would prefer a more well-adapted GNU/Linux file system. I would recommend ext4, which is what most distros use, unless you have any particular reason to use something else.

First use sudo fdisk /dev/sda to partition your hard drive (this is assuming that the hard drive is the only USB harddisk or pendrive attached to your Raspberry Pi – if it is not, make sure you pick the right one!).

1. Press o to create a new partition table.
2. Create a new partition using the n command. Choose primary (p) and use the suggested sizes (unless you have reason to change them). Choose the Linux filesystem, which should be the default.
3. When you are back at the main menu, press w to write everything to disk and quit.

Now, format the drive as ext4: sudo mkfs.ext4 -L "Time Machine" /dev/sda1. When you are done, determine the unique identifier (UUID) of the new partition with blkid /dev/sda1 and copy the entire UUID="LOTS OF TEXT" part.

Create a mount point at /media/time_machine with sudo mkdir /media/time_machine.

Edit /etc/fstab and add a line like this: UUID="ca92ada0-e97a-44fc-badb-f0e934d775c9" /media/time_machine ext4 defaults,rw,user,auto 0 0

Mount it using sudo mount -a and try writing anything to /media/time_machine (e.g. touch /media/time_machine/test.file). If you get permissions errors, do sudo chown -R user /media/time_machine, where user is your user name (again, proably pi).

Netatalk is a free implementation of Apples network/file sharing protocols. It is available from the official repositories, but that version is ancient, so we need to compie it ourselves.

First, download it. You can either do it on your local machine and copy it to your raspberry pi using scp, or you can find a link on the download page and use wget <file link> to download it directly. After you have it, just extract it with the usual tar xvf netatalk-3.1.9.tar.bz2 (assuming you have the same version).

You can follow the official guide, but basically it is a matter of running configure with the right flags.

First, see which version of tracker you got from apt-get: pkg-config --list-all | grep tracker and insert it after –with-tracker-pkgconfig-version in the proposed command. In my case, I got 1.0:

./configure --with-init-style=debian-systemd  \
--without-libevent  --without-tdb \
--with-cracklib --enable-krbV-uam \
--with-pam-confdir=/etc/pam.d     \
--with-dbus-daemon=/usr/bin/dbus-daemon \
--with-dbus-sysconf-dir=/etc/dbus-1/system.d \
--with-tracker-pkgconfig-version=1.0

Verify that DHX2 is enabled (you need it for password authentication on recent versions of macOS, at least El Capitan):

UAMS:

Then make && sudo make install it!

4. Configure netatalk

After that, update your /usr/local/etc/afp.conf:

[Global]
; Global server settings
vol preset = default_for_all_vol
log file = /var/log/netatalk.log
uam list = uams_dhx.so,uams_dhx2.so
mimic model = TimeCapsule6,106

[default_for_all_vol]
file perm = 0664
directory perm = 0774
cnid scheme = dbd
valid users = albin

[Time Machine]
path = /media/time_machine
time machine = yes

Substitute your own user name for albin at valid users, or omit the line entirely to allow all users. Remember, this is a user account on the server. If you are using a Raspberry Pi, this is probably the “pi” user and “raspberry” password (but you really should create a user of your own and change the password of the default account!). mimic model doesn’t really do much, except giving your Raspberry Pi a nice Time Cube icon in Finder.

Start up netatalk:

sudo service netatalk start

Keep track of the logs using sudo tail -f /var/log/netatalk.log, and try to browse and log in from your computer. The Raspberry Pi should appear in Finder, and you should be able to log in as your chosen user (e.g. pi).

When you are confident everything works, you can set up netatalk to start when the server does:

sudo systemctl enable netatalk

After this, you should be able to find and select your shoebox server as a target in Time Machine. Now, go and make a very big cup of tea as your computer runs its initial backup.

Monoprice tablets and multiple screens under ElementaryOS (and other GNU/Linuxes)

I recently got a 10 x 6.25-inch Graphic Monoprice drawing tablet via Massdrop. It turns out that these tablets are actually re-branded Huion devices, supported by recent kernels and by the Digimend driver. Mine is a Huion H610. ElementaryOS Freya’s kernel is apparently patched to contain the necessary drivers, and everything worked out of the box in terms of reading input.

However, the coordinates on the tablet are mapped to X11 coordinates. Since I have two monitors, this means that every coordinate on the tablet is mapped against a corresponding coordinate on the combined surface of both my screens, which makes navigation extremely awkward. This can be solved by modifying the coordinate transformation matrix. The easiest way to do this is to use the neat tool xrestrict, which simply prompts you to click on the desired screen and sets up the coordinate transformation matrix to restrict inputs to that screen for the tool you just clicked with. It is currently not available in the official repos, but building and running it was fairly straightforward.