ecoprimer.c 20 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
/*
 * ecoprimer.c
 *
 *  Created on: 7 nov. 2008
 *      Author: coissac
 */

#include "libecoprimer/ecoprimer.h"
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <getopt.h>
#include <time.h>
#include <sys/time.h>

#define VERSION "0.1"
  /* TR: by default, statistics are made on species level*/
#define DEFULTTAXONRANK "species"

/* ----------------------------------------------- */
/* printout help                                   */
/* ----------------------------------------------- */
#define PP fprintf(stdout,

static void PrintHelp()
{
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
			  PP      "------------------------------------------\n");
			  PP      " ecoPrimer Version %s\n", VERSION);
			  PP      "------------------------------------------\n");
              PP      "synopsis : finding primers and measureing the quality of primers and barcode region\n");
              PP      "usage: ./ecoPrimer [options] \n");
              PP      "------------------------------------------\n");
              PP      "options:\n");
              PP      "-d    : [D]atabase : to match the expected format, the database\n");
              PP      "        has to be formated first by the ecoPCRFormat.py program located.\n");
              PP      "        in the ecoPCR/tools directory.\n");
              PP      "        ecoPCRFormat.py creates three file types :\n");
              PP      "            .sdx : contains the sequences\n");
              PP      "            .tdx : contains information concerning the taxonomy\n");
              PP      "            .rdx : contains the taxonomy rank\n\n");
              PP      "        ecoPrimer needs all the file type. As a result, you have to write the\n");
              PP      "        database radical without any extension. For example /ecoPrimerDB/fstvert\n\n");        
              PP      "-e    : [E]rror : max error allowed by oligonucleotide (0 by default)\n\n");
              PP      "-h    : [H]elp - print <this> help\n\n");
              PP      "-i    : [I]gnore the given taxonomy id.\n\n");
              PP      "-l    : minimum [L]ength : define the minimum amplication length. \n\n");
              PP      "-L    : maximum [L]ength : define the maximum amplicationlength. \n\n");
              PP      "-r    : [R]estricts the search to the given taxonomic id.\n\n");
              PP      "-c    : Consider that the database sequences are [c]ircular\n\n");
              PP      "-3 	 : Three prime strict match\n\n");
              PP      "-q    : Strict matching [q]uorum, percentage of the sequences in which strict primers are found. By default it is 70\n\n");
              PP      "-s    : [S]ensitivity quorum\n\n");
              PP      "-t    : required [t]axon level for results, by default the results are computed at species level\n\n");
              PP      "-x    : false positive quorum\n\n");
              PP      "-D    : set in [d]ouble strand mode\n\n");
              PP      "-S    : Set in [s]ingle strand mode\n\n");
              PP      "-U    : No multi match\n\n");
              PP      "\n");
              PP      "------------------------------------------\n");
              PP      "Table result description : \n");
              PP      "column 1 : serial number\n");
              PP      "column 2 : primer1\n");
              PP      "column 3 : primer2\n");
              PP      "column 4 : good/bad\n");
              PP      "column 5 : in sequence count\n");
              PP      "column 6 : out sequence count\n");
              PP      "column 7 : yule\n");
              PP      "column 8 : in taxa count\n");
              PP      "column 9 : out taxa count\n");
              PP      "column 10 : coverage\n");
              PP      "column 11 : specificity\n");
              PP      "column 12 : minimum amplified length\n");
              PP      "column 13 : maximum amplified length\n");
              PP      "column 14 : average amplified length\n");
              PP      "------------------------------------------\n");
              PP		" http://www.grenoble.prabi.fr/trac/ecoPrimer/\n");
              PP      "------------------------------------------\n\n");        
              PP      "\n");

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
}

static void ExitUsage(int stat)
{
        PP      "usage: ecoprimer [-d database] [-l value] [-L value] [-e value] [-r taxid] [-i taxid] [-R rank] [-t taxon level]\n");
        PP      "type \"ecoprimer -h\" for help\n");

        if (stat)
            exit(stat);
}

#undef  PP

void initoptions(poptions_t options)
{
	options->lmin=0;                   //< Amplifia minimal length
	options->lmax=0;                   //< Amplifia maximal length
	options->error_max=3;              //**< maximum error count in fuzzy search
	options->primer_length=18;          //**< minimal length of the primers
	options->restricted_taxid=NULL;      //**< limit amplification below these taxid
	options->ignored_taxid=NULL;         //**< no amplification below these taxid
	options->prefix=NULL;
	options->circular=0;
	options->doublestrand=1;
	options->strict_quorum=0.7;
	options->strict_exclude_quorum=0.1;
	options->sensitivity_quorum=0.9;
	options->false_positive_quorum=0.1;
109
	options->strict_three_prime=0;
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
	options->r=0;
	options->g=0;
	options->no_multi_match=FALSE;
	strcpy(options->taxonrank, DEFULTTAXONRANK);			/*taxon level for results, species by default*/
}

