TEST_F(testLHCNoiseFB, constructor2) {

    auto lhcnfb = new LHCNoiseFB(1.0, 0.1, 0.9, 100, false);

    auto params = std::string(TEST_FILES) +
                  "/LHCNoiseFB/constructor/test2/";
    f_vector_t v;

    util::read_vector_from_file(v, params + "g.txt");
    // util::dump(lhcnfb->fG, "fG\n");
    ASSERT_EQ(v.size(), lhcnfb->fG.size());

    auto epsilon = 1e-8;
    for (unsigned int i = 0; i < v.size(); ++i) {
        auto ref = v[i];
        auto real = lhcnfb->fG[i];

        ASSERT_NEAR(ref, real, epsilon * std::max(fabs(ref), fabs(real)))
            << "Testing of fG failed on i " << i << std::endl;
    }

    delete lhcnfb;
}
TEST_F(testLHCNoiseFB, fwhm_interpolation2) {
    auto Slice = Context::Slice;

    auto lhcnfb = new LHCNoiseFB(1.0);
    for (uint i = 0; i < Slice->n_slices; i++) {
        Slice->n_macroparticles[i] = 100 * i;
        Slice->bin_centers[i] = 1e10 * (i + 1) / Slice->n_slices;
    }

    auto params = std::string(TEST_FILES) +
                  "/LHCNoiseFB/fwhm_interpolation/test2/";
    f_vector_t v;

    util::read_vector_from_file(v, params + "return.txt");
    // util::dump(lhcnfb->fG, "fG\n");
    auto index = mymath::arange<uint>(0, 99);
    auto epsilon = 1e-8;
    auto ref = v[0];
    auto real = lhcnfb->fwhm_interpolation(index, 1);
    ASSERT_NEAR(ref, real, epsilon * std::max(fabs(ref), fabs(real)));

    delete lhcnfb;
}
TEST_F(testLHCNoiseFB, fwhm_single_bunch1) {
    auto Slice = Context::Slice;

    auto lhcnfb = new LHCNoiseFB(1.0);
    for (uint i = 0; i < Slice->n_slices; i++) {
        Slice->n_macroparticles[i] = (Slice->n_slices - i);
        Slice->bin_centers[i] = 1e10 * (i + 1) / Slice->n_slices;
    }
    lhcnfb->fwhm_single_bunch();

    auto params = std::string(TEST_FILES) +
                  "/LHCNoiseFB/fwhm_single_bunch/test1/";
    f_vector_t v;

    util::read_vector_from_file(v, params + "bl_meas.txt");
    // util::dump(lhcnfb->fG, "fG\n");
    auto epsilon = 1e-8;
    auto ref = v[0];
    auto real = lhcnfb->fBlMeas;
    ASSERT_NEAR(ref, real, epsilon * std::max(fabs(ref), fabs(real)));

    delete lhcnfb;
}
TEST_F(testLHCNoiseFB, track1)
{

    auto long_tracker = new RingAndRfSection();

    auto lhcnfb = new LHCNoiseFB(1.0, 0.1, 0.9, 1);

    f_vector_t res;
    for (uint i = 0; i < 100; ++i) {
        long_tracker->track();
        Context::Slice->track();
        lhcnfb->track();
        res.push_back(lhcnfb->fX);
    }

    auto params =
        std::string(TEST_FILES) + "/LHCNoiseFB/track/test1/";
    f_vector_t v;

    util::read_vector_from_file(v, params + "x.txt");
    // util::dump(lhcnfb->fG, "fG\n");

    ASSERT_EQ(v.size(), res.size());

    auto epsilon = 1e-8;
    for (unsigned int i = 0; i < v.size(); ++i) {
        auto ref = v[i];
        auto real = res[i];

        ASSERT_NEAR(ref, real, epsilon * std::max(fabs(ref), fabs(real)))
                << "Testing of fX failed on i " << i << std::endl;
    }

    delete lhcnfb;
    delete long_tracker;
}
TEST(WingComponentSegment5, GetSegmentIntersection_BUG)
{
    const char* filename = "TestData/CS_SegIntersectionBUG.xml";
    ReturnCode tixiRet;
    TiglReturnCode tiglRet;

    TiglCPACSConfigurationHandle tiglHandle = -1;
    TixiDocumentHandle tixiHandle = -1;

    tixiRet = tixiOpenDocument(filename, &tixiHandle);
    ASSERT_EQ (SUCCESS, tixiRet);
    tiglRet = tiglOpenCPACSConfiguration(tixiHandle, "", &tiglHandle);
    ASSERT_EQ(TIGL_SUCCESS, tiglRet);

    double xsi = 0;
    TiglBoolean hasWarning;
    tiglRet = tiglWingComponentSegmentGetSegmentIntersection(tiglHandle, "wing_Cseg", "wing_Seg2", 0.0589568, 1., 0.35, 1., 1., &xsi, &hasWarning);
    ASSERT_EQ(TIGL_SUCCESS, tiglRet);
    ASSERT_EQ(TIGL_TRUE, hasWarning);
    ASSERT_NEAR(1.0, xsi, 1e-2);

    ASSERT_EQ(TIGL_SUCCESS, tiglCloseCPACSConfiguration(tiglHandle));
    ASSERT_EQ(SUCCESS, tixiCloseDocument(tixiHandle));
}
Exemple #6
0
	void TestDrawListRandom(int numEntries) {

		DrawList<MyData> list;
		std::vector<double> configured;
		std::vector<double> drawn;

		const unsigned int cnt = numEntries;
		const unsigned int numDraw = cnt * 4096;
		double probSum = 0;

		list.resize(cnt);
		drawn.resize(cnt);
		configured.resize(cnt);

		// fill
		for (unsigned int i = 0; i < cnt; ++i) {
			double rnd = double(rand()) / double(RAND_MAX);
			configured[i] = rnd;
			list.set(i, MyData(i,i), rnd);
			probSum += rnd;
		}

		// draw
		for (unsigned int i = 0; i < numDraw; ++i) {
			MyData& d = list.draw();
			drawn[d.x]++;
		}

		// compare
		for (unsigned int i = 0; i < cnt; ++i) {
			double a = (configured[i] / probSum);
			double b = (drawn[i] / numDraw);
			ASSERT_NEAR(a, b, a*0.50);			// allow 50% difference between cfg and drawn
		}

	}
