/// CONFIGURABLE INTERFACE
 void AbstractIAFController::notifyOnChange(const paramkey& key){
   if(key=="thresholdi") {
     tI.toZero().toSum((*conf.thresholdI)*sqrt(*conf.numberIAFNeuronsPerInput));
   } else if (key=="thresholdo") {
     tO.toZero().toSum((*conf.thresholdO)*sqrt(*conf.numberIAFNeuronsPerOutput));
   } else if(key=="wiinitscale") {
       wI.toId().toMult(*conf.wIInitScale); // scale
   } else if(key=="woinitscale") {
     wI.toId().toMult(*conf.wOInitScale); // scale
   } else if(key=="niafperinput") {
     initMatrices();
   } else if(key=="niafperoutput") {
     initMatrices();
   }
 }
Ejemplo n.º 2
0
bool OpenGL::initContext()
{
	if (contextInitialized)
		return true;

	if (!gladLoadGLLoader(LOVEGetProcAddress))
		return false;

	initOpenGLFunctions();
	initVendor();
	initMatrices();

	bugs = {};

#if defined(LOVE_WINDOWS) || defined(LOVE_LINUX)
	// See the comments in OpenGL.h.
	if (getVendor() == VENDOR_AMD)
	{
		bugs.clearRequiresDriverTextureStateUpdate = true;
		bugs.generateMipmapsRequiresTexture2DEnable = true;
	}
#endif

	contextInitialized = true;

	return true;
}
Ejemplo n.º 3
0
void StressMinimization::call(GraphAttributes& GA)
{
	const Graph& G = GA.constGraph();
	// if the graph has at most one node nothing to do
	if (G.numberOfNodes() <= 1) {
		// make it exception save
		for(node v : G.nodes)
		{
			GA.x(v) = 0;
			GA.y(v) = 0;
		}
		return;
	}
	if (m_componentLayout && !isConnected(G)) {
		OGDF_THROW(PreconditionViolatedException);
		return;
	}
	NodeArray<NodeArray<double> > shortestPathMatrix(G);
	NodeArray<NodeArray<double> > weightMatrix(G);
	initMatrices(G, shortestPathMatrix, weightMatrix);
	// if the edge costs are defined by the attribute copy it to an array and
	// construct the proper shortest path matrix
	if (m_hasEdgeCostsAttribute) {
		if (!GA.has(GraphAttributes::edgeDoubleWeight)) {
			OGDF_THROW(PreconditionViolatedException);
			return;
		}
		m_avgEdgeCosts = dijkstra_SPAP(GA, shortestPathMatrix);
		// compute shortest path all pairs
	} else {
		m_avgEdgeCosts = m_edgeCosts;
		bfs_SPAP(G, shortestPathMatrix, m_edgeCosts);
	}
	call(GA, shortestPathMatrix, weightMatrix);
}
Ejemplo n.º 4
0
/* ************************************************************************ */
int
main (int argc, char** argv)
{
	struct options options;
	struct calculation_arguments arguments;
	struct calculation_results results;

	/* get parameters */
	AskParams(&options, argc, argv);              /* ************************* */

	initVariables(&arguments, &results, &options);           /* ******************************************* */

	allocateMatrices(&arguments);        /*  get and initialize variables and matrices  */
	initMatrices(&arguments, &options);            /* ******************************************* */
	
	pthread_barrier_init(&loop_barrier, NULL, options.number+1);	/* init der Loop-Barriere */

	gettimeofday(&start_time, NULL);                   /*  start timer         */
	calculate(&arguments, &results, &options);                                      /*  solve the equation  */
	gettimeofday(&comp_time, NULL);                   /*  stop timer          */

	displayStatistics(&arguments, &results, &options);
	DisplayMatrix(&arguments, &results, &options);

	freeMatrices(&arguments);                                       /*  free memory     */

	return 0;
}
Ejemplo n.º 5
0
/* ************************************************************************ */
int
main (int argc, char** argv)
{
	struct options options;
	struct mpi_options mpi_options;
	struct calculation_arguments arguments;
	struct calculation_results results;
	
	initMpi(&mpi_options, &argc, &argv);
	/* get parameters */
	AskParams(&options, argc, argv, mpi_options.mpi_rank == 0);              /* ************************* */

	initVariables(&arguments, &results, &options, &mpi_options);           /* ******************************************* */
	allocateMatrices(&arguments);        /*  get and initialize variables and matrices  */
	initMatrices(&arguments, &options);            /* ******************************************* */

	gettimeofday(&start_time, NULL);                   /*  start timer         */
	calculate(&arguments, &results, &options, &mpi_options);                                      /*  solve the equation  */
	gettimeofday(&comp_time, NULL);                   /*  stop timer          */

	if(mpi_options.mpi_rank == 0) displayStatistics(&arguments, &results, &options);
	DisplayMatrix(&arguments, &results, &options, mpi_options.mpi_rank, mpi_options.mpi_size, arguments.row_start, arguments.row_end);

	freeMatrices(&arguments);                                       /*  free memory     */

	MPI_Finalize();
	return 0;
}
Ejemplo n.º 6
0
/* ************************************************************************ */
int
main (int argc, char** argv)
{
	struct options options;
	struct calculation_arguments arguments;
	struct calculation_results results; 

	/* get parameters */
	AskParams(&options, argc, argv);              /* ************************* */

	initVariables(&arguments, &results, &options);           /* ******************************************* */

	allocateMatrices(&arguments);        /*  get and initialize variables and matrices  */
	initMatrices(&arguments, &options);            /* ******************************************* */

	gettimeofday(&start_time, NULL);                   /*  start timer         */
	calculate(&arguments, &results, &options);                                      /*  solve the equation  */
	gettimeofday(&comp_time, NULL);                   /*  stop timer          */

	displayStatistics(&arguments, &results, &options);                                  /* **************** */
	DisplayMatrix("Matrix:",                              /*  display some    */
			arguments.Matrix[results.m][0], options.interlines);            /*  statistics and  */

	freeMatrices(&arguments);                                       /*  free memory     */

	return 0;
}
Ejemplo n.º 7
0
int main (int argc, char** argv) {
	
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_RGBA|GLUT_DOUBLE|GLUT_DEPTH);
	glutInitWindowSize(800, 600);
	glutCreateWindow("Index Buffers");
	glutReshapeFunc(changeViewport);
	glutDisplayFunc(render);
	glewInit();

	/*set up the matricies*/
	initMatrices(); 

	// Make a shader
	shaderProgramID = createShaders();

	glGenVertexArrays(1, &vao);
	glBindVertexArray(vao);
	
	glGenBuffers(1, &vbo);
	glBindBuffer(GL_ARRAY_BUFFER, vbo);

	// Create the buffer, but don't load anything yet
	glBufferData(GL_ARRAY_BUFFER, sizeof(colors)*sizeof(vertices), NULL, GL_STATIC_DRAW);
	// Load the vertex points
	glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices); 
	// Load the colors right after that
	glBufferSubData(GL_ARRAY_BUFFER, sizeof(vertices),sizeof(colors), colors);
	


	glGenBuffers(1, &indexBufferID);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferID);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
	
	positionID = glGetAttribLocation(shaderProgramID, "s_vPosition");
	colorID = glGetAttribLocation(shaderProgramID, "s_vColor");
	
	perspectiveMatrixID = glGetUniformLocation(shaderProgramID, "mP");
	viewMatrixID = glGetUniformLocation(shaderProgramID, "mV");
	modelMatrixID = glGetUniformLocation(shaderProgramID, "mM");

	glVertexAttribPointer(positionID, 3, GL_FLOAT, GL_FALSE, 0, 0);
	glVertexAttribPointer(colorID, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(sizeof(vertices)));
	
	glutKeyboardFunc(keyboard);

	glUseProgram(shaderProgramID);
	glEnableVertexAttribArray(positionID);
	glEnableVertexAttribArray(colorID);
	glutSpecialFunc(SpecialInput);


	printWelcome();

	glutMainLoop();
	
	return 0;
}
 void AbstractIAFController::init(int sensornumber, int motornumber, RandGen* randGen) {
   if(!randGen) randGen = new RandGen(); // this gives a small memory leak
   this->randG=randGen;
   // set dimensions
   sensorNumber=sensornumber;
   motorNumber=motornumber;
   initMatrices();
   initialised=true;
 }
