Where is the mass affected? plot_calcs: used for the overall stellar mass function -will return bin_centers -> make these the specific ones to go with each bin that actually has something hist_calcs: definitely affected; but where to change them? being fed mass_dat... mass_dat is going into plot_calcs dictionary values and error are zero Should be okay: bin_func: should be okay. median distance to nearest neighbor shouldn't be calculated if the bin is empty... Notes: Need a definitive bin_centers variable for plotting the medians, among other things. neigh_dict and nn_dict are the same thing. Need to combine/change variables at some point


In [1]:
from __future__ import division, absolute_import

import astropy.stats
import glob
import math
import matplotlib.pyplot as plt 
from matplotlib import ticker
from matplotlib.ticker import FormatStrFormatter
import numpy as np 
import os
import pandas as pd
from scipy import integrate,optimize,spatial


C:\Users\Hannah\Anaconda2\lib\site-packages\matplotlib\__init__.py:508: UserWarning: matplotlibrc text.usetex can not be used unless ghostscript-7.07 or later is installed on your system
  'installed on your system') % gs_req)

In [3]:
__author__     =['Victor Calderon']
__copyright__  =["Copyright 2016 Victor Calderon, Index function"]
__email__      =['victor.calderon@vanderbilt.edu']
__maintainer__ =['Victor Calderon']

def Index(directory, datatype):
    """
    Indexes the files in a directory `directory' with a
    specific data type.

    Parameters
    ----------
    directory: str
            Absolute path to the folder that is indexed.

    datatype: str
            Data type of the files to be indexed in the folder.

    Returns
    -------
    file_array: array_like 
            np.array of indexed files in the folder 'directory' 
            with specific datatype.

    Examples
    --------
    >>> Index('~/data', '.txt')
    >>> array(['A.txt', 'Z'.txt', ...])
    """
    assert(os.path.exists(directory))
    files = np.array(glob.glob('{0}/*{1}'.format(directory, datatype)))

    return files

def myceil(x, base=10):
    """
    Returns the upper-bound integer of 'x' in base 'base'.

    Parameters
    ----------
    x: float
        number to be approximated to closest number to 'base'

    base: float
        base used to calculate the closest 'largest' number

    Returns
    -------
    n_high: float
        Closest float number to 'x', i.e. upper-bound float.

    Example
    -------
    >>>> myceil(12,10)
      20
    >>>>
    >>>> myceil(12.05, 0.1)
     12.10000 
    """
    n_high = float(base*math.ceil(float(x)/base))

    return n_high

###############################################################################    

def myfloor(x, base=10):
    """
    Returns the lower-bound integer of 'x' in base 'base'

    Parameters
    ----------
    x: float
        number to be approximated to closest number of 'base'

    base: float
        base used to calculate the closest 'smallest' number

    Returns
    -------
    n_low: float
        Closest float number to 'x', i.e. lower-bound float.

    Example
    -------
    >>>> myfloor(12, 5)
    >>>> 10
    """
    n_low = float(base*math.floor(float(x)/base))

    return n_low

###############################################################################

def Bins_array_create(arr, base=10):
    """
    Generates array between [arr.min(), arr.max()] in steps of `base`.

    Parameters
    ----------
    arr: array_like, Shape (N,...), One-dimensional
        Array of numerical elements

    base: float, optional (default=10)
        Interval between bins

    Returns
    -------
    bins_arr: array_like
        Array of bin edges for given arr

    """
    base = float(base)
    arr  = np.array(arr)
    assert(arr.ndim==1)
    arr_min  = myfloor(arr.min(), base=base)
    arr_max  = myceil( arr.max(), base=base)
    bins_arr = np.arange(arr_min, arr_max+0.5*base, base)

    return bins_arr

In [4]:
def sph_to_cart(ra,dec,cz):
    """
    Converts spherical coordinates to Cartesian coordinates.

    Parameters
    ----------
    ra: array-like
        right-ascension of galaxies in degrees
    dec: array-like
        declination of galaxies in degrees
    cz: array-like
        velocity of galaxies in km/s

    Returns
    -------
    coords: array-like, shape = N by 3
        x, y, and z coordinates
    """
    cz_dist = cz/70. #converts velocity into distance
    x_arr   = cz_dist*np.cos(np.radians(ra))*np.cos(np.radians(dec))
    y_arr   = cz_dist*np.sin(np.radians(ra))*np.cos(np.radians(dec))
    z_arr   = cz_dist*np.sin(np.radians(dec))
    coords  = np.column_stack((x_arr,y_arr,z_arr))

    return coords

############################################################################

def calc_dens(n_val,r_val):
    """
    Returns densities of spheres with radius being the distance to the 
        nth nearest neighbor.

    Parameters
    ----------
    n_val = integer
        The 'N' from Nth nearest neighbor
    r_val = array-like
        An array with the distances to the Nth nearest neighbor for
        each galaxy

    Returns
    -------
    dens: array-like
        An array with the densities of the spheres created with radii
        to the Nth nearest neighbor.
    """
    dens = np.array([(3.*(n_val+1)/(4.*np.pi*r_val[hh]**3)) \
                     for hh in range(len(r_val))])

    return dens

In [5]:
def plot_calcs(mass,bins,dlogM):
    """
    Returns values for plotting the stellar mass function and 
        mass ratios

    Parameters
    ----------
    mass: array-like
        A 1D array with mass values, assumed to be in order
    bins: array=like
        A 1D array with the values which will be used as the bin edges
        by the histogram function
    dlogM: float-like
        The log difference between bin edges

    Returns
    -------
    bin_centers: array-like
        An array with the medians mass values of the mass bins
    mass-freq: array-like
        Contains the number density values of each mass bin
    ratio_dict: dictionary-like
        A dictionary with three keys, corresponding to the divisors
        2,4, and 10 (as the percentile cuts are based on these 
        divisions). Each key has the density-cut, mass ratios for
        that specific cut (50/50 for 2; 25/75 for 4; 10/90 for 10).
    """

    mass_counts, edges = np.histogram(mass,bins)
    bin_centers        = 0.5*(edges[:-1]+edges[1:])

    mass_freq  = mass_counts/float(len(mass))/dlogM
    
#     non_zero   = (mass_freq!=0)

    ratio_dict = {}
    frac_val   = [2,4,10]

    yerr = []
    bin_centers_fin = []

    for ii in frac_val:
        ratio_dict[ii] = {}
        frac_data      = int(len(mass)/ii)
        
        # Calculations for the lower density cut
        frac_mass      = mass[0:frac_data]
        counts, edges  = np.histogram(frac_mass,bins)

        # Calculations for the higher density cut
        frac_mass_2       = mass[-frac_data:]
        counts_2, edges_2 = np.histogram(frac_mass_2,bins)

        # Ratio determination
        ratio_counts   = (1.*counts_2)/(1.*counts)
        
        non_zero = np.isfinite(ratio_counts)

        ratio_counts_1 = ratio_counts[non_zero]
        
#         print 'len ratio_counts: {0}'.format(len(ratio_counts_1))
        
        ratio_dict[ii] = ratio_counts_1
        
        temp_yerr = (counts_2*1.)/(counts*1.)*\
            np.sqrt(1./counts + 1./counts_2)
            
        temp_yerr_1 = temp_yerr[non_zero]
        
#         print 'len yerr: {0}'.format(len(temp_yerr_1))

        yerr.append(temp_yerr_1)
        
        bin_centers_1 = bin_centers[non_zero]
        
#         print 'len bin_cens: {0}'.format(len(bin_centers_1))
        
        bin_centers_fin.append(bin_centers_1)
        

    mass_freq_list     = [[] for xx in xrange(2)]
    mass_freq_list[0]  = mass_freq
    mass_freq_list[1]  = np.sqrt(mass_counts)/float(len(mass))/dlogM
    mass_freq          = np.array(mass_freq_list)

    ratio_dict_list    = [[] for xx in range(2)]
    ratio_dict_list[0] = ratio_dict
    ratio_dict_list[1] = yerr
    ratio_dict         = ratio_dict_list

    return bin_centers, mass_freq, ratio_dict, bin_centers_fin

