Exemplo n.º 1
0
	exit_t main()
	{
		FILE* read_fp=stdin;
		char separator = ' ';

		switch(argc)
		{
			case 2: assert_usage(!strcmp(argv[1],"newlines"));
				separator = '\n';
			case 1: break;
			default: exit_usage();
		}

		std::vector<int> grid;
		dimension dim;

		read_grid(read_fp, &grid, &dim);

		for(unsigned int i=0; i<grid.size(); i++)
		{
			const int human = internal2human(i,dim.width());
			while(grid[i] != INT_MIN && grid[i]--)
			 fprintf(stdout, "%d%c", human, separator);
		}
		fputs("\n", stdout);

		return exit_t::success;
	}
Exemplo n.º 2
0
 /// Construct a grid from an input file.
 /// The file format used is currently undocumented,
 /// and is therefore only suited for internal use.
 GridManager::GridManager(const std::string& input_filename)
 {
     ug_ = read_grid(input_filename.c_str());
     if (!ug_) {
         OPM_THROW(std::runtime_error, "Failed to read grid from file " << input_filename);
     }
 }
Exemplo n.º 3
0
/* read an image and generate a result */
int main(int argc, char **argv) {
    int rows=0;
    int cols=0;
    int iterations=0;
    int i;
    int **grid = NULL;
    int **neighbors = NULL;

    if (argc<2 || !(grid=read_grid(stdin,&rows,&cols))
            || (iterations=atoi(argv[1]))<0) {
        fprintf(stderr,"life usage:  life iterations <inputfile\n");
        exit(1);
    }
#ifdef DEBUG
    printf("input:\n");
    print_grid(stdout,grid,rows,cols);
#endif /* DEBUG */
    neighbors = make_grid(rows,cols);
    for (i=0; i<iterations; i++) {
        next(grid, neighbors, rows, cols);
#ifdef DEBUG
        printf("next\n");
        print_grid(stdout,grid,rows,cols);
#endif /* DEBUG */
    }
    print_grid(stdout,grid,rows,cols);
    free_grid(grid,rows);
    free_grid(neighbors,rows);
}
Exemplo n.º 4
0
static void main2(int c, char **v) {
    enum {X, Y, Z};
    TInput ve;
    if (Chain) {
        read_vecs(&c, &v, &ve.v);
        read_vecs(&c, &v, &ve.u);
    } else if (Grid) {
        read_grid(&c, &v, &ve.f);
        read_grid(&c, &v, &ve.t);
    } else if (Tex) {
        read_tex(&c, &v, &ve.tex);
    } else {
        read_vecs(&c, &v, &ve.v);
    }
    UC(main1(&ve));
}
Exemplo n.º 5
0
SQUARE_GRID *read_square_grid(char *keyname,DOUBLEMATRIX *DTM,long (*index_pixel_from_a_bin)(long r, long c,LONGVECTOR *s_index),DOUBLEVECTOR *V,int (*check_novalues)(double x, DOUBLEVECTOR *V),short print) {
	/*!
	 *
	 * \author Emanuele Cordano
	 * \date May 2009
	 *
	 *\param keyname (char *) - keyname of the SQUARE_GRID
	 *\param DTM     (DOUBLEMATRIX *) - Digital Terrain Model
	 *\param long (*index_pixel_from_a_bin)(long r, long c,LONGVECTOR *s_index) - function for the space filling curve
	 *\param V - (DOUBLEVECTOR *) - vector containig novalue information
	 *\param int (*check_novalues)(double x, DOUBLEVECTOR *V) - function identintifyng novalue information
	 *\param print (short)
	 *
	 *\return a SQUARE GRID whose data are written in files with FLUIdTurtle formalism
	 *
	 *
	 *
	 */

	SQUARE_GRID *sq;
	long count,r,c;

//	sq=(SQUARE_GRID *)malloc(sizeof(SQUARE_GRID));
//	if (!sq) t_error("Square Grid sq was not allocated");

//	sq->indices_pixel=m_indices_from_mask(DTM,0,0,INTEGER_NULL,0,index_pixel_from_a_bin,V,(*check_novalues));
//	sq->indices_vertex=m_indices_from_mask(DTM,-1,-1,INTEGER_NULL,0,(*index_pixel_from_a_bin),V,(*check_novalues));
//	sq->indices_horizontal_lines=m_indices_from_mask(DTM,-1,0,INTEGER_NULL,0,(*index_pixel_from_a_bin),V,(*check_novalues));

	sq=(SQUARE_GRID *)malloc(sizeof(SQUARE_GRID));
	if (!sq) t_error("Square Grid sq was not allocated");
	sq->indices_pixel=m_indices_from_mask(DTM,0,0,INTEGER_NULL,0,index_pixel_from_a_bin,V,(*check_novalues));
	sq->indices_vertex=m_indices_from_mask(DTM,-1,-1,INTEGER_NULL,0,(*index_pixel_from_a_bin),V,(*check_novalues));
	sq->indices_horizontal_lines=m_indices_from_mask(DTM,-1,0,INTEGER_NULL,0,(*index_pixel_from_a_bin),V,(*check_novalues));
	count=0;
	for(r=sq->indices_horizontal_lines->nrl;r<=sq->indices_horizontal_lines->nrh;r++){
		for (c=sq->indices_horizontal_lines->ncl;c<=sq->indices_horizontal_lines->nch;c++){
	    	if (sq->indices_horizontal_lines->element[r][c]!=INTEGER_NULL) count++;
		}
	}
	sq->nhorizontal_lines=count;
	sq->novalue=INTEGER_NULL;
	sq->indices_vertical_lines=m_indices_from_mask(DTM,0,-1,INTEGER_NULL,count,(*index_pixel_from_a_bin),V,(*check_novalues));


    printf("Warning: index matrix of SQUARE_GRID (already created)  %s was not checked!!\n",keyname);
    sq->novalue=sq->indices_pixel->element[1][1]; /*! first element of sqp->inices_pixel is assumed as a no-value */
	sq->grid=read_grid(keyname,print);
    if (print==1) printf("Function read_square_grid (%s) was correctly executed!!! \n",keyname);
	return sq;

}
Exemplo n.º 6
0
/** Read the density data of a 8-bit MRC file */
void MRCReaderWriter::read_8_data(float *pt)
{
  seek_to_data();
  size_t n = header.nx*header.ny*header.nz;
  unsigned char *grid_8bit= new unsigned char [n]; // memory
  read_grid(grid_8bit,sizeof(unsigned char), n);
  // Transfer to floats
  for(size_t i=0;i<n;i++)
    pt[i]=(float)grid_8bit[i];
  delete(grid_8bit);
  //  std::cout << "MRC file read in 8-bit mode: grid "
  //<< header.nx << "x" << header.ny << "x" << header.nz << "\n";
}
Exemplo n.º 7
0
main()
{
    int t;

    scanf("%d",&t);
    while (t--)
    {
        read_grid();
        init();
        solve();
        print_grid();
    }
    return 0;
}
Exemplo n.º 8
0
int main(int argc, char *argv[])
{
  GSList *words, *letters, *constraints, *ll;
  GPtrArray *dictionary;
  gchar *grid;
  struct wordvar *w;

  if (argc != 3) {
    printf("usage: %s grid dictionary\n", argv[0]);
    exit (-1);
  }
  
  words = letters = constraints = NULL;

  grid = read_grid(argv[1], &words, &letters, &constraints);
  dictionary = read_words(argv[2]);
  init_vars(words, letters, dictionary);

  printf("%s\n", grid);

  w = words->data;
  printf("Initial %d\n", w->possible_values->len);

  for (ll = constraints; ll != NULL; ll = ll->next) {
    struct constraint *c = ll->data;
    put_constraint_on_queue(c);
  }

  run_constraints();

  printf("First %d\n", w->possible_values->len);

  for (ll = constraints; ll != NULL; ll = ll->next) {
    struct constraint *c = ll->data;
    put_constraint_on_queue(c);
  }


  total = 0;
  find_solution(words, letters, grid, 0);
  printf("total %d\n", total);


  return (0);
}
Exemplo n.º 9
0
    exit_t main()
    {
        std::vector<int> grid;
        dimension dim;
        read_grid(stdin, &grid, &dim);
        const int grid_size = dim.area_without_border();
        int idx;
        for(int i = 1; i < argc; i++)
        {
            idx = atoi(argv[i]);
            if(! human_idx_on_grid(grid_size, idx))
                exit("You must assert for each index i: 0 <= i < area.");
            grid[human2internal(atoi(argv[i]),dim.width())]++;
        }

        write_grid(stdout, &grid, &dim);
        return exit_t::success;
    }
Exemplo n.º 10
0
/** Read the density data of a 32-bit MRC file */
void MRCReaderWriter::read_32_data(float *pt)
{
  int needswap;
  seek_to_data();
  size_t n = header.nx*header.ny*header.nz; // size of the grid
  read_grid(pt,sizeof(float), n);
  // Check for the necessity of changing the endian
  needswap = 0;
  for(size_t i=0;i<n;i++)
    if (pt[i] > 1e10 || pt[i] < -1e10) {
      // Really large values usually result if the endian is not correct
      needswap = 1;
      break;
    }
  /* Change endian if necessary */
  if (needswap == 1) {
    unsigned char *ch = (unsigned char *)pt;
    byte_swap(ch, n);
  }
  //  std::cout << "MRC file read in 32-bit mode: grid " << header.nx << "x"
  //          << header.ny << "x" << header.nz << std::endl;
}
Exemplo n.º 11
0
int main(int argc, char* argv[]) {
    FILE* outputFile;
    FILE* gridFile;
    FILE* listFile;

    process_command_line(argc, argv);
    /*
    printf("%d %s %s %s\n", sort, outputFileName, gridFileName, listFileName);
    */
    
    /* Make sure we can open all the files - exit if we don't. */
    /* Note that exiting will close any open files, we do not have to close
    ** them explicitly. */
    gridFile = open_file(gridFileName, "r");
    listFile = open_file(listFileName, "r");
    outputFile = open_file(outputFileName, "w");

    read_grid(gridFile);
    process_list(listFile, outputFile);

    return 0;
}
Exemplo n.º 12
0
int main(int argc, char** argv)
{
	(void)argv;
	FILE* read_fp = stdin;
	if(argc>1) {
		fputs("There are no arguments for this tool.\n", stderr);
		exit(1);
	}

	std::vector<int> grid;
	dimension dim;
	read_grid(read_fp, &grid, &dim);

	graph_t T, S, A;
	create_A(&A, &grid, &dim);
	create_S(&S, &A);
	create_T(&T, &S);

	dump_graph_as_tgf(stdout, &A);

	return 0;
}
Exemplo n.º 13
0
int	main(void)
{
	t_filler	f;
	char		*line;

	line = NULL;
	if (!init_map(&f, &line))
		return (free_filler(&f, &line));
	if (!my_compute(&f))
		return (free_filler(&f, &line));
	free_grid(&f.form);
	while (1)
	{
		if (!read_grid(&f.grid, &line))
			return (free_filler(&f, &line));
		if (!init_grid(&f.form, &line, PIECE))
			return (free_filler(&f, &line));
		if (!my_compute(&f))
			return (free_filler(&f, &line));
		free_grid(&f.form);
	}
	return (free_filler(&f, &line));
}
Exemplo n.º 14
0
int main(){
	_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );

	int istep, nstep, outp_size;
	double t, tmax;

	std::string name("state");
	read_grid("KIRPICH.GRD");
	read_val("initval");
	read_opt("opt", nstep, tmax, outp_size);
	
	if(!recover("schG1.ini", istep, t)){istep = 0;	t = 0;}
	show(name);
	while(istep < nstep || t < tmax){
		step(t);
		istep++;
		std::stringstream ss; ss<<istep;
		std::string s(name);		s.append(ss.str());
		show(s);
	}

	free_all();
	return 0;
}
Exemplo n.º 15
0
// Main programm
int main (int argc, char *argv[]) {

	Search_settings sett;	
	Command_line_opts opts;
  	Search_range s_range; 
  	Aux_arrays aux_arr;
  	double *F; 			// F-statistic array
  	int i, j, r, c, a, b, g; 	
	int d, o, m, k;
	int bins = 2, ROW, dim = 4;	// neighbourhood of point will be divide into defined number of bins
	double pc[4];			// % define neighbourhood around each parameter for initial grid
	double pc2[4];			// % define neighbourhood around each parameter for direct maximum search (MADS & Simplex)
	double tol = 1e-10;
//	double delta = 1e-5;		// initial step in MADS function
//	double *results;		// Vector with results from Fstatnet function
//	double *maximum;		// True maximum of Fstat
//	double results_max[11];	
	double s1, s2, s3, s4;
	double sgnlo[4]; 		 
	double **arr;		//  arr[ROW][COL], arrg[ROW][COL];
	double nSource[3];
  	double sinalt, cosalt, sindelt, cosdelt;
	double F_min;
	char path[512];
	double x, y;
	ROW = pow((bins+1),4);

#ifdef YEPPP
    yepLibrary_Init();
    Yep64f *results_max = (Yep64f*)malloc(sizeof(Yep64f)*11); 
    Yep64f *results_first = (Yep64f*)malloc(sizeof(Yep64f)*11);
    Yep64f *results = (Yep64f*)malloc(sizeof(Yep64f)*11);
    Yep64f *maximum = (Yep64f*)malloc(sizeof(Yep64f)*11);
//    Yep64f *sgnlo = (Yep64f*)malloc(sizeof(Yep64f)*4);  
//    Yep64f *nSource = (Yep64f*)malloc(sizeof(Yep64f)*3); 
    Yep64f *mean = (Yep64f*)malloc(sizeof(Yep64f)*4); 

    enum YepStatus status;

#endif

	pc[0] = 0.015;
	pc[1] = 0.015;
	pc[2] = 0.015;
	pc[3] = 0.015;

	for (i = 0; i < 4; i++){
		pc2[i] = 2*pc[i]/bins;
	}
// Time tests
	double tdiff;
	clock_t tstart, tend;

// Command line options 
	handle_opts(&sett, &opts, argc, argv); 
// Output data handling
/*  struct stat buffer;

  if (stat(opts.prefix, &buffer) == -1) {
    if (errno == ENOENT) {
      // Output directory apparently does not exist, try to create one
      if(mkdir(opts.prefix, S_IRWXU | S_IRGRP | S_IXGRP 
          | S_IROTH	| S_IXOTH) == -1) {
	      perror (opts.prefix);
	      return 1;
      }
    } else { // can't access output directory
      perror (opts.prefix);
      return 1;
    }
  }
*/
	sprintf(path, "%s/candidates.coi", opts.dtaprefix);

//Glue function
	if(strlen(opts.glue)) {
		glue(&opts);

		sprintf(opts.dtaprefix, "./data_total");
		sprintf(opts.dtaprefix, "%s/followup_total_data", opts.prefix); 
		opts.ident = 000;
	}	
	FILE *coi;
	int z;
	if ((coi = fopen(path, "r")) != NULL) {
//		while(!feof(coi)) {

/*			if(!fread(&w, sizeof(unsigned short int), 1, coi)) { break; } 
		  	fread(&mean, sizeof(float), 5, coi);
		  	fread(&fra, sizeof(unsigned short int), w, coi); 
		  	fread(&ops, sizeof(int), w, coi);

			if((fread(&mean, sizeof(float), 4, coi)) == 4){
*/
			while(fscanf(coi, "%le %le %le %le", &mean[0], &mean[1], &mean[2], &mean[3]) == 4){
//Time test
//			tstart = clock();
				arr = matrix(ROW, 4);

//Function neighbourhood - generating grid around point
				arr = neigh(mean, pc, bins);
// Output data handling
/*  				struct stat buffer;

  				if (stat(opts.prefix, &buffer) == -1) {
    					if (errno == ENOENT) {
// Output directory apparently does not exist, try to create one
      						if(mkdir(opts.prefix, S_IRWXU | S_IRGRP | S_IXGRP 
          						| S_IROTH	| S_IXOTH) == -1) {
	      						perror (opts.prefix);
	      						return 1;
      						}
    					} 
					else { // can't access output directory
			      			perror (opts.prefix);
			      			return 1;
			    		}
  				}
*/
// Grid data
  				if(strlen(opts.addsig)) { 

					read_grid(&sett, &opts);
				}
// Search settings
  				search_settings(&sett); 
// Detector network settings
  				detectors_settings(&sett, &opts); 

// Array initialization
  				init_arrays(&sett, &opts, &aux_arr, &F);
				
// Amplitude modulation functions for each detector  
				for(i=0; i<sett.nifo; i++) rogcvir(&ifo[i]); 
// Adding signal from file
  				if(strlen(opts.addsig)) { 

    					add_signal(&sett, &opts, &aux_arr, &s_range);
  				}

// Setting number of using threads (not required)
omp_set_num_threads(1);

				results_max[5] = 0.;

// ifo zostaje shared
// ifo....shft i ifo....xdatm{a,b] prerobić na lokalne tablice w fstatnet
// w regionie parallel wprowadzić tablice private aa i bb ; alokować i przekazywać je jako argumenty do fstatnet i amoeba

// Main loop - over all parameters + parallelisation
#pragma omp parallel default(shared) private(d, i, sgnlo, sinalt, cosalt, sindelt, cosdelt, nSource, results, maximum)
{

                       		double **sigaa, **sigbb;   // aa[nifo][N]
              			sigaa = matrix(sett.nifo, sett.N);
				sigbb = matrix(sett.nifo, sett.N);

#pragma omp for  
				for (d = 0; d < ROW; ++d){

					for (i = 0; i < 4; i++){
						sgnlo[i] = arr[d][i];
//						sgnlo[i] = mean[i]; 
					}
 
					sinalt = sin(sgnlo[3]);
					cosalt = cos(sgnlo[3]);
					sindelt = sin(sgnlo[2]);
					cosdelt = cos(sgnlo[2]);

					nSource[0] = cosalt*cosdelt;
					nSource[1] = sinalt*cosdelt;
					nSource[2] = sindelt;

					for (i = 0; i < sett.nifo; ++i){
						modvir(sinalt, cosalt, sindelt, cosdelt, 
					   		sett.N, &ifo[i], &aux_arr, sigaa[i], sigbb[i]);  
					}
// F-statistic in given point

					results = Fstatnet(&sett, sgnlo, nSource, sigaa, sigbb);
//printf("Fstatnet: %le %le %le %le %le %le\n", results[6], results[7], results[8], results[9], results[5], results[4]);

#pragma omp critical
					if(results[5] < results_max[5]){
						for (i = 0; i < 11; i++){
							results_max[i] = results[i];
						}
					}

// Maximum search using simplex algorithm
					if(opts.simplex_flag){
//						puts("Simplex");

						maximum = amoeba(&sett, &aux_arr, sgnlo, nSource, results, dim, tol, pc2, sigaa, sigbb);
printf("Amoeba: %le %le %le %le %le %le\n", maximum[6], maximum[7], maximum[8], maximum[9], maximum[5], maximum[4]);
// Maximum value in points searching
#pragma omp critical
						if(maximum[5] < results_max[5]){
							for (i = 0; i < 11; i++){
								results_max[i] = maximum[i];
							}
						}

					} //simplex
				} // d - main outside loop
				free_matrix(sigaa, sett.nifo, sett.N);
				free_matrix(sigbb, sett.nifo, sett.N);

} //pragma

				for(g = 0; g < 11; g++) results_first[g] = results_max[g];

// Maximum search using MADS algorithm
  				if(opts.mads_flag) {
//					puts("MADS");
					maximum = MADS(&sett, &aux_arr, results_max, mean, tol, pc2, bins);

				}

//Time test
//				tend = clock();
//				tdiff = (tend - tstart)/(double)CLOCKS_PER_SEC;
				printf("%le %le %le %le %le %le\n", results_max[6], results_max[7], results_max[8], results_max[9], results_max[5], results_max[4]);



			} // while fread coi
//		}
	} //if coi
	else {
		
		perror (path);
		return 1;
	}

// Output information
/*	puts("**********************************************************************");
	printf("***	Maximum value of F-statistic for grid is : (-)%.8le	***\n", -results_first[5]);
	printf("Sgnlo: %.8le %.8le %.8le %.8le\n", results_first[6], results_first[7], results_first[8], results_first[9]);
	printf("Amplitudes: %.8le %.8le %.8le %.8le\n", results_first[0], results_first[1], results_first[2], results_first[3]);
	printf("Signal-to-noise ratio: %.8le\n", results_first[4]); 
	printf("Signal-to-noise ratio from estimated amplitudes (for h0 = 1): %.8le\n", results_first[10]);
	puts("**********************************************************************");
if((opts.mads_flag)||(opts.simplex_flag)){
	printf("***	True maximum is : (-)%.8le				***\n", -maximum[5]);
	printf("Sgnlo for true maximum: %.8le %.8le %.8le %.8le\n", maximum[6], maximum[7], maximum[8], maximum[9]);
	printf("Amplitudes for true maximum: %.8le %.8le %.8le %.8le\n", maximum[0], maximum[1], maximum[2], maximum[3]);
	printf("Signal-to-noise ratio for true maximum: %.8le\n", maximum[4]); 
	printf("Signal-to-noise ratio from estimated amplitudes (for h0 = 1) for true maximum: %.8le\n", maximum[10]);
	puts("**********************************************************************");
}*/
// Cleanup & memory free 
	free(results_max);
	free(results_first);
	free(results);
	free(maximum);
	free(mean);
	free_matrix(arr, ROW, 4);
  	cleanup_followup(&sett, &opts, &s_range, &aux_arr, F);
	

	return 0;

}
int main() {

// Define Variables
	std::string parameter_filename = "solver_parms.txt";
	std::string input_filename = "test4.bkcfd";
	std::string output_filename = "test4_output.txt";
	std::vector<double> parameters;
	std::vector<double> Fiph, Fimh, Giph, Gimh;
	double CFL, dt, delta_x, delta_y, min_delta_x, min_delta_y, min_delta;
	TDstate state_minus, state_plus, slope_minus, slope_plus, limiter_value;
	TDstate state_leftcell, state_rightcell, state_bottomcell, state_topcell;
	std::vector<TDstate> F (2);
	std::vector<TDstate> G (2);

	double thresh = pow(10,-8); // 1E-8 tolerance for riemann solver - velocity
	double gamma = 1.4;
	bool debug = false;
	bool save_timesteps = true;	

// 1 = harmonic mean for slopes, 2 = first order upwind (no limiter) ...
	int limiter_number = 2; 

	std::vector<cell> grid;

	// Read parameters from input file defined by filename string
	parameters = read_parameters(parameter_filename);
	CFL = parameters.at(0);	
	int num_timesteps = parameters.at(1);
	

// Read initial file defined from Matlab with cell edges and connections
// Read the initial condition file from MATLAB with [rho rho*u rho*v e] defined for each cell
	read_grid(input_filename, grid, gamma);
	
	min_delta_x = gridmin(grid, 'x');
	min_delta_y = gridmin(grid, 'y');
	min_delta = std::min(min_delta_x,min_delta_y);
/*
	for(auto input: grid) {
		std::cout << input.cellnumber << '\n';
		std::cout << "cornerlocs_x: " << input.cornerlocs_x[0] << ' ';
		std::cout << input.cornerlocs_x[1] << ' ';
		std::cout << input.cornerlocs_x[2] << ' ';
		std::cout << input.cornerlocs_x[3] << '\n';
		std::cout << "cornerlocs_y: " << input.cornerlocs_y[0] << ' ';
		std::cout << input.cornerlocs_y[1] << ' ';
		std::cout << input.cornerlocs_y[2] << ' ';
		std::cout << input.cornerlocs_y[3] << '\n';
		std::cout << "adjacent_cells: " << input.adjacent_cells[0] << ' ';
		std::cout << input.adjacent_cells[1] << ' ';
		std::cout << input.adjacent_cells[2] << ' ';
		std::cout << input.adjacent_cells[3] << '\n';
		std::cout << "is_edgecell: " << input.is_edgecell << '\n';
		std::cout << "state: " << input.state.rho << ' ';
		std::cout << input.state.rhou << ' ';
		std::cout << input.state.rhov << ' ';
		std::cout << input.state.E << '\n' << '\n';
	} 
*/
	std::vector<TDstate> U;
	for (unsigned int cellnum = 0; cellnum < grid.size(); ++cellnum) {
		U.push_back(grid[cellnum].state);
	}

	double max_wavespeed = 0; 	
	for (unsigned int cellnum = 0; cellnum < grid.size(); ++cellnum) { // For each cell
		if (grid[cellnum].is_edgecell == 0) { // Cell is not a ghost cell/edge cell
         FluxSolver(grid, delta_x, delta_y, state_minus, state_plus, gamma, slope_plus, slope_minus, limiter_number, cellnum, limiter_value, F, G, CFL, max_wavespeed, U, debug);
		}
	}
	dt = CFL*min_delta/max_wavespeed;

// Start calculation in for loop going to final time
	TDstate Uph;
	std::vector<TDstate> Up1 (grid.size());
	for (int timestep = 0; timestep < num_timesteps; timestep++) { // for each timestep
		std::cout << "Timestep " << timestep << " of " << num_timesteps << '\n';
		if (timestep > 0) {
			U = Up1;
		}
		if (debug) {
			outputU(U);
		}

// Go through each cell, calculate fluxes, update to new piecewise linear state
		for (unsigned int cellnum = 0; cellnum < grid.size(); ++cellnum) { // For each cell
			if (grid[cellnum].is_edgecell == 0)  { // Cell is not a ghost cell/edge cell
   	   	FluxSolver(grid, delta_x, delta_y, state_minus, state_plus, gamma, slope_plus, slope_minus, limiter_number, cellnum, limiter_value, F, G, CFL, max_wavespeed, U, debug);
			// Now, use the fluxes calculated above to assign a new state, Uph
				compute_halfway_state(Uph, U[cellnum], F, G, dt, delta_x, delta_y);
		
				if (debug) {				
				std::cout << "Cell number: " << cellnum << '\n';
				std::cout << "bottom/top Limiter - " << limiter_value.rho << " " << limiter_value.rhou << " " << limiter_value.rhov << " "  << limiter_value.E << '\n';
				std::cout << "Current State: " << U[cellnum].rho << " " << U[cellnum].rhou << " " << U[cellnum].rhov << " " << U[cellnum].E << '\n';
//				std::cout << "F, cell number " << cellnum << ": " << '\n';
//				std::cout << F[0].rho << " " << F[0].rhou << " " << F[0].rhov << " " << F[0].E << '\n';
//				std::cout << F[1].rho << " " << F[1].rhou << " " << F[1].rhov << " " << F[1].E << '\n';
	
//				std::cout << "G, cell number: " << cellnum << '\n';
//				std::cout << G[0].rho << " " << G[0].rhou << " " << G[0].rhov << " " << G[0].E << '\n';
//				std::cout << G[1].rho << " " << G[1].rhou << " " << G[1].rhov << " " << G[1].E << '\n';
	
				std::cout << "Cell " << cellnum << " half-state: " <<  Uph.rho << " " << Uph.rhou << " " << Uph.rhov << " " << Uph.E << '\n';
				}

// Solve riemann problem on edge for euler flux
				TDstate state_center_2D = U[cellnum];
				TDstate tempflux;
				ODstate state_leftcell_1D, center_lr, center_bt, state_rightcell_1D, state_bottomcell_1D, state_topcell_1D;
				
				assign_edge_state(state_leftcell, state_rightcell, U, grid, cellnum, 0); // The left and right cell TDstates of the current cell
				assign_edge_state(state_bottomcell, state_topcell, U, grid, cellnum, 1); // The bottom and top cell TDstates of the current cell
				
// All this mess is because the riemann problem is 1D and we store 2D states.
// So we have to make new, temporary 1D states and fixes (all the doubles) to make the RP work.
				center_lr.rho = U[cellnum].rho;
				center_lr.rhou = U[cellnum].rhou;
				double center_lr_parallelvel = U[cellnum].rhov/U[cellnum].rho; 
				center_lr.E = U[cellnum].E;

				center_bt.rho = U[cellnum].rho;
				double center_bt_parallelvel = U[cellnum].rhou/U[cellnum].rho; 
				center_bt.rhou = U[cellnum].rhov;	
				center_bt.E = U[cellnum].E;

				state_leftcell_1D.rho = state_leftcell.rho;
				state_leftcell_1D.rhou = state_leftcell.rhou;
				double leftcell_parallelvel = state_leftcell.rhov/state_leftcell.rho;
				state_leftcell_1D.E = state_leftcell.E;

				state_rightcell_1D.rho = state_rightcell.rho; 
				state_rightcell_1D.rhou = state_rightcell.rhou;
				double rightcell_parallelvel = state_rightcell.rhov/state_rightcell.rho; 
				state_rightcell_1D.E = state_rightcell.E;

				state_bottomcell_1D.rho = state_bottomcell.rho;
				double bottomcell_parallelvel = state_bottomcell.rhou/state_bottomcell.rho;
				state_bottomcell_1D.rhou = state_bottomcell.rhov;
				state_bottomcell_1D.E = state_bottomcell.E;

				state_topcell_1D.rho = state_topcell.rho;
				double topcell_parallelvel = state_topcell.rhou/state_topcell.rho;
				state_topcell_1D.rhou = state_topcell.rhov;
				state_topcell_1D.E = state_topcell.E;


// Need to read in overall velocity magnitude to Exact Riemann Solver so we can get an accurate pressure reading!
// Reconstruct, from the state_[  ] ODstates, the TDstates corresponding assuming that the non-OD direction velocity is constant
// Then compute the flux from these new TDstates (4x), and update solution from t+1/2 to t+1 !!!
				ODstate state_leftedge_1D = Exact_Riemann_Solver(state_leftcell_1D, center_lr, leftcell_parallelvel, center_lr_parallelvel, thresh, gamma, debug);
				ODstate state_rightedge_1D = Exact_Riemann_Solver(center_lr, state_rightcell_1D, center_lr_parallelvel, rightcell_parallelvel, thresh, gamma, debug);
				ODstate state_bottomedge_1D = Exact_Riemann_Solver(state_bottomcell_1D, center_bt, bottomcell_parallelvel, center_bt_parallelvel, thresh, gamma, debug);
				ODstate state_topedge_1D = Exact_Riemann_Solver(center_bt, state_topcell_1D, center_bt_parallelvel, topcell_parallelvel, thresh, gamma, debug);


				TDstate state_leftedge_2D, state_rightedge_2D, state_bottomedge_2D, state_topedge_2D;


				state_leftedge_2D.rho = state_leftedge_1D.rho;
				state_leftedge_2D.rhou = state_leftedge_1D.rhou;
				state_leftedge_2D.rhov = state_center_2D.rhov;
				state_leftedge_2D.E = state_leftedge_1D.E;
				
				state_rightedge_2D.rho = state_rightedge_1D.rho;
				state_rightedge_2D.rhou = state_rightedge_1D.rhou;
				state_rightedge_2D.rhov = state_center_2D.rhov;
				state_rightedge_2D.E = state_rightedge_1D.E;

				state_bottomedge_2D.rho = state_bottomedge_1D.rho;
				state_bottomedge_2D.rhou = state_center_2D.rhou; 
				state_bottomedge_2D.rhov = state_bottomedge_1D.rhou;
				state_bottomedge_2D.E = state_bottomedge_1D.E;

				state_topedge_2D.rho = state_topedge_1D.rho;
				state_topedge_2D.rhou = state_center_2D.rhou; 
				state_topedge_2D.rhov = state_topedge_1D.rhou;
				state_topedge_2D.E = state_topedge_1D.E;

				compute_cell_flux(tempflux, state_leftedge_2D, 0, gamma);
				F[0] = tempflux;
				compute_cell_flux(tempflux, state_rightedge_2D, 0, gamma);
				F[1] = tempflux;
				compute_cell_flux(tempflux, state_bottomedge_2D, 1, gamma);
				G[0] = tempflux;
				compute_cell_flux(tempflux, state_topedge_2D, 1, gamma);
				G[1] = tempflux;
//Use all these fluxes to define updated state on each cell 
				compute_halfway_state(Up1[cellnum], Uph, F, G, dt, delta_x, delta_y); 
	
				if (debug) {
					std::cout << "Cell " << cellnum << " Updated State : " <<  Up1[cellnum].rho << " " << Up1[cellnum].rhou << " " << Up1[cellnum].rhov << " " << Up1[cellnum].E << '\n' << '\n';
				}
			} // end of if (!isedge(grid,cell)) 
		} // end of for(unsigned int cell = 0; cell < grid.size(); ++cell) (first one)

		// Now need to redefine the ghost cells to the correct values
		for(unsigned int cellnum = 0; cellnum < grid.size(); ++cellnum) {
			if (grid[cellnum].is_edgecell == 1) { // It is a ghost cell 
				int special_value = -1;		
				int num_edges = 0;		
				std::vector<int> edge_locations;
				for(int adjacentcell = 0; adjacentcell < 4; ++adjacentcell) {
					if (grid[cellnum].adjacent_cells[adjacentcell] == special_value) {
						edge_locations.push_back(adjacentcell);
						num_edges++;
					}
				}
		//		if (num_edges >= 2) {
	//				continue; // Sorry bro, we don't care about updating you!
//				} else if (num_edges == 1) {
					if (edge_locations[0] < 2) {
						edge_locations[0] = (edge_locations[0] + 2);
					} else {
						edge_locations[0] = (edge_locations[0] - 2);					
					}
				
					Up1[cellnum] = Up1[grid[cellnum].adjacent_cells[edge_locations[0]]];
					if (edge_locations[0] >= 2) {
						edge_locations[0] = (edge_locations[0] - 2);
					}
					assert((edge_locations[0] == 0) || (edge_locations[0] == 1));
					if (edge_locations[0] == 0) { // left-right
						if (Up1[cellnum].rhou == 0) {
							continue;
						} else {
							Up1[cellnum].rhou = -(Up1[cellnum].rhou);
						}
					} else if (edge_locations[0] == 1) { //up-down
						if (Up1[cellnum].rhou == 0) {
							continue;
						} else {
							Up1[cellnum].rhov = -(Up1[cellnum].rhov);
						}
					}
				//}
			} // end of if (isedge(grid,cell)) 
		} // end of for(unsigned int cell = 0; cell < grid.size(); ++cell) (second one)
		if (save_timesteps) {
			write_to_file(grid,Up1,output_filename);
		}
	} // end of for(double t = 0; t <= 2*dt; t++) 
return 0;
}
Exemplo n.º 17
0
int main(void)
    {
    double inmon, tmon;
    double mon, nxt, lst;
    double *iyr;
    double *nyr;
    double dyr, day;
    double ndyr;
    double *dy;
    double dmon[12];
    double dbmon;
    double yearday;
    int imon, inxt, ilst;
# ifndef WRTTS
    int itts; /* tracer time step counter */
# endif
    int nmnfirst;
#ifdef SEPFILES
    double smon, snxt;
    int ismon, isnxt, ihnxt;
#endif

#ifndef WRTTS
    size_t nrec = 0;
#endif
    int err, i, j, k;
    int cmon;
    int nmn;
    double frac;
    static int m;
#ifndef WRTTS
    int varmap[NOVARS];

    FILE *fn;
    char output_filename[200];
#endif
    char run_name[200];
    char restart_filename[200];
    struct vardesc var_out[NOVARS];
#ifndef WRTTS
    struct varcdfinfo varinfo[NOVARS];
    int nvar = 0, cdfid, timeid[2];
#endif

    extern int flags[NOVARS];
    extern int rflags[NOVARS];

    //BX-a  for testing only
    int status;
    char message[144];
    //BX-e

    //BX  allocate tracer fields
    err = alloc_arrays();
    if (err)
	printf("Error allocating arrays.\n");

    err = alloc_trac();
    if (err)
	printf("Error allocating tracer field.\n");

    iyr = malloc(sizeof(double));
    nyr = malloc(sizeof(double));
    dy = malloc(sizeof(double));

    mlen[0] = 31; /* January      */
    mlen[1] = 28; /* February     */
    mlen[2] = 31; /* March        */
    mlen[3] = 30; /* April        */
    mlen[4] = 31; /* May          */
    mlen[5] = 30; /* June         */
    mlen[6] = 31; /* July         */
    mlen[7] = 31; /* August       */
    mlen[8] = 30; /* September    */
    mlen[9] = 31; /* October      */
    mlen[10] = 30; /* November     */
    mlen[11] = 31; /* December     */

    dmon[0] = 0.0;

    for (i = 1; i <= 11; i++)
	{
	dmon[i] = dmon[i - 1] + mlen[i - 1];
	}

    /*----------------------------------*
     *
     *     get user input
     *
     *----------------------------------*/

    {
    char line[100];
    int scan_count, done = 1;

    printf("Enter directory to use to read.\n");
    fgets(directory, sizeof(directory), stdin);

    directory[strlen(directory) - 1] = '\0';
    k = strlen(directory);
    if (k > 0)
	if (directory[k - 1] != '/')
	    {
	    directory[k] = '/';
	    directory[k + 1] = '\0';
	    printf("Using directory %s first.\n", directory);
	    }

    strcat(directory, fname);
    strcpy(fname, directory);
    printf("file path = %s\n", fname);

    while (done)
	{

	printf(
		"\nEnter the starting month and the total months to integrate.\n");

	fgets(line, sizeof(line), stdin);
	line[strlen(line) - 1] = '\0';
	scan_count = sscanf(line, "%lg, %lg,", &inmon, &tmon);
	if (scan_count == 2)
	    {
	    if (inmon < 0 || tmon < 0)
		printf("Negative values not allowed\n");
	    else
		done = 0;
	    }
	else
	    printf("Incorrect number of values, %d, read.\n", scan_count);
	}

    printf("\ninitial month = %g \n", inmon);
    printf("final month = %g \n", inmon + tmon - 1);
    printf("total months = %g \n\n", tmon);

    /*-----------------------------------
     *
     *     set output print flags to 0
     *
     *     added restart flags as a restart bug fix until
     *     memory restriction problem is solved 31OCT07 BX
     *
     *----------------------------------*/

    for (i = 0; i <= NOVARS - 1; i++)
	flags[i] = 0;
    for (i = 0; i <= NOVARS - 1; i++)
	rflags[i] = 0;

    flags[1] = 0;
    flags[2] = 0; /* u,v */
    rflags[1] = 0;
    rflags[2] = 0; /* u,v */
    flags[0] = 0;
    flags[3] = 0; /* D, h */
    rflags[0] = 0;
    rflags[3] = 0; /* D, h */
    flags[4] = 0;
    flags[5] = 0; /* uhtm, vhtm */
    rflags[4] = 0;
    rflags[5] = 0; /* uhtm, vhtm */
    flags[6] = 0;
    flags[7] = 0;
    flags[8] = 0; /* ea, eb, eaml */
    flags[18] = 0; /* ML potential density */
    rflags[18] = 0; /* ML potential density */
#ifdef AGE
    flags[9] = 1;
    rflags[9] = 1; /* ideal age tracer*/
#endif

    printf("Enter base name for output\n");

    fgets(run_name, sizeof(run_name), stdin);
    run_name[strlen(run_name) - 1] = '\0';
    sprintf(output_filename, "%s.%04g.nc", run_name, inmon + tmon - 1);
    printf("Create NetCDF output file '%s'.\n", output_filename);



    } // end of block "get user input"

    //DT
    lastsave = -1;
    //DT

    /*-----------------------------------
     *
     *     allocate and initialize fields
     *
     *----------------------------------*/

    read_grid();
    printf("Done reading grid or metric file.\n");

    set_metrics();
    printf("Done setting metrics.\n");

    /* Copy the variable descriptions to a list of the actual output variables. */
    for (i = 0; i < NOVARS; i++)
	if (flags[i] > 0)
	    {
	    var_out[nvar] = vars[i];
	    varmap[i] = nvar;
	    nvar++;
	    }
    // force float precision output with last argument
    printf("Making NETCDF %s file\n", output_filename);
    create_file(output_filename, NETCDF_FILE, var_out, nvar, &fn, &cdfid,
	    timeid, varinfo, 1);
    // don't force
    // create_file(output_filename, NETCDF_FILE, var_out, nvar, &fn, &cdfid, timeid, varinfo, 0);
    printf("Closing file \n");
    close_file(&cdfid, &fn);

    /* Allocate the memory for the fields to be calculated.		*/
    alloc_fields();

    /* initialize tracer pointers					*/

    for (m = 0; m < NOVARS; m++)
	{
	if (flags[m])
	    for (k = 0; k < varsize[m]; k++)
		var[m][k] = 0.0;
	}

    /********** set means to zero                                   */
    /*  2d variables */
    if (flags[8])
	set_fix_darray2d_zero(mn_eaml);


    /*  3d variables */
    if (flags[1])
	set_darray3d_zero(mn_u, NZ, NXMEM, NYMEM);
    if (flags[2])
	set_darray3d_zero(mn_v, NZ, NXMEM, NYMEM);
    if (flags[3])
	set_darray3d_zero(mn_h, NZ, NXMEM, NYMEM);
    if (flags[4])
	set_darray3d_zero(mn_uhtm, NZ, NXMEM, NYMEM);
    if (flags[5])
	set_darray3d_zero(mn_vhtm, NZ, NXMEM, NYMEM);
    if (flags[6])
	set_darray3d_zero(mn_ea, NZ, NXMEM, NYMEM);
    if (flags[7])
	set_darray3d_zero(mn_eb, NZ, NXMEM, NYMEM);
#ifdef AGE
    if (flags[9])
	set_darray3d_zero(mn_age, NZ, NXMEM, NYMEM);

#endif
    printf("Reading bathymetry, D.\n");

    // initialize D to be all ocean first

    for (i = 0; i <= NXMEM - 1; i++)
	{
	for (j = 0; j <= NYMEM - 1; j++)
	    {
	    D[i][j] = MINIMUM_DEPTH;
	    }
	}
#ifndef USE_CALC_H
    printf("calling read_D\n");
    read_D();

    for (i = 0; i <= NXMEM - 1; i++)
	for (j = 0; j <= NYMEM - 1; j++)
	    if (D[i][j] < 10.0)
		D[i][j] = MINIMUM_DEPTH;
#endif

    read_grid();
    set_metrics();

    dyr = inmon / 12;
    smon = (double) ((int) inmon % NMONTHS);
    mon = 12 * modf(dyr, iyr);

    printf("\n initial mon = %g - %g - %g \n\n", inmon, smon, mon);


    imon = (int) (mon + 0.00001);
    /* Begin edit DT */
    int iyear = floor((inmon + imon) / 12);
    theyear = iyear;
#ifdef RESTART
    theyear++;
    iyear++;
#endif
    /*  End edit DT  */
    inxt = imon + 1;

    ismon = (int) (smon + 0.00001) % NMONTHS;

    isnxt = (ismon+1) % NMONTHS;
    ihnxt = (ismon+2) % NMONTHS;

    dbmon = (double) inmon;
    lst = 12 * modf((dbmon - 1 + 12) / 12, iyr);
    ilst = (int) (lst + 0.00001);

    // ashao: Read in next month's isopycnal thickness fields
    // (will be copied at the beginning of the integration)
    // Done this way so that if hindcasts are used the physical fields switch smoothly
    // to/from climatological fields
    //BX  files are not in regular order (uvw are midmonth and h starts with last month)

        currtime = BEGYEAR;
    if (usehindcast) {
        // Check to see if simulation started within the hindcast years
        if ( (currtime >= BEGHIND) || (currtime < (ENDHIND+1) ) ) {
        	hindindex=inmon;
        	read_h(ismon,hend,"hind");
        }
    }
    else {
    	read_h(ismon, hend,"clim");
    }
    // for files in regular order (h before uvw) use code here
    //BX
    // read_uvw(imon,1);
    //BX
    // read_h(imon,inxt);



#ifdef USE_CALC_H
    z_sum(h, D);
#endif
    printf("\nSetting up and initializing\n");

#ifdef RESTART
    initialize(inmon,run_name);
#else
    initialize(imon);
#endif
    nmn = 0;

    //HF the next line should be in init.h (and be optional!)
#undef OUTPUT_IC
#ifdef OUTPUT_IC
    /*-----------------------------------
     *
     *     write tracer initial conditions
     *
     *----------------------------------*/

    printf("Writing initial condition variables out to netCDF\n\n",cmon);

    //  open netcdf file for each writing
    status = nc_open(output_filename, NC_WRITE, &cdfid);
    if (status != NC_NOERR)
	{
	strcpy(message,"Opening file"); strcat(message,output_filename);
	handle_error(message,status);
	}

    err = write_time(cdfid,fn,timeid[0],nrec, dy);
    if (err == -1) printf("Error writing day.\n");

    if (flags[3])
	{
	for (k=0;k<NZ;k++)
	    for (i=0;i<NXMEM;i++)
		for (j=0;j<NYMEM;j++)
		    mn_h[k][i][j] += h[k][i][j];
	}

#ifdef AGE
    if (flags[9]) add_darray3d(mn_age, age, NZ, NXMEM, NYMEM);
    /*{
     for (k=0;k<NZ;k++)
     for (i=0;i<NXMEM;i++)
     for (j=0;j<NYMEM;j++)
     mn_age[k][i][j] += age[k][i][j];
     }*/
#endif /* AGE */


    for (m=0;m<NOVARS;m++) if (flags[m])
	{
	err = write_field(cdfid, fn, vars[m], varinfo[varmap[m]],
		nrec,var[m]);
	if (err == -1) printf("Error writing %s.\n",vars[m].name);
	}
    //  close file after each writing
    close_file(&cdfid, &fn);
    printf("netcdf record = %d\n",nrec++);
#endif /* OUTPUT_IC */




    /*-------------------------------------------------------------------*
     *
     *     begin integration loop
     *
     *-------------------------------------------------------------------*/

    mon = 0.0; /* reiniti */
    nmnfirst = 1;


    for (cmon = inmon; cmon < inmon + tmon; cmon++)
	{
	nmn++;

	dyr = cmon / 12.0;
	ndyr = (cmon + 1) / 12.0;

	dbmon = (double) cmon;
	lst = 12 * modf((dbmon - 1 + 12) / 12, iyr);
	ilst = (int) (lst + 0.00001);
	printf("double-mon=%g,lastmon=%g,ilst=%i\n", dbmon, lst, ilst);


	smon = (double) ((int) cmon % NMONTHS);
	snxt = (double) ((int) (cmon + 1) % NMONTHS);

	mon = 12.0 * modf(dyr, iyr);
	nxt = 12.0 * modf(ndyr, nyr);

	printf("the current month is %i-%g-%g \n", cmon, smon, mon);
	printf("the current year is %g \n", *iyr);

	imon = (int) (mon + 0.00001);
	inxt = (int) (nxt + 0.00001);

	ismon = (int) (smon + 0.00001);
	isnxt = (int) (snxt + 0.00001);

	yearday = 0;
	for (i=0;i<=imon;i++) yearday += dmon[imon];
	currtime = *iyr + BEGYEAR + yearday/365.0;

	day = (*iyr) * 365.0 + dmon[imon];
	*dy = currtime;

	printf("the current day is -%g- \n", *dy);
	printf("the current ismon/smon is -%i-%g- \n", ismon, smon);
	printf("the next smonth/mean index: -%i- \n", isnxt);

	dt = ((double) mlen[imon]);
	dt = dt * 86400 / (double) NTSTEP;


	for (itts = 1; itts <= NTSTEP; itts++)
	    {
	    printf("\nSub time step number= %i \n", itts);
	    /*-----------------------------------
	     *
	     *     get physical fields and bc's
	     *
	     *----------------------------------*/

	    printf("Month %d timestamp Start: %4.2f End: %4.2f\n",cmon,currtime,currtime+dt/31536000);
	    currtime += dt / 31536000; //ashao: advance currenttime
	    copy_2fix_darray3d(hstart,hend,NZ,NXMEM,NYMEM);
	    copy_2fix_darray3d(h,hstart,NZ,NXMEM,NYMEM);
	    if (usehindcast) {
	        if ( ( cmon >= starthindindex) && ( hindindex <= (numhindmonths-1) )) {
			
			printf("Reading in UVW from hindcast\n");
	        	read_uvw(hindindex,"hind");
		        read_h(hindindex,hend,"hind");
	        	hindindex++;
	        }
		else {
		
		printf("Reading in UVW from climatology\n");
	    	read_uvw(isnxt,"clim");
	    	read_h(isnxt, hend,"clim");
		}
	    }
	    else {
		printf("Reading in UVW from climatology\n");
	    	read_uvw(isnxt,"clim");
	    	read_h(isnxt, hend,"clim");
	    }
	    printf("Month- hstart:%d hend:%d\n",ismon,isnxt);

	    /*-----------------------------------
	     *
	     *     integrate 1 time step
	     *
	     *----------------------------------*/

	    printf("step fields - day = %g\n\n", day);
	    step_fields(iyear, itts, imon, iterno); // modified ashao


	    /*-------------------------------------------------------------------*
	     *
	     *     end integration loop
	     *
	     *-------------------------------------------------------------------*/

	    /*-----------------------------------
	     *
	     *     calculate tracer averages
	     *
	     *----------------------------------*/

	    printf("calculate tracer averages\n");

	    if (flags[8])
		add_fix_darray2d(mn_eaml, eaml);
	    if (flags[1])
		add_darray3d(mn_u, u, NZ, NXMEM, NYMEM);
	    if (flags[2])
		add_darray3d(mn_v, v, NZ, NXMEM, NYMEM);
	    if (flags[3])
		{
		for (k = 0; k < NZ; k++)
		    for (i = 0; i < NXMEM; i++)
			for (j = 0; j < NYMEM; j++)
			    {
			    mn_h[k][i][j] += h[k][i][j];
			    }
		}
	    if (flags[4])
		add_darray3d(mn_uhtm, uhtm, NZ, NXMEM, NYMEM);
	    if (flags[5])
		add_darray3d(mn_vhtm, vhtm, NZ, NXMEM, NYMEM);
	    if (flags[6])
		add_darray3d(mn_ea, ea, NZ, NXMEM, NYMEM);
	    if (flags[7])
		add_darray3d(mn_eb, eb, NZ, NXMEM, NYMEM);
#ifdef AGE
	    //DT
	    //    if (flags[9]) add_darray3d(mn_age, age, NZ, NXMEM, NYMEM);
	    if (flags[9])
	    {
	    	for (k = 0; k < NZ; k++)
	    	{
	    		for (i = 0; i < NXMEM; i++)
	    		{
	    			for (j = 0; j < NYMEM; j++)
	    			{
	    				if (age[k][i][j] > 0.0)
	    				{
	    					{
	    						mn_age[k][i][j] += age[k][i][j];
	    					}
	    				}}}}}

	    				//DT
#endif
	    if (flags[18])
		{
		for (k = 0; k < 2; k++)
		    for (i = 0; i < NXMEM; i++)
			for (j = 0; j < NYMEM; j++)
			    mn_rml[k][i][j] += rml[k][i][j];
		}


	    /* calculate the mean */

	    if (nmn == WRINT && itts == 1)
		{
		printf("***nmn= %i, itts= %i, nmnfirst= %i\n", nmn, itts,
			nmnfirst);
		frac = 1.0 / ((double) nmn * (double) NTSTEP);

		if (flags[8])
		    mult_fix_darray2d(mn_eaml, frac);
		if (flags[1])
		    mult_darray3d(mn_u, NZ, NXMEM, NYMEM, frac);
		if (flags[2])
		    mult_darray3d(mn_v, NZ, NXMEM, NYMEM, frac);
		if (flags[3])
		    mult_darray3d(mn_h, NZ, NXMEM, NYMEM, frac);
		if (flags[4])
		    mult_darray3d(mn_uhtm, NZ, NXMEM, NYMEM, frac);
		if (flags[5])
		    mult_darray3d(mn_vhtm, NZ, NXMEM, NYMEM, frac);
		if (flags[6])
		    mult_darray3d(mn_ea, NZ, NXMEM, NYMEM, frac);
		if (flags[7])
		    mult_darray3d(mn_eb, NZ, NXMEM, NYMEM, frac);
#ifdef AGE
		if (flags[9])
		    mult_darray3d(mn_age, NZ, NXMEM, NYMEM, frac);
#endif

		if (flags[18])
		    mult_darray3d_mv(mn_rml, 2, NXMEM, NYMEM, frac, D, misval);

		/*-----------------------------------
		 *
		 *     write tracer averages and reset to 0
		 *
		 *----------------------------------*/
		printf("Writing month %i variables out to netCDF\n\n", cmon);

		status = nc_open(output_filename, NC_WRITE, &cdfid);
		if (status != NC_NOERR)
		    {
		    strcpy(message, "Opening file");
		    strcat(message, output_filename);
		    handle_error(message, status);
		    }

		err = write_time(cdfid, fn, timeid[0], nrec, dy);
		if (err == -1)
		    printf("Error writing day.\n");

		for (m = 0; m < NOVARS; m++)
		    if (flags[m]==1)
			{
			printf("m = %d\n",m);
			err = write_field(cdfid, fn, vars[m],
				varinfo[varmap[m]], nrec, var[m]);
			if (err == -1)
			    printf("Error writing %s.\n", vars[m].name);
			}
		close_file(&cdfid, &fn);

		/*    reset all means to zero */
		nmn = 0;
		if (flags[8])
		    set_fix_darray2d_zero(mn_eaml);
		if (flags[1])
		    set_darray3d_zero(mn_u, NZ, NXMEM, NYMEM);
		if (flags[2])
		    set_darray3d_zero(mn_v, NZ, NXMEM, NYMEM);
		if (flags[3])
		    set_darray3d_zero(mn_h, NZ, NXMEM, NYMEM);
		if (flags[4])
		    set_darray3d_zero(mn_uhtm, NZ, NXMEM, NYMEM);
		if (flags[5])
		    set_darray3d_zero(mn_vhtm, NZ, NXMEM, NYMEM);
		if (flags[6])
		    set_darray3d_zero(mn_ea, NZ, NXMEM, NYMEM);
		if (flags[7])
		    set_darray3d_zero(mn_eb, NZ, NXMEM, NYMEM);
		if (flags[18])
		    set_darray3d_zero(mn_rml, 2, NXMEM, NYMEM);
#ifdef AGE
		if (flags[9])
		    set_darray3d_zero(mn_age, NZ, NXMEM, NYMEM);

#endif
		// begin ashao
		// end ashao

		printf("netcdf record = %d\n", nrec + 1);
		nrec++;

		} /*  end if nmn==WRITEINT */

	    /*-------------------------------------------------------------------*
	     *
	     *     end integration loop
	     *
	     *-------------------------------------------------------------------*/

	    } /* end itts loop over NTSTEP */
	} /* end while */

    //BX-a
    /*-----------------------------------
     *
     *     write restart file
     *
     *----------------------------------*/

    //   First write the up-to-date tracer values to the mean fields.
    //   In order to save memory the instantaneous values for the
    //   restart will be written on mean fields in the restart file.

    printf("start of array copying\n");
    //HF #ifdef SMOOTH_REST
    copy_fix_darray3d(mn_h, h, NZ, NXMEM, NYMEM);
    //HF #endif
#ifdef AGE
    copy_darray3d(mn_age, age, NZ, NXMEM, NYMEM);
#endif
    for (k = 0; k < NZ; k++)
	{
	for (i = 0; i < NXMEM; i++)
	    {
	    for (j = 0; j < NYMEM; j++)
		{
		} /* for j loop */
	    } /* for i loop */
	} /* for k loop */

    //  Second, create restart file name and open file

    sprintf(restart_filename, "restart.%s.%04d.nc", run_name, cmon);
    printf("Writing NetCDF restart file '%s'.\n\n", restart_filename);

    /* Copy the variable descriptions to a list of the actual restart variables. */
    nvar = 0;
    for (i = 0; i < NOVARS; i++)
	if (rflags[i] > 0)
	    {
	    var_out[nvar] = vars[i];
	    varmap[i] = nvar;
	    nvar++;
	    }

    // do NOT force float precision output with last argument
    create_file(restart_filename, NETCDF_FILE, var_out, nvar, &fn, &cdfid,
	    timeid, varinfo, 0);

    for (m = 0; m < NOVARS; m++)
	if (rflags[m])
	    {
	    err = write_field(cdfid, &fn, vars[m], varinfo[varmap[m]], 0,
		    var[m]);
	    if (err == -1)
		printf("Error writing %s.\n", vars[m].name);
	    }

    close_file(&cdfid, &fn);

    printf("\n programme termine normallement. \n");
    return (0);
    }
