コード例 #1
0
ファイル: TestUtil.cpp プロジェクト: absorbguo/Paddle
MatrixPtr makeRandomSparseMatrix(size_t height,
                                 size_t width,
                                 bool withValue,
                                 bool useGpu,
                                 bool equalNnzPerSample) {
#ifndef PADDLE_MOBILE_INFERENCE
  std::vector<int64_t> ids(height);
  std::vector<int64_t> indices(height + 1);
  indices[0] = 0;

  std::function<size_t()> randomer = [] { return uniformRandom(10); };
  if (equalNnzPerSample) {
    size_t n = 0;
    do {
      n = uniformRandom(10);
    } while (!n);
    randomer = [=] { return n; };
  }
  for (size_t i = 0; i < height; ++i) {
    indices[i + 1] = indices[i] + std::min(randomer(), width);
    ids[i] = i;
  }

  if (!withValue) {
    std::vector<sparse_non_value_t> data;
    data.resize(indices[height] - indices[0]);
    for (size_t i = 0; i < data.size(); ++i) {
      data[i].col = uniformRandom(width);
    }
    auto mat = Matrix::createSparseMatrix(
        height, width, data.size(), NO_VALUE, SPARSE_CSR, false, useGpu);
    if (useGpu) {
      std::dynamic_pointer_cast<GpuSparseMatrix>(mat)->copyFrom(
          ids.data(), indices.data(), data.data(), HPPL_STREAM_DEFAULT);
    } else {
      std::dynamic_pointer_cast<CpuSparseMatrix>(mat)->copyFrom(
          ids.data(), indices.data(), data.data());
    }
    return mat;
  } else {
    std::vector<sparse_float_value_t> data;
    data.resize(indices[height] - indices[0]);
    for (size_t i = 0; i < data.size(); ++i) {
      data[i].col = uniformRandom(width);
      data[i].value = rand() / static_cast<float>(RAND_MAX);  // NOLINT
    }
    auto mat = Matrix::createSparseMatrix(
        height, width, data.size(), FLOAT_VALUE, SPARSE_CSR, false, useGpu);
    if (useGpu) {
      std::dynamic_pointer_cast<GpuSparseMatrix>(mat)->copyFrom(
          ids.data(), indices.data(), data.data(), HPPL_STREAM_DEFAULT);
    } else {
      std::dynamic_pointer_cast<CpuSparseMatrix>(mat)->copyFrom(
          ids.data(), indices.data(), data.data());
    }
    return mat;
  }
#endif
  return nullptr;
}
コード例 #2
0
ファイル: N_UTL_RandomNumbers.C プロジェクト: Xycedev/Xyce
//-----------------------------------------------------------------------------
// Function      : Xyce::Util::RandomNumbers::gaussianRandom
// Purpose       : Provide standardized, portable source of high-quality
//                 random numbers, normally distributed with mean mu and
//                 standard deviation sigma.
// Special Notes : Method is a variant of the Box-Muller transformation.
//                 A pair of random numbers from a uniform distribution is
//                 selected such that they can be the coordinates of a
//                 unit vector.  The magnitude and phase of this vector
//                 are used in the Box-Muller transformation to create a 
//                 set of values that are normally distributed instead of
//                 uniformly distributed.
// Creator       : Tom Russo
// Creation Date : 05/27/2014
//-----------------------------------------------------------------------------
double RandomNumbers::gaussianRandom(double mu, double sigma)
{
  double x1, x2, w, y1;
  
  if (useLastGaussian_)      /* use value from previous call */
  {
    y1 = ySaveGaussian_;
    useLastGaussian_ = false;
  }
  else
  {
    do 
    {
      x1 = 2.0 * uniformRandom() - 1.0;
      x2 = 2.0 * uniformRandom() - 1.0;
      w = x1 * x1 + x2 * x2;
    } while ( w >= 1.0 );
    
    w = sqrt( (-2.0 * log( w ) ) / w );
    y1 = x1 * w;
    ySaveGaussian_ = x2 * w;
    useLastGaussian_ = true;
  }
  
  return( mu + y1 * sigma );
}
コード例 #3
0
double normalRandom()
{
	// Box-Muller transform
	double u1,u2;
	u1 = u2 = 0;
	while(u1 == 0) {u1 = uniformRandom();}
	while(u2 == 0) {u2 = uniformRandom();}
	return cos(2*M_PI*u2)*sqrt(-2.*log(u1));
}
コード例 #4
0
ファイル: Sphere.cpp プロジェクト: Gigelf/Infinity_Core
Vector3 Sphere::randomInteriorPoint() const {
    Vector3 result;
    do {
        result = Vector3(uniformRandom(-1, 1),
                         uniformRandom(-1, 1),
                         uniformRandom(-1, 1));
    } while (result.squaredMagnitude() >= 1.0f);

    return result * radius + center;
}
コード例 #5
0
ファイル: Vector2.cpp プロジェクト: jolan78/MoveMaps
Vector2 Vector2::random() {
    Vector2 result;

    do {
        result = Vector2(uniformRandom(-1, 1), uniformRandom(-1, 1));

    } while (result.squaredLength() >= 1.0f);

    result.unitize();

    return result;
}
コード例 #6
0
ファイル: Quat.cpp プロジェクト: Blumfield/ptc2
// From "Uniform Random Rotations", Ken Shoemake, Graphics Gems III.
Quat Quat::unitRandom() {
    float x0 = uniformRandom();
    float r1 = sqrtf(1 - x0), 
          r2 = sqrtf(x0);
    float t1 = (float)G3D::twoPi() * uniformRandom();
    float t2 = (float)G3D::twoPi() * uniformRandom();
    float c1 = cosf(t1), 
          s1 = sinf(t1);
    float c2 = cosf(t2), 
          s2 = sinf(t2);
    return Quat(s1 * r1, c1 * r1, s2 * r2, c2 * r2);
}
コード例 #7
0
ファイル: Vector3.cpp プロジェクト: AwkwardDev/Summit
Vector3 Vector3::random() {
    Vector3 result;

    do {
        result = Vector3(uniformRandom(-1.0, 1.0), 
                         uniformRandom(-1.0, 1.0),
                         uniformRandom(-1.0, 1.0));
    } while (result.squaredMagnitude() >= 1.0f);

    result.unitize();

    return result;
}
コード例 #8
0
ファイル: AABox.cpp プロジェクト: TheGhostGroup/AscEmu
Vector3 AABox::randomSurfacePoint() const
{
    Vector3 extent = hi - lo;
    float aXY = extent.x * extent.y;
    float aYZ = extent.y * extent.z;
    float aZX = extent.z * extent.x;

    float r = (float)uniformRandom(0.0f, aXY + aYZ + aZX);

    // Choose evenly between positive and negative face planes
    float d = ((float)uniformRandom(0, 1) < 0.5f) ? 0.0f : 1.0f;

    // The probability of choosing a given face is proportional to
    // its area.
    if (r < aXY)
    {
        return lo + Vector3((float)uniformRandom(0.0f, extent.x), (float)uniformRandom(0.0f, extent.y), d * extent.z);
    }
    else if (r < aYZ)
    {
        return lo + Vector3(d * extent.x, (float)uniformRandom(0, extent.y), (float)uniformRandom(0, extent.z));
    }
    else
    {
        return lo + Vector3((float)uniformRandom(0, extent.x), d * extent.y, (float)uniformRandom(0, extent.z));
    }
}
コード例 #9
0
ファイル: Cylinder.cpp プロジェクト: A7med-Shoukry/g3d
void Cylinder::getRandomSurfacePoint(Vector3& p, Vector3& N) const {
    float h = height();
    float r = radius();

    // Create a random point on a standard cylinder and then rotate to the global frame.

    // Relative areas (factor of 2PI already taken out)
    float capRelArea  = square(r) / 2.0f;
    float sideRelArea = r * h;

    float r1 = uniformRandom(0, capRelArea * 2 + sideRelArea);

    if (r1 < capRelArea * 2) {

        // Select a point uniformly at random on a disk
        // @cite http://mathworld.wolfram.com/DiskPointPicking.html
        float a = uniformRandom(0, (float)twoPi());
        float r2 = sqrt(uniformRandom(0, 1)) * r;
        p.x = cos(a) * r2;
        p.z = sin(a) * r2;

        N.x = 0;
        N.z = 0;
        if (r1 < capRelArea) {
            // Top
            p.y = h / 2.0f;
            N.y = 1;
        } else {
            // Bottom
            p.y = -h / 2.0f;
            N.y = -1;
        }
    } else {
        // Side
        float a = uniformRandom(0, (float)twoPi());
        N.x = cos(a);
        N.y = 0;
        N.z = sin(a);
        p.x = N.x * r;
        p.z = N.y * r;
        p.y = uniformRandom(-h / 2.0f, h / 2.0f);
    }

    // Transform to world space
    CoordinateFrame cframe;
    getReferenceFrame(cframe);
    
    p = cframe.pointToWorldSpace(p);
    N = cframe.normalToWorldSpace(N);
}
コード例 #10
0
ファイル: Box.cpp プロジェクト: luaman/g3d-cpp
void Box::getRandomSurfacePoint(Vector3& P, Vector3& N) const {
    float aXY = _extent.x * _extent.y;
    float aYZ = _extent.y * _extent.z;
    float aZX = _extent.z * _extent.x;

    float r = (float)uniformRandom(0, aXY + aYZ + aZX);

    // Choose evenly between positive and negative face planes
    float d = (uniformRandom(0, 1) < 0.5f) ? -1.0f : 1.0f;

    // The probability of choosing a given face is proportional to
    // its area.
    if (r < aXY) {
        P = _axis[0] * (float)uniformRandom(-0.5, 0.5) * _extent.x +
            _axis[1] * (float)uniformRandom(-0.5, 0.5) * _extent.y +
            _center + _axis[2] * d * _extent.z * 0.5f;
        N = _axis[2] * d;
    } else if (r < aYZ) {
        P = _axis[1] * (float)uniformRandom(-0.5, 0.5) * _extent.y +
            _axis[2] * (float)uniformRandom(-0.5, 0.5) * _extent.z +
            _center + _axis[0] * d * _extent.x * 0.5f;
        N = _axis[0] * d;
    } else {
        P = _axis[2] * (float)uniformRandom(-0.5, 0.5) * _extent.z +
            _axis[0] *(float) uniformRandom(-0.5, 0.5) * _extent.x +
            _center + _axis[1] * d * _extent.y * 0.5f;
        N = _axis[1] * d;
    }
}
コード例 #11
0
ファイル: Triangle.cpp プロジェクト: lev1976g/easywow
	Vector3 Triangle::randomPoint() const {
		// Choose a random point in the parallelogram

		float s = uniformRandom();
		float t = uniformRandom();

		if (t > 1.0f - s) {
			// Outside the triangle; reflect about the
			// diagonal of the parallelogram
			t = 1.0f - t;
			s = 1.0f - s;
		}

		return _edge01 * s + _edge02 * t + _vertex[0];
	}
コード例 #12
0
ファイル: tMatrix3.cpp プロジェクト: luaman/g3d-cpp
void testMatrix3() {
    printf("G3D::Matrix3  ");

    testEuler();

    {
        Matrix3 M = Matrix3::identity();
        for (int i = 0; i < 3; ++i) {
            for (int j = 0; j < 3; ++j) {
                M[i][j] = uniformRandom(0, 1);
            }
        }

        Vector3 v = Vector3::random();

        Vector3 x1 = v * M;
        Vector3 x2 = M.transpose() * v;

        debugAssert(x1 == x2);

    }


    printf("passed\n");
}
コード例 #13
0
ファイル: TestUtil.cpp プロジェクト: absorbguo/Paddle
void generateSequenceStartPositions(size_t batchSize,
                                    ICpuGpuVectorPtr& sequenceStartPositions) {
  int numSeqs;
  if (FLAGS_fixed_seq_length != 0) {
    numSeqs = std::ceil((float)batchSize / (float)FLAGS_fixed_seq_length);
  } else {
    numSeqs = batchSize / 10 + 1;
  }
  sequenceStartPositions =
      ICpuGpuVector::create(numSeqs + 1, /* useGpu= */ false);
  int* buf = sequenceStartPositions->getMutableData(false);
  int64_t pos = 0;
  int len = FLAGS_fixed_seq_length;
  int maxLen = 2 * batchSize / numSeqs;
  for (int i = 0; i < numSeqs; ++i) {
    if (FLAGS_fixed_seq_length == 0) {
      len = uniformRandom(
                std::min<int64_t>(maxLen, batchSize - pos - numSeqs + i)) +
            1;
    }
    buf[i] = pos;
    pos += len;
    VLOG(1) << " len=" << len;
  }
  buf[numSeqs] = batchSize;
}
コード例 #14
0
ファイル: TestUtil.cpp プロジェクト: absorbguo/Paddle
void generateSubSequenceStartPositions(
    const ICpuGpuVectorPtr& sequenceStartPositions,
    ICpuGpuVectorPtr& subSequenceStartPositions) {
  int numSeqs = sequenceStartPositions->getSize() - 1;
  const int* buf = sequenceStartPositions->getData(false);
  int numOnes = 0;
  for (int i = 0; i < numSeqs; ++i) {
    if (buf[i + 1] - buf[i] == 1) {
      ++numOnes;
    }
  }
  // each seq has two sub-seq except length 1
  int numSubSeqs = numSeqs * 2 - numOnes;
  subSequenceStartPositions =
      ICpuGpuVector::create(numSubSeqs + 1, /* useGpu= */ false);
  int* subBuf = subSequenceStartPositions->getMutableData(false);
  int j = 0;
  for (int i = 0; i < numSeqs; ++i) {
    if (buf[i + 1] - buf[i] == 1) {
      subBuf[j++] = buf[i];
    } else {
      int len = uniformRandom(buf[i + 1] - buf[i] - 1) + 1;
      subBuf[j++] = buf[i];
      subBuf[j++] = buf[i] + len;
    }
  }
  subBuf[j] = buf[numSeqs];
}
コード例 #15
0
ファイル: Box.cpp プロジェクト: luaman/g3d-cpp
Vector3 Box::randomInteriorPoint() const {
    Vector3 sum = _center;

    for (int a = 0; a < 3; ++a) {
        sum += _axis[a] * (float)uniformRandom(-0.5, 0.5) * _extent[a];
    }

    return sum;
}
コード例 #16
0
void PolygonGenerator::SetParticle(int i) {
    pos[i*3] = uniformRandom(p.xMin, p.xMax);
    pos[i*3+1] = uniformRandom(p.yMin, p.yMax);
    pos[i*3+2] = uniformRandom(p.zMin, p.zMax);

    vector3d e;
    e.x = uniformRandom(-v_tolerance, v_tolerance);
    e.y = uniformRandom(-v_tolerance, v_tolerance);
    e.z = uniformRandom(-v_tolerance, v_tolerance);

    vector3d vNew = mag(vi) * (p.normal + e); // TODO: should be v0, what is that?
    vel[i*3] = vNew.x;
    vel[i*3+1] = vNew.y;
    vel[i*3+2] = vNew.z;

    life[i] = (int)uniformRandom(life_avg-life_tolerance,life_avg+life_tolerance);

    col[i*3] = uniformRandom(clamp(c.r-c_tolerance), clamp(c.r+c_tolerance));
    col[i*3+1] = uniformRandom(clamp(c.g-c_tolerance), clamp(c.g+c_tolerance));
    col[i*3+2] = uniformRandom(clamp(c.b-c_tolerance), clamp(c.b+c_tolerance));
}
コード例 #17
0
void DirectedGenerator::SetParticle(int i) {
    pos[i*3] = p.x + uniformRandom(-1.0, 1.0);
    pos[i*3+1] = p.y + uniformRandom(-1.0, 1.0);
    pos[i*3+2] = p.z + uniformRandom(-1.0, 1.0);

    vector3d e;
    e.x = uniformRandom(-v_tolerance, v_tolerance);
    e.y = uniformRandom(-v_tolerance, v_tolerance);
    e.z = uniformRandom(-v_tolerance, v_tolerance);

    vector3d vNew = mag(vi) * (normal + e); // TODO: should be v0, what is that?
    vel[i*3] = vNew.x;
    vel[i*3+1] = vNew.y;
    vel[i*3+2] = vNew.z;

    life[i] = (int)uniformRandom(life_avg-life_tolerance,life_avg+life_tolerance);

    col[i*3] = uniformRandom(clamp(c.r-c_tolerance), clamp(c.r+c_tolerance));
    col[i*3+1] = uniformRandom(clamp(c.g-c_tolerance), clamp(c.g+c_tolerance));
    col[i*3+2] = uniformRandom(clamp(c.b-c_tolerance), clamp(c.b+c_tolerance));
}
コード例 #18
0
ファイル: Cylinder.cpp プロジェクト: A7med-Shoukry/g3d
Vector3 Cylinder::randomInteriorPoint() const {
    float h = height();
    float r = radius();

    // Create a random point in a standard cylinder and then rotate to the global frame.

    // Select a point uniformly at random on a disk
    // @cite http://mathworld.wolfram.com/DiskPointPicking.html
    float a = uniformRandom(0, (float)twoPi());
    float r2 = sqrt(uniformRandom(0, 1)) * r;

    Vector3 p(  cos(a) * r2,
                uniformRandom(-h / 2.0f, h / 2.0f),
                sin(a) * r2);

    // Transform to world space
    CoordinateFrame cframe;
    getReferenceFrame(cframe);
    
    return cframe.pointToWorldSpace(p);
}
コード例 #19
0
ファイル: GaussianRandom.cpp プロジェクト: PetaVision/OpenPV
// gaussianDist uses the Box-Muller transformation, using code based on the routine at
// <http://code.google.com/p/bzflags/source/browse/trunk/inc/boxmuller.c?spec=svn113&r=113>.
//
// /* boxmuller.c           Implements the Polar form of the Box-Muller
//                          Transformation
//
//                       (c) Copyright 1994, Everett F. Carter Jr.
//                           Permission is granted by the author to use
//                           this software for any application provided this
//                           copyright notice is preserved.
//
// */
//
// #include <math.h>
// #include <cstdlib>
//
// float ranf();
//
// float ranf() {
//     int randNum = rand();
//     float result = randNum / RAND_MAX;
//     return result;
// }/* ranf() is uniform in 0..1 */
//
//
// float box_muller(float m, float s)      /* normal random variate generator */
// {                                       /* mean m, standard deviation s */
//         float x1, x2, w, y1;
//         static float y2;
//         static int use_last = 0;
//
//         if (use_last)                   /* use value from previous call */
//         {
//                 y1 = y2;
//                 use_last = 0;
//         }
//         else
//         {
//                 do {
//                         x1 = 2.0 * ranf() - 1.0;
//                         x2 = 2.0 * ranf() - 1.0;
//                         w = x1 * x1 + x2 * x2;
//                 } while ( w >= 1.0 );
//
//                 w = sqrt( (-2.0 * log( w ) ) / w );
//                 y1 = x1 * w;
//                 y2 = x2 * w;
//                 use_last = 1;
//         }
//
//         return( m + y1 * s );
// }
float GaussianRandom::gaussianDist(int localIndex) {
   float x1, x2, y;
   struct box_muller_data bmdata = heldValues[localIndex];
   if (bmdata.hasHeldValue) {
      y = bmdata.heldValue;
   }
   else {
      float w;
      do {
         x1 = 2.0 * uniformRandom(localIndex) - 1.0;
         x2 = 2.0 * uniformRandom(localIndex) - 1.0;
         w = x1 * x1 + x2 * x2;
      } while ( w >= 1.0 );

      w = sqrt( (-2.0 * log( w ) ) / w );
      y = x1 * w;
      bmdata.heldValue = x2 * w;
   }
   bmdata.hasHeldValue = !bmdata.hasHeldValue;

   return y;
}
コード例 #20
0
void particleFilter(IplImage* img)
{
	// Diffusion
	for(int i = 0; i < N; i++)
	{
		// Position
		particles[i].x += sigma_diffusion*normalRandom();
		if(particles[i].x < 0) {particles[i].x = 0;}
		if(particles[i].x > height-1) {particles[i].x = height-1;}

		particles[i].y += sigma_diffusion*normalRandom();
		if(particles[i].y < 0) {particles[i].y = 0;}
		if(particles[i].y > width-1) {particles[i].y = width-1;}
	}

	// Weighting
	double norm = 0;
	int** integral = integralImage(img);
	for(int i = 0; i < N; i++)
	{
		particles[i].w = evaluate(particles[i].x,particles[i].y,particles[i].sx,particles[i].sy,integral);
		norm += particles[i].w;
	}
	for(int i = 0; i < N; i++)
	{
		particles[i].w = particles[i].w/norm;
	}

	// Resampling
	double cdf[N];
	cdf[0] = particles[0].w;
	for(int i = 1; i < N; i++)
	{
		cdf[i] = cdf[i-1] + particles[i].w;
	}

	double r = uniformRandom()/N;
	for(int i = 0; i < N; i++)
	{
		for(int j = 0; j < N; j++)
		{
			if(cdf[j] >= r)
			{
				particles[i] = particles[j];
				break;
			}
		}
		particles[i].w = (double)1/N;
		r += (double)1/N;
	}
}
コード例 #21
0
ファイル: Capsule.cpp プロジェクト: h4s0n/Sandshroud
Vector3 Capsule::randomInteriorPoint() const {
    float h = height();
    float r = radius();

    // Create a random point in a standard capsule and then rotate to the global frame.

    Vector3 p;

    float hemiVolume = pi() * (r*r*r) * 4 / 6.0;
    float cylVolume = pi() * square(r) * h;
    
    float r1 = uniformRandom(0, 2.0 * hemiVolume + cylVolume);

    if (r1 < 2.0 * hemiVolume) {

        p = Sphere(Vector3::zero(), r).randomInteriorPoint();

        p.y += sign(p.y) * h / 2.0f;

    } else {

        // Select a point uniformly at random on a disk
        float a = uniformRandom(0, (float)twoPi());
        float r2 = sqrt(uniformRandom(0, 1)) * r;

        p = Vector3(cos(a) * r2,
                    uniformRandom(-h / 2.0f, h / 2.0f),
                    sin(a) * r2);
    }

    // Transform to world space
    CoordinateFrame cframe;
    getReferenceFrame(cframe);
    
    return cframe.pointToWorldSpace(p);
}
コード例 #22
0
ファイル: Capsule.cpp プロジェクト: h4s0n/Sandshroud
void Capsule::getRandomSurfacePoint(Vector3& p, Vector3& N) const {
    float h = height();
    float r = radius();

    // Create a random point on a standard capsule and then rotate to the global frame.

    // Relative areas
    float capRelArea  = sqrt(r) / 2.0f;
    float sideRelArea = r * h;

    float r1 = uniformRandom(0, capRelArea * 2 + sideRelArea);

    if (r1 < capRelArea * 2) {

        // Select a point uniformly at random on a sphere
        N = Sphere(Vector3::zero(), 1).randomSurfacePoint();
        p = N * r;
        p.y += sign(p.y) * h / 2.0f;
    } else {
        // Side
        float a = uniformRandom(0, (float)twoPi());
        N.x = cos(a);
        N.y = 0;
        N.z = sin(a);
        p.x = N.x * r;
        p.z = N.y * r;
        p.y = uniformRandom(-h / 2.0f, h / 2.0f);
    }

    // Transform to world space
    CoordinateFrame cframe;
    getReferenceFrame(cframe);
    
    p = cframe.pointToWorldSpace(p);
    N = cframe.normalToWorldSpace(N);
}
コード例 #23
0
ファイル: LineSegment.cpp プロジェクト: Cryptoh/server
Vector3 LineSegment::randomPoint() const {
    return _point + uniformRandom(0, 1) * direction;
}
コード例 #24
0
ファイル: AABox.cpp プロジェクト: 55887MX/CCORE
Vector3 AABox::randomInteriorPoint() const {
    return Vector3(
        (float)uniformRandom(lo.x, hi.x),
        (float)uniformRandom(lo.y, hi.y),
        (float)uniformRandom(lo.z, hi.z));
}
コード例 #25
0
ファイル: simplept.cpp プロジェクト: MrShroom/CS-114
 void sample(const Vec &n, const Vec &o, Vec &i, double &pdf) const {
     
     uniformRandom(n, i, pdf);
 }