Ejemplo n.º 9
0
void MyWindow::initialize()
{
    CreateVertexBuffer();
    initShaders();
    initMatrices();

    //mRotationMatrixLocation = mProgram->uniformLocation("RotationMatrix");

    glFrontFace(GL_CCW);
    glEnable(GL_DEPTH_TEST);
}
Ejemplo n.º 10
0
/* ************************************************************************ */
int
main (int argc, char** argv)
{
	struct options options;
	struct calculation_arguments arguments;
	struct calculation_results results;

	struct comm_options comm;

	MPI_Init(&argc, &argv);
	MPI_Comm_rank(MPI_COMM_WORLD, &comm.rank);
	MPI_Comm_size(MPI_COMM_WORLD, &comm.num_procs);

	/* get parameters */
	AskParams(&options, argc, argv, comm.rank);              /* ************************* */
	initVariables(&arguments, &results, &options);           /* ******************************************* */

	if (options.method == METH_JACOBI && comm.num_procs > 1)
	{
		allocateMatrices_mpi(&arguments, &comm);
		initMatrices_mpi(&arguments, &options, &comm); 

		gettimeofday(&start_time, NULL);                   /*  start timer         */
		calculate_mpi(&arguments, &results, &options, &comm);                                      /*  solve the equation  */
		gettimeofday(&comp_time, NULL);                   /*  stop timer          */

		if (comm.rank == ROOT)
		{
			displayStatistics(&arguments, &results, &options);
		}

		DisplayMatrix_mpi(&arguments, &results, &options, comm.rank, comm.num_procs, comm.absoluteStartRow, comm.absoluteStartRow + comm.matrixRows -3);
		freeMatrices(&arguments);                                       /*  free memory     */
	}
	else
	{
		allocateMatrices(&arguments);        /*  get and initialize variables and matrices  */
		initMatrices(&arguments, &options);            /* ******************************************* */

		gettimeofday(&start_time, NULL);                   /*  start timer         */
		calculate(&arguments, &results, &options);                                      /*  solve the equation  */
		gettimeofday(&comp_time, NULL);                   /*  stop timer          */

		displayStatistics(&arguments, &results, &options);
		DisplayMatrix(&arguments, &results, &options);

		freeMatrices(&arguments);                                       /*  free memory     */
	}

	MPI_Finalize();

	return 0;
}
Ejemplo n.º 11
0
/* ************************************************************************ */
int
main (int argc, char** argv)
{
    MPI_Init(&argc, &argv);

    struct options options;
    struct calculation_arguments arguments;
    struct calculation_results results;

    /* get parameters */
    AskParams(&options, argc, argv);

    initVariables(&arguments, &results, &options);

    allocateMatrices(&arguments);        /*  get and initialize variables and matrices  */
    initMatrices(&arguments, &options);

    gettimeofday(&start_time, NULL);                  /*  start timer         */
    if (options.method == METH_JACOBI)
        calculate_jacobi(&arguments, &results, &options);        /*  solve the equation using Jaocbi  */
    else
        calculate_gaussseidel(&arguments, &results, &options);   /*  solve the equation using Gauss-Seidel  */

    MPI_Barrier(MPI_COMM_WORLD);
    gettimeofday(&comp_time, NULL);                   /*  stop timer          */

    // only attempt communication if we have more than 1 procss
    if(arguments.nproc > 1)
    {
        // communicate final maxresiduum from last rank to rank 0
        if(arguments.rank == 0)
            MPI_Recv(&results.stat_precision, 1, MPI_DOUBLE, arguments.nproc - 1, 1, MPI_COMM_WORLD, NULL);

        if(arguments.rank == arguments.nproc - 1)
            MPI_Send(&results.stat_precision, 1, MPI_DOUBLE, 0, 1, MPI_COMM_WORLD);
    }

    //printDebug(&arguments, &results); // pretty-print matrix if we are debugging
    if(arguments.rank == 0)
        displayStatistics(&arguments, &results, &options);

    DisplayMatrix("Matrix:", arguments.Matrix[results.m][0], options.interlines,
                  arguments.rank, arguments.nproc, arguments.offset + ((arguments.rank > 0) ? 1 : 0),
                  (arguments.offset + arguments.N - ((arguments.rank != arguments.nproc - 1) ? 1 : 0)));

    freeMatrices(&arguments);                                       /*  free memory     */

    MPI_Finalize();

    return 0;
}
void MyWindow::initialize()
{
    CreateVertexBuffer();
    initShaders();
    pass1Index = mFuncs->glGetSubroutineIndex( mProgram->programId(), GL_FRAGMENT_SHADER, "pass1");
    pass2Index = mFuncs->glGetSubroutineIndex( mProgram->programId(), GL_FRAGMENT_SHADER, "pass2");
    pass3Index = mFuncs->glGetSubroutineIndex( mProgram->programId(), GL_FRAGMENT_SHADER, "pass3");

    initMatrices();
    setupFBO();

    glFrontFace(GL_CCW);
    glEnable(GL_DEPTH_TEST);
}
Ejemplo n.º 13
0
void MyWindow::initialize()
{
    mFuncs->glGenVertexArrays(1, &mVAO);
    mFuncs->glBindVertexArray(mVAO);

    CreateVertexBuffer();
    initShaders();
    initMatrices();

    mRotationMatrixLocation = mProgramSimpleADS->uniformLocation("RotationMatrix");

    glFrontFace(GL_CCW);
    glEnable(GL_DEPTH_TEST);
}
Ejemplo n.º 14
0
void MyWindow::initialize()
{
    CreateVertexBuffer();
    initShaders();
    initMatrices();

    //PrepareTexture(GL_TEXTURE0, GL_TEXTURE_2D, "../Media/cement.jpg", false);
    //PrepareTexture(GL_TEXTURE1, GL_TEXTURE_2D, "../Media/moss.png", true);
    PrepareCubeMap(GL_TEXTURE0, "../media/cubemapnight/night", true);

    //mRotationMatrixLocation = mProgram->uniformLocation("RotationMatrix");

    glFrontFace(GL_CCW);
    glEnable(GL_DEPTH_TEST);
}
Ejemplo n.º 15
0
/* ************************************************************************ */
int
main (int argc, char** argv)
{
	struct options options;
	struct calculation_arguments arguments;
	struct calculation_results results;

    // mpi setup ---------------------------------------------------------------
    MPI_Init(NULL, NULL);

    int rank, nprocs;
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &nprocs);

	/* get parameters */
	AskParams(&options, argc, argv, rank);

	initVariables(&arguments, &results, &options, rank, nprocs);

    // printf("[%d] %" PRIu64 " %" PRIu64 "\n", rank, arguments.offset_start, arguments.offset_end);


    // get and initialize variables and matrices
	allocateMatrices(&arguments);
	initMatrices(&arguments, &options);

	gettimeofday(&start_time, NULL);                   /*  start timer         */
    // solve the equation
    if (options.method == METH_JACOBI)
	{
		calculate_mpi(&arguments, &results, &options);
	} else
	{
		calculate(&arguments, &results, &options);
	}

	// MPI_Barrier(MPI_COMM_WORLD);
	// gettimeofday(&comp_time, NULL);                   /*  stop timer          */

	DisplayMatrix(&arguments, &results, &options);

	freeMatrices(&arguments);

    MPI_Finalize();
	return 0;
}
int main(int argc, char **argv) {

	ros::init(argc, argv, "imu_vision_bias_fusion");
 	ros::NodeHandle nh;

 	state_pub = nh.advertise<geometry_msgs::TwistWithCovarianceStamped>("state",1); 

 	acc_pub = nh.advertise<geometry_msgs::Twist>("compensatedACC",1);

 	bias_pub = nh.advertise<geometry_msgs::Twist>("estimatedBias",1); 
 
	error_pub = nh.advertise<geometry_msgs::Twist>("error_vision_state",1); 

  	ros::Subscriber imu_sub = nh.subscribe("imu/data", 1, imuCb); 

  	ros::Subscriber vision_sub = nh.subscribe("vision_transformed", 1, visionCb); 

  	PrevCbTime = ros::Time::now();
 	
 	// INPUT
 	// posSTD, velSTD, bias_STD, visionSTD, biasNoise, biasInitValue;

  	if( argc >= 6)
  	{
    posSTD = atof(argv[1]);
    velSTD = atof(argv[2]);
    biasSTD = atof(argv[3]);
    visionSTD = atof(argv[4]);
    biasNoise = atof(argv[5]);
    posNoise = atof(argv[6]);
    velNoise = atof(argv[7]);
    biasInitValue = atof(argv[8]);
  	}

  	// 0.2 0.05 0.03 0.01 0.1 0.05 0.001 0.05

  	ROS_INFO_STREAM("		Input Parameters		");
  	ROS_INFO_STREAM("posSTD: " << posSTD << "  velSTD: " << velSTD << "  biasSTD: " << biasSTD << "  visionSTD: " << visionSTD);
  	ROS_INFO_STREAM("posNoise: " << posNoise << "  velNoise: " << velNoise << "  biasNoise: " << biasNoise << "  biasInitValue: " << biasInitValue);

  	initMatrices();

  	ros::spin();
}
Ejemplo n.º 17
0
int
main (int argc, char** argv) {
    AskParams(&options, argc, argv);
    if (argc > 7) {
        altermode = argv[7];
        if (rank == root) {
            printf("altermode enabled!\n");
        }
    }

    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &size);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    last = size-1;

    printf("process %d starting ...\n", rank);

    initVariables();
    initMatrices();

    gettimeofday(&start_time, NULL);
    if (options.method == METH_JACOBI) {
        calculateJacobi();
    }
    MPI_Barrier(MPI_COMM_WORLD);
    gettimeofday(&comp_time, NULL);

    if (rank == root) {
        double time = (comp_time.tv_sec - start_time.tv_sec) + (comp_time.tv_usec - start_time.tv_usec) * 1e-6;
        printf("Berechnungszeit:    %f s \n", time);
        printf("Anzahl Iterationen: %d\n", iteration);
    }

    DisplayMatrix();

    freeMemory();

    MPI_Finalize();
}
Ejemplo n.º 18
0
/* ************************************************************************ */
int
main (int argc, char** argv)
{
	struct options options;
	struct calculation_arguments arguments;
	struct calculation_results results;

	// MPI Init
	MPI_Init(&argc, &argv);
	MPI_Comm_size(MPI_COMM_WORLD, &size);
	MPI_Comm_rank(MPI_COMM_WORLD, &rank);
	
	/* get parameters */
	AskParams(&options, argc, argv);              /* ************************* */

	initVariables(&arguments, &results, &options);           /* ******************************************* */

	allocateMatrices(&arguments);        /*  get and initialize variables and matrices  */
	initMatrices(&arguments, &options);            /* ******************************************* */

	gettimeofday(&start_time, NULL);                   /*  start timer         */
	calculate(&arguments, &results, &options);                                      /*  solve the equation  */
	
	//wait
	MPI_Barrier(MPI_COMM_WORLD);
	gettimeofday(&comp_time, NULL);                   /*  stop timer          */

	if (rank == root){
	displayStatistics(&arguments, &results, &options);
	}
	DisplayMatrix(&arguments, &results, &options);

	freeMatrices(&arguments);                                       /*  free memory     */

	//MPI End
	MPI_Finalize();
	return 0;
}
Ejemplo n.º 19
0
int main (int argc, char** argv) {
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_RGBA|GLUT_DOUBLE|GLUT_DEPTH);
	glutInitWindowSize(800, 600);
	glutCreateWindow("Project 2: hot shot!");
	glutReshapeFunc(changeViewport);
	glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
	glutDisplayFunc(render);
	glewInit();

	/*set up the matricies*/
	initMatrices(); 

	initShaders();//
	
	glutKeyboardFunc(keyboard);

	glEnableVertexAttribArray(positionID);
	glEnableVertexAttribArray(colorID);
	glutMainLoop();
	
	return 0;
}
Ejemplo n.º 20
0
/* ************************************************************************ */
int
main (int argc, char** argv)
{
	struct options options;
	struct calculation_arguments arguments;
	struct calculation_results results;

	/* get parameters */
	AskParams(&options, argc, argv);              /* ************************* */

	initVariables(&arguments, &results, &options);           /* ******************************************* */

	allocateMatrices(&arguments, &options);        /*  get and initialize variables and matrices  */
	initMatrices(&arguments, &options);            /* ******************************************* */

  if (options.inf_func == FUNC_FPISIN) /* Init Cache für Sinus berechnung */
    initMysin(&arguments);
  

	gettimeofday(&start_time, NULL);                   /*  start timer         */
	calculate(&arguments, &results, &options);                                      /*  solve the equation  */
	gettimeofday(&comp_time, NULL);                   /*  stop timer          */

//  int i, j;
//	for(i = 0; i <=arguments.N ; i++)
//	 for(j = 0; j <=arguments.N; j++)
//	     arguments.Matrix[results.m][i][j] = Matrix_getValue(arguments.Mat[results.m], i, j); 

	displayStatistics(&arguments, &results, &options);                                  /* **************** */
	DisplayMatrix("Matrix:",                              /*  display some    */
			arguments.Mat[results.m], options.interlines);            /*  statistics and  */

  freeMysin(&arguments);                     /* Cache für Sinus freigeben */
	freeMatrices(&arguments);                                       /*  free memory     */

	return 0;
}
Ejemplo n.º 21
0
/* ************************************************************************ */
int
main (int argc, char** argv)
{
  struct options options;
  struct calculation_arguments arguments;
  struct calculation_results results; 
  int rc;
  
  rc = MPI_Init(&argc,&argv);
  if (rc != MPI_SUCCESS) 
  {
    printf("Error initializing MPI. Terminating.\n");
    MPI_Abort(MPI_COMM_WORLD, rc);
  }
  AskParams(&options, argc, argv);                    /* get parameters */   
  initVariables(&arguments, &results, &options);           /* ******************************************* */
  initMPI(&mpis, &arguments);	                     /* initalize MPI */
  allocateMatrices(&arguments);                            /*  get and initialize variables and matrices  */
  initMatrices(&arguments, &options);                      /* ******************************************* */
  
  gettimeofday(&start_time, NULL);                   /*  start timer         */
  calculate(&arguments, &results, &options);         /*  solve the equation  */
  gettimeofday(&comp_time, NULL);                    /*  stop timer          */
  if (0 == mpis.rank)
  {
    displayStatistics(&arguments, &results, &options);               /* **************** */
    DisplayMatrix("Matrix:",                                         /*  display some    */
		  arguments.Matrix[results.m][0], options.interlines);       /*  statistics and  */
  }
  freeMatrices(&arguments);
  freeMPI(&mpis);                                                      /*  free memory     */
  /* **************** */
  //MPI_Barrier(MPI_COMM_WORLD);
  MPI_Finalize();
  return 0;
}
Ejemplo n.º 22
0
/* ************************************************************************ */
int
main (int argc, char** argv)
{
    int rank;
    int size;
    int rest;
    int from, to;

    MPI_Init(&argc, &argv);

    MPI_Comm_size(MPI_COMM_WORLD, &size);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);

    struct options options;
    struct calculation_arguments arguments;
    struct calculation_results results;

    /* Parameter nur einmal abfragen */
    if(rank == 0)
    {
        AskParams(&options, argc, argv);
    }
    MPI_Bcast(&options, (sizeof(options)), MPI_BYTE, MASTER, MPI_COMM_WORLD);

    initVariables(&arguments, &results, &options);

    /* Damit allocation + initialization richtig läuft, wird für GS size = 1 gesetzt */
    if(options.method == METH_GAUSS_SEIDEL)
    {
        size = 1;
    }

    /* Aufteilen bis auf rest */
    int N_part = arguments.N;
    int lines = N_part - 1;
    rest = lines % size;
    N_part = (lines - rest) / size;

    /* globale zeilennummer berechnen, hier wird der rest beachtet						*/
    /* offset ist (rank + 1) für rank < rest, steigt also linear mit steigendem rang 	*/
    if(rank < rest)
    {
        from = N_part * rank 		+ rank + 1;
        to = N_part * (rank + 1) 	+ (rank + 1);
    }
    /* offset hier ist rest also die der maximale offset von oben */
    else
    {
        from = N_part * rank 		+ rest + 1;
        to = N_part * (rank + 1) 	+ rest ;
    }
    arguments.to = to;
    arguments.from = from;


    /* at least we only need N - 1 processes for calculation */
    if((unsigned int)size > (arguments.N -1))
    {
        size = (arguments.N - 1);

        if(rank == MASTER )
        {
            printf("\nWarning, you are using more processes than rows.\n This can slow down the calculation process! \n\n");
        }

    }

    //calculate Number of Rows
    arguments.numberOfRows = ((to - from + 1) > 0 ) ? (to - from + 1) : 0;

    allocateMatrices(&arguments);
    initMatrices(&arguments, &options, rank, size);

    gettimeofday(&start_time, NULL);                   /*  start timer         */


    if (options.method == METH_JACOBI )
    {
        calculateJacobi(&arguments, &results, &options, rank, size);
    }
    else
    {
        /* GS berechnet nur MASTER */
        if(rank == MASTER)
        {
            printf("\nGS wird nur sequentiell berechnet! \n");
            calculate(&arguments, &results, &options);
        }
    }

    gettimeofday(&comp_time, NULL);                   /*  stop timer          */

    /* only once */
    if(rank == MASTER)
    {
        displayStatistics(&arguments, &results, &options, size);
    }

    /* GS macht alte ausgabe */
    if((options.method == METH_GAUSS_SEIDEL) && (rank == MASTER))
    {
        DisplayMatrix(&arguments, &results, &options);
    }
    else
    {
        DisplayMatrixMPI(&arguments, &results, &options, rank, size, from, to);
    }

    freeMatrices(&arguments);                                       /*  free memory     */

    MPI_Finalize();
    return 0;
}
Ejemplo n.º 23
0
int main (int argc, char** argv) {
	// Standard stuff...
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_RGBA|GLUT_DOUBLE|GLUT_DEPTH);
	glutInitWindowSize(800, 600);
	glutCreateWindow("Diffuse Lighting");
	glutReshapeFunc(changeViewport);
	glutDisplayFunc(render);
	glewInit();

	initMatrices(); 

	GLfloat vertices[]= {
	-0.5f,0.5f,0.5f,  -0.5f,-0.5f,0.5f,  0.5f,-0.5f,0.5f,  -0.5f,0.5f,0.5f,  0.5f,-0.5f,0.5f,   0.5f,0.5f, 0.5f,
	 0.5f,0.5f,0.5f,   0.5f,-0.5f,0.5f,  0.5f,-0.5f,-0.5f,  0.5f,0.5f,0.5f,  0.5f,-0.5f,-0.5f,  0.5f,0.5f,-0.5f,
	 0.5f,-0.5f,0.5f, -0.5f,-0.5f,0.5f, -0.5f,-0.5f,-0.5f,  0.5f,-0.5f,0.5f, -0.5f,-0.5f,-0.5f,  0.5f,-0.5f,-0.5f,
	 0.5f,0.5f,-0.5f, -0.5f, 0.5f,-0.5f, -0.5f,0.5f,0.5f,   0.5f,0.5f,-0.5f,  -0.5f,0.5f,0.5f,   0.5f,0.5f,0.5f,
    -0.5f,-0.5f,-0.5f, -0.5f,0.5f,-0.5f,  0.5f,0.5f,-0.5f,  -0.5f,-0.5f,-0.5f, 0.5f,0.5f,-0.5f,  0.5f,-0.5f,-0.5f,
	-0.5f,0.5f,-0.5f,  -0.5f,-0.5f,-0.5f, -0.5f,-0.5f,0.5f, -0.5f,0.5f,-0.5f, -0.5f,-0.5f,0.5f,  -0.5f,0.5f,0.5f,


	};

	//GLuint indices[] = {1,0,3,2,2,3,7,6,3,0,4,7,6,5,1,2,4,5,6,7,5,4,0,1};

	GLfloat normals[]={
	0.0f,0.0f,1.0f,  0.0f,0.0f,1.0f,  0.0f,0.0f,1.0f,  0.0f,0.0f,1.0f,  0.0f,0.0f,1.0f,  0.0f,0.0f,1.0f,
	1.0f,0.0f,0.0f,  1.0f,0.0f,0.0f,  1.0f,0.0f,0.0f,  1.0f,0.0f,0.0f,  1.0f,0.0f,0.0f,  1.0f,0.0f,0.0f,
	0.0f,-1.0f,0.0f, 0.0f,-1.0f,0.0f, 0.0f,-1.0f,0.0f, 0.0f,-1.0f,0.0f, 0.0f,-1.0f,0.0f, 0.0f,-1.0f,0.0f,
	0.0f,1.0f,0.0f,  0.0f,1.0f,0.0f,  0.0f,1.0f,0.0f,  0.0f,1.0f,0.0f,  0.0f,1.0f,0.0f,  0.0f,1.0f,0.0f,
	0.0f,0.0f,-1.0f, 0.0f,0.0f,-1.0f, 0.0f,0.0f,-1.0f, 0.0f,0.0f,-1.0f,  0.0f,0.0f,-1.0f, 0.0f,0.0f,-1.0f,
	-1.0f,0.0f,0.0f, -1.0f,0.0f,0.0f, -1.0f,0.0f,0.0f, -1.0f,0.0f,0.0f, -1.0f,0.0f,0.0f, -1.0f,0.0f,0.0f,
};



	/*GLfloat vertices[] = {0.0f, 0.5f, 0.0f, // 0
						-0.25f, 0.0f, 0.0f, // 1
						0.25f, 0.0f, 0.0f, // 2
						-0.5f, -0.5f, 0.0f, // 3
						0.0f, -0.5f, 0.0f, // 4
						0.5f, -0.5f, 0.0f // 5
	};

	GLuint indices[] = {0, 1, 2, 1, 3, 4, 2, 4, 5};


	GLfloat normals[]={
	0.0f,0.0f,1.0f,
	0.0f,0.0f,1.0f,
	0.0f,0.0f,1.0f,
	0.0f,0.0f,1.0f,
	0.0f,0.0f,1.0f,
	0.0f,0.0f,1.0f
};*/


	// Make a shader
	char* vertexShaderSourceCode = readFile("vertexShader.vsh");
	char* fragmentShaderSourceCode = readFile("fragmentShader.fsh");
	GLuint vertShaderID = makeVertexShader(vertexShaderSourceCode);
	GLuint fragShaderID = makeFragmentShader(fragmentShaderSourceCode);
	shaderProgramID = makeShaderProgram(vertShaderID, fragShaderID);

	// Create the "remember all"
	glGenVertexArrays(1, &vao);
	glBindVertexArray(vao);
	
	glGenBuffers(1, &vbo);
	glBindBuffer(GL_ARRAY_BUFFER, vbo);
	// Create the buffer, but don't load anything yet
	//glBufferData(GL_ARRAY_BUFFER, 7*NUM_VERTICES*sizeof(GLfloat), NULL, GL_STATIC_DRAW);
	glBufferData(GL_ARRAY_BUFFER, 6*NUM_VERTICES*sizeof(GLfloat), NULL, GL_STATIC_DRAW);		// NEW!! - We're only loading vertices and normals (6 elements, not 7)
	
	// Load the vertex points
	glBufferSubData(GL_ARRAY_BUFFER, 0, 3*NUM_VERTICES*sizeof(GLfloat), vertices);
	// Load the colors right after that
	//glBufferSubData(GL_ARRAY_BUFFER, 3*NUM_VERTICES*sizeof(GLfloat),4*NUM_VERTICES*sizeof(GLfloat), colors);
	glBufferSubData(GL_ARRAY_BUFFER, 3*NUM_VERTICES*sizeof(GLfloat),3*NUM_VERTICES*sizeof(GLfloat), normals);
	
	
