Correlation function of DR72 SDSS VAGC Catalog

First import all the modules such as healpy and astropy needed for analyzing the structure


In [1]:
import healpix_util as hu
import astropy as ap
import numpy as np
from astropy.io import fits
from astropy.table import Table
import astropy.io.ascii as ascii
from astropy.io import fits
from astropy.constants import c
import matplotlib.pyplot as plt
import math as m
from math import pi
#from scipy.constants import c
import scipy.special as sp
from astroML.decorators import pickle_results
from scipy import integrate
import warnings
from sklearn.neighbors import BallTree
import pickle
import multiprocessing as mp
import time
#from cython_metric import *
#from cymetric import *
from aptestmetricdt import *
from aptestmetricdz import *
from progressbar import *
from tqdm import *
from functools import partial
import pymangle
from scipy.optimize import curve_fit
#from astroML.datasets import fetch_sdss_specgals
#from astroML.correlation import bootstrap_two_point_angular
%matplotlib inline

In [ ]:
data=ascii.read("../output/DR7srarf.dat")

In [ ]:
data

In [ ]:
len(data)

In [ ]:
data.remove_column('s')
data.remove_column('ra')
data.remove_column('dec')

In [ ]:
data

In [ ]:
data.sort('z')

In [ ]:
data

In [ ]:


In [ ]:
z=np.array(data['z'])
rar=np.array(data['rar'])
decr=np.array(data['decr'])

In [ ]:
dat=np.array([z,rar,decr])

In [ ]:
dat.reshape(3,len(data['z']))

In [ ]:
dat=dat.transpose()

In [ ]:
dat

In [ ]:
with open('../output/datzAP.pkl','w') as f:
    pickle.dump(dat,f)

