# When To Stop Fuzzing

In the past chapters, we have discussed several fuzzing techniques.  Knowing _what_ to do is important, but it is also important to know when to _stop_ doing things.  In this chapter, we will learn when to _stop fuzzing_ – and use a prominent example for this purpose: The *Enigma* machine that was used in the second world war by the navy of Nazi Germany to encrypt communications, and how Alan Turing and I.J. Good used _fuzzing techniques_ to crack ciphers for the Naval Enigma machine.

Turing did not only develop the foundations of computer science, the Turing machine. Together with his assistant I.J. Good, he also invented estimators of the probability of an event occuring that has never previously occured. We show how the Good-Turing estimator can be used to quantify the *residual risk* of a fuzzing campaign that finds no vulnerabilities. Meaning, we show how it estimates the probability of discovering a vulnerability when no vulnerability has been observed before throughout the fuzzing campaign.

We discuss means to speed up [coverage-based fuzzers](Coverage.ipynb) and introduce a range of estimation and extrapolation methodologies to assess and extrapolate fuzzing progress and residual risk.

**Prerequisites**

* _The chapter on [Coverage](Coverage.ipynb) discusses how to use coverage information for an executed test input to guide a coverage-based mutational greybox fuzzer_.
* Some knowledge of statistics is helpful.

```python
import bookutils
```

```python
import Fuzzer
import Coverage
```

## The Enigma Machine

It is autumn in the year of 1938. Turing has just finished his PhD at Princeton University demonstrating the limits of computation and laying the foundation for the theory of computer science. Nazi Germany is rearming. It has reoccupied the Rhineland and annexed Austria against the treaty of Versailles. It has just annexed the Sudetenland in Czechoslovakia and begins preparations to take over the rest of Czechoslovakia despite an agreement just signed in Munich.

