gbquant.c 16.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
  gbquant  (ver. 5.6.1) -- Print quantiles of data distribution
  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
16
  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 18 19 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
*/

#include "tools.h"

int main(int argc,char* argv[]){

  double *xvals=NULL,*qvals=0;;
  size_t xvalnum=0,qvalnum=0;

  size_t n=10;

  double wqmin=0,wqmax=1.;

  char *splitstring = strdup(" \t");

  /* options */
  int o_xval  = 0;
  int o_qval = 0;
  int o_err = 0;
  int o_qwindow = 0;
  int o_table = 0;
  int o_verbose=0;
  int o_position=1;

  /* variables for reading command line options */
  /* ------------------------------------------ */
  char opt;
  /* ------------------------------------------ */

  /* COMMAND LINE PROCESSING */    
  while((opt=getopt_long(argc,argv,"W:w:vhtx:q:en:F:",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=='h'){
      /*print help*/
      fprintf(stdout,"Print distribution quantiles. Data are read from standard input. If no\n");
      fprintf(stdout,"-x or -q options are provided, a quantiles table is plotted. The number\n");
      fprintf(stdout,"of quantiles can be chosen with -n. The option -x #1 prints the quantile\n");
      fprintf(stdout,"associated with the value #1, while -q #2 print the value associate with\n");
      fprintf(stdout,"the quantile #2. Of course #2 must be between 0 and 1. Multiple values\n");
      fprintf(stdout,"can be provided to -x or -q, separated with commas. With -w #1,#2 all\n");
      fprintf(stdout,"the observations inside the quantile range [#1,#2) are printed. If more\n");
      fprintf(stdout,"columns are provided with option -t, the specified action is repeated on\n");
      fprintf(stdout,"each column. Without -t, columns are pooled unless -w is specified, in\n");
      fprintf(stdout,"which case all rows whose first element is inside the range are printed.\n");
      fprintf(stdout,"A different column for sorting can be specified with option -W. If 0 is\n");
      fprintf(stdout,"specified, the cut is applied with respect to all columns\n");
      fprintf(stdout,"\nUsage: %s [options]\n\n",argv[0]);
      fprintf(stdout,"Options:\n");
      fprintf(stdout," -n  number of quantiles to print (default 10)\n");
      fprintf(stdout," -x  print the quantile (interpolated) associated with the value\n");
      fprintf(stdout," -q  print the value (interpolated) associated with the quantile\n");
      fprintf(stdout," -e  print the (asymptotic) error for -x or -q; doesn't work with -t\n");
      fprintf(stdout," -w  print observations inside a quantile windows\n");
      fprintf(stdout," -W  set the column to use (default 1)\n");
      fprintf(stdout," -t  consider separately each column of input\n");
      fprintf(stdout," -F  specify the input fields separators (default \" \\t\")\n");
      fprintf(stdout," -h  this help\n");
      fprintf(stdout," -v  verbose mode\n");
      return(0);
    }
    else if(opt=='W'){
      o_position=atoi(optarg);
      if(o_position <0){
	fprintf(stderr,
		"ERROR (%s): Column number must be non-negative\n",
		GB_PROGNAME);
	exit(1);
      }
    }
    else if(opt=='w'){
      /*set the quantile window */

      char *stmp1=strdup (optarg);
      char *stmp2;
      char *stmp3=stmp1;

      stmp2=strsep (&stmp1,",");
      if(strlen(stmp2)>0) 
	wqmin=atof(stmp2);
      if(stmp1 != NULL && strlen(stmp1)>0)
	wqmax=atof(stmp1);
      free(stmp3);

      if(wqmax<wqmin){
	const double dtmp1 = wqmax;
	wqmax=wqmin;
	wqmin=dtmp1;
      }

      o_qwindow=1;
    }
    else if(opt=='F'){
      /*set the fields separator string*/
      free(splitstring);
      splitstring = strdup(optarg);
    }
    else if(opt=='t'){
      /*set the table form*/
      o_table=1;
    }
    else if(opt=='n'){
      /*set the number of quantiles*/
      n=atoi(optarg);
    }
    else if(opt=='x'){
      /*set the value whose quantile is required*/
      char *stmp1=strdup (optarg);
      char *stmp2;
      char *stmp3=stmp1;
      while( (stmp2=strsep (&stmp1,",")) != NULL && strlen(stmp2)>0 ){
	xvalnum++;
	xvals = (double *) my_realloc((void *) xvals,xvalnum*sizeof(double));
	xvals[xvalnum-1]=atof(stmp2);
      }
      o_xval=1;
      free(stmp3);
    }
    else if(opt=='q'){
      /*set the quantile whose value is required*/
      char *stmp1=strdup (optarg);
      char *stmp2;
      char *stmp3=stmp1;
      while( (stmp2=strsep (&stmp1,",")) != NULL && strlen(stmp2)>0 ){
	qvalnum++;
	qvals = (double *) my_realloc((void *) qvals,qvalnum*sizeof(double));
	qvals[qvalnum-1]=atof(stmp2);
      }
      o_qval=1;
      free(stmp3);
    }
    else if(opt=='e'){
      /*set the verbose mode*/
      o_err=1;
    }
    else if(opt=='v'){
      /*set the verbose mode*/
      o_verbose=1;
    }
  }    
  /* END OF COMMAND LINE PROCESSING */

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

  if(o_xval==0 && o_qval==0 && o_qwindow==0){/* print the list of quantiles */

    if(!o_table){
      size_t size;
      double *vals=NULL;
      size_t quant;

      load(&vals,&size,0,splitstring);
      denan(&vals,&size);
      qsort(vals,size,sizeof(double),sort_by_value);

      /*+++++++++++++++++++++++++++++++++++++++*/
      if(o_verbose)
	fprintf(stderr,"loaded %zd data\n",size);
      /*+++++++++++++++++++++++++++++++++++++++*/
	
      if(n>size) n = size;/* for consistency */

      /*+++++++++++++++++++++++++++++++++++++++*/
      if(o_verbose){ 
	printf(EMPTY_SEP,"#quant.");
	printf(EMPTY_NL,"val");
      }
      /*+++++++++++++++++++++++++++++++++++++++*/
      for(quant=1;quant<=n;quant++){
	double dtmp1 = quant/(n+1.);
	int index = floor((size+1.)*dtmp1);
	double delta = (size+1.)*dtmp1-index;
	printf(FLOAT_SEP,dtmp1);
	printf(FLOAT_NL,vals[index-1]*(1.-delta)+vals[index]*delta);
      }
    }
    else{
      size_t rows=0,columns=0,i,j;
      double **vals=NULL;
      double **quantiles;
      
      loadtable(&vals,&rows,&columns,0,splitstring);

      /*+++++++++++++++++++++++++++++++++++++++*/
      if(o_verbose)
	fprintf(stderr,"loaded %zdx%zd data table\n",rows,columns);
      /*+++++++++++++++++++++++++++++++++++++++*/

      if(n>rows) n = rows;/* for consistency */

      /* allocate the array for the result */
      quantiles = (double **) my_alloc(n*sizeof(double*));
      for(i=0;i<n;i++)
	quantiles[i] = (double *) my_alloc(columns*sizeof(double));

      /* compute the result */
      for(i=0;i<columns;i++){
	size_t size=rows;
	denan(&(vals[i]),&size);
	qsort(vals[i],size,sizeof(double),sort_by_value);
	for(j=1;j<=n;j++){
	  double dtmp1 = j/(n+1.);
	  int index = floor((size+1.)*dtmp1);
	  double delta = (size+1.)*dtmp1-index;

	  if(dtmp1<1./(size+1.)) quantiles[j-1][i]=vals[i][0];
	  else if (dtmp1>1.-1./(size+1.)) quantiles[j-1][i]=vals[i][size-1];	  
	  else quantiles[j-1][i]=vals[i][index-1]*(1.-delta)+vals[i][index]*delta;
	}
      }

      /*+++++++++++++++++++++++++++++++++++++++*/
      if(o_verbose){ 
	printf(EMPTY_SEP,"#quant.");
	printf(EMPTY_NL,"vals->");
      }
      /*+++++++++++++++++++++++++++++++++++++++*/

      printmatrixbyrows(stdout,quantiles,n,columns);
    }
  }
  else if(o_qwindow==1){ /* print the data inside the quantile windows */
    if(!o_table){
      size_t rows=0,columns=0,i,j;
      double **vals=NULL;

      size_t indexmin,indexmax;

      /* load data: data[column][row] */
      loadtable(&vals,&rows,&columns,0,splitstring);
      
      if(o_position > columns){
	fprintf(stderr,
		"ERROR (%s): Column position larger than columns number.\n",
		GB_PROGNAME);
	exit(1);
      }

      /* remove NAN entries */
      denan_data(&vals,&rows,&columns);

      /* define the indexes boundaries */
      indexmin = floor(rows*wqmin);
      indexmax = ceil(rows*wqmax);
      
      if(columns==1){
	/*+++++++++++++++++++++++++++++++++++++++*/
	if(o_verbose)
	  fprintf(stderr,"loaded %zd data\n",rows);
	/*+++++++++++++++++++++++++++++++++++++++*/

	/* sort data */
	qsort(vals[0],rows,sizeof(double),sort_by_value);

	for(j=0;j<indexmin;j++)
	  vals[0][j]=NAN;

	for(j=indexmax;j<rows;j++)
	  vals[0][j]=NAN;

      }
      else if(columns>1){
	/*+++++++++++++++++++++++++++++++++++++++*/
	if(o_verbose)
	  fprintf(stderr,"loaded %zdx%zd data table\n",rows,columns);
	/*+++++++++++++++++++++++++++++++++++++++*/


	if(o_position>0){/* sort data accordong to given position*/
	  sortn(vals,columns,rows,o_position-1,2);

	  for(j=0;j<indexmin;j++)
	    vals[o_position-1][j]=NAN;

	  for(j=indexmax;j<rows;j++)
	    vals[o_position-1][j]=NAN;

	}
	else if(o_position==0){/* sort data according to each position */

	  for(i=0;i<columns;i++){
	    sortn(vals,columns,rows,i,2);
	    
	    for(j=0;j<indexmin;j++)
	      vals[i][j]=NAN;
	    
	    for(j=indexmax;j<rows;j++)
	      vals[i][j]=NAN;
	    
	  }
	}
      }
      else{
	fprintf(stderr,
		"ERROR (%s): Provide at least one column of data\n",
		GB_PROGNAME);
	exit(1);
      }

      /* remove NAN entries generated by cropping*/
      denan_data(&vals,&rows,&columns); 

      
      /*+++++++++++++++++++++++++++++++++++++++*/
      if(o_verbose) 
	printf("#data in quantile range [%f,%f]\n",wqmin,wqmax);
      /*+++++++++++++++++++++++++++++++++++++++*/

      for(i=0;i<rows;i++){
	for(j=0;j<columns-1;j++) printf(FLOAT_SEP,vals[j][i]);
	printf(FLOAT_NL,vals[columns-1][i]);
      }

    }
    else{

      size_t rows=0,columns=0,i,j;
      double **vals=NULL;
      double **result=NULL;
      size_t *resnum=NULL;
      size_t maxresnum=0;
      size_t indexmin,indexmax;

      loadtable(&vals,&rows,&columns,0,splitstring);

      /* allocate the array for the result */
      result = (double **) my_alloc(columns*sizeof(double *));
      resnum = (size_t *) my_alloc(columns*sizeof(size_t));
      

      /*+++++++++++++++++++++++++++++++++++++++*/
      if(o_verbose)
	fprintf(stderr,"loaded %zdx%zd data table\n",rows,columns);
      /*+++++++++++++++++++++++++++++++++++++++*/

      /* compute the result */
      for(i=0;i<columns;i++){
	size_t size=rows;
	denan(&(vals[i]),&size);
	qsort(vals[i],size,sizeof(double),sort_by_value);

	indexmin = floor(size*wqmin);
	indexmax = ceil(size*wqmax);

	result[i] = (double *) my_alloc((indexmax-indexmin)*sizeof(double));
	resnum[i] = indexmax-indexmin;
	if(resnum[i]> maxresnum) maxresnum = resnum[i];
	for(j=0;j<indexmax-indexmin;j++)
	  result[i][j] = vals[i][j+indexmin];
      }

      /*+++++++++++++++++++++++++++++++++++++++*/
      if(o_verbose) 
	printf("#data in quantile range [%f,%f]\n",wqmin,wqmax);
      /*+++++++++++++++++++++++++++++++++++++++*/
      for(i=0;i<maxresnum;i++){
	for(j=0;j<columns;j++){
	  if(i<resnum[j])
	    printf(FLOAT_SEP,result[j][i]);
	  else
	    printf(FLOAT_SEP,NAN);
	}
	printf("\n");
      }
    }
  }
  else if(o_xval==1){ /* print the quantile associated with the value */
    if(!o_table){
      size_t size,index;
      double *vals=NULL;
      
      load(&vals,&size,0,splitstring);

      /*+++++++++++++++++++++++++++++++++++++++*/
      if(o_verbose)
	fprintf(stderr,"loaded %zd data\n",size);
      /*+++++++++++++++++++++++++++++++++++++++*/

      denan(&vals,&size);
      qsort(vals,size,sizeof(double),sort_by_value);

      /*+++++++++++++++++++++++++++++++++++++++*/
      if(o_verbose){
	if(o_err==0)
	  printf(EMPTY_NL,"#cumulated");
	else{
	  printf(EMPTY_SEP,"#cumulated");
	  printf(EMPTY_NL,"std.err.");
	}
      }
      /*+++++++++++++++++++++++++++++++++++++++*/
      for(index=0;index<xvalnum;index++){
	const double xval = xvals[index];
	if(xval<vals[0]) printf(FLOAT_NL,0.0);
	else if (xval>vals[size-1]) printf(FLOAT_NL,1.0);
	else {
	  int i=0;
	  double dtmp1,dtmp2;
	  while(vals[i]<xval) i++;
	  dtmp1=xval-vals[i-1];
	  dtmp2=vals[i]-xval;
	  if(o_err==0)
	    printf(FLOAT_NL,(i*dtmp2+(i+1.)*dtmp1)/((size+1.)*(dtmp1+dtmp2)));
	  else{
	    printf(FLOAT_SEP,(i*dtmp2+(i+1.)*dtmp1)/((size+1.)*(dtmp1+dtmp2)));
	    printf(FLOAT_NL,
		   sqrt(((size+1-i)*i*dtmp2+(size-i)*(i+1.)*dtmp1)/((size+1.)*(size+1.)*(size+2.)*(dtmp1+dtmp2))));
	  }
	}
      }
    }
    else{
      size_t rows=0,columns=0,i,j;
      double **vals=NULL;
      double **results=NULL;

      loadtable(&vals,&rows,&columns,0,splitstring);

      /* allocate the array for the result */
      results = (double **) my_alloc(xvalnum*sizeof(double *));
      for(j=0;j<xvalnum;j++)
	results[j] = (double *) my_alloc(columns*sizeof(double));

      /*+++++++++++++++++++++++++++++++++++++++*/
      if(o_verbose)
	fprintf(stderr,"loaded %zdx%zd data table\n",rows,columns);
      /*+++++++++++++++++++++++++++++++++++++++*/

      /* compute the result */
      for(i=0;i<columns;i++){
	size_t size=rows;
	denan(&(vals[i]),&size);
	qsort(vals[i],size,sizeof(double),sort_by_value);

	for(j=0;j<xvalnum;j++){
	  const double xval = xvals[j];

/* 	  printf("%d %f [%f,%f] \n",i,xval,vals[i][0],vals[i][size-1]); */
	  
	  if(xval<vals[i][0]) results[j][i]=0.0;
	  else if (xval>vals[i][size-1]) results[j][i]=1.0;
	  else {
	    int index=0;
	    double dtmp1,dtmp2;
	    while(vals[i][index]<xval) index++;
	    dtmp1=xval-vals[i][index-1];
	    dtmp2=vals[i][index]-xval;
	    results[j][i]=(index*dtmp2+(index+1.)*dtmp1)/((size+1.)*(dtmp1+dtmp2));
	  }
	}
      }

      /*+++++++++++++++++++++++++++++++++++++++*/
      if(o_verbose) 
	printf(EMPTY_NL,"#cumulated->");
      /*+++++++++++++++++++++++++++++++++++++++*/
      printmatrixbyrows(stdout,results,xvalnum,columns);

    }
  }
  else if(o_qval==1) { /* print the values associated with the quantile */
    if(!o_table){
      size_t size,index;
      double *vals=NULL;
      
     load(&vals,&size,0,splitstring);

      /*+++++++++++++++++++++++++++++++++++++++*/
      if(o_verbose)
	fprintf(stderr,"loaded %zd data\n",size);
      /*+++++++++++++++++++++++++++++++++++++++*/

      denan(&vals,&size);
      qsort(vals,size,sizeof(double),sort_by_value);

      /*+++++++++++++++++++++++++++++++++++++++*/
      if(o_verbose){
	if(o_err==0)
	  printf(EMPTY_NL,"#quantiles");
	else{
	  printf(EMPTY_SEP,"#quantiles");
	  printf(EMPTY_NL,"std.err.");
	}
      }
      /*+++++++++++++++++++++++++++++++++++++++*/
      for(index=0;index<qvalnum;index++){
	const double qval = qvals[index];
	if(qval<1./(size+1.)) printf(FLOAT_NL,vals[0]);
	else if (qval>1.-1./(size+1.)) printf(FLOAT_NL,vals[size-1]);
	else {
	  int index = floor((size+1.)*qval);
	  double delta =  (size+1.)*qval-index;
	  double quantile = vals[index-1]*(1.-delta)+vals[index]*delta;
	  if(o_err==0)
	    printf(FLOAT_NL,quantile);
	  else{
	    int supindex = ceil((size+1.)*qval+sqrt(qval*(1-qval)*(size+2.)));
	    int infindex = floor((size+1.)*qval-sqrt(qval*(1-qval)*(size+2.)));
	    double supdist= vals[supindex-1]-quantile;
	    double infdist = quantile-vals[infindex-1];
	    printf(FLOAT_SEP,vals[index-1]*(1.-delta)+vals[index]*delta);
	    printf(FLOAT_NL,(supdist>infdist?supdist:infdist));
	  }
	}
      }
    }
    else{
      size_t rows=0,columns=0,i,j;
      double **vals=NULL;
      double **results;
      
      loadtable(&vals,&rows,&columns,0,splitstring);

      /*+++++++++++++++++++++++++++++++++++++++*/
      if(o_verbose)
	fprintf(stderr,"loaded %zdx%zd data table\n",rows,columns);
      /*+++++++++++++++++++++++++++++++++++++++*/

      /* allocate the array for the result */
      results = (double **) my_alloc(qvalnum*sizeof(double *));
      for(j=0;j<qvalnum;j++)
	results[j] = (double *) my_alloc(columns*sizeof(double));
      
      for(i=0;i<columns;i++){
	size_t size=rows;
	denan(&(vals[i]),&size);
	qsort(vals[i],size,sizeof(double),sort_by_value);

	for(j=0;j<qvalnum;j++){
	  const double qval = qvals[j];
	  
	  if(qval<1./(size+1.)) results[j][i]=vals[i][0];
	  else if (qval>1.-1./(size+1.)) results[j][i]=vals[i][size-1];
	  else {
	    int index = floor((size+1.)*qval);
	    double delta =  (size+1.)*qval-index;
	    results[j][i]=vals[i][index-1]*(1.-delta)+vals[i][index]*delta;
	  }
	}
      }

      /*+++++++++++++++++++++++++++++++++++++++*/
      if(o_verbose) 
	printf(EMPTY_NL,"#quantiles->");
      /*+++++++++++++++++++++++++++++++++++++++*/
      printmatrixbyrows(stdout,results,qvalnum,columns);

    }
  }
  else{
    fprintf(stderr,"you asked for something impossible! check %s -h\n",argv[0]);      
  }
  
  return(0);
}