DR12Q random catalog creation

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
import scipy.special as sp
from astroML.decorators import pickle_results
from scipy import integrate
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

Read the ply data file mangle polygons


In [2]:
dat=fits.open("./input/DR12Q.fits")

In [3]:
dat=dat[1].data

In [4]:
z=dat['Z_PIPE']

In [5]:
z


Out[5]:
array([ 2.30909729,  2.49794078,  1.61884606, ...,  2.45101476,
        3.11339068,  2.39766693], dtype=float32)

In [6]:
len(z)


Out[6]:
297301

In [7]:
mangle=pymangle.Mangle("./input/boss_geometry_2014_05_28.ply")

In [8]:
%%time
rar,decr=mangle.genrand(len(z))


CPU times: user 1.12 s, sys: 4.41 ms, total: 1.13 s
Wall time: 1.14 s

In [9]:
rar


Out[9]:
array([ 200.46421,  16.276615,  217.50623, ...,  140.52798,  5.9646122,
        152.62438], dtype=float128)

In [10]:
decr


Out[10]:
array([ 38.475609,  6.1485714,  27.729229, ...,  43.966504,  29.114936,
        40.696016], dtype=float128)

In [11]:
len(rar)


Out[11]:
297301

In [12]:
print len(z)
print len(decr)


297301
297301

In [13]:
fdata = open("./output/randDR12Q.dat",'w')
fdata.write("z\t ra\t dec \n")
for i in range(0,len(rar)-1):
    fdata.write("%f\t" %z[i])
    fdata.write("%f\t" %rar[i])
    fdata.write("%f\n" %decr[i])
fdata.close()

In [14]:
fd=ascii.read("./output/randDR12Q.dat")

In [15]:
fd


Out[15]:
<Table length=297300>
zradec
float64float64float64
2.309097200.46421138.475609
2.49794116.2766156.148571
1.618846217.50623427.729229
1.360358209.7500069.125118
2.33265523.81912415.051518
3.088839245.17165157.761975
2.373299173.3549734.91245
2.542303137.50700439.254526
3.711993158.20371219.110721
2.164559241.6033520.833734
.........
1.197253343.65904412.314154
3.06474926.382062-0.859049
2.552077317.5616531.809564
2.398304155.41260129.174921
2.181301206.3569036.363123
2.43917930.74446728.764067
2.187777133.62529854.045642
2.415508182.17529226.12546
2.451015140.5279843.966504
3.1133915.96461229.114936

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

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

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

In [20]:
hpixdata


Out[20]:
array([ 0.,  0.,  0., ...,  0.,  0.,  0.])

In [21]:
hu.mollview(hpixdata,rot=180)
plt.savefig("randDR12Qm.pdf")



In [22]:
hu.orthview(hpixdata)
plt.savefig("rand12Q.pdf")



In [23]:
print min(rar)
print max(rar)
print min(decr)
print max(decr)


0.000188855808432
359.996729426
-10.9989631307
68.7228354106

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

In [25]:
ra=dat['RA']
dec=dat['DEC']

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

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

In [27]:
hpixdata


Out[27]:
array([ 0.,  0.,  0., ...,  0.,  0.,  0.])

In [28]:
hu.mollview(hpixdata,rot=180)
plt.savefig("DR12Qmollview.pdf")



In [29]:
hu.orthview(hpixdata)
plt.savefig("DR12Qorth.pdf")



In [30]:
plt.hist(z)


Out[30]:
(array([  1.43820000e+04,   4.83090000e+04,   4.26500000e+04,
          1.39641000e+05,   4.29450000e+04,   7.69800000e+03,
          1.11600000e+03,   2.71000000e+02,   1.75000000e+02,
          1.14000000e+02]),
 array([ -4.94136522e-03,   6.96677249e-01,   1.39829586e+00,
          2.09991448e+00,   2.80153309e+00,   3.50315170e+00,
          4.20477032e+00,   4.90638893e+00,   5.60800755e+00,
          6.30962616e+00,   7.01124477e+00]),
 <a list of 10 Patch objects>)

In [31]:
help(plt.hist)


Help on function hist in module matplotlib.pyplot:

