void CvFaceElement::FindRects(IplImage* img, IplImage* thresh, int nLayers, int dMinSize) { FindContours(img, thresh, nLayers, dMinSize / 4); if (0 == m_seqRects->total) return; Energy(); cvSeqSort(m_seqRects, CompareEnergy, NULL); CvTrackingRect* pR = (CvTrackingRect*)cvGetSeqElem(m_seqRects, 0); if (m_seqRects->total < 32) { MergeRects(dMinSize / 8); Energy(); cvSeqSort(m_seqRects, CompareEnergy, NULL); } pR = (CvTrackingRect*)cvGetSeqElem(m_seqRects, 0); if ((pR->iEnergy > 100 && m_seqRects->total < 32) || (m_seqRects->total < 16)) { MergeRects(dMinSize / 4); Energy(); cvSeqSort(m_seqRects, CompareEnergy, NULL); } pR = (CvTrackingRect*)cvGetSeqElem(m_seqRects, 0); if ((pR->iEnergy > 100 && m_seqRects->total < 16) || (pR->iEnergy > 200 && m_seqRects->total < 32)) { MergeRects(dMinSize / 2); Energy(); cvSeqSort(m_seqRects, CompareEnergy, NULL); } }// void CvFaceElement::FindRects(IplImage* img, IplImage* thresh, int nLayers, int dMinSize)
double InvMass (double m1, double m2, double p1x, double p1y, double p1z, double p2x, double p2y, double p2z) { double E1 = Energy(m1,p1x,p1y,p1z); double E2 = Energy(m2,p2x,p2y,p2z); return sqrt( m1*m1 + m2*m2 + 2*(E1*E2 - p1x*p2x - p1y*p2y - p1z*p2z) ); }
void Destroyable::damage(const Energy& energy) { m_remaining_hit_points = m_remaining_hit_points - energy ; if (m_remaining_hit_points < Energy()) { m_remaining_hit_points = Energy() ; } notify() ; }
void Destroyable::damage(const Energy& _energy) { resistance = resistance - _energy ; if (resistance < Energy()) { resistance = Energy() ; } notify() ; }
double POTENTIAL::Num_Der(int n, double **X, double **DX) { //EVALUATE THE n^th ORDER DERIVATIVE BY RECURSIVELY CALCULATING FIRST //ORDER DERIVARIVES BY CENTRAL DIFFERENCE OR FIVE-POINT STENCIL if(n>=1) { n -= 1; double df_dx; //df_dx /*//Central Finite Difference (Order 2^n computations)// DX[n][0] += SMALL; //x+dx df_dx = Num_Der(n, X, DX); //+f(x+dx) DX[n][0] -= SMALL+SMALL; //x-dx df_dx -= Num_Der(n, X, DX); //-f(x-dx) DX[n][0] += SMALL; //x return(df_dx/(SMALL+SMALL)); //df/dx = [f(x+dx)-f(x-dx)]/[2dx]*/ //Five-Point Stencil (Order 4^n computations)// DX[n][0] -= SMALL + SMALL; //x-2dx df_dx = Num_Der(n, X, DX); //+f(x-2dx) DX[n][0] += SMALL; //x-dx df_dx -= 8.*Num_Der(n, X, DX);//-8f(x-dx) DX[n][0] += SMALL + SMALL; //x+dx df_dx += 8.*Num_Der(n, X, DX);//+8f(x+dx) DX[n][0] += SMALL; //x+2dx df_dx -= Num_Der(n, X, DX); //-f(x+2dx) DX[n][0] -= SMALL + SMALL; //x df_dx = df_dx/(12.0*SMALL); //if( (df_dx<1.0e-10)&&(df_dx>-1.0e-10) ) {return(0.0);} return(df_dx); //df/dx = [f(x-2dx)-8f(x-dx)+8f(x+dx)-f(x+2dx)]/[12dx] } else if(n==0) {return(Energy(X));} else {Log <<"Error computing numerical derivative."<<endl;exit(0);} }
string GBRobot::Details() const { string dets = ToString(Energy(), 0) + " energy, " + ToString(hardware.Armor(), 0) + " armor"; if (hardware.constructor.Progress()) dets += ", " + ToPercentString(hardware.constructor.Progress() / hardware.constructor.Type()->Cost(), 0) + " " + hardware.constructor.Type()->Name(); return dets; }
LOCAL void g_fprint_raw_state( FILE *file, Locstate state, int dim) { int i; static char mname[3][3] = { "mx", "my", "mz"}; (void) fprintf(file,"state %p\n",state); //(void) fprintf(file,"\t%-7s = %"FFMT" %-7s = %"FFMT"\n\t","density", // Dens(state),"energy",Energy(state)); (void) fprintf(file,"\t%-7s = %22.16g %-7s = %22.16g\n\t","density", Dens(state),"energy",Energy(state)); for (i = 0; i < dim; i++) (void) fprintf(file,"%-7s = %"FFMT" ",mname[i],Mom(state)[i]); (void) fprintf(file,"\n"); (void) fprintf(file,"\ttype = %u, failed = %u\n", state_type(state),material_failure(state)); if (debugging("prt_params")) fprint_Gas_param(file,Params(state)); else (void) fprintf(file,"Gas_param = %llu\n", gas_param_number(Params(state))); if (debugging("local_gamma")) { (void) fprintf(file,"Local gamma set: %s\n", Local_gamma_set(state) ? "YES" : "NO"); if (Local_gamma_set(state)) (void) fprintf(file,"Local gamma = %"FFMT"\n", Local_gamma(state)); } } /*end g_fprint_raw_state*/
//Histogram *Unser(Image *img) float *Unser(Image *img) { Histogram *h = NULL; float sum[4][511], dif[4][511], *val=NULL; float mean, contrast, correlation; int i; val = (float*) calloc(SIZE,sizeof(float)); ComputeHistograms(img, sum, dif); for (i=0; i<4; i++){ mean = Mean(sum[i]); val[i * 8 + 0] = mean; contrast = Contrast(dif[i]); val[i * 8 + 1] = contrast;// / 255.0; correlation = Correlation(sum[i], mean, contrast); val[i * 8 + 2] = (correlation);// + 32512.5) / 255.0; val[i * 8 + 3] = Energy(sum[i], dif[i]);// * 255.0 ; val[i * 8 + 4] = Entropy(sum[i], dif[i]);// * 255.0 / 5.4168418; val[i * 8 + 5] = Homogeneity(dif[i]);// * 255.0; val[i * 8 + 6] = MaximalProbability(sum[i]);// * 255.0; val[i * 8 + 7] = StandardDeviation(contrast, correlation);// *sqrt(2); } //h = CreateHistogram(SIZE); //LinearNormalizeHistogram(h->v, val, 255.0, SIZE); //return(h); return(val); }
int main( ) { double t, energy, number, sf, sf2; int i, N; FILE *fp; fp = fopen("BEC_ideal2.dat", "w"); //partition N = 50; fprintf(fp, "# Temp ChemiPo Energy Num\n"); for(i=0; i<=2*N; i++) { t = 1.0*i/N; energy = Energy(t, 0); number = Number(t); sf = Specific_heat(t,2.0/N, sf2); printf("%20.16f %20.16f %20.16f %20.16f %20.16f \n", t, mu(t), energy, number, sf); fprintf(fp ,"%20.16f %20.16f %20.16f %20.16f %20.16f\n", t, mu(t), energy, number, sf); sf2 = sf; } fclose(fp); return 0; }
const LfnIc::Energy* LfnIc::ConstNodeLabels::GetMessages(int index) const { wxASSERT(index >= 0); wxASSERT(index < size()); static const Energy globalMessageSet[NumNeighborEdges] = {Energy(0)}; return m_globalLabelSet ? globalMessageSet : m_node.m_labelInfoSet[index].messages; }
ParticleSampler::ParticleSampler(const ParticleSamplerObject* definition, const Source* source) : user_id(definition->getSamplerid()), position(definition->getPosition()), direction(definition->getDirection()), energy(Energy(0,definition->getEnergy())), weight(1.0) { /* Get distributions */ vector<DistributionId> distribution_ids = definition->getDistributionIds(); for(vector<DistributionId>::iterator it = distribution_ids.begin() ; it != distribution_ids.end() ; ++it) distributions.push_back(source->getObject<DistributionBase>((*it))[0]); }
//return Pressure, Velocity, Density, Energy Real4 CaseVacuum(Real PressureLeft, Real VelocityLeft, Real DensityLeft, Real GammaLeft, Real SoundLeft, Real PressureRight, Real VelocityRight, Real DensityRight, Real GammaRight, Real SoundRight) { Real4 Result; if (VelocityLeft - SoundLeft >= 0) { Density(Result) = DensityLeft; Pressure(Result) = PressureLeft; Velocity(Result) = VelocityLeft; Energy(Result) = Pressure(Result) / ((GammaLeft - 1) * Density(Result)); } else if (VelocityLeft + 2 * SoundLeft / (GammaLeft - 1) >= 0) { Real Ratio = 2 / (GammaLeft + 1); Density(Result) = DensityLeft * Ratio; Pressure(Result) = PressureLeft * Ratio; Velocity(Result) = VelocityLeft + SoundLeft * Ratio; Energy(Result) = Pressure(Result) / ((GammaLeft - 1) * Density(Result)); } if (VelocityRight + SoundRight <= 0) { Density(Result) = DensityRight; Pressure(Result) = PressureRight; Velocity(Result) = VelocityRight; Energy(Result) = Pressure(Result) / ((GammaRight - 1) * Density(Result)); } else if (VelocityLeft - 2 * SoundRight / (GammaRight - 1) <= 0) { Real Ratio = 2 / (GammaRight + 1); Density(Result) = DensityRight * Ratio; Pressure(Result) = PressureRight * Ratio; Velocity(Result) = VelocityRight - SoundLeft * Ratio; Energy(Result) = Pressure(Result) / ((GammaRight - 1) * Density(Result)); } else { Density(Result) = 0; Pressure(Result) = 0; Velocity(Result) = 0; Energy(Result) = 0; }; return Result; }
double EnergyFunction(double trial[],bool &bAtSolution) { double result=evaluatePlane(trial[0],trial[1],V,Vmag, maxFreq, planeWidth, direction, NULL, setPos, rotPos, tiltPos); if (count++ % (5*nPop) == 0) std::cout << "Evaluations= " << count/nPop << " energy= " << Energy() << " rot= " << Solution()[0] << " tilt= " << Solution()[1] << std::endl; bAtSolution=false; return result; }
LOCAL Locstate load_tmpst( float rho, float e, Locstate state) { static Locstate tmpst = NULL; if (tmpst == NULL) g_alloc_state(&tmpst,Params(state)->sizest); Set_params(tmpst,state); Dens(tmpst) = rho; Energy(tmpst) = e; set_type_of_state(tmpst,EGAS_STATE); return tmpst; } /*load_tmpst*/
Jet MuXboostedBTagging::Core(std::vector<Jet> const &core_candidates, std::vector<Lepton> const &muons) const { INFO0; auto hardest_muon = *boost::range::max_element(muons, [](Lepton const & muon_1, Lepton const & muon_2) { return muon_1.Pt() > muon_2.Pt(); }); auto min_delta_mass = std::numeric_limits<Mass>::max(); // Default to infinity auto core = core_candidates.front(); // Default to hardest core for (auto const &core_candidate : core_candidates) { if (core_candidate.Energy() == 0_eV) continue; auto g = sqr(MassOf(Id::Dpm) / core_candidate.Energy()); // Make sure we still have sufficient boost after muon subtraction if (g * sqr(core_min_boost_) > 1.) continue; auto y = core_candidate.Spatial().Tan2(hardest_muon.Spatial()); // The core has the mass closest to fSubjetMassHypothesis auto radicant = 1. - ((g - y) + g * y); if (radicant < 0) continue; auto denom = 1. + y + sqrt(radicant); if (denom == 0) continue; auto radicant2 = sqr(MassOf(Id::Dpm)) + (4. * hardest_muon.Energy() * core_candidate.Energy() * (g + y)) / denom; if (radicant2 < 0_eV * eV) continue; auto delta_mass = abs(sqrt(radicant2) - MassOf(Id::B0)); if (delta_mass > min_delta_mass) continue; min_delta_mass = delta_mass; core = core_candidate; } if (core.ModP2() == 0_eV * eV) return core; // The current mass depends more on the granularity of the CAL more than anything else // To fix the mass, We need to scale the momentum of the core (but not the energy) core.ScaleMomentum(sqrt((core.Energy() - MassOf(Id::Dpm)) * (core.Energy() + MassOf(Id::Dpm)) / core.ModP2())); return core; }
/* For the equations that include energy The state equations is: p = \rho RT, where \rho is the density, T is the temperature, and R is the gas constant which is 8.3144621 J K^{-1} mol^{-1}. Note that here x->rE is the rho scaled total energy per unit mass r*E, that is the total energy per unit volume */ PetscErrorCode Pressure_Partial(User user,const Node *x,PetscScalar *p) { PetscErrorCode ierr; PetscScalar e; // the internal energy per unit mass PetscFunctionBeginUser; ierr = Energy(user, x, &e); CHKERRQ(ierr);// Compute the iternal energy // p = rho*(gamma - 1)*e (*p) = x->r*(user->adiabatic-1)*e; PetscFunctionReturn(0); }
wxString grib_pi::GetLongDescription() { return _("GRIB PlugIn for OpenCPN\n\ Provides basic GRIB file overlay capabilities for several GRIB file types\n\ and a request function to get GRIB files by eMail.\n\n\ Supported GRIB data include:\n\ - wind direction and speed (at 10 m)\n\ - wind gust\n\ - surface pressure\n\ - rainfall\n\ - cloud cover\n\ - significant wave height and direction\n\ - air surface temperature (at 2 m)\n\ - sea surface temperature\n\ - surface current direction and speed\n\ - Convective Available Potential Energy (CAPE)\n\ - wind, altitude, temperature and relative humidity at 300, 500, 700, 850 hPa." ); }
LOCAL void g_fprint_raw_Estate( FILE *file, Locstate state, int dim) { int i; static char vname[3][3] = { "vx", "vy", "vz"}; (void) fprintf(file,"\tdensity = %"FFMT" energy = %"FFMT" ", Dens(state),Energy(state)); for (i = 0; i < dim; i++) (void) fprintf(file,"%-8s = %"FFMT" ",vname[i],Vel(state)[i]); if (debugging("prt_params")) fprint_Gas_param(file,Params(state)); else (void) fprintf(file,"Gas_param = %llu\n", gas_param_number(Params(state))); } /*end g_fprint_raw_Estate*/
// x and y are in image space FORCE_INLINE Energy Get(const Image::Pixel* imagePixel, const Mask::Value* maskBuffer, int x, int y) const { Energy e(0); if (x >= 0 && y >= 0 && x < m_imageWidth && y < m_imageHeight) { const int imageIdx = LfnTech::GetRowMajorIndex(m_imageWidth, x, y); if (!maskBuffer || maskBuffer[imageIdx] == Mask::KNOWN) { const Image::Pixel& pixel = imagePixel[imageIdx]; for (int c = 0; c < Image::Pixel::NUM_CHANNELS; ++c) { e += Energy(pixel.channel[c] * pixel.channel[c]); } } } return e; }
Kernel::Trait* Laser::read(Kernel::Reader* reader) { Laser* result = new Laser(Position(),Orientation(),Energy()) ; while (!reader->isEndNode() && reader->processNode()) { if (reader->isTraitNode() && reader->getTraitName() == "Position") { result->m_out_position = Position::read(reader) ; } else if (reader->isTraitNode() && reader->getTraitName() == "Orientation") { result->m_out_orientation = Orientation::read(reader) ; } else if (reader->isTraitNode() && reader->getTraitName() == "Energy") { result->m_laser_beam_energy = Energy::read(reader) ; } else if (reader->isTraitNode() && reader->getTraitName() == "Duration") { if (reader->getName() == "beam_lifetime") result->m_beam_lifetime = Duration::read(reader) ; else if (reader->getName() == "shot_delay") result->m_time_between_shots = Duration::read(reader) ; } else if (reader->isTraitNode() && reader->getTraitName() == "Distance") { if (reader->getName() == "beam_length") result->m_beam_length = Distance::read(reader) ; else if (reader->getName() == "beam_radius") result->m_beam_radius = Distance::read(reader) ; } } reader->processNode() ; return result ; }
EXPORT void g_print_internal_energy( const char *mesg, float **ucon, Vec_Muscl *vmuscl, int start, int end) { int i, j, dim = vmuscl->dim; float int_e, ke; float E, m[MAXD], rho; Locstate *state = vmuscl->vst->state + vmuscl->offset; static Locstate st = NULL; if (st == NULL) { g_alloc_state(&st,vmuscl->sizest); } (void) printf("%s\n",mesg); (void) printf("%-4s %-14s %-14s\n","n","Int_energy","Pressure"); for (j = start; j < end; ++j) { Dens(st) = rho = ucon[0][j]; Energy(st) = E = ucon[1][j]; ke = 0.0; for (i = 0; i < dim; ++i) { Mom(st)[i] = m[i] = ucon[2+i][j]; ke += 0.5*sqr(m[i])/rho; } Set_params(st,state[j]); set_type_of_state(st,GAS_STATE); reset_gamma(st); int_e = (E - ke)/rho; (void) printf("%-4d %-14g %-14g",j,int_e,pressure(st)); if (int_e < 0.0) (void) printf("\tNEGATIVE INTERNAL ENERGY\n"); else (void) printf("\n"); } } /*end g_print_internal_energy*/
//return Pressure, Velocity, Density, Energy Real4 SolveHalfProblem(Real PressureOut, Real VelocityOut, Real DensityOut, Real GammaOut, Real SoundOut, Real PressureContact, Real VelocityContact, bool Left) { Real Sign = Left ? Real(1) : Real(-1); Real4 Result; if (PressureOut > PressureContact) Result = HalfProblemDepressionWave(PressureOut, Sign * VelocityOut, DensityOut, GammaOut, SoundOut, PressureContact, Sign * VelocityContact); else if (PressureOut < PressureContact) Result = HalfProblemShockWave(PressureOut, Sign * VelocityOut, DensityOut, GammaOut, SoundOut, PressureContact, Sign * VelocityContact); else Result = HalfProblemContactDiscontinuty(PressureOut, Sign * VelocityOut, DensityOut, GammaOut, SoundOut, PressureContact, Sign * VelocityContact); Energy(Result) = Pressure(Result) / ((GammaOut - 1) * Density(Result)); Velocity(Result) = Sign * Velocity(Result); return Result; }
Kernel::Trait* Destroyable::read(Kernel::Reader* reader) { Destroyable* result = new Destroyable(Energy()) ; bool read_max_hit_point = false ; bool read_current_hit_point = false ; while (!reader->isEndNode() && reader->processNode()) { if (reader->isTraitNode() && reader->getTraitName() == "Energy") { if (reader->getName() == "max_hit_points") { result->m_max_hit_points = Energy::read(reader) ; read_max_hit_point = true ; } else if (reader->getName() == "current_hit_points") { result->m_remaining_hit_points = Energy::read(reader) ; read_current_hit_point = true ; } } else { Trait::read(reader) ; } } reader->processNode() ; if (!read_max_hit_point) { ErrorMessage("Model::Destroyable::read must specify an Energy sub node with name max_hit_points") ; } if(! read_current_hit_point) { result->m_remaining_hit_points = result->m_max_hit_points ; } return result ; }
EXPORT void g_fprint_tdp_boundary_state_data( FILE *file, INTERFACE *intfc, BOUNDARY_STATE *bstate) { FD_DATA *fd_data = (FD_DATA*)bstate->_boundary_state_data; (void) f_fprint_boundary_state_data(file,intfc,bstate); (void) fprintf(file,"Rise time = %g\n",fd_data->tr); (void) fprintf(file,"Peak time = %g\n",fd_data->tp); (void) fprintf(file,"Shut-off time = %g\n",fd_data->ts); (void) fprintf(file,"Ambient pressure = %g\n",fd_data->pr_a); (void) fprintf(file,"Peak pressure = %g\n",fd_data->pr_p); /* Feb 19 2004: print reference state */ if (fd_data->state != NULL) { (void) fprintf(file,"Reference state:\n"); Energy(fd_data->state)=energy(fd_data->state); set_type_of_state(fd_data->state,GAS_STATE); fprint_state_data(file,fd_data->state,intfc); } } /* end g_fprint_tdp_boundary_state_data */
//============================================================== // Processes n events //============================================================== void box::Process(int n) { double deltat = gtime; for (int i=0; i<n; i++) { ProcessEvent(); } pf = PackingFraction(); // packing fraction deltat = gtime - deltat; double oldenergy = energy; energy = Energy(); // kinetic energy energychange = ((oldenergy - energy)/oldenergy)*100; // percent change in energy if (deltat != 0.) pressure = 1+xmomentum/(2.*energy*N*deltat); // reset to 0 ncollisions = 0; ntransfers = 0; nchecks = 0; xmomentum = 0.; ncycles++; }
LfnIc::Energy LfnIc::EnergyWsst::Calculate(int left, int top, int width, int height) const { wxASSERT(width % m_blockWidth == 0); wxASSERT(height % m_blockHeight == 0); if (width > 0 && height > 0 && width % m_blockWidth == 0 && height % m_blockHeight == 0) { Energy e = Energy(0); // m_table is padded to the top and left by m_blockWidth and // m_blockHeight, respectively. left and top are in image space, // and so much be transformed to table space. const int tableLeft = left + m_blockWidth; const int tableTop = top + m_blockHeight; const int numBlockCols = width / m_blockWidth; const int numBlockRows = height / m_blockHeight; for (int j = 0, tableY = tableTop; j < numBlockRows; ++j, tableY += m_blockHeight) { for (int i = 0, tableX = tableLeft; i < numBlockCols; ++i, tableX += m_blockWidth) { if (tableX >= 0 && tableY >= 0 && tableX < m_tableWidth && tableY < m_tableHeight) { e += m_table[LfnTech::GetRowMajorIndex(m_tableWidth, tableX, tableY)]; } } } return e; } else { wxFAIL_MSG("LfnIc::EnergyWsst::Calculate - width and/or height was invalid!"); return ENERGY_MIN; } }
boca::LorentzVector< Momentum > PseudoJet::LorentzVector() const { return {Px(), Py(), Pz(), Energy()}; }
void EnemyManager::update(float delta) { if(enemies.empty()) { ammo_manager->getPlanet()->increaseRound(); while( enemies.size() < (unsigned)(4+ammo_manager->getPlanet()->getRound()) ) { float spawn_angle = ( (float)rand()/(float)RAND_MAX ) * 360.0f; for(auto i = enemies.begin(); i != enemies.end();) { if( (i->spawned_angle+10 > spawn_angle) && (i->spawned_angle-10 < spawn_angle) ) { spawn_angle += 15; } else { i++; } } float x = 400 + (500 * cosf(spawn_angle * PI / 180.0f)); float y = 300 + (500 * sinf(spawn_angle * PI / 180.0f)); float dx = 400 - x; float dy = 300 - y; float angle = atan2(dy, dx); int rndm_shoottime = 1 + (rand() % 5); int health = 80; int lvl = 1; if(ammo_manager->getPlanet()->getRound() >= 2) { lvl += (rand() % 2); if(lvl == 2) health += 20; } enemies.push_back(Enemy(x, y, angle, spawn_angle, health, 2, rndm_shoottime, lvl, enemies.size())); } return; } else { for(auto i = enemies.begin(); i != enemies.end();) { // is dead if(i->life <= 0) { energies.push_back(Energy(i->x, i->y, 5)); i = enemies.erase(i); } else { // enemies & player shots enemy_sprite.setPosition(i->x, i->y); enemy_sprite.setRotation((i->angle * 180.0f / PI) + 90.0f); sf::Rect<float> bounds = enemy_sprite.getGlobalBounds(); for(auto j = ammo_manager->getShots()->begin(); j != ammo_manager->getShots()->end();) { if(bounds.contains(j->x, j->y) && (j->id != i->id)) { i->life -= j->dmg; j = ammo_manager->getShots()->erase(j); } else { j++; } } // fly around sf::Vector2f dir( 400 - i->x, 300 - i->y ); float length = sqrtf( powf(dir.x, 2.0f) + powf(dir.y, 2.0f) ); if(i->lvl == 1 && length > 200.0f) { i->x += delta*150.0f*cosf(i->angle); i->y += delta*150.0f*sinf(i->angle); } else if(i->lvl >= 2 && length > 250.0f) { i->x += delta*150.0f*cosf(i->angle); i->y += delta*150.0f*sinf(i->angle); } // shoot if(i->time.asSeconds() > i->shoot_time) { i->time = sf::Time::Zero; ammo_manager->addShot(i->x, i->y, i->angle * 180.0f / PI, i->dmg, i->id); } else { i->time += i->clock.restart(); } i++; } } } }
EXPORT bool output_spectral_analysis( char *basename, Wave *wave, Front *front) { COMPONENT comp; Locstate state; float *coords; float *L = wave->rect_grid->L; float *U = wave->rect_grid->U; float *h = wave->rect_grid->h; int icoords[MAXD]; int dim = wave->rect_grid->dim; int status; int step = front->step; char energy_name[100],vorticity_name[100], enstrophy_name[100],dens_name[100],pres_name[100]; FILE *energy_file,*vorticity_file, *enstrophy_file,*dens_file,*pres_file; debug_print("fft","Entered fft_energy_spectral()\n"); (void) sprintf(energy_name,"%s.energy%s.dat",basename, right_flush(step,TSTEP_FIELD_WIDTH)); (void) sprintf(vorticity_name,"%s.vorticity%s.dat",basename, right_flush(step,TSTEP_FIELD_WIDTH)); (void) sprintf(enstrophy_name,"%s.enstrophy%s.dat",basename, right_flush(step,TSTEP_FIELD_WIDTH)); (void) sprintf(dens_name,"%s.density%s.dat",basename, right_flush(step,TSTEP_FIELD_WIDTH)); (void) sprintf(pres_name,"%s.pressure%s.dat",basename, right_flush(step,TSTEP_FIELD_WIDTH)); energy_file = fopen(energy_name,"w"); vorticity_file = fopen(vorticity_name,"w"); enstrophy_file = fopen(enstrophy_name,"w"); dens_file = fopen(dens_name,"w"); pres_file = fopen(pres_name,"w"); if (wave->sizest == 0) { debug_print("fft","Left fft_energy_spectral()\n"); return FUNCTION_FAILED; } switch (dim) { #if defined(ONED) case 1: { int ix; int xmax; COMPLEX *mesh_energy; xmax = wave->rect_grid->gmax[0]; uni_array(&mesh_energy,xmax,sizeof(COMPLEX)); for (ix = 0; ix < xmax; ++ix) { icoords[0] = ix; coords = Rect_coords(icoords,wave); comp = Rect_comp(icoords,wave); state = Rect_state(icoords,wave); mesh_energy[ix].real = Energy(state); mesh_energy[ix].imag = 0.0; } break; } #endif /* defined(ONED) */ #if defined(TWOD) case 2: { int ix, iy; int xmax, ymax, mx, my, dummy; COMPLEX **mesh_energy,**mesh_vorticity,**mesh_enstrophy; Locstate lstate,rstate,bstate,tstate; float kk,kx,ky,dk; xmax = wave->rect_grid->gmax[0]; ymax = wave->rect_grid->gmax[1]; if (!Powerof2(xmax,&mx,&dummy) || !Powerof2(ymax,&my,&dummy)) { screen("fft_energy_spectral() cannot analyze " "mesh not power of 2\n"); screen("xmax = %d ymax = %d\n",xmax,ymax); return FUNCTION_FAILED; } bi_array(&mesh_energy,xmax,ymax,sizeof(COMPLEX)); bi_array(&mesh_vorticity,xmax,ymax,sizeof(COMPLEX)); fprintf(energy_file,"zone i=%d, j=%d\n",xmax,ymax); fprintf(vorticity_file,"zone i=%d, j=%d\n",xmax,ymax); fprintf(dens_file,"zone i=%d, j=%d\n",xmax,ymax); fprintf(pres_file,"zone i=%d, j=%d\n",xmax,ymax); fprintf(enstrophy_file,"zone i=%d, j=%d\n",xmax,ymax); for (iy = 0; iy < ymax; ++iy) { for (ix = 0; ix < xmax; ++ix) { icoords[0] = ix; icoords[1] = iy; coords = Rect_coords(icoords,wave); comp = Rect_comp(icoords,wave); state = Rect_state(icoords,wave); mesh_energy[ix][iy].real = kinetic_energy(state); mesh_energy[ix][iy].imag = 0.0; if (ix != 0) icoords[0] = ix - 1; else icoords[0] = ix; lstate = Rect_state(icoords,wave); if (ix != xmax-1) icoords[0] = ix + 1; else icoords[0] = ix; rstate = Rect_state(icoords,wave); icoords[0] = ix; if (iy != 0) icoords[1] = iy - 1; else icoords[1] = iy; bstate = Rect_state(icoords,wave); if (iy != ymax-1) icoords[1] = iy + 1; else icoords[1] = iy; tstate = Rect_state(icoords,wave); mesh_vorticity[ix][iy].real = (Mom(rstate)[1]/Dens(rstate) - Mom(lstate)[1]/Dens(lstate))/h[0] - (Mom(tstate)[0]/Dens(tstate) - Mom(bstate)[0]/Dens(bstate))/h[1]; mesh_vorticity[ix][iy].imag = 0.0; fprintf(energy_file,"%lf\n",kinetic_energy(state)); fprintf(vorticity_file,"%lf\n",mesh_vorticity[ix][iy].real); fprintf(enstrophy_file,"%lf\n", sqr(mesh_vorticity[ix][iy].real)); fprintf(dens_file,"%lf\n",Dens(state)); fprintf(pres_file,"%lf\n",pressure(state)); } } fft_output2d(basename,"energy",step,wave->rect_grid, mesh_energy); fft_output2d(basename,"vorticity",step,wave->rect_grid, mesh_vorticity); free_these(2,mesh_energy,mesh_vorticity); break; } #endif /* defined(TWOD) */ #if defined(THREED) case 3: { int ix, iy, iz; int xmax, ymax, zmax; COMPLEX ***mesh_energy; xmax = wave->rect_grid->gmax[0]; ymax = wave->rect_grid->gmax[1]; zmax = wave->rect_grid->gmax[2]; tri_array(&mesh_energy,xmax,ymax,zmax,sizeof(COMPLEX)); for (iz = 0; iz < zmax; ++iz) { icoords[2] = iz; for (iy = 0; iy < ymax; ++iy) { icoords[1] = iy; for (ix = 0; ix < xmax; ++ix) { icoords[0] = ix; coords = Rect_coords(icoords,wave); comp = Rect_comp(icoords,wave); state = Rect_state(icoords,wave); mesh_energy[ix][iy][iz].real = Energy(state); mesh_energy[ix][iy][iz].imag = 0.0; } } } break; } #endif /* defined(THREED) */ } fclose(energy_file); fclose(vorticity_file); fclose(enstrophy_file); fclose(dens_file); fclose(pres_file); debug_print("fft","Left fft_energy_spectral()\n"); return FUNCTION_SUCCEEDED; } /*end fft_energy_spectral*/
void simulated_annealing(Model_data *Best, Model_data *Current, Model_data *New, sa_parms sap) { /* a simulated annealing algorithm very similar to the gsl algorithm described here: * https://www.gnu.org/software/gsl/manual/html_node/Simulated-Annealing.html * This function is a global optimization method that randomly searches to the parameter space to * find the optimal set of parameters that minimizes the negative log likelihood function */ double bolt = 0.0; double tmin = sap.tmin; double mu = sap.mu; double Temp = sap.startTemp; unsigned int no_iter = sap.no_iter; double k = sap.k; double *step_size = sap.step_size; double *upper_bound = sap.upper_bound; double rand = 0.0; double Best_E = 0.0; double Current_E = 0.0; double New_E = 0.0; unsigned int z; gsl_rng *r = gsl_rng_alloc(gsl_rng_uni); gsl_rng_set(r,10); gsl_rng *r1 = gsl_rng_alloc(gsl_rng_uni); gsl_rng_set(r1,22); /* start of the simualation with the current point as the best */ Current_E = Energy((void *)Current); Best_E = Energy((void *)Best); printf("Iter Temp r K c Current Best\n"); while (Temp > tmin) { z++; for (int i = 0; i < no_iter; i++) { /* reset "new" parameters to that of the current parameters */ memmove((void *)New,(void *)Current,sizeof(Model_data)); /*take a random step from current parameter position */ Step(r1, (Model_data *)New, step_size, upper_bound); /* evaluate energy associated with new parameters */ New_E = Energy(New); if (New_E <= Best_E) { /* change new to best */ memmove((void *)Best,(void *)New,sizeof(Model_data)); Best_E = New_E; /* and also to current */ memmove((void *)Current,(void *)New,sizeof(Model_data)); Current_E = New_E; } else if (New_E <= Current_E) { /*change new to current */ memmove((void *)Current,(void *)New,sizeof(Model_data)); Current_E = New_E; } else { bolt = exp(-(New_E-Best_E)/(k*Temp)); rand = gsl_rng_uniform(r); if (rand < bolt) { /*take a step leading to higher energy (for global optimization) * change new to current */ memmove((void *)Current,(void *)New,sizeof(Model_data)); Current_E = New_E; } } } /*temperature cooling by damping factor mu */ Temp /= mu; /*print "new" parameters along with current and best energy */ printf("%d %.5e %.2f %.2f %.2f %.2f %.2f\n",z,Temp,New->x[0],New->x[1],New->x[2],Current_E,Best_E); } /*print the optimal solution */ printf("Parameters for best NLL:\n"); printf("r = %f, K = %f, c = %f\n",Best->x[0],Best->x[1],Best->x[2]); gsl_rng_free(r); gsl_rng_free(r1); }