Showing posts with label sdss. Show all posts
Showing posts with label sdss. Show all posts

Wednesday, May 15, 2013

Daily Paper #4: Dark halo response and the stellar initial mass function in early-type and late-type galaxies

Our group meeting ate most of my day, so here's a delayed review. Title: Dark halo response and the stellar initial mass function in early-type and late-type galaxies
Authors: Dutton, Conroy, van den Bosch et al., http://arxiv.org/abs/1012.5859
Year: 2011
The authors try to find the origins of the TF and Faber-Jackson relations, using a big sample of observed galaxies from SDSS, a set of observational scaling relations showing the distribution of baryons in galaxies, with constrains on the DM halo structure from simulations.
They claim in the introduction that the origin of TFR and FJR is the relation between the halo virial velocity and its virial mass, which scales as v_vir \propto M^(1/3). The relation between v_opt (*) and v_vir depends on 3 factors:
-- the contribution of baryons to v_opt
-- the structure of pristine (DM-only) haloes. The halo profiles are well-enough defined by the NFW profile.
-- and the halo response to the disk formation (contraction/expansion)
The biggest source of uncertainty for the first factor is the IMF, as most of the baryonic mass in galaxies (except the low-mass star-forming ones) is in stars.
The third factor, the halo response, is quite uncertain. It can be adiabatic or non-adiabatic contraction, or expansion due to a number of different processes.
They use a large number of observed relations (TF and FJ relations too) to constrain or predict unknown quantities in their analytic model, modelling the DM halo, bulges, disks, gas disks, constructing 3D models of their SDSS sample galaxies (~100 000 LTGs, ~160 000 ETGs).
They construct mass models for all those galaxies using various IMF and assumptions about the halo response. Then they compare them with the observed circular velocity -- stellar mass relations (I do not understand it at this point -- they already used the TFR as a constraint while solving for the halo contraction at a given IMF, so it is inbuilt in their model somehow?).
Nevertheless, they do not reproduce the zero-point of the TFR with the standard Chabrier IMF and standard adiabatic halo contraction model, as the velocity is overpredicted. They claim that it is possible to fix that by either assuming a different IMF, or changing the halo response, or having different halo concentrations (set by formation time or \sigma_8, they claim that both ways to do it do not solve the zero-point problem).
However, they find that early-type and late-type galaxies cannot have the same IMF and halo response. For any given halo response model, ETGs and LTGs must have different IMF normalisations to reproduce the TFR. If we assume a universal IMF, early-type galaxies require stronger halo contraction.
They look into the model circular velocity profiles (see attached) for models that reproduce the TF and FJRs, with Chabrier IMF. The velocity profiles look rather constant at higher radii, reaching the maximum at ~0.3 R_vir. (For the LTGs, they convert the velocity dispersion to v_circ picking a rather simple conversion factor between sqrt(2) and sqrt(3).) They claim that the flatness of the rotation curves does not depend strongly on the IMF and the halo response model, and 'is a natural consequence for galaxies embedded in LCDM haloes'.
Then they discuss possible mechanisms that would account for differences in IMF or halo response for ETGs and LTGs. The halo contraction/expansion may depend on galaxy morphology via a number of processes:
-- adiabatic contraction due to smooth accretion -- results in disk growth and SF, important for LTGs
-- wet major mergers -- result in halo contraction because gas settles in the center of a galaxy, transforms LTGs to ellipticals
-- dry major mergers ( for ETGs) -- halo contraction due to violent relaxation which mixes stars and DM
-- clumpy accretion/minor mergers: halo expansion due to dynamical friction. Clumps must be baryonic, so that's likely to occur at high redshifts (A. Dekel was arguing in Jerusalem that it must be the case).
-- feedback causes halo expansion, more important to LTGs and for higher redshifts.
-- bars -- halo expansion or contraction, not clear.

