STKUNIT_UNIT_TEST(norm, string_function_1)
{
  EXCEPTWATCH;
  LocalFixture     fix(4);
  mesh::fem::FEMMetaData&        metaData     = fix.metaData;
  mesh::BulkData&        bulkData     = fix.bulkData;
  //PerceptMesh&        eMesh     = fix.eMesh;
  //mesh::FieldBase*       coords_field = fix.coords_field;
  StringFunction   sfx          = fix.sfx;
  ConstantFunction sfx_res      = fix.sfx_res;

  /// Create the operator that will do the work
  /// get the l2 norm
  Norm<2> l2Norm(bulkData, &metaData.universal_part(), TURBO_NONE);
  if (0) l2Norm(sfx, sfx_res);

  /// the function to be integrated:  sqrt(Integral[(x*y*z)^2, dxdydz]) =?= (see unitTest1.py)
  StringFunction sfxyz("x*y*z", Name("sfxyz"), Dimensions(3), Dimensions(1) );
  //l2Norm(sfxyz, sfx_res);
  //sfx_expect = 0.0240562612162344;
  //STKUNIT_EXPECT_DOUBLE_EQ_APPROX( sfx_expect, sfx_res.getValue());

  /// indirection
  std::cout << "tmp srk start..." << std::endl;
  StringFunction sfxyz_first("sfxyz", Name("sfxyz_first"), Dimensions(3), Dimensions(1) );
  l2Norm(sfxyz_first, sfx_res);
  double sfx_expect = 0.0240562612162344;
  STKUNIT_EXPECT_DOUBLE_EQ_APPROX( sfx_expect, sfx_res.getValue());
}
void MovingSprite::DoWaterAccelerationBubbles()
{
	if (mTimeUntilCanSpawnWaterBubbles <= 0.0f)
	{
		ParticleEmitterManager::Instance()->CreateDirectedSpray(30,
																Vector3(m_position.X - (m_direction.X < 0.0f ? 30 : -30), m_position.Y, m_position.Z),
																Vector3(-m_direction.X, -m_direction.Y, 0),
																0.15f,
																Vector3(3200, 2000, 0),
																"Media\\Ambient\\bubble.png",
																0.03f,
																0.15f,
																1.5f,
																3.0f,
																2,
																4,
																-0.2f,
																false,
																1.0f,
																1.0f,
																-1,
																true,
																2.0f,
																0.01f * Dimensions().X,
																0.03f * Dimensions().Y,
																0.0f,
																0.9f);

		mTimeUntilCanSpawnWaterBubbles = 0.2f;
	}
}
STKUNIT_UNIT_TEST(function, stringFunction_vector_valued)
{
  EXCEPTWATCH;
  double x = 1.234;
  double y = 5.678;
  double z = 3.456;
  double t = 0;

  bool didCatch = false;
  try {
    StringFunction sfv0("v[0]=x; v[1]=y; v[2]=z; x", Name("sfv"), Dimensions(1,4), Dimensions(1,3) );
    eval_vec3_print(1,2,3,0, sfv0);
  }
  catch (...)
  {
    didCatch = true;
    std::cout << "TEST::function::stringFunctionVector: expected to catch this since dom/codomain dimensions should be rank-1" << std::endl;
  }
  STKUNIT_EXPECT_TRUE(didCatch);

  StringFunction sfv("v[0]=x*y*z; v[1]=y; v[2]=z; x", Name("sfv"), Dimensions(3), Dimensions(3) );
  eval_vec3_print(1.234, 2.345e-3, 3.456e+5, 0., sfv);
  MDArray vec = eval_vec3(x, y, z, t, sfv);
  std::cout << " x = " << x
            << " y = " << y
            << " z = " << z
            << " val = " << (vec[0]*vec[1]*vec[2]) << std::endl;
  STKUNIT_EXPECT_DOUBLE_EQ(vec[0], x*y*z);
  STKUNIT_EXPECT_DOUBLE_EQ(vec[1], y);
  STKUNIT_EXPECT_DOUBLE_EQ(vec[2], z);

}
    void DCDataSet::append(size_t count, size_t offset, size_t stride, const void* data)
    throw (DCException)
    {
        log_msg(2, "DCDataSet::append");

        if (!opened)
            throw DCException(getExceptionString("append: Dataset has not been opened/created."));

        log_msg(3, "logical_size = %s", getLogicalSize().toString().c_str());

        Dimensions target_offset(getLogicalSize());
        // extend size (dataspace) of existing dataset with count elements
        getLogicalSize()[0] += count;

        hsize_t * max_dims = new hsize_t[ndims];
        for (size_t i = 0; i < ndims; ++i)
            max_dims[i] = H5F_UNLIMITED;

        if (H5Sset_extent_simple(dataspace, 1, getLogicalSize().getPointer(), max_dims) < 0)
            throw DCException(getExceptionString("append: Failed to set new extent"));

        delete[] max_dims;
        max_dims = NULL;

        log_msg(3, "logical_size = %s", getLogicalSize().toString().c_str());

        if (H5Dset_extent(dataset, getLogicalSize().getPointer()) < 0)
            throw DCException(getExceptionString("append: Failed to extend dataset"));

        // select the region in the target DataSpace to write to
        Dimensions dim_data(count, 1, 1);
        if (H5Sselect_hyperslab(dataspace, H5S_SELECT_SET, target_offset.getPointer(),
                NULL, dim_data.getPointer(), NULL) < 0 ||
                H5Sselect_valid(dataspace) < 0)
            throw DCException(getExceptionString("append: Invalid target hyperslap selection"));

        // append data to the dataset.
        // select the region in the source DataSpace to read from
        Dimensions dim_src(offset + count * stride, 1, 1);
        hid_t dsp_src = H5Screate_simple(1, dim_src.getPointer(), NULL);
        if (dsp_src < 0)
            throw DCException(getExceptionString("append: Failed to create src dataspace while appending"));

        if (H5Sselect_hyperslab(dsp_src, H5S_SELECT_SET, Dimensions(offset, 0, 0).getPointer(),
                Dimensions(stride, 1, 1).getPointer(), dim_data.getPointer(), NULL) < 0 ||
                H5Sselect_valid(dsp_src) < 0)
            throw DCException(getExceptionString("append: Invalid source hyperslap selection"));

        if (!data || (count == 0))
        {
            H5Sselect_none(dataspace);
            data = NULL;
        }

        if (H5Dwrite(dataset, this->datatype, dsp_src, dataspace, dsetWriteProperties, data) < 0)
            throw DCException(getExceptionString("append: Failed to append dataset"));

        H5Sclose(dsp_src);
    }
      /// Note that since this is a Function also, one can make multiple compositions e.g. h(g(f(x))) by
      /// CompositeFunction g_of_f (f, g)
      /// CompositeFunction h_of_g_of_f (g_of_f, h);
      /// The first function in the list is always applied first.
      CompositeFunction(const char *name, Function& func_1, Function& func_2,
                        Dimensions domain_dimensions = Dimensions(),
                        Dimensions codomain_dimensions = Dimensions(),
                        unsigned integration_order = 0) : Function(name, domain_dimensions, codomain_dimensions, integration_order),
                                                          m_func1(func_1), m_func2(func_2) 
      {
        EXCEPTWATCH;
//         std::cout << "func_1 = " << func_1 << std::endl;
//         std::cout << "func_2 = " << func_2 << std::endl;
//         std::cout << "domain_dimensions= " << domain_dimensions << std::endl;
//         std::cout << "codomain_dimensions= " << codomain_dimensions << std::endl;
        setDomainDimensions(func_1.getDomainDimensions());
        setCodomainDimensions(func_2.getCodomainDimensions());
      }
END_TEST

START_TEST ( test_Layout_new_with_id_and_dimensions )
{
  std::string id="TestLayoutId";
  Dimensions dimensions=Dimensions(LN,-1.1,2.2,3.3);
  Layout* l=new Layout(LN,id,&dimensions);
  fail_unless( l->getTypeCode()    == SBML_LAYOUT_LAYOUT );
  fail_unless( l->getMetaId()      == "" );
  //    fail_unless( l->getNotes()       == "" );
  //    fail_unless( l->getAnnotation()  == "" );
  fail_unless( l->getId()          == id );
  fail_unless( l->isSetId());
  Dimensions* dim=(l->getDimensions());
  fail_unless (dim->getWidth()  == dimensions.getWidth() );
  fail_unless (dim->getHeight() == dimensions.getHeight() );
  fail_unless (dim->getDepth()  == dimensions.getDepth() );
  
  fail_unless ( l->getNumCompartmentGlyphs()         == 0 );
  fail_unless ( l->getNumSpeciesGlyphs()             == 0 );
  fail_unless ( l->getNumReactionGlyphs()            == 0 );
  fail_unless ( l->getNumTextGlyphs()                == 0 );
  fail_unless ( l->getNumAdditionalGraphicalObjects() == 0 );
  delete l;
}
void Graphics::drawTerrain(Terrain* terrain)
{
	// Set effect data
	HR(mFX->SetTechnique(mhTerrainTech));
	D3DXMATRIX m;
	D3DXMatrixIdentity(&m);
	setEffectData(mTex0, terrain->getPosition(), Dimensions(1, 1, 1), terrain->getMaterial(), 0, m);
	
	// Texture handles
	HR(mFX->SetTexture(mhTex0, mTex0));
	HR(mFX->SetTexture(mhTex1, mTex1));
	HR(mFX->SetTexture(mhTex2, mTex2));
	HR(mFX->SetTexture(mhBlendMap, mBlendMap));

	// Begin passes.
	HR(mFX->Begin(0, 0));
	HR(mFX->BeginPass(0));

	for(UINT i = 0; i < terrain->mSubGridMeshes.size(); ++i) {
		//if(gCamera->isVisible(terrain->mSubGridBndBoxes[i]))
			HR(terrain->mSubGridMeshes[i]->DrawSubset(0));
	}
		
	HR(mFX->EndPass());
	HR(mFX->End());
}
RoomHallways_Lower::RoomHallways_Lower(void)
    : Room(0, -2*screen->h, Dimensions(screen->w, screen->h), Element::NORMAL, LAYER_ENV_LOWER), m_SnowPositions()
{
    BuildWallsLeft();
    BuildWallsRight();

    // Initialise the little snow positions
    SDL_Rect crack1 = { 29*TILE_SIZE, TILE_SIZE, TILE_SIZE/2, TILE_SIZE/2 };
    SDL_Rect crack2 = { static_cast<Sint16>(29.5*TILE_SIZE), TILE_SIZE, TILE_SIZE/2, TILE_SIZE/2 };
    SDL_Rect crack3 = { 29*TILE_SIZE, static_cast<Sint16>(1.5*TILE_SIZE), TILE_SIZE/2, TILE_SIZE/2 };
    SDL_Rect crack4 = { static_cast<Sint16>(29.5*TILE_SIZE), static_cast<Sint16>(1.5*TILE_SIZE), TILE_SIZE/2, TILE_SIZE/2 };
    SDL_Rect cracks[] = {crack1, crack2, crack3, crack4};

    for (int i = 0; i < NUM_SNOW; i++)
    {
        // Create a random position, and a random corresponding spritesheet index
        m_SnowPositions.push_back(
            pair<Position, SDL_Rect>(
                Position(rand() % (HALLWAY_WIDTH/8) * 8,
                         rand() % ((HALLWAY_HEIGHT-TILE_SIZE)/8) * 8),
                cracks[rand()%4]
            )
        );
    }
}
Exemple #9
0
    void operator()(ThreadParams& params,
                const std::string& name, T_Scalar* value,
                const std::string& attrName = "", T_Attribute* attribute = nullptr)
    {
        log<picLog::INPUT_OUTPUT>("HDF5: read %1%D scalars: %2%") % simDim % name;

        Dimensions domain_offset(0, 0, 0);
        for (uint32_t d = 0; d < simDim; ++d)
            domain_offset[d] = Environment<simDim>::get().GridController().getPosition()[d];

        // avoid deadlock between not finished pmacc tasks and mpi calls in adios
        __getTransactionEvent().waitForFinished();

        DomainCollector::DomDataClass data_class;
        DataContainer *dataContainer =
            params.dataCollector->readDomain(params.currentStep,
                                               name.c_str(),
                                               Domain(domain_offset, Dimensions(1, 1, 1)),
                                               &data_class);

        typename traits::PICToSplash<T_Scalar>::type splashType;
        *value = *static_cast<T_Scalar*>(dataContainer->getIndex(0)->getData());
        __delete(dataContainer);

        if(!attrName.empty())
        {
            log<picLog::INPUT_OUTPUT>("HDF5: read attribute %1% for scalars: %2%") % attrName % name;
            params.dataCollector->readAttributeInfo(params.currentStep, name.c_str(), attrName.c_str()).read(attribute, sizeof(T_Attribute));
            log<picLog::INPUT_OUTPUT>("HDF5: attribute %1% = %2%") % attrName % *attribute;
        }
    }
