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

# # Naive Bayes
# Welcome to week two of this specialization. You will learn about Naive Bayes. Concretely, you will be using Naive Bayes for sentiment analysis on tweets. Given a tweet, you will decide if it has a positive sentiment or a negative one. Specifically you will:
#
# * Train a naive bayes model on a sentiment analysis task
# * Test using your model
# * Compute ratios of positive words to negative words
# * Do some error analysis
# * Predict on your own tweet
#
# You may already be familiar with Naive Bayes and its justification in terms of conditional probabilities and independence.
# * In this week's lectures and assignments we used the ratio of probabilities between positive and negative sentiments.
# * This approach gives us simpler formulas for these 2-way classification tasks.
#
# Load the cell below to import some packages.
# You  may want to browse the documentation of unfamiliar libraries and functions.

# In[2]:

from utils import process_tweet, lookup
import pdb
from nltk.corpus import stopwords, twitter_samples
import numpy as np
import pandas as pd
import nltk
import string
from nltk.tokenize import TweetTokenizer
from os import getcwd

# If you are running this notebook in your local computer,
# don't forget to download the twitter samples and stopwords from nltk.
#
# ```
# nltk.download('stopwords')
# nltk.download('twitter_samples')
# ```

# In[3]:

# add folder, tmp2, from our local workspace containing pre-downloaded corpora files to nltk's data path
filePath = f"{getcwd()}/../tmp2/"
nltk.data.path.append(filePath)

# In[4]:

# get the sets of positive and negative tweets
all_positive_tweets = twitter_samples.strings('positive_tweets.json')
all_negative_tweets = twitter_samples.strings('negative_tweets.json')

# split the data into two pieces, one for training and one for testing (validation set)
test_pos = all_positive_tweets[4000:]
train_pos = all_positive_tweets[:4000]
test_neg = all_negative_tweets[4000:]
train_neg = all_negative_tweets[:4000]

train_x = train_pos + train_neg
test_x = test_pos + test_neg

# avoid assumptions about the length of all_positive_tweets
train_y = np.append(np.ones(len(train_pos)), np.zeros(len(train_neg)))
test_y = np.append(np.ones(len(test_pos)), np.zeros(len(test_neg)))

# # Part 1: Process the Data
#
# For any machine learning project, once you've gathered the data, the first step is to process it to make useful inputs to your model.
# - **Remove noise**: You will first want to remove noise from your data -- that is, remove words that don't tell you much about the content. These include all common words like 'I, you, are, is, etc...' that would not give us enough information on the sentiment.
# - We'll also remove stock market tickers, retweet symbols, hyperlinks, and hashtags because they can not tell you a lot of information on the sentiment.
# - You also want to remove all the punctuation from a tweet. The reason for doing this is because we want to treat words with or without the punctuation as the same word, instead of treating "happy", "happy?", "happy!", "happy," and "happy." as different words.
# - Finally you want to use stemming to only keep track of one variation of each word. In other words, we'll treat "motivation", "motivated", and "motivate" similarly by grouping them within the same stem of "motiv-".
#
# We have given you the function `process_tweet()` that does this for you.

# In[5]:

custom_tweet = "RT @Twitter @chapagain Hello There! Have a great day. :) #good #morning http://chapagain.com.np"

# print cleaned tweet
print(process_tweet(custom_tweet))

# ## Part 1.1 Implementing your helper functions
#
# To help train your naive bayes model, you will need to build a dictionary where the keys are a (word, label) tuple and the values are the corresponding frequency.  Note that the labels we'll use here are 1 for positive and 0 for negative.
#
# You will also implement a `lookup()` helper function that takes in the `freqs` dictionary, a word, and a label (1 or 0) and returns the number of times that word and label tuple appears in the collection of tweets.
#
# For example: given a list of tweets `["i am rather excited", "you are rather happy"]` and the label 1, the function will return a dictionary that contains the following key-value pairs:
#
# {
#     ("rather", 1): 2
#     ("happi", 1) : 1
#     ("excit", 1) : 1
# }
#
# - Notice how for each word in the given string, the same label 1 is assigned to each word.
# - Notice how the words "i" and "am" are not saved, since it was removed by process_tweet because it is a stopword.
# - Notice how the word "rather" appears twice in the list of tweets, and so its count value is 2.
#
# #### Instructions
# Create a function `count_tweets()` that takes a list of tweets as input, cleans all of them, and returns a dictionary.
# - The key in the dictionary is a tuple containing the stemmed word and its class label, e.g. ("happi",1).
# - The value the number of times this word appears in the given collection of tweets (an integer).

#
#
#     Hints
#
#

#

#
Please use the `process_tweet` function that was imported above, and then store the words in their respective dictionaries and sets.

#
You may find it useful to use the `zip` function to match each element in `tweets` with each element in `ys`.

#
Remember to check if the key in the dictionary exists before adding that key to the dictionary, or incrementing its value.

#
Assume that the `result` dictionary that is input will contain clean key-value pairs (you can assume that the values will be integers that can be incremented).  It is good practice to check the datatype before incrementing the value, but it's not required here.

#

#

# In[6]:

# UNQ_C1 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
def count_tweets(result, tweets, ys):
    '''
    Input:
        result: a dictionary that will be used to map each pair to its frequency
        tweets: a list of tweets
        ys: a list corresponding to the sentiment of each tweet (either 0 or 1)
    Output:
        result: a dictionary mapping each pair to its frequency
    '''

    ### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ###
    for y, tweet in zip(ys, tweets):
        for word in process_tweet(tweet):
            # define the key, which is the word and label tuple
            pair = (word, y)

            # if the key exists in the dictionary, increment the count
            if pair in result:
                result[pair] += 1

            # else, if the key is new, add it to the dictionary and set the count to 1
            else:
                result[pair] = 1
    ### END CODE HERE ###

    return result

# In[7]:

# Testing your function

result = {}
tweets = ['i am happy', 'i am tricked', 'i am sad', 'i am tired', 'i am tired']
ys = [1, 0, 0, 0, 0]
count_tweets(result, tweets, ys)

# **Expected Output**: {('happi', 1): 1, ('trick', 0): 1, ('sad', 0): 1, ('tire', 0): 2}

# # Part 2: Train your model using Naive Bayes
#
# Naive bayes is an algorithm that could be used for sentiment analysis. It takes a short time to train and also has a short prediction time.
#
# #### So how do you train a Naive Bayes classifier?
# - The first part of training a naive bayes classifier is to identify the number of classes that you have.
# - You will create a probability for each class.
# $P(D_{pos})$ is the probability that the document is positive.
# $P(D_{neg})$ is the probability that the document is negative.
# Use the formulas as follows and store the values in a dictionary:
#
# $$P(D_{pos}) = \frac{D_{pos}}{D}\tag{1}$$
#
# $$P(D_{neg}) = \frac{D_{neg}}{D}\tag{2}$$
#
# Where $D$ is the total number of documents, or tweets in this case, $D_{pos}$ is the total number of positive tweets and $D_{neg}$ is the total number of negative tweets.

# #### Prior and Logprior
#
# The prior probability represents the underlying probability in the target population that a tweet is positive versus negative.  In other words, if we had no specific information and blindly picked a tweet out of the population set, what is the probability that it will be positive versus that it will be negative? That is the "prior".
#
# The prior is the ratio of the probabilities $\frac{P(D_{pos})}{P(D_{neg})}$.
# We can take the log of the prior to rescale it, and we'll call this the logprior
#
# $$\text{logprior} = log \left( \frac{P(D_{pos})}{P(D_{neg})} \right) = log \left( \frac{D_{pos}}{D_{neg}} \right)$$.
#
# Note that $log(\frac{A}{B})$ is the same as $log(A) - log(B)$.  So the logprior can also be calculated as the difference between two logs:
#
# $$\text{logprior} = \log (P(D_{pos})) - \log (P(D_{neg})) = \log (D_{pos}) - \log (D_{neg})\tag{3}$$

# #### Positive and Negative Probability of a Word
# To compute the positive probability and the negative probability for a specific word in the vocabulary, we'll use the following inputs:
#
# - $freq_{pos}$ and $freq_{neg}$ are the frequencies of that specific word in the positive or negative class. In other words, the positive frequency of a word is the number of times the word is counted with the label of 1.
# - $N_{pos}$ and $N_{neg}$ are the total number of positive and negative words for all documents (for all tweets), respectively.
# - $V$ is the number of unique words in the entire set of documents, for all classes, whether positive or negative.
#
# We'll use these to compute the positive and negative probability for a specific word using this formula:
#
# $$ P(W_{pos}) = \frac{freq_{pos} + 1}{N_{pos} + V}\tag{4} $$
# $$ P(W_{neg}) = \frac{freq_{neg} + 1}{N_{neg} + V}\tag{5} $$
#
# Notice that we add the "+1" in the numerator for additive smoothing.  This [wiki article](https://en.wikipedia.org/wiki/Additive_smoothing) explains more about additive smoothing.

# #### Log likelihood
# To compute the loglikelihood of that very same word, we can implement the following equations:
#
# $$\text{loglikelihood} = \log \left(\frac{P(W_{pos})}{P(W_{neg})} \right)\tag{6}$$

# ##### Create `freqs` dictionary
# - Given your `count_tweets()` function, you can compute a dictionary called `freqs` that contains all the frequencies.
# - In this `freqs` dictionary, the key is the tuple (word, label)
# - The value is the number of times it has appeared.
#
# We will use this dictionary in several parts of this assignment.

# In[8]:

# Build the freqs dictionary for later uses

freqs = count_tweets({}, train_x, train_y)

# #### Instructions
# Given a freqs dictionary, `train_x` (a list of tweets) and a `train_y` (a list of labels for each tweet), implement a naive bayes classifier.
#
# ##### Calculate $V$
# - You can then compute the number of unique words that appear in the `freqs` dictionary to get your $V$ (you can use the `set` function).
#
# ##### Calculate $freq_{pos}$ and $freq_{neg}$
# - Using your `freqs` dictionary, you can compute the positive and negative frequency of each word $freq_{pos}$ and $freq_{neg}$.
#
# ##### Calculate $N_{pos}$ and $N_{neg}$
# - Using `freqs` dictionary, you can also compute the total number of positive words and total number of negative words $N_{pos}$ and $N_{neg}$.
#
# ##### Calculate $D$, $D_{pos}$, $D_{neg}$
# - Using the `train_y` input list of labels, calculate the number of documents (tweets) $D$, as well as the number of positive documents (tweets) $D_{pos}$ and number of negative documents (tweets) $D_{neg}$.
# - Calculate the probability that a document (tweet) is positive $P(D_{pos})$, and the probability that a document (tweet) is negative $P(D_{neg})$
#
# ##### Calculate the logprior
# - the logprior is $log(D_{pos}) - log(D_{neg})$
#
# ##### Calculate log likelihood
# - Finally, you can iterate over each word in the vocabulary, use your `lookup` function to get the positive frequencies, $freq_{pos}$, and the negative frequencies, $freq_{neg}$, for that specific word.
# - Compute the positive probability of each word $P(W_{pos})$, negative probability of each word $P(W_{neg})$ using equations 4 & 5.
#
# $$ P(W_{pos}) = \frac{freq_{pos} + 1}{N_{pos} + V}\tag{4} $$
# $$ P(W_{neg}) = \frac{freq_{neg} + 1}{N_{neg} + V}\tag{5} $$
#
# **Note:** We'll use a dictionary to store the log likelihoods for each word.  The key is the word, the value is the log likelihood of that word).
#
# - You can then compute the loglikelihood: $log \left( \frac{P(W_{pos})}{P(W_{neg})} \right)\tag{6}$.

# In[24]:

# UNQ_C2 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
def train_naive_bayes(freqs, train_x, train_y):
    '''
    Input:
        freqs: dictionary from (word, label) to how often the word appears
        train_x: a list of tweets
        train_y: a list of labels correponding to the tweets (0,1)
    Output:
        logprior: the log prior. (equation 3 above)
        loglikelihood: the log likelihood of you Naive bayes equation. (equation 6 above)
    '''
    loglikelihood = {}
    logprior = 0

    ### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ###

    # calculate V, the number of unique words in the vocabulary
    vocab = set([pair[0] for pair in freqs.keys()])
    V = len(vocab)

    # calculate N_pos and N_neg
    N_pos = N_neg = 0

    for pair in freqs.keys():
        # if the label is positive (greater than zero)
        if pair[1] > 0:

            # Increment the number of positive words by the count for this (word, label) pair
            N_pos += freqs[pair]

        # else, the label is negative
        else:

            # increment the number of negative words by the count for this (word,label) pair
            N_neg += freqs[pair]

    # Calculate D, the number of documents
    D = len(train_y)

    # Calculate D_pos, the number of positive documents (*hint: use sum(<np_array>))
    D_pos = (train_y == 1).sum()

    # Calculate D_neg, the number of negative documents (*hint: compute using D and D_pos)
    D_neg = (train_y == 0).sum()

    # Calculate logprior
    logprior = np.log(D_pos) - np.log(D_neg)

    # For each word in the vocabulary...
    for word in vocab:
        # get the positive and negative frequency of the word
        if (word, 1) in freqs:
            freq_pos = freqs[(word, 1)]
        else:
            freq_pos = 0

        if (word, 0) in freqs:
            freq_neg = freqs[(word, 0)]
        else:
            freq_neg = 0

        # calculate the probability that each word is positive, and negative
        p_w_pos = (freq_pos + 1)/ (V + N_pos)
        p_w_neg = (freq_neg + 1)/ (V + N_neg)

        # calculate the log likelihood of the word
        loglikelihood[word] = np.log(p_w_pos) - np.log(p_w_neg)

    ### END CODE HERE ###

    return logprior, loglikelihood

# In[25]:

# UNQ_C3 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
# You do not have to input any code in this cell, but it is relevant to grading, so please do not change anything
logprior, loglikelihood = train_naive_bayes(freqs, train_x, train_y)
print(logprior)
print(len(loglikelihood))

# **Expected Output**:
#
# 0.0
#
# 9089

# # Part 3: Test your naive bayes
#
# Now that we have the `logprior` and `loglikelihood`, we can test the naive bayes function by making predicting on some tweets!
#
# #### Implement `naive_bayes_predict`
# **Instructions**:
# Implement the `naive_bayes_predict` function to make predictions on tweets.
# * The function takes in the `tweet`, `logprior`, `loglikelihood`.
# * It returns the probability that the tweet belongs to the positive or negative class.
# * For each tweet, sum up loglikelihoods of each word in the tweet.
# * Also add the logprior to this sum to get the predicted sentiment of that tweet.
#
# $$ p = logprior + \sum_i^N (loglikelihood_i)$$
#
# #### Note
# Note we calculate the prior from the training data, and that the training data is evenly split between positive and negative labels (4000 positive and 4000 negative tweets).  This means that the ratio of positive to negative 1, and the logprior is 0.
#
# The value of 0.0 means that when we add the logprior to the log likelihood, we're just adding zero to the log likelihood.  However, please remember to include the logprior, because whenever the data is not perfectly balanced, the logprior will be a non-zero value.

# In[19]:

# UNQ_C4 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
def naive_bayes_predict(tweet, logprior, loglikelihood):
    '''
    Input:
        tweet: a string
        logprior: a number
        loglikelihood: a dictionary of words mapping to numbers
    Output:
        p: the sum of all the logliklihoods of each word in the tweet (if found in the dictionary) + logprior (a number)

    '''
    ### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ###
    # process the tweet to get a list of words
    word_l = process_tweet(tweet)

    # initialize probability to zero
    p = 0

    # add the logprior
    p += logprior

    for word in word_l:

        # check if the word exists in the loglikelihood dictionary
        if word in loglikelihood:
            # add the log likelihood of that word to the probability
            p += loglikelihood[word]

    ### END CODE HERE ###

    return p

# In[26]:

# UNQ_C5 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
# You do not have to input any code in this cell, but it is relevant to grading, so please do not change anything

# Experiment with your own tweet.
my_tweet = 'She smiled.'
p = naive_bayes_predict(my_tweet, logprior, loglikelihood)
print('The expected output is', p)

# **Expected Output**:
# - The expected output is around 1.57
# - The sentiment is positive.

# #### Implement test_naive_bayes
# **Instructions**:
# * Implement `test_naive_bayes` to check the accuracy of your predictions.
# * The function takes in your `test_x`, `test_y`, log_prior, and loglikelihood
# * It returns the accuracy of your model.
# * First, use `naive_bayes_predict` function to make predictions for each tweet in text_x.

# In[27]:

# UNQ_C6 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
def test_naive_bayes(test_x, test_y, logprior, loglikelihood):
    """
    Input:
        test_x: A list of tweets
        test_y: the corresponding labels for the list of tweets
        logprior: the logprior
        loglikelihood: a dictionary with the loglikelihoods for each word
    Output:
        accuracy: (# of tweets classified correctly)/(total # of tweets)
    """
    accuracy = 0  # return this properly

    ### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ###
    y_hats = []
    for tweet in test_x:
        # if the prediction is > 0
        if naive_bayes_predict(tweet, logprior, loglikelihood) > 0:
            # the predicted class is 1
            y_hat_i = 1
        else:
            # otherwise the predicted class is 0
            y_hat_i = 0

        # append the predicted class to the list y_hats
        y_hats.append(y_hat_i)

    # error is the average of the absolute values of the differences between y_hats and test_y
    error = (1/len(test_y))*(test_y != y_hats).sum()

    # Accuracy is 1 minus the error
    accuracy = 1- error

    ### END CODE HERE ###

    return accuracy

# In[28]:

print("Naive Bayes accuracy = %0.4f" %
      (test_naive_bayes(test_x, test_y, logprior, loglikelihood)))

# **Expected Accuracy**:
#
# 0.9940

# In[29]:

# UNQ_C7 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
# You do not have to input any code in this cell, but it is relevant to grading, so please do not change anything

# Run this cell to test your function
for tweet in ['I am happy', 'I am bad', 'this movie should have been great.', 'great', 'great great', 'great great great', 'great great great great']:
    # print( '%s -> %f' % (tweet, naive_bayes_predict(tweet, logprior, loglikelihood)))
    p = naive_bayes_predict(tweet, logprior, loglikelihood)
#     print(f'{tweet} -> {p:.2f} ({p_category})')
    print(f'{tweet} -> {p:.2f}')

# **Expected Output**:
# - I am happy -> 2.15
# - I am bad -> -1.29
# - this movie should have been great. -> 2.14
# - great -> 2.14
# - great great -> 4.28
# - great great great -> 6.41
# - great great great great -> 8.55

# In[30]:

# Feel free to check the sentiment of your own tweet below
my_tweet = 'you are bad :('
naive_bayes_predict(my_tweet, logprior, loglikelihood)

# # Part 4: Filter words by Ratio of positive to negative counts
#
# - Some words have more positive counts than others, and can be considered "more positive".  Likewise, some words can be considered more negative than others.
# - One way for us to define the level of positiveness or negativeness, without calculating the log likelihood, is to compare the positive to negative frequency of the word.
#     - Note that we can also use the log likelihood calculations to compare relative positivity or negativity of words.
# - We can calculate the ratio of positive to negative frequencies of a word.
# - Once we're able to calculate these ratios, we can also filter a subset of words that have a minimum ratio of positivity / negativity or higher.
# - Similarly, we can also filter a subset of words that have a maximum ratio of positivity / negativity or lower (words that are at least as negative, or even more negative than a given threshold).
#
# #### Implement `get_ratio()`
# - Given the `freqs` dictionary of words and a particular word, use `lookup(freqs,word,1)` to get the positive count of the word.
# - Similarly, use the `lookup()` function to get the negative count of that word.
# - Calculate the ratio of positive divided by negative counts
#
# $$ ratio = \frac{\text{pos_words} + 1}{\text{neg_words} + 1} $$
#
# Where pos_words and neg_words correspond to the frequency of the words in their respective classes.
#

#

#
#             Words
#
#
#         Positive word count
#
#
#         Negative Word Count
#
#

#

#
#         glad
#
#
#         41
#
#
#         2
#
#

#

#
#         arriv
#
#
#         57
#
#
#         4
#
#

#

#
#         :(
#
#
#         1
#
#
#         3663
#
#

#

#
#         :-(
#
#
#         0
#
#
#         378
#
#

#

# In[31]:

# UNQ_C8 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
def get_ratio(freqs, word):
    '''
    Input:
        freqs: dictionary containing the words
        word: string to lookup

    Output: a dictionary with keys 'positive', 'negative', and 'ratio'.
        Example: {'positive': 10, 'negative': 20, 'ratio': 0.5}
    '''
    pos_neg_ratio = {'positive': 0, 'negative': 0, 'ratio': 0.0}
    ### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ###
    # use lookup() to find positive counts for the word (denoted by the integer 1)
    pos_neg_ratio['positive'] = lookup(freqs, word, 1)

    # use lookup() to find negative counts for the word (denoted by integer 0)
    pos_neg_ratio['negative'] = lookup(freqs, word, 0)

    # calculate the ratio of positive to negative counts for the word
    pos_neg_ratio['ratio'] = (pos_neg_ratio['positive'] + 1)/( pos_neg_ratio['negative'] + 1)
    ### END CODE HERE ###
    return pos_neg_ratio

# In[32]:

get_ratio(freqs, 'happi')

# #### Implement `get_words_by_threshold(freqs,label,threshold)`
#
# * If we set the label to 1, then we'll look for all words whose threshold of positive/negative is at least as high as that threshold, or higher.
# * If we set the label to 0, then we'll look for all words whose threshold of positive/negative is at most as low as the given threshold, or lower.
# * Use the `get_ratio()` function to get a dictionary containing the positive count, negative count, and the ratio of positive to negative counts.
# * Append a dictionary to a list, where the key is the word, and the dictionary is the dictionary `pos_neg_ratio` that is returned by the `get_ratio()` function.
# An example key-value pair would have this structure:
# ```
# {'happi':
#     {'positive': 10, 'negative': 20, 'ratio': 0.5}
# }
# ```

# In[35]:

# UNQ_C9 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
def get_words_by_threshold(freqs, label, threshold):
    '''
    Input:
        freqs: dictionary of words
        label: 1 for positive, 0 for negative
        threshold: ratio that will be used as the cutoff for including a word in the returned dictionary
    Output:
        word_set: dictionary containing the word and information on its positive count, negative count, and ratio of positive to negative counts.
        example of a key value pair:
        {'happi':
            {'positive': 10, 'negative': 20, 'ratio': 0.5}
        }
    '''
    word_list = {}

    ### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ###
    for key in freqs.keys():
        word, _ = key

        # get the positive/negative ratio for a word
        pos_neg_ratio = get_ratio(freqs, word)['ratio']

        # if the label is 1 and the ratio is greater than or equal to the threshold...
        if label == 1 and pos_neg_ratio >= threshold:

            # Add the pos_neg_ratio to the dictionary
            word_list[word] = pos_neg_ratio

        # If the label is 0 and the pos_neg_ratio is less than or equal to the threshold...
        elif label == 0 and pos_neg_ratio <= threshold:

            # Add the pos_neg_ratio to the dictionary
            word_list[word] = pos_neg_ratio

        # otherwise, do not include this word in the list (do nothing)

    ### END CODE HERE ###
    return word_list

# In[36]:

# Test your function: find negative words at or below a threshold
get_words_by_threshold(freqs, label=0, threshold=0.05)

# In[37]:

# Test your function; find positive words at or above a threshold
get_words_by_threshold(freqs, label=1, threshold=10)

# Notice the difference between the positive and negative ratios. Emojis like :( and words like 'me' tend to have a negative connotation. Other words like 'glad', 'community', and 'arrives' tend to be found in the positive tweets.

# # Part 5: Error Analysis
#
# In this part you will see some tweets that your model missclassified. Why do you think the misclassifications happened? Were there any assumptions made by the naive bayes model?

# In[38]:

# Some error analysis done for you
print('Truth Predicted Tweet')
for x, y in zip(test_x, test_y):
    y_hat = naive_bayes_predict(x, logprior, loglikelihood)
    if y != (np.sign(y_hat) > 0):
        print('%d\t%0.2f\t%s' % (y, np.sign(y_hat) > 0, ' '.join(
            process_tweet(x)).encode('ascii', 'ignore')))

