<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <math.h>
#include <vector>
#include <iostream>
#include <math.h>

/************************************************************
This is a simple isend/ireceive program in MPI
************************************************************/
using namespace std;

vector <vector <char>> create_environment(int dimention){
	vector <vector <char>> env;

	for (int i = 0; i < dimention; ++i){
		vector <char> row;
		for (int j = 0; j < dimention; ++j){
			row.push_back(0);
		}
		env.push_back(row);
	}

	return env;
}

vector <vector <char>> set_diagonal(vector <vector <char>> env){
	for (unsigned int i = 0; i < env.size(); ++i){
		for (unsigned int j = 0; j < env.at(i).size(); ++j){
			if (i == j){
				env[i][j] = 1;
			}
		}
	}
	for (unsigned int i = 0; i < env.size(); ++i){
		for (unsigned int j = 0; j < env.at(i).size(); ++j){
			if (j == (env.size() - i - 1)){
				env[i][j] = 1;
			}
		}
	}
	return env;
}

char * vector_to_array(vector<vector<char>> env, int dimention){
	char * arr = new char[dimention * dimention];
	int index = 0;
	for (unsigned int i = 0; i < env.size(); ++i){
		for (unsigned int j = 0; j < env[0].size(); ++j){
			arr[index] = env[i][j];
			++index;
		}
	}
	env.clear();
	return arr;
}

void print_array(char arr[], int full_dimention){
	// PRINTING ARRAY
	cout << endl;
	for (int i = 0; i < full_dimention; ++i){
		cout << (int)arr[i];
		if (((i + 1) % (int)sqrt(full_dimention)) == 0 && i / 1 != 0){
			cout << endl;
		}
	}
}

char * array_copy(char arr[], int full_dimention){
	char * new_arr = new char[full_dimention];
	copy(arr, arr + (full_dimention), new_arr);
	return new_arr;
}

int check_neighbours(char arr[], int dimention, int x){
	int count = 0;
	char a, b, c, d, e, f, g, h = 0;
	a = b = c = d = e = f = g = h;

	if ((x - dimention - 1) > -1 && ((int)((x - dimention - 1) / dimention)) == ((int)((x - dimention) / dimention))){
		a = arr[x - dimention - 1];
	}

	if (x - dimention > -1){
		b = arr[x - dimention];
	}

	if ((x - dimention + 1 > 0) && ((int)((x - dimention + 1) / dimention)) == ((int)((x - dimention) / dimention))){
		c = arr[x - dimention + 1];
	}

	if (x - 1 > -1 && ((int)((x - 1) / dimention)) == ((int)(x / dimention))){
		d = arr[x - 1];
	}

	if (x + 1 < dimention*dimention && ((int)((x + 1) / dimention)) == ((int)(x / dimention))){
		e = arr[x + 1];
	}

	if ((x + dimention - 1) < dimention*dimention && ((int)((x + dimention - 1) / dimention)) == ((int)((x + dimention) / dimention))){
		f = arr[x + dimention - 1];
	}

	if ((x + dimention) < dimention*dimention ){
		g = arr[x + dimention];
	}

	if ((x + dimention + 1) < dimention*dimention && ((int)((x + dimention + 1) / dimention)) == ((int)((x + dimention) / dimention))){
		h = arr[x + dimention + 1];
	}

	count = a + b + c + d + e + f + g + h;

	return count;
}

int main(int argc, char *argv[])
{

	int tag = 7;
	int count = 10;
	int dimention = 10;
	int full_dimention = 100;

	//MPI_Status status;
	//MPI_Request request;
	MPI_Request request[4];
    MPI_Status status[4];
	request[0] = MPI_REQUEST_NULL;
	request[1] = MPI_REQUEST_NULL;
	request[2] = MPI_REQUEST_NULL;
	request[3] = MPI_REQUEST_NULL;

	const int size = 10;

 	char buffi[100] = {};
 	char buffo[100] = {};
 	char buffc[100] = {};

 	for (int i = 0; i < 100; ++i){
 		buffi[i] = i;
 		buffo[i] = i;
 	}

 	//print_array(buffo, 100);

 	vector< vector<char>> env = create_environment(dimention);
	env = set_diagonal(env);

	char * arr = vector_to_array(env, dimention);
	char * b_arr = array_copy(arr, full_dimention);

	//print_array(arr, full_dimention);

	int test = 0;
	if (test == 1){

		cout << "ITERATIONS TEST" << endl;

		int iterations = 13;

		char * b_arr = array_copy(arr, full_dimention);

		while (iterations > 0){

			char * c_arr = array_copy(b_arr, full_dimention);

			for (int i = 0; i < full_dimention; ++i){

				int neighbours = check_neighbours(b_arr, dimention, i);

				if (b_arr[i] == 0){
					if (neighbours == 1 || neighbours == 2){
						c_arr[i] = 1;
					}
				}
				else {
					if (neighbours > 2 || neighbours < 1){
						c_arr[i] = 0;
					}
				}
			}
			cout << iterations << endl;
		 	print_array(c_arr, full_dimention);

		 	copy(c_arr, c_arr + (full_dimention), b_arr);
		 	--iterations;
		 	free(c_arr);

		}
	}

	// CORRECT ABOVE

	// MPI INIT
	MPI_Init(&argc,&argv);

	int numprocs;
	MPI_Comm_size(MPI_COMM_WORLD,&numprocs);

	int id;
	MPI_Comm_rank(MPI_COMM_WORLD,&id);

	int iterations = 2;

	//while (iterations > 0){

		if (id == 0){
			MPI_Isend(&arr,full_dimention,MPI_CHAR,1,tag,MPI_COMM_WORLD,&request[0]);
			for (int i = 0; i < 100; ++i){
				cout << i << ": " << (int) arr[i] << endl;
			}
		}
		if (id == 1){
			char buffc[100] = {};
			MPI_Irecv(&buffc,full_dimention,MPI_CHAR,0,tag,MPI_COMM_WORLD,&request[1]);
		}
		MPI_Wait(&request[0],&status[0]);
		MPI_Wait(&request[1],&status[1]);
		if (id == 1){
			--iterations;
			//cout << " Array "<< iterations <<" has been received." << endl;
			//print_array(buffo, 100);

			for (int i = 0; i < 100; ++i){
				cout << i << ": " << (int) buffc[i] << endl;
			}
		}

		--iterations;
	//}

	MPI_Finalize();

	return 0;

 	// MPI INIT
	MPI_Init(&argc,&argv);

	//int numprocs;
	MPI_Comm_size(MPI_COMM_WORLD,&numprocs);

	//int id;
	MPI_Comm_rank(MPI_COMM_WORLD,&id);

	if(id == 0){
		//MPI_Isend(&buffi,count,MPI_CHAR,0,tag,MPI_COMM_WORLD,&request);
		//MPI_Isend(&buffi,count,MPI_CHAR,1,tag,MPI_COMM_WORLD,&request);
		//MPI_Isend(&buffi,count,MPI_CHAR,2,tag,MPI_COMM_WORLD,&request);
		//MPI_Isend(&buffi,count,MPI_CHAR,3,tag,MPI_COMM_WORLD,&request);
	}
	if(id == 0){
		//MPI_Irecv(&buffo,count,MPI_CHAR,0,tag,MPI_COMM_WORLD,&request);
	}
	if(id == 1){
		//MPI_Irecv(&buffo,count,MPI_CHAR,0,tag,MPI_COMM_WORLD,&request);
	}
	if(id == 2){
		//MPI_Irecv(&buffo,count,MPI_CHAR,0,tag,MPI_COMM_WORLD,&request);
	}
	if(id == 3){
		//MPI_Irecv(&buffo,count,MPI_CHAR,0,tag,MPI_COMM_WORLD,&request);
	}

	//MPI_Wait(&request,&status);
	if(id == 0){
		printf("processor %d sent %d\n",id,(int)buffi[0]);
		printf("processor %d sent %d\n",id,(int)buffi[0]);
		printf("processor %d sent %d\n",id,(int)buffi[0]);
		printf("processor %d sent %d\n",id,(int)buffi[0]);
	}
	if(id == 0){
		for (unsigned int i = 0; i < count; ++i){
			printf("processor %d got %d - %d\n",id,i,(int)buffo[i]);
		}
	}
	if(id == 1){
		for (unsigned int i = 0; i < count; ++i){
			printf("processor %d got %d - %d\n",id,i,(int)buffo[i]);
		}
	}
	if(id == 2){
		for (unsigned int i = 0; i < count; ++i){
			printf("processor %d got %d - %d\n",id,i,(int)buffo[i]);
		}
	}
	if(id == 3){
		for (unsigned int i = 0; i < count; ++i){
			printf("processor %d got %d - %d\n",id,i,(int)buffo[i]);
		}
	}

	MPI_Finalize();

	return 0;
}<commit_msg>Fuck yeah<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <math.h>
#include <vector>
#include <iostream>
#include <math.h>
#include <array>

/************************************************************
This is a simple isend/ireceive program in MPI
************************************************************/
using namespace std;

vector <vector <char>> create_environment(int dimention){
	vector <vector <char>> env;

	for (int i = 0; i < dimention; ++i){
		vector <char> row;
		for (int j = 0; j < dimention; ++j){
			row.push_back(0);
		}
		env.push_back(row);
	}

	return env;
}

vector <vector <char>> set_diagonal(vector <vector <char>> env){
	for (unsigned int i = 0; i < env.size(); ++i){
		for (unsigned int j = 0; j < env.at(i).size(); ++j){
			if (i == j){
				env[i][j] = 1;
			}
		}
	}
	for (unsigned int i = 0; i < env.size(); ++i){
		for (unsigned int j = 0; j < env.at(i).size(); ++j){
			if (j == (env.size() - i - 1)){
				env[i][j] = 1;
			}
		}
	}
	return env;
}

char * vector_to_array(vector<vector<char>> env, int dimention){
	char * arr = new char[dimention * dimention];
	int index = 0;
	for (unsigned int i = 0; i < env.size(); ++i){
		for (unsigned int j = 0; j < env[0].size(); ++j){
			arr[index] = env[i][j];
			++index;
		}
	}
	env.clear();
	return arr;
}

void print_array(char arr[], int full_dimention){
	// PRINTING ARRAY
	cout << endl;
	for (int i = 0; i < full_dimention; ++i){
		cout << (int)arr[i];
		if (((i + 1) % (int)sqrt(full_dimention)) == 0 && i / 1 != 0){
			cout << endl;
		}
	}
}

char * array_copy(char arr[], int full_dimention){
	char * new_arr = new char[full_dimention];
	copy(arr, arr + (full_dimention), new_arr);
	return new_arr;
}

int check_neighbours(char arr[], int dimention, int x){
	int count = 0;
	char a, b, c, d, e, f, g, h = 0;
	a = b = c = d = e = f = g = h;

	if ((x - dimention - 1) > -1 && ((int)((x - dimention - 1) / dimention)) == ((int)((x - dimention) / dimention))){
		a = arr[x - dimention - 1];
	}

	if (x - dimention > -1){
		b = arr[x - dimention];
	}

	if ((x - dimention + 1 > 0) && ((int)((x - dimention + 1) / dimention)) == ((int)((x - dimention) / dimention))){
		c = arr[x - dimention + 1];
	}

	if (x - 1 > -1 && ((int)((x - 1) / dimention)) == ((int)(x / dimention))){
		d = arr[x - 1];
	}

	if (x + 1 < dimention*dimention && ((int)((x + 1) / dimention)) == ((int)(x / dimention))){
		e = arr[x + 1];
	}

	if ((x + dimention - 1) < dimention*dimention && ((int)((x + dimention - 1) / dimention)) == ((int)((x + dimention) / dimention))){
		f = arr[x + dimention - 1];
	}

	if ((x + dimention) < dimention*dimention ){
		g = arr[x + dimention];
	}

	if ((x + dimention + 1) < dimention*dimention && ((int)((x + dimention + 1) / dimention)) == ((int)((x + dimention) / dimention))){
		h = arr[x + dimention + 1];
	}

	count = a + b + c + d + e + f + g + h;

	return count;
}