/*
 * Sets the dimensions to a copy of the Dimensions object given.
 */ 
void
BoundingBox::setDimensions (const Dimensions* d)
{
  if(!d) return;
  this->mDimensions = Dimensions(*d);
  this->mDimensions.connectToParent(this);
  this->mDimensionsExplicitlySet = true;
}
Exemple #11
0
bool window::select_activate(grid::POS dir) {
    Display* disp = XOpenDisplay(NULL);
    if (disp == NULL) {
        ERROR("unable to get display");
        return false;
    }

    std::vector<Window> wins;

    {
        size_t win_count = 0;
        static Atom clientlist_msg = XInternAtom(disp, "_NET_CLIENT_LIST", False);
        Window* all_wins = (Window*)x11_util::get_property(disp, DefaultRootWindow(disp),
                XA_WINDOW, clientlist_msg, &win_count);
        if (all_wins == NULL || win_count == 0) {
            ERROR("unable to get list of windows");
            if (all_wins != NULL) {
                x11_util::free_property(all_wins);
            }
            XCloseDisplay(disp);
            return false;
        }
        // only select normal windows, ignore docks and menus
        for (size_t i = 0; i < win_count; ++i) {
            if (!is_dock_window(disp, all_wins[i]) && !is_menu_window(disp, all_wins[i])) {
                wins.push_back(all_wins[i]);
            }
        }
        x11_util::free_property(all_wins);
    }

    size_t active_window = 0;
    dim_list_t all_windows;
    {
        Window* active = get_active_window(disp);
        if (active == NULL) {
            XCloseDisplay(disp);
            return false;
        }
        for (size_t i = 0; i < wins.size(); ++i) {
            if (wins[i] == *active) {
                active_window = i;
                DEBUG("ACTIVE:");
            }
            all_windows.push_back(Dimensions());
            get_window_size(disp, wins[i], &all_windows.back(), NULL, NULL);
        }
        x11_util::free_property(active);
    }

    size_t next_window;
    neighbor::select(dir, all_windows, active_window, next_window);

    bool ok = activate_window(disp, wins[active_window], wins[next_window]);

    XCloseDisplay(disp);
    return ok;
}
STKUNIT_UNIT_TEST(function, stringFunction_derivative_2)
{
  EXCEPTWATCH;
  for (unsigned ipts = 0; ipts < NPTS; ipts++)
  {
    double x = testpoints_fd[ipts][0];
    double y = testpoints_fd[ipts][1];
    double z = testpoints_fd[ipts][2];
    double t = testpoints_fd[ipts][3];

    double eps=1.e-10;
    double eps_loc = eps*(std::fabs(x) + std::fabs(y) + std::fabs(z) + std::fabs(t))/4.0;

    // start_demo_stringFunction_derivative_2
    StringFunction sf(" sin(x*y*z*z) " );
    std::string grad[] = {"y*z*z*cos(x*y*z*z)",  "x*z*z*cos(x*y*z*z)", "2*x*y*z*cos(x*y*z*z)"};
    std::string gradv = "v[0]="+grad[0]+"; v[1]="+grad[1]+" ; v[2]="+grad[2]+";";
    StringFunction dsf_grad(gradv.c_str(), Name("test"), Dimensions(3), Dimensions(3) );
    MDArrayString dxyz(3,1);
    dxyz(0,0)="x"; dxyz(1,0)="y"; dxyz(2,0)="z";
    sf.set_gradient_strings(grad, 3);
    Teuchos::RCP<Function> dsf_grad_fd = sf.derivative_test_fd(dxyz, eps_loc);
    Teuchos::RCP<Function> dsf_grad_2  = sf.derivative(dxyz);

    MDArray dv_fd = eval_vec3(x, y, z, t, *dsf_grad_fd);
    MDArray dv2   = eval_vec3(x, y, z, t, *dsf_grad_2);
    MDArray dv    = eval_vec3(x, y, z, t, dsf_grad);

    // the two different functions should give the same result
    for (int ii = 0; ii < 3; ii++)
    {
      //std::cout << "\n ii= " << ii << "\n"<< std::endl;
      STKUNIT_EXPECT_DOUBLE_EQ(dv(ii), dv2(ii));
      if (std::fabs(dv(ii)-dv_fd(ii)) > 0.5*(std::fabs(dv_fd(ii))+std::fabs(dv(ii)))*1.e-6)
      {
        std::cout << "\nii = " << ii << " x= "<<x<<" y= "<<y<<" z= " << z << " expected= " << dv(ii) << " actual= " << dv_fd(ii) << std::endl;
      }

      STKUNIT_EXPECT_DOUBLE_EQ_APPROX_TOL(dv(ii), dv_fd(ii), 1.e-4);
    }


    // end_demo
  }
}
 void DCDataSet::read(Dimensions dstBuffer,
         Dimensions dstOffset,
         Dimensions &sizeRead,
         uint32_t& srcNDims,
         void* dst)
 throw (DCException)
 {
     read(dstBuffer, dstOffset, getLogicalSize(), Dimensions(0, 0, 0),
             sizeRead, srcNDims, dst);
 }