hist(x, bins=None, range=None, normed=False, weights=None, cumulative=False, bottom=None, histtype=u'bar', align=u'mid', orientation=u'vertical', rwidth=None, log=False, color=None, label=None, stacked=False, hold=None, data=None, **kwargs)
    Plot a histogram.
    
    Compute and draw the histogram of *x*. The return value is a
    tuple (*n*, *bins*, *patches*) or ([*n0*, *n1*, ...], *bins*,
    [*patches0*, *patches1*,...]) if the input contains multiple
    data.
    
    Multiple data can be provided via *x* as a list of datasets
    of potentially different length ([*x0*, *x1*, ...]), or as
    a 2-D ndarray in which each column is a dataset.  Note that
    the ndarray form is transposed relative to the list form.
    
    Masked arrays are not supported at present.
    
    Parameters
    ----------
    x : (n,) array or sequence of (n,) arrays
        Input values, this takes either a single array or a sequency of
        arrays which are not required to be of the same length
    
    bins : integer or array_like or 'auto', optional
        If an integer is given, `bins + 1` bin edges are returned,
        consistently with :func:`numpy.histogram` for numpy version >=
        1.3.
    
        Unequally spaced bins are supported if `bins` is a sequence.
    
        If Numpy 1.11 is installed, may also be ``'auto'``.
    
        Default is taken from the rcParam ``hist.bins``.
    
    range : tuple or None, optional
        The lower and upper range of the bins. Lower and upper outliers
        are ignored. If not provided, `range` is (x.min(), x.max()). Range
        has no effect if `bins` is a sequence.
    
        If `bins` is a sequence or `range` is specified, autoscaling
        is based on the specified bin range instead of the
        range of x.
    
        Default is ``None``
    
    normed : boolean, optional
        If `True`, the first element of the return tuple will
        be the counts normalized to form a probability density, i.e.,
        ``n/(len(x)`dbin)``, i.e., the integral of the histogram will sum
        to 1. If *stacked* is also *True*, the sum of the histograms is
        normalized to 1.
    
        Default is ``False``
    
    weights : (n, ) array_like or None, optional
        An array of weights, of the same shape as `x`.  Each value in `x`
        only contributes its associated weight towards the bin count
        (instead of 1).  If `normed` is True, the weights are normalized,
        so that the integral of the density over the range remains 1.
    
        Default is ``None``
    
    cumulative : boolean, optional
        If `True`, then a histogram is computed where each bin gives the
        counts in that bin plus all bins for smaller values. The last bin
        gives the total number of datapoints.  If `normed` is also `True`
        then the histogram is normalized such that the last bin equals 1.
        If `cumulative` evaluates to less than 0 (e.g., -1), the direction
        of accumulation is reversed.  In this case, if `normed` is also
        `True`, then the histogram is normalized such that the first bin
        equals 1.
    
        Default is ``False``
    
    bottom : array_like, scalar, or None
        Location of the bottom baseline of each bin.  If a scalar,
        the base line for each bin is shifted by the same amount.
        If an array, each bin is shifted independently and the length
        of bottom must match the number of bins.  If None, defaults to 0.
    
        Default is ``None``
    
    histtype : {'bar', 'barstacked', 'step',  'stepfilled'}, optional
        The type of histogram to draw.
    
        - 'bar' is a traditional bar-type histogram.  If multiple data
          are given the bars are aranged side by side.
    
        - 'barstacked' is a bar-type histogram where multiple
          data are stacked on top of each other.
    
        - 'step' generates a lineplot that is by default
          unfilled.
    
        - 'stepfilled' generates a lineplot that is by default
          filled.
    
        Default is 'bar'
    
    align : {'left', 'mid', 'right'}, optional
        Controls how the histogram is plotted.
    
            - 'left': bars are centered on the left bin edges.
    
            - 'mid': bars are centered between the bin edges.
    
            - 'right': bars are centered on the right bin edges.
    
        Default is 'mid'
    
    orientation : {'horizontal', 'vertical'}, optional
        If 'horizontal', `~matplotlib.pyplot.barh` will be used for
        bar-type histograms and the *bottom* kwarg will be the left edges.
    
    rwidth : scalar or None, optional
        The relative width of the bars as a fraction of the bin width.  If
        `None`, automatically compute the width.
    
        Ignored if `histtype` is 'step' or 'stepfilled'.
    
        Default is ``None``
    
    log : boolean, optional
        If `True`, the histogram axis will be set to a log scale. If `log`
        is `True` and `x` is a 1D array, empty bins will be filtered out
        and only the non-empty (`n`, `bins`, `patches`) will be returned.
    
        Default is ``False``
    
    color : color or array_like of colors or None, optional
        Color spec or sequence of color specs, one per dataset.  Default
        (`None`) uses the standard line color sequence.
    
        Default is ``None``
    
    label : string or None, optional
        String, or sequence of strings to match multiple datasets.  Bar
        charts yield multiple patches per dataset, but only the first gets
        the label, so that the legend command will work as expected.
    
        default is ``None``
    
    stacked : boolean, optional
        If `True`, multiple data are stacked on top of each other If
        `False` multiple data are aranged side by side if histtype is
        'bar' or on top of each other if histtype is 'step'
    
        Default is ``False``
    
    Returns
    -------
    n : array or list of arrays
        The values of the histogram bins. See **normed** and **weights**
        for a description of the possible semantics. If input **x** is an
        array, then this is an array of length **nbins**. If input is a
        sequence arrays ``[data1, data2,..]``, then this is a list of
        arrays with the values of the histograms for each of the arrays
        in the same order.
    
    bins : array
        The edges of the bins. Length nbins + 1 (nbins left edges and right
        edge of last bin).  Always a single array even when multiple data
        sets are passed in.
    
    patches : list or list of lists
        Silent list of individual patches used to create the histogram
        or list of such list if multiple input datasets.
    
    Other Parameters
    ----------------
    kwargs : `~matplotlib.patches.Patch` properties
    
    See also
    --------
    hist2d : 2D histograms
    
    Notes
    -----
    Until numpy release 1.5, the underlying numpy histogram function was
    incorrect with `normed`=`True` if bin sizes were unequal.  MPL
    inherited that error.  It is now corrected within MPL when using
    earlier numpy versions.
    
    Examples
    --------
    .. plot:: mpl_examples/statistics/histogram_demo_features.py
    
    .. note::
        In addition to the above described arguments, this function can take a
        **data** keyword argument. If such a **data** argument is given, the
        following arguments are replaced by **data[<arg>]**:
    
        * All arguments with the following names: 'weights', 'x'.


In [32]:
np.histogram(z)


Out[32]:
(array([ 14382,  48309,  42650, 139641,  42945,   7698,   1116,    271,
           175,    114]),
 array([ -4.94136522e-03,   6.96677249e-01,   1.39829586e+00,
          2.09991448e+00,   2.80153309e+00,   3.50315170e+00,
          4.20477032e+00,   4.90638893e+00,   5.60800755e+00,
          6.30962616e+00,   7.01124477e+00]))

In [33]:
help(np.histogram)


Help on function histogram in module numpy.lib.function_base:

histogram(a, bins=10, range=None, normed=False, weights=None, density=None)
    Compute the histogram of a set of data.
    
    Parameters
    ----------
    a : array_like
        Input data. The histogram is computed over the flattened array.
    bins : int or sequence of scalars or str, optional
        If `bins` is an int, it defines the number of equal-width
        bins in the given range (10, by default). If `bins` is a
        sequence, it defines the bin edges, including the rightmost
        edge, allowing for non-uniform bin widths.
    
        .. versionadded:: 1.11.0
    
        If `bins` is a string from the list below, `histogram` will use
        the method chosen to calculate the optimal bin width and
        consequently the number of bins (see `Notes` for more detail on
        the estimators) from the data that falls within the requested
        range. While the bin width will be optimal for the actual data
        in the range, the number of bins will be computed to fill the
        entire range, including the empty portions. For visualisation,
        using the 'auto' option is suggested. Weighted data is not
        supported for automated bin size selection.
    
        'auto'
            Maximum of the 'sturges' and 'fd' estimators. Provides good
            all round performance
    
        'fd' (Freedman Diaconis Estimator)
            Robust (resilient to outliers) estimator that takes into
            account data variability and data size .
    
        'doane'
            An improved version of Sturges' estimator that works better
            with non-normal datasets.
    
        'scott'
            Less robust estimator that that takes into account data
            variability and data size.
    
        'rice'
            Estimator does not take variability into account, only data
            size. Commonly overestimates number of bins required.
    
        'sturges'
            R's default method, only accounts for data size. Only
            optimal for gaussian data and underestimates number of bins
            for large non-gaussian datasets.
    
        'sqrt'
            Square root (of data size) estimator, used by Excel and
            other programs for its speed and simplicity.
    
    range : (float, float), optional
        The lower and upper range of the bins.  If not provided, range
        is simply ``(a.min(), a.max())``.  Values outside the range are
        ignored. The first element of the range must be less than or
        equal to the second. `range` affects the automatic bin
        computation as well. While bin width is computed to be optimal
        based on the actual data within `range`, the bin count will fill
        the entire range including portions containing no data.
    normed : bool, optional
        This keyword is deprecated in Numpy 1.6 due to confusing/buggy
        behavior. It will be removed in Numpy 2.0. Use the ``density``
        keyword instead. If ``False``, the result will contain the
        number of samples in each bin. If ``True``, the result is the
        value of the probability *density* function at the bin,
        normalized such that the *integral* over the range is 1. Note
        that this latter behavior is known to be buggy with unequal bin
        widths; use ``density`` instead.
    weights : array_like, optional
        An array of weights, of the same shape as `a`.  Each value in
        `a` only contributes its associated weight towards the bin count
        (instead of 1). If `density` is True, the weights are
        normalized, so that the integral of the density over the range
        remains 1.
    density : bool, optional
        If ``False``, the result will contain the number of samples in
        each bin. If ``True``, the result is the value of the
        probability *density* function at the bin, normalized such that
        the *integral* over the range is 1. Note that the sum of the
        histogram values will not be equal to 1 unless bins of unity
        width are chosen; it is not a probability *mass* function.
    
        Overrides the ``normed`` keyword if given.
    
    Returns
    -------
    hist : array
        The values of the histogram. See `density` and `weights` for a
        description of the possible semantics.
    bin_edges : array of dtype float
        Return the bin edges ``(length(hist)+1)``.
    
    
    See Also
    --------
    histogramdd, bincount, searchsorted, digitize
    
    Notes
    -----
    All but the last (righthand-most) bin is half-open.  In other words,
    if `bins` is::
    
      [1, 2, 3, 4]
    
    then the first bin is ``[1, 2)`` (including 1, but excluding 2) and
    the second ``[2, 3)``.  The last bin, however, is ``[3, 4]``, which
    *includes* 4.
    
    .. versionadded:: 1.11.0
    
    The methods to estimate the optimal number of bins are well founded
    in literature, and are inspired by the choices R provides for
    histogram visualisation. Note that having the number of bins
    proportional to :math:`n^{1/3}` is asymptotically optimal, which is
    why it appears in most estimators. These are simply plug-in methods
    that give good starting points for number of bins. In the equations
    below, :math:`h` is the binwidth and :math:`n_h` is the number of
    bins. All estimators that compute bin counts are recast to bin width
    using the `ptp` of the data. The final bin count is obtained from
    ``np.round(np.ceil(range / h))`.
    
    'Auto' (maximum of the 'Sturges' and 'FD' estimators)
        A compromise to get a good value. For small datasets the Sturges
        value will usually be chosen, while larger datasets will usually
        default to FD.  Avoids the overly conservative behaviour of FD
        and Sturges for small and large datasets respectively.
        Switchover point is usually :math:`a.size \approx 1000`.
    
    'FD' (Freedman Diaconis Estimator)
        .. math:: h = 2 \frac{IQR}{n^{1/3}}
    
        The binwidth is proportional to the interquartile range (IQR)
        and inversely proportional to cube root of a.size. Can be too
        conservative for small datasets, but is quite good for large
        datasets. The IQR is very robust to outliers.
    
    'Scott'
        .. math:: h = \sigma \sqrt[3]{\frac{24 * \sqrt{\pi}}{n}}
    
        The binwidth is proportional to the standard deviation of the
        data and inversely proportional to cube root of ``x.size``. Can
        be too conservative for small datasets, but is quite good for
        large datasets. The standard deviation is not very robust to
        outliers. Values are very similar to the Freedman-Diaconis
        estimator in the absence of outliers.
    
    'Rice'
        .. math:: n_h = 2n^{1/3}
    
        The number of bins is only proportional to cube root of
        ``a.size``. It tends to overestimate the number of bins and it
        does not take into account data variability.
    
    'Sturges'
        .. math:: n_h = \log _{2}n+1
    
        The number of bins is the base 2 log of ``a.size``.  This
        estimator assumes normality of data and is too conservative for
        larger, non-normal datasets. This is the default method in R's
        ``hist`` method.
    
    'Doane'
        .. math:: n_h = 1 + \log_{2}(n) +
                        \log_{2}(1 + \frac{|g_1|}{\sigma_{g_1})}
    
            g_1 = mean[(\frac{x - \mu}{\sigma})^3]
    
            \sigma_{g_1} = \sqrt{\frac{6(n - 2)}{(n + 1)(n + 3)}}
    
        An improved version of Sturges' formula that produces better
        estimates for non-normal datasets. This estimator attempts to
        account for the skew of the data.
    
    'Sqrt'
        .. math:: n_h = \sqrt n
        The simplest and fastest estimator. Only takes into account the
        data size.
    
    Examples
    --------
    >>> np.histogram([1, 2, 1], bins=[0, 1, 2, 3])
    (array([0, 2, 1]), array([0, 1, 2, 3]))
    >>> np.histogram(np.arange(4), bins=np.arange(5), density=True)
    (array([ 0.25,  0.25,  0.25,  0.25]), array([0, 1, 2, 3, 4]))
    >>> np.histogram([[1, 2, 1], [1, 0, 1]], bins=[0,1,2,3])
    (array([1, 4, 1]), array([0, 1, 2, 3]))
    
    >>> a = np.arange(5)
    >>> hist, bin_edges = np.histogram(a, density=True)
    >>> hist
    array([ 0.5,  0. ,  0.5,  0. ,  0. ,  0.5,  0. ,  0.5,  0. ,  0.5])
    >>> hist.sum()
    2.4999999999999996
    >>> np.sum(hist*np.diff(bin_edges))
    1.0
    
    .. versionadded:: 1.11.0
    
    Automated Bin Selection Methods example, using 2 peak random data
    with 2000 points:
    
    >>> import matplotlib.pyplot as plt
    >>> rng = np.random.RandomState(10)  # deterministic random data
    >>> a = np.hstack((rng.normal(size=1000),
    ...                rng.normal(loc=5, scale=2, size=1000)))
    >>> plt.hist(a, bins='auto')  # plt.hist passes it's arguments to np.histogram
    >>> plt.title("Histogram with 'auto' bins")
    >>> plt.show()


In [46]:
z>=6.96677249e-01 and z<1.39829586


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-46-fd2ee321d7c4> in <module>()
----> 1 z>=6.96677249e-01 and z<1.39829586

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

In [51]:
np.argwhere(z>=6.96677249e-01)


Out[51]:
array([[     0],
       [     1],
       [     2],
       ..., 
       [297298],
       [297299],
       [297300]])

In [52]:
z11=np.argwhere(z<1.39829586)
z12=np.argwhere(z>=6.96677249e-01)

In [62]:
len(z11)


Out[62]:
62691

In [64]:
z11v=z[z11]

In [65]:
z11v


Out[65]:
array([[ 1.36035752],
       [ 0.67536956],
       [ 1.13454401],
       ..., 
       [ 0.78650928],
       [ 0.83587337],
       [ 1.19725287]], dtype=float32)

In [66]:
len(z11v)


Out[66]:
62691

In [70]:
z1ind=np.argwhere(z11v>=6.96677249e-01)
z1=z11v[z1ind]

In [71]:
len(z[z1ind])


Out[71]:
48309

In [72]:
z1


Out[72]:
array([[[ 1.36035752],
        [ 1.36035752]],

       [[ 1.13454401],
        [ 1.36035752]],

       [[ 0.8353247 ],
        [ 1.36035752]],

       ..., 
       [[ 0.78650928],
        [ 1.36035752]],

       [[ 0.83587337],
        [ 1.36035752]],

       [[ 1.19725287],
        [ 1.36035752]]], dtype=float32)

In [41]:
plt.plot(np.histogram(z)[1][1:],np.histogram(z)[0])


Out[41]:
[<matplotlib.lines.Line2D at 0x13781ad90>]

In [42]:
plt.hist(z)


Out[42]:
(array([  1.43820000e+04,   4.83090000e+04,   4.26500000e+04,
          1.39641000e+05,   4.29450000e+04,   7.69800000e+03,
          1.11600000e+03,   2.71000000e+02,   1.75000000e+02,
          1.14000000e+02]),
 array([ -4.94136522e-03,   6.96677249e-01,   1.39829586e+00,
          2.09991448e+00,   2.80153309e+00,   3.50315170e+00,
          4.20477032e+00,   4.90638893e+00,   5.60800755e+00,
          6.30962616e+00,   7.01124477e+00]),
 <a list of 10 Patch objects>)

In [ ]: