# Versão da Linguagem Python
from platform import python_version
print('Versão da Linguagem Python Usada Neste Jupyter Notebook:', python_version())

"""
Explanation: <font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 8</font>
Download: http://github.com/dsacademybr
End of explanation
"""


import scipy
scipy.__version__

import matplotlib
matplotlib.__version__

# Função imread foi descontinuada no Scipy
# from scipy import misc
# misc.imread('Matplotlib-Mapa.png')   

# Usamos agora a função do pacote imageio
from imageio import imread
imread('Matplotlib-Mapa.png')  

# Matplotlib tem uma função similar
import matplotlib.pyplot as plt
plt.imread('Matplotlib-Mapa.png') 

"""
Explanation: SciPy
Para compreender o SciPy é necessário compreender conceitos avançados de Matemática e Estatística, o que está fora do escopo deste treinamento. Caso queira aprender aplicações práticas do pacote em Machine Learning e IA, consulte estes dois cursos aqui na DSA:
<a href="https://www.datascienceacademy.com.br/course/machine-learning-engineer">Machine Learning</a>
<a href="https://www.datascienceacademy.com.br/course/programao-paralela-em-gpu">Programação Paralela em GPU</a>
O SciPy possui um conjunto de pacotes para operações matemáticas e científicas
<table class="ArticleTableNoBorder">
    <tbody>
        <tr>
            <td><strong>Pacote</strong></td>
            <td><strong>Descrição</strong></td>
        </tr>
        <tr>
            <td><code>cluster</code></td>
            <td>Clustering algorithms</td>
        </tr>
        <tr>
            <td><code>constants</code></td>
            <td>Mathematical and physical constants</td>
        </tr>
        <tr>
            <td><code>fftpack</code></td>
            <td>Fourier transforms</td>
        </tr>
        <tr>
            <td><code>integrate</code></td>
            <td>Numerical integration</td>
        </tr>
        <tr>
            <td><code>interpolate</code></td>
            <td>Interpolation</td>
        </tr>
        <tr>
            <td><code>io</code></td>
            <td>Input and output</td>
        </tr>
        <tr>
            <td><code>linalg</code></td>
            <td>Linear algebra</td>
        </tr>
        <tr>
            <td><code>maxentropy</code></td>
            <td>Maximum entropy models</td>
        </tr>
        <tr>
            <td><code>misc</code></td>
            <td>Miscellaneous</td>
        </tr>
        <tr>
            <td><code>ndimage</code></td>
            <td>Multi-dimensional image processing</td>
        </tr>
        <tr>
            <td><code>odr</code></td>
            <td>Orthogonal distance regression</td>
        </tr>
        <tr>
            <td><code>optimize</code></td>
            <td>Optimization</td>
        </tr>
        <tr>
            <td><code>signal</code></td>
            <td>Signal processing</td>
        </tr>
        <tr>
            <td><code>sparse</code></td>
            <td>Sparse matrices</td>
        </tr>
        <tr>
            <td><code>spatial</code></td>
            <td>Spatial algorithms and data structures</td>
        </tr>
        <tr>
            <td><code>special</code></td>
            <td>Special functions</td>
        </tr>
        <tr>
            <td><code>stats</code></td>
            <td>Statistical functions</td>
        </tr>
        <tr>
            <td><code>stsci</code></td>
            <td>Image processing</td>
        </tr>
        <tr>
            <td><code>weave</code></td>
            <td>C/C++ integration</td>
        </tr>
    </tbody>
</table>

Processamento de Imagens
End of explanation
"""


import numpy as np
np.__version__

from numpy import *
from scipy.integrate import quad, dblquad, tplquad

# Integração
val, abserr = quad(lambda x: exp(-x ** 2),  Inf, Inf)
val, abserr

from scipy.integrate import odeint, ode

from pylab import *
%matplotlib inline

def dy(y, t, zeta, w0):
    x, p = y[0], y[1]
    
    dx = p
    dp = -2 * zeta * w0 * p - w0**2 * x

    return [dx, dp]


y0 = [1.0, 0.0]

t = linspace(0, 10, 1000)
w0 = 2*pi*1.0


y1 = odeint(dy, y0, t, args=(0.0, w0)) 
y2 = odeint(dy, y0, t, args=(0.2, w0)) 
y3 = odeint(dy, y0, t, args=(1.0, w0)) 
y4 = odeint(dy, y0, t, args=(5.0, w0)) 

fig, ax = subplots()
ax.plot(t, y1[:,0], 'k', label="Não Abafado", linewidth=0.25)
ax.plot(t, y2[:,0], 'r', label="Pouco Abafado")
ax.plot(t, y3[:,0], 'b', label="Criticamente Abafado")
ax.plot(t, y4[:,0], 'g', label="Perigosamente Abafado")
ax.legend();

"""
Explanation: Integração Numérica
End of explanation
"""


from scipy.fftpack import *

# Fourier transformation
N = len(t)
dt = t[1]-t[0]

F = fft(y2[:,0]) 

w = fftfreq(N, dt)

fig, ax = subplots(figsize=(9,3))
ax.plot(w, abs(F));

"""
Explanation: Fourier Transformation
End of explanation
"""


A = np.array([[3, 2, 0], [1, -1, 0], [0, 5, 1]])
b = np.array([2, 4, -1])

# Resolvendo um sistema de equações lineares
x = solve(A, b)
x

A = rand(3,3)
B = rand(3,3)

evals, evecs = eig(A)

evals

evecs

svd(A)

"""
Explanation: Álgebra Linear
End of explanation
"""


from scipy import optimize

def f(x):
    return 4*x**3 + (x-2)**2 + x**4

fig, ax  = subplots()
x = linspace(-5, 3, 100)
ax.plot(x, f(x));

x_min = optimize.fmin_bfgs(f, -0.5)
x_min

"""
Explanation: Otimização
End of explanation
"""


from scipy import stats

Y = stats.norm()

x = linspace(-5,5,100)

fig, axes = subplots(3,1, sharex=True)

axes[0].plot(x, Y.pdf(x))

axes[1].plot(x, Y.cdf(x));

axes[2].hist(Y.rvs(size=1000), bins=50);

Y.mean(), Y.std(), Y.var()

# T-test
t_statistic, p_value = stats.ttest_ind(Y.rvs(size=1000), Y.rvs(size=1000))
t_statistic, p_value

"""
Explanation: Estatística
End of explanation
"""