END_TEST

START_TEST ( test_Layout_setDimensions )
{
  Dimensions dimensions=Dimensions(LN,-1.1,2.2,-3.3);
  L->setDimensions(&dimensions);
  Dimensions* dim=(L->getDimensions());
  fail_unless(dim->getWidth()  == dimensions.getWidth());
  fail_unless(dim->getHeight() == dimensions.getHeight());
  fail_unless(dim->getDepth()  == dimensions.getDepth());
}
Exemple #15
0
	App::PointInt Viewer::calculateWindowTopLeft(ResizePositionMethod method, const SizeInt &newSize ) {
		wxDisplay display(DisplayFromPointFallback(PositionScreen()));
		auto rtDesktop = wxToRect(display.GetClientArea());

		switch (method) {
		case ResizePositionMethod::PositionToScreen:
			return rtDesktop.TopLeft() + RoundCast((rtDesktop.Dimensions() - newSize) * 0.5f);

		case ResizePositionMethod::PositionToCurrent:
			{
				auto pt = AnchorCenter() + RoundCast(newSize * -0.5f);
				if ((pt.X + newSize.Width) > rtDesktop.Right()) {
					pt.X = rtDesktop.Right() - newSize.Width;
				}
				else if (pt.X < rtDesktop.Left()) {
					pt.X = rtDesktop.Left();
				}

				if (pt.Y + newSize.Height > rtDesktop.Bottom()) {
					pt.Y = rtDesktop.Bottom() - newSize.Height;
				}
				else if (pt.Y < rtDesktop.Top()) {
					pt.Y = rtDesktop.Top();
				}

				AnchorTL(pt);

				return pt;
			}

		case ResizePositionMethod::PositionNothing:
			{
				// Cap to screen
				PointInt pt = AnchorTL();

				if ((pt.X + newSize.Width) > rtDesktop.Right())
					pt.X=rtDesktop.Right()-newSize.Width;
				else if (pt.X < rtDesktop.Left())
					pt.X = rtDesktop.Left();

				if ((pt.Y + newSize.Height) > rtDesktop.Bottom())
					pt.Y=rtDesktop.Bottom()-newSize.Height;
				else if (pt.Y < rtDesktop.Top())
					pt.Y=rtDesktop.Top();

				AnchorCenter(pt + RoundCast(newSize * 0.5f));

				return pt;
			}

		default:
			DO_THROW(Err::InvalidParam, "Invalid reposition method: " + ToAString(method));
		}
	}
    void Visualisation::initContainer()
    {
        Container container(Dimensions(10, 4, 5), 1);
        IPackageGenerator* generator = new PackageGenerator(container.getDimensions(), 10, 5);

        if(loader != nullptr)
            delete loader;
            
        loader = new ContainerLoader(container, generator);

        delete generator;
    }