int main(int argc, char *argv[])
{

	int tag = 7;
	int count = 10;
	int dimention = 10;
	int full_dimention = 100;

	//MPI_Status status;
	//MPI_Request request;
	MPI_Request request;
    MPI_Status status;
	request = MPI_REQUEST_NULL;

	MPI_Request	send_request,recv_request;

	const int size = 10;

 	char buffi[100] = {};
 	char buffo[100] = {};
 	char buffc[100];

 	for (int i = 0; i < 100; ++i){
 		buffc[i] = 0;
 	}

 	//print_array(buffo, 100);

 	vector< vector<char>> env = create_environment(dimention);
	env = set_diagonal(env);

	char * arr = vector_to_array(env, dimention);
	char * b_arr = array_copy(arr, full_dimention);

	int	        buffsize = 100;
	char       *sendbuff,*recvbuff;
	sendbuff=(char *)malloc(sizeof(char)*buffsize);
	recvbuff=(char *)malloc(sizeof(char)*buffsize);

	for(int i=0;i<buffsize;i++){
     sendbuff[i]=0;
   	}

	//print_array(arr, full_dimention);

	// int test = 0;
	// if (test == 1){

	// 	cout << "ITERATIONS TEST" << endl;

	// 	int iterations = 13;

	// 	char * b_arr = array_copy(arr, full_dimention);

	// 	while (iterations > 0){

	// 		char * c_arr = array_copy(b_arr, full_dimention);

	// 		for (int i = 0; i < full_dimention; ++i){

	// 			int neighbours = check_neighbours(b_arr, dimention, i);

	// 			if (b_arr[i] == 0){
	// 				if (neighbours == 1 || neighbours == 2){
	// 					c_arr[i] = 1;
	// 				}
	// 			}
	// 			else {
	// 				if (neighbours > 2 || neighbours < 1){
	// 					c_arr[i] = 0;
	// 				}
	// 			}
	// 		}
	// 		cout << iterations << endl;
	// 	 	print_array(c_arr, full_dimention);

	// 	 	copy(c_arr, c_arr + (full_dimention), b_arr);
	// 	 	--iterations;
	// 	 	free(c_arr);

	// 	}
	// }

	// CORRECT ABOVE

	// MPI INIT
	MPI_Init(&argc,&argv);

	int numprocs;
	MPI_Comm_size(MPI_COMM_WORLD,&numprocs);

	int id;
	MPI_Comm_rank(MPI_COMM_WORLD,&id);

	int iterations = 2;

	//while (iterations > 0){
		if (id == 1){

			//MPI_Irecv(&buffc,full_dimention,MPI_CHAR,0,tag,MPI_COMM_WORLD,&request);
			int ierr=MPI_Irecv(recvbuff,buffsize,MPI_CHAR,0,tag,MPI_COMM_WORLD,&recv_request);
			ierr=MPI_Wait(&recv_request,&status);
			//print_array(recvbuff, full_dimention);

		}
		if (id == 0){

			//MPI_Isend(&arr,full_dimention,MPI_CHAR,1,tag,MPI_COMM_WORLD,&request);
			int ierr=MPI_Isend(arr,buffsize,MPI_CHAR, 1,tag,MPI_COMM_WORLD,&send_request);
			//print_array(arr, full_dimention);
			ierr=MPI_Wait(&send_request,&status);
		}

		//MPI_Wait(&request,&status);

		if (id == 1){
			--iterations;

			//cout << " Array "<< iterations <<" has been received." << endl;
			//print_array(buffo, 100);

			print_array(recvbuff, full_dimention);
			// int sum = 0;
			// for (int i = 0; i < full_dimention;++i){
			// 	sum += recvbuff[i];
			// }
			// cout << sum << endl;
		}

		--iterations;
	//}

	MPI_Finalize();

	return 0;

 	// MPI INIT
	MPI_Init(&argc,&argv);

	//int numprocs;
	MPI_Comm_size(MPI_COMM_WORLD,&numprocs);

	//int id;
	MPI_Comm_rank(MPI_COMM_WORLD,&id);

	if(id == 0){
		//MPI_Isend(&buffi,count,MPI_CHAR,0,tag,MPI_COMM_WORLD,&request);
		//MPI_Isend(&buffi,count,MPI_CHAR,1,tag,MPI_COMM_WORLD,&request);
		//MPI_Isend(&buffi,count,MPI_CHAR,2,tag,MPI_COMM_WORLD,&request);
		//MPI_Isend(&buffi,count,MPI_CHAR,3,tag,MPI_COMM_WORLD,&request);
	}
	if(id == 0){
		//MPI_Irecv(&buffo,count,MPI_CHAR,0,tag,MPI_COMM_WORLD,&request);
	}
	if(id == 1){
		//MPI_Irecv(&buffo,count,MPI_CHAR,0,tag,MPI_COMM_WORLD,&request);
	}
	if(id == 2){
		//MPI_Irecv(&buffo,count,MPI_CHAR,0,tag,MPI_COMM_WORLD,&request);
	}
	if(id == 3){
		//MPI_Irecv(&buffo,count,MPI_CHAR,0,tag,MPI_COMM_WORLD,&request);
	}

	//MPI_Wait(&request,&status);
	if(id == 0){
		printf("processor %d sent %d\n",id,(int)buffi[0]);
		printf("processor %d sent %d\n",id,(int)buffi[0]);
		printf("processor %d sent %d\n",id,(int)buffi[0]);
		printf("processor %d sent %d\n",id,(int)buffi[0]);
	}
	if(id == 0){
		for (unsigned int i = 0; i < count; ++i){
			printf("processor %d got %d - %d\n",id,i,(int)buffo[i]);
		}
	}
	if(id == 1){
		for (unsigned int i = 0; i < count; ++i){
			printf("processor %d got %d - %d\n",id,i,(int)buffo[i]);
		}
	}
	if(id == 2){
		for (unsigned int i = 0; i < count; ++i){
			printf("processor %d got %d - %d\n",id,i,(int)buffo[i]);
		}
	}
	if(id == 3){
		for (unsigned int i = 0; i < count; ++i){
			printf("processor %d got %d - %d\n",id,i,(int)buffo[i]);
		}
	}

	MPI_Finalize();

	return 0;
}<|endoftext|>


<commit_before>#ifndef SCHEDULER_TAG_HH
# define SCHEDULER_TAG_HH

# include <vector>

# include <libport/symbol.hh>
# include <libport/weak-ptr.hh>

# include "scheduler/fwd.hh"

namespace scheduler
{

  // A Tag is an entity attached to zero or more scheduler jobs. Each job
  // can have zero or more tags. When a new job is created, it usually
  // inherits the tags from its creator.
  //
  // The Tag state is represented by two parameters:
  //
  //   - frozen: jobs with this tag are not supposed to do any useful work;
  //
  //   - blocked: jobs with this tag are supposed to rewind their call
  //     stack until they die or until they are no longer affected by
  //     the tag.
  //
  // A tag is frozen when it has been explicitly frozen or when its parent
  // is frozen. Ditto for blocked.
  //
  // Stopping a tag is an immediate operation: all the jobs holding this
  // tag must act as if they were blocked, but only once. For example, they
  // must rewind their call stack in order not to be blocked anymore, but
  // when they resume execution, if they get the same tag again, they will
  // not act as if they were blocked again.

  class Tag: public libport::RefCounted
  {
  public:
    // Create a new tag, with or without a parent
    static rTag fresh (libport::Symbol name);
    static rTag fresh (rTag parent, libport::Symbol name);
    virtual ~Tag ();

    // Get a reference-counted pointer on the tag
    rTag self () const;

    // Is this tag directly or indirectly frozen or blocked?
    bool frozen () const;
    bool blocked () const;

    // Act on a tag and make the scheduler take it into account
    void freeze (Scheduler&);
    void unfreeze (Scheduler&);
    void block (Scheduler&);
    void unblock (Scheduler&);
    void stop (Scheduler&);

    // Return true if the tag has been directly blocked through a call
    // to "block". Return false if it is only indirectly blocked
    // through its parent.
    bool own_blocked () const;

    // Mark the tag as blocked. This is supposed to be used by the
    // scheduler to execute a "stop" command. It can also be used to
    // block a tag but without necessarily resuming its execution so that
    // it can rewind its call stack. For example, it can be used to stop
    // jobs if we know that the tag is permanently attached to the job:
    // if the job is currently sleeping, it may not be woken up just
    // so that it can die, it may die after it is done sleeping.
    void set_blocked (bool);

    const libport::Symbol& name_get () const;

  private:
    Tag (libport::Symbol name);
    Tag (rTag parent, libport::Symbol name);
    rTag            parent_;
    bool            blocked_;
    bool            frozen_;
    libport::Symbol name_;
  };

  typedef std::vector<rTag> tags_type;

} // namespace scheduler

# include "scheduler/tag.hxx"

#endif // SCHEDULER_TAG_HH
<commit_msg>Do not include unused weak-ptr.hh.<commit_after>#ifndef SCHEDULER_TAG_HH
# define SCHEDULER_TAG_HH

# include <vector>

# include <libport/symbol.hh>

# include "scheduler/fwd.hh"

namespace scheduler
{

  // A Tag is an entity attached to zero or more scheduler jobs. Each job
  // can have zero or more tags. When a new job is created, it usually
  // inherits the tags from its creator.
  //
  // The Tag state is represented by two parameters:
  //
  //   - frozen: jobs with this tag are not supposed to do any useful work;
  //
  //   - blocked: jobs with this tag are supposed to rewind their call
  //     stack until they die or until they are no longer affected by
  //     the tag.
  //
  // A tag is frozen when it has been explicitly frozen or when its parent
  // is frozen. Ditto for blocked.
  //
  // Stopping a tag is an immediate operation: all the jobs holding this
  // tag must act as if they were blocked, but only once. For example, they
  // must rewind their call stack in order not to be blocked anymore, but
  // when they resume execution, if they get the same tag again, they will
  // not act as if they were blocked again.

  class Tag: public libport::RefCounted
  {
  public:
    // Create a new tag, with or without a parent
    static rTag fresh (libport::Symbol name);
    static rTag fresh (rTag parent, libport::Symbol name);
    virtual ~Tag ();

    // Get a reference-counted pointer on the tag
    rTag self () const;

    // Is this tag directly or indirectly frozen or blocked?
    bool frozen () const;
    bool blocked () const;

    // Act on a tag and make the scheduler take it into account
    void freeze (Scheduler&);
    void unfreeze (Scheduler&);
    void block (Scheduler&);
    void unblock (Scheduler&);
    void stop (Scheduler&);

    // Return true if the tag has been directly blocked through a call
    // to "block". Return false if it is only indirectly blocked
    // through its parent.
    bool own_blocked () const;

    // Mark the tag as blocked. This is supposed to be used by the
    // scheduler to execute a "stop" command. It can also be used to
    // block a tag but without necessarily resuming its execution so that
    // it can rewind its call stack. For example, it can be used to stop
    // jobs if we know that the tag is permanently attached to the job:
    // if the job is currently sleeping, it may not be woken up just
    // so that it can die, it may die after it is done sleeping.
    void set_blocked (bool);

    const libport::Symbol& name_get () const;

  private:
    Tag (libport::Symbol name);
    Tag (rTag parent, libport::Symbol name);
    rTag            parent_;
    bool            blocked_;
    bool            frozen_;
    libport::Symbol name_;
  };

  typedef std::vector<rTag> tags_type;

} // namespace scheduler

# include "scheduler/tag.hxx"

#endif // SCHEDULER_TAG_HH
<|endoftext|>


<commit_before>#include <gtk/gtk.h>

#include <Scintilla.h>
#include <SciLexer.h>
#define PLAT_GTK 1
#include <ScintillaWidget.h>

#include <v8.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <map>
#include <string>

#include "sciMessages.h"

char* filename;

v8::Handle<v8::Script> readFromFile(char* filename);

v8::Isolate* isolate;
v8::Handle<v8::Context> context;

static int exit_app(GtkWidget*w, GdkEventAny*e, gpointer p) {
   gtk_main_quit();
   return w||e||p||1;	// Avoid warnings
}

static void log(const v8::FunctionCallbackInfo<v8::Value>& args) {
	v8::String::AsciiValue what(args[0]);
	std::cout << ">>> " << *what << "\n";
}

std::map<std::string, v8::Persistent<v8::Function> > handlers;

static void setHandler(const v8::FunctionCallbackInfo<v8::Value>& args) {
	v8::String::AsciiValue ascii2(args[0]);
	printf("setting handler for: %s\n", *ascii2);
	v8::Persistent<v8::Function> charAddedHandler = v8::Persistent<v8::Function>::New(v8::Handle<v8::Function>::Cast(args[1]));
	handlers[*ascii2] = charAddedHandler;
}

static void saveIt(const v8::FunctionCallbackInfo<v8::Value>& args) {
    if (filename != NULL) {
        std::cout << "this should save the file to " << filename << " ...\n";

        int n = scintilla_send_message(sci, SCI_GETLENGTH, 0, 0);
        std::cout << "text length should be " << n << "\n";

        char* contents = (char*) malloc(n + 1);
        scintilla_send_message(sci, SCI_GETTEXT, n + 1, (sptr_t) contents);
        std::cout << "text contents should be " << contents << "\n";

        std::ofstream myfile;
        myfile.open (filename);
        myfile << contents;
        myfile.close();
        free(contents);
    } else {
        std::cout << "tried to save but there is no filename\n";
    }
}

static std::map<int, std::string> signals;

static void handleSCISignal(GtkWidget *, gint /*wParam*/, SCNotification *notification, void *data) {
	int code = notification->nmhdr.code;
	std::string signal = signals[code];
    if (!signal.empty()) {
        std::cout << "Calling handler for " << signal << "! (if any)\n";
        v8::Persistent<v8::Function> handler = handlers.at(signal);
        v8::Local<v8::Object> global = context->Global();
        v8::Handle<v8::Value> args[2];
        args[0] = v8::Number::New(notification->ch);
        args[1] = v8::Number::New(notification->modifiers);
        handler->Call(global, 2, args);
    }
}

int main(int argc, char **argv) {

    /* TODO Take this out of here */
    signals[SCN_CHARADDED] = "charAdded";
    signals[SCN_KEY] = "key";

	GtkWidget *app;
	GtkWidget *editor;

	gtk_init(&argc, &argv);
	app = gtk_window_new(GTK_WINDOW_TOPLEVEL);
	editor = scintilla_new();
	sci = SCINTILLA(editor);

    GtkWidget* layout = gtk_fixed_new();

	gtk_container_add(GTK_CONTAINER(app), layout);
	gtk_fixed_put(GTK_FIXED(layout), editor, 0, 20);

	gtk_signal_connect(GTK_OBJECT(app), "delete_event", GTK_SIGNAL_FUNC(exit_app), 0);

	scintilla_set_id(sci, 0);
	gtk_widget_set_usize(editor, 500, 300);

	/***************/
	/* Try adding a new editor pane to the same window */

    GtkWidget *pane;
    pane = scintilla_new();
	ScintillaObject *sci2 = SCINTILLA(pane);
	gtk_fixed_put(GTK_FIXED(layout), pane, 0, 0);
	scintilla_set_id(sci2, 1);

	scintilla_send_message(sci2, SCI_SETWRAPMODE, 2, 0);

    scintilla_send_message(sci2, SCI_STYLECLEARALL, 0, 0);

    scintilla_send_message(sci2, SCI_STYLESETFONT, 0, (sptr_t) "monospace");
    scintilla_send_message(sci2, SCI_STYLESETSIZE, 0, 10);

	gtk_widget_set_usize(pane, 500, 20);

	/***************/
	/* Try reading a file */
	if (argc > 1) {
	    filename = argv[1];

	    std::cout << "Will read file '" << filename << "'\n";

	    FILE *f = fopen(filename, "r");
        fseek(f, 0, SEEK_END);
        long fsize = ftell(f);
        fseek(f, 0, SEEK_SET);

        char *string = (char*) malloc(fsize + 1);
        fread(string, fsize, 1, f);
        fclose(f);

        string[fsize] = 0;
        scintilla_send_message(sci, SCI_INSERTTEXT, 0, (sptr_t) string);
        scintilla_send_message(sci2, SCI_INSERTTEXT, 0, (sptr_t) filename);
	} else {
	    std::cout << "No filename passed\n";
	    scintilla_send_message(sci2, SCI_INSERTTEXT, 0, (sptr_t) "[new file]");
	}

	scintilla_send_message(sci2, SCI_SETREADONLY, 1, 0);
	/***************/

	isolate = v8::Isolate::GetCurrent();
	v8::HandleScope handle_scope(isolate);

	v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();

	v8::Handle<v8::ObjectTemplate> sciObj = v8::ObjectTemplate::New();

	global->Set(v8::String::New("SCI"), sciObj);
	makeFunsAvailable(sciObj);
	sciObj->Set(v8::String::New("on"), v8::FunctionTemplate::New(setHandler));

	v8::Handle<v8::ObjectTemplate> utilObj = v8::ObjectTemplate::New();
	global->Set(v8::String::New("Util"), utilObj);
	utilObj->Set(v8::String::New("save"), v8::FunctionTemplate::New(saveIt));
	utilObj->Set(v8::String::New("log"), v8::FunctionTemplate::New(log));

	g_signal_connect(editor, SCINTILLA_NOTIFY, G_CALLBACK(handleSCISignal), NULL);

	context = v8::Context::New(isolate, NULL, global);
	v8::Context::Scope context_scope(context);

	v8::Handle<v8::Script> script = readFromFile("./.sciborg.js");
	v8::Handle<v8::Value> result = script->Run();

	gtk_widget_show_all(app);
	gtk_widget_grab_focus(GTK_WIDGET(editor));
	gtk_main();

	return 0;
}

v8::Handle<v8::Script> readFromFile(char* filename) {
	// PARSING JS FILE
	FILE *f = fopen(filename, "r");
	fseek(f, 0, SEEK_END);
	long fsize = ftell(f);
	fseek(f, 0, SEEK_SET);

	char *string = (char*) malloc(fsize + 1);
	fread(string, fsize, 1, f);
	fclose(f);

	string[fsize] = 0;
	//printf("contents: %s\n", string);
	v8::Handle<v8::String> source = v8::String::New(string);
	return v8::Script::Compile(source);
}

<commit_msg>Added a nice new panel intended for an interactive console. Switched to VBox layout, contents now expand with the window size.<commit_after>#include <gtk/gtk.h>

#include <Scintilla.h>
#include <SciLexer.h>
#define PLAT_GTK 1
#include <ScintillaWidget.h>

#include <v8.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <map>
#include <string>

#include "sciMessages.h"

char* filename;

v8::Handle<v8::Script> readFromFile(char* filename);

v8::Isolate* isolate;
v8::Handle<v8::Context> context;

static int exit_app(GtkWidget*w, GdkEventAny*e, gpointer p) {
   gtk_main_quit();
   return w||e||p||1;	// Avoid warnings
}

static void log(const v8::FunctionCallbackInfo<v8::Value>& args) {
	v8::String::AsciiValue what(args[0]);
	std::cout << ">>> " << *what << "\n";
}

std::map<std::string, v8::Persistent<v8::Function> > handlers;

static void setHandler(const v8::FunctionCallbackInfo<v8::Value>& args) {
	v8::String::AsciiValue ascii2(args[0]);
	printf("setting handler for: %s\n", *ascii2);
	v8::Persistent<v8::Function> charAddedHandler = v8::Persistent<v8::Function>::New(v8::Handle<v8::Function>::Cast(args[1]));
	handlers[*ascii2] = charAddedHandler;
}

static void saveIt(const v8::FunctionCallbackInfo<v8::Value>& args) {
    if (filename != NULL) {
        std::cout << "this should save the file to " << filename << " ...\n";

        int n = scintilla_send_message(sci, SCI_GETLENGTH, 0, 0);
        std::cout << "text length should be " << n << "\n";

        char* contents = (char*) malloc(n + 1);
        scintilla_send_message(sci, SCI_GETTEXT, n + 1, (sptr_t) contents);
        std::cout << "text contents should be " << contents << "\n";

        std::ofstream myfile;
        myfile.open (filename);
        myfile << contents;
        myfile.close();
        free(contents);
    } else {
        std::cout << "tried to save but there is no filename\n";
    }
}

static std::map<int, std::string> signals;

static void handleSCISignal(GtkWidget *, gint /*wParam*/, SCNotification *notification, void *data) {
	int code = notification->nmhdr.code;
	std::string signal = signals[code];
    if (!signal.empty()) {
        std::cout << "Calling handler for " << signal << "! (if any)\n";
        v8::Persistent<v8::Function> handler = handlers.at(signal);
        v8::Local<v8::Object> global = context->Global();
        v8::Handle<v8::Value> args[2];
        args[0] = v8::Number::New(notification->ch);
        args[1] = v8::Number::New(notification->modifiers);
        handler->Call(global, 2, args);
    }
}

int main(int argc, char **argv) {

    /* TODO Take this out of here */
    signals[SCN_CHARADDED] = "charAdded";
    signals[SCN_KEY] = "key";

	GtkWidget *app;
	GtkWidget *editor;

	gtk_init(&argc, &argv);
	app = gtk_window_new(GTK_WINDOW_TOPLEVEL);
	editor = scintilla_new();
	gtk_widget_set_usize(editor, 500, 300);
	sci = SCINTILLA(editor);
	scintilla_set_id(sci, 0);

    GtkWidget* vbox = gtk_vbox_new(FALSE, 0);

	gtk_container_add(GTK_CONTAINER(app), vbox);

	gtk_signal_connect(GTK_OBJECT(app), "delete_event", GTK_SIGNAL_FUNC(exit_app), 0);

	/***************/
	/* Try adding a new editor pane to the same window */

    GtkWidget *pane;
    pane = scintilla_new();
    gtk_widget_set_usize(pane, 500, 20);

	ScintillaObject *sci2 = SCINTILLA(pane);
	scintilla_set_id(sci2, 1);

	scintilla_send_message(sci2, SCI_SETWRAPMODE, 2, 0);
    scintilla_send_message(sci2, SCI_STYLECLEARALL, 0, 0);
    scintilla_send_message(sci2, SCI_STYLESETFONT, 0, (sptr_t) "monospace");
    scintilla_send_message(sci2, SCI_STYLESETSIZE, 0, 10);

    GtkWidget *console;
    console = scintilla_new();
    gtk_widget_set_usize(console, 500, 60);

	ScintillaObject *sci3 = SCINTILLA(console);
	scintilla_set_id(sci3, 2);

	scintilla_send_message(sci3, SCI_SETWRAPMODE, 2, 0);
    scintilla_send_message(sci3, SCI_STYLECLEARALL, 0, 0);
    scintilla_send_message(sci3, SCI_STYLESETFONT, 0, (sptr_t) "monospace");
    scintilla_send_message(sci3, SCI_STYLESETSIZE, 0, 10);

	gtk_box_pack_start(GTK_BOX(vbox), pane, FALSE, FALSE, 0);
	gtk_box_pack_start(GTK_BOX(vbox), editor, TRUE, TRUE, 0);
	gtk_box_pack_start(GTK_BOX(vbox), console, FALSE, FALSE, 0);

	/***************/
	/* Try reading a file */
	if (argc > 1) {
	    filename = argv[1];

	    std::cout << "Will read file '" << filename << "'\n";

	    FILE *f = fopen(filename, "r");
        fseek(f, 0, SEEK_END);
        long fsize = ftell(f);
        fseek(f, 0, SEEK_SET);

        char *string = (char*) malloc(fsize + 1);
        fread(string, fsize, 1, f);
        fclose(f);

        string[fsize] = 0;
        scintilla_send_message(sci, SCI_INSERTTEXT, 0, (sptr_t) string);
        scintilla_send_message(sci2, SCI_INSERTTEXT, 0, (sptr_t) filename);
	} else {
	    std::cout << "No filename passed\n";
	    scintilla_send_message(sci2, SCI_INSERTTEXT, 0, (sptr_t) "[new file]");
	}

	scintilla_send_message(sci2, SCI_SETREADONLY, 1, 0);
	/***************/

	isolate = v8::Isolate::GetCurrent();
	v8::HandleScope handle_scope(isolate);

	v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();

	v8::Handle<v8::ObjectTemplate> sciObj = v8::ObjectTemplate::New();

	global->Set(v8::String::New("SCI"), sciObj);
	makeFunsAvailable(sciObj);
	sciObj->Set(v8::String::New("on"), v8::FunctionTemplate::New(setHandler));

	v8::Handle<v8::ObjectTemplate> utilObj = v8::ObjectTemplate::New();
	global->Set(v8::String::New("Util"), utilObj);
	utilObj->Set(v8::String::New("save"), v8::FunctionTemplate::New(saveIt));
	utilObj->Set(v8::String::New("log"), v8::FunctionTemplate::New(log));

	g_signal_connect(editor, SCINTILLA_NOTIFY, G_CALLBACK(handleSCISignal), NULL);

	context = v8::Context::New(isolate, NULL, global);
	v8::Context::Scope context_scope(context);

	v8::Handle<v8::Script> script = readFromFile("./.sciborg.js");
	v8::Handle<v8::Value> result = script->Run();

	gtk_widget_show_all(app);
	gtk_widget_grab_focus(GTK_WIDGET(editor));
	gtk_main();

	return 0;
}

