```python
from IPython.display import HTML

hide_me = ''
HTML('''
<form action="javascript:code_toggle()"><input style="opacity:0" type="submit" value="Click here to toggle on/off the raw code."></form>''')
```

## Exercise

Solve this system of equations for $x$ and $y$.

$$
\begin{equation}
  \begin{cases}
    y = x + 3 \\
    y - 12 = -2x
  \end{cases}
\end{equation}
$$

Write a function `ex()` to return SymPy equations for `x` and `y`.

```python
from sympy import symbols, Eq, simplify

def ex():
    x, y = symbols('x y')
    my_x, my_y = Eq(x, 0), Eq(y, 0)

    print('Starting equations:')
    eq1, eq2 = Eq(y, x + 3), Eq(y - 12, -2*x)
    display(eq1)
    display(eq2)

    print('Your solution:')
    # YOUR CODE HERE
    raise NotImplementedError()

    return(my_x, my_y)

x_ans, y_ans = ex()  # Test out results
print('Your answer:')
display(x_ans)
display(y_ans)
```

```python
# hide_me

import unittest
import inspect

x, y = symbols('x y')

enable_print  = print
enable_display = display
disable_print = lambda *x, **y: None
disable_display = lambda *x, **y: None

print = disable_print
display = disable_display

class TestSystemEquations(unittest.TestCase):

    def test_functionExists(self):
        """You should have a function ex() defined."""
        self.assertTrue('ex' in globals())

    def test_xAnswer(self):
        """Your x answer should equal 3."""
        self.assertEqual(simplify(ex()[0]), Eq(x, 3))

    def test_xSet(self):
        """You should not directly assign the x answer."""
        self.assertTrue('Eq(x, 3)' not in inspect.getsource(ex))

    def test_yAnswer(self):
        """Your y answer should be 6."""
        self.assertEqual(simplify(ex()[1]), Eq(y, 6))

    def test_ySet(self):
        """You should not directly assign the y answer."""
        self.assertTrue('Eq(y, 6)' not in inspect.getsource(ex))

    def test_useLHS(self):
        """You should use the .lhs attribute."""
        self.assertTrue('.lhs' in inspect.getsource(ex))

    def test_useRHS(self):
        """You should use the .rhs attribute."""
        self.assertTrue('.lhs' in inspect.getsource(ex))

    def test_noSolver(self):
        """You should not use the solve function."""
        self.assertTrue('solve' not in inspect.getsource(ex))

    def test_noLinearSolver(self):
        """You should not use the solve_linear_systems function."""
        self.assertTrue('solve_linear_system' not in inspect.getsource(ex))

    def test_returnEquations(self):
        """Your function should return SymPy equations."""
        self.assertTrue(type(ex()[1]) == Eq and type(ex()[1]) == Eq)

def suite():
    suite = unittest.TestSuite()
    suite.addTest(TestSystemEquations('test_functionExists'))
    suite.addTest(TestSystemEquations('test_xAnswer'))
    suite.addTest(TestSystemEquations('test_xSet'))
    suite.addTest(TestSystemEquations('test_yAnswer'))
    suite.addTest(TestSystemEquations('test_ySet'))
    suite.addTest(TestSystemEquations('test_useLHS'))
    suite.addTest(TestSystemEquations('test_useRHS'))
    suite.addTest(TestSystemEquations('test_noSolver'))
    suite.addTest(TestSystemEquations('test_noLinearSolver'))
    suite.addTest(TestSystemEquations('test_returnEquations'))
    return suite

runner = unittest.TextTestRunner(verbosity=2)
runner.run(suite())

# Reset suppression of print statements
print = enable_print
display = enable_display
```

```python

```


# CMSIS-DSP Python package example

## Installing and importing the needed packages

The following command may take some time to execute : the full cmsisdsp library is built.

```python
!pip install cmsisdsp
```

    Requirement already satisfied: cmsisdsp in c:\benchresults\pythonwrappertests\testenv\lib\site-packages (1.2.1)
    Requirement already satisfied: numpy>=1.19 in c:\benchresults\pythonwrappertests\testenv\lib\site-packages (from cmsisdsp) (1.22.2)
    Requirement already satisfied: jinja2>=3.0 in c:\benchresults\pythonwrappertests\testenv\lib\site-packages (from cmsisdsp) (3.0.3)
    Requirement already satisfied: networkx>=2.5 in c:\benchresults\pythonwrappertests\testenv\lib\site-packages (from cmsisdsp) (2.6.3)
    Requirement already satisfied: sympy>=1.6 in c:\benchresults\pythonwrappertests\testenv\lib\site-packages (from cmsisdsp) (1.9)
    Requirement already satisfied: MarkupSafe>=2.0 in c:\benchresults\pythonwrappertests\testenv\lib\site-packages (from jinja2>=3.0->cmsisdsp) (2.1.0)
    Requirement already satisfied: mpmath>=0.19 in c:\benchresults\pythonwrappertests\testenv\lib\site-packages (from sympy>=1.6->cmsisdsp) (1.2.1)

```python
import numpy as np
import cmsisdsp as dsp
import cmsisdsp.fixedpoint as f
```

```python
import matplotlib.pyplot as plt
from ipywidgets import interact, interactive, fixed, interact_manual,FloatSlider
import ipywidgets as widgets
```

## Creating the signal

### Conversion functions to use CMSIS-DSP FFTs with complex numbers

CMSIS-DSP FFTs are processing  array of complex numbers which are represented in memory asan array of floats. There is no specific data types for complex numbers.
The Python array is containing complex numbers. They need to be replaced by a sequence of real numbers.
The two functions below are doing those conversions.