void printcurrenttime ()
{
    time_t     now;
    struct tm  *ts;
    char       buf[80];

    /* Get the current time */
    now = time(NULL);

    /* Format and print the time, "ddd yyyy-mm-dd hh:mm:ss zzz" */
    ts = localtime(&now);
    strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", ts);
128
    fprintf(stderr,"#%d#, %s\n",(int)now, buf);
129 130 131 132 133 134 135 136 137 138 139 140 141 142
 }

void printcurrenttimeinmilli()
{
     struct timeval tv;
     struct timezone tz;
     struct tm *tm;
     gettimeofday(&tv, &tz);
     tm=localtime(&tv.tv_sec);
     fprintf(stderr, " %d:%02d:%02d %d %d \n", tm->tm_hour, tm->tm_min,
              tm->tm_sec, tv.tv_usec, tv.tv_usec/1000);
}

/*TR: Added*/
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

void printapair(int32_t index,ppair_t pair, poptions_t options)
{
	uint32_t wellidentifiedtaxa;
	
	printf("%6d\t",index);
	if (pair->asdirect1)
		printf("%s\t",ecoUnhashWord(pair->p1->word,options->primer_length));
	else
		printf("%s\t",ecoUnhashWord(ecoComplementWord(pair->p1->word,
				                                      options->primer_length),options->primer_length));

	if (pair->asdirect2)
		printf("%s",ecoUnhashWord(pair->p2->word,options->primer_length));
	else
		printf("%s",ecoUnhashWord(ecoComplementWord(pair->p2->word,
				                                    options->primer_length),options->primer_length));

	printf("\t%c%c", "bG"[(int)pair->p1->good],"bG"[(int)pair->p2->good]);


	printf("\t%d", pair->inexample);
	printf("\t%d", pair->outexample);
	printf("\t%4.3f", pair->yule);

	printf("\t%d", pair->intaxa);
	printf("\t%d", pair->outtaxa);
	printf("\t%4.3f", (float)pair->intaxa/options->intaxa);
	
	wellidentifiedtaxa = (pair->intaxa + pair->outtaxa) - pair->notwellidentifiedtaxa;
	
	//printf("\t%d", pair->notwellidentifiedtaxa);
	
	//printf("\t%d", (pair->intaxa + pair->outtaxa));


	
	printf("\t%4.3f", (float)wellidentifiedtaxa/(options->intaxa + options->outtaxa));


	printf("\t%d", pair->mind);
	printf("\t%d", pair->maxd);
	printf("\t%3.2f\n", (float)pair->sumd/pair->inexample);

}

uint32_t filterandsortpairs(ppair_t* sortedpairs,uint32_t count, poptions_t options)
{
	uint32_t i,j;
	float q,qfp;

	for (i=0,j=0;i < count;i++)
	{
		if (options->insamples)
			q = (float)sortedpairs[i]->inexample/options->insamples;
		else q=1.0;

		if (options->outsamples)
			qfp = (float)sortedpairs[i]->outexample/options->outsamples;
		else qfp=0.0;

		sortedpairs[i]->quorumin = q;
		sortedpairs[i]->quorumout = qfp;
		sortedpairs[i]->yule = q -qfp;


		sortedpairs[j]=sortedpairs[i];



		if (q > options->sensitivity_quorum &&
			qfp < options->false_positive_quorum)
		{
			(void)taxonomycoverage(sortedpairs[j],options);
			taxonomyspecificity(sortedpairs[j]);
			j++;
		}
	}

	return j;
}

void printpairs (ppairtree_t pairs, poptions_t options)
{
   ppair_t* sortedpairs;
   ppair_t* index;
   ppairlist_t pl;
   size_t i,j;
   int32_t count;

   //printf("Index\tPrimer1\tPrimer2\tGB\tInexampleCount\tOutexampleCount\tYule\tIntaxaCount\tOuttaxaCount\tCoverage\tSpecificity\tMinAmplifiedLength\tMaxAmplifiedLength\tAvgAmplifiedLength\n"); 
   
   fprintf(stderr,"Total pair count : %d\n",pairs->count);

   sortedpairs = ECOMALLOC(pairs->count*sizeof(ppair_t),"Cannot Allocate ordered pairs");
   index=sortedpairs;
   pl=pairs->first;
   j=0;
   while(pl->next)
   {
	   for (i=0;i<pl->paircount;i++,j++)
		   sortedpairs[j]=pl->pairs+i;
	   pl=pl->next;
   }

   for (i=0;i<pl->paircount;i++,j++)
	   sortedpairs[j]=pl->pairs+i;

   count=filterandsortpairs(sortedpairs,pairs->count,options);

   for (i=0;i < count;i++)
	   printapair(i,sortedpairs[i],options);

}