Read the data file (taken from http://cosmo.nyu.edu/~eak306/SDSS-LRG.html ) converted to ascii with comoving distance etc. in V01 reading from pkl files for faster read


In [2]:
# Getting back the objects:
with open('../output/datzAP.pkl') as f:  # Python 3: open(..., 'rb')
    dat = pickle.load(f)
dat


Out[2]:
array([[ 0.160002,  5.964543,  0.235823],
       [ 0.160018,  3.089162,  0.28616 ],
       [ 0.16002 ,  4.085181,  0.284492],
       ..., 
       [ 0.469989,  3.059253,  0.349895],
       [ 0.469994,  3.506603,  1.073682],
       [ 0.469996,  2.217024,  0.108364]])

In [3]:
APzdtheta(dat[0],dat[1])


Out[3]:
0.40915642068845975

In [4]:
APdz(dat[0],dat[1])


Out[4]:
1.5999999999988246e-05

In [5]:
%%time
BTpar = BallTree(dat,metric='pyfunc',func=APdz,leaf_size=5) 

with open('../output/BTdatAPpar.pkl', 'w') as f:
    pickle.dump(BTpar,f)


CPU times: user 5.15 s, sys: 41.6 ms, total: 5.19 s
Wall time: 5.2 s

In [6]:
with open('../output/BTdatAPpar.pkl') as f:
    BTpar = pickle.load(f)
    
BTpar


Out[6]:
<sklearn.neighbors.ball_tree.BinaryTree at 0x7f861ff7e150>

In [8]:
%%time
BTper = BallTree(dat,metric='pyfunc',func=APzdtheta,leaf_size=5) 

with open('../output/BTdatAPper.pkl', 'w') as f:
    pickle.dump(BTper,f)


CPU times: user 6.04 s, sys: 50.1 ms, total: 6.09 s
Wall time: 6.13 s

In [9]:
with open('../output/BTdatAPper.pkl') as f:
    BTper = pickle.load(f)
    
BTper


Out[9]:
<sklearn.neighbors.ball_tree.BinaryTree at 0x7f861d5191a0>

In [11]:
sample1=BTpar.query_radius(dat,0.002)

In [12]:
sample1


Out[12]:
array([ array([283, 341,  78,  65, 102,  54,  97, 296, 221,   9, 228, 238, 249,
       292, 212, 268, 339,  27, 156, 243, 358, 216, 294, 229, 209,  55,
       116, 161, 190, 274, 348,  69, 170, 286, 288, 257, 204, 367, 316,
        77, 322,  30, 144, 125, 362, 273,  47,  71, 301,  98,  46, 182,
        14, 368, 210,  70,  40, 215, 233, 334, 191, 307, 193, 101,  50,
       360,  74,  86, 237,  31, 300, 247, 175, 351, 225, 189, 287, 122,
       282, 346,  63, 347, 199,  20, 332,  53,  37,  32, 312, 177,  93,
       320, 173, 218, 306, 214, 140, 151,  44,  72, 344, 183, 112, 281,
        66, 327, 355, 253, 143, 245,  85,  34, 262, 163, 147,  45, 103,
       168, 220, 353, 131, 149,  76, 293, 259, 105, 331, 124, 340,  59,
        99, 198,   1,  11, 219, 206, 155,  15, 186,   8, 311,  57,  39,
       176, 154, 321,  10, 275,   5,  26, 267, 181, 185, 284,  29,  51,
       297, 251, 330, 106, 302, 137, 213, 178, 345, 365, 317, 207, 366,
        49, 361, 278, 260, 211,  95, 230,  23, 108, 159, 291,  56, 160,
       195,   7, 303, 132,  82, 357, 107, 242,  19, 256, 276, 240,  21,
         4, 164, 289, 187, 231, 222, 224, 141,  58, 323, 200, 250, 304,
       310, 318, 153, 263, 205, 319, 110, 152, 338,   3, 167, 117, 136,
       138,  13, 241, 337, 232,  87, 172, 308,  60, 119, 244, 150, 266,
        24, 201, 166, 324, 309, 298, 239, 359, 226,  43, 335,  67,  35,
       146, 342, 369, 120, 179, 234, 290, 192, 261, 104, 350, 315, 246,
       280,  89, 333, 271, 111, 352, 277,  33, 196, 325, 258, 169, 128,
       272,  79, 235,   6,  90,  92, 118, 129,  73,  12, 134, 162, 174,
       126, 208,  16, 217, 133,  22, 158, 254,   2,  48, 115, 248,  62,
       197, 194, 354, 157, 295, 252, 329, 364, 139,  81, 363, 114, 109,
        68, 227,  36, 264,  38,  52, 279, 100, 299, 121,  28, 255,  17,
       188,  18, 336, 326, 236, 113, 142, 313, 180, 203, 184, 314,  91,
       265,  88, 223,  25, 127,  83,  41, 171, 202,  75,  94,  61, 356,
       269, 305, 270, 328, 145, 370, 148,  96,  64, 123, 343, 349, 285,
        80, 165,   0,  42,  84, 130, 135]),
       array([283, 341,  78,  65, 102,  54,  97, 296, 221,   9, 228, 238, 249,
       292, 212, 268, 339,  27, 156, 243, 358, 216, 294, 229, 209,  55,
       116, 161, 190, 274, 348,  69, 170, 286, 288, 257, 204, 367, 316,
        77, 322,  30, 144, 125, 362, 273,  47,  71, 301,  98,  46, 182,
        14, 368, 210,  70,  40, 215, 233, 334, 191, 307, 193, 101,  50,
       360,  74,  86, 237,  31, 300, 247, 175, 351, 225, 189, 287, 122,
       282, 346,  63, 347, 199,  20, 332,  53,  37,  32, 312, 177,  93,
       320, 173, 218, 372, 306, 214, 140, 151,  44,  72, 344, 183, 112,
       281,  66, 327, 355, 253, 143, 245,  85,  34, 262, 163, 147,  45,
       103, 168, 220, 353, 131, 149,  76, 293, 259, 105, 331, 124, 340,
        59,  99, 198,   1,  11, 219, 206, 155,  15, 186,   8, 311,  57,
        39, 176, 154, 321,  10, 275,   5,  26, 267, 181, 185, 284,  29,
        51, 297, 251, 330, 106, 302, 137, 213, 178, 345, 365, 317, 207,
       366,  49, 361, 371, 278, 260, 211,  95, 230,  23, 108, 159, 291,
        56, 160, 195,   7, 303, 132,  82, 357, 107, 242,  19, 256, 276,
       240,  21,   4, 164, 289, 187, 231, 222, 224, 141,  58, 323, 200,
       250, 304, 310, 318, 153, 263, 205, 319, 110, 152, 338,   3, 167,
       117, 136, 138,  13, 241, 337, 232,  87, 172, 308,  60, 119, 244,
       150, 266,  24, 201, 166, 324, 309, 298, 239, 359, 226,  43, 335,
        67,  35, 146, 342, 369, 120, 179, 234, 290, 192, 261, 104, 350,
       315, 246, 280,  89, 333, 271, 111, 352, 277,  33, 196, 325, 258,
       169, 128, 272,  79, 235,   6,  90,  92, 118, 129,  73,  12, 134,
       162, 174, 126, 208,  16, 217, 133,  22, 158, 254,   2,  48, 115,
       248,  62, 197, 194, 354, 157, 295, 252, 329, 364, 139,  81, 363,
       114, 109,  68, 227,  36, 264,  38,  52, 279, 100, 299, 121,  28,
       255,  17, 188,  18, 336, 326, 236, 113, 142, 313, 180, 203, 184,
       314,  91, 265,  88, 223,  25, 127,  83,  41, 171, 202,  75,  94,
        61, 356, 269, 305, 270, 328, 145, 370, 148,  96,  64, 123, 343,
       349, 285,  80, 165,   0,  42,  84, 130, 135]),
       array([283, 341,  78,  65, 102,  54,  97, 296, 221,   9, 228, 238, 249,
       292, 212, 268, 339,  27, 156, 243, 358, 216, 294, 229, 209,  55,
       116, 161, 190, 274, 348,  69, 170, 286, 288, 257, 204, 367, 316,
        77, 322,  30, 144, 125, 362, 273, 373,  47,  71, 301,  98,  46,
       182,  14, 368, 210,  70,  40, 215, 233, 334, 191, 307, 193, 101,
        50, 360,  74,  86, 237,  31, 300, 247, 175, 351, 225, 189, 287,
       122, 282, 346,  63, 347, 199,  20, 332,  53,  37,  32, 312, 177,
        93, 320, 173, 218, 372, 306, 214, 140, 151,  44,  72, 344, 183,
       112, 281,  66, 327, 355, 253, 143, 245,  85,  34, 262, 163, 147,
        45, 103, 168, 220, 353, 131, 149,  76, 293, 259, 105, 331, 124,
       340,  59,  99, 198,   1,  11, 219, 206, 155,  15, 186,   8, 311,
        57,  39, 176, 154, 321,  10, 275,   5,  26, 267, 181, 185, 284,
        29,  51, 297, 251, 330, 106, 302, 137, 213, 178, 345, 365, 317,
       207, 366,  49, 361, 371, 278, 260, 211,  95, 230,  23, 108, 159,
       291,  56, 160, 195,   7, 303, 132,  82, 357, 107, 242,  19, 256,
       276, 240,  21,   4, 164, 289, 187, 231, 222, 224, 141,  58, 323,
       200, 250, 304, 310, 318, 153, 263, 205, 319, 110, 152, 338,   3,
       167, 117, 136, 138,  13, 241, 337, 232,  87, 172, 308,  60, 119,
       244, 150, 266,  24, 201, 166, 324, 309, 298, 239, 359, 226,  43,
       335,  67,  35, 146, 342, 369, 120, 179, 234, 290, 192, 261, 104,
       350, 315, 246, 280,  89, 333, 271, 111, 352, 277,  33, 196, 325,
       258, 169, 128, 272,  79, 235,   6,  90,  92, 118, 129,  73,  12,
       134, 162, 174, 126, 208,  16, 217, 133,  22, 158, 254,   2,  48,
       115, 248,  62, 197, 194, 354, 157, 295, 252, 329, 364, 139,  81,
       363, 114, 109,  68, 227,  36, 264,  38,  52, 279, 100, 299, 121,
        28, 255,  17, 188,  18, 336, 326, 236, 113, 142, 313, 180, 203,
       184, 314,  91, 265,  88, 223,  25, 127,  83,  41, 171, 202,  75,
        94,  61, 356, 269, 305, 270, 328, 145, 370, 148,  96,  64, 123,
       343, 349, 285,  80, 165,   0,  42,  84, 130, 135]),
       ...,
       array([105726, 105791, 105675, 105599, 105490, 105632, 105600, 105526,
       105593, 105467, 105605, 105781, 105750, 105571, 105792, 105456,
       105615, 105435, 105649, 105798, 105451, 105567, 105529, 105604,
       105521, 105452, 105829, 105655, 105808, 105517, 105465, 105761,
       105446, 105753, 105663, 105695, 105823, 105708, 105680, 105481,
       105790, 105560, 105809, 105653, 105433, 105763, 105462, 105524,
       105580, 105687, 105644, 105469, 105498, 105491, 105574, 105766,
       105717, 105553, 105681, 105497, 105541, 105534, 105538, 105584,
       105634, 105767, 105444, 105775, 105586, 105764, 105788, 105535,
       105617, 105742, 105635, 105482, 105613, 105639, 105774, 105818,
       105826, 105588, 105752, 105736, 105678, 105489, 105694, 105621,
       105471, 105730, 105630, 105665, 105589, 105552, 105637, 105527,
       105590, 105608, 105510, 105461, 105633, 105579, 105458, 105741,
       105664, 105793, 105765, 105537, 105805, 105624, 105725, 105816,
       105502, 105609, 105459, 105732, 105682, 105821, 105511, 105525,
       105558, 105743, 105544, 105532, 105487, 105549, 105747, 105554,
       105501, 105587, 105476, 105668, 105691, 105813, 105626, 105520,
       105652, 105431, 105799, 105669, 105795, 105711, 105450, 105827,
       105804, 105618, 105749, 105731, 105568, 105696, 105504, 105796,
       105488, 105548, 105671, 105803, 105472, 105627, 105715, 105540,
       105737, 105651, 105800, 105735, 105598, 105610, 105601, 105449,
       105438, 105713, 105466, 105547, 105714, 105815, 105562, 105542,
       105778, 105523, 105468, 105495, 105551, 105536, 105706, 105810,
       105783, 105733, 105576, 105770, 105463, 105508, 105645, 105480,
       105445, 105518, 105785, 105606, 105478, 105531, 105595, 105690,
       105769, 105440, 105712, 105512, 105591, 105594, 105483, 105667,
       105745, 105722, 105812, 105739, 105660, 105622, 105654, 105780,
       105674, 105631, 105628, 105754, 105513, 105719, 105650, 105575,
       105619, 105583, 105629, 105519, 105436, 105566, 105614, 105784,
       105817, 105486, 105760, 105825, 105686, 105684, 105496, 105776,
       105662, 105473, 105657, 105530, 105643, 105516, 105721, 105688,
       105638, 105740, 105806, 105625, 105561, 105578, 105559, 105623,
       105822, 105612, 105506, 105515, 105777, 105505, 105454, 105728,
       105585, 105573, 105447, 105701, 105479, 105811, 105533, 105689,
       105661, 105705, 105441, 105577, 105507, 105500, 105683, 105828,
       105509, 105789, 105724, 105485, 105484, 105773, 105616, 105659,
       105636, 105429, 105448, 105685, 105545, 105550, 105442, 105782,
       105539, 105670, 105673, 105703, 105759, 105702, 105514, 105570,
       105679, 105755, 105738, 105762, 105718, 105794, 105751, 105557,
       105758, 105443, 105787, 105697, 105709, 105434, 105457, 105797,
       105620, 105748, 105528, 105460, 105607, 105692, 105592, 105563,
       105807, 105640, 105771, 105642, 105716, 105453, 105611, 105699,
       105581, 105656, 105464, 105700, 105503, 105492, 105564, 105672,
       105648, 105582, 105746, 105474, 105455, 105698, 105693, 105801,
       105493, 105499, 105704, 105437, 105772, 105494, 105756, 105710,
       105543, 105641, 105569, 105596, 105666, 105658, 105768, 105428,
       105744, 105786, 105779, 105646, 105819, 105546, 105565, 105729,
       105602, 105475, 105647, 105572, 105734, 105824, 105757, 105814,
       105723, 105477, 105470, 105556, 105603, 105430, 105820, 105727,
       105597, 105676, 105720, 105802, 105555, 105432, 105707, 105677,
       105439, 105522]),
       array([105726, 105791, 105675, 105599, 105490, 105632, 105600, 105526,
       105593, 105467, 105605, 105781, 105750, 105571, 105792, 105456,
       105615, 105435, 105649, 105798, 105451, 105567, 105529, 105604,
       105521, 105452, 105829, 105655, 105808, 105517, 105465, 105761,
       105446, 105753, 105663, 105695, 105823, 105708, 105680, 105481,
       105790, 105560, 105809, 105653, 105433, 105763, 105462, 105524,
       105580, 105687, 105644, 105469, 105498, 105491, 105574, 105766,
       105717, 105553, 105681, 105497, 105541, 105534, 105538, 105584,
       105634, 105767, 105444, 105775, 105586, 105764, 105788, 105535,
       105617, 105742, 105635, 105482, 105613, 105639, 105774, 105818,
       105826, 105588, 105752, 105736, 105678, 105489, 105694, 105621,
       105471, 105730, 105630, 105665, 105589, 105552, 105637, 105527,
       105590, 105608, 105510, 105461, 105633, 105579, 105458, 105741,
       105664, 105793, 105765, 105537, 105805, 105624, 105725, 105816,
       105502, 105609, 105459, 105732, 105682, 105821, 105511, 105525,
       105558, 105743, 105544, 105532, 105487, 105549, 105747, 105554,
       105501, 105587, 105476, 105668, 105691, 105813, 105626, 105520,
       105652, 105431, 105799, 105669, 105795, 105711, 105450, 105827,
       105804, 105618, 105749, 105731, 105568, 105696, 105504, 105796,
       105488, 105548, 105671, 105803, 105472, 105627, 105715, 105540,
       105737, 105651, 105800, 105735, 105598, 105610, 105601, 105449,
       105438, 105713, 105466, 105547, 105714, 105815, 105562, 105542,
       105778, 105523, 105468, 105495, 105551, 105536, 105706, 105810,
       105783, 105733, 105576, 105770, 105463, 105508, 105645, 105480,
       105445, 105518, 105785, 105606, 105478, 105531, 105595, 105690,
       105769, 105440, 105712, 105512, 105591, 105594, 105483, 105667,
       105745, 105722, 105812, 105739, 105660, 105622, 105654, 105780,
       105674, 105631, 105628, 105754, 105513, 105719, 105650, 105575,
       105619, 105583, 105629, 105519, 105436, 105566, 105614, 105784,
       105817, 105486, 105760, 105825, 105686, 105684, 105496, 105776,
       105662, 105473, 105657, 105530, 105643, 105516, 105721, 105688,
       105638, 105740, 105806, 105625, 105561, 105578, 105559, 105623,
       105822, 105612, 105506, 105515, 105777, 105505, 105454, 105728,
       105585, 105573, 105447, 105701, 105479, 105811, 105533, 105689,
       105661, 105705, 105441, 105577, 105507, 105500, 105683, 105828,
       105509, 105789, 105724, 105485, 105484, 105773, 105616, 105659,
       105636, 105429, 105448, 105685, 105545, 105550, 105442, 105782,
       105539, 105670, 105673, 105703, 105759, 105702, 105514, 105570,
       105679, 105755, 105738, 105762, 105718, 105794, 105751, 105557,
       105758, 105443, 105787, 105697, 105709, 105434, 105457, 105797,
       105620, 105748, 105528, 105460, 105607, 105692, 105592, 105563,
       105807, 105640, 105771, 105642, 105716, 105453, 105611, 105699,
       105581, 105656, 105464, 105700, 105503, 105492, 105564, 105672,
       105648, 105582, 105746, 105474, 105455, 105698, 105693, 105801,
       105493, 105499, 105704, 105437, 105772, 105494, 105756, 105710,
       105543, 105641, 105569, 105596, 105666, 105658, 105768, 105744,
       105786, 105779, 105646, 105819, 105546, 105565, 105729, 105602,
       105475, 105647, 105572, 105734, 105824, 105757, 105814, 105723,
       105477, 105470, 105556, 105603, 105430, 105820, 105727, 105597,
       105676, 105720, 105802, 105555, 105432, 105707, 105677, 105439,
       105522]),
       array([105726, 105791, 105675, 105599, 105490, 105632, 105600, 105526,
       105593, 105467, 105605, 105781, 105750, 105571, 105792, 105456,
       105615, 105435, 105649, 105798, 105451, 105567, 105529, 105604,
       105521, 105452, 105829, 105655, 105808, 105517, 105465, 105761,
       105446, 105753, 105663, 105695, 105823, 105708, 105680, 105481,
       105790, 105560, 105809, 105653, 105433, 105763, 105462, 105524,
       105580, 105687, 105644, 105469, 105498, 105491, 105574, 105766,
       105717, 105553, 105681, 105497, 105541, 105534, 105538, 105584,
       105634, 105767, 105444, 105775, 105586, 105764, 105788, 105535,
       105617, 105742, 105635, 105482, 105613, 105639, 105774, 105818,
       105826, 105588, 105752, 105736, 105678, 105489, 105694, 105621,
       105471, 105730, 105630, 105665, 105589, 105552, 105637, 105527,
       105590, 105608, 105510, 105461, 105633, 105579, 105458, 105741,
       105664, 105793, 105765, 105537, 105805, 105624, 105725, 105816,
       105502, 105609, 105459, 105732, 105682, 105821, 105511, 105525,
       105558, 105743, 105544, 105532, 105487, 105549, 105747, 105554,
       105501, 105587, 105476, 105668, 105691, 105813, 105626, 105520,
       105652, 105431, 105799, 105669, 105795, 105711, 105450, 105827,
       105804, 105618, 105749, 105731, 105568, 105696, 105504, 105796,
       105488, 105548, 105671, 105803, 105472, 105627, 105715, 105540,
       105737, 105651, 105800, 105735, 105598, 105610, 105601, 105449,
       105438, 105713, 105466, 105547, 105714, 105815, 105562, 105542,
       105778, 105523, 105468, 105495, 105551, 105536, 105706, 105810,
       105783, 105733, 105576, 105770, 105463, 105508, 105645, 105480,
       105445, 105518, 105785, 105606, 105478, 105531, 105595, 105690,
       105769, 105440, 105712, 105512, 105591, 105594, 105483, 105667,
       105745, 105722, 105812, 105739, 105660, 105622, 105654, 105780,
       105674, 105631, 105628, 105754, 105513, 105719, 105650, 105575,
       105619, 105583, 105629, 105519, 105436, 105566, 105614, 105784,
       105817, 105486, 105760, 105825, 105686, 105684, 105496, 105776,
       105662, 105473, 105657, 105530, 105643, 105516, 105721, 105688,
       105638, 105740, 105806, 105625, 105561, 105578, 105559, 105623,
       105822, 105612, 105506, 105515, 105777, 105505, 105454, 105728,
       105585, 105573, 105447, 105701, 105479, 105811, 105533, 105689,
       105661, 105705, 105441, 105577, 105507, 105500, 105683, 105828,
       105509, 105789, 105724, 105485, 105484, 105773, 105616, 105659,
       105636, 105429, 105448, 105685, 105545, 105550, 105442, 105782,
       105539, 105670, 105673, 105703, 105759, 105702, 105514, 105570,
       105679, 105755, 105738, 105762, 105718, 105794, 105751, 105557,
       105758, 105443, 105787, 105697, 105709, 105434, 105457, 105797,
       105620, 105748, 105528, 105460, 105607, 105692, 105592, 105563,
       105807, 105640, 105771, 105642, 105716, 105453, 105611, 105699,
       105581, 105656, 105464, 105700, 105503, 105492, 105564, 105672,
       105648, 105582, 105746, 105474, 105455, 105698, 105693, 105801,
       105493, 105499, 105704, 105437, 105772, 105494, 105756, 105710,
       105543, 105641, 105569, 105596, 105666, 105658, 105768, 105744,
       105786, 105779, 105646, 105819, 105546, 105565, 105729, 105602,
       105475, 105647, 105572, 105734, 105824, 105757, 105814, 105723,
       105477, 105470, 105556, 105603, 105430, 105820, 105727, 105597,
       105676, 105720, 105802, 105555, 105432, 105707, 105677, 105439,
       105522])], dtype=object)

In [15]:
bins2=np.arange(0,0.022,0.002)
print bins2


[ 0.     0.002  0.004  0.006  0.008  0.01   0.012  0.014  0.016  0.018
  0.02 ]

In [24]:
s1=np.concatenate(sample1)
print s1


[   283    341     78 ..., 105677 105439 105522]

In [25]:
s1=np.unique(s1)
print s1


[     0      1      2 ..., 105827 105828 105829]

In [26]:
len(s1)


Out[26]:
105830

In [17]:
per1=BTper.two_point_correlation(dat[sample1[0]],bins2)

In [18]:
per1


Out[18]:
array([   284,   4430,  15736,  33865,  58022,  88590, 124927, 167518,
       217043, 271957, 332750])

In [19]:
len(sample1)


Out[19]:
105830

In [20]:
sample1.size


Out[20]:
105830

In [21]:
sample1[105829]


Out[21]:
array([105726, 105791, 105675, 105599, 105490, 105632, 105600, 105526,
       105593, 105467, 105605, 105781, 105750, 105571, 105792, 105456,
       105615, 105435, 105649, 105798, 105451, 105567, 105529, 105604,
       105521, 105452, 105829, 105655, 105808, 105517, 105465, 105761,
       105446, 105753, 105663, 105695, 105823, 105708, 105680, 105481,
       105790, 105560, 105809, 105653, 105433, 105763, 105462, 105524,
       105580, 105687, 105644, 105469, 105498, 105491, 105574, 105766,
       105717, 105553, 105681, 105497, 105541, 105534, 105538, 105584,
       105634, 105767, 105444, 105775, 105586, 105764, 105788, 105535,
       105617, 105742, 105635, 105482, 105613, 105639, 105774, 105818,
       105826, 105588, 105752, 105736, 105678, 105489, 105694, 105621,
       105471, 105730, 105630, 105665, 105589, 105552, 105637, 105527,
       105590, 105608, 105510, 105461, 105633, 105579, 105458, 105741,
       105664, 105793, 105765, 105537, 105805, 105624, 105725, 105816,
       105502, 105609, 105459, 105732, 105682, 105821, 105511, 105525,
       105558, 105743, 105544, 105532, 105487, 105549, 105747, 105554,
       105501, 105587, 105476, 105668, 105691, 105813, 105626, 105520,
       105652, 105431, 105799, 105669, 105795, 105711, 105450, 105827,
       105804, 105618, 105749, 105731, 105568, 105696, 105504, 105796,
       105488, 105548, 105671, 105803, 105472, 105627, 105715, 105540,
       105737, 105651, 105800, 105735, 105598, 105610, 105601, 105449,
       105438, 105713, 105466, 105547, 105714, 105815, 105562, 105542,
       105778, 105523, 105468, 105495, 105551, 105536, 105706, 105810,
       105783, 105733, 105576, 105770, 105463, 105508, 105645, 105480,
       105445, 105518, 105785, 105606, 105478, 105531, 105595, 105690,
       105769, 105440, 105712, 105512, 105591, 105594, 105483, 105667,
       105745, 105722, 105812, 105739, 105660, 105622, 105654, 105780,
       105674, 105631, 105628, 105754, 105513, 105719, 105650, 105575,
       105619, 105583, 105629, 105519, 105436, 105566, 105614, 105784,
       105817, 105486, 105760, 105825, 105686, 105684, 105496, 105776,
       105662, 105473, 105657, 105530, 105643, 105516, 105721, 105688,
       105638, 105740, 105806, 105625, 105561, 105578, 105559, 105623,
       105822, 105612, 105506, 105515, 105777, 105505, 105454, 105728,
       105585, 105573, 105447, 105701, 105479, 105811, 105533, 105689,
       105661, 105705, 105441, 105577, 105507, 105500, 105683, 105828,
       105509, 105789, 105724, 105485, 105484, 105773, 105616, 105659,
       105636, 105429, 105448, 105685, 105545, 105550, 105442, 105782,
       105539, 105670, 105673, 105703, 105759, 105702, 105514, 105570,
       105679, 105755, 105738, 105762, 105718, 105794, 105751, 105557,
       105758, 105443, 105787, 105697, 105709, 105434, 105457, 105797,
       105620, 105748, 105528, 105460, 105607, 105692, 105592, 105563,
       105807, 105640, 105771, 105642, 105716, 105453, 105611, 105699,
       105581, 105656, 105464, 105700, 105503, 105492, 105564, 105672,
       105648, 105582, 105746, 105474, 105455, 105698, 105693, 105801,
       105493, 105499, 105704, 105437, 105772, 105494, 105756, 105710,
       105543, 105641, 105569, 105596, 105666, 105658, 105768, 105744,
       105786, 105779, 105646, 105819, 105546, 105565, 105729, 105602,
       105475, 105647, 105572, 105734, 105824, 105757, 105814, 105723,
       105477, 105470, 105556, 105603, 105430, 105820, 105727, 105597,
       105676, 105720, 105802, 105555, 105432, 105707, 105677, 105439,
       105522])

In [23]:
per2=BTper.two_point_correlation(dat[sample1[1]],bins2)
print per2


[   286   4448  15800  34030  58319  89072 125641 168466 218301 273594
 334740]

In [ ]:
bins=np.arange(0.,0.08,0.005)

Above methods not working


In [ ]:


In [ ]:
print bins

In [ ]:
Nbins=len(bins)

In [ ]:
Nbins

In [ ]:
LCfmetric=LCDMmetric

In [ ]:
LCfmetric(dat[0],dat[1])

In [ ]:
%%time
start_time=time.time()
counts_DD=BTDLC.two_point_correlation(dat,bins)
print counts_DD
end_time=time.time()
tottime=end_time-start_time
print "Total run time:"
print tottime

with open('BTDcDDLCf.pkl', 'w') as f:
    pickle.dump(counts_DD,f)

In [ ]:
with open('BTDcDDLCf.pkl') as f:
    counts_DD = pickle.load(f)
    
counts_DD

In [ ]:
DD=np.diff(counts_DD)

In [ ]:
DD

In [ ]:
plt.plot(bins[1:len(bins)],DD,'ro-')

BallTree.two_point_correlation works almost 10 times faster! with leaf_size=5 Going with it to the random catalog


In [ ]:
dataR=ascii.read("./output/rand200kdr72.dat")

In [ ]:
dataR

In [ ]:
len(dataR)

In [ ]:
dataR=ascii.read("./output/rDR7200kLCsrarf.dat")

In [ ]:
dataR

In [ ]:
dataR.remove_column('z')
dataR.remove_column('ra')
dataR.remove_column('dec')

In [ ]:
dataR

In [ ]:
rs=np.array(dataR['s'])
rrar=np.array(dataR['rar'])
rdecr=np.array(dataR['decr'])

In [ ]:
datR=np.array([rs,rrar,rdecr])

In [ ]:
datR

In [ ]:
datR.reshape(3,len(dataR))

In [ ]:
datR=datR.transpose()

In [ ]:
datR

In [ ]:
# Saving the objects:
with open('rDR7200kLCsrarf.pkl', 'w') as f:  # Python 3: open(..., 'wb')
    pickle.dump(datR, f)

In [ ]:
# Getting back the objects:
with open('rDR7200kLCsrarf.pkl') as f:  # Python 3: open(..., 'rb')
    datR = pickle.load(f)
datR

In [ ]:
%%time
BT_RLC = BallTree(datR,metric='pyfunc',func=LCfmetric,leaf_size=5) 

with open('BTR200kdatsLCf.pkl', 'w') as f:
    pickle.dump(BT_RLC,f)

In [ ]:
with open('BTR200kdatsLCf.pkl') as f:
    BTRLC = pickle.load(f)
    
BTRLC

In [ ]:
%%time
start_time=time.time()
counts_RR=BTRLC.two_point_correlation(datR,bins)
print counts_RR
end_time=time.time()
tottime=end_time-start_time
print "Total run time:"
print tottime

with open('BTR200kcRRLCf.pkl', 'w') as f:
    pickle.dump(counts_RR,f)

with open('BTR200kcRRLCf.pkl') as f:
    counts_RR = pickle.load(f)
    
counts_RR

In [ ]:
counts_RR

In [ ]:
RR=np.diff(counts_RR)

In [ ]:
RR

In [ ]:
plt.plot(bins[1:len(bins)],RR,'bo-')

In [ ]:
RR_zero = (RR == 0)
RR[RR_zero] = 1

In [ ]:
%%time
start_time=time.time()
counts_DR=BTRLC.two_point_correlation(dat,bins)
print counts_DR
end_time=time.time()
tottime=end_time-start_time
print "Total run time:"
print tottime

with open('BTR200kcDRLCf.pkl', 'w') as f:
    pickle.dump(counts_DR,f)

In [ ]:
with open('BTR200kcDRLCf.pkl') as f:
    counts_DR = pickle.load(f)
    
counts_DR

In [ ]:
DR=np.diff(counts_DR)

In [ ]:
DR

In [ ]:
corrells=(4.0 * DD - 4.0 * DR + RR) / RR

In [ ]:
corrells

In [ ]:
plt.plot(bins[1:len(bins)],corrells,'go-')

In [ ]:
plt.plot(bins[1:len(bins)],bins[1:len(bins)]*bins[1:len(bins)]*corrells*(c*1e-5)**2,'go-')

In [ ]:
plt.plot(bins[2:len(bins)],bins[2:len(bins)]*bins[2:len(bins)]*corrells[1:len(bins)]*(c*1e-5)**2,'go-')

In [ ]:
plt.plot(bins[2:len(bins)],corrells[1:len(bins)],'go-')

In [ ]:
plt.plot(bins[2:len(bins)],corrells[1:len(bins)],'go-')
plt.savefig("correl2xlsLCf.pdf")

In [ ]:
plt.plot(bins[2:len(bins)]*c/1e5,corrells[1:len(bins)],'bo-')
plt.savefig("correl2x1lsLCf.pdf")

In [ ]:
plt.yscale('log')
plt.plot(bins[1:len(bins)]*c/1e5,corrells,'bo-')
plt.savefig("correllsfiglogLCf.pdf")

In [ ]:
plt.yscale('log')
plt.plot(bins[2:len(bins)]*c/1e5,corrells[1:len(bins)],'ro-')
plt.savefig("correllslog2xLCf.pdf")

In [ ]:
plt.yscale('log')
plt.xscale('log')
plt.plot(bins[1:len(bins)]*c/1e5,corrells,'bo-')
plt.savefig("correllsloglogLCf.pdf")

In [ ]:


In [ ]:


In [ ]:
from functools import partial

def harvester(text, case):
    X = case[0]
    return text + str(X)


partial_harvester = partial(harvester, case=RAW_DATASET)

partial_qr=partial(BTD.query_radius,count_only=True)

if __name__ == '__main__':
    pool = multiprocessing.Pool(processes=6)
    case_data = RAW_DATASET
    pool.map(partial_harvester, case_data, 1)
    pool.close()
    pool.join()

mapfunc = partial(BTD.query_radius, count_only=True)
map(mapfunc, volume_ids)

In [ ]:


In [ ]:
#ascii.write("DR72DDbinned.dat",(bins[1:len(bins)],DDresult))
start_time=time.time()
@pickle_results("DR72DDmp1.pkl")
def ddcal(BTD,dat,bins,Nbins):
    counts_DD=np.zeros(Nbins)
    for i in tqdm(range(Nbins)):
        counts_DD[i]=np.sum(BTD.query_radius(dat, bins[i],count_only=True))
    DD = np.diff(counts_DD)
    print counts_DD
    print DD
    return DD

def mf_wrap(args):
    return ddcal(*args)

pool=mp.Pool(8)

arg=[(BTD,dat,bins,Nbins)]
%timeit DDresult=pool.map(mf_wrap,arg) 
#DDresult = ddcal(BTD,dat,bins,Nbins)
end_time=time.time()
tottime=end_time-start_time
print "Total run time:"
print tottime

In [ ]:
%timeit dat

In [ ]:
DDresult[0]

In [ ]:
DDresult[1]

In [ ]:
plt.plot(bins[1:len(bins)],DDresult[0],'ro')

In [ ]:


In [ ]:


In [ ]:
def myfun(a,b):
  print a + b
  return a+b

def mf_wrap(args):
  return myfun(*args)

p = mp.Pool(4)

fl = [(a,b) for a in range(3) for b in range(2)]

p.map(mf_wrap, fl)

In [ ]:


In [ ]:


In [ ]:


In [ ]:
counts_DD=np.zeros(Nbins)

for i in range(Nbins):
    counts_DD[i]=np.sum(BTD.query_radius(dat, bins[i],count_only=True))
DD = np.diff(counts_DD)

In [ ]:
print counts_DD
print DD

In [ ]:
plt.plot(bins[1:len(bins)],DD,'ro')

In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:
dataR=fits.open("/Users/rohin/Downloads/random-DR7-Full.fits")

In [ ]:
dataR=dataR[1].data

In [ ]:
len(dataR)

In [ ]:


In [ ]:
tdata=np.array(data)

In [ ]:
type(tdata[4])

In [ ]:
tdata.shape

In [ ]:


In [ ]:
tdata.shape

In [ ]:
tdata=np.atleast_d(tdata)

In [ ]:
tdata.shape

In [ ]:
tdata.reshape(len(tdata),3)

In [ ]:
tdata=np.asarray(data)
tdata=tdata.transpose()

In [ ]:


In [ ]:


In [ ]:
tdata

In [ ]:
len(tdata)

In [ ]:


In [ ]:
BTD.two_point_correlationpoint_correlationpoint_correlationpoint_correlationtime
stime=time.time()
tpcf=BTD.two_point_correlation(dat,bins)
print time.time()-stime
print tpcf
plt.plot(bins,tpcf)

In [ ]:
stime=time.time()
tpcfd=BTD.two_point_correlation(dat,bins,dualtree=True)
print time.time()-stime
print tpcfd
plt.plot(bins,tpcfd)

In [ ]:


In [ ]:


In [ ]:


In [ ]:
X

In [ ]:


In [ ]:
np.random.seed(0)
X = np.random.random((30,3))
r = np.linspace(0, 1, 10)
tree = BallTree(X,metric='pyfunc',func=LCDMmetric)                
s = pickle.dumps(tree)                     
treedump = pickle.loads(s) 
treedump.two_point_correlation(X,r)

In [ ]:
BT_D = BallTree(data)
        BT_R = BallTree(data_R)

        counts_DD = np.zeros(Nbins + 1)
        counts_RR = np.zeros(Nbins + 1)

        for i in range(Nbins + 1):
            counts_DD[i] = np.sum(BT_D.query_radius(data, bins[i],
                                                    count_only=True))
            counts_RR[i] = np.sum(BT_R.query_radius(data_R, bins[i],
                                                    count_only=True))

    DD = np.diff(counts_DD)
    RR = np.diff(counts_RR)

    # check for zero in the denominator
    RR_zero = (RR == 0)
    RR[RR_zero] = 1

    if method == 'standard':
        corr = factor ** 2 * DD / RR - 1
    elif method == 'landy-szalay':
        if sklearn_has_two_point:
            counts_DR = KDT_R.two_point_correlation(data, bins)
        else:
            counts_DR = np.zeros(Nbins + 1)
            for i in range(Nbins + 1):
                counts_DR[i] = np.sum(BT_R.query_radius(data, bins[i],
                                                        count_only=True))
        DR = np.diff(counts_DR)

        corr = (factor ** 2 * DD - 2 * factor * DR + RR) / RR

    corr[RR_zero] = np.nan

    return corr

In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:
dr7fdat=np.array([data['s'][0:300] data['rar'][0:300] data['decr'][0:300]])
dr7fdat

In [ ]:
dr7fdat[2]

In [ ]:


In [ ]:
def LCDMmetric(p1,p2):
    costheta=m.sin(dec1)*m.sin(dec2)+m.cos(dec1)*m.cos(dec2)*m.cos(ra1-ra2)
    s1=DC_LCDM(z1)
    s2=DC_LCDM(z2)
    return np.sqrt(s1**2+s2**2-2.0*s1*s2*costheta)

In [ ]:


In [ ]:
#fdata=fits.open("/Users/rohin/Downloads/DR7-Full.fits")

In [ ]:
#fdata.writeto("./output/DR7fulltrim.fits")

In [ ]:
fdata=fits.open("./output/DR7fulltrim.fits")

In [ ]:
cols=fdata[1].columns

In [ ]:
cols.del_col('ZTYPE')

In [ ]:
cols.del_col('SECTOR')
cols.del_col('FGOTMAIN')
cols.del_col('QUALITY')
cols.del_col('ISBAD')
cols.del_col('M')
cols.del_col('MMAX')
cols.del_col('ILSS')
cols.del_col('ICOMB')
cols.del_col('VAGC_SELECT')
cols.del_col('LSS_INDEX')
cols.del_col('FIBERWEIGHT')
cols.del_col('PRIMTARGET')
cols.del_col('MG')
cols.del_col('SECTOR_COMPLETENESS')
cols.del_col('COMOV_DENSITY')
cols.del_col('RADIAL_WEIGHT')

In [ ]:
fdata[1].columns

In [ ]:
fdata.writeto("./output/DR7fullzradec.fits")

In [ ]:
fdat=fits.open("./output/DR7fullzradec.fits")

In [ ]:
fdat[1].columns

In [ ]:
fdat[1].data['Z']

In [ ]:
fdat[1].data['RA']

In [ ]:


In [ ]:
comovlcdm=DC_LCDM(fdat[1].data['Z'])

In [ ]:
fdat[1].data['Z']

In [ ]:
comovlcdm

In [ ]:
comovlcdm.dtype

In [ ]:
#cols=fdat[1].columns

In [ ]:
nc=fits.Column(name='COMOV',format='D',array=comovlcdm)

In [ ]:
nc1=fits.Column(name='COMOV',format='D')

In [ ]:
fdata[1].data['Z']

In [ ]:
fdata[1].data['RA']

In [ ]:
nc

In [ ]:
nc.dtype

In [ ]:
#cols.add_col(nc)

In [ ]:
fdat[1].columns

In [ ]:
fdat[1].columns.info()

In [ ]:
fdat[1].columns.add_col(nc1)

In [ ]:
fdat[1].data['COMOV']=comovlcdm

In [ ]:
comovlcdm

In [ ]:
fdat[1].data['Z']

In [ ]:
fdat[1].data['COMOV']

In [ ]:
fdat[1].data['RA']

In [ ]:
fdat[1].data['RA']=fdat[1].data['RA']*pi/180.0

In [ ]:
comovlcdm=DC_LCDM(fdat[1].data['Z'])
comovlcdm

In [ ]:


In [ ]:

Random catalog created based on the survey limitations also taken from http://cosmo.nyu.edu/~eak306/SDSS-LRG.html


In [ ]:
dataR=fits.open("/Users/rohin/Downloads/random-DR7-Full.fits")

In [ ]:
dataR

In [ ]:
dataR=dataR[1].data

In [ ]:
len(dataR)

In [ ]:
NSIDE=512
dr72hpix=hu.HealPix("ring",NSIDE)

In [ ]:
pixdata = open("./output/pixdatadr72VAGCfullrand.dat",'w')
pixdata.write("z\t pix \n")

for i in range(0,len(data)-1):
    pixdata.write("%f\t" %data['z'][i])
    pixdata.write("%d\n" %dr72hpix.eq2pix(dataR['ra'][i],dataR['dec'][i]))
pixdata.close()

In [ ]:
pixdata = ascii.read("./output/pixdatadr72VAGCfullrand.dat")
hpixdata=np.array(np.zeros(hu.nside2npix(NSIDE)))
for j in range(len(pixdata)):
    hpixdata[pixdata[j]['pix']]+=1

In [ ]:
hpixdata

In [ ]:
hu.mollview(hpixdata,rot=180)

In [ ]:
hu.orthview(hpixdata)

In [ ]:
"""
Tools for computing two-point correlation functions.
"""

#from .utils import check_random_state
# From scikit-learn utilities:
def check_random_state(seed):
    """Turn seed into a np.random.RandomState instance

    If seed is None, return the RandomState singleton used by np.random.
    If seed is an int, return a new RandomState instance seeded with seed.
    If seed is already a RandomState instance, return it.
    Otherwise raise ValueError.
    """
    if seed is None or seed is np.random:
        return np.random.mtrand._rand
    if isinstance(seed, (int, np.integer)):
        return np.random.RandomState(seed)
    if isinstance(seed, np.random.RandomState):
        return seed
    raise ValueError('%r cannot be used to seed a numpy.random.RandomState'
                     ' instance' % seed)

# Check if scikit-learn's two-point functionality is available.
# This was added in scikit-learn version 0.14
try:
    from sklearn.neighbors import KDTree
    sklearn_has_two_point = True
except ImportError:
    import warnings
    sklearn_has_two_point = False


def uniform_sphere(RAlim, DEClim, size=1):
    """Draw a uniform sample on a sphere

    Parameters
    ----------
    RAlim : tuple
        select Right Ascension between RAlim[0] and RAlim[1]
        units are degrees
    DEClim : tuple
        select Declination between DEClim[0] and DEClim[1]
    size : int (optional)
        the size of the random arrays to return (default = 1)

    Returns
    -------
    RA, DEC : ndarray
        the random sample on the sphere within the given limits.
        arrays have shape equal to size.
    """
    zlim = np.sin(np.pi * np.asarray(DEClim) / 180.)

    z = zlim[0] + (zlim[1] - zlim[0]) * np.random.random(size)
    DEC = (180. / np.pi) * np.arcsin(z)
    RA = RAlim[0] + (RAlim[1] - RAlim[0]) * np.random.random(size)

    return RA, DEC


def ra_dec_to_xyz(ra, dec):
    """Convert ra & dec to Euclidean points

    Parameters
    ----------
    ra, dec : ndarrays

    Returns
    x, y, z : ndarrays
    """
    sin_ra = np.sin(ra * np.pi / 180.)
    cos_ra = np.cos(ra * np.pi / 180.)

    sin_dec = np.sin(np.pi / 2. - dec * np.pi / 180.)
    cos_dec = np.cos(np.pi / 2. - dec * np.pi / 180.)

    return (cos_ra * sin_dec,
            sin_ra * sin_dec,
            cos_dec)


def angular_dist_to_euclidean_dist(D, r=1):
    """convert angular distances to euclidean distances"""
    return 2 * r * np.sin(0.5 * D * np.pi / 180.)


def two_point(data, bins, method='standard',
              data_R=None, random_state=None):
    """Two-point correlation function

    Parameters
    ----------
    data : array_like
        input data, shape = [n_samples, n_features]
    bins : array_like
        bins within which to compute the 2-point correlation.
        shape = Nbins + 1
    method : string
        "standard" or "landy-szalay".
    data_R : array_like (optional)
        if specified, use this as the random comparison sample
    random_state : integer, np.random.RandomState, or None
        specify the random state to use for generating background

    Returns
    -------
    corr : ndarray
        the estimate of the correlation function within each bin
        shape = Nbins
    """
    data = np.asarray(data)
    bins = np.asarray(bins)
    rng = check_random_state(random_state)

    if method not in ['standard', 'landy-szalay']:
        raise ValueError("method must be 'standard' or 'landy-szalay'")

    if bins.ndim != 1:
        raise ValueError("bins must be a 1D array")

    if data.ndim == 1:
        data = data[:, np.newaxis]
    elif data.ndim != 2:
        raise ValueError("data should be 1D or 2D")

    n_samples, n_features = data.shape
    Nbins = len(bins) - 1

    # shuffle all but one axis to get background distribution
    if data_R is None:
        data_R = data.copy()
        for i in range(n_features - 1):
            rng.shuffle(data_R[:, i])
    else:
        data_R = np.asarray(data_R)
        if (data_R.ndim != 2) or (data_R.shape[-1] != n_features):
            raise ValueError('data_R must have same n_features as data')

    factor = len(data_R) * 1. / len(data)

    if sklearn_has_two_point:
        # Fast two-point correlation functions added in scikit-learn v. 0.14
        KDT_D = KDTree(data)
        KDT_R = KDTree(data_R)

        counts_DD = KDT_D.two_point_correlation(data, bins)
        counts_RR = KDT_R.two_point_correlation(data_R, bins)

    else:
        warnings.warn("Version 0.3 of astroML will require scikit-learn "
                      "version 0.14 or higher for correlation function "
                      "calculations. Upgrade to sklearn 0.14+ now for much "
                      "faster correlation function calculations.")

        BT_D = BallTree(data)
        BT_R = BallTree(data_R)

        counts_DD = np.zeros(Nbins + 1)
        counts_RR = np.zeros(Nbins + 1)

        for i in range(Nbins + 1):
            counts_DD[i] = np.sum(BT_D.query_radius(data, bins[i],
                                                    count_only=True))
            counts_RR[i] = np.sum(BT_R.query_radius(data_R, bins[i],
                                                    count_only=True))

    DD = np.diff(counts_DD)
    RR = np.diff(counts_RR)

    # check for zero in the denominator
    RR_zero = (RR == 0)
    RR[RR_zero] = 1

    if method == 'standard':
        corr = factor ** 2 * DD / RR - 1
    elif method == 'landy-szalay':
        if sklearn_has_two_point:
            counts_DR = KDT_R.two_point_correlation(data, bins)
        else:
            counts_DR = np.zeros(Nbins + 1)
            for i in range(Nbins + 1):
                counts_DR[i] = np.sum(BT_R.query_radius(data, bins[i],
                                                        count_only=True))
        DR = np.diff(counts_DR)

        corr = (factor ** 2 * DD - 2 * factor * DR + RR) / RR

    corr[RR_zero] = np.nan

    return corr


def bootstrap_two_point(data, bins, Nbootstrap=10,
                        method='standard', return_bootstraps=False,
                        random_state=None):
    """Bootstrapped two-point correlation function

    Parameters
    ----------
    data : array_like
        input data, shape = [n_samples, n_features]
    bins : array_like
        bins within which to compute the 2-point correlation.
        shape = Nbins + 1
    Nbootstrap : integer
        number of bootstrap resamples to perform (default = 10)
    method : string
        "standard" or "landy-szalay".
    return_bootstraps: bool
        if True, return full bootstrapped samples
    random_state : integer, np.random.RandomState, or None
        specify the random state to use for generating background

    Returns
    -------
    corr, corr_err : ndarrays
        the estimate of the correlation function and the bootstrap
        error within each bin. shape = Nbins
    """
    data = np.asarray(data)
    bins = np.asarray(bins)
    rng = check_random_state(random_state)

    if method not in ['standard', 'landy-szalay']:
        raise ValueError("method must be 'standard' or 'landy-szalay'")

    if bins.ndim != 1:
        raise ValueError("bins must be a 1D array")

    if data.ndim == 1:
        data = data[:, np.newaxis]
    elif data.ndim != 2:
        raise ValueError("data should be 1D or 2D")

    if Nbootstrap < 2:
        raise ValueError("Nbootstrap must be greater than 1")

    n_samples, n_features = data.shape

    # get the baseline estimate
    corr = two_point(data, bins, method=method, random_state=rng)

    bootstraps = np.zeros((Nbootstrap, len(corr)))

    for i in range(Nbootstrap):
        indices = rng.randint(0, n_samples, n_samples)
        bootstraps[i] = two_point(data[indices, :], bins, method=method,
                                  random_state=rng)

    # use masked std dev in case of NaNs
    corr_err = np.asarray(np.ma.masked_invalid(bootstraps).std(0, ddof=1))

    if return_bootstraps:
        return corr, corr_err, bootstraps
    else:
        return corr, corr_err


def two_point_angular(ra, dec, bins, method='standard', random_state=None):
    """Angular two-point correlation function

    A separate function is needed because angular distances are not
    euclidean, and random sampling needs to take into account the
    spherical volume element.

    Parameters
    ----------
    ra : array_like
        input right ascention, shape = (n_samples,)
    dec : array_like
        input declination
    bins : array_like
        bins within which to compute the 2-point correlation.
        shape = Nbins + 1
    method : string
        "standard" or "landy-szalay".
    random_state : integer, np.random.RandomState, or None
        specify the random state to use for generating background

    Returns
    -------
    corr : ndarray
        the estimate of the correlation function within each bin
        shape = Nbins
    """
    ra = np.asarray(ra)
    dec = np.asarray(dec)
    rng = check_random_state(random_state)

    if method not in ['standard', 'landy-szalay']:
        raise ValueError("method must be 'standard' or 'landy-szalay'")

    if bins.ndim != 1:
        raise ValueError("bins must be a 1D array")

    if (ra.ndim != 1) or (dec.ndim != 1) or (ra.shape != dec.shape):
        raise ValueError('ra and dec must be 1-dimensional '
                         'arrays of the same length')

    n_features = len(ra)
    Nbins = len(bins) - 1

    # draw a random sample with N points
    ra_R, dec_R = uniform_sphere((min(ra), max(ra)),
                                 (min(dec), max(dec)),
                                 2 * len(ra))

    data = np.asarray(ra_dec_to_xyz(ra, dec), order='F').T
    data_R = np.asarray(ra_dec_to_xyz(ra_R, dec_R), order='F').T

    # convert spherical bins to cartesian bins
    bins_transform = angular_dist_to_euclidean_dist(bins)

    return two_point(data, bins_transform, method=method,
                     data_R=data_R, random_state=rng)


def bootstrap_two_point_angular(ra, dec, bins, method='standard',
                                Nbootstraps=10, random_state=None):
    # type: (object, object, object, object, object, object) -> object
    """Angular two-point correlation function

    A separate function is needed because angular distances are not
    euclidean, and random sampling needs to take into account the
    spherical volume element.

    Parameters
    ----------
    ra : array_like
        input right ascention, shape = (n_samples,)
    dec : array_like
        input declination
    bins : array_like
        bins within which to compute the 2-point correlation.
        shape = Nbins + 1
    method : string
        "standard" or "landy-szalay".
    Nbootstraps : int
        number of bootstrap resamples
    random_state : integer, np.random.RandomState, or None
        specify the random state to use for generating background

    Returns
    -------
    corr : ndarray
        the estimate of the correlation function within each bin
        shape = Nbins
    dcorr : ndarray
        error estimate on dcorr (sample standard deviation of
        bootstrap resamples)
    bootstraps : ndarray
        The full sample of bootstraps used to compute corr and dcorr
    """
    ra = np.asarray(ra)
    dec = np.asarray(dec)
    rng = check_random_state(random_state)

    if method not in ['standard', 'landy-szalay']:
        raise ValueError("method must be 'standard' or 'landy-szalay'")

    if bins.ndim != 1:
        raise ValueError("bins must be a 1D array")

    if (ra.ndim != 1) or (dec.ndim != 1) or (ra.shape != dec.shape):
        raise ValueError('ra and dec must be 1-dimensional '
                         'arrays of the same length')

    n_features = len(ra)
    Nbins = len(bins) - 1
    data = np.asarray(ra_dec_to_xyz(ra, dec), order='F').T

    # convert spherical bins to cartesian bins
    bins_transform = angular_dist_to_euclidean_dist(bins)

    bootstraps = []

    for i in range(Nbootstraps):
        # draw a random sample with N points
        ra_R, dec_R = uniform_sphere((min(ra), max(ra)),
                                     (min(dec), max(dec)),
                                     2 * len(ra))

        data_R = np.asarray(ra_dec_to_xyz(ra_R, dec_R), order='F').T

        if i > 0:
            # random sample of the data
            ind = np.random.randint(0, data.shape[0], data.shape[0])
            data_b = data[ind]
        else:
            data_b = data

        bootstraps.append(two_point(data_b, bins_transform, method=method,
                                    data_R=data_R, random_state=rng))

    bootstraps = np.asarray(bootstraps)
    corr = np.mean(bootstraps, 0)
    corr_err = np.std(bootstraps, 0, ddof=1)

    return corr, corr_err, bootstraps

In [ ]:
sklearn_has_two_point

In [ ]:
help(KDTree)

In [ ]:
dataxyz=ra_dec_to_xyz(data['ra'],data['dec'])

In [ ]:
dataxyz=np.asarray(dataxyz)

In [ ]:
dataxyz=dataxyz.transpose()

In [ ]:
dataxyz

In [ ]:
dataxyzR=ra_dec_to_xyz(dataR['ra'],dataR['dec'])

In [ ]:
dataxyzR=np.asarray(dataxyzR)

In [ ]:
dataxyzR=dataxyzR.transpose()

In [ ]:
dataxyzR

In [ ]:
bins=np.arange(0.0,1.05,0.05)

In [ ]:
bins

In [ ]:


In [ ]:
#@pickle_results("tpcf_std.pkl")
tpcf=two_point(dataxyz,bins,method='standard',data_R=dataxyzR, random_state=None)

In [ ]:
tpcf

In [ ]:
plt.plot(bins[1:],tpcf,'ro')

In [ ]:
tpcfam=two_point(dataxyz,bins,method='standard',data_R=None, random_state=None)

In [ ]:
tpcfam

In [ ]:
plt.plot(bins[1:],tpcfam,'bo')

In [ ]:
bins2=np.arange(0.2,0.6,0.02)

In [ ]:
tpcfamb2=two_point(dataxyz,bins2,method='standard',data_R=None, random_state=None)

In [ ]:
plt.plot(bins2[1:],tpcfamb2,'go')

The above doesn't show any BAO feature... It used inbuilt astroML method to generate random catalog... by shuffling the original data's content... That way all of the random points fall in the same survey area and will adhere to all the filtering criteria... the factor or ratio of data pts vs. random pts will be 1... instead of large no. in case if we take existing random catalog or create one


In [ ]:
rng = check_random_state(None)

n_samples, n_features = dataxyz.shape
Nbins = len(bins) - 1

# shuffle all but one axis to get background distribution
data_Rxyz = dataxyz.copy()
print data_Rxyz
for i in range(n_features - 1):
    rng.shuffle(data_Rxyz[:, i])
print data_Rxyz

Lets see how it looks with a healpix map


In [ ]:


In [ ]:
NSIDE=512
dr72hpix=hu.HealPix("ring",NSIDE)

In [ ]:
import math as m

def cart2sph(x,y,z):
    XsqPlusYsq = x**2 + y**2
    r = m.sqrt(XsqPlusYsq + z**2)               # r
    elev = m.atan2(z,m.sqrt(XsqPlusYsq))     # theta
    az = m.atan2(y,x)                           # phi
    return r, elev, az

def cart2sphA(pts):
    return np.array([cart2sph(x,y,z) for x,y,z in pts])

def appendSpherical(xyz):
    np.hstack((xyz, cart2sphA(xyz)))

In [ ]:
ang=cart2sphA(data_Rxyz)

In [ ]:
ang

In [ ]:
ang.shape

In [ ]:
#ang.resize((105831, 2))
np.squeeze(ang, axis=None)

In [ ]:
help(ang.squeeze)

In [ ]:
ang2=ang[:,1:]

In [ ]:
ang2

In [ ]:
ang2.shape

In [ ]:
ang2[2,0]

In [ ]:


In [ ]:
pixdata = open("./output/pixdatadr72VAGCfullrandam.dat",'w')
pixdata.write("pix \n")
for i in range(0,len(ang2)-1):
    #pixdata.write("%f\t" %data['z'][i])
    pixdata.write("%d\n" %dr72hpix.ang2pix(ang2[i,0],ang2[i,1]))
pixdata.close()

In [ ]:
pixdata = ascii.read("./output/pixdatadr72VAGCfullrandam.dat")
hpixdata=np.array(np.zeros(hu.nside2npix(NSIDE)))
for j in range(len(pixdata)):
    hpixdata[pixdata[j]['pix']]+=1

In [ ]:
hpixdata

In [ ]:
hu.mollview(hpixdata,rot=180)

In [ ]:
hu.orthview(hpixdata)

This method doesnt seem to produce right random catalogs...doing it with ra and dec as follows


In [ ]:
data

In [ ]:
data['z'],data['ra'],data['dec']

In [ ]:
datzradec=np.array([data['z'], data['ra'], data['dec']])

In [ ]:
datzradec

In [ ]:
rng = check_random_state(None)

n_features, n_samples  = datzradec.shape

# shuffle all but one axis to get background distribution
data_Rzradec = datzradec.copy()
print data_Rzradec
for i in range(1,n_features):
    rng.shuffle(data_Rzradec[:, i])
print data_Rzradec

In [ ]:
min(data_Rzradec[:, 1])

In [ ]:
max(data_Rzradec[:, 1])

In [ ]:
min(data_Rzradec[:, 2])

In [ ]:
max(data_Rzradec[:, 2])

In [ ]:


In [ ]:
min(datzradec[:, 1])

In [ ]:
max(datzradec[:, 1])

In [ ]:
min(datzradec[:, 2])

In [ ]:
max(datzradec[:, 2])

In [ ]:
range(1,3)

In [ ]:


In [ ]:


In [ ]:
help(rng.shuffle)

In [ ]:
n_samples

In [ ]:
n_features

In [ ]:
data_Rzradec

In [ ]:
data_Rzradec[0][2]

In [ ]:
len(data_Rzradec[0][:])

In [ ]:
data_Rzradec[0][:]

In [ ]:
pixdata = open("./output/pixdatadr72VAGCfullrandamrd.dat",'w')
pixdata.write("z\t pix \n")
for i in range(0,len(data_Rzradec[0][:])-1):
    pixdata.write("%f\t" %data_Rzradec[0][i])
    pixdata.write("%d\n" %dr72hpix.eq2pix(data_Rzradec[1][i],data_Rzradec[2][i]))
pixdata.close()

In [ ]:
pixdata = ascii.read("./output/pixdatadr72VAGCfullrandamrd.dat")
hpixdata=np.array(np.zeros(hu.nside2npix(NSIDE)))
for j in range(len(pixdata)):
    hpixdata[pixdata[j]['pix']]+=1

In [ ]:
hpixdata

In [ ]:
hu.mollview(hpixdata,rot=180)

In [ ]:
hu.orthview(hpixdata)

In [ ]:
dataxyz

In [ ]:
dataxyzR1=ra_dec_to_xyz(data_Rzradec[1][:],data_Rzradec[2][:])

In [ ]:
data_Rzradec[1][:]

In [ ]:


In [ ]:


In [ ]:
dataxyzR1

In [ ]:
dataxyzR1=np.asarray(dataxyzR1)

In [ ]:


In [ ]:
dataxyzR1=dataxyzR1.transpose()

In [ ]:
dataxyzR1

In [ ]:
bins=np.arange(0.025,1.025,0.025)

In [ ]:
bins

In [ ]:


In [ ]:
#@pickle_results("tpcf_std.pkl")
tpcf=two_point(dataxyz,bins,method='standard',data_R=dataxyzR1, random_state=None)

In [ ]:
tpcf

In [ ]:
plt.plot(bins[1:],tpcf,'ro')

In [ ]:
bins=np.arange(0.0,1.05,0.05)

In [ ]:
#@pickle_results("tpcf_std.pkl")
tpcf=two_point(dataxyz,bins,method='standard',data_R=dataxyzR1, random_state=None)

In [ ]:
tpcf

In [ ]:
plt.plot(bins[1:],tpcf,'ro')

In [ ]:
btpcf=bootstrap_two_point(dataxyz, bins, Nbootstrap=10,
                        method='standard', return_bootstraps=False,
                        random_state=None)

In [ ]:
btpcf

In [ ]:
plt.errorbar(bins[1:],btpcf[0],yerr=btpcf[1],fmt='ro-')

In [ ]:
help(plt.errorbar)

In [ ]:
@pickle_results("tpcf_ls.pkl")
tpcfls=two_point(dataxyz,bins,method='landy-szalay',
              data_R=dataxyzR, random_state=None)

In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:
#------------------------------------------------------------
# Set up correlation function computation
#  This calculation takes a long time with the bootstrap resampling,
#  so we'll save the results.
@pickle_results("correlation_functionsdr72.pkl")
def compute_results(Nbins=16, Nbootstraps=10,  method='landy-szalay', rseed=0):
    np.random.seed(rseed)
    bins = 10 ** np.linspace(np.log10(1. / 60.), np.log10(6), 16)

    results = [bins]
    for D in [data]:
        results += bootstrap_two_point_angular(D['ra'],
                                               D['dec'],
                                               bins=bins,
                                               method=method,
                                               Nbootstraps=Nbootstraps)

    return results

(bins, r_corr, r_corr_err, r_bootstraps) = compute_results()

bin_centers = 0.5 * (bins[1:] + bins[:-1])

In [ ]:
bins

In [ ]:
r_corr

In [ ]:
r_corr_err

In [ ]:
r_bootstraps

In [ ]:
#------------------------------------------------------------
# Plot the results

label = '$0.15<z<0.25$\n$N=33813$' 

fig = plt.figure(figsize=(6, 6))
plt.xscale('log')
plt.yscale('log')
plt.errorbar(bin_centers, r_corr, r_corr_err,fmt='.k', ecolor='gray', lw=1)
fig.text(0.8, 0.8, label, ha='right', va='top')
plt.xlabel(r'$\theta\ (deg)$')
plt.ylabel(r'$w(\theta)$')
plt.show()

plt.show()
fig.savefig("wth_dr72015025.pdf")

In [ ]:


In [ ]:
data=ascii.read('./input/sdssdr72_sorted_z.dat')

In [ ]:
data

In [ ]:
#m_max = 19

# redshift and magnitude cuts
data = data[data['z'] > 0.05]
data = data[data['z'] < 0.15]
#data = data[data['petroMag_r'] < m_max]

# RA/DEC cuts
RAmin, RAmax = 140, 220
DECmin, DECmax = 5, 45
data = data[data['ra'] < RAmax]
data = data[data['ra'] > RAmin]
data = data[data['dec'] < DECmax]
data = data[data['dec'] > DECmin]

#ur = data['modelMag_u'] - data['modelMag_r']
#flag_red = (ur > 2.22)
#flag_blue = ~flag_red

#datag 

print "data size:"
print "  total gals: ", len(data)
#print "  blue gals:", len(data_blue)

In [ ]:
NSIDE=512
dr72hpix=hu.HealPix("ring",NSIDE)

In [ ]:
pixdata = open("./output/pixdatadr72005015.dat",'w')
pixdata.write("z\t pix \n")

for i in range(0,len(data)-1):
    pixdata.write("%f\t" %data['z'][i])
    pixdata.write("%d\n" %dr72hpix.eq2pix(data['ra'][i],data['dec'][i]))
pixdata.close()

In [ ]:
pixdata = ascii.read("./output/pixdatadr72005015.dat")
hpixdata=np.array(np.zeros(hu.nside2npix(NSIDE)))
for j in range(len(pixdata)):
    hpixdata[pixdata[j]['pix']]+=1

In [ ]:
hpixdata

In [ ]:
hu.mollview(hpixdata,rot=180)

In [ ]:
hu.orthview(hpixdata)

In [ ]:
#------------------------------------------------------------
# Set up correlation function computation
#  This calculation takes a long time with the bootstrap resampling,
#  so we'll save the results.
@pickle_results("correlation_functionsdr720515.pkl")
def compute_results(Nbins=16, Nbootstraps=10,  method='landy-szalay', rseed=0):
    np.random.seed(rseed)
    bins = 10 ** np.linspace(np.log10(1. / 60.), np.log10(6), 16)

    results = [bins]
    for D in [data]:
        results += bootstrap_two_point_angular(D['ra'],
                                               D['dec'],
                                               bins=bins,
                                               method=method,
                                               Nbootstraps=Nbootstraps)

    return results

(bins, r_corr, r_corr_err, r_bootstraps) = compute_results()

bin_centers = 0.5 * (bins[1:] + bins[:-1])

In [ ]:
bins

In [ ]:
r_corr

In [ ]:
r_corr_err

In [ ]:
r_bootstraps

In [ ]:
#------------------------------------------------------------
# Plot the results
label = '$0.05<z<0.15$\n$N=138051$'

fig = plt.figure(figsize=(6, 6))
plt.xscale('log')
plt.yscale('log')
plt.errorbar(bin_centers, r_corr, r_corr_err,fmt='.k', ecolor='gray', lw=1)
fig.text(0.8, 0.8, label, ha='right', va='top')
plt.xlabel(r'$\theta\ (deg)$')
plt.ylabel(r'$w(\theta)$')
plt.show()
fig.savefig("wth_dr72005015.pdf")

In [ ]:
plt.errorbar(bins[0:len(bins)-1],r_corr,r_corr_err)

In [ ]:
data=ascii.read('./input/sdssdr72_sorted_z.dat')

In [ ]:
data

In [ ]:
data['z']

In [ ]:
#m_max = 19

# redshift and magnitude cuts
data = data[data['z'] > 0.05]
data = data[data['z'] <= 0.10]
#data = data[data['petroMag_r'] < m_max]

# RA/DEC cuts
RAmin, RAmax = 140, 220
DECmin, DECmax = 5, 45
data = data[data['ra'] < RAmax]
data = data[data['ra'] > RAmin]
data = data[data['dec'] < DECmax]
data = data[data['dec'] > DECmin]

#ur = data['modelMag_u'] - data['modelMag_r']
#flag_red = (ur > 2.22)
#flag_blue = ~flag_red

#datag 

print "data size:"
print "  total gals: ", len(data)
#print "  blue gals:", len(data_blue)

In [ ]:
NSIDE=512
dr72hpix=hu.HealPix("ring",NSIDE)

In [ ]:
pixdata = open("./output/pixdatadr7200501.dat",'w')
pixdata.write("z\t pix \n")

for i in range(0,len(data)-1):
    pixdata.write("%f\t" %data['z'][i])
    pixdata.write("%d\n" %dr72hpix.eq2pix(data['ra'][i],data['dec'][i]))
pixdata.close()

In [ ]:
pixdata = ascii.read("./output/pixdatadr7200501.dat")
hpixdata=np.array(np.zeros(hu.nside2npix(NSIDE)))
for j in range(len(pixdata)):
    hpixdata[pixdata[j]['pix']]+=1

In [ ]:
hpixdata

In [ ]:
hu.mollview(hpixdata,rot=180)

In [ ]:
hu.orthview(hpixdata)

In [ ]:
#------------------------------------------------------------
# Set up correlation function computation
#  This calculation takes a long time with the bootstrap resampling,
#  so we'll save the results.
@pickle_results("correlation_functionsdr720501.pkl")
def compute_results(Nbins=16, Nbootstraps=10,  method='landy-szalay', rseed=0):
    np.random.seed(rseed)
    bins = 10 ** np.linspace(np.log10(1. / 60.), np.log10(6), 16)

    results = [bins]
    for D in [data]:
        results += bootstrap_two_point_angular(D['ra'],
                                               D['dec'],
                                               bins=bins,
                                               method=method,
                                               Nbootstraps=Nbootstraps)

    return results

(bins, r_corr, r_corr_err, r_bootstraps) = compute_results()

bin_centers = 0.5 * (bins[1:] + bins[:-1])

In [ ]:
bins

In [ ]:
r_corr

In [ ]:
r_corr_err

In [ ]:
r_bootstraps

In [ ]:
#------------------------------------------------------------
# Plot the results

label = '$0.05<z<0.10$\n$N=78939$'

fig = plt.figure(figsize=(6, 6))
plt.xscale('log')
plt.yscale('log')
plt.errorbar(bin_centers, r_corr, r_corr_err,fmt='.k', ecolor='gray', lw=1)
fig.text(0.8, 0.8, label, ha='right', va='top')
plt.xlabel(r'$\theta\ (deg)$')
plt.ylabel(r'$w(\theta)$')
plt.show()
fig.savefig("wth_dr720501.pdf")

In [ ]:
plt.errorbar(bins[0:len(bins)-1],r_corr,r_corr_err)

In [ ]:


In [ ]:
data=ascii.read('./input/sdssdr72_sorted_z.dat')

In [ ]:
data

In [ ]:
data['z']

In [ ]:
#m_max = 19

# redshift and magnitude cuts
data = data[data['z'] > 0.10]
data = data[data['z'] <= 0.15]
#data = data[data['petroMag_r'] < m_max]

# RA/DEC cuts
RAmin, RAmax = 140, 220
DECmin, DECmax = 5, 45
data = data[data['ra'] < RAmax]
data = data[data['ra'] > RAmin]
data = data[data['dec'] < DECmax]
data = data[data['dec'] > DECmin]

#ur = data['modelMag_u'] - data['modelMag_r']
#flag_red = (ur > 2.22)
#flag_blue = ~flag_red

#datag 

print "data size:"
print "  total gals: ", len(data)
#print "  blue gals:", len(data_blue)

In [ ]:
NSIDE=512
dr72hpix=hu.HealPix("ring",NSIDE)

In [ ]:
pixdata = open("./output/pixdatadr72001015.dat",'w')
pixdata.write("z\t pix \n")

for i in range(0,len(data)-1):
    pixdata.write("%f\t" %data['z'][i])
    pixdata.write("%d\n" %dr72hpix.eq2pix(data['ra'][i],data['dec'][i]))
pixdata.close()

In [ ]:
pixdata = ascii.read("./output/pixdatadr72001015.dat")
hpixdata=np.array(np.zeros(hu.nside2npix(NSIDE)))
for j in range(len(pixdata)):
    hpixdata[pixdata[j]['pix']]+=1

In [ ]:
hpixdata

In [ ]:
hu.mollview(hpixdata,rot=180)

In [ ]:
hu.orthview(hpixdata)

In [ ]:
#------------------------------------------------------------
# Set up correlation function computation
#  This calculation takes a long time with the bootstrap resampling,
#  so we'll save the results.
@pickle_results("correlation_functionsdr72001015.pkl")
def compute_results(Nbins=16, Nbootstraps=10,  method='landy-szalay', rseed=0):
    np.random.seed(rseed)
    bins = 10 ** np.linspace(np.log10(1. / 60.), np.log10(6), 16)

    results = [bins]
    for D in [data]:
        results += bootstrap_two_point_angular(D['ra'],
                                               D['dec'],
                                               bins=bins,
                                               method=method,
                                               Nbootstraps=Nbootstraps)

    return results

(bins, r_corr, r_corr_err, r_bootstraps) = compute_results()

bin_centers = 0.5 * (bins[1:] + bins[:-1])

In [ ]:
bins

In [ ]:
r_corr

In [ ]:
r_corr_err

In [ ]:
r_bootstraps

In [ ]:
#------------------------------------------------------------
# Plot the results

label = '$0.10<z<0.15$\n$N=59112$'
fig = plt.figure(figsize=(6, 6))
plt.xscale('log')
plt.yscale('log')
plt.errorbar(bin_centers, r_corr, r_corr_err,fmt='.k', ecolor='gray', lw=1)
fig.text(0.8, 0.8, label, ha='right', va='top')
plt.xlabel(r'$\theta\ (deg)$')
plt.ylabel(r'$w(\theta)$')
plt.show()
fig.savefig("wth_dr7201015.pdf")

In [ ]:
plt.errorbar(bins[0:len(bins)-1],r_corr,r_corr_err)

In [ ]:
hu.mollview(hpixdatab,rot=180)

In [ ]:
hu.orthview(hpixdatab)

In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:
help(hu.mollview)

In [ ]:
from astroML.datasets import fetch_sdss_specgals
from astroML.correlation import bootstrap_two_point_angular

In [ ]:
help(bootstrap_two_point_angular)

In [ ]:
help(astroML.correlation)

In [ ]:
import astroML.correlation

In [ ]:
import sklearn.neighbors

In [ ]:
help(sklearn.neighbors)

Sorted and reduced column set data can now be 'read' to reduce RAM requirements of the table reading.


In [ ]:
sdssdr72=ascii.read('./input/dssdr72_sorted_z.dat')

Create a healpix map with NSIDE=64 (no. of pixels = 49152 as $NPIX=12\times NSIDE^2$) because the no. of galaxies in the survey are less. For higher resolution (later for dr12) we will consider NSIDE=512 or even 1024. For now, we will create a 64 NSIDE map.


In [ ]:
NSIDE=64
dt72hpix=hu.HealPix("ring",NSIDE)

We have data of galaxies with redshifts between 0 and 0.5 ($0<z<0.5$). To look at a time slice/at a certain epoch we need to choose the list of galaxies within a redshift window. As, measurement of redshift has $\pm 0.05$ error. We can bin all the data into redshifts with range limited to 0.05 variation each. So, we have 10 databins with almost identical redshifts. We save each databin in a different file.


In [ ]:
j=0
for i in range(1,17):
    pixdata = open("/home/rohin/Desktop/healpix/binned1/pixdata%d_%d.dat"%(NSIDE,i),'w')
    pixdata.write("ra\t dec\t z\t pix \n")
    #for j in range(len(sdssdr72)):
    try:
        while sdssdr72[j]['z']<0.03*i:
            pixdata.write("%f\t" %sdssdr72[j]['ra'])
            pixdata.write("%f\t" %sdssdr72[j]['dec'])
            pixdata.write("%f\t" %sdssdr72[j]['z'])
            pixdata.write("%d\n" %dt72hpix.eq2pix(sdssdr72[j]['ra'],sdssdr72[j]['dec']))
            #print dt72hpix.eq2pix(sdssdr72[j]['ra'],sdssdr72[j]['dec'])
            j=j+1
    except:
        pass
    pixdata.close()

In [ ]:
for i in range(1,17):
    pixdata = ascii.read("/home/rohin/Desktop/healpix/binned1/pixdata%d_%d.dat"%(NSIDE,i))
    mpixdata = open("/home/rohin/Desktop/healpix/binned1/masked/pixdata%d_%d.dat"%(NSIDE,i),'w')
    mpixdata.write("ra\t dec\t z\t pix \n")
    for j in range((len(pixdata)-1)):
        if 100<pixdata[j]['ra']<250:
            mpixdata.write("%f\t" %pixdata[j]['ra'])
            mpixdata.write("%f\t" %pixdata[j]['dec'])
            mpixdata.write("%f\t" %pixdata[j]['z'])
            mpixdata.write("%d\n" %pixdata[j]['pix'])
    #pixdata.write("/home/rohin/Desktop/healpix/binned1/masked/pixdata_%d.dat"%i,format='ascii')
                
                
            #print dt72hpix.eq2pix(sdssdr72[j]['ra'],sdssdr72[j]['dec'])
    mpixdata.close()

We now, take each databin and assign the total no. of galaxies as the value of each pixel. The following routine will calculate the no. of galaxies by couting the occurence of pixel numbers in the file.


In [ ]:
pixdata = ascii.read("/home/rohin/Desktop/healpix/binned1/masked/pixdata%d_2.dat"%NSIDE)
hpixdata=np.array(np.zeros(hu.nside2npix(NSIDE)))
for j in range(len(pixdata)):
    hpixdata[pixdata[j]['pix']]+=1

In [ ]:
hpixdata

In [ ]:
hu.orthview(hpixdata,rot=180)

In [ ]:
pixcl=hu.anafast(hpixdata,lmax=300)
ell = np.arange(len(pixcl))
plt.figure()
plt.plot(ell,np.log(pixcl))
plt.show()

In [ ]:
pixcl=hu.anafast(hpixdata,lmax=300)
ell = np.arange(len(pixcl))
plt.figure()
plt.plot(ell,np.sqrt(ell*(ell+1)*pixcl/(4*math.pi)))
plt.show()

In [ ]:
theta=np.arange(0,np.pi,0.001)

In [ ]:
correldat = np.polynomial.legendre.legval(np.cos(theta),(2*ell+1)*np.absolute(pixcl))/(4*math.pi)

In [ ]:
plt.figure()
plt.plot(theta[0:600]*180/math.pi,correldat[0:600])
plt.show()

In [ ]:
plt.figure()
plt.plot(theta*180/math.pi,correldat)
plt.show()

In [ ]:
randra,randdec=hu.randsphere(2200000)

In [ ]:
randhp=hu.HealPix("RING",NSIDE)

In [ ]:
randhppix=randhp.eq2pix(randra,randdec)

In [ ]:
randpixdat=np.array(np.zeros(hu.nside2npix(NSIDE)))

In [ ]:
for j in range(len(randhppix)):
    randpixdat[randhppix[j]]+=1

In [ ]:
randmaphp=hu.mollview(randpixdat)

In [ ]:
randcl=hu.anafast(randpixdat,lmax=300)
ell = np.arange(len(randcl))
plt.figure()
plt.plot(ell,np.sqrt(ell*(ell+1)*randcl/(4*math.pi)))
plt.show()

In [ ]:
correlrand = np.polynomial.legendre.legval(np.cos(theta),(2*ell+1)*np.absolute(randcl))/(4*math.pi)
plt.figure()
plt.plot(theta[0:600]*180/math.pi,correlrand[0:600])
plt.show()

In [ ]:
finalcorrel=correldat-correlrand
plt.figure()
plt.plot(theta[0:600]*180/math.pi,finalcorrel[0:600])
plt.show()

In [ ]:
finalpix=hpixdata-randpixdat

In [ ]:
hu.mollview(finalpix,rot=180)

In [ ]:
cl=hu.anafast(finalpix,lmax=300)
ell = np.arange(len(cl))
plt.figure()
plt.plot(ell,np.sqrt(ell*(ell+1)*cl/(4*math.pi)))
plt.show()

In [ ]:
correlrand = np.polynomial.legendre.legval(np.cos(theta),(2*ell+1)*np.absolute(cl))/(4*math.pi)
plt.figure()
plt.plot(theta[0:600]*180/math.pi,correlrand[0:600])
plt.show()

In [ ]:
finalcl=pixcl-randcl
correlrand = np.polynomial.legendre.legval(np.cos(theta),(2*ell+1)*np.absolute(finalcl))/(4*math.pi)
plt.figure()
plt.plot(theta[0:600]*180/math.pi,correlrand[0:600])
plt.show()

In [ ]:
help(fits)

In [ ]:
data[1].data['z']

In [ ]: