Пример #1
0
//returns random POSITIONS that will correspond to id's
//todo: check duplicate possibility p(1/10000) but exists
vector<int> Cluster::_selectRandomSeeds(int K) {
  vector<int> seeds (K, 0);
  int size = doc_term_index.size();

  int id;
  double r;

  //build a copy list of item ids
  vector<int> nums;
  for (unordered_int_string_map::iterator i = doc_term_index.begin(); i != doc_term_index.end(); ++i) {
    nums.insert(nums.begin(), i->first );
  }

  srand( time(NULL) );

  for (int k = 0; k < K; k++) {
    //random seed
    r = (double) rand() / (double) RAND_MAX;
    //cout << "r: " << r << endl;
    id = (int) (r * (size-k));
    //take random position from nums (vector of ids) and that is a seed
    seeds[k] = nums[id];
    //cout << nums[id] <<endl;
    //remove that seed and shrink available nums accordingly

    nums.erase(nums.begin() + id );
  }

  cout << "Finished _selectRandomSeeds(" << K << ")" <<endl;
  return seeds;
}
Пример #2
0
    std::vector<std::default_random_engine> GetRandomEngines(int num, std::string seed_string)
    {
        std::vector<int> seeds(num);

        if (seed_string != "")
        {
            std::seed_seq seq(seed_string.begin(), seed_string.end());
            seq.generate(seeds.begin(), seeds.end());
        }
        else
        {
            std::random_device d;
            std::seed_seq seq{ d(), d(), d(), d(), d(), d(), d(), d() };
            seq.generate(seeds.begin(), seeds.end());
        }

        // create the independent generators
        std::vector<std::default_random_engine> rngs;
        rngs.reserve(num);
        for (auto seed : seeds)
        {
            rngs.emplace_back(seed);
        }

        return rngs;
    }
Пример #3
0
void OPTICSFilter::expandClusterOrder(OPTICSObject_Ptr node) {
    OPTICSObjectVector_Ptr epsilonNeighbors = getEpsilonNeighbors(node);
    node->processed = true;

    // output p to the ordered list
    _orderedObjects.push_back(node);

    OPTICSObjectVector_Ptr seeds(new OPTICSObjectVector);
    if (node->coreDistance != UNDEFINED_DISTANCE) {
        updateSeeds(epsilonNeighbors, node, seeds);

        while (!seeds->empty()) {
            OPTICSObject_Ptr currentObject = seeds->back();
            seeds->pop_back();

            OPTICSObjectVector_Ptr currentObjectEpsilonNeighbors = getEpsilonNeighbors(currentObject);

            // output q to the ordered list
            if (currentObject->processed == false) {
                _orderedObjects.push_back(currentObject);
                currentObject->processed = true;
            } else
                continue;

            if (currentObject->coreDistance != UNDEFINED_DISTANCE) {
                updateSeeds(currentObjectEpsilonNeighbors, currentObject, seeds);
            }
        }
    }
}
Пример #4
0
TEST(test_Random, MultiThreadSeed)
{
    int count = 20;
    std::vector<uint32_t> seeds(count);
    std::vector<std::thread> ths;

    try {
        for (int i = 0; i < count; ++i) {
            ths.push_back(std::move(std::thread([i, &seeds]{
                seeds[i] = swift::Random::RandomNumberSeed();
            })));
        }

        for (auto&& i : ths) {
            i.join();
        }

        std::sort(seeds.begin(), seeds.end());
        for (int i = 0; i < count - 1; ++i) {
            EXPECT_LT(seeds[i], seeds[i + 1]);
        }
    }
    catch (std::exception& e) {
        std::cout << e.what() << std::endl;
    }
}
Пример #5
0
 /**
  * Create and seed the RNG
  */
 RandomGenerator() {
     std::random_device rd;
     std::mt19937::result_type random_data[std::mt19937::state_size];
     std::generate(std::begin(random_data), std::end(random_data), std::ref(rd));
     std::seed_seq seeds(std::begin(random_data), std::end(random_data));
     _mt.seed(seeds);
 }
Пример #6
0
// [[Rcpp::export]]
Rcpp::IntegerMatrix quantileNorm(Rcpp::IntegerMatrix mat, Rcpp::IntegerVector ref, int nthreads=1, int seed=13){
    if (mat.nrow() != ref.length()) Rcpp::stop("incompatible arrays...");
    if (!std::is_sorted(ref.begin(), ref.end())) Rcpp::stop("ref must be sorted");
    int ncol = mat.ncol();
    int nrow = mat.nrow();
    //allocate new matrix
    Rcpp::IntegerMatrix res(nrow, ncol);
    Mat<int> oldmat = asMat(mat); 
    Mat<int> newmat = asMat(res);
    Vec<int> ref2 = asVec(ref);
    //allocate a seed for each column
    std::seed_seq sseq{seed};
    std::vector<std::uint32_t> seeds(ncol);
    sseq.generate(seeds.begin(), seeds.end());
    
    #pragma omp parallel num_threads(nthreads)
    {
        std::vector<std::pair<int, int> > storage(nrow);//pairs <value, index>
        #pragma omp for 
        for (int col = 0; col < ncol; ++col){
            std::mt19937 gen(seeds[col]);
            qtlnorm(oldmat.getCol(col), ref2, newmat.getCol(col), storage, gen);
        }
    }
    
    res.attr("dimnames") = mat.attr("dimnames");
    return res;
}
Пример #7
0
p_struct createDirich(std::vector<double> alpha, std::size_t numSamples) {
  arma::mat R(numSamples, alpha.size()); //careful because of fortran <-> c-order!
  typedef std::gamma_distribution<double> Distribution;

  std::vector<int> seeds(alpha.size());
  std::seed_seq({0}).generate(seeds.begin(), seeds.end());

  std::vector<std::future<int> > answers(alpha.size());

  for (std::size_t i = 0; i < alpha.size(); ++i) {
    std::default_random_engine rSeedEngine_(seeds[i]);
    auto generator = std::bind(Distribution(alpha[i]), rSeedEngine_);
    answers[i] = std::async(std::launch::deferred,&writeToArray<decltype(R.begin()), decltype(generator)>, R.begin() + numSamples * i, R.begin() + numSamples * (i + 1), generator);
  }
  for (int i = 0; i < alpha.size(); ++i) {
    answers[i].get();
  }
  //normalize for every sample:
  arma::mat scaling = arma::sum(R,1);
  for (std::size_t i = 0; i < numSamples; ++i) {
    R.row(i) /= arma::as_scalar(scaling(i));
  }
  p_struct p;
  p.p2 = 1 - arma::as_scalar(arma::sum(arma::max(R, 1))) / numSamples;
  arma::mat alphaW(alpha.data(), alpha.size(), 1, false);
  p.p1 = 1 - arma::as_scalar(arma::max(alphaW) / arma::sum(alphaW));
  //arma::sum(R, 1).print();
  //std::cout << "blub" << std::endl;
  return p;
}
Пример #8
0
Файл: main.cpp Проект: sh0/dasp
Eigen::MatrixXf ComputePointDensity(const asp::Superpixels<Eigen::Vector3f>& sp, const Eigen::MatrixXf& ref)
{
	std::vector<Eigen::Vector2f> seeds(sp.clusters.size());
	std::transform(sp.clusters.begin(), sp.clusters.end(), seeds.begin(),
		[](const asp::Cluster<Eigen::Vector3f>& c) {
			return Eigen::Vector2f{ c.x, c.y };
		});
	return density::PointDensity(seeds, ref);
}
Пример #9
0
int main()
{
    std::seed_seq seq{1,2,3,4,5};
    std::vector<std::uint32_t> seeds(2);
    seq.generate(seeds.begin(), seeds.end());
    for (std::uint32_t n : seeds) {
        std::cout << n << '\n';
    }
}
Пример #10
0
bool ForegroundExtractor::run(const cv::Mat& img, const cv::Mat& mot, int motionQ,bool wasAmbig,std::vector<std::vector<cv::Point> >& validContours){

    cv::Mat seeds;
    cv::Mat out;

    if(motionQ > 0){ //todo rational
        this->updateTrainingRate();
        //
        double modifier;
        if(!wasAmbig || roundTrained < m_roundToTrain){
            modifier = 1;
        }
        else{
            modifier = FOREGROUND_MODIF_MANY_BLOBS;
        }

        mog(img, out,trainingRate * modifier);

        cv::dilate(out,out,cv::Mat(),cv::Point(-1,-1),1);
        cv::erode(out,out,cv::Mat(),cv::Point(-1,-1),2);


        cv::bitwise_and(out,mot,seeds);
        std::vector<std::vector<cv::Point> > contours;
        cv::findContours(out, contours,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_SIMPLE);
        validContours.resize(contours.size());
        size_t idx = 0;
        for(size_t i = 0; i < contours.size(); i++){
            if(contours[i].size() > 5){
                cv::Rect boundRect =  cv::boundingRect(contours[i]);
                cv::Mat miniMask(boundRect.height,boundRect.width,CV_8U,cv::Scalar(0));
                cv::approxPolyDP(contours[i],contours[i],5,true);
                cv::drawContours(miniMask,contours,i,cv::Scalar(255),-1,8,cv::noArray(),INT_MAX ,cv::Point(-boundRect.x,-boundRect.y));
                cv::bitwise_and(miniMask,seeds(boundRect),miniMask);
                if (cv::countNonZero(miniMask) > 0){
                    validContours[idx] = contours[i]; //todo copyTo
                    idx++;
                }
            }
        }

        validContours.resize(idx);

        this->mergeContours(seeds,validContours);
        unsigned int beforeLargeRemoval = validContours.size();
        this->removeLargeContours(validContours, (img.cols+img.rows)/5);//magic number

        if(validContours.size() >1 || beforeLargeRemoval >  validContours.size())
            return false;
        else
            return true;
    }
    else{
        validContours.resize(0);
        return false;
    }
}
Пример #11
0
QPixmap SegmentationTool::getLabel( size_t axis ) {
    size_t xsz = guiImage->width( axis );
    size_t ysz = guiImage->heigth( axis );
    if( !seedsVisible && !maskVisible ) {
        return( QPixmap( ) );
    }
    if( !needUpdate[ axis ] ) {
        return( pixmaps[ axis ] );
    }
    const Bial::FastTransform &transf = guiImage->getTransform( axis );
    QImage res( xsz, ysz, QImage::Format_ARGB32 );
    if( !seedsVisible ) {
        res.fill( qRgba( 0, 0, 0, 0 ) );
    }
    else {
#pragma omp parallel for
        for( size_t y = 0; y < ysz; ++y ) {
            QRgb *scanLine = ( QRgb* ) res.scanLine( y );
            for( size_t x = 0; x < xsz; ++x ) {
                Bial::Point3D pos = transf( x, y, guiImage->currentSlice( axis ) );
                char pixel = seeds( pos.x, pos.y, pos.z );
                if( pixel == 1 ) {
                    scanLine[ x ] = qRgb( 0, 255, 0 );
                }
                else if( pixel == 2 ) {
                    scanLine[ x ] = qRgb( 0, 0, 255 );
                }
                else {
                    scanLine[ x ] = qRgba( 0, 0, 0, 0 );
                }
            }
        }
    }
    if( maskVisible && ( mask.size( ) == seeds.size( ) ) ) {
#pragma omp parallel for
        for( size_t y = 0; y < ysz; ++y ) {
            QRgb *scanLine = ( QRgb* ) res.scanLine( y );
            for( size_t x = 0; x < xsz; ++x ) {
                Bial::Point3D pos = transf( x, y, guiImage->currentSlice( axis ) );
                if( mask( pos.x, pos.y, pos.z ) ) {
                    scanLine[ x ] = qRgb( 255, 0, 0 );
                }
            }
        }
    }
    pixmaps[ axis ] = QPixmap::fromImage( res );
    return( pixmaps[ axis ] );
}
autoCategories PatternList_to_Categories_cluster
(
    ///////////////////////////////
    // Parameters                //
    ///////////////////////////////

    PatternList p,              // source
    //
    FeatureWeights fws,     // feature weights
    //
    long k,                 // k(!)
    //
    double s,               // clustersize constraint 0 < s <= 1
    //
    long m                  // reseed maximum
    //
)

{
    autoCategories categories = Categories_createWithSequentialNumbers (k);
    if (k == p->ny)
        return categories;

    autoKNN knn = KNN_create();
    if (p -> ny % k)
        if (s > (double) (p -> ny / k) / (double) (p -> ny / k + 1))   // FIXME check whether integer division is correct
            s = (double) (p -> ny / k) / (double) (p -> ny / k + 1);

    double progress = m;
    autoNUMvector <double> sizes (0L, k);
    autoNUMvector <long> seeds (0L, k);

    autoPatternList centroids = PatternList_create (k, p -> nx);
    autoNUMvector <double> beta (0L, centroids -> nx);

    do
    {
        double delta;
        long nfriends  = 0;
        Melder_progress (1 - (progress - m) / progress, U"");

        for (long y = 1; y <= centroids->ny; y++)
        {
            int ifriend = 1;
            long ys = (long) lround(NUMrandomUniform(1, p->ny));

            if (nfriends)
            {
                while (ifriend)
                {
                    ys = (long) lround(NUMrandomUniform(1, p->ny));
                    for (long fc = 0; fc < nfriends; fc++)
                    {
                        ifriend = 0;
                        Melder_assert (fc < k);
                        if (seeds [fc] == ys)
                        {
                            ifriend = 1;
                            break;
                        }
                    }
                }
            }
            Melder_assert (nfriends <= k);
            seeds [nfriends++] = ys;

            for (long x = 1; x <= centroids->nx; x++)
                centroids->z[y][x] = p->z[ys][x];
        }
        do
        {
            delta = 0;
            KNN_learn (knn.get(), centroids.get(), categories.get(), kOla_REPLACE, kOla_SEQUENTIAL);
            autoCategories interim = KNN_classifyToCategories (knn.get(), p, fws, 1, kOla_FLAT_VOTING);

            for (long x = 1; x <= k; x ++)
                sizes [x] = 0;

            for (long yp = 1; yp <= categories->size; yp ++)
            {
                double alfa = 1;
                Melder_assert (yp <= centroids -> ny);

                for (long x = 1; x <= centroids -> nx; x ++)
                {
                    beta [x] = centroids -> z [yp] [x];
                }

                for (long ys = 1; ys <= interim->size; ys ++)
                {
                    if (FeatureWeights_areFriends (categories->at [yp], interim->at [ys]))
                    {
                        for (long x = 1; x <= p -> nx; x ++)
                        {
                            Melder_assert (ys <= p -> ny);
                            if (alfa == 1)
                            {
                                centroids -> z [yp] [x] = p -> z [ys] [x];
                            }
                            else
                            {
                                centroids -> z [yp] [x] += (p -> z [ys] [x] - centroids -> z [yp] [x]) / alfa;
                            }
                        }
                        Melder_assert (yp <= k);
                        sizes [yp] ++;
                        alfa ++;
                    }
                }

                for (long x = 1; x <= centroids -> nx; x ++)
                {
                    delta += fabs (beta [x] - centroids -> z [yp] [x]);
                }
            }
        }
        while (delta != 0.0);

        double smax = sizes [1];
        double smin = sizes [1];

        for (long x = 1; x <= k; x++)
        {
            if (smax < sizes [x]) smax = sizes [x];
            if (smin > sizes [x]) smin = sizes [x];
        }

        sizes [0] = smin / smax;
        -- m;
    }
    while (sizes[0] < s && m > 0);

    autoCategories output = KNN_classifyToCategories (knn.get(), p, fws, 1, kOla_FLAT_VOTING);

    return output;
}
Пример #13
0
arma::mat SuperPixels::calculateSegmentation(cv::Mat& img_, int nSuperPixels, int display) {
   

    IplImage* img=new IplImage(img_);
	
	int NR_SUPERPIXELS=nSuperPixels;
    if ((!img))
      {
        printf("Error while opening file\n");
        
      }

    int width = img->width;
    int height = img->height;
    int sz = height*width;


    UINT* ubuff = new UINT[sz];
    //UINT* ubuff2 = new UINT[sz];
    //UINT* dbuff = new UINT[sz];
    UINT pValue;
    //UINT pdValue;
    char c;
    UINT r,g,b,d;
    int idx = 0;
    for(int j=0;j<img->height;j++)
      for(int i=0;i<img->width;i++)
        {
          if(img->nChannels == 3)
            {
              // image is assumed to have data in BGR order
              b = ((uchar*)(img->imageData + img->widthStep*(j)))[(i)*img->nChannels];
              g = ((uchar*)(img->imageData + img->widthStep*(j)))[(i)*img->nChannels+1];
              r = ((uchar*)(img->imageData + img->widthStep*(j)))[(i)*img->nChannels+2];
  			if (d < 128) d = 0;
              pValue = b | (g << 8) | (r << 16);
            }
          else if(img->nChannels == 1)
            {
              c = ((uchar*)(img->imageData + img->widthStep*(j)))[(i)*img->nChannels];
              pValue = c | (c << 8) | (c << 16);
            }
          else
            {
              printf("Unknown number of channels %d\n", img->nChannels);
          
            }
          ubuff[idx] = pValue;
          //ubuff2[idx] = pValue;
          idx++;
        }




  /*******************************************
   * SEEDS SUPERPIXELS                       *
   *******************************************/
  int NR_BINS = 5; // Number of bins in each histogram channel

  //printf("Generating SEEDS with %d superpixels\n", NR_SUPERPIXELS);
  SEEDS seeds(width, height, 3, NR_BINS);

  // SEEDS INITIALIZE
  int nr_superpixels = NR_SUPERPIXELS;

  // NOTE: the following values are defined for images from the BSD300 or BSD500 data set.
  // If the input image size differs from 480x320, the following values might no longer be
  // accurate.
  // For more info on how to select the superpixel sizes, please refer to README.TXT.
  int seed_width = 3; int seed_height = 4; int nr_levels = 4;
  if (width >= height)
  {
  	if (nr_superpixels == 600) {seed_width = 2; seed_height = 2; nr_levels = 4;}
  	if (nr_superpixels == 400) {seed_width = 3; seed_height = 2; nr_levels = 4;}
  	if (nr_superpixels == 266) {seed_width = 3; seed_height = 3; nr_levels = 4;}
  	if (nr_superpixels == 200) {seed_width = 3; seed_height = 4; nr_levels = 4;}
  	if (nr_superpixels == 150) {seed_width = 2; seed_height = 2; nr_levels = 5;}
  	if (nr_superpixels == 100) {seed_width = 3; seed_height = 2; nr_levels = 5;}
  	if (nr_superpixels == 50)  {seed_width = 3; seed_height = 4; nr_levels = 5;}
  	if (nr_superpixels == 25)  {seed_width = 3; seed_height = 2; nr_levels = 6;}
  	if (nr_superpixels == 17)  {seed_width = 3; seed_height = 3; nr_levels = 6;}
  	if (nr_superpixels == 12)  {seed_width = 3; seed_height = 4; nr_levels = 6;}
  	if (nr_superpixels == 9)  {seed_width = 2; seed_height = 2; nr_levels = 7;}
  	if (nr_superpixels == 6)  {seed_width = 3; seed_height = 2; nr_levels = 7;}
  }
  else
  {
  	if (nr_superpixels == 600) {seed_width = 2; seed_height = 2; nr_levels = 4;}
  	if (nr_superpixels == 400) {seed_width = 2; seed_height = 3; nr_levels = 4;}
  	if (nr_superpixels == 266) {seed_width = 3; seed_height = 3; nr_levels = 4;}
  	if (nr_superpixels == 200) {seed_width = 4; seed_height = 3; nr_levels = 4;}
  	if (nr_superpixels == 150) {seed_width = 2; seed_height = 2; nr_levels = 5;}
  	if (nr_superpixels == 100) {seed_width = 2; seed_height = 3; nr_levels = 5;}
  	if (nr_superpixels == 50)  {seed_width = 4; seed_height = 3; nr_levels = 5;}
  	if (nr_superpixels == 25)  {seed_width = 2; seed_height = 3; nr_levels = 6;}
  	if (nr_superpixels == 17)  {seed_width = 3; seed_height = 3; nr_levels = 6;}
  	if (nr_superpixels == 12)  {seed_width = 4; seed_height = 3; nr_levels = 6;}
  	if (nr_superpixels == 9)  {seed_width = 2; seed_height = 2; nr_levels = 7;}
  	if (nr_superpixels == 6)  {seed_width = 2; seed_height = 3; nr_levels = 7;}
  }

  seeds.initialize(seed_width, seed_height, nr_levels);



  //clock_t begin = clock();

  seeds.update_image_ycbcr(ubuff);

  seeds.iterate();

    
    
  //clock_t end = clock();
  //double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
  //printf("    elapsed time=%lf sec\n", elapsed_secs);

  //printf("SEEDS produced %d labels\n", seeds.count_superpixels());
  
//  seeds.DrawContoursAroundSegments(ubuff, seeds.labels[nr_levels-1], width, height, 0xff0000, false);//0xff0000 draws red contours

    //     delete[] ubuff;
    //     delete[] output_buff;
 
  //std::string imageFileName = "./test_labels.png";
  //printf("Saving image %s\n",imageFileName.c_str());
  //seeds.SaveImage(ubuff, width, height,imageFileName.c_str());

  // DRAW SEEDS OUTPUT
    

  
//    arma::mat Label(img_.cols,img_.rows,arma::fill::zeros);
    
    arma::mat Label(img_.cols,img_.rows,arma::fill::zeros);
    for (int x=0; x<img_.cols;x++) {
        
        for (int y=0; y<img_.rows; y++) {
            //std::cout<<labels[y*image.cols+x]<<std::endl;//[y * width + x]
            Label(x,y)=seeds.get_labels()[y*img_.cols+x];
        }
        
    }
    
    if (display!=0) {
            seeds.DrawContoursAroundSegments(ubuff, seeds.labels[nr_levels-1], width, height, 0xff0000, false);//0xff0000 draws red contours
        cv::Mat c(img_.rows,img_.cols,CV_8U);
        
        for (int x=0; x<img_.cols; x++) {
            for (int y=0; y<img_.rows; y++) {
                c.at<uchar>(y,x)=ubuff[y*img_.cols+x];
            }
        }
        
        this->canvas=c;
    }
    
    


    
    
    
    delete img;
    delete[] ubuff;
    
    seeds.deinitialize();
    
   
    return Label;
    
  	// sz = 3*width*height;
  	//
  	//     UINT* output_buff = new UINT[sz];
  	//     for (int i = 0; i<sz; i++) output_buff[i] = 0;
  	//
  	//
  	//     //printf("Draw Contours Around Segments\n");
  	//     DrawContoursAroundSegments(ubuff, seeds.labels[nr_levels-1], width, height, 0xff0000, false);//0xff0000 draws red contours
  	//     DrawContoursAroundSegments(output_buff, seeds.labels[nr_levels-1], width, height, 0xffffff, true);//0xff0000 draws white contours
  	//
  	//    	std::string imageFileName="";
  	//     imageFileName = "./test_labels.png";
  	//     //printf("Saving image %s\n",imageFileName.c_str());
  	//     SaveImage(ubuff, width, height,
  	//               imageFileName.c_str());
  	//
  	//        imageFileName = "./test_boundary.png";
  	//     //printf("Saving image %s\n",imageFileName.c_str());
  	//     SaveImage(output_buff, width, height,
  	//               imageFileName.c_str());
  	//
  	//
  	//     std::string labelFileNameTxt = "./test_.seg";
  	//     seeds.SaveLabels_Text(labelFileNameTxt);
  	//
  	//
  	//

}
Пример #14
0
void sc_plugin_interface::initialize(server_arguments const & args, float * control_busses)
{
    done_nodes.reserve(64);
    pause_nodes.reserve(16);
    resume_nodes.reserve(16);
    freeAll_nodes.reserve(16);
    freeDeep_nodes.reserve(16);

    /* define functions */
    sc_interface.fDefineUnit = &define_unit;
    sc_interface.fDefineBufGen = &define_bufgen;
    sc_interface.fDefinePlugInCmd = &define_plugincmd;
    sc_interface.fDefineUnitCmd = &define_unitcmd;

    /* interface functions */
    sc_interface.fNodeEnd = &node_end;
    sc_interface.fGetNode = &get_node;
    sc_interface.fNodeRun = &node_set_run;
    sc_interface.fPrint = &print;
    sc_interface.fDoneAction = &done_action;

    /* sndfile functions */
#ifdef NO_LIBSNDFILE
    sc_interface.fSndFileFormatInfoFromStrings = NULL;
#else
    sc_interface.fSndFileFormatInfoFromStrings = &sndfileFormatInfoFromStrings;
#endif

    /* wave tables */
    sc_interface.mSine = gSine;
    sc_interface.mCosecant = gInvSine;
    sc_interface.mSineSize = kSineSize;
    sc_interface.mSineWavetable = gSineWavetable;

    /* memory allocation */
    sc_interface.fRTAlloc = &rt_alloc;
    sc_interface.fRTRealloc = &rt_realloc;
    sc_interface.fRTFree = &rt_free;

    sc_interface.fNRTAlloc = &nrt_alloc;
    sc_interface.fNRTRealloc = &nrt_realloc;
    sc_interface.fNRTFree = &nrt_free;

    /* ugen functions */
    sc_interface.fClearUnitOutputs = clear_outputs;

    /* buffer functions */
    sc_interface.fBufAlloc = &buf_alloc;

    /* trigger functions */
    sc_interface.fSendTrigger = &send_trigger;
    sc_interface.fSendNodeReply = &send_node_reply;

    /* world locks */
    sc_interface.fNRTLock = &world_lock;
    sc_interface.fNRTUnlock = &world_unlock;
    world.mNRTLock = new SC_Lock();

    /* fft library */
    sc_interface.fSCfftCreate = &scfft_create;
    sc_interface.fSCfftDestroy = &scfft_destroy;
    sc_interface.fSCfftDoFFT = &scfft_dofft;
    sc_interface.fSCfftDoIFFT = &scfft_doifft;

    /* scope API */
    sc_interface.fGetScopeBuffer = &get_scope_buffer;
    sc_interface.fPushScopeBuffer = &push_scope_buffer;
    sc_interface.fReleaseScopeBuffer = &release_scope_buffer;

    /* osc plugins */
    sc_interface.fDoAsynchronousCommand = &do_asynchronous_command;

    /* initialize world */
    /* control busses */
    world.mControlBus = control_busses;
    world.mNumControlBusChannels = args.control_busses;
    world.mControlBusTouched = new int32[args.control_busses];
    std::fill(world.mControlBusTouched, world.mControlBusTouched + args.control_busses, -1);

    /* audio busses */
    audio_busses.initialize(args.audio_busses, args.blocksize);

    world.mAudioBus = audio_busses.buffers;
    world.mNumAudioBusChannels = args.audio_busses;
    world.mAudioBusTouched = new int32[args.audio_busses];
    world.mAudioBusLocks = audio_busses.locks;
    world.mControlBusLock = new spin_lock();
    std::fill(world.mAudioBusTouched, world.mAudioBusTouched + args.audio_busses, -1);

    /* audio buffers */
    world.mNumSndBufs = args.buffers;
    world.mSndBufs = new SndBuf[world.mNumSndBufs];
    world.mSndBufsNonRealTimeMirror = new SndBuf[world.mNumSndBufs];
    world.mSndBufUpdates = new SndBufUpdates[world.mNumSndBufs];
    memset(world.mSndBufs, 0, world.mNumSndBufs*sizeof(SndBuf));
    memset(world.mSndBufsNonRealTimeMirror, 0, world.mNumSndBufs*sizeof(SndBuf));
    memset(world.mSndBufUpdates, 0, world.mNumSndBufs*sizeof(SndBufUpdates));
    world.mBufCounter = 0;

    async_buffer_guards.reset(new std::mutex[world.mNumSndBufs]);

    /* audio settings */
    world.mBufLength = args.blocksize;
    world.mSampleRate = args.samplerate;

    initialize_rate(world.mFullRate, args.samplerate, args.blocksize);
    initialize_rate(world.mBufRate, double(args.samplerate)/args.blocksize, 1);

    world.mNumInputs = args.input_channels;
    world.mNumOutputs = args.output_channels;

    world.mRealTime = !args.non_rt;

    /* rngs */
    world.mNumRGens = args.rng_count;
    world.mRGen = new RGen[world.mNumRGens];
    std::vector<std::uint32_t> seeds(world.mNumRGens);

    try {
        std::random_device rd;
        std::seed_seq seq({ rd(), rd(), rd() });
        seq.generate(seeds.begin(), seeds.end());
    } catch (...) {
        auto now = std::chrono::high_resolution_clock::now();

        auto seconds = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch());

        std::seed_seq seq({ seconds.count() });
        seq.generate(seeds.begin(), seeds.end());
    }

    for (int i=0; i<world.mNumRGens; ++i)
        world.mRGen[i].init(seeds[i]);
}
Пример #15
0
double perfectMRF2(int *delta,int Q,int G,
		   const vector<vector<int> > &neighbour,
		   const vector<double> &potOn,
		   const vector<double> &potOff,
		   double alpha,double beta,
		   double betag,unsigned int *seed,int draw) {
  unsigned int finalStart = *seed;

  if (draw == 1) {
    vector<int> start(1,-1);
    vector<unsigned int> seeds(1,finalStart);

    unsigned int nextSeed;
    int finished = 0;
    while (finished == 0) {
      vector<int> valueLower(Q * G,0);
      vector<int> valueUpper(Q * G,1);

      int b;
      for (b = start.size() - 1; b >= 0; b--) {
	int first = start[b];
	int last;
	if (b > 0)
	  last = start[b-1];
	else
	  last = 0;

	Random ran(seeds[b]);
	int k;
	for (k = first; k < last; k++) {
	  int q,g;
	  for (q = 0; q < Q; q++)
	    for (g = 0; g < G; g++)
	      updateMRF2perfect(q,g,Q,G,valueLower,valueUpper,potOn,potOff,
				neighbour,alpha,beta,betag,ran);
	}

	unsigned int dummy = 1;
	if (b == start.size() - 1) nextSeed = ran.ChangeSeed(dummy);
      }

      int nUndef = 0;
      int q,g;
      for (q = 0; q < Q; q++)
	for (g = 0; g < G; g++) {
	  int kqg = qg2index(q,g,Q,G);
	  nUndef += (valueLower[kqg] != valueUpper[kqg]);
	}
      //      cout << "nUndef: " << nUndef << endl;

      if (nUndef == 0) {
	finished = 1;
	finalStart = nextSeed;
      }
      else {
	finished = 0;
	seeds.push_back(nextSeed);
	start.push_back(2*start[start.size() - 1]);
      }

      if (finished == 1) {
	for (q = 0; q < Q; q++)
	  for (g = 0; g < G; g++) {
	    int kqg = qg2index(q,g,Q,G);
	    delta[kqg] = valueLower[kqg];
	  }
      }
    }

    *seed = nextSeed;
  }

  double pot = 0.0;
  int q,g;
  for (q = 0; q < Q; q++)
    for (g = 0; g < G; g++) {
      int kqg = qg2index(q,g,Q,G);
      if (delta[kqg] == 1)
	pot += - alpha + potOn[kqg];
      else
	pot += potOff[kqg];

      int k;
      for (k = 0; k < neighbour[g].size(); k++) {
	int gg = neighbour[g][k];
	int kqgg = qg2index(q,gg,Q,G);
	if (delta[kqg] == delta[kqgg]) {
	  int ng = neighbour[g].size();
	  int ngg = neighbour[gg].size();
	  //	  double w = 0.5 * exp(- kappa * log((double) (ng * ngg)));
	  double w = 1.0 / ((double) ng);

	  pot += - beta * w;
	}
      }
    }

  int qq;
  for (q = 0; q < Q; q++)
    for (qq = q + 1; qq < Q; qq++)
      for (g = 0; g < G; g++) {
	int kqg = qg2index(q,g,Q,G);
	int kqqg = qg2index(qq,g,Q,G);
	if (delta[kqg] == delta[kqqg])
	  pot += - betag / ((double) (Q - 1));
      }

  return pot;
}
TEST(RMDCuTests, seedMatrixInit)
{
  const boost::filesystem::path dataset_path("../test_data");
  const boost::filesystem::path sequence_file_path("../test_data/first_200_frames_traj_over_table_input_sequence.txt");

  rmd::PinholeCamera cam(481.2f, -480.0f, 319.5f, 239.5f);

  rmd::test::Dataset dataset(dataset_path.string(), sequence_file_path.string(), cam);
  if (!dataset.readDataSequence())
    FAIL() << "could not read dataset";

  const size_t ref_ind = 1;
  const size_t curr_ind = 20;

  const auto ref_entry = dataset(ref_ind);
  cv::Mat ref_img;
  dataset.readImage(ref_img, ref_entry);
  cv::Mat ref_img_flt;
  ref_img.convertTo(ref_img_flt, CV_32F, 1.0f/255.0f);

  cv::Mat ref_depthmap;
  dataset.readDepthmap(ref_depthmap, ref_entry, ref_img.cols, ref_img.rows);

  rmd::SE3<float> T_world_ref;
  dataset.readCameraPose(T_world_ref, ref_entry);

  const auto curr_entry = dataset(curr_ind);
  cv::Mat curr_img;
  dataset.readImage(curr_img, curr_entry);
  cv::Mat curr_img_flt;
  curr_img.convertTo(curr_img_flt, CV_32F, 1.0f/255.0f);

  rmd::SE3<float> T_world_curr;
  dataset.readCameraPose(T_world_curr, curr_entry);

  const float min_scene_depth = 0.4f;
  const float max_scene_depth = 1.8f;

  rmd::SeedMatrix seeds(ref_img.cols, ref_img.rows, cam);

  StopWatchInterface * timer = NULL;
  sdkCreateTimer(&timer);
  sdkResetTimer(&timer);
  sdkStartTimer(&timer);

  seeds.setReferenceImage(
        reinterpret_cast<float*>(ref_img_flt.data),
        T_world_ref.inv(),
        min_scene_depth,
        max_scene_depth);

  sdkStopTimer(&timer);
  double t = sdkGetAverageTimerValue(&timer) / 1000.0;
  printf("setReference image CUDA execution time: %f seconds.\n", t);

  cv::Mat initial_depthmap(ref_img.rows, ref_img.cols, CV_32FC1);
  seeds.downloadDepthmap(reinterpret_cast<float*>(initial_depthmap.data));

  cv::Mat initial_sigma_sq(ref_img.rows, ref_img.cols, CV_32FC1);
  seeds.downloadSigmaSq(reinterpret_cast<float*>(initial_sigma_sq.data));

  cv::Mat initial_a(ref_img.rows, ref_img.cols, CV_32FC1);
  seeds.downloadA(reinterpret_cast<float*>(initial_a.data));

  cv::Mat initial_b(ref_img.rows, ref_img.cols, CV_32FC1);
  seeds.downloadB(reinterpret_cast<float*>(initial_b.data));

  const float avg_scene_depth = (min_scene_depth+max_scene_depth)/2.0f;
  const float max_scene_sigma_sq = (max_scene_depth - min_scene_depth) * (max_scene_depth - min_scene_depth) / 36.0f;
  for(size_t r=0; r<ref_img.rows; ++r)
  {
    for(size_t c=0; c<ref_img.cols; ++c)
    {
      ASSERT_FLOAT_EQ(avg_scene_depth, initial_depthmap.at<float>(r, c));
      ASSERT_FLOAT_EQ(max_scene_sigma_sq, initial_sigma_sq.at<float>(r, c));
      ASSERT_FLOAT_EQ(10.0f, initial_a.at<float>(r, c));
      ASSERT_FLOAT_EQ(10.0f, initial_b.at<float>(r, c));
    }
  }

  // Test initialization of NCC template statistics

  // CUDA computation
  cv::Mat cu_sum_templ(ref_img.rows, ref_img.cols, CV_32FC1);
  seeds.downloadSumTempl(reinterpret_cast<float*>(cu_sum_templ.data));
  cv::Mat cu_const_templ_denom(ref_img.rows, ref_img.cols, CV_32FC1);
  seeds.downloadConstTemplDenom(reinterpret_cast<float*>(cu_const_templ_denom.data));

  // Host computation
  cv::Mat ocv_sum_templ(ref_img.rows, ref_img.cols, CV_32FC1);
  cv::Mat ocv_const_templ_denom(ref_img.rows, ref_img.cols, CV_32FC1);

  const int side = seeds.getPatchSide();
  for(size_t y=side; y<ref_img.rows-side/2; ++y)
  {
    for(size_t x=side; x<ref_img.cols-side/2; ++x)
    {
      double sum_templ    = 0.0f;
      double sum_templ_sq = 0.0f;
      for(int patch_y=0; patch_y<side; ++patch_y)
      {
        for(int patch_x=0; patch_x<side; ++patch_x)
        {
          const double templ = (double) ref_img_flt.at<float>( y-side/2+patch_y, x-side/2+patch_x );
          sum_templ += templ;
          sum_templ_sq += templ*templ;
        }
      }
      ocv_sum_templ.at<float>(y, x) = (float) sum_templ;
      ocv_const_templ_denom.at<float>(y, x) = (float) ( ((double)(side*side))*sum_templ_sq - sum_templ*sum_templ );
    }
  }
  for(size_t r=side; r<ref_img.rows-side/2; ++r)
  {
    for(size_t c=side; c<ref_img.cols-side/2; ++c)
    {
      ASSERT_NEAR(ocv_sum_templ.at<float>(r, c), cu_sum_templ.at<float>(r, c), 0.00001f);
      ASSERT_NEAR(ocv_const_templ_denom.at<float>(r, c), cu_const_templ_denom.at<float>(r, c), 0.001f);
    }
  }

}
Пример #17
0
std::vector<unsigned int> Preprocessor::isolateRegions ()
{
	boost::timer timer;
	timer.restart();

	// Traverse the press clip searching the ink pixels where the flooding process will start from
	std::vector<PixelCoordinates> seeds(0);
	seeds.reserve(clip_.size());
	for ( unsigned int i = 0; i < clipHeight_; ++i )
	{
		for ( unsigned int j = 0; j < clipWidth_; ++j )
		{
			if ( clip_.at(i * clipWidth_ + j) == 1 )
				seeds.push_back( PixelCoordinates(i,j) );
		}
	}

	// Build the initial list of regions by applying the flooding algorithm
	regions_.clear();
	std::deque<bool> visited(clip_.size(), false);
	for ( std::vector<PixelCoordinates>::iterator s = seeds.begin(); s != seeds.end(); ++s )
	{
		int row		= s->first;
		int column	= s->second;

		if ( not visited.at(row * clipWidth_ + column) )
		{
			visited.at(row * clipWidth_ + column) = true;

			// This seed begins a new region
			Region region;
			region.addCoordinates( PixelCoordinates(row, column) );

			// Explore the immediate neighbourhood
			for ( int i = row-1; (i <= row+1) && (i < static_cast<int>(clipHeight_)); ++i )
			{
				for ( int j = column-1; (j <= column+1) && (j < static_cast<int>(clipWidth_)); ++j )
				{
					if ( i >= 0 && j >= 0 )
					{
						if ( clip_.at(i * clipWidth_ + j) == 1 && not visited.at(i * clipWidth_ + j) )
						{
							visited.at(i * clipWidth_ + j) = true;
							region.addCoordinates( PixelCoordinates(i,j) );
						}
					}
				}
			}

			// Explore the neighbours of the neighbours
			unsigned int k = 1;
			while ( region.size() > k )
			{
				PixelCoordinates coordinates( region.at(k) );

				for ( int i = coordinates.first-1; (i <= static_cast<int>(coordinates.first+1)) && (i < static_cast<int>(clipHeight_)); ++i )
				{
					for ( int j = coordinates.second-1; (j <= static_cast<int>(coordinates.second+1)) && (j < static_cast<int>(clipWidth_)); ++j )
					{
						if ( i >= 0 && j >= 0 )
						{
							if ( clip_.at(i * clipWidth_ + j) == 1 && not visited.at(i * clipWidth_ + j) )
							{
								visited.at(i * clipWidth_ + j) = true;
								region.addCoordinates( PixelCoordinates(i, j) );
							}
						}
					}
				}
				++k;
			}

			regions_.push_back(region);
		}
	}

	findLineDelimiters(visited);
	organizeRegionsIntoLines();

	mergeVerticallyOverlappedRegions();

	averageCharacterHeight_ = std::accumulate (regions_.begin(), regions_.end(), 0.0, accumulateHeightIncrement()) / regions_.size();
	averageCharacterWidth_ = std::accumulate (regions_.begin(), regions_.end(), 0.0, accumulateWidthIncrement()) / regions_.size();

	for( RegionLines::iterator i = inlineRegions_.begin(); i != inlineRegions_.end(); ++i )
		sortRegions(i->second);

	std::vector<unsigned int> spaceLocations = findSpacesBetweenWords();
	statistics_.nRegions(regions_.size());
	statistics_.nLines(delimiters_.size());
	statistics_.averageCharacterHeight(averageCharacterHeight_);
	statistics_.averageCharacterWidth(averageCharacterWidth_);
	statistics_.segmentationTime(timer.elapsed());

	return spaceLocations;
}
void PointCloudProcessing::pclRegionGrow(const PointCloudC::Ptr scene,
                                         const PointCloudC::Ptr seedsIn,
                                         float growSpeed,
                                         float searchRadius,
                                         float heightThd,
                                         PointCloudC::Ptr &cloudSeg,
                                         std::set<int> &clusterIdx)
{
  PointCloudC::Ptr seeds(new PointCloudC);
  pcl::copyPointCloud(*seedsIn, *seeds);
  int clusterSize = 0;
  std::vector<std::vector<int> > neighIdx;
  std::vector< std::vector<f32> > neighDist;
  std::set<int> newSeedIdx;
  //    std::cout<<"seeds size: "<<seeds->points.size()<<std::endl;
  clusterIdx.clear();
  // seeded region growing
  do
    {
      //        std::cout<<"initial clusterIdx size: "<<clusterIdx.size()<<std::endl;
      clusterSize = clusterIdx.size(); newSeedIdx.clear();
      //        std::cout<<"seeds size: "<<seeds->points.size()<<std::endl;
      getKnnRadius(scene, seeds, searchRadius, neighIdx, neighDist);
      // update cluster elements
      std::vector<std::vector<int> >::iterator seedNeighIdx = neighIdx.begin();
      std::vector<std::vector<float> >::iterator seedNeighDist = neighDist.begin();
      for(int i=0; i<neighIdx.size(); i++, seedNeighIdx++, seedNeighDist++)
        {
          for(int j=0; j<seedNeighIdx->size(); j++)
            {
              clusterIdx.insert((*seedNeighIdx).at(j));
              if((*seedNeighDist).at(j)>growSpeed*searchRadius)
                {  newSeedIdx.insert((*seedNeighIdx).at(j));  }
            }
        }
      // newSeeds for next growing iteration
      PointCloudC::Ptr newSeeds(new PointCloudC); newSeeds->points.clear();
      std::set<int>::iterator newSeedIdxIter = newSeedIdx.begin();
      for(int i=0; i<newSeedIdx.size(); i++, newSeedIdxIter++)
        {
          PointC newSeed = scene->points.at(*newSeedIdxIter);
          if(newSeed.z > heightThd+searchRadius)
            {
              newSeeds->points.push_back(newSeed);
            }
        }
      seeds->points.clear();
      pcl::copyPointCloud(*newSeeds, *seeds);
      //        std::cout<<"newSeeds size: "<<newSeeds->points.size()<<std::endl;
      //        std::cout<<"grown clusterSize: "<<clusterSize<<"\n";
    }while(clusterSize != clusterIdx.size());

  // get segmented point cloud
  cloudSeg.reset(new PointCloudC); cloudSeg->points.clear();
  std::set<int>::iterator clusterIdxIter = clusterIdx.begin();
  for(int i=0; i<clusterIdx.size(); i++, clusterIdxIter++)
    {
      PointC pointSeg = scene->points.at(*clusterIdxIter);
      if(pointSeg.z > heightThd)
        {
          cloudSeg->points.push_back(pointSeg);
        }
    }
  std::cout<<"cloudSeg size: "<<cloudSeg->points.size()<<std::endl;
  cloudSeg->width = 1;
  cloudSeg->height = cloudSeg->points.size();
}
Пример #19
0
double perfectMRF1_onedelta(int *delta,int G,
			    const vector<vector<int> > &neighbour,
			    const vector<double> &potOn,
			    const vector<double> &potOff,
			    double eta0,double omega0,double kappa,
			    unsigned int *seed,int draw) {
  unsigned int finalStart = *seed;

  if (draw == 1) {
    vector<int> start(1,-1);
    vector<unsigned int> seeds(1,finalStart);

    unsigned int nextSeed;
    int finished = 0;
    while (finished == 0) {
      vector<int> valueLower(G,0);
      vector<int> valueUpper(G,1);

      int b;
      for (b = start.size() - 1; b >= 0; b--) {
	int first = start[b];
	int last;
	if (b > 0)
	  last = start[b-1];
	else
	  last = 0;

	Random ran(seeds[b]);
	int k;
	for (k = first; k < last; k++) {
	  int g;
	  for (g = 0; g < G; g++)
	    updateMRF1perfect_onedelta(g,valueLower,valueUpper,potOn,
				       potOff,neighbour,
				       eta0,omega0,kappa,ran);
	}

	unsigned int dummy = 1;
	if (b == start.size() - 1) nextSeed = ran.ChangeSeed(dummy);
      }

      int nUndef = 0;
      int g;
      for (g = 0; g < G; g++)
	nUndef += (valueLower[g] != valueUpper[g]);
      //      cout << "nUndef: " << nUndef << endl;

      if (nUndef == 0) {
	finished = 1;
	finalStart = nextSeed;
      }
      else {
	finished = 0;
	seeds.push_back(nextSeed);
	start.push_back(2*start[start.size() - 1]);
      }

      if (finished == 1) {
	for (g = 0; g < G; g++)
	  delta[g] = valueLower[g];
      }
    }

    *seed = nextSeed;
  }

  double pot = 0.0;
  int g;
  for (g = 0; g < G; g++) {
    if (delta[g] == 1)
      pot += potOn[g];
    else
      pot += potOff[g];

    int n = neighbour[g].size();
    double omega;
    if (n > 0)
      omega = omega0 * ((double) n) / (kappa + ((double) n));
    else
      omega = 0.0;
    int nOn = 0;
    int gg;
    for (gg = 0; gg < neighbour[g].size(); gg++)
      nOn += delta[neighbour[g][gg]];
    double fraction = ((double) nOn) / ((double) neighbour[g].size());
    double eta;
    if (omega > 0)
      eta = (1.0 - omega) * eta0 + omega * fraction;
    else
      eta = eta0;

    if (delta[g] == 1)
      pot += - log(eta);
    else
      pot += - log(1.0 - eta);
  }

  return pot;
}
TEST(RMDCuTests, seedMatrixCheck)
{
  const boost::filesystem::path dataset_path("../test_data");
  const boost::filesystem::path sequence_file_path("../test_data/first_200_frames_traj_over_table_input_sequence.txt");

  rmd::PinholeCamera cam(481.2f, -480.0f, 319.5f, 239.5f);

  rmd::test::Dataset dataset(dataset_path.string(), sequence_file_path.string(), cam);
  if (!dataset.readDataSequence())
    FAIL() << "could not read dataset";

  const size_t ref_ind = 1;
  const size_t curr_ind = 20;

  const auto ref_entry = dataset(ref_ind);
  cv::Mat ref_img;
  dataset.readImage(ref_img, ref_entry);
  cv::Mat ref_img_flt;
  ref_img.convertTo(ref_img_flt, CV_32F, 1.0f/255.0f);

  cv::Mat ref_depthmap;
  dataset.readDepthmap(ref_depthmap, ref_entry, ref_img.cols, ref_img.rows);

  rmd::SE3<float> T_world_ref;
  dataset.readCameraPose(T_world_ref, ref_entry);

  const auto curr_entry = dataset(curr_ind);
  cv::Mat curr_img;
  dataset.readImage(curr_img, curr_entry);
  cv::Mat curr_img_flt;
  curr_img.convertTo(curr_img_flt, CV_32F, 1.0f/255.0f);

  rmd::SE3<float> T_world_curr;
  dataset.readCameraPose(T_world_curr, curr_entry);

  const float min_scene_depth = 0.4f;
  const float max_scene_depth = 1.8f;

  rmd::SeedMatrix seeds(ref_img.cols, ref_img.rows, cam);

  seeds.setReferenceImage(
        reinterpret_cast<float*>(ref_img_flt.data),
        T_world_ref.inv(),
        min_scene_depth,
        max_scene_depth);

  StopWatchInterface * timer = NULL;
  sdkCreateTimer(&timer);
  sdkResetTimer(&timer);
  sdkStartTimer(&timer);

  seeds.update(
        reinterpret_cast<float*>(ref_img_flt.data),
        T_world_curr.inv());

  sdkStopTimer(&timer);
  double t = sdkGetAverageTimerValue(&timer) / 1000.0;
  printf("update CUDA execution time: %f seconds.\n", t);

  cv::Mat cu_convergence(ref_img.rows, ref_img.cols, CV_32SC1);
  seeds.downloadConvergence(reinterpret_cast<int*>(cu_convergence.data));

  const int side = seeds.getPatchSide();
  for(size_t r=0; r<ref_img.rows; ++r)
  {
    for(size_t c=0; c<ref_img.cols; ++c)
    {
      if(r>ref_img.rows-side-1
         || r<side
         || c>ref_img.cols-side-1
         || c<side)
      {
        ASSERT_EQ(rmd::ConvergenceStates::BORDER, cu_convergence.at<int>(r, c)) << "(r, c) = (" << r << ", " << c <<")";
      }
      else
      {
        const int result = cu_convergence.at<int>(r, c);
        const bool success = (result == rmd::ConvergenceStates::UPDATE      ||
                              result == rmd::ConvergenceStates::DIVERGED    ||
                              result == rmd::ConvergenceStates::CONVERGED   ||
                              result == rmd::ConvergenceStates::NOT_VISIBLE ||
                              result == rmd::ConvergenceStates::NO_MATCH    );
        ASSERT_EQ(true, success) << "(r, c) = (" << r << ", " << c <<")";
      }
    }
  }

}
Пример #21
0
int main(int argc, char *argv[])
{
    int ii;
    int ret_val;
    double x_orig, y_orig;
    static int rand1 = 12345;
    static int rand2 = 67891;
    struct GModule *module;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("hydrology"));
    module->description =
	_("Overland flow hydrologic simulation using "
	  "path sampling method (SIMWE).");

    parm.elevin = G_define_standard_option(G_OPT_R_ELEV);
    
    parm.dxin = G_define_standard_option(G_OPT_R_INPUT);
    parm.dxin->key = "dx";
    parm.dxin->description = _("Name of x-derivatives raster map [m/m]");

    parm.dyin = G_define_standard_option(G_OPT_R_INPUT);
    parm.dyin->key = "dy";
    parm.dyin->description = _("Name of y-derivatives raster map [m/m]");

    parm.rain = G_define_standard_option(G_OPT_R_INPUT);
    parm.rain->key = "rain";
    parm.rain->required = NO;
    parm.rain->description =
	_("Name of rainfall excess rate (rain-infilt) raster map [mm/hr]");
    parm.rain->guisection = _("Input");
    
    parm.rainval = G_define_option();
    parm.rainval->key = "rain_value";
    parm.rainval->type = TYPE_DOUBLE;
    parm.rainval->answer = RAINVAL;
    parm.rainval->required = NO;
    parm.rainval->description =
	_("Rainfall excess rate unique value [mm/hr]");
    parm.rainval->guisection = _("Input");

    parm.infil = G_define_standard_option(G_OPT_R_INPUT);
    parm.infil->key = "infil";
    parm.infil->required = NO;
    parm.infil->description =
	_("Name of runoff infiltration rate raster map [mm/hr]");
    parm.infil->guisection = _("Input");

    parm.infilval = G_define_option();
    parm.infilval->key = "infil_value";
    parm.infilval->type = TYPE_DOUBLE;
    parm.infilval->answer = INFILVAL;
    parm.infilval->required = NO;
    parm.infilval->description =
	_("Runoff infiltration rate unique value [mm/hr]");
    parm.infilval->guisection = _("Input");

    parm.manin = G_define_standard_option(G_OPT_R_INPUT);
    parm.manin->key = "man";
    parm.manin->required = NO;
    parm.manin->description = _("Name of mannings n raster map");
    parm.manin->guisection = _("Input");

    parm.maninval = G_define_option();
    parm.maninval->key = "man_value";
    parm.maninval->type = TYPE_DOUBLE;
    parm.maninval->answer = MANINVAL;
    parm.maninval->required = NO;
    parm.maninval->description = _("Mannings n unique value");
    parm.maninval->guisection = _("Input");

    parm.traps = G_define_standard_option(G_OPT_R_INPUT);
    parm.traps->key = "traps";
    parm.traps->required = NO;
    parm.traps->description =
	_("Name of flow controls raster map (permeability ratio 0-1)");
    parm.traps->guisection = _("Input");

    parm.observation = G_define_standard_option(G_OPT_V_INPUT);
    parm.observation->key = "observation";
    parm.observation->required = NO;
    parm.observation->description =
	_("Name of the sampling locations vector points map");
    parm.observation->guisection = _("Input_options");

    parm.logfile = G_define_standard_option(G_OPT_F_OUTPUT);
    parm.logfile->key = "logfile";
    parm.logfile->required = NO;
    parm.logfile->description =
	_("Name of the sampling points output text file. For each observation vector point the time series of water depth is stored.");
    parm.logfile->guisection = _("Output");

    parm.depth = G_define_standard_option(G_OPT_R_OUTPUT);
    parm.depth->key = "depth";
    parm.depth->required = NO;
    parm.depth->description = _("Name for output water depth raster map [m]");
    parm.depth->guisection = _("Output");

    parm.disch = G_define_standard_option(G_OPT_R_OUTPUT);
    parm.disch->key = "disch";
    parm.disch->required = NO;
    parm.disch->description = _("Name for output water discharge raster map [m3/s]");
    parm.disch->guisection = _("Output");

    parm.err = G_define_standard_option(G_OPT_R_OUTPUT);
    parm.err->key = "err";
    parm.err->required = NO;
    parm.err->description = _("Name for output simulation error raster map [m]");
    parm.err->guisection = _("Output");

    parm.outwalk = G_define_standard_option(G_OPT_V_OUTPUT);
    parm.outwalk->key = "outwalk";
    parm.outwalk->required = NO;
    parm.outwalk->description =
	_("Base name of the output walkers vector points map");
    parm.outwalk->guisection = _("Output_options");

    parm.nwalk = G_define_option();
    parm.nwalk->key = "nwalk";
    parm.nwalk->type = TYPE_INTEGER;
    parm.nwalk->required = NO;
    parm.nwalk->description =
	_("Number of walkers, default is twice the no. of cells");
    parm.nwalk->guisection = _("Parameters");

    parm.niter = G_define_option();
    parm.niter->key = "niter";
    parm.niter->type = TYPE_INTEGER;
    parm.niter->answer = NITER;
    parm.niter->required = NO;
    parm.niter->description = _("Time used for iterations [minutes]");
    parm.niter->guisection = _("Parameters");

    parm.outiter = G_define_option();
    parm.outiter->key = "outiter";
    parm.outiter->type = TYPE_INTEGER;
    parm.outiter->answer = ITEROUT;
    parm.outiter->required = NO;
    parm.outiter->description =
	_("Time interval for creating output maps [minutes]");
    parm.outiter->guisection = _("Parameters");

/*
    parm.density = G_define_option();
    parm.density->key = "density";
    parm.density->type = TYPE_INTEGER;
    parm.density->answer = DENSITY;
    parm.density->required = NO;
    parm.density->description = _("Density of output walkers");
    parm.density->guisection = _("Parameters");
*/

    parm.diffc = G_define_option();
    parm.diffc->key = "diffc";
    parm.diffc->type = TYPE_DOUBLE;
    parm.diffc->answer = DIFFC;
    parm.diffc->required = NO;
    parm.diffc->description = _("Water diffusion constant");
    parm.diffc->guisection = _("Parameters");

    parm.hmax = G_define_option();
    parm.hmax->key = "hmax";
    parm.hmax->type = TYPE_DOUBLE;
    parm.hmax->answer = HMAX;
    parm.hmax->required = NO;
    parm.hmax->label =
	_("Threshold water depth [m]");
    parm.hmax->description = _("Diffusion increases after this water depth is reached");
    parm.hmax->guisection = _("Parameters");

    parm.halpha = G_define_option();
    parm.halpha->key = "halpha";
    parm.halpha->type = TYPE_DOUBLE;
    parm.halpha->answer = HALPHA;
    parm.halpha->required = NO;
    parm.halpha->description = _("Diffusion increase constant");
    parm.halpha->guisection = _("Parameters");

    parm.hbeta = G_define_option();
    parm.hbeta->key = "hbeta";
    parm.hbeta->type = TYPE_DOUBLE;
    parm.hbeta->answer = HBETA;
    parm.hbeta->required = NO;
    parm.hbeta->description =
	_("Weighting factor for water flow velocity vector");
    parm.hbeta->guisection = _("Parameters");

    flag.tserie = G_define_flag();
    flag.tserie->key = 't';
    flag.tserie->description = _("Time-series output");

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    G_get_set_window(&cellhd);

    conv = G_database_units_to_meters_factor();

    mixx = conv * cellhd.west;
    maxx = conv * cellhd.east;
    miyy = conv * cellhd.south;
    mayy = conv * cellhd.north;

    stepx = cellhd.ew_res * conv;
    stepy = cellhd.ns_res * conv;
    /*  step = amin1(stepx,stepy); */
    step = (stepx + stepy) / 2.;
    mx = cellhd.cols;
    my = cellhd.rows;
    x_orig = cellhd.west * conv;
    y_orig = cellhd.south * conv;	/* do we need this? */
    xmin = 0.;
    ymin = 0.;
    xp0 = xmin + stepx / 2.;
    yp0 = ymin + stepy / 2.;
    xmax = xmin + stepx * (float)mx;
    ymax = ymin + stepy * (float)my;

    ts = flag.tserie->answer;

    elevin = parm.elevin->answer;
    dxin = parm.dxin->answer;
    dyin = parm.dyin->answer;
    rain = parm.rain->answer;
    infil = parm.infil->answer;
    traps = parm.traps->answer;
    manin = parm.manin->answer;
    depth = parm.depth->answer;
    disch = parm.disch->answer;
    err = parm.err->answer;
    outwalk = parm.outwalk->answer; 

    sscanf(parm.niter->answer, "%d", &timesec);
    sscanf(parm.outiter->answer, "%d", &iterout);
    sscanf(parm.diffc->answer, "%lf", &frac);
    sscanf(parm.hmax->answer, "%lf", &hhmax);
    sscanf(parm.halpha->answer, "%lf", &halpha);
    sscanf(parm.hbeta->answer, "%lf", &hbeta);

    /* if no rain map input, then: */
    if (parm.rain->answer == NULL) {
	/*Check for Rain Unique Value Input */
	/* if no rain unique value input */
	if (parm.rainval->answer == NULL) {
	    /*No rain input so use default */
	    sscanf(RAINVAL, "%lf", &rain_val);
	    /* if rain unique input exist, load it */
	}
	else {
	    /*Unique value input only */
	    sscanf(parm.rainval->answer, "%lf", &rain_val);
	}
	/* if Rain map exists */
    }
    else {
	/*Map input, so set rain_val to -999.99 */
	if (parm.rainval->answer == NULL) {
	    rain_val = -999.99;
	}
	else {
	    /*both map and unique value exist */
	    /*Choose the map, discard the unique value */
	    rain_val = -999.99;
	}
    }
    /* Report the final value of rain_val */
    G_debug(3, "rain_val is set to: %f\n", rain_val);

    /* if no Mannings map, then: */
    if (parm.manin->answer == NULL) {
	/*Check for Manin Unique Value Input */
	/* if no Mannings unique value input */
	if (parm.maninval->answer == NULL) {
	    /*No Mannings input so use default */
	    sscanf(MANINVAL, "%lf", &manin_val);
	    /* if mannings unique input value exists, load it */
	}
	else {
	    /*Unique value input only */
	    sscanf(parm.maninval->answer, "%lf", &manin_val);
	}
	/* if Mannings map exists */
    }
    else {
	/* Map input, set manin_val to -999.99 */
	if (parm.maninval->answer == NULL) {
	    manin_val = -999.99;
	}
	else {
	    /*both map and unique value exist */
	    /*Choose map, discard the unique value */
	    manin_val = -999.99;
	}
    }
    /* Report the final value of manin_val */
    G_debug(1, "manin_val is set to: %f\n", manin_val);

    /* if no infiltration map, then: */
    if (parm.infil->answer == NULL) {
	/*Check for Infil Unique Value Input */
	/*if no infiltration unique value input */
	if (parm.infilval->answer == NULL) {
	    /*No infiltration unique value so use default */
	    sscanf(INFILVAL, "%lf", &infil_val);
	    /* if infiltration unique value exists, load it */
	}
	else {
	    /*unique value input only */
	    sscanf(parm.infilval->answer, "%lf", &infil_val);
	}
	/* if infiltration map exists */
    }
    else {
	/* Map input, set infil_val to -999.99 */
	if (parm.infilval->answer == NULL) {
	    infil_val = -999.99;
	}
	else {
	    /*both map and unique value exist */
	    /*Choose map, discard the unique value */
	    infil_val = -999.99;
	}
    }
    /* Report the final value of infil_val */
    G_debug(1, "infil_val is set to: %f\n", infil_val);

    /* Recompute timesec from user input in minutes
     * to real timesec in seconds */
    timesec = timesec * 60.0;
    iterout = iterout * 60.0;
    if ((timesec / iterout) > 100.0)
	G_message(_("More than 100 files are going to be created !!!!!"));

    /* compute how big the raster is and set this to appr 2 walkers per cell */
    if (parm.nwalk->answer == NULL) {
	maxwa = mx * my * 2;
	rwalk = (double)(mx * my * 2.);
	G_message(_("default nwalk=%d, rwalk=%f"), maxwa, rwalk);
    }
    else {
	sscanf(parm.nwalk->answer, "%d", &maxwa);
	rwalk = (double)maxwa;
    }

    /*      rwalk = (double) maxwa; */

    if (conv != 1.0)
	G_message(_("Using metric conversion factor %f, step=%f"), conv,
		  step);

 if ((depth == NULL) && (disch == NULL) && (err == NULL))
        G_warning(_("You are not outputting any raster maps"));
    ret_val = input_data();
    if (ret_val != 1)
        G_fatal_error(_("Input failed"));


    /* memory allocation for output grids */
    G_debug(1, "beginning memory allocation for output grids");

    gama = G_alloc_matrix(my, mx);
    if (err != NULL)
	gammas = G_alloc_matrix(my, mx);
    dif = G_alloc_fmatrix(my, mx);

    G_debug(1, "seeding randoms");
    seeds(rand1, rand2);
    grad_check();
    main_loop();

    if (ts == 0) {
	ii = output_data(0, 1.);
	if (ii != 1)
	    G_fatal_error(_("Cannot write raster maps"));
    }

    /* Exit with Success */
    exit(EXIT_SUCCESS);
}
Пример #22
0
Файл: main.c Проект: caomw/grass
int main(int argc, char *argv[])
{
    int ii;
    int ret_val;
    double x_orig, y_orig;
    static int rand1 = 12345;
    static int rand2 = 67891;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("hydrology"));
    G_add_keyword(_("sediment flow"));
    G_add_keyword(_("erosion"));
    G_add_keyword(_("deposition"));
    module->description =
	_("Sediment transport and erosion/deposition simulation "
	  "using path sampling method (SIMWE).");

    parm.elevin = G_define_standard_option(G_OPT_R_ELEV);
    
    parm.wdepth = G_define_standard_option(G_OPT_R_INPUT);
    parm.wdepth->key = "wdepth";
    parm.wdepth->description = _("Name of water depth raster map [m]");

    parm.dxin = G_define_standard_option(G_OPT_R_INPUT);
    parm.dxin->key = "dx";
    parm.dxin->description = _("Name of x-derivatives raster map [m/m]");

    parm.dyin = G_define_standard_option(G_OPT_R_INPUT);
    parm.dyin->key = "dy";
    parm.dyin->description = _("Name of y-derivatives raster map [m/m]");
    
    parm.detin = G_define_standard_option(G_OPT_R_INPUT);
    parm.detin->key = "det";
    parm.detin->description =
	_("Name of detachment capacity coefficient raster map [s/m]");

    parm.tranin = G_define_standard_option(G_OPT_R_INPUT);
    parm.tranin->key = "tran";
    parm.tranin->description =
	_("Name of transport capacity coefficient raster map [s]");
    
    parm.tauin = G_define_standard_option(G_OPT_R_INPUT);
    parm.tauin->key = "tau";
    parm.tauin->description =
	_("Name of critical shear stress raster map [Pa]");

    parm.manin = G_define_standard_option(G_OPT_R_INPUT);
    parm.manin->key = "man";
    parm.manin->required = NO;
    parm.manin->description = _("Name of Manning's n raster map");
    parm.manin->guisection = _("Input");

    parm.maninval = G_define_option();
    parm.maninval->key = "man_value";
    parm.maninval->type = TYPE_DOUBLE;
    parm.maninval->answer = MANINVAL;
    parm.maninval->required = NO;
    parm.maninval->description = _("Manning's n unique value");
    parm.maninval->guisection = _("Input");

    parm.outwalk = G_define_standard_option(G_OPT_V_OUTPUT);
    parm.outwalk->key = "outwalk";
    parm.outwalk->required = NO;
    parm.outwalk->description =
	_("Base name of the output walkers vector points map");
    parm.outwalk->guisection = _("Output options");
    
    parm.observation = G_define_standard_option(G_OPT_V_INPUT);
    parm.observation->key = "observation";
    parm.observation->required = NO;
    parm.observation->description =
	_("Name of sampling locations vector points map");
    parm.observation->guisection = _("Input options");

    parm.logfile = G_define_standard_option(G_OPT_F_OUTPUT);
    parm.logfile->key = "logfile";
    parm.logfile->required = NO;
    parm.logfile->description =
	_("Name for sampling points output text file. For each observation vector point the time series of sediment transport is stored.");
    parm.logfile->guisection = _("Output");

    parm.tc = G_define_standard_option(G_OPT_R_OUTPUT);
    parm.tc->key = "tc";
    parm.tc->required = NO;
    parm.tc->description = _("Name for output transport capacity raster map [kg/ms]");
    parm.tc->guisection = _("Output");

    parm.et = G_define_standard_option(G_OPT_R_OUTPUT);
    parm.et->key = "et";
    parm.et->required = NO;
    parm.et->description =
	_("Name for output transport limited erosion-deposition raster map [kg/m2s]");
    parm.et->guisection = _("Output");

    parm.conc = G_define_standard_option(G_OPT_R_OUTPUT);
    parm.conc->key = "conc";
    parm.conc->required = NO;
    parm.conc->description =
	_("Name for output sediment concentration raster map [particle/m3]");
    parm.conc->guisection = _("Output");

    parm.flux = G_define_standard_option(G_OPT_R_OUTPUT);
    parm.flux->key = "flux";
    parm.flux->required = NO;
    parm.flux->description = _("Name for output sediment flux raster map [kg/ms]");
    parm.flux->guisection = _("Output");

    parm.erdep = G_define_standard_option(G_OPT_R_OUTPUT);
    parm.erdep->key = "erdep";
    parm.erdep->required = NO;
    parm.erdep->description =
	_("Name for output erosion-deposition raster map [kg/m2s]");
    parm.erdep->guisection = _("Output");

    parm.nwalk = G_define_option();
    parm.nwalk->key = "nwalk";
    parm.nwalk->type = TYPE_INTEGER;
    parm.nwalk->required = NO;
    parm.nwalk->description = _("Number of walkers");
    parm.nwalk->guisection = _("Parameters");

    parm.niter = G_define_option();
    parm.niter->key = "niter";
    parm.niter->type = TYPE_INTEGER;
    parm.niter->answer = NITER;
    parm.niter->required = NO;
    parm.niter->description = _("Time used for iterations [minutes]");
    parm.niter->guisection = _("Parameters");

    parm.outiter = G_define_option();
    parm.outiter->key = "outiter";
    parm.outiter->type = TYPE_INTEGER;
    parm.outiter->answer = ITEROUT;
    parm.outiter->required = NO;
    parm.outiter->description =
	_("Time interval for creating output maps [minutes]");
    parm.outiter->guisection = _("Parameters");

/*
    parm.density = G_define_option();
    parm.density->key = "density";
    parm.density->type = TYPE_INTEGER;
    parm.density->answer = DENSITY;
    parm.density->required = NO;
    parm.density->description = _("Density of output walkers");
    parm.density->guisection = _("Parameters");
*/

    parm.diffc = G_define_option();
    parm.diffc->key = "diffc";
    parm.diffc->type = TYPE_DOUBLE;
    parm.diffc->answer = DIFFC;
    parm.diffc->required = NO;
    parm.diffc->description = _("Water diffusion constant");
    parm.diffc->guisection = _("Parameters");

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    G_get_set_window(&cellhd);

    conv = G_database_units_to_meters_factor();

    mixx = cellhd.west * conv;
    maxx = cellhd.east * conv;
    miyy = cellhd.south * conv;
    mayy = cellhd.north * conv;

    stepx = cellhd.ew_res * conv;
    stepy = cellhd.ns_res * conv;
    /*  step = amin1(stepx,stepy); */
    step = (stepx + stepy) / 2.;
    mx = cellhd.cols;
    my = cellhd.rows;
    x_orig = cellhd.west * conv;
    y_orig = cellhd.south * conv;	/* do we need this? */
    xmin = 0.;
    ymin = 0.;
    xp0 = xmin + stepx / 2.;
    yp0 = ymin + stepy / 2.;
    xmax = xmin + stepx * (float)mx;
    ymax = ymin + stepy * (float)my;
    hhc = hhmax = 0.;

#if 0
    bxmi = 2093113. * conv;
    bymi = 731331. * conv;
    bxma = 2093461. * conv;
    byma = 731529. * conv;
    bresx = 2. * conv;
    bresy = 2. * conv;
    maxwab = 100000;

    mx2o = (int)((bxma - bxmi) / bresx);
    my2o = (int)((byma - bymi) / bresy);

    /* relative small box coordinates: leave 1 grid layer for overlap */

    bxmi = bxmi - mixx + stepx;
    bymi = bymi - miyy + stepy;
    bxma = bxma - mixx - stepx;
    byma = byma - miyy - stepy;
    mx2 = mx2o - 2 * ((int)(stepx / bresx));
    my2 = my2o - 2 * ((int)(stepy / bresy));
#endif

    elevin = parm.elevin->answer;
    wdepth = parm.wdepth->answer;
    dxin = parm.dxin->answer;
    dyin = parm.dyin->answer;
    detin = parm.detin->answer;
    tranin = parm.tranin->answer;
    tauin = parm.tauin->answer;
    manin = parm.manin->answer;
    tc = parm.tc->answer;
    et = parm.et->answer;
    conc = parm.conc->answer;
    flux = parm.flux->answer;
    erdep = parm.erdep->answer;
    outwalk = parm.outwalk->answer; 

    /*      sscanf(parm.nwalk->answer, "%d", &maxwa); */
    sscanf(parm.niter->answer, "%d", &timesec);
    sscanf(parm.outiter->answer, "%d", &iterout);