#ifdef MASKEDCODE
260
void printpairs (pairscount_t pairs, poptions_t options, int32_t rankdbstats, uint32_t seqdbsize)
261

262 263 264 265 266 267 268
{
	uint32_t i;
	uint32_t  wordsize = options->primer_length;
	uint32_t	 quorumseqs;
	double sens;
	double speci;
	float  avg;
269

270
	quorumseqs = seqdbsize * 70 / 100;
271

272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
	printf("primer_1\tseq_1\tPrimer_2\tseq_2\tamplifia_count\t%s_snes\t%s_spe\tmin_l\tmax_l\tavr_l\n", options->taxonrank, options->taxonrank);

	for (i=0; i < pairs.paircount; i++)
	{
		if (quorumseqs > pairs.pairs[i].inexample) continue;
		sens = (pairs.pairs[i].taxsetindex*1.0)/rankdbstats*100;
		speci = (pairs.pairs[i].oktaxoncount*1.0)/pairs.pairs[i].taxsetindex*100;
		avg = (pairs.pairs[i].mind+pairs.pairs[i].maxd)*1.0/2;

		printf("P1\t%s", ecoUnhashWord(pairs.pairs[i].w1, wordsize));
		printf("\tP2\t%s", ecoUnhashWord(pairs.pairs[i].w2, wordsize));
		printf("\t%d", pairs.pairs[i].inexample);
		printf("\t%3.2f", sens);
		printf("\t%3.2f", speci);
		printf("\t%d", pairs.pairs[i].mind);
		printf("\t%d", pairs.pairs[i].maxd);
		printf("\t%3.2f\n", avg);
	}
}

292 293
#endif /* MASKEDCODE */

294 295
/*updateseqparams: This function counts the insample and outsample sequences
 *  and with each sequences adds a tag of the taxon to which the sequence beongs*/
296 297

void updateseqparams (pecodnadb_t seqdb, uint32_t seqdbsize, ecotaxonomy_t *taxonomy,
298 299 300 301 302 303 304
		poptions_t options, int32_t *insamples, int32_t *outsamples)
{
	uint32_t i;
	int32_t taxid;
	ecotx_t  *tmptaxon;

    for (i=0;i<seqdbsize;i++)
305
    {
306 307 308 309 310 311 312
    	seqdb[i]->isexample=isGoodTaxon(taxonomy,seqdb[i]->taxid,options);
    	if (seqdb[i]->isexample)
    		(*insamples)++;
    	else
    		(*outsamples)++;

    	taxid = taxonomy->taxons->taxon[seqdb[i]->taxid].taxid;
313
		tmptaxon = eco_findtaxonbytaxid(taxonomy, taxid);
314 315 316 317 318 319 320 321 322 323 324 325 326 327
		if (tmptaxon)
			tmptaxon = eco_findtaxonatrank(tmptaxon, options->taxonrankidx);
		if (tmptaxon)
			seqdb[i]->ranktaxonid = tmptaxon->taxid;
    }
}

void setresulttaxonrank (ecotaxonomy_t *taxonomy, poptions_t options)
{
	int32_t i;

    /*set taxon rank for which result is to be given*/
    for (i = 0; i < taxonomy->ranks->count; i++)
    {
328
    	if (strcmp(taxonomy->ranks->label[i], options->taxonrank) == 0)
329 330 331 332 333 334 335 336 337 338 339 340 341 342
    	{
    		options->taxonrankidx = i;
    		break;
    	}
    }

    if (i == taxonomy->ranks->count)
    {
    	fprintf(stderr,"\nUnknown taxon level: '%s'\n", options->taxonrank);
    	exit(0);
    }
}
/* to get db stats, totals of species, genus etc....*/

343
#ifdef MASKEDCODE
344

