{"id":2053,"date":"2024-01-14T03:48:36","date_gmt":"2024-01-14T11:48:36","guid":{"rendered":"https:\/\/gantovnik.com\/bio-tips\/?p=2053"},"modified":"2024-01-14T03:48:36","modified_gmt":"2024-01-14T11:48:36","slug":"406-nonlinear-least-squares-fitting-using-leastsq-from-scipy-optimize-in-python","status":"publish","type":"post","link":"https:\/\/gantovnik.com\/bio-tips\/2024\/01\/406-nonlinear-least-squares-fitting-using-leastsq-from-scipy-optimize-in-python\/","title":{"rendered":"#406 Nonlinear least squares fitting using leastsq from scipy.optimize in python"},"content":{"rendered":"<p><a href=\"https:\/\/gantovnik.com\/bio-tips\/2024\/01\/406-nonlinear-least-squares-fitting-using-leastsq-from-scipy-optimize-in-python\/ex406\/\" rel=\"attachment wp-att-2054\"><img data-recalc-dims=\"1\" decoding=\"async\" src=\"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2024\/01\/ex406.png?resize=640%2C480&#038;ssl=1\" alt=\"\" width=\"640\" height=\"480\" class=\"alignnone size-full wp-image-2054\" srcset=\"https:\/\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2024\/01\/ex406.png 640w, https:\/\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2024\/01\/ex406-480x360.png 480w\" sizes=\"(min-width: 0px) and (max-width: 480px) 480px, (min-width: 481px) 640px, 100vw\" \/><\/a><\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.optimize import leastsq\r\n\r\nA, freq, tau = 5, 4, 0.5\r\n\r\ndef f(t, A, freq, tau):\r\n    return A * np.exp(-t\/tau) * np.cos(3*np.pi * freq * t)\r\n\r\ntmax, dt = 1, 0.01\r\nt = np.arange(0, tmax, dt)\r\nyexact = f(t, A, freq, tau)\r\ny = yexact + np.random.randn(len(yexact))*2\r\n\r\ndef residuals(p, y, t):\r\n    A, freq, tau = p\r\n    return y - f(t, A, freq, tau)\r\n\r\n# nonlinear least squares fitting routine\r\np0 = 5, 5, 1\r\nplsq = leastsq(residuals, p0, args=(y, t))\r\nplt.plot(t, y, 'o', c='black', label='Data')\r\nplt.plot(t, yexact, c='red', label='Exact')\r\npfit = plsq&#x5B;0]\r\nplt.plot(t, f(t, *pfit), c='green', label='Fit')\r\nplt.legend()\r\nplt.savefig(&quot;ex406.png&quot;, dpi=100)\r\nplt.show()\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>import numpy as np import matplotlib.pyplot as plt from scipy.optimize import leastsq A, freq, tau = 5, 4, 0.5 def f(t, A, freq, tau): return A * np.exp(-t\/tau) * np.cos(3*np.pi * freq * t) tmax, dt = 1, 0.01 t = np.arange(0, tmax, dt) yexact = f(t, A, freq, tau) y = yexact + np.random.randn(len(yexact))*2 [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"nf_dc_page":"","_et_pb_use_builder":"","_et_pb_old_content":"","_et_gb_content_width":"","_lmt_disableupdate":"yes","_lmt_disable":"","_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_post_was_ever_published":false},"categories":[69,2,71],"tags":[],"class_list":["post-2053","post","type-post","status-publish","format-standard","hentry","category-matplotlib","category-python","category-scipy"],"modified_by":"gantovnik","jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p8bH0k-x7","jetpack_likes_enabled":true,"jetpack-related-posts":[{"id":308,"url":"https:\/\/gantovnik.com\/bio-tips\/2019\/01\/elementor-308\/","url_meta":{"origin":2053,"position":0},"title":"# 54 Nonlinear Least Squares Fitting","author":"gantovnik","date":"2019-01-22","format":false,"excerpt":"import os import numpy as np import matplotlib.pyplot as plt os.chdir(r'D:\\\\data\\scripts\\wordpress\\ex54') os.getcwd() A,freq,tau=10,4,0.5 def f(t,A,freq,tau): return A*np.exp(-t\/tau)*np.cos(2*np.pi*freq*t) tmax,dt=1,0.01 t=np.arange(0,tmax,dt) yexact=f(t,A,freq,tau) y=yexact + np.random.randn(len(yexact))*2 plt.plot(t,yexact) plt.scatter(t,y,marker='o',facecolors='blue', edgecolors='black') def residuals(p,y,t): A,freq,tau=p return y-f(t,A,freq,tau) from scipy.optimize import leastsq p0=5,5,1 plsq=leastsq(residuals,p0,args=(y,t)) plsq[0][1] pfit = (plsq[0][0],plsq[0][1],plsq[0][2]) plt.plot(t,y,'o',c='k',label='Data') plt.plot(t,yexact,c='green',label='Exact') plt.plot(t,f(t,plsq[0][0],plsq[0][1],plsq[0][2]),c='red',label='Fit') plt.legend() plt.tight_layout() plt.savefig(\"ex54.png\", dpi=100) plt.show() plt.close()","rel":"","context":"In &quot;python&quot;","block_context":{"text":"python","link":"https:\/\/gantovnik.com\/bio-tips\/category\/python\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example54-1.png?resize=350%2C200&ssl=1","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example54-1.png?resize=350%2C200&ssl=1 1x, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example54-1.png?resize=525%2C300&ssl=1 1.5x"},"classes":[]},{"id":318,"url":"https:\/\/gantovnik.com\/bio-tips\/2019\/01\/weighted-and-unweighted-least-squares-fitting\/","url_meta":{"origin":2053,"position":1},"title":"Weighted and unweighted least squares fitting","author":"gantovnik","date":"2019-01-22","format":false,"excerpt":"[code language=\"python\"] import os import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit os.chdir(r'D:\\data\\scripts\\wordpress\\ex55') os.getcwd() x0,A,gamma=12,3,5 n=200 x=np.linspace(1,20,n) yexact=A*gamma**2\/(gamma**2+(x-x0)**2) #Learning Scientific Programming with Python # Add some noise with a sigma of 0.5 apart from a particularly noisy region # near x0 where sigma is 3 sigma=np.ones(n)*0.5\u2026","rel":"","context":"In &quot;python&quot;","block_context":{"text":"python","link":"https:\/\/gantovnik.com\/bio-tips\/category\/python\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example55.png?resize=350%2C200&ssl=1","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example55.png?resize=350%2C200&ssl=1 1x, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example55.png?resize=525%2C300&ssl=1 1.5x"},"classes":[]},{"id":220,"url":"https:\/\/gantovnik.com\/bio-tips\/2019\/01\/2nd-order-runge-kutta-type-c\/","url_meta":{"origin":2053,"position":2},"title":"#46 2nd-order Runge-Kutta type C using python","author":"gantovnik","date":"2019-01-12","format":false,"excerpt":"import os import numpy as np import matplotlib.pyplot as plt os.chdir(r'D:\\projects\\wordpress\\ex46') os.getcwd() #2nd-order Runge-Kutta methods with A=1\/3 (type C) # dy\/dx=exp(-2x)-2y # y(0)=0.1, interval x=[0,2], step size = h=0.2 def feval(funcName, *args): return eval(funcName)(*args) def RK2C(func, yinit, x_range, h): m = len(yinit) n = int((x_range[-1] - x_range[0])\/h) x = x_range[0]\u2026","rel":"","context":"In &quot;numerical&quot;","block_context":{"text":"numerical","link":"https:\/\/gantovnik.com\/bio-tips\/category\/numerical\/"},"img":{"alt_text":"example46","src":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example46.png?resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example46.png?resize=350%2C200 1x, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example46.png?resize=525%2C300 1.5x"},"classes":[]},{"id":210,"url":"https:\/\/gantovnik.com\/bio-tips\/2019\/01\/2nd-order-runge-kutta-type-a\/","url_meta":{"origin":2053,"position":3},"title":"#44 2nd-order Runge-Kutta type A using python","author":"gantovnik","date":"2019-01-12","format":false,"excerpt":"[code language=\"python\"] import os import numpy as np import matplotlib.pyplot as plt os.chdir(r'D:\\projects\\wordpress\\ex44') os.getcwd() #2nd-order Runge-Kutta methods with A=1\/2 (type A) # dy\/dx=exp(-2x)-2y # y(0)=0.1, interval x=[0,2], step size = h=0.2 def feval(funcName, *args): return eval(funcName)(*args) def RK2A(func, yinit, x_range, h): m = len(yinit) n = int((x_range[-1] - x_range[0])\/h) x\u2026","rel":"","context":"In &quot;numerical&quot;","block_context":{"text":"numerical","link":"https:\/\/gantovnik.com\/bio-tips\/category\/numerical\/"},"img":{"alt_text":"example44","src":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example44-1.png?resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example44-1.png?resize=350%2C200 1x, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example44-1.png?resize=525%2C300 1.5x"},"classes":[]},{"id":217,"url":"https:\/\/gantovnik.com\/bio-tips\/2019\/01\/2nd-order-runge-kutta-type-b\/","url_meta":{"origin":2053,"position":4},"title":"#45  2nd-order Runge-Kutta type B using python","author":"gantovnik","date":"2019-01-12","format":false,"excerpt":"import os import numpy as np import matplotlib.pyplot as plt os.chdir(r'D:\\projects\\wordpress\\ex45') os.getcwd() #2nd-order Runge-Kutta methods with A=0 (type B) # dy\/dx=exp(-2x)-2y # y(0)=0.1, interval x=[0,2], step size = h=0.2 def feval(funcName, *args): return eval(funcName)(*args) def RK2B(func, yinit, x_range, h): m = len(yinit) n = int((x_range[-1] - x_range[0])\/h) x = x_range[0]\u2026","rel":"","context":"In &quot;differential equations&quot;","block_context":{"text":"differential equations","link":"https:\/\/gantovnik.com\/bio-tips\/category\/differential-equations\/"},"img":{"alt_text":"example45","src":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example45.png?resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example45.png?resize=350%2C200 1x, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example45.png?resize=525%2C300 1.5x"},"classes":[]},{"id":1758,"url":"https:\/\/gantovnik.com\/bio-tips\/2023\/01\/335-solution-of-nonlinear-equation-using-brent-method-in-python\/","url_meta":{"origin":2053,"position":5},"title":"#335 Solution of nonlinear equation by Brent&#8217;s method in python","author":"gantovnik","date":"2023-01-06","format":false,"excerpt":"Brent's method is a hybrid root-finding algorithm combining the bisection method, the secant method, and inverse quadratic interpolation. ex335.py [code language=\"python\"] import numpy as np import matplotlib.pyplot as plt import scipy.optimize as optimize def f(x): return 2*x - 1 + 2*np.cos(np.pi*x) x = np.linspace(0.0,2.0,201) y=f(x) plt.plot(x,y,label='$2x - 1 + 2\\\\cos(\\\\pi\u2026","rel":"","context":"In &quot;optimization&quot;","block_context":{"text":"optimization","link":"https:\/\/gantovnik.com\/bio-tips\/category\/optimization\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2023\/01\/ex335.png?resize=350%2C200&ssl=1","width":350,"height":200},"classes":[]}],"_links":{"self":[{"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/posts\/2053","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/comments?post=2053"}],"version-history":[{"count":2,"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/posts\/2053\/revisions"}],"predecessor-version":[{"id":2056,"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/posts\/2053\/revisions\/2056"}],"wp:attachment":[{"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/media?parent=2053"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/categories?post=2053"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/tags?post=2053"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}