int main()
{
  const size_t npts = 10;
  const SS::GhostData ghost(0);
  const SS::BoundaryCellInfo bc = SS::BoundaryCellInfo::build<FieldT>();
  const SS::MemoryWindow mw( SS::IntVec( npts, 1, 1 ) );

  FieldT f( mw, bc, ghost, NULL );

  double x=0.1;
  for( FieldT::iterator ifld=f.begin(); ifld!=f.end(); ++ifld, x+=1.0 ){
    *ifld = x;
  }

  TestHelper status(true);

  FieldT::interior_iterator i2=f.interior_begin();
  for( FieldT::iterator i=f.begin(); i!=f.end(); ++i, ++i2 ){
    status( *i==*i2, "value" );
    status( &*i == &*i2, "address" );
  }

  {
    typedef SS::ConstValEval BCVal;
    typedef SS::BoundaryCondition<FieldT,BCVal> BC;

    BC bc1( SS::IntVec(2,1,1), BCVal(1.234) );
    BC bc2( SS::IntVec(4,1,1), BCVal(3.456) );
  
    bc1(f);
    bc2(f);
    status( f[2] == 1.234, "point BC 1" );
    status( f[4] == 3.456, "point BC 2" );
  }

  {
    std::vector<size_t> ix;
    ix.push_back(4);
    ix.push_back(2);
    SpatialOps::Point::FieldToPoint<FieldT> ftp(ix);
    SpatialOps::Point::PointToField<FieldT> ptf(ix);

    const SS::MemoryWindow mw2( SpatialOps::structured::IntVec(2,1,1) );
    FieldT f2( mw2, bc, ghost, NULL );
    ftp.apply_to_field( f, f2 );
    status( f2[0] == 3.456, "Field2Point Interp (1)" );
    status( f2[1] == 1.234, "Field2Point Interp (2)" );

    f2[0] = -1.234;
    f2[1] = -3.456;
    ptf.apply_to_field( f2, f );
    status( f[2] == -3.456, "Point2Field Interp (1)" );
    status( f[4] == -1.234, "Point2Field Interp (2)" );
  }


  if( status.ok() ) return 0;
  return -1;
}
예제 #2
0
int main() {
    bc1( &x );
    bc2( &x );
    bc3( &x );
    bcd( &x );
    _PASS;
}
예제 #3
0
void BinnedCorr2<D1,D2>::processPairwise(
    const SimpleField<D1,C>& field1, const SimpleField<D2,C>& field2, bool dots)
{ 
    Assert(_coords == -1 || _coords == C);
    _coords = C;
    const long nobj = field1.getNObj();
    const long nobj2 = field2.getNObj();
    xdbg<<"field1 has "<<nobj<<" objects\n";
    xdbg<<"field2 has "<<nobj2<<" objects\n";
    Assert(nobj > 0);
    Assert(nobj == nobj2);

    const long sqrtn = long(sqrt(double(nobj)));

#ifdef _OPENMP
#pragma omp parallel 
    {
        // Give each thread their own copy of the data vector to fill in.
        BinnedCorr2<D1,D2> bc2(*this,false);
#else
        BinnedCorr2<D1,D2>& bc2 = *this;
#endif

#ifdef _OPENMP
#pragma omp for schedule(static)
#endif
        for (long i=0;i<nobj;++i) {
            // Let the progress dots happen every sqrt(n) iterations.
            if (dots && (i % sqrtn == 0)) {
#ifdef _OPENMP
#pragma omp critical
#endif
                {
                    //xdbg<<omp_get_thread_num()<<" "<<i<<std::endl;
                    std::cout<<'.'<<std::flush;
                }
            }
            const Cell<D1,C>& c1 = *field1.getCells()[i];
            const Cell<D2,C>& c2 = *field2.getCells()[i];
            const double dsq = MetricHelper<M>::DistSq(c1.getPos(),c2.getPos());
            if (dsq >= _minsepsq && dsq < _maxsepsq) {
                bc2.template directProcess11<C,M>(c1,c2,dsq);
            }
        }
#ifdef _OPENMP
        // Accumulate the results
#pragma omp critical
        {
            *this += bc2;
        }
    }
#endif
    if (dots) std::cout<<std::endl;
}
예제 #4
0
CCommandQueue::iterator CCommandAI::GetCancelQueued(const Command& c, CCommandQueue& q)
{
	CCommandQueue::iterator ci = q.end();

	while (ci != q.begin()) {
		--ci; //iterate from the end and dont check the current order
		const Command& c2 = *ci;
		const int cmdID = c.GetID();
		const int cmd2ID = c2.GetID();

		const bool attackAndFight = (cmdID == CMD_ATTACK && cmd2ID == CMD_FIGHT && c2.params.size() == 1);

		if (c2.params.size() != c.params.size())
			continue;

		if ((cmdID == cmd2ID) || (cmdID < 0 && cmd2ID < 0) || attackAndFight) {
			if (c.params.size() == 1) {
				// assume the param is a unit-ID or feature-ID
				if ((c2.params[0] == c.params[0]) &&
				    (cmd2ID != CMD_SET_WANTED_MAX_SPEED)) {
					return ci;
				}
			}
			else if (c.params.size() >= 3) {
				if (cmdID < 0) {
					BuildInfo bc1(c);
					BuildInfo bc2(c2);

					if (bc1.def == NULL) continue;
					if (bc2.def == NULL) continue;

					if (math::fabs(bc1.pos.x - bc2.pos.x) * 2 <= std::max(bc1.GetXSize(), bc2.GetXSize()) * SQUARE_SIZE &&
					    math::fabs(bc1.pos.z - bc2.pos.z) * 2 <= std::max(bc1.GetZSize(), bc2.GetZSize()) * SQUARE_SIZE) {
						return ci;
					}
				} else {
					// assume c and c2 are positional commands
					const float3& c1p = c.GetPos(0);
					const float3& c2p = c2.GetPos(0);

					if ((c1p - c2p).SqLength2D() >= (COMMAND_CANCEL_DIST * COMMAND_CANCEL_DIST))
						continue;
					if ((c.options & SHIFT_KEY) != 0 && (c.options & INTERNAL_ORDER) != 0)
						continue;

					return ci;
				}
			}
		}
	}
	return q.end();
}
예제 #5
0
void BinnedCorr2<D1,D2>::process(const Field<D1,C>& field1, const Field<D2,C>& field2,
                                 bool dots)
{
    Assert(_coords == -1 || _coords == C);
    _coords = C;
    const long n1 = field1.getNTopLevel();
    const long n2 = field2.getNTopLevel();
    xdbg<<"field1 has "<<n1<<" top level nodes\n";
    xdbg<<"field2 has "<<n2<<" top level nodes\n";
    Assert(n1 > 0);
    Assert(n2 > 0);

#ifdef _OPENMP
#pragma omp parallel 
    {
        // Give each thread their own copy of the data vector to fill in.
        BinnedCorr2<D1,D2> bc2(*this,false);
#else
        BinnedCorr2<D1,D2>& bc2 = *this;
#endif

#ifdef _OPENMP
#pragma omp for schedule(dynamic)
#endif
        for (int i=0;i<n1;++i) {
#ifdef _OPENMP
#pragma omp critical
#endif
            {
                //dbg<<omp_get_thread_num()<<" "<<i<<std::endl;
                if (dots) std::cout<<'.'<<std::flush;
            }
            const Cell<D1,C>& c1 = *field1.getCells()[i];
            for (int j=0;j<n2;++j) {
                const Cell<D2,C>& c2 = *field2.getCells()[j];
                bc2.process11<C,M>(c1,c2);
            }
        }
#ifdef _OPENMP
        // Accumulate the results
#pragma omp critical
        {
            *this += bc2;
        }
    }
#endif
    if (dots) std::cout<<std::endl;
}
예제 #6
0
CCommandQueue::iterator CCommandAI::GetCancelQueued(const Command& c, CCommandQueue& q)
{
	CCommandQueue::iterator ci = q.end();

	while (ci != q.begin()) {
		--ci; //iterate from the end and dont check the current order
		const Command& c2 = *ci;
		const int& cmd_id = c.GetID();
		const int& cmd2_id = c2.GetID();

		if (((cmd_id == cmd2_id) || ((cmd_id < 0) && (cmd2_id < 0))
				|| (cmd2_id == CMD_FIGHT && cmd_id == CMD_ATTACK && c2.params.size() == 1))
				&& (c2.params.size() == c.params.size())) {
			if (c.params.size() == 1) {
				// assume the param is a unit-ID or feature-ID
				if ((c2.params[0] == c.params[0]) &&
				    (cmd2_id != CMD_SET_WANTED_MAX_SPEED)) {
					return ci;
				}
			}
			else if (c.params.size() >= 3) {
				if (cmd_id < 0) {
					BuildInfo bc(c);
					BuildInfo bc2(c2);
					if (bc.def && bc2.def
					    && fabs(bc.pos.x - bc2.pos.x) * 2 <= std::max(bc.GetXSize(), bc2.GetXSize()) * SQUARE_SIZE
					    && fabs(bc.pos.z - bc2.pos.z) * 2 <= std::max(bc.GetZSize(), bc2.GetZSize()) * SQUARE_SIZE) {
						return ci;
					}
				} else {
					// assume this means that the first 3 makes a position
					float3 cp(c.params[0], c.params[1], c.params[2]);
					float3 c2p(c2.params[0], c2.params[1], c2.params[2]);
					if ((cp - c2p).SqLength2D() < (17.0f * 17.0f)) {
						return ci;
					}
				}
			}
		}
	}
	return q.end();
}
예제 #7
0
int main(){
	Simple_window win(Point(100, 100), 600, 400, "Bar_chart");

	Bar_chart bc1(Point(0, 0), win.x_max() / 2, win.y_max() / 2);
	bc1.add_data(100);
	bc1.add_data(600);
	bc1.add_data(300);
	bc1.add_data(700);
	bc1.add_data(200);

	Bar_chart bc2(Point(win.x_max() / 2, win.y_max() / 2), win.x_max() / 2, win.y_max() / 2);
	bc2.add_data(30, "7", Color::yellow);
	bc2.add_data(180, "1", Color::red);
	bc2.add_data(20, "8", Color::blue);
	bc2.add_data(150, "2", Color::yellow);
	bc2.add_data(70, "5", Color::yellow);
	bc2.add_data(40, "6", Color::yellow);
	bc2.add_data(130, "3", Color::yellow);
	bc2.add_data(90, "4", Color::yellow);

	win.attach(bc1);
	win.attach(bc2);
	win.wait_for_button();
}
예제 #8
0
    void TestUseCoarsePdeMesh() throw(Exception)
    {
        EXIT_IF_PARALLEL;

        // Create a cell population
        HoneycombMeshGenerator generator(4, 4, 0);
        MutableMesh<2,2>* p_generating_mesh = generator.GetMesh();
        NodesOnlyMesh<2> mesh;
        mesh.ConstructNodesWithoutMesh(*p_generating_mesh, 1.5);

        std::vector<CellPtr> cells;
        CellsGenerator<FixedDurationGenerationBasedCellCycleModel, 2> cells_generator;
        cells_generator.GenerateBasic(cells, mesh.GetNumNodes());

        NodeBasedCellPopulation<2> cell_population(mesh, cells);

        // Create a PDE handler object using this cell population
        CellBasedPdeHandler<2> pde_handler(&cell_population);

        // Test that UseCoarsePdeMesh() throws an exception if no PDEs are specified
        ChastePoint<2> lower(0.0, 0.0);
        ChastePoint<2> upper(9.0, 9.0);
        ChasteCuboid<2> cuboid(lower, upper);
        TS_ASSERT_THROWS_THIS(pde_handler.UseCoarsePdeMesh(3.0, cuboid, true),
            "mPdeAndBcCollection should be populated prior to calling UseCoarsePdeMesh().");

        // Set up PDE and pass to handler
        AveragedSourcePde<2> pde(cell_population, -0.1);
        ConstBoundaryCondition<2> bc(1.0);
        PdeAndBoundaryConditions<2> pde_and_bc(&pde, &bc, false);
        pde_handler.AddPdeAndBc(&pde_and_bc);

        // Test UseCoarsePdeMesh() again
        pde_handler.UseCoarsePdeMesh(3.0, cuboid, true);

        // Test that the coarse mesh has the correct number of nodes and elements
        TetrahedralMesh<2,2>* p_coarse_mesh = pde_handler.GetCoarsePdeMesh();
        TS_ASSERT_EQUALS(p_coarse_mesh->GetNumNodes(), 16u);
        TS_ASSERT_EQUALS(p_coarse_mesh->GetNumElements(), 18u);

        // Find centre of cell population
        c_vector<double,2> centre_of_cell_population = cell_population.GetCentroidOfCellPopulation();

        // Find centre of coarse PDE mesh
        c_vector<double,2> centre_of_coarse_pde_mesh = zero_vector<double>(2);
        for (unsigned i=0; i<p_coarse_mesh->GetNumNodes(); i++)
        {
            centre_of_coarse_pde_mesh += p_coarse_mesh->GetNode(i)->rGetLocation();
        }
        centre_of_coarse_pde_mesh /= p_coarse_mesh->GetNumNodes();

        // Test that the two centres match
        c_vector<double,2> centre_difference = centre_of_cell_population - centre_of_coarse_pde_mesh;
        TS_ASSERT_DELTA(norm_2(centre_difference), 0.0, 1e-4);

        // Test that UseCoarsePdeMesh()  throws an exception if the wrong type of PDE is specified
        SimpleUniformSourcePde<2> pde2(-0.1);
        ConstBoundaryCondition<2> bc2(1.0);
        PdeAndBoundaryConditions<2> pde_and_bc2(&pde2, &bc2, false);
        pde_and_bc2.SetDependentVariableName("second variable");
        pde_handler.AddPdeAndBc(&pde_and_bc2);

        TS_ASSERT_THROWS_THIS(pde_handler.UseCoarsePdeMesh(3.0, cuboid, true),
            "UseCoarsePdeMesh() should only be called if averaged-source PDEs are specified.");

        // Now test the 1D case
        std::vector<Node<1>*> nodes_1d;
        nodes_1d.push_back(new Node<1>(0, true,  0.0));

        NodesOnlyMesh<1> mesh_1d;
        mesh_1d.ConstructNodesWithoutMesh(nodes_1d, 1.5);

        std::vector<CellPtr> cells_1d;
        CellsGenerator<FixedDurationGenerationBasedCellCycleModel, 1> cells_generator_1d;
        cells_generator_1d.GenerateBasic(cells_1d, mesh_1d.GetNumNodes());

        NodeBasedCellPopulation<1> cell_population_1d(mesh_1d, cells_1d);

        CellBasedPdeHandler<1> pde_handler_1d(&cell_population_1d);

        AveragedSourcePde<1> pde_1d(cell_population_1d, -0.1);
        ConstBoundaryCondition<1> bc_1d(1.0);
        PdeAndBoundaryConditions<1> pde_and_bc_1d(&pde_1d, &bc_1d, false);
        pde_handler_1d.AddPdeAndBc(&pde_and_bc_1d);

        ChastePoint<1> lower1(0.0);
        ChastePoint<1> upper1(9.0);
        ChasteCuboid<1> cuboid1(lower1, upper1);
        pde_handler_1d.UseCoarsePdeMesh(3.0, cuboid1, true);

        // Test that the coarse mesh has the correct number of nodes and elements
        TetrahedralMesh<1,1>* p_coarse_mesh_1d = pde_handler_1d.GetCoarsePdeMesh();
        TS_ASSERT_EQUALS(p_coarse_mesh_1d->GetNumNodes(), 4u);
        TS_ASSERT_EQUALS(p_coarse_mesh_1d->GetNumElements(), 3u);

        // Now test the 3D case
        std::vector<Node<3>*> nodes_3d;
        nodes_3d.push_back(new Node<3>(0, true,  0.0));

        NodesOnlyMesh<3> mesh_3d;
        mesh_3d.ConstructNodesWithoutMesh(nodes_3d, 1.5);

        std::vector<CellPtr> cells_3d;
        CellsGenerator<FixedDurationGenerationBasedCellCycleModel, 3> cells_generator_3d;
        cells_generator_3d.GenerateBasic(cells_3d, mesh_3d.GetNumNodes());

        NodeBasedCellPopulation<3> cell_population_3d(mesh_3d, cells_3d);

        CellBasedPdeHandler<3> pde_handler_3d(&cell_population_3d);

        AveragedSourcePde<3> pde_3d(cell_population_3d, -0.1);
        ConstBoundaryCondition<3> bc_3d(1.0);
        PdeAndBoundaryConditions<3> pde_and_bc_3d(&pde_3d, &bc_3d, false);
        pde_handler_3d.AddPdeAndBc(&pde_and_bc_3d);

        ChastePoint<3> lower3(0.0, 0.0, 0.0);
        ChastePoint<3> upper3(9.0, 9.0, 9.0);
        ChasteCuboid<3> cuboid3(lower3, upper3);

        pde_handler_3d.UseCoarsePdeMesh(3.0, cuboid3, true);

        // Test that the coarse mesh has the correct number of nodes and elements
        TetrahedralMesh<3,3>* p_coarse_mesh_3d = pde_handler_3d.GetCoarsePdeMesh();
        TS_ASSERT_EQUALS(p_coarse_mesh_3d->GetNumNodes(), 64u);
        TS_ASSERT_EQUALS(p_coarse_mesh_3d->GetNumElements(), 162u);

        // Avoid memory leak
        for (unsigned i=0; i<nodes_1d.size(); i++)
        {
            delete nodes_1d[i];
            delete nodes_3d[i];
        }
    }
int main(int argc, char **argv)
{
	dest_x=0;
	dest_y=6000;
	v = 200;	
	numberofobjects = 2;
	v1 = 100;
	ra[0][5] = 400;
	ra[1][5] = 400;
	ra[2][5] = 400; 
	ra[3][5] = 400;
	//argv[1]="-rh";
	//argv[2]="10.2.36.7";
	//argc=3;
	BotConnector bc(argc, argv);
	if( bc.connect() )
	{
		printf( "Connected to Robot\n" );
	}
	else
	{
		printf( "Connection attempt to Robot failed, Sorry :(\n" );
		return EXIT_SUCCESS;
	}
	argv[1]="-rrtp";
	argv[2]="8102";
	argc=3;
	BotConnector bc1(argc, argv);
	if( bc1.connect() )
	{
		printf( "Connected to Robot1\n" );
	}
	else
	{
		printf( "Connection attempt to Robot failed, Sorry :(\n" );
		return EXIT_SUCCESS;
	}
//	bc.setRobotVelocity_idle(100,100); // initialising vr and vl
	bc.setRobotVelocity(100,100, 10000);
	bc.getAngles(0);// updating ra[][].
//	omnicx = ra[0][1]+ra[0][5]*cos(ra[0][0]);
//	omnicy = ra[0][2]+ra[0][5]*sin(ra[0][0]);
	//bc1.moveRobot(0,90);
//bc1.setRobotVelocity(100,100, 10000);
bc1.moveRobot(6000,90);
//bc1.setRobotVelocity(100,100, 30000);
bc1.moveRobot(0,180);
	argv[1]="-rrtp";
	argv[2]="8103";	
	argc=3;
	BotConnector bc2(argc, argv);
	if( bc2.connect() )
	{
		printf( "Connected to Robot2\n" );
	}
	else
	{
		printf( "Connection attempt to Robot failed, Sorry :(\n" );
		return EXIT_SUCCESS;
	}
bc2.moveRobot(2000,90);
//bc2.setRobotVelocity(100,100, 20000);
bc2.moveRobot(2000,-45);
//bc2.setRobotVelocity(200,200, 25000);
bc2.moveRobot(0,135);
/*	argv[1]="-rrtp";
  argv[2]="8104";
  argc=3;
  BotConnector bc3(argc, argv);
  if( bc3.connect() )
  {
          printf( "Connected to Robot\n" );
  }
  else
  {
          printf( "Connection attempt to Robot failed, Sorry :(\n" );
          return EXIT_SUCCESS;
  }
//bc.setVelocity1(-100,-100, 10000);
bc3.moveRobot(0,90);
bc3.setRobotVelocity(150,150, 30000);
bc3.moveRobot(0,-125);
bc3.setRobotVelocity(100,100, 20000);
bc3.moveRobot(0,180);*/
/*argv[1]="-rrtp";
  argv[2]="8105";
  argc=3;
  BotConnector bc4(argc, argv);
  if( bc4.connect() )
  {
          printf( "Connected to Robot\n" );
  }
  else
  {
          printf( "Connection attempt to Robot failed, Sorry :(\n" );
          return EXIT_SUCCESS;
  }
//bc.setVelocity1(-100,-100, 10000);
bc4.getAngles(4);
bc4.moveRobot(0,90);
bc4.setRobotVelocity(100,100, 40000);
bc4.moveRobot(0,0);
bc4.setRobotVelocity(200,200, 25000);
bc4.moveRobot(0,180);
argv[1]="-rrtp";
  argv[2]="8106";
  argc=3;
  BotConnector bc5(argc, argv);
  if( bc5.connect() )
  {
          printf( "Connected to Robot\n" );
  }
  else
  {
          printf( "Connection attempt to Robot failed, Sorry :(\n" );
          return EXIT_SUCCESS;
  }
//bc.setVelocity1(-100,-100, 10000);
bc5.getAngles(5);
bc5.moveRobot(0,90);
bc5.setRobotVelocity(200,200, 25000);
bc5.moveRobot(0,-80);
bc5.setRobotVelocity(300,300, 15000);
bc5.moveRobot(0,180);*/
bc.setRobotVelocity(-100,-100, 10000);
bc.moveRobot(0,90);
bc.getAngles(0);
bc1.getAngles(1);
bc2.getAngles(2);
omnicx = ra[0][1];
omnicy = ra[0][2]+300;
//bc3.getAngles(3);
/*bc4.getAngles(4);
bc5.getAngles(5);*/
 ArUtil::sleep(5000);
	
	int f;
	for(f=0;f<200;f++)
	{
			float dest,dest1;
			int j;
			dest = tan_inv((dest_y-omnicy),(dest_x-omnicx));
			j=update(dest);
			right_left();
		//	robot_motion();
 			bc.setRobotVelocity_idle(vright,vleft);
         		 bc1.setRobotVelocity_idle(100,100);
	  		bc2.setRobotVelocity_idle(100,100);
			// bc3.setRobotVelocity_idle(250,250);
          		/*bc4.setRobotVelocity_idle(250,250);
          		bc5.setRobotVelocity_idle(250,250);*/
			 ArUtil::sleep(300);
          		bc.getAngles(0);
          		bc1.getAngles(1);
         		 bc2.getAngles(2);
			//bc3.getAngles(3);
			omnicx = omnicx+ra[0][3]*0.3;
			omnicy = omnicy+ra[0][4]*0.3;
			/*bc.setRobotVelocity_idle(0,0);
         		 bc1.setRobotVelocity_idle(0,0);
	  		bc2.setRobotVelocity_idle(0,0);
			 bc3.setRobotVelocity_idle(0,0);*/
		//	omnicx = ra[0][1]+ra[0][5]*cos(ra[0][0]);
//omnicy = ra[0][2]+ra[0][5]*sin(ra[0][0]);
			printf("omnicx = %f, omnicy = %f\n",omnicx,omnicy);
			printf("x = %d",f);
		/*	bc3.getAngles(3);
			bc4.getAngles(4);
			bc5.getAngles(5);*/
	}
	return bc.disconnect();
}
예제 #10
0
int main(int argc, char* argv[])
{
  // Initialize POOMA and Tester class.
  Pooma::initialize(argc, argv);
  Pooma::Tester tester(argc, argv);

  tester.out() << argv[0] << ": KillBC with expressions" << std::endl;
  tester.out() << "------------------------------------------------"
               << std::endl;

  // First create a Particles object with some Attributes for BC's to act upon.

  tester.out() << "Creating Particles object with DynamicArray attributes ..."
               << std::endl;
  UniformLayout pl(Pooma::contexts());
#if POOMA_MESSAGING
  MyParticles<MPRemoteDynamicUniform> P(pl);
#else
  MyParticles<MPDynamicUniform> P(pl);
#endif

  if (Pooma::context() == 0)
    P.create(10,0,false);
  P.sync(P.a1);

  // Initialize the arrays with scalars.
  // Block since we're starting scalar code.

  Pooma::blockAndEvaluate();
  
  tester.out() << "Initializing DynamicArray objects ..."
               << std::endl;
  int i;
  for (i=0; i < P.size(); ++i) {
    P.a1(i) = 0.1 * i;
    P.a2(i) = 0.25 * i - 1.5;
  }

  tester.out() << "Initialization complete:" << std::endl;
  tester.out() << "  a1 = " << P.a1 << std::endl;
  tester.out() << "  a2 = " << P.a2 << std::endl;
  tester.out() << "  a1*a1+a2*a2 = " << P.a1 * P.a1 + P.a2 * P.a2
               << std::endl;

  // Create a KillBC

  tester.out() << "Creating a Particle KillBC object ..."
               << std::endl;

  // For each BC, we construct the BCType with boundary values.
  // Then we add a ParticleBC with this type to our list, and we provide
  // the subject of the BC (and the object, if different).
  // For the KillBC, object must be the Particles object itself.

  KillBC<double> bc1(0.0, 0.8);
  P.addBoundaryCondition(P.a1 * P.a1 + P.a2 * P.a2, P, bc1);

  // Apply boundary condition and display the results

  tester.out() << "Applying the boundary conditions ..." << std::endl;
  tester.out() << "Before BC's, Particles = " << P << std::endl;
  P.applyBoundaryConditions();
  tester.out() << "After BC's, Particles = " << P << std::endl;
  P.performDestroy();
  Pooma::blockAndEvaluate();
  tester.out() << "Status after applying BC: " << std::endl;
  tester.out() << "  a1 = " << P.a1 << std::endl;
  tester.out() << "  a2 = " << P.a2 << std::endl;

  tester.check(P.size() == 5);

  // Let's also try a KillBC on a free-standing DynamicArray.

  tester.out() << "Creating a free-standing DynamicArray ..." << std::endl;
#if POOMA_MESSAGING
  DynamicArray< Vector<2,int>, MultiPatch< DynamicTag, Remote<Dynamic> > > a3;
#else
  DynamicArray< Vector<2,int>, MultiPatch<DynamicTag,Dynamic> > a3;
#endif

  Interval<1> empty;
  DynamicLayout layout(empty, Pooma::contexts());
  a3.initialize(layout);
  int npc = 20 / Pooma::contexts();
  int rem = 20 % Pooma::contexts();
  if (Pooma::context() < rem) npc++;
  a3.create(npc);
  a3.layout().sync();

  Pooma::blockAndEvaluate();
  for (i=0; i<a3.domain().size(); ++i)
    a3(i) = Vector<2,int>(i,2*i+1);

  tester.out() << "Initialization complete." << std::endl;
  tester.out() << "a3 = " << a3 << std::endl;

  // Now construct a KillBC for this DynamicArray and apply it

  tester.out() << "Creating a DynamicArray KillBC object ..." << std::endl;
  KillBC< Vector<2,int> > bc2(Vector<2,int>(2,2), Vector<2,int>(24,24));
  ParticleBCItem* killbc2 = bc2.create(a3);

  tester.out() << "Applying the boundary condition ..." << std::endl;
  killbc2->applyBoundaryCondition();
  a3.layout().sync();
  Pooma::blockAndEvaluate();
  tester.out() << "Status after applying BC:" << std::endl;
  tester.out() << "a3 = " << a3 << std::endl;

  tester.check(a3.domain().size() == 10);

  // Delete the ParticleBC that we created

  delete killbc2;

  // Return resulting error code and shut down POOMA.

  tester.out() << "------------------------------------------------"
               << std::endl;
  int retval = tester.results("KillBC with expression");
  Pooma::finalize();
  return retval;
}
예제 #11
0
int main(int argc, char* argv[])
{
    // Load the mesh.
    Mesh mesh;
    H2DReader mloader;
    mloader.load("domain.mesh", &mesh);

    // Perform uniform mesh refinement.
    for(int i = 0; i < INIT_REF_NUM; i++) mesh.refine_all_elements(2); // 2 is for vertical split.

    // Initialize boundary conditions
    DefaultEssentialBCConst bc1(BDY_PERFECT, 0.0);
    EssentialBCNonConst bc2(BDY_LEFT);
    EssentialBCs bcs(Hermes::vector<EssentialBoundaryCondition *>(&bc1, &bc2));

    // Create an H1 space with default shapeset.
    H1Space e_r_space(&mesh, &bcs, P_INIT);
    H1Space e_i_space(&mesh, &bcs, P_INIT);
    int ndof = Space::get_num_dofs(&e_r_space);
    info("ndof = %d", ndof);

    // Initialize the weak formulation
    // Weak forms for real and imaginary parts

    // Initialize the weak formulation.
    WeakFormHelmholtz wf(eps, mu, omega, sigma, beta, E0, h);

    // Initialize the FE problem.
    bool is_linear = true;
    DiscreteProblem dp(&wf, Hermes::vector<Space *>(&e_r_space, &e_i_space), is_linear);

    // Set up the solver, matrix, and rhs according to the solver selection.
    SparseMatrix* matrix = create_matrix(matrix_solver);
    Vector* rhs = create_vector(matrix_solver);
    Solver* solver = create_linear_solver(matrix_solver, matrix, rhs);

    // Initialize the solutions.
    Solution e_r_sln, e_i_sln;

    // Assemble the stiffness matrix and right-hand side vector.
    info("Assembling the stiffness matrix and right-hand side vector.");
    dp.assemble(matrix, rhs);

    // Solve the linear system and if successful, obtain the solutions.
    info("Solving the matrix problem.");
    if(solver->solve())
        Solution::vector_to_solutions(solver->get_solution(),
                                      Hermes::vector<Space *>(&e_r_space, &e_i_space),
                                      Hermes::vector<Solution *>(&e_r_sln, &e_i_sln));
    else
        error ("Matrix solver failed.\n");

    // Visualize the solution.
    ScalarView viewEr("Er [V/m]", new WinGeom(0, 0, 800, 400));
    viewEr.show(&e_r_sln);
    // viewEr.save_screenshot("real_part.bmp");

    ScalarView viewEi("Ei [V/m]", new WinGeom(0, 450, 800, 400));
    viewEi.show(&e_i_sln);
    // viewEi.save_screenshot("imaginary_part.bmp");

    // Wait for the view to be closed.
    View::wait();

    // Clean up.
    delete solver;
    delete matrix;
    delete rhs;

    return 0;
}
//Resolution of min 1/2 x^t A x + b^t x with x in [-4, +infinity]
//and x_1 in [-1.0, 0.7]
//    x_2 in [-1.3, 1.4]
//    x_3 in [-2.0, 2.1]
int main()
{
    //Definition of the quadratic function
    roboptim::Function::matrix_t A( 3,3 );
    roboptim::Function::vector_t b( 3 );

    A << 1,7,4,7,3,6,4,6,2;
    b << 1,3,4;

    roboptim::NumericQuadraticFunction f( A, b );

    //Testing f([1,1,1])
    roboptim::Function::vector_t x( 3 );
    x << 1,1,1;
    std::cout << "f(x) = " << f( x ) << std::endl;

    //Definition the constraint x_min < x < x_max
    roboptim::Function::vector_t offset( 3 );
    boost::shared_ptr< roboptim::IdentityFunction > c1(
            new roboptim::IdentityFunction( offset ) );

    //Definition of another constraint 0 < Ax +b < +infinity
    roboptim::Function::matrix_t Ac2( 3,3 );
    roboptim::Function::vector_t bc2( 3 );
    Ac2 << 2,3,1,7,1,0,3,5,2;
    bc2 << 4,3,4;
    boost::shared_ptr< roboptim::NumericLinearFunction > c2(
            new roboptim::NumericLinearFunction(Ac2, bc2) );
    
    //Test c([1,1,1])
    roboptim::IdentityFunction c1_el = *c1.get();
    std::cout << "c1(x) = [" << c1_el( x ) << "]" << std::endl;
    
    //Creation of the problem
    solver_t::problem_t pb ( f );
    std::cout << "problem input size : " << pb.function().inputSize() << std::endl;
    std::cout << "problem output size : " << pb.function().outputSize() << std::endl;

    //Set bounds for x in f(x)
    roboptim::Function::intervals_t function_arg_bounds;
    for( unsigned int i=0; i< pb.function().inputSize(); ++i ){
        roboptim::Function::interval_t x_bound = roboptim::Function::makeInterval( -4.0, roboptim::Function::infinity() );
        function_arg_bounds.push_back( x_bound );
    }

    pb.argumentBounds() = function_arg_bounds;

    //Set bounds for constraints: x_min and x_max
    roboptim::Function::intervals_t constraint_bounds;
    roboptim::Function::interval_t c1_0 = roboptim::Function::makeInterval( -1.0, 0.7 );
    roboptim::Function::interval_t c1_1 = roboptim::Function::makeInterval( -1.3, 1.4 );
    roboptim::Function::interval_t c1_2 = roboptim::Function::makeInterval( -2.0, 2.1 );
    constraint_bounds.push_back( c1_0 );
    constraint_bounds.push_back( c1_1 );
    constraint_bounds.push_back( c1_2 );

    //Set bounds for c2
    roboptim::Function::intervals_t c2_bounds;
    for( unsigned int i=0; i< pb.function().inputSize(); ++i ){
        roboptim::Function::interval_t c2_interval = roboptim::Function::makeLowerInterval( 0 );
        c2_bounds.push_back(c2_interval);
    }

    //Set scales for the problem
    solver_t::problem_t::scales_t scales(pb.function().inputSize(), 1.0);
    
    //Add constraint
    pb.addConstraint(
            boost::static_pointer_cast<
      roboptim::GenericLinearFunction<roboptim::EigenMatrixDense>  >
            (c1), constraint_bounds, scales );

    
    pb.addConstraint(
            boost::static_pointer_cast<
      roboptim::GenericLinearFunction<roboptim::EigenMatrixDense> >
            (c2), c2_bounds, scales);
      
    //Set initial guess
    roboptim::NumericQuadraticFunction::argument_t x_init( 3 );
    x_init << 0.4,0.0,0.2;

    pb.startingPoint() = x_init;

    //Set path of the roboptim-core-plugin-ipopt.so so that libltdl finds the lib.
    //The path is detected in the CMakeLists.txt which will substitute the variable PLUGIN_PATH during the compilation
    //Those two lines can be omitted if the environment variable LD_LIBRARY_PATH contains the path of the plugin
    lt_dlinit();
    lt_dlsetsearchpath (PLUGIN_PATH);

    roboptim::SolverFactory<solver_t> factory ("ipopt", pb);
    solver_t& solver = factory ();

    solver_t::result_t res = solver.minimum ();

    std::cout << solver << std::endl;

    // Check if the minimization has succeed.
    if (res.which () != solver_t::SOLVER_VALUE)
    {
        std::cout << "A solution should have been found. Failing..."
            << std::endl
            << boost::get<roboptim::SolverError> (res).what ()
            << std::endl;
        return 0;
    } 

    // Get the result.
    roboptim::Result& result = boost::get<roboptim::Result> (res);
    std::cout << "A solution has been found: " << std::endl
              << result << std::endl;
    return 1;
}
예제 #13
0
int main(int argc, char* argv[])
{
    // Load the mesh.
  Mesh mesh;
  MeshReaderH2D mloader;
  mloader.load("domain.mesh", &mesh);

  // Perform uniform mesh refinement.
  // 2 is for vertical split.
  for(int i = 0; i < INIT_REF_NUM; i++) mesh.refine_all_elements(2); 

  // Initialize boundary conditions
  DefaultEssentialBCConst<double> bc1("Bdy_perfect", 0.0);
  EssentialBCNonConst bc2("Bdy_left");
  DefaultEssentialBCConst<double> bc3("Bdy_left", 0.0);
  EssentialBCs<double> bcs(Hermes::vector<EssentialBoundaryCondition<double> *>(&bc1, &bc2));
  EssentialBCs<double> bcs_im(Hermes::vector<EssentialBoundaryCondition<double> *>(&bc1, &bc3));

  // Create an H1 space with default shapeset.
  H1Space<double> e_r_space(&mesh, &bcs, P_INIT);
  H1Space<double> e_i_space(&mesh, &bcs_im, P_INIT);
  int ndof = Space<double>::get_num_dofs(&e_r_space);
  Hermes::Mixins::Loggable::Static::info("ndof = %d", ndof);

  // Initialize the weak formulation.
  WeakFormHelmholtz wf(eps, mu, omega, sigma, beta, E0, h);

  // Initialize the FE problem.
  DiscreteProblem<double> dp(&wf, Hermes::vector<const Space<double>*>(&e_r_space, &e_i_space));

  // Initialize the solutions.
  Solution<double> e_r_sln, e_i_sln;

  // Initial coefficient vector for the Newton's method.  
  ndof = Space<double>::get_num_dofs(Hermes::vector<const Space<double>*>(&e_r_space, &e_i_space));

  Hermes::Hermes2D::NewtonSolver<double> newton(&dp);
  try
  {
    newton.set_newton_tol(NEWTON_TOL);
    newton.set_newton_max_iter(NEWTON_MAX_ITER);
    newton.solve();
  }
  catch(Hermes::Exceptions::Exception e)
  {
    e.printMsg();
    throw Hermes::Exceptions::Exception("Newton's iteration failed.");
  };

  // Translate the resulting coefficient vector into Solutions.
  Solution<double>::vector_to_solutions(newton.get_sln_vector(), Hermes::vector<const Space<double>*>(&e_r_space, &e_i_space), 
      Hermes::vector<Solution<double>*>(&e_r_sln, &e_i_sln));

  // Visualize the solution.
  ScalarView viewEr("Er [V/m]", new WinGeom(0, 0, 800, 400));
  viewEr.show(&e_r_sln);
  // viewEr.save_screenshot("real_part.bmp");

  ScalarView viewEi("Ei [V/m]", new WinGeom(0, 450, 800, 400));
  viewEi.show(&e_i_sln);
  // viewEi.save_screenshot("imaginary_part.bmp");

  // Wait for the view to be closed.
  View::wait();

  return 0;
}