Ejemplo n.º 1
0
attemptRandomStep()
{
  double step_x, step_y, step_z;
  double metropolis;

  step_x = (rnd()-.5) * step_size_factor;
  step_y = (rnd()-.5) * step_size_factor;
  step_z = (rnd()-.5) * step_size_factor;

//  energy = new_energy;

  energy = calculateEnergy();

  test_x += step_x;
  test_y += step_y;
  test_z += step_z;
  
  new_energy = calculateEnergy();
  if ((new_energy < energy) || (rnd() < exp(-(new_energy-energy)*beta)))
  {
    successes++;
    return;
  }
  else 
  {
    test_x-=step_x;
    test_y-=step_y;
    test_z-=step_z;
    new_energy=energy;
  }
}
Ejemplo n.º 2
0
void MonteCarlo::monteCarloAlgorithm() {
	logg("start monteCarlo algorithm...");
	Time st(boost::posix_time::microsec_clock::local_time());
	calculateEnergy();
	vector<cell*> listCells;
	for (int i = 0; i < 100; i++) {
		copySpaces(oldstate, cells);
		fillList(&listCells, cells);
		//cout<<listCells.size()<<endl;
		if(listCells.size()>0){
		executeList(&listCells,cells,oldstate);
		}
		manager->run();
		manager->join_all();
		listCells.clear();

	}

	Time end(boost::posix_time::microsec_clock::local_time());
	TimeDuraction d = end - st;
	duraction = d.total_milliseconds();
	loggTime("time execution montecarlo algorithm: ",duraction);
	saveToFile();
	//drawSpace();

}
Ejemplo n.º 3
0
//need to make a proper evaluation function
//get the best CPG function, delete the rest of CPGs and clear the m_birdCPGs array
void BirdOptimizer::evaluateCurrentGenerationBirds() {

    m_perturb_scaler = btExp(-btPow(((m_numGeneration - 1) * 2.8f/50.f + 1.5f), 1.2f));

    if (m_numGeneration == 0)
        return;

    //choose the best CPG
    float minEnergy = FLT_MAX;
    int minIndex = -1;
    for (int ii = 0; ii < m_birdTrajectoryData.size(); ++ii) {
        float energy =
            calculateTimeToHitGround(m_birdTrajectoryData[ii])
            + calculateTotalUpTime(m_birdTrajectoryData[ii])
            + calculateEnergy(m_birdTrajectoryData[ii])/1500.0;
        std::cout << "\tenergy: " << energy << std::endl;
        if (energy < minEnergy)
        {
            minEnergy = energy;
            minIndex = ii;
        }
    }
    std::cout << "---GENERATION: " << m_numGeneration << " :: "
              << "min_energy: " << minEnergy
              << ", index: " << minIndex
              << ", scaler: " << m_perturb_scaler
              << std::endl;
    m_currentBestInfo = m_birdInfos[minIndex];

    // Save bird configuration.

    proto::BirdOptimizerResult* result = m_result_data.add_result();
    result->set_cum_energy(minEnergy);
    result->mutable_bird()->CopyFrom(*m_birdInfos[minIndex]);


    {
        std::ofstream ofs("C:\\Users\\k\\bird_data.pbdata", std::ios::out | std::ios::trunc | std::ios::binary);
        ofs << m_result_data.SerializeAsString();
    }
    {
        std::ofstream ofs("C:\\Users\\k\\bird_data.txt", std::ios::out | std::ios::trunc);
        ofs << m_result_data.DebugString();
    }



    for (int ii = 0; ii < m_birdTrajectoryData.size(); ++ii) {
        delete m_birdTrajectoryData[ii];
    }
    m_birdTrajectoryData.clear();

    for (int ii = 0; ii < m_birdInfos.size(); ii++) {
        if (m_birdInfos[ii] == m_currentBestInfo) continue;
        delete m_birdInfos[ii];
    }
    m_birdInfos.clear();

}
Ejemplo n.º 4
0
void *ThreadMain(void *passval) { 
  Trajectory *p_traj = (Trajectory *)malloc(sizeof(Trajectory));
  assert(p_traj);
  p_traj->thread_id = *(int *)passval; 
  MersenneInitialize(&(p_traj->rng), seed + p_traj->thread_id);

  generateTestPoint(p_traj);

  // guarantee insertion point not be located in a valley whose bottom is > 0 energy... otherwise cannot size with real value
  while (calculateEnergy(p_traj, 0.0) > 0) generateTestPoint(p_traj);
   
  // now find energy minimum point
  findEnergyMinimum(p_traj);
   
  p_traj->sq_distance_from_initial_pt 	= (p_traj->test_x-p_traj->test_x0)*(p_traj->test_x-p_traj->test_x0) 
				   	+ (p_traj->test_y-p_traj->test_y0)*(p_traj->test_y-p_traj->test_y0) 
				   	+ (p_traj->test_z-p_traj->test_z0)*(p_traj->test_z-p_traj->test_z0);
  if (!volume_sampling || (p_traj->sq_distance_from_initial_pt < .25 * p_traj->diameter * p_traj->diameter)) {
    makeVerletList(p_traj);
    expandTestParticle(p_traj);
    if (p_traj->diameter > min_diameter) {
      // correct for box edges...
      while (p_traj->test_x >= box_x) 	p_traj->test_x -= box_x;
      while (p_traj->test_x < 0) 	p_traj->test_x += box_x;
      while (p_traj->test_y >= box_y) 	p_traj->test_y -= box_y;
      while (p_traj->test_y < 0) 	p_traj->test_y += box_y;
      while (p_traj->test_z >= box_z) 	p_traj->test_z -= box_z;
      while (p_traj->test_z < 0) 	p_traj->test_z += box_z;

      pthread_mutex_lock(&mutex);
      printf("%lf\t%lf\t%lf\t%lf", p_traj->test_x, p_traj->test_y, p_traj->test_z, p_traj->diameter);
      if (include_center_energy) printf("\t%lf", calculateEnergy(p_traj, p_traj->diameter));
      if (show_steps) printf("\t%d", p_traj->attempts);
      printf("\n");
      pthread_mutex_unlock(&mutex);
    }
  }
  
free(p_traj);
  sem_post(&semaphore);
  sem_post(&completion_semaphore);
  pthread_exit(NULL);
}
Ejemplo n.º 5
0
/*! @brief Runs calculations on meter use statistics.
 *
 *  After all the samples over a period have been collected, this routine is invoked.
 */