In [6]:
def bin_func(mass_dist,bins,kk,bootstrap=False):
    """
    Returns median distance to Nth nearest neighbor

    Parameters
    ----------
    mass_dist: array-like
        An array with mass values in at index 0 (when transformed) and distance 
        to the Nth nearest neighbor in the others
        Example: 6239 by 7
            Has mass values and distances to 6 Nth nearest neighbors  
    bins: array=like
        A 1D array with the values which will be used as the bin edges     
    kk: integer-like
        The index of mass_dist (transformed) where the appropriate distance 
        array may be found

    Optional
    --------
    bootstrap == True
        Calculates the bootstrap errors associated with each median distance 
        value. Creates an array housing arrays containing the actual distance 
        values associated with every galaxy in a specific bin. Bootstrap error
        is then performed using astropy, and upper and lower one sigma values 
        are found for each median value.  These are added to a list with the 
        median distances, and then converted to an array and returned in place 
        of just 'medians.'

    Returns
    -------
    medians: array-like
        An array with the median distance to the Nth nearest neighbor from 
        all the galaxies in each of the bins
    """
    
    edges        = bins
    bin_centers  = 0.5*(edges[:-1]+edges[1:])

    # print 'length bins:'
    # print len(bins)

    digitized    = np.digitize(mass_dist.T[0],edges)
    digitized   -= int(1)

    bin_nums          = np.unique(digitized)
    
    bin_nums_list = list(bin_nums)

    if (len(bin_centers)) in bin_nums_list:
        bin_nums_list.remove(len(bin_centers))
        
    bin_nums = np.array(bin_nums_list)
    
#     print bin_nums

    non_zero_bins = []
    for ii in bin_nums:
        if (len(mass_dist.T[kk][digitized==ii]) != 0):
            non_zero_bins.append(bin_centers[ii])
#     print len(non_zero_bins)
    
    for ii in bin_nums:

        if len(mass_dist.T[kk][digitized==ii]) == 0:
#             temp_list = list(mass_dist.T[kk]\
#                                              [digitized==ii])
#             temp_list.append(np.nan)
            mass_dist.T[kk][digitized==ii] = np.nan

    # print bin_nums
    # print len(bin_nums)
    
    medians  = np.array([np.nanmedian(mass_dist.T[kk][digitized==ii]) \
                for ii in bin_nums])

    # print len(medians)

    if bootstrap == True:
        dist_in_bin    = np.array([(mass_dist.T[kk][digitized==ii]) \
                for ii in bin_nums])
        for vv in range(len(dist_in_bin)):
            if len(dist_in_bin[vv]) == 0:
#                 dist_in_bin_list = list(dist_in_bin[vv])
#                 dist_in_bin[vv] = np.zeros(len(dist_in_bin[0]))
                dist_in_bin[vv] = np.nan
        low_err_test   = np.array([np.percentile(astropy.stats.bootstrap\
                        (dist_in_bin[vv],bootnum=1000,bootfunc=np.median),16) \
                        for vv in range(len(dist_in_bin))])
        high_err_test  = np.array([np.percentile(astropy.stats.bootstrap\
                        (dist_in_bin[vv],bootnum=1000,bootfunc=np.median),84) \
                        for vv in range(len(dist_in_bin))])

        med_list    = [[] for yy in range(4)]
        med_list[0] = medians
        med_list[1] = low_err_test
        med_list[2] = high_err_test
        medians     = np.array(med_list)
        
#     print len(medians)
#     print len(non_zero_bins)

    return medians, np.array(non_zero_bins)

In [7]:
def hist_calcs(mass,bins,dlogM):
    """
    Returns dictionaries with the counts for the upper
        and lower density portions; calculates the 
        three different percentile cuts for each mass
        array given
    
    Parameters
    ----------
    mass: array-like
        A 1D array with log stellar mass values, assumed
        to be an order which corresponds to the ascending 
        densities; (necessary, as the index cuts are based 
        on this)
    bins: array-like
        A 1D array with the values which will be used as the bin edges   
    dlogM: float-like
        The log difference between bin edges
        
    Returns
    -------
    hist_dict_low: dictionary-like
        A dictionary with three keys (the frac vals), with arrays
        as values. The values for the lower density cut
    hist_dict_high: dictionary like
        A dictionary with three keys (the frac vals), with arrays
        as values. The values for the higher density cut
    """
    hist_dict_low  = {}
    hist_dict_high = {}
    frac_val  = np.array([2,4,10])
    frac_dict = {2:0,4:1,10:2}
    
    low_err   = [[] for xx in xrange(len(frac_val))]
    high_err  = [[] for xx in xrange(len(frac_val))]
    
    for ii in frac_val:
#         hist_dict_low[ii]  = {}
#         hist_dict_high[ii] = {}
    
        frac_data     = int(len(mass)/ii)
        
        frac_mass     = mass[0:frac_data]
        counts, edges = np.histogram(frac_mass,bins)
        low_counts    = (counts/float(len(frac_mass))/dlogM)
        
        non_zero = (low_counts!=0)
        low_counts_1 = low_counts[non_zero]
        hist_dict_low[ii]  = low_counts_1
        
        low_err = np.sqrt(counts)/len(frac_mass)/dlogM
        low_err_1 = low_err[non_zero]
        err_key = 'err_{0}'.format(ii)
        hist_dict_low[err_key] = low_err_1
        
        frac_mass_2        = mass[-frac_data:]
        counts_2, edges_2  = np.histogram(frac_mass_2,bins)
        high_counts        = (counts_2/float(len(frac_mass_2))/dlogM)
        
        non_zero = (high_counts!=0)
        high_counts_1 = high_counts[non_zero]
        hist_dict_high[ii] = high_counts_1
        
        high_err = np.sqrt(counts_2)/len(frac_mass_2)/dlogM
        high_err_1 = high_err[non_zero]
        hist_dict_high[err_key] = high_err_1
    
    return hist_dict_low, hist_dict_high

In [8]:
def mean_bin_mass(mass_dist,bins,kk):
    """
    Returns mean mass of galaxies in each bin

    Parameters
    ----------
    mass_dist: array-like
        An array with mass values in at index 0 (when transformed) 
    bins: array=like
        A 1D array with the values which will be used as the bin edges     

    Returns
    -------

    """
    edges        = bins

    digitized    = np.digitize(mass_dist.T[0],edges)
    digitized   -= int(1)
    
    bin_nums          = np.unique(digitized)
    
    for ii in bin_nums:
        if len(mass_dist.T[kk][digitized==ii]) == 0:
            mass_dist.T[kk][digitized==ii] = np.nan



    mean_mass = np.array([np.nanmean(mass_dist.T[0][digitized==ii]) \
                for ii in bin_nums])

    return mean_mass 

###note, this should use the same bin_centers as provided by the 
#median from bin_func

In [9]:
dirpath  = r"C:\Users\Hannah\Desktop\Vanderbilt_REU\Stellar_mass_env_density"
dirpath += r"\Catalogs\Resolve_plk_5001_so_mvir_scatter_ECO_Mocks_"
dirpath += r"scatter_mocks\Resolve_plk_5001_so_mvir_scatter0p1_ECO_Mocks"

usecols  = (0,1,4,8,13)
dlogM    = 0.2
neigh_dict = {1:0,2:1,3:2,5:3,10:4,20:5}

In [10]:
ECO_cats = (Index(dirpath,'.dat'))

names    = ['ra','dec','Halo_ID','cz','logMstar']

PD = [[] for ii in range(len(ECO_cats))]

for ii in range(len(ECO_cats)):
    temp_PD = (pd.read_csv(ECO_cats[ii],sep="\s+", usecols= usecols,header=None,\
                   skiprows=2,names=names))
    col_list = list(temp_PD)
    col_list[2], col_list[3], col_list[4] = col_list[3], col_list[4], col_list[2]
    temp_PD.ix[:,col_list]
    PD[ii] = temp_PD

PD_comp_1  = [(PD[ii][PD[ii].logMstar >= 9.1]) for ii in range(len(ECO_cats))]
PD_comp  = [(PD_comp_1[ii][PD_comp_1[ii].logMstar <=11.77]) for ii in range(len(ECO_cats))]

[(PD_comp[ii].reset_index(drop=True,inplace=True)) for ii in range(len(ECO_cats))]


Out[10]:
[None, None, None, None, None, None, None, None]

In [11]:
min_max_mass_arr = []

for ii in range(len(PD_comp)):
    min_max_mass_arr.append(max(PD_comp[ii].logMstar))
    min_max_mass_arr.append(min(PD_comp[ii].logMstar))

min_max_mass_arr = np.array(min_max_mass_arr)

bins = Bins_array_create(min_max_mass_arr,dlogM)
bins+= 0.1
bins_list = list(bins)
for ii in bins:
    if ii > 11.77:
        bins_list.remove(ii)

bins = np.array(bins_list)

num_of_bins = int(len(bins) - 1) 

ra_arr  = np.array([(PD_comp[ii].ra) \
    for ii in range(len(PD_comp))])

dec_arr  = np.array([(PD_comp[ii].dec) \
    for ii in range(len(PD_comp))])

cz_arr  = np.array([(PD_comp[ii].cz) \
    for ii in range(len(PD_comp))])

mass_arr  = np.array([(PD_comp[ii].logMstar) \
    for ii in range(len(PD_comp))])

halo_id_arr  = np.array([(PD_comp[ii].Halo_ID) \
    for ii in range(len(PD_comp))])


coords_test = np.array([sph_to_cart(ra_arr[vv],dec_arr[vv],cz_arr[vv]) \
                for vv in range(len(ECO_cats))])

neigh_vals  = np.array([1,2,3,5,10,20])

nn_arr_temp = [[] for uu in xrange(len(coords_test))]
nn_arr      = [[] for xx in xrange(len(coords_test))]
nn_arr_nn   = [[] for yy in xrange(len(neigh_vals))]
nn_idx      = [[] for zz in xrange(len(coords_test))]

for vv in range(len(coords_test)):
    nn_arr_temp[vv] = spatial.cKDTree(coords_test[vv])
    nn_arr[vv] = np.array(nn_arr_temp[vv].query(coords_test[vv],21)[0])
    nn_idx[vv] = np.array(nn_arr_temp[vv].query(coords_test[vv],21)[1])
    

nn_specs       = [(np.array(nn_arr).T[ii].T[neigh_vals].T) for ii in \
                    range(len(coords_test))]
nn_mass_dist   = np.array([(np.column_stack((mass_arr[qq],nn_specs[qq]))) \
                    for qq in range(len(coords_test))])

nn_neigh_idx      = np.array([(np.array(nn_idx).T[ii].T[neigh_vals].T) for ii in \
                    range(len(coords_test))])

In [12]:
truth_vals = {}
for ii in range(len(halo_id_arr)):
    truth_vals[ii] = {}
    for jj in neigh_vals:
        halo_id_neigh = halo_id_arr[ii][nn_neigh_idx[ii].T[neigh_dict[jj]]].values
        truth_vals[ii][jj] = halo_id_neigh==halo_id_arr[ii].values

In [13]:
halo_frac = {}
for ii in range(len(mass_arr)):
    halo_frac[ii] = {}
    mass_binning = np.digitize(mass_arr[ii],bins)
    bins_to_use = list(np.unique(mass_binning))
    if (len(bins)-1) not in bins_to_use:
        bins_to_use.append(len(bins)-1)
    if len(bins) in bins_to_use:
        bins_to_use.remove(len(bins))
    for jj in neigh_vals:
        one_zero = truth_vals[ii][jj].astype(int)
        frac = []
        for xx in bins_to_use:
            truth_binning = one_zero[mass_binning==xx]
            num_in_bin = len(truth_binning)
            if num_in_bin == 0:
                num_in_bin = np.nan
            num_same_halo = np.count_nonzero(truth_binning==1)
            frac.append(num_same_halo/(1.*num_in_bin))
        halo_frac[ii][jj] = frac

In [14]:
nn_dict   = {1:0,2:1,3:2,5:3,10:4,20:5}

mean_mock_halo_frac = {}

for ii in neigh_vals:
    for jj in range(len(halo_frac)):
        bin_str = '{0}'.format(ii)
        oo_arr = halo_frac[jj][ii]
        n_o_elem = len(oo_arr)
        if jj == 0:
            oo_tot = np.zeros((n_o_elem,1))
        oo_tot = np.insert(oo_tot,len(oo_tot.T),oo_arr,1)
    oo_tot = np.array(np.delete(oo_tot,0,axis=1))
    oo_tot_mean = [np.nanmean(oo_tot[uu]) for uu in xrange(len(oo_tot))]
    oo_tot_std  = [np.nanstd(oo_tot[uu])/np.sqrt(len(halo_frac)) for uu in xrange(len(oo_tot))]
    mean_mock_halo_frac[bin_str] = [oo_tot_mean,oo_tot_std]

In [15]:
# nn_dist    = {}
nn_dens    = {}
mass_dat   = {}
ratio_info = {}
bin_cens_diff = {}

mass_freq  = [[] for xx in xrange(len(coords_test))]

for ii in range(len(coords_test)):
#     nn_dist[ii]    = {}
    nn_dens[ii]    = {}
    mass_dat[ii]   = {}
    ratio_info[ii] = {}
    bin_cens_diff[ii] = {}

#     nn_dist[ii]['mass'] = nn_mass_dist[ii].T[0]

    for jj in range(len(neigh_vals)):
#         nn_dist[ii][(neigh_vals[jj])]  = np.array(nn_mass_dist[ii].T\
#                                             [range(1,len(neigh_vals)+1)[jj]])
        nn_dens[ii][(neigh_vals[jj])]  = np.column_stack((nn_mass_dist[ii].T\
                                            [0],calc_dens(neigh_vals[jj],\
                                            nn_mass_dist[ii].T[range(1,len\
                                                (neigh_vals)+1)[jj]])))

        idx = np.array([nn_dens[ii][neigh_vals[jj]].T[1].argsort()])
        mass_dat[ii][(neigh_vals[jj])] = (nn_dens[ii][neigh_vals[jj]]\
                                            [idx].T[0])

        bin_centers, mass_freq[ii], ratio_info[ii][neigh_vals[jj]],bin_cens_diff[ii][neigh_vals[jj]] = \
                            plot_calcs(mass_dat[ii][neigh_vals[jj]],bins,dlogM)

all_mock_meds = [[] for xx in range(len(nn_mass_dist))]
mock_meds_bins = [[] for xx in range(len(nn_mass_dist))]
all_mock_mass_means = [[] for xx in range(len(nn_mass_dist))]

for vv in range(len(nn_mass_dist)):
    for jj in range(len(nn_mass_dist[vv].T)-1):
        for vv in range(len(nn_mass_dist)):
            all_mock_meds[vv],mock_meds_bins[vv] = (bin_func(nn_mass_dist[vv],bins,(jj+1)))
            all_mock_mass_means[vv] = (mean_bin_mass(nn_mass_dist[vv],bins,(jj+1))) 

    
# med_plot_arr = [([[] for yy in xrange(len(nn_mass_dist))]) \
#                                             for xx in xrange(len(neigh_vals))]

# for ii in range(len(neigh_vals)):
#     for jj in range(len(nn_mass_dist)):
#         med_plot_arr[ii][jj] = all_mock_meds[jj][ii]    

# for ii in range(len(neigh_vals)):
#     for jj in range(len(nn_mass_dist)):
#         print len(all_mock_meds[jj][ii])

# mass_freq_plot  = (np.array(mass_freq))
# max_lim = [[] for xx in range(len(mass_freq_plot.T))]
# min_lim = [[] for xx in range(len(mass_freq_plot.T))]
# for jj in range(len(mass_freq_plot.T)):
#     max_lim[jj] = max(mass_freq_plot.T[jj])
#     min_lim[jj] = min(mass_freq_plot.T[jj])

In [16]:
bins_curve_fit = bins.copy()
global bins_curve_fit

In [17]:
eco_path  = r"C:\Users\Hannah\Desktop\Vanderbilt_REU\Stellar_mass_env_density"
eco_path += r"\Catalogs\ECO_true"
eco_cols  = np.array([0,1,2,4])

In [18]:
ECO_true = (Index(eco_path,'.txt'))
names    = ['ra','dec','cz','logMstar']
PD_eco   = pd.read_csv(ECO_true[0],sep="\s+", usecols=(eco_cols),header=None,\
                skiprows=1,names=names)
eco_comp = PD_eco[PD_eco.logMstar >= 9.1]

ra_eco   = (np.array(eco_comp)).T[0]
dec_eco  = (np.array(eco_comp)).T[1] 
cz_eco   = (np.array(eco_comp)).T[2] 
mass_eco = (np.array(eco_comp)).T[3]

coords_eco        = sph_to_cart(ra_eco,dec_eco,cz_eco)
eco_neighbor_tree = spatial.cKDTree(coords_eco)
eco_tree_dist     = np.array(eco_neighbor_tree.query(coords_eco,\
                    (neigh_vals[-1]+1))[0])

eco_mass_dist = np.column_stack((mass_eco,eco_tree_dist.T[neigh_vals].T))
##range 1,7 because of the six nearest neighbors (and fact that 0 is mass)
##the jj is there to specify which index in the [1,6] array
eco_dens = ([calc_dens(neigh_vals[jj],\
            (eco_mass_dist.T[range(1,7)[jj]])) for jj in range\
            (len(neigh_vals))])

eco_mass_dens = [(np.column_stack((mass_eco,eco_dens[ii]))) for ii in \
                range(len(neigh_vals))]
eco_idx  = [(eco_mass_dens[jj].T[1].argsort()) for jj in \
            range(len(neigh_vals))]
eco_mass_dat  = [(eco_mass_dens[jj][eco_idx[jj]].T[0]) for jj in \
                range(len(neigh_vals))]

eco_ratio_info    = [[] for xx in xrange(len(eco_mass_dat))]
eco_final_bins    = [[] for xx in xrange(len(eco_mass_dat))]


for qq in range(len(eco_mass_dat)):
    bin_centers, eco_freq, eco_ratio_info[qq],eco_final_bins[qq] = plot_calcs(eco_mass_dat[qq],\
                                    bins,dlogM)

eco_medians   = [[] for xx in xrange(len(eco_mass_dat))]    
eco_med_bins   = [[] for xx in xrange(len(eco_mass_dat))]    
eco_mass_means   = [[] for xx in xrange(len(eco_mass_dat))] 

for jj in (range(len(eco_mass_dat))):
    eco_medians[jj],eco_med_bins[jj] = np.array(bin_func(eco_mass_dist,bins,(jj+1),\
        bootstrap=True))
    eco_mass_means[jj] = (mean_bin_mass(eco_mass_dist,bins,(jj+1)))

In [19]:
hist_low_info  = {}
hist_high_info = {}

for ii in xrange(len(coords_test)):
    hist_low_info[ii]  = {}
    hist_high_info[ii] = {}
    
    for jj in range(len(neigh_vals)):
        hist_low_info[ii][neigh_vals[jj]],hist_high_info[ii][neigh_vals[jj]] \
        = hist_calcs(mass_dat[ii][neigh_vals[jj]],bins,dlogM)
        
frac_vals     = [2,4,10]
hist_low_arr  = [[[] for yy in xrange(len(nn_mass_dist))] for xx in \
    xrange(len(neigh_vals))]
hist_high_arr = [[[] for yy in xrange(len(nn_mass_dist))] for xx in \
    xrange(len(neigh_vals))]

for ii in range(len(neigh_vals)):
    for jj in range(len(nn_mass_dist)):
        hist_low_arr[ii][jj]  = (hist_low_info[jj][neigh_vals[ii]])
        hist_high_arr[ii][jj] = (hist_high_info[jj][neigh_vals[ii]])
        
        
#         plot_low_hist  = [[[[] for yy in xrange(len(nn_mass_dist))] \
#                          for zz in xrange(len(frac_vals))] for xx in \
#                          xrange(len(hist_low_arr))]
        
#         plot_high_hist = [[[[] for yy in xrange(len(nn_mass_dist))] \
#                  for zz in xrange(len(frac_vals))] for xx in \
#                  xrange(len(hist_high_arr))]

# for jj in range(len(nn_mass_dist)):
#     for hh in range(len(frac_vals)):
#         for ii in range(len(neigh_vals)):
#             plot_low_hist[ii][hh][jj]  = hist_low_arr[ii][jj][frac_vals[hh]]        
#             plot_high_hist[ii][hh][jj] = hist_high_arr[ii][jj][frac_vals[hh]]

In [20]:
eco_low  = {}
eco_high = {}
for jj in range(len(neigh_vals)):
    eco_low[neigh_vals[jj]]  = {}
    eco_high[neigh_vals[jj]] = {}
    eco_low[neigh_vals[jj]], eco_high[neigh_vals[jj]] = hist_calcs\
    (eco_mass_dat[jj],bins,dlogM)

In [21]:
def mean_perc_mass(mass,bins):
    """
    Returns mean mass of galaxies in each bin

    Parameters
    ----------
    mass_dist: array-like
        An array with mass values in at index 0 (when transformed) 
    bins: array=like
        A 1D array with the values which will be used as the bin edges     

    Returns
    -------

    """
    edges        = bins

    digitized    = np.digitize(mass,edges)
    digitized   -= int(1)
    
    bin_nums          = np.unique(digitized)
    
#     bin_nums_list = list(bin_nums)
#     if len(bin_nums) in bin_nums_list:
#         bin_nums_list.remove(len(bin_nums))
    
#     bin_nums = np.array(bin_nums_list)
    
#     for ii in bin_nums:
#         if len(mass[digitized==ii]) == 0:
#             mass[digitized==ii] = np.nan



    mean_mass = np.array([np.nanmean(mass[digitized==ii])\
                    for ii in bin_nums])

    return mean_mass

In [22]:
def perc_calcs(mass,bins,dlogM):
    mass_counts, edges = np.histogram(mass,bins)
    mass_freq          = mass_counts/float(len(mass))/dlogM
    
    bin_centers        = 0.5*(edges[:-1]+edges[1:])
    
    non_zero = (mass_freq!=0)
    
    mass_freq_1 = mass_freq[non_zero]
    
    smf_err            = np.sqrt(mass_counts)/float(len(mass))/dlogM
    
    smf_err_1   = smf_err[non_zero] 
    
    bin_centers_1 = bin_centers[non_zero]
    
    mean_mass = mean_perc_mass(mass,bins)
    
#     mean_mass_1 = mean_mass[non_zero]
    
#     print 'set'
#     print len(bin_centers_1)
#     print len(mean_mass)

    return mass_freq_1, smf_err_1, bin_centers_1, mean_mass

In [23]:
def quartiles(mass):
    dec_val     =  int(len(mass)/4)
    res_list      =  [[] for bb in range(4)]

    for aa in range(0,4):
        if aa == 3:
            res_list[aa] = mass[aa*dec_val:]
        else:
            res_list[aa] = mass[aa*dec_val:(aa+1)*dec_val]

    return res_list

In [24]:
def deciles(mass):
    dec_val     =  int(len(mass)/10)
    res_list      =  [[] for bb in range(10)]

    for aa in range(0,10):
        if aa == 9:
            res_list[aa] = mass[aa*dec_val:]
        else:
            res_list[aa] = mass[aa*dec_val:(aa+1)*dec_val]

    return res_list

In [25]:
def schechter_real_func(mean_of_mass_bin,phi_star,alpha,Mstar):
    """
    
    mean_of_mass_bin: array-like
        Unlogged x-values
    phi-star: float-like
        Normalization value
    alpha: float-like
        Low-mass end slope
    Mstar: float-like
        Unlogged value where function switches from power-law to exponential
    
    """
#     M_over_mstar = (10**mean_of_mass_bin)/Mstar
    M_over_mstar = (mean_of_mass_bin)/Mstar
    res_arr    = phi_star/Mstar * M_over_mstar**(alpha) * \
                        np.exp(- M_over_mstar)

    return res_arr

In [26]:
def schech_integral(edge_1,edge_2,phi_star,alpha,Mstar):
    bin_integral = (integrate.quad(schechter_real_func,edge_1,edge_2,args=(phi_star,alpha,Mstar))[0])
#     tot_integral = (integrate.quad(schechter_real_func,9.1,11.7,args=(phi_star,alpha,Mstar)))[0]
# #     
#     result = bin_integral/tot_integral/0.2
    
    return bin_integral

In [27]:
def schech_step_3(xdata,phi_star,alpha,Mstar):
    """
    xdata: array-like
        Unlogged x-values
    Mstar:
        unlogged
    """
    test_int = []
    for ii in range(len(xdata)):
        test_int.append((schech_integral(10**bins_curve_fit[ii],10**bins_curve_fit[ii+1],phi_star,alpha,Mstar)))
    return test_int