/*    sscanf(parm.density->answer, "%d", &ldemo); */
    sscanf(parm.diffc->answer, "%lf", &frac);
    sscanf(parm.maninval->answer, "%lf", &manin_val);

    /* Recompute timesec from user input in minutes
     * to real timesec in seconds */
    timesec = timesec * 60.0;
    iterout = iterout * 60.0;
    if ((timesec / iterout) > 100.0)
	G_message(_("More than 100 files are going to be created !!!!!"));

    /* compute how big the raster is and set this to appr 2 walkers per cell */
    if (parm.nwalk->answer == NULL) {
	maxwa = mx * my * 2;
	rwalk = (double)(mx * my * 2.);
	G_message(_("default nwalk=%d, rwalk=%f"), maxwa, rwalk);
    }
    else {
	sscanf(parm.nwalk->answer, "%d", &maxwa);
	rwalk = (double)maxwa;
    }
    /*rwalk = (double) maxwa; */

    if (conv != 1.0)
	G_message(_("Using metric conversion factor %f, step=%f"), conv,
		  step);


    if ((tc == NULL) && (et == NULL) && (conc == NULL) && (flux == NULL) &&
	(erdep == NULL))
	G_warning(_("You are not outputting any raster or site files"));
    ret_val = input_data();
    if (ret_val != 1)
	G_fatal_error(_("Input failed"));

    /* mandatory for si,sigma */

    si = G_alloc_matrix(my, mx);
    sigma = G_alloc_matrix(my, mx);

    /* memory allocation for output grids */

    dif = G_alloc_fmatrix(my, mx);
    if (erdep != NULL || et != NULL)
	er = G_alloc_fmatrix(my, mx);

    seeds(rand1, rand2);
    grad_check();

    if (et != NULL)
	erod(si);
    /* treba dat output pre topoerdep */
    main_loop();

    if (tserie == NULL) {
	ii = output_data(0, 1.);
	if (ii != 1)
	    G_fatal_error(_("Cannot write raster maps"));
    }

    /* Exit with Success */
    exit(EXIT_SUCCESS);
}
Пример #23
0
/**  Implementation of the tcl-command
     t_random [{ int \<n\> | seed [\<seed(0)\> ... \<seed(n_nodes-1)\>] | stat [status-list] }]
     <ul>
     <li> Without further arguments, it returns a random double between 0 and 1.
     <li> If 'int \<n\>' is given, it returns a random integer between 0 and n-1.
     <li> If 'seed'/'stat' is given without further arguments, it returns a tcl-list with
          the current seeds/status of the n_nodes active nodes; otherwise it issues the 
	  given parameters as the new seeds/status to the respective nodes.     
     </ul>
 */
