示例#1
0
/*! Realiza a busca de manpages que contém as duas
 * 	chaves secundárias definidas pelo usuário
 */
void searchByTwoWords() {
	printf("\nInforme a primeira palavra a ser procurada:\n");
	char word[100];
	for(int i=0; i<commandSize; i++) {
		 word[i] = ' ';
	}
	scanf("%s", word);

	FileNoAVL *avlNode = new FileNoAVL(0, word, fopen("invertedIndex.dat", "r+"));
	int wordAddress = avlNode->search(avlNode->getNode());
	delete avlNode;
	if (wordAddress == -1) {
		printf("Palavra inexistente\n");
		return;
	}

	printf("\nInforme a segunda palavra a ser procurada:\n");
	char word2[100];
	for(int i=0; i<commandSize; i++) {
		 word2[i] = ' ';
	}
	scanf("%s", word2);

	FileNoAVL *avlNode2 = new FileNoAVL(0, word2, fopen("invertedIndex.dat", "r+"));
	int wordAddress2 = avlNode2->search(avlNode2->getNode());
	delete avlNode2;
	if (wordAddress == -1) {
		printf("Palavra inexistente\n");
		return;
	}

	Word wordTmp;
	FILE* invertedDat = fopen("inverted.dat", "r");
	fseek(invertedDat, wordAddress, SEEK_SET);
	fread(&wordTmp, sizeof(Word), 1, invertedDat);

	Word wordTmp2;
	fseek(invertedDat, wordAddress2, SEEK_SET);
	fread(&wordTmp2, sizeof(Word), 1, invertedDat);
	fclose(invertedDat);


	std::vector<int> wordOccurrences = std::vector<int>();
	for(int i = 0; i <= wordTmp.occurrenceIndex; i++)
		wordOccurrences.push_back(wordTmp.occurrences[i]);
	sort(wordOccurrences.begin(), wordOccurrences.end());

	std::vector<int> wordOccurrences2 = std::vector<int>();
	for(int i = 0; i <= wordTmp2.occurrenceIndex; i++)
		wordOccurrences2.push_back(wordTmp2.occurrences[i]);
	sort(wordOccurrences2.begin(), wordOccurrences2.end());

	std::vector<int> intersection;
	set_intersection(wordOccurrences.begin(), wordOccurrences.end(),
					 wordOccurrences2.begin(), wordOccurrences2.end(),
					 back_inserter(intersection));

	if(intersection.size() == 0) {
		printf("\nNão existe a ocorrência destas duas palavras em um única manpage\n");
		return;
	}

	FILE* manPageDat = fopen("manpage.dat", "r");
	for(int i = 0; i < (int)intersection.size(); i++) {
		ManPage manPage;
		fseek(manPageDat, intersection[i], SEEK_SET);
		fread(&manPage, sizeof(ManPage), 1, manPageDat);
		printf("%s\n", manPage.command);
	}
	fclose(manPageDat);
}
示例#2
0
int main(int argc, char* argv[]) {

  gErrorIgnoreLevel = kError;

  // Add options here

  boost::program_options::options_description desc("Allowed options");
  desc.add_options()
    ("help,h", "print help message")
    ("file,f", boost::program_options::value<std::vector<std::string> >(), "data file (-f or -F required)")
    ("Files,F", boost::program_options::value<std::string>(), "text file containing names of data files, one per line")
    ("catalog,c", boost::program_options::value<std::string>(), "catalog")
    ("decodeLFN,d", "Convert LFN to PFN")
    ("uuid,u", "Print uuid")
    ("adler32,a", "Print adler32 checksum.")
    ("allowRecovery", "Allow root to auto-recover corrupted files")
    ("JSON,j", "JSON output format.  Any arguments listed below are ignored")
    ("ls,l", "list file content")
    ("print,P", "Print all")
    ("verbose,v", "Verbose printout")
    ("printBranchDetails,b", "Call Print()sc for all branches")
    ("tree,t", boost::program_options::value<std::string>(), "Select tree used with -P and -b options")
    ("events,e", "Print list of all Events, Runs, and LuminosityBlocks in the file sorted by run number, luminosity block number, and event number.  Also prints the entry numbers and whether it is possible to use fast copy with the file.")
    ("eventsInLumis","Print how many Events are in each LuminosityBlock.");

  // What trees do we require for this to be a valid collection?
  std::vector<std::string> expectedTrees;
  expectedTrees.push_back(edm::poolNames::metaDataTreeName());
  expectedTrees.push_back(edm::poolNames::eventTreeName());

  boost::program_options::positional_options_description p;
  p.add("file", -1);

  boost::program_options::variables_map vm;


  try {
      boost::program_options::store(boost::program_options::command_line_parser(argc, argv).
                                    options(desc).positional(p).run(), vm);
  } catch (boost::program_options::error const& x) {
      std::cerr << "Option parsing failure:\n"
                << x.what() << "\n\n";
      std::cerr << desc << "\n";
      return 1;
  }

  boost::program_options::notify(vm);

  if (vm.count("help")) {
    std::cout << desc << "\n";
    return 1;
  }

  int rc = 0;
  try {
    std::unique_ptr<edm::SiteLocalConfig> slcptr = std::make_unique<edm::service::SiteLocalConfigService>(edm::ParameterSet());
    auto slc = std::make_shared<edm::serviceregistry::ServiceWrapper<edm::SiteLocalConfig> >(std::move(slcptr));
    edm::ServiceToken slcToken = edm::ServiceRegistry::createContaining(slc);
    edm::ServiceRegistry::Operate operate(slcToken);

    std::vector<std::string> in = (vm.count("file") ? vm["file"].as<std::vector<std::string> >() : std::vector<std::string>());
    if (vm.count("Files")) {
      std::ifstream ifile(vm["Files"].as<std::string>().c_str());
      std::istream_iterator<std::string> beginItr(ifile);
      if (ifile.fail()) {
        std::cout << "File '" << vm["Files"].as<std::string>() << "' not found, not opened, or empty\n";
        return 1;
      }
      std::istream_iterator<std::string> endItr;
      copy(beginItr, endItr, back_inserter(in));
    }
    if (in.empty()) {
      std::cout << "Data file(s) not set.\n";
      std::cout << desc << "\n";
      return 1;
    }
    std::string catalogIn = (vm.count("catalog") ? vm["catalog"].as<std::string>() : std::string());
    bool decodeLFN = vm.count("decodeLFN");
    bool uuid = vm.count("uuid");
    bool adler32 = vm.count("adler32");
    bool allowRecovery = vm.count("allowRecovery");
    bool json = vm.count("JSON");
    bool more = !json;
    bool verbose = more && (vm.count("verbose") > 0 ? true : false);
    bool events = more && (vm.count("events") > 0 ? true : false);
    bool eventsInLumis = more && (vm.count("eventsInLumis") > 0 ? true : false);
    bool ls = more && (vm.count("ls") > 0 ? true : false);
    bool tree = more && (vm.count("tree") > 0 ? true : false);
    bool print = more && (vm.count("print") > 0 ? true : false);
    bool printBranchDetails = more && (vm.count("printBranchDetails") > 0 ? true : false);
    bool onlyDecodeLFN = decodeLFN && !(uuid || adler32 || allowRecovery || json || events || tree || ls || print || printBranchDetails);
    std::string selectedTree = tree ? vm["tree"].as<std::string>() : edm::poolNames::eventTreeName().c_str();

    if (events||eventsInLumis) {
      try {
        edmplugin::PluginManager::configure(edmplugin::standard::config());
      } catch(std::exception& e) {
        std::cout << "exception caught in EdmFileUtil while configuring the PluginManager\n" << e.what();
        return 1;
      }
    }

    edm::InputFileCatalog catalog(in, catalogIn, true);
    std::vector<std::string> const& filesIn = catalog.fileNames();

    if (json) {
      std::cout << '[' << std::endl;
    }

    // now run..
    // Allow user to input multiple files
    for(unsigned int j = 0; j < in.size(); ++j) {

      // We _only_ want the LFN->PFN conversion. No need to open the file,
      // just check the catalog and move on
      if (onlyDecodeLFN) {
        std::cout << filesIn[j] << std::endl;
        continue;
      }

      // open a data file
      if (!json) std::cout << in[j] << "\n";
      std::string const& lfn = in[j];
      std::unique_ptr<TFile> tfile{edm::openFileHdl(filesIn[j])};
      if (tfile == nullptr) return 1;

      std::string const& pfn = filesIn[j];

      if (verbose) std::cout << "ECU:: Opened " << pfn << std::endl;

      std::string datafile = decodeLFN ? pfn : lfn;

      // First check that this file is not auto-recovered
      // Stop the job unless specified to do otherwise

      bool isRecovered = tfile->TestBit(TFile::kRecovered);
      if (isRecovered) {
        if (allowRecovery) {
          if (!json) {
            std::cout << pfn << " appears not to have been closed correctly and has been autorecovered \n";
            std::cout << "Proceeding anyway\n";
          }
        } else {
          std::cout << pfn << " appears not to have been closed correctly and has been autorecovered \n";
          std::cout << "Stopping. Use --allowRecovery to try ignoring this\n";
          return 1;
        }
      } else {
        if (verbose) std::cout << "ECU:: Collection not autorecovered. Continuing\n";
      }

      // Ok. Do we have the expected trees?
      for (unsigned int i = 0; i < expectedTrees.size(); ++i) {
        TTree *t = (TTree*) tfile->Get(expectedTrees[i].c_str());
        if (t == 0) {
          std::cout << "Tree " << expectedTrees[i] << " appears to be missing. Not a valid collection\n";
          std::cout << "Exiting\n";
          return 1;
        } else {
          if (verbose) std::cout << "ECU:: Found Tree " << expectedTrees[i] << std::endl;
        }
      }

      if (verbose) std::cout << "ECU:: Found all expected trees\n";

      std::ostringstream auout;
      if (adler32) {
        unsigned int const EDMFILEUTILADLERBUFSIZE = 10*1024*1024; // 10MB buffer
        static char buffer[EDMFILEUTILADLERBUFSIZE];
        size_t bufToRead = EDMFILEUTILADLERBUFSIZE;
        uint32_t a = 1, b = 0;
        size_t fileSize = tfile->GetSize();
        tfile->Seek(0, TFile::kBeg);

        for (size_t offset = 0; offset < fileSize;
              offset += EDMFILEUTILADLERBUFSIZE) {
            // true on last loop
            if (fileSize - offset < EDMFILEUTILADLERBUFSIZE)
              bufToRead = fileSize - offset;
            tfile->ReadBuffer((char*)buffer, bufToRead);
            cms::Adler32(buffer, bufToRead, a, b);
        }
        uint32_t adler32sum = (b << 16) | a;
        if (json) {
          auout << ",\"adler32sum\":" << adler32sum;
        } else {
          auout << ", " << std::hex << adler32sum << " adler32sum";
        }
      }

      if (uuid) {
        TTree *paramsTree = (TTree*)tfile->Get(edm::poolNames::metaDataTreeName().c_str());
        if (json) {
          auout << ",\"uuid\":\"" << edm::getUuid(paramsTree) << '"';
        } else {
          auout << ", " << edm::getUuid(paramsTree) << " uuid";
        }
      }

      // Ok. How many events?
      int nruns = edm::numEntries(tfile.get(), edm::poolNames::runTreeName());
      int nlumis = edm::numEntries(tfile.get(), edm::poolNames::luminosityBlockTreeName());
      int nevents = edm::numEntries(tfile.get(), edm::poolNames::eventTreeName());
      if (json) {
        if (j > 0) std::cout << ',' << std::endl;
        std::cout << "{\"file\":\"" << datafile << '"'
                  << ",\"runs\":" << nruns
                  << ",\"lumis\":" << nlumis
                  << ",\"events\":" << nevents
                  << ",\"bytes\":" << tfile->GetSize()
                  << auout.str()
                  << '}' << std::endl;
      } else {
        std::cout << datafile << " ("
                  << nruns << " runs, "
                  << nlumis << " lumis, "
                  << nevents << " events, "
                  << tfile->GetSize() << " bytes"
                  << auout.str()
                  << ")" << std::endl;
      }

      if (json) {
        // Remainder of arguments not supported in JSON yet.
        continue;
      }

      // Look at the collection contents
      if (ls) {
        if (tfile != nullptr) tfile->ls();
      }

      // Print out each tree
      if (print) {
        TTree *printTree = (TTree*)tfile->Get(selectedTree.c_str());
        if (printTree == 0) {
          std::cout << "Tree " << selectedTree << " appears to be missing. Could not find it in the file.\n";
          std::cout << "Exiting\n";
          return 1;
        }
        edm::printBranchNames(printTree);
      }

      if (printBranchDetails) {
        TTree *printTree = (TTree*)tfile->Get(selectedTree.c_str());
        if (printTree == 0) {
          std::cout << "Tree " << selectedTree << " appears to be missing. Could not find it in the file.\n";
          std::cout << "Exiting\n";
          return 1;
        }
        edm::longBranchPrint(printTree);
      }

      // Print out event lists
      if (events) {
        edm::printEventLists(tfile.get());
      }

      if(eventsInLumis) {
        edm::printEventsInLumis(tfile.get());
      }
      
      tfile->Close();
    }
    if (json) {
      std::cout << ']' << std::endl;
    }
  }
  catch (cms::Exception const& e) {
    std::cout << "cms::Exception caught in "
              <<"EdmFileUtil"
              << '\n'
              << e.explainSelf();
    rc = 1;
  }
  catch (std::exception const& e) {
    std::cout << "Standard library exception caught in "
              << "EdmFileUtil"
              << '\n'
              << e.what();
    rc = 1;
  }
  catch (...) {
    std::cout << "Unknown exception caught in "
              << "EdmFileUtil";
    rc = 2;
  }
  return rc;
}
示例#3
0
  /**
   * Initialize the Sphere's vertices.
   * @param radius The radius of the Sphere.
   * @param pProgram The currently installed shader program.
   * @param pMatrixStack The World's MatrixStack.
   * @name The name of the Sphere.
   * @param numTriangleStrips The number of horizontal triangle strips.  This
   * number should be even.  If odd, it is rounded down.  The number should
   * also be greater than 3.  If not, it will be set to 4.
   * @param colors Two colors for stripes (see WorldObject).
   */
  Sphere::Sphere(float radius, Program* pProgram, MatrixStack* pMatrixStack,
    const string& name, unsigned numTriangleStrips, vector<vec4> colors) : 
    WorldObject(name, pProgram, pMatrixStack)
  {
    vector<vec3> vertBuf;
    vector<vec4> colorBuf;
    vector<vec4> colorToggle;

    // Basic initialization.
    this->radius = radius;

    if (numTriangleStrips % 2 == 1)
      this->numTriangleStrips = numTriangleStrips - 1;
    else
      this->numTriangleStrips = numTriangleStrips;

    if (numTriangleStrips < 4)
      this->numTriangleStrips = 4;

    // Make sure there are two colors for striping.
    this->setColors(colors, 2);
    colorToggle.reserve(2);
    colorToggle.push_back(colors.at(0));
    colorToggle.push_back(colors.at(1));

    // Create a quarter dome.
    buildQuarterDome(vertBuf, colorBuf);
    this->colors.clear();

    /*
     * Build the sphere out of 8 quarter domes.  The first 4 quarter domes are
     * rotated about the Y axis.  The second 4 are rotated about the Z axis
     * and the Y axis.
     */

    // Reserve space for the vertices and colors.
    this->vertices.reserve(vertBuf.size()  * 8);
    this->colors.reserve(colorBuf.size()   * 8);

    for (int dome = 0; dome < 2; ++dome)
    {
      vec3 zAxis(0.0f, 0.0f, 1.0f);
      mat4 rotationZ = rotate(mat4(1.0f), pi<float>() * dome, zAxis);

      for (int i = 0; i < 4; ++i)
      {
        vec3 yAxis(0.0f, 1.0f,   0.0f);
        mat4 rotationY = rotate(mat4(1.0f), half_pi<float>() * i, yAxis);

        for (vector<vec3>::iterator it = vertBuf.begin(); it != vertBuf.end(); ++it)
          this->vertices.push_back(vec3(rotationZ * rotationY * vec4(*it, 1.0f)));
      }
    }

    // Duplicate the colors.  The first 4 quarter domes have identical colors.
    for (int i = 0; i < 4; ++i)
      copy(colorBuf.begin(), colorBuf.end(), back_inserter(this->colors));

    // The bottom 4 quarter domes have inverse colors (otherwise the color at
    // the equator would be repeated).
    transform(this->colors.begin(),
      this->colors.end(),
      back_inserter(this->colors),
      Inverter<vec4>(colorToggle.at(0), colorToggle.at(1)));

    // Compute the normals for each vertex.
    this->computeVertexNormals();

    // Set up and fill the vertex buffer, color buffer, and normal buffer.
    this->getProgram()->createAndFillBuffer(this->vertices,
      this->getProgram()->getVertexPositionAttr(), this->getVAO());
    this->getProgram()->createAndFillBuffer(this->vertexNormals,
      this->getProgram()->getVertexNormalAttr(), this->getVAO());
    this->getProgram()->createAndFillBuffer(this->colors,
      this->getProgram()->getVertexColorAttr(), this->getVAO());
  }
