# To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %%
from IPython import get_ipython

# %% [markdown]
# #CS228 Python Tutorial
# %% [markdown]
# Adapted by [Volodymyr Kuleshov](http://web.stanford.edu/~kuleshov/) and [Isaac Caswell](https://symsys.stanford.edu/viewing/symsysaffiliate/21335) from the `CS231n` Python tutorial by Justin Johnson (http://cs231n.github.io/python-numpy-tutorial/).
# %% [markdown]
# ##Introduction
# %% [markdown]
# Python is a great general-purpose programming language on its own, but with the help of a few popular libraries (numpy, scipy, matplotlib) it becomes a powerful environment for scientific computing.
#
# We expect that many of you will have some experience with Python and numpy; for the rest of you, this section will serve as a quick crash course both on the Python programming language and on the use of Python for scientific computing.
#
# Some of you may have previous knowledge in Matlab, in which case we also recommend the numpy for Matlab users page (https://docs.scipy.org/doc/numpy-dev/user/numpy-for-matlab-users.html).
# %% [markdown]
# In this tutorial, we will cover:
#
# * Basic Python: Basic data types (Containers, Lists, Dictionaries, Sets, Tuples), Functions, Classes
# * Numpy: Arrays, Array indexing, Datatypes, Array math, Broadcasting
# * Matplotlib: Plotting, Subplots, Images
# * IPython: Creating notebooks, Typical workflows
# %% [markdown]
# ##Basics of Python
# %% [markdown]
# Python is a high-level, dynamically typed multiparadigm programming language. Python code is often said to be almost like pseudocode, since it allows you to express very powerful ideas in very few lines of code while being very readable. As an example, here is an implementation of the classic quicksort algorithm in Python:

# %%
def quicksort(arr):
    if len(arr) <= 1:
        return arr
    pivot = arr[len(arr) // 2]
    left = [x for x in arr if x < pivot]
    middle = [x for x in arr if x == pivot]
    right = [x for x in arr if x > pivot]
    return quicksort(left) + middle + quicksort(right)

print(quicksort([3,6,8,10,1,2,1]) )

# %% [markdown]
# ###Python versions
# %% [markdown]
# There are currently two different supported versions of Python, 2.7 and 3.4. Somewhat confusingly, Python 3.0 introduced many backwards-incompatible changes to the language, so code written for 2.7 may not work under 3.4 and vice versa. For this class all code will use Python 2.7.
#
# You can check your Python version at the command line by running `python --version`.
# %% [markdown]
# ###Basic data types
# %% [markdown]
# ####Numbers
# %% [markdown]
# Integers and floats work as you would expect from other languages:

# %%
x = 3
print(x, type(x))

# %%
print(x + 1)   # Addition;
print(x - 1)   # Subtraction;
print(x * 2)   # Multiplication;
print(x ** 2)  # Exponentiation;

# %%
x += 1
print(x)  # Prints "4"
x *= 2
print(x)  # Prints "8"

# %%
y = 2.5
print(type(y)) # Prints "<type 'float'>"
print(y, y + 1, y * 2, y ** 2) # Prints "2.5 3.5 5.0 6.25"

# %% [markdown]
# Note that unlike many languages, Python does not have unary increment (x++) or decrement (x--) operators.
#
# Python also has built-in types for long integers and complex numbers; you can find all of the details in the [documentation](https://docs.python.org/2/library/stdtypes.html#numeric-types-int-float-long-complex).
# %% [markdown]
# ####Booleans
# %% [markdown]
# Python implements all of the usual operators for Boolean logic, but uses English words rather than symbols (`&&`, `||`, etc.):

# %%
t, f = True, False
print(type(t)) # Prints "<type 'bool'>"

# %% [markdown]
# Now we let's look at the operations:

# %%
print(t and f) # Logical AND;
print(t or f)  # Logical OR;
print(not t)   # Logical NOT;
print(t != f)  # Logical XOR;

# %% [markdown]
# ####Strings

# %%
hello = 'hello'   # String literals can use single quotes
world = "world"   # or double quotes; it does not matter.
print(hello, len(hello))

# %%
hw = hello + ' ' + world  # String concatenation
print(hw)                 # prints "hello world"

# %%
hw12 = '%s %s %d' % (hello, world, 12)  # sprintf style string formatting
print(hw12)                             # prints "hello world 12"

# %% [markdown]
# String objects have a bunch of useful methods; for example:

# %%
s = "hello"
print(s.capitalize())           # Capitalize a string; prints "Hello"
print(s.upper())                # Convert a string to uppercase; prints "HELLO"
print(s.rjust(7))               # Right-justify a string, padding with spaces; prints "  hello"
print(s.center(7))              # Center a string, padding with spaces; prints " hello "
print(s.replace('l', '(ell)'))  # Replace all instances of one substring with another;
                                # prints "he(ell)(ell)o"
print('  world '.strip())       # Strip leading and trailing whitespace; prints "world"

# %% [markdown]
# You can find a list of all string methods in the [documentation](https://docs.python.org/2/library/stdtypes.html#string-methods).
# %% [markdown]
# ###Containers
# %% [markdown]
# Python includes several built-in container types: lists, dictionaries, sets, and tuples.
# %% [markdown]
# ####Lists
# %% [markdown]
# A list is the Python equivalent of an array, but is resizeable and can contain elements of different types:

# %%
xs = [3, 1, 2]   # Create a list
print(xs, xs[2])
print(xs[-1])     # Negative indices count from the end of the list; prints "2"

# %%
xs[2] = 'foo'    # Lists can contain elements of different types
print(xs)

# %%
xs.append('bar') # Add a new element to the end of the list
print(xs)

# %%
x = xs.pop()     # Remove and return the last element of the list
print(x, xs)

# %% [markdown]
# As usual, you can find all the gory details about lists in the [documentation](https://docs.python.org/2/tutorial/datastructures.html#more-on-lists).
# %% [markdown]
# ####Slicing
# %% [markdown]
# In addition to accessing list elements one at a time, Python provides concise syntax to access sublists; this is known as slicing:

# %%
nums = list(range(5))    # range is a built-in function that creates a list of integers
print(nums)         # Prints "[0, 1, 2, 3, 4]"
print(nums[2:4])    # Get a slice from index 2 to 4 (exclusive); prints "[2, 3]"
print(nums[2:])     # Get a slice from index 2 to the end; prints "[2, 3, 4]"
print(nums[:2])     # Get a slice from the start to index 2 (exclusive); prints "[0, 1]"
print(nums[:])      # Get a slice of the whole list; prints ["0, 1, 2, 3, 4]"
print(nums[:-1])    # Slice indices can be negative; prints ["0, 1, 2, 3]"
nums[2:4] = [8, 9]  # Assign a new sublist to a slice
print (nums)        # Prints "[0, 1, 8, 9, 4]"

# %% [markdown]
# ####Loops
# %% [markdown]
# You can loop over the elements of a list like this:

# %%
animals = ['cat', 'dog', 'monkey']
for animal in animals:
    print(animal)

# %% [markdown]
# If you want access to the index of each element within the body of a loop, use the built-in `enumerate` function:

# %%
animals = ['cat', 'dog', 'monkey']
for idx, animal in enumerate(animals):
    print('#%d: %s' % (idx + 1, animal))

# %% [markdown]
# ####List comprehensions:
# %% [markdown]
# When programming, frequently we want to transform one type of data into another. As a simple example, consider the following code that computes square numbers:

# %%
nums = [0, 1, 2, 3, 4]
squares = []
for x in nums:
    squares.append(x ** 2)
print(squares)

# %% [markdown]
# You can make this code simpler using a list comprehension:

# %%
nums = [0, 1, 2, 3, 4]
squares = [x ** 2 for x in nums]
print(squares)

# %% [markdown]
# List comprehensions can also contain conditions:

# %%
nums = [0, 1, 2, 3, 4]
even_squares = [x ** 2 for x in nums if x % 2 == 0]
print(even_squares)

# %% [markdown]
# ####Dictionaries
# %% [markdown]
# A dictionary stores (key, value) pairs, similar to a `Map` in Java or an object in Javascript. You can use it like this:

# %%
d = {'cat': 'cute', 'dog': 'furry'}  # Create a new dictionary with some data
print(d['cat'])       # Get an entry from a dictionary; prints "cute"
print('cat' in d)     # Check if a dictionary has a given key; prints "True"

# %%
d['fish'] = 'wet'    # Set an entry in a dictionary
print(d['fish'])     # Prints "wet"

# %%
print(d['monkey'])  # KeyError: 'monkey' not a key of d

# %%
print(d.get('monkey', 'N/A'))  # Get an element with a default; prints "N/A"
print(d.get('fish', 'N/A'))    # Get an element with a default; prints "wet"

# %%
del d['fish']               # Remove an element from a dictionary
print(d.get('fish', 'N/A')) # "fish" is no longer a key; prints "N/A"

# %% [markdown]
# You can find all you need to know about dictionaries in the [documentation](https://docs.python.org/2/library/stdtypes.html#dict).
# %% [markdown]
# It is easy to iterate over the keys in a dictionary:

# %%
d = {'person': 2, 'cat': 4, 'spider': 8}
for animal in d:
    legs = d[animal]
    print('A %s has %d legs' % (animal, legs))

# %% [markdown]
# If you want access to keys and their corresponding values, use the iteritems method:

# %%
d = {'person': 2, 'cat': 4, 'spider': 8}
for animal, legs in d.items():
    print('A %s has %d legs' % (animal, legs))

# %% [markdown]
# Dictionary comprehensions: These are similar to list comprehensions, but allow you to easily construct dictionaries. For example:

# %%
nums = [0, 1, 2, 3, 4]
even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}
print(even_num_to_square)

# %% [markdown]
# ####Sets
# %% [markdown]
# A set is an unordered collection of distinct elements. As a simple example, consider the following:

# %%
animals = {'cat', 'dog'}
print('cat' in animals)   # Check if an element is in a set; prints "True"
print('fish' in animals)  # prints "False"

# %%
animals.add('fish')      # Add an element to a set
print('fish' in animals)
print(len(animals))       # Number of elements in a set;

# %%
animals.add('cat')       # Adding an element that is already in the set does nothing
print(len(animals))
animals.remove('cat')    # Remove an element from a set
print(len(animals))

# %% [markdown]
# _Loops_: Iterating over a set has the same syntax as iterating over a list; however since sets are unordered, you cannot make assumptions about the order in which you visit the elements of the set:

# %%
animals = {'cat', 'dog', 'fish'}
for idx, animal in enumerate(animals):
    print('#%d: %s' % (idx + 1, animal))
# Prints "#1: dog", "#2: fish", "#3: cat"

# %% [markdown]
# Set comprehensions: Like lists and dictionaries, we can easily construct sets using set comprehensions:

# %%
from math import sqrt
print({int(sqrt(x)) for x in range(30)})

# %% [markdown]
# ####Tuples
# %% [markdown]
# A tuple is an (immutable) ordered list of values. A tuple is in many ways similar to a list; one of the most important differences is that tuples can be used as keys in dictionaries and as elements of sets, while lists cannot. Here is a trivial example:

# %%
d = {(x, x + 1): x for x in range(10)}  # Create a dictionary with tuple keys
t = (5, 6)       # Create a tuple
print(type(t))
print(d[t])
print(d[(1, 2)])

# %%
t[0] = 1

# %% [markdown]
# ###Functions
# %% [markdown]
# Python functions are defined using the `def` keyword. For example:

# %%
def sign(x):
    if x > 0:
        return 'positive'
    elif x < 0:
        return 'negative'
    else:
        return 'zero'

for x in [-1, 0, 1]:
    print(sign(x))

# %% [markdown]
# We will often define functions to take optional keyword arguments, like this:

# %%
def hello(name, loud=False):
    if loud:
        print('HELLO, %s' % name.upper())
    else:
        print('Hello, %s!' % name)

hello('Bob')
hello('Fred', loud=True)

# %% [markdown]
# ###Classes
# %% [markdown]
# The syntax for defining classes in Python is straightforward:

# %%
class Greeter:

    # Constructor
    def __init__(self, name):
        self.name = name  # Create an instance variable

    # Instance method
    def greet(self, loud=False):
        if loud:
            print('HELLO, %s!' % self.name.upper())
        else:
            print('Hello, %s' % self.name)

g = Greeter('Fred')  # Construct an instance of the Greeter class
g.greet()            # Call an instance method; prints "Hello, Fred"
g.greet(loud=True)   # Call an instance method; prints "HELLO, FRED!"

# %% [markdown]
# ##Numpy
# %% [markdown]
# Numpy is the core library for scientific computing in Python. It provides a high-performance multidimensional array object, and tools for working with these arrays. If you are already familiar with MATLAB, you might find this [tutorial](http://wiki.scipy.org/NumPy_for_Matlab_Users) useful to get started with Numpy.
# %% [markdown]
# To use Numpy, we first need to import the `numpy` package:

# %%
import numpy as np

# %% [markdown]
# ###Arrays
# %% [markdown]
# A numpy array is a grid of values, all of the same type, and is indexed by a tuple of nonnegative integers. The number of dimensions is the rank of the array; the shape of an array is a tuple of integers giving the size of the array along each dimension.
# %% [markdown]
# We can initialize numpy arrays from nested Python lists, and access elements using square brackets:

# %%
a = np.array([1, 2, 3])  # Create a rank 1 array
print (type(a), a.shape, a[0], a[1], a[2])
a[0] = 5                 # Change an element of the array
print(a)

# %%
b = np.array([[1,2,3],[4,5,6]])   # Create a rank 2 array
print(b)

# %%
print(b.shape)
print(b[0, 0], b[0, 1], b[1, 0])

# %% [markdown]
# Numpy also provides many functions to create arrays:

# %%
a = np.zeros((2,2))  # Create an array of all zeros
print(a)

# %%
b = np.ones((1,2))   # Create an array of all ones
print(b)

# %%
c = np.full((2,2), 7) # Create a constant array
print(c)

# %%
d = np.eye(2)        # Create a 2x2 identity matrix
print(d)

# %%
e = np.random.random((2,2)) # Create an array filled with random values
print(e)

# %% [markdown]
# ###Array indexing
# %% [markdown]
# Numpy offers several ways to index into arrays.
# %% [markdown]
# Slicing: Similar to Python lists, numpy arrays can be sliced. Since arrays may be multidimensional, you must specify a slice for each dimension of the array:

# %%
import numpy as np

# Create the following rank 2 array with shape (3, 4)
# [[ 1  2  3  4]
#  [ 5  6  7  8]
#  [ 9 10 11 12]]
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])

# Use slicing to pull out the subarray consisting of the first 2 rows
# and columns 1 and 2; b is the following array of shape (2, 2):
# [[2 3]
#  [6 7]]
b = a[:2, 1:3]
print(b)

# %% [markdown]
# A slice of an array is a view into the same data, so modifying it will modify the original array.

# %%
print(a[0, 1])
b[0, 0] = 77    # b[0, 0] is the same piece of data as a[0, 1]
print(a[0, 1])

# %% [markdown]
# You can also mix integer indexing with slice indexing. However, doing so will yield an array of lower rank than the original array. Note that this is quite different from the way that MATLAB handles array slicing:

# %%
# Create the following rank 2 array with shape (3, 4)
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
print(a)

# %% [markdown]
# Two ways of accessing the data in the middle row of the array.
# Mixing integer indexing with slices yields an array of lower rank,
# while using only slices yields an array of the same rank as the
# original array:

# %%
row_r1 = a[1, :]    # Rank 1 view of the second row of a
row_r2 = a[1:2, :]  # Rank 2 view of the second row of a
row_r3 = a[[1], :]  # Rank 2 view of the second row of a
print(row_r1, row_r1.shape)
print(row_r2, row_r2.shape)
print(row_r3, row_r3.shape)

# %%
# We can make the same distinction when accessing columns of an array:
col_r1 = a[:, 1]
col_r2 = a[:, 1:2]
col_r3 = a[:, [1]]
print(col_r1, col_r1.shape)
print(col_r2, col_r2.shape)
print(col_r3, col_r3.shape)

# %% [markdown]
# Integer array indexing: When you index into numpy arrays using slicing, the resulting array view will always be a subarray of the original array. In contrast, integer array indexing allows you to construct arbitrary arrays using the data from another array. Here is an example:

# %%
a = np.array([[1,2], [3, 4], [5, 6]])

# An example of integer array indexing.
# The returned array will have shape (3,) and
print(a[[0, 1, 2], [0, 1, 0]])

# The above example of integer array indexing is equivalent to this:
print(np.array([a[0, 0], a[1, 1], a[2, 0]]))

# %%
# When using integer array indexing, you can reuse the same
# element from the source array:
print(a[[0, 0], [1, 1]])

# Equivalent to the previous integer array indexing example
print(np.array([a[0, 1], a[0, 1]]))

# %% [markdown]
# One useful trick with integer array indexing is selecting or mutating one element from each row of a matrix:

# %%
# Create a new array from which we will select elements
a = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
print(a)

# %%
# Create an array of indices
b = np.array([0, 2, 0, 1])

# Select one element from each row of a using the indices in b
print(a[np.arange(4), b])  # Prints "[ 1  6  7 11]"

# %%
# Mutate one element from each row of a using the indices in b
a[np.arange(4), b] += 10
print(a)

# %% [markdown]
# Boolean array indexing: Boolean array indexing lets you pick out arbitrary elements of an array. Frequently this type of indexing is used to select the elements of an array that satisfy some condition. Here is an example:

# %%
import numpy as np

a = np.array([[1,2], [3, 4], [5, 6]])

bool_idx = (a > 2)  # Find the elements of a that are bigger than 2;
                    # this returns a numpy array of Booleans of the same
                    # shape as a, where each slot of bool_idx tells
                    # whether that element of a is > 2.

print(bool_idx)

# %%
# We use boolean array indexing to construct a rank 1 array
# consisting of the elements of a corresponding to the True values
# of bool_idx
print(a[bool_idx])

# We can do all of the above in a single concise statement:
print(a[a > 2])

# %% [markdown]
# For brevity we have left out a lot of details about numpy array indexing; if you want to know more you should read the documentation.
# %% [markdown]
# ###Datatypes
# %% [markdown]
# Every numpy array is a grid of elements of the same type. Numpy provides a large set of numeric datatypes that you can use to construct arrays. Numpy tries to guess a datatype when you create an array, but functions that construct arrays usually also include an optional argument to explicitly specify the datatype. Here is an example:

# %%
x = np.array([1, 2])  # Let numpy choose the datatype
y = np.array([1.0, 2.0])  # Let numpy choose the datatype
z = np.array([1, 2], dtype=np.int64)  # Force a particular datatype

print(x.dtype, y.dtype, z.dtype)

# %% [markdown]
# You can read all about numpy datatypes in the [documentation](http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html).
# %% [markdown]
# ###Array math
# %% [markdown]
# Basic mathematical functions operate elementwise on arrays, and are available both as operator overloads and as functions in the numpy module:

# %%
x = np.array([[1,2],[3,4]], dtype=np.float64)
y = np.array([[5,6],[7,8]], dtype=np.float64)

# Elementwise sum; both produce the array
print(x + y)
print(np.add(x, y))

# %%
# Elementwise difference; both produce the array
print(x - y)
print(np.subtract(x, y))

# %%
# Elementwise product; both produce the array
print(x * y)
print(np.multiply(x, y))

# %%
# Elementwise division; both produce the array
# [[ 0.2         0.33333333]
#  [ 0.42857143  0.5       ]]
print(x / y)
print(np.divide(x, y))

# %%
# Elementwise square root; produces the array
# [[ 1.          1.41421356]
#  [ 1.73205081  2.        ]]
print(np.sqrt(x))

# %% [markdown]
# Note that unlike MATLAB, `*` is elementwise multiplication, not matrix multiplication. We instead use the dot function to compute inner products of vectors, to multiply a vector by a matrix, and to multiply matrices. dot is available both as a function in the numpy module and as an instance method of array objects:

# %%
x = np.array([[1,2],[3,4]])
y = np.array([[5,6],[7,8]])

v = np.array([9,10])
w = np.array([11, 12])

# Inner product of vectors; both produce 219
print (v.dot(w))
print (np.dot(v, w))

# %%
# Matrix / vector product; both produce the rank 1 array [29 67]
print(x.dot(v))
print(np.dot(x, v))

# %% [markdown]
# In order to avoide cumbersome code, the @ operator can be used for matrix multiplication:

# %%
# Matrix / matrix product; both produce the rank 2 array
# [[19 22]
#  [43 50]]
print(x.dot(y))
print(np.dot(x, y))
print(x@y)

# %% [markdown]
# Numpy provides many useful functions for performing computations on arrays; one of the most useful is `sum`:

# %%
x = np.array([[1,2],[3,4]])

print(np.sum(x))  # Compute sum of all elements; prints "10"
print(np.sum(x, axis=0))  # Compute sum of each column; prints "[4 6]"
print(np.sum(x, axis=1))  # Compute sum of each row; prints "[3 7]"

# %% [markdown]
# You can find the full list of mathematical functions provided by numpy in the [documentation](http://docs.scipy.org/doc/numpy/reference/routines.math.html).
#
# Apart from computing mathematical functions using arrays, we frequently need to reshape or otherwise manipulate data in arrays. The simplest example of this type of operation is transposing a matrix; to transpose a matrix, simply use the T attribute of an array object:

# %%
print(x)
print(x.T)

# %%
v = np.array([[1,2,3]])
print(v)
print(v.T)

# %% [markdown]
# ###Broadcasting
# %% [markdown]
# Broadcasting is a powerful mechanism that allows numpy to work with arrays of different shapes when performing arithmetic operations. Frequently we have a smaller array and a larger array, and we want to use the smaller array multiple times to perform some operation on the larger array.
#
# For example, suppose that we want to add a constant vector to each row of a matrix. We could do it like this:

# %%
# We will add the vector v to each row of the matrix x,
# storing the result in the matrix y
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
y = np.empty_like(x)   # Create an empty matrix with the same shape as x

# Add the vector v to each row of the matrix x with an explicit loop
for i in range(4):
    y[i, :] = x[i, :] + v

print(y)

# %% [markdown]
# This works; however when the matrix `x` is very large, computing an explicit loop in Python could be slow. Note that adding the vector v to each row of the matrix `x` is equivalent to forming a matrix `vv` by stacking multiple copies of `v` vertically, then performing elementwise summation of `x` and `vv`. We could implement this approach like this:

# %%
vv = np.tile(v, (4, 1))  # Stack 4 copies of v on top of each other
print(vv)                # Prints "[[1 0 1]
                         #          [1 0 1]
                         #          [1 0 1]
                         #          [1 0 1]]"

# %%
y = x + vv  # Add x and vv elementwise
print(y)

# %% [markdown]
# Numpy broadcasting allows us to perform this computation without actually creating multiple copies of v. Consider this version, using broadcasting:

# %%
import numpy as np

# We will add the vector v to each row of the matrix x,
# storing the result in the matrix y
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
y = x + v  # Add v to each row of x using broadcasting
print(y)

