int main (void)
{
  enum { N = 20, L = 10, resolution = 600};

  Matrix M = TestMatrix(N,N);

  Vector level(1,L);
  double mi = Min(M), ma = Max(M);
  for (int i = 1; i <= L; ++i) 
    level[i] = mi + (i-1)*(ma-mi)/(L-1);
  level[4]  = -3; 
  level[5]  = -2.5;
  cerr << mi << " " << ma << endl <<  level << endl;

  ColorMap cmap("spectral-256");
  MpImage image(resolution,resolution);
  Scene scene(image);

  MpContourSurface(scene,M, M.Rlo(),M.Rhi(), M.Clo(),M.Chi(), 
		   level,cmap,Min(M),Max(M));

  scene.LookFrom(Vector3D(100,50,-30));    // define the camera position
  scene.SetColoring(Scene::PerVertex);     // coloring (GLobal/PerVertex/PerFacet)
  scene.SetGlobalShading(Facet::Flat);     // shading (Constant/Flat/Gouraud/Phong)
  scene.SetGlobalEdgeLines(true);	   // edge lines (true/false)

  scene.Show();				   // now start rendering of the surface

  MpFrame display("Contour",resolution+4,resolution+4);
  new MpScrollImageWindow(display,image,resolution+4,resolution+4);
  new MpQuitButton(display,"Quit",80,25,0,0);
  display.EventLoop();
}
void Chapter9Test::Test9_9() {
  ofstream fout;
  OpenLogFile(fout, "test9_9.html", "Problem 9.9: print all eight queuens solutions");

  vector<vector<string> >matrix;

  // 1.
  matrix.clear();
  matrix = sol.prob9_9(4);
  TestMatrix(fout, "4", matrix, matrix);
  // 2.
  matrix.clear();
  matrix = sol.prob9_9(8);
  TestMatrix(fout, "8", matrix, matrix);

  CloseLogFile(fout);
}
void Chapter1Test::Test1_6() {
  ofstream fout;
  OpenLogFile(fout,"test1_6.html","Problem 1.6: rotate an image by 90 degrees clockwisely");


  vector<vector<int> > img, expected;
  stringstream input;

  tools.GenerateNewMatrix(img, {1,2,3,4}, 2, 2);
  tools.GenerateNewMatrix(expected, {3,1,4,2}, 2, 2);
  tools.PrintMatrix2File(img, input);
  sol.prob1_6(img);
  TestMatrix(fout, input.str(), img, expected);

  tools.GenerateNewMatrix(img, {1,2,3,4,5,6,7,8,9}, 3, 3);
  tools.GenerateNewMatrix(expected, {7,4,1,8,5,2,9,6,3}, 3, 3);
  input.str("");
  tools.PrintMatrix2File(img, input);
  sol.prob1_6(img);
  TestMatrix(fout, input.str(), img, expected);

  tools.GenerateNewMatrix(img, {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}, 4, 4);
  tools.GenerateNewMatrix(expected, {13,9,5,1,14,10,6,2,15,11,7,3,16,12,8,4}, 4, 4);
  input.str("");
  tools.PrintMatrix2File(img, input);
  sol.prob1_6(img);
  TestMatrix(fout, input.str(), img, expected);

  tools.GenerateNewMatrix(img, {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25}, 5, 5);
  tools.GenerateNewMatrix(expected, {21,16,11,6,1,22,17,12,7,2,23,18,13,8,3,24,19,14,9,4,25,20,15,10,5}, 5, 5);
  input.str("");
  tools.PrintMatrix2File(img, input);
  sol.prob1_6(img);
  TestMatrix(fout, input.str(), img, expected);

  tools.GenerateNewMatrix(img, {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36}, 6, 6);
  tools.GenerateNewMatrix(expected, {31,25,19,13,7,1,32,26,20,14,8,2,33,27,21,15,9,3,34,28,22,16,10,4,35,29,23,17,11,5,36,30,24,18,12,6}, 6, 6);
  input.str("");
  tools.PrintMatrix2File(img, input);
  sol.prob1_6(img);
  TestMatrix(fout, input.str(), img, expected);

  tools.GenerateNewMatrix(img, {}, 0, 0);
  tools.GenerateNewMatrix(expected, {}, 0, 0);
  input.str("");
  tools.PrintMatrix2File(img, input);
  sol.prob1_6(img);
  TestMatrix(fout, input.str(), img, expected);

  tools.GenerateNewMatrix(img, {1}, 1, 1);
  tools.GenerateNewMatrix(expected, {1}, 1, 1);
  input.str("");
  tools.PrintMatrix2File(img, input);
  sol.prob1_6(img);
  TestMatrix(fout, input.str(), img, expected);

  CloseLogFile(fout);
}
示例#4
0
void LibTest::Run()
{
    if ( !TestMatrix() )
    {
        std::cout << "TestMatrix() failed\n";
    }

    if ( !TestVector() )
    {
        std::cout << "TestVector() failed\n";
    }
}
void Chapter9Test::Test9_2() {
  ofstream fout;
  OpenLogFile(fout,"test9_2.html", "Problem 9.2: count all possible paths that makes a robot moves from (0, 0) to (X, Y)");

  Chapter9::Maze maze({{Chapter9::Maze::path, Chapter9::Maze::path},{Chapter9::Maze::path,Chapter9::Maze::path}});
  TestBasic(fout, "X = 2, Y = 2", maze.countAllPossiblePaths(), 2ul);
  TestMatrix(fout, "Print Paths", maze.findAllPossiblePaths(), maze.findAllPossiblePaths());
  ;
  maze.GenerateMaze({{0,0,0},{0,0,0},{0,0,0}});
  TestBasic(fout, "X = 3, Y = 3", maze.countAllPossiblePaths(), 6ul);
  TestMatrix(fout, "Print Paths", maze.findAllPossiblePaths(), maze.findAllPossiblePaths());

  maze.GenerateMaze({{0,0,0},{0,1,0},{0,0,0}});
  TestBasic(fout, "X = 3, Y = 3", maze.countAllPossiblePaths(), 2ul);
  TestMatrix(fout, "Print Paths", maze.findAllPossiblePaths(), maze.findAllPossiblePaths());

  maze.GenerateMaze({{0,0,0},{0,0,1},{0,0,0}});
  TestBasic(fout, "X = 3, Y = 3", maze.countAllPossiblePaths(), 3ul);
  TestMatrix(fout, "Print Paths", maze.findAllPossiblePaths(), maze.findAllPossiblePaths());

  maze.GenerateMaze({{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}});
  TestBasic(fout, "X = 3, Y = 3", maze.countAllPossiblePaths(), 20ul);
  TestMatrix(fout, "Print Paths", maze.findAllPossiblePaths(), maze.findAllPossiblePaths());

  maze.GenerateMaze({{0,0,0,0},{0,0,0,1},{0,0,0,0},{0,0,0,0}});
  TestBasic(fout, "X = 3, Y = 3", maze.countAllPossiblePaths(), 16ul);
  TestMatrix(fout, "Print Paths", maze.findAllPossiblePaths(), maze.findAllPossiblePaths());

  CloseLogFile(fout);
}
void Chapter9Test::Test9_4() {
  ofstream fout;
  OpenLogFile(fout, "test9_4.html", "Problem 9.4: return all subsets of a set.");

  vector<vector<int> > mat;
  vector<int> input;
  ostringstream ss;
  size_t expected;


  ss.str(""); ss.clear();
  input = {4,1,5,5,8,2};
  tools.PrintVector(input, ss);
  mat = sol.prob9_4(input);
  expected = static_cast<size_t>(pow(2.0, input.size()));
  TestMatrix(fout, ss.str(), mat, mat);
  TestBasic(fout, ss.str(), mat.size(), expected);

  ss.str(""); ss.clear();
  input = {1,2,3};
  tools.PrintVector(input, ss);
  mat = sol.prob9_4(input);
  expected = static_cast<size_t>(pow(2.0, input.size()));
  TestMatrix(fout, ss.str(), mat, mat);
  TestBasic(fout, ss.str(), mat.size(), expected);

  ss.str(""); ss.clear();
  input = {1,1,1};
  tools.PrintVector(input, ss);
  mat = sol.prob9_4(input);
  expected = static_cast<size_t>(pow(2.0, input.size()));
  TestMatrix(fout, ss.str(), mat, mat);
  TestBasic(fout, ss.str(), mat.size(), expected);

  CloseLogFile(fout);
}
示例#7
0
 TestData()
 : fRect(SkRect::MakeXYWH(SkIntToScalar(0), SkIntToScalar(0),
                              SkIntToScalar(2), SkIntToScalar(1)))
 , fMatrix(TestMatrix())
 , fPath(TestPath())
 , fNearlyZeroLengthPath(TestNearlyZeroLengthPath())
 , fIRect(SkIRect::MakeXYWH(0, 0, 2, 1))
 , fRegion(TestRegion())
 , fColor(0x01020304)
 , fPoints(kTestPoints)
 , fPointCount(3)
 , fWidth(2)
 , fHeight(2)
 , fText("Hello World")
 , fPoints2(kTestPoints2)
 , fBitmap(TestBitmap())
 { }
