gbmodes.c 16.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/*
  gbmodes (ver. 5.6) -- Analyze multimodality in univariate data
  data using direct (and slow) kernel computation with Silverman
  method and, when applicable, Hall York corrections.

  Copyright (C) 2004-2014 Giulio Bottazzi

  This program is free software; you can redistribute it and/or
  modify it under the terms of the GNU General Public License
  (version 2) as published by the Free Software Foundation;
  
  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
  
  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
19
  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
*/

#include "tools.h"

#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>


/* =========================================== */
/* 1 - Kernels                                 */
/* =========================================== */


/* K(x) = exp(-x^2/(2 \pi))/sqrt(2 \pi) */
/* ------------------------------------ */
double Kgauss_rng(const gsl_rng * rng)
{
  return(gsl_ran_ugaussian (rng));
}

/* K(x) = exp(-sqrt(2) |x|)/sqrt(2) */
/* -------------------------------- */
double Klaplace_rng(const gsl_rng * rng)
{
  return(gsl_ran_laplace (rng,M_SQRT1_2));
}
/* =========================================== */


/* =========================================== */
/* 2 - Functions                               */
/* =========================================== */


/* Counts the modes and Find the modal values  */
/* ------------------------------------------- */

/* Input:
   data   list of observations
   size   number of observations
   min    lower bound of the range where to search
   max    upper bound of the range where to search
   N      number of equispaced points
   h      bandwidth
   K      kernel

   Output:
   modes_pos      if not NULL position of modes
   modes_height   if not NULL height of modes

   modes  number of modes
 */

unsigned findmodes(const double *data, size_t size,
	       const double min, const double max, const unsigned N,
	       const double h, double (*K) (double),
	       double **modes_pos, double **modes_height)
{
  unsigned i,modes;
  const double delta = (max-min)/((double) N-1.0);

  /* the kernel estimate */
  double * x = my_alloc(N*sizeof(double));

  /* compute the kernel density estimates on the equispaced points */
  for(i=0;i<N;i++){
    const double z = min+i*delta;
    double sum=0;
    size_t j;
    
      for(j=0;j<size;j++){
	sum+= K((z-data[j])/h);
      }
      x[i]=sum/(h*size);
  }
  

  /* initialize the pointers */
  if(modes_pos != NULL && modes_height != NULL){
    free(*modes_pos); *modes_pos=NULL;
    free(*modes_height); *modes_height=NULL;
  }
  

  /* count the number of modes*/
  modes=0;
  if(x[0]>=x[1]){
    modes++;
    if(modes_pos != NULL && modes_height != NULL){
      *modes_pos = (double *) my_realloc(*modes_pos,modes*sizeof(double));
      (*modes_pos)[modes-1]=min;
      *modes_height = (double *) my_realloc(*modes_height,modes*sizeof(double));
      (*modes_height)[modes-1]=x[0];
    }
  }  
  for(i=1;i<N-1;i++){
    if(x[i]>x[i-1] && x[i]>x[i+1]){
      modes++;
      if(modes_pos != NULL && modes_height != NULL){
	*modes_pos = (double *) my_realloc(*modes_pos,modes*sizeof(double));
	(*modes_pos)[modes-1]=min+i*delta;
	*modes_height = (double *) my_realloc(*modes_height,modes*sizeof(double));
	(*modes_height)[modes-1]=x[i];
      }
    }
  }
  if(x[N-1]>=x[N-2]){
    modes++;
    if(modes_pos != NULL && modes_height != NULL){
      *modes_pos = (double *) my_realloc(*modes_pos,modes*sizeof(double));
      (*modes_pos)[modes-1]=max;
      *modes_height = (double *) my_realloc(*modes_height,modes*sizeof(double));
      (*modes_height)[modes-1]=x[N-1];
    }
  }
  /* free allocated space */
  free(x);
  return(modes);  
}

/* Find the critical bandwidth                  */
/* ------------------------------------------- */

/* Input:
   data       list of observations
   size       number of observations
   min        lower bound of the range where to search
   max        upper bound of the range where to search
   N          number of equispaced points
   K          kernel
   M          number of modes
   o_verbose  verbosity level
   epsrel     relative tolerance on critical bandwidth

   Output:
   hmin       lower bound on critical bandwidth
   hmax       upper bound on critical bandwidth

   modes  number of modes
 */