END_TEST

START_TEST ( test_BoundingBox_setDimensions )
{
  Dimensions dim=Dimensions(LN,-4.4,5.5,-6.6);
  BB->setDimensions(&dim);
  Dimensions *dim2=BB->getDimensions();
  fail_unless(dim2 != NULL);
  fail_unless(dim.getWidth () == dim2->getWidth () );
  fail_unless(dim.getHeight() == dim2->getHeight() );
  fail_unless(dim.getDepth () == dim2->getDepth () );
}
STKUNIT_UNIT_TEST(function, stringFunction_multiplePoints)
{
  EXCEPTWATCH;
  MDArray points(NPTS, 3);
  MDArray output(NPTS, 1);
  MDArray output_expect(NPTS, 1);

  StringFunction sf1("x+y*z");
  for (unsigned ipts = 0; ipts < NPTS; ipts++)
  {
    double x = testpoints[ipts][0];
    double y = testpoints[ipts][1];
    double z = testpoints[ipts][2];
    double t = testpoints[ipts][3];
    points(ipts, 0) = x;
    points(ipts, 1) = y;
    points(ipts, 2) = z;
    //points(ipts, 3) = t;

    //std::cout << "stringFunction_op: ipts= " << ipts << std::endl;

    double vx = eval(x, y, z, t, sf1);
    STKUNIT_EXPECT_DOUBLE_EQ(vx, x+y*z);
    output_expect(ipts, 0) = vx;
  }
  //StringFunction sf2(sf1.getFunctionString().c_str(), Name("sf2"), Dimensions(NPTS, 4), Dimensions(NPTS, 1));
  StringFunction sf2(sf1.getFunctionString().c_str(), Name("sf2"), Dimensions( 3), Dimensions( 1));
  sf2(points, output, 0.0);
  for (unsigned ipts = 0; ipts < NPTS; ipts++)
  {
    STKUNIT_EXPECT_DOUBLE_EQ(output(ipts, 0), output_expect(ipts, 0));
  }
  /// indirection
  StringFunction sf2_1("sf2", Name("sf2_1"), Dimensions( 3), Dimensions( 1));
  sf2_1(points, output, 0.0);
  for (unsigned ipts = 0; ipts < NPTS; ipts++)
  {
    STKUNIT_EXPECT_DOUBLE_EQ(output(ipts, 0), output_expect(ipts, 0));
  }
}
void Graphics::drawRay(D3DXVECTOR3 start, D3DXVECTOR3 direction, float length, float width)
{
	// NOTE: The vertices are not positioned 100% correctly.
	VertexPNT* v;
	WORD* k;

	mRayMesh->LockVertexBuffer(0, (void**)&v);
	mRayMesh->LockIndexBuffer(0, (void**)&k);

	D3DXVECTOR3 right = gCamera->getRight();

	v[0].pos = start - right * width;
	v[1].pos = start + D3DXVECTOR3(0, -10, 0)  + right * width;
	v[2].pos = start + direction * length + right * width;
	v[3].pos = start + direction * length - right * width;

	v[0].tex0 = D3DXVECTOR2(0, 0);
	v[1].tex0 = D3DXVECTOR2(0, 1);
	v[2].tex0 = D3DXVECTOR2(1, 1);
	v[3].tex0 = D3DXVECTOR2(1, 0);

	k[0] = 0;
	k[1] = 1;
	k[2] = 2;
	k[3] = 0;
	k[4] = 2;
	k[5] = 3;

	mRayMesh->UnlockVertexBuffer();
	mRayMesh->UnlockIndexBuffer();

	mFX->SetTechnique(mhTex);
	//D3DXMATRIX I;
	//D3DXMatrixIdentity(&I);
	//setEffectParameters(I);
	setEffectData(mWhiteTexture, D3DXVECTOR3(0, 0, 0), Dimensions(), Material(BLUE, D3DXCOLOR(0, 0, 1, 0.5), BLUE));

	HR(gd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, true));
	HR(gd3dDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA));
	HR(gd3dDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA));

	HR(mFX->Begin(0, 0));
	HR(mFX->BeginPass(0));

	mRayMesh->DrawSubset(0);

	HR(mFX->EndPass());
	HR(mFX->End());

	HR(gd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, false));
}
/*
 * Creates a new BoundingBox from the given XMLNode
 */