int tclcommand_t_random (ClientData data, Tcl_Interp *interp, int argc, char **argv) {
  char buffer[100 + TCL_DOUBLE_SPACE + 3*TCL_INTEGER_SPACE];

  if (argc == 1) {                  /* 't_random' */
    sprintf(buffer, "%f", d_random());
    Tcl_AppendResult(interp, buffer, (char *) NULL); return (TCL_OK);
  }

  /* argc > 1 */
  argc--; argv++;

  if ( ARG_IS_S(0,"int") )          /* 't_random int <n>' */
  {
    if(argc < 2)
    { 
      Tcl_AppendResult(interp, "\nWrong # of args: Usage: 't_random int <n>'", (char *) NULL); 
      return (TCL_ERROR); 
    }
    else 
    {
      int i_max;
      if( !ARG_IS_I(1,i_max) )
      { 
        Tcl_AppendResult(interp, "\nWrong type: Usage: 't_random int <n>'", (char *) NULL); 
        return (TCL_ERROR); 
      }

      sprintf(buffer, "%d", i_random(i_max));
      Tcl_AppendResult(interp, buffer, (char *) NULL); 
      return (TCL_OK);
    }
  }
  else if ( ARG_IS_S(0,"stat") ) {
    if(argc == 1) {
      Tcl_AppendResult(interp, Random::mpi_random_get_stat().c_str(), nullptr);

      return TCL_OK;
    } else {
      auto error_msg = [interp]() {
        Tcl_AppendResult(interp, "\nWrong # of args: Usage: 't_random stat \"<state(1)> ... <state(n_nodes*625)>\"'", (char *) NULL);
      };
      
      if(argc != 2) {
        error_msg();
        return TCL_ERROR;
      }
      std::vector<std::string> states(n_nodes);

      std::istringstream iss(argv[1]);
      std::string tmp;
      
      /** Argument counter to check that the caller provided enough numbers. */      
      int n_args = 0;
      for(int node = 0; (node < n_nodes) && std::getline(iss, tmp, ' '); node++) {
        n_args++;


        /** First one is handled different, because of the space */        
        states[node] = tmp;

        for(int i = 0; (i < 624) && std::getline(iss, tmp, ' '); i++) {
          n_args++;
          states[node].append(" ");
          states[node].append(tmp);
        }
      }

      if(n_args == n_nodes*625) {
        Random::mpi_random_set_stat(states);
        return TCL_OK;
      }
      else {
        error_msg();
        return TCL_ERROR;
      }
    }
  }
  
  else if ( ARG_IS_S(0,"seed") )    /* 't_random seed [<seed(0)> ... <seed(n_nodes-1)>]' */
  {
    std::vector<int> seeds(n_nodes);

    if ((argc > 1) && (argc < n_nodes+1))      /* Fewer seeds than nodes */
    { 
      sprintf(buffer, "Wrong # of args (%d)! Usage: 't_random seed [<seed(0)> ... <seed(%d)>]'", argc,n_nodes-1);
      Tcl_AppendResult(interp, buffer, (char *)NULL); 
      return (TCL_ERROR); 
    }
    
    if (argc <= 1)
    {
      std::iota(seeds.begin(), seeds.end(), 1);
      for(auto &seed: seeds)
      {
        sprintf(buffer, "%d ", seed); 
        Tcl_AppendResult(interp, buffer, (char *) NULL); 
      }
    }
    else                            /* Get seeds for different nodes */
    {
      for (int i = 0; i < n_nodes; i++) {
        if( !ARG_IS_I(i+1,seeds[i]) ) { 
          sprintf(buffer, "\nWrong type for seed %d:\nUsage: 't_random seed [<seed(0)> ... <seed(%d)>]'", i+1 ,n_nodes-1);
          Tcl_AppendResult(interp, buffer, (char *)NULL);  
          return (TCL_ERROR); 
        }
      }
    }

#ifdef RANDOM_TRACE
    printf("Got "); 
        
    for(int i=0;i<n_nodes;i++) 
      printf("%d ",seeds[i]);
        
    printf("as new seeds.\n");
#endif
    
    Random::mpi_random_seed(n_nodes,seeds);
    
    return(TCL_OK);
  }

  /* else */
  sprintf(buffer, "Usage: 't_random [{ int <n> | seed [<seed(0)> ... <seed(%d)>] }]'",n_nodes-1);
  Tcl_AppendResult(interp, "Unknown argument '",argv[0],"' requested!\n",buffer, (char *)NULL);
  return (TCL_ERROR); 
}