Example #1
0
bool palIListSortTest() {
  int_container a,b,c,d,e,f,g;

  a.z = palGenerateRandom();
  b.z = palGenerateRandom();
  c.z = palGenerateRandom();
  d.z = palGenerateRandom();
  e.z = palGenerateRandom();
  f.z = palGenerateRandom();
  g.z = palGenerateRandom();


  palIList ilist_head;

  ilist_head.AddHead(&a.list_node);
  ilist_head.AddHead(&b.list_node);
  ilist_head.AddHead(&c.list_node);
  ilist_head.AddHead(&d.list_node);
  ilist_head.AddHead(&e.list_node);
  ilist_head.AddHead(&f.list_node);
  ilist_head.AddHead(&g.list_node);

  palIListSorterDeclare(int_container, list_node) sorter(&ilist_head);
  palIListForeachDeclare(int_container, list_node) fe(&ilist_head);

  printf("Unsorted\n");
  while (fe.Finished() == false)
  {
    int_container* list_entry = fe.GetListEntry();
    printf("%d\n", list_entry->z);
    fe.Next();
  }

  sorter.Sort(int_container_compare);

  fe.First();
  
  printf("Sorted\n");
  while (fe.Finished() == false)
  {
    int_container* list_entry = fe.GetListEntry();
    printf("%d\n", list_entry->z);
    fe.Next();
  }

  return true;
}
Example #2
0
Node* WithLocaleNodeFactory::getNode( const QString &tagContent, Parser *p ) const
{
  QStringList expr = smartSplit( tagContent );

  if ( expr.size() != 2 ) {
    throw Grantlee::Exception( TagSyntaxError, QString::fromLatin1( "%1 expected format is for example 'with_locale \"de_DE\"'" ).arg( expr.first() ) );
  }

  FilterExpression fe( expr.at( 1 ), p );

  WithLocaleNode *n = new WithLocaleNode( fe, p );
  NodeList nodeList = p->parse( n, QStringLiteral( "endwith_locale" ) );
  n->setNodeList( nodeList );
  p->removeNextToken();

  return n;
}
Example #3
0
void __fastcall TFormPrincipal::Abrirfiltro1Click(TObject *Sender)
{
        OpenDialog1->Filter = "Filtro de palabras (*.FDP)|*.FDP|Documento de Texto (*.txt)|*.TXT";
        if (OpenDialog1->Execute()){
           delete filtro;
           filtro = new tBST<string>;
           rutaArchivoFiltro = OpenDialog1->FileName;
           ifstream fe(rutaArchivoFiltro.c_str());
           string tmp;

           while (fe >> tmp)
                 this->filtro->insertar(tmp);

           fe.close();

           MostrarFiltro1Click(this);
           }
void palTrackingAllocator::ConsoleDump() const {
    palIListForeachDeclare(palTrackedAllocation, list_node) fe(const_cast<palIList*>(&_tracked_allocations));
    if (fe.Finished()) {
        return;
    }
    palPrintf("Dumping leaks from %s\n", GetName());
    while (fe.Finished() == false) {
        palTrackedAllocation* list_entry = fe.GetListEntry();
        palPrintf("%p [%d]\n", list_entry->ptr, GetSize(list_entry->ptr));
        int i = 0;
        while (list_entry->stacktrace[i] != NULL) {
            palPrintf("        %d: %s %p\n", i, palDebugLookupSymbol(list_entry->stacktrace[i], MAX_SYMBOL_NAME_LENGTH, _symbol_lookup_buffer), list_entry->stacktrace[i]);
            i++;
        }
        fe.Next();
    }
}
Example #5
0
void
MaxQpsThread::operator()(const ConstElemRange & range)
{
  ParallelUniqueId puid;
  _tid = puid.id;

  // For short circuiting reinit
  std::set<ElemType> seen_it;
  for (const auto & elem : range)
  {
    // Only reinit if the element type has not previously been seen
    if (seen_it.insert(elem->type()).second)
    {
      FEType fe_type(FIRST, LAGRANGE);
      unsigned int dim = elem->dim();
      unsigned int side = 0; // we assume that any element will have at least one side ;)

      // We cannot mess with the FE objects in Assembly, because we might need to request second
      // derivatives
      // later on. If we used them, we'd call reinit on them, thus making the call to request second
      // derivatives harmful (i.e. leading to segfaults/asserts). Thus, we have to use a locally
      // allocated object here.
      std::unique_ptr<FEBase> fe(FEBase::build(dim, fe_type));

      // figure out the number of qps for volume
      std::unique_ptr<QBase> qrule(QBase::build(_qtype, dim, _order));
      fe->attach_quadrature_rule(qrule.get());
      fe->reinit(elem);
      if (qrule->n_points() > _max)
        _max = qrule->n_points();

      unsigned int n_shape_funcs = fe->n_shape_functions();
      if (n_shape_funcs > _max_shape_funcs)
        _max_shape_funcs = n_shape_funcs;

      // figure out the number of qps for the face
      // NOTE: user might specify higher order rule for faces, thus possibly ending up with more qps
      // than in the volume
      std::unique_ptr<QBase> qrule_face(QBase::build(_qtype, dim - 1, _face_order));
      fe->attach_quadrature_rule(qrule_face.get());
      fe->reinit(elem, side);
      if (qrule_face->n_points() > _max)
        _max = qrule_face->n_points();
    }
  }
}
Example #6
0
    int PROCCALL pushRemoveImmediately(char const* url, char const* data, char const* filename, int repeatCount)
    {
        TRY
        MtQueue::DataToSend data_packet;
        MtQueue::FileDataEntry fe(filename, data, url);

        data_packet.initialize(fe, MtQueue::DataToSend::LTF_RemoveImmediately, repeatCount);

        MtQueue::MtQueueManager* ppProxymanager = NULL;
        MtQueue::MtQueueManager::initialize(MtQueue::MtQueueManager::IF_RESOLVE, &ppProxymanager);
        if (ppProxymanager)
            ppProxymanager->push( data_packet );
        else
            THROW(CppUtils::OperationFailed, "exc_InvalidProxyManagerPointer", "ctx_RESOLVE_INST_PTR", "");


        CATCH_ALL("pushRemoveImmedaitely");
    }
Example #7
0
int perm_feistel_next(struct perm_t* perm, uint32_t* ct) {
	struct feistel_data_t* feistel_data = perm->mode_data;

	c = fe(r, a, b);

	if(feistel_data->count >= perm->range) {
		perm_errno = PERM_END;
		return PERM_END;
	}

	do {
		perm_rc5_enc(perm, feistel_data->next, ct);
		feistel_data->next++;
	}while(*ct >= perm->range);

	feistel_data->count++;

	return 0;
}
Example #8
0
//------------------------------------------------------------------------------
Teuchos::Array<Teuchos::RCP<const PHX::FieldTag>>
Albany::MechanicsProblem::
buildEvaluators(PHX::FieldManager<PHAL::AlbanyTraits>& fm0,
    const Albany::MeshSpecsStruct& meshSpecs,
    Albany::StateManager& stateMgr,
    Albany::FieldManagerChoice fmchoice,
    const Teuchos::RCP<Teuchos::ParameterList>& responseList)
{
  // Call constructeEvaluators<EvalT>(*rfm[0], *meshSpecs[0], stateMgr);
  // for each EvalT in PHAL::AlbanyTraits::BEvalTypes
  ConstructEvaluatorsOp<MechanicsProblem> op(*this,
      fm0,
      meshSpecs,
      stateMgr,
      fmchoice,
      responseList);
  Sacado::mpl::for_each<PHAL::AlbanyTraits::BEvalTypes> fe(op);
  return *op.tags;
}
int main(int argc, char *argv[])
{
    strcpy(buf,"Frank");
    char opt = argv[1][0];
    if(opt == 'a')
        fa();
    else if(opt == 'b')
        fb();

    else if(opt == 'c')
        fc();
    else if(opt == 'd')
        fd();
    else if(opt == 'e')
        fe();
    else if(opt == 's')
        fs();
    return 0;
}
//Load file, create Items and item Array
void ItemProcessor::load(std::string nameFile) {

	nameFile = "./resources/" + nameFile;
	int numLine = 0;
	ifstream fe("./Resources/input.txt");
	std::string line;

	while (std::getline(fe, line)) {
		string arr[5];
		int i = 0;
		stringstream ssin(line);
		while (ssin.good() && i < 5) {
			ssin >> arr[i];
			++i;
		}
		ItemBuyable *newItem;
		if (numLine == 0) {
			_numUniqueItems = atoi(arr[0].c_str());
			_cartItems = new ItemBuyable*[_numUniqueItems];

		} else {

			switch (line[0]) {
			case '1':
				newItem = new ItemBook(arr[2], arr[1], atof(arr[3].c_str()));
				break;

			case '2':
				newItem = new ItemSuper(arr[1], atof(arr[3].c_str()),
						atoi(arr[2].c_str()));
				break;

			case '3':
				newItem = new ItemToy(arr[1], arr[2], atof(arr[4].c_str()),
						atoi(arr[3].c_str()));
				break;
			}
			_cartItems[numLine - 1] = newItem;
		}
		numLine++;
	}
	fe.close();
}
PConditionalProbabilityEstimator TConditionalProbabilityEstimatorConstructor_ByRows::operator()(PContingency frequencies, PDistribution apriori, PExampleGenerator gen, const long &weightID, const int &attrNo) const
{ if (!frequencies)
    frequencies = mlnew TContingencyAttrClass(gen, weightID, attrNo);
  if (frequencies->varType != TValue::INTVAR)
    if (frequencies->outerVariable)
      raiseError("attribute '%s' is not discrete", frequencies->outerVariable->get_name().c_str());
    else
      raiseError("discrete attribute for condition expected");

  /* We first try to construct a list of Distributions; if we suceed, we'll return an instance of
     TConditionProbabilityEstimator_FromDistribution. If we fail, we'll construct an instance of
     TConditionProbabilityEstimator_ByRows. */

  // This list stores conditional estimators for the case we fail
  PProbabilityEstimatorList cpel = mlnew TProbabilityEstimatorList();

  PContingency newcont = mlnew TContingencyAttrClass(frequencies->outerVariable, frequencies->innerVariable);
  TDistributionVector::const_iterator fi(frequencies->discrete->begin()), fe(frequencies->discrete->end());
  for (int i = 0; fi!=fe; fi++, i++) {
    PProbabilityEstimator est = estimatorConstructor->call(*fi, apriori, PExampleGenerator(), 0, attrNo);
    cpel->push_back(est);
    PDistribution dist = est->call();
    if (!dist)
      break;
    if (i >= newcont->discrete->size())
      newcont->discrete->push_back(dist);
    else
      newcont->discrete->operator[](i) = dist;
  }
  

  if (fi==fe)
    return mlnew TConditionalProbabilityEstimator_FromDistribution(newcont);

  /* We failed at constructing a matrix of probabilites. We'll just complete the list of estimators. */
  for (; fi!=fe; fi++)
    cpel->push_back(estimatorConstructor->call(*fi, apriori, gen, weightID));

  TConditionalProbabilityEstimator_ByRows *cbr = mlnew TConditionalProbabilityEstimator_ByRows();
  PConditionalProbabilityEstimator wcbr = cbr;
  cbr->estimatorList = cpel;
  return wcbr;
}
void VCXYPadFixtureEditor_Test::accept()
{
    QList <VCXYPadFixture> list;

    VCXYPadFixture fxi(m_doc);
    fxi.setDisplayMode(VCXYPadFixture::Percentage);

    fxi.setHead(GroupHead(0, 0));
    fxi.setX(0, 1, false);
    fxi.setY(0, 1, false);
    list << fxi;

    fxi.setHead(GroupHead(1, 0));
    fxi.setX(0.5, 0.6, true);
    fxi.setY(0.5, 0.6, true);
    list << fxi;

    VCXYPadFixtureEditor fe(NULL, list);
    fe.m_xMin->setValue(10);
    fe.m_xMax->setValue(20);
    fe.m_yMin->setValue(30);
    fe.m_yMax->setValue(40);
    fe.accept();
    QCOMPARE(fe.m_xMin->value(), 10);
    QCOMPARE(fe.m_xMax->value(), 20);
    QCOMPARE(fe.m_yMin->value(), 30);
    QCOMPARE(fe.m_yMax->value(), 40);

    list = fe.fixtures();
    QCOMPARE(list[0].head().fxi, quint32(0));
    QCOMPARE(list[0].head().head, 0);
    QCOMPARE(list[0].xMin(), qreal(0.1));
    QCOMPARE(list[0].xMax(), qreal(0.2));
    QCOMPARE(list[0].yMin(), qreal(0.3));
    QCOMPARE(list[0].yMax(), qreal(0.4));
    QCOMPARE(list[1].head().fxi, quint32(1));
    QCOMPARE(list[1].head().head, 0);
    QCOMPARE(list[1].xMin(), qreal(0.1));
    QCOMPARE(list[1].xMax(), qreal(0.2));
    QCOMPARE(list[1].yMin(), qreal(0.3));
    QCOMPARE(list[1].yMax(), qreal(0.4));
}
Example #13
0
void mdeath::fungus( monster &z )
{
    // If the fungus died from anti-fungal poison, don't pouf
    if( g->m.get_field_strength( z.pos(), fd_fungicidal_gas ) ) {
        return;
    }

    //~ the sound of a fungus dying
    sounds::sound( z.pos(), 10, sounds::sound_t::combat, _( "Pouf!" ), false, "misc", "puff" );

    fungal_effects fe( *g, g->m );
    for( auto &&sporep : g->m.points_in_radius( z.pos(), 1 ) ) { // *NOPAD*
        if( g->m.impassable( sporep ) ) {
            continue;
        }
        // z is dead, don't credit it with the kill
        // Maybe credit z's killer?
        fe.fungalize( sporep, nullptr, 0.25 );
    }
}
Example #14
0
Node *WithNodeFactory::getNode(const QString &tagContent, Parser *p) const
{
  auto expr = smartSplit(tagContent);

  if (expr.size() != 4 || expr.at(2) != QStringLiteral("as")) {
    throw Grantlee::Exception(
        TagSyntaxError, QStringLiteral("%1 expected format is 'value as name'")
                            .arg(expr.first()));
  }

  FilterExpression fe(expr.at(1), p);
  QString name(expr.at(3));

  auto n = new WithNode(fe, name, p);
  auto nodeList = p->parse(n, QStringLiteral("endwith"));
  n->setNodeList(nodeList);
  p->removeNextToken();

  return n;
}
void
ComputeCrackTipEnrichmentSmallStrain::computeProperties()
{
  FEType fe_type(Utility::string_to_enum<Order>("first"),
                 Utility::string_to_enum<FEFamily>("lagrange"));
  const unsigned int dim = _current_elem->dim();
  std::unique_ptr<FEBase> fe(FEBase::build(dim, fe_type));
  fe->attach_quadrature_rule(_qrule);
  _fe_phi = &(fe->get_phi());
  _fe_dphi = &(fe->get_dphi());

  if (isBoundaryMaterial())
    fe->reinit(_current_elem, _current_side);
  else
    fe->reinit(_current_elem);

  for (unsigned int i = 0; i < _BI.size(); ++i)
    crackTipEnrichementFunctionAtPoint(*(_current_elem->get_node(i)), _BI[i]);

  ComputeStrainBase::computeProperties();
}
Example #16
0
Grantlee::Node* FilterNodeFactory::getNode( const QString& tagContent, Grantlee::Parser* p ) const
{
  QStringList expr = tagContent.split( QLatin1Char( ' ' ), QString::SkipEmptyParts );

  expr.removeFirst();

  QString expression = expr.join( QChar::fromLatin1( ' ' ) );
  FilterExpression fe( QStringLiteral( "var|%1" ).arg( expression ), p );

  QStringList filters = fe.filters();
  if ( filters.contains( QStringLiteral( "safe" ) ) || filters.contains( QStringLiteral( "escape" ) ) ) {
    throw Grantlee::Exception( TagSyntaxError, QStringLiteral( "Use the \"autoescape\" tag instead." ) );
  }

  FilterNode *n = new FilterNode( fe, p );

  NodeList filterNodes = p->parse( n, QStringLiteral( "endfilter" ) );
  p->removeNextToken();

  n->setNodeList( filterNodes );
  return n;
}
Example #17
0
void FileManager :: saveSchema(){

    const char* extTxt = ".txt";
    std::string result = std::string(directory) +std::string(nameOfFile) + std::string(extTxt);
    const char * schemaName = result.c_str();
    // Crea un fichero de salida

       ofstream fe(schemaName);

       Nodo3d<const char*,int,int>* temp;
       temp = schema.get_primerNodo();
       schema.get_ultimoNodo()->set_siguiente(NULL);
       for(int x=0 ; x<(schema.getLength());x++){
           fe << temp->get_elemento1() <<endl;
           fe << temp->get_elemento2() <<endl;
           fe << temp->get_elemento3() <<endl;

           temp = temp->get_siguiente();

       }
       fe.close();
}
Example #18
0
Real
InteractionIntegralSM::computeIntegral()
{
  Real sum = 0;

  // calculate phi and dphi for this element
  FEType fe_type(Utility::string_to_enum<Order>("first"),
                 Utility::string_to_enum<FEFamily>("lagrange"));
  const unsigned int dim = _current_elem->dim();
  UniquePtr<FEBase> fe(FEBase::build(dim, fe_type));
  fe->attach_quadrature_rule(_qrule);
  _phi_curr_elem = &fe->get_phi();
  _dphi_curr_elem = &fe->get_dphi();
  fe->reinit(_current_elem);

  // calculate q for all nodes in this element
  _q_curr_elem.clear();
  unsigned int ring_base = (_q_function_type == "TOPOLOGY") ? 0 : 1;

  for (unsigned int i = 0; i < _current_elem->n_nodes(); ++i)
  {
    Node * this_node = _current_elem->get_node(i);
    Real q_this_node;

    if (_q_function_type == "GEOMETRY")
      q_this_node = _crack_front_definition->DomainIntegralQFunction(
          _crack_front_point_index, _ring_index - ring_base, this_node);
    else if (_q_function_type == "TOPOLOGY")
      q_this_node = _crack_front_definition->DomainIntegralTopologicalQFunction(
          _crack_front_point_index, _ring_index - ring_base, this_node);

    _q_curr_elem.push_back(q_this_node);
  }

  for (_qp = 0; _qp < _qrule->n_points(); _qp++)
    sum += _JxW[_qp] * _coord[_qp] * computeQpIntegral();
  return sum;
}
void VCXYPadFixtureEditor_Test::valueSlots()
{
    QList <VCXYPadFixture> list;
    VCXYPadFixtureEditor fe(NULL, list);

    fe.m_xMin->setValue(50);
    fe.m_xMax->setValue(20);
    QCOMPARE(fe.m_xMin->value(), 19);
    QCOMPARE(fe.m_xMax->value(), 20);

    fe.m_xMin->setValue(40);
    QCOMPARE(fe.m_xMin->value(), 40);
    QCOMPARE(fe.m_xMax->value(), 41);

    fe.m_yMin->setValue(50);
    fe.m_yMax->setValue(20);
    QCOMPARE(fe.m_yMin->value(), 19);
    QCOMPARE(fe.m_yMax->value(), 20);

    fe.m_yMin->setValue(40);
    QCOMPARE(fe.m_yMin->value(), 40);
    QCOMPARE(fe.m_yMax->value(), 41);
}
void VCXYPadFixtureEditor_Test::initial()
{
    QList <VCXYPadFixture> list;

    VCXYPadFixture fxi(m_doc);
    fxi.setDisplayMode(VCXYPadFixture::Percentage);

    fxi.setHead(GroupHead(0, 0));
    fxi.setX(0.1, 0.2, false);
    fxi.setY(0.3, 0.4, true);
    list << fxi;

    fxi.setHead(GroupHead(1, 0));
    fxi.setX(0, 1, true);
    fxi.setY(0, 1, false);
    list << fxi;

    VCXYPadFixtureEditor fe(NULL, list);
    QCOMPARE(fe.fixtures(), list);
    QCOMPARE(fe.m_xMin->value(), 10);
    QCOMPARE(fe.m_xMax->value(), 20);
    QCOMPARE(fe.m_xReverse->isChecked(), false);
    QCOMPARE(fe.m_yMin->value(), 30);
    QCOMPARE(fe.m_yMax->value(), 40);
    QCOMPARE(fe.m_yReverse->isChecked(), true);

    list.clear();

    VCXYPadFixtureEditor fe2(NULL, list);
    QCOMPARE(fe2.fixtures().isEmpty(), true);
    QCOMPARE(fe2.m_xMin->value(), 0);
    QCOMPARE(fe2.m_xMax->value(), 100);
    QCOMPARE(fe2.m_xReverse->isChecked(), false);
    QCOMPARE(fe2.m_yMin->value(), 0);
    QCOMPARE(fe2.m_yMax->value(), 100);
    QCOMPARE(fe2.m_yReverse->isChecked(), false);
}
Example #21
0
void eff_hs_overlap(TString f_name, TString p_name, TString pt)
{
  // efficiency vs half-strip  - including overlaps in odd&even
  TCut ok_eta = "TMath::Abs(eta)>1.64 && TMath::Abs(eta)<2.12";
  
  
  TTree *t = getTree(f_name);
  TH1F* ho = draw_eff(t, "         GEM reconstruction efficiency               CMS Simulation;LCT half-strip number;Efficiency", "h_odd", "(130,0.5,130.5)", "hs_lct_odd", ok_lct1 && ok_eta , ok_pad1_overlap, "", kRed);
  TH1F* he = draw_eff(t, "         GEM reconstruction efficiency               CMS Simulation;LCT half-strip number;Efficiency", "h_evn", "(130,0.5,130.5)", "hs_lct_even", ok_lct2 && ok_eta , ok_pad2_overlap, "same");

  TF1 fo("fo", "pol0", 6., 123.);
  ho->Fit("fo","RN");
  TF1 fe("fe", "pol0", 6., 123.);
  he->Fit("fe","RN");

  TLegend *leg = new TLegend(0.25,0.23,.75,0.5, NULL, "brNDC");
  leg->SetBorderSize(0);
  leg->SetFillStyle(0);
  leg->SetTextSize(0.06);
  leg->AddEntry((TObject*)0,"muon p_{T} = " + pt + " GeV/c",""); 
  leg->AddEntry(he, "\"Close\" chamber pairs","l");
  leg->AddEntry(ho, "\"Far\" chamber pairs","l");
  leg->Draw();

  // Print additional information
  TLatex* tex2 = new TLatex(.67,.8,"   L1 Trigger");
  tex2->SetTextSize(0.05);
  tex2->SetNDC();
  tex2->Draw();
    
  TLatex *  tex = new TLatex(.66,.73,"1.64<|#eta|<2.12");
  tex->SetTextSize(0.05);
  tex->SetNDC();
  tex->Draw();

  gPad->Print(p_name);
}
Example #22
0
File: if.c Project: choppsv1/ircii
/*
 * How it works -- if There are no parenthesis, it must be a
 * foreach array command.  If there are parenthesis, and there are
 * exactly two commas, it must be a C-like for command, else it must
 * must be an foreach word command
 */
void
foreach_handler(u_char *command, u_char *args, u_char *subargs)
{
	u_char	*temp = NULL;
	u_char	*placeholder;
	u_char	*temp2 = NULL;

	malloc_strcpy(&temp, args);
	placeholder = temp;
	if (*temp == '(')
	{
		if ((temp2 = next_expr(&temp, '(')) == NULL) {
			new_free(&placeholder);
			return;
		}
		if (charcount(temp2, ',') == 2)
			forcmd(command, args, subargs);
		else
			fe(command, args, subargs);
	}
	else
		foreach(command, args, subargs);
	new_free(&placeholder);
}
void
MultiAppProjectionTransfer::assembleL2From(EquationSystems & es, const std::string & system_name)
{
  unsigned int n_apps = _multi_app->numGlobalApps();
  std::vector<NumericVector<Number> *> from_slns(n_apps, NULL);
  std::vector<MeshFunction *> from_fns(n_apps, NULL);
  std::vector<MeshTools::BoundingBox *> from_bbs(n_apps, NULL);

  // get bounding box, mesh function and solution for each subapp
  for (unsigned int i = 0; i < n_apps; i++)
  {
    if (!_multi_app->hasLocalApp(i))
      continue;

    MPI_Comm swapped = Moose::swapLibMeshComm(_multi_app->comm());

    FEProblem & from_problem = *_multi_app->appProblem(i);
    EquationSystems & from_es = from_problem.es();
    MeshBase & from_mesh = from_es.get_mesh();
    MeshTools::BoundingBox * app_box = new MeshTools::BoundingBox(MeshTools::processor_bounding_box(from_mesh, from_mesh.processor_id()));
    from_bbs[i] = app_box;

    MooseVariable & from_var = from_problem.getVariable(0, _from_var_name);
    System & from_sys = from_var.sys().system();
    unsigned int from_var_num = from_sys.variable_number(from_var.name());

    NumericVector<Number> * serialized_from_solution = NumericVector<Number>::build(from_sys.comm()).release();
    serialized_from_solution->init(from_sys.n_dofs(), false, SERIAL);
    // Need to pull down a full copy of this vector on every processor so we can get values in parallel
    from_sys.solution->localize(*serialized_from_solution);
    from_slns[i] = serialized_from_solution;

    MeshFunction * from_func = new MeshFunction(from_es, *serialized_from_solution, from_sys.get_dof_map(), from_var_num);
    from_func->init(Trees::ELEMENTS);
    from_func->enable_out_of_mesh_mode(NOTFOUND);
    from_fns[i] = from_func;

    Moose::swapLibMeshComm(swapped);
  }


  const MeshBase& mesh = es.get_mesh();
  const unsigned int dim = mesh.mesh_dimension();

  LinearImplicitSystem & system = es.get_system<LinearImplicitSystem>(system_name);

  FEType fe_type = system.variable_type(0);
  AutoPtr<FEBase> fe(FEBase::build(dim, fe_type));
  QGauss qrule(dim, fe_type.default_quadrature_order());
  fe->attach_quadrature_rule(&qrule);
  const std::vector<Real> & JxW = fe->get_JxW();
  const std::vector<std::vector<Real> > & phi = fe->get_phi();
  const std::vector<Point> & xyz = fe->get_xyz();

  const DofMap& dof_map = system.get_dof_map();
  DenseMatrix<Number> Ke;
  DenseVector<Number> Fe;
  std::vector<dof_id_type> dof_indices;

  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)
  {
    const Elem* elem = *el;

    fe->reinit (elem);

    dof_map.dof_indices (elem, dof_indices);
    Ke.resize (dof_indices.size(), dof_indices.size());
    Fe.resize (dof_indices.size());

    for (unsigned int qp = 0; qp < qrule.n_points(); qp++)
    {
      Point qpt = xyz[qp];
      Real f = 0.;
      for (unsigned int app = 0; app < n_apps; app++)
      {
        Point pt = qpt - _multi_app->position(app);
        if (from_bbs[app] != NULL && from_bbs[app]->contains_point(pt))
        {
          MPI_Comm swapped = Moose::swapLibMeshComm(_multi_app->comm());
          f = (*from_fns[app])(pt);
          Moose::swapLibMeshComm(swapped);
          break;
        }
      }

      // Now compute the element matrix and RHS contributions.
      for (unsigned int i=0; i<phi.size(); i++)
      {
        // RHS
        Fe(i) += JxW[qp] * (f * phi[i][qp]);

        if (_compute_matrix)
          for (unsigned int j = 0; j < phi.size(); j++)
          {
            // The matrix contribution
            Ke(i,j) += JxW[qp] * (phi[i][qp] * phi[j][qp]);
          }
      }
      dof_map.constrain_element_matrix_and_vector(Ke, Fe, dof_indices);

      if (_compute_matrix)
        system.matrix->add_matrix(Ke, dof_indices);
      system.rhs->add_vector(Fe, dof_indices);
    }
  }

  for (unsigned int i = 0; i < n_apps; i++)
  {
    delete from_fns[i];
    delete from_bbs[i];
    delete from_slns[i];
  }
}
void
MultiAppProjectionTransfer::assembleL2To(EquationSystems & es, const std::string & system_name)
{
  unsigned int app = es.parameters.get<unsigned int>("app");

  FEProblem & from_problem = *_multi_app->problem();
  EquationSystems & from_es = from_problem.es();

  MooseVariable & from_var = from_problem.getVariable(0, _from_var_name);
  System & from_sys = from_var.sys().system();
  unsigned int from_var_num = from_sys.variable_number(from_var.name());

  NumericVector<Number> * serialized_from_solution = NumericVector<Number>::build(from_sys.comm()).release();
  serialized_from_solution->init(from_sys.n_dofs(), false, SERIAL);
  // Need to pull down a full copy of this vector on every processor so we can get values in parallel
  from_sys.solution->localize(*serialized_from_solution);

  MeshFunction from_func(from_es, *serialized_from_solution, from_sys.get_dof_map(), from_var_num);
  from_func.init(Trees::ELEMENTS);
  from_func.enable_out_of_mesh_mode(0.);


  const MeshBase& mesh = es.get_mesh();
  const unsigned int dim = mesh.mesh_dimension();

  LinearImplicitSystem & system = es.get_system<LinearImplicitSystem>(system_name);

  FEType fe_type = system.variable_type(0);
  AutoPtr<FEBase> fe(FEBase::build(dim, fe_type));
  QGauss qrule(dim, fe_type.default_quadrature_order());
  fe->attach_quadrature_rule(&qrule);
  const std::vector<Real> & JxW = fe->get_JxW();
  const std::vector<std::vector<Real> > & phi = fe->get_phi();
  const std::vector<Point> & xyz = fe->get_xyz();

  const DofMap& dof_map = system.get_dof_map();
  DenseMatrix<Number> Ke;
  DenseVector<Number> Fe;
  std::vector<dof_id_type> dof_indices;

  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)
  {
    const Elem* elem = *el;

    fe->reinit (elem);

    dof_map.dof_indices (elem, dof_indices);
    Ke.resize (dof_indices.size(), dof_indices.size());
    Fe.resize (dof_indices.size());

    for (unsigned int qp = 0; qp < qrule.n_points(); qp++)
    {
      Point qpt = xyz[qp];
      Point pt = qpt + _multi_app->position(app);
      Real f = from_func(pt);

      // Now compute the element matrix and RHS contributions.
      for (unsigned int i=0; i<phi.size(); i++)
      {
        // RHS
        Fe(i) += JxW[qp] * (f * phi[i][qp]);

        if (_compute_matrix)
          for (unsigned int j = 0; j < phi.size(); j++)
          {
            // The matrix contribution
            Ke(i,j) += JxW[qp] * (phi[i][qp] * phi[j][qp]);
          }
      }
      dof_map.constrain_element_matrix_and_vector(Ke, Fe, dof_indices);

      if (_compute_matrix)
        system.matrix->add_matrix(Ke, dof_indices);
      system.rhs->add_vector(Fe, dof_indices);
    }
  }
}
Example #25
0
void
IMPInitializer::registerMesh(MeshBase* mesh, int level_number)
{
    const int max_levels = d_gridding_alg->getMaxLevels();
    if (level_number < 0) level_number = max_levels - 1;
    level_number = std::min(level_number, max_levels - 1);
    const unsigned int mesh_idx = static_cast<unsigned int>(d_meshes[level_number].size());
    d_meshes[level_number].push_back(mesh);

    // Compute the Cartesian grid spacing on the specified level of the mesh.
    Pointer<CartesianGridGeometry<NDIM> > grid_geom = d_hierarchy->getGridGeometry();
    const double* const dx0 = grid_geom->getDx();
    double dx[NDIM];
    std::copy(dx0, dx0 + NDIM, dx);
    for (int ln = 1; ln <= level_number; ++ln)
    {
        const IntVector<NDIM> ratio = d_gridding_alg->getRatioToCoarserLevel(ln);
        for (unsigned int d = 0; d < NDIM; ++d) dx[d] /= static_cast<double>(ratio(d));
    }
    const double dx_min = *std::min_element(dx, dx + NDIM);

    // Setup data structures for computing the positions of the material points
    // and weighting factors.
    const int dim = mesh->mesh_dimension();
    FEType fe_type(FIRST, LAGRANGE);
    AutoPtr<QBase> qrule = QBase::build(QGAUSS, dim, FIRST);
    AutoPtr<FEBase> fe(FEBase::build(dim, fe_type));
    fe->attach_quadrature_rule(qrule.get());
    const std::vector<libMesh::Point>& q_point = fe->get_xyz();
    const std::vector<double>& JxW = fe->get_JxW();
    const MeshBase::const_element_iterator el_begin = mesh->active_elements_begin();
    const MeshBase::const_element_iterator el_end = mesh->active_elements_end();

    // Count the number of material points.
    d_num_vertex[level_number].push_back(0);
    d_vertex_offset[level_number].push_back(0);
    if (mesh_idx > 0)
    {
        d_vertex_offset[level_number][mesh_idx] =
            d_vertex_offset[level_number][mesh_idx - 1] + d_num_vertex[level_number][mesh_idx - 1];
    }
    for (MeshBase::const_element_iterator el_it = el_begin; el_it != el_end; ++el_it)
    {
        const Elem* const elem = *el_it;
        const double hmax = elem->hmax();
        const int npts = std::max(MIN_POINTS, std::ceil(POINT_FACTOR * hmax / dx_min));
        const Order order = static_cast<Order>(std::min(2 * npts - 1, static_cast<int>(FORTYTHIRD)));
        if (order != qrule->get_order())
        {
            qrule = QBase::build(QGAUSS, dim, order);
            fe->attach_quadrature_rule(qrule.get());
        }
        fe->reinit(elem);
        d_num_vertex[level_number][mesh_idx] += qrule->n_points();
    }

    // Initialize the material points.
    d_vertex_posn[level_number].resize(d_vertex_posn[level_number].size() + 1);
    d_vertex_wgt[level_number].resize(d_vertex_wgt[level_number].size() + 1);
    d_vertex_subdomain_id[level_number].resize(d_vertex_subdomain_id[level_number].size() + 1);
    d_vertex_posn[level_number][mesh_idx].resize(d_num_vertex[level_number][mesh_idx]);
    d_vertex_wgt[level_number][mesh_idx].resize(d_num_vertex[level_number][mesh_idx]);
    d_vertex_subdomain_id[level_number][mesh_idx].resize(d_num_vertex[level_number][mesh_idx]);
    unsigned int k = 0;
    for (MeshBase::const_element_iterator el_it = el_begin; el_it != el_end; ++el_it)
    {
        const Elem* const elem = *el_it;
        const double hmax = elem->hmax();
        const int npts = std::max(MIN_POINTS, std::ceil(POINT_FACTOR * hmax / dx_min));
        const Order order = static_cast<Order>(std::min(2 * npts - 1, static_cast<int>(FORTYTHIRD)));
        if (order != qrule->get_order())
        {
            qrule = QBase::build(QGAUSS, dim, order);
            fe->attach_quadrature_rule(qrule.get());
        }
        fe->reinit(elem);
        for (unsigned int qp = 0; qp < qrule->n_points(); ++qp, ++k)
        {
            d_vertex_posn[level_number][mesh_idx][k] = q_point[qp];
            d_vertex_wgt[level_number][mesh_idx][k] = JxW[qp];
            d_vertex_subdomain_id[level_number][mesh_idx][k] = elem->subdomain_id();
        }
    }
    return;
} // registerMesh
void
MultiAppProjectionTransfer::execute()
{
  _console << "Beginning projection transfer " << name() << std::endl;

  getAppInfo();

  ////////////////////
  // We are going to project the solutions by solving some linear systems.  In
  // order to assemble the systems, we need to evaluate the "from" domain
  // solutions at quadrature points in the "to" domain.  Some parallel
  // communication is necessary because each processor doesn't necessarily have
  // all the "from" information it needs to set its "to" values.  We don't want
  // to use a bunch of big all-to-all broadcasts, so we'll use bounding boxes to
  // figure out which processors have the information we need and only
  // communicate with those processors.
  //
  // Each processor will
  // 1. Check its local quadrature points in the "to" domains to see which
  //    "from" domains they might be in.
  // 2. Send quadrature points to the processors with "from" domains that might
  //    contain those points.
  // 3. Recieve quadrature points from other processors, evaluate its mesh
  //    functions at those points, and send the values back to the proper
  //    processor
  // 4. Recieve mesh function evaluations from all relevant processors and
  //    decide which one to use at every quadrature point (the lowest global app
  //    index always wins)
  // 5. And use the mesh function evaluations to assemble and solve an L2
  //    projection system on its local elements.
  ////////////////////

  ////////////////////
  // For every combination of global "from" problem and local "to" problem, find
  // which "from" bounding boxes overlap with which "to" elements.  Keep track
  // of which processors own bounding boxes that overlap with which elements.
  // Build vectors of quadrature points to send to other processors for mesh
  // function evaluations.
  ////////////////////

  // Get the bounding boxes for the "from" domains.
  std::vector<MeshTools::BoundingBox> bboxes = getFromBoundingBoxes();

  // Figure out how many "from" domains each processor owns.
  std::vector<unsigned int> froms_per_proc = getFromsPerProc();

  std::vector<std::vector<Point> > outgoing_qps(n_processors());
  std::vector<std::map<std::pair<unsigned int, unsigned int>, unsigned int> > element_index_map(n_processors());
  // element_index_map[i_to, element_id] = index
  // outgoing_qps[index] is the first quadrature point in element

  if (! _qps_cached)
  {
    for (unsigned int i_to = 0; i_to < _to_problems.size(); i_to++)
    {
      MeshBase & to_mesh = _to_meshes[i_to]->getMesh();

      LinearImplicitSystem & system = * _proj_sys[i_to];

      FEType fe_type = system.variable_type(0);
      std::unique_ptr<FEBase> fe(FEBase::build(to_mesh.mesh_dimension(), fe_type));
      QGauss qrule(to_mesh.mesh_dimension(), fe_type.default_quadrature_order());
      fe->attach_quadrature_rule(&qrule);
      const std::vector<Point> & xyz = fe->get_xyz();

      MeshBase::const_element_iterator       el     = to_mesh.local_elements_begin();
      const MeshBase::const_element_iterator end_el = to_mesh.local_elements_end();

      unsigned int from0 = 0;
      for (processor_id_type i_proc = 0;
           i_proc < n_processors();
           from0 += froms_per_proc[i_proc], i_proc++)
      {
        for (el = to_mesh.local_elements_begin(); el != end_el; el++)
        {
          const Elem* elem = *el;
          fe->reinit (elem);

          bool qp_hit = false;
          for (unsigned int i_from = 0;
               i_from < froms_per_proc[i_proc] && ! qp_hit; i_from++)
          {
            for (unsigned int qp = 0;
                 qp < qrule.n_points() && ! qp_hit; qp ++)
            {
              Point qpt = xyz[qp];
              if (bboxes[from0 + i_from].contains_point(qpt + _to_positions[i_to]))
                qp_hit = true;
            }
          }

          if (qp_hit)
          {
            // The selected processor's bounding box contains at least one
            // quadrature point from this element.  Send all qps from this element
            // and remember where they are in the array using the map.
            std::pair<unsigned int, unsigned int> key(i_to, elem->id());
            element_index_map[i_proc][key] = outgoing_qps[i_proc].size();
            for (unsigned int qp = 0; qp < qrule.n_points(); qp ++)
            {
              Point qpt = xyz[qp];
              outgoing_qps[i_proc].push_back(qpt + _to_positions[i_to]);
            }
          }
        }
      }
    }

    if (_fixed_meshes)
      _cached_index_map = element_index_map;
  }
  else
  {
    element_index_map = _cached_index_map;
  }

  ////////////////////
  // Request quadrature point evaluations from other processors and handle
  // requests sent to this processor.
  ////////////////////

  // Non-blocking send quadrature points to other processors.
  std::vector<Parallel::Request> send_qps(n_processors());
  if (! _qps_cached)
    for (processor_id_type i_proc = 0; i_proc < n_processors(); i_proc++)
      if (i_proc != processor_id())
        _communicator.send(i_proc, outgoing_qps[i_proc], send_qps[i_proc]);

  // Get the local bounding boxes.
  std::vector<MeshTools::BoundingBox> local_bboxes(froms_per_proc[processor_id()]);
  {
    // Find the index to the first of this processor's local bounding boxes.
    unsigned int local_start = 0;
    for (processor_id_type i_proc = 0;
         i_proc < n_processors() && i_proc != processor_id();
         i_proc++)
      local_start += froms_per_proc[i_proc];

    // Extract the local bounding boxes.
    for (unsigned int i_from = 0; i_from < froms_per_proc[processor_id()]; i_from++)
      local_bboxes[i_from] = bboxes[local_start + i_from];
  }

  // Setup the local mesh functions.
  std::vector<MeshFunction *> local_meshfuns(froms_per_proc[processor_id()], NULL);
  for (unsigned int i_from = 0; i_from < _from_problems.size(); i_from++)
  {
    FEProblemBase & from_problem = *_from_problems[i_from];
    MooseVariable & from_var = from_problem.getVariable(0, _from_var_name);
    System & from_sys = from_var.sys().system();
    unsigned int from_var_num = from_sys.variable_number(from_var.name());

    MeshFunction * from_func = new MeshFunction(from_problem.es(),
         *from_sys.current_local_solution, from_sys.get_dof_map(), from_var_num);
    from_func->init(Trees::ELEMENTS);
    from_func->enable_out_of_mesh_mode(OutOfMeshValue);
    local_meshfuns[i_from] = from_func;
  }

  // Recieve quadrature points from other processors, evaluate mesh frunctions
  // at those points, and send the values back.
  std::vector<Parallel::Request> send_evals(n_processors());
  std::vector<Parallel::Request> send_ids(n_processors());
  std::vector<std::vector<Real> > outgoing_evals(n_processors());
  std::vector<std::vector<unsigned int> > outgoing_ids(n_processors());
  std::vector<std::vector<Real> > incoming_evals(n_processors());
  std::vector<std::vector<unsigned int> > incoming_app_ids(n_processors());
  for (processor_id_type i_proc = 0; i_proc < n_processors(); i_proc++)
  {
    // Use the cached qps if they're available.
    std::vector<Point> incoming_qps;
    if (! _qps_cached)
    {
      if (i_proc == processor_id())
        incoming_qps = outgoing_qps[i_proc];
      else
        _communicator.receive(i_proc, incoming_qps);
      // Cache these qps for later if _fixed_meshes
      if (_fixed_meshes)
        _cached_qps[i_proc] = incoming_qps;
    }
    else
    {
      incoming_qps = _cached_qps[i_proc];
    }

    outgoing_evals[i_proc].resize(incoming_qps.size(), OutOfMeshValue);
    if (_direction == FROM_MULTIAPP)
      outgoing_ids[i_proc].resize(incoming_qps.size(), libMesh::invalid_uint);
    for (unsigned int qp = 0; qp < incoming_qps.size(); qp++)
    {
      Point qpt = incoming_qps[qp];

      // Loop until we've found the lowest-ranked app that actually contains
      // the quadrature point.
      for (unsigned int i_from = 0; i_from < _from_problems.size(); i_from++)
      {
        if (local_bboxes[i_from].contains_point(qpt))
        {
          outgoing_evals[i_proc][qp] = (* local_meshfuns[i_from])(qpt - _from_positions[i_from]);
          if (_direction == FROM_MULTIAPP)
            outgoing_ids[i_proc][qp] = _local2global_map[i_from];
        }
      }
    }

    if (i_proc == processor_id())
    {
      incoming_evals[i_proc] = outgoing_evals[i_proc];
      if (_direction == FROM_MULTIAPP)
        incoming_app_ids[i_proc] = outgoing_ids[i_proc];
    }
    else
    {
      _communicator.send(i_proc, outgoing_evals[i_proc], send_evals[i_proc]);
      if (_direction == FROM_MULTIAPP)
        _communicator.send(i_proc, outgoing_ids[i_proc], send_ids[i_proc]);
    }
  }

  ////////////////////
  // Gather all of the qp evaluations and pick out the best ones for each qp.
  ////////////////////
  for (processor_id_type i_proc = 0; i_proc < n_processors(); i_proc++)
  {
    if (i_proc == processor_id())
      continue;
    _communicator.receive(i_proc, incoming_evals[i_proc]);
    if (_direction == FROM_MULTIAPP)
      _communicator.receive(i_proc, incoming_app_ids[i_proc]);
  }

  std::vector<std::vector<Real> > final_evals(_to_problems.size());
  std::vector<std::map<unsigned int, unsigned int> > trimmed_element_maps(_to_problems.size());

  for (unsigned int i_to = 0; i_to < _to_problems.size(); i_to++)
  {
    MeshBase & to_mesh = _to_meshes[i_to]->getMesh();
    LinearImplicitSystem & system = * _proj_sys[i_to];

    FEType fe_type = system.variable_type(0);
    std::unique_ptr<FEBase> fe(FEBase::build(to_mesh.mesh_dimension(), fe_type));
    QGauss qrule(to_mesh.mesh_dimension(), fe_type.default_quadrature_order());
    fe->attach_quadrature_rule(&qrule);
    const std::vector<Point> & xyz = fe->get_xyz();

    MeshBase::const_element_iterator       el     = to_mesh.local_elements_begin();
    const MeshBase::const_element_iterator end_el = to_mesh.local_elements_end();

    for (el = to_mesh.active_local_elements_begin(); el != end_el; el++)
    {
      const Elem* elem = *el;
      fe->reinit (elem);

      bool element_is_evaled = false;
      std::vector<Real> evals(qrule.n_points(), 0.);

      for (unsigned int qp = 0; qp < qrule.n_points(); qp++)
      {
        Point qpt = xyz[qp];

        unsigned int lowest_app_rank = libMesh::invalid_uint;
        for (unsigned int i_proc = 0; i_proc < n_processors(); i_proc++)
        {
          // Ignore the selected processor if the element wasn't found in it's
          // bounding box.
          std::map<std::pair<unsigned int, unsigned int>, unsigned int> & map = element_index_map[i_proc];
          std::pair<unsigned int, unsigned int> key(i_to, elem->id());
          if (map.find(key) == map.end())
            continue;
          unsigned int qp0 = map[key];

          // Ignore the selected processor if it's app has a higher rank than the
          // previously found lowest app rank.
          if (_direction == FROM_MULTIAPP)
            if (incoming_app_ids[i_proc][qp0 + qp] >= lowest_app_rank)
              continue;

          // Ignore the selected processor if the qp was actually outside the
          // processor's subapp's mesh.
          if (incoming_evals[i_proc][qp0 + qp] == OutOfMeshValue)
            continue;

          // This is the best meshfunction evaluation so far, save it.
          element_is_evaled = true;
          evals[qp] = incoming_evals[i_proc][qp0 + qp];
        }
      }

      // If we found good evaluations for any of the qps in this element, save
      // those evaluations for later.
      if (element_is_evaled)
      {
        trimmed_element_maps[i_to][elem->id()] = final_evals[i_to].size();
        for (unsigned int qp = 0; qp < qrule.n_points(); qp++)
          final_evals[i_to].push_back(evals[qp]);
      }
    }
  }

  ////////////////////
  // We now have just one or zero mesh function values at all of our local
  // quadrature points.  Stash those values (and a map linking them to element
  // ids) in the equation systems parameters and project the solution.
  ////////////////////

  for (unsigned int i_to = 0; i_to < _to_problems.size(); i_to++)
  {
    _to_es[i_to]->parameters.set<std::vector<Real>*>("final_evals") = & final_evals[i_to];
    _to_es[i_to]->parameters.set<std::map<unsigned int, unsigned int>*>("element_map") = & trimmed_element_maps[i_to];
    projectSolution(i_to);
    _to_es[i_to]->parameters.set<std::vector<Real>*>("final_evals") = NULL;
    _to_es[i_to]->parameters.set<std::map<unsigned int, unsigned int>*>("element_map") = NULL;
  }

  for (unsigned int i = 0; i < _from_problems.size(); i++)
    delete local_meshfuns[i];


  // Make sure all our sends succeeded.
  for (processor_id_type i_proc = 0; i_proc < n_processors(); i_proc++)
  {
    if (i_proc == processor_id())
      continue;
    if (! _qps_cached)
      send_qps[i_proc].wait();
    send_evals[i_proc].wait();
    if (_direction == FROM_MULTIAPP)
      send_ids[i_proc].wait();
  }

  if (_fixed_meshes)
    _qps_cached = true;

  _console << "Finished projection transfer " << name() << std::endl;
}
void
MultiAppProjectionTransfer::assembleL2(EquationSystems & es, const std::string & system_name)
{
  // Get the system and mesh from the input arguments.
  LinearImplicitSystem & system = es.get_system<LinearImplicitSystem>(system_name);
  MeshBase & to_mesh = es.get_mesh();

  // Get the meshfunction evaluations and the map that was stashed in the es.
  std::vector<Real> & final_evals = * es.parameters.get<std::vector<Real>*>("final_evals");
  std::map<unsigned int, unsigned int> & element_map = * es.parameters.get<std::map<unsigned int, unsigned int>*>("element_map");

  // Setup system vectors and matrices.
  FEType fe_type = system.variable_type(0);
  std::unique_ptr<FEBase> fe(FEBase::build(to_mesh.mesh_dimension(), fe_type));
  QGauss qrule(to_mesh.mesh_dimension(), fe_type.default_quadrature_order());
  fe->attach_quadrature_rule(&qrule);
  const DofMap& dof_map = system.get_dof_map();
  DenseMatrix<Number> Ke;
  DenseVector<Number> Fe;
  std::vector<dof_id_type> dof_indices;
  const std::vector<Real> & JxW = fe->get_JxW();
  const std::vector<std::vector<Real> > & phi = fe->get_phi();

  const MeshBase::const_element_iterator end_el = to_mesh.active_local_elements_end();
  for (MeshBase::const_element_iterator el = to_mesh.active_local_elements_begin(); el != end_el; ++el)
  {
    const Elem* elem = *el;
    fe->reinit (elem);

    dof_map.dof_indices (elem, dof_indices);
    Ke.resize (dof_indices.size(), dof_indices.size());
    Fe.resize (dof_indices.size());

    for (unsigned int qp = 0; qp < qrule.n_points(); qp++)
    {
      Real meshfun_eval = 0.;
      if (element_map.find(elem->id()) != element_map.end())
      {
        // We have evaluations for this element.
        meshfun_eval = final_evals[element_map[elem->id()] + qp];
      }

      // Now compute the element matrix and RHS contributions.
      for (unsigned int i=0; i<phi.size(); i++)
      {
        // RHS
        Fe(i) += JxW[qp] * (meshfun_eval * phi[i][qp]);

        if (_compute_matrix)
          for (unsigned int j = 0; j < phi.size(); j++)
          {
            // The matrix contribution
            Ke(i,j) += JxW[qp] * (phi[i][qp] * phi[j][qp]);
          }
      }
      dof_map.constrain_element_matrix_and_vector(Ke, Fe, dof_indices);

      if (_compute_matrix)
        system.matrix->add_matrix(Ke, dof_indices);
      system.rhs->add_vector(Fe, dof_indices);
    }
  }
}
Example #28
0
void ExactSolution::_compute_error(const std::string& sys_name,
				   const std::string& unknown_name,
				   std::vector<Real>& error_vals)
{
  // This function must be run on all processors at once
  parallel_only();

  // Make sure we aren't "overconfigured"
  libmesh_assert (!(_exact_values.size() && _equation_systems_fine));

  // Get a reference to the system whose error is being computed.
  // If we have a fine grid, however, we'll integrate on that instead
  // for more accuracy.
  const System& computed_system = _equation_systems_fine ?
    _equation_systems_fine->get_system(sys_name) :
    _equation_systems.get_system (sys_name);

  const Real time = _equation_systems.get_system(sys_name).time;

  const unsigned int sys_num = computed_system.number();
  const unsigned int var = computed_system.variable_number(unknown_name);
  const unsigned int var_component =
    computed_system.variable_scalar_number(var, 0);

  // Prepare a global solution and a MeshFunction of the coarse system if we need one
  AutoPtr<MeshFunction> coarse_values;
  AutoPtr<NumericVector<Number> > comparison_soln = NumericVector<Number>::build();
  if (_equation_systems_fine)
    {
      const System& comparison_system
	= _equation_systems.get_system(sys_name);

      std::vector<Number> global_soln;
      comparison_system.update_global_solution(global_soln);
      comparison_soln->init(comparison_system.solution->size(), true, SERIAL);
      (*comparison_soln) = global_soln;

      coarse_values = AutoPtr<MeshFunction>
	(new MeshFunction(_equation_systems,
			  *comparison_soln,
			  comparison_system.get_dof_map(),
			  comparison_system.variable_number(unknown_name)));
      coarse_values->init();
    }

  // Initialize any functors we're going to use
  for (unsigned int i=0; i != _exact_values.size(); ++i)
    if (_exact_values[i])
      _exact_values[i]->init();

  for (unsigned int i=0; i != _exact_derivs.size(); ++i)
    if (_exact_derivs[i])
      _exact_derivs[i]->init();

  for (unsigned int i=0; i != _exact_hessians.size(); ++i)
    if (_exact_hessians[i])
      _exact_hessians[i]->init();

  // Get a reference to the dofmap and mesh for that system
  const DofMap& computed_dof_map = computed_system.get_dof_map();

  const MeshBase& _mesh = computed_system.get_mesh();

  const unsigned int dim = _mesh.mesh_dimension();

  // Zero the error before summation
  // 0 - sum of square of function error (L2)
  // 1 - sum of square of gradient error (H1 semi)
  // 2 - sum of square of Hessian error (H2 semi)
  // 3 - sum of sqrt(square of function error) (L1)
  // 4 - max of sqrt(square of function error) (Linfty)
  // 5 - sum of square of curl error (HCurl semi)
  // 6 - sum of square of div error (HDiv semi)
  error_vals = std::vector<Real>(7, 0.);

  // Construct Quadrature rule based on default quadrature order
  const FEType& fe_type  = computed_dof_map.variable_type(var);

  unsigned int n_vec_dim = FEInterface::n_vec_dim( _mesh, fe_type );

  // FIXME: MeshFunction needs to be updated to support vector-valued
  //        elements before we can use a reference solution.
  if( (n_vec_dim > 1) && _equation_systems_fine )
    {
      libMesh::err << "Error calculation using reference solution not yet\n"
		   << "supported for vector-valued elements."
		   << std::endl;
      libmesh_not_implemented();
    }

  AutoPtr<QBase> qrule =
    fe_type.default_quadrature_rule (dim,
                                     _extra_order);

  // Construct finite element object

  AutoPtr<FEGenericBase<OutputShape> > fe(FEGenericBase<OutputShape>::build(dim, fe_type));

  // Attach quadrature rule to FE object
  fe->attach_quadrature_rule (qrule.get());

  // The Jacobian*weight at the quadrature points.
  const std::vector<Real>& JxW                               = fe->get_JxW();

  // The value of the shape functions at the quadrature points
  // i.e. phi(i) = phi_values[i][qp]
  const std::vector<std::vector<OutputShape> >&  phi_values         = fe->get_phi();

  // The value of the shape function gradients at the quadrature points
  const std::vector<std::vector<typename FEGenericBase<OutputShape>::OutputGradient> >& 
		    dphi_values = fe->get_dphi();

  // The value of the shape function curls at the quadrature points
  // Only computed for vector-valued elements
  const std::vector<std::vector<typename FEGenericBase<OutputShape>::OutputShape> >* curl_values = NULL;

  // The value of the shape function divergences at the quadrature points
  // Only computed for vector-valued elements
  const std::vector<std::vector<typename FEGenericBase<OutputShape>::OutputDivergence> >* div_values = NULL;

  if( FEInterface::field_type(fe_type) == TYPE_VECTOR )
    {
      curl_values = &fe->get_curl_phi();
      div_values = &fe->get_div_phi();
    }

#ifdef LIBMESH_ENABLE_SECOND_DERIVATIVES
  // The value of the shape function second derivatives at the quadrature points
  const std::vector<std::vector<typename FEGenericBase<OutputShape>::OutputTensor> >& 
		    d2phi_values = fe->get_d2phi(); 
#endif

  // The XYZ locations (in physical space) of the quadrature points
  const std::vector<Point>& q_point                          = fe->get_xyz();

  // The global degree of freedom indices associated
  // with the local degrees of freedom.
  std::vector<dof_id_type> dof_indices;


  //
  // Begin the loop over the elements
  //
  // TODO: this ought to be threaded (and using subordinate
  // MeshFunction objects in each thread rather than a single
  // master)
  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)
    {
      // Store a pointer to the element we are currently
      // working on.  This allows for nicer syntax later.
      const Elem* elem = *el;

      // reinitialize the element-specific data
      // for the current element
      fe->reinit (elem);

      // Get the local to global degree of freedom maps
      computed_dof_map.dof_indices    (elem, dof_indices, var);

      // The number of quadrature points
      const unsigned int n_qp = qrule->n_points();

      // The number of shape functions
      const unsigned int n_sf = 
	libmesh_cast_int<unsigned int>(dof_indices.size());

      //
      // Begin the loop over the Quadrature points.
      //
      for (unsigned int qp=0; qp<n_qp; qp++)
	{
	  // Real u_h = 0.;
	  // RealGradient grad_u_h;

	  typename FEGenericBase<OutputShape>::OutputNumber u_h = 0.;

	  typename FEGenericBase<OutputShape>::OutputNumberGradient grad_u_h;
#ifdef LIBMESH_ENABLE_SECOND_DERIVATIVES
	  typename FEGenericBase<OutputShape>::OutputNumberTensor grad2_u_h;
#endif
	  typename FEGenericBase<OutputShape>::OutputNumber curl_u_h = 0.0;
	  typename FEGenericBase<OutputShape>::OutputNumberDivergence div_u_h = 0.0;

	  // Compute solution values at the current
	  // quadrature point.  This reqiures a sum
	  // over all the shape functions evaluated
	  // at the quadrature point.
	  for (unsigned int i=0; i<n_sf; i++)
	    {
	      // Values from current solution.
	      u_h      += phi_values[i][qp]*computed_system.current_solution  (dof_indices[i]);
	      grad_u_h += dphi_values[i][qp]*computed_system.current_solution (dof_indices[i]);
#ifdef LIBMESH_ENABLE_SECOND_DERIVATIVES
	      grad2_u_h += d2phi_values[i][qp]*computed_system.current_solution (dof_indices[i]);
#endif
	      if( FEInterface::field_type(fe_type) == TYPE_VECTOR )
		{
		  curl_u_h += (*curl_values)[i][qp]*computed_system.current_solution (dof_indices[i]);
		  div_u_h += (*div_values)[i][qp]*computed_system.current_solution (dof_indices[i]);
		}
	    }

	  // Compute the value of the error at this quadrature point
	  typename FEGenericBase<OutputShape>::OutputNumber exact_val = 0;
	  RawAccessor<typename FEGenericBase<OutputShape>::OutputNumber> exact_val_accessor( exact_val, dim );
          if (_exact_values.size() > sys_num && _exact_values[sys_num])
	    {
	      for( unsigned int c = 0; c < n_vec_dim; c++)
		exact_val_accessor(c) =
		  _exact_values[sys_num]->
		  component(var_component+c, q_point[qp], time);
	    }
	  else if (_equation_systems_fine)
	    {
	      // FIXME: Needs to be updated for vector-valued elements
	      exact_val = (*coarse_values)(q_point[qp]);
	    }
	  const typename FEGenericBase<OutputShape>::OutputNumber val_error = u_h - exact_val;

	  // Add the squares of the error to each contribution
	  Real error_sq = TensorTools::norm_sq(val_error);
	  error_vals[0] += JxW[qp]*error_sq;

	  Real norm = sqrt(error_sq);
	  error_vals[3] += JxW[qp]*norm;

	  if(error_vals[4]<norm) { error_vals[4] = norm; }

	  // Compute the value of the error in the gradient at this
	  // quadrature point
	  typename FEGenericBase<OutputShape>::OutputNumberGradient exact_grad;
	  RawAccessor<typename FEGenericBase<OutputShape>::OutputNumberGradient> exact_grad_accessor( exact_grad, _mesh.spatial_dimension() );
	  if (_exact_derivs.size() > sys_num && _exact_derivs[sys_num])
	    {
	      for( unsigned int c = 0; c < n_vec_dim; c++)
		for( unsigned int d = 0; d < _mesh.spatial_dimension(); d++ )
		  exact_grad_accessor(d + c*_mesh.spatial_dimension() ) =
		    _exact_derivs[sys_num]->
		    component(var_component+c, q_point[qp], time)(d);
	    }
	  else if (_equation_systems_fine)
	    {
	      // FIXME: Needs to be updated for vector-valued elements
	      exact_grad = coarse_values->gradient(q_point[qp]);
	    }

	  const typename FEGenericBase<OutputShape>::OutputNumberGradient grad_error = grad_u_h - exact_grad;
	  
	  error_vals[1] += JxW[qp]*grad_error.size_sq();


	  if( FEInterface::field_type(fe_type) == TYPE_VECTOR )
	    {
	      // Compute the value of the error in the curl at this
	      // quadrature point
	      typename FEGenericBase<OutputShape>::OutputNumber exact_curl = 0.0;
	      if (_exact_derivs.size() > sys_num && _exact_derivs[sys_num])
		{
		  exact_curl = TensorTools::curl_from_grad( exact_grad );
		}
	      else if (_equation_systems_fine)
		{
		  // FIXME: Need to implement curl for MeshFunction and support reference
		  //        solution for vector-valued elements
		}

	      const typename FEGenericBase<OutputShape>::OutputNumber curl_error = curl_u_h - exact_curl;
	      
	      error_vals[5] += JxW[qp]*TensorTools::norm_sq(curl_error);

	      // Compute the value of the error in the divergence at this
	      // quadrature point
	      typename FEGenericBase<OutputShape>::OutputNumberDivergence exact_div = 0.0;
	      if (_exact_derivs.size() > sys_num && _exact_derivs[sys_num])
		{
		  exact_div = TensorTools::div_from_grad( exact_grad );
		}
	      else if (_equation_systems_fine)
		{
		  // FIXME: Need to implement div for MeshFunction and support reference
		  //        solution for vector-valued elements
		}
	      
	      const typename FEGenericBase<OutputShape>::OutputNumberDivergence div_error = div_u_h - exact_div;
	      
	      error_vals[6] += JxW[qp]*TensorTools::norm_sq(div_error);
	    }

#ifdef LIBMESH_ENABLE_SECOND_DERIVATIVES
	  // Compute the value of the error in the hessian at this
	  // quadrature point
	  typename FEGenericBase<OutputShape>::OutputNumberTensor exact_hess;
	  RawAccessor<typename FEGenericBase<OutputShape>::OutputNumberTensor> exact_hess_accessor( exact_hess, dim );
	  if (_exact_hessians.size() > sys_num && _exact_hessians[sys_num])
	    {
	      //FIXME: This needs to be implemented to support rank 3 tensors 
	      //       which can't happen until type_n_tensor is fully implemented
	      //       and a RawAccessor<TypeNTensor> is fully implemented
	      if( FEInterface::field_type(fe_type) == TYPE_VECTOR )
		libmesh_not_implemented();

	      for( unsigned int c = 0; c < n_vec_dim; c++)
		for( unsigned int d = 0; d < dim; d++ )
		  for( unsigned int e =0; e < dim; e++ )
		    exact_hess_accessor(d + e*dim + c*dim*dim) =
		      _exact_hessians[sys_num]->
		      component(var_component+c, q_point[qp], time)(d,e);
	    }
	  else if (_equation_systems_fine)
	    {
	      // FIXME: Needs to be updated for vector-valued elements
	      exact_hess = coarse_values->hessian(q_point[qp]);
	    }
	  
	  const typename FEGenericBase<OutputShape>::OutputNumberTensor grad2_error = grad2_u_h - exact_hess;
	  
	  // FIXME: PB: Is this what we want for rank 3 tensors?
	  error_vals[2] += JxW[qp]*grad2_error.size_sq();
#endif

	} // end qp loop
    } // end element loop

  // Add up the error values on all processors, except for the L-infty
  // norm, for which the maximum is computed.
  Real l_infty_norm = error_vals[4];
  CommWorld.max(l_infty_norm);
  CommWorld.sum(error_vals);
  error_vals[4] = l_infty_norm;
}
Example #29
0
void
RichardsMaterial::computeProperties()
{
  // Grab reference to linear Lagrange finite element object pointer,
  // currently this is always a linear Lagrange element, so this might need to
  // be generalized if we start working with higher-order elements...
  FEBase * & fe(_assembly.getFE(getParam<bool>("linear_shape_fcns") ? FEType(FIRST, LAGRANGE) : FEType(SECOND, LAGRANGE), _current_elem->dim()));

  // Grab references to FE object's mapping data from the _subproblem's FE object
  const std::vector<Real>& dxidx(fe->get_dxidx());
  const std::vector<Real>& dxidy(fe->get_dxidy());
  const std::vector<Real>& dxidz(fe->get_dxidz());
  const std::vector<Real>& detadx(fe->get_detadx());
  const std::vector<Real>& detady(fe->get_detady());
  const std::vector<Real>& detadz(fe->get_detadz());
  const std::vector<Real>& dzetadx(fe->get_dzetadx());
  const std::vector<Real>& dzetady(fe->get_dzetady());
  const std::vector<Real>& dzetadz(fe->get_dzetadz());

  // this gets run for each element
  for (unsigned int qp=0; qp<_qrule->n_points(); qp++)
  {

    _porosity[qp] = _material_por + (*_por_change)[qp];
    _porosity_old[qp] = _material_por + (*_por_change_old)[qp];

    _permeability[qp] = _material_perm;
    for (unsigned int i=0; i<3; i++)
      for (unsigned int j=0; j<3; j++)
        _permeability[qp](i,j) *= std::pow(10,(*_perm_change[3*i+j])[qp]);

    _gravity[qp] = _material_gravity;

    _viscosity[qp].resize(_num_p);

    _density_old[qp].resize(_num_p);
    _density[qp].resize(_num_p);
    _ddensity[qp].resize(_num_p);
    _d2density[qp].resize(_num_p);

    _rel_perm[qp].resize(_num_p);
    _drel_perm[qp].resize(_num_p);
    _d2rel_perm[qp].resize(_num_p);

    _seff_old[qp].resize(_num_p);
    _seff[qp].resize(_num_p);
    _dseff[qp].resize(_num_p);
    _d2seff[qp].resize(_num_p);

    _sat_old[qp].resize(_num_p);
    _sat[qp].resize(_num_p);
    _dsat[qp].resize(_num_p);
    _d2sat[qp].resize(_num_p);


    for (unsigned int i=0 ; i<_num_p; ++i)
    {
      _viscosity[qp][i] = _material_viscosity[i];

      _density_old[qp][i] = (*_material_density_UO[i]).density((*_pressure_old_vals[i])[qp]);
      _density[qp][i] = (*_material_density_UO[i]).density((*_pressure_vals[i])[qp]);
      _ddensity[qp][i] = (*_material_density_UO[i]).ddensity((*_pressure_vals[i])[qp]);
      _d2density[qp][i] = (*_material_density_UO[i]).d2density((*_pressure_vals[i])[qp]);

      _seff_old[qp][i] = (*_material_seff_UO[i]).seff(_pressure_old_vals, qp);
      _seff[qp][i] = (*_material_seff_UO[i]).seff(_pressure_vals, qp);

      _dseff[qp][i].resize(_num_p);
      _dseff[qp][i] = (*_material_seff_UO[i]).dseff(_pressure_vals, qp);

      _d2seff[qp][i].resize(_num_p);
      for (unsigned int j=0 ; j<_num_p; ++j)
      {
        _d2seff[qp][i][j].resize(_num_p);
      }
      _d2seff[qp][i] = (*_material_seff_UO[i]).d2seff(_pressure_vals, qp);

      _sat_old[qp][i] = (*_material_sat_UO[i]).sat(_seff_old[qp][i]);
      _sat[qp][i] = (*_material_sat_UO[i]).sat(_seff[qp][i]);
      //Moose::out << "qp= " << qp << " i= " << i << " pressure= " << (*_pressure_vals[0])[qp] << " " << (*_pressure_vals[1])[qp] << " sat= " << _sat[qp][i] << "\n";
      _dsat[qp][i].resize(_num_p);
      for (unsigned int j=0 ; j<_num_p; ++j)
      {
        _dsat[qp][i][j] = (*_material_sat_UO[i]).dsat(_seff[qp][i])*_dseff[qp][i][j]; // could optimise
      }
      _d2sat[qp][i].resize(_num_p);
      for (unsigned int j=0 ; j<_num_p; ++j)
      {
        _d2sat[qp][i][j].resize(_num_p);
        for (unsigned int k=0 ; k<_num_p; ++k)
        {
          _d2sat[qp][i][j][k] = (*_material_sat_UO[i]).d2sat(_seff[qp][i])*_dseff[qp][i][j]*_dseff[qp][i][k] + (*_material_sat_UO[i]).dsat(_seff[qp][i])*_d2seff[qp][i][j][k];
        }
      }

      _rel_perm[qp][i] = (*_material_relperm_UO[i]).relperm(_seff[qp][i]);
      _drel_perm[qp][i] = (*_material_relperm_UO[i]).drelperm(_seff[qp][i]);
      _d2rel_perm[qp][i] =(* _material_relperm_UO[i]).d2relperm(_seff[qp][i]);

    }


    // Now SUPG stuff
    _tauvel_SUPG[qp].resize(_num_p);
    _dtauvel_SUPG_dgradp[qp].resize(_num_p);
    _dtauvel_SUPG_dp[qp].resize(_num_p);

    // Bounds checking on element data and putting into vector form
    mooseAssert(qp < dxidx.size(), "Insufficient data in dxidx array!");
    mooseAssert(qp < dxidy.size(), "Insufficient data in dxidy array!");
    mooseAssert(qp < dxidz.size(), "Insufficient data in dxidz array!");
    if (_mesh.dimension() >= 2)
    {
      mooseAssert(qp < detadx.size(), "Insufficient data in detadx array!");
      mooseAssert(qp < detady.size(), "Insufficient data in detady array!");
      mooseAssert(qp < detadz.size(), "Insufficient data in detadz array!");
    }
    if (_mesh.dimension() >= 3)
    {
      mooseAssert(qp < dzetadx.size(), "Insufficient data in dzetadx array!");
      mooseAssert(qp < dzetady.size(), "Insufficient data in dzetady array!");
      mooseAssert(qp < dzetadz.size(), "Insufficient data in dzetadz array!");
    }

    // CHECK : Does this work spherical, cylindrical, etc?
    RealVectorValue xi_prime(dxidx[qp], dxidy[qp], dxidz[qp]);
    RealVectorValue eta_prime, zeta_prime;
    if (_mesh.dimension() >= 2)
    {
      eta_prime(0) = detadx[qp];
      eta_prime(1) = detady[qp];
    }
    if (_mesh.dimension() == 3)
    {
      eta_prime(2) = detadz[qp];
      zeta_prime(0) = dzetadx[qp];
      zeta_prime(1) = dzetady[qp];
      zeta_prime(2) = dzetadz[qp];
    }

    for (unsigned int i=0 ; i<_num_p; ++i)
    {
      RealVectorValue vel = (*_material_SUPG_UO[i]).velSUPG(_permeability[qp], (*_grad_p[i])[qp], _density[qp][i], _gravity[qp]);
      RealTensorValue dvel_dgradp = (*_material_SUPG_UO[i]).dvelSUPG_dgradp(_permeability[qp]);
      RealVectorValue dvel_dp = (*_material_SUPG_UO[i]).dvelSUPG_dp(_permeability[qp], _ddensity[qp][i], _gravity[qp]);
      RealVectorValue bb = (*_material_SUPG_UO[i]).bb(vel, _mesh.dimension(), xi_prime, eta_prime, zeta_prime);
      RealVectorValue dbb2_dgradp = (*_material_SUPG_UO[i]).dbb2_dgradp(vel, dvel_dgradp, xi_prime, eta_prime, zeta_prime);
      Real dbb2_dp = (*_material_SUPG_UO[i]).dbb2_dp(vel, dvel_dp, xi_prime, eta_prime, zeta_prime);
      Real tau = (*_material_SUPG_UO[i]).tauSUPG(vel, _trace_perm, bb);
      RealVectorValue dtau_dgradp = (*_material_SUPG_UO[i]).dtauSUPG_dgradp(vel, dvel_dgradp, _trace_perm, bb, dbb2_dgradp);
      Real dtau_dp = (*_material_SUPG_UO[i]).dtauSUPG_dp(vel, dvel_dp, _trace_perm, bb, dbb2_dp);

      _tauvel_SUPG[qp][i] = tau*vel;

      _dtauvel_SUPG_dgradp[qp][i] = tau*dvel_dgradp;
      for (unsigned int j=0 ; j<3; ++j)
        for (unsigned int k=0 ; k<3; ++k)
          _dtauvel_SUPG_dgradp[qp][i](j,k) += dtau_dgradp(j)*vel(k); // this is outerproduct - maybe libmesh can do it better?

      _dtauvel_SUPG_dp[qp][i] = dtau_dp*vel + tau*dvel_dp;
    }
  }
}
Example #30
0
int main(int argc, char **argv)
{
#ifdef QUESO_HAVE_LIBMESH
  unsigned int i, j;
  QUESO::EnvOptionsValues opts;
  opts.m_seed = -1;

#ifdef QUESO_HAS_MPI
  MPI_Init(&argc, &argv);
  QUESO::FullEnvironment env(MPI_COMM_WORLD, "", "", &opts);
#else
  QUESO::FullEnvironment env("", "", &opts);
#endif

#ifdef LIBMESH_DEFAULT_SINGLE_PRECISION
  // SLEPc currently gives us a nasty crash with Real==float
  libmesh_example_assert(false, "--disable-singleprecision");
#endif

// Need an artificial block here because libmesh needs to
// call PetscFinalize before we call MPI_Finalize
#ifdef LIBMESH_HAVE_SLEPC
{
  libMesh::LibMeshInit init(argc, argv);

  libMesh::Mesh mesh(init.comm());
  libMesh::MeshTools::Generation::build_square(mesh,
      20, 20, 0.0, 1.0, 0.0, 1.0, libMeshEnums::QUAD4);

  QUESO::FunctionOperatorBuilder builder;

  builder.order = "FIRST";
  builder.family = "LAGRANGE";
  builder.num_req_eigenpairs = 10;

  QUESO::LibMeshNegativeLaplacianOperator precision(builder, mesh);

  libMesh::EquationSystems & es = precision.get_equation_systems();
  libMesh::CondensedEigenSystem & eig_sys = es.get_system<libMesh::CondensedEigenSystem>(
      "Eigensystem");

  // Check all eigenfunctions have unit L2 norm
  std::vector<double> norms(builder.num_req_eigenpairs, 0);
  for (i = 0; i < builder.num_req_eigenpairs; i++) {
    eig_sys.get_eigenpair(i);
    norms[i] = eig_sys.calculate_norm(*eig_sys.solution,
                                      libMesh::SystemNorm(libMeshEnums::L2));
    if (abs(norms[i] - 1.0) > TEST_TOL) {
      return 1;
    }
  }

  const unsigned int dim = mesh.mesh_dimension();
  const libMesh::DofMap & dof_map = eig_sys.get_dof_map();
  libMesh::FEType fe_type = dof_map.variable_type(0);
  libMesh::AutoPtr<libMesh::FEBase> fe(libMesh::FEBase::build(dim, fe_type));
  libMesh::QGauss qrule(dim, libMeshEnums::FIFTH);
  fe->attach_quadrature_rule(&qrule);
  const std::vector<libMesh::Real> & JxW = fe->get_JxW();
  const std::vector<std::vector<libMesh::Real> >& phi = fe->get_phi();

  libMesh::AutoPtr<libMesh::NumericVector<libMesh::Real> > u, v;
  double ui = 0.0;
  double vj = 0.0;
  double ip = 0.0;

  for (i = 0; i < builder.num_req_eigenpairs - 1; i++) {
    eig_sys.get_eigenpair(i);
    u = eig_sys.solution->clone();
    for (j = i + 1; j < builder.num_req_eigenpairs; j++) {
      libMesh::MeshBase::const_element_iterator el = mesh.active_local_elements_begin();
      libMesh::MeshBase::const_element_iterator end_el = mesh.active_local_elements_end();
      eig_sys.get_eigenpair(j);
      v = eig_sys.solution->clone();
      for ( ; el != end_el; ++el) {
        const libMesh::Elem * elem = *el;
        fe->reinit(elem);
        for (unsigned int qp = 0; qp < qrule.n_points(); qp++) {
          for (unsigned int dof = 0; dof < phi.size(); dof++) {
            ui += (*u)(dof) * phi[dof][qp];
            vj += (*v)(dof) * phi[dof][qp];
          }
          ip += ui * vj * JxW[qp];
          ui = 0.0;
          vj = 0.0;
        }
      }
      std::cerr << "INTEGRAL of " << i << " against " << j << " is: " << ip << std::endl;
      if (abs(ip) > INTEGRATE_TOL) {
        return 1;
      }
      ip = 0.0;
    }
  }
}
#endif  // LIBMESH_HAVE_SLEPC
#ifdef QUESO_HAS_MPI
  MPI_Finalize();
#endif
  return 0;
#else
  return 77;
#endif
}