コード例 #1
0
ファイル: task_dispatcher.c プロジェクト: asqz/runner
struct task_t* task_dispatcher_enqueue_task(struct task_dispatcher_t* td, task_callback_pf callback, void* ctx, long delay, long interval)
{
   struct task_t task =
   {
      .callback = callback,
      .ctx = ctx,
      .interval = interval,
   };

   timestamp_set(&task.enqueue_time);
   timestamp_offset(&task.enqueue_time, &task.activate_time, delay);

   pthread_mutex_lock(&td->lock);

   struct task_t* queued_task = pool_get_next(td->tasks, NULL);
   struct task_t* after = NULL;
   while (queued_task != NULL && timestamp_diff(&queued_task->activate_time, &task.activate_time) <= 0)
   {
      after = queued_task;
      queued_task = pool_get_next(td->tasks, queued_task);
   }

   struct task_t* p = pool_insert(td->tasks, &task, after);
   LOGD("Enqueued task %p after %p", p, after);

   if (after == NULL)
   {
      pthread_cond_broadcast(&td->event);
   }

   pthread_mutex_unlock(&td->lock);

   return p;
}
コード例 #2
0
ファイル: glx_hook.c プロジェクト: derhass/glx_hook
static void
frametimes_init_base(GH_frametimes *ft)
{
	/* get the base timestamp */
	if (ft->mode > GH_FRAMETIME_NONE) {
		GH_timestamp base;
		unsigned int i;
		GH_frametime *last=&ft->frametime[ft->num_results * ft->num_timestamps];

		timestamp_init(&base);
		timestamp_set(&base, &last[0], ft->mode);
		timestamp_set(&base, &last[0], ft->mode);
		for (i=1; i<ft->num_timestamps; i++) {
			last[i]=last[0];
		}
		timestamp_cleanup(&base);
	}
}
コード例 #3
0
ファイル: glx_hook.c プロジェクト: derhass/glx_hook
static void
frametimes_before_swap(GH_frametimes *ft)
{
	unsigned int ts_idx;
	unsigned int rs_idx;

	if (ft->mode == GH_FRAMETIME_NONE)
		return;
	ts_idx=ft->cur_pos * ft->num_timestamps + GH_FRAMETIME_BEFORE_SWAPBUFFERS;
	rs_idx=ft->cur_result * ft->num_timestamps + GH_FRAMETIME_BEFORE_SWAPBUFFERS;
	timestamp_set(&ft->timestamp[ts_idx], &ft->frametime[rs_idx], ft->mode);
}
コード例 #4
0
ファイル: glx_hook.c プロジェクト: derhass/glx_hook
static void
frametimes_after_swap(GH_frametimes *ft)
{
	unsigned int ts_idx;
	unsigned int rs_idx;

	if (ft->mode == GH_FRAMETIME_NONE)
		return;
	ts_idx=ft->cur_pos * ft->num_timestamps + GH_FRAMETIME_AFTER_SWAPBUFFERS;
	rs_idx=ft->cur_result * ft->num_timestamps + GH_FRAMETIME_AFTER_SWAPBUFFERS;
	timestamp_set(&ft->timestamp[ts_idx], &ft->frametime[rs_idx], ft->mode);
	frametimes_finish_frame(ft);
}
コード例 #5
0
ファイル: achievements_manager.c プロジェクト: asqz/runner
int am_update_achievements(achievement_manager_t* am, void* context)
{
   timestamp_t current_time = {0};
   timestamp_set(&current_time);

   uint32_t i = 0;
   achievement_state_t* state = &am->states[0];
   for (; i < am->nachievements; ++i, ++state)
   {
      const achievement_info_t* info = am->achievements[i];
      achievement_status_t* status = &state->status;

      if (status->unlocked)
      {
         continue;
      }

      int32_t progress = (*info->get_progress)(info, &current_time, &state->data, context);
      if (progress != status->progress)
      {
         status->last_change = current_time;
         status->prev_progress = status->progress;
         status->progress = progress;

         if (status->progress >= info->target_progress)
         {
            LOGI("Achievement '%s' unlocked", info->id);
            status->unlocked = 1;
            status->unlocked_at = current_time;

            // notify about achievement unlocked
            if (am->unlocked)
            {
               (*am->unlocked)(info);
            }
         }
         else if ((int)(status->prev_progress / info->notification_step) < (int)(status->progress / info->notification_step))
         {
            LOGI("Achievement '%s' progress [%d of %d]", info->id, status->progress, info->target_progress);

            // notify about achievement progress
            if (am->progress)
            {
               (*am->progress)(info, status);
            }
         }
      }
   }

   return 0;
}
コード例 #6
0
void SensorConditionItem::getStruct(shf_condition_item_t* item) const
{
    memset(item, 0, sizeof(shf_condition_item_t));
    item->dindex1 = mIndex1;
    item->dindex2 = mIndex2;
    item->op = mOperation;
    item->combine = mCombine;	
    switch (mDataType) {
    case DATA_TYPE_UINT32: {
        item->value.duint32 = mIntValue;
    }
        break;
    case DATA_TYPE_UINT64: {
        ALOGV("getStruct: value=%lld", mLongValue);
        timestamp_set(&item->value.dtime, mLongValue);
    }
        break;
    case DATA_TYPE_FLOAT: {
        uint32_t temp = mFloatValue * FLOAT_MULTIPLY_FACTOR;
        ALOGV("getStruct: float(%f) -> int(%u)", mFloatValue, temp);		
        item->value.duint32 = temp;
    }
        break;
    default:
        break;
    }
    if (mIsLast1) {
        item->op |= SHF_OPERATION_MASK_OLD1;
    }
    if (mIsLast2) {
        item->op |= SHF_OPERATION_MASK_OLD2;
    }
    if (mConditionType == CONDITION_TYPE_CMP) {
        item->op |= SHF_OPERATION_MASK_CMP;
    } else if (mConditionType == CONDITION_TYPE_DIF) {
        item->op |= SHF_OPERATION_MASK_DIF;
    }
    if (mBracketLeft) {
        item->combine |= SHF_COMBINE_MASK_BRACKET_LEFT;
    }
}
コード例 #7
0
ファイル: achievements_manager.c プロジェクト: asqz/runner
int am_init(struct achievement_manager_t** pam, const achievement_info_t* const* achievements, uint32_t nachievements, am_achievement_progress progress, am_achievement_unlocked unlocked)
{
   uint32_t i = 0;

   uint32_t size = sizeof(achievement_manager_t) + nachievements * (sizeof(achievement_state_t) + sizeof(achievement_index_t));
   achievement_manager_t* am = malloc(size);
   memset(am, 0, size);

   am->nachievements = nachievements;
   am->achievements = achievements;
   am->progress = progress;
   am->unlocked = unlocked;
   am->states = (achievement_state_t*)((uint8_t*)am + sizeof(achievement_manager_t));
   am->indices = (achievement_index_t*)((uint8_t*)am->states + nachievements * sizeof(achievement_state_t));

   timestamp_t current_time = {0};
   timestamp_set(&current_time);

   achievement_state_t* state = &am->states[0];
   achievement_index_t* index = &am->indices[0];
   for (; i < am->nachievements; ++i, ++state, ++index)
   {
      const achievement_info_t* info = am->achievements[i];

      strcpy(state->achievement_id, info->id);
      state->status.unlocked = 0;
      state->status.last_change = current_time;

      strcpy(index->achievement_id, info->id);
      index->index = i;
   }

   qsort(am->indices, am->nachievements, sizeof(achievement_index_t), cmp_achievement_index);

   (*pam) = am;
   return 0;
}
コード例 #8
0
ファイル: irbis.c プロジェクト: BioinformaticsArchive/irbis
int main(int argc, char** argv) {
    char buff[MAXBUFFLENGTH];
    char aux[MAXBUFFLENGTH];

    dictionary<ATOMIC>* dict_f[MAXSPECIES];
    dictionary<ATOMIC>* dict_r[MAXSPECIES];
    dictionary<PAIR<ATOMIC> >* dict_bp[MAXSPECIES];
    dictionary<ATOMIC>* filter;

    conservation_table* cons_f[MAXSPECIES];
    conservation_table* cons_r[MAXSPECIES];

    char right_file_name[MAXBUFFLENGTH]="";
    char left_file_name[MAXBUFFLENGTH]="";
    char right_sbs_file_name[MAXBUFFLENGTH]="";
    char left_sbs_file_name[MAXBUFFLENGTH]="";

    char rel_binary_file_name[MAXBUFFLENGTH]="";
    char rel_tabdel_file_name[MAXBUFFLENGTH]="";

    relation* rel=NULL;

    FILE *right_file, *left_file, *rel_file, *outfile;
 
    char* specie_name[MAXSPECIES];
    double weight[MAXSPECIES];

    char filename[MAXBUFFLENGTH];
    char outfilename[MAXBUFFLENGTH];

    double threshold, threshold1, threshold2;
    int halfsize,gap,n_species;
    int halfsize1,gap1,n_species1;
    double tot_weight=0;

    int redundant_pairs = 2;
    const char RED_P[3][24]={"strictly not allowed", "not allowed", "allowed"};

    double min_cons = 0;
    int min_length   = 0;
    int joint_fold = 1;
    int number_of_gt_basepairs=0;

    index_t p,q,r,s;
    word_t a,b;
    int i,j;
    int repeat_length=1;
    int min_gc=0;
    char *pc;
    word_t aux_array[GT_ARRAY_CAPACITY];
    int aux_array_length;
    int n,m;

    subset *left_restriction=NULL;
    subset *right_restriction=NULL;

    if(argc==1) {
	fprintf(stderr, "BInary Search for COnserved RNa Structures\n");
	fprintf(stderr, "Usage: %s -l [left_metacalc] -r [right_metacalc] -o [output_tabular file]\n",argv[0]);
	fprintf(stderr, " -v suppress verbose output\n -t threshold for intersection\n -u redundant pairs (0=strict no, 1=no, 2=allowed)\n -L min length\n");
	fprintf(stderr, " -B binary relation file\n -b tab-delimited relation file\n -j suppress joint fold (fold species separately)\n");
	exit(0);
    }

    timestamp_set();
    rel_binary_file_name[0] = rel_tabdel_file_name[0] = 0;
    for(i=1;i<argc;i++) {
        pc = argv[i];
        if(*pc == '-') {
            if(strcmp(pc+1,"v") == 0) verbose=0;
	    if(strcmp(pc+1,"l") == 0)  sscanf(argv[++i], "%s",  &left_file_name[0]);
	    if(strcmp(pc+1,"r") == 0)  sscanf(argv[++i], "%s",  &right_file_name[0]);
            if(strcmp(pc+1,"lr")== 0)  sscanf(argv[++i], "%s",  &left_sbs_file_name[0]);
            if(strcmp(pc+1,"rr")== 0)  sscanf(argv[++i], "%s",  &right_sbs_file_name[0]);
            if(strcmp(pc+1,"B") == 0)  sscanf(argv[++i], "%s",  &rel_binary_file_name[0]);
            if(strcmp(pc+1,"b") == 0)  sscanf(argv[++i], "%s",  &rel_tabdel_file_name[0]);
	    if(strcmp(pc+1,"o") == 0)  sscanf(argv[++i], "%s",  &outfilename[0]);
	    if(strcmp(pc+1,"t") == 0)  sscanf(argv[++i], "%lf", &threshold);
	    if(strcmp(pc+1,"L") == 0)  sscanf(argv[++i], "%i",  &min_length);
	    if(strcmp(pc+1,"C") == 0)  sscanf(argv[++i], "%lf", &min_cons);
	    if(strcmp(pc+1,"u") == 0)  sscanf(argv[++i], "%i",  &redundant_pairs);
	    if(strcmp(pc+1,"g") == 0)  sscanf(argv[++i], "%i",  &number_of_gt_basepairs);
	    if(strcmp(pc+1,"j") == 0)  joint_fold = 0;
        }
    }

    outfile = fopen(outfilename,"w");
    if(outfile==NULL) {
        if(verbose) fprintf(logfile,"Cannot open outfile, exiting\n");
        exit(1);
    }

    if(left_sbs_file_name[0]!=0)  left_restriction  = new subset(left_sbs_file_name);
    if(right_sbs_file_name[0]!=0) right_restriction = new subset(right_sbs_file_name);

    if(redundant_pairs>2) redundant_pairs=2;
    if(verbose) fprintf(logfile,"[Params: max_gt=%i, threshold=%2.1lf%%, min_length=%i, min_cons_score=%2.1lf, redundant_pairs=%s, joint_fold=%s]\n",
            number_of_gt_basepairs, threshold*100, min_length, min_cons, RED_P[redundant_pairs], yesno(joint_fold));

    if(rel_binary_file_name[0]!=0) {
	rel = new relation();
	rel->get_from_bin_file(rel_binary_file_name);
    }

    if(rel_tabdel_file_name[0]!=0) {
        rel = new relation();
        rel->get_from_tab_file(rel_tabdel_file_name);
    }

    if(verbose) fprintf(logfile,"Reading left %s", left_file_name);
    left_file = fopen(left_file_name,"r");
    if(left_file==NULL) {
	fprintf(stderr,"cannot be found, exiting\n");
	exit(1);
    }
    fgets(buff, MAXBUFFLENGTH, left_file);
    sscanf(buff,"%i %i %i %lf",&halfsize, &gap, &n_species, &threshold1);
    if(verbose) fprintf(logfile,"\n");
    for(i=0;i<n_species;i++) {
        dict_f[i] = new dictionary<ATOMIC>(halfsize,gap);
	fgets(buff, MAXBUFFLENGTH, left_file);
	specie_name[i] = (char*)malloc(sizeof(char)*MAXBUFFLENGTH);
	sscanf(buff,"%s %lf",&specie_name[i][0],&weight[i]);
 	tot_weight+=weight[i];
        if(verbose) fprintf(logfile,"[Loading %s ",specie_name[i]);
        dict_f[i]->load(left_file);
        cons_f[i] = new conservation_table();
        cons_f[i]->load(left_file);
        dict_f[i]->info();
	if(left_restriction!=NULL) {
	    dict_f[i]->subset_on(left_restriction);
	}
        dict_f[i]->check();
        if(verbose) fprintf(logfile,"]\n");
    }

    if(verbose) fprintf(logfile,"Reading right %s", right_file_name);
    right_file = fopen(right_file_name,"r");
    if(right_file == NULL) {
	fprintf(stderr, "cannot be found, exiting\n");
	exit(1);
    }
    if(verbose) fprintf(logfile,"\n");
    fgets(buff, MAXBUFFLENGTH, right_file);
    sscanf(buff,"%i %i %i %lf",&halfsize1, &gap1, &n_species1, &threshold2);
    if(halfsize!=halfsize1 || gap!=gap1) {
	fprintf(logfile,"Dictionaries not compartible (%i %i) and (%i %i), exiting\n", halfsize, gap, halfsize1, gap1);
	exit(1);
    }
    if(n_species!=n_species1) {
	fprintf(logfile,"Number of species are different");
	exit(1);
    }
    for(i=0;i<n_species;i++) {
        dict_r[i] = new dictionary<ATOMIC>(halfsize,gap);
        fgets(buff, MAXBUFFLENGTH, right_file);
        sscanf(buff,"%s",&aux[0]);
	if(strcmp(aux,specie_name[i])!=0) {
	    fprintf(logfile,"Species are not the same (%s vs %s), exiting\n", aux, specie_name[i]);
	    exit(1);
	}
        if(verbose) fprintf(logfile,"[Loading %s ",specie_name[i]);
        dict_r[i]->load(right_file);
        cons_r[i] = new conservation_table();
        cons_r[i]->load(right_file);
        dict_r[i]->info();
	if(right_restriction!=NULL) {
	    dict_r[i]->subset_on(right_restriction);
	}
        dict_r[i]->check();
        if(verbose) fprintf(logfile,"]\n");
    }

    if(threshold<threshold1 || threshold<threshold2) {
        threshold=MAX2(threshold1, threshold2);
        if(verbose) fprintf(logfile,"[WARNING: product threshold set to %2.2lf%%]\n",threshold*100);
    }

    if((threshold1<threshold || threshold2<threshold) && verbose) fprintf(logfile,"Threshold rose to %2.2lf%%, need to trim again\n",threshold*100);
    if(threshold1<threshold) dictionary<ATOMIC>::intersect_many(dict_f, n_species, weight, threshold*tot_weight, (char*)"Forward\t");
    if(threshold2<threshold) dictionary<ATOMIC>::intersect_many(dict_r, n_species, weight, threshold*tot_weight, (char*)"Reverse\t");

    for(i=0;i<n_species;i++) {
	if(verbose) fprintf(logfile,"[%s forward ",specie_name[i]);
	dict_f[i]->info();
	if(verbose) fprintf(logfile,", reverse: ");
        dict_r[i]->info();
        if(verbose) fprintf(logfile,", product: ");

	/** times procedure **/
    	dict_bp[i] = new dictionary<PAIR<ATOMIC> >(dict_f[i]->half_size,dict_f[i]->gap_size);
    	for(s=0,a=0;a<=dict_f[i]->last_word;a++) {
	    dict_bp[i]->revcomp_gt(a, number_of_gt_basepairs, aux_array, &aux_array_length);
	    for(;aux_array_length>0;aux_array_length--) { 
	    	b = aux_array[aux_array_length-1];
	    	if(rel) {
	    	    for(p=dict_f[i]->index[a];p<dict_f[i]->index[a+1];p++) {
		    	for(q=dict_r[i]->index[b];q<dict_r[i]->index[b+1];q++) {
		    	    if(rel->check(dict_f[i]->table[p].getid(), dict_r[i]->table[q].getid())) s++;
		    	}
		    }
	    	}
	    	else {
	    	    s+=(dict_f[i]->index[a+1]-dict_f[i]->index[a])*(dict_r[i]->index[b+1]-dict_r[i]->index[b]);
	    	}
	    }
	}

    	dict_bp[i]->table = (PAIR<ATOMIC>*)malloc((size_t)sizeof(PAIR<ATOMIC>)*(s + ARRAY_MARGIN));
    	r=0;
    	for(a=0;a<=dict_f[i]->last_word;a++) {
	    dict_bp[i]->index[a]=r;
	    dict_bp[i]->revcomp_gt(a, number_of_gt_basepairs, aux_array, &aux_array_length);
            for(;aux_array_length>0;aux_array_length--) {
	    	b = aux_array[aux_array_length-1];
            	for(p=dict_f[i]->index[a];p<dict_f[i]->index[a+1];p++) {
            	    for(q=dict_r[i]->index[b];q<dict_r[i]->index[b+1];q++) {
		    	if(rel) if(!rel->check(dict_f[i]->table[p].getid(), dict_r[i]->table[q].getid())) continue;
                    	if(redundant_pairs==2 || redundant_pairs==1 && (dict_f[i]->table[p].getid()<dict_r[i]->table[q].getid() || dict_f[i]->table[p].getid()==dict_r[i]->table[q].getid() && dict_f[i]->table[p].getpos() + dict_f[i]->full_size<dict_r[i]->table[q].getpos()) || redundant_pairs==0 && dict_f[i]->table[p].getid()<dict_r[i]->table[q].getid()) 
			    dict_bp[i]->table[r++].set(dict_f[i]->table[p], dict_r[i]->table[q]);
            	    }
                }
	    }
	    PAIR<ATOMIC>::quicksort_less(dict_bp[i]->table, dict_bp[i]->index[a], r-1); 
    	}
    	dict_bp[i]->index[a]=r;

    	if(verbose) fprintf(logfile,"%li/%li/%li ",(long)dict_bp[i]->last_word,(long)r,(long)s);
        free(dict_bp[i]->count);
        dict_bp[i]->phase = PHASE_COMPLETED;
	/** end of times procedure **/

	dict_bp[i]->info();
	dict_bp[i]->check();
	dict_f[i]->drop();
        dict_r[i]->drop();
	if(verbose) fprintf(logfile,"]\n");
    }

    dictionary<PAIR<ATOMIC> >::intersect_many(dict_bp, n_species, weight, threshold*tot_weight, (char*)"Intersection of products \t");

    if(joint_fold) {
    	dictionary<PAIR<ATOMIC> >::foldall(outfile, dict_bp, specie_name, n_species, weight, threshold*tot_weight, cons_f, cons_r, min_cons, min_length);
    }
    else {
    	if(verbose) fprintf(logfile,"[Folding and saving to %s...]\n",outfilename);
    	for(i=0;i<n_species;i++) {
	    if(verbose) fprintf(logfile,"[%s ",specie_name[i]);
	    dict_bp[i]->info();
	    n = dict_bp[i]->fold_and_save_standalone(outfile, i, cons_f[i], cons_r[i], min_length);
            if(verbose) fprintf(logfile,", %i structures]\n",n);
    	}
    }
    fclose(outfile);
    timestamp_report();
    return(0);
}
コード例 #9
0
ファイル: task_dispatcher.c プロジェクト: asqz/runner
static void* working_thread(void* ctx)
{
   struct task_dispatcher_t* td = (struct task_dispatcher_t*)ctx;
   LOGI("Task dispatcher working thread started");

   pthread_mutex_lock(&td->event_lock);
   while (1)
   {
      if (pool_is_empty(td->tasks))
      {
         LOGD("Waiting for event");
         pthread_cond_wait(&td->event, &td->event_lock);
      }
      else
      {
         struct task_t* task = pool_get_next(td->tasks, NULL);

         struct timespec activate_time = {0};
         timestamp_to_timespec(&task->activate_time, &activate_time);

         timestamp_t current = {0};
         timestamp_set(&current);

         LOGD("Waiting for task [%ld:%d -> %ld:%d]", current.value.tv_sec, current.value.tv_usec, task->activate_time.value.tv_sec, task->activate_time.value.tv_usec);
         pthread_cond_timedwait(&td->event, &td->event_lock, &activate_time);
      }

      if (!td->running)
      {
         LOGI("Stopping working thread");
         break;
      }

      if (!pool_is_empty(td->tasks))
      {
         struct task_t* task = pool_get_next(td->tasks, NULL);

         timestamp_t current = {0};
         timestamp_set(&current);

         if (timestamp_diff(&current, &task->activate_time) >= 0)
         {
            pool_remove(td->tasks, task);
            LOGD("Removed task %p [queue empty %d]", task, pool_is_empty(td->tasks));

            if (task->interval > 0)
            {
               task_dispatcher_enqueue_task(td, task->callback, task->ctx, task->interval, task->interval);
            }

            pthread_mutex_unlock(&td->event_lock);

            LOGD("Running task");
            task->callback(td, task, &task->enqueue_time, &current, task->ctx);

            pthread_mutex_lock(&td->event_lock);
         }
      }
   }
   pthread_mutex_unlock(&td->event_lock);

   LOGI("Task dispatcher working thread stopped");
   return NULL;
}
コード例 #10
0
int main(int argc, char* argv[]) {
    char aln_file_name[MAXBUFFLENGTH];
    char out_file_name[MAXBUFFLENGTH]="";
 
    char buff[MAXBUFFLENGTH];
    char chr1[MAXBUFFLENGTH];
    char chr2[MAXBUFFLENGTH];

    double dthreshold = 1.50;
    int dlimit = 100000;
    int max_depth = 4;

    int** chr_t;
    int** str_t;
    int** pos_t;

    int* chr_q;
    int* str_q;
    int* pos_q;

    int **score;
    int **jbest;
    int **lbest;

    int a,b,d,dmin,lmin,s;
    char c,c1,c2;

    int *count;
    int *ptr;

    int max_rec=0;

    int pos1, pos2, str1, str2;
    int i, j, k, l, n;

    int s_max, k_max;

    if(argc==1) {
	fprintf(stderr,"This utility takes a non-unique mapping in cps3+cps3 format and does ad-hoc filtering of the projected coordinates by maximum synteny\n");
        fprintf(stderr,"Last update by Dmitri Pervouchine ([email protected]) on Mar 26, 2013\n");
        fprintf(stderr,"Usage: %s -in <aln_file> -out <output_file> [-maxdepth <int>] [-threshold <double>] [-lendiff <diff>] [-quiet]\n",argv[0]);
	fprintf(stderr," -in cps3+cps3 file, remember to sort by position in ascending order\n");
	fprintf(stderr," -out <output_file> [default=stdout]\n");
	fprintf(stderr," -maxdepth <integer> how many preceding positions can be skipped [default=%i]\n", max_depth);
	fprintf(stderr," -threshold <double> max change of segment length, in percent [default=%2.2lf]\n", dthreshold);
	fprintf(stderr," -lendiff <integer>, [default=%i]\n",dlimit);
	fprintf(stderr," -quiet suppress verbose output [default=NO]\n");
	fprintf(stderr,"Note: the mapping [x,x+dx] -> [y,y+dy] is OK if |dy-dx|/dx<threshold OR |dy-dx|<dlimit\n");
	exit(1);
    }

    timestamp_set();
    for(i=1;i<argc;i++) {
        if(strcmp(argv[i],"-in")==0) {
            sscanf(argv[++i], "%s", &aln_file_name[0]);
        }
        if(strcmp(argv[i],"-out")==0) {
            sscanf(argv[++i], "%s", &out_file_name[0]);
        }
        if(strcmp(argv[i],"-lendiff")==0) {
            sscanf(argv[++i], "%i", &dlimit);
        }
        if(strcmp(argv[i],"-threshold")==0) {
            sscanf(argv[++i], "%lf", &dthreshold);
        }
        if(strcmp(argv[i],"-maxdepth")==0) {
            sscanf(argv[++i], "%i", &max_depth);
        }
        if(strcmp(argv[i],"-quiet")==0) {
            verbose=0;
        }
    }

    if(out_file_name[0]==0) {
        fprintf(stderr,"[WARNING: output file not specified, redirect to stdout]\n");
        out_file = stdout;
    }
    else {
        out_file = fopen(out_file_name,"w");
        if(out_file == NULL) {
            fprintf(stderr,"[ERROR: output file (%s) cannot be opened, exiting]\n", out_file_name);
            exit(1);
        }
	if(verbose) fprintf(stderr,"[>%s]\n",out_file_name);
    }

/*******************************************************************************************************/
    aln_file= fopen(aln_file_name,"r");
    if(aln_file==NULL) {
        fprintf(stderr,"[ERROR: cannot access %s, exiting]\n", aln_file_name);
	exit(1);
    }

    if(verbose) fprintf(stderr,"[<%s, pass 1", aln_file_name);
    while(fgets(buff, MAXBUFFLENGTH, aln_file)) {
	if(strlen(buff)<2) break;
	max_rec++;
    }
    if(verbose) fprintf(stderr,"]\n");

    chr_q = (int*)malloc(sizeof(int)*(max_rec + ARRAY_MARGIN));
    str_q = (int*)malloc(sizeof(int)*(max_rec + ARRAY_MARGIN));
    pos_q = (int*)malloc(sizeof(int)*(max_rec + ARRAY_MARGIN));

    chr_t = (int**)malloc(sizeof(int*)*(max_rec + ARRAY_MARGIN));
    str_t = (int**)malloc(sizeof(int*)*(max_rec + ARRAY_MARGIN));
    pos_t = (int**)malloc(sizeof(int*)*(max_rec + ARRAY_MARGIN));

    score = (int**)malloc(sizeof(int*)*(max_rec + ARRAY_MARGIN));
    lbest = (int**)malloc(sizeof(int*)*(max_rec + ARRAY_MARGIN));
    jbest = (int**)malloc(sizeof(int*)*(max_rec + ARRAY_MARGIN));

    count = (int*)malloc(sizeof(int)*(max_rec + ARRAY_MARGIN));
    ptr   = (int*)malloc(sizeof(int)*(max_rec + ARRAY_MARGIN));

    if(chr_q == NULL || str_q == NULL || pos_q == NULL || count == NULL || ptr == NULL || chr_t == NULL || str_t == NULL || pos_t == NULL) {
	fprintf(stderr,"[ERROR: not enough memory, exiting]\n");
	exit(1);
    }

    for(i=0;i<max_rec;i++) count[i] = ptr[i] = 0;

    if(verbose) fprintf(stderr,"[<%s, pass 2", aln_file_name);
    fseek (aln_file, 0, SEEK_SET);
    n=0;
    while(fgets(buff, MAXBUFFLENGTH, aln_file)) {
        if(strlen(buff)<2) break;
        sscanf(buff,"%s %i %c" , &chr1[0], &pos1, &c);
	str1 = strand_c2i(c);
	if(assign_code(chr1) != chr_q[n] || str1 != str_q[n] || pos1 != pos_q[n]) {
	    n++;
	    chr_q[n] = assign_code(chr1);
            str_q[n] = str1;
            pos_q[n] = pos1;
	}
	count[n]++;
    }
    if(verbose) fprintf(stderr,"]\n");

    for(i=1; i<=n; i++) {
        chr_t[i] = (int*)malloc(sizeof(int)*(count[i] + ARRAY_MARGIN));
	pos_t[i] = (int*)malloc(sizeof(int)*(count[i] + ARRAY_MARGIN));
        str_t[i] = (int*)malloc(sizeof(int)*(count[i] + ARRAY_MARGIN));

	score[i] = (int*)malloc(sizeof(int)*(count[i] + ARRAY_MARGIN));
	lbest[i] = (int*)malloc(sizeof(int)*(count[i] + ARRAY_MARGIN));
        jbest[i] = (int*)malloc(sizeof(int)*(count[i] + ARRAY_MARGIN));

	if(chr_t[i] == NULL || str_t[i] == NULL || pos_t[i] == NULL) {
	    fprintf(stderr,"[ERROR: not enough memory, exiting]\n");
	    exit(1);
	}
    }

    if(verbose) fprintf(stderr,"[<%s, pass 3", aln_file_name);
    fseek (aln_file, 0, SEEK_SET);
    n=0;
    while(fgets(buff, MAXBUFFLENGTH, aln_file)) {
        if(strlen(buff)<2) break;
        sscanf(buff,"%s %i %c %s %i %c" , &chr1[0], &pos1, &c1, &chr2[0], &pos2, &c2);
	str1 = strand_c2i(c1);
	str2 = strand_c2i(c2);
	if(assign_code(chr1) != chr_q[n] || str1 != str_q[n] || pos1 != pos_q[n]) n++;
	chr_t[n][ptr[n]] = assign_code(chr2);
	pos_t[n][ptr[n]] = pos2;
	str_t[n][ptr[n]] = str2;
	ptr[n]++;
    }
    if(verbose) fprintf(stderr,"]\n");

    for(i=1; i<=n; i++) {
	progressbar(i, n, (char*)"Filtering ", verbose);
	for(k=0; k<count[i]; k++) {
	    score[i][k] = 0;
	    lbest[i][k] = -1;
	    jbest[i][k] = -1;
	    for(j=i-1; j>0 && i-j<=max_depth; j--) {
		a = abs(pos_q[i] - pos_q[j]);
                dmin = INFTY;
                lmin = -1;
		for(l=0; l<count[j]; l++) {
		    if(chr_t[i][k] == chr_t[j][l] && str_t[i][k]*str_t[j][l] == str_q[i]*str_q[j]) {
			b = abs(pos_t[i][k] - pos_t[j][l]);
                        d = abs(b-a);
                        if(d<dmin) {
                            dmin = d;
                            lmin = l;
                        }
                    }
                }
		s = (lmin>=0 && (((double)dmin/a) < dthreshold || dmin < dlimit)) ? score[j][lmin] + a : 0;
		if(s > score[i][k]) {
		    score[i][k] = s;
		    jbest[i][k] = j;
		    lbest[i][k] = lmin;
		} 
	    }
	}
    }
    
    for(i=n;i>0;i--) {
	s_max = 0;
	k_max = -1;
	for(k=0; k<count[i]; k++) {
	    if(score[i][k]>s_max) {
		s_max = score[i][k];
		k_max = k;
	    }
	}
	if(k_max>=0) {
	    k = k_max; 
	    while(jbest[i][k]>=0 && lbest[i][k]>=0) {
		fprintf(out_file,"%s\t%i\t%c\t", get_chr_name(chr_q[i]), pos_q[i], strand_i2c(str_q[i]));
		fprintf(out_file,"%s\t%i\t%c\n", get_chr_name(chr_t[i][k]), pos_t[i][k], strand_i2c(str_t[i][k]));
		j = jbest[i][k];
		l = lbest[i][k];
		i = j;
		k = l;
	    }
	}

    }
    timestamp_report();
    exit(0);
}
コード例 #11
0
ファイル: timestamp.c プロジェクト: asqz/runner
long timestamp_update(timestamp_t* timestamp)
{
   timestamp_t prev = *timestamp;
   timestamp_set(timestamp);
   return timestamp_diff(timestamp, &prev);
}
コード例 #12
0
ファイル: timestamp.c プロジェクト: asqz/runner
long timestamp_elapsed(const timestamp_t* timestamp)
{
   timestamp_t current;
   timestamp_set(&current);
   return timestamp_diff(&current, timestamp);
}
コード例 #13
0
ファイル: shadow.c プロジェクト: Duncaen/OpenDoas
void
shadowauth(const char *myname, int persist)
{
	const char *hash;
	char *encrypted;
	struct passwd *pw;
	char *challenge, *response, rbuf[1024], cbuf[128];

#ifdef USE_TIMESTAMP
	int fd = -1;
	int valid = 0;

	if (persist)
		fd = timestamp_open(&valid, 5 * 60);
	if (fd != -1 && valid == 1)
		goto good;
#else
	(void) persist;
#endif

	if ((pw = getpwnam(myname)) == NULL)
		err(1, "getpwnam");

	hash = pw->pw_passwd;
	if (hash[0] == 'x' && hash[1] == '\0') {
		struct spwd *sp;
		if ((sp = getspnam(myname)) == NULL)
			errx(1, "Authorization failed");
		hash = sp->sp_pwdp;
	} else if (hash[0] != '*') {
		errx(1, "Authorization failed");
	}

	char host[HOST_NAME_MAX + 1];
	if (gethostname(host, sizeof(host)))
		snprintf(host, sizeof(host), "?");
	snprintf(cbuf, sizeof(cbuf),
			"\rdoas (%.32s@%.32s) password: "******"tty required for %s", myname);
		errx(1, "a tty is required");
	}
	if (response == NULL)
		err(1, "readpassphrase");
	if ((encrypted = crypt(response, hash)) == NULL) {
		explicit_bzero(rbuf, sizeof(rbuf));
		errx(1, "Authorization failed");
	}
	explicit_bzero(rbuf, sizeof(rbuf));
	if (strcmp(encrypted, hash) != 0) {
		syslog(LOG_AUTHPRIV | LOG_NOTICE, "failed auth for %s", myname);
		errx(1, "Authorization failed");
	}