```python
# Array of complex numbers as an array of real numbers
def imToReal1D(a):
    ar=np.zeros(np.array(a.shape) * 2)
    ar[0::2]=a.real
    ar[1::2]=a.imag
    return(ar)

# Array of real numbers as an array of complex numbers
def realToIm1D(ar):
    return(ar[0::2] + 1j * ar[1::2])
```

```python
nb = 512
signal = None
```

You can play with the slider to change the frequency of the signal.
Don't forget to reconvert the signal to a Q15 format if you want to test the Q15 FFT.

```python
@interact(f=FloatSlider(100,min=10,max=150,step=20,continuous_update=False))
def gen_signal(f=100):
    global signal
    global nb
    signal = np.sin(2 * np.pi * np.arange(nb)*f / nb) + 0.1*np.random.randn(nb)
    plt.plot(signal)
    plt.show()
```

    interactive(children=(FloatSlider(value=100.0, continuous_update=False, description='f', max=150.0, min=10.0, …

## Using the F32 CMSIS-DSP FFT

The `arm_cfft_instance_f32` is created and initialized.

```python
# CMSIS-DSP FFT F32 initialization
cfftf32=dsp.arm_cfft_instance_f32()
status=dsp.arm_cfft_init_f32(cfftf32,nb)
print(status)
```

    0

The log magnitude of the FFT is computed and siplayed.

```python
# Re-evaluate this each time you change the signal
signalR = imToReal1D(signal)
resultR = dsp.arm_cfft_f32(cfftf32,signalR,0,1)
resultI = realToIm1D(resultR)
mag=20 * np.log10(np.abs(resultI))

plt.plot(mag[1:nb//2])
plt.show()
```

## Using the Q15 CMSIS-DSP FFT

The signal must be converted to Q15 each time it is changed with the slider above.

```python
# Convert the signal to Q15 and viewed as a real array
signalR = imToReal1D(signal)
signalRQ15 = f.toQ15(signalR)
```

The `arm_cfft_instance_q15` is created and initialized

```python
# Initialize the Q15 CFFT
cfftq15 = dsp.arm_cfft_instance_q15()
status = dsp.arm_cfft_init_q15(cfftq15,nb)
print(status)
```

    0

```python
# Compute the Q15 CFFT and convert back to float and complex array
resultR = dsp.arm_cfft_q15(cfftq15,signalRQ15,0,1)
resultR = f.Q15toF32(resultR)
resultI = realToIm1D(resultR)*nb

mag = 20 * np.log10(np.abs(resultI))
plt.plot(mag[1:nb//2])
plt.show()
```

```python

```


# Symbolic Statistics with SymPy

[back to overview page](index.ipynb)

This notebook just lists the (sometimes slightly modified) examples from the paper [Symbolic Statistics with SymPy](http://scitation.aip.org/content/aip/journal/cise/14/3/10.1109/MCSE.2012.56) ([doi:10.1109/MCSE.2012.56]( http://dx.doi.org/10.1109/MCSE.2012.56)) by  Matthew Rocklin and Andy R. Terrel, published in Computing in Science & Engineering, Volume 14, Issue 3 (2012).

```python
from sympy import stats
import sympy
sympy.init_printing()
```

```python
sympy.__version__
```

    '0.7.7.dev'

## Example 1: Dice

[sympy.stats.Die](http://docs.sympy.org/dev/modules/stats.html#sympy.stats.Die), by default 6-sided.

```python
X = stats.Die('X')
Y = stats.Die('Y')
```

```python
X
```

```python
type(X)
```

    sympy.stats.rv.RandomSymbol

```python
stats.density(X)
```

```python
stats.density(X).dict
```

```python
stats.P(X > 3)  # probability
```

```python
stats.E(X + Y)  # expectation
```

```python
mod_X = X + 3
mod_X
```

```python
stats.E(2*X + 4)
```

$P(X>3 \mid X+Y\ge 8)$

```python
stats.P(X > 3, X + Y >= 8)
```

```python
A = X > 3
B = X + Y >= 10
```

Note: this is not a proof for the general case:

```python
stats.P(B, A) == stats.P(A, B) * stats.P(B) / stats.P(A)
```

    True

```python
density = dict(heads=0.5, tails=0.5)
density
```

    {'heads': 0.5, 'tails': 0.5}

```python
coin = stats.FiniteRV('coin', density)
coin
```

```python
type(coin)
```

    sympy.stats.rv.RandomSymbol

```python
stats.density(coin)
```

```python
stats.density(coin).dict
```

## Table 1

```python
stats.P(X > 3)
```

```python
stats.E(2 * X)
```

```python
stats.variance(X + 3)
```

```python
stats.density(2 * X)
```

## Table 2

```python
X2 = stats.given(X, X < 3)
X2
```

```python
stats.density(X, X > 3)
```

```python
stats.E(X, X > 3)
```

## Example 2: Data Assimilation

```python
T = stats.Normal('T', 30, 3)
T
```

```python
type(T)
```

    sympy.stats.rv.RandomSymbol

```python
stats.density(T)
```

```python
stats.P(T > 33)
```

```python
_.n()
```

```python
noise = stats.Normal('noise', 0, 1.5)
noise
```

```python
type(noise)
```

    sympy.stats.rv.RandomSymbol

```python
observation = T + noise
observation
```

```python
T_posterior = stats.given(T, sympy.Eq(observation, 26))
T_posterior
```

```python
stats.density(T_posterior)
```

## Example 3: Kinematics

```python
# TODO
```

  To the extent possible under law,
  the person who associated CC0
  with this work has waived all copyright and related or neighboring
  rights to this work.