示例#1
0
文件: ps1.c 项目: cristeahub/komptek
// Return a (dynamically allocated) array of length size,
// filled with random numbers between 0 and n
int* create_random_array(int size, int n){
    int *random_array = (int*)malloc(size * sizeof(int));

    for(int i = 0; i < size; i++) {
        random_array[i] = get_random_number(n);
    }

    return random_array;
}
示例#2
0
文件: array.c 项目: givanse/snipe
/**
 * Shuffle an array of pointers.
 */
void array_shuffle(int arrSize, void **ptrsArr) {        
    /* Fisher & Yates shuffle, modern version (Knuth) */                         
    int i;                                                                       
    for(i = arrSize - 1; i >= 1; i--) {                                        
        /* j ← random integer with 0 ≤ j ≤ i */                                  
        int j = get_random_number(0, i);                                         
        /* exchange a[j] and a[i] */                                             
        void *tmp = ptrsArr[i];                                            
        ptrsArr[i] = ptrsArr[j];                                     
        ptrsArr[j] = tmp;                                                  
    }                                                                            
}   
示例#3
0
bool RayTracer::depth_of_field(int i, int j, SbVec3f *position, SbVec3f *color){
    //SbVec3f pix_pos, d_vec;
    SbVec3f tempColor;
    float R = DISK_SIZE;
    float du;
    float dv;
    bool should_color ;
    int number_of_jitter_positions = NUMBER_OF_CAMERAS;

    if(depth_of_field_on == 0) {
          //  std::cout<<"No Depth of field";
            //depth of field off
            //pix_pos = calculate_pixel_location(i,j, 0.5, 0.5);
           // d_vec  = pix_pos - *position;
           // d_vec.normalize();
            should_color = distribute_shade(i,j, position, color);
    }
    else{
        for(int k =0; k< number_of_jitter_positions ; k++){
            SbVec3f camera_position = *position;
            du = get_random_number();
            dv = get_random_number();
            //du = (du ) * R;
            //dv = (dv ) * R;
            //std::cout<<pixel_height<<pixel_width <<std::endl;
            //camera_position = camera_position  + (du * R * this->u) + (dv * R * this->v);
            camera_position = camera_position  + (du * R * pixel_width * this->u) + (dv * pixel_height * R * this->v);
            //pix_pos = calculate_pixel_location(i,j, 0.5, 0.5);
            //d_vec  = pix_pos - (camera_position);
            //d_vec.normalize();
            tempColor.setValue(0.0,0.0,0.0);
            should_color = distribute_shade(i, j, &camera_position,&tempColor);
            *color = *color + tempColor;
        }
        *color = *color/number_of_jitter_positions ;

    }
    return should_color;

}
示例#4
0
int AntColony::realize_probability(const ant_t& ant, const std::vector<CityProbability>& prob)
{
	double reailized = static_cast<double>(get_random_number(RAND_MAX)) / RAND_MAX;
	double commulated_prob = 0;

	for (const auto& p : prob)
	{
		commulated_prob += p.get_probability();
		if (commulated_prob > reailized) return p.get_city_num();
	}

	return prob[prob.size() - 1].get_city_num();
}
示例#5
0
文件: wkill.c 项目: niclashoyer/wkill
void printstr(char *str, ...) {
	if (arguments.silent) {
		int i = get_random_number(silentstrlength);
		printf("%s\n", silentstr[i]);
		return;
	}

	if (!arguments.quiet) {
		va_list ap;
		va_start (ap, str);
		vfprintf (stdout, str, ap);
		va_end (ap);
	}
}
示例#6
0
// Allocate a matrix of dimensions height*width
//	If init == 0, initialize to all zeroes.  
//	If init == 1, perform random initialization.
Matrix allocate_matrix(int num_rows, int num_columns, int init){
    	Matrix M;
    	M.num_columns = M.pitch = num_columns;
    	M.num_rows = num_rows;
    	int size = M.num_rows * M.num_columns;
		
	M.elements = (float*) malloc(size*sizeof(float));
	for(unsigned int i = 0; i < size; i++){
		if(init == 0) M.elements[i] = 0; 
		else
			M.elements[i] = get_random_number(MIN_NUMBER, MAX_NUMBER);
	}
    return M;
}	
示例#7
0
TEST_F(board_test, new_randoms) {
    //given
    board b(4, 4, 3, 5, irandom_mock_,
        {
            none   , yellow , green  , purple
          , none   , green  , blue   , black
          , purple , green  , yellow , purple
          , blue   , blue   , green  , black
        }
    );
    std::vector<position> n{position(0, 0), position(0, 1)};

    //expect
    EXPECT_CALL(*irandom_mock_, get_random_number(GT::_, GT::_)).WillRepeatedly(GT::Return(black));

    //when
    auto new_randoms = b.new_randoms();

    //then
    EXPECT_EQ(n.size(), new_randoms.size());
    for (const auto& pos : n) {
        EXPECT_TRUE(new_randoms.find(pos) != new_randoms.end());
    }
}
示例#8
0
void lineofsight_output(void)
{
  char buf[500];
  int n, s, next;
  double ti;

  next = find_next_lineofsighttime(All.Ti_nextlineofsight);

  ti = All.TimeBegin * exp(next * All.Timebase_interval);

  if(ThisTask == 0)
    {
      printf("Line of sight output! ThisTask=%d Time=%g  NextTime=%g\n", ThisTask, All.Time, ti);
      fflush(stdout);
    }

  H_a = hubble_function(All.Time);
  Wmax = All.Time * H_a * All.BoxSize;


  if(ThisTask == 0)
    {
      sprintf(buf, "%s/los", All.OutputDir);
      mkdir(buf, 02755);
    }

  Los = mymalloc(sizeof(struct line_of_sight));
  LosGlobal = mymalloc(sizeof(struct line_of_sight));

  for(n = 0, s = 0; n < N_LOS; n++)
    {
      if(s + 3 >= RNDTABLE)
	{
	  set_random_numbers();
	  s = 0;
	}

      Los->zaxis = (int) (3.0 * get_random_number(s++));
      switch (Los->zaxis)
	{
	case 2:
	  Los->xaxis = 0;
	  Los->yaxis = 1;
	  break;
	case 0:
	  Los->xaxis = 1;
	  Los->yaxis = 2;
	  break;
	case 1:
	  Los->xaxis = 2;
	  Los->yaxis = 0;
	  break;
	}

      Los->Xpos = All.BoxSize * get_random_number(s++);
      Los->Ypos = All.BoxSize * get_random_number(s++);

#ifdef OUTPUTLINEOFSIGHT_SPECTRUM
      add_along_lines_of_sight();
      sum_over_processors_and_normalize();
      absorb_along_lines_of_sight();
      output_lines_of_sight(n);
#endif

#ifdef OUTPUTLINEOFSIGHT_PARTICLES
      find_particles_and_save_them(n);
#endif
    }

  myfree(LosGlobal);
  myfree(Los);
}
示例#9
0
bool RayTracer::shade(SbVec3f *ray_origin, SbVec3f *ray_direction, SbVec3f *retColor, int recursionDepth, int flag){
	float t_value, t_min = 999;
	float epsilon = 0.01;
	SbVec3f normal_at_intersection;
	SbVec3f normal_at_intersection1, actual_ray_direction ;
	bool should_color = false;
    SbVec3f color;
    color[0] = 0.0;
    color[1] = 0.0;
    color[2] = 0.0;
    //Cone *tempCone = new Cone();
    for(int k =0; k<objects.size(); k++){
        //Object temp1 ;
        //temp1 = spheres.at(k);
        Sphere tempSphere;
        Cube tempCube;
        Cone tempCone;
        Object temp;
        bool intersects = false;
        int shapetype = 0;
        shapetype = objects.at(k).shapeType ;
        if(shapetype == 1){
            tempSphere = objects.at(k);
            intersects = tempSphere.intersection(ray_origin, ray_direction, &t_value);
        }
        else if (shapetype ==2){
            //std::cout<<"cube";
            tempCube = objects.at(k);
            intersects = tempCube.intersection(ray_origin, ray_direction, &t_value);
            //temp = (Cube)tempCube;
        }else{
            tempCone = objects.at(k);
            intersects = tempCone.intersection(ray_origin, ray_direction, &t_value);

        }

        if(intersects)
        {
            if(t_value < t_min && t_value > 0 && t_value !=999) {
                t_min = t_value;
                SbVec3f V = -(*ray_direction); //view vector
                V.normalize();
                SbVec3f point_of_intersection ;

                if(shapetype == 1){
                    normal_at_intersection = tempSphere.calculate_normal(ray_origin, ray_direction, t_value);
                    normal_at_intersection.normalize(); // N vector at the point of intersection
                    point_of_intersection = tempSphere.point_of_intersection( ray_origin, ray_direction, t_value);
                    temp = tempSphere;
                }else if(shapetype == 2){
                    normal_at_intersection = tempCube.calculate_normal(ray_origin, ray_direction, t_value);
                    normal_at_intersection.normalize(); // N vector at the point of intersection
                    point_of_intersection = tempCube.point_of_intersection( ray_origin, ray_direction, t_value);
                    temp = tempCube;
                }
                else{
                    normal_at_intersection = tempCone.calculate_normal(ray_origin, ray_direction, t_value);
                    normal_at_intersection.normalize(); // N vector at the point of intersection
                    point_of_intersection = tempCone.point_of_intersection( ray_origin, ray_direction, t_value);
                    temp = tempCone;

                }


                for(int i = 0; i <3; i++) {// set the ambient color component
                        color[i] = (0.2 *  temp.material->ambientColor[0][i] * (1 - temp.transparency ));
                }
                //*retColor = color; return true;//ntc
                // iterate through all the lights and add the diffuse and specular component
                for(int j = 0; j < lights.size(); j++){
                        SbVec3f poi;

                        actual_ray_direction = lights.at(j).position - point_of_intersection ;
                        actual_ray_direction.normalize();
                        poi = point_of_intersection + (epsilon * actual_ray_direction);
                        bool shadowFlag = false;
                        if(shadow_on == 0 || shadow_on == 1)
                        {
                            if(shadow_on == 1)
                                shadowFlag = shadow_ray_intersection(&poi, &actual_ray_direction , j );
                            //shadowFlag = true;
                            if(!shadowFlag)
                            {
                                SbVec3f L = lights.at(j).position - point_of_intersection;
                                L.normalize();
                                SbVec3f R;
                                R = (2 * normal_at_intersection.dot(L) * normal_at_intersection) - L;
                                R.normalize();

                                float NdotL = normal_at_intersection.dot(L);
                                float cos_theta = V.dot(R);

                                for(int i = 0; i <3; i++){
                                    if(NdotL > 0)
                                        color[i] += (( NdotL * temp.material->diffuseColor[0][i] * lights.at(j).intensity * lights.at(j).color[i]  * (1 - temp.transparency )));
                                    if(cos_theta > 0)
                                        color[i] += (( pow(cos_theta, 50) * temp.material->specularColor[0][i]* lights.at(j).intensity * lights.at(j).color[i]) );
                                }
                            }
                        }
                    else
                    { // soft shadows
                            {

                         //shadowLevel = soft_shadow_ray_intersection(&point_of_intersection, j );
                            SbVec3f actual_ray_direction, offset_ray_direction;
                            SbVec3f tempu, tempv, tempn;
                            int number_of_shadow_rays;
                            number_of_shadow_rays = NUMBER_OF_SHADOW_RAYS;
                            float epsilon = 0.01;
                            float R = 0.1;
                            actual_ray_direction = lights.at(j).position - point_of_intersection ;
                            actual_ray_direction.normalize();
                            SbVec3f point = point_of_intersection + (epsilon * actual_ray_direction);

                            calculate_coordinate_system(&tempu, &tempv, &tempn, actual_ray_direction);

                            for(int ir =0; ir< number_of_shadow_rays; ir++){

                                    float du, dv;
                                    //float t;
                                    du = get_random_number();
                                    dv = get_random_number();
                                    du = R * (du - 0.5);
                                    dv = R * (dv - 0.5);
                                    offset_ray_direction = actual_ray_direction + (du * tempu) + (dv * tempv);
                                    offset_ray_direction.normalize();

                                    //offset_ray_direction = actual_ray_direction - (R/2 * u) - (R/2 * v) + (du * R * u) + (dv *R * v);
                                    SbVec3f poi;
                                    poi = point + (epsilon * offset_ray_direction);
                                    //offset_ray_direction = actual_ray_direction;
                                    if(!shadow_ray_intersection(&poi, &offset_ray_direction, j)){
                                        //normal_at_intersection = temp.calculate_normal(&poi, &offset_ray_direction, t_value);
                                        //normal_at_intersection.normalize();
                                        SbVec3f V = -1 * (*ray_direction); //view vector
                                        V.normalize();
                                        SbVec3f L = offset_ray_direction;
                                        L.normalize();
                                        SbVec3f R;
                                        R = (2 * normal_at_intersection.dot(L) * normal_at_intersection) - L;
                                        R.normalize();

                                        float NdotL = normal_at_intersection.dot(L);
                                        float cos_theta = V.dot(R);
                                        //if(temp.transparency > 0) std::cout<<"trnas";
                                        for(int i = 0; i <3; i++){
                                            {
                                                if(NdotL > 0)
                                                    color[i] += (( NdotL * temp.material->diffuseColor[0][i] * lights.at(j).intensity * lights.at(j).color[i]  * (1 - temp.transparency ))/ number_of_shadow_rays);
                                                if(cos_theta > 0)
                                                    color[i] += (( pow(cos_theta, 50) * temp.material->specularColor[0][i]* lights.at(j).intensity * lights.at(j).color[i]) / number_of_shadow_rays);
                                            }
                                        }

                                    }

                    }

                    }

                        }
                }
                SbVec3f refColor(0.0,0.0,0.0);
                SbVec3f refracColor(0.0,0.0,0.0);
                // if the current depth of recustion is less than the maximum depth,
                //reflect the ray and add the color returned dude to the result of reflection
                //std::cout<<"here";
                if(refraction_on && recursionDepth < 2){
                    if(temp.isTransparent){
                        SbVec3f T;
                        if(refract(ray_direction, &normal_at_intersection, &T)){
                            T.normalize();
                            SbVec3f poi;
                            poi = point_of_intersection + (epsilon * T);
                            shade(&poi, &T, &refracColor, recursionDepth+1);
                            color = color + (temp.transparency * refracColor);
                        }

                    }
                }
                if(reflection_on && recursionDepth < 2){

                    if(temp.isShiny){//} && !temp.isTransparent){
                        // compute replection of the ray, R1
                        SbVec3f R1;
                        R1 = reflect(&normal_at_intersection, ray_direction);
                        SbVec3f poi;
                        poi = point_of_intersection + (epsilon * R1);
                        shade(&poi, &R1, &refColor, recursionDepth+1);
                        color = color + ((1 - temp.transparency) * temp.shininess * refColor);

                    }
                }

                should_color = true;
            }

        }
    }
    *retColor = color;
    return should_color;
}
示例#10
0
int main(int argc, char *argv[])
{
    struct donut_ring *shared_ring;
    int i,j,k;
    int donuts[NUMFLAVORS][12];
    int counter[NUMFLAVORS];
    
    
    //Signal catching 
    sigset_t mask_sigs;
    int nsigs;
    struct sigaction new_action;
    int sigs[] = {SIGHUP,SIGINT,SIGQUIT,SIGBUS,SIGTERM,SIGSEGV,SIGFPE};
    nsigs = sizeof(sigs)/sizeof(int);
    sigemptyset(&mask_sigs);
    for (i = 0; i< nsigs ; i++)
    {
        sigaddset(&mask_sigs,sigs[i]);
    }
    for (i = 0; i < nsigs; i++)
    {
        new_action.sa_handler = sig_handler;
        new_action.sa_mask = mask_sigs;
        new_action.sa_flags = 0;
        
        if (sigaction (sigs[i],&new_action,NULL) == -1)
        {
            perror("can't set signals: ");
            exit(1);
        }
    }
    //shared memory
    if ((shmid = shmget(MEMKEY, sizeof (struct donut_ring), 0)) == -1)
    {
        perror("shared get failed: ");
        exit(1);
    }
    if ((shared_ring = shmat(shmid,NULL,0)) == (void *) -1)
    {
        perror("shared attach failed: ");
    }
    //shemaphores
    for (i = 0; i<NUMSEMIDS; i++)
    {
        if ((semid[i] = semget(SEMKEY+i, NUMFLAVORS, 0)) == -1)
        {
            perror("semaphore allocation failed: ");
        }
    }
    
    for (i = 0;i < 10; i++)
    {
        for (k = 0;k<NUMFLAVORS;k++)
        {
            counter[k] = 0;
        }
        for (k = 0;k<12;k++)
        {
            j = get_random_number();
            int donut_outptr;
            //take ticket
            if (p(semid[CONSUMER],j) == -1)
            {
                sig_handler(-1);
            }
            //lock the outptr
            if (p(semid[OUTPTR],j) == -1)
            {
                sig_handler(-1);
            }
            donuts[j][counter[j]] = shared_ring->flavor[j][shared_ring->outptr[j]];
            shared_ring->outptr[j]=(shared_ring->outptr[j] + 1) % NUMSLOTS;
            //unlock the outptr
            if (v(semid[OUTPTR],j) == -1)
            {
                sig_handler(-1);
            }
            //allow producer to make another donut in that slot
            if (v(semid[PROD],j) == -1)
            {
                sig_handler(-1);
            }
            printf("Donut: %d\tSerial Number: %d\n",j,donuts[j][counter[j]]);
            counter[j]++;
        }
        
        //print out of donut information
        struct timeval tv; 
        struct tm* ptm; 
        char time_string[40]; 
        long useconds; 
        gettimeofday (&tv, NULL); 
        ptm = localtime (&tv.tv_sec); 
        strftime (time_string, sizeof (time_string), "%H:%M:%S", ptm); 
        useconds = tv.tv_usec; 
        printf("------------------------------------------------------------------------\n");
        printf("consumer process PID: %d\ttime: %s.%06ld\t dozen #: %d\n",getpid(),time_string, useconds,i);
        printf("\n");
        printf("plain\tjelly\tcoconut\thoney-dip\n");
        for (k = 0;k<12;k++)
        {
            int rowtest = 0;
            for (j = 0; j< NUMFLAVORS; j++)
            {
                if (counter[j] > k)
                {
                    printf("%d\t",donuts[j][k]);
                    rowtest++;
                }
                else
                {
                    printf("\t");
                }
            }
            if (rowtest > 0)
            {
                printf("\n");
            }
        }
        printf("\r");
        printf("------------------------------------------------------------------------\n");
        printf("\n");
        
        //microsleep to give up CPU
        usleep(100);
    }
    return 0;
}
示例#11
0
int
fill_random_buffer(unsigned long long size, unsigned long long ** seg_addr, MEMORY_SET * mem)  {


    size_t shm_size;
    char msg[4096];
    int shm_id, rc = 0;
    unsigned int memflg;
    unsigned long long *addr_8, *end_addr, *addr;
	unsigned long long i , j ;

#ifndef __HTX_LINUX__ /* AIX Specific */ 

   	psize_t psize = 16*M;
    struct shmid_ds shm_buf = { 0 };
	
	memflg = (IPC_CREAT | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
	if(SET_PAGESIZE) { 
		memflg |= (SHM_LGPAGE | SHM_PIN);
    	psize = 16*M;
	} else { 
		psize = 4 * K; 
	} 
#else	/* Linux Specific */ 
	unsigned long long psize;

    memflg = (IPC_CREAT | IPC_EXCL |SHM_R | SHM_W);
	if(SET_PAGESIZE) { 
		memflg |= (SHM_HUGETLB);
		psize = 16*M;
	} else { 
		psize = 4 * K; 
	} 
#endif 

    shm_size = size;


    shm_id = shmget(IPC_PRIVATE, shm_size , memflg);
    if(shm_id == -1) {
          sprintf(msg,"shmget failed with %d !\n", errno);
          hxfmsg(&htx_d, rc, HTX_HE_HARD_ERROR, msg);
          return(-1);
    }

#ifndef __HTX_LINUX__
	if( SET_PAGESIZE) {  
	    if ( shm_size > 256*M) {
    	  if ((rc = shmctl(shm_id, SHM_GETLBA, &shm_buf)) == -1)   {
        	    sprintf(msg,"\n shmctl failed to get minimum alignment requirement - %d", errno);
            	hxfmsg(&htx_d, rc, HTX_HE_HARD_ERROR, msg);
            	return(-1);
       		}
    	}
    	shm_buf.shm_pagesize = psize;
    	if( (rc = shmctl(shm_id, SHM_PAGESIZE, &shm_buf)) == -1) {
         	sprintf(msg,"\n shmctl failed with %d while setting page size.",errno);
         	hxfmsg(&htx_d, rc, HTX_HE_HARD_ERROR, msg);
         	return(-1);
    	}
	} 	
#endif
    addr = (unsigned long long *) shmat(shm_id, 0, 0);
    if(-1 == (int)addr) {
        sprintf(msg,"\n shmat failed with %d",errno);
        hxfmsg(&htx_d, -1,HTX_HE_HARD_ERROR, msg);
        memory_set_cleanup();
        return(-1);
    }
    addr_8 = (unsigned long long *)addr;
    end_addr = (unsigned long long *) ((char *)addr + shm_size);
	DEBUGON("%s: addr_8 = %llx , end_addr = %llx \n",__FUNCTION__, addr_8, end_addr);
    for(; addr_8 < end_addr; ) {
        *addr_8 = get_random_number();
        addr_8++;
    }

	/* Lock the new shared memory, so that its always memory resident */
	rc = mlock(addr, shm_size);
	if(rc == -1) {
		sprintf(msg,"\n mlock failed with %d", errno);
		hxfmsg(&htx_d, rc, HTX_HE_HARD_ERROR, msg);
		memory_set_cleanup();
		return(-1);
	}

	mem->seg_addr = (char *)addr ;
	mem->shm_id = shm_id ;
	mem->memory_set_size = size;
	*seg_addr = (unsigned long long *)addr ;
    return 0;
}
int main(int argc, char **argv)
{
	int opt;
	const char *appname = strdup(argv[0]);
	const char *device = NULL;
	const char *interface = NULL;
	const char *mode = NULL;

	while ((opt = getopt(argc, argv, "d:i:h")) > 0) {
		switch (opt) {
		case 'd':
			device = optarg;
			break;
		case 'i':
			interface = optarg;
			break;
		case 'h':
		default:
			usage(appname);
			break;
		}
	}

	argc -= optind;
	argv += optind;

	mode = argv[0];
	
	printf("# dLAN Wireless M-Bus Repeater\n");

	if(1 != argc)
	{
		return usage(appname);
	}

	if(-1 == amber_open(device, mode))
		return -1;

	if(-1 == netw_open(interface))
	{
		amber_close();
		return -1;
	}

	// prepare timed buffers
	timedbuff_init();

	// prepare select
	fd_set rfds;
	int nfd = max( amber_get_fd(), netw_get_fd() ) + 1;

	// main loop

	unsigned char module_data[2048];
	int len=0, offs=0;
	while(1)
	{
		FD_ZERO(&rfds);
		FD_SET(amber_get_fd(), &rfds);	
		FD_SET(netw_get_fd(), &rfds);	

		struct timeval timeout;
		timeout.tv_sec = time_delay;
		timeout.tv_usec = 0;

		printf("(%s) select is sleeping for %ld secs\n", get_timestamp(), time_delay);
		int rc = select(nfd, &rfds, NULL, NULL, (timeout.tv_sec ? &timeout : NULL) );

		if (amber_fd_is_valid(device) < 0)
		{
			printf("ERROR: device disconnected\n");
			goto out;
		}

		if(-1 == rc)
		{
			printf("ERROR: select failed\n");
			continue;
		}

		// check if any timed buffers need to be sent
		time_delay = send_timed_buffers();

		if(!rc) // no data via serial/network
			continue;

		// Data from serial amber module?
		if(FD_ISSET(amber_get_fd(), &rfds))
		{
			unsigned char ibuf[2048];
			int r = amber_read(ibuf, sizeof(ibuf));
			if(0==r) continue;
			if(0==len)
			{
				if( 0 && 0xff == ibuf[0] ) // cmd feedback from module
				{
					memcpy(&module_data[0], &ibuf[0], r);
					offs = r; len = 0;
				}
				else // data from module
				{
					len = (int) ibuf[0] + 1;
					memcpy(&module_data[0], &ibuf[0], r);
					offs = r; len -= r;
				}
			}
			else
			{
				memcpy(&module_data[offs], &ibuf[0], r);
				offs += r; len -= r;
			}

			if(0==len)
			{
				int should_repeat = oms_unidir_should_repeat(module_data, offs);
				printf("(%s) wM-Bus %s (%d bytes):\n", get_timestamp(), should_repeat?"TO eth":"ignore", offs);
				wmbus_hex_dump(module_data, offs);
				wmbus_dump(module_data, offs);
				printf("\n");
				if(should_repeat)
				{
					time_t buff_delay;
					unsigned short sw = wmbus_apl_get_signature_word(module_data);
					wmbus_set_hopcount(&sw);
					wmbus_apl_set_signature_word(module_data, sw);

					buff_delay = (get_random_number()%20)+5; // OMS spec tells us to delay for 5..25 seconds
					timedbuff_store(module_data, offs, buff_delay, USE_NETW);
					time_delay = timedbuff_get_delay();
					printf("     delaying for %ld seconds\n", buff_delay);

					// now we need to check for SND-IR (C=0x46, hopcount=0) and reply with SND-NKE.
					// the telegram's hopcount was 0 initially, otherwise we would not be in the should_repeat branch.
					if(0x46 == wmbus_dll_get_c(module_data))
					{
						unsigned char sndnke[2048];
						int sndnke_len = sizeof(sndnke);
						// prepare SND-NKE telegram
						sndnke_len = wmbus_dvl_create_snd_nke(module_data, offs, sndnke, sndnke_len);
						
						// fill in details:
						// set meter id, meter manu, meter vers, meter devtype
						if(wmbus_apl_has_long_header(module_data))
						{
							wmbus_apl_set_meter_id(sndnke, wmbus_apl_get_meter_id(module_data));
							wmbus_apl_set_meter_manu(sndnke, wmbus_apl_get_meter_manu(module_data));
							wmbus_apl_set_meter_version(sndnke, wmbus_apl_get_meter_version(module_data));
							wmbus_apl_set_meter_devtype(sndnke, wmbus_apl_get_meter_devtype(module_data));
						}
						else
						{
							wmbus_apl_set_meter_id(sndnke, wmbus_dll_get_id(module_data));
							wmbus_apl_set_meter_manu(sndnke, wmbus_dll_get_manu(module_data));
							wmbus_apl_set_meter_version(sndnke, wmbus_dll_get_version(module_data));
							wmbus_apl_set_meter_devtype(sndnke, wmbus_dll_get_devtype(module_data));
						}

						// access nr, status, sigword
						wmbus_apl_set_access_nr(sndnke, access_nr++);
						wmbus_apl_set_status(sndnke, 0x00);
						wmbus_apl_set_signature_word(sndnke, 0x0000);

						// send to wmbus with delay [2..5] after sending SNR-IR
						time_t nke_buff_delay = (get_random_number()%3)+2;
						timedbuff_store(sndnke, sndnke_len, nke_buff_delay+buff_delay, USE_AMBER);
						time_delay = timedbuff_get_delay();
						printf("(%s) send SND-NKE to wM-Bus, delaying for %ld + %ld secs (%d bytes):\n", get_timestamp(), buff_delay, nke_buff_delay, sndnke_len);
						wmbus_hex_dump(sndnke, sndnke_len);
						wmbus_dump(sndnke, sndnke_len);
						printf("\n");
					}
				}
			}
		}

		// Data from network?
		if(FD_ISSET(netw_get_fd(), &rfds))
		{
			unsigned char buf[2048];
			int r = netw_receive(buf, sizeof(buf));
			if(-1==r)
			{
				printf("ERROR: netw_recv\n");
			}
			else if(0<r)
			{
				printf("(%s) eth to wM-Bus (%d bytes):\n", get_timestamp(), r);
				wmbus_hex_dump(buf, r);
				wmbus_dump(buf, r);
				printf("\n");
				amber_write(buf, r);

			}
		}
	}

out:
	netw_close();
	amber_close();

	return 0;
}
示例#13
0
static void do_updates(multiple_query_ctx_t *query_ctx)
{
	char *iter = (char *) (query_ctx->query_param + 1);
	size_t sz = MAX_UPDATE_QUERY_LEN(query_ctx->num_result);

	// Sort the results to avoid database deadlock.
	qsort(query_ctx->res, query_ctx->num_result, sizeof(*query_ctx->res), compare_items);
	query_ctx->query_param->param.command = iter;
	query_ctx->query_param->param.nParams = 0;
	query_ctx->query_param->param.on_result = on_update_result;
	query_ctx->query_param->param.paramFormats = NULL;
	query_ctx->query_param->param.paramLengths = NULL;
	query_ctx->query_param->param.paramValues = NULL;
	query_ctx->query_param->param.flags = 0;
	query_ctx->res->random_number = 1 + get_random_number(MAX_ID, &query_ctx->ctx->random_seed);

	int c = snprintf(iter,
	                 sz,
	                 UPDATE_QUERY_BEGIN,
	                 query_ctx->res->id,
	                 query_ctx->res->random_number);

	if ((size_t) c >= sz)
		goto error;

	iter += c;
	sz -= c;

	for (size_t i = 1; i < query_ctx->num_result; i++) {
		query_ctx->res[i].random_number = 1 + get_random_number(MAX_ID,
		                                                        &query_ctx->ctx->random_seed);
		c = snprintf(iter,
		             sz,
		             UPDATE_QUERY_ELEM,
		             query_ctx->res[i].id,
		             query_ctx->res[i].random_number);

		if ((size_t) c >= sz)
			goto error;

		iter += c;
		sz -= c;
	}

	c = snprintf(iter, sz, UPDATE_QUERY_END);

	if ((size_t) c >= sz)
		goto error;

	if (execute_query(query_ctx->ctx, &query_ctx->query_param->param)) {
		query_ctx->cleanup = true;
		send_service_unavailable_error(DB_REQ_ERROR, query_ctx->req);
	}
	else
		query_ctx->num_query_in_progress++;

	return;
error:
	query_ctx->cleanup = true;
	LIBRARY_ERROR("snprintf", "Truncated output.");
	send_error(INTERNAL_SERVER_ERROR, REQ_ERROR, query_ctx->req);
}
示例#14
0
static void do_updates(multiple_query_ctx_t *query_ctx)
{
	thread_context_t * const ctx = H2O_STRUCT_FROM_MEMBER(thread_context_t,
	                                                      event_loop.h2o_ctx,
	                                                      query_ctx->req->conn->ctx);
	char *iter = (char *) (query_ctx->query_param + 1);
	size_t sz = MAX_UPDATE_QUERY_LEN(query_ctx->num_result);

	// Sort the results to avoid database deadlock.
	qsort(query_ctx->res, query_ctx->num_result, sizeof(*query_ctx->res), compare_items);
	query_ctx->query_param->param.command = iter;
	query_ctx->query_param->param.nParams = 0;
	query_ctx->query_param->param.on_result = on_update_result;
	query_ctx->query_param->param.paramFormats = NULL;
	query_ctx->query_param->param.paramLengths = NULL;
	query_ctx->query_param->param.paramValues = NULL;
	query_ctx->query_param->param.flags = 0;
	query_ctx->res->random_number = get_random_number(MAX_ID, &ctx->random_seed) + 1;

	int c = snprintf(iter,
	                 sz,
	                 UPDATE_QUERY_BEGIN,
	                 query_ctx->res->id,
	                 query_ctx->res->random_number);

	if ((size_t) c >= sz)
		goto error;

	iter += c;
	sz -= c;

	for (size_t i = 1; i < query_ctx->num_result; i++) {
		query_ctx->res[i].random_number = get_random_number(MAX_ID, &ctx->random_seed) + 1;
		c = snprintf(iter,
		             sz,
		             UPDATE_QUERY_ELEM,
		             query_ctx->res[i].id,
		             query_ctx->res[i].random_number);

		if ((size_t) c >= sz)
			goto error;

		iter += c;
		sz -= c;
	}

	c = snprintf(iter, sz, UPDATE_QUERY_END);

	if ((size_t) c >= sz)
		goto error;

	if (execute_query(ctx, &query_ctx->query_param->param))
		send_service_unavailable_error(DB_REQ_ERROR, query_ctx->req);
	else {
		query_ctx->num_query_in_progress++;
		h2o_mem_addref_shared(query_ctx);
	}

	return;
error:
	LIBRARY_ERROR("snprintf", "Truncated output.");
	send_error(INTERNAL_SERVER_ERROR, REQ_ERROR, query_ctx->req);
}
示例#15
0
void blackhole_evaluate(int target, int mode)
{
  int startnode, numngb, j, k, n, index, id;
  FLOAT *pos, *velocity, h_i;
  double w, dx, dy, dz, h_i2, r2, r, u, hinv, hinv3, wk, accreted_mass, accreted_BH_mass, mass, bh_mass;
  double mdot, p, rho, vrel, csnd, dt, accreted_momentum[3];

#ifdef BH_KINETICFEEDBACK
  /*  double deltavel; */
  double activetime, activeenergy;
#endif
#ifdef BH_THERMALFEEDBACK
  double energy;
#endif
#ifdef REPOSITION_ON_POTMIN
  double minpotpos[3], minpot = 1.0e30;
#endif

  if(mode == 0)
    {
      pos = P[target].Pos;
      rho = P[target].BH_Density;
      mdot = P[target].BH_Mdot;
      dt = (P[target].Ti_endstep - P[target].Ti_begstep) * All.Timebase_interval / hubble_a;
      h_i = PPP[target].Hsml;
      mass = P[target].Mass;
      bh_mass = P[target].BH_Mass;
      velocity = P[target].Vel;
      index = target;
      id = P[target].ID;
#ifdef BH_KINETICFEEDBACK
      activetime = P[target].ActiveTime;
      activeenergy = P[target].ActiveEnergy;
#endif
    }
  else
    {
      pos = BlackholeDataGet[target].Pos;
      rho = BlackholeDataGet[target].Density;
      mdot = BlackholeDataGet[target].Mdot;
      dt = BlackholeDataGet[target].Dt;
      h_i = BlackholeDataGet[target].Hsml;
      mass = BlackholeDataGet[target].Mass;
      bh_mass = BlackholeDataGet[target].BH_Mass;
      velocity = BlackholeDataGet[target].Vel;
      index = BlackholeDataGet[target].Index;
      id = BlackholeDataGet[target].ID;
#ifdef BH_KINETICFEEDBACK
      activetime = BlackholeDataGet[target].ActiveTime;
      activeenergy = BlackholeDataGet[target].ActiveEnergy;
#endif
    }

  /* initialize variables before SPH loop is started */
  h_i2 = h_i * h_i;

  accreted_mass = 0;
  accreted_BH_mass = 0;
  accreted_momentum[0] = accreted_momentum[1] = accreted_momentum[2] = 0;


  /* Now start the actual SPH computation for this particle */
  startnode = All.MaxPart;
  do
    {
      numngb = ngb_treefind_blackhole(&pos[0], h_i, &startnode);

      for(n = 0; n < numngb; n++)
	{
	  j = Ngblist[n];

	  if(P[j].Mass > 0)
	    {
	      if(mass > 0)
		{
		  dx = pos[0] - P[j].Pos[0];
		  dy = pos[1] - P[j].Pos[1];
		  dz = pos[2] - P[j].Pos[2];
#ifdef PERIODIC			/*  now find the closest image in the given box size  */
		  if(dx > boxHalf_X)
		    dx -= boxSize_X;
		  if(dx < -boxHalf_X)
		    dx += boxSize_X;
		  if(dy > boxHalf_Y)
		    dy -= boxSize_Y;
		  if(dy < -boxHalf_Y)
		    dy += boxSize_Y;
		  if(dz > boxHalf_Z)
		    dz -= boxSize_Z;
		  if(dz < -boxHalf_Z)
		    dz += boxSize_Z;
#endif
		  r2 = dx * dx + dy * dy + dz * dz;

		  if(r2 < h_i2)
		    {
#ifdef REPOSITION_ON_POTMIN
		      if(P[j].Potential < minpot)
			{
			  minpot = P[j].Potential;
			  for(k = 0; k < 3; k++)
			    minpotpos[k] = P[j].Pos[k];
			}
#endif
		      if(P[j].Type == 5)	/* we have a black hole merger */
			{
			  if(r2 > 0)
			    {
			      if(All.NumCurrentTiStep & 1)
				if(P[j].ID > id)
				  continue;

			      if(!(All.NumCurrentTiStep & 1))
				if(P[j].ID < id)
				  continue;


			      /* compute relative velocity of BHs */

			      for(k = 0, vrel = 0; k < 3; k++)
				vrel += (P[j].Vel[k] - velocity[k]) * (P[j].Vel[k] - velocity[k]);

			      vrel = sqrt(vrel) / ascale;
			      csnd =
				sqrt(GAMMA * P[j].BH_Entropy *
				     pow(P[j].BH_Density / (ascale * ascale * ascale), GAMMA_MINUS1));

			      if(vrel > 0.5 * csnd)
				{
				  fprintf(FdBlackHolesDetails,
					  "ThisTask=%d, time=%g: id=%d would like to swallow %d, but vrel=%g csnd=%g\n",
					  ThisTask, All.Time, id, P[j].ID, vrel, csnd);
				}
			      else
				{
				  fprintf(FdBlackHolesDetails,
					  "ThisTask=%d, time=%g: id=%d swallows %d (vrel=%g csnd=%g)\n",
					  ThisTask, All.Time, id, P[j].ID, vrel, csnd);

				  accreted_mass += P[j].Mass;
				  accreted_BH_mass += P[j].BH_Mass;

				  for(k = 0; k < 3; k++)
				    accreted_momentum[k] += P[j].Mass * P[j].Vel[k];

				  P[j].Mass = 0;
				  P[j].BH_Mass = 0;

				  N_BH_swallowed++;

				  fprintf(FdBlackHolesDetails, "BHM=%d %d %g %g %g\n",
					  id, P[j].ID, bh_mass, P[j].BH_Mass, All.Time);
				}
			    }
			}
		      if(P[j].Type == 0)
			{
			  /* here we have a gas particle */

			  r = sqrt(r2);
			  hinv = 1 / h_i;
#ifndef  TWODIMS
			  hinv3 = hinv * hinv * hinv;
#else
			  hinv3 = hinv * hinv / boxSize_Z;
#endif

			  u = r * hinv;

			  if(u < 0.5)
			    wk = hinv3 * (KERNEL_COEFF_1 + KERNEL_COEFF_2 * (u - 1) * u * u);
			  else
			    wk = hinv3 * KERNEL_COEFF_5 * (1.0 - u) * (1.0 - u) * (1.0 - u);

#ifdef SWALLOWGAS
			  /* compute accretion probability */

			  if((bh_mass - mass) > 0)
			    p = (bh_mass - mass) * wk / rho;
			  else
			    p = 0;

			  /* compute random number, uniform in [0,1] */
			  w = get_random_number(P[j].ID);
			  if(w < p)
			    {
			      accreted_mass += P[j].Mass;
			      P[j].Mass = 0;

			      N_gas_swallowed++;
			    }
#endif

			  if(P[j].Mass > 0)
			    {
#ifdef BH_THERMALFEEDBACK
			      energy = All.BlackHoleFeedbackFactor * 0.1 * mdot * dt *
				pow(C / All.UnitVelocity_in_cm_per_s, 2);

			      SphP[j].Injected_BH_Energy += energy * P[j].Mass * wk / rho;
#endif

#ifdef BH_KINETICFEEDBACK
			      if(activetime > All.BlackHoleActiveTime)
				{
				  SphP[j].Injected_BH_Energy += activeenergy * P[j].Mass * wk / rho;
				  /*
				     deltavel = ascale * sqrt(2 * activeenergy * wk / rho);

				     printf("deltavel = %g  energy=%g u=%g\n",
				     deltavel, activeenergy, u);
				     fflush(stdout);

				     if(r > 0)
				     {
				     P[j].Vel[0] -= deltavel * dx/r;
				     P[j].Vel[1] -= deltavel * dy/r;
				     P[j].Vel[2] -= deltavel * dz/r;
				     SphP[j].VelPred[0] -= deltavel * dx/r;
				     SphP[j].VelPred[1] -= deltavel * dy/r;
				     SphP[j].VelPred[2] -= deltavel * dz/r;
				     }
				   */
				}
#endif
			    }

			}
		    }
		}
	    }
	}
    }
  while(startnode >= 0);

  /* Now collect the result at the right place */
  if(mode == 0)
    {
      if(P[target].Mass + accreted_mass > 0)
	{
	  for(k = 0; k < 3; k++)
	    P[target].Vel[k] =
	      (P[target].Vel[k] * P[target].Mass + accreted_momentum[k]) / (P[target].Mass + accreted_mass);
	}

      P[target].Mass += accreted_mass;
      P[target].BH_Mass += accreted_BH_mass;

#ifdef REPOSITION_ON_POTMIN
      for(k = 0; k < 3; k++)
	P[target].BH_MinPotPos[k] = minpotpos[k];
      P[target].BH_MinPot = minpot;
#endif

    }
  else
    {
      BlackholeDataResult[target].Mass = accreted_mass;
      BlackholeDataResult[target].BH_Mass = accreted_BH_mass;
      for(k = 0; k < 3; k++)
	BlackholeDataResult[target].AccretedMomentum[k] = accreted_momentum[k];

#ifdef REPOSITION_ON_POTMIN
      for(k = 0; k < 3; k++)
	BlackholeDataResult[target].BH_MinPotPos[k] = minpotpos[k];
      BlackholeDataResult[target].BH_MinPot = minpot;
#endif


    }
}
示例#16
0
/*! This routine does the test of the gravitational tree force by computing
 *  the force for a random subset of particles with direct summation.
 */
void gravity_forcetest(void)
{
  int ntot, iter = 0, ntotleft, nthis;
  double tstart, tend, timetree = 0;
  int i, j, ndone, ngrp, maxfill, place, ndonetot;

#ifndef NOGRAVITY
  int *noffset, *nbuffer, *nsend, *nsend_local;
  int k, nexport;
  int level, sendTask, recvTask;
  double fac1;
#ifndef NOMPI
  MPI_Status status;
#endif
#endif
  double costtotal, *costtreelist;
  double maxt, sumt, *timetreelist;
  double fac;
  char buf[200];

#ifdef PMGRID
  if(All.PM_Ti_endstep != All.Ti_Current)
    return;
#endif

  if(All.ComovingIntegrationOn)
    set_softenings();		/* set new softening lengths */

  for(i = 0, NumForceUpdate = 0; i < NumPart; i++)
    {
      if(P[i].Ti_endstep == All.Ti_Current)
	{
	  if(get_random_number(P[i].ID) < FORCETEST)
	    {
	      P[i].Ti_endstep = -P[i].Ti_endstep - 1;
	      NumForceUpdate++;
	    }
	}
    }

  /* NumForceUpdate is the number of particles on this processor that want a force update */
#ifndef NOMPI
  MPI_Allreduce(&NumForceUpdate, &ntot, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
#else
  ntot = NumForceUpdate;
#endif

  costtotal = 0;

  noffset = malloc(sizeof(int) * NTask);	/* offsets of bunches in common list */
  nbuffer = malloc(sizeof(int) * NTask);
  nsend_local = malloc(sizeof(int) * NTask);
  nsend = malloc(sizeof(int) * NTask * NTask);

  i = 0;			/* beginn with this index */
  ntotleft = ntot;		/* particles left for all tasks together */

  while(ntotleft > 0)
    {
      iter++;

      for(j = 0; j < NTask; j++)
	nsend_local[j] = 0;

      /* do local particles and prepare export list */
      tstart = second();
      for(nexport = 0, ndone = 0; i < NumPart && nexport < All.BunchSizeForce - NTask; i++)
	if(P[i].Ti_endstep < 0)
	  {
	    ndone++;

	    for(j = 0; j < NTask; j++)
	      Exportflag[j] = 1;
	    Exportflag[ThisTask] = 0;

	    costtotal += force_treeevaluate_direct(i, 0);

	    for(j = 0; j < NTask; j++)
	      {
		if(Exportflag[j])
		  {
		    for(k = 0; k < 3; k++)
		      GravDataGet[nexport].u.Pos[k] = P[i].Pos[k];

#ifdef UNEQUALSOFTENINGS
		    GravDataGet[nexport].Type = P[i].Type;
#endif
		    GravDataGet[nexport].w.OldAcc = P[i].OldAcc;

		    GravDataIndexTable[nexport].Task = j;
		    GravDataIndexTable[nexport].Index = i;
		    GravDataIndexTable[nexport].SortIndex = nexport;

		    nexport++;
		    nsend_local[j]++;
		  }
	      }
	  }
      tend = second();
      timetree += timediff(tstart, tend);

      qsort(GravDataIndexTable, nexport, sizeof(struct gravdata_index), grav_tree_compare_key);

      for(j = 0; j < nexport; j++)
	GravDataIn[j] = GravDataGet[GravDataIndexTable[j].SortIndex];

      for(j = 1, noffset[0] = 0; j < NTask; j++)
	noffset[j] = noffset[j - 1] + nsend_local[j - 1];

#ifndef NOMPI
      MPI_Allgather(nsend_local, NTask, MPI_INT, nsend, NTask, MPI_INT, MPI_COMM_WORLD);
#else
    nsend[0] = nsend_local[i];
#endif
      /* now do the particles that need to be exported */

      for(level = 1; level < (1 << PTask); level++)
	{
	  for(j = 0; j < NTask; j++)
	    nbuffer[j] = 0;
	  for(ngrp = level; ngrp < (1 << PTask); ngrp++)
	    {
	      maxfill = 0;
	      for(j = 0; j < NTask; j++)
		{
		  if((j ^ ngrp) < NTask)
		    if(maxfill < nbuffer[j] + nsend[(j ^ ngrp) * NTask + j])
		      maxfill = nbuffer[j] + nsend[(j ^ ngrp) * NTask + j];
		}
	      if(maxfill >= All.BunchSizeForce)
		break;

	      sendTask = ThisTask;
	      recvTask = ThisTask ^ ngrp;

	      if(recvTask < NTask)
		{
		  if(nsend[ThisTask * NTask + recvTask] > 0 || nsend[recvTask * NTask + ThisTask] > 0)
		    {
		      /* get the particles */
		      MPI_Sendrecv(&GravDataIn[noffset[recvTask]],
				   nsend_local[recvTask] * sizeof(struct gravdata_in), MPI_BYTE,
				   recvTask, TAG_DIRECT_A,
				   &GravDataGet[nbuffer[ThisTask]],
				   nsend[recvTask * NTask + ThisTask] * sizeof(struct gravdata_in), MPI_BYTE,
				   recvTask, TAG_DIRECT_A, MPI_COMM_WORLD, &status);
		    }
		}

	      for(j = 0; j < NTask; j++)
		if((j ^ ngrp) < NTask)
		  nbuffer[j] += nsend[(j ^ ngrp) * NTask + j];
	    }

	  tstart = second();
	  for(j = 0; j < nbuffer[ThisTask]; j++)
	    {
	      costtotal += force_treeevaluate_direct(j, 1);
	    }
	  tend = second();
	  timetree += timediff(tstart, tend);


	  /* get the result */
	  for(j = 0; j < NTask; j++)
	    nbuffer[j] = 0;
	  for(ngrp = level; ngrp < (1 << PTask); ngrp++)
	    {
	      maxfill = 0;
	      for(j = 0; j < NTask; j++)
		{
		  if((j ^ ngrp) < NTask)
		    if(maxfill < nbuffer[j] + nsend[(j ^ ngrp) * NTask + j])
		      maxfill = nbuffer[j] + nsend[(j ^ ngrp) * NTask + j];
		}
	      if(maxfill >= All.BunchSizeForce)
		break;

	      sendTask = ThisTask;
	      recvTask = ThisTask ^ ngrp;
	      if(recvTask < NTask)
		{
		  if(nsend[ThisTask * NTask + recvTask] > 0 || nsend[recvTask * NTask + ThisTask] > 0)
		    {
		      /* send the results */
		      MPI_Sendrecv(&GravDataResult[nbuffer[ThisTask]],
				   nsend[recvTask * NTask + ThisTask] * sizeof(struct gravdata_in),
				   MPI_BYTE, recvTask, TAG_DIRECT_B,
				   &GravDataOut[noffset[recvTask]],
				   nsend_local[recvTask] * sizeof(struct gravdata_in),
				   MPI_BYTE, recvTask, TAG_DIRECT_B, MPI_COMM_WORLD, &status);

		      /* add the result to the particles */
		      for(j = 0; j < nsend_local[recvTask]; j++)
			{
			  place = GravDataIndexTable[noffset[recvTask] + j].Index;

			  for(k = 0; k < 3; k++)
			    P[place].GravAccelDirect[k] += GravDataOut[j + noffset[recvTask]].u.Acc[k];
			}
		    }
		}

	      for(j = 0; j < NTask; j++)
		if((j ^ ngrp) < NTask)
		  nbuffer[j] += nsend[(j ^ ngrp) * NTask + j];
	    }

	  level = ngrp - 1;
	}

      MPI_Allreduce(&ndone, &ndonetot, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);

      ntotleft -= ndonetot;
    }

  free(nsend);
  free(nsend_local);
  free(nbuffer);
  free(noffset);


  /* now add things for comoving integration */

  if(All.ComovingIntegrationOn)
    {
#ifndef PERIODIC
      fac1 = 0.5 * All.Hubble * All.Hubble * All.Omega0 / All.G;

      for(i = 0; i < NumPart; i++)
	if(P[i].Ti_endstep < 0)
	  for(j = 0; j < 3; j++)
	    P[i].GravAccelDirect[j] += fac1 * P[i].Pos[j];
#endif
    }



  /*  muliply by G */

  for(i = 0; i < NumPart; i++)
    if(P[i].Ti_endstep < 0)
      for(j = 0; j < 3; j++)
	P[i].GravAccelDirect[j] *= All.G;



  /* Finally, the following factor allows a computation of cosmological simulation
     with vacuum energy in physical coordinates */

  if(All.ComovingIntegrationOn == 0)
    {
      fac1 = All.OmegaLambda * All.Hubble * All.Hubble;

      for(i = 0; i < NumPart; i++)
	if(P[i].Ti_endstep < 0)
	  for(j = 0; j < 3; j++)
	    P[i].GravAccelDirect[j] += fac1 * P[i].Pos[j];
    }

  /* now output the forces to a file */

  for(nthis = 0; nthis < NTask; nthis++)
    {
      if(nthis == ThisTask)
	{
	  sprintf(buf, "%s%s", All.OutputDir, "forcetest.txt");
	  if(!(FdForceTest = fopen(buf, "a")))
	    {
	      printf("error in opening file '%s'\n", buf);
	      endrun(17);
	    }
	  for(i = 0; i < NumPart; i++)
	    if(P[i].Ti_endstep < 0)
	      {
#ifndef PMGRID
		fprintf(FdForceTest, "%d %g %g %g %g %g %g %g %g %g %g %g\n",
			P[i].Type, All.Time, All.Time - TimeOfLastTreeConstruction,
			P[i].Pos[0], P[i].Pos[1], P[i].Pos[2],
			P[i].GravAccelDirect[0], P[i].GravAccelDirect[1], P[i].GravAccelDirect[2],
			P[i].GravAccel[0], P[i].GravAccel[1], P[i].GravAccel[2]);
#else
		fprintf(FdForceTest, "%d %g %g %g %g %g %g %g %g %g %g %g %g %g %g\n",
			P[i].Type, All.Time, All.Time - TimeOfLastTreeConstruction,
			P[i].Pos[0], P[i].Pos[1], P[i].Pos[2],
			P[i].GravAccelDirect[0], P[i].GravAccelDirect[1], P[i].GravAccelDirect[2],
			P[i].GravAccel[0], P[i].GravAccel[1], P[i].GravAccel[2],
			P[i].GravPM[0] + P[i].GravAccel[0],
			P[i].GravPM[1] + P[i].GravAccel[1], P[i].GravPM[2] + P[i].GravAccel[2]);
#endif
	      }
	  fclose(FdForceTest);
	}

#ifndef NOMPI
	      MPI_Barrier(MPI_COMM_WORLD);
#endif
    }

  for(i = 0; i < NumPart; i++)
    if(P[i].Ti_endstep < 0)
      P[i].Ti_endstep = -P[i].Ti_endstep - 1;

  /* Now the force computation is finished */



  timetreelist = malloc(sizeof(double) * NTask);
  costtreelist = malloc(sizeof(double) * NTask);

  MPI_Gather(&costtotal, 1, MPI_DOUBLE, costtreelist, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
  MPI_Gather(&timetree, 1, MPI_DOUBLE, timetreelist, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);

  if(ThisTask == 0)
    {
      fac = NTask / ((double) All.TotNumPart);

      for(i = 0, maxt = timetreelist[0], sumt = 0, costtotal = 0; i < NTask; i++)
	{
	  costtotal += costtreelist[i];

	  if(maxt < timetreelist[i])
	    maxt = timetreelist[i];
	  sumt += timetreelist[i];
	}

      fprintf(FdTimings, "DIRECT Nf= %d    part/sec=%g | %g  ia/part=%g \n", ntot, ntot / (sumt + 1.0e-20),
	      ntot / (maxt * NTask), ((double) (costtotal)) / ntot);
      fprintf(FdTimings, "\n");

      fflush(FdTimings);
    }

  free(costtreelist);
  free(timetreelist);
}