コード例 #1
0
ファイル: paraboloide.c プロジェクト: kokaz/raytracer
double		inter_paraboloide(t_cam *eye, t_obj *o)
{
  double	a;
  double	b;
  double	c;
  double	delta;
  double	tan_square;
  double	k;
  t_vector	p;

  tan_square = pow(tan(o->size), 2.0);
  a = pow(eye->v.x, 2.0)
    + pow(eye->v.y, 2.0);
  b = 2 * (eye->pos.x * eye->v.x
	   + eye->pos.y * eye->v.y)
    - tan_square * eye->v.z;
  c = pow(eye->pos.x, 2.0)
    + pow(eye->pos.y, 2.0)
    - tan_square * eye->pos.z;
  delta = pow(b, 2.0) - (4.0 * a * c);
  k = solve_eq(a, b, delta);
  p = eq_parametric(eye->pos, eye->v, k);
  if (double_are_same(check_limit(p, o), -1.0))
    return (-1.0);
  return (k);
}
コード例 #2
0
ファイル: logremote.c プロジェクト: AndrewBurian/tripwire
void log_flush_remote(struct log_context *logctx)
{
	char *msg = 0;

	// check to see if we have a rate limit catchup to send
	if (logctx->remote_limited && check_limit(logctx->remote_ratelimit, 0)) {

		msg = malloc(MAX_PACKET_SIZE + 1);
		bzero(msg, MAX_PACKET_SIZE + 1);

		switch (logctx->remote_format) {
		case TYPE_TEXT:
			snprintf(msg, MAX_PACKET_SIZE,
				 "Tripwire has dropped %d events due to ratelimiting\n",
				 logctx->remote_limited);
			break;
		case TYPE_CEF:
			snprintf(msg, MAX_PACKET_SIZE,
				 "CEF:0|||||Tripwire Rate Limiting Activated.||msg=Tripware has dropped %d events due to ratelimiting",
				 logctx->remote_limited);
			break;
		}
		switch (logctx->remote_type) {
		case TRANS_UDP:
			log_msg_udp(logctx, msg);
			break;
		case TRANS_TCP:
			log_msg_tcp(logctx, msg);
			break;
		}

		free(msg);
		logctx->remote_limited = 0;
	}
}
コード例 #3
0
ファイル: tocentry.c プロジェクト: ncbi/ncbi-vdb
static
rc_t KTocEntryInflateNodeSoftLink (KToc * toc, const KTocEntryInflateCommon * common, 
				  const void ** ptr, uint64_t offset, const void * limit, bool rev)
{
    rc_t rc;
    uint16_t llen;
    char * link;

    rc = read_u16 (ptr, limit, rev, &llen);
    if (rc)
	return rc;

    if (check_limit (*ptr, limit, llen))
	return RC (rcFS, rcTocEntry, rcParsing, rcBuffer, rcTooShort);;

    link = malloc (llen + 1);
    if (link == NULL)
	return RC (rcFS, rcTocEntry, rcParsing, rcMemory, rcExhausted);

    memmove (link, *ptr, llen);
    link[llen] = '\0';

    rc = KTocCreateSoftLink (toc, 
			     common->mtime,
			     common->access,
			     (KCreateMode)(kcmInit|kcmParents),
			     link,
			     common->name);
    
    free (link);
    return rc;
}
コード例 #4
0
ファイル: pass.c プロジェクト: federicosan/ponyc
// Peform the AST passes on the given AST up to the speficied last pass
static bool ast_passes(ast_t** astp, pass_opt_t* options, pass_id last)
{
  assert(astp != NULL);
  bool r;

  if(!visit_pass(astp, options, last, &r, PASS_SUGAR, pass_sugar, NULL))
    return r;

  if(options->check_tree)
    check_tree(*astp, options->check.errors);

  if(!visit_pass(astp, options, last, &r, PASS_SCOPE, pass_scope, NULL))
    return r;

  if(!visit_pass(astp, options, last, &r, PASS_IMPORT, pass_import, NULL))
    return r;

  if(!visit_pass(astp, options, last, &r, PASS_NAME_RESOLUTION, NULL,
    pass_names))
    return r;

  if(!visit_pass(astp, options, last, &r, PASS_FLATTEN, NULL, pass_flatten))
    return r;

  if(!visit_pass(astp, options, last, &r, PASS_TRAITS, pass_traits, NULL))
    return r;

  if(!check_limit(astp, options, PASS_DOCS, last))
    return true;

  if(options->docs && ast_id(*astp) == TK_PROGRAM)
    generate_docs(*astp, options);

  if(!visit_pass(astp, options, last, &r, PASS_EXPR, pass_pre_expr, pass_expr))
    return r;

  if(!check_limit(astp, options, PASS_FINALISER, last))
    return true;

  if(!pass_finalisers(*astp, options))
    return false;

  if(options->check_tree)
    check_tree(*astp, options->check.errors);
  return true;
}
コード例 #5
0
static void
check_limits(const char *line, struct pattern_rule *rule, regmatch_t *parens, time_t tstamp)
{
	char **entry;

	for (entry = rule->limits; *entry != NULL; entry++) {
		check_limit(*entry, line, rule, parens, tstamp);
	}
}
コード例 #6
0
ファイル: maingui.cpp プロジェクト: Youscribe/ttfautohint
void
Main_GUI::set_defaults()
{
  min_box->setValue(hinting_range_min);
  max_box->setValue(hinting_range_max);

  fallback_box->setCurrentIndex(latin_fallback);

  limit_box->setValue(hinting_limit ? hinting_limit : hinting_range_max);
  // handle command line option `--hinting-limit=0'
  if (!hinting_limit)
  {
    hinting_limit = max_box->value();
    no_limit_box->setChecked(true);
  }

  increase_box->setValue(increase_x_height ? increase_x_height
                                           : TA_INCREASE_X_HEIGHT);
  // handle command line option `--increase-x-height=0'
  if (!increase_x_height)
  {
    increase_x_height = TA_INCREASE_X_HEIGHT;
    no_increase_box->setChecked(true);
  }

  snapping_line->setText(x_height_snapping_exceptions_string);

  if (windows_compatibility)
    wincomp_box->setChecked(true);
  if (pre_hinting)
    pre_box->setChecked(true);
  if (hint_with_components)
    hint_box->setChecked(true);
  if (symbol)
    symbol_box->setChecked(true);
  if (!no_info)
    info_box->setChecked(true);

  if (gray_strong_stem_width)
    gray_box->setChecked(true);
  if (gdi_cleartype_strong_stem_width)
    gdi_box->setChecked(true);
  if (dw_cleartype_strong_stem_width)
    dw_box->setChecked(true);

  run_button->setEnabled(false);

  check_min();
  check_max();
  check_limit();

  check_no_limit();
  check_no_increase();
  check_number_set();
}
コード例 #7
0
ファイル: sphere.c プロジェクト: m2omou/raytracer
double		calc_k_sphere(t_vect *o, t_vect *u, t_obj *obj)
{
  t_vect	tmp;
  double	x1;
  double	x2;

  tmp.x = (u->x * u->x + u->y * u->y + u->z * u->z);
  tmp.y = 2 * (o->x * u->x + o->y * u->y + o->z * u->z);
  tmp.z = (o->x * o->x + o->y * o->y + o->z * o->z - obj->param * obj->param);
  if (res_eq_sc(&tmp, &x1, &x2))
    {
      if ((x1 * norme(u)) > PAS && x1 < x2 && check_limit(o, u, x1, obj))
	return (x1);
      else if ((x2 * norme(u)) > PAS && check_limit(o, u, x2, obj))
	return (x2);
      else
	return (-1);
    }
  else
    return (-1);
}
コード例 #8
0
ファイル: m_admin.c プロジェクト: ircnet/not-ratbox
/*
 * mr_admin - ADMIN command handler
 *      parv[0] = sender prefix   
 *      parv[1] = servername   
 */
static int
mr_admin(struct Client *client_p, struct Client *source_p, int parc, const char *parv[])
{
	static time_t last_used = 0L;
	static int count;

	if (!check_limit(source_p, &last_used, &count, "ADMIN"))
		return 0;

	do_admin(source_p);

	return 0;
}
コード例 #9
0
ファイル: tocentry.c プロジェクト: ncbi/ncbi-vdb
static
rc_t read_u8 (const void ** _ptr, const void * limit, uint8_t * pout)
{
    const uint8_t * ptr;

    if (check_limit (*_ptr, limit, sizeof (uint8_t)))
	return RC (rcFS, rcTocEntry, rcParsing, rcBuffer, rcTooShort);

    ptr = *_ptr;
    *pout = *ptr++;
    *_ptr = ptr;
    return 0;
}
コード例 #10
0
ファイル: data_access.c プロジェクト: isadorasophia/MC404
/**
 * Read an argument converted in string, either in hex or decimal.
 * Report an error if it wasn't declared correctly.
 *
 * min:             minimum value of decimal number
 * max:             maximum value of decimal number
 * hex:             can it be a hex value?
 * return:          value in decimal
 */
lld read_constant(char* buffer, int line, lld min, lld max,
                  bool hex, regex_t* decimal_regex, regex_t* hex_regex) {
    lld tmp_lld;

    if (match(decimal_regex, buffer)) {
        // save value
        tmp_lld = atol(buffer);

        /* Since its a decimal value, make sure
         * it has a proper size */
        check_limit(min, max, tmp_lld, line);
    } else if (match(hex_regex, buffer)) {
        // save value as decimal
        sscanf(buffer, "%llx", &tmp_lld);
    } else {
        // none of them, report an error!
        report_error(strcat(buffer, " is not a valid argument!"), line, 1);
    }

    return tmp_lld;
}
コード例 #11
0
ファイル: inter_cone.c プロジェクト: Geod24/Raytracer
double		inter_cone(t_obj *obj, t_calc *calc)
{
  t_coord	abc;
  double	delta;
  t_coord	tmp_view;
  t_coord	tmp_eye;
  double	res;

  init_view(&tmp_eye, &tmp_view, obj, calc);
  abc.x = (SQ(VIEW_X) + SQ(VIEW_Y) -
	   ((SQ(VIEW_Z)) / SQ(tan(RAD(ANGLE)))));
  abc.y = ((EYE_X * 2 * VIEW_X) + (EYE_Y * 2 * VIEW_Y) -
	   ((EYE_Z * 2 * VIEW_Z) / SQ(tan(RAD(ANGLE)))));
  abc.z = (SQ(EYE_X) + SQ(EYE_Y) -
	   (SQ(EYE_Z) / SQ(tan(RAD(ANGLE)))));
  delta = SQ(abc.y) - (4 * abc.x * abc.z);
  res = calc_delta(&abc, delta);
  if (res != -1.0 && (obj->typdef.size_x != -1 || obj->typdef.size_y != -1))
    res = check_limit(obj, res, &tmp_eye, &tmp_view);
  return (res);
}
コード例 #12
0
ファイル: m_info.c プロジェクト: ircnet/not-ratbox
/*
** m_info
**  parv[0] = sender prefix
**  parv[1] = servername
*/
static int
m_info(struct Client *client_p, struct Client *source_p, int parc, const char *parv[])
{
	static time_t last_used = 0L;
	static int count;

	if (!check_limit(source_p, &last_used, &count, "INFO")) {
		sendto_one_numeric(source_p, RPL_ENDOFINFO, form_str(RPL_ENDOFINFO));
		return 0;
	}

	if(hunt_server(client_p, source_p, ":%s INFO :%s", 1, parc, parv) != HUNTED_ISME)
		return 0;

	info_spy(source_p);
	SetCork(source_p);
	send_info_text(source_p);
	send_birthdate_online_time(source_p);
	ClearCork(source_p);
	sendto_one_numeric(source_p, RPL_ENDOFINFO, form_str(RPL_ENDOFINFO));
	return 0;
}
コード例 #13
0
ファイル: pass.c プロジェクト: federicosan/ponyc
// Perform an ast_visit pass, after checking the pass limits.
// Returns true to continue, false to stop processing and return the value in
// out_r.
static bool visit_pass(ast_t** astp, pass_opt_t* options, pass_id last_pass,
  bool* out_r, pass_id pass, ast_visit_t pre_fn, ast_visit_t post_fn)
{
  assert(out_r != NULL);

  if(!check_limit(astp, options, pass, last_pass))
  {
    *out_r = true;
    return false;
  }

  //fprintf(stderr, "Pass %s (last %s) on %s\n", pass_name(pass),
  //  pass_name(last_pass), ast_get_print(*astp));

  if(ast_visit(astp, pre_fn, post_fn, options, pass) != AST_OK)
  {
    *out_r = false;
    return false;
  }

  return true;
}
コード例 #14
0
ファイル: logremote.c プロジェクト: AndrewBurian/tripwire
void log_event_remote(struct log_context *logctx, struct sockaddr_in *remote,
		      struct sockaddr_in *local)
{
	char *msg = 0;