In [28]:
def find_params(bin_int,mean_mass,count_err):
    """
    Parameters
    ----------
    bin_int: array-like
        Integral (number of counts) in each bin of width dlogM
    mean_mass: array-like
        Logged values (?)

    Returns
    -------
    opt_v: array-like
        Array with three values: phi_star, alpha, and M_star
    res_arr: array-like
        Array with two values: alpha and log_M_star


    """
    xdata = 10**mean_mass
#     xdata = mean_mass
    p0    = (1,-1.1,10**10.64)
    opt_v,est_cov = optimize.curve_fit(schech_step_3,xdata,\
                            bin_int,p0=p0,sigma=count_err,check_finite=True,method='trf')
    alpha   = opt_v[1]
    log_m_star    = np.log10(opt_v[2])
    
    res_arr = np.array([alpha,log_m_star])
    
#     perr = np.sqrt(np.diag(est_cov))
    
    even_val = schech_step_3(mean_mass,opt_v[0],opt_v[1],opt_v[2])
    
    chi_sq = (bin_int - even_val)/count_err
    
    chi_sq_ret = np.sum(chi_sq**2)

#     return opt_v, res,arr, chi_sq_ret
    return res_arr, chi_sq_ret

In [29]:
eco_res_arr, chi_squ = find_params(eco_freq[0],eco_mass_means[0][:-1],eco_freq[1])

In [30]:
eco_dec = {}
for cc in range(len(eco_mass_dat)):
    eco_dec[neigh_vals[cc]] = deciles(eco_mass_dat[cc])
    
eco_dec_smf = {}
eco_dec_err = {}
eco_dec_bin = {}
eco_dec_mean = {}

for ss in neigh_vals:
    eco_dec_smf[ss] = {}
    eco_dec_err[ss] = {}
    eco_dec_bin[ss] = {}
    eco_dec_mean[ss] = {}
    for tt in range(len(eco_dec[ss])):
        eco_dec_smf[ss][tt], eco_dec_err[ss][tt], eco_dec_bin[ss][tt], eco_dec_mean[ss][tt] \
        = perc_calcs(eco_dec[ss][tt],bins,dlogM)
        
        
eco_dec_alpha    = {}
eco_dec_logMstar = {}
eco_dec_chi = {}

for oo in neigh_vals:
    eco_dec_alpha[oo]    = []
    eco_dec_logMstar[oo] = []
    eco_dec_chi[oo] = []
    for pp in range(len(eco_dec[oo])):
        idx= (len(eco_dec_mean[oo][pp])-len(eco_dec_smf[oo][pp]))
#             print avg_test
#         print '{0}_{1}'.format(oo,pp)
#         print len(eco_dec_smf[oo][pp])
#         print len(eco_dec_err[oo][pp])
#         print len(eco_dec_bin[oo][pp])
#         print len(eco_dec_mean[oo][pp])
#         print len(eco_dec_mean[oo][pp])
#         print len(eco_dec_smf[oo][pp])
#         print idx
        if idx == 0:
            temp_res_arr, temp_chi = find_params(eco_dec_smf[oo][pp],eco_dec_bin[oo][pp],eco_dec_err[oo][pp])
        else:
#             temp_res_arr, temp_chi = find_params(eco_dec_smf[oo][pp],eco_dec_mean[oo][pp][:-idx],eco_dec_err[oo][pp])
            temp_res_arr, temp_chi = find_params(eco_dec_smf[oo][pp],eco_dec_bin[oo][pp],eco_dec_err[oo][pp])
        eco_dec_alpha[oo].append(temp_res_arr[0])
        eco_dec_logMstar[oo].append(temp_res_arr[1])
        eco_dec_chi[oo].append(temp_chi)

dec_x = range(1,11)

In [31]:
eco_quarts = {}
for cc in range(len(eco_mass_dat)):
    eco_quarts[neigh_vals[cc]] = quartiles(eco_mass_dat[cc])

eco_quarts_smf = {}
eco_quarts_err = {}
eco_quarts_bin = {}
eco_quarts_mean = {}

for ss in neigh_vals:
    eco_quarts_smf[ss] = {}
    eco_quarts_err[ss] = {}
    eco_quarts_bin[ss] = {}
    eco_quarts_mean[ss] = {}
    for tt in range(len(eco_quarts[ss])):
        eco_quarts_smf[ss][tt], eco_quarts_err[ss][tt], eco_quarts_bin[ss][tt], eco_quarts_mean[ss][tt]\
        = perc_calcs(eco_quarts[ss][tt],bins,dlogM)    

eco_quarts_alpha    = {}
eco_quarts_logMstar = {}
eco_quarts_chi = {}

for oo in neigh_vals:
    eco_quarts_alpha[oo]    = []
    eco_quarts_logMstar[oo] = []
    eco_quarts_chi[oo] = []
    for pp in range(len(eco_quarts[oo])):
        idx= (len(eco_quarts_mean[oo][pp])-len(eco_quarts_smf[oo][pp]))
#         print idx
        if idx == 0:
            temp_res_arr, temp_chi = find_params(eco_quarts_smf[oo][pp],eco_quarts_bin[oo][pp],eco_quarts_err[oo][pp])
        else:
            temp_res_arr, temp_chi = find_params(eco_quarts_smf[oo][pp],eco_quarts_bin[oo][pp],eco_quarts_err[oo][pp])
        eco_quarts_alpha[oo].append(temp_res_arr[0])
        eco_quarts_logMstar[oo].append(temp_res_arr[1])
        eco_quarts_chi[oo].append(temp_chi)

quarts_x = range(1,5)

In [37]:
def quart_finder(mass,bins,dlogM,neigh_vals):
    quarts = {}
    for ii in neigh_vals:
        quarts[ii] = quartiles(mass[ii])

    quarts_smf = {}
    quarts_err = {}
    quarts_bin = {}
    quarts_mean = {}

    for ss in neigh_vals:
        quarts_smf[ss] = {}
        quarts_err[ss] = {}
        quarts_bin[ss] = {}
        quarts_mean[ss] = {}
        for tt in range(len(quarts[ss])):
            quarts_smf[ss][tt], quarts_err[ss][tt], quarts_bin[ss][tt], quarts_mean[ss][tt] = perc_calcs(quarts[ss][tt],bins,dlogM)    


    quarts_alpha    = {}
    quarts_logMstar = {}
    quarts_chi = {}

    for oo in neigh_vals:
        quarts_alpha[oo]    = []
        quarts_logMstar[oo] = []
        quarts_chi[oo] = []
        for pp in range(len(eco_quarts[oo])):
            temp_res_arr, temp_chi = find_params(quarts_smf[oo][pp],quarts_bin[oo][pp],quarts_err[oo][pp])
            quarts_alpha[oo].append(temp_res_arr[0])
            quarts_logMstar[oo].append(temp_res_arr[1])
            quarts_chi[oo].append(temp_chi)


    return quarts_alpha, quarts_logMstar, quarts_chi

In [38]:
def dec_finder(mass,bins,dlogM,neigh_vals):
    decs = {}
    for ii in neigh_vals:
        decs[ii] = deciles(mass[ii])

    dec_smf = {}
    dec_err = {}
    dec_bin = {}
    dec_mean = {}

    for ss in neigh_vals:
        dec_smf[ss] = {}
        dec_err[ss] = {}
        dec_bin[ss] = {}
        dec_mean[ss] ={}
        for tt in range(len(decs[ss])):
            dec_smf[ss][tt], dec_err[ss][tt], dec_bin[ss][tt], dec_mean[ss][tt] = perc_calcs(decs[ss][tt],bins,dlogM)    


    dec_alpha    = {}
    dec_logMstar = {}
    dec_chi = {}

    for oo in neigh_vals:
        dec_alpha[oo]    = []
        dec_logMstar[oo] = []
        dec_chi[oo] = []
        for pp in range(len(eco_dec[oo])):
            temp_res_arr, temp_chi = find_params(dec_smf[oo][pp],dec_bin[oo][pp],dec_err[oo][pp])
            dec_alpha[oo].append(temp_res_arr[0])
            dec_logMstar[oo].append(temp_res_arr[1])
            dec_chi[oo].append(temp_chi)


    return dec_alpha, dec_logMstar, dec_chi

In [39]:
mock_quarts_alpha_dict = {}
mock_quarts_logMstar_dict = {}
mock_quarts_chi_dict = {}