示例#4
0
文件: calib.cpp 项目: mvernacc/RT
void StereoCalib(const vector<string>& imagelist, Size boardSize, bool useCalibrated=true, bool showRectified=true)
{
    if( imagelist.size() % 2 != 0 )
    {
        cout << "Error: the image list contains odd (non-even) number of elements\n";
        return;
    }
    printf("board size: %d x %d", boardSize.width, boardSize.height);
    bool displayCorners = true;
    const int maxScale = 2;
    const float squareSize = 1.f;  // Set this to your actual square size
    // ARRAY AND VECTOR STORAGE:

    vector<vector<Point2f> > imagePoints[2];
    vector<vector<Point3f> > objectPoints;
    Size imageSize;

    int i, j, k, nimages = (int)imagelist.size()/2;

    imagePoints[0].resize(nimages);
    imagePoints[1].resize(nimages);
    vector<string> goodImageList;

    for( i = j = 0; i < nimages; i++ )
    {
        for( k = 0; k < 2; k++ )
        {
            const string& filename = imagelist[i*2+k];
            Mat img = imread(filename, 0);
            if(img.empty())
                break;
            if( imageSize == Size() )
                imageSize = img.size();
            else if( img.size() != imageSize )
            {
                cout << "The image " << filename << " has the size different from the first image size. Skipping the pair\n";
                break;
            }
            bool found = false;
            vector<Point2f>& corners = imagePoints[k][j];
            for( int scale = 1; scale <= maxScale; scale++ )
            {
                Mat timg;
                if( scale == 1 )
                    timg = img;
                else
                    resize(img, timg, Size(), scale, scale);
                found = findChessboardCorners(timg, boardSize, corners,
                    CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_NORMALIZE_IMAGE);
                if( found )
                {
                    if( scale > 1 )
                    {
                        Mat cornersMat(corners);
                        cornersMat *= 1./scale;
                    }
                    break;
                }
            }
            if( displayCorners )
            {
                cout << filename << endl;
                Mat cimg, cimg1;
                cvtColor(img, cimg, CV_GRAY2BGR);
                drawChessboardCorners(cimg, boardSize, corners, found);
                double sf = 640./MAX(img.rows, img.cols);
                resize(cimg, cimg1, Size(), sf, sf);
                imshow("corners", cimg1);
                char c = (char)waitKey(500);
                if( c == 27 || c == 'q' || c == 'Q' ) //Allow ESC to quit
                    exit(-1);
            }
            else
                putchar('.');
            if( !found )
                break;
            cornerSubPix(img, corners, Size(11,11), Size(-1,-1),
                         TermCriteria(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS,
                                      30, 0.01));
        }
        if( k == 2 )
        {
            goodImageList.push_back(imagelist[i*2]);
            goodImageList.push_back(imagelist[i*2+1]);
            j++;
        }
    }
    cout << j << " pairs have been successfully detected.\n";
    nimages = j;
    if( nimages < 2 )
    {
        cout << "Error: too little pairs to run the calibration\n";
        return;
    }

    imagePoints[0].resize(nimages);
    imagePoints[1].resize(nimages);
    objectPoints.resize(nimages);

    for( i = 0; i < nimages; i++ )
    {
        for( j = 0; j < boardSize.height; j++ )
            for( k = 0; k < boardSize.width; k++ )
                objectPoints[i].push_back(Point3f(j*squareSize, k*squareSize, 0));
    }

    cout << "Running stereo calibration ...\n";

    Mat cameraMatrix[2], distCoeffs[2];
    cameraMatrix[0] = Mat::eye(3, 3, CV_64F);
    cameraMatrix[1] = Mat::eye(3, 3, CV_64F);
    Mat R, T, E, F;

    double rms = stereoCalibrate(objectPoints, imagePoints[0], imagePoints[1],
                    cameraMatrix[0], distCoeffs[0],
                    cameraMatrix[1], distCoeffs[1],
                    imageSize, R, T, E, F,
                    TermCriteria(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 100, 1e-5),
                    CV_CALIB_FIX_ASPECT_RATIO +
                    CV_CALIB_ZERO_TANGENT_DIST +
                    //CV_CALIB_SAME_FOCAL_LENGTH +
                    CV_CALIB_RATIONAL_MODEL +
                    CV_CALIB_FIX_K3 + CV_CALIB_FIX_K4 + CV_CALIB_FIX_K5);
    cout << "done with RMS error=" << rms << endl;

// CALIBRATION QUALITY CHECK
// because the output fundamental matrix implicitly
// includes all the output information,
// we can check the quality of calibration using the
// epipolar geometry constraint: m2^t*F*m1=0
    double err = 0;
    int npoints = 0;
    vector<Vec3f> lines[2];
    for( i = 0; i < nimages; i++ )
    {
        int npt = (int)imagePoints[0][i].size();
        Mat imgpt[2];
        for( k = 0; k < 2; k++ )
        {
            imgpt[k] = Mat(imagePoints[k][i]);
            undistortPoints(imgpt[k], imgpt[k], cameraMatrix[k], distCoeffs[k], Mat(), cameraMatrix[k]);
            computeCorrespondEpilines(imgpt[k], k+1, F, lines[k]);
        }
        for( j = 0; j < npt; j++ )
        {
            double errij = fabs(imagePoints[0][i][j].x*lines[1][j][0] +
                                imagePoints[0][i][j].y*lines[1][j][1] + lines[1][j][2]) +
                           fabs(imagePoints[1][i][j].x*lines[0][j][0] +
                                imagePoints[1][i][j].y*lines[0][j][1] + lines[0][j][2]);
            err += errij;
        }
        npoints += npt;
    }
    cout << "average reprojection err = " <<  err/npoints << endl;

    // save intrinsic parameters
    FileStorage fs("calib/intrinsics.yml", CV_STORAGE_WRITE);
    if( fs.isOpened() )
    {
        fs << "M1" << cameraMatrix[0] << "D1" << distCoeffs[0] <<
            "M2" << cameraMatrix[1] << "D2" << distCoeffs[1];
        fs.release();
    }
    else
        cout << "Error: can not save the intrinsic parameters\n";

    Mat R1, R2, P1, P2, Q;
    Rect validRoi[2];

    stereoRectify(cameraMatrix[0], distCoeffs[0],
                  cameraMatrix[1], distCoeffs[1],
                  imageSize, R, T, R1, R2, P1, P2, Q,
                  CALIB_ZERO_DISPARITY, 1, imageSize, &validRoi[0], &validRoi[1]);

    fs.open("calib/extrinsics.yml", CV_STORAGE_WRITE);
    if( fs.isOpened() )
    {
        fs << "R" << R << "T" << T << "R1" << R1 << "R2" << R2 << "P1" << P1 << "P2" << P2 << "Q" << Q;
        fs.release();
    }
    else
        cout << "Error: can not save the intrinsic parameters\n";

    // OpenCV can handle left-right
    // or up-down camera arrangements
    bool isVerticalStereo = fabs(P2.at<double>(1, 3)) > fabs(P2.at<double>(0, 3));

// COMPUTE AND DISPLAY RECTIFICATION
    if( !showRectified )
        return;

    Mat rmap[2][2];
// IF BY CALIBRATED (BOUGUET'S METHOD)
    if( useCalibrated )
    {
        // we already computed everything
    }
// OR ELSE HARTLEY'S METHOD
    else
 // use intrinsic parameters of each camera, but
 // compute the rectification transformation directly
 // from the fundamental matrix
    {
        vector<Point2f> allimgpt[2];
        for( k = 0; k < 2; k++ )
        {
            for( i = 0; i < nimages; i++ )
                std::copy(imagePoints[k][i].begin(), imagePoints[k][i].end(), back_inserter(allimgpt[k]));
        }
        F = findFundamentalMat(Mat(allimgpt[0]), Mat(allimgpt[1]), FM_8POINT, 0, 0);
        Mat H1, H2;
        stereoRectifyUncalibrated(Mat(allimgpt[0]), Mat(allimgpt[1]), F, imageSize, H1, H2, 3);

        R1 = cameraMatrix[0].inv()*H1*cameraMatrix[0];
        R2 = cameraMatrix[1].inv()*H2*cameraMatrix[1];
        P1 = cameraMatrix[0];
        P2 = cameraMatrix[1];
    }

    //Precompute maps for cv::remap()
    initUndistortRectifyMap(cameraMatrix[0], distCoeffs[0], R1, P1, imageSize, CV_16SC2, rmap[0][0], rmap[0][1]);
    initUndistortRectifyMap(cameraMatrix[1], distCoeffs[1], R2, P2, imageSize, CV_16SC2, rmap[1][0], rmap[1][1]);

    Mat canvas;
    double sf;
    int w, h;
    if( !isVerticalStereo )
    {
        sf = 600./MAX(imageSize.width, imageSize.height);
        w = cvRound(imageSize.width*sf);
        h = cvRound(imageSize.height*sf);
        canvas.create(h, w*2, CV_8UC3);
    }
    else
    {
        sf = 300./MAX(imageSize.width, imageSize.height);
        w = cvRound(imageSize.width*sf);
        h = cvRound(imageSize.height*sf);
        canvas.create(h*2, w, CV_8UC3);
    }

    for( i = 0; i < nimages; i++ )
    {
        for( k = 0; k < 2; k++ )
        {
            Mat img = imread(goodImageList[i*2+k], 0), rimg, cimg;
            remap(img, rimg, rmap[k][0], rmap[k][1], CV_INTER_LINEAR);
            cvtColor(rimg, cimg, CV_GRAY2BGR);
            Mat canvasPart = !isVerticalStereo ? canvas(Rect(w*k, 0, w, h)) : canvas(Rect(0, h*k, w, h));
            resize(cimg, canvasPart, canvasPart.size(), 0, 0, CV_INTER_AREA);
            if( useCalibrated )
            {
                Rect vroi(cvRound(validRoi[k].x*sf), cvRound(validRoi[k].y*sf),
                          cvRound(validRoi[k].width*sf), cvRound(validRoi[k].height*sf));
                rectangle(canvasPart, vroi, Scalar(0,0,255), 3, 8);
            }
        }

        if( !isVerticalStereo )
            for( j = 0; j < canvas.rows; j += 16 )
                line(canvas, Point(0, j), Point(canvas.cols, j), Scalar(0, 255, 0), 1, 8);
        else
            for( j = 0; j < canvas.cols; j += 16 )
                line(canvas, Point(j, 0), Point(j, canvas.rows), Scalar(0, 255, 0), 1, 8);
        imshow("rectified", canvas);
        char c = (char)waitKey();
        if( c == 27 || c == 'q' || c == 'Q' )
            break;
    }
}
int main(int argc, const char * argv[]) {

	if (argc < 2) {
		cout << "Usage: " << argv[0] << " assembly_file_name.asm" << endl;
		return 0;
	}
    
	SourceReader sourceReader(argv[1]);
	sourceReader.findLabelAddresses();
	sourceReader.constructInstructionList();

	vector<Instruction> originalInstructionList = sourceReader.getInstructionList();
    vector<SimulatedInstruction> simulatedInstructionList = vector<SimulatedInstruction>();

	cout << "-------------Start Simulation-------------" << endl;
	cout << "Original number of instructions : " << originalInstructionList.size() << endl;
    cout << string(OUTPUT_WIDTH, '-') << endl;


    for (Instruction instruction: originalInstructionList) {
		simulatedInstructionList.push_back(SimulatedInstruction(instruction));
	}

    // Inserts an end instruction followed by 3 'NOPs' to terminate the instruction list
    // An end NOP instruction is used to indicate the end of the instruction list
    
    SimulatedInstruction end = SimulatedInstruction();
    end.originalString = "end";
    end.opcodeString = "end";
	simulatedInstructionList.push_back(end);
    fill_n(back_inserter(simulatedInstructionList), 3, SimulatedInstruction());

	for (int i = 0; i < simulatedInstructionList.size(); i++) {
		simulatedInstructionList[i].instructionLocation = i;
	}

	Simulator simulator(simulatedInstructionList);
    
    cout << "Press enter to run the entire simulation without pauses" << endl;
    cout << "Or press space to step through the simulation" << endl;
    
    BufferToggle bt;
    
    while (simulator.memoryStage.currentInstructionList.front().originalString != "end") {
        
        bt.off();
        char input = getchar();
        bt.on();

        if (input == ' ') {
            cout << endl;
            simulator.stepProcess();
        } else if (input == '\n' || input == '\r') {
            simulator.process();
        }
    }
    
    
    simulator.printFinalOutput();
    
	return 0;
}
示例#6
0
void BackendRenderer::AcceptMessage(ref_ptr<Message> message)
{
  switch (message->GetType())
  {
  case Message::UpdateReadManager:
    {
      TTilesCollection tiles = m_requestedTiles->GetTiles();
      if (!tiles.empty())
      {
        ScreenBase const screen = m_requestedTiles->GetScreen();
        bool const have3dBuildings = m_requestedTiles->Have3dBuildings();
        m_readManager->UpdateCoverage(screen, have3dBuildings, tiles, m_texMng);
        m_updateCurrentCountryFn(screen.ClipRect().Center(), (*tiles.begin()).m_zoomLevel);
      }
      break;
    }

  case Message::InvalidateReadManagerRect:
    {
      ref_ptr<InvalidateReadManagerRectMessage> msg = message;
      if (msg->NeedInvalidateAll())
        m_readManager->InvalidateAll();
      else
        m_readManager->Invalidate(msg->GetTilesForInvalidate());
      break;
    }

  case Message::ShowChoosePositionMark:
    {
      RecacheChoosePositionMark();
      break;
    }

  case Message::GuiRecache:
    {
      ref_ptr<GuiRecacheMessage> msg = message;
      RecacheGui(msg->GetInitInfo(), msg->NeedResetOldGui());

#ifdef RENRER_DEBUG_INFO_LABELS
      RecacheDebugLabels();
#endif
      break;
    }

  case Message::GuiLayerLayout:
    {
      ref_ptr<GuiLayerLayoutMessage> msg = message;
      m_commutator->PostMessage(ThreadsCommutator::RenderThread,
                                make_unique_dp<GuiLayerLayoutMessage>(msg->AcceptLayoutInfo()),
                                MessagePriority::Normal);
      break;
    }

  case Message::TileReadStarted:
    {
      ref_ptr<TileReadStartMessage> msg = message;
      m_batchersPool->ReserveBatcher(msg->GetKey());
      break;
    }

  case Message::TileReadEnded:
    {
      ref_ptr<TileReadEndMessage> msg = message;
      m_batchersPool->ReleaseBatcher(msg->GetKey());
      break;
    }

  case Message::FinishTileRead:
    {
      ref_ptr<FinishTileReadMessage> msg = message;
      m_commutator->PostMessage(ThreadsCommutator::RenderThread,
                                make_unique_dp<FinishTileReadMessage>(msg->MoveTiles()),
                                MessagePriority::Normal);
      break;
    }

  case Message::FinishReading:
    {
      TOverlaysRenderData overlays;
      overlays.swap(m_overlays);
      if (!overlays.empty())
      {
        m_commutator->PostMessage(ThreadsCommutator::RenderThread,
                                  make_unique_dp<FlushOverlaysMessage>(move(overlays)),
                                  MessagePriority::Normal);
      }
      break;
    }

  case Message::MapShapesRecache:
    {
      RecacheMapShapes();
      break;
    }

  case Message::MapShapeReaded:
    {
      ref_ptr<MapShapeReadedMessage> msg = message;
      auto const & tileKey = msg->GetKey();
      if (m_requestedTiles->CheckTileKey(tileKey) && m_readManager->CheckTileKey(tileKey))
      {
        ref_ptr<dp::Batcher> batcher = m_batchersPool->GetTileBatcher(tileKey);
        for (drape_ptr<MapShape> const & shape : msg->GetShapes())
        {
          batcher->SetFeatureMinZoom(shape->GetFeatureMinZoom());
          shape->Draw(batcher, m_texMng);
        }
      }
      break;
    }

  case Message::OverlayMapShapeReaded:
    {
      ref_ptr<OverlayMapShapeReadedMessage> msg = message;
      auto const & tileKey = msg->GetKey();
      if (m_requestedTiles->CheckTileKey(tileKey) && m_readManager->CheckTileKey(tileKey))
      {
        CleanupOverlays(tileKey);

        OverlayBatcher batcher(tileKey);
        for (drape_ptr<MapShape> const & shape : msg->GetShapes())
          batcher.Batch(shape, m_texMng);

        TOverlaysRenderData renderData;
        batcher.Finish(renderData);
        if (!renderData.empty())
        {
          m_overlays.reserve(m_overlays.size() + renderData.size());
          move(renderData.begin(), renderData.end(), back_inserter(m_overlays));
        }
      }
      break;
    }

  case Message::UpdateUserMarkLayer:
    {
      ref_ptr<UpdateUserMarkLayerMessage> msg = message;

      UserMarksProvider const * marksProvider = msg->StartProcess();
      if (marksProvider->IsDirty())
      {
        size_t const layerId = msg->GetLayerId();
        m_commutator->PostMessage(ThreadsCommutator::RenderThread,
                                  make_unique_dp<ClearUserMarkLayerMessage>(layerId),
                                  MessagePriority::Normal);

        TUserMarkShapes shapes = CacheUserMarks(marksProvider, m_texMng);
        m_commutator->PostMessage(ThreadsCommutator::RenderThread,
                                  make_unique_dp<FlushUserMarksMessage>(layerId, move(shapes)),
                                  MessagePriority::Normal);
      }
      msg->EndProcess();
      break;
    }

  case Message::AddRoute:
    {
      ref_ptr<AddRouteMessage> msg = message;
      m_routeBuilder->Build(msg->GetRoutePolyline(), msg->GetTurns(),
                            msg->GetColor(), msg->GetPattern(), m_texMng, msg->GetRecacheId());
      break;
    }

  case Message::CacheRouteSign:
    {
      ref_ptr<CacheRouteSignMessage> msg = message;
      m_routeBuilder->BuildSign(msg->GetPosition(), msg->IsStart(), msg->IsValid(), m_texMng, msg->GetRecacheId());
      break;
    }

  case Message::CacheRouteArrows:
    {
      ref_ptr<CacheRouteArrowsMessage> msg = message;
      m_routeBuilder->BuildArrows(msg->GetRouteIndex(), msg->GetBorders(), m_texMng, msg->GetRecacheId());
      break;
    }

  case Message::RemoveRoute:
    {
      ref_ptr<RemoveRouteMessage> msg = message;
      m_routeBuilder->ClearRouteCache();
      // We have to resend the message to FR, because it guaranties that
      // RemoveRouteMessage will be processed after FlushRouteMessage.
      m_commutator->PostMessage(ThreadsCommutator::RenderThread,
                                make_unique_dp<RemoveRouteMessage>(msg->NeedDeactivateFollowing()),
                                MessagePriority::Normal);
      break;
    }

  case Message::InvalidateTextures:
    {
      m_texMng->Invalidate(VisualParams::Instance().GetResourcePostfix());
      RecacheMapShapes();
      break;
    }

  case Message::CacheGpsTrackPoints:
    {
      ref_ptr<CacheGpsTrackPointsMessage> msg = message;
      drape_ptr<GpsTrackRenderData> data = make_unique_dp<GpsTrackRenderData>();
      data->m_pointsCount = msg->GetPointsCount();
      GpsTrackShape::Draw(m_texMng, *data.get());
      m_commutator->PostMessage(ThreadsCommutator::RenderThread,
                                make_unique_dp<FlushGpsTrackPointsMessage>(move(data)),
                                MessagePriority::Normal);
      break;
    }

  case Message::Allow3dBuildings:
    {
      ref_ptr<Allow3dBuildingsMessage> msg = message;
      m_readManager->Allow3dBuildings(msg->Allow3dBuildings());
      break;
    }

  case Message::RequestSymbolsSize:
    {
      ref_ptr<RequestSymbolsSizeMessage> msg = message;
      auto const & symbols = msg->GetSymbols();

      vector<m2::PointU> sizes(symbols.size());
      for (size_t i = 0; i < symbols.size(); i++)
      {
        dp::TextureManager::SymbolRegion region;
        m_texMng->GetSymbolRegion(symbols[i], region);
        sizes[i] = region.GetPixelSize();
      }
      msg->InvokeCallback(sizes);

      break;
    }

  default:
    ASSERT(false, ());
    break;
  }
}
示例#7
0
void AudioTimingControllerKaraoke::GetLabels(TimeRange const& range, std::vector<AudioLabel> &out) const {
	copy(labels | boost::adaptors::filtered([&](AudioLabel const& l) {
		return range.overlaps(l.range);
	}), back_inserter(out));
}
示例#8
0
void wmi_pager::get_items(const map_location& hex,
		game_data & gamedata, filter_context & fc, unit_map & units,
               std::vector<wmi_ptr > & items,
               std::vector<std::string> & descriptions)
{
	if (!wmi_container_) {
		return;
	}

	const int page_size_int = preferences::max_wml_menu_items();

	assert(page_size_int >= 0 && "max wml menu items cannot be negative, this indicates preferences corruption");

	const size_t page_size = page_size_int;

	assert(page_size > 2u && "if we dont have at least 3 items, we can't display anything on a middle page...");

	std::vector<wmi_pair > new_items = wmi_container_->get_items(hex, gamedata, fc, units);

	if (new_items.size() <= page_size) { //In this case the first page is sufficient and we don't have to do anything.
		std::transform(new_items.begin(), new_items.end(), back_inserter(items), select_first);
		std::transform(new_items.begin(), new_items.end(), back_inserter(descriptions), select_second);

		page_num_ = 0; //reset page num in case there are more items later.
		return;
	}

	if (page_num_ < 0) //should never happen but maybe some wierd gui thing happens idk
	{
		page_num_ = 0;
	}

	if (page_num_ == 0) { //we are on the first page, so show page_size-1 items and a next button
		wmi_it end_first_page = new_items.begin();
		std::advance(end_first_page, page_size - 1);

		std::transform(new_items.begin(), end_first_page, back_inserter(items), select_first);
		std::transform(new_items.begin(), end_first_page, back_inserter(descriptions), select_second);

		add_next_page_item(items, descriptions);
		return;
	}

	add_prev_page_item(items, descriptions); //this will be necessary since we aren't on the first page

	// first page has page_size - 1.
	// last page has page_size - 1.
	// all other pages have page_size - 2;

	size_t first_displayed_index = (page_size - 2) * page_num_ + 1; //this is the 0-based index of the first item displayed on this page.
									//alternatively, the number of items displayed on earlier pages

	while (first_displayed_index >= new_items.size())
	{
		page_num_--; //The list must have gotten shorter and our page counter is now off the end, so decrement
		first_displayed_index = (page_size - 2) * page_num_ + 1; //recalculate
	}
	// ^ This loop terminates with first_displayed_index > 0, because new_items.size() > page_size or else we exited earlier, and we only decrease by (page_size-2) each time.

	if (first_displayed_index + page_size-1 >= new_items.size()) //if this can be the last page, then we won't put next page at the bottom.
	{
		//The last page we treat differently -- we always want to display (page_size) entries, to prevent resizing the context menu, so count back from end.
		wmi_it end_range = new_items.end(); // It doesn't really matter if we display some entries that appeared on the previous page by doing this.
		wmi_it start_range = end_range;
		std::advance(start_range, -static_cast<signed int>(page_size-1));

		std::transform(start_range, end_range, back_inserter(items), select_first);
		std::transform(start_range, end_range, back_inserter(descriptions), select_second);
		return;
	} else { //we are in a middle page
		wmi_it start_range = new_items.begin();
		std::advance(start_range, first_displayed_index); // <-- get an iterator to the start of our range. begin() + n doesn't work because map is not random access

		wmi_it end_range = start_range;
		std::advance(end_range, page_size-2);

		std::transform(start_range, end_range, back_inserter(items), select_first);
		std::transform(start_range, end_range, back_inserter(descriptions), select_second);

		add_next_page_item(items, descriptions);
		return;
	}
}
User::List UploadManager::getWaitingUsers() {
	Lock l(cs);
	User::List u;
	transform(waitingUsers.begin(), waitingUsers.end(), back_inserter(u), select1st<WaitingUser>());
	return u;
}
示例#10
0
SparseWeightMatrix tangent_weight_matrix(RandomAccessIterator begin, RandomAccessIterator end,
                                         const Neighbors& neighbors, PairwiseCallback callback,
                                         const IndexType target_dimension, const ScalarType shift,
                                         const bool partial_eigendecomposer=false)
{
	timed_context context("KLTSA weight matrix computation");
	const IndexType k = neighbors[0].size();

	SparseTriplets sparse_triplets;
	sparse_triplets.reserve((k*k+2*k+1)*(end-begin));

#pragma omp parallel shared(begin,end,neighbors,callback,sparse_triplets) default(none)
	{
		IndexType index_iter;
		DenseMatrix gram_matrix = DenseMatrix::Zero(k,k);
		DenseVector rhs = DenseVector::Ones(k);
		DenseMatrix G = DenseMatrix::Zero(k,target_dimension+1);
		G.col(0).setConstant(1/sqrt(static_cast<ScalarType>(k)));
		DenseSelfAdjointEigenSolver solver;
		SparseTriplets local_triplets;
		local_triplets.reserve(k*k+2*k+1);

#pragma omp for nowait
		for (index_iter=0; index_iter<static_cast<IndexType>(end-begin); index_iter++)
		{
			const LocalNeighbors& current_neighbors = neighbors[index_iter];

			for (IndexType i=0; i<k; ++i)
			{
				for (IndexType j=i; j<k; ++j)
				{
					ScalarType kij = callback.kernel(begin[current_neighbors[i]],begin[current_neighbors[j]]);
					gram_matrix(i,j) = kij;
					gram_matrix(j,i) = kij;
				}
			}

			centerMatrix(gram_matrix);

			//UNRESTRICT_ALLOC;
#ifdef TAPKEE_WITH_ARPACK
			if (partial_eigendecomposer)
			{
				G.rightCols(target_dimension).noalias() =
					eigendecomposition<DenseMatrix,DenseMatrixOperation>(Arpack,gram_matrix,target_dimension,0).first;
			}
			else
#endif
			{
				solver.compute(gram_matrix);
				G.rightCols(target_dimension).noalias() = solver.eigenvectors().rightCols(target_dimension);
			}
			//RESTRICT_ALLOC;
			gram_matrix.noalias() = G * G.transpose();

			SparseTriplet diagonal_triplet(index_iter,index_iter,shift);
			local_triplets.push_back(diagonal_triplet);
			for (IndexType i=0; i<k; ++i)
			{
				SparseTriplet neighborhood_diagonal_triplet(current_neighbors[i],current_neighbors[i],1.0);
				local_triplets.push_back(neighborhood_diagonal_triplet);

				for (IndexType j=0; j<k; ++j)
				{
					SparseTriplet tangent_triplet(current_neighbors[i],current_neighbors[j],-gram_matrix(i,j));
					local_triplets.push_back(tangent_triplet);
				}
			}
#pragma omp critical
			{
				copy(local_triplets.begin(),local_triplets.end(),back_inserter(sparse_triplets));
			}

			local_triplets.clear();
		}
	}

	return sparse_matrix_from_triplets(sparse_triplets, end-begin, end-begin);
}
示例#11
0
	void image_callback(const sensor_msgs::Image& image_source)
	{
		cv_bridge::CvImagePtr cv_image = cv_bridge::toCvCopy(image_source, sensor_msgs::image_encodings::BGR8);
		cv::Mat image_track = cv_image->image;
		
		ObjectDetection empty_detection;
		empty_detection.rect=cv::Rect(0,0,0,0);
		empty_detection.score=0;
		unsigned int i;

		std::vector<bool> tracker_matched(obj_trackers_.size(), false);
		std::vector<bool> object_matched(obj_detections_.size(), false);

		//check object detections vs current trackers
		for (i =0; i< obj_detections_.size(); i++)
		{
			for (unsigned int j = 0; j < obj_trackers_.size(); j++)
			{
				if (tracker_matched[j] || object_matched[i])
					continue;

				ObjectDetection tmp_detection = obj_detections_[i];
				int area = tmp_detection.rect.width * tmp_detection.rect.height;
				cv::Rect intersection = tmp_detection.rect & obj_trackers_[j]->GetTrackedObject().rect;
				if ( (intersection.width * intersection.height) > area*0.3 )
				{

					obj_trackers_[j]->Track(image_track, obj_detections_[i], true);
					tracker_matched[j] = true;
					object_matched[i] = true;
					//std::cout << "matched " << i << " with " << j << std::endl;
				}
			}
		}

		//run the trackers not matched
		for(i = 0; i < obj_trackers_.size(); i++)
		{
			if(!tracker_matched[i])
			{
				obj_trackers_[i]->Track(image_track, empty_detection, false);
			}
		}

		//create trackers for those objects not being tracked yet
		for(unsigned int i=0; i<obj_detections_.size(); i++)
		{
			if (!object_matched[i])//if object wasn't matched by overlapping area, create a new tracker
			{
				if (num_trackers_ >10)
					num_trackers_=0;
				LkTracker* new_tracker = new LkTracker(++num_trackers_, min_heights_[i], max_heights_[i], ranges_[i]);
				new_tracker->Track(image_track, obj_detections_[i], true);

				//std::cout << "added new tracker" << std::endl;
				obj_trackers_.push_back(new_tracker);
			}
		}

		ApplyNonMaximumSuppresion(obj_trackers_, 0.3);

		//remove those trackers with its lifespan <=0
		std::vector<LkTracker*>::iterator it;
		for(it = obj_trackers_.begin(); it != obj_trackers_.end();)
		{
			if ( (*it)->GetRemainingLifespan()<=0 )
			{
				it = obj_trackers_.erase(it);
				//std::cout << "deleted a tracker " << std::endl;
			}
			else
				it++;
		}

		//copy results to ros msg
		unsigned int num = obj_trackers_.size();
		std::vector<cv_tracker_msgs::image_rect_ranged> rect_ranged_array;//tracked rectangles
		std::vector<int> real_data(num,0);//boolean array to show if data in rect_ranged comes from tracking or detection
		std::vector<unsigned int> obj_id(num, 0);//id number for each rect_range
		std::vector<unsigned int> lifespan(num, 0);//remaining lifespan of each rectranged
		for(i=0; i < num; i++)
		{
			cv_tracker_msgs::image_rect_ranged rect_ranged;
			LkTracker tracker_tmp = *obj_trackers_[i];
			rect_ranged.rect.x = tracker_tmp.GetTrackedObject().rect.x;
			rect_ranged.rect.y = tracker_tmp.GetTrackedObject().rect.y;
			rect_ranged.rect.width = tracker_tmp.GetTrackedObject().rect.width;
			rect_ranged.rect.height = tracker_tmp.GetTrackedObject().rect.height;
			rect_ranged.rect.score = tracker_tmp.GetTrackedObject().score;
			rect_ranged.max_height = tracker_tmp.max_height_;
			rect_ranged.min_height = tracker_tmp.min_height_;
			rect_ranged.range = tracker_tmp.range_;

			rect_ranged_array.push_back(rect_ranged);

			lifespan[i] = tracker_tmp.GetRemainingLifespan();
			obj_id[i] = tracker_tmp.object_id;
			if(lifespan[i]==tracker_tmp.DEFAULT_LIFESPAN_)
				real_data[i] = 1;

			cv::rectangle(image_track, tracker_tmp.GetTrackedObject().rect, cv::Scalar(0,255,0), 2);
		}

		//std::cout << "TRACKERS: " << obj_trackers_.size() << std::endl;

		obj_detections_.clear();
        ranges_.clear();

		cv_tracker_msgs::image_obj_tracked tmp_objects_msg;

		tmp_objects_msg.type = tracked_type_;
		tmp_objects_msg.total_num = num;
		copy(rect_ranged_array.begin(), rect_ranged_array.end(), back_inserter(tmp_objects_msg.rect_ranged)); // copy vector
		copy(real_data.begin(), real_data.end(), back_inserter(tmp_objects_msg.real_data)); // copy vector
		copy(obj_id.begin(), obj_id.end(), back_inserter(tmp_objects_msg.obj_id)); // copy vector
		copy(lifespan.begin(), lifespan.end(), back_inserter(tmp_objects_msg.lifespan)); // copy vector

		tmp_objects_msg.header = image_source.header;

		ros_objects_msg_ = tmp_objects_msg;

		//publisher_tracked_objects_.publish(ros_objects_msg);

		//cv::imshow("KLT",image_track);
		//cv::waitKey(1);

		track_ready_ = true;
		//ready_ = false;

		publish_if_possible();

	}