void findhcrit(const double *data,const unsigned size,
	       const double min, const double max, const unsigned N,
	       double (*K) (double),const unsigned M,  
	       const unsigned o_verbose,const double epsrel,double *hmin,double *hmax)
{
  double epsabs;
  double h=.5*(*hmin+*hmax);

  /* find initial boundary [hmin,hmax] */
  if( findmodes(data,size,min,max,N,h,K,NULL,NULL) <=M ){
    *hmax=h;
    *hmin=h/1.5;
    while(findmodes(data,size,min,max,N,*hmin,K,NULL,NULL)<=M) *hmin/=1.5;
  }
  else{
    *hmin=h;
    *hmax=1.5*h;
    while(findmodes(data,size,min,max,N,*hmax,K,NULL,NULL)>M) *hmax*=1.5;
  }


  /* re-scale the absolute value by the problem's scale */
  epsabs=epsrel*0.5*(*hmin+*hmax);
  
  /* ++++++++++++++++++++++++++++ */
  if(o_verbose > 1){
    fprintf(stderr," initial interval      [%e,%e]\n",*hmin,*hmax);
    fprintf(stderr," absolute error on h   %e\n",epsabs);
  }
  /* ++++++++++++++++++++++++++++ */


  
  /* find an estimate for h_c */    
  do{
    double *modes_pos=NULL,*modes_height=NULL;
    const double h = .5*(*hmin+*hmax);
    const unsigned modes = findmodes(data,size,min,max,N,h,K,&modes_pos,&modes_height);
    
    /* ++++++++++++++++++++++++++++ */
    if(o_verbose>1) {
      unsigned i;	
      fprintf(stderr," h=%.3e modes: ",h);
      for(i=0;i<modes;i++){
	fprintf(stderr,"(%+.3e,%+.3e) ",modes_pos[i],modes_height[i]);
      }
      fprintf(stderr,"\n");
    }
    /* ++++++++++++++++++++++++++++ */
    
    if( modes > M) *hmin=h;
    else *hmax=h;
    
    free(modes_pos);
    free(modes_height);      
    
  } while(fabs(*hmax-*hmin)>epsabs);

  /* ++++++++++++++++++++++++++++ */
  if(o_verbose > 0){
    fprintf(stderr," bandwidth final interval [%e,%e]\n",*hmin,*hmax);
  }
  /* ++++++++++++++++++++++++++++ */

}


/* Compute the significance of h_c using Silverman            */
/* ---------------------------------------------------------- */

/* 
   Input:

   data   list of observations
   size   number of observations
   ave    data average
   sdev   data standard deviation
   min    lower bound of the range where to search
   max    upper bound of the range where to search
   N      number of bins
   h      bandwidth
   M      number of modes
   trials number of sample trials
   seed   RNG seed
   K      kernel
   K_rng  random number generator
   alpha  significance

   Output:
   ratio score/trials
   
 */


double pscore(const double *data,const unsigned size,const double sdev,
	      const double min,const double max,const unsigned N,
	      const double h, const unsigned M, const unsigned trials,
	      const unsigned long seed,double (*K) (double),
	      double (*K_rng) (const gsl_rng *),
	      const double alpha)
{

  unsigned t,i;
  double score=0.0;
  const double samplescale = 1./sqrt(1.+h*h/(sdev*sdev));
  double *sample = (double *) my_alloc(size*sizeof(double));
  double lambda=1.;

  const gsl_rng_type * T = gsl_rng_default ;

  gsl_rng * rng = gsl_rng_alloc (T);
  gsl_rng_set (rng,seed);

  /* set the lambda value of the Hall-York correction if:
     - the number of modes is 1
     - the kernel is Gaussian
     - a proper value of alpha is provided

     Hall and York, Statistica Sinica 11(2001), 515-536
  */
  if(M==1 && alpha > 0 && alpha < 1 && K == Kgauss){
    /* Hall-York coefficient */
    const double c[] = {.94029,-1.59914,.17695,.48971,-1.77793,.36162,.42423};
    lambda = (c[0]*pow(alpha,3.)+c[1]*pow(alpha,2.)+c[2]*alpha+c[3])/(pow(alpha,3.)+c[4]*pow(alpha,2.)+c[5]*alpha+c[6]);    
  }
  
  for(t=0;t<trials;t++){
    /* create the sample */
    for(i=0;i<size;i++){
      const unsigned index = gsl_rng_uniform_int (rng,size);
      const double eps = K_rng (rng);
      sample[i] = ( data[index]+h*eps)*samplescale;
    }

    if(findmodes(sample,size,min,max,N,h*lambda,K,NULL,NULL) >M ) score+=1;
  }
  
  free(sample);
  gsl_rng_free (rng);
  
  return(score/trials);
  
}
/* =========================================== */