They sum it all up by saying that the key formation event that distinguishes ETGs from LTGs is a major merger (dry or wet), which causes halo contraction. For LTGs, haloes could expand due to a combination of clumpy cold accretion and intensive feedback.
The IMF may plausibly vary with redshift due to its alleged dependence on ISM temperature via the Jeans mass. Since ETGs form their stars earlier than LTGs, their IMF might be different. They discuss the van Dokkum & Conroy 2008 article on the different IMF at the cores of massive ellipticals, and conclude that this IMF would not fit for the other ETGs well.
All in all, they show that there is a degeneracy between IMF and the halo response to disk formation, and we cannot match the two for ETGs and LTGs if we want to reproduce the TFR. However, I'm puzzled here -- like in the previous Mo, Mao, White article, they do not model galaxy evolution in a self-contained way, and a model cannot show things that are not included in it. Mo, Mao & White include one set of parameters in their article, and get a set dependences on their parameters (like the disk formation time). Here Dutton et al. model rotation curves as functions of other parameters, and get dependence on another set of parameters. I think it's tricky to understand which parameters are really important, because in astrophysics we often have many coupled parameters, and it's not difficult to find correlations between them. It's more difficult to find out which ones are the fundamental ones, which really affect the TFR.
-- a question: what does it mean "TFR is an edge-on projection of the fundamental plane" (p. 323)?
(*) v2.2 for late-type galaxies and some measure of velocity proportional to dispersion at the effective radius for early types

Friday, April 26, 2013

Batch downloading SDSS image cutouts

I remember I've done that before, but couldn't find the script. Here is one I quickly put together, based on Min-Su Shin's code.

import os
import db
from utils import *

ids = db.dbUtils.getFromDB('id', dbDir+'MyDB.sqlite', 'mothersample')

for id in ids:
  id = str(id)
  ra = db.dbUtils.getFromDB('ra', dbDir+'MyDB.sqlite', 'mothersample', ' where id = '+id)[0]
  dec = db.dbUtils.getFromDB('dec', dbDir+'MyDB.sqlite', 'mothersample', ' where id = '+id)[0]
  name = "data/cutouts/"+id+".png"
  command = str("wget 'http://casjobs.sdss.org/ImgCutoutDR7/getjpeg.aspx?ra="+str(ra)+"&dec="+str(dec)+"&scale=0.5020920&width=150&height=150&opt=GS&query=&Grid=on&PhotoObjs=on' -O "+str(name)  )
  os.system(command)




Thursday, February 7, 2013

SDSS: a query for clean photometry galaxies with redshifts

SELECT g.objid, g.ra, g.dec, g.petroMag_u, g.petroMag_g, g.petromag_r, g.petromag_i, g.petromag_z, s.z, g.petroR50_r, g.petroR90_r, g.rho, g.isoA_r, g.isoB_r, g.isophi_r,
dbo.fPhotoFlagsN(flags) as flags into mydb.galaxies from Galaxy as G
   JOIN SpecObj as S ON G.objId=S.bestObjId 
WHERE ((flags & 0x10000000) != 0)       
AND ((flags & 0x8100000c00a0) = 0)     
       
       
       
AND (((flags & 0x400000000000) = 0) or (psfmagerr_g <= 0.2))
       
       
AND (((flags & 0x100000000000) = 0) or (flags & 0x1000) = 0)

Monday, November 26, 2012

some Python scripts from Durham

A pile of interesting astrophysics scripts, especially the one creating images from GALFIT output files and the other plotting Petrosian quantities for different n.

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.

Thursday, October 18, 2012

SQLite: some average values

For copying and pasting:SELECT avg(zpt), avg(ext_coeff), avg(airmass) FROM u_tsfieldParams
select z.califa_id, z.z_mag - m.petroMag_z, z.z_mag, m.petroMag_z from z_test as z, mothersample as m where m.califa_id = z.califa_id

Thursday, October 11, 2012

