# -*- coding: utf-8 -*-
"""L04_Welliton.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1Z4mLm2egCuODcKhluqWbwYHbnOIjB_y7

**Welliton Leal - Aula de Exercícios 01**

***N-dimensional Arrays***
"""

import numpy as np #importa biblioteca e define atalho pra chama-la
lst = [[1, 2, 3], [4, 5, 6]] #cria lista com duas linhas
ary2d = np.array(lst)  #armazena em um vetor de 2 dimensões
ary2d

ary2d.dtype #exibe o tipo

"""***Array Construction Routines***"""

float32_ary = ary2d.astype(np.float32) #muda o tipo
float32_ary

float32_ary.dtype

ary2d.size #mostra tamanho

ary2d.ndim #mostra dimensão

ary2d.shape #mostra formato

np.array([1, 2, 3]).shape

np.ones((3, 3)) #matriz de 1's

np.zeros((3, 3)) #matriz de 0's

np.eye(3) #matriz ID

np.diag((3, 3, 3)) #matriz IDxEscalar

np.arange(4., 10.) #cria array com valores dentro do intervalo

np.arange(5) #cria array com valores de 0 até o valor

np.linspace(0., 1., num=5) #cria array no intervalo de 0 a 1 dividido em 5 partes = 1/5

"""***Array Indexing***"""

ary = np.array([1, 2, 3]) #exibe valor da pos 0
ary[0]

ary[:2] # equivalent to ary[0:2]

ary = np.array([[1, 2, 3],
... [4, 5, 6]])
ary[0, 0] #exibe valor na pos superior esquerda

ary[-1, -1] # exibe valor na pos inferior da direita

ary[0, 1] #exibe primeira linha segunda coluna

ary[0] # exibe primeira linha inteira

ary[:, 0] # exibe a primeira coluna inteira

ary[:, :2] #exibe as primeiras duas colunas

ary[0,0]

"""***Array Math and Universal Functions***"""

lst = [[1, 2, 3], [4, 5, 6]] #cria lista
for row_idx, row_val in enumerate(lst):
  for col_idx, col_val in enumerate(row_val):
    lst[row_idx][col_idx] += 1
lst

lst = [[1, 2, 3], [4, 5, 6]]
[[cell + 1 for cell in row] for row in lst]

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

ary + 1 #soma 1 em tudo

ary**2 #multiplica tudo por 2

ary = np.array([[1, 2, 3],
... [4, 5, 6]])
np.add.reduce(ary) #soma as colunas

np.add.reduce(ary, axis=1) #soma as linha

ary.sum(axis=0) #soma as colunas

ary.sum() #some todos os valores

"""***Broadcasting***"""

ary1 = np.array([1, 2, 3])
ary2 = np.array([4, 5, 6])
ary1 + ary2 #soma os 2 vetores valor a valor

ary3 = np.array([[4, 5, 6],
... [7, 8, 9]]) #definindo nova lista

ary3 + ary1 #soma ary1 + ary3

"""***Advanced Indexing – Memory Views and Copies***"""

ary = np.array([[1, 2, 3],
... [4, 5, 6]])
first_row = ary[0] #cria variável e armazena toda a primeira linha
first_row += 99 #soma 99 a a todos os valores
ary

ary = np.array([[1, 2, 3],
... [4, 5, 6]])
center_col = ary[:, 1] #recebe só a coluna do meio
center_col += 99 #soma a coluna do meio + 99
ary

ary = np.array([[1, 2, 3],
... [4, 5, 6]])
second_row = ary[1].copy()
second_row += 99
ary

ary = np.array([[1, 2, 3],
... [4, 5, 6]])
ary[:, [0, 2]] # first and and last column

ary[:, [2, 0]] # first and and last column

ary = np.array([[1, 2, 3],
... [4, 5, 6]])
greater3_mask = ary > 3 #retorna "true" pra valores maiores que 3
greater3_mask

ary[greater3_mask] #retorna os valores maiores que 3

ary[(ary > 3) & (ary % 2 == 0)] #maiores que 3 e divisíveis por 2

"""***Random Number Generators***"""

np.random.seed(123) #gerador de randomicos 
np.random.rand(3) #quantidade de números