# # Part 6: Predict with your own tweet
#
# In this part you can predict the sentiment of your own tweet.

# In[39]:

# Test with your own tweet - feel free to modify `my_tweet`
my_tweet = 'I am happy because I am learning :)'

p = naive_bayes_predict(my_tweet, logprior, loglikelihood)
print(p)

# Congratulations on completing this assignment. See you next week!


#!/usr/bin/env python3

import time
import math
from datetime import datetime
from time import sleep
import numpy as np
import random
import cv2
import os
import argparse
import torch
import sys
sys.path.append('./')

from env import Engine
from utils_env import get_view,safe_path,cut_frame,point2traj,get_gripper_pos,backup_code

class Engine27(Engine):
    def __init__(self, worker_id, opti, p_id, taskId=5, maxSteps=15, n_dmps=3, cReward=True):
        super(Engine27,self).__init__(opti, wid=worker_id, p_id=p_id, maxSteps=maxSteps, taskId=taskId, n_dmps=n_dmps, cReward=cReward,robot_model=None)
        self.opti = opti
        self._wid = worker_id
        self.robot.gripperMaxForce = 10000.0
        self.robot.armMaxForce = 200.0
        self.robot.jd = [0.01] * 14

        self.p.setPhysicsEngineParameter(enableConeFriction=1)
        self.p.setPhysicsEngineParameter(contactBreakingThreshold=0.001)
        self.p.setPhysicsEngineParameter(allowedCcdPenetration=0.0)

        self.p.setPhysicsEngineParameter(numSolverIterations=20)
        self.p.setPhysicsEngineParameter(numSubSteps=10)

        self.p.setPhysicsEngineParameter(constraintSolverType=self.p.CONSTRAINT_SOLVER_LCP_DANTZIG,globalCFM=0.000001)
        self.p.setPhysicsEngineParameter(enableFileCaching=0)

        self.p.setGravity(0,0,-9.81)

    def reset_new(self):
        self.seq_num = 0
        self.init_dmp()
        self.init_motion ()
        self.init_rl ()
        self.reset_obj ()
        self.init_grasp ()
        return self.get_observation()

    def init_obj(self):
        self.obj_id = self.p.loadURDF( os.path.join(self.resources_dir, "urdf/obj_libs/bottles/b1/b1.urdf"))
        self.p.changeVisualShape (self.obj_id, -1, rgbaColor=[1.,0.,0.,1])

    def reset_obj(self):
        self.p.resetBasePositionAndOrientation(self.obj_id,[0.3637 + 0.06, -0.05, 0.34],[0, 0, -0.1494381, 0.9887711])

        obj_friction_ceof = 20000.0
        self.p.changeDynamics(self.obj_id, -1, mass=0.9)
        self.p.changeDynamics(self.obj_id, -1, lateralFriction=obj_friction_ceof)
        self.p.changeDynamics(self.obj_id, -1, rollingFriction=obj_friction_ceof)
        self.p.changeDynamics(self.obj_id, -1, spinningFriction=obj_friction_ceof)
        self.p.changeDynamics(self.obj_id, -1, linearDamping=40.0)
        self.p.changeDynamics(self.obj_id, -1, angularDamping=1.0)
        self.p.changeDynamics(self.obj_id, -1, contactStiffness=1.0, contactDamping=0.9)

        table_friction_ceof = 0.4
        self.p.changeDynamics(self.table_id, -1, lateralFriction=table_friction_ceof)
        self.p.changeDynamics(self.table_id, -1, rollingFriction=table_friction_ceof)
        self.p.changeDynamics(self.table_id, -1, spinningFriction=table_friction_ceof)
        self.p.changeDynamics(self.table_id, -1, contactStiffness=1.0, contactDamping=0.9)

    def init_motion(self):
        self.data_q = np.load (os.path.join(self.robot_recordings_dir,"47-4/q.npy"))
        self.data_gripper = np.load (self.configs_dir + '/init/gripper.npy')
        self.robot.setJointValue(self.data_q[0],gripper=self.data_gripper[0])

    def init_grasp(self):
        self.robot.gripperControl(0)

        qlist = np.load( os.path.join(self.robot_recordings_dir, "47-4/q.npy"))
        glist = np.load( os.path.join(self.robot_recordings_dir, "47-4/gripper.npy"))
        num_q = len(qlist[0])
        self.fix_orn = np.load (os.path.join (self.configs_dir, 'init', 'orn.npy'))

        self.robot.setJointValue(qlist[40],glist[40])
        for i in range(40,180,1):
            glist[i] = min(130,glist[i])
            self.robot.jointPositionControl(qlist[i],gripper=glist[i])

        pos = self.p.getLinkState (self.robotId, 7)[0]
        up_traj = point2traj([pos, [pos[0], pos[1], pos[2]+0.3]])

        self.start_pos = self.p.getLinkState (self.robotId, 7)[0]
        cur_joint = self.robot.getJointValue()
        cur_pos = self.robot.getEndEffectorPos()
        cur_orn = self.robot.getEndEffectorOrn()
        pos_diff = np.random.uniform(-0.1,0.1,size=(2,))
        cur_pos[:2] = cur_pos[:2] + pos_diff
        cur_pos[2] += 0.02
        for i in range(19):
           self.robot.positionControl(cur_pos,cur_orn,null_pose=cur_joint,gripperPos=130)
        self.init_pos = self.p.getBasePositionAndOrientation(self.obj_id)[0]

    def get_success (self,seg=None):
        pos1 = self.p.getBasePositionAndOrientation(self.obj_id)[0]
        pos1 = np.array(pos1)
        if pos1[2] - self.init_pos[2] > 0.15:
          return True
        else:
          return False


import sys
import math

import cv2
import numpy as np
from PIL import Image

from util.richlog import get_logger
from . import imgops
from . import item
from . import minireco
from . import resources
from . import util

logger = get_logger(__name__)

class RecognizeSession:
    def __init__(self):
        self.recognized_groups = []
        self.low_confidence = False
        self.vh = 0
        self.vw = 0

def tell_stars(starsimg):
    thstars = (np.asarray(starsimg.convert('L')) > 96)
    width, height = thstars.shape[::-1]
    starwidth = width // 3
    threshold = height * (width / 12)
    stars = []
    star1 = thstars[:, 0:starwidth]
    stars.append(np.count_nonzero(star1) > threshold)

    star2 = thstars[:, starwidth:starwidth * 2]
    stars.append(np.count_nonzero(star2) > threshold)

    star3 = thstars[:, starwidth * 2:]
    stars.append(np.count_nonzero(star3) > threshold)
    return tuple(stars)

recozh = minireco.MiniRecognizer(resources.load_pickle('minireco/NotoSansCJKsc-Medium.dat'))
reco_novecento_bold = minireco.MiniRecognizer(resources.load_pickle('minireco/Novecentosanswide_Bold.dat'))

def tell_group(groupimg, session, bartop, barbottom, ):
    logger.logimage(groupimg)
    grouptext = groupimg.crop((0, barbottom, groupimg.width, groupimg.height))

    thim = imgops.enhance_contrast(grouptext.convert('L'), 60)
    # thim = imgops.crop_blackedge(thim)
    logger.logimage(thim)

    groupname, diff = tell_group_name_alt(thim, session)
    if diff > 0.8:
        session.low_confidence = True

    if groupname == '幸运掉落':
        return (groupname, [('(家具)', 1)])

    vw, vh = session.vw, session.vh
    itemwidth = 20.370 * vh
    itemcount = roundint(groupimg.width / itemwidth)
    logger.logtext('group has %d items' % itemcount)
    result = []
    for i in range(itemcount):
        itemimg = groupimg.crop((itemwidth * i, 0.000 * vh, itemwidth * (i+1), 18.981 * vh))
        # x1, _, x2, _ = (0.093*vh, 0.000*vh, 19.074*vh, 18.981*vh)
        itemimg = itemimg.crop((0.093 * vh, 0, 19.074 * vh, itemimg.height))
        recognized_item = item.tell_item(itemimg, session)
        if recognized_item.low_confidence:
            session.low_confidence = True
        result.append((recognized_item.name, recognized_item.quantity))
    return (groupname, result)

def tell_group_name_alt(img, session):
    names = [('龙门币', '声望&龙门币奖励'),
             ('常规', '常规掉落'),
             ('特殊', '特殊掉落'),
             ('幸运', '幸运掉落'),
             ('额外', '额外物资'),
             ('首次', '首次掉落'),
             ('返还', '理智返还'),
             ('报酬', '报酬')]
    comparsions = []
    scale = session.vh * 100 / 1080

    for name, group in names:
        if group in session.recognized_groups:
            continue
        template = resources.load_image_cached(f'end_operation/group/{name}.png', 'L')
        scaled_height = template.height * scale
        scaled_height_floor = math.floor(scaled_height)
        scaled_template_floor = imgops.scale_to_height(template, scaled_height_floor)
        if scaled_template_floor.width > img.width or scaled_template_floor.height > img.height:
            raise ValueError('image smaller than template')
        _, diff_floor = imgops.match_template(img, scaled_template_floor, cv2.TM_SQDIFF_NORMED)
        if scaled_height_floor + 1 <= img.height:
            scaled_template_ceil = imgops.scale_to_height(template, scaled_height_floor + 1)
            _, diff_ceil = imgops.match_template(img, scaled_template_ceil, cv2.TM_SQDIFF_NORMED)
            diff = min(diff_floor, diff_ceil)
        else:
            diff = diff_floor
        comparsions.append((group, diff))

    if comparsions:
        comparsions.sort(key=lambda x: x[1])
        logger.logtext(repr(comparsions))
        return comparsions[0]

def find_jumping(ary, threshold):
    ary = np.array(ary, dtype=np.int16)
    diffs = np.diff(ary)
    shit = [x for x in enumerate(diffs) if abs(x[1]) >= threshold]
    if not shit:
        return []
    groups = [[shit[0]]]
    for x in shit[1:]:
        lastgroup = groups[-1]
        if np.sign(x[1]) == np.sign(lastgroup[-1][1]):
            lastgroup.append(x)
        else:
            groups.append([x])
    logger.logtext(repr(groups))
    pts = []
    for group in groups:
        pts.append(int(np.average(
            tuple(x[0] for x in group), weights=tuple(abs(x[1]) for x in group))) + 1)
    return pts

def roundint(x):
    return int(round(x))

# scale = 0

def check_annihilation_report(img):
    vw, vh = util.get_vwvh(img.size)
    template = resources.load_image_cached('end_operation/annihilation.png', 'L')
    operation_end_img = img.crop((24.583*vh, 40.000*vh, 35.556*vh, 42.639*vh)).convert('L')
    mse = imgops.compare_mse(*imgops.uniform_size(template, operation_end_img))
    return mse < 3251

def check_level_up_popup(img):
    vw, vh = util.get_vwvh(img.size)

    lvl_up_img = img.crop((50*vw-48.796*vh, 47.685*vh, 50*vw-23.148*vh, 56.019*vh)).convert('L')  # 等级提升
    lvl_up_img = imgops.enhance_contrast(lvl_up_img, 216, 255)
    lvl_up_text = recozh.recognize(lvl_up_img)
    return minireco.check_charseq(lvl_up_text, '提升')

def check_end_operation(img):
    vw, vh = util.get_vwvh(img.size)
    template = resources.load_image_cached('end_operation/friendship.png', 'RGB')
    operation_end_img = img.crop((117.083*vh, 64.306*vh, 121.528*vh, 69.583*vh)).convert('RGB')
    mse = imgops.compare_mse(*imgops.uniform_size(template, operation_end_img))
    return mse < 3251

def check_end_operation_alt(img):
    vw, vh = util.get_vwvh(img.size)
    template = resources.load_image_cached('end_operation/end.png', 'L')
    operation_end_img = img.crop((4.722 * vh, 80.278 * vh, 56.389 * vh, 93.889 * vh)).convert('L')
    operation_end_img = imgops.enhance_contrast(operation_end_img, 225, 255)
    mse = imgops.compare_mse(*imgops.uniform_size(template, operation_end_img))
    return mse < 6502

def get_dismiss_level_up_popup_rect(viewport):
    vw, vh = util.get_vwvh(viewport)
    return (100 * vw - 67.315 * vh, 16.019 * vh, 100 * vw - 5.185 * vh, 71.343 * vh)