orientation angles of SDSS images wrt North

I was happy using the position angles of galaxies relative to SDSS image's y axis, but people in the collaboration needed the absolute position angles with respect to the North. I used astroLib's astWCS.getRotationDeg() function, in this script. Didn't test yet, I don't know if that makes sense.

Sunday, October 7, 2012

SDSS CASjobs -- looking for objects within a given radius of a coordinate pair

There's an inbuilt function for that:

select p.ra,p.dec,p.b,p.l,p.objID,p.run,p.rerun,p.camcol,p.field,p.obj,p.type,p.flags,p.fiberMag_r,p.petroMag_u,p.petroMag_g,p.petroMag_r,p.petroMag_i,p.petroMag_z,
       p.petroRad_r,p.petroR50_r,p.petroR90_r,p.isoA_g,p.isoB_g,p.isoA_r,p.isoB_r,p.isoPhi_r,p.specObjID into mydb.MiceB from PhotoObjAll as p,
dbo.fGetNearbyObjEq(191.5, 30.7, 1.0)
n 
WHERE p.objID = n.objID 

      and
      ( flags & (dbo.fPhotoFlags('NOPETRO') +
       dbo.fPhotoFlags('MANYPETRO')
       +dbo.fPhotoFlags('TOO_FEW_GOOD_DETECTIONS')) ) = 0

Friday, August 17, 2012

Getting a fits header keyword value from a list of files

I wanted to get the sky value estimates from SDSS fits headers (fpC). There were 939 of them. It was amusing to see how many SDSS images of large galaxies didn't have the sky estimated -- should probably look at why that was the case. I remember writing something similar before, but it was easier to quickly script it.

#a rough excerpt from ellipse_photometry module. 
#loops through filenames, extracts fits header keyword values.

  sky = np.empty((939, 2))
  for i in range(0, 939):    
    try:
      fileName = GalaxyParameters.getSDSSUrl(listFile, dataDir, i)
      head = pyfits.open(fileName)[0].header
      sky[i:, 0] = i+1
      sky[i:, 1] = head['SKY']
      print head['SKY']
    except IOError as e:
      sky[i:, 0] = i+1
      sky[i:, 1] = 0
      pass
    except KeyError as err:
      sky[i:, 0] = i+1
      sky[i:, 1] = -1
      pass
  np.savetxt('SDSS_skies.txt', sky, fmt = ['%i', '%10.5f'])

Monday, May 28, 2012

Saturday, May 26, 2012

SDSS axis ratio measures

I copy it verbatim from here, to have a reference ready.

The model fits yield an estimate of the axis ratio and position angle of each object, but it is useful to have model-independent measures of ellipticity. In the data released here, frames provides two further measures of ellipticity, one based on second moments, the other based on the ellipticity of a particular isophote. The model fits do correctly account for the effect of the seeing, while the methods presented here do not.

The first method measures flux-weighted second moments, defined as:

  • Mxx = x^2/r^2
  • Myy = y^2/r^2
  • Mxy = x^y/r^2

In the case that the object's isophotes are self-similar ellipses, one can show:

  • Q = Mxx - Myy = [(a-b)/(a+b)]cos2φ
  • U = Mxy = [(a-b)/(a+b)]sin2φ

where a and b are the semi-major and semi-minor axes, and φ is the position angle. Q and U are Q and U in PhotoObj and are referred to as "Stokes parameters." They can be used to reconstruct the axis ratio and position angle, measured relative to row and column of the CCDs. This is equivalent to the normal definition of position angle (East of North), for the scans on the Equator. The performance of the Stokes parameters are not ideal at low S/N. For future data releases, frames will also output variants of the adaptive shape measures used in the weak lensing analysis of Fischer et al. (2000), which are closer to optimal measures of shape for small objects.

Isophotal Quantities