v8::Handle<v8::Script> readFromFile(char* filename) {
	// PARSING JS FILE
	FILE *f = fopen(filename, "r");
	fseek(f, 0, SEEK_END);
	long fsize = ftell(f);
	fseek(f, 0, SEEK_SET);

	char *string = (char*) malloc(fsize + 1);
	fread(string, fsize, 1, f);
	fclose(f);

	string[fsize] = 0;
	//printf("contents: %s\n", string);
	v8::Handle<v8::String> source = v8::String::New(string);
	return v8::Script::Compile(source);
}

<|endoftext|>


<commit_before>/*********************************************************************
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2018 Pilz GmbH & Co. KG
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Pilz GmbH & Co. KG nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *********************************************************************/

#include "pilz_industrial_motion_planner/trajectory_generator_ptp.h"
#include "moveit/robot_state/conversions.h"
#include "ros/ros.h"

#include <iostream>
#include <sstream>

#include <tf2_eigen/tf2_eigen.h>
#include <tf2_geometry_msgs/tf2_geometry_msgs.h>

namespace pilz_industrial_motion_planner
{
TrajectoryGeneratorPTP::TrajectoryGeneratorPTP(const robot_model::RobotModelConstPtr& robot_model,
                                               const LimitsContainer& planner_limits)
  : TrajectoryGenerator::TrajectoryGenerator(robot_model, planner_limits)
{
  if (!planner_limits_.hasJointLimits())
  {
    throw TrajectoryGeneratorInvalidLimitsException("joint limit not set");
  }

  joint_limits_ = planner_limits_.getJointLimitContainer();

  // collect most strict joint limits for each group in robot model
  for (const auto& jmg : robot_model->getJointModelGroups())
  {
    const auto& active_joints = jmg->getActiveJointModelNames();

    // no active joints
    if (active_joints.empty())
    {
      continue;
    }

    JointLimit most_strict_limit = joint_limits_.getCommonLimit(active_joints);

    if (!most_strict_limit.has_velocity_limits)
    {
      ROS_ERROR_STREAM("velocity limit not set for group " << jmg->getName());
      throw TrajectoryGeneratorInvalidLimitsException("velocity limit not set for group " + jmg->getName());
    }
    if (!most_strict_limit.has_acceleration_limits)
    {
      ROS_ERROR_STREAM("acceleration limit not set for group " << jmg->getName());
      throw TrajectoryGeneratorInvalidLimitsException("acceleration limit not set for group " + jmg->getName());
    }
    if (!most_strict_limit.has_deceleration_limits)
    {
      ROS_ERROR_STREAM("deceleration limit not set for group " << jmg->getName());
      throw TrajectoryGeneratorInvalidLimitsException("deceleration limit not set for group " + jmg->getName());
    }

    most_strict_limits_.insert(std::pair<std::string, JointLimit>(jmg->getName(), most_strict_limit));
  }

  ROS_INFO("Initialized Point-to-Point Trajectory Generator.");
}

void TrajectoryGeneratorPTP::planPTP(const std::map<std::string, double>& start_pos,
                                     const std::map<std::string, double>& goal_pos,
                                     trajectory_msgs::JointTrajectory& joint_trajectory, const std::string& group_name,
                                     const double& velocity_scaling_factor, const double& acceleration_scaling_factor,
                                     const double& sampling_time)
{
  // initialize joint names
  for (const auto& item : goal_pos)
  {
    joint_trajectory.joint_names.push_back(item.first);
  }

  // check if goal already reached
  bool goal_reached = true;
  for (auto const& goal : goal_pos)
  {
    if (fabs(start_pos.at(goal.first) - goal.second) >= MIN_MOVEMENT)
    {
      goal_reached = false;
      break;
    }
  }
  if (goal_reached)
  {
    ROS_INFO_STREAM("Goal already reached, set one goal point explicitly.");
    if (joint_trajectory.points.empty())
    {
      trajectory_msgs::JointTrajectoryPoint point;
      point.time_from_start = ros::Duration(sampling_time);
      for (const std::string& joint_name : joint_trajectory.joint_names)
      {
        point.positions.push_back(start_pos.at(joint_name));
        point.velocities.push_back(0);
        point.accelerations.push_back(0);
      }
      joint_trajectory.points.push_back(point);
    }
    return;
  }

  // compute the fastest trajectory and choose the slowest joint as leading axis
  std::string leading_axis = joint_trajectory.joint_names.front();
  double max_duration = -1.0;

  std::map<std::string, VelocityProfileATrap> velocity_profile;
  for (const auto& joint_name : joint_trajectory.joint_names)
  {
    // create vecocity profile if necessary
    velocity_profile.insert(std::make_pair(
        joint_name,
        VelocityProfileATrap(velocity_scaling_factor * most_strict_limits_.at(group_name).max_velocity,
                             acceleration_scaling_factor * most_strict_limits_.at(group_name).max_acceleration,
                             acceleration_scaling_factor * most_strict_limits_.at(group_name).max_deceleration)));

    velocity_profile.at(joint_name).SetProfile(start_pos.at(joint_name), goal_pos.at(joint_name));
    if (velocity_profile.at(joint_name).Duration() > max_duration)
    {
      max_duration = velocity_profile.at(joint_name).Duration();
      leading_axis = joint_name;
    }
  }

  // Full Synchronization
  // This should only work if all axes have same max_vel, max_acc, max_dec
  // values
  // reset the velocity profile for other joints
  double acc_time = velocity_profile.at(leading_axis).firstPhaseDuration();
  double const_time = velocity_profile.at(leading_axis).secondPhaseDuration();
  double dec_time = velocity_profile.at(leading_axis).thirdPhaseDuration();

  for (const auto& joint_name : joint_trajectory.joint_names)
  {
    if (joint_name != leading_axis)
    {
      // make full synchronization
      // causes the program to terminate if acc_time<=0 or dec_time<=0 (should
      // be prevented by goal_reached block above)
      // by using the most strict limit, the following should always return true
      if (!velocity_profile.at(joint_name)
               .setProfileAllDurations(start_pos.at(joint_name), goal_pos.at(joint_name), acc_time, const_time,
                                       dec_time))
      // LCOV_EXCL_START
      {
        std::stringstream error_str;
        error_str << "TrajectoryGeneratorPTP::planPTP(): Can not synchronize "
                     "velocity profile of axis "
                  << joint_name << " with leading axis " << leading_axis;
        throw PtpVelocityProfileSyncFailed(error_str.str());
      }
      // LCOV_EXCL_STOP
    }
  }

  // first generate the time samples
  std::vector<double> time_samples;
  for (double t_sample = 0.0; t_sample < max_duration; t_sample += sampling_time)
  {
    time_samples.push_back(t_sample);
  }
  // add last time
  time_samples.push_back(max_duration);

  // construct joint trajectory point
  for (double time_stamp : time_samples)
  {
    trajectory_msgs::JointTrajectoryPoint point;
    point.time_from_start = ros::Duration(time_stamp);
    for (std::string& joint_name : joint_trajectory.joint_names)
    {
      point.positions.push_back(velocity_profile.at(joint_name).Pos(time_stamp));
      point.velocities.push_back(velocity_profile.at(joint_name).Vel(time_stamp));
      point.accelerations.push_back(velocity_profile.at(joint_name).Acc(time_stamp));
    }
    joint_trajectory.points.push_back(point);
  }

  // Set last point velocity and acceleration to zero
  std::fill(joint_trajectory.points.back().velocities.begin(), joint_trajectory.points.back().velocities.end(), 0.0);
  std::fill(joint_trajectory.points.back().accelerations.begin(), joint_trajectory.points.back().accelerations.end(),
            0.0);
}

void TrajectoryGeneratorPTP::extractMotionPlanInfo(const planning_scene::PlanningSceneConstPtr& scene,
                                                   const planning_interface::MotionPlanRequest& req,
                                                   MotionPlanInfo& info) const
{
  info.group_name = req.group_name;

  // extract start state information
  info.start_joint_position.clear();
  for (std::size_t i = 0; i < req.start_state.joint_state.name.size(); ++i)
  {
    info.start_joint_position[req.start_state.joint_state.name[i]] = req.start_state.joint_state.position[i];
  }

  // extract goal
  info.goal_joint_position.clear();
  if (!req.goal_constraints.at(0).joint_constraints.empty())
  {
    for (const auto& joint_constraint : req.goal_constraints.at(0).joint_constraints)
    {
      info.goal_joint_position[joint_constraint.joint_name] = joint_constraint.position;
    }
  }
  // slove the ik
  else
  {
    geometry_msgs::Point p =
        req.goal_constraints.at(0).position_constraints.at(0).constraint_region.primitive_poses.at(0).position;
    p.x -= req.goal_constraints.at(0).position_constraints.at(0).target_point_offset.x;
    p.y -= req.goal_constraints.at(0).position_constraints.at(0).target_point_offset.y;
    p.z -= req.goal_constraints.at(0).position_constraints.at(0).target_point_offset.z;

    geometry_msgs::Pose pose;
    pose.position = p;
    pose.orientation = req.goal_constraints.at(0).orientation_constraints.at(0).orientation;
    Eigen::Isometry3d pose_eigen;
    normalizeQuaternion(pose.orientation);
    tf2::fromMsg(pose, pose_eigen);
    if (!computePoseIK(scene, req.group_name, req.goal_constraints.at(0).position_constraints.at(0).link_name,
                       pose_eigen, robot_model_->getModelFrame(), info.start_joint_position, info.goal_joint_position))
    {
      throw PtpNoIkSolutionForGoalPose("No IK solution for goal pose");
    }
  }
}

void TrajectoryGeneratorPTP::plan(const planning_scene::PlanningSceneConstPtr& /*scene*/,
                                  const planning_interface::MotionPlanRequest& req, const MotionPlanInfo& plan_info,
                                  const double& sampling_time, trajectory_msgs::JointTrajectory& joint_trajectory)
{
  // plan the ptp trajectory
  planPTP(plan_info.start_joint_position, plan_info.goal_joint_position, joint_trajectory, plan_info.group_name,
          req.max_velocity_scaling_factor, req.max_acceleration_scaling_factor, sampling_time);
}

}  // namespace pilz_industrial_motion_planner
<commit_msg>Avoid duplicate error messages<commit_after>/*********************************************************************
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2018 Pilz GmbH & Co. KG
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Pilz GmbH & Co. KG nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *********************************************************************/

#include "pilz_industrial_motion_planner/trajectory_generator_ptp.h"
#include "moveit/robot_state/conversions.h"
#include "ros/ros.h"

#include <iostream>
#include <sstream>

#include <tf2_eigen/tf2_eigen.h>
#include <tf2_geometry_msgs/tf2_geometry_msgs.h>

