{"id":318,"date":"2019-01-22T17:54:39","date_gmt":"2019-01-23T01:54:39","guid":{"rendered":"http:\/\/gantovnik.com\/bio-tips\/?p=318"},"modified":"2019-01-22T21:59:11","modified_gmt":"2019-01-23T05:59:11","slug":"weighted-and-unweighted-least-squares-fitting","status":"publish","type":"post","link":"https:\/\/gantovnik.com\/bio-tips\/2019\/01\/weighted-and-unweighted-least-squares-fitting\/","title":{"rendered":"Weighted and unweighted least squares fitting"},"content":{"rendered":"<p><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import curve_fit\nos.chdir(r'D:\\data\\scripts\\wordpress\\ex55')\nos.getcwd()\nx0,A,gamma=12,3,5\nn=200\nx=np.linspace(1,20,n)\nyexact=A*gamma**2\/(gamma**2+(x-x0)**2)\n#Learning Scientific Programming with Python\n# Add some noise with a sigma of 0.5 apart from a particularly noisy region\n# near x0 where sigma is 3\nsigma=np.ones(n)*0.5\nsigma&#x5B;np.abs(x-x0+1)&lt;1]=3\nnoise=np.random.randn(n)*sigma\ny=yexact+noise\n\ndef f(x,x0,A,gamma):\n    #The Lorentzian entered at x0 with amplitude A and HWHM gamma\n    return A*gamma**2\/(gamma**2+(x-x0)**2)\n\ndef rms(y,yfit):\n    return np.sqrt(np.sum((y-yfit)**2))\n\n# Unweighted fit\np0=10,4,2\npopt,pcov=curve_fit(f,x,y,p0)\nyfit=f(x,*popt)\nprint('Unweighted fit parameters:',popt)\nprint('Covarian cematrix:')\nprint(pcov)\nprint('rms error in fit:',rms(yexact,yfit))\nprint()\n# Weighted fit\npopt2,pcov2=curve_fit(f,x,y,p0,sigma=sigma,absolute_sigma=True)\nyfit2=f(x,*popt2)\nprint('Weighted fit parameters:',popt2)\nprint('Covariancematrix:')\nprint(pcov2)\nprint('rms error in fit:',rms(yexact,yfit2))\nplt.plot(x,yexact,label='Exact')\nplt.plot(x,y,'o',label='Noisy data')\nplt.plot(x,yfit,label='Unweighted fit')\nplt.plot(x,yfit2,label='Weighted fit')\nplt.ylim(-1,4)\nplt.legend(loc='lower center')\n\nplt.tight_layout()\nplt.savefig(&quot;example55.png&quot;, dpi=100)\nplt.show()\nplt.close()\n<\/pre><\/p><br \/><br \/><img data-recalc-dims=\"1\" decoding=\"async\" class=\" size-full wp-image-327 aligncenter\" src=\"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example55.png?resize=600%2C400&#038;ssl=1\" alt=\"example55\" width=\"600\" height=\"400\" srcset=\"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example55.png?w=600&amp;ssl=1 600w, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example55.png?resize=300%2C200&amp;ssl=1 300w\" sizes=\"(max-width: 600px) 100vw, 600px\" \/><\/pre>","protected":false},"excerpt":{"rendered":"<p>import os import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit os.chdir(r&#8217;D:\\data\\scripts\\wordpress\\ex55&#8242;) 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 sigma&#x5B;np.abs(x-x0+1)&lt;1]=3 noise=np.random.randn(n)*sigma y=yexact+noise def f(x,x0,A,gamma): #The Lorentzian [&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_post_was_ever_published":false,"_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":""},"categories":[2],"tags":[],"class_list":["post-318","post","type-post","status-publish","format-standard","hentry","category-python"],"modified_by":"gantovnik","jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p8bH0k-58","jetpack_likes_enabled":true,"jetpack-related-posts":[{"id":1758,"url":"https:\/\/gantovnik.com\/bio-tips\/2023\/01\/335-solution-of-nonlinear-equation-using-brent-method-in-python\/","url_meta":{"origin":318,"position":0},"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":[]},{"id":154,"url":"https:\/\/gantovnik.com\/bio-tips\/2019\/01\/inexact-solutions-to-odes\/","url_meta":{"origin":318,"position":1},"title":"Inexact solutions to ODEs","author":"gantovnik","date":"2019-01-08","format":false,"excerpt":"\u00a0 import os import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl import sympy from IPython.display import display sympy.init_printing() mpl.rcParams['text.usetex'] = True import sympy os.chdir(r'D:\\projects\\wordpress\\ex33') os.getcwd() def plot_direction_field(x, y_x, f_xy, x_lim=(-5, 5), y_lim=(-5, 5), ax=None): f_np = sympy.lambdify((x, y_x), f_xy, 'numpy') x_vec = np.linspace(x_lim[0], x_lim[1], 20) y_vec\u2026","rel":"","context":"In &quot;python&quot;","block_context":{"text":"python","link":"https:\/\/gantovnik.com\/bio-tips\/category\/python\/"},"img":{"alt_text":"example33","src":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example33.png?resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example33.png?resize=350%2C200 1x, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example33.png?resize=525%2C300 1.5x"},"classes":[]},{"id":845,"url":"https:\/\/gantovnik.com\/bio-tips\/2021\/01\/149-optimization-in-python\/","url_meta":{"origin":318,"position":2},"title":"#149 Optimization in python","author":"gantovnik","date":"2021-01-24","format":false,"excerpt":"#149 Optimization in python [code language=\"python\"] import os import numpy as np from scipy.optimize import minimize os.chdir(r'D:\\projects\\wordpress\\ex149') os.getcwd() def obj(x): return (1-x[0])**2 + 100*(x[1]-x[0]**2)**2 def con(x): g=np.zeros(2) g[0]=1-x[0]**2-x[1]**2 g[1]=5-x[0]-3*x[1] return g x0=[5.0,5.0] constraints = {'type': 'ineq','fun': con} options={'disp':True} res = minimize(obj,x0,constraints=constraints,options=options) print('x =',res.x) print('f =',res.fun) print(res.success) [\/code] Output: [code language=\"python\"]\u2026","rel":"","context":"In &quot;optimization&quot;","block_context":{"text":"optimization","link":"https:\/\/gantovnik.com\/bio-tips\/category\/optimization\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":1746,"url":"https:\/\/gantovnik.com\/bio-tips\/2023\/01\/204-mandelbrot-fractal-using-python-2-2-2-2-2-2-2-2-2-2\/","url_meta":{"origin":318,"position":3},"title":"#331 Interpolation with Newton&#8217;s polynomial using python","author":"gantovnik","date":"2023-01-04","format":false,"excerpt":"interpolation.py [code language=\"python\"] def interpolation(c,x,x0): # Evaluate Newton's polynomial at x0. # Degree of polynomial n = len(x) - 1 y0 = c[n] for k in range(1,n+1): y0 = c[n-k] + (x0 - x[n-k]) * y0 return y0 def coef(x,y): # Computes the coefficients of Newton's polynomial. # Number of\u2026","rel":"","context":"In &quot;interpolation&quot;","block_context":{"text":"interpolation","link":"https:\/\/gantovnik.com\/bio-tips\/category\/interpolation\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2023\/01\/ex331.png?resize=350%2C200&ssl=1","width":350,"height":200},"classes":[]},{"id":82,"url":"https:\/\/gantovnik.com\/bio-tips\/2018\/12\/plot-with-an-inset\/","url_meta":{"origin":318,"position":4},"title":"#12: Plot with an inset in python","author":"gantovnik","date":"2018-12-29","format":false,"excerpt":"[code language=\"python\"] import os import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np os.chdir('\/home\/vg\/Downloads\/projects\/ex12') os.getcwd() fig = plt.figure(figsize=(10,8)) def f(x): return 1\/(1+x**2) + 0.1\/(1+((3-x)\/0.1)**2) def plot_and_format_axes(ax,x,f,fontsize): ax.plot(x,f(x),linewidth=2) ax.xaxis.set_major_locator(mpl.ticker.MaxNLocator(5)) ax.yaxis.set_major_locator(mpl.ticker.MaxNLocator(4)) ax.set_xlabel(r\"$x$\",fontsize=fontsize) ax.set_ylabel(r\"$f(x)$\",fontsize=fontsize) ax=fig.add_axes([0.1,0.15,0.8,0.8],facecolor=\"#f5f5f5\") x = np.linspace(-4,14,1000) plot_and_format_axes(ax,x,f,18) plt.title('Plot with inset') x0,x1=2.5,3.5 ax.axvline(x0,ymax=0.3,color=\"grey\",linestyle=\":\") ax.axvline(x1,ymax=0.3,color=\"grey\",linestyle=\":\") ax_insert=fig.add_axes([0.5,0.5,0.38,0.42],facecolor='none') x=np.linspace(x0,x1,1000) plot_and_format_axes(ax_insert,x,f,14) plt.savefig(\"example12.png\", dpi=100)\u2026","rel":"","context":"In &quot;matplotlib&quot;","block_context":{"text":"matplotlib","link":"https:\/\/gantovnik.com\/bio-tips\/category\/matplotlib\/"},"img":{"alt_text":"example12","src":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2018\/12\/example12.png?resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2018\/12\/example12.png?resize=350%2C200 1x, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2018\/12\/example12.png?resize=525%2C300 1.5x"},"classes":[]},{"id":1718,"url":"https:\/\/gantovnik.com\/bio-tips\/2022\/12\/204-mandelbrot-fractal-using-python-2-2-2-2-2-2\/","url_meta":{"origin":318,"position":5},"title":"#325 Finding the intersection points between two functions using python","author":"gantovnik","date":"2022-12-13","format":false,"excerpt":"[code language=\"python\"] from scipy.optimize import fsolve import numpy as np import matplotlib.pyplot as plt # Defining function to simplify intersection solution def findIntersection(func1, func2, x0): return fsolve(lambda x : func1(x) - func2(x), x0) # Defining functions that will intersect funky = lambda x : np.cos(x \/ 5) * np.sin(x \/\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\/2022\/12\/ex325.png?resize=350%2C200&ssl=1","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2022\/12\/ex325.png?resize=350%2C200&ssl=1 1x, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2022\/12\/ex325.png?resize=525%2C300&ssl=1 1.5x"},"classes":[]}],"_links":{"self":[{"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/posts\/318","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=318"}],"version-history":[{"count":0,"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/posts\/318\/revisions"}],"wp:attachment":[{"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/media?parent=318"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/categories?post=318"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/tags?post=318"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}