Beispiel #1
0
Ray Camera::GetJitteredRay(unsigned x, unsigned y) {
	assert(x <= film.GetWidth() && y <= film.GetHeight());
	filmCenter = position + dfilm * direction;
	float dx = (x - midx) * 0.01f + urd(mt) * 0.01f;
	float dy = (y - midy) * 0.01f + urd(mt) * 0.01f;	
	Point p(filmCenter + dx * right + dy * -up);
	return Ray(position, p - position, 0.000001f);
}
Beispiel #2
0
void urd(int i)  /* up-right-down */
{
    if (i == 0) return;
    rul(i - 1);  draw_rel( 0,  h);
    urd(i - 1);  draw_rel( h,  0);
    urd(i - 1);  draw_rel( 0, -h);
    ldr(i - 1);
}
int uart_getc(int port, bool wait)
{
	if (!uart_ready)
		return -1;
	while (!(urd(UART_SR) & UART_SR_RX_READY))
		if (!wait)
			return -1;

	return urd(UART_RF);
}
Beispiel #4
0
Population* Population::nextGeneration()
{
    Population *out=new Population(this->family, this->id+1);
    /*elements of the new population*/
    std::vector<Chromosome>& parentElems = this->getElements();
    std::vector<Chromosome> selectedElems;
    std::vector<Chromosome>& childElems = out->getElements();
    /* copying the best ancestor chromosomes from the parent population */
    for(size_t i=0; i<family.getAncCount(); i++)
        childElems.push_back(parentElems[i]);
    /* selection chromosomes from previous generation, 
     * the number of them is popSz - ancCount
     * input vector for crossing operator */
    select(parentElems, selectedElems);
    /* some of selected will be crossed */ 
    std::vector<Chromosome> cxOpIn;
    float pc = family.getPc();
    std::uniform_real_distribution<float> urd(0,1);
    size_t crossedCnt=0, rewritedCnt=0;
    for(Chromosome &c : selectedElems)
    {
        /* for each chromosome generate randomly g
         * if rg < pc then this chromosome is to be crossed,
         * otherwise it goes to the new population directly
         */
        float rg = urd(gen);
        if(rg<pc)
        {
            cxOpIn.push_back(c);
            crossedCnt++;
        }
        else
        {
            childElems.push_back(c);
            rewritedCnt++;
        }
    }
    /* applying crossing operator on subsequent pairs of selected chromosomes */
    /* trick - number of crossed elements always even for convienience */
    if(crossedCnt %2 == 1)
    {
        cxOpIn.push_back(cxOpIn[0]);
        childElems.pop_back();
        rewritedCnt--;
    }
    const std::vector<Chromosome> cxOpOut = (family.getCrossOp())->run(cxOpIn);
    for(const Chromosome &c : cxOpOut)
        childElems.push_back(c);
    /* generation new chromosomes */
    for(size_t i=0; i<family.getGenSz(); i++)
        childElems.push_back(Chromosome( family.getCitiesNb(), family.getChromSz()) );
    /* mutation */
    mutate(childElems); 
    return out;
}
Beispiel #5
0
void rul(int i)  /* right-up-left */
{
    if (i == 0) return;
    urd(i - 1);  draw_rel( h, 0);
    rul(i - 1);  draw_rel( 0, h);
    rul(i - 1);  draw_rel(-h, 0);
    dlu(i - 1);
}
Beispiel #6
0
void ldr(int i)  /* left-down-right */
{
    if (i == 0) return;
    dlu(i - 1);  draw_rel(-h,  0);
    ldr(i - 1);  draw_rel( 0, -h);
    ldr(i - 1);  draw_rel( h,  0);
    urd(i - 1);
}
Beispiel #7
0
Ray Camera::GetJitteredSubRay(unsigned x, unsigned y, int subx, int suby) {
	assert(x <= film.GetWidth() && y <= film.GetHeight());
	filmCenter = position + dfilm * direction;
	float dx = (x - midx) * 0.01f;
	float dy = (y - midy) * 0.01f;

	float minx = (float)(subx - 1) * 0.005f + dx;
	float maxx = (float)(subx) * 0.005f + dx;
	float miny = (float)(suby - 1) * 0.005f + dy;
	float maxy = (float)(suby) * 0.005f + dy;

	dx = minx + (float)urd(mt) * (maxx - minx);
	dy = miny + (float)urd(mt) * (maxy - miny);

	Point p(filmCenter + dx * right + dy * -up);
	return Ray(position, p - position, 0.000001f);
}
static int _uart_putc(int port, char c)
{
	if (!uart_ready)
		return -1;
	while (!(urd(UART_SR) & UART_SR_TX_READY)) ;
	uwr(c, UART_TF);
	return 0;
}
Beispiel #9
0
void Population::select(
        std::vector<Chromosome>& inElems, 
        std::vector<Chromosome>& outElems
        )
{
    /* method as described on page 59 */
    /* each chromosome has been evaluated, counting the sum of evaluation marks */
    float ratioSum = 0.0;
    for(Chromosome& c : inElems)
        ratioSum += c.getRatio();
    /* computing selection probability */
    size_t sz = family.getPopSz();
    size_t maxInd = sz-1;
    float selectionProb[sz];
    float cumulativeProb[sz];
    for(size_t i=0; i<sz; i++)
    {
        /* selectionProb and cumulativeProb are in ascending order, whereas inElems is in
         * descending order so subsequent values are inserted from the largest to the smallest
         * index
         */ 
        selectionProb[maxInd-i] = inElems[i].getRatio() / ratioSum;
        cumulativeProb[maxInd-i] = 0.0;
        /* computing the cumulative distribution of ratios */
        for(size_t j=0; j<=i; j++)
            cumulativeProb[maxInd-i] += selectionProb[maxInd-j];
    }
    /* all needed computation have been made, roulette can run */
    std::uniform_real_distribution<float> urd(0, 1);
    size_t howManySelected = family.getPopSz() - family.getAncCount() - family.getGenSz();
    for(size_t i=0; i<howManySelected; i++)
    {
        /* c++11 version uniformly distributed random number */
        float rf = urd(gen);
        /* function that gets random value and returns the proper index based on cumulative
         * probability distribution table computed before
         */
        size_t genId = findIndex(cumulativeProb, maxInd, rf);
        outElems.push_back(inElems[genId]);
    }
}
Beispiel #10
0
double random(int s, int e) {
    std::random_device rd;
    std::uniform_real_distribution<> urd(s, e);
    return urd(rd);
}
Beispiel #11
0
int uart_tx_ready(void)
{
	return urd(UART_SR) & UART_SR_TX_READY;
}
Beispiel #12
0
void uart_putc(unsigned c)
{
	while(!(urd(UART_SR) & UART_SR_TX_READY)) ;
	uwr(c, UART_TF);
}
Beispiel #13
0
int uart_getc(void)
{
	if(!(urd(UART_SR) & UART_SR_RX_READY))
		return -1;
	return urd(UART_RF);
}
GMMDesc initutil::gonzalezKwedlo(commonutil::DataSet const& input, idx_type k, std::mt19937& gen, fp_type sampleFactor)
{  
	
// 	std::cout << "sampleFactor = " << sampleFactor << std::endl;	
// 	std::cout << "use2GMM = " << use2GMM << std::endl;	
	
	idx_type sampleSize = sampleFactor * input.points.cols();
	
	idx_type d = input.points.rows();
	idx_type n = input.points.cols();
	
	initutil::check(k, d, n);

	GMMDesc desc;
	Vector sample;

	
	GMMDesc gmmdesc = gmmutil::optimalGaussian(input);
	Matrix covar = gmmdesc.covariances.at(0);
	fp_type trace = covar.trace()/(10.*d*k);	
	desc.means.resize(0,0);
	desc.weights.resize(0);

		
	std::uniform_real_distribution<> urd(0,1);
	std::uniform_int_distribution<> uid(0,input.points.cols()-1);
	
	Matrix randMatrix(d,d);
	Matrix randOrthonormalMatrix(d,d);
	Vector eigenvalues(d);
	
	for (idx_type i=0; i<k; ++i)
	{
		
		if (i==0)
			// draw first point uniformly
			sample = input.points.col(commonutil::randomIndex(input.weights, gen)); 
		else
		{
			// draw next point w.r.t. current mixture
			
			if(sampleFactor < 1)
			{
				commonutil::DataSet samples;
				samples.points.resize(d,sampleSize);
				samples.weights.resize(sampleSize);
				idx_type index;
				for(idx_type j=0; j<sampleSize; ++j){
					index = uid(gen);
				
// std::cout << "index = " << index << std::endl;
					
					samples.points.col(j) = input.points.col(index);
					samples.weights(j) = input.weights(index);
				}
				Vector densities = gmmutil::adaptiveDensities(samples, desc, 1.);	
				
// std::cout << "densities.size() = " << densities.size() << std::endl;

				densities.maxCoeff(&index);
				sample = samples.points.col(index); 

			}
			else
			{
				idx_type index;
				Vector densities = gmmutil::adaptiveDensities(input, desc, 1.);	

// std::cout << "densities.size() = " << densities.size() << std::endl;

				densities.maxCoeff(&index);
				sample = input.points.col(index); 
			}
			
		}
		
		desc.means.conservativeResize(d,i+1);
		desc.means.col(i) = sample;
		
		desc.weights.conservativeResize(i+1);
		desc.weights(i) = urd(gen);
			
		// random covariance
		for (idx_type i=0; i<d; ++i)
			for (idx_type j=0; j<d; ++j)
				randMatrix(i,j)=urd(gen);
		Eigen::HouseholderQR<Matrix> qr(randMatrix);
		randOrthonormalMatrix = qr.householderQ();
		commonutil::fill(eigenvalues,gen, 1.,10.);
		fp_type tmp = trace/eigenvalues.sum();
		eigenvalues = tmp * eigenvalues;
		randMatrix = randOrthonormalMatrix.transpose()*eigenvalues.asDiagonal()*randOrthonormalMatrix;
			
		desc.covariances.push_back(randMatrix);
		
	}
	

	desc.weights /= desc.weights.sum();

	return desc;
}
Beispiel #15
0
		Map(short width, short height, unsigned char numberOfPlayers) {
			//Find number closest to square that makes the match symmetric.
			int dw = sqrt(numberOfPlayers);
			while(numberOfPlayers % dw != 0) dw--;
			int dh = numberOfPlayers / dw;

			//Figure out chunk width and height accordingly.
			//Matches width and height as closely as it can, but is not guaranteed to match exactly.
			//It is guaranteed to be smaller if not the same size, however.
			int cw = width / dw;
			int ch = height / dh;

			//Pseudorandom number generator.
			std::mt19937 prg(std::chrono::system_clock::now().time_since_epoch().count());
			std::uniform_real_distribution<double> urd(0.0, 1.0);

			const std::function<double()> rud = [&]() -> double { return urd(prg); };

			class Region {
			private:
				double factor;
			public:
				std::vector< std::vector<Region * > > children; //Tries to make it 4x4.
				Region(int _w, int _h, double _min, double _max, const std::function<double()> & _rud) {
					factor = pow(_rud(), 2) * (_max - _min) + _min;
					children.clear();
					const int CHUNK_SIZE = 4;
					if(_w == 1 && _h == 1) return;
					int cw = _w / CHUNK_SIZE, ch = _h / CHUNK_SIZE;
					int difW = _w - CHUNK_SIZE * cw, difH = _h - CHUNK_SIZE * ch;
					for(int a = 0; a < CHUNK_SIZE; a++) {
						int tch = a < difH ? ch + 1 : ch;
						if(tch > 0) {
							children.push_back(std::vector<Region * >());
							for(int b = 0; b < CHUNK_SIZE; b++) {
								int tcw = b < difW ? cw + 1 : cw;
								if(tcw > 0) {
									children.back().push_back(new Region(tcw, tch, _min, _max, _rud));
								}
							}
						}
					}
					const double OWN_WEIGHT = 0.75;
					for(int a = 0; a < 2; a++) { //2 iterations found by experiment.
						for(int a = 0; a < children.size(); a++) {
							int mh = a - 1, ph = a + 1;
							if(mh < 0) mh += children.size();
							if(ph == children.size()) ph = 0;
							for(int b = 0; b < children.front().size(); b++) {
								int mw = b - 1, pw = b + 1;
								if(mw < 0) mw += children.front().size();
								if(pw == children.front().size()) pw = 0;
								children[a][b]->factor *= OWN_WEIGHT;
								children[a][b]->factor += children[mh][b]->factor * (1 - OWN_WEIGHT) / 4;
								children[a][b]->factor += children[ph][b]->factor * (1 - OWN_WEIGHT) / 4;
								children[a][b]->factor += children[a][mw]->factor * (1 - OWN_WEIGHT) / 4;
								children[a][b]->factor += children[a][pw]->factor * (1 - OWN_WEIGHT) / 4;
							}
						}
					}
				 };
				std::vector< std::vector<double> > getFactors() {
					if(children.size() == 0) return std::vector< std::vector<double> >(1, std::vector<double>(1, factor));
					std::vector< std::vector< std::vector< std::vector<double> > > > childrenFactors(children.size(), std::vector< std::vector< std::vector<double> > >(children.front().size()));
					for(int a = 0; a < children.size(); a++) {
						for(int b = 0; b < children.front().size(); b++) {
							childrenFactors[a][b] = children[a][b]->getFactors();
						}
					}
					int width = 0, height = 0;
					for(int a = 0; a < children.size(); a++) height += childrenFactors[a].front().size();
					for(int b = 0; b < children.front().size(); b++) width += childrenFactors.front()[b].front().size();
					std::vector< std::vector<double> > factors(height, std::vector<double>(width));
					int x = 0, y = 0;
					for(int my = 0; my < children.size(); my++) {
						for(int iy = 0; iy < childrenFactors[my].front().size(); iy++) {
							for(int mx = 0; mx < children.front().size(); mx++) {
								for(int ix = 0; ix < childrenFactors.front()[mx].front().size(); ix++) {
									factors[y][x] = childrenFactors[my][mx][iy][ix] * factor;
									x++;
								}
							}
							y++;
							x = 0;
						}
					}
					return factors;
				}
				~Region() { for(auto a = children.begin(); a != children.end(); a++) for(auto b = a->begin(); b != a->end(); b++) delete *b; }
			};

			//For final iteration
			const double OWN_WEIGHT = 0.66667;

			Region prodRegion(cw, ch, 0.5, 3, rud);
			std::vector< std::vector<double> > prodChunk = prodRegion.getFactors();

			//Iterate this region as well to produce better caverns:
			for(int a = 0; a < 5; a++) { // 5 iterations found by experiment.
				for(int a = 0; a < prodChunk.size(); a++) {
					int mh = a - 1, ph = a + 1;
					if(mh < 0) mh += prodChunk.size();
					if(ph == prodChunk.size()) ph = 0;
					for(int b = 0; b < prodChunk.front().size(); b++) {
						int mw = b - 1, pw = b + 1;
						if(mw < 0) mw += prodChunk.front().size();
						if(pw == prodChunk.front().size()) pw = 0;
						prodChunk[a][b] *= OWN_WEIGHT;
						prodChunk[a][b] += prodChunk[mh][b] * (1 - OWN_WEIGHT) / 4;
						prodChunk[a][b] += prodChunk[ph][b] * (1 - OWN_WEIGHT) / 4;
						prodChunk[a][b] += prodChunk[a][mw] * (1 - OWN_WEIGHT) / 4;
						prodChunk[a][b] += prodChunk[a][pw] * (1 - OWN_WEIGHT) / 4;
					}
				}
			}

			Region strengthRegion(cw, ch, 0.4, 2.25, rud);
			std::vector< std::vector<double> > strengthChunk = strengthRegion.getFactors();

			//Iterate this region as well to produce better caverns:
			for(int a = 0; a < 3; a++) { // 3 iterations found by experiment.
				for(int a = 0; a < strengthChunk.size(); a++) {
					int mh = a - 1, ph = a + 1;
					if(mh < 0) mh += strengthChunk.size();
					if(ph == strengthChunk.size()) ph = 0;
					for(int b = 0; b < strengthChunk.front().size(); b++) {
						int mw = b - 1, pw = b + 1;
						if(mw < 0) mw += strengthChunk.front().size();
						if(pw == strengthChunk.front().size()) pw = 0;
						strengthChunk[a][b] *= OWN_WEIGHT;
						strengthChunk[a][b] += strengthChunk[mh][b] * (1 - OWN_WEIGHT) / 4;
						strengthChunk[a][b] += strengthChunk[ph][b] * (1 - OWN_WEIGHT) / 4;
						strengthChunk[a][b] += strengthChunk[a][mw] * (1 - OWN_WEIGHT) / 4;
						strengthChunk[a][b] += strengthChunk[a][pw] * (1 - OWN_WEIGHT) / 4;
					}
				}
			}

			map_width = cw * dw;
			map_height = ch * dh;
			contents = std::vector< std::vector<Site> >(map_height, std::vector<Site>(map_width, { 0, 0, 0 }));

			//Fill in with chunks.
			const int MED_PROD = 1, MED_STR = 50;
			bool reflectVertical = dh % 2 == 0, reflectHorizontal = dw % 2 == 0;
			for(int a = 0; a < dh; a++) {
				for(int b = 0; b < dw; b++) {
					for(int c = 0; c < ch; c++) {
						for(int d = 0; d < cw; d++) {
							int cc = reflectVertical && a % 2 != 0 ? ch - c - 1 : c, dd = reflectHorizontal && b % 2 != 0 ? cw - d - 1 : d;
							contents[a * ch + c][b * cw + d].production = round(MED_PROD * prodChunk[cc][dd]); //Set production values.
							contents[a * ch + c][b * cw + d].strength = round(MED_STR * strengthChunk[cc][dd]);
						}
					}
					contents[a * ch + ch / 2][b * cw + cw / 2].owner = a * dw + b + 1; //Set owners.
					contents[a * ch + ch / 2][b * cw + cw / 2].strength = 255; //Set strengths
				}
			}
		}