for jj in range(len(mass_dat)):
    mock_quarts_alpha_dict[jj], mock_quarts_logMstar_dict[jj], mock_quarts_chi_dict[jj]  = quart_finder\
                                    (mass_dat[jj],bins,dlogM,neigh_vals)

In [40]:
mock_quarts_chi_dict


Out[40]:
{0: {1: [19.231386181982071,
   38.556471463410581,
   27.302772222102359,
   82.492796784065476],
  2: [31.171034317373163,
   54.317419068419142,
   65.043396840853646,
   44.260698585144205],
  3: [27.02625209510785,
   26.853476179873319,
   56.996542109627669,
   39.707193893845115],
  5: [36.426912958216761,
   59.955525521654643,
   64.980398908514601,
   23.458988953092405],
  10: [46.592030788643015,
   44.307454340366021,
   56.164967989120314,
   18.308512971804209],
  20: [47.636207187629722,
   24.875866176628307,
   51.208340982322667,
   13.912998011995365]},
 1: {1: [24.402263431984498,
   56.146587092267133,
   39.889355489882085,
   48.087901637511578],
  2: [25.072153261220521,
   33.756214331519011,
   99.900757848702597,
   34.192316311091894],
  3: [27.682088606429474,
   56.092454981754564,
   46.867566789380803,
   37.280113847513825],
  5: [20.632529556328382,
   45.888581644422366,
   37.226647906395144,
   35.844845826834636],
  10: [23.072032989485525,
   66.833972508899294,
   24.932736350201004,
   25.148493097223152],
  20: [26.89420917017182,
   46.16463905267122,
   47.360933069834232,
   25.47710023789195]},
 2: {1: [41.95805662617002,
   32.051815929700425,
   27.320792450944836,
   66.521231683450821],
  2: [20.28102617143265,
   44.916280126769557,
   48.526368365814072,
   40.296654107069976],
  3: [26.564606154918533,
   38.190048051495985,
   44.884828409485031,
   35.11838704254955],
  5: [20.4389233047822,
   34.312407070034482,
   59.955868591231734,
   25.628670608852126],
  10: [30.149246281558746,
   42.236173808223413,
   35.184615762672806,
   23.851593599654347],
  20: [26.768042109022929,
   39.479676540269658,
   35.461119045703477,
   22.481661616961301]},
 3: {1: [9.6754878448726931,
   64.777995937231424,
   31.65440256935004,
   125.46092002174581],
  2: [21.380794551947766,
   42.441524224770809,
   73.163596513980323,
   75.68358741917902],
  3: [25.531714935694424,
   51.343640014926414,
   72.124686745510118,
   59.693293177985836],
  5: [10.333418612473235,
   45.820552677128035,
   73.775797100894948,
   50.270950347597058],
  10: [17.759786676649586,
   59.047361571545146,
   49.219690605248381,
   40.958683012952449],
  20: [18.724601111574628,
   41.493663494938644,
   56.970586175578397,
   31.940503838748747]},
 4: {1: [99.105268793468767,
   53.886163827397112,
   70.368839490618981,
   154.66953328937797],
  2: [96.201484530654298,
   65.266463574064559,
   109.34855383234222,
   109.05609650989544],
  3: [95.308333183598506,
   62.460004954104129,
   115.66765264777062,
   85.57759018885956],
  5: [87.530116026632939,
   76.873985430682438,
   112.60586610543714,
   63.387408785417506],
  10: [81.328525069581644,
   68.429479969665138,
   64.012849961174595,
   41.946151405431145],
  20: [60.427367274065936,
   94.32512561521996,
   37.742807517357846,
   28.921045284606397]},
 5: {1: [48.956505553049126,
   66.222975912083072,
   49.94854004586697,
   129.80824819453173],
  2: [45.3112457366543,
   104.56078559096692,
   57.859130424868241,
   92.251075282991465],
  3: [59.012064152872817,
   66.814183168746922,
   75.602971751466427,
   84.846197224114235],
  5: [58.946896536246513,
   68.362382542026211,
   95.045842915923515,
   55.962155389796443],
  10: [49.830879964000069,
   52.334172250923899,
   96.718465591870185,
   42.61903865282472],
  20: [48.960373687009834,
   60.290657480650864,
   74.625455610189661,
   36.962863040286088]},
 6: {1: [30.099617800834242,
   69.493101977260409,
   35.598371822128925,
   72.66459053086875],
  2: [47.157206898656305,
   72.587011391921124,
   73.024296645144062,
   39.492223276461822],
  3: [46.884161440962636,
   85.854328332656337,
   69.264567057654574,
   27.373269910819207],
  5: [41.309373283162266,
   50.306392216568213,
   47.017421666566001,
   24.982456999093561],
  10: [39.934094777221695,
   66.474670407853438,
   56.426807328791419,
   29.0600077375273],
  20: [51.418035124487773,
   50.661345991889014,
   52.169071375940852,
   23.600125266038091]},
 7: {1: [40.692135950959234,
   57.906316450971261,
   35.651444639131775,
   78.664857774546562],
  2: [39.40660287351303,
   52.686356177216204,
   56.965122753779411,
   57.803930015336043],
  3: [42.322107565075434,
   38.163406444636493,
   61.900867703495109,
   39.024215944529921],
  5: [30.098021407675187,
   49.17323916384445,
   48.563756649307933,
   30.866261354138356],
  10: [51.271052115730619,
   40.668943846487196,
   40.007823961045268,
   34.723318570050743],
  20: [46.700715290873688,
   47.845121084905749,
   32.65714928731213,
   33.720567358089895]}}

In [41]:
mock_dec_alpha_dict = {}
mock_dec_logMstar_dict = {}
mock_dec_chi_dict = {}

for jj in range(len(mass_dat)):
    mock_dec_alpha_dict[jj], mock_dec_logMstar_dict[jj], mock_dec_chi_dict[jj] = dec_finder\
                                    (mass_dat[jj],bins,dlogM,neigh_vals)

In [42]:
mock_dec_chi_dict