#ifdef USING_INDEX_BUFFER
	glGenBuffers(1, &indexBufferID);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferID);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, NUM_INDICES*sizeof(GLuint), indices, GL_STATIC_DRAW);
#endif
	
	// Find the position of the variables in the shader
	positionID = glGetAttribLocation(shaderProgramID, "s_vPosition");
	normalID = glGetAttribLocation(shaderProgramID, "s_vNormal");
	lightID = glGetUniformLocation(shaderProgramID, "vLight");	// NEW
	
	// ============ glUniformLocation is how you pull IDs for uniform variables===============
	perspectiveMatrixID = glGetUniformLocation(shaderProgramID, "mP");
	viewMatrixID = glGetUniformLocation(shaderProgramID, "mV");
	modelMatrixID = glGetUniformLocation(shaderProgramID, "mM");
	allRotsMatrixID = glGetUniformLocation(shaderProgramID, "mRotations");	// NEW
	//=============================================================================================

	glVertexAttribPointer(positionID, 3, GL_FLOAT, GL_FALSE, 0, 0);
	//glVertexAttribPointer(colorID, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(sizeof(vertices)));
	glVertexAttribPointer(normalID, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(sizeof(vertices)));
	
	glUseProgram(shaderProgramID);
	glEnableVertexAttribArray(positionID);
	glEnableVertexAttribArray(normalID);
	
	
	glEnable(GL_CULL_FACE);  // NEW! - we're doing real 3D now...  Cull (don't render) the backsides of triangles
	glCullFace(GL_BACK);	// Other options?  GL_FRONT and GL_FRONT_AND_BACK
	glEnable(GL_DEPTH_TEST);// Make sure the depth buffer is on.  As you draw a pixel, update the screen only if it's closer than previous ones
	 glClearColor( 1.0, 1.0, 1.0, 1.0 );

	glutKeyboardFunc( keyboard );
	glutMainLoop();
	
	return 0;
}
Ejemplo n.º 24
0
int main( void )
{
	initGLFW();
	initWindow();
	initGLEW();
	initKeyboard();
	
	// Dark blue background
	glClearColor(0.0f, 0.0f, 0.4f, 0.0f);

	int size = 5;
	float* map = generateHeightMap(size);
	printf("generated map\n" );
	std::vector<glm::vec3> terrain;
	mapHeightsToPoints(terrain, map, size);
	printf("mapped to points\n");
	// GLuint* indices = generateIndices(terrain, size);

	uint terrainVertexAmount = size* size * 3;
	uint indiceAmount = 3 * (1 << size);

	for(int i = 0; i < terrain.size(); ++i){
		printf("[%f, %f, %f]\n", terrain[i].x, terrain[i].y, terrain[i].z);
	}

	printf("vertices %d\n", terrainVertexAmount);

	GLuint VertexArrayID = newVertexArray();

	// Create and compile our GLSL program from the shaders
	GLuint programID = LoadShaders( "SimpleVertexShader.vertexshader", "SimpleFragmentShader.fragmentshader" );
	printf("loaded\n");
	initMatrices(programID);

	
	GLuint vertexbuffer = newVertexBuffer(terrainVertexAmount, &terrain);
	
	double lastTime = glfwGetTime();
 	int nbFrames = 0;
 	printf("loop\n");


 	initDepth();
	do{

		// Clear the screen
		glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		// Use our shader
		glUseProgram(programID);
		
		// TODO
		// recalculateMatrices();

		// Send our transformation to the currently bound shader, 
		// in the "MVP" uniform
		glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]);

		// 1rst attribute buffer : vertices
		bindVertexBuffer(vertexbuffer);

		// Draw the triangle !
		glDrawArrays(GL_TRIANGLE_FAN, 0, terrainVertexAmount); // 3 indices starting at 0 -> 1 triangle

		glDisableVertexAttribArray(0);

		// Swap buffers
		glfwSwapBuffers(window);
		glfwPollEvents();


		// measureTime(lastTime, &nbFrames);

	} // Check if the ESC key was pressed or the window was closed
	while( glfwGetKey(window, GLFW_KEY_ESCAPE ) != GLFW_PRESS &&
		   glfwWindowShouldClose(window) == 0 );

	// Cleanup VBO
	glDeleteBuffers(1, &vertexbuffer);
	glDeleteVertexArrays(1, &VertexArrayID);
	glDeleteProgram(programID);

	// Close OpenGL window and terminate GLFW
	glfwTerminate();
	// normal** ns = generateNormals(map, size);
	return 0;
}
Ejemplo n.º 25
0
int main (int argc, char** argv) {
	// Standard stuff...
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_RGBA|GLUT_DOUBLE|GLUT_DEPTH);
	glutInitWindowSize(800, 600);
	glutCreateWindow("Index Buffers");
	glutReshapeFunc(changeViewport);
	
	glewInit();

	initMatrices(); // New <========================================
	vao=gen_particles();

