Ejemplo n.º 1
0
void UDTTest::handleMessage(std::unique_ptr<Message> message) {
    // generate the byte array that should match this message - using the same seed the sender did
    
    int packetSize = udt::Packet::maxPayloadSize(true);
    int messageSize = message->data.size();
    
    QByteArray messageData(messageSize, 0);
   
    for (int i = 0; i < messageSize; i += packetSize) {
        // generate the random 64-bit unsigned integer that should lead this packet
        uint64_t randomInt = _distribution(_generator);
        
        messageData.replace(i, sizeof(randomInt), reinterpret_cast<char*>(&randomInt), sizeof(randomInt));
    }
    
    bool dataMatch = messageData == message->data;
    
    Q_ASSERT_X(dataMatch, "UDTTest::handleMessage",
               "received message did not match expected message (from seeded random number generation).");
    
    if (!dataMatch) {
        qCritical() << "UDTTest::handleMessage" << "received message did not match expected message"
            << "(from seeded random number generation).";
    }
}
Ejemplo n.º 2
0
void RandomDisplacementKernel<_Scalar,_SampleContainer,_PrimitiveContainer, NumberDistribution>::generateDisplacement(
        typename _PrimitiveContainer::value_type::vec* darray,
        const _SampleContainer& scontainer,
        const _PrimitiveContainer& pcontainer){
    typedef typename _PrimitiveContainer::value_type::vec vec;

    for (typename SampleContainer::const_iterator it = scontainer.cbegin();
         it != scontainer.cend(); it++, darray++){
        *darray = (*it).normal*_distribution(_generator);
    }
}
_Individual* _GA_Solver<_Individual,_NumberOfIndividual,_Selector,_Scaler,is_Multi>::solveAnswer(int max_age){
    _Individual* answer;
    std::vector<_Individual*> new_poplation;
    
    populationSettings();
    
    for(int i=0;i<max_age;i++){
        new_poplation.push_back(_population.front());
        
        while(new_poplation.size() < _NumberOfIndividual){
            _Individual *father = _selector(std::move(_population)),
            *mother = _selector(std::move(_population));
            
            new_poplation.push_back(father->cross_over(mother));
            
            if(_distribution(_mt) < PROBABILITY_OF_MUTATION){
                new_poplation.push_back(_population.back()->mutation());
            }
            
            new_poplation.back()->setEvalution(new_poplation.back()->calcEvalution(_aux));
            
            /*if(new_poplation.end() == std::find_if(new_poplation.begin(),new_poplation.end(),
                                                   [&](_Individual* rhs){
                                                       return new_poplation.back()->getEvalution() == rhs->getEvalution();
                                                   }
                                                   )
               )
                new_poplation.pop_back();*/
        }
        
        _population.erase(_population.begin());
        for(auto ptr: _population){
            delete ptr;
        }
        
        _population = new_poplation;
        new_poplation.clear();
        
        try{
            populationSettings();
        }
        catch(std::string str){
            std::cout << str << std::endl;
            break;
        }
    }
    
    answer = _population.front();
    return answer;
}
Ejemplo n.º 4
0
bool MetropolisTest::test(Array<double> &trial_coords, double trial_energy,
        Array<double>& old_coords, double old_energy, double temperature, 
        MC * mc)
{
    double rand, w, wcomp;
    bool success = true;

    wcomp = (trial_energy - old_energy) / temperature;
    w = exp(-wcomp);

    if (w < 1.0){
        rand = _distribution(_generator);
        if (rand > w) success = false;
    }

    return success;
}
Ejemplo n.º 5
0
    inline int owner( Package p ) {
        int o;
        switch ( this->common().selection() ) {
        default:
        case 1:
            o = p.hash() % ( this->common().worldSize() - 1 ) + 1;
            break;
        case 2:
            return this->common().rank() % this->common().worldSize() + 1;
        case 3:
            o = _distribution( _generator );
            break;
        case 4:
            o = _generator() % ( this->common().worldSize() - 1 ) + 1;
            break;
        case 5:
            o = ::rand_r( &_seed ) % ( this->common().worldSize() - 1 ) + 1;
            break;
        }

        if ( o >= this->common().rank() )
            ++o;
        return o;
    }
