int test_ht(void* arg) { int nlines = 10; int* lines = new int[4*nlines]; float* flines = new float[2*nlines]; float rho = 10.0f, theta = 0.1f; int srn = 10, stn = 10; int threshold = 10; int lineLength = 10, lineGap = 2; int w = 100; /* width and height of the rect */ int h = 100; int type = int(arg); IplImage* image; /* Source and destination images */ image = cvCreateImage( cvSize(w, h), 8, 1 ); iplSet(image, 0); if( image == NULL ) { delete lines; delete flines; return trsResult(TRS_FAIL, "Not enough memory to perform the test"); } switch(type) { case HT_STANDARD: /* Run the distance transformation function */ cvHoughLines(image, rho, theta, threshold, flines, nlines); break; case HT_PP: cvHoughLinesP(image, rho, theta, threshold, lineLength, lineGap, lines, nlines); break; case HT_MD: cvHoughLinesSDiv(image, rho, srn, theta, stn, threshold, flines, nlines); break; default: iplDeallocate( image, IPL_IMAGE_ALL ); delete lines; delete flines; trsResult(TRS_FAIL, "No such function"); } cvReleaseImage( &image ); delete lines; delete flines; if(iplGetErrStatus() < 0) { return trsResult(TRS_FAIL, "Function returned 'bad argument'"); } else { return trsResult(TRS_OK, "No errors"); } }
int testGibbsInference() { int ret = TRS_OK; int seed = time(0); std::cout<<"seed = "<< seed<<std::endl; pnlSeed(seed); ///////////////////////////////////////////////////////////////////////////// float eps = -1.0f; while( eps <= 0 ) { trssRead( &eps, "1.5e-1f", "accuracy in test" ); } ret = ret && GibbsForTreeBNet(); ret = ret && GibbsMPEforScalarGaussianBNet( eps ); ret = ret && GibbsForSingleGaussian( eps ); ret = ret && GibbsForMixtureBNet(eps); ret = ret && GibbsForScalarGaussianBNet( eps ); ret = ret && GibbsForSimplestGaussianBNet( eps ); ret = ret && GibbsForGaussianBNet( eps ); ret = ret && GibbsForAsiaBNet( eps ); ret = ret && GibbsForMNet( eps ); ret = ret && GibbsMPEForMNet( eps ); ret = ret && GibbsForInceneratorBNet( eps ); ret = ret && GibbsForSparseBNet( eps ); return trsResult( ret, ret == TRS_OK ? "No errors" : "Bad test on Gibbs Sampling Inference" ); }
int testCondGaussian() { int res = TRS_OK; TestsPnlHigh tests; try { tests.TestDesc(); tests.TestNTabNCont(); tests.TestDefaultDistribution(); tests.TestCondGaussianFillData(); tests.TestSetPGaussian(); tests.TestGetDiscreteParentValuesIndexes(); tests.TestGetGaussianMeanCovarWeights(); tests.TestConditionalGaussianGetJPD(); tests.Test2EditEvidence(); tests.TestCondGaussianGetMPE(); tests.TestCondGaussianParamLearning(); } catch(pnl::CException e) { std::cout << e.GetMessage(); res = TRS_FAIL; } return trsResult( res, res == TRS_OK ? "No errors" : "Bad test on DBN wrappers"); }
template<class Storage, class SrcType, class ThreshType, class DstType> static int foaCvBackProject(Storage, SrcType, ThreshType, DstType) { const S1 = 4; const S2 = 4; const S3 = 4; CvSize roi = {100, 100}; int step = roi.width * sizeof( SrcType ); SrcType* src[3]; src[0] = new SrcType[roi.width * roi.height]; src[1] = new SrcType[roi.width * roi.height]; src[2] = new SrcType[roi.width * roi.height]; DstType* measure = new DstType[roi.width * roi.height]; ThreshType _thresh[3][5] = {{1, 2, 3, 4, 5}, {2, 3, 4, 5, 6}, {5, 6, 7, 9, 10}}; ThreshType* thresh[3] = { _thresh[0], _thresh[1], _thresh[2] }; int Errors = 0; for( int i = 0; i < roi.width * roi.height; i++ ) src[0][i] = src[1][i] = src[2][i] = 0; for( i = 0; i < roi.width; i++ ) for( int j = 0; j < 3; j++ ) src[j][roi.width + i] = (SrcType)thresh[j][i%5]; CVHistogram<Storage> hist( S1, S2, S3 ); CvCalculateC1( hist, src, roi, step, thresh ); CvBackProject<CVHistogram<Storage>, SrcType, ThreshType, DstType> ( hist, src, roi, step, thresh, measure, roi.width * sizeof(DstType), 0 ); for( i = 0; i < roi.width; i++ ) if( measure[roi.width + i] != roi.width / 5 * (1 + (i%5 == 0) + (i%5 == 1))) { trsWrite( ATS_CON | ATS_LST, "Wrong destination value\n" ); Errors++; break; } for( int y = 0; y < roi.height; y++ ) for( int x = 0; x < roi.width; x++ ) if( y != 1 && measure[roi.width * y + x] != 0 ) { trsWrite( ATS_CON | ATS_LST, "Wrong destination value (non zero)\n" ); Errors++; goto _exit; } _exit:; delete src[0]; delete src[1]; delete src[2]; delete measure; return Errors == 0 ? TRS_OK : trsResult( TRS_FAIL, "Fixed %d errors", Errors ); }
int testMatrix() { int ret = TRS_OK; int dim = 0; int i; while(dim <= 0) { trsiRead( &dim, "128", "matrix dimension" ); } int* range = (int*)trsGuardcAlloc( dim, sizeof(int) ); float* data = (float*)trsGuardcAlloc( dim, sizeof(float) ); for(i = 0; i < dim; i++) { range[i] = 1; data[i] = 1.0f*i; } range[0] = dim; CNumericDenseMatrix<float>* m = CNumericDenseMatrix<float>::Create(1, range, data); int length; const float *mdata; m->GetRawData(&length, &mdata); for(i = 0; i < dim; i++) { // Test the values... if(mdata[i] != data[i]) { ret = TRS_FAIL; break; } } delete m; int range_memory_flag = trsGuardCheck( range ); int data_memory_flag = trsGuardCheck( data ); trsGuardFree( range ); trsGuardFree( data ); if(range_memory_flag || data_memory_flag) { return trsResult( TRS_FAIL, "Dirty memory"); } return trsResult( ret, ret == TRS_OK ? "No errors" : "Bad matrix data"); }
static int fmaMemoryTest( void/** prm*/ ) { long errors = 0; /* Some variables */ errors = gAtsMemoryManager.CheckMemoryLeaks(); return errors == 0 ? TRS_OK : trsResult( TRS_FAIL, "Fixed %d errors", errors ); }
template <class Val, class Idx> static int foaCvTreeIterator() { int Errors = 0; typedef CvTree<Val, Idx>::node_type node_type; CvTree<Val, Idx> tree; for( Idx i = 0; i < SIZE; i++ ) tree[i] = (Val)(i + 1); CvTreeIterator<node_type> iterator; iterator = tree.begin(); if( *iterator != 1 ) { Errors++; trsWrite( ATS_CON | ATS_LST, "Wrong CvTree::begin() function\n" ); } if( *(iterator++) != 1 ) { Errors++; trsWrite( ATS_CON | ATS_LST, "Wrong postfix operator++ (not postfix)\n" ); } if( *iterator != 2 ) { Errors++; trsWrite( ATS_CON | ATS_LST, "Wrong postfix operator++ (not increment)\n" ); } for( i = 2; i < SIZE; i++ ) if( *(++iterator) != (i + 1) ) { Errors++; trsWrite( ATS_CON | ATS_LST, "Wrong prefix operator++ (not increment)\n" ); break; } if( *(++iterator) != SIZE ) { Errors++; trsWrite( ATS_CON | ATS_LST, "Wrong operator++ (increment out of date)\n" ); } if( !(iterator == iterator) ) { Errors++; trsWrite( ATS_CON | ATS_LST, "Bad operator==" ); } if( iterator != iterator ) { Errors++; trsWrite( ATS_CON | ATS_LST, "Bad operator!=" ); } return Errors == 0 ? TRS_OK : trsResult( TRS_FAIL, "Fixed %d errors", Errors ); }
int test1_5JTreeInfDBNCondGauss() { int ret = TRS_OK; int seed = pnlTestRandSeed(); std::cout<<"seed"<<seed<<std::endl; srand( seed ); CDBN *pDBN = tCreateArHMMwithGaussObs(); int nTimeSlice = -1; while(nTimeSlice <= 0) { trsiRead (&nTimeSlice, "4", "Number of slices"); } float eps = -1.0f; while( eps <= 0 ) { trssRead( &eps, "1e-2f", "accuracy in test"); } int result = 1; result = CompareSmoothingArHMM( pDBN, nTimeSlice, eps ); if( !result ) { ret = TRS_FAIL; } result = CompareFilteringArHMM( pDBN, nTimeSlice, eps ); if( !result ) { ret = TRS_FAIL; } result = CompareFixLagSmoothingArHMM( pDBN, nTimeSlice, eps ); if( !result ) { ret = TRS_FAIL; } result = CompareViterbyArHMM( pDBN, nTimeSlice, eps ); if( !result ) { ret = TRS_FAIL; } ////////////////////////////////////////////////////////////////////////// delete pDBN; return trsResult( ret, ret == TRS_OK ? "No errors" : "Bad test on 1_5 Slice JTree DBN"); }
static int hu_moments_test( void ) { const double success_error_level = 1e-7; CvSize size = { 512, 512 }; int i; IplImage* img = atsCreateImage( size.width, size.height, 8, 1, 0 ); CvMoments moments; CvHuMoments a, b; AtsRandState rng_state; int seed = atsGetSeed(); double nu20, nu02, nu11, nu30, nu21, nu12, nu03; double err = 0; char buffer[100]; atsRandInit( &rng_state, 0, 255, seed ); atsbRand8u( &rng_state, (uchar*)(img->imageData), size.width * size.height ); cvMoments( img, &moments, 0 ); atsReleaseImage( img ); nu20 = cvGetNormalizedCentralMoment( &moments, 2, 0 ); nu11 = cvGetNormalizedCentralMoment( &moments, 1, 1 ); nu02 = cvGetNormalizedCentralMoment( &moments, 0, 2 ); nu30 = cvGetNormalizedCentralMoment( &moments, 3, 0 ); nu21 = cvGetNormalizedCentralMoment( &moments, 2, 1 ); nu12 = cvGetNormalizedCentralMoment( &moments, 1, 2 ); nu03 = cvGetNormalizedCentralMoment( &moments, 0, 3 ); cvGetHuMoments( &moments, &a ); b.hu1 = nu20 + nu02; b.hu2 = sqr(nu20 - nu02) + 4*sqr(nu11); b.hu3 = sqr(nu30 - 3*nu12) + sqr(3*nu21 - nu03); b.hu4 = sqr(nu30 + nu12) + sqr(nu21 + nu03); b.hu5 = (nu30 - 3*nu12)*(nu30 + nu12)*(sqr(nu30 + nu12) - 3*sqr(nu21 + nu03)) + (3*nu21 - nu03)*(nu21 + nu03)*(3*sqr(nu30 + nu12) - sqr(nu21 + nu03)); b.hu6 = (nu20 - nu02)*(sqr(nu30 + nu12) - sqr(nu21 + nu03)) + 4*nu11*(nu30 + nu12)*(nu21 + nu03); b.hu7 = (3*nu21 - nu03)*(nu30 + nu12)*(sqr(nu30 + nu12) - 3*sqr(nu21 + nu03)) + (3*nu12 - nu30)*(nu21 + nu03)*(3*sqr(nu30 + nu12) - sqr(nu21 + nu03)); for( i = 0; i < 7; i++ ) { double t = rel_err( ((double*)&b)[i], ((double*)&a)[i] ); if( t > err ) err = t; } sprintf( buffer, "Accuracy: %.4e", err ); return trsResult( err > success_error_level ? TRS_FAIL : TRS_OK, buffer ); }
static int foaCvTreeType( void* param ) { int Param = (int)param; switch (Param) { case INT: return foaCvTree( (int) 1, (int)2 ); case FLOAT: return foaCvTree( (float) 1, (int)2 ); case SHORT: return foaCvTree( (short) 1, (int)2 ); default: return trsResult( TRS_FAIL, "Wrong parameter" ); } }
static int foaCvTreeIteratorType( void* param ) { int Param = (int)param; switch (Param) { case INT: return foaCvTreeIterator<int, int>(); case FLOAT: return foaCvTreeIterator<float, int>(); case SHORT: return foaCvTreeIterator<short, int>(); default: return trsResult( TRS_FAIL, "Wrong parameter" ); } }
template<class Storage1, class Storage2> static int foaOperations(Storage1, Storage2) { const int SIZE = 720; typedef Storage1::value_type Val; typedef Storage1::idx_type Idx; CVHistogram<Storage1> hist1( SIZE ); CVHistogram<Storage2> hist2( SIZE ); int Errors = 0; for( Idx i = 0; i < SIZE; i++ ) { hist1[i] = (Val)(i % 10); hist2[i] = (Val)(9 - hist1[i]); } if( calc_histogram_intersection( hist1, hist2 ) != SIZE * 2 ) { Errors++; trsWrite( ATS_CON | ATS_LST, "Error Intersection function\n" ); } double res; if( (res = fabs(calc_histogram_chi_square( hist1, hist2 ) - SIZE * 330 / 90)) > 0.0001 ) { Errors++; trsWrite( ATS_CON | ATS_LST, "Error ChiSqr function\n" ); } for( i = 0; i < SIZE; i++ ) { hist1[i] = (Val)(i % 9); hist2[i] = (Val)(8 - hist1[i]); } if( fabs(calc_histogram_correlation( hist1, hist2 ) + 1 ) >= 0.0001 ) { Errors++; trsWrite( ATS_CON | ATS_LST, "Error Correl function\n" ); } return Errors == 0 ? TRS_OK : trsResult( TRS_FAIL, "Fixed %d errors", Errors ); }
static int foaCvBackProjectType( void* param ) { int Param = (int)param; switch(Param) { case ARRAY_INT: return foaCvBackProject(CvArray<int>(),int(), int(), int()); case ARRAY_FLOAT: return foaCvBackProject(CvArray<float>(),float(), float(), int()); case ARRAY_SHORT: return foaCvBackProject(CvArray<short>(),short(), short(), int()); case TREE_INT: return foaCvBackProject(CvTree<int>(),int(), int(), int()); case TREE_FLOAT: return foaCvBackProject(CvTree<float>(),float(), float(), int()); case TREE_SHORT: return foaCvBackProject(CvTree<short>(),short(), short(), int()); default: assert( 0 ); return trsResult( TRS_UNDEF, "Wrong parameter" ); } }
int testGraph() { int i, j; int ret = TRS_OK; const int nnodes = 7; int numOfNeigh[] = { 3, 3, 4, 5, 2, 3, 2 }; int neigh1[] = { 3, 1, 2 }; int neigh2[] = { 2, 0, 3 }; int neigh3[] = { 0, 1, 3, 6 }; int neigh4[] = { 0, 1, 2, 4, 5 }; int neigh5[] = { 3, 5 }; int neigh6[] = { 3, 4, 6 }; int neigh7[] = { 5, 2 }; ENeighborType orient1[] = { ntChild, ntChild, ntChild }; ENeighborType orient2[] = { ntChild, ntParent, ntChild }; ENeighborType orient3[] = { ntParent, ntParent, ntChild, ntChild }; ENeighborType orient4[] = { ntParent, ntParent, ntParent, ntNeighbor, ntNeighbor }; ENeighborType orient5[] = { ntNeighbor, ntNeighbor }; ENeighborType orient6[] = { ntNeighbor, ntNeighbor, ntChild }; ENeighborType orient7[] = { ntParent, ntParent }; int *neigh[] = { neigh1, neigh2, neigh3, neigh4, neigh5, neigh6, neigh7 }; ENeighborType *orient[] = { orient1, orient2, orient3, orient4, orient5, orient6, orient7 }; const int *neighbors; const ENeighborType *orientation; double time1; TestGraph *graph; /* The graph I used to have a test is described in a document named graph_structure.doc which is stored in VSS base in docs folder */ /* to test graph the graph creation you can either: */ /* 1. create it from the list of neighbors */ trsTimerStart(0); graph = new TestGraph(nnodes, numOfNeigh, neigh, orient); graph->Dump(); /* look at the graph */ for( i = 0; i < nnodes; i++ ) { graph->GetNeighbors( i, &numOfNeigh[i], &neighbors, &orientation ); intVector neighToComp( neigh[i], neigh[i] + numOfNeigh[i] ); std::sort( neighToComp.begin(), neighToComp.end() ); for( j = 0; j < numOfNeigh[i]; j++ ) { if(neighbors[j] != neighToComp[j]) { ret = TRS_FAIL; } } } delete(graph); time1 = trsTimerClock(0); std::cout<<"timing of graph creation with all neighbors preset " <<time1<<std::endl; /* 2. create a graph with a blank list of neighbors and then set neighbors */ trsTimerStart(0); graph = new TestGraph(nnodes, NULL, NULL, NULL); graph->SetNeighbors( 0, numOfNeigh[0], neigh1, orient1 ); graph->SetNeighbors( 1, numOfNeigh[1], neigh2, orient2 ); graph->SetNeighbors( 2, numOfNeigh[2], neigh3, orient3 ); graph->SetNeighbors( 3, numOfNeigh[3], neigh4, orient4 ); graph->SetNeighbors( 4, numOfNeigh[4], neigh5, orient5 ); graph->SetNeighbors( 5, numOfNeigh[5], neigh6, orient6 ); graph->SetNeighbors( 6, numOfNeigh[6], neigh7, orient7 ); graph->Dump(); for( i = 0; i < nnodes; i++ ) { graph->GetNeighbors( i, &numOfNeigh[i], &neighbors, &orientation ); intVector neighToComp( neigh[i], neigh[i] + numOfNeigh[i] ); std::sort( neighToComp.begin(), neighToComp.end() ); for( j = 0; j < numOfNeigh[i]; j++ ) { if(neighbors[j] != neighToComp[j]) { ret = TRS_FAIL; } } } delete(graph); time1 = trsTimerClock(0); std::cout<<"graph creation with setting the each neighbor separatly " <<time1<<std::endl; /* 3. create a blank graph and add edges to it. take the edges from the list of neighbors above */ trsTimerStart(0); graph = new TestGraph(nnodes, NULL, NULL, NULL); graph->AddEdge( 0, 1, 1 ); graph->AddEdge( 0, 2, 1 ); graph->AddEdge( 0, 3, 1 ); graph->AddEdge( 1, 2, 1 ); graph->AddEdge( 1, 3, 1 ); graph->AddEdge( 2, 3, 1 ); graph->AddEdge( 2, 6, 1 ); graph->AddEdge( 3, 4, 0 ); graph->AddEdge( 3, 5, 0 ); graph->AddEdge( 4, 5, 0 ); graph->AddEdge( 5, 6, 1 ); graph->Dump(); for( i = 0; i < nnodes; i++ ) { graph->GetNeighbors( i, &numOfNeigh[i], &neighbors, &orientation ); intVector neighToComp( neigh[i], neigh[i] + numOfNeigh[i] ); std::sort( neighToComp.begin(), neighToComp.end() ); for( j = 0; j < numOfNeigh[i]; j++ ) { if(neighbors[j] != neighToComp[j]) { ret = TRS_FAIL; } } } delete(graph); time1 = trsTimerClock(0); std::cout<<"timing graph creation with edges added "<<time1<<std::endl; /* all three graphs that are shown, should look the same */ return trsResult( ret, ret == TRS_OK ? "No errors" : "Graph FAILED"); }
int testSEGaussian() { PNL_USING int i; int ret = TRS_OK; float eps = 1e-4f; //create Gaussian distribution (inside the potential) and try to multiply //is by Delta //create Model Domain int nSimNodes = 3; CNodeType simNT = CNodeType(0, 2); CModelDomain* pSimDomain = CModelDomain::Create( nSimNodes, simNT ); //create 2 potentials intVector dom; dom.assign(3,0); dom[1] = 1; dom[2] = 2; floatVector mean; mean.assign(6, 0); floatVector cov; cov.assign(36, 0.1f); for( i = 0; i < 6; i++ ) { mean[i] = 1.1f*i; cov[i*7] = 2.0f; } CGaussianPotential* pPot = CGaussianPotential::Create( dom, pSimDomain, 1, mean, cov, 1.0f ); //create gaussian CPD with gaussian parent const pConstNodeTypeVector* pTypes = pPot->GetArgType(); //create data weigth floatVector weights1; weights1.assign(4, 1.0f); floatVector weights2; weights2.assign(4, 2.0f); const float* weights[] = { &weights1.front(), &weights2.front()}; CGaussianDistribFun* pGauCPD = CGaussianDistribFun::CreateInMomentForm( 0, 3, &pTypes->front(), &mean.front(), &cov.front(), weights ); pPot->Dump(); pPot->Normalize(); //try to get multiplied delta intVector pos; floatVector valuesDelta; intVector offsets; pPot->GetMultipliedDelta(&pos, &valuesDelta, &offsets); if( pos.size() != 0 ) { ret = TRS_FAIL; } //enter evidence to the pot and after that expand and compare results //create evidence object /* valueVector obsVals; obsVals.assign(6,Value(0) ); obsVals[0].SetFlt(1.0f); obsVals[1].SetFlt(1.5f); obsVals[2].SetFlt(2.0f); obsVals[3].SetFlt(2.5f); obsVals[4].SetFlt(3.0f); obsVals[5].SetFlt(3.5f); CEvidence* pEvid = CEvidence::Create( pSimDomain, 3, &dom.front(), obsVals ); CPotential* pShrPot = pPot->ShrinkObservedNodes( pEvid );*/ CGaussianPotential* pCanonicalPot = CGaussianPotential::Create( dom, pSimDomain, 0, mean, cov, 1.0f ); CMatrix<float>* matrK = pCanonicalPot->GetMatrix(matK); intVector multIndex; multIndex.assign(2,5); matrK->SetElementByIndexes( 3.0f, &multIndex.front() ); CMatrix<float>* matrH = pCanonicalPot->GetMatrix(matH); multIndex[0] = 0; matrH->SetElementByIndexes(0.0f, &multIndex.front()); pPot->ConvertToSparse(); pPot->ConvertToDense(); //create other Gaussian potential for division i = 1; floatVector meanSmall; meanSmall.assign(2, 1.0f); floatVector covSmall; covSmall.assign(4, 0.0f); covSmall[0] = 1.0f; covSmall[3] = 1.0f; CGaussianPotential* pSmallPot = CGaussianPotential::Create( &i, 1, pSimDomain, 1, &meanSmall.front(), &covSmall.front(), 1.0f ); //divide by distribution in moment form (*pCanonicalPot) /= (*pSmallPot); //create big unit function distribution and marginalize it CGaussianPotential* pBigUnitPot = CGaussianPotential::CreateUnitFunctionDistribution(dom, pSimDomain, 1); CGaussianPotential* pCloneBigUniPot = static_cast<CGaussianPotential*>( pBigUnitPot->CloneWithSharedMatrices()); if( !pCloneBigUniPot->IsFactorsDistribFunEqual(pBigUnitPot, eps) ) { ret = TRS_FAIL; } CPotential* pMargUniPot = pBigUnitPot->Marginalize(&dom.front(), 1, 0); (*pBigUnitPot) /= (*pSmallPot); (*pBigUnitPot) *= (*pSmallPot); //check if there are some problems static_cast<CGaussianDistribFun*>(pBigUnitPot->GetDistribFun())->CheckCanonialFormValidity(); if( pBigUnitPot->IsDistributionSpecific() != 1 ) { ret = TRS_FAIL; } (*pBigUnitPot) /= (*pCanonicalPot); (*pBigUnitPot) *= (*pCanonicalPot); static_cast<CGaussianDistribFun*>(pBigUnitPot->GetDistribFun())->CheckCanonialFormValidity(); if( pBigUnitPot->IsDistributionSpecific() != 1 ) { ret = TRS_FAIL; } static_cast<CGaussianDistribFun*>(pSmallPot->GetDistribFun())-> UpdateCanonicalForm(); (*pPot) /= (*pSmallPot); pSmallPot->SetCoefficient(0.0f,1); pSmallPot->Dump(); //create canonical potential without coefficient i = 0; CDistribFun* pCopyPotDistr = pPot->GetDistribFun()->ConvertCPDDistribFunToPot(); CGaussianPotential* pCanSmallPot = CGaussianPotential::Create( &i, 1, pSimDomain, 0, &meanSmall.front(), &covSmall.front(), 1.0f ); CGaussianPotential* pCanPotCopy = static_cast<CGaussianPotential*>(pCanSmallPot->Clone()); CGaussianPotential* pCanPotCopy1 = static_cast<CGaussianPotential*>(pCanPotCopy->CloneWithSharedMatrices()); (*pPot) /= (*pCanSmallPot); (*pPot) *= (*pCanSmallPot); //can compare results, if we want CDistribFun* pMultDivRes = pPot->GetDistribFun(); float diff = 0; if( !pMultDivRes->IsEqual(pCopyPotDistr, eps,1, &diff) ) { ret = TRS_FAIL; std::cout<<"the diff is "<<diff<<std::endl; } delete pCopyPotDistr; //create delta distribution floatVector deltaMean; deltaMean.assign( 2, 1.5f ); i = 0; CGaussianPotential* pDeltaPot = CGaussianPotential::CreateDeltaFunction( &i, 1, pSimDomain, &deltaMean.front(), 1 ); CGaussianDistribFun* pDeltaDistr = static_cast<CGaussianDistribFun*>( pDeltaPot->GetDistribFun()); pDeltaDistr->CheckMomentFormValidity(); pDeltaDistr->CheckCanonialFormValidity(); pDeltaPot->Dump(); //multiply some potential by delta (*pCanSmallPot) *= (*pDeltaPot); (*pPot) *= (*pDeltaPot); //(*pPot) *= (*pDeltaPot); pPot->GetMultipliedDelta(&pos, &valuesDelta, &offsets); (*pCanonicalPot) *= (*pDeltaPot); //marginalize this distribFun multiplied by delta intVector margDims; margDims.assign(2,1); margDims[1] = 2; CPotential* pMargPot = pPot->Marginalize( &margDims.front(), 2 ); i = 0; CPotential* pSmallMargPot = pPot->Marginalize(&i, 1); //marginalize in canonical form CPotential* pMargCanPot = pCanonicalPot->Marginalize( &margDims.front(), 2 ); CPotential* pSmallCanPot = pCanonicalPot->Marginalize(&i,1); //create unit function distribution in canonical form i = 0; CGaussianPotential* pUnitPot = CGaussianPotential::CreateUnitFunctionDistribution( &i, 1, pSimDomain, 1); pUnitPot->Dump(); CGaussianDistribFun* pUnitDistr = static_cast<CGaussianDistribFun*>( pUnitPot->GetDistribFun()); pUnitDistr->CheckCanonialFormValidity(); pUnitDistr->CheckMomentFormValidity(); (*pPot) *= (*pUnitPot); if( pUnitPot->IsFactorsDistribFunEqual(pBigUnitPot, eps, 1) ) { ret = TRS_FAIL; } deltaMean.resize(6); deltaMean[2] = 2.5f; deltaMean[3] = 2.5f; deltaMean[4] = 3.5f; deltaMean[5] = 3.5f; CGaussianPotential* pBigDeltaPot = CGaussianPotential::CreateDeltaFunction( dom, pSimDomain, deltaMean, 1 ); CGaussianPotential* pCloneBigDeltaPot = static_cast<CGaussianPotential*>( pBigDeltaPot->CloneWithSharedMatrices()); //we can shrink observed nodes in this potential valueVector vals; vals.resize(2); vals[0].SetFlt(1.5f); vals[1].SetFlt(1.5f); i = 0; CEvidence* pDeltaEvid = CEvidence::Create( pSimDomain, 1, &i,vals ); CGaussianPotential* pShrGauDeltaPot = static_cast<CGaussianPotential*>( pBigDeltaPot->ShrinkObservedNodes( pDeltaEvid )); delete pDeltaEvid; pShrGauDeltaPot->Dump(); delete pShrGauDeltaPot; CPotential* pSmallDeltaMarg = pBigDeltaPot->Marginalize( &dom.front(), 1, 0 ); pSmallDeltaMarg->Normalize(); pDeltaPot->Normalize(); if( !pSmallDeltaMarg->IsFactorsDistribFunEqual( pDeltaPot, eps, 1 ) ) { ret = TRS_FAIL; } //call operator = for delta distributions (*pSmallDeltaMarg) = (*pDeltaPot); //call operator = for canonical and delta distribution (*pCanPotCopy) = (*pUnitPot); //call operator = for canonical and unit distribution (*pCanPotCopy1) = (*pDeltaPot); (*pUnitPot) = (*pUnitPot); (*pPot) *= (*pBigDeltaPot); (*pCloneBigDeltaPot) *= (*pDeltaPot); if( !pCloneBigDeltaPot->IsFactorsDistribFunEqual(pBigDeltaPot, eps) ) { ret = TRS_FAIL; } //we can create the matrix which will be almost delta distribution, //but covariance matrix will contain almost zeros floatVector almostDeltaCov; almostDeltaCov.assign(4, 0.0f); almostDeltaCov[0] = 0.00001f; almostDeltaCov[3] = 0.00001f; i = 0; CGaussianPotential* pAlmostDeltaPot = CGaussianPotential::Create( &i, 1, pSimDomain, 1, &deltaMean.front(), &almostDeltaCov.front(), 1.0f ); if( !pDeltaPot->IsFactorsDistribFunEqual( pAlmostDeltaPot, eps, 0 ) ) { ret = TRS_FAIL; } if( !pAlmostDeltaPot->IsFactorsDistribFunEqual( pDeltaPot, eps, 0 ) ) { ret = TRS_FAIL; } (*pCloneBigUniPot ) = ( *pPot ); if( !(pCloneBigUniPot->IsFactorsDistribFunEqual(pPot, eps)) ) { ret = TRS_FAIL; } (*pCloneBigDeltaPot) = (*pPot); if( !(pCloneBigDeltaPot->IsFactorsDistribFunEqual(pPot, eps)) ) { ret = TRS_FAIL; } delete pCanPotCopy; delete pCanPotCopy1; delete pAlmostDeltaPot; delete pMargUniPot; delete pCloneBigUniPot; delete pBigUnitPot; delete pCanSmallPot; delete pDeltaPot; delete pUnitPot; delete pCloneBigDeltaPot; delete pBigDeltaPot; delete pMargCanPot; delete pSmallCanPot; delete pMargPot; delete pSmallMargPot; delete pCanonicalPot; //delete pShrPot; //delete pEvid; delete pGauCPD; delete pPot; delete pSimDomain; return trsResult( ret, ret == TRS_OK ? "No errors" : "Bad test on SEGaussian"); }
int testSetStatistics() { int ret = TRS_OK; float eps = 0.1f; int seed = pnlTestRandSeed(); pnlSeed( seed ); CBNet *pBNet = pnlExCreateCondGaussArBNet(); CModelDomain *pMD = pBNet->GetModelDomain(); CGraph *pGraph = CGraph::Copy(pBNet->GetGraph()); CBNet *pBNet1 = CBNet::CreateWithRandomMatrices( pGraph, pMD ); pEvidencesVector evidences; int nEvidences = pnlRand( 3000, 4000); pBNet->GenerateSamples( &evidences, nEvidences ); int i; for( i = 0; i < nEvidences; i++) { //evidences[i]->MakeNodeHiddenBySerialNum(0); } CEMLearningEngine *pLearn = CEMLearningEngine::Create(pBNet1); pLearn->SetData( nEvidences, &evidences.front() ); pLearn->SetMaxIterEM(); pLearn->Learn(); for( i = 0; i < pBNet->GetNumberOfFactors(); i++ ) { if( ! pBNet->GetFactor(i)->IsFactorsDistribFunEqual(pBNet1->GetFactor(i), eps)) { ret = TRS_FAIL; pBNet->GetFactor(i)->GetDistribFun()->Dump(); pBNet1->GetFactor(i)->GetDistribFun()->Dump(); } } CDistribFun *pDistr; const CMatrix<float>* pMat; CFactor *pCPD; pDistr = pBNet1->GetFactor(0)->GetDistribFun(); pMat = pDistr->GetStatisticalMatrix(stMatTable); pCPD = pBNet->GetFactor(0); pCPD->SetStatistics(pMat, stMatTable); pCPD->ProcessingStatisticalData(nEvidences); if( ! pCPD->IsFactorsDistribFunEqual(pBNet1->GetFactor(0), 0.0001f) ) { ret = TRS_FAIL; } pDistr = pBNet1->GetFactor(1)->GetDistribFun(); int parentVal; pCPD = pBNet->GetFactor(1); parentVal = 0; pCPD->SetStatistics(pMat, stMatCoeff); pMat = pDistr->GetStatisticalMatrix(stMatMu, &parentVal); pCPD->SetStatistics(pMat, stMatMu, &parentVal); pMat = pDistr->GetStatisticalMatrix(stMatSigma, &parentVal); pCPD->SetStatistics(pMat, stMatSigma, &parentVal); parentVal = 1; pMat = pDistr->GetStatisticalMatrix(stMatMu, &parentVal); pCPD->SetStatistics(pMat, stMatMu, &parentVal); pMat = pDistr->GetStatisticalMatrix(stMatSigma, &parentVal); pCPD->SetStatistics(pMat, stMatSigma, &parentVal); pCPD->ProcessingStatisticalData(nEvidences); if( ! pCPD->IsFactorsDistribFunEqual(pBNet1->GetFactor(1), eps) ) { ret = TRS_FAIL; } for( i = 0; i < nEvidences; i++) { delete evidences[i]; } delete pLearn; delete pBNet1; delete pBNet; return trsResult( ret, ret == TRS_OK ? "No errors" : "Bad test on SetStatistics"); }
/*=================================================== Test body ========================== */ static int fmaFloodFill( void ) { /* Some Variables */ int nx, ny, stepX, stepY, numTest, ROI_offset, mp=0, mp4=0; int i, j, k, ij, it, n, n4, ov, d1, d2, ntest2, nerr, nerr1=0, nerr2=0, nerr3=0, nerr4=0; int step, step4; uchar *pI0, *pI1, *pI2; float* pI3, *pI4; IplImage *I0, *I1, *I2, *I3, *I4; CvSize size; CvPoint seed; CvConnectedComp Comp; CvStatus r; /* Reading test parameters */ trsiRead( &nx, "64", "Image width" ); trsiRead( &stepX, "16", "Seed point horizontal step" ); trsiRead( &numTest, "32", "Number of each seed point tests" ); trsiRead( &ROI_offset, "0", "ROI offset" ); ny = nx; stepY = stepX; n = nx*ny; ntest2 = numTest/2; size.width = nx; size.height = ny; I0 = cvCreateImage( size, IPL_DEPTH_8U, 1 ); I1 = cvCreateImage( size, IPL_DEPTH_8U, 1 ); I2 = cvCreateImage( size, IPL_DEPTH_8U, 1 ); I3 = cvCreateImage( size, IPL_DEPTH_32F,1 ); I4 = cvCreateImage( size, IPL_DEPTH_32F,1 ); pI0 = (uchar*)I0->imageData; pI1 = (uchar*)I1->imageData; pI2 = (uchar*)I2->imageData; pI3 = (float*)I3->imageData; pI4 = (float*)I4->imageData; step = I1->widthStep; step4 = I3->widthStep; n = step*ny; n4 = (step4/4)*ny; if(ROI_offset) { mp = ROI_offset + ROI_offset*step; mp4= ROI_offset + ROI_offset*step4; size.width = nx - 2*ROI_offset; size.height = ny - 2*ROI_offset; I1->roi->xOffset = I1->roi->yOffset = ROI_offset; I1->roi->height = size.height; I1->roi->width = size.width; I3->roi->xOffset = I3->roi->yOffset = ROI_offset; I3->roi->height = size.height; I3->roi->width = size.width; } /* T E S T I N G */ /* Zero interval */ d1 = d2 = 0; ats1bInitRandom ( 0, 1.5, pI0, n ); /*for(i=0;i<n;i++)printf(" %d",pI0[i]);getchar(); */ for(j=0; j<size.height; j=j+stepY) { seed.y = j; for(i=0; i<size.width; i=i+stepX) { seed.x = i; for(k=0; k<n; k++) pI1[k]=pI2[k]=pI0[k]; for(k=0; k<n4; k++) pI3[k]=pI4[k]=(float)pI0[k]; /* 8U */ Counter = 0; X1 = X2 = i; Y1 = Y2 = j; /* Run CVL function */ cvFloodFill ( I1, seed, 10.0, 0.0, 0.0, &Comp ); /* Run test function */ r = _cvFloodFill8uC1R_slow (pI2+mp, step, size, seed, 10, 0, 0 ); /* Comparison */ for(k=0; k<n; k++) if( (pI1[k]-pI2[k]) ) nerr1++; if( Comp.area!=Counter ) nerr1++; if(X1!=Comp.rect.x) nerr1++; if(Y1!=Comp.rect.y) nerr1++; if((X2-X1+1)!=Comp.rect.width) nerr1++; if((Y2-Y1+1)!=Comp.rect.height) nerr1++; /* 32F */ Counter = 0; X1 = X2 = i; Y1 = Y2 = j; /* Run CVL function */ cvFloodFill ( I3, seed, 10.0, 0.0, 0.0, &Comp ); /* Run test function */ r = _cvFloodFill32fC1R_slow (pI4+mp4, step4, size, seed, 10.0, 0.0f, 0.0f ); /* Comparison */ for(k=0; k<n4; k++) if( (pI3[k]-pI4[k]) ) nerr2++; if( Comp.area!=Counter ) nerr2++; if(X1!=Comp.rect.x) nerr2++; if(Y1!=Comp.rect.y) nerr2++; if((X2-X1+1)!=Comp.rect.width) nerr2++; if((Y2-Y1+1)!=Comp.rect.height) nerr2++; if( nerr1 != 0 || nerr2 != 0 ) goto test_end; } } /* Non-zero interval */ ats1bInitRandom ( 0, 254.99, pI0, n ); for(j=1; j<size.height; j=j+stepY) { seed.y = j; for(i=1; i<size.width; i=i+stepX) { ij=i+step*j; ov=pI0[ij+mp]; seed.x = i; for(it=0; it<numTest; it++) { for(k=0; k<n; k++) pI1[k]=pI2[k]=pI0[k]; for(k=0; k<n4; k++) pI3[k]=pI4[k]=(float)pI0[k]; if(it<ntest2) /* sequential increase interval */ { d1=(ov*(it+1))/ntest2; d2=((255-ov)*(it+1))/ntest2; } else /* random interval */ { d1 = (int)atsInitRandom(1.0, 127); d2 = (int)atsInitRandom(1.0, 127); if(it>(3*numTest)/4){d1/=2; d2/=2;} } /* 8U */ Counter = 0; X1 = X2 = i; Y1 = Y2 = j; /* Run CVL function */ cvFloodFill ( I1, seed, 255.0, (double)d1, (double)d2, &Comp ); /* Run test function */ r = _cvFloodFill8uC1R_slow (pI2+mp, step, size, seed, 255, d1, d2 ); /* Comparison */ for(k=0; k<n; k++) if( (pI1[k]-pI2[k]) ) nerr3++; if( Comp.area!=Counter ) nerr3++; if(X1!=Comp.rect.x) nerr3++; if(Y1!=Comp.rect.y) nerr3++; if((X2-X1+1)!=Comp.rect.width) nerr3++; if((Y2-Y1+1)!=Comp.rect.height) nerr3++; /* 32F */ Counter = 0; X1 = X2 = i; Y1 = Y2 = j; /* Run CVL function */ cvFloodFill ( I3, seed, 255.0, (double)d1, (double)d2, &Comp ); /* Run test function */ r = _cvFloodFill32fC1R_slow (pI4+mp4, step4, size, seed, 255.0, (float)d1, (float)d2 ); /* Comparison */ for(k=0; k<n4; k++) if( (pI3[k]-pI4[k]) ) nerr4++; if( Comp.area!=Counter ) nerr4++; if(X1!=Comp.rect.x) nerr4++; if(Y1!=Comp.rect.y) nerr4++; if((X2-X1+1)!=Comp.rect.width) nerr4++; if((Y2-Y1+1)!=Comp.rect.height) nerr4++; if( nerr3 != 0 || nerr4 != 0 ) goto test_end; } } trsWrite(TW_RUN|TW_CON, " %d%% ", ((j+stepY)*100)/size.height); } test_end: cvReleaseImage( &I0 ); cvReleaseImage( &I1 ); cvReleaseImage( &I2 ); cvReleaseImage( &I3 ); cvReleaseImage( &I4 ); nerr = nerr1 + nerr2 + nerr3 + nerr4; printf( "\n zero: %d %d non-zero: %d %d\n", nerr1, nerr2, nerr3, nerr4 ); trsWrite(TW_RUN|TW_CON|TW_SUM, " Nerr = %d\n", nerr); if( nerr == 0 ) return trsResult( TRS_OK, "No errors fixed by this test" ); else return trsResult( TRS_FAIL, "Total fixed %d errors", nerr ); } /*fma*/
/* ///////////////////// moments_test ///////////////////////// */ static int moments_test( void* arg ) { static double weight[] = { 1e6, 1e6, 1e6, /* m00, m10, m01 */ 1e6, 1e6, 1e6, 1, 1, 1, 1, /* m20 - m03 */ 1, 1e-4, 1, 1e-5, 1e-5, 1e-5, 1e-5, /* mu20 - mu03 */ 1, 1, 1, 1, 1, 1, 1 }; /* nu20 - nu03 */ const double success_error_level = 1e-4; int param = (int)arg; int binary = param >= 6; int depth = (param % 6)/2; int channels = (param & 1); int seed = atsGetSeed(); /* position where the maximum error occured */ int merr_w = 0, merr_h = 0, merr_iter = 0, merr_c = 0; /* test parameters */ int w = 0, h = 0, i = 0, c = 0; double max_err = 0.; //int code = TRS_OK; IplROI roi; IplImage *img; AtsRandState rng_state; atsRandInit( &rng_state, 0, 1, seed ); read_moments_params(); if( !(ATS_RANGE( binary, fn_l, fn_h+1 ) && ATS_RANGE( depth, dt_l, dt_h+1 ) && ATS_RANGE( channels, ch_l, ch_h+1 ))) return TRS_UNDEF; depth = depth == 2 ? IPL_DEPTH_32F : depth == 1 ? IPL_DEPTH_8S : IPL_DEPTH_8U; channels = channels*2 + 1; img = atsCreateImage( max_img_size, max_img_size, depth, channels, 0 ); roi.coi = 0; roi.xOffset = roi.yOffset = 0; img->roi = &roi; for( h = min_img_size; h <= max_img_size; ) { for( w = min_img_size; w <= max_img_size; ) { int denom = (w - min_img_size + 1)*(h - min_img_size + 1)*channels; int iters = (base_iters*2 + denom)/(2*denom); roi.width = w; roi.height = h; if( iters < 1 ) iters = 1; for( i = 0; i < iters; i++ ) { switch( depth ) { case IPL_DEPTH_8U: atsRandSetBounds( &rng_state, 0, img8u_range ); break; case IPL_DEPTH_8S: atsRandSetBounds( &rng_state, -img8s_range, img8s_range ); break; case IPL_DEPTH_32F: atsRandSetBounds( &rng_state, -img32f_range, img32f_range ); if( binary ) atsRandSetFloatBits( &rng_state, img32f_bits ); break; } roi.coi = 0; atsFillRandomImageEx( img, &rng_state ); /*iplSet( img, depth == IPL_DEPTH_8S ? 125 : 251 );*/ for( c = 1; c <= channels; c++ ) { double err0 = 0; AtsMomentState astate0, astate1; CvMoments istate; double* a0 = (double*)&astate0; double* a1 = (double*)&astate1; int j; roi.coi = c; /* etalon function */ atsCalcMoments( img, &astate0, binary ); /* cv function */ cvMoments( img, &istate, binary ); atsGetMoments( &istate, &astate1 ); /*iplMoments( img, lstate ); */ /*convert_ipl_to_ats( lstate, &astate1 ); */ for( j = 0; j < sizeof(astate0)/sizeof(double); j++ ) { double err = rel_err( a0[j], a1[j] )*weight[j]; err0 = MAX( err0, err ); } if( err0 > max_err ) { merr_w = w; merr_h = h; merr_iter = i; merr_c = c; max_err = err0; if( max_err > success_error_level ) goto test_exit; } } } ATS_INCREASE( w, img_size_delta_type, img_size_delta ); } /* end of the loop by w */ ATS_INCREASE( h, img_size_delta_type, img_size_delta ); } /* end of the loop by h */ test_exit: img->roi = 0; iplDeallocate( img, IPL_IMAGE_ALL ); //if( code == TRS_OK ) { trsWrite( ATS_LST, "Max err is %g at w = %d, h = %d, " "iter = %d, c = %d, seed = %08x", max_err, merr_w, merr_h, merr_iter, merr_c, seed ); return max_err <= success_error_level ? trsResult( TRS_OK, "No errors" ) : trsResult( TRS_FAIL, "Bad accuracy" ); } /*else { trsWrite( ATS_LST, "Fatal error at w = %d, h = %d, " "iter = %d, c = %d, seed = %08x", w, h, i, c, seed ); return trsResult( TRS_FAIL, "Function returns error code" ); }*/ }
int testRandomFactors() { int ret = TRS_OK; int nnodes = 0; int i; while(nnodes <= 0) { trsiRead( &nnodes, "5", "Number of nodes in Model" ); } //create node types int seed1 = pnlTestRandSeed(); //create string to display the value char *value = new char[20]; #if 0 value = _itoa(seed1, value, 10); #else sprintf( value, "%d", seed1 ); #endif trsiRead(&seed1, value, "Seed for srand to define NodeTypes etc."); delete []value; trsWrite(TW_CON|TW_RUN|TW_DEBUG|TW_LST, "seed for rand = %d\n", seed1); //create 2 node types and model domain for them nodeTypeVector modelNodeType; modelNodeType.resize(2); modelNodeType[0] = CNodeType( 1, 4 ); modelNodeType[1] = CNodeType( 1, 3 ); intVector NodeAssociat; NodeAssociat.assign(nnodes, 0); for( i = 0; i < nnodes; i++ ) { float rand = pnlRand( 0.0f, 1.0f ); if( rand < 0.5f ) { NodeAssociat[i] = 1; } } CModelDomain* pMDDiscr = CModelDomain::Create( modelNodeType, NodeAssociat ); //create random graph - number of nodes for every node is rand too int lowBorder = nnodes - 1; int upperBorder = int((nnodes * (nnodes - 1))/2); int numEdges = pnlRand( lowBorder, upperBorder ); mark: CGraph* pGraph = tCreateRandomDAG( nnodes, numEdges, 1 ); if ( pGraph->NumberOfConnectivityComponents() != 1 ) { delete pGraph; goto mark; } CBNet* pDiscrBNet = CBNet::CreateWithRandomMatrices( pGraph, pMDDiscr ); //start jtree inference just for checking //the model is valid for inference and all operations can be made CEvidence* pDiscrEmptyEvid = CEvidence::Create( pMDDiscr, 0, NULL, valueVector() ); CJtreeInfEngine* pDiscrInf = CJtreeInfEngine::Create( pDiscrBNet ); pDiscrInf->EnterEvidence( pDiscrEmptyEvid ); const CPotential* pot = NULL; for( i = 0; i < nnodes; i++ ) { intVector domain; pDiscrBNet->GetFactor(i)->GetDomain( &domain ); pDiscrInf->MarginalNodes( &domain.front(), domain.size() ); pot = pDiscrInf->GetQueryJPD(); } //make copy of Graph for using with other models pGraph = CGraph::Copy( pDiscrBNet->GetGraph() ); delete pDiscrInf; delete pDiscrBNet; delete pDiscrEmptyEvid; delete pMDDiscr; //create gaussian model domain modelNodeType[0] = CNodeType( 0, 4 ); modelNodeType[1] = CNodeType( 0, 2 ); CModelDomain* pMDCont = CModelDomain::Create( modelNodeType, NodeAssociat ); CBNet* pContBNet = CBNet::CreateWithRandomMatrices( pGraph, pMDCont ); CEvidence* pContEmptyEvid = CEvidence::Create( pMDCont, 0, NULL, valueVector() ); CNaiveInfEngine* pContInf = CNaiveInfEngine::Create( pContBNet ); pContInf->EnterEvidence( pContEmptyEvid ); for( i = 0; i < nnodes; i++ ) { intVector domain; pContBNet->GetFactor(i)->GetDomain( &domain ); pContInf->MarginalNodes( &domain.front(), domain.size() ); pot = pContInf->GetQueryJPD(); } pGraph = CGraph::Copy(pContBNet->GetGraph()); delete pContInf; delete pContBNet; delete pContEmptyEvid; delete pMDCont; //find the node that haven't any parents //and change its node type for it to create Conditional Gaussian CPD int numOfNodeWithoutParents = -1; intVector parents; parents.reserve(nnodes); for( i = 0; i < nnodes; i++ ) { pGraph->GetParents( i, &parents ); if( parents.size() == 0 ) { numOfNodeWithoutParents = i; break; } } //change node type of this node, make it discrete CNodeType ntTab = CNodeType( 1,4 ); modelNodeType.push_back( ntTab ); NodeAssociat[numOfNodeWithoutParents] = 2; //need to change this model domain CModelDomain* pMDCondGau = CModelDomain::Create( modelNodeType, NodeAssociat ); CBNet* pCondGauBNet = CBNet::CreateWithRandomMatrices( pGraph, pMDCondGau ); //need to create evidence for all gaussian nodes intVector obsNodes; obsNodes.reserve(nnodes); int numGauVals = 0; for( i = 0; i < numOfNodeWithoutParents; i++ ) { int GauSize = pMDCondGau->GetVariableType(i)->GetNodeSize(); numGauVals += GauSize; obsNodes.push_back( i ); } for( i = numOfNodeWithoutParents + 1; i < nnodes; i++ ) { int GauSize = pMDCondGau->GetVariableType(i)->GetNodeSize(); numGauVals += GauSize; obsNodes.push_back( i ); } valueVector obsGauVals; obsGauVals.resize( numGauVals ); floatVector obsGauValsFl; obsGauValsFl.resize( numGauVals); pnlRand( numGauVals, &obsGauValsFl.front(), -3.0f, 3.0f); //fill the valueVector for( i = 0; i < numGauVals; i++ ) { obsGauVals[i].SetFlt(obsGauValsFl[i]); } CEvidence* pCondGauEvid = CEvidence::Create( pMDCondGau, obsNodes, obsGauVals ); CJtreeInfEngine* pCondGauInf = CJtreeInfEngine::Create( pCondGauBNet ); pCondGauInf->EnterEvidence( pCondGauEvid ); pCondGauInf->MarginalNodes( &numOfNodeWithoutParents, 1 ); pot = pCondGauInf->GetQueryJPD(); pot->Dump(); delete pCondGauInf; delete pCondGauBNet; delete pCondGauEvid; delete pMDCondGau; return trsResult( ret, ret == TRS_OK ? "No errors" : "Bad test on RandomFactors"); }
template <class Val, class Idx> static int foaCvTree( Val, Idx ) { CvTree<Val, Idx> tree; int res = TRS_OK; /* Check adding new node (operator[]) */ for( Idx i = 0; i < hsize; i++ ) { Idx num = (Idx)atsInitRandom( 0, hsize ); tree[num] = (Val)i; if( check_direct( tree.get_root() ) != TRS_OK || check_balance( tree.get_root() ) < 0 ) { return trsResult( TRS_FAIL, "Error adding new node" ); } } /* Check getting node */ for( i = 0; i < hsize; i++ ) tree[i] = (Val)i; for( i = 0; i < hsize; i++ ) if( tree[i] != (Val)i ) { trsWrite( ATS_CON | ATS_LST, "error operator[] (get node)\n" ); res = TRS_FAIL; break; } for( i = 0; i < hsize; i++ ) if( tree.query(i) != (Val)i ) { trsWrite( ATS_CON | ATS_LST, "error query() function\n" ); res = TRS_FAIL; break; } tree.clear(); for( i = 0; i < hsize; i++ ) tree[i] = (Val)i; for( i = 0; i < hsize; i++ ) { Idx num = (Idx)atsInitRandom( 0, hsize ); tree.remove( num ); if( check_direct( tree.get_root() ) != TRS_OK || check_balance( tree.get_root() ) < 0 ) { return trsResult( TRS_FAIL, "Error removing node" ); } if( tree.query( num ) != 0 ) { trsWrite( ATS_CON | ATS_LST, "Error remove() function (not null) \n" ); res = TRS_FAIL; } } for( i = 0; i < hsize / 2; i++ ) { tree.remove( i ); if( check_direct( tree.get_root() ) != TRS_OK || check_balance( tree.get_root() ) < 0 ) { return trsResult( TRS_FAIL, "Error removing node" ); } if( tree.query( i ) != 0 ) { trsWrite( ATS_CON | ATS_LST, "Error remove() function (not null) \n" ); res = TRS_FAIL; } } for( i = hsize; i > hsize / 2 - 1; i-- ) { tree.remove( i ); if( check_direct( tree.get_root() ) != TRS_OK || check_balance( tree.get_root() ) < 0 ) { return trsResult( TRS_FAIL, "Error removing node" ); } if( tree.query( i ) != 0 ) { trsWrite( ATS_CON | ATS_LST, "Error remove() function (not null) \n" ); res = TRS_FAIL; } } tree.clear(); for( i = 0; i < hsize; i++ ) tree[i] = (Val)(i + 1); CvTree<Val, Idx>::iterator iterator = tree.begin(); if( *iterator != 1 ) { trsWrite( ATS_CON | ATS_LST, "Wrong begin() function (bad val)\n"); res = TRS_FAIL; } if( iterator.get_idx() != 0 ) { trsWrite( ATS_CON | ATS_LST, "Wrong begin() function (bad idx)\n"); res = TRS_FAIL; } iterator = tree.end(); if( *iterator != hsize ) { trsWrite( ATS_CON | ATS_LST, "Wrong end() function (bad val)\n"); res = TRS_FAIL; } if( iterator.get_idx() != hsize - 1 ) { trsWrite( ATS_CON | ATS_LST, "Wrong end() function (bad idx)\n"); res = TRS_FAIL; } CvTree<Val, Idx> empty; empty = tree; CvTree<Val, Idx>::iterator beg1 = empty.begin(); CvTree<Val, Idx>::iterator beg2 = tree.begin(); CvTree<Val, Idx>::iterator end = tree.begin(); while( beg2 != end ) { if( *beg2 != *beg1 ) { res = TRS_FAIL; trsWrite( ATS_CON | ATS_LST, "Wrong operator= (bad value)\n" ); break; } if( beg2.get_idx() != beg1.get_idx() ) { res = TRS_FAIL; trsWrite( ATS_CON | ATS_LST, "Wrong operator= (bad idx)\n" ); break; } beg1++; beg2++; } if( *beg2 != *beg1 ) { res = TRS_FAIL; trsWrite( ATS_CON | ATS_LST, "Wrong operator= (bad value)\n" ); } if( beg2.get_idx() != beg1.get_idx() ) { res = TRS_FAIL; trsWrite( ATS_CON | ATS_LST, "Wrong operator= (bad idx)\n" ); } return res; }
int testBayesLearningEngine() { int ret = TRS_OK; int i, j; const int nnodes = 4;//Number of nodes int numNt = 1;//number of Node Types float eps = -1.0f; while( eps <= 0) { trssRead( &eps, "0.01f", "accuracy in test"); } CNodeType *nodeTypes = new CNodeType [numNt]; for( i=0; i < numNt; i++ ) { nodeTypes[i] = CNodeType(1,2);//all nodes are discrete and binary } int nodeAssociation[] = {0, 0, 0, 0}; int obs_nodes[] = { 0, 1, 2, 3 }; int numOfNeigh[] = { 2, 2, 2, 2}; int neigh0[] = { 1, 2 }; int neigh1[] = { 0, 3 }; int neigh2[] = { 0, 3 }; int neigh3[] = { 1, 2 }; ENeighborType orient0[] = { ntChild, ntChild }; ENeighborType orient1[] = { ntParent, ntChild }; ENeighborType orient2[] = { ntParent, ntChild }; ENeighborType orient3[] = { ntParent, ntParent }; int *neigh[] = { neigh0, neigh1, neigh2, neigh3 }; ENeighborType *orient[] = { orient0, orient1, orient2, orient3 }; float prior0[] = { 1.f, 1.f }; float prior1[] = { 1.f, 1.f, 1.f, 1.f }; float prior2[] = { 1.f, 1.f, 1.f, 1.f }; float prior3[] = { 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f }; float* priors[] = { prior0,prior1,prior2,prior3 }; float zero_array[] = { 1,1,1,1, 1,1,1,1 }; float test_data0[] = { 0.636364f, 0.363636f }; float test_data1[] = { 0.6f, 0.4f, 0.777778f, 0.222222f }; float test_data2[] = { 0.866667f, 0.133333f, 0.111111f, 0.888889f }; float test_data3[] = { 0.888889f, 0.111111f, 0.111111f, 0.888889f, 0.142857f, 0.857143f, 0.333333f, 0.666667f }; float* test_data_first[] = { test_data0, test_data1, test_data2, test_data3 }; float test_data4[] = { 0.519231f, 0.480769f }; float test_data5[] = { 0.571429f, 0.428571f, 0.884615f, 0.115385f }; float test_data6[] = { 0.857143f, 0.142857f, 0.0769231f, 0.923077f }; float test_data7[] = { 0.937500f, 0.0625000f, 0.12f, 0.88f, 0.166667f, 0.833333f, 0.2f, 0.8f }; float* test_data_second[] = { test_data4, test_data5, test_data6, test_data7 }; CGraph* Graph = CGraph::Create( nnodes, numOfNeigh, neigh, orient); CBNet *myBNet = CBNet::Create(nnodes, numNt, nodeTypes, nodeAssociation, Graph ); myBNet->AllocFactors(); for ( int node = 0; node < nnodes; node++ ) { myBNet->AllocFactor( node ); //allocate empty CPT matrix, it needs to be allocated even if //we are going to learn train it. (myBNet->GetFactor( node ))->AllocMatrix( zero_array, matTable ); //allocate prior matrices (myBNet->GetFactor( node ))->AllocMatrix( priors[node], matDirichlet ); static_cast<CCPD *>(myBNet->GetFactor( node ))->NormalizeCPD(); } /////////////////////////////////////////////////////////////// //Reading cases from disk FILE *fp; const int nEv = 50; CEvidence **m_pEv; m_pEv = new CEvidence *[nEv]; std::vector<valueVector> Evidence(nEv); for( int ev = 0; ev < nEv; ev++) { Evidence[ev].resize(nnodes); } int simbol; char *argv = "../c_pgmtk/tests/testdata/cases1"; fp = fopen(argv, "r"); if(!fp) { argv = "../testdata/cases1"; if ((fp = fopen(argv, "r")) == NULL) { printf( "can't open file %s\n", argv ); ret = TRS_FAIL; return trsResult( ret, ret == TRS_OK ? "No errors" : "Bad test: no file with cases"); } } if (fp) { i = 0; j = 0; while( i < nEv) { simbol = getc( fp ); if( isdigit( simbol ) ) { (Evidence[i])[j].SetInt(simbol - '0'); j++; if( ( j - nnodes ) == 0 ) { i++; j = 0; } } } } for( i = 0; i < nEv; i++ ) { m_pEv[i] = CEvidence::Create(myBNet->GetModelDomain(), nnodes, obs_nodes, Evidence[i]); } //create bayesin learning engine CBayesLearningEngine *pLearn = CBayesLearningEngine::Create(myBNet); //Learn only portion of evidences pLearn->SetData(20, m_pEv); pLearn ->Learn(); /////////////////////////////////////////////////////////////////////////////// CNumericDenseMatrix<float> *pMatrix; int length = 0; const float *output; for ( i = 0; i < nnodes; i++) { pMatrix = static_cast<CNumericDenseMatrix<float>*>(myBNet-> GetFactor(i)->GetMatrix(matTable)); pMatrix->GetRawData(&length, &output); for (j = 0; j < length; j++) { if( fabs(output[j] - test_data_first[i][j] ) > eps ) { ret = TRS_FAIL; return trsResult( ret, ret == TRS_OK ? "No errors" : "Bad test on BayesLearningEngine"); break; } } } //Learn second portion of evidences pLearn->AppendData(20, m_pEv+20); pLearn->AppendData(10, m_pEv+40); pLearn ->Learn(); //check second portion for ( i = 0; i < nnodes; i++) { pMatrix = static_cast<CNumericDenseMatrix<float>*>(myBNet-> GetFactor(i)->GetMatrix(matTable)); pMatrix->GetRawData(&length, &output); for (j = 0; j < length; j++) { if( fabs(output[j] - test_data_second[i][j] ) > eps ) { ret = TRS_FAIL; return trsResult( ret, ret == TRS_OK ? "No errors" : "Bad test on BayesLearningEngine"); break; } } } for( i = 0; i < nEv; i++ ) { delete (m_pEv[i]); } delete []m_pEv; delete (pLearn); delete (myBNet); delete [](nodeTypes); fclose(fp); return trsResult( ret, ret == TRS_OK ? "No errors" : "Bad test on BayesLearningEngine"); }
int testMarginalize() { int ret = TRS_OK; const int nnodes = 4; const int numnt = 2; intVector nodeAssociation = intVector( nnodes ); nodeTypeVector nodeTypes; nodeTypes.assign( numnt, CNodeType() ); nodeTypes[0].SetType(1, 2); nodeTypes[1].SetType(1, 3); nodeAssociation[0] = 0; nodeAssociation[1] = 0; nodeAssociation[2] = 0; nodeAssociation[3] = 1; CModelDomain* pMD = CModelDomain::Create( nodeTypes, nodeAssociation ); int *domain = (int*)trsGuardcAlloc( nnodes, sizeof(int) ); domain[0]=0; domain[1]=1; domain[2]=2; domain[3]=3; float* data = (float*)trsGuardcAlloc( 24, sizeof(float) ); for (int i0=0; i0<24; data[i0]=i0*0.01f, i0++){}; EMatrixType mType=matTable; CTabularPotential *pxParam1=CTabularPotential::Create( domain, nnodes, pMD); pxParam1->AllocMatrix(data, mType); pxParam1->Dump(); int domSize=2; int *pSmallDom = (int*)trsGuardcAlloc( domSize, sizeof(int) ); pSmallDom[0] = 1; pSmallDom[1] = 3; CFactor *pxParam2=pxParam1->Marginalize(pSmallDom, domSize, 0); // CFactor *pxParam2=pxParam1->Marginalize(pSmallDom, 0, 0); const CNumericDenseMatrix<float> *pxMatrix = static_cast< CNumericDenseMatrix<float>*>(pxParam2->GetMatrix(mType)); const float* dmatrix1; // const float* dmatrix1 = (const float*)trsGuardcAlloc( 1, sizeof(float) ); int n; pxMatrix->GetRawData(&n, &dmatrix1); float *testdata1=new float[6]; testdata1[0]=0.30f; testdata1[1]=0.34f; testdata1[2]=0.38f; testdata1[3]=0.54f; testdata1[4]=0.58f; testdata1[5]=0.62f; for(int i1 = 0; i1 < n; i1++) { // Test the values... //printf("%d %f %f", i1, dmatrix1[i1], testdata1[i1] ); if(fabs(testdata1[i1] - dmatrix1[i1]) > eps) { return trsResult(TRS_FAIL, "data doesn't agree at max=0"); } } CFactor *pxParam3=pxParam1->Marginalize(pSmallDom, domSize, 1); const CNumericDenseMatrix<float> *pxMatrix1 = static_cast< CNumericDenseMatrix<float>*>(pxParam3->GetMatrix(mType)); const float *dmatrix2; pxMatrix1->GetRawData(&n, &dmatrix2); float *testdata2 = new float[6]; testdata2[0]=0.15f; testdata2[1]=0.16f; testdata2[2]=0.17f; testdata2[3]=0.21f; testdata2[4]=0.22f; testdata2[5]=0.23f; for(int i2 = 0; i2 < 6; i2++) { // Test the values... // printf("%d %f %f", i2, dmatrix2[i2], testdata2[i2]); if( fabs(dmatrix2[i2] - testdata2[i2]) > eps) { return trsResult(TRS_FAIL, "data doesn't agree at max=1"); } } //we can check some methods of Tabular CTabularPotential* pUniPot = CTabularPotential::CreateUnitFunctionDistribution( domain, nnodes, pMD, 1 ); CTabularPotential* pCopyUniPot = static_cast<CTabularPotential*>( pUniPot->CloneWithSharedMatrices()); CTabularPotential* pNormUniPot = static_cast<CTabularPotential*>( pUniPot->GetNormalized()); pUniPot->Dump(); pUniPot->ConvertToDense(); pUniPot->ConvertToSparse(); (*pCopyUniPot) = (*pCopyUniPot); pxParam1->AllocMatrix(data, matTable); intVector indices; indices.assign(4,0); pxParam1->GetMatrix(matTable)->SetElementByIndexes(-1.0f,&indices.front()); //we've just damaged the potential std::string s; if( pxParam1->IsValid(&s) ) { ret = TRS_FAIL; } else { std::cout<<s<<std::endl; } intVector pos; floatVector vals; intVector offsets; pUniPot->GetMultipliedDelta(&pos, &vals, &offsets); delete pNormUniPot; delete pCopyUniPot; delete pUniPot; delete pxParam1; delete pxParam2; delete pxParam3; delete testdata1; delete testdata2; delete pMD; int data_memory_flag = trsGuardCheck( data ); int domain_memory_flag = trsGuardCheck( domain ); int Smalldomain_memory_flag = trsGuardCheck( pSmallDom ); trsGuardFree( data ); trsGuardFree( domain ); trsGuardFree( pSmallDom ); if( data_memory_flag || domain_memory_flag || Smalldomain_memory_flag ) { return trsResult( TRS_FAIL, "Dirty memory"); } return trsResult( ret, ret == TRS_OK ? "No errors" : "Marginalize FAILED"); }
int testShrinkObservedNodes() { int i/*,j*/; int ret = TRS_OK; /*prepare to read the values from console*/ EDistributionType dt; int disType = -1; EFactorType pt; int paramType = -1; /*read int disType corresponding DistributionType*/ while((disType<0)||(disType>0))/*now we have only Tabulars&Gaussian*/ { trsiRead( &disType, "0", "DistributionType"); } /*read int paramType corresponding FactorType*/ while((paramType<0)||(paramType>2)) { trsiRead( ¶mType, "0", "FactorType"); } dt = EDistributionType(disType); pt = EFactorType(paramType); int numberOfNodes = 0; /*read number of nodes in Factor domain*/ while(numberOfNodes<=0) { trsiRead( &numberOfNodes, "1", "Number of Nodes in domain"); } int numNodeTypes = 0; /*read number of node types in model*/ while(numNodeTypes<=0) { trsiRead( &numNodeTypes, "1", "Number of node types in Domain"); } //int seed1 = pnlTestRandSeed()/*%100000*/; /*create string to display the value*/ /* char *value = new char[20]; value = _itoa(seed1, value, 10); trsiRead(&seed1, value, "Seed for srand to define NodeTypes etc."); delete []value; trsWrite(TW_CON|TW_RUN|TW_DEBUG|TW_LST, "seed for rand = %d\n", seed1); int *domain = (int *)trsGuardcAlloc(numberOfNodes, sizeof(int)); CNodeType * allNodeTypes = (CNodeType*)trsGuardcAlloc(numNodeTypes, sizeof(CNodeType)); //To generate the NodeTypes we use rand()% and creates only Tabular now for(i=0; i<numNodeTypes; i++) { allNodeTypes[i] = CNodeType(1, 1+rand()%(numNodeTypes+3)); } */ /*load data for parameter::ShrinkObservedNodes from console*/ intVector domain; domain.assign( numberOfNodes, 0 ); nodeTypeVector allNodeTypes; allNodeTypes.assign( numNodeTypes, CNodeType() ); /*read node types*/ for(i=0; i < numNodeTypes; i++) { int IsDiscrete = -1; int NodeSize = -1; while((IsDiscrete<0)||(IsDiscrete>1)) /*now we have tabular & Gaussian nodes!! */ trsiRead(&IsDiscrete, "1", "Is the node discrete?"); while(NodeSize<0) trsiRead(&NodeSize, "2", "NodeSize of node"); allNodeTypes[i] = CNodeType( IsDiscrete != 0, NodeSize ); } const CNodeType **nodeTypesOfDomain = (const CNodeType**) trsGuardcAlloc(numberOfNodes, sizeof(CNodeType*)); int numData = 1; int *Ranges = (int*)trsGuardcAlloc(numberOfNodes, sizeof(int)); /*associate nodes to node types*/ for(i=0; i<numberOfNodes; i++) { domain[i] = i; int nodeAssociationToNodeType = -1; while((nodeAssociationToNodeType<0)||(nodeAssociationToNodeType>= numNodeTypes)) trsiRead(&nodeAssociationToNodeType, "0", "node i has type nodeAssociationToNodeType"); nodeTypesOfDomain[i] = &allNodeTypes[nodeAssociationToNodeType]; // nodeTypesOfDomain[i] = &allNodeTypes[rand()%numNodeTypes]; Ranges[i] = nodeTypesOfDomain[i]->GetNodeSize(); numData=numData*Ranges[i]; } CModelDomain* pMD = CModelDomain::Create( allNodeTypes, domain ); /*create factor according all information*/ CFactor *pMyParam = NULL; float *data = (float *)trsGuardcAlloc(numData, sizeof(float)); char *stringVal;/* = (char*)trsGuardcAlloc(50, sizeof(char));*/ double val=0; /*read the values from console*/ if(pt == ftPotential) { pMyParam = CTabularPotential::Create( &domain.front(), numberOfNodes, pMD ); /*here we can create data by multiply on 0.1 - numbers are nonnormalized*/ for(i=0; i<numData; i++) { val = 0.1*i; stringVal = trsDouble(val); trsdRead(&val, stringVal, "value of i's data position"); data[i] = (float)val; //data[i] = (float)rand()/1000; } } else { /*we can only read data from console - it must be normalized!! (according their dimensions) - or we can normalize it by function!*/ if(pt == ftCPD) pMyParam = CTabularCPD::Create( &domain.front(), numberOfNodes, pMD ); for(i=0; i<numData; i++) { val = -1; while((val<0)||(val>1)) { trsdRead(&val, "-1", "value of (2*i)'s data position"); } data[i] = (float)val; } } //trsWrite(TW_CON|TW_RUN|TW_DEBUG|TW_LST, "data for Factor = %d\n", data[i]); pMyParam->AllocMatrix(data,matTable); int nObsNodes = 0; /*rand()%numberOfNodes;*/ while((nObsNodes<=0)||(nObsNodes>numberOfNodes)) { trsiRead(&nObsNodes, "1", "Number of Observed Nodes"); } intVector myHelpForEvidence = intVector(domain.begin(), domain.end() ); int *ObsNodes = (int *)trsGuardcAlloc(nObsNodes, sizeof(int)); valueVector TabularValues; TabularValues.assign( nObsNodes, (Value)0 ); char *strVal; for(i=0; i<nObsNodes; i++) { //fixme - we need to have noncopy only different ObsNodes /* j = rand()%(numberOfNodes-i);*/ int numberOfObsNode = -1; strVal = trsInt(i); intVector::iterator j = std::find( myHelpForEvidence.begin(), myHelpForEvidence.end(), numberOfObsNode ); while((numberOfObsNode<0)||(numberOfObsNode>numberOfNodes)|| (j==myHelpForEvidence.end())) { trsiRead(&numberOfObsNode, strVal,"Number of i's observed node"); j = std::find(myHelpForEvidence.begin(), myHelpForEvidence.end(), numberOfObsNode); } //ObsNodes[i] = myHelpForEvidence[j]; myHelpForEvidence.erase( j ); ObsNodes[i] = numberOfObsNode; int valueOfNode = -1; int maxValue = (*nodeTypesOfDomain[ObsNodes[i]]).GetNodeSize(); while((valueOfNode<0)||(valueOfNode>=maxValue)) { trsiRead(&valueOfNode,"0","this is i's observed node value"); } TabularValues[i].SetInt(valueOfNode); /*rand()%((*nodeTypesOfDomain[ObsNodes[i]]).pgmGetNodeSize());*/ } CEvidence* pEvidence = CEvidence::Create( pMD, nObsNodes, ObsNodes, TabularValues ); myHelpForEvidence.clear(); CNodeType *ObservedNodeType = (CNodeType*)trsGuardcAlloc(1, sizeof(CNodeType)); *ObservedNodeType = CNodeType(1,1); CPotential *myTakedInFactor = static_cast<CPotential*>(pMyParam)->ShrinkObservedNodes(pEvidence); const int *myfactorDomain; int factorDomSize ; myTakedInFactor->GetDomain(&factorDomSize, &myfactorDomain); #if 0 CNumericDenseMatrix<float> *mySmallMatrix = static_cast< CNumericDenseMatrix<float>*>(myTakedInFactor->GetMatrix(matTable)); int n; const float* mySmallData; mySmallMatrix->GetRawData(&n, &mySmallData); int nDims; // = mySmallMatrix->GetNumberDims(); const int * mySmallRanges; mySmallMatrix->GetRanges(&nDims, &mySmallRanges); if(nDims!=numberOfNodes) { ret = TRS_FAIL; trsWrite(TW_CON|TW_RUN|TW_DEBUG|TW_LST, "nDims = %d\n", nDims); } else { int numSmallData = 1; for(i=0; i<nDims; i++) { numSmallData = numSmallData*mySmallRanges[i]; trsWrite(TW_CON|TW_RUN|TW_DEBUG|TW_LST, "Range[%d] = %d\n", i, mySmallRanges[i]); } for(i=0; i<numSmallData; i++) { trsWrite(TW_CON|TW_RUN|TW_DEBUG|TW_LST, "mySmallData[%d] = %f ", i, mySmallData[i]); } } #endif //getchar(); delete(myTakedInFactor); delete (pMyParam); delete pMD; //test gaussian parameter nodeTypeVector nTypes; nTypes.assign( 2, CNodeType() ); nTypes[0] = CNodeType( 0, 2 ); nTypes[1] = CNodeType( 0,1 ); intVector domn = intVector(3,0); domn[1] = 1; domn[2] = 1; CModelDomain* pMD1 = CModelDomain::Create( nTypes, domn ); domn[2] = 2; CPotential *BigFactor = CGaussianPotential::CreateUnitFunctionDistribution( &domn.front(), domn.size(), pMD1,0 ); float mean[] = { 1.0f, 3.2f}; CPotential *SmallDelta = CGaussianPotential::CreateDeltaFunction( &domn.front(), 1, pMD1, mean, 1 ); domn.resize( 2 ); domn[0] = 1; domn[1] = 2; CPotential *SmallFunct = CGaussianPotential::Create( &domn.front(), domn.size(), pMD1); float datH[] = { 1.1f, 2.2f, 3.3f }; float datK[] = { 1.2f, 2.3f, 2.3f, 3.4f, 5.6f, 6.7f, 3.4f, 6.7f, 9.0f }; SmallFunct->AllocMatrix( datH, matH ); SmallFunct->AllocMatrix( datK, matK ); static_cast<CGaussianPotential*>(SmallFunct)->SetCoefficient( 0.2f, 1 ); CPotential* multFact = BigFactor->Multiply( SmallDelta ); CPotential* nextMultFact = multFact->Multiply( SmallFunct ); domn[0] = 0; domn[1] = 1; CPotential *marginalized = static_cast<CPotential*>(nextMultFact->Marginalize( &domn.front(), domn.size() )); int isSpecific = marginalized->IsDistributionSpecific(); if( isSpecific ) { trsWrite(TW_CON|TW_RUN|TW_DEBUG|TW_LST, "\nGaussian Distribution is specific"); } delete BigFactor; delete SmallFunct; delete SmallDelta; delete pMD1; int ranges_memory_flag = trsGuardCheck(Ranges); int data_memory_flag = trsGuardCheck(data); int nodeTypesOfDomain_mem_b = trsGuardCheck(nodeTypesOfDomain); int ObsNodes_mem_b = trsGuardCheck(ObsNodes); int ObsNodeType_mem_b = trsGuardCheck(ObservedNodeType); if(((ranges_memory_flag)||(data_memory_flag)|| (nodeTypesOfDomain_mem_b)|| (ObsNodes_mem_b)||(ObsNodeType_mem_b))) { ret = TRS_FAIL; return trsResult( ret, ret == TRS_OK ? "No errors" : "Bad test on ShrinkObservedNodes Method - memory"); } else { trsGuardFree(ObservedNodeType); trsGuardFree(ObsNodes); trsGuardFree(nodeTypesOfDomain); trsGuardFree(data); trsGuardFree(Ranges); } return trsResult( ret, ret == TRS_OK ? "No errors" : "Bad test on ShrinkObservedNodes Method"); }
int testMultiplyMatrix() { int ret = TRS_OK; int i; #if 0 int range_max=5; int seed1 = pnlTestRandSeed(); /*create string to display the value*/ char *value = new char[20]; value = _itoa(seed1, value, 10); trsiRead(&seed1, value, "Seed for srand to define NodeTypes etc."); delete []value; trsWrite(TW_CON|TW_RUN|TW_DEBUG|TW_LST, "seed for rand = %d\n", seed1); srand ((unsigned int)seed1); int Nrow1 = 1+rand()%((int) range_max); int Ncol1 = 1+rand()%((int) range_max); int Nrow2=Ncol1; int Ncol2=1+rand()%((int) range_max); #endif int Nrow1 = 4; int Ncol1 = 6; int Nrow2=Ncol1; int Ncol2=5; int* ranges1 = (int*)trsGuardcAlloc( 2, sizeof(int) ); int* ranges2 = (int*)trsGuardcAlloc( 2, sizeof(int) ); ranges1[0]=Nrow1; ranges1[1]=Ncol1; ranges2[0]=Nrow2; ranges2[1]=Ncol2; int data_length1=ranges1[0]*ranges1[1]; int data_length2=ranges2[0]*ranges2[1]; float* data1 = (float*)trsGuardcAlloc( data_length1, sizeof(float) ); float* data2 = (float*)trsGuardcAlloc( data_length2, sizeof(float) ); for (i = 0; i < data_length1; data1[i] = (div(i,Ncol1).quot+1)*1.0f, i++); for (i = 0; i < data_length2; data2[i] = (div(i,Ncol2).rem+1)*0.1f, i++); C2DNumericDenseMatrix<float>* m1 = C2DNumericDenseMatrix<float>::Create( ranges1, data1); C2DNumericDenseMatrix<float>* m2 = C2DNumericDenseMatrix<float>::Create( ranges2, data2); C2DNumericDenseMatrix<float>* m3 = pnlMultiply(m1,m2,0); int data_length3; const float *m3data; m3->GetRawData(&data_length3, &m3data); float *testdata0=new float[data_length3]; int currow;int curcol; for (i = 0; i < data_length3; i++) { currow=div(i,Ncol2).quot+1; curcol=div(i,Ncol2).rem+1; testdata0[i] =currow*curcol*Ncol1*0.1f; } for(i = 0; i < data_length3; i++) { // Test the values... //printf("%3d %4.2f %4.2f\n",i, testdata0[i], m3data[i]); if(m3data[i] - testdata0[i]>eps) { return trsResult(TRS_FAIL, "data doesn't agree at max=0, preorder"); } } delete m3; m3 = pnlMultiply(m2,m1,0); m3->GetRawData(&data_length3, &m3data); for(i = 0; i < data_length3; i++) { // Test the values... //printf("%3d %4.2f %4.2f\n",i, testdata0[i], m3data[i]); if(m3data[i] - testdata0[i]>eps) { return trsResult(TRS_FAIL, "data doesn't agree at max=0, postorder"); } } #if 0 float *data4 = new float[data_length2]; for (i=0;i<data_length2;i++) { currow=div(i,Ncol2).quot+1; curcol=div(i,Ncol2).rem+1; data4[i]=currow*(1e+curcol-3f); } CNumericDenseMatrix<float> * m4=CNumericDenseMatrix<float>::Create(2,ranges2, data4); #endif delete m3; m3 = pnlMultiply(m1,m2,1); m3->GetRawData(&data_length3, &m3data); float *testdata1=new float[data_length3]; for (i = 0; i < data_length3; i++) { int currow=div(i,Ncol2).quot+1; int curcol=div(i,Ncol2).rem+1; testdata1[i] =currow*curcol*0.1f; } for(i = 0; i < data_length3; i++) { // Test the values... //printf("%3d %4.2f %4.2f\n",i, testdata1[i], m3data[i]); if(m3data[i] - testdata1[i] > eps) { return trsResult(TRS_FAIL, "data doesn't agree at max=1, preorder"); } } delete m3; m3 = pnlMultiply(m2,m1,1); m3->GetRawData(&data_length3, &m3data); for(i = 0; i < data_length3; i++) { // Test the values... //printf("%3d %4.2f %4.2f\n",i, testdata1[i], m3data[i]); if(m3data[i] - testdata1[i]>eps) { return trsResult(TRS_FAIL, "data doesn't agree at max=1, postorder"); } } int ranges1_memory_flag = trsGuardCheck( ranges1 ); int ranges2_memory_flag = trsGuardCheck( ranges2 ); int data1_memory_flag = trsGuardCheck( data1 ); int data2_memory_flag = trsGuardCheck( data2 ); trsGuardFree( ranges1 ); trsGuardFree( ranges2 ); trsGuardFree( data1 ); trsGuardFree( data2 ); if(ranges1_memory_flag || ranges2_memory_flag || data1_memory_flag|| data2_memory_flag) { return trsResult( TRS_FAIL, "Dirty memory"); } delete m1; delete m2; delete m3; delete []testdata1; delete []testdata0; return trsResult( ret, ret == TRS_OK ? "No errors" : "Bad matrix data"); }
static int drawing_test() { static int read_params = 0; static int read = 0; const int channel = 3; CvSize size = cvSize(600, 300); int i, j; int Errors = 0; if( !read_params ) { read_params = 1; trsCaseRead( &read, "/n/y", "y", "Read from file ?" ); } // Create image IplImage* image = cvCreateImage( size, IPL_DEPTH_8U, channel ); // cvLine cvZero( image ); for( i = 0; i < 100; i++ ) { CvPoint p1 = cvPoint( i - 30, i * 4 + 10 ); CvPoint p2 = cvPoint( size.width + 30 - i, size.height - 10 - i * 4 ); cvLine( image, p1, p2, CV_RGB(178+i, 255-i, i), i % 10 ); } Errors += ProcessImage( image, "cvLine", read ); // cvLineAA cvZero( image ); for( i = 0; i < 100; i++ ) { CvPoint p1 = cvPoint( i - 30, i * 4 + 10 ); CvPoint p2 = cvPoint( size.width + 30 - i, size.height - 10 - i * 4 ); cvLine( image, p1, p2, CV_RGB(178+i, 255-i, i), 1, CV_AA, 0 ); } //Errors += ProcessImage( image, "cvLineAA", read ); // cvRectangle cvZero( image ); for( i = 0; i < 100; i++ ) { CvPoint p1 = cvPoint( i - 30, i * 4 + 10 ); CvPoint p2 = cvPoint( size.width + 30 - i, size.height - 10 - i * 4 ); cvRectangle( image, p1, p2, CV_RGB(178+i, 255-i, i), i % 10 ); } Errors += ProcessImage( image, "cvRectangle", read ); #if 0 named_window( "Diff", 0 ); #endif // cvCircle cvZero( image ); for( i = 0; i < 100; i++ ) { CvPoint p1 = cvPoint( i * 3, i * 2 ); CvPoint p2 = cvPoint( size.width - i * 3, size.height - i * 2 ); cvCircle( image, p1, i, CV_RGB(178+i, 255-i, i), i % 10 ); cvCircle( image, p2, i, CV_RGB(178+i, 255-i, i), i % 10 ); #if 0 show_iplimage( "Diff", image ); wait_key(0); #endif } Errors += ProcessImage( image, "cvCircle", read ); // cvCircleAA cvZero( image ); for( i = 0; i < 100; i++ ) { CvPoint p1 = cvPoint( i * 3, i * 2 ); CvPoint p2 = cvPoint( size.width - i * 3, size.height - i * 2 ); cvCircleAA( image, p1, i, RGB(i, 255 - i, 178 + i), 0 ); cvCircleAA( image, p2, i, RGB(i, 255 - i, 178 + i), 0 ); } Errors += ProcessImage( image, "cvCircleAA", read ); // cvEllipse cvZero( image ); for( i = 10; i < 100; i += 10 ) { CvPoint p1 = cvPoint( i * 6, i * 3 ); CvSize axes = cvSize( i * 3, i * 2 ); cvEllipse( image, p1, axes, 180 * i / 100, 90 * i / 100, 90 * (i - 100) / 100, CV_RGB(178+i, 255-i, i), i % 10 ); } Errors += ProcessImage( image, "cvEllipse", read ); // cvEllipseAA cvZero( image ); for( i = 10; i < 100; i += 10 ) { CvPoint p1 = cvPoint( i * 6, i * 3 ); CvSize axes = cvSize( i * 3, i * 2 ); cvEllipseAA( image, p1, axes, 180 * i / 100, 90 * i / 100, 90 * (i - 100) / 100, RGB(i, 255 - i, 178 + i), i % 10 ); } Errors += ProcessImage( image, "cvEllipseAA", read ); // cvFillConvexPoly cvZero( image ); for( j = 0; j < 5; j++ ) for( i = 0; i < 100; i += 10 ) { CvPoint p[4] = {{ j * 100 - 10, i }, { j * 100 + 10, i }, { j * 100 + 30, i * 2 }, { j * 100 + 170, i * 3 }}; cvFillConvexPoly( image, p, 4, CV_RGB(178+i, 255-i, i) ); } Errors += ProcessImage( image, "cvFillConvexPoly", read ); // cvFillPoly cvZero( image ); for( i = 0; i < 100; i += 10 ) { CvPoint p0[] = {{-10, i}, { 10, i}, { 30, i * 2}, {170, i * 3}}; CvPoint p1[] = {{ 90, i}, {110, i}, {130, i * 2}, {270, i * 3}}; CvPoint p2[] = {{190, i}, {210, i}, {230, i * 2}, {370, i * 3}}; CvPoint p3[] = {{290, i}, {310, i}, {330, i * 2}, {470, i * 3}}; CvPoint p4[] = {{390, i}, {410, i}, {430, i * 2}, {570, i * 3}}; CvPoint* p[] = {p0, p1, p2, p3, p4}; int n[] = {4, 4, 4, 4, 4}; cvFillPoly( image, p, n, 5, CV_RGB(178+i, 255-i, i) ); } Errors += ProcessImage( image, "cvFillPoly", read ); // cvPolyLine cvZero( image ); for( i = 0; i < 100; i += 10 ) { CvPoint p0[] = {{-10, i}, { 10, i}, { 30, i * 2}, {170, i * 3}}; CvPoint p1[] = {{ 90, i}, {110, i}, {130, i * 2}, {270, i * 3}}; CvPoint p2[] = {{190, i}, {210, i}, {230, i * 2}, {370, i * 3}}; CvPoint p3[] = {{290, i}, {310, i}, {330, i * 2}, {470, i * 3}}; CvPoint p4[] = {{390, i}, {410, i}, {430, i * 2}, {570, i * 3}}; CvPoint* p[] = {p0, p1, p2, p3, p4}; int n[] = {4, 4, 4, 4, 4}; cvPolyLine( image, p, n, 5, 1, CV_RGB(178+i, 255-i, i), i % 10 ); } Errors += ProcessImage( image, "cvPolyLine", read ); // cvPolyLineAA cvZero( image ); for( i = 0; i < 100; i += 10 ) { CvPoint p0[] = {{-10, i}, { 10, i}, { 30, i * 2}, {170, i * 3}}; CvPoint p1[] = {{ 90, i}, {110, i}, {130, i * 2}, {270, i * 3}}; CvPoint p2[] = {{190, i}, {210, i}, {230, i * 2}, {370, i * 3}}; CvPoint p3[] = {{290, i}, {310, i}, {330, i * 2}, {470, i * 3}}; CvPoint p4[] = {{390, i}, {410, i}, {430, i * 2}, {570, i * 3}}; CvPoint* p[] = {p0, p1, p2, p3, p4}; int n[] = {4, 4, 4, 4, 4}; cvPolyLineAA( image, p, n, 5, 1, RGB(i, 255 - i, 178 + i), 0 ); } Errors += ProcessImage( image, "cvPolyLineAA", read ); // cvPolyLineAA cvZero( image ); for( i = 1; i < 10; i++ ) { CvFont font; cvInitFont( &font, CV_FONT_VECTOR0, (double)i / 5, (double)i / 5, (double)i / 10, i ); cvPutText( image, "privet. this is test. :)", cvPoint(0, i * 20), &font, CV_RGB(178+i, 255-i, i) ); } Errors += ProcessImage( image, "cvPutText", read ); cvReleaseImage( &image ); return Errors ? trsResult( TRS_FAIL, "errors" ) : trsResult( TRS_OK, "ok" ); }
int fmaFitEllipse(void) { long lErrors = 0; CvPoint points[1000]; CvPoint2D32f fpoints[1000]; CvBox2D box; CvMemStorage* storage = cvCreateMemStorage(0); CvContour* contour; CvSize axis; IplImage* img = cvCreateImage( cvSize(200,200), IPL_DEPTH_8U, 1 ); for( int k = 0 ; k < 1000; k++ ) { iplSet( img, 0 ); CvPoint center = { 100, 100 }; double angle = atsInitRandom( 0, 360 ); axis.height = (int)atsInitRandom( 5, 50 ); axis.width = (int)atsInitRandom( 5, 50 ); cvEllipse( img, center, axis, angle, 0, 360, 255, -1 ); cvFindContours( img, storage, (CvSeq**)&contour, sizeof(CvContour) ); cvCvtSeqToArray( (CvSeq*)contour, points ); for( int i = 0; i < contour->total; i++ ) { fpoints[i].x = (float)points[i].x; fpoints[i].y = (float)points[i].y; } cvFitEllipse( fpoints, contour->total, &box ); //compare boxes if( fabs( box.center.x - center.x) > 1 || fabs( box.center.y - center.y ) > 1 ) { lErrors++; } if( ( fabs( box.size.width - (axis.width * 2 ) ) > 4 || fabs( box.size.height - (axis.height * 2) ) > 4 ) && ( fabs( box.size.height - (axis.width * 2 ) ) > 4 || fabs( box.size.width - (axis.height * 2) ) > 4 ) ) { lErrors++; //graphic /*IplImage* rgb = cvCreateImage( cvSize(200,200), IPL_DEPTH_8U, 3 ); iplSet( rgb, 0 ); cvEllipse( rgb, center, axis, angle, 0, 360, CV_RGB(255,0,0) , 1 ); int window = atsCreateWindow( "proba", cvPoint(0,0), cvSize(200,200) ); cvEllipse( rgb, center, cvSize( box.size.width/2, box.size.height/2) , -box.angle, 0, 360, CV_RGB(0,255,0) , 1 ); //draw center cvEllipse( rgb, center, cvSize( 0, 0) , 0, 0, 360, CV_RGB(255,255,255) , -1 ); atsDisplayImage( rgb, window, cvPoint(0,0), cvSize(200,200) ); getch(); atsDestroyWindow( window ); //one more cvFitEllipse( fpoints, contour->total, &box ); */ } } cvReleaseMemStorage( &storage ); if( !lErrors) return trsResult(TRS_OK, "No errors"); else return trsResult(TRS_FAIL, "Fixed %d errors", lErrors); }
int testEvidence() { int ret = TRS_OK; int nnodes = 0; int nObsNodes = 0; int i,j; while(nnodes <= 0) { trsiRead( &nnodes, "10", "Number of nodes in Model" ); } while((nObsNodes <= 0)||(nObsNodes>nnodes)) { trsiRead( &nObsNodes, "2", "Number of Observed nodes from all nodes in model"); } int seed1 = pnlTestRandSeed(); /*create string to display the value*/ char value[42]; sprintf(value, "%i", seed1); trsiRead(&seed1, value, "Seed for srand to define NodeTypes etc."); trsWrite(TW_CON|TW_RUN|TW_DEBUG|TW_LST, "seed for rand = %d\n", seed1); CNodeType *modelNodeType = new CNodeType[2]; modelNodeType[0] = CNodeType( 1, 4 ); modelNodeType[1] = CNodeType( 0, 3 ); int *NodeAssociat=new int [nnodes+1]; for(i=0; i<(nnodes+1)/2; i++) { NodeAssociat[2*i]=0; NodeAssociat[2*i+1]=1; } //create random graph - number of nodes for every node is rand too int lowBorder = nnodes - 1; int upperBorder = int((nnodes * (nnodes - 1)) / 2); int numEdges = rand()%(upperBorder - lowBorder)+lowBorder; CGraph* theGraph = tCreateRandomDAG( nnodes, numEdges, 1 ); CBNet *grModel = CBNet::Create(nnodes, 2, modelNodeType, NodeAssociat,theGraph); int *obsNodes = (int*)trsGuardcAlloc(nObsNodes, sizeof(int)); srand ((unsigned int)seed1); intVector residuaryNodes; for (i=0; i<nnodes; i++) { residuaryNodes.push_back(i); } int num = 0; valueVector Values; Values.reserve(3*nnodes); Value val; for (i = 0; i<nObsNodes; i++) { num = rand()%(nnodes-i); obsNodes[i] = residuaryNodes[num]; residuaryNodes.erase(residuaryNodes.begin()+num); CNodeType nt = modelNodeType[NodeAssociat[obsNodes[i]]]; if(nt.IsDiscrete()) { val.SetInt(1); Values.push_back(val); } else { val.SetFlt(1.0f); Values.push_back(val); val.SetFlt(2.0f); Values.push_back(val); val.SetFlt(3.0f); Values.push_back(val); } } residuaryNodes.clear(); CEvidence *pMyEvid = CEvidence::Create(grModel, nObsNodes, obsNodes, Values) ; int nObsNodesFromEv = pMyEvid->GetNumberObsNodes(); const int *pObsNodesNow = pMyEvid->GetObsNodesFlags(); // const int *myOffset = pMyEvid->GetOffset(); const int *myNumAllObsNodes = pMyEvid->GetAllObsNodes(); valueVector ev; pMyEvid->GetRawData(&ev); const Value* vall = pMyEvid->GetValue(obsNodes[0]); if( NodeAssociat[obsNodes[0]] == 0 ) { if( (vall)[0].GetInt() != 1 ) { ret = TRS_FAIL; } } else { for( j=0; j<3; j++) { if( (vall)[j].GetFlt() != (j+1)*1.0f ) { ret = TRS_FAIL; break; } } } if(nObsNodesFromEv == nObsNodes) { intVector numbersOfReallyObsNodes; int numReallyObsNodes=0; for ( i=0; i<nObsNodesFromEv; i++) { if (pObsNodesNow[i]) { numbersOfReallyObsNodes.push_back(myNumAllObsNodes[i]); numReallyObsNodes++; } } #if 0 const CNodeType ** AllNodeTypesFromModel= new const CNodeType*[nnodes]; for (i=0; i<nnodes; i++) { AllNodeTypesFromModel[i] = grModel->GetNodeType(i); } for (i=0; i<nObsNodesFromEv; i++) { //Test the values which are keep in Evidence CNodeType nt = *AllNodeTypesFromModel[myNumAllObsNodes[i]]; int IsDiscreteNode = nt.IsDiscrete(); if(IsDiscreteNode) { int valFromEv = (ev[myOffset[i]].GetInt()); if(!(Values[i].GetInt() == valFromEv)) { ret=TRS_FAIL; break; } } else { ; for (j=0; j<3; j++) { if(!((ev[myOffset[i]+j]).GetFlt() == Values[i+j].GetFlt())) { ret=TRS_FAIL; break; } } } } delete []AllNodeTypesFromModel; #endif } else { ret = TRS_FAIL; } //Toggle some Node int someNumber = (int)(rand()*nObsNodesFromEv/RAND_MAX); int *someOfNodes = new int[someNumber]; intVector residuaryNums = intVector(myNumAllObsNodes, myNumAllObsNodes+nObsNodesFromEv); num=0; for(i=0; i<someNumber;i++) { num = (int)(rand()%(nObsNodes-i)); someOfNodes[i] = residuaryNums[num]; residuaryNums.erase(residuaryNums.begin()+num); } residuaryNums.clear(); pMyEvid->ToggleNodeState(someNumber, someOfNodes); const int *pObsNodesAfterToggle = pMyEvid->GetObsNodesFlags(); for (i=0; i<nObsNodesFromEv; i++) { //Test the ToggleNode method... if(pObsNodesAfterToggle[i]) { for(j=0; j<someNumber;j++) { if(myNumAllObsNodes[i]==someOfNodes[j]) { ret=TRS_FAIL; break; } } } } delete grModel; delete pMyEvid; delete []modelNodeType; delete []NodeAssociat; delete []someOfNodes; int obsNodes_memory_flag = trsGuardCheck( obsNodes ); if( obsNodes_memory_flag) { return trsResult( TRS_FAIL, "Dirty memory"); } trsGuardFree( obsNodes ); return trsResult( ret, ret == TRS_OK ? "No errors" : "Bad test on Values"); }
//--------------------------------------------------- Test body -------------------------- static int fmaUnDistort( void ) { int i, itest, io=0, num_test, err1=0, err2=0, err3=0, err4=0, err10=0, err20=0, err30=0, err40=0, err=0, err5, pass=1; int n, n3, step, step3; int* data; IplImage* undistMap = 0; uchar *srcImg, *dstImg, *tstImg, *srcImg3, *dstImg3, *tstImg3; IplImage *src, *dst, *tst, *src3, *dst3, *tst3; float *a, *k, p = 0.f; AtsRandState state; CvSize size; double norm, norm1; /* Reading test parameters */ trsiRead( &img_width, "320", "width of image" ); trsiRead( &img_height, "240", "height of image" ); trsiRead( &roi_step, "0", "ROI step" ); n = img_width * img_height; size.height = img_height; size.width = img_width; a = (float*)cvAlloc( sizeof(float) * 9 ); k = (float*)cvAlloc( sizeof(float) * 4 ); //data = (int*) icvAlloc( 3*n*sizeof(int) ); src = cvCreateImage( size, IPL_DEPTH_8U, 1 ); cvSetImageROI( src, cvRect(0, 0, src->width, src->height) ); dst = cvCreateImage( size, IPL_DEPTH_8U, 1 ); cvSetImageROI( dst, cvRect(0, 0, dst->width, dst->height) ); tst = cvCreateImage( size, IPL_DEPTH_8U, 1 ); cvSetImageROI( tst, cvRect(0, 0, tst->width, tst->height) ); src3 = cvCreateImage( size, IPL_DEPTH_8U, 3 ); cvSetImageROI( src3, cvRect(0, 0, src3->width, src3->height) ); dst3 = cvCreateImage( size, IPL_DEPTH_8U, 3 ); cvSetImageROI( dst3, cvRect(0, 0, dst3->width, dst3->height) ); tst3 = cvCreateImage( size, IPL_DEPTH_8U, 3 ); cvSetImageROI( tst3, cvRect(0, 0, tst3->width, tst3->height) ); undistMap = cvCreateImage( size, IPL_DEPTH_32S, 3 ); srcImg = (uchar*)src->imageData; dstImg = (uchar*)dst->imageData; tstImg = (uchar*)tst->imageData; srcImg3 = (uchar*)src3->imageData; dstImg3 = (uchar*)dst3->imageData; tstImg3 = (uchar*)tst3->imageData; data = (int*)undistMap->imageData; step = src->widthStep; step3 = src3->widthStep; n = step*img_height; n3 = step3*img_height; atsRandInit( &state, 0, 255, 13 ); atsbRand8u ( &state, srcImg, n ); atsbRand8u ( &state, srcImg3, n3 ); a[0] = img_width/3.f; a[4] = img_height/2.f; a[2] = img_width/2.f; a[5] = img_height/2.f; k[0] = -0.04f; k[1] = 0.004f; k[2] = 0.f; k[3] = 0.f; if(roi_step) { num_test = (img_width/2 - 3)/roi_step; if( num_test > (img_height/2)/roi_step ) num_test = (img_height/2)/roi_step; } else num_test = 1; if( num_test < 1 ) num_test = 1; begin: trsWrite(TW_RUN|TW_CON, "\n %d pass of 4 :\n", pass); for(itest=0; itest<num_test; itest++) { int ii = (itest*10)/num_test; int roi_offset = roi_step*itest; int img_offset = roi_offset*(step + 1); int img_offset3 = roi_offset*(step3 + 3); size.width = img_width - 2*roi_offset; size.height = img_height - 2*roi_offset; src->roi->xOffset = src->roi->yOffset = roi_offset; src->roi->height = size.height; src->roi->width = size.width; dst->roi->xOffset = dst->roi->yOffset = roi_offset; dst->roi->height = size.height; dst->roi->width = size.width; tst->roi->xOffset = tst->roi->yOffset = roi_offset; tst->roi->height = size.height; tst->roi->width = size.width; src3->roi->xOffset = src3->roi->yOffset = roi_offset; src3->roi->height = size.height; src3->roi->width = size.width; dst3->roi->xOffset = dst3->roi->yOffset = roi_offset; dst3->roi->height = size.height; dst3->roi->width = size.width; tst3->roi->xOffset = tst3->roi->yOffset = roi_offset; tst3->roi->height = size.height; tst3->roi->width = size.width; /* 8uC1 flavor test without interpolation */ for(i=0; i<n; i++) dstImg[i] = tstImg[i] = 0; cvUnDistortInit ( src, undistMap, a, k, 0 ); cvUnDistort ( src, dst, undistMap, 0 ); UnDistortTest_C1( srcImg + img_offset, tstImg + img_offset, step, size, a, k, 0 ); if( !img_offset ) { norm = norm1 = 0.0; for(i=0; i<n; i++) { norm += fabs( dstImg[i] - tstImg[i] ); norm1 += fabs( tstImg[i] ); } norm /= norm1; printf( " 8u C1 without interpolation: %g\n", norm ); } for(i=0; i<n; i++) { int d = dstImg[i] - tstImg[i]; if( d > MAXDIFF || d < -MAXDIFF ) err1++; } for(i=0; i<n; i++) dstImg[i] = 0; cvUnDistortOnce ( src, dst, a, k, 0 ); //for(i=0; i<n; i++)printf(" %d", dstImg[i]); getchar(); if( !img_offset ) { norm = norm1 = 0.0; for(i=0; i<n; i++) { norm += fabs( dstImg[i] - tstImg[i] ); norm1 += fabs( tstImg[i] ); } norm /= norm1; printf( " %g\n", norm ); } for(i=0; i<n; i++) { int d = dstImg[i] - tstImg[i]; if( d > MAXDIFF || d < -MAXDIFF ) err10++; } /* 8uC1 flavor test with interpolation */ for(i=0; i<n; i++) dstImg[i] = tstImg[i] = 0; cvUnDistortInit ( src, undistMap, a, k, 1 ); cvUnDistort ( src, dst, undistMap, 1 ); UnDistortTest_C1( srcImg + img_offset, tstImg + img_offset, step, size, a, k, 1 ); if( !img_offset ) { norm = norm1 = 0.0; for(i=0; i<n; i++) { norm += fabs( dstImg[i] - tstImg[i] ); norm1 += fabs( tstImg[i] ); } norm /= norm1; printf( " 8u C1 with interpolation: %g\n", norm ); } for(i=0; i<n; i++) { int d = dstImg[i] - tstImg[i]; if( d > MAXDIFF || d < -MAXDIFF ) err2++; } for(i=0; i<n; i++) dstImg[i] = 0; cvUnDistortOnce ( src, dst, a, k, 1 ); if( !img_offset ) { norm = norm1 = 0.0; for(i=0; i<n; i++) { norm += fabs( dstImg[i] - tstImg[i] ); norm1 += fabs( tstImg[i] ); } norm /= norm1; printf( " %g\n", norm ); } for(i=0; i<n; i++) { int d = dstImg[i] - tstImg[i]; if( d > MAXDIFF || d < -MAXDIFF ) err20++; } /* 8uC3 flavor test without interpolation */ for(i=0; i<n3; i++) dstImg3[i] = tstImg3[i] = 0; cvUnDistortInit ( src3, undistMap, a, k, 0 ); cvUnDistort ( src3, dst3, undistMap, 0 ); UnDistortTest_C3( srcImg3+img_offset3, tstImg3+img_offset3, step3, size, a, k, 0 ); for(i=0; i<n3; i++) { int d = dstImg3[i] - tstImg3[i]; if( d > MAXDIFF || d < -MAXDIFF ) err3++; } if( !img_offset ) { norm = norm1 = 0.0; for(i=0; i<n3; i++) { norm += fabs( dstImg3[i] - tstImg3[i] ); norm1 += fabs( tstImg3[i] ); } norm /= norm1; printf( " 8u C3 without interpolation: %g\n", norm ); } for(i=0; i<n3; i++) dstImg3[i] = 0; cvUnDistortOnce ( src3, dst3, a, k, 0 ); if( !img_offset ) { norm = norm1 = 0.0; for(i=0; i<n3; i++) { norm += fabs( dstImg3[i] - tstImg3[i] ); norm1 += fabs( tstImg3[i] ); } norm /= norm1; printf( " %g\n", norm ); } for(i=0; i<n3; i++) { int d = dstImg3[i] - tstImg3[i]; if( d > MAXDIFF || d < -MAXDIFF ) err30++; } /* 8uC3 flavor test with interpolation */ for(i=0; i<n3; i++) dstImg3[i] = tstImg3[i] = 0; cvUnDistortInit ( src3, undistMap, a, k, 1 ); cvUnDistort ( src3, dst3, undistMap, 1 ); UnDistortTest_C3( srcImg3+img_offset3, tstImg3+img_offset3, step3, size, a, k, 1 ); for(i=0; i<n3; i++) { int d = dstImg3[i] - tstImg3[i]; if( d > MAXDIFF || d < -MAXDIFF ) err4++; } if( !img_offset ) { norm = norm1 = 0.0; for(i=0; i<n3; i++) { norm += fabs( dstImg3[i] - tstImg3[i] ); norm1 += fabs( tstImg3[i] ); } norm /= norm1; printf( " 8u C3 with interpolation: %g\n", norm ); } for(i=0; i<n3; i++) dstImg3[i] = 0; cvUnDistortOnce ( src3, dst3, a, k, 1 ); if( !img_offset ) { norm = norm1 = 0.0; for(i=0; i<n3; i++) { norm += fabs( dstImg3[i] - tstImg3[i] ); norm1 += fabs( tstImg3[i] ); } norm /= norm1; printf( " %g\n", norm ); } for(i=0; i<n3; i++) { int d = dstImg3[i] - tstImg3[i]; if( d > MAXDIFF || d < -MAXDIFF ) err40++; } if(ii>io) { trsWrite(TW_RUN|TW_CON, " %d%% ", 10*ii); io=ii; } } err5 = err1 + err2 + err3 + err4 + err10 + err20 + err30 + err40; err += err5; if( p < err1*100.f / (float)(n*num_test) ) p = err1*100.f / (float)(n*num_test); if( p < err2*100.f / (float)(n*num_test) ) p = err2*100.f / (float)(n*num_test); if( p < err3*100.f / (float)(3*n*num_test) ) p = err3*100.f / (float)(3*n*num_test); if( p < err4*100.f / (float)(3*n*num_test) ) p = err4*100.f / (float)(3*n*num_test); if( p < err10*100.f / (float)(n*num_test) ) p = err10*100.f / (float)(n*num_test); if( p < err20*100.f / (float)(n*num_test) ) p = err20*100.f / (float)(n*num_test); if( p < err30*100.f / (float)(3*n*num_test) ) p = err30*100.f / (float)(3*n*num_test); if( p < err40*100.f / (float)(3*n*num_test) ) p = err40*100.f / (float)(3*n*num_test); //printf("\n %d %d %d %d\n %d %d %d %d %7.3f%% errors\n", // err1, err2, err3, err4, err10, err20, err30, err40, p); switch( pass ) { case 1: k[0] = -k[0]; io = 0; err1 = err2 = err3 = err4 = err10 = err20 = err30 = err40 = 0; pass++; goto begin; break; case 2: k[0] = -k[0]; k[2] = k[3] = 0.02f; io = 0; err1 = err2 = err3 = err4 = err10 = err20 = err30 = err40 = 0; pass++; goto begin; break; case 3: k[0] = -k[0]; io = 0; err1 = err2 = err3 = err4 = err10 = err20 = err30 = err40 = 0; pass++; goto begin; break; } if( p < MAXPERCENT ) err = 0; cvReleaseImage( &src ); cvReleaseImage( &dst ); cvReleaseImage( &tst ); cvReleaseImage( &src3 ); cvReleaseImage( &dst3 ); cvReleaseImage( &tst3 ); cvReleaseImage( &undistMap ); cvFree( (void**)&a ); cvFree( (void**)&k ); if( err == 0 ) return trsResult( TRS_OK, "No errors fixed by this test" ); else return trsResult( TRS_FAIL, "Total fixed %d errors", err ); } /*fma*/
int testBKInfUsingClusters() { int ret = TRS_OK; int seed = pnlTestRandSeed(); pnlSeed( seed ); std::cout<<"seed"<<seed<<std::endl; int nTimeSlices = -1; while(nTimeSlices <= 5) { trsiRead (&nTimeSlices, "10", "Number of slices"); } float eps = -1.0f; while( eps <= 0 ) { trssRead( &eps, "1.0e-1f", "accuracy in test"); } CDBN *pDBN = CDBN::Create( pnlExCreateBatNetwork() ); intVecVector clusters; intVector interfNds; pDBN->GetInterfaceNodes( &interfNds ); int numIntNds = interfNds.size(); int numOfClusters = pnlRand( 1, numIntNds ); clusters.resize(numOfClusters); int i; for( i = 0; i < numIntNds; i++ ) { ( clusters[pnlRand( 0, numOfClusters-1 )] ).push_back( interfNds[i] ); } intVecVector validClusters; validClusters.reserve(numOfClusters); for( i = 0; i < clusters.size(); i++ ) { if(! clusters[i].empty()) { validClusters.push_back(clusters[i]); } } CBKInfEngine *pBKInf; pBKInf = CBKInfEngine::Create( pDBN, validClusters ); C1_5SliceJtreeInfEngine *pJTreeInf; pJTreeInf = C1_5SliceJtreeInfEngine::Create( pDBN ); intVector nSlices( 1, nTimeSlices ); pEvidencesVecVector pEvid; pDBN->GenerateSamples( &pEvid, nSlices); int nnodesPerSlice = pDBN->GetNumberOfNodes(); intVector nodes(nnodesPerSlice, 0); for( i = 0; i < nnodesPerSlice; i++ ) { nodes[i] = i; } intVector ndsToToggle; for( i = 0; i < nTimeSlices; i++ ) { std::random_shuffle( nodes.begin(), nodes.end() ); ndsToToggle.resize( pnlRand(1, nnodesPerSlice) ); int j; for( j = 0; j < ndsToToggle.size(); j++ ) { ndsToToggle[j] = nodes[j]; } (pEvid[0])[i]->ToggleNodeState( ndsToToggle ); } pBKInf->DefineProcedure( ptSmoothing, nTimeSlices ); pBKInf->EnterEvidence( &(pEvid[0]).front(), nTimeSlices ); pBKInf->Smoothing(); pJTreeInf->DefineProcedure( ptSmoothing, nTimeSlices ); pJTreeInf->EnterEvidence( &pEvid[0].front(), nTimeSlices ); pJTreeInf->Smoothing(); int querySlice = pnlRand( 0, nTimeSlices - 1 ); int queryNode = pnlRand( 0, nnodesPerSlice - 1); queryNode += (querySlice ? nnodesPerSlice : 0); intVector query; pDBN->GetGraph()->GetParents( queryNode, &query ); query.push_back( queryNode ); std::random_shuffle( query.begin(), query.end() ); query.resize( pnlRand(1, query.size()) ); pBKInf->MarginalNodes(&query.front(), query.size(), querySlice); pJTreeInf->MarginalNodes(&query.front(), query.size(), querySlice); const CPotential *potBK = pBKInf->GetQueryJPD(); const CPotential *potJTree = pJTreeInf->GetQueryJPD(); if( !potBK->IsFactorsDistribFunEqual( potJTree , eps ) ) { std::cout<<"BK query JPD \n"; potBK->Dump(); std::cout<<"JTree query JPD \n"; potJTree->Dump(); ret = TRS_FAIL; } for( i = 0; i < nTimeSlices; i++ ) { delete (pEvid[0])[i]; } delete pBKInf; delete pJTreeInf; delete pDBN; return trsResult( ret, ret == TRS_OK ? "No errors" : "Bad test on BK Inference using clusters"); }
static int foaThreshold( void* prm ) { long lParam = (long)prm; int Flavour = lParam & 0xf; CvThreshType Type = (CvThreshType)((lParam >> 4) & 0xf); IplImage* Src8uR; IplImage* Src8sR; IplImage* Src32fR; IplImage* Src8uControlR; IplImage* Src8sControlR; IplImage* Src32fControlR; int height; int width; long Errors = NULL; float ThreshMax; float ThreshMin; float _Thresh; int i; static int read_param = 0; /* Initialization global parameters */ if( !read_param ) { read_param = 1; trslRead( &Len, "106", "Size of sourse array" ); trssRead( &Thresh, "125", "Threshold value" ); } width = Len; height = Len / 2 + 1; Src8uR = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 1); Src8sR = cvCreateImage(cvSize(width, height), IPL_DEPTH_8S, 1); Src32fR = cvCreateImage(cvSize(width, height), IPL_DEPTH_32F, 1); Src8uControlR = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 1); Src8sControlR = cvCreateImage(cvSize(width, height), IPL_DEPTH_8S, 1); Src32fControlR = cvCreateImage(cvSize(width, height), IPL_DEPTH_32F, 1); assert( Src8uR ); assert( Src8sR ); assert( Src32fR ); assert( Src8uControlR ); assert( Src8sControlR ); assert( Src32fControlR ); ThreshMin = (Flavour == ATS_8U ? MAX( -Thresh, 0 ) : Flavour == ATS_8S ? MAX( -Thresh, -128 ) : -Thresh); ThreshMax = Thresh; for( _Thresh = ThreshMin; _Thresh <= ThreshMax; _Thresh++ ) { CvSize size = cvSize( width, height ); for( i = 0; i < height; i++ ) { ats1bInitRandom( 0, 255, (uchar*)Src8uControlR->imageData + i * Src8uControlR->widthStep, Len ); ats1cInitRandom( -128, 127, Src8sControlR->imageData + i * Src8sControlR->widthStep, Len ); ats1flInitRandom( -255, 255, (float*)(Src32fControlR->imageData + i * Src32fControlR->widthStep), Len ); } /* Run CVL function comparing results */ switch( Flavour ) { case ATS_8U: cvThreshold( Src8uControlR, Src8uR, _Thresh, 250, Type ); /* Run my function */ myThreshR( Src8uControlR, Src8sControlR, Src32fControlR, _Thresh, 250, Type ); Errors += atsCompare2Db( (uchar*)Src8uR->imageData, (uchar*)Src8uControlR->imageData, size, Src8uR->widthStep, 0 ); break; case ATS_8S: cvThreshold( Src8sControlR,Src8sR, _Thresh, 120, Type ); /* Run my function */ myThreshR( Src8uControlR, Src8sControlR, Src32fControlR, _Thresh, 120, Type ); Errors += atsCompare2Dc( Src8sR->imageData, Src8sControlR->imageData, size, Src8sR->widthStep, 0 ); break; case ATS_32F: cvThreshold( Src32fControlR, Src32fR, _Thresh, 250, Type ); /* Run my function */ myThreshR( Src8uControlR, Src8sControlR, Src32fControlR, _Thresh, 250, Type ); Errors += atsCompare2Dfl( (float*)Src32fR->imageData, (float*)Src32fControlR->imageData, size, Src32fR->widthStep, 0 ); break; default: assert( 0 ); } } cvReleaseImage( &Src8uR ); cvReleaseImage( &Src8sR ); cvReleaseImage( &Src32fR ); cvReleaseImage( &Src8uControlR ); cvReleaseImage( &Src8sControlR ); cvReleaseImage( &Src32fControlR ); return Errors == 0 ? TRS_OK : trsResult( TRS_FAIL, "Fixed %d errors", Errors ); }