Out[42]:
{0: {1: [7.8648235231647021,
   16.197346816434475,
   14.525726122345862,
   15.542820761030004,
   14.738394163783312,
   12.805945539926023,
   11.258033194728899,
   12.296918524750385,
   40.791884725233089,
   47.777148171783779],
  2: [11.190678644711864,
   12.017984674105463,
   12.816247214271806,
   16.326984822400778,
   32.111148967338572,
   28.191789454496906,
   18.301796391742648,
   16.015613555034889,
   18.971590806421851,
   54.299558374527862],
  3: [14.942112151770671,
   16.097236900834023,
   13.408115570321524,
   23.83549233268047,
   19.482561595167816,
   35.206512846796628,
   17.928304126732527,
   15.895938786533616,
   18.831102455595776,
   33.761367221011362],
  5: [17.044458316352721,
   8.8728325406080071,
   36.633757142745011,
   12.765386276860966,
   38.163474339821498,
   24.289207536598049,
   35.41215725636016,
   24.804929477067752,
   11.306263499863963,
   30.084351346964901],
  10: [20.520661613794513,
   36.819728500432582,
   9.6752331488362877,
   18.619544951249008,
   25.020480640981265,
   33.388727424196297,
   17.083247765304741,
   37.301598275767887,
   7.9277403470016603,
   12.151770948188698],
  20: [33.617144741555265,
   10.66330131186583,
   26.728337227239276,
   23.691138642141475,
   6.6929850198850813,
   32.434130732698385,
   18.612303624298598,
   28.966712314338473,
   15.605757351747663,
   4.5434012386508424]},
 1: {1: [11.539126650560309,
   14.512706621229997,
   15.608350965945302,
   25.518882857607021,
   30.285301301366346,
   17.917173822887179,
   12.228572190618145,
   14.337044207913282,
   15.053545309527159,
   41.306035978195105],
  2: [9.6684265522849948,
   9.6728196506868702,
   40.652703958454822,
   19.800047250738572,
   7.7955281759658064,
   29.650699196557291,
   28.244993443577386,
   23.11994172636691,
   13.069355000583768,
   29.980888620510079],
  3: [11.016844781320303,
   13.944900275058968,
   15.383466393745628,
   20.799196092381457,
   26.657368285453394,
   21.072189161321049,
   15.810715770473641,
   45.34835002325179,
   18.791434240815839,
   27.096049888596575],
  5: [7.0449052902103775,
   12.472041958180146,
   17.15378086108927,
   26.148618548503435,
   15.887300830510679,
   30.98663579312856,
   17.137152980322295,
   11.743185800158892,
   30.901557772667886,
   19.969390070810082],
  10: [13.477929806258535,
   12.579408852673668,
   20.433296470888855,
   22.720327683806357,
   22.472635876506494,
   24.713211605390875,
   7.9913361754218162,
   11.504814655268632,
   20.882070390544666,
   17.839296711563968],
  20: [22.2888597492794,
   11.895943923421227,
   14.038218669632601,
   34.111073967739792,
   11.397544083822735,
   10.127150699116873,
   16.552453306411575,
   29.394720757864985,
   19.568810945280482,
   19.123016833155617]},
 2: {1: [12.294424128141749,
   29.76059783799386,
   18.672557856731242,
   20.806057280909052,
   15.497103899681807,
   18.592752820323302,
   20.215403049442177,
   12.432274512674235,
   20.849035353316726,
   68.582825497656017],
  2: [14.230179130021053,
   9.2227140926561653,
   10.519201728831032,
   27.726968720656235,
   14.170647830652401,
   27.137474186996915,
   19.064351362636522,
   31.751918395062297,
   15.715626813005352,
   32.954798899178115],
  3: [13.425546223957138,
   11.252069246468864,
   16.843315391237486,
   16.039079664944008,
   21.316803118757292,
   18.721719938749377,
   29.748886047380335,
   26.314791681161321,
   15.778957466466727,
   28.883949785734728],
  5: [16.558263248516528,
   10.999965655716448,
   13.790938701052953,
   28.458298898326287,
   12.389842714382924,
   22.017003512388836,
   32.436095969419277,
   39.64767957917568,
   17.00646067225,
   19.950361643125785],
  10: [14.349280440889588,
   15.333371068036975,
   22.679639325658869,
   16.913421012831964,
   19.960616427325505,
   15.171877216564187,
   24.101447568251142,
   20.29585486632654,
   21.889723516225406,
   13.413773251955529],
  20: [16.769866419929926,
   23.128738388411495,
   13.981931048516548,
   23.439259043853642,
   11.692619218054675,
   20.420220875415211,
   24.795282212133991,
   21.117753167351516,
   14.595868687034349,
   17.217363300022644]},
 3: {1: [7.9118654929159966,
   3.9676042983419442,
   8.1864400122277878,
   34.143705605708632,
   26.337106858312676,
   18.28873278280804,
   23.710319297064373,
   24.591170695275302,
   36.699964437437842,
   78.825908492477893],
  2: [3.6109720809207335,
   14.977909469152053,
   15.990687508733119,
   27.029190317105321,
   16.221258305382477,
   42.839623325427382,
   20.883806201425013,
   28.089069780761797,
   35.91857058721601,
   60.518543055831906],
  3: [9.1766919649352658,
   15.142976869401398,
   21.786857396090504,
   26.620211894498141,
   18.488413829265259,
   19.133968714827269,
   64.485983447595302,
   34.22798473684626,
   38.746143010605529,
   46.960784214488427],
  5: [4.1807082511688014,
   7.7441065200695869,
   8.3788086305921059,
   11.810634855471845,
   24.95912164387569,
   30.403044268749337,
   19.236513645266626,
   50.193189649722328,
   41.429921598449496,
   42.966261523410928],
  10: [9.9051198600417116,
   9.8722363259241348,
   15.884290589050389,
   6.6843251159483321,
   29.748544489893682,
   18.376146442935173,
   20.581543649271907,
   41.30694056055323,
   27.635196465403737,
   22.265606829965144],
  20: [8.7081546802102281,
   6.9603890935356496,
   19.788457280531162,
   19.406660117393578,
   40.521596643664409,
   29.201680015274597,
   27.877947985556407,
   21.185066207539549,
   15.884843088009367,
   19.444507729302842]},
 4: {1: [35.911945717095513,
   28.103318558285512,
   46.016556432551894,
   20.30116298098352,
   29.850053459063197,
   72.886673493338051,
   23.840092646371147,
   10.224126578974797,
   73.551771926790408,
   106.92956793137289],
  2: [36.994644914066711,
   44.979233250643126,
   40.484389834186736,
   30.272815071235918,
   30.872575495847141,
   46.46074660201409,
   36.099248446266429,
   62.455444221784809,
   29.304673959002539,
   88.166961334438625],
  3: [26.946122048209379,
   49.466218063850846,
   39.161851629780493,
   53.075776124482779,
   15.988143986707566,
   49.881593037863311,
   36.097862901541866,
   70.069314510437493,
   38.512030950322988,
   66.365028654038056],
  5: [27.533701653279905,
   41.651164009085051,
   39.170852487091842,
   51.710102099792749,
   24.567300304819394,
   23.72736411033986,
   53.648774819812104,
   43.194377332525598,
   36.671715706145321,
   44.553284619497333],
  10: [27.471675367612832,
   40.857523447089335,
   71.475487535779294,
   15.77732673418053,
   34.725874538442902,
   39.85935549781049,
   20.902226301115988,
   28.539144355796335,
   26.715851648136553,
   30.895262711618383],
  20: [22.7653330403609,
   24.745430006015269,
   53.033079396468892,
   33.594520611817018,
   24.18460936206429,
   19.409157034768313,
   30.364033563071057,
   13.407286002573285,
   22.222044955511588,
   12.326161194425865]},
 5: {1: [15.363744307527458,
   22.770069396746869,
   15.978565565173819,
   25.209742407954078,
   42.474909270857069,
   29.341530336489249,
   20.538764792202336,
   33.59488614455568,
   40.577798943191461,
   72.684541056085749],
  2: [21.143944878570448,
   16.020681561092523,
   16.691647680936928,
   31.878090615685167,
   39.429095437052538,
   27.770312278635672,
   26.182347906144017,
   48.005891755714885,
   37.652389348665061,
   91.333648328488181],
  3: [19.057740793323486,
   44.63966332406234,
   11.138549262892848,
   30.074614195233877,
   37.46325219261275,
   30.398376348155136,
   62.310822495042764,
   26.927448453670955,
   56.570400791923952,
   55.248657353324774],
  5: [14.419529508167889,
   32.138769835708395,
   29.597728142674288,
   16.08580715928036,
   47.311231372512445,
   41.059200135707613,
   34.072423855951996,
   42.925641634089594,
   41.485201239689665,
   40.520202827372771],
  10: [13.641385289763599,
   23.157327843626,
   13.815926568605814,
   20.301749562754363,
   36.005476167796054,
   44.187647693291751,
   28.393699114900013,
   55.549624036781374,
   43.96492975506429,
   22.98698343574312],
  20: [14.993460887298674,
   24.096955300786359,
   29.243330300603443,
   16.327160403359343,
   41.436992148885729,
   20.252222262085681,
   45.392339273389219,
   19.543864612906699,
   24.248791566764503,
   25.941628739009076]},
 6: {1: [4.0065584434953454,
   11.805045083559712,
   27.241574407937897,
   29.212411449326371,
   28.188672185378525,
   15.303653575451589,
   19.653613767618157,
   21.007227723554678,
   31.598058961564167,
   46.183153783124077],
  2: [3.1389843801915633,
   15.59939121351543,
   28.612543849707841,
   27.656246597895656,
   29.272016032545,
   24.955033309773295,
   22.320801794670849,
   21.167716693317146,
   21.36124395152731,
   34.700621959533549],
  3: [3.4227658856086061,
   21.694740847800144,
   25.939056156770107,
   17.486346948823709,
   31.642196926499139,
   31.399962856389831,
   18.478132814562777,
   39.713159190930625,
   16.44201419079219,
   23.845767329572126],
  5: [1.7403017658670794,
   14.761541596529261,
   40.046958284056828,
   22.417891725508134,
   22.261822516406042,
   18.036231453836216,
   42.01068239184626,
   23.436272266534299,
   23.713639850856637,
   10.939403078030864],
  10: [15.866141141113211,
   32.512814035496156,
   19.146127761850302,
   24.641970761719794,
   20.769306817309069,
   29.189644038407483,
   22.845402106064689,
   28.152715127082331,
   27.72520299284426,
   5.1337972410873602],
  20: [16.860690139073558,
   26.66462374833073,
   43.062506901903127,
   17.400465125731653,
   17.604261302258806,
   25.728958826884242,
   20.900601295198335,
   28.063707450515331,
   32.850683760704811,
   7.9575454650636681]},
 7: {1: [9.7323653440365163,
   15.319395319043197,
   39.591623441604519,
   21.761345564292064,
   23.313663442683922,
   18.846122865510001,
   21.736487868616209,
   12.147436668376606,
   32.036034615824889,
   55.265660591478373],
  2: [32.354258074586383,
   27.906416039438142,
   18.756303588907066,
   27.086183019401517,
   19.714965007072319,
   26.06211322820894,
   30.734125488799009,
   27.892419832974952,
   28.653639556697659,
   23.600477762365106],
  3: [22.192378955380843,
   24.340873686144203,
   13.415896914216132,
   17.832128159082448,
   26.321191437325616,
   44.195717835191317,
   27.366499990115848,
   21.690972924544202,
   26.011370658004932,
   17.651473648732562],
  5: [26.447103045096142,
   13.242642736189374,
   12.795661283070411,
   32.472863293982016,
   20.166177369628681,
   22.912409994456581,
   27.709312861064465,
   16.193682542242485,
   23.771379024382547,
   18.78160896362607],
  10: [22.974545541286172,
   21.954019305026854,
   6.1794889365529606,
   34.535356713328106,
   8.4546792729216591,
   20.998128576480401,
   24.892663236587918,
   16.545320015212315,
   26.88405630017985,
   16.680058454774787],
  20: [18.890441903629021,
   29.898773733486316,
   19.385555545724198,
   35.443709338436037,
   15.798486331163744,
   9.2201085262947622,
   15.792332359770787,
   18.748953880170664,
   28.063702262134044,
   11.949657191192228]}}