get_dismiss_end_operation_rect = get_dismiss_level_up_popup_rect

def recognize(im):
    import time
    t0 = time.monotonic()
    vw, vh = util.get_vwvh(im.size)

    lower = im.crop((0, 61.111 * vh, 100 * vw, 100 * vh))
    logger.logimage(lower)

    operation_id = lower.crop((0, 4.444 * vh, 23.611 * vh, 11.388 * vh)).convert('L')
    # logger.logimage(operation_id)
    operation_id = imgops.enhance_contrast(imgops.crop_blackedge(operation_id), 80, 220)
    logger.logimage(operation_id)
    operation_id_str = reco_novecento_bold.recognize(operation_id).upper()
    fixup, operation_id_str = minireco.fix_stage_name(operation_id_str)
    if fixup:
        logger.logtext('fixed to ' + operation_id_str)
    # operation_name = lower.crop((0, 14.074*vh, 23.611*vh, 20*vh)).convert('L')
    # operation_name = imgops.enhance_contrast(imgops.crop_blackedge(operation_name))
    # logger.logimage(operation_name)

    stars = lower.crop((23.611 * vh, 6.759 * vh, 53.241 * vh, 16.944 * vh))
    logger.logimage(stars)
    stars_status = tell_stars(stars)

    # level = lower.crop((63.148 * vh, 4.444 * vh, 73.333 * vh, 8.611 * vh))
    # logger.logimage(level)
    # exp = lower.crop((76.852 * vh, 5.556 * vh, 94.074 * vh, 7.963 * vh))
    # logger.logimage(exp)

    recoresult = {
        'operation': operation_id_str,
        'stars': stars_status,
        'items': [],
        'low_confidence': False
    }

    items = lower.crop((68.241 * vh, 10.926 * vh, lower.width, 35.000 * vh))
    logger.logimage(items)

    x, y = 6.667 * vh, 18.519 * vh
    linedet = items.crop((x, y, x + 1, items.height)).convert('L')
    d = np.asarray(linedet)
    linedet = find_jumping(d.reshape(linedet.height), 64)
    if len(linedet) >= 2:
        linetop, linebottom, *_ = linedet
    else:
        logger.logtext('horizontal line detection failed')
        recoresult['low_confidence'] = True
        return recoresult
    linetop += y
    linebottom += y

    grouping = items.crop((0, linetop, items.width, linebottom))
    grouping = grouping.resize((grouping.width, 1), Image.BILINEAR)
    grouping = grouping.convert('L')

    logger.logimage(grouping.resize((grouping.width, 16)))

    d = np.array(grouping, dtype=np.int16)[0]
    points = [0, *find_jumping(d, 64)]
    if len(points) % 2 != 0:
        raise RuntimeError('possibly incomplete item list')
    finalgroups = list(zip(*[iter(points)] * 2))  # each_slice(2)
    logger.logtext(repr(finalgroups))

    imggroups = [items.crop((x1, 0, x2, items.height))
                 for x1, x2 in finalgroups]
    items = []

    session = RecognizeSession()
    session.vw = vw
    session.vh = vh

    for group in imggroups:
        groupresult = tell_group(group, session, linetop, linebottom)
        session.recognized_groups.append(groupresult[0])
        items.append(groupresult)

    t1 = time.monotonic()
    if session.low_confidence:
        logger.logtext('LOW CONFIDENCE')
    logger.logtext('time elapsed: %f' % (t1 - t0))
    recoresult['items'] = items
    recoresult['low_confidence'] = recoresult['low_confidence'] or session.low_confidence
    return recoresult

def get_still_check_rect(viewport):
    vw, vh = util.get_vwvh(viewport)
    return (68.241 * vh, 61.111 * vh, 100 * vw, 100 * vh)

if __name__ == '__main__':
    print(globals()[sys.argv[-2]](Image.open(sys.argv[-1])))


import numpy as np
from tensorflow.keras.models import model_from_json

import tensorflow as tf

# handling the frames on the gpu
config = tf.compat.v1.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.15
session = tf.compat.v1.Session(config=config)

class FEM(object):
    exps = ['angry', 'fear', 'happy', 'neutral', 'sad', 'surprise']

#   loading the model and its weights for the prediction
    def __init__(self, model_json_file, model_weight_file):
        with open(model_json_file, 'r') as json_file:
            loaded_model_json = json_file.read()
            self.loaded_model = model_from_json(loaded_model_json)

        self.loaded_model.load_weights(model_weight_file)
        self.loaded_model._make_predict_function()

#   predicting the expression
    def predict_exp(self, img):
        self.preds = self.loaded_model.predict(img)
        return FEM.exps[np.argmax(self.preds)]


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

# # Classical Mechanics, Mathematics and Numerical background
#
# ## Introduction
#
# Classical mechanics is a topic which has been taught intensively over
# several centuries. It is, with its many variants and ways of
# presenting the educational material, normally the first **real** physics
# course many of us meet and it lays the foundation for further physics
# studies. Many of the equations and ways of reasoning about the
# underlying laws of motion and pertinent forces, shape our approaches and understanding
# of the scientific method and discourse, as well as the way we develop our insights
# and deeper understanding about physical systems.
#
#
# There is a wealth of
# well-tested (from both a physics point of view and a pedagogical
# standpoint) exercises and problems which can be solved
# analytically. However, many of these problems represent idealized and
# less realistic situations.  The large majority of these problems are
# solved by paper and pencil and are traditionally aimed
# at what we normally refer to as continuous models from which we may find an analytical solution.  As a consequence,
# when teaching mechanics, it implies that we can seldomly venture beyond an idealized case
# in order to develop our understandings and insights about the
# underlying forces and laws of motion.
#
# We aim at changing this here by introducing throughout the course what
# we will call a **computational path**, where with computations we mean
# solving scientific problems with all possible tools and means, from
# plain paper an pencil exercises, via symbolic calculations to writing
# a code and running a program to solve a specific
# problem. Mathematically this normally means that we move from a
# continuous problem to a discretized one. This appproach enables us to
# solve a much broader class of problems.
# In mechanics this means, since we often rephrase the physical problems in terms of differential equations, that we can in most settings reuse the same program with some minimal changes.
#
#
# ## Reminder on vectors and other mathematical quantities
#
# Our studies will start with the motion of different types of objects
# such as a falling ball, a runner, a bicycle etc etc. It means that an
# object's position in space varies with time.
# In order to study such systems we need to define
#
# * choice of origin
#
# * choice of the direction of the axes
#
# * choice of positive direction (left-handed or right-handed system of reference)
#
# * choice of units and dimensions
#
# These choices lead to some important questions such as
#
# * is the  physics of a system independent of the origin of the axes?
#
# * is the  physics independent of the directions of the axes, that is are there privileged axes?
#
# * is the physics independent of the orientation of system?
#
# * is the physics independent of the scale of the length?
#
# Throughout this course we will use the standardized SI units. The standard unit for length is thus one meter 1m, for mass
# one kilogram 1kg, for time one second 1s, for force one Newton 1kgm/s$^2$ and for energy 1 Joule 1kgm$^2$s$^{-2}$.
#
# We will use the following notations for various variables (vectors are always boldfaced in these lecture notes):
# * position $\boldsymbol{r}$, in one dimention we will normally just use $x$,
#
# * mass $m$,
#
# * time $t$,
#
# * velocity $\boldsymbol{v}$ or just $v$ in one dimension,
#
# * acceleration $\boldsymbol{a}$ or just $a$ in one dimension,
#
# * momentum $\boldsymbol{p}$ or just $p$ in one dimension,
#
# * kinetic energy $K$,
#
# * potential energy $V$ and
#
# * frequency $\omega$.
#
# More variables will be defined as we need them.
#
#
# It is also important to keep track of dimensionalities. Don't mix this
# up with a chosen unit for a given variable. We mark the dimensionality
# in these lectures as $[a]$, where $a$ is the quantity we are
# interested in. Thus
#
# * $[\boldsymbol{r}]=$ length
#
# * $[m]=$ mass
#
# * $[K]=$ energy
#
# * $[t]=$ time
#
# * $[\boldsymbol{v}]=$ length over time
#
# * $[\boldsymbol{a}]=$ length over time squared
#
# * $[\boldsymbol{p}]=$ mass times length over time
#
# * $[\omega]=$ 1/time
#
# ## Scalars, Vectors and Matrices
#
# A scalar is something with a value that is independent of coordinate
# system. Examples are mass, or the relative time between events. A
# vector has magnitude and direction. Under rotation, the magnitude
# stays the same but the direction changes. Scalars have no spatial
# index, whereas a three-dimensional vector has 3 indices, e.g. the
# position $\boldsymbol{r}$ has components $r_1,r_2,r_3$, which are often
# referred to as $x,y,z$.
#
# There are several categories of changes of coordinate system. The
# observer can translate the origin, might move with a different
# velocity, or might rotate her/his coordinate axes. For instance, a
# particle's position vector changes when the origin is translated, but
# its velocity does not. When you study relativity you will find that
# quantities you thought of as scalars, such as time or an electric
# potential, are actually parts of four-dimensional vectors and that
# changes of the velocity of the reference frame act in a similar way to
# rotations.
#
# In addition to vectors and scalars, there are matrices, which have two
# indices. One also has objects with 3 or four indices. These are called
# tensors of rank $n$, where $n$ is the number of indices. A matrix is a
# rank-two tensor. The Levi-Civita symbol, $\epsilon_{ijk}$ used for
# cross products of vectors, is a tensor of rank three.
#
#
#
#
# In these lectures we will use boldfaced lower-case letters to label a
# vector. A vector $\boldsymbol{a}$ in three dimensions is thus defined as

# $$
# \boldsymbol{a} =(a_x,a_y, a_z),
# $$

# and using the unit vectors (see below) in a cartesian system we have

# $$
# \boldsymbol{a} = a_x\boldsymbol{e}_1+a_y\boldsymbol{e}_2+a_z\boldsymbol{e}_3,
# $$

# where the unit vectors have magnitude $\vert\boldsymbol{e}_i\vert = 1$ with
# $i=1=x$, $i=2=y$ and $i=3=z$. Some authors use letters
# $\boldsymbol{i}=\boldsymbol{e}_1$, $\boldsymbol{j}=\boldsymbol{e}_2$ and $\boldsymbol{k}=\boldsymbol{e}_3$.
#
#
#
# Alternatively, you may also encounter the above vector as

# $$
# \boldsymbol{a} = a_1\boldsymbol{e}_1+a_2\boldsymbol{e}_2+a_3\boldsymbol{e}_3.
# $$

# Here we have used that $a_1=a_x$, $a_2=a_y$ and $a_3=a_z$. Such a
# notation is sometimes more convenient if we wish to represent vector
# operations in a mathematically more compact way, see below here. We may also find this useful if  we want the different
# components to represent other coordinate systems that the Cartesian one. A typical example would be going from a Cartesian representation to a spherical basis. We will encounter such cases many times in this course.
#
# We use lower-case letters for vectors and upper-case letters for matrices. Vectors and matrices are always boldfaced.
#
#
#
# ### Polar Coordinates
#
# As an example, consider a two-dimensional Cartesian system with a vector $\boldsymbol{r}=(x,y)$.
# Our vector is then written as

# $$
# \boldsymbol{r} = x\boldsymbol{e}_1+y\boldsymbol{e}_2.
# $$

# Transforming to polar coordinates with the radius $\rho\in [0,\infty)$
# and the angle $\phi \in [0,2\pi]$ we have the familiar transformations

# $$
# x = \rho \cos{\phi} \hspace{0.5cm}   y = \rho \sin{\phi},
# $$

# and the inverse relations

# $$
# \rho =\sqrt{x^2+y^2} \hspace{0.5cm}   \phi = \mathrm{arctan}(\frac{y}{x}).
# $$

# We can rewrite the vector $\boldsymbol{a}$ in terms of $\rho$ and $\phi$ as

# $$
# \boldsymbol{a} = \rho \cos{\phi}\boldsymbol{e}_1+\rho \sin{\phi}\boldsymbol{e}_2,
# $$

# and we define the new unit vectors as $\boldsymbol{e}'_1=\cos{\phi}\boldsymbol{e}_1$ and $\boldsymbol{e}'_2=\sin{\phi}\boldsymbol{e}_2$, we have

# $$
# \boldsymbol{a}' = \rho\boldsymbol{e}'_1+\rho \boldsymbol{e}'_2.
# $$

# Below we will show that the norms of this vector in a Cartesian basis and a Polar basis are equal.
#
#
# ### Unit Vectors
#
# Also known as basis vectors, unit vectors point in the direction of
# the coordinate axes, have unit norm, and are orthogonal to one
# another. Sometimes this is referred to as an orthonormal basis,

#
#

#
# $$
# \begin{equation}
# \boldsymbol{e}_i\cdot\boldsymbol{e}_j=\delta_{ij}=\begin{bmatrix}
# 1 & 0 & 0\\
# 0& 1 & 0\\
# 0 & 0 & 1
# \end{bmatrix}.
# \label{_auto1} \tag{1}
# \end{equation}
# $$

# Here, $\delta_{ij}$ is unity when $i=j$ and is zero otherwise. This is
# called the unit matrix, because you can multiply it with any other
# matrix and not change the matrix. The **dot** denotes the dot product,
# $\boldsymbol{a}\cdot\boldsymbol{b}=a_1b_1+a_2b_2+a_3b_3=|a||b|\cos\theta_{ab}$. Sometimes
# the unit vectors are called $\hat{x}$, $\hat{y}$ and
# $\hat{z}$.
#
#
#
# Vectors can be decomposed in terms of unit vectors,

#
#

#
# $$
# \begin{equation}
# \boldsymbol{r}=r_1\hat{e}_1+r_2\hat{e}_2+r_3\hat{e}_3.
# \label{_auto2} \tag{2}
# \end{equation}
# $$

# The vector components $r_1$, $r_2$ and $r_3$ might be
# called $x$, $y$ and $z$ for a displacement. Another way to write this is to define the vector $\boldsymbol{r}=(x,y,z)$.
#
# Similarly, for the velocity we will use in this course the components  $\boldsymbol{v}=(v_x, v_y,v_z$. The accelaration is then given by $\boldsymbol{a}=(a_x,a_y,a_z)$.
#
#
#
# As mentioned above, repeated indices infer sums.
# This means that when you encounter an expression like the one on the left-hand side here, it stands actually for a sum (right-hand side)

# $$
# x_iy_i=\sum_i x_iy_i=\boldsymbol{x}\cdot\boldsymbol{y}.
# $$

# We will in our lectures seldom use this notation and rather spell out the summations.  This inferred summation over indices is normally called [Einstein summation convention](https://en.wikipedia.org/wiki/Einstein_notation).
#
#
# ## Vector Operations, Scalar Product (or dot product)
#
# For two vectors $\boldsymbol{a}$ and $\boldsymbol{b}$ we have

# $$
# \begin{eqnarray*}
# \boldsymbol{a}\cdot\boldsymbol{b}&=&\sum_ia_ib_i=|a||b|\cos\theta_{ab},\\
# |a|&\equiv& \sqrt{\boldsymbol{a}\cdot\boldsymbol{a}},
# \end{eqnarray*}
# $$

# or with a norm-2 notation

# $$
# |a|\equiv \vert\vert \boldsymbol{a}\vert\vert_2=\sqrt{\sum_i a_i^2}.
# $$

# Not of all of you are familiar with linear algebra. Numerically we will always deal with arrays and the dot product vector is given by the product of the transposed vector multiplied with the other vector, that is we have

# $$
# \boldsymbol{a}^T\boldsymbol{b}=\sum_i a_ib_i=|a||b|\cos\theta_{ab}.
# $$

# The superscript $T$ represents the transposition operations.
#
#
#
# ## Digression, Linear Algebra Notation for Vectors
#
# As an example, consider a three-dimensional velocity defined by a vector $\boldsymbol{v}=(v_x,v_y,v_z)$. For those of you familiar with linear algebra, we would write this quantity as

# $$
# \boldsymbol{v}=\begin{bmatrix} v_x\\ v_y \\ v_z \end{bmatrix},
# $$

# and the transpose as

# $$
# \boldsymbol{v}^T=\begin{bmatrix} v_x & v_y &v_z \end{bmatrix}.
# $$

# The norm is

# $$
# \boldsymbol{v}^T\boldsymbol{v}=v_x^2+v_y^2+v_z^2,
# $$

# as it should.
#
# Since we will use Python as a programming language throughout this course, the above vector, using the package **numpy** (see discussions below), can be written as

# In[1]:

import numpy as np
# Define the values of vx, vy and vz
vx = 0.0
vy = 1.0
vz = 0.0
v = np.array([vx, vy, vz])
print(v)
# The print the transpose of v
print(v.T)

# Try to figure out how to calculate the norm with **numpy**.
# We will come back to **numpy** in the examples below.
#
#
#
#
# As an example, consider our transformation of a two-dimensional Cartesian vector $\boldsymbol{r}$ to polar coordinates.
# We had

# $$
# \boldsymbol{r} = x\boldsymbol{e}_1+y\boldsymbol{e}_2.
# $$

# Transforming to polar coordinates with the radius $\rho\in [0,\infty)$
# and the angle $\phi \in [0,2\pi]$ we have

# $$
# x = \rho \cos{\phi} \hspace{0.5cm}   y = \rho \sin{\phi}.
# $$

# We can write this

# $$
# \boldsymbol{r} = \begin{bmatrix} x \\ y \end{bmatrix}= \begin{bmatrix} \rho \cos{\phi}  \\ \rho \sin{\phi}  \end{bmatrix}.
# $$

# The norm in Cartesian coordinates is $\boldsymbol{r}\cdot\boldsymbol{r}=x^2+y^2$ and
# using Polar coordinates we have
# $\rho^2(\cos{\phi})^2+\rho^2(\cos{\phi})^2=\rho^2$, which shows that
# the norm is conserved since we have $\rho = \sqrt{x^2+y^2}$. A
# transformation to a new basis should not change the norm.
#
#
#
# ## Vector Product (or cross product) of vectors $\boldsymbol{a}$ and $\boldsymbol{b}$

# $$
# \begin{eqnarray*}
# \boldsymbol{c}&=&\boldsymbol{a}\times\boldsymbol{b},\\
# c_i&=&\epsilon_{ijk}a_jb_k.
# \end{eqnarray*}
# $$

# Here $\epsilon$ is the third-rank anti-symmetric tensor, also known as
# the Levi-Civita symbol. It is $\pm 1$ only if all three indices are
# different, and is zero otherwise. The choice of $\pm 1$ depends on
# whether the indices are an even or odd permutation of the original
# symbols. The permutation $xyz$ or $123$ is considered to be $+1$. Its elements are

# $$
# \begin{eqnarray}
# \epsilon_{ijk}&=&-\epsilon_{ikj}=-\epsilon_{jik}=-\epsilon_{kji}\\
# \nonumber
# \epsilon_{123}&=&\epsilon_{231}=\epsilon_{312}=1,\\
# \nonumber
# \epsilon_{213}&=&\epsilon_{132}=\epsilon_{321}=-1,\\
# \nonumber
# \epsilon_{iij}&=&\epsilon_{iji}=\epsilon_{jii}=0.
# \end{eqnarray}
# $$

# You may have met cross-products when studying magnetic
# fields. Because the matrix is anti-symmetric, switching the $x$ and
# $y$ axes (or any two axes) flips the sign. If the coordinate system is
# right-handed, meaning the $xyz$ axes satisfy
# $\hat{x}\times\hat{y}=\hat{z}$, where you can point along the $x$ axis
# with your extended right index finger, the $y$ axis with your
# contracted middle finger and the $z$ axis with your extended
# thumb. Switching to a left-handed system flips the sign of the vector
# $\boldsymbol{c}=\boldsymbol{a}\times\boldsymbol{b}$.
#
# Note that
# $\boldsymbol{a}\times\boldsymbol{b}=-\boldsymbol{b}\times\boldsymbol{a}$. The vector $\boldsymbol{c}$ is
# perpendicular to both $\boldsymbol{a}$ and $\boldsymbol{b}$ and the magnitude of
# $\boldsymbol{c}$ is given by

# $$
# |c|=|a||b|\sin{\theta_{ab}}.
# $$

# ### Pseudo-vectors
#
# Vectors obtained by the cross product of two real vectors are called
# pseudo-vectors because the assignment of their direction can be
# arbitrarily flipped by defining the Levi-Civita symbol to be based on
# left-handed rules. Examples are the magnetic field and angular
# momentum. If the direction of a real vector prefers the right-handed
# over the left-handed direction, that constitutes a violation of
# parity. For instance, one can polarize the spins (angular momentum) of
# nuclei with a magnetic field so that the spins preferentially point
# along the direction of the magnetic field. This does not violate
# parity because both are pseudo-vectors. Now assume these polarized
# nuclei decay and that electrons are one of the products. If these
# electrons prefer to exit the decay parallel vs. antiparallel to the
# polarizing magnetic field, this constitutes parity violation because
# the direction of the outgoing electron momenta are a real vector. This
# is precisely what is observed in weak decays.
#
#
# ## Differentiation of a vector with respect to a scalar
#
# As an  example, consider the
# acceleration $\boldsymbol{a}$, which is given by the change in velocity per unit time, $\boldsymbol{a}=d\boldsymbol{v}/dt$
# with components

# $$
# a_i = (d\boldsymbol{v}/dt)_i=\frac{dv_i}{dt}.
# $$

# Here $i=x,y,z$ or $i=1,2,3$ if we are in three dimensions.
#
#
# ### Gradient operator $\nabla$
#
# This represents  the derivatives $\partial/\partial
# x$, $\partial/\partial y$ and $\partial/\partial z$. An often used shorthand is  $\partial_x=\partial/\partial_x$.
#
# The gradient of a scalar function of position and time
# $\Phi(x,y,z)=\Phi(\boldsymbol{r},t)$ is given by

# $$
# \boldsymbol{\nabla}~\Phi,
# $$

# with components $i$

# $$
# (\nabla\Phi(x,y,z,t))_i=\partial/\partial r_i\Phi(\boldsymbol{r},t)=\partial_i\Phi(\boldsymbol{r},t).
# $$

# Note that the gradient is a vector.
#
# Taking the dot product of the gradient with a vector, normally called the divergence,
# we have

# $$
# \mathrm{div} \boldsymbol{a}, \nabla\cdot\boldsymbol{a}=\sum_i \partial_i a_i.
# $$

# Note that the divergence is a scalar.
#
#
# ### The curl
#
# The **curl** of a vector is defined as
# $\nabla\times\boldsymbol{a}$,

# $$
# {\rm\bf curl}~\boldsymbol{a},
# $$

# with components

# $$
# (\boldsymbol{\nabla}\times\boldsymbol{a})_i=\epsilon_{ijk}\partial_j a_k(\boldsymbol{r},t).
# $$

# ### The Laplacian
#
# The Laplacian is referred to as $\nabla^2$ and is defined as

# $$
# \boldsymbol{\nabla}^2=\boldsymbol{\nabla}\cdot\boldsymbol{\nabla}=\frac{\partial^2}{\partial x^2}+\frac{\partial^2}{\partial y^2}+\frac{\partial^2}{\partial z^2}.
# $$

# Question: is the Laplacian a scalar or a vector?
#
# ### Some identities
#
# Here we simply state these, but you may wish to prove a few. They are useful for this class and will be essential when you study electromagnetism.

# $$
# \begin{eqnarray}
# \boldsymbol{a}\cdot(\boldsymbol{b}\times\boldsymbol{c})&=&\boldsymbol{b}\cdot(\boldsymbol{c}\times\boldsymbol{a})=\boldsymbol{c}\cdot(\boldsymbol{a}\times\boldsymbol{b})\\
# \nonumber
# \boldsymbol{a}\times(\boldsymbol{b}\times\boldsymbol{c})&=&(\boldsymbol{a}\cdot\boldsymbol{c})\boldsymbol{b}-(\boldsymbol{a}\cdot\boldsymbol{b})\boldsymbol{c}\\
# \nonumber
# (\boldsymbol{a}\times\boldsymbol{b})\cdot(\boldsymbol{c}\times\boldsymbol{d})&=&(\boldsymbol{a}\cdot\boldsymbol{c})(\boldsymbol{b}\cdot\boldsymbol{d})
# -(\boldsymbol{a}\cdot\boldsymbol{d})(\boldsymbol{b}\cdot\boldsymbol{c})
# \end{eqnarray}
# $$