static void runCalculations(void)
{
  uint8_t i;

  //Loop through the samples to -1 the total sample length
  for(i = 0; i < 15; i++)
  {
    calculateEnergy(VoltageSamples[i], CurrentSamples[i], bFALSE);
    calculateRMS(VoltageSamples[i], bFALSE, RMS_VOLTAGE);
    calculateRMS(CurrentSamples[i], bFALSE, RMS_CURRENT);
  }

  //Calculate the final values, indicating to the functions that all samples have been accounted for
  calculateEnergy(VoltageSamples[15], CurrentSamples[15], bTRUE);
  calculateRMS(VoltageSamples[15], bTRUE, RMS_VOLTAGE);
  calculateRMS(CurrentSamples[15], bTRUE, RMS_CURRENT);

  PerformingCalculations = bFALSE;
}
Ejemplo n.º 6
0
//************************************************************
void Observables::calculateObservables()
{

    if(minimize){
        calculateEnergy();
        calculateVariationalDerivateRatio();
    }
    else{
        calculateEnergy();
        calculateAverageDistance();
        if(cycle %5==0){
            addPositionsToPositionMatrix();
        }

        if(blockingIsEnable){
            addEnergyTototEnergyVector();
        }
    }

}
Ejemplo n.º 7
0
QImage GradientEnergy::getEnergyPlot(){
    //QImage plot = QImage(image.width(),image.height(),QImage::Format_Mono);
    unsigned int* pixs = (unsigned int*) malloc(sizeof(unsigned int)*height*width);
    float temp = 0;
    for (int y = 0; y < height; y++){
        for (int x = 0; x < width; x++){
            temp = calculateEnergy(x,y);
            pixs[y*width+x] = qRgb(temp,temp,temp);
        }
    }
    return QImage((unsigned char*)pixs,width,height,QImage::Format_ARGB32);
}
Ejemplo n.º 8
0
void run(cv::Mat& image,cv::Mat& outImage,cv::Mat& outMinTrace,cv::Mat& outDeletedLine)
{
	cv::Mat image_gray(image.rows,image.cols,CV_8U,cv::Scalar(0));
	cv::cvtColor(image,image_gray,CV_BGR2GRAY); //彩色图像转换为灰度图像

	cv::Mat gradiant_H(image.rows,image.cols,CV_32F,cv::Scalar(0));//水平梯度矩阵
	cv::Mat gradiant_V(image.rows,image.cols,CV_32F,cv::Scalar(0));//垂直梯度矩阵

	cv::Mat kernel_H = (cv::Mat_<float>(3,3) << 0, 0, 0, 0, 1, -1, 0, 0, 0); //求水平梯度所使用的卷积核(赋初始值)
	cv::Mat kernel_V = (cv::Mat_<float>(3,3) << 0, 0, 0, 0, 1, 0, 0, -1, 0); //求垂直梯度所使用的卷积核(赋初始值)

	cv::filter2D(image_gray,gradiant_H,gradiant_H.depth(),kernel_H);
	cv::filter2D(image_gray,gradiant_V,gradiant_V.depth(),kernel_V);

	cv::Mat gradMag_mat(image.rows,image.rows,CV_32F,cv::Scalar(0));
	cv::add(cv::abs(gradiant_H),cv::abs(gradiant_V),gradMag_mat);//水平与垂直滤波结果的绝对值相加,可以得到近似梯度大小

	////如果要显示梯度大小这个图,因为gradMag_mat深度是CV_32F,所以需要先转换为CV_8U
	//cv::Mat testMat;
	//gradMag_mat.convertTo(testMat,CV_8U,1,0);
	//cv::imshow("Image Show Window2",testMat);

	//计算能量线
	cv::Mat energyMat(image.rows,image.cols,CV_32F,cv::Scalar(0));//累计能量矩阵
	cv::Mat traceMat(image.rows,image.cols,CV_32F,cv::Scalar(0));//能量最小轨迹矩阵
	calculateEnergy(gradMag_mat,energyMat,traceMat); 

	//找出最小能量线
	cv::Mat minTrace(image.rows,1,CV_32F,cv::Scalar(0));//能量最小轨迹矩阵中的最小的一条的轨迹
	getMinEnergyTrace(energyMat,traceMat,minTrace);

	//显示最小能量线
	cv::Mat tmpImage(image.rows,image.cols,image.type());
	image.copyTo(tmpImage);
	for (int i = 0;i < image.rows;i++)
	{
		int k = minTrace.at<float>(i,0);
		tmpImage.at<cv::Vec3b>(i,k)[0] = 0;
		tmpImage.at<cv::Vec3b>(i,k)[1] = 0;
		tmpImage.at<cv::Vec3b>(i,k)[2] = 255;
	}
	cv::imshow("Image Show Window (缩小)",tmpImage);

	//删除一列
	cv::Mat image2(image.rows,image.cols-1,image.type());
	cv::Mat beDeletedLine(image.rows,1,CV_8UC3);//记录被删掉的那一列的值
	delOneCol(image,image2,minTrace,beDeletedLine);
	cv::imshow("Image Show Window",image2);

	image2.copyTo(outImage);
	minTrace.copyTo(outMinTrace);
	beDeletedLine.copyTo(outDeletedLine);
}
Ejemplo n.º 9
0
int main(int argc, char *argv[])
{
  double sq_distance_from_initial_pt;
  int i;

  // overhead

  setCommandLineParameters(argc, argv);
  verbose = getFlagParam("-verbose");
  getIntParam("-seed", &seed);
  if (getFlagParam("-randomize")) randomize();
  else initializeRandomNumberGenerator();

  getVectorParam("-box", &box_x, &box_y, &box_z);
  getDoubleParam("-verlet_cutoff", &verlet_cutoff);
  getDoubleParam("-sea_level", &sea_level);
  getDoubleParam("-test_diameter", &test_diameter);
  getDoubleParam("-test_epsilon", &test_epsilon);
  getIntParam("-n", &number_of_samples);

  if (getFlagParam("-usage"))
  {
    printf("\nusage:\t-box [ 10 10 10 ]\n");
    printf("      \t-verlet_cutoff [ 64.0 ]\n");
    printf("      \t-sea_level [ 347.0 ]\n");
    printf("      \t-test_diameter [ 1.0 ]\n");
    printf("      \t-test_epsilon [ 1.0 ]\n");
    printf("      \t-n [ 100 ]\n\n");
    exit(0);
  }

  x_increment=box_x/(0.0 + number_of_samples);
  y_increment=box_y/(0.0 + number_of_samples);
  z_increment=box_z/(0.0 + number_of_samples);

  readConfiguration();
  for (i=0; i<number_of_molecules; i++)
  {
    while (x[i] >= box_x) x[i] -= box_x;
    while (y[i] >= box_y) y[i] -= box_y;
    while (z[i] >= box_z) z[i] -= box_z;
    while (x[i] < 0) x[i] += box_x;
    while (y[i] < 0) y[i] += box_y;
    while (z[i] < 0) z[i] += box_z;
  }
  
  for (test_x=0; test_x < box_x; test_x += x_increment)
    for (test_y=0; test_y < box_y; test_y += y_increment)
      for (test_z=0; test_z < box_z; test_z += z_increment)
        if (calculateEnergy(test_diameter) < sea_level) printf("%lf\t%lf\t%lf\t%lf\n", test_x, test_y, test_z, test_diameter);

  return 0;
}
Ejemplo n.º 10
0
void expandTestParticle(Trajectory *p_traj)
{
  double slope;
  double step_size;
  double energy, old_energy;
  double e0, e1, r0, r1;

  double diameter = 0.0;

  // improved initial guess
  old_energy = calculateEnergy(p_traj, diameter);
  if (old_energy > 0) return;
  while (diameter += .1)
  {
    energy = calculateEnergy(p_traj, diameter);
    if (energy > old_energy) break;
    old_energy = energy;
  }

  while(1) // Newton's method
  {
    r0 = diameter - .001;
    r1 = diameter + .001;
    
    e0 = calculateEnergy(p_traj, r0);
    e1 = calculateEnergy(p_traj, r1);
    energy = calculateEnergy(p_traj, diameter);

    slope = (e1-e0)/(r1-r0);
    step_size = -energy/slope;

    diameter = diameter + step_size;

    if (step_size*step_size < .00000001) break;
  }

  // copy diameter to trajectory data
  p_traj->diameter = diameter;
}
Ejemplo n.º 11
0
/********************************* Simulation (constructor) *********************************/ 
Simulation::Simulation(double J, double sigmaBar, vector<double>* TList, int L, 
                       MTRand* randomGen, int numWarmUpSweeps, int sweepsPerMeas, 
                       int measPerBin, int numBins, const char* outputFileName)
{
  spinDim               = 2;
  maxZ                  = 4;
  this->J               = J;
  this->sigmaBar        = sigmaBar;
  this->TList           = TList;
  this->T               = TList->at(0);
  this->L               = L;
  this->N               = L*L;
  this->randomGen       = randomGen;
  this->numWarmUpSweeps = numWarmUpSweeps;
  this->sweepsPerMeas   = sweepsPerMeas;
  this->measPerBin      = measPerBin;
  this->numBins         = numBins;
  this->outputFileName  = outputFileName;
  
  spins = new VecND*[N+1];
  spins[N] = new VecND(spinDim,0);  //The (N+1)st spin is an effective neighbour for spins
                                    //on the lattice boundary. The value of this spin is zero
                                    //so that it does not affect values of observables.
  
  neighbours = new int*[N];
  for( int i=0; i<N; i++ )
  { neighbours[i] = new int[maxZ]; }
  crossProds = new int*[N];
  for( int i=0; i<N; i++ )
  { crossProds[i] = new int[maxZ]; }
  coordNums = new int[N];
  setUpNeighbours();
  
  randomizeLattice();
  
  calculateEnergy();
  mag = new VecND(spinDim,0);
  calculateMagnetization();
  
  /*inCluster = new bool[N];
  for( int i=0; i<N; i++ )
  { inCluster[i] = 0; }
  
  cluster  = new vector<int>;
  buffer   = new vector<int>;*/
}
Ejemplo n.º 12
0
generateTestPoint()
{
  test_x = test_x0 = rand() * rand_step * box_x;
  test_y = test_y0 = rand() * rand_step * box_y;
  test_z = test_z0 = rand() * rand_step * box_z;

  makeVerletList();

  while (rand() * rand_step > exp(-(calculateEnergy()/T))) 
  {
    test_x = test_x0 = rand() * rand_step * box_x;
    test_y = test_y0 = rand() * rand_step * box_y;
    test_z = test_z0 = rand() * rand_step * box_z;

    makeVerletList();
  }
}
Ejemplo n.º 13
0
generateTestPoint()
{
  test_x = test_x0 = rnd() * box_x;
  test_y = test_y0 = rnd() * box_y;
  test_z = test_z0 = rnd() * box_z;

  makeVerletList();

  while (rnd() > exp(-beta*calculateEnergy())) 
  {
    test_x = test_x0 = rnd() * box_x;
    test_y = test_y0 = rnd() * box_y;
    test_z = test_z0 = rnd() * box_z;

    makeVerletList();
  }
}
Ejemplo n.º 14
0
int main(int argc, char *argv[])
{
  double sq_distance_from_initial_pt; // 
  double n_steps_taken; // how many steps from initial insertion
  double dx, dy, dz, dd, dt, d; // distance deltas...
  double phi, theta; // used for choosing direction
  double x_step, y_step, z_step; // step size in that direction
  double mid_x, mid_y, mid_z, mid_t;
  double R_t;
  int t_bin;
  double time_elapsed=0.0;
  double collision_t;
  double kinetic_energy;
  double old_energy, new_energy;
  double velocity;
  double time_step;
  double D;
  int bisections;
  int i;
  double bisection_factor;
  double R_sq;

  setCommandLineParameters(argc, argv);
  verbose = getFlagParam("-verbose");
  getIntParam("-seed", &seed);
  if (getFlagParam("-randomize")) seed=time(NULL);
  srand(seed);
  if (getFlagParam("-usage")) 
  {
    printf("\nusage:  configuration in, list of path lengths  and times out\n\n");
    printf("        -box [ 6.0 6.0 6.0 ] (sigma)\n");
    printf("        -T [ 1.0 ]\n");
    printf("        -N [ 1024 ]\n");
    printf("        -step_size [ .050 ]\n");
    printf("        -target_time [ 100.0 ]\n");
    printf("        -bin_size [ 1 ]\n");
    printf("        -seed [ 123450 ]\n");
    printf("        -randomize\n\n");

    exit(0);
  }

  srand(seed);

  getVectorParam("-box", &box_x, &box_y, &box_z);
  getDoubleParam("-step_size", &step_size);
  getDoubleParam("-verlet_cutoff", &verlet_cutoff);
  getDoubleParam("-test_diameter", &test_diameter);
  getDoubleParam("-target_time", &target_time);
  target_time;
  getDoubleParam("-test_epsilon", &test_epsilon);
  getDoubleParam("-T", &T);
  getIntParam("-n", &number_of_samples);
  getIntParam("-N", &number_of_steps);
  getIntParam("-bin_size", &bin_size);
  time_series = getFlagParam("-time_series");

  readConfiguration();

  for (i=0; i<1000; i++)
  {
    //time_series_R_delta_t[i] = 0;
    time_series_R_sq_delta_t[i] = 0;
    time_series_delta_t[i] = 0;
  }

  // loop until time is up
  while (time_elapsed<target_time)
  {
    // pick a particle
    active_molecule = (rand_step*rand())*number_of_molecules;
fprintf(stderr, "active molecule:  %d\n", active_molecule);
    // additional selection criteria so all particles get to move until enough time elapses

    // pick a direction
    phi = 2*PI*rand()*rand_step;
    theta = PI*rand()*rand_step;
    x_step = step_size*cos(phi)*sin(theta); 
    y_step = step_size*sin(phi)*sin(theta);
    z_step = step_size*cos(theta);

    // pick a velocity
    kinetic_energy = -1.5*T*log(rand_step*rand()); 
    velocity = sqrt(2.0*kinetic_energy);
//fprintf(stderr, "v=%lf\n", velocity);
    collision_x = x[active_molecule];
    collision_y = y[active_molecule];
    collision_z = z[active_molecule];
    collision_t = t[active_molecule];
    bisection_factor=1.0;
    old_energy = calculateEnergy();

    // extend ray from collision point
    bisections=0; 
    while (bisections<=15)
    {
      x[active_molecule] += x_step;
      y[active_molecule] += y_step;
      z[active_molecule] += z_step;

      new_energy = calculateEnergy();

      if ((new_energy > (kinetic_energy)) && (new_energy >= old_energy))
      {
        // new_energy = old_energy;
        x[active_molecule]-=x_step;
        y[active_molecule]-=y_step;
        z[active_molecule]-=z_step;

        x_step*=.5;
        y_step*=.5;
        z_step*=.5;
        bisection_factor*=.5;
        bisections++;
      }

//fprintf(stderr, "%f\t%lf\t%lf\n", x[active_molecule], y[active_molecule], z[active_molecule]);
        
    } // end loop over bisections
    
    // got the new position

    mid_x = (x[active_molecule] + collision_x) * .5;
    mid_y = (y[active_molecule] + collision_y) * .5;
    mid_z = (z[active_molecule] + collision_z) * .5;

    dx = mid_x - collision_x;
    dy = mid_y - collision_y;
    dz = mid_z - collision_z;

    dt = sqrt(dx*dx + dy*dy + dz*dz)/velocity;

    // now get displacement from overall starting point
    dx = drift_x[active_molecule] + mid_x - x_0[active_molecule];
    dy = drift_y[active_molecule] + mid_y - y_0[active_molecule];
    dz = drift_z[active_molecule] + mid_z - z_0[active_molecule];
    R_sq = dx*dx + dy*dy + dz*dz;

    t_bin = floor((time_elapsed + .5*dt) + .5);

//  time_series_R_delta_t[t_bin] += R_t*dt;
    time_series_R_sq_delta_t[t_bin] += R_sq*dt;
    time_series_delta_t[t_bin]+= dt;

    t[active_molecule] += dt;

    x[active_molecule] = mid_x;
    y[active_molecule] = mid_y;
    z[active_molecule] = mid_z;

    // correct for periodic boundaries

    while (x[active_molecule] >= box_x) {x[active_molecule] -= box_x; drift_x[active_molecule] += box_x;}
    while (y[active_molecule] >= box_y) {y[active_molecule] -= box_y; drift_y[active_molecule] += box_y;}
    while (z[active_molecule] >= box_z) {z[active_molecule] -= box_z; drift_z[active_molecule] += box_z;}

    while (x[active_molecule] < box_x) {x[active_molecule] += box_x; drift_x[active_molecule] -= box_x;}
    while (y[active_molecule] < box_y) {y[active_molecule] += box_y; drift_y[active_molecule] -= box_y;}
    while (z[active_molecule] < box_z) {z[active_molecule] += box_z; drift_z[active_molecule] -= box_z;}

    time_elapsed=0;
    for (i=0; i<number_of_molecules; i++) time_elapsed += t[i];
    time_elapsed /= number_of_molecules;
fprintf(stderr,"time elapsed=%lf\n", time_elapsed);

  } // end loop until target_time 
  
  for (i=0; i*bin_size < time_elapsed; i++) printf("%d\t%lf\n", i*bin_size, time_series_R_sq_delta_t[i]/time_series_delta_t[i]);

  return 0;
}
Ejemplo n.º 15
0
int main(int argc, char *argv[])
{
  double sq_distance_from_initial_pt;
  double step_number;
  double dx, dy, dz;
  double phi, theta;
  double x_step, y_step, z_step;


  setCommandLineParameters(argc, argv);
  verbose = getFlagParam("-verbose");
  getIntParam("-seed", &seed);
  if (getFlagParam("-randomize")) randomize();
  else initializeRandomNumberGeneratorTo(seed);
  if (getFlagParam("-usage")) 
  {
    printf("\nusage:  configuration in, list of path lengths out\n\n");
    printf("        -box [ 6.0 6.0 6.0 ]\n");
    printf("        -test_diameter [ 1.0 ]\n");
    printf("        -test_epsilon [ 1.0 ]\n");
    printf("        -T [ 343.0 ]\n");
    printf("        -n [ 1 ]\n");
    printf("        -step_size [ .001 ]\n");
    printf("        -verlet_cutoff [ 100.0 ]\n");
    printf("        -seed [ 123450 ]\n");
    printf("        -randomize\n\n");

    exit(0);
  }

  srand(seed);

  getVectorParam("-box", &box_x, &box_y, &box_z);
  getDoubleParam("-step_size", &step_size);
  getDoubleParam("-verlet_cutoff", &verlet_cutoff);
  getDoubleParam("-test_diameter", &test_diameter);
  getDoubleParam("-test_epsilon", &test_epsilon);
  getDoubleParam("-T", &T);
  getIntParam("-n", &number_of_samples);

  readConfiguration();
  
  while (number_of_samples-- > 0)
  {
    generateTestPoint();
    drift_x=drift_y=drift_z=0;

    V printf("test point:  %lf, %lf, %lf\n", test_x, test_y, test_z);
    
    // pick a direction
    phi = 2*PI*rand()*rand_step;
    theta = PI*rand()*rand_step;
    x_step = step_size*cos(phi)*sin(theta); 
    y_step = step_size*sin(phi)*sin(theta);
    z_step = step_size*cos(theta);

    // extend ray from test point
    while (1)
    {
      test_x += x_step;
      test_y += y_step;
      test_z += z_step;

      dx=test_x - verlet_center_x;
      dy=test_y - verlet_center_y;
      dz=test_z - verlet_center_z;
      if (dx*dx + dy*dy + dz*dz > .01 * verlet_cutoff) makeVerletList();
      V printf("%lf, %lf, %lf:\t%lf\n", test_x, test_y, test_z, calculateEnergy());

      if (calculateEnergy() > (T * 1.5)) break;
    }
  
    dx = test_x - test_x0 + drift_x;
    dy = test_y - test_y0 + drift_y;
    dz = test_z - test_z0 + drift_z;

    printf("%lf\n", 2*sqrt(dx*dx + dy*dy + dz*dz));
  }

  return 0;
}
Ejemplo n.º 16
0
    void runTemperatureRound(double t_parameter) {
    
      AbstractAlgorithm::runTemperatureRound(t_parameter);
      
      if(start) {
        for(int i = 0; i < lattice->getN(); i++) {
          spins[i] = bool(gsl_rng_uniform_int(generator, 2));
        }

        energy  = calculateEnergy();
        spinSum = calculateSpinSum();
        start = false;
      }
    
      for(long i = 0; i < runCount; i++) {
      
        if(i > runCount - measureCount) {
          energyMeasurements[i - runCount + measureCount]                   = energy / lattice->getN();
          magnetisationMeasurements[i - runCount + measureCount]            = double(spinSum) / lattice->getN();
          absoluteMagnetisationMeasurements[i - runCount + measureCount]    = fabs(double(spinSum) / lattice->getN());
        }
        
        doSweep();
        
      }

      IsingEnergyAnalyzer *isingEnergyAnalyzer = new IsingEnergyAnalyzer(this, lattice);
      isingEnergyAnalyzer->analyze();
      averageEnergy = isingEnergyAnalyzer->getAverage();
      errorOfEnergy = isingEnergyAnalyzer->getError();
      autoCorrelationTimeOfEnergy = isingEnergyAnalyzer->getAutoCorrelationTime();
      delete isingEnergyAnalyzer;

      IsingHeatCapacityAnalyzer *isingHeatCapacityAnalyzer = new IsingHeatCapacityAnalyzer(this, lattice);
      isingHeatCapacityAnalyzer->analyze();
      averageHeatCapacity = isingHeatCapacityAnalyzer->getAverage();
      errorOfHeatCapacity = isingHeatCapacityAnalyzer->getError();
      autoCorrelationTimeOfHeatCapacity = isingHeatCapacityAnalyzer->getAutoCorrelationTime();
      delete isingHeatCapacityAnalyzer;

      IsingMagnetisationAnalyzer *isingMagnetisationAnalyzer = new IsingMagnetisationAnalyzer(this, lattice);
      isingMagnetisationAnalyzer->analyze();
      averageMagnetisation = isingMagnetisationAnalyzer->getAverage();
      errorOfMagnetisation = isingMagnetisationAnalyzer->getError();
      autoCorrelationTimeOfMagnetisation = isingMagnetisationAnalyzer->getAutoCorrelationTime();
      delete isingMagnetisationAnalyzer;

      IsingSusceptibilityAnalyzer *isingSusceptibilityAnalyzer = new IsingSusceptibilityAnalyzer(this, lattice);
      isingSusceptibilityAnalyzer->analyze();
      averageSusceptibility = isingSusceptibilityAnalyzer->getAverage();
      errorOfSusceptibility = isingSusceptibilityAnalyzer->getError();
      autoCorrelationTimeOfSusceptibility = isingSusceptibilityAnalyzer->getAutoCorrelationTime();
      delete isingSusceptibilityAnalyzer;

      IsingAbsoluteMagnetisationAnalyzer *isingAbsoluteMagnetisationAnalyzer = new IsingAbsoluteMagnetisationAnalyzer(this, lattice);
      isingAbsoluteMagnetisationAnalyzer->analyze();
      averageAbsoluteMagnetisation = isingAbsoluteMagnetisationAnalyzer->getAverage();
      errorOfAbsoluteMagnetisation = isingAbsoluteMagnetisationAnalyzer->getError();
      autoCorrelationTimeOfAbsoluteMagnetisation = isingAbsoluteMagnetisationAnalyzer->getAutoCorrelationTime();
      delete isingAbsoluteMagnetisationAnalyzer;

      IsingAbsoluteSusceptibilityAnalyzer *isingAbsoluteSusceptibilityAnalyzer = new IsingAbsoluteSusceptibilityAnalyzer(this, lattice);
      isingAbsoluteSusceptibilityAnalyzer->analyze();
      averageAbsoluteSusceptibility = isingAbsoluteSusceptibilityAnalyzer->getAverage();
      errorOfAbsoluteSusceptibility = isingAbsoluteSusceptibilityAnalyzer->getError();
      autoCorrelationTimeOfAbsoluteSusceptibility = isingAbsoluteSusceptibilityAnalyzer->getAutoCorrelationTime();
      delete isingAbsoluteSusceptibilityAnalyzer;
      
    };
