示例#1
0
void ARingTower::text_out(buffer &o) const
{
  o << "Tower[ZZ/" << characteristic() << "[";
  for (size_t i = 0; i < n_vars() - 1; i++) o << varNames()[i] << ",";
  if (n_vars() > 0) o << varNames()[n_vars() - 1];
  o << "]]";
  extensions_text_out(o);
}
示例#2
0
bool SchurRing::initialize_schur()
{
  _SMtab.initialize(n_vars());
  _SMfilled.initialize(n_vars());
  _SMcurrent = 0;
  _SMfinalwt = 0;
  _SMresult = 0;

  _SMtab.p = newarray_atomic_clear(int,nvars_+1);
  return true;
}
示例#3
0
void RBEIMConstruction::init_data()
{
  // set the coupling matrix to be diagonal
  _coupling_matrix.resize(n_vars());

  // resize zeroed the matrix; we just need to set diagonal entries
  for(unsigned int var=0; var<n_vars(); var++)
    _coupling_matrix(var,var) = 1;

  this->get_dof_map()._dof_coupling = &_coupling_matrix;

  Parent::init_data();
}
示例#4
0
void RBEIMConstruction::init_data()
{
  // set the coupling matrix to be diagonal
  _coupling_matrix.resize(n_vars());
  for(unsigned int var1=0; var1<n_vars(); var1++)
    for(unsigned int var2=0; var2<n_vars(); var2++)
    {
      unsigned char value = (var1==var2) ? 1 : 0;
      _coupling_matrix(var1,var2) = value;
    }

  this->get_dof_map()._dof_coupling = &_coupling_matrix;

  Parent::init_data();
}
示例#5
0
文件: monoid.cpp 项目: BertiniM2/M2
std::vector<int> Monoid::getFirstWeightVector() const
{
  std::vector<int> result;

  // grab the first weight vector
  if (getMonomialOrdering()->len > 0 and
      getMonomialOrdering()->array[0]->type == MO_WEIGHTS)
    {
      int i;
      result.reserve(n_vars());
      const int *wts = getMonomialOrdering()->array[0]->wts;
      for (i = 0; i < getMonomialOrdering()->array[0]->nvars; i++)
        result.push_back(wts[i]);
      for (; i < n_vars(); i++) result.push_back(0);
    }
  return result;
}
示例#6
0
void RBEIMConstruction::init_context(FEMContext &c)
{
  // default implementation of init_context
  // for compute_best_fit
  for(unsigned int var=0; var<n_vars(); var++)
  {
    c.element_fe_var[var]->get_JxW();
    c.element_fe_var[var]->get_phi();
    c.element_fe_var[var]->get_xyz();
  }
}
示例#7
0
void RBEIMConstruction::init_context(FEMContext &c)
{
  // default implementation of init_context
  // for compute_best_fit
  for(unsigned int var=0; var<n_vars(); var++)
    {
      FEBase* elem_fe = NULL;
      c.get_element_fe( var, elem_fe );
      elem_fe->get_JxW();
      elem_fe->get_phi();
      elem_fe->get_xyz();
    }
}
示例#8
0
Real RBEIMConstruction::truth_solve(int plot_solution)
{
  START_LOG("truth_solve()", "RBEIMConstruction");

//  matrix should have been set to inner_product_matrix during initialization
//  if(!single_matrix_mode)
//  {
//    matrix->zero();
//    matrix->add(1., *inner_product_matrix);
//  }
//  else
//  {
//    assemble_inner_product_matrix(matrix);
//  }

  int training_parameters_found_index = -1;
  if( _parametrized_functions_in_training_set_initialized )
  {
    // Check if parameters are in the training set. If so, we can just load the
    // solution from _parametrized_functions_in_training_set

    for(unsigned int i=0; i<get_n_training_samples(); i++)
    {
      if(get_parameters() == get_params_from_training_set(i))
      {
        training_parameters_found_index = i;
        break;
      }
    }
  }

  // If the parameters are in the training set, just copy the solution vector
  if(training_parameters_found_index >= 0)
  {
    *solution = *_parametrized_functions_in_training_set[training_parameters_found_index];
    update(); // put the solution into current_local_solution as well
  }
  // Otherwise, we have to compute the projection
  else
  {
    RBEIMEvaluation& eim_eval = libmesh_cast_ref<RBEIMEvaluation&>(get_rb_evaluation());
    eim_eval.set_parameters( get_parameters() );

    // Compute truth representation via projection
    const MeshBase& mesh = this->get_mesh();

    AutoPtr<FEMContext> c = this->build_context();
    FEMContext &context  = libmesh_cast_ref<FEMContext&>(*c);

    this->init_context(context);

    rhs->zero();

    MeshBase::const_element_iterator       el     = mesh.active_local_elements_begin();
    const MeshBase::const_element_iterator end_el = mesh.active_local_elements_end();

    for ( ; el != end_el; ++el)
    {
      context.pre_fe_reinit(*this, *el);
      context.elem_fe_reinit();

      for(unsigned int var=0; var<n_vars(); var++)
      {
        const std::vector<Real> &JxW =
          context.element_fe_var[var]->get_JxW();

        const std::vector<std::vector<Real> >& phi =
          context.element_fe_var[var]->get_phi();

        const std::vector<Point> &xyz =
          context.element_fe_var[var]->get_xyz();

        unsigned int n_qpoints = context.element_qrule->n_points();
        unsigned int n_var_dofs = libmesh_cast_int<unsigned int>
	  (context.dof_indices_var[var].size());

        DenseSubVector<Number>& subresidual_var = *context.elem_subresiduals[var];

        for(unsigned int qp=0; qp<n_qpoints; qp++)
          for(unsigned int i=0; i != n_var_dofs; i++)
            subresidual_var(i) += JxW[qp] * eim_eval.evaluate_parametrized_function(var, xyz[qp]) * phi[i][qp];
      }

      // Apply constraints, e.g. periodic constraints
      this->get_dof_map().constrain_element_vector(context.get_elem_residual(), context.dof_indices);

      // Add element vector to global vector
      rhs->add_vector(context.get_elem_residual(), context.dof_indices);
    }

    // Solve to find the best fit, then solution stores the truth representation
    // of the function to be approximated
    solve();

    // Make sure we didn't max out the number of iterations
    if( (this->n_linear_iterations() >=
         this->get_equation_systems().parameters.get<unsigned int>("linear solver maximum iterations")) &&
        (this->final_linear_residual() >
         this->get_equation_systems().parameters.get<Real>("linear solver tolerance")) )
    {
        libMesh::out << "Warning: Linear solver may not have converged! Final linear residual = "
                     << this->final_linear_residual() << ", number of iterations = "
                     << this->n_linear_iterations() << std::endl << std::endl;
  //     libmesh_error();
    }

    if(reuse_preconditioner)
    {
      // After we've done a solve we can now reuse the preconditioner
      // because the matrix is not changing
      linear_solver->reuse_preconditioner(true);
    }
  }

  if(plot_solution > 0)
  {
#ifdef LIBMESH_HAVE_EXODUS_API
    ExodusII_IO(get_mesh()).write_equation_systems ("truth.e",
                                                    this->get_equation_systems());
#endif
  }

  STOP_LOG("truth_solve()", "RBEIMConstruction");

  return 0.;
}
示例#9
0
void RBEIMConstruction::enrich_RB_space()
{
  START_LOG("enrich_RB_space()", "RBEIMConstruction");

  // put solution in _ghosted_meshfunction_vector so we can access it from the mesh function
  // this allows us to compute EIM_rhs appropriately
  solution->localize(*_ghosted_meshfunction_vector, this->get_dof_map().get_send_list());

  RBEIMEvaluation& eim_eval = libmesh_cast_ref<RBEIMEvaluation&>(get_rb_evaluation());

  // If we have at least one basis function we need to use
  // rb_solve to find the EIM interpolation error, otherwise just use solution as is
  if(get_rb_evaluation().get_n_basis_functions() > 0)
  {
    // get the right-hand side vector for the EIM approximation
    // by sampling the parametrized function (stored in solution)
    // at the interpolation points
    unsigned int RB_size = get_rb_evaluation().get_n_basis_functions();
    DenseVector<Number> EIM_rhs(RB_size);
    for(unsigned int i=0; i<RB_size; i++)
    {
      EIM_rhs(i) = evaluate_mesh_function( eim_eval.interpolation_points_var[i],
                                           eim_eval.interpolation_points[i] );
    }

    eim_eval.set_parameters( get_parameters() );
    eim_eval.rb_solve(EIM_rhs);

    // Load the "EIM residual" into solution by subtracting
    // the EIM approximation
    for(unsigned int i=0; i<get_rb_evaluation().get_n_basis_functions(); i++)
    {
      solution->add(-eim_eval.RB_solution(i), get_rb_evaluation().get_basis_function(i));
    }
  }

  // need to update since context uses current_local_solution
  update();

  // Find the quadrature point at which solution (which now stores
  // the "EIM residual") has maximum absolute value
  // by looping over the mesh
  Point optimal_point;
  Number optimal_value = 0.;
  unsigned int optimal_var;

  // Compute truth representation via projection
  const MeshBase& mesh = this->get_mesh();

  AutoPtr<FEMContext> c = this->build_context();
  FEMContext &context  = libmesh_cast_ref<FEMContext&>(*c);

  this->init_context(context);

  MeshBase::const_element_iterator       el     = mesh.active_local_elements_begin();
  const MeshBase::const_element_iterator end_el = mesh.active_local_elements_end();

  for ( ; el != end_el; ++el)
  {
    context.pre_fe_reinit(*this, *el);
    context.elem_fe_reinit();

    for(unsigned int var=0; var<n_vars(); var++)
    {
      unsigned int n_qpoints = context.element_qrule->n_points();

      for(unsigned int qp=0; qp<n_qpoints; qp++)
      {
        Number value = context.interior_value(var, qp);

        if( std::abs(value) > std::abs(optimal_value) )
        {
          optimal_value = value;
          optimal_point = context.element_fe_var[var]->get_xyz()[qp];
          optimal_var = var;
        }

      }
    }
  }

  Real global_abs_value = std::abs(optimal_value);
  unsigned int proc_ID_index;
  this->comm().maxloc(global_abs_value, proc_ID_index);

  // Broadcast the optimal point from proc_ID_index
  this->comm().broadcast(optimal_point, proc_ID_index);

  // Also broadcast the corresponding optimal_var and optimal_value
  this->comm().broadcast(optimal_var, proc_ID_index);
  this->comm().broadcast(optimal_value, proc_ID_index);

  // Scale the solution
  solution->scale(1./optimal_value);

  // Store optimal point in interpolation_points
  if(!_performing_extra_greedy_step)
  {
    eim_eval.interpolation_points.push_back(optimal_point);
    eim_eval.interpolation_points_var.push_back(optimal_var);

    NumericVector<Number>* new_bf = NumericVector<Number>::build(this->comm()).release();
    new_bf->init (this->n_dofs(), this->n_local_dofs(), false, libMeshEnums::PARALLEL);
    *new_bf = *solution;
    get_rb_evaluation().basis_functions.push_back( new_bf );
  }
  else
  {
    eim_eval.extra_interpolation_point = optimal_point;
    eim_eval.extra_interpolation_point_var = optimal_var;
  }

  STOP_LOG("enrich_RB_space()", "RBEIMConstruction");
}
示例#10
0
Real RBEIMConstruction::truth_solve(int plot_solution)
{
  START_LOG("truth_solve()", "RBEIMConstruction");

  int training_parameters_found_index = -1;
  if( _parametrized_functions_in_training_set_initialized )
    {
      // Check if parameters are in the training set. If so, we can just load the
      // solution from _parametrized_functions_in_training_set

      for(unsigned int i=0; i<get_n_training_samples(); i++)
        {
          if(get_parameters() == get_params_from_training_set(i))
            {
              training_parameters_found_index = i;
              break;
            }
        }
    }

  // If the parameters are in the training set, just copy the solution vector
  if(training_parameters_found_index >= 0)
    {
      *solution = *_parametrized_functions_in_training_set[training_parameters_found_index];
      update(); // put the solution into current_local_solution as well
    }
  // Otherwise, we have to compute the projection
  else
    {
      RBEIMEvaluation& eim_eval = cast_ref<RBEIMEvaluation&>(get_rb_evaluation());
      eim_eval.set_parameters( get_parameters() );

      // Compute truth representation via projection
      const MeshBase& mesh = this->get_mesh();

      UniquePtr<DGFEMContext> c = this->build_context();
      DGFEMContext &context  = cast_ref<DGFEMContext&>(*c);

      this->init_context(context);

      rhs->zero();

      MeshBase::const_element_iterator       el     = mesh.active_local_elements_begin();
      const MeshBase::const_element_iterator end_el = mesh.active_local_elements_end();

      for ( ; el != end_el; ++el)
        {
          context.pre_fe_reinit(*this, *el);
          context.elem_fe_reinit();

          // All variables should have the same quadrature rule, hence
          // we can get JxW and xyz based on first_elem_fe.
          FEBase* first_elem_fe = NULL;
          context.get_element_fe( 0, first_elem_fe );
          unsigned int n_qpoints = context.get_element_qrule().n_points();
          const std::vector<Real> &JxW = first_elem_fe->get_JxW();
          const std::vector<Point> &xyz = first_elem_fe->get_xyz();

          // Loop over qp before var because parametrized functions often use
          // some caching based on qp.
          for (unsigned int qp=0; qp<n_qpoints; qp++)
            {
              for (unsigned int var=0; var<n_vars(); var++)
                {
                  FEBase* elem_fe = NULL;
                  context.get_element_fe( var, elem_fe );
                  const std::vector<std::vector<Real> >& phi = elem_fe->get_phi();

                  DenseSubVector<Number>& subresidual_var = context.get_elem_residual( var );

                  unsigned int n_var_dofs = cast_int<unsigned int>(context.get_dof_indices( var ).size());

                  Number eval_result = eim_eval.evaluate_parametrized_function(var, xyz[qp], *(*el));
                  for (unsigned int i=0; i != n_var_dofs; i++)
                    subresidual_var(i) += JxW[qp] * eval_result * phi[i][qp];
                }
            }

          // Apply constraints, e.g. periodic constraints
          this->get_dof_map().constrain_element_vector(context.get_elem_residual(), context.get_dof_indices() );

          // Add element vector to global vector
          rhs->add_vector(context.get_elem_residual(), context.get_dof_indices() );
        }

      // Solve to find the best fit, then solution stores the truth representation
      // of the function to be approximated
      solve_for_matrix_and_rhs(*inner_product_solver, *inner_product_matrix, *rhs);

      if (assert_convergence)
        check_convergence(*inner_product_solver);
    }

  if(plot_solution > 0)
    {
#ifdef LIBMESH_HAVE_EXODUS_API
      ExodusII_IO(get_mesh()).write_equation_systems ("truth.exo",
                                                      this->get_equation_systems());
#endif
    }

  STOP_LOG("truth_solve()", "RBEIMConstruction");

  return 0.;
}
void GeneticAlgorithm::record_error_plot(PeldorCalculator const& peldor_calc,
	                                     Chromosome const& chromosome,
									     std::vector<exp_signal> const& signals_exp,
									     Spin const& spinA, Spin const& spinB,
									     std::vector<int> const& param_numbers,
									     std::vector<int> const& param_modes,
										 std::vector<bound> const& param_bounds,
										 genetic_parameters const& genetic_param,
									     output_parameters const& output_param) const
{
	const size_t n_plots = output_param.error_plot_variables.size();
	const size_t plot_size = output_param.error_plot_size;
	size_t n_vars(0);
	// Initialize random generator
	std::random_device rd;
	std::array<unsigned int, std::mt19937::state_size> seed_data;
	std::generate_n(seed_data.begin(), seed_data.size(), std::ref(rd));
	std::seed_seq seq(std::begin(seed_data), std::end(seed_data));
	std::mt19937 engine(seq);
	for (size_t i = 0; i < n_plots; ++i) { // iterate over the error plots
		n_vars = output_param.error_plot_variables[i].size();
		// Check if the selected variables of the error plot were optimized
		int indexVariable(0);
		bool inappropriateVariables(0);
		for (size_t j = 0; j < n_vars; ++j) {
			indexVariable = output_param.error_plot_variables[i][j] - 1;
			if (param_numbers[indexVariable] == -1) {
				std::cout << "  Inappropriate variable (it was not optimized): " << output_param.error_plot_variables[i][j] << std::endl;
				inappropriateVariables = 1;
				break;
			}
		}
		if (inappropriateVariables) continue;
		// Create a generation with different values of the parameters to be varied
		genetic_parameters genetic_param_ep(genetic_param);
		genetic_param_ep.size_generation = output_param.error_plot_size;
		Generation* generation_ep = new Generation(genetic_param_ep);
		for (size_t k = 0; k < plot_size; ++k) generation_ep->chromosomes.push_back(chromosome); // initialize all chromosomes with the optimized chromosome
		int indexGene(0);
		for (size_t j = 0; j < n_vars; ++j) { // vary the genes corresponding to the defined variables
			indexGene = param_numbers[output_param.error_plot_variables[i][j] - 1];
			for (size_t k = 0; k < plot_size; ++k) {
				generation_ep->chromosomes[k].genes[indexGene] = chromosome.create_random_gene(param_bounds[indexGene].lower, param_bounds[indexGene].upper, engine);
			}
		}
		// Score the generation
		generation_ep->score_chromosomes(peldor_calc, signals_exp, spinA, spinB, param_numbers, param_modes, genetic_param);
		generation_ep->sort_chromosomes();
		//// Modified! Save fits
		//output_parameters output_param_ep(output_param);
		//for (size_t j = 0; j < n_vars; ++j) {
		//	std::stringstream nPlot;
		//	nPlot << j;
		//	output_param_ep.directory = output_param.directory + nPlot.str();
		//	record_fit(peldor_calc, generation_ep->chromosomes[j], signals_exp, spinA, spinB, param_numbers, param_modes, output_param_ep);
		//}
		// Create & open a file
		std::ostringstream filename;
		filename << output_param.directory << "error_plot";
		for (size_t j = 0; j < n_vars; ++j) filename << "_" << output_param.error_plot_variables[i][j];
		filename << ".dat";
		std::fstream file;
		file.open(filename.str().c_str(), std::ios::out);
		// Write the names of columns
		size_t const col_width = 15;
		std::ostringstream col_name;
		for (size_t j = 0; j < n_vars; ++j) {
			col_name << "Parameter" << (j + 1);
			file << std::left << std::setw(col_width) << col_name.str();
			col_name.str(std::string()); col_name.clear();
		}
		if (genetic_param.merit_function == 1)      file << std::left << std::setw(col_width) << "RMSD" << std::endl;
		else if (genetic_param.merit_function == 2) file << std::left << std::setw(col_width) << "RMSD/PCC" << std::endl;
		else if (genetic_param.merit_function == 3) file << std::left << std::setw(col_width) << "PCC" << std::endl;
		// Write the error plot
		for (size_t k = 0; k < plot_size; ++k) {
			for (size_t j = 0; j < n_vars; ++j) { 
				indexGene = param_numbers[output_param.error_plot_variables[i][j] - 1];
				if (std::count(angular_indices, angular_indices + 20, indexGene)) {
					file << std::left << std::setw(col_width) << std::fixed << std::setprecision(0) << generation_ep->chromosomes[k].genes[indexGene] * rad2deg;
				}
				else {
					file << std::left << std::setw(col_width) << std::fixed << std::setprecision(2) << generation_ep->chromosomes[k].genes[indexGene];
				}
			}
			file << std::left << std::setw(col_width) << std::fixed << std::setprecision(5) << generation_ep->chromosomes[k].fitness;
			file << std::endl;
		}
		file.close();
		// Clean up
		delete generation_ep;
	}
}