示例#8
0
int main(int argc, char *argv)
{
	std::cout << RotateMatrixCWInplace(TestMatrix<int>(0, 0, 10)) << std::endl;
	std::cout << RotateMatrixCWInplace(TestMatrix<int>(1, 1, 10)) << std::endl;
	std::cout << RotateMatrixCWInplace(TestMatrix<int>(2, 2, 10)) << std::endl;
	std::cout << RotateMatrixCWInplace(TestMatrix<int>(5, 5, 10)) << std::endl;
	std::cout << std::endl;
	std::cout << SetColAndRowTo0IfElemIs0(TestMatrix<int>(0, 0, 10)) << std::endl;
	std::cout << SetColAndRowTo0IfElemIs0(TestMatrix<int>(1, 2, 10)) << std::endl;
	std::cout << SetColAndRowTo0IfElemIs0(TestMatrix<int>(2, 3, 10)) << std::endl;
	auto m1 = TestMatrix(10, 8, 10);
	m1[5][3] = 0;
	m1[7][3] = 0;
	m1[0][0] = 0;
	std::cout << m1 << std::endl;
	SetColAndRowTo0IfElemIs0(m1);
	std::cout << m1 << std::endl;

	return 0;
}
示例#9
0
void TestLightmass()
{
	UE_LOG(LogLightmass, Display, TEXT("\n\n"));
	UE_LOG(LogLightmass, Display, TEXT("==============================================================================================="));
	UE_LOG(LogLightmass, Display, TEXT("Running \"unit test\". This will take several seconds, and will end with an assertion."));
	UE_LOG(LogLightmass, Display, TEXT("This is on purpose, as it's testing the callstack gathering..."));
	UE_LOG(LogLightmass, Display, TEXT("==============================================================================================="));
	UE_LOG(LogLightmass, Display, TEXT("\n\n"));

	void* Buf = FMemory::Malloc(1024);

	TArray<int32> TestArray;

	TestArray.Add(5);

	TArray<int32> ArrayCopy = TestArray;
	
	FVector4 TestVectorA(1, 0, 0, 1);
	FVector4 TestVectorB(1, 1, 1, 1);
	FVector4 TestVector = TestVectorA + TestVectorB;

	FString TestString = FString::Printf(TEXT("Copy has %d, Vector is [%.2f, %.2f, %.2f, %.2f]\n"), ArrayCopy[0], TestVector.X, TestVector.Y, TestVector.Z, TestVector.W);

	wprintf(*TestString);

	FMemory::Free(Buf);

	struct FAlignTester
	{
		uint8 A;
		FMatrix M1;
		uint8 B;
		FMatrix M2;
		uint8 C;
		FVector4 V;
	};
	FAlignTester AlignTest;
	checkf(((PTRINT)(&FMatrix::Identity) & 15) == 0, TEXT("Identity matrix unaligned"));
	checkf(((PTRINT)(&AlignTest.M1) & 15) == 0, TEXT("First matrix unaligned"));
	checkf(((PTRINT)(&AlignTest.M2) & 15) == 0, TEXT("Second matrix unaligned"));
	checkf(((PTRINT)(&AlignTest.V) & 15) == 0, TEXT("Vector unaligned"));

	FGuid Guid(1, 2, 3, 4);
	UE_LOG(LogLightmass, Display, TEXT("Guid is %s"), *Guid.ToString());

	TMap<FString, int32> TestMap;
	TestMap.Add(FString(TEXT("Five")), 5);
	TestMap.Add(TEXT("Ten"), 10);

	UE_LOG(LogLightmass, Display, TEXT("Map[Five] = %d, Map[Ten] = %d"), TestMap.FindRef(TEXT("Five")), TestMap.FindRef(FString(TEXT("Ten"))));

	FMatrix TestMatrix(FVector(0, 0, 0.1f), FVector(0, 1.0f, 0), FVector(0.9f, 0, 0), FVector(0, 0, 0));

	UE_LOG(LogLightmass, Display, TEXT("Mat=\n  [%0.2f, %0.2f, %0.2f, %0.2f]\n  [%0.2f, %0.2f, %0.2f, %0.2f]\n  [%0.2f, %0.2f, %0.2f, %0.2f]\n  [%0.2f, %0.2f, %0.2f, %0.2f]"), 
		TestMatrix.M[0][0], TestMatrix.M[0][1], TestMatrix.M[0][2], TestMatrix.M[0][3], 
		TestMatrix.M[1][0], TestMatrix.M[1][1], TestMatrix.M[1][2], TestMatrix.M[1][3], 
		TestMatrix.M[2][0], TestMatrix.M[2][1], TestMatrix.M[2][2], TestMatrix.M[2][3], 
		TestMatrix.M[3][0], TestMatrix.M[3][1], TestMatrix.M[3][2], TestMatrix.M[3][3]
		);

	TestMatrix = TestMatrix.GetTransposed();

	UE_LOG(LogLightmass, Display, TEXT("Transposed Mat=\n  [%0.2f, %0.2f, %0.2f, %0.2f]\n  [%0.2f, %0.2f, %0.2f, %0.2f]\n  [%0.2f, %0.2f, %0.2f, %0.2f]\n  [%0.2f, %0.2f, %0.2f, %0.2f]"), 
		TestMatrix.M[0][0], TestMatrix.M[0][1], TestMatrix.M[0][2], TestMatrix.M[0][3], 
		TestMatrix.M[1][0], TestMatrix.M[1][1], TestMatrix.M[1][2], TestMatrix.M[1][3], 
		TestMatrix.M[2][0], TestMatrix.M[2][1], TestMatrix.M[2][2], TestMatrix.M[2][3], 
		TestMatrix.M[3][0], TestMatrix.M[3][1], TestMatrix.M[3][2], TestMatrix.M[3][3]
		);

	TestMatrix = TestMatrix.GetTransposed().InverseFast();

	UE_LOG(LogLightmass, Display, TEXT("Inverted Mat=\n  [%0.2f, %0.2f, %0.2f, %0.2f]\n  [%0.2f, %0.2f, %0.2f, %0.2f]\n  [%0.2f, %0.2f, %0.2f, %0.2f]\n  [%0.2f, %0.2f, %0.2f, %0.2f]"), 
		TestMatrix.M[0][0], TestMatrix.M[0][1], TestMatrix.M[0][2], TestMatrix.M[0][3], 
		TestMatrix.M[1][0], TestMatrix.M[1][1], TestMatrix.M[1][2], TestMatrix.M[1][3], 
		TestMatrix.M[2][0], TestMatrix.M[2][1], TestMatrix.M[2][2], TestMatrix.M[2][3], 
		TestMatrix.M[3][0], TestMatrix.M[3][1], TestMatrix.M[3][2], TestMatrix.M[3][3]
		);

	UE_LOG(LogLightmass, Display, TEXT("sizeof FDirectionalLight = %d, FLight = %d, FDirectionalLightData = %d"), sizeof(FDirectionalLight), sizeof(FLight), sizeof(FDirectionalLightData));

	TOctree<float, FTestOctreeSemantics> TestOctree(FVector4(0), 10.0f);
	TestOctree.AddElement(5);


	// kDOP test
	TkDOPTree<FTestCollisionDataProvider, uint16> TestkDOP;
	FTestCollisionDataProvider TestDataProvider(TestkDOP);
	FHitResult TestResult;
	
	FkDOPBuildCollisionTriangle<uint16> TestTri(0, FVector4(0,0,0,0), FVector4(1,1,1,0), FVector4(2,2,2,0), INDEX_NONE, INDEX_NONE, INDEX_NONE, false, true);
	TArray<FkDOPBuildCollisionTriangle<uint16> > TestTriangles;
	TestTriangles.Add(TestTri);

	TestkDOP.Build(TestTriangles);
	
	UE_LOG(LogLightmass, Display, TEXT("\nStarting a thread"));
	FTestRunnable* TestRunnable = new FTestRunnable;
	// create a thread with the test runnable, and let it auto-delete itself
	FRunnableThread* TestThread = FRunnableThread::Create(TestRunnable, TEXT("TestRunnable"));


	double Start = FPlatformTime::Seconds();
	UE_LOG(LogLightmass, Display, TEXT("\nWaiting 4 seconds"), Start);
	FPlatformProcess::Sleep(4.0f);
	UE_LOG(LogLightmass, Display, TEXT("%.2f seconds have passed, killing thread"), FPlatformTime::Seconds() - Start);
	
	// wait for thread to end
	double KillStart = FPlatformTime::Seconds();
	TestRunnable->Stop();
	TestThread->WaitForCompletion();
		
	delete TestThread;
	delete TestRunnable;
	
	UE_LOG(LogLightmass, Display, TEXT("It took %.2f seconds to kill the thread [should be < 1 second]"), FPlatformTime::Seconds() - KillStart);


	UE_LOG(LogLightmass, Display, TEXT("\n\n"));

	checkf(5 == 2, TEXT("And boom goes the dynamite\n"));
}
示例#10
0
int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
 	// TODO: Place code here.
	WNDCLASS  cs;
	cs.cbClsExtra =0;
	cs.cbWndExtra = 0;
	cs.hbrBackground = (HBRUSH)(COLOR_WINDOW +1);//°×É«±³¾°
	cs.hCursor       = LoadCursor(NULL,IDC_CROSS);
	cs.hIcon         = LoadIcon(NULL,IDI_APPLICATION);
	cs.hInstance  = hInstance;
	cs.lpszClassName = "CircleLine";
	cs.lpszMenuName = NULL;
	cs.style = CS_OWNDC;
	cs.lpfnWndProc =(WNDPROC) MyWndProc;
	if(!RegisterClass(&cs))
	{
		MessageBox(NULL,"Register window class error","Error",MB_OK);
	}
    int  x = 	GetSystemMetrics(SM_CXSCREEN);
	int  y =    GetSystemMetrics(SM_CYSCREEN);
   HWND hWindowHandle =	CreateWindowEx(WS_EX_CLIENTEDGE|WS_EX_OVERLAPPEDWINDOW,"CircleLine","Lab1",
	              WS_OVERLAPPEDWINDOW ,x/2,y/2,800,600,NULL,NULL,NULL,NULL);
   _ASSERT(hWindowHandle != NULL);
   g_hwnd = hWindowHandle;
   g_hdc = GetDC(g_hwnd);

   Init();

   ShowWindow(hWindowHandle,nCmdShow);
   UpdateWindow(hWindowHandle);