namespace pilz_industrial_motion_planner
{
TrajectoryGeneratorPTP::TrajectoryGeneratorPTP(const robot_model::RobotModelConstPtr& robot_model,
                                               const LimitsContainer& planner_limits)
  : TrajectoryGenerator::TrajectoryGenerator(robot_model, planner_limits)
{
  if (!planner_limits_.hasJointLimits())
  {
    throw TrajectoryGeneratorInvalidLimitsException("joint limit not set");
  }

  joint_limits_ = planner_limits_.getJointLimitContainer();

  // collect most strict joint limits for each group in robot model
  for (const auto& jmg : robot_model->getJointModelGroups())
  {
    const auto& active_joints = jmg->getActiveJointModelNames();

    // no active joints
    if (active_joints.empty())
    {
      continue;
    }

    JointLimit most_strict_limit = joint_limits_.getCommonLimit(active_joints);

    if (!most_strict_limit.has_velocity_limits)
      throw TrajectoryGeneratorInvalidLimitsException("velocity limit not set for group " + group_name);
    if (!most_strict_limit.has_acceleration_limits)
      throw TrajectoryGeneratorInvalidLimitsException("acceleration limit not set for group " + group_name);
    if (!most_strict_limit.has_deceleration_limits)
      throw TrajectoryGeneratorInvalidLimitsException("deceleration limit not set for group " + group_name);

    most_strict_limits_.insert(std::pair<std::string, JointLimit>(jmg->getName(), most_strict_limit));
  }

  ROS_INFO("Initialized Point-to-Point Trajectory Generator.");
}

void TrajectoryGeneratorPTP::planPTP(const std::map<std::string, double>& start_pos,
                                     const std::map<std::string, double>& goal_pos,
                                     trajectory_msgs::JointTrajectory& joint_trajectory, const std::string& group_name,
                                     const double& velocity_scaling_factor, const double& acceleration_scaling_factor,
                                     const double& sampling_time)
{
  // initialize joint names
  for (const auto& item : goal_pos)
  {
    joint_trajectory.joint_names.push_back(item.first);
  }

  // check if goal already reached
  bool goal_reached = true;
  for (auto const& goal : goal_pos)
  {
    if (fabs(start_pos.at(goal.first) - goal.second) >= MIN_MOVEMENT)
    {
      goal_reached = false;
      break;
    }
  }
  if (goal_reached)
  {
    ROS_INFO_STREAM("Goal already reached, set one goal point explicitly.");
    if (joint_trajectory.points.empty())
    {
      trajectory_msgs::JointTrajectoryPoint point;
      point.time_from_start = ros::Duration(sampling_time);
      for (const std::string& joint_name : joint_trajectory.joint_names)
      {
        point.positions.push_back(start_pos.at(joint_name));
        point.velocities.push_back(0);
        point.accelerations.push_back(0);
      }
      joint_trajectory.points.push_back(point);
    }
    return;
  }

  // compute the fastest trajectory and choose the slowest joint as leading axis
  std::string leading_axis = joint_trajectory.joint_names.front();
  double max_duration = -1.0;

  std::map<std::string, VelocityProfileATrap> velocity_profile;
  for (const auto& joint_name : joint_trajectory.joint_names)
  {
    // create vecocity profile if necessary
    velocity_profile.insert(std::make_pair(
        joint_name,
        VelocityProfileATrap(velocity_scaling_factor * most_strict_limits_.at(group_name).max_velocity,
                             acceleration_scaling_factor * most_strict_limits_.at(group_name).max_acceleration,
                             acceleration_scaling_factor * most_strict_limits_.at(group_name).max_deceleration)));

    velocity_profile.at(joint_name).SetProfile(start_pos.at(joint_name), goal_pos.at(joint_name));
    if (velocity_profile.at(joint_name).Duration() > max_duration)
    {
      max_duration = velocity_profile.at(joint_name).Duration();
      leading_axis = joint_name;
    }
  }

  // Full Synchronization
  // This should only work if all axes have same max_vel, max_acc, max_dec
  // values
  // reset the velocity profile for other joints
  double acc_time = velocity_profile.at(leading_axis).firstPhaseDuration();
  double const_time = velocity_profile.at(leading_axis).secondPhaseDuration();
  double dec_time = velocity_profile.at(leading_axis).thirdPhaseDuration();

  for (const auto& joint_name : joint_trajectory.joint_names)
  {
    if (joint_name != leading_axis)
    {
      // make full synchronization
      // causes the program to terminate if acc_time<=0 or dec_time<=0 (should
      // be prevented by goal_reached block above)
      // by using the most strict limit, the following should always return true
      if (!velocity_profile.at(joint_name)
               .setProfileAllDurations(start_pos.at(joint_name), goal_pos.at(joint_name), acc_time, const_time,
                                       dec_time))
      // LCOV_EXCL_START
      {
        std::stringstream error_str;
        error_str << "TrajectoryGeneratorPTP::planPTP(): Can not synchronize "
                     "velocity profile of axis "
                  << joint_name << " with leading axis " << leading_axis;
        throw PtpVelocityProfileSyncFailed(error_str.str());
      }
      // LCOV_EXCL_STOP
    }
  }

  // first generate the time samples
  std::vector<double> time_samples;
  for (double t_sample = 0.0; t_sample < max_duration; t_sample += sampling_time)
  {
    time_samples.push_back(t_sample);
  }
  // add last time
  time_samples.push_back(max_duration);

  // construct joint trajectory point
  for (double time_stamp : time_samples)
  {
    trajectory_msgs::JointTrajectoryPoint point;
    point.time_from_start = ros::Duration(time_stamp);
    for (std::string& joint_name : joint_trajectory.joint_names)
    {
      point.positions.push_back(velocity_profile.at(joint_name).Pos(time_stamp));
      point.velocities.push_back(velocity_profile.at(joint_name).Vel(time_stamp));
      point.accelerations.push_back(velocity_profile.at(joint_name).Acc(time_stamp));
    }
    joint_trajectory.points.push_back(point);
  }

  // Set last point velocity and acceleration to zero
  std::fill(joint_trajectory.points.back().velocities.begin(), joint_trajectory.points.back().velocities.end(), 0.0);
  std::fill(joint_trajectory.points.back().accelerations.begin(), joint_trajectory.points.back().accelerations.end(),
            0.0);
}

void TrajectoryGeneratorPTP::extractMotionPlanInfo(const planning_scene::PlanningSceneConstPtr& scene,
                                                   const planning_interface::MotionPlanRequest& req,
                                                   MotionPlanInfo& info) const
{
  info.group_name = req.group_name;

  // extract start state information
  info.start_joint_position.clear();
  for (std::size_t i = 0; i < req.start_state.joint_state.name.size(); ++i)
  {
    info.start_joint_position[req.start_state.joint_state.name[i]] = req.start_state.joint_state.position[i];
  }

  // extract goal
  info.goal_joint_position.clear();
  if (!req.goal_constraints.at(0).joint_constraints.empty())
  {
    for (const auto& joint_constraint : req.goal_constraints.at(0).joint_constraints)
    {
      info.goal_joint_position[joint_constraint.joint_name] = joint_constraint.position;
    }
  }
  // slove the ik
  else
  {
    geometry_msgs::Point p =
        req.goal_constraints.at(0).position_constraints.at(0).constraint_region.primitive_poses.at(0).position;
    p.x -= req.goal_constraints.at(0).position_constraints.at(0).target_point_offset.x;
    p.y -= req.goal_constraints.at(0).position_constraints.at(0).target_point_offset.y;
    p.z -= req.goal_constraints.at(0).position_constraints.at(0).target_point_offset.z;

    geometry_msgs::Pose pose;
    pose.position = p;
    pose.orientation = req.goal_constraints.at(0).orientation_constraints.at(0).orientation;
    Eigen::Isometry3d pose_eigen;
    normalizeQuaternion(pose.orientation);
    tf2::fromMsg(pose, pose_eigen);
    if (!computePoseIK(scene, req.group_name, req.goal_constraints.at(0).position_constraints.at(0).link_name,
                       pose_eigen, robot_model_->getModelFrame(), info.start_joint_position, info.goal_joint_position))
    {
      throw PtpNoIkSolutionForGoalPose("No IK solution for goal pose");
    }
  }
}

void TrajectoryGeneratorPTP::plan(const planning_scene::PlanningSceneConstPtr& /*scene*/,
                                  const planning_interface::MotionPlanRequest& req, const MotionPlanInfo& plan_info,
                                  const double& sampling_time, trajectory_msgs::JointTrajectory& joint_trajectory)
{
  // plan the ptp trajectory
  planPTP(plan_info.start_joint_position, plan_info.goal_joint_position, joint_trajectory, plan_info.group_name,
          req.max_velocity_scaling_factor, req.max_acceleration_scaling_factor, sampling_time);
}

}  // namespace pilz_industrial_motion_planner
<|endoftext|>


<commit_before>//- ------------------------------------------------------------------
//-    Copyright (c) Changjiang. Liu -- All Rights Reserved
//-    Licensed under the Apache License, Version 2.0 (the "License").
//-
//-    Available at https://github.com/rookiecalf/IQmath_fake
//-
//-
//-    Authorized users may use this source code in your own
//-    projects. We make no guarantees that this source code is
//-    fit for any purpose.
//-
//-    softci.com    rookiecalf@gmail.com
//- ------------------------------------------------------------------

#include "CppUTest/TestHarness.h"

extern "C"
{
	#include "IQmathLib.h"
}

TEST_GROUP(IQmath_Division)
{
    void setup()
    {

    }

    void teardown()
    {

    }

};

TEST(IQmath_Division, IQ1div)
{
    LONGS_EQUAL(_IQ1(1.5), _IQ1div(_IQ1(3.0), _IQ1(2.0))) ;
    LONGS_EQUAL(_IQ1(536870911.5), _IQ1div(_IQ1(1073741823), _IQ1(2.0))) ;
}

TEST(IQmath_Division, IQ1divNegative)
{
    LONGS_EQUAL(_IQ1(1.5), _IQ1div(_IQ1(-3.0), _IQ1(-2.0))) ;
    LONGS_EQUAL(_IQ1(-536870911.5), _IQ1div(_IQ1(-1073741823), _IQ1(2.0))) ;
}

TEST(IQmath_Division, IQ2div)
{
    LONGS_EQUAL(_IQ2(1.5), _IQ2div(_IQ2(3.0), _IQ2(2.0))) ;
    LONGS_EQUAL(_IQ2(16268815.48), _IQ2div(_IQ2(536870911), _IQ2(33))) ;
}

<commit_msg>添加IQ2div的负数测试<commit_after>//- ------------------------------------------------------------------
//-    Copyright (c) Changjiang. Liu -- All Rights Reserved
//-    Licensed under the Apache License, Version 2.0 (the "License").
//-
//-    Available at https://github.com/rookiecalf/IQmath_fake
//-
//-
//-    Authorized users may use this source code in your own
//-    projects. We make no guarantees that this source code is
//-    fit for any purpose.
//-
//-    softci.com    rookiecalf@gmail.com
//- ------------------------------------------------------------------

#include "CppUTest/TestHarness.h"

extern "C"
{
	#include "IQmathLib.h"
}

TEST_GROUP(IQmath_Division)
{
    void setup()
    {

    }

    void teardown()
    {

    }

};

TEST(IQmath_Division, IQ1div)
{
    LONGS_EQUAL(_IQ1(1.5), _IQ1div(_IQ1(3.0), _IQ1(2.0))) ;
    LONGS_EQUAL(_IQ1(536870911.5), _IQ1div(_IQ1(1073741823), _IQ1(2.0))) ;
}

TEST(IQmath_Division, IQ1divNegative)
{
    LONGS_EQUAL(_IQ1(1.5), _IQ1div(_IQ1(-3.0), _IQ1(-2.0))) ;
    LONGS_EQUAL(_IQ1(-536870911.5), _IQ1div(_IQ1(-1073741823), _IQ1(2.0))) ;
}

TEST(IQmath_Division, IQ2div)
{
    LONGS_EQUAL(_IQ2(1.5), _IQ2div(_IQ2(3.0), _IQ2(2.0))) ;
    LONGS_EQUAL(_IQ2(16268815.48), _IQ2div(_IQ2(536870911), _IQ2(33))) ;
}

TEST(IQmath_Division, IQ2divNegative)
{
    LONGS_EQUAL(_IQ2(1.5), _IQ2div(_IQ2(-3.0), _IQ2(-2.0))) ;
    LONGS_EQUAL(_IQ2(-16268815.48), _IQ2div(_IQ2(-536870911), _IQ2(33))) ;
}

<|endoftext|>


<commit_before>/*
Author: 	Anfego
Date:		04/11/14
Class: 		CSCI 6430
Professor:	Dr. Buttler
University: MTSU
Desciption:
	This program is an implementation of a MPI tupple space
	Support for:
		PP_Init()
		PP_Put()
		PP_Get()
		PP_Reserve()
		PP_Finalize()

*/
#include <vector>          // stack
#include <utility>
#include <pthread.h>
#include <iostream>
#include <stack>

#include "/nfshome/rbutler/public/courses/pp6430/mpich3i/include/mpi.h"
#include "pp.h"
#include "lindaStuff.h"

using namespace std;

/*<sumary>
	</sumary>*/
lindaStuff lindaSpace;

/*<sumary>
    int num_user_types;
    Any valid integer can be a user type.
	Wildcards will be described below.
    int user_types[PP_MAX_USER_TYPES];
    int server_flag;  // I begin to execute server code if true
    Discussion:
	The user should do MPI_Init and MPI_Finalize.
	</sumary>*/
