Exemple #1
0
void Mic_DoNoise(BOOL noise)
{
	u8 (*generator) (void) = NULL;

	if (micSampleBuffer == NULL) {
		return;
	}

	if (!noise) {
		generator = &Mic_GenerateNullSample;
	} else if (CommonSettings.micMode == TCommonSettings::InternalNoise) {
		generator = &Mic_GenerateInternalNoiseSample;
	} else if (CommonSettings.micMode == TCommonSettings::Random) {
		generator = &Mic_GenerateWhiteNoiseSample;
	}

	if (generator == NULL) {
		return;
	}

	while (micBufferFillCount < MIC_MAX_BUFFER_SAMPLES) {
		Mic_DefaultBufferWrite(generator());
	}
}
    void TestSave() throw (Exception)
    {
        EXIT_IF_PARALLEL;    // Potts simulations don't work in parallel because they depend on NodesOnlyMesh for writing.

        // Create a simple 2D PottsMesh
        PottsMeshGenerator<2> generator(10, 1, 4, 10, 1, 4);
        PottsMesh<2>* p_mesh = generator.GetMesh();

        // Create cells
        std::vector<CellPtr> cells;
        MAKE_PTR(StemCellProliferativeType, p_stem_type);
        CellsGenerator<UniformlyDistributedGenerationBasedCellCycleModel, 2> cells_generator;
        cells_generator.GenerateBasicRandom(cells, p_mesh->GetNumElements(), p_stem_type);

        // Create cell population
        PottsBasedCellPopulation<2> cell_population(*p_mesh, cells);

        // Set up cell-based simulation
        OnLatticeSimulation<2> simulator(cell_population);
        simulator.SetOutputDirectory("TestOnLatticeSimulationWithPottsBasedCellPopulationSaveAndLoad");
        simulator.SetDt(0.1);
        simulator.SetEndTime(10);
        simulator.SetSamplingTimestepMultiple(10);

        // Create update rules and pass to the simulation
        MAKE_PTR(VolumeConstraintPottsUpdateRule<2>, p_volume_constraint_update_rule);
        simulator.AddPottsUpdateRule(p_volume_constraint_update_rule);
        MAKE_PTR(AdhesionPottsUpdateRule<2>, p_adhesion_update_rule);
        simulator.AddPottsUpdateRule(p_adhesion_update_rule);

        // Run simulation
        simulator.Solve();

        // Save the results
        CellBasedSimulationArchiver<2, OnLatticeSimulation<2> >::Save(&simulator);
    }
Exemple #3
0
QDBusMetaObject *QDBusMetaObject::createMetaObject(const QString &interface, const QString &xml,
                                                   QHash<QString, QDBusMetaObject *> &cache,
                                                   QDBusError &error)
{
    error = QDBusError();
    QDBusIntrospection::Interfaces parsed = QDBusIntrospection::parseInterfaces(xml);

    QDBusMetaObject *we = 0;
    QDBusIntrospection::Interfaces::ConstIterator it = parsed.constBegin();
    QDBusIntrospection::Interfaces::ConstIterator end = parsed.constEnd();
    for ( ; it != end; ++it) {
        // check if it's in the cache
        bool us = it.key() == interface;

        QDBusMetaObject *obj = cache.value(it.key(), 0);
        if ( !obj && ( us || !interface.startsWith( QLatin1String("local.") ) ) ) {
            // not in cache; create
            obj = new QDBusMetaObject;
            QDBusMetaObjectGenerator generator(it.key(), it.value().constData());
            generator.write(obj);

            if ( (obj->cached = !it.key().startsWith( QLatin1String("local.") )) )
                // cache it
                cache.insert(it.key(), obj);
            else if (!us)
                delete obj;

        }

        if (us)
            // it's us
            we = obj;
    }

    if (we)
        return we;
    // still nothing?
    
    if (parsed.isEmpty()) {
        // object didn't return introspection
        we = new QDBusMetaObject;
        QDBusMetaObjectGenerator generator(interface, 0);
        generator.write(we);
        we->cached = false;
        return we;
    } else if (interface.isEmpty()) {
        // merge all interfaces
        it = parsed.constBegin();
        QDBusIntrospection::Interface merged = *it.value().constData();
 
        for (++it; it != end; ++it) {
            merged.annotations.unite(it.value()->annotations);
            merged.methods.unite(it.value()->methods);
            merged.signals_.unite(it.value()->signals_);
            merged.properties.unite(it.value()->properties);
        }

        merged.name = QLatin1String("local.Merged");
        merged.introspection.clear();

        we = new QDBusMetaObject;
        QDBusMetaObjectGenerator generator(merged.name, &merged);
        generator.write(we);
        we->cached = false;
        return we;
    }

    // mark as an error
    error = QDBusError(QDBusError::UnknownInterface,
                       QString( QLatin1String("Interface '%1' was not found") )
                       .arg(interface));
    return 0;
}
Exemple #4
0
int main()
{
  // Define a random number generator and initialize it with a reproducible
  // seed.
  base_generator_type generator(42);

  std::cout << "10 samples of a uniform distribution in [0..1):\n";

  // Define a uniform random number distribution which produces "double"
  // values between 0 and 1 (0 inclusive, 1 exclusive).
  boost::uniform_real<> uni_dist(0,1);
  boost::variate_generator<base_generator_type&, boost::uniform_real<> > uni(generator, uni_dist);

  std::cout.setf(std::ios::fixed);
  // You can now retrieve random numbers from that distribution by means
  // of a STL Generator interface, i.e. calling the generator as a zero-
  // argument function.
  for(int i = 0; i < 10; i++)
    std::cout << uni() << '\n';

  /*
   * Change seed to something else.
   *
   * Caveat: std::time(0) is not a very good truly-random seed.  When
   * called in rapid succession, it could return the same values, and
   * thus the same random number sequences could ensue.  If not the same
   * values are returned, the values differ only slightly in the
   * lowest bits.  A linear congruential generator with a small factor
   * wrapped in a uniform_smallint (see experiment) will produce the same
   * values for the first few iterations.   This is because uniform_smallint
   * takes only the highest bits of the generator, and the generator itself
   * needs a few iterations to spread the initial entropy from the lowest bits
   * to the whole state.
   */
  generator.seed(static_cast<unsigned int>(std::time(0)));

  std::cout << "\nexperiment: roll a die 10 times:\n";

  // You can save a generator's state by copy construction.
  base_generator_type saved_generator = generator;

  // When calling other functions which take a generator or distribution
  // as a parameter, make sure to always call by reference (or pointer).
  // Calling by value invokes the copy constructor, which means that the
  // sequence of random numbers at the caller is disconnected from the
  // sequence at the callee.
  experiment(generator);

  std::cout << "redo the experiment to verify it:\n";
  experiment(saved_generator);

  // After that, both generators are equivalent
  assert(generator == saved_generator);

  // as a degenerate case, you can set min = max for uniform_int
  boost::uniform_int<> degen_dist(4,4);
  boost::variate_generator<base_generator_type&, boost::uniform_int<> > deg(generator, degen_dist);
  std::cout << deg() << " " << deg() << " " << deg() << std::endl;
  
  {
    // You can save the generator state for future use.  You can read the
    // state back in at any later time using operator>>.
    std::ofstream file("rng.saved", std::ofstream::trunc);
    file << generator;
  }

  return 0;
}
    void TestGetMeshForVtk()
    {
        // Create mesh
        CylindricalHoneycombVertexMeshGenerator generator(4, 4);
        Cylindrical2dVertexMesh* p_mesh = generator.GetCylindricalMesh();

        TS_ASSERT_EQUALS(p_mesh->GetNumNodes(), 40u);
        TS_ASSERT_EQUALS(p_mesh->GetNumElements(), 16u);

        // Test GetMeshForVtk() method
        MutableVertexMesh<2, 2>* p_mesh_for_vtk = p_mesh->GetMeshForVtk();

        // The mesh for VTK should have the same number of elements, but 16 extra nodes
        TS_ASSERT_EQUALS(p_mesh_for_vtk->GetNumElements(), 16u);
        TS_ASSERT_EQUALS(p_mesh_for_vtk->GetNumNodes(), 48u);

        // Every element in the mesh for VTK should have 6 nodes
        for (unsigned elem_index=0; elem_index<p_mesh_for_vtk->GetNumElements(); elem_index++)
        {
            TS_ASSERT_EQUALS(p_mesh_for_vtk->GetElement(elem_index)->GetNumNodes(), 6u);
        }

        VertexElement<2, 2>* p_element0 = p_mesh_for_vtk->GetElement(0);
        TS_ASSERT_EQUALS(p_element0->GetNodeGlobalIndex(0), 0u);
        TS_ASSERT_EQUALS(p_element0->GetNodeGlobalIndex(1), 5u);
        TS_ASSERT_EQUALS(p_element0->GetNodeGlobalIndex(2), 9u);
        TS_ASSERT_EQUALS(p_element0->GetNodeGlobalIndex(3), 12u);
        TS_ASSERT_EQUALS(p_element0->GetNodeGlobalIndex(4), 8u);
        TS_ASSERT_EQUALS(p_element0->GetNodeGlobalIndex(5), 4u);

        VertexElement<2, 2>* p_element3 = p_mesh_for_vtk->GetElement(3);
        TS_ASSERT_EQUALS(p_element3->GetNodeGlobalIndex(0), 3u);
        TS_ASSERT_EQUALS(p_element3->GetNodeGlobalIndex(1), 39u);
        TS_ASSERT_EQUALS(p_element3->GetNodeGlobalIndex(2), 40u);
        TS_ASSERT_EQUALS(p_element3->GetNodeGlobalIndex(3), 15u);
        TS_ASSERT_EQUALS(p_element3->GetNodeGlobalIndex(4), 11u);
        TS_ASSERT_EQUALS(p_element3->GetNodeGlobalIndex(5), 7u);

        VertexElement<2, 2>* p_element7 = p_mesh_for_vtk->GetElement(7);
        TS_ASSERT_EQUALS(p_element7->GetNodeGlobalIndex(0), 40u);
        TS_ASSERT_EQUALS(p_element7->GetNodeGlobalIndex(1), 41u);
        TS_ASSERT_EQUALS(p_element7->GetNodeGlobalIndex(2), 42u);
        TS_ASSERT_EQUALS(p_element7->GetNodeGlobalIndex(3), 43u);
        TS_ASSERT_EQUALS(p_element7->GetNodeGlobalIndex(4), 19u);
        TS_ASSERT_EQUALS(p_element7->GetNodeGlobalIndex(5), 15u);

        VertexElement<2, 2>* p_element12 = p_mesh_for_vtk->GetElement(12);
        TS_ASSERT_EQUALS(p_element12->GetNodeGlobalIndex(0), 25u);
        TS_ASSERT_EQUALS(p_element12->GetNodeGlobalIndex(1), 29u);
        TS_ASSERT_EQUALS(p_element12->GetNodeGlobalIndex(2), 33u);
        TS_ASSERT_EQUALS(p_element12->GetNodeGlobalIndex(3), 36u);
        TS_ASSERT_EQUALS(p_element12->GetNodeGlobalIndex(4), 32u);
        TS_ASSERT_EQUALS(p_element12->GetNodeGlobalIndex(5), 28u);

        VertexElement<2, 2>* p_element15 = p_mesh_for_vtk->GetElement(15);
        TS_ASSERT_EQUALS(p_element15->GetNodeGlobalIndex(0), 44u);
        TS_ASSERT_EQUALS(p_element15->GetNodeGlobalIndex(1), 45u);
        TS_ASSERT_EQUALS(p_element15->GetNodeGlobalIndex(2), 46u);
        TS_ASSERT_EQUALS(p_element15->GetNodeGlobalIndex(3), 47u);
        TS_ASSERT_EQUALS(p_element15->GetNodeGlobalIndex(4), 35u);
        TS_ASSERT_EQUALS(p_element15->GetNodeGlobalIndex(5), 31u);

        // Avoid memory leak
        delete p_mesh_for_vtk;
    }
    void TestTessellationConstructor() throw (Exception)
    {
        // Create a simple Cylindrical2dMesh, the Delaunay triangulation
        unsigned cells_across = 3;
        unsigned cells_up = 3;
        unsigned thickness_of_ghost_layer = 0;
        CylindricalHoneycombMeshGenerator generator(cells_across, cells_up, thickness_of_ghost_layer);
        Cylindrical2dMesh* p_delaunay_mesh = generator.GetCylindricalMesh();


        TrianglesMeshWriter<2,2> mesh_writer("TestVertexMeshWriters", "DelaunayMesh", false);
        TS_ASSERT_THROWS_NOTHING(mesh_writer.WriteFilesUsingMesh(*p_delaunay_mesh));



        TS_ASSERT_EQUALS(p_delaunay_mesh->GetWidth(0), 3u);
        TS_ASSERT_EQUALS(p_delaunay_mesh->CheckIsVoronoi(), true);
        TS_ASSERT_EQUALS(p_delaunay_mesh->GetNumElements(), 12u);
        TS_ASSERT_EQUALS(p_delaunay_mesh->GetNumNodes(), 9u);

        // Create a vertex mesh, the Voronoi tessellation, using the tetrahedral mesh
        Cylindrical2dVertexMesh voronoi_mesh(*p_delaunay_mesh);

        VertexMeshWriter<2,2> vertexmesh_writer("TestVertexMeshWriters", "VertexMesh", false);
        TS_ASSERT_THROWS_NOTHING(vertexmesh_writer.WriteFilesUsingMesh(voronoi_mesh));

        // Test the Voronoi tessellation has the correct number of nodes and elements
        TS_ASSERT_EQUALS(voronoi_mesh.GetWidth(0), 3u);
        TS_ASSERT_EQUALS(voronoi_mesh.GetNumElements(), 9u);
        TS_ASSERT_EQUALS(voronoi_mesh.GetNumNodes(), 12u);
//
        // Test the location of the Voronoi nodes
        /* These are ordered from right to left from bottom to top as
         * 10 1 0 5 4 6 9 2 3 11 7 8
         * Due to the numbering of the elements in the generator.
         */
        TS_ASSERT_DELTA(voronoi_mesh.GetNode(10)->rGetLocation()[0], 3.0, 1e-6);
        TS_ASSERT_DELTA(voronoi_mesh.GetNode(10)->rGetLocation()[1], sqrt(3.0)/3.0, 1e-6);
        TS_ASSERT_DELTA(voronoi_mesh.GetNode(1)->rGetLocation()[0], 0.5, 1e-6);
        TS_ASSERT_DELTA(voronoi_mesh.GetNode(1)->rGetLocation()[1], sqrt(3.0)/6.0, 1e-6);
        TS_ASSERT_DELTA(voronoi_mesh.GetNode(0)->rGetLocation()[0], 1.0, 1e-6);
        TS_ASSERT_DELTA(voronoi_mesh.GetNode(0)->rGetLocation()[1], sqrt(3.0)/3.0, 1e-6);
        TS_ASSERT_DELTA(voronoi_mesh.GetNode(5)->rGetLocation()[0], 1.5, 1e-6);
        TS_ASSERT_DELTA(voronoi_mesh.GetNode(5)->rGetLocation()[1], sqrt(3.0)/6.0, 1e-6);
        TS_ASSERT_DELTA(voronoi_mesh.GetNode(4)->rGetLocation()[0], 2.0, 1e-6);
        TS_ASSERT_DELTA(voronoi_mesh.GetNode(4)->rGetLocation()[1], sqrt(3.0)/3.0, 1e-6);
        TS_ASSERT_DELTA(voronoi_mesh.GetNode(6)->rGetLocation()[0], 2.5, 1e-6);
        TS_ASSERT_DELTA(voronoi_mesh.GetNode(6)->rGetLocation()[1], sqrt(3.0)/6.0, 1e-6);
        TS_ASSERT_DELTA(voronoi_mesh.GetNode(9)->rGetLocation()[0], 0.0, 1e-6);
        TS_ASSERT_DELTA(voronoi_mesh.GetNode(9)->rGetLocation()[1], 2.0*sqrt(3.0)/3.0, 1e-6);
        TS_ASSERT_DELTA(voronoi_mesh.GetNode(2)->rGetLocation()[0], 0.5, 1e-6);
        TS_ASSERT_DELTA(voronoi_mesh.GetNode(2)->rGetLocation()[1], 5.0*sqrt(3.0)/6.0, 1e-6);
        TS_ASSERT_DELTA(voronoi_mesh.GetNode(3)->rGetLocation()[0], 1.0, 1e-6);
        TS_ASSERT_DELTA(voronoi_mesh.GetNode(3)->rGetLocation()[1], 2.0*sqrt(3.0)/3.0, 1e-6);
        TS_ASSERT_DELTA(voronoi_mesh.GetNode(11)->rGetLocation()[0], 1.5, 1e-6);
        TS_ASSERT_DELTA(voronoi_mesh.GetNode(11)->rGetLocation()[1], 5.0*sqrt(3.0)/6.0, 1e-6);
        TS_ASSERT_DELTA(voronoi_mesh.GetNode(7)->rGetLocation()[0], 2.0, 1e-6);
        TS_ASSERT_DELTA(voronoi_mesh.GetNode(7)->rGetLocation()[1], 2.0*sqrt(3.0)/3.0, 1e-6);
        TS_ASSERT_DELTA(voronoi_mesh.GetNode(8)->rGetLocation()[0], 2.5, 1e-6);
        TS_ASSERT_DELTA(voronoi_mesh.GetNode(8)->rGetLocation()[1], 5.0*sqrt(3.0)/6.0, 1e-6);

        // Test the number of nodes owned by each Voronoi element
        TS_ASSERT_EQUALS(voronoi_mesh.GetElement(0)->GetNumNodes(), 3u);
        TS_ASSERT_EQUALS(voronoi_mesh.GetElement(1)->GetNumNodes(), 3u);
        TS_ASSERT_EQUALS(voronoi_mesh.GetElement(2)->GetNumNodes(), 3u);
        TS_ASSERT_EQUALS(voronoi_mesh.GetElement(3)->GetNumNodes(), 6u);
        TS_ASSERT_EQUALS(voronoi_mesh.GetElement(4)->GetNumNodes(), 6u);
        TS_ASSERT_EQUALS(voronoi_mesh.GetElement(5)->GetNumNodes(), 6u);
        TS_ASSERT_EQUALS(voronoi_mesh.GetElement(6)->GetNumNodes(), 3u);
        TS_ASSERT_EQUALS(voronoi_mesh.GetElement(7)->GetNumNodes(), 3u);
        TS_ASSERT_EQUALS(voronoi_mesh.GetElement(8)->GetNumNodes(), 3u);

        // Test element areas
        TS_ASSERT_DELTA(voronoi_mesh.GetVolumeOfElement(0), sqrt(3.0)/12.0, 1e-6);
        TS_ASSERT_DELTA(voronoi_mesh.GetVolumeOfElement(1), sqrt(3.0)/12.0, 1e-6);
        TS_ASSERT_DELTA(voronoi_mesh.GetVolumeOfElement(2), sqrt(3.0)/12.0, 1e-6);
        TS_ASSERT_DELTA(voronoi_mesh.GetVolumeOfElement(3), sqrt(3.0)/2.0, 1e-6);
        TS_ASSERT_DELTA(voronoi_mesh.GetVolumeOfElement(4), sqrt(3.0)/2.0, 1e-6);
        TS_ASSERT_DELTA(voronoi_mesh.GetVolumeOfElement(5), sqrt(3.0)/2.0, 1e-6);
        TS_ASSERT_DELTA(voronoi_mesh.GetVolumeOfElement(6), sqrt(3.0)/12.0, 1e-6);
        TS_ASSERT_DELTA(voronoi_mesh.GetVolumeOfElement(7), sqrt(3.0)/12.0, 1e-6);
        TS_ASSERT_DELTA(voronoi_mesh.GetVolumeOfElement(8), sqrt(3.0)/12.0, 1e-6);
    }
    void TestElementAreaPerimeterCentroidAndMoments()
    {
        // Test methods with a regular cylindrical honeycomb mesh
        CylindricalHoneycombVertexMeshGenerator generator(4, 4);
        Cylindrical2dVertexMesh* p_mesh = generator.GetCylindricalMesh();

        TS_ASSERT_EQUALS(p_mesh->GetNumNodes(), 40u);

        // Test area and perimeter calculations for all elements
        for (unsigned i=0; i<p_mesh->GetNumElements(); i++)
        {
            TS_ASSERT_DELTA(p_mesh->GetVolumeOfElement(i), 0.8660, 1e-4);
            TS_ASSERT_DELTA(p_mesh->GetSurfaceAreaOfElement(i), 3.4641, 1e-4);
        }

        // Test centroid calculations for non-periodic element
        c_vector<double, 2> centroid = p_mesh->GetCentroidOfElement(5);
        TS_ASSERT_DELTA(centroid(0), 2.0, 1e-4);
        TS_ASSERT_DELTA(centroid(1), 5.0*0.5/sqrt(3.0), 1e-4);

        // Test centroid calculations for periodic element
        centroid = p_mesh->GetCentroidOfElement(7);
        TS_ASSERT_DELTA(centroid(0), 0.0, 1e-4);
        TS_ASSERT_DELTA(centroid(1), 5.0*0.5/sqrt(3.0), 1e-4);

        // Test CalculateMomentOfElement() for all elements
        // all elements are regular hexagons with edge 1/sqrt(3.0)
        c_vector<double, 3> moments;
        for (unsigned i=0; i<p_mesh->GetNumElements(); i++)
        {
            moments = p_mesh->CalculateMomentsOfElement(i);

            TS_ASSERT_DELTA(moments(0), 5*sqrt(3.0)/16/9, 1e-6); // Ixx
            TS_ASSERT_DELTA(moments(1), 5*sqrt(3.0)/16/9, 1e-6); // Iyy
            TS_ASSERT_DELTA(moments(2), 0.0, 1e-6);            // Ixy = 0 by symmetry
        }

        // Test methods with a cylindrical mesh comprising a single rectangular element
        std::vector<Node<2>*> rectangle_nodes;
        rectangle_nodes.push_back(new Node<2>(0, false, 8.0, 2.0));
        rectangle_nodes.push_back(new Node<2>(1, false, 8.0, 0.0));
        rectangle_nodes.push_back(new Node<2>(2, false, 2.0, 0.0));
        rectangle_nodes.push_back(new Node<2>(3, false, 2.0, 2.0));
        std::vector<VertexElement<2,2>*> rectangle_elements;
        rectangle_elements.push_back(new VertexElement<2,2>(0, rectangle_nodes));

        Cylindrical2dVertexMesh rectangle_mesh(10.0, rectangle_nodes, rectangle_elements);

        TS_ASSERT_DELTA(rectangle_mesh.GetVolumeOfElement(0), 8.0, 1e-10);
        TS_ASSERT_DELTA(rectangle_mesh.GetSurfaceAreaOfElement(0), 12.0, 1e-4);

        ///\todo #2393 - for consistency, the centroid should be at (0, 2.5)
        c_vector<double, 2> rectangle_centroid = rectangle_mesh.GetCentroidOfElement(0);
        TS_ASSERT_DELTA(rectangle_centroid(0), 10.0, 1e-4);
        TS_ASSERT_DELTA(rectangle_centroid(1), 1.0, 1e-4);

        c_vector<double, 3> rectangle_moments = rectangle_mesh.CalculateMomentsOfElement(0);
        TS_ASSERT_DELTA(rectangle_moments(0), 8.0/3.0, 1e-6);  // Ixx
        TS_ASSERT_DELTA(rectangle_moments(1), 32.0/3.0, 1e-6); // Iyy
        TS_ASSERT_DELTA(rectangle_moments(2), 0.0, 1e-6);      // Ixy = 0 by symmetry

        c_vector<double, 2> rectangle_short_axis = rectangle_mesh.GetShortAxisOfElement(0);
        TS_ASSERT_DELTA(rectangle_short_axis(0), 0.0, 1e-4);
        TS_ASSERT_DELTA(rectangle_short_axis(1), 1.0, 1e-4);
    }
void thread_mcl::run_kdl_sampling(){
    //--- SETTING VARIABLES ---
    int T = 0;
    int limit_min = 300;
    int k, M, Mx;
    float confidence = 0.3; // ztable is from right side of mean (Values between 0 ~ .5)
    float error = 0.4;
    float zvalue = 4.1;
    float noise_foward = 0.01;
    float noise_turn = 0.01;
    float noise_sense = 3.0;
    movement mv;
    random_device generator;
    mt19937 gen(generator());

    uniform_int_distribution<int> randomDist(1, 3);
    std::uniform_real_distribution<double> randomTh(-.5,.5);
    //-------------------------
    this->build_tablez();

    robo->representation();

    myMcl->set_noise_particles(noise_foward, noise_turn, noise_sense);

    if(localization) //TRUE = LOCAL
        myMcl->set_position(robo->robot_pose);

    confidence = fmin(0.49998,fmax(0,confidence));

    for(int i = 0; i < ztable.size(); i++){
        if(ztable[i] >= confidence){
            zvalue = i/100.00;
            cout<<"ztable["<<i<<"] = "<<ztable[i]<<"  >=  "<<confidence<<endl;
            cout<<"Z VALUE: "<<zvalue<<endl;
            break;
        }
    }

    while(true){
        particle new_particle;
        vector<particle> new_particles;
        k = M = 0;
        Mx = numeric_limits<int>::max();
        this->myMap->set_empty_map(); //SET EMPTY MAP

        mv.dist = randomDist(gen);
        mv.angle = randomTh(gen);
        robo->move(mv);

        img = myMcl->Gera_Imagem_Pixmap(this->robo);

        myMcl->normalizing_particle();
        new_particles.clear();
        do{
            new_particle = myMcl->resample_Roleta_single();  //RESAMPLING
            state = "\n\t\t\t  Resampling";

            new_particle = myMcl->sampling_single(new_particle, mv); //SAMPLING
            state = "\n\t\t\t  Sampling";

            new_particle = myMcl->weight_particles_single(new_particle, robo->sense()); //WEIGHTING
            state = "\n\t\t\t  Weighting";

            new_particles.push_back(new_particle);

            if(bin_is_empty(new_particle)){
                k++;
                if(k > 1){
                  Mx = (int)ceil(((k-1)/(2*error))*pow(1 - (2/(9.0*(k-1))) + (sqrt(2/(9.0*(k-1))))*zvalue,3));
                  cout<<"Mx VALUE: "<<Mx<<endl;
                }
            }
            M++;
            if(Mx < limit_min)
                Mx = limit_min;
            cout<<"M:"<<M<<" Mx:"<<Mx;
            cout<<" -- Scale particle:"<<new_particle.s<<endl;
        }while(M < Mx);

        n_particles = M;
        myMcl->particles.clear();
        myMcl->particles = new_particles;
        sleep(1);
    }
}
    void TestAddCellwithExclusionBasedDivisionRule()
    {
        /**
         * In this test we basically test that the AbstractCaBasedDivisionRule is implemented and joined with the population
         * correctly. We make a new ExclusionCaBasedDivisionRule, divide a cell with it and check that the new cells
         * are in the correct locations.
         */

        // Make a simple Potts mesh
        PottsMeshGenerator<2> generator(3, 0, 0, 3, 0, 0);
        PottsMesh<2>* p_mesh = generator.GetMesh();

        // Create 6 cells in the bottom 2 rows
        std::vector<unsigned> location_indices;
        for (unsigned index=0; index<6; index++)
        {
            location_indices.push_back(index);
        }

        std::vector<CellPtr> cells;
        CellsGenerator<FixedG1GenerationalCellCycleModel, 1> cells_generator;
        cells_generator.GenerateBasic(cells, location_indices.size());

        // Create cell population
        CaBasedCellPopulation<2> cell_population(*p_mesh, cells, location_indices);

        CellPtr p_cell_0 = cell_population.GetCellUsingLocationIndex(0);
        MAKE_PTR(WildTypeCellMutationState, p_state);
        MAKE_PTR(StemCellProliferativeType, p_stem_type);

        FixedG1GenerationalCellCycleModel* p_model = new FixedG1GenerationalCellCycleModel();
        CellPtr p_temp_cell(new Cell(p_state, p_model));
        p_temp_cell->SetCellProliferativeType(p_stem_type);
        p_temp_cell->SetBirthTime(-1);

        // Set the division rule for our population to be the exclusion division rule (note that this is the default

        boost::shared_ptr<AbstractCaBasedDivisionRule<2> > p_division_rule_to_set(new ExclusionCaBasedDivisionRule<2>());
        cell_population.SetCaBasedDivisionRule(p_division_rule_to_set);

        // Get the division rule back from the population and try to add new cell by dividing cell at site 0;
        boost::shared_ptr<AbstractCaBasedDivisionRule<2> > p_division_rule = cell_population.GetCaBasedDivisionRule();

        CellPtr p_parent_cell = cell_population.GetCellUsingLocationIndex(0);
        TS_ASSERT(!(p_division_rule->IsRoomToDivide(p_parent_cell,cell_population)));

        // Test adding the new cell in the population (note this calls CalculateDaughterNodeIndex)
        TS_ASSERT_THROWS_THIS(cell_population.AddCell(p_cell_0, p_parent_cell),
                              "Trying to divide when there is no room to divide, check your division rule");

        // Test adding it in a free space
        p_parent_cell = cell_population.GetCellUsingLocationIndex(4);
        TS_ASSERT(p_division_rule->IsRoomToDivide(p_parent_cell,cell_population));

        TS_ASSERT_EQUALS(p_division_rule->CalculateDaughterNodeIndex(p_cell_0,p_parent_cell,cell_population), 7u);

        // Test adding the new cell in the population (note this calls CalculateDaughterNodeIndex)
        cell_population.AddCell(p_cell_0, p_parent_cell);

        // Now check the cells are in the correct place
        TS_ASSERT_EQUALS(cell_population.GetNumRealCells(), 7u);
    }
    void TestAddCellWithShovingBasedDivisionRule()
    {
        /**
         * In this test we create a new ShovingCaBasedDivisionRule, divide a cell with it
         * and check that the new cells are in the correct locations. First, we test where
         * there is space around the cells. This is the default setup.
         */

        // Create a simple Potts mesh
        PottsMeshGenerator<2> generator(5, 0, 0, 5, 0, 0);
        PottsMesh<2>* p_mesh = generator.GetMesh();

        // Create 9 cells in the central nodes
        std::vector<unsigned> location_indices;
        for (unsigned row=1; row<4; row++)
        {
            location_indices.push_back(1+row*5);
            location_indices.push_back(2+row*5);
            location_indices.push_back(3+row*5);
        }

        std::vector<CellPtr> cells;
        CellsGenerator<FixedG1GenerationalCellCycleModel, 1> cells_generator;
        cells_generator.GenerateBasic(cells, location_indices.size());

        // Create cell population
        CaBasedCellPopulation<2> cell_population(*p_mesh, cells, location_indices);

        // Check the cell locations
        unsigned cell_locations[9] = {6, 7, 8, 11, 12, 13, 16, 17, 18};
        unsigned index = 0;
        for (AbstractCellPopulation<2>::Iterator cell_iter = cell_population.Begin();
             cell_iter != cell_population.End();
             ++cell_iter)
        {
            TS_ASSERT_EQUALS(cell_population.GetLocationIndexUsingCell(*cell_iter),cell_locations[index])
            ++index;
        }

        // Make a new cell to add
        MAKE_PTR(WildTypeCellMutationState, p_state);
        MAKE_PTR(StemCellProliferativeType, p_stem_type);

        FixedG1GenerationalCellCycleModel* p_model = new FixedG1GenerationalCellCycleModel();
        CellPtr p_new_cell(new Cell(p_state, p_model));
        p_new_cell->SetCellProliferativeType(p_stem_type);
        p_new_cell->SetBirthTime(-1);

        // Set the division rule for our population to be the shoving division rule
        boost::shared_ptr<AbstractCaBasedDivisionRule<2> > p_division_rule_to_set(new ShovingCaBasedDivisionRule<2>());
        cell_population.SetCaBasedDivisionRule(p_division_rule_to_set);

        // Get the division rule back from the population and try to add new cell by dividing cell at site 0
        boost::shared_ptr<AbstractCaBasedDivisionRule<2> > p_division_rule = cell_population.GetCaBasedDivisionRule();

        // Select central cell
        CellPtr p_cell_12 = cell_population.GetCellUsingLocationIndex(12);

        // The ShovingCaBasedDivisionRule method IsRoomToDivide() always returns true
        TS_ASSERT_EQUALS((p_division_rule->IsRoomToDivide(p_cell_12, cell_population)), true);

        /*
         * Test adding the new cell to the population; this calls CalculateDaughterNodeIndex().
         * The new cell moves into node 13.
         */
        cell_population.AddCell(p_new_cell, p_cell_12);

        // Now check the cells are in the correct place
        TS_ASSERT_EQUALS(cell_population.GetNumRealCells(), 10u);

        // Note the cell originally on node 13 has been shoved to node 14 and the new cell is on node 13
        unsigned new_cell_locations[10] = {6, 7, 8, 11, 12, 14, 16, 17, 18, 13};
        index = 0;
        for (AbstractCellPopulation<2>::Iterator cell_iter = cell_population.Begin();
             cell_iter != cell_population.End();
             ++cell_iter)
        {
            TS_ASSERT_EQUALS(cell_population.GetLocationIndexUsingCell(*cell_iter), new_cell_locations[index])
            ++index;
        }
    }
