9 - INTERPOLACAO-E-AJUSTE-CURVAS

502 days ago by jmarcellopereira

INTERPOLAÇÃO E AJUSTE DE CURVAS

INTERPOLAÇÃO

Função Interp1d. 

‘linear’, ‘nearest’, ‘zero’, ‘slinear’, ‘quadratic, ‘cubic’ where ‘slinear’, ‘quadratic’ and ‘cubic’ refer to a spline interpolation of first, second or third order) or as an integer specifying the order of the spline interpolator to use. Default is ‘linear’.

x = [0,0.500000000000000,1,1.50000000000000,2,2.50000000000000,3,3.50000000000000,4,4.50000000000000,5] y = [1,3,4,6,9,7,8,4,3,8,10] 
       
from scipy.interpolate import interp1d 
       
f_int_linear = interp1d(x,y,kind = 'linear') f_int_linear 
       
g_int_spcubic = interp1d(x,y,kind = 'cubic') g_int_spcubic 
       

Testando

f_int_linear(1.8); g_int_spcubic(1.8) 
       

point(zip(x,y), legend_label='pontos',size = 30,gridlines='minor', figsize=(6, 5)) + plot(f_int_linear,(0,5),legend_label='Int.Linear',color='red',figsize=(6, 5)) + plot(g_int_spcubic,(0,5),legend_label='Int.Cubic',color='black') 
       

Função Spline

x = [0,0.500000000000000,1,1.50000000000000,2,2.50000000000000,3,3.50000000000000,4,4.50000000000000,5] y = [1,3,4,6,9,7,8,4,3,8,10] 
       
pontos = zip(x,y) 
       
point(pontos, legend_label="pontos",size = 30,gridlines="minor", figsize=(6, 5)) 
       
f_spline = spline(pontos) 
       

Saber qual é o ponto  correspondente a x = 0.2

f_spline(0.2) 
       
point(pontos, legend_label="pontos",size = 30,gridlines="minor", figsize=(6, 5)) + plot(f_spline,(0,5),legend_label="spline", color = "red", gridlines="minor"); 
       

AJUSTE DE CURVAS

LINEAR

reset(); 
       
var("a,b,x,y") 
       
import csv 
       

faça o upload do arquivo "tabela_reta.csv"

tabela_reta = open(DATA + "dados_reta.csv","rU") 
       
x = [0.0,0.2,0.4,0.8,1.0,1.2,1.4,1.6,2.0,2.2,2.6,2.8,3.0,3.4] y = [-0.183440428023042, -0.131101157495126, 0.0268875670852843, 0.110532679260319, 0.253944632998395, 0.257190123748649, 0.531888837111346, 0.579048247883555, 0.935180993484717, 0.916600344376623, 1.13328608090532, 1.26893326843583, 1.10202945535186, 1.13391615491257]; 
       
 
       
tab = open('dados_reta.csv', 'wb') 
       
tabela_reta.flush? 
       

File:

Type: <type 'builtin_function_or_method'>

Definition: tabela_reta.flush(*args, **kwds)

Docstring:


flush() -> None.  Flush the internal I/O buffer.

File:

Type: <type 'builtin_function_or_method'>

Definition: tabela_reta.flush(*args, **kwds)

Docstring:


flush() -> None.  Flush the internal I/O buffer.
pontos = zip(x,y) 
       
points(pontos,color = "red",size=20,legend_label="pontos coletados",gridlines="minor", figsize=(6, 5)) 
       
modelo_reta(x) = a*x + b; modelo_reta 
       
# A opção solution_dict=True,utilizada para criar o dicionários das constantes, é opcional, mas caso não ocorra erro, coloque-a como true ajuste = find_fit(pontos, modelo_reta,[0.5,0.5],solution_dict=True);ajuste 
       
modelo_reta_ajustado(x) = modelo_reta.subs(ajuste);modelo_reta_ajustado(x) 
       
point(pontos,color = "red",size=20,legend_label="pontos coletados",gridlines="minor", figsize=(6, 5)) + plot(modelo_reta_ajustado(x),(x,0,3.5),legend_label="reta ajustada") 
       

POLINOMIAL (GRAU>1)

ATENÇÃO! É importante resetar as variaveis antes de usar os outros modelos de ajuste de curvas, pois as constantes a,b,c são as mesmas em todos os modelos

reset() 
       
var("a, b, c, x") 
       