# %% [markdown]
# The line `y = x + v` works even though `x` has shape `(4, 3)` and `v` has shape `(3,)` due to broadcasting; this line works as if v actually had shape `(4, 3)`, where each row was a copy of `v`, and the sum was performed elementwise.
#
# Broadcasting two arrays together follows these rules:
#
# 1. If the arrays do not have the same rank, prepend the shape of the lower rank array with 1s until both shapes have the same length.
# 2. The two arrays are said to be compatible in a dimension if they have the same size in the dimension, or if one of the arrays has size 1 in that dimension.
# 3. The arrays can be broadcast together if they are compatible in all dimensions.
# 4. After broadcasting, each array behaves as if it had shape equal to the elementwise maximum of shapes of the two input arrays.
# 5. In any dimension where one array had size 1 and the other array had size greater than 1, the first array behaves as if it were copied along that dimension
#
# If this explanation does not make sense, try reading the explanation from the [documentation](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) or this [explanation](http://wiki.scipy.org/EricsBroadcastingDoc).
#
# Functions that support broadcasting are known as universal functions. You can find the list of all universal functions in the [documentation](http://docs.scipy.org/doc/numpy/reference/ufuncs.html#available-ufuncs).
#
# Here are some applications of broadcasting:

# %%
# Compute outer product of vectors
v = np.array([1,2,3])  # v has shape (3,)
w = np.array([4,5])    # w has shape (2,)
# To compute an outer product, we first reshape v to be a column
# vector of shape (3, 1); we can then broadcast it against w to yield
# an output of shape (3, 2), which is the outer product of v and w:

print(np.reshape(v, (3, 1)) * w)

# %%
# Add a vector to each row of a matrix
x = np.array([[1,2,3], [4,5,6]])
# x has shape (2, 3) and v has shape (3,) so they broadcast to (2, 3),
# giving the following matrix:

print(x + v)

# %%
# Add a vector to each column of a matrix
# x has shape (2, 3) and w has shape (2,).
# If we transpose x then it has shape (3, 2) and can be broadcast
# against w to yield a result of shape (3, 2); transposing this result
# yields the final result of shape (2, 3) which is the matrix x with
# the vector w added to each column. Gives the following matrix:

print((x.T + w).T)

# %%
# Another solution is to reshape w to be a row vector of shape (2, 1);
# we can then broadcast it directly against x to produce the same
# output.
print(x + np.reshape(w, (2, 1) ) )

# %%
# Multiply a matrix by a constant:
# x has shape (2, 3). Numpy treats scalars as arrays of shape ();
# these can be broadcast together to shape (2, 3), producing the
# following array:
print(x * 2)

# %% [markdown]
# Broadcasting typically makes your code more concise and faster, so you should strive to use it where possible.
# %% [markdown]
# This brief overview has touched on many of the important things that you need to know about numpy, but is far from complete. Check out the [numpy reference](http://docs.scipy.org/doc/numpy/reference/) to find out much more about numpy.

# %%
##SciPy

# %% [markdown]
# Numpy provides a high-performance multidimensional array and basic tools to compute with and manipulate these arrays. SciPy builds on this, and provides a large number of functions that operate on numpy arrays and are useful for different types of scientific and engineering applications.
#
# The best way to get familiar with SciPy is to browse the documentation. We will highlight some parts of SciPy that you might find useful for this class.
# %% [markdown]
# ###Image operations
# %% [markdown]
# SciPy provides some basic functions to work with images. For example, it has functions to read images from disk into numpy arrays, to write numpy arrays to disk as images, and to resize images. Here is a simple example that showcases these functions:

# %%
from imageio import imread, imsave # Scipy.imread    is deprecated, use imageio instead
from skimage.transform import resize #Scipy.imresize is deprecated, use skimage.transform instead

# Read an JPEG image into a numpy array
img = imread('cat.jpg')
print(img.dtype, img.shape)  # Prints "uint8 (400, 248, 3)"

# We can tint the image by scaling each of the color channels
# by a different scalar constant. The image has shape (400, 248, 3);
# we multiply it by the array [1, 0.95, 0.9] of shape (3,);
# numpy broadcasting means that this leaves the red channel unchanged,
# and multiplies the green and blue channels by 0.95 and 0.9
# respectively.
img_tinted = img * [1, 0.5, 0.9]

# Resize the tinted image to be 300 by 300 pixels.
img_tinted = resize(img_tinted, (300, 300))

# Write the tinted image back to disk
imsave('cat_tinted.jpg', np.uint8(img_tinted))

# %% [markdown]
# ###Distance between points
# %% [markdown]
# SciPy defines some useful functions for computing distances between sets of points.
#
# The function scipy.spatial.distance.pdist computes the distance between all pairs of points in a given set:

# %%
import numpy as np
from scipy.spatial.distance import pdist, squareform

# Create the following array where each row is a point in 2D space:
# [[0 1]
#  [1 0]
#  [2 0]]
x = np.array([[0, 1], [1, 0], [2, 0]])
print(x)

# Compute the Euclidean distance between all rows of x.
# d[i, j] is the Euclidean distance between x[i, :] and x[j, :],
d = squareform(pdist(x, 'euclidean'))
print(d)

# %% [markdown]
# ##Matplotlib
# %% [markdown]
# Matplotlib is a plotting library. In this section give a brief introduction to the `matplotlib.pyplot` module, which provides a plotting system similar to that of MATLAB.

# %%
import numpy as np
import matplotlib.pyplot as plt

# %% [markdown]
# By running this special iPython command, we will be displaying plots inline:

# %%
get_ipython().magic('matplotlib inline')

# %% [markdown]
# ###Plotting
# %% [markdown]
# The most important function in `matplotlib` is plot, which allows you to plot 2D data. Here is a simple example:
# %% [markdown]
# With just a little bit of extra work we can easily plot multiple lines at once, and add a title, legend, and axis labels:

# %%
# Compute the x and y coordinates for points on a sine curve
x = np.arange(0, 3 * np.pi, 0.1)
y = np.sin(x)

# Plot the points using matplotlib
plt.plot(x, y)

# %%
y_sin = np.sin(x)
y_cos = np.cos(x)

# Plot the points using matplotlib
plt.plot(x, y_sin)
plt.plot(x, y_cos)
plt.xlabel('x axis label')
plt.ylabel('y axis label')
plt.title('Sine and Cosine')
plt.legend(['Sine', 'Cosine'])

# %% [markdown]
# ###Subplots
# %% [markdown]
# You can plot different things in the same figure using the subplot function. Here is an example:

# %%
# Compute the x and y coordinates for points on sine and cosine curves
x = np.arange(0, 3 * np.pi, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)

# Set up a subplot grid that has height 2 and width 1,
# and set the first such subplot as active.
plt.subplot(2, 1, 1)

# Make the first plot
plt.plot(x, y_sin)
plt.title('Sine')

# Set the second subplot as active, and make the second plot.
plt.subplot(2, 1, 2)
plt.plot(x, y_cos)
plt.title('Cosine')

# Show the figure.
plt.show()

# %% [markdown]
# You can read much more about the `subplot` function in the [documentation](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.subplot).
# %% [markdown]
# You can use the imshow function to show images. Here is an example:

# %%
import numpy as np
from scipy.misc import imresize
from imageio import imread # Scipy.imread is deprecated, use imageio instead
import matplotlib.pyplot as plt

img = imread('cat.jpg')
img_tinted = img * [1, 0.5, 0.9]

# Show the original image
plt.subplot(1, 2, 1)
plt.imshow(img)

# Show the tinted image
plt.subplot(1, 2, 2)

# A slight gotcha with imshow is that it might give strange results
# if presented with data that is not uint8. To work around this, we
# explicitly cast the image to uint8 before displaying it.
plt.imshow(np.uint8(img_tinted))
plt.show()

# %%


"""
Tests for values coercion in setitem-like operations on DataFrame.

For the most part, these should be multi-column DataFrames, otherwise
we would share the tests with Series.
"""
import numpy as np
import pytest

import pandas as pd
from pandas import (
    DataFrame,
    MultiIndex,
    NaT,
    Series,
    Timestamp,
    date_range,
)
import pandas._testing as tm

class TestDataFrameSetitemCoercion:
    @pytest.mark.xfail(reason="Unnecessary cast.")
    @pytest.mark.parametrize("consolidate", [True, False])
    def test_loc_setitem_multiindex_columns(self, consolidate):
        # GH#18415 Setting values in a single column preserves dtype,
        #  while setting them in multiple columns did unwanted cast.

        # Note that A here has 2 blocks, below we do the same thing
        #  with a consolidated frame.
        A = DataFrame(np.zeros((6, 5), dtype=np.float32))
        A = pd.concat([A, A], axis=1, keys=[1, 2])
        if consolidate:
            A = A._consolidate()

        A.loc[2:3, (1, slice(2, 3))] = np.ones((2, 2), dtype=np.float32)
        assert (A.dtypes == np.float32).all()

        A.loc[0:5, (1, slice(2, 3))] = np.ones((6, 2), dtype=np.float32)
        assert (A.dtypes == np.float32).all()

        A.loc[:, (1, slice(2, 3))] = np.ones((6, 2), dtype=np.float32)
        assert (A.dtypes == np.float32).all()

        # TODO: i think this isn't about MultiIndex and could be done with iloc?

def test_37477():
    # fixed by GH#45121
    orig = DataFrame({"A": [1, 2, 3], "B": [3, 4, 5]})
    expected = DataFrame({"A": [1, 2, 3], "B": [3, 1.2, 5]})

    df = orig.copy()
    df.at[1, "B"] = 1.2
    tm.assert_frame_equal(df, expected)

    df = orig.copy()
    df.loc[1, "B"] = 1.2
    tm.assert_frame_equal(df, expected)

    df = orig.copy()
    df.iat[1, 1] = 1.2
    tm.assert_frame_equal(df, expected)

    df = orig.copy()
    df.iloc[1, 1] = 1.2
    tm.assert_frame_equal(df, expected)

def test_6942(indexer_al):
    # check that the .at __setitem__ after setting "Live" actually sets the data
    start = Timestamp("2014-04-01")
    t1 = Timestamp("2014-04-23 12:42:38.883082")
    t2 = Timestamp("2014-04-24 01:33:30.040039")

    dti = date_range(start, periods=1)
    orig = DataFrame(index=dti, columns=["timenow", "Live"])

    df = orig.copy()
    indexer_al(df)[start, "timenow"] = t1

    df["Live"] = True

    df.at[start, "timenow"] = t2
    assert df.iloc[0, 0] == t2

def test_26395(indexer_al):
    # .at case fixed by GH#45121 (best guess)
    df = DataFrame(index=["A", "B", "C"])
    df["D"] = 0

    indexer_al(df)["C", "D"] = 2
    expected = DataFrame({"D": [0, 0, 2]}, index=["A", "B", "C"], dtype=np.int64)
    tm.assert_frame_equal(df, expected)

    indexer_al(df)["C", "D"] = 44.5
    expected = DataFrame({"D": [0, 0, 44.5]}, index=["A", "B", "C"], dtype=np.float64)
    tm.assert_frame_equal(df, expected)

    indexer_al(df)["C", "D"] = "hello"
    expected = DataFrame({"D": [0, 0, "hello"]}, index=["A", "B", "C"], dtype=object)
    tm.assert_frame_equal(df, expected)

@pytest.mark.xfail(reason="unwanted upcast")
def test_15231():
    df = DataFrame([[1, 2], [3, 4]], columns=["a", "b"])
    df.loc[2] = Series({"a": 5, "b": 6})
    assert (df.dtypes == np.int64).all()

    df.loc[3] = Series({"a": 7})

    # df["a"] doesn't have any NaNs, should not have been cast
    exp_dtypes = Series([np.int64, np.float64], dtype=object, index=["a", "b"])
    tm.assert_series_equal(df.dtypes, exp_dtypes)

@pytest.mark.xfail(reason="Unnecessarily upcasts to float64")
def test_iloc_setitem_unnecesssary_float_upcasting():
    # GH#12255
    df = DataFrame(
        {
            0: np.array([1, 3], dtype=np.float32),
            1: np.array([2, 4], dtype=np.float32),
            2: ["a", "b"],
        }
    )
    orig = df.copy()

    values = df[0].values.reshape(2, 1)
    df.iloc[:, 0:1] = values

    tm.assert_frame_equal(df, orig)

