bool invert(const boost::numeric::ublas::matrix<T>& input, boost::numeric::ublas::matrix<T>& inverse) { // create a working copy of the input boost::numeric::ublas::matrix<T> A(input); // create a permutation matrix for the LU-factorization boost::numeric::ublas::permutation_matrix<std::size_t> pm(A.size1()); // perform LU-factorization typename boost::numeric::ublas::matrix<T>::size_type res = boost::numeric::ublas::lu_factorize(A, pm); if( res != 0 ){ LOG_FREE(Info, "boost.ublas", "boost::numeric::ublas::lu_factorize returned res = " << res << ", A = " << A << ", pm = " << pm << " for input = " << input); return false; } // create identity matrix of "inverse" inverse.assign(boost::numeric::ublas::identity_matrix<T>(A.size1())); // backsubstitute to get the inverse try { boost::numeric::ublas::lu_substitute(A, pm, inverse); }catch (std::exception& e){ LOG_FREE(Info, "boost.ublas", "boost::numeric::ublas::lu_substitute threw exception '" << e.what() << "' for A = " << A << ", pm = " << pm); return false; } return true; }
path completePathToFile(const path& p,const path& base,const std::string& ext,bool warnOnMismatch) { path result(p); // handle file extension if (!ext.empty()) { result = setFileExtension(p,ext,false,warnOnMismatch); if (result.empty()) { result = p; } } // complete path if (!result.is_complete()) { try { if (!base.empty()) { result = boost::filesystem::complete(result,base); } else { result = boost::filesystem::complete(result); } } catch (...) { LOG_FREE(Info,"openstudio.completePathToFile","Unable to compete path '" << toString(p) << "'. Returning an empty path."); return path(); } } // check that result is a file if (!boost::filesystem::is_regular_file(result)) { LOG_FREE(Info,"openstudio.completePathToFile","Path '" << toString(p) << "' could not be resolved to an existing file. Returning an empty path."); return path(); } return result; }
bool initializeModelTempDir(const openstudio::path& osmPath, const openstudio::path& modelTempDir) { bool result = true; if( osmPath.empty() || !boost::filesystem::exists(osmPath)){ LOG_FREE(Debug, "initializeModelTempDir", "OSM path '" << toString(osmPath) << "' is empty or does not exist"); result = false; }else{ LOG_FREE(Debug, "initializeModelTempDir", "Copying '" << toString(osmPath) << "' to '" << toString(modelTempDir / toPath("in.osm")) << "'"); // copy osm file bool test = QFile::copy(toQString(osmPath), toQString(modelTempDir / toPath("in.osm"))); if (!test){ LOG_FREE(Error, "initializeModelTempDir", "Could not copy '" << toString(osmPath) << "' to '" << toString(modelTempDir / toPath("in.osm")) << "'"); } // Copy all files from existing resources dir into temp dir when opening openstudio::path sourceDir = osmPath.parent_path() / osmPath.stem(); openstudio::path destDir = modelTempDir / toPath("resources"); if (boost::filesystem::exists(sourceDir)){ LOG_FREE(Debug, "initializeModelTempDir", "Copying '" << toString(sourceDir) << "' to '" << toString(destDir) << "'"); test = copyDir(toQString(sourceDir), toQString(destDir)); if (!test){ LOG_FREE(Error, "initializeModelTempDir", "Could not copy '" << toString(sourceDir) << "' to '" << toString(destDir) << "'"); result = false; } } } return result; }
int main(int argc, char *argv[]) { #if _DEBUG || (__GNUC__ && !NDEBUG) #ifdef _WIN32 const char *logfilepath = "./resultsviewer.log"; #else const char *logfilepath = "/var/log/resultsviewer.log"; #endif openstudio::Logger::instance().standardOutLogger().setLogLevel(Debug); openstudio::FileLogSink fileLog(openstudio::toPath(logfilepath)); fileLog.setLogLevel(Debug); #else openstudio::Logger::instance().standardOutLogger().setLogLevel(Warn); #endif bool cont = true; while(cont) { cont = false; // Make the run path the default plugin search location QCoreApplication::addLibraryPath(openstudio::toQString(openstudio::getApplicationRunDirectory())); QApplication qApplication(argc,argv); openstudio::Application::instance().setApplication(&qApplication); try { resultsviewer::MainWindow w; w.show(); return qApplication.exec(); } catch (const std::exception &e) { LOG_FREE(Fatal, "ResultsViewer", "An unhandled exception has occurred: " << e.what()); cont = true; QMessageBox msgBox; msgBox.setWindowTitle("Unhandled Exception"); msgBox.setIcon(QMessageBox::Critical); msgBox.setText("An unhandled exception has occurred."); msgBox.setInformativeText(e.what()); msgBox.setStandardButtons(QMessageBox::Retry | QMessageBox::Close); msgBox.button(QMessageBox::Retry)->setText("Relaunch"); if (msgBox.exec() == QMessageBox::Close) { cont = false; } } catch (...) { LOG_FREE(Fatal, "ResultsViewer", "An unknown exception has occurred."); cont = true; QMessageBox msgBox; msgBox.setWindowTitle("Unknown Exception"); msgBox.setIcon(QMessageBox::Critical); msgBox.setText("An unknown exception has occurred."); msgBox.setStandardButtons(QMessageBox::Retry | QMessageBox::Close); msgBox.button(QMessageBox::Retry)->setText("Relaunch"); if (msgBox.exec() == QMessageBox::Close) { cont = false; } } } }
AnalysisJSONLoadResult loadJSON(const openstudio::path& p) { OptionalAnalysisObject result; StringStreamLogSink logger; logger.setLogLevel(Error); try { QVariant variant = openstudio::loadJSON(p); VersionString version = extractOpenStudioVersion(variant); QVariantMap map = variant.toMap(); QVariantMap objectMap; if (map.contains("data_point")) { // leave objectMap blank, because it cannot contain project_dir result = detail::DataPoint_Impl::factoryFromVariant(map["data_point"],version,boost::none); } else if (map.contains("analysis")) { objectMap = map["analysis"].toMap(); result = detail::Analysis_Impl::fromVariant(objectMap,version); } else { LOG_FREE_AND_THROW("openstudio.analysis.AnalysisObject", "The file at " << toString(p) << " does not contain a data_point or " << "an analysis."); } OS_ASSERT(result); openstudio::path projectDir; if (version < VersionString("1.1.2")) { OS_ASSERT(map.contains("metadata")); if (map["metadata"].toMap().contains("project_dir")) { projectDir = toPath(map["metadata"].toMap()["project_dir"].toString()); } } else { if (objectMap.contains("project_dir")) { projectDir = toPath(objectMap["project_dir"].toString()); } } return AnalysisJSONLoadResult(*result,projectDir,version); } catch (std::exception& e) { LOG_FREE(Error,"openstudio.analysis.AnalysisObject", "The file at " << toString(p) << " cannot be parsed as an OpenStudio " << "analysis framework json file, because " << e.what()); } catch (...) { LOG_FREE(Error,"openstudio.analysis.AnalysisObject", "The file at " << toString(p) << " cannot be parsed as an OpenStudio " << "analysis framework json file."); } return AnalysisJSONLoadResult(logger.logMessages()); }
path relocatePath(const path& originalPath, const path& originalBase, const path& newBase) { path result; path temp = relativePath(originalPath,originalBase); LOG_FREE(Debug,"openstudio.utilities.core","Original path '" << toString(originalPath) << "', relative to '" << toString(originalBase) << "' is '" << toString(temp) << "'."); if (!temp.empty()) { result = newBase / temp; LOG_FREE(Debug,"openstudio.utilities.core","Relocating path to '" << toString(result) << "'."); } return result; }
int main(int argc, char *argv[]) { openstudio::Logger::instance().standardOutLogger().disable(); openstudio::FileLogSink logFile(openstudio::toPath(logfilepath)); logFile.setLogLevel(Warn); bool cont = true; while(cont) { cont = false; QApplication qApplication(argc,argv); openstudio::Application::instance().setApplication(&qApplication); try { resultsviewer::MainWindow w; w.show(); return qApplication.exec(); } catch (const std::exception &e) { LOG_FREE(Fatal, "ResultsViewer", "An unhandled exception has occurred: " << e.what()); cont = true; QMessageBox msgBox; msgBox.setWindowTitle("Unhandled Exception"); msgBox.setIcon(QMessageBox::Critical); msgBox.setText("An unhandled exception has occurred."); msgBox.setInformativeText(e.what()); msgBox.setStandardButtons(QMessageBox::Retry | QMessageBox::Close); msgBox.button(QMessageBox::Retry)->setText("Relaunch"); if (msgBox.exec() == QMessageBox::Close) { cont = false; } } catch (...) { LOG_FREE(Fatal, "ResultsViewer", "An unknown exception has occurred."); cont = true; QMessageBox msgBox; msgBox.setWindowTitle("Unknown Exception"); msgBox.setIcon(QMessageBox::Critical); msgBox.setText("An unknown exception has occurred."); msgBox.setStandardButtons(QMessageBox::Retry | QMessageBox::Close); msgBox.button(QMessageBox::Retry)->setText("Relaunch"); if (msgBox.exec() == QMessageBox::Close) { cont = false; } } } }
openstudio::path createModelTempDir() { openstudio::path result; auto tempFile = new QTemporaryFile(); if( tempFile->open() ) { QString path = longPathName(tempFile->fileName()); // must close tempFile so you can create directory with same name on Windows delete tempFile; QDir modelTempDir(path); LOG_FREE(Info, "createModelTempDir", "Creating directory '" << toString(modelTempDir.path()) << "'"); bool test = modelTempDir.mkpath(modelTempDir.path()); OS_ASSERT(test); result = toPath(path); return result; } delete tempFile; OS_ASSERT(false); return openstudio::path(); }
VersionString extractOpenStudioVersion(const QVariant& variant) { QJsonObject topLevel = QJsonDocument::fromVariant(variant).object(); if (topLevel.contains("metadata")) { topLevel = topLevel["metadata"].toObject(); } OptionalVersionString version; if (topLevel.contains("openstudio_version")) { version = VersionString(topLevel["openstudio_version"].toString().toStdString()); } else if (topLevel.contains("version")) { version = VersionString(topLevel["version"].toString().toStdString()); } else { LOG_FREE_AND_THROW("openstudio.core.Json","No version identifier found in QJSON variant."); } OS_ASSERT(version); if (version.get() > VersionString(openStudioVersion())) { LOG_FREE(Warn,"openstudio.Json","Loading json file from version " << version << " with OpenStudio version " << VersionString(openStudioVersion()) << ". OpenStudio json files are not designed to be forwards-compatible. " << "Unexpected behavior may result.") } return version.get(); }
inline void assertion_failed(char const * expr, char const * function, char const * file, long line) { std::stringstream ss; ss << "Assertion " << expr << " failed on line " << line << " of " << function << " in file " << file << "."; openstudio::Logger::instance().standardErrLogger().enable(); LOG_FREE(Fatal, "BOOST_ASSERT", ss.str()); assert(false); }
void addRadianceToProject(openstudio::analysisdriver::SimpleProject &t_project) { openstudio::analysis::Problem problem = t_project.analysis().problem(); OptionalInt index = getProjectRadianceJobIndex(t_project); if (index) { return; // nothing to do } openstudio::runmanager::ConfigOptions co(true); std::vector<openstudio::runmanager::ToolInfo> rad = co.getTools().getAllByName("rad").tools(); if (!rad.empty()) { openstudio::path radiancePath = rad.back().localBinPath.parent_path(); OptionalInt index = problem.getWorkflowStepIndexByJobType(runmanager::JobType::ModelToIdf); if (index) { LOG_FREE(Debug, "WorkflowTools", "Adding radiance job at location " << *index); openstudio::runmanager::WorkItem wi = runmanager::Workflow::radianceDaylightCalculations(getOpenStudioRubyIncludePath(), radiancePath); wi.jobkeyname = "pat-radiance-job"; problem.insert(*index, wi); } } }
path setFileExtension(const path& p, const std::string& ext, bool replaceOnMismatch, bool warnOnMismatch) { path result(p); path wext = toPath(ext); std::string pext = boost::filesystem::extension(p); if (!pext.empty()) { // remove '.' from pext pext = std::string(++pext.begin(),pext.end()); } if (!pext.empty()) { if (pext != wext.string()) { if (warnOnMismatch) { LOG_FREE(Warn,"openstudio.setFileExtension","Path p, '" << toString(p) << "', has an unexpected file extension. Was expecting '" << toString(wext) << "'."); } if (!replaceOnMismatch) { return result; } } } // if result.replace_extension(wext.string()); return result; }
void saveModelTempDir(const openstudio::path& modelTempDir, const openstudio::path& osmPath) { bool test = true; // must remove file, QFile::copy does not overwrite QFileInfo osmInfo(toQString(osmPath)); if (osmInfo.exists() && osmInfo.isFile()){ test = QFile::remove(toQString(osmPath)); if (!test){ LOG_FREE(Error, "saveModelTempDir", "Could not remove previous osm at '" << toString(osmPath) << "'"); } } // copy osm file openstudio::path srcPath = modelTempDir / toPath("in.osm"); test = QFile::copy(toQString(srcPath), toQString(osmPath)); if (!test){ LOG_FREE(Error, "saveModelTempDir", "Could not copy osm from '" << toString(srcPath) << "' to '" << toString(osmPath) << "'"); } if( QFileInfo(toQString(osmPath)).exists() ) { // copy resources openstudio::path srcDir = modelTempDir / toPath("resources"); openstudio::path dstDir = osmPath.parent_path() / osmPath.stem(); openstudio::path srcproject = srcDir / toPath("project.osp"); openstudio::path destproject = dstDir / toPath("project.osp"); // LOG_FREE(Debug, "saveModelTempDir", "copying project file: " << toString(srcproject) << " to " << toString(destproject)); // QFile::copy(toQString(srcproject), toQString(destproject)); LOG_FREE(Debug, "saveModelTempDir", "Copying " << toString(srcDir) << " to " << toString(dstDir)); test = copyDir(toQString(srcDir), toQString(dstDir)); if (!test){ LOG_FREE(Error, "saveModelTempDir", "Could not copy '" << toString(srcDir) << "' to '" << toString(dstDir) << "'"); } // TODO: Open all osps just copied over to make the stored paths look reasonable. } }
void iniche_free_log(log_data_t **p) { if(*p == NULL) { return; } #ifdef USE_LOGFILE if((*p)->log_fp) { nv_fclose((*p)->log_fp); (*p)->log_fp = NULL; } #endif if((*p)->argv) { LOG_FREE((*p)->argv); (*p)->argv = NULL; } LOG_FREE(*p); *p = NULL; }
bool copyDir(const QString &srcPath, const QString &dstPath) { bool result = true; bool test = true; LOG_FREE(Info, "copyDir", "copyDir '" << toString(srcPath) << "' to '" << toString(dstPath) << "'"); // ensure directory exists QFileInfo dstInfo(dstPath); QString fileName = dstInfo.fileName(); if (!dstInfo.exists() || !dstInfo.isDir()){ QDir parentDstDir(QFileInfo(dstPath).path()); LOG_FREE(Info, "copyDir", "Creating directory named = '" << toString(fileName) << "' in parentDstDir = '" << toString(parentDstDir.path()) << "'"); if (!parentDstDir.mkpath(fileName)){ LOG_FREE(Error, "copyDir", "Failed to create directory = '" << toString(fileName) << "' in parentDstDir = '" << toString(parentDstDir.path()) << "'"); return false; } } QDir srcDir(srcPath); // remove all files in dst as well as any directories in dst that are not in src test = synchDirStructures(srcPath, dstPath); if (!test){ LOG_FREE(Error, "copyDir", "Failed to synch destination '" << toString(dstPath) << "' with source '" << toString(srcPath) << "'"); result = false; } // copy all files in src to dst for (const QFileInfo &srcItemInfo : srcDir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot)) { QString srcItemPath = srcPath + "/" + srcItemInfo.fileName(); QString dstItemPath = dstPath + "/" + srcItemInfo.fileName(); QFileInfo dstItemInfo = QFileInfo(dstItemPath); if (srcItemInfo.isDir()) { test = copyDir(srcItemPath, dstItemPath); if (!test){ LOG_FREE(Error, "copyDir", "Failed to copy directory '" << toString(srcItemPath) << "' to '" << toString(dstItemPath) << "'"); result = false; // DLM: do we really want to give up here? //return false; } } else if (srcItemInfo.isFile()) { test = QFile::copy(srcItemPath, dstItemPath); if (!test){ LOG_FREE(Error, "copyDir", "Failed to copy file '" << toString(srcItemPath) << "' to '" << toString(dstItemPath) << "'"); result = false; // DLM: do we really want to give up here? //return false; } } } return result; }
unsigned x86emu_clear_log(x86emu_t *emu, int flush) { if(!emu) emu = &M; if(flush && emu->log.flush) { if(emu->log.ptr && emu->log.ptr != emu->log.buf) { emu->log.flush(emu, emu->log.buf, emu->log.ptr - emu->log.buf); } } if((emu->log.ptr = emu->log.buf)) *emu->log.ptr = 0; return emu->log.ptr ? LOG_FREE(emu) : 0; }
OptionalInt getProjectRadianceJobIndex(const openstudio::analysisdriver::SimpleProject &t_project) { openstudio::analysis::Problem problem = t_project.analysis().problem(); OptionalInt index = problem.getWorkflowStepIndexByJobType(runmanager::JobType::ModelToIdf); LOG_FREE(Trace, "WorkflowTools", "ModelToIdf job found " << (index?"true":"false")); if (index) { LOG_FREE(Trace, "WorkflowTools", "ModelToIdf job found at " << *index); } else { return OptionalInt(); } int i = *index - 1; std::vector<openstudio::analysis::WorkflowStep> workflow = problem.workflow(); if (i > 0 && workflow[i].isWorkItem() && workflow[i].workItem().jobkeyname == "pat-radiance-job") { return i; } else { return OptionalInt(); } }
path relativePath(const path& p,const path& base) { path wp = p; path wBase = base; path::const_iterator wpIt = wp.begin(); path::const_iterator wpEnd = wp.end(); path::const_iterator wBaseIt = wBase.begin(); path::const_iterator wBaseEnd = wBase.end(); while ((wpIt != wpEnd) && (wBaseIt != wBaseEnd) && ((*wpIt) == (*wBaseIt))) { ++wpIt; ++wBaseIt; } // p is not an extension of base, try to complete, then return p if (!((wBaseIt == wBaseEnd) || (toString(*wBaseIt) == "."))) { path completeP = boost::filesystem::complete(p); path completeBase = boost::filesystem::complete(base); if ((completeP != wp) || (completeBase != wBase)) { LOG_FREE(Debug,"openstudio.utilities.core","Path '" << toString(p) << "' does not extend base '" << toString(base) << "'. Try again after completing both paths."); return relativePath(completeP,completeBase); } else { LOG_FREE(Debug,"openstudio.utilities.core","Path '" << toString(p) << "' does not extend base '" << toString(base) << "'."); return path(); } } // p is an extension of base, keep whatever remains of p path result; while (wpIt != wpEnd) { result = result/(*wpIt); ++wpIt; } return result; }
void SpaceTypesController::onAddObject(const openstudio::model::ModelObject& modelObject) { if (IddObjectType::OS_SpaceType == modelObject.iddObjectType().value()) { openstudio::model::SpaceType(this->model()); return; } boost::optional<model::ParentObject> parent = modelObject.parent(); OS_ASSERT(parent); // Expect a load from the gridview loads tab switch (modelObject.iddObjectType().value()){ case IddObjectType::OS_People: openstudio::model::People(openstudio::model::PeopleDefinition(this->model())).setParent(*parent); break; case IddObjectType::OS_InternalMass: openstudio::model::InternalMass(openstudio::model::InternalMassDefinition(this->model())).setParent(*parent); break; case IddObjectType::OS_Lights: openstudio::model::Lights(openstudio::model::LightsDefinition(this->model())).setParent(*parent); break; case IddObjectType::OS_Luminaire: openstudio::model::Luminaire(openstudio::model::LuminaireDefinition(this->model())).setParent(*parent); break; case IddObjectType::OS_ElectricEquipment: openstudio::model::ElectricEquipment(openstudio::model::ElectricEquipmentDefinition(this->model())).setParent(*parent); break; case IddObjectType::OS_GasEquipment: openstudio::model::GasEquipment(openstudio::model::GasEquipmentDefinition(this->model())).setParent(*parent); break; case IddObjectType::OS_SteamEquipment: openstudio::model::SteamEquipment(openstudio::model::SteamEquipmentDefinition(this->model())).setParent(*parent); break; case IddObjectType::OS_OtherEquipment: openstudio::model::OtherEquipment(openstudio::model::OtherEquipmentDefinition(this->model())).setParent(*parent); break; case IddObjectType::OS_WaterUse_Equipment: openstudio::model::WaterUseEquipment(openstudio::model::WaterUseEquipmentDefinition(this->model())).setParent(*parent); break; default: // Should not get here OS_ASSERT(false); LOG_FREE(Error, "LoadsController", "Unknown IddObjectType '" << modelObject.iddObjectType().valueName() << "'"); } }
bool saveJSON(const QVariant& json, openstudio::path p, bool overwrite) { // Ensures file extension is .json. Warns if there is a mismatch. p = setFileExtension(p,"json",true); openstudio::filesystem::ofstream file(p, std::ios_base::binary); if (file.is_open()) { QJsonDocument doc = QJsonDocument::fromVariant(json); const auto json = doc.toJson(); file.write(json.constData(), json.size()); file.close(); return true; } LOG_FREE(Error,"openstudio.Json","Could not open file " << toString(p) << " for writing."); return false; }
bool saveJSON(const QVariant& json, openstudio::path p, bool overwrite) { // Ensures file extension is .json. Warns if there is a mismatch. p = setFileExtension(p,"json",true); // Use QFile and QIODevice serialize QFile file(toQString(p)); if (file.open(QFile::WriteOnly)) { QJsonDocument doc = QJsonDocument::fromVariant(json); file.write(doc.toJson()); file.close(); return true; } LOG_FREE(Error,"openstudio.Json","Could not open file " << toString(p) << " for writing."); return false; }
openstudio::path saveModel(openstudio::model::Model model, const openstudio::path& osmPath, const openstudio::path& modelTempDir) { openstudio::path modelPath = osmPath; if (getFileExtension(osmPath).empty()) { modelPath = setFileExtension(osmPath,modelFileExtension(),false,true); } // save osm to temp directory, saveModelTempDir will copy to real location openstudio::path tempModelPath = modelTempDir / toPath("in.osm"); Workspace(model).save(tempModelPath,true); LOG_FREE(Debug, "saveModel", "Saved model to '" << toString(tempModelPath) << "'"); // DLM: eventually put saveRunManagerDatabase here, needs to happen before saveModelTempDir // DLM: eventually add this back in too // DLM: for now this is accomplished by calling saveModelTempDir after saveModel in all cases //saveModelTempDir(modelTempDir, modelPath); return modelPath; }
std::vector<std::vector<Point3d> > computeTriangulation(const Point3dVector& vertices, const std::vector<std::vector<Point3d> >& holes, double tol) { std::vector<std::vector<Point3d> > result; // check input if (vertices.size () < 3){ return result; } boost::optional<Vector3d> normal = getOutwardNormal(vertices); if (!normal || normal->z() > -0.999){ return result; } for (const auto& hole : holes){ normal = getOutwardNormal(hole); if (!normal || normal->z() > -0.999){ return result; } } std::vector<Point3d> allPoints; // PolyPartition does not support holes which intersect the polygon or share an edge // if any hole is not fully contained we will use boost to remove all the holes bool polyPartitionHoles = true; for (const std::vector<Point3d>& hole : holes){ if (!within(hole, vertices, tol)){ // PolyPartition can't handle this polyPartitionHoles = false; break; } } if (!polyPartitionHoles){ // use boost to do all the intersections std::vector<std::vector<Point3d> > allFaces = subtract(vertices, holes, tol); std::vector<std::vector<Point3d> > noHoles; for (const std::vector<Point3d>& face : allFaces){ std::vector<std::vector<Point3d> > temp = computeTriangulation(face, noHoles); result.insert(result.end(), temp.begin(), temp.end()); } return result; } // convert input to vector of TPPLPoly std::list<TPPLPoly> polys; TPPLPoly outerPoly; // must be counter-clockwise, input vertices are clockwise outerPoly.Init(vertices.size()); outerPoly.SetHole(false); unsigned n = vertices.size(); for(unsigned i = 0; i < n; ++i){ // should all have zero z coordinate now double z = vertices[n-i-1].z(); if (abs(z) > tol){ LOG_FREE(Error, "utilities.geometry.computeTriangulation", "All points must be on z = 0 plane for triangulation methods"); return result; } Point3d point = getCombinedPoint(vertices[n-i-1], allPoints, tol); outerPoly[i].x = point.x(); outerPoly[i].y = point.y(); } outerPoly.SetOrientation(TPPL_CCW); polys.push_back(outerPoly); for (const std::vector<Point3d>& holeVertices : holes){ if (holeVertices.size () < 3){ LOG_FREE(Error, "utilities.geometry.computeTriangulation", "Hole has fewer than 3 points, ignoring"); continue; } TPPLPoly innerPoly; // must be clockwise, input vertices are clockwise innerPoly.Init(holeVertices.size()); innerPoly.SetHole(true); //std::cout << "inner :"; for(unsigned i = 0; i < holeVertices.size(); ++i){ // should all have zero z coordinate now double z = holeVertices[i].z(); if (abs(z) > tol){ LOG_FREE(Error, "utilities.geometry.computeTriangulation", "All points must be on z = 0 plane for triangulation methods"); return result; } Point3d point = getCombinedPoint(holeVertices[i], allPoints, tol); innerPoly[i].x = point.x(); innerPoly[i].y = point.y(); } innerPoly.SetOrientation(TPPL_CW); polys.push_back(innerPoly); } // do partitioning TPPLPartition pp; std::list<TPPLPoly> resultPolys; int test = pp.Triangulate_EC(&polys,&resultPolys); if (test == 0){ test = pp.Triangulate_MONO(&polys, &resultPolys); } if (test == 0){ LOG_FREE(Error, "utilities.geometry.computeTriangulation", "Failed to partition polygon"); return result; } // convert back to vertices std::list<TPPLPoly>::iterator it, itend; //std::cout << "Start" << std::endl; for(it = resultPolys.begin(), itend = resultPolys.end(); it != itend; ++it){ it->SetOrientation(TPPL_CW); std::vector<Point3d> triangle; for (long i = 0; i < it->GetNumPoints(); ++i){ TPPLPoint point = it->GetPoint(i); triangle.push_back(Point3d(point.x, point.y, 0)); } //std::cout << triangle << std::endl; result.push_back(triangle); } //std::cout << "End" << std::endl; return result; }
OSArgument toOSArgument(const QVariant& variant, const VersionString& version) { QVariantMap map = variant.toMap(); OSArgumentType type(map["type"].toString().toStdString()); QVariant value, defaultValue; OS_ASSERT(value.isNull() && defaultValue.isNull()); if (map.contains("value")) { if (type == OSArgumentType::Quantity) { value = toQuantityQVariant(map,"value","value_units"); } else { value = map["value"]; } } if (map.contains("default_value")) { if (type == OSArgumentType::Quantity) { defaultValue = toQuantityQVariant(map,"default_value","default_value_units"); } else { defaultValue = map["default_value"]; } } std::vector<QVariant> domain; if (map.contains("domain")) { if (type == OSArgumentType::Quantity) { domain = deserializeOrderedVector( map["domain"].toList(), "domain_value_index", std::function<QVariant (QVariant*)>(std::bind( toQuantityQVariant, std::bind(&QVariant::toMap,std::placeholders::_1), "value", "units"))); } else { domain = deserializeOrderedVector( map["domain"].toList(), "value", "domain_value_index", std::function<QVariant (const QVariant&)>(std::bind(boost::value_factory<QVariant>(),std::placeholders::_1))); } } StringVector choices, choiceDisplayNames; if (map.contains("choices")) { QVariantList choicesList = map["choices"].toList(); choices = deserializeOrderedVector( choicesList, "value", "choice_index", std::function<std::string (QVariant*)>(std::bind(&QString::toStdString, std::bind(&QVariant::toString,std::placeholders::_1)))); if (!choicesList.empty() && choicesList[0].toMap().contains("display_name")) { try { choiceDisplayNames = deserializeOrderedVector( choicesList, "display_name", "choice_index", std::function<std::string (QVariant*)>(std::bind(&QString::toStdString, std::bind(&QVariant::toString,std::placeholders::_1)))); } catch (...) { LOG_FREE(Warn,"openstudio.ruleset.OSArgument","Unable to deserialize partial list of choice display names."); } } } return OSArgument(toUUID(map["uuid"].toString().toStdString()), toUUID(map["version_uuid"].toString().toStdString()), map["name"].toString().toStdString(), map.contains("display_name") ? map["display_name"].toString().toStdString() : std::string(), map.contains("description") ? map["description"].toString().toStdString() : boost::optional<std::string>(), type, map.contains("units") ? map["units"].toString().toStdString() : boost::optional<std::string>(), map["required"].toBool(), map["modelDependent"].toBool(), value, defaultValue, OSDomainType(map["domain_type"].toString().toStdString()), domain, choices, choiceDisplayNames, map.contains("is_read") ? map["is_read"].toBool() : false, map.contains("extension") ? map["extension"].toString().toStdString() : std::string()); }
int main(int argc, char *argv[]) { ruby_sysinit(&argc, &argv); { RUBY_INIT_STACK; ruby_init(); } #if _DEBUG || (__GNUC__ && !NDEBUG) #ifdef _WIN32 const char *logfilepath = "./openstudio_pat.log"; #else const char *logfilepath = "/var/log/openstudio_pat.log"; #endif openstudio::Logger::instance().standardOutLogger().setLogLevel(Debug); openstudio::FileLogSink fileLog(openstudio::toPath(logfilepath)); fileLog.setLogLevel(Debug); #else openstudio::Logger::instance().standardOutLogger().setLogLevel(Warn); #endif // list of Ruby modules we want to load into the interpreter std::vector<std::string> modules; modules.push_back("openstudioutilitiescore"); modules.push_back("openstudioutilitiesbcl"); modules.push_back("openstudioutilitiesidd"); modules.push_back("openstudioutilitiesidf"); modules.push_back("openstudioutilities"); modules.push_back("openstudiomodel"); modules.push_back("openstudiomodelcore"); modules.push_back("openstudiomodelsimulation"); modules.push_back("openstudiomodelresources"); modules.push_back("openstudiomodelgeometry"); modules.push_back("openstudiomodelhvac"); modules.push_back("openstudiomodelrefrigeration"); modules.push_back("openstudioenergyplus"); modules.push_back("openstudioruleset"); bool cont = true; while(cont) { cont = false; // Initialize the embedded Ruby interpreter std::shared_ptr<openstudio::detail::RubyInterpreter> rubyInterpreter( new openstudio::detail::RubyInterpreter(openstudio::getOpenStudioRubyPath(), openstudio::getOpenStudioRubyScriptsPath(), modules)); // Initialize the argument getter QSharedPointer<openstudio::ruleset::RubyUserScriptInfoGetter> infoGetter( new openstudio::ruleset::EmbeddedRubyUserScriptInfoGetter<openstudio::detail::RubyInterpreter>(rubyInterpreter)); // Make the run path the default plugin search location QCoreApplication::addLibraryPath(openstudio::toQString(openstudio::getApplicationRunDirectory())); openstudio::pat::PatApp app(argc, argv, infoGetter); openstudio::Application::instance().setApplication(&app); try { return app.exec(); } catch (const std::exception &e) { LOG_FREE(Fatal, "PatApp", "An unhandled exception has occurred: " << e.what()); cont = true; QMessageBox msgBox; msgBox.setWindowTitle("Unhandled Exception"); msgBox.setIcon(QMessageBox::Critical); msgBox.setText("An unhandled exception has occurred."); msgBox.setInformativeText(e.what()); msgBox.setStandardButtons(QMessageBox::Retry | QMessageBox::Close); msgBox.button(QMessageBox::Retry)->setText("Relaunch"); if (msgBox.exec() == QMessageBox::Close) { cont = false; } } catch (...) { LOG_FREE(Fatal, "PatApp", "An unknown exception has occurred."); cont = true; QMessageBox msgBox; msgBox.setWindowTitle("Unknown Exception"); msgBox.setIcon(QMessageBox::Critical); msgBox.setText("An unknown exception has occurred."); msgBox.setStandardButtons(QMessageBox::Retry | QMessageBox::Close); msgBox.button(QMessageBox::Retry)->setText("Relaunch"); if (msgBox.exec() == QMessageBox::Close) { cont = false; } } } }
int glog_app(void * pio) { int i; char *buf; buf = (char *) ((GEN_IO)pio)->inbuf; ns_printf(pio,"%s\n", buf); if(p_global_log == NULL) { p_global_log = (log_data_t *) LOG_MALLOC(sizeof(log_data_t)); if(p_global_log == NULL) { ns_printf(pio,"glog_app: LOG_MALLOC() failed\n"); return(-1); } memset(p_global_log, 0, sizeof(log_data_t)); p_global_log->log_level = DEFAULT_LOG_LEVEL; #ifdef USE_LOGFILE strcpy(p_global_log->log_fname, LOG_FILE_DEFAULT); #endif } if(p_global_log->argv) { LOG_FREE(p_global_log->argv); p_global_log->argv = NULL; } p_global_log->argv = parse_args(buf, GLOG_MAX_ARGC, &(p_global_log->argc)); if(p_global_log->argv == NULL) { ns_printf(pio, "parse_args() failed for %s\n", buf); return(-1); } #if 0 for(i = 0; i < p_global_log->argc; i++) { ns_printf(pio, "%s ", p_global_log->argv[i]); } ns_printf(pio,"\n"); #endif if(glog_process_args(p_global_log)) { ns_printf(pio, "glog_process_args() failed\n"); return(-1); } /* Here now we can configure our log app */ if(p_global_log->stop_flag) { glog_with_type(LOG_TYPE_INFO, "INICHE LOG stopped", 1); iniche_free_log(&p_global_log); return(0); } if(p_global_log->start_flag) { #ifdef USE_LOGFILE if(iniche_create_log(&p_global_log, p_global_log->log_level, p_global_log->log_fname, pio)) #else if(iniche_create_log(&p_global_log, p_global_log->log_level, NULL, pio)) #endif { ns_printf(pio,"iniche_create_log() failed\n"); } else { ns_printf(pio,"starting glog:\n"); glog_with_type(LOG_TYPE_INFO, "INICHE LOG initialized", 1); } p_global_log->start_flag = 0; } return 0; }
int main(int argc, char *argv[]) { #if RUBY_API_VERSION_MAJOR && RUBY_API_VERSION_MAJOR==2 ruby_sysinit(&argc, &argv); { RUBY_INIT_STACK; ruby_init(); } #endif #if _DEBUG || (__GNUC__ && !NDEBUG) openstudio::Logger::instance().standardOutLogger().setLogLevel(Debug); openstudio::FileLogSink fileLog(openstudio::toPath(logfilepath)); fileLog.setLogLevel(Debug); #else openstudio::Logger::instance().standardOutLogger().setLogLevel(Warn); #endif bool cont = true; while(cont) { cont = false; std::vector<std::string> modules; modules.push_back("openstudioutilitiescore"); modules.push_back("openstudioutilitiesbcl"); modules.push_back("openstudioutilitiesidd"); modules.push_back("openstudioutilitiesidf"); modules.push_back("openstudioutilities"); modules.push_back("openstudiomodel"); modules.push_back("openstudiomodelcore"); modules.push_back("openstudiomodelsimulation"); modules.push_back("openstudiomodelresources"); modules.push_back("openstudiomodelgeometry"); modules.push_back("openstudiomodelhvac"); modules.push_back("openstudioenergyplus"); modules.push_back("openstudioruleset"); //try { // Initialize the embedded Ruby interpreter boost::shared_ptr<openstudio::detail::RubyInterpreter> rubyInterpreter( new openstudio::detail::RubyInterpreter(openstudio::getOpenStudioRubyPath(), openstudio::getOpenStudioRubyScriptsPath(), modules)); // Initialize the argument getter QSharedPointer<openstudio::ruleset::RubyUserScriptArgumentGetter> argumentGetter( new openstudio::ruleset::detail::RubyUserScriptArgumentGetter_Impl<openstudio::detail::RubyInterpreter>(rubyInterpreter)); openstudio::OpenStudioApp app(argc, argv, argumentGetter); openstudio::Application::instance().setApplication(&app); try { return app.exec(); } catch (const std::exception &e) { LOG_FREE(Fatal, "OpenStudio", "An unhandled exception has occurred: " << e.what()); cont = true; QMessageBox msgBox; msgBox.setWindowTitle("Unhandled Exception"); msgBox.setIcon(QMessageBox::Critical); msgBox.setText("An unhandled exception has occurred."); msgBox.setInformativeText(e.what()); msgBox.setStandardButtons(QMessageBox::Retry | QMessageBox::Close); msgBox.button(QMessageBox::Retry)->setText("Relaunch"); if (msgBox.exec() == QMessageBox::Close) { cont = false; } } catch (...) { LOG_FREE(Fatal, "OpenStudio", "An unknown exception has occurred."); cont = true; QMessageBox msgBox; msgBox.setWindowTitle("Unknown Exception"); msgBox.setIcon(QMessageBox::Critical); msgBox.setText("An unknown exception has occurred."); msgBox.setStandardButtons(QMessageBox::Retry | QMessageBox::Close); msgBox.button(QMessageBox::Retry)->setText("Relaunch"); if (msgBox.exec() == QMessageBox::Close) { cont = false; } } } }
void Xfree(pointer ptr) { unsigned long size; unsigned long *pheader; /* free(NULL) IS valid :-( - and widely used throughout the server.. */ if (!ptr) return; pheader = (unsigned long *)((char *)ptr - SIZE_HEADER); #ifdef XALLOC_DEBUG if (MAGIC != pheader[1]) { /* Diagnostic */ if (MAGIC_FREE == pheader[1]) { #ifdef FATALERRORS XfreeTrap(); FatalError("Xalloc error: range already freed in Xrealloc() :-(\n"); #else ErrorF("Xalloc error: range already freed in Xrealloc() :-(\a\n"); sleep(5); XfreeTrap(); #endif LOG_FREE("Xalloc error: ranged already freed in Xrealloc() :-(", ptr); return; } #ifdef FATALERRORS XfreeTrap(); FatalError("Xalloc error: Header corrupt in Xfree() :-(\n"); #else ErrorF("Xalloc error: Header corrupt in Xfree() :-(\n"); XfreeTrap(); #endif LOG_FREE("Xalloc error: Header corrupt in Xfree() :-(", ptr); return; } #endif /* XALLOC_DEBUG */ size = pheader[0]; if (size <= MAX_SMALL) { int indx; /* * small block */ #ifdef SIZE_TAIL if (MAGIC2 != *(unsigned long *)((char *)ptr + size)) { /* Diagnostic */ #ifdef FATALERRORS XfreeTrap(); FatalError("Xalloc error: Tail corrupt in Xfree() for small block (adr=0x%x, val=0x%x)\n",(char *)ptr + size,*(unsigned long *)((char *)ptr + size)); #else ErrorF("Xalloc error: Tail corrupt in Xfree() for small block (adr=0x%x, val=0x%x)\n",(char *)ptr + size,*(unsigned long *)((char *)ptr + size)); XfreeTrap(); #endif LOG_FREE("Xalloc error: Tail corrupt in Xfree() for small block", ptr); return; } #endif /* SIZE_TAIL */ #ifdef XFREE_ERASES memset(ptr,0xF0,size); #endif /* XFREE_ERASES */ #ifdef XALLOC_DEBUG pheader[1] = MAGIC_FREE; #endif /* put this small block at the head of the list */ indx = (size-1) / SIZE_STEPS; *(unsigned long **)(ptr) = free_lists[indx]; free_lists[indx] = (unsigned long *)ptr; LOG_FREE("Xfree", ptr); return; #if defined(HAS_MMAP_ANON) || defined(MMAP_DEV_ZERO) } else if (size >= MIN_LARGE) { /* * large block */ #ifdef SIZE_TAIL if (MAGIC2 != ((unsigned long *)((char *)ptr + size))[0]) { /* Diagnostic */ #ifdef FATALERRORS XfreeTrap(); FatalError("Xalloc error: Tail corrupt in Xfree() for big block (adr=0x%x, val=0x%x)\n",(char *)ptr+size,((unsigned long *)((char *)ptr + size))[0]); #else ErrorF("Xalloc error: Tail corrupt in Xfree() for big block (adr=0x%x, val=0x%x)\n",(char *)ptr+size,((unsigned long *)((char *)ptr + size))[0]); XfreeTrap(); #endif LOG_FREE("Xalloc error: Tail corrupt in Xfree() for big block", ptr); return; } size += SIZE_TAIL; #endif /* SIZE_TAIL */ LOG_FREE("Xfree", ptr); size += SIZE_HEADER; munmap((caddr_t)pheader, (size_t)size); /* no need to clear - mem is inaccessible after munmap.. */ #endif /* HAS_MMAP_ANON */ } else { /* * medium sized block */ #ifdef SIZE_TAIL if (MAGIC2 != *(unsigned long *)((char *)ptr + size)) { /* Diagnostic */ #ifdef FATALERRORS XfreeTrap(); FatalError("Xalloc error: Tail corrupt in Xfree() for medium block (adr=0x%x, val=0x%x)\n",(char *)ptr + size,*(unsigned long *)((char *)ptr + size)); #else ErrorF("Xalloc error: Tail corrupt in Xfree() for medium block (adr=0x%x, val=0x%x)\n",(char *)ptr + size,*(unsigned long *)((char *)ptr + size)); XfreeTrap(); #endif LOG_FREE("Xalloc error: Tail corrupt in Xfree() for medium block", ptr); return; } #endif /* SIZE_TAIL */ #ifdef XFREE_ERASES memset(pheader,0xF0,size+SIZE_HEADER); #endif /* XFREE_ERASES */ #ifdef XALLOC_DEBUG pheader[1] = MAGIC_FREE; #endif LOG_FREE("Xfree", ptr); free((char *)pheader); } }
bool synchDirStructures(const QString &srcPath, const QString &dstPath) { bool result = true; bool test = true; QDir srcDir(srcPath); QDir dstDir(dstPath); if (srcDir.canonicalPath() == dstDir.canonicalPath()){ LOG_FREE(Warn, "synchDirStructures", "Cannot synch destination '" << toString(dstPath) << "' with source '" << toString(srcPath) << "' because they resolve to the same location"); return true; // already synched } LOG_FREE(Info, "synchDirStructures", "Synching destination '" << toString(dstPath) << "' with source '" << toString(srcPath) << "'"); // remove all files in dst as well as any directories in dst that are not in src for (const QFileInfo &dstItemInfo : dstDir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot)) { QString srcItemPath = srcPath + "/" + dstItemInfo.fileName(); QString dstItemPath = dstPath + "/" + dstItemInfo.fileName(); QFileInfo srcItemInfo = QFileInfo(srcItemPath); if (dstItemInfo.isDir()){ if (srcItemInfo.exists() && srcItemInfo.isDir()){ // directory also exists in source test = synchDirStructures(srcItemPath, dstItemPath); if (!test){ LOG_FREE(Error, "synchDirStructures", "Failed to synch destination '" << toString(dstItemPath) << "' with source '" << toString(srcItemPath) << "'"); result = false; // DLM: do we really want to give up here? //return result; } }else{ // directory does not exist in source test = removeDir(dstItemPath); if (!test){ LOG_FREE(Error, "synchDirStructures", "Failed to remove directory '" << toString(dstItemPath) << "'"); result = false; // DLM: do we really want to give up here? //return result; } } }else if (dstItemInfo.isFile()){ test = QFile::remove(dstItemInfo.absoluteFilePath()); if (!test){ LOG_FREE(Error, "synchDirStructures", "Failed to remove file '" << toString(dstItemInfo.absoluteFilePath()) << "'"); result = false; // DLM: do we really want to give up here? //return result; } } } return result; }
std::string getReportRequestMeasureArgument(const std::vector<runmanager::WorkItem>& workItems) { std::vector<openstudio::runmanager::RubyJobBuilder> rubyJobBuilders; // loop over all reporting measures and gather ruby jobs bool pastEnergyPlus = false; for (const auto& workItem : workItems) { if (workItem.type == openstudio::runmanager::JobType::EnergyPlus){ pastEnergyPlus = true; } if (pastEnergyPlus && workItem.type == openstudio::runmanager::JobType::UserScript){ openstudio::runmanager::RubyJobBuilder rjb(workItem); const std::vector<openstudio::runmanager::RubyJobBuilder>& mergedJobs = rjb.mergedJobs(); if (mergedJobs.empty()){ rubyJobBuilders.push_back(rjb); } else { rubyJobBuilders.insert(rubyJobBuilders.end(), mergedJobs.begin(), mergedJobs.end());; } } } QVariantList measureList; // loop over ruby jobs and gather information for report request measure for (const auto& rjb : rubyJobBuilders){ QVariantMap measureHash; // DLM: this is just UserScriptAdapter to get the actual script you need to use requiredFiles //measureHash["script"] = toQString(rjb.script()); //QVariantList requiredFileList; for (const auto& requiredFile : rjb.requiredFiles()){ //QVariantMap requiredFileMap; // second is local file path, first is absolute system path //requiredFileMap[toQString(requiredFile.second)] = toQString(requiredFile.first); //requiredFileList << requiredFileMap; // DLM: most measures have the measure mapped to both required file user_script.rb and measure.rb // if have both, use measure.rb if (istringEqual(toString(requiredFile.second), "user_script.rb")){ if (!measureHash.contains("measure")){ measureHash["measure"] = toQString(requiredFile.first); } } if (istringEqual(toString(requiredFile.second), "measure.rb")){ measureHash["measure"] = toQString(requiredFile.first); } } // DLM: I should probably be attaching these required files to this job in some way? // DLM: will this work for now given that we are removing the requirement for remote runs? //measureHash["required_files"] = requiredFileList; // The measure arguments will be script parameters in pairs of "--argumentName=name","argumentValue=value" QVariantMap argumentHash; QString lastArgumentName; QRegularExpression argumentNameExp("--argumentName=(.*)"); QRegularExpression argumentValueExp("--argumentValue=(.*)"); for (const auto& parameter : rjb.getScriptParameters()){ QString temp = toQString(parameter); QRegularExpressionMatch match = argumentNameExp.match(temp); if (match.hasMatch()){ lastArgumentName = match.captured(1); } else { match = argumentValueExp.match(temp); if (match.hasMatch()){ argumentHash[lastArgumentName] = match.captured(1); } else { LOG_FREE(Error, "openstudio.runmanager.getReportRequestMeasureArgument", "Unexpected parameter '" << parameter << "'"); } } }; measureHash["arguments"] = argumentHash; // DLM: args were not populated here //QVariantList argList; //auto args = openstudio::runmanager::RubyJobBuilder::toOSArguments(itr->params); //for (const auto& arg : args){ // argList << ruleset::detail::toVariant(arg); //} //measureHash["arguments"] = argList; if (measureHash.contains("measure")){ measureList << measureHash; } else{ LOG_FREE(Debug, "openstudio.runmanager.getReportRequestMeasureArgument", "RubyJobBuilder does not include measure") } } QJsonDocument document = QJsonDocument::fromVariant(measureList); QString jsonValue = document.toJson(QJsonDocument::Compact); //QString jsonValue = document.toJson(QJsonDocument::Indented); return toString(jsonValue); }