x = [0.000000000000000, 0.500000000000000, 1.00000000000000, 1.50000000000000, 2.00000000000000, 2.50000000000000, 3.00000000000000, 3.50000000000000, 4.00000000000000, 4.50000000000000, 5.00000000000000, 5.50000000000000,6.00000000000000,6.50000000000000,7.00000000000000,7.50000000000000,8.00000000000000,8.50000000000000,9.00000000000000,9.50000000000000]; y = [1.03736647643897, 4.18970182023376, 9.37327499233461, 13.5687048342334, 15.5096536090038, 17.7217021365479, 20.6548588248431, 21.5216664448986, 23.3510698514123, 25.3057105638087, 25.5157069999231, 24.1923642765836, 24.6472608635721, 23.4335951485990, 21.4386185353279, 19.0562165935788,16.5694168481929, 12.2986069810249, 11.1529183727088, 4.59224973788333] 
       
pontos = zip(x,y) 
       
point(pontos,color = "red",size=20,legend_label="pontos coletados", gridlines="minor", figsize=(6, 5)) 
       
modelo_polinomial(x) = a*x^2 + b*x + c; modelo_polinomial 
       
# A opção solution_dict=True,utilizada para criar o dicionários das constantes, é opcional, mas caso não ocorra erro, coloque-a como true ajuste = find_fit(pontos, modelo_polinomial,[0.5,0.5,0.5],solution_dict=True);ajuste 
       
modelo_polinomial_ajustado(x) = modelo_polinomial.subs(ajuste);modelo_polinomial_ajustado(x) 
       
point(pontos,color = "red",size=20,legend_label="pontos coletados",gridlines="minor", figsize=(6, 5)) + plot(modelo_polinomial_ajustado(x) ,(x,0,10),legend_label="curva ajustada") 
       

Mini Função Caseira de Ajuste Polinomial

print(0:10) 
       