@pytest.mark.xfail(reason="unwanted casting to dt64")
def test_12499():
    # TODO: OP in GH#12499 used np.datetim64("NaT") instead of pd.NaT,
    #  which has consequences for the expected df["two"] (though i think at
    #  the time it might not have because of a separate bug). See if it makes
    #  a difference which one we use here.
    ts = Timestamp("2016-03-01 03:13:22.98986", tz="UTC")

    data = [{"one": 0, "two": ts}]
    orig = DataFrame(data)
    df = orig.copy()
    df.loc[1] = [np.nan, NaT]

    expected = DataFrame(
        {"one": [0, np.nan], "two": Series([ts, NaT], dtype="datetime64[ns, UTC]")}
    )
    tm.assert_frame_equal(df, expected)

    data = [{"one": 0, "two": ts}]
    df = orig.copy()
    df.loc[1, :] = [np.nan, NaT]
    tm.assert_frame_equal(df, expected)

@pytest.mark.xfail(reason="Too many columns cast to float64")
def test_20476():
    mi = MultiIndex.from_product([["A", "B"], ["a", "b", "c"]])
    df = DataFrame(-1, index=range(3), columns=mi)
    filler = DataFrame([[1, 2, 3.0]] * 3, index=range(3), columns=["a", "b", "c"])
    df["A"] = filler

    expected = DataFrame(
        {
            0: [1, 1, 1],
            1: [2, 2, 2],
            2: [3.0, 3.0, 3.0],
            3: [-1, -1, -1],
            4: [-1, -1, -1],
            5: [-1, -1, -1],
        }
    )
    expected.columns = mi
    exp_dtypes = Series(
        [np.dtype(np.int64)] * 2 + [np.dtype(np.float64)] + [np.dtype(np.int64)] * 3,
        index=mi,
    )
    tm.assert_series_equal(df.dtypes, exp_dtypes)


""" Basic introduction to unit testing with Python

@brief get started with python testing by looking at https://docs.pytest.org/en/latest/getting-started.html#getstarted. Note that any script to be ran within the python testing framework (pytest) should follow the standard test discovery rules (https://docs.pytest.org/en/latest/goodpractices.html#test-discovery)
"""
import numpy as np
import os
print('Starting test script from working directory : '+os.getcwd())

def test_basicTrue():
    """ one of the simplest test that does nothing except saying it works..."""
    assert True

#testing session 1 functions
def load_s1_script():
    """
        utility function that tris to load the script written along the first lesson
        @throws an ImportError exception if the script file does not exist
        @return the script as a loaded module
    """
    S1_script_filename='../Session1/S1_algotools.py'
    print('Trying to load target scripts:'+S1_script_filename)
    import imp
    s1_algotools=imp.load_source('session_1_script', S1_script_filename)
    return  s1_algotools

#load the scripts to check
def test_session1script_exists():
    try:
        load_s1_script()
        assert True
    except  ImportError:
        print('Expected script not found, carrefuly check the assignement instructions ')
        assert False

def check_s1_selective_average(testList):
    ##
    # utility function that asserts if load_S1_script().average_above_zero works fine
    # @param testList a list of values onto average_above_zero is applied
    # @test ensures the function returns the correct average value
    import numpy as np
    #another way to process the positive elements average to compare with
    positive_elements_float_array=np.array([i for i in testList if i >= 0], dtype=float)
    reference_average_value=np.mean(positive_elements_float_array)
    assert load_s1_script().average_above_zero(testList) ==reference_average_value

def test_s1_selective_average_non_zeros_values():
    ##
    # @test validates average_above_zero works fine with integer values >0
    check_s1_selective_average([1,2,3,4,-7])

def test_s1_selective_average_with_negative_values():
    ##
    # @test validates average_above_zero works fine with integer values <=0
    check_s1_selective_average([0,-7])

def test_s1_selective_average_with_string_values():
    ##
    # @test validates average_above_zero works fine with integer values <=0
    check_s1_selective_average(['ab','c'])

def test_s1_selective_average_with_string_values():
    ##
    # @test validates average_above_zero works fine with an empty list
    try:
        check_s1_selective_average([])
        assert False
    except ValueError:
        assert True

#  =========================== test about reverse_table
def test_reverse_table_value():
    ##
    # @test validates reverse_table works fine with correct array
    assert load_s1_script().reverse_table([1, 1, 2, 3, 5, 8]) == [8, 5, 3, 2, 1, 1]

def test_reverse_table_of_table():
    ##
    # @test validates reverse_table works fine with array in array
    assert load_s1_script().reverse_table([[1, 1], 2, 3, [5, 8]]) == [[5,8], 3, 2, [1, 1]]
def test_reverse_table_with_string():
    ##
    # @test validates reverse_table works fine with string instead of array
    try:
        load_s1_script().reverse_table('array')
        assert False
    except TypeError:
        assert True

#  =========================== test about roi_bbox

def test_roi_bbox_no_np_array():
    ##
    # @test validates roi_bbox works fine with no numpy array in parameter.
    try:
        load_s1_script().roi_bbox(5)
        assert False
    except TypeError:
        assert True

def test_roi_bbox_with_array():
    ##
    # @test validates roi_bbox works fine with array.
    assert np.array_equal(load_s1_script().roi_bbox(np.array([[  0, 0, 0, 0, 0, 0],
               [  0, 1, 0, 0, 0, 0],
               [  0, 0, 0, 1, 0, 0],
               [  0, 0, 0, 0, 0, 0],
               [  0, 0, 1, 0, 0, 0],
               [  0, 0, 0, 0, 0, 0]])) , np.array([[1, 1], [1, 3], [4, 1], [4, 3]]))

#  =========================== test about random_fill_sparse

def test_random_fill_sparse_value_with_no_int():
    ##
    # @test validates random_fill_sparse works fine with not int as second parameter.
    try:
        load_s1_script().random_fill_sparse(np.array([['', '', ''], ['', '', '']]), 'dd')
        assert False
    except TypeError:
        assert True

#  =========================== test about remove_whitespace

def test_remove_whitespace_with():
    ##
    # @test validates remove_whitespace works fine.
    assert load_s1_script().remove_whitespace('La fleur en bouquet fane, et jamais ne renaît !') == 'Lafleurenbouquetfane,etjamaisnerenaît!'

def test_remove_whitespace_with_no_string():
    ##
    # @test validates remove_whitespace works fine with no string in parameter.
    try:
        load_s1_script().remove_whitespace(8)
        assert False
    except TypeError:
        assert True

#  =========================== test about shuffle

def test_shuffle_with_no_array_value():
    ##
    # @test validates shuffle works fine with no array in parameter.
    try:
        load_s1_script().shuffle(3)
        assert False
    except TypeError:
        assert True

def test_shuffle_with_array():
    ##
    # @test validates shuffle works fine with array
    arrayTest = [i for i in range(10)]
    initSum = sum(arrayTest)
    result = load_s1_script().shuffle(arrayTest)

    assert initSum == sum(result)

#  =========================== test about sort_selective

def test_sort_selective_with_no_array():
    ##
    # @test validates sort_selective works fine with no array in parameter.
    try:
        load_s1_script().sort_selective(12)
        assert False
    except TypeError:
        assert True

def test_sort_selective_with_array():
    ##
    # @test validates sort_selective works fine with array.
    assert load_s1_script().sort_selective([2, 5, 3, 25, 7, 9, 6, 7, 7, 1, 0, 10]) == [0, 1, 2, 3, 5, 6, 7, 7, 7, 9, 10, 25]

#  =========================== test about sort_bubble

def test_sort_bubble_with_no_array():
    ##
    # @test validates sort_bubble works fine with no array in parameter..
    try:
        load_s1_script().sort_bubble(2)
        assert False
    except TypeError:
        assert True

def test_sort_bubble_with_array_of_ten():
    ##
    # @test validates sort_bubble works fine with array of 10 values.
    assert load_s1_script().sort_bubble([2, 5, 8, 3, 7, 9, 6, 7, 7, 6, 1, 0]) == [0, 1, 2, 3, 5, 6, 6, 7, 7, 7, 8, 9]


import copy
import logging
import pprint
import sys
from typing import Callable, Dict, List, Union

import numpy as np
from pydantic import BaseModel

pp = pprint.PrettyPrinter(width=120)

def _handle_return(passfail: bool, label: str, message: str, return_message: bool, quiet: bool = False):
    """Function to print a '*label*...PASSED' line to log."""

    if not quiet:
        if passfail:
            logging.info(f"    {label:.<53}PASSED")
        else:
            logging.error(f"    {label:.<53}FAILED")
            logging.error(f"    {message:.<53}")

    if return_message:
        return passfail, message
    else:
        return passfail

def tnm() -> str:
    """Returns the name of the calling function, usually name of test case."""

    return sys._getframe().f_back.f_code.co_name

def compare_values(
    expected,
    computed,
    label: str = None,
    *,
    atol: float = 1.0e-6,
    rtol: float = 1.0e-16,
    equal_nan: bool = False,
    equal_phase: bool = False,
    passnone: bool = False,
    quiet: bool = False,
    return_message: bool = False,
    return_handler: Callable = None,
) -> bool:
    """Returns True if two floats or float arrays are element-wise equal within a tolerance.

    Parameters
    ----------
    expected : float or float array-like
        Reference value against which `computed` is compared.
    computed : float or float array-like
        Input value to compare against `expected`.
    atol : float, optional
        Absolute tolerance (see formula below).
    label : str, optional
        Label for passed and error messages. Defaults to calling function name.
    rtol : float, optional
        Relative tolerance (see formula below). By default set to zero so `atol` dominates.
    equal_nan : bool, optional
        Passed to np.isclose. Compare NaN's as equal.
    equal_phase : bool, optional
        Compare computed *or its opposite* as equal.
    passnone : bool, optional
        Return True when both expected and computed are None.
    quiet : bool, optional
        Whether to log the return message.
    return_message : bool, optional
        Whether to return tuple. See below.

    Returns
    -------
    allclose : bool
        Returns True if `expected` and `computed` are equal within tolerance; False otherwise.
    message : str, optional
        When return_message=True, also return passed or error message.

    Other Parameters
    ----------------
    return_handler : function, optional
        Function to control printing, logging, raising, and returning.
        Specialized interception for interfacing testing systems.

    Notes
    -----
    * Akin to np.allclose.
    * For scalar float-comparable types and for arbitrary-dimension, np.ndarray-castable, uniform-type,
      float-comparable types. For mixed types, use :py:func:`compare_recursive`.
    * Sets rtol to zero to match expected Psi4 behaviour, otherwise measured as:

    .. code-block:: python

        absolute(computed - expected) <= (atol + rtol * absolute(expected))

    """
    label = label or sys._getframe().f_back.f_code.co_name
    pass_message = f"\t{label:.<66}PASSED"
    if return_handler is None:
        return_handler = _handle_return

    if passnone:
        if expected is None and computed is None:
            return return_handler(True, label, pass_message, return_message, quiet)

    if np.iscomplexobj(expected):
        dtype = np.complex
    else:
        dtype = np.float

    try:
        xptd, cptd = np.array(expected, dtype=dtype), np.array(computed, dtype=dtype)
    except Exception:
        return return_handler(
            False, label, f"""\t{label}: inputs not cast-able to ndarray of {dtype}.""", return_message, quiet
        )

    if xptd.shape != cptd.shape:
        return return_handler(
            False,
            label,
            f"""\t{label}: computed shape ({cptd.shape}) does not match ({xptd.shape}).""",
            return_message,
            quiet,
        )  # lgtm: [py/syntax-error]

    digits1 = abs(int(np.log10(atol))) + 2
    digits_str = f"to atol={atol}"
    if rtol > 1.0e-12:
        digits_str += f", rtol={rtol}"

    isclose = np.isclose(cptd, xptd, rtol=rtol, atol=atol, equal_nan=equal_nan)
    allclose = bool(np.all(isclose))

    if not allclose and equal_phase and hasattr(cptd, "__neg__"):
        n_isclose = np.isclose(-cptd, xptd, rtol=rtol, atol=atol, equal_nan=equal_nan)
        allclose = bool(np.all(n_isclose))

    if allclose:
        message = pass_message

    else:
        if xptd.shape == ():
            xptd_str = f"{float(xptd):.{digits1}f}"
        else:
            xptd_str = np.array_str(xptd, max_line_width=120, precision=12, suppress_small=True)
            xptd_str = "\n".join("    " + ln for ln in xptd_str.splitlines())

        if cptd.shape == ():
            cptd_str = f"{float(cptd):.{digits1}f}"
        else:
            cptd_str = np.array_str(cptd, max_line_width=120, precision=12, suppress_small=True)
            cptd_str = "\n".join("    " + ln for ln in cptd_str.splitlines())

        diff = cptd - xptd
        if xptd.shape == ():
            diff_str = f"{float(diff):.{digits1}f}"
            message = """\t{}: computed value ({}) does not match ({}) {} by difference ({}).""".format(
                label, cptd_str, xptd_str, digits_str, diff_str
            )
        else:
            diff[isclose] = 0.0
            diff_str = np.array_str(diff, max_line_width=120, precision=12, suppress_small=False)
            diff_str = "\n".join("    " + ln for ln in diff_str.splitlines())
            message = """\t{}: computed value does not match {}.\n  Expected:\n{}\n  Observed:\n{}\n  Difference (passed elements are zeroed):\n{}\n""".format(
                label, digits_str, xptd_str, cptd_str, diff_str
            )

    return return_handler(allclose, label, message, return_message, quiet)