Ejemplo n.º 6
0
void UDTTest::sendPacket() {
    
    if (_maxSendPackets != -1 && _totalQueuedPackets > _maxSendPackets) {
        // don't send more packets, we've hit max
        return;
    }
    
    if (_maxSendBytes != -1 && _totalQueuedBytes > _maxSendBytes) {
        // don't send more packets, we've hit max
        return;
    }
    
    // we're good to send a new packet, construct it now
    
    // figure out what size the packet will be
    int packetPayloadSize = 0;
    
    if (_minPacketSize == _maxPacketSize) {
        // we know what size we want - figure out the payload size
        packetPayloadSize = _maxPacketSize - udt::Packet::localHeaderSize(false);
    } else {
        // pick a random size in our range
        int randomPacketSize = rand() % _maxPacketSize + _minPacketSize;
        packetPayloadSize = randomPacketSize - udt::Packet::localHeaderSize(false);
    }

    if (_sendOrdered) {
        // check if it is time to add another message - we do this every time 95% of the message size has been sent
        static int call = 0;
        static int packetSize = udt::Packet::maxPayloadSize(true);
        static int messageSizePackets = (int) ceil(_messageSize / udt::Packet::maxPayloadSize(true));
        
        static int refillCount = (int) (messageSizePackets * 0.95);
        
        if (call++ % refillCount == 0) {
            // construct a reliable and ordered packet list
            auto packetList = udt::PacketList::create(PacketType::BulkAvatarData, QByteArray(), true, true);
            
            // fill the packet list with random data according to the constant seed (so receiver can verify)
            for (int i = 0; i < messageSizePackets; ++i) {
                // setup a QByteArray full of zeros for our random padded data
                QByteArray randomPaddedData { packetSize, 0 };
                
                // generate a random integer for the first 8 bytes of the random data
                uint64_t randomInt = _distribution(_generator);
                randomPaddedData.replace(0, sizeof(randomInt), reinterpret_cast<char*>(&randomInt), sizeof(randomInt));
                
                // write this data to the PacketList
                packetList->write(randomPaddedData);
            }
            
            packetList->closeCurrentPacket();
            
            _totalQueuedBytes += (int)packetList->getDataSize();
            _totalQueuedPackets += (int)packetList->getNumPackets();
            
            _socket.writePacketList(std::move(packetList), _target);
        }
        
    } else {
        auto newPacket = udt::Packet::create(packetPayloadSize, _sendReliable);
        newPacket->setPayloadSize(packetPayloadSize);
        
        _totalQueuedBytes += newPacket->getDataSize();
        
        // queue or send this packet by calling write packet on the socket for our target
        if (_sendReliable) {
            _socket.writePacket(std::move(newPacket), _target);
        } else {
            _socket.writePacket(*newPacket, _target);
        }
        
        ++_totalQueuedPackets;
    }
    
}
Ejemplo n.º 7
0
int main (int argc, char **argv)
{
  VsgVector2d lbound = {-1., -1.};
  VsgVector2d ubound = {1., 1.};
  PointAccum *points[N] = {0};
  VsgPRTree2d *prtree;
  AranSolver2d *solver;
  int ret = 0;
  guint i;

  aran_init();

  parse_args (argc, argv);

  prtree = 
    vsg_prtree2d_new_full (&lbound, &ubound,
			    (VsgPoint2dLocFunc) vsg_vector2d_vector2d_locfunc,
			    (VsgPoint2dDistFunc) vsg_vector2d_dist,
			    (VsgRegion2dLocFunc) NULL, maxbox);

  aran_binomial_require (2*order);

  solver = aran_solver2d_new (prtree, ARAN_TYPE_DEVELOPMENT2D,
			      aran_development2d_new (0, order),
			      (AranZeroFunc) aran_development2d_set_zero);

  aran_solver2d_set_functions (solver,
			       (AranParticle2ParticleFunc2d) p2p,
			       (AranParticle2MultipoleFunc2d) p2m,
			       (AranMultipole2MultipoleFunc2d) aran_development2d_m2m,
			       (AranMultipole2LocalFunc2d) aran_development2d_m2l,
			       (AranLocal2LocalFunc2d) aran_development2d_l2l,
			       (AranLocal2ParticleFunc2d)l2p);

  _distribution (points, solver);

  aran_solver2d_solve (solver);

/*   vsg_prtree2d_write (prtree, stderr); */

  aran_solver2d_free (solver);

  if (check)
    {
      for (i=0; i<np; i++)
	{
	  guint j;
	  gcomplex128 sum = 0.;
	  gcomplex128 err;

	  for (j=0; j<np; j++)
	    {
	      if (i != j)
		{
		  gcomplex128 zd_m_zs =
		    (points[i]->vector.x + I*points[i]->vector.y) -
		    (points[j]->vector.x + I*points[j]->vector.y);

		  sum += 1./zd_m_zs * points[j]->density;
		}
	    }

	  err = (points[i]->accum - sum) /
	    MAX(cabs (points[i]->accum), cabs (sum));

	  if (cabs (err) > err_lim)
	    {
	      g_printerr ("Error: pt%u (%e,%e) -> ",
			  i,
			  creal (err), cimag (err));
	      vsg_vector2d_write (&points[i]->vector, stderr);
	      g_printerr ("\n");
	      ret ++;
	    }
	}
    }

  for (i=0; i<np; i++)
    {
      g_free (points[i]);
    }


  return ret;
}
Ejemplo n.º 8
0
int main (int argc, char **argv)
{
  VsgVector3d lbound = {-TR, -TR, -TR};
  VsgVector3d ubound = {TR, TR, TR};
  PointAccum **points;
  VsgPRTree3d *prtree;
  AranSolver3d *solver;
  int ret = 0;
  guint i;

  aran_init();

  parse_args (argc, argv);

  points = g_malloc0 (np * sizeof (PointAccum *));

  prtree =
    vsg_prtree3d_new_full (&lbound, &ubound,
			    (VsgPoint3dLocFunc) vsg_vector3d_vector3d_locfunc,
			    (VsgPoint3dDistFunc) vsg_vector3d_dist,
			    (VsgRegion3dLocFunc) NULL, maxbox);

  solver = aran_solver3d_new (prtree, ARAN_TYPE_DEVELOPMENT3D,
			      aran_development3d_new (0, order),
			      (AranZeroFunc) aran_development3d_set_zero);

  aran_solver3d_set_functions (solver,
			       (AranParticle2ParticleFunc3d) p2p,
			       (AranParticle2MultipoleFunc3d) p2m,
                               m2m,
			       m2l,
			       l2l,
			       (AranLocal2ParticleFunc3d)l2p);

  _distribution (points, solver);

/*   g_printerr ("ok depth = %d size = %d\n", */
/*               aran_solver3d_depth (solver), */
/*               aran_solver3d_point_count (solver)); */

  if (direct) _direct (points, np);
  else aran_solver3d_solve (solver);

/*   vsg_prtree3d_write (prtree, stderr); */

  aran_solver3d_free (solver);

  if (check)
    {
      gint i, j;

      for (i=0; i<np; i ++)
        {
          PointAccum *particle = points[i];

          PointAccum check;
          VsgVector3d tmp;
          gdouble err, denom;

          memcpy (&check, particle, sizeof (PointAccum));

/*           check.accum = 0.; */
          check.field = VSG_V3D_ZERO;

          for (j=0; j<np; j ++)
            {
              p2p_one_way (&check, points[j]);
            }

          denom = vsg_vector3d_norm (&check.field);
          vsg_vector3d_sub (&particle->field, &check.field, &tmp);
          err = vsg_vector3d_norm (&tmp);
          if (denom > 0.) err /= denom;

          if (fabs (err) > err_lim)
            {
              g_printerr ("Field simulation error: %d relative=(%e) "
                          "pos=(%f,%f,%f)\n"
                          "                        computed=(%f,%f,%f) "
                          "exact=(%f,%f,%f)\n",
                          i, fabs(err),
                          particle->vector.x, particle->vector.y, particle->vector.z,
                          particle->field.x, particle->field.y, particle->field.z,
                          check.field.x, check.field.y, check.field.z);
/*               g_printerr ("         pc=%f pe=%f\n", */
/*                           creal (particle->accum), */
/*                           creal (check.accum)); */
              ret ++;
            }
        }
    }

  for (i=0; i<np; i++)
    {
      g_free (points[i]);
    }

  g_free (points);

  return ret;
}
Ejemplo n.º 9
0
double Prng::generate(double a, double b) 
{
    double x = _distribution(_engine);
    double dx = b - a;
    return x*dx + a;
}
Ejemplo n.º 10
0
double Prng::generate() 
{
    return _distribution(_engine);
}
Ejemplo n.º 11
0
int main (int argc, char **argv)
{
#ifdef VSG_HAVE_MPI
  VsgPRTreeParallelConfig pconfig = {{NULL,}};
#endif

  VsgVector2d lbound = {-1., -1.};
  VsgVector2d ubound = {1., 1.};
  VsgPRTree2d *prtree;
  AranSolver2d *solver;
  int ret = 0;
  guint i;
  GTimer *timer = NULL;

#ifdef VSG_HAVE_MPI
  MPI_Init (&argc, &argv);

  MPI_Comm_size (MPI_COMM_WORLD, &sz);
  MPI_Comm_rank (MPI_COMM_WORLD, &rk);
#endif

  aran_init();

  parse_args (argc, argv);

#ifdef VSG_HAVE_MPI
  pconfig.communicator = MPI_COMM_WORLD;

  pconfig.point = point_accum_vtable;

  aran_development2d_vtable_init (&pconfig.node_data, 0, order);
#endif

  points = g_ptr_array_new ();

  if (check)
    check_points = g_malloc0 (np * sizeof (PointAccum));

  prtree = 
    vsg_prtree2d_new_full (&lbound, &ubound,
			    (VsgPoint2dLocFunc) vsg_vector2d_vector2d_locfunc,
			    (VsgPoint2dDistFunc) vsg_vector2d_dist,
			    (VsgRegion2dLocFunc) NULL, maxbox);

  aran_binomial_require (2*order);

  solver = aran_solver2d_new (prtree, ARAN_TYPE_DEVELOPMENT2D,
			      aran_development2d_new (0, order),
			      (AranZeroFunc) aran_development2d_set_zero);

#ifdef VSG_HAVE_MPI
  aran_solver2d_set_parallel (solver, &pconfig);
#endif

  if (virtual_maxbox != 0)
    aran_solver2d_set_nf_isleaf (solver, _nf_isleaf_virtual_maxbox,
                                 &virtual_maxbox);

  aran_solver2d_set_functions (solver,
			       (AranParticle2ParticleFunc2d) p2p,
			       (AranParticle2MultipoleFunc2d) p2m,
			       (AranMultipole2MultipoleFunc2d) aran_development2d_m2m,
			       (AranMultipole2LocalFunc2d) aran_development2d_m2l,
			       (AranLocal2LocalFunc2d) aran_development2d_l2l,
			       (AranLocal2ParticleFunc2d)l2p);

  if (semifar_threshold < G_MAXUINT)
    {
      aran_solver2d_set_functions_full (solver,
                                        (AranParticle2ParticleFunc2d) p2p,
                                        (AranParticle2MultipoleFunc2d) p2m,
                                        (AranMultipole2MultipoleFunc2d) aran_development2d_m2m,
                                        (AranMultipole2LocalFunc2d) aran_development2d_m2l,
                                        (AranLocal2LocalFunc2d) aran_development2d_l2l,
                                        (AranLocal2ParticleFunc2d) l2p,
                                        (AranParticle2LocalFunc2d) p2l,
                                        (AranMultipole2ParticleFunc2d) m2p,
                                        semifar_threshold);

      if (semifar_threshold == 0)
        {
          PointAccum p1 = {{0.1, 0.1}, 0.1, 0., 0};
          PointAccum p2 = {{-0.1, -0.1}, 0.1, 0., 1};

          /* compute operators timings to be able to compute optimal solver parameters */
          aran_solver2d_profile_operators (solver, (AranParticleInitFunc2d) point_accum_clear_accum,
                                           &p1, &p2);

          /* alternatively, we could get timings from profile databases */
          /* aran_profile_db_read_file ("./profiledb-newtonfield3.ini", NULL); */
          /* aran_solver2d_db_profile_operators (solver, (gdouble) order); */

        }

      
    }
  if (_hilbert)
    {
      /* configure for hilbert curve order traversal */
      aran_solver2d_set_children_order_hilbert (solver);
    }

  _distribution (points, solver);

  if (_verbose)
    {
      g_printerr ("%d : solve begin\n", rk);

#ifdef VSG_HAVE_MPI
      MPI_Barrier (MPI_COMM_WORLD);
#endif

      timer = g_timer_new ();
    }

  aran_solver2d_solve (solver);

  if (_verbose)
    {
#ifdef VSG_HAVE_MPI
      MPI_Barrier (MPI_COMM_WORLD);
#endif

      g_printerr ("%d : solve ok elapsed=%f seconds\n", rk,
                  g_timer_elapsed (timer, NULL));

      g_timer_destroy (timer);
    }

  if (check)
    {
      if (sz == 1)
        {
          for (i=0; i<np; i++)
            {
              PointAccum *pi = &check_points[i];
              guint j;

              for (j=0; j<np; j++)
                {
                  if (i != j)
                    {
                      PointAccum *pj = &check_points[j];
                      gcomplex128 zd_m_zs =
                        (pi->vector.x + I*pi->vector.y) -
                        (pj->vector.x + I*pj->vector.y);

                      pi->accum += 1./zd_m_zs * pj->density;
                    }
                }
            }
        }
      else
        check_parallel_points (solver);

      aran_solver2d_foreach_point (solver, (GFunc) check_point_accum, &ret);

      if (_verbose)
        g_printerr ("%d : max err = %e\n", rk, maxerr);

      g_free (check_points);
    }

  aran_solver2d_free (solver);

#ifdef VSG_HAVE_MPI
  aran_development2d_vtable_clear (&pconfig.node_data);
#endif

  /* destroy the points */
  g_ptr_array_foreach (points, empty_array, NULL);
  g_ptr_array_free (points, TRUE);

#ifdef VSG_HAVE_MPI
  MPI_Finalize ();
#endif

  return ret;
}
Ejemplo n.º 12
0
float Random::generate() {
	return _distribution(_engine);
}