rng1 = np.random.RandomState(seed=123)
rng1.rand(3)

"""***Reshaping Arrays***"""

ary1d = np.array([1, 2, 3, 4, 5, 6])
ary2d_view = ary1d.reshape(2, 3)
ary2d_view

np.may_share_memory(ary2d_view, ary1d)

ary1d.reshape(2, -1)

ary1d.reshape(-1, 2)

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

ary.reshape(-1)

ary = np.array([1, 2, 3])

# stack along the first axis
np.concatenate((ary, ary))

ary = np.array([[1, 2, 3]])

# stack along the first axis (here: rows)
np.concatenate((ary, ary), axis=0)

# stack along the second axis (here: column)
np.concatenate((ary, ary), axis=1)

"""***Comparison Operators and Masks***"""

ary = np.array([1, 2, 3, 4])
mask = ary > 2 #true para todos os masiores
mask

ary[mask] #todos que cumpriram a restrição

mask.sum() #qtd deles

np.where(ary > 2, 1, 0) # 1 para os que cumpriram a restrição

ary = np.array([1, 2, 3, 4])
mask = ary > 2
ary[mask] = 1
ary[~mask] = 0
ary

ary = np.array([1, 2, 3, 4])
(ary > 3) | (ary < 2) #retorna de acordo com a condição

~((ary > 3) | (ary < 2)) #retorna o contrário da condição, sua negação

"""*** Linear Algebra with NumPy Arrays***"""

row_vector = np.array([1, 2, 3])
row_vector

column_vector = np.array([[1, 2, 3]]).reshape(-1, 1)
column_vector

row_vector[:, np.newaxis]

row_vector[:, None]

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

np.matmul(matrix, column_vector)

np.matmul(matrix, row_vector)

np.matmul(row_vector, row_vector)

np.dot(row_vector, row_vector)

np.dot(matrix, row_vector)

np.dot(matrix, column_vector)

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

matrix.transpose()

np.matmul(matrix, matrix.transpose())

matrix.T

"""***Matplotlib***"""

# Commented out IPython magic to ensure Python compatibility.
# %matplotlib inline
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x))
plt.show()

x = np.linspace(0, 10, 100)

plt.plot(x, np.sin(x))
plt.xlim([2, 8])
plt.ylim([0, 0.75])
plt.xlabel('x-axis')
plt.ylabel('y-axis')

x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x), label=('sin(x)'))
plt.plot(x, np.cos(x), label=('cos(x)'))
plt.ylabel('f(x)')
plt.xlabel('x')
plt.legend(loc='lower left')

"""*** Scatter Plots***"""

rng = np.random.RandomState(123)
x = rng.normal(size=500)
y = rng.normal(size=500)
plt.scatter(x, y)
plt.show()

"""***Bar Plots***"""

# input data
means = [1, 2, 3]
stddevs = [0.2, 0.4, 0.5]
bar_labels = ['bar 1', 'bar 2', 'bar 3']
# plot bars
x_pos = list(range(len(bar_labels)))
plt.bar(x_pos, means, yerr=stddevs)
plt.show()

"""***Histograms***"""

rng = np.random.RandomState(123)
x = rng.normal(0, 20, 1000)
# fixed bin size
bins = np.arange(-100, 100, 5) # fixed bin size
plt.hist(x, bins=bins)
plt.show()

rng = np.random.RandomState(123)
x1 = rng.normal(0, 20, 1000)
x2 = rng.normal(15, 10, 1000)
# fixed bin size
bins = np.arange(-100, 100, 5) # fixed bin size
plt.hist(x1, bins=bins, alpha=0.5)
plt.hist(x2, bins=bins, alpha=0.5)
plt.show()

"""***Subplots***"""

import matplotlib.pyplot as plt
x = range(11)
y = range(11)
fig, ax = plt.subplots(nrows=2, ncols=3, sharex=True, sharey=True)
for row in ax:
  for col in row:
    col.plot(x, y)
plt.show()

"""***Colors and Markers***"""

x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x),
color='orange',
marker='^',
linestyle='')
plt.show()

"""***Saving Plots***"""

x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x))
plt.savefig('myplot.png', dpi=300)
plt.savefig('myplot.pdf')
plt.show()