Beispiel #16
0
//---
// Writer a dot rpf file for entry to output directory.
// 
// NOTES:
//
// 1) All coordinate written out in AREA or edge to edge format.
// 2) Throws ossimException on error.
//---
void ossimRpfUtil::writeDotRpfFile( const ossimRpfToc* toc,
                                    const ossimRpfTocEntry* tocEntry,
                                    const ossimFilename& outputDir,
                                    ossim_uint32 entry)
{
   static const char MODULE[] = "ossimRpfUtil::writeDotRpfFile";

   if ( traceDebug() )
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << MODULE << " entered..."
         << "\noutput directory:  " << outputDir
         << "\nentry: " << entry << "\n";
   }

   if ( !toc )
   {
      std::string errMsg = MODULE;
      errMsg += " ERROR toc pointer null!";
      throw ossimException(errMsg);
   }
   if ( !tocEntry )
   {
      std::string errMsg = MODULE;
      errMsg += " ERROR toc entry pointer null!";
      throw ossimException(errMsg);
   }

   // Get the file name.
   ossimFilename outFile;
   if ( outputDir.expand().isDir() )
   {
      getDotRfpFilenameForEntry(outputDir, entry, outFile);
   }
   else
   {
      outFile = outputDir;
   }
   
   // Open the file to write.
   std::ofstream os;
   os.open(outFile.c_str(), ios::out);
   if ( os.good() == false )
   {
      std::string errMsg = MODULE;
      errMsg += "ERROR could not open: ";
      errMsg += outFile.string();
      throw ossimException(errMsg);
   }
   
   // Set up the output stream fix with full precision for ground points.
   os << setiosflags(std::ios_base::fixed) << setprecision(15);
   
   //---
   // Overall TOC entry bounds:
   // 
   // Write the first line which is the bounding box of the entry in the form of:
   // "89.9850464205332, 23.9892538162654|90.5085823882692, 24.5002602501599|1"
   //      lr-lon            lr-lat           ul-lon            ul-lat
   //---
   ossimRefPtr<ossimImageGeometry> geom = tocEntry->getImageGeometry();
   if( geom.valid() == false)
   {
      std::string errMsg = "ERROR could not get geometry.";
      errMsg += outFile.string();
      throw ossimException(errMsg);  
   }

   // Rectangle in image space.
   ossimIrect outputRect;
   tocEntry->getBoundingRect(outputRect);

   // bands:
   ossim_uint32 bands = tocEntry->getNumberOfBands();

   // scale:
   ossimDpt scale;
   tocEntry->getDecimalDegreesPerPixel(scale);
   ossimDpt halfPix = scale / 2.0;

   ossimGpt llg;
   ossimGpt urg;
   geom->localToWorld(outputRect.ur(), urg);
   geom->localToWorld(outputRect.ll(), llg);

   if ( traceDebug() )
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << "outputRect: " << outputRect
         << "\nbands: " << bands
         << "\nscale: " << scale
         << "\nllg:   " << llg
         << "\nurg:   " << urg
         << std::endl;
   }

   // Expand coordinates to edge:
   llg.lon -= halfPix.x;
   llg.lat -= halfPix.y;
   urg.lon += halfPix.x;
   urg.lat += halfPix.y;
   
   // Test for 360 degrees apart.
   checkLongitude(llg, urg);
   
   os << llg.lon << "," // lower left longitude
      << llg.lat << "|" // lower left latitude
      << urg.lon << "," // upper right longitude
      << urg.lat << "|" // upper right latitude
      << bands << "\n";

   // Frame loop:
   const ossim_int32 FRAMESIZE = 1536;
   const ossim_int32 ROWS = static_cast<ossim_int32>(tocEntry->getNumberOfFramesVertical());
   if( ROWS == 0 )
   {
      std::string errMsg = MODULE;
      errMsg += " ERROR no rows!";
      throw ossimException(errMsg);  
   }
   const ossim_int32 COLS = static_cast<ossim_int32>(tocEntry->getNumberOfFramesHorizontal());
   if( COLS == 0 )
   {
      std::string errMsg = MODULE;
      errMsg += " ERROR no columns!";
      throw ossimException(errMsg);  
   }

   // Set the initial lower left and upper right image points for localToWorld call.
   //ossimDpt urd( ( (ROWS-1)*FRAMESIZE) -1, 0.0);
   //ossimDpt lld(0.0, (ROWS*FRAMESIZE)-1);
   ossimDpt urd( FRAMESIZE-1, 0.0);
   ossimDpt lld(0.0, FRAMESIZE-1);
   
   for (ossim_int32 row = ROWS-1; row > -1; --row)
   {
      for (ossim_int32 col = 0; col < COLS; ++col)
      {
         //---
         // Example format (only with 15 digit precision):
         // /data/spadac/rpf/world/cb01/ng467a1/0xslpk1a.i41|90.0448,24.3621|90.0598,24.3750
         //---
         
         // Get the path to the frame.
         ossimFilename path;
         toc->getRootDirectory(path);
         
         path = path.dirCat( toc->getRelativeFramePath(entry, row, col) );

         // Not sure if this is backwards:
         geom->localToWorld(urd, urg);
         geom->localToWorld(lld, llg);

         // Expand coordinates to edge:
         llg.lon -= halfPix.x;
         llg.lat -= halfPix.y;
         urg.lon += halfPix.x;
         urg.lat += halfPix.y;
         
         // Test for 360 degrees apart.
         checkLongitude(llg, urg);

         os << path.c_str() << "|"
            << llg.lon << "," // lower left longitude
            << llg.lat << "|" // lower left latitude
            << urg.lon << "," // upper right longitude
            << urg.lat        // upper right latitude
            << "\n";

         if ( traceDebug() )
         {
            ossimNotify(ossimNotifyLevel_DEBUG)
               << "row[" << row << "]col[" << col << "]path: " << path
               << "\nlld: " << lld
               << "\nllg: " << llg
               << "\nurd: " << urd
               << "\nurg: " << urg
               << std::endl;
         }

         // Go to next col.
         urd.x += FRAMESIZE;
         lld.x += FRAMESIZE;
            
      } // End column loop.

      // Go to nex row.
      urd.y += FRAMESIZE;
      urd.x = FRAMESIZE-1;
      lld.y += FRAMESIZE;
      lld.x = 0;
      
   } // End row loop.

   // Close the file.
   os.close();

   ossimNotify(ossimNotifyLevel_DEBUG) << "wrote file: " << outFile << std::endl;
   
} // End: ossimRpfUtil::writeDotRpfFile
Beispiel #17
0
// start DFS-traversal
void BoyerMyrvoldInit::computeDFS()
{
	// compute random edge costs
	EdgeArray<int> costs;
	EdgeComparer comp;

	if(m_randomness > 0 && m_edgeCosts != nullptr) {
		costs.init(m_g);

		int minCost = std::numeric_limits<int>::max();
		int maxCost = std::numeric_limits<int>::min();

		for(edge e : m_g.edges) {
			minCost = min(minCost, (*m_edgeCosts)[e]);
			maxCost = min(maxCost, (*m_edgeCosts)[e]);
		}

		std::uniform_real_distribution<> urd(-1, 1);
		for(edge e : m_g.edges) {
			costs[e] = minCost + (int)((1 - m_randomness) * ((*m_edgeCosts)[e] - minCost) + m_randomness * (maxCost - minCost) * urd(m_rand));
		}

		comp.setCosts(&costs);
	} else if(m_edgeCosts != nullptr) {
		comp.setCosts(m_edgeCosts);
	}

	StackPure<adjEntry> stack;
	int nextDFI = 1;
	const int numberOfNodes = m_g.numberOfNodes();

	SListPure<adjEntry> adjList;
	SListPure<node> list;
	m_g.allNodes(list);

	// get random dfs-tree, if wanted
	if (m_randomness > 0) {
		list.permute();
	}

	for (node v : list) {
		if (v->degree() == 0) {
			m_dfi[v] = nextDFI;
			m_leastAncestor[v] = nextDFI;
			m_nodeFromDFI[nextDFI] = v;
			++nextDFI;
		} else {
			adjList.clear();
			m_g.adjEntries(v, adjList);
			adjList.quicksort(comp);
			m_g.sort(v, adjList);
			stack.push(v->firstAdj());
		}
	}

	while (nextDFI <= numberOfNodes) {
		OGDF_ASSERT(!stack.empty());
		adjEntry prnt = stack.pop();
		node v = prnt->theNode();
		// check, if node v was visited before.
		if (m_dfi[v] != 0) continue;
		// parentNode=nullptr on first node on connected component
		node parentNode = prnt->twinNode();
		if (m_dfi[parentNode] == 0) parentNode = nullptr;

		// if not, mark node as visited and initialize NodeArrays
		m_dfi[v] = nextDFI;
		m_leastAncestor[v] = nextDFI;
		m_nodeFromDFI[nextDFI] = v;
		++nextDFI;

		// push all adjacent nodes onto stack
		for(adjEntry adj : v->adjEdges) {
			edge e = adj->theEdge();
			if (adj == prnt && parentNode != nullptr) continue;

			// check for self-loops and dfs- and dfs-parallel edges
			node w = adj->twinNode();
			if (m_dfi[w] == 0) {
				m_edgeType[e] = EDGE_DFS;
				m_adjParent[w] = adj;
				m_link[CW][w] = adj;
				m_link[CCW][w] = adj;

				// found new dfs-edge: preorder
				stack.push(adj->twin());
			} else if (w == v) {
				// found self-loop
				m_edgeType[e] = EDGE_SELFLOOP;
			} else {
				// node w already has been visited and is an dfs-ancestor of v
				OGDF_ASSERT(m_dfi[w] < m_dfi[v]);
				if (w == parentNode) {
					// found parallel edge of dfs-parent-edge
					m_edgeType[e] = EDGE_DFS_PARALLEL;
				} else {
					// found backedge
					m_edgeType[e] = EDGE_BACK;
					// set least Ancestor
					if (m_dfi[w] < m_leastAncestor[v])
						m_leastAncestor[v] = m_dfi[w];
				}
			}
		}
	}
}