A second measure of ellipticity is given by measuring the ellipticity of the 25 magnitudes per square arcsecond isophote (in all bands). In detail, frames measures the radius of a particular isophote as a function of angle and Fourier expands this function. It then extracts from the coefficients the centroid (isoRowC,isoColC), major and minor axis (isoA,isoB), position angle (isoPhi), and average radius of the isophote in question (Profile). Placeholders exist in the database for the errors on each of these quantities, but they are not currently calculated. It also reports the derivative of each of these quantities with respect to isophote level, necessary to recompute these quantities if the photometric calibration changes.

Many more about those second order moments, and why they are called 'Stokes' parameters' can be found in references herein.

Wednesday, May 23, 2012

Left outer joins in SDSS

While I was working on our survey sample characterisation paper, I had to redo the sample selection again. There's an interesting effect in diameter limiter surveys: they should theoretically include more highly-inclined disk galaxies near the lower diameter limit, as their total brightness is projected onto a smaller area.

I was selecting two samples from the SDSS DR7: one which was only redshift-selected, and another which had no cuts in redshift, but was diameter-limited. I wanted to keep the redshift information for the diameter-limited sample (wherein not all galaxies have spectroscopic redshifts), if it was available for a particular galaxy. Hence, outer joins.


Tuesday, April 24, 2012

Efficiency 101: reading large FITS table with Python

Last week I hastily wrote some code to search the NSAtlas. It was almost ok for a single galaxy: the array is huge, and iterating through it 1000 times...it took 1 minute for each loop, so I would have to wait all day for the full query to complete.

I've changed the 'if' loop to numpy.where statements and used the collections module: here. It is almost usable, though it takes 15 minutes to search for some variable for 1000 galaxies, and the machine slows down to an almost complete halt.

There is a significant overhead associated with opening and closing files, especially as the one in question was quite huge (0.5 GB) in this case. Not calling the function from within a loop, but passing an array of search arguments and then looping through it within the function reduced the running time to 16 seconds. A 60-fold improvement in two minutes.

I'd also like to mention a fine module called collections, which helped me find an overlap between two lists, like that:

      a_multiset = collections.Counter(list(ras[0]))
      b_multiset = collections.Counter(list(decs[0]))
      overlap = list((a_multiset & b_multiset).elements())

Wednesday, April 18, 2012

NSAtlas, surface photometry

I wrote some [terribly inefficient, as of now] code for searching NASA Sloan Atlas, given a ra and dec of a galaxy. Just like I expected, my photometry results (SDSS r band) fall somewhere in between the original SDSS photometry and Sloan Atlas (they re-did the photometry, using more sophisticated sky-fitting techniques). And I am still unsure if mine makes sense. Just a good point illustrating the lesson from the previous post: due to the sheer number of pixels in the outskirts of the galaxy, the fine systematic differences on where to stop integrating give rise to significant variations in the final brightness.

Monday, April 16, 2012

Surface photometry

I used to think that galaxy photometry is difficult only in that sense that it necessarily includes errors. As galaxy edges are diffuse, it's impossible to decide where the limit is, so any estimate is subjective and uncertain. I used to think that those are only second-order errors, important in statistical sense (every approach brings its own systematics), but not for individual galaxies. Last week I was struck by a simple plot I made -- a graph showing cumulative flux, flux per pixel and flux at a ring of given distance vs. distance from the galaxy center. The cumulative flux curve does not flatten or grow linear as one would be inclined to think -- as the number of pixels at each distance increases quadratically, their contributed flux increases as well. Mean flux per pixel, however, does flatten (and gives us a rough estimate of the sky value). It might just be a pretty good measure, but I'm worried about gradient in SDSS sky.

Friday, April 13, 2012

SDSS database utilities

I've digested some available scripts for SDSS into my code, namely, Min-Su Shin's code that fetches SDSS ugriz magnitudes (actually, not necessarily, any query can do) from SDSS database, and Tamas Budavari's sqlcl.py. The first one was disemboweled to be a callable function instead of standalone command-line tool. It's in github.

