bool cLevel::slideCol(BOB_Rect* pos, coord* centroid) { bool col = false; int dt, dr, db, dl; for (int i = 0; i < walls.size(); ++i) { if (BOBrectCol(*pos, walls[i])) { // Pushes players outside walls displace(pos, walls[i]); col = true; } } for (int i = 0; i < 4; ++i) { if (BOBrectCol(*pos, borders[i])) { // Keeps player within borders displace(pos, borders[i]); col = true; } } if (col) {// Recalculate centroid centroid->x = pos->x + pos->w / 2.0; centroid->y = pos->y + pos->h / 2.0; } return col; }
void Map::step() { for(int i(0); i < int(seeds_.size()); ++i) { if(seeds_[i].tileType_ == "water") { if(bernoulli(waterTpProb_)) { seeds_[i].pos_.y = uniform(0, int(height_-1)); seeds_[i].pos_.x = uniform(0, int(width_-1)); tiles_[seeds_[i].pos_.y*width_+seeds_[i].pos_.x] = getCurrentGame().tileAtlas_.at(seeds_[i].tileType_); for(int j(-humidityRange_); j<=humidityRange_; ++j) { for(int k(-humidityRange_); k<=humidityRange_; ++k) { int index(j*width_ + k + seeds_[i].pos_.y*width_+seeds_[i].pos_.x); if(!(index < 0 || index > humidity_.size()-1)) { humidity_[index] += eta_*exp(-sqrt(pow(j,2)+pow(k,2))/lambda_); } } } } else{ displace(seeds_[i].pos_, width_, height_); tiles_[seeds_[i].pos_.y*width_+seeds_[i].pos_.x] = getCurrentGame().tileAtlas_.at(seeds_[i].tileType_); for(int j(-humidityRange_); j<=humidityRange_; ++j) { for(int k(-humidityRange_); k<=humidityRange_; ++k) { int index(j*width_ + k + seeds_[i].pos_.y*width_+seeds_[i].pos_.x); if(!(index < 0 || index > humidity_.size()-1)) { humidity_[index] += eta_*exp(-sqrt(pow(j,2)+pow(k,2))/lambda_); } } } } } else if(seeds_[i].tileType_ == "grass") { displace(seeds_[i].pos_, width_, height_); if(tiles_[seeds_[i].pos_.y*width_+seeds_[i].pos_.x].tileType() != TileType::WATER) tiles_[seeds_[i].pos_.y*width_+seeds_[i].pos_.x] = getCurrentGame().tileAtlas_.at(seeds_[i].tileType_); } else if(seeds_[i].tileType_ == "forest") { displace(seeds_[i].pos_, width_, height_); if(tiles_[seeds_[i].pos_.y*width_+seeds_[i].pos_.x].tileType() != TileType::WATER) tiles_[seeds_[i].pos_.y*width_+seeds_[i].pos_.x] = getCurrentGame().tileAtlas_.at(seeds_[i].tileType_); } } }
/** * Walks the chain of objects accessible from the specified CallFrame. */ void GarbageCollector::verify_call_frame(CallFrame* top_call_frame, AddressDisplacement* offset) { CallFrame* call_frame = top_call_frame; while(call_frame) { call_frame = displace(call_frame, offset); if(call_frame->constant_scope_) { call_frame->constant_scope_->validate(); } if(call_frame->compiled_code) { call_frame->compiled_code->validate(); } if(call_frame->compiled_code) { native_int stack_size = call_frame->compiled_code->stack_size()->to_native(); for(native_int i = 0; i < stack_size; i++) { Object* obj = call_frame->stk[i]; obj->validate(); } } VariableScope* scope = call_frame->top_scope_; if(call_frame->multiple_scopes_p() && scope && !scope->nil_p()) { scope->validate(); } if(BlockEnvironment* env = call_frame->block_env()) { env->validate(); } Arguments* args = displace(call_frame->arguments, offset); if(!call_frame->inline_method_p() && args) { args->recv()->validate(); args->block()->validate(); Object** ary = displace(args->arguments(), offset); for(uint32_t i = 0; i < args->total(); i++) { ary[i]->validate(); } } if(call_frame->scope && call_frame->compiled_code) { verify_variable_scope(call_frame, displace(call_frame->scope, offset)); } call_frame = call_frame->previous; } }
void Robby::goKiwi(int i, int j, int k, double deltaT) { double x = (2*k-i-j)/3.0; double y = (j-i)/sqrt(3); double r = (i+j+k)/3.0; displace(x,y,r,deltaT); }
// get count for value v value_type get(key_type const v) const { uint64_t const p0 = hash(v); uint64_t p = p0; do { // position in use? // correct value stored if ( H[p].first == v ) { return H[p].second; } else if ( H[p].first == base_type::unused() ) { ::libmaus::exception::LibMausException se; se.getStream() << "SimpleHashMap::get() called for key " << v << " which is not contained." << std::endl; se.finish(); throw se; } else { p = displace(p,v); } } while ( p != p0 ); ::libmaus::exception::LibMausException se; se.getStream() << "SimpleHashMap::get() called for key " << v << " which is not contained." << std::endl; se.finish(); throw se; }
bool HeartOfFire::loadFromFile(FILE* f, Room* r){ if (f == NULL) return false; Point2d position; //have a temporary buffer used to read the file line by line... char buffer[1000]; //this is where it happens. while (!feof(f)){ //get a line from the file... Game::readValidLine(buffer, f, sizeof(buffer)); char *line = Game::lTrim(buffer); int lineType = Game::getTypeID(line); switch (lineType) { case POSITION: if (sscanf(line, "%lf %lf", &position.x, &position.y) != 2) return false; break; case FACING_RIGHT: if (sscanf(line, "%d", &facingRight) != 1) return false; break; case END: room=r; displace(position); return true; default: return false; } } return false; }
int minimax(t_env *e, int depth) { int i; int v; int bestvalue; int move; i = -1; bestvalue = -MAX_VALUE; while (++i < e->w) { if (e->board[0][i] == '.') { board_insert(e, i, 2); v = min(e, 1, depth); if (v > bestvalue) { bestvalue = v; move = i; } board_delete(e, i); } } move = displace(e, bestvalue, move); return (move); }
void drive_away( t_block *block, t_block *block_nearest, int dir) { float box_block[8]; float box_nearest[8]; float margin = 5; get_bounding_box( block, margin ,box_block); get_bounding_box( block_nearest, margin, box_nearest); float *big; float *small; if( block->width >= block_nearest->width && block->height >= block_nearest->height) { big = box_block; small = box_nearest; } else { big = box_nearest; small = box_block; } int test = test_bounding_box( big, small); if( test) { displace( block, block_nearest, dir); drive_away( block, block_nearest, dir); } }
void SecondaryStructureRMSD::setSecondaryStructure( std::vector<Vector>& structure, double bondlength, double units ){ // If we are in natural units get conversion factor from nm into natural length units if( plumed.getAtoms().usingNaturalUnits() ){ error("cannot use this collective variable when using natural units"); } plumed_massert( !(align_strands && align_atom_1==0 && align_atom_2==0), "you must use setAtomsFromStrands with strands cutoff"); // Convert into correct units for(unsigned i=0;i<structure.size();++i){ structure[i][0]*=units; structure[i][1]*=units; structure[i][2]*=units; } if( references.size()==0 ){ finishTaskListUpdate(); readVesselKeywords(); if( getNumberOfVessels()==0 ){ double r0; parse("R_0",r0); double d0; parse("D_0",d0); int nn; parse("NN",nn); int mm; parse("MM",mm); std::ostringstream ostr; ostr<<"RATIONAL R_0="<<r0<<" D_0="<<d0<<" NN="<<nn<<" MM="<<mm; std::string input=ostr.str(); addVessel( "LESS_THAN", input, -1 ); // -1 here means that this value will be named getLabel() readVesselKeywords(); // This makes sure resizing is done } } // Set the reference structure references.push_back( metricRegister().create<SingleDomainRMSD>( alignType ) ); unsigned nn=references.size()-1; std::vector<double> align( structure.size(), 1.0 ), displace( structure.size(), 1.0 ); references[nn]->setBoundsOnDistances( true , bondlength ); // We always use pbc references[nn]->setReferenceAtoms( structure, align, displace ); // references[nn]->setNumberOfAtoms( structure.size() ); }
// returns true if value v is contained bool contains(key_type const v) const { uint64_t const p0 = hash(v); uint64_t p = p0; do { // position in use? if ( H[p].first == base_type::unused() ) { return false; } // correct value stored else if ( H[p].first == v ) { return true; } else { p = displace(p,v); } } while ( p != p0 ); return false; }
const short* select_bundle(ODFModel* odf_model,short* position, float angle,float fa_threshold,unsigned int& count) { float cos_angle = std::cos(angle); image::basic_image<char,3> level_map(odf_model->fib_data.dim); std::deque<image::vector<3,float> > seed_dir; std::deque<image::pixel_index<3> > seed_pos; seed_pos.push_back(image::pixel_index<3>(position[0],position[1],position[2],odf_model->fib_data.dim)); seed_pos.push_back(image::pixel_index<3>(position[0],position[1],position[2],odf_model->fib_data.dim)); seed_dir.push_back(odf_model->fib_data.fib.getDir(seed_pos.back().index(),0)); seed_dir.push_back(-odf_model->fib_data.fib.getDir(seed_pos.back().index(),0)); level_map[seed_pos.back().index()] = 1; while (!seed_pos.empty()) { std::vector<image::pixel_index<3> > neighbors; image::get_neighbors(seed_pos.front(),odf_model->fib_data.dim,neighbors); image::vector<3,float> center(seed_pos.front()); for (unsigned int index = 0;index < neighbors.size();++index) { // select front if (level_map[neighbors[index].index()]) continue; image::vector<3,float> displace(neighbors[index]); displace -= center; if (displace*seed_dir.front() < 0.2) continue; image::vector<3,float> new_dir; if (!odf_model->fib_data.get_nearest_dir(neighbors[index].index(),seed_dir.front(),new_dir,fa_threshold,cos_angle)) continue; if (std::abs(new_dir*seed_dir.front()) < cos_angle) continue; if (new_dir*seed_dir.front() < 0) new_dir = -new_dir; seed_pos.push_back(neighbors[index]); seed_dir.push_back(new_dir); level_map[neighbors[index].index()] = 1; } seed_pos.pop_front(); seed_dir.pop_front(); } //image::morphology_smoothing(level_map); static std::vector<short> sel_regions; sel_regions.clear(); for (image::pixel_index<3> index;index.valid(odf_model->fib_data.dim);index.next(odf_model->fib_data.dim)) if (level_map[index.index()]) { sel_regions.push_back(index.x()); sel_regions.push_back(index.y()); sel_regions.push_back(index.z()); } count = sel_regions.size(); return &*sel_regions.begin(); }
static inline void displace(Ta n, Ta e, Tb* lat, Tb* lon) { // Dummy variable double hae = 0.00; // Call the general method displace(n, e, 0.00, lat, lon, &hae); }
void GarbageCollector::scan(VariableRootBuffers& buffers, bool young_only, AddressDisplacement* offset) { for(VariableRootBuffers::Iterator vi(buffers); vi.more(); vi.advance()) { Object*** buffer = displace(vi->buffer(), offset); for(int idx = 0; idx < vi->size(); idx++) { Object** var = displace(buffer[idx], offset); Object* tmp = *var; if(tmp->reference_p() && (!young_only || tmp->young_object_p())) { *var = saw_object(tmp); } } } }
// // send_block_content // // Send the content of a block to monitor. // void Monitor::send_block_content() { // get zone malloc_zone_t *zone = (malloc_zone_t *)strtoul(_args[2], NULL, 0); // get block void *block = (void *)strtoul(_args[3], NULL, 0); print("content %s\n", _args[1]); if (zone == (malloc_zone_t *)Zone::zone()) { Zone *azone = (Zone *)zone; if (azone->is_block(block)) { usword_t size = azone->block_size(block); for (usword_t offset = 0; offset < size; offset += sizeof(void *)) { intptr_t *slot = (intptr_t *)displace(block, offset); intptr_t content = *slot; print("slot %p %lu %p", slot, offset, content); if (azone->is_block((void *)content)) { send_block_info(azone, (void *)content); } else { // room for comment } print("\n"); } } } else { // it's a malloc_zone_t block of some kind. size_t size = malloc_size(block); if (size != 0) { for (usword_t offset = 0; offset < size; offset += sizeof(void *)) { intptr_t *slot = (intptr_t *)displace(block, offset); intptr_t content = *slot; print("slot %p %lu %p", slot, offset, content); size_t content_size = malloc_size((void *)content); if (content_size) { send_malloc_block_info((void *)content, content_size); } else { // room for comment } print("\n"); } } } print("\\content\n"); }
// extendBy methods void plane:: extendBy ( const vec3& pt ) { if ( contains ( pt ) == containsResult::NoneIn ) { ValueType d = distToPtSigned ( pt ); displace ( d ); } }
void GarbageCollector::scan(VariableRootBuffers& buffers, bool young_only, AddressDisplacement* offset) { VariableRootBuffer* vrb = displace(buffers.front(), offset); while(vrb) { Object*** buffer = displace(vrb->buffer(), offset); for(int idx = 0; idx < vrb->size(); idx++) { Object** var = displace(buffer[idx], offset); Object* tmp = *var; if(tmp && tmp->reference_p() && (!young_only || tmp->young_object_p())) { *var = saw_object(tmp); } } vrb = displace((VariableRootBuffer*)vrb->next(), offset); } }
// get count for value v without checks value_type getUnchecked(key_type const v) const { uint64_t p = hash(v); while ( true ) // correct value stored if ( H[p].first == v ) return H[p].second; else p = displace(p,v); }
void main() { int a[100], i, j, k,n; printf("enter the range of array \n"); scanf("%d", &n); printf("enter the array \n"); for (i = 0;i < n;i++) { scanf("%d", &a[i]); } displace(a, n); getch(); }
void MidpointDisplacement::generate( std::vector<Point> &points, int roughness, int npoints ) { if ( npoints < 0 ) return; for ( unsigned int i = 1; i < points.size(); i += 2 ) { Point pMid = middle( points.at( i ), points.at( i - 1 ) ); Point pDis = displace( pMid, roughness ); points.insert( points.begin() + i, pDis ); npoints--; } generate( points, roughness / 2, npoints ); }
void justify( t_block *block, t_block *block_nearest, int dir) { float x = block_nearest->pos[0]; float y = block_nearest->pos[1]; float m = 60; switch( dir) { case WEST: if( x + block_nearest->width + m >= block->pos[0]) { displace( block, block_nearest, dir); justify( block, block_nearest, dir); } break; case EAST: if( x <= block->pos[0] +block->width + m) { displace( block, block_nearest, dir); justify( block, block_nearest, dir); } break; case NORTH: if( y <= block->pos[1] + block->height + m) { displace( block, block_nearest, dir); justify( block, block_nearest, dir); } break; case SOUTH: if( y <= block->pos[1] + block->height + m) { displace( block, block_nearest, dir); justify( block, block_nearest, dir); } break; } }
void main() { /* Layout: BASE_X, BASE_Y, BASE_Z, WIDTH, CONCAVITY,SEED, TIP_X, TIP_Y, TIP_Z, NUM_LEAFS,ROUNDESS, RESERVED, UP_X, UP_Y, UP_Z, RESERVED, RESERVED, RESERVED */ float width = gs_in[0].param.x; float concavity = gs_in[0].param.y; float seed = gs_in[0].param.z; vec3 base = displace( gl_in[0].gl_Position.xyz, seed ); vec3 tip = displace( gl_in[1].gl_Position.xyz, seed ); vec3 up = normalize( displace( gl_in[2].gl_Position.xyz, seed ) ); float num_leafs = gs_in[1].param.x; float roundness = gs_in[1].param.y; for( float s =-1.0; s <= 1.0; s += 2.0 ) { vec3 curve = (base + (tip-base) / 2.0 * roundness ) + s * normalize( cross( up-tip, up-base ) ) * width + up * (concavity+0.01); vec2 t1 = vec2(0); for( float t =0; t < 1.0; t += 0.2 ) { vec3 v1 = bezier2( t, base, base, tip ); vec3 v2 = bezier2( t, base, curve, tip ); emitAndMult( v1, s * cross( v1, v2), t1 ); emitAndMult( v2, s * cross( v1, v2 ), t1 ); } emitAndMult( tip, up, t1 ); } }
void moveTo(float target[]){ int d = distance(me,target); int speed = 1; if (d > 0.5){ displace(target,me); speed = 15; tarVec[0] = tarVec[0] * speed; tarVec[1] = tarVec[1] * speed; tarVec[2] = tarVec[2] * speed; api.setVelocityTarget(tarVec); } else if (d > 0.3){ displace(target,me); speed = 9; tarVec[0] = tarVec[0] * speed; tarVec[1] = tarVec[1] * speed; tarVec[2] = tarVec[2] * speed; api.setVelocityTarget(tarVec); } else { api.setPositionTarget(target); } }
void HeartOfFire::resolveCollision(Still* other){ for(unsigned int i=0;i<other->getHitboxCount();i++){ for(unsigned int j=0;j<hitboxes.size();j++){ Point2d d; if(other->getHitbox(i)->intersect(hitboxes[j],d)){ double d2 = d.length2(); if(d2!=0.0){ displace(d); if(d.dot(speed)<0) speed = speed-d*d.dot(speed)/d2; if(d.y<0.0) onGround=other;//if the still is pushing the player upwards, we are standing on something } } } } }
/** * Walks the chain of objects accessible from the specified CallFrame. */ void GarbageCollector::walk_call_frame(CallFrame* top_call_frame, AddressDisplacement* offset) { CallFrame* call_frame = top_call_frame; while(call_frame) { call_frame = displace(call_frame, offset); if(call_frame->constant_scope_ && call_frame->constant_scope_->reference_p()) { call_frame->constant_scope_ = (ConstantScope*)mark_object(call_frame->constant_scope_); } if(call_frame->compiled_code && call_frame->compiled_code->reference_p()) { call_frame->compiled_code = (CompiledCode*)mark_object(call_frame->compiled_code); } if(call_frame->compiled_code) { native_int stack_size = call_frame->compiled_code->stack_size()->to_native(); for(native_int i = 0; i < stack_size; i++) { Object* obj = call_frame->stk[i]; if(obj && obj->reference_p()) { call_frame->stk[i] = mark_object(obj); } } } if(call_frame->multiple_scopes_p() && call_frame->top_scope_) { call_frame->top_scope_ = (VariableScope*)mark_object(call_frame->top_scope_); } if(BlockEnvironment* env = call_frame->block_env()) { call_frame->set_block_env((BlockEnvironment*)mark_object(env)); } Arguments* args = displace(call_frame->arguments, offset); if(!call_frame->inline_method_p() && args) { args->set_recv(mark_object(args->recv())); args->set_block(mark_object(args->block())); if(Tuple* tup = args->argument_container()) { args->update_argument_container((Tuple*)mark_object(tup)); } else { Object** ary = displace(args->arguments(), offset); for(uint32_t i = 0; i < args->total(); i++) { ary[i] = mark_object(ary[i]); } } } if(NativeMethodFrame* nmf = call_frame->native_method_frame()) { nmf->handles().gc_scan(this); } #ifdef ENABLE_LLVM if(jit::RuntimeDataHolder* jd = call_frame->jit_data()) { jd->set_mark(); ObjectMark mark(this); jd->mark_all(0, mark); } if(jit::RuntimeData* rd = call_frame->runtime_data()) { rd->method_ = (CompiledCode*)mark_object(rd->method()); rd->name_ = (Symbol*)mark_object(rd->name()); rd->module_ = (Module*)mark_object(rd->module()); } #endif if(call_frame->scope && call_frame->compiled_code) { saw_variable_scope(call_frame, displace(call_frame->scope, offset)); } call_frame = call_frame->previous; } }
int main(int argc, char **argv) { if(argc < 2) { fprintf(stdout, "\nParameters are missing.\n"); fprintf(stdout, "Call with <ParameterFile>\n\n"); exit(0); } /*Make sure stdout is line buffered even when not * printing to a terminal but, eg, perl*/ setlinebuf(stdout); //May throw std::runtime_error try { //Read the config file SpbConfigParser config(argv[1]); //Cosmological parameters const auto Omega = config.PopValue<double>("Omega"); const auto OmegaLambda = config.PopValue<double>("OmegaLambda"); const auto OmegaBaryon = config.PopValue<double>("OmegaBaryon"); const auto HubbleParam = config.PopValue<double>("HubbleParam"); //Which output format should we use. 4 is bigfile, 3 is HDF5, 2 is Gadget 2. Default to 3. const auto ICFormat = config.PopValue<int>("ICFormat", 3); //How many output files to use in the set const auto NumFiles = config.PopValue<int>("NumFiles"); //Parameters of the simulation box const auto Box = config.PopValue<double>("Box"); const auto Redshift = config.PopValue<double>("Redshift"); const double InitTime = 1 / (1 + Redshift); //Size of FFT const size_t Nmesh = config.PopValue<int>("Nmesh"); //Unused unless CAMB spectrum const auto FileWithInputSpectrum = config.PopValue<std::string>("FileWithInputSpectrum"); const auto FileWithTransfer = config.PopValue<std::string>("FileWithTransfer"); const auto InputSpectrum_UnitLength_in_cm = config.PopValue<double>("InputSpectrum_UnitLength_in_cm", 3.085678e24); //Output filenames const auto OutputDir = config.PopValue<std::string>("OutputDir"); const auto FileBase = config.PopValue<std::string>("FileBase"); //Random number seed const auto Seed = config.PopValue<int>("Seed"); //Various boolean flags const auto ReNormalizeInputSpectrum = config.PopValue<bool>("ReNormalizeInputSpectrum", false); const auto RayleighScatter = config.PopValue<bool>("RayleighScatter", true); //Power spectrum to use. Default to CAMB const auto WhichSpectrum = config.PopValue<int>("WhichSpectrum", 2); //Is twolpt on? const auto twolpt = config.PopValue<bool>("TWOLPT",true); //Unit system const auto UnitLength_in_cm = config.PopValue<double>("UnitLength_in_cm", 3.085678e21); const auto UnitVelocity_in_cm_per_s = config.PopValue<double>("UnitVelocity_in_cm_per_s", 1e5); const auto UnitMass_in_g = config.PopValue<double>("UnitMass_in_g", 1.989e43); const double UnitTime_in_s = UnitLength_in_cm / UnitVelocity_in_cm_per_s; //WDM options bool WDM_Vtherm_On = config.PopValue<bool>("WDM_Vtherm_On",false); const auto WDM_PartMass_in_kev = config.PopValue<double>("WDM_PartMass_in_kev", 0); //Neutrino options //Add thermal velocities to type 2 particles bool NU_Vtherm_On = config.PopValue<bool>("NU_Vtherm_On",true); //This triggers the use of neutrinos via an altered transfer function //Should be on only if you are faking neutrinos by combining them with the dark matter, //and changing the transfer function, which is a terrible way of simulating neutrinos. So leave it off. const auto combined_neutrinos = config.PopValue<bool>("NU_in_DM",false); //Changes whether we have two heavy and one light neutrino or one heavy two light. //0 is 3 degenerate species, 1 is normal (two light species) and -1 is inverted (two heavy) const auto Hierarchy = config.PopValue<int>("Hierarchy",0); //If enabled, turn off radiation in the initial velocities const auto NoRadiation = config.PopValue<bool>("NoRadiation",false); //Total neutrino mass const auto NU_PartMass_in_ev = config.PopValue<double>("NU_PartMass_in_ev",0); //Parameter for the Efstathiou power spectrum. Generally does nothing. const auto ShapeGamma = config.PopValue<double>("ShapeGamma",0.201); //Needed if ReNormaliseInputSpectrum is on. Otherwise unused const auto PrimordialIndex = config.PopValue<double>("PrimordialIndex",1.); const auto Sigma8 = config.PopValue<double>("Sigma8",0.8); //Number of particles desired std::valarray<int64_t> npart((int64_t)0,(size_t)N_TYPE); int64_t CbRtNpart[6] = {0}; CbRtNpart[BARYON_TYPE] = config.PopValue<int>("NBaryon", 0); CbRtNpart[DM_TYPE] = config.PopValue<int>("NCDM", 0); CbRtNpart[NEUTRINO_TYPE] = config.PopValue<int>("NNeutrino", 0); for(int type=0; type<N_TYPES; ++type) npart[type] = static_cast<int64_t>(CbRtNpart[type])*CbRtNpart[type]*CbRtNpart[type]; //Make a cosmology Cosmology cosmo(HubbleParam, Omega, OmegaLambda, NU_PartMass_in_ev, Hierarchy, NoRadiation); //Init structure for neutrino velocities //Maximum velocity to sample Fermi-Dirac from, in km/s at z=0 const double v_th = cosmo.NU_V0(Redshift, UnitVelocity_in_cm_per_s); //Convert physical km/s at z=0 in an unperturbed universe to internal gadget (comoving) velocity units at starting redshift. double vnumax = config.PopValue<double>("Max_nuvel", -1)*pow((1+Redshift),1.5)*(UnitVelocity_in_cm_per_s/1e5); if (vnumax < 0 || vnumax > v_th*MAX_FERMI_DIRAC) vnumax = v_th*MAX_FERMI_DIRAC; printf("Particle numbers: %ld %ld %ld\n",npart[BARYON_TYPE], npart[DM_TYPE], npart[NEUTRINO_TYPE]); assert(npart[BARYON_TYPE] > 0 || npart[DM_TYPE] > 0 || npart[NEUTRINO_TYPE] > 0); if (Nmesh % 2 != 0){ printf("Nmesh must be even or correct output is not guaranteed.\n"); exit(1); } std::vector<std::string> unexpected = config.GetRemainingKeys(); if(unexpected.size() > 0){ std::cerr<<"Config file contained the following unexpected keys:"<<std::endl; for(auto unex: unexpected) std::cerr<<unex<<std::endl; exit(1); } DisplacementFields displace(Nmesh, Seed, Box, twolpt); /*Set particle numbers*/ if(npart.sum() == 0) exit(1); //Set the flag that checks whether neutrinos are free-streaming cosmo.SetNeutrinoFreeStream(Box*UnitLength_in_cm, v_th * UnitVelocity_in_cm_per_s*sqrt(InitTime), InitTime); //Initialise a power spectrum PowerSpec * PSpec; switch(WhichSpectrum) { case 1: PSpec = new PowerSpec_EH(HubbleParam, Omega, OmegaBaryon, UnitLength_in_cm); break; case 2: PSpec = new PowerSpec_Tabulated(FileWithTransfer, FileWithInputSpectrum, Omega, OmegaLambda, OmegaBaryon, cosmo.OmegaNu(1),InputSpectrum_UnitLength_in_cm, UnitLength_in_cm, !npart[BARYON_TYPE], combined_neutrinos); break; default: PSpec = new PowerSpec_Efstathiou(ShapeGamma, UnitLength_in_cm); } //If normalisation or WDM are on, decorate the base power spectrum //to do that if (ReNormalizeInputSpectrum) { double Dplus = cosmo.GrowthFactor(InitTime, 1.0); printf("Growth factor to z=0: %g \n", Dplus); PSpec = new NormalizedPowerSpec(PSpec, Sigma8, PrimordialIndex, Dplus, UnitLength_in_cm); } if(WDM_Vtherm_On) PSpec = new WDMPowerSpec(PSpec, WDM_PartMass_in_kev, Omega, OmegaBaryon, HubbleParam, UnitLength_in_cm); std::string extension(""); if (ICFormat > 4 || ICFormat < 2) { fprintf(stderr, "Supported ICFormats:\n 2: Gadget 2 format files\n 3: HDF5\n 4: BigFile\n"); exit(1); } if (ICFormat == 3){ printf("Outputting HDF5 ICs\n"); extension=".hdf5"; } GadgetWriter::GWriteBaseSnap *osnap; #ifdef HAVE_BGFL if(ICFormat == 4) { osnap = new GadgetWriter::GWriteBigSnap(OutputDir+std::string("/")+FileBase+extension, npart, NumFiles); } else #endif osnap = new GadgetWriter::GWriteSnap(OutputDir+std::string("/")+FileBase+extension, npart,NumFiles, sizeof(id_type)); assert(osnap); /*Write headers*/ gadget_header header = generate_header(npart, Omega, OmegaBaryon, cosmo.OmegaNu(1), OmegaLambda, HubbleParam, Box, InitTime, UnitMass_in_g, UnitLength_in_cm, UnitVelocity_in_cm_per_s, combined_neutrinos); if ( vnumax/v_th < MAX_FERMI_DIRAC ) { FermiDiracVel therm_vels (v_th, vnumax/v_th); header.mass[NEUTRINO_TYPE]*=therm_vels.total_frac; printf("F-D velocity scale: %g (km/s). Max particle vel: %g (km/s). Fraction of mass in particles: %g\n",v_th/sqrt(1+Redshift), vnumax/sqrt(1+Redshift), therm_vels.total_frac); } //Generate regular particle grid part_grid Pgrid(CbRtNpart, header.mass, Box); if(osnap->WriteHeaders(header)) { fprintf(stderr, "Could not write headers to snapshot\n"); exit(1); } int64_t FirstId=1; //Compute the factors to go from velocity to displacement const double hubble_a = cosmo.Hubble(InitTime)*UnitTime_in_s; const double vel_prefac = InitTime * hubble_a * cosmo.F_Omega(InitTime) /sqrt(InitTime); //Only used if twolpt is on //This is slightly approximate: we are assuming that D2 ~ -3/7 Da^2 Omega_m^{-1/143} (Bouchet, F 1995, A&A 296) const double vel_prefac2 = -3./7.*pow(Omega, -1./143)*InitTime * hubble_a * cosmo.F2_Omega(InitTime) /sqrt(InitTime); printf("vel_prefac= %g hubble_a=%g fom=%g Omega=%g \n", vel_prefac, hubble_a, cosmo.F_Omega(InitTime), Omega); for(int type=0; type<N_TYPE;type++){ if(npart[type] == 0) continue; FermiDiracVel * therm_vels = NULL; //For WDM thermal velocities if(WDM_Vtherm_On && type == DM_TYPE){ const double wdm_vth = WDM_V0(Redshift, WDM_PartMass_in_kev, Omega-OmegaBaryon, HubbleParam, UnitVelocity_in_cm_per_s); therm_vels = new FermiDiracVel (wdm_vth); printf("\nWarm dark matter rms velocity dispersion at starting redshift = %g km/sec\n\n",3.59714 * wdm_vth); } //Neutrino thermal velocities if(NU_Vtherm_On && type == NEUTRINO_TYPE) { therm_vels = new FermiDiracVel (v_th, vnumax/v_th); printf("\nNeutrino rms vel. dispersion %g (km/s)\n\n",v_th/sqrt(1+Redshift)); } //Only compute zeldovich displacements if we have all the neutrinos in particles. if(type != 2 || !therm_vels || therm_vels->total_frac > 0.95) { lpt_data outdata = displace.displacement_fields(type, Pgrid, PSpec, RayleighScatter); outdata.SetVelPrefac(vel_prefac, vel_prefac2); FirstId = write_particle_data(*osnap, type,&outdata, Pgrid, therm_vels, FirstId); } //Otherwise pass empty values for the velocity fields. else FirstId = write_particle_data(*osnap, type,NULL, Pgrid, therm_vels, FirstId); delete therm_vels; } delete osnap; delete PSpec; printf("Initial scale factor = %g\n", InitTime); } catch(std::ios_base::failure& e) { std::cerr<<e.what(); return 4; } catch(std::runtime_error& e) { std::cerr<<e.what(); return 1; } catch(std::invalid_argument& e) { std::cerr<<e.what(); return 2; } catch(std::domain_error& e) { std::cerr<<e.what(); return 3; } return 0; }
/* scroll of displacement */ void i_displace(pob o) { if (o->blessing > -1) Objects[o->id].known = 1; displace(o->blessing); }
static void run (const gchar *name, gint nparams, const GimpParam *param, gint *nreturn_vals, GimpParam **return_vals) { static GimpParam values[1]; GimpDrawable *drawable; GimpRunMode run_mode; GimpPDBStatusType status = GIMP_PDB_SUCCESS; run_mode = param[0].data.d_int32; INIT_I18N (); /* Get the specified drawable */ drawable = gimp_drawable_get (param[2].data.d_drawable); /* set the tile cache size */ gimp_tile_cache_ntiles (TILE_CACHE_SIZE); *nreturn_vals = 1; *return_vals = values; values[0].type = GIMP_PDB_STATUS; values[0].data.d_status = status; switch (run_mode) { case GIMP_RUN_INTERACTIVE: /* Possibly retrieve data */ gimp_get_data (PLUG_IN_PROC, &dvals); /* First acquire information with a dialog */ if (! displace_dialog (drawable)) return; break; case GIMP_RUN_NONINTERACTIVE: /* Make sure all the arguments are there! */ if (nparams != 10) { status = GIMP_PDB_CALLING_ERROR; } else { dvals.amount_x = param[3].data.d_float; dvals.amount_y = param[4].data.d_float; dvals.do_x = param[5].data.d_int32; dvals.do_y = param[6].data.d_int32; dvals.displace_map_x = param[7].data.d_int32; dvals.displace_map_y = param[8].data.d_int32; dvals.displace_type = param[9].data.d_int32; dvals.mode = (strcmp (name, "plug-in-displace-polar") == 0 ? POLAR_MODE : CARTESIAN_MODE); } break; case GIMP_RUN_WITH_LAST_VALS: /* Possibly retrieve data */ gimp_get_data (PLUG_IN_PROC, &dvals); break; default: break; } if (status == GIMP_PDB_SUCCESS) { if (dvals.displace_map_x != -1 && (gimp_drawable_width (dvals.displace_map_x) != drawable->width || gimp_drawable_height (dvals.displace_map_x) != drawable->height)) status = GIMP_PDB_CALLING_ERROR; } if (status == GIMP_PDB_SUCCESS) { if (dvals.displace_map_y != -1 && (gimp_drawable_width (dvals.displace_map_y) != drawable->width || gimp_drawable_height (dvals.displace_map_y) != drawable->height)) status = GIMP_PDB_CALLING_ERROR; } if (status == GIMP_PDB_SUCCESS && (dvals.do_x || dvals.do_y)) { gimp_progress_init (_("Displacing")); /* run the displace effect */ displace (drawable, NULL); if (run_mode != GIMP_RUN_NONINTERACTIVE) gimp_displays_flush (); /* Store data */ if (run_mode == GIMP_RUN_INTERACTIVE) gimp_set_data (PLUG_IN_PROC, &dvals, sizeof (DisplaceVals)); } values[0].data.d_status = status; gimp_drawable_detach (drawable); }
//-------------------------------------------------------------- void testApp::setup(){ //ofSetCircleResolution(30); ofDisableArbTex(); receiver.setup( PORT ); sender.setup(HOST, SCPORT); ofxOscMessage m; m.setAddress("/init"); sender.sendMessage(m); //ofSetVerticalSync(true); ofSetFrameRate(60); outputMode = 1; int rows, cols; showPoints = false; screenHeight = ofGetScreenHeight(); screenWidth = ofGetScreenHeight(); radius = screenHeight; circum = screenWidth * 1.25; blurBG.setup(screenWidth, screenHeight); blurFG.setup(screenWidth, screenHeight); float h, s, offset; rows = 18; s = screenHeight/(rows * 2.8); h = s * sqrt(3.0f); cols = circum/h; offset = h/4.0f; bg_alpha = 45; selPoint = 0; int noise = 2; int count = 0; rotSpeed = -screenWidth/3600; for(int i = 0; i < cols; i ++){ vector<star *> s1; vector<star *> s0; for(int j = 0; j < rows; j ++){ ofVec2f positions[4] = { ofVec2f(i * h, j * s * 3), ofVec2f(i * h, j * s * 3 + s), ofVec2f(h/2 + h * i, -offset + j * s * 3), ofVec2f(h/2 + h * i, -offset + j * s * 3 + s * 2) }; for(int k =0; k < 4; k ++){ star * newStar = new star(); newStar->worldCircum = circum; newStar->worldHeight = screenHeight; newStar->rotSpeed = rotSpeed; //rotation once every 15 secs newStar->pos = ofVec2f(positions[k].x - circum/2, positions[k].y - screenHeight/2); ofVec2f displace(ofRandom(-noise,noise), ofRandom(-noise,noise)); newStar->pos += displace; newStar->id = count; newStar->assignAlgorithm(i%5); ///(i%5); newStar->setupAttributes(); newStar->activeStarList = &activeStarList; if(k < 2){ newStar->col = i * 2; s0.push_back(newStar); }else{ newStar->col = i * 2 + 1; s1.push_back(newStar); } count ++; } } stars2d.push_back(s0); stars2d.push_back(s1); } numStars = count; columnWidth = circum/stars2d.size(); for(int i =0; i < 20; i++){ dsUsers[i].id = i; dsUsers[i].isActive = false; } testIndex = 0; distThresh = 200; testPoint = false; bg.loadImage("moonTest.jpg"); sp.loadImage("sphere.jpg"); fbo_tex.allocate(screenWidth, screenHeight, GL_RGBA); map_tex.allocate(screenWidth, screenHeight, GL_RGBA); w_prop = (float)screenWidth/ofNextPow2(screenWidth); h_prop = (float)screenHeight/ofNextPow2(screenHeight); gridSize = 11; for(int y= 0; y < gridSize; y++){ for(int x= 0; x < gridSize; x++){ ofPoint p((float)x/(gridSize-1),(float)y/(gridSize-1)); ofPoint np = p * ofPoint(screenWidth,screenHeight); v_points.push_back(np); o_points.push_back(p); p *= ofPoint(w_prop,h_prop); t_points.push_back(p); } } sphereRot = 0; loadMappingPoints(); }
/* apply what was already determined in checkpointing */ void make_move(system_t *system) { int i, j, k, p, q; cavity_t *cavities_array; int cavities_array_counter, random_index; double com[3], rand[3]; molecule_t *molecule_ptr; atom_t *atom_ptr; pair_t *pair_ptr; /* update the cavity grid prior to making a move */ if (system->cavity_bias) { cavity_update_grid(system); system->checkpoint->biased_move = 0; } switch (system->checkpoint->movetype) { case MOVETYPE_INSERT: /* insert a molecule at a random pos and orientation */ /* umbrella sampling */ if (system->cavity_bias && system->cavities_open) { /* doing a biased move - this flag lets mc.c know about it */ system->checkpoint->biased_move = 1; /* make an array of possible insertion points */ cavities_array = calloc(system->cavities_open, sizeof(cavity_t)); memnullcheck(cavities_array, system->cavities_open * sizeof(cavity_t), __LINE__ - 1, __FILE__); for (i = 0, cavities_array_counter = 0; i < system->cavity_grid_size; i++) { for (j = 0; j < system->cavity_grid_size; j++) { for (k = 0; k < system->cavity_grid_size; k++) { if (!system->cavity_grid[i][j][k].occupancy) { for (p = 0; p < 3; p++) cavities_array[cavities_array_counter].pos[p] = system->cavity_grid[i][j][k].pos[p]; ++cavities_array_counter; } } /* end k */ } /* end j */ } /* end i */ /* insert randomly at one of the free cavity points */ random_index = (system->cavities_open - 1) - (int)rint(((double)(system->cavities_open - 1)) * get_rand(system)); for (p = 0; p < 3; p++) com[p] = cavities_array[random_index].pos[p]; /* free the insertion array */ free(cavities_array); } // end umbrella else { /* insert the molecule to a random location within the unit cell */ for (p = 0; p < 3; p++) rand[p] = 0.5 - get_rand(system); for (p = 0; p < 3; p++) for (q = 0, com[p] = 0; q < 3; q++) com[p] += system->pbc->basis[q][p] * rand[q]; } /* process the inserted molecule */ for (atom_ptr = system->checkpoint->molecule_backup->atoms; atom_ptr; atom_ptr = atom_ptr->next) { /* move the molecule back to the origin and then assign it to com */ for (p = 0; p < 3; p++) atom_ptr->pos[p] += com[p] - system->checkpoint->molecule_backup->com[p]; } /* update the molecular com */ for (p = 0; p < 3; p++) system->checkpoint->molecule_backup->com[p] = com[p]; /* give it a random orientation */ rotate(system, system->checkpoint->molecule_backup, system->pbc, 1.0); // insert into the list if (system->num_insertion_molecules) { // If inserting a molecule from an insertion list, we will always insert at the end system->checkpoint->head->next = system->checkpoint->molecule_backup; system->checkpoint->molecule_backup->next = NULL; } else { if (!system->checkpoint->head) { // if we're at the start of the list: system->molecules = system->checkpoint->molecule_backup; } else { system->checkpoint->head->next = system->checkpoint->molecule_backup; } system->checkpoint->molecule_backup->next = system->checkpoint->molecule_altered; } /* set new altered and tail to reflect the insertion */ system->checkpoint->molecule_altered = system->checkpoint->molecule_backup; system->checkpoint->tail = system->checkpoint->molecule_altered->next; system->checkpoint->molecule_backup = NULL; if (system->num_insertion_molecules) { //multi sorbate // Free all pair memory in the list for (molecule_ptr = system->molecules; molecule_ptr; molecule_ptr = molecule_ptr->next) { for (atom_ptr = molecule_ptr->atoms; atom_ptr; atom_ptr = atom_ptr->next) { pair_ptr = atom_ptr->pairs; while (pair_ptr) { pair_t *temp = pair_ptr; pair_ptr = pair_ptr->next; free(temp); } } } // Generate new pairs lists for all atoms in system setup_pairs(system); } // only one sorbate else update_pairs_insert(system); //reset atom and molecule id's enumerate_particles(system); break; case MOVETYPE_REMOVE: /* remove a randomly chosen molecule */ if (system->cavity_bias) { if (get_rand(system) < pow((1.0 - system->avg_observables->cavity_bias_probability), ((double)system->cavity_grid_size * system->cavity_grid_size * system->cavity_grid_size))) system->checkpoint->biased_move = 0; else system->checkpoint->biased_move = 1; } /* remove 'altered' from the list */ if (!system->checkpoint->head) { /* handle the case where we're removing from the start of the list */ system->checkpoint->molecule_altered = system->molecules; system->molecules = system->molecules->next; } else { system->checkpoint->head->next = system->checkpoint->tail; } free_molecule(system, system->checkpoint->molecule_altered); system->checkpoint->molecule_altered = NULL; /* Insurance against memory errors */ update_pairs_remove(system); //reset atom and molecule id's enumerate_particles(system); break; case MOVETYPE_DISPLACE: /* change coords of 'altered' */ if (system->rd_anharmonic) displace_1D(system, system->checkpoint->molecule_altered, system->move_factor); else if (system->spectre) spectre_displace(system, system->checkpoint->molecule_altered, system->move_factor, system->spectre_max_charge, system->spectre_max_target); else if (system->gwp) { if (system->checkpoint->molecule_altered->atoms->gwp_spin) { displace(system, system->checkpoint->molecule_altered, system->pbc, system->gwp_probability, system->rot_factor); displace_gwp(system, system->checkpoint->molecule_altered, system->gwp_probability); } else displace(system, system->checkpoint->molecule_altered, system->pbc, system->move_factor, system->rot_factor); } else displace(system, system->checkpoint->molecule_altered, system->pbc, system->move_factor, system->rot_factor); break; case MOVETYPE_ADIABATIC: /* change coords of 'altered' */ displace(system, system->checkpoint->molecule_altered, system->pbc, system->adiabatic_probability, 1.0); break; case MOVETYPE_SPINFLIP: if (get_rand(system) < 0.5) system->checkpoint->molecule_altered->nuclear_spin = NUCLEAR_SPIN_PARA; else system->checkpoint->molecule_altered->nuclear_spin = NUCLEAR_SPIN_ORTHO; break; case MOVETYPE_VOLUME: volume_change(system); // I don't want to contribute to the god damned mess -- kmclaugh break; default: error( "MC_MOVES: invalid mc move\n"); die(-1); } return; }
// insert value and return count after insertion void insert(key_type const v, uint64_t const w) { uint64_t const p0 = hash(v); uint64_t p = p0; // uint64_t loopcnt = 0; do { // position in use? if ( H[p].first != base_type::unused() ) { // value already present if ( H[p].first == v ) { H[p].second = w; return; } // in use but by other value (collision) else { p = displace(p,v); } } // position is not currently in use, try to get it else { #if defined(LIBMAUS_HAVE_SYNC_OPS) bool const ok = __sync_bool_compare_and_swap ( &(H[p].first), base_type::unused(), v); #else hlock.lock(); bool const ok = (H[p].first == base_type::unused()); if ( ok ) H[p].first = v; hlock.unlock(); #endif assert ( H[p].first != base_type::unused() ); // got it if ( H[p].first == v ) { // if this inserted the value, then increment fill if ( ok ) { #if defined(LIBMAUS_HAVE_SYNC_OPS) __sync_fetch_and_add(&fill,1); #else clock.lock(); fill++; clock.unlock(); #endif } H[p].second = w; return; } // someone else snapped position p before we got it else { p = displace(p,v); } } } while ( p != p0 ); ::libmaus::exception::LibMausException se; se.getStream() << "SimpleHashMap::insert(): unable to insert, table is full." << std::endl; se.finish(); throw se; }