//---------------------------------------------------------------------------
///Due to funny Array behavior, it is needed
///to implement Mutate a bit clumsily
void NeuralNet::Mutate(const double m)
{
  Array<double> weights = this->getWeights();
  BOOST_FOREACH(double& x,weights)
  {
    x+= (GetRandomUniform() * (2.0 * m)) - m;
  }
simulation::simulation()
  : plant_densities{},
    water_concentrations{},
    t{0.0}
{
  //Create a 2D grid of water
  //Initialize the grid with zeros
  //grid water_concentrations = create_initial_water_concentrations(parameters);
  //grid water_concentrations (grid::width, grid::height);

  //Create a 2D grid of plants
  //Initialize the grid with random numbers between 0 and 10 (not higher, because otherwise the
  //time steps have to be really small).
  //grid plant_densities = create_initial_plant_densities(parameters);
  //grid plant_densities (grid::width, grid::height);
  for(int x = 0; x < grid::height; ++x)
  {
    for(int y = 0; y < grid::width; ++y)
      {
        const double initial_plant_density = (GetRandomUniform() * 10.0);
        //Multiply random number by 10, because I want a random number between 1.0 and 10.0
        plant_densities.set(x, y, initial_plant_density);
      }
  }
  t = 0.0;
}
示例#3
0
int main()
{
    for (int i=0; i!=10; ++i)
    {
        const double x{GetRandomUniform()};
        assert(x >= 0.0 && x < 1.0);
        std::cout << x << '\n';
    }
}
//---------------------------------------------------------------------------
//Go to next time step
void SimBrainiac::Tick()
{
  //Lowest index  = loser
  //Highest index = brainiac
  //Every tick it is possible for the loser to become the brainiac
  const int size = mBrainiacs.size();

  for (int i=0; i!=size-1; ++i)
  {
    //i has question?
    if (GetRandomUniform() > mBrainiacs[i].pHasQuestion) continue;
    //i has a question...
    //Will i's opponent know the answer
    if (GetRandomUniform() < mBrainiacs[i + 1].pCorrectAnswer) continue;
    //Nope, swap i and its opponent
    std::swap(mBrainiacs[i], mBrainiacs[i+1]);
  }
}
//---------------------------------------------------------------------------
SpriteActiveCell::SpriteActiveCell(
  const double x, const double y)
  : Sprite(x,y),
  mGoLeft( (std::rand() >> 4 ) % 2 == 0)
{

}
//---------------------------------------------------------------------------
void SpriteActiveCell::Move()
{
  const double dx = GetRandomUniform() * speed * 2.0 * (mGoLeft == true ? 1.0 : -1.0);
  const double dy = GetRandomUniform() * speed * 2.0;

  double x = GetX() + dx;
  double y = GetY() + dy;

  if      (x + GetWidth() > maxx) { x -= speed; mGoLeft = false; }
  else if (x              < 0   ) { x += speed; mGoLeft = true; }
  if (y > maxy)
  y = -GetHeight()-2.0; //-2.0 so it can be detected before
                         //actually appearing on screen
  SetX(x);
  SetY(y);
}
//---------------------------------------------------------------------------
const std::auto_ptr<EnumLocation> SpriteAntibody::WantsToMigrateTo() const
{
  EnumLocation * location = 0;

  if (GetY() < -GetHeight())
  {
    switch( (std::rand() >> 4) % 3)
    {
      case 0: location = new EnumLocation(bloodStream); break;
      //case 1: location = new EnumLocation(boneMarrow ); break;
      case 1: location = new EnumLocation(cellTissue ); break;
      case 2: location = new EnumLocation(lymphNode  ); break;
      default:
        assert(!"Should not get here");
        throw std::logic_error("Unknown location");
    }
  }
  return std::auto_ptr<EnumLocation>(location);
}
示例#6
0
  TransparentSprite(
    const int width, const int height,
    const int r = 255,
    const int g = 255,
    const int b = 255)
    : angle(GetRandomUniform() * 2.0 * boost::math::constants::pi<double>()), //Random direction
      speed(2.0),
      maxx(0),
      maxy(0)
  {
    QImage i(width,height,QImage::Format_ARGB32);
    const QColor transparency_color = QColor(0,0,0,255);
    const double r_real = static_cast<double>(r);
    const double g_real = static_cast<double>(g);
    const double b_real = static_cast<double>(b);
    const double midx = static_cast<double>(width ) / 2.0;
    const double midy = static_cast<double>(height) / 2.0;
    const double ray = std::min(midx,midy);
    for (int y=0;y!=height;++y)
    {
      const double y_real = static_cast<double>(y);
      const double dy = midy - y_real;
      const double dy2 = dy * dy;
      for (int x=0;x!=width;++x)
      {
        const double x_real = static_cast<double>(x);
        const double dx = midx - x_real;
        const double dx2 = dx * dx;
        const double dist = std::sqrt(dx2 + dy2);
        if (dist < ray)
        {
          const QColor c(
            (1.0 - (dist / ray)) * r_real,
            (1.0 - (dist / ray)) * g_real,
            (1.0 - (dist / ray)) * b_real
          );
          i.setPixel(x,y,c.rgb());
        }
        else
        {
          i.setPixel(x,y,transparency_color.rgb());

        }
      }
    }
    this->setPixmap(this->pixmap().fromImage(i));

    //Add transparancy
    QPixmap pixmap = this->pixmap();
    const QBitmap mask = pixmap.createMaskFromColor(transparency_color);
    pixmap.setMask(mask);
    this->setPixmap(pixmap);

  }
//---------------------------------------------------------------------------
void __fastcall TFormShureSm58::TimerSingTimer(TObject *Sender)
{
  //This singer sings at a strength of mSingerAverage
  // plus or minus 0.5 * mSingerAverage
  const double audioSignalStrength = (mSinging == true
    ? (0.5 * mSingerAverage) + (GetRandomUniform() * mSingerAverage)
    : 0.0);
  mMicrophone->SetAudioSignalStrength(audioSignalStrength);
  DrawAudioSignal(ImageAudioSignal,mMicrophone->GetAudioSignalStrength());
  mFormParent->OnControllerClick();
}
int ribi::nabl::Learner::SelectAction() const
{
  //Explore or exploit?
  if (GetRandomUniform() < mEpsilon)
  { //Select random action
    mLastAction = std::rand() % mRewards.size();
  }
  else
  {
    //Selects an action probabilistically
    //and stores this action
    assert(mSelection.get()!=0);
    mLastAction = mSelection->SelectIndex(mRewards);
  }
  return mLastAction;
}
//---------------------------------------------------------------------------
__fastcall TFormShureSm58::TFormShureSm58(TComponent* Owner,
    TFormSimStagecraftMain * const formParent)
  : TFormMachine(Owner,formParent),
    mMicrophone(boost::shared_ptr<ShureSm58>(new ShureSm58)),
    mSinging(false),
    mSingerAverage( 0.4 + GetRandomUniform() * 0.6)
{
  //Use
  //Connect
  mXlrMale = boost::shared_ptr<XlrMaleControl>(
    new XlrMaleControl(this,mMicrophone->mXlrInput,ImageXlrMale));

  OnResize(0);

  CreateWatermark(ImageView,ImageWatermark);
}
示例#10
0
 SirSprite(const int width, const int height, const bool is_infected = false)
   : angle(GetRandomUniform() * 2.0
       #ifdef __STRICT_ANSI__
       * boost::math::constants::pi<double>()
       #else
       * M_PI
       #endif
     ), //Random direction
     speed(5.0),
     state(is_infected ? infected : susceptible),
     maxx(0),
     maxy(0)
 {
   QImage i(width,height,QImage::Format_ARGB32);
   this->setPixmap(this->pixmap().fromImage(i));
   setState(is_infected ? infected : susceptible);
 }
示例#11
0
//---------------------------------------------------------------------------
Person::Person(
  const double anyX,
  const double anyY,
  const double anyPproposeSafe,
  const double anyPagreeSafe,
  const double anyPagreeUnsafe,
  Extctrls::TImage * const anyImage
  )
  : x(anyX), y(anyY),
    pProposeSafe(anyPproposeSafe),
    pAgreeSafe(anyPagreeSafe),
    pAgreeUnsafe(anyPagreeUnsafe),
    image(anyImage),
    isInfected(false),
    direction( M_PI * 2.0 * GetRandomUniform() )
{

}
//---------------------------------------------------------------------------
void __fastcall TFormSoaSimMain::TimerMoveTimer(TObject *Sender)
{
    const int personWidth  = ImagePersonRed->Picture->Graphic->Width;
    const int personHeight = ImagePersonRed->Picture->Graphic->Height;
    const double speed = 5.0;
    //Move everybody
    const std::list<boost::shared_ptr<Person > >::iterator j = mPersons.end();
    for (std::list<boost::shared_ptr<Person > >::iterator i = mPersons.begin();
            i!=j;
            ++i)
    {
        //Move
        (*i)->direction += (GetRandomUniform() * M_PI * 2.0 * 0.05) - (0.025 * M_PI * 2.0);
        (*i)->x += std::sin( (*i)->direction ) * speed;
        (*i)->y -= std::cos( (*i)->direction ) * speed;
        //Keep in screen
        if ((*i)->x + personWidth > ClientWidth)
        {
            (*i)->x = ClientWidth - personWidth;
            (*i)->direction += M_PI;
        }
        else if ((*i)->x < 32)
        {
            (*i)->x = 32;
            (*i)->direction -= M_PI;
        }

        if ((*i)->y + personHeight > ClientHeight)
        {
            (*i)->y = ClientHeight - personHeight;
            (*i)->direction += M_PI;
        }
        else if ((*i)->y < 32)
        {
            (*i)->y = 32;
            (*i)->direction -= M_PI;
        }
    }

    DrawScreen();
}
示例#13
0
void FillNet(shared_ptr< Layer<float> > data_layer,
             shared_ptr< Layer<float> > label_layer, int num_output) {

  std::function<float()> rfu = GetRandomUniform<float>(-1.0, 1.0);
  std::function<float()> riu = GetRandomUniform(0, num_output);

  if (data_layer != NULL) {
    std::vector<cv::Mat> images;
    std::vector<int> labels;

    shared_ptr<caffe::MemoryDataLayer<float>> data_layer_ptr =
        boost::dynamic_pointer_cast<caffe::MemoryDataLayer<float>>(data_layer);

    // int bn = data_layer_ptr->batch_size();
    int bc = data_layer_ptr->channels();
    int bh = data_layer_ptr->height();
    int bw = data_layer_ptr->width();

    cv::Mat image(bh, bw, CV_32FC(bc));

#pragma omp parallel for
    for (int h = 0; h < bh; ++h) {
      for (int w = 0; w < bw; ++w) {
        for (int c = 0; c < bc; ++c) {
          *(image.ptr<float>(h, w) + c) = rfu();
        }
      }
    }

    images.push_back(image);
    labels.push_back(0);
    data_layer_ptr->AddMatVector(images, labels);

  }

  if (label_layer != NULL) {
    std::vector<cv::Mat> images;
    std::vector<int> labels;

    shared_ptr<caffe::MemoryDataLayer<float>> layer_ptr =
        boost::dynamic_pointer_cast<caffe::MemoryDataLayer<float>>(label_layer);

    // int bn = layer_ptr->batch_size();
    int bc = layer_ptr->channels();
    int bh = layer_ptr->height();
    int bw = layer_ptr->width();

    cv::Mat image(bh, bw, CV_32FC(bc));

#pragma omp parallel for
    for (int h = 0; h < bh; ++h) {
      for (int w = 0; w < bw; ++w) {
        for (int c = 0; c < bc; ++c) {
          *(image.ptr<float>(h, w) + c) = riu();
        }
      }
    }

    images.push_back(image);
    labels.push_back(0);
    layer_ptr->AddMatVector(images, labels);
  }
}
示例#14
0
//---------------------------------------------------------------------------
bool Person::AgreeUnsafe() const
{
  if (GetRandomUniform() < pAgreeUnsafe) return true;
  return false;
}
示例#15
0
//---------------------------------------------------------------------------
bool Person::ProposeSafe() const
{
  if (GetRandomUniform() < pProposeSafe) return true;
  return false;
}
示例#16
0
//---------------------------------------------------------------------------
void Sprite::Move()
{
  Move( (GetRandomUniform() * 2.0 * speed) - speed, (GetRandomUniform() * speed) );
}
//---------------------------------------------------------------------------
///ProjectRampalTest is the testing facility of ProjectRampal.
///A newly developed brach of the project can be tested with
///this program in terms of obtaining the right output and speed.
///ProjectRampalTest forbids the use of a release mode,
///because its purpose is to test the code.
int main(int argc, char* argv[])
{
  if (argc == 1)
  {
    QApplication a(argc, argv);
    DialogRampalTest d;
    d.show();
    return a.exec();
  }

  std::cout << GetCurrentFolder(argv[0]) << "/" << argv[0]
    << " (version 300.0)\n";
  #ifdef NDEBUG
    std::cout
      << "ProjectTest cannot be run in no-debug mode!\n"
      << "Please recompile without the NDEBUG #define"
      << std::endl;
    return 1;
  #endif

  if (argc!=4) { ShowCorrectUse(); return 0; }

  const std::string argv1 = StrToLower(argv[1]);
  const std::string argv2 = StrToLower(argv[2]);
  //Check if the fourth argument is an integer
  try
  {
    boost::lexical_cast<int>(argv[3]);
  }
  catch (boost::bad_lexical_cast&)
  {
    ShowCorrectUse();
    return 1;
  }
  const int argv3 = boost::lexical_cast<int>(argv[3]);
  //Test sanity of input
  //First parameter: theta
  {
    try { boost::lexical_cast<double>(argv1); } //Is it a double?
    catch(...)
    {
      if (argv1!="-m" && argv1!="-r") { ShowCorrectUse(); return 0; }
    }
  }
  //Second parameter: phylogeny
  {
    try { BinaryNewickVector n(argv2); } //Is it a newick?
    catch(...)
    {
      if (argv2!="-m" && argv2!="-r" ) { ShowCorrectUse(); return 0; }
    }
  }
  //Third parameter: test
  {
    if (argv3 <= 0 || argv3 > 63) { ShowCorrectUse(); return 0; }
  }
  //Input is sane

  RandomizeTimer();

  std::ofstream file("Results.txt");
  file << "Results of " << argv[0] << " " << argv[1] << " " << argv[2] << " " << argv[3] << "\n";
  file.close();

  std::cout << std::setprecision(10);

  while (1)
  {
    //Obtain theta
    //Theta input parameters:
    // -any positive non-zero value, for example '10.0'
    // -f: theta values from file 'test_thetas.txt'
    // -m: manual input of thetas
    double theta = 0.0;
    if (argv1 == "-m")
    {
      theta = AskUserForTheta();
      if (theta==0.0) break;
    }
    else if (argv1 == "-r")
    {
      theta = GetRandomUniform() * 100.0;
    }
    else
    {
      theta = boost::lexical_cast<double>(argv1);
    }

    //Obtain newick
    std::string newick;
    //Input parameters:
    // -any newick string, for example '(1,(2,3))'
    // -m: manual input of newick strings
    // -p: predefined newick strings
    // -r: random newick strings
    if (argv2 == "-m")
    {
      newick = AskUserForNewick();
      if (newick.empty()) break;
    }
    else if (argv2 == "-r")
    {
      newick = Newick::CreateRandomNewick(7,7);
    }
    else
    {
      newick = argv2;
    }

    std::ofstream file("Results.txt", std::ios_base::app);
    file << std::setprecision(99);

    //Create all tests
    std::vector<boost::shared_ptr<Test> > tests
      = Test::CreateTests(newick,theta,argv3);

    //Execute all tests
    BOOST_FOREACH(boost::shared_ptr<Test> t,tests)
    {
      t->Execute();
    }

    //Show test results
    std::cout
      << '\n'
      << "Theta: '" << theta << "'\n"
      << "Newick: '" << newick << "'\n"
      << "Number of combinations: "
      << Newick::CalcNumOfCombinations(BinaryNewickVector(newick).Get())
      << "\n\n\n\n\n"
      << "TestName\t\t\tProbability\tTime\n";

    BOOST_FOREACH(boost::shared_ptr<Test> t,tests)
    {
      std::cout
        << t->GetTestName()
        << "\t" << t->GetProbability()
        //<< '\t' << t->GetEwensProbability()
        << '\t' << t->GetTime()
        << '\n';
      file
        << t->GetTestName()
        << '\t' << t->GetNewick()
        << '\t' << t->GetProbability()
        << '\t' << t->GetEwensProbability()
        << '\t' << t->GetTime()
        << '\n';
    }

    //Probably we're done,
    //except if the user wants to input another value manually
    if (argv1!="-m" && argv2!="-m") break;
  }