void Framework::update(){ OStringStream o; o << "aho" << endl; //const char* char ts[ 3 ]; ts[ 0 ] = 'O'; ts[ 1 ] = 'K'; ts[ 2 ] = '\0'; o << ts << endl; //char* o << string( "baka" ) << endl; //string o << RefString( "tonma" ) << endl; //RefString o << 'a' << endl; //char o << '\n'; //char ( new-line ) o << static_cast< char >( -74 ) << endl; //char (out of range ) o << static_cast< char >( 14 ) << endl; //char (out of range ) o << static_cast< unsigned char >( 99 ) << endl; //unsigned char o << static_cast< short >( -9999 ) << endl; //short o << static_cast< unsigned short >( 65534 ) << endl; //unsigned short o << static_cast< int >( -2012345678 ) << endl; //int o << static_cast< unsigned >( 4012345678 ) << endl; //unsigned o.precision( 7 ); o << 50.00000000000 << endl; o << 0.09999999999f << endl; o << 0.0399999999f << endl; o << 1.f << endl; //float ( 1 ) o << 1.5f << endl; //float ( 1 ) o << 1.75f << endl; //float ( 1 ) o << 152423.f << endl; //float ( 1 ) o << -123456789.f * 1000000.f << endl; //float (big) o << -1.23456789f * 0.000000001f << endl; //float (small) // o.precision( 15 ); o << -1.23456789f * 0.000000001f << endl; //float (small) o << -134.56712839f << endl; o << -0.056712839f << endl; o << 0.0 << endl; //float +0 o << -0.0 << endl; //float -0 o << sqrtf( -1.f ) << endl; //float NaN o << -1e30f * 1e30f << endl; //float +Inf o << 1e-30f * 1e-30f << endl; //float -Denorm o << -numeric_limits< float >::max() << endl; //float max o << numeric_limits< float >::min() << endl; //float min o << -123456789.0 * 1000000.0 << endl; //double (big) o << -1.234567890 * 0.000000001 << endl; //double (small) o << 0.0 << endl; //double +0 o << -0.0 << endl; //double -0 o << sqrt( -1.0 ) << endl; //double NaN o << -1e300 * 1e300 << endl; //double +Inf o << 1e-300 * 1e-300 << endl; //double -Denorm o << -numeric_limits< double >::max() << endl; //double max Array< char > out; o.get( &out ); cout << &out[ 0 ] << endl; cout << o << endl; requestEnd(); }
static std::string toString(const std::vector<DATA> &values) { OStringStream ost; for (auto v : values) ost << "'" << v << "' "; // adds quote around the string to see whitespace return ost.str(); }
Ostream& writeData( Ostream &o, Type value, const string annotation, const word header, bool newLine=false ) { const label annotationLen=25; if(annotation!="") { o << annotation.c_str(); for(label i=0;i<(annotationLen-label(annotation.size()));i++) { o << " "; } } writeValue(o,value); for(direction i=0;i<pTraits<Type>::nComponents;i++) { scalar v=component(value,i); csvHeader+=","+header; if(pTraits<Type>::nComponents>1) { csvHeader+=string(" ")+pTraits<Type>::componentNames[i]; } OStringStream s; s << v; csvLine+=","+s.str(); } if(newLine) { o << endl; } return o; }
const Foam::fvPatchField<Type>& Foam::codedFixedValueFvPatchField<Type>::redirectPatchField() const { if (!redirectPatchFieldPtr_.valid()) { // Construct a patch // Make sure to construct the patchfield with up-to-date value OStringStream os; os.writeKeyword("type") << redirectType_ << token::END_STATEMENT << nl; static_cast<const Field<Type>&>(*this).writeEntry("value", os); IStringStream is(os.str()); dictionary dict(is); redirectPatchFieldPtr_.set ( fvPatchField<Type>::New ( this->patch(), this->dimensionedInternalField(), dict ).ptr() ); } return redirectPatchFieldPtr_(); }
std::string StringTools::toString( double value ) { OStringStream stream; stream << value; return stream.str(); }
const Foam::mixedFvPatchField<Type>& Foam::codedMixedFvPatchField<Type>::redirectPatchField() const { if (!redirectPatchFieldPtr_.valid()) { // Construct a patch // Make sure to construct the patchfield with up-to-date value // Write the data from the mixed b.c. OStringStream os; mixedFvPatchField<Type>::write(os); IStringStream is(os.str()); // Construct dictionary from it. dictionary dict(is); // Override the type to enforce the fvPatchField::New constructor // to choose our type dict.set("type", name_); redirectPatchFieldPtr_.set ( dynamic_cast<mixedFvPatchField<Type>*> ( fvPatchField<Type>::New ( this->patch(), this->internalField(), dict ).ptr() ) ); } return redirectPatchFieldPtr_(); }
String XMLNodeImpl::toString() const { OStringStream ss; printNode( ss ); return ss.releaseString(); }
void Foam::vtkPVblockMesh::updateInfoEdges ( vtkDataArraySelection* arraySelection ) { if (debug) { Info<< "<beg> Foam::vtkPVblockMesh::updateInfoEdges" << " [meshPtr=" << (meshPtr_ ? "set" : "NULL") << "]" << endl; } arrayRangeEdges_.reset( arraySelection->GetNumberOfArrays() ); const blockMesh& blkMesh = *meshPtr_; const curvedEdgeList& edges = blkMesh.edges(); const int nEdges = edges.size(); forAll(edges, edgeI) { OStringStream ostr; ostr<< edges[edgeI].start() << ":" << edges[edgeI].end() << " - " << edges[edgeI].type(); // Add "beg:end - type" to GUI list arraySelection->AddArray(ostr.str().c_str()); }
Foam::primitiveEntry::primitiveEntry(const keyType& keyword, const T& t) : entry(keyword), ITstream(keyword, tokenList(10)) { OStringStream os; os << t << token::END_STATEMENT; readEntry(dictionary::null, IStringStream(os.str())()); }
void Assertion::ASSERT_ANY_COMPARE(const ROAnything &inputAny, const ROAnything &masterAny, String location, char delimSlot, char idxdelim) { OStringStream s; String failingPath(location); if(!AnyUtils::AnyCompareEqual(inputAny, masterAny, failingPath,&s, delimSlot, idxdelim)) { String strfail(failingPath); strfail << "\n" << s.str(); ASSERTM((const char*)strfail, false); } }
static std::string toString(const EERIEMATRIX &matrix) { OStringStream ost; ost << std::endl << std::fixed; ost << matrix._11 << "\t" << matrix._12 << "\t" << matrix._13 << "\t" << matrix._14 << std::endl; ost << matrix._21 << "\t" << matrix._22 << "\t" << matrix._23 << "\t" << matrix._24 << std::endl; ost << matrix._31 << "\t" << matrix._32 << "\t" << matrix._33 << "\t" << matrix._34 << std::endl; ost << matrix._41 << "\t" << matrix._42 << "\t" << matrix._43 << "\t" << matrix._44 << std::endl; return ost.str(); }
Foam::string Foam::stringOps::getVariable ( const word& name, const dictionary& dict, const bool allowEnvVars, const bool allowEmpty ) { string value; const entry* ePtr = dict.lookupScopedEntryPtr ( name, true, false ); if (ePtr) { OStringStream buf; // Force floating point numbers to be printed with at least // some decimal digits. buf << fixed; buf.precision(IOstream::defaultPrecision()); // fail for non-primitiveEntry dynamicCast<const primitiveEntry> ( *ePtr ).write(buf, true); value = buf.str(); } else if (allowEnvVars) { value = getEnv(name); if (value.empty()) { FatalIOErrorInFunction ( dict ) << "Cannot find dictionary or environment variable " << name << exit(FatalIOError); } } else { FatalIOErrorInFunction ( dict ) << "Cannot find dictionary variable " << name << exit(FatalIOError); } return value; }
void HTTPClient::sendAuthorization() { if ( !m_sAuthorization.empty()) { OStringStream ostr; ostr << m_sAuthorization << " "; if ( m_sAuthorization == "Basic" ) { getCredentialsIfNecessary(); ostr << HTTPUtils::base64Encode( m_url.principal + ":" + m_url.credential ); } #ifndef OW_DISABLE_DIGEST else if ( m_sAuthorization == "Digest" ) { String sNonceCount; sNonceCount.format( "%08x", m_iDigestNonceCount ); HTTPUtils::DigestCalcResponse( m_sDigestSessionKey, m_sDigestNonce, sNonceCount, m_sDigestCNonce, "auth", m_requestMethod, m_httpPath, "", m_sDigestResponse ); ostr << "username=\"" << m_url.principal << "\", "; ostr << "realm=\"" << m_sRealm << "\", "; ostr << "nonce=\"" << m_sDigestNonce << "\", "; ostr << "uri=\"" + m_httpPath + ", "; ostr << "qop=\"auth\", "; ostr << "nc=" << sNonceCount << ", "; ostr << "cnonce=\"" << m_sDigestCNonce << "\", "; ostr << "response=\"" << m_sDigestResponse << "\""; m_iDigestNonceCount++; } #endif else if (m_sAuthorization == "OWLocal") { if (m_localNonce.empty()) { // first round - we just send our euid ostr << "uid=\"" << UserUtils::getEffectiveUserId() << "\""; } else { // second round - send the nonce and the cookie // first try to read the cookie std::ifstream cookieFile(m_localCookieFile.c_str()); if (!cookieFile) { OW_THROW_ERR(HTTPException, Format("Unable to open local authentication file: %1", strerror(errno)).c_str(), m_statusCode); } String cookie = String::getLine(cookieFile); ostr << "nonce=\"" << m_localNonce << "\", "; ostr << "cookie=\"" << cookie << "\""; } } addHeaderNew("Authorization", ostr.toString()); } }
CPPUNIT_NS_BEGIN std::string StringTools::toString( int value ) { OStringStream stream; stream << value; return stream.str(); }
explicit set_args_(const Range &args) { OStringStream os; boost::for_each(args, boost::bind(&set_args_::add, this, _1, boost::ref(os))); String s = os.str(); cmd_line_.reset(new Char[s.size() + 1]); boost::copy(s, cmd_line_.get()); cmd_line_[s.size()] = 0; }
Foam::PtrList<Foam::dictionary> Foam::blockMesh::patchDicts() const { const polyPatchList& patchTopologies = topology().boundaryMesh(); PtrList<dictionary> patchDicts(patchTopologies.size()); forAll(patchTopologies, patchI) { OStringStream os; patchTopologies[patchI].write(os); IStringStream is(os.str()); patchDicts.set(patchI, new dictionary(is)); }
bool Foam::functionEntries::calcEntry::execute ( const dictionary& parentDict, primitiveEntry& entry, Istream& is ) { dictionary args(parentDict, is); OStringStream resultStream; resultStream << (args.lookup("x")[0].number() + args.lookup("y")[0].number()); entry.read(parentDict, IStringStream(resultStream.str())()); return true; }
String::String(UInt64 val) : m_buf(NULL) { #if defined(OW_INT64_IS_LONG) char tmpbuf[32]; ::snprintf(tmpbuf, sizeof(tmpbuf), "%lu", val); m_buf = new ByteBuf(tmpbuf); #elif defined(OW_INT64_IS_LONG_LONG) // unfortunately not all C libraries support long long with snprintf(). // but the C++ iostream library handles it. OStringStream ss; ss << val; m_buf = new ByteBuf(ss.c_str()); #endif }
string groovyBCCommon<Type>::nullValue() { if(string(pTraits<Type>::typeName)==string("vector")) { return string("vector(0,0,0)"); } else if(string(pTraits<Type>::typeName)==string("tensor")) { return string("tensor(0,0,0,0,0,0,0,0,0)"); } else if(string(pTraits<Type>::typeName)==string("symmTensor")) { return string("symmTensor(0,0,0,0,0,0)"); } else if(string(pTraits<Type>::typeName)==string("sphericalTensor")) { return string("sphericalTensor(0)"); } else { OStringStream tmp; tmp << pTraits<Type>::zero; return tmp.str(); } }
Foam::string Foam::Reaction<ReactionThermo>::reactionStr ( OStringStream& reaction ) const { reactionStrLeft(reaction); reaction << " = "; reactionStrRight(reaction); return reaction.str(); }
forAll(fractionBiggerThan,i) { scalar value=fractionBiggerThan[i]; NumericAccumulationNamedEnum::accuSpecification bigger( NumericAccumulationNamedEnum::numBigger, value ); NumericAccumulationNamedEnum::accuSpecification wbigger( NumericAccumulationNamedEnum::numWeightedBigger, value ); OStringStream annotation; annotation << "x > " << value << " | weighted"; writeData( Info,calculator(bigger), annotation.str(),NumericAccumulationNamedEnum::toString(bigger)); Info << " | "; writeData( Info,calculator(wbigger), "",NumericAccumulationNamedEnum::toString(wbigger),true); }
bool LeaderFollowerPool::InitReactor(ROAnything args) { StartTrace(LeaderFollowerPool.InitReactor); TraceAny(args, "Init arguments:"); long argSz = args.GetSize(); if (argSz <= 0) { Trace("argSz:[" << argSz << "]"); SYSERROR("no acceptors: argument <= 0"); return false; } if (!fReactor) { Trace("Reactor not set"); SYSERROR("Reactor not set"); return false; } for (long i = 0; i < argSz; ++i) { Acceptor *acceptor = (Acceptor *) args[i].AsIFAObject(0); if (acceptor) { int retVal; if ((retVal = acceptor->PrepareAcceptLoop()) != 0) { String logMsg; logMsg << "server (" << args.SlotName(i) << ") prepare accept failed with retVal " << (long) retVal; SYSERROR(logMsg); Trace(logMsg); return false; } // start the accept loop OStringStream os; os << std::setw(20) << args.SlotName(i) << " Accepting requests from: " << acceptor->GetAddress() << " port: " << acceptor->GetPort() << " backlog: " << acceptor->GetBacklog() << std::endl; SystemLog::WriteToStderr(os.str()); fReactor->RegisterHandle(acceptor); } else { return false; } } return true; }
void Foam::equationReader::fatalParseError ( const label index, const tokenList& tl, const label fromToken, const label toToken, const string& errorIn, const OStringStream& description ) const { OStringStream errorMessage; forAll(tl, i) { if (i == fromToken) { errorMessage << "<"; } if (tl[i].isPunctuation() && tl[i].pToken() == token::COLON) { errorMessage << "^"; } else { errorMessage << tl[i]; } if (i == toToken) { errorMessage << ">"; } } FatalErrorIn(errorIn) << "Parsing error in the equation for " << operator[](index).name() << ", given by:" << endl << endl << token::TAB << operator[](index).rawText() << endl << endl << "Error occurs withing the < angle brackets >:" << endl << endl << token::TAB << errorMessage.str() << endl << endl << description.str() << abort(FatalError); }
void OW_StringStreamTestCases::testSomething() { OStringStream ss; ss << "O"; unitAssert(ss.length() == 1); unitAssert(ss.toString().equals("O")); ss.reset(); unitAssert(ss.length() == 0); unitAssert(ss.toString().equals("")); ss << String("Hello World"); unitAssert(ss.length() == 11); unitAssert(ss.toString().equals("Hello World")); }
Foam::string Foam::solidReaction<ReactionThermo>::solidReactionStr ( OStringStream& reaction ) const { this->reactionStrLeft(reaction); if (glhs().size() > 0) { reaction << " + "; solidReactionStrLeft(reaction); } reaction << " = "; this->reactionStrRight(reaction); if (grhs().size() > 0) { reaction << " + "; solidReactionStrRight(reaction); } return reaction.str(); }
int main() { HASHTABLE_CLASS<double> table1(13); table1.insert("aaa", 1.0); table1.insert("aba", 2.0); table1.insert("aca", 3.0); table1.insert("ada", 4.0); table1.insert("aeq", 5.0); table1.insert("aaw", 6.0); table1.insert("abs", 7.0); table1.insert("acr", 8.0); table1.insert("adx", 9.0); table1.insert("aec", 10.0); table1.erase("aaw"); table1.erase("abs"); Info<< "\ntable1 toc: " << table1.toc() << endl; table1.printInfo(Info) << "table1 [" << table1.size() << "] " << endl; forAllIter(HASHTABLE_CLASS<double>, table1, iter) { Info<< iter.key() << " => " << iter() << nl; } table1.set("acr", 108); table1.set("adx", 109); table1.set("aec", 100); table1("aaw") -= 1000; table1("aeq") += 1000; Info<< "\noverwrote some values table1: " << table1 << endl; Info<< "\ntest find:" << endl; Info<< table1.find("aaa")() << nl << table1.find("aba")() << nl << table1.find("aca")() << nl << table1.find("ada")() << nl << table1.find("aeq")() << nl << table1.find("acr")() << nl << table1.find("adx")() << nl << table1.find("aec")() << nl << table1["aaa"] << nl; { OStringStream os; os << table1; HASHTABLE_CLASS<double> readTable(IStringStream(os.str())(), 100); Info<< "Istream constructor:" << readTable << endl; } HASHTABLE_CLASS<double> table2(table1); HASHTABLE_CLASS<double> table3(table1.xfer()); Info<< "\ncopy table1 -> table2" << nl << "transfer table1 -> table3 via the xfer() method" << nl; Info<< "\ntable1" << table1 << nl << "\ntable2" << table2 << nl << "\ntable3" << table3 << nl; Info<< "\nerase table2 by iterator" << nl; forAllIter(HASHTABLE_CLASS<double>, table2, iter) { Info<< "erasing " << iter.key() << " => " << iter() << " ... "; table2.erase(iter); Info<< "erased" << endl; }
int main(int argc, char *argv[]) { #include "setRootCase.H" #include "createTime.H" Info<< "Create mesh, no clear-out\n" << endl; fvMesh mesh ( IOobject ( fvMesh::defaultRegion, runTime.timeName(), runTime, IOobject::MUST_READ ) ); Info<< mesh.C() << endl; Info<< mesh.V() << endl; surfaceVectorField Cf = mesh.Cf(); Info<< Cf << endl; // Test construct from cellShapes { pointField points(mesh.points()); cellShapeList shapes(mesh.cellShapes()); const polyBoundaryMesh& pbm = mesh.boundaryMesh(); faceListList boundaryFaces(pbm.size()); forAll(pbm, patchI) { boundaryFaces[patchI] = pbm[patchI]; } wordList boundaryPatchNames(pbm.names()); PtrList<dictionary> boundaryDicts(pbm.size()); forAll(pbm, patchI) { OStringStream os; os << pbm[patchI]; IStringStream is(os.str()); boundaryDicts.set(patchI, new dictionary(is)); } word defaultBoundaryPatchName = "defaultFaces"; word defaultBoundaryPatchType = emptyPolyPatch::typeName; fvMesh newMesh ( IOobject ( "newMesh", runTime.timeName(), runTime, Foam::IOobject::NO_READ ), Xfer<pointField>(points), shapes, boundaryFaces, boundaryPatchNames, boundaryDicts, defaultBoundaryPatchName, defaultBoundaryPatchType ); Info<< newMesh.C() << endl; Info<< newMesh.V() << endl; surfaceVectorField Cf = newMesh.Cf(); Info<< Cf << endl; }
void reportValues( const word &fieldName, const fvMesh &mesh, CommonValueExpressionDriver &driver, const string &entName ) { startLine( mesh.time(), entName ); Field<Type> result( driver.evaluate<Type>(fieldName) ); AccumulationCalculation<Type> calculator( result, false, driver ); writeData(Info,calculator.size(),"Size | Weight Sum","size"); Info << " | "; writeData(Info,calculator.weightSum(),"","weight_sum",true); writeData(Info,calculator.minimum(),"Range (min-max)","minimum"); Info << " | "; writeData(Info,calculator.maximum(),"","maximum",true); writeData( Info,calculator.average(), "Average | weighted","average"); Info << " | "; writeData( Info,calculator.weightedAverage(), "","average_weighted",true); writeData( Info,calculator.sum(), "Sum | weighted","sum"); Info << " | "; writeData( Info,calculator.weightedSum(), "","sum_weighted",true); writeData( Info,calculator.distribution().median(), "Median | weighted","median"); Info << " | "; writeData( Info,calculator.weightedDistribution().median(), "","median_weighted",true); if(nrOfQuantiles) { scalar dx=1./nrOfQuantiles; for(label i=1;i<nrOfQuantiles;i++) { scalar thisQuantile=dx*i; NumericAccumulationNamedEnum::accuSpecification quant( NumericAccumulationNamedEnum::numQuantile, thisQuantile ); NumericAccumulationNamedEnum::accuSpecification wquant( NumericAccumulationNamedEnum::numWeightedQuantile, thisQuantile ); OStringStream annotation; annotation << thisQuantile << " quantile | weighted"; writeData( Info,calculator(quant), annotation.str(),NumericAccumulationNamedEnum::toString(quant)); Info << " | "; writeData( Info,calculator(wquant), "",NumericAccumulationNamedEnum::toString(wquant),true); } } forAll(fractionSmallerThan,i) { scalar value=fractionSmallerThan[i]; NumericAccumulationNamedEnum::accuSpecification smaller( NumericAccumulationNamedEnum::numSmaller, value ); NumericAccumulationNamedEnum::accuSpecification wsmaller( NumericAccumulationNamedEnum::numWeightedSmaller, value ); OStringStream annotation; annotation << "x <= " << value << " | weighted"; writeData( Info,calculator(smaller), annotation.str(),NumericAccumulationNamedEnum::toString(smaller)); Info << " | "; writeData( Info,calculator(wsmaller), "",NumericAccumulationNamedEnum::toString(wsmaller),true); }
int main(int argc, char** argv) { // Initialize libMesh. LibMeshInit init (argc, argv); // Skip adaptive examples on a non-adaptive libMesh build #ifndef LIBMESH_ENABLE_AMR libmesh_example_assert(false, "--enable-amr"); #else // Parse the input file GetPot input_file("adaptivity_ex3.in"); // Read in parameters from the input file const unsigned int max_r_steps = input_file("max_r_steps", 3); const unsigned int max_r_level = input_file("max_r_level", 3); const Real refine_percentage = input_file("refine_percentage", 0.5); const Real coarsen_percentage = input_file("coarsen_percentage", 0.5); const unsigned int uniform_refine = input_file("uniform_refine",0); const std::string refine_type = input_file("refinement_type", "h"); const std::string approx_type = input_file("approx_type", "LAGRANGE"); const unsigned int approx_order = input_file("approx_order", 1); const std::string element_type = input_file("element_type", "tensor"); const int extra_error_quadrature = input_file("extra_error_quadrature", 0); const int max_linear_iterations = input_file("max_linear_iterations", 5000); const bool output_intermediate = input_file("output_intermediate", false); dim = input_file("dimension", 2); const std::string indicator_type = input_file("indicator_type", "kelly"); singularity = input_file("singularity", true); // Skip higher-dimensional examples on a lower-dimensional libMesh build libmesh_example_assert(dim <= LIBMESH_DIM, "2D/3D support"); // Output file for plotting the error as a function of // the number of degrees of freedom. std::string approx_name = ""; if (element_type == "tensor") approx_name += "bi"; if (approx_order == 1) approx_name += "linear"; else if (approx_order == 2) approx_name += "quadratic"; else if (approx_order == 3) approx_name += "cubic"; else if (approx_order == 4) approx_name += "quartic"; std::string output_file = approx_name; output_file += "_"; output_file += refine_type; if (uniform_refine == 0) output_file += "_adaptive.m"; else output_file += "_uniform.m"; std::ofstream out (output_file.c_str()); out << "% dofs L2-error H1-error" << std::endl; out << "e = [" << std::endl; // Create a mesh. Mesh mesh; // Read in the mesh if (dim == 1) MeshTools::Generation::build_line(mesh,1,-1.,0.); else if (dim == 2) mesh.read("lshaped.xda"); else mesh.read("lshaped3D.xda"); // Use triangles if the config file says so if (element_type == "simplex") MeshTools::Modification::all_tri(mesh); // We used first order elements to describe the geometry, // but we may need second order elements to hold the degrees // of freedom if (approx_order > 1 || refine_type != "h") mesh.all_second_order(); // Mesh Refinement object MeshRefinement mesh_refinement(mesh); mesh_refinement.refine_fraction() = refine_percentage; mesh_refinement.coarsen_fraction() = coarsen_percentage; mesh_refinement.max_h_level() = max_r_level; // Create an equation systems object. EquationSystems equation_systems (mesh); // Declare the system and its variables. // Creates a system named "Laplace" LinearImplicitSystem& system = equation_systems.add_system<LinearImplicitSystem> ("Laplace"); // Adds the variable "u" to "Laplace", using // the finite element type and order specified // in the config file system.add_variable("u", static_cast<Order>(approx_order), Utility::string_to_enum<FEFamily>(approx_type)); // Give the system a pointer to the matrix assembly // function. system.attach_assemble_function (assemble_laplace); // Initialize the data structures for the equation system. equation_systems.init(); // Set linear solver max iterations equation_systems.parameters.set<unsigned int>("linear solver maximum iterations") = max_linear_iterations; // Linear solver tolerance. equation_systems.parameters.set<Real>("linear solver tolerance") = std::pow(TOLERANCE, 2.5); // Prints information about the system to the screen. equation_systems.print_info(); // Construct ExactSolution object and attach solution functions ExactSolution exact_sol(equation_systems); exact_sol.attach_exact_value(exact_solution); exact_sol.attach_exact_deriv(exact_derivative); // Use higher quadrature order for more accurate error results exact_sol.extra_quadrature_order(extra_error_quadrature); // A refinement loop. for (unsigned int r_step=0; r_step<max_r_steps; r_step++) { std::cout << "Beginning Solve " << r_step << std::endl; // Solve the system "Laplace", just like example 2. system.solve(); std::cout << "System has: " << equation_systems.n_active_dofs() << " degrees of freedom." << std::endl; std::cout << "Linear solver converged at step: " << system.n_linear_iterations() << ", final residual: " << system.final_linear_residual() << std::endl; #ifdef LIBMESH_HAVE_EXODUS_API // After solving the system write the solution // to a ExodusII-formatted plot file. if (output_intermediate) { OStringStream outfile; outfile << "lshaped_" << r_step << ".e"; ExodusII_IO (mesh).write_equation_systems (outfile.str(), equation_systems); } #endif // #ifdef LIBMESH_HAVE_EXODUS_API // Compute the error. exact_sol.compute_error("Laplace", "u"); // Print out the error values std::cout << "L2-Error is: " << exact_sol.l2_error("Laplace", "u") << std::endl; std::cout << "H1-Error is: " << exact_sol.h1_error("Laplace", "u") << std::endl; // Print to output file out << equation_systems.n_active_dofs() << " " << exact_sol.l2_error("Laplace", "u") << " " << exact_sol.h1_error("Laplace", "u") << std::endl; // Possibly refine the mesh if (r_step+1 != max_r_steps) { std::cout << " Refining the mesh..." << std::endl; if (uniform_refine == 0) { // The \p ErrorVector is a particular \p StatisticsVector // for computing error information on a finite element mesh. ErrorVector error; if (indicator_type == "exact") { // The \p ErrorEstimator class interrogates a // finite element solution and assigns to each // element a positive error value. // This value is used for deciding which elements to // refine and which to coarsen. // For these simple test problems, we can use // numerical quadrature of the exact error between // the approximate and analytic solutions. // However, for real problems, we would need an error // indicator which only relies on the approximate // solution. ExactErrorEstimator error_estimator; error_estimator.attach_exact_value(exact_solution); error_estimator.attach_exact_deriv(exact_derivative); // We optimize in H1 norm, the default // error_estimator.error_norm = H1; // Compute the error for each active element using // the provided indicator. Note in general you // will need to provide an error estimator // specifically designed for your application. error_estimator.estimate_error (system, error); } else if (indicator_type == "patch") { // The patch recovery estimator should give a // good estimate of the solution interpolation // error. PatchRecoveryErrorEstimator error_estimator; error_estimator.estimate_error (system, error); } else if (indicator_type == "uniform") { // Error indication based on uniform refinement // is reliable, but very expensive. UniformRefinementEstimator error_estimator; error_estimator.estimate_error (system, error); } else { libmesh_assert_equal_to (indicator_type, "kelly"); // The Kelly error estimator is based on // an error bound for the Poisson problem // on linear elements, but is useful for // driving adaptive refinement in many problems KellyErrorEstimator error_estimator; error_estimator.estimate_error (system, error); } // Write out the error distribution OStringStream ss; ss << r_step; #ifdef LIBMESH_HAVE_EXODUS_API std::string error_output = "error_"+ss.str()+".e"; #else std::string error_output = "error_"+ss.str()+".gmv"; #endif error.plot_error( error_output, mesh ); // This takes the error in \p error and decides which elements // will be coarsened or refined. Any element within 20% of the // maximum error on any element will be refined, and any // element within 10% of the minimum error on any element might // be coarsened. Note that the elements flagged for refinement // will be refined, but those flagged for coarsening _might_ be // coarsened. mesh_refinement.flag_elements_by_error_fraction (error); // If we are doing adaptive p refinement, we want // elements flagged for that instead. if (refine_type == "p") mesh_refinement.switch_h_to_p_refinement(); // If we are doing "matched hp" refinement, we // flag elements for both h and p if (refine_type == "matchedhp") mesh_refinement.add_p_to_h_refinement(); // If we are doing hp refinement, we // try switching some elements from h to p if (refine_type == "hp") { HPCoarsenTest hpselector; hpselector.select_refinement(system); } // If we are doing "singular hp" refinement, we // try switching most elements from h to p if (refine_type == "singularhp") { // This only differs from p refinement for // the singular problem libmesh_assert (singularity); HPSingularity hpselector; // Our only singular point is at the origin hpselector.singular_points.push_back(Point()); hpselector.select_refinement(system); } // This call actually refines and coarsens the flagged // elements. mesh_refinement.refine_and_coarsen_elements(); } else if (uniform_refine == 1) { if (refine_type == "h" || refine_type == "hp" || refine_type == "matchedhp") mesh_refinement.uniformly_refine(1); if (refine_type == "p" || refine_type == "hp" || refine_type == "matchedhp") mesh_refinement.uniformly_p_refine(1); } // This call reinitializes the \p EquationSystems object for // the newly refined mesh. One of the steps in the // reinitialization is projecting the \p solution, // \p old_solution, etc... vectors from the old mesh to // the current one. equation_systems.reinit (); } } #ifdef LIBMESH_HAVE_EXODUS_API // Write out the solution // After solving the system write the solution // to a ExodusII-formatted plot file. ExodusII_IO (mesh).write_equation_systems ("lshaped.e", equation_systems); #endif // #ifdef LIBMESH_HAVE_EXODUS_API // Close up the output file. out << "];" << std::endl; out << "hold on" << std::endl; out << "plot(e(:,1), e(:,2), 'bo-');" << std::endl; out << "plot(e(:,1), e(:,3), 'ro-');" << std::endl; // out << "set(gca,'XScale', 'Log');" << std::endl; // out << "set(gca,'YScale', 'Log');" << std::endl; out << "xlabel('dofs');" << std::endl; out << "title('" << approx_name << " elements');" << std::endl; out << "legend('L2-error', 'H1-error');" << std::endl; // out << "disp('L2-error linear fit');" << std::endl; // out << "polyfit(log10(e(:,1)), log10(e(:,2)), 1)" << std::endl; // out << "disp('H1-error linear fit');" << std::endl; // out << "polyfit(log10(e(:,1)), log10(e(:,3)), 1)" << std::endl; #endif // #ifndef LIBMESH_ENABLE_AMR // All done. return 0; }
Foam::word Foam::name(const septernion& s) { OStringStream buf; buf << '(' << s.t() << ',' << s.r() << ')'; return buf.str(); }