Monday, April 2, 2012

Getting tsField files from SDSS

I'm always looking for this or that little piece of code I really wrote sometime ago but can't remember where I put it. Then I end up rewriting it because it is faster than grepping entire work directory and sorting through the offal. I wrote about batch downloading of SDSS images, now it seems I need a specific pipeline parameter from all 900 tsField files. Here's a oneliner (from a multi-line blob of code I'm now keeping at GitHub).
 
wget http://das.sdss.org/imaging/'+run+'/'+rerun+'/calibChunks/'+camcol+'/tsField-'+runstr+'-'+camcol+'-'+rerun+'-'+field_str+'.fit

After downloading (or just reading the parameter from header and moving happily along, I'm currently figuring that out)-- no downloading. I'm reading the value from header via http, as pyfits are capable of that.

Thursday, March 22, 2012

SDSS images batch downloading, getting key values from .fits headers

I'm sure I'm probably a 1000th person writing scripts to download a bunch of SDSS images (here and here are the two examples I know of). It takes a list of (awk-generated) SDSS parameters, uses wget to download them, reads some value from the .fits file header and writes it out. A colleague asked me to get a list of such values, so here it goes.
I'm using a couple of string manipulation functions from sdsspy, I felt it's really pointless to rewrite those.

import os
import pyfits
import csv
import numpy
import string
import gzip


#awk < sdss_database_dump.csv 'BEGIN { FS="," }; { print $1,",",$2,",",$3,",",$8,",",$9,",",$10,",",$11}' > list.txt

dataFile = 'list.txt'

#the next three functions are from sdsspy library (http://code.google.com/p/sdsspy/)

def run2string(runs):
    """
    rs = run2string(runs)
    Return the string version of the run.  756->'000756'
    Range checking is applied.
    """
    return tostring(runs,0,999999)

def field2string(fields):
    """
    fs = field2string(field)
    Return the string version of the field.  25->'0025'
    Range checking is applied.
    """
    return tostring(fields,0,9999)


def tostring(val, nmin=None, nmax=None):
    if not numpy.isscalar(val):
        return [tostring(v,nmin,nmax) for v in val]
    if isinstance(val, (str,unicode)):
 nlen = len(str(nmax))
 vstr = str(val).zfill(nlen)
 return vstr
    if nmax is not None:
        if val > nmax:
            raise ValueError("Number ranges higher than max value of %s\n" % nmax)
    if nmax is not None:
        nlen = len(str(nmax))
        vstr = str(val).zfill(nlen)
    else:
        vstr = str(val)
    return vstr        



csvReader = csv.reader(open(dataFile, "rU"), delimiter=',')
f = csv.writer(open('angles.txt', 'w'), delimiter=',')
for row in csvReader:
      print '********************************', row[0]      
      ID = string.strip(row[0])
      ra = string.strip(row[1])
      dec = string.strip(row[2])
      run = string.strip(row[3])
      rerun = string.strip(row[4])
      camcol = string.strip(row[5])
      field = string.strip(row[6])
      runstr = run2string(run)
      field_str = field2string(field)
      print 'wget http://das.sdss.org/imaging/'+run+'/'+rerun+'/corr/'+camcol+'/fpC-'+runstr+'-r'+camcol+'-'+field_str+'.fit.gz'
      os.system('wget http://das.sdss.org/imaging/'+run+'/'+rerun+'/corr/'+camcol+'/fpC-'+runstr+'-r'+camcol+'-'+field_str+'.fit.gz')
      print 'uncompressing..'
      gz = gzip.open('fpC-'+runstr+'-r'+camcol+'-'+field_str+'.fit.gz')
      imgFile = pyfits.open(gz, mode='readonly')
      print 'getting header info...'
      head = imgFile[0].header
      angle = head['SPA']
      info = (int(ID), angle)  
      f.writerow(info)