Package: bces
Linear regression for data with measurement errors and intrinsic scatter (BCES)Python module for performing robust linear regression on (X,Y) data points where both X and Y have measurement errors.The fitting method is thebivariate correlated errors and intrinsic scatter(BCES) and follows the description given inAkritas & Bershady. 1996, ApJ. Some of the advantages of BCES regression compared to ordinary least squares fitting (quoted from Akritas & Bershady 1996):it allows for measurement errors on both variablesit permits the measurement errors for the two variables to be dependentit permits the magnitudes of the measurement errors to depend on the measurementsother "symmetric" lines such as the bisector and the orthogonal regression can be constructed.In order to understand how to perform and interpret the regression results, please read the paper.InstallationUsingpip:pip install bcesIf that does not work, you can install it using thesetup.pyscript:python setup.py installYou may need to run the last command withsudo.Alternatively, if you plan to modify the source then install the package with a symlink, so that changes to the source files will be immediately available:python setup.py developUsageimport bces.bces as BCES
a,b,aerr,berr,covab=BCES.bcesp(x,xerr,y,yerr,cov)Arguments:x,y: 1D data arraysxerr,yerr: measurement errors affecting x and y, 1D arrayscov: covariance between the measurement errors, 1D arrayIf you have no reason to believe that your measurement errors are correlated (which is usually the case), you can provide an  array of zeroes as input forcov:cov = numpy.zeros_like(x)Output:a,b: best-fit parameters a,b of the linear regression such thaty = Ax + B.aerr,berr: the standard deviations in a,bcovab: the covariance between a and b (e.g. for plotting confidence bands)Each element of the arraysa,b,aerr,berrandcovabcorrespond to the result of one of the different BCES lines:y|x,x|y, bissector and orthogonal, as detailed in the table below. Please read theoriginal BCES paperto understand what these different lines mean.ElementMethodDescription0y|xAssumesxas the independent variable1x|yAssumesyas the independent variable2bissectorLine that bisects they|xandx|y. This approach is self-inconsistent,do not use this method, cf.Hogg, D. et al. 2010, arXiv:1008.4686.3orthogonalOrthogonal least squares: line that minimizes orthogonal distances. Should be used when it is not clear which variable should be treated as the independent oneBy default,bcesprun in parallel with bootstrapping.Examplesbces-example.ipynbis a jupyter notebookincluding a practical, step-by-step example of how to use BCES to perform regression on data with uncertainties on x and y. It also illustrates how to plot the confidence band for a fit.If you have suggestions of more examples, feel free to add them.Running TestsTo test your installation, run the following command inside the BCES directory:pytest-vRequirementsSeerequirements.txt.CitationIf you end up using this code in your paper, you are morally obliged to cite the following worksThe original BCES paper:Akritas, M. G., & Bershady, M. A. Astrophysical Journal, 1996, 470, 706Nemmen, R. et al.Science, 2012, 338, 1445(bibtex citation info)I spent considerable time writing this code, making sure it is correct anduser-friendly, so I would appreciate your citation of the second paper in the above list as a token of gratitude.If you arereallyhappy with the code,you can buy me a beer.Misc.This python module is inspired on the (much faster) fortran routineoriginally written Akritas et al. I wrote it because I wanted something more portable and easier to use, trading off speed.For a general tutorial on how to (and how not to) perform linear regression,please read this paper: Hogg, D. et al. 2010, arXiv:1008.4686. In particular,please refrain from using the bisector method.If you want to plot confidence bands for your fits, have a look atnmmnpackage(in particular, modulesnmmn.plots.fitconfandstats).Bayesian linear regressionThere are a couple of Bayesian approaches to perform linear regression which can be more powerful than BCES, some of which are described below.A Gibbs Sampler for Multivariate Linear Regression:R code,arXiv:1509.00908.
Linear regression in the fairly general case with errors in X and Y, errors may be correlated, intrinsic scatter. The prior distribution of covariates is modeled by a flexible mixture of Gaussians. This is an extension of the very nice work by Brandon Kelly(Kelly, B. 2007, ApJ).LIRA: A Bayesian approach to linear regression in astronomy:R code,arXiv:1509.05778Bayesian hierarchical modelling of data with heteroscedastic and possibly correlated measurement errors and intrinsic scatter. The method fully accounts for time evolution. The slope, the normalization, and the intrinsic scatter of the relation can evolve with the redshift. The intrinsic distribution of the independent variable is approximated using a mixture of Gaussian distributions whose means and standard deviations depend on time. The method can address scatter in the measured independent variable (a kind of Eddington bias), selection effects in the response variable (Malmquist bias), and departure from linearity in form of a knee.AstroML: Machine Learning and Data Mining for Astronomy.Python exampleof a linear fit to data with correlated errors in x and y using AstroML. In the literature, this is often referred to as total least squares or errors-in-variables fitting.TodoIf you have improvements to the code, suggestions of examples,speeding up the code etc, feel free tosubmit a pull request.implement weighted least squares (WLS)implement unit testing:bcesunit testing:bootstrapVisit the author's web pageand/or follow him on twitter (@nemmen).Copyright (c) 2023,Rodrigo Nemmen.All rights reserved.Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.