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_();
}
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_();
}
Beispiel #3
0
 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();
 }
Beispiel #4
0
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;
}
Beispiel #5
0
std::string 
StringTools::toString( double value )
{
  OStringStream stream;
  stream << value;
  return stream.str();
}
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());
    }
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);
	}
}
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())());
}
		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;
}
Beispiel #11
0
Foam::string Foam::Reaction<ReactionThermo>::reactionStr
(
    OStringStream& reaction
) const
{
    reactionStrLeft(reaction);
    reaction << " = ";
    reactionStrRight(reaction);
    return reaction.str();
}
Beispiel #12
0
CPPUNIT_NS_BEGIN


std::string 
StringTools::toString( int value )
{
  OStringStream stream;
  stream << value;
  return stream.str();
}
Beispiel #13
0
 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;
 }
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);
}
Beispiel #15
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;
}
Beispiel #17
0
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();
    }
}
Beispiel #18
0
    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);
    }
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();

}
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;
}
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;
    }
Beispiel #22
0
Foam::string Foam::dimensionSet::asText() const
{
    OStringStream buf;

    bool Dimensionless = true;

    for (int Dimension=0; Dimension < dimensionSet::nDimensions-1; ++Dimension)
    {
        const scalar& expt = exponents_[Dimension];

        if (expt < smallExponent && expt > -smallExponent)
        {
            continue;
        }

        if (Dimensionless)
        {
            Dimensionless = false;
        }
        else
        {
            buf << ' ';
        }

        // note: currently only handle SI
        switch (Dimension)
        {
            case MASS:
                buf << "kg";
                break;

            case LENGTH:
                buf << "m";
                break;

            case TIME:
                buf << "s";
                break;

            case TEMPERATURE:
                buf << "K";
                break;

            case MOLES:
                buf << "mol";
                break;

            case CURRENT:
                buf << "A";
                break;

            case LUMINOUS_INTENSITY:
                buf << "Cd";
                break;

            default:
                buf << "??";  // this shouldn't be - flag as being weird
                break;
        }

        if (expt != 1)
        {
            buf << '^' << expt;
        }
    }

    if (Dimensionless)
    {
        return "none";
    }
    else
    {
        return buf.str();
    }
}
Beispiel #23
0
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 Foam::equationReader::removePowExponents
(
    const label index,
    tokenList& tl,
    PtrList<equationOperation>& map,
    labelList& opLvl,
    labelList& pl
) const
{
    // Remove pow(a,b) exponent part 'b' from an equation and create a sub-
    // equation.
    label tokenI(0);

    while (tokenI < map.size())
    {
        if (map[tokenI].operation() == equationOperation::otpow)
        {
            // Found a 'pow('. Look for ','; fail on ')', or end of list
            // pl checks ensure the ',' or ')' relate to the 'pow(', and not
            // another function / parethesis
            const label powFoundAt(tokenI);
            const label pLvl(pl[tokenI]);
            while ((opLvl[tokenI] != 5) || (pl[tokenI] != pLvl))
            {
                if
                (
                    ((opLvl[tokenI] == -4) && (pl[tokenI] == pLvl))
                 || (tokenI == (map.size() - 1))
                )
                {
                    OStringStream description;
                    description << "pow() function takes two arguments.";
                    fatalParseError
                    (
                        index,
                        tl,
                        powFoundAt,
                        tokenI,
                        "equationReader::removePowExponents",
                        description
                    );
                }
                tokenI++;
            }

            // Found 'pow( ... ,' look for ')', fail on list end
            const label commaFoundAt(tokenI);
            while ((opLvl[tokenI] != -4) || (pl[tokenI] != pLvl))
            {
                if (tokenI == (map.size() - 1))
                {
                    OStringStream description;
                    description << "Can't find closing parenthesis for "
                        << "pow() function.";
                    fatalParseError
                    (
                        index,
                        tl,
                        powFoundAt,
                        tokenI,
                        "equationReader::removePowExponents",
                        description
                    );
                }
                tokenI++;
            }

            const label closeFoundAt(tokenI);
            // Ignore if the exponent is only 1 token
            if ((closeFoundAt - commaFoundAt) > 2)
            {

                // Now create sub-equation
                OStringStream subEqnStream;
                for
                (
                    label subTokenI(commaFoundAt + 1);
                    subTokenI < closeFoundAt;
                    subTokenI++
                )
                {
                    if
                    (
                        tl[subTokenI].isPunctuation()
                     && (tl[subTokenI].pToken() == token::COLON))
                    {
                        subEqnStream << "^";
                    }
                    else
                    {
                        subEqnStream << tl[subTokenI];
                    }
                }
                string subEqnRawText(subEqnStream.str());
                const equation& eqn(operator[](index));
                equation subEqn
                (
                    eqn.name() + "_powExponent_" + name(powFoundAt),
                    subEqnRawText,
                    eqn.overrideDimensions(),
                    eqn.changeDimensions()
                );

                bool eqnCreated(false);
                for (label eqnI(0); eqnI < size(); eqnI++)
                {
                    const equation& eqnTest(operator[](eqnI));
                    if (eqnTest.name() == subEqn.name())
                    {
                        clearEquation(eqnI);
                        eqnTest.setRawText(subEqn.rawText());
                        eqnTest.setOverrideDimensions
                        (
                            subEqn.overrideDimensions()
                        );
                        eqnTest.setChangeDimensions
                        (
                            eqnTest.changeDimensions()
                        );
                        eqnCreated = true;
                    }
                }

                if (!eqnCreated)
                {
                    createEquation(subEqn);
                }

                // Change commaFoundAt + 1 entry to reflect new subEquation
                // reference
                tl[commaFoundAt + 1] = token(subEqn.name());
                map.set
                (
                    commaFoundAt + 1,
                    new equationOperation(findSource(subEqn.name()))
                );
                opLvl[commaFoundAt + 1] = 0;
                pl[commaFoundAt + 1] = pl[commaFoundAt];

                // Remove the subEquation from tl, map, opLvl and pl
                label tokensRemoved(closeFoundAt - (commaFoundAt + 2));
                label newSize(map.size() - tokensRemoved);
                for
                (
                    label subTokenI(commaFoundAt + 2);
                    subTokenI < newSize;
                    subTokenI++
                )
                {
                    tl[subTokenI] = tl[subTokenI + tokensRemoved];
                    map[subTokenI] = map[subTokenI + tokensRemoved];
                    opLvl[subTokenI] = opLvl[subTokenI + tokensRemoved];
                    pl[subTokenI] = pl[subTokenI + tokensRemoved];
                }
                tl.setSize(newSize);
                map.setSize(newSize);
                opLvl.setSize(newSize);
                pl.setSize(newSize);
            }
        }
        tokenI++;
    }
}
void HTMLTemplateRenderer::RenderAll(std::ostream &reply, Context &context, const ROAnything &args)
{
	StartTrace(HTMLTemplateRenderer.RenderAll);
	TraceAny(args, "args");
	ROAnything theRendererConfig, roaParserConfig;
	Anything rendererConfig;

	// check if we have special parser configuration to use
	if ( !args.LookupPath(roaParserConfig, "ParserConfig") ) {
		context.Lookup("HTMLTemplateConfig.ParserConfig", roaParserConfig);
	}

	if (args.IsDefined("TemplateName")) {
		String filename;
		Renderer::RenderOnString(filename, context, args["TemplateName"]);
		if (filename.Length() == 0) {
			SystemLog::Error("HTMLTemplateRenderer::RenderAll: cannot find template name");
		} else {
			const char *lang = context.Language();		// cache language flag for localized strings
			TraceAny(fgNameMap, "current cache map");
			String pathUsed = fgNameMap[filename][lang].AsCharPtr("");
			Trace("Template file :" << filename << ";" << pathUsed << ";" << lang );
			if ( pathUsed.Length() > 0 ) { // we got the filekey
				theRendererConfig = fgTemplates[pathUsed];
			} else {
				std::istream *fp = LocalizationUtils::OpenStream(context, filename, pathUsed);
				if (fp) {
					std::istream &reader = *fp;
					{
						MethodTimer(HTMLTemplateRenderer.RenderAll, filename, context);
						TemplateParser *tp = GetParser();
						rendererConfig = tp->Parse(reader, filename, 1L, rendererConfig.GetAllocator(), roaParserConfig);
						delete tp;
						theRendererConfig = rendererConfig;
					}
					delete fp;
				} else {
					String logMsg("HTMLTemplateRenderer::RenderAll: cannot open file ");
					logMsg << filename << ".html";
					SystemLog::Error(logMsg);
				}
			}
		}
	} else {
		// look for /Template
		MethodTimer(HTMLTemplateRenderer.RenderAll, "Template", context);
		ROAnything templ;
		if (args.IsDefined("Template")) {
			templ = args["Template"];
		} else {
			// bail out.
			OStringStream str;
			str << "HTMLTemplateRenderer::RenderAll: neither Template nor TemplateName is defined :";
			args.PrintOn(str); // log what we've got
			SystemLog::Error(str.str());
			return;
		}

		String buf;
		for (long i = 0, size = templ.GetSize(); i < size; ++i) {
			// PS: only append anonymous entries to allow for future parameters
			// PS: this will take care of things like /Options /Method in subclass FormRenderer
			if ( 0 == templ.SlotName(i) ) {
				buf.Append(templ[i].AsCharPtr());
			}
		}
		IStringStream reader(buf);
		TemplateParser *tp = GetParser();
		rendererConfig = tp->Parse(reader, "from config", 1L, rendererConfig.GetAllocator(), roaParserConfig);
		delete tp;
		theRendererConfig = rendererConfig;

	}
	Render(reply, context, theRendererConfig);
}
inline word addressToWord(const uintptr_t addr)
{
    OStringStream nStream;
    nStream << "0x" << hex << addr;
    return nStream.str();
}
Beispiel #27
0
Foam::string& Foam::stringOps::inplaceExpand
(
    string& s,
    const dictionary& dict,
    const char sigil
)
{
    string::size_type begVar = 0;

    // Expand $VAR or ${VAR}
    // Repeat until nothing more is found
    while
    (
        (begVar = s.find(sigil, begVar)) != string::npos
     && begVar < s.size()-1
    )
    {
        if (begVar == 0 || s[begVar-1] != '\\')
        {
            // Find end of first occurrence
            string::size_type endVar = begVar;
            string::size_type delim = 0;

            if (s[begVar+1] == '{')
            {
                endVar = s.find('}', begVar);
                delim = 1;
            }
            else
            {
                string::iterator iter = s.begin() + begVar + 1;

                // more generous in accepting keywords than for env variables
                while
                (
                    iter != s.end()
                 &&
                    (
                        isalnum(*iter)
                     || *iter == '.'
                     || *iter == ':'
                     || *iter == '_'
                    )
                )
                {
                    ++iter;
                    ++endVar;
                }
            }

            if (endVar == string::npos)
            {
                // likely parsed '${...' without closing '}' - abort
                break;
            }
            else if (endVar == begVar)
            {
                // parsed '${}' or $badChar  - skip over
                begVar = endVar + 1;
            }
            else
            {
                const word varName
                (
                    s.substr
                    (
                        begVar + 1 + delim,
                        endVar - begVar - 2*delim
                    ),
                    false
                );


                // lookup in the dictionary
                const entry* ePtr = dict.lookupScopedEntryPtr
                (
                    varName,
                    true,
                    false   // wildcards disabled. See primitiveEntry
                );

                // if defined - copy its entries
                if (ePtr)
                {
                    OStringStream buf;
                    // Force floating point numbers to be printed with at least
                    // some decimal digits.
                    buf << fixed;
                    buf.precision(IOstream::defaultPrecision());
                    if (ePtr->isDict())
                    {
                        ePtr->dict().write(buf, false);
                    }
                    else
                    {
                        // fail for other types
                        dynamicCast<const primitiveEntry>
                        (
                            *ePtr
                        ).write(buf, true);
                    }

                    s.std::string::replace
                    (
                        begVar,
                        endVar - begVar + 1,
                        buf.str()
                    );
                    begVar += buf.str().size();
                }
                else
                {
                    // not defined - leave original string untouched
                    begVar = endVar + 1;
                }
            }
        }
        else
        {
            ++begVar;
        }
    }

    return s;
}
Beispiel #28
0
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);
    }
Foam::word Foam::name(const septernion& s)
{
    OStringStream buf;
    buf << '(' << s.t() << ',' << s.r() << ')';
    return buf.str();
}
Beispiel #30
0
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;
}