Exemple #11
0
JSObject* ProgramExecutable::compileInternal(ExecState* exec, ScopeChainNode* scopeChainNode, JITCode::JITType jitType)
{
#if !ENABLE(JIT)
    UNUSED_PARAM(jitType);
#endif
    JSObject* exception = 0;
    JSGlobalData* globalData = &exec->globalData();
    JSGlobalObject* lexicalGlobalObject = exec->lexicalGlobalObject();
    RefPtr<ProgramNode> programNode = globalData->parser->parse<ProgramNode>(lexicalGlobalObject, lexicalGlobalObject->debugger(), exec, m_source, 0, isStrictMode() ? JSParseStrict : JSParseNormal, &exception);
    if (!programNode) {
        ASSERT(exception);
        return exception;
    }
    recordParse(programNode->features(), programNode->hasCapturedVariables(), programNode->lineNo(), programNode->lastLine());

    JSGlobalObject* globalObject = scopeChainNode->globalObject.get();
    
    OwnPtr<CodeBlock> previousCodeBlock = m_programCodeBlock.release();
    ASSERT((jitType == JITCode::bottomTierJIT()) == !previousCodeBlock);
    m_programCodeBlock = adoptPtr(new ProgramCodeBlock(this, GlobalCode, globalObject, source().provider(), previousCodeBlock.release()));
    OwnPtr<BytecodeGenerator> generator(adoptPtr(new BytecodeGenerator(programNode.get(), scopeChainNode, &globalObject->symbolTable(), m_programCodeBlock.get(), !!m_programCodeBlock->alternative() ? OptimizingCompilation : FirstCompilation)));
    if ((exception = generator->generate())) {
        m_programCodeBlock = static_pointer_cast<ProgramCodeBlock>(m_programCodeBlock->releaseAlternative());
        programNode->destroyData();
        return exception;
    }

    programNode->destroyData();
    m_programCodeBlock->copyDataFromAlternative();

#if ENABLE(JIT)
    if (exec->globalData().canUseJIT()) {
        bool dfgCompiled = false;
        if (jitType == JITCode::DFGJIT)
            dfgCompiled = DFG::tryCompile(exec, m_programCodeBlock.get(), m_jitCodeForCall);
        if (dfgCompiled) {
            if (m_programCodeBlock->alternative())
                m_programCodeBlock->alternative()->unlinkIncomingCalls();
        } else {
            if (m_programCodeBlock->alternative()) {
                m_programCodeBlock = static_pointer_cast<ProgramCodeBlock>(m_programCodeBlock->releaseAlternative());
                return 0;
            }
            m_jitCodeForCall = JIT::compile(scopeChainNode->globalData, m_programCodeBlock.get());
        }
#if !ENABLE(OPCODE_SAMPLING)
        if (!BytecodeGenerator::dumpsGeneratedCode())
            m_programCodeBlock->discardBytecode();
#endif
        m_programCodeBlock->setJITCode(m_jitCodeForCall, MacroAssemblerCodePtr());
    }
#endif

#if ENABLE(JIT)
#if ENABLE(INTERPRETER)
    if (!m_jitCodeForCall)
        Heap::heap(this)->reportExtraMemoryCost(sizeof(*m_programCodeBlock));
    else
#endif
        Heap::heap(this)->reportExtraMemoryCost(sizeof(*m_programCodeBlock) + m_jitCodeForCall.size());
#else
    Heap::heap(this)->reportExtraMemoryCost(sizeof(*m_programCodeBlock));
#endif

    return 0;
}
    void TestCaBasedSquareMonolayer()
    {
        PottsMeshGenerator<2> generator(10, 0, 0, 10, 0, 0);
        PottsMesh<2>* p_mesh = generator.GetMesh();

        // Scale so cells are on top of those in the above centre based tests
        p_mesh->Scale(1.0,sqrt(3.0)*0.5);

        // Specify where cells lie
        std::vector<unsigned> location_indices;
        for (unsigned i=0; i<100; i++)
        {
            location_indices.push_back(i);
        }

        std::vector<CellPtr> cells;
        MAKE_PTR(DifferentiatedCellProliferativeType, p_differentiated_type);
        CellsGenerator<UniformCellCycleModel, 2> cells_generator;
        cells_generator.GenerateBasicRandom(cells, location_indices.size(), p_differentiated_type);

        // Make cells with x<5.0 apoptotic (so no source term)
        boost::shared_ptr<AbstractCellProperty> p_apoptotic_property =
            cells[0]->rGetCellPropertyCollection().GetCellPropertyRegistry()->Get<ApoptoticCellProperty>();
        for (unsigned i=0; i<cells.size(); i++)
        {
            c_vector<double,2> cell_location;
            cell_location = p_mesh->GetNode(i)->rGetLocation();
            if (cell_location(0) < 5.0)
            {
                cells[i]->AddCellProperty(p_apoptotic_property);
            }
            // Set initial condition for PDE
            cells[i]->GetCellData()->SetItem("variable",1.0);
        }
        TS_ASSERT_EQUALS(p_apoptotic_property->GetCellCount(), 50u);

        CaBasedCellPopulation<2> cell_population(*p_mesh, cells, location_indices);

        // Set up simulation time for file output
        SimulationTime::Instance()->SetEndTimeAndNumberOfTimeSteps(1.0, 10);

        // Create PDE and boundary condition objects
        MAKE_PTR_ARGS(AveragedSourceParabolicPde<2>, p_pde, (cell_population, 0.1, 1.0, -1.0));
        MAKE_PTR_ARGS(ConstBoundaryCondition<2>, p_bc, (1.0));

        // Create a ChasteCuboid on which to base the finite element mesh used to solve the PDE
        ChastePoint<2> lower(-5.0, -5.0);
        ChastePoint<2> upper(15.0, 15.0);
        MAKE_PTR_ARGS(ChasteCuboid<2>, p_cuboid, (lower, upper));

        // Create a PDE modifier and set the name of the dependent variable in the PDE
        MAKE_PTR_ARGS(ParabolicBoxDomainPdeModifier<2>, p_pde_modifier, (p_pde, p_bc, false, p_cuboid));
        p_pde_modifier->SetDependentVariableName("variable");

        // For coverage, output the solution gradient
        p_pde_modifier->SetOutputGradient(true);
        p_pde_modifier->SetupSolve(cell_population,"TestAveragedParabolicPdeWithNodeOnSquare");

        // Run for 10 time steps
        for (unsigned i=0; i<10; i++)
        {
            SimulationTime::Instance()->IncrementTimeOneStep();
            p_pde_modifier->UpdateAtEndOfTimeStep(cell_population);
            p_pde_modifier->UpdateAtEndOfOutputTimeStep(cell_population);
        }

        // Test the solution at some fixed points to compare with other cell populations
        CellPtr p_cell_0 = cell_population.GetCellUsingLocationIndex(0);
        TS_ASSERT_DELTA(cell_population.GetLocationOfCellCentre(p_cell_0)[0], 0, 1e-4);
        TS_ASSERT_DELTA(cell_population.GetLocationOfCellCentre(p_cell_0)[1], 0.0, 1e-4);
        TS_ASSERT_DELTA( p_cell_0->GetCellData()->GetItem("variable"), 0.8513, 2e-2); // Low tolerance as mesh is slightly larger than for off-lattice models

        // Checking it doesn't change for this cell population
        TS_ASSERT_DELTA(p_cell_0->GetCellData()->GetItem("variable"), 0.8343, 1e-4);
    }
    void TestNodeBasedSquareMonolayer()
    {
        HoneycombMeshGenerator generator(10,10,0);
        MutableMesh<2,2>* p_generating_mesh = generator.GetMesh();
        NodesOnlyMesh<2>* p_mesh = new NodesOnlyMesh<2>;
        p_mesh->ConstructNodesWithoutMesh(*p_generating_mesh, 1.5);

        std::vector<CellPtr> cells;
        MAKE_PTR(DifferentiatedCellProliferativeType, p_differentiated_type);
        CellsGenerator<UniformCellCycleModel, 2> cells_generator;
        cells_generator.GenerateBasicRandom(cells, p_mesh->GetNumNodes(), p_differentiated_type);

        // Make cells with x<5.0 apoptotic (so no source term)
        boost::shared_ptr<AbstractCellProperty> p_apoptotic_property =
                        cells[0]->rGetCellPropertyCollection().GetCellPropertyRegistry()->Get<ApoptoticCellProperty>();
        for (unsigned i=0; i<cells.size(); i++)
        {
            c_vector<double,2> cell_location;
            cell_location = p_mesh->GetNode(i)->rGetLocation();
            if (cell_location(0) < 5.0)
            {
                cells[i]->AddCellProperty(p_apoptotic_property);
            }
            // Set initial condition for PDE
            cells[i]->GetCellData()->SetItem("variable",1.0);
        }
        TS_ASSERT_EQUALS(p_apoptotic_property->GetCellCount(), 50u);

        NodeBasedCellPopulation<2> cell_population(*p_mesh, cells);

        // Set up simulation time for file output
        SimulationTime::Instance()->SetEndTimeAndNumberOfTimeSteps(1.0, 10);

        // Create PDE and boundary condition objects
        MAKE_PTR_ARGS(AveragedSourceParabolicPde<2>, p_pde, (cell_population, 0.1, 1.0, -1.0));
        MAKE_PTR_ARGS(ConstBoundaryCondition<2>, p_bc, (1.0));

        // Create a ChasteCuboid on which to base the finite element mesh used to solve the PDE
        ChastePoint<2> lower(-5.0, -5.0);
        ChastePoint<2> upper(15.0, 15.0);
        MAKE_PTR_ARGS(ChasteCuboid<2>, p_cuboid, (lower, upper));

        // Create a PDE modifier and set the name of the dependent variable in the PDE
        MAKE_PTR_ARGS(ParabolicBoxDomainPdeModifier<2>, p_pde_modifier, (p_pde, p_bc, false, p_cuboid));
        p_pde_modifier->SetDependentVariableName("variable");

        // For coverage, output the solution gradient
        p_pde_modifier->SetOutputGradient(true);
        p_pde_modifier->SetupSolve(cell_population,"TestAveragedParabolicPdeWithNodeOnSquare");

        // Run for 10 time steps
        for (unsigned i=0; i<10; i++)
        {
            SimulationTime::Instance()->IncrementTimeOneStep();
            p_pde_modifier->UpdateAtEndOfTimeStep(cell_population);
            p_pde_modifier->UpdateAtEndOfOutputTimeStep(cell_population);
        }

        // Test the solution at some fixed points to compare with other cell populations
        CellPtr p_cell_0 = cell_population.GetCellUsingLocationIndex(0);
        TS_ASSERT_DELTA(cell_population.GetLocationOfCellCentre(p_cell_0)[0], 0, 1e-4);
        TS_ASSERT_DELTA(cell_population.GetLocationOfCellCentre(p_cell_0)[1], 0.0, 1e-4);
        TS_ASSERT_DELTA( p_cell_0->GetCellData()->GetItem("variable"), 0.8513, 1e-4);

        // Clear memory
        delete p_mesh;
    }
