Esempio n. 1
0
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        g=count=0;
        memset(hash,0,sizeof(hash));
        memset(vis,0,sizeof(vis));
        scanf("%d",&n);
        A2[i]=0;
        for(i=1; i<=n; i++)
        {
            scanf("%d",&a[i]);
            //num1[i]=a[i];
            A2[i]=1;
            //hash[i]=0;
        }
        for(i=1; i<=n; i++)
        {
            c=1;
            if(!vis[i])
            {
                k=a[i];
                vis[k]=1;
                while(i!=k)
                {
                    vis[k]=1;
                    k=a[k];
                    c++;
                }
            }

            /*for(i=1; i<=n; i++)
            {

                if((num1[i])!=-1)
                {
                    count++;
                    pos1=i;
                    temp1=num1[pos1];
                    while(1)
                    {
                        pos1=temp1;
                        if(pos1==i)
                        {
                            num1[pos1];
                            break;
                        }
                        temp1=num1[pos1];
                        num1[pos1]=-1;
                        m++;
                    }

                }*/
                if(hash[c]<1)
                {
                    A2[g]=c;
                    hash[c]++;
                    if(g==0)
                        k=A2[0];
                    if(k>1)
                        k=lcm(k,A2[g])%mod;
                    g++;
                }
                // A2[i]=m;
                c=1;

            }
            //            for(i=0;i<g;i++)
            //	printf("%d ",A2[i]);
            //  long int k;
            //  k=lcms(g,A2)%1000000007;
            printf("%lld\n",k);
        }


        return 0;
    }
Esempio n. 2
0
bool Fraction::operator<=(const Fraction& val) const
{
    const int v = lcm(_denominator, val._denominator);
    return _numerator * (v / _denominator) <= val._numerator * (v / val._denominator);
}
bool ReducedFraction::operator!=(const ReducedFraction& val) const
      {
      const int v = lcm(denominator_, val.denominator_);
      return fractionPart(v, numerator_, denominator_)
                  != fractionPart(v, val.numerator_, val.denominator_);
      }