# ### More useful relations
#
# Using the fact that multiplication of reals is distributive we can show that

# $$
# \boldsymbol{a}(\boldsymbol{b}+\boldsymbol{c})=\boldsymbol{a}\boldsymbol{b}+\boldsymbol{a}\boldsymbol{c},
# $$

# Similarly we can also show that (using product rule for differentiating reals)

# $$
# \frac{d}{dt}(\boldsymbol{a}\boldsymbol{b})=\boldsymbol{a}\frac{d\boldsymbol{b}}{dt}+\boldsymbol{b}\frac{d\boldsymbol{a}}{dt}.
# $$

# We can repeat these operations for the cross products and show that they are distribuitive

# $$
# \boldsymbol{a}\times(\boldsymbol{b}+\boldsymbol{c})=\boldsymbol{a}\times\boldsymbol{b}+\boldsymbol{a}\times\boldsymbol{c}.
# $$

# We have also that

# $$
# \frac{d}{dt}(\boldsymbol{a}\times\boldsymbol{b})=\boldsymbol{a}\times\frac{d\boldsymbol{b}}{dt}+\boldsymbol{b}\times\frac{d\boldsymbol{a}}{dt}.
# $$

# ### Gauss's Theorem
#
# For an integral over a volume $V$ confined by a surface $S$, Gauss's theorem gives

# $$
# \int_V dv~\nabla\cdot\boldsymbol{A}=\int_Sd\boldsymbol{S}\cdot\boldsymbol{A}.
# $$

# For a closed path $C$ which carves out some area $S$,

# $$
# \int_C d\boldsymbol{\ell}\cdot\boldsymbol{A}=\int_Sd\boldsymbol{s} \cdot(\nabla\times\boldsymbol{A})
# $$

# ### and Stokes's Theorem
#
# Stoke's law can be understood by considering a small rectangle,
# $-\Delta x<x<\Delta x$, $-\Delta y<y<\Delta y$. The path integral
# around the edges is

# $$
# \begin{eqnarray}
# \int_C d\boldsymbol{\ell}\cdot\boldsymbol{A}&=&2\Delta y[A_y(\Delta x,0)-A_y(-\Delta x,0)]-2\Delta x[A_x(0,\Delta y)-A_x(0,-\Delta y)]\\
# \nonumber
# &=&4\Delta x\Delta y\left\{
# \frac{A_y(\Delta x,0)-A_y(-\Delta x,0)}{2\Delta x}-\frac{A_x(0,\Delta y)-A_x(0,-\Delta y)}{2\Delta y}\right\}\\
# \nonumber
# &=&4\Delta x\Delta y\left\{\frac{\partial A_y}{\partial x}-\frac{\partial A_x}{\partial y}\right\}\\
# &=&\Delta S \cdot \nabla\times\boldsymbol{A}.
# \end{eqnarray}
# $$

# Here $\Delta S$ is the area of the surface element.
#
#
#
#
# ## Basic Matrix Features
#
# **Note**: The material on matrices is optional and will not be used much
# (except for illustrations at the very end on garmonic oscillations)
# since most of you have not yet taken a course on linear algebra. The
# material is however included here for the sake of completeness.

# $$
# \mathbf{A} =
#       \begin{bmatrix} a_{11} & a_{12} & a_{13} & a_{14} \\
#                                  a_{21} & a_{22} & a_{23} & a_{24} \\
#                                    a_{31} & a_{32} & a_{33} & a_{34} \\
#                                   a_{41} & a_{42} & a_{43} & a_{44}
#              \end{bmatrix}\qquad
# \mathbf{I} =
#       \begin{bmatrix} 1 & 0 & 0 & 0 \\
#                                  0 & 1 & 0 & 0 \\
#                                  0 & 0 & 1 & 0 \\
#                                  0 & 0 & 0 & 1
#              \end{bmatrix}
# $$

# The inverse of a matrix is defined by

# $$
# \mathbf{A}^{-1} \cdot \mathbf{A} = I
# $$

#

#

#
              Relations               	       Name     	                             matrix elements

#

#

#
   $A = A^{T}$                               	    symmetric          	    $a_{ij} = a_{ji}$

#
   $A = \left (A^{T} \right )^{-1}$          	    real orthogonal    	    $\sum_k a_{ik} a_{jk} = \sum_k a_{ki} a_{kj} = \delta_{ij}$

#
   $A = A^{ * }$                             	    real matrix        	    $a_{ij} = a_{ij}^{ * }$

#
   $A = A^{\dagger}$                         	    hermitian          	    $a_{ij} = a_{ji}^{ * }$

#
   $A = \left (A^{\dagger} \right )^{-1}$    	    unitary            	    $\sum_k a_{ik} a_{jk}^{ * } = \sum_k a_{ki}^{ * } a_{kj} = \delta_{ij}$

#

#

#
#
# ### Some famous Matrices
#
#   * Diagonal if $a_{ij}=0$ for $i\ne j$
#
#   * Upper triangular if $a_{ij}=0$ for $i > j$
#
#   * Lower triangular if $a_{ij}=0$ for $i < j$
#
#   * Upper Hessenberg if $a_{ij}=0$ for $i > j+1$
#
#   * Lower Hessenberg if $a_{ij}=0$ for $i < j+1$
#
#   * Tridiagonal if $a_{ij}=0$ for $|i -j| > 1$
#
#   * Lower banded with bandwidth $p$: $a_{ij}=0$ for $i > j+p$
#
#   * Upper banded with bandwidth $p$: $a_{ij}=0$ for $i < j+p$
#
#   * Banded, block upper triangular, block lower triangular....
#
# For an $N\times N$ matrix  $\mathbf{A}$ the following properties are all equivalent
#
#   * If the inverse of $\mathbf{A}$ exists, $\mathbf{A}$ is nonsingular.
#
#   * The equation $\mathbf{Ax}=0$ implies $\mathbf{x}=0$.
#
#   * The rows of $\mathbf{A}$ form a basis of $R^N$.
#
#   * The columns of $\mathbf{A}$ form a basis of $R^N$.
#
#   * $\mathbf{A}$ is a product of elementary matrices.
#
#   * $0$ is not eigenvalue of $\mathbf{A}$.
#
# ## Rotations
#
#
# Here, we use rotations as an example of matrices and their operations. One can consider a different orthonormal basis $\hat{e}'_1$, $\hat{e}'_2$ and $\hat{e}'_3$. The same vector $\boldsymbol{r}$ mentioned above can also be expressed in the new basis,

#
#

#
# $$
# \begin{equation}
# \boldsymbol{r}=r'_1\hat{e}'_1+r'_2\hat{e}'_2+r'_3\hat{e}'_3.
# \label{_auto3} \tag{3}
# \end{equation}
# $$

# Even though it is the same vector, the components have changed. Each
# new unit vector $\hat{e}'_i$ can be expressed as a linear sum of the
# previous vectors,

#
#

#
# $$
# \begin{equation}
# \hat{e}'_i=\sum_j U_{ij}\hat{e}_j,
# \label{_auto4} \tag{4}
# \end{equation}
# $$

# and the matrix $U$ can be found by taking the dot product of both sides with $\hat{e}_k$,

#
#

#
# $$
# \begin{eqnarray}
# \nonumber
# \hat{e}_k\cdot\hat{e}'_i&=&\sum_jU_{ij}\hat{e}_k\cdot\hat{e}_j\\
# \label{eq:lambda_angles} \tag{5}
# \hat{e}_k\cdot\hat{e}'_i&=&\sum_jU_{ij}\delta_{jk}=U_{ik}.
# \end{eqnarray}
# $$

# Thus, the matrix lambda has components $U_{ij}$ that are equal to the
# cosine of the angle between new unit vector $\hat{e}'_i$ and the old
# unit vector $\hat{e}_j$.

#
#

#
# $$
# \begin{equation}
# U = \begin{bmatrix}
# \hat{e}'_1\cdot\hat{e}_1& \hat{e}'_1\cdot\hat{e}_2& \hat{e}'_1\cdot\hat{e}_3\\
# \hat{e}'_2\cdot\hat{e}_1& \hat{e}'_2\cdot\hat{e}_2& \hat{e}'_2\cdot\hat{e}_3\\
# \hat{e}'_3\cdot\hat{e}_1& \hat{e}'_3\cdot\hat{e}_2& \hat{e}'_3\cdot\hat{e}_3
# \end{bmatrix},~~~~~U_{ij}=\hat{e}'_i\cdot\hat{e}_j=\cos\theta_{ij}.
# \label{_auto5} \tag{6}
# \end{equation}
# $$

# Note that the matrix is not symmetric, $U_{ij}\ne U_{ji}$. One can also look at the inverse transformation, by switching the primed and unprimed coordinates,

#
#

#
# $$
# \begin{eqnarray}
# \label{eq:inverseU} \tag{7}
# \hat{e}_i&=&\sum_jU^{-1}_{ij}\hat{e}'_j,\\
# \nonumber
# U^{-1}_{ij}&=&\hat{e}_i\cdot\hat{e}'_j=U_{ji}.
# \end{eqnarray}
# $$

# The definition of transpose of a matrix, $M^{t}_{ij}=M_{ji}$, allows one to state this as

#
#

#
# $$
# \begin{eqnarray}
# \label{eq:transposedef} \tag{8}
# U^{-1}&=&U^{t}.
# \end{eqnarray}
# $$

# ### Tensors
#
# A tensor obeying Eq. ([8](#eq:transposedef)) defines what is known as
# a unitary, or orthogonal, transformation.
#
# The matrix $U$ can be used to transform any vector to the new basis. Consider a vector

# $$
# \begin{eqnarray}
# \boldsymbol{r}&=&r_1\hat{e}_1+r_2\hat{e}_2+r_3\hat{e}_3\\
# \nonumber
# &=&r'_1\hat{e}'_1+r'_2\hat{e}'_2+r'_3\hat{e}'_3.
# \end{eqnarray}
# $$

# This is the same vector expressed as a sum over two different sets of
# basis vectors. The coefficients $r_i$ and $r'_i$ represent components
# of the same vector. The relation between them can be found by taking
# the dot product of each side with one of the unit vectors,
# $\hat{e}_i$, which gives

# $$
# \begin{eqnarray}
# r_i&=&\sum_j \hat{e}_i\cdot\hat{e}'_j~r'_j.
# \end{eqnarray}
# $$

# Using Eq. ([7](#eq:inverseU)) one can see that the transformation of $r$ can be also written in terms of $U$,

#
#

#
# $$
# \begin{eqnarray}
# \label{eq:rotateR} \tag{9}
# r_i&=&\sum_jU^{-1}_{ij}~r'_j.
# \end{eqnarray}
# $$

# Thus, the matrix that transforms the coordinates of the unit vectors,
# Eq. ([7](#eq:inverseU)) is the same one that transforms the
# coordinates of a vector, Eq. ([9](#eq:rotateR)).
#
#
#
# As a small exercise, find the rotation matrix $U$ for finding the
# components in the primed coordinate system given from those in the
# unprimed system, given that the unit vectors in the new system are
# found by rotating the coordinate system by and angle $\phi$ about the
# $z$ axis.
#
# In this case

# $$
# \begin{eqnarray*}
# \hat{e}'_1&=&\cos\phi \hat{e}_1-\sin\phi\hat{e}_2,\\
# \hat{e}'_2&=&\sin\phi\hat{e}_1+\cos\phi\hat{e}_2,\\
# \hat{e}'_3&=&\hat{e}_3.
# \end{eqnarray*}
# $$

# By inspecting Eq. ([5](#eq:lambda_angles)), we get

# $$
# U=\left(\begin{array}{ccc}
# \cos\phi&-\sin\phi&0\\
# \sin\phi&\cos\phi&0\\
# 0&0&1\end{array}\right).
# $$

# Under a unitary transformation $U$ (or basis transformation) scalars
# are unchanged, whereas vectors $\boldsymbol{r}$ and matrices $M$ change as