/*#ifdef USING_INDEX_BUFFER


	
#endif*/

	// Make a shader
	char* vertexShaderSourceCode = readFile("vertexShader1.vsh");
	char* fragmentShaderSourceCode = readFile("fragmentShader1.fsh");
	GLuint vertShaderID = makeVertexShader(vertexShaderSourceCode);
	GLuint fragShaderID = makeFragmentShader(fragmentShaderSourceCode);
	shaderProgramID = makeShaderProgram(vertShaderID, fragShaderID);

	/*/ / Create the "remember all"
	glGenVertexArrays(1, &vao);
	glBindVertexArray(vao);
	
	glGenBuffers(1, &vbo);
	glBindBuffer(GL_ARRAY_BUFFER, vbo);
	// Create the buffer, but don't load anything yet
	//glBufferData(GL_ARRAY_BUFFER, 7*NUM_VERTICES*sizeof(GLfloat), NULL, GL_STATIC_DRAW);
	glBufferData(GL_ARRAY_BUFFER, 6*NUM_VERTICES*sizeof(GLfloat), NULL, GL_STATIC_DRAW);
	
	// Load the vertex points
	glBufferSubData(GL_ARRAY_BUFFER, 0, 3*NUM_VERTICES*sizeof(GLfloat), vertices);
	// Load the colors right after that
	//glBufferSubData(GL_ARRAY_BUFFER, 3*NUM_VERTICES*sizeof(GLfloat),4*NUM_VERTICES*sizeof(GLfloat), colors);
	glBufferSubData(GL_ARRAY_BUFFER, 3*NUM_VERTICES*sizeof(GLfloat),3*NUM_VERTICES*sizeof(GLfloat), normals);*/
	
	