#ifdef _DEBUG
   TestVector();
   TestMatrix();
#endif
  
   MSG  msg;
   while(1)
   {
	   if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))
	   { 
		   // test if this is a quit
		   if (msg.message == WM_QUIT)
			   break;

		   // translate any accelerator keys
		   TranslateMessage(&msg);

		   // send the message to the window proc
		   DispatchMessage(&msg);
	   } // end if

	   // main game processing goes here
	  // Render();
	   //LOCAL rotation
	   main_logic(hWindowHandle);

   } // end whi
  
 
	return msg.wParam;
}
示例#11
0
int main(int argc,char **args)
{
    const PetscScalar xvals[] = {11,13},yvals[] = {17,19},zvals[] = {23,29};
    const PetscInt    inds[]  = {0,1};
    PetscScalar       avals[] = {2,3,5,7};
    Mat               A,S,D[4],N;
    Vec               X,Y,Z;
    User              user;
    PetscInt          i;
    PetscErrorCode    ierr;

    PetscInitialize(&argc,&args,(char*)0,help);
    ierr = MatCreateSeqAIJ(PETSC_COMM_WORLD,2,2,2,NULL,&A);
    CHKERRQ(ierr);
    ierr = MatSetUp(A);
    CHKERRQ(ierr);
    ierr = MatSetValues(A,2,inds,2,inds,avals,INSERT_VALUES);
    CHKERRQ(ierr);
    ierr = VecCreateSeq(PETSC_COMM_WORLD,2,&X);
    CHKERRQ(ierr);
    ierr = VecDuplicate(X,&Y);
    CHKERRQ(ierr);
    ierr = VecDuplicate(X,&Z);
    CHKERRQ(ierr);
    ierr = VecSetValues(X,2,inds,xvals,INSERT_VALUES);
    CHKERRQ(ierr);
    ierr = VecSetValues(Y,2,inds,yvals,INSERT_VALUES);
    CHKERRQ(ierr);
    ierr = VecSetValues(Z,2,inds,zvals,INSERT_VALUES);
    CHKERRQ(ierr);
    ierr = MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
    CHKERRQ(ierr);
    ierr = MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
    CHKERRQ(ierr);
    ierr = VecAssemblyBegin(X);
    CHKERRQ(ierr);
    ierr = VecAssemblyBegin(Y);
    CHKERRQ(ierr);
    ierr = VecAssemblyBegin(Z);
    CHKERRQ(ierr);
    ierr = VecAssemblyEnd(X);
    CHKERRQ(ierr);
    ierr = VecAssemblyEnd(Y);
    CHKERRQ(ierr);
    ierr = VecAssemblyEnd(Z);
    CHKERRQ(ierr);

    ierr    = PetscNew(struct _n_User,&user);
    CHKERRQ(ierr);
    user->B = A;

    ierr = MatCreateShell(PETSC_COMM_WORLD,2,2,2,2,user,&S);
    CHKERRQ(ierr);
    ierr = MatSetUp(S);
    CHKERRQ(ierr);
    ierr = MatShellSetOperation(S,MATOP_MULT,(void (*)(void))MatMult_User);
    CHKERRQ(ierr);
    ierr = MatShellSetOperation(S,MATOP_MULT_TRANSPOSE,(void (*)(void))MatMultTranspose_User);
    CHKERRQ(ierr);
    ierr = MatShellSetOperation(S,MATOP_GET_DIAGONAL,(void (*)(void))MatGetDiagonal_User);
    CHKERRQ(ierr);

    for (i=0; i<4; i++) {
        ierr = MatCreateSeqDense(PETSC_COMM_WORLD,1,1,&avals[i],&D[i]);
        CHKERRQ(ierr);
    }
    ierr = MatCreateNest(PETSC_COMM_WORLD,2,NULL,2,NULL,D,&N);
    CHKERRQ(ierr);
    ierr = MatSetUp(N);
    CHKERRQ(ierr);

    ierr = TestMatrix(S,X,Y,Z);
    CHKERRQ(ierr);
    ierr = TestMatrix(A,X,Y,Z);
    CHKERRQ(ierr);
    ierr = TestMatrix(N,X,Y,Z);
    CHKERRQ(ierr);

    for (i=0; i<4; i++) {
        ierr = MatDestroy(&D[i]);
        CHKERRQ(ierr);
    }
    ierr = MatDestroy(&A);
    CHKERRQ(ierr);
    ierr = MatDestroy(&S);
    CHKERRQ(ierr);
    ierr = MatDestroy(&N);
    CHKERRQ(ierr);
    ierr = VecDestroy(&X);
    CHKERRQ(ierr);
    ierr = VecDestroy(&Y);
    CHKERRQ(ierr);
    ierr = VecDestroy(&Z);
    CHKERRQ(ierr);
    ierr = PetscFree(user);
    CHKERRQ(ierr);
    ierr = PetscFinalize();
    return 0;
}
示例#12
0
文件: main.cpp 项目: samindaa/MLLib
void testConvolutionAndPool()
{
  if (true)
  {
    const int filterDim = 8;
    const int imageDim = 28;
    const int poolDim = 3;
    const int numFilters = 100;
    const int outputDim = (imageDim - filterDim + 1) / poolDim;
    RandomFilterFunction rff(filterDim, numFilters);
    rff.configure();

    SigmoidFunction sf;
    ConvolutionFunction cf(&rff, &sf);
    MeanPoolFunction pf(numFilters, outputDim);
    //MeanPoolFunction mpf;
    Eigen::Vector2i configImageDim;
    configImageDim << imageDim, imageDim;

    MNISTDataFunction mnistdf;
    Config config;
    updateMNISTConfig(config);
    config.setValue("addBiasTerm", false);
    config.setValue("meanStddNormalize", false);

    mnistdf.configure(&config);

    Convolutions* convolvedFeatures = nullptr;
    for (int i = 0; i < 13; ++i)
      convolvedFeatures = cf.conv(mnistdf.getTrainingX().topRows<199>(), configImageDim);

    assert(convolvedFeatures->unordered_map.size() == 199);
    for (auto i = convolvedFeatures->unordered_map.begin();
        i != convolvedFeatures->unordered_map.end(); ++i)
      assert((int )i->second.size() == rff.getWeights().cols());

    // Validate convoluations
    Matrix_t ConvImages = mnistdf.getTrainingX().topRows<8>();
    for (int i = 0; i < 1000; ++i)
    {
      const int filterNum = rand() % rff.getWeights().cols();
      const int imageNum = rand() % 8;
      const int imageRow = rand() % (configImageDim(0) - rff.getConfig()(0) + 1);
      const int imageCol = rand() % (configImageDim(1) - rff.getConfig()(1) + 1);

      Vector_t im = ConvImages.row(imageNum);
      Eigen::Map<Matrix_t> Image(im.data(), configImageDim(0), configImageDim(1));

      Matrix_t Patch = Image.block(imageRow, imageCol, rff.getConfig()(0), rff.getConfig()(1));

      // Filter
      Eigen::Map<Matrix_t> W(rff.getWeights().col(filterNum).data(), rff.getConfig()(0),
          rff.getConfig()(1));
      const double b = rff.getBiases()(filterNum);

      double feature = Patch.cwiseProduct(W).sum() + b;
      feature = 1.0f / (1.0f + exp(-feature));

      if (fabs(
          feature - convolvedFeatures->unordered_map[imageNum][filterNum]->X(imageRow, imageCol))
          > 1e-9)
      {
        std::cout << "Convolved feature does not match test feature: " << i << std::endl;
        std::cout << "Filter Number: " << filterNum << std::endl;
        std::cout << "Image Number: " << imageNum << std::endl;
        std::cout << "Image Row: " << imageRow << std::endl;
        std::cout << "Image Col: " << imageCol << std::endl;
        std::cout << "Convolved feature: "
            << convolvedFeatures->unordered_map[imageNum][filterNum]->X(imageRow, imageCol)
            << std::endl;
        std::cout << "Test feature: " << feature << std::endl;
        std::cout << "Convolved feature does not match test feature" << std::endl;
        exit(EXIT_FAILURE);
      }

    }

    // Pool
    Poolings* pooling = nullptr;
    for (int i = 0; i < 13; ++i)
      pooling = pf.pool(convolvedFeatures, poolDim);

    assert((int )pooling->unordered_map.size() == 199);
    for (auto iter = pooling->unordered_map.begin(); iter != pooling->unordered_map.end(); ++iter)
    {
      assert(iter->second.size() == (size_t )rff.getWeights().cols());
      for (auto iter2 = iter->second.begin(); iter2 != iter->second.end(); ++iter2)
      {
        assert(iter2->second->X.rows() == (configImageDim(0) - rff.getConfig()(0) + 1) / 3);
        assert(iter2->second->X.rows() == 7);
        assert(iter2->second->X.cols() == (configImageDim(0) - rff.getConfig()(0) + 1) / 3);
        assert(iter2->second->X.cols() == 7);
      }
    }

  }

  if (true)
  {
    // test pool function

    Vector_t testVec(64);
    for (int i = 0; i < testVec.size(); ++i)
      testVec(i) = i + 1;
    Eigen::Map<Matrix_t> TestMatrix(testVec.data(), 8, 8);

    std::cout << "TestMatrix: " << std::endl;
    std::cout << TestMatrix << std::endl;

    Matrix_t ExpectedMatrix(2, 2);
    ExpectedMatrix(0, 0) = TestMatrix.block(0, 0, 4, 4).array().mean();
    ExpectedMatrix(0, 1) = TestMatrix.block(0, 4, 4, 4).array().mean();
    ExpectedMatrix(1, 0) = TestMatrix.block(4, 0, 4, 4).array().mean();
    ExpectedMatrix(1, 1) = TestMatrix.block(4, 4, 4, 4).array().mean();

    std::cout << "Expected: " << std::endl;
    std::cout << ExpectedMatrix << std::endl;

    Convolutions cfs;
    Convolution xcf;
    xcf.X = TestMatrix;
    cfs.unordered_map[0].insert(std::make_pair(0, (&xcf)));

    MeanPoolFunction testMpf(1, 2);
    Poolings* pfs = testMpf.pool(&cfs, 4);

    assert(pfs->unordered_map.size() == 1);
    assert(pfs->unordered_map[0].size() == 1);
    Matrix_t PX = pfs->unordered_map[0][0]->X;

    std::cout << "Obtain: " << std::endl;
    std::cout << PX << std::endl;
  }

}
示例#13
0
double ON_SubDMatrix::TestEvaluation() const
{
  if ( nullptr == m_S || m_R < 3 )
    return ON_SUBD_RETURN_ERROR(ON_UNSET_VALUE);

  if (!m_sector_type.IsValid())
    return ON_SUBD_RETURN_ERROR(ON_UNSET_VALUE);

  const ON_SubD::SubDType subd_type = m_sector_type.SubDType();
  //ON_SubD::VertexTag center_vertex_tag = m_sector_type.VertexTag();

  const unsigned int F = m_sector_type.FaceCount();
  if (0 == F)
    return ON_SUBD_RETURN_ERROR(ON_UNSET_VALUE);

  const unsigned int N = m_sector_type.EdgeCount();
  if (0 == N)
    return ON_SUBD_RETURN_ERROR(ON_UNSET_VALUE);

  const unsigned int R = m_sector_type.PointRingCount();
  if (0 == R)
    return ON_SUBD_RETURN_ERROR(ON_UNSET_VALUE);
  if (R != m_R)
    return ON_SUBD_RETURN_ERROR(ON_UNSET_VALUE);
  
  const unsigned f_edge_count = m_sector_type.FacetEdgeCount();
  if (0 == f_edge_count)
    return ON_SUBD_RETURN_ERROR(ON_UNSET_VALUE);

  double rc = TestMatrix();
  const double*const* S = m_S;
  
  unsigned int SP_low_precision_index = ON_UNSET_UINT_INDEX;
  
  ON_SimpleArray< ON_3dPoint > _P(R);
  ON_3dPoint* SP = _P.Array();

  ON_SimpleArray< double > _Scol(R);
  double* Scol = _Scol.Array();

  ON_SubD subd;
  if (&subd != m_sector_type.SectorRingSubD(0.0,0.0,&subd))
    return ON_SUBD_RETURN_ERROR(ON_UNSET_VALUE);
  const ON_SubDVertex* vertex0 = subd.FirstVertex();
  if (nullptr == vertex0)
    return ON_SUBD_RETURN_ERROR(ON_UNSET_VALUE);
  if (N != vertex0->m_edge_count)
    return ON_SUBD_RETURN_ERROR(ON_UNSET_VALUE);
  if (F != vertex0->m_face_count)
    return ON_SUBD_RETURN_ERROR(ON_UNSET_VALUE);
  
  ON_SubDSectorIterator sit;
  if ( nullptr == sit.Initialize(vertex0) )
    return ON_SUBD_RETURN_ERROR(ON_UNSET_VALUE);

  ON_SimpleArray<const ON_SubDVertex*> vertex_ring_array(subd.VertexCount());
  for (const ON_SubDVertex* vertex = vertex0; nullptr != vertex; vertex = vertex->m_next_vertex)
  {
    vertex_ring_array.Append(vertex);
  }
  if ( R != vertex_ring_array.UnsignedCount())
    return ON_SUBD_RETURN_ERROR(ON_UNSET_VALUE);
  const ON_SubDVertex*const* vertex_ring = vertex_ring_array.Array();

  ON_SimpleArray<ON_SubDComponentPtr> component_ring_array;
  const unsigned int component_ring_count = ON_SubD::GetSectorComponentRing(sit,component_ring_array);
  if ( component_ring_count < 4 || component_ring_count != m_sector_type.ComponentRingCount())
    return ON_SUBD_RETURN_ERROR(ON_UNSET_VALUE);
  const ON_SubDComponentPtr* component_ring = component_ring_array.Array();

  ON_SimpleArray< ON_3dPoint > _ringP0;

  ON_SimpleArray< ON_3dPoint > _ringP1;

  for (unsigned int vi = 0; vi < R; vi++)
    Scol[vi] = ON_DBL_QNAN;

  for (unsigned int vi = 0; vi < R; vi++)
  {
    double N_vertex_point_precision[3] = { 0 };
    double N_outer_point_precision[3] = { 0 };
    double N_Scol_precision[3] = { 0 };

    for (unsigned int Pi = 0; Pi < 3; Pi++)
    {
      if (false == ClearCachedPoints(component_ring_count,component_ring))
        return ON_SUBD_RETURN_ERROR(ON_UNSET_VALUE);

      const_cast<ON_SubDVertex*>(vertex_ring[vi])->m_P[Pi] = 1.0;

      if ( R != ON_SubD::GetSectorPointRing(subd_type,false,component_ring_count,component_ring,_ringP0))
        return ON_SUBD_RETURN_ERROR(ON_UNSET_VALUE);
      const ON_3dPoint* ringP0 = _ringP0.Array();

      // vertex_ring[]->m_P and ringP0[] should be same point lists
      for (unsigned int i = 0; i < R; i++)
      {
        if (0.0 == ringP0[i][(Pi+1)%3] && 0.0 == ringP0[i][(Pi+2)%3])
        {
          if ( ringP0[i][Pi] == ((i == vi) ? 1.0 : 0.0) )
            continue;
        }
        // vertex_ring[] is not in the expected order or
        // there is a bug in ON_SubD::GetSectorPointRing
        return ON_SUBD_RETURN_ERROR(ON_UNSET_VALUE);
      }

      if ( R != ON_SubD::GetSectorSubdivisionPointRing(subd_type,component_ring_count,component_ring,_ringP1))
        return ON_SUBD_RETURN_ERROR(ON_UNSET_VALUE);
      const ON_3dPoint* ringP1 = _ringP1.Array();

      for (unsigned int i = 0; i < R; i++)
      {
        SP[i] = ON_3dPoint::Origin;
        for (unsigned int j = 0; j < R; j++)
        {
          SP[i] += S[i][j] * ringP0[j];
        }
      }

      if (!(SP[vi][Pi] > 0.0))
      {
        // ON_ERROR("SP[vi][Pi] is not positive.");
        return ON_SUBD_RETURN_ERROR(ON_UNSET_VALUE);
      }

      if (false == TestPoint(SP, 0, ringP1[0], Pi, N_vertex_point_precision, &SP_low_precision_index))
        return ON_SUBD_RETURN_ERROR(ON_UNSET_VALUE);

      for (unsigned int j = 1; j < R; j++)
      {
        if (false == TestPoint(SP, j, ringP1[j], Pi, N_outer_point_precision, &SP_low_precision_index))
          return ON_SUBD_RETURN_ERROR(ON_UNSET_VALUE);
      }

      for (unsigned int i = 0; i < R; i++)
      {
        double d = fabs(S[i][vi] - ringP1[i][Pi]);
        if (d > N_Scol_precision[Pi])
          N_Scol_precision[Pi] = d;
      }

      if (!(N_vertex_point_precision[0] == N_vertex_point_precision[Pi]))
      {
        ON_ERROR("x,y,z vertex point precisions are not identical.");
        return ON_SUBD_RETURN_ERROR(ON_UNSET_VALUE);
      }
      if (!(N_outer_point_precision[0] == N_outer_point_precision[Pi]))
      {
        ON_ERROR("x,y,z outer point precisions are not identical.");
        return ON_SUBD_RETURN_ERROR(ON_UNSET_VALUE);
      }
      if (!(N_Scol_precision[0] == N_Scol_precision[Pi]))
      {
        ON_ERROR("x,y,z S column precisions are not identical.");
        return ON_SUBD_RETURN_ERROR(ON_UNSET_VALUE);
      }

      if (rc < N_vertex_point_precision[0])
        rc = N_vertex_point_precision[0];
      if (rc < N_outer_point_precision[0])
        rc = N_outer_point_precision[0];
      if (rc < N_Scol_precision[0])
        rc = N_Scol_precision[0];

      const_cast<ON_SubDVertex*>(vertex_ring[vi])->m_P[Pi] = 0.0;
    }
  }

  return rc; // basic tests passed.
}
示例#14
0
void RotationConverter::R2AnglesRxRyRz(const Matrix &R, double &Rx, double &Ry, double &Rz){

   double r1 = R(0,0);
   double r2 = R(0,1);
   double r3 = R(0,2);
   double r4 = R(1,0);
   double r5 = R(1,1);
   double r6 = R(1,2);
   double r9 = R(2,2);

   double r3Abs = (r3>0.0 ? r3:-r3);
   if( (1.0 - r3Abs) > NUM_PRECISION_DOUBLE ){

 
      Ry = asin(r3);

      if( (r9>0.0?r9:-r9) > NUM_PRECISION_DOUBLE){
         Rx = atan(-r6/r9);
      }else{
         Rx = PI/2.0;
         if(r6 > 0.0) Rx = -Rx;
      }

      if( (r1>0.0?r1:-r1) > NUM_PRECISION_DOUBLE){
         Rz = atan(-r2/r1);
      }else{
         Rz = PI/2.0;
         if(r2 > 0.0) Rz = -Rz;
      }


      double RxAltern[2];
      double RyAltern[2];
      double RzAltern[2];


      RxAltern[0] = Rx;
      RyAltern[0] = Ry;
      RzAltern[0] = Rz;

      if(Rx > 0.0) RxAltern[1] =  Rx - PI;
      else         RxAltern[1] =  Rx + PI;
      if(Ry > 0.0) RyAltern[1] =  PI - Ry;
      else         RyAltern[1] = -PI - Ry;
      if(Rz > 0.0) RzAltern[1] =  Rz - PI;
      else         RzAltern[1] =  Rz + PI;


        enum {MaxIsRx, MaxIsRy, MaxIsRz};

      int Max = MaxIsRx;
      double MaxVal = (Rx>0.0?Rx:-Rx);
   
      if( (Ry>0.0?Ry:-Ry) > MaxVal){
         Max = MaxIsRy;
         MaxVal = (Ry>0.0?Ry:-Ry);
      }
      if( (Rz>0.0?Rz:-Rz) > MaxVal ){
         Max = MaxIsRz;
         MaxVal = (Rz>0.0?Rz:-Rz);
      }

      Matrix TestMatrix(3,3);
      Matrix RxTestMatrix(3,3);
      Matrix RyTestMatrix(3,3);
      Matrix RzTestMatrix(3,3);
   
      double ErrorHypothesis[2];  
   
      double SinRx, SinRy, SinRz;
      double CosRx, CosRy, CosRz;

     
      for(int Hypothesis = 0; Hypothesis<2; Hypothesis++){

         switch(Max){

         case MaxIsRx :

            SinRx = sin(RxAltern[Hypothesis]);
            CosRx = cos(RxAltern[Hypothesis]);

    
            if( (SinRx>0.0?SinRx:-SinRx) < NUM_PRECISION_DOUBLE ){
               CosRy =  r9/CosRx;
            }else{
               CosRy = -r6/SinRx;
            }
            SinRy = r3;

            GetAngle(SinRy, CosRy, RyAltern[Hypothesis]);

            SinRz = -r2/CosRy;
            CosRz =  r1/CosRy;

            GetAngle(SinRz, CosRz, RzAltern[Hypothesis]);

            break;

         case MaxIsRy :

  
            SinRy = sin(RyAltern[Hypothesis]);
            CosRy = cos(RyAltern[Hypothesis]);

 
            SinRz = -r2/CosRy;
            CosRz =  r1/CosRy;

            GetAngle(SinRz, CosRz, RzAltern[Hypothesis]);


            SinRx = -r6/CosRy;
            CosRx =  r9/CosRy;

            GetAngle(SinRx, CosRx, RxAltern[Hypothesis]);

            break;

         case MaxIsRz :

            
            SinRz = sin(RzAltern[Hypothesis]);
            CosRz = cos(RzAltern[Hypothesis]);
            if( (SinRz>0.0?SinRz:-SinRz) < NUM_PRECISION_DOUBLE ){
               CosRy =  r1/CosRz;
            }else{
               CosRy = -r2/SinRz;
            }
            SinRy = r3;

            GetAngle(SinRy, CosRy, RyAltern[Hypothesis]);
            SinRx = -r6/CosRy;
            CosRx =  r9/CosRy;

            GetAngle(SinRx, CosRx, RxAltern[Hypothesis]);

            break;

         }

         RxTestMatrix.I();
         RyTestMatrix.I();
         RzTestMatrix.I();

         RxTestMatrix(1,1) = cos(RxAltern[Hypothesis]);
         RxTestMatrix(2,2) = RxTestMatrix(1,1);
         RxTestMatrix(2,1) = sin(RxAltern[Hypothesis]);
         RxTestMatrix(1,2) = -RxTestMatrix(2,1);
         RyTestMatrix(0,0) = cos(RyAltern[Hypothesis]);
         RyTestMatrix(2,2) = RyTestMatrix(0,0);
         RyTestMatrix(0,2) = sin(RyAltern[Hypothesis]);
         RyTestMatrix(2,0) = -RyTestMatrix(0,2);
         RzTestMatrix(0,0) = cos(RzAltern[Hypothesis]);
         RzTestMatrix(1,1) = RzTestMatrix(0,0);
         RzTestMatrix(1,0) = sin(RzAltern[Hypothesis]);
         RzTestMatrix(0,1) = -RzTestMatrix(1,0);

         TestMatrix = RxTestMatrix*RyTestMatrix*RzTestMatrix;

         TestMatrix -= R;

         double Err = 0.0;
         for(int i=0; i<3; i++){
            for(int j=0; j<3; j++){
               Err += TestMatrix(i,j)*TestMatrix(i,j);
            }
         }
         ErrorHypothesis[Hypothesis] = Err;
      
      }

      double ErrorDiff = ErrorHypothesis[0]-ErrorHypothesis[1];

      if( (ErrorDiff>0.0?ErrorDiff:-ErrorDiff) < NUM_PRECISION_DOUBLE ){

         double SumAngles[2] = {0.0, 0.0};
         for(int i=0; i<2; i++){
            SumAngles[i] += (RxAltern[i]>0.0)?RxAltern[i]:-RxAltern[i];
            SumAngles[i] += (RyAltern[i]>0.0)?RyAltern[i]:-RyAltern[i];
            SumAngles[i] += (RzAltern[i]>0.0)?RzAltern[i]:-RzAltern[i];
         }
         int GoodAlt = 0;
         if(SumAngles[1] < SumAngles[0]) GoodAlt = 1;
         Rx = RxAltern[GoodAlt];
         Ry = RyAltern[GoodAlt];
         Rz = RzAltern[GoodAlt];

      }else{
         
         //One of the two hypothesis is good. Let's choose the best one.
         int GoodAlt = 0;
         if(ErrorHypothesis[1] < ErrorHypothesis[0]) GoodAlt = 1;
         Rx = RxAltern[GoodAlt];
         Ry = RyAltern[GoodAlt];
         Rz = RzAltern[GoodAlt];

      }

   }else{
      
     
      if(r3>0.0){
         Ry =  PI/2.0;
         if( (r5>0.0?r5:-r5) > NUM_PRECISION_DOUBLE){
            Rx = atan2(r4,r5);
         }else{
            if( r4>0.0) Rx =  PI/2.0;
            else        Rx = -PI/2.0;
         }
      }else{
         Ry = -PI/2.0;
         if( (r5>0.0?r5:-r5) > NUM_PRECISION_DOUBLE){
            Rx = atan2(-r4,r5);
         }else{
            if(-r4>0.0) Rx =  PI/2.0;
            else        Rx = -PI/2.0;
         }
      }

      Rz = 0.0;
   
   }

}
示例#15
0
TestAsFPArgs::TestAsFPArgs(GrProcessorTestData* d)
    : fViewMatrixStorage(TestMatrix(d->fRandom))
    , fColorSpaceInfoStorage(skstd::make_unique<GrColorSpaceInfo>(TestColorSpace(d->fRandom),
                                                                  kRGBA_8888_GrPixelConfig))
    , fArgs(d->context(), &fViewMatrixStorage, kNone_SkFilterQuality, fColorSpaceInfoStorage.get())
{}
void Chapter1Test::Test1_7() {
  ofstream fout;
  OpenLogFile(fout,"test1_7.html","Problem 1.7: compress a string by counting consecutive chars");


  vector<vector<int> > matrix, expected;
  stringstream input;

  tools.GenerateNewMatrix(matrix, {0}, 0, 0);
  tools.GenerateNewMatrix(expected, {0}, 0, 0);
  input.str("");
  tools.PrintMatrix2File(matrix, input);
  sol.prob1_7(matrix);
  TestMatrix(fout, input.str(), matrix, expected);

  tools.GenerateNewMatrix(matrix, {1}, 1, 1);
  tools.GenerateNewMatrix(expected, {1}, 1, 1);
  input.str("");
  tools.PrintMatrix2File(matrix, input);
  sol.prob1_7(matrix);
  TestMatrix(fout, input.str(), matrix, expected);

  tools.GenerateNewMatrix(matrix, {1,2,3,4,0,6,7}, 7, 1);
  tools.GenerateNewMatrix(expected, {0,0,0,0,0,0,0}, 7, 1);
  input.str("");
  tools.PrintMatrix2File(matrix, input);
  sol.prob1_7(matrix);
  TestMatrix(fout, input.str(), matrix, expected);

  tools.GenerateNewMatrix(matrix, {1,2,3,4,0,6,7}, 1, 7);
  tools.GenerateNewMatrix(expected, {0,0,0,0,0,0,0}, 1, 7);
  input.str("");
  tools.PrintMatrix2File(matrix, input);
  sol.prob1_7(matrix);
  TestMatrix(fout, input.str(), matrix, expected);

  tools.GenerateNewMatrix(matrix, {1,2,3,4}, 2, 2);
  tools.GenerateNewMatrix(expected, {1,2,3,4}, 2, 2);
  input.str("");
  tools.PrintMatrix2File(matrix, input);
  sol.prob1_7(matrix);
  TestMatrix(fout, input.str(), matrix, expected);

  tools.GenerateNewMatrix(matrix, {1,2,3,0}, 2, 2);
  tools.GenerateNewMatrix(expected, {1,0,0,0}, 2, 2);
  input.str("");
  tools.PrintMatrix2File(matrix, input);
  sol.prob1_7(matrix);
  TestMatrix(fout, input.str(), matrix, expected);

  tools.GenerateNewMatrix(matrix, {0,0,0,0,0,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25}, 5, 5);
  tools.GenerateNewMatrix(expected, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, 5, 5);
  input.str("");
  tools.PrintMatrix2File(matrix, input);
  sol.prob1_7(matrix);
  TestMatrix(fout, input.str(), matrix, expected);

  tools.GenerateNewMatrix(matrix, {0,2,3,4,5,6,7,8,0,10,0,0,13,14,15,16,0,18,19,0,21,22,23,24,25}, 5, 5);
  tools.GenerateNewMatrix(expected, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,23,0,0}, 5, 5);
  input.str("");
  tools.PrintMatrix2File(matrix, input);
  sol.prob1_7(matrix);
  TestMatrix(fout, input.str(), matrix, expected);

  CloseLogFile(fout);
}
示例#17
0
int main()
{
  TestMatrix(cout);
  return 0;
}