def compare(
    expected,
    computed,
    label: str = None,
    *,
    equal_phase: bool = False,
    quiet: bool = False,
    return_message: bool = False,
    return_handler: Callable = None,
) -> bool:
    """Returns True if two integers, strings, booleans, or integer arrays are element-wise equal.

    Parameters
    ----------
    expected : int, bool, str or int array-like
        Reference value against which `computed` is compared.
    computed : int, bool, str or int array-like
        Input value to compare against `expected`.
    label : str, optional
        Label for passed and error messages. Defaults to calling function name.
    equal_phase : bool, optional
        Compare computed *or its opposite* as equal.

    Returns
    -------
    allclose : bool
        Returns True if `expected` and `computed` are equal; False otherwise.
    message : str, optional
        When return_message=True, also return passed or error message.

    Other Parameters
    ----------------
    return_handler : function, optional
        Function to control printing, logging, raising, and returning.
        Specialized interception for interfacing testing systems.

    Notes
    -----
    * Akin to np.array_equal.
    * For scalar exactly-comparable types and for arbitrary-dimension, np.ndarray-castable, uniform-type,
      exactly-comparable types. For mixed types, use :py:func:`compare_recursive`.

    """
    label = label or sys._getframe().f_back.f_code.co_name
    pass_message = f"\t{label:.<66}PASSED"
    if return_handler is None:
        return_handler = _handle_return

    try:
        xptd, cptd = np.array(expected), np.array(computed)
    except Exception:
        return return_handler(False, label, f"""\t{label}: inputs not cast-able to ndarray.""", return_message, quiet)

    if xptd.shape != cptd.shape:
        return return_handler(
            False,
            label,
            f"""\t{label}: computed shape ({cptd.shape}) does not match ({xptd.shape}).""",
            return_message,
            quiet,
        )

    isclose = np.asarray(xptd == cptd)
    allclose = bool(isclose.all())

    if not allclose and equal_phase:
        try:
            n_isclose = np.asarray(xptd == -cptd)
        except TypeError:
            pass
        else:
            allclose = bool(n_isclose.all())

    if allclose:
        message = pass_message

    else:
        if xptd.shape == ():
            xptd_str = f"{xptd}"
        else:
            xptd_str = np.array_str(xptd, max_line_width=120, precision=12, suppress_small=True)
            xptd_str = "\n".join("    " + ln for ln in xptd_str.splitlines())

        if cptd.shape == ():
            cptd_str = f"{cptd}"
        else:
            cptd_str = np.array_str(cptd, max_line_width=120, precision=12, suppress_small=True)
            cptd_str = "\n".join("    " + ln for ln in cptd_str.splitlines())

        try:
            diff = cptd - xptd
        except TypeError:
            diff_str = "(n/a)"
        else:
            if xptd.shape == ():
                diff_str = f"{diff}"
            else:
                diff_str = np.array_str(diff, max_line_width=120, precision=12, suppress_small=False)
                diff_str = "\n".join("    " + ln for ln in diff_str.splitlines())

        if xptd.shape == ():
            message = """\t{}: computed value ({}) does not match ({}) by difference ({}).""".format(
                label, cptd_str, xptd_str, diff_str
            )
        else:
            message = """\t{}: computed value does not match.\n  Expected:\n{}\n  Observed:\n{}\n  Difference:\n{}\n""".format(
                label, xptd_str, cptd_str, diff_str
            )

    return return_handler(allclose, label, message, return_message, quiet)

def _compare_recursive(expected, computed, atol, rtol, _prefix=False, equal_phase=False):

    errors = []
    name = _prefix or "root"
    prefix = name + "."

    # Initial conversions if required
    if isinstance(expected, BaseModel):
        expected = expected.dict()

    if isinstance(computed, BaseModel):
        computed = computed.dict()

    if isinstance(expected, (str, int, bool, complex)):
        if expected != computed:
            errors.append((name, "Value {} did not match {}.".format(expected, computed)))

    elif isinstance(expected, (list, tuple)):
        try:
            if len(expected) != len(computed):
                errors.append((name, "Iterable lengths did not match"))
            else:
                for i, item1, item2 in zip(range(len(expected)), expected, computed):
                    errors.extend(
                        _compare_recursive(
                            item1, item2, _prefix=prefix + str(i), atol=atol, rtol=rtol, equal_phase=equal_phase
                        )
                    )
        except TypeError:
            errors.append((name, "Expected computed to have a __len__()"))

    elif isinstance(expected, dict):
        expected_extra = computed.keys() - expected.keys()
        computed_extra = expected.keys() - computed.keys()
        if len(expected_extra):
            errors.append((name, "Found extra keys {}".format(expected_extra)))
        if len(computed_extra):
            errors.append((name, "Missing keys {}".format(computed_extra)))

        for k in expected.keys() & computed.keys():
            name = prefix + str(k)
            errors.extend(
                _compare_recursive(
                    expected[k], computed[k], _prefix=name, atol=atol, rtol=rtol, equal_phase=equal_phase
                )
            )

    elif isinstance(expected, (float, np.number)):
        passfail, msg = compare_values(
            expected, computed, atol=atol, rtol=rtol, equal_phase=equal_phase, return_message=True, quiet=True
        )
        if not passfail:
            errors.append((name, "Arrays differ." + msg))

    elif isinstance(expected, np.ndarray):
        if np.issubdtype(expected.dtype, np.floating):
            passfail, msg = compare_values(
                expected, computed, atol=atol, rtol=rtol, equal_phase=equal_phase, return_message=True, quiet=True
            )
        else:
            passfail, msg = compare(expected, computed, equal_phase=equal_phase, return_message=True, quiet=True)
        if not passfail:
            errors.append((name, "Arrays differ." + msg))

    elif isinstance(expected, type(None)):
        if expected is not computed:
            errors.append((name, "'None' does not match."))

    else:
        errors.append((name, f"Type {type(expected)} not understood -- stopping recursive compare."))

    return errors

def compare_recursive(
    expected: Union[Dict, BaseModel, "ProtoModel"],  # type: ignore
    computed: Union[Dict, BaseModel, "ProtoModel"],  # type: ignore
    label: str = None,
    *,
    atol: float = 1.0e-6,
    rtol: float = 1.0e-16,
    forgive: List[str] = None,
    equal_phase: Union[bool, List] = False,
    quiet: bool = False,
    return_message: bool = False,
    return_handler: Callable = None,
) -> bool:
    """
    Recursively compares nested structures such as dictionaries and lists.

    Parameters
    ----------
    expected : dict
        Reference value against which `computed` is compared.
        Dict may be of any depth but should contain Plain Old Data.
    computed : int, bool, str or int array-like
        Input value to compare against `expected`.
        Dict may be of any depth but should contain Plain Old Data.
    atol : int or float, optional
        Absolute tolerance (see formula below).
    label : str, optional
        Label for passed and error messages. Defaults to calling function name.
    rtol : float, optional
        Relative tolerance (see formula below). By default set to zero so `atol` dominates.
    forgive : list, optional
        Keys in top level which may change between `expected` and `computed` without triggering failure.
    equal_phase : bool, optional
        Compare computed *or its opposite* as equal.

    Returns
    -------
    allclose : bool
        Returns True if `expected` and `computed` are equal within tolerance; False otherwise.
    message : str, optional
        When return_message=True, also return passed or error message.

    Notes
    -----

    .. code-block:: python

        absolute(computed - expected) <= (atol + rtol * absolute(expected))

    """
    label = label or sys._getframe().f_back.f_code.co_name
    if atol >= 1:
        raise ValueError(
            "Prior to v0.4.0, ``compare_recursive`` used to 10**-atol any atol >=1. That has ceased, so please express your atol literally."
        )
    if return_handler is None:
        return_handler = _handle_return

    errors = _compare_recursive(expected, computed, atol=atol, rtol=rtol)

    if errors and equal_phase:
        n_errors = _compare_recursive(expected, computed, atol=atol, rtol=rtol, equal_phase=True)
        n_errors = dict(n_errors)

        if equal_phase is False:
            equal_phase = []
        elif equal_phase is True:
            equal_phase = list(dict(errors).keys())
        else:
            equal_phase = [(ep if ep.startswith("root.") else "root." + ep) for ep in equal_phase]
        phased = []

        for nomatch in sorted(errors):
            for ep in equal_phase or []:
                if nomatch[0].startswith(ep):
                    if nomatch[0] not in n_errors:
                        phased.append(nomatch)
                        errors.remove(nomatch)

    if forgive is None:
        forgive = []
    else:
        forgive = [(fg if fg.startswith("root.") else "root." + fg) for fg in forgive]
    forgiven = []

    for nomatch in sorted(errors):
        for fg in forgive or []:
            if nomatch[0].startswith(fg):
                forgiven.append(nomatch)
                errors.remove(nomatch)

    ## print if verbose >= 2 if these functions had that knob
    # forgiven_message = []
    # for e in sorted(forgiven):
    #     forgiven_message.append(e[0])
    #     forgiven_message.append("forgiven    " + e[1])
    # pprint.pprint(forgiven)

    message = []
    for e in sorted(errors):
        message.append(e[0])
        message.append("    " + e[1])

    ret_msg_str = "\n".join(message)

    return return_handler(len(ret_msg_str) == 0, label, ret_msg_str, return_message, quiet)