/*#ifdef USING_INDEX_BUFFER
	glGenBuffers(1, &indexBufferID);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferID);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, NUM_INDICES*sizeof(GLuint), indices, GL_STATIC_DRAW);
#endif*/
	

	// Find the position of the variables in the shader
	//ositionID = glGetAttribLocation(shaderProgramID, "v_i");
	//colorID = glGetAttribLocation(shaderProgramID, "elapsed_system_time");
	
	// ============ New! glUniformLocation is how you pull IDs for uniform variables===============
	perspectiveMatrixID = glGetUniformLocation(shaderProgramID, "P");
	viewMatrixID = glGetUniformLocation(shaderProgramID, "V");
	emitterID=glGetUniformLocation(shaderProgramID, "emitter_pos_wor");
	timeID=glGetUniformLocation(shaderProgramID, "elapsed_system_time");
	
	//=============================================================================================

	/*glVertexAttribPointer(positionID, 3, GL_FLOAT, GL_FALSE, 0, 0);
	//glVertexAttribPointer(colorID, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(sizeof(vertices)));
	glVertexAttribPointer(colorID, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(sizeof(vertices)));
	printf ("BUFFER_OFFSET is: %d\n", sizeof(vertices));*/

	glUseProgram(shaderProgramID);
	//glEnableVertexAttribArray(positionID);
	//glEnableVertexAttribArray(colorID);
	//glEnable(GL_DEPTH_TEST);
    //glClearColor( 0.0, 0.0, 0.0, 0.2 );

	//current_seconds=Timer();
	glutDisplayFunc(render);

	glutKeyboardFunc( keyboard );
	glutMainLoop();
	
	return 0;
}
Ejemplo n.º 26
0
int compute(){
    //Assuming that the processes form a square
    int n_procs_row = sqrt(number_of_processes);
    int n_procs_col = n_procs_row;
    if (n_procs_col * n_procs_row != number_of_processes) {
        std::cerr << "number of proccessors must be a perfect square!" << std::endl;
        MPI_Abort(MPI_COMM_WORLD, 1);
    }

    int n_dims = 2;
    int dims[n_dims] = {n_procs_row, n_procs_col};
    int periods[n_dims] = {0, 0};
    int repeat = 0;

    //create comm_groups
    MPI_Comm comm_cart;
    MPI_Cart_create(MPI_COMM_WORLD, n_dims, dims, periods, repeat, &comm_cart);

    int m_block = m / n_procs_row;
    int n_block = n / n_procs_col;
    int k_block = k / n_procs_col;

    if (m_block * n_procs_row != m) {
        std::cerr << "m must be dividable by n_procs_row" << std::endl;
        MPI_Abort(MPI_COMM_WORLD, 1);
    }
    if (n_block * n_procs_col != n) {
        std::cerr << "n must be dividable by n_procs_col" << std::endl;
        MPI_Abort(MPI_COMM_WORLD, 1);
    }
    if (k_block * n_procs_col != k) {
        std::cerr << "k must be dividable by n_procs_col" << std::endl;
        MPI_Abort(MPI_COMM_WORLD, 1);
    }

    double * A_local = (double *) calloc(m_block * n_block, sizeof(double));
    double * B_local = (double *) calloc(n_block * k_block, sizeof(double));
    double * C_local = (double *) calloc(m_block * k_block, sizeof(double));

    double * A = (double *) calloc(m * n, sizeof(double));
    double * B = (double *) calloc(n * k, sizeof(double));

    initMatrices(A_local, B_local, C_local, m_block, n_block, comm_cart);


    /**
    testing the scatter function
    */
    if(rank == 0){
        double * A_1 = (double *) calloc(n * k, sizeof(double));
        double * B_1 = (double *) calloc(n * k, sizeof(double));
        double * C_1 = (double *) calloc(n * k, sizeof(double));

        initMatrices(A_1, B_1, C_1, n, n, comm_cart);

        distributeSquareMatrix(A_1, n, C_1);
    }

    gatherMatrix(m_block, n_block, A_local, m, n, A);
    gatherMatrix(n_block, k_block, B_local, n, k, B);
    /*if (rank == 3) {
    std::cout << "A" << std::endl;
      printMatrix(m_block,m_block, A_local);
      std::cout << "B" << std::endl;
      printMatrix(m_block,m_block, B_local);
      std::cout << "C" << std::endl;
      printMatrix(m_block,m_block, C_local);
    }*/
    double start_time, end_time;

    start_time = MPI_Wtime();

    summa(comm_cart, m_block, n_block, k_block, A_local, B_local, C_local);

    end_time = MPI_Wtime();

    getTimes(start_time, end_time);

    double * C = (double *) calloc(m * n, sizeof(double));
    double * C_naive = (double *) calloc(m * n, sizeof(double));

    gatherMatrix(m_block, k_block, C_local, m, k, C);

    if (rank == 0) {

        multMatricesLineByLine(m, n, k, A, B, C_naive);

        double eps = validate(n, k, C, C_naive);
        if (eps > 1e-4) {
            std::cerr <<  "ERROR: Invalid matrix -> eps = " << eps << std::endl;
            MPI_Abort(MPI_COMM_WORLD, 1);
        } else {
            std::cout << "Valid matrix" << std::endl;
        }
    }
}
Ejemplo n.º 27
0
int main (int argc, char** argv) {
	// GLUT initialisation and matrices
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_RGBA|GLUT_DOUBLE|GLUT_DEPTH);
	glutInitWindowSize(800, 600);
	glutCreateWindow("GCP Assignment");
	glutReshapeFunc(changeViewport);
	glutKeyboardFunc(keyboardFunc);
	glutDisplayFunc(render);
	glewInit();

	initMatrices(); 

	// Make shaders
	char* vertexShaderSourceCode = readFile("vertexShader.vsh");
	char* fragmentShaderSourceCode = readFile("fragmentShader.fsh");
	GLuint vertShaderID = makeVertexShader(vertexShaderSourceCode);
	GLuint fragShaderID = makeFragmentShader(fragmentShaderSourceCode);
	shaderProgramID = makeShaderProgram(vertShaderID, fragShaderID);

	// create and bind the VBO toi the VAO"
	glGenVertexArrays(1, &vao);
	glBindVertexArray(vao);
	
	glGenBuffers(1, &vbo);
	glBindBuffer(GL_ARRAY_BUFFER, vbo);
	// Create the buffer of the size necessary to store the model  3 flaots for RGB 3 for the vertices XYZ
	glBufferData(GL_ARRAY_BUFFER, 6*NUM_VERTICES*sizeof(GLfloat), NULL, GL_STATIC_DRAW);
	
	// Load the vertex points
	glBufferSubData(GL_ARRAY_BUFFER, 0, 3*NUM_VERTICES*sizeof(GLfloat), vertices);
	// Load the colors right after that
	glBufferSubData(GL_ARRAY_BUFFER, 3*NUM_VERTICES*sizeof(GLfloat),3*NUM_VERTICES*sizeof(GLfloat), normals);
	
	