In [43]:
def plot_quartiles(quart_num,y_vals,ax,plot_idx,eco=False,logMstar=False,\
    color='gray'):
    if eco == True:
        titles = [1,2,3,5,10,20]
        ax.set_xlim(0,5)
        if logMstar == True:
            ax.set_ylim(10,12)
            ax.set_yticks(np.arange(10,12,0.5))
        else:
            ax.set_ylim(-1.5,0)
            ax.set_yticks(np.arange(-1.25,0,0.25))
            plt.gca().invert_yaxis()
        ax.set_xticks(range(1,5))
        title_here = 'n = {0}'.format(titles[plot_idx])
        ax.text(0.05, 0.95, title_here,horizontalalignment='left',\
                verticalalignment='top',transform=ax.transAxes,fontsize=18)
        if plot_idx == 4:
            ax.set_xlabel('Quartiles',fontsize=18)
    if eco == True:
        ax.plot(quart_num,y_vals,marker='o',color=color,linewidth=2,\
            markeredgecolor=color)
    else:
        ax.plot(quart_num,y_vals,color=color)

In [44]:
def plot_deciles(dec_num,y_vals,ax,plot_idx,eco=False,logMstar=False,\
    color='gray'):
    if eco == True:
        titles = [1,2,3,5,10,20]
        ax.set_xlim(0,11)
        if logMstar == True:
            ax.set_ylim(10,12)
            ax.set_yticks(np.arange(10,12,0.5))
        else:    
            ax.set_ylim(-1.5,0)
            ax.set_yticks(np.arange(-1.25,0,0.25))
            plt.gca().invert_yaxis()
        ax.set_xticks(range(1,11))
        title_here = 'n = {0}'.format(titles[plot_idx])
        ax.text(0.05, 0.5, title_here,horizontalalignment='left',\
                verticalalignment='top',transform=ax.transAxes,fontsize=18)
        if plot_idx == 4:
            ax.set_xlabel('Decile',fontsize=18)
    if eco == True:
        ax.plot(dec_num,y_vals,marker='o',color=color,linewidth=2.5,\
            markeredgecolor=color)
    else:
        ax.plot(dec_num,y_vals,color=color,alpha=0.5)

In [45]:
nrow_num_mass = int(2)
ncol_num_mass = int(3)

fig, axes = plt.subplots(nrows=nrow_num_mass, ncols=ncol_num_mass, \
        figsize=(4,6), sharex= True, sharey = True)
axes_flat = axes.flatten()


fig.text(0.01, 0.5, '$\log\ (M_{*}/M_{\odot})$', ha='center', \
    va='center',rotation='vertical',fontsize=20)


zz = int(0)
while zz <=5:   
    ii = neigh_vals[zz]
    for ff in range(len(mass_dat)):
        plot_quartiles(quarts_x,mock_quarts_logMstar_dict[ff][ii],axes_flat[zz],\
            zz,logMstar=True)
    plot_quartiles(quarts_x,eco_quarts_logMstar[ii],axes_flat[zz],zz,\
        logMstar=True,color='crimson',eco=True)
    zz   += 1
        
plt.subplots_adjust(left=0.05, bottom=0.09, right=1.00, top=1.00,\
            hspace=0,wspace=0)
plt.show()


C:\Users\Hannah\Anaconda2\lib\site-packages\matplotlib\font_manager.py:1288: UserWarning: findfont: Font family [u'serif'] not found. Falling back to Bitstream Vera Sans
  (prop.get_family(), self.defaultFamily[fontext]))

In [46]:
nrow_num_mass = int(2)
ncol_num_mass = int(3)

fig, axes = plt.subplots(nrows=nrow_num_mass, ncols=ncol_num_mass, \
        figsize=(5,8), sharex= True, sharey = True)
axes_flat = axes.flatten()

fig.text(0.01, 0.5, r'$\alpha$', ha='center', \
    va='center',rotation='vertical',fontsize=25)

zz = int(0)
while zz <=5:   
    ii = neigh_vals[zz]
    for ff in range(len(mass_dat)):
        plot_quartiles(quarts_x,mock_quarts_alpha_dict[ff][ii],axes_flat[zz],zz,\
            logMstar=False)
    plot_quartiles(quarts_x,eco_quarts_alpha[ii],axes_flat[zz],zz,\
        logMstar=False,color='crimson',eco=True)
    zz   += 1
        
plt.subplots_adjust(left=0.05, bottom=0.09, right=1.00, top=1.00,\
            hspace=0,wspace=0)
plt.show()

In [47]:
nrow_num_mass = int(2)
ncol_num_mass = int(3)

fig, axes = plt.subplots(nrows=nrow_num_mass, ncols=ncol_num_mass, \
        figsize=(5,7), sharex= True, sharey = True)
axes_flat = axes.flatten()


fig.text(0.01, 0.5, '$\log\ (M_{*}/M_{\odot})$', ha='center', \
    va='center',rotation='vertical',fontsize=20)


zz = int(0)
while zz <=5:   
    ii = neigh_vals[zz]
    for ff in range(len(mass_dat)):
        plot_deciles(dec_x,mock_dec_logMstar_dict[ff][ii],axes_flat[zz],\
            zz,logMstar=True)
    plot_deciles(dec_x,eco_dec_logMstar[ii],axes_flat[zz],zz,\
        logMstar=True,color='crimson',eco=True)
    zz   += 1
        
plt.subplots_adjust(left=0.05, bottom=0.09, right=1.00, top=1.00,\
            hspace=0,wspace=0)
plt.show()

In [48]:
nrow_num_mass = int(2)
ncol_num_mass = int(3)

fig, axes = plt.subplots(nrows=nrow_num_mass, ncols=ncol_num_mass, \
        figsize=(6,8), sharex= True, sharey = True)
axes_flat = axes.flatten()

fig.text(0.01, 0.5, r'$\alpha$', ha='center', \
    va='center',rotation='vertical',fontsize=25)

zz = int(0)
while zz <=5:   
    ii = neigh_vals[zz]
    for ff in range(len(mass_dat)):
        plot_deciles(dec_x,mock_dec_alpha_dict[ff][ii],axes_flat[zz],zz,\
            logMstar=False)
    plot_deciles(dec_x,eco_dec_alpha[ii],axes_flat[zz],zz,\
        logMstar=False,color='crimson',eco=True)
    zz   += 1
        
plt.subplots_adjust(left=0.05, bottom=0.09, right=1.00, top=1.00,\
            hspace=0,wspace=0)
plt.show()