Esempio n. 1
0
/* 
 * ===  FUNCTION  ======================================================================
 *         Name:  process_flags
 *  Description:  processes input flags  
 * =====================================================================================
 */
int process_flags(int argc, char* argv[])
{
    if((argc % 2) == 0) 
    {
        cout << "invalid number of arguments specified.\n";
        cout << "usage: " << argv[0] << " <flag> <value> ";
        exit(-1);
    }
    
    int num_flags = (argc-1)/2;
    string* flags = new string[num_flags];
    const char** values = new const char*[num_flags];
    
    int j = 0;
    for(int i = 1; i+1 < argc; ++i)
    {
        flags[j] = string(argv[i]);
        values[j] = argv[i+1];
        ++i;
        ++j;
    }
    
    // validate flags 
    validate_flags(flags, values, num_flags);
    // if no flags provided, globals will use default values
    initialize_variables(flags, values, num_flags);
    
    delete [] flags;
    delete [] values;

	return 0;
}
Esempio n. 2
0
void LBCSolver::solve()
{
	if(!valid_init_data_){
		std::cerr << "Invalid data, unable to solve...." << std::endl;
		return;
	}

	initialize_variables();

    start_timer();
    int iter = 0;
    optimization_end_ = false;

    while (!optimization_end_)
    {
        iter++;
        check_convergence_ = (iter % convergence_check_frequency_ == 0 || iter >= param_.max_iterations);
        output_progress_ = (iter % output_frequency_ == 0 );

        #pragma omp parallel
        {
            this->update_x();

            this->update_w();

            this->update_y();

            this->update_dual_variables(iter);
        }
    }

    end_timer();
    show_elapsed_time();
}
Esempio n. 3
0
/********************
 * dres_parse_file
 ********************/
EXPORTED dres_t *
dres_parse_file(char *path)
{
#define FAIL(err) do { status = err; goto fail; } while (0)
    dres_t *dres = NULL;
    int     status, i;

    if (path == NULL)
        FAIL(EINVAL);
    
    if ((status = lexer_open(path)) != 0)
        FAIL(status);
    
    if ((dres = dres_init(NULL)) == NULL)
        FAIL(errno);

    if ((status = yyparse(dres)) != 0 ||
        (status = check_undefined(dres)) != 0 ||
        (status = initialize_variables(dres)) != 0 ||
        (status = finalize_variables(dres)) != 0)
        FAIL(status);
    
    dres->vm.nlocal = dres->ndresvar;
    for (i = 0; i < dres->ndresvar; i++)
        vm_set_varname(&dres->vm, i, dres->dresvars[i].name);
    
    return dres;
    
 fail:
    if (dres != NULL)
        dres_exit(dres);
    
    errno = status;
    return NULL;
#undef FAIL
}
/*
 * Main function
 */