345
void setoktaxforspecificity (ppairtree_t pairs)
346 347 348 349 350 351 352
{
	uint32_t i;
	uint32_t j;
	uint32_t k;
	uint32_t l;
	int taxcount;
	int32_t taxid;
353

354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
	for (i = 0; i < pairs->paircount; i++)
	{
		for (j = 0; j < pairs->pairs[i].taxsetindex; j++)
		{
			for (k = 0; k < pairs->pairs[i].taxset[j].amplifiaindex; k++)
			{
				taxid = 0;
				taxcount = 0;
				for (l = 0; l < pairs->pairs[i].ampsetindex; l++)
				{
					/*compare only char pointers because for equal strings we have same pointer in both sets*/
					if (pairs->pairs[i].taxset[j].amplifia[k] == pairs->pairs[i].ampset[l].amplifia)
					{
						if (pairs->pairs[i].ampset[l].seqidindex > 1)
						{
							taxcount += pairs->pairs[i].ampset[l].seqidindex;
							break;
						}
372

373 374 375
						if (taxid != pairs->pairs[i].ampset[l].taxonids[0])
						{
							if (!taxid) taxid = pairs->pairs[i].ampset[l].taxonids[0];
376
							taxcount++;
377
						}
378

379 380 381 382 383 384 385 386 387
						if (taxcount > 1) break;
					}
				}
				if (taxcount == 1) pairs->pairs[i].oktaxoncount++;
			}
		}
	}
}

388 389
#endif