BoundingBox::BoundingBox(const XMLNode& node, unsigned int l2version)
 :  SBase(2,l2version)
  , mId("")
  , mPosition(2,l2version)
  , mDimensions(2,l2version)
  ,mPositionExplicitlySet (false)
  ,mDimensionsExplicitlySet (false)
{
    mPosition.setElementName("position");

    const XMLAttributes& attributes=node.getAttributes();
    const XMLNode* child;

    //ExpectedAttributes ea(getElementName());
    ExpectedAttributes ea;
    addExpectedAttributes(ea);
    this->readAttributes(attributes,ea);
    unsigned int n=0,nMax = node.getNumChildren();
    while(n<nMax)
    {
        child=&node.getChild(n);
        const std::string& childName=child->getName();
        if(childName=="position")
        {
            this->mPosition=Point(*child);
            this->mPositionExplicitlySet = true;
        }
        else if(childName=="dimensions")
        {
            this->mDimensions=Dimensions(*child);
            this->mDimensionsExplicitlySet = true;
        }
        else if(childName=="annotation")
        {
            this->mAnnotation=new XMLNode(*child);
        }
        else if(childName=="notes")
        {
            this->mNotes=new XMLNode(*child);
        }
        else
        {
            //throw;
        }
        ++n;
    }    
  setSBMLNamespacesAndOwn(new LayoutPkgNamespaces(2,l2version));
  connectToChild();
}
Exemple #21
0
ToolsSplashParallel::ToolsSplashParallel(ProgramOptions &options, Dims &mpiTopology, std::ostream &outStream) :
ITools(options, mpiTopology, outStream),
dc(MPI_COMM_WORLD, MPI_INFO_NULL, Dimensions(mpiTopology[0], mpiTopology[1], mpiTopology[2]), 100),
errorStream(std::cerr)
{
    DataCollector::FileCreationAttr fattr;
    fattr.enableCompression = false;
    fattr.fileAccType = DataCollector::FAT_READ_MERGED;
    fattr.mpiPosition.set(0, 0, 0);
    fattr.mpiSize.set(0, 0, 0);

    if (m_options.verbose)
        errorStream << m_options.inputFile << std::endl;

    dc.open(m_options.inputFile.c_str(), fattr);
}
int main(int argc, const char *argv[])
{
    Field a(Dimensions(8, 8, 1));
    ConstExpr b(5), c(2);

    core_assign(a, b);

    FieldExpr<Field> typedef A;
    BinExpr<SumOp, A, ConstExpr> typedef AB;
    BinExpr<MultOp, AB, ConstExpr> typedef ABC;

    core_assign(a, ABC(AB(A(a), b), c));

    core_write_field(std::cout, a);
    return 0;
}
int main(int argc, const char *argv[])
{
    Field a(Dimensions(8, 8, 1), device);

    a <<= 5;
    a <<= 5.0;
    a <<= (a + 5) * 2;
    a <<= (a + 5.0) * 2;

    #ifdef __CUDACC__
    a.copy_gpu_to_cpu();
    #endif

    std::cout << a;
    return 0;
}
Exemple #24
0
	SizeInt Viewer::calculateImageSize( ResizeBehaviour mode, float xratio, float yratio, const SizeInt &imageSize, const SizeInt &windowEdges ) {
		wxDisplay display(DisplayFromPointFallback(PositionScreen()));
		auto rtDesktop = wxToRect(display.GetClientArea());

		// The image is larger than the desktop. The image is not supposed
		// to be downscaled so fill the screen.
		if ((mode == ResizeEnlargeOnly) && (xratio < 1.0) && (yratio < 1.0))
			return rtDesktop.Dimensions();
		// The image is smaller than the desktop. It must not be made
		// smaller needlessly so size the window after the image.
		else if ((mode == ResizeReduceOnly) && (xratio > 1.0) && (yratio > 1.0))
			return SizeInt(
				std::max<int>(MinWindowWidth, imageSize.Width + windowEdges.Width),
				std::max<int>(MinWindowHeight,imageSize.Height + windowEdges.Height));

		return Maximum(SizeInt(MinWindowWidth, MinWindowHeight), Minimum(RoundCast(imageSize * std::min(xratio, yratio)) + windowEdges, rtDesktop.Dimensions()));
	}