TEST (LowPassFilterTest, DoesBothAtOnce) {
    // make two sine waves, one second long
    KeyFinder::AudioData a;
    a.setChannels(1);
    a.setFrameRate(frameRate);
    a.addToSampleCount(frameRate);
    for (unsigned int i = 0; i < frameRate; i++) {
        float sample = 0.0;
        sample += sine_wave(i, highFrequency, frameRate, magnitude); // high freq
        sample += sine_wave(i, lowFrequency, frameRate, magnitude); // low freq
        a.setSample(i, sample);
    }

    KeyFinder::LowPassFilter* lpf = new KeyFinder::LowPassFilter(filterOrder, frameRate, cornerFrequency, filterFFT);
    KeyFinder::Workspace w;
    lpf->filter(a, w);
    delete lpf;

    // test for lower wave only
    for (unsigned int i = 0; i < frameRate; i++) {
        float expected = sine_wave(i, lowFrequency, frameRate, magnitude);
        ASSERT_NEAR(expected, a.getSample(i), tolerance);
    }
}
TEST(WingComponentSegment4, tiglWingComponentSegmentPointGetSegmentEtaXsi_BUG2)
{
    TiglCPACSConfigurationHandle tiglHandle = -1;
    TixiDocumentHandle tixiHandle = -1;
    
    const char* filename = "TestData/simple_rectangle_compseg.xml";
    
    ReturnCode tixiRet = tixiOpenDocument(filename, &tixiHandle);
    ASSERT_TRUE (tixiRet == SUCCESS);
    TiglReturnCode tiglRet = tiglOpenCPACSConfiguration(tixiHandle, "D150modelID", &tiglHandle);
    ASSERT_TRUE(tiglRet == TIGL_SUCCESS);
    
    double sEta = 0., sXsi = 0.;
    char *wingUID = NULL, *segmentUID = NULL;
    double errorDistance = 0;
    tiglRet = tiglWingComponentSegmentPointGetSegmentEtaXsi(tiglHandle, "D150_wing_CS", 0.5, 0.10142, &wingUID, &segmentUID, &sEta, &sXsi, &errorDistance);
    ASSERT_EQ(TIGL_SUCCESS, tiglRet);
    ASSERT_LT(errorDistance, 1e-2);
    ASSERT_STREQ("D150_wing_1Segment3ID", segmentUID);
    ASSERT_NEAR(0.5, sEta, 0.0001);

    tiglCloseCPACSConfiguration(tiglHandle);
    tixiCloseDocument(tixiHandle);
}
TEST (AudioDataTest, DownsamplerResamplesSineWave) {
  unsigned int frameRate = 10000;
  unsigned int frames = frameRate * 4;
  float freq = 20;
  float magnitude = 32768.0;
  unsigned int factor = 5;

  KeyFinder::AudioData a;
  a.setChannels(1);
  a.setFrameRate(frameRate);
  a.addToSampleCount(frames);
  for (unsigned int i = 0; i < frames; i++)
    a.setSample(i, sine_wave(i, freq, frameRate, magnitude));

  a.downsample(factor);

  unsigned int newFrameRate = frameRate / factor;
  unsigned int newFrames = frames / factor;

  ASSERT_EQ(newFrameRate, a.getFrameRate());
  ASSERT_EQ(newFrames, a.getSampleCount());
  for (unsigned int i = 0; i < newFrames; i++)
    ASSERT_NEAR(sine_wave(i, freq, newFrameRate, magnitude), a.getSample(i), magnitude * 0.05);
}
TEST(CalcRPSTest, ReverseLeft) {
	double twist_msg[3] = {17, 0, -4.273};

	/* test linear_RPS calculations */

	double actual_left_linear_RPS = CalcLinearRPS( twist_msg[0] );
	double actual_right_linear_RPS = CalcLinearRPS( twist_msg[0] );

//	double expected_left_linear_RPS = twist_msg[0] / CIRCUMFERENCE;
	double expected_left_linear_RPS = (17/CIRCUMFERENCE);
	double expected_right_linear_RPS = (twist_msg[0]/CIRCUMFERENCE);

	ASSERT_NEAR(actual_left_linear_RPS, expected_left_linear_RPS,	0.01);
	ASSERT_NEAR(actual_right_linear_RPS, expected_right_linear_RPS, 0.01);

	/* test angular_rps calculations */

	double actual_left_angular_RPS = CalcAngularRPS( twist_msg[2], 'L' );
	double actual_right_angular_RPS = CalcAngularRPS( twist_msg[2], 'R' );

	double expected_left_angular_RPS = twist_msg[2]/(CalcWheelDirection(twist_msg[2], 'L')*DISTANCE_TO_CENTER*2*PI*WHEEL_RADIUS);

	double expected_right_angular_RPS = twist_msg[2] /
				(	CalcWheelDirection( twist_msg[2], 'R' )*
					DISTANCE_TO_CENTER*2*PI*WHEEL_RADIUS );

	ASSERT_NEAR(actual_left_angular_RPS, expected_left_angular_RPS,
							0.01);
	ASSERT_NEAR(actual_right_angular_RPS, expected_right_angular_RPS,
							0.01);

	/* test actual total rps */

	double expected_left_RPS = actual_left_linear_RPS + actual_left_angular_RPS;
	double expected_right_RPS = actual_right_linear_RPS + actual_right_angular_RPS;
	
	double actual_left_RPS = CalcRPS( twist_msg, 'L' );
	double actual_right_RPS = CalcRPS( twist_msg, 'R' );

	ASSERT_NEAR(actual_left_RPS, expected_left_RPS, 0.01);
	ASSERT_NEAR(actual_right_RPS, expected_right_RPS, 0.01);
}
TEST_F(WingComponentSegmentSimple, getPointInternal_accuracy)
{
    int compseg = 1;
    // now we have do use the internal interface as we currently have no public api for this
    tigl::CCPACSConfigurationManager & manager = tigl::CCPACSConfigurationManager::GetInstance();
    tigl::CCPACSConfiguration & config = manager.GetConfiguration(tiglHandle);
    tigl::CCPACSWing& wing = config.GetWing(1);
    tigl::CCPACSWingComponentSegment& segment = (tigl::CCPACSWingComponentSegment&) wing.GetComponentSegment(compseg);

    gp_Pnt point = segment.GetPoint(0.25, 0.5);
    ASSERT_NEAR(point.X(), 0.5, 1e-7);
    ASSERT_NEAR(point.Y(), 0.5, 1e-7);

    point = segment.GetPoint(0.5, 0.5);
    ASSERT_NEAR(point.X(), 0.5, 1e-7);
    ASSERT_NEAR(point.Y(), 1.0, 1e-7);

    point = segment.GetPoint(0.75, 0.5);
    ASSERT_NEAR(point.X(), 0.625, 1e-7);
    ASSERT_NEAR(point.Y(), 1.5, 1e-7);
}
Exemple #12
0
    void checkInDense(std::vector<int>& amdRowPtr, std::vector<int>& amdColIndices, std::vector<T>& amdVals)
    {
        uBLAS::mapped_matrix<T> sparseDense(csrMatrixC.num_rows, csrMatrixC.num_cols, 0);
        uBLAS::mapped_matrix<T> boostDense(csrMatrixC.num_rows, csrMatrixC.num_cols, 0);

        // boost sparse_prod cancels out zeros and hence reports more accurately non-zeros
        // In clSPARSE, spGeMM produces more non-zeros, and considers some zeros as nonzeros.
        // Therefore converting to dense and verifying the output in  dense format
        // Convert CSR to Dense

        for (int i = 0; i < amdRowPtr.size() - 1; i++)
        {
            // i corresponds to row index
            for (int j = amdRowPtr[i]; j < amdRowPtr[i + 1]; j++)
                sparseDense(i, amdColIndices[j]) = amdVals[j];
        }

        for (int i = 0; i < this->C.index1_data().size() - 1; i++)
        {
            for (int j = this->C.index1_data()[i]; j < this->C.index1_data()[i + 1]; j++)
                boostDense(i, this->C.index2_data()[j]) = this->C.value_data()[j];
        }

        bool brelativeErrorFlag = false;
        bool babsErrorFlag = false;
        
        for (int i = 0; i < csrMatrixC.num_rows; i++)
        {
            for (int j = 0; j < csrMatrixC.num_cols; j++)
            {
                //ASSERT_EQ(boostDense(i, j), sparseDense(i, j));
#ifdef _DEBUG_SpMxSpM_
                ASSERT_NEAR(boostDense(i, j), sparseDense(i, j), SPGEMM_PREC_ERROR);
#else
                if (fabs(boostDense(i, j) - sparseDense(i, j)) > SPGEMM_PREC_ERROR)
                {
                    babsErrorFlag = true;
                    SCOPED_TRACE("Absolute Error Fail");
                    break;
                }
#endif
            }
        }
        // Relative Error
        for (int i = 0; i < csrMatrixC.num_rows; i++)
        {
            for (int j = 0; j < csrMatrixC.num_cols; j++)
            {
                float diff  = fabs(boostDense(i, j) - sparseDense(i, j));
                float ratio = diff / boostDense(i, j);
#ifdef _DEBUG_SpMxSpM_
                // ratio is less than or almost equal to SPGEMM_REL_ERROR
                EXPECT_PRED_FORMAT2(::testing::FloatLE, ratio, SPGEMM_REL_ERROR);
#else
                if (diff / boostDense(i, j) > SPGEMM_REL_ERROR)
                {
                    brelativeErrorFlag = true;
                    SCOPED_TRACE("Relative Error Fail");
                    break;
                }
#endif
            }
        }//
#ifndef _DEBUG_SpMxSpM_
        if (brelativeErrorFlag)
        {
            ASSERT_FALSE(babsErrorFlag);
        }

        if (babsErrorFlag)
        {
            ASSERT_FALSE(brelativeErrorFlag);
        }
#endif
    }// end