int main(int argc, char** argv)
{
	if (argc < 2)
	{
		std::cout << "specify data file name" << std::endl;
		return 0;
	}
	const char* data_file_name = argv[1];

const unsigned long long full_program_start = current_time_ns();
{
	// set far field conditions
	{
		const double angle_of_attack = double(3.1415926535897931 / 180.0) * double(deg_angle_of_attack);

		ff_variable[VAR_DENSITY] = double(1.4);

		double ff_pressure = double(1.0);
		double ff_speed_of_sound = sqrt(GAMMA*ff_pressure / ff_variable[VAR_DENSITY]);
		double ff_speed = double(ff_mach)*ff_speed_of_sound;

		cfd_double3 ff_velocity;
		ff_velocity.x = ff_speed*double(cos((double)angle_of_attack));
		ff_velocity.y = ff_speed*double(sin((double)angle_of_attack));
		ff_velocity.z = 0.0;

		ff_variable[VAR_MOMENTUM+0] = ff_variable[VAR_DENSITY] * ff_velocity.x;
		ff_variable[VAR_MOMENTUM+1] = ff_variable[VAR_DENSITY] * ff_velocity.y;
		ff_variable[VAR_MOMENTUM+2] = ff_variable[VAR_DENSITY] * ff_velocity.z;

		ff_variable[VAR_DENSITY_ENERGY] = ff_variable[VAR_DENSITY]*(double(0.5)*(ff_speed*ff_speed)) + (ff_pressure / double(GAMMA-1.0));

		cfd_double3 ff_momentum;
		ff_momentum.x = *(ff_variable+VAR_MOMENTUM+0);
		ff_momentum.y = *(ff_variable+VAR_MOMENTUM+1);
		ff_momentum.z = *(ff_variable+VAR_MOMENTUM+2);
		compute_flux_contribution(ff_variable[VAR_DENSITY], ff_momentum, ff_variable[VAR_DENSITY_ENERGY], ff_pressure, ff_velocity, ff_flux_contribution_momentum_x, ff_flux_contribution_momentum_y, ff_flux_contribution_momentum_z, ff_flux_contribution_density_energy);
	}
	int nel;
	int nelr;

	// read in domain geometry
	double* areas;
	int* elements_surrounding_elements;
	double* normals;
	{
		std::ifstream file(data_file_name);

		file >> nel;
		nelr = block_length*((nel / block_length )+ std::min(1, nel % block_length));

		areas = new double[nelr];
		elements_surrounding_elements = new int[nelr*NNB];
		normals = new double[NDIM*NNB*nelr];

		// read in data
		for(int i = 0; i < nel; i++)
		{
			file >> areas[i];
			for(int j = 0; j < NNB; j++)
			{
				file >> elements_surrounding_elements[i*NNB + j];
				if(elements_surrounding_elements[i*NNB+j] < 0) elements_surrounding_elements[i*NNB+j] = -1;
				elements_surrounding_elements[i*NNB + j]--; //it's coming in with Fortran numbering

				for(int k = 0; k < NDIM; k++)
				{
					file >>  normals[(i*NNB + j)*NDIM + k];
					normals[(i*NNB + j)*NDIM + k] = -normals[(i*NNB + j)*NDIM + k];
				}
			}
		}

		// fill in remaining data
		int last = nel-1;
		for(int i = nel; i < nelr; i++)
		{
			areas[i] = areas[last];
			for(int j = 0; j < NNB; j++)
			{
				// duplicate the last element
				elements_surrounding_elements[i*NNB + j] = elements_surrounding_elements[last*NNB + j];
				for(int k = 0; k < NDIM; k++) normals[(i*NNB + j)*NDIM + k] = normals[(last*NNB + j)*NDIM + k];
			}
		}
	}

	// Create arrays and set initial conditions
	double* variables = alloc<double>(nelr*NVAR);
	initialize_variables(nelr, variables);

	double* old_variables = alloc<double>(nelr*NVAR);
	double* fluxes = alloc<double>(nelr*NVAR);
	double* step_factors = alloc<double>(nelr);

	// these need to be computed the first time in order to compute time step
	std::cout << "Starting..." << std::endl;

	// Begin iterations
	for(int i = 0; i < iterations; i++)
	{
		copy(old_variables, variables, nelr*NVAR);

		// for the first iteration we compute the time step
		compute_step_factor(nelr, variables, areas, step_factors);

		for(int j = 0; j < RK; j++)
		{
			compute_flux(nelr, elements_surrounding_elements, normals, variables, fluxes);
			time_step(j, nelr, old_variables, variables, step_factors, fluxes);
		}
	}

	std::cout << "Saving solution..." << std::endl;
	dump(variables, nel, nelr);
	std::cout << "Saved solution..." << std::endl;


	std::cout << "Cleaning up..." << std::endl;
	dealloc<double>(areas);
	dealloc<int>(elements_surrounding_elements);
	dealloc<double>(normals);

	dealloc<double>(variables);
	dealloc<double>(old_variables);
	dealloc<double>(fluxes);
	dealloc<double>(step_factors);
    } ; 
const unsigned long long full_program_end = current_time_ns();
printf("full_program %llu ns\n", full_program_end - full_program_start);


	std::cout << "Done..." << std::endl;

	return 0;
}
Esempio n. 5
0
XeTeX::XeTeX(int dummy)
{
  create_work_area ();
  place_ptx2pdf_macros ();
  initialize_variables ();
}
Esempio n. 6
0
int main(int argc, char** argv) {
    if ((argc>4)||(argc<3)) {
        fprintf(stderr,"\nERROR: Incorrect usage. Aborting...\n\n");
        fprintf(stderr,"\nExample usage:\n\n");
        fprintf(stderr,"> %s input.dat table.bin 0\n\n",argv[0]);
        fprintf(stderr,"  1st argument = file containing matrix size, type, and margins, formatted as e.g.\n");
        fprintf(stderr,"                   13 17 0\n");
        fprintf(stderr,"                   14 13 14 10 12 2 10 1 10 11 6 2 17\n");
        fprintf(stderr,"                   4 4 11 10 10 8 9 10 8 9 3 10 4 7 9 3 3\n");
        fprintf(stderr,"  2nd argument = filename to use for saving binary data\n");
        fprintf(stderr,"  3rd argument = 0: normal output (default)\n");
        fprintf(stderr,"                 1: suppress all output except the number of matrices\n");
        fprintf(stderr,"\n\n");
        exit(1);
    }
    
    if (argc==4) sscanf(argv[3],"%i",&quiet_mode);
    else quiet_mode = 0; // default is normal output (quiet mode off)
    
    char* input_filename = argv[1];
    char* table_filename = argv[2];
    
    // Read p (row sums), q (column sums), and matrix_type from input file
    int m,n,matrix_type;
    FILE* file = fopen(input_filename, "r");
    fscanf(file,"%i %i %i",&m,&n,&matrix_type);
    int* p; allocate_vector(int,p,m);
    int* q; allocate_vector(int,q,n);
    for (int i = 0; i<m; i++) fscanf(file,"%i",&p[i]);
    for (int i = 0; i<n; i++) fscanf(file,"%i",&q[i]);
    fclose(file);
    
    // Echo what we read in
    print("\n");
    print("Input file: %s\n",input_filename);
    print("Table file: %s\n",table_filename);
    if (matrix_type==0) { print("Binary matrices\n"); }
    else if (matrix_type==1)  { print("Nonnegative integer matrices\n"); }
    else { error("Please use a matrix type of either 0 (binary) or 1 (nonnegative integer)."); }
    print("m = %d\n",m);
    print("n = %d\n",n);
    print("p = "); if (!quiet_mode) print_vector("%d ",p,m);
    print("q = "); if (!quiet_mode) print_vector("%d ",q,n);
    print("====================================\n");
    
    // Make sure p and q are valid.
    validate_margins(p,q,m,n);

    // Initialize counting variables
    data_t* v = initialize_variables(p,q,m,n,"");
    
    print("Counting...\n");
    
    // Start the clock (to time how long it takes to run)
    clock_t start_time = clock();
    
    // Count the number of matrices
    bigint* result = count(v,matrix_type);
                
    // Stop the clock
    clock_t end_time = clock();
    double elapsed_time = ((double)(end_time - start_time))/CLOCKS_PER_SEC;
    
    // Print results
    print("\n");
    print("Elapsed CPU time = %f seconds\n",elapsed_time);
    print("Number of matrices = ");
    gmp_printf("%Zd",*result); // in quiet mode, this is the only output
    
    // Save the hash table to file
    print("\n\n");
    print("Saving lookup table to file...\n");
    hash_table_save(v->table, table_filename);
    
    return 0;
}
Esempio n. 7
0
/*===================================================
=				Programa principal        			=
===================================================*/
int main()
{
	char* argumentos[MAX_ARGS];		//	Argumentos dos executáveis
	char buffer[BUFFER_SIZE];		//	Buffer que guarda os dados da leitura do pipe
	int input;		 				// 	Descritor de ficheiro para o pipe que recebe input dos terminais
	/**
	 * 	Inicializar as variáveis e estruturas da par-shell
	 */
	initialize_variables();	
	/**
	 * 	Atualizar as informações do log da par-shell
	 */
	update_log_values();
	/**
	 * 	Catch do signal ctrl+c
	 */
	if(signal(SIGINT, sig_handler) == SIG_ERR){
		perror("Erro no signal: ");
	}

    while(1){
    	/**
    	 * 	Abrir o pipe que recebe input dos terminais
    	 */
    	if((inputdesc = open(inputpipe,O_RDONLY)) < 0){
    		perror("Erro no open do pipe: ");
    		exit(EXIT_FAILURE);
    	} 
    	/**
    	 * 	Ler informações do pipe
    	 */
    	if((input = read(inputdesc,buffer,BUFFER_SIZE)) <= 0){
    		//	Fechar o pipe apos a leitura
    		close(inputdesc);
    		//	Não lê nada mas tambem não dá erro, continua o ciclo (e.g press enter) 
    		if(input == 0){
    			continue;
    		}
    		perror("Erro no read do input");
    	}
    	else{
    		buffer[input] = '\0';
			if(strcmp(buffer,"exit-global") == 0) {
				/**
				 * 	Sair da par-shell
				 */
				exit_par_shell();
			}
			
			if (sscanf(buffer, "/tmp/terminal-%d", &pidterminal) > 0) {
				/**
				 *	Registar um terminal especifico e o seu pipe
				 */
				printf("Terminal %d criado\n",pidterminal);
				if(fflush(stdout) < 0)
				    perror("Erro no fflush de escrita no par-shell na criação de terminal: ");
				//	Inserir pid do terminal na lista de terminais
				insert_new_terminal(lista_terminais,pidterminal);  
				continue;
			}
			
			if(sscanf(buffer,"stats %d",&pidterminal) > 0){
				/**
				 * 	Enviar o número de processos filhos em execução e 
				 *  o tempo total de execução da par-shell para o terminal
				 */
				//	Construir strings de output e do nome do pipe do terminal
				sprintf(output,"Número de filhos em execução: %d \nTempo total: %g",nfilhos,tempo_total_execucao);
				sprintf(terminalpipe,"/tmp/terminal-%d",pidterminal);
				//	Abrir o pipe do terminal para escrita
				if((fd_write = open(terminalpipe, O_WRONLY)) < 0){
					perror("Erro no open do stats da par-shell: ");
					exit(EXIT_FAILURE); 
				}    
				//	Escrever no pipe do terminal             
				if(write(fd_write,output,strlen(output)) < 0){
					perror("Erro no write do stats da par-shell: ");
				}
				//	Fechar o pipe do terminal
				if(close(fd_write) < 0){
					perror("Erro no close do stats da par-shell: ");
				}
				strcpy(output,"\0");
				continue;
			}
			else {
				int i;		//	Inteiro temporário usado no ciclo de processamento dos argumentos 
				int pid;	//	Pid do processo filho criado com fork
				/**
				 * 	Processar todos os argumentos que poderá receber
				 */
				argumentos[0] = strtok(buffer," ");
				for(i = 1; i < MAX_ARGS; i++){ 
					argumentos[i] = strtok(NULL," ");
				}
				/**
				 * 	Confirmar se podem ser criados filhos
				 */
				mutex_lock();
				while (! (nfilhos < MAXPAR))
					if(pthread_cond_wait(&podeCriarFilhos,&mutex) != 0){
						perror("Erro no pthread_cond_wait na par-shell: ");
					}
				mutex_unlock();

				/**
				 * 	Criar processo filho usando fork
				 */
				pid = fork(); 					
				//	Registar tempo de inicio do processo filho
				time_t starttime = time(NULL);  
				if (pid < 0) {
					perror("Erro no fork: ");
					continue;
				}
				/**
				 * 	Código do processo filho
				 */
				if (pid == 0) {  		
					// 	Redirecionar o output do processo filho		
					redirect_stdout();
					// 	Evitar que o ctrl+c se propague para o processo filho -> signal é ignorado
					signal(SIGINT,SIG_IGN);
					//	Trocar código do processo filho pelo do executável	
					if(execv(argumentos[0], argumentos) < 0){
						perror("Erro no execv:");
						exit(EXIT_FAILURE);
					}
				}
				/**
				 * 	Código do processo pai
				 */
				mutex_lock();		
				nfilhos++;
				if(pthread_cond_signal(&podeMonitorizar) != 0){
					perror("Erro no pthread_cond_signal na par-shell: ");
				}
				insert_new_process(list,pid,starttime);
				mutex_unlock();
			}
		}	
	}
	return 0;
}