int PP_Init(int num_user_types, int * user_types, int * am_server_flag)
{
	int server = *am_server_flag;
	int my_inter_rank;
	int my_side_rank;
	int my_world_rank;
	int world_size;
	int my_side_size;
	int inter_size;
	int other_side_size;
	int other_side_leader;

	MPI_Comm_dup(MPI_COMM_WORLD, &(lindaSpace.WORLD_COMM_DUP));
	MPI_Comm_rank(lindaSpace.WORLD_COMM_DUP,&my_world_rank);
	MPI_Comm_size(lindaSpace.WORLD_COMM_DUP,&world_size);

	MPI_Comm_split(MPI_COMM_WORLD, *am_server_flag, 0,&(lindaSpace.MY_SIDE_COMM));
	MPI_Comm_rank(lindaSpace.MY_SIDE_COMM,&my_side_rank);
	MPI_Comm_size(lindaSpace.MY_SIDE_COMM,&my_side_size);

	// store usefull information
	lindaSpace.my_world_rank = my_world_rank;
	lindaSpace.my_side_rank = my_side_rank;

	lindaSpace.world_size = world_size;
	lindaSpace.my_side_size = my_side_size;
	if (server ==0)
	{
		lindaSpace.other_side_leader = my_side_size; 		// assing as leader of servers the next
															// rank after app ranks.
	}
	else
	{
		lindaSpace.other_side_leader = 0; 					// Leader of app is Rank 0;
	}
	MPI_Intercomm_create(
		lindaSpace.MY_SIDE_COMM,
		0,
		lindaSpace.WORLD_COMM_DUP,
		lindaSpace.other_side_leader,
		666,
		&(lindaSpace.INTER_COMM));

	MPI_Comm_rank(lindaSpace.INTER_COMM,&my_inter_rank);
	MPI_Comm_size(lindaSpace.INTER_COMM,&inter_size);
	MPI_Comm_remote_size(lindaSpace.INTER_COMM,&other_side_size);
	lindaSpace.other_side_size = other_side_size;

	if(server == 0)
	{
		// printf("I am an APP %d\n", lindaSpace.am_i_server());

		printf("App: %d  %d  %d \n",my_world_rank,my_side_rank,my_inter_rank);
		return PP_SUCCESS;
	}
	// printf("I am a server %d\n", lindaSpace.am_i_server());

	printf("\tServer: %d  %d  %d other_side_size %d\n",my_world_rank,my_side_rank,my_inter_rank,other_side_size);

	vector<int> uTypes;
	// create stack for user types
	int done = 0;
	int mpi_flag = 0;
	MPI_Status status;
	for (int i = 0; i < num_user_types; ++i)
	{
	}

	while(!done)
	{
		MPI_Iprobe(lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &mpi_flag, &status);
		if (mpi_flag == 1)		// if true there is a message, PP_Finalize
		{
			printf("Server DONE :  %d\n",done);
			MPI_Recv(&done, 1, MPI_INT, lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);
		}
	}
	printf("Server Exit\n");

	return PP_SUCCESS;
}
/*<sumary>
	</sumary>*/

int PP_Finalize()
{
	MPI_Status status;
	//Send "To finish" signal
	int done = 1;
	int my_side_rank;
	int my_inter_rank;

	// wait until all app's get until this point
	MPI_Barrier(lindaSpace.MY_SIDE_COMM);
	if(lindaSpace.am_i_server() == false)
	{
		if(lindaSpace.my_side_rank == 0) 			// if Im rank 0 in app side do Bcast
		{
			// Sends to every server a "to finish" signal
			printf("END servers!\n");
			for(int i = 0; i < lindaSpace.other_side_size; i++)
			{
				MPI_Send(&done,1, MPI_INT, i, 666, lindaSpace.INTER_COMM);
			}
		}

	}
	printf("Im out: %d\n",my_inter_rank);

	MPI_Barrier(lindaSpace.WORLD_COMM_DUP);			//Wait for all processes hit this point

	// free LindaSpace communicators
	MPI_Comm_free(&(lindaSpace.INTER_COMM));
	MPI_Comm_free(&(lindaSpace.MY_SIDE_COMM));
	MPI_Comm_free(&(lindaSpace.WORLD_COMM_DUP));

	return PP_SUCCESS;
}
/*<sumary>
	</sumary>*/

int PP_Put()
{
	return PP_SUCCESS;
}
/*<sumary>
	</sumary>*/

int PP_Reserve()
{
	return PP_SUCCESS;
}
/*<sumary>
	</sumary>*/

int PP_Get()
{
	return PP_SUCCESS;
}
/*<sumary>
	</sumary>*/

int PP_Set_problem_done()
{
	return PP_SUCCESS;
}
/*<sumary>
	</sumary>*/

int PP_Abort()
{
	return PP_SUCCESS;
}

<commit_msg>PP_Finalize: merged to master<commit_after>/*
Author: 	Anfego
Date:		04/11/14
Class: 		CSCI 6430
Professor:	Dr. Buttler
University: MTSU
Desciption:
	This program is an implementation of a MPI tupple space
	Support for:
		PP_Init()
		PP_Put()
		PP_Get()
		PP_Reserve()
		PP_Finalize()

*/
#include <vector>          // stack
#include <utility>
#include <pthread.h>
#include <iostream>
#include <stack>

#include "/nfshome/rbutler/public/courses/pp6430/mpich3i/include/mpi.h"
#include "pp.h"
#include "lindaStuff.h"

using namespace std;

/*<sumary>
	</sumary>*/
lindaStuff lindaSpace;

/*<sumary>
    int num_user_types;
    Any valid integer can be a user type.
	Wildcards will be described below.
    int user_types[PP_MAX_USER_TYPES];
    int server_flag;  // I begin to execute server code if true
    Discussion:
	The user should do MPI_Init and MPI_Finalize.
	</sumary>*/
int PP_Init(int num_user_types, int * user_types, int * am_server_flag)
{
	int server = *am_server_flag;
	int my_inter_rank;
	int my_side_rank;
	int my_world_rank;
	int world_size;
	int my_side_size;
	int inter_size;
	int other_side_size;
	int other_side_leader;

	MPI_Comm_dup(MPI_COMM_WORLD, &(lindaSpace.WORLD_COMM_DUP));
	MPI_Comm_rank(lindaSpace.WORLD_COMM_DUP,&my_world_rank);
	MPI_Comm_size(lindaSpace.WORLD_COMM_DUP,&world_size);

	MPI_Comm_split(MPI_COMM_WORLD, *am_server_flag, 0,&(lindaSpace.MY_SIDE_COMM));
	MPI_Comm_rank(lindaSpace.MY_SIDE_COMM,&my_side_rank);
	MPI_Comm_size(lindaSpace.MY_SIDE_COMM,&my_side_size);

	// store usefull information
	lindaSpace.my_world_rank = my_world_rank;
	lindaSpace.my_side_rank = my_side_rank;

	lindaSpace.world_size = world_size;
	lindaSpace.my_side_size = my_side_size;
	if (server ==0)
	{
		lindaSpace.other_side_leader = my_side_size; 		// assing as leader of servers the next
															// rank after app ranks.
	}
	else
	{
		lindaSpace.other_side_leader = 0; 					// Leader of app is Rank 0;
	}
	MPI_Intercomm_create(
		lindaSpace.MY_SIDE_COMM,
		0,
		lindaSpace.WORLD_COMM_DUP,
		lindaSpace.other_side_leader,
		666,
		&(lindaSpace.INTER_COMM));

	MPI_Comm_rank(lindaSpace.INTER_COMM,&my_inter_rank);
	MPI_Comm_size(lindaSpace.INTER_COMM,&inter_size);
	MPI_Comm_remote_size(lindaSpace.INTER_COMM,&other_side_size);
	lindaSpace.other_side_size = other_side_size;

	if(server == 0)
	{
		return PP_SUCCESS;
	}

	vector<int> uTypes;
	// create stack for user types
	int done = 0;
	int mpi_flag = 0;
	MPI_Status status;

	while(!done)
	{
		// checks if there is a "to finish"
		MPI_Iprobe(lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &mpi_flag, &status);
		if (mpi_flag == 1)		// if true there is a message, PP_Finalize
		{
			MPI_Recv(&done, 1, MPI_INT, lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);
		}

	}
	printf("tuppleSpace Exit\n");

	return PP_SUCCESS;
}
/*<sumary>
	</sumary>*/

int PP_Finalize()
{
	MPI_Status status;
	//Send "To finish" signal
	int done = 1;
	int my_side_rank;
	int my_inter_rank;

	// wait until all app's get until this point
	MPI_Barrier(lindaSpace.MY_SIDE_COMM);
	if(lindaSpace.am_i_server() == false)
	{
		if(lindaSpace.my_side_rank == 0) 			// if Im rank 0 in app side do Bcast
		{
			// Sends to every server a "to finish" signal
			for(int i = 0; i < lindaSpace.other_side_size; i++)
			{
				MPI_Send(&done,1, MPI_INT, i, 666, lindaSpace.INTER_COMM);
			}
		}

	}
	// printf("Im out: %d\n",my_inter_rank);

	MPI_Barrier(lindaSpace.WORLD_COMM_DUP);			//Wait for all processes hit this point

	// free LindaSpace communicators
	MPI_Comm_free(&(lindaSpace.INTER_COMM));
	MPI_Comm_free(&(lindaSpace.MY_SIDE_COMM));
	MPI_Comm_free(&(lindaSpace.WORLD_COMM_DUP));
	if (lindaSpace.my_world_rank == 0)
	{
		printf("PP_Finalize = PP_SUCCESS\n");
	}
	return PP_SUCCESS;
}
/*<sumary>
	</sumary>*/

int PP_Put()
{
	return PP_SUCCESS;
}
/*<sumary>
	</sumary>*/

int PP_Reserve()
{
	return PP_SUCCESS;
}
/*<sumary>
	</sumary>*/

int PP_Get()
{
	return PP_SUCCESS;
}
/*<sumary>
	</sumary>*/

int PP_Set_problem_done()
{
	return PP_SUCCESS;
}
/*<sumary>
	</sumary>*/

int PP_Abort()
{
	return PP_SUCCESS;
}

<|endoftext|>


<commit_before>/*
Author: 	Anfego
Date:		04/11/14
Class: 		CSCI 6430
Professor:	Dr. Buttler
University: MTSU
Desciption:
	This program is an implementation of a MPI tupple space
	Support for:
		PP_Init()
		PP_Put()
		PP_Get()
		PP_Reserve()
		PP_Finalize()

*/
#include <vector>          // stack
#include <utility>
#include <pthread.h>
#include <iostream>
#include <stack>
#include <random>

#include "/nfshome/rbutler/public/courses/pp6430/mpich3i/include/mpi.h"
#include "pp.h"
#include "lindaStuff.h"

using namespace std;

	struct pass_struct
	{
		int size;
		int num_types;
		int local_index;
	}__attribute__ ((packed));

/*<sumary>
	</sumary>*/
lindaStuff lindaSpace;

/*<sumary>
    int num_user_types;
    Any valid integer can be a user type.
	Wildcards will be described below.
    int user_types[PP_MAX_USER_TYPES];
    int server_flag;  // I begin to execute server code if true
    Discussion:
	The user should do MPI_Init and MPI_Finalize.
	</sumary>*/
int PP_Init(int num_user_types, int * user_types, int * am_server_flag)
{
	srand(time(NULL));
	int server = *am_server_flag;
	int my_inter_rank;
	int my_side_rank;
	int my_world_rank;
	int world_size;
	int my_side_size;
	int inter_size;
	int other_side_size;
	int other_side_leader;

	MPI_Comm_dup(MPI_COMM_WORLD, &(lindaSpace.WORLD_COMM_DUP));
	MPI_Comm_rank(lindaSpace.WORLD_COMM_DUP,&my_world_rank);
	MPI_Comm_size(lindaSpace.WORLD_COMM_DUP,&world_size);

	MPI_Comm_split(MPI_COMM_WORLD, *am_server_flag, 0,&(lindaSpace.MY_SIDE_COMM));
	MPI_Comm_rank(lindaSpace.MY_SIDE_COMM,&my_side_rank);
	MPI_Comm_size(lindaSpace.MY_SIDE_COMM,&my_side_size);

	char * work_unit_buf = (char *) malloc(work_unit_size);

	// store usefull information
	lindaSpace.my_world_rank = my_world_rank;
	lindaSpace.my_side_rank = my_side_rank;

	lindaSpace.world_size = world_size;
	lindaSpace.my_side_size = my_side_size;
	if (server ==0)
	{
		lindaSpace.other_side_leader = my_side_size; 		// assing as leader of servers the next
															// rank after app ranks.
	}
	else
	{
		lindaSpace.other_side_leader = 0; 					// Leader of app is Rank 0;
	}
	MPI_Intercomm_create(
		lindaSpace.MY_SIDE_COMM,
		0,
		lindaSpace.WORLD_COMM_DUP,
		lindaSpace.other_side_leader,
		666,
		&(lindaSpace.INTER_COMM));

	MPI_Comm_rank(lindaSpace.INTER_COMM,&my_inter_rank);
	MPI_Comm_size(lindaSpace.INTER_COMM,&inter_size);
	MPI_Comm_remote_size(lindaSpace.INTER_COMM,&other_side_size);
	lindaSpace.other_side_size = other_side_size;

	if(server == 0)
	{
		return PP_SUCCESS;
	}

	vector<int> uTypes;
	// create stack for user types
	int done = 0;
	int mpi_flag = 0;
	pass_struct put_struct;
	MPI_Status status;
	int temp_buf[2];
	int reserve_buf[num_user_types+1];//+1because first is number of elements is array
	int handle[4];
	int index;
	while(!done)
	{
		// checks if there is a "to finish"
		MPI_Iprobe(lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &mpi_flag, &status);
		if (mpi_flag == 1)		// if true there is a message, PP_Finalize
		{
			MPI_Recv(&done, 1, MPI_INT, lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);
		}
		else if( mpi_flag == 2 )//received PUT
		{
			memset(temp_buf, '\0', sizeof(temp_buf) );

			MPI_Recv(&temp_buf, 1, sizeof(temp_buf), lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);
			// if(type_rec == good rec) - receive
			// resp is index in vector, never can be less than zero
			/*int allocate(int &size, int &type)*/
			resp = lindaSpace.allocate(temp_buf[0]/*size*/, temp_buf[1]/*type*/);
			MPI_Send(&resp,1, MPI_INT, i, 666, lindaSpace.INTER_COMM);
			//get the data
			if (resp != PP_FAIL)
			{
				MPI_Recv(work_unit_buf, 1, work_unit_size, lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);
				//put in allocated space
				/*void 	store(void *work_unit_buf, int &index)*/
				lindaSpace.store(work_unit_buf, resp);
				//send success(index in array) or fail(-1)
				MPI_Send(&resp,1, MPI_INT, i, 666, lindaSpace.INTER_COMM);
			}
		}
		else if( mpi_flag == 3)//received reserve
		{
			MPI_Recv(&reserve_buf, 1, sizeof(reserve_buf), lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);
			/*void reserver(int reserve_buf[], int handle[])*/
			lindaSpace.reserver(reserve_buf, handle);
			// if (handle[1] < 0) - NOT FOUD
			MPI_Send(&handle,1, sizeof(handle), i, 666, lindaSpace.INTER_COMM);

		}
		else if( mpi_flag == 4)//received get
		{
			MPI_Recv(&index, 1, MPI_INT, lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);
			/*void taker(int index, void * work_unit_buf)*/
			lindaSpace.taker(index, work_unit_buf);
			MPI_Send(&work_unit_buf,1, sizeof(work_unit_buf), i, 666, lindaSpace.INTER_COMM);
		}
	}
	printf("tuppleSpace Exit\n");

	return PP_SUCCESS;
}
/*<sumary>
	</sumary>*/