#ifdef USE_TIMESTAMP
good:
	if (fd != -1) {
		timestamp_set(fd, 5 * 60);
		close(fd);
	}
#endif
}
コード例 #14
0
ファイル: cardgame.c プロジェクト: asqz/runner
int init(const platform_env_t* env)
{
    paused = 0;

    LOGI("Environment:\n  Platform: %d\n  Assets: %s\n  Shared: %s\n  Config: %s\n  Tmp: %s\n",
         env->platform,
         env->assets_dir,
         env->shared_dir,
         env->config_dir,
         env->tmp_dir);

    io_driver_t* assets = NULL;
    io_driver_t* config = NULL;
    io_driver_t* tmp = NULL;
    io_driver_t* shared = NULL;
    if (io_init(&io) != 0 ||
#ifdef ANDROID
            io_driver_apk_init(&assets, env->platform_specific) != 0 ||
#else
            io_driver_fs_init(&assets, env->assets_dir) != 0 ||
#endif
            io_driver_fs_init(&config, env->config_dir) != 0 ||
            io_driver_fs_init(&shared, env->shared_dir) != 0 ||
            io_driver_fs_init(&tmp, env->tmp_dir) != 0 ||
            io_bind(io, "/config", config) ||
            io_bind(io, "/tmp", tmp) ||
            io_bind(io, "/shared", shared) ||
            io_bind(io, "/assets", assets)
       )
    {
        LOGE("Error initializing I/O system");
        return -1;
    }
    io_set_working_dir(io, "/assets");
    io_set_default(io);

    if (gfx_init(&gfx) != 0)
    {
        LOGE("Error initializing GFX system");
        return -1;
    }

    font_info_t info =
    {
        .name = "fonts/default.ttf",
        .face_index = 0,
        .width = 0,
        .height = 14 * 64,
        .dpi_x = 0,
        .dpi_y = 72,
    };
    if (font_init(&font, &info, NULL) != 0)
    {
        LOGE("Error loading font");
        return -1;
    }

    info.height = 22 * 64;
    if (font_init(&big_font, &info, NULL) != 0)
    {
        LOGE("Error loading font");
        return -1;
    }

    if (atlases_load(&atlases, "atlases.dat") != 0)
    {
        LOGE("Error loading atlases metadata");
        return -1;
    }

    if (sprites_load(&sprites, "sprites.dat") != 0)
    {
        LOGE("Error loading sprites metadata");
        return -1;
    }

    stats_load(&global_stats, "/config/player.dat");

    if (am_init(&am, achievements_get_all(), achievements_get_count(), achievement_progress, achievement_unlocked))
    {
        LOGE("Unable to initialize achievements manager");
        return -1;
    }
    achievements_context.am = am;
    am_load(am, "/config/achievements.dat");

    timestamp_set(&timer);
    timestamp_set(&fps_timer);

    push_screen(SCREEN_MAIN_MENU);

    return 0;
}

