these are really good lecture notes, explaining the linear algebra, covariance matrices and so on. Directly helps for coding.
Showing posts with label fitting. Show all posts
Showing posts with label fitting. Show all posts
Friday, December 20, 2013
Thursday, December 5, 2013
stats: the covariance matrix
The covariance matrix is N-dimensional generalisation of the scalar variance in 1 dimension. Here's a simple explanation of it which I needed in order to code up a test case for fitting a 2D Gaussian with intrinsic scatter.
Tuesday, November 26, 2013
Python: scikit-learn MoG
Probably should have tried this, before reinventing the wheel.
Tuesday, November 19, 2013
lit: Some aspects of measurement error in linear regression of astronomical data, Kelly 2007
Kelly 2007:
I describe a Bayesian method to account for measurement errors in linear regression of astronomical data. The method allows for heteroscedastic and possibly correlated measurement errors and intrinsic scatter in the regression relationship. The method is based on deriving a likelihood function for the measured data, and I focus on the case when the intrinsic distribution of the independent variables can be approximated using a mixture of Gaussian functions. I generalize the method to incorporate multiple independent variables, non-detections, and selection effects (e.g., Malmquist bias).
I describe a Bayesian method to account for measurement errors in linear regression of astronomical data. The method allows for heteroscedastic and possibly correlated measurement errors and intrinsic scatter in the regression relationship. The method is based on deriving a likelihood function for the measured data, and I focus on the case when the intrinsic distribution of the independent variables can be approximated using a mixture of Gaussian functions. I generalize the method to incorporate multiple independent variables, non-detections, and selection effects (e.g., Malmquist bias).
Thursday, November 14, 2013
Daily paper: The Tully-Fisher relations of early-type spiral and S0 galaxies
I gave a talk at our group meeting yesterday, this was one of several useful suggestions and references I got.
bWilliams et al. 2010, The Tully-Fisher relations of early-type spiral and S0 galaxies
Offsets which are ascribed to fading or brightening could in fact be due to systematic biases that differ between the measures of rotation used. For typical slopes of the TFR, a relatively small systematic difference in velocity of ∼0.1 dex introduces an offset in the TFR that is indistinguishable from a ∼ 1mag difference in luminosity.
Our conclusions in this section have three consequences for previous works that measure the TFR of S0 galaxies using stellar kinematics corrected for asymmetric drift (e.g. Neistein et al. 1999; Hinz et al. 2001, 2003, BAM06): (i) the asymmetric drift correction they use yields similar results to detailed Jeans modelling; (ii) the drift correction does not seem to introduce a systematic bias between spirals and S0s and, if applied to samples of both spirals and S0s, can indeed be used to compare the TFRs of the two classes; (iii) however, a TFR derived from asymmetric drift-corrected stellar kinematics cannot be directly compared to TFRs derived from global HI line widths or resolved emission line PVDs. ==== There's a really interesting section on the ADC, and a nice comparison of gas/HI/AD corrected stellar kinematics. Also I should check their section on TFR fitting, intrinsic scatter in it, etc.In addition, I ought to take a look at the references therein, esp. the introduction.
Offsets which are ascribed to fading or brightening could in fact be due to systematic biases that differ between the measures of rotation used. For typical slopes of the TFR, a relatively small systematic difference in velocity of ∼0.1 dex introduces an offset in the TFR that is indistinguishable from a ∼ 1mag difference in luminosity.
Our conclusions in this section have three consequences for previous works that measure the TFR of S0 galaxies using stellar kinematics corrected for asymmetric drift (e.g. Neistein et al. 1999; Hinz et al. 2001, 2003, BAM06): (i) the asymmetric drift correction they use yields similar results to detailed Jeans modelling; (ii) the drift correction does not seem to introduce a systematic bias between spirals and S0s and, if applied to samples of both spirals and S0s, can indeed be used to compare the TFRs of the two classes; (iii) however, a TFR derived from asymmetric drift-corrected stellar kinematics cannot be directly compared to TFRs derived from global HI line widths or resolved emission line PVDs. ==== There's a really interesting section on the ADC, and a nice comparison of gas/HI/AD corrected stellar kinematics. Also I should check their section on TFR fitting, intrinsic scatter in it, etc.In addition, I ought to take a look at the references therein, esp. the introduction.
Monday, October 28, 2013
Uncertainties are distributions, not errorbar values
This clicked on me while preparing for a talk, though it's an obvious thing: too often we are content with just plotting errorbars and not specifying what do they mean (for instance: 1 sigma-uncertainties, Gaussian distribution). This makes propagating uncertainties (and using the data for model selection) actually impossible.
To put it another way: we don't have datapoints, we operate with slippery, diffuse clouds of probabilities of data. My current task is to take full 2D uncertainties distribution for my datapoints and re-use them in the following steps of hierarchical analysis.
To put it another way: we don't have datapoints, we operate with slippery, diffuse clouds of probabilities of data. My current task is to take full 2D uncertainties distribution for my datapoints and re-use them in the following steps of hierarchical analysis.
Wednesday, September 25, 2013
lit: Precise TFRs without galaxy inclinations
Precise TFRs without galaxy inclinations, by Obreschkow et al. A really interesting read about why photometric (axis ratio-based) inclination values are not optimal, what TFR is good for, fitting the TFR, etc. The main point of the article is recovering the TFR for samples with limited or no inclination data, but I haven't read it in detail yet.
Monday, August 26, 2013
Fitting the Tully-Fisher relation
There's one thing I can't quite wrap my head around while reading literature on the Tully-Fisher relation: why is the fitting always performed in the magnitude-log(velocity) space? It may be easier to fit an expression y = mx + b to data than y = c*x**z, but one would have to deal with asymmetric errors in two dimensions.
I'm currently trying to figure out a way to do the fit in semi-log space, namely, magnitude-velocity space, using errors in both directions and MCMC.
I'm currently trying to figure out a way to do the fit in semi-log space, namely, magnitude-velocity space, using errors in both directions and MCMC.
Tuesday, April 30, 2013
lit: 2dSWML algorithm, HI mass function
The 1000 Brightest HIPASS Galaxies by Zwaan et al.: has a nice section on Vmax corrections/fitting distribution functions, with a reference to the original Schmidt 1968 article.
Thursday, April 11, 2013
Thursday, March 14, 2013
Fitting a model to data: lit review
Yesterday I showed some preliminary TF results at our group meeting, and it was rightly noted that the straight line fit I made was wrong. I've only included errors in one variable (velocity, obtained by using bootstrapping) in the fit, and made a mess of that by mixing the variables on the plot.
I've been thinking about how to do a proper fit when the data has uncertainties in both directions, and been revisiting this paper by Hogg et al.:
In the astrophysics literature (see, for example, the Tully Fisher literature, there is a tradition, when there are uncertainties in both directions, of fi tting the "forward" and "reverse" relations, that is, fi tting y as a function of x and then x as a function of y, and then splitting the diff erence between the two slopes so obtained, or treating the di fference between the slopes as a systematic uncertainty. This is unjusti ed.
I've been thinking about how to do a proper fit when the data has uncertainties in both directions, and been revisiting this paper by Hogg et al.:
In the astrophysics literature (see, for example, the Tully Fisher literature, there is a tradition, when there are uncertainties in both directions, of fi tting the "forward" and "reverse" relations, that is, fi tting y as a function of x and then x as a function of y, and then splitting the diff erence between the two slopes so obtained, or treating the di fference between the slopes as a systematic uncertainty. This is unjusti ed.
Monday, February 18, 2013
Parallel processing in Python
I just wrote a series of scripts that run batch GALFIT fits. Since it's boring to parallelise this manually (e.g. splitting the list of input ID's into smaller lists, then running same script separately for each sublist, or setting the chunks of IDs from command line), I wrote a simple multithreading routine using multiprocessing. It's quite trivial, as the parallel processes here don't have to communicate (unless I see some terrible race conditions arising). The ID lists are made by hand, but it'll be easy to split the list into smaller chunks of desired length by looping through it, or by using list comprehension.
Monday, February 4, 2013
lit review: The shape of the dark matter halo in the early-type galaxy NGC 2974
The shape of the dark matter halo in the early-type galaxy NGC 2974, by Weijmans, Krajnovic et al. They use kinemetry to analyse gas and stellar kinematics, with clear description of the AD correction. (Thanks, Mariya!)
lit review: a generalization of photometry to the higher moments of the line-of-sight velocity distribution
by Krajnovic et al.. This will probably be one of the important papers when writing: an interesting breakdown and discussion of velocity map moments, also many useful references (esp. Schoenmakers
et al. (1997), the degeneracy of q, center and systemic velocity v0.
We have presented a generalization of surface photometry to the higher-order moments of the LOSVD, observed with integral-field spectrograph. We call our method kinemetry. For even moments of the LOSVD, kinemetry reduces to photometry. For odd moments, kinemetry is based on the assumption that it is possible to define an ellipse such that the kinematic profile extracted along the ellipse can be well described by a simple cosine law. This assumption is satisfied in the case of simple axisymmetric rotators.
We have presented a generalization of surface photometry to the higher-order moments of the LOSVD, observed with integral-field spectrograph. We call our method kinemetry. For even moments of the LOSVD, kinemetry reduces to photometry. For odd moments, kinemetry is based on the assumption that it is possible to define an ellipse such that the kinematic profile extracted along the ellipse can be well described by a simple cosine law. This assumption is satisfied in the case of simple axisymmetric rotators.
Thursday, January 24, 2013
Wednesday, October 24, 2012
Photometry: linear regression fitting of sky
Yesterday we agreed that the photometry procedure should have as little arbitrary procedures, constants, etc., as possible. So I'm back to the photometry measurements again...but that's a good thing, as I didn't feel entirely happy about them.
The idea I had this morning on the train was simple -- I don't know what conceptual block prevented me from going this way sooner.
Basically, having a cumulative flux curve (the growth curve) is not generally helpful, as the growth of flux outside is non-linear (depends on geometry as well as on the sky value). However, if I normalise the flux profile to _flux_per_pixel, it should theoretically flatten far away from the galaxy. The slope of a linear regression fit should show the quality of the sky value -- the level of variations. If the sky slope is negative and pretty large, then we probably still are within the galaxy.
If the slope is reasonably small (here go the arbitrary parameters again..), simply taking a mean of all measurements within the ring would give a reasonably good sky value.
The catch is getting the width of the elliptical ring used for fitting right. (I can get its distance by waving my hands, taking the maximum distance from my previous measurements, multiplying it by pi/2 or something. We're testing for it anyway).
However, the width of this ring is a tradeoff between accuracy and precision. Taking a wider ring would surely help to reduce the scatter due to random noise, arbitrary gradients and so. However, the possibility to get a (poorly) masked region or some sky artifact, etc. inside this ring also increases.
I tested it a bit using scipy.linalg routines, so far the slope was below 10^-4 counts.
The growth curve itself is useful as a sky subtraction quality check.
The idea I had this morning on the train was simple -- I don't know what conceptual block prevented me from going this way sooner.
Basically, having a cumulative flux curve (the growth curve) is not generally helpful, as the growth of flux outside is non-linear (depends on geometry as well as on the sky value). However, if I normalise the flux profile to _flux_per_pixel, it should theoretically flatten far away from the galaxy. The slope of a linear regression fit should show the quality of the sky value -- the level of variations. If the sky slope is negative and pretty large, then we probably still are within the galaxy.
If the slope is reasonably small (here go the arbitrary parameters again..), simply taking a mean of all measurements within the ring would give a reasonably good sky value.
The catch is getting the width of the elliptical ring used for fitting right. (I can get its distance by waving my hands, taking the maximum distance from my previous measurements, multiplying it by pi/2 or something. We're testing for it anyway).
However, the width of this ring is a tradeoff between accuracy and precision. Taking a wider ring would surely help to reduce the scatter due to random noise, arbitrary gradients and so. However, the possibility to get a (poorly) masked region or some sky artifact, etc. inside this ring also increases.
I tested it a bit using scipy.linalg routines, so far the slope was below 10^-4 counts.
The growth curve itself is useful as a sky subtraction quality check.
Tuesday, March 20, 2012
the end of MICE
I'm about to finish running GALFIT on the HST F606 MICE image (preview here).
I've used GALFIT before, while writing my MSc thesis, but oh, those were faint, redshifted and unremarkable SDSS galaxies. That was simple -- I used 5 components once, because a galaxy had a LINER AGN.
The MICE are monsters. They've apparently already passed through each other once, and have highly disturbed tidal features, clumps of active star formation, dust lanes, you name it. I've never used GALFIT to model spiral arms, too, so that was an interesting experience.
Here are they:
I started simple, first masking out each galaxy and fitting the other in turn, then fitting both simultaneously (that's a better way to do it anyway). After running about 150 models I decided to mask out the dark dust lanes in galaxy A -- I couldn't fit them using truncation functions, as GALFIT crashes (on my 64bit SUSE, at least) while attempting that and I don't think the science goal required this. I have some reservations about the decomposition, as I think the image has some flat-fielding issues, besides, the galaxies take up a large part of the overall image, so I have doubts about the determined sky value as well.
In the end I had 91 free parameter, and I think more might have made sense, but that was past the point of diminishing returns. I stopped at Chi^2 = 1.877, and guess the main reason why the model would fit the image so poorly were the bright and irregular cores of the galaxies -- or possible higher order flat-field curvature. The other objects were masked out. Here is the model -- at ds9's 99.5 scale and heat colourmap (this is handy: ds9 -scale mode 99.5 -cmap Heat -medatacube ~/workspace/MICE/galfit/subcomps.fits). The long, bright tails are not well visible with these settings, but they weren't the goal. I am not really happy with the residual picture, as it tells me there are some big, obscured components lurking underneath. But that'll have to do for the moment, as I have other assignments. I've been doing this for other people in the collaboration, so I don't think I can publish the fit logs here, unfortunately.
I've used GALFIT before, while writing my MSc thesis, but oh, those were faint, redshifted and unremarkable SDSS galaxies. That was simple -- I used 5 components once, because a galaxy had a LINER AGN.
The MICE are monsters. They've apparently already passed through each other once, and have highly disturbed tidal features, clumps of active star formation, dust lanes, you name it. I've never used GALFIT to model spiral arms, too, so that was an interesting experience.
Here are they:
I started simple, first masking out each galaxy and fitting the other in turn, then fitting both simultaneously (that's a better way to do it anyway). After running about 150 models I decided to mask out the dark dust lanes in galaxy A -- I couldn't fit them using truncation functions, as GALFIT crashes (on my 64bit SUSE, at least) while attempting that and I don't think the science goal required this. I have some reservations about the decomposition, as I think the image has some flat-fielding issues, besides, the galaxies take up a large part of the overall image, so I have doubts about the determined sky value as well.
In the end I had 91 free parameter, and I think more might have made sense, but that was past the point of diminishing returns. I stopped at Chi^2 = 1.877, and guess the main reason why the model would fit the image so poorly were the bright and irregular cores of the galaxies -- or possible higher order flat-field curvature. The other objects were masked out. Here is the model -- at ds9's 99.5 scale and heat colourmap (this is handy: ds9 -scale mode 99.5 -cmap Heat -medatacube ~/workspace/MICE/galfit/subcomps.fits). The long, bright tails are not well visible with these settings, but they weren't the goal. I am not really happy with the residual picture, as it tells me there are some big, obscured components lurking underneath. But that'll have to do for the moment, as I have other assignments. I've been doing this for other people in the collaboration, so I don't think I can publish the fit logs here, unfortunately.
Friday, March 9, 2012
Healing holes in arrays in Python: interpolation vs. inpainting
I had solved that interpolation task I was working on previously, by the way. I post my approach here, in case someone finds it useful.
If the bad pixel regions are big, standard methods of interpolation are not applicable. Interpolation works under assumption that the regions are contiguous, whereas this is not necessarily the case. Besides, none of interpolation implementations in python seem to work with masked arrays, and I've tried a metric ton of them. miceuz, who was sitting on this task half night as well, asked about it on stackoverflow, and someone mentioned the right keyword: inpainting.That's still inventing the data, but the option is having unquantifiable errors in photometry if we leave out the bad pixels or don't mask the bad areas at all.
OpenCV is a huge piece of software, and using it to fill those holes is tantamount to using a hammer to crack a nut. However, I reused this tiny piece of code, adding a [hardcoded ,)] Gaussian weights kernel as I needed to use inverse distance weighting for interpolation. Here's the code:
import numpy as np
import pyfits
from scipy import ndimage
import inpaint
maskedImg = np.ma.array(cutout, mask = cutoutMask)
NANMask = maskedImg.filled(np.NaN)
badArrays, num_badArrays = sp.ndimage.label(cutoutMask)
print num_badArrays
data_slices = sp.ndimage.find_objects(badArrays)
filled = inpaint.replace_nans(NANMask, 5, 0.5, 2, 'iwd')
hdu = pyfits.PrimaryHDU(filled)
hdu.writeto('filled_lm.fits')
inpaint module boils down to this -- I used the code linked above, just lobotomised the Cython:
# -*- coding: utf-8 -*-
"""A module for various utilities and helper functions"""
import numpy as np
#cimport numpy as np
#cimport cython
DTYPEf = np.float64
#ctypedef np.float64_t DTYPEf_t
DTYPEi = np.int32
#ctypedef np.int32_t DTYPEi_t
#@cython.boundscheck(False) # turn of bounds-checking for entire function
#@cython.wraparound(False) # turn of bounds-checking for entire function
def replace_nans(array, max_iter, tol,kernel_size=1,method='localmean'):
"""Replace NaN elements in an array using an iterative image inpainting algorithm.
The algorithm is the following:
1) For each element in the input array, replace it by a weighted average
of the neighbouring elements which are not NaN themselves. The weights depends
of the method type. If ``method=localmean`` weight are equal to 1/( (2*kernel_size+1)**2 -1 )
2) Several iterations are needed if there are adjacent NaN elements.
If this is the case, information is "spread" from the edges of the missing
regions iteratively, until the variation is below a certain threshold.
Parameters
----------
array : 2d np.ndarray
an array containing NaN elements that have to be replaced
max_iter : int
the number of iterations
kernel_size : int
the size of the kernel, default is 1
method : str
the method used to replace invalid values. Valid options are
`localmean`, 'idw'.
Returns
-------
filled : 2d np.ndarray
a copy of the input array, where NaN elements have been replaced.
"""
# cdef int i, j, I, J, it, n, k, l
# cdef int n_invalids
filled = np.empty( [array.shape[0], array.shape[1]], dtype=DTYPEf)
kernel = np.empty( (2*kernel_size+1, 2*kernel_size+1), dtype=DTYPEf )
# cdef np.ndarray[np.int_t, ndim=1] inans
# cdef np.ndarray[np.int_t, ndim=1] jnans
# indices where array is NaN
inans, jnans = np.nonzero( np.isnan(array) )
# number of NaN elements
n_nans = len(inans)
# arrays which contain replaced values to check for convergence
replaced_new = np.zeros( n_nans, dtype=DTYPEf)
replaced_old = np.zeros( n_nans, dtype=DTYPEf)
# depending on kernel type, fill kernel array
if method == 'localmean':
print 'kernel_size', kernel_size
for i in range(2*kernel_size+1):
for j in range(2*kernel_size+1):
kernel[i,j] = 1
print kernel, 'kernel'
elif method == 'idw':
kernel = np.array([[0, 0.5, 0.5, 0.5,0],
[0.5,0.75,0.75,0.75,0.5],
[0.5,0.75,1,0.75,0.5],
[0.5,0.75,0.75,0.5,1],
[0, 0.5, 0.5 ,0.5 ,0]])
print kernel, 'kernel'
else:
raise ValueError( 'method not valid. Should be one of `localmean`.')
# fill new array with input elements
for i in range(array.shape[0]):
for j in range(array.shape[1]):
filled[i,j] = array[i,j]
# make several passes
# until we reach convergence
for it in range(max_iter):
print 'iteration', it
# for each NaN element
for k in range(n_nans):
i = inans[k]
j = jnans[k]
# initialize to zero
filled[i,j] = 0.0
n = 0
# loop over the kernel
for I in range(2*kernel_size+1):
for J in range(2*kernel_size+1):
# if we are not out of the boundaries
if i+I-kernel_size < array.shape[0] and i+I-kernel_size >= 0:
if j+J-kernel_size < array.shape[1] and j+J-kernel_size >= 0:
# if the neighbour element is not NaN itself.
if filled[i+I-kernel_size, j+J-kernel_size] == filled[i+I-kernel_size, j+J-kernel_size] :
# do not sum itself
if I-kernel_size != 0 and J-kernel_size != 0:
# convolve kernel with original array
filled[i,j] = filled[i,j] + filled[i+I-kernel_size, j+J-kernel_size]*kernel[I, J]
n = n + 1*kernel[I,J]
print n
# divide value by effective number of added elements
if n != 0:
filled[i,j] = filled[i,j] / n
replaced_new[k] = filled[i,j]
else:
filled[i,j] = np.nan
# check if mean square difference between values of replaced
#elements is below a certain tolerance
print 'tolerance', np.mean( (replaced_new-replaced_old)**2 )
if np.mean( (replaced_new-replaced_old)**2 ) < tol:
break
else:
for l in range(n_nans):
replaced_old[l] = replaced_new[l]
return filled
def sincinterp(image, x, y, kernel_size=3 ):
"""Re-sample an image at intermediate positions between pixels.
This function uses a cardinal interpolation formula which limits
the loss of information in the resampling process. It uses a limited
number of neighbouring pixels.
The new image :math:`im^+` at fractional locations :math:`x` and :math:`y` is computed as:
.. math::
im^+(x,y) = \sum_{i=-\mathtt{kernel\_size}}^{i=\mathtt{kernel\_size}} \sum_{j=-\mathtt{kernel\_size}}^{j=\mathtt{kernel\_size}} \mathtt{image}(i,j) sin[\pi(i-\mathtt{x})] sin[\pi(j-\mathtt{y})] / \pi(i-\mathtt{x}) / \pi(j-\mathtt{y})
Parameters
----------
image : np.ndarray, dtype np.int32
the image array.
x : two dimensions np.ndarray of floats
an array containing fractional pixel row
positions at which to interpolate the image
y : two dimensions np.ndarray of floats
an array containing fractional pixel column
positions at which to interpolate the image
kernel_size : int
interpolation is performed over a ``(2*kernel_size+1)*(2*kernel_size+1)``
submatrix in the neighbourhood of each interpolation point.
Returns
-------
im : np.ndarray, dtype np.float64
the interpolated value of ``image`` at the points specified
by ``x`` and ``y``
"""
# indices
# cdef int i, j, I, J
# the output array
r = np.zeros( [x.shape[0], x.shape[1]], dtype=DTYPEf)
# fast pi
pi = 3.1419
# for each point of the output array
for I in range(x.shape[0]):
for J in range(x.shape[1]):
#loop over all neighbouring grid points
for i in range( int(x[I,J])-kernel_size, int(x[I,J])+kernel_size+1 ):
for j in range( int(y[I,J])-kernel_size, int(y[I,J])+kernel_size+1 ):
# check that we are in the boundaries
if i >= 0 and i <= image.shape[0] and j >= 0 and j <= image.shape[1]:
if (i-x[I,J]) == 0.0 and (j-y[I,J]) == 0.0:
r[I,J] = r[I,J] + image[i,j]
elif (i-x[I,J]) == 0.0:
r[I,J] = r[I,J] + image[i,j] * np.sin( pi*(j-y[I,J]) )/( pi*(j-y[I,J]) )
elif (j-y[I,J]) == 0.0:
r[I,J] = r[I,J] + image[i,j] * np.sin( pi*(i-x[I,J]) )/( pi*(i-x[I,J]) )
else:
r[I,J] = r[I,J] + image[i,j] * np.sin( pi*(i-x[I,J]) )*np.sin( pi*(j-y[I,J]) )/( pi*pi*(i-x[I,J])*(j-y[I,J]))
return r
#cdef extern from "math.h":
# double sin(double)
The thing that's bugging me is that this algorithm doesn't traverse around the edges of the hole, rather, it indexes the bad pixels incrementally. However, it does several iterations of smoothing, so maybe it's ok. At least, there are no visible spooky artifacts.
Subscribe to:
Posts (Atom)


