Example #1
0
double M_sc(double       z,
            cosmo_info **cosmo,
            int          mode,
            int          component){
  int     i;
  int     n_k;
  size_t  n_k_dim;
  double *lM_k;
  double *lk_P;
  double *sigma2;
  interp_info *interp;
  double  delta_sc=1.686;
  double  b_z;
  double  r_val;
  char    mode_name[ADaPS_NAME_LENGTH];
  char    component_name[ADaPS_NAME_LENGTH];
  char    sigma2_name[ADaPS_NAME_LENGTH];
  static double M_sc_last;
  static double z_last=-42.;

  if(z!=z_last){
    // Set/initialize variance
    pspec_names(mode,component,mode_name,component_name);
    sprintf(sigma2_name,"sigma2_k_%s_%s_interp",mode_name,component_name);
    if(!ADaPS_exist(*cosmo,sigma2_name))
      init_power_spectrum_variance(cosmo,z,mode,component);
    interp   =(interp_info *)ADaPS_fetch(*cosmo,sigma2_name);
    b_z      =linear_growth_factor(z,*cosmo);
    r_val    =bisect_array(interp,delta_sc*delta_sc/(b_z*b_z),1e-4);
    M_sc_last=M_of_k(take_alog10(r_val),z,*cosmo);
    z_last   =z;
  }

  return(M_sc_last);
}
Example #2
0
void set_NFW_params(double       M,
                    double       z,
                    int          mode,
                    cosmo_info **cosmo,
                    double      *c_vir,
                    double      *R_vir){
  double M_o;
  double Delta;
  double h_Hubble;
  double Omega_M;

  if(mode!=NFW_MODE_DEFAULT)
     SID_trap_error("Unknown mode (%d) in set_NFW_params()",ERROR_LOGIC,mode);

  switch(ADaPS_exist(*cosmo,"M_WDM")){
  case FALSE:
    {
    Omega_M =((double *)ADaPS_fetch(*cosmo,"Omega_M"))[0];
    h_Hubble=((double *)ADaPS_fetch(*cosmo,"h_Hubble"))[0];
    M_o     =M_sc(z,cosmo,PSPEC_LINEAR_TF,PSPEC_ALL_MATTER);

    // Mass-concentration from Munoz-Cuartas et al 2010
    //(*c_vir)=(11./(1.+z))*pow(M/M_o,-0.13);     // Bullock et al '01 & Zehavi et al '04
    double w    =   0.029;
    double m    =   0.097;
    double alpha=-110.001;
    double beta =2469.720;
    double gamma=  16.885;
    double a_z  =w*z-m;
    double b_z  =alpha/(z+gamma)+beta/pow(z+gamma,2.);
    (*c_vir)    =take_alog10(a_z*take_log10(M/(M_SOL/h_Hubble))+b_z);

    Delta   =Delta_vir(z,*cosmo);
    Delta=200.;
    (*R_vir)=R_Delta_z(M,Delta,z,*cosmo);       // Bullock et al '01
    }
    break;
  case TRUE:
    SID_trap_error("ENS not working.",ERROR_LOGIC);
    //(*c_vir)=c_ENS(M,z,*cosmo);          // Eke, Navarro and Steinmetz
    //(*R_vir)=R_Delta_z(M,200.,z,*cosmo); // R_200
    break;
  }
}
Example #3
0
double bias_model_BPR_integral(cosmo_info **cosmo, double z) {
    double       z_max = 10000.;
    interp_info *interp;
    if(!ADaPS_exist(*cosmo, "bias_model_BPR_Iz_interp")) {
        int     n_int;
        int     i_int;
        double  dz;
        double  Omega_M, Omega_k, Omega_Lambda;
        double  z_temp;
        double *x_int;
        double *y_int;
        double  log_z;
        double  dlog_z;
        n_int        = 250;
        Omega_M      = ((double *)ADaPS_fetch(*cosmo, "Omega_M"))[0];
        Omega_k      = ((double *)ADaPS_fetch(*cosmo, "Omega_k"))[0];
        Omega_Lambda = ((double *)ADaPS_fetch(*cosmo, "Omega_Lambda"))[0];
        x_int        = (double *)SID_malloc(sizeof(double) * n_int);
        y_int        = (double *)SID_malloc(sizeof(double) * n_int);
        i_int        = 0;
        x_int[i_int] = 0.;
        y_int[i_int] = pow((1. + x_int[i_int]) / E_z(Omega_M, Omega_k, Omega_Lambda, x_int[i_int]), 3.);
        i_int++;
        x_int[i_int] = take_log10(z_max) / (double)(n_int - 1);
        y_int[i_int] = pow((1. + x_int[i_int]) / E_z(Omega_M, Omega_k, Omega_Lambda, x_int[i_int]), 3.);
        log_z        = take_log10(x_int[i_int]);
        dlog_z       = (take_log10(z_max) - log_z) / (double)(n_int - 2);
        for(i_int++, log_z += dlog_z; i_int < (n_int - 1); i_int++, log_z += dlog_z) {
            x_int[i_int] = take_alog10(log_z);
            y_int[i_int] = pow((1. + x_int[i_int]) / E_z(Omega_M, Omega_k, Omega_Lambda, x_int[i_int]), 3.);
        }
        x_int[i_int] = z_max;
        y_int[i_int] = pow((1. + x_int[i_int]) / E_z(Omega_M, Omega_k, Omega_Lambda, x_int[i_int]), 3.);
        init_interpolate(x_int, y_int, (size_t)n_int, gsl_interp_cspline, &interp);
        SID_free(SID_FARG x_int);
        SID_free(SID_FARG y_int);
        ADaPS_store_interp(cosmo, (void *)(interp), "bias_model_BPR_Iz_interp");

    } else
        interp = (interp_info *)ADaPS_fetch(*cosmo, "bias_model_BPR_Iz_interp");
    return (interpolate_integral(interp, z, z_max));
}
Example #4
0
void write_cfunc(cfunc_info *cfunc, const char *filename_out_root, plist_info *plist, const char *species_name, const char *randoms_name, int i_run) {
    // Now that all 4 runs are done, let's write the results
    SID_log("Writing correlation functions...", SID_LOG_OPEN | SID_LOG_TIMER);
    if(SID.I_am_Master) {
        // Set output filenames
        char filename_out_1D_ascii[SID_MAX_FILENAME_LENGTH];
        char filename_out_1D[SID_MAX_FILENAME_LENGTH];
        char filename_out_2D[SID_MAX_FILENAME_LENGTH];
        sprintf(filename_out_1D_ascii, "%s_1D_cfunc.ascii", filename_out_root);
        sprintf(filename_out_1D, "%s_1D_cfunc.dat", filename_out_root);
        sprintf(filename_out_2D, "%s_2D_cfunc.dat", filename_out_root);

        // Fetch the number of objects that contributed to the calculation
        size_t n_species;
        size_t n_randoms;
        n_species = ((size_t *)ADaPS_fetch(plist->data, "n_all_%s", species_name))[0];
        n_randoms = ((size_t *)ADaPS_fetch(plist->data, "n_all_%s", randoms_name))[0];

        // Write 1-D Results to an ascii file
        FILE *fp_out;
        int   i_r;
        char  grouping_name[SID_MAX_FILENAME_LENGTH];
        strcpy(grouping_name, filename_out_root);
        strip_path(grouping_name);
        fp_out = fopen(filename_out_1D_ascii, "w");
        fprintf(fp_out, "# 1D Correlation functions for grouping {%s}\n", grouping_name);
        fprintf(fp_out, "#\n");
        fprintf(fp_out, "# No. of objects:         %zd\n", n_species);
        fprintf(fp_out, "# No. of randoms:         %zd\n", n_randoms);
        fprintf(fp_out, "# Redshift:               %5.3lf\n", cfunc->redshift);
        fprintf(fp_out, "# Box size:               %9.3le [Mpc/h]\n", cfunc->box_size);
        fprintf(fp_out, "# No. of jack-knifes:     %d^3\n", cfunc->n_jack);
        fprintf(fp_out, "#\n");
        fprintf(fp_out, "# Start of first log-bin: %9.3le [Mpc/h]\n", cfunc->r_min_l1D);
        fprintf(fp_out, "# Size of linear 1D bins: %9.3le [Mpc/h]\n", cfunc->dr_1D);
        fprintf(fp_out, "# Size of linear 2D bins: %9.3le [Mpc/h]\n", cfunc->dr_2D);
        int i_column = 1;
        int j_run;
        fprintf(fp_out, "#\n");
        fprintf(fp_out, "# Column: (%02d) r_log [Mpc/h]; Logarithmically spaced bins\n", i_column++);
        fprintf(fp_out, "#         (%02d) r_lin [Mpc/h]; Linearly        spaced bins\n", i_column++);
        for(j_run = 0; j_run <= i_run; j_run++) {
            char run_name[128];
            switch(j_run) {
                case 0:
                    sprintf(run_name, "real");
                    break;
                case 1:
                    sprintf(run_name, "x-projected z");
                    break;
                case 2:
                    sprintf(run_name, "y-projected z");
                    break;
                case 3:
                    sprintf(run_name, "z-projected z");
                    break;
            }
            fprintf(fp_out, "#         (%02d) xi(r_log);  %s-space\n", i_column++, run_name);
            fprintf(fp_out, "#         (%02d) dxi(r_log); %s-space\n", i_column++, run_name);
            fprintf(fp_out, "#         (%02d) xi(r_lin);  %s-space\n", i_column++, run_name);
            fprintf(fp_out, "#         (%02d) dxi(r_lin); %s-space\n", i_column++, run_name);
        }
        fprintf(fp_out, "#\n");
        double r_log;
        double r_lin;
        r_log = cfunc->lr_min_l1D + 0.5 * cfunc->dr_l1D;
        r_lin = 0.5 * cfunc->dr_1D;
        for(i_r = 0; i_r < cfunc->n_1D; i_r++, r_log += cfunc->dr_l1D, r_lin += cfunc->dr_1D) {
            fprintf(fp_out, "%9.4le %9.3le ", take_alog10(r_log), r_lin);
            for(j_run = 0; j_run <= i_run; j_run++)
                fprintf(fp_out,
                        "  %le %le %le %le",
                        cfunc->CFUNC_l1D[j_run][i_r],
                        cfunc->dCFUNC_l1D[j_run][i_r],
                        cfunc->CFUNC_1D[j_run][i_r],
                        cfunc->dCFUNC_1D[j_run][i_r]);
            fprintf(fp_out, "\n");
        }
        fclose(fp_out);

        // Write 1-D Results to a binary file
        int i_jack;
        if(i_run == 0) {
            fp_out = fopen(filename_out_1D, "w");
            fwrite(&(cfunc->n_1D), sizeof(int), 1, fp_out);
            fwrite(&(cfunc->n_jack), sizeof(int), 1, fp_out);
            fwrite(&(cfunc->r_min_l1D), sizeof(double), 1, fp_out);
            fwrite(&(cfunc->r_max_1D), sizeof(double), 1, fp_out);
            fwrite(&(cfunc->n_data), sizeof(int), 1, fp_out);
            fwrite(&(cfunc->n_random), sizeof(int), 1, fp_out);
        } else
            fp_out = fopen(filename_out_1D, "a");
        fwrite(cfunc->CFUNC_1D[i_run], sizeof(double), cfunc->n_1D, fp_out);
        fwrite(cfunc->dCFUNC_1D[i_run], sizeof(double), cfunc->n_1D, fp_out);
        fwrite(cfunc->COVMTX_1D[i_run], sizeof(double), cfunc->n_1D * cfunc->n_1D, fp_out);
        for(i_jack = 0; i_jack <= cfunc->n_jack_total; i_jack++) {
            fwrite(cfunc->DD_1D[i_jack], sizeof(long long), cfunc->n_1D, fp_out);
            fwrite(cfunc->DR_1D[i_jack], sizeof(long long), cfunc->n_1D, fp_out);
            fwrite(cfunc->RR_1D[i_jack], sizeof(long long), cfunc->n_1D, fp_out);
        }
        fwrite(cfunc->CFUNC_l1D[i_run], sizeof(double), cfunc->n_1D, fp_out);
        fwrite(cfunc->dCFUNC_l1D[i_run], sizeof(double), cfunc->n_1D, fp_out);
        fwrite(cfunc->COVMTX_l1D[i_run], sizeof(double), cfunc->n_1D * cfunc->n_1D, fp_out);
        for(i_jack = 0; i_jack <= cfunc->n_jack_total; i_jack++) {
            fwrite(cfunc->DD_l1D[i_jack], sizeof(long long), cfunc->n_1D, fp_out);
            fwrite(cfunc->DR_l1D[i_jack], sizeof(long long), cfunc->n_1D, fp_out);
            fwrite(cfunc->RR_l1D[i_jack], sizeof(long long), cfunc->n_1D, fp_out);
        }
        fclose(fp_out);

        // Write 2D correlation functions to a binary file
        if(i_run == 0) {
            fp_out = fopen(filename_out_2D, "w");
            fwrite(&(cfunc->n_2D), sizeof(int), 1, fp_out);
            fwrite(&(cfunc->n_jack), sizeof(int), 1, fp_out);
            fwrite(&(cfunc->r_min_2D), sizeof(double), 1, fp_out);
            fwrite(&(cfunc->r_max_2D), sizeof(double), 1, fp_out);
            fwrite(&(cfunc->n_data), sizeof(int), 1, fp_out);
            fwrite(&(cfunc->n_random), sizeof(int), 1, fp_out);
        } else
            fp_out = fopen(filename_out_2D, "a");
        fwrite(cfunc->CFUNC_2D[i_run], sizeof(double), cfunc->n_2D_total, fp_out);
        fwrite(cfunc->dCFUNC_2D[i_run], sizeof(double), cfunc->n_2D_total, fp_out);
        fwrite(cfunc->COVMTX_2D[i_run], sizeof(double), cfunc->n_2D_total * cfunc->n_2D_total, fp_out);
        for(i_jack = 0; i_jack <= cfunc->n_jack_total; i_jack++) {
            fwrite(cfunc->DD_2D[i_jack], sizeof(long long), cfunc->n_2D_total, fp_out);
            fwrite(cfunc->DR_2D[i_jack], sizeof(long long), cfunc->n_2D_total, fp_out);
            fwrite(cfunc->RR_2D[i_jack], sizeof(long long), cfunc->n_2D_total, fp_out);
        }
        fclose(fp_out);
    }
    SID_log("Done.", SID_LOG_CLOSE);
}
Example #5
0
int main(int argc, char *argv[]){

  SID_init(&argc,&argv,NULL,NULL);

  char   filename_cosmology[MAX_FILENAME_LENGTH];
  char   paramterization[MAX_FILENAME_LENGTH];
  double log_M_min    =atof(argv[1]);
  double log_M_max    =atof(argv[2]);
  int    n_M_bins     =atoi(argv[3]);
  double redshift     =atof(argv[4]);
  strcpy(filename_cosmology,argv[5]);
  strcpy(paramterization,   argv[6]);

  SID_log("Constructing mass function between log(M)=%5.3lf->%5.3lf at z=%5.3lf...",SID_LOG_OPEN,log_M_min,log_M_max,redshift);

  // Initialize cosmology
  cosmo_info *cosmo=NULL;
  read_gbpCosmo_file(&cosmo,filename_cosmology);

  // Decide which parameterization we are going to use
  int  select_flag;
  char mfn_text[32];
  if(!strcmp(paramterization,"JENKINS")){
     sprintf(mfn_text,"Jenkins");
     select_flag=MF_JENKINS;
  }
  else if(!strcmp(paramterization,"PS")){
     sprintf(mfn_text,"Press & Schechter");
     select_flag=MF_PS;
  }
  else if(!strcmp(paramterization,"ST")){
     sprintf(mfn_text,"Sheth & Tormen");
     select_flag=MF_ST;
  }
  else
     SID_trap_error("Invalid parameterization selected {%s}.  Should be {JENKINS,PS or ST}.",ERROR_SYNTAX,paramterization);

  // Create output filename
  char  filename_out[MAX_FILENAME_LENGTH];
  char  redshift_text[64];
  char *cosmology_name=(char *)ADaPS_fetch(cosmo,"name");
  float_to_text(redshift,3,redshift_text);
  sprintf(filename_out,"mass_function_z%s_%s_%s.txt",redshift_text,cosmology_name,paramterization);

  // Open file and write header
  FILE *fp_out=NULL;
  fp_out=fopen(filename_out,"w");
  int i_column=1;
  fprintf(fp_out,"# Mass function (%s) for %s cosmology at z=%lf\n",mfn_text,filename_cosmology,redshift);
  fprintf(fp_out,"# \n");
  fprintf(fp_out,"# Column (%02d): log M [h^-1 M_sol]\n",                              i_column++);
  fprintf(fp_out,"#        (%02d): Mass function [(h^{-1} Mpc]^{-3} per dlogM]\n",     i_column++);
  fprintf(fp_out,"#        (%02d): Cumulative Mass function(>M) [(h^{-1} Mpc]^{-3}]\n",i_column++);

  // Create the mass function
  SID_log("Writing results to {%s}...",SID_LOG_OPEN|SID_LOG_TIMER,filename_out);
  pcounter_info pcounter;
  SID_init_pcounter(&pcounter,n_M_bins,10);
  double h_Hubble   =((double *)ADaPS_fetch(cosmo,"h_Hubble"))[0];
  double mass_factor=M_SOL/h_Hubble;
  double MFct_factor=pow(M_PER_MPC,3.0);
  for(int i_bin=0;i_bin<n_M_bins;i_bin++){
     double log_M;
     if(i_bin==0)
        log_M=log_M_min;
     else if(i_bin==(n_M_bins-1))
        log_M=log_M_max;
     else
        log_M=log_M_min+(((double)(i_bin))/((double)(n_M_bins-1)))*(log_M_max-log_M_min);
     fprintf(fp_out,"%le %le %le\n",log_M,
                                    MFct_factor*mass_function           (mass_factor*take_alog10(log_M),redshift,&cosmo,select_flag),
                                    MFct_factor*mass_function_cumulative(mass_factor*take_alog10(log_M),redshift,&cosmo,select_flag));
     SID_check_pcounter(&pcounter,i_bin);
  }
  fclose(fp_out);
  SID_log("Done.",SID_LOG_CLOSE);

  // Clean-up
  free_cosmo(&cosmo);

  SID_log("Done.",SID_LOG_CLOSE);
  SID_exit(ERROR_NONE);
}
Example #6
0
int main(int argc, char *argv[]){

  SID_init(&argc,&argv,NULL,NULL);

  // Parse arguments and initialize
  double z;
  if(argc<2 || argc>3){
    fprintf(stderr,"\n Syntax: %s z [gbpCosmo_file.txt]\n",argv[0]);
    fprintf(stderr," ------\n\n");
    return(ERROR_SYNTAX);
  }
  else
    z=(double)atof(argv[1]);

  SID_log("Computing clustering information for z=%.2lf...",SID_LOG_OPEN,z);

  // Initialize cosmology
  cosmo_info *cosmo=NULL;
  if(argc==2)
     init_cosmo_default(&cosmo);
  else if(argc==3)
     read_gbpCosmo_file(&cosmo,argv[2]);

  // Initialize
  int     mode     =PSPEC_LINEAR_TF;
  int     component=PSPEC_ALL_MATTER;
  init_sigma_M(&cosmo,z,mode,component);
  int     n_k     =((int    *)ADaPS_fetch(cosmo,"n_k"))[0];
  double *lk_P    = (double *)ADaPS_fetch(cosmo,"lk_P");
  double  h_Hubble=((double *)ADaPS_fetch(cosmo,"h_Hubble"))[0];
  SID_log("Done.",SID_LOG_CLOSE);

  // Generate file
  SID_log("Writing table to stdout...",SID_LOG_OPEN);
  double delta_c    =1.686;
  double m_per_mpc_h=M_PER_MPC/h_Hubble;
  printf("# Column (01): k [h Mpc^-1]\n");
  printf("#        (02): R [h^-1 Mpc] \n");
  printf("#        (03): M [h^-1 M_sol]\n");
  printf("#        (04): V_max [km/s] \n");
  printf("#        (05): P_k [(h^-1 Mpc)^3]\n");
  printf("#        (06): sigma\n");
  printf("#        (07): nu (peak height)\n");
  printf("#        (08): b_BPR\n");
  printf("#        (09): b_TRK\n");
  printf("#        (10): z-space boost Kaiser '87 (applied to b_TRK)\n");
  printf("#        (11): b_TRK total (w/ Kaiser boost)\n");
  printf("#        (12): b_halo_Poole \n");
  printf("#        (13): z-space boost Poole \n");
  printf("#        (14): b_total_Poole \n");
  printf("#        (15): b_halo_Poole        (substructure)\n");
  printf("#        (16): z-space boost Poole (substructure)\n");
  printf("#        (17): b_total_Poole       (substructure)\n");
  for(int i_k=0;i_k<n_k;i_k++){
     double k_P  =take_alog10(lk_P[i_k]);
     double R_P  =R_of_k(k_P);
     double M_R  =M_of_k(k_P,z,cosmo);
     double P_k  =power_spectrum(k_P,z,&cosmo,mode,component);
     double sigma=sqrt(power_spectrum_variance(k_P,z,&cosmo,mode,component));
     double V_max=V_max_NFW(M_R,z,NFW_MODE_DEFAULT,&cosmo);
     double nu   =delta_c/sigma;
     double bias =1.;
     if(M_R<1e16*M_SOL){
        printf("%10.5le %10.5le %10.5le %10.5le %10.5le %10.5le %10.5le %10.5le %10.5le %10.5le %10.5le %10.5le %10.5le %10.5le %10.5le %10.5le %10.5le\n",
               k_P*m_per_mpc_h,
               R_P/m_per_mpc_h,
               M_R/(M_SOL/h_Hubble),
               V_max*1e-3,
               P_k/pow(m_per_mpc_h,3.),
               sigma,
               nu,
               bias_model(M_R,delta_c,z,&cosmo,BIAS_MODEL_BPR),
               bias_model(M_R,delta_c,z,&cosmo,BIAS_MODEL_TRK),
               bias_model(M_R,delta_c,z,&cosmo,BIAS_MODEL_TRK|BIAS_MODEL_KAISER_BOOST),
               bias_model(M_R,delta_c,z,&cosmo,BIAS_MODEL_TRK|BIAS_MODEL_KAISER),
               bias_model(M_R,delta_c,z,&cosmo,BIAS_MODEL_POOLE_HALO),
               bias_model(M_R,delta_c,z,&cosmo,BIAS_MODEL_POOLE_ZSPACE),
               bias_model(M_R,delta_c,z,&cosmo,BIAS_MODEL_POOLE_TOTAL),
               bias_model(M_R,delta_c,z,&cosmo,BIAS_MODEL_POOLE_SUBSTRUCTURE|BIAS_MODEL_POOLE_HALO),
               bias_model(M_R,delta_c,z,&cosmo,BIAS_MODEL_POOLE_SUBSTRUCTURE|BIAS_MODEL_POOLE_ZSPACE),
               bias_model(M_R,delta_c,z,&cosmo,BIAS_MODEL_POOLE_SUBSTRUCTURE|BIAS_MODEL_POOLE_TOTAL));
     }
  }
  SID_log("Done.",SID_LOG_CLOSE);

  // Clean-up
  free_cosmo(&cosmo);

  SID_log("Done.",SID_LOG_CLOSE);
  SID_exit(ERROR_NONE);
}
int main(int argc, char *argv[]){
   double  redshift;
   char    filename_in[MAX_FILENAME_LENGTH];
   char    filename_out[MAX_FILENAME_LENGTH];
   char    filename_cosmology[MAX_FILENAME_LENGTH];
   double  box_size;
   double  lM_min,dlM;
   char   *line=NULL;
   size_t  line_length=0;
   int     M_column;
   int     n_bins;
   int     flag_log;
 
   // Initialization -- MPI etc.
   SID_init(&argc,&argv,NULL,NULL);
   if(argc!=11)
     SID_trap_error("Incorrect syntax.",ERROR_SYNTAX);

   // Parse arguments
   strcpy(filename_in, argv[1]);
   strcpy(filename_out,argv[2]);
   redshift=(double)atof(argv[3]);
   strcpy(filename_cosmology,argv[4]);
   box_size=(double)atof(argv[5]);
   M_column=(int)   atoi(argv[6]);
   flag_log=(int)   atoi(argv[7]);
   lM_min  =(double)atof(argv[8]);
   dlM     =(double)atof(argv[9]);
   n_bins  =(int)   atoi(argv[10]);

   SID_log("Producing a mass function for ascii file {%s}...",SID_LOG_OPEN|SID_LOG_TIMER,filename_in);
 
   // Initialize cosmology
   cosmo_info *cosmo;
   read_gbpCosmo_file(&cosmo,filename_cosmology);
   double h_Hubble=((double *)ADaPS_fetch(cosmo,"h_Hubble"))[0];

   // Open file
   FILE *fp_in;
   if((fp_in=fopen(filename_in,"r"))==NULL)
      SID_trap_error("Could not open {%s} for reading.",ERROR_IO_OPEN,filename_in);

   // Allocate memory for the data. Read it and sort it in ascending order 
   SID_log("Reading data...",SID_LOG_OPEN|SID_LOG_TIMER);
   int     n_data_in=count_lines_data(fp_in);
   SID_log("(%d items)...",SID_LOG_CONTINUE,n_data_in);
   double *data  =(double *)malloc(sizeof(double)*n_data_in);
   int n_data=0;
   for(int i=0;i<n_data_in;i++){
     double data_in;
     grab_next_line_data(fp_in,&line,&line_length);
     grab_double(line,M_column,&data_in);
     if(!flag_log)
        data_in=take_log10(data_in);
     if(data_in>=lM_min)
        data[n_data++]=data_in;
   }
   SID_log("(%d will be used)...",SID_LOG_CONTINUE,n_data);
   fclose(fp_in);
   SID_free(SID_FARG line);
   SID_log("Done.",SID_LOG_CLOSE);

   // Perform sort
   SID_log("Sorting data...",SID_LOG_OPEN|SID_LOG_TIMER);
   merge_sort(data,n_data,NULL,SID_DOUBLE,SORT_INPLACE_ONLY,SORT_COMPUTE_INPLACE);
   SID_log("Done.",SID_LOG_CLOSE);

   // Compile histogram
   SID_log("Computing mass function...",SID_LOG_OPEN|SID_LOG_TIMER);
   double *bin       =(double *)SID_malloc(sizeof(double)*(n_bins+1));
   double *bin_median=(double *)SID_malloc(sizeof(double)*n_bins);
   int    *hist      =(int    *)SID_calloc(sizeof(int)   *n_bins);
   double  lM_bin_min=lM_min;
   double  lM_bin_max=lM_min;
   int     i_data_lo=-1;
   int     i_data_hi=-1;
   int     i_bin =0;
   int     i_data=0;
   for(i_bin=0;i_bin<n_bins;i_bin++){
     lM_bin_min=lM_bin_max;
     lM_bin_max=lM_min+((double)(i_bin+1))*dlM;
     bin[i_bin]=lM_bin_min;
     i_data_lo=i_data;
     i_data_hi=i_data;
     while(data[i_data]<lM_bin_max && i_data<n_data){
        hist[i_bin]++;
        i_data_hi=i_data;
        i_data++;
        if(i_data>=n_data) break;
     }
     int i_data_mid=(i_data_lo+i_data_hi)/2;
     if(hist[i_bin]>0){
       if(hist[i_bin]%2)
         bin_median[i_bin]=data[i_data_mid];
       else
         bin_median[i_bin]=0.5*(data[i_data_mid]+data[i_data_mid+1]);
     }
     else
        bin_median[i_bin]=0.5*(lM_bin_max+lM_bin_min);
   }
   bin[i_bin]=lM_bin_max;
   SID_log("Done.",SID_LOG_CLOSE);

   // Write mass function
   FILE *fp_out;
   if((fp_out=fopen(filename_out,"w"))==NULL){
     fprintf(stderr,"Error opening output file {%s}.\n",filename_out);
     SID_free(SID_FARG data);
     return(1);
   }
   SID_log("Writing results to {%s}...",SID_LOG_OPEN|SID_LOG_TIMER,filename_out);
   double box_volume=box_size*box_size*box_size;
   fprintf(fp_out,"# Mass function for column %d in {%s}\n",M_column,filename_in);
   fprintf(fp_out,"# Column (01): M_lo     [source units]\n");
   fprintf(fp_out,"#        (02): M_median [source units]\n");
   fprintf(fp_out,"#        (03): M_hi     [source units]\n");
   fprintf(fp_out,"#        (04): No. in bin\n");
   fprintf(fp_out,"#        (05): MFn (per unit volume, per dlogM)\n");
   fprintf(fp_out,"#        (06): +/- MFn\n");
   fprintf(fp_out,"#        (07): Sheth & Tormen MFn\n");
   fprintf(fp_out,"#        (08): Watson MFn\n");
   fprintf(fp_out,"#        (09): No. w/ M>M_lo\n");
   fprintf(fp_out,"#        (10): Cumulative MFn (per unit volume)\n");
   fprintf(fp_out,"#        (11): +/- Cumulative MFn\n");
   fprintf(fp_out,"#        (12): Sheth & Tormen Cumulative MFn\n");
   fprintf(fp_out,"#        (13): Watson Cumulative MFn\n");
   double M_sol_inv_h=M_SOL/h_Hubble;
   double Mpc_inv_h  =M_PER_MPC/h_Hubble;
   for(int i=0;i<n_bins;i++){
     double dn_dlogM_theory_1=mass_function(take_alog10(bin_median[i])*M_sol_inv_h,
                                            redshift,
                                            &cosmo,
                                            MF_ST)*pow(Mpc_inv_h,3.0);
     double n_theory_1=mass_function_cumulative(take_alog10(bin[i])*M_sol_inv_h,
                                                redshift,
                                                &cosmo,
                                                MF_ST)*pow(Mpc_inv_h,3.0);
     double dn_dlogM_theory_2=mass_function(take_alog10(bin_median[i])*M_sol_inv_h,
                                            redshift,
                                            &cosmo,
                                            MF_WATSON)*pow(Mpc_inv_h,3.0);
     double n_theory_2=mass_function_cumulative(take_alog10(bin[i])*M_sol_inv_h,
                                                redshift,
                                                &cosmo,
                                                MF_WATSON)*pow(Mpc_inv_h,3.0);
     // Compute cumulative histogram
     int cumulative_hist=0;
     for(int j_bin=i;j_bin<n_bins;j_bin++)
        cumulative_hist+=hist[j_bin];
     fprintf(fp_out,"%11.4le %11.4le %11.4le %6d %11.4le %11.4le %10.4le %10.4le %6d %10.4le %10.4le %10.4le %10.4le\n",
             bin[i],
             bin_median[i],
             bin[i+1],
             hist[i],
             (double)(hist[i])/(box_volume*dlM),
             sqrt((double)(hist[i]))/(box_volume*dlM),
             dn_dlogM_theory_1,dn_dlogM_theory_2,
             cumulative_hist,
             (double)(cumulative_hist)/box_volume,
             sqrt((double)(cumulative_hist))/box_volume,
             n_theory_1,n_theory_2);
   }
   fclose(fp_out);
   SID_log("Done.",SID_LOG_CLOSE);

   // Free allocated memory
   SID_free(SID_FARG data);
   SID_free(SID_FARG bin);
   SID_free(SID_FARG bin_median);
   SID_free(SID_FARG hist);
  
   SID_log("Done.",SID_LOG_CLOSE);
   SID_exit(ERROR_NONE);
}
int compute_group_analysis(halo_properties_info  *properties,
                           halo_profile_info     *profile,
                           double (*p_i_fctn) (void *,int,int), 
                           double (*v_i_fctn) (void *,int,int), 
                           size_t (*id_i_fctn)(void *,int), 
                           void   *params,
                           double                 box_size,
                           double                 particle_mass,
                           int                    n_particles,
                           double                 expansion_factor,
                           double                *x,
                           double                *y,
                           double                *z,
                           double                *vx,
                           double                *vy,
                           double                *vz,
                           double                *R,
                           size_t               **R_index_in,
                           int                    flag_manual_centre,
                           int                    flag_compute_shapes,
                           cosmo_info            *cosmo){
  size_t      *R_index;
  int          i,j;
  int          i_profile;
  int          j_profile;
  int          k_profile;
  int          n_profile;
  size_t       i_particle;
  size_t       j_particle;
  size_t       k_particle;
  int          next_bin_particle;
  interp_info *V_R_interpolate;
  interp_info *vir_interpolate;
  int          i_bin;
  int          n_in_bin;
  double       n_per_bin;
  int          n_cumulative;
  double       V1;
  double       V2;
  double       dV;
  double       dM;
  double       sigma_r_mean;
  double       sigma_t_mean;
  double       sigma_T_mean;
  double       sigma_P_mean;
  double       sigma_mean;
  double       x_COM_accumulator;
  double       y_COM_accumulator;
  double       z_COM_accumulator;
  double       vx_COM_accumulator;
  double       vy_COM_accumulator;
  double       vz_COM_accumulator;
  double       spin_x_accumulator;
  double       spin_y_accumulator;
  double       spin_z_accumulator;
  double       r_xy;
  double       v_tot,v_rad,v_tan;
  double       v_x_mean,v_y_mean,v_z_mean,v_rad_mean;
  double       shape_eigen_values[3];
  double       shape_eigen_vectors[3][3];
  double       x_COM,y_COM,z_COM,R_COM;
  double       r_c[MAX_PROFILE_BINS_P1];
  double       v_c[MAX_PROFILE_BINS_P1];
  double       r_interp[MAX_PROFILE_BINS];
  double       y_interp[MAX_PROFILE_BINS];
  size_t       n_bins_temp;
  double       V_max,R_max;
  double       Delta,Omega;
  double       norm;
  int          flag_interpolated=FALSE;
  const gsl_interp_type  *interp_type;
  double sigma_cor,sigma_halo;
  double M_cor,M_halo;
  double x_vir,gamma;

  double h_Hubble=((double *)ADaPS_fetch(cosmo,"h_Hubble"))[0];
  double Omega_M =((double *)ADaPS_fetch(cosmo,"Omega_M"))[0];
  double redshift=z_of_a(expansion_factor);

  Delta=Delta_vir(redshift,cosmo);
  Omega=1.;

  // Initialize properties
  properties->id_MBP         =id_i_fctn(params,0);//id_array[index_MBP];
  properties->n_particles    =n_particles;
  properties->position_COM[0]=0.;
  properties->position_COM[1]=0.;
  properties->position_COM[2]=0.;
  properties->position_MBP[0]=(float)p_i_fctn(params,0,0);//(x_array[index_MBP]);
  properties->position_MBP[1]=(float)p_i_fctn(params,1,0);//(y_array[index_MBP]);
  properties->position_MBP[2]=(float)p_i_fctn(params,2,0);//(z_array[index_MBP]);
  properties->velocity_COM[0]=0.;
  properties->velocity_COM[1]=0.;
  properties->velocity_COM[2]=0.;
  properties->velocity_MBP[0]=(float)v_i_fctn(params,0,0);//(vx_array[index_MBP]);
  properties->velocity_MBP[1]=(float)v_i_fctn(params,1,0);//(vy_array[index_MBP]);
  properties->velocity_MBP[2]=(float)v_i_fctn(params,2,0);//(vz_array[index_MBP]);
  properties->M_vir          =0.;
  properties->R_vir          =0.;
  properties->R_halo         =0.;
  properties->R_max          =0.;
  properties->V_max          =0.;
  properties->sigma_v        =0.;
  properties->spin[0]        =0.;
  properties->spin[1]        =0.;
  properties->spin[2]        =0.;
  properties->q_triaxial     =1.;
  properties->s_triaxial     =1.;
  for(i=0;i<3;i++){
    for(j=0;j<3;j++)
      properties->shape_eigen_vectors[i][j]=0.;
    properties->shape_eigen_vectors[i][i]=1.;
  }

  // Set the number of profile bins and the number of particles per bin
  profile->n_bins=MAX(MIN_PROFILE_BINS,MIN((int)((6.2*log10((double)n_particles)-3.5)+((double)n_particles/1000.)+1),MAX_PROFILE_BINS));
  n_per_bin      =(double)(n_particles)/(double)profile->n_bins;

  // There's nothing to do if there are no particles
  if(n_particles==0)
    profile->n_bins=0;
  else{
    // Create a v_c(0)=0 bin
    r_c[0]=0.;
    v_c[0]=0.;

    // Initialize profiles
    for(i_bin=0;i_bin<profile->n_bins;i_bin++){
      profile->bins[i_bin].r_med           =0.;
      profile->bins[i_bin].r_max           =0.;
      profile->bins[i_bin].n_particles     =0;
      profile->bins[i_bin].M_r             =0.;
      profile->bins[i_bin].rho             =0.;
      profile->bins[i_bin].overdensity     =0.;
      profile->bins[i_bin].position_COM[0] =0.;
      profile->bins[i_bin].position_COM[1] =0.;
      profile->bins[i_bin].position_COM[2] =0.;
      profile->bins[i_bin].velocity_COM[0] =0.;
      profile->bins[i_bin].velocity_COM[1] =0.;
      profile->bins[i_bin].velocity_COM[2] =0.;
      profile->bins[i_bin].sigma_rad       =0.;
      profile->bins[i_bin].sigma_tan       =0.;
      profile->bins[i_bin].sigma_tot       =0.;
      profile->bins[i_bin].spin[0]         =0.;
      profile->bins[i_bin].spin[1]         =0.;
      profile->bins[i_bin].spin[2]         =0.;
      profile->bins[i_bin].q_triaxial      =1.;
      profile->bins[i_bin].s_triaxial      =1.;
      for(i=0;i<3;i++){
        for(j=0;j<3;j++)
          profile->bins[i_bin].shape_eigen_vectors[i][j]=0.;
        profile->bins[i_bin].shape_eigen_vectors[i][i]=1.;
      }
    }

    // Fill temporary arrays for particle positions, radii (all w.r.t MBP) and velocities
    //   Also, enforce periodic box on particle positions
    double x_cen;
    double y_cen;
    double z_cen;
    x_cen=(double)properties->position_MBP[0];
    y_cen=(double)properties->position_MBP[1];
    z_cen=(double)properties->position_MBP[2];
    if(flag_manual_centre){
       double x_cen_manual;
       double y_cen_manual;
       double z_cen_manual;
       // Compute a rough comoving centre
       for(j_particle=0;j_particle<n_particles;j_particle++){
         x[j_particle]=d_periodic(p_i_fctn(params,0,j_particle)-x_cen,box_size);//(double)(x_array[k_particle])-x_cen,box_size);
         y[j_particle]=d_periodic(p_i_fctn(params,1,j_particle)-y_cen,box_size);//(double)(y_array[k_particle])-y_cen,box_size);
         z[j_particle]=d_periodic(p_i_fctn(params,2,j_particle)-z_cen,box_size);//(double)(z_array[k_particle])-z_cen,box_size);
       }
       // Refine it with shrinking spheres
       int n_iterations;
       n_iterations=compute_centroid3D(NULL,
                                       x,
                                       y,
                                       z,
                                       n_particles,
                                       1e-3, // 1 kpc
                                       0.75,
                                       30,
                                       CENTROID3D_MODE_FACTOR|CENTROID3D_MODE_INPLACE,
                                       &x_cen_manual,
                                       &y_cen_manual,
                                       &z_cen_manual);
       x_cen+=x_cen_manual;
       y_cen+=y_cen_manual;
       z_cen+=z_cen_manual;
       properties->position_MBP[0]=x_cen;
       properties->position_MBP[1]=y_cen;
       properties->position_MBP[2]=z_cen;
       if(properties->position_MBP[0]< box_size) properties->position_MBP[0]+=box_size;
       if(properties->position_MBP[1]< box_size) properties->position_MBP[1]+=box_size;
       if(properties->position_MBP[2]< box_size) properties->position_MBP[2]+=box_size;
       if(properties->position_MBP[0]>=box_size) properties->position_MBP[0]-=box_size;
       if(properties->position_MBP[1]>=box_size) properties->position_MBP[1]-=box_size;
       if(properties->position_MBP[2]>=box_size) properties->position_MBP[2]-=box_size;
    }
    
    for(j_particle=0;j_particle<n_particles;j_particle++){
      // ... halo-centric particle positions ...
      x[j_particle]=expansion_factor*d_periodic(p_i_fctn(params,0,j_particle)-x_cen,box_size);//((double)x_array[k_particle])-x_cen,box_size);
      y[j_particle]=expansion_factor*d_periodic(p_i_fctn(params,1,j_particle)-y_cen,box_size);//((double)y_array[k_particle])-y_cen,box_size);
      z[j_particle]=expansion_factor*d_periodic(p_i_fctn(params,2,j_particle)-z_cen,box_size);//((double)z_array[k_particle])-z_cen,box_size);

      // ... velocities ...
      vx[j_particle]=v_i_fctn(params,0,j_particle);//(double)(vx_array[k_particle]);
      vy[j_particle]=v_i_fctn(params,1,j_particle);//(double)(vy_array[k_particle]);
      vz[j_particle]=v_i_fctn(params,2,j_particle);//(double)(vz_array[k_particle]);

      // ... particle radii ...
      R[j_particle]=sqrt(x[j_particle]*x[j_particle]+y[j_particle]*y[j_particle]+z[j_particle]*z[j_particle]);
    }
    
    // Sort particles by radius
    merge_sort((void *)R,(size_t)n_particles,R_index_in,SID_DOUBLE,SORT_COMPUTE_INDEX,SORT_COMPUTE_NOT_INPLACE);
    R_index=(*R_index_in);

    // Use the average of the central 30 particles for the MBP velocity if we are
    //    manually computing centres
    if(flag_manual_centre){
       double vx_cen_temp=0.;
       double vy_cen_temp=0.;
       double vz_cen_temp=0.;
       int    n_cen =0;
       for(i_particle=0;i_particle<MIN(30,n_particles);i_particle++){
          vx_cen_temp+=vx[i_particle];
          vy_cen_temp+=vy[i_particle];
          vz_cen_temp+=vz[i_particle];
          n_cen++;
       }
       properties->velocity_MBP[0]=vx_cen_temp/(double)n_cen;
       properties->velocity_MBP[1]=vy_cen_temp/(double)n_cen;
       properties->velocity_MBP[2]=vz_cen_temp/(double)n_cen;
    }

    // We need the COM velocity at R_vir before we can get halo centric velocities.  Thus,
    //   we need the overdensity profile first
    x_COM_accumulator  =0.;
    y_COM_accumulator  =0.;
    z_COM_accumulator  =0.;
    vx_COM_accumulator =0.;
    vy_COM_accumulator =0.;
    vz_COM_accumulator =0.;
    V2                 =0.;
    n_cumulative       =0;
    for(i_bin=0,i_particle=0;i_bin<profile->n_bins;i_bin++,i_particle+=n_in_bin){

      V1=V2; // Volumes

      // ... particle numbers ...
      if(i_bin<profile->n_bins-1)
        n_in_bin=(int)((double)(i_bin+1)*n_per_bin)-i_particle;
      else
        n_in_bin=n_particles-i_particle;
      n_cumulative                    +=n_in_bin;
      profile->bins[i_bin].n_particles =n_in_bin;

      // ... mass profile ...
      profile->bins[i_bin].M_r=particle_mass*(double)n_cumulative;

      // ... binning radii ...
      if(n_in_bin%2==1)
        profile->bins[i_bin].r_med=(float)R[R_index[i_particle+n_in_bin/2]];
      else
        profile->bins[i_bin].r_med=0.5*(float)(R[R_index[i_particle+n_in_bin/2-1]]+R[R_index[i_particle+n_in_bin/2]]);
      profile->bins[i_bin].r_max=(float)R[R_index[i_particle+n_in_bin-1]];

      // ... COM positions and velocities ...
      for(j_particle=0;j_particle<n_in_bin;j_particle++){
        k_particle=R_index[i_particle+j_particle];
        x_COM_accumulator += x[k_particle];
        y_COM_accumulator += y[k_particle];
        z_COM_accumulator += z[k_particle];
        vx_COM_accumulator+=vx[k_particle];
        vy_COM_accumulator+=vy[k_particle];
        vz_COM_accumulator+=vz[k_particle];
      }
      profile->bins[i_bin].position_COM[0]=(float)(x_COM_accumulator/(double)n_cumulative);
      profile->bins[i_bin].position_COM[1]=(float)(y_COM_accumulator/(double)n_cumulative);
      profile->bins[i_bin].position_COM[2]=(float)(z_COM_accumulator/(double)n_cumulative);
      profile->bins[i_bin].velocity_COM[0]=(float)(vx_COM_accumulator/(double)n_cumulative);
      profile->bins[i_bin].velocity_COM[1]=(float)(vy_COM_accumulator/(double)n_cumulative);
      profile->bins[i_bin].velocity_COM[2]=(float)(vz_COM_accumulator/(double)n_cumulative);

      // ... density ...
      V2=FOUR_THIRDS_PI*profile->bins[i_bin].r_max*profile->bins[i_bin].r_max*profile->bins[i_bin].r_max; // Volume
      dV=V2-V1;
      dM=particle_mass*(double)n_in_bin;
      profile->bins[i_bin].rho        =(float)(dM/dV);
      profile->bins[i_bin].overdensity=(float)(profile->bins[i_bin].M_r/(V2*Omega*rho_crit_z(redshift,cosmo)));

      /// ... triaxiality ...
      if(flag_compute_shapes){
         compute_triaxiality(x,
                             y,
                             z,
                             (double)profile->bins[i_bin].position_COM[0],
                             (double)profile->bins[i_bin].position_COM[1],
                             (double)profile->bins[i_bin].position_COM[2],
                             box_size,
                             n_cumulative,
                             R_index,
                             shape_eigen_values,
                             shape_eigen_vectors);
         profile->bins[i_bin].q_triaxial=(float)(shape_eigen_values[1]/shape_eigen_values[0]);
         profile->bins[i_bin].s_triaxial=(float)(shape_eigen_values[2]/shape_eigen_values[0]);
         for(i=0;i<3;i++)
           for(j=0;j<3;j++)
             profile->bins[i_bin].shape_eigen_vectors[i][j]=(float)shape_eigen_vectors[i][j];
      }
    }

    // Interpolate to get R_vir
    flag_interpolated=FALSE;
    properties->R_halo=profile->bins[profile->n_bins-1].r_max;
    if(profile->n_bins>1){

      // Remove any small-radius monotonic increases from the interpolation interval
      j_profile=0;
      while(profile->bins[j_profile].overdensity<=profile->bins[j_profile+1].overdensity && j_profile<profile->n_bins-2)
        j_profile++;

      // Only keep decreasing bins
      n_bins_temp=0;
      r_interp[n_bins_temp]=take_log10((double)profile->bins[j_profile].r_max);
      y_interp[n_bins_temp]=take_log10((double)profile->bins[j_profile].overdensity);
      n_bins_temp++;
      for(i_profile=j_profile+1;i_profile<profile->n_bins;i_profile++){
        if(take_log10((double)profile->bins[i_profile].overdensity)<y_interp[n_bins_temp-1]){
          r_interp[n_bins_temp]=take_log10((double)profile->bins[i_profile].r_max);
          y_interp[n_bins_temp]=take_log10((double)profile->bins[i_profile].overdensity);
          n_bins_temp++;
        }
      }

      if(n_bins_temp>1){
        // Perform interpolation
        if(y_interp[0]>=take_log10(Delta) && y_interp[n_bins_temp-1]<=take_log10(Delta)){
          if(n_bins_temp>9)
            interp_type=gsl_interp_cspline;
          else
            interp_type=gsl_interp_linear;
          interp_type=gsl_interp_linear;
          init_interpolate(y_interp,r_interp,n_bins_temp,interp_type,&vir_interpolate);
          properties->R_vir       =(float)take_alog10(interpolate(vir_interpolate,take_log10(Delta)));
          free_interpolate(SID_FARG vir_interpolate,NULL);
          flag_interpolated=TRUE;
        }
        else if(y_interp[0]<take_log10(Delta)){
          properties->R_vir=(float)take_alog10(r_interp[0]);
          flag_interpolated=FLAG_INTERP_MIN_BIN;
        }
        else{
          properties->R_vir=(float)take_alog10(r_interp[n_bins_temp-1]);
          flag_interpolated=FLAG_INTERP_MAX_BIN;
        }
      }
      else{
        properties->R_vir=(float)take_alog10(r_interp[0]);
        flag_interpolated=FLAG_INTERP_MIN_BIN;
      }
    }
    else{
      properties->R_vir=profile->bins[0].r_max; 
      flag_interpolated=FLAG_INTERP_MIN_BIN;
    }

    // Set the interpolation method
    if(n_bins_temp>9)
      interp_type=gsl_interp_cspline;
    else
      interp_type=gsl_interp_linear;
    interp_type=gsl_interp_linear;

    // Compute v_COM(R_vir)
    for(i_profile=0;i_profile<profile->n_bins;i_profile++)
      r_interp[i_profile]=(double)profile->bins[i_profile].r_max;
    if(flag_interpolated==TRUE){
      for(i_profile=0;i_profile<profile->n_bins;i_profile++)
        y_interp[i_profile]=(double)profile->bins[i_profile].velocity_COM[0];
      init_interpolate(r_interp,y_interp,profile->n_bins,interp_type,&vir_interpolate);
      properties->velocity_COM[0]=(float)interpolate(vir_interpolate,properties->R_vir);
      free_interpolate(SID_FARG vir_interpolate,NULL);
      for(i_profile=0;i_profile<profile->n_bins;i_profile++)
        y_interp[i_profile]=(double)profile->bins[i_profile].velocity_COM[1];
      init_interpolate(r_interp,y_interp,profile->n_bins,interp_type,&vir_interpolate);
      properties->velocity_COM[1]=(float)interpolate(vir_interpolate,properties->R_vir);
      free_interpolate(SID_FARG vir_interpolate,NULL);
      for(i_profile=0;i_profile<profile->n_bins;i_profile++)
        y_interp[i_profile]=(double)profile->bins[i_profile].velocity_COM[2];
      init_interpolate(r_interp,y_interp,profile->n_bins,interp_type,&vir_interpolate);
      properties->velocity_COM[2]=(float)interpolate(vir_interpolate,properties->R_vir);
      free_interpolate(SID_FARG vir_interpolate,NULL);
    }
    else{
      if(flag_interpolated==FLAG_INTERP_MIN_BIN)      i_profile=0;
      else if(flag_interpolated==FLAG_INTERP_MAX_BIN) i_profile=profile->n_bins-1;
      else SID_trap_error("Unrecognized value for flag_interpolated {%d}.",flag_interpolated);
      properties->velocity_COM[0]=(float)profile->bins[i_profile].velocity_COM[0];
      properties->velocity_COM[1]=(float)profile->bins[i_profile].velocity_COM[1];
      properties->velocity_COM[2]=(float)profile->bins[i_profile].velocity_COM[2];
    }

    // Compute halo-centric particle velocities
    //   Subtract COM mean and add Hubble flow
    for(j_particle=0;j_particle<n_particles;j_particle++){
      vx[j_particle]+=x[j_particle]*H_convert(H_z(redshift,cosmo))-(double)properties->velocity_COM[0];
      vy[j_particle]+=y[j_particle]*H_convert(H_z(redshift,cosmo))-(double)properties->velocity_COM[1];
      vz[j_particle]+=z[j_particle]*H_convert(H_z(redshift,cosmo))-(double)properties->velocity_COM[2];
    }

    // Compute remaining profiles ...
    spin_x_accumulator=0.;
    spin_y_accumulator=0.;
    spin_z_accumulator=0.;
    V2                =0.;
    n_cumulative      =0;
    for(i_bin=0,i_particle=0;i_bin<profile->n_bins;i_bin++,i_particle+=n_in_bin){

      V1=V2; // Volumes

      // ... particle numbers ...
      if(i_bin<profile->n_bins-1)
        n_in_bin=(int)((double)(i_bin+1)*n_per_bin)-i_particle;
      else
        n_in_bin=n_particles-i_particle;
      n_cumulative+=n_in_bin;

      // ... spins and mean velocities ...
      v_x_mean  =0.;
      v_y_mean  =0.;
      v_z_mean  =0.;
      v_rad_mean=0.;
      for(j_particle=0;j_particle<n_in_bin;j_particle++){
        k_particle=R_index[i_particle+j_particle];
      
        // ... spins ...
        spin_x_accumulator+=(double)(y[k_particle]*vz[k_particle]-z[k_particle]*vy[k_particle]);
        spin_y_accumulator+=(double)(z[k_particle]*vx[k_particle]-x[k_particle]*vz[k_particle]);
        spin_z_accumulator+=(double)(x[k_particle]*vy[k_particle]-y[k_particle]*vx[k_particle]);

        // ... mean velocities (needed below for velocity dispersions) ...
        if(R[k_particle]>0.){
          v_rad      =(x[k_particle]*vx[k_particle]+y[k_particle]*vy[k_particle]+z[k_particle]*vz[k_particle])/R[k_particle];
          v_x_mean  +=vx[k_particle];
          v_y_mean  +=vy[k_particle];
          v_z_mean  +=vz[k_particle];
          v_rad_mean+=v_rad;
        }
      }
      profile->bins[i_bin].spin[0]=(float)(spin_x_accumulator)/n_cumulative;
      profile->bins[i_bin].spin[1]=(float)(spin_y_accumulator)/n_cumulative;
      profile->bins[i_bin].spin[2]=(float)(spin_z_accumulator)/n_cumulative;
      v_x_mean  /=(double)n_in_bin;
      v_y_mean  /=(double)n_in_bin;
      v_z_mean  /=(double)n_in_bin;
      v_rad_mean/=(double)n_in_bin;

      // ... velocity dispersions ...
      for(j_particle=0;j_particle<n_in_bin;j_particle++){
        k_particle=R_index[i_particle+j_particle];
        if(R[k_particle]>0.){
          v_tot=sqrt(pow(vx[k_particle]-v_x_mean,2.)+pow(vy[k_particle]-v_y_mean,2.)+pow(vz[k_particle]-v_z_mean,2.));
          v_rad=(x[k_particle]*(vx[k_particle]-v_x_mean)+y[k_particle]*(vy[k_particle]-v_y_mean)+z[k_particle]*(vz[k_particle]-v_z_mean))/R[k_particle];
          v_tan=sqrt(v_tot*v_tot-v_rad*v_rad);
          profile->bins[i_bin].sigma_tot+=(float)((v_tot)*(v_tot));
          profile->bins[i_bin].sigma_rad+=(float)((v_rad-v_rad_mean)*(v_rad-v_rad_mean));
          profile->bins[i_bin].sigma_tan+=(float)((v_tan)*(v_tan));
        }
      }
      profile->bins[i_bin].sigma_tot=(float)sqrt((double)profile->bins[i_bin].sigma_tot/(double)n_in_bin);
      profile->bins[i_bin].sigma_rad=(float)sqrt((double)profile->bins[i_bin].sigma_rad/(double)n_in_bin);
      profile->bins[i_bin].sigma_tan=(float)sqrt((double)profile->bins[i_bin].sigma_tan/(double)n_in_bin);
    
      // ... circular velocity; v_c(R) ...
      r_c[i_bin+1]=profile->bins[i_bin].r_max;
      v_c[i_bin+1]=sqrt(G_NEWTON*profile->bins[i_bin].M_r/(double)profile->bins[i_bin].r_max);
    }
    
    // Determine R_max and V_max from v_c(R)...
    R_max=(double)r_c[1]; // default for a monotonically increasing V_c(r)
    V_max=(double)v_c[1]; // default for a monotonically increasing V_c(r)
    if(profile->n_bins>1){

      // Remove any large-radius monotonic increases from the interpolation interval
      k_profile=profile->n_bins;
      while(v_c[k_profile-1]<=v_c[k_profile] && k_profile>1)
        k_profile--;
      if(v_c[0]<=v_c[1] && k_profile==1)
        k_profile--;

      // If the profile is not monotonically increasing ...
      if(k_profile>0){
        n_bins_temp=k_profile+1;
      
        // ...find the maximum (call its index j_profile)
        for(i_profile=0,j_profile=0;i_profile<n_bins_temp;i_profile++){
          if(v_c[i_profile]>v_c[j_profile])
            j_profile=i_profile;
        }

        // ...find bottom of range in which to search for maximum (call its index i_profile)
        i_profile=j_profile-1;
        while(v_c[i_profile]>=v_c[j_profile] && i_profile>0)
          i_profile--;
    
        // ...find top of range in which to search for maximum (call its index k_profile)
        k_profile=j_profile+1;
        while(v_c[k_profile]>=v_c[j_profile] && k_profile<n_bins_temp-1)
          k_profile++;

        //   ... perform interpolation
        V_max=(double)v_c[j_profile];
        R_max=(double)r_c[j_profile];
        if(i_profile<j_profile && j_profile<k_profile){
          if(n_bins_temp>9)
            interp_type=gsl_interp_cspline;
          else
            interp_type=gsl_interp_linear;
          interp_type=gsl_interp_linear;
          init_interpolate(r_c,v_c,n_bins_temp,gsl_interp_cspline,&V_R_interpolate);
          interpolate_maximum(V_R_interpolate,
                              r_c[i_profile],
                              r_c[j_profile],
                              r_c[k_profile],
                              0.05,
                              &R_max,
                              &V_max);
          free_interpolate(SID_FARG V_R_interpolate,NULL);
        }
      }
    }
    properties->R_max=(float)R_max;
    properties->V_max=(float)V_max;

    if(profile->n_bins>9)
      interp_type=gsl_interp_cspline;
    else
      interp_type=gsl_interp_linear;
    interp_type=gsl_interp_linear;

    // Perform normal interpolation from profiles to get the rest of the global quantities
    if(flag_interpolated==TRUE){
      //  ... COM positions ...
      for(i_profile=0;i_profile<profile->n_bins;i_profile++)
        y_interp[i_profile]=(double)profile->bins[i_profile].position_COM[0]/expansion_factor;
      init_interpolate(r_interp,y_interp,profile->n_bins,interp_type,&vir_interpolate);
      properties->position_COM[0]=(float)interpolate(vir_interpolate,properties->R_vir);
      free_interpolate(SID_FARG vir_interpolate,NULL);
      for(i_profile=0;i_profile<profile->n_bins;i_profile++)
        y_interp[i_profile]=(double)profile->bins[i_profile].position_COM[1]/expansion_factor;
      init_interpolate(r_interp,y_interp,profile->n_bins,interp_type,&vir_interpolate);
      properties->position_COM[1]=(float)interpolate(vir_interpolate,properties->R_vir);
      free_interpolate(SID_FARG vir_interpolate,NULL);
      for(i_profile=0;i_profile<profile->n_bins;i_profile++)
        y_interp[i_profile]=(double)profile->bins[i_profile].position_COM[2]/expansion_factor;
      init_interpolate(r_interp,y_interp,profile->n_bins,interp_type,&vir_interpolate);
      properties->position_COM[2]=(float)interpolate(vir_interpolate,properties->R_vir);
      free_interpolate(SID_FARG vir_interpolate,NULL);
      //  ... M_vir ...
      for(i_profile=0;i_profile<profile->n_bins;i_profile++)
        y_interp[i_profile]=(double)profile->bins[i_profile].M_r;
      init_interpolate(r_interp,y_interp,profile->n_bins,interp_type,&vir_interpolate);
      properties->M_vir=interpolate(vir_interpolate,properties->R_vir);
      free_interpolate(SID_FARG vir_interpolate,NULL);
      //  ... sigma_v ...
      for(i_profile=0;i_profile<profile->n_bins;i_profile++)
        y_interp[i_profile]=(double)profile->bins[i_profile].sigma_tot;
      init_interpolate(r_interp,y_interp,profile->n_bins,interp_type,&vir_interpolate);
      properties->sigma_v=(float)interpolate(vir_interpolate,properties->R_vir);
      free_interpolate(SID_FARG vir_interpolate,NULL);
      //   ... spin ...
      for(i_profile=0;i_profile<profile->n_bins;i_profile++)
        y_interp[i_profile]=(double)profile->bins[i_profile].spin[0];
      init_interpolate(r_interp,y_interp,profile->n_bins,interp_type,&vir_interpolate);
      properties->spin[0]=(float)interpolate(vir_interpolate,properties->R_vir);
      free_interpolate(SID_FARG vir_interpolate,NULL);
      for(i_profile=0;i_profile<profile->n_bins;i_profile++)
        y_interp[i_profile]=(double)profile->bins[i_profile].spin[1];
      init_interpolate(r_interp,y_interp,profile->n_bins,interp_type,&vir_interpolate);
      properties->spin[1]=(float)interpolate(vir_interpolate,properties->R_vir);
      free_interpolate(SID_FARG vir_interpolate,NULL);
      for(i_profile=0;i_profile<profile->n_bins;i_profile++)
        y_interp[i_profile]=(double)profile->bins[i_profile].spin[2];
      init_interpolate(r_interp,y_interp,profile->n_bins,interp_type,&vir_interpolate);
      properties->spin[2]=(float)interpolate(vir_interpolate,properties->R_vir);
      free_interpolate(SID_FARG vir_interpolate,NULL);
      //  ... triaxial axes ratios ...
      for(i_profile=0;i_profile<profile->n_bins;i_profile++)
        y_interp[i_profile]=(double)profile->bins[i_profile].q_triaxial;
      init_interpolate(r_interp,y_interp,profile->n_bins,interp_type,&vir_interpolate);
      properties->q_triaxial=(float)interpolate(vir_interpolate,properties->R_vir);
      free_interpolate(SID_FARG vir_interpolate,NULL);
      for(i_profile=0;i_profile<profile->n_bins;i_profile++)
        y_interp[i_profile]=(double)profile->bins[i_profile].s_triaxial;
      init_interpolate(r_interp,y_interp,profile->n_bins,interp_type,&vir_interpolate);
      properties->s_triaxial=(float)interpolate(vir_interpolate,properties->R_vir);
      free_interpolate(SID_FARG vir_interpolate,NULL);
      // ... shape eigen vectors ...
      for(i=0;i<3;i++){
        for(j=0;j<3;j++){
          for(i_profile=0;i_profile<profile->n_bins;i_profile++)
            y_interp[i_profile]=(double)cos(profile->bins[i_profile].shape_eigen_vectors[i][j]);
          init_interpolate(r_interp,y_interp,profile->n_bins,interp_type,&vir_interpolate);
          properties->shape_eigen_vectors[i][j]=(float)acos(MAX(0,MIN(1.,interpolate(vir_interpolate,properties->R_vir))));
          free_interpolate(SID_FARG vir_interpolate,NULL);
        }
        norm=sqrt(properties->shape_eigen_vectors[i][0]*properties->shape_eigen_vectors[i][0]+
                  properties->shape_eigen_vectors[i][1]*properties->shape_eigen_vectors[i][1]+
                  properties->shape_eigen_vectors[i][2]*properties->shape_eigen_vectors[i][2]);
        for(j=0;j<3;j++)
          properties->shape_eigen_vectors[i][j]/=norm;
      }
    }
    // ... else apply defaults to faulty cases.
    else{ 
      if(flag_interpolated==FLAG_INTERP_MIN_BIN)      i_profile=0;
      else if(flag_interpolated==FLAG_INTERP_MAX_BIN) i_profile=profile->n_bins-1;
      else SID_trap_error("Unrecognized value for flag_interpolated {%d}.",flag_interpolated);

      //  ... COM positions ...
      properties->position_COM[0]=(double)(profile->bins[i_profile].position_COM[0])/expansion_factor;
      properties->position_COM[1]=(double)(profile->bins[i_profile].position_COM[1])/expansion_factor;
      properties->position_COM[2]=(double)(profile->bins[i_profile].position_COM[2])/expansion_factor;
      //  ... M_vir ...
      properties->M_vir=(double)profile->bins[i_profile].M_r;
      //  ... sigma_v ...
      properties->sigma_v=(float)profile->bins[i_profile].sigma_tot;
      //   ... spin ...
      properties->spin[0]=(float)profile->bins[i_profile].spin[0];
      properties->spin[1]=(float)profile->bins[i_profile].spin[1];
      properties->spin[2]=(float)profile->bins[i_profile].spin[2];
      //  ... triaxial axes ratios ...
      properties->q_triaxial=(float)profile->bins[i_profile].q_triaxial;
      properties->s_triaxial=(float)profile->bins[i_profile].s_triaxial;
      // ... shape eigen vectors ...
      for(i=0;i<3;i++){
        for(j=0;j<3;j++)
          properties->shape_eigen_vectors[i][j]=(float)profile->bins[i_profile].shape_eigen_vectors[i][j];
        norm=sqrt(properties->shape_eigen_vectors[i][0]*properties->shape_eigen_vectors[i][0]+
                  properties->shape_eigen_vectors[i][1]*properties->shape_eigen_vectors[i][1]+
                  properties->shape_eigen_vectors[i][2]*properties->shape_eigen_vectors[i][2]);
        for(j=0;j<3;j++)
          properties->shape_eigen_vectors[i][j]/=norm;
      }
    }

    // Enforce periodic box on COM position
    properties->position_COM[0]+=x_cen;
    properties->position_COM[1]+=y_cen;
    properties->position_COM[2]+=z_cen;
    if(properties->position_COM[0]< box_size) properties->position_COM[0]+=box_size;
    if(properties->position_COM[1]< box_size) properties->position_COM[1]+=box_size;
    if(properties->position_COM[2]< box_size) properties->position_COM[2]+=box_size;
    if(properties->position_COM[0]>=box_size) properties->position_COM[0]-=box_size;
    if(properties->position_COM[1]>=box_size) properties->position_COM[1]-=box_size;
    if(properties->position_COM[2]>=box_size) properties->position_COM[2]-=box_size;

    // Perform unit conversions
    //   ... properties first ...
    properties->position_COM[0]*=h_Hubble/M_PER_MPC;
    properties->position_COM[1]*=h_Hubble/M_PER_MPC;
    properties->position_COM[2]*=h_Hubble/M_PER_MPC;
    properties->position_MBP[0]*=h_Hubble/M_PER_MPC;
    properties->position_MBP[1]*=h_Hubble/M_PER_MPC;
    properties->position_MBP[2]*=h_Hubble/M_PER_MPC;
    properties->velocity_COM[0]*=1e-3;
    properties->velocity_COM[1]*=1e-3;
    properties->velocity_COM[2]*=1e-3;
    properties->velocity_MBP[0]*=1e-3;
    properties->velocity_MBP[1]*=1e-3;
    properties->velocity_MBP[2]*=1e-3;
    properties->M_vir          *=h_Hubble/M_SOL;
    properties->R_vir          *=h_Hubble/M_PER_MPC;
    properties->R_halo         *=h_Hubble/M_PER_MPC;
    properties->R_max          *=h_Hubble/M_PER_MPC;
    properties->V_max          *=1e-3;
    properties->sigma_v        *=1e-3;
    properties->spin[0]        *=1e-3*h_Hubble/M_PER_MPC;
    properties->spin[1]        *=1e-3*h_Hubble/M_PER_MPC;
    properties->spin[2]        *=1e-3*h_Hubble/M_PER_MPC;

    //   ... then profiles ...
    for(i_bin=0;i_bin<profile->n_bins;i_bin++){
      profile->bins[i_bin].r_med          *=h_Hubble/M_PER_MPC;
      profile->bins[i_bin].r_max          *=h_Hubble/M_PER_MPC;
      profile->bins[i_bin].M_r            *=h_Hubble/M_SOL;
      profile->bins[i_bin].rho            *=M_PER_MPC*M_PER_MPC*M_PER_MPC/(h_Hubble*h_Hubble*M_SOL);
      profile->bins[i_bin].position_COM[0]*=h_Hubble/M_PER_MPC;
      profile->bins[i_bin].position_COM[1]*=h_Hubble/M_PER_MPC;
      profile->bins[i_bin].position_COM[2]*=h_Hubble/M_PER_MPC;
      profile->bins[i_bin].velocity_COM[0]*=1e-3;
      profile->bins[i_bin].velocity_COM[1]*=1e-3;
      profile->bins[i_bin].velocity_COM[2]*=1e-3;
      profile->bins[i_bin].sigma_rad      *=1e-3;
      profile->bins[i_bin].sigma_tan      *=1e-3;
      profile->bins[i_bin].sigma_tot      *=1e-3;
      profile->bins[i_bin].spin[0]        *=1e-3*h_Hubble/M_PER_MPC;
      profile->bins[i_bin].spin[1]        *=1e-3*h_Hubble/M_PER_MPC;
      profile->bins[i_bin].spin[2]        *=1e-3*h_Hubble/M_PER_MPC;
    }
  
  }

  return(flag_interpolated);
}
Example #9
0
double bias_model(double x_in, double delta_c, double z, cosmo_info **cosmo, int mode) {
    // Decide what the input is
    int    flag_Vmax_ordinate = SID_CHECK_BITFIELD_SWITCH(mode, BIAS_MODEL_VMAX_ORDINATE);
    double M_R;
    double V_max;
    if(flag_Vmax_ordinate)
        V_max = x_in;
    else
        M_R = x_in;

    double bias;
    int    flag_done = GBP_FALSE;

    // Tinker et al 2010
    if(SID_CHECK_BITFIELD_SWITCH(mode, BIAS_MODEL_TRK)) {
        if(flag_done)
            SID_exit_error("Mode flag (%d) is invalid in bias_model().  Multiple model definitions.", SID_ERROR_LOGIC,
                           mode);
        flag_done = GBP_TRUE;
        if(flag_Vmax_ordinate)
            M_R = Vmax_to_Mvir_NFW(V_max, z, NFW_MODE_DEFAULT, cosmo);
        double y     = take_log10(Delta_vir(z, *cosmo));
        double A     = 1. + 0.24 * y * exp(-pow(4. / y, 4.));
        double B     = 0.183;
        double C     = 0.019 + 0.107 * y + 0.19 * exp(-pow(4. / y, 4.));
        double a     = 0.44 * y - 0.88;
        double b     = 1.5;
        double c     = 2.4;
        double sigma = sigma_M(cosmo, M_R, z, PSPEC_LINEAR_TF, PSPEC_ALL_MATTER);
        double nu    = delta_c / sigma;
        bias         = 1. - A * pow(nu, a) / (pow(nu, a) + pow(delta_c, a)) + B * pow(nu, b) + C * pow(nu, c);
    }
    // Basilakos and Plionis (2001;2003) w/ Papageorgiou et al 2013 coeeficients
    if(SID_CHECK_BITFIELD_SWITCH(mode, BIAS_MODEL_BPR)) {
        if(flag_done)
            SID_exit_error("Mode flag (%d) is invalid in bias_model().  Multiple model definitions.", SID_ERROR_LOGIC,
                           mode);
        flag_done = GBP_TRUE;
        if(flag_Vmax_ordinate)
            M_R = Vmax_to_Mvir_NFW(V_max, z, NFW_MODE_DEFAULT, cosmo);
        double alpha_1 = 4.53;
        double alpha_2 = -0.41;
        double beta_1  = 0.37;
        double beta_2  = 0.36;
        double I_z;
        double C_1;
        double C_2;
        double Omega_M, Omega_k, Omega_Lambda, h_Hubble;
        double Ez;
        Omega_M      = ((double *)ADaPS_fetch(*cosmo, "Omega_M"))[0];
        Omega_k      = ((double *)ADaPS_fetch(*cosmo, "Omega_k"))[0];
        Omega_Lambda = ((double *)ADaPS_fetch(*cosmo, "Omega_Lambda"))[0];
        h_Hubble     = ((double *)ADaPS_fetch(*cosmo, "h_Hubble"))[0];
        Ez           = E_z(Omega_M, Omega_k, Omega_Lambda, z);
        I_z          = bias_model_BPR_integral(cosmo, z);
        C_1          = alpha_1 * pow(M_R / (1e13 * M_SOL / h_Hubble), beta_1);
        C_2          = alpha_2 * pow(M_R / (1e13 * M_SOL / h_Hubble), beta_2);
        bias         = (C_1 + C_2 * I_z) * Ez + 1.;
    }
    // Poole et al 2014
    if(SID_CHECK_BITFIELD_SWITCH(mode, BIAS_MODEL_POOLE_HALO)) {
        if(flag_done)
            SID_exit_error("Mode flag (%d) is invalid in bias_model().  Multiple model definitions.", SID_ERROR_LOGIC,
                           mode);
        flag_done = GBP_TRUE;
        if(!flag_Vmax_ordinate)
            V_max = V_max_NFW(M_R, z, NFW_MODE_DEFAULT, cosmo) * 1e-3;
        else
            V_max *= 1e-3;
        double V_SF_o;
        double V_SF_z;
        double s_V_o;
        double s_V_z;
        double b_o_o;
        double b_o_z;
        double b_V_o;
        double b_V_z;
        if(SID_CHECK_BITFIELD_SWITCH(mode, BIAS_MODEL_POOLE_SUBSTRUCTURE)) {
            V_SF_o = 5.326176e-02;
            V_SF_z = -1.673868e-01;
            s_V_o  = 4.026941e-01;
            s_V_z  = 6.096567e-01;
            b_o_o  = -1.974311e-01;
            b_o_z  = 2.138219e-01;
            b_V_o  = 2.707540e-01;
            b_V_z  = 8.202001e-02;
        } else {
            V_SF_o = 2.819063e-02;
            V_SF_z = -1.381993e-01;
            s_V_o  = 3.685953e-01;
            s_V_z  = 6.154695e-01;
            b_o_o  = -3.793559e-01;
            b_o_z  = 3.074326e-01;
            b_V_o  = 3.147507e-01;
            b_V_z  = 6.072666e-02;
        }
        double b_o  = b_o_o + b_o_z * z;
        double b_V  = (b_V_o + b_V_z * z) / 220.;
        double V_SF = take_alog10(V_SF_o + V_SF_z * z) * 220.;
        double s_V  = (s_V_o + s_V_z * z) / 220.;
        double s    = s_V * fabs(V_max - V_SF);
        bias        = take_alog10(0.5 * (b_o + b_V * V_max));
    }
    if(SID_CHECK_BITFIELD_SWITCH(mode, BIAS_MODEL_POOLE_ZSPACE)) {
        if(flag_done)
            SID_exit_error("Mode flag (%d) is invalid in bias_model().  Multiple model definitions.", SID_ERROR_LOGIC,
                           mode);
        flag_done = GBP_TRUE;
        if(!flag_Vmax_ordinate)
            V_max = V_max_NFW(M_R, z, NFW_MODE_DEFAULT, cosmo) * 1e-3;
        else
            V_max *= 1e-3;
        double V_SF_o;
        double V_SF_z;
        double s_V_o;
        double s_V_zz;
        double b_o_o;
        double b_o_zz;
        double b_V_o;
        double b_V_z;
        double z_b_c;
        if(SID_CHECK_BITFIELD_SWITCH(mode, BIAS_MODEL_POOLE_SUBSTRUCTURE)) {
            V_SF_o = 3.173152e-01;
            V_SF_z = -1.599133e-01;
            s_V_o  = 5.344408e-01;
            s_V_zz = 7.102406e-02;
            b_o_o  = 2.198795e-01;
            b_o_zz = -3.749491e-02;
            b_V_o  = -4.628602e-02;
            b_V_z  = -1.832620e-02;
            z_b_c  = 9.292014e-01;
        } else {
            V_SF_o = 3.100167e-01;
            V_SF_z = -2.026411e-01;
            s_V_o  = 3.342258e-01;
            s_V_zz = 9.233431e-02;
            b_o_o  = 2.206163e-01;
            b_o_zz = -4.419126e-02;
            b_V_o  = -4.804747e-02;
            b_V_z  = -1.454479e-02;
            z_b_c  = 7.852721e-01;
        }
        double b_o  = b_o_o + b_o_zz * (z - z_b_c) * (z - z_b_c);
        double b_V  = (b_V_o + b_V_z * z) / 220.;
        double V_SF = 220. * take_alog10(V_SF_o + V_SF_z * z);
        double s_V  = (s_V_o + s_V_zz * z * z) / 220.;
        double s    = s_V * fabs(V_max - V_SF);
        bias        = take_alog10(0.5 * (b_o + b_V * V_max));
    }
    if(SID_CHECK_BITFIELD_SWITCH(mode, BIAS_MODEL_POOLE_TOTAL)) {
        if(flag_done)
            SID_exit_error("Mode flag (%d) is invalid in bias_model().  Multiple model definitions.", SID_ERROR_LOGIC,
                           mode);
        flag_done = GBP_TRUE;
        if(!flag_Vmax_ordinate)
            V_max = V_max_NFW(M_R, z, NFW_MODE_DEFAULT, cosmo) * 1e-3;
        else
            V_max *= 1e-3;
        double V_SF_o;
        double V_SF_z;
        double s_V_o;
        double s_V_z;
        double b_o_o;
        double b_o_z;
        double b_V_o;
        double b_V_z;
        if(SID_CHECK_BITFIELD_SWITCH(mode, BIAS_MODEL_POOLE_SUBSTRUCTURE)) {
            V_SF_o = 2.128681e-01;
            V_SF_z = -2.280569e-01;
            s_V_o  = 1.118792e+00;
            s_V_z  = 6.121383e-01;
            b_o_o  = 1.198136e-02;
            b_o_z  = 2.112670e-01;
            b_V_o  = 2.153513e-01;
            b_V_z  = 7.763461e-02;
        } else {
            V_SF_o = 2.041659e-01;
            V_SF_z = -2.966696e-01;
            s_V_o  = 9.408169e-01;
            s_V_z  = 4.514711e-01;
            b_o_o  = -1.534952e-01;
            b_o_z  = 2.799483e-01;
            b_V_o  = 2.547096e-01;
            b_V_z  = 6.760491e-02;
        }
        double b_o  = b_o_o + b_o_z * z;
        double b_V  = (b_V_o + b_V_z * z) / 220.;
        double V_SF = V_SF_o + V_SF_z * z;
        double s_V  = (s_V_o + s_V_z * z) / 220.;
        double s    = s_V * fabs(V_max - V_SF);
        bias        = take_alog10(0.5 * (b_o + b_V * V_max));
    }
    if(!flag_done)
        SID_exit_error("Mode flag (%d) is invalid in bias_model().  No model definition.", SID_ERROR_LOGIC, mode);
    // Apply the Kaiser '87 model to whatever model has been processed above.  Be careful, there
    //   are some mode flags (such as BIAS_MODE_POOLE_ZSPACE) for which this does not make sence
    //   and we presently don't check for this.
    if(SID_CHECK_BITFIELD_SWITCH(mode, BIAS_MODEL_KAISER_BOOST)) {
        double Omega_M_z = Omega_z(z, (*cosmo));
        double f         = pow(Omega_M_z, 0.55);
        double beta      = f / bias;
        double boost     = pow(1. + TWO_THIRDS * beta + 0.2 * beta * beta, 0.5);
        bias             = boost;
    }
    if(SID_CHECK_BITFIELD_SWITCH(mode, BIAS_MODEL_KAISER)) {
        double Omega_M_z = Omega_z(z, (*cosmo));
        double f         = pow(Omega_M_z, 0.55);
        double beta      = f / bias;
        double boost     = pow(1. + TWO_THIRDS * beta + 0.2 * beta * beta, 0.5);
        bias *= boost;
    }
    return (bias);
}