Skip to content

Commit

Permalink
integração completa com numpy
Browse files Browse the repository at this point in the history
  • Loading branch information
viniciusdutra314 committed Jan 21, 2025
1 parent 121fe52 commit 72f98f2
Show file tree
Hide file tree
Showing 13 changed files with 61 additions and 166 deletions.
5 changes: 0 additions & 5 deletions LabIFSC2/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,6 @@

from ._arrays import (arrayM, curva_max, curva_min, incertezas, linspace,
nominais)
from ._matematica import (aceitamedida, acos, acosh, arccos, arccosh, arcseno,
arcsin, arcsinh, arctan, arctanh, arctg, asenh, asin,
asinh, atan, atanh, atgh, cbrt, cos, cosh, exp, exp2,
ln, log, log2, log10, pow, power, senh, seno, sin,
sinh, sqrt, tan, tanh, tg, tgh)
from ._medida import Comparacao, Medida, comparar_medidas, montecarlo
from ._regressões import (MExponencial, MPolinomio, regressao_exponencial,
regressao_linear, regressao_polinomial,
Expand Down
2 changes: 1 addition & 1 deletion LabIFSC2/_arrays.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ def linspace(a:Real,b:Real,n : int,
entre as Medidas
"""
return np.array([Medida(i,incertezas,unidade) for i in np.linspace(float(a),float(b),n)])
return np.array([Medida(i,incertezas,unidade) for i in np.linspace(float(a),float(b),n)],dtype=object)


@obrigar_tipos
Expand Down
86 changes: 0 additions & 86 deletions LabIFSC2/_matematica.py

This file was deleted.

13 changes: 13 additions & 0 deletions LabIFSC2/_medida.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,19 @@ def __str__(self) -> str:
return self.__format__('')
def __repr__(self) -> str:
return self.__format__('')
'''O método abaixo faz a magia que basicamente qualquer função do numpy possa
ser aplicada diretamente em uma medida
'''
def __getattr__(self, func_name:str) -> Any:
funcoes_suportadas=['sin','cos','exp','sqrt',"sinh","cosh","tanh","arcsinh","arccosh",
"arctanh","cbrt","power","pow",
'tan','arcsin','arccos','arctan','log','log2','log10']
if func_name not in funcoes_suportadas:
raise AttributeError
else:
func=getattr(np,func_name)
def FuncaoComMedida() -> Any: return montecarlo(func, self)
return FuncaoComMedida

def _adicao_subtracao(self,outro: 'Medida',positivo:bool) -> 'Medida':
if not (isinstance(outro,Medida) or isinstance(outro,Real)):
Expand Down
7 changes: 4 additions & 3 deletions LabIFSC2/_regressões.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@

import numpy as np
import pint
from numpy import exp, log, power
from numpy.polynomial import Polynomial

from ._arrays import arrayM, nominais
from ._matematica import aceitamedida, exp, log, power
from ._medida import Medida
from ._tipagem_forte import obrigar_tipos

Expand Down Expand Up @@ -74,7 +74,8 @@ def __init__(self,a:Medida,k:Medida,base:Real):

@obrigar_tipos
def __call__(self,x:Medida | np.ndarray) -> Medida | np.ndarray:
resultado: Medida | np.ndarray=self.a*power(float(self.base),x*self.k)
base=Medida(self.base,0,"")
resultado: Medida | np.ndarray=self.a*base**(x*self.k)
return resultado

def __repr__(self)->str:
Expand Down Expand Up @@ -152,7 +153,7 @@ def regressao_exponencial(x_medidas:np.ndarray,y_medidas:np.ndarray,

if base<1: raise ValueError('Base precisa ser maior que 1')

pegar_log=lambda x: log(x)/log(base)
pegar_log=lambda x: log(x)/log(float(base))
log_y_medidas=_aplicar_funcao_sem_passar_pelo_sistema_de_unidades(y_medidas,pegar_log)
polinomio=regressao_linear(x_medidas,log_y_medidas)
k=polinomio.a
Expand Down
13 changes: 0 additions & 13 deletions tests/test_doc_aceitamedida.py

This file was deleted.

2 changes: 1 addition & 1 deletion tests/test_doc_grafico_fitting.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,4 @@
plt.fill_between(nominais(x,unidade_x),curva_min(regressao(x),unidade_y),
curva_max(regressao(x),unidade_y),color='blue',alpha=0.3)
plt.legend()
plt.savefig('teste.jpg')
#plt.savefig('teste.jpg')
2 changes: 1 addition & 1 deletion tests/test_doc_sqrt_vetorizado.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@

areas=np.array([Medida(4,0.01,'cm²'),Medida(9,0.01,'m²'),
Medida(16,0.01,'km²')])
lados=sqrt(areas)
lados=np.sqrt(areas)
print(lados) #[(2,000 ± 0,003) cm (3,000 ± 0,002) m (4,000 ± 0,001) km]
#assert str(lados)== "[(2,000 ± 0,003) cm (3,000 ± 0,002) m (4,000 ± 0,001) km]"
13 changes: 0 additions & 13 deletions tests/test_funcoes_vetorizadas.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,6 @@
import LabIFSC2 as lab


def test_funcoes_customizadas():
x=lab.Medida(0,0.01,'')
sinc=lambda x: np.sin(x)/x
with pytest.raises(TypeError):
sinc(x)
lab_sinc=lab.aceitamedida(sinc)
assert np.isclose(lab_sinc(x).nominal(""),1,rtol=1e-4)
x_array=lab.linspace(0.1,10,10,0.001,'')
aplicado=lab_sinc(x_array)
for i in range(len(aplicado)):
assert np.isclose(aplicado[i].nominal(""),
sinc(x_array[i].nominal("")),rtol=1e-4)

def test_array_medida_soma():
x=lab.Medida(0,0.0001,'')
x_array=lab.linspace(0,10,10,0.001,'')
Expand Down
34 changes: 17 additions & 17 deletions tests/test_propagacao_de_erros.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def comparar_ufloat_lab2(ufloat:ufloat,medida_lab2:lab2.Medida,precisao=1e-3):
assert np.isclose(medida_lab2.incerteza(""),ufloat.std_dev,rtol=precisao)


def test_number_in_a_lab_func(): assert lab2.sin(0)==0
def test_number_in_a_lab_func(): assert np.sin(0)==0

def test_arithmetic_operations():
incerteza = 1e-4
Expand Down Expand Up @@ -80,59 +80,59 @@ def test_trignometria():
for value in np.linspace(0.5,0,9,100):
x = umath.sin(ufloat(value, incerteza))
x_lab1 = lab1.sin(lab1.Medida((value, incerteza), ''))
x_lab2 = lab2.sin(lab2.Medida(value, incerteza, ''))
x_lab2 = np.sin(lab2.Medida(value, incerteza, ''))
comparar_relativo_ufloat_lab1_lab2(x, x_lab1, x_lab2)

x = umath.cos(ufloat(value, incerteza))
x_lab1 = lab1.cos(lab1.Medida((value, incerteza), ''))
x_lab2 = lab2.cos(lab2.Medida(value, incerteza, ''))
x_lab2 = np.cos(lab2.Medida(value, incerteza, ''))
comparar_relativo_ufloat_lab1_lab2(x, x_lab1, x_lab2)

x = umath.tan(ufloat(value, incerteza))
x_lab1 = lab1.tan(lab1.Medida((value, incerteza), ''))
x_lab2 = lab2.tan(lab2.Medida(value, incerteza, ''))
x_lab2 = np.tan(lab2.Medida(value, incerteza, ''))
comparar_relativo_ufloat_lab1_lab2(x, x_lab1, x_lab2, precisao=1e-1)

x = umath.asin(ufloat(value , incerteza))
x_lab1 = lab1.arc_sin(lab1.Medida((value , incerteza), ''))
x_lab2 = lab2.asin(lab2.Medida(value , incerteza, ''))
x_lab2 = np.asin(lab2.Medida(value , incerteza, ''))
comparar_relativo_ufloat_lab1_lab2(x, x_lab1, x_lab2)

x = umath.acos(ufloat(value , incerteza))
x_lab1 = lab1.arc_cos(lab1.Medida((value , incerteza), ''))
x_lab2 = lab2.acos(lab2.Medida(value , incerteza, ''))
x_lab2 = np.acos(lab2.Medida(value , incerteza, ''))
comparar_relativo_ufloat_lab1_lab2(x, x_lab1, x_lab2)

x = umath.atan(ufloat(value, incerteza))
x_lab1 = lab1.arc_tan(lab1.Medida((value, incerteza), ''))
x_lab2 = lab2.atan(lab2.Medida(value, incerteza, ''))
x_lab2 = np.atan(lab2.Medida(value, incerteza, ''))
comparar_relativo_ufloat_lab1_lab2(x, x_lab1, x_lab2,precisao=1)

def test_hiperbolicas():
incerteza = 1e-6
for value in np.linspace(0.5, 1, 100):
x = umath.sinh(ufloat(value, incerteza))
x_lab2 = lab2.sinh(lab2.Medida(value, incerteza, ''))
x_lab2 = np.sinh(lab2.Medida(value, incerteza, ''))
comparar_ufloat_lab2(x, x_lab2,precisao=1e-2)

x = umath.cosh(ufloat(value, incerteza))
x_lab2 = lab2.cosh(lab2.Medida(value, incerteza, ''))
x_lab2 = np.cosh(lab2.Medida(value, incerteza, ''))
comparar_ufloat_lab2(x, x_lab2)

x = umath.tanh(ufloat(value, incerteza))
x_lab2 = lab2.tanh(lab2.Medida(value, incerteza, ''))
x_lab2 = np.tanh(lab2.Medida(value, incerteza, ''))
comparar_ufloat_lab2(x, x_lab2)

x = umath.asinh(ufloat(value, incerteza))
x_lab2 = lab2.asinh(lab2.Medida(value, incerteza, ''))
x_lab2 = np.asinh(lab2.Medida(value, incerteza, ''))
comparar_ufloat_lab2(x, x_lab2)

x = umath.acosh(ufloat(value + 1, incerteza)) # value + 1 to ensure it's in the domain of acosh
x_lab2 = lab2.acosh(lab2.Medida(value + 1, incerteza, ''))
x_lab2 = np.acosh(lab2.Medida(value + 1, incerteza, ''))
comparar_ufloat_lab2(x, x_lab2)

x = umath.atanh(ufloat(value / 2, incerteza)) # value / 2 to ensure it's in the domain of atanh
x_lab2 = lab2.atanh(lab2.Medida(value / 2, incerteza, ''))
x_lab2 = np.atanh(lab2.Medida(value / 2, incerteza, ''))
comparar_ufloat_lab2(x, x_lab2)


Expand All @@ -141,21 +141,21 @@ def test_power():
for value in np.linspace(1,3,100):
x = umath.pow(ufloat(value, incerteza), 2)
x_lab1 = lab1.Medida((value, incerteza), '')**2
x_lab2 = lab2.pow(lab2.Medida(value, incerteza, ''), 2)
x_lab2 = np.pow(lab2.Medida(value, incerteza, ''), 2)
comparar_relativo_ufloat_lab1_lab2(x, x_lab1, x_lab2)

x = umath.pow(ufloat(value, incerteza), 3)
x_lab1 = lab1.Medida((value, incerteza), '')**3
x_lab2 = lab2.pow(lab2.Medida(value, incerteza, ''), 3)
x_lab2 = np.pow(lab2.Medida(value, incerteza, ''), 3)
comparar_relativo_ufloat_lab1_lab2(x, x_lab1, x_lab2)

x = umath.sqrt(ufloat(value, incerteza))
x_lab1 = lab1.sqrt(lab1.Medida((value, incerteza), ''))
x_lab2 = lab2.sqrt(lab2.Medida(value, incerteza, ''))
x_lab2 = np.sqrt(lab2.Medida(value, incerteza, ''))
comparar_relativo_ufloat_lab1_lab2(x, x_lab1, x_lab2)

x = ufloat(value, incerteza)**(1/3)
x_lab1 = lab1.cbrt(lab1.Medida((value, incerteza), ''))
x_lab2 = lab2.cbrt(lab2.Medida(value, incerteza, ''))
x_lab2 = np.cbrt(lab2.Medida(value, incerteza, ''))
comparar_relativo_ufloat_lab1_lab2(x, x_lab1, x_lab2)

15 changes: 7 additions & 8 deletions tests/test_regressoes_exponenciais.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,26 +33,25 @@ def test_MExponencial_call():
(1,0)
])
def test_equivalencia_com_scipy(a, k):
exponencial_lab = lambda x, a, k: a * lab.exp(k * x)
exponencial_np = lambda x, a, k: a * np.exp(k * x)

ruido = np.random.normal(1, 0.001, 100)
x_dados = np.linspace(3, 10, 100)
y_dados = exponencial_lab(x_dados, a, k) * ruido
y_dados = exponencial_np(x_dados, a, k) * ruido
popt, pcov = curve_fit(exponencial_np, x_dados, y_dados, p0=[a, k])
a_scipy, k_scipy = popt
perr = np.sqrt(np.diag(pcov))
a_scipy = lab.Medida(a_scipy, perr[0], '')
k_scipy = lab.Medida(k_scipy, perr[1], '')

x_dados = lab.linspace(3, 10, 100, 0.01, '')
y_dados = exponencial_lab(x_dados, a, k) * ruido
exponencial_lab = lab.regressao_exponencial(x_dados, y_dados)
y_dados = exponencial_np(x_dados, a, k) * ruido
exponencial_np = lab.regressao_exponencial(x_dados, y_dados)

assert np.isclose(a_scipy.nominal(""),exponencial_lab.a.nominal(""),atol=(5e-1)*a)
assert np.isclose(k_scipy.nominal(""),exponencial_lab.k.nominal(""),atol=(1e-2))
assert np.isclose(a,exponencial_lab.a.nominal(""),rtol=1e-2) or np.isclose(a,exponencial_lab.a.nominal(""),atol=1e-2)
assert np.isclose(k,exponencial_lab.k.nominal(""),rtol=1e-2) or np.isclose(k,exponencial_lab.k.nominal(""),atol=1e-2)
assert np.isclose(a_scipy.nominal(""),exponencial_np.a.nominal(""),atol=(5e-1)*a)
assert np.isclose(k_scipy.nominal(""),exponencial_np.k.nominal(""),atol=(1e-2))
assert np.isclose(a,exponencial_np.a.nominal(""),rtol=1e-2) or np.isclose(a,exponencial_np.a.nominal(""),atol=1e-2)
assert np.isclose(k,exponencial_np.k.nominal(""),rtol=1e-2) or np.isclose(k,exponencial_np.k.nominal(""),atol=1e-2)



Expand Down
15 changes: 7 additions & 8 deletions tests/test_regressoes_potencia.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,22 +14,21 @@
(1,0.05)
])
def test_lei_de_potencia(a, b):
potencia_lab = lambda x, a, b: a * lab.pow(x, b)
potencia_np = lambda x, a, b: a * np.power(x, b)

ruido = np.random.normal(1, 0.002, 100)
x_dados = np.linspace(3, 10, 100)
y_dados = potencia_lab(x_dados, a, b) * ruido
y_dados = potencia_np(x_dados, a, b) * ruido
popt, pcov = curve_fit(potencia_np, x_dados, y_dados)
a_scipy, b_scipy = popt

x_dados = lab.linspace(3, 10, 100, 0.01, '')
y_dados = potencia_lab(x_dados, a, b) * ruido
potencia_lab = lab.regressao_potencia(x_dados, y_dados)
assert np.isclose(a_scipy,potencia_lab.a.nominal(""),atol=(1e-2)*a)
assert np.isclose(b_scipy,potencia_lab.n.nominal(""),atol=(1e-2))
assert np.isclose(a,potencia_lab.a.nominal(""),rtol=1e-2) or np.isclose(a,potencia_lab.a.nominal(""),atol=1e-2)
assert np.isclose(b,potencia_lab.n.nominal(""),rtol=1e-2) or np.isclose(b,potencia_lab.n.nominal(""),atol=1e-2)
y_dados = potencia_np(x_dados, a, b) * ruido
potencia_np = lab.regressao_potencia(x_dados, y_dados)
assert np.isclose(a_scipy,potencia_np.a.nominal(""),atol=(1e-2)*a)
assert np.isclose(b_scipy,potencia_np.n.nominal(""),atol=(1e-2))
assert np.isclose(a,potencia_np.a.nominal(""),rtol=1e-2) or np.isclose(a,potencia_np.a.nominal(""),atol=1e-2)
assert np.isclose(b,potencia_np.n.nominal(""),rtol=1e-2) or np.isclose(b,potencia_np.n.nominal(""),atol=1e-2)


def test_exceptions():
Expand Down
Loading

0 comments on commit 72f98f2

Please sign in to comment.