void shutdown()
{
    LOGI("shutdown");
    atlases_free(atlases);
    sprites_free(sprites);
    font_free(font);
    font_free(big_font);
    gfx_free(gfx);

    stats_dump(&global_stats);
    stats_save(&global_stats, "/config/player.dat");
    stats_free(&global_stats);

    if (am != NULL)
    {
        am_save(am, "/config/achievements.dat");
        am_dump(am);
        am_free(am);
        am = NULL;
    }

    io_free(io);
    io = NULL;

    atlases = NULL;
    sprites = NULL;
    font = NULL;
    big_font = NULL;
    gfx = NULL;
}
コード例 #15
0
ファイル: cardgame.c プロジェクト: asqz/runner
int update()
{
    if (get_active_screen() == NULL)
    {
        return 1;
    }

    timestamp_t current = {0};
    timestamp_set(&current);
    long dt = timestamp_diff(&current, &timer);
    if (dt > 0)
    {
        timer = current;
        screen_update(dt);
    }

    long fps_dt = timestamp_diff(&current, &fps_timer);
    LOGD("DT: %ld", fps_dt);
    if (fps_dt > 500)
    {
        fps = frames * 1000.0f / (float)fps_dt;
        fps_timer = current;
        frames = 0;
        LOGI("FPS: %.2f", fps);
    }
    else
    {
        ++frames;
    }

    char fps_str[32] = {0};
    sprintf(fps_str, "FPS: %.2f", fps);

    const rect_t fps_rect = { 8.0f, 8.0f, 256.0f, 32.0f };
    const rgba_t fps_color = { 1.0f, 0.0f, 0.0f, 0.8f };

    mat4f_t transform = {0};
    mat4_mult(&transform, &camera.proj, &camera.view);

    rect_t screen = { 0, 0, screen_size.x, screen_size.y };

    rgba_t color = {0.7f, 0.7f, 0.0f, 1.0f };

    gfx_set_target(gfx, "test_target", &screen);
    gfx_enable_depth_buffer(gfx, 1);

    gfx_clear(gfx);
    screen_render(gfx, &camera);
    gfx_set_shader(gfx, "text");
    gfx_set_uniform_mat4f(gfx, "uMVP", 1, &transform);
    draw_text(fps_str, &fps_rect, 0.0f, 4.9f, &fps_color);
    gfx_flush(gfx);

    static int take_screenshot = 0;
    if (take_screenshot && frames == 0)
    {
        take_screenshot = 0;

        image_t* img = NULL;
        if (gfx_take_screenshot(gfx, &img) == 0)
        {
            image_save_to_png(img, "screenshot.png");
            image_free(img);
        }
    }

    gfx_set_target(gfx, NULL, &screen);
    gfx_enable_depth_buffer(gfx, 0);
    gfx_clear(gfx);

    int32_t sampler = 0;
    rect_t uv = { 0, screen.height/buffer_size.y, screen.width/buffer_size.x, -screen.height/buffer_size.y };

    gfx_set_shader(gfx, "postprocess");
    gfx_set_uniform_mat4f(gfx, "uMVP", 1, &transform);
    gfx_set_uniform_1i(gfx, "uTex", 1, &sampler);
    gfx_set_texture(gfx, "test_texture", sampler);
    gfx_render_textured_rect(gfx, &screen, 1.0f, &uv);
    gfx_set_texture(gfx, NULL, sampler);

    gfx_flush(gfx);

    return 0;
}
コード例 #16
0
int main(int argc, char* argv[]) {
    char cpsfilename[MAXBUFFLENGTH];
    char chainfilename[MAXBUFFLENGTH];
    char outfilename[MAXBUFFLENGTH]="";
 
    int marginlength = 0;

    int MAXREC; 

    char c;
    char *pc;
    int x;

    char buff[MAXBUFFLENGTH+1];
    char aux[MAXBUFFLENGTH+1];

    long score;
    int start1,end1,len1,start2,end2,len2;
    char strand1, strand2, chr1[MAXBUFFLENGTH], chr2[MAXBUFFLENGTH];

    int *size, *dq, *dt;
    int a,b,k,i,j,s,m;

    int *position;
    char *strand;
    int *ids;
    int *idg;
    char *type;

    int chridx[MAXCHR+1];
    int chroff[MAXCHR+1];

    char resstr;
    int  rescrd;


    if(argc==1) {
	fprintf(stderr,"Finds matches of the given set of sites (CPS file) in the BLASTZ chain alignment (CHAIN file)\n");
        fprintf(stderr,"Last update by (dp) on Sep 21, 2011\n");
	fprintf(stderr,"Keys:\n -i CPS file (remember to sort by position in ascending order)\n -d CHAIN alignment file\n -o output file\n");
 	fprintf(stderr," -m margin length [0]\n -v suppress verbose output [NO]\n");
	exit(1);
    }

    timestamp_set();
    for(i=1;i<argc;i++) {
	pc = argv[i];
	if(*pc != '-') continue;
        if(*(pc+1) == 'i') {
	   sscanf(argv[++i], "%s", &cpsfilename[0]);
	}
	if(*(pc+1) == 'd') {
	   sscanf(argv[++i], "%s", &chainfilename[0]);
	}
        if(*(pc+1) == 'o') {
           sscanf(argv[++i], "%s", &outfilename[0]);
        }
        if(*(pc+1) == 'm') {
           sscanf(argv[++i], "%i", &marginlength);
        }
        if(*(pc+1) == 'v') {
	   verbose=0;
	} 
    }

    if(outfilename[0]==0) {
	fprintf(stderr,"No output file privided, exiting\n");
	exit(1);
    }
    outfile = fopen(outfilename,"w");
    if(outfile == NULL) {
	fprintf(stderr,"Can't open output file, exiting\n");
	exit(1);
    }

    for(i=0;i<MAXCHR;i++) {
      	chridx[i]=chroff[i]=0;
    }

    MAXREC = 0;
    cpsfile= fopen(cpsfilename,"r");
    if(cpsfile==NULL) {
	fprintf(stderr,"Can't access CPS file. Exiting\n");
	exit(1);
    }

    if(verbose) fprintf(stderr,"Reading CPS input pass 1");

    while(!feof(cpsfile)) {
      	buff[0]=0;
      	fgets(buff,MAXBUFFLENGTH,cpsfile);
      	if(strlen(buff)<2) break;
      	sscanf(buff,"%s" , aux);
      	chridx[assign_code(aux)]++;
	MAXREC++;
    }
    fclose(cpsfile);

    for(s=i=0;i<MAXCHR;i++) {
        x = chridx[i];
	chridx[i] =s;
	s+=x;
    }
    chridx[i] = s;

    position   = (int*)  malloc(sizeof(int)*(s+4));
    strand     = (char*) malloc(sizeof(char)*(s+4));
    type       = (char*) malloc(sizeof(char)*(s+4));
    ids	       = (int*)  malloc(sizeof(int)*(s+4));
    idg        = (int*)  malloc(sizeof(int)*(s+4));

    if(position==NULL || strand==NULL || type==NULL || ids==NULL || idg==NULL) {
        fprintf(stderr,"Not enough memory. Terminated\n");
        exit(1);
    }

    cpsfile= fopen(cpsfilename,"r");
    if(verbose) fprintf(stderr,", records = %i\nReading CPS input pass 2",MAXREC);
    while(!feof(cpsfile)) {
      	buff[0]=0;
      	fgets(buff,MAXBUFFLENGTH,cpsfile);
        if(strlen(buff)<2) break;
        sscanf(buff,"%s" , aux);
        i = assign_code(aux);
        m = chridx[i]+chroff[i];
        sscanf(buff,"%*s %i %c %i %i %c" , position+m, strand+m, idg+m, ids+m, type+m);
        chroff[i]++;
    }
    fclose(cpsfile);

    if(verbose) fprintf(stderr,"\nSorting segments");

/*
    for(i=0;i<MAXCHR;i++) {
	quickSort_ic(position,strand,chridx[i],chridx[i+1]-1);
    }
*/
	

    for(i=0;i<MAXCHR;i++) {
        k=1;
        while(k) {
            k=0;
            for(j=chridx[i];j<chridx[i+1]-1;j++) {
                if(position[j]>position[j+1]) {
                    k=1;
                    swapi(position+j,position+j+1);
                    swapc(strand+j,strand+j+1);
                    swapc(type+j,type+j+1);
		    swapi(ids+j,ids+j+1);
                    swapi(idg+j,idg+j+1);
                }
            }
        }
    }

    if(verbose) fprintf(stderr," done\nProcessing chains");

/**********************************************************************************************/
    size = (int*) malloc(sizeof(int)*MAXALN);
    dq   = (int*) malloc(sizeof(int)*MAXALN);
    dt   = (int*) malloc(sizeof(int)*MAXALN);

    if(size ==0 || dq ==0 || dt==0) {
        fprintf(stderr,"Not enough memory for such long chains. Terminated\n");
        exit(1);
    }


/**********************************************************************************************/

    chainfile = fopen(chainfilename,"r");
    while(!feof(chainfile)) {
     	buff[0]=0;
     	fgets(buff,MAXBUFFLENGTH,chainfile);
     	if(strlen(buff)<2) break;
     	buff[5]=0;
     	if(strcmp(buff,"chain")==0) {
       	    sscanf(buff+6,"%li %s %i %c %i %i %s %i %c %i %i",&score, &chr1[0], &len1, &strand1, &start1, &end1, &chr2[0], &len2, &strand2, &start2, &end2);
	    k=0;
	    while(!feof(chainfile)) {
	    	buff[0]=0;
	    	fgets(buff,MAXBUFFLENGTH,chainfile);
            	if(strlen(buff)<2) break;
	    	sscanf(buff,"%i %i %i",&size[k],&dt[k],&dq[k]);
	    	k++;
	    	if(k>MAXALN) {
		    fprintf(stderr,"Chain length exceeded. Terminating");
		    exit(1);
	    	}
	    }

	    x = get_chr_code(chr1);
	    if(x<0) continue;

            a=start1;b=start2;
            j=0;

	    for(i=chridx[x];i<chridx[x+1] && position[i]<start1;i++);
	    for(;i<chridx[x+1]&& position[i]<end1;i++) {
	    	while(position[i]>a+size[j]+dt[j] && j<k){
		    a+=size[j]+dt[j];
		    b+=size[j]+dq[j];
		    j++;
	    	}
	        if(j>=k) break;
	        if(position[i]-a > marginlength && a+size[j]-position[i] >= marginlength) {
                    if(strand1==strand2) {
                    	resstr = strand[i];
                    	rescrd = position[i] - a + b;
                    }
                    else {
                    	resstr = (strand[i]=='+') ? '-' : '+';
                    	rescrd = len2 - (position[i] - a + b - 1) ;
                    }
		    fprintf(outfile,"%s\t%i\t%c\t%s\t%i\t%c\t%i\t%i\t%c\t%li\n",chr1, position[i], strand[i],chr2,rescrd, resstr, idg[i], ids[i],type[i],score);
	    	}
	    }
     	}
    }
    if(verbose) fprintf(stderr," done\n");
    fclose(chainfile);
    fclose(outfile);
    timestamp_report();
    exit(0);
}
コード例 #17
0
ファイル: map_single.c プロジェクト: pervouchine/maptools
int main(int argc, char* argv[]) {
    char cps_file_name[MAXBUFFLENGTH];
    char chain_file_name[MAXBUFFLENGTH];
    char out_file_name[MAXBUFFLENGTH]="";
 
    int marginlength = 0;

    char buff[MAXBUFFLENGTH+1];
    char aux[MAXBUFFLENGTH+1];

    long score;
    int start1,end1,len1,start2,end2,len2;
    char strand1, strand2, chr1[MAXBUFFLENGTH], chr2[MAXBUFFLENGTH];

    int *size, *dq, *dt;
    int a,b,k,i,j,s,m,x;

    int *position;
    int *strand;
    int *idg;
    int *ids;
    char *type;
    char c;

    int chridx[MAXCHR+1];
    int chroff[MAXCHR+1];

    char resstr;
    int  rescrd;
    long chain_id;


    if(argc==1) {
        fprintf(stderr,"This utility does liftOver of coordinates (cps) by  using chain alignment\n");
        fprintf(stderr,"Gene information is included in the output\n");
        fprintf(stderr,"Last update by Dmitri Pervouchine ([email protected]) on Mar 22, 2013\n");
        fprintf(stderr,"Usage: %s -in <cps_file> -chain <chain_alignment_file> [-margin <length>] [-quiet]\n", argv[0]);
        fprintf(stderr," -in cps6, i.e. chr1/position1/strand1/gene/site/type tab-delimited file, strand is +/-\n");
        fprintf(stderr," -chain UCSC chain alignment file, species1=>2\n");
        fprintf(stderr," -out <output_file> [default=stdout]\n");
        fprintf(stderr," -margin margin length [default=0]\n -quiet suppress verbose output [default=NO]\n");
	fprintf(stderr,"NOTE: Input has to be sorted by position!\n");
        fprintf(stderr,"Output format cps3+cps6: chr1/position1/strand1/chr2/position2/strand2/gene/site/type/score\n");
        exit(1);
    }

    timestamp_set();
    for(i=1;i<argc;i++) {
	if(strcmp(argv[i],"-in")==0) {
	   sscanf(argv[++i], "%s", &cps_file_name[0]);
	}
	if(strcmp(argv[i],"-chain")==0) {
	   sscanf(argv[++i], "%s", &chain_file_name[0]);
	}
	if(strcmp(argv[i],"-out")==0) {
           sscanf(argv[++i], "%s", &out_file_name[0]);
        }
	if(strcmp(argv[i],"-margin")==0) {
           sscanf(argv[++i], "%i", &marginlength);
        }
	if(strcmp(argv[i],"-quiet")==0) {
	   verbose=0;
	} 
    }

    if(out_file_name[0]==0) {
	fprintf(stderr,"[WARNING: output file not specified, redirect to stdout]\n");
	out_file = stdout;
    }
    else {
    	out_file = fopen(out_file_name,"w");
    	if(out_file == NULL) {
	    fprintf(stderr,"[ERROR: output file %s cannot be opened for writing, exiting]\n", out_file_name);
	    exit(1);
	}
	if(verbose) fprintf(stderr,"[>%s]\n",out_file_name);
    }

    cps_file= fopen(cps_file_name,"r");
    if(cps_file==NULL) {
	fprintf(stderr,"[ERROR: cannot access %s, exiting]\n", cps_file_name);
	exit(1);
    }

    for(i=0;i<MAXCHR;i++) chridx[i] = chroff[i] = 0;

    if(verbose) fprintf(stderr,"[<%s, pass 1",cps_file_name);
    while(fgets(buff,MAXBUFFLENGTH,cps_file)) {
        if(strlen(buff)<2) break;
      	sscanf(buff,"%s" , aux);
      	chridx[assign_code(aux)]++;
    }
    if(verbose) fprintf(stderr,"]\n");

    for(s=i=0;i<MAXCHR;i++) {
        x = chridx[i];
	chridx[i] =s;
	s+=x;
    }
    chridx[i] = s;

    position   = (int*) malloc(sizeof(int)*(s + ARRAY_MARGIN));
    strand     = (int*) malloc(sizeof(int)*(s + ARRAY_MARGIN));
    ids        = (int*) malloc(sizeof(int)*(s + ARRAY_MARGIN));
    idg        = (int*) malloc(sizeof(int)*(s + ARRAY_MARGIN));
    type       = (char*) malloc(sizeof(char)*(s + ARRAY_MARGIN));

    if(position==NULL || strand==NULL || type==NULL || ids==NULL || idg==NULL) {
        fprintf(stderr,"[ERROR: failed to create index tables, exiting]\n");
        exit(1);
    }

    fseek (cps_file, 0, SEEK_SET);
    if(verbose) fprintf(stderr,"[<%s, pass 2", cps_file_name);
    while(fgets(buff,MAXBUFFLENGTH,cps_file)) {
        if(strlen(buff)<2) break;
        sscanf(buff,"%s" , aux);
        i = assign_code(aux);
        m = chridx[i]+chroff[i];
        sscanf(buff,"%*s %i %c %i %i %c" , &position[m], &c,&idg[m],&ids[m],&type[m]);
	strand[m] = strand_c2i(c);
        chroff[i]++;
    }
    fclose(cps_file);
    if(verbose) fprintf(stderr,"]\n");


    if(verbose) fprintf(stderr,"[Sort by position (if not done before)");
    for(i=0;i<MAXCHR;i++) {
        k=1;
        while(k) {
            k=0;
            for(j=chridx[i];j<chridx[i+1]-1;j++) {
                if(position[j]>position[j+1]) {
                    k=1;
                    swapi(position+j,position+j+1);
                    swapi(strand+j,strand+j+1);
		    swapi(idg+j,idg+j+1);
		    swapi(ids+j,ids+j+1);
		    swapc(type+j,type+j+1);
                }
            }
        }
    }
    if(verbose) fprintf(stderr,"]\n");


/**********************************************************************************************/
    size = (int*) malloc(sizeof(int)*(MAXALN + ARRAY_MARGIN));
    dq   = (int*) malloc(sizeof(int)*(MAXALN + ARRAY_MARGIN));
    dt   = (int*) malloc(sizeof(int)*(MAXALN + ARRAY_MARGIN));

    if(size ==0 || dq ==0 || dt==0) {
        fprintf(stderr,"[ERROR: not enough memory for chains, exiting]\n");
        exit(1);
    }


/**********************************************************************************************/

    chain_file = fopen(chain_file_name,"r");
    if(chain_file==NULL) {
	fprintf(stderr,"[ERROR: cannot access %s, exiting]\n", chain_file_name);
	exit(1);
    }

    fseek(chain_file, 0, SEEK_END);
    unsigned int last_pos = ftell(chain_file);
    fseek(chain_file, 0, SEEK_SET);

    while(fgets(buff,MAXBUFFLENGTH,chain_file)) {
        if(strlen(buff)<2) break;
     	buff[5]=0;
     	if(strcmp(buff,"chain")==0) {
       	    sscanf(buff+6,"%li %s %i %c %i %i %s %i %c %i %i %li",&score, &chr1[0], &len1, &strand1, &start1, &end1, &chr2[0], &len2, &strand2, &start2, &end2, &chain_id);
	    k=0;
	    while(fgets(buff,MAXBUFFLENGTH,chain_file)) {
		if(strlen(buff)<2) break;
		progressbar(ftell(chain_file), last_pos-1, (char*)"Processing ", verbose);
	    	sscanf(buff,"%i %i %i",size + k, dt + k, dq + k);
	    	k++;
	    	if(k>=MAXALN) {
		    fprintf(stderr,"[ERROR: chain too long, exiting]\n");
		    exit(1);
	    	}
	    }

	    x = get_chr_code(chr1);
	    if(x<0) continue;

            a=start1;b=start2;
            j=0;

	    for(i=chridx[x];i<chridx[x+1] && position[i]<start1;i++);
	    for(;i<chridx[x+1]&& position[i]<end1;i++) {
	    	while(position[i]>a+size[j]+dt[j] && j<k){
		    a+=size[j]+dt[j];
		    b+=size[j]+dq[j];
		    j++;
	    	}
	        if(j>=k) break;
	        if(position[i]-a > marginlength && a+size[j]-position[i] >= marginlength) {
                    if(strand1==strand2) {
                    	resstr = strand[i];
                    	rescrd = position[i] - a + b;
                    }
                    else {
                    	resstr = -strand[i];
                    	rescrd = len2 - (position[i] - a + b - 1) ;
                    }
                    fprintf(out_file,"%s\t%i\t%c\t%s\t%i\t%c\t%i\t%i\t%c\t%li\n",chr1, position[i], strand_i2c(strand[i]), chr2, rescrd, strand_i2c(resstr), idg[i], ids[i],type[i],score);
	    	}
	    }
     	}
    }
    fclose(chain_file);
    fclose(out_file);
    timestamp_report();

    free(size);
    free(dq);
    free(dt);

    free(position);
    free(strand);
    exit(0);
}
コード例 #18
0
ファイル: getmuf.c プロジェクト: BioinformaticsArchive/irbis
int main(int argc, char** argv) {
    char outputfilename[MAXBUFFLENGTH]="";
    char chr[MAXBUFFLENGTH]; 
    char* filename[MAXSPECIES];

    char buff[MAXLONGBUFFLENGTH];
    char seq[MAXLONGBUFFLENGTH];

    int  key[MAXKEYS];

    FILE *inpfile;
    FILE *outputfile;

    char *pc;
    int	x, max_key;
    int	i, j, nk, n_species;

    long pos, len, total;
    char strand;
    int *ind;
    char **muf;

    if(argc==1) {
	fprintf(stderr, "MUF builder\n");
	fprintf(stderr, "Usage: %s -i [input_file_1] [input_file_2] ... [input_file_n] -o [output file]\n STDIN: cps file for subsetting\n",argv[0]);
	exit(1);
    }

    timestamp_set();
    n_species=0;
    for(i=1; i<argc; i++) {
        pc = argv[i];
        if(*pc != '-') continue;
        if(*(pc+1) == 'o') {
            sscanf(argv[++i], "%s", &outputfilename[0]);
        }
        if(*(pc+1) == 'i') {
	    for(;i+1<argc;i++) {
		pc = argv[i+1];
		if(*pc == '-') break;
		filename[n_species]    = (char*)malloc(sizeof(char)*MAXBUFFLENGTH);
		strcpy(filename[n_species++],pc);
	    }
        }
	if(*(pc+1) == 'v') {
	    verbose=0;
	}
    }

    outputfile = fopen(outputfilename,"w");
    if(outputfile == NULL) {
        fprintf(stderr,"Can't open output file, exiting\n");
        exit(1);
    }

    max_key=0;
    nk=0;
    while(fgets(buff,MAXBUFFLENGTH,stdin)) {
        sscanf(buff,"%*s %*i %*c %*i %i",&x);
        if(x>max_key) max_key=x;
        key[nk++]=x;
        if(nk>=MAXKEYS-1) {fprintf(stderr,"[WARNING: too many keys to hold, ignoring the rest]\n");break;}
    }

    ind = (int*)malloc(sizeof(int)*(max_key + 16));
    muf = (char**)malloc(sizeof(char*)*(max_key + 16));
    if(ind==NULL) {
        fprintf(stderr,"Can't create index (%i), exiting\n",max_key);
        exit(1);
    }

    for(i=0;i<=max_key;i++) ind[i]=0;
    for(j=0;j<nk;j++) {
	ind[key[j]]=1;
	muf[key[j]]=(char*)malloc(sizeof(char)*MAXLONGBUFFLENGTH*MAXSPECIES);
	if(muf[key[j]]==NULL) {
	    fprintf(stderr,"Can't allocate enough memory, exiting\n");
	    exit(1);
	}
	muf[key[j]][0]=0;
	if(verbose) fprintf(stderr,"[%i]",key[j]);
    }
    if(verbose) fprintf(stderr,"\n");

    for(i=0;i<n_species;i++) {
	inpfile = fopen(filename[i], "r");
	if(verbose) fprintf(stderr,"[%s, ", filename[i]);
	if(inpfile==NULL) {
	    fprintf(stderr,"Cannot open %s, exiting",filename[i]);
            exit(1);
        }
	for(j=strlen(filename[i])-1;filename[i][j]!='.' && j>=0;j--);
	filename[i][j]=0;
	for(j--;filename[i][j]!='/' && j>=0;j--);
        if(verbose) fprintf(stderr,"tag=%s", filename[i] + j + 1);
	while(fgets(buff, MAXLONGBUFFLENGTH, inpfile)) {
	    x=0;
	    sscanf(buff,"%i %s %li %li %c %li %s", &x, &chr[0], &pos, &len, &strand, &total, &seq[0]);
	    if(x==0) {fprintf(stderr,"!");continue; }
	    if(x<=max_key) {
		if(ind[x]) {
                    sprintf(buff,"s %s.%s %li %li %c %li %s\n", filename[i] + j + 1, chr, pos, len, strand, total, seq);	
		    strcat(muf[x],buff);
		}
 	    }
	}
	if(verbose) fprintf(stderr,"]\n");
    }

    for(i=0;i<=max_key;i++) {
	if(ind[i]) if(strlen(muf[i])>1) fprintf(outputfile,"a id=%i\n%s\n", i, muf[i]);	
    }

    fclose(outputfile);

    timestamp_report();
    exit(0);
}
コード例 #19
0
ファイル: getwind.c プロジェクト: pervouchine/irbis
int main(int argc, char* argv[]) {
    char out_file_name[MAXBUFFLENGTH]="";
    char input_file_name[MAXBUFFLENGTH]="";
    char idx_file_name[MAXBUFFLENGTH];
    char dbx_file_name[MAXBUFFLENGTH];

    long offset;
    long seqlen;
    long intronic_window = 150;
    long exonic_window = 0;

    char filename[MAXBUFFLENGTH];
    char name[MAXBUFFLENGTH];

    char chr_name[MAXBUFFLENGTH];
    char buff[MAXBUFFLENGTH];
    char longbuff[MAXLONGBUFFLENGTH];
    char longbuffm[MAXLONGBUFFLENGTH];

    FILE *idx_file;
    FILE *dbx_file;
    FILE *input_file;
    FILE *outfile;
   
    int b,i,j,q,k,n,a,m,s;
    char c;
    long position,y;
    int strand;

    long** pos;
    int** str;
    char** typ;
    char*** ids;
    long p,l;

    int record_count[MAXCHR];
    int record_idx[MAXCHR];
    int cis = 0;
    int coord = 0;
    int all=0;

    int warnings = 0;

    char format[][64] = {"%*s %*i %*i %s %li %i %*s %s %c", "%s %li %i %*s %s %c"};

    if(argc==1) {
        fprintf(stderr,"This routine get sequence segments from a custom compressed FASTA repository  (see transf)\n");
        fprintf(stderr,"Last update by Dmitri Pervouchine ([email protected]) on Mar 22, 2013\n");
        fprintf(stderr," -in <aln_file>\n -dbx <database_file>\n -idx <index_file>\n -out <output_file>\n");
        fprintf(stderr," -we <exonic_window> [default=%i]\n -wi <intronic_window> [default=%i]\n -cis [use colunms 1-3] [default=%i]\n", exonic_window, intronic_window, cis);
	fprintf(stderr," -quiet <suppress verbose output> [default=no]\n -all <include all sites>\n -coord <offset for 3'-sites> [default=%i]\n",coord);
	exit(1);
    }

    timestamp_set();
    for(i=1;i<argc;i++) {
        if(strcmp(argv[i],"-in")==0) {
            sscanf(argv[++i], "%s", &input_file_name[0]);
        }

	if(strcmp(argv[i],"-dbx")==0) {
            sscanf(argv[++i], "%s", &dbx_file_name[0]);
	}

        if(strcmp(argv[i],"-idx")==0) {
            sscanf(argv[++i], "%s", &idx_file_name[0]);
        }

        if(strcmp(argv[i],"-out")==0) {
            sscanf(argv[++i], "%s", &out_file_name[0]);
        }

        if(strcmp(argv[i],"-we")==0) {
            sscanf(argv[++i], "%li", &exonic_window);
        }

        if(strcmp(argv[i],"-wi")==0) {
            sscanf(argv[++i], "%li", &intronic_window);
        }

        if(strcmp(argv[i],"-coord")==0) {
            sscanf(argv[++i], "%i", &coord);
        }

        if(strcmp(argv[i],"-quiet")==0) {
	    verbose = 0;
	}

        if(strcmp(argv[i],"-cis")==0) {
            cis = 1;
        }

        if(strcmp(argv[i],"-all")==0) {
            all = 1;
        }

    }

    if(out_file_name[0]==0) {
        fprintf(stderr,"[WARNING: output file not specified, redirect to stdout]\n");
        outfile = stdout;
    }
    else {
        outfile = fopen(out_file_name,"w");
        if(outfile == NULL) {
            fprintf(stderr,"[ERROR: output file %s cannot be opened for writing, exiting]\n", out_file_name);
            exit(1);
        }
        if(verbose) fprintf(stderr,"[>%s]\n",out_file_name);
    }

    input_file = fopen(input_file_name,"r");
    if(input_file == NULL) {
        fprintf(stderr,"[ERROR: cannot access %s, exiting]\n", input_file_name);
        exit(1);
    }

    if(verbose) fprintf(stderr,"[<%s, pass 1",input_file_name);
    while(fgets(buff,MAXBUFFLENGTH,input_file)) {
        if(strlen(buff)<2) break;
      	sscanf(buff, format[cis], &chr_name[0], &position, &strand, &name[0], &c);
      	n = assign_code(chr_name);
      	record_count[n]++;
    }
    if(verbose) fprintf(stderr,"]\n");

    pos = (long**) malloc(sizeof(long*)*(N_CHR_NAMES+1));
    str = (int**)  malloc(sizeof(int*)*(N_CHR_NAMES+1));
    typ = (char**) malloc(sizeof(char*)*(N_CHR_NAMES+1));
    ids = (char***)malloc(sizeof(char**)*(N_CHR_NAMES+1));

    if(pos==NULL || str==NULL || typ==NULL || ids==NULL) {
        fprintf(stderr,"[ERROR: failed to create index tables, exiting]\n");
        exit(1);
    }

    for(i=0;i<N_CHR_NAMES;i++) {
    	if(record_count[i]>0) {
	    pos[i] = (long*)  malloc(sizeof(long)*(record_count[i]+1));
	    str[i] = (int*)   malloc(sizeof(int)*(record_count[i]+1));
            typ[i] = (char*)  malloc(sizeof(char)*(record_count[i]+1));
	    ids[i] = (char**) malloc(sizeof(char*)*(record_count[i]+1));
	    if(pos[i]==NULL || str[i]==NULL || typ[i]==NULL || ids[i]==NULL) {
        	fprintf(stderr,"[ERROR: failed to create index tables, exiting]\n");
        	exit(1);
    	    }
	    record_idx[i]=0;
	}
    }

    if(verbose) fprintf(stderr,"[<%s, pass 2",input_file_name);
    fseek(input_file,  0, SEEK_SET);
    while(fgets(buff,MAXBUFFLENGTH,input_file)) {
        if(strlen(buff)<2) break;
	sscanf(buff, format[cis], &chr_name[0], &position, &strand, &name[0], &c);
	i = get_chr_code(chr_name);
	j = record_idx[i];
	pos[i][j] = position + (c=='D' ? coord*strand : 0);
	str[i][j] = strand;
	typ[i][j] = c;
	ids[i][j] = (char*) malloc(sizeof(char)*(strlen(name)+1));
	strcpy(ids[i][j],name);
	record_idx[i]++;
    }
    if(verbose) fprintf(stderr,"]\n");

    if(verbose) fprintf(stderr,"[<%s,%s",idx_file_name,dbx_file_name);
    idx_file = fopen(idx_file_name,"r");
    dbx_file = fopen(dbx_file_name,"r");
    if(idx_file == NULL || dbx_file == NULL) {
        fprintf(stderr,"[ERROR: cannot access %s or %s, exiting]\n", idx_file_name, dbx_file_name);
        exit(1);
    }

    offset = 0;
    while(fgets(buff,MAXBUFFLENGTH,idx_file)) {
        if(strlen(buff)<2) break;
        sscanf(buff,"%s" , &name[0]);
	while(fgets(buff,MAXBUFFLENGTH,idx_file)) {
            if(strlen(buff)<2) break;
	    sscanf(buff,"%s %li" , &chr_name[0], &seqlen);
	    i = get_chr_code(chr_name);
	    for(k=0;k<record_count[i];k++) {
               if(pos[i][k]>seqlen) {
		    warnings++;
                    continue;
                }
		l = exonic_window + intronic_window;
		if(typ[i][k]=='D' || typ[i][k]=='A' || all) { 
		    if(str[i][k]>0) {
		    	p = pos[i][k] - 1 - (typ[i][k]=='D' ? exonic_window : intronic_window);
		    }
		    else {
			p = pos[i][k] - (typ[i][k]=='D' ? intronic_window : exonic_window);
		    }
		    fget_segment(longbuff, dbx_file, offset, p, l);
		    if(str[i][k]<0) {
		    	rev1(longbuff);
		    }
               	    if(is_all_n(longbuff)) continue;
		    fprintf(outfile,"%s\t%s\t%li\t%li\t%i\t%li\t%s\t%c\n",ids[i][k], chr_name, (str[i][k]>0 ? p + 1 : seqlen - (p + l)), l, str[i][k], seqlen, longbuff,typ[i][k]);
		}
	    }
            offset+= (seqlen % 8 == 0) ? seqlen/8 : (seqlen/8 + 1);
	}
    }
    fclose(outfile);
    fclose(idx_file);
    fclose(dbx_file);
    if(verbose) fprintf(stderr,"]\n");
    if(verbose && warnings>0) fprintf(stderr,"[WARNING: %i windows were out of range, they were ignored]\n", warnings);

    timestamp_report();
    exit(0);
}
コード例 #20
0
ファイル: trim.c プロジェクト: BioinformaticsArchive/irbis
int main(int argc, char** argv) {
    dictionary<ATOMIC>* dict[MAXSPECIES];
    dictionary<ATOMIC>* filter;
    conservation_table* cons[MAXSPECIES];

    int i,j;
    FILE *configfile, *metacalc;

    wordexp_t exp_result;

    char buff[MAXBUFFLENGTH];
    char tag[MAXBUFFLENGTH];
    char aux[MAXBUFFLENGTH];

    char path[MAXBUFFLENGTH]="";
    char suffix[MAXBUFFLENGTH]="";

    char configfilename[MAXBUFFLENGTH];
    char restrictionfilename[MAXBUFFLENGTH];
    char metacalcfilename[MAXBUFFLENGTH]="";
    char maffilename[MAXBUFFLENGTH]="";

    int n_species=0;
    char* file_name[MAXSPECIES];
    double weight[MAXSPECIES];


    double threshold=0;
    double tot_weight=0;
    int halfsize=4;
    int gap=2;
    int min_gc=1;
    int repeat_length=2;
    int length_limit=0;

    subset *restriction=NULL;

    index_t p,q,r,s;
    word_t a;
    char *pc;
    char *p_file_name;

    int reverse_complement=0;


/***************************************************************************************************************************************/

    if(argc==1) {
	fprintf(stderr, "TRIM - this program takes sequences, creates corresponding hash tables, and intersects them by trimmming\n");
        fprintf(stderr, "Usage: %s -i config_file [-maf maf_file_name] -r restriction_file -o output_metafile\n",argv[0]);
	fprintf(stderr, "Other parameters are:\n -verbose [suppress verbose output]\n -rc [reverse complement sequences before adding]\n");
	exit(1);
    }

    timestamp_set();
    maffilename[0]=0;
    for(i=1;i<argc;i++) {
        pc = argv[i];
        if(*pc == '-') {
            if(strcmp(pc+1,"i") == 0) {
		configfile = fopen(argv[++i],"r");
		if(configfile==NULL) {
		    fprintf(logfile,"Input file (%s) cannot be opened, exiting", argv[i]);
		    exit(1);
		}
		n_species = 0;
		tot_weight= 0;
    		while(fgets(buff,MAXBUFFLENGTH,configfile)) {
        	    tag[0]=0;
        	    sscanf(buff,"%s %*s",tag);
        	    if(strcmp(tag,"path")==0) sscanf(buff,"%*s %s", &path[0]);
        	    if(strcmp(tag,"extention")==0)  sscanf(buff,"%*s %s", &suffix[0]);
        	    if(strcmp(tag,"halfsize")==0)   sscanf(buff,"%*s %i", &halfsize);
        	    if(strcmp(tag,"gap")==0)        sscanf(buff,"%*s %i", &gap);
        	    if(strcmp(tag,"repeatmask")==0) sscanf(buff,"%*s %i", &repeat_length);
        	    if(strcmp(tag,"gccontent")==0)  sscanf(buff,"%*s %i", &min_gc);
        	    if(strcmp(tag,"lowercase")==0)  sscanf(buff,"%*s %i", &lowercase_allowed);
        	    if(strcmp(tag,"threshold")==0)  sscanf(buff,"%*s %lf",&threshold);
		    if(strcmp(tag,"samewindow")==0) sscanf(buff,"%*s %i", &SAMEWINDOW);
		    if(strcmp(tag,"limit")==0)	    sscanf(buff,"%*s %i", &length_limit);
        	    if(strcmp(tag,"species")==0) {
			file_name[n_species] = (char*)malloc(sizeof(char)*MAXBUFFLENGTH);
			sscanf(buff,"%*s %s %lf", &file_name[n_species][0], &weight[n_species]);
			tot_weight+=weight[n_species];
            		n_species++;
		    }
		}
		fclose(configfile);
	    }
	    if(strcmp(pc+1,"maf") == 0) sscanf(argv[++i],"%s",&maffilename[0]);
	    if(strcmp(pc+1,"r") == 0)   restriction = new subset(argv[++i]);
	    if(strcmp(pc+1,"o") == 0) 	sscanf(argv[++i], "%s", &metacalcfilename[0]);
	    if(strcmp(pc+1,"verbose") == 0)	verbose = 0;
	    if(strcmp(pc+1,"rc") == 0)		reverse_complement = 1;

            if(strcmp(pc+1,"log")==0) {
            	logfile = fopen(argv[++i], "w");
            	if(logfile==NULL) logfile = stderr;
            }
	    
        }
    }

    if(halfsize<2 || gap>3) {
        if(verbose) fprintf(logfile,"Word size or gap are incorrect, exiting\n");
        exit(1);
    }

    metacalc = fopen(metacalcfilename,"wb");
    if(metacalc==NULL) {
        if(verbose) fprintf(logfile,"Output metacalc file cannot be opened, exiting\n");
        exit(1);
    }


/***************************************************************************************************************************************/

    if(threshold==0) threshold = 0.5;

    if(verbose) fprintf(logfile, "[Numeric parameters are: pattern=%i-%i-%i, minGC=%i, repeat=%i, threshold=%2.1lf%%]\n", halfsize, gap, halfsize, min_gc, repeat_length, threshold*100);
    if(verbose) fprintf(logfile, "[Boolean parameters are: lowercase=%s, reverse_complement=%s]\n",yesno(lowercase_allowed), yesno(reverse_complement)); 
    if(verbose) fprintf(logfile, "[Extra parameters are: SAMEWINDOW=%i, sequence length limit=%i]\n",SAMEWINDOW,length_limit); 

    wordexp(path, &exp_result, 0);
    sprintf(&path[0],"%s",exp_result.we_wordv[0]);


/***************************************************************************************************************************************/

    filter = new dictionary<ATOMIC>(halfsize,gap);
    filter->mask_low_complexity(repeat_length);
    if(min_gc>0) filter->mask_low_GCcontent(min_gc);
    for(i=0;i<n_species;i++) {
        dict[i] = new dictionary<ATOMIC>(halfsize,gap);
        dict[i]->filter = filter;
    }

    if(maffilename[0]==0) {
    	for(i=0;i<n_species;i++) {
	    p_file_name = getfullname(path,file_name[i],suffix);
	    if(verbose) fprintf(logfile,"[Reading %s: ",p_file_name);
	    dict[i]->read_from_suf(p_file_name, restriction, reverse_complement,length_limit);
	    dict[i]->check();
	    cons[i] = new conservation_table(dict[i]->max_key);
	    cons[i]->before = dict[i]->fill_cons();
            if(verbose) fprintf(logfile,", weight=%2.1lf]\n",weight[i]);
	}
    }
    else {
    	if(verbose) fprintf(logfile,"[Reading %s: ", maffilename);
    	dictionary<ATOMIC>::read_from_muf(maffilename, dict, restriction, file_name, n_species, reverse_complement,length_limit);
    	if(verbose) fprintf(logfile,"]\n");
    	for(i=0;i<n_species;i++) {
            if(verbose) fprintf(logfile,"[%s",file_name[i]);
            dict[i]->info();
            dict[i]->check();
            cons[i] = new conservation_table(dict[i]->max_key);
            cons[i]->before = dict[i]->fill_cons();
            if(verbose) fprintf(logfile,", weight=%2.1lf]\n",weight[i]);
    	}
    }

    dictionary<ATOMIC>::intersect_many(dict, n_species, weight, threshold*tot_weight, (char*)"Intersect ");

    if(verbose) fprintf(logfile,"[Compute conservation rates:");
    for(i=0;i<n_species;i++) {
	if(verbose) fprintf(logfile," %s",file_name[i]);
	cons[i]->after = dict[i]->fill_cons();
    }
    if(verbose) fprintf(logfile,"]\n");

    if(verbose) fprintf(logfile,"[Metacalc: saving data to %s]\n",metacalcfilename);
    fprintf(metacalc,"%i %i %i %lf\n", halfsize, gap, n_species, threshold);
    for(i=0;i<n_species;i++) {
    	if(verbose) fprintf(logfile,"[Saving %s",file_name[i]);
	dict[i]->check();
	dict[i]->info();
	fprintf(metacalc,"%s %lf\n", file_name[i], weight[i]);
	dict[i]->save(metacalc);
	cons[i]->save(metacalc);
	if(verbose) fprintf(logfile,"]\n");
    }

    fclose(metacalc);
    timestamp_report();
    return(0);
}
コード例 #21
0
ファイル: best_match.c プロジェクト: pervouchine/irbis
int main(int argc, char* argv[]) {
    char alnfilename[MAXBUFFLENGTH];
    char cpsfilename[MAXBUFFLENGTH];
    char outfilename[MAXBUFFLENGTH]="";
 
    char c;

    char buff[MAXBUFFLENGTH];
    char aux[MAXBUFFLENGTH];

    int start1,end1,len1,start2,end2,len2;
    char strand1, strand2;

    int a,b,k,l,i,j,s,m,q;
    int d,dmin,lmin,score_max;
    int x,y;

    int qbest, kbest, jbest;
    int kprev;

    int *gene_idx;	//index
    int *gene_off;	//offset  
    int *gene_site;	//site number
    char *gene_styp;	//site type
    int *gene_pos;	//site position
    int *gene_chr;	//chromosome
    char *gene_str;	//strand

    int max_genes;
    int max_sites;

    int *site_idx;	//index
    int *site_off;	//offset
    int *site_chr;	//matching chromosome
    int *site_pos;	//matching pos
    int *site_str;	//matching strand
    int *site_score;	//--- optimal score
    int *site_lbest;    //--- where it came from
    int *site_qbest;    //--- where it came from

    int specific_site=0;

    double dthreshold = 0.50;
    int dlimit = 5000;
    int max_depth = 4;

    int pos, strand;

    if(argc==1) {
	fprintf(stderr,"Select best unique maping from the ALN file created by map_single\n");
        fprintf(stderr,"Last updated by Dmitri Pervouchine ([email protected]) on Jan 28, 2013\n");
	fprintf(stderr,"Keys:\n -in <cps file>\n -aln <aln file>\n -out <output file>\n");
 	//fprintf(stderr," -l length difference limit [%i]\n -t percentage difference threshold [%1.2lf] (ONE OR THE OTHER THRESHOLD IS USED)\n -h max_depth [%i]\n",dlimit, dthreshold,max_depth);
	//fprintf(stderr," -v suppress verbose output [NO]\n");
	exit(1);
    }

    timestamp_set();
    for(i=1;i<argc;i++) {
        if(strcmp(argv[i],"-in")==0) {
            sscanf(argv[++i], "%s", &cpsfilename[0]);
        }
        if(strcmp(argv[i],"-aln")==0) {
            sscanf(argv[++i], "%s", &alnfilename[0]);
        }
        if(strcmp(argv[i],"-out")==0) {
            sscanf(argv[++i], "%s", &outfilename[0]);
        }
        if(strcmp(argv[i],"-lendiff")==0) {
            sscanf(argv[++i], "%i", &dlimit);
        }
        if(strcmp(argv[i],"-threshold")==0) {
            sscanf(argv[++i], "%lf", &dthreshold);
        }
        if(strcmp(argv[i],"-maxdepth")==0) {
            sscanf(argv[++i], "%i", &max_depth);
        }
        if(strcmp(argv[i],"-quiet")==0) {
            verbose=0;
        }
        if(strcmp(argv[i],"-s")==0) {
            sscanf(argv[++i], "%i", &specific_site);
        }
    }

    if(outfilename[0]==0) {
        fprintf(stderr,"[WARNING: output file not specified, redirect to stdout]\n");
        outfile = stdout;
    }
    else {
        outfile = fopen(outfilename,"w");
        if(outfile == NULL) {
            fprintf(stderr,"[ERROR: output file (%s) cannot be opened, exiting]\n", outfilename);
            exit(1);
        }
    }

/*******************************************************************************************************/
    cpsfile= fopen(cpsfilename,"r");
    if(cpsfile==NULL) {
	fprintf(stderr,"Can't access CPS file. Exiting\n");
	exit(1);
    }

    if(verbose) fprintf(stderr,"[Reading CPS, pass 0");
    max_sites = max_genes = 0;
    while(fgets(buff,MAXBUFFLENGTH,cpsfile)) {
      	if(strlen(buff)<2) break;
        sscanf(buff,"%*s %*i %*i %i %i", &i, &j);
        if(i>max_genes) max_genes = i;
	if(j>max_sites) max_sites = j;
    }

    max_genes++;
    max_sites++;

    gene_idx = (int*)  malloc(sizeof(int)*(max_genes+1));
    gene_off = (int*)  malloc(sizeof(int)*(max_genes+1));
    gene_chr = (int*)  malloc(sizeof(int)*(max_genes+1));
    gene_str = (char*) malloc(sizeof(char)*(max_genes+1));

    for(i=0;i<max_genes;i++) gene_idx[i]=gene_off[i]=0;

    if(verbose) fprintf(stderr,", max_genes = %i, max_sites = %i]\n", max_genes, max_sites);

    if(verbose) fprintf(stderr,"[Reading CPS, pass 1");
    fseek (cpsfile, 0, SEEK_SET);
    while(fgets(buff,MAXBUFFLENGTH,cpsfile)) {
        if(strlen(buff)<2) break;
        sscanf(buff,"%s %*i %i %i %*i" , aux, &strand, &i);
        gene_idx[i]++;
	gene_chr[i] = assign_code(aux);
	gene_str[i] = strand;
    }

    for(s=i=0;i<max_genes;i++) {
        x = gene_idx[i];
        gene_idx[i] =s;
        s+=x;
    }
    gene_idx[i] = s;

    gene_site = (int*)  malloc(sizeof(int)*(s+1));
    gene_styp = (char*) malloc(sizeof(char)*(s+1));
    gene_pos  = (int*)  malloc(sizeof(int)*(s+1));

    if(verbose) fprintf(stderr,", records = %i]\n", s);

    if(verbose) fprintf(stderr,"[Reading CPS, pass 2");
    fseek (cpsfile, 0, SEEK_SET);
    while(fgets(buff,MAXBUFFLENGTH,cpsfile)) {
        if(strlen(buff)<2) break;
        sscanf(buff,"%*s %i %*i %i %i %c" , &x, &i, &j, &c);
	gene_site[gene_idx[i]+gene_off[i]]=j;
        gene_styp[gene_idx[i]+gene_off[i]]=c;
        gene_pos[gene_idx[i]+gene_off[i]]=x;
	gene_off[i]++;
    }
    fclose(cpsfile);
    if(verbose) fprintf(stderr,"]\n");
/**********************************************************************************************/

    alnfile = fopen(alnfilename,"r");
    if(alnfile == NULL) {
	fprintf(stderr, "Cant open alignment file, exiting\n");
	exit(1);
    }

    site_idx = (int*) malloc(sizeof(int)*(max_sites+1));
    site_off = (int*) malloc(sizeof(int)*(max_sites+1));

    for(i=0;i<max_sites;i++) {
        site_idx[i]=site_off[i]=0;
    }

    if(verbose) fprintf(stderr,"[Reading alignment file, pass 1");

    while(fgets(buff,MAXBUFFLENGTH,alnfile)) {
        if(strlen(buff)<2) break;
        sscanf(buff,"%*s %*i %*i %*s %*i %*i %*i %i %*c" , &i);
	site_idx[i]++;
    }

    for(s=i=0;i<max_sites;i++) {
        x = site_idx[i];
        site_idx[i] =s;
        s+=x;
    }
    site_idx[i] = s;

    site_chr   = (int*) malloc(sizeof(int)*(s+1));
    site_pos   = (int*) malloc(sizeof(int)*(s+1));
    site_str   = (int*) malloc(sizeof(int)*(s+1));
    site_score = (int*) malloc(sizeof(int)*(s+1));
    site_lbest = (int*) malloc(sizeof(int)*(s+1));
    site_qbest = (int*) malloc(sizeof(int)*(s+1));

    if(verbose) fprintf(stderr,", records = %i]\n",s);

    if(verbose) fprintf(stderr,"[Reading alignment file, pass 2");
    fseek (alnfile, 0, SEEK_SET);
    while(fgets(buff,MAXBUFFLENGTH,alnfile)) {
        if(strlen(buff)<2) break;
        sscanf(buff,"%*s %*i %*i %s %i %i %*i %i %*c" , &aux, &pos, &strand, &i);
	site_chr[site_idx[i]+site_off[i]] = assign_code(aux);
        site_pos[site_idx[i]+site_off[i]] = pos;
        site_str[site_idx[i]+site_off[i]] = strand;
	site_score[site_idx[i]+site_off[i]] = 0;
        site_lbest[site_idx[i]+site_off[i]] = -1;
        site_qbest[site_idx[i]+site_off[i]] = -1;
	site_off[i]++;
    }
    fclose(alnfile);
    if(verbose) fprintf(stderr,"]\n");

    for(i=0;i<max_genes;i++) {
	progressbar(i,max_genes-1, (char*)"Processing");
	score_max=0;
	kbest = -1;
	for(j=gene_idx[i];j<gene_idx[i+1];j++) {
	    x = gene_site[j];
	    for(k=site_idx[x];k<site_idx[x+1];k++) {
		site_score[k] = 0;
		site_lbest[k] = site_qbest[k] = -1;
	    }
	    for(q=1;q<=max_depth;q++) {
            	if(j-q>=gene_idx[i]) {
                    y = gene_site[j-q];
	   	    a = abs(gene_pos[j]-gene_pos[j-q]);
		    for(k=site_idx[x];k<site_idx[x+1];k++) {
			dmin = INFTY;
			lmin = -1;
			for(l=site_idx[y];l<site_idx[y+1];l++) {
			    if(site_chr[k] == site_chr[l] && site_str[k] == site_str[l]) {
			    	b = abs(site_pos[k]-site_pos[l]);
				d = abs(b-a);
				if(d<dmin) {
				    dmin = d;
				    lmin = l;
				}
				if(x==specific_site) fprintf(stderr,"[prev=%i curr=%i pos_p=%i pos_c=%i d=%i]\n",y,x,site_pos[l],site_pos[k],d);
			    }
			}
			m  = (lmin>=0 && (((double)dmin/a)<dthreshold || dmin<dlimit)) ? site_score[lmin] + a : 0;			
			if(m>site_score[k]) {
			    site_score[k] = m;
			    site_lbest[k] = lmin;
                            site_qbest[k] = q;
			}
			if(site_score[k]>score_max) {
			    score_max = site_score[k];
			    kbest = k; jbest = j;
			}
			if(x==specific_site) fprintf(stderr,"[curr=%i score=%i]\n",x,site_score[k]);
		    }
		}
	    }
	}
	j = jbest;
	k = kbest;
	if(k>=0 && site_score[k]>0) {
	    fprintf(outfile,"%s\t%i\t%i\t%s\t%i\t%i\t",get_chr_name(gene_chr[i]),gene_pos[j],gene_str[i],get_chr_name(site_chr[k]),site_pos[k],site_str[k]);
	    fprintf(outfile,"%i\t%i\t%c\t%i\t%i\n",i,gene_site[j],gene_styp[j],site_pos[site_lbest[k]],0);
	    while(site_score[k]>0 && site_lbest[k]>=0 && site_qbest[k]>=0) {
		kprev = k;
            	j = j - site_qbest[k];
                k = site_lbest[k];
 		fprintf(outfile,"%s\t%i\t%i\t%s\t%i\t%i\t",get_chr_name(gene_chr[i]),gene_pos[j],gene_str[i],get_chr_name(site_chr[k]),site_pos[k],site_str[k]);
		fprintf(outfile,"%i\t%i\t%c\t%i\t%i\n",i,gene_site[j],gene_styp[j],(site_lbest[k]>=0?site_pos[site_lbest[k]]:0),(kprev>=0?site_pos[kprev]:0));
	    }
 
	}
    }
    timestamp_report();
    exit(0);
}