Meanwhile, the British intelligence is building up their capability to break encrypted messages used by the Germans to communicate military and naval information. The Germans are using [Enigma machines](https://en.wikipedia.org/wiki/Enigma_machine) for encryption.  Enigma machines use a series of electro-mechanical rotor cipher machines to protect military communication.  Here is a picture of an Enigma machine:

By the time Turing joined the British Bletchley park, the Polish intelligence reverse engineered the logical structure of the Enigma machine and built a decryption machine called *Bomba* (perhaps because of the ticking noise they made). A bomba simulates six Enigma machines simultaneously and tries different decryption keys until the code is broken. The Polish bomba might have been the very _first fuzzer_.

Turing took it upon himself to crack ciphers of the Naval Enigma machine, which were notoriously hard to crack. The Naval Enigma used, as part of its encryption key, a three letter sequence called *trigram*. These trigrams were selected from a book, called *Kenngruppenbuch*, which contained all trigrams in a random order.

### The Kenngruppenbuch

Let's start with the Kenngruppenbuch (K-Book).

We are going to use the following Python functions.
* `shuffle(elements)` - shuffle *elements* and put items in random order.
* `choice(elements, p=weights)` - choose an item from *elements* at random. An element with twice the *weight* is twice as likely to be chosen.
* `log(a)` - returns the natural logarithm of a.
* `a ** b` - means `a` to the power of `b` (a.k.a. [power operator](https://docs.python.org/3/reference/expressions.html#the-power-operator))

```python
import string
```

```python
import numpy
from numpy.random import choice
from numpy.random import shuffle
from numpy import log
```

We start with creating the set of trigrams:

```python
letters = list(string.ascii_letters[26:])  # upper-case characters
trigrams = [str(a + b + c) for a in letters for b in letters for c in letters]
shuffle(trigrams)
```

```python
trigrams[:10]
```

    ['KYA', 'URR', 'TPC', 'VBQ', 'KRK', 'LOI', 'ZIR', 'JNX', 'WIW', 'ZXY']

These now go into the Kenngruppenbuch.  However, it was observed that some trigrams were more likely chosen than others. For instance, trigrams at the top-left corner of any page, or trigrams on the first or last few pages were more likely than one somewhere in the middle of the book or page.  We reflect this difference in distribution by assigning a _probability_ to each trigram, using Benford's law as introduced in [Probabilistic Fuzzing](ProbabilisticGrammarFuzzer.ipynb).

Recall, that Benford's law assigns the $i$-th digit the probability $\log_{10}\left(1 + \frac{1}{i}\right)$ where the base 10 is chosen because there are 10 digits $i\in [0,9]$. However, Benford's law works for an arbitrary number of "digits". Hence, we assign the $i$-th trigram the probability $\log_b\left(1 + \frac{1}{i}\right)$ where the base $b$ is the number of all possible trigrams $b=26^3$.

```python
k_book = {}  # Kenngruppenbuch

for i in range(1, len(trigrams) + 1):
    trigram = trigrams[i - 1]
    # choose weights according to Benford's law
    k_book[trigram] = log(1 + 1 / i) / log(26**3 + 1)
```

Here's a random trigram from the Kenngruppenbuch:

```python
random_trigram = choice(list(k_book.keys()), p=list(k_book.values()))
random_trigram
```

    'YHL'

And this is its probability:

```python
k_book[random_trigram]
```

    9.551288804867227e-06

### Fuzzing the Enigma

In the following, we introduce an extremely simplified implementation of the Naval Enigma based on the trigrams from the K-book. Of course, the encryption mechanism of the actual Enigma machine is much more sophisticated and worthy of a much more detailed investigation. We encourage the interested reader to follow up with further reading listed in the Background section.

The personell at Bletchley Park can only check whether an encoded message is encoded with a (guessed) trigram.
Our implementation `naval_enigma()` takes a `message` and a `key` (i.e., the guessed trigram).  If the given key matches the (previously computed) key for the message, `naval_enigma()` returns `True`.

```python
from Fuzzer import RandomFuzzer
from Fuzzer import Runner
```

```python
class EnigmaMachine(Runner):
    def __init__(self, k_book):
        self.k_book = k_book
        self.reset()

    def reset(self):
        """Resets the key register"""
        self.msg2key = {}

    def internal_msg2key(self, message):
        """Internal helper method.
           Returns the trigram for an encoded message."""
        if not message in self.msg2key:
            # Simulating how an officer chooses a key from the Kenngruppenbuch to encode the message.
            self.msg2key[message] = choice(list(self.k_book.keys()), p=list(self.k_book.values()))
        trigram = self.msg2key[message]
        return trigram

    def naval_enigma(self, message, key):
        """Returns true if 'message' is encoded with 'key'"""
        if key == self.internal_msg2key(message):
            return True
        else:
            return False
```

To "fuzz" the `naval_enigma()`, our job will be to come up with a key that matches a given (encrypted) message.  Since the keys only have three characters, we have a good chance to achieve this in much less than a second.  (Of course, longer keys will be much harder to find via random fuzzing.)

```python
class EnigmaMachine(EnigmaMachine):
    def run(self, tri):
        """PASS if cur_msg is encoded with trigram tri"""
        if self.naval_enigma(self.cur_msg, tri):
            outcome = self.PASS
        else:
            outcome = self.FAIL

        return (tri, outcome)
```

Now we can use the `EnigmaMachine` to check whether a certain message is encoded with a certain trigram.

```python
enigma = EnigmaMachine(k_book)
enigma.cur_msg = "BrEaK mE. L0Lzz"
enigma.run("AAA")
```

    ('AAA', 'FAIL')

The simplest way to crack an encoded message is by brute forcing. Suppose, at Bletchley park they would try random trigrams until a message is broken.

```python
class BletchleyPark(object):
    def __init__(self, enigma):
        self.enigma = enigma
        self.enigma.reset()
        self.enigma_fuzzer = RandomFuzzer(
            min_length=3,
            max_length=3,
            char_start=65,
            char_range=26)

    def break_message(self, message):
        """Returning the trigram for an encoded message"""
        self.enigma.cur_msg = message
        while True:
            (trigram, outcome) = self.enigma_fuzzer.run(self.enigma)
            if outcome == self.enigma.PASS:
                break
        return trigram
```

How long does it take Bletchley park to find the key using this brute forcing approach?

```python
from Timer import Timer
```

```python
enigma = EnigmaMachine(k_book)
bletchley = BletchleyPark(enigma)

with Timer() as t:
    trigram = bletchley.break_message("BrEaK mE. L0Lzz")
```

Here's the key for the current message:

```python
trigram
```

    'SUK'

And no, this did not take long:

```python
'%f seconds' % t.elapsed_time()
```

    '0.012987 seconds'

```python
'Bletchley cracks about %d messages per second' % (1/t.elapsed_time())
```

    'Bletchley cracks about 76 messages per second'

### Turing's Observations
Okay, lets crack a few messages and count the number of times each trigram is observed.

```python
from collections import defaultdict
```

```python
n = 100  # messages to crack
```

```python
observed = defaultdict(int)
for msg in range(0, n):
    trigram = bletchley.break_message(msg)
    observed[trigram] += 1

# list of trigrams that have been observed
counts = [k for k, v in observed.items() if int(v) > 0]

t_trigrams = len(k_book)
o_trigrams = len(counts)
```

```python
"After cracking %d messages, we observed %d out of %d trigrams." % (
    n, o_trigrams, t_trigrams)
```

    'After cracking 100 messages, we observed 76 out of 17576 trigrams.'

```python
singletons = len([k for k, v in observed.items() if int(v) == 1])
```

```python
"From the %d observed trigrams, %d were observed only once." % (
    o_trigrams, singletons)
```

    'From the 76 observed trigrams, 65 were observed only once.'

Given a sample of previously used entries, Turing wanted to _estimate the likelihood_ that the current unknown entry was one that had been previously used, and further, to estimate the probability distribution over the previously used entries. This lead to the development of the estimators of the missing mass and estimates of the true probability mass of the set of items occuring in the sample. Good worked with Turing during the war and, with Turing’s permission, published the analysis of the bias of these estimators in 1953.

Suppose, after finding the keys for n=100 messages, we have observed the trigram "ABC" exactly $X_\text{ABC}=10$ times. What is the probability $p_\text{ABC}$ that "ABC" is the key for the next message? Empirically, we would estimate $\hat p_\text{ABC}=\frac{X_\text{ABC}}{n}=0.1$. We can derive the empirical estimates for all other trigrams that we have observed.  However, it becomes quickly evident that the complete probability mass is distributed over the *observed* trigrams. This leaves no mass for *unobserved* trigrams, i.e., the probability of discovering a new trigram. This is called the missing probability mass or the discovery probability.

Turing and Good derived an estimate of the *discovery probability* $p_0$, i.e., the probability to discover an unobserved trigram, as the number $f_1$ of trigrams observed exactly once divided by the total number $n$ of messages cracked:
$$
p_0 = \frac{f_1}{n}
$$
where $f_1$ is the number of singletons and $n$ is the number of cracked messages.

Lets explore this idea for a bit. We'll extend `BletchleyPark` to crack `n` messages and record the number of trigrams observed as the number of cracked messages increases.

```python
class BletchleyPark(BletchleyPark):

    def break_message(self, message):
        """Returning the trigram for an encoded message"""
        # For the following experiment, we want to make it practical
        #   to break a large number of messages. So, we remove the
        #   loop and just return the trigram for a message.
        #
        # enigma.cur_msg = message
        # while True:
        #     (trigram, outcome) = self.enigma_fuzzer.run(self.enigma)
        #     if outcome == self.enigma.PASS:
        #         break
        trigram = enigma.internal_msg2key(message)
        return trigram

    def break_n_messages(self, n):
        """Returns how often each trigram has been observed,
           and #trigrams discovered for each message."""
        observed = defaultdict(int)
        timeseries = [0] * n

        # Crack n messages and record #trigrams observed as #messages increases
        cur_observed = 0
        for cur_msg in range(0, n):
            trigram = self.break_message(cur_msg)

            observed[trigram] += 1
            if (observed[trigram] == 1):
                cur_observed += 1
            timeseries[cur_msg] = cur_observed

        return (observed, timeseries)
```

Let's crack 2000 messages and compute the GT-estimate.

```python
n = 2000        # messages to crack
```

```python
bletchley = BletchleyPark(enigma)
(observed, timeseries) = bletchley.break_n_messages(n)
```

Let us determine the Good-Turing estimate of the probability that the next trigram has not been observed before:

```python
singletons = len([k for k, v in observed.items() if int(v) == 1])
gt = singletons / n
gt
```

    0.378

We can verify the Good-Turing estimate empirically and compute the empirically determined probability that the next trigram has not been observed before. To do this, we repeat the following experiment `repeats=1000` times, reporting the average: If the next message is a new trigram, return 1, otherwise return 0. Note that here, we do not record the newly discovered trigrams as observed.

```python
repeats = 1000  # experiment repetitions
```

```python
newly_discovered = 0
for cur_msg in range(n, n + repeats):
    trigram = bletchley.break_message(cur_msg)
    if(observed[trigram] == 0):
        newly_discovered += 1

newly_discovered / repeats
```

    0.429

Looks pretty accurate, huh? The difference between estimates is reasonably small, probably below 0.03. However, the Good-Turing estimate did not nearly require as much computational resources as the empirical estimate. Unlike the empirical estimate, the Good-Turing estimate can be computed during the campaign. Unlike the empirical estimate, the Good-Turing estimate requires no additional, redundant repetitions.

In fact, the Good-Turing (GT) estimator often performs close to the best estimator for arbitrary distributions ([Try it here!](#Kenngruppenbuch)). Of course, the concept of *discovery* is not limited to trigrams. The GT estimator is also used in the study of natural languages to estimate the likelihood that we haven't ever heard or read the word we next encounter. The GT estimator is used in ecology to estimate the likelihood of discovering a new, unseen species in our quest to catalog all _species_ on earth. Later, we will see how it can be used to estimate the probability to discover a vulnerability when none has been observed, yet (i.e., residual risk).

Alan Turing was interested in the _complement_ $(1-GT)$ which gives the proportion of _all_ messages for which the Brits have already observed the trigram needed for decryption. For this reason, the complement is also called sample coverage. The *sample coverage* quantifies how much we know about decryption of all messages given the few messages we have already decrypted.

The probability that the next message can be decrypted with a previously discovered trigram is:

```python
1 - gt
```

    0.622

The *inverse* of the GT-estimate (1/GT) is a _maximum likelihood estimate_ of the expected number of messages that we can decrypt with previously observed trigrams before having to find a new trigram to decrypt the message.  In our setting, the number of messages for which we can expect to reuse previous trigrams before having to discover a new trigram is:

```python
1 / gt
```

    2.6455026455026456

But why is GT so accurate? Intuitively, despite a large sampling effort (i.e., cracking $n$ messages), there are still $f_1$ trigrams that have been observed only once. We could say that such "singletons" are very rare trigrams. Hence, the probability that the next messages is encoded with such a rare but observed trigram gives a good upper bound on the probability that the next message is encoded with an evidently much rarer, unobserved trigram. Since Turing's observation 80 years ago, an entire statistical theory has been developed around the hypothesis that rare, observed "species" are good predictors of unobserved species.

Let's have a look at the distribution of rare trigrams.

```python
%matplotlib inline
```

```python
import matplotlib.pyplot as plt
```

```python
frequencies = [v for k, v in observed.items() if int(v) > 0]
frequencies.sort(reverse=True)
# Uncomment to see how often each discovered trigram has been observed
# print(frequencies)

# frequency of rare trigrams
plt.figure(num=None, figsize=(12, 4), dpi=80, facecolor='w', edgecolor='k')
plt.subplot(1, 2, 1)
plt.hist(frequencies, range=[1, 21], bins=numpy.arange(1, 21) - 0.5)
plt.xticks(range(1, 21))
plt.xlabel('# of occurances (e.g., 1 represents singleton trigrams)')
plt.ylabel('Frequency of occurances')
plt.title('Figure 1. Frequency of Rare Trigrams')

# trigram discovery over time
plt.subplot(1, 2, 2)
plt.plot(timeseries)
plt.xlabel('# of messages cracked')
plt.ylabel('# of trigrams discovered')
plt.title('Figure 2. Trigram Discovery Over Time');
```

```python
# Statistics for most and least often observed trigrams
singletons = len([v for k, v in observed.items() if int(v) == 1])
total = len(frequencies)

print("%3d of %3d trigrams (%.3f%%) have been observed   1 time (i.e., are singleton trigrams)."
      % (singletons, total, singletons * 100 / total))

print("%3d of %3d trigrams ( %.3f%%) have been observed %d times."
      % (1, total, 1 / total, frequencies[0]))
```

    756 of 968 trigrams (78.099%) have been observed   1 time (i.e., are singleton trigrams).
      1 of 968 trigrams ( 0.001%) have been observed 130 times.

The *majority of trigrams* have been observed only once, as we can see in Figure 1 (left). In other words, the majority of observed trigrams are "rare" singletons. In Figure 2 (right), we can see that discovery is in full swing. The trajectory seems almost linear. However, since there is a finite number of trigrams (26^3 = 17,576) trigram discovery will slow down and eventually approach an asymptote (the total number of trigrams).

### Boosting the Performance of BletchleyPark
Some trigrams have been observed very often. We call these "abundant" trigrams.

```python
print("Trigram : Frequency")
for trigram in sorted(observed, key=observed.get, reverse=True):
    if observed[trigram] > 10:
        print("    %s : %d" % (trigram, observed[trigram]))
```

    Trigram : Frequency
        KYA : 130
        URR : 92
        TPC : 52
        VBQ : 46
        KRK : 40
        LOI : 36
        ZIR : 34
        ZXY : 29
        RRR : 21
        MYZ : 20
        JNX : 20
        WIW : 20
        NKZ : 16
        LUS : 13
        VVM : 13
        ESC : 13
        RBW : 13
        RPF : 12
        ZZM : 12
        MEC : 12
        HKI : 11
        AWR : 11

We'll speed up the code breaking by _trying the abundant trigrams first_.

First, we'll find out how many messages can be cracked by the existing brute forcing strategy at Bledgley park, given a maximum number of attempts. We'll also track the number of messages cracked over time (`timeseries`).

```python
class BletchleyPark(BletchleyPark):

    def __init__(self, enigma):
        super().__init__(enigma)
        self.cur_attempts = 0
        self.cur_observed = 0
        self.observed = defaultdict(int)
        self.timeseries = [None] * max_attempts * 2

    def break_message(self, message):
        """Returns the trigram for an encoded message, and
           track #trigrams observed as #attempts increases."""
        self.enigma.cur_msg = message
        while True:
            self.cur_attempts += 1                                 # NEW
            (trigram, outcome) = self.enigma_fuzzer.run(self.enigma)
            self.timeseries[self.cur_attempts] = self.cur_observed # NEW
            if outcome == self.enigma.PASS:
                break
        return trigram

    def break_max_attempts(self, max_attempts):
        """Returns #messages successfully cracked after a given #attempts."""
        cur_msg  = 0
        n_messages = 0

        while True:
            trigram = self.break_message(cur_msg)

            # stop when reaching max_attempts
            if self.cur_attempts >= max_attempts:
                break

            # update observed trigrams
            n_messages += 1
            self.observed[trigram] += 1
            if (self.observed[trigram] == 1):
                self.cur_observed += 1
                self.timeseries[self.cur_attempts] = self.cur_observed
            cur_msg += 1
        return n_messages
```

`original` is the number of messages cracked by the bruteforcing strategy, given 100k attempts.  Can we beat this?

```python
max_attempts = 100000
```

```python
bletchley = BletchleyPark(enigma)
original = bletchley.break_max_attempts(max_attempts)
original
```

    11

Now, we'll create a boosting strategy by trying trigrams first that we have previously observed most often.

```python
class BoostedBletchleyPark(BletchleyPark):

    def break_message(self, message):
        """Returns the trigram for an encoded message, and
           track #trigrams observed as #attempts increases."""
        self.enigma.cur_msg = message

        # boost cracking by trying observed trigrams first
        for trigram in sorted(self.prior, key=self.prior.get, reverse=True):
            self.cur_attempts += 1
            (_, outcome) = self.enigma.run(trigram)
            self.timeseries[self.cur_attempts] = self.cur_observed
            if outcome == self.enigma.PASS:
                return trigram

        # else fall back to normal cracking
        return super().break_message(message)
```

`boosted` is the number of messages cracked by the boosted strategy.

```python
boostedBletchley = BoostedBletchleyPark(enigma)
boostedBletchley.prior = observed
boosted = boostedBletchley.break_max_attempts(max_attempts)
boosted
```

    23

We see that the boosted technique cracks substantially more messages. It is worthwhile to record how often each trigram is being used as key and try them in the order of their occurence.

***Try it***. *For practical reasons, we use a large number of previous observations as prior (`boostedBletchley.prior = observed`). You can try to  change the code such that the strategy uses the trigram frequencies (`self.observed`) observed **during** the campaign itself to boost the campaign. You will need to increase `max_attempts` and wait for a long while.*

Let's compare the number of trigrams discovered over time.

```python
# print plots
line_old, = plt.plot(bletchley.timeseries, label="Bruteforce Strategy")
line_new, = plt.plot(boostedBletchley.timeseries, label="Boosted Strategy")
plt.legend(handles=[line_old, line_new])
plt.xlabel('# of cracking attempts')
plt.ylabel('# of trigrams discovered')
plt.title('Trigram Discovery Over Time');
```

We see that the boosted fuzzer is constantly superior over the random fuzzer.

## Estimating the Probability of Path Discovery

<!-- ## Residual Risk: Probability of Failure after an Unsuccessful Fuzzing Campaign -->
<!-- Residual risk is not formally defined in this section, so I made the title a bit more generic -- AZ -->

So, what does Turing's observation for the Naval Enigma have to do with fuzzing _arbitrary_ programs? Turing's assistant I.J. Good extended and published Turing's work on the estimation procedures in Biometrica, a journal for theoretical biostatistics that still exists today. Good did not talk about trigrams. Instead, he calls them "species". Hence, the GT estimator is presented to estimate how likely it is to discover a new species, given an existing sample of individuals (each of which belongs to exactly one species).

Now, we can associate program inputs to species, as well. For instance, we could define the path that is exercised by an input as that input's species. This would allow us to _estimate the probability that fuzzing discovers a new path._ Later, we will see how this discovery probability estimate also estimates the likelihood of discovering a vulnerability when we have not seen one, yet (residual risk).

Let's do this. We identify the species for an input by computing a hash-id over the set of statements exercised by that input. In the [Coverage](Coverage.ipynb) chapter, we have learned about the [Coverage class](Coverage.ipynb#A-Coverage-Class) which collects coverage information for an executed Python function. As an example, the function [`cgi_decode()`](Coverage.ipynb#A-CGI-Decoder) was introduced. The function `cgi_decode()` takes a string encoded for a website URL and decodes it back to its original form.

Here's what `cgi_decode()` does and how coverage is computed.

```python
from Coverage import Coverage, cgi_decode
```

```python
encoded = "Hello%2c+world%21"
with Coverage() as cov:
    decoded = cgi_decode(encoded)
```

```python
decoded
```

    'Hello, world!'

```python
print(cov.coverage());
```

    {('cgi_decode', 12), ('cgi_decode', 9), ('cgi_decode', 15), ('cgi_decode', 18), ('cgi_decode', 24), ('cgi_decode', 21), ('cgi_decode', 30), ('cgi_decode', 8), ('cgi_decode', 11), ('cgi_decode', 17), ('cgi_decode', 20), ('cgi_decode', 26), ('cgi_decode', 23), ('__exit__', 79), ('cgi_decode', 32), ('cgi_decode', 10), ('cgi_decode', 19), ('cgi_decode', 16), ('cgi_decode', 22), ('cgi_decode', 25), ('cgi_decode', 31)}

### Trace Coverage
First, we will introduce the concept of execution traces, which are a coarse abstraction of the execution path taken by an input. Compared to the definition of path, a trace ignores the sequence in which statements are exercised or how often each statement is exercised.

* `pickle.dumps()` - serializes an object by producing a byte array from all the information in the object
* `hashlib.md5()` - produces a 128-bit hash value from a byte array

```python
import pickle
import hashlib
```

```python
def getTraceHash(cov):
    pickledCov = pickle.dumps(cov.coverage())
    hashedCov = hashlib.md5(pickledCov).hexdigest()
    return hashedCov
```

Remember our model for the Naval Enigma machine? Each message must be decrypted using exactly one trigram while multiple messages may be decrypted by the same trigram. Similarly, we need each input to yield exactly one trace hash while multiple inputs can yield the same trace hash.

Let's see whether this is true for our `getTraceHash()` function.

```python
inp1 = "a+b"
inp2 = "a+b+c"
inp3 = "abc"

with Coverage() as cov1:
    cgi_decode(inp1)
with Coverage() as cov2:
    cgi_decode(inp2)
with Coverage() as cov3:
    cgi_decode(inp3)
```

The inputs `inp1` and `inp2` execute the same statements:

```python
inp1, inp2
```

    ('a+b', 'a+b+c')

```python
cov1.coverage() - cov2.coverage()
```

    set()

The difference between both coverage sets is empty. Hence, the trace hashes should be the same:

```python
getTraceHash(cov1)
```

    '1f6a3162d288a31508d7f6e9fc32f4d9'

```python
getTraceHash(cov2)
```

    '1f6a3162d288a31508d7f6e9fc32f4d9'

```python
assert getTraceHash(cov1) == getTraceHash(cov2)
```

In contrast, the inputs `inp1` and `inp3` execute _different_ statements:

```python
inp1, inp3
```

    ('a+b', 'abc')

```python
cov1.coverage() - cov3.coverage()
```

    {('cgi_decode', 20)}

Hence, the trace hashes should be different, too:

```python
getTraceHash(cov1)
```

    '1f6a3162d288a31508d7f6e9fc32f4d9'

```python
getTraceHash(cov3)
```

    '5dc3db33fefc6cf7a6e49ea1673e0832'

```python
assert getTraceHash(cov1) != getTraceHash(cov3)
```

### Measuring Trace Coverage over Time
In order to measure trace coverage for a `function` executing a `population` of fuzz inputs, we slightly adapt the `population_coverage()` function from the [Chapter on Coverage](Coverage.ipynb#Coverage-of-Basic-Fuzzing).

```python
def population_trace_coverage(population, function):
    cumulative_coverage = []
    all_coverage = set()
    cumulative_singletons = []
    cumulative_doubletons = []
    singletons = set()
    doubletons = set()

    for s in population:
        with Coverage() as cov:
            try:
                function(s)
            except BaseException:
                pass
        cur_coverage = set([getTraceHash(cov)])

        # singletons and doubletons -- we will need them later
        doubletons -= cur_coverage
        doubletons |= singletons & cur_coverage
        singletons -= cur_coverage
        singletons |= cur_coverage - (cur_coverage & all_coverage)
        cumulative_singletons.append(len(singletons))
        cumulative_doubletons.append(len(doubletons))

        # all and cumulative coverage
        all_coverage |= cur_coverage
        cumulative_coverage.append(len(all_coverage))

    return all_coverage, cumulative_coverage, cumulative_singletons, cumulative_doubletons
```

Let's see whether our new function really contains coverage information only for *two* traces given our three inputs for `cgi_decode`.

```python
all_coverage = population_trace_coverage([inp1, inp2, inp3], cgi_decode)[0]
assert len(all_coverage) == 2
```

Unfortunately, the `cgi_decode()` function is too simple. Instead, we will use the original Python [HTMLParser](https://docs.python.org/3/library/html.parser.html) as our test subject.

```python
from Fuzzer import RandomFuzzer
from Coverage import population_coverage
from html.parser import HTMLParser
```

```python
trials = 50000  # number of random inputs generated
```

Let's run a random fuzzer for $n=50000$ times and plot trace coverage over time.

```python
# create wrapper function
def my_parser(inp):
    parser = HTMLParser()  # resets the HTMLParser object for every fuzz input
    parser.feed(inp)
```

```python
# create random fuzzer
fuzzer = RandomFuzzer(min_length=1, max_length=100,
                      char_start=32, char_range=94)

# create population of fuzz inputs
population = []
for i in range(trials):
    population.append(fuzzer.fuzz())

# execute and measure trace coverage
trace_timeseries = population_trace_coverage(population, my_parser)[1]

# execute and measure code coverage
code_timeseries = population_coverage(population, my_parser)[1]

# plot trace coverage over time
plt.figure(num=None, figsize=(12, 4), dpi=80, facecolor='w', edgecolor='k')
plt.subplot(1, 2, 1)
plt.plot(trace_timeseries)
plt.xlabel('# of fuzz inputs')
plt.ylabel('# of traces exercised')
plt.title('Trace Coverage Over Time')

# plot code coverage over time
plt.subplot(1, 2, 2)
plt.plot(code_timeseries)
plt.xlabel('# of fuzz inputs')
plt.ylabel('# of statements covered')
plt.title('Code Coverage Over Time');
```

Above, we can see trace coverage (left) and code coverage (right) over time. Here are our observations.
1. **Trace coverage is more robust**. There are less sudden jumps in the graph compared to code coverage.
2. **Trace coverage is more fine grained.** There are more traces than statements covered in the end (y-axis).
3. **Trace coverage grows more steadily**. Code coverage exercises more than half the statements it has exercised after 50k inputs with the first input. Instead, the number of traces covered grows slowly and steadily since each input can yield only one execution trace.

It is for this reason that one of the most prominent and successful fuzzers today, american fuzzy lop (AFL), uses a similar *measure of progress* (a hash computed over the branches exercised by the input).

### Evaluating the Discovery Probability Estimate

Let's find out how the Good-Turing estimator performs as estimate of discovery probability when we are fuzzing to discover execution traces rather than trigrams.

To measure the empirical probability, we execute the same population of inputs (n=50000) and measure in regular intervals (`measurements=100` intervals). During each measurement, we repeat the following experiment `repeats=500` times, reporting the average: If the next input yields a new trace, return 1, otherwise return 0. Note that during these repetitions, we do not record the newly discovered traces as observed.

```python
repeats = 500      # experiment repetitions
measurements = 100  # experiment measurements
```

```python
emp_timeseries = []
all_coverage = set()
step = int(trials / measurements)

for i in range(0, trials, step):
    if i - step >= 0:
        for j in range(step):
            inp = population[i - j]
            with Coverage() as cov:
                try:
                    my_parser(inp)
                except BaseException:
                    pass
            all_coverage |= set([getTraceHash(cov)])

    discoveries = 0
    for _ in range(repeats):
        inp = fuzzer.fuzz()
        with Coverage() as cov:
            try:
                my_parser(inp)
            except BaseException:
                pass
        if getTraceHash(cov) not in all_coverage:
            discoveries += 1
    emp_timeseries.append(discoveries / repeats)
```

Now, we compute the Good-Turing estimate over time.

```python
gt_timeseries = []
singleton_timeseries = population_trace_coverage(population, my_parser)[2]
for i in range(1, trials + 1, step):
    gt_timeseries.append(singleton_timeseries[i - 1] / i)
```

Let's go ahead and plot both time series.

```python
line_emp, = plt.semilogy(emp_timeseries, label="Empirical")
line_gt, = plt.semilogy(gt_timeseries, label="Good-Turing")
plt.legend(handles=[line_emp, line_gt])
plt.xticks(range(0, measurements + 1, int(measurements / 5)),
           range(0, trials + 1, int(trials / 5)))
plt.xlabel('# of fuzz inputs')
plt.ylabel('discovery probability')
plt.title('Discovery Probability Over Time');
```

Again, the Good-Turing estimate appears to be *highly accurate*. In fact, the empirical estimator has a much lower precision as indicated by the large swings. You can try and increase the number of repetitions (`repeats`) to get more precision for the empirical estimates, however, at the cost of waiting much longer.

### Discovery Probability Quantifies Residual Risk

Alright. You have gotten a hold of a couple of powerful machines and used them to fuzz a software system for several months without finding any vulnerabilities. Is the system vulnerable?

Well, who knows? We cannot say for sure; there is always some residual risk. Testing is not verification. Maybe the next test input that is generated reveals a vulnerability.

Let's say *residual risk* is the probability that the next test input reveals a vulnerability that has not been found, yet. Böhme \cite{Boehme2018stads} has shown that the Good-Turing estimate of the discovery probability is also an estimate of the maximum residual risk.

**Proof sketch (Residual Risk)**. Here is a proof sketch that shows that an estimator of discovery probability for an arbitrary definition of species gives an upper bound on the probability to discover a vulnerability when none has been found: Suppose, for each "old" species A (here, execution trace), we derive two "new" species: Some inputs belonging to A expose a vulnerability while others belonging to A do not. We know that _only_ species that do not expose a vulnerability have been discovered. Hence, _all_ species exposing a vulnerability and _some_ species that do not expose a vulnerability remain undiscovered. Hence, the probability to discover a new species gives an upper bound on the probability to discover (a species that exposes) a vulnerability. **QED**.

An estimate of the discovery probability is useful in many other ways.

1. **Discovery probability**. We can estimate, at any point during the fuzzing campaign, the probability that the next input belongs to a previously unseen species (here, that it yields a new execution trace, i.e., exercises a new set of statements).
2. **Complement of discovery probability**. We can estimate the proportion of *all* inputs the fuzzer can generate for which we have already seen the species (here, execution traces). In some sense, this allows us to quantify the *progress of the fuzzing campaign towards completion*: If the probability to discovery a new species is too low, we might as well abort the campaign.
3. **Inverse of discovery probability**. We can predict the number of test inputs needed, so that we can expect the discovery of a new species (here, execution trace).

## How Do We Know When to Stop Fuzzing?

In fuzzing, we have measures of progress such as [code coverage](Coverage.ipynb) or [grammar coverage](GrammarCoverageFuzzer.ipynb). Suppose, we are interested in covering all statements in the program. The _percentage_ of statements that have already been covered quantifies how "far" we are from completing the fuzzing campaign. However, sometimes we know only the _number_ of species $S(n)$ (here, statements) that have been discovered after generating $n$ fuzz inputs. The percentage $S(n)/S$ can only be computed if we know the _total number_ of species $S$. Even then, not all species may be feasible.

### A Success Estimator

If we do not _know_ the total number of species, then let's at least _estimate_ it: As we have seen before, species discovery slows down over time. In the beginning, many new species are discovered. Later, many inputs need to be generated before discovering the next species. In fact, given enough time, the fuzzing campaign approaches an _asymptote_. It is this asymptote that we can estimate.

In 1984, Anne Chao, a well-known theoretical bio-statistician, has developed an estimator $\hat S$ which estimates the asymptotic total number of species $S$:
\begin{align}
\hat S_\text{Chao1} = \begin{cases}
S(n) + \frac{f_1^2}{2f_2} & \text{if $f_2>0$}\\
S(n) + \frac{f_1(f_1-1)}{2} & \text{otherwise}
\end{cases}
\end{align}
* where $f_1$ and $f_2$ is the number of singleton and doubleton species, respectively (that have been observed exactly once or twice, resp.), and
* where $S(n)$ is the number of species that have been discovered after generating $n$ fuzz inputs.

So, how does Chao's estimate perform? To investigate this, we generate `trials=400000` fuzz inputs using a fuzzer setting that allows us to see an asymptote in a few seconds: We measure trace coverage. After half-way into our fuzzing campaign (`trials`/2=100000), we generate Chao's estimate $\hat S$ of the asymptotic total number of species. Then, we run the remainer of the campaign to see the "empirical" asymptote.

```python
trials = 400000
fuzzer = RandomFuzzer(min_length=2, max_length=4,
                      char_start=32, char_range=32)
population = []
for i in range(trials):
    population.append(fuzzer.fuzz())

_, trace_ts, f1_ts, f2_ts = population_trace_coverage(population, my_parser)
```

```python
time = int(trials / 2)
time
```

    200000

```python
f1 = f1_ts[time]
f2 = f2_ts[time]
Sn = trace_ts[time]
if f2 > 0:
    hat_S = Sn + f1 * f1 / (2 * f2)
else:
    hat_S = Sn + f1 * (f1 - 1) / 2
```

After executing `time` fuzz inputs (half of all), we have covered this many traces:

```python
time
```

    200000

```python
Sn
```

    62

We can estimate there are this many traces in total:

```python
hat_S
```

    72.125

Hence, we have achieved this percentage of the estimate:

```python
100 * Sn / hat_S
```

    85.96187175043327

After executing `trials` fuzz inputs, we have covered this many traces:

```python
trials
```

    400000

```python
trace_ts[trials - 1]
```

    71

The accuracy of Chao's estimator is quite reasonable. It isn't always accurate -- particularly at the beginning of a fuzzing campaign when the [discovery probability](WhenIsEnough.ipynb#Measuring-Trace-Coverage-over-Time) is still very high. Nevertheless, it demonstrates the main benefit of reporting a percentage to assess the progress of a fuzzing campaign towards completion.

***Try it***. *Try setting `trials` to 1 million and `time` to `int(trials / 4)`.*

### Extrapolating Fuzzing Success
<!--  ## Cost-Benefit Analysis: Extrapolating the Number of Species Discovered -->

Suppose you have run the fuzzer for a week, which generated $n$ fuzz inputs and discovered $S(n)$ species (here, covered $S(n)$ execution traces). Instead, of running the fuzzer for another week, you would like to *predict* how many more species you would discover. In 2003, Anne Chao and her team developed an extrapolation methodology to do just that. We are interested in the number $S(n+m^*)$ of species discovered if $m^*$ more fuzz inputs were generated:

\begin{align}
\hat S(n + m^*) = S(n) + \hat f_0 \left[1-\left(1-\frac{f_1}{n\hat f_0 + f_1}\right)^{m^*}\right]
\end{align}
* where $\hat f_0=\hat S - S(n)$ is an estimate of the number $f_0$ of undiscovered species, and
* where $f_1$ is the number of singleton species, i.e., those we have observed exactly once.

The number $f_1$ of singletons, we can just keep track of during the fuzzing campaign itself. The estimate of the number $\hat f_0$ of undiscovered species, we can simply derive using Chao's estimate $\hat S$ and the number of observed species $S(n)$.

Let's see how Chao's extrapolator performs by comparing the predicted number of species to the empirical number of species.

```python
prediction_ts = [None] * time
f0 = hat_S - Sn

for m in range(trials - time):
    assert (time * f0 + f1) != 0 , 'time:%s f0:%s f1:%s' % (time, f0,f1)
    prediction_ts.append(Sn + f0 * (1 - (1 - f1 / (time * f0 + f1)) ** m))
```

```python
plt.figure(num=None, figsize=(12, 3), dpi=80, facecolor='w', edgecolor='k')
plt.subplot(1, 3, 1)
plt.plot(trace_ts, color='white')
plt.plot(trace_ts[:time])
plt.xticks(range(0, trials + 1, int(time)))
plt.xlabel('# of fuzz inputs')
plt.ylabel('# of traces exercised')

plt.subplot(1, 3, 2)
line_cur, = plt.plot(trace_ts[:time], label="Ongoing fuzzing campaign")
line_pred, = plt.plot(prediction_ts, linestyle='--',
                      color='black', label="Predicted progress")
plt.legend(handles=[line_cur, line_pred])
plt.xticks(range(0, trials + 1, int(time)))
plt.xlabel('# of fuzz inputs')
plt.ylabel('# of traces exercised')

plt.subplot(1, 3, 3)
line_emp, = plt.plot(trace_ts, color='grey', label="Actual progress")
line_cur, = plt.plot(trace_ts[:time], label="Ongoing fuzzing campaign")
line_pred, = plt.plot(prediction_ts, linestyle='--',
                      color='black', label="Predicted progress")
plt.legend(handles=[line_emp, line_cur, line_pred])
plt.xticks(range(0, trials + 1, int(time)))
plt.xlabel('# of fuzz inputs')
plt.ylabel('# of traces exercised');
```

The prediction from Chao's extrapolator looks quite accurate. We make a prediction at `time=trials/4`. Despite an extrapolation by 3 times (i.e., at trials), we can see that the predicted value (black, dashed line) closely matches the empirical value (grey, solid line).

***Try it***. Again, try setting `trials` to 1 million and `time` to `int(trials / 4)`.

## Lessons Learned

* One can measure the _progress_ of a fuzzing campaign (as species over time, i.e., $S(n)$).
* One can measure the _effectiveness_ of a fuzzing campaign (as asymptotic total number of species $S$).
* One can estimate the _effectiveness_ of a fuzzing campaign using the Chao1-estimator $\hat S$.
* One can extrapolate the _progress_ of a fuzzing campaign, $\hat S(n+m^*)$.
* One can estimate the _residual risk_ (i.e., the probability that a bug exists that has not been found) using the Good-Turing estimator $GT$ of the species discovery probability.

## Next Steps

This chapter is the last in the book!  If you want to continue reading, have a look at the [Appendices](99_Appendices.ipynb).  Otherwise, _make use of what you have learned and go and create great fuzzers and test generators!_

## Background

* A **statistical framework for fuzzing**, inspired from ecology. Marcel Böhme. [STADS: Software Testing as Species Discovery](https://mboehme.github.io/paper/TOSEM18.pdf). ACM TOSEM 27(2):1--52
* Estimating the **discovery probability**: I.J. Good. 1953. [The population frequencies of species and the
estimation of population parameters](https://www.jstor.org/stable/2333344). Biometrika 40:237–264.
* Estimating the **asymptotic total number of species** when each input can belong to exactly one species: Anne Chao. 1984. [Nonparametric estimation of the number of classes in a population](https://www.jstor.org/stable/4615964). Scandinavian Journal of Statistics 11:265–270
* Estimating the **asymptotic total number of species** when each input can belong to one or more species: Anne Chao. 1987. [Estimating the population size for capture-recapture data with unequal catchability](https://www.jstor.org/stable/2531532). Biometrics 43:783–791
* **Extrapolating** the number of discovered species: Tsung-Jen Shen, Anne Chao, and Chih-Feng Lin. 2003. [Predicting the Number of New Species in Further Taxonomic Sampling](http://chao.stat.nthu.edu.tw/wordpress/paper/2003_Ecology_84_P798.pdf). Ecology 84, 3 (2003), 798–804.

## Exercises
I.J. Good and Alan Turing developed an estimator for the case where each input belongs to exactly one species. For instance, each input yields exactly one execution trace (see function [`getTraceHash`](#Trace-Coverage)). However, this is not true in general. For instance, each input exercises multiple statements and branches in the source code. Generally, each input can belong to one *or more* species.

In this extended model, the underlying statistics are quite different. Yet, all estimators that we have discussed in this chapter turn out to be almost identical to those for the simple, single-species model. For instance, the Good-Turing estimator $C$ is defined as
$$C=\frac{Q_1}{n}$$
where $Q_1$ is the number of singleton species and $n$ is the number of generated test cases.
Throughout the fuzzing campaign, we record for each species the *incidence frequency*, i.e., the number of inputs that belong to that species. Again, we define a species $i$ as *singleton species* if we have seen exactly one input that belongs to species $i$.

### Exercise 1: Estimate and Evaluate the Discovery Probability for Statement Coverage

In this exercise, we create a Good-Turing estimator for the simple fuzzer.

#### Part 1: Population Coverage

Implement a function `population_stmt_coverage()` as in [the section on estimating discovery probability](#Estimating-the-Discovery-Probability) that monitors the number of singletons and doubletons over time, i.e., as the number $i$ of test inputs increases.

```python
from Coverage import population_coverage, Coverage
...
```

**Solution.** Here we go:

```python
def population_stmt_coverage(population, function):
    cumulative_coverage = []
    all_coverage = set()
    cumulative_singletons = []
    cumulative_doubletons = []
    singletons = set()
    doubletons = set()

    for s in population:
        with Coverage() as cov:
            try:
                function(s)
            except BaseException:
                pass
        cur_coverage = cov.coverage()

        # singletons and doubletons
        doubletons -= cur_coverage
        doubletons |= singletons & cur_coverage
        singletons -= cur_coverage
        singletons |= cur_coverage - (cur_coverage & all_coverage)
        cumulative_singletons.append(len(singletons))
        cumulative_doubletons.append(len(doubletons))

        # all and cumulative coverage
        all_coverage |= cur_coverage
        cumulative_coverage.append(len(all_coverage))

    return all_coverage, cumulative_coverage, cumulative_singletons, cumulative_doubletons
```

#### Part 2: Population

Use the random `fuzzer(min_length=1, max_length=1000, char_start=0, char_range=255)` from [the chapter on Fuzzers](Fuzzer.ipynb) to generate a population of $n=10000$ fuzz inputs.

```python
from Fuzzer import RandomFuzzer
from html.parser import HTMLParser
...
```

    Ellipsis

**Solution.**  This is fairly straightforward:

```python
trials = 2000  # increase to 10000 for better convergences. Will take a while..
```

We create a wrapper function...

```python
def my_parser(inp):
    parser = HTMLParser()  # resets the HTMLParser object for every fuzz input
    parser.feed(inp)
```

... and a random fuzzer:

```python
fuzzer = RandomFuzzer(min_length=1, max_length=1000,
                      char_start=0, char_range=255)
```

We fill the population:

```python
population = []
for i in range(trials):
    population.append(fuzzer.fuzz())
```

#### Part 3: Estimating Probabilities

Execute the generated inputs on the Python HTML parser (`from html.parser import HTMLParser`) and estimate the probability that the next input covers a previously uncovered statement (i.e., the discovery probability) using the Good-Turing estimator.

**Solution.** Here we go:

```python
measurements = 100  # experiment measurements
step = int(trials / measurements)

gt_timeseries = []
singleton_timeseries = population_stmt_coverage(population, my_parser)[2]
for i in range(1, trials + 1, step):
    gt_timeseries.append(singleton_timeseries[i - 1] / i)
```

#### Part 4: Empirical Evaluation

Empirically evaluate the accuracy of the Good-Turing estimator (using $10000$ repetitions) of the probability to cover new statements using the experimental procedure at the end of [the section on estimating discovery probability](#Estimating-the-Discovery-Probability).

**Solution.** This is as above:

```python
# increase to 10000 for better precision (less variance). Will take a while..
repeats = 100
```

```python
emp_timeseries = []
all_coverage = set()
for i in range(0, trials, step):
    if i - step >= 0:
        for j in range(step):
            inp = population[i - j]
            with Coverage() as cov:
                try:
                    my_parser(inp)
                except BaseException:
                    pass
            all_coverage |= cov.coverage()

    discoveries = 0
    for _ in range(repeats):
        inp = fuzzer.fuzz()
        with Coverage() as cov:
            try:
                my_parser(inp)
            except BaseException:
                pass
        # If intersection not empty, a new stmt was (dis)covered
        if cov.coverage() - all_coverage:
            discoveries += 1
    emp_timeseries.append(discoveries / repeats)
```

```python
%matplotlib inline
import matplotlib.pyplot as plt
line_emp, = plt.semilogy(emp_timeseries, label="Empirical")
line_gt, = plt.semilogy(gt_timeseries, label="Good-Turing")
plt.legend(handles=[line_emp, line_gt])
plt.xticks(range(0, measurements + 1, int(measurements / 5)),
           range(0, trials + 1, int(trials / 5)))
plt.xlabel('# of fuzz inputs')
plt.ylabel('discovery probability')
plt.title('Discovery Probability Over Time');
```

### Exercise 2: Extrapolate and Evaluate Statement Coverage

In this exercise, we use Chao's extrapolation method to estimate the success of fuzzing.

#### Part 1: Create Population

Use the random `fuzzer(min_length=1, max_length=1000, char_start=0, char_range=255)` to generate a population of $n=400000$ fuzz inputs.

**Solution.** Here we go:

```python
trials = 400  # Use 400000 for actual solution.  This takes a while!
```

```python
population = []
for i in range(trials):
    population.append(fuzzer.fuzz())

_, stmt_ts, Q1_ts, Q2_ts = population_stmt_coverage(population, my_parser)
```

#### Part 2: Compute Estimate

Compute an estimate of the total number of statements $\hat S$ after $n/4=100000$ fuzz inputs were generated. In the extended model, $\hat S$ is computed as
\begin{align}
\hat S_\text{Chao1} = \begin{cases}
S(n) + \frac{Q_1^2}{2Q_2} & \text{if $Q_2>0$}\\
S(n) + \frac{Q_1(Q_1-1)}{2} & \text{otherwise}
\end{cases}
\end{align}
  * where $Q_1$ and $Q_2$ is the number of singleton and doubleton statements, respectively (i.e., statements that have been exercised by exactly one or two fuzz inputs, resp.), and
  * where $S(n)$ is the number of statements that have been (dis)covered after generating $n$ fuzz inputs.

**Solution.** Here we go:

```python
time = int(trials / 4)
Q1 = Q1_ts[time]
Q2 = Q2_ts[time]
Sn = stmt_ts[time]

if Q2 > 0:
    hat_S = Sn + Q1 * Q1 / (2 * Q2)
else:
    hat_S = Sn + Q1 * (Q1 - 1) / 2

print("After executing %d fuzz inputs, we have covered %d **(%.1f %%)** statements.\n" % (time, Sn, 100 * Sn / hat_S) +
      "After executing %d fuzz inputs, we estimate there are %d statements in total.\n" % (time, hat_S) +
      "After executing %d fuzz inputs, we have covered %d statements." % (trials, stmt_ts[trials - 1]))
```

    After executing 100 fuzz inputs, we have covered 137 **(53.3 %)** statements.
    After executing 100 fuzz inputs, we estimate there are 257 statements in total.
    After executing 400 fuzz inputs, we have covered 143 statements.

#### Part 3: Compute and Evaluate Extrapolator

Compute and evaluate Chao's extrapolator by comparing the predicted number of statements to the empirical number of statements.

**Solution.** Here's our solution:

```python
prediction_ts = [None] * time
Q0 = hat_S - Sn

for m in range(trials - time):
    prediction_ts.append(Sn + Q0 * (1 - (1 - Q1 / (time * Q0 + Q1)) ** m))
```

```python
plt.figure(num=None, figsize=(12, 3), dpi=80, facecolor='w', edgecolor='k')
plt.subplot(1, 3, 1)
plt.plot(stmt_ts, color='white')
plt.plot(stmt_ts[:time])
plt.xticks(range(0, trials + 1, int(time)))
plt.xlabel('# of fuzz inputs')
plt.ylabel('# of statements exercised')

plt.subplot(1, 3, 2)
line_cur, = plt.plot(stmt_ts[:time], label="Ongoing fuzzing campaign")
line_pred, = plt.plot(prediction_ts, linestyle='--',
                      color='black', label="Predicted progress")
plt.legend(handles=[line_cur, line_pred])
plt.xticks(range(0, trials + 1, int(time)))
plt.xlabel('# of fuzz inputs')
plt.ylabel('# of statements exercised')

plt.subplot(1, 3, 3)
line_emp, = plt.plot(stmt_ts, color='grey', label="Actual progress")
line_cur, = plt.plot(stmt_ts[:time], label="Ongoing fuzzing campaign")
line_pred, = plt.plot(prediction_ts, linestyle='--',
                      color='black', label="Predicted progress")
plt.legend(handles=[line_emp, line_cur, line_pred])
plt.xticks(range(0, trials + 1, int(time)))
plt.xlabel('# of fuzz inputs')
plt.ylabel('# of statements exercised');
```


Text provided under a Creative Commons Attribution license, CC-BY.  All code is made available under the FSF-approved BSD-3 license.  (c) Lorena A. Barba, Gilbert F. Forsyth 2017. Thanks to NSF for support via CAREER award #1149784.
[@LorenaABarba](https://twitter.com/LorenaABarba)

12 steps to Navier–Stokes
=====
***

We continue our journey to solve the Navier–Stokes equation with Step 4. But don't continue unless you have completed the previous steps! In fact, this next step will be a combination of the two previous ones. The wonders of *code reuse*!

Step 4: Burgers' Equation
----
***

You can read about Burgers' Equation on its [wikipedia page](http://en.wikipedia.org/wiki/Burgers'_equation).

Burgers' equation in one spatial dimension looks like this:

$$\frac{\partial u}{\partial t} + u \frac{\partial u}{\partial x} = \nu \frac{\partial ^2u}{\partial x^2}$$

As you can see, it is a combination of non-linear convection and diffusion. It is surprising how much you learn from this neat little equation!

We can discretize it using the methods we've already detailed in Steps [1](./01_Step_1.ipynb) to [3](./04_Step_3.ipynb).  Using forward difference for time, backward difference for space and our 2nd-order method for the second derivatives yields:

$$\frac{u_i^{n+1}-u_i^n}{\Delta t} + u_i^n \frac{u_i^n - u_{i-1}^n}{\Delta x} = \nu \frac{u_{i+1}^n - 2u_i^n + u_{i-1}^n}{\Delta x^2}$$

As before, once we have an initial condition, the only unknown is $u_i^{n+1}$. We will step in time as follows:

$$u_i^{n+1} = u_i^n - u_i^n \frac{\Delta t}{\Delta x} (u_i^n - u_{i-1}^n) + \nu \frac{\Delta t}{\Delta x^2}(u_{i+1}^n - 2u_i^n + u_{i-1}^n)$$

### Initial and Boundary Conditions

To examine some interesting properties of Burgers' equation, it is helpful to use different initial and boundary conditions than we've been using for previous steps.

Our initial condition for this problem is going to be:

\begin{eqnarray}
u &=& -\frac{2 \nu}{\phi} \frac{\partial \phi}{\partial x} + 4 \\\
\phi &=& \exp \bigg(\frac{-x^2}{4 \nu} \bigg) + \exp \bigg(\frac{-(x-2 \pi)^2}{4 \nu} \bigg)
\end{eqnarray}

This has an analytical solution, given by:

\begin{eqnarray}
u &=& -\frac{2 \nu}{\phi} \frac{\partial \phi}{\partial x} + 4 \\\
\phi &=& \exp \bigg(\frac{-(x-4t)^2}{4 \nu (t+1)} \bigg) + \exp \bigg(\frac{-(x-4t -2 \pi)^2}{4 \nu(t+1)} \bigg)
\end{eqnarray}

Our boundary condition will be:

$$u(0) = u(2\pi)$$

This is called a *periodic* boundary condition. Pay attention! This will cause you a bit of headache if you don't tread carefully.

### Saving Time with SymPy

The initial condition we're using for Burgers' Equation can be a bit of a pain to evaluate by hand.  The derivative $\frac{\partial \phi}{\partial x}$ isn't too terribly difficult, but it would be easy to drop a sign or forget a factor of $x$ somewhere, so we're going to use SymPy to help us out.

[SymPy](http://sympy.org/en/) is the symbolic math library for Python.  It has a lot of the same symbolic math functionality as Mathematica with the added benefit that we can easily translate its results back into our Python calculations (it is also free and open source).

Start by loading the SymPy library, together with our favorite library, NumPy.

```python
import numpy
import sympy
```

```python
# !pip3 install --user sympy
```

We're also going to tell SymPy that we want all of its output to be rendered using $\LaTeX$. This will make our Notebook beautiful!

```python
from sympy import init_printing
init_printing(use_latex=True)
```

Start by setting up symbolic variables for the three variables in our initial condition and then type out the full equation for $\phi$.  We should get a nicely rendered version of our $\phi$ equation.

```python
x, nu, t = sympy.symbols('x nu t')
phi = (sympy.exp(-(x - 4 * t)**2 / (4 * nu * (t + 1))) +
       sympy.exp(-(x - 4 * t - 2 * sympy.pi)**2 / (4 * nu * (t + 1))))
phi
```

```python
sympy.symbols('mu'),sympy.symbols('nu') # dynamic viscous, and kinematic viscous
```

It's maybe a little small, but that looks right.  Now to evaluate our partial derivative $\frac{\partial \phi}{\partial x}$ is a trivial task.

```python
phiprime = phi.diff(x)
phiprime
```

If you want to see the unrendered version, just use the Python print command.

```python
print(phiprime)
```

    -(-8*t + 2*x)*exp(-(-4*t + x)**2/(4*nu*(t + 1)))/(4*nu*(t + 1)) - (-8*t + 2*x - 4*pi)*exp(-(-4*t + x - 2*pi)**2/(4*nu*(t + 1)))/(4*nu*(t + 1))

### Now what?

Now that we have the Pythonic version of our derivative, we can finish writing out the full initial condition equation and then translate it into a usable Python expression.  For this, we'll use the *lambdify* function, which takes a SymPy symbolic equation and turns it into a callable function.

```python
from sympy.utilities.lambdify import lambdify

u = -2 * nu * (phiprime / phi) + 4
print(u)
u
```

### Lambdify

To lambdify this expression into a useable function, we tell lambdify which variables to request and the function we want to plug them in to.

```python
ufunc = lambdify((t, x, nu), u)
print(ufunc(1, 4, 3))
```

    3.49170664206445

### Back to Burgers' Equation

Now that we have the initial conditions set up, we can proceed and finish setting up the problem.  We can generate the plot of the initial condition using our lambdify-ed function.

```python
from matplotlib import pyplot
%matplotlib inline

###variable declarations
nx = 301
nt = 100
dx = 4 * numpy.pi / (nx - 1)
nu = 0.07
dt = dx * nu

x = numpy.linspace(0, 4 * numpy.pi, nx)
un = numpy.empty(nx)
t = 0

u = numpy.asarray([ufunc(t, x0, nu) for x0 in x])
u
```

    array([ 4.        ,  4.0418879 ,  4.0837758 ,  4.12566371,  4.16755161,
            4.20943951,  4.25132741,  4.29321531,  4.33510322,  4.37699112,
            4.41887902,  4.46076692,  4.50265482,  4.54454273,  4.58643063,
            4.62831853,  4.67020643,  4.71209433,  4.75398224,  4.79587014,
            4.83775804,  4.87964594,  4.92153385,  4.96342175,  5.00530965,
            5.04719755,  5.08908545,  5.13097336,  5.17286126,  5.21474916,
            5.25663706,  5.29852496,  5.34041287,  5.38230077,  5.42418867,
            5.46607657,  5.50796447,  5.54985238,  5.59174028,  5.63362818,
            5.67551608,  5.71740398,  5.75929189,  5.80117979,  5.84306769,
            5.88495559,  5.92684349,  5.9687314 ,  6.0106193 ,  6.0525072 ,
            6.0943951 ,  6.136283  ,  6.17817091,  6.22005881,  6.26194671,
            6.30383461,  6.34572251,  6.38761042,  6.42949832,  6.47138622,
            6.51327412,  6.55516202,  6.59704993,  6.63893783,  6.68082572,
            6.72271359,  6.76460125,  6.80648759,  6.84836523,  6.89018589,
            6.93163322,  6.97063555,  6.99367964,  6.91482855,  6.26782654,
            4.        ,  1.73217346,  1.08517145,  1.00632036,  1.02936445,
            1.06836678,  1.10981411,  1.15163477,  1.19351241,  1.23539875,
            1.27728641,  1.31917428,  1.36106217,  1.40295007,  1.44483798,
            1.48672588,  1.52861378,  1.57050168,  1.61238958,  1.65427749,
            1.69616539,  1.73805329,  1.77994119,  1.82182909,  1.863717  ,
            1.9056049 ,  1.9474928 ,  1.9893807 ,  2.0312686 ,  2.07315651,
            2.11504441,  2.15693231,  2.19882021,  2.24070811,  2.28259602,
            2.32448392,  2.36637182,  2.40825972,  2.45014762,  2.49203553,
            2.53392343,  2.57581133,  2.61769923,  2.65958713,  2.70147504,
            2.74336294,  2.78525084,  2.82713874,  2.86902664,  2.91091455,
            2.95280245,  2.99469035,  3.03657825,  3.07846615,  3.12035406,
            3.16224196,  3.20412986,  3.24601776,  3.28790567,  3.32979357,
            3.37168147,  3.41356937,  3.45545727,  3.49734518,  3.53923308,
            3.58112098,  3.62300888,  3.66489678,  3.70678469,  3.74867259,
            3.79056049,  3.83244839,  3.87433629,  3.9162242 ,  3.9581121 ,
            4.        ,  4.0418879 ,  4.0837758 ,  4.12566371,  4.16755161,
            4.20943951,  4.25132741,  4.29321531,  4.33510322,  4.37699112,
            4.41887902,  4.46076692,  4.50265482,  4.54454273,  4.58643063,
            4.62831853,  4.67020643,  4.71209433,  4.75398224,  4.79587014,
            4.83775804,  4.87964594,  4.92153385,  4.96342175,  5.00530965,
            5.04719755,  5.08908545,  5.13097336,  5.17286126,  5.21474916,
            5.25663706,  5.29852496,  5.34041287,  5.38230077,  5.42418867,
            5.46607657,  5.50796447,  5.54985238,  5.59174028,  5.63362818,
            5.67551608,  5.71740398,  5.75929189,  5.80117979,  5.84306769,
            5.88495559,  5.92684349,  5.9687314 ,  6.0106193 ,  6.0525072 ,
            6.0943951 ,  6.136283  ,  6.17817091,  6.22005881,  6.26194671,
            6.30383461,  6.34572251,  6.38761042,  6.42949832,  6.47138622,
            6.51327412,  6.55516202,  6.59704993,  6.63893783,  6.68082573,
            6.72271363,  6.76460154,  6.80648944,  6.84837734,  6.89026524,
            6.93215314,  6.97404105,  7.01592895,  7.05781685,  7.09970475,
            7.14159265,  7.18348056,  7.22536846,  7.26725636,  7.30914426,
            7.35103216,  7.39292007,  7.43480797,  7.47669587,  7.51858377,
            7.56047167,  7.60235958,  7.64424748,  7.68613538,  7.72802328,
            7.76991118,  7.81179909,  7.85368699,  7.89557489,  7.93746279,
            7.97935069,  8.0212386 ,  8.0631265 ,  8.1050144 ,  8.1469023 ,
            8.1887902 ,  8.23067811,  8.27256601,  8.31445391,  8.35634181,
            8.39822972,  8.44011762,  8.48200552,  8.52389342,  8.56578132,
            8.60766923,  8.64955713,  8.69144503,  8.73333293,  8.77522083,
            8.81710874,  8.85899664,  8.90088454,  8.94277244,  8.98466034,
            9.02654825,  9.06843615,  9.11032405,  9.15221195,  9.19409985,
            9.23598776,  9.27787566,  9.31976356,  9.36165146,  9.40353936,
            9.44542727,  9.48731517,  9.52920307,  9.57109097,  9.61297887,
            9.65486678,  9.69675468,  9.73864258,  9.78053048,  9.82241838,
            9.86430629,  9.90619419,  9.94808209,  9.98996999, 10.03185789,
           10.0737458 , 10.1156337 , 10.1575216 , 10.1994095 , 10.24129741,
           10.28318531])

```python
pyplot.figure(figsize=(8, 4), dpi=100)
pyplot.plot(x, u, marker='o', lw=2)
# pyplot.xlim([0, 2 * numpy.pi])
# pyplot.ylim([0, 10]);
```

This is definitely not the hat function we've been dealing with until now. We call it a "saw-tooth function".  Let's proceed forward and see what happens.

### Periodic Boundary Conditions

One of the big differences between Step 4 and the previous lessons is the use of *periodic* boundary conditions.  If you experiment with Steps 1 and 2 and make the simulation run longer (by increasing `nt`) you will notice that the wave will keep moving to the right until it no longer even shows up in the plot.

With periodic boundary conditions, when a point gets to the right-hand side of the frame, it *wraps around* back to the front of the frame.

Recall the discretization that we worked out at the beginning of this notebook:

$$u_i^{n+1} = u_i^n - u_i^n \frac{\Delta t}{\Delta x} (u_i^n - u_{i-1}^n) + \nu \frac{\Delta t}{\Delta x^2}(u_{i+1}^n - 2u_i^n + u_{i-1}^n)$$

What does $u_{i+1}^n$ *mean* when $i$ is already at the end of the frame?

Think about this for a minute before proceeding.

```python
for n in range(nt):
    un = u.copy()
    for i in range(1, nx-1):
        u[i] = un[i] - un[i] * dt / dx *(un[i] - un[i-1]) + nu * dt / dx**2 *\
                (un[i+1] - 2 * un[i] + un[i-1])
    u[0] = un[0] - un[0] * dt / dx * (un[0] - un[-2]) + nu * dt / dx**2 *\
                (un[1] - 2 * un[0] + un[-2])
    u[-1] = u[0]

u_analytical = numpy.asarray([ufunc(nt * dt, xi, nu) for xi in x])
```

```python
pyplot.figure(figsize=(11, 7), dpi=100)
pyplot.plot(x,u, marker='o', lw=2, label='Computational')
pyplot.plot(x, u_analytical, label='Analytical')
# pyplot.xlim([0, 2 * numpy.pi])
# pyplot.ylim([0, 10])
pyplot.legend();
```

***

What next?
----

The subsequent steps, from 5 to 12, will be in two dimensions. But it is easy to extend the 1D finite-difference formulas to the partial derivatives in 2D or 3D. Just apply the definition — a partial derivative with respect to $x$ is the variation in the $x$ direction *while keeping $y$ constant*.

Before moving on to [Step 5](./07_Step_5.ipynb), make sure you have completed your own code for steps 1 through 4 and you have experimented with the parameters and thought about what is happening. Also, we recommend that you take a slight break to learn about [array operations with NumPy](./06_Array_Operations_with_NumPy.ipynb).

```python
from IPython.core.display import HTML
def css_styling():
    styles = open("../styles/custom.css", "r").read()
    return HTML(styles)
css_styling()
```


# Dynamical System Approximation

In this notebook we implement for experimental purposes the Salsa algorithm from Kraemer et. al. (Stable ALS Approximation in the TT-Format for Rank adaptive Tensor Completion.

We use a mixture from Xerus and Numpy to deal with Tensors.

Again, we try to learn  functional correlations based on given snapshots. The data is created through the following ODE:
\begin{align}
\frac{d^2}{dt^2} x_i = (x_{i+1} - 2x_i + x_{i-1}) + 0.7((x_{i+1} - x_i)^3 - (x_i-x_{i-1})^3)
\end{align}

```python
import numpy as np
import xerus

import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
import time as _time
from itertools import chain
import helpers as hp
import pandas as pd

```

## Salsa implementation
Now we can try to recover the exact solution with the SALS algorithm.

### Intialization
We intialize Salsa with a random rank one Tensor and kmin additional ranks.

```python
def initialize(p,noo,kmin):
    dim = [p for i in range(0,noo)]
    dim.append(noo)
    ranks = [kmin + 1 for i in range(0,noo)]
    X = xerus.TTTensor.random(dim,ranks)
    X.move_core(0)
    X = 0.0*X
    omega = 0.5
    r1 = 1
    r2 = 1
    maxrank1 = []
    maxrank2 = []
    for i in range(len(ranks)):
        r1 = r1*dim[i]
        r2 = r2*dim[noo-i]
        maxrank1.append(r1)
        maxrank2.append(r2)
    maxrank2.reverse()
    maxranks =np.minimum(maxrank1,maxrank2)
    return X, maxranks
```

### Perform one SALSA sweep

```python
# build exact solution
def exact(noo,p):
    beta = 0.7
    Solution = hp.construct_exact_fermit_pasta_single_TT(noo,p,beta) #build in monomial basis
    #transform to legendre polynomials
    M = np.zeros([4,4])
    M[0,0] = 1   #1
    M[1,1] = 1   #1
    M[2,2] = 1.5 #1.5
    M[3,3] = 2.5 #2.5
    M[0,2] = -0.5 #-0.5
    M[1,3] = -1.5 #-1.5
    t = xerus.Tensor.from_ndarray(np.linalg.inv(M))
    a1,a2,a3,a4,b1,b2,b3,b4 = xerus.indices(8)
    for eq in range(noo):
        tmp = Solution.get_component(eq)
        tmp(a1,a2,a3) <<  tmp(a1,b2,a3)* t(a2,b2)
        Solution.set_component(eq,tmp)
    return Solution

```

```python
#Master iteration
#data_noo_nos = [(6,300),(6,400),(6,500),(6,600),(6,700),(12,1400), \
#            (12,1700),(12,2000),(12,2500),(12,3000),(12,3500),(12,4000)] #pairs used in simulations in the paper
#                                                       uncomment to simulate but is computational intensive

data_noo_nos = [(8,2000)] #specify pairs to simulate for
runs = 1 #specify number of runs for each pair (10 in the paper)
#runs = 10
max_iter = 60 # specify number of sweeps
output = 'data.csv' # specify name of output file

# build data structure to store solution
tuples = []
for data in data_noo_nos:
    noo = data[0]
    nos = data[1]
    for r in range(0,runs):
        tuples.append((noo,nos,r))
index = pd.MultiIndex.from_tuples(tuples, names=['d', 'm','runs'])
df = pd.DataFrame(np.zeros([len(tuples),max_iter]), index=index)
print(len(index))
print(data_noo_nos)
```

```python
#loop over all pairs of samples, calls hp.run_salsa for the solution
kmin = 2

psi = hp.basis(0) # get basis functions, Legendre
p = len(psi)
for data in data_noo_nos:
    noo = data[0]
    nos = data[1]
    print( "(noo,nos) = (" + str(noo) +',' + str(nos) + ')' )
    Solution = exact(noo,p)
    print("Solution frob_norm: " +str(Solution.frob_norm()))
    for r in range(runs):
        [x, y] = hp.fermi_pasta_ulam(noo, nos)
        Alist = hp.build_data_tensor_list2(noo,x,nos,psi,p)
        print(Alist[0].dimensions[0])
        Y = xerus.Tensor.from_ndarray(y)
        X, maxranks = initialize(p,noo, kmin)
        errors = hp.run_salsa(X,noo,Alist,nos,Solution,Y,max_iter,maxranks, kmin)
        for i in range(len(errors)):
            df[i].loc[(noo,nos,r)] = errors[i]
        print("Run: " +str(r) + " finished result = " + str(errors))
        df.to_csv(output)
```

```python

```

```python

```


# The Discrete Fourier Transform

*This Jupyter notebook is part of a [collection of notebooks](../index.ipynb) in the bachelors module Signals and Systems, Comunications Engineering, Universität Rostock. Please direct questions and suggestions to [Sascha.Spors@uni-rostock.de](mailto:Sascha.Spors@uni-rostock.de).*

## Properties

The discrete Fourier transform (DFT) has a number of specific properties that are reviewed in the following.

### Invertibility

The discrete signal $x[k]$ can be recovered from its DFT $X[\mu] = \text{DFT}_N \{ x[k] \}$ by an inverse DFT (IDFT)

\begin{equation}
x[k] = \text{IDFT}_N \left\{ \text{DFT}_N \{ x[k] \} \right\}
\end{equation}

for $k=0,1, \dots, N-1$. This can be proven by introducing the [definition of the DFT](definition.ipynb) into the definition of the IDFT

\begin{align}
x[k] &= \frac{1}{N} \sum_{\mu = 0}^{N-1} \left( \sum_{n = 0}^{N-1} x[n] w_N^{\mu n} \right) w_N^{-\mu k} \\
&= \frac{1}{N} \sum_{n = 0}^{N-1} x[n] \sum_{\mu = 0}^{N-1} w_N^{\mu n} w_N^{- \mu k} \\
&= x[k]
\end{align}

where $w_N = e^{- j \frac{2 \pi}{N}}$. The last equality follows from the DFT of the shifted Dirac impulse (orthogonality of the complex exponentials)

\begin{equation}
\text{DFT}_N \{ \delta[k-n] \} = w_N^{\mu n}
\end{equation}

and its sifting property.

**Example**

The invertibility of the DFT is illustrated at the example of the [rectangular signal](../discrete_signals/standard_signals.ipynb#Rectangular-Signal) $x[k] = \text{rect}_M[k]$. The signal $x[k]$, its magnitude spectrum $|X[\mu]|$ as well as the IDFT of the spectrum $\text{IDFT} \{ X[\mu] \}$ are plotted. Note that the IDFT is not exactly real valued due to numerical effects.

```python
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from scipy.linalg import dft

def rect(k, N):
    return np.where((0 <= k) & (k < N), 1.0, 0.0)

N = 16
M = 8

F = dft(N)
IF = 1/N*np.conjugate(np.transpose(F))
k = np.arange(N)
x = rect(k, M)
X = np.matmul(F, x)
xr = np.matmul(IF, X)

plt.figure(figsize=(10,3))
plt.subplot(1, 3, 1)
plt.stem(x)
plt.xlabel('$k$')
plt.ylabel('$x[k]$')
plt.ylim([-.1, 1.1])

plt.subplot(1, 3, 2)
plt.stem(abs(X))
plt.xlabel('$\mu$')
plt.ylabel('$|X[\mu]|$')

plt.subplot(1, 3, 3)
plt.stem(np.real(xr))
plt.xlabel('$k$')
plt.ylabel(r'$\mathrm{IDFT}_N {X[\mu]}$')
plt.ylim([-.1, 1.1])
plt.tight_layout()
```

### Linearity

The DFT is a linear operation. For two signals $x_1[k]$ and $x_2[k]$ with transforms $X_1[\mu] = \text{DFT}_N \{ x_1[k] \}$ and $X_2[\mu] = \text{DFT}_N \{ x_2[k] \}$ the following holds

\begin{equation}
\text{DFT}_N \{ A \cdot x_1[k] + B \cdot x_2[k] \} = A \cdot X_1[\mu] + B \cdot X_2[\mu]
\end{equation}

with $A, B \in \mathbb{C}$. The DFT of a weighted superposition of discrete signals is equal to the weighted superposition of the individual DFTs. This property is useful to derive the DFT of signals that can be expressed as superposition of other signals for which the DFT is known or can be calculated easier. Linearity holds also for the inverse DFT.

#### Transformation of the cosine and sine signal

The DTFT of $\cos(\Omega_0 k)$ and $\sin(\Omega_0 k)$ is derived by expressing both as harmonic exponential signals using [Euler's formula](https://en.wikipedia.org/wiki/Euler's_formula)

\begin{align}
\cos(\Omega_0 k) &= \frac{1}{2} \left(  e^{-j \Omega_0 k} + e^{j \Omega_0 k} \right) \\
\sin(\Omega_0 k) &= \frac{j}{2} \left( e^{-j \Omega_0 k} - e^{j \Omega_0 k}  \right)
\end{align}

together with the $\text{DFT}_N \{ e^{j \Omega_0 k} \} = \frac{1 - e^{j (\Omega_0 - \mu \frac{2 \pi}{N}) N}}{1 - e^{j (\Omega_0 - \mu \frac{2 \pi}{N})}}$ of the [complex exponential signal](definition.ipynb#Transformation-of-the-Exponential-Signal) yields

\begin{align}
\text{DFT}_N \{ \cos(\Omega_0 k) \} &= \frac{1}{2} \left(
\frac{1 - e^{- j (\Omega_0 + \mu \frac{2 \pi}{N}) N}}{1 - e^{-j (\Omega_0 + \mu \frac{2 \pi}{N})}} +
\frac{1 - e^{j (\Omega_0 - \mu \frac{2 \pi}{N}) N}}{1 - e^{j (\Omega_0 - \mu \frac{2 \pi}{N})}}
\right) \\
\text{DFT}_N \{ \sin(\Omega_0 k) \} &= \frac{j}{2} \left(
\frac{1 - e^{- j (\Omega_0 + \mu \frac{2 \pi}{N}) N}}{1 - e^{-j (\Omega_0 + \mu \frac{2 \pi}{N})}} -
\frac{1 - e^{j (\Omega_0 - \mu \frac{2 \pi}{N}) N}}{1 - e^{j (\Omega_0 - \mu \frac{2 \pi}{N})}}
\right)
\end{align}

for the special case of a periodic cosine/sine signal with $\Omega_0 = M \frac{2 \pi}{N}$, $M \in \mathbb{Z}$ the DFTs simplify to

\begin{align}
\text{DFT}_N \{ \cos(\Omega_0 k) \} &= \frac{N}{2} \left( \delta[\mu + M - N] + \delta[\mu - M] \right) \\
\text{DFT}_N \{ \sin(\Omega_0 k) \} &= \frac{j N}{2} \left( \delta[\mu + M - N] - \delta[\mu - M] \right)
\end{align}

**Example**

The $\text{DFT}_N \{ \cos(\Omega_0 k) \}$ of a cosine signal is computed by numerical evaluation of the definition of the DFT. The magnitude spectrum $|X[\mu]|$ is plotted for illustration.

```python
M = 3.3
N = 16

W0 = 3.3 * 2*np.pi/N
x = np.cos(W0*k)
F = dft(N)
X = np.matmul(F, x)

plt.stem(abs(X))
plt.xlabel('$\mu$')
plt.ylabel(r'$|X[\mu]|$');
```

**Exercise**

* Rerun the example with different normalized frequencies $\Omega_0 = M \frac{2 \pi}{N}$ resulting in periodic or aperiodic cosine signals.

### Symmetries

In order to investigate the symmetries of the DFT $X[\mu] = \text{DFT}_N \{ x[k] \}$ of a signal $x[k]$, first the even and odd part of a discrete signal of finite length is introduced. Based on this, the symmetries of the DFT of a real valued signal $x[k] \in \mathbb{R}$ are derived. The results are then generalized to complex signals $x[k] \in \mathbb{C}$.

#### Even and odd part of a finite-length signal

The symmetry relations of [even and odd functions](https://en.wikipedia.org/wiki/Even_and_odd_functions) are typically formulated in terms of the behavior of a function when its argument changes the sign. These definitions cannot be applied straightforward to causal discrete signals $x[k]$ of finite length $N$, since $x[k] = 0$ for $k<0$. An alternative definition for the symmetry relations of even and odd signals of finite length is based on the periodic continuation $\tilde{x}[k]$ of the finite-length signal $x[k]$. It is given as

\begin{equation}
\tilde{x}[k] = \sum_{\nu = -\infty}^{\infty} x[k - \nu N]
\end{equation}

Using the periodic continuation, a causal finite length signal $x_\text{e}[k]$ with even symmetry is defined by

\begin{equation}
\tilde{x}_\text{e}[k] = \tilde{x}_\text{e}[-k]
\end{equation}

and a causal finite length signal $x_\text{o}[k]$ with odd symmetry by

\begin{equation}
\tilde{x}_\text{o}[k] = - \tilde{x}_\text{o}[-k]
\end{equation}

Using these definitions signal $x[k]$ can be decomposed into its even and odd part

\begin{align}
x_\text{e}[k] &= \frac{1}{2} \left( \tilde{x}[k] + \tilde{x}[-k] \right) \\
x_\text{o}[k] &= \frac{1}{2} \left( \tilde{x}[k] - \tilde{x}[-k] \right)
\end{align}

with $x[k] = x_\text{e}[k] + x_\text{o}[k]$. It follows from these relations that $x_\text{e}[0] = x[0]$ and $x_\text{o}[0] = 0$.

**Example**

The decomposition of the signal $x[k] = \text{rect}_8[k]$ of length $N$ into its even and odd part is illustrated. Note, the reversal of the periodic continuation $\tilde{x}[-k]$ is realized in `Python` by reversing the order of the vector containing the values of the signal $x[k]$ followed by a circular shift by one.

```python
N = 16
k = np.arange(N)
x = rect(k, 8)
xe = 1/2 * (x + np.roll(x[::-1], 1))
xo = 1/2 * (x - np.roll(x[::-1], 1))

plt.figure(figsize=(10,3))
plt.subplot(1, 3, 1)
plt.stem(x)
plt.xlabel('$k$')
plt.ylabel('$x[k]$')
plt.ylim([-1.1, 1.1])

plt.subplot(1, 3, 2)
plt.stem(xe)
plt.xlabel('$k$')
plt.ylabel('$x_\mathrm{e}[k]$')
plt.ylim([-1.1, 1.1])

plt.subplot(1, 3, 3)
plt.stem(xo)
plt.xlabel('$k$')
plt.ylabel('$x_\mathrm{o}[k]$')
plt.ylim([-1.1, 1.1])
plt.tight_layout()
```

**Exercise**

* Examine the symmetries of the periodic cosine $x[k] = \cos(M \frac{2 \pi}{N} k)$ and sine $x[k] = \sin(M \frac{2 \pi}{N} k)$ signals for $M \in 0,1, \dots, N-1$.

#### Real valued signals

Decomposing a real valued signal $x[k] \in \mathbb{R}$ into its even and odd part $x[k] = x_\text{e}[k] + x_\text{o}[k]$ and introducing these into the definition of the DFT yields

\begin{align}
X[\mu] &= \sum_{k = 0}^{N-1} \left( x_\text{e}[k] + x_\text{o}[k] \right) e^{-j \mu \frac{2 \pi}{N} k} \\
&= \sum_{k = 0}^{N-1} \left( x_\text{e}[k] + x_\text{o}[k] \right) \cdot \left( \cos(\mu \frac{2 \pi}{N} k) - j \sin(\mu \frac{2 \pi}{N} k) \right) \\
&= \underbrace{\sum_{k = 0}^{N-1} x_\text{e}[k] \cos(\mu \frac{2 \pi}{N} k)}_{X_\text{e}[\mu]} +
j \underbrace{\sum_{k = 0}^{N-1} - x_\text{o}[k] \sin(\mu \frac{2 \pi}{N} k) }_{X_\text{o}[\mu]}
\end{align}

For the last equality the fact was exploited that the periodic cosine and sine show even and odd symmetry, respectively and that the summation is zero for odd series. In order to conclude on the symmetry of $X[\mu]$, the behavior of its periodic continuation $\tilde{X}[\mu]$ for a reverse of the sign of $\mu$ has to be investigated. Due to the even and odd symmetry of $\cos(\mu \frac{2 \pi}{N} k)$ and $\sin(\mu \frac{2 \pi}{N} k)$, it follows that the DFT of the

* even part $x_\text{e}[k]$ is real valued with even symmetry $\tilde{X}_\text{e}[\mu] = \tilde{X}_\text{e}[-\mu]$
* odd part $x_\text{o}[k]$ is imaginary with odd symmetry $\tilde{X}_\text{o}[\mu] = - \tilde{X}_\text{o}[-\mu]$

where $\tilde{X}_\text{e}[\mu]$ and $\tilde{X}_\text{o}[\mu]$ denote the periodic continuation of the even and odd part of $X[\mu]$. Combining the results, it can be concluded that the DFT $X[\mu]$ of a real-valued signal $x[k] \in \mathbb{R}$ shows complex conjugate symmetry

\begin{equation}
\tilde{X}[\mu] = \tilde{X}^*[-\mu]
\end{equation}

#### Complex signals

By following the same procedure as above for an imaginary signal, the symmetries of the DFT of the even and odd part of an imaginary signal can be derived. The results can be combined, by decomposing a complex signal $x[k] \in \mathbb{C}$ and its DFT into its even and odd part for both the real and imaginary part. This results in the following symmetry relations

The transformation symbols $\circ \!\! - \!\! \bullet$ illustrate which part of the signal $x[k]$ is related to which part of its spectrum $X[\mu]$. For instance, the odd part of the real part $\Re \{ x_\text{o} [k] \}$ results in an imaginary spectrum with odd symmetry $\Im \{ X_\text{o} [\mu] \}$. This holds for instance for the spectrum of the periodic sine function derived above.

**Copyright**

The notebooks are provided as [Open Educational Resource](https://de.wikipedia.org/wiki/Open_Educational_Resources). Feel free to use the notebooks for your own educational purposes. The text is licensed under [Creative Commons Attribution 4.0](https://creativecommons.org/licenses/by/4.0/), the code of the IPython examples under the [MIT license](https://opensource.org/licenses/MIT). Please attribute the work as follows: *Lecture Notes on Signals and Systems* by Sascha Spors.


```python
import math
import json
import sympy as sp
from sympy.utilities.lambdify import lambdify
import numpy as np
import matplotlib.pyplot as plt

import openrtdynamics2.lang as dy
import openrtdynamics2.py_execute as dyexe
from openrtdynamics2.ORTDtoNumpy import ORTDtoNumpy

from vehicle_lib.vehicle_lib import *
import vehicle_lib.path_transformations as pt
import vehicle_lib.motion_primitives as mp
```

```python
Ts = 0.01
```

```python
# load track data
with open("track_data/simple_track.json", "r") as read_file:
    track_data = json.load(read_file)

```

# Under construction...

```python

```

```python

```

```python

```

# Kinematic bicycle model

The dynamic system equations are given by

$
\dot X
=
f(x,y,\psi)
=
\begin{pmatrix}
  \dot x \\
  \dot y \\
  \dot \psi
\end{pmatrix}
=
\begin{pmatrix}
  v \cos( \delta + \psi) \\
  v \sin( \delta + \psi) \\
  v / l_r \sin( \delta ), \\
\end{pmatrix}
$

with the state vector

$ X = [ x, y, \psi ]^T $.

Herein, $x$ and $y$ denote the coordinates of the vehicle front axle in cartesian space and $\psi$ the vehicle body orientation angle. The system inputs are the steering angle $\delta$ and the vehicle velocity $v$. Finally, the parameter $l_r$ denotes the wheelbase, which is the length in-between front and rear axle.

```python
x, y, v, delta, psi, l_r, T_s, n = sp.symbols('x y v delta psi l_r T_s n')

x_dot   = v * sp.cos( delta + psi )
y_dot   = v * sp.sin( delta + psi )
psi_dot = v / l_r * sp.sin( delta )

# system function f
f = sp.Matrix([ x_dot, y_dot, psi_dot ])

# state vector
X_bic = sp.Matrix( [ x, y, psi ])

# input vector
U_bic = sp.Matrix( [ delta, v ])
```

```python
f
```

$\displaystyle \left[\begin{matrix}v \cos{\left(\delta + \psi \right)}\\v \sin{\left(\delta + \psi \right)}\\\frac{v \sin{\left(\delta \right)}}{l_{r}}\end{matrix}\right]$

# Discretization of the continunous model

By applying Euler-forward discretization

$ {X}[k+1] = \underbrace{ {X}[k] + T_s  \dot{X} }_{f_{dscr}} $,

the continuous system is time-discretized with the sampling time $T_s$ yielding the discrete system funtion $f_{dscr}$.

```python
# apply Euler forward
f_dscr = sp.Matrix( [x,y,psi]) + T_s * f
```

```python
f_dscr
```

$\displaystyle \left[\begin{matrix}T_{s} v \cos{\left(\delta + \psi \right)} + x\\T_{s} v \sin{\left(\delta + \psi \right)} + y\\\frac{T_{s} v \sin{\left(\delta \right)}}{l_{r}} + \psi\end{matrix}\right]$

# Analytically compute the Jacobian matrices

A linearization of the non-linear system function around a dynamic set point is calculated by deriving the jacobian matrices w.r.t. the state vector $X$ and each system input $\delta$ and $v$:

continuous case
$
  A = \frac{ \partial f }{ \partial X},
  \qquad
  B = \frac{ \partial f }{ \partial [ \delta, v ]^T },
$

discrete-time case
$
  A_{dscr} = \frac{ \partial f_{dscr} }{ \partial X},
  \qquad
  B_{dscr} = \frac{ \partial f_{dscr} }{ \partial [ \delta, v ]^T },
$

```python
# continuous system matrices
A = f.jacobian(X_bic)
B = f.jacobian(U_bic)

# discrete system matrices
A_dscr = f_dscr.jacobian(X_bic)
B_dscr = f_dscr.jacobian(U_bic)
```

```python
A_dscr
```

$\displaystyle \left[\begin{matrix}1 & 0 & - T_{s} v \sin{\left(\delta + \psi \right)}\\0 & 1 & T_{s} v \cos{\left(\delta + \psi \right)}\\0 & 0 & 1\end{matrix}\right]$

```python
B_dscr
```

$\displaystyle \left[\begin{matrix}- T_{s} v \sin{\left(\delta + \psi \right)} & T_{s} \cos{\left(\delta + \psi \right)}\\T_{s} v \cos{\left(\delta + \psi \right)} & T_{s} \sin{\left(\delta + \psi \right)}\\\frac{T_{s} v \cos{\left(\delta \right)}}{l_{r}} & \frac{T_{s} \sin{\left(\delta \right)}}{l_{r}}\end{matrix}\right]$

# Create functions that generate the matrices A, B, and the system function f

Create python functions with which the symbolically dervied matrices and system function can be evaluated.

```python
variables = (T_s,l_r, x,y,psi,v,delta)

array2mat = [{'ImmutableDenseMatrix': np.matrix}, 'numpy']

A_dscr_fn = lambdify( variables, A_dscr, modules=array2mat)
B_dscr_fn = lambdify( variables, B_dscr, modules=array2mat)
f_dscr_fn = lambdify( variables, f_dscr, modules=array2mat)

```

```python
A_dscr_fn(0.01, 3.0, 0.1,0.2,0.4,10,0.1)
```

    matrix([[ 1.        ,  0.        , -0.04794255],
            [ 0.        ,  1.        ,  0.08775826],
            [ 0.        ,  0.        ,  1.        ]])

```python
B_dscr_fn(0.01, 3.0, 0.1,0.2,0.4,10,0.1)
```

    matrix([[-0.04794255,  0.00877583],
            [ 0.08775826,  0.00479426],
            [ 0.03316681,  0.00033278]])

```python
f_dscr_fn(0.01, 3.0, 0.1,0.2,0.4,10,0.1)
```

    matrix([[0.18775826],
            [0.24794255],
            [0.40332778]])

```python

```

```python

```

# Run a simulation to generate test data

Set-up a simulation of a vehicle (bicycle model). The vehicle is controlled to follow a given path. In addition, an intended lateral distance $\Delta l$ is modulated by applying a pre-defined profile to the reference $\Delta l_r$.

```python
path_transform = pt.LateralPathTransformer(wheelbase=3.0)
```

    compiling system store_input_data (level 1)...
    compiling system tracker_loop (level 3)...
    compiling system Subsystem1000 (level 2)...
    compiling system controller (level 2)...
    compiling system simulation_model (level 2)...
    compiling system process_data (level 1)...
    compiling system simulation (level 0)...
    Generated code will be written to generated/tmp1 .

```python
lateral_profile = mp.generate_lateral_profile_1(Ts=Ts, T_phase1=1, T_phase2=3, T_phase3=1, T_phase4=3, T_phase5=1)

mp.plot_lateral_profile(lateral_profile)
```

```python
output_path = path_transform.run_lateral_path_transformer( track_data, lateral_profile )

plt.figure(figsize=(8,4), dpi=100)
plt.plot( output_path['X'], output_path['Y']+0.1 )
plt.plot( track_data['X'], track_data['Y'] )
plt.legend(['manipulated (output) path', 'original (input) path'])
plt.grid()
plt.xlabel('x [m]')
plt.ylabel('y [m]')
plt.show()
```

```python
output_path.keys()
```

    dict_keys(['D', 'X', 'Y', 'PSI', 'K', 'D_STAR', 'V_DELTA_DOT', 'V_DELTA', 'V_PSI_DOT', 'V_PSI', 'V_VELOCITY'])

# Add noise to the model (sensing noise)

Simulate measurement noise which is, e.g., introduced by GPS.

```python
# X/Y positioning noise (normal distribution)
N = len( output_path['X'] )
eta_x = np.random.normal(0, 0.1, N) * 1
eta_y = np.random.normal(0, 0.1, N) * 1

x_meas       = eta_x + output_path['X']
y_meas       = eta_y + output_path['Y']
psi_meas     = output_path['V_PSI']
psi_dot_meas = output_path['V_PSI_DOT']
v_meas       = output_path['V_VELOCITY']

plt.figure(figsize=(12,8), dpi=70)
plt.plot(x_meas, y_meas)
plt.plot(track_data['X'], track_data['Y'])
plt.show()

plt.figure(figsize=(12,8), dpi=70)
plt.plot(psi_meas)
plt.show()
```

# Extended Kalman filter

The extended Kalman filter is applied to the linearized model descibed by the matrices $A_{dscr}$ and $B_{dscr}$ and given the system function $f_{dscr}$. The simulated data serves as measured data and is the input to the filter.

```python
f_dscr
```

$\displaystyle \left[\begin{matrix}T_{s} v \cos{\left(\delta + \psi \right)} + x\\T_{s} v \sin{\left(\delta + \psi \right)} + y\\\frac{T_{s} v \sin{\left(\delta \right)}}{l_{r}} + \psi\end{matrix}\right]$

```python
A_dscr
```

$\displaystyle \left[\begin{matrix}1 & 0 & - T_{s} v \sin{\left(\delta + \psi \right)}\\0 & 1 & T_{s} v \cos{\left(\delta + \psi \right)}\\0 & 0 & 1\end{matrix}\right]$

```python
B_dscr
```

$\displaystyle \left[\begin{matrix}- T_{s} v \sin{\left(\delta + \psi \right)} & T_{s} \cos{\left(\delta + \psi \right)}\\T_{s} v \cos{\left(\delta + \psi \right)} & T_{s} \sin{\left(\delta + \psi \right)}\\\frac{T_{s} v \cos{\left(\delta \right)}}{l_{r}} & \frac{T_{s} \sin{\left(\delta \right)}}{l_{r}}\end{matrix}\right]$

The implemented filter in form of a loop

```python
l_r = 3.0

# allocate space to store the filter results
results = {'delta' : np.zeros(N), 'x' : np.zeros(N), 'y' : np.zeros(N), 'psi' : np.zeros(N) }

# the guess/estimate of the initial states
X = np.matrix([ [0.5], [0.5], [0.1] ])

P = np.matrix([  [0.1, 0,   0     ],
                 [0,   0.1, 0     ],
                 [0,   0,   0.1   ]  ])

# covariance of the noise w addtitive to the states
Q = 0.00001*np.matrix([  [1, 0, 0 ],
                         [0, 1, 0 ],
                         [0, 0, 1 ]  ])

# covariance of the noise v in the measured system output signal
R = np.matrix([  [0.1, 0   ],
                 [0  , 0.1 ]  ])

for i in range(0,N):

    # measured input signals
    v       = v_meas[i]
    x       = x_meas[i]
    y       = y_meas[i]
    psi_dot = psi_dot_meas[i]

    # compute steering angle by the inverse for the vehicle orientation change
    delta = math.asin( psi_dot * l_r / v )

    # system output vector (x, y)
    z = np.matrix([ [x], [y] ])

    # pridiction step using the non-linear model (f_dscr)
    # x(k-1|k-1) --> x(k|k-1)

    X[0] = X[0] + Ts * ( v * math.cos( X[2] + delta ) )
    X[1] = X[1] + Ts * ( v * math.sin( X[2] + delta ) )
    X[2] = X[2] + Ts * ( v / l_r * math.sin(delta) )

    # optionally use the auto-generated python function for evaluation
    # X = f_dscr_fn( Ts, l_r, float(X[0]), float(X[1]), float(X[2]), v, delta )

    # evaluate jacobi matrices A_dscr and B_dscr
    F = np.matrix([  [1, 0, -Ts*v*math.sin(delta+X[2])  ],
                     [0, 1,  Ts*v*math.cos(delta+X[2])  ],
                     [0, 0, 1                           ]   ])

    # optionally use the auto-generated python function for evaluation
    # F = A_dscr_fn( Ts, l_r, float(X[0]), float(X[1]), float(X[2]), v, delta )

    B = np.matrix([  [-Ts*v*math.sin(delta+X[2]), Ts*math.cos(delta+X[2])      ],
                     [ Ts*v*math.cos(delta+X[2]), Ts*math.sin(delta+X[2])      ],
                     [Ts*v/l_r * math.cos(delta), Ts/l_r * math.sin(delta)     ]   ])

    # optionally use the auto-generated python function for evaluation
    # B = B_dscr_fn( Ts, l_r, float(X[0]), float(X[1]), float(X[2]), v, delta )

    # the system output matrix: returns X and Y when multiplied with the state vector X
    # which are compared to the measurements
    H = np.matrix([  [1,0,0],
                     [0,1,0] ])

    # prdicted state covariance P(k|k-1)
    P = F*P*F.transpose() + Q

    # estimation output residual vector
    e = z - H*X

    # Kalman gain
    S = H*P*H.transpose() + R
    K = P*H.transpose() * np.linalg.inv( S )

    # post priori state X(k|k)
    X = X + K*e

    # post priori covariance
    P = (np.eye(3) - K*H) * P

    # store results
    results['delta'][i] = delta
    results['x'][i] = X[0]
    results['y'][i] = X[1]
    results['psi'][i] = X[2]

# show results
plt.figure(figsize=(12,8), dpi=79)
#plt.plot(x_meas, y_meas, '+')
plt.plot(output_path['X'], output_path['Y'], 'g')
plt.plot(results['x'], results['y'], 'r')
plt.show()

plt.figure(figsize=(12,8), dpi=70)
plt.plot(results['psi'])
plt.plot(output_path['V_PSI'], 'g')
plt.show()
```

```python

```