	// check for rate limiting
	if (logctx->remote_ratelimit
	    && !check_limit(logctx->remote_ratelimit, 1)) {
		logctx->remote_limited++;
	} else {
		// flush logs and catch up alerts
		log_flush(logctx);

		// send alert
		switch (logctx->remote_format) {
		case TYPE_TEXT:
			text_format(&msg, remote, local, logctx);
			break;
		case TYPE_CEF:
			cef_format(&msg, remote, local, logctx);
			break;
		}

		// send alert to remote location
		switch (logctx->remote_type) {
		case TRANS_UDP:
			log_msg_udp(logctx, msg);
			break;
		case TRANS_TCP:
			log_msg_tcp(logctx, msg);
			break;
		}

		// free the message allocated by *_format()
		free(msg);
	}
}
コード例 #15
0
int do_icache_dump(cmd_tbl_t *cmdtp, int flag, int argc, char *argv[])
{
	int cache_status = icache_status();

	if (cache_status)
		icache_disable();

	uint32_t cmd_base, tag, cache_upper, cache_lower;

	size_t way, way_start = 0, way_end = 3;
	size_t sbnk, sbnk_start = 0, sbnk_end = 3;
	size_t set, set_start = 0, set_end = 31;
	size_t dw;

	if (argc > 1) {
		way_start = way_end = simple_strtoul(argv[1], NULL, 10);
		if (argc > 2) {
			sbnk_start = sbnk_end = simple_strtoul(argv[2], NULL, 10);
			if (argc > 3)
				set_start = set_end = simple_strtoul(argv[3], NULL, 10);
		}
	}

	if (check_limit("way", 0, 3, way_start, way_end) || \
	    check_limit("subbank", 0, 3, sbnk_start, sbnk_end) || \
	    check_limit("set", 0, 31, set_start, set_end))
		return 1;

	puts("Way:Subbank:Set: [valid-tag lower upper] {invalid-tag lower upper}...\n");

	for (way = way_start; way <= way_end; ++way) {
		for (sbnk = sbnk_start; sbnk <= sbnk_end; ++sbnk) {
			for (set = set_start; set <= set_end; ++set) {
				printf("%zu:%zu:%2zu: ", way, sbnk, set);
				for (dw = 0; dw < 4; ++dw) {
					if (ctrlc())
						return 1;

					cmd_base = \
						(way  << 26) | \
						(sbnk << 16) | \
						(set  <<  5) | \
						(dw   <<  3);

					/* first read the tag */
					bfin_write_ITEST_COMMAND(cmd_base | 0x0);
					SSYNC();
					tag = bfin_read_ITEST_DATA0();
					printf("%c%08x ", (tag & 0x1 ? ' ' : '{'), tag);

					/* grab the data at this loc */
					bfin_write_ITEST_COMMAND(cmd_base | 0x4);
					SSYNC();
					cache_lower = bfin_read_ITEST_DATA0();
					cache_upper = bfin_read_ITEST_DATA1();
					printf("%08x %08x%c ", cache_lower, cache_upper, (tag & 0x1 ? ' ' : '}'));
				}
				puts("\n");
			}
		}
	}

	if (cache_status)
		icache_enable();

	return 0;
}
コード例 #16
0
ファイル: place_halos.c プロジェクト: savila/halogen.c
//place_halos():
//
//Takes a list of halo masses (Nhalos, HaloMass), a list of particles (NTotPart,PartX,PartY,PartZ), some simulation parameters (L, mp), and user-defined parameters (Nlin,rho_ref,alpha,Malpha,Nalpha,seed)
//and returns a list of halo positions and radii (HaloX,HaloY,HaloZ,HaloR)
int place_halos(long Nend, float *HaloMass, long Nlin, long NTotPart, float *PartX, float *PartY, float *PartZ, float *PartVX, float *PartVY, float *PartVZ,float L, float rho_ref, long seed, float mp, double *alpha, int *Nhalosbin,long Nalpha,float *HaloX, float *HaloY, float *HaloZ, float *HaloVX, float *HaloVY, float *HaloVZ,float *HaloR,long **ListOfPart, long *NPartPerCell){


fprintf(stderr,"\tThis is place_halos.c v11\n");


//Initiallising -------------------------------------------------
	long i,j,k,lin_ijk,check, Nmin;
	long *count,trials;
	long ihalo, ipart,Halos_done;
	double invL = 1./L;
	float Mcell,Mhalo; 
	float R;
	time_t t0;
	int i_alpha;
	long icell;


	double mpart;
	double exponent;
	double TotProb;
	double *MassLeft;
	double *CumulativeProb; 
	long **ListOfHalos,  *NHalosPerCell;
	long Nstart=0,Nhalos;

	#ifdef VERB
	time_t t1,t2,t3,t4,t5,tI,tII;
	float diff;
	#endif

	NCells = Nlin;
	Lbox = L;
	
	t0=time(NULL);
	NTotCells = NCells*NCells*NCells;
	
	MassLeft = malloc(NTotCells*sizeof(double));

        fprintf(stderr,"N[0]=%ld, N[1]=%ld, N[2]=%ld, \n",NPartPerCell[0],NPartPerCell[1],NPartPerCell[2]); 
	//Allocate memory for the arrays 
	//NPartPerCell = (long *) calloc(NTotCells,sizeof(long));
  /*	if( NPartPerCell == NULL) {
    		fprintf(stderr,"\tplace_halos(): could not allocate %ld array for NPartPerCell[]\nABORTING",NTotCells);
    		exit(-1);
	}*/
	NHalosPerCell = (long *) calloc(NTotCells,sizeof(long));
  	if(NHalosPerCell == NULL) {
    		fprintf(stderr,"\tplace_halos(): could not allocate %ld array for NHalosPerCell[]\nABORTING",NTotCells);
    		exit(-1);
	}
	count = (long *) calloc(NTotCells,sizeof(long));
  	if(count == NULL) {
    		fprintf(stderr,"\tplace_halos(): could not allocate %ld array for NTotCells[]\nABORTING",NTotCells);
    		exit(-1);
	}
	CumulativeProb = (double *) calloc(NTotCells, sizeof(double));
  	if(CumulativeProb == NULL) {
    		fprintf(stderr,"\tplace_halos(): could not allocate %ld array for CumulativeProb[]\nABORTING",NTotCells);
    		exit(-1);
	}
	fprintf(stderr,"\tUsing OMP with %d threads\n",omp_get_max_threads());
	
	#ifdef MASS_OF_PARTS
	Nexcluded = (long *) calloc(NTotCells,sizeof(long));
  	if(Nexcluded == NULL) {
    		fprintf(stderr,"\tplace_halos(): could not allocate %ld array for Nexcluded[]\nABORTING",NTotCells);
    		exit(-1);
	}
 	excluded  = (int *) calloc(NTotPart, sizeof(long));
  	if(excluded == NULL) {
    		fprintf(stderr,"\tplace_halos(): could not allocate %ld array for excluded[]\nABORTING",NTotPart);
    		exit(-1);
	}
	#endif

        //Initiallise random numbers
	#ifdef VERB
        fprintf(stderr,"\tinput seed: %ld.    time0: %ld.",seed,t0);
	#endif

        if (seed>=0){
                srand(seed);
		#ifdef VERB
        	fprintf(stderr,"Used: %ld \n",seed);
		#endif
	}
        else {
                srand(t0);
        	fprintf(stderr,"Seed Used: %ld \n",t0);
	}

	mpart = (double) mp;
	//Nmin = (long)ceil(HaloMass[Nhalos-1]/mpart);
	Nmin = (long)ceil(HaloMass[Nend-1]*0.8/mpart);

	lcell = (float) L/NCells;
	#ifdef VERB
	fprintf(stderr,"\n\tParticles and Halos placed in %ld^3 cells\n",NCells);
	fprintf(stderr,"\tBOX = %f  lcell =%f   rho_ref = %e  invL %f\n",L,L/NCells,rho_ref,invL);
	fprintf(stderr,"\tNhalostart = %ld,Nhalosend = %ld,  NPart = %ld\n",Nstart, Nend, NTotPart);
	#endif
	

	#ifdef DEBUG
	fprintf(stderr,"\n\tRAND_MAX=%d\n",RAND_MAX);
	fprintf(stderr,"\tX[0] = %f Y[0] = %f Z[0] = %f\n",PartX[0],PartY[0],PartZ[0]);
	fprintf(stderr,"\tX[1] = %f Y[1] = %f Z[1] = %f\n",PartX[1],PartY[1],PartZ[1]);
	fprintf(stderr,"\tM[0] = %e \n",HaloMass[0]);
	fprintf(stderr,"\tM[1] = %e \n",HaloMass[1]);
	fprintf(stderr,"\tM[%ld] = %e \n",Nend-1,HaloMass[Nend-1]);
	fprintf(stderr,"\n\tMinimmum mass= %e. Minimum part per halo = %ld. mpart %e\n",HaloMass[Nend-1],Nmin,mpart);
	#endif	
	
	if (L/NCells<R_from_mass(HaloMass[0],rho_ref)){
		fprintf(stderr,"WARNING!!!: cell size is smaller than the radius of the biggest halo. Please, change the number of cells\n");
		//exit(0);
	}
	
	#ifdef VERB
	t1=time(NULL);
 	diff = difftime(t1,t0);
	fprintf(stderr,"\ttime of initialisation %f\n",diff);
	#endif
// ------------------------------------------------- Initiallised



#ifdef VERB
	fprintf(stderr,"\tAssigning particles to grid ...\n");
#endif



#ifdef VERB
	fprintf(stderr,"\t... particles counted ...\n");
	t2=time(NULL);
 	diff = difftime(t2,t1);
	fprintf(stderr,"\ttime counting %f\n",diff);
#endif

	//Alloc Enough Memory
	//ListOfPart = (long **) calloc(NCells*NCells*NCells,sizeof(long *));
	ListOfHalos = (long **) calloc(NCells*NCells*NCells,sizeof(long *));
	for (i=0;i<NCells;i++){
	for (j=0;j<NCells;j++){
	for (k=0;k<NCells;k++){
		lin_ijk = k+j*NCells+i*NCells*NCells;
		//ListOfPart[lin_ijk] = (long *) calloc(NPartPerCell[lin_ijk],sizeof(long));
		Nhalos = (long) (NPartPerCell[lin_ijk]/Nmin);
		ListOfHalos[lin_ijk] = (long *) calloc(Nhalos,sizeof(long));
		if (Nstart==0)
			MassLeft[lin_ijk] = (double) NPartPerCell[lin_ijk]*mpart; 
#ifdef ULTRADEBUG
		if (lin_ijk<10 || lin_ijk > (NCells*NCells*NCells) - 10){
			fprintf(stderr,"\tAllocated %ld (longs) in ListOfPart(%ld=[%ld,%ld,%ld])\n",NPartPerCell[lin_ijk],lin_ijk,i,j,k);
			fprintf(stderr,"\tAllocated %ld (longs) in ListOfHalos(%ld=[%ld,%ld,%ld])\n",Nhalos,lin_ijk,i,j,k);
		}
#endif		
	}	
	}
	}

#ifdef VERB
	fprintf(stderr,"\t... memory allocated ...\n");
	t3=time(NULL);
 	diff = difftime(t3,t2);
	fprintf(stderr,"\ttime allocating %f\n",diff);
#endif 


	for (ihalo=0;ihalo<Nstart;ihalo++){
		i = (long) (invL * HaloX[ihalo]*NCells);
		j = (long) (invL * HaloY[ihalo]*NCells);
		k = (long) (invL * HaloZ[ihalo]*NCells);
		i=check_limit(i,NCells);
		j=check_limit(j,NCells);
		k=check_limit(k,NCells);
		lin_ijk = k+j*NCells+i*NCells*NCells;
		ListOfHalos[lin_ijk][NHalosPerCell[lin_ijk]] = ihalo;
		NHalosPerCell[lin_ijk]++;
	}

#ifdef DEBUG
        fprintf(stderr,"\tMass_cell[0]=%e",MassLeft[0]);
	fprintf(stderr,"\t Mass Function\n");
	for (ihalo=0;ihalo<15;ihalo++){
		fprintf(stderr,"\thalo %ld: ",ihalo);
		fprintf(stderr,"M=%e\n",HaloMass[ihalo]);
	}
#endif


#ifdef VERB
	fprintf(stderr,"\t ...done\n\n");
	t4=time(NULL);
 	diff = difftime(t4,t3);
	fprintf(stderr,"\ttime of the actual assignment %f\n",diff);
	fprintf(stderr,"\tComputing probabilities...\n");
#endif

//----------------------------------- Particles and haloes assigned to grid





//Actually placing the haloes----------------------------------- 
	Halos_done =0;
	for(i_alpha=0;i_alpha<Nalpha;i_alpha++){
		exponent = alpha[i_alpha];
		tI=time(NULL);
		TotProb=ComputeCumulative(exponent, mpart, MassLeft, CumulativeProb);
		tII=time(NULL);
 		diff = difftime(tII,tI);
		fprintf(stderr,"\t\t alpha[%d]=%f. time computing prob: %f\n",i_alpha,exponent,diff);
		Nstart = Halos_done;
		Nend = Halos_done + Nhalosbin[i_alpha];
		fprintf(stderr,"\tNstart=%ld, Nend=%ld\n",Nstart,Nend);



		#ifndef NO_HALOS_PARALLEL
                #pragma omp parallel for private(Mhalo,ihalo,Mcell,R,i,j,k,lin_ijk,check,trials,ipart,icell) shared(rho_ref,HaloMass,NCells,TotProb,Nend,Nstart,stderr,ListOfHalos,ListOfPart,NHalosPerCell,NPartPerCell,MassLeft,PartX,PartY,PartZ,PartVX,PartVY,PartVZ,HaloX,HaloY,HaloZ,HaloVX,HaloVY,HaloVZ,HaloR,CumulativeProb,stdout) default(none)
		#endif
		for (ihalo=Nstart;ihalo<Nend;ihalo++){
			#ifdef DEBUG
			fprintf(stderr,"\n\t- Halo %ld \n",ihalo);
			#endif
			#ifdef VERB
			if ((ihalo%1000000)==0)
			fprintf(stderr,"\t%ld million haloes done\n",(ihalo/1000000));
			#endif


			Mhalo= HaloMass[ihalo];

			do {	
		 		 //First, choose a cell	
		  		trials=0;
		 		#ifndef RANKED				
				do{ 
		  			lin_ijk = select_cell(TotProb, CumulativeProb);
					if (trials == MAXTRIALS){
						fprintf(stderr,"WARNING: MAXTRIALS=%d reached and selected a complete cell\n",MAXTRIALS);
						break;
					}
					trials++;
		 		} while (MassLeft[lin_ijk]==0.);
		  		k=lin_ijk%(NCells);
		  		j=((lin_ijk-k)/NCells)%NCells;
	  	  		i=(lin_ijk-k-j*NCells)/(NCells*NCells);
		  		#else
		  		lin_ijk=select_heaviest_cell(&i,&j,&k);		  
		  		#endif


		  		trials=0;


		  		//Second, choose a particle in that cell
		  		do {
					ipart = select_part(lin_ijk,ListOfPart, NPartPerCell);		
               				HaloX[ihalo] = PartX[ipart];
               				HaloY[ihalo] = PartY[ipart];
               				HaloZ[ihalo] = PartZ[ipart];
               				HaloVX[ihalo] = PartVX[ipart];
               				HaloVY[ihalo] = PartVY[ipart];
               				HaloVZ[ihalo] = PartVZ[ipart];
					R=R_from_mass(HaloMass[ihalo],rho_ref);
					HaloR[ihalo]= R;
					#ifdef NO_EXCLUSION
					check = 0;
					#else
					//Third, check that is not overlapping a previous halo
					//check = check_HaloR_in_mesh(ihalo,HaloX,HaloY,HaloZ,HaloR,i,j,k,ListOfHalos,NHalosPerCell);
					fprintf(stderr,"Shouldnt be here!\n");
					#endif
					if (check==1){
						#ifdef DEBUG
						fprintf(stderr,"Refused part : %ld\n",ipart);
						#endif
						trials++;
					}
					if (trials == MAXTRIALS){
						//in order to avoid infinite loop, we will exit this loop, after MAXTRIALS trials
						//#ifdef VERB
						fprintf(stderr,"MAXTRIALS=%d reached, removing cell [%ld,%ld,%ld]\n",MAXTRIALS,i,j,k);
						//#endif
						MassLeft[lin_ijk]=0.;
						//TotProb=ComputeCumulative(exponent, mpart, MassLeft, CumulativeProb);
						break;
					}

		  		} while (check==1);//If the particle was excluded, try another one in the same cell

	        	} while(check==1); //if reached MAXTRIALS, select another cell
			//Particle chosen!
		
			//mass in cell before assignment
                	Mcell=MassLeft[lin_ijk];
		  	#ifndef MASS_OF_PARTS 
                  	if (Mcell>HaloMass[ihalo])
				MassLeft[lin_ijk] -= Mhalo; 
                	else
                        	MassLeft[lin_ijk] = 0.;
		  	#else
				exclude(ipart,R,PartX,PartY,PartZ,i,j,k);
		  	#endif



			#ifndef NO_MASS_CONSERVATION
				double ProbDiff = pow(MassLeft[lin_ijk]/mpart,exponent)-pow(Mcell/mpart,exponent);
				#ifdef DEBUG
				fprintf(stderr,"\n \tassigned to cell %ld=[%ld,%ld,%ld]\n\t Before: Mcell=%e, CProbCell=%e,  TotProb=%e. ",lin_ijk,i,j,k,Mcell,CumulativeProb[lin_ijk],TotProb);
				#endif
		
				#ifndef MASS_OF_PARTS
		  		//Substract the Probability difference from the array (only affected those cells after the selected one)
                  		#pragma omp parallel for private(icell) shared(CumulativeProb,ProbDiff,NTotCells,lin_ijk) default(none)
                  		for(icell=lin_ijk;icell<NTotCells;icell++){
                        		CumulativeProb[icell]+=ProbDiff;
                  		}
                  		TotProb=CumulativeProb[NCells*NCells*NCells-1];
				#endif
			#endif


			#ifdef DEBUG
				fprintf(stderr," After: Mcell=%e, CProbCell=%e, TotProb=%e.   ProbDiff=, Mhalo=%e. CProb[last]=%e\n",MassLeft[lin_ijk],CumulativeProb[lin_ijk],TotProb,Mhalo,CumulativeProb[NCells*NCells*NCells-1]);
				fprintf(stderr,"\thalo %ld assigned to particle %ld at [%f,%f,%f]. R= %f, M= %e\n",ihalo,ipart,HaloX[ihalo],HaloY[ihalo],HaloZ[ihalo],R,Mhalo);
			#endif

			ListOfHalos[lin_ijk][NHalosPerCell[lin_ijk]]=ihalo;
			NHalosPerCell[lin_ijk]++;
		}//for(ihalo=Halos_done + Nalpha)
		Halos_done += Nhalosbin[i_alpha];
	}
//----------------------------------- Haloes Placed




#ifdef VERB
	t5=time(NULL);
 	diff = difftime(t5,t4);
	fprintf(stderr,"\ttime placing %f\n",diff);
 	diff = difftime(t5,t0);
	fprintf(stderr,"\ttotal time in place_halos.c %f\n",diff);
	fprintf(stderr,"\n\tPlacement done!!!\n");
#endif
	free(NHalosPerCell);
        free(count); 
        free(CumulativeProb);
	free(MassLeft);
/*        for (i=0;i<NCells;i++){
                for (j=0;j<NCells;j++){
                        for (k=0;k<NCells;k++){
                                lin_ijk = k+j*NCells+i*NCells*NCells;
                                free(ListOfHalos[lin_ijk]);
                        }
                }
        }
*/
        free(ListOfHalos);
#ifdef MASS_OF_PARTS
	free(excluded); free(Nexcluded);
#endif
		fprintf(stderr," e ");
	return 0;
}
コード例 #17
0
ファイル: place_halos.c プロジェクト: savila/halogen.c
int place_halos(long NHalosTot, float *HaloMass, long Nlin, long NTotPart, float *PartX, float *PartY, float *PartZ, float L, float rho_ref, long seed, float mp, double *alpha, double *Malpha,long Nalpha,float *HaloX, float *HaloY, float *HaloZ, float *HaloR){

fprintf(stderr,"\tThis is place_halos.c v9.2\n");


//Initiallising -------------------------------------------------
	long i,j,k,lin_ijk,check, icell, Nmin;
	long *count,trials;
	long ihalo,ilong, ipart, Nhalos,i_alpha;
	double invL = 1./L, ProbDiff;
	float Mcell,Mhalo,Mchange,exp; 
	float R;
	time_t t0;

	#ifdef VERB
	time_t t1,t2,t3,t4,t5;
	float diff;
	#endif

	NCells = Nlin;
	Lbox = L;
	
	t0=time(NULL);
	NTotCells = NCells*NCells*NCells;
	
	//Allocate memory for the arrays 
	NPartPerCell = (long *) calloc(NCells*NCells*NCells,sizeof(long));
	NHalosPerCell = (long *) calloc(NCells*NCells*NCells,sizeof(long));
	MassLeft = (double *) calloc(NCells*NCells*NCells,sizeof(double));
	count = (long *) calloc(NCells*NCells*NCells,sizeof(long));


	CumulativeProb = (double *) calloc(NTotCells, sizeof(double));
  	if(CumulativeProb == NULL) {
    		fprintf(stderr,"\tplace_halos(): could not allocate %ld  array for CumulativeProb[]\nABORTING",NTotCells);
    		exit(-1);
	}
	fprintf(stderr,"\tUsing OMP with %d threads\n",omp_get_max_threads());

        //Initiallise random numbers
	#ifdef VERB
        fprintf(stderr,"\tinput seed: %ld.    time0: %ld. Used: ",seed,t0);
	#endif

        if (seed>=0){
                srand(seed);
		#ifdef VERB
        	fprintf(stderr,"%ld \n",seed);
		#endif
	}
        else {
                srand(t0);
		#ifdef VERB
        	fprintf(stderr,"%ld \n",t0);
		#endif
	}

	mpart = (double) mp;

	Nmin = (long)ceil(HaloMass[NHalosTot-1]/mpart);

	
	#ifdef VERB
	fprintf(stderr,"\n\tParticles and Halos placed in %ld^3 cells\n",NCells);
	fprintf(stderr,"\tBOX = %f  lcell =%f   rho_ref = %e  invL %f\n",L,L/NCells,rho_ref,invL);
	fprintf(stderr,"\tNhalos = %ld NPart = %ld\n",NHalosTot, NTotPart);
	#endif
	#ifdef DEBUG
	fprintf(stderr,"\n\tRAND_MAX=%d\n",RAND_MAX);
	fprintf(stderr,"\tX[0] = %f Y[0] = %f Z[0] = %f\n",PartX[0],PartY[0],PartZ[0]);
	fprintf(stderr,"\tX[1] = %f Y[1] = %f Z[1] = %f\n",PartX[1],PartY[1],PartZ[1]);
	fprintf(stderr,"\tM[0] = %e \n",HaloMass[0]);
	fprintf(stderr,"\tM[1] = %e \n",HaloMass[1]);
	fprintf(stderr,"\tM[%ld] = %e \n",NHalosTot-1,HaloMass[NHalosTot-1]);
	fprintf(stderr,"\n\tMinimmum mass= %e. Minimum part per halo = %ld. mpart %e\n",HaloMass[NHalosTot-1],Nmin,mpart);
	#endif	

	
	#ifdef VERB
	t1=time(NULL);
 	diff = difftime(t1,t0);
	fprintf(stderr,"\ttime of initialisation %f\n",diff);
	#endif
// ------------------------------------------------- Initiallised



#ifdef VERB
	fprintf(stderr,"\tAssigning particles to grid ...\n");
#endif


//Assign particles to grid ------------------------------------
	//count particles per cell
	for (ilong=0;ilong<NTotPart;ilong++) {
		i = (long) (invL * PartX[ilong]*NCells);
		j = (long) (invL * PartY[ilong]*NCells);
		k = (long) (invL * PartZ[ilong]*NCells);
		if (i<0 || i>=NCells || j<0 || j>=NCells || k<0 || k>=NCells){	
			fprintf(stderr,"\tWARNING: Particle %ld at [%f,%f,%f] seems to be out of the right box interval [0.,%f)",ilong,PartX[ilong],PartY[ilong],PartZ[ilong],L);	
			i=check_limit(i,NCells);
			j=check_limit(j,NCells);
			k=check_limit(k,NCells);
			fprintf(stderr,", placed at cell [%ld,%ld,%ld]\n",i,j,k);
		}
		lin_ijk = k+j*NCells+i*NCells*NCells;
		NPartPerCell[lin_ijk]++;
#ifdef DEBUG
		if(ilong<10 || ilong > NTotPart -10 || ilong==243666)
			fprintf(stderr,"\tipart=%ld  cell: %ld=[%ld,%ld,%ld] Parts in cell=%ld, Pos= [%f,%f,%f]\n",ilong,lin_ijk,i,j,k,NPartPerCell[lin_ijk],PartX[ilong],PartY[ilong],PartZ[ilong]);
#endif
	}
#ifdef VERB
	fprintf(stderr,"\t... particles counted ...\n");
	t2=time(NULL);
 	diff = difftime(t2,t1);
	fprintf(stderr,"\ttime counting %f\n",diff);
#endif
	//Alloc Enough Memory
	ListOfPart = (long **) calloc(NCells*NCells*NCells,sizeof(long *));
	ListOfHalos = (long **) calloc(NCells*NCells*NCells,sizeof(long *));
	for (i=0;i<NCells;i++){
	for (j=0;j<NCells;j++){
	for (k=0;k<NCells;k++){
		lin_ijk = k+j*NCells+i*NCells*NCells;
		ListOfPart[lin_ijk] = (long *) calloc(NPartPerCell[lin_ijk],sizeof(long));
		Nhalos = (long) (NPartPerCell[lin_ijk]/Nmin);
		ListOfHalos[lin_ijk] = (long *) calloc(Nhalos,sizeof(long));
		MassLeft[lin_ijk] = (double) NPartPerCell[lin_ijk]*mpart; 
#ifdef ULTRADEBUG
		if (lin_ijk<10 || lin_ijk > (NCells*NCells*NCells) - 10){
			fprintf(stderr,"\tAllocated %ld (longs) in ListOfPart(%ld=[%ld,%ld,%ld])\n",NPartPerCell[lin_ijk],lin_ijk,i,j,k);
			fprintf(stderr,"\tAllocated %ld (longs) in ListOfHalos(%ld=[%ld,%ld,%ld])\n",Nhalos,lin_ijk,i,j,k);
		}
#endif		
	}	
	}
	}

#ifdef VERB
	fprintf(stderr,"\t... memory allocated ...\n");
	t3=time(NULL);
 	diff = difftime(t3,t2);
	fprintf(stderr,"\ttime allocating %f\n",diff);
#endif

	for (ilong=0;ilong<NTotPart;ilong++) {
		i = (long) (invL * PartX[ilong]*NCells);
		j = (long) (invL * PartY[ilong]*NCells);
		k = (long) (invL * PartZ[ilong]*NCells);
		i=check_limit(i,NCells);
		j=check_limit(j,NCells);
		k=check_limit(k,NCells);
		lin_ijk = k+j*NCells+i*NCells*NCells;
		ListOfPart[lin_ijk][count[lin_ijk]] = ilong;
		count[lin_ijk]++;
	}

#ifdef DEBUG
        fprintf(stderr,"\tMass_cell[0]=%e",MassLeft[0]);
#endif

	Mhalo = HaloMass[0];
	i_alpha = 0;
	while(Mhalo<Malpha[i_alpha]) {
		i_alpha++;
		if (i_alpha==Nalpha){
			fprintf(stderr,"\tERROR: No alpha low enough found\n");
			exit(0);
		}
	}	
	Mchange = Malpha[i_alpha];
	exp = alpha[i_alpha];
	ComputeCumulative(exp);
#ifdef VERB
        fprintf(stderr,"\tNumber of alphas: %ld\n",Nalpha);
        fprintf(stderr,"\tUsing alpha_%ld=%f for M>%e\n",i_alpha,exp,Mchange);
#endif



//----------------------------------- Particles assigned to grid


#ifdef VERB
	fprintf(stderr,"\t ...done\n\n");
	t4=time(NULL);
 	diff = difftime(t4,t3);
	fprintf(stderr,"\ttime of the actual assignment %f\n",diff);
#endif
#ifdef DEBUG
	fprintf(stderr,"\t Mass Function\n");
	for (ihalo=0;ihalo<15;ihalo++){
		fprintf(stderr,"\thalo %ld: ",ihalo);
		fprintf(stderr,"M=%e\n",HaloMass[ihalo]);
	}
#endif

#ifdef VERB
	fprintf(stderr,"\n\tPlacing Halos...\n\n");
#endif

	for (ihalo=0;ihalo<NHalosTot;ihalo++){

		#ifdef DEBUG
		fprintf(stderr,"\n\t- Halo %ld ",ihalo);
		#endif
		
		do {		
		  #ifndef RANKED				
		  lin_ijk = select_cell();
		 
		  k=lin_ijk%(NCells);
		  j=((lin_ijk-k)/NCells)%NCells;
	  	  i=(lin_ijk-k-j*NCells)/(NCells*NCells);
		  #else
		  lin_ijk=select_heaviest_cell(&i,&j,&k);		  
		  #endif


		  trials=0;
		  do {
			ipart = select_part(lin_ijk);		
               		HaloX[ihalo] = PartX[ipart];
               		HaloY[ihalo] = PartY[ipart];
               		HaloZ[ihalo] = PartZ[ipart];
			R=R_from_mass(HaloMass[ihalo],rho_ref);
			HaloR[ihalo]= R;
			#ifdef NO_EXCLUSION
			check = 1;
			#else
			check = check_HaloR_in_mesh(ihalo,HaloX,HaloY,HaloZ,HaloR,i,j,k);
			#endif
			if (check==0){
				#ifdef DEBUG
				fprintf(stderr,"Refused part : %ld\n",ipart);
				#endif
				trials++;
			}
			if (trials == MAXTRIALS){
				#ifdef DEBUG
				fprintf(stderr,"MAXTRIALS=%d reached, selecting another cell\n",MAXTRIALS);
				#endif
				break;
			}
		  } while (check==0);//PART excluded
	        } while(check==0); //if reached MAXTRIALS, select another cell
		
                Mcell=MassLeft[lin_ijk];
		Mhalo= HaloMass[ihalo];

		while (Mhalo < Mchange){
			i_alpha++;		
			Mchange = Malpha[i_alpha];
			exp = alpha[i_alpha];
			ComputeCumulative(exp);
		#ifdef VERB
        		fprintf(stderr,"\n\tUsing alpha_%ld=%f for M>%e\n",i_alpha,exp,Mchange);
		#endif
		}
		
		#ifndef NO_MASS_CONSERVATION 
                if (Mcell>HaloMass[ihalo])
			MassLeft[lin_ijk] -= Mhalo; 
                else
                        MassLeft[lin_ijk] = 0.;
		#endif

		ProbDiff = pow(MassLeft[lin_ijk]/mpart,exp)-pow(Mcell/mpart,exp);

		#ifdef DEBUG
		fprintf(stderr,"\n \tassigned to cell %ld=[%ld,%ld,%ld]\n\t Before: Mcell=%e, TotProb=%e. ",lin_ijk,i,j,k,Mcell,TotProb);
		#endif

                #pragma omp parallel for private(icell) shared(CumulativeProb,ProbDiff,NTotCells,lin_ijk) default(none)
                for(icell=lin_ijk;icell<NTotCells;icell++){
                        CumulativeProb[icell]+=ProbDiff;
                }
                TotProb+=ProbDiff;

		#ifdef DEBUG
		fprintf(stderr," After: Mcell=%e, TotProb=%e.   ProbDiff=%e, Mhalo=%e\n",MassLeft[lin_ijk],TotProb,ProbDiff,Mhalo);
		#endif
	

		#ifdef DEBUG
		fprintf(stderr,"\thalo %ld assigned to particle %ld at [%f,%f,%f]. R= %f, M= %e\n",ihalo,ipart,HaloX[ihalo],HaloY[ihalo],HaloZ[ihalo],R,Mhalo);
		#endif

		ListOfHalos[lin_ijk][NHalosPerCell[lin_ijk]]=ihalo;
		NHalosPerCell[lin_ijk]++;
	}

#ifdef VERB
	t5=time(NULL);
 	diff = difftime(t5,t4);
	fprintf(stderr,"\ttime placing %f\n",diff);
 	diff = difftime(t5,t0);
	fprintf(stderr,"\ttotal time in .c %f\n",diff);
	fprintf(stderr,"\n\tPlacement done!!!\n");
#endif
	free(count); free(NPartPerCell); free(ListOfPart);
	free(CumulativeProb);
	return 0;
}
コード例 #18
0
ファイル: deck_con.cpp プロジェクト: OhnkytaBlabdey/ygopro
bool DeckBuilder::OnEvent(const irr::SEvent& event) {
	if(mainGame->dField.OnCommonEvent(event))
		return false;
	switch(event.EventType) {
	case irr::EET_GUI_EVENT: {
		s32 id = event.GUIEvent.Caller->getID();
		if(mainGame->wCategories->isVisible() && id != BUTTON_CATEGORY_OK)
			break;
		if(mainGame->wQuery->isVisible() && id != BUTTON_YES && id != BUTTON_NO)
			break;
		if(mainGame->wLinkMarks->isVisible() && id != BUTTON_MARKERS_OK)
			break;
		switch(event.GUIEvent.EventType) {
		case irr::gui::EGET_BUTTON_CLICKED: {
			switch(id) {
			case BUTTON_CLEAR_DECK: {
				deckManager.current_deck.main.clear();
				deckManager.current_deck.extra.clear();
				deckManager.current_deck.side.clear();
				break;
			}
			case BUTTON_SORT_DECK: {
				std::sort(deckManager.current_deck.main.begin(), deckManager.current_deck.main.end(), ClientCard::deck_sort_lv);
				std::sort(deckManager.current_deck.extra.begin(), deckManager.current_deck.extra.end(), ClientCard::deck_sort_lv);
				std::sort(deckManager.current_deck.side.begin(), deckManager.current_deck.side.end(), ClientCard::deck_sort_lv);
				break;
			}
			case BUTTON_SHUFFLE_DECK: {
				std::random_shuffle(deckManager.current_deck.main.begin(), deckManager.current_deck.main.end());
				break;
			}
			case BUTTON_SAVE_DECK: {
				int sel = mainGame->cbDBDecks->getSelected();
				if(sel >= 0 && deckManager.SaveDeck(deckManager.current_deck, mainGame->cbDBDecks->getItem(sel))) {
					mainGame->stACMessage->setText(dataManager.GetSysString(1335));
					mainGame->PopupElement(mainGame->wACMessage, 20);
				}
				break;
			}
			case BUTTON_SAVE_DECK_AS: {
				const wchar_t* dname = mainGame->ebDeckname->getText();
				if(*dname == 0)
					break;
				int sel = -1;
				for(size_t i = 0; i < mainGame->cbDBDecks->getItemCount(); ++i) {
					if(!wcscmp(dname, mainGame->cbDBDecks->getItem(i))) {
						sel = i;
						break;
					}
				}
				if(sel >= 0)
					mainGame->cbDBDecks->setSelected(sel);
				else {
					mainGame->cbDBDecks->addItem(dname);
					mainGame->cbDBDecks->setSelected(mainGame->cbDBDecks->getItemCount() - 1);
				}
				if(deckManager.SaveDeck(deckManager.current_deck, dname)) {
					mainGame->stACMessage->setText(dataManager.GetSysString(1335));
					mainGame->PopupElement(mainGame->wACMessage, 20);
				}
				break;
			}
			case BUTTON_DELETE_DECK: {
				int sel = mainGame->cbDBDecks->getSelected();
				if(sel == -1)
					break;
				mainGame->gMutex.Lock();
				wchar_t textBuffer[256];
				myswprintf(textBuffer, L"%ls\n%ls", mainGame->cbDBDecks->getItem(sel), dataManager.GetSysString(1337));
				mainGame->SetStaticText(mainGame->stQMessage, 310, mainGame->textFont, (wchar_t*)textBuffer);
				mainGame->PopupElement(mainGame->wQuery);
				mainGame->gMutex.Unlock();
				prev_operation = id;
				break;
			}
			case BUTTON_LEAVE_GAME: {
				Terminate();
				break;
			}
			case BUTTON_EFFECT_FILTER: {
				mainGame->PopupElement(mainGame->wCategories);
				break;
			}
			case BUTTON_START_FILTER: {
				StartFilter();
				break;
			}
			case BUTTON_CLEAR_FILTER: {
				ClearSearch();
				break;
			}
			case BUTTON_CATEGORY_OK: {
				filter_effect = 0;
				long long filter = 0x1;
				for(int i = 0; i < 32; ++i, filter <<= 1)
					if(mainGame->chkCategory[i]->isChecked())
						filter_effect |= filter;
				mainGame->HideElement(mainGame->wCategories);
				break;
			}
			case BUTTON_SIDE_OK: {
				if(deckManager.current_deck.main.size() != deckManager.pre_deck.main.size() || deckManager.current_deck.extra.size() != deckManager.pre_deck.extra.size()
				        || deckManager.current_deck.side.size() != deckManager.pre_deck.side.size()) {
					mainGame->env->addMessageBox(L"", dataManager.GetSysString(1410));
					break;
				}
				mainGame->imgCard->setImage(imageManager.tCover[0]);
				mainGame->stName->setText(L"");
				mainGame->stInfo->setText(L"");
				mainGame->stDataInfo->setText(L"");
				mainGame->stSetName->setText(L"");
				mainGame->stText->setText(L"");
				mainGame->showingcard = 0;
				mainGame->scrCardText->setVisible(false);
				char deckbuf[1024];
				char* pdeck = deckbuf;
				BufferIO::WriteInt32(pdeck, deckManager.current_deck.main.size() + deckManager.current_deck.extra.size());
				BufferIO::WriteInt32(pdeck, deckManager.current_deck.side.size());
				for(size_t i = 0; i < deckManager.current_deck.main.size(); ++i)
					BufferIO::WriteInt32(pdeck, deckManager.current_deck.main[i]->first);
				for(size_t i = 0; i < deckManager.current_deck.extra.size(); ++i)
					BufferIO::WriteInt32(pdeck, deckManager.current_deck.extra[i]->first);
				for(size_t i = 0; i < deckManager.current_deck.side.size(); ++i)
					BufferIO::WriteInt32(pdeck, deckManager.current_deck.side[i]->first);
				DuelClient::SendBufferToServer(CTOS_UPDATE_DECK, deckbuf, pdeck - deckbuf);
				break;
			}
			case BUTTON_SIDE_RELOAD: {
				deckManager.current_deck = deckManager.pre_deck;
				break;
			}
			case BUTTON_MSG_OK: {
				mainGame->HideElement(mainGame->wMessage);
				mainGame->actionSignal.Set();
				break;
			}
			case BUTTON_YES: {
				mainGame->HideElement(mainGame->wQuery);
				if(!mainGame->is_building || mainGame->is_siding)
					break;
				if(prev_operation == BUTTON_DELETE_DECK) {
					int sel = mainGame->cbDBDecks->getSelected();
					if(deckManager.DeleteDeck(deckManager.current_deck, mainGame->cbDBDecks->getItem(sel))) {
						mainGame->cbDBDecks->removeItem(sel);
						int count = mainGame->cbDBDecks->getItemCount();
						if(sel >= count)
							sel = count - 1;
						mainGame->cbDBDecks->setSelected(sel);
						if(sel != -1)
							deckManager.LoadDeck(mainGame->cbDBDecks->getItem(sel));
						mainGame->stACMessage->setText(dataManager.GetSysString(1338));
						mainGame->PopupElement(mainGame->wACMessage, 20);
						prev_deck = sel;
					}
				} else if(prev_operation == BUTTON_LEAVE_GAME) {
					Terminate();
				} else if(prev_operation == COMBOBOX_DBDECKS) {
					int sel = mainGame->cbDBDecks->getSelected();
					deckManager.LoadDeck(mainGame->cbDBDecks->getItem(sel));
					prev_deck = sel;
				}
				prev_operation = 0;
				break;
			}
			case BUTTON_NO: {
				mainGame->HideElement(mainGame->wQuery);
				if (prev_operation == COMBOBOX_DBDECKS) {
					mainGame->cbDBDecks->setSelected(prev_deck);
				}
				prev_operation = 0;
				break;
			}
			case BUTTON_MARKS_FILTER: {
				mainGame->PopupElement(mainGame->wLinkMarks);
				break;
			}
			case BUTTON_MARKERS_OK: {
				filter_marks = 0;
				if (mainGame->btnMark[0]->isPressed())
					filter_marks |= 0100;
				if (mainGame->btnMark[1]->isPressed())
					filter_marks |= 0200;
				if (mainGame->btnMark[2]->isPressed())
					filter_marks |= 0400;
				if (mainGame->btnMark[3]->isPressed())
					filter_marks |= 0010;
				if (mainGame->btnMark[4]->isPressed())
					filter_marks |= 0040;
				if (mainGame->btnMark[5]->isPressed())
					filter_marks |= 0001;
				if (mainGame->btnMark[6]->isPressed())
					filter_marks |= 0002;
				if (mainGame->btnMark[7]->isPressed())
					filter_marks |= 0004;
				mainGame->HideElement(mainGame->wLinkMarks);
				StartFilter();
				break;
			}
			}
			break;
		}
		case irr::gui::EGET_EDITBOX_ENTER: {
			switch(id) {
			case EDITBOX_KEYWORD: {
				StartFilter();
				break;
			}
			}
			break;
		}
		case irr::gui::EGET_EDITBOX_CHANGED: {
			switch (id) {
			case EDITBOX_KEYWORD: {
				stringw filter = mainGame->ebCardName->getText();
				if (filter.size() > 2) {
					StartFilter();
				}
				break;
			}
			case EDITBOX_DECK_NAME: {
				mainGame->ValidateName(mainGame->ebDeckname);
				break;
			}
			}
			break;
		}
		case irr::gui::EGET_COMBO_BOX_CHANGED: {
			switch(id) {
			case COMBOBOX_DBLFLIST: {
				filterList = deckManager._lfList[mainGame->cbDBLFList->getSelected()].content;
				break;
			}
			case COMBOBOX_DBDECKS: {
				int sel = mainGame->cbDBDecks->getSelected();
				if(sel >= 0)
					deckManager.LoadDeck(mainGame->cbDBDecks->getItem(sel));
				prev_deck = sel;
				break;
			}
			case COMBOBOX_MAINTYPE: {
				mainGame->cbCardType2->setSelected(0);
				mainGame->cbAttribute->setSelected(0);
				mainGame->cbRace->setSelected(0);
				mainGame->ebAttack->setText(L"");
				mainGame->ebDefense->setText(L"");
				mainGame->ebStar->setText(L"");
				mainGame->ebScale->setText(L"");
				switch(mainGame->cbCardType->getSelected()) {
				case 0: {
					mainGame->cbCardType2->setEnabled(false);
					mainGame->cbCardType2->setSelected(0);
					mainGame->cbRace->setEnabled(false);
					mainGame->cbAttribute->setEnabled(false);
					mainGame->ebAttack->setEnabled(false);
					mainGame->ebDefense->setEnabled(false);
					mainGame->ebStar->setEnabled(false);
					mainGame->ebScale->setEnabled(false);
					break;
				}
				case 1: {
					wchar_t normaltuner[32];
					wchar_t normalpen[32];
					wchar_t syntuner[32];
					mainGame->cbCardType2->setEnabled(true);
					mainGame->cbRace->setEnabled(true);
					mainGame->cbAttribute->setEnabled(true);
					mainGame->ebAttack->setEnabled(true);
					mainGame->ebDefense->setEnabled(true);
					mainGame->ebStar->setEnabled(true);
					mainGame->ebScale->setEnabled(true);
					mainGame->cbCardType2->clear();
					mainGame->cbCardType2->addItem(dataManager.GetSysString(1080), 0);
					mainGame->cbCardType2->addItem(dataManager.GetSysString(1054), TYPE_MONSTER + TYPE_NORMAL);
					mainGame->cbCardType2->addItem(dataManager.GetSysString(1055), TYPE_MONSTER + TYPE_EFFECT);
					mainGame->cbCardType2->addItem(dataManager.GetSysString(1056), TYPE_MONSTER + TYPE_FUSION);
					mainGame->cbCardType2->addItem(dataManager.GetSysString(1057), TYPE_MONSTER + TYPE_RITUAL);
					mainGame->cbCardType2->addItem(dataManager.GetSysString(1063), TYPE_MONSTER + TYPE_SYNCHRO);
					mainGame->cbCardType2->addItem(dataManager.GetSysString(1073), TYPE_MONSTER + TYPE_XYZ);
					mainGame->cbCardType2->addItem(dataManager.GetSysString(1074), TYPE_MONSTER + TYPE_PENDULUM);
					mainGame->cbCardType2->addItem(dataManager.GetSysString(1076), TYPE_MONSTER + TYPE_LINK);
					mainGame->cbCardType2->addItem(dataManager.GetSysString(1075), TYPE_MONSTER + TYPE_SPSUMMON);
					myswprintf(normaltuner, L"%ls|%ls", dataManager.GetSysString(1054), dataManager.GetSysString(1062));
					mainGame->cbCardType2->addItem(normaltuner, TYPE_MONSTER + TYPE_NORMAL + TYPE_TUNER);
					myswprintf(normalpen, L"%ls|%ls", dataManager.GetSysString(1054), dataManager.GetSysString(1074));
					mainGame->cbCardType2->addItem(normalpen, TYPE_MONSTER + TYPE_NORMAL + TYPE_PENDULUM);
					myswprintf(syntuner, L"%ls|%ls", dataManager.GetSysString(1063), dataManager.GetSysString(1062));
					mainGame->cbCardType2->addItem(syntuner, TYPE_MONSTER + TYPE_SYNCHRO + TYPE_TUNER);
					mainGame->cbCardType2->addItem(dataManager.GetSysString(1062), TYPE_MONSTER + TYPE_TUNER);
					mainGame->cbCardType2->addItem(dataManager.GetSysString(1061), TYPE_MONSTER + TYPE_DUAL);
					mainGame->cbCardType2->addItem(dataManager.GetSysString(1060), TYPE_MONSTER + TYPE_UNION);
					mainGame->cbCardType2->addItem(dataManager.GetSysString(1059), TYPE_MONSTER + TYPE_SPIRIT);
					mainGame->cbCardType2->addItem(dataManager.GetSysString(1071), TYPE_MONSTER + TYPE_FLIP);
					mainGame->cbCardType2->addItem(dataManager.GetSysString(1072), TYPE_MONSTER + TYPE_TOON);
					break;
				}
				case 2: {
					mainGame->cbCardType2->setEnabled(true);
					mainGame->cbRace->setEnabled(false);
					mainGame->cbAttribute->setEnabled(false);
					mainGame->ebAttack->setEnabled(false);
					mainGame->ebDefense->setEnabled(false);
					mainGame->ebStar->setEnabled(false);
					mainGame->ebScale->setEnabled(false);
					mainGame->cbCardType2->clear();
					mainGame->cbCardType2->addItem(dataManager.GetSysString(1080), 0);
					mainGame->cbCardType2->addItem(dataManager.GetSysString(1054), TYPE_SPELL);
					mainGame->cbCardType2->addItem(dataManager.GetSysString(1066), TYPE_SPELL + TYPE_QUICKPLAY);
					mainGame->cbCardType2->addItem(dataManager.GetSysString(1067), TYPE_SPELL + TYPE_CONTINUOUS);
					mainGame->cbCardType2->addItem(dataManager.GetSysString(1057), TYPE_SPELL + TYPE_RITUAL);
					mainGame->cbCardType2->addItem(dataManager.GetSysString(1068), TYPE_SPELL + TYPE_EQUIP);
					mainGame->cbCardType2->addItem(dataManager.GetSysString(1069), TYPE_SPELL + TYPE_FIELD);
					break;
				}
				case 3: {
					mainGame->cbCardType2->setEnabled(true);
					mainGame->cbRace->setEnabled(false);
					mainGame->cbAttribute->setEnabled(false);
					mainGame->ebAttack->setEnabled(false);
					mainGame->ebDefense->setEnabled(false);
					mainGame->ebStar->setEnabled(false);
					mainGame->ebScale->setEnabled(false);
					mainGame->cbCardType2->clear();
					mainGame->cbCardType2->addItem(dataManager.GetSysString(1080), 0);
					mainGame->cbCardType2->addItem(dataManager.GetSysString(1054), TYPE_TRAP);
					mainGame->cbCardType2->addItem(dataManager.GetSysString(1067), TYPE_TRAP + TYPE_CONTINUOUS);
					mainGame->cbCardType2->addItem(dataManager.GetSysString(1070), TYPE_TRAP + TYPE_COUNTER);
					break;
				}
				}
				StartFilter();
				break;
			}
			case COMBOBOX_SECONDTYPE:
			case COMBOBOX_OTHER_FILT: {
				if (id==COMBOBOX_SECONDTYPE && mainGame->cbCardType->getSelected() == 1) {
					if (mainGame->cbCardType2->getSelected() == 8) {
						mainGame->ebDefense->setEnabled(false);
						mainGame->ebDefense->setText(L"");
					} else {
						mainGame->ebDefense->setEnabled(true);
					}
				}
				StartFilter();
				break; 
			}
			case COMBOBOX_SORTTYPE: {
				SortList();
				mainGame->env->setFocus(0);
				break;
			}
			}
			break;
		}
		case irr::gui::EGET_CHECKBOX_CHANGED: {
			switch (id) {
				case CHECKBOX_SHOW_ANIME: {
					int prevLimit = mainGame->cbLimit->getSelected();
					mainGame->cbLimit->clear();
					mainGame->cbLimit->addItem(dataManager.GetSysString(1310));
					mainGame->cbLimit->addItem(dataManager.GetSysString(1316));
					mainGame->cbLimit->addItem(dataManager.GetSysString(1317));
					mainGame->cbLimit->addItem(dataManager.GetSysString(1318));
					mainGame->cbLimit->addItem(dataManager.GetSysString(1240));
					mainGame->cbLimit->addItem(dataManager.GetSysString(1241));
					mainGame->cbLimit->addItem(dataManager.GetSysString(1242));
					if(mainGame->chkAnime->isChecked()) {
						mainGame->cbLimit->addItem(dataManager.GetSysString(1243));
						mainGame->cbLimit->addItem(L"Illegal");
						mainGame->cbLimit->addItem(L"VG");
						mainGame->cbLimit->addItem(L"Custom");
					}
					if (prevLimit < 8)
						mainGame->cbLimit->setSelected(prevLimit);
					StartFilter();
					break;
				}
			}
			break;
		}
		default: break;
		}
		break;
	}
	case irr::EET_MOUSE_INPUT_EVENT: {
		switch(event.MouseInput.Event) {
		case irr::EMIE_LMOUSE_PRESSED_DOWN: {
			irr::gui::IGUIElement* root = mainGame->env->getRootGUIElement();
			if(root->getElementFromPoint(mouse_pos) != root)
				break;
			if(mainGame->wCategories->isVisible() || mainGame->wQuery->isVisible())
				break;
			if(hovered_pos == 0 || hovered_seq == -1)
				break;
			click_pos = hovered_pos;
			dragx = event.MouseInput.X;
			dragy = event.MouseInput.Y;
			draging_pointer = dataManager.GetCodePointer(hovered_code);
			if(draging_pointer == dataManager._datas.end())
				break;
			if(hovered_pos == 4) {
				if(!check_limit(draging_pointer))
					break;
			}
			is_draging = true;
			if(hovered_pos == 1)
				pop_main(hovered_seq);
			else if(hovered_pos == 2)
				pop_extra(hovered_seq);
			else if(hovered_pos == 3)
				pop_side(hovered_seq);
			mouse_pos.set(event.MouseInput.X, event.MouseInput.Y);
			GetHoveredCard();
			break;
		}
		case irr::EMIE_LMOUSE_LEFT_UP: {
			if(!is_draging)
				break;
			bool pushed = false;
			if(hovered_pos == 1)
				pushed = push_main(draging_pointer, hovered_seq);
			else if(hovered_pos == 2)
				pushed = push_extra(draging_pointer, hovered_seq + is_lastcard);
			else if(hovered_pos == 3)
				pushed = push_side(draging_pointer, hovered_seq + is_lastcard);
			else if(hovered_pos == 4 && !mainGame->is_siding)
				pushed = true;
			if(!pushed) {
				if(click_pos == 1)
					push_main(draging_pointer);
				else if(click_pos == 2)
					push_extra(draging_pointer);
				else if(click_pos == 3)
					push_side(draging_pointer);
			}
			is_draging = false;
			break;
		}
		case irr::EMIE_RMOUSE_LEFT_UP: {
			if(mainGame->is_siding) {
				if(is_draging)
					break;
				if(hovered_pos == 0 || hovered_seq == -1)
					break;
				auto pointer = dataManager.GetCodePointer(hovered_code);
				if(pointer == dataManager._datas.end())
					break;
				if(hovered_pos == 1) {
					if(push_side(pointer))
						pop_main(hovered_seq);
				} else if(hovered_pos == 2) {
					if(push_side(pointer))
						pop_extra(hovered_seq);
				} else {
					if(push_extra(pointer) || push_main(pointer))
						pop_side(hovered_seq);
				}
				break;
			}
			if(mainGame->wCategories->isVisible() || mainGame->wQuery->isVisible())
				break;
			if(!is_draging) {
				if(hovered_pos == 0 || hovered_seq == -1)
					break;
				if(hovered_pos == 1) {
					pop_main(hovered_seq);
				} else if(hovered_pos == 2) {
					pop_extra(hovered_seq);
				} else if(hovered_pos == 3) {
					pop_side(hovered_seq);
				} else {
					auto pointer = dataManager.GetCodePointer(hovered_code);
					if(pointer == dataManager._datas.end())
						break;
					if(event.MouseInput.Shift)
						push_side(pointer);
					else {
						if (!check_limit(pointer))
							break;
						if (!push_extra(pointer) && !push_main(pointer))
							push_side(pointer);
					}
				}
			} else {
				if(click_pos == 1) {
					push_side(draging_pointer);
				} else if(click_pos == 2) {
					push_side(draging_pointer);
				} else if(click_pos == 3) {
					if(!push_extra(draging_pointer))
						push_main(draging_pointer);
				} else {
					push_side(draging_pointer);
				}
				is_draging = false;
			}
			break;
		}
		case irr::EMIE_MMOUSE_LEFT_UP: {
			if (mainGame->is_siding)
				break;
			if (mainGame->wCategories->isVisible() || mainGame->wQuery->isVisible())
				break;
			if (hovered_pos == 0 || hovered_seq == -1)
				break;
			if (is_draging)
				break;
			auto pointer = dataManager.GetCodePointer(hovered_code);
			if(!check_limit(pointer))
				break;
			if (hovered_pos == 1) {
				if(!push_main(pointer))
					push_side(pointer);
			} else if (hovered_pos == 2) {
				if(!push_extra(pointer))
					push_side(pointer);
			} else if (hovered_pos == 3) {
				if(!push_side(pointer) && !push_extra(pointer))
					push_main(pointer);
			} else {
				if(!push_extra(pointer) && !push_main(pointer))
					push_side(pointer);
			}
			break;
		}
		case irr::EMIE_MOUSE_MOVED: {
			mouse_pos.set(event.MouseInput.X, event.MouseInput.Y);
			GetHoveredCard();
			break;
		}
		case irr::EMIE_MOUSE_WHEEL: {
			if(!mainGame->scrFilter->isVisible())
				break;
			if(!mainGame->Resize(805, 160, 1020, 630).isPointInside(mouse_pos))
				break;
			if(event.MouseInput.Wheel < 0) {
				if(mainGame->scrFilter->getPos() < mainGame->scrFilter->getMax())
					mainGame->scrFilter->setPos(mainGame->scrFilter->getPos() + 1);
			} else {
				if(mainGame->scrFilter->getPos() > 0)
					mainGame->scrFilter->setPos(mainGame->scrFilter->getPos() - 1);
			}
			GetHoveredCard();
			break;
		}
		default: break;
		}
		break;
	}
	default: break;
	}
	return false;
}
コード例 #19
0
ファイル: place_halos.c プロジェクト: savila/halogen.c
int place_halos(long NHalosTot, double *HaloMass, long Nlin, long NTotPart, float *PartX, float *PartY, float *PartZ, float L, float mp, float rho_ref, long seed, double *alpha, double *Malpha,long Nalpha,float *HaloX, float *HaloY, float *HaloZ){

fprintf(stderr,"Hi! This is place_halos.c v9.2\n");
fprintf(stdout,"Hi! This is place_halos.c v9.2\n");


//Initiallising -------------------------------------------------
	long i,j,k,lin_ijk,check, icell, Nmin;
	long *count,trials;
	long ihalo,ilong, ipart, Nhalos,i_alpha;
	double invL = 1./L,diff,ProbDiff,Mcell,Mhalo,Mchange,exp;
	float R; 
	double Mmin;	
	time_t t0,t1,t2,t3,t4,t5;
	NCells = Nlin;
	lcell=L/NCells;
	Lbox = L;
	
	t0=time(NULL);
	NTotCells = NCells*NCells*NCells;

	//temp
	float *HaloR;	
	
	//Allocate memory for the arrays 
	excluded = (long *) calloc(NTotPart, sizeof(long));
	NPartPerCell = (long *) calloc(NCells*NCells*NCells,sizeof(long));
	NHalosPerCell = (long *) calloc(NCells*NCells*NCells,sizeof(long));
	MassLeft = (double *) calloc(NCells*NCells*NCells,sizeof(double));
	count = (long *) calloc(NCells*NCells*NCells,sizeof(long));
	Nexcluded = (long *) calloc(NTotCells,sizeof(long)); 

	HaloR = (float *) calloc(NHalosTot,sizeof(float));

	CumulativeProb = (double *) calloc(NTotCells, sizeof(double));
  	if(CumulativeProb == NULL) {
    		fprintf(stderr,"place_halos(): could not allocate %ld  array for CumulativeProb[]\nABORTING",NTotCells);
    		exit(-1);
	}
	fprintf(stderr,"Using OMP with %d threads\n",omp_get_max_threads());

        //Initiallise random numbers
        if (seed>=0)
                srand(seed);
        else
                srand(t0);

        fprintf(stderr,"input seed: %ld.    time0: %ld\n",seed,t0);


	mpart = (double) mp;



#ifdef _VERB
	fprintf(stderr,"#def _VERB\n");
#endif 
#ifdef _DEBUG
	fprintf(stderr,"#def _DEBUG \n");
#endif
#ifdef _ULTRADEBUG
	fprintf(stderr,"#def _ULTRADEBUG \n");
#endif
#ifdef _PERIODIC
	fprintf(stderr,"#def _PERIODIC\n");
#endif
#ifdef _ONLYBIG
	fprintf(stderr,"#def _ONLYBIG\n");
#endif

	Mmin = HaloMass[NHalosTot-1];
	Nmin = (long)ceil(HaloMass[NHalosTot-1]/mp);

	
	#ifdef _VERB
	fprintf(stderr,"\nMassFunction computed globally with hmf. Particles and Halos placed in %ld^3 cells\n",NCells);
	fprintf(stderr,"Exclusion done only with haloes.\n");
	fprintf(stderr,"BOX = %f  lcell =%f   rho_ref = %e  invL %f\n",L,lcell,rho_ref,invL);
	fprintf(stderr,"Nhalos = %ld NPart = %ld\n",NHalosTot, NTotPart);
	fprintf(stderr,"\nRAND_MAX=%d\n",RAND_MAX);
	fprintf(stderr,"X[0] = %f Y[0] = %f Z[0] = %f\n",PartX[0],PartY[0],PartZ[0]);
	fprintf(stderr,"X[1] = %f Y[1] = %f Z[1] = %f\n",PartX[1],PartY[1],PartZ[1]);
	fprintf(stderr,"M[0] = %e \n",HaloMass[0]);
	fprintf(stderr,"M[1] = %e \n",HaloMass[1]);
	fprintf(stderr,"\nExclusion done only with haloes. Minimmum mass= %e. Minimum part per halo = %ld. Effective mp (not the real one) %e\n",HaloMass[NHalosTot-1],Nmin,mp);
	#endif	

	
	


	t1=time(NULL);
 	diff = difftime(t1,t0);
	fprintf(stderr,"time of initialisation %f\n",diff);
// ------------------------------------------------- Initiallised



#ifdef _VERB
	fprintf(stderr,"Assigning particles to grid ...\n");
#endif


//Assign particles to grid ------------------------------------
	//count particles per cell
	for (ilong=0;ilong<NTotPart;ilong++) {
		i = (long) (invL * PartX[ilong]*NCells);
		j = (long) (invL * PartY[ilong]*NCells);
		k = (long) (invL * PartZ[ilong]*NCells);
		if (i<0 || i>=NCells || j<0 || j>=NCells || k<0 || k>=NCells){	
			fprintf(stderr,"WARNING: Particle %ld at [%f,%f,%f] seems to be out of the right box interval [0.,%f)",ilong,PartX[ilong],PartY[ilong],PartZ[ilong],L);	
			i=check_limit(i,NCells);
			j=check_limit(j,NCells);
			k=check_limit(k,NCells);
			fprintf(stderr,", placed at cell [%ld,%ld,%ld]\n",i,j,k);
		}
		lin_ijk = k+j*NCells+i*NCells*NCells;
		NPartPerCell[lin_ijk]++;
#ifdef _DEBUG
		if(ilong<10 || ilong > NTotPart -10 || ilong==243666)
			fprintf(stderr,"ipart=%ld  cell: %ld=[%ld,%ld,%ld] Parts in cell=%ld, Pos= [%f,%f,%f]\n",ilong,lin_ijk,i,j,k,NPartPerCell[lin_ijk],PartX[ilong],PartY[ilong],PartZ[ilong]);
#endif
	}
#ifdef _DEBUG
	fprintf(stderr,"... particles counted ...\n");
	t2=time(NULL);
 	diff = difftime(t2,t1);
	fprintf(stderr,"time counting %f\n",diff);
#endif
	//Alloc Enough Memory
	ListOfPart = (long **) calloc(NCells*NCells*NCells,sizeof(long *));
	ListOfHalos = (long **) calloc(NCells*NCells*NCells,sizeof(long *));
	for (i=0;i<NCells;i++){
	for (j=0;j<NCells;j++){
	for (k=0;k<NCells;k++){
		lin_ijk = k+j*NCells+i*NCells*NCells;
		ListOfPart[lin_ijk] = (long *) calloc(NPartPerCell[lin_ijk],sizeof(long));
		Nhalos = (long) (NPartPerCell[lin_ijk]/Nmin);
		ListOfHalos[lin_ijk] = (long *) calloc(Nhalos,sizeof(long));
		MassLeft[lin_ijk] = (double) NPartPerCell[lin_ijk]*mpart; 
#ifdef _ULTRADEBUG
		if (lin_ijk<10 || lin_ijk > (NCells*NCells*NCells) - 10){
			fprintf(stderr,"Allocated %ld (longs) in ListOfPart(%ld=[%ld,%ld,%ld])\n",NPartPerCell[lin_ijk],lin_ijk,i,j,k);
			fprintf(stderr,"Allocated %ld (longs) in ListOfHalos(%ld=[%ld,%ld,%ld])\n",Nhalos,lin_ijk,i,j,k);
		}
#endif		
	}	
	}
	}

#ifdef _DEBUG
	fprintf(stderr,"... memory allocated ...\n");
	t3=time(NULL);
 	diff = difftime(t3,t2);
	fprintf(stderr,"time allocating %f\n",diff);
#endif

	for (ilong=0;ilong<NTotPart;ilong++) {
		i = (long) (invL * PartX[ilong]*NCells);
		j = (long) (invL * PartY[ilong]*NCells);
		k = (long) (invL * PartZ[ilong]*NCells);
		i=check_limit(i,NCells);
		j=check_limit(j,NCells);
		k=check_limit(k,NCells);
		lin_ijk = k+j*NCells+i*NCells*NCells;
		ListOfPart[lin_ijk][count[lin_ijk]] = ilong;
		count[lin_ijk]++;
	}


        fprintf(stderr,"Mass_cell[0]=%e",MassLeft[0]);
        fprintf(stderr,"  TotProb=%e\n",TotProb);
	

	Mhalo = HaloMass[0];
	i_alpha = 0;
	while(Mhalo<Malpha[i_alpha]) {
		i_alpha++;
		if (i_alpha==Nalpha){
			fprintf(stderr,"ERROR: No alpha low enough found\n");
			exit(0);
		}
	}	
	Mchange = Malpha[i_alpha];
	exp = alpha[i_alpha];
	ComputeCumulative(exp);
//----------------------------------- Particles assigned to grid


#ifdef _VERB
	fprintf(stderr," ...done\n\n");
	t4=time(NULL);
 	diff = difftime(t4,t3);
	fprintf(stderr,"time of the actual assignment %f\n",diff);
#endif
#ifdef _DEBUG
	fprintf(stderr," Mass Function\n");
	for (ihalo=0;ihalo<15;ihalo++){
		fprintf(stderr,"halo %ld: ",ihalo);
		fprintf(stderr,"M=%e\n",HaloMass[ihalo]);
	}
#endif

#ifdef _VERB
	fprintf(stderr,"\nPlacing Halos...\n\n");
#endif

	for (ihalo=0;ihalo<NHalosTot;ihalo++){

		#ifdef _DEBUG
		fprintf(stderr,"\n- Halo %ld ",ihalo);
		#endif
		
				
		lin_ijk = select_cell();

		if(lin_ijk<0) {
			fprintf(stderr,"Maximum Mass cell was %e\n",MassLeft[select_heaviest_cell(&i,&j,&k,MassLeft,NCells,HaloMass[ihalo])]);
			break;
		}

		k=lin_ijk%(NCells);
		j=((lin_ijk-k)/NCells)%NCells;
		i=(lin_ijk-k-j*NCells)/(NCells*NCells);


                Mcell=MassLeft[lin_ijk];
		Mhalo= HaloMass[ihalo];

		while (Mhalo < Mchange){
			i_alpha++;		
			Mchange = Malpha[i_alpha];
			exp = alpha[i_alpha];
			ComputeCumulative(exp);
		}

                if (Mcell>HaloMass[ihalo])
			MassLeft[lin_ijk] -= Mhalo; 
                else
                        MassLeft[lin_ijk] = 0.;

		ProbDiff = pow(MassLeft[lin_ijk]/mpart,exp)-pow(Mcell/mpart,exp);

		#ifdef _DEBUG
		fprintf(stderr,"\n assigned to cell %ld=[%ld,%ld,%ld]\n Before: Mcell=%e, TotProb=%e. ",lin_ijk,i,j,k,Mcell,TotProb);
		#endif

                #pragma omp parallel for private(icell) shared(CumulativeProb,ProbDiff,NTotCells,lin_ijk) default(none)
                for(icell=lin_ijk;icell<NTotCells;icell++){
                        CumulativeProb[icell]+=ProbDiff;
                }
                TotProb+=ProbDiff;

		#ifdef _DEBUG
		fprintf(stderr," After: Mcell=%e, TotProb=%e.   ProbDiff=%e, Mhalo=%e\n",MassLeft[lin_ijk],TotProb,ProbDiff,Mhalo);
		#endif
	
		trials=0;
		do {
			ipart = select_part(lin_ijk);		
               		HaloX[ihalo] = PartX[ipart];
               		HaloY[ihalo] = PartY[ipart];
               		HaloZ[ihalo] = PartZ[ipart];
			R=R_from_mass(HaloMass[ihalo],rho_ref);
			HaloR[ihalo]=R;
			check = check_HaloR_in_mesh(ihalo,HaloX,HaloY,HaloZ,HaloR,i,j,k);
			if (check==0){
				#ifdef _DEBUG
				fprintf(stderr,"Refused part : %ld\n",ipart);
				#endif
				trials++;
			}
			if (trials ==20)
				exit(-1);

		} while (check==0);

		#ifdef _DEBUG
		fprintf(stderr,"halo %ld assigned to particle %ld at [%f,%f,%f]. R= %f, M= %e\n",ihalo,ipart,HaloX[ihalo],HaloY[ihalo],HaloZ[ihalo],R,Mhalo);
		#endif

		ListOfHalos[lin_ijk][NHalosPerCell[lin_ijk]]=ihalo;
		NHalosPerCell[lin_ijk]++;
	}

#ifdef _VERB
	t5=time(NULL);
 	diff = difftime(t5,t4);
	fprintf(stderr,"time placing %f\n",diff);
 	diff = difftime(t5,t0);
	fprintf(stderr,"total time in .c %f\n",diff);
	fprintf(stderr,"\nEverything done!!!\n");
#endif
	free(count); free(NPartPerCell); free(ListOfPart); free(excluded);
	free(CumulativeProb);
	return 0;
}
コード例 #20
0
ファイル: tocentry.c プロジェクト: ncbi/ncbi-vdb
static
rc_t KTocEntryInflateNodeCommon (const void ** ptr,
				 const void * limit,
				 KTocEntryInflateCommon * common,
				 const char * path,
				 bool rev)
{
    rc_t rc;
    uint16_t plen;
    uint16_t nlen;

    rc = read_u16 (ptr, limit, rev, &nlen);
    if (rc)
	return rc;

    if (check_limit (*ptr, limit, nlen))
	return RC (rcFS, rcTocEntry, rcParsing, rcBuffer, rcTooShort);;

    plen = (uint16_t)strlen (path);
    if (plen == 0)
    {
	common->name = malloc (nlen+1);
	if (common->name == NULL)
	{
	    return RC (rcFS, rcTocEntry, rcInflating, rcMemory, rcExhausted);
	}
	memmove (common->name, *ptr, nlen);
	common->name[nlen] = '\0';
    }
    else
    {
	common->name = malloc (plen + 1 + nlen+1);
	if (common->name == NULL)
	{
	    return RC (rcFS, rcTocEntry, rcInflating, rcMemory, rcExhausted);
	}
	memmove (common->name, path, plen);
	common->name[plen] = '/';
	memmove (common->name+plen+1, *ptr, nlen);
	common->name[plen + nlen + 1] = '\0';
    }

    *ptr = ((uint8_t*)*ptr) + nlen;

    rc = read_i64 (ptr, limit, rev, &common->mtime);
    if (rc == 0)
    {
	rc =read_u32 (ptr, limit, rev, &common->access);
	if (rc == 0)
	{
	    uint8_t type;
	    rc = read_u8 (ptr, limit, &type);
	    if (rc == 0)
	    {
		common->type = type;
		return 0;
	    }
	}
    }
    free (common->name);
    common->name = NULL;
    common->mtime = 0;
    common->access = 0;
    common->type = ktocentrytype_unknown;
    return rc;
}
コード例 #21
0
ファイル: place_halos_original.c プロジェクト: savila/HALOGEN
//place_halos():
//
//Takes a list of halo masses (Nhalos, HaloMass), a list of particles (NTotPart,PartX,PartY,PartZ), some simulation parameters (L, mp), and user-defined parameters (Nlin,rho_ref,alpha,Malpha,Nalpha,seed)
//and returns a list of halo positions and radii (HaloX,HaloY,HaloZ,HaloR)
int place_halos(long Nend, float *HaloMass, long Nlin, long NTotPart, float *PartX, float *PartY, float *PartZ, float *PartVX, float *PartVY, float *PartVZ,float L, float rho_ref, long seed, float mp, double *alpha, double *Malpha,long Nalpha,float *HaloX, float *HaloY, float *HaloZ, float *HaloVX, float *HaloVY, float *HaloVZ,float *HaloR,long **ListOfPart, long *NPartPerCell){


fprintf(stderr,"\tThis is place_halos.c v11\n");


//Initiallising -------------------------------------------------
	long i,j,k,lin_ijk, Nmin;
	long *count,trials;
	long ihalo,ilong, ipart,i_alpha;
	double invL = 1./L;
	float Mcell,Mhalo,Mchange; 
	float R;
	time_t t0;
	int check;

	double mpart;
	double exponent;
	double TotProb;
	double *MassLeft;
	double *CumulativeProb; 
	long **ListOfHalos,  *NHalosPerCell;
	long Nstart=0,Nhalos;

	#ifdef VERB
	time_t t1,t2,t3,t4,t4_5,t5;
	float diff;
	#endif

	NCells = Nlin;
	Lbox = L;
	
	t0=time(NULL);
	NTotCells = NCells*NCells*NCells;
	
	MassLeft = malloc(NTotCells*sizeof(double));


	//Allocate memory for the arrays 
	//NPartPerCell = (long *) calloc(NTotCells,sizeof(long));
  /*	if( NPartPerCell == NULL) {
    		fprintf(stderr,"\tplace_halos(): could not allocate %ld array for NPartPerCell[]\nABORTING",NTotCells);
    		exit(-1);
	}*/
	NHalosPerCell = (long *) calloc(NTotCells,sizeof(long));
  	if(NHalosPerCell == NULL) {
    		fprintf(stderr,"\tplace_halos(): could not allocate %ld array for NHalosPerCell[]\nABORTING",NTotCells);
    		exit(-1);
	}
	count = (long *) calloc(NTotCells,sizeof(long));
  	if(count == NULL) {
    		fprintf(stderr,"\tplace_halos(): could not allocate %ld array for NTotCells[]\nABORTING",NTotCells);
    		exit(-1);
	}
	CumulativeProb = (double *) calloc(NTotCells, sizeof(double));
  	if(CumulativeProb == NULL) {
    		fprintf(stderr,"\tplace_halos(): could not allocate %ld array for CumulativeProb[]\nABORTING",NTotCells);
    		exit(-1);
	}
	fprintf(stderr,"\tUsing OMP with %d threads\n",omp_get_max_threads());
	
	#ifdef MASS_OF_PARTS
	Nexcluded = (long *) calloc(NTotCells,sizeof(long));
  	if(Nexcluded == NULL) {
    		fprintf(stderr,"\tplace_halos(): could not allocate %ld array for Nexcluded[]\nABORTING",NTotCells);
    		exit(-1);
	}
 	excluded  = (int *) calloc(NTotPart, sizeof(long));
  	if(excluded == NULL) {
    		fprintf(stderr,"\tplace_halos(): could not allocate %ld array for excluded[]\nABORTING",NTotPart);
    		exit(-1);
	}
	#endif

        //Initiallise random numbers
	#ifdef VERB
        fprintf(stderr,"\tinput seed: %ld.    time0: %ld.",seed,t0);
	#endif

        if (seed>=0){
                srand(seed);
		#ifdef VERB
        	fprintf(stderr,"Used: %ld \n",seed);
		#endif
	}
        else {
                srand(t0);
        	fprintf(stderr,"Seed Used: %ld \n",t0);
	}

	mpart = (double) mp;
	//Nmin = (long)ceil(HaloMass[Nhalos-1]/mpart);
	Nmin = (long)ceil(HaloMass[Nend-1]*0.8/mpart);

	lcell = (float) L/NCells;
	#ifdef VERB
	fprintf(stderr,"\n\tParticles and Halos placed in %ld^3 cells\n",NCells);
	fprintf(stderr,"\tBOX = %f  lcell =%f   rho_ref = %e  invL %f\n",L,L/NCells,rho_ref,invL);
	fprintf(stderr,"\tNhalostart = %ld,Nhalosend = %ld,  NPart = %ld\n",Nstart, Nend, NTotPart);
	#endif
	

	#ifdef DEBUG
	fprintf(stderr,"\n\tRAND_MAX=%d\n",RAND_MAX);
	fprintf(stderr,"\tX[0] = %f Y[0] = %f Z[0] = %f\n",PartX[0],PartY[0],PartZ[0]);
	fprintf(stderr,"\tX[1] = %f Y[1] = %f Z[1] = %f\n",PartX[1],PartY[1],PartZ[1]);
	fprintf(stderr,"\tM[0] = %e \n",HaloMass[0]);
	fprintf(stderr,"\tM[1] = %e \n",HaloMass[1]);
	fprintf(stderr,"\tM[%ld] = %e \n",Nend-1,HaloMass[Nend-1]);
	fprintf(stderr,"\n\tMinimmum mass= %e. Minimum part per halo = %ld. mpart %e\n",HaloMass[Nend-1],Nmin,mpart);
	#endif	
	
	if (L/NCells<R_from_mass(HaloMass[0],rho_ref)){
		fprintf(stderr,"ERROR: cell size is smaller than the radius of the biggest halo. Please, change the number of cells\n");
		exit(0);
	}
	
	#ifdef VERB
	t1=time(NULL);
 	diff = difftime(t1,t0);
	fprintf(stderr,"\ttime of initialisation %f\n",diff);
	#endif
// ------------------------------------------------- Initiallised



#ifdef VERB
	fprintf(stderr,"\tAssigning particles to grid ...\n");
#endif


//Assign particles to grid ------------------------------------
	//count particles per cell
	/*for (ilong=0;ilong<NTotPart;ilong++) {

                if (PartX[ilong]==Lbox)
                        PartX[ilong]=0.;
                if (PartY[ilong]==Lbox)
                        PartY[ilong]=0.;
                if (PartZ[ilong]==Lbox)
                        PartZ[ilong]=0.;
                i = (long) (invL * PartX[ilong]*NCells);
                j = (long) (invL * PartY[ilong]*NCells);
                k = (long) (invL * PartZ[ilong]*NCells);
                if (i<0 || i>=NCells || j<0 || j>=NCells || k<0 || k>=NCells){
                        fprintf(stderr,"\tERROR: Particle %ld at [%f,%f,%f] seems to be out of the right box interval [0.,%f)",ilong,PartX[ilong],PartY[ilong],PartZ[ilong],L);
		}

		lin_ijk = k+j*NCells+i*NCells*NCells;
//		NPartPerCell[lin_ijk]++;
#ifdef DEBUG
		if(ilong<10 || ilong > NTotPart -10 || ilong==243666)
			fprintf(stderr,"\tipart=%ld  cell: %ld=[%ld,%ld,%ld] Parts in cell=%ld, Pos= [%f,%f,%f]\n",ilong,lin_ijk,i,j,k,NPartPerCell[lin_ijk],PartX[ilong],PartY[ilong],PartZ[ilong]);
#endif
	}*/
#ifdef VERB
	fprintf(stderr,"\t... particles counted ...\n");
	t2=time(NULL);
 	diff = difftime(t2,t1);
	fprintf(stderr,"\ttime counting %f\n",diff);
#endif
	//Alloc Enough Memory
	//ListOfPart = (long **) calloc(NCells*NCells*NCells,sizeof(long *));
	ListOfHalos = (long **) calloc(NCells*NCells*NCells,sizeof(long *));
	for (i=0;i<NCells;i++){
	for (j=0;j<NCells;j++){
	for (k=0;k<NCells;k++){
		lin_ijk = k+j*NCells+i*NCells*NCells;
		//ListOfPart[lin_ijk] = (long *) calloc(NPartPerCell[lin_ijk],sizeof(long));
		Nhalos = (long) (NPartPerCell[lin_ijk]/Nmin);
		ListOfHalos[lin_ijk] = (long *) calloc(Nhalos,sizeof(long));
		if (Nstart==0)
			MassLeft[lin_ijk] = (double) NPartPerCell[lin_ijk]*mpart; 
#ifdef ULTRADEBUG
		if (lin_ijk<10 || lin_ijk > (NCells*NCells*NCells) - 10){
			fprintf(stderr,"\tAllocated %ld (longs) in ListOfPart(%ld=[%ld,%ld,%ld])\n",NPartPerCell[lin_ijk],lin_ijk,i,j,k);
			fprintf(stderr,"\tAllocated %ld (longs) in ListOfHalos(%ld=[%ld,%ld,%ld])\n",Nhalos,lin_ijk,i,j,k);
		}
#endif		
	}	
	}
	}

#ifdef VERB
	fprintf(stderr,"\t... memory allocated ...\n");
	t3=time(NULL);
 	diff = difftime(t3,t2);
	fprintf(stderr,"\ttime allocating %f\n",diff);
#endif 
/*
	#pragma omp parallel for private(ilong,i,k,j,lin_ijk) shared(NTotPart,invL,NCells,ListOfPart,count,PartZ,PartX,PartY,L,stderr) default(none)
	for (ilong=0;ilong<NTotPart;ilong++) {
		i = (long) (invL * PartX[ilong]*NCells);
		j = (long) (invL * PartY[ilong]*NCells);
		k = (long) (invL * PartZ[ilong]*NCells);
                if (i<0 || i>=NCells || j<0 || j>=NCells || k<0 || k>=NCells){
                        fprintf(stderr,"\tERROR: Particle %ld at [%f,%f,%f] seems to be out of the right box interval [0.,%f)",ilong,PartX[ilong],PartY[ilong],PartZ[ilong],L);
		}
		lin_ijk = k+j*NCells+i*NCells*NCells;
		ListOfPart[lin_ijk][count[lin_ijk]] = ilong;
		count[lin_ijk]++;
	}

#ifdef VERB
	fprintf(stderr,"\t...particles assigned, now haloes...\n");
#endif */
	for (ihalo=0;ihalo<Nstart;ihalo++){
		i = (long) (invL * HaloX[ihalo]*NCells);
		j = (long) (invL * HaloY[ihalo]*NCells);
		k = (long) (invL * HaloZ[ihalo]*NCells);
		i=check_limit(i,NCells);
		j=check_limit(j,NCells);
		k=check_limit(k,NCells);
		lin_ijk = k+j*NCells+i*NCells*NCells;
		ListOfHalos[lin_ijk][NHalosPerCell[lin_ijk]] = ihalo;
		NHalosPerCell[lin_ijk]++;
	}

#ifdef DEBUG
        fprintf(stderr,"\tMass_cell[0]=%e",MassLeft[0]);
	fprintf(stderr,"\t Mass Function\n");
	for (ihalo=0;ihalo<15;ihalo++){
		fprintf(stderr,"\thalo %ld: ",ihalo);
		fprintf(stderr,"M=%e\n",HaloMass[ihalo]);
	}
#endif


#ifdef VERB
	fprintf(stderr,"\t ...done\n\n");
	t4=time(NULL);
 	diff = difftime(t4,t3);
	fprintf(stderr,"\ttime of the actual assignment %f\n",diff);
	fprintf(stderr,"\tComputing probabilities...\n");
#endif

//----------------------------------- Particles and haloes assigned to grid



//Computing Cumulative Probability -----------------------------
	
	//find the right alpha
	Mhalo = HaloMass[Nstart];
	i_alpha = 0;
	while(Mhalo<Malpha[i_alpha]) {
		i_alpha++;
		if (i_alpha==Nalpha){
			fprintf(stderr,"\tERROR: No M_alpha low enough found\n");
			fprintf(stderr,"\tERROR: N_alpha = %ld, Mh=%e, Ma= %e\n",Nalpha,Mhalo,Malpha[i_alpha-1]);
			exit(0);
		}
	}	
	Mchange = Malpha[i_alpha];
	exponent = alpha[i_alpha];
	//compute the probability
	TotProb = ComputeCumulative(exponent, mpart, MassLeft, CumulativeProb);
#ifdef VERB
        fprintf(stderr,"\tNumber of alphas: %ld\n",Nalpha);
        fprintf(stderr,"\tUsing alpha_%ld=%f for M>%e\n",i_alpha,exponent,Mchange);

	t4_5=time(NULL);
 	diff = difftime(t4_5,t4);
	fprintf(stderr,"\tprobabilty computed in %f secods\n",diff);
#endif
// ----------------------------------------- Computed Probability




//Actually placing the haloes----------------------------------- 
#ifdef VERB
	fprintf(stderr,"\n\tPlacing Halos...\n\n");
#endif

	//Place one by one all the haloes (assumed to be ordered from the most massive to the least massive)
	for (ihalo=Nstart;ihalo<Nend;ihalo++){

		#ifdef DEBUG
		fprintf(stderr,"\n\t- Halo %ld ",ihalo);
		#endif
		#ifdef VERB
		if ((ihalo%1000000)==0)
			fprintf(stderr,"\t%ld million haloes done\n",(ihalo/1000000));
		#endif
		//Check whether or not, a change of alpha is needed for this halo mass 		
		Mhalo= HaloMass[ihalo];
//		if (ihalo<=-1)
//			fprintf(stderr,"\tMhalo=%e\n",Mhalo);

		while (Mhalo < Mchange){//if so search the right alpha, and recompute probabilities
			i_alpha++;		
			if (i_alpha==Nalpha){
				fprintf(stderr,"\tERROR: No M_alpha low enough found\n");
				exit(0);
			}
			Mchange = Malpha[i_alpha];
			exponent = alpha[i_alpha];
			TotProb=ComputeCumulative(exponent, mpart, MassLeft, CumulativeProb);
		#ifdef VERB
        		fprintf(stderr,"\n\tUsing alpha_%ld=%f for M>%e\n",i_alpha,exponent,Mchange);
		#endif
		}
//		if (ihalo<=-1)
//			fprintf(stderr,"\talpha=%f\n",exponent);


		do {	
		  //First, choose a cell	
		  #ifndef RANKED				
		  lin_ijk = select_cell(TotProb, CumulativeProb);
//		  if (ihalo<=-1)
//			fprintf(stderr,"\tlin_ijk=%ld  ",lin_ijk);
		 
		  k=lin_ijk%(NCells);
		  j=((lin_ijk-k)/NCells)%NCells;
	  	  i=(lin_ijk-k-j*NCells)/(NCells*NCells);
		  if (ihalo<=-1)
			fprintf(stderr," = [%ld,%ld,%ld]\n",i,j,k);
		  #else
		  lin_ijk=select_heaviest_cell(&i,&j,&k);		  
		  #endif

		  trials=0;


		  //Second, choose a particle in that cell
		  do {
			ipart = select_part(lin_ijk,ListOfPart, NPartPerCell);		
//			if (ihalo<=-1)
//				fprintf(stderr,"\tipart=%ld\n",ipart);
               		HaloX[ihalo] = PartX[ipart];
               		HaloY[ihalo] = PartY[ipart];
               		HaloZ[ihalo] = PartZ[ipart];
               		HaloVX[ihalo] = PartVX[ipart];
               		HaloVY[ihalo] = PartVY[ipart];
               		HaloVZ[ihalo] = PartVZ[ipart];
			R=R_from_mass(HaloMass[ihalo],rho_ref);
			HaloR[ihalo]= R;
//			if (ihalo<=-1)
//				fprintf(stderr,"\thalo: [[%f,%f,%f],[%f,%f,%f],%f]\n",HaloX[ihalo],HaloY[ihalo],HaloZ[ihalo],HaloVX[ihalo],HaloVY[ihalo],HaloVZ[ihalo],HaloR[ihalo]);
			#ifdef NO_EXCLUSION
			check = 0;
			#else
			//Third, check that is not overlapping a previous halo
			check = check_HaloR_in_mesh(ihalo,HaloX,HaloY,HaloZ,HaloR,i,j,k,ListOfHalos,NHalosPerCell);
			#endif
//			if (ihalo<=-1)
//				fprintf(stderr,"\tCHECK=%d\n",check);
			if (check==1){
				#ifdef DEBUG
				fprintf(stderr,"Refused part : %ld\n",ipart);
				#endif
				trials++;
			}
			if (trials == MAXTRIALS){
				//in order to avoid infinite loop, we will exit this loop, after MAXTRIALS trials
				#ifdef VERB
				fprintf(stderr,"MAXTRIALS=%d reached, removing cell [%ld,%ld,%ld]\n",MAXTRIALS,i,j,k);
				#endif
				MassLeft[lin_ijk]=0.;
				TotProb=ComputeCumulative(exponent, mpart, MassLeft, CumulativeProb);
				break;
			}
		  } while (check==1);//If the particle was excluded, try another one in the same cell

	        } while(check==1); //if reached MAXTRIALS, select another cell
		//Particle chosen!
		
		//mass in cell before assignment
                Mcell=MassLeft[lin_ijk];
//		if (ihalo<=-1)
//			fprintf(stderr,"\tMbefore=%e\n",Mcell);

		
		  #ifndef MASS_OF_PARTS 
                  if (Mcell>HaloMass[ihalo])
			MassLeft[lin_ijk] -= Mhalo; 
                  else
                        MassLeft[lin_ijk] = 0.;
		  #else
			exclude(ipart,R,PartX,PartY,PartZ,i,j,k);
		  #endif
////		if (ihalo<=-1)
//			fprintf(stderr,"\tMafter=%e\n",MassLeft[lin_ijk]);



	#ifndef NO_MASS_CONSERVATION
		if (ihalo<=-1)
			fprintf(stderr,"\tOld version!\n");
		double ProbDiff = pow(MassLeft[lin_ijk]/mpart,exponent)-pow(Mcell/mpart,exponent);

		#ifdef DEBUG
		fprintf(stderr,"\n \tassigned to cell %ld=[%ld,%ld,%ld]\n\t Before: Mcell=%e, CProbCell=%e,  TotProb=%e. ",lin_ijk,i,j,k,Mcell,CumulativeProb[lin_ijk],TotProb);
		#endif
		
		#ifndef MASS_OF_PARTS
		long icell;
		  //Substract the Probability difference from the array (only affected those cells after the selected one)
                  #pragma omp parallel for private(icell) shared(CumulativeProb,robDiff,NTotCells,lin_ijk) default(none)
                  for(icell=lin_ijk;icell<NTotCells;icell++){
                        CumulativeProb[icell]+=ProbDiff;
                  }
                  //TotProb+=ProbDiff;
                  TotProb=CumulativeProb[NCells*NCells*NCells-1];
		#endif
	#endif



		#ifdef DEBUG
		fprintf(stderr," After: Mcell=%e, CProbCell=%e, TotProb=%e.   , Mhalo=%e. CProb[last]=%e\n",MassLeft[lin_ijk],CumulativeProb[lin_ijk],TotProb,Mhalo,CumulativeProb[NTotCells-1]);
		#endif
	
		#ifdef DEBUG
		fprintf(stderr,"\thalo %ld assigned to particle %ld at [%f,%f,%f]. R= %f, M= %e\n",ihalo,ipart,HaloX[ihalo],HaloY[ihalo],HaloZ[ihalo],R,Mhalo);
		#endif

//		if (ihalo<=-1)
//			fprintf(stderr,"\tplace ihalo=%ld",ihalo);
		ListOfHalos[lin_ijk][NHalosPerCell[lin_ijk]]=ihalo;
//		if (ihalo<=-1)
//			fprintf(stderr,"\t check: %ld\n",ListOfHalos[lin_ijk][NHalosPerCell[lin_ijk]]);
		NHalosPerCell[lin_ijk]++;
//		if (ihalo<=-1)
//			fprintf(stderr,"\t Nhalospercell[%ld]= %ld\n",lin_ijk,NHalosPerCell[lin_ijk]);
	}//for(ihalo=Nstart:Nend)
//----------------------------------- Haloes Placed

#ifdef VERB
	t5=time(NULL);
 	diff = difftime(t5,t4_5);
	fprintf(stderr,"\ttime placing %f\n",diff);
 	diff = difftime(t5,t0);
	fprintf(stderr,"\ttotal time in place_halos.c %f\n",diff);
	fprintf(stderr,"\n\tPlacement done!!!\n");
#endif
	free(NHalosPerCell);
        free(count); 
	//free(NPartPerCell);
        free(CumulativeProb);
	free(MassLeft);
        for (i=0;i<NCells;i++){
                for (j=0;j<NCells;j++){
                        for (k=0;k<NCells;k++){
                                lin_ijk = k+j*NCells+i*NCells*NCells;
                                //free(ListOfPart[lin_ijk]);
                                //free(ListOfHalos[lin_ijk]);
                        }
                }
        }

        //free(ListOfPart);
        free(ListOfHalos);
#ifdef MASS_OF_PARTS
	free(excluded); free(Nexcluded);
#endif
		fprintf(stderr," e ");
	return 0;
}