def compare_molrecs(
    expected,
    computed,
    label: str = None,
    *,
    atol: float = 1.0e-6,
    rtol: float = 1.0e-16,
    forgive=None,
    verbose: int = 1,
    relative_geoms="exact",
    return_message: bool = False,
    return_handler: Callable = None,
) -> bool:
    """Function to compare Molecule dictionaries. Prints
    #    :py:func:`util.success` when elements of `computed` match elements of
    #    `expected` to `tol` number of digits (for float arrays).

    """
    # Need to manipulate the dictionaries a bit, so hold values
    xptd = copy.deepcopy(expected)
    cptd = copy.deepcopy(computed)

    def massage_dicts(dicary):
        # if 'fix_symmetry' in dicary:
        #     dicary['fix_symmetry'] = str(dicary['fix_symmetry'])
        # if 'units' in dicary:
        #     dicary['units'] = str(dicary['units'])
        if "fragment_files" in dicary:
            dicary["fragment_files"] = [str(f) for f in dicary["fragment_files"]]
        # and about int vs long errors
        # if 'molecular_multiplicity' in dicary:
        #     dicary['molecular_multiplicity'] = int(dicary['molecular_multiplicity'])
        # if 'fragment_multiplicities' in dicary:
        #     dicary['fragment_multiplicities'] = [(m if m is None else int(m))
        #                                          for m in dicary['fragment_multiplicities']]
        if "fragment_separators" in dicary:
            dicary["fragment_separators"] = [(s if s is None else int(s)) for s in dicary["fragment_separators"]]
        # forgive generator version changes
        if "provenance" in dicary:
            dicary["provenance"].pop("version")
        # regularize connectivity ordering
        if "connectivity" in dicary:
            conn = [(min(at1, at2), max(at1, at2), bo) for (at1, at2, bo) in dicary["connectivity"]]
            conn.sort(key=lambda tup: tup[0])
            dicary["connectivity"] = conn

        return dicary

    xptd = massage_dicts(xptd)
    cptd = massage_dicts(cptd)

    if relative_geoms == "exact":
        pass
    elif relative_geoms == "align":
        # can't just expect geometries to match, so we'll align them, check that
        #   they overlap and that the translation/rotation arrays jibe with
        #   fix_com/orientation, then attach the oriented geom to computed before the
        #   recursive dict comparison.
        from .molutil.align import B787

        cgeom = np.array(cptd["geom"]).reshape((-1, 3))
        rgeom = np.array(xptd["geom"]).reshape((-1, 3))
        rmsd, mill = B787(
            rgeom=rgeom,
            cgeom=cgeom,
            runiq=None,
            cuniq=None,
            atoms_map=True,
            mols_align=True,
            run_mirror=False,
            verbose=0,
        )
        if cptd["fix_com"]:
            return compare(
                True,
                np.allclose(np.zeros((3)), mill.shift, atol=atol),
                "null shift",
                quiet=(verbose == 0),
                return_message=return_message,
                return_handler=return_handler,
            )
        if cptd["fix_orientation"]:
            return compare(
                True,
                np.allclose(np.identity(3), mill.rotation, atol=atol),
                "null rotation",
                quiet=(verbose == 0),
                return_message=return_message,
                return_handler=return_handler,
            )
        ageom = mill.align_coordinates(cgeom)
        cptd["geom"] = ageom.reshape((-1))

    return compare_recursive(
        xptd,
        cptd,
        atol=atol,
        rtol=rtol,
        label=label,
        forgive=forgive,
        quiet=(verbose == 0),
        return_message=return_message,
        return_handler=return_handler,
    )


# coding: utf-8

# In[78]:

#!/usr/bin/python
import time
start_time = time.time()

import sys
import pickle
import numpy as np
sys.path.append("../tools/")

from feature_format import featureFormat, targetFeatureSplit
from tester import dump_classifier_and_data
from tester import test_classifier

# In[79]:

#------------------------------------------------------------------
### Task 1: Select what features you'll use.
### features_list is a list of strings, each of which is a feature name.
### The first feature must be "poi".

poi = ['poi']
financial_features = ['salary','bonus','deferral_payments','deferred_income',
                      'exercised_stock_options','expenses','long_term_incentive',
                      'other','restricted_stock','total_payments','total_stock_value']
email_features = ['from_messages','from_poi_to_this_person','from_this_person_to_poi',
                  'shared_receipt_with_poi','to_messages']
features_list =  poi + financial_features + email_features

### Load the dictionary containing the dataset
with open("final_project_dataset.pkl", "r") as data_file:
    data_dict = pickle.load(data_file)

print "Size dataset: " , len(data_dict)
poi = 0
not_poi = 0
for k in data_dict:
    if data_dict[k]['poi'] == True:
        poi += 1
    if data_dict[k]['poi'] == False:
        not_poi += 1

print "Number of POI: " , poi
print "Number of not POI: " , not_poi
print "Number of financial Features: " , len(financial_features)
print "Number of email Features: " , len(email_features)

# In[80]:

#-----------------------------------------------------------------
### Task 2: Remove outliers

# remove 'TOTAL' from dictionary
del data_dict['TOTAL']

# remove 'THE TRAVEL AGENCY IN THE PARK' from dictionary
del data_dict['THE TRAVEL AGENCY IN THE PARK']

# remove negative values from 'restricted_stock'
for person in data_dict:
        if data_dict[person]['restricted_stock'] < 0 and data_dict[person]['restricted_stock'] != 'NaN':
            data_dict[person]['restricted_stock'] = 'NaN'

# remove negative values from 'deferral_payments'
for person in data_dict:
        if data_dict[person]['deferral_payments'] < 0 and data_dict[person]['deferral_payments'] != 'NaN':
            data_dict[person]['deferral_payments'] = 'NaN'

# remove negative values from 'total_stock_value'
for person in data_dict:
        if data_dict[person]['total_stock_value'] < 0 and data_dict[person]['total_stock_value'] != 'NaN':
            data_dict[person]['total_stock_value'] = 'NaN'

# Remove 'restricted_stock_deferred' and 'loan_advances' from the features, few relevant data available

# Remove 'director_fee' because there is only non-POI data

# In[81]:

# Checking if had some person without value
not_NaN_data = {}
for key in data_dict:
    not_NaN_feature = 0
    for feature in data_dict[key]:
        if data_dict[key][feature] != 'NaN':
            not_NaN_feature += 1
    not_NaN_data[key] = not_NaN_feature

for k in not_NaN_data:
    if not_NaN_data[k] == 1:
        print k
        print data_dict[k]

# In[82]:

# remove 'THE TRAVEL AGENCY IN THE PARK' from dictionary
del data_dict['LOCKHART EUGENE E']

# In[83]:

#------------------------------------------------------------------
### Task 3: Create new feature(s)
### Store to my_dataset for easy export below.

### The messages to and from POI are an absolute measure, let's create new features that are a ratio of the total messages.
def new_feature_ratio(new_feature, numerator, denominator):
    for key in data_dict:
        if data_dict[key][denominator] != 'NaN' and data_dict[key][numerator] != "NaN":
            data_dict[key][new_feature] = float(data_dict[key][numerator]) / float(data_dict[key][denominator])
        else:
            data_dict[key][new_feature] = "NaN"
    features_list.append(new_feature)

### Feature - 'from_this_person_to_poi_ratio'
new_feature_ratio('from_this_person_to_poi_ratio', 'from_this_person_to_poi', 'from_messages')

### Feature - 'from_poi_to_this_person_ratio'
new_feature_ratio('from_poi_to_this_person_ratio', 'from_poi_to_this_person', 'to_messages')

### Feature - 'bonus_ratio'
new_feature_ratio('bonus_ratio', 'bonus', 'salary')

# In[84]:

from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler(feature_range=(0, 1))
my_dataset = data_dict

### Put features with "long tail" in log10 scale
features_list_log = ['salary','bonus','deferral_payments','exercised_stock_options',
                     'expenses','long_term_incentive','other','restricted_stock',
                     'total_payments','total_stock_value', 'from_messages',
                     'from_poi_to_this_person', 'from_this_person_to_poi',
                     'shared_receipt_with_poi', 'bonus_ratio']
features_list_log = []
for n in range(1,len(features_list_log)):
    for person in my_dataset:
        if my_dataset[person][features_list_log[n]] != "NaN":
            if my_dataset[person][features_list_log[n]] >= 0:
                if my_dataset[person][features_list_log[n]] == 0:
                    my_dataset[person][features_list_log[n]] = 0
            else:
                my_dataset[person][features_list_log[n]] = np.log10(my_dataset[person][features_list_log[n]]*-1)

### Extract features and labels from dataset for local testing
data = featureFormat(my_dataset, features_list, sort_keys = True)
labels, features = targetFeatureSplit(data)

### Put all features in same reange (0,1)
for n in range(0,len(features[0])):
    feature = []
    for person in range(0,len(features)):
        feature.append(features[person][n])
    feature = np.array(feature).reshape(-1,1)
    feature = scaler.fit_transform(feature)
    for person in range(0,len(features)):
        features[person][n] = feature[person]

# In[85]:

#-----------------------------------------------------------------
### Task 4: Try a varity of classifiers
### Please name your classifier clf for easy export below.
### Note that if you want to do PCA or other multi-stage operations,
### you'll need to use Pipelines. For more info:
### http://scikit-learn.org/stable/modules/pipeline.html

# Provided to give you a starting point. Try a variety of classifiers.
from sklearn.model_selection import GridSearchCV

from sklearn.naive_bayes import GaussianNB
clf_NB = GaussianNB()

from sklearn import svm
from sklearn.svm import SVC
parameters = {'kernel':('linear', 'rbf', 'poly', 'sigmoid'), 'C':[1, 10], 'degree': [2,10]}
svr = svm.SVC()
clf_SVM = GridSearchCV(svr, parameters, scoring = 'f1')

from sklearn.tree import DecisionTreeClassifier
parameters = {'criterion':('gini', 'entropy'), 'splitter':('best', 'random'), 'min_samples_split':[2,200]}
svr = DecisionTreeClassifier()
clf_tree = GridSearchCV(svr, parameters, scoring = 'f1')

from sklearn.ensemble import RandomForestClassifier
parameters = {'n_estimators': [2,20], 'criterion':('gini', 'entropy'), 'min_samples_split':[2,200]}
svr = RandomForestClassifier()
clf_randon_forest = GridSearchCV(svr, parameters, scoring = 'f1')

classifiers = {"clf_NB": clf_NB,
               "clf_SVM": clf_SVM,
               "clf_tree": clf_tree,
               "clf_randon_forest": clf_randon_forest}

#----------------------------------------------------------------
### Task 5: Tune your classifier to achieve better than .3 precision and recall
### using our testing script. Check the tester.py script in the final project
### folder for details on the evaluation method, especially the test_classifier
### function. Because of the small size of the dataset, the script uses
### stratified shuffle split cross validation. For more info:
### http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.StratifiedShuffleSplit.html

# Example starting point. Try investigating other evaluation techniques!

### Using K-fold
from sklearn.metrics import accuracy_score
from sklearn.metrics import precision_recall_fscore_support
from sklearn.model_selection import StratifiedKFold
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import f_classif
from sklearn.pipeline import make_pipeline

def train_test_StratifiedKFold(clf, k_best, features):
    # Enter a classifier and the number of the k-best features and the function return
    # the classifier and validation metrics
    acc = []
    pre = []
    rec = []
    f = []
    skf = StratifiedKFold(2, shuffle=True)
    for train_index, test_index in skf.split(features, labels):
        features_train = [features[ii] for ii in train_index]
        labels_train = [labels[ii] for ii in train_index]
        features_test = [features[ii] for ii in test_index]
        labels_test = [labels[ii] for ii in test_index]

        skb = SelectKBest(f_classif, k = k_best)
        pipe = make_pipeline(skb, clf)
        pipe.fit(features_train, labels_train)
        labels_pred = pipe.predict(features_test)
        acc.append(accuracy_score (labels_test, labels_pred))
        pre_rec_f = precision_recall_fscore_support (labels_test, labels_pred)
        try:
            pre.append(pre_rec_f[0][1])
        except:
            pass
        try:
            rec.append(pre_rec_f[1][1])
        except:
            pass
        try:
            f.append(pre_rec_f[2][1])
        except:
            pass
    return [pipe, np.mean(acc), np.mean(pre), np.mean(rec), np.mean(f)]

