Exemplo n.º 1
0
/* unsafe function that will be replaced by a threadsafe companion in the future */
PRIVATE void init_alifold(int length){
  unsigned int n;
  if (length<1) nrerror("initialize_fold: argument must be greater 0");
  if (init_length>0) free_alifold_arrays();
  get_arrays((unsigned) length);
  make_pair_matrix();
  init_length=length;

  for (n = 1; n <= (unsigned) length; n++)
    indx[n] = (n*(n-1)) >> 1;        /* n(n-1)/2 */

  update_fold_params();
}
Exemplo n.º 2
0
/* unsafe function that will be replaced by a threadsafe companion in the future */
PRIVATE void init_alifold(int length){

#ifdef _OPENMP
/* Explicitly turn off dynamic threads */
  omp_set_dynamic(0);
#endif

  if (length < 1) nrerror("initialize_fold: argument must be greater 0");
  free_alifold_arrays();
  get_arrays((unsigned) length);
  init_length = length;

  indx = get_indx((unsigned)length);

  update_alifold_params();
}
Exemplo n.º 3
0
Arquivo: RNAz.c Projeto: wash/rnaz
int main(int argc, char *argv[])
{

  char *modelDir=NULL;              /* Directory with model files */
  struct svm_model* decision_model; /* SVM classification model */

  /* Command line options */
  int reverse=0;     /* Scan reverse complement */
  int showVersion=0; /* Shows version and exits */
  int showHelp=0;    /* Show short help and exits */
  int from=-1;       /* Scan slice from-to  */
  int to=-1;

  FILE *clust_file=stdin; /* Input file */
  FILE *out=stdout; /* Output file */

  struct aln *AS[MAX_NUM_NAMES];     
  struct aln *window[MAX_NUM_NAMES]; 
  char *tmpAln[MAX_NUM_NAMES];

  int n_seq;  /* number of input sequences */
  int length; /* length of alignment/window */
  int z_score_type;
  int decision_model_type;

  char *structure=NULL;
  char *singleStruc,*gapStruc, *output,*woGapsSeq;
  char strand[8];
  char warningString[2000];
  char warningString_regression[2000];
  char *string=NULL;
  double singleMFE,sumMFE,singleZ,sumZ,z,sci,id,decValue,prob,comb,entropy,GC;
  double min_en, real_en;
  int i,j,k,l,ll,r,countAln,nonGaps,singleGC;
  int (*readFunction)(FILE *clust,struct aln *alignedSeqs[]);
  char** lines=NULL;
  int directions[3]={FORWARD,0,0};
  int currDirection;
  struct gengetopt_args_info args;

  double meanMFE_fwd=0;
  double consensusMFE_fwd=0;
  double sci_fwd=0;
  double z_fwd=0;
  int strandGuess;
  int avoid_shuffle=0;
  double strandProb,strandDec;
  
  if (cmdline_parser (argc, argv, &args) != 0){
    usage();
    exit(EXIT_FAILURE);
  }

  if (args.help_given){
    help();
    exit(EXIT_SUCCESS);
  }

  if (args.version_given){
    version();
    exit(EXIT_SUCCESS);
  }

  if (args.outfile_given){
    out = fopen(args.outfile_arg, "w");
    if (out == NULL){
      fprintf(stderr, "ERROR: Can't open output file %s\n", args.outfile_arg);
      exit(1);
    }
  }
    

  /* Strand prediction implies both strands scored */
  if (args.predict_strand_flag){
    args.both_strands_flag=1;
  }
  
  
  if (args.forward_flag && !args.reverse_flag){
    directions[0]=FORWARD;
    directions[1]=directions[2]=0;
  }
  if (!args.forward_flag && args.reverse_flag){
    directions[0]=REVERSE;
    directions[1]=directions[2]=0;
  }
  if ((args.forward_flag && args.reverse_flag) || args.both_strands_flag){
    directions[0]=FORWARD;
    directions[1]=REVERSE;
  }

  if (args.window_given){
    if (sscanf(args.window_arg,"%d-%d",&from,&to)!=2){
      nrerror("ERROR: Invalid --window/-w command. "
              "Use it like '--window 100-200'\n");
    }
    printf("from:%d,to:%d\n",from,to);
  }

  
  if (args.inputs_num>=1){
    clust_file = fopen(args.inputs[0], "r"); 
    if (clust_file == NULL){
      fprintf(stderr, "ERROR: Can't open input file %s\n", args.inputs[0]);
      exit(1);
    }
  }

 
  /* Global RNA package variables */
  do_backtrack = 1; 
  dangles=2;

  switch(checkFormat(clust_file)){
  case CLUSTAL:
    readFunction=&read_clustal;
    break;
  case MAF:
    readFunction=&read_maf;
    break;
  case 0:
    nrerror("ERROR: Unknown alignment file format. Use Clustal W or MAF format.\n");
  }

  /* Set z-score type (mono/dinucleotide) here */
  z_score_type = 2;

  if (args.mononucleotide_given) z_score_type = 0;


  /* now let's decide which decision model to take */
  /* decision_model_type = 1 for normal model used in RNAz 1.0 */
  /* decision_model_type = 2 for normal model using dinucelotide background */
  /* decision_model_type = 3 for structural model using dinucelotide background */
  decision_model_type = 2;
  if (args.mononucleotide_given) decision_model_type = 1;
  if (args.locarnate_given) decision_model_type = 3;
  if ((args.mononucleotide_given) && args.locarnate_given){
    z_score_type=2;
    nrerror("ERROR: Structural decision model only trained with dinucleotide background model.\n");
  }

  if (args.no_shuffle_given) avoid_shuffle = 1;

  decision_model=get_decision_model(NULL, decision_model_type);

  /* Initialize Regression Models for mononucleotide */
  /* Not needed if we score with dinucleotides */
  if (z_score_type == 0) regression_svm_init();
  
  countAln=0;

  while ((n_seq=readFunction(clust_file, AS))!=0){

	if (n_seq ==1){
	  nrerror("ERROR: You need at least two sequences in the alignment.\n");
	}
	
	countAln++;
	
	length = (int) strlen(AS[0]->seq);
	
	/* if a slice is specified by the user */
  
	if ((from!=-1 || to!=-1) && (countAln==1)){
      
	  if ((from>=to)||(from<=0)||(to>length)){
		nrerror("ERROR: Invalid window range given.\n");
	  }
	  
	  sliceAln((const struct aln**)AS, (struct aln **)window, from, to);
	  length=to-from+1;
	} else { /* take complete alignment */
	  /* window=AS does not work..., deep copy seems not necessary here*/
	  from=1;
	  to=length;
	  sliceAln((const struct aln **)AS, (struct aln **)window, 1, length);
	}

	 /* Convert all Us to Ts for RNAalifold. There is a slight
	    difference in the results. During training we used alignments
	    with Ts, so we use Ts here as well. */

	for (i=0;i<n_seq;i++){
	  j=0;
	  while (window[i]->seq[j]){
		window[i]->seq[j]=toupper(window[i]->seq[j]);
		if (window[i]->seq[j]=='U') window[i]->seq[j]='T';
		++j;
	  }
	}
	
	k=0;
	while ((currDirection=directions[k++])!=0){
	  
	  if (currDirection==REVERSE){
		revAln((struct aln **)window);
		strcpy(strand,"reverse");
	  } else {
		strcpy(strand,"forward");
	  }

	  structure = (char *) space((unsigned) length+1);

	  for (i=0;window[i]!=NULL;i++){
		tmpAln[i]=window[i]->seq;
	  }
	  tmpAln[i]=NULL;

	  min_en = alifold(tmpAln, structure);
	  free_alifold_arrays();

	  comb=combPerPair(window,structure);
	  
	  sumZ=0.0;
	  sumMFE=0.0;
	  GC=0.0;

	  output=(char *)space(sizeof(char)*(length+160)*(n_seq+1)*3);

	  strcpy(warningString,"");
	  strcpy(warningString_regression,"");

	  for (i=0;i<n_seq;i++){
		singleStruc = space(strlen(window[i]->seq)+1);
		woGapsSeq = space(strlen(window[i]->seq)+1);
		j=0;
		nonGaps=0;
		singleGC=0;
		while (window[i]->seq[j]){
		  /* Convert all Ts to Us for RNAfold. There is a difference
		     between the results. With U in the function call, we get
		     the results as RNAfold gives on the command line. Since
		     this variant was also used during training, we use it here
		     as well. */
		  if (window[i]->seq[j]=='T') window[i]->seq[j]='U';
		  if (window[i]->seq[j]=='C') singleGC++;
		  if (window[i]->seq[j]=='G') singleGC++;
		  if (window[i]->seq[j]!='-'){
		    nonGaps++;
		    woGapsSeq[strlen(woGapsSeq)]=window[i]->seq[j];
		    woGapsSeq[strlen(woGapsSeq)]='\0';
		  }
		  ++j;
		}
		
		/* z-score is calculated here! */
		singleMFE = fold(woGapsSeq, singleStruc);
		free_arrays();
		/* z-score type may be overwritten. If it is out of training
		   bounds, we switch to shuffling if allowed (avoid_shuffle). */
		int z_score_type_orig = z_score_type;


		singleZ=mfe_zscore(woGapsSeq,singleMFE, &z_score_type, avoid_shuffle, warningString_regression);

		GC+=(double) singleGC/nonGaps;
		sumZ+=singleZ;
		sumMFE+=singleMFE;

		if (window[1]->strand!='?' && !args.window_given){
		  sprintf(output+strlen(output),
			  ">%s %d %d %c %d\n",
			  window[i]->name,window[i]->start,
			  window[i]->length,window[i]->strand,
			  window[i]->fullLength);
		} else {
		  sprintf(output+strlen(output),">%s\n",window[i]->name);
		}


    gapStruc= (char *) space(sizeof(char)*(strlen(window[i]->seq)+1));

    l=ll=0;

    while (window[i]->seq[l]!='\0'){
			if (window[i]->seq[l]!='-'){
			  gapStruc[l]=singleStruc[ll];
			  l++;
			  ll++;
			} else {
			  gapStruc[l]='-';
			  l++;
			}
    }
    char ch;
    ch = 'R';
    if (z_score_type == 1 || z_score_type == 3) ch = 'S';
		  		  
    sprintf(output+strlen(output),"%s\n%s ( %6.2f, z-score = %6.2f, %c)\n",
            window[i]->seq,gapStruc,singleMFE,singleZ,ch);
    z_score_type = z_score_type_orig;
		  

		free(woGapsSeq);
		free(singleStruc);
		
	  }

	  {
		int i; double s=0;
		extern int eos_debug;
		eos_debug=-1; /* shut off warnings about nonstandard pairs */
		for (i=0; window[i]!=NULL; i++) 
		  s += energy_of_struct(window[i]->seq, structure);
		real_en = s/i;
	  }

	  string = consensus((const struct aln**) window);
	  sprintf(output+strlen(output),
			  ">consensus\n%s\n%s (%6.2f = %6.2f + %6.2f) \n",
			  string, structure, min_en, real_en, min_en-real_en );
	  free(string);

	  id=meanPairID((const struct aln**)window);
	  entropy=NormShannonEntropy((const struct aln**)window);
	  z=sumZ/n_seq;
	  GC=(double)GC/n_seq;

	  if (sumMFE==0){ 
		/*Set SCI to 0 in the weird case of no structure in single
		  sequences*/
		sci=0;
	  } else {
		sci=min_en/(sumMFE/n_seq);
	  }

	  
	  	  
	  decValue=999;
	  prob=0;
	
	  classify(&prob,&decValue,decision_model,id,n_seq,z,sci,entropy,decision_model_type);

	  if (args.cutoff_given){
		if (prob<args.cutoff_arg){
		  continue;
		}
	  }

	  warning(warningString,id,n_seq,z,sci,entropy,(struct aln **)window,decision_model_type);
	  

 	  fprintf(out,"\n############################  RNAz "PACKAGE_VERSION"  ##############################\n\n"); 
 	  fprintf(out," Sequences: %u\n", n_seq); 

 	  if (args.window_given){ 
 		fprintf(out," Slice: %u to %u\n",from,to); 
 	  } 
 	  fprintf(out," Columns: %u\n",length);
 	  fprintf(out," Reading direction: %s\n",strand); 
	  fprintf(out," Mean pairwise identity: %6.2f\n", id);
	  fprintf(out," Shannon entropy: %2.5f\n", entropy);
	  fprintf(out," G+C content: %2.5f\n", GC);
 	  fprintf(out," Mean single sequence MFE: %6.2f\n", sumMFE/n_seq); 
 	  fprintf(out," Consensus MFE: %6.2f\n",min_en); 
 	  fprintf(out," Energy contribution: %6.2f\n",real_en); 
 	  fprintf(out," Covariance contribution: %6.2f\n",min_en-real_en); 
 	  fprintf(out," Combinations/Pair: %6.2f\n",comb); 
	  fprintf(out," Mean z-score: %6.2f\n",z);
	  fprintf(out," Structure conservation index: %6.2f\n",sci);
	  if (decision_model_type == 1) {
	    fprintf(out," Background model: mononucleotide\n");
	    fprintf(out," Decision model: sequence based alignment quality\n");
	  }
	  if (decision_model_type == 2) {
	    fprintf(out," Background model: dinucleotide\n");
	    fprintf(out," Decision model: sequence based alignment quality\n");
	  }
	  if (decision_model_type == 3) {
	    fprintf(out," Background model: dinucleotide\n");
	    fprintf(out," Decision model: structural RNA alignment quality\n");
	  }
 	  fprintf(out," SVM decision value: %6.2f\n",decValue); 
 	  fprintf(out," SVM RNA-class probability: %6f\n",prob); 
 	  if (prob>0.5){ 
 		fprintf(out," Prediction: RNA\n"); 
 	  } 
 	  else { 
 		fprintf(out," Prediction: OTHER\n"); 
 	  } 

	  fprintf(out,"%s",warningString_regression);

	  fprintf(out,"%s",warningString);
	  
 	  fprintf(out,"\n######################################################################\n\n"); 
	
 	  fprintf(out,"%s",output); 
	
	  fflush(out);

	  free(structure);
	  free(output);

	  if (currDirection==FORWARD && args.predict_strand_flag){
		meanMFE_fwd=sumMFE/n_seq;
		consensusMFE_fwd=min_en;
		sci_fwd=sci;
		z_fwd=z;
	  }

	  if (currDirection==REVERSE && args.predict_strand_flag){

		if (predict_strand(sci_fwd-sci, meanMFE_fwd-(sumMFE/n_seq),
						   consensusMFE_fwd-min_en, z_fwd-z, n_seq, id, 
						   &strandGuess, &strandProb, &strandDec, NULL)){
		  if (strandGuess==1){
			fprintf(out, "\n# Strand winner: forward (%.2f)\n",strandProb);
		  } else {
			fprintf(out, "\n# Strand winner: reverse (%.2f)\n",1-strandProb);
		  }
		} else {
		  fprintf(out, "\n# WARNING: No strand prediction (values out of range)\n");
		}
	  }
	}
	freeAln((struct aln **)AS);
	freeAln((struct aln **)window);
	
  }
  if (args.inputs_num>=1){
    fclose(clust_file);
  }
  cmdline_parser_free (&args);

  if (countAln==0){
	nrerror("ERROR: Empty alignment file\n");
  }
  
  
  svm_destroy_model(decision_model);
  regression_svm_free();
  
  
  return 0;
}
Exemplo n.º 4
0
/*--------------------------------------------------------------------------*/
int main(int argc, char *argv[]){
  struct        RNAalifold_args_info args_info;
  unsigned int  input_type;
  char          ffname[FILENAME_MAX_LENGTH], gfname[FILENAME_MAX_LENGTH], fname[FILENAME_MAX_LENGTH];
  char          *input_string, *string, *structure, *cstruc, *ParamFile, *ns_bases, *c;
  int           n_seq, i, length, sym, r, noPS, with_sci;
  int           endgaps, mis, circular, doAlnPS, doColor, doMEA, n_back, eval_energy, pf, istty;
  double        min_en, real_en, sfact, MEAgamma, bppmThreshold, betaScale;
  char          *AS[MAX_NUM_NAMES];          /* aligned sequences */
  char          *names[MAX_NUM_NAMES];       /* sequence names */
  FILE          *clust_file = stdin;
  pf_paramT     *pf_parameters;
  model_detailsT  md;

  fname[0] = ffname[0] = gfname[0] = '\0';
  string = structure = cstruc = ParamFile = ns_bases = NULL;
  pf_parameters = NULL;
  endgaps = mis = pf = circular = doAlnPS = doColor = n_back = eval_energy = oldAliEn = doMEA = ribo = noPS = 0;
  do_backtrack  = 1;
  dangles       = 2;
  gquad         = 0;
  sfact         = 1.07;
  bppmThreshold = 1e-6;
  MEAgamma      = 1.0;
  betaScale     = 1.;
  with_sci      = 0;

  set_model_details(&md);

  /*
  #############################################
  # check the command line prameters
  #############################################
  */
  if(RNAalifold_cmdline_parser (argc, argv, &args_info) != 0) exit(1);
  /* temperature */
  if(args_info.temp_given)        temperature = args_info.temp_arg;
  /* structure constraint */
  if(args_info.constraint_given)  fold_constrained=1;
  /* do not take special tetra loop energies into account */
  if(args_info.noTetra_given)     md.special_hp = tetra_loop=0;
  /* set dangle model */
  if(args_info.dangles_given){
    if((args_info.dangles_arg != 0) && (args_info.dangles_arg != 2))
      warn_user("required dangle model not implemented, falling back to default dangles=2");
    else
      md.dangles = dangles=args_info.dangles_arg;
  }
  /* do not allow weak pairs */
  if(args_info.noLP_given)        md.noLP = noLonelyPairs = 1;
  /* do not allow wobble pairs (GU) */
  if(args_info.noGU_given)        md.noGU = noGU = 1;
  /* do not allow weak closing pairs (AU,GU) */
  if(args_info.noClosingGU_given) md.noGUclosure = no_closingGU = 1;
  /* gquadruplex support */
  if(args_info.gquad_given)       md.gquad = gquad = 1;
  /* sci computation */
  if(args_info.sci_given)         with_sci = 1;
  /* do not convert DNA nucleotide "T" to appropriate RNA "U" */
  /* set energy model */
  if(args_info.energyModel_given) energy_set = args_info.energyModel_arg;
  /* take another energy parameter set */
  if(args_info.paramFile_given)   ParamFile = strdup(args_info.paramFile_arg);
  /* Allow other pairs in addition to the usual AU,GC,and GU pairs */
  if(args_info.nsp_given)         ns_bases = strdup(args_info.nsp_arg);
  /* set pf scaling factor */
  if(args_info.pfScale_given)     sfact = args_info.pfScale_arg;
  /* assume RNA sequence to be circular */
  if(args_info.circ_given)        circular=1;
  /* do not produce postscript output */
  if(args_info.noPS_given)        noPS = 1;
  /* partition function settings */
  if(args_info.partfunc_given){
    pf = 1;
    if(args_info.partfunc_arg != -1)
      do_backtrack = args_info.partfunc_arg;
  }
  /* MEA (maximum expected accuracy) settings */
  if(args_info.MEA_given){
    pf = doMEA = 1;
    if(args_info.MEA_arg != -1)
      MEAgamma = args_info.MEA_arg;
  }
  if(args_info.betaScale_given)   betaScale = args_info.betaScale_arg;
  /* set the bppm threshold for the dotplot */
  if(args_info.bppmThreshold_given)
    bppmThreshold = MIN2(1., MAX2(0.,args_info.bppmThreshold_arg));
  /* set cfactor */
  if(args_info.cfactor_given)     cv_fact = args_info.cfactor_arg;
  /* set nfactor */
  if(args_info.nfactor_given)     nc_fact = args_info.nfactor_arg;
  if(args_info.endgaps_given)     endgaps = 1;
  if(args_info.mis_given)         mis = 1;
  if(args_info.color_given)       doColor=1;
  if(args_info.aln_given)         doAlnPS=1;
  if(args_info.old_given)         oldAliEn = 1;
  if(args_info.stochBT_given){
    n_back = args_info.stochBT_arg;
    do_backtrack = 0;
    pf = 1;
    init_rand();
  }
  if(args_info.stochBT_en_given){
    n_back = args_info.stochBT_en_arg;
    do_backtrack = 0;
    pf = 1;
    eval_energy = 1;
    init_rand();
  }
  if(args_info.ribosum_file_given){
    RibosumFile = strdup(args_info.ribosum_file_arg);
    ribo = 1;
  }
  if(args_info.ribosum_scoring_given){
    RibosumFile = NULL;
    ribo = 1;
  }
  if(args_info.layout_type_given)
    rna_plot_type = args_info.layout_type_arg;

  /* alignment file name given as unnamed option? */
  if(args_info.inputs_num == 1){
    clust_file = fopen(args_info.inputs[0], "r");
    if (clust_file == NULL) {
      fprintf(stderr, "can't open %s\n", args_info.inputs[0]);
    }
  }

  /* free allocated memory of command line data structure */
  RNAalifold_cmdline_parser_free (&args_info);

  /*
  #############################################
  # begin initializing
  #############################################
  */
  if(circular && gquad){
    nrerror("G-Quadruplex support is currently not available for circular RNA structures");
  }

  make_pair_matrix();

  if (circular && noLonelyPairs)
    warn_user("depending on the origin of the circular sequence, "
            "some structures may be missed when using --noLP\n"
            "Try rotating your sequence a few times\n");

  if (ParamFile != NULL) read_parameter_file(ParamFile);

  if (ns_bases != NULL) {
    nonstandards = space(33);
    c=ns_bases;
    i=sym=0;
    if (*c=='-') {
      sym=1; c++;
    }
    while (*c!='\0') {
      if (*c!=',') {
        nonstandards[i++]=*c++;
        nonstandards[i++]=*c;
        if ((sym)&&(*c!=*(c-1))) {
          nonstandards[i++]=*c;
          nonstandards[i++]=*(c-1);
        }
      }
      c++;
    }
  }

  istty = isatty(fileno(stdout))&&isatty(fileno(stdin));

  /*
  ########################################################
  # handle user input from 'stdin' if necessary
  ########################################################
  */
  if(fold_constrained){
    if(istty){
      print_tty_constraint_full();
      print_tty_input_seq_str("");
    }
    input_type = get_input_line(&input_string, VRNA_INPUT_NOSKIP_COMMENTS);
    if(input_type & VRNA_INPUT_QUIT){ return 0;}
    else if((input_type & VRNA_INPUT_MISC) && (strlen(input_string) > 0)){
      cstruc = strdup(input_string);
      free(input_string);
    }
    else warn_user("constraints missing");
  }

  if (istty && (clust_file == stdin))
    print_tty_input_seq_str("Input aligned sequences in clustalw or stockholm format\n(enter a line starting with \"//\" to indicate the end of your input)");

  n_seq = read_clustal(clust_file, AS, names);
  if (n_seq==0) nrerror("no sequences found");

  if (clust_file != stdin) fclose(clust_file);
  /*
  ########################################################
  # done with 'stdin' handling, now init everything properly
  ########################################################
  */

  length    = (int)   strlen(AS[0]);
  structure = (char *)space((unsigned) length+1);

  if(fold_constrained && cstruc != NULL)
    strncpy(structure, cstruc, length);

  if (endgaps)
    for (i=0; i<n_seq; i++) mark_endgaps(AS[i], '~');

  /*
  ########################################################
  # begin actual calculations
  ########################################################
  */

  if (circular) {
    int     i;
    double  s = 0;
    min_en    = circalifold((const char **)AS, structure);
    for (i=0; AS[i]!=NULL; i++)
      s += energy_of_circ_structure(AS[i], structure, -1);
    real_en = s/i;
  } else {
    float *ens  = (float *)space(2*sizeof(float));
    min_en      = alifold((const char **)AS, structure);
    if(md.gquad)
      energy_of_ali_gquad_structure((const char **)AS, structure, n_seq, ens);
    else
      energy_of_alistruct((const char **)AS, structure, n_seq, ens);

    real_en     = ens[0];
    free(ens);
  }

  string = (mis) ? consens_mis((const char **) AS) : consensus((const char **) AS);
  printf("%s\n%s", string, structure);

  if(istty){
    if(with_sci){
      float sci = min_en;
      float e_mean = 0;
      for (i=0; AS[i]!=NULL; i++){
        char *seq = get_ungapped_sequence(AS[i]);
        char *str = (char *)space(sizeof(char) * (strlen(seq) + 1));
        e_mean    += fold(seq, str);
        free(seq);
        free(str);
      }
      e_mean  /= i;
      sci     /= e_mean;

      printf( "\n minimum free energy = %6.2f kcal/mol (%6.2f + %6.2f)"
              "\n SCI = %2.4f\n",
              min_en, real_en, min_en-real_en, sci);
    } else
      printf("\n minimum free energy = %6.2f kcal/mol (%6.2f + %6.2f)\n",
             min_en, real_en, min_en - real_en);
  } else {
    if(with_sci){
      float sci = min_en;
      float e_mean = 0;
      for (i=0; AS[i]!=NULL; i++){
        char *seq = get_ungapped_sequence(AS[i]);
        char *str = (char *)space(sizeof(char) * (strlen(seq) + 1));
        e_mean    += fold(seq, str);
        free(seq);
        free(str);
      }
      e_mean  /= i;
      sci     /= e_mean;

      printf(" (%6.2f = %6.2f + %6.2f) [%2.4f]\n", min_en, real_en, min_en-real_en, sci);
    }
    else
      printf(" (%6.2f = %6.2f + %6.2f) \n", min_en, real_en, min_en-real_en );
  }

  strcpy(ffname, "alirna.ps");
  strcpy(gfname, "alirna.g");

  if (!noPS) {
    char **A;
    A = annote(structure, (const char**) AS);

    if(md.gquad){
      if (doColor)
        (void) PS_rna_plot_a_gquad(string, structure, ffname, A[0], A[1]);
      else
        (void) PS_rna_plot_a_gquad(string, structure, ffname, NULL, A[1]);
    } else {
      if (doColor)
        (void) PS_rna_plot_a(string, structure, ffname, A[0], A[1]);
      else
        (void) PS_rna_plot_a(string, structure, ffname, NULL, A[1]);
    }
    free(A[0]); free(A[1]); free(A);
  }
  if (doAlnPS)
    PS_color_aln(structure, "aln.ps", (const char const **) AS, (const char const **) names);

  /* free mfe arrays */
  free_alifold_arrays();

  if (pf) {
    float energy, kT;
    char * mfe_struc;

    mfe_struc = strdup(structure);

    kT = (betaScale*((temperature+K0)*GASCONST))/1000.; /* in Kcal */
    pf_scale = exp(-(sfact*min_en)/kT/length);
    if (length>2000) fprintf(stderr, "scaling factor %f\n", pf_scale);
    fflush(stdout);

    if (cstruc!=NULL) strncpy(structure, cstruc, length+1);

    pf_parameters = get_boltzmann_factors_ali(n_seq, temperature, betaScale, md, pf_scale);
    energy = alipf_fold_par((const char **)AS, structure, NULL, pf_parameters, do_backtrack, fold_constrained, circular);

    if (n_back>0) {
      /*stochastic sampling*/
      for (i=0; i<n_back; i++) {
        char *s;
        double prob=1.;
        s = alipbacktrack(&prob);
        printf("%s ", s);
        if (eval_energy ) printf("%6g %.2f ",prob, -1*(kT*log(prob)-energy));
        printf("\n");
         free(s);
      }

    }
    if (do_backtrack) {
      printf("%s", structure);
      if (!istty) printf(" [%6.2f]\n", energy);
      else printf("\n");
    }
    if ((istty)||(!do_backtrack))
      printf(" free energy of ensemble = %6.2f kcal/mol\n", energy);
    printf(" frequency of mfe structure in ensemble %g\n",
           exp((energy-min_en)/kT));

    if (do_backtrack) {
      FILE *aliout;
      cpair *cp;
      char *cent;
      double dist;
      FLT_OR_DBL *probs = export_ali_bppm();
      plist *pl, *mfel;

      assign_plist_from_pr(&pl, probs, length, bppmThreshold);
      assign_plist_from_db(&mfel, mfe_struc, 0.95*0.95);

      if (!circular){
        float *ens;
        cent = get_centroid_struct_pr(length, &dist, probs);
        ens=(float *)space(2*sizeof(float));
        energy_of_alistruct((const char **)AS, cent, n_seq, ens);
        /*cent_en = energy_of_struct(string, cent);*/ /*ali*/
        printf("%s %6.2f {%6.2f + %6.2f}\n",cent,ens[0]-ens[1],ens[0],(-1)*ens[1]);
        free(cent);
        free(ens);
      }
      if(doMEA){
        float mea, *ens;
        plist *pl2;
        assign_plist_from_pr(&pl2, probs, length, 1e-4/(1+MEAgamma));
        mea = MEA(pl2, structure, MEAgamma);
        ens = (float *)space(2*sizeof(float));
        if(circular)
          energy_of_alistruct((const char **)AS, structure, n_seq, ens);
        else
          ens[0] = energy_of_structure(string, structure, 0);
        printf("%s {%6.2f MEA=%.2f}\n", structure, ens[0], mea);
        free(ens);
        free(pl2);
      }

      if (fname[0]!='\0') {
        strcpy(ffname, fname);
        strcat(ffname, "_ali.out");
      } else strcpy(ffname, "alifold.out");
      aliout = fopen(ffname, "w");
      if (!aliout) {
        fprintf(stderr, "can't open %s    skipping output\n", ffname);
      } else {
        print_aliout(AS, pl, bppmThreshold, n_seq, mfe_struc, aliout);
      }
      fclose(aliout);
      if (fname[0]!='\0') {
        strcpy(ffname, fname);
        strcat(ffname, "_dp.ps");
      } else strcpy(ffname, "alidot.ps");
      cp = make_color_pinfo(AS,pl, bppmThreshold, n_seq, mfel);
      (void) PS_color_dot_plot(string, cp, ffname);
      free(cp);
      free(pl);
      free(mfel);
    }
    free(mfe_struc);
    free_alipf_arrays();
    free(pf_parameters);
  }
  if (cstruc!=NULL) free(cstruc);
  (void) fflush(stdout);
  free(string);
  free(structure);
  for (i=0; AS[i]; i++) {
    free(AS[i]); free(names[i]);
  }
  return 0;
}
Exemplo n.º 5
0
int main(int argc, char *argv[])
{
    char *string;
    char *structure=NULL;
    char *cstruc=NULL;
    char *ns_bases=NULL;
    char *c;
    int  n_seq;
    int  i;
    int  length;
    int  sym;
    int  endgaps = 0;
    int  mis = 0;
    double min_en;
    double real_en;
    double sfact = 1.07;
    int  pf = 0;
    int  istty;
    char *AS[MAX_NUM_NAMES];	/* aligned sequences */
    char *names[MAX_NUM_NAMES];	/* sequence names */

    AjPSeqset  seq       = NULL;

    AjPFile confile   = NULL;
    AjPFile alifile   = NULL;
    AjPFile paramfile = NULL;
    AjPFile outf      = NULL;
    AjPFile essfile   = NULL;
    AjPFile dotfile   = NULL;
    

    AjPStr constring = NULL;
  
    float eT = 0.;
    AjBool eGU;
  
    AjBool eclose;
    AjBool lonely;
    AjPStr ensbases = NULL;
    AjBool etloop;
    AjPStr eenergy = NULL;
    char ewt = '\0';
    float escale = 0.;
    AjPStr edangles = NULL;
    char edangle = '\0';

    ajint len;

    AjPSeq tseq = NULL;
    AjPStr tname = NULL;

    int circ = 0;
    int doAlnPS = 0;
    int doColor = 0;
    

    embInitPV("vrnaalifoldpf",argc,argv,"VIENNA",VERSION);
    
    
    constring = ajStrNew();
    
    seq       = ajAcdGetSeqset("sequence");
    confile   = ajAcdGetInfile("constraintfile");
    paramfile = ajAcdGetInfile("paramfile");
    eT        = ajAcdGetFloat("temperature");
    eGU       = ajAcdGetBoolean("gu");
    eclose    = ajAcdGetBoolean("closegu");
    lonely    = ajAcdGetBoolean("lp");
    ensbases  = ajAcdGetString("nsbases");
    etloop    = ajAcdGetBoolean("tetraloop");
    eenergy   = ajAcdGetListSingle("energy");
    escale    = ajAcdGetFloat("scale");
    edangles  = ajAcdGetListSingle("dangles");
    mis       = !!ajAcdGetBoolean("most");
    endgaps   = !!ajAcdGetBoolean("endgaps");
    nc_fact   = (double) ajAcdGetFloat("nspenalty");
    cv_fact   = (double) ajAcdGetFloat("covariance");

    outf      = ajAcdGetOutfile("outfile");
    essfile   = ajAcdGetOutfile("ssoutfile");
    alifile   = ajAcdGetOutfile("alignoutfile");
    circ      = !!ajAcdGetBoolean("circular");
    doColor   = !!ajAcdGetBoolean("colour");

    dotfile   = ajAcdGetOutfile("dotoutfile");
    
    
    do_backtrack = 1; 
    pf = 1;
    string = NULL;
    istty = 0;
    dangles = 2;

    temperature   = (double) eT;
    noGU          = (eGU) ? 0 : 1;
    no_closingGU  = (eclose) ? 0 : 1;
    noLonelyPairs = (lonely) ? 0 : 1;
    ns_bases      = (ajStrGetLen(ensbases)) ? MAJSTRGETPTR(ensbases) : NULL;
    tetra_loop    = !!etloop;
    
    ewt = *ajStrGetPtr(eenergy);
    if(ewt == '0')
	energy_set = 0;
    else if(ewt == '1')
	energy_set = 1;
    else if(ewt == '2')
	energy_set = 2;
    
    sfact = (double) escale;
    
    edangle = *ajStrGetPtr(edangles);
    if(edangle == '0')
	dangles = 0;
    else if(edangle == '1')
	dangles = 1;
    else if(edangle == '2')
	dangles = 2;
    else if(edangle == '3')
	dangles = 3;


    if(paramfile)
	read_parameter_file(paramfile);
   
    if (ns_bases != NULL)
    {
	nonstandards = space(33);
	c=ns_bases;
	i=sym=0;
	if (*c=='-')
	{
	    sym=1;
	    c++;
	}
	while (*c!='\0')
	{
	    if (*c!=',')
	    {
		nonstandards[i++]=*c++;
		nonstandards[i++]=*c;
		if ((sym)&&(*c!=*(c-1)))
		{
		    nonstandards[i++]=*c;
		    nonstandards[i++]=*(c-1);
		}
	    }
	    c++;
	}
    }

    if(alifile)
        doAlnPS = 1;

    
    if(confile)
	vienna_GetConstraints(confile,&constring);

    n_seq = ajSeqsetGetSize(seq);

    if(n_seq > MAX_NUM_NAMES - 1)
	ajFatal("[e]RNAalifold is restricted to %d sequences\n",
		MAX_NUM_NAMES - 1);

    if (n_seq==0)
	ajFatal("No sequences found");

    for(i=0;i<n_seq;++i)
    {
	tseq  = (AjPSeq) ajSeqsetGetseqSeq(seq,i);
	ajSeqGapStandard(tseq, '-');
	tname = (AjPStr) ajSeqsetGetseqNameS(seq,i);
	len   = ajSeqGetLen(tseq);
	AS[i] = (char *) space(len+1);
	names[i] = (char *) space(ajStrGetLen(tname)+1);
	strcpy(AS[i],ajSeqGetSeqC(tseq));
	strcpy(names[i],ajStrGetPtr(tname));
    }
    AS[n_seq] = NULL;
    names[n_seq] = NULL;
    
    if (endgaps)
	for (i=0; i<n_seq; i++)
	    mark_endgaps(AS[i], '~');


    length = (int) strlen(AS[0]);
    structure = (char *) space((unsigned) length+1);
    if(confile)
    {
	fold_constrained = 1;
	strcpy(structure,ajStrGetPtr(constring));
    }

    
  
  if (circ && noLonelyPairs)
    ajWarn(
	    "warning, depending on the origin of the circular sequence, "
	    "some structures may be missed when using -noLP\n"
	    "Try rotating your sequence a few times\n");

  if (circ)
      min_en = circalifold((const char **)AS, structure);
  else
    min_en = alifold(AS, structure);
  {
    int i;
    double s=0;
    extern int eos_debug;
    eos_debug=-1; /* shut off warnings about nonstandard pairs */
    for (i=0; AS[i]!=NULL; i++)
      if (circ)
	s += energy_of_circ_struct(AS[i], structure);
      else
	s += energy_of_struct(AS[i], structure);
    real_en = s/i;
  }
  string = (mis) ?
    consens_mis((const char **) AS) : consensus((const char **) AS);
  ajFmtPrintF(outf,"%s\n%s", string, structure);

  ajFmtPrintF(outf," (%6.2f = %6.2f + %6.2f) \n", min_en, real_en,
              min_en-real_en );

  if (length<=2500) {
    char **A;
    A = annote(structure, (const char**) AS);
    if (doColor)
      (void) PS_rna_plot_a(string, structure, essfile, A[0], A[1]);
    else
      (void) PS_rna_plot_a(string, structure, essfile, NULL, A[1]);
    free(A[0]); free(A[1]);free(A);
  } else
    ajWarn("INFO: structure too long, not doing xy_plot\n");

  if (doAlnPS)
    PS_color_aln(structure, alifile, AS,  names);

  { /* free mfe arrays but preserve base_pair for PS_dot_plot */
    struct bond  *bp;
    bp = base_pair; base_pair = space(16);
    free_alifold_arrays();  /* free's base_pair */
    free_alipf_arrays();
    base_pair = bp;
  }
  if (pf) {
    double energy, kT;
    pair_info *pi;
    char * mfe_struc;

    mfe_struc = strdup(structure);

    kT = (temperature+273.15)*1.98717/1000.; /* in Kcal */
    pf_scale = exp(-(sfact*min_en)/kT/length);
    if (length>2000)
        ajWarn("scaling factor %f\n", pf_scale);

    /* init_alipf_fold(length); */

    if (confile)
        strncpy(structure, ajStrGetPtr(constring), length+1);
    energy = (circ) ? alipf_circ_fold(AS, structure, &pi) : alipf_fold(AS, structure, &pi);

    if (do_backtrack) {
        ajFmtPrintF(outf,"%s", structure);
        ajFmtPrintF(outf," [%6.2f]\n", energy);
    }
    if ((istty)||(!do_backtrack))
        ajFmtPrintF(outf," free energy of ensemble = %6.2f kcal/mol\n", energy);
    ajFmtPrintF(outf," frequency of mfe structure in ensemble %g\n",
	   exp((energy-min_en)/kT));

    if (do_backtrack) {
      FILE *aliout;
      cpair *cp;
      short *ptable; int k;
	ptable = make_pair_table(mfe_struc);
        ajFmtPrintF(outf,"\n# Alignment section\n\n");
        aliout = ajFileGetFileptr(outf);
        
	fprintf(aliout, "%d sequences; length of alignment %d\n",
		n_seq, length);
	fprintf(aliout, "alifold output\n");
	for (k=0; pi[k].i>0; k++) {
	  pi[k].comp = (ptable[pi[k].i] == pi[k].j) ? 1:0;
	  print_pi(pi[k], aliout);
	}
	fprintf(aliout, "%s\n", structure);
	free(ptable);

    cp = make_color_pinfo(pi);
      (void) PS_color_dot_plot(string, cp, dotfile);
      free(cp);
    free(mfe_struc);
    free(pi);
    }
  }
  


  if (cstruc!=NULL) free(cstruc);
  free(base_pair);
  (void) fflush(stdout);
  free(string);
  free(structure);
  for (i=0; AS[i]; i++) {
    free(AS[i]); free(names[i]);
  }

  ajSeqsetDel(&seq);
  ajStrDel(&constring);
  ajStrDel(&eenergy);
  ajStrDel(&edangles);
  ajStrDel(&ensbases);

  ajFileClose(&confile);
  ajFileClose(&paramfile);
  ajFileClose(&outf);
  ajFileClose(&essfile);
  ajFileClose(&alifile);
  ajFileClose(&dotfile);

  embExit();  

  return 0;
}