Exemple #25
0
void jpcnn_classify_image(void* networkHandle, void* inputHandle, unsigned int flags, int layerOffset, float** outPredictionsValues, int* outPredictionsLength, char*** outPredictionsNames, int* outPredictionsNamesLength) {

  const bool doMultiSample = (flags & JPCNN_MULTISAMPLE);
  const bool doRandomSample = (flags & JPCNN_RANDOM_SAMPLE);
  const bool skipRescale = (flags & JPCNN_SKIP_RESCALE);

  Graph* graph = (Graph*)(networkHandle);
  Buffer* input = (Buffer*)(inputHandle);

  bool doFlip;
  int imageSize;
  bool isMeanChanneled;
  if (graph->_isHomebrewed) {
    imageSize = 224;
    doFlip = false;
    isMeanChanneled = true;
  } else {
    imageSize = 227;
    doFlip = true;
    isMeanChanneled = false;
  }

  Buffer* rescaledInput;
  if (skipRescale) {
    // substract mean
    rescaledInput = new Buffer(Dimensions(input->_dims[0], graph->_inputSize, graph->_inputSize, 1));
    rescaledInput->copyDataFrom(input);
    matrix_add_inplace(rescaledInput, graph->_dataMean, -1.0f);
  } else {
    const int rescaledSize = graph->_inputSize;
    PrepareInput prepareInput(graph->_dataMean, !doMultiSample, doFlip, doRandomSample, imageSize, rescaledSize, isMeanChanneled);
    rescaledInput = prepareInput.run(input);
  }
  Buffer* predictions = graph->run(rescaledInput, layerOffset);


  *outPredictionsValues = predictions->_data;
  *outPredictionsLength = predictions->_dims.elementCount();
  if (layerOffset == 0) {
    *outPredictionsNames = graph->_labelNames;
    *outPredictionsNamesLength = graph->_labelNamesLength;
  } else {
    *outPredictionsNames = NULL;
    *outPredictionsNamesLength = predictions->_dims.removeDimensions(1).elementCount();
  }
}
STKUNIT_UNIT_TEST(function, stringFunction_derivative_1)
{
  EXCEPTWATCH;
  for (unsigned ipts = 0; ipts < NPTS; ipts++)
  {
    double x = testpoints[ipts][0];
    double y = testpoints[ipts][1];
    double z = testpoints[ipts][2];
    double t = testpoints[ipts][3];

    double eps=1.e-6;
    double eps_loc = eps*(std::fabs(x) + std::fabs(y) + std::fabs(z) + std::fabs(t))/4.0;

    // start_demo_stringFunction_derivative_1
    StringFunction sfxy(" x - y ");
    StringFunction dsfxy_grad("v[0]=1; v[1]= -1; v[2]=0", Name("test"), Dimensions(3), Dimensions(3) );
    MDArrayString dxyz(3,1);
    dxyz(0,0)="x"; dxyz(1,0)="y"; dxyz(2,0)="z";
    std::string grad[] = {"1","-1","0"};
    sfxy.set_gradient_strings(grad, 3);
    Teuchos::RCP<Function> dsfxy_grad_1  = sfxy.derivative_test(dxyz);
    Teuchos::RCP<Function> dsfxy_grad_fd = sfxy.derivative_test_fd(dxyz, eps_loc);
    Teuchos::RCP<Function> dsfxy_grad_2  = sfxy.derivative(dxyz);

    MDArray dvxy1   = eval_vec3(x, y, z, t, *dsfxy_grad_1);
    MDArray dvxy_fd = eval_vec3(x, y, z, t, *dsfxy_grad_fd);
    MDArray dvxy2   = eval_vec3(x, y, z, t, *dsfxy_grad_2);
    MDArray dvxy    = eval_vec3(x, y, z, t, dsfxy_grad);

    // the two different functions should give the same result
    for (int ii = 0; ii < 3; ii++)
    {
      STKUNIT_EXPECT_DOUBLE_EQ(dvxy(ii), dvxy1(ii));
      STKUNIT_EXPECT_DOUBLE_EQ(dvxy(ii), dvxy2(ii));
      STKUNIT_EXPECT_DOUBLE_EQ_APPROX(dvxy(ii), dvxy_fd(ii));
    }

    // and they should give the same result as C++
    STKUNIT_EXPECT_DOUBLE_EQ(dvxy(0), 1.0);
    STKUNIT_EXPECT_DOUBLE_EQ(dvxy(1), -1.0);

    // end_demo
  }
}
void Graphics::drawTest(ID3DXMesh* mesh, IDirect3DTexture9* texture, D3DXVECTOR3 position, D3DXVECTOR3 rotation)
{
	HR(mFX->SetTechnique(mhTexTech));

	D3DXMATRIX M;

	float rotY = atan2f(rotation.x, rotation.z);
	D3DXMatrixRotationY(&M, rotY);

	setEffectData(texture, position, Dimensions(500), Material(), 0, M, true);

	HR(mFX->Begin(0, 0));
	HR(mFX->BeginPass(0));

	mesh->DrawSubset(0);

	HR(mFX->EndPass());
	HR(mFX->End());
}
        optional<Dimensions> getDimensions() const
        {
            if (polylines.empty())
                return optional<Dimensions>();

            optional<Point> min = getMinPoint(polylines[0].points);
            optional<Point> max = getMaxPoint(polylines[0].points);
            for (unsigned i = 0; i < polylines.size(); ++i) {
                if (getMinPoint(polylines[i].points)->x < min->x)
                    min->x = getMinPoint(polylines[i].points)->x;
                if (getMinPoint(polylines[i].points)->y < min->y)
                    min->y = getMinPoint(polylines[i].points)->y;
                if (getMaxPoint(polylines[i].points)->x > max->x)
                    max->x = getMaxPoint(polylines[i].points)->x;
                if (getMaxPoint(polylines[i].points)->y > max->y)
                    max->y = getMaxPoint(polylines[i].points)->y;
            }

            return optional<Dimensions>(Dimensions(max->x - min->x, max->y - min->y));
        }
 Teuchos::RCP<Function > StringFunction::derivative_test_fd(MDArrayString& deriv_spec, double eps)
 {
   std::string eps_string = boost::lexical_cast<std::string>(eps);
   std::string fstr = m_func_string;
   std::string fstr_p = m_func_string;
   std::string fstr_m = m_func_string;
   // FIXME this is just for a simple test and only works for linear functions
   int outputDim = deriv_spec.dimension(0);
   static std::string s_xyzt[] = {"x", "y", "z", "t"};
   std::string out_str;
   for (int iresult = 0; iresult < deriv_spec.dimension(0); iresult++)
     {
       fstr = m_func_string;
       fstr_p = m_func_string;
       fstr_m = m_func_string;
       for (int jderiv = 0; jderiv < deriv_spec.dimension(1); jderiv++)
         {
           //std::cout << "deriv_spec= " << deriv_spec(iresult, jderiv)  << " fstr= " << fstr << std::endl;
           std::string rep = "("+deriv_spec(iresult, jderiv)+"+"+eps_string+")";
           Util::replace(fstr_p, deriv_spec(iresult, jderiv), rep);
           rep = "("+deriv_spec(iresult, jderiv)+"-"+eps_string+")";
           Util::replace(fstr_m, deriv_spec(iresult, jderiv), rep);
           fstr = "(("+fstr_p+")-("+fstr_m+"))/(2.0*"+eps_string+")";
           //std::cout << "xyzt= " << xyzt << " fstr= " << fstr << std::endl;
         }
       if (deriv_spec.dimension(0) > 1)
         {
           out_str += "v["+boost::lexical_cast<std::string>(iresult)+"]= " + fstr+";";
         }
       else
         {
           out_str = fstr;
         }
     }
   std::string fname = getName();
   std::string new_name = "deriv_"+fname;
   //std::cout << "fname= " << fname << " new_name= " << new_name << " out_str= " << out_str << std::endl;
   //Util::pause(true, "tmp:: StringFunction::derivative");
   return Teuchos::rcp(new StringFunction(out_str.c_str(), Name(new_name), Dimensions(3), Dimensions(outputDim) ));
 }
 Teuchos::RCP<Function > StringFunction::derivative_test(MDArrayString& deriv_spec)
 {
   bool debug=true;
   std::string fstr = m_func_string;
   // FIXME this is just for a simple test and only works for linear functions
   int outputDim = deriv_spec.dimension(0);
   static std::string s_xyzt[] = {"x", "y", "z", "t"};
   std::string out_str;
   //if (debug) std::cout << "deriv_spec= " << deriv_spec << std::endl;
   for (int iresult = 0; iresult < deriv_spec.dimension(0); iresult++)
     {
       fstr = m_func_string;
       for (int jderiv = 0; jderiv < deriv_spec.dimension(1); jderiv++)
         {
           if (debug) std::cout << "deriv_spec= " << deriv_spec(iresult, jderiv)  << " fstr= " << fstr << std::endl;
           char xyzt = deriv_spec(iresult, jderiv)[0];
           std::replace( fstr.begin(), fstr.end(), xyzt, '1' );
           if (debug) std::cout << "xyzt= " << xyzt << " fstr= " << fstr << std::endl;
         }
       for (int jderiv = 0; jderiv < 4; jderiv++)
         {
           char xyzt = s_xyzt[jderiv][0];
           std::replace( fstr.begin(), fstr.end(), xyzt, '0' );
           if (debug) std::cout << "xyzt= " << xyzt << " fstr= " << fstr << std::endl;
         }
       if (deriv_spec.dimension(0) > 1)
         {
           out_str += "v["+boost::lexical_cast<std::string>(iresult)+"]= " + fstr+";";
         }
       else
         {
           out_str = fstr;
         }
     }
   std::string fname = getName();
   std::string new_name = "deriv_"+fname;
   if (debug) std::cout << "fname= " << fname << " new_name= " << new_name << " out_str= " << out_str << std::endl;
   //Util::pause(true, "tmp:: StringFunction::derivative");
   return Teuchos::rcp(new StringFunction(out_str.c_str(), Name(new_name), Dimensions(3), Dimensions(outputDim) ));
 }