Exemplo n.º 1
0
/* open the specified url in the configured browser */
static int command_open_url(char *text, int len)
{
	text = getparams(text);
	if (*text)
		open_web_link(text);
	return 1;
}
Exemplo n.º 2
0
	//Constructor
	TritechMicron(ros::NodeHandle & nh) {
	

	 getparams(nh); 
	

	if ( !simulate_ )
	{
		scan_line_pub_ = nh.advertise<_ScanLineMsgType>( "scan_line", 1 );

		driver_ = new TritechMicronDriver( num_bins_, range_, velocity_of_sound_,angle_step_size_, leftLimit_, rightLimit_,use_debug_mode );
		reconfigserver = nh.advertiseService("Sonar_Reconfiguration", &TritechMicron::reconfig, this);
		

		driver_->registerScanLineCallback( std::bind( &TritechMicron::publish,this,std::placeholders::_1,  std::placeholders::_2,std::placeholders::_3 ) );

    	uint8_t angle_step_size_byte = std::max(1, std::min(255, angle_step_size_));

		if ( !driver_->connect( port_.c_str()) )
		{
			ROS_ERROR( "Could not connect to device; simulating instead." );
			simulate_ = true;
		}

	}
	} 
Exemplo n.º 3
0
int command_accept_buddy(char *text, int len)
{
	/* This command is here to make sure the requests queue is up to date */
	text = getparams(text);
	/* Make sure a name is given */
	if(*text)
		accept_buddy_console_command(text);
	return 0; // also pass to server
}
Exemplo n.º 4
0
/* set the command queues wait time between commands */
static int command_set_user_menu_wait_time_ms(char *text, int len)
{
	text = getparams(text);
	if (*text)
		set_command_queue_wait_time_ms(atol(text));
	else
		set_command_queue_wait_time_ms(0);
	return 1;
}
Exemplo n.º 5
0
Parse_stat MCComref::parse(MCScriptPoint &sp)
{
	initpoint(sp);
	if (getparams(sp, &params) != PS_NORMAL)
	{
		MCperror->add(PE_STATEMENT_BADPARAMS, sp);
		return PS_ERROR;
	}
	return PS_NORMAL;
}
Exemplo n.º 6
0
/* pretend the specified key has been pressed - allows user menu to trigger keypress events */
int command_keypress(char *text, int len)
{
	text = getparams(text);
	if (*text)
	{
		Uint32 value = get_key_value(text);
		if (value)
			do_keypress(value);
	}
	return 1;
}
Exemplo n.º 7
0
/* pretend the specified key has been pressed - allows user menu to trigger keypress events */
int command_keypress(char *text, int len)
{
	text = getparams(text);
	if (*text)
	{
		Uint32 value = get_key_value(text);
		if (value)
			keypress_root_common(value, 0);
	}
	return 1;
}
Exemplo n.º 8
0
Parse_stat MCSampleVariance::parse(MCScriptPoint &sp, Boolean the)
{
	initpoint(sp);
	
	if (getparams(sp, &params) != PS_NORMAL)
	{
		MCperror->add
		(PE_VARIANCE_BADPARAM, line, pos);
		return PS_ERROR;
	}
	return PS_NORMAL;
}
Exemplo n.º 9
0
Parse_stat MCAvgDev::parse(MCScriptPoint &sp, Boolean the)
{
	initpoint(sp);
	
	if (getparams(sp, &params) != PS_NORMAL)
	{
		MCperror->add
		(PE_AVGDEV_BADPARAM, line, pos);
		return PS_ERROR;
	}
	return PS_NORMAL;
}
Exemplo n.º 10
0
Parse_stat MCHarmonicMean::parse(MCScriptPoint &sp, Boolean the)
{
	initpoint(sp);
	
	if (getparams(sp, &params) != PS_NORMAL)
	{
		MCperror->add
		(PE_HAR_MEAN_BADPARAM, line, pos);
		return PS_ERROR;
	}
	return PS_NORMAL;
}
Exemplo n.º 11
0
/* parse the command parameters for a spell message, then cast it */
static int command_cast_spell(char *text, int len)
{
	int index = 0;
	int valid_looking_message = 1;
	Uint8 str[30];
	
	/* valid messages start with the CAST_SPELL message of 39 or 0x27 */
	text = getparams(text);
	if (!*text || strstr(text, "27")==NULL)
		valid_looking_message = 0;
	/* skip past everything until the CAST_SPELL message type */
	else
		text = strstr(text, "27");
	
	/* while we have hex digit pairs to process */
	while (valid_looking_message && strlen(text)>0 && index<30)
	{
		int i;
		Uint8 d[2];
		while (*text==' ')
			text++;
		if (strlen(text)<2)
			break;
		for (i=0; i<2; i++)
		{
			d[i] = *text++;
			if (d[i] >= '0' && d[i] <= '9')
				d[i] -= '0';
			else if (d[i] >= 'a' && d[i] <= 'f')
				d[i] -= 'a'-10;
			else if (d[i] >= 'A' && d[i] <= 'F')
				d[i] -= 'A'-10;
			else
			{
				valid_looking_message = 0;
				break;
			}
		}
		/* store the spell message byte */
		if (valid_looking_message)
			str[index++] = d[1] + 16*d[0];
	}
	
	/* if we're now at the end of the text, we have some message bytes and it looks valid */
	if (!*text && index && valid_looking_message)
		send_spell(str, index);
	else
		LOG_TO_CONSOLE(c_red2, invalid_spell_string_str);
	
	return 1;
}
Exemplo n.º 12
0
// TODO: make this automatic or a better command, m is too short
int command_msg(char *text, int len)
{
	int no;

	// find first space, then skip any spaces
	text = getparams(text);
	if(my_strncompare(text, "all", 3))
	{
		print_all_messages();
	}
	else
	{
		no = atoi(text) - 1;
		print_message(no);
	}
	return 1;
}
Exemplo n.º 13
0
// TODO: make this automatic or a better command, m is too short
int command_msg(char *text, int len)
{
	int no;//, m=-1;

	// find first space, then skip any spaces
	text = getparams(text);
	if(my_strncompare(text, "all", 3)) {
		for(no = 0; no < pm_log.ppl; no++) {
			print_message(no);
		}
	} else {
		no = atoi(text) - 1;
		if(no < pm_log.ppl && no >= 0) {
			print_message(no);
		}
	}
	return 1;
}
Exemplo n.º 14
0
int command_accept_buddy(char *text, int len)
{
	/* This command is here to make sure the requests queue is up to date */
	text = getparams(text);
	/* Make sure a name is given */
	if(*text && !queue_isempty(buddy_request_queue)) {
		node_t *node = queue_front_node(buddy_request_queue);

		/* Search for the node in the queue */
		while(node != NULL) {
			if(strcasecmp(text, node->data) == 0) {
				/* This is the node we're looking for, delete it */
				queue_delete_node(buddy_request_queue, node);
				break;
			}
			node = node->next;
		}
	}
	return 0;
}
Exemplo n.º 15
0
/* display or test the md5sum of the current map or the specified file */
int command_ckdata(char *text, int len)
{
	const int DIGEST_LEN = 16;
	Uint8 digest[DIGEST_LEN];
	char digest_str[DIGEST_LEN*2+1];
	char expected_digest_str[DIGEST_LEN*2+1];
	char result_str[256];
	char filename[256];

	/* paramters are optional, first is expected checksum value, second is filename */
	/* if only a filename is specfied, we display checksum rather than do match */
	filename[0] = digest_str[0] = expected_digest_str[0] = '\0';
	text = getparams(text);
	if (*text)
	{
		/* if we have at least one space and the first string is of digest length, assume we matching */
		char *tempstr = safe_strcasestr(text, strlen(text), " ", 1);
		if ((tempstr != NULL) && (strlen(text) - strlen(tempstr) == DIGEST_LEN*2))
		{
			safe_strncpy2(expected_digest_str, text, DIGEST_LEN*2+1, DIGEST_LEN*2 );
			/* trim leading space from filename */
			while (*tempstr == ' ')
				tempstr++;
			if (*tempstr)
				safe_strncpy(filename, tempstr, 256);
		}
		/* else we only have a filename */
		else
			safe_strncpy(filename, text, 256 );
	}
	/* if no parameters default to current map elm file */
	else
		safe_strncpy(filename, continent_maps[cur_map].name, 256 );

	/* calculate, display checksum if we're not matching */
	if (*filename && el_file_exists(filename) && get_file_digest(filename, digest))
	{
		int i;	
		for(i=0; i<DIGEST_LEN; i++)
			sprintf(&digest_str[2*i], "%02x", (int)digest[i]);
		digest_str[DIGEST_LEN*2] = 0;
		if (! *expected_digest_str)
		{
			safe_snprintf(result_str, sizeof(result_str), "#ckdata %s %s", digest_str, filename );
			LOG_TO_CONSOLE(c_grey1,result_str);
		}
	}
	/* show help if something fails */
	else
	{
		LOG_TO_CONSOLE(c_red2, "ckdata: invalid file or command syntax.");
		LOG_TO_CONSOLE(c_red1, "Show current map (elm): #ckdata");
		LOG_TO_CONSOLE(c_red1, "Show specified file:    #ckdata file_name");
		LOG_TO_CONSOLE(c_red1, "Check specified file:   #ckdata expected_checksum file_name");
		return 1;
	}

	/* if we have an expected value, compare then display an appropriate message */
	if (*expected_digest_str)
	{
		if (my_strcompare(digest_str, expected_digest_str))
			LOG_TO_CONSOLE(c_green2,"ckdata: File matches expected checksum");
		else
			LOG_TO_CONSOLE(c_red2,"ckdata: File does not match expected checksum");
	}
	
	return 1;
	
} /* end command_ckdata() */
Exemplo n.º 16
0
int main (void)
{
	sei();
	uart_init(UART_BAUD_SELECT(9600, F_CPU));
	uart_puts("\r\n\r\nTHIS PROGRAM USES 57600 BAUD - PLEASE CHANGE\r\n\r\n");

	_delay_ms(100);
	uart_init(UART_BAUD_SELECT(57600, F_CPU));
	cmd_clear();

	uart_puts_P("\n\n\n\n\r");
	uart_puts_P("--------------------------\r\n");
	uart_puts_P("System                [OK]\r\n");
	systimer_init();
	uart_puts_P("System Timer          [OK]\r\n");

	/* SD Karte Initilisieren */
	cmd_init();

	uart_puts_P("--------------------------\r\n\r\n");

	_delay_ms(100);
	char input[50]={0};
	static char parameters[10][32];
	while(1)
	{
		for (uint8_t i = 0; i<=10; *parameters[++i]=0x00);

		// Input
		uart_puts_P("> ");
		uart_input(input);

		// Process Input
		getparams(input, 10, 32, parameters);
		char *cmd = parameters[0];

		// Call Functions
		if (strings_equal(cmd, "ls"))
		{
			uint32_t cluster = 0;
			if (parameters[1][0] != 0x00)
				cluster = str2num(parameters[1], 16);
			cmd_ls(cluster);
		}
		else if (strings_equal(cmd, "cat"))
		{
			if (parameters[1][0] == 0x00 || parameters[2][0] == 0x00)
				cmd_help("cat");
			else
			{
				uint64_t cluster	= str2num(parameters[1], 16);
				uint64_t size		= str2num(parameters[2], 16);
				cmd_cat(cluster, size);
			}
		}
		else if (strings_equal(cmd, "readtest"))
		{
			if (parameters[1][0] == 0x00 || parameters[2][0] == 0x00)
				cmd_help("readtest");
			else
			{
				uint64_t cluster	= str2num(parameters[1], 16);
				uint64_t size		= str2num(parameters[2], 16);
				cmd_readtest(cluster, size);
			}
		}
		else if (strings_equal(cmd, "write"))
		{
			if (parameters[1][0] == 0x00 || parameters[2][0] == 0x00)
				cmd_help("write");
			else
			{
				uint64_t cluster	= str2num(parameters[1], 16);
				uint8_t  adcport	= str2num(parameters[2], 10);
				uint64_t maxsize	= str2num(parameters[3], 16);
				uint8_t  speed		= str2num(parameters[4], 10);
				if (parameters[3][0] == 0x00)
					maxsize = 512;
				if (parameters[4][0] == 0x00)
					speed = 50;
				cmd_write(cluster, adcport, maxsize, speed);
			}
		}
		else if (strings_equal(cmd, "clear"))
			cmd_clear();
		else if (strings_equal(cmd, "time"))
			cmd_time();
		else if (strings_equal(cmd, "init"))
			cmd_init();
		else if (strings_equal(cmd, "help"))
			cmd_help(parameters[1]);
		else
			uart_puts_P("Error: Command not found\n\r");
	}

	while (1);
	return (1);
}
Exemplo n.º 17
0
/*  Display book names that match the specified string, or all if
 *  no string specified.  Highlighing the books that have been read.
 */
