void manipulateFvSolutionFvSchemesFunctionObject::resetDict(dictionary &dict) { if(dict.name()==fvSchemesDict().name()) { resetFvSchemes(); } else if(dict.name()==fvSolutionDict().name()) { resetFvSolution(); } else { FatalErrorIn("manipulateFvSolutionFvSchemesFunctionObject::resetDict(dictionary &dict)") << "Can't reset unknown dictionary" << dict.name() << nl << "Is neither " << fvSchemesDict().name() << " nor " << fvSolutionDict().name() << endl << exit(FatalError); } }
bool Foam::functionEntries::codeStream::execute ( const dictionary& parentDict, primitiveEntry& entry, Istream& is ) { Info<< "Using #codeStream at line " << is.lineNumber() << " in file " << parentDict.name() << endl; dynamicCode::checkSecurity ( "functionEntries::codeStream::execute(..)", parentDict ); // get code dictionary // must reference parent for stringOps::expand to work nicely dictionary codeDict("#codeStream", parentDict, is); streamingFunctionType function = getFunction(parentDict, codeDict); // use function to write stream OStringStream os(is.format()); (*function)(os, parentDict); // get the entry from this stream IStringStream resultStream(os.str()); entry.read(parentDict, resultStream); return true; }
bool Foam::functionEntries::includeEntry::execute ( dictionary& parentDict, Istream& is ) { const fileName fName(includeFileName(is)); IFstream ifs(fName); if (ifs) { if (Foam::functionEntries::includeEntry::report) { Info<< fName << endl; } parentDict.read(ifs); return true; } else { FatalIOErrorIn ( "functionEntries::includeEntry::includeEntry" "(dictionary& parentDict, Istream&)", is ) << "Cannot open include file " << ifs.name() << " while reading dictionary " << parentDict.name() << exit(FatalIOError); return false; } }
forceEquation<T>::forceEquation ( const dictionary& dict, const fvMesh& mesh ) : FieldValueExpressionDriver(dict,mesh), valueExpression_( dict.lookup("valueExpression"), dict ), maskExpression_( dict.lookup("maskExpression"), dict ), verbose_(dict.lookupOrDefault<bool>("verbose",true)) { createWriterAndRead(dict.name().name()+"_"+this->type()+"<"+pTraits<T>::typeName+">"); if(verbose_) { WarningIn(string("forceEquation<") + pTraits<T>::typeName + ">::forceEquation") << "Fixing to the values " << valueExpression_ << " with the mask " << maskExpression_ << " will be verbose. To switch this off set the parameter 'verbose'" << "to false" << endl; } }
bool Foam::functionEntries::includeEntry::execute ( dictionary& parentDict, Istream& is ) { const fileName rawFName(is); const fileName fName ( includeFileName(is.name().path(), rawFName, parentDict) ); IFstream ifs(fName); if (ifs) { if (Foam::functionEntries::includeEntry::log) { Info<< fName << endl; } parentDict.read(ifs); return true; } else { FatalIOErrorInFunction ( is ) << "Cannot open include file " << (ifs.name().size() ? ifs.name() : rawFName) << " while reading dictionary " << parentDict.name() << exit(FatalIOError); return false; } }
Foam::calculateGlobalVariables::calculateGlobalVariables ( const word& name, const objectRegistry& obr, const dictionary& dict, const bool loadFromFiles ) : obr_(obr), driver_( CommonValueExpressionDriver::New( dict, refCast<const fvMesh>(obr) ) ), toGlobalNamespace_(dict.lookup("toGlobalNamespace")), toGlobalVariables_(dict.lookup("toGlobalVariables")), noReset_(dict.lookupOrDefault<bool>("noReset",false)) { if(debug) { Info << "calculateGlobalVariables " << name << " created" << endl; } if(!dict.found("noReset")) { WarningIn("calculateGlobalVariables::calculateGlobalVariables") << "No entry 'noReset' in " << dict.name() << ". Assumig 'false'"<< endl; } driver_->createWriterAndRead(name+"_"+type()); executeAndWriteToGlobal(); }
writeAndEndFunctionObject::writeAndEndFunctionObject ( const word &name, const Time& t, const dictionary& dict ) : simpleFunctionObject(name,t,dict), isStopped_(false), storeAndWritePreviousState_( dict.lookupOrDefault<bool>("storeAndWritePreviousState",false) ) { if(storeAndWritePreviousState_) { lastTimes_.set( new TimeCloneList( dict ) ); } else if(!dict.found("storeAndWritePreviousState")){ WarningIn("writeAndEndFunctionObject::writeAndEndFunctionObject") << "'storeAndWritePreviousState' unset in " << dict.name() << endl; } }
expressionSource<T>::expressionSource ( const dictionary& dict, const fvMesh& mesh ) : FieldValueExpressionDriver(dict,mesh), expression_(dict.lookup("expression")) { createWriterAndRead(dict.name().name()+"_"+this->type()+"<"+pTraits<T>::typeName+">"); }
StateMachine::StateMachine( const dictionary &dict, const fvMesh &mesh ): driver_( CommonValueExpressionDriver::New( dict, mesh ) ), mesh_(mesh), names_( dict.lookup("states") ), machineName_( dict.lookup("machineName") ), initialState_( stateCode( word(dict.lookup("initialState")) ) ), state_(initialState_), lastStateChange_( mesh.time().value() ), stepsSinceChange_(0), changedTo_( names_.size(), 0 ) { driver_->createWriterAndRead( "StateMachine_"+machineName_+"_"+dict.name().name() ); List<dictionary> data( dict.lookup("transitions") ); transitions_.resize(data.size()); forAll(data,i) { transitions_.set( i, new StateTransition( *this, dictionary( dict, data[i] ) ) ); }
void switchableNotImplemented( const word &methodName, const dictionary &dict ) { static HashSet<fileName> notImplementedWarningAlreadyIssued; word switchName="ignore_unimplemented_"+methodName; bool warn=dict.lookupOrDefault<bool>(switchName,false); if(warn) { fileName fullName=dict.name()+"_"+methodName; if(!notImplementedWarningAlreadyIssued.found(fullName)) { Info << endl; WarningIn("switchableNotImpleemnted") << "The method " << methodName << " isn't properly " << " implemented (at least that is what the developer " << " thinks. You chose to ignore this for " << dict.name() << endl << "The consequences are your responsibility " << "(but if you're lucky everything will be OK)" << endl << "This warning will only appear once" << nl << endl; notImplementedWarningAlreadyIssued.insert(fullName); } } else { Info << endl << endl; Info << "It seems that the method " << methodName << " is not properly implemented (neither in the class or " << " any appropriate subclasses)." << endl << "If you think that it should work anyway add the entry" << nl << nl << switchName << " true;" << nl << endl << "to the dictionary " << dict.name() << " and we will " << "go on. Alternativly properly implement the method." << nl << nl << "Anyway: I'll go die now"; Info << endl << endl; notImplemented(methodName); } }
void Foam::solveLaplacianPDE::read(const dictionary& dict) { solvePDECommonFiniteVolume::read(dict); if(active_) { if(needsRhoField(true)) { readExpressionAndDimension( dict, "rho", rhoExpression_, rhoDimension_ ); } readExpressionAndDimension( dict, "lambda", lambdaExpression_, lambdaDimension_ ); readExpressionAndDimension( dict, "source", sourceExpression_, sourceDimension_ ); if(dict.found("sourceImplicit")) { readExpressionAndDimension( dict, "sourceImplicit", sourceImplicitExpression_, sourceImplicitDimension_ ); if(dict.found("sourceImplicitUseSuSp")) { sourceImplicitUseSuSp_=readBool(dict.lookup("sourceImplicitUseSuSp")); } else { WarningIn("Foam::solveLaplacianPDE::read(const dictionary& dict)") << "'sourceImplicitUseSuSp' not set in " << dict.name() << " assuming 'false'" << endl; } } else { if(sourceExpression_!="0") { WarningIn("Foam::solveLaplacianPDE::read(const dictionary& dict)") << "Source expression " << sourceExpression_ << " set. " << "Consider factoring out parts to 'sourceImplicit'\n" << endl; } } } }
provokeSignalFunctionObject::provokeSignalFunctionObject ( const word &name, const Time& t, const dictionary& dict ) : simpleFunctionObject(name,t,dict), signalToRaise_( possibleSignalsNames_[ word(dict.lookup("signalToRaise")) ] ), timeToRaise_( readScalar(dict.lookup("timeToRaise")) ), raiseOnThisProc_(false) { if(Pstream::parRun()) { HashSet<label> allProcs( labelList( dict.lookup("processorsToRaiseSignal") ) ); raiseOnThisProc_=allProcs.found( Pstream::myProcNo() ); } else { if(!dict.found("processorsToRaiseSignal")) { WarningIn("provokeSignalFunctionObject::provokeSignalFunctionObject") << "No entry 'processorsToRaiseSignal' in " << dict.name() << nl << "Not needed now but needed in parallel runs" << endl; } raiseOnThisProc_=true; } if(raiseOnThisProc_) { Pout << endl; Pout << "Will raise signal " << possibleSignalsNames_[signalToRaise_] << " at time " << timeToRaise_ << " and there is nothing you can do about it. " << "In fact the only possible use of this is testing" << endl; Pout << endl; } }
scalar postProcessingWaves::readDeltaT ( const dictionary& timeDict ) { scalar dt( readScalar(timeDict.lookup("deltaT")) ); // Check for validity of the time step if (dt <= 0.0) { FatalErrorIn("scalar postProcessingWaves::readDeltaT") << "The time step (deltaT) given in\n " << timeDict.name() << endl << "is less than or equal to zero." << endl << exit(FatalError); } return dt; }
void Foam::expressionField::read(const dictionary& dict) { Dbug << " read(&dict) - active: " << active_ << endl; if(active_) { name_=word(dict.lookup("fieldName")); expression_=exprString( dict.lookup("expression"), dict ); autowrite_=Switch(dict.lookup("autowrite")); if(dict.found("dimension")) { dimensions_.reset(dimensionSet(dict.lookup("dimension"))); setDimensions_=true; } else { WarningIn("Foam::expressionField::read(const dictionary& dict)") << "No entry 'dimension' in " << dict.name() << " for field " << name_ << endl << "Not resetting the dimensions of the field" << nl << endl; dimensions_.reset(dimless); setDimensions_=false; } const fvMesh& mesh = refCast<const fvMesh>(obr_); driver_.set( new FieldValueExpressionDriver( mesh.time().timeName(), mesh.time(), mesh, false, // no caching. No need true, // search fields in memory false, // don't look up files in memory dict_ ) ); driver_->readVariablesAndTables(dict_); // this might not work when rereading ... but what is consistent in that case? driver_->createWriterAndRead(name_+"_"+type()); } Dbug << " read(&dict) - end " << endl; }
SwakSetValue<T>::SwakSetValue ( const word& name, const word& modelType, const dictionary& dict, const fvMesh& mesh ) : SwakBasicSourceCommon<T>(name, modelType, dict, mesh), useMaskExpression_(readBool(this->coeffs().lookup("useMaskExpression"))), maskExpression_( useMaskExpression_ ? string(this->coeffs().lookup("maskExpression")) : string("") ) { this->read(dict); this->driver().createWriterAndRead( dict.name().name()+"_"+this->type()+"<"+ pTraits<T>::typeName+">" ); if(this->verbose_) { WarningIn( string("SwakSetValue<") + pTraits<T>::typeName + ">::SwakSetValue" ) << "Fixing to the fields " << this->fieldNames_ << " to the values " << this->expressions_ << " with the mask " << maskExpression_ << " will be verbose. To switch this off set the " << "parameter 'verbose' to false" << endl; } }
Foam::dynamicCodeContext::dynamicCodeContext(const dictionary& dict) : dict_(dict), code_(), localCode_(), include_(), options_(), libs_() { // expand dictionary entries { const entry& codeEntry = dict.lookupEntry("code", false, false); code_ = stringOps::trim(codeEntry.stream()); stringOps::inplaceExpand(code_, dict); } // note: removes any leading/trailing whitespace // - necessary for compilation options, convenient for includes // and body. // optional const entry* includePtr = dict.lookupEntryPtr ( "codeInclude", false, false ); if (includePtr) { include_ = stringOps::trim(includePtr->stream()); stringOps::inplaceExpand(include_, dict); } // optional const entry* optionsPtr = dict.lookupEntryPtr ( "codeOptions", false, false ); if (optionsPtr) { options_ = stringOps::trim(optionsPtr->stream()); stringOps::inplaceExpand(options_, dict); } // optional const entry* libsPtr = dict.lookupEntryPtr("codeLibs", false, false); if (libsPtr) { libs_ = stringOps::trim(libsPtr->stream()); stringOps::inplaceExpand(libs_, dict); } // optional const entry* localPtr = dict.lookupEntryPtr("localCode", false, false); if (localPtr) { localCode_ = stringOps::trim(localPtr->stream()); stringOps::inplaceExpand(localCode_, dict); } // calculate SHA1 digest from include, options, localCode, code OSHA1stream os; os << include_ << options_ << libs_ << localCode_ << code_; sha1_ = os.digest(); // Add line number after calculating sha1 since includes processorDDD // in path which differs between processors. { const entry& codeEntry = dict.lookupEntry("code", false, false); addLineDirective(code_, codeEntry.startLineNumber(), dict.name()); } if (includePtr) { addLineDirective(include_, includePtr->startLineNumber(), dict.name()); } // Do not add line directive to options_ (Make/options) and libs since // they are preprocessed as a single line at this point. Can be fixed. if (localPtr) { addLineDirective(localCode_, localPtr->startLineNumber(), dict.name()); } }
void setScoped ( dictionary& dict, const word& keyword, const bool overwrite, entry* d ) { if (keyword[0] == ':') { // Go up to top level and recurse to find entries setScoped ( const_cast<dictionary&>(dict.topDict()), keyword.substr(1, keyword.size()-1), overwrite, d ); return; } else { string::size_type dotPos = keyword.find('.'); if (dotPos == string::npos) { // Non-scoped lookup if (overwrite) { dict.set(d); } else { dict.add(d, false); } return; } else { if (dotPos == 0) { // Starting with a '.'. Go up for every 2nd '.' found const dictionary* dictPtr = &dict; string::size_type begVar = dotPos + 1; string::const_iterator iter = keyword.begin() + begVar; string::size_type endVar = begVar; while ( iter != keyword.end() && *iter == '.' ) { ++iter; ++endVar; // Go to parent if (&dictPtr->parent() == &dictionary::null) { FatalIOErrorInFunction(dict) << "No parent of current dictionary" << " when searching for " << keyword.substr ( begVar, keyword.size() - begVar ) << exit(FatalIOError); } dictPtr = &dictPtr->parent(); } setScoped ( const_cast<dictionary&>(*dictPtr), keyword.substr(endVar), overwrite, d ); return; } else { // Extract the first word word firstWord = keyword.substr(0, dotPos); const entry* entPtr = dict.lookupScopedEntryPtr ( firstWord, false, // Recursive false ); if (!entPtr || !entPtr->isDict()) { FatalIOErrorInFunction(dict) << "keyword " << firstWord << " is undefined in dictionary " << dict.name() << " or is not a dictionary" << endl << "Valid keywords are " << dict.keys() << exit(FatalIOError); } const dictionary& firstDict = entPtr->dict(); setScoped ( const_cast<dictionary&>(firstDict), keyword.substr(dotPos, keyword.size()-dotPos), overwrite, d ); return; } } } }
pythonInterpreterWrapper::pythonInterpreterWrapper ( const objectRegistry& obr, const dictionary& dict, bool forceToNamespace ): generalInterpreterWrapperCRTP<pythonInterpreterWrapper>( obr, dict, forceToNamespace, "python" ), pythonState_(NULL), useNumpy_(dict.lookupOrDefault<bool>("useNumpy",true)), useIPython_(dict.lookupOrDefault<bool>("useIPython",true)), triedIPython_(false), oldIPython_(false) { if(generalInterpreterWrapper::debug>debug) { debug=1; } Pbug << "Starting constructor" << endl; syncParallel(); #ifdef FOAM_HAS_LOCAL_DEBUGSWITCHES debug=dict.lookupOrDefault<label>("debugPythonWrapper",debug()); #else debug=dict.lookupOrDefault<label>("debugPythonWrapper",debug); #endif if(!dict.found("useNumpy")) { WarningIn("pythonInterpreterWrapper::pythonInterpreterWrapper") << "Switch 'useNumpy' not found in " << dict.name() << nl << "Assuming it to be 'true' (if that is not what you want " << "set it. Also set it to make this warning go away)" << endl; } if(!dict.found("useIPython")) { WarningIn("pythonInterpreterWrapper::pythonInterpreterWrapper") << "Switch 'useIPython' not found in " << dict.name() << nl << "Assuming it to be 'true' (if that is not what you want " << "set it. Also set it to make this warning go away)" << endl; } if(interpreterCount==0) { Pbug << "Initializing Python" << endl; Py_Initialize(); if(debug) { PyThreadState *current=PyGILState_GetThisThreadState(); Pbug << "GIL-state before thread" << getHex(current) << endl; } PyEval_InitThreads(); if(debug) { PyThreadState *current=PyGILState_GetThisThreadState(); Pbug << "GIL-state after thread" << getHex(current) << endl; } // importLib("scipy.stats","stats"); - OK mainThreadState = PyEval_SaveThread(); // importLib("scipy.stats","stats"); - segFault Pbug << "Main thread state: " << getHex(mainThreadState) << endl; // PyRun_SimpleString("import IPython\n" // here it works as expected // "IPython.embed()\n"); } if(Pstream::parRun()) { Pbug << "This is a parallel run" << endl; parallelMasterOnly_=readBool(dict.lookup("parallelMasterOnly")); } if(parallelNoRun(true)) { Pbug << "Getting out because of 'parallelNoRun'" << endl; return; } interpreterCount++; Pbug << "Getting new interpreter" << endl; pythonState_=Py_NewInterpreter(); Pbug << "Interpreter state: " << getHex(pythonState_) << endl; // interactiveLoop("Clean"); initIPython(); Pbug << "Currently " << interpreterCount << " Python interpreters (created one)" << endl; if( interactiveAfterExecute_ || interactiveAfterException_ ) { } else { if(useIPython_) { WarningIn("pythonInterpreterWrapper::pythonInterpreterWrapper") << "'useIPython' not needed in " << dict.name() << " if there is no interactivity" << endl; } } if(useNumpy_) { Dbug << "Attempting to import numpy" << endl; static bool warnedNumpy=false; if(!warnedNumpy) { if(getEnv("FOAM_SIGFPE")!="false") { WarningInFunction << "Attempting to import numpy. On some platforms that will raise a " << "(harmless) floating point exception. To avoid switch off " << "by setting the environment variable 'FOAM_SIGFPE' to 'false'" << endl; } warnedNumpy=true; } int fail=!importLib("numpy"); if(fail) { FatalErrorIn("pythonInterpreterWrapper::pythonInterpreterWrapper") << "Problem during import of numpy." << nl << "Switch if off with 'useNumpy false;' if it is not needed" << endl << exit(FatalError); } fail=PyRun_SimpleString( // "def _swak_wrapOpenFOAMField_intoNumpy(address,typestr,size,nr=None):\n" // " class iWrap(object):\n" // " def __init__(self):\n" // " self.__array_interface__={}\n" // " self.__array_interface__['data']=(int(address,16),False)\n" // " if nr:\n" // " self.__array_interface__['shape']=(size,nr)\n" // " else:\n" // " self.__array_interface__['shape']=(size,)\n" // " self.__array_interface__['version']=3\n" // " self.__array_interface__['typestr']=typestr\n" // " return numpy.asarray(iWrap())\n" "class OpenFOAMFieldArray(numpy.ndarray):\n" " def __new__(cls,address,typestr,size,nr=None,names=None):\n" " obj=type('Temporary',(object,),{})\n" " obj.__array_interface__={}\n" " obj.__array_interface__['data']=(address,False)\n" " if nr:\n" " obj.__array_interface__['shape']=(size,nr)\n" " else:\n" " obj.__array_interface__['shape']=(size,)\n" // " obj.__array_interface__['descr']=[('x',typestr)]\n" " obj.__array_interface__['version']=3\n" " obj.__array_interface__['typestr']=typestr\n" " obj=numpy.asarray(obj).view(cls)\n" " if names:\n" " for i,n in enumerate(names):\n" " def f(ind):\n" " return obj[:,ind]\n" " setattr(obj,n,f(i))\n" " return obj\n" " def __array_finalize__(self,obj):\n" " if obj is None: return\n" ); } if(dict.found("importLibs")) { const dictionary &libList=dict.subDict("importLibs"); forAllConstIter(dictionary,libList,iter) { word as=(*iter).keyword(); word full((*iter).stream()); if(full=="") { full=as; } importLib(full,as,true); } } else {