int main() {
    std::mt19937 generator(time(nullptr));

    sys::ComputeSystem cs;

    cs.create(sys::ComputeSystem::_gpu);

    sys::ComputeProgram program;
    program.loadFromFile("resources/ei.cl", cs);

    std::shared_ptr<ei::EIlayer::Kernels> layerKernels = std::make_shared<ei::EIlayer::Kernels>();

    layerKernels->loadFromProgram(program);

    std::shared_ptr<ei::HEInet::Kernels> hKernels = std::make_shared<ei::HEInet::Kernels>();

    hKernels->loadFromProgram(program);

    ei::HEInet ht;

    float sequence[8][4] = {
        { 0.0f, 1.0f, 0.0f, 0.0f },
        { 0.0f, 0.0f, 0.0f, 1.0f },
        { 0.0f, 0.0f, 0.0f, 1.0f },
        { 0.0f, 1.0f, 0.0f, 0.0f },
        { 1.0f, 0.0f, 0.0f, 0.0f },
        { 0.0f, 1.0f, 0.0f, 0.0f },
        { 0.0f, 0.0f, 1.0f, 0.0f },
        { 1.0f, 0.0f, 0.0f, 0.0f }
    };

    std::vector<ei::EIlayer::Configuration> configs;

    std::vector<cl_int2> eSizes(1);
    std::vector<cl_int2> iSizes(1);

    eSizes[0].x = 8;
    eSizes[0].y = 8;
    //eSizes[1].x = 12;
    //eSizes[1].y = 12;
    //eSizes[2].x = 8;
    //eSizes[2].y = 8;

    iSizes[0].x = 4;
    iSizes[0].y = 4;
    //iSizes[1].x = 6;
    //iSizes[1].y = 6;
    //iSizes[2].x = 4;
    //iSizes[2].y = 4;

    cl_int2 inputSize = { 2, 2 };

    ei::generateConfigsFromSizes(inputSize, eSizes, iSizes, configs);

    ht.createRandom(configs, 6, 6, 0.0f, 1.0f, 0.0f, 1.0f, 0.01f, 0.01f, 0.1f, 0.1f, cs, layerKernels, hKernels, generator);

    cl::Image2D inputImage = cl::Image2D(cs.getContext(), CL_MEM_READ_WRITE, cl::ImageFormat(CL_R, CL_FLOAT), inputSize.x, inputSize.y);

    cl::Image2D zeroImage = cl::Image2D(cs.getContext(), CL_MEM_READ_WRITE, cl::ImageFormat(CL_R, CL_FLOAT), 1, 1);

    sf::RenderWindow window;

    sf::ContextSettings contextSettings;
    contextSettings.antialiasingLevel = 4;

    window.create(sf::VideoMode(1280, 720), "HEInetGPU", sf::Style::Default, contextSettings);

    window.setFramerateLimit(60);

    bool quit = false;

    int s = 0;

    while (!quit) {
        sf::Event e;

        while (window.pollEvent(e)) {
            switch (e.type) {
            case sf::Event::Closed:
                quit = true;
                break;
            }
        }

        s = (s + 1) % 8;

        if (s == 0) {
            std::cout << "Sequence:" << std::endl;
        }

        cl::size_t<3> zeroCoord;
        zeroCoord[0] = zeroCoord[1] = zeroCoord[2] = 0;

        cl::size_t<3> dims;
        dims[0] = inputSize.x;
        dims[1] = inputSize.y;
        dims[2] = 1;

        cs.getQueue().enqueueWriteImage(inputImage, CL_TRUE, zeroCoord, dims, 0, 0, sequence[s]);

        ht.spikeSumBegin(cs);

        for (int iter = 0; iter < 50; iter++) {
            ht.update(cs, inputImage, zeroImage, 0.02f, 0.1f);
            ht.sumSpikes(cs, 2.0f / 50.0f);
            ht.learn(cs, zeroImage, 0.008f, 0.008f, 0.005f, 0.008f, 0.008f, 0.01f, 0.005f, 0.025f, 0.025f);
            ht.stepEnd(cs);
        }

        ht.predict(cs);
        ht.learnPrediction(cs, inputImage, 0.005f);

        window.clear();

        std::vector<cl_float> iSpikeData(ht.getEIlayers()[0].getConfig()._iWidth * ht.getEIlayers()[0].getConfig()._iHeight);
        std::vector<cl_float> eSpikeData(ht.getEIlayers()[0].getConfig()._eWidth * ht.getEIlayers()[0].getConfig()._eHeight);
        std::vector<float> predictionData(4);

        cl::size_t<3> inputDims;
        inputDims[0] = inputSize.x;
        inputDims[1] = inputSize.y;
        inputDims[2] = 1;

        cl::size_t<3> eDims;
        eDims[0] = ht.getEIlayers()[0].getConfig()._eWidth;
        eDims[1] = ht.getEIlayers()[0].getConfig()._eHeight;
        eDims[2] = 1;

        cl::size_t<3> iDims;
        iDims[0] = ht.getEIlayers()[0].getConfig()._iWidth;
        iDims[1] = ht.getEIlayers()[0].getConfig()._iHeight;
        iDims[2] = 1;

        cs.getQueue().enqueueReadImage(ht._iSpikeSumsIterPrev, CL_TRUE, zeroCoord, iDims, 0, 0, iSpikeData.data());
        cs.getQueue().enqueueReadImage(ht._eSpikeSumsIterPrev, CL_TRUE, zeroCoord, eDims, 0, 0, eSpikeData.data());
        cs.getQueue().enqueueReadImage(ht._prediction, CL_TRUE, zeroCoord, inputDims, 0, 0, predictionData.data());

        {
            sf::Image img;
            img.create(iDims[0], iDims[1]);

            for (int x = 0; x < iDims[0]; x++)
                for (int y = 0; y < iDims[1]; y++) {
                    sf::Color c;
                    c.r = c.g = c.b = 255 * iSpikeData[x + y * iDims[0]];
                    c.a = 255;

                    img.setPixel(x, y, c);
                }

            sf::Texture tex;

            tex.loadFromImage(img);

            sf::Sprite s;
            s.setTexture(tex);

            s.setScale(4.0f, 4.0f);

            window.draw(s);
        }

        {
            sf::Image img;
            img.create(eDims[0], eDims[1]);

            for (int x = 0; x < eDims[0]; x++)
                for (int y = 0; y < eDims[1]; y++) {
                    sf::Color c;
                    c.r = c.g = c.b = 255 * eSpikeData[x + y * eDims[0]];
                    c.a = 255;

                    img.setPixel(x, y, c);
                }

            sf::Texture tex;

            tex.loadFromImage(img);

            sf::Sprite s;
            s.setTexture(tex);
            s.setPosition(8.0f * iDims[0], 0.0f);

            s.setScale(4.0f, 4.0f);

            window.draw(s);
        }

        {
            cl::size_t<3> effWeightsDims;
            effWeightsDims[0] = ht.getEIlayers()[0].getConfig()._eWidth;
            effWeightsDims[1] = ht.getEIlayers()[0].getConfig()._eHeight;
            effWeightsDims[2] = std::pow(configs[0]._eFeedForwardRadius * 2 + 1, 2);

            std::vector<float> eWeights(eDims[0] * eDims[1] * effWeightsDims[2], 0.0f);

            cs.getQueue().enqueueReadImage(ht.getEIlayers()[0]._eFeedForwardWeights._weights, CL_TRUE, zeroCoord, effWeightsDims, 0, 0, eWeights.data());

            sf::Image img;

            int diam = configs[0]._eFeedForwardRadius * 2 + 1;

            img.create(effWeightsDims[0] * diam, effWeightsDims[1] * diam);

            for (int rx = 0; rx < effWeightsDims[0]; rx++)
                for (int ry = 0; ry < effWeightsDims[1]; ry++) {
                    for (int wx = 0; wx < diam; wx++)
                        for (int wy = 0; wy < diam; wy++) {
                            int index = (rx + ry * effWeightsDims[0]) + (wx + wy * diam) * effWeightsDims[0] * effWeightsDims[1];

                            sf::Color c;
                            c.r = c.g = c.b = 255 * sigmoid(4.0f * eWeights[index]);
                            c.a = 255;
                            img.setPixel(rx * diam + wx, ry * diam + wy, c);
                        }
                }

            sf::Texture tex;

            tex.loadFromImage(img);

            sf::Sprite s;

            s.setTexture(tex);
            s.setScale(2.0f, 2.0f);

            s.setPosition(0.0f, window.getSize().y - img.getSize().y * 2.0f);

            window.draw(s);
        }

        for (int i = 0; i < predictionData.size(); i++)
            std::cout << (predictionData[i] > 0.0f ? 1 : 0) << " ";

        std::cout << std::endl;

        ht.predictionEnd();

        window.display();
    }

    return 0;
}
int main() {
	std::mt19937 generator(time(nullptr));

	sf::RenderWindow renderWindow;

	sf::ContextSettings cs;
	cs.antialiasingLevel = 8;

	renderWindow.create(sf::VideoMode(800, 600), "Reinforcement Learning", sf::Style::Default, cs);
	
	renderWindow.setVerticalSyncEnabled(true);
	renderWindow.setFramerateLimit(60);

	renderWindow.setMouseCursorVisible(false);

	sdr::PredictiveRSDR rsdr;

	std::vector<sdr::PredictiveRSDR::LayerDesc> layerDescs(3);

	layerDescs[0]._width = 16;
	layerDescs[0]._height = 16;

	layerDescs[1]._width = 12;
	layerDescs[1]._height = 12;

	layerDescs[2]._width = 8;
	layerDescs[2]._height = 8;

	rsdr.createRandom(16, 16, layerDescs, -0.01f, 0.01f, 0.01f, 0.05f, 0.1f, generator);

	int ticksPerSample = 3;

	int predSteps = 4;

	int tickCounter = 0;

	std::vector<sf::Vector2f> predTrailBuffer;
	std::vector<sf::Vector2f> actualTrailBuffer;

	int trailBufferLength = 200;

	float trailDecay = 0.97f;

	predTrailBuffer.resize(trailBufferLength);
	actualTrailBuffer.resize(trailBufferLength);

	// ------------------------------- Simulation Loop -------------------------------

	bool quit = false;

	float dt = 0.017f;

	sf::Vector2i prevMousePos(-999, -999);
	sf::Vector2f predictRenderPos(-999.0f, -999.0f);

	do {
		sf::Event event;

		while (renderWindow.pollEvent(event)) {
			switch (event.type) {
			case sf::Event::Closed:
				quit = true;
				break;
			}
		}

		if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
			quit = true;

		renderWindow.clear();

		sf::Vector2i mousePos = sf::Mouse::getPosition(renderWindow);

		if (prevMousePos == sf::Vector2i(-999, -999)) {
			prevMousePos = mousePos;
			predictRenderPos = sf::Vector2f(mousePos.x, mousePos.y);

			for (int t = 0; t < trailBufferLength; t++)
				predTrailBuffer[t] = actualTrailBuffer[t] = predictRenderPos;
		}

		if (tickCounter >= ticksPerSample) {
			sf::Vector2i delta = mousePos - prevMousePos;

			prevMousePos = mousePos;

			int px = std::min(15, std::max(0, static_cast<int>(16.0f * mousePos.x / static_cast<float>(renderWindow.getSize().x))));
			int py = std::min(15, std::max(0, static_cast<int>(16.0f * mousePos.y / static_cast<float>(renderWindow.getSize().y))));

			for (int i = 0; i < 256; i++)
				rsdr.setInput(i, 0.0f);

			rsdr.setInput(px, py, 1.0f);
			//htsl.setInput(0, mousePos.x / static_cast<float>(renderWindow.getSize().x));
			//htsl.setInput(1, mousePos.y / static_cast<float>(renderWindow.getSize().y));

			rsdr.simStep();
			

			tickCounter = 0;
		}
		else
			tickCounter++;

		sdr::PredictiveRSDR copy = rsdr;

		for (int s = 0; s < predSteps; s++) {
			copy.setInput(0, copy.getPrediction(0));
			copy.setInput(1, copy.getPrediction(1));
			copy.setInput(2, copy.getPrediction(2));
			copy.setInput(3, copy.getPrediction(3));

			copy.simStep(false);
		}

		sf::Vector2f predPos;

		float div = 0.0f;

		for (int i = 0; i < 256; i++) {
			int x = i % 16;
			int y = i / 16;

			float v = copy.getPrediction(i);

			predPos += v * sf::Vector2f(x / 16.0f * renderWindow.getSize().x, y / 16.0f * renderWindow.getSize().y);
			div += v;
		}

		if (div != 0.0f)
			predPos /= div;

		predictRenderPos += 0.2f * (predPos - predictRenderPos);

		for (int t = trailBufferLength - 1; t > 0; t--) {
			predTrailBuffer[t] = predTrailBuffer[t - 1];
			actualTrailBuffer[t] = actualTrailBuffer[t - 1];
		}

		predTrailBuffer[0] = predictRenderPos;
		actualTrailBuffer[0] = sf::Vector2f(mousePos.x, mousePos.y);

		float intensity = 1.0f;

		sf::VertexArray predVertices;
		predVertices.setPrimitiveType(sf::LinesStrip);
		predVertices.resize(trailBufferLength);

		sf::VertexArray actualVertices;
		actualVertices.setPrimitiveType(sf::LinesStrip);
		actualVertices.resize(trailBufferLength);

		for (int t = 0; t < trailBufferLength; t++) {	
			actualVertices[t].position = actualTrailBuffer[t];
			actualVertices[t].color = sf::Color(255, 0, 0, 255 * intensity);

			predVertices[t].position = predTrailBuffer[t];
			predVertices[t].color = sf::Color(0, 255, 0, 255 * intensity);

			intensity *= trailDecay;
		}

		renderWindow.draw(actualVertices);
		renderWindow.draw(predVertices);

		float alignment = 0.0f;

		float scale = 8.0f;

		for (int l = 0; l < rsdr.getLayers().size(); l++) {
			sf::Image sdr;
			sdr.create(rsdr.getLayerDescs()[l]._width, rsdr.getLayerDescs()[l]._height);

			for (int x = 0; x < rsdr.getLayerDescs()[l]._width; x++)
				for (int y = 0; y < rsdr.getLayerDescs()[l]._height; y++) {
					sf::Color c;
					c.r = c.g = c.b = rsdr.getLayers()[l]._sdr.getHiddenState(x, y) * 255.0f;

					sdr.setPixel(x, y, c);
				}

			sf::Texture sdrt;
			sdrt.loadFromImage(sdr);

			alignment += scale * sdr.getSize().x;

			sf::Sprite sdrs;
			sdrs.setTexture(sdrt);
			sdrs.setPosition(renderWindow.getSize().x - alignment, renderWindow.getSize().y - sdr.getSize().y * scale);
			sdrs.setScale(scale, scale);

			vis::PrettySDR psdr;
			psdr.create(rsdr.getLayerDescs()[l]._width, rsdr.getLayerDescs()[l]._height);

			for (int x = 0; x < rsdr.getLayerDescs()[l]._width; x++)
				for (int y = 0; y < rsdr.getLayerDescs()[l]._height; y++) {
					psdr.at(x, y) = rsdr.getLayers()[l]._predictionNodes[x + y * rsdr.getLayerDescs()[l]._width]._statePrev;
				}

			psdr._nodeSpaceSize = scale;
			psdr.draw(renderWindow, sf::Vector2f(renderWindow.getSize().x - alignment, renderWindow.getSize().y - sdr.getSize().y * scale));

			//renderWindow.draw(sdrs);
		}

		renderWindow.display();
	} while (!quit);

	return 0;
}
Exemple #16
0
 Config()
     : file_version(FILE_VERSION)
     , bbs_name_sysop("New OBV2 XRM Sysop")
     , bbs_name("New OBV2 XRM BBS")
     , bbs_uuid("")
     , password_system("system")
     , password_sysop("sysop")
     , password_newuser("newuser")
     , port_telnet(6023)
     , port_ssl(443)
     , use_service_telnet(true)
     , use_service_ssl(false)
     , directory_screens("")
     , directory_boards("")
     , directory_files("")
     , directory_data("")
     , directory_menu("")
     , directory_work("")
     , directory_text_files("")
     , directory_file_mail("")
     , directory_doors("")
     , directory_log("")
     , directory_scripts("")
     , directory_prompts("")
     , points_per_kilobyte(0)
     , points_earned_postcall(0)
     , access_sysop("s255")
     , access_message_sysop("s200")
     , access_file_sysop("s200")
     , access_hidden_files("s200")
     , access_post_anonymous("s20")
     , access_mail_attachment("s20")
     , access_top_ten("s20")
     , access_check_sysop_avail("s20")
     , invalid_password_attempts(3)
     , invalid_newuser_password_attempts(3)
     , use_file_points(false)
     , use_postcall_ratio(false)
     , use_library_ansi(true)
     , use_notify_on_logins(true)
     , use_notify_on_logoff(true)
     , use_log_chat_sessions(true)
     , use_screen_prelogin(false)
     , use_screen_welcome(false)
     , use_matrix_login(true)
     , use_newuser_password(true)
     , use_disclaimer(true)
     , use_address(true)
     , use_handle(true)
     , use_real_name(true)
     , use_location(true)
     , use_country(true)
     , use_email(true)
     , use_user_note(true)
     , use_birthdate(true)
     , use_gender(true)
     , use_challenge_question(true)
     , use_yesno_bars(true)
     , use_pause(true)
     , use_clear_screen(true)
     , use_ansi_color(true)
     , use_backspace(true)        
     , hidden_input_character('*')        
     , use_auto_validate_users(false)
     , use_newuser_voting(false)
     , use_auto_kick_unvalidated(false)        
     , newuser_votes_validate(3)
     , newuser_votes_delete(3)
     , newuser_days_to_upload(7)
     , days_keep_logs(30)
     , qwk_packet_name("Obv2_XRM")
     , starting_menu_name("top")
     , use_message_attachments(false)
     , days_keep_attachments(30)
     , default_color_regular("|09")
     , default_color_stat("|03")
     , default_color_propmpt("|01")
     , default_color_input("|15")
     , default_color_inverse("|17")
     , default_color_box("|11")
     , default_user_flags("")
     , flag_change_daily("")
     , flag_change_session("")
     , default_level(20)
     , default_file_level(20)
     , default_message_level(20)
     , default_file_points(0)
     , default_file_ratio(0)
     , default_kilobyte_ratio(0)
     , default_kilobyte_daily(0)
     , default_post_call_ratio(0)
     , default_time_limit(120)
     , default_user_timeout(20)        
     , use_auto_validate_files(false)
     , use_upload_checker(false) // default to true lateron!        
     , cmdline_virus_scan("")
     , filename_bbs_ad("")
     , filename_archive_comments("")
     , directory_bad_files("")        
     , use_greater_then_for_quotes(false)        
     , regexp_generic_validation("[^\\s][\\A\\w\\s,.!@#$%^&*()]+")  // testing no starting spaces!
     , regexp_generic_validation_msg("At least one AlphaNumeric Word characters required space seperators.")        
     , regexp_handle_validation("(?=.*[a-zA-Z])(?!.*\\d).{2,}")
     , regexp_handle_validation_msg("At least two characters case insensitive no spaces.")        
     , regexp_password_validation("(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).{8,}")
     , regexp_password_validation_msg("At least one lower, one upper, one digit and minimum of 8.")        
     , regexp_date_validation("(19|20)\\d\\d([- /.])(0[1-9]|1[012])\\2(0[1-9]|[12][0-9]|3[01])")
     , regexp_date_validation_msg("Must be a valid year matching UTC Format yyyy-mm-dd")        
     , regexp_email_validation("[\\w.]+[@]{1}[\\w]+[.]*[\\w]*")
     , regexp_email_validation_msg("Must be a valid email at the very lest name@domain")
 {
     // Generates an Initial Unique Board UUID when the configuration is created.
     // If someone wipes out their config, they should save this and re-enter it!
     boost::uuids::random_generator generator;
     boost::uuids::uuid uuid = generator();
     bbs_uuid = boost::lexical_cast<std::string>(uuid);
 }
void thread_mcl::run_normal(){
    //--- SETTING VARIABLES ---
    int T = 0;
    int timeSleep = 90000;
    bool flag_neff = false;
    float noise_foward = 0.01;
    float noise_turn = 0.01;
    float noise_sense = 3.0;
    movement mv;
    random_device generator;
    mt19937 gen(generator());

    uniform_int_distribution<int> randomDist(1, 3);
    uniform_real_distribution<float> randomTh(-.5,.5);
    //-------------------------

    robo->representation();

    myMcl->set_noise_particles(noise_foward, noise_turn, noise_sense);

    if(localization) //TRUE = LOCAL
        myMcl->set_position(robo->robot_pose);

    this->myMap->set_empty_map(); //SET EMPTY MAP - KLD sampling

    while(true){
        mv.dist = randomDist(gen);
        mv.angle = randomTh(gen);

        img = myMcl->Gera_Imagem_Pixmap(this->robo);

        robo->move(mv);

        myMcl->sampling(mv);
        state = "\n\t\t\t  Sampling";
        usleep(timeSleep);

        myMcl->weight_particles(robo->sense());
        state = "\n\t\t\t  Weighting";
        usleep(timeSleep);

        if(flag_neff){ //TRUE = neff on  - FALSE = neff off

            float neff2 = myMcl->number_effective();
            if(neff2 < myMcl->num_particles/2){
                cout<<"NEFF: "<<neff2<<" - Vou fazer resample ";
//                myMcl->resample();
                myMcl->resample_Roleta();
                state = "\n\t\t\t  Resampling";
                usleep(timeSleep);
            }
            neff = QString::number(neff2);
        }else{
            myMcl->resample_Roleta();
            state = "\n\t\t\t  Resampling";
            usleep(timeSleep);
            neff = "OFF";
        }
        cout<<"T:"<<T++<<endl;
    }
}
Exemple #18
0
 vector<string> generateParenthesis(int n) {
 	vector<string> res;
 	string s;
 	generator(res, s, n, 0, 0);
 	return res;
 }
Exemple #19
0
int main(int argc, char* argv[])
{
	// Define arguments.
	struct arg_lit* show_help = arg_lit0("h", "help", "Show this help.");
	struct arg_str* type_assembler = arg_str0("t", NULL, "<type>", "The type of assembler to output for.");
	struct arg_file* input_file = arg_file1(NULL, NULL, "<file>", "The input file (or - to read from standard input).");
	struct arg_file* output_file = arg_file1("o", "output", "<file>", "The output file (or - to send to standard output).");
	struct arg_end *end = arg_end(20);
	void *argtable[] = { output_file, show_help, type_assembler, input_file, end };

	// Parse arguments.
	int nerrors = arg_parse(argc,argv,argtable);
	if (nerrors != 0 || show_help->count != 0)
	{
		if (show_help->count != 0)
			arg_print_errors(stdout, end, "compiler");
		fprintf(stderr, "syntax:\n    compiler");
		arg_print_syntax(stdout, argtable, "\n");
		fprintf(stderr, "options:\n");
		arg_print_glossary(stdout, argtable, "    %-25s %s\n");
		return 1;
	}

	// Parse C.
	pp_add_search_path(".");
	pp_add_search_path("include");
	pp_add_search_path(dirname<std::string>(input_file->filename[0]).c_str());
	yyout = stderr;
	yyin = pp_do(input_file->filename[0]);
	if (yyin == NULL)
	{
		pp_cleanup();
		return 1;
	}
	yyparse();
	if (yyin != stdin)
		fclose(yyin);
	pp_cleanup();
	if (program == NULL)
	{
		std::cerr << "An error occurred while compiling." << std::endl;
		return 1;
	}

	// Assembler type.
	const char* asmtype = "dcpu16toolchain";
	if (type_assembler->count > 0)
		asmtype = type_assembler->sval[0];

	// Spacing.
	std::cerr << std::endl;

	// Generate assembly using the AST.
	try
	{
		AsmGenerator generator(asmtype);
		AsmBlock* block = program->compile(generator);
		if (strcmp(output_file->filename[0], "-") == 0)
		{
			std::cout << generator.m_Preassembly << std::endl;
			std::cout << *block << std::endl;
			std::cout << generator.m_Postassembly << std::endl;
		}
		else
		{
			std::ofstream output(output_file->filename[0], std::ios::out | std::ios::trunc);
			output << generator.m_Preassembly << std::endl;
			output << *block << std::endl;
			output << generator.m_Postassembly << std::endl;
			output.close();
		}
		delete block;
	}
	catch (CompilerException* ex)
	{
		std::string msg = ex->getMessage();
		std::cerr << "An error occurred while compiling." << std::endl;
		std::cerr << msg << std::endl;
		return 1;
	}
	
	return 0;
}
//////////////////////////////////
// The new main function to call the Ocelot tracer and the original main
//////////////////////////////////
int main(int argc, char** argv) {
    TraceGenerator generator(argv[2], argv[1]);
    ocelot::addTraceGenerator(generator);
    original_main(argc - 2,argv + 2);
    return 0;
}
    void TestDivideElementAlongGivenAxis()
    {
        // Create mesh
        CylindricalHoneycombVertexMeshGenerator generator(4, 4);
        Cylindrical2dVertexMesh* p_mesh = generator.GetCylindricalMesh();

        TS_ASSERT_EQUALS(p_mesh->GetNumElements(), 16u);
        TS_ASSERT_EQUALS(p_mesh->GetNumNodes(), 40u);

        c_vector<double, 2> axis_of_division;
        axis_of_division(0) = 1.0/sqrt(2.0);
        axis_of_division(1) = 1.0/sqrt(2.0);

        // Divide non-periodic element
        unsigned new_element_index = p_mesh->DivideElementAlongGivenAxis(p_mesh->GetElement(2), axis_of_division, true);

        TS_ASSERT_EQUALS(new_element_index, 16u);
        TS_ASSERT_EQUALS(p_mesh->GetNumElements(), 17u);
        TS_ASSERT_EQUALS(p_mesh->GetNumNodes(), 42u);

        TS_ASSERT_DELTA(p_mesh->GetNode(40)->rGetLocation()[0], 2.8660, 1e-4);
        TS_ASSERT_DELTA(p_mesh->GetNode(40)->rGetLocation()[1], 0.9433, 1e-4);

        TS_ASSERT_DELTA(p_mesh->GetNode(41)->rGetLocation()[0], 2.1339, 1e-4);
        TS_ASSERT_DELTA(p_mesh->GetNode(41)->rGetLocation()[1], 0.2113, 1e-4);

        // Test new elements have correct nodes
        TS_ASSERT_EQUALS(p_mesh->GetElement(2)->GetNumNodes(), 5u);
        TS_ASSERT_EQUALS(p_mesh->GetElement(2)->GetNode(0)->GetIndex(), 2u);
        TS_ASSERT_EQUALS(p_mesh->GetElement(2)->GetNode(1)->GetIndex(), 7u);
        TS_ASSERT_EQUALS(p_mesh->GetElement(2)->GetNode(2)->GetIndex(), 11u);
        TS_ASSERT_EQUALS(p_mesh->GetElement(2)->GetNode(3)->GetIndex(), 40u);
        TS_ASSERT_EQUALS(p_mesh->GetElement(2)->GetNode(4)->GetIndex(), 41u);

        TS_ASSERT_EQUALS(p_mesh->GetElement(16)->GetNumNodes(), 5u);
        TS_ASSERT_EQUALS(p_mesh->GetElement(16)->GetNode(0)->GetIndex(), 40u);
        TS_ASSERT_EQUALS(p_mesh->GetElement(16)->GetNode(1)->GetIndex(), 14u);
        TS_ASSERT_EQUALS(p_mesh->GetElement(16)->GetNode(2)->GetIndex(), 10u);
        TS_ASSERT_EQUALS(p_mesh->GetElement(16)->GetNode(3)->GetIndex(), 6u);
        TS_ASSERT_EQUALS(p_mesh->GetElement(16)->GetNode(4)->GetIndex(), 41u);

        // Divide periodic element
        new_element_index = p_mesh->DivideElementAlongGivenAxis(p_mesh->GetElement(3), axis_of_division, true);

        TS_ASSERT_EQUALS(new_element_index, 17u);
        TS_ASSERT_EQUALS(p_mesh->GetNumElements(), 18u);
        TS_ASSERT_EQUALS(p_mesh->GetNumNodes(), 44u);

        TS_ASSERT_DELTA(p_mesh->GetNode(42)->rGetLocation()[0], -0.1339, 1e-4);
        TS_ASSERT_DELTA(p_mesh->GetNode(42)->rGetLocation()[1], 0.9433, 1e-4);

        TS_ASSERT_DELTA(p_mesh->GetNode(43)->rGetLocation()[0], 3.1339, 1e-4);
        TS_ASSERT_DELTA(p_mesh->GetNode(43)->rGetLocation()[1], 0.2113, 1e-4);

        // Test new elements have correct nodes
        TS_ASSERT_EQUALS(p_mesh->GetElement(3)->GetNumNodes(), 5u);
        TS_ASSERT_EQUALS(p_mesh->GetElement(3)->GetNode(0)->GetIndex(), 3u);
        TS_ASSERT_EQUALS(p_mesh->GetElement(3)->GetNode(1)->GetIndex(), 4u);
        TS_ASSERT_EQUALS(p_mesh->GetElement(3)->GetNode(2)->GetIndex(), 8u);
        TS_ASSERT_EQUALS(p_mesh->GetElement(3)->GetNode(3)->GetIndex(), 42u);
        TS_ASSERT_EQUALS(p_mesh->GetElement(3)->GetNode(4)->GetIndex(), 43u);

        TS_ASSERT_EQUALS(p_mesh->GetElement(17)->GetNumNodes(), 5u);
        TS_ASSERT_EQUALS(p_mesh->GetElement(17)->GetNode(0)->GetIndex(), 42u);
        TS_ASSERT_EQUALS(p_mesh->GetElement(17)->GetNode(1)->GetIndex(), 15u);
        TS_ASSERT_EQUALS(p_mesh->GetElement(17)->GetNode(2)->GetIndex(), 11u);
        TS_ASSERT_EQUALS(p_mesh->GetElement(17)->GetNode(3)->GetIndex(), 7u);
        TS_ASSERT_EQUALS(p_mesh->GetElement(17)->GetNode(4)->GetIndex(), 43u);
    }
Exemple #22
0
int tester(void)
{
	int i,j;
	int e = 0;

	fld = malloc(NROWS * sizeof(int *));/*[5][5] = {
	    {1,6,11,16,21},
	    {2,7,12,17,22},
	    {3,8,13,18,23},
	    {4,9,14,19,24},
	    {5,10,15,20,25}
	};*/
	if(fld == NULL){
		printf("Oops, couldn't ``malloc''?");
		return(1);
	}
	for(i=0; i<NROWS; i++){
		fld[i] = malloc(NCOLS * sizeof(int));
		if(fld[i] == NULL){
			printf("Hmm, couldn't do the second-dimension ``malloc''.");
			return(1);
		}
	}

	/* Initialize the array! */
	for(j=0;j<NROWS;j++){
		for(i=0;i<NCOLS;i++){
			fld[i][j] = e;
			e++;
		}
	}
			

	#ifdef TEST
	for(j=0;j<NROWS;j++){
		for(i=0;i<NCOLS;i++){
			printf("%d\t",fld[i][j]);
			if((i+1) == x) printf("\n");
		}
	}
	#endif

	printf("About to test the printer function.\n\n");
	viz(fld);
	/* Should show:
	0	1	2
	3	4	5
	6	7	8
	Or some similar such, depending on NCOLS and NROWS
	*/

	/* Kill all cells! They should be all 0's now.*/
	for(j=0;j<NROWS;j++){
		for(i=0;i<NCOLS;i++){
			killf(i,j);
		}
	}
	viz(fld);
	/* Spawn all cells! They should be all 1's now.*/
	for(j=0;j<NROWS;j++){
		for(i=0;i<NCOLS;i++){
			spawn(i,j);
		}
	}
	viz(fld);

	printf("A corner cell should have 3 live neighbours: %d\n", friends(0,0));
	printf("A middle cell should have 8 live neighbours: %d\n", friends(1,1));
	printf("A  side  cell should have 5 live neighbours: %d\n", friends(1,0));
	printf("Goodbye\n\n");

	/* Try some basic tests of the generator and rule. */
	for(j=0;j<NROWS;j++){
		for(i=0;i<NCOLS;i++){
			killf(i,j);
		}
	}
	spawn(0,1);
	spawn(1,1);
	spawn(2,1);
	viz(fld);
	generator(1);
	viz(fld);
	generator(1);
	viz(fld);

	

	printf("\n\nDone testing.\n\n");
	return(0);
}
    void TestArchiving() throw (Exception)
    {
        FileFinder archive_dir("archive", RelativeTo::ChasteTestOutput);
        std::string archive_file = "cylindrical_vertex_mesh_base.arch";
        ArchiveLocationInfo::SetMeshFilename("cylindrical_vertex_mesh");

        // Create mesh
        unsigned num_cells_across = 4;
        unsigned num_cells_up = 7;
        CylindricalHoneycombVertexMeshGenerator generator(num_cells_across, num_cells_up);
        AbstractMesh<2,2>* const p_saved_mesh = generator.GetCylindricalMesh();

        double crypt_width = num_cells_across;

        /*
         * You need the const above to stop a BOOST_STATIC_ASSERTION failure.
         * This is because the serialization library only allows you to save
         * tracked objects while the compiler considers them const, to prevent
         * the objects changing during the save, and so object tracking leading
         * to wrong results. For example, A is saved once via pointer, then
         * changed, then saved again.  The second save notes that A was saved
         * before, so doesn't write its data again, and the change is lost.
         */
        {
            // Serialize the mesh
            TS_ASSERT_DELTA((static_cast<Cylindrical2dVertexMesh*>(p_saved_mesh))->GetWidth(0), crypt_width, 1e-7);

            // Create output archive
            ArchiveOpener<boost::archive::text_oarchive, std::ofstream> arch_opener(archive_dir, archive_file);
            boost::archive::text_oarchive* p_arch = arch_opener.GetCommonArchive();

            // We have to serialize via a pointer here, or the derived class information is lost.
            (*p_arch) << p_saved_mesh;
        }

        {
            // De-serialize and compare
            AbstractMesh<2,2>* p_loaded_mesh;

            // Create an input archive
            ArchiveOpener<boost::archive::text_iarchive, std::ifstream> arch_opener(archive_dir, archive_file);
            boost::archive::text_iarchive* p_arch = arch_opener.GetCommonArchive();

            // Restore from the archive
            (*p_arch) >> p_loaded_mesh;

            // Compare the loaded mesh against the original
            Cylindrical2dVertexMesh* p_mesh2 = static_cast<Cylindrical2dVertexMesh*>(p_loaded_mesh);
            Cylindrical2dVertexMesh* p_mesh = static_cast<Cylindrical2dVertexMesh*>(p_saved_mesh);

            // Compare width
            TS_ASSERT_DELTA(p_mesh2->GetWidth(0), crypt_width, 1e-7);
            TS_ASSERT_DELTA(p_mesh->GetWidth(0), crypt_width, 1e-7);

            // Compare nodes
            TS_ASSERT_EQUALS(p_mesh->GetNumNodes(), p_mesh2->GetNumNodes());

            for (unsigned i=0; i<p_mesh->GetNumNodes(); i++)
            {
                Node<2>* p_node = p_mesh->GetNode(i);
                Node<2>* p_node2 = p_mesh2->GetNode(i);
                TS_ASSERT_EQUALS(p_node->IsDeleted(), p_node2->IsDeleted());
                TS_ASSERT_EQUALS(p_node->GetIndex(), p_node2->GetIndex());

                TS_ASSERT_EQUALS(p_node->IsBoundaryNode(), p_node2->IsBoundaryNode());
                for (unsigned j=0; j<2; j++)
                {
                    TS_ASSERT_DELTA(p_node->rGetLocation()[j], p_node2->rGetLocation()[j], 1e-4);
                }
            }

            // Compare elements
            TS_ASSERT_EQUALS(p_mesh->GetNumElements(), p_mesh2->GetNumElements());
            TS_ASSERT_EQUALS(p_mesh->GetNumAllElements(), p_mesh2->GetNumAllElements());

            for (unsigned i=0; i<p_mesh->GetNumElements(); i++)
            {
                VertexElement<2,2>* p_elt = p_mesh->GetElement(i);
                VertexElement<2,2>* p_elt2 = p_mesh2->GetElement(i);
                TS_ASSERT_EQUALS(p_elt->GetNumNodes(), p_elt2->GetNumNodes());
                for (unsigned j=0; j<p_elt->GetNumNodes(); j++)
                {
                    TS_ASSERT_EQUALS(p_elt->GetNodeGlobalIndex(j), p_elt2->GetNodeGlobalIndex(j));
                }
            }

            // Tidy up
            delete p_mesh2;
        }
    }
    void TestGrowApex() throw(Exception)
    {
#if defined(CHASTE_VTK) && ( (VTK_MAJOR_VERSION >= 5 && VTK_MINOR_VERSION >= 6) || VTK_MAJOR_VERSION >= 6)
        EXIT_IF_PARALLEL;

        vtkSmartPointer<vtkPolyData> sphere = CreateSphere(100);

        double min_branch_length = 0.01;
        unsigned point_limit = 5;
        double angle_limit = 180.0;
        double branching_fraction = 1.0;

        AirwayGenerator generator(sphere, min_branch_length, point_limit, angle_limit, branching_fraction);

        double origin[3] = {0.0, 1.0001, 0.0}; //to avoid bias in the splitting plane
        double direction[3] = {1.0, 0.0, 0.0};
        double parent_direction[3] = {1.0, 0.0, 0.0};

        generator.AddInitialApex(origin, direction, parent_direction, 10.0, 0);
        Apex& apex = generator.GetGenerations()[0].GetApices()[0];
        apex.mPointCloud = generator.CreatePointCloudUsingTargetPoints(5000);

        generator.GrowApex(apex);

        //Test that two branches were generated
        TS_ASSERT_EQUALS(generator.GetAirwayTree()->GetNumberOfPoints(), 3);
        TS_ASSERT_EQUALS(generator.GetAirwayTree()->GetNumberOfCells(), 2);

        //Test the exact generated locations
        double inserted_end_location1[3];
        generator.GetAirwayTree()->GetPoints()->GetPoint(1, inserted_end_location1);

        double inserted_end_location2[3];
        generator.GetAirwayTree()->GetPoints()->GetPoint(2, inserted_end_location2);

        //Generated points should have x ~= 0, y ~= 0.0,  z ~= +/- 3/8
        TS_ASSERT_DELTA(inserted_end_location1[0], 0.0, 1e-2);
        TS_ASSERT_DELTA(inserted_end_location1[1], 0.0, 1e-2);
        TS_ASSERT_DELTA(inserted_end_location1[2], -3.0/8.0, 1e-2);
        TS_ASSERT_DELTA(inserted_end_location2[0], 0.0, 1e-2);
        TS_ASSERT_DELTA(inserted_end_location2[1], 0.0, 1e-2);
        TS_ASSERT_DELTA(inserted_end_location2[2], 3.0/8.0, 1e-2);

        //Test that two child apices were created in generation 1
        TS_ASSERT_EQUALS(generator.GetGenerations()[1].GetApices().size(), 2u);

        //Check the start ids, parent directions and current directions of the two apices
        Apex& new_apex_1 = generator.GetGenerations()[1].GetApices()[0];
        Apex& new_apex_2 = generator.GetGenerations()[1].GetApices()[1];

        TS_ASSERT_EQUALS(new_apex_1.mStartId, 1);
        TS_ASSERT_EQUALS(new_apex_2.mStartId, 2);

        double branch_length = std::sqrt(9.0/64.0 + 1.0);

        TS_ASSERT_DELTA(new_apex_1.mOriginalDirection[0], 0.0, 1e-2);
        TS_ASSERT_DELTA(new_apex_1.mOriginalDirection[1], -1/branch_length, 1e-2);
        TS_ASSERT_DELTA(new_apex_1.mOriginalDirection[2], -3.0/8.0/branch_length, 1e-2);
        TS_ASSERT_DELTA(new_apex_2.mOriginalDirection[0], 0.0, 1e-2);
        TS_ASSERT_DELTA(new_apex_2.mOriginalDirection[1], -1/branch_length, 1e-2);
        TS_ASSERT_DELTA(new_apex_2.mOriginalDirection[2], 3.0/8.0/branch_length, 1e-2);

#endif
    }
Exemple #25
0
void defense_game::init_map(game *g)
{
 for (int x = 0; x < OMAPX; x++) {
  for (int y = 0; y < OMAPY; y++) {
   g->cur_om->ter(x, y, 0) = ot_field;
   g->cur_om->seen(x, y, 0) = true;
  }
 }

 g->cur_om->save();
 g->levx = 100;
 g->levy = 100;
 g->levz = 0;
 g->u.posx = SEEX;
 g->u.posy = SEEY;

 switch (location) {

 case DEFLOC_HOSPITAL:
  for (int x = 49; x <= 51; x++) {
   for (int y = 49; y <= 51; y++)
    g->cur_om->ter(x, y, 0) = ot_hospital;
  }
  g->cur_om->ter(50, 49, 0) = ot_hospital_entrance;
  break;

 case DEFLOC_MALL:
  for (int x = 49; x <= 51; x++) {
   for (int y = 49; y <= 51; y++)
    g->cur_om->ter(x, y, 0) = ot_megastore;
  }
  g->cur_om->ter(50, 49, 0) = ot_megastore_entrance;
  break;

 case DEFLOC_BAR:
  g->cur_om->ter(50, 50, 0) = ot_bar_north;
  break;

 case DEFLOC_MANSION:
  for (int x = 49; x <= 51; x++) {
   for (int y = 49; y <= 51; y++)
    g->cur_om->ter(x, y, 0) = ot_mansion;
  }
  g->cur_om->ter(50, 49, 0) = ot_mansion_entrance;
  break;
 }
// Init the map
 int old_percent = 0;
 for (int i = 0; i <= MAPSIZE * 2; i += 2) {
  for (int j = 0; j <= MAPSIZE * 2; j += 2) {
   int mx = g->levx - MAPSIZE + i, my = g->levy - MAPSIZE + j;
   int percent = 100 * ((j / 2 + MAPSIZE * (i / 2))) /
                       ((MAPSIZE) * (MAPSIZE + 1));
   if (percent >= old_percent + 1) {
    popup_nowait("Please wait as the map generates [%s%d%]",
                 (percent < 10 ? " " : ""), percent);
    old_percent = percent;
   }
// Round down to the nearest even number
   mx -= mx % 2;
   my -= my % 2;
   tinymap tm(&g->itypes, &g->mapitems, &g->traps);
   tm.generate(g, g->cur_om, mx, my, 0, int(g->turn));
   tm.clear_spawns();
   tm.clear_traps();
   tm.save(g->cur_om, int(g->turn), mx, my, 0);
  }
 }

 g->m.load(g, g->levx, g->levy, g->levz, true);

 g->update_map(g->u.posx, g->u.posy);
 monster generator(g->mtypes[mon_generator], g->u.posx + 1, g->u.posy + 1);
// Find a valid spot to spawn the generator
 std::vector<point> valid;
 for (int x = g->u.posx - 1; x <= g->u.posx + 1; x++) {
  for (int y = g->u.posy - 1; y <= g->u.posy + 1; y++) {
   if (generator.can_move_to(g, x, y) && g->is_empty(x, y))
    valid.push_back( point(x, y) );
  }
 }
 if (!valid.empty()) {
  point p = valid[rng(0, valid.size() - 1)];
  generator.spawn(p.x, p.y);
 }
 generator.friendly = -1;
 g->z.push_back(generator);
}
//
//    void xxxTestGrowTerminalPointsApex() throw(Exception)
//    {
//#if defined(CHASTE_VTK) && ( (VTK_MAJOR_VERSION >= 5 && VTK_MINOR_VERSION >= 6) || VTK_MAJOR_VERSION >= 6)
//        EXIT_IF_PARALLEL;
//
//        vtkSmartPointer<vtkPolyData> sphere = CreateSphere();
//
//        AirwayGenerator generator(sphere, 0.1, 51);
//
//        double origin[3] = {0.0, 1.0, 0.0};
//        double direction[3] = {0.0, -1.0, 0.0};
//
//        generator.AddInitialApex(origin, direction, 10.0, 1, generator.CreatePointCloud(50));
//        generator.GrowCurrentApex();
//
//        //Test that the branch was generated
//        TS_ASSERT_EQUALS(generator.GetAirwayTree()->GetNumberOfPoints(), 2);
//        TS_ASSERT_EQUALS(generator.GetAirwayTree()->GetNumberOfCells(), 1);
//
//        //Test that no child apices were created
//        TS_ASSERT_EQUALS(generator.GetApices().size(), 0u);
//#endif
//    }
//
//
//
    void TestCheckAngleAndLength() throw(Exception)
    {
#if defined(CHASTE_VTK) && ( (VTK_MAJOR_VERSION >= 5 && VTK_MINOR_VERSION >= 6) || VTK_MAJOR_VERSION >= 6)
        EXIT_IF_PARALLEL;

        vtkSmartPointer<vtkPolyData> sphere = CreateSphere();

        //Check the angle code works for right angles
        {
            AirwayGenerator generator(sphere, 0.1, 5, 45, 0.5);

            double origin[3] = {0.0, 1.0, 0.0};
            double direction[3] = {0.0, -1.0, 0.0};

            double centre[3] = {1.0, 1.0, 0.0}; //Requires rotating and scaling

            generator.AddInitialApex(origin, direction, direction, 10.0, 1);

            generator.CheckBranchAngleLengthAndAdjust(0, direction, centre);

            TS_ASSERT_DELTA(centre[0], 0.5*1.0/std::sqrt(2.0), 1e-6);
            TS_ASSERT_DELTA(centre[1], 1.0 - 0.5*1/std::sqrt(2.0), 1e-6);
            TS_ASSERT_DELTA(centre[2], 0.0, 1e-6);
        }

        //Check the angle code works for acute angles
        {
            AirwayGenerator generator(sphere, 0.1, 5, 0.0, 1.0); //No branching angle allowed

            double origin[3] = {0.0, 1.0, 0.0};
            double direction[3] = {0.0, -1.0, 0.0};

            double centre[3] = {1/std::sqrt(2.0), 1.0-1/std::sqrt(2.0), 0.0};

            generator.AddInitialApex(origin, direction, direction, 10.0, 1);

            generator.CheckBranchAngleLengthAndAdjust(0, direction, centre);

            TS_ASSERT_DELTA(centre[0], 0.0, 1e-6);
            TS_ASSERT_DELTA(centre[1], 0.0, 1e-6);
            TS_ASSERT_DELTA(centre[2], 0.0, 1e-6);
        }

        //check the code works for obtuse angles
        {
            AirwayGenerator generator(sphere, 0.1, 5, 90, 1.0);

            double origin[3] = {0.0, 1.0, 0.0};
            double direction[3] = {0.0, -1.0, 0.0};

            double centre[3] = {1.0, 2.0, 0.0}; //results in a vector of length sqrt(2.0)

            generator.AddInitialApex(origin, direction, direction, 10.0, 1);

            generator.CheckBranchAngleLengthAndAdjust(0, direction, centre);

            TS_ASSERT_DELTA(centre[0], std::sqrt(2.0), 1e-6);
            TS_ASSERT_DELTA(centre[1], 1.0, 1e-6);
            TS_ASSERT_DELTA(centre[2], 0.0, 1e-6);
        }
#endif
    }