/* =========================================== */
/* 3 - Main                                    */
/* =========================================== */
int main(int argc,char* argv[]){

    double *data=NULL;
    size_t size;

    char *splitstring = strdup(" \t");
    
    double data_ave,data_sdev,data_min,data_max;

    /* OPTIONS */
    int o_verbose=0;
    int o_kerneltype=0;
    int o_setxregion=0;
    int o_output=0;
    int o_setxscale=0;
    double xscale=1; /* the scale factor defining the range where to look for modes*/
    int N=100; /* number of bins */

    double alpha=0.0; /*significance level*/

    double xmin=0,xmax=0; /* range where to look for modes */

    double hmin,hmax;
    unsigned modes;
    double epsrel=1e-6;
    unsigned long seed=0;

    unsigned M=1;/* number of modes */
    unsigned trials=1000;/* trials number for pscore*/

    double (*K) (double); /* the kernel to use */
    
    double (*K_rng) (const gsl_rng *);
    
    
    /* COMMAND LINE PROCESSING */
    
    /* variables for reading command line options */
    /* ------------------------------------------ */
    char opt;
    /* ------------------------------------------ */
    
    
    /* read the command line */    
    while((opt=getopt_long(argc,argv,"t:n:m:he:vR:K:r:O:s:F:S:",gb_long_options, &gb_option_index))!=EOF){
      if(opt==0){
      gbutils_header(argv[0],stdout);
      exit(0);
    }
    else if(opt=='?'){
	fprintf(stderr,"option %c not recognized\n",optopt);
	return(-1);
      }
      else if(opt=='n'){
	/*the number of bins*/
	N=(int) atoi(optarg);
      }
      else if(opt=='v'){
	/*increase verbosity*/
	o_verbose ++;
      }
      else if(opt=='m'){
	/*number of modes*/
	M = (unsigned) atoi(optarg);
      }
      else if(opt=='r'){
	/*where to look for modes*/
	if(!strchr (optarg,',')){
	fprintf(stderr,
		"option -r requires comma separated couple of values\n");
	return(-1);
	}
	else{
	  char *stmp1=strdup (optarg);
	  xmin = atof(strtok (stmp1,","));
	  xmax = atof(strtok (NULL,","));
	  free(stmp1);
	}
	o_setxregion=1;
      }
      else if(opt=='s'){
	/*where to look for modes: scaling factor*/
	xscale=atof(optarg);
	o_setxscale=1;
      }
      else if(opt=='R'){
	/*RNG seed*/
	seed = (unsigned) atol(optarg);
      }
      else if(opt=='t'){
	/*number of trials*/
	trials = (unsigned) atoi(optarg);
      }
      else if(opt=='K'){
	/*the Kernel to use*/
	o_kerneltype = atoi(optarg);
      }
      else if(opt=='O'){
	/*the type of output*/
	o_output = atoi(optarg);
      }
      else if(opt=='e'){
	/*set the absolute error on h_c*/
	epsrel = atof(optarg);
      }
      else if(opt=='F'){
	/*set the fields separator string*/
	free(splitstring);
	splitstring = strdup(optarg);
      }
      else if(opt=='S'){
	/*set the significance level*/
	alpha = atof(optarg);
      }
      else if(opt=='h'){
	/*print short help*/
	fprintf(stdout,"Multimodality analysis via kernel density estimation. Compute the maximal\n");
	fprintf(stdout,"kernel bandwidth h_c(M) for which #(modes in the estimated density)>M.The\n");
	fprintf(stdout,"significance of h_c is computed via smoothed bootstrap. Read data from std.\n");
	fprintf(stdout,"input. Print the couple h_c p(h_c) and the modal values (set with -O).\n");
	fprintf(stdout,"\nUsage: %s [options]\n\n",argv[0]);
	fprintf(stdout,"Options:\n");
	fprintf(stdout," -n  number of equispaced points where the density is computed (default 100)\n");
	fprintf(stdout," -m  number of modes (default 1)\n");
	fprintf(stdout," -r  search range for modes; comma separated couple 'data_min,data_max'\n");
	fprintf(stdout," -s  scale the search range to [min*s+(1-s)*Max,Max*s+(1-s)*min] (default 1)\n");
	fprintf(stdout," -e  relative tolerance on h_c value (default 1e-6)\n");
	fprintf(stdout," -S  significance level (for Hall-York correction) (default .05)\n");
	fprintf(stdout," -t  number of bootstrap trials used for significance computation (default 1000)\n");
	fprintf(stdout," -R  RNG seed for bootstrap trials (default 0)\n");
	fprintf(stdout," -K  choose the kernel to use: 0 Gaussian or 1 Laplacian  (default 0)\n");
	fprintf(stdout," -v  verbose mode (more verbose if provided 2 times)                   \n");
	fprintf(stdout," -O  output type (default 0)\n");
	fprintf(stdout,"      0  h_c p(h_c) [modes locations]                                           \n");
	fprintf(stdout,"      1  h_c [modes locations and heights]                                      \n");
	fprintf(stdout," -F  specify the input fields separators (default \" \\t\")\n");
	fprintf(stdout," -h  this help\n");
	exit(0);
      }
    }

    /* END OF COMMAND LINE PROCESSING */

    /* initialize global variables */
    initialize_program(argv[0]);

    switch(o_kerneltype){
    case 0:
      K=Kgauss;
      K_rng=Kgauss_rng;
      break;
    case 1:
      K=Klaplace;
      K_rng=Klaplace_rng;
      break;
    default:
      fprintf(stdout,"unknown kernel; use %s -h\n",argv[0]);
      exit(+1);
    }

    /* load data */
   load(&data,&size,0,splitstring);

    /* sort the data */
    qsort(data,size,sizeof(double),sort_by_value);

    /* compute relevant statistics */
    moment_short(data,size,&data_ave,&data_sdev,&data_min,&data_max);

    /* the parameter h is initially set according to [Silverman p.48] */
    {
      const double inter = fabs(data[3*size/4]-data[size/4])/1.34;
      const double A = (data_sdev>inter && inter>0 ? inter : data_sdev);
      hmin=hmax=0.9*A/pow(size,.2);
    }

    /* set the boundaries of region where to check for modes*/
    if(o_setxregion){ /* user provided boundaries */
      if(xmin>=xmax){ /* swap if wrongly provided by user */
	double dtmp=xmin;
	xmin=xmax;
	xmax=dtmp;
      }
    }
    else{ /* automatic setting */
	xmin=data_min;
	xmax=data_max;
    }

    /* apply the scaling factor */
    if(o_setxscale){
      const double delta= .5*(xmax-xmin)*(1.-xscale);
      xmax-=delta;
      xmin+=delta;
    }
    
    /* cut excessive range */
    if(xmax>data_max) xmax= data_max;
    if(xmin<data_min) xmin= data_min;


    /* ++++++++++++++++++++++++++++ */
    if(o_verbose > 0){
      /* data */
      fprintf(stdout," number of data           %zd\n",size);
      fprintf(stdout," sample mean              %f\n",data_ave);
      fprintf(stdout," sample std. dev.         %f\n",data_sdev);
      /* binning */
      fprintf(stdout," number of bins           %d\n",N);
      fprintf(stdout," modes search region      [%f,%f]\n",xmin,xmax);
      fprintf(stdout," number of modes          %d\n",M);
      /* kernel type */
      fprintf(stdout," kernel type              ");
      switch(o_kerneltype){
      case 0:
	fprintf(stdout,"Gaussian");
	break;
      case 1:
	fprintf(stdout,"Laplacian");
	break;
      }
      fprintf(stdout,"\n");
      /* bandwidth */
      fprintf(stdout," initial bandwidth        %e\n",hmin);
    }
    /* ++++++++++++++++++++++++++++ */


    /* find the critical bandwidth */
    findhcrit(data,size,xmin,xmax,N,K,M,o_verbose,epsrel,&hmin,&hmax);


    switch (o_output){
      
    case 0:
      {
	double *modes_pos=NULL,*modes_height=NULL;
	unsigned i;
	
	modes = findmodes(data,size,xmin,xmax,N,hmax,K,&modes_pos,&modes_height);
	
	/* ++++++++++++++++++++++++++++ */
	if(o_verbose > 0){
	  printf("#h_c(%d)\t\tpscore",M);
	  if(M==1 && alpha > 0 && alpha < 1 && K == Kgauss && o_output==0)
	    printf(" (HY %.3f)",alpha);
	  else
	    printf("\t");
	  printf("\tmodes locations ->\n");
	}
	/* ++++++++++++++++++++++++++++ */

	printf(FLOAT_SEP,.5*(hmax+hmin));
	printf(FLOAT_SEP,
	       pscore(data,size,data_sdev,xmin,xmax,N,
		      .5*(hmin+hmax),M,trials,seed,K,K_rng,alpha));

	for(i=0;i<modes;i++){
	  printf(FLOAT_SEP,modes_pos[i]);
	}
	printf("\n");

	free(modes_pos);
	free(modes_height);      

      }
      break;

      
    case 1:
      {
	double *modes_pos=NULL,*modes_height=NULL;
	unsigned i;

	modes = findmodes(data,size,xmin,xmax,N,hmax,K,&modes_pos,&modes_height);

	/* ++++++++++++++++++++++++++++ */
	if(o_verbose > 0) printf("#h_c(%d)\t\tmodes (location,height) ->\n",M);
	/* ++++++++++++++++++++++++++++ */

	printf(FLOAT_SEP,.5*(hmax+hmin));
	for(i=0;i<modes;i++){
	  printf("(");
	  printf(FLOAT,modes_pos[i]);
	  printf(",");
	  printf(FLOAT,modes_height[i]);
	  printf(") ");
	}
	printf("\n");

	free(modes_pos);
	free(modes_height);      

      }
      break;

    default:
      fprintf(stdout,"unknown output type; use %s -h\n",argv[0]);
      exit(+1);
    }

    exit(0);
}