예제 #1
0
파일: main.cpp 프로젝트: thodrek/sampler
int main(int argv, char** argc){
	// parse arguments
  dd::CmdParser cmd_parser = parse_input(argv, argc);

  // run gibbs sampler
  if(cmd_parser.app_name == "gibbs"){
    gibbs(cmd_parser);
  } else if (cmd_parser.app_name == "em") {
      em(cmd_parser);
  }

}
예제 #2
0
void SimulatedAnnealingInference::PerformInference() {
	// Initialize best solution
	unsigned int var_count =
		static_cast<unsigned int>(fg->Cardinalities().size());
	primal_best.resize(var_count);
	primal_best_energy = std::numeric_limits<double>::infinity();

	// Initialize Gibbs sampler
	GibbsSampler gibbs(fg);

	// Calculate exponential multiplier alpha such that T(sa_steps)=Tfinal.
	double alpha = std::exp(std::log(Tfinal / T0) /
		static_cast<double>(sa_steps));
	gibbs.SetInverseTemperature(1.0 / T0);
	gibbs.Sweep(1);

	// Perform annealing
	for (unsigned int k = 1; k <= sa_steps; ++k) {
		// Logarithmic schedule (Geman and Geman)
		// temperature = anneal_C / std::log(1.0 + static_cast<double>(k));

		// Exponential schedule
		double temperature = T0 * std::pow(alpha, static_cast<double>(k));
		gibbs.SetInverseTemperature(1.0 / temperature);
		double cur_energy = fg->EvaluateEnergy(gibbs.State());
		double energy_delta;
		for (unsigned int vi = 0; vi < var_count; ++vi) {
			unsigned int new_state = gibbs.SampleSite(vi, energy_delta);
			gibbs.SetState(vi, new_state);
			cur_energy += energy_delta;
			if (cur_energy < primal_best_energy) {
				// Re-evaluate for numerical reasons
				cur_energy = fg->EvaluateEnergy(gibbs.State());
				if (cur_energy < primal_best_energy) {
					primal_best_energy = cur_energy;
					std::copy(gibbs.State().begin(), gibbs.State().end(),
						primal_best.begin());
				}
			}
		}

	}
}
int main() {
  const double HBC = Constants::HBCFmMeV;
  const double PI = Constants::Pi;
  
	//std::vector<double> Ska35S2009{-172.485, 172.087, -1767.71, 0.282732, 
  //    12899.2, 0.413266, 0.35};
  double Tmin = 1.e-2;
  double Tmax = 2.e2;
  EOSSkyrme eos = EOSSkyrme::FromErmalSkyrme(ErmalSkyrmeParameters::Ska35S2009);
  EOSSingleNucleus eosSN(eos, false, Tmin, Tmax);
  GibbsPhaseConstruct gibbs(eos, false, Tmin, Tmax);
  EOSElectron eosEl; 
   
  // Read in pre-calculated EoS data 
  std::ifstream ifs("eos_data.arx");
  if (ifs) {
    boost::archive::binary_iarchive ia(ifs); 
    ia >> gibbs;
    ifs.close();
  } else {
예제 #4
0
파일: gibbs.cpp 프로젝트: thodrek/sampler
void gibbs(dd::CmdParser & cmd_parser){

  // number of NUMA nodes
  int n_numa_node = numa_max_node() + 1;
  // number of max threads per NUMA node
  int n_thread_per_numa = (sysconf(_SC_NPROCESSORS_CONF))/(n_numa_node);

  // get command line arguments
  std::string fg_file = cmd_parser.fg_file->getValue();

  std::string weight_file = cmd_parser.weight_file->getValue();
  std::string variable_file = cmd_parser.variable_file->getValue();
  std::string factor_file = cmd_parser.factor_file->getValue();
  std::string edge_file = cmd_parser.edge_file->getValue();
  std::string meta_file = cmd_parser.meta_file->getValue();

  std::string output_folder = cmd_parser.output_folder->getValue();

  int n_learning_epoch = cmd_parser.n_learning_epoch->getValue();
  int n_samples_per_learning_epoch = cmd_parser.n_samples_per_learning_epoch->getValue();
  int n_inference_epoch = cmd_parser.n_inference_epoch->getValue();

  double stepsize = cmd_parser.stepsize->getValue();
  double stepsize2 = cmd_parser.stepsize2->getValue();
  // hack to support two parameters to specify step size
  if (stepsize == 0.01) stepsize = stepsize2;
  double decay = cmd_parser.decay->getValue();

  int n_datacopy = cmd_parser.n_datacopy->getValue();
  double reg_param = cmd_parser.reg_param->getValue();
  double reg1_param = cmd_parser.reg1_param->getValue();
  bool is_quiet = cmd_parser.quiet->getValue();
  bool sample_evidence = cmd_parser.sample_evidence->getValue();
  int burn_in = cmd_parser.burn_in->getValue();
  bool learn_non_evidence = cmd_parser.learn_non_evidence->getValue();

  Meta meta = read_meta(fg_file); 

  if (is_quiet) {
    std::cout << "Running in quiet mode..." << std::endl;
  } else {
    std::cout << std::endl;
    std::cout << "#################MACHINE CONFIG#################" << std::endl;
    std::cout << "# # NUMA Node        : " << n_numa_node << std::endl;
    std::cout << "# # Thread/NUMA Node : " << n_thread_per_numa << std::endl;
    std::cout << "################################################" << std::endl;
    std::cout << std::endl;
    std::cout << "#################GIBBS SAMPLING#################" << std::endl;
    std::cout << "# fg_file            : " << fg_file << std::endl;
    std::cout << "# edge_file          : " << edge_file << std::endl;
    std::cout << "# weight_file        : " << weight_file << std::endl;
    std::cout << "# variable_file      : " << variable_file << std::endl;
    std::cout << "# factor_file        : " << factor_file << std::endl;
    std::cout << "# meta_file          : " << meta_file << std::endl;
    std::cout << "# output_folder      : " << output_folder << std::endl;
    std::cout << "# n_learning_epoch   : " << n_learning_epoch << std::endl;
    std::cout << "# n_samples/l. epoch : " << n_samples_per_learning_epoch << std::endl;
    std::cout << "# n_inference_epoch  : " << n_inference_epoch << std::endl;
    std::cout << "# stepsize           : " << stepsize << std::endl;
    std::cout << "# decay              : " << decay << std::endl;
    std::cout << "# regularization     : " << reg_param << std::endl;
    std::cout << "# l1 regularization     : " << reg1_param << std::endl;
    std::cout << "################################################" << std::endl;
    std::cout << "# IGNORE -s (n_samples/l. epoch). ALWAYS -s 1. #" << std::endl;
    std::cout << "# IGNORE -t (threads). ALWAYS USE ALL THREADS. #" << std::endl;
    std::cout << "################################################" << std::endl;


    std::cout << "# nvar               : " << meta.num_variables << std::endl;
    std::cout << "# nfac               : " << meta.num_factors << std::endl;
    std::cout << "# nweight            : " << meta.num_weights << std::endl;
    std::cout << "# nedge              : " << meta.num_edges << std::endl;
    std::cout << "################################################" << std::endl;
  }

  // run on NUMA node 0
  numa_run_on_node(0);
  numa_set_localalloc();

  // load factor graph
  dd::FactorGraph fg(meta.num_variables, meta.num_factors, meta.num_weights, meta.num_edges);
  fg.load(cmd_parser, is_quiet);
  dd::GibbsSampling gibbs(&fg, &cmd_parser, n_datacopy, sample_evidence, burn_in, learn_non_evidence);

  // number of learning epochs
  // the factor graph is copied on each NUMA node, so the total epochs =
  // epochs specified / number of NUMA nodes
  int numa_aware_n_learning_epoch = (int)(n_learning_epoch/n_numa_node) + 
                            (n_learning_epoch%n_numa_node==0?0:1);

  // learning
  /*gibbs.learn(numa_aware_n_learning_epoch, n_samples_per_learning_epoch,
    stepsize, decay, reg_param, reg1_param, meta_file, is_quiet);*/
  gibbs.learn(numa_aware_n_learning_epoch, n_samples_per_learning_epoch,
              stepsize, decay, reg_param, reg1_param, is_quiet);

  // dump weights
  gibbs.dump_weights(is_quiet);

  // number of inference epochs
  int numa_aware_n_epoch = (int)(n_inference_epoch/n_numa_node) + 
                            (n_inference_epoch%n_numa_node==0?0:1);

  // inference
  gibbs.inference(numa_aware_n_epoch, is_quiet);
  gibbs.aggregate_results_and_dump(is_quiet);


  // print weights from inference result
  for(long t=0;t<fg.n_weight;t++) {
      std::cout<<fg.infrs->weight_values[t]<<std::endl;
  }

  // print weights from factor graph
  std::cout<<"PRINTING WEIGHTS FROM WEIGHT VARIABLE"<<std::endl;
  for(long t=0;t<fg.n_weight;t++) {
      std::cout<<fg.weights[t].weight<<std::endl;
  }
}
예제 #5
0
파일: gibbs.cpp 프로젝트: thodrek/sampler
void em(dd::CmdParser & cmd_parser){

  // number of NUMA nodes
  int n_numa_node = numa_max_node() + 1;
  // number of max threads per NUMA node
  int n_thread_per_numa = (sysconf(_SC_NPROCESSORS_CONF))/(n_numa_node);

  // get command line arguments
  std::string fg_file = cmd_parser.fg_file->getValue();

  std::string weight_file = cmd_parser.weight_file->getValue();
  std::string variable_file = cmd_parser.variable_file->getValue();
  std::string factor_file = cmd_parser.factor_file->getValue();
  std::string edge_file = cmd_parser.edge_file->getValue();
  std::string meta_file = cmd_parser.meta_file->getValue();

  std::string output_folder = cmd_parser.output_folder->getValue();

  int n_learning_epoch = cmd_parser.n_learning_epoch->getValue();
  int n_samples_per_learning_epoch = cmd_parser.n_samples_per_learning_epoch->getValue();
  int n_inference_epoch = cmd_parser.n_inference_epoch->getValue();

  double stepsize = cmd_parser.stepsize->getValue();
  double stepsize2 = cmd_parser.stepsize2->getValue();
  // hack to support two parameters to specify step size
  if (stepsize == 0.01) stepsize = stepsize2;
  double decay = cmd_parser.decay->getValue();

  int n_datacopy = cmd_parser.n_datacopy->getValue();
  double reg_param = cmd_parser.reg_param->getValue();
  double reg1_param = cmd_parser.reg1_param->getValue();
  bool is_quiet = cmd_parser.quiet->getValue();
  bool check_convergence = cmd_parser.check_convergence->getValue();
  bool sample_evidence = cmd_parser.sample_evidence->getValue();
  int burn_in = cmd_parser.burn_in->getValue();
  int n_iter = cmd_parser.n_iter->getValue();
  int wl_conv = cmd_parser.wl_conv->getValue();
  int delta = cmd_parser.delta->getValue();
  bool learn_non_evidence = cmd_parser.learn_non_evidence->getValue();

  Meta meta = read_meta(fg_file);

  if (is_quiet) {
    std::cout << "Running in quiet mode..." << std::endl;
  } else {
    std::cout << std::endl;
    std::cout << "#################MACHINE CONFIG#################" << std::endl;
    std::cout << "# # NUMA Node        : " << n_numa_node << std::endl;
    std::cout << "# # Thread/NUMA Node : " << n_thread_per_numa << std::endl;
    std::cout << "################################################" << std::endl;
    std::cout << std::endl;
    std::cout << "#################GIBBS SAMPLING#################" << std::endl;
    std::cout << "# fg_file            : " << fg_file << std::endl;
    std::cout << "# edge_file          : " << edge_file << std::endl;
    std::cout << "# weight_file        : " << weight_file << std::endl;
    std::cout << "# variable_file      : " << variable_file << std::endl;
    std::cout << "# factor_file        : " << factor_file << std::endl;
    std::cout << "# meta_file          : " << meta_file << std::endl;
    std::cout << "# output_folder      : " << output_folder << std::endl;
    std::cout << "# n_learning_epoch   : " << n_learning_epoch << std::endl;
    std::cout << "# n_samples/l. epoch : " << n_samples_per_learning_epoch << std::endl;
    std::cout << "# n_inference_epoch  : " << n_inference_epoch << std::endl;
    std::cout << "# stepsize           : " << stepsize << std::endl;
    std::cout << "# decay              : " << decay << std::endl;
    std::cout << "# regularization     : " << reg_param << std::endl;
    std::cout << "# l1 regularization     : " << reg1_param << std::endl;
    std::cout << "################################################" << std::endl;
    std::cout << "# IGNORE -s (n_samples/l. epoch). ALWAYS -s 1. #" << std::endl;
    std::cout << "# IGNORE -t (threads). ALWAYS USE ALL THREADS. #" << std::endl;
    std::cout << "################################################" << std::endl;


    std::cout << "# nvar               : " << meta.num_variables << std::endl;
    std::cout << "# nfac               : " << meta.num_factors << std::endl;
    std::cout << "# nweight            : " << meta.num_weights << std::endl;
    std::cout << "# nedge              : " << meta.num_edges << std::endl;
    std::cout << "################################################" << std::endl;
  }

  // run on NUMA node 0
  numa_run_on_node(0);
  numa_set_localalloc();

  // load factor graph
  dd::FactorGraph fg(meta.num_variables, meta.num_factors, meta.num_weights, meta.num_edges);
  fg.load(cmd_parser, is_quiet);
  dd::GibbsSampling gibbs(&fg, &cmd_parser, n_datacopy, sample_evidence, burn_in, learn_non_evidence);

  // Initialize EM instance
  dd::ExpMax expMax(&fg, &gibbs, wl_conv, delta, check_convergence);

  // number of inference epochs
  int numa_aware_n_epoch;
  int numa_aware_n_learning_epoch;

  // EM init -- run Maximzation (semi-supervised learning)

  // Maximization step
  numa_aware_n_learning_epoch = (int)(n_learning_epoch/n_numa_node) +
                                (n_learning_epoch%n_numa_node==0?0:1);
  expMax.maximization(numa_aware_n_learning_epoch, n_samples_per_learning_epoch,
                      stepsize, decay, reg_param, reg1_param, is_quiet);
  /*expMax.maximization(numa_aware_n_learning_epoch, n_samples_per_learning_epoch,
                      stepsize, decay, reg_param, reg1_param, meta_file, is_quiet);*/

  while (!expMax.hasConverged && n_iter > 0) {

    // Expectation step
    numa_aware_n_epoch = (int)(n_inference_epoch/n_numa_node) +
                         (n_inference_epoch%n_numa_node==0?0:1);
    expMax.expectation(numa_aware_n_epoch,is_quiet);


    // Maximization step
    numa_aware_n_learning_epoch = (int)(n_learning_epoch/n_numa_node) +
                                  (n_learning_epoch%n_numa_node==0?0:1);
    /*expMax.maximization(numa_aware_n_learning_epoch, n_samples_per_learning_epoch,
                        stepsize, decay, reg_param, reg1_param, meta_file, is_quiet);*/
    expMax.maximization(numa_aware_n_learning_epoch, n_samples_per_learning_epoch,
                        stepsize, decay, reg_param, reg1_param, is_quiet);

    //Decrement iteration counter
    n_iter--;
  }

  expMax.dump_weights(is_quiet);
  expMax.aggregate_results_and_dump(is_quiet);


}
int main() {
  double HBC = Constants::HBCFmMeV;
  
  //EOSSkyrme eos;
	//std::vector<double> Ska35S2009{-172.485, 172.087, -1767.71, 0.282732, 
  //    12899.2, 0.413266, 0.35};
  EOSSkyrme eos = EOSSkyrme::FromErmalSkyrme(ErmalSkyrmeParameters::Ska35S2009);
  GibbsPhaseConstruct gibbs(eos, false);
  
  // Calculat self bound liquid densities
  std::ofstream selfBoundFile; 
  selfBoundFile.open("self_bound.out");
  selfBoundFile << "# [1] Nb " << std::endl;
  selfBoundFile << "# [2] T (MeV) " << std::endl;
  selfBoundFile << "# [3] Ye " << std::endl;
  selfBoundFile << "# [4] P " << std::endl;
  selfBoundFile << "# [5] Mun " << std::endl;
  selfBoundFile << "# [6] Mup " << std::endl;
  selfBoundFile << "# [7] Nn (low density) " << std::endl;
  selfBoundFile << "# [8] Np (low density) " << std::endl;
  selfBoundFile << "# [9] P (low density) " << std::endl;
  
  std::ofstream outFile; 
  outFile.open("gibbs_boundary.out");
  outFile << "#[1] Nn_1 (fm^-3)" << std::endl; 
  outFile << "#[2] Nn_2 (fm^-3)" << std::endl; 
  outFile << "#[3] Np_1 (fm^-3)" << std::endl; 
  outFile << "#[4] Np_2 (fm^-3)" << std::endl; 
  outFile << "#[5] P (MeV fm^-3)" << std::endl; 
  outFile << "#[6] Mun (MeV fm^-3)" << std::endl; 
  outFile << "#[7] Mup (MeV fm^-3)" << std::endl; 
  outFile << "#[8] T (MeV)" << std::endl; 
  
  double TStart = 0.1/HBC; 
  double TEnd = 0.01/HBC;
  auto phaseBoundFull = gibbs.FindFixedTPhaseBoundary(TStart);
  std::cout << phaseBoundFull.size() << std::endl;
   
  for (double lT = log10(TStart); lT>=log10(TEnd); lT -= 1.0) {
    double T = pow(10.0, lT);
    std::cout << T * HBC << " "; 
    
    //auto selfBound = gibbs.SelfBoundPoints(T);  
    //for (auto &ptpair : selfBound) {
    //  auto pt = ptpair.second;
    //  selfBoundFile << pt.Nb() << " " << pt.T()*HBC << " " << pt.Ye() << " "  
    //      << pt.P() << " " << pt.Mun() << " " << pt.Mup() << " "; 
    //  auto eosPts = 
    //      eos.FromMuAndT(EOSData::InputFromTMunMup(pt.T(), pt.Mun(), pt.Mup()));
    //  if (eosPts.size()>0) {
    //    selfBoundFile << eosPts[0].Np() << " " << eosPts[0].Nn() << " " 
    //        << eosPts[0].P(); 
    //  }
    //  selfBoundFile << std::endl;
    //} 
    //selfBoundFile << std::endl; 
   
    // Calculate phase boundaries
    auto phaseBound = phaseBoundFull; 
    if (T < TStart)  
      phaseBound = gibbs.FindFixedTPhaseBoundary(T, phaseBoundFull); 
    
    std::cout << phaseBound.size() << std::endl; 
    if (phaseBound.size() > 0) {
      // Write out the phase boundary
      for (auto &a : phaseBound) {
        outFile << (a.first).Nn() << " "; 
        outFile << (a.second).Nn() << " "; 
        outFile << (a.first).Np() << " "; 
        outFile << (a.second).Np() << " ";
        outFile << (a.first).P()*HBC << " ";
        outFile << (a.first).Mun()*HBC << " ";
        outFile << (a.first).Mup()*HBC << " ";
        outFile << (a.first).T()*HBC << std::endl;
      }
      outFile << std::endl; 
    } 
  }  
   
  selfBoundFile.close();
  outFile.close(); 
  return 0;
}
int main() 
{
  struct stat buffer;   
  double HBC = Constants::HBCFmMeV;
  std:: array<std::string,5> Skyrmenames09 = {"Ska35s2009.xml","Ska25s2009.xml","SKT109.xml","SKT209.xml","SKT309.xml"};
  std:: array<std::string,5> Skyrmenames1 = {"Ska35s201.xml","Ska25s201.xml","SKT11.xml","SKT21.xml","SKT31.xml"};
  std:: string eos_dataName_ermal("eos_data_"),eos_dataName_saturation("eos_data_sat_"), eos_dataName; 
  for (int counter = 0; counter < 5; counter++)
  {
	eos_dataName=eos_dataName_ermal+Skyrmenames09[counter];
	if((stat (eos_dataName.c_str(), &buffer) != 0))
	{
			EOSSkyrme eos = EOSSkyrme::FromErmalSkyrme(ErmalSkyrmeParameters::ErmalAllSkyrme09[counter]);
			EOSSingleNucleus gibbs(eos);
			std::ofstream ofs(eos_dataName.c_str()); 
			boost::archive::text_oarchive oa(ofs); 
			oa << gibbs; 
			ofs.close();
	}
	eos_dataName=eos_dataName_ermal+Skyrmenames1[counter];
	if((stat (eos_dataName.c_str(), &buffer) != 0))
	{
			EOSSkyrme eos = EOSSkyrme::FromErmalSkyrme(ErmalSkyrmeParameters::ErmalAllSkyrme1[counter]);
			EOSSingleNucleus gibbs(eos);
			std::ofstream ofs(eos_dataName.c_str()); 
			boost::archive::text_oarchive oa(ofs); 
			oa << gibbs; 
			ofs.close();
	}
	eos_dataName=eos_dataName_saturation+Skyrmenames09[counter];
	if((stat (eos_dataName.c_str(), &buffer) != 0))
	{
			EOSSkyrme eos = EOSSkyrme::FromSaturation(SaturationSkyrmeParameters::SaturationSkyrme09[counter]);
			EOSSingleNucleus gibbs(eos);
			std::ofstream ofs(eos_dataName.c_str()); 
			boost::archive::text_oarchive oa(ofs); 
			oa << gibbs; 
			ofs.close();
	}
	eos_dataName=eos_dataName_saturation+Skyrmenames1[counter];
	if((stat (eos_dataName.c_str(), &buffer) != 0))
	{
			EOSSkyrme eos = EOSSkyrme::FromSaturation(SaturationSkyrmeParameters::SaturationSkyrme1[counter]);
			EOSSingleNucleus gibbs(eos);
			std::ofstream ofs(eos_dataName.c_str()); 
			boost::archive::text_oarchive oa(ofs); 
			oa << gibbs; 
			ofs.close();
	}
  }
  //GibbsPhaseConstruct reloadGibbs(eos, false); 
  //
  //std::ifstream ifs("eos_data.xml");
  //boost::archive::text_iarchive ia(ifs); 
  //ia >> reloadGibbs;
  //ifs.close();
  
   
   
  return 0;
}