Esempio n. 4
0
int main(){
    int t,tNum, conditions, i, j, k,i1,i2,l, lcmT, lcmP, X, Y;
    long long N;
    scanf("%d", &t);
    while(t--){
        scanf("%I64d %d", &N, &conditions);
        for(i=6; i>0; i--,conditions/=10)cond[i]=conditions%10;
        if(cond[1]==0){
            printf("0\n");
            continue;
        }
        lcmT=1;lcmP=1;l=0;
        for(i=2; i<7; i++){
            if(cond[i]==1)lcmT=lcm(lcmT, i);
            if(cond[i]==0&&++l)lcmP=lcm(lcmP, i);
        }
        X = countDiv(N, lcmT);

        Y=0;
        for(i=2; i<7; i++){
            if(cond[i]==0) {
                Y=modulo(Y+countDiv(N, lcm(lcmT, i)) ,MOD);
            }
        }
        if(l<2){
            printf("%d\n", modulo(X-Y, MOD));
            continue;
        }
        for(i=2; i<7; i++){
            if(cond[i]==0){
                for(j=i+1; j<7; j++){
                    if(cond[j]==0){
                        Y=modulo(Y-countDiv(N, lcm(lcm(lcmT, i), lcm(lcmT, j))), MOD);
                    }
                }
            }
        }
        if(l<3){
            printf("%d\n", modulo(X-Y, MOD));
            continue;
        }
        for(i=2; i<7; i++){
            if(cond[i]==0){
                for(j=i+1; j<7; j++){
                    if(cond[j]==0){
                        for(k=j+1; k<7; k++){
                            if(cond[k]==0){
                                Y=modulo(Y+countDiv(N, lcm(lcm(lcm(lcmT, i), lcm(lcmT, j)),lcm(lcmT, k))), MOD);
                            }
                        }
                    }
                }
            }
        }
        if(l<4){
            printf("%d\n", modulo(X-Y, MOD));
            continue;
        }
        for(i=2; i<7; i++){
            if(cond[i]==0){
                for(j=i+1; j<7; j++){
                    if(cond[j]==0){
                        for(k=j+1; k<7; k++){
                            if(cond[k]==0){
                                for(i1=k+1; i1<7; i1++){
                                    if(cond[i1]==0){
                                        Y=modulo(Y-countDiv(N, lcm(lcm(lcm(lcm(lcmT, i), lcm(lcmT, j)),lcm(lcmT, k)), lcm(lcmT,i1))), MOD);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        if(l<5){
            printf("%d\n", modulo(X-Y, MOD));
            continue;
        }
        if(cond[2]==0){
            if(cond[3]==0){
                if(cond[4]==0){
                    if(cond[5]==0){
                        if(cond[6]==0){
                            Y=modulo(Y+countDiv(N, 60) , MOD);
                        }
                    }
                }
            }
        }
        printf("%d\n", modulo(X-Y, MOD));
    }
    return 0;
}
Esempio n. 5
0
rtems_task Init(
	rtems_task_argument argument
)
{
	rtems_status_code status;
	rtems_time_of_day time;
	int i = 0;
	int schedulability;
	double start, end;
 
	printf("10tasks_1.83hardFactor_1.83softFactor_60.0hardTasksPerc_70uti\nSet 0 to Set 9:\n\n");
	//printf("10tasks_1.83hardFactor_1.83softFactor_40.0hardTasksPerc_86uti\nSet 10 to Set 19:\n\n");
	//printf("10tasks_1.83hardFactor_1.0softFactor_60.0hardTasksPerc_78uti\nSet 10 to Set 19:\n\n");
	//printf("10tasks_1.08hardFactor_1.08softFactor_60.0hardTasksPerc_92uti\nSet 0 to Set 9:\n\n");
	//printf("10tasks_2.83hardFactor_2.83softFactor_60.0hardTasksPerc_50uti\nSet 0 to Set 9:\n\n");

	tick_per_second = rtems_clock_get_ticks_per_second();
	printf("\nTicks per second in your system: %" PRIu32 "\n", tick_per_second);

// sec_loopCount=LoopCountingForASec(); //for init the relative count
//	printf("Loop count per second: %i \n\n", sec_loopCount);

/*
  start = rtems_clock_get_ticks_since_boot() / (double)tick_per_second;
  LOOP(0.005);
  end = rtems_clock_get_ticks_since_boot() / (double)tick_per_second;
  printf("start = %.6f, end = %.6f\n", start, end);
*/
/*
  time.year   = 1988;
  time.month  = 12;
  time.day    = 31;
  time.hour   = 9;
  time.minute = 0;
  time.second = 0;
  time.ticks  = 0;

  status = rtems_clock_set( &time );
*/
	#include "10tasks_1.83hardFactor_1.83softFactor_60.0hardTasksPerc_70uti.h"
	//#include "10tasks_1.83hardFactor_1.83softFactor_40.0hardTasksPerc_86uti_mod.h"
	//#include "10tasks_1.83hardFactor_1.0softFactor_60.0hardTasksPerc_78uti_mod.h"
	//#include "10tasks_1.08hardFactor_1.08softFactor_60.0hardTasksPerc_92uti_mod.h"	
	//#include "10tasks_2.83hardFactor_2.83softFactor_60.0hardTasksPerc_50uti_mod.h"
	
	
  	Task_name[ 1 ] = rtems_build_name( 'T', 'A', '1', ' ' );
  	Task_name[ 2 ] = rtems_build_name( 'T', 'A', '2', ' ' );
  	Task_name[ 3 ] = rtems_build_name( 'T', 'A', '3', ' ' );
  	Task_name[ 4 ] = rtems_build_name( 'T', 'A', '4', ' ' );
  	Task_name[ 5 ] = rtems_build_name( 'T', 'A', '5', ' ' );
  	Task_name[ 6 ] = rtems_build_name( 'T', 'A', '6', ' ' );
  	Task_name[ 7 ] = rtems_build_name( 'T', 'A', '7', ' ' );
  	Task_name[ 8 ] = rtems_build_name( 'T', 'A', '8', ' ' );
  	Task_name[ 9 ] = rtems_build_name( 'T', 'A', '9', ' ' );
  	Task_name[ 10 ] = rtems_build_name( 'T', 'A', '1', '0' );

  	for(i = 0; i<ntask; i++){
		  taskrunning_table[i] = 0;
		  preempted_table[0][i] = 0;
		  preempted_table[1][i] = 0;
		  deltastart_table[i] = 0;
     	d_t[i] = 0;
    	sp_dl_missed_table[i] = 0;
   		tsk[i].period = 0;
   		tsk[i].utilization = 0;
		  tsk[i].task_type = 0;
    	tsk[i].normal_et = 0;
  		tsk[i].abnormal_et= 0;
   		tsk[i].id = i;
   		tsk[i].priority = -1;
	  }

  while(1){
#if 0
		int lcmAmong=(int)tsk[0].period;
  		for(i=1; i<ntask; i++){
			lcmAmong=lcm(lcmAmong, (int)tsk[i].period);
      			printf("\n");
  		}
  		testnumber = CEILING_POS((double)lcmAmong / tsk[4].period); //take hyperperiod to setup the lowest priority task
#else
    testnumber = 15;
  		//testnumber = taskinputs[task_set_idx].testnum;
  		//printf("testnumber %d,", testnumber);
#endif

		for(i=0; i<ntask; i++){
			tsk[i].period = taskinput[task_set_idx].tasks[i].period;
  			//tsk[i].utilization = taskinputs[task_set_idx].tasks[i].utilization;
			tsk[i].task_type = taskinput[task_set_idx].tasks[i].task_type;
			tsk[i].normal_et = taskinput[task_set_idx].tasks[i].normal_et;
			tsk[i].abnormal_et = taskinput[task_set_idx].tasks[i].abnormal_et;
			//printf("Task %i with normal exe %.1f\n",i,tsk[i].normal_et);
		}
  
/************************************************/
		//printf("Again Declaratioan of variable:\n");
		sys_totalruntime = 0;
	  sys_totalhealthy_percentage = 0;
		sys_totalunhealthy_percentage = 0;
		sys_healthy_start = 0;
    sys_healthy_end = 0;
		sys_unhealthy_start = 0;
    sys_unhealthy_end = 0;
		sys_healthy_duration = 0;
    sys_unhealthy_duration = 0;
    sys_healthy_total_duration = 0;
    sys_unhealthy_total_duration = 0;
    task_running_flag = FALSE;
    sys_fault_flag = FALSE;
    sys_stop_flag = FALSE;
      
		for(i=0; i<ntask; i++){
			taskrunning_table[i] = 0;
      tsk[i].priority = -1;
    }
//      printf("\n\n\n*** NXT TEST %d ***\n", inittask_count);

#if 1
/*
  		tsk[0].task_type = 0;
 		tsk[1].task_type = 0;
  		tsk[2].task_type = 0;
  		tsk[3].task_type = 1;
  		tsk[4].task_type = 1;
  
  		inittask_count = 28;
*/
#else
		Exhaustive_Task_Type(ntask, inittask_count, tsk);
#endif

		schedulability =priority_assignment(tsk, ntask);

		if(schedulability == -1){
			printf("x\n");
//         		printf("Tasks are not schedulable.\nThis Operation will skip immediately.\n");	 
    }else{
    	if(task_set_idcheck != task_set_idx){
				printf("Current task set is set %d. \n",task_set_idx);
				task_set_idcheck = task_set_idx;
			}

			status = rtems_task_create(
				Task_name[ 1 ], tsk[0].priority, RTEMS_MINIMUM_STACK_SIZE * 2, RTEMS_DEFAULT_MODES,
            			RTEMS_DEFAULT_ATTRIBUTES, &Task_id[ 1 ]
         		);
         		if ( status != RTEMS_SUCCESSFUL) {
            			printf( "rtems_task_create 1 failed with status of %d.\n", status );
           		 	exit( 1 );
         		} 
			running_flag[0]=1; 
#if 0
      			status = rtems_task_create(
				Task_name[ 2 ], tsk[1].priority, RTEMS_MINIMUM_STACK_SIZE * 2, RTEMS_DEFAULT_MODES,
				RTEMS_DEFAULT_ATTRIBUTES, &Task_id[ 2 ]
			);
        	 	if ( status != RTEMS_SUCCESSFUL) {
				printf( "rtems_task_create 2 failed with status of %d.\n", status );
				exit( 1 );
			}
			running_flag[1]=1; 

			status = rtems_task_create(
				Task_name[ 3 ], tsk[2].priority, RTEMS_MINIMUM_STACK_SIZE * 2, RTEMS_DEFAULT_MODES,
				RTEMS_DEFAULT_ATTRIBUTES, &Task_id[ 3 ]
			);
        	 	if ( status != RTEMS_SUCCESSFUL) {
				printf( "rtems_task_create 3 failed with status of %d.\n", status );
				exit( 1 );
			}
	         	running_flag[2]=1; 
 
        		status = rtems_task_create(
				Task_name[ 4 ], tsk[3].priority, RTEMS_MINIMUM_STACK_SIZE * 2, RTEMS_DEFAULT_MODES,
				RTEMS_DEFAULT_ATTRIBUTES, &Task_id[ 4 ]
			);
			if ( status != RTEMS_SUCCESSFUL) {
				printf( "rtems_task_create 4 failed with status of %d.\n", status );
				exit( 1 );
			} 
         		running_flag[3]=1;
 
			status = rtems_task_create(
				Task_name[ 5 ], tsk[4].priority, RTEMS_MINIMUM_STACK_SIZE * 2, RTEMS_DEFAULT_MODES,
				RTEMS_DEFAULT_ATTRIBUTES, &Task_id[ 5 ]
			);
			if ( status != RTEMS_SUCCESSFUL) {
				printf( "rtems_task_create 5 failed with status of %d.\n", status );
				exit( 1 );
			}
	        	running_flag[4]=1; 

      			status = rtems_task_create(
         			Task_name[ 6 ], tsk[5].priority, RTEMS_MINIMUM_STACK_SIZE * 2, RTEMS_DEFAULT_MODES,
         			RTEMS_DEFAULT_ATTRIBUTES, &Task_id[ 6 ]
         		);
        		if ( status != RTEMS_SUCCESSFUL) {
         			printf( "rtems_task_create 6 failed with status of %d.\n", status );
           			exit( 1 );
			}
         		running_flag[5]=1; 

      			status = rtems_task_create(
         			Task_name[ 7 ], tsk[6].priority, RTEMS_MINIMUM_STACK_SIZE * 2, RTEMS_DEFAULT_MODES,
         			RTEMS_DEFAULT_ATTRIBUTES, &Task_id[ 7 ]
         		);
        		if ( status != RTEMS_SUCCESSFUL) {
         			printf( "rtems_task_create 7 failed with status of %d.\n", status );
            			exit( 1 );
        		} 
         		running_flag[6]=1; 

	      		status = rtems_task_create(
        	 		Task_name[ 8 ], tsk[7].priority, RTEMS_MINIMUM_STACK_SIZE * 2, RTEMS_DEFAULT_MODES,
         			RTEMS_DEFAULT_ATTRIBUTES, &Task_id[ 8 ]
         		);
        		if ( status != RTEMS_SUCCESSFUL  ) {
         			printf( "rtems_task_create 8 failed with status of %d.\n", status );
      				exit( 1 );
     			}
         		running_flag[7]=1; 

	      		status = rtems_task_create(
        	 		Task_name[ 9 ], tsk[8].priority, RTEMS_MINIMUM_STACK_SIZE * 2, RTEMS_DEFAULT_MODES,
         			RTEMS_DEFAULT_ATTRIBUTES, &Task_id[ 9 ]
         		);
        		if( status != RTEMS_SUCCESSFUL) {
				printf( "rtems_task_create 9 failed with status of %d.\n", status );
				exit( 1 );
			}
			running_flag[8]=1;
#endif
			status = rtems_task_create(
	         		Task_name[ 10 ], tsk[9].priority, RTEMS_MINIMUM_STACK_SIZE * 2, RTEMS_DEFAULT_MODES,
        	 		RTEMS_DEFAULT_ATTRIBUTES, &Task_id[ 10 ]
         		);
        		if ( status != RTEMS_SUCCESSFUL) {
         			printf( "rtems_task_create 10 failed with status of %d.\n", status );
           			exit( 1 );
        		}
        		running_flag[9]=1; 

      // prototype: rtems_task_start( id, entry_point, argument );
			experiment_flag = 1;
			inittask_id=rtems_task_self();
			status = rtems_task_start( Task_id[ 1 ], Task_1, 1);
			if ( status != RTEMS_SUCCESSFUL) {
				printf( "rtems_task_start 1 failed with status of %d.\n", status );
          			exit( 1 );
      			}
#if 0
			status = rtems_task_start( Task_id[ 2 ], Task_2, 1);
	       		if ( status != RTEMS_SUCCESSFUL) {
	        		printf( "rtems_task_start 2 failed with status of %d.\n", status );
	           		exit( 1 );
	       		}

			status = rtems_task_start( Task_id[ 3 ], Task_3, 1);
		         if ( status != RTEMS_SUCCESSFUL) {
	       			printf( "rtems_task_start 3 failed with status of %d.\n", status );
	          		exit( 1 );
	       		}

			status = rtems_task_start( Task_id[ 4 ], Task_4, 1);
	 	  	if ( status != RTEMS_SUCCESSFUL) {
				printf( "rtems_task_start 4 failed with status of %d.\n", status );
		           	exit( 1 );
       			}

			status = rtems_task_start( Task_id[ 5 ], Task_5, 1);
			if ( status != RTEMS_SUCCESSFUL) {
				printf( "rtems_task_start 5 failed with status of %d.\n", status );
	        	  	exit( 1 );
      			}

      			status = rtems_task_start( Task_id[ 6 ], Task_6, 1);
       			if ( status != RTEMS_SUCCESSFUL) {
     				printf( "rtems_task_start 6 failed with status of %d.\n", status );
     		     		exit( 1 );
      			}

   			status = rtems_task_start( Task_id[ 7 ], Task_7, 1);
      			if ( status != RTEMS_SUCCESSFUL) {
        			printf( "rtems_task_start 7 failed with status of %d.\n", status );
        			exit( 1 );
    			}

    			status = rtems_task_start( Task_id[ 8 ], Task_8, 1);
	      		if ( status != RTEMS_SUCCESSFUL) {
       				printf( "rtems_task_start 8 failed with status of %d.\n", status );
      				exit( 1 );
    			}

     			status = rtems_task_start( Task_id[ 9 ], Task_9, 1);
    			if ( status != RTEMS_SUCCESSFUL) {
	       			printf( "rtems_task_start 9 failed with status of %d.\n", status );
				exit( 1 );
      			}
#endif
      			status = rtems_task_start( Task_id[ 10 ], Task_10, 1);
      			if ( status != RTEMS_SUCCESSFUL) {
       				printf( "rtems_task_start 10 failed with status of %d.\n", status );
        			exit( 1 );
       			}

          		//printf("checkpoint 1.\n");
      			// delete init task after starting the three working tasks
			status = rtems_task_suspend(RTEMS_SELF);
	//	      printf("YES, it is feasible to use suspend/resume on init\n");
		}

		printf("with fault rate at %.6f rate and task count now is %d. \n",fault_rate[refer_fault_rate],inittask_count);
		inittask_count+=1;
		if(refer_fault_rate+1 == 4){
		//if(refer_fault_rate+1 == 2){
			printf("checked\n\n");
  			task_set_idx++;
		}
		refer_fault_rate= (refer_fault_rate+1)%4;  
		//refer_fault_rate= (refer_fault_rate+1)%2;
      		//At this moment, the experiment is done; inittask_count for experiment to be finished is number of fault rate to be tested * number of task set
		//if (inittask_count == 40){
		if (inittask_count == 1){
			printf("The testing is finished among 40 combinations\n");
			break;
  		}
	}
	status = rtems_task_delete( RTEMS_SELF );
}
Esempio n. 6
0
int
addresslist_append(struct addresslist *adrlist, uint8_t proto,
    struct in_addr saddr_begin, struct in_addr saddr_end,
    struct in_addr daddr_begin, struct in_addr daddr_end,
    uint16_t sport_begin, uint16_t sport_end,
    uint16_t dport_begin, uint16_t dport_end)
{
	struct address_tuple *newtuple;
	struct in_addr saddr, daddr;
	uint16_t sport, dport;
	unsigned int saddr_num, daddr_num, sport_num, dport_num;
	unsigned int addr_num, port_num;
	unsigned int tuple_num, n;

	saddr_num = ntohl(saddr_end.s_addr) - ntohl(saddr_begin.s_addr) + 1;
	daddr_num = ntohl(daddr_end.s_addr) - ntohl(daddr_begin.s_addr) + 1;
	sport_num = sport_end - sport_begin+ 1;
	dport_num = dport_end - dport_begin+ 1;

	addr_num = lcm(saddr_num, daddr_num);
	port_num = lcm(sport_num, dport_num);
	tuple_num = lcm(addr_num, port_num);

	if (adrlist->tuple_limit < (adrlist->ntuple + tuple_num)) {
		fprintf(stderr, "too large flowlist: %u: %s-%s:%d-%d - %s-%s:%d-%d\n",
		    adrlist->ntuple + tuple_num,
		    ip4_sprintf(&saddr_begin), ip4_sprintf(&saddr_end),
		    sport_begin, sport_end,
		    ip4_sprintf(&daddr_begin), ip4_sprintf(&daddr_end),
		    dport_begin, dport_end);
		return -1;
	}


	if (adrlist->tuple == NULL) {
		newtuple = malloc(sizeof(struct address_tuple) * tuple_num);
		memset(newtuple, 0, sizeof(struct address_tuple) * tuple_num);
	} else {
		newtuple = realloc(adrlist->tuple, sizeof(struct address_tuple) * (adrlist->ntuple + tuple_num));
		memset(newtuple + adrlist->ntuple, 0, sizeof(struct address_tuple) * tuple_num);
	}

	if (newtuple == NULL) {
		fprintf(stderr, "Cannot allocate memory. number of session is %u\n", adrlist->ntuple + tuple_num);
		return -1;
	}

	adrlist->tuple = newtuple;

	saddr.s_addr = saddr_begin.s_addr;
	daddr.s_addr = daddr_begin.s_addr;
	sport = sport_begin;
	dport = dport_begin;

	for (n = 0; n < tuple_num; ) {
		if (exists_in_addresses(AF_INET, &saddr, adrlist->exclude_saddr, adrlist->exclude_saddr_num) ||
		    exists_in_addresses(AF_INET, &daddr, adrlist->exclude_daddr, adrlist->exclude_daddr_num)) {
			tuple_num--;
		} else {
			newtuple[adrlist->ntuple + n].saddr.af = AF_INET;
			newtuple[adrlist->ntuple + n].saddr.a.addr4.s_addr = saddr.s_addr;
			newtuple[adrlist->ntuple + n].daddr.af = AF_INET;
			newtuple[adrlist->ntuple + n].daddr.a.addr4.s_addr = daddr.s_addr;
			newtuple[adrlist->ntuple + n].sport = sport;
			newtuple[adrlist->ntuple + n].dport = dport;
			newtuple[adrlist->ntuple + n].proto = proto;

			l2random(&newtuple[adrlist->ntuple + n].saddr.a.addr4,
			    sizeof(newtuple[adrlist->ntuple + n].saddr.a.addr4),
			    &newtuple[adrlist->ntuple + n].seaddr);
			l2random(&newtuple[adrlist->ntuple + n].daddr.a.addr4,
			    sizeof(newtuple[adrlist->ntuple + n].daddr.a.addr4),
			    &newtuple[adrlist->ntuple + n].deaddr);

			n++;
		}

		/* increment addresses and ports */
		if (saddr.s_addr == saddr_end.s_addr)
			saddr.s_addr = saddr_begin.s_addr;
		else
			saddr.s_addr = htonl(ntohl(saddr.s_addr) + 1);

		if (daddr.s_addr == daddr_end.s_addr)
			daddr.s_addr = daddr_begin.s_addr;
		else
			daddr.s_addr = htonl(ntohl(daddr.s_addr) + 1);

		if (sport == sport_end)
			sport = sport_begin;
		else
			sport++;

		if (dport == dport_end)
			dport = dport_begin;
		else
			dport++;
	}

	adrlist->ntuple += tuple_num;
	adrlist->sorted = 0;
	return 0;
}
Esempio n. 7
0
	long long multiLCM(vector<Type> data)
	{
		long long lcmVal = data[0];
		for(int i=1; i<data.size(); i++) lcmVal = lcm(lcmVal, data[i]);
		return lcmVal;
	}
Esempio n. 8
0
int start_edf_deadline_main(ALGORITHM_PARAMS parameters)
{

	task_set_t *t = NULL; /* Head of task set's list */
	processor_t *p = NULL; /* Head of processor's list */
	sched_event_t *event = NULL; /* Head of scheduling events list */
	sched_event_t *missed_deadlines = NULL; /* Head of missed deadlines events list */

	int n; /* Number of tasks */
	//int m; /* Number of processors */
	double current_time, max_time;
	float util;


	FILE *in_file; /* Input file */

	int no_proc, i;
	int event_id = 0, deadln_miss_id = 0;
	char line[80]; /* Input line */
	float period, wcet, deadline;
	task_set_t new_task; /* List pointers */
	task_set_t *task_to_execute, *task_in_processor, *task_in_event, *preemptable_task;
	processor_t new_processor;
	sched_event_t new_event;
	processor_t *current_processor, *preemptable_processor;

	int no_task = 0;
#ifdef USE_TRACE_FILE
	////////////// tracer
	int file_id = 0;
	char file_trace[255];
	char basename_trace[255];

	trace_event new_trace_event;
	new_trace_event.next = NULL;
	///////////////////////////////
#endif

	///////////////////////////////////////// checking params
	//if (argc != 3) {
	//	LOG( "\nYou must supply the number of processors, simulation time (0 = lcm) and a file name with the task set parameters (see README file for details)\n");
	//	return -1;
	//}

	no_proc = parameters.processor;//atoi(argv[argid]);
	if (no_proc <= 0) {
		LOG( "Error: number of processor must be > 0 (%s)\n", no_proc);
		return -1;
	}

	max_time = (double) parameters.time;//atoi(argv[argid + 1]);
	if (max_time < 0) {
		LOG( "Error: simulation time must be >= 0 (%s)\n", max_time);
		return -1;
	}

	//in_file = fopen(argv[argid + 2], "r");
	in_file = fopen(parameters.data, "r");
	if (in_file == NULL) {
		LOG( "Error:Unable to open %s file\n", parameters.data);
		return -1;
	}
	/////////////////////////////////////////////////////////////////////////////////////


#ifdef USE_TRACE_FILE
	//get basename used for trace file output
	get_basename(parameters.data, &basename_trace[0]);
#endif

	
	/// Create processor's list
	for (i = 0; i < no_proc; i++) {
		new_processor.id = i;
		new_processor.status = PROCESSOR_IDLE;
		new_processor.u = 0.0;
		new_processor.task = NULL;
		p = add_processor_list(p, new_processor);
	}

	//* Read in data
	n = 0;
	current_time = 0.0;
	event_id = 0;
	while (1) {
		if (fgets(line, sizeof(line), in_file) == NULL)
			break;

		/* read task set parameters from file */
		if (line[0] != '#') {
			sscanf(line, "%f%f%f", &period, &wcet, &deadline);
			/* set task parameters for first activation */
			new_task.id = ++n;
			new_task.t = (double) period;
			new_task.c = (double) wcet;
			new_task.d = (double) deadline;
			new_task.r = current_time;
			new_task.res = NULL;
			new_task.deadline = new_task.r + new_task.d;
			new_task.cet = 0.0;
			new_task.e = -1;
			new_task.p = set_task_edf_deadline_priority(&new_task);
			new_task.state = TASK_READY;
			t = add_task_list_p_sorted(t, new_task);
			
			task_in_event = pointer_to_task(t, new_task.id);
			
			//* add event (task release) to sched events list
			new_event.id = event_id++;
			new_event.t_event = (int) SCHEDE_RELEASE;
			// event.time = task.f;            /* start execution at 0 + task phase */
			new_event.time = current_time;
			new_event.task = task_in_event;
			new_event.p = task_in_event -> p;
			new_event.processor = NULL;
			event = add_sched_event_list_time_sorted(event, new_event);

			no_task++;
		}
	}

	if (!n) {
		LOG( "Error: empty file %s\n", parameters.data);
		return -1;
	}

	//* Get System's Utilization
	util = 0.0;
	task_in_event = t;
	while (task_in_event) {
		util += (float) (task_in_event -> c / task_in_event -> t); /* Ui = Ci/Ti  */
		// LOG("u(%d) = %f\n", task_in_event -> id, (float) (task_in_event -> c/task_in_event -> t));
		task_in_event = (task_set_t *) task_in_event -> next;
	}
	// LOG("\nTotal utilization of task set = %f\n", util);
	// LOG("\nTotal utilization of multiprocessor system = %f\n\n", util/no_proc);


	if (max_time == 0.0) {
		// LOG("Calculating simulation time\n");
		max_time = lcm(t);
		//LOG("Simulation time = [0, %.2f]\n", max_time);
	}

#ifdef USE_TRACE_FILE
	//////////////////////////////
	task_in_event = t;
	while (task_in_event) {

		// add task deadline
		new_trace_event.time = current_time + task_in_event->d;
		new_trace_event.task = task_in_event->id;
		new_trace_event.t_event = DEADLINE_TASK;
		//add finish task
		current_processor = p;
		while (current_processor) {
			/*(trace_event *)*/ current_processor->tracer = (trace_event *) add_trace_event((trace_event *) current_processor->tracer, new_trace_event);
			current_processor = (processor_t *) current_processor->next;
		}
		task_in_event = (task_set_t *) task_in_event -> next;
	}
	for (current_time = 1; current_time <= max_time; current_time++) {
		task_in_event = t;
		while (task_in_event) {
			if (((int) (current_time) % (int) (task_in_event -> t)) == 0) {
				// add task period
				new_trace_event.time = (int) current_time;
				new_trace_event.task = task_in_event->id;
				new_trace_event.t_event = PERIOD_TASK;
				//add finish task
				current_processor = p;
				while (current_processor) {
					/*(trace_event *) */current_processor->tracer = (trace_event *) add_trace_event((trace_event *) current_processor->tracer, new_trace_event);
					current_processor = (processor_t *) current_processor->next;
				}
				// add task deadline
				new_trace_event.time = current_time + task_in_event-> d;
				new_trace_event.task = task_in_event->id;
				new_trace_event.t_event = DEADLINE_TASK;
				//add finish task
				current_processor = p;
				while (current_processor) {
					/*(trace_event *)*/ current_processor->tracer = (trace_event *) add_trace_event((trace_event *) current_processor->tracer, new_trace_event);
					current_processor = (processor_t *) current_processor->next;
				}
			}

			task_in_event = (task_set_t *) task_in_event -> next;
		}
	}
	///////////////////////////////////////
#endif

	/*
	   Start scheduling task set on no_proc processors
	 */
	if (event) {
		task_in_event = event -> task;
		current_time = event -> time;
	}

	while ((event) && (current_time <= max_time)) {

		//if(previous_time != current_time)
		LOG("\n================= Time %.2f ==============\n", current_time);
		switch (event->t_event) {

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//										TASK START/RESUME
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		case SCHEDE_RELEASE: /* new task is released, try to assign it to a processor */
			LOG("Event: Release task %d\n", task_in_event->id);
#ifdef USE_TRACE_FILE
			////////////////////// print activate task
			current_processor = p;
			while (current_processor) {
				new_trace_event.task = task_in_event->id;
				new_trace_event.time = (int) current_time;
				new_trace_event.t_event = ACTIVATE_TASK;
				/*(trace_event *)*/ current_processor->tracer = (trace_event *) add_trace_event((trace_event *) current_processor->tracer, new_trace_event);
				current_processor = (processor_t *) current_processor->next;
			}
			///////////////////////////////////////
#endif

			// search an IDLE processor
			current_processor = p;
			task_in_processor = current_processor -> task;
			while ((current_processor) && (current_processor -> status != PROCESSOR_IDLE)) {
				current_processor = (processor_t *) current_processor -> next;
				if (current_processor)
					task_in_processor = current_processor -> task;
			}
			///////////////////////////////////////
			//if IDLE processor found
			if ((current_processor) && (current_processor->status == PROCESSOR_IDLE)) {
				// idle processors found	Active the current task	/////////////////////////////////
				// add FINISH event for task	/////////////////////////////////////////////////////
				new_event.id = event_id++;
				new_event.t_event = (int) SCHEDE_FINISH;
				new_event.time = current_time + task_in_event -> c;
				new_event.task = task_in_event;
				new_event.p = event -> p;
				new_event.processor = current_processor;
				event = add_sched_event_list_time_sorted(event, new_event);
				/////////////////////////////////////////////////////////////////////////////////////
				task_in_event -> e = current_time;

				// set Task to process task is now running
				assign_task_to_processor(current_processor, task_in_event, current_time);
				LOG("|_ Task %d is now executing on processor %d\n", task_in_event->id, current_processor->id);

#ifdef USE_TRACE_FILE				
				/// Print task execute
				new_trace_event.task = new_event.task->id;
				new_trace_event.time = (int) current_time;
				new_trace_event.t_event = EXECUTE_TASK;
				/*(trace_event *) */current_processor->tracer = (trace_event *) add_trace_event((trace_event *) current_processor->tracer, new_trace_event);
				//////////////////////////////////////////////
#endif
				//print task active
				// getchar();

			} else {
				// NO IDLE processor found

				// Search for one task in processor less prioritary ////////////////////////////////////////////////////////////
				preemptable_task = NULL;
				current_processor = p;
				task_in_processor = current_processor -> task;
				while (current_processor) {
					if ((current_processor->status == PROCESSOR_BUSY) && (event -> p < task_in_processor -> p)) {
						if (!preemptable_task) {
							preemptable_task = current_processor -> task;
							preemptable_processor = current_processor;
						} else {
							if (preemptable_task -> p < task_in_processor -> p) {
								preemptable_task = task_in_processor;
								preemptable_processor = current_processor;
							}
						}
					}
					current_processor = (processor_t *) current_processor -> next;
					if (current_processor) {
						task_in_processor = current_processor -> task;
					}
				}
				//////////////////////////////////////////////////////////////////////////////////////////////////////////////
				// IF one task less prioritary found
				if (preemptable_task) {

					current_processor = preemptable_processor;

					/// Update information for task in processor before paused
					task_in_processor = preemptable_task;
					new_event.time = task_in_processor -> e + task_in_processor -> c - task_in_processor -> cet;
					task_in_processor -> cet += current_time - task_in_processor -> e;
					
					task_in_processor -> state = TASK_READY;
					/* delerte finish event of preempted task */
					// LOG("delete finish event for preempted task\n");
					LOG("|_ Removing task %d, from processor %d\n", task_in_processor->id, current_processor->id);

					// Delete schedule FINISH event	/////////////////////////////////
					new_event.task = task_in_processor;
					new_event.t_event = SCHEDE_FINISH;
					if (is_event_in_list(event, &new_event, &i)) {
						event = del_sched_event_from_list(event, i);
					
					}

#ifdef USE_TRACE_FILE
					//////////////////////////////// add suspend task
					new_trace_event.task = task_in_processor->id;
					new_trace_event.time = (int) current_time;
					new_trace_event.t_event = SUSPEND_TASK;
					/*(trace_event *)*/ current_processor->tracer =(trace_event *)  add_trace_event((trace_event *) current_processor->tracer, new_trace_event);
					//////////////////////////////////////////////////
#endif

					// ADD schedule FINISH event for new task	/////////////////////////////////
					new_event.id = event_id++;
					new_event.t_event = (int) SCHEDE_FINISH;
					new_event.time = current_time + task_in_event -> c;
					new_event.task = task_in_event;
					new_event.p = event -> p;
					new_event.processor = current_processor;
					event = add_sched_event_list_time_sorted(event, new_event);
					//LOG("\nDefining new event FINISH task %d at time %.2f\n", task_in_event -> id, new_event.time);

#ifdef USE_TRACE_FILE
					//////////////////////////// deadline task and execute task
					new_trace_event.task = task_in_event->id;
					new_trace_event.time = (int) current_time;
					new_trace_event.t_event = EXECUTE_TASK;
					/*(trace_event *)*/ current_processor->tracer = (trace_event *) add_trace_event((trace_event *) current_processor->tracer, new_trace_event);
					////////////////////////////////////////////////////
#endif
					// Asign new task to processor
					assign_task_to_processor(current_processor, task_in_event, current_time);

					LOG("|_ Task %d is now executing on processor %d\n", task_in_event->id, current_processor->id);


				} else { // Task less prioritary NOT FOUND, set this task in ready state, set execute time to 0
					task_in_event -> state = (int) TASK_READY;
					task_in_event -> cet = 0.0;
				}
			}
			break;
			///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
			//										TASK END
			///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		case SCHEDE_FINISH:
			
			current_processor = event -> processor;
			LOG("Event: Finish task %d\n", task_in_event->id);
			/* check if task finished by its deadline */
			if (current_time > task_in_event -> deadline) { /* deadline miseed, thus generate event */

				LOG("|_ **Task deadline missed\n");
				//print task fail
				new_event.id = deadln_miss_id++;
				new_event.t_event = (int) SCHEDE_DEADLN_MISS;
				new_event.time = current_time;
				new_event.p = 0;
				new_event.task = task_in_event;
				missed_deadlines = add_sched_event_list_time_sorted(missed_deadlines, new_event);

#ifdef USE_TRACE_FILE
				/////////////////////////////////// add tracer fail task
				new_trace_event.task = task_in_event -> id;
				new_trace_event.time = (int) new_event.time;
				new_trace_event.t_event = FAIL_TASK;
				/*(trace_event *)*/ current_processor->tracer = (trace_event *) add_trace_event((trace_event *) current_processor->tracer, new_trace_event);
				/////////////////////////////////////////////////////

#ifdef END_ON_MISS_DEADLINE
				///////////////////// print trace to file
				current_processor = p;
				while (current_processor) {
					file_id++;
					//print_trace_list(current_processor->tracer);
					sprintf(file_trace, "%s_p%d.ktr", &basename_trace[0], file_id);
					create_trace_list(file_trace, current_processor->tracer, no_task, current_time, (char *) "EDF with Deadlines");
					current_processor = current_processor->next;

				}
				current_processor = event -> processor;

#endif
				////////////////////////////////////////////////////////
#endif
#ifdef END_ON_MISS_DEADLINE
				LOG("Not Scheduled by edf: %d", 0);
				return 0;
#endif
			}
			/* set task parameters for next activation */
			task_in_event->r += task_in_event -> t;
			task_in_event->deadline = task_in_event -> r + task_in_event -> d;
			task_in_event->cet = 0.0;
			task_in_event->e = -1;
			task_in_event->state = (int) TASK_READY;
			task_in_event->p = set_task_edf_priority(task_in_event);
			/* add event (task release) for next task activation (since current activation has finished */
			new_event.id = event_id++;
			new_event.t_event = (int) SCHEDE_RELEASE;
			new_event.time = task_in_event -> r;
			new_event.task = task_in_event;
			new_event.p = task_in_event -> p;
			new_event.processor = NULL;
			event = add_sched_event_list_time_sorted(event, new_event);

			//print new activate
			//LOG("\nDefining new event RELEASE task %d at time %.2f\n", task_in_event -> id, new_event.time);
			// getchar();

#ifdef USE_TRACE_FILE
			////////////////////////////// add end task on tracer
			new_trace_event.task = task_in_event->id;
			new_trace_event.time = (int) current_time;
			new_trace_event.t_event = END_TASK;
			/*(trace_event *)*/ current_processor->tracer = (trace_event *) add_trace_event((trace_event *) current_processor->tracer, new_trace_event);
			//////////////////////////////
#endif


			//LOG("check if there is a task in ready state elegible to execute at time %.2f\n", current_time);
			task_to_execute = find_task_to_execute(t, event -> time);
			if (task_to_execute) {

				//print task to execute
				//LOG("task %d found with release time %.2f and cet %.2f to be executed\n", task_to_execute -> id, task_to_execute -> r, task_to_execute -> cet);
				// getchar();
				/* check if the release event for this task is in event list (i.e., if release time = current_time */
				if (task_to_execute -> r == current_time) {
					// LOG("checking for release event for task %d in event list at time %.2f\n", task_to_execute -> id, current_time);
					new_event.time = current_time;
					new_event.task = task_to_execute;
					new_event.t_event = SCHEDE_RELEASE;
					if (is_event_in_list(event, &new_event, &i)) {
						event = del_sched_event_from_list(event, i);
					}
				}

				new_event.id = event_id++;
				new_event.t_event = (int) SCHEDE_FINISH;
				new_event.time = current_time + (task_to_execute -> c - task_to_execute -> cet);
				new_event.task = task_to_execute;
				new_event.p = task_to_execute -> p;
				new_event.processor = current_processor;
				event = add_sched_event_list_time_sorted(event, new_event);
				// LOG("\nDefining new event FINISH task %d at time %.2f\n", task_to_execute -> id, new_event.time);
				// getchar();
				assign_task_to_processor(current_processor, task_to_execute, current_time);
				task_to_execute -> e = current_time;
				task_to_execute -> state = (int) TASK_RUNNING;
				LOG("|_ Task %d is now executing on processor %d\n", task_to_execute->id, current_processor->id);

#ifdef USE_TRACE_FILE
				/////////////////////////////////// add tracer deadline and execute
				new_trace_event.task = task_to_execute->id;
				new_trace_event.time = (int) current_time;
				new_trace_event.t_event = EXECUTE_TASK;
				/*(trace_event *)*/ current_processor->tracer = (trace_event *) add_trace_event((trace_event *) current_processor->tracer, new_trace_event);
				///////////////////////////////////
#endif
				// getchar();

			} else {
				/* no task to execute found, set processor to idle state */
				LOG("|_ No task in wait queue found, set processor %d to idle state\n", current_processor -> id);
				current_processor -> status = PROCESSOR_IDLE;
				current_processor -> task = NULL;
			}
			break;
		}
		/*
			  if(event->event >= SCHEDE_RELEASE && event->event <= SCHEDE_DEADLN_MISS)
				eventLog = add_sched_event_list(eventLog, *event);*/
		event = del_sched_event_head_list(event);
		if (event) {
			task_in_event = event -> task;
			current_time = event -> time;
		}
	}

	LOG("\nScheduled by edf using: \n\nNo. of processors: %d", no_proc);
	LOG("\nSimulation time = [0, %.2f]\n", max_time);
#ifdef USE_TRACE_FILE
	///////////////////// print trace to file
	current_processor = p;
	while (current_processor) {
		file_id++;
		LOG("\nProcessor %d: U = %f", file_id, current_processor->u);
		//print_trace_list((trace_event *)current_processor->tracer);
		sprintf(file_trace, "%s_p%d.ktr", &basename_trace[0], file_id);
		create_trace_list(file_trace, (trace_event *) current_processor->tracer, no_task, (int) max_time, (char *) "EDF with Deadlines");
		current_processor = (processor_t *) current_processor->next;

	}
	////////////////////////////////////////////////////////
#endif

	//LOG("Scheduling activities finished at current time = %.2f\n", current_time);
	return(no_proc);
}
Esempio n. 9
0
int
stp_curve_compose(stp_curve_t **retval,
		  stp_curve_t *a, stp_curve_t *b,
		  stp_curve_compose_t mode, int points)
{
  stp_curve_t *ret;
  double *tmp_data;
  double gamma_a = stp_curve_get_gamma(a);
  double gamma_b = stp_curve_get_gamma(b);
  unsigned points_a = stp_curve_count_points(a);
  unsigned points_b = stp_curve_count_points(b);
  double alo, ahi, blo, bhi;

  if (a->piecewise && b->piecewise)
    return 0;
  if (a->piecewise)
    {
      stp_curve_t *a_save = a;
      a = stp_curve_create_copy(a_save);
      stp_curve_resample(a, stp_curve_count_points(b));
    }
  if (b->piecewise)
    {
      stp_curve_t *b_save = b;
      b = stp_curve_create_copy(b_save);
      stp_curve_resample(b, stp_curve_count_points(a));
    }

  if (mode != STP_CURVE_COMPOSE_ADD && mode != STP_CURVE_COMPOSE_MULTIPLY)
    return 0;
  if (stp_curve_get_wrap(a) != stp_curve_get_wrap(b))
    return 0;
  stp_curve_get_bounds(a, &alo, &ahi);
  stp_curve_get_bounds(b, &blo, &bhi);
  if (mode == STP_CURVE_COMPOSE_MULTIPLY && (alo < 0 || blo < 0))
    return 0;

  if (stp_curve_get_wrap(a) == STP_CURVE_WRAP_AROUND)
    {
      points_a++;
      points_b++;
    }
  if (points == -1)
    {
      points = lcm(points_a, points_b);
      if (stp_curve_get_wrap(a) == STP_CURVE_WRAP_AROUND)
	points--;
    }
  if (points < 2 || points > curve_point_limit ||
      ((stp_curve_get_wrap(a) == STP_CURVE_WRAP_AROUND) &&
       points > curve_point_limit - 1))
    return 0;

  if (gamma_a && gamma_b && gamma_a * gamma_b > 0 &&
      mode == STP_CURVE_COMPOSE_MULTIPLY)
    return create_gamma_curve(retval, alo * blo, ahi * bhi, gamma_a + gamma_b,
			      points);
  tmp_data = stp_malloc(sizeof(double) * points);
  if (!interpolate_points(a, b, mode, points, tmp_data))
    {
      stp_free(tmp_data);
      return 0;
    }
  ret = stp_curve_create(stp_curve_get_wrap(a));
  if (mode == STP_CURVE_COMPOSE_ADD)
    {
      stp_curve_rescale(ret, (ahi - alo) + (bhi - blo),
			STP_CURVE_COMPOSE_MULTIPLY, STP_CURVE_BOUNDS_RESCALE);
      stp_curve_rescale(ret, alo + blo,
			STP_CURVE_COMPOSE_ADD, STP_CURVE_BOUNDS_RESCALE);
    }
  else
    {
      stp_curve_rescale(ret, (ahi - alo) * (bhi - blo),
			STP_CURVE_COMPOSE_MULTIPLY, STP_CURVE_BOUNDS_RESCALE);
      stp_curve_rescale(ret, alo * blo,
			STP_CURVE_COMPOSE_ADD, STP_CURVE_BOUNDS_RESCALE);
    }
  if (! stp_curve_set_data(ret, points, tmp_data))
    goto bad1;
  *retval = ret;
  stp_free(tmp_data);
  return 1;
 bad1:
  stp_curve_destroy(ret);
  stp_free(tmp_data);
  return 0;
}
Esempio n. 10
0
int main() {
    int id, sarn, sacn, sbcn, sbrn, LCM, t, i, j, l, jp, ip, local_block;
    double t1, t2;
    Matrix A, B, C, // global matrices
           sa, sb, sc, //local matrices of the process
           subsa, subsb, subsc; //local submatrices of the process
    
    create_matrix(&A, A_RN, A_CN);
    create_matrix(&B, B_RN, B_CN);
    create_matrix(&C, A_RN, B_CN);

    populate_matrix(&A);
    populate_matrix(&B);

    //printf("\nMatrices generadas\n");
    //print_matrix(&A, 'A');
    //printf("\n");
    //print_matrix(&B, 'B');

    //submatrices sizes
    sarn = (A_RN / M) * (M / P);
    sacn = (A_CN / K) * (K / Q);
    sbrn = (B_RN / K) * (K / P);
    sbcn = (B_CN / N) * (N / Q);
    
    local_block =  BLOCK_SZ;
    
    LCM = lcm(P, Q);
    shift_matrix_left(&A, BLOCK_SZ, 1);
    shift_matrix_up(&B, BLOCK_SZ, 1);

    t1 = omp_get_wtime();
    #pragma omp parallel default(none) shared(A, B, C, sarn, sacn, sbrn, sbcn, LCM, local_block) \
                                       private(sa, sb, sc, id, t, i, j, l, jp, ip, subsa, subsb, subsc) num_threads(P * Q)
    {
        id = omp_get_thread_num();

        create_matrix(&sa, sarn, sacn);
        create_matrix(&sb, sbrn, sbcn);
        create_matrix(&sc, sarn, sbcn);
        
        for(t = 0; t < LCM; t++){
            
            create_matrix(&subsa, local_block, local_block);
            create_matrix(&subsb, local_block, local_block);
            create_matrix(&subsc, local_block, local_block);
            
            rsync_process_blocks(&A, &sa, id, FALSE);
            rsync_process_blocks(&B, &sb, id, FALSE);
            
            for(i = 0; i < (M / P); i++){
                for(j = 0; j < (N / Q); j++){
                    for(l = 0; l < (K / LCM); l++){
                        jp = (j % K + l * LCM / Q) % (K / Q);
                        ip = (i % K + l * LCM / P) % (K / P);

                        rsync_process_submatrix(&sc, &subsc, i, j, FALSE);
                        rsync_process_submatrix(&sa, &subsa, i, jp, FALSE);
                        rsync_process_submatrix(&sb, &subsb, ip, j, FALSE);
                        
                        matrix_product(&subsc, &subsa, &subsb);

                        rsync_process_submatrix(&sc, &subsc, i, j, TRUE);
                    }
                }
            }
            
            rsync_process_blocks(&C, &sc, id, TRUE);
            
            #pragma omp barrier

            #pragma omp single
            {
                shift_matrix_left(&A, BLOCK_SZ, 0);
                shift_matrix_up(&B, BLOCK_SZ, 0);
            }
        }
    }
    t2 = omp_get_wtime();

    printf("\nResultado\n");
    //print_matrix(&C, 'C');
    printf("\nTiempo: %.4f segundos\n", (t2 - t1));

    return 0;
}
Esempio n. 11
0
stfio::filetype stfio_file_type(HDRTYPE* hdr) {
#ifdef __LIBBIOSIG2_H__
        switch (biosig_get_filetype(hdr)) {
#else
        switch (hdr->TYPE) {
#endif

#if (BIOSIG_VERSION > 10500)
        case ABF2:	return stfio::abf;
#endif
        case ABF:	return stfio::abf;
        case ATF:	return stfio::atf;
        case CFS:	return stfio::cfs;
        case HEKA:	return stfio::heka;
        case HDF:	return stfio::hdf5;
#if (BIOSIG_VERSION > 10403)
        case AXG:	return stfio::axg;
        case IBW:	return stfio::igor;
        case SMR:	return stfio::son;
#endif
        default:	return stfio::none;
        }
}

#if (defined(WITH_BIOSIG) || defined(WITH_BIOSIG2))
bool stfio::check_biosig_version(int a, int b, int c) {
	return (BIOSIG_VERSION >= 10000*a + 100*b + c);
}
#endif

stfio::filetype stfio::importBiosigFile(const std::string &fName, Recording &ReturnData, ProgressInfo& progDlg) {

    std::string errorMsg("Exception while calling std::importBSFile():\n");
    std::string yunits;
    stfio::filetype type;

    // =====================================================================================================================
    //
    // importBiosig opens file with libbiosig
    //	- performs an automated identification of the file format
    //  - and decides whether the data is imported through importBiosig (currently CFS, HEKA, ABF1, GDF, and others)
    //  - or handed back to other import*File functions (currently ABF2, AXG, HDF5)
    //
    // There are two implementations, level-1 and level-2 interface of libbiosig.
    //   level 1 is used when -DWITH_BIOSIG, -lbiosig
    //   level 2 is used when -DWITH_BIOSIG2, -lbiosig2
    //
    //   level 1 is better tested, but it does not provide ABI compatibility between MinGW and VisualStudio
    //   level 2 interface has been developed to provide ABI compatibility, but it is less tested
    //      and the API might still undergo major changes.
    // =====================================================================================================================


#ifdef __LIBBIOSIG2_H__

    HDRTYPE* hdr =  sopen( fName.c_str(), "r", NULL );
    if (hdr==NULL) {
        ReturnData.resize(0);
        return stfio::none;
    }

    type = stfio_file_type(hdr);
    if (biosig_check_error(hdr)) {
        ReturnData.resize(0);
        destructHDR(hdr);
        return type;
    }
    enum FileFormat biosig_filetype=biosig_get_filetype(hdr);
    if (biosig_filetype==ATF || biosig_filetype==ABF2 || biosig_filetype==HDF ) {
        // ATF, ABF2 and HDF5 support should be handled by importATF, and importABF, and importHDF5 not importBiosig
        ReturnData.resize(0);
        destructHDR(hdr);
        return type;
    }

    // earlier versions of biosig support only the file type identification, but did not properly read the files
    if ( (BIOSIG_VERSION < 10603)
      && (biosig_filetype==AXG)
       ) {
        ReturnData.resize(0);
        destructHDR(hdr);
        return type;
    }

    // ensure the event table is in chronological order	
    sort_eventtable(hdr);

    // allocate local memory for intermediate results;
    const int strSize=100;
    char str[strSize];

    /*
	count sections and generate list of indices indicating start and end of sweeps
     */	

    double fs = biosig_get_eventtable_samplerate(hdr);
    size_t numberOfEvents = biosig_get_number_of_events(hdr);
    size_t nsections = biosig_get_number_of_segments(hdr);
    size_t *SegIndexList = (size_t*)malloc((nsections+1)*sizeof(size_t));
    SegIndexList[0] = 0;
    SegIndexList[nsections] = biosig_get_number_of_samples(hdr);
    std::string annotationTableDesc = std::string();
    for (size_t k=0, n=0; k < numberOfEvents; k++) {
        uint32_t pos;
        uint16_t typ;
#if BIOSIG_VERSION < 10605
        char *desc;
#else
        const char *desc;
#endif
        /*
        uint32_t dur;
        uint16_t chn;
        gdftype  timestamp;
        */

        biosig_get_nth_event(hdr, k, &typ, &pos, NULL, NULL, NULL, &desc);

        if (typ == 0x7ffe) {
            SegIndexList[++n] = pos;
        }
        else if (typ < 256) {
            sprintf(str,"%f s:\t%s\n", pos/fs, desc);
            annotationTableDesc += std::string( str );
        }
    }
    int numberOfChannels = biosig_get_number_of_channels(hdr);

    /*************************************************************************
        rescale data to mV and pA
     *************************************************************************/
    for (int ch=0; ch < numberOfChannels; ++ch) {
        CHANNEL_TYPE *hc = biosig_get_channel(hdr, ch);
        switch (biosig_channel_get_physdimcode(hc) & 0xffe0) {
        case 4256:  // Volt
		//biosig_channel_scale_to_unit(hc, "mV");
		biosig_channel_change_scale_to_physdimcode(hc, 4274);
		break;
        case 4160:  // Ampere
		//biosig_channel_scale_to_unit(hc, "pA");
		biosig_channel_change_scale_to_physdimcode(hc, 4181);
		break;
	    }
    }

    /*************************************************************************
        read bulk data
     *************************************************************************/
    biosig_data_type *data = biosig_get_data(hdr, 0);
    size_t SPR = biosig_get_number_of_samples(hdr);

#ifdef _STFDEBUG
    std::cout << "Number of events: " << numberOfEvents << std::endl;
    /*int res = */ hdr2ascii(hdr, stdout, 4);
#endif

    for (int NS=0; NS < numberOfChannels; ) {
        CHANNEL_TYPE *hc = biosig_get_channel(hdr, NS);
        Channel TempChannel(nsections);
        TempChannel.SetChannelName(biosig_channel_get_label(hc));
        TempChannel.SetYUnits(biosig_channel_get_physdim(hc));

        for (size_t ns=1; ns<=nsections; ns++) {
	        size_t SPS = SegIndexList[ns]-SegIndexList[ns-1];	// length of segment, samples per segment

		int progbar = int(100.0*(1.0*ns/nsections + NS)/numberOfChannels);
		std::ostringstream progStr;
		progStr << "Reading channel #" << NS + 1 << " of " << numberOfChannels
			<< ", Section #" << ns << " of " << nsections;
		progDlg.Update(progbar, progStr.str());

		/* unused //
		char sweepname[20];
		sprintf(sweepname,"sweep %i",(int)ns);
		*/
		Section TempSection(
                                SPS, // TODO: hdr->nsamplingpoints[nc][ns]
                                "" // TODO: hdr->sectionname[nc][ns]
        );

		std::copy(&(data[NS*SPR + SegIndexList[ns-1]]),
			  &(data[NS*SPR + SegIndexList[ns]]),
			  TempSection.get_w().begin() );

        try {
            TempChannel.InsertSection(TempSection, ns-1);
        }
        catch (...) {
			ReturnData.resize(0);
			destructHDR(hdr);
			return type;
		}
	}
    try {
        if ((int)ReturnData.size() < numberOfChannels) {
            ReturnData.resize(numberOfChannels);
		}
		ReturnData.InsertChannel(TempChannel, NS++);
    }
    catch (...) {
		ReturnData.resize(0);
		destructHDR(hdr);
		return type;
        }
    }

    free(SegIndexList);

    ReturnData.SetComment ( biosig_get_recording_id(hdr) );

    sprintf(str,"v%i.%i.%i (compiled on %s %s)",BIOSIG_VERSION_MAJOR,BIOSIG_VERSION_MINOR,BIOSIG_PATCHLEVEL,__DATE__,__TIME__);
    std::string Desc = std::string("importBiosig with libbiosig ")+std::string(str) + " ";

    const char* tmpstr;
    if ((tmpstr=biosig_get_technician(hdr)))
            Desc += std::string ("\nTechnician:\t") + std::string (tmpstr) + " ";
    Desc += std::string( "\nCreated with: ");
    if ((tmpstr=biosig_get_manufacturer_name(hdr)))
        Desc += std::string( tmpstr ) + " ";
    if ((tmpstr=biosig_get_manufacturer_model(hdr)))
        Desc += std::string( tmpstr ) + " ";
    if ((tmpstr=biosig_get_manufacturer_version(hdr)))
        Desc += std::string( tmpstr ) + " ";
    if ((tmpstr=biosig_get_manufacturer_serial_number(hdr)))
        Desc += std::string( tmpstr ) + " ";

    Desc += std::string ("\nUser specified Annotations:\n")+annotationTableDesc;

    ReturnData.SetFileDescription(Desc);

#if (BIOSIG_VERSION > 10509)
    tmpstr = biosig_get_application_specific_information(hdr);
    if (tmpstr != NULL) /* MSVC2008 can not properly handle std::string( (char*)NULL ) */
        ReturnData.SetGlobalSectionDescription(tmpstr);
#endif

    ReturnData.SetXScale(1000.0/biosig_get_samplerate(hdr));
    ReturnData.SetXUnits("ms");
    ReturnData.SetScaling("biosig scaling factor");

    /*************************************************************************
        Date and time conversion
     *************************************************************************/
    struct tm T;
    biosig_get_startdatetime(hdr, &T);
    ReturnData.SetDateTime(T);

    destructHDR(hdr);


#else  // #ifndef __LIBBIOSIG2_H__


    HDRTYPE* hdr =  sopen( fName.c_str(), "r", NULL );
    if (hdr==NULL) {
        ReturnData.resize(0);
        return stfio::none;
    }
    type = stfio_file_type(hdr);

#if !defined(BIOSIG_VERSION) || (BIOSIG_VERSION < 10501)
    if (hdr->TYPE==ABF) {
        /*
           biosig v1.5.0 and earlier does not always return
           with a proper error message for ABF files.
           This causes problems with the ABF fallback mechanism
        */
#else
    if ( hdr->TYPE==ABF2 ) {
        // ABF2 support should be handled by importABF not importBiosig
        ReturnData.resize(0);
        destructHDR(hdr);
        return type;
    }
    if (hdr->TYPE==ABF && hdr->AS.B4C_ERRNUM) {
        /* this triggers the fall back mechanims w/o reporting an error message */
#endif
        ReturnData.resize(0);
        destructHDR(hdr);	// free allocated memory
        return type;
    }

#if defined(BIOSIG_VERSION) && (BIOSIG_VERSION > 10400)
    if (hdr->AS.B4C_ERRNUM) {
#else
    if (B4C_ERRNUM) {
#endif
        ReturnData.resize(0);
        destructHDR(hdr);	// free allocated memory
        return type;
    }
    if ( hdr->TYPE==ATF || hdr->TYPE==HDF) {
        // ATF, HDF5 support should be handled by importATF and importHDF5 not importBiosig
        ReturnData.resize(0);
        destructHDR(hdr);
        return type;
    }

    // earlier versions of biosig support only the file type identification, but did not read AXG files
#if defined(BIOSIG_VERSION) && (BIOSIG_VERSION > 10403)
    if ( (BIOSIG_VERSION < 10600)
         && (hdr->TYPE==AXG)
       ) {
        // biosig's AXG import crashes on Windows at this time
        ReturnData.resize(0);
        destructHDR(hdr);
        return type;
    }
#endif
    
    // ensure the event table is in chronological order
    sort_eventtable(hdr);

    // allocate local memory for intermediate results;
    const int strSize=100;
    char str[strSize];

    /*
	count sections and generate list of indices indicating start and end of sweeps
     */
    size_t numberOfEvents = hdr->EVENT.N;
    size_t LenIndexList = 256;
    if (LenIndexList > numberOfEvents) LenIndexList = numberOfEvents + 2;
    size_t *SegIndexList = (size_t*)malloc(LenIndexList*sizeof(size_t));
    uint32_t nsections = 0;
    SegIndexList[nsections] = 0;
    size_t MaxSectionLength = 0;
    for (size_t k=0; k <= numberOfEvents; k++) {
        if (LenIndexList <= nsections+2) {
            // allocate more memory as needed
		    LenIndexList *=2;
		    SegIndexList = (size_t*)realloc(SegIndexList, LenIndexList*sizeof(size_t));
	    }
        /*
            count number of sections and stores it in nsections;
            EVENT.TYP==0x7ffe indicate number of breaks between sweeps
	        SegIndexList includes index to first sample and index to last sample,
	        thus, the effective length of SegIndexList is the number of 0x7ffe plus two.
	    */
        if (0)                              ;
        else if (k >= hdr->EVENT.N)         SegIndexList[++nsections] = hdr->NRec*hdr->SPR;
        else if (hdr->EVENT.TYP[k]==0x7ffe) SegIndexList[++nsections] = hdr->EVENT.POS[k];
        else                                continue;

        size_t SPS = SegIndexList[nsections]-SegIndexList[nsections-1];	// length of segment, samples per segment
	    if (MaxSectionLength < SPS) MaxSectionLength = SPS;
    }

    int numberOfChannels = 0;
    for (int k=0; k < hdr->NS; k++)
        if (hdr->CHANNEL[k].OnOff==1)
            numberOfChannels++;

    /*************************************************************************
        rescale data to mV and pA
     *************************************************************************/    
    for (int ch=0; ch < hdr->NS; ++ch) {
        CHANNEL_TYPE *hc = hdr->CHANNEL+ch;
        if (hc->OnOff != 1) continue;
        double scale = PhysDimScale(hc->PhysDimCode); 
        switch (hc->PhysDimCode & 0xffe0) {
        case 4256:  // Volt
                hc->PhysDimCode = 4274; // = PhysDimCode("mV");
                scale *=1e3;   // V->mV
                hc->PhysMax *= scale;         
                hc->PhysMin *= scale;         
                hc->Cal *= scale;         
                hc->Off *= scale;         
                break; 
        case 4160:  // Ampere
                hc->PhysDimCode = 4181; // = PhysDimCode("pA");
                scale *=1e12;   // A->pA
                hc->PhysMax *= scale;         
                hc->PhysMin *= scale;         
                hc->Cal *= scale;         
                hc->Off *= scale;         
                break; 
        }     
    }

    /*************************************************************************
        read bulk data 
     *************************************************************************/    
    hdr->FLAG.ROW_BASED_CHANNELS = 0;
    /* size_t blks = */ sread(NULL, 0, hdr->NRec, hdr);
    biosig_data_type *data = hdr->data.block;
    size_t SPR = hdr->NRec*hdr->SPR;

#ifdef _STFDEBUG
    std::cout << "Number of events: " << numberOfEvents << std::endl;
    /*int res = */ hdr2ascii(hdr, stdout, 4);
#endif

    int NS = 0;   // number of non-empty channels
    for (size_t nc=0; nc < hdr->NS; ++nc) {

        if (hdr->CHANNEL[nc].OnOff == 0) continue;

        Channel TempChannel(nsections);
        TempChannel.SetChannelName(hdr->CHANNEL[nc].Label);
#if defined(BIOSIG_VERSION) && (BIOSIG_VERSION > 10301)
        TempChannel.SetYUnits(PhysDim3(hdr->CHANNEL[nc].PhysDimCode));
#else
        PhysDim(hdr->CHANNEL[nc].PhysDimCode,str);
        TempChannel.SetYUnits(str);
#endif

        for (size_t ns=1; ns<=nsections; ns++) {
	        size_t SPS = SegIndexList[ns]-SegIndexList[ns-1];	// length of segment, samples per segment

		int progbar = 100.0*(1.0*ns/nsections + NS)/numberOfChannels;
		std::ostringstream progStr;
		progStr << "Reading channel #" << NS + 1 << " of " << numberOfChannels
			<< ", Section #" << ns << " of " << nsections;
		progDlg.Update(progbar, progStr.str());

		/* unused //
		char sweepname[20];
		sprintf(sweepname,"sweep %i",(int)ns);		
		*/
		Section TempSection(
                                SPS, // TODO: hdr->nsamplingpoints[nc][ns]
                                "" // TODO: hdr->sectionname[nc][ns]
            	);

		std::copy(&(data[NS*SPR + SegIndexList[ns-1]]),
			  &(data[NS*SPR + SegIndexList[ns]]),
			  TempSection.get_w().begin() );

        try {
            TempChannel.InsertSection(TempSection, ns-1);
        }
        catch (...) {
			ReturnData.resize(0);
			destructHDR(hdr);
			return type;
		}
	}        
    try {
        if ((int)ReturnData.size() < numberOfChannels) {
            ReturnData.resize(numberOfChannels);
        }
        ReturnData.InsertChannel(TempChannel, NS++);
    }
    catch (...) {
		ReturnData.resize(0);
		destructHDR(hdr);
		return type;
        }
    }

    free(SegIndexList); 	

    ReturnData.SetComment ( hdr->ID.Recording );

    sprintf(str,"v%i.%i.%i (compiled on %s %s)",BIOSIG_VERSION_MAJOR,BIOSIG_VERSION_MINOR,BIOSIG_PATCHLEVEL,__DATE__,__TIME__);
    std::string Desc = std::string("importBiosig with libbiosig ")+std::string(str);

    if (hdr->ID.Technician)
            Desc += std::string ("\nTechnician:\t") + std::string (hdr->ID.Technician);
    Desc += std::string( "\nCreated with: ");
    if (hdr->ID.Manufacturer.Name)
        Desc += std::string( hdr->ID.Manufacturer.Name );
    if (hdr->ID.Manufacturer.Model)
        Desc += std::string( hdr->ID.Manufacturer.Model );
    if (hdr->ID.Manufacturer.Version)
        Desc += std::string( hdr->ID.Manufacturer.Version );
    if (hdr->ID.Manufacturer.SerialNumber)
        Desc += std::string( hdr->ID.Manufacturer.SerialNumber );

    Desc += std::string ("\nUser specified Annotations:\n");
    for (size_t k=0; k < numberOfEvents; k++) {
        if (hdr->EVENT.TYP[k] < 256) {
            sprintf(str,"%f s:\t",hdr->EVENT.POS[k]/hdr->EVENT.SampleRate);
            Desc += std::string( str );
            Desc += std::string( hdr->EVENT.CodeDesc[hdr->EVENT.TYP[k]] ) + "\n";
        }
    }
    ReturnData.SetFileDescription(Desc);
    // hdr->AS.bci2000 is an alias to hdr->AS.fpulse, which available only in libbiosig v1.6.0 or later

    if (hdr->AS.bci2000) ReturnData.SetGlobalSectionDescription(std::string(hdr->AS.bci2000));

    ReturnData.SetXScale(1000.0/hdr->SampleRate);
    ReturnData.SetXUnits("ms");
    ReturnData.SetScaling("biosig scaling factor");

    /*************************************************************************
        Date and time conversion
     *************************************************************************/
    struct tm T;
#if (BIOSIG_VERSION_MAJOR > 0)
    gdf_time2tm_time_r(hdr->T0, &T);
#else
    struct tm* Tp;
    Tp = gdf_time2tm_time(hdr->T0);
    T = *Tp;
#endif

    ReturnData.SetDateTime(T);

    destructHDR(hdr);

#endif
    return stfio::biosig;
}


    // =====================================================================================================================
    //
    // Save file with libbiosig into GDF format
    //
    // There basically two implementations, one with libbiosig before v1.6.0 and
    // and one for libbiosig v1.6.0 and later
    //
    // =====================================================================================================================

bool stfio::exportBiosigFile(const std::string& fName, const Recording& Data, stfio::ProgressInfo& progDlg) {
/*
    converts the internal data structure to libbiosig's internal structure
    and saves the file as gdf file.

    The data in converted into the raw data format, and not into the common
    data matrix.
*/

#ifdef __LIBBIOSIG2_H__

    size_t numberOfChannels = Data.size();
    HDRTYPE* hdr = constructHDR(numberOfChannels, 0);

	/* Initialize all header parameters */
    biosig_set_filetype(hdr, GDF);

    biosig_set_startdatetime(hdr, Data.GetDateTime());

    const char *xunits = Data.GetXUnits().c_str();
    uint16_t pdc = PhysDimCode(xunits);

    if ((pdc & 0xffe0) != PhysDimCode("s")) {
        fprintf(stderr,"Stimfit exportBiosigFile: xunits [%s] has not proper units, assume [ms]\n",Data.GetXUnits().c_str());
        pdc = PhysDimCode("ms");
    }

    double fs = 1.0/(PhysDimScale(pdc) * Data.GetXScale());
    biosig_set_samplerate(hdr, fs);

#if (BIOSIG_VERSION < 10700)
    biosig_set_flags(hdr, 0, 0, 0);
#else
    biosig_reset_flag(hdr, BIOSIG_FLAG_COMPRESSION | BIOSIG_FLAG_UCAL | BIOSIG_FLAG_OVERFLOWDETECTION | BIOSIG_FLAG_ROW_BASED_CHANNELS );
#endif

    size_t k, m, numberOfEvents=0;
    size_t NRec=0;	// corresponds to hdr->NRec
    size_t SPR=1;	// corresponds to hdr->SPR
    size_t chSPR=0;	// corresponds to hc->SPR

    /* Initialize all channel parameters */
#ifndef DONOTUSE_DYNAMIC_ALLOCATION_FOR_CHANSPR
	size_t *chanSPR = (size_t*)malloc(numberOfChannels*sizeof(size_t));
#endif
    for (k = 0; k < numberOfChannels; ++k) {
        CHANNEL_TYPE *hc = biosig_get_channel(hdr, k);

		biosig_channel_set_datatype_to_double(hc);
		biosig_channel_set_scaling(hc, 1e9, -1e9, 1e9, -1e9);
		biosig_channel_set_label(hc, Data[k].GetChannelName().c_str());
		biosig_channel_set_physdim(hc, Data[k].GetYUnits().c_str());

		biosig_channel_set_filter(hc, NAN, NAN, NAN);
		biosig_channel_set_timing_offset(hc, 0.0);
		biosig_channel_set_impedance(hc, NAN);

        chSPR    = SPR;

        // each segment gets one marker, roughly
        numberOfEvents += Data[k].size();

        size_t m,len = 0;
        for (len=0, m = 0; m < Data[k].size(); ++m) {
            unsigned div = lround(Data[k][m].GetXScale()/Data.GetXScale());
            chSPR = lcm(chSPR,div);  // sampling interval of m-th segment in k-th channel
            len += div*Data[k][m].size();
        }
        SPR = lcm(SPR, chSPR);

        /*
            hc->SPR (i.e. chSPR) is 'abused' to store final hdr->SPR/hc->SPR, this is corrected in the loop below
            its a hack to avoid the need for another malloc().
        */
#ifdef DONOTUSE_DYNAMIC_ALLOCATION_FOR_CHANSPR
        biosig_channel_set_samples_per_record(hc, chSPR);
#else
        chanSPR[k]=chSPR;
#endif

        if (k==0) {
            NRec = len;
        }
        else if ((size_t)NRec != len) {
            destructHDR(hdr);
            throw std::runtime_error("File can't be exported:\n"
                "No data or traces have different sizes" );

            return false;
        }
    }

    biosig_set_number_of_samples(hdr, NRec, SPR);
    size_t bpb = 0;
    for (k = 0; k < numberOfChannels; ++k) {
        CHANNEL_TYPE *hc = biosig_get_channel(hdr, k);
        // the 'abuse' of hc->SPR described above is corrected
#ifdef DONOTUSE_DYNAMIC_ALLOCATION_FOR_CHANSPR
        size_t spr = biosig_channel_get_samples_per_record(hc);
        spr = SPR / spr;
        biosig_channel_set_samples_per_record(hc, spr);
#else
        size_t spr = SPR/chanSPR[k];
        chanSPR[k] = spr;
#endif
        bpb += spr * 8; /* its always double */
    }

	/***
	    build Event table for storing segment information
	    pre-allocate memory for even table
         ***/

        numberOfEvents *= 2;    // about two events per segment
        biosig_set_number_of_events(hdr, numberOfEvents);

    /* check whether all segments have same size */
    {
        char flag = (numberOfChannels > 0);
        size_t m, POS, pos;
        for (k=0; k < numberOfChannels; ++k) {
            pos = Data[k].size();
            if (k==0)
                POS = pos;
            else
                flag &= (POS == pos);
        }
        for (m=0; flag && (m < Data[(size_t)0].size()); ++m) {
            for (k=0; k < biosig_get_number_of_channels(hdr); ++k) {
                pos = Data[k][m].size() * lround(Data[k][m].GetXScale()/Data.GetXScale());
                if (k==0)
                    POS = pos;
                else
                    flag &= (POS == pos);
            }
        }
        if (!flag) {
            destructHDR(hdr);
            throw std::runtime_error(
                    "File can't be exported:\n"
                    "Traces have different sizes or no channels found"
            );
            return false;
        }
    }

        size_t N=0;
        k=0;
        size_t pos = 0;
        for (m=0; m < (Data[k].size()); ++m) {
            if (pos > 0) {
                uint16_t typ=0x7ffe;
                uint32_t pos32=pos;
                uint16_t chn=0;
                uint32_t dur=0;
                // set break marker
                biosig_set_nth_event(hdr, N++, &typ, &pos32, &chn, &dur, NULL, NULL);
                /*
                // set annotation
                const char *Desc = Data[k][m].GetSectionDescription().c_str();
                 if (Desc != NULL && strlen(Desc)>0)
                    biosig_set_nth_event(hdr, N++, NULL, &pos32, &chn, &dur, NULL, Desc);   // TODO
                */
            }
            pos += Data[k][m].size() * lround(Data[k][m].GetXScale()/Data.GetXScale());
        }

        biosig_set_number_of_events(hdr, N);
        biosig_set_eventtable_samplerate(hdr, fs);
        sort_eventtable(hdr);

        /* convert data into GDF rawdata from  */
        uint8_t *rawdata = (uint8_t*)malloc(bpb * NRec);

        size_t bi=0;
	for (k=0; k < numberOfChannels; ++k) {
        CHANNEL_TYPE *hc = biosig_get_channel(hdr, k);
#ifdef DONOTUSE_DYNAMIC_ALLOCATION_FOR_CHANSPR
        size_t chSPR = biosig_channel_get_samples_per_record(hc);
#else
        size_t chSPR = chanSPR[k];
#endif
        size_t m,n,len=0;
        for (m=0; m < Data[k].size(); ++m) {

            size_t div = lround(Data[k][m].GetXScale()/Data.GetXScale());
            size_t div2 = SPR/div;		  // TODO: avoid using hdr->SPR

            // fprintf(stdout,"k,m,div,div2: %i,%i,%i,%i\n",(int)k,(int)m,(int)div,(int)div2);  //
            for (n=0; n < Data[k][m].size(); ++n) {
                uint64_t val;
                double d = Data[k][m][n];
#if !defined(__MINGW32__) && !defined(_MSC_VER) && !defined(__APPLE__)
                val = htole64(*(uint64_t*)&d);
#else
                val = *(uint64_t*)&d;
#endif
                size_t p, spr = (len + n*div) / SPR;

                for (p=0; p < div2; p++)
                   *(uint64_t*)(rawdata + bi + bpb * spr + p*8) = val;
            }
            len += div*Data[k][m].size();
        }
		bi += chSPR*8;
    }

#ifndef DONOTUSE_DYNAMIC_ALLOCATION_FOR_CHANSPR
	if (chanSPR) free(chanSPR);
#endif

    /******************************
        write to file
    *******************************/
    std::string errorMsg("Exception while calling std::exportBiosigFile():\n");

    hdr = sopen( fName.c_str(), "w", hdr );
    if (serror2(hdr)) {
        errorMsg += biosig_get_errormsg(hdr);
        destructHDR(hdr);
        throw std::runtime_error(errorMsg.c_str());
        return false;
    }

    ifwrite(rawdata, bpb, NRec, hdr);

    sclose(hdr);
    destructHDR(hdr);
    free(rawdata);


#else   // #ifndef __LIBBIOSIG2_H__


    HDRTYPE* hdr = constructHDR(Data.size(), 0);
    assert(hdr->NS == Data.size());

	/* Initialize all header parameters */
    hdr->TYPE = GDF;
#if (BIOSIG_VERSION >= 10508)
    /* transition in biosig to rename HDR->VERSION to HDR->Version
       to avoid name space conflict with macro VERSION
     */
    hdr->Version = 3.0;   // select latest supported version of GDF format
#else
    hdr->VERSION = 3.0;   // select latest supported version of GDF format
#endif

    struct tm t = Data.GetDateTime();

    hdr->T0 = tm_time2gdf_time(&t);

    const char *xunits = Data.GetXUnits().c_str();
#if (BIOSIG_VERSION_MAJOR > 0)
    uint16_t pdc = PhysDimCode(xunits);
#else
    uint16_t pdc = PhysDimCode((char*)xunits);
#endif
    if ((pdc & 0xffe0) == PhysDimCode("s")) {
        fprintf(stderr,"Stimfit exportBiosigFile: xunits [%s] has not proper units, assume [ms]\n",Data.GetXUnits().c_str());
        pdc = PhysDimCode("ms");
    }
    hdr->SampleRate = 1.0/(PhysDimScale(pdc) * Data.GetXScale());
    hdr->SPR  = 1;

    hdr->FLAG.UCAL = 0;
    hdr->FLAG.OVERFLOWDETECTION = 0;

    hdr->FILE.COMPRESSION = 0;

	/* Initialize all channel parameters */
    size_t k, m;
    for (k = 0; k < hdr->NS; ++k) {
        CHANNEL_TYPE *hc = hdr->CHANNEL+k;

        hc->PhysMin = -1e9;
        hc->PhysMax =  1e9;
        hc->DigMin  = -1e9;
        hc->DigMax  =  1e9;
        hc->Cal     =  1.0;
        hc->Off     =  0.0;

        /* Channel descriptions. */
        strncpy(hc->Label, Data[k].GetChannelName().c_str(), MAX_LENGTH_LABEL);
#if (BIOSIG_VERSION_MAJOR > 0)
        hc->PhysDimCode = PhysDimCode(Data[k].GetYUnits().c_str());
#else
        hc->PhysDimCode = PhysDimCode((char*)Data[k].GetYUnits().c_str());
#endif
        hc->OnOff      = 1;
        hc->LeadIdCode = 0;

        hc->TOffset  = 0.0;
        hc->Notch    = NAN;
        hc->LowPass  = NAN;
        hc->HighPass = NAN;
        hc->Impedance= NAN;

        hc->SPR    = hdr->SPR;
        hc->GDFTYP = 17; 	// double

        // each segment gets one marker, roughly
        hdr->EVENT.N += Data[k].size();

        size_t m,len = 0;
        for (len=0, m = 0; m < Data[k].size(); ++m) {
            unsigned div = lround(Data[k][m].GetXScale()/Data.GetXScale());
            hc->SPR = lcm(hc->SPR,div);  // sampling interval of m-th segment in k-th channel
            len += div*Data[k][m].size();
        }
        hdr->SPR = lcm(hdr->SPR, hc->SPR);

        if (k==0) {
            hdr->NRec = len;
        }
        else if ((size_t)hdr->NRec != len) {
            destructHDR(hdr);
            throw std::runtime_error("File can't be exported:\n"
                "No data or traces have different sizes" );

            return false;
        }
    }

    hdr->AS.bpb = 0;
    for (k = 0; k < hdr->NS; ++k) {
        CHANNEL_TYPE *hc = hdr->CHANNEL+k;
        hc->SPR = hdr->SPR / hc->SPR;
        hc->bi  = hdr->AS.bpb;
        hdr->AS.bpb += hc->SPR * 8; /* its always double */
    }

	/***
	    build Event table for storing segment information
	 ***/
	size_t N = hdr->EVENT.N * 2;    // about two events per segment
	hdr->EVENT.POS = (uint32_t*)realloc(hdr->EVENT.POS, N * sizeof(*hdr->EVENT.POS));
	hdr->EVENT.DUR = (uint32_t*)realloc(hdr->EVENT.DUR, N * sizeof(*hdr->EVENT.DUR));
	hdr->EVENT.TYP = (uint16_t*)realloc(hdr->EVENT.TYP, N * sizeof(*hdr->EVENT.TYP));
	hdr->EVENT.CHN = (uint16_t*)realloc(hdr->EVENT.CHN, N * sizeof(*hdr->EVENT.CHN));
#if (BIOSIG_VERSION >= 10500)
	hdr->EVENT.TimeStamp = (gdf_time*)realloc(hdr->EVENT.TimeStamp, N * sizeof(gdf_time));
#endif

    /* check whether all segments have same size */
    {
        char flag = (hdr->NS>0);
        size_t m, POS, pos;
        for (k=0; k < hdr->NS; ++k) {
            pos = Data[k].size();
            if (k==0)
                POS = pos;
            else
                flag &= (POS == pos);
        }
        for (m=0; flag && (m < Data[(size_t)0].size()); ++m) {
            for (k=0; k < hdr->NS; ++k) {
                pos = Data[k][m].size() * lround(Data[k][m].GetXScale()/Data.GetXScale());
                if (k==0)
                    POS = pos;
                else
                    flag &= (POS == pos);
            }
        }
        if (!flag) {
            destructHDR(hdr);
            throw std::runtime_error(
                    "File can't be exported:\n"
                    "Traces have different sizes or no channels found"
            );
            return false;
        }
    }

        N=0;
        k=0;
        size_t pos = 0;
        for (m=0; m < (Data[k].size()); ++m) {
            if (pos > 0) {
                // start of new segment after break
                hdr->EVENT.POS[N] = pos;
                hdr->EVENT.TYP[N] = 0x7ffe;
                hdr->EVENT.CHN[N] = 0;
                hdr->EVENT.DUR[N] = 0;
                N++;
            }
#if 0
            // event description
            hdr->EVENT.POS[N] = pos;
            FreeTextEvent(hdr, N, "myevent");
            //FreeTextEvent(hdr, N, Data[k][m].GetSectionDescription().c_str()); // TODO
            hdr->EVENT.CHN[N] = k;
            hdr->EVENT.DUR[N] = 0;
            N++;
#endif
            pos += Data[k][m].size() * lround(Data[k][m].GetXScale()/Data.GetXScale());
        }

        hdr->EVENT.N = N;
        hdr->EVENT.SampleRate = hdr->SampleRate;

        sort_eventtable(hdr);

	/* convert data into GDF rawdata from  */
	hdr->AS.rawdata = (uint8_t*)realloc(hdr->AS.rawdata, hdr->AS.bpb*hdr->NRec);
	for (k=0; k < hdr->NS; ++k) {
        CHANNEL_TYPE *hc = hdr->CHANNEL+k;

        size_t m,n,len=0;
        for (m=0; m < Data[k].size(); ++m) {
            size_t div = lround(Data[k][m].GetXScale()/Data.GetXScale());
            size_t div2 = hdr->SPR/div;

            // fprintf(stdout,"k,m,div,div2: %i,%i,%i,%i\n",(int)k,(int)m,(int)div,(int)div2);  //
            for (n=0; n < Data[k][m].size(); ++n) {
                uint64_t val;
                double d = Data[k][m][n];
#if !defined(__MINGW32__) && !defined(_MSC_VER) && !defined(__APPLE__)
                val = htole64(*(uint64_t*)&d);
#else
                val = *(uint64_t*)&d;
#endif
                size_t p, spr = (len + n*div) / hdr->SPR;
                for (p=0; p < div2; p++)
                   *(uint64_t*)(hdr->AS.rawdata + hc->bi + hdr->AS.bpb * spr + p*8) = val;
            }
            len += div*Data[k][m].size();
        }
    }

    /******************************
        write to file
    *******************************/
    std::string errorMsg("Exception while calling std::exportBiosigFile():\n");

    hdr = sopen( fName.c_str(), "w", hdr );
#if (BIOSIG_VERSION > 10400)
    if (serror2(hdr)) {
        errorMsg += hdr->AS.B4C_ERRMSG;
#else
    if (serror()) {
	    errorMsg += B4C_ERRMSG;
#endif
        destructHDR(hdr);
        throw std::runtime_error(errorMsg.c_str());
        return false;
    }

    ifwrite(hdr->AS.rawdata, hdr->AS.bpb, hdr->NRec, hdr);

    sclose(hdr);
    destructHDR(hdr);
#endif

    return true;
}
Esempio n. 12
0
static int parse_tcfile( FILE *tcfile_in, timecode_hnd_t *h, video_info_t *info )
{
    char buff[256];
    int ret, tcfv, num, seq_num, timecodes_num;
    int64_t pts_seek_offset;
    double *timecodes = NULL;
    double *fpss = NULL;

    ret = fscanf( tcfile_in, "# timecode format v%d", &tcfv );
    if( ret != 1 || (tcfv != 1 && tcfv != 2) )
    {
        fprintf( stderr, "timecode [error]: unsupported timecode format\n" );
        return -1;
    }

    if( tcfv == 1 )
    {
        uint64_t file_pos;
        double assume_fps, seq_fps;
        int start, end = h->seek;
        int prev_start = -1, prev_end = -1;

        h->assume_fps = 0;
        for( num = 2; fgets( buff, sizeof(buff), tcfile_in ) != NULL; num++ )
        {
            if( buff[0] == '#' || buff[0] == '\n' || buff[0] == '\r' )
                continue;
            if( sscanf( buff, "assume %lf", &h->assume_fps ) != 1 && sscanf( buff, "Assume %lf", &h->assume_fps ) != 1 )
            {
                fprintf( stderr, "timecode [error]: tcfile parsing error: assumed fps not found\n" );
                return -1;
            }
            break;
        }
        if( h->assume_fps <= 0 )
        {
            fprintf( stderr, "timecode [error]: invalid assumed fps %.6f\n", h->assume_fps );
            return -1;
        }

        file_pos = ftell( tcfile_in );
        h->stored_pts_num = 0;
        for( seq_num = 0; fgets( buff, sizeof(buff), tcfile_in ) != NULL; num++ )
        {
            if( buff[0] == '#' || buff[0] == '\n' || buff[0] == '\r' )
            {
                if( sscanf( buff, "# TDecimate Mode 3:  Last Frame = %d", &end ) == 1 )
                    h->stored_pts_num = end + 1 - h->seek;
                continue;
            }
            ret = sscanf( buff, "%d,%d,%lf", &start, &end, &seq_fps );
            if( ret != 3 && ret != EOF )
            {
                fprintf( stderr, "timecode [error]: invalid input tcfile\n" );
                return -1;
            }
            if( start > end || start <= prev_start || end <= prev_end || seq_fps <= 0 )
            {
                fprintf( stderr, "timecode [error]: invalid input tcfile at line %d: %s\n", num, buff );
                return -1;
            }
            prev_start = start;
            prev_end = end;
            if( h->auto_timebase_den || h->auto_timebase_num )
                ++seq_num;
        }
        if( !h->stored_pts_num )
            h->stored_pts_num = end + 1 - h->seek;
        timecodes_num = h->stored_pts_num + h->seek;
        fseek( tcfile_in, file_pos, SEEK_SET );

        timecodes = malloc( timecodes_num * sizeof(double) );
        if( !timecodes )
            return -1;
        if( h->auto_timebase_den || h->auto_timebase_num )
        {
            fpss = malloc( (seq_num + 1) * sizeof(double) );
            if( !fpss )
                goto fail;
        }

        assume_fps = correct_fps( h->assume_fps, h );
        if( assume_fps < 0 )
            goto fail;
        timecodes[0] = 0;
        for( num = seq_num = 0; num < timecodes_num - 1; )
        {
            fgets( buff, sizeof(buff), tcfile_in );
            if( buff[0] == '#' || buff[0] == '\n' || buff[0] == '\r' )
                continue;
            ret = sscanf( buff, "%d,%d,%lf", &start, &end, &seq_fps );
            if( ret != 3 )
                start = end = timecodes_num - 1;
            if( h->auto_timebase_den || h->auto_timebase_num )
                fpss[seq_num++] = seq_fps;
            seq_fps = correct_fps( seq_fps, h );
            if( seq_fps < 0 )
                goto fail;
            for( ; num < start && num < timecodes_num - 1; num++ )
                timecodes[num + 1] = timecodes[num] + 1 / assume_fps;
            for( num = start; num <= end && num < timecodes_num - 1; num++ )
                timecodes[num + 1] = timecodes[num] + 1 / seq_fps;
        }
        if( h->auto_timebase_den || h->auto_timebase_num )
            fpss[seq_num] = h->assume_fps;

        if( h->auto_timebase_num && !h->auto_timebase_den )
        {
            double exponent;
            double assume_fps_sig, seq_fps_sig;
            if( try_mkv_timebase_den( fpss, h, seq_num + 1 ) < 0 )
                goto fail;
            fseek( tcfile_in, file_pos, SEEK_SET );
            assume_fps_sig = sigexp10( h->assume_fps, &exponent );
            assume_fps = MKV_TIMEBASE_DEN / ( round( MKV_TIMEBASE_DEN / assume_fps_sig ) / exponent );
            for( num = 0; num < timecodes_num - 1; )
            {
                fgets( buff, sizeof(buff), tcfile_in );
                if( buff[0] == '#' || buff[0] == '\n' || buff[0] == '\r' )
                    continue;
                ret = sscanf( buff, "%d,%d,%lf", &start, &end, &seq_fps );
                if( ret != 3 )
                    start = end = timecodes_num - 1;
                seq_fps_sig = sigexp10( seq_fps, &exponent );
                seq_fps = MKV_TIMEBASE_DEN / ( round( MKV_TIMEBASE_DEN / seq_fps_sig ) / exponent );
                for( ; num < start && num < timecodes_num - 1; num++ )
                    timecodes[num + 1] = timecodes[num] + 1 / assume_fps;
                for( num = start; num <= end && num < timecodes_num - 1; num++ )
                    timecodes[num + 1] = timecodes[num] + 1 / seq_fps;
            }
        }
        if( fpss )
            free( fpss );

        h->assume_fps = assume_fps;
        h->last_timecode = timecodes[timecodes_num - 1];
    }
    else    /* tcfv == 2 */
    {
        uint64_t file_pos = ftell( tcfile_in );

        num = h->stored_pts_num = 0;
        while( fgets( buff, sizeof(buff), tcfile_in ) != NULL )
        {
            if( buff[0] == '#' || buff[0] == '\n' || buff[0] == '\r' )
            {
                if( !num )
                    file_pos = ftell( tcfile_in );
                continue;
            }
            if( num >= h->seek )
                ++h->stored_pts_num;
            ++num;
        }
        timecodes_num = h->stored_pts_num + h->seek;
        if( !timecodes_num )
        {
            fprintf( stderr, "timecode [error]: input tcfile doesn't have any timecodes!\n" );
            return -1;
        }
        fseek( tcfile_in, file_pos, SEEK_SET );

        timecodes = malloc( timecodes_num * sizeof(double) );
        if( !timecodes )
            return -1;

        fgets( buff, sizeof(buff), tcfile_in );
        ret = sscanf( buff, "%lf", &timecodes[0] );
        if( ret != 1 )
        {
            fprintf( stderr, "timecode [error]: invalid input tcfile for frame 0\n" );
            goto fail;
        }
        for( num = 1; num < timecodes_num; )
        {
            fgets( buff, sizeof(buff), tcfile_in );
            if( buff[0] == '#' || buff[0] == '\n' || buff[0] == '\r' )
                continue;
            ret = sscanf( buff, "%lf", &timecodes[num] );
            timecodes[num] *= 1e-3;         /* Timecode format v2 is expressed in milliseconds. */
            if( ret != 1 || timecodes[num] <= timecodes[num - 1] )
            {
                fprintf( stderr, "timecode [error]: invalid input tcfile for frame %d\n", num );
                goto fail;
            }
            ++num;
        }

        if( timecodes_num == 1 )
            h->timebase_den = info->fps_num;
        else if( h->auto_timebase_den )
        {
            fpss = malloc( (timecodes_num - 1) * sizeof(double) );
            if( !fpss )
                goto fail;
            for( num = 0; num < timecodes_num - 1; num++ )
            {
                fpss[num] = 1 / (timecodes[num + 1] - timecodes[num]);
                if( h->timebase_den >= 0 )
                {
                    int i = 1;
                    int fps_num, fps_den;
                    double exponent;
                    double fps_sig = sigexp10( fpss[num], &exponent );
                    while( 1 )
                    {
                        fps_den = i * h->timebase_num;
                        fps_num = round( fps_den * fps_sig ) * exponent;
                        if( fps_num < 0 || fabs( ((double)fps_num / fps_den) / exponent - fps_sig ) < DOUBLE_EPSILON )
                            break;
                        ++i;
                    }
                    h->timebase_den = fps_num > 0 && h->timebase_den ? lcm( h->timebase_den, fps_num ) : fps_num;
                    if( h->timebase_den < 0 )
                    {
                        h->auto_timebase_den = 0;
                        continue;
                    }
                }
            }
            if( h->auto_timebase_num && !h->auto_timebase_den )
                if( try_mkv_timebase_den( fpss, h, timecodes_num - 1 ) < 0 )
                    goto fail;
            free( fpss );
        }

        if( timecodes_num > 1 )
            h->assume_fps = 1 / (timecodes[timecodes_num - 1] - timecodes[timecodes_num - 2]);
        else
            h->assume_fps = (double)info->fps_num / info->fps_den;
        h->last_timecode = timecodes[timecodes_num - 1];
    }

    if( h->auto_timebase_den || h->auto_timebase_num )
    {
        x264_reduce_fraction( &h->timebase_num, &h->timebase_den );
        fprintf( stderr, "timecode [info]: automatic timebase generation %d/%d\n", h->timebase_num, h->timebase_den );
    }
    else if( h->timebase_den <= 0 )
    {
        fprintf( stderr, "timecode [error]: automatic timebase generation failed.\n"
                         "                  Specify an appropriate timebase manually.\n" );
        goto fail;
    }

    h->pts = malloc( h->stored_pts_num * sizeof(int64_t) );
    if( !h->pts )
        goto fail;
    pts_seek_offset = (int64_t)( timecodes[h->seek] * ((double)h->timebase_den / h->timebase_num) + 0.5 );
    h->pts[0] = 0;
    for( num = 1; num < h->stored_pts_num; num++ )
    {
        h->pts[num] = (int64_t)( timecodes[h->seek + num] * ((double)h->timebase_den / h->timebase_num) + 0.5 );
        h->pts[num] -= pts_seek_offset;
        if( h->pts[num] <= h->pts[num - 1] )
        {
            fprintf( stderr, "timecode [error]: invalid timebase or timecode for frame %d\n", num );
            goto fail;
        }
    }

    free( timecodes );
    return 0;

fail:
    if( timecodes )
        free( timecodes );
    if( fpss )
        free( fpss );
    return -1;
}
Esempio n. 13
0
bool Fraction::operator>(const Fraction& val) const
{
    const int v = lcm(_denominator, val._denominator);
    return (_numerator * (v / _denominator)) > (val._numerator * (v / val._denominator));
}
Esempio n. 14
0
	/**
	 * 通分用最小公倍数の取得
	 * @param 通分対象の有理数
	 * @return 分母同士の最小公倍数
	 */
	NumberType getCommonDenominator(const Rational& rhs) const throw()
	{
		return lcm(this->denominator, rhs.denominator);
	}
/*
 * Heuristically guess the PLL tree for a given common multiplier and
 * divisor. Begin with the operational timing and continue to video
 * timing once operational timing has been verified.
 *
 * @mul is the PLL multiplier and @div is the common divisor
 * (pre_pll_clk_div and op_sys_clk_div combined). The final PLL
 * multiplier will be a multiple of @mul.
 *
 * @return Zero on success, error code on error.
 */
static int __smiapp_pll_calculate(struct device *dev,
				  const struct smiapp_pll_limits *limits,
				  struct smiapp_pll *pll, uint32_t mul,
				  uint32_t div, uint32_t lane_op_clock_ratio,
				  uint32_t lane_vt_clock_ratio)
{
	uint32_t sys_div;
	uint32_t best_pix_div = INT_MAX >> 1;
	uint32_t vt_op_binning_div;
	/*
	 * Higher multipliers (and divisors) are often required than
	 * necessitated by the external clock and the output clocks.
	 * There are limits for all values in the clock tree. These
	 * are the minimum and maximum multiplier for mul.
	 */
	uint32_t more_mul_min, more_mul_max;
	uint32_t more_mul_factor;
	uint32_t min_vt_div, max_vt_div, vt_div;
	uint32_t min_sys_div, max_sys_div;
	unsigned int i;
	int rval;

	/*
	 * Get pre_pll_clk_div so that our pll_op_clk_freq_hz won't be
	 * too high.
	 */
	dev_dbg(dev, "pre_pll_clk_div %u\n", pll->pre_pll_clk_div);

	/* Don't go above max pll multiplier. */
	more_mul_max = limits->max_pll_multiplier / mul;
	dev_dbg(dev, "more_mul_max: max_pll_multiplier check: %u\n",
		more_mul_max);
	/* Don't go above max pll op frequency. */
	more_mul_max =
		min_t(uint64_t,
		      more_mul_max,
		      div_u64(limits->max_pll_op_freq_hz,
			      (pll->ext_clk_freq_hz /
			       pll->pre_pll_clk_div * mul)));
	dev_dbg(dev, "more_mul_max: max_pll_op_freq_hz check: %u\n",
		more_mul_max);
	/* Don't go above the division capability of op sys clock divider. */
	more_mul_max = min(more_mul_max,
			   limits->op.max_sys_clk_div * pll->pre_pll_clk_div
			   / div);
	dev_dbg(dev, "more_mul_max: max_op_sys_clk_div check: %u\n",
		more_mul_max);
	/* Ensure we won't go above min_pll_multiplier. */
	more_mul_max = min(more_mul_max,
			   DIV_ROUND_UP(limits->max_pll_multiplier, mul));
	dev_dbg(dev, "more_mul_max: min_pll_multiplier check: %u\n",
		more_mul_max);

	/* Ensure we won't go below min_pll_op_freq_hz. */
	more_mul_min = div_u64_round_up(
		limits->min_pll_op_freq_hz,
		pll->ext_clk_freq_hz / pll->pre_pll_clk_div * mul);
	dev_dbg(dev, "more_mul_min: min_pll_op_freq_hz check: %u\n",
		more_mul_min);
	/* Ensure we won't go below min_pll_multiplier. */
	more_mul_min = max(more_mul_min,
			   DIV_ROUND_UP(limits->min_pll_multiplier, mul));
	dev_dbg(dev, "more_mul_min: min_pll_multiplier check: %u\n",
		more_mul_min);

	if (more_mul_min > more_mul_max) {
		dev_dbg(dev,
			"unable to compute more_mul_min and more_mul_max\n");
		return -EINVAL;
	}

	more_mul_factor = lcm(div, pll->pre_pll_clk_div) / div;
	dev_dbg(dev, "more_mul_factor: %u\n", more_mul_factor);
	more_mul_factor = lcm(more_mul_factor, limits->op.min_sys_clk_div);
	dev_dbg(dev, "more_mul_factor: min_op_sys_clk_div: %u\n",
		more_mul_factor);
	i = roundup(more_mul_min, more_mul_factor);
	if (!is_one_or_even(i))
		i <<= 1;

	dev_dbg(dev, "final more_mul: %u\n", i);
	if (i > more_mul_max) {
		dev_dbg(dev, "final more_mul is bad, max %u\n", more_mul_max);
		return -EINVAL;
	}

	pll->pll_multiplier = mul * i;
	pll->op_sys_clk_div = div * i / pll->pre_pll_clk_div;
	dev_dbg(dev, "op_sys_clk_div: %u\n", pll->op_sys_clk_div);

	pll->pll_ip_clk_freq_hz = pll->ext_clk_freq_hz
		/ pll->pre_pll_clk_div;

	pll->pll_op_clk_freq_hz = pll->pll_ip_clk_freq_hz
		* pll->pll_multiplier;

	/* Derive pll_op_clk_freq_hz. */
	pll->op_sys_clk_freq_hz =
		div_u64(pll->pll_op_clk_freq_hz, pll->op_sys_clk_div);

	pll->op_pix_clk_div = pll->bits_per_pixel;
	if (pll->flags & SMIAPP_PLL_FLAG_OP_PIX_DIV_HALF)
		pll->op_pix_clk_div /= 2;
	dev_dbg(dev, "op_pix_clk_div: %u\n", pll->op_pix_clk_div);

	pll->op_pix_clk_freq_hz =
		div_u64(pll->op_sys_clk_freq_hz, pll->op_pix_clk_div);

	/*
	 * Some sensors perform analogue binning and some do this
	 * digitally. The ones doing this digitally can be roughly be
	 * found out using this formula. The ones doing this digitally
	 * should run at higher clock rate, so smaller divisor is used
	 * on video timing side.
	 */
	if (limits->min_line_length_pck_bin > limits->min_line_length_pck
	    / pll->binning_horizontal)
		vt_op_binning_div = pll->binning_horizontal;
	else
		vt_op_binning_div = 1;
	dev_dbg(dev, "vt_op_binning_div: %u\n", vt_op_binning_div);

	/*
	 * Profile 2 supports vt_pix_clk_div E [4, 10]
	 *
	 * Horizontal binning can be used as a base for difference in
	 * divisors. One must make sure that horizontal blanking is
	 * enough to accommodate the CSI-2 sync codes.
	 *
	 * Take scaling factor into account as well.
	 *
	 * Find absolute limits for the factor of vt divider.
	 */
	dev_dbg(dev, "scale_m: %u\n", pll->scale_m);
	min_vt_div = DIV_ROUND_UP(pll->op_pix_clk_div * pll->op_sys_clk_div
				  * pll->scale_n * lane_vt_clock_ratio,
				  lane_op_clock_ratio * vt_op_binning_div
				  * pll->scale_m);

	/* Find smallest and biggest allowed vt divisor. */
	dev_dbg(dev, "min_vt_div: %u\n", min_vt_div);
	min_vt_div = max_t(uint32_t, min_vt_div,
			   div_u64_round_up(pll->pll_op_clk_freq_hz,
					    limits->vt.max_pix_clk_freq_hz));
	dev_dbg(dev, "min_vt_div: max_vt_pix_clk_freq_hz: %u\n",
		min_vt_div);
	min_vt_div = max_t(uint32_t, min_vt_div,
			   limits->vt.min_pix_clk_div
			   * limits->vt.min_sys_clk_div);
	dev_dbg(dev, "min_vt_div: min_vt_clk_div: %u\n", min_vt_div);

	max_vt_div = limits->vt.max_sys_clk_div * limits->vt.max_pix_clk_div;
	dev_dbg(dev, "max_vt_div: %u\n", max_vt_div);
	max_vt_div = min_t(uint32_t, max_vt_div,
			   div_u64_round_up(pll->pll_op_clk_freq_hz,
					    limits->vt.min_pix_clk_freq_hz));
	dev_dbg(dev, "max_vt_div: min_vt_pix_clk_freq_hz: %u\n",
		max_vt_div);

	/*
	 * Find limitsits for sys_clk_div. Not all values are possible
	 * with all values of pix_clk_div.
	 */
	min_sys_div = limits->vt.min_sys_clk_div;
	dev_dbg(dev, "min_sys_div: %u\n", min_sys_div);
	min_sys_div = max(min_sys_div,
			  DIV_ROUND_UP(min_vt_div,
				       limits->vt.max_pix_clk_div));
	dev_dbg(dev, "min_sys_div: max_vt_pix_clk_div: %d\n", min_sys_div);
	min_sys_div = max_t(uint32_t, min_sys_div,
			    pll->pll_op_clk_freq_hz
			    / limits->vt.max_sys_clk_freq_hz);
	dev_dbg(dev, "min_sys_div: max_pll_op_clk_freq_hz: %d\n", min_sys_div);
	min_sys_div = clk_div_up(min_sys_div, 0);
	dev_dbg(dev, "min_sys_div: one or even: %d\n", min_sys_div);

	max_sys_div = limits->vt.max_sys_clk_div;
	dev_dbg(dev, "max_sys_div: %u\n", max_sys_div);
	max_sys_div = min(max_sys_div,
			  DIV_ROUND_UP(max_vt_div,
				       limits->vt.min_pix_clk_div));
	dev_dbg(dev, "max_sys_div: min_vt_pix_clk_div: %u\n", max_sys_div);
	max_sys_div = min_t(uint32_t, max_sys_div,
			    div_u64_round_up(pll->pll_op_clk_freq_hz,
					     limits->vt.min_pix_clk_freq_hz));
	dev_dbg(dev, "max_sys_div: min_vt_pix_clk_freq_hz: %u\n", max_sys_div);

	/*
	 * Find pix_div such that a legal pix_div * sys_div results
	 * into a value which is not smaller than div, the desired
	 * divisor.
	 */
	for (vt_div = min_vt_div; vt_div <= max_vt_div;
	     vt_div += 2 - (vt_div & 1)) {
		for (sys_div = min_sys_div;
		     sys_div <= max_sys_div;
		     sys_div += 2 - (sys_div & 1)) {
			uint16_t pix_div = DIV_ROUND_UP(vt_div, sys_div);

			if (pix_div < limits->vt.min_pix_clk_div
			    || pix_div > limits->vt.max_pix_clk_div) {
				dev_dbg(dev,
					"pix_div %u too small or too big (%u--%u)\n",
					pix_div,
					limits->vt.min_pix_clk_div,
					limits->vt.max_pix_clk_div);
				continue;
			}

			/* Check if this one is better. */
			if (pix_div * sys_div
			    <= roundup(min_vt_div, best_pix_div))
				best_pix_div = pix_div;
		}
		if (best_pix_div < INT_MAX >> 1)
			break;
	}

	pll->vt_sys_clk_div = DIV_ROUND_UP(min_vt_div, best_pix_div);
	pll->vt_pix_clk_div = best_pix_div;

	pll->vt_sys_clk_freq_hz =
		div_u64(pll->pll_op_clk_freq_hz, pll->vt_sys_clk_div);
	pll->vt_pix_clk_freq_hz =
		div_u64(pll->vt_sys_clk_freq_hz, pll->vt_pix_clk_div);

	pll->pixel_rate_csi =
		pll->op_pix_clk_freq_hz * lane_op_clock_ratio;
	pll->pixel_rate_pixel_array = pll->vt_pix_clk_freq_hz
		* lane_vt_clock_ratio;
	if (pll->flags & SMIAPP_PLL_FLAG_PIX_CLOCK_DOUBLE) {
		pll->pixel_rate_csi *= 2;
		pll->pixel_rate_pixel_array *= 2;
	}

	rval = bounds_check(dev, pll->pll_ip_clk_freq_hz,
			    limits->min_pll_ip_freq_hz,
			    limits->max_pll_ip_freq_hz,
			    "pll_ip_clk_freq_hz");
	if (!rval)
		rval = bounds_check(
			dev, pll->pll_multiplier,
			limits->min_pll_multiplier, limits->max_pll_multiplier,
			"pll_multiplier");
	if (!rval)
		rval = bounds_check(
			dev, pll->pll_op_clk_freq_hz,
			limits->min_pll_op_freq_hz, limits->max_pll_op_freq_hz,
			"pll_op_clk_freq_hz");
	if (!rval)
		rval = bounds_check(
			dev, pll->op_sys_clk_div,
			limits->op.min_sys_clk_div, limits->op.max_sys_clk_div,
			"op_sys_clk_div");
	if (!rval)
		rval = bounds_check(
			dev, pll->op_sys_clk_freq_hz,
			limits->op.min_sys_clk_freq_hz,
			limits->op.max_sys_clk_freq_hz,
			"op_sys_clk_freq_hz");
	if (!rval)
		rval = bounds_check(
			dev, pll->op_pix_clk_freq_hz,
			limits->op.min_pix_clk_freq_hz,
			limits->op.max_pix_clk_freq_hz,
			"op_pix_clk_freq_hz");
	if (!rval)
		rval = bounds_check(
			dev, pll->vt_sys_clk_freq_hz,
			limits->vt.min_sys_clk_freq_hz,
			limits->vt.max_sys_clk_freq_hz,
			"vt_sys_clk_freq_hz");
	if (!rval)
		rval = bounds_check(
			dev, pll->vt_pix_clk_freq_hz,
			limits->vt.min_pix_clk_freq_hz,
			limits->vt.max_pix_clk_freq_hz,
			"vt_pix_clk_freq_hz");

	return rval;
}
Esempio n. 16
0
int main(int argc,char** argv) {

    bool ttl_one = false;
    bool visualization = false;

    std::string pose_channel = "STATE_ESTIMATOR_POSE";
    std::string stereo_channel = "stereo";
    std::string rc_trajectory_commands_channel = "rc-trajectory-commands";
    std::string state_machine_go_autonomous_channel = "state-machine-go-autonomous";

    std::string tvlqr_action_out_channel = "tvlqr-action";
    std::string arm_for_takeoff_channel = "arm-for-takeoff";
    std::string state_message_channel = "state-machine-state";
    std::string altitude_reset_channel = "altitude-reset";


    ConciseArgs parser(argc, argv);
    parser.add(ttl_one, "t", "ttl-one", "Pass to set LCM TTL=1");
    parser.add(pose_channel, "p", "pose-channel", "LCM channel to listen for pose messages on.");
    parser.add(stereo_channel, "e", "stereo-channel", "LCM channel to listen to stereo messages on.");
    parser.add(tvlqr_action_out_channel, "o", "tvlqr-out-channel", "LCM channel to publish which TVLQR trajectory is running on.");
    parser.add(rc_trajectory_commands_channel, "r", "rc-trajectory-commands-channel", "LCM channel to listen for RC trajectory commands on.");
    parser.add(state_machine_go_autonomous_channel, "a", "state-machine-go-autonomous-channel", "LCM channel to send go-autonmous messages on.");
    parser.add(visualization, "v", "visualization", "Enables visualization for HUD / LCMGL.");
    parser.add(arm_for_takeoff_channel, "A", "arm-for-takeoff-channel", "LCM channel to receive arm for takeoff messages on.");
    parser.add(state_message_channel, "s" "state-machine-state-channel", "LCM channel to send state machine state messages on.");

    parser.parse();


    std::string lcm_url;
    // create an lcm instance
    if (ttl_one) {
        lcm_url = "udpm://239.255.76.67:7667?ttl=1";
    } else {
        lcm_url = "udpm://239.255.76.67:7667?ttl=0";
    }
    lcm::LCM lcm(lcm_url);

    if (!lcm.good()) {
        std::cerr << "LCM creation failed." << std::endl;
        return 1;
    }

    BotParam *param = bot_param_new_from_server(lcm.getUnderlyingLCM(), 0);

    std::string trajectory_dir = std::string(bot_param_get_str_or_fail(param, "tvlqr_controller.library_dir"));


    trajectory_dir = ReplaceUserVarInPath(trajectory_dir);

    StateMachineControl fsm_control(&lcm, trajectory_dir, tvlqr_action_out_channel, state_message_channel, altitude_reset_channel, visualization);
    //fsm_control.GetFsmContext()->setDebugFlag(true);

    // subscribe to LCM channels
    lcm.subscribe(pose_channel, &StateMachineControl::ProcessImuMsg, &fsm_control);
    lcm.subscribe(stereo_channel, &StateMachineControl::ProcessStereoMsg, &fsm_control);
    lcm.subscribe(rc_trajectory_commands_channel, &StateMachineControl::ProcessRcTrajectoryMsg, &fsm_control);
    lcm.subscribe(state_machine_go_autonomous_channel, &StateMachineControl::ProcessGoAutonomousMsg, &fsm_control);
    lcm.subscribe(arm_for_takeoff_channel, &StateMachineControl::ProcessArmForTakeoffMsg, &fsm_control);

    omp_set_num_threads(3); // set the maximum number of threads
                            // to be 1 less than our number of
                            // cores so we never slow down
                            // the tvlqr process


    printf("Receiving LCM:\n\tPose: %s\n\tStereo: %s\n\tRC Trajectories: %s\n\tGo Autonomous: %s\n\tArm for Takeoff: %s\n\nSending LCM:\n\tTVLQR Action: %s\n\tState Machine State: %s\n\tAltitude reset: %s\n", pose_channel.c_str(), stereo_channel.c_str(), rc_trajectory_commands_channel.c_str(), state_machine_go_autonomous_channel.c_str(), arm_for_takeoff_channel.c_str(), tvlqr_action_out_channel.c_str(), state_message_channel.c_str(), altitude_reset_channel.c_str());

    while (true) {
        while (NonBlockingLcm(lcm.getUnderlyingLCM())) {}

        fsm_control.DoDelayedImuUpdate();
    }

    return 0;
}
Esempio n. 17
0
Lisp_Object Llcm(Lisp_Object nil, Lisp_Object a, Lisp_Object b)
{
    a = lcm(a, b);
    errexit();
    return onevalue(a);
}
Esempio n. 18
0
int main(int argc, char ** argv)
{
    lcm::LCM lcm("udpm://224.0.0.251:7667?ttl=1");
    if(!lcm.good())
        return 1;

    exlcm::imu1 imu_data;

    time_t sta,stp;

    time(&sta);

    VN_ERROR_CODE errorCode;
    Vn100 vn100;
    VnYpr ypr;
    VnVector3 accel;
    VnVector3 angRate;
    long i;

    errorCode = vn100_connect(
        &vn100,
        COM_PORT,
        BAUD_RATE);
    
    /* Make sure the user has permission to use the COM port. */
    if (errorCode == VNERR_PERMISSION_DENIED) {

        printf("Current user does not have permission to open the COM port.\n");
        printf("Try running again using 'sudo'.\n");

        return 0;
    }
    else if (errorCode != VNERR_NO_ERROR)
    {
        printf("Error encountered when trying to connect to the sensor.\n");

        return 0;
    }    

    for (i = 1; i > 0; i++)
    {
        
        /* Query the YawPitchRoll register of the VN-100. Note this method of
           retrieving the attitude is blocking since a serial command will be
           sent to the physical sensor and this program will wait until a
           response is received. */
        errorCode = vn100_getYawPitchRoll(&vn100, &ypr);
        errorCode = vn100_getAcceleration(&vn100, &accel);
        errorCode = vn100_getAngularRate(&vn100, &angRate);

        imu_data.timestamp = i;

        imu_data.name = "IMU Data";

        imu_data.orientation[0] = ypr.yaw;
        imu_data.orientation[1] = ypr.pitch;
        imu_data.orientation[2] = ypr.roll;

        imu_data.linAcc[0] = accel.c0;
        imu_data.linAcc[1] = accel.c1;
        imu_data.linAcc[2] = accel.c2;

        imu_data.angAcc[0] = angRate.c0;
        imu_data.angAcc[1] = angRate.c1;
        imu_data.angAcc[2] = angRate.c2;
        
        imu_data.enabled = true;

        lcm.publish("IMU_DATA", &imu_data);
        
        //printf("  %+#7.2f %+#7.2f %+#7.2f\t\t", ypr.yaw, ypr.pitch, ypr.roll);
        //printf("  %+#7.2f %+#7.2f %+#7.2f\t\t", accel.c0, accel.c1, accel.c2);
        //printf("  %+#7.2f %+#7.2f %+#7.2f\n", angRate.c0, angRate.c1, angRate.c2);
        
        /* Wait for 1 second before we query the sensor again. */
        sleep(0.5);
        
    }
    
    time(&stp); 
    printf("Duration = %f\n",difftime(stp,sta));
    
    errorCode = vn100_disconnect(&vn100);
    
    if (errorCode != VNERR_NO_ERROR)
    {
        printf("Error encountered when trying to disconnect from the sensor.\n");
        
        return 0;
    }        

    return 0;
}
Esempio n. 19
0
inline T lcm (const T& a, const T& b)
{
    return lcm(a, b, factory<T>());
}
Esempio n. 20
0
int main()
{
    int i,j,k,r,c,a[MAX][MAX],b[MAX][MAX],det=1,l,d1,d2;
    printf("\nEnter the number of Rows of the Matrix: ");
    scanf("%d",&r);
    printf("\nEnter the number of Columns of the Matrix: ");
    scanf("%d",&c);
    if(r==c)
    {
       printf("\nEnter the Elements of the Matrix:\n");
       for(i=0;i<r;i++)
       {
          for(j=0;j<c;j++)
          {
             scanf("%d",&a[i][j]);
          }
       }
       for(i=0;i<r-1;i++)
       {
           for(j=i+1;j<r;j++)
           {
             l=lcm(a[i][i],a[j][i]);
             if(l!=0&&(a[i][i]!=0&&a[j][i]!=0))
             {
               l=(a[i][i]*a[j][i])/l;
               d1=l/a[i][i];
               d2=l/a[j][i];
               a[j][i]=0;
               for(k=i+1;k<r;k++)
               {
                 a[j][k]=(d2*a[j][k])-(d1*a[i][k]);
               }
             }
           }
        }
        printf("\nThe given Matrix after Gauss Elimination is:\n");
        for(i=0;i<r;i++)
        {
          for(j=0;j<c;j++)
          {
             printf("%d\t",a[i][j]);
          }
          printf("\n");
        }
        for(i=r-1;i>0;i--)
        {
           for(j=i-1;j>=0;j--)
           {
             l=lcm(a[i][i],a[j][i]);
             if(l!=0&&(a[i][i]!=0&&a[j][i]!=0))
             {
               l=(a[i][i]*a[j][i])/l;
               d1=l/a[i][i];
               d2=l/a[j][i];
               for(k=0;k<=r;k++)
               {
                 a[j][k]=(d2*a[j][k])-(d1*a[i][k]);
               }
             }
           }
        }
        printf("\nThe given Matrix after Gauss Jordan Elimination is:\n");
        for(i=0;i<r;i++)
        {
          for(j=0;j<c;j++)
          {
             printf("%d\t",a[i][j]);
          }
          printf("\n");
        }
     }
     else
     {
        printf("\nThis is not a Square Matrix!!!\n");
     }
     return 0;
}
Esempio n. 21
0
inline T lcm (const vector<T, REFCNT>& x)
{
    return lcm(x, factory<T>());
}
Esempio n. 22
0
int
addresslist_append6(struct addresslist *adrlist, uint8_t proto,
    struct in6_addr *saddr_begin, struct in6_addr *saddr_end,
    struct in6_addr *daddr_begin, struct in6_addr *daddr_end,
    uint16_t sport_begin, uint16_t sport_end,
    uint16_t dport_begin, uint16_t dport_end)
{
	struct address_tuple *newtuple;
	struct in6_addr saddr, daddr;
	uint16_t sport, dport;
	uint64_t saddr_num, daddr_num, sport_num, dport_num;
	uint64_t addr_num, port_num;
	uint64_t tuple_num, n;

	saddr_num = ipv6_sub(saddr_end, saddr_begin) + 1;
	daddr_num = ipv6_sub(daddr_end, daddr_begin) + 1;
	sport_num = sport_end - sport_begin+ 1;
	dport_num = dport_end - dport_begin+ 1;

	addr_num = lcm(saddr_num, daddr_num);
	port_num = lcm(sport_num, dport_num);
	tuple_num = lcm(addr_num, port_num);

	if (adrlist->tuple_limit < (adrlist->ntuple + tuple_num)) {
		fprintf(stderr, "too large flowlist: %lu: [%s-%s]:%d-%d - [%s-%s]:%d-%d\n",
		    adrlist->ntuple + tuple_num,
		    ip6_sprintf(saddr_begin), ip6_sprintf(saddr_end),
		    sport_begin, sport_end,
		    ip6_sprintf(daddr_begin), ip6_sprintf(daddr_end),
		    dport_begin, dport_end);
		return -1;
	}

	if (adrlist->tuple == NULL) {
		newtuple = malloc(sizeof(struct address_tuple) * tuple_num);
		memset(newtuple, 0, sizeof(struct address_tuple) * tuple_num);
	} else {
		newtuple = realloc(adrlist->tuple, sizeof(struct address_tuple) * (adrlist->ntuple + tuple_num));
		memset(newtuple + adrlist->ntuple, 0, sizeof(struct address_tuple) * tuple_num);
	}

	if (newtuple == NULL) {
		fprintf(stderr, "Cannot allocate memory. number of session is %lu\n", adrlist->ntuple + tuple_num);
		return -1;
	}

	adrlist->tuple = newtuple;

	saddr = *saddr_begin;
	daddr = *daddr_begin;
	sport = sport_begin;
	dport = dport_begin;

	for (n = 0; n < tuple_num; ) {
		if (exists_in_addresses(AF_INET, &saddr, adrlist->exclude_saddr, adrlist->exclude_saddr_num) ||
		    exists_in_addresses(AF_INET, &daddr, adrlist->exclude_daddr, adrlist->exclude_daddr_num)) {
			tuple_num--;
		} else {
			newtuple[adrlist->ntuple + n].saddr.af = AF_INET6;
			newtuple[adrlist->ntuple + n].saddr.a.addr6 = saddr;
			newtuple[adrlist->ntuple + n].daddr.af = AF_INET6;
			newtuple[adrlist->ntuple + n].daddr.a.addr6 = daddr;
			newtuple[adrlist->ntuple + n].sport = sport;
			newtuple[adrlist->ntuple + n].dport = dport;
			newtuple[adrlist->ntuple + n].proto = proto;

			l2random(&newtuple[adrlist->ntuple + n].saddr.a.addr6,
			    sizeof(newtuple[adrlist->ntuple + n].saddr.a.addr6),
			    &newtuple[adrlist->ntuple + n].seaddr);
			l2random(&newtuple[adrlist->ntuple + n].daddr.a.addr6,
			    sizeof(newtuple[adrlist->ntuple + n].daddr.a.addr6),
			    &newtuple[adrlist->ntuple + n].deaddr);

			n++;
		}

		/* increment addresses and ports */
		if (ipv6_equal(&saddr, saddr_end))
			saddr = *saddr_begin;
		else
			ipv6_increment(&saddr);

		if (ipv6_equal(&daddr, daddr_end))
			daddr = *daddr_begin;
		else
			ipv6_increment(&daddr);

		if (sport == sport_end)
			sport = sport_begin;
		else
			sport++;

		if (dport == dport_end)
			dport = dport_begin;
		else
			dport++;
	}

	adrlist->ntuple += tuple_num;
	adrlist->sorted = 0;
	return 0;
}
Esempio n. 23
0
int main() {
	int a, b;
	scanf("%d %d", &a, &b);
	printf("GCD = %d\n", gcd(a, b));
	printf("LCM = %d", lcm(a, b));
}
    // Construct
    void LanczosResizerImpl<ArchAVX2FMA>::init(
        unsigned int degree,
        size_t srcW, size_t srcH,
        size_t dstW, size_t dstH,
        size_t pxScale
    ) {
        m_SrcW = int32_t(srcW);
        m_SrcH = int32_t(srcH);
        m_DstW = int32_t(dstW);
        m_DstH = int32_t(dstH);

        // setup coefficients
        int32_t gcdW = int32_t(gcd(m_SrcW, m_DstW));
        int32_t gcdH = int32_t(gcd(m_SrcH, m_DstH));
        int32_t rSrcW = m_SrcW / gcdW;
        int32_t rDstW = m_DstW / gcdW;
        int32_t rSrcH = m_SrcH / gcdH;
        int32_t rDstH = m_DstH / gcdH;
        int64_t alignedW  = alignCeil<int32_t>(m_DstW, kVecStepX);
        int64_t unrolledW = lcm(rDstW, kVecStepX);
        m_NumCoefsX = int32_t(calcNumCoefsForLanczos(degree, rSrcW, rDstW, pxScale));
        m_NumCoefsY = int32_t(calcNumCoefsForLanczos(degree, rSrcH, rDstH, pxScale));
        m_NumCoordsX = rDstW;
        m_NumUnrolledCoordsX = int32_t(std::min(alignedW, unrolledW));
        m_NumUnrolledCoordsX /= kVecStepX;
        m_TablesXWidth = kVecStepX * m_NumCoefsX;
        m_NumCoordsY = rDstH;
        size_t alignedTblXSize = size_t(m_TablesXWidth) * m_NumUnrolledCoordsX + kVecStepX;
        m_TablesX_.reserve(alignedTblXSize);
        m_TablesX_.resize(alignedTblXSize);
        intptr_t addrTablesX_ = intptr_t(&m_TablesX_[0]);
        intptr_t addrTablesX  = alignCeil<intptr_t>(addrTablesX_, sizeof(*m_TablesX) * kVecStepX);
        m_TablesX = reinterpret_cast<float *>(addrTablesX);
        size_t tblYSize = size_t(m_NumCoefsY) * m_NumCoordsY;
        m_TablesY.reserve(tblYSize);
        m_TablesY.resize(tblYSize);

        // X coefs
        std::vector<float> tablesX(m_NumCoefsX * m_NumCoordsX);
        for ( int32_t dstX = 0; dstX < m_NumCoordsX; ++dstX ) {
            float * table = &tablesX[dstX * m_NumCoefsX];
            float sumCoefs = setLanczosTable(degree, rSrcW, rDstW, dstX, pxScale, m_NumCoefsX, table);
            for ( int32_t i = 0; i < m_NumCoefsX; i++ ) {
                table[i] /= sumCoefs;
            }
        }

        // unroll X coefs
        //
        //      srcX: A B C    (upto m_NumCoordsX)
        //    coef #: 0 1 2 3
        //   tablesX: A0A1A2A3
        //            B0B1B2B3
        //            C0C1C2C3
        //
        //      srcX: ABCA BCAB CABC (upto m_NumUnrolledCoordsX; unroll to kVecStepX)
        // m_TablesX: A0B0C0A0 .. A3B3C3A3
        //            B0C0A0B0 .. B3C3A3B3
        //            C0A0B0C0 .. C3A3B3C3
        //
        // other cases
        //
        //      srcX: A B         -> ABAB
        //      srcX: A B C D E   -> ABCD EABC DEAB CDEA BCDE
        //      srcX: A B C D E F -> ABCD EFAB CDEF
        ptrdiff_t nCoefs  = m_NumCoefsX;
        ptrdiff_t nCoords = m_NumCoordsX;
        ptrdiff_t nCols   = m_TablesXWidth;
        ptrdiff_t nRows   = m_NumUnrolledCoordsX;
        for ( ptrdiff_t row = 0; row < nRows; ++row ) {
            for ( ptrdiff_t col = 0; col < nCols; ++col ) {
                ptrdiff_t iCoef = col/kVecStepX;
                ptrdiff_t srcX = (col%kVecStepX + row*kVecStepX) % nCoords;
                m_TablesX[col + nCols*row] = tablesX[iCoef + srcX*nCoefs];
            }
        }

        // Y coefs
        std::vector<float> tablesY(m_NumCoefsY);
        for ( int32_t dstY = 0; dstY < m_NumCoordsY; ++dstY ) {
            float * table = &m_TablesY[dstY * m_NumCoefsY];
            float sumCoefs = setLanczosTable(degree, rSrcH, rDstH, dstY, pxScale, m_NumCoefsY, table);
            for ( int32_t i = 0; i < m_NumCoefsY; ++i ) {
                table[i] /= sumCoefs;
            }
        }

        // allocate workspace
        m_WorkW = alignCeil<int32_t>(m_SrcW, kVecStepY);
        int32_t workSize = m_WorkW * HWCap::getNumberOfProcs();
        m_Work = alignedAlloc<float>(workSize, sizeof(*m_Work) * kVecStepY);

        // calc indices
        int32_t alignedDstW = alignCeil<int32_t>(m_DstW, kVecStepX);
        m_IndicesX.reserve(alignedDstW);
        m_IndicesX.resize(alignedDstW);
        for ( int32_t dstX = 0; dstX < alignedDstW; ++dstX ) {
            //      srcOX = floor(dstX / scale)
            int32_t srcOX = int32_t(int64_t(dstX) * rSrcW / rDstW + 1);
            m_IndicesX[dstX] = srcOX;
        }
    }
Esempio n. 25
0
/* Generates the process definition for this leaf-node. */
int __htree_task_def(__htree_node_t *node) {
    int i, j, k, l;
    if (pattern_matrix[node->ptype][node->stype] == 0) {
        printf("Error\n");
        return -1;
    }
    if ((node->sol.n > 0) && (node->sil.n > 0))
        l = lcm(node->sol.n, node->sil.n);
    else
        l = node->sol.n + node->sil.n;
    if (latex) {
        sprintf (temp, "t_{%d} & \\rmdef & ", node->index);
        strcat(process, temp);
    }
    fprintf(output_file, "t_%d = \t", node->index);
    switch(pattern_matrix[node->ptype][node->stype]) {
    case 1:
    case 2:
        for (i = 0; i < l; i++) {
            k = node->sil.l[i % node->sil.n];
            if (latex) {
                sprintf(temp, "(comp_{%d}, %f).(move_{%d,%d}, \\infty).%s",
                        node->index, node->rate, node->index, k,
                        ((l > 1) && (i < l - 1)) ? "\\\\&&" : "");
                strcat(process, temp);
            }
            fprintf(output_file, "(comp_%d, %f).(move_%d_%d, infty).%s",
                    node->index, node->rate, node->index, k,
                    ((l > 1) && (i < l - 1)) ? "\n\t" : "");
        }
        break;
    case 4:
    case 8:
        for (i = 0; i < l; i++) {
            j = node->sol.l[i % node->sol.n];
            if (latex) {
                sprintf(temp, "(move_{%d,%d}, \\infty).(comp_{%d}, %f).%s",
                        j, node->index, node->index, node->rate,
                        ((l > 1) && (i < l - 1)) ? "\\\\&&" : "");
                strcat(process, temp);
            }
            fprintf(output_file, "(move_%d_%d, infty).(comp_%d, %f).%s",
                    j, node->index, node->index, node->rate,
                    ((l > 1) && (i < l - 1)) ? "\n\t" : "");
        }
        break;        
    case 5:
    case 6:
    case 9:
    case 10:
        for (i = 0; i < l; i++) {
            k = node->sil.l[i % node->sil.n];
            j = node->sol.l[i % node->sol.n];
            if (latex) {
                sprintf(temp, "(move_{%d,%d}, \\infty).(comp_{%d}, %f)."
                        "(move_{%d,%d}, \\infty).%s",
                        j, node->index, node->index, node->rate, node->index, k,
                        ((l > 1) && (i < l - 1)) ? "\\\\&&" : "");
                strcat(process, temp);
            } 
            fprintf(output_file, "(move_%d_%d, infty).(comp_%d, %f)."
                    "(move_%d_%d, infty).%s",
                    j, node->index, node->index, node->rate, node->index, k,
                    ((l > 1) && (i < l - 1)) ? "\n\t" : "");
        }
        break;        
    case 3:
        if (latex) {
            sprintf(temp, "(comp_{%d}, %f).t_{%d}^{0};\\\\"
                    "t_{%d}^{0} & \\rmdef & "
                    "(move_{%d,%d}, \\infty).t_{%d}",
                    node->index, node->rate, node->index, node->index,
                    node->index, node->sil.l[0], node->index);
            strcat(process, temp);
            for (i = 1; i < node->sil.n; i++) {
                sprintf(temp, "\\\\&&+ (move_{%d,%d}, \\infty).",
                        node->index, node->sil.l[i % node->sil.n]);
                strcat(process, temp);
                if ((node->sil.n > 1) && (i < node->sil.n - 1)) {
                    sprintf(temp, "t_{%d}", node->index);
                    strcat(process, temp);
                }
            }
        }
        fprintf(output_file, "(comp_%d, %f).t_%d_0;\nt_%d_0 = "
                "(move_%d_%d, infty).t_%d",
                node->index, node->rate, node->index, node->index,
                node->index, node->sil.l[0], node->index);
        for (i = 1; i < node->sil.n; i++) {
            fprintf(output_file, "\n\t+ (move_%d_%d, infty).",
                    node->index, node->sil.l[i % node->sil.n]);
            if ((node->sil.n > 1) && (i < node->sil.n - 1))
                fprintf(output_file, "t_%d", node->index);
        }
        break;
    case 12:
        if (latex) {
            sprintf(temp, "(move_{%d,%d}, \\infty).t_{%d}^{0}",
                    node->sol.l[0], node->index, node->index);
            strcat(process, temp);
            for (i = 1; i < node->sol.n; i++) {
                sprintf(temp, "\\\\&&+ (move_{%d,%d}, \\infty).t_{%d}^{0}",
                        node->sol.l[i], node->index, node->index);
                strcat(process, temp);
            }
            sprintf(temp, ";\\\\t_{%d}^{0} & \\rmdef & (comp_{%d}, %f).",
                    node->index, node->index, node->rate);
            strcat(process, temp);
        }
        fprintf(output_file, "(move_%d_%d, infty).t_%d_0",
                node->sol.l[0], node->index, node->index);
        for (i = 1; i < node->sol.n; i++) {
            fprintf(output_file, "\n\t+ (move_%d_%d, infty).t_%d_0",
                    node->sol.l[i], node->index, node->index);
        }
        fprintf(output_file, ";\nt_%d_0 = (comp_%d, %f).",
                node->index, node->index, node->rate);
        break;
    case 7:
    case 11:
        if (latex) {
            for (i = 0; i < node->sol.n; i++) {
                sprintf(temp,
                        "(move_{%d,%d}, \\infty).(comp_{%d}, %f).t_{%d}^{%d};\\\\"
                        "t_{%d}^{%d} & \\rmdef & (move_{%d,%d}, \\infty).",
                        node->sil.l[i], node->index, node->index, node->rate,
                        node->index, i, node->index, i, node->index, node->sil.l[0]);
                strcat(process, temp);
                if (i < node->sol.n - 1)
                    sprintf(temp, "t_{%d}^{%d}",    node->index, i+1);
                else
                    sprintf(temp, "t_{%d}", node->index);
                strcat(process, temp);
                for (j = 1; j < node->sil.n; j++) {
                    sprintf(temp,
                            "\\\\&&+ (move_{%d,%d}, \\infty).",
                            node->index, node->sil.l[j]);
                    strcat(process, temp);
                    if (i < node->sol.n - 1) {
                        sprintf(temp, "t_{%d}^{%d}", node->index, i+1);
                        strcat(process, temp);
                    } else {
                        if (j < node->sil.n - 1) {
                            sprintf(temp, "t_{%d}", node->index);
                            strcat(process, temp);
                        }
                    }
                }
            }
        }
        for (i = 0; i < node->sol.n; i++) {
            fprintf(output_file,
                    "(move_%d_%d, infty).(comp_%d, %f).t_%d_%d;\n"
                    "t_%d_%d = (move_%d_%d, infty).",
                    node->sil.l[i], node->index, node->index, node->rate,
                    node->index, i, node->index, i, node->index, node->sil.l[0]);
            if (i < node->sol.n - 1)
                fprintf(output_file, "t_%d_%d",    node->index, i+1);
            else
                fprintf(output_file, "t_%d", node->index);
            for (j = 1; j < node->sil.n; j++) {
                fprintf(output_file,
                        "\n\t+ (move_%d_%d, infty).",
                        node->index, node->sil.l[j]);
                if (i < node->sol.n - 1)
                    fprintf(output_file, "t_%d_%d",    node->index, i+1);
                else {
                    if (j < node->sil.n - 1)
                        fprintf(output_file, "t_%d", node->index);
                }
            }
        }
        break;
    case 13:
    case 14:
        if (latex) {
            for (i = 0, k = 0; i < node->sil.n; i++) {
                sprintf(temp,
                        "(move_{%d,%d}, \\infty).t_{%d}^{%d}",
                        node->sol.l[0], node->index, node->index, k);
                strcat(process, temp);
                for (j = 1; j < node->sol.n; j++) {
                    sprintf(temp,
                            "\\\\&&+ (move_{%d,%d}, \\infty).t_{%d}^{%d}",
                            node->sol.l[j], node->index, node->index, k);
                    strcat(process, temp);
                }
                sprintf(temp,
                        ";\\\\t_{%d}^{%d} & \\rmdef & "
                        "(comp_{%d}, %f).(move_{%d,%d}, \\infty).",
                        node->index, k, node->index, node->rate,
                        node->index, node->sil.l[i]);
                strcat(process, temp);
                if (i < node->sil.n - 1) {
                    sprintf(temp, "t_{%d}^{%d};\\\\"
                            "t_{%d}^{%d} & \\rmdef & ",
                            node->index, k+1, node->index, k+1);
                    strcat(process, temp);
                }
                k += 2;
            }
        }
        for (i = 0, k = 0; i < node->sil.n; i++) {
            fprintf(output_file,
                    "(move_%d_%d, infty).t_%d_%d",
                    node->sol.l[0], node->index, node->index, k);
            for (j = 1; j < node->sol.n; j++) {
                fprintf(output_file,
                        "\n\t+ (move_%d_%d, infty).t_%d_%d",
                        node->sol.l[j], node->index, node->index, k);
            }
            fprintf(output_file,
                    ";\nt_%d_%d = (comp_%d, %f).(move_%d_%d, infty).",
                    node->index, k, node->index, node->rate,
                    node->index, node->sil.l[i]);
            if (i < node->sil.n - 1) {
                fprintf(output_file, "t_%d_%d;\nt_%d_%d = ",
                        node->index, k+1, node->index, k+1);
            }
            k += 2;
        }
        break;
    case 15:
        if (latex) {
            sprintf(temp, 
                    "(move_{%d,%d}, \\infty).(comp_{%d}, %f).t_{%d}^{0}",
                    node->sol.l[0], node->index, node->index,
                    node->rate, node->index);
            strcat(process, temp);
            for (i = 1; i < node->sol.n; i++) {
                sprintf(temp, 
                        "\\\\&&+ (move_{%d,%d}, \\infty).(comp_{%d}, %f).t_{%d}^{0}",
                        node->sol.l[i], node->index, node->index,
                        node->rate, node->index);
                strcat(process, temp);
            }
            sprintf(temp, 
                    ";\\\\t_{%d}^{0} & \\rmdef & (move_{%d,%d}, \\infty).",
                    node->index, node->index, node->sil.l[0]);
            strcat(process, temp);
            for (i = 1; i < node->sil.n; i++) {
                sprintf(temp, 
                        "t_{%d}\\\\&&+ (move_{%d,%d}, \\infty).",
                        node->index, node->index, node->sil.l[i]);
                strcat(process, temp);
            }
        }
        fprintf(output_file,
                "(move_%d_%d, infty).(comp_%d, %f).t_%d_0",
                node->sol.l[0], node->index, node->index,
                node->rate, node->index);
        for (i = 1; i < node->sol.n; i++) {
            fprintf(output_file,
                    "\n\t+ (move_%d_%d, infty).(comp_%d, %f).t_%d_0",
                    node->sol.l[i], node->index, node->index,
                    node->rate, node->index);
        }
        fprintf(output_file,
                ";\nt_%d_0 = (move_%d_%d, infty).",
                node->index, node->index, node->sil.l[0]);        
        for (i = 1; i < node->sil.n; i++) {
            fprintf(output_file,
                    "t_%d\n\t+ (move_%d_%d, infty).",
                    node->index, node->index, node->sil.l[i]);
        }
        break;
    }
    if (latex) {
        sprintf(temp, "t_{%d};\\\\\n", node->index);
        strcat(process, temp);
    }
    fprintf(output_file, "t_%d;\n", node->index);
    return 0;
}
Esempio n. 26
0
int main () {
    int a = 18, b = 84;
    printf("gcd(%d, %d) = %d\n", a, b, gcd(a, b));
    printf("lcm(%d, %d) = %d\n", a, b, lcm(a, b));
}
Esempio n. 27
0
int main() {
  std::cout << gcd(9, 6) << std::endl;
  std::cout << lcm(9, 6) << std::endl;
  std::cout << gcd(1071, 1029) << std::endl;
  std::cout << lcm(1071, 1029) << std::endl;
}
Esempio n. 28
0
CNode* VariableEliminator::apply_cooper(Clause& cl, Term* evar,
		set<ILPLeaf*>& positive, set<ILPLeaf*>& negative)
{
	if(DEBUG){
		cout << "Applying Cooper's method..." << cl.to_string("&") <<
		"to eliminate " << evar->to_string() << endl;
	}
	set<CNode*> new_constraints;
	set<ILPLeaf*>::iterator pos_it = positive.begin();
	for(; pos_it!= positive.end(); pos_it++)
	{
		ILPLeaf* pos_ilp = *pos_it;
		long int pos_coef = pos_ilp->get_coefficient(evar);
		set<ILPLeaf*>::iterator neg_it = negative.begin();
		for(; neg_it != negative.end(); neg_it++)
		{
			ILPLeaf* neg_ilp = *neg_it;
			long int neg_coef = neg_ilp->get_coefficient(evar);
			long int pos_neg_lcm = lcm(pos_coef, neg_coef);
			long int pos_factor = labs(pos_neg_lcm/pos_coef);
			long int neg_factor = labs(pos_neg_lcm/neg_coef);


			CNode* _pos_ilp = pos_ilp->multiply(pos_factor);
			_pos_ilp = _pos_ilp->fold_negated_ilps();
			assert(_pos_ilp->get_type() == ILP);
			ILPLeaf* pos_ilp = (ILPLeaf*) _pos_ilp;


			CNode* _neg_ilp = neg_ilp->multiply(neg_factor);
			_neg_ilp = _neg_ilp->fold_negated_ilps();
			assert(_neg_ilp->get_type() == ILP);
			neg_ilp = (ILPLeaf*) _neg_ilp;
			CNode* new_node = pos_ilp->add(neg_ilp);
			new_node = new_node->fold_negated_ilps();

			if(new_node->get_type() == FALSE_NODE){
				return False::make();
			}

			if(track_new_inequalities) {
				add_new_inequality(evar, pos_ilp, neg_ilp);
			}


			if(pos_neg_lcm > LCM_LIMIT){
				large_lcm = true;
				cerr << "Large LCM in existential quantifier elimination --"
						"INTRODUCINGS *LOTS OF* DISJUNCTS" << endl;
				cerr << "Original constraint: " << orig_c->to_string() << endl;
				cerr << "Var to eliminate: " << evar->to_string() << endl;
				cerr << "Current clause: " << cl.to_string("&") << endl;
				//assert(false);
				return True::make();
			}
			set<CNode*> to_or;
			vector<CNode*> divisibility_vec;
			set<CNode*> divisibility_set;
			map<Term*, long int> new_elems = neg_ilp->get_elems();
			new_elems.erase(evar);
			long int new_constant = -neg_ilp->get_constant();

			Term* t=ArithmeticTerm::make(new_elems,new_constant);


			for(int i=0; i<pos_neg_lcm; i++){
				Term* cur_t = t->add(i);
				CNode* ml = ModLeaf::make(cur_t,pos_neg_lcm,(long int)0);
				divisibility_set.insert(ml);
				divisibility_vec.push_back(ml);
			}

			if(new_node->get_type() == TRUE_NODE)
			{
				CNode* divisibility_node = Connective::make_or(divisibility_set);
				new_constraints.insert(divisibility_node);
				continue;
			}

			assert(new_node->get_type() == ILP);
			ILPLeaf* ilp = (ILPLeaf*) new_node;
			assert(ilp->get_operator() == ILP_LEQ);
			const map<Term*, long int>& elems = ilp->get_elems();
			long int ilp_constant = ilp->get_constant();
			for(int i=0;i<pos_neg_lcm;i++){
				CNode* cur_ilp = ILPLeaf::make(ILP_LEQ, elems, ilp_constant-i);
				CNode* mod_c = divisibility_vec[i];
				CNode* and_c = Connective::make(AND, cur_ilp, mod_c);
				to_or.insert(and_c);
			}
			CNode* or_c = Connective::make_or(to_or);
			new_constraints.insert(or_c);

		}
	}

	set<ILPLeaf*>::iterator it = positive.begin();
	for(; it!= positive.end(); it++){
		cl.pos_ilp.erase(*it);
	}
	it = negative.begin();
	for(; it!= negative.end(); it++){
		cl.pos_ilp.erase(*it); //this is not a mistake --negative refers to sign
	}
	CNode* orig = cl.to_cnode();
	new_constraints.insert(orig);
	CNode* res = Connective::make_and(new_constraints);
	return res;
}
Esempio n. 29
0
bool Fraction::operator!=(const Fraction& val) const
{
    const int v = lcm(_denominator, val._denominator);
    return (_numerator * (v / _denominator)) != (val._numerator * (v / val._denominator));
//      return (_numerator != val._numerator) || (_denominator != val._denominator);
}