Traceback (click to the left of this block for traceback)
...
SyntaxError: invalid syntax
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "_sage_input_55.py", line 10, in <module>
    exec compile(u'open("___code___.py","w").write("# -*- coding: utf-8 -*-\\n" + _support_.preparse_worksheet_cell(base64.b64decode("cHJpbnQoMDoxMCk="),globals())+"\\n"); execfile(os.path.abspath("___code___.py"))
  File "", line 1, in <module>
    
  File "/tmp/tmpzUmnVB/___code___.py", line 3
    print(_sage_const_0 :_sage_const_10 )
                        ^
SyntaxError: invalid syntax
def fpolyfit(x, y, n): for i in range(1,len(x)): for p in range(0,n): A = (x(i))**p return show(A\y) 
       

def fpolyfit(x, y, n):

A = [ (x(i))^p for i = 1:length(x), p = range(0,n) ]:
A \ y

def fpolyfit(x, y, h): A = [ n(x[i])^p for i in range(2,len(x)), p in range(1,h) ] return show(A) 
       
A = [ n(x[i])**p for i in range(0,len(x)+1), p in range(0,3) ] 
       
Traceback (click to the left of this block for traceback)
...
NameError: name 'p' is not defined
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "_sage_input_58.py", line 10, in <module>
    exec compile(u'open("___code___.py","w").write("# -*- coding: utf-8 -*-\\n" + _support_.preparse_worksheet_cell(base64.b64decode("QSA9IFsgbih4W2ldKSoqcCBmb3IgaSBpbiByYW5nZSgwLGxlbih4KSsxKSwgcCBpbiByYW5nZSgwLDMpIF0="),globals())+"\\n"); execfile(os.path.abspath("___code___.py"))
  File "", line 1, in <module>
    
  File "/tmp/tmpYaAEhh/___code___.py", line 3, in <module>
    exec compile(u'A = [ n(x[i])**p for i in range(_sage_const_0 ,len(x)+_sage_const_1 ), p in range(_sage_const_0 ,_sage_const_3 ) ]
  File "", line 1, in <module>
    
NameError: name 'p' is not defined
x[0] 
       
Traceback (click to the left of this block for traceback)
...
TypeError: 'sage.symbolic.expression.Expression' object does not support
indexing
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "_sage_input_59.py", line 10, in <module>
    exec compile(u'open("___code___.py","w").write("# -*- coding: utf-8 -*-\\n" + _support_.preparse_worksheet_cell(base64.b64decode("eFswXQ=="),globals())+"\\n"); execfile(os.path.abspath("___code___.py"))
  File "", line 1, in <module>
    
  File "/tmp/tmpkh39Pu/___code___.py", line 3, in <module>
    exec compile(u'x[_sage_const_0 ]
  File "", line 1, in <module>
    
TypeError: 'sage.symbolic.expression.Expression' object does not support indexing
a = fpolyfit(x,y,2) 
       
Traceback (click to the left of this block for traceback)
...
NameError: global name 'p' is not defined
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "_sage_input_60.py", line 10, in <module>
    exec compile(u'open("___code___.py","w").write("# -*- coding: utf-8 -*-\\n" + _support_.preparse_worksheet_cell(base64.b64decode("YSA9IGZwb2x5Zml0KHgseSwyKQ=="),globals())+"\\n"); execfile(os.path.abspath("___code___.py"))
  File "", line 1, in <module>
    
  File "/tmp/tmp79b2KK/___code___.py", line 3, in <module>
    exec compile(u'a = fpolyfit(x,y,_sage_const_2 )
  File "", line 1, in <module>
    
  File "/tmp/tmpGecnm0/___code___.py", line 5, in fpolyfit
    A = [ n(x[i])**p for i in range(_sage_const_2 ,len(x)), p in range(_sage_const_1 ,h) ]
NameError: global name 'p' is not defined
# Como é função polinomial, segue a sequencia a[n]*x + a[n-1]*x + a[n-2]*x +...+ a[1] a = fpolyfit(x,y,2) # modelo(Xm,a) = a[3]*Xm^2 + a[2]*Xm + a[3]; 
       
Traceback (click to the left of this block for traceback)
...
NameError: global name 'p' is not defined
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "_sage_input_61.py", line 10, in <module>
    exec compile(u'open("___code___.py","w").write("# -*- coding: utf-8 -*-\\n" + _support_.preparse_worksheet_cell(base64.b64decode("IyBDb21vIMOpIGZ1bsOnw6NvIHBvbGlub21pYWwsIHNlZ3VlIGEgc2VxdWVuY2lhIGFbbl0qeCArIGFbbi0xXSp4ICsgYVtuLTJdKnggKy4uLisgYVsxXQoKYSA9IGZwb2x5Zml0KHgseSwyKQoKIyBtb2RlbG8oWG0sYSkgPSBhWzNdKlhtXjIgKyBhWzJdKlhtICsgYVszXTs="),globals())+"\\n"); execfile(os.path.abspath("___code___.py"))
  File "", line 1, in <module>
    
  File "/tmp/tmp1H61aY/___code___.py", line 4, in <module>
    a = fpolyfit(x,y,_sage_const_2 )
  File "/tmp/tmpGecnm0/___code___.py", line 5, in fpolyfit
    A = [ n(x[i])**p for i in range(_sage_const_2 ,len(x)), p in range(_sage_const_1 ,h) ]
NameError: global name 'p' is not defined
# plot 
       

NÃO POLINOMIAL 

ATENÇÃO! É importante resetar as variaveis antes de usar os outros modelos de ajuste de curvas, pois as constantes a,b,c são as mesmas em todos os modelos

reset() 
       
var("a,b,c,x") 
       
x = [0.0,0.2,0.4,1.0,1.6,1.8,2.0,2.6,2.8,3.0,3.8,4.8,5.0,5.2,6.0,6.2,7.4,7.6,7.8,8.6,8.8,9.0,9.2,9.4,10.0,10.6,10.8,11.2,11.6,11.8,12.2,12.4]; y = [-0.18344042, -0.13110, 0.026887, 0.30012, 0.5790482, 0.85260583, 0.93518099, 1.1332860, 1.2689332, 1.10202945,1.0920113718,1.14279083, 0.81130253532, 0.90973537, 0.417067545528, 0.460107770, -0.516307074859, -0.333994077, -0.5041247449, -0.945794320, -0.915934553, -0.9754585956, -1.099437074, -1.11254211, -1.29739980, -1.234404396, -0.9538075041, -1.122402748, -0.609284630, -0.592560286, -0.40252129, -0.510090363]; 
       
pontos = zip(x,y) 
       
point(pontos,color = "red",size=20,legend_label="pontos coletados",gridlines="minor", figsize=(6, 5)) 
       
modelo_seno(x) = a*sin(b*x + c); modelo_seno(x) 
       
# A opção solution_dict=True,utilizada para criar o dicionários das constantes, é opcional, mas caso não ocorra erro, coloque-a como true ajuste = find_fit(pontos, modelo_seno,[0.5,0.5,0.5],solution_dict=true);ajuste 
       
modelo_seno_ajustado(x) = modelo_seno.subs(ajuste);modelo_seno_ajustado(x) 
       
point(pontos,color = "red",size=20,legend_label="pontos coletados",gridlines="minor", figsize=(6, 5))+ plot(modelo_seno_ajustado(x),(x,0,12),legend_label="curva ajustada") 
       

%%% FIM INTERPOLAÇÃO E AJUSTE DE CURVAS %%%