#ifdef USING_INDEX_BUFFER
	glGenBuffers(1, &indexBufferID);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferID);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, NUM_INDICES*sizeof(GLuint), indices, GL_STATIC_DRAW);
#endif
	

	// the console output
	std::cout << "Giannandrea Grone Assignment \n";
	std::cout << "Simple demonstration of rotating a model around itself with Quaternions or Matrices\n ";
	std::cout << "The results seem similar but the maths behind it is significantly different\n ";
	std::cout << "How to use: \n ";
	std::cout << "Press P to toggle between Matrices and Quaternions \n ";
	std::cout << "Press O to toggle between Automatic and Manual \n ";
	std::cout << "WASD to move the camera (left, right, forward, backward \n ";
	std::cout << "QE  to move the camera upward downward \n ";
	std::cout << "RT FG CV to rotate the camera on XYZ \n ";
	std::cout << "(Manual only) YU HJ NM to rotate the model on XYZ \n";




	// bind the data with the shaders
	positionID = glGetAttribLocation(shaderProgramID, "s_vPosition");
	normalID = glGetAttribLocation(shaderProgramID, "s_vNormal");
	lightID = glGetUniformLocation(shaderProgramID, "vLight");	// NEW
	
	// gives the data to the shaders
	perspectiveMatrixID = glGetUniformLocation(shaderProgramID, "mP");
	viewMatrixID = glGetUniformLocation(shaderProgramID, "mV");
	modelMatrixID = glGetUniformLocation(shaderProgramID, "mM");
	allRotsMatrixID = glGetUniformLocation(shaderProgramID, "mRotations");
	

	glVertexAttribPointer(positionID, 3, GL_FLOAT, GL_FALSE, 0, 0);
	glVertexAttribPointer(normalID, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(sizeof(vertices)));
	
	glUseProgram(shaderProgramID);
	glEnableVertexAttribArray(positionID);
	glEnableVertexAttribArray(normalID);
	
	// Turn on depth cullint
	glEnable(GL_CULL_FACE);
	glCullFace(GL_BACK);
	glEnable(GL_DEPTH_TEST);
	
	glutMainLoop();
	
	return 0;
}
Ejemplo n.º 28
0
/* ************************************************************************ */
static
void
calculate (struct calculation_arguments const* arguments, struct calculation_results *results, struct options const* options)
{
	int i, j;                                   /* local variables for loops  */
	int m1, m2;                                 /* used as indices for old and new matrices       */
	double star;                                /* four times center value minus 4 neigh.b values */
	double residuum;                            /* residuum of current iteration                  */
	double maxresiduum;                         /* maximum residuum value of a slave in iteration */

	int const N = arguments->N;
	double const h = arguments->h;

	double pih = 0.0;
	double fpisin = 0.0;

	int term_iteration = options->term_iteration;

	/* initialize m1 and m2 depending on algorithm */
	if (options->method == METH_JACOBI)
	{
		m1 = 0;
		m2 = 1;
	}
	else
	{
		m1 = 0;
		m2 = 0;
	}

	if (options->inf_func == FUNC_FPISIN)
	{
		pih = PI * h;
		fpisin = 0.25 * TWO_PI_SQUARE * h * h;
	}

#if defined(ROWS) || defined(COLS) || defined(ELEMENTS)
	omp_set_num_threads(options->number);	
#endif

	while (term_iteration > 0)
	{
		double** Matrix_Out = arguments->Matrix[m1];
		double** Matrix_In  = arguments->Matrix[m2];

		maxresiduum = 0;


#if !defined(ROWS) && !defined(COLS) && !defined(ELEMENTS)	
		for (i = 1; i < N; i++)
				{
					double fpisin_i = 0.0;

					if (options->inf_func == FUNC_FPISIN)
					{
						fpisin_i = fpisin * sin(pih * (double)i);
					}

					/* over all columns */
					for (j = 1; j < N; j++)
					{
#endif


#ifdef ROWS
		
	#pragma omp parallel for private(j, star, residuum) reduction(max : maxresiduum)
		
		/* over all rows */

		for (i = 1; i < N; i++)
		{
			double fpisin_i = 0.0;

			if (options->inf_func == FUNC_FPISIN)
			{
				fpisin_i = fpisin * sin(pih * (double)i);
			}

			/* over all columns */
			for (j = 1; j < N; j++)
			{
#endif
	

#ifdef COLS

	#pragma omp parallel for private(i, star, residuum) reduction(max : maxresiduum)
			
		/* over all colums */
		for (j = 1; j < N; j++)
		{

			/* over all rows */
			for (i = 1; i < N; i++)
			{

			double fpisin_i = 0.0;

			if (options->inf_func == FUNC_FPISIN)
			{
				fpisin_i = fpisin * sin(pih * (double)i);
			}

#endif

#ifdef ELEMENTS
		int k;
		#pragma omp parallel for private(i, j, star, residuum) reduction(max : maxresiduum)
			
			for (k = 0; k < ((N-1) * (N-1) - 1); k++)
			{
				j = k % (N - 1) + 1;	// +1 weil k bei 0 anfängt
				i = k / N +1; 			// i ist int, die Nachkommastellen fallen weg; +1 weil k bei 0 anfängt

				double fpisin_i = 0.0;

				if (options->inf_func == FUNC_FPISIN)
				{
					fpisin_i = fpisin * sin(pih * (double)i);
				}

#endif

					star = 0.25 * (Matrix_In[i-1][j] + Matrix_In[i][j-1] + Matrix_In[i][j+1] + Matrix_In[i+1][j]);

					if (options->inf_func == FUNC_FPISIN)
					{
						star += fpisin_i * sin(pih * (double)j);
					}

					if (options->termination == TERM_PREC || term_iteration == 1)
					{
						residuum = Matrix_In[i][j] - star;
						residuum = (residuum < 0) ? -residuum : residuum;
						maxresiduum = (residuum < maxresiduum) ? maxresiduum : residuum;
					}

					Matrix_Out[i][j] = star;
				
			}

#ifndef	ELEMENTS	
		}
#endif

		results->stat_iteration++;
		results->stat_precision = maxresiduum;

		/* exchange m1 and m2 */
		i = m1;
		m1 = m2;
		m2 = i;

		/* check for stopping calculation, depending on termination method */
		if (options->termination == TERM_PREC)
		{
			if (maxresiduum < options->term_precision)
			{
				term_iteration = 0;
			}
		}
		else if (options->termination == TERM_ITER)
		{
			term_iteration--;
		}
	}

	results->m = m2;
}

/* ************************************************************************ */
/*  displayStatistics: displays some statistics about the calculation       */
/* ************************************************************************ */
static
void
displayStatistics (struct calculation_arguments const* arguments, struct calculation_results const* results, struct options const* options)
{
	int N = arguments->N;
	double time = (comp_time.tv_sec - start_time.tv_sec) + (comp_time.tv_usec - start_time.tv_usec) * 1e-6;

	printf("Berechnungszeit:    %f s \n", time);
	printf("Speicherbedarf:     %f MiB\n", (N + 1) * (N + 1) * sizeof(double) * arguments->num_matrices / 1024.0 / 1024.0);
	printf("Berechnungsmethode: ");

	if (options->method == METH_GAUSS_SEIDEL)
	{
		printf("Gauss-Seidel");
	}
	else if (options->method == METH_JACOBI)
	{
		printf("Jacobi");
	}

	printf("\n");
	printf("Interlines:         %" PRIu64 "\n",options->interlines);
	printf("Stoerfunktion:      ");

	if (options->inf_func == FUNC_F0)
	{
		printf("f(x,y) = 0");
	}
	else if (options->inf_func == FUNC_FPISIN)
	{
		printf("f(x,y) = 2pi^2*sin(pi*x)sin(pi*y)");
	}

	printf("\n");
	printf("Terminierung:       ");

	if (options->termination == TERM_PREC)
	{
		printf("Hinreichende Genaugkeit");
	}
	else if (options->termination == TERM_ITER)
	{
		printf("Anzahl der Iterationen");
	}

	printf("\n");
	printf("Anzahl Iterationen: %" PRIu64 "\n", results->stat_iteration);
	printf("Norm des Fehlers:   %e\n", results->stat_precision);
	printf("\n");
}

/****************************************************************************/
/** Beschreibung der Funktion DisplayMatrix:                               **/
/**                                                                        **/
/** Die Funktion DisplayMatrix gibt eine Matrix                            **/
/** in einer "ubersichtlichen Art und Weise auf die Standardausgabe aus.   **/
/**                                                                        **/
/** Die "Ubersichtlichkeit wird erreicht, indem nur ein Teil der Matrix    **/
/** ausgegeben wird. Aus der Matrix werden die Randzeilen/-spalten sowie   **/
/** sieben Zwischenzeilen ausgegeben.                                      **/
/****************************************************************************/
static
void
DisplayMatrix (struct calculation_arguments* arguments, struct calculation_results* results, struct options* options)
{
	int x, y;

	double** Matrix = arguments->Matrix[results->m];

	int const interlines = options->interlines;

	printf("Matrix:\n");

	for (y = 0; y < 9; y++)
	{
		for (x = 0; x < 9; x++)
		{
			printf ("%7.4f", Matrix[y * (interlines + 1)][x * (interlines + 1)]);
		}

		printf ("\n");
	}

	fflush (stdout);
	
}

/* ************************************************************************ */
/*  main                                                                    */
/* ************************************************************************ */
int
main (int argc, char** argv)
{
	struct options options;
	struct calculation_arguments arguments;
	struct calculation_results results;

	/* get parameters */
	AskParams(&options, argc, argv);              /* ************************* */

	initVariables(&arguments, &results, &options);           /* ******************************************* */

	allocateMatrices(&arguments);        /*  get and initialize variables and matrices  */
	initMatrices(&arguments, &options);            /* ******************************************* */

	gettimeofday(&start_time, NULL);                   /*  start timer         */
	calculate(&arguments, &results, &options);                                      /*  solve the equation  */
	gettimeofday(&comp_time, NULL);                   /*  stop timer          */

	displayStatistics(&arguments, &results, &options);
	DisplayMatrix(&arguments, &results, &options);

	freeMatrices(&arguments);                                       /*  free memory     */

	return 0;
}
Ejemplo n.º 29
0
int main(int argc, const char *argv[])
{
    int N,
		    M,
		    T,
		    maxIters,
		    seed,
		    i,
		    j,
		    iter,
        str_len;

    char **alphabet;

    double logProb,
           newLogProb;

  	double *pi,
           *piBar, 
           **A,
           **Abar,
           **B,
           **Bbar;

    struct stepStruct *step;

    FILE *in,
         *out;
    
    char s[80];

	int wantTraining = 1;
    
    if(argc != 10)
    {
        fprintf(stderr, "\nUsage: %s N M T maxIters filename alphabet modelfile seed\n\n", argv[0]);
        fprintf(stderr, "where N == number of states of the HMM\n");
        fprintf(stderr, "      M == number of observation symbols\n");
        fprintf(stderr, "      T == number of observations in the training set\n");
        fprintf(stderr, "      maxIters == max iterations of re-estimation algorithm\n");
        fprintf(stderr, "      filename == name of input file\n");
        fprintf(stderr, "      alphabet == name of file defining the alphabet\n");
        fprintf(stderr, "      modelfile == name of model output file\n");
        fprintf(stderr, "      seed == seed value for pseudo-random number generator (PRNG)\n\n");
		fprintf(stderr, "      wantTraining == to train enter 1, otherwise 0 \n\n");
        fprintf(stderr, "For example:\n\n      %s 2 10 10000 500 datafile alphabet modelfile 1241\n\n", argv[0]);
        fprintf(stderr, "will create a HMM with 2 states and 10 observation symbols,\n");
        fprintf(stderr, "will read in the first 10000 observations from `datafile',\n");
        fprintf(stderr, "will use the observation symbols defined in file `alphabet', and\n");
        fprintf(stderr, "will write the model (pi, A, B) to `modelfile', and\n");
        fprintf(stderr, "will seed the PRNG with 1241 and train the HMM with a maximum of 500 iterations.\n\n");
        exit(0);
    }

    N = atoi(argv[1]);
    M = atoi(argv[2]);
    T = atoi(argv[3]);
    maxIters = atoi(argv[4]);
    seed = atoi(argv[8]);
	wantTraining = atoi(argv[9]);

    pi = (double *)malloc(N * sizeof(double));
    piBar = (double *)malloc(N * sizeof(double));

    A = (double **)malloc(N * sizeof(double*));
    Abar =static_cast<double **>(malloc(N * sizeof(double*)));
    for (i=0; i<N; ++i)
    {
      A[i] = static_cast<double *>(malloc(N * sizeof(double)));
      Abar[i] = static_cast<double *>(malloc(N * sizeof(double)));
    }

    B = static_cast<double **>(malloc(N * sizeof(double*)));
    Bbar = static_cast<double **>(malloc(N * sizeof(double*)));
    for (i=0; i<N; ++i)
    {
      B[i] = static_cast<double *>(malloc(M * sizeof(double)));
      Bbar[i] = static_cast<double *>(malloc(M * sizeof(double)));
    }
    
   
    ////////////////////////
    // read the data file //
    ////////////////////////

    // allocate memory
    printf("allocating %d bytes of memory... ", (T + 1) * sizeof(struct stepStruct));
    fflush(stdout);
    if((step = static_cast<stepStruct *>(calloc(T + 1, sizeof(struct stepStruct)))) == NULL)
    {
        fprintf(stderr, "\nUnable to allocate alpha\n\n");
        exit(0);
    }
    for (i=0; i<T+1; ++i)
    {
      step[i].alpha = static_cast<double *>(malloc(N * sizeof(double)));
      step[i].beta = static_cast<double *>(malloc(N * sizeof(double)));
      step[i].gamma = static_cast<double *>(malloc(N * sizeof(double)));
      step[i].diGamma = static_cast<double **>(malloc(N * sizeof(double*)));
      for (j=0; j<N; ++j)
      {
        step[i].diGamma[j] = static_cast<double *>(malloc(N * sizeof(double)));
      }
    }
    printf("done\n");

    // read in the observations from file
    printf("GetObservations... ");
    fflush(stdout);
    in = fopen(argv[5], "r"); // argv[5] = filename
    if(in == NULL)
    {
        fprintf(stderr, "\nError opening file %s\n\n", argv[5]);
        exit(0);
    }
    i = 0;
    fgets(s,80,in); // get rid of the first line
    while (i < T)
    {
      fgets(s,80,in);
      step[i].obs = atoi(s);
      ++i;
    }
    fclose(in);
    printf("done\n");

    // read in the alphabet from file
    printf("GetAlphabet... ");
    fflush(stdout);
    alphabet = static_cast<char **>(malloc(M * sizeof (char*)));
    in = fopen(argv[6], "r"); // argv[6] = alphabet
    if(in == NULL)
    {
        fprintf(stderr, "\nError opening file %s\n\n", argv[6]);
        exit(0);
    }
    i = 0;
    fgets(s,80,in); // get rid of the first line
    while (i < M)
    {
      fgets(s,80,in);
	    str_len = strlen(s);
      alphabet[i] = static_cast<char *>(malloc(str_len * sizeof(char)));
      strncpy(alphabet[i], s, str_len-1);
      alphabet[i][str_len-1] = '\0';
      ++i;
    }
    fclose(in);
    printf("done\n");


    /////////////////////////
    // hidden markov model //
    /////////////////////////

    srand(seed);

    // initialize pi[], A[][] and B[][]
    initMatrices(pi, A, B, N, M, seed);

    // print pi[], A[][] and B[][] transpose
    printf("\nN = %d, M = %d, T = %d\n", N, M, T);
    printf("initial pi =\n");
    printPi(pi, N);
    printf("initial A =\n");
    printA(A, N);
    printf("initial B^T =\n");
    printBT(B, N, M, alphabet);

    // initialization
    iter = 0;
    logProb = -1.0;
    newLogProb = 0.0;

	if (wantTraining) {

		// main loop
		while((iter < maxIters) && (newLogProb > logProb))
		{
			printf("\nbegin iteration = %d\n", iter);

			logProb = newLogProb;

			// alpha (or forward) pass
			printf("alpha pass... ");
			fflush(stdout);
			alphaPass(step, pi, A, B, N, T);
			printf("done\n");

			// beta (or backwards) pass
			printf("beta pass... ");
			fflush(stdout);
			betaPass(step, pi, A, B, N, T);
			printf("done\n");

			// compute gamma's and diGamma's
			printf("compute gamma's and diGamma's... ");
			fflush(stdout);
			computeGammas(step, pi, A, B, N, T);
			printf("done\n");

			// find piBar, reestimate of pi
			printf("reestimate pi... ");
			fflush(stdout);
			reestimatePi(step, piBar, N);
			printf("done\n");

			// find Abar, reestimate of A
			printf("reestimate A... ");
			fflush(stdout);
			reestimateA(step, Abar, N, T);
			printf("done\n");

			// find Bbar, reestimate of B
			printf("reestimate B... ");
			fflush(stdout);
			reestimateB(step, Bbar, N, M, T);
			printf("done\n");

	#ifdef PRINT_REESTIMATES
			printf("piBar =\n");
			printPi(piBar, N);
			printf("Abar =\n");
			printA(Abar, N);
			printf("Bbar^T = \n");
			printBT(Bbar, N, M, alphabet);
	#endif // PRINT_REESTIMATES

			// assign pi, A and B corresponding "bar" values
			for(i = 0; i < N; ++i)
			{
				pi[i] = piBar[i];

				for(j = 0; j < N; ++j)
				{
					A[i][j] = Abar[i][j];
				}

				for(j = 0; j < M; ++j)
				{
					B[i][j] = Bbar[i][j];
				}

			}// next i

			// compute log [P(observations | lambda)], where lambda = (A,B,pi)
			newLogProb = 0.0;
			for(i = 0; i < T; ++i)
			{
				newLogProb += log(step[i].c);
			}
			newLogProb = -newLogProb;

			// a little trick so that no initial logProb is required
			if(iter == 0)
			{
				logProb = newLogProb - 1.0;
			}

			printf("completed iteration = %d, log [P(observation | lambda)] = %f\n",
					iter, newLogProb);

			++iter;

		}// end while
    
		out = fopen(argv[7], "w"); // argv[7] = modelfile
		writeModel(pi, A, B, N, M, T, alphabet, out);
		fclose(out);
    
		printf("\nT = %d, N = %d, M = %d, iterations = %d\n\n", T, N, M, iter);
		printf("final pi =\n");
		printPi(pi, N);
		printf("\nfinal A =\n");
		printA(A, N);
		printf("\nfinal B^T =\n");
		printBT(B, N, M, alphabet);
		printf("\nlog [P(observations | lambda)] = %f\n\n", newLogProb);

	} // end of training
	else { //want to do testing


		out = fopen(argv[7], "r"); // argv[7] = modelfile
		readModelFile(pi, A, B, N, M, T, alphabet, out);
		
		// alpha (or forward) pass
		printf("alpha pass... ");
		fflush(stdout);
		alphaPass(step, pi, A, B, N, T);
		printf("done\n");
		printf("logProb %f\n", computeLogProb(step, T)/T);
		
	//	FILE * newFile = fopen("testing.txt", "a");
		//writeModel(pi, A, B, N, M, T, alphabet, newFile);

		//fclose(newFile);

		fclose(out);
	} // end of testing
}// end hmm
Ejemplo n.º 30
0
int
main (int argc, char** argv) {
	AskParams(&options, argc, argv);
	if (argc > 7) {
		altermode = argv[7];
		if (rank == root) { printf("altermode enabled!\n"); }
	}
	
	MPI_Init(&argc, &argv);
	MPI_Comm_size(MPI_COMM_WORLD, &size);
	MPI_Comm_rank(MPI_COMM_WORLD, &rank);
	last = size-1;
	
	printf("process %d starting ...\n", rank);
	
	initVariables();
	initMatrices();
	
	gettimeofday(&start_time, NULL);
	calculate();
	MPI_Barrier(MPI_COMM_WORLD);
	gettimeofday(&comp_time, NULL);
	
	if (rank == root) {
		double time = (comp_time.tv_sec - start_time.tv_sec) + (comp_time.tv_usec - start_time.tv_usec) * 1e-6;
		printf("Berechnungszeit:    %f s \n", time);
		printf("Anzahl Iterationen: %d\n", iteration);
	}
	
	DisplayMatrix();
	//testPrint();
	
	/*MPI_Barrier(MPI_COMM_WORLD);
	if (rank == 0) {
		for (int i = 0; i < actuallines; i++) {
			for (int j = 0; j <= N; j++) {
				printf("%7.4f ", newmatrix[i][j]);
			}
			printf("\n");
		}
		printf("\n");
	}
	MPI_Barrier(MPI_COMM_WORLD);
	if (rank == 1) {
		for (int i = 0; i < actuallines; i++) {
			for (int j = 0; j <= N; j++) {
				printf("%7.4f ", newmatrix[i][j]);
			}
			printf("\n");
		}
		printf("\n");
	}
	MPI_Barrier(MPI_COMM_WORLD);
	if (rank == 2) {
		for (int i = 0; i < actuallines; i++) {
			for (int j = 0; j <= N; j++) {
				printf("%7.4f ", newmatrix[i][j]);
			}
			printf("\n");
		}
		printf("\n");
	}
	MPI_Barrier(MPI_COMM_WORLD);
	if (rank == 3) {
		for (int i = 0; i < actuallines; i++) {
			for (int j = 0; j <= N; j++) {
				printf("%7.4f ", newmatrix[i][j]);
			}
			printf("\n");
		}
		printf("\n");
	}*/
	
	freeMemory();
	
	MPI_Finalize();
}