# In[86]:

#---------------------------------------------------------
# Now we will test the best classifiers

best_clf = [None, None, None]

# We will test all combination of the 4 algoritms and k-best features (k from 1 to 19).
# For each metric (accuracy, precision, recall and f) we will print the best combination.
# We will try 5 times to be sure to choose the best combination
for test in range(1,6):
    max_acc = [0, 'NaN', 'NaN']
    max_pre = [0, 'NaN', 'NaN']
    max_rec = [0, 'NaN', 'NaN']
    max_f = [0, 'NaN', 'NaN']
    for algor in classifiers:
        for k_best in range(1, 17): #20):
            preview_clf, acc, pre, rec, f = train_test_StratifiedKFold(classifiers[algor], k_best, features)
            if acc > max_acc[0]:
                max_acc = [acc, algor, k_best]
            if pre > max_pre[0]:
                max_pre = [pre, algor, k_best]
            if rec > max_rec[0]:
                max_rec = [rec, algor, k_best]
            if f > max_f[0]:
                max_f = [f, algor, k_best]
                best_clf = ['k-best', max_f, preview_clf]

    print ""
    print "Test k-best ", test
    print 'Accuracy: ', max_acc
    print 'Precision: ', max_pre
    print 'Reccal: ', max_rec
    print 'f Score: ', max_f

### We will do the same but decomponding the features using PCA (n° of componnents 1 to 19)
from sklearn.decomposition import PCA

for test in range(1,6):
    max_acc = [0, 'NaN', 'NaN']
    max_pre = [0, 'NaN', 'NaN']
    max_rec = [0, 'NaN', 'NaN']
    max_f = [0, 'NaN', 'NaN']
    for algor in classifiers:
        for n_comp in range(1, 17): #20):
            pca = PCA(n_components = n_comp)
            pipe = make_pipeline(pca, classifiers[algor])
            #pca_features = pca.fit_transform(features)
            preview_clf, acc, pre, rec, f = train_test_StratifiedKFold(pipe, "all", features)
            if acc > max_acc[0]:
                max_acc = [acc, algor, n_comp]
            if pre > max_pre[0]:
                max_pre = [pre, algor, n_comp]
            if rec > max_rec[0]:
                max_rec = [rec, algor, n_comp]
            if f > max_f[0]:
                max_f = [f, algor, n_comp]
            if f > best_clf[1][0]:
                best_clf = ['PCA', max_f, preview_clf]

    print ""
    print "Test PCA", test
    print 'Accuracy: ', max_acc
    print 'Precision: ', max_pre
    print 'Reccal: ', max_rec
    print 'f Score: ', max_f

# In[87]:

#--------------------------------------------------------
### Task 6: Dump your classifier, dataset, and features_list so anyone can
### check your results. You do not need to change anything below, but make sure
### that the version of poi_id.py that you submit can be run on its own and
### generates the necessary .pkl files for validating your results.

print "f classi: ", best_clf[1]
print "K-best or PCA: ", best_clf[0]
print "Classifier:"
print best_clf[2]

### The best classifier is
clf = best_clf[2]

dump_classifier_and_data(clf, my_dataset, features_list)
print ""
test_classifier(clf, my_dataset, features_list, folds = 1000)

print ""
print("--- %s seconds ---" % (time.time() - start_time))


import tensorflow as tf
import numpy as np
from functools import reduce

def get_data(train_file, test_file):
    """
    Read and parse the train and test file line by line, then tokenize the sentences to build the train and test data separately.
    Create a vocabulary dictionary that maps all the unique tokens from your train and test data as keys to a unique integer value.
    Then vectorize your train and test data based on your vocabulary dictionary.

    :param train_file: Path to the training file.
    :param test_file: Path to the test file.
    :return: Tuple of train (1-d list or array with training words in vectorized/id form), test (1-d list or array with testing words in vectorized/id form), vocabulary (Dict containg index->word mapping)
    """

    # TODO: load and concatenate training data from training file.

    # TODO: load and concatenate testing data from testing file.

    # TODO: read in and tokenize training data

    # TODO: read in and tokenize testing data

    # TODO: return tuple of training tokens, testing tokens, and the vocab dictionary.

    train_data=open(train_file, 'r')
    test_data=open(test_file, 'r')

    train=[]
    test=[]
    vocab_dict=dict()
    curr_id=0

    for line in train_data:
        words=line.split()
        for w in words:
            if w not in vocab_dict:
                vocab_dict[w]=curr_id
                curr_id+=1
            w_id=vocab_dict[w]
            train.append(w_id)
    train=np.array(train)

    for line in test_data:
        words=line.split()
        for w in words:
            if w not in vocab_dict:
                vocab_dict[w]=curr_id
                curr_id+=1
            w_id=vocab_dict[w]
            test.append(w_id)
    test=np.array(test)

    return vocab_dict,train,test


import numpy as np
from sortingComplexity import run

def test_basic_test():
    #asserts that the outputs of both algorithms in "basic test" are equivalent
    assert run.basic_test()

def test_complexity_experiment_and_vis():

    c,i = run.complexity_experiment()

    #format of output is correct (two dictionaries)
    assert type(c)==dict
    assert type(i)==dict


import math
import numpy

class Wave:

    """An helper class for Wave values  (vectors u, u_(i-1) etc. in
    the instructions). This class contains additional code for checking
    the correct shape of these vectors."""

    def __init__(self, values):
        assert type(values) == numpy.ndarray
        assert len(values.shape) == 1
        self.values = values

    def copy_from(self, values):

        """Copies data from the given NumPy array into this
        Wave vector."""

        assert type(values) == numpy.ndarray
        assert self.values.shape == values.shape

        self.values[:] = values[:]


# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Defines unit tests for :mod:`colour.adaptation.cie1994` module.
"""

from __future__ import division, unicode_literals

import numpy as np
import unittest
from itertools import permutations

from colour.adaptation import chromatic_adaptation_CIE1994
from colour.utilities import domain_range_scale, ignore_numpy_errors

__author__ = 'Colour Developers'
__copyright__ = 'Copyright (C) 2013-2019 - Colour Developers'
__license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause'
__maintainer__ = 'Colour Developers'
__email__ = 'colour-science@googlegroups.com'
__status__ = 'Production'

__all__ = ['TestChromaticAdaptationCIE1994']

class TestChromaticAdaptationCIE1994(unittest.TestCase):
    """
    Defines :func:`colour.adaptation.cie1994.chromatic_adaptation_CIE1994`
    definition unit tests methods.
    """

    def test_chromatic_adaptation_CIE1994(self):
        """
        Tests :func:`colour.adaptation.cie1994.chromatic_adaptation_CIE1994`
        definition.
        """

        np.testing.assert_almost_equal(
            chromatic_adaptation_CIE1994(
                XYZ_1=np.array([28.00, 21.26, 5.27]),
                xy_o1=np.array([0.44760, 0.40740]),
                xy_o2=np.array([0.31270, 0.32900]),
                Y_o=20,
                E_o1=1000,
                E_o2=1000),
            np.array([24.03379521, 21.15621214, 17.64301199]),
            decimal=7)

        np.testing.assert_almost_equal(
            chromatic_adaptation_CIE1994(
                XYZ_1=np.array([21.77, 19.18, 16.73]),
                xy_o1=np.array([0.31270, 0.32900]),
                xy_o2=np.array([0.31270, 0.32900]),
                Y_o=50,
                E_o1=100,
                E_o2=1000),
            np.array([21.12891746, 19.42980532, 19.49577765]),
            decimal=7)

        np.testing.assert_almost_equal(
            chromatic_adaptation_CIE1994(
                XYZ_1=np.array([0.07818780, 0.06157201, 0.28099326]) * 100,
                xy_o1=np.array([0.31270, 0.32900]),
                xy_o2=np.array([0.37208, 0.37529]),
                Y_o=20,
                E_o1=100,
                E_o2=1000),
            np.array([9.14287406, 9.35843355, 15.95753504]),
            decimal=7)

    def test_n_dimensional_chromatic_adaptation_CIE1994(self):
        """
        Tests :func:`colour.adaptation.cie1994.chromatic_adaptation_CIE1994`
        definition n-dimensional arrays support.
        """

        XYZ_1 = np.array([28.00, 21.26, 5.27])
        xy_o1 = np.array([0.44760, 0.40740])
        xy_o2 = np.array([0.31270, 0.32900])
        Y_o = 20
        E_o1 = 1000
        E_o2 = 1000
        XYZ_2 = chromatic_adaptation_CIE1994(XYZ_1, xy_o1, xy_o2, Y_o, E_o1,
                                             E_o2)

        XYZ_1 = np.tile(XYZ_1, (6, 1))
        XYZ_2 = np.tile(XYZ_2, (6, 1))
        np.testing.assert_almost_equal(
            chromatic_adaptation_CIE1994(XYZ_1, xy_o1, xy_o2, Y_o, E_o1, E_o2),
            XYZ_2,
            decimal=7)

        xy_o1 = np.tile(xy_o1, (6, 1))
        xy_o2 = np.tile(xy_o2, (6, 1))
        Y_o = np.tile(Y_o, 6)
        E_o1 = np.tile(E_o1, 6)
        E_o2 = np.tile(E_o2, 6)
        np.testing.assert_almost_equal(
            chromatic_adaptation_CIE1994(XYZ_1, xy_o1, xy_o2, Y_o, E_o1, E_o2),
            XYZ_2,
            decimal=7)

        XYZ_1 = np.reshape(XYZ_1, (2, 3, 3))
        xy_o1 = np.reshape(xy_o1, (2, 3, 2))
        xy_o2 = np.reshape(xy_o2, (2, 3, 2))
        Y_o = np.reshape(Y_o, (2, 3))
        E_o1 = np.reshape(E_o1, (2, 3))
        E_o2 = np.reshape(E_o2, (2, 3))
        XYZ_2 = np.reshape(XYZ_2, (2, 3, 3))
        np.testing.assert_almost_equal(
            chromatic_adaptation_CIE1994(XYZ_1, xy_o1, xy_o2, Y_o, E_o1, E_o2),
            XYZ_2,
            decimal=7)

    def test_domain_range_scale_chromatic_adaptation_CIE1994(self):
        """
        Tests :func:`colour.adaptation.cie1994.chromatic_adaptation_CIE1994`
        definition domain and range scale support.
        """

        XYZ_1 = np.array([28.00, 21.26, 5.27])
        xy_o1 = np.array([0.44760, 0.40740])
        xy_o2 = np.array([0.31270, 0.32900])
        Y_o = 20
        E_o1 = 1000
        E_o2 = 1000
        XYZ_2 = chromatic_adaptation_CIE1994(XYZ_1, xy_o1, xy_o2, Y_o, E_o1,
                                             E_o2)

        d_r = (('reference', 1), (1, 0.01), (100, 1))
        for scale, factor in d_r:
            with domain_range_scale(scale):
                np.testing.assert_almost_equal(
                    chromatic_adaptation_CIE1994(XYZ_1 * factor, xy_o1, xy_o2,
                                                 Y_o * factor, E_o1, E_o2),
                    XYZ_2 * factor,
                    decimal=7)

    @ignore_numpy_errors
    def test_nan_chromatic_adaptation_CIE1994(self):
        """
        Tests :func:`colour.adaptation.cie1994.chromatic_adaptation_CIE1994`
        definition nan support.
        """

        cases = [-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan]
        cases = set(permutations(cases * 3, r=3))
        for case in cases:
            XYZ_1 = np.array(case)
            xy_o1 = np.array(case[0:2])
            xy_o2 = np.array(case[0:2])
            Y_o = case[0]
            E_o1 = case[0]
            E_o2 = case[0]
            chromatic_adaptation_CIE1994(XYZ_1, xy_o1, xy_o2, Y_o, E_o1, E_o2)

if __name__ == '__main__':
    unittest.main()


# Introduction to Lists and Arrays

L1 = list()
L2 = []

L3 = [3,4,1,6,7,5]
L4 = [[2, 9, -5], [-1, 0, 4], [3, 1, 2]]

import numpy as np
nparray = np.zeros((5,5))

Chapter 03/Lists and Arrays/listsAndArrays.py


#!/usr/bin/env python
# coding: utf-8

# # K-mer
# Basic K-mer counting.

# In[1]:

import time
def show_time():
    t = time.time()
    print(time.strftime('%Y-%m-%d %H:%M:%S %Z', time.localtime(t)))
show_time()

# In[2]:

PC_SEQUENCES=32000
NC_SEQUENCES=32000
RNA_LEN=32
CDS_LEN=16

# In[3]:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# In[4]:

import sys
IN_COLAB = False
try:
    from google.colab import drive
    IN_COLAB = True
except:
    pass
if IN_COLAB:
    print("On Google CoLab, mount cloud-local file, get our code from GitHub.")
    PATH='/content/drive/'
    #drive.mount(PATH,force_remount=True)  # hardly ever need this
    #drive.mount(PATH)    # Google will require login credentials
    DATAPATH=PATH+'My Drive/data/'  # must end in "/"
    import requests
    r = requests.get('https://raw.githubusercontent.com/ShepherdCode/Soars2021/master/SimTools/RNA_describe.py')
    with open('RNA_describe.py', 'w') as f:
        f.write(r.text)
    from RNA_describe import Random_Base_Oracle
else:
        print("CoLab not working. On my PC, use relative paths.")
        DATAPATH='data/'  # must end in "/"
        sys.path.append("..") # append parent dir in order to use sibling dirs
        from SimTools.RNA_describe import Random_Base_Oracle
MODELPATH="BestModel"  # saved on cloud instance and lost after logout
#MODELPATH=DATAPATH+MODELPATH  # saved on Google Drive but requires login

# ## K-mer counting

# ### Functions to create the dict of {kmer:count}

# In[5]:

def make_kmer_keys(K):
    shorter_kmers=['']
    for i in range(K):
        longer_kmers=[]
        for mer in shorter_kmers:
            # No support for N or any non-ACGT bases.
            longer_kmers.append(mer+'A')
            longer_kmers.append(mer+'C')
            longer_kmers.append(mer+'G')
            longer_kmers.append(mer+'T')
        shorter_kmers = longer_kmers
    return shorter_kmers
def make_kmer_dict(keys,init=0):
    return dict.fromkeys(keys,init)
def make_dict_upto_K(max_K):
    keys=make_kmer_keys(1)
    for k in range(2,max_K+1):
        keys.extend(make_kmer_keys(k))
    counts = make_kmer_dict(keys)
    return counts

# ### Naive K-mer counting algorithm
# Algorithm:
# 1. for every string
#     1. for every K
#         1. for every position
#             1. kmer=substring
#             2. count{kmer}++

# In[6]:

def update_count_one_K(counts,K,rna,tail=False):
    L = len(rna)
    padding=" "*(K-1)
    padded=rna+padding
    for i in range(0,L-K+1):
        kmer=padded[i:i+K]
        counts[kmer] += 1
    if tail and K>1:
        # for Harvester algorithm, count last letters as special case
        for start_pos in range(L-K+1,L):
            for end_pos in range(start_pos+1,L+1):
                kmer=rna[start_pos:end_pos]
                counts[kmer] += 1
    return counts
def update_count_upto_K(counts,max_K,sample,tail=False):
    for i in range(1,max_K+1):
        update_count_one_K(counts,i,sample,tail)
    return counts

# ### Harvester K-mer counting algorithm
# Algorithm:
# 1. Count K-mers for max K only
# 2. For each K-mer in counts table:
#     1. For every prefix of the K-mer:
#         1. count{prefix} += count{kmer}
# 3. Handle last K-1 letters of each string as special case

# In[7]:

def harvest_counts_from_K(counts,max_K):
    for kmer in counts.keys():
        klen = len(kmer)
        kcnt = counts[kmer]
        if klen==max_K and kcnt>0:
            for i in range(1,klen):
                prefix = kmer[:i]
                counts[prefix] += kcnt
    return counts

# In[8]:

def count_to_frequency(counts,max_K):
    freqs = dict.fromkeys(counts.keys(),0.0)
    for k in range(1,max_K+1):
        tot = 0
        for kmer in counts.keys():
            if len(kmer)==k:
                tot += counts[kmer]
        for kmer in counts.keys():
            if len(kmer)==k:
                freqs[kmer] = 1.0*counts[kmer]/tot
    return freqs

# ## Demo

# ### Demo: Naive algorithm

# In[9]:

MAX_K = 3
counts1 = make_dict_upto_K(MAX_K)
print("Initial counts:\n",counts1)

sample = "ACCGGGTTTTACGTACGT"
update_count_upto_K(counts1,MAX_K,sample)
print("Final counts:\n",counts1)

# ### Demo: Harvester algorithm

# In[10]:

MAX_K = 3
counts2 = make_dict_upto_K(MAX_K)
print("Initial counts:\n",counts2)

sample = "ACCGGGTTTTACGTACGT"
update_count_one_K(counts2,MAX_K,sample,True)
print("Partial counts (just max K and special case letters)\n:",counts2)
harvest_counts_from_K(counts2,MAX_K)
print("Final counts (includes smaller values of K):\n",counts2)

# In[11]:

if counts1==counts2:
    print("Success. Harvester output matches naive results!")
else:
    print("Fail. Harvester output differs from naive results!")

# In[12]:

freqs = count_to_frequency(counts2,MAX_K)
print ("Frequency:\n",freqs)

# ## Demo on large dataset

# In[13]:

rbo=Random_Base_Oracle(RNA_LEN,True)
pc_all,nc_all = rbo.get_partitioned_sequences(CDS_LEN,10) # just testing
pc_all,nc_all = rbo.get_partitioned_sequences(CDS_LEN,PC_SEQUENCES)
print("Use",len(pc_all),"PC seqs")
print("Use",len(nc_all),"NC seqs")

# In[14]:

MAX_K = 3
pc_counts = make_dict_upto_K(MAX_K)
for sample in pc_all:
    update_count_one_K(pc_counts,MAX_K,sample,True)
harvest_counts_from_K(pc_counts,MAX_K)
print("PC counts:\n",pc_counts)
pc_freqs = count_to_frequency(pc_counts,MAX_K)
print ("Frequency:\n",pc_freqs)

# In[15]:

nc_counts = make_dict_upto_K(MAX_K)
for sample in nc_all:
    update_count_one_K(nc_counts,MAX_K,sample,True)
harvest_counts_from_K(nc_counts,MAX_K)
print("NC counts:\n",nc_counts)
nc_freqs = count_to_frequency(nc_counts,MAX_K)
print ("Frequency:\n",nc_freqs)

# In[ ]:


#example of two dimensional array
import numpy as np

my_list1 =[1,2,3,4]
my_list2=[6,7,8,9]

#my_array1=np.array(my_list1)

my_array=np.array([my_list1,my_list2])

print my_array


#
#  File:
#    hov_1.py
#
#  Synopsis:
#    Default black and white Hovmueller plot.
#
#  Category:
#    contour plot
#
#  Based on NCL example:
#    hov_1.ncl
#
#  Author:
#    Karin Meier-Fleischer
#
#  Date of initial publication:
#    November, 2018
#
#  Description:
#    This example shows how to create a default black and white Hovmueller plot.
#
#  Effects illustrated:
#    o  Creating a Hovmueller plot
#    o  Using text function codes to generate umlauts
#
#  Output:
#     A single visualization is produced.
#
'''
  PyNGL Example: 	hov_1.py

  -  Creating a Hovmueller plot
  -  Using text function codes to generate umlauts

'''
from __future__ import print_function
import numpy as np
import os, sys
import Ngl,Nio

#-------------------------------------------------------
#-- Function:	add_titles(wks,plot,resources,title,left,center,right)
#-------------------------------------------------------
def add_titles(wks,plot,title="",left="",center="",right=""):

   vpx = Ngl.get_float(plot,"vpXF")             #-- retrieve value of res.vpXF from plot
   vpy = Ngl.get_float(plot,"vpYF")             #-- retrieve value of res.vpYF from plot
   vpw = Ngl.get_float(plot,"vpWidthF")         #-- retrieve value of res.vpWidthF from plot
   vph = Ngl.get_float(plot,"vpHeightF")        #-- retrieve value of res.vpHeightF from plot

   ymax = vpy+0.08                              #-- we need space for the title and strings

   if(ymax > 0.98):
     print("--> if you can't see the title use res.nglMaximize = False and/or set res.vpYF")

#-- add title
   if(title != ""):
      tires = Ngl.Resources()
      tires.txFontHeightF =  0.018
      tires.txJust        = "CenterCenter"
      tires.txFont        =  22                     #-- Font 22: Helvetica bold
      if(left != "" or center != "" or right != ""):
         y = vpy + 0.07
      else:
         y = vpy + 0.05
      Ngl.text_ndc(wks, title, 0.5, y, tires)

#-- add left, center and/or right string
   txres = Ngl.Resources()
   txres.txFontHeightF = 0.014                  #-- font size for left, center and right string

   y = vpy + 0.035                              #-- y-position

   if(left != ""):
      txres.txJust = "CenterLeft"               #-- text justification
      x = vpx                                   #-- x-position
      Ngl.text_ndc(wks, left, x, y, txres)      #-- add text to wks

   if(center != ""):
      txres.txJust = "CenterCenter"             #-- text justification
      Ngl.text_ndc(wks, center, 0.5, y, txres)  #-- add text to wks

   if(right != ""):
      txres.txJust = "CenterRight"              #-- text justification
      x = vpx+vpw                               #-- x-position
      Ngl.text_ndc(wks, right, x, y, txres)     #-- add text to wks

#-------------------------------------------------------
#--              MAIN
#-------------------------------------------------------
#-- data path and file name
ncarg_root = os.environ.get('NCARG_ROOT')
diri  = ncarg_root + '/lib/ncarg/data/cdf/'
fname = 'chi200_ud_smooth.nc'

#-- open file and read variables
f     =  Nio.open_file(diri + fname,"r")    #-- open data file
chi   =  f.variables['CHI'][:,:]            #-- read variable CHI[time,lon]
lon   =  f.variables['lon'][:]
time  =  f.variables['time'][:]

scale =  1.0e6
chi   =  chi/scale

#-- create the plot
wks =  Ngl.open_wks('png','plot_hovmueller')
                                            #-- open workstation
#-- set resources
res                       =  Ngl.Resources
res.nglFrame              =  False
res.nglMaximize           =  False          #-- maximize plot output

#res.tiMainString          = 'Default Hovmu~H-13V2F35~H~FV-2H3~ller' #-- title

res.sfXArray              =  lon            #-- scalar field x
res.sfYArray              =  time           #-- scalar field y

res.tiYAxisString         = 'elapsed time'
res.tmYLLabelFontHeightF  =  0.015

res.nglPointTickmarksOutward = True         #-- point tickmarks out

plot = Ngl.contour(wks,chi,res)             #-- draw contours

#-- delete resources because they will cause warnings (Why?)
del([res.sfXArray,res.sfYArray,res.tiYAxisString,res.tmYLLabelFontHeightF])

#-- add the title and left, center and/or right string
title     = "Default Hovmu~H-13V2F35~H~FV-2H3~ller"
long_name = f.variables["CHI"].attributes['long_name']
units     = f.variables["CHI"].attributes['units']

add_titles(wks,plot,title,left=long_name,right=units)

#-- advance the frame
Ngl.frame(wks)

#-- end
Ngl.end()