Exemple #27
0
int main() {
	std::mt19937 generator(time(nullptr));

	sys::ComputeSystem cs;

	cs.create(sys::ComputeSystem::_gpu);

	sys::ComputeProgram prog;

	prog.loadFromFile("resources/neoKernels.cl", cs);

	std::vector<Level> levels;

	std::unordered_set<char> tileDataCharset;
	std::unordered_set<char> objectDataCharset;

	loadLevels("userlevels.txt", levels, tileDataCharset, objectDataCharset);

	// --------------------------- Create the Sparse Coder ---------------------------

	const int numTiles = levels.front()._tileData.length();

	const int charsetSize = 128 + 2; // + 2 indicating the portion it is on (01 for tiles, 10 for objects)

	const cl::size_type visDim = std::ceil(std::sqrt(static_cast<float>(charsetSize)));
	const int visArea = visDim * visDim;

	const int maxObjects = 1000;

	cl::Image2D input = cl::Image2D(cs.getContext(), CL_MEM_READ_WRITE, cl::ImageFormat(CL_R, CL_FLOAT), visDim, visDim);

	std::vector<float> inputData(visArea, 0.0f);
	std::vector<float> predData(visArea, 0.0f);

	std::vector<neo::PredictiveHierarchy::LayerDesc> layerDescs(3);

	layerDescs[0]._size = { 16, 16 };
	layerDescs[1]._size = { 16, 16 };
	layerDescs[2]._size = { 16, 16 };

	neo::PredictiveHierarchy ph;

	ph.createRandom(cs, prog, { static_cast<int>(visDim), static_cast<int>(visDim) }, layerDescs, { -0.01f, 0.01f }, generator);

	ph._whiteningKernelRadius = 1;

	// Learn levels
	std::uniform_int_distribution<int> levelDist(0, levels.size() - 1);

	for (int iter = 0; iter < 20; iter++) {
		// Choose random level
		int index = levelDist(generator);

		const Level &l = levels[index];

		// Set mode for tiles
		inputData[charsetSize - 2] = 0.0f;
		inputData[charsetSize - 1] = 1.0f;

		// Run through once to get PH ready
		inputData['#'] = 1.0f;

		cs.getQueue().enqueueWriteImage(input, CL_TRUE, cl::array<cl::size_type, 3> { 0, 0, 0 }, cl::array<cl::size_type, 3> { visDim, visDim, 1 }, 0, 0, inputData.data());

		ph.simStep(cs, input);

		inputData['#'] = 0.0f;

		// Run through tile data
		for (int i = 0; i < l._tileData.length(); i++) {
			// Set character to 1
			inputData[l._tileData[i]] = 1.0f;

			cs.getQueue().enqueueWriteImage(input, CL_TRUE, cl::array<cl::size_type, 3> { 0, 0, 0 }, cl::array<cl::size_type, 3> { visDim, visDim, 1 }, 0, 0, inputData.data());

			ph.simStep(cs, input);

			// Unset character
			inputData[l._tileData[i]] = 0.0f;
		}

		// Set mode for objects
		inputData[charsetSize - 2] = 1.0f;
		inputData[charsetSize - 1] = 0.0f;

		// Run through once to get PH ready
		inputData['#'] = 1.0f;

		cs.getQueue().enqueueWriteImage(input, CL_TRUE, { 0, 0, 0 }, { visDim, visDim, 1 }, 0, 0, inputData.data());

		ph.simStep(cs, input);

		inputData['#'] = 0.0f;

		// Run through object data
		for (int i = 0; i < l._objectData.length(); i++) {
			// Set character to 1
			inputData[l._objectData[i]] = 1.0f;

			cs.getQueue().enqueueWriteImage(input, CL_TRUE, { 0, 0, 0 }, { visDim, visDim, 1 }, 0, 0, inputData.data());

			ph.simStep(cs, input);

			// Unset character
			inputData[l._objectData[i]] = 0.0f;
		}

		std::cout << "Went over level #" << (index + 1) << " \"" << l._name << "\"" << std::endl;
	}

	// Generate new maps
	std::ofstream toFile("generatedNLevels.txt");

	std::normal_distribution<float> noiseDist(0.0f, 1.0f);

	for (int i = 0; i < 10; i++) {
		toFile << "$" << "Generated Level " << (i + 1) << "#NeoRL#Experimental#";

		// Generated level data


		// Set mode for tiles
		inputData[charsetSize - 2] = 0.0f;
		inputData[charsetSize - 1] = 1.0f;

		// Run through once to get PH ready
		//cs.getQueue().enqueueWriteImage(input, CL_TRUE, cl::array<cl::size_type, 3> { 0, 0, 0 }, cl::array<cl::size_type, 3> { visDim, visDim, 1 }, 0, 0, inputData.data());

		//ph.simStep(cs, input);

		char prevChar = 0;

		for (int i = 0; i < numTiles; i++) {
			// Set character to 1
			inputData[prevChar] = 1.0f;

			cs.getQueue().enqueueWriteImage(input, CL_TRUE, cl::array<cl::size_type, 3> { 0, 0, 0 }, cl::array<cl::size_type, 3> { visDim, visDim, 1 }, 0, 0, inputData.data());

			ph.simStep(cs, input, false);

			// Unset character
			inputData[prevChar] = 0.0f;

			char newChar = 0;

			cs.getQueue().enqueueReadImage(ph.getPrediction(), CL_TRUE, cl::array<cl::size_type, 3> { 0, 0, 0 }, cl::array<cl::size_type, 3> { visDim, visDim, 1 }, 0, 0, predData.data());
	
			for (int j = 1; j < charsetSize - 2; j++)
				if (predData[j] > predData[newChar])
					newChar = j;

			// Add new character
			toFile << newChar;

			prevChar = newChar;
		}

		toFile << "|";

		// Set mode for objects
		inputData[charsetSize - 2] = 1.0f;
		inputData[charsetSize - 1] = 0.0f;

		// Run through once to get PH ready
		//cs.getQueue().enqueueWriteImage(input, CL_TRUE, cl::array<cl::size_type, 3> { 0, 0, 0 }, cl::array<cl::size_type, 3> { visDim, visDim, 1 }, 0, 0, inputData.data());

		//ph.simStep(cs, input);

		prevChar = 0;

		for (int i = 0; i < maxObjects; i++) {
			// Set character to 1
			inputData[prevChar] = 1.0f;

			std::vector<float> noisyInputData = inputData;

			for (int j = 0; j < noisyInputData.size(); j++) {
				noisyInputData[j] += noiseDist(generator) * 0.1f;
			}

			cs.getQueue().enqueueWriteImage(input, CL_TRUE, cl::array<cl::size_type, 3> { 0, 0, 0 }, cl::array<cl::size_type, 3> { visDim, visDim, 1 }, 0, 0, inputData.data());

			ph.simStep(cs, input, false);

			// Unset character
			inputData[prevChar] = 0.0f;

			char newChar = 0;

			cs.getQueue().enqueueReadImage(ph.getPrediction(), CL_TRUE, cl::array<cl::size_type, 3> { 0, 0, 0 }, cl::array<cl::size_type, 3> { visDim, visDim, 1 }, 0, 0, predData.data());

			for (int j = 1; j < charsetSize - 2; j++)
				if (predData[j] > predData[newChar])
					newChar = j;

			// If is delimiter, break
			if (newChar == '#')
				break;

			// Add new character
			toFile << newChar;

			prevChar = newChar;
		}

		toFile << "#" << std::endl << std::endl;
	}

	return 0;
}
    void TestHorsfieldOrder() throw(Exception)
    {
#if defined(CHASTE_VTK) && ( (VTK_MAJOR_VERSION >= 5 && VTK_MINOR_VERSION >= 6) || VTK_MAJOR_VERSION >= 6)
        EXIT_IF_PARALLEL;

        vtkSmartPointer<vtkPolyData> sphere = CreateSphere();

        AirwayGenerator generator(sphere, 0.1, 10);
        generator.CreatePointCloudUsingTargetPoints(50);

        double origin[3] = {0.0, 1.0, 0.0};
        double direction[3] = {0.0, -1.0, 0.0};

        generator.AddInitialApex(origin, direction, direction, 10.0, 1);
        generator.Generate();

        generator.CalculateHorsfieldOrder();

        //Test resulting orders, these have been calculated by hand for this tree
        vtkSmartPointer<vtkDataArray> order = generator.GetAirwayTree()->GetPointData()->GetArray("horsfield_order");
        TS_ASSERT_DELTA(order->GetTuple1(0), 4, 1e-6);
        TS_ASSERT_DELTA(order->GetTuple1(1), 3, 1e-6);
        TS_ASSERT_DELTA(order->GetTuple1(2), 3, 1e-6);
        TS_ASSERT_DELTA(order->GetTuple1(3), 2, 1e-6);
        TS_ASSERT_DELTA(order->GetTuple1(4), 1, 1e-6);
        TS_ASSERT_DELTA(order->GetTuple1(5), 2, 1e-6);
        TS_ASSERT_DELTA(order->GetTuple1(6), 2, 1e-6);
        TS_ASSERT_DELTA(order->GetTuple1(7), 1, 1e-6);
        TS_ASSERT_DELTA(order->GetTuple1(8), 1, 1e-6);
        TS_ASSERT_DELTA(order->GetTuple1(9), 1, 1e-6);
        TS_ASSERT_DELTA(order->GetTuple1(10), 1, 1e-6);
        TS_ASSERT_DELTA(order->GetTuple1(11), 1, 1e-6);
        TS_ASSERT_DELTA(order->GetTuple1(12), 1, 1e-6);

        generator.CalculateRadii(1.6);

        vtkSmartPointer<vtkDataArray> radii = generator.GetAirwayTree()->GetPointData()->GetArray("radius");

        double log_max_diameter = std::log10(20.0);
        double max_order = 4.0;
        double log_diameter_ratio = std::log10(1.6);

        for (int i = 0; i < radii->GetSize(); ++i)
        {
            TS_ASSERT_DELTA(radii->GetTuple1(i), std::pow(10.0, log_diameter_ratio*(order->GetTuple1(i) - max_order) + log_max_diameter)/2.0, 1e-4);
        }

        generator.MarkStartIds();
        vtkSmartPointer<vtkDataArray> start_ids = generator.GetAirwayTree()->GetPointData()->GetArray("start_id");

        TS_ASSERT_DELTA(start_ids->GetTuple1(0), 1.0, 1e-4);
        TS_ASSERT_DELTA(start_ids->GetTuple1(1), 0.0, 1e-4);
        TS_ASSERT_DELTA(start_ids->GetTuple1(2), 0.0, 1e-4);
        TS_ASSERT_DELTA(start_ids->GetTuple1(3), 0.0, 1e-4);
        TS_ASSERT_DELTA(start_ids->GetTuple1(4), 0.0, 1e-4);
        TS_ASSERT_DELTA(start_ids->GetTuple1(5), 0.0, 1e-4);
        TS_ASSERT_DELTA(start_ids->GetTuple1(6), 0.0, 1e-4);
        TS_ASSERT_DELTA(start_ids->GetTuple1(7), 0.0, 1e-4);
        TS_ASSERT_DELTA(start_ids->GetTuple1(8), 0.0, 1e-4);
        TS_ASSERT_DELTA(start_ids->GetTuple1(9), 0.0, 1e-4);
        TS_ASSERT_DELTA(start_ids->GetTuple1(10), 0.0, 1e-4);
        TS_ASSERT_DELTA(start_ids->GetTuple1(11), 0.0, 1e-4);
        TS_ASSERT_DELTA(start_ids->GetTuple1(12), 0.0, 1e-4);

        //To visualise
        /*OutputFileHandler output("TestAirwayGenerator");
        std::string output_file = output.GetOutputDirectoryFullPath() + "/test.vtp";

        vtkSmartPointer<vtkXMLPolyDataWriter> writer = vtkSmartPointer<vtkXMLPolyDataWriter>::New();
        writer->SetFileName(output_file.c_str());
#if VTK_MAJOR_VERSION >= 6
        writer->SetInputData(generator.GetAirwayTree());
#else
        writer->SetInput(generator.GetAirwayTree());
#endif
        writer->Write();*/
#endif
    }