# $$
# \begin{eqnarray}
# r'_i&=&U_{ij}~ r_j, ~~({\rm sum~inferred})\\
# \nonumber
# M'_{ij}&=&U_{ik}M_{km}U^{-1}_{mj}.
# \end{eqnarray}
# $$

# Physical quantities with no spatial indices are scalars (or
# pseudoscalars if they depend on right-handed vs. left-handed
# coordinate systems), and are unchanged by unitary
# transformations. This includes quantities like the trace of a matrix,
# the matrix itself had indices but none remain after performing the
# trace.

# $$
# \begin{eqnarray}
# {\rm Tr} M&\equiv& M_{ii}.
# \end{eqnarray}
# $$

# Because there are no remaining indices, one expects it to be a scalar. Indeed one can see this,

# $$
# \begin{eqnarray}
# {\rm Tr} M'&=&U_{ij}M_{jm}U^{-1}_{mi}\\
# \nonumber
# &=&M_{jm}U^{-1}_{mi}U_{ij}\\
# \nonumber
# &=&M_{jm}\delta_{mj}\\
# \nonumber
# &=&M_{jj}={\rm Tr} M.
# \end{eqnarray}
# $$

# A similar example is the determinant of a matrix, which is also a scalar.
#
#
#
#
# ## Numerical Elements
#
# Numerical algorithms call for approximate discrete models and much of
# the development of methods for continuous models are nowadays being
# replaced by methods for discrete models in science and industry,
# simply because **much larger classes of problems can be addressed** with
# discrete models, often by simpler and more generic methodologies.
#
# As we will see throughout this course, when properly scaling the equations at hand,
# discrete models open up for more advanced abstractions and the possibility to
# study  real life systems, with the added bonus that we can explore and
# deepen our basic understanding of various physical systems
#
# Analytical solutions are as important as before. In addition, such
# solutions provide us with invaluable benchmarks and tests for our
# discrete models. Such benchmarks, as we will see below, allow us
# to discuss possible sources of errors and their behaviors.  And
# finally, since most of our models are based on various algorithms from
# numerical mathematics, we have a unique oppotunity to gain a deeper
# understanding of the mathematical approaches we are using.
#
#
#
# With computing and data science as important elements in essentially
# all aspects of a modern society, we could  then try to define Computing as
# **solving scientific problems using all possible tools, including
# symbolic computing, computers and numerical algorithms, and analytical
# paper and pencil solutions**.
# Computing provides us with the tools to develope our own understanding of the scientific method by enhancing algorithmic thinking.
#
#
#
# The way we will teach this course reflects this definition of
# computing. The course contains both classical paper and pencil
# exercises as well as computational projects and exercises. The hope is
# that this will allow you to explore the physics of systems governed by
# the degrees of freedom of classical mechanics at a deeper level, and
# that these insights about the scientific method will help you to
# develop a better understanding of how the underlying forces and
# equations of motion and how they impact a given system.
#
# Furthermore,
# by introducing various numerical methods via computational projects
# and exercises, we aim at developing your competences and skills about
# these topics.
#
#
#
#
# These competences will enable you to
#
# * understand how algorithms are used to solve mathematical problems,
#
# * derive, verify, and implement algorithms,
#
# * understand what can go wrong with algorithms,
#
# * use these algorithms to construct reproducible scientific outcomes and to engage in science in ethical ways, and
#
# * think algorithmically for the purposes of gaining deeper insights about scientific problems.
#
# All these elements are central for maturing and gaining a better understanding of the modern scientific process *per se*.
#
# The power of the scientific method lies in identifying a given problem
# as a special case of an abstract class of problems, identifying
# general solution methods for this class of problems, and applying a
# general method to the specific problem (applying means, in the case of
# computing, calculations by pen and paper, symbolic computing, or
# numerical computing by ready-made and/or self-written software). This
# generic view on problems and methods is particularly important for
# understanding how to apply available, generic software to solve a
# particular problem.
#
# *However, verification of algorithms and understanding their limitations requires much of the classical knowledge about continuous models.*
#
#
#
# ## A well-known example to illustrate many of the above concepts
#
# Before we venture into a reminder on Python and mechanics relevant applications, let us briefly outline some of the
# abovementioned topics using an example many of you may have seen before in for example CMSE201.
# A simple algorithm for integration is the Trapezoidal rule.
# Integration of a function $f(x)$ by the Trapezoidal Rule is given by following algorithm for an interval $x \in [a,b]$

# $$
# \int_a^b(f(x) dx = \frac{1}{2}\left [f(a)+2f(a+h)+\dots+2f(b-h)+f(b)\right] +O(h^2),
# $$

# where $h$ is the so-called stepsize defined by the number of integration points $N$ as $h=(b-a)/(n)$.
# Python offers an  extremely versatile programming  environment, allowing for
# the inclusion of analytical studies in a numerical program. Here we show an
# example code with the **trapezoidal rule**. We use also **SymPy** to evaluate the exact value of the integral and compute the absolute error
# with respect to the numerically evaluated one of the integral
# $\int_0^1 dx x^2 = 1/3$.
# The following code for  the trapezoidal rule allows you  to plot the relative error by comparing with the exact result. By increasing to $10^8$ points one arrives at a region where numerical errors start to accumulate.

# In[2]:

get_ipython().run_line_magic('matplotlib', 'inline')

from math import log10
import numpy as np
from sympy import Symbol, integrate
import matplotlib.pyplot as plt
# function for the trapezoidal rule
def Trapez(a,b,f,n):
   h = (b-a)/float(n)
   s = 0
   x = a
   for i in range(1,n,1):
       x = x+h
       s = s+ f(x)
   s = 0.5*(f(a)+f(b)) +s
   return h*s
#  function to compute pi
def function(x):
    return x*x
# define integration limits
a = 0.0;  b = 1.0;
# find result from sympy
# define x as a symbol to be used by sympy
x = Symbol('x')
exact = integrate(function(x), (x, a, b))
# set up the arrays for plotting the relative error
n = np.zeros(9); y = np.zeros(9);
# find the relative error as function of integration points
for i in range(1, 8, 1):
    npts = 10**i
    result = Trapez(a,b,function,npts)
    RelativeError = abs((exact-result)/exact)
    n[i] = log10(npts); y[i] = log10(RelativeError);
plt.plot(n,y, 'ro')
plt.xlabel('n')
plt.ylabel('Relative error')
plt.show()

# ### Analyzing the above example
#
# This example shows the potential of combining numerical algorithms
# with symbolic calculations, allowing us to
#
# * Validate and verify  their  algorithms.
#
# * Including concepts like unit testing, one has the possibility to test and test several or all parts of the code.
#
# * Validation and verification are then included *naturally* and one can develop a better attitude to what is meant with an ethically sound scientific approach.
#
# * The above example allows the student to also test the mathematical error of the algorithm for the trapezoidal rule by changing the number of integration points. The students get **trained from day one to think error analysis**.
#
# * With a Jupyter notebook you can keep exploring similar examples and turn them in as your own notebooks.
#
# ## Python practicalities, Software and needed installations
#
# We will make extensive use of Python as programming language and its
# myriad of available libraries.  You will find
# Jupyter notebooks invaluable in your work.
#
# If you have Python installed (we strongly recommend Python3) and you feel
# pretty familiar with installing different packages, we recommend that
# you install the following Python packages via **pip** as
#
# 1. pip install numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas pillow
#
# For Python3, replace **pip** with **pip3**.
#
# For OSX users we recommend, after having installed Xcode, to
# install **brew**. Brew allows for a seamless installation of additional
# software via for example
#
# 1. brew install python3
#
# For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution,
# you can use **pip** as well and simply install Python as
#
# 1. sudo apt-get install python3  (or python for pyhton2.7)
#
# etc etc.
#
#
#
# ### Python installers
#
# If you don't want to perform these operations separately and venture
# into the hassle of exploring how to set up dependencies and paths, we
# recommend two widely used distrubutions which set up all relevant
# dependencies for Python, namely
#
# * [Anaconda](https://docs.anaconda.com/),
#
# which is an open source
# distribution of the Python and R programming languages for large-scale
# data processing, predictive analytics, and scientific computing, that
# aims to simplify package management and deployment. Package versions
# are managed by the package management system **conda**.
#
# * [Enthought canopy](https://www.enthought.com/product/canopy/)
#
# is a Python
# distribution for scientific and analytic computing distribution and
# analysis environment, available for free and under a commercial
# license.
#
# Furthermore, [Google's Colab](https://colab.research.google.com/notebooks/welcome.ipynb) is a free Jupyter notebook environment that requires
# no setup and runs entirely in the cloud. Try it out!
#
#
# ## Useful Python libraries
#
# Here we list several useful Python libraries we strongly recommend (if you use anaconda many of these are already there)
#
# * [NumPy](https://www.numpy.org/) is a highly popular library for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays
#
# * [The pandas](https://pandas.pydata.org/) library provides high-performance, easy-to-use data structures and data analysis tools
#
# * [Xarray](http://xarray.pydata.org/en/stable/) is a Python package that makes working with labelled multi-dimensional arrays simple, efficient, and fun!
#
# * [Scipy](https://www.scipy.org/) (pronounced “Sigh Pie”) is a Python-based ecosystem of open-source software for mathematics, science, and engineering.
#
# * [Matplotlib](https://matplotlib.org/) is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.
#
# * [Autograd](https://github.com/HIPS/autograd) can automatically differentiate native Python and Numpy code. It can handle a large subset of Python's features, including loops, ifs, recursion and closures, and it can even take derivatives of derivatives of derivatives
#
# * [SymPy](https://www.sympy.org/en/index.html) is a Python library for symbolic mathematics.
#
# * [scikit-learn](https://scikit-learn.org/stable/) has simple and efficient tools for machine learning, data mining and data analysis
#
# * [TensorFlow](https://www.tensorflow.org/) is a Python library for fast numerical computing created and released by Google
#
# * [Keras](https://keras.io/) is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano
#
# * And many more such as [pytorch](https://pytorch.org/),  [Theano](https://pypi.org/project/Theano/) etc
#
# Your jupyter notebook can easily be
# converted into a nicely rendered **PDF** file or a Latex file for
# further processing. For example, convert to latex as

#         pycod jupyter nbconvert filename.ipynb --to latex
#

# And to add more versatility, the Python package [SymPy](http://www.sympy.org/en/index.html) is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS)  and is entirely written in Python.
#
#
#
# ## Numpy examples and Important Matrix and vector handling packages
#
# There are several central software libraries for linear algebra and eigenvalue problems. Several of the more
# popular ones have been wrapped into ofter software packages like those from the widely used text **Numerical Recipes**. The original source codes in many of the available packages are often taken from the widely used
# software package LAPACK, which follows two other popular packages
# developed in the 1970s, namely EISPACK and LINPACK.  We describe them shortly here.
#
#   * LINPACK: package for linear equations and least square problems.
#
#   * LAPACK:package for solving symmetric, unsymmetric and generalized eigenvalue problems. From LAPACK's website <http://www.netlib.org> it is possible to download for free all source codes from this library. Both C/C++ and Fortran versions are available.
#
#   * BLAS (I, II and III): (Basic Linear Algebra Subprograms) are routines that provide standard building blocks for performing basic vector and matrix operations. Blas I is vector operations, II vector-matrix operations and III matrix-matrix operations. Highly parallelized and efficient codes, all available for download from <http://www.netlib.org>.
#
# [Numpy](http://www.numpy.org/) provides an easy way to handle arrays in Python. The standard way to import this library is as

# In[ ]:

import numpy as np

# Here follows a simple example where we set up an array of ten elements, all determined by random numbers drawn according to the normal distribution,

# In[ ]:

n = 10
x = np.random.normal(size=n)
print(x)

# We defined a vector $x$ with $n=10$ elements with its values given by the Normal distribution $N(0,1)$.
# Another alternative is to declare a vector as follows

# In[ ]:

import numpy as np
x = np.array([1, 2, 3])
print(x)

# Here we have defined a vector with three elements, with $x_0=1$, $x_1=2$ and $x_2=3$. Note that both Python and C++
# start numbering array elements from $0$ and on. This means that a vector with $n$ elements has a sequence of entities $x_0, x_1, x_2, \dots, x_{n-1}$. We could also let (recommended) Numpy to compute the logarithms of a specific array as

# In[ ]:

import numpy as np
x = np.log(np.array([4, 7, 8]))
print(x)

# In the last example we used Numpy's unary function $np.log$. This function is
# highly tuned to compute array elements since the code is vectorized
# and does not require looping. We normaly recommend that you use the
# Numpy intrinsic functions instead of the corresponding **log** function
# from Python's **math** module. The looping is done explicitely by the
# **np.log** function. The alternative, and slower way to compute the
# logarithms of a vector would be to write

# In[ ]:

import numpy as np
from math import log
x = np.array([4, 7, 8])
for i in range(0, len(x)):
    x[i] = log(x[i])
print(x)

# We note that our code is much longer already and we need to import the **log** function from the **math** module.
# The attentive reader will also notice that the output is $[1, 1, 2]$. Python interprets automagically our numbers as integers (like the **automatic** keyword in C++). To change this we could define our array elements to be double precision numbers as

# In[ ]:

import numpy as np
x = np.log(np.array([4, 7, 8], dtype = np.float64))
print(x)

# or simply write them as double precision numbers (Python uses 64 bits as default for floating point type variables), that is

# In[ ]:

import numpy as np
x = np.log(np.array([4.0, 7.0, 8.0])
print(x)

# To check the number of bytes (remember that one byte contains eight bits for double precision variables), you can use simple use the **itemsize** functionality (the array $x$ is actually an object which inherits the functionalities defined in Numpy) as

# In[ ]:

import numpy as np
x = np.log(np.array([4.0, 7.0, 8.0])
print(x.itemsize)

# ### Matrices in Python
#
# Having defined vectors, we are now ready to try out matrices. We can
# define a $3 \times 3 $ real matrix $\hat{A}$ as (recall that we user
# lowercase letters for vectors and uppercase letters for matrices)

# In[ ]:

import numpy as np
A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))
print(A)

# If we use the **shape** function we would get $(3, 3)$ as output, that is verifying that our matrix is a $3\times 3$ matrix. We can slice the matrix and print for example the first column (Python organized matrix elements in a row-major order, see below) as

# In[ ]:

import numpy as np
A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))
# print the first column, row-major order and elements start with 0
print(A[:,0])

# We can continue this was by printing out other columns or rows. The example here prints out the second column

# In[ ]:

import numpy as np
A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))
# print the first column, row-major order and elements start with 0
print(A[1,:])

# Numpy contains many other functionalities that allow us to slice, subdivide etc etc arrays. We strongly recommend that you look up the [Numpy website for more details](http://www.numpy.org/). Useful functions when defining a matrix are the **np.zeros** function which declares a matrix of a given dimension and sets all elements to zero

# In[ ]:

import numpy as np
n = 10
# define a matrix of dimension 10 x 10 and set all elements to zero
A = np.zeros( (n, n) )
print(A)

# or initializing all elements to

# In[ ]:

import numpy as np
n = 10
# define a matrix of dimension 10 x 10 and set all elements to one
A = np.ones( (n, n) )
print(A)

# or as unitarily distributed random numbers (see the material on random number generators in the statistics part)

# In[ ]:

import numpy as np
n = 10
# define a matrix of dimension 10 x 10 and set all elements to random numbers with x \in [0, 1]
A = np.random.rand(n, n)
print(A)

# ### Meet the Pandas
#
# Another useful Python package is
# [pandas](https://pandas.pydata.org/), which is an open source library
# providing high-performance, easy-to-use data structures and data
# analysis tools for Python. **pandas** stands for panel data, a term borrowed from econometrics and is an efficient library for data analysis with an emphasis on tabular data.
#
# **pandas** has two major classes, the **DataFrame** class with
# two-dimensional data objects and tabular data organized in columns and
# the class **Series** with a focus on one-dimensional data objects. Both
# classes allow you to index data easily as we will see in the examples
# below.  **pandas** allows you also to perform mathematical operations on
# the data, spanning from simple reshapings of vectors and matrices to
# statistical operations.
#
# The following simple example shows how we can, in an easy way make
# tables of our data. Here we define a data set which includes names,
# place of birth and date of birth, and displays the data in an easy to
# read way. We will see repeated use of **pandas**, in particular in
# connection with classification of data.

# In[ ]:

import pandas as pd
from IPython.display import display
data = {'First Name': ["Frodo", "Bilbo", "Aragorn II", "Samwise"],
        'Last Name': ["Baggins", "Baggins","Elessar","Gamgee"],
        'Place of birth': ["Shire", "Shire", "Eriador", "Shire"],
        'Date of Birth T.A.': [2968, 2890, 2931, 2980]
        }
data_pandas = pd.DataFrame(data)
display(data_pandas)

# In the above we have imported **pandas** with the shorthand **pd**, the latter has become the standard way we import **pandas**. We make then a list of various variables
# and reorganize the above lists into a **DataFrame** and then print out  a neat table with specific column labels as *Name*, *place of birth* and *date of birth*.
# Displaying these results, we see that the indices are given by the default numbers from zero to three.
# **pandas** is extremely flexible and we can easily change the above indices by defining a new type of indexing as

# In[ ]:

data_pandas = pd.DataFrame(data,index=['Frodo','Bilbo','Aragorn','Sam'])
display(data_pandas)

# Thereafter we display the content of the row which begins with the index **Aragorn**

# In[ ]:

display(data_pandas.loc['Aragorn'])

# We can easily append data to this, for example

# In[ ]:

new_hobbit = {'First Name': ["Peregrin"],
              'Last Name': ["Took"],
              'Place of birth': ["Shire"],
              'Date of Birth T.A.': [2990]
              }
data_pandas=data_pandas.append(pd.DataFrame(new_hobbit, index=['Pippin']))
display(data_pandas)

# Here are other examples where we use the **DataFrame** functionality to handle arrays, now with more interesting features for us, namely numbers. We set up a matrix
# of dimensionality $10\times 5$ and compute the mean value and standard deviation of each column. Similarly, we can perform mathematial operations like squaring the matrix elements and many other operations.

# In[ ]:

import numpy as np
import pandas as pd
from IPython.display import display
np.random.seed(100)
# setting up a 10 x 5 matrix
rows = 10
cols = 5
a = np.random.randn(rows,cols)
df = pd.DataFrame(a)
display(df)
print(df.mean())
print(df.std())
display(df**2)

# Thereafter we can select specific columns only and plot final results

# In[ ]:

df.columns = ['First', 'Second', 'Third', 'Fourth', 'Fifth']
df.index = np.arange(10)

display(df)
print(df['Second'].mean() )
print(df.info())
print(df.describe())

from pylab import plt, mpl
plt.style.use('seaborn')
mpl.rcParams['font.family'] = 'serif'

df.cumsum().plot(lw=2.0, figsize=(10,6))
plt.show()

df.plot.bar(figsize=(10,6), rot=15)
plt.show()

# We can produce a $4\times 4$ matrix

# In[ ]:

b = np.arange(16).reshape((4,4))
print(b)
df1 = pd.DataFrame(b)
print(df1)

# and many other operations.
#
#
# The **Series** class is another important class included in
# **pandas**. You can view it as a specialization of **DataFrame** but where
# we have just a single column of data. It shares many of the same
# features as **DataFrame**. As with **DataFrame**, most operations are
# vectorized, achieving thereby a high performance when dealing with
# computations of arrays, in particular labeled arrays.  As we will see
# below it leads also to a very concice code close to the mathematical
# operations we may be interested in.  For multidimensional arrays, we
# recommend strongly
# [xarray](http://xarray.pydata.org/en/stable/). **xarray** has much of
# the same flexibility as **pandas**, but allows for the extension to
# higher dimensions than two.
#
#
#
#
#
# ## Introduction to Git and GitHub/GitLab and similar
#
# [Git](https://git-scm.com/) is a distributed version-control system
# for tracking changes in any set of files, originally designed for
# coordinating work among programmers cooperating on source code during
# software development.
#
# The [reference document and videos here](https://git-scm.com/doc)
# give you an excellent introduction to the **git**.
#
# We believe you will find version-control software very useful in your work.
#
#
#
#
# All teaching material related to this course is open and freely
# available via the GitHub site of the course. The video here gives a
# short intro to
# [GitHub](https://www.youtube.com/watch/w3jLJU7DT5E?reload=9).
#
# See also the [overview video on Git and GitHub](https://mediaspace.msu.edu/media/t/1_8mgx3cyf).
#
#
#
# ### Useful Git and GitHub links
#
# These are a couple references that we have found useful (git commands, markdown, GitPages):
# * <https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet>
#
# * <https://education.github.com/git-cheat-sheet-education.pdf>
#
# * <https://guides.github.com/features/pages/>
#
# When dealing with homeworks, at some point you would need to use an
# editor, or an integrated development envinroment (IDE). As an IDE, we
# would like to recommend **anaconda** since we end up using
# jupyter-notebooks.  **anaconda** runs on all known operating systems.
#
#
# If you prefer editing **Python** codes, there are several excellent cross-platform editors.
# If you are in a Windows environment, **word** is the classical text editor.
#
# There is however a wealth of text editors and/ord IDEs that run on all operating
# systems and functions well with Python.  Some of the more popular ones  are
#
# * [Atom](https://atom.io/)
#
# * [Sublime](https://www.sublimetext.com/)


#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Mar  9 14:05:02 2020

@author: miguel-asd
"""

from evdev import InputDevice, categorize, ecodes
from select import select
import numpy as np

class Joystick:
    def __init__(self , event):
        #python3 /usr/local/lib/python3.8/dist-packages/evdev/evtest.py for identify event
        self.gamepad = InputDevice(event)
        self.L3 = np.array([0. , 0.])
        self.R3 = np.array([0. , 0.])

        self.x=0
        self.triangle=0
        self.circle=0
        self.square=0

        self.T = 0.4
        self.compliantMode = False
        self.CoM_move = np.zeros(3)
    def read(self):
        r,w,x = select([self.gamepad.fd], [], [], 0.)

        if r:
            for event in self.gamepad.read():
#                print(event)
                if event.type == ecodes.EV_KEY:
                    if event.value == 1:
                        if event.code == 544:#up arrow
                            self.T += 0.05
                        if event.code == 545:#down arrow
                            self.T -= 0.05
                        if event.code == 308:#square
                            if self.compliantMode == True:
                                self.compliantMode = False
                            elif self.compliantMode == False:
                                self.compliantMode = True
                        if event.code == 310:#R1
                            self.CoM_move[0] += 0.0005
                        if event.code == 311:#L1
                            self.CoM_move[0] -= 0.0005
                    else:
                        print("boton soltado")
                ########################################  for my own joystick
                #      ^           #     ^            #
                #    ABS_Y         #    ABS_RY        #
                #  ←─────→ ABS_X #  ←─────→ ABS_RX   #
                #     ↓           #     ↓            #
                #######################################
                elif event.type == ecodes.EV_ABS:
                    absevent = categorize(event)
                    if ecodes.bytype[absevent.event.type][absevent.event.code] == "ABS_X":
                        self.L3[0]=absevent.event.value-127
                    elif ecodes.bytype[absevent.event.type][absevent.event.code] == "ABS_Y":
                        self.L3[1]=absevent.event.value-127
                    elif ecodes.bytype[absevent.event.type][absevent.event.code] == "ABS_RX":
                        self.R3[0]=absevent.event.value-127
#                        print(self.d_z)
                    elif ecodes.bytype[absevent.event.type][absevent.event.code] == "ABS_RY":
                        self.R3[1]=absevent.event.value-127

        L = np.sqrt(self.L3[1]**2 + self.L3[0]**2)/250.
        angle = np.rad2deg(np.arctan2(-self.L3[0] , -self.L3[1]))
        Lrot = -self.R3[0]/250.
#        Lrot = 0.
        if L <= 0.035:
            L = 0.
        if Lrot <= 0.035 and Lrot >= -0.035:
            Lrot = 0.

#        pitch = np.deg2rad(self.R3[1]/2)
#        yaw = np.deg2rad(self.R3[0]/3)
        pitch = 0.
        yaw = 0.
        return self.CoM_move , L , -angle , -Lrot , self.T , self.compliantMode , yaw , pitch