int main() {

// Define Variables
	std::string parameter_filename = "solver_parms.txt";
	std::string input_filename = "5x5square2.bkcfd";
	std::vector<double> parameters;
	std::vector<double> Fiph, Fimh, Giph, Gimh;
	double CFL, tmax, delta_x, delta_y, min_delta_x, min_delta_y, min_delta;
	TDstate state_minus, state_plus, slope_minus, slope_plus, limiter_value;
	std::vector<TDstate> F (2);
	std::vector<TDstate> G (2);

//	double thresh = 0.00001; // 1E-5 tolerance for riemann solver - velocity
	double gamma = 1.4;

// 1 = harmonic mean for slopes, 2 = ...
	int limiter_number = 1; 

	std::vector<cell> grid;

	// Read parameters from input file defined by filename string
	parameters = read_parameters(parameter_filename);
//	CFL = parameters.at(0);	
//	tmax = parameters.at(1);
	

// Read initial file defined from Matlab with cell edges and connections
// Read the initial condition file from MATLAB with [rho rho*u rho*v e] defined for each cell
	read_grid(input_filename, grid, gamma);
	
	std::vector<TDstate> Uph (grid.size());	

	min_delta_x = gridmin(grid, 'x');
	min_delta_y = gridmin(grid, 'y');
	min_delta = std::min(min_delta_x,min_delta_y);
	

/*		std::cout << "printing now..." << '\n';
	for(auto input: grid) {
		std::cout << input.cellnumber << '\n';
		std::cout << input.cornerlocs_x[0] << ' ';
		std::cout << input.cornerlocs_x[1] << ' ';
		std::cout << input.cornerlocs_x[2] << ' ';
		std::cout << input.cornerlocs_x[3] << '\n';
		std::cout << input.cornerlocs_y[0] << ' ';
		std::cout << input.cornerlocs_y[1] << ' ';
		std::cout << input.cornerlocs_y[2] << ' ';
		std::cout << input.cornerlocs_y[3] << '\n';
		std::cout << input.adjacent_cells[0] << ' ';
		std::cout << input.adjacent_cells[1] << ' ';
		std::cout << input.adjacent_cells[2] << ' ';
		std::cout << input.adjacent_cells[3] << '\n';
		std::cout << input.state.rho << ' ';
		std::cout << input.state.rhou << ' ';
		std::cout << input.state.rhov << ' ';
		std::cout << input.state.E << '\n' << '\n';
	} 
*/

// Start calculation in for loop going to final time

//	for (double t = 0, t <= tmax; t++) 
	double max_wavespeed = 0; 

// Go through each cell, calculate fluxes, update to new piecewise linear state
	for (unsigned int cellnum = 0; cellnum < grid.size(); ++cellnum) { // For each cell
		if (!isedge(grid,cellnum)) {
			delta_x = (vectormax(grid[cellnum].cornerlocs_x) - vectormin(grid[cellnum].cornerlocs_x));
			delta_y = (vectormax(grid[cellnum].cornerlocs_y) - vectormin(grid[cellnum].cornerlocs_y));

			// Calculate the limited flux of each conserved quantity for initial t -> t+1/2 update
			for (int direction = 0; direction < 2; ++direction) { // For the left/right direction and up/down direction
				// Assign the bottom/left and the top/right states for each cell
				assign_edge_state(state_minus, state_plus, grid, cellnum, direction);	
								

				// Calculate the flux of each conserved variable, in each direction, on each face, of that cell.
				// Flux needs to be calculated by first finding the limiter (direction-dependent), then using that limiter to calculate the directional flux, then using the two directional fluxes to update from u_t to u_t+1/2	
				
				compute_slope(slope_minus, slope_plus, grid, cellnum, direction, state_minus, state_plus, delta_x, delta_y);
				compute_limiter(limiter_value, slope_minus, slope_plus, limiter_number);

				if (direction == 0) { // Compute F, x-fluxes
					compute_limited_flux(F, limiter_value, min_delta, CFL, grid[cellnum].state, slope_plus, direction, gamma);
//					std::cout << "rho limiter x: " << limiter_value.rho << '\n';
				} else { // Compute G, y-fluxes
//					std::cout << "rho limiter y: " << limiter_value.rho << '\n';
					compute_limited_flux(G, limiter_value, min_delta, CFL, grid[cellnum].state, slope_plus, direction, gamma);
				}
			} // end of for (int direction = 0; direction < 2; ++direction)
//			std::cout << "F flux: " << F[0].rho << " " << F[1].rho << ", G flux: " << G[0].rho << " " << G[1].rho << '\n';	
			fluxmax(max_wavespeed, F, G, grid[cellnum].state);
		} // end of if (!isedge(grid,cell)) 	


		// Compute the max 
		// Now, use the fluxes calculated above to assign a new state, Uph
		compute_halfway_state(Uph, F, G, CFL);


// -----------------------------
// Need to check values of flux to see if they are giving accurate results!

//
// Go through each edge, calculate flux, save
//		for (int edge = 1, edge <= numedges, ++edge) 
//
// Solve riemann problem on edge for euler flux
		ODstate left;
		ODstate right;
		left.rho = 1.0; //rho
		left.rhou = 300; //rho*u or rho*v
		left.E = 100000/0.4 - pow(left.rhou,2)/(left.rho*2); //E
		right.rho = 1;
		right.rhou = 0;
		right.E = 100000/0.4 - pow(right.rhou,2)/(right.rho*2);				

/*		ODstate test_state = Exact_Riemann_Solver(left, right, thresh, gamma);

		std::cout << '\n' << "State on x=0 is:" << '\n';
		std::cout << test_state.rho << '\n';
		std::cout << test_state.rhou << '\n';
		std::cout << test_state.E << '\n';
		std::cout << test_state.pressure << '\n';
*/


//Use all these fluxes to define updated state on each cell 

//Option to save at each timestep

	} // end of for(unsigned int cell = 0; cell < grid.size(); ++cell)
return 0;
}
Exemplo n.º 19
0
int main(int argc, char *argv[]) {
BBoardPtr board=NULL;
char grid[MAX_ROWS][MAX_COLS];
int cmd;
int nrows, ncols, r, c, score;
int done;



    if(argc == 1) 
	board = bb_create(30, 30);
    else if(argc==2){
	if(!read_grid(grid, argv[1], &nrows, &ncols)) {
	    fprintf(stderr, "failed to read file %s\n", argv[1]);
	    fprintf(stderr, "Goodbye\n");
	    return 0;
	}
	printf("Successfully read input file %s\n", argv[1]);
	scrub_grid(grid, nrows, ncols);
	board = bb_create_from_mtx(grid, nrows, ncols);
     }
    else {
        fprintf(stderr, "usage error:  zero or 1 cmd-line arg\n");
        fprintf(stderr, "Goodbye\n");
	return 0;
    }
    // if we get here
    if(board != NULL) {

	if(!bb_is_compact(board)) {
		fprintf(stderr, "ERR:  board not compact\n");
		bb_display(board);
		fprintf(stderr, "Goodbye\n");
		bb_destroy(board);
		return 1;
	}
	done = 0;
	while(!done) {
	    bb_display(board);
	    score = bb_score(board);
	    printf("SCORE: %i\n", score);
	    cmd = read_cmd(&r, &c);
	    
	    switch(cmd) {
		case POP:  bb_pop(board, r, c); 
			   make_compact(board);
			   break;
		case QUIT: // bb_destroy(board);
			   done = 1;
			   break;
		case UNDO: if(!bb_undo(board)) {
				printf("  undo failed\n");
			   }
			   break;
		case UNKNOWN:
			   printf("  what?  try again\n");
			   break;
	
	    }
	}
	printf("FINAL SCORE:  %i\n", bb_score(board));
	bb_destroy(board);
	printf("  Goodbye\n");
    }  // end if board != NULL
}
Exemplo n.º 20
0
int
main(int argc, char *argv[])
{
    char input[MAX_FILENAME_SIZE];
    int c;
    int iterations = 1;
    int generate = 0;
    struct Grid *grid;
    struct Grid *tmp_grid;

    if (argc < 2) {
        help();
        return 0;
    }

    while ((c = getopt(argc, argv, "?hv:n:i:g")) != -1) {
        switch (c) {
            case 'h':
            case 'v':
                help();
                return 0;
            case 'n':
                iterations = atoi((char *) getopt);
                break;
            case 'i':
                strncpy(input, optarg, MAX_FILENAME_SIZE);
                break;
            case 'g':
                generate = 1;
                break;
            default:
                help();
                return 0;
        }
    } 

    if (argc != optind) {
        help();
        return 0;
    }

    grid = allocate_grid();
    tmp_grid = allocate_grid();
    if (!grid || !tmp_grid) {
        printf("error: out of memory\n");
        return -1;
    }
    if (generate) {
        generate_grid(grid);
    } else {
        read_grid(input, grid); 
    }
    for (c = 0; c < iterations; c++) {
        mean_filter(grid, tmp_grid);
        struct Grid *tmp = grid;
        grid = tmp_grid;
        tmp_grid = tmp;
    }
    write_grid(grid);
    cleanup_grid(grid);
    cleanup_grid(tmp_grid);

    return 0;
}
Exemplo n.º 21
0
int create_grid(char *infile, char *outfile, int gridsize, char *format, char *layer) {

	OGRSFDriverH out_driver;
	OGRDataSourceH out_ds;
	OGRLayerH out_layer;
	OGRFieldDefnH field;
	OGRFeatureH feat;
	OGRGeometryH geom;
	morph *mgrid;
	int xstep, ystep, step;
	double topleftx, toplefty, weres, nsres, rot1, rot2;
	int i,j, fid, row, col;
	
	
	OGRRegisterAll();
	
	// Read the morph grid file.
	mgrid = read_grid(infile);
	if (mgrid == NULL) {
		fprintf(stderr, "Error. Unable to read input morph file '%s'.\n", infile);
		exit(1);
	}
	
	// Create the ouptut layer.
	out_driver = OGRGetDriverByName(format);
	if (out_driver == NULL) {
		fprintf(stderr, "Error. Driver for format '%s' not available.\n", format);
		exit(1);
	}
	out_ds = OGR_Dr_CreateDataSource(out_driver, outfile, NULL);
	if (out_ds == NULL) {
		fprintf(stderr, "Error. Unable to create output data source.\n");
		exit(1);
	}
	out_layer = OGR_DS_CreateLayer(out_ds, layer, NULL, wkbLineString, NULL);
	if (out_layer == NULL) {
		fprintf(stderr, "Error. Unable to create output layer.\n");
		exit(1);
	}
	
	// Add the attributes to the new layer.
	field = OGR_Fld_Create("ID", OFTInteger);
	OGR_Fld_SetWidth(field, 11);
	if (OGR_L_CreateField(out_layer, field, TRUE) != OGRERR_NONE) {
		fprintf(stderr, "Error. Creating ID attribute failed.\n");
		exit(1);
	}
	OGR_Fld_Destroy(field);
	
	field = OGR_Fld_Create("ROW", OFTInteger);
	OGR_Fld_SetWidth(field, 6);
	if (OGR_L_CreateField(out_layer, field, TRUE) != OGRERR_NONE) {
		fprintf(stderr, "Error. Creating ROW attribute failed.\n");
		exit(1);
	}
	OGR_Fld_Destroy(field);
	
	field = OGR_Fld_Create("COL", OFTInteger);
	OGR_Fld_SetWidth(field, 6);
	if (OGR_L_CreateField(out_layer, field, TRUE) != OGRERR_NONE) {
		fprintf(stderr, "Error. Creating COL attribute failed.\n");
		exit(1);
	}
	OGR_Fld_Destroy(field);
	
	// Compute the step size.
	xstep = mgrid->xsize / gridsize;
	if (xstep < 1) {
		xstep = 1;
	}
	if (xstep > (mgrid->xsize / 2)) {
		xstep = mgrid->xsize / 2;
	}
	ystep = mgrid->ysize / gridsize;
	if (ystep < 1) {
		ystep = 1;
	}
	if (ystep > (mgrid->ysize / 2)) {
		ystep = mgrid->ysize / 2;
	}
	if (xstep < ystep) {
		step = ystep;
	} else {
		step = xstep;
	}
	
	// Read the georeference
	topleftx = mgrid->georef[0];
	weres = mgrid->georef[1];
	rot1 = mgrid->georef[2];
	toplefty = mgrid->georef[3];
	rot2 = mgrid->georef[4];
	nsres = mgrid->georef[5];
	
	// Write all horizontal lines.
	fid = 1;
	row = 1;
	for (j = 0; j < mgrid->ysize; j += step) {
		// Create a new Feature with the projected coordinates.
		feat = OGR_F_Create(OGR_L_GetLayerDefn(out_layer));
		OGR_F_SetFieldInteger(feat, OGR_F_GetFieldIndex(feat, "ID"), fid);
		OGR_F_SetFieldInteger(feat, OGR_F_GetFieldIndex(feat, "ROW"), row);
		OGR_F_SetFieldInteger(feat, OGR_F_GetFieldIndex(feat, "COL"), 0);

		// Create a new geometry object.
		geom = OGR_G_CreateGeometry(wkbLineString);
		for (i = 0; i < mgrid->xsize; i++) {
			OGR_G_SetPoint_2D(
							  geom, 
							  i, 
							  topleftx + mgrid->x[i][j]*weres + mgrid->y[i][j]*rot1, 
							  toplefty + mgrid->x[i][j]*rot2 + mgrid->y[i][j]*nsres);
		}
		OGR_F_SetGeometry(feat, geom);
		OGR_G_DestroyGeometry(geom);
		
		// Write the feature to the output vector layer.
		if (OGR_L_CreateFeature(out_layer, feat) != OGRERR_NONE) {
			fprintf(stderr, "Error. Unable to create new feature.\n");
			exit(1);
		}
		OGR_F_Destroy(feat);
		
		row++;
		fid++;
	}
	
	// Write all vertical lines.
	col = 1;
	for (i = 0; i < mgrid->xsize; i += step) {
		// Create a new Feature with the projected coordinates.
		feat = OGR_F_Create(OGR_L_GetLayerDefn(out_layer));
		OGR_F_SetFieldInteger(feat, OGR_F_GetFieldIndex(feat, "ID"), fid);
		OGR_F_SetFieldInteger(feat, OGR_F_GetFieldIndex(feat, "ROW"), 0);
		OGR_F_SetFieldInteger(feat, OGR_F_GetFieldIndex(feat, "COL"), col);
		
		// Create a new geometry object.
		geom = OGR_G_CreateGeometry(wkbLineString);
		for (j = 0; j < mgrid->ysize; j++) {
			OGR_G_SetPoint_2D(
							  geom, 
							  j, 
							  topleftx + mgrid->x[i][j]*weres + mgrid->y[i][j]*rot1, 
							  toplefty + mgrid->x[i][j]*rot2 + mgrid->y[i][j]*nsres);
		}
		OGR_F_SetGeometry(feat, geom);
		OGR_G_DestroyGeometry(geom);
		
		// Write the feature to the output vector layer.
		if (OGR_L_CreateFeature(out_layer, feat) != OGRERR_NONE) {
			fprintf(stderr, "Error. Unable to create new feature.\n");
			exit(1);
		}
		OGR_F_Destroy(feat);
		
		col++;
		fid++;
	}

	// Close the datasources and free the memory.
	OGR_DS_Destroy(out_ds);
	free_morph(mgrid);
	
	return 0;
}
Exemplo n.º 22
0
int main( int argc, char *argv[] )
{
   int infile;
   int id;
   int compressmode, i;

   if (argc==1) {
      printf("Usage:\n");
      printf("   comp_to_v5d compfile outfile.v5d\n");
      printf("Options:\n");
      printf("   -compress N\n");
      printf("      Specifies compress to N bytes per grid point where\n");
      printf("      N = 1, 2 or 4.\n");
      exit(0);
   }

   compressmode = 1; /* default */

   for (i=2;i<argc;i++) {
      if (strcmp(argv[i],"-compress")==0 && i+1<argc) {
         compressmode = atoi( argv[i+1] );
         i++;
      }
   }

   infile = open( argv[1], O_RDONLY );
   if (infile<0) {
      printf("Error:  couldn't open %s for reading\n", argv[1] );
      exit(0);
   }

   id = read_comp_header( infile );
   if (id) {
      for (i=0; i<NumVars; i++) nl[i] = Nl;
      projection = 1;
      proj_args[0] = NorthLat[0];
      proj_args[1] = WestLon[0];
      proj_args[2] = LatInc;
      proj_args[3] = LonInc;
      vertical = 1;
      vert_args[0] = Bottom;
      vert_args[1] = HgtInc;
      if (v5dCreate( argv[2], NumTimes, NumVars, Nr, Nc, nl,
                     (const char (*)[10]) VarName, TimeStamp, DateStamp,
                     compressmode,
                     projection, proj_args, vertical, vert_args)) {
/*
      if (v5dCreateSimple( argv[2], NumTimes, NumVars, Nr, Nc, Nl,
                           VarName, TimeStamp, DateStamp,
                           NorthLat[0], LatInc,
                           WestLon[0], LonInc,
                           Bottom, HgtInc )) {
*/

         int time, var;
         float *data;

         data = (float *) malloc( Nr * Nc * Nl * sizeof(float) );

         /* Read each 3-D grid, decompress it and write to output file */
         for (time=0;time<NumTimes;time++) {
            for (var=0;var<NumVars;var++) {
               read_grid( infile, id, data );

               v5dWrite( time+1, var+1, data );
            }
         }

         v5dClose();
      }
      else {
         printf("Error:  couldn't create output file: %s\n", argv[2] );
      }
   }

   return 0;
}
Exemplo n.º 23
0
int main (int argc, char* argv[]) {

  Command_line_opts opts;
  Search_settings sett;
  Search_range s_range; 
  Aux_arrays aux_arr;
  double *F; 			  // F-statistic array
  int i; 

#define QUOTE(x) #x
#define STR(macro) QUOTE(macro)
#define CVSTR STR(CODEVER)

  printf("Code version : " CVSTR "\n");

  // Command line options 
  handle_opts(&sett, &opts, argc, argv);  
	
  // Output data handling
  struct stat buffer;

  if (stat(opts.prefix, &buffer) == -1) {
    if (errno == ENOENT) {
      // Output directory apparently does not exist, try to create one
      if(mkdir(opts.prefix, S_IRWXU | S_IRGRP | S_IXGRP 
          | S_IROTH	| S_IXOTH) == -1) {
	      perror (opts.prefix);
	      return 1;
      }
    } else { // can't access output directory
      perror (opts.prefix);
      return 1;
    }
  }
 
  // Grid data 
  read_grid(&sett, &opts);	
	
  // Search settings
  search_settings(&sett); 

  // Detector network settings
  detectors_settings(&sett, &opts); 

  // Array initialization and reading the ephemerids 
  init_arrays(&sett, &opts, &aux_arr, &F);

  // Narrowing-down the band (excluding the edges 
  // according to the opts.narrowdown parameter) 
  if(opts.narrowdown < 0.5*M_PI)
    narrow_down_band(&sett, &opts);

  // Reading known lines data from external files 
  if(opts.veto_flag) { 
    for(i=0; i<sett.nifo; i++) {
      printf("Reading known lines data for %s from %s\n", ifo[i].name, opts.dtaprefix);
      read_lines(&sett, &opts, &ifo[i]);
    }

    // Vetoing known lines in band 
    lines_in_band(&sett, &opts); 
  } 

  // If excluded parts of band, list them
  // and check if the band isn't fully vetoed 
  if(sett.numlines_band) {     

    int k; 
    printf("list of excluded frequencies in band (in radians):\n"); 
    for(k=0; k<sett.numlines_band; k++) 
      printf("%f %f\n", sett.lines[k][0], sett.lines[k][1]);

    check_if_band_is_fully_vetoed(&sett); 

  } 

  // Amplitude modulation functions for each detector  
  for(i=0; i<sett.nifo; i++)   
    rogcvir(&ifo[i]); 

  // Grid search range
  if(strlen(opts.addsig)) { 
    // If addsig switch used, add signal from file, 
    // search around this position (+- gsize)
    add_signal(&sett, &opts, &aux_arr, &s_range); 
  } else 
    // Set search range from range file  
    set_search_range(&sett, &opts, &s_range);

  // FFT plans 
  FFTW_plans fftw_plans;
  FFTW_arrays fftw_arr;
  plan_fftw(&sett, &opts, &fftw_plans, &fftw_arr, &aux_arr);
  if (strlen(opts.getrange)) exit(EXIT_SUCCESS);

  // Checkpointing
  int Fnum=0;			        // candidate signal number
  read_checkpoints(&opts, &s_range, &Fnum);

  // main search job
  search(&sett, &opts, &s_range, 
        &fftw_plans, &fftw_arr, &aux_arr,
	      &Fnum, F);

  // state file zeroed at the end of the run
  FILE *state;
  if(opts.checkp_flag) {
    state = fopen (opts.qname, "w");
    fclose (state);
  }
	
  // Cleanup & memory free 
  cleanup(&sett, &opts, &s_range, 
          &fftw_plans, &fftw_arr, &aux_arr, F);

  return 0; 
	
}