示例#12
0
SparseWeightMatrix hessian_weight_matrix(RandomAccessIterator begin, RandomAccessIterator end,
                                         const Neighbors& neighbors, PairwiseCallback callback,
                                         const IndexType target_dimension)
{
	timed_context context("Hessian weight matrix computation");
	const IndexType k = neighbors[0].size();

	SparseTriplets sparse_triplets;
	sparse_triplets.reserve(k*k*(end-begin));

	const IndexType dp = target_dimension*(target_dimension+1)/2;

#pragma omp parallel shared(begin,end,neighbors,callback,sparse_triplets) default(none)
	{
		IndexType index_iter;
		DenseMatrix gram_matrix = DenseMatrix::Zero(k,k);
		DenseMatrix Yi(k,1+target_dimension+dp);

		SparseTriplets local_triplets;
		local_triplets.reserve(k*k+2*k+1);

#pragma omp for nowait
		for (index_iter=0; index_iter<static_cast<IndexType>(end-begin); index_iter++)
		{
			const LocalNeighbors& current_neighbors = neighbors[index_iter];

			for (IndexType i=0; i<k; ++i)
			{
				for (IndexType j=i; j<k; ++j)
				{
					ScalarType kij = callback.kernel(begin[current_neighbors[i]],begin[current_neighbors[j]]);
					gram_matrix(i,j) = kij;
					gram_matrix(j,i) = kij;
				}
			}

			centerMatrix(gram_matrix);

			DenseSelfAdjointEigenSolver sae_solver;
			sae_solver.compute(gram_matrix);

			Yi.col(0).setConstant(1.0);
			Yi.block(0,1,k,target_dimension).noalias() = sae_solver.eigenvectors().rightCols(target_dimension);

			IndexType ct = 0;
			for (IndexType j=0; j<target_dimension; ++j)
			{
				for (IndexType p=0; p<target_dimension-j; ++p)
				{
					Yi.col(ct+p+1+target_dimension).noalias() = Yi.col(j+1).cwiseProduct(Yi.col(j+p+1));
				}
				ct += ct + target_dimension - j;
			}

			for (IndexType i=0; i<static_cast<IndexType>(Yi.cols()); i++)
			{
				for (IndexType j=0; j<i; j++)
				{
					ScalarType r = Yi.col(i).dot(Yi.col(j));
					Yi.col(i) -= r*Yi.col(j);
				}
				ScalarType norm = Yi.col(i).norm();
				Yi.col(i) *= (1.f / norm);
			}
			for (IndexType i=0; i<dp; i++)
			{
				ScalarType colsum = Yi.col(1+target_dimension+i).sum();
				if (colsum > 1e-4)
					Yi.col(1+target_dimension+i).array() /= colsum;
			}

			// reuse gram matrix storage m'kay?
			gram_matrix.noalias() = Yi.rightCols(dp)*(Yi.rightCols(dp).transpose());

			for (IndexType i=0; i<k; ++i)
			{
				for (IndexType j=0; j<k; ++j)
				{
					SparseTriplet hessian_triplet(current_neighbors[i],current_neighbors[j],gram_matrix(i,j));
					local_triplets.push_back(hessian_triplet);
				}
			}

			#pragma omp critical
			{
				copy(local_triplets.begin(),local_triplets.end(),back_inserter(sparse_triplets));
			}

			local_triplets.clear();
		}
	}

	return sparse_matrix_from_triplets(sparse_triplets, end-begin, end-begin);
}
示例#13
0
SparseWeightMatrix linear_weight_matrix(const RandomAccessIterator& begin, const RandomAccessIterator& end,
                                        const Neighbors& neighbors, PairwiseCallback callback,
                                        const ScalarType shift, const ScalarType trace_shift)
{
	timed_context context("KLLE weight computation");
	const IndexType k = neighbors[0].size();

	SparseTriplets sparse_triplets;
	sparse_triplets.reserve((k*k+2*k+1)*(end-begin));

#pragma omp parallel shared(begin,end,neighbors,callback,sparse_triplets) default(none)
	{
		IndexType index_iter;
		DenseMatrix gram_matrix = DenseMatrix::Zero(k,k);
		DenseVector dots(k);
		DenseVector rhs = DenseVector::Ones(k);
		DenseVector weights;
		SparseTriplets local_triplets;
		local_triplets.reserve(k*k+2*k+1);

		//RESTRICT_ALLOC;
#pragma omp for nowait
		for (index_iter=0; index_iter<static_cast<IndexType>(end-begin); index_iter++)
		{
			ScalarType kernel_value = callback.kernel(begin[index_iter],begin[index_iter]);
			const LocalNeighbors& current_neighbors = neighbors[index_iter];

			for (IndexType i=0; i<k; ++i)
				dots[i] = callback.kernel(begin[index_iter], begin[current_neighbors[i]]);

			for (IndexType i=0; i<k; ++i)
			{
				for (IndexType j=i; j<k; ++j)
					gram_matrix(i,j) = kernel_value - dots(i) - dots(j) +
					                   callback.kernel(begin[current_neighbors[i]],begin[current_neighbors[j]]);
			}

			ScalarType trace = gram_matrix.trace();
			gram_matrix.diagonal().array() += trace_shift*trace;
			weights = gram_matrix.selfadjointView<Eigen::Upper>().ldlt().solve(rhs);
			weights /= weights.sum();

			SparseTriplet diagonal_triplet(index_iter,index_iter,1.0+shift);
			local_triplets.push_back(diagonal_triplet);
			for (IndexType i=0; i<k; ++i)
			{
				SparseTriplet row_side_triplet(current_neighbors[i],index_iter,-weights[i]);
				SparseTriplet col_side_triplet(index_iter,current_neighbors[i],-weights[i]);
				local_triplets.push_back(row_side_triplet);
				local_triplets.push_back(col_side_triplet);
				for (IndexType j=0; j<k; ++j)
				{
					SparseTriplet cross_triplet(current_neighbors[i],current_neighbors[j],weights(i)*weights(j));
					local_triplets.push_back(cross_triplet);
				}
			}

#pragma omp critical
			{
				copy(local_triplets.begin(),local_triplets.end(),back_inserter(sparse_triplets));
			}

			local_triplets.clear();
		}
		//UNRESTRICT_ALLOC;
	}

	return sparse_matrix_from_triplets(sparse_triplets, end-begin, end-begin);
}
示例#14
0
void pancake::init_masks(const uint32* masks, const uint8 m)
{
  hord_masks_.clear();
  copy(masks, masks+m, back_inserter(hord_masks_)); 
}
示例#15
0
    nlohmann::json collection::evaluate_log(std::string const& log)
    {
        nlohmann::json json_log;
        std::istringstream log_stream(log);
        for(std::string line; std::getline(log_stream, line); ) {
            auto const delimiter = line.find_first_of(':');
            if(delimiter != std::string::npos) {
                std::string key = line.substr(0, delimiter);
                std::string val = line.substr(delimiter + 2);
                std::replace(key.begin(), key.end(), ' ', '_');
                std::transform(key.begin(), key.end(), key.begin(), ::tolower);
                nlohmann::json json_val;
                try {
                    json_val = boost::lexical_cast<long>(val);
                } catch(boost::bad_lexical_cast const& e) {
                    if(val == "YES") {
                        json_val = true;
                    } else if(val == "NO") {
                        json_val = false;
                    } else if(val == "'NONE'") {
                        json_val = nullptr;
                    } else {
                        size_t const bson_hex_delimiter = val.find_first_of('/');
                        if(bson_hex_delimiter != std::string::npos) {
                            std::string const bson_hex_string = val.substr(0, bson_hex_delimiter);
                            std::string bson_decoded_data;
                            boost::algorithm::unhex(bson_hex_string.begin(), bson_hex_string.end(), back_inserter(bson_decoded_data));
                            json_val = convert_to_json(std::shared_ptr<bson>(bson_create_from_buffer(bson_decoded_data.data(), bson_decoded_data.size()), bson_del));
                        } else {
                            json_val = val;
                        }
                    }
                }

                if(json_log.find(key) != json_log.end()) {
                    if(json_log[key].type() != nlohmann::json::value_t::array) {
                        json_log[key] = nlohmann::json::array_t({ json_log[key] });
                    }
                    json_log[key].push_back(json_val);
                } else {
                    json_log[key] = json_val;

                }
            }
        }
        return json_log;
    }
std::vector<std::string> split(const std::string &str){
  std::istringstream iss(str); std::vector<std::string> res;
  copy(std::istream_iterator<std::string>(iss),  std::istream_iterator<std::string>(), back_inserter(res));
  return res;
}
示例#17
0
string JsonObject::convertUnicodeToUTF8(wstring source)
{
	string utf8line;
	utf8::utf16to8(source.begin(), source.end(), back_inserter(utf8line));
	return utf8line;
}
  bool generate() {
    code_.Clear();
    code_ += "{";
    code_ += "  \"$schema\": \"http://json-schema.org/draft-04/schema#\",";
    code_ += "  \"definitions\": {";
    for (auto e = parser_.enums_.vec.cbegin();
         e != parser_.enums_.vec.cend();
         ++e) {
      code_ += "    \"" + GenFullName(*e) + "\" : {";
      code_ += "      " + GenType("string") + ",";
      std::string enumdef("      \"enum\": [");
      for (auto enum_value = (*e)->vals.vec.begin(); 
           enum_value != (*e)->vals.vec.end();
           ++enum_value) {
        enumdef.append("\"" + (*enum_value)->name + "\"");
        if (*enum_value != (*e)->vals.vec.back()) {
          enumdef.append(", ");
        }
      }
      enumdef.append("]");
      code_ += enumdef;
      code_ += "    },";  // close type
    }
    for (auto s = parser_.structs_.vec.cbegin(); 
         s != parser_.structs_.vec.cend();
         ++s) {
      const auto &structure = *s;
      code_ += "    \"" + GenFullName(structure) + "\" : {";
      code_ += "      " + GenType("object") + ",";
      std::string comment;
      const auto &comment_lines = structure->doc_comment;
      for (auto comment_line = comment_lines.cbegin();
           comment_line != comment_lines.cend();
           ++comment_line) {
        comment.append(*comment_line);
      }
      if (comment.size() > 0) {
        code_ += "      \"description\" : \"" + comment + "\",";
      }
      code_ += "      \"properties\" : {";

      const auto &properties = structure->fields.vec;
      for (auto prop = properties.cbegin(); prop != properties.cend(); ++prop) {
        const auto &property = *prop;
        std::string typeLine("        \"" + property->name + "\" : { " + GenType(property->value.type) + " }");
        if (property != properties.back()) {
          typeLine.append(",");
        }          
        code_ += typeLine;
      }
      code_ += "      },";  // close properties

      std::vector<FieldDef *> requiredProperties;
      std::copy_if(properties.begin(), properties.end(),
                   back_inserter(requiredProperties),
                   [](FieldDef const *prop) { return prop->required; });
      if (requiredProperties.size() > 0) {
        std::string required_string("      \"required\" : [");
        for (auto req_prop = requiredProperties.cbegin();
             req_prop != requiredProperties.cend();
             ++req_prop) {
          required_string.append("\"" + (*req_prop)->name + "\"");
          if (*req_prop != requiredProperties.back()) {
            required_string.append(", ");
          }
        }
        required_string.append("],");
        code_ += required_string;
      }
      code_ += "      \"additionalProperties\" : false";
      std::string closeType("    }");
      if (*s != parser_.structs_.vec.back()) {
        closeType.append(",");
      }
      code_ += closeType;  // close type
    }
    code_ += "  },";  // close definitions

    // mark root type
    code_ += "  \"$ref\" : \"#/definitions/" +
             GenFullName(parser_.root_struct_def_) + "\"";

    code_ += "}";  // close schema root
    const std::string file_path = GeneratedFileName(path_, file_name_);
    const std::string final_code = code_.ToString();
    return SaveFile(file_path.c_str(), final_code, false);
  }
DottedVersion::DottedVersion(const std::string &verstr) :
    parts_()
{
  split(verstr, ".", back_inserter(parts_));
}
示例#20
0
ostream& operator<<(ostream& stream, const SequencedIteratorPair& p) {
    string s;
    copy(p.start, p.end, back_inserter(s));
    stream << "SI - i(" << p.sequence << ") sz(" << p.end-p.start << ") data: --" << s << "--";
    return stream;
}
示例#21
0
void TestUTF8 (void)
{
    cout << "Generating Unicode characters ";
    vector<wchar_t> srcChars;
    srcChars.resize (0xFFFF);
    iota (srcChars.begin(), srcChars.end(), 0);
    cout << size_t(srcChars[0]) << " - " << size_t(srcChars.back()) << endl;

    cout << "Encoding to utf8." << endl;
    string encoded;
    encoded.reserve (srcChars.size() * 4);
    copy (srcChars, utf8out (back_inserter(encoded)));
    const char c_ProperEncoding[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    if (encoded.compare (encoded.begin(), encoded.begin() + VectorSize(c_ProperEncoding), VectorRange(c_ProperEncoding))) {
	cout << "Encoding failed: ";
	for (string::const_iterator i = encoded.begin(); i != encoded.begin() + VectorSize(c_ProperEncoding); ++ i)
	    cout << uint32_t(*i);
	cout << endl;
    }

    cout << "Decoding back." << endl;
    vector<wchar_t> decChars;
    assert( decChars.size() == 0 );
    Widen (encoded, decChars);

    cout << "Comparing." << endl;
    cout << "src = " << srcChars.size();
    cout << " chars, encoded = " << encoded.size();
    cout << " chars, decoded = " << decChars.size() << endl;
    size_t nDiffs = 0;
    for (uoff_t i = 0; i < min (srcChars.size(), decChars.size()); ++ i) {
	if (srcChars[i] != decChars[i]) {
	    cout << uint32_t(srcChars[i]) << " != " << uint32_t(decChars[i]) << endl;
	    ++ nDiffs;
	}
    }
    cout << nDiffs << " differences between src and decoded." << endl;

    cout << "Testing wide character string::insert" << endl;
    string ws ("1234567890", 10);

    ws.insert (0, wchar_t(1234));
    ws.insert (3, wchar_t(2345));
    const wchar_t c_WChars[2] = { 3456, 4567 };
    ws.insert (3, VectorRange(c_WChars), 2);
    ws.insert (ws.utf_length(), wchar_t(5678));
    cout << "Values[" << ws.utf_length() << "]:";
    for (string::utf8_iterator j = ws.utf8_begin(); j < ws.utf8_end(); ++ j)
	cout << ' ' << (uint32_t) *j;
    cout << endl;

    cout << "Character offsets:";
    for (string::utf8_iterator k = ws.utf8_begin(); k < ws.utf8_end(); ++ k)
	cout << ' ' << distance (ws.begin(), k.base());
    cout << endl;

    cout << "Erasing character " << ws.utf_length() - 1 << ": ";
    ws.erase (ws.utf_length() - 1);
    Widen (ws, decChars);
    DumpWchars (decChars);
    cout << endl;

    cout << "Erasing characters 3-5: ";
    ws.erase (3, 2);
    Widen (ws, decChars);
    DumpWchars (decChars);
    cout << endl;
}
示例#22
0
/**
 * Find a list of candidate marker from a given scene
 *
 * @param current frame, in grayscale 8UC1 format
 * @return a list of marker candidates
 **/
vector<Marker> MarkerDetector::findMarkerCandidates( Mat& frame ) {
    vector<Marker> candidates;
    
    /* Do some thresholding, in fact you should tune the parameters here a bit */
    Mat thresholded;
    threshold( frame, thresholded, 50.0, 255.0, CV_THRESH_BINARY );
    
    /* Find contours */
    vector<vector<Point>> contours;
    findContours( thresholded.clone(), contours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE );
    
    for( vector<Point> contour: contours ) {
        /* Approximate polygons out of these contours */
        vector<Point> approxed;
        approxPolyDP( contour, approxed, contour.size() * 0.05, true );
        
        /* Make sure it passes our first candidate check */
        if( !checkPoints( approxed ) )
            continue;
        
        /* Do some perspective transformation on the candidate marker to a predetermined square */
        Marker marker;
        marker.matrix = Mat( markerHeight, markerWidth, CV_8UC1 );
        std::copy( approxed.begin(), approxed.end(), back_inserter( marker.poly ) );
        
        /* Apply sub pixel search */
        cornerSubPix( thresholded, marker.poly, Size(5, 5), Size(-1, -1), TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 40, 0.001) );
        
        /* Projection target */
        const static vector<Point2f> target_corners = {
            Point2f( -0.5f, -0.5f ),
            Point2f( +5.5f, -0.5f ),
            Point2f( +5.5f, +5.5f ),
            Point2f( -0.5f, +5.5f ),
        };
        
        /* Apply perspective transformation, to project our 3D marker to a predefined 2D coords */
        Mat projection = getPerspectiveTransform( marker.poly, target_corners );
        warpPerspective( thresholded, marker.matrix, projection, marker.matrix.size() );
        
        /* Ignore those region that's fully black, or not surrounded by black bars */
        if( sum(marker.matrix) == Scalar(0) ||
           countNonZero( marker.matrix.row(0)) != 0 ||
           countNonZero( marker.matrix.row(markerHeight - 1)) != 0 ||
           countNonZero( marker.matrix.col(0)) != 0 ||
           countNonZero( marker.matrix.col(markerWidth - 1)) != 0 ) {
            continue;
        }
        
        
        /* Find the rotation that has the smallest hex value */
        pair<unsigned int, unsigned int> minimum = { numeric_limits<unsigned int>::max(), 0 };
        vector<unsigned int> codes(markerHeight);
        unsigned int power = 1 << (markerWidth - 3);
        
        /* Rotate the marker 4 times, store the hex code upon each rotation */
        for( int rotation = 0; rotation < 4; rotation++ ) {
            stringstream ss;
            codes[rotation] = 0;
            
            for( int i = 1; i < markerHeight - 1; i++ ) {
                unsigned int code = 0;
                for ( int j = 1; j < markerWidth - 1; j++ ){
                    int value = static_cast<int>(marker.matrix.at<uchar>(i, j));
                    if( value == 0 )
                        code = code + ( power >> j );
                }
                
                ss << hex << code;
            }
            ss >> codes[rotation];
            
            if( minimum.first > codes[rotation] ) {
                minimum.first  = codes[rotation];
                minimum.second = rotation;
            }
            
            flip( marker.matrix, marker.matrix, 1 );
            marker.matrix = marker.matrix.t();
        }
        
        
        rotate( marker.poly.begin(), marker.poly.begin() + ((minimum.second + 2) % 4), marker.poly.end() );
        for( int i = 0; i < minimum.second; i++ ) {
            flip( marker.matrix, marker.matrix, 1 );
            marker.matrix = marker.matrix.t();
        }
        
        marker.code = minimum.first;
        
        candidates.push_back( marker );
    }
    
    return candidates;
}
示例#23
0
    void
    operator()(const CommunicatorDescriptorPtr& desc)
    {
        //
        // Figure out the configuration file name for the communicator
        // (if it's a service, it's "config_<service name>", if it's
        // the server, it's just "config").
        //
        string filename = "config";
        ServiceDescriptorPtr svc = ServiceDescriptorPtr::dynamicCast(desc);
        if(svc)
        {
            filename += "_" + svc->name;
            _desc->services->push_back(svc->name);
        }

        PropertyDescriptorSeq& props = _desc->properties[filename];
        PropertyDescriptorSeq communicatorProps = desc->propertySet.properties;

        //
        // If this is a service communicator and the IceBox server has Admin
        // enabled or Admin endpoints configured, we ignore the server-lifetime attributes
        // of the service object adapters and assume it's set to false.
        //
        bool ignoreServerLifetime = false;
        if(svc)
        {
            if(_iceVersion == 0 || _iceVersion >= 30300)
            {
                if(getPropertyAsInt(_desc->properties["config"], "Ice.Admin.Enabled") > 0 ||
                   getProperty(_desc->properties["config"], "Ice.Admin.Endpoints") != "")
                {
                    ignoreServerLifetime = true;
                }
            }
        }
        //
        // Add the adapters and their configuration.
        //
        for(AdapterDescriptorSeq::const_iterator q = desc->adapters.begin(); q != desc->adapters.end(); ++q)
        {
            _desc->adapters.push_back(new InternalAdapterDescriptor(q->id,
                                                                    ignoreServerLifetime ? false : q->serverLifetime));

            props.push_back(createProperty("# Object adapter " + q->name));
            PropertyDescriptor prop = removeProperty(communicatorProps, q->name + ".Endpoints");
            prop.name = q->name + ".Endpoints";
            props.push_back(prop);
            props.push_back(createProperty(q->name + ".AdapterId", q->id));
            if(!q->replicaGroupId.empty())
            {
                props.push_back(createProperty(q->name + ".ReplicaGroupId", q->replicaGroupId));
            }

            //
            // Ignore the register process attribute if the server is using Ice >= 3.3.0
            //
            if(_iceVersion != 0 && _iceVersion < 30300)
            {
                if(q->registerProcess)
                {
                    props.push_back(createProperty(q->name + ".RegisterProcess", "1"));
                    _desc->processRegistered = true;
                }
            }
        }

        _desc->logs.insert(_desc->logs.end(), desc->logs.begin(), desc->logs.end());

        const string dbsPath = _node->dataDir + "/servers/" + _desc->id + "/dbs/";
        for(DbEnvDescriptorSeq::const_iterator p = desc->dbEnvs.begin(); p != desc->dbEnvs.end(); ++p)
        {
            props.push_back(createProperty("# Database environment " + p->name));
            if(p->dbHome.empty())
            {
                _desc->dbEnvs.push_back(new InternalDbEnvDescriptor(p->name, p->properties));
                props.push_back(createProperty("Freeze.DbEnv." + p->name + ".DbHome", dbsPath + p->name));
            }
            else
            {
                props.push_back(createProperty("Freeze.DbEnv." + p->name + ".DbHome", p->dbHome));
            }
        }

        //
        // Copy the communicator descriptor properties.
        //
        if(!communicatorProps.empty())
        {
            if(svc)
            {
                props.push_back(createProperty("# Service descriptor properties"));
            }
            else
            {
                props.push_back(createProperty("# Server descriptor properties"));
            }
            copy(communicatorProps.begin(), communicatorProps.end(), back_inserter(props));
        }

        //
        // For Ice servers > 3.3.0 escape the properties.
        //
        if(_iceVersion == 0 || _iceVersion >= 30300)
        {
            for(PropertyDescriptorSeq::iterator p = props.begin(); p != props.end(); ++p)
            {
                if(p->name.find('#') != 0 || !p->value.empty())
                {
                    p->name = escapeProperty(p->name, true);
                    p->value = escapeProperty(p->value);
                }
            }
        }
    }
void iAnt_controller::GetPattern(string ith_Pattern)
{
    copy(ith_Pattern.begin(),ith_Pattern.end(),back_inserter(tempPattern));
    reverse(tempPattern.begin(), tempPattern.end());
}
示例#25
0
void NaiveBayes::train(const Matrix &X, const Matrix &y)
{
    // clear last data
    labelDistinct.clear();
    attributeUniqueNumber.clear();
    labelProbability.clear();
    attributeProbability.clear();

    // y distinct
    vector<double> labels;
    for (Matrix::size_type i = 0; i < y.rowSize(); ++i) {
        labels.push_back(y(i, 0));
    }
    sort(labels.begin(), labels.end());
    unique_copy(labels.begin(), labels.end(), back_inserter(labelDistinct));
#ifdef DEBUG
    cout << "all labels" << endl;
    for (auto label : labels)
        cout << label << '\t';
    cout << endl;

    cout << "distinct labels" << endl;
    for (auto label : labelDistinct)
        cout << label << '\t';
    cout << endl << endl;
#endif

    // calculate labelPro
    auto N = y.rowSize();
    double yDistinct = static_cast<double>(y.distinctColumn()[0].size());
    for (auto yEach : labelDistinct) {
        auto range = equal_range(labels.begin(), labels.end(), yEach);
        auto yCount = range.second - range.first;
        labelProbability[yEach] = (yCount + lambda) / (static_cast<double>(N) + yDistinct * lambda);
#ifdef DEBUG
        cout << "y = " << yEach << " ";
        cout << "labelPro = " << labelProbability[yEach] << endl;
#endif
    }

    // calculate distinct number of attribute in each column
    vector<vector<double>> distinctAttribute = X.distinctColumn();
    attributeUniqueNumber.resize(X.columnSize());
    transform(distinctAttribute.begin(), distinctAttribute.end(), attributeUniqueNumber.begin(),
              [](const vector<double> &distinctUnit) {return distinctUnit.size();});
#ifdef DEBUG
    for (auto &distinctNumber : attributeUniqueNumber)
        cout << distinctNumber << '\t';
    cout << endl;
#endif

    // attributeProbability
    vector<Matrix> trainVec = X.merge(y, 1).splictRow();
    for (auto yEach : labelDistinct) {
#ifdef DEBUG
        cout << "y = " << yEach << endl;
#endif
        attributeProbability[yEach].resize(X.columnSize());
        auto partitionIter = partition(trainVec.begin(), trainVec.end(),
                  [=](const Matrix &m) {return m(0, m.columnSize() - 1) == yEach;});
        auto xWithSameY = partitionIter - trainVec.begin();
        vector<vector<double>> attributes(X.columnSize());
        for (vector<Matrix>::iterator it = trainVec.begin(); it != partitionIter; ++it) {
            for (Matrix::size_type col = 0; col < it->columnSize() - 1; ++col) {
                attributes[col].push_back(it->operator()(0, col));
            }
        }
        for (auto i = 0; i < attributes.size(); ++i) {
            vector<double> columnEach = attributes[i];
            sort(columnEach.begin(), columnEach.end());
            vector<double> columnDistinct;
            unique_copy(columnEach.begin(), columnEach.end(), back_inserter(columnDistinct));
            for (double &attributeEach : columnDistinct) {
                auto range = equal_range(columnEach.begin(), columnEach.end(), attributeEach);
                auto xCount = range.second - range.first;
                attributeProbability[yEach][i][attributeEach] =
                        (xCount + lambda) / (static_cast<double>(xWithSameY) + attributeUniqueNumber[i] * lambda);
#ifdef DEBUG
                cout << "y = " << yEach << " " << i << "th column ";
                cout << " attribute = " << attributeEach ;
                cout << " attributePro = " << xCount / static_cast<double>(xWithSameY) << endl;
#endif
            }
        }
    }

}
    /* Initialize the robot's actuator and sensor objects. */
    motorActuator   = GetActuator<CCI_DSA>("differential_steering");
    compass         = GetSensor<CCI_PS>   ("positioning");
    proximitySensor = GetSensor<CCI_FBPS> ("footbot_proximity");

    TConfigurationNode iAnt_params = GetNode(node, "iAnt_params");
    GetNodeAttribute(iAnt_params, "RobotForwardSpeed", RobotForwardSpeed);
    GetNodeAttribute(iAnt_params, "RobotTurningSpeed", RobotTurningSpeed);
    GetNodeAttribute(iAnt_params, "AngleToleranceInDegrees", angleInDegrees);

    AngleToleranceInRadians.Set(-ToRadians(angleInDegrees),ToRadians(angleInDegrees));

    stepSize = 0.1; /* Assigns the robot's stepSize */
    startPosition = CVector3(0.0, 0.0, 0.0);
}


bool iAnt_controller::Stop ()
{
    bool stop = false;

    if(stopTimeStep > 0)
    {
        stopTimeStep--;
        stop = true;
    }
    return stop;

}

void iAnt_controller::SetStop(size_t stop_time_in_seconds)
{
    stopTimeStep += stop_time_in_seconds* data->TicksPerSecond;

}

void iAnt_controller::GetPattern(string ith_Pattern)
{
    copy(ith_Pattern.begin(),ith_Pattern.end(),back_inserter(tempPattern));
    reverse(tempPattern.begin(), tempPattern.end());
}

// /*****
//  *
//  *****/
void iAnt_controller::CopyPatterntoTemp()
{
    copy(pattern.begin(),pattern.end(),back_inserter(tempPattern));
    reverse(tempPattern.begin(),tempPattern.end());/* Reverses the tempPattern */
}
示例#27
0
vector<double> make_cb (vector<double> wb, double eta, double wc, double dw) {
  //vector<double> cb(wb.size(),0.0);
  vector<double> cb;
  boost::transform(wb,back_inserter(cb), c{j(eta,wc),dw});
  return cb;
}
示例#28
0
  bool OBMoleculeFormat::ReadChemObjectImpl(OBConversion* pConv, OBFormat* pFormat)
  {
    std::istream &ifs = *pConv->GetInStream();
    if (!ifs.good())
      return false;

    OBMol* pmol = new OBMol;

    std::string auditMsg = "OpenBabel::Read molecule ";
    std::string description(pFormat->Description());
    auditMsg += description.substr(0,description.find('\n'));
    obErrorLog.ThrowError(__FUNCTION__,
                          auditMsg,
                          obAuditMsg);

    if(pConv->IsOption("C",OBConversion::GENOPTIONS))
      return DeferMolOutput(pmol, pConv, pFormat);

    bool ret=true;
   if(pConv->IsOption("separate",OBConversion::GENOPTIONS))
   {
     //On first call, separate molecule and put fragments in MolArray.
     //On subsequent calls, remove a fragment from MolArray and send it for writing
     //Done this way so that each fragment can be written to its own file (with -m option)
     if(!StoredMolsReady)
     {
       while(ret) //do all the molecules in the file
       {
         ret = pFormat->ReadMolecule(pmol,pConv);

         if(ret && (pmol->NumAtoms() > 0 || (pFormat->Flags()&ZEROATOMSOK)))
         {
           vector<OBMol> SepArray = pmol->Separate(); //use un-transformed molecule
           //Add an appropriate title to each fragment
           if(SepArray.size()>1)
             for(int i=0;i<SepArray.size();++i)
             {
               stringstream ss;
               ss << pmol->GetTitle() << '#' << i+1;
               string title = ss.str();
               SepArray[i].SetTitle(title);
             }
           else
              SepArray[0].SetTitle(pmol->GetTitle());

           copy(SepArray.begin(),SepArray.end(),back_inserter(MolArray));
         }
       }
       reverse(MolArray.begin(),MolArray.end());
       StoredMolsReady = true;
       //Clear the flags of the input stream(which may have found eof) to ensure will
       //try to read anothe molecule and allow the stored ones to be sent for output.
       pConv->GetInStream()->clear();
     }

     if(MolArray.empty()) //normal end of fragments
       ret =false;
     else
     {
       // Copying is needed because the OBMol passed to AddChemObject will be deleted.
       // The OBMol in the vector is deleted here.
       OBMol* pMolCopy = new OBMol( MolArray.back());
       MolArray.pop_back();
       ret = pConv->AddChemObject(
           pMolCopy->DoTransformations(pConv->GetOptions(OBConversion::GENOPTIONS), pConv))!=0;
     }
     if(!ret)
       StoredMolsReady = false;

     delete pmol;
     return ret;
   }

    ret=pFormat->ReadMolecule(pmol,pConv);

    OBMol* ptmol = NULL;
    //Molecule is valid if it has some atoms
    //or the format allows zero-atom molecules and it has a title or properties
    if(ret && (pmol->NumAtoms() > 0 
      || (pFormat->Flags()&ZEROATOMSOK && (*pmol->GetTitle() || pmol->HasData(1)))))
    {
      ptmol = static_cast<OBMol*>(pmol->DoTransformations(pConv->GetOptions(OBConversion::GENOPTIONS),pConv));
      if(ptmol && (pConv->IsOption("j",OBConversion::GENOPTIONS)
                || pConv->IsOption("join",OBConversion::GENOPTIONS)))
      {
        //With j option, accumulate all mols in one stored in this class
        if(pConv->IsFirstInput())
          _jmol = new OBMol;
        pConv->AddChemObject(_jmol);
        //will be discarded in WriteChemObjectImpl until the last input mol. This complication
        //is needed to allow joined molecules to be from different files. pOb1 in AddChem Object
        //is zeroed at the end of a file and _jmol is in danger of not being output.
        *_jmol += *ptmol;
        delete ptmol;
        return true;
      }
    }
    else
      delete pmol;

    // Normal operation - send molecule to be written
    ret = ret && (pConv->AddChemObject(ptmol)!=0); //success of both writing and reading
    return ret;
  }
示例#29
0
文件: mru.cpp 项目: jeeb/aegisub
/// @brief Load MRU Lists.
/// @param key List name.
/// @param array json::Array of values.
void MRUManager::Load(const std::string &key, const json::Array& array) {
	transform(array.Begin(), array.End(), back_inserter(mru[key]), cast_str);
	Prune(mru[key]);
}
示例#30
0
 void CPP::add_model(Ptr<Model> m){
   if(have_model(m)) return;
   models_.push_back(m);
   ParamVec tmp(m->t());
   std::copy(tmp.begin(), tmp.end(), back_inserter(t_));
 }