TEST(Solution, LinearElastic2D)
{
    try {
        MeshLib::IMesh *msh = MeshGenerator::generateStructuredRegularQuadMesh(2.0, 2, .0, .0, .0);
        GeoLib::Rectangle* _rec = new GeoLib::Rectangle(Point(0.0, 0.0, 0.0),  Point(2.0, 2.0, 0.0));
        Geo::PorousMedia pm;
        pm.hydraulic_conductivity = new NumLib::TXFunctionConstant(1.e-11);
        pm.porosity = new NumLib::TXFunctionConstant(0.2);
        Geo::Solid solid;
        solid.density = 3e+3;
        solid.poisson_ratio = 0.2;
        solid.Youngs_modulus = 10e+9;
        pm.solidphase = &solid;
        DiscreteSystem dis(msh);
        FemLib::LagrangeFeObjectContainer feObjects(msh);
        Geo::FemLinearElasticProblem* pDe = defineLinearElasticProblem(dis, *_rec, pm, &feObjects);
        TimeStepFunctionConstant tim(.0, 10.0, 10.0);
        pDe->setTimeSteppingFunction(tim);
        // options
        BaseLib::Options options;
        BaseLib::Options* op_lis = options.addSubGroup("LinearSolver");
        op_lis->addOption("solver_type", "CG");
        op_lis->addOption("precon_type", "NONE");
        op_lis->addOptionAsNum("error_tolerance", 1e-10);
        op_lis->addOptionAsNum("max_iteration_step", 500);
        BaseLib::Options* op_nl = options.addSubGroup("Nonlinear");
        op_nl->addOption("solver_type", "Linear");
        op_nl->addOptionAsNum("error_tolerance", 1e-6);
        op_nl->addOptionAsNum("max_iteration_step", 500);

        MyFunctionDisplacement f_u;
        f_u.define(&dis, pDe, &pm, options);
        f_u.setOutputParameterName(0, "u_x");
        f_u.setOutputParameterName(1, "u_y");
        f_u.setOutputParameterName(2, "Strain");
        f_u.setOutputParameterName(3, "Stress");
//        MyFunctionStressStrain f_sigma;
//        f_sigma.setOutputParameterName(0, "strain_xx");

        SerialStaggeredMethod method(1e-5, 100);
        AsyncPartitionedSystem apart1;
        apart1.setAlgorithm(method);
        apart1.resizeOutputParameter(4);
        apart1.setOutputParameterName(0, "u_x");
        apart1.setOutputParameterName(1, "u_y");
        apart1.setOutputParameterName(2, "Strain");
        apart1.setOutputParameterName(3, "Stress");
        apart1.addProblem(f_u);
        apart1.connectParameters();

        TimeSteppingController timestepping;
        timestepping.setTransientSystem(apart1);

        //const double epsilon = 1.e-3;
        timestepping.setBeginning(.0);
        timestepping.solve(tim.getEnd());

//        const MyNodalFunctionScalar* r_f_ux = apart1.getOutput<MyNodalFunctionScalar>(apart1.getOutputParameterID("u_x"));
//        const MyNodalFunctionScalar* r_f_uy = apart1.getOutput<MyNodalFunctionScalar>(apart1.getOutputParameterID("u_y"));
        const MyIntegrationPointFunctionVector* r_f_strain = apart1.getOutput<MyIntegrationPointFunctionVector>(apart1.getOutputParameterID("Strain"));
        const MyIntegrationPointFunctionVector* r_f_stress = apart1.getOutput<MyIntegrationPointFunctionVector>(apart1.getOutputParameterID("Stress"));
//        const IDiscreteVector<double>* vec_r_f_ux = r_f_ux->getDiscreteData();
//        const IDiscreteVector<double>* vec_r_f_uy = r_f_uy->getDiscreteData();
        const MyIntegrationPointFunctionVector::MyDiscreteVector* vec_strain = r_f_strain->getDiscreteData();
        const MyIntegrationPointFunctionVector::MyDiscreteVector* vec_stress = r_f_stress->getDiscreteData();

//        r_f_ux->printout();
//        r_f_uy->printout();
//        r_f_strain->printout();
//        r_f_stress->printout();

        const MathLib::LocalVector &strain1 = (*vec_strain)[0][0];
        const MathLib::LocalVector &stress1 = (*vec_stress)[0][0];
        double E = solid.Youngs_modulus;
        double nu = solid.poisson_ratio;
        double sx = .0; //E/((1.+nu)*(1-2*nu))*((1-nu)*ex+nu*ey);
        double sy = -1e+6; //E/((1.-nu)*(1-2*nu))*(nu*ex+(1-nu)*ey);
        double sxy = .0; //0.5*E/(1.+nu)*exy;
        double ex = (1+nu)/E*((1-nu)*sx-nu*sy);
        double ey = (1+nu)/E*((1-nu)*sy-nu*sx);
        double exy = 2*(1+nu)/E*sxy;
        double sz = nu*E/((1.+nu)*(1-2*nu))*(ex+ey);
        double epsilon = 1e-6;
        ASSERT_NEAR(ex, strain1(0), epsilon);
        ASSERT_NEAR(ey, strain1(1), epsilon);
        ASSERT_NEAR(.0, strain1(2), epsilon);
        ASSERT_NEAR(exy, strain1(3), epsilon);
        epsilon = 1;
        ASSERT_NEAR(sx, stress1(0), epsilon);
        ASSERT_NEAR(sy, stress1(1), epsilon);
        ASSERT_NEAR(sz, stress1(2), epsilon);
        ASSERT_NEAR(sxy, stress1(3), epsilon);

    } catch (const char* e) {
        std::cout << "***Exception caught! " << e << std::endl;
    }

}
TEST_F(WingComponentSegmentSimple, InterpolateOnLine)
{
    tigl::CCPACSConfigurationManager & manager = tigl::CCPACSConfigurationManager::GetInstance();
    tigl::CCPACSConfiguration & config = manager.GetConfiguration(tiglHandle);
    tigl::CCPACSWing& wing = config.GetWing(1);
    tigl::CCPACSWingComponentSegment& compSegment = (tigl::CCPACSWingComponentSegment&) wing.GetComponentSegment(1);

    double xsi = 0;
    double error = 0.;

    // check trivial borders for validity
    compSegment.InterpolateOnLine(0.0, 0.0, 1.0, 1.0, 0.0, xsi, error);
    ASSERT_NEAR(0.0, xsi, 1e-6);
    ASSERT_NEAR(0.0, error, 1e-6);

    compSegment.InterpolateOnLine(0.0, 0.0, 1.0, 1.0, 1.0, xsi, error);
    ASSERT_NEAR(1.0, xsi, 1e-6);
    ASSERT_NEAR(0.0, error, 1e-6);

    // check cases in first segment
    compSegment.InterpolateOnLine(0.0, 0.0, 1.0, 1.0, 0.25, xsi, error);
    ASSERT_NEAR(0.25, xsi, 1e-6);
    ASSERT_NEAR(0.0, error, 1e-6);

    compSegment.InterpolateOnLine(0.0, 0.0, 1.0, 1.0, 0.4, xsi, error);
    ASSERT_NEAR(0.4, xsi, 1e-6);
    ASSERT_NEAR(0.0, error, 1e-6);

    // now check the not so trivial cases in second segment
    compSegment.InterpolateOnLine(0.0, 0.0, 1.0, 1.0, 0.5, xsi, error);
    ASSERT_NEAR(0.5, xsi, 1e-6);
    ASSERT_NEAR(0.0, error, 1e-6);

    compSegment.InterpolateOnLine(0.0, 0.0, 1.0, 1.0, 0.75, xsi, error);
    ASSERT_NEAR(0.5/0.75, xsi, 1e-6);
    ASSERT_NEAR(0.0, error, 1e-6);

    compSegment.InterpolateOnLine(0.0, 0.0, 1.0, 1.0, 0.6, xsi, error);
    ASSERT_NEAR(0.5/0.9, xsi, 1e-6);
    ASSERT_NEAR(0.0, error, 1e-6);

    compSegment.InterpolateOnLine(0.0, 0.0, 1.0, 1.0, 0.9, xsi, error);
    ASSERT_NEAR(0.5/0.6, xsi, 1e-6);
    ASSERT_NEAR(0.0, error, 1e-6);
}
Exemple #15
0
TEST(macro_ASSERT_NEAR, floats_test_out_to_equal_within_given_epsilon)
{
  ASSERT_NEAR(3.1415, M_PI, 0.0001);
}
Exemple #16
0
TEST_F(MeshLibProperties, AddDoublePointerProperties)
{
    ASSERT_TRUE(mesh != nullptr);
    std::string const& prop_name("GroupProperty");
    // check if a property with the name is already assigned to the mesh
    ASSERT_FALSE(mesh->getProperties().hasPropertyVector(prop_name));
    // data needed for the property
    const std::size_t n_prop_val_groups(10);
    const std::size_t n_items(mesh_size*mesh_size*mesh_size);
    std::vector<std::size_t> prop_item2group_mapping(n_items);
    // create simple mat_group to index mapping
    for (std::size_t j(0); j<n_prop_val_groups; j++) {
        std::size_t const lower(
            static_cast<std::size_t>(
                (static_cast<double>(j)/n_prop_val_groups)*n_items
            )
        );
        std::size_t const upper(
            static_cast<std::size_t>(
                (static_cast<double>(j+1)/n_prop_val_groups)*n_items
            )
        );
        for (std::size_t k(lower); k<upper; k++) {
            prop_item2group_mapping[k] = j;
        }
    }
    // obtain PropertyVector data structure
    boost::optional<MeshLib::PropertyVector<double*> &> group_properties(
        mesh->getProperties().createNewPropertyVector<double*>(
            prop_name, n_prop_val_groups, prop_item2group_mapping,
            MeshLib::MeshItemType::Cell
        )
    );
    ASSERT_EQ(prop_item2group_mapping.size(), (*group_properties).size());

    // initialize the property values
    for (std::size_t i(0); i<n_prop_val_groups; i++) {
        (*group_properties).initPropertyValue(i, static_cast<double>(i+1));
    }
    // check mapping to values
    for (std::size_t i(0); i<n_prop_val_groups; i++) {
        std::size_t const lower(
            static_cast<std::size_t>(
                (static_cast<double>(i)/n_prop_val_groups)*n_items
            )
        );
        std::size_t const upper(
            static_cast<std::size_t>(
                (static_cast<double>(i+1)/n_prop_val_groups)*n_items
            )
        );
        for (std::size_t k(lower); k<upper; k++) {
            ASSERT_NEAR(static_cast<double>(i+1), *(*group_properties)[k],
                std::numeric_limits<double>::epsilon());
        }
    }

    // the mesh should have the property assigned to cells
    ASSERT_TRUE(mesh->getProperties().hasPropertyVector(prop_name));
    // fetch the properties from the container
    boost::optional<MeshLib::PropertyVector<double*> const&>
        group_properties_cpy(mesh->getProperties().getPropertyVector<double*>(
            prop_name));
    ASSERT_FALSE(!group_properties_cpy);

    for (std::size_t k(0); k<n_items; k++) {
        ASSERT_EQ((*group_properties)[k], (*group_properties_cpy)[k]);
    }

    mesh->getProperties().removePropertyVector(prop_name);
    boost::optional<MeshLib::PropertyVector<double*> const&>
        removed_group_properties(mesh->getProperties().getPropertyVector<double*>(
            prop_name));

    ASSERT_TRUE(!removed_group_properties);
}
Exemple #17
0
TEST(Math, VectorLength) {
	Vec3 v1(1,2,3);
	ASSERT_NEAR(3.7414, Math::length(v1), 0.001);
	Vec3 v2(0,0,-1);
	ASSERT_NEAR(1.0, Math::length(v2), 0.001);
}
TEST_F(NetworkControllerTest, trainNet){
	NetworkController nc;
	nc.loadNetwork(TEST_DATA_PATH("Student.na"));
	nc.loadNetwork(TEST_DATA_PATH("Student.sif"));
	nc.loadObservations(TEST_DATA_PATH("StudentData.txt"),TEST_DATA_PATH("controlStudent.json"));
	nc.trainNetwork();
	Network n = nc.getNetwork();
	Node grade = n.getNode("Grade");
	ASSERT_NEAR(0.3f,grade.getProbability(0,0),0.001);
	ASSERT_NEAR(0.05f,grade.getProbability(0,2),0.001);
	ASSERT_NEAR(0.9f,grade.getProbability(0,1),0.001);
	ASSERT_NEAR(0.5f,grade.getProbability(0,3),0.001);
	ASSERT_NEAR(0.4f,grade.getProbability(1,0),0.001);
	ASSERT_NEAR(0.25f,grade.getProbability(1,2),0.001);
	ASSERT_NEAR(0.08f,grade.getProbability(1,1),0.001);
	ASSERT_NEAR(0.3f,grade.getProbability(1,3),0.001);
	ASSERT_NEAR(0.3f,grade.getProbability(2,0),0.001);
	ASSERT_NEAR(0.7f,grade.getProbability(2,2),0.001);
	ASSERT_NEAR(0.02f,grade.getProbability(2,1),0.001);
	ASSERT_NEAR(0.2f,grade.getProbability(2,3),0.001);
	Node letter = n.getNode("Letter");
	ASSERT_NEAR(0.1f,letter.getProbability(0,0),0.001);
	ASSERT_NEAR(0.4f,letter.getProbability(0,1),0.001);
	ASSERT_NEAR(0.99f,letter.getProbability(0,2),0.001);
	ASSERT_NEAR(0.9f,letter.getProbability(1,0),0.001);
	ASSERT_NEAR(0.6f,letter.getProbability(1,1),0.001);
	ASSERT_NEAR(0.01f,letter.getProbability(1,2),0.001);
	Node intelligence = n.getNode("Intelligence");
	ASSERT_NEAR(0.7, intelligence.getProbability(0,0),0.001);
	ASSERT_NEAR(0.3, intelligence.getProbability(1,0),0.001);
	Node difficulty = n.getNode("Difficulty");
	ASSERT_NEAR(0.6, difficulty.getProbability(0,0),0.001);
	ASSERT_NEAR(0.4, difficulty.getProbability(1,0),0.001);	
	Node sat = n.getNode("SAT");
	ASSERT_NEAR(0.95f,sat.getProbability(0,0),0.001);
	ASSERT_NEAR(0.05f,sat.getProbability(1,0),0.001);
	ASSERT_NEAR(0.2f,sat.getProbability(0,1),0.001);
	ASSERT_NEAR(0.8f,sat.getProbability(1,1),0.001);
}
Exemple #19
0
TEST_F(MeshLibProperties, AddArrayPointerProperties)
{
    ASSERT_TRUE(mesh != nullptr);
    std::string const& prop_name("GroupPropertyWithArray");
    const std::size_t n_prop_val_groups(10);
    const std::size_t n_items(mesh_size*mesh_size*mesh_size);
    std::vector<std::size_t> prop_item2group_mapping(n_items);
    // create simple mat_group to index mapping
    for (std::size_t j(0); j<n_prop_val_groups; j++) {
        std::size_t const lower(
            static_cast<std::size_t>(
                (static_cast<double>(j)/n_prop_val_groups)*n_items
            )
        );
        std::size_t const upper(
            static_cast<std::size_t>(
                (static_cast<double>(j+1)/n_prop_val_groups)*n_items
            )
        );
        for (std::size_t k(lower); k<upper; k++) {
            prop_item2group_mapping[k] = j;
        }
    }
    boost::optional<MeshLib::PropertyVector<std::array<double,3>*> &>
        group_prop_vec(
            mesh->getProperties().createNewPropertyVector<std::array<double,3>*>(
                prop_name, n_prop_val_groups, prop_item2group_mapping,
                MeshLib::MeshItemType::Cell
            )
        );
    ASSERT_EQ(prop_item2group_mapping.size(), group_prop_vec->size());

    // initialize the property values
    for (std::size_t i(0); i<n_prop_val_groups; i++) {
        (*group_prop_vec).initPropertyValue(i,
            std::array<double,3>({{static_cast<double>(i),
                static_cast<double>(i+1),
                static_cast<double>(i+2)}}
            )
        );
    }
    // check the mapping to values
    for (std::size_t i(0); i<n_prop_val_groups; i++) {
        std::size_t const lower(
            static_cast<std::size_t>(
                (static_cast<double>(i)/n_prop_val_groups)*n_items
            )
        );
        std::size_t const upper(
            static_cast<std::size_t>(
                (static_cast<double>(i+1)/n_prop_val_groups)*n_items
            )
        );
        for (std::size_t k(lower); k<upper; k++) {
            ASSERT_NEAR(static_cast<double>(i), (*(*group_prop_vec)[k])[0],
                std::numeric_limits<double>::epsilon());
            ASSERT_NEAR(static_cast<double>(i+1), (*(*group_prop_vec)[k])[1],
                std::numeric_limits<double>::epsilon());
            ASSERT_NEAR(static_cast<double>(i+2), (*(*group_prop_vec)[k])[2],
                std::numeric_limits<double>::epsilon());
        }
    }

    boost::optional<MeshLib::PropertyVector<std::array<double,3>*> const&>
        group_properties_cpy(
            mesh->getProperties().getPropertyVector<std::array<double,3>*>(prop_name)
        );
    ASSERT_FALSE(!group_properties_cpy);

    for (std::size_t k(0); k<n_items; k++) {
        ASSERT_EQ((*((*group_prop_vec)[k]))[0],
            (*((*group_properties_cpy)[k]))[0]);
        ASSERT_EQ((*((*group_prop_vec)[k]))[1],
            (*((*group_properties_cpy)[k]))[1]);
        ASSERT_EQ((*((*group_prop_vec)[k]))[2],
            (*((*group_properties_cpy)[k]))[2]);
    }

    mesh->getProperties().removePropertyVector(prop_name);
    boost::optional<MeshLib::PropertyVector<std::array<double, 3>*> const&>
        removed_group_properties(
            mesh->getProperties().getPropertyVector<std::array<double,3>*>(prop_name)
        );

    ASSERT_TRUE(!removed_group_properties);
}
TEST(RMDCuTests, seedMatrixInit)
{
  const boost::filesystem::path dataset_path("../test_data");
  const boost::filesystem::path sequence_file_path("../test_data/first_200_frames_traj_over_table_input_sequence.txt");

  rmd::PinholeCamera cam(481.2f, -480.0f, 319.5f, 239.5f);

  rmd::test::Dataset dataset(dataset_path.string(), sequence_file_path.string(), cam);
  if (!dataset.readDataSequence())
    FAIL() << "could not read dataset";

  const size_t ref_ind = 1;
  const size_t curr_ind = 20;

  const auto ref_entry = dataset(ref_ind);
  cv::Mat ref_img;
  dataset.readImage(ref_img, ref_entry);
  cv::Mat ref_img_flt;
  ref_img.convertTo(ref_img_flt, CV_32F, 1.0f/255.0f);

  cv::Mat ref_depthmap;
  dataset.readDepthmap(ref_depthmap, ref_entry, ref_img.cols, ref_img.rows);

  rmd::SE3<float> T_world_ref;
  dataset.readCameraPose(T_world_ref, ref_entry);

  const auto curr_entry = dataset(curr_ind);
  cv::Mat curr_img;
  dataset.readImage(curr_img, curr_entry);
  cv::Mat curr_img_flt;
  curr_img.convertTo(curr_img_flt, CV_32F, 1.0f/255.0f);

  rmd::SE3<float> T_world_curr;
  dataset.readCameraPose(T_world_curr, curr_entry);

  const float min_scene_depth = 0.4f;
  const float max_scene_depth = 1.8f;

  rmd::SeedMatrix seeds(ref_img.cols, ref_img.rows, cam);

  StopWatchInterface * timer = NULL;
  sdkCreateTimer(&timer);
  sdkResetTimer(&timer);
  sdkStartTimer(&timer);

  seeds.setReferenceImage(
        reinterpret_cast<float*>(ref_img_flt.data),
        T_world_ref.inv(),
        min_scene_depth,
        max_scene_depth);

  sdkStopTimer(&timer);
  double t = sdkGetAverageTimerValue(&timer) / 1000.0;
  printf("setReference image CUDA execution time: %f seconds.\n", t);

  cv::Mat initial_depthmap(ref_img.rows, ref_img.cols, CV_32FC1);
  seeds.downloadDepthmap(reinterpret_cast<float*>(initial_depthmap.data));

  cv::Mat initial_sigma_sq(ref_img.rows, ref_img.cols, CV_32FC1);
  seeds.downloadSigmaSq(reinterpret_cast<float*>(initial_sigma_sq.data));

  cv::Mat initial_a(ref_img.rows, ref_img.cols, CV_32FC1);
  seeds.downloadA(reinterpret_cast<float*>(initial_a.data));

  cv::Mat initial_b(ref_img.rows, ref_img.cols, CV_32FC1);
  seeds.downloadB(reinterpret_cast<float*>(initial_b.data));

  const float avg_scene_depth = (min_scene_depth+max_scene_depth)/2.0f;
  const float max_scene_sigma_sq = (max_scene_depth - min_scene_depth) * (max_scene_depth - min_scene_depth) / 36.0f;
  for(size_t r=0; r<ref_img.rows; ++r)
  {
    for(size_t c=0; c<ref_img.cols; ++c)
    {
      ASSERT_FLOAT_EQ(avg_scene_depth, initial_depthmap.at<float>(r, c));
      ASSERT_FLOAT_EQ(max_scene_sigma_sq, initial_sigma_sq.at<float>(r, c));
      ASSERT_FLOAT_EQ(10.0f, initial_a.at<float>(r, c));
      ASSERT_FLOAT_EQ(10.0f, initial_b.at<float>(r, c));
    }
  }

  // Test initialization of NCC template statistics

  // CUDA computation
  cv::Mat cu_sum_templ(ref_img.rows, ref_img.cols, CV_32FC1);
  seeds.downloadSumTempl(reinterpret_cast<float*>(cu_sum_templ.data));
  cv::Mat cu_const_templ_denom(ref_img.rows, ref_img.cols, CV_32FC1);
  seeds.downloadConstTemplDenom(reinterpret_cast<float*>(cu_const_templ_denom.data));

  // Host computation
  cv::Mat ocv_sum_templ(ref_img.rows, ref_img.cols, CV_32FC1);
  cv::Mat ocv_const_templ_denom(ref_img.rows, ref_img.cols, CV_32FC1);

  const int side = seeds.getPatchSide();
  for(size_t y=side; y<ref_img.rows-side/2; ++y)
  {
    for(size_t x=side; x<ref_img.cols-side/2; ++x)
    {
      double sum_templ    = 0.0f;
      double sum_templ_sq = 0.0f;
      for(int patch_y=0; patch_y<side; ++patch_y)
      {
        for(int patch_x=0; patch_x<side; ++patch_x)
        {
          const double templ = (double) ref_img_flt.at<float>( y-side/2+patch_y, x-side/2+patch_x );
          sum_templ += templ;
          sum_templ_sq += templ*templ;
        }
      }
      ocv_sum_templ.at<float>(y, x) = (float) sum_templ;
      ocv_const_templ_denom.at<float>(y, x) = (float) ( ((double)(side*side))*sum_templ_sq - sum_templ*sum_templ );
    }
  }
  for(size_t r=side; r<ref_img.rows-side/2; ++r)
  {
    for(size_t c=side; c<ref_img.cols-side/2; ++c)
    {
      ASSERT_NEAR(ocv_sum_templ.at<float>(r, c), cu_sum_templ.at<float>(r, c), 0.00001f);
      ASSERT_NEAR(ocv_const_templ_denom.at<float>(r, c), cu_const_templ_denom.at<float>(r, c), 0.001f);
    }
  }

}
inline void test_array_equals_constant(float * array, int n_elements, float c){
	const float EPS = 0.01;
	for(int i=0;i<n_elements;i++){
		ASSERT_NEAR(array[i], c, EPS);
	}
}
TEST(rosToEigen, pose) {
	Eigen::Isometry3d pose1 = toEigen(makePose(makePoint(0, 1.5, 2), makeQuaternion(1, 0, 0, 0)));
	Eigen::Isometry3d pose2 = toEigen(makePose(makePoint(-1.5, -2.6, -3.7), makeQuaternion(0, 0, 0, 1)));

	Eigen::Vector3d const & p1 = pose1.translation();
	Eigen::Vector3d const & p2 = pose2.translation();
	Eigen::Quaterniond const & q1 = Eigen::Quaterniond{pose1.rotation()};
	Eigen::Quaterniond const & q2 = Eigen::Quaterniond{pose2.rotation()};

	ASSERT_NEAR(0.0, p1.x(), 1e-5);
	ASSERT_NEAR(1.5, p1.y(), 1e-5);
	ASSERT_NEAR(2.0, p1.z(), 1e-5);
	ASSERT_NEAR(-1.5, p2.x(), 1e-5);
	ASSERT_NEAR(-2.6, p2.y(), 1e-5);
	ASSERT_NEAR(-3.7, p2.z(), 1e-5);

	ASSERT_NEAR(1, q1.x(), 1e-5);
	ASSERT_NEAR(0, q1.y(), 1e-5);
	ASSERT_NEAR(0, q1.z(), 1e-5);
	ASSERT_NEAR(0, q1.w(), 1e-5);
	ASSERT_NEAR(0, q2.x(), 1e-5);
	ASSERT_NEAR(0, q2.y(), 1e-5);
	ASSERT_NEAR(0, q2.z(), 1e-5);
	ASSERT_NEAR(1, q2.w(), 1e-5);
}
TEST(MathLib, DenseGaussAlgorithmDenseVector)
{
	std::size_t n_rows(50);
	std::size_t n_cols(n_rows);

	MathLib::DenseMatrix<double,std::size_t> mat(n_rows, n_cols);

	// *** fill matrix with arbitrary values
	// ** initialize random seed
	srand ( static_cast<unsigned>(time(nullptr)) );
	// ** loop over rows and columns
	for (std::size_t i(0); i<n_rows; i++) {
		for (std::size_t j(0); j<n_cols; j++) {
			mat(i,j) = rand()/static_cast<double>(RAND_MAX);
		}
	}

	// *** create solution vector, set all entries to 0.0
	MathLib::DenseVector<double> x(n_cols);
	std::fill(std::begin(x), std::end(x), 0.0);
	MathLib::DenseVector<double> b0(mat * x);

	// *** create other right hand sides,
	// set all entries of the solution vector to 1.0
	std::fill(std::begin(x), std::end(x), 1.0);
	MathLib::DenseVector<double> b1(mat * x);

	std::generate(std::begin(x), std::end(x), std::rand);
	MathLib::DenseVector<double> b2(mat * x);

	// right hand side and solution vector with random entries
	MathLib::DenseVector<double> b3(mat * x);
	MathLib::DenseVector<double> b3_copy(mat * x);
	MathLib::DenseVector<double> x3 (n_cols);
	std::generate(std::begin(x3),std::end(x3), std::rand);

	MathLib::GaussAlgorithm<MathLib::DenseMatrix<double, std::size_t>, MathLib::DenseVector<double>> gauss(mat);

	// solve with b0 as right hand side
	gauss.solve(b0, true);
	for (std::size_t i(0); i<n_rows; i++) {
		ASSERT_NEAR(b0[i], 0.0, 1e5 * std::numeric_limits<float>::epsilon());
	}

	// solve with b1 as right hand side
	gauss.solve(b1, false);
	for (std::size_t i(0); i<n_rows; i++) {
		ASSERT_NEAR(b1[i], 1.0, std::numeric_limits<float>::epsilon());
	}

	// solve with b2 as right hand side
	gauss.solve(b2, false);
	for (std::size_t i(0); i<n_rows; i++) {
		ASSERT_NEAR(fabs(b2[i]-x[i])/fabs(x[i]), 0.0, std::numeric_limits<float>::epsilon());
	}

	gauss.solve(b3, x3, false);
	for (std::size_t i(0); i<n_rows; i++) {
		ASSERT_NEAR(fabs(x3[i]-x[i])/fabs(x[i]), 0.0, std::numeric_limits<float>::epsilon());
	}
	// assure entries of vector b3 are not changed
	for (std::size_t i(0); i<n_rows; i++) {
		ASSERT_NEAR(fabs(b3[i]-b3_copy[i])/fabs(b3[i]), 0.0, std::numeric_limits<float>::epsilon());
	}
}
TEST(MathLib, DenseGaussAlgorithm)
{
	std::size_t n_rows(100);
	std::size_t n_cols(n_rows);

	MathLib::DenseMatrix<double,std::size_t> mat(n_rows, n_cols);

	// *** fill matrix with arbitrary values
	// ** initialize random seed
	srand ( static_cast<unsigned>(time(nullptr)) );
	// ** loop over rows and columns
	for (std::size_t i(0); i<n_rows; i++) {
		for (std::size_t j(0); j<n_cols; j++) {
			mat(i,j) = rand()/static_cast<double>(RAND_MAX);
		}
	}

	// *** create solution vector, set all entries to 0.0
	double *x(new double[n_cols]);
	std::fill(x,x+n_cols, 0.0);
	double *b0(mat * x);

	// *** create other right hand sides,
	// set all entries of the solution vector to 1.0
	std::fill(x,x+n_cols, 1.0);
	double *b1(mat * x);

	std::generate(x,x+n_cols, std::rand);
	double *b2(mat * x);

	// right hand side and solution vector with random entries
	double *b3(mat * x);
	double *b3_copy(mat * x);
	double *x3 (new double[n_cols]);
	std::generate(x3,x3+n_cols, std::rand);

	MathLib::GaussAlgorithm<MathLib::DenseMatrix<double, std::size_t>, double*> gauss(mat);

	// solve with b0 as right hand side
	gauss.solve(b0, true);
	for (std::size_t i(0); i<n_rows; i++) {
		ASSERT_NEAR(b0[i], 0.0, std::numeric_limits<float>::epsilon());
	}

	// solve with b1 as right hand side
	gauss.solve(b1, false);
	for (std::size_t i(0); i<n_rows; i++) {
		ASSERT_NEAR(b1[i], 1.0, std::numeric_limits<float>::epsilon());
	}

	// solve with b2 as right hand side
	gauss.solve(b2, false);
	for (std::size_t i(0); i<n_rows; i++) {
		ASSERT_NEAR(fabs(b2[i]-x[i])/fabs(x[i]), 0.0, std::numeric_limits<float>::epsilon());
	}

	// solve with b3 as right hand side and x3 as solution vector
	gauss.solve(b3, x3, false);
	for (std::size_t i(0); i<n_rows; i++) {
		ASSERT_NEAR(fabs(x3[i]-x[i])/fabs(x[i]), 0.0, std::numeric_limits<float>::epsilon());
	}
	// assure entries of vector b3 are not changed
	for (std::size_t i(0); i<n_rows; i++) {
		ASSERT_NEAR(fabs(b3[i]-b3_copy[i])/fabs(b3[i]), 0.0, std::numeric_limits<float>::epsilon());
	}

	delete [] x;
	delete [] b0;
	delete [] b1;
	delete [] b2;
	delete [] b3;
	delete [] x3;
	delete [] b3_copy;
}
TEST(rosToEigen, transform) {
	Eigen::Isometry3d transform1 = toEigen(makeTransform(makeVector3(0, 1.5, 2), makeQuaternion(1, 0, 0, 0)));
	Eigen::Isometry3d transform2 = toEigen(makeTransform(makeVector3(-1.5, -2.6, -3.7), makeQuaternion(0, 0, 0, 1)));

	Eigen::Vector3d const & p1 = transform1.translation();
	Eigen::Vector3d const & p2 = transform2.translation();
	Eigen::Quaterniond const & q1 = Eigen::Quaterniond{transform1.rotation()};
	Eigen::Quaterniond const & q2 = Eigen::Quaterniond{transform2.rotation()};

	ASSERT_NEAR(0.0, p1.x(), 1e-5);
	ASSERT_NEAR(1.5, p1.y(), 1e-5);
	ASSERT_NEAR(2.0, p1.z(), 1e-5);
	ASSERT_NEAR(-1.5, p2.x(), 1e-5);
	ASSERT_NEAR(-2.6, p2.y(), 1e-5);
	ASSERT_NEAR(-3.7, p2.z(), 1e-5);

	ASSERT_NEAR(1, q1.x(), 1e-5);
	ASSERT_NEAR(0, q1.y(), 1e-5);
	ASSERT_NEAR(0, q1.z(), 1e-5);
	ASSERT_NEAR(0, q1.w(), 1e-5);
	ASSERT_NEAR(0, q2.x(), 1e-5);
	ASSERT_NEAR(0, q2.y(), 1e-5);
	ASSERT_NEAR(0, q2.z(), 1e-5);
	ASSERT_NEAR(1, q2.w(), 1e-5);
}
Exemple #26
0
// C = A * A; // Square matrices are only supported
TYPED_TEST(TestCSRSpGeMM, square)
{
    using SPER = CSRSparseEnvironment;
    using CLSE = ClSparseEnvironment;
    typedef typename uBLAS::compressed_matrix<float, uBLAS::row_major, 0, uBLAS::unbounded_array<int> > uBlasCSRM;
 
    cl::Event event;
    clsparseEnableAsync(CLSE::control, true);

#ifdef TEST_LONG
    clsparseStatus status = generateSpGemmResult_long<TypeParam>(this->csrMatrixC);
#else
    clsparseStatus status = generateSpGemmResult<TypeParam>(this->csrMatrixC);
#endif

    EXPECT_EQ(clsparseSuccess, status);

    status = clsparseGetEvent(CLSE::control, &event());
    EXPECT_EQ(clsparseSuccess, status);
    event.wait();

    //std::cout << "nrows =" << (this->csrMatrixC).num_rows << std::endl;
    //std::cout << "nnz =" << (this->csrMatrixC).num_nonzeros << std::endl;

    std::vector<int> resultRowPtr((this->csrMatrixC).num_rows + 1); // Get row ptr of Output CSR matrix
    std::vector<int> resultColIndices((this->csrMatrixC).num_nonzeros); // Col Indices
    std::vector<TypeParam> resultVals((this->csrMatrixC).num_nonzeros); // Values

    this->C = uBlasCSRM((this->csrMatrixC).num_rows, (this->csrMatrixC).num_cols, (this->csrMatrixC).num_nonzeros);
    (this->C).complete_index1_data();

    cl_int cl_status = clEnqueueReadBuffer(CLSE::queue,
        this->csrMatrixC.values, CL_TRUE, 0,
        (this->csrMatrixC).num_nonzeros *sizeof(TypeParam),
        resultVals.data(), 0, NULL, NULL);
    
    EXPECT_EQ(CL_SUCCESS, cl_status);

    
    cl_status = clEnqueueReadBuffer(CLSE::queue,
        this->csrMatrixC.colIndices, CL_TRUE, 0,
        (this->csrMatrixC).num_nonzeros * sizeof(int), resultColIndices.data(), 0, NULL, NULL);
    
    EXPECT_EQ(CL_SUCCESS, cl_status);

    
    cl_status = clEnqueueReadBuffer(CLSE::queue,
        this->csrMatrixC.rowOffsets, CL_TRUE, 0,
        ((this->csrMatrixC).num_rows + 1)  * sizeof(int), resultRowPtr.data(), 0, NULL, NULL);

    EXPECT_EQ(CL_SUCCESS, cl_status);

    std::cout << "Done with GPU" << std::endl;

#ifdef TEST_LONG 
    // Generate referencee result from ublas
    if (typeid(TypeParam) == typeid(float))
    {
        this->C = uBLAS::sparse_prod(SPER::ublasSCsrA, SPER::ublasSCsrB, this->C);
    }
#else
    if (typeid(TypeParam) == typeid(float))
    {
        this->C = uBLAS::sparse_prod(SPER::ublasSCsr, SPER::ublasSCsr, this->C);
    }

#endif
    
    /*
    if (typeid(TypeParam) == typeid(double))
    {
        this->C = uBLAS::sparse_prod(SPER::ublasDCsr, SPER::ublasDCsr, this->C);;
    }*/

    /*
    for (int i = 0; i < resultRowPtr.size(); i++)
    {
        ASSERT_EQ(resultRowPtr[i], this->C.index1_data()[i]);
    }*/
    this->browOffsetsMisFlag = false;
   this->checkRowOffsets(resultRowPtr);
   //if (::testing::Test::HasFailure())
   if (this->browOffsetsMisFlag == true)
    {
        // Check the values in Dense format
        this->checkInDense(resultRowPtr, resultColIndices, resultVals);
    }
    else
    {
        /* Check Col Indices */
        for (int i = 0; i < resultColIndices.size(); i++)
        {
            ASSERT_EQ(resultColIndices[i], this->C.index2_data()[i]);
        }

        /* Check Values */
        for (int i = 0; i < resultVals.size(); i++)
        {
            //TODO: how to define the tolerance 
            ASSERT_NEAR(resultVals[i], this->C.value_data()[i], 0.1);
        }

        ASSERT_EQ(resultRowPtr.size(), this->C.index1_data().size());

        //Rest of the col_indices should be zero
        for (size_t i = resultColIndices.size(); i < this->C.index2_data().size(); i++)
        {
            ASSERT_EQ(0, this->C.index2_data()[i]);
        }

        // Rest of the values should be zero
        for (size_t i = resultVals.size(); i < this->C.value_data().size(); i++)
        {
            ASSERT_EQ(0, this->C.value_data()[i]);
        }
    }

}//end TestCSRSpGeMM: square
/**
 * @brief Prüft, ob der Wald korrekt wächst.
 */