int knowledge_command(char *text, int len)
{
	char this_string[80], count_str[60];
	char *cr;
	int num_read = 0, num_total = 0;
	int show_read = 1, show_unread = 1, show_help = 0;
	size_t i;
	char * pstr[3] = { knowledge_param_read, knowledge_param_unread, knowledge_param_total };
	size_t plen[3] = { strlen(knowledge_param_read), strlen(knowledge_param_unread), strlen(knowledge_param_total) };

	// find first space, then skip any spaces
	text = getparams(text);

	// use the short form of the params (-r -u -t) if valid and different
	if ((plen[0] > 1) && (plen[1] > 1) && (plen[2] > 1) &&
		(pstr[0][0] == '-') && (pstr[1][0] == '-') && (pstr[2][0] == '-') &&
		(pstr[0][1] != pstr[1][1]) && (pstr[0][1] != pstr[2][1]) && (pstr[1][1] != pstr[2][1]))
		plen[0] = plen[1] = plen[2] = 2;

	// show the help if no paramaters specified
	if (strlen(text) == 0)
		show_help = 1;

	// Look for -read, -unread or -total paramaters and vary the output appropriately
	else if (strncmp(text, knowledge_param_read, plen[0]) == 0)
	{
		show_unread = 0;
		text = getparams(text+plen[0]);
	}
	else if (strncmp(text, knowledge_param_unread, plen[1]) == 0)
	{
		show_read = 0;
		text = getparams(text+plen[1]);
	}
	else if (strncmp(text, knowledge_param_total, plen[2]) == 0)
	{
		show_read = show_unread = 0;
		text = getparams(text+plen[2]);
	}

	if (show_read || show_unread)
		LOG_TO_CONSOLE(c_green2,knowledge_cmd_str);

	for (i=0; i<KNOWLEDGE_LIST_SIZE; i++)
	{
		// only display books that contain the specified parameter string
		// shows all books if no string specified
		if ((strlen(knowledge_list[i].name) > 0) &&
			(get_string_occurance(text, knowledge_list[i].name, strlen(knowledge_list[i].name), 1) != -1))
		{
			// remove any trailing carrage return
			safe_strncpy(this_string, knowledge_list[i].name, sizeof(this_string));
			if ( (cr = strchr(this_string, '\n')) != NULL)
				*cr = '\0';
			// highlight books that have been read
			if (knowledge_list[i].present)
			{
				if (show_read)
					LOG_TO_CONSOLE(c_grey1,this_string);
				++num_read;
			}
			else if (show_unread)
				LOG_TO_CONSOLE(c_grey2,this_string);
			++num_total;
		}
	}
	safe_snprintf(count_str, sizeof(count_str), book_count_str, num_read, num_total);
	LOG_TO_CONSOLE(c_grey1, count_str);

	// give help only if no parameters specified
	if (show_help)
		LOG_TO_CONSOLE(c_grey1, know_help_str);

	return 1;
}
Exemplo n.º 18
0
Arquivo: find.hpp Projeto: atyuwen/nt2
 BOOST_FORCEINLINE result_type operator()( A0& a0, A1& a1 ) const
 {
   bool    first =  true;
   getparams(a0, first, N0());
   compute(a0, a1, first, N1());
 }