390 391 392 393 394 395 396 397 398 399 400 401 402
int main(int argc, char **argv)
{
	pecodnadb_t   seqdb; /* of type ecoseq_t */
	uint32_t        seqdbsize=0;
	ecotaxonomy_t *taxonomy;

	options_t     options;
	int           carg;
	int32_t       errflag=0;

	int32_t       insamples=0;
	int32_t       outsamples=0;
	uint32_t        i;
403 404 405 406 407

	pwordcount_t    words;
	pprimercount_t  primers;
	ppairtree_t		pairs;

408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
	int32_t		  rankdbstats = 0;

	//printcurrenttime();
	//return 0;

	initoptions(&options);

    while ((carg = getopt(argc, argv, "hcUDSd:l:L:e:i:r:q:3:s:x:t:")) != -1) {

     switch (carg) {
                                /* -------------------- */
        case 'd':               /* database name        */
                                /* -------------------- */
        	options.prefix = ECOMALLOC(strlen(optarg)+1,
                              "Error on prefix allocation");
           strcpy(options.prefix,optarg);
           break;

                                /* -------------------- */
        case 'h':               /* help                 */
                                /* -------------------- */
429 430 431
        	PrintHelp();
        	 exit(0);
        	 break;
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

                                /* ------------------------- */
        case 'l':               /* min amplification lenght  */
                                /* ------------------------- */
           sscanf(optarg,"%d",&(options.lmin));
           break;

                                /* -------------------------- */
        case 'L':               /* max amplification lenght   */
                                /* -------------------------- */
          sscanf(optarg,"%d",&(options.lmax));
          break;

                                /* -------------------- */
        case 'e':               /* error max            */
                                /* -------------------- */
          sscanf(optarg,"%d",&(options.error_max));
          break;


								/* ------------------------ */
		case '3':               /* three prime strict match */
                                /* ------------------------ */
			sscanf(optarg,"%d",&(options.strict_three_prime));
			break;

                                /* -------------------- */
        case 'q':               /* strict matching quorum           */
                                /* -------------------- */
          sscanf(optarg,"%f",&(options.strict_quorum));
          break;

								/* -------------------- */
        case 's':               /* strict matching quorum      */
								/* -------------------- */
        	sscanf(optarg,"%f",&(options.sensitivity_quorum));
        	break;

        						/* -------------------- */
        case 't':               /* required taxon level for results           */
        						/* -------------------- */
        	strncpy(options.taxonrank, optarg, 19);
        	options.taxonrank[19] = 0;
            break;
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
        						/* -------------------- */
        case 'x':               /* strict matching quorum           */
								/* -------------------- */
        	sscanf(optarg,"%f",&(options.false_positive_quorum));
        	break;

							    /* ---------------------------- */
		case 'D':               /* set in double strand mode    */
							    /* ---------------------------- */
			options.doublestrand=1;
			break;

								/* ---------------------------- */
		case 'S':               /* set in single strand mode    */
								/* ---------------------------- */
			options.doublestrand=0;
			break;

			                    /* ---------------------------- */
        case 'U':               /* set in single strand mode    */
			                    /* ---------------------------- */
            options.no_multi_match=TRUE;
            break;

         						/* ------------------------------------------ */
        case 'r':               /* stores the restricting search taxonomic id */
        						/* ------------------------------------------ */
          options.restricted_taxid = ECOREALLOC(options.restricted_taxid,sizeof(int32_t)*(options.r+1),
          									"Error on restricted_taxid reallocation");
          sscanf(optarg,"%d",&(options.restricted_taxid[options.r]));
          options.r++;
          break;

         						/* --------------------------------- */
        case 'i':               /* stores the taxonomic id to ignore */
        						/* --------------------------------- */
          options.ignored_taxid = ECOREALLOC(options.ignored_taxid,sizeof(int32_t)*(options.g+1),
          									"Error on excluded_taxid reallocation");
          sscanf(optarg,"%d",&(options.ignored_taxid[options.g]));
          options.g++;
          break;

                                /* -------------------- */
        case 'c':               /* sequences are circular */
        						/* --------------------------------- */
		  options.circular = 1;
          break;

        case '?':               /* bad option           */
                                /* -------------------- */
            errflag++;
   		}

	}

    fprintf(stderr,"Reading taxonomy database ...");
    taxonomy = read_taxonomy(options.prefix,0);
    fprintf(stderr,"Ok\n");
535

536
    setresulttaxonrank(taxonomy, &options); /*TR: set rank level for statistics*/
537

538 539 540 541 542 543
    fprintf(stderr,"Reading sequence database ...\n");

    seqdb = readdnadb(options.prefix,&seqdbsize);

    fprintf(stderr,"Ok\n");
    fprintf(stderr,"Sequence read : %d\n",(int32_t)seqdbsize);
544

545
    updateseqparams(seqdb, seqdbsize, taxonomy, &options, &insamples , &outsamples);
546 547 548
    options.dbsize=seqdbsize;
    options.insamples=insamples;
    options.outsamples=outsamples;
549 550 551

    rankdbstats = getrankdbstats(seqdb, seqdbsize, taxonomy, &options);

552 553 554 555
    fprintf(stderr,"Database is constituted of %5d examples        corresponding to %5d %s\n",insamples,
    		options.intaxa,options.taxonrank);
    fprintf(stderr,"                       and %5d counterexamples corresponding to %5d %s\n",outsamples,
    		options.outtaxa,options.taxonrank);
556 557 558 559 560 561 562
    fprintf(stderr,"Total distinct %s count %d\n",options.taxonrank, rankdbstats);

    fprintf(stderr,"\nIndexing words in sequences\n");

    printcurrenttimeinmilli();
    words = lookforStrictPrimer(seqdb,seqdbsize,insamples,&options);
    printcurrenttimeinmilli();
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
    fprintf(stderr,"\n  Strict primer count : %d\n",words->size);

    if (options.no_multi_match)
    {
    	(void)filterMultiStrictPrimer(words);
    	fprintf(stderr,"\n  Strict primer with single match count : %d\n",words->size);
    }


    fprintf(stderr,"\n\n  Primer sample : \n");
    for (i=0; i<MINI(10,words->size); i++)
    	fprintf(stderr,"  + Primer : %s   sequence count : %d\n",ecoUnhashWord(words->words[i],options.primer_length),words->strictcount[i]);


    fprintf(stderr,"\nEncoding sequences for fuzzy pattern matching...\n");
    for (i=0;i<seqdbsize;i++)
    {
    	encodeSequence(seqdb[i]);
    	fprintf(stderr,"  Encoded sequences %5d/%5d          \r",(int32_t)i+1,(int32_t)seqdbsize);
    }

    ECOFREE(words->strictcount,"Free strict primer count table");

    primers = lookforAproxPrimer(seqdb,seqdbsize,insamples,words,&options);

    ECOFREE(words->words,"Free strict primer table");
    ECOFREE(words,"Free strict primer structure");
    fprintf(stderr,"\n\n  Approximate repeats :%d \n", primers->size);

    fprintf(stderr,"\n\n  Primer sample : \n");
    for (i=0; i<MINI(10,primers->size); i++)
    	fprintf(stderr,"  + Primer : %s   example sequence count : %5d counterexample sequence count : %5d  status : %s\n",ecoUnhashWord(primers->primers[i].word,options.primer_length),
                       primers->primers[i].inexample,
                       primers->primers[i].outexample,
                       primers->primers[i].good ? "good":"bad");

    fprintf(stderr,"\n");

    /*TR: Added*/
    pairs = buildPrimerPairs(seqdb, seqdbsize, primers, &options);
    
605 606 607 608 609 610 611 612

  //  setoktaxforspecificity (&pairs);

     printpairs (pairs, &options);



    //ECOFREE(pairs.pairs,"Free pairs table");
613 614 615

    return 0;
}