TEST_F(HarvestableTest, growHarvestable) {
    const double allowedDoubleError = 0.001;

    // Anfangsbedingungen testen
    ASSERT_NEAR(1.0, northernForest1->getAge(), allowedDoubleError);
    ASSERT_NEAR(1.3, northernForest2->getAge(), allowedDoubleError);

    // Wachsum sollte 1.0 pro 40 Sekunden Spielzeit sein.
    // Test nach 20 Sekunden: Erwarte Wachsum von 0.5
    game->update(20000);

    ASSERT_NEAR(1.5, northernForest1->getAge(), allowedDoubleError);
    ASSERT_NEAR(1.8, northernForest2->getAge(), allowedDoubleError);

    // Test nach 40 Sekunden: Erwarte Wachsum von 1.0
    game->update(20000);

    ASSERT_NEAR(2.0, northernForest1->getAge(), allowedDoubleError);
    ASSERT_NEAR(2.3, northernForest2->getAge(), allowedDoubleError);

    // Test nach 108 Sekunden: Erwarte Wachsum von 2.7
    game->update(68000);

    ASSERT_NEAR(3.7, northernForest1->getAge(), allowedDoubleError);
    ASSERT_NEAR(4.0, northernForest2->getAge(), allowedDoubleError);

    // Maximalwert ist 4,0. northernForest2 sollte nicht weiterwachsen, northernForest1 aber schon
    game->update(4000);

    ASSERT_NEAR(3.8, northernForest1->getAge(), allowedDoubleError);
    ASSERT_NEAR(4.0, northernForest2->getAge(), allowedDoubleError);

    // Maximalwert ist 4,0. Wälder müssen nun vollgewachsen sein.
    game->update(999999);

    ASSERT_NEAR(4.0, northernForest1->getAge(), allowedDoubleError);
    ASSERT_NEAR(4.0, northernForest2->getAge(), allowedDoubleError);
}
Exemple #28
0
// C = A * A; // A is filled with random powers of 2
TYPED_TEST(TestCSRSpGeMM, Powersof2)
{
    using SPER = CSRSparseEnvironment;
    using CLSE = ClSparseEnvironment;
    typedef typename uBLAS::compressed_matrix<float, uBLAS::row_major, 0, uBLAS::unbounded_array<int> > uBlasCSRM;

    cl::Event event;
    clsparseEnableAsync(CLSE::control, true);

    clsparse_matrix_fill<float> objFillVals(42, -14, 14);

    std::vector<float> tmpArray;
    tmpArray.resize(SPER::csrSMatrix.num_nonzeros);

    objFillVals.fillMtxTwoPowers(tmpArray.data(), tmpArray.size());
    //objFillVals.fillMtxOnes(tmpArray.data(), tmpArray.size());

    // Fill ublas scr with the same matrix values
    for (size_t i = 0; i < tmpArray.size(); i++)
    {
        SPER::ublasSCsr.value_data()[i] = tmpArray[i];
    }
    
    // Copy host to the device
    cl_int cl_status = clEnqueueWriteBuffer(CLSE::queue, SPER::csrSMatrix.values, CL_TRUE, 0, sizeof(float)* tmpArray.size(),
                                                 tmpArray.data(), 0, nullptr, nullptr);
    EXPECT_EQ(CL_SUCCESS, cl_status);
    tmpArray.clear();

    clsparseStatus status = generateSpGemmResult<TypeParam>(this->csrMatrixC);

    EXPECT_EQ(clsparseSuccess, status);

    status = clsparseGetEvent(CLSE::control, &event());
    EXPECT_EQ(clsparseSuccess, status);
    event.wait();


    std::vector<int> resultRowPtr((this->csrMatrixC).num_rows + 1); // Get row ptr of Output CSR matrix
    std::vector<int> resultColIndices((this->csrMatrixC).num_nonzeros); // Col Indices
    std::vector<TypeParam> resultVals((this->csrMatrixC).num_nonzeros); // Values

    this->C = uBlasCSRM((this->csrMatrixC).num_rows, (this->csrMatrixC).num_cols, (this->csrMatrixC).num_nonzeros);
    (this->C).complete_index1_data();

    cl_status = clEnqueueReadBuffer(CLSE::queue,
        this->csrMatrixC.values, CL_TRUE, 0,
        (this->csrMatrixC).num_nonzeros *sizeof(TypeParam),
        resultVals.data(), 0, NULL, NULL);

    EXPECT_EQ(CL_SUCCESS, cl_status);


    cl_status = clEnqueueReadBuffer(CLSE::queue,
        this->csrMatrixC.colIndices, CL_TRUE, 0,
        (this->csrMatrixC).num_nonzeros * sizeof(int), resultColIndices.data(), 0, NULL, NULL);

    EXPECT_EQ(CL_SUCCESS, cl_status);


    cl_status = clEnqueueReadBuffer(CLSE::queue,
        this->csrMatrixC.rowOffsets, CL_TRUE, 0,
        ((this->csrMatrixC).num_rows + 1)  * sizeof(int), resultRowPtr.data(), 0, NULL, NULL);

    EXPECT_EQ(CL_SUCCESS, cl_status);

    std::cout << "Done with GPU" << std::endl;

    if (typeid(TypeParam) == typeid(float))
    {
        this->C = uBLAS::sparse_prod(SPER::ublasSCsr, SPER::ublasSCsr, this->C);
    }

    this->browOffsetsMisFlag = false;
    this->checkRowOffsets(resultRowPtr);
    //if (::testing::Test::HasFailure())
    if (this->browOffsetsMisFlag == true)
    {
        // Check the values in Dense format
        this->checkInDense(resultRowPtr, resultColIndices, resultVals);
    }
    else
    {
        /* Check Col Indices */
        for (int i = 0; i < resultColIndices.size(); i++)
        {
            ASSERT_EQ(resultColIndices[i], this->C.index2_data()[i]);
        }

        /* Check Values */
        for (int i = 0; i < resultVals.size(); i++)
        {
            //TODO: how to define the tolerance 
            ASSERT_NEAR(resultVals[i], this->C.value_data()[i], 0.0);
        }

        ASSERT_EQ(resultRowPtr.size(), this->C.index1_data().size());

        //Rest of the col_indices should be zero
        for (size_t i = resultColIndices.size(); i < this->C.index2_data().size(); i++)
        {
            ASSERT_EQ(0, this->C.index2_data()[i]);
        }

        // Rest of the values should be zero
        for (size_t i = resultVals.size(); i < this->C.value_data().size(); i++)
        {
            ASSERT_EQ(0, this->C.value_data()[i]);
        }
    }

}//end TestCSRSpGeMM: Powersof2
TEST(GradientMachine, testPredict) {
  //! TODO(yuyang18): Test GPU Code.
  paddle::TrainerConfigHelper config("./test_predict_network.py");
  std::string buffer;
  ASSERT_TRUE(config.getModelConfig().SerializeToString(&buffer));
  paddle_gradient_machine machine;

  ASSERT_EQ(kPD_NO_ERROR,
            paddle_gradient_machine_create_for_inference(
                &machine, &buffer[0], (int)buffer.size()));
  std::unique_ptr<paddle::GradientMachine> gm(
      paddle::GradientMachine::create(config.getModelConfig()));
  ASSERT_NE(nullptr, gm);
  gm->randParameters();
  gm->saveParameters("./");

  ASSERT_EQ(kPD_NO_ERROR,
            paddle_gradient_machine_load_parameter_from_disk(machine, "./"));

  paddle_gradient_machine machineSlave;
  ASSERT_EQ(kPD_NO_ERROR,
            paddle_gradient_machine_create_shared_param(
                machine, &buffer[0], (int)buffer.size(), &machineSlave));
  std::swap(machineSlave, machine);
  paddle_arguments outArgs = paddle_arguments_create_none();

  paddle_arguments inArgs = paddle_arguments_create_none();
  ASSERT_EQ(kPD_NO_ERROR, paddle_arguments_resize(inArgs, 1));
  paddle_matrix mat = paddle_matrix_create(1, 100, false);
  static_assert(std::is_same<paddle_real, paddle::real>::value, "");

  auto data = randomBuffer(100);
  paddle_real* rowPtr;
  ASSERT_EQ(kPD_NO_ERROR, paddle_matrix_get_row(mat, 0, &rowPtr));
  memcpy(rowPtr, data.data(), data.size() * sizeof(paddle_real));

  ASSERT_EQ(kPD_NO_ERROR, paddle_arguments_set_value(inArgs, 0, mat));
  ASSERT_EQ(kPD_NO_ERROR,
            paddle_gradient_machine_forward(machine, inArgs, outArgs, false));

  uint64_t sz;
  ASSERT_EQ(kPD_NO_ERROR, paddle_arguments_get_size(outArgs, &sz));
  ASSERT_EQ(1UL, sz);

  ASSERT_EQ(kPD_NO_ERROR, paddle_arguments_get_value(outArgs, 0, mat));
  std::vector<paddle::Argument> paddleInArgs;
  std::vector<paddle::Argument> paddleOutArgs;
  paddleInArgs.resize(1);
  paddleInArgs[0].value =
      paddle::Matrix::create(data.data(), 1, 100, false, false);

  gm->forward(paddleInArgs, &paddleOutArgs, paddle::PASS_TEST);

  auto matPaddle = paddleOutArgs[0].value;

  uint64_t height, width;
  ASSERT_EQ(kPD_NO_ERROR, paddle_matrix_get_shape(mat, &height, &width));
  ASSERT_EQ(matPaddle->getHeight(), height);
  ASSERT_EQ(matPaddle->getWidth(), width);

  ASSERT_EQ(kPD_NO_ERROR, paddle_matrix_get_row(mat, 0, &rowPtr));
  for (size_t i = 0; i < width; ++i) {
    ASSERT_NEAR(matPaddle->getData()[i], rowPtr[i], 1e-5);
  }

  ASSERT_EQ(kPD_NO_ERROR, paddle_matrix_destroy(mat));
  ASSERT_EQ(kPD_NO_ERROR, paddle_arguments_destroy(inArgs));
  ASSERT_EQ(kPD_NO_ERROR, paddle_arguments_destroy(outArgs));
  std::swap(machineSlave, machine);
  ASSERT_EQ(kPD_NO_ERROR, paddle_gradient_machine_destroy(machineSlave));
  ASSERT_EQ(kPD_NO_ERROR, paddle_gradient_machine_destroy(machine));
}
TEST(SquareRootTest, PosParam) {
    ASSERT_NEAR(2, my_root(4), 1e-6);
    ASSERT_NEAR(1.732050, my_root(3), 1e-6);
    ASSERT_NEAR(351.36306, my_root(123456), 1e-6);
}