Exemplo n.º 19
0
int main(int argc, const char* argv[])
{
	
	if (argc < 2) {
    printf("Usage: ./dinneuro filename\n");
    return -1;
	}
	
	//подготавливаем выборки
	if (csv2fann2(argv[1], 59, 50, 100, true)) { printf("Converted\n"); }
	
	//получим данные о количестве входных и выходных параметров
	int *params;
	const char * filename;
	const char * normfilename;
	filename = "data.data";
	//filename = "scaling.data";
	normfilename = "normalized.train";
	params = getparams(filename);
	
    unsigned int num_threads = omp_get_thread_num();
	float error;
	const unsigned int num_input = params[1];
	const unsigned int num_output = params[2];
	//printf("num_input=%d num_output=%d\n", num_input, num_output);
	const unsigned int num_layers = 4;
	//const unsigned int num_neurons_hidden = num_output;
	const unsigned int num_neurons_hidden = 5;
	const float desired_error = (const float) 0.0001;
	const unsigned int max_epochs = 5000;
	const unsigned int epochs_between_reports = 1000;
	struct fann_train_data * data = NULL;
	struct fann *ann = fann_create_standard(num_layers, num_input, num_neurons_hidden, num_neurons_hidden, num_output);
	fann_set_activation_function_hidden(ann, FANN_LINEAR);
	fann_set_activation_function_output(ann, FANN_SIGMOID_SYMMETRIC);
	fann_set_training_algorithm(ann, FANN_TRAIN_RPROP);
	//printf("test\n");
	data = fann_read_train_from_file(filename);
	
	printf("Readed train from %s\n", filename);
	
	fann_set_scaling_params(
		    ann,
			data,
			-1,	/* New input minimum */
			1,	/* New input maximum */
			-1,	/* New output minimum */
			1);	/* New output maximum */

	fann_scale_train( ann, data );
	printf("Scaled\n");
	
	//сохраним нормализованную обучающу выборку в файл
	fann_save_train(data, normfilename);
	printf("Saved scaled file %s\n", normfilename);
	
	unsigned int i;
	printf("Start learning...\n");
	for(i = 1; i <= max_epochs; i++)
	{
		error = num_threads > 1 ? fann_train_epoch_irpropm_parallel(ann, data, num_threads) : fann_train_epoch(ann, data);
		//если ошибка обучения меньше или равно заданной - выходим из цикла обучения
		//if (error <= desired_error) { printf ("Desired error detected. Finishing teaching.\n"); break; }
		//если текущий счетчик делится без остатка на epochs_between_reports - пишем лог
		//if (i % epochs_between_reports == 0) { printf("Epochs     %8d. Current error: %.10f\n", i, error); }
		
	}
	printf("End learning.\n");
	printf("MSE = %f\n", fann_get_MSE(ann));

	//fann_train_on_data(ann, data, max_epochs, epochs_between_reports, desired_error);
	fann_destroy_train( data );
	fann_save(ann, "scaling.net");
	fann_destroy(ann);
	
	//проверка
	printf("Testing...\n");
	fann_type *calc_out;
	//printf("fann_length_train_data=%d\n",fann_length_train_data(data));
	printf("Creating network.\n");
	ann = fann_create_from_file("scaling.net");
	if(!ann)
	{
		printf("Error creating ann --- ABORTING.\n");
		return 0;
	}
	
	//печатаем параметры сети
	//fann_print_connections(ann);
	//fann_print_parameters(ann);
	
	printf("Testing network.\n");
	data = fann_read_train_from_file(filename);
	for(i = 0; i < fann_length_train_data(data); i++)
	{
		fann_reset_MSE(ann);
    	fann_scale_input( ann, data->input[i] );
		calc_out = fann_run( ann, data->input[i] );
		fann_descale_output( ann, calc_out );
		printf("Result %f original %f error %f or %.2f%%\n",
			calc_out[0], data->output[i][0],
			(float) fann_abs(calc_out[0] - data->output[i][0]), (100*(float) fann_abs(calc_out[0] - data->output[i][0]))/(float)calc_out[0]);
	}

	fann_destroy_train( data );
	fann_destroy(ann);

return 0;
}
Exemplo n.º 20
0
int 
main(int argc, char *argv[])
{
   MPI_Comm comm = MPI_COMM_WORLD;  /* Communicator. */
   MPI_Datatype pparams_mpi;         /* Contains all the parameters. */
   MPI_Status   time_sts;
   int nnodes = 5;                  /* Total number of nodes. */
   int gsize[2] = {0};               /* Grid size. */
   int periods[2] = {false, false};
   int rank = 0;
   int coord[2];
   /* We are interested in the diffusion process in two directions. */
   const size_t dims = 2;
   int status;
   int offset[2];
   size_t grains[2];
   int coord_lneigh[2];
   int coord_rneigh[2];
   int coord_uneigh[2];
   int coord_dneigh[2];
   int rank_lneigh;
   int rank_rneigh;
   int rank_uneigh;
   int rank_dneigh;
   MPI_Status xdown_status;
   MPI_Status xup_status;
   MPI_Status yleft_status;
   MPI_Status yright_status;

   double time_start_comm = 0;
   double time_start_comp = 0;
   double time_start_init = 0;
   double time_end_init = 0;
   double time_end_comm = 0;
   double time_end_comp = 0;
   double time_start_total = 0;
   double time_end_total = 0;
   double time_recv_buf;

   size_t yend;
   size_t ystart;

#ifndef NO_SSE
   grid_simd_type   sse_ratio;
   grid_simd_type   sse_ratio1;
   grid_simd_type   curr_grid;
   grid_simd_type   currr_grid;
   grid_simd_type   currl_grid;
   grid_simd_type   curru_grid;
   grid_simd_type   currd_grid;
   grid_simd_type   ngrid_sse;
#endif /* NO_SSE */

   grid_type **grid = NULL;
   grid_type **ngrid = NULL;
   grid_type *xdown = NULL;
   grid_type *xup = NULL;

   grid_type ratio;
   grid_type ratio1;

   /* Arguments. */
   pparams params;

   FILE   *profilefile = NULL;
   FILE   *statusfile = NULL;

   size_t i;
   size_t x, y;
#ifndef NO_SSE
   size_t y_qdl;
   size_t y_qdl_r;
#endif /* NO_SSE */
   long time = 0;

   MPI_Init(&argc, &argv);
   time_start_init = MPI_Wtime();
   time_start_total = MPI_Wtime();
   MPI_Comm_rank(comm, &rank);
   /* Parse the parameters. The function only parses parameters if this
    * processor has rank zero. */
   if ((status = getparams(argc, argv, &params, &profilefile, &statusfile,
               &pparams_mpi, rank)) != EX_OK)
      MPI_Abort(comm, status);

   /* Send all the parameters to the remaining nodes in the comm. */
   MPI_Bcast(&params, 1, pparams_mpi, 0, MPI_COMM_WORLD);

   /* Determine the number of nodes in the communicator. */
   MPI_Comm_size(comm, &nnodes);

   /* Check whether the number of nodes can be used to form a two dimensional
    * grid equal height and length. */
   if (rank == 0 && nnodes / params.l != params.h) {
      usage(); 
   }
   /* The grid should be the same on each node. */
   if (rank == 0 && params.ntotal % (params.l * params.h) != 0) {
      usage();
   }
   /* Compute the grid form. */
   gsize[X_COORD] = params.l;
   gsize[Y_COORD] = params.h;

   /* Create a get information of a Cartesian grid topology. */
   if (MPI_Cart_create(comm, dims, gsize, periods, true, &comm) != 
         MPI_SUCCESS) 
      MPI_Abort(comm, EX_UNAVAILABLE);

   /* Translate the current rank to the coordinate in the Cartesian 
    * topology. */
   MPI_Cart_coords(comm, rank, dims, coord);


   /* Using the coordinate of the current node we can determine the amount of
    * points this node has to compute and the offset of the points. */
   for (i = 0; i < dims; i++) {
      grains[i] = params.ntotal / gsize[i] + (params.ntotal % gsize[i] +
            gsize[i] - coord[i] - 1) / gsize[i];

      if (grains[i] > (size_t)params.ntotal / gsize[i])
         offset[i] = (params.ntotal / gsize[i] + 1) * coord[i];
      else
         offset[i] = params.ntotal / gsize[i] * coord[i] + params.ntotal % gsize[i];
   }

   /* With the current dimensions arrays which represent the grid can be
    * allocated. Two more entries are used to store neighbouring points. 
    *
    * Grids are composed as follows:
    *
    * |  |  |  |   |   |       |            |
    * |  |  |  |   |   |       |            |
    * |  |  |  |   |   |       |            |
    * |  |  |  |   |   |       |            |
    * |  |  |  |   |   |       |            |
    * 0  1  2  ..  ..  ..  grains[x]    grains[x] + 1
    * |  |  |  |   |   |       |            |
    * |  |  |  |   |   |       |            |
    * |  |  |  |   |   |       |            |
    * |  |  |  |   |   |       |            |
    * |  |  |  |   |   |       |            |
    *
    */
   if ((grid = calloc(grains[X_COORD] + 2, sizeof(grid_type *))) == NULL ||
         (ngrid = calloc(grains[X_COORD] + 2, sizeof(grid_type *))) == NULL)
      MPI_Abort(comm, EX_OSERR);

   for (i = 0; i < grains[X_COORD] + 2; i++)
      if ((grid[i] = calloc(grains[Y_COORD] + 2, sizeof(grid_type))) == NULL ||
            (ngrid[i] = calloc(grains[Y_COORD] + 2, sizeof(grid_type))) == NULL)
         MPI_Abort(comm, EX_OSERR);

   /* Create temporary storage to prevent iterating through the entire grid. */
   if ((xdown = calloc(grains[X_COORD], sizeof(grid_type))) == NULL ||
         (xup = calloc(grains[X_COORD], sizeof(grid_type))) == NULL)
      MPI_Abort(comm, EX_OSERR);

   if ((params.dt * params.D * 4 / (params.dx * params.dx)) > 1)
      ratio = 1;
   else
      ratio = params.dt * params.D / (params.dx * params.dx);

   ratio = 1.0 / 4.0;
   ratio1 = 1.0 - 4.0 * ratio;
#ifndef NO_SSE
#   ifdef DOUBLE
   sse_ratio = _mm_set1_pd(ratio);
   /* This variable is used to reduce the number of computations when computing
    * the finite difference scheme. */
   sse_ratio1 = _mm_set1_pd(1.0 - 4.0 * ratio);
#   else
   sse_ratio = _mm_set_ps1(ratio);
   sse_ratio1 = _mm_set_ps1(1.0 - 4.0 * ratio);
#   endif /* DOUBLE */
#endif /* NO_SSE */

   /* All the coordinates are translated to ranks by first computing the
    * coordinate of the appropriate neighbours. Then the coordinates are
    * used to determine the rank. These ranks can be used for the
    * communication. */
   coord_lneigh[X_COORD] = (coord[X_COORD] + gsize[X_COORD] - 1) % gsize[X_COORD];
   coord_rneigh[X_COORD] = (coord[X_COORD] + 1) % gsize[X_COORD];
   coord_lneigh[Y_COORD] = coord[Y_COORD];
   coord_rneigh[Y_COORD] = coord[Y_COORD];

   coord_dneigh[Y_COORD] = (coord[Y_COORD] + gsize[Y_COORD] - 1) % gsize[Y_COORD];
   coord_uneigh[Y_COORD] = (coord[Y_COORD] + 1) % gsize[Y_COORD];
   coord_dneigh[X_COORD] = coord[X_COORD];
   coord_uneigh[X_COORD] = coord[X_COORD];

   MPI_Cart_rank(comm, coord_lneigh, &rank_lneigh);
   MPI_Cart_rank(comm, coord_rneigh, &rank_rneigh);
   MPI_Cart_rank(comm, coord_dneigh, &rank_dneigh);
   MPI_Cart_rank(comm, coord_uneigh, &rank_uneigh);

   /* Compute by how much the loop iterators have to be adjusted. */
   yend = 1;
   ystart = 1;
   if (coord[Y_COORD] == (gsize[Y_COORD] - 1)) {
      yend--;
      for (x = 1; x < grains[X_COORD] + 1; ++x) 
         grid[x][grains[Y_COORD]] = 1;
   } 

   if (grains[Y_COORD] - yend - ystart < 1)
      MPI_Abort(MPI_COMM_WORLD, EX_USAGE);

   if (coord[Y_COORD] == 0)
      ystart++;

#ifndef NO_SSE
   /* Compute the loop start and end for the SSE instructions. */
   y_qdl =  (grains[Y_COORD] - ystart + yend) / SIMD_CAPACITY;
   y_qdl_r = (grains[Y_COORD] - ystart + yend) % SIMD_CAPACITY;
#endif /* NO_SSE */
   time_end_init = MPI_Wtime() - time_start_init;

   for (time = 0; time < params.ttotal; time++)
   {
      /* Create two new arrays to prevent bad memory access. */
      for (i = 0; i < grains[X_COORD]; i++) {
         xup[i] = grid[i + 1][grains[Y_COORD]];
         xdown[i] = grid[i + 1][1];
      }

      time_start_comm = MPI_Wtime();
      MPI_Send((void *)xdown, grains[X_COORD], MPI_GRID_TYPE, rank_dneigh, X_DOWN_TAG, comm);
      MPI_Send((void *)xup, grains[X_COORD], MPI_GRID_TYPE, rank_uneigh, X_UP_TAG, comm);

      MPI_Recv((void *)xdown, grains[X_COORD], MPI_GRID_TYPE, rank_dneigh,
            X_UP_TAG, comm, &xdown_status);
      MPI_Recv((void *)xup, grains[X_COORD], MPI_GRID_TYPE, rank_uneigh,
            X_DOWN_TAG, comm, &xup_status);

      time_end_comm += MPI_Wtime() - time_start_comm;

      /* The freshly received xup and xdown have to be put in the grid. */
      for (i = 0; i < grains[X_COORD]; i++) {
         grid[i + 1][grains[Y_COORD] + 1] = xup[i];
         grid[i + 1][0] = xdown[i];
      }

      time_start_comm = MPI_Wtime();
      MPI_Send((void *)(grid[grains[X_COORD]] + 1), grains[Y_COORD], MPI_GRID_TYPE,
            rank_rneigh, Y_RIGHT_TAG, comm);
      MPI_Send((void *)(grid[1] + 1), grains[Y_COORD], MPI_GRID_TYPE,
            rank_lneigh, Y_LEFT_TAG, comm);
      MPI_Recv((void *)(grid[0] + 1), grains[Y_COORD], MPI_GRID_TYPE,
            rank_lneigh, Y_RIGHT_TAG, comm, &yright_status);
      MPI_Recv((void *)(grid[grains[X_COORD] + 1] + 1), grains[Y_COORD], MPI_GRID_TYPE,
            rank_rneigh, Y_LEFT_TAG, comm, &yleft_status);

      time_end_comm += MPI_Wtime() - time_start_comm;

      /* Do a non blocking send of the current grid for printing. */
      if ((time % params.freq) == 0) 
         send_grid(grid, grains, offset, rank, comm, &time_end_comm, PRINT_COMM);

      time_start_comp = MPI_Wtime();
      /* Process the grid per column. */
      for (x = 1; x < grains[X_COORD] + 1; x++) {
#ifdef NO_SSE
         for (y = ystart; y < grains[Y_COORD] + yend; y++) {
            /* Do the finite difference computation. */
            ngrid[x][y] = ratio * (grid[x][y + 1] + grid[x][y - 1]
                  + grid[x + 1][y] + grid[x - 1][y]) 
               + ratio1 *  grid[x][y];
         }
#else
         for (i = 0, y = ystart; i < y_qdl; ++i, y += SIMD_CAPACITY) {
#   ifdef DOUBLE
            /* Load all the necessary values to  SSE2 variables. */
            /* r1 = (x, y + 1)
             * r0 = (x, y)
             */
            curr_grid = _mm_loadu_pd(grid[x] + y);
            /* rr0 = (x + 1, y + 1)
             * rr0 = (x + 1, y) */
            currr_grid = _mm_loadu_pd(grid[x + 1] + y);
            /* rl0 = (x - 1, y + 1)
             * rl0 = (x - 1, y) */
            currl_grid = _mm_loadu_pd(grid[x - 1] + y);
            /* ru0 = (x, y + 2)
             * ru0 = (x, y + 1) */
            curru_grid = _mm_loadu_pd(grid[x] + y + 1);
            /* rd0 = (x, y)
             * rd0 = (x, y - 1) */
            currd_grid = _mm_loadu_pd(grid[x] + y - 1);

            /* Perform arithmetic in an order which should reduce the number of
             * bubbles in the processor pipeline. */
            /* rr = rr + rl */
            currr_grid = _mm_add_pd(currr_grid, currl_grid);
            /* ru = ru + rd */
            curru_grid = _mm_add_pd(curru_grid, currd_grid);
            /* nr = (1 - 4 * ratio) * rr */
            ngrid_sse = _mm_mul_pd(curr_grid, sse_ratio1);
            /* rr = rr + ru */
            currr_grid = _mm_add_pd(currr_grid, curru_grid);
            /* rr += ratio */
            currr_grid = _mm_mul_pd(currr_grid, sse_ratio);
            /* nr += rr */
            ngrid_sse = _mm_add_pd(currr_grid, ngrid_sse);
            /* (x, y + 1) = nr1
             * (x, y) = nr0 */
            _mm_storeu_pd(ngrid[x] + y, ngrid_sse);
#   else
            /* Load all the necessary values to  SSE variables. */
            /* r3 = (x, y + 3)
             * r2 = (x, y + 2)
             * r1 = (x, y + 1)
             * r0 = (x, y)
             */
            curr_grid = _mm_loadu_ps(grid[x] + y);
            currr_grid = _mm_loadu_ps(grid[x + 1] + y);
            currl_grid = _mm_loadu_ps(grid[x - 1] + y);
            curru_grid = _mm_loadu_ps(grid[x] + y + 1);
            currd_grid = _mm_loadu_ps(grid[x] + y - 1);

            /* Perform arithmetic in an order which should reduce the number of
             * bubbles in the processor pipeline. */
            currr_grid = _mm_add_ps(currr_grid, currl_grid);
            curru_grid = _mm_add_ps(curru_grid, currd_grid);
            ngrid_sse = _mm_mul_ps(curr_grid, sse_ratio1);
            currr_grid = _mm_add_ps(currr_grid, curru_grid);
            currr_grid = _mm_mul_ps(currr_grid, sse_ratio);
            ngrid_sse = _mm_add_ps(currr_grid, ngrid_sse);
            _mm_storeu_ps(ngrid[x] + y, ngrid_sse);
#   endif /* DOUBLE */
         }

         /* Compute the remaining points. */
         for (i = 0; i < y_qdl_r; ++i) {
            ngrid[x][y] = ratio * (grid[x][y + 1] + grid[x][y - 1]
                  + grid[x + 1][y] + grid[x - 1][y]) 
               + ratio1 *  grid[x][y];
            y++;
         }
#endif /* NO_SSE */
      }
      time_end_comp += MPI_Wtime() - time_start_comp;

      if (time % params.freq == 0)
         recv_grid(grid, grains, offset, time, rank, nnodes,
               comm, &time_end_comm, PRINT_COMM, &print_elem,
               (void *)profilefile);

      /* Copy the new grid to the current grid. Use the previously computed
       * y-offsets to determine where copying should start. */
      for (x = 1; x < grains[X_COORD] + 1; ++x) 
         memcpy((void *)(grid[x] + ystart), (void *)(ngrid[x] + ystart),
               (grains[Y_COORD] - (ystart - yend)) * sizeof(grid_type));

      /* Ensure that all the processes are at the same point. */
      MPI_Barrier(comm);
   }

   /* Free the memory used for the grid. */
   for (i = 0; i < grains[X_COORD] + 2; i++) {
      free(grid[i]);
      free(ngrid[i]);
   }

   free(grid);
   free(ngrid);
   free(xup);
   free(xdown);

   if (rank != 0) {
      MPI_Send(&time_end_comm, 1, MPI_DOUBLE, 0, TIME_COMM_TAG, MPI_COMM_WORLD);
      MPI_Send(&time_end_comp, 1, MPI_DOUBLE, 0, TIME_COMP_TAG, MPI_COMM_WORLD);
      MPI_Send(&time_end_init, 1, MPI_DOUBLE, 0, TIME_INIT_TAG, MPI_COMM_WORLD);
   } 

   /* Get all the information on the running time. */
   if (rank == 0) {
      for (i = 1; i < (size_t)nnodes; ++i) {
         MPI_Recv(&time_recv_buf, 1, MPI_DOUBLE, i, TIME_COMM_TAG,
               MPI_COMM_WORLD, &time_sts);
         time_end_comm += time_recv_buf;

         MPI_Recv(&time_recv_buf, 1, MPI_DOUBLE, i, TIME_COMP_TAG,
               MPI_COMM_WORLD, &time_sts);
         time_end_comp += time_recv_buf;

         MPI_Recv(&time_recv_buf, 1, MPI_DOUBLE, i, TIME_INIT_TAG,
               MPI_COMM_WORLD, &time_sts);
         time_end_init += time_recv_buf;
      }
      if (statusfile != NULL) {
         time_end_total = MPI_Wtime() - time_start_total;
         fprintf(statusfile, "%s %i %i %i %li %lf %lf %lf %lf %li\n", argv[0],
               nnodes, gsize[X_COORD], gsize[Y_COORD], sizeof(grid_type),
               time_end_total, time_end_comp,
               time_end_init, time_end_comm, time);
         fclose(statusfile);
      }

      fclose(profilefile);
   }


   MPI_Finalize();
   return EX_OK;
}
Exemplo n.º 21
0
/* show counters for this session */
static int session_counters(char *text, int len)
{
	text = getparams(text);
	print_session_counters(text);
	return 1;
}
Exemplo n.º 22
0
void CTextView::OnEditAsciiart() 
{

CAsciiArtDlg dlg;

  dlg.m_strText = App.m_strAsciiArtText;
  dlg.m_iLayout = App.m_iAsciiArtLayout;
  dlg.m_strFont = App.m_strAsciiArtFont;

  if (dlg.DoModal () != IDOK)
    return;

  // remember text but don't save in registry
  App.m_strAsciiArtText = dlg.m_strText;

  // remember layout in registry
  if (dlg.m_iLayout != (int) App.m_iAsciiArtLayout)
    App.db_write_int ("prefs", "AsciiArtLayout", dlg.m_iLayout);	
  App.m_iAsciiArtLayout = dlg.m_iLayout;

  // remember font in registry
  if (dlg.m_strFont != App.m_strAsciiArtFont)
    App.db_write_string ("prefs", "AsciiArtFont", dlg.m_strFont);	
  App.m_strAsciiArtFont = dlg.m_strFont;

CString str = dlg.m_strText;

  switch (dlg.m_iLayout)
    {
    case 1:   // full smush
        smushmode = SM_SMUSH;
      	smushoverride = SMO_FORCE;
        break;

    case 2:   // kern
        smushmode = SM_KERN;
        smushoverride = SMO_YES;
        break;

    case 3:   // full width
        smushmode = 0;
      	smushoverride = SMO_YES;
        break;

    case 4:   // overlap
        smushmode = SM_SMUSH;
      	smushoverride = SMO_YES;
        break;

    default:  // default is normal smush
        smushoverride = SMO_NO;
        break;

    } // end of switch

inchr c;
int i;

	try
	  {
    getparams ();
    readfont (dlg.m_strFont);	
    linealloc();

    for (i = 0; i < str.GetLength (); i++) {

      c = str [i];

      if (isascii(c)&&isspace(c)) {
        c = (c=='\t'||c==' ') ? ' ' : '\n';
        }

      if ((c>'\0' && c<' ' && c!='\n') || c==127) continue;


      addchar (c);

      } // end of processing each character


    for (i=0;i<charheight;i++) {
      CString strLine = Replace (outputline[i], hardblank, " ");
      GetEditCtrl ().ReplaceSel (CFormat ("%s%s", (LPCTSTR) strLine, ENDLINE), true);
      }

    linefree ();
    fontfree ();
    
    }
	catch (CException* e)
	  {
		e->ReportError();
		e->Delete();
    linefree ();    // free memory used
    fontfree ();
	  }
}