int PP_Finalize()
{
	MPI_Status status;
	//Send "To finish" signal
	int done = 1;
	int my_side_rank;
	int my_inter_rank;

	// wait until all app's get until this point
	MPI_Barrier(lindaSpace.MY_SIDE_COMM);
	if(lindaSpace.am_i_server() == false)
	{
		if(lindaSpace.my_side_rank == 0) 			// if Im rank 0 in app side do Bcast
		{
			// Sends to every server a "to finish" signal
			for(int i = 0; i < lindaSpace.other_side_size; i++)
			{
				MPI_Send(&done,1, MPI_INT, i, 666, lindaSpace.INTER_COMM);
			}
		}

	}
	// printf("Im out: %d\n",my_inter_rank);

	MPI_Barrier(lindaSpace.WORLD_COMM_DUP);			//Wait for all processes hit this point

	// free LindaSpace communicators
	MPI_Comm_free(&(lindaSpace.INTER_COMM));
	MPI_Comm_free(&(lindaSpace.MY_SIDE_COMM));
	MPI_Comm_free(&(lindaSpace.WORLD_COMM_DUP));
	if (lindaSpace.my_world_rank == 0)
	{
		printf("PP_Finalize = PP_SUCCESS\n");
	}
	return PP_SUCCESS;
}
/*<sumary>
	</sumary>*/

int PP_Put(int type, int size, void * buffer )
{
	int picked_server = random()%other_side_size;
	int resp = -1;

	int temp_buf[2];
	temp_buf[0] = size;
	temp_buf[1] = type;

	MPI_Send(&temp_buf,1, sizeof(temp_buf), picked_server, 666, lindaSpace.INTER_COMM);
	MPI_Recv(&resp, 1, MPI_INT, lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);
	//because of using resp we do not care about status.
	//it may mean memory or network problem, we just send to the next random server
	if (resp != -1)
	{//then we feel very good and just send it
		MPI_Send(buffer,1, size, picked_server, 666, lindaSpace.INTER_COMM);
		resp = -1;
		MPI_Recv(&resp, 1, MPI_INT, lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);
		if (resp == 0)
			return PP_SUCCESS;//else PP_FAIL
	}
	return PP_FAIL;
}
/*<sumary>
	</sumary>*/
int PP_Reserve(int& num_types, int types[], int &size, int& type, int handle[] )
{
	int types_pass[num_types+1];
	memset(handle, '\0', 4*sizeof(int));
	types_pass[0] = num_types;
	if (num_types > 1)
	{
		for (int i = 0; i < num_types; ++i)
		{
			types_pass[i+1] = types[i];
		}
	}

	MPI_Send(&types_pas,1, sizeof(types_pas), picked_server, 666, lindaSpace.INTER_COMM);

	MPI_Recv(&handle, 1, sizeof(handle), lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);
	if(handle[1] != -1)
	{
		// handle[0]/*.rank*/			= picked_server;
  //       handle[1]/*.ID*/			= resp.ID;
  //       handle[2]/*.size_of_work*/	= resp.size;
  //       handle[3]/*.type_of_work*/	= resp.type;
		return PP_SUCCESS;
	}
	else
		return NOT_FOUND;
}
/*<sumary>
	</sumary>*/

int PP_Get(void*work_unit_buf, int handler[])
{

	MPI_Send(handle[1]/*ID*/,1, MPI_INT, handle[0], 666, lindaSpace.INTER_COMM);
	MPI_Recv(work_unit_buf,1, handle[2], lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);

	if (status == MPI_SUCCESS)
	{
		return PP_SUCCESS;
	}
	return FAIL;
}
/*<sumary>
	</sumary>*/

int PP_Set_problem_done()
{
	return PP_SUCCESS;
}
/*<sumary>
	</sumary>*/

int PP_Abort()
{
	return PP_SUCCESS;
}

<commit_msg>fixed random in reserve<commit_after>/*
Author: 	Anfego
Date:		04/11/14
Class: 		CSCI 6430
Professor:	Dr. Buttler
University: MTSU
Desciption:
	This program is an implementation of a MPI tupple space
	Support for:
		PP_Init()
		PP_Put()
		PP_Get()
		PP_Reserve()
		PP_Finalize()

*/
#include <vector>          // stack
#include <utility>
#include <pthread.h>
#include <iostream>
#include <stack>
#include <random>

#include "/nfshome/rbutler/public/courses/pp6430/mpich3i/include/mpi.h"
#include "pp.h"
#include "lindaStuff.h"

using namespace std;

	struct pass_struct
	{
		int size;
		int num_types;
		int local_index;
	}__attribute__ ((packed));

/*<sumary>
	</sumary>*/
lindaStuff lindaSpace;

/*<sumary>
    int num_user_types;
    Any valid integer can be a user type.
	Wildcards will be described below.
    int user_types[PP_MAX_USER_TYPES];
    int server_flag;  // I begin to execute server code if true
    Discussion:
	The user should do MPI_Init and MPI_Finalize.
	</sumary>*/
int PP_Init(int num_user_types, int * user_types, int * am_server_flag)
{
	srand(time(NULL));
	int server = *am_server_flag;
	int my_inter_rank;
	int my_side_rank;
	int my_world_rank;
	int world_size;
	int my_side_size;
	int inter_size;
	int other_side_size;
	int other_side_leader;

	MPI_Comm_dup(MPI_COMM_WORLD, &(lindaSpace.WORLD_COMM_DUP));
	MPI_Comm_rank(lindaSpace.WORLD_COMM_DUP,&my_world_rank);
	MPI_Comm_size(lindaSpace.WORLD_COMM_DUP,&world_size);

	MPI_Comm_split(MPI_COMM_WORLD, *am_server_flag, 0,&(lindaSpace.MY_SIDE_COMM));
	MPI_Comm_rank(lindaSpace.MY_SIDE_COMM,&my_side_rank);
	MPI_Comm_size(lindaSpace.MY_SIDE_COMM,&my_side_size);

	char * work_unit_buf = (char *) malloc(work_unit_size);

	// store usefull information
	lindaSpace.my_world_rank = my_world_rank;
	lindaSpace.my_side_rank = my_side_rank;

	lindaSpace.world_size = world_size;
	lindaSpace.my_side_size = my_side_size;
	if (server ==0)
	{
		lindaSpace.other_side_leader = my_side_size; 		// assing as leader of servers the next
															// rank after app ranks.
	}
	else
	{
		lindaSpace.other_side_leader = 0; 					// Leader of app is Rank 0;
	}
	MPI_Intercomm_create(
		lindaSpace.MY_SIDE_COMM,
		0,
		lindaSpace.WORLD_COMM_DUP,
		lindaSpace.other_side_leader,
		666,
		&(lindaSpace.INTER_COMM));

	MPI_Comm_rank(lindaSpace.INTER_COMM,&my_inter_rank);
	MPI_Comm_size(lindaSpace.INTER_COMM,&inter_size);
	MPI_Comm_remote_size(lindaSpace.INTER_COMM,&other_side_size);
	lindaSpace.other_side_size = other_side_size;

	if(server == 0)
	{
		return PP_SUCCESS;
	}

	vector<int> uTypes;
	// create stack for user types
	int done = 0;
	int mpi_flag = 0;
	pass_struct put_struct;
	MPI_Status status;
	int temp_buf[2];
	int reserve_buf[num_user_types+1];//+1because first is number of elements is array
	int handle[4];
	int index;
	while(!done)
	{
		// checks if there is a "to finish"
		MPI_Iprobe(lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &mpi_flag, &status);
		if (mpi_flag == 1)		// if true there is a message, PP_Finalize
		{
			MPI_Recv(&done, 1, MPI_INT, lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);
		}
		else if( mpi_flag == 2 )//received PUT
		{
			memset(temp_buf, '\0', sizeof(temp_buf) );

			MPI_Recv(&temp_buf, 1, sizeof(temp_buf), lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);
			// if(type_rec == good rec) - receive
			// resp is index in vector, never can be less than zero
			/*int allocate(int &size, int &type)*/
			resp = lindaSpace.allocate(temp_buf[0]/*size*/, temp_buf[1]/*type*/);
			MPI_Send(&resp,1, MPI_INT, i, 666, lindaSpace.INTER_COMM);
			//get the data
			if (resp != PP_FAIL)
			{
				MPI_Recv(work_unit_buf, 1, work_unit_size, lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);
				//put in allocated space
				/*void 	store(void *work_unit_buf, int &index)*/
				lindaSpace.store(work_unit_buf, resp);
				//send success(index in array) or fail(-1)
				MPI_Send(&resp,1, MPI_INT, i, 666, lindaSpace.INTER_COMM);
			}
		}
		else if( mpi_flag == 3)//received reserve
		{
			MPI_Recv(&reserve_buf, 1, sizeof(reserve_buf), lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);
			/*void reserver(int reserve_buf[], int handle[])*/
			lindaSpace.reserver(reserve_buf, handle);
			// if (handle[1] < 0) - NOT FOUD
			MPI_Send(&handle,1, sizeof(handle), i, 666, lindaSpace.INTER_COMM);

		}
		else if( mpi_flag == 4)//received get
		{
			MPI_Recv(&index, 1, MPI_INT, lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);
			/*void taker(int index, void * work_unit_buf)*/
			lindaSpace.taker(index, work_unit_buf);
			MPI_Send(&work_unit_buf,1, sizeof(work_unit_buf), i, 666, lindaSpace.INTER_COMM);
		}
	}
	printf("tuppleSpace Exit\n");

	return PP_SUCCESS;
}
/*<sumary>
	</sumary>*/

int PP_Finalize()
{
	MPI_Status status;
	//Send "To finish" signal
	int done = 1;
	int my_side_rank;
	int my_inter_rank;

	// wait until all app's get until this point
	MPI_Barrier(lindaSpace.MY_SIDE_COMM);
	if(lindaSpace.am_i_server() == false)
	{
		if(lindaSpace.my_side_rank == 0) 			// if Im rank 0 in app side do Bcast
		{
			// Sends to every server a "to finish" signal
			for(int i = 0; i < lindaSpace.other_side_size; i++)
			{
				MPI_Send(&done,1, MPI_INT, i, 666, lindaSpace.INTER_COMM);
			}
		}

	}
	// printf("Im out: %d\n",my_inter_rank);

	MPI_Barrier(lindaSpace.WORLD_COMM_DUP);			//Wait for all processes hit this point

	// free LindaSpace communicators
	MPI_Comm_free(&(lindaSpace.INTER_COMM));
	MPI_Comm_free(&(lindaSpace.MY_SIDE_COMM));
	MPI_Comm_free(&(lindaSpace.WORLD_COMM_DUP));
	if (lindaSpace.my_world_rank == 0)
	{
		printf("PP_Finalize = PP_SUCCESS\n");
	}
	return PP_SUCCESS;
}
/*<sumary>
	</sumary>*/

