void ImageImporter::execute() { if (mFilename == "") throw Exception("No filename was supplied to the ImageImporter"); uchar* convertedPixelData; // Load image from disk using Qt QImage image; reportInfo() << "Trying to load image..." << Reporter::end(); if(!image.load(mFilename.c_str())) { throw FileNotFoundException(mFilename); } reportInfo() << "Loaded image with size " << image.width() << " " << image.height() << Reporter::end(); QImage::Format format; if(mGrayscale) { format = QImage::Format_Grayscale8; } else { format = QImage::Format_RGB888; } QImage convertedImage = image.convertToFormat(format); // Get pixel data convertedPixelData = convertedImage.bits(); Image::pointer output = getOutputData<Image>(); std::cout << "image info" << std::endl; std::cout << convertedImage.width() << std::endl; std::cout << convertedImage.depth() << std::endl; std::cout << convertedImage.bytesPerLine() << std::endl; if(convertedImage.width()*convertedImage.depth()/8 != convertedImage.bytesPerLine()) { const int bytesPerPixel = (convertedImage.depth()/8); std::unique_ptr<uchar[]> fixedPixelData = std::make_unique<uchar[]>(image.width()*image.height()); // Misalignment for(int scanline = 0; scanline < image.height(); ++scanline) { std::memcpy( &fixedPixelData[scanline*image.width()*bytesPerPixel], &convertedPixelData[scanline*convertedImage.bytesPerLine()], image.width()*bytesPerPixel ); } output->create( image.width(), image.height(), TYPE_UINT8, mGrayscale ? 1 : 3, getMainDevice(), fixedPixelData.get() ); } else { output->create( image.width(), image.height(), TYPE_UINT8, mGrayscale ? 1 : 3, getMainDevice(), convertedPixelData ); } }
void ManualImageStreamer::stop() { { std::unique_lock<std::mutex> lock(mStopMutex); mStop = true; } mThread->join(); reportInfo() << "File streamer thread returned" << reportEnd(); }
void setupUi(QDialog *kregularGraphDialog) { if (kregularGraphDialog->objectName().isEmpty()) kregularGraphDialog->setObjectName(QString::fromUtf8("kregularGraphDialog")); kregularGraphDialog->setWindowModality(Qt::WindowModal); kregularGraphDialog->resize(377, 249); kregularGraphDialog->setMinimumSize(QSize(377, 249)); kregularGraphDialog->setMaximumSize(QSize(377, 249)); kregularGraphDialog->setLayoutDirection(Qt::LeftToRight); kregularGraphDialog->setModal(false); buttonBox = new QDialogButtonBox(kregularGraphDialog); buttonBox->setObjectName(QString::fromUtf8("buttonBox")); buttonBox->setGeometry(QRect(30, 190, 331, 32)); buttonBox->setOrientation(Qt::Horizontal); buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok); formLayoutWidget = new QWidget(kregularGraphDialog); formLayoutWidget->setObjectName(QString::fromUtf8("formLayoutWidget")); formLayoutWidget->setGeometry(QRect(39, 70, 291, 101)); formLayout = new QFormLayout(formLayoutWidget); formLayout->setObjectName(QString::fromUtf8("formLayout")); formLayout->setHorizontalSpacing(5); formLayout->setVerticalSpacing(23); formLayout->setContentsMargins(0, 0, 0, 0); label = new QLabel(formLayoutWidget); label->setObjectName(QString::fromUtf8("label")); formLayout->setWidget(0, QFormLayout::LabelRole, label); label_2 = new QLabel(formLayoutWidget); label_2->setObjectName(QString::fromUtf8("label_2")); formLayout->setWidget(1, QFormLayout::LabelRole, label_2); spinBox = new QSpinBox(formLayoutWidget); spinBox->setObjectName(QString::fromUtf8("spinBox")); spinBox->setMinimum(1); spinBox->setMaximum(1000); formLayout->setWidget(0, QFormLayout::FieldRole, spinBox); spinBox_2 = new QSpinBox(formLayoutWidget); spinBox_2->setObjectName(QString::fromUtf8("spinBox_2")); formLayout->setWidget(1, QFormLayout::FieldRole, spinBox_2); label_3 = new QLabel(kregularGraphDialog); label_3->setObjectName(QString::fromUtf8("label_3")); label_3->setGeometry(QRect(40, 30, 291, 18)); retranslateUi(kregularGraphDialog); QObject::connect(buttonBox,SIGNAL(accepted()), this , SLOT(reportInfo())); QObject::connect(buttonBox, SIGNAL(accepted()), kregularGraphDialog, SLOT(accept())); QObject::connect(buttonBox, SIGNAL(rejected()), kregularGraphDialog, SLOT(reject())); QMetaObject::connectSlotsByName(kregularGraphDialog); } // setupUi
void getCommand(unsigned long runTime) { int ch; unsigned long preTime = getclocks(); do { while (cmdWaitAck > 0 && !cmdBuffferNearFull()) { response_ack(); cmdWaitAck--; } if (commandAvailable() <= 0) break; ch = readCommandChr(); if (ch == '\n' || ch == '\t' || (ch == ':' && !cmdCommentDetected)) { cmdCommentDetected = false; if (cmdTail == cmdTailOut) continue; cmdBuffer[cmdTail] = '\0'; cmdTail = (cmdTail + 1) % cmdSize; if (parseCommand() == false) request_to_send(cmdLineNumber + 1); else if (reportInfo() == false) cmdTailOut = skipUnusedCode(); cmdTail = cmdTailOut; if (cmdBuffferNearFull()) cmdWaitAck++; else response_ack(); } else if (ch == ';') cmdCommentDetected = true; else if (cmdCommentDetected == false) { cmdBuffer[cmdTail] = ch; cmdTail = (cmdTail + 1) % cmdSize; } } while (getclocks() - preTime < runTime); }
void ImageClassifier::execute() { run(); Tensor::pointer tensor = m_engine->getOutputNodes().begin()->second.data; TensorAccess::pointer access = tensor->getAccess(ACCESS_READ); auto data = access->getData<2>(); ImageClassification::pointer output = getOutputData<ImageClassification>(0); for(int i = 0; i < data.dimension(0); ++i) { // for each input image std::map<std::string, float> mapResult; for(int j = 0; j < data.dimension(1); ++j) { // for each class mapResult[mLabels[j]] = data(i, j); reportInfo() << mLabels[j] << ": " << data(i, j) << reportEnd(); } output->create(mapResult); } }
/* * That is a method which gets called from check_wrapper * */ int CppCheckExecutor::check_internal(CppCheck& cppcheck, int /*argc*/, const char* const argv[]) { Settings& settings = cppcheck.settings(); _settings = &settings; bool std = tryLoadLibrary(settings.library, argv[0], "std.cfg"); bool posix = true; if (settings.standards.posix) posix = tryLoadLibrary(settings.library, argv[0], "posix.cfg"); bool windows = true; if (settings.isWindowsPlatform()) windows = tryLoadLibrary(settings.library, argv[0], "windows.cfg"); if (!std || !posix || !windows) { const std::list<ErrorLogger::ErrorMessage::FileLocation> callstack; const std::string msg("Failed to load " + std::string(!std ? "std.cfg" : !posix ? "posix.cfg" : "windows.cfg") + ". Your Cppcheck installation is broken, please re-install."); #ifdef CFGDIR const std::string details("The Cppcheck binary was compiled with CFGDIR set to \"" + std::string(CFGDIR) + "\" and will therefore search for " "std.cfg in that path."); #else const std::string cfgfolder(Path::fromNativeSeparators(Path::getPathFromFilename(argv[0])) + "cfg"); const std::string details("The Cppcheck binary was compiled without CFGDIR set. Either the " "std.cfg should be available in " + cfgfolder + " or the CFGDIR " "should be configured."); #endif ErrorLogger::ErrorMessage errmsg(callstack, Severity::information, msg+" "+details, "failedToLoadCfg", false); reportErr(errmsg); return EXIT_FAILURE; } if (settings.reportProgress) time1 = std::time(0); if (settings._xml) { reportErr(ErrorLogger::ErrorMessage::getXMLHeader(settings._xml_version)); } unsigned int returnValue = 0; if (settings._jobs == 1) { // Single process settings.jointSuppressionReport = true; std::size_t totalfilesize = 0; for (std::map<std::string, std::size_t>::const_iterator i = _files.begin(); i != _files.end(); ++i) { totalfilesize += i->second; } std::size_t processedsize = 0; unsigned int c = 0; for (std::map<std::string, std::size_t>::const_iterator i = _files.begin(); i != _files.end(); ++i) { if (!_settings->library.markupFile(i->first) || !_settings->library.processMarkupAfterCode(i->first)) { returnValue += cppcheck.check(i->first); processedsize += i->second; if (!settings.quiet) reportStatus(c + 1, _files.size(), processedsize, totalfilesize); c++; } } // second loop to parse all markup files which may not work until all // c/cpp files have been parsed and checked for (std::map<std::string, std::size_t>::const_iterator i = _files.begin(); i != _files.end(); ++i) { if (_settings->library.markupFile(i->first) && _settings->library.processMarkupAfterCode(i->first)) { returnValue += cppcheck.check(i->first); processedsize += i->second; if (!settings.quiet) reportStatus(c + 1, _files.size(), processedsize, totalfilesize); c++; } } cppcheck.analyseWholeProgram(); } else if (!ThreadExecutor::isEnabled()) { std::cout << "No thread support yet implemented for this platform." << std::endl; } else { // Multiple processes ThreadExecutor executor(_files, settings, *this); returnValue = executor.check(); } if (settings.isEnabled("information") || settings.checkConfiguration) { const bool enableUnusedFunctionCheck = cppcheck.unusedFunctionCheckIsEnabled(); if (settings.jointSuppressionReport) { for (std::map<std::string, std::size_t>::const_iterator i = _files.begin(); i != _files.end(); ++i) { reportUnmatchedSuppressions(settings.nomsg.getUnmatchedLocalSuppressions(i->first, enableUnusedFunctionCheck)); } } reportUnmatchedSuppressions(settings.nomsg.getUnmatchedGlobalSuppressions(enableUnusedFunctionCheck)); } if (!settings.checkConfiguration) { cppcheck.tooManyConfigsError("",0U); if (settings.isEnabled("missingInclude") && (Preprocessor::missingIncludeFlag || Preprocessor::missingSystemIncludeFlag)) { const std::list<ErrorLogger::ErrorMessage::FileLocation> callStack; ErrorLogger::ErrorMessage msg(callStack, Severity::information, "Cppcheck cannot find all the include files (use --check-config for details)\n" "Cppcheck cannot find all the include files. Cppcheck can check the code without the " "include files found. But the results will probably be more accurate if all the include " "files are found. Please check your project's include directories and add all of them " "as include directories for Cppcheck. To see what files Cppcheck cannot find use " "--check-config.", Preprocessor::missingIncludeFlag ? "missingInclude" : "missingIncludeSystem", false); reportInfo(msg); } } if (settings._xml) { reportErr(ErrorLogger::ErrorMessage::getXMLFooter(settings._xml_version)); } _settings = 0; if (returnValue) return settings._exitCode; else return 0; }
int CppCheckExecutor::check(int argc, const char* const argv[]) { Preprocessor::missingIncludeFlag = false; CppCheck cppCheck(*this, true); Settings& settings = cppCheck.settings(); _settings = &settings; if (!parseFromArgs(&cppCheck, argc, argv)) { return EXIT_FAILURE; } if (settings.reportProgress) time1 = std::time(0); if (settings._xml) { reportErr(ErrorLogger::ErrorMessage::getXMLHeader(settings._xml_version)); } unsigned int returnValue = 0; if (settings._jobs == 1) { // Single process std::size_t totalfilesize = 0; for (std::map<std::string, std::size_t>::const_iterator i = _files.begin(); i != _files.end(); ++i) { totalfilesize += i->second; } std::size_t processedsize = 0; unsigned int c = 0; for (std::map<std::string, std::size_t>::const_iterator i = _files.begin(); i != _files.end(); ++i) { returnValue += cppCheck.check(i->first); processedsize += i->second; if (!settings._errorsOnly) reportStatus(c + 1, _files.size(), processedsize, totalfilesize); c++; } cppCheck.checkFunctionUsage(); } else if (!ThreadExecutor::isEnabled()) { std::cout << "No thread support yet implemented for this platform." << std::endl; } else { // Multiple processes ThreadExecutor executor(_files, settings, *this); returnValue = executor.check(); } if (!settings.checkConfiguration) { if (!settings._errorsOnly) reportUnmatchedSuppressions(settings.nomsg.getUnmatchedGlobalSuppressions()); cppCheck.tooManyConfigsError("",0U); if (settings.isEnabled("missingInclude") && Preprocessor::missingIncludeFlag) { const std::list<ErrorLogger::ErrorMessage::FileLocation> callStack; ErrorLogger::ErrorMessage msg(callStack, Severity::information, "Cppcheck cannot find all the include files (use --check-config for details)\n" "Cppcheck cannot find all the include files. Cppcheck can check the code without the " "include files found. But the results will probably be more accurate if all the include " "files are found. Please check your project's include directories and add all of them " "as include directories for Cppcheck. To see what files Cppcheck cannot find use " "--check-config.", "missingInclude", false); reportInfo(msg); } } if (settings._xml) { reportErr(ErrorLogger::ErrorMessage::getXMLFooter(settings._xml_version)); } _settings = 0; if (returnValue) return settings._exitCode; else return 0; }
void VTKMeshFileImporter::execute() { if(mFilename == "") throw Exception("No filename given to the VTKMeshFileImporter"); // Try to open file and check that it exists std::ifstream file(mFilename.c_str()); std::string line; if(!file.is_open()) { throw FileNotFoundException(mFilename); } // Check file header? // Read vertices std::vector<Vector3f> vertices; if(!gotoLineWithString(file, "POINTS")) { throw Exception("Found no vertices in the VTK surface file"); } while(getline(file, line)) { boost::trim(line); if(line.size() == 0) break; if(!(isdigit(line[0]) || line[0] == '-')) { // Has reached end break; } std::vector<std::string> tokens; boost::split(tokens, line, boost::is_any_of(" ")); for(int i = 0; i < tokens.size(); i += 3) { Vector3f v; v(0) = boost::lexical_cast<float>(tokens[i]); v(1) = boost::lexical_cast<float>(tokens[i+1]); v(2) = boost::lexical_cast<float>(tokens[i+2]); vertices.push_back(v); } } file.seekg(0); // set stream to start // Read triangles (other types of polygons not supported yet) std::vector<Vector3ui> triangles; if(!gotoLineWithString(file, "POLYGONS")) { throw Exception("Found no triangles in the VTK surface file"); } while(getline(file, line)) { boost::trim(line); if(line.size() == 0) break; if(!isdigit(line[0])) { // Has reached end break; } std::vector<std::string> tokens; boost::split(tokens, line, boost::is_any_of(" ")); if(boost::lexical_cast<int>(tokens[0]) != 3) { throw Exception("The VTKMeshFileImporter currently only supports reading files with triangles. Encountered a non-triangle. Aborting."); } if(tokens.size() != 4) { throw Exception("Error while reading triangles in VTKMeshFileImporter. Check format."); } Vector3ui triangle; triangle(0) = boost::lexical_cast<uint>(tokens[1]); triangle(1) = boost::lexical_cast<uint>(tokens[2]); triangle(2) = boost::lexical_cast<uint>(tokens[3]); triangles.push_back(triangle); } file.seekg(0); // set stream to start // Read normals (if any) std::vector<Vector3f> normals; if(!gotoLineWithString(file, "NORMALS")) { // Create dummy normals for(uint i = 0; i < vertices.size(); i++) { Vector3f dummyNormal; normals.push_back(dummyNormal); } } else { while(getline(file, line)) { boost::trim(line); if(line.size() == 0) break; if(!(isdigit(line[0]) || line[0] == '-')) { // Has reached end break; } std::vector<std::string> tokens; boost::split(tokens, line, boost::is_any_of(" ")); for(int i = 0; i < tokens.size(); i += 3) { Vector3f v; v(0) = boost::lexical_cast<float>(tokens[i]); v(1) = boost::lexical_cast<float>(tokens[i+1]); v(2) = boost::lexical_cast<float>(tokens[i+2]); normals.push_back(v); } } if(normals.size() != vertices.size()) { std::string message = "Read different amount of vertices (" + boost::lexical_cast<std::string>(vertices.size()) + ") and normals (" + boost::lexical_cast<std::string>(normals.size()) + ")."; throw Exception(message); } } Mesh::pointer output = getOutputData<Mesh>(0); // Add data to output output->create(vertices, normals, triangles); reportInfo() << "MESH IMPORTED vertices " << vertices.size() << " normals " << normals.size() << " triangles " << triangles.size() << Reporter::end; }
void ManualImageStreamer::producerStream() { uint i = mStartNumber; int replays = 0; uint64_t previousTimestamp = 0; auto previousTimestampTime = std::chrono::high_resolution_clock::time_point::min(); int currentSequence = 0; while(true) { { std::unique_lock<std::mutex> lock(mStopMutex); if(mStop) { mStreamIsStarted = false; mFirstFrameIsInserted = false; mHasReachedEnd = false; break; } } try { Image::pointer image = mImages[currentSequence].at(i); addOutputData(0, image); if(image->getCreationTimestamp() != 0) { uint64_t timestamp = image->getCreationTimestamp(); // Wait as long as necessary before adding image // Time passed since last frame auto timePassed = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::high_resolution_clock::now() - previousTimestampTime); while (timestamp > previousTimestamp + timePassed.count()) { // Wait int64_t left = (timestamp - previousTimestamp) - timePassed.count(); reportInfo() << "Sleeping for " << left << " ms" << reportEnd(); std::this_thread::sleep_for(std::chrono::milliseconds(left)); timePassed = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::high_resolution_clock::now() - previousTimestampTime); } previousTimestamp = timestamp; previousTimestampTime = std::chrono::high_resolution_clock::now(); } if(mSleepTime > 0) std::this_thread::sleep_for(std::chrono::milliseconds(mSleepTime)); if(!mFirstFrameIsInserted) { { std::lock_guard<std::mutex> lock(mFirstFrameMutex); mFirstFrameIsInserted = true; } mFirstFrameCondition.notify_one(); } mNrOfFrames++; i += mStepSize; } catch(std::out_of_range &e) { if(i > 0) { reportInfo() << "Reached end of stream" << Reporter::end(); // If there where no files found at all, we need to release the execute method if(!mFirstFrameIsInserted) { { std::lock_guard<std::mutex> lock(mFirstFrameMutex); mFirstFrameIsInserted = true; } mFirstFrameCondition.notify_one(); } if(mLoop || (mNrOfReplays > 0 && replays != mNrOfReplays || (currentSequence < mImages.size()-1))) { // Restart stream previousTimestamp = 0; previousTimestampTime = std::chrono::high_resolution_clock::time_point::min(); replays++; i = mStartNumber; currentSequence++; // Go to first sequence if looping is enabled if(mLoop && currentSequence == mImages.size()) { currentSequence = 0; } continue; } mHasReachedEnd = true; // Reached end of stream break; } else { throw e; } } } }
void TensorFlowEngine::run() { if(mInputNodes.empty()) throw Exception("At least one output node has to be given to the NeuralNetwork before execution"); if(mOutputNodes.empty()) throw Exception("At least one output node has to be given to the NeuralNetwork before execution"); // For each input, create a tensorflow tensor: std::vector <std::pair<std::string, tensorflow::Tensor>> input_tensors; for(auto inputNode : mInputNodes) { const std::string name = inputNode.first; if(!inputNode.second.data) throw Exception("Input node " + name + " has not received any data"); auto shape = inputNode.second.data->getShape(); if(shape.getUnknownDimensions() > 0) throw Exception("Input shape must be fully known when executing NN"); // Construct tensorflow tensor tensorflow::TensorShape tensorShape; for(auto i : shape.getAll()) { tensorShape.AddDim(i); } tensorflow::Tensor input_tensor( tensorflow::DT_FLOAT, tensorShape ); // Give tensor data to tensorflow // TODO is the data here actually moved? TensorAccess::pointer access = inputNode.second.data->getAccess(ACCESS_READ); switch(shape.getDimensions()) { case 2: input_tensor.tensor<float, 2>() = std::move(access->getData<2>()); break; case 3: input_tensor.tensor<float, 3>() = std::move(access->getData<3>()); break; case 4: input_tensor.tensor<float, 4>() = std::move(access->getData<4>()); break; case 5: input_tensor.tensor<float, 5>() = std::move(access->getData<5>()); break; case 6: input_tensor.tensor<float, 6>() = std::move(access->getData<6>()); break; default: throw Exception("Invalid tensor dimension size"); } // Add tensorflow tensor to list of input tensors input_tensors.push_back(std::make_pair(name, input_tensor)); } for(std::string name : mLearningPhaseTensors) { // Create a scalar tensor which tells the system we are NOT doing training tensorflow::Tensor input_tensor2( tensorflow::DT_BOOL, tensorflow::TensorShape() // Scalar ); auto input_tensor_mapped2 = input_tensor2.tensor<bool, 0>(); input_tensor_mapped2(0) = false; input_tensors.push_back(std::make_pair(name, input_tensor2)); } std::vector<tensorflow::Tensor> output_tensors; reportInfo() << "Running network" << reportEnd(); tensorflow::Status s; //mRuntimeManager->startRegularTimer("network_execution"); std::vector<std::string> outputNames; for(auto node : mOutputNodes) outputNames.push_back(node.first); s = mSession->Run(input_tensors, outputNames, {}, &output_tensors); //mRuntimeManager->stopRegularTimer("network_execution"); if (!s.ok()) { throw Exception("Error during inference: " + s.ToString()); } reportInfo() << "Finished executing network" << reportEnd(); // Collect all output data as FAST tensors for(int j = 0; j < outputNames.size(); ++j) { const std::string outputName = outputNames[j]; const NetworkNode node = mOutputNodes[outputName]; auto tensor = TensorflowTensor::New(); tensor->create(std::move(output_tensors[j])); mOutputNodes[outputName].data = tensor; } reportInfo() << "Finished parsing output" << reportEnd(); }
void TensorFlowEngine::load() { const auto networkFilename = getFilename(); tensorflow::SessionOptions options; tensorflow::ConfigProto &config = options.config; tensorflow::GPUOptions* gpuOptions = config.mutable_gpu_options(); gpuOptions->set_allow_growth(true); // Set this so that tensorflow will not use up all GPU memory //gpuOptions->set_per_process_gpu_memory_fraction(0.5); mSession.reset(tensorflow::NewSession(options)); tensorflow::GraphDef tensorflow_graph; { reportInfo() << "Loading network file: " << networkFilename << reportEnd(); tensorflow::Status s = ReadBinaryProto(tensorflow::Env::Default(), networkFilename, &tensorflow_graph); if (!s.ok()) { throw Exception("Could not read TensorFlow graph file " + networkFilename); } } bool nodesSpecified = true; int inputCounter = 0; if(mInputNodes.size() == 0) { nodesSpecified = false; } for(int i = 0; i < tensorflow_graph.node_size(); ++i) { tensorflow::NodeDef node = tensorflow_graph.node(i); if(mInputNodes.count(node.name()) > 0) { } if(node.op() == "Placeholder") { if(node.name().find("keras_learning_phase") != std::string::npos) { //mLearningPhaseTensors.insert(node.name()); mLearningPhaseTensors.push_back(node.name()); } else { // Input node found: // Get its shape // Input nodes use the Op Placeholder reportInfo() << "Found input node: " << i << " with name " << node.name() << reportEnd(); auto shape = getShape(node); reportInfo() << "Node has shape " << shape.toString() << reportEnd(); if(mInputNodes.count(node.name()) == 0) { if(nodesSpecified) { throw Exception("Encountered unknown node " + node.name()); } reportInfo() << "Node was not specified by user" << reportEnd(); // If node has not been specified by user, we need to add it // and thus know its type (fast image or tensor) // It is assumed to be an image if input shape has at least 4 dimensions NodeType type = NodeType::TENSOR; if(shape.getKnownDimensions() >= 2) { reportInfo() << "Assuming node is an image" << reportEnd(); type = NodeType::IMAGE; } else { reportInfo() << "Assuming node is a tensor" << reportEnd(); } addInputNode(inputCounter, tensorflow_graph.node(0).name(), type, shape); ++inputCounter; } // Set its shape mInputNodes[node.name()].shape = shape; } } } reportInfo() << "Creating session." << reportEnd(); tensorflow::Status s = mSession->Create(tensorflow_graph); if (!s.ok()) { throw Exception("Could not create TensorFlow Graph"); } //tensorflow::graph::SetDefaultDevice("/gpu:0", &tensorflow_graph); // Clear the proto to save memory space. tensorflow_graph.Clear(); reportInfo() << "TensorFlow graph loaded from: " << networkFilename << reportEnd(); setIsLoaded(true); }
void IterativeClosestPoint::execute() { float error = std::numeric_limits<float>::max(), previousError; uint iterations = 0; // Get access to the two point sets PointSetAccess::pointer accessFixedSet = ((PointSet::pointer)getStaticInputData<PointSet>(0))->getAccess(ACCESS_READ); PointSetAccess::pointer accessMovingSet = ((PointSet::pointer)getStaticInputData<PointSet>(1))->getAccess(ACCESS_READ); // Get transformations of point sets AffineTransformation::pointer fixedPointTransform2 = SceneGraph::getAffineTransformationFromData(getStaticInputData<PointSet>(0)); Eigen::Affine3f fixedPointTransform; fixedPointTransform.matrix() = fixedPointTransform2->matrix(); AffineTransformation::pointer initialMovingTransform2 = SceneGraph::getAffineTransformationFromData(getStaticInputData<PointSet>(1)); Eigen::Affine3f initialMovingTransform; initialMovingTransform.matrix() = initialMovingTransform2->matrix(); // These matrices are Nx3 MatrixXf fixedPoints = accessFixedSet->getPointSetAsMatrix(); MatrixXf movingPoints = accessMovingSet->getPointSetAsMatrix(); Eigen::Affine3f currentTransformation = Eigen::Affine3f::Identity(); // Want to choose the smallest one as moving bool invertTransform = false; if(false && fixedPoints.cols() < movingPoints.cols()) { reportInfo() << "switching fixed and moving" << Reporter::end; // Switch fixed and moving MatrixXf temp = fixedPoints; fixedPoints = movingPoints; movingPoints = temp; invertTransform = true; // Apply initial transformations //currentTransformation = fixedPointTransform.getTransform(); movingPoints = fixedPointTransform*movingPoints.colwise().homogeneous(); fixedPoints = initialMovingTransform*fixedPoints.colwise().homogeneous(); } else { // Apply initial transformations //currentTransformation = initialMovingTransform.getTransform(); movingPoints = initialMovingTransform*movingPoints.colwise().homogeneous(); fixedPoints = fixedPointTransform*fixedPoints.colwise().homogeneous(); } do { previousError = error; MatrixXf movedPoints = currentTransformation*(movingPoints.colwise().homogeneous()); // Match closest points using current transformation MatrixXf rearrangedFixedPoints = rearrangeMatrixToClosestPoints( fixedPoints, movedPoints); // Get centroids Vector3f centroidFixed = getCentroid(rearrangedFixedPoints); //reportInfo() << "Centroid fixed: " << Reporter::end; //reportInfo() << centroidFixed << Reporter::end; Vector3f centroidMoving = getCentroid(movedPoints); //reportInfo() << "Centroid moving: " << Reporter::end; //reportInfo() << centroidMoving << Reporter::end; Eigen::Transform<float, 3, Eigen::Affine> updateTransform = Eigen::Transform<float, 3, Eigen::Affine>::Identity(); if(mTransformationType == IterativeClosestPoint::RIGID) { // Create correlation matrix H of the deviations from centroid MatrixXf H = (movedPoints.colwise() - centroidMoving)* (rearrangedFixedPoints.colwise() - centroidFixed).transpose(); // Do SVD on H Eigen::JacobiSVD<Eigen::MatrixXf> svd(H, Eigen::ComputeFullU | Eigen::ComputeFullV); // Estimate rotation as R=V*U.transpose() MatrixXf temp = svd.matrixV()*svd.matrixU().transpose(); Matrix3f d = Matrix3f::Identity(); d(2,2) = sign(temp.determinant()); Matrix3f R = svd.matrixV()*d*svd.matrixU().transpose(); // Estimate translation Vector3f T = centroidFixed - R*centroidMoving; updateTransform.linear() = R; updateTransform.translation() = T; } else { // Only translation Vector3f T = centroidFixed - centroidMoving; updateTransform.translation() = T; } // Update current transformation currentTransformation = updateTransform*currentTransformation; // Calculate RMS error MatrixXf distance = rearrangedFixedPoints - currentTransformation*(movingPoints.colwise().homogeneous()); error = 0; for(uint i = 0; i < distance.cols(); i++) { error += pow(distance.col(i).norm(),2); } error = sqrt(error / distance.cols()); iterations++; reportInfo() << "Error: " << error << Reporter::end; // To continue, change in error has to be above min error change and nr of iterations less than max iterations } while(previousError-error > mMinErrorChange && iterations < mMaxIterations); if(invertTransform){ currentTransformation = currentTransformation.inverse(); } mError = error; mTransformation->matrix() = currentTransformation.matrix(); }
void setupUi(QDialog *strangersbanquetGraphDialog) { if (strangersbanquetGraphDialog->objectName().isEmpty()) strangersbanquetGraphDialog->setObjectName(QString::fromUtf8("strangersbanquetGraphDialog")); strangersbanquetGraphDialog->setWindowModality(Qt::WindowModal); strangersbanquetGraphDialog->resize(424, 339); strangersbanquetGraphDialog->setMinimumSize(QSize(424, 339)); strangersbanquetGraphDialog->setMaximumSize(QSize(377, 249)); strangersbanquetGraphDialog->setLayoutDirection(Qt::LeftToRight); strangersbanquetGraphDialog->setModal(false); buttonBox = new QDialogButtonBox(strangersbanquetGraphDialog); buttonBox->setObjectName(QString::fromUtf8("buttonBox")); buttonBox->setGeometry(QRect(40, 290, 371, 32)); buttonBox->setOrientation(Qt::Horizontal); buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok); formLayoutWidget = new QWidget(strangersbanquetGraphDialog); formLayoutWidget->setObjectName(QString::fromUtf8("formLayoutWidget")); formLayoutWidget->setGeometry(QRect(39, 70, 351, 201)); formLayout = new QFormLayout(formLayoutWidget); formLayout->setObjectName(QString::fromUtf8("formLayout")); formLayout->setHorizontalSpacing(5); formLayout->setVerticalSpacing(23); formLayout->setContentsMargins(0, 0, 0, 0); label = new QLabel(formLayoutWidget); label->setObjectName(QString::fromUtf8("label")); formLayout->setWidget(0, QFormLayout::LabelRole, label); label_2 = new QLabel(formLayoutWidget); label_2->setObjectName(QString::fromUtf8("label_2")); formLayout->setWidget(2, QFormLayout::LabelRole, label_2); spinBox = new QSpinBox(formLayoutWidget); spinBox->setObjectName(QString::fromUtf8("spinBox")); spinBox->setMinimum(1); spinBox->setMaximum(1000); formLayout->setWidget(0, QFormLayout::FieldRole, spinBox); label_5 = new QLabel(formLayoutWidget); label_5->setObjectName(QString::fromUtf8("label_5")); formLayout->setWidget(1, QFormLayout::LabelRole, label_5); spinBox_2 = new QSpinBox(formLayoutWidget); spinBox_2->setObjectName(QString::fromUtf8("spinBox_2")); spinBox_2->setMinimum(1); spinBox_2->setMaximum(5); formLayout->setWidget(1, QFormLayout::FieldRole, spinBox_2); label_4 = new QLabel(formLayoutWidget); label_4->setObjectName(QString::fromUtf8("label_4")); formLayout->setWidget(3, QFormLayout::LabelRole, label_4); doubleSpinBox_2 = new QDoubleSpinBox(formLayoutWidget); doubleSpinBox_2->setObjectName(QString::fromUtf8("doubleSpinBox_2")); doubleSpinBox_2->setDecimals(3); doubleSpinBox_2->setMaximum(1); doubleSpinBox_2->setSingleStep(0.01); formLayout->setWidget(2, QFormLayout::FieldRole, doubleSpinBox_2); doubleSpinBox_3 = new QDoubleSpinBox(formLayoutWidget); doubleSpinBox_3->setObjectName(QString::fromUtf8("doubleSpinBox_3")); doubleSpinBox_3->setDecimals(3); doubleSpinBox_3->setMaximum(1); doubleSpinBox_3->setSingleStep(0.01); formLayout->setWidget(3, QFormLayout::FieldRole, doubleSpinBox_3); label_3 = new QLabel(strangersbanquetGraphDialog); label_3->setObjectName(QString::fromUtf8("label_3")); label_3->setGeometry(QRect(40, 30, 351, 18)); retranslateUi(strangersbanquetGraphDialog); retranslateUi(strangersbanquetGraphDialog); QObject::connect(buttonBox,SIGNAL(accepted()),this , SLOT(reportInfo())); QObject::connect(buttonBox, SIGNAL(accepted()), strangersbanquetGraphDialog, SLOT(accept())); QObject::connect(buttonBox, SIGNAL(rejected()), strangersbanquetGraphDialog, SLOT(reject())); QMetaObject::connectSlotsByName(strangersbanquetGraphDialog); } // setupUi
unsigned int CppCheck::processFile(const std::string& filename) { exitcode = 0; // only show debug warnings for accepted C/C++ source files if (!Path::acceptFile(filename)) _settings.debugwarnings = false; if (_settings.terminated()) return exitcode; if (_settings._errorsOnly == false) { std::string fixedpath = Path::simplifyPath(filename.c_str()); fixedpath = Path::toNativeSeparators(fixedpath); _errorLogger.reportOut(std::string("Checking ") + fixedpath + std::string("...")); } try { Preprocessor preprocessor(&_settings, this); std::list<std::string> configurations; std::string filedata = ""; if (!_fileContent.empty()) { // File content was given as a string std::istringstream iss(_fileContent); preprocessor.preprocess(iss, filedata, configurations, filename, _settings._includePaths); } else { // Only file name was given, read the content from file std::ifstream fin(filename.c_str()); Timer t("Preprocessor::preprocess", _settings._showtime, &S_timerResults); preprocessor.preprocess(fin, filedata, configurations, filename, _settings._includePaths); } if (_settings.checkConfiguration) { return 0; } if (!_settings.userDefines.empty()) { configurations.clear(); configurations.push_back(_settings.userDefines); } if (!_settings._force && configurations.size() > _settings._maxConfigs) { const std::string fixedpath = Path::toNativeSeparators(filename); ErrorLogger::ErrorMessage::FileLocation location; location.setfile(fixedpath); const std::list<ErrorLogger::ErrorMessage::FileLocation> loclist(1, location); std::ostringstream msg; msg << "Too many #ifdef configurations - cppcheck will only check " << _settings._maxConfigs << " of " << configurations.size() << ".\n" "The checking of the file will be interrupted because there are too many " "#ifdef configurations. Checking of all #ifdef configurations can be forced " "by --force command line option or from GUI preferences. However that may " "increase the checking time."; ErrorLogger::ErrorMessage errmsg(loclist, Severity::information, msg.str(), "toomanyconfigs", false); reportErr(errmsg); } unsigned int checkCount = 0; for (std::list<std::string>::const_iterator it = configurations.begin(); it != configurations.end(); ++it) { // Check only a few configurations (default 12), after that bail out, unless --force // was used. if (!_settings._force && checkCount >= _settings._maxConfigs) { const std::string fixedpath = Path::toNativeSeparators(filename); ErrorLogger::ErrorMessage::FileLocation location; location.setfile(fixedpath); std::list<ErrorLogger::ErrorMessage::FileLocation> loclist; loclist.push_back(location); ErrorLogger::ErrorMessage errmsg(loclist, Severity::information, "Interrupted checking because of too many #ifdef configurations.", "toomanyconfigs", false); reportInfo(errmsg); break; } cfg = *it; // If only errors are printed, print filename after the check if (_settings._errorsOnly == false && it != configurations.begin()) { std::string fixedpath = Path::simplifyPath(filename.c_str()); fixedpath = Path::toNativeSeparators(fixedpath); _errorLogger.reportOut(std::string("Checking ") + fixedpath + ": " + cfg + std::string("...")); } Timer t("Preprocessor::getcode", _settings._showtime, &S_timerResults); const std::string codeWithoutCfg = preprocessor.getcode(filedata, *it, filename, _settings.userDefines.empty()); t.Stop(); const std::string &appendCode = _settings.append(); if (_settings.debugFalsePositive) { if (findError(codeWithoutCfg + appendCode, filename.c_str())) { return exitcode; } } else { checkFile(codeWithoutCfg + appendCode, filename.c_str()); } ++checkCount; } } catch (const std::runtime_error &e) { // Exception was thrown when checking this file.. const std::string fixedpath = Path::toNativeSeparators(filename); _errorLogger.reportOut("Bailing out from checking " + fixedpath + ": " + e.what()); } if (!_settings._errorsOnly) reportUnmatchedSuppressions(_settings.nomsg.getUnmatchedLocalSuppressions(filename)); _errorList.clear(); return exitcode; }
// --------------------- void serialParse(void) { char charCh; byte hexRead, oldHexRead; charCh = getChar(); if (!charCh) return; if (sysStat & ST_DEBUG_MODE) // Super commands for Monitor { rs485TransmitEna(); putChar(charCh); switch(charCh) { case 'd': putStr("\tNode ID switch test.\n\r"); putStr("\tHit any key to quit.\n\r"); rs485TransmitDisa(); while(1) { charCh = getChar(); if (charCh) break; hexRead = readNodeSw(); if (hexRead != oldHexRead) { rs485TransmitEna(); sprintf(ioBfr, "\n\r Node ID: %02Xh", hexRead); putStr(ioBfr); oldHexRead = hexRead; rs485TransmitDisa(); } } break; case 'f': putStr("\tFlood sensor test: "); adcFloodSensor(ADC_LOQUACIOUS); break; case 'h': adcRHumid(ADC_LOQUACIOUS); break; case 'r': reportInfo(); break; case 't': adcTemper(ADC_LOQUACIOUS); break; case 'T': adcTemperSecondary(ADC_LOQUACIOUS); break; case '1': RELAY1 ^= 1; if (RELAY1) putStr("\tRelay 1 on"); else putStr("\tRelay 1 off"); break; case '2': RELAY2 ^= 1; if (RELAY2) putStr("\tRelay 2 on"); else putStr("\tRelay 2 off"); break; case '3': SwiPwr1 ^= 1; if (SwiPwr1) putStr("\tSwi Pwr1 on"); else putStr("\tSwi Pwr1 off"); break; case '4': SwiPwr2 ^= 1; if (SwiPwr2) putStr("\tSwi Pwr2 on"); else putStr("\tSwi Pwr2 off"); break; case '?': menuDisplay(); break; } // EO switch putPrompt(); rs485TransmitDisa(); } // EO if debug else { childStateMach(charCh); } }