Exemple #29
0
int main() {
	sf::RenderWindow window;

	sf::ContextSettings glContextSettings;
	glContextSettings.antialiasingLevel = 4;

	window.create(sf::VideoMode(800, 600), "BIDInet", sf::Style::Default, glContextSettings);

	window.setFramerateLimit(60);
	window.setVerticalSyncEnabled(true);

	std::mt19937 generator(time(nullptr));

	/*sys::ComputeSystem cs;

	cs.create(sys::ComputeSystem::_gpu);

	sys::ComputeProgram program;

	program.loadFromFile("resources/bidinet.cl", cs);

	bidi::BIDInet bidinet;

	std::vector<bidi::BIDInet::InputType> inputTypes(64, bidi::BIDInet::_state);

	const int numStates = 3 + 3 + 2 + 2 + 1 + 2 + 2;
	const int numActions = 3 + 3 + 2 + 2;
	const int numQ = 8;

	for (int i = 0; i < numStates; i++)
		inputTypes[i] = bidi::BIDInet::_state;

	for (int i = 0; i < numActions; i++)
		inputTypes[numStates + i] = bidi::BIDInet::_action;

	std::vector<bidi::BIDInet::LayerDesc> layerDescs(2);

	layerDescs[0]._fbRadius = 16;
	layerDescs[1]._width = 8;
	layerDescs[1]._height = 8;

	bidinet.createRandom(cs, program, 8, 8, inputTypes, layerDescs, -0.1f, 0.1f, 0.001f, 1.0f, generator);*/

	// Physics
	std::shared_ptr<b2World> world = std::make_shared<b2World>(b2Vec2(0.0f, -9.81f));

	const float pixelsPerMeter = 256.0f;

	const float groundWidth = 5000.0f;
	const float groundHeight = 5.0f;

	// Create ground
	b2BodyDef groundBodyDef;
	groundBodyDef.position.Set(0.0f, 0.0f);

	b2Body* groundBody = world->CreateBody(&groundBodyDef);

	b2PolygonShape groundBox;
	groundBox.SetAsBox(groundWidth * 0.5f, groundHeight * 0.5f);

	groundBody->CreateFixture(&groundBox, 0.0f);

	sf::Texture skyTexture;

	skyTexture.loadFromFile("resources/background1.png");

	skyTexture.setSmooth(true);

	sf::Texture floorTexture;
	
	floorTexture.loadFromFile("resources/floor1.png");

	floorTexture.setRepeated(true);
	floorTexture.setSmooth(true);

	Runner runner0;

	runner0.createDefault(world, b2Vec2(0.0f, 2.762f), 0.0f, 1);

	//Runner runner1;

	//runner1.createDefault(world, b2Vec2(0.0f, 2.762f), 0.0f, 2);

	//deep::FERL ferl;

	const int recCount = 4;
	const int clockCount = 4;

	//ferl.createRandom(3 + 3 + 2 + 2 + 1 + 2 + 2 + recCount + clockCount, 3 + 3 + 2 + 2 + recCount, 32, 0.01f, generator);

	//std::vector<float> prevAction(ferl.getNumAction(), 0.0f);

	deep::CSRL prsdr;

	const int inputCount = 3 + 3 + 2 + 2 + 1 + 2 + 2 + recCount + clockCount + 1;
	const int outputCount = 3 + 3 + 2 + 2 + recCount;

	std::vector<deep::CSRL::LayerDesc> layerDescs(2);

	layerDescs[0]._width = 8;
	layerDescs[0]._height = 8;

	layerDescs[1]._width = 4;
	layerDescs[1]._height = 4;

	std::vector<sdr::IPRSDRRL::InputType> inputTypes(7 * 7, sdr::IPRSDRRL::_state);

	prsdr.createRandom(7, 7, 8, layerDescs, -0.01f, 0.01f, 0.5f, generator);

	//deep::SDRRL sdrrl;

	//sdrrl.createRandom(inputCount, outputCount, 32, -0.01f, 0.01f, 0.0f, generator);

	// ---------------------------- Game Loop -----------------------------

	sf::View view = window.getDefaultView();

	bool quit = false;

	sf::Clock clock;

	float dt = 0.017f;

	int steps = 0;

	do {
		clock.restart();

		// ----------------------------- Input -----------------------------

		sf::Event windowEvent;

		while (window.pollEvent(windowEvent))
		{
			switch (windowEvent.type)
			{
			case sf::Event::Closed:
				quit = true;
				break;
			}
		}

		if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
			quit = true;

		//bidinet.simStep(cs, 0.0f, 0.98f, 0.001f, 0.95f, 0.01f, 0.01f, generator);

		const float maxRunnerBodyAngle = 0.3f;
		const float runnerBodyAngleStab = 10.0f;

		{
			float reward;
			
			if (sf::Keyboard::isKeyPressed(sf::Keyboard::K))
				reward = -runner0._pBody->GetLinearVelocity().x;
			else
				reward = runner0._pBody->GetLinearVelocity().x;

			std::vector<float> state;

			runner0.getStateVector(state);

			std::vector<float> action(3 + 3 + 2 + 2 + recCount);

			for (int a = 0; a < recCount; a++)
				state.push_back(prsdr.getPrediction(inputCount + outputCount - recCount + a));

			for (int a = 0; a < clockCount; a++)
				state.push_back(std::sin(steps / 60.0f * 2.0f * a * 2.0f * 3.141596f));

			for (int i = 0; i < state.size(); i++)
				prsdr.setInput(i, state[i]);

			//sdrrl.simStep(reward, 0.1f, 0.99f, 16, 0.01f, 0.01f, 0.01f, 0.01f, 16, 0.05f, 0.98f, 0.05f, 0.01f, 0.01f, 4.0f, generator);
			prsdr.simStep(reward, generator);

			for (int i = 0; i < action.size(); i++)
				action[i] = prsdr.getPrediction(inputCount + i) * 0.5f + 0.5f;

			runner0.motorUpdate(action, 12.0f);

			// Keep upright
			if (std::abs(runner0._pBody->GetAngle()) > maxRunnerBodyAngle)
				runner0._pBody->SetAngularVelocity(-runnerBodyAngleStab * runner0._pBody->GetAngle());
		}

		/*{
			float reward;

			if (sf::Keyboard::isKeyPressed(sf::Keyboard::K))
				reward = -runner1._pBody->GetLinearVelocity().x;
			else
				reward = runner1._pBody->GetLinearVelocity().x;

			std::vector<float> state;

			runner1.getStateVector(state);

			std::vector<float> action(3 + 3 + 2 + 2 + recCount);

			for (int a = 0; a < recCount; a++)
				state.push_back(prevAction[prevAction.size() - recCount + a]);

			for (int a = 0; a < clockCount; a++)
				state.push_back(std::sin(steps / 60.0f * 2.0f * a * 2.0f * 3.141596f));

			// Bias
			state.push_back(1.0f);

			//ferl.step(state, action, reward, 0.5f, 0.99f, 0.98f, 0.05f, 16, 4, 0.05f, 0.01f, 0.05f, 600, 64, 0.01f, generator);

			for (int i = 0; i < action.size(); i++)
				action[i] = action[i] * 0.5f + 0.5f;

			prevAction = action;

			runner1.motorUpdate(action, 12.0f);

			// Keep upright
			if (std::abs(runner1._pBody->GetAngle()) > maxRunnerBodyAngle)
				runner1._pBody->SetAngularVelocity(-runnerBodyAngleStab * runner1._pBody->GetAngle());
		}*/

		int subSteps = 1;

		for (int ss = 0; ss < subSteps; ss++) {
			world->ClearForces();

			world->Step(1.0f / 60.0f / subSteps, 64, 64);
		}

		if (!sf::Keyboard::isKeyPressed(sf::Keyboard::T) || steps % 200 == 1) {
			// -------------------------------------------------------------------

			//if (!sf::Keyboard::isKeyPressed(sf::Keyboard::B))
			//	view.setCenter(runner1._pBody->GetPosition().x * pixelsPerMeter, -runner1._pBody->GetPosition().y * pixelsPerMeter);
			//else
				view.setCenter(runner0._pBody->GetPosition().x * pixelsPerMeter, -runner0._pBody->GetPosition().y * pixelsPerMeter);

			// Draw sky
			sf::Sprite skySprite;
			skySprite.setTexture(skyTexture);

			window.setView(window.getDefaultView());

			window.draw(skySprite);

			window.setView(view);

			sf::RectangleShape floorShape;
			floorShape.setSize(sf::Vector2f(groundWidth * pixelsPerMeter, groundHeight * pixelsPerMeter));
			floorShape.setTexture(&floorTexture);
			floorShape.setTextureRect(sf::IntRect(0, 0, groundWidth * pixelsPerMeter, groundHeight * pixelsPerMeter));

			floorShape.setOrigin(sf::Vector2f(groundWidth * pixelsPerMeter * 0.5f, groundHeight * pixelsPerMeter * 0.5f));

			window.draw(floorShape);

			//runner1.renderDefault(window, sf::Color::Blue, pixelsPerMeter);
			runner0.renderDefault(window, sf::Color::Red, pixelsPerMeter);

			/*sf::Image img;
			img.create(sdrrl.getNumCells(), 1);

			for (int i = 0; i < sdrrl.getNumCells(); i++) {
				sf::Color c = sf::Color::Black;

				c.r = c.g = c.b = 255.0f * (sdrrl.getCellState(i) > 0.0f ? 1.0f : 0.0f);

				img.setPixel(i, 0, c);
			}

			float scale = 4.0f;

			sf::Texture tex;
			tex.loadFromImage(img);

			sf::Sprite s;
			s.setTexture(tex);

			s.setScale(sf::Vector2f(scale, scale));

			s.setPosition(sf::Vector2f(0.0f, window.getSize().y - scale * img.getSize().y));

			window.setView(window.getDefaultView());

			window.draw(s);*/

			window.setView(view);

			window.display();
		}
		else {
			if (steps % 100 == 0)
				std::cout << "Steps: " << steps << " Distance: " << runner0._pBody->GetPosition().x << std::endl;
		}

		//dt = clock.getElapsedTime().asSeconds();

		steps++;

	} while (!quit);

	world->DestroyBody(groundBody);

	return 0;
}
    /*
     * === Using the cell property in a cell-based simulation ===
     *
     * We conclude with a brief test demonstrating how {{{MotileCellProperty}}} can be used
     * in a cell-based simulation.
     */
    void TestOffLatticeSimulationWithMotileCellProperty() throw(Exception)
    {
        /* Note that HoneycombMeshGenerator, used in this test, is not
         *  yet implemented in parallel. */

        /* We use the {{{HoneycombMeshGenerator}}} to create a honeycomb mesh covering a
         * circular domain of given radius, and use this to generate a {{{NodesOnlyMesh}}}
         * as follows. */
        HoneycombMeshGenerator generator(10, 10);
        MutableMesh<2,2>* p_generating_mesh = generator.GetCircularMesh(5);

        NodesOnlyMesh<2> mesh;
        /* We construct the mesh using the generating mesh and a cut-off 1.5 which defines the
         * connectivity in the mesh.
         */
        mesh.ConstructNodesWithoutMesh(*p_generating_mesh, 1.5);

        /* We now create a shared pointer to our new property, as follows. */
        MAKE_PTR(MotileCellProperty, p_motile);
        /*
         * Also create a shared pointer to a cell label so we can visualize the
         * different cell types. Note that this is also a {{{CellProperty}}}.
         */
        MAKE_PTR(CellLabel, p_label);

        /* Next, we create some cells. We don't use a Generator as we want to give some cells the new cell property, therefore
         * we create the cells in a loop, as follows.*/
        MAKE_PTR(WildTypeCellMutationState, p_state);
        MAKE_PTR(DifferentiatedCellProliferativeType, p_diff_type);
        std::vector<CellPtr> cells;
        for (unsigned i=0; i<mesh.GetNumNodes(); i++)
        {
            /* For each node we create a cell with our cell-cycle model and the wild-type cell mutation state.
             * We then add the property {{{MotileCellProperty}}} to a random selection of the cells, as follows. */
            FixedDurationGenerationBasedCellCycleModel* p_model = new FixedDurationGenerationBasedCellCycleModel();

            CellPropertyCollection collection;
            if (RandomNumberGenerator::Instance()->ranf() < 0.2)
            {
                collection.AddProperty(p_motile);
                collection.AddProperty(p_label);
            }

            CellPtr p_cell(new Cell(p_state, p_model, false, collection));
            p_cell->SetCellProliferativeType(p_diff_type);

            /* Now, we define a random birth time, chosen from [-T,0], where
             * T = t,,1,, + t,,2,,, where t,,1,, is a parameter representing the G,,1,, duration
             * of a stem cell, and t,,2,, is the basic S+G,,2,,+M phases duration.
             */
            double birth_time = - RandomNumberGenerator::Instance()->ranf() *
                                    (p_model->GetStemCellG1Duration()
                                        + p_model->GetSG2MDuration());

            /* Finally, we set the birth time and push the cell back into the vector of cells. */
            p_cell->SetBirthTime(birth_time);
            cells.push_back(p_cell);
        }

        /* Now that we have defined the mesh and cells, we can define the cell population. The constructor
         * takes in the mesh and the cells vector. */
        NodeBasedCellPopulation<2> cell_population(mesh, cells);

        /* In order to visualize labelled cells we need to use the following command.*/
        cell_population.AddCellPopulationCountWriter<CellMutationStatesCountWriter>();

        /* We then pass in the cell population into an {{{OffLatticeSimulation}}},
         * and set the output directory, output multiple, and end time. */
        OffLatticeSimulation<2> simulator(cell_population);
        simulator.SetOutputDirectory("TestOffLatticeSimulationWithMotileCellProperty");
        simulator.SetSamplingTimestepMultiple(12);
        simulator.SetEndTime(10.0);

        /* We create a force law and pass it to the {{{OffLatticeSimulation}}}. */
        MAKE_PTR(GeneralisedLinearSpringForce<2>, p_linear_force);
        p_linear_force->SetCutOffLength(1.5);
        simulator.AddForce(p_linear_force);

        /* Now create a {{{MotlieForce}}} and pass it to the {{{OffLatticeSimulation}}}. */
        MAKE_PTR(MyMotiveForce, p_motive_force);
        simulator.AddForce(p_motive_force);

        /* To run the simulation, we call {{{Solve()}}}. */
        simulator.Solve();
    }