int PP_Put(int type, int size, void * buffer )
{
	int picked_server = random()%other_side_size;
	int resp = -1;

	int temp_buf[2];
	temp_buf[0] = size;
	temp_buf[1] = type;

	MPI_Send(&temp_buf,1, sizeof(temp_buf), picked_server, 666, lindaSpace.INTER_COMM);
	MPI_Recv(&resp, 1, MPI_INT, lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);
	//because of using resp we do not care about status.
	//it may mean memory or network problem, we just send to the next random server
	if (resp != -1)
	{//then we feel very good and just send it
		MPI_Send(buffer,1, size, picked_server, 666, lindaSpace.INTER_COMM);
		resp = -1;
		MPI_Recv(&resp, 1, MPI_INT, lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);
		if (resp == 0)
			return PP_SUCCESS;//else PP_FAIL
	}
	return PP_FAIL;
}
/*<sumary>
	</sumary>*/
int PP_Reserve(int& num_types, int types[], int &size, int& type, int handle[] )
{
	int types_pass[num_types+1];
	memset(handle, '\0', 4*sizeof(int));
	picked_server = random()%other_side_size;
	types_pass[0] = num_types;
	if (num_types > 1)
	{
		for (int i = 0; i < num_types; ++i)
		{
			types_pass[i+1] = types[i];
		}
	}

	MPI_Send(&types_pas,1, sizeof(types_pas), picked_server, 666, lindaSpace.INTER_COMM);

	MPI_Recv(&handle, 1, sizeof(handle), lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);
	if(handle[1] != -1)
	{
		// handle[0]/*.rank*/			= picked_server;
  //       handle[1]/*.ID*/			= resp.ID;
  //       handle[2]/*.size_of_work*/	= resp.size;
  //       handle[3]/*.type_of_work*/	= resp.type;
		return PP_SUCCESS;
	}
	else
		return NOT_FOUND;
}
/*<sumary>
	</sumary>*/

int PP_Get(void*work_unit_buf, int handler[])
{

	MPI_Send(handle[1]/*ID*/,1, MPI_INT, handle[0], 666, lindaSpace.INTER_COMM);
	MPI_Recv(work_unit_buf,1, handle[2], lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);

	if (status == MPI_SUCCESS)
	{
		return PP_SUCCESS;
	}
	return FAIL;
}
/*<sumary>
	</sumary>*/

int PP_Set_problem_done()
{
	return PP_SUCCESS;
}
/*<sumary>
	</sumary>*/

int PP_Abort()
{
	return PP_SUCCESS;
}

<|endoftext|>


<commit_before>//----------------------------  extract_boundary_mesh_03.cc  ---------------------------
//    $Id: bem.cc 22693 2010-11-11 20:11:47Z kanschat $
//    Version: $Name$
//
//    Copyright (C) 2010 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//----------------------------  extract_boundary_mesh_03.cc  ---------------------------

#include "../tests.h"

#include <grid/tria.h>
#include <grid/grid_generator.h>
#include <grid/tria_boundary_lib.h>
#include <grid/grid_out.h>
#include <grid/grid_tools.h>
#include <fe/fe_system.h>
#include <fe/fe_q.h>

#include <dofs/dof_handler.h>
#include <dofs/dof_accessor.h>

using namespace std;

void test ()
{
  const unsigned int dim=2;

  Triangulation<dim-1,dim> boundary_mesh;
  map<Triangulation<dim-1,dim>::cell_iterator,Triangulation<dim,dim>::face_iterator >
    surface_to_volume_mapping;
  Triangulation<dim> volume_mesh;
  GridGenerator::hyper_cube(volume_mesh);

  surface_to_volume_mapping
    = GridTools::extract_boundary_mesh (volume_mesh, boundary_mesh);

  FE_Q <dim-1,dim>  boundary_fe (1);
  DoFHandler<dim-1,dim> boundary_dh(boundary_mesh);
  boundary_dh.distribute_dofs (boundary_fe);

  deallog << "n_dofs=" << boundary_dh.n_dofs() << std::endl;

  for (DoFHandler<dim-1,dim>::active_cell_iterator
	 cell = boundary_dh.begin_active(),
	 endc = boundary_dh.end(); cell!=endc; ++cell)
    {
      deallog << "Cell: " << cell << std::endl;
      for (unsigned int v=0; v<GeometryInfo<dim-1>::vertices_per_cell; ++v)
	{
	  unsigned int index = cell->vertex_dof_index(v,0);
	  deallog << "vertex: " << v
		  << ", global: " << cell->vertex_index(v)
		  << " index: " << index << std::endl;
	}

      deallog << std::endl;
    }
}

int main ()
{

  ofstream logfile("extract_boundary_mesh_05/output");
  deallog.attach(logfile);
  deallog.depth_console(0);

  test ();
 }
<commit_msg>Fix number.<commit_after>//----------------------------  extract_boundary_mesh_05.cc  ---------------------------
//    $Id: bem.cc 22693 2010-11-11 20:11:47Z kanschat $
//    Version: $Name$
//
//    Copyright (C) 2010, 2011 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//----------------------------  extract_boundary_mesh_05.cc  ---------------------------

#include "../tests.h"

#include <grid/tria.h>
#include <grid/grid_generator.h>
#include <grid/tria_boundary_lib.h>
#include <grid/grid_out.h>
#include <grid/grid_tools.h>
#include <fe/fe_system.h>
#include <fe/fe_q.h>

#include <dofs/dof_handler.h>
#include <dofs/dof_accessor.h>

using namespace std;

void test ()
{
  const unsigned int dim=2;

  Triangulation<dim-1,dim> boundary_mesh;
  map<Triangulation<dim-1,dim>::cell_iterator,Triangulation<dim,dim>::face_iterator >
    surface_to_volume_mapping;
  Triangulation<dim> volume_mesh;
  GridGenerator::hyper_cube(volume_mesh);

  surface_to_volume_mapping
    = GridTools::extract_boundary_mesh (volume_mesh, boundary_mesh);

  FE_Q <dim-1,dim>  boundary_fe (1);
  DoFHandler<dim-1,dim> boundary_dh(boundary_mesh);
  boundary_dh.distribute_dofs (boundary_fe);

  deallog << "n_dofs=" << boundary_dh.n_dofs() << std::endl;

  for (DoFHandler<dim-1,dim>::active_cell_iterator
	 cell = boundary_dh.begin_active(),
	 endc = boundary_dh.end(); cell!=endc; ++cell)
    {
      deallog << "Cell: " << cell << std::endl;
      for (unsigned int v=0; v<GeometryInfo<dim-1>::vertices_per_cell; ++v)
	{
	  unsigned int index = cell->vertex_dof_index(v,0);
	  deallog << "vertex: " << v
		  << ", global: " << cell->vertex_index(v)
		  << " index: " << index << std::endl;
	}

      deallog << std::endl;
    }
}

int main ()
{

  ofstream logfile("extract_boundary_mesh_05/output");
  deallog.attach(logfile);
  deallog.depth_console(0);

  test ();
 }
<|endoftext|>


<commit_before>/*
Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
// Simple test for memset.
// Also serves as a template for other tests.

/* HIT_START
 * BUILD: %t %s ../../test_common.cpp
 * //Small copy
 * RUN: %t -N 10    --memsetval 0x42
 * HIT_END
 */

#include "hip/hip_runtime.h"
#include "test_common.h"

bool testhipMemset3D(int memsetval,int p_gpuDevice)
{
    size_t numH = 256;
    size_t numW = 256;
    size_t depth = 1;
    size_t pitch_A;
    size_t width = numW * sizeof(char);
    size_t sizeElements = width * numH * depth;
    size_t elements = numW* numH* depth;

	printf ("testhipMemset3D memsetval=%2x device=%d\n", memsetval, p_gpuDevice);
    char *A_d;
    char *A_h;
    bool testResult = true;
    hipExtent extent = make_hipExtent(width, numH, depth);
    hipPitchedPtr devPitchedPtr;

    HIPCHECK(hipMalloc3D(&devPitchedPtr, extent));
	A_h = (char*)malloc(sizeElements);
	HIPASSERT(A_h != NULL);
	for (size_t i=0; i<elements; i++) {
        A_h[i] = 1;
    }
    hipStream_t stream;
    //HIPCHECK(hipStreamCreate(&stream));
	HIPCHECK ( hipMemset3D( devPitchedPtr, memsetval, extent) );
	//HIPCHECK ( hipMemcpy3D(A_h, width, A_d, pitch_A, numW, numH, hipMemcpyDeviceToHost));
	hipMemcpy3DParms myparms = {0};
	myparms.srcPos = make_hipPos(0,0,0);
	myparms.dstPos = make_hipPos(0,0,0);
	myparms.dstPtr = make_hipPitchedPtr(A_h, width , numW, numH);
	myparms.srcPtr = devPitchedPtr;
    //myparms.dstArray = cuArray;
	myparms.extent = extent;
#ifdef __HIP_PLATFORM_NVCC__
	myparms.kind = hipMemcpyKindToCudaMemcpyKind(hipMemcpyDeviceToHost);
#else
    myparms.kind = hipMemcpyDeviceToHost;
#endif
    hipMemcpy3D(&myparms);

    for (int i=0; i<elements; i++) {
        if (A_h[i] != memsetval) {
			testResult = false;
            printf("mismatch at index:%d computed:%02x, memsetval:%02x\n", i, (int)A_h[i], (int)memsetval);
            break;
        }
    }
    hipFree(A_d);
    free(A_h);
    return testResult;
}

int main(int argc, char *argv[])
{
    HipTest::parseStandardArguments(argc, argv, true);
    bool testResult = false;
    HIPCHECK(hipSetDevice(p_gpuDevice));
    testResult = testhipMemset3D(memsetval, p_gpuDevice);

    passed();

}
<commit_msg>Cleaned up hipMemset3D test<commit_after>/*
Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
// Simple test for memset.
// Also serves as a template for other tests.

/* HIT_START
 * BUILD: %t %s ../../test_common.cpp
 * //Small copy
 * RUN: %t -N 10    --memsetval 0x42
 * HIT_END
 */

#include "hip/hip_runtime.h"
#include "test_common.h"

bool testhipMemset3D(int memsetval,int p_gpuDevice)
{
    size_t numH = 256;
    size_t numW = 256;
    size_t depth = 10;
    size_t width = numW * sizeof(char);
    size_t sizeElements = width * numH * depth;
    size_t elements = numW* numH* depth;

	printf ("testhipMemset3D memsetval=%2x device=%d\n", memsetval, p_gpuDevice);
    char *A_h;
    bool testResult = true;
    hipExtent extent = make_hipExtent(width, numH, depth);
    hipPitchedPtr devPitchedPtr;

    HIPCHECK(hipMalloc3D(&devPitchedPtr, extent));
	A_h = (char*)malloc(sizeElements);
	HIPASSERT(A_h != NULL);
	for (size_t i=0; i<elements; i++) {
        A_h[i] = 1;
    }
	HIPCHECK ( hipMemset3D( devPitchedPtr, memsetval, extent) );
	hipMemcpy3DParms myparms = {0};
	myparms.srcPos = make_hipPos(0,0,0);
	myparms.dstPos = make_hipPos(0,0,0);
	myparms.dstPtr = make_hipPitchedPtr(A_h, width , numW, numH);
	myparms.srcPtr = devPitchedPtr;
	myparms.extent = extent;
#ifdef __HIP_PLATFORM_NVCC__
	myparms.kind = hipMemcpyKindToCudaMemcpyKind(hipMemcpyDeviceToHost);
#else
    myparms.kind = hipMemcpyDeviceToHost;
#endif
    HIPCHECK(hipMemcpy3D(&myparms));

    for (int i=0; i<elements; i++) {
        if (A_h[i] != memsetval) {
			testResult = false;
            printf("mismatch at index:%d computed:%02x, memsetval:%02x\n", i, (int)A_h[i], (int)memsetval);
            break;
        }
    }
    HIPCHECK(hipFree(devPitchedPtr.ptr));
    free(A_h);
    return testResult;
}

int main(int argc, char *argv[])
{
    HipTest::parseStandardArguments(argc, argv, true);
    bool testResult = false;
    HIPCHECK(hipSetDevice(p_gpuDevice));
    testResult = testhipMemset3D(memsetval, p_gpuDevice);
    if (testResult) {
        passed();
    } else {
        exit(EXIT_FAILURE);
    }
}
<|endoftext|>