Ejemplo n.º 17
0
int main(int argc, char *argv[])
{
  double sq_distance_from_initial_pt; // 
  double n_steps_taken; // how many steps from initial insertion
  double dx, dy, dz, dd, dt, d; // distance deltas...
  double phi, theta; // used for choosing direction
  double x_step, y_step, z_step; // step size in that direction
  double mid_x, mid_y, mid_z, mid_t;
  double R_t;
  int t_bin;
  double time_elapsed;
  double collision_t;
  double kinetic_energy;
  double old_energy, new_energy;
  double velocity;
  double time_step;
  double D;
  int bisections;
  int i;
  double intercollision_distance;
  double bisection_factor;
  double grad_x, grad_y, grad_z, grad;

  setCommandLineParameters(argc, argv);
  verbose = getFlagParam("-verbose");
  getIntParam("-seed", &seed);
  if (getFlagParam("-randomize")) seed=time(NULL);
  srand(seed);
  if (getFlagParam("-usage")) 
  {
    printf("\nusage:  configuration in, list of path lengths  and times out\n\n");
    printf("        -box [ 6.0 6.0 6.0 ] (Angstroms)\n");
    printf("        -T [ 1.0 ]\n");
    printf("        -n [ 1 ]\n");
    printf("        -N [ 1024 ]\n");
    printf("        -step_size [ .050 ]\n");
    printf("        -verlet_cutoff [ 16.0 ]\n");
    printf("        -target_time [ 100.0 ]\n");
    printf("        -bin_size [ 1 ]\n");
    printf("        -seed [ 123450 ]\n");
    printf("        -randomize\n\n");

    exit(0);
  }

  srand(seed);

  getVectorParam("-box", &box_x, &box_y, &box_z);
  getDoubleParam("-step_size", &step_size);
  getDoubleParam("-verlet_cutoff", &verlet_cutoff);
  getDoubleParam("-test_diameter", &test_diameter);
  getDoubleParam("-target_time", &target_time);
  target_time;
  getDoubleParam("-test_epsilon", &test_epsilon);
  getDoubleParam("-T", &T);
  getIntParam("-n", &number_of_samples);
  getIntParam("-N", &number_of_steps);
  getIntParam("-bin_size", &bin_size);
  time_series = getFlagParam("-time_series");

  readConfiguration();

  for (i=0; i<1000; i++)
  {
    time_series_R_delta_t[i] = 0;
    time_series_R_sq_delta_t[i] = 0;
    time_series_delta_t[i] = 0;
  }

  // loop over # of insertions
  while (number_of_samples-- > 0)
  {
    generateTestPoint();
    new_energy = old_energy = calculateEnergy();
    drift_x=drift_y=drift_z=0;
    time_elapsed=0;

    while (time_elapsed<target_time)
    {
      // pick a direction
      phi = 2*PI*rand()*rand_step;
      theta = PI*rand()*rand_step;
      x_step = step_size*cos(phi)*sin(theta); 
      y_step = step_size*sin(phi)*sin(theta);
      z_step = step_size*cos(theta);

      // pick a velocity
      // kinetic_energy = -1.5*log(rand_step*rand())*8.314*T; // in J/mol
      kinetic_energy = -1.5*T*log(rand_step*rand()); 
      velocity = sqrt(2.0*kinetic_energy);
//fprintf(stderr, "v=%lf\n", velocity);
      collision_x = test_x;
      collision_y = test_y;
      collision_z = test_z;
      collision_t = time_elapsed;
      intercollision_distance=0;
      bisection_factor=1.0;

      // extend ray from collision point
      for (bisections=0; bisections<=15; )
      {
        test_x += x_step;
        test_y += y_step;
        test_z += z_step;

        dx=test_x - verlet_center_x;
        dy=test_y - verlet_center_y;
        dz=test_z - verlet_center_z;

        if (dx*dx + dy*dy + dz*dz > .01 * verlet_cutoff) makeVerletList();

        old_energy = new_energy;
        new_energy = calculateEnergy();
        if ((new_energy > (kinetic_energy)) && (new_energy >= old_energy))
        {
          new_energy = old_energy;

          test_x-=x_step;
          test_y-=y_step;
          test_z-=z_step;

          x_step*=.5;
          y_step*=.5;
          z_step*=.5;
          bisection_factor*=.5;

          bisections++;
        }
        
        // figure out what time it is
        intercollision_distance+=step_size*bisection_factor;
        time_elapsed += step_size*bisection_factor/velocity;

        dx = test_x - test_x0 + drift_x;
        dy = test_y - test_y0 + drift_y;
        dz = test_z - test_z0 + drift_z;
        dd = dx*dx + dy*dy + dz*dz;

      } // end loop over bisections

//      if (time_series)
//      {
        mid_x = (test_x+collision_x) * .5;
        mid_y = (test_y+collision_y) * .5;
        mid_z = (test_z+collision_z) * .5;
        dx=mid_x-test_x0+drift_x;
        dy=mid_y-test_y0+drift_y;
        dz=mid_z-test_z0+drift_z;
        R_t = sqrt(dx*dx + dy*dy + dz*dz);
        dt = time_elapsed - collision_t;
        mid_t = collision_t + (dt * .5);
//fprintf(stderr, "mid_t=%lf\n", mid_t);

        t_bin = floor(mid_t/bin_size + .5);

        // t_bin = floor(mid_t + .5);

        time_series_R_delta_t[t_bin] += R_t*dt;
        time_series_R_sq_delta_t[t_bin] += R_t*R_t*dt;
        time_series_delta_t[t_bin]+= dt;
//      }

    } // end loop until target_time 
  
    // put the test particle back
    number_of_molecules++;

  } // end loop over all samples
 
  for (i=0; i*bin_size < time_elapsed; i++) printf("%d\t%lf\n", i*bin_size, time_series_R_sq_delta_t[i]/time_series_delta_t[i]);

  return 0;
}
Ejemplo n.º 18
0
/****************************************** runSim ******************************************/ 
void Simulation::runSim()
{
  unsigned int      TIndex;
  ofstream          outFile;
  double            currPsiSq;
  VecND*            currn;
  VecND*            currnSq;
  double            aveE, aveESq;
  double            aveDiamag;
  double            aveHelicityX, aveHelicityY;
  double            avePsiSq, avePsi4;
  double            aveSumPsiSq;
  //double            aveSF;
  VecND* aven   = new VecND(spinDim,0);
  VecND* avenSq = new VecND(spinDim,0);
  
  
  outFile.open(outputFileName);
  outFile.precision(20);
  
  //loop over all temperatures:
  for(TIndex=0; TIndex<(TList->size()); TIndex++)
  {
    //T = TMax - TIndex*(TMax-TMin)/( (double)max(1,(numTSteps-1)) );
    T = TList->at(TIndex);
    std::cout << "\n******** L = " << L << ", T = " << T << " (Temperature #" << (TIndex+1) << ") ********" << std::endl;
    
    //take out the following two lines if you want the system to use its previous state from 
    //the last temperature (i.e. cooling the system):
    randomizeLattice();
    
    //do warm-up sweeps:
    for( int i=0; i<numWarmUpSweeps; i++ )
    { sweep(); }
    
    for( int i=0; i<numBins; i++ )
    {
      aveE=0;
      aveESq=0;
      aveDiamag=0;
      aveHelicityX=0;
      aveHelicityY=0;
      avePsiSq=0;
      avePsi4=0;
      aveSumPsiSq=0;
      aven->clear();
      avenSq->clear();
      //aveSF = 0;
  
      for( int j=0; j<measPerBin; j++ )
      { 
        //perform one measurement:
        for( int k=0; k<sweepsPerMeas; k++ )
        { sweep(); }
        
        //put this section in to avoid rounding errors (rather than trusting the energy and
        //magnetization we have been updating ourselves):
        calculateEnergy();
        calculateMagnetization();
        
        currn = mag->getMultiple(1.0/N);
        currnSq = mag->getSqComponents();
        currnSq->multiply(1.0/(N*N));
        currPsiSq = currnSq->v_[0] + currnSq->v_[1];
        
        aveE         += energy/N;
        aveESq       += pow( (energy/N), 2);
        //aveSF      += getSF();
        aveDiamag    += getDiamag()/(1.0*T);
        aveHelicityX += getHelicityModulus(0);
        aveHelicityY += getHelicityModulus(1);
        avePsiSq     += currPsiSq;
        avePsi4      += pow(currPsiSq,2);
        aveSumPsiSq  += getSumPsiSq();
        aven->add(currn);
        avenSq->add(currnSq);
        
        if(currn!=NULL)
        { delete currn; }
        currn = NULL;
        
        if(currnSq!=NULL)
        { delete currnSq; }
        currnSq=NULL;
        
      } //j (measPerBin)
      //calculate average for the bin:
      aveE         = aveE/measPerBin;
      aveESq       = aveESq/measPerBin;
      aveDiamag    = aveDiamag/measPerBin;
      aveHelicityX = aveHelicityX/measPerBin;
      aveHelicityY = aveHelicityY/measPerBin;
      //aveSF      = aveSF/measPerBin;
      avePsiSq     = avePsiSq/measPerBin;
      avePsi4      = avePsi4/measPerBin;
      aveSumPsiSq  = aveSumPsiSq/measPerBin;
      aven->multiply(1.0/measPerBin);
      avenSq->multiply(1.0/measPerBin);
      
      outFile << L << '\t' << T << '\t' << (i+1) << '\t' << aveE << '\t' << aveESq << '\t'
              << aveDiamag << '\t' << aveHelicityX << '\t' << aveHelicityY << '\t'
              << avePsiSq << '\t' << avePsi4 << '\t' << aveSumPsiSq << '\t';
      for( uint j=0; j<spinDim; j++ )
      { outFile << aven->v_[j] << '\t'; }
      for( uint j=0; j<spinDim; j++ )
      { outFile << avenSq->v_[j] << '\t'; }
      outFile << std::endl;
      
      std::cout << (i+1) << " Bins Complete" << std::endl;
      //std::cout << "Diamag. = " << aveDiamag << "\n" << std::endl;
    } //i (bins)
  }  //closes T loop
  
  outFile.close();
}