Beispiel #1
0
int main(int argc, char *argv[]) {
  // printf("%s\n", argv[0]);
  Vector v1 = read_input_file(argv[1]);
  quicksort_classico(v1.integers, 0, v1.size-1);
  free_vector(v1);

}
Beispiel #2
0
int main ( int argc, char **argv ) {
	struct input_file input;
	struct output_file output;
	struct zinfo_file zinfo;
	unsigned int i;

	if ( argc != 3 ) {
		fprintf ( stderr, "Syntax: %s file.bin file.zinfo "
			  "> file.zbin\n", argv[0] );
		exit ( 1 );
	}

	if ( read_input_file ( argv[1], &input ) < 0 )
		exit ( 1 );
	if ( read_zinfo_file ( argv[2], &zinfo ) < 0 )
		exit ( 1 );
	if ( alloc_output_file ( ( input.len * 4 ), &output ) < 0 )
		exit ( 1 );

	for ( i = 0 ; i < zinfo.num_entries ; i++ ) {
		if ( process_zinfo ( &input, &output,
				     &zinfo.zinfo[i] ) < 0 )
			exit ( 1 );
	}

	if ( write_output_file ( &output ) < 0 )
		exit ( 1 );

	return 0;
}
Beispiel #3
0
int main () {
    read_input_file();
    int total_flow = max_flow(0,n-1);
    printf("%d\n", total_flow*2/(n-2));
    //printf("%d\n", total_flow);
    return 0;
}
Beispiel #4
0
int main(int argc, char * argv[])
{
    int i;
    int total;
    struct input_t ** input;
    
    if (argc != 3)
    {
        printf("./codejam inputfile outputfile\n");
        return -1;
    }
    
    //read in file
    input = read_input_file(argv[1],&total);
    
    //solve
    for (i = 0;i < total;i++)
    {
        solution(input[i]);
    }
    
    //write output file
    write_output_file(argv[2],input,total);

    return 1;
}
Beispiel #5
0
int main(int argc, char const *argv[]) {
  Vector v = read_input_file("input");
  selection(v);
  write_output_file(v, "output");
  free_vector(v);
  return 0;
}
Beispiel #6
0
int main(int argc, char *argv[]) {

    // Configuration
    string path;
    if(!check_flags(argc,argv,path)){
        return 1;
    }
    read_input_file(path);

    // Algorithm
    //int iteration = 0;
    //int loop;
    int watch_best;
    int best_fitness;

    solutions_generation(sols);
    fitness_calculation(sols);

    solutions_improvement(sols);
    refset_build();

    save_best_solution(refset);
    refset_tmp = refset;

    do {
        // number of new solutions in the RefSet
        loop = 0;
        while (get_difference(refset_tmp,refset) != 0)
        {
            refset_tmp = refset;
            solutions_combination();
            fitness_calculation(new_set);
            new_set = solutions_improvement2(new_set);
            //solutions_improvement(new_set);
            refset_modification(new_set);
            loop++;
        }
        save_best_solution(refset);

        /* A: If we find the optimal, stop */
        if(best.p == 100){
            iteration = max_iter;
        }
        /* A: end */

        refset_rebuild();
        iteration++;
        print_one_solution(best);
        //print_strip(best);
        //print_tikz(best);
    } while (iteration < max_iter);
    //print_one_solution(best);
    //print_strip(best);
    print_tikz(best);

    return 0;
}
Beispiel #7
0
int main(int argc, char *argv[])
{
	get_exec_name(argv[0]);
	get_options(argc, argv);             /* may exit */
	open_files();                        /* may exit */
	read_input_file();                   /* may exit */
	validate_input_file();               /* may exit */
	generate_interrupt_vector_bitmap();  /* may exit */
	generate_idt();                      /* may exit */
	close_files();
	return 0;
}
Beispiel #8
0
int main(void) {
    int rank, size; // MPI parameters
    long long int vect_length; // User-specified vector length
    long long int i;
    int* vector; // The master vector --  not yet allocated
    int* chunk_vector; // The chunk vector -- not yet allocated
    char infilename[100], outfilename[100];

    MPI_Init (NULL, NULL);
    MPI_Comm_size(MPI_COMM_WORLD, &size); //gets size
    MPI_Comm_rank(MPI_COMM_WORLD, &rank); //gets rank
    
    // Get user input: total length of vector, filenames
    // and read vector

    if (rank == 0) {
        printf("Vector length:\n");
        scanf("%lld", &vect_length);
        printf("Name of input file:\n");
        scanf("%99s", infilename);
        printf("Name of output file:\n");
        scanf("%99s", outfilename);
        printf("\n");
        vector = (int *) malloc(vect_length * sizeof(int*)+1);
        read_input_file(infilename, vect_length, vector);
    }

    int chunk;
    chunk = vect_length / size;
    chunk_vector = (int *) malloc(chunk * sizeof(int*)+1);
 
    if(rank == 0){
      MPI_Scatter(vector, chunk, MPI_INT, chunk_vector, chunk, MPI_INT, 0, MPI_COMM_WORLD);
    }
    
      printf("rank %d of %d recieved chunk size of %d\n", rank, size, chunk);    
      int k;
      for(k = 0; k < chunk; k++){
	chunk_vector[k]++;
      }
    
    if(rank == 0){
      MPI_Gather(vector, chunk, MPI_INT, vector, vect_length, MPI_INT, 0, MPI_COMM_WORLD);//this isnt working
      write_output_file(outfilename, vect_length, vector);
    }
    
    // free(vector);
    MPI_Finalize();

    return 0;
}
Beispiel #9
0
int main( int argc, char *argv[] ) {
  word_count *casted_c;
  GHashTableIter iter_c;
  //int *id_t, *id_c; 
  gpointer key_c, value_t_c, value_t, key_t;  
  if( argc != 2 ) { usage(); }
  perr( "Reading input file into hashmap...\n" );
  read_input_file( argv[1] ); 

  // File header
  perr( "Calculating association scores...\n" );
  printf( "target\tid_target\tcontext\tid_context\tf_tc\tf_t\tf_c\t" );
  printf( "cond_prob\tpmi\tnpmi\tlmi\ttscore\tzscore\tdice\tchisquare\t" );
  printf( "loglike\taffinity\tentropy_target\tentropy_context\n" );
  // First calculate all entropies for contexts
  g_hash_table_iter_init( &iter_c, c_dict );
  while( g_hash_table_iter_next( &iter_c, &key_c, &value_t_c ) ){
    casted_c = g_hash_table_lookup( c_dict, key_c );
    casted_c->entropy = calculate_entropy(casted_c->count, casted_c->links);      
  }
  g_hash_table_iter_init( &iter_t, t_dict );
  nb_targets = g_hash_table_size( t_dict );
  if( nb_threads > 1 ) {
    run_multi_threaded( &calculate_ams_all, nb_threads );
  }
  else {
    while( g_hash_table_iter_next( &iter_t, &key_t, &value_t ) ){
      calculate_ams_all_serial( (word_count *)value_t, key_t );
      update_count();
    }
  }
  // Clean and free to avoid memory leaks
  perr( "Finished, cleaning up...\n" );
  g_hash_table_destroy( t_dict );
  g_hash_table_destroy( c_dict );
  // MUST be last to be destroyed, otherwise will destroy keys in previous dicts 
  // and memory will leak from unreachable values
  g_hash_table_destroy( symbols_dict );   
  g_hash_table_destroy( inv_symbols_dict ); // no effect  
  
  perra( "Number of targets: %d\n", idc_t );
  perra( "Number of contexts: %d\n", idc_c );
  perr( "You can now calculate similarities with command below\n");
  perr( "  ./calculate_similarity [OPTIONS] <out-file>\n\n" );
  return 0;
}
Beispiel #10
0
int main(int argc, char **argv)
{
  char *input_file;
  char *output_file;

  if (argc != 3)
  {
    puts(HELP);
    return 1;
  }

  input_file = convert_path(argv[1]);
  if (input_file[0] == 0)
    {
      free(input_file);
      printf("Missing input-filename\n");
      return 1;
    }

  output_file = convert_path(argv[2]);
  if (output_file[0] == 0)
    {
      free(input_file);
      free(output_file);
      printf("Missing output-filename\n");
      return 1;
    }

  out = fopen(output_file, "wb");
  if (out == NULL)
    {
      free(input_file);
      free(output_file);
    	printf("Cannot open output file");
    	return 1;
     }

  read_input_file(input_file);

  free(input_file);
  free(output_file);
  fclose(out);

  return 0;
}
Beispiel #11
0
int main(int argc, char *argv[]) {
	//check for correct usage
	if (argc < 2) {
		printf("The correct usage is ./proja <filename>\n");
		perror("Incorrect usage of program!! exiting!!\n");
		return -1;
	}

	init_process();

	char *filename = argv[1];

	//1. read the input parameter file
	read_input_file(filename);
	sleep(2);//to see if that helps the last client being stuck at infinite loop

	destroy_process();
	return 0;
}
Beispiel #12
0
int main(int argc, char** argv)
{
	if (argc != 2) {
		printf("Uso: ep1 <arquivo_de_entrada>\n");
		return EXIT_FAILURE;
	}
	
	srand(time(NULL));

	setup_track();		
	setup_boxes();

	if (read_input_file(argv[1])) {	
		create_track_mutexes();		
		create_boxes_mutexes();
		setup_pilots();
		choose_reduced_pilots();
		setup_start_grid();
		if (DEBUG) show_pilots();		
		if (DEBUG) show_track();
		if (DEBUG) show_boxes();
	}

	create_barrier_semaphores();
	create_coordinator_thread();
	create_pilots_threads();

	if (DEBUG) printf("\n[Foi dada a largada]\n");
	start = 1;

	join_threads();

	if (DEBUG) printf("\n[Corrida finalizada]\n");
	
	show_race_result();
	show_championship_classification();
	show_teams_classification();

	clean_up();
	
	return EXIT_SUCCESS;
}
Beispiel #13
0
int main(int argc, char *argv[]){
	FILE *fin, *fout;

	if(argc < 5){
		printf("To few arguments passed.\n");
		exit(0);
	}

	fin = fopen(argv[2], "r");
	fout = fopen(argv[4], "w");

	if(fin == NULL || fout == NULL){
		printf("Couldn't open input or output file.\n");
		exit(0);
	}

	read_input_file(fin, fout, argv[1], argv[3]);

	return 0;
}
int main(int argc, char **argv)
{
	struct ifi_info	*ifihead;
	int sockfd;

	if (argc != 2)
		err_quit("usage: client <FileName>");

	read_input_file(argv[1]);
	
	// Print information about the IP address and network masks
	ifihead = Get_ifi_info_plus(AF_INET, 1);
	prifinfo_plus(ifihead);

	// Create a socket that connects to the server
	sockfd = create_socket();

	receive_file(sockfd);

	return 0;
}
Beispiel #15
0
Datei: main.c Projekt: goma/goma
int
main(int argc, char **argv)
     
     /*
      * Initial main driver for GOMA. Derived from a (1/93) release of
      * the rf_salsa program by
      *        
      *        Original Authors: John  Shadid (1421)
      *		                 Scott Hutchinson (1421)
      *        		         Harry Moffat (1421)
      *       
      *        Date:		12/3/92
      * 
      *
      *        Updates and Changes by:
      *                           Randy Schunk (9111)
      *                           P. A. Sackinger (9111)
      *                           R. R. Rao       (9111)
      *                           R. A. Cairncross (Univ. of Delaware)
      *        Dates:           2/93 - 6/96
      *
      *       Modified for continuation
      *                           Ian Gates
      *       Dates:            2/98 - 10/98
      *       Dates:            7/99 - 8/99
      * 
      * Last modified: Wed  June 26 14:21:35 MST 1994 [email protected]
      * Hello.
      * 
      * Note: Many modifications from an early 2/93 pre-release
      *	      version of rf_salsa were made by various persons 
      *       in order to test ideas about moving/deforming meshes...
      */ 
{
  /* Local Declarations */

  double time_start, total_time;   /* timing variables */
#ifndef PARALLEL
  /*  struct tm *tm_ptr;               additional serial timing variables */
  time_t now;
#endif

  int error;
  int i;
  int j;

  char	**ptmp;
  char *yo;

  struct Command_line_command **clc=NULL; /* point to command line structure */
  int           nclc = 0;		/* number of command line commands */

/********************** BEGIN EXECUTION ***************************************/

#ifdef FP_EXCEPT
  feenableexcept ((FE_OVERFLOW | FE_DIVBYZERO | FE_INVALID));
#endif

/* assume number of commands is less than or equal to the number of 
 * arguments in the command line minus 1 (1st is program name) */

  /*
  *  Get the name of the executable, yo
  */
  yo = argv[0];

#ifdef PARALLEL
  MPI_Init(&argc, &argv);
  time_start = MPI_Wtime();
#endif /* PARALLEL */
#ifndef PARALLEL
  (void)time(&now);
  time_start = (double)now;
#endif /* PARALLEL */

  time_goma_started = time_start;

  Argv = argv;

  Argc = argc;

#ifdef PARALLEL
  /*
   * Determine the parallel processing status, if any. We need to know
   * pretty early if we're "one of many" or the only process.
   */

  error = MPI_Comm_size(MPI_COMM_WORLD, &Num_Proc);
  error = MPI_Comm_rank(MPI_COMM_WORLD, &ProcID);

  /*
   * Setup a default Proc_config so we can use utility routines 
   * from Aztec
   */

  AZ_set_proc_config(Proc_Config, MPI_COMM_WORLD);

  /* set the output limit flag if need be */

  if( Num_Proc > DP_PROC_PRINT_LIMIT ) Unlimited_Output = FALSE;

#ifdef HAVE_MPE_H
  error = MPE_Init_log();
#endif /* HAVE_MPE_H */

  Dim = 0;			/* for any hypercube legacy code...  */

#endif /* PARALLEL */
  
#ifndef PARALLEL
  Dim        = 0;
  ProcID     = 0;
  Num_Proc   = 1;
#endif /* PARALLEL */


  /*
  *   HKM - Change the ieee exception handling based on the machine and
  *         the level of debugging/speed desired. This call currently causes
  *         core dumps for floating point exceptions.
  */

  handle_ieee();
  
  log_msg("--------------");
  log_msg("GOMA begins...");

  /*
   * Some initial stuff that only the master process does.
   */

  if ( ProcID == 0 )
    {
      if (argc > 1)
	{
	  log_msg("Preprocessing command line options.");
	  clc = (struct Command_line_command **) 
	    smalloc( argc * sizeof(struct Command_line_command *));
	  for (i=0; i<argc; i++)
	    {
	      clc[i] = (struct Command_line_command *) 
		smalloc(sizeof(struct Command_line_command));
	      clc[i]->type   = 0; /* initialize command line structure */
	      clc[i]->i_val  = 0;
	      clc[i]->r_val  = 0.;
	      clc[i]->string = (char *) 
		smalloc(MAX_COMMAND_LINE_LENGTH*sizeof(char));
	      for ( j=0; j<MAX_COMMAND_LINE_LENGTH; j++)
		{
		  clc[i]->string[j] = '\0';
		}
#ifdef DEBUG
	      fprintf(stderr, "clc[%d]->string is at 0x%x\n", i, clc[i]->string);
	      fprintf(stderr, "clc[%d]         is at 0x%x\n", i, clc[i]);
#endif
	    }
	}

      strcpy(Input_File, "input");
      strcpy(Echo_Input_File , "echo_input");

      if (argc > 1) translate_command_line(argc, argv, clc, &nclc);
	  	  
	  ECHO("OPEN", Echo_Input_File);
      
	  echo_command_line( argc, argv, Echo_Input_File );
      print_code_version();
      ptmp = legal_notice;
      while ( strcmp(*ptmp, LAST_LEGAL_STRING) != 0 )
	{
	  fprintf(stderr, "%s", *ptmp++);
	}
    }

  /*
   *  Allocate the uniform problem description structure and
   *  the problem description structures on all processors
   */
  error = pd_alloc();
  EH(error, "pd_alloc problem");

#ifdef DEBUG
  fprintf(stderr, "P_%d at barrier after pd_alloc\n", ProcID);
#ifdef PARALLEL
  error = MPI_Barrier(MPI_COMM_WORLD);
#endif
#endif

  log_msg("Allocating mp, gn, ...");

  error = mp_alloc();
  EH(error, "mp_alloc problem");

  error = gn_alloc();
  EH(error, "gn_alloc problem");

  error = ve_alloc();
  EH(error, "ve_alloc problem");

  error = elc_alloc();
  EH(error, "elc_alloc problem");

  error = elc_rs_alloc();
  EH(error, "elc_alloc problem");

  error = cr_alloc();
  EH(error, "cr_alloc problem");

  error = evp_alloc();
  EH(error, "evp_alloc problem");

  error = tran_alloc();
  EH(error, "tran_alloc problem");

  error = eigen_alloc();
  EH(error, "eigen_alloc problem");

  error = cont_alloc();
  EH(error, "cont_alloc problem");

  error = loca_alloc();
  EH(error, "loca_alloc problem");

  error = efv_alloc();
  EH(error, "efv_alloc problem");

#ifdef DEBUG
  fprintf(stderr, "P_%d at barrier before read_input_file()\n", ProcID);
#ifdef PARALLEL
  error = MPI_Barrier(MPI_COMM_WORLD);
#endif
#endif

  /*
   * Read ASCII input file, data files, related exodusII FEM databases.
   */	
  if ( ProcID == 0 )
    {
      log_msg("Reading input file ...");
      read_input_file(clc, nclc); /* Read ascii input file get file names */

      /* update inputed data to account for command line arguments that
       * might override the input deck...
       */
      log_msg("Overriding any input file specs w/ any command line specs...");
      if (argc > 1) apply_command_line(clc, nclc);

#ifdef DEBUG
      DPRINTF(stderr, "apply_command_line() is done.\n");
#endif
    }

  /*
   * The user-defined material properties, etc. available to goma users
   * mean that some dynamically allocated data needs to be communicated.
   *
   * To handle this, sizing information from the input file scan is
   * broadcast in stages so that the other processors can allocate space
   * accordingly to hold the data.
   *
   * Note: instead of handpacking a data structure, use MPI derived datatypes
   * to gather and scatter. Pray this is done efficiently. Certainly it costs
   * less from a memory standpoint.
   */

#ifdef PARALLEL

  /*
   *  Make sure the input file was successully processed before moving on
   */
  check_parallel_error("Input file error");


  /*
   * This is some sizing information that helps fit a little bit more
   * onto the ark later on.
   */

#ifdef DEBUG
  fprintf(stderr, "P_%d at barrier before noahs_raven()\n", ProcID);
  error = MPI_Barrier(MPI_COMM_WORLD);
#endif

  noahs_raven();

#ifdef DEBUG
  fprintf(stderr, "P_%d at barrier before MPI_Bcast of Noahs_Raven\n", ProcID);
  error = MPI_Barrier(MPI_COMM_WORLD);
#endif

  MPI_Bcast(MPI_BOTTOM, 1, Noahs_Raven->new_type, 0, MPI_COMM_WORLD);

#ifdef DEBUG
  fprintf(stderr, "P_%d at barrier after Bcast/before raven_landing()\n", 
	  ProcID);
  error = MPI_Barrier(MPI_COMM_WORLD);
#endif  
  /*
   * Get the other processors ready to handle ark data.
   */

  raven_landing();

#ifdef DEBUG
  fprintf(stderr, "P_%d at barrier before noahs_ark()\n", ProcID);
  error = MPI_Barrier(MPI_COMM_WORLD);
#endif
  
  
  /*
   * This is the main body of communicated information, including some
   * whose sizes were determined because of advanced legwork by the raven.
   */

  noahs_ark();
  MPI_Bcast(MPI_BOTTOM, 1, Noahs_Ark->new_type, 0, MPI_COMM_WORLD);

  /*
   * Chemkin was initialized on processor zero during the input file
   * process. Now, distribute it to all processors
   */
#ifdef USE_CHEMKIN
  if (Chemkin_Needed) {
    chemkin_initialize_mp();
  }
#endif 

  /*
   * Once the ark has landed, there are additional things that will need to
   * be sent by dove. Example: BC_Types[]->u-BC arrays.
   *
   */

  ark_landing();

  noahs_dove();
  MPI_Bcast(MPI_BOTTOM, 1, Noahs_Dove->new_type, 0, MPI_COMM_WORLD);


#endif          /* End of ifdef PARALLEL */


  /*
   * We sent the packed line to all processors that contained geometry
   * creation commands.  Now we need to step through it and create
   * geometry as we go (including possibly reading an ACIS .sat file).
   *
   */

  /* Check to see if BRK File option exists and if so check if file exits */
  if (Brk_Flag == 1) {
    check_for_brkfile(Brk_File);
  }
  check_parallel_error("Error encountered in check for brkfile");

  /* Now break the exodus files */
  if (Num_Proc > 1 && ProcID == 0 && Brk_Flag == 1) {
    call_brk();
  }
  check_parallel_error("Error in brking exodus files");
  MPI_Barrier(MPI_COMM_WORLD);

  /*
   * For parallel execution, assume the following variables will be changed
   * to reflect the multiple file aspect of the problem.
   *
   *	FEM file = file.exoII		--> file_3of15.exoII
   *
   *	Output EXODUS II file = out.exoII --> out_3of15.exoII
   *
   */


  /*
   * Allocate space for structures holding the EXODUS II finite element
   * database information and for the Distributed Processing information.
   *
   * These are mostly skeletons with pointers that get allocated in the
   * rd_exoII and rd_dpi routines. Remember to free up those arrays first
   * before freeing the major pointers.
   */

  EXO_ptr = alloc_struct_1(Exo_DB, 1);
  init_exo_struct(EXO_ptr);
  DPI_ptr = alloc_struct_1(Dpi, 1);
  init_dpi_struct(DPI_ptr);  

  log_msg("Reading mesh from EXODUS II file...");
  error = read_mesh_exoII(EXO_ptr, DPI_ptr);

  /*
   *   Missing files on any processor are detected at a lower level
   *   forcing a return to the higher level
   *         rd_exo -->  rd_mesh  -->  main
   *   Shutdown now, if any of the exodus files weren't found
   */
  if (error < 0) {
#ifdef PARALLEL
    MPI_Finalize();
#endif
    return(-1);
  }

  /*
   * All of the MPI_Type_commit() calls called behind the scenes that build
   * the dove, ark and raven really allocated memory. Let's free it up now that
   * the initial information has been communicated.
   */

#ifdef PARALLEL
  MPI_Type_free(&(Noahs_Raven->new_type));
  MPI_Type_free(&(Noahs_Ark->new_type));
  MPI_Type_free(&(Noahs_Dove->new_type));
#endif   

  /*
   * Setup the rest of the Problem Description structure that depends on
   * the mesh that was read in from the EXODUS II file...
   * 
   * Note that memory allocation and some setup has already been performed
   * in mm_input()...
   */

  error = setup_pd();
  EH( error, "Problem setting up Problem_Description.");
  /*
   * Let's check to see if we need the large elasto-plastic global tensors
   * and allocate them if so 
   */
  error = evp_tensor_alloc(EXO_ptr);
  EH( error, "Problems setting up evp tensors");
  
  /*
   * Now that we know about what kind of problem we're solving and the
   * mesh information, let's allocate space for elemental assembly structures
   *
   */
#ifdef DEBUG
  DPRINTF(stderr, "About to assembly_alloc()...\n");
#endif
  log_msg("Assembly allocation...");

  error = assembly_alloc(EXO_ptr);
  EH( error, "Problem from assembly_alloc");

  if (Debug_Flag)  {
    DPRINTF(stderr, "%s:  setting up EXODUS II output files...\n", yo);
  }

  /*
   * These are not critical - just niceties. Also, they should not overburden
   * your db with too much of this - they're capped verbiage compliant routines.
   */

  add_qa_stamp(EXO_ptr);

  add_info_stamp(EXO_ptr);

#ifdef DEBUG
  fprintf(stderr, "added qa and info stamps\n");
#endif

  /*
   * If the output EXODUS II database file is different from the input
   * file, then we'll need to replicate all the basic mesh information.
   * But, remember that if we're parallel, that the output file names must
   * be multiplexed first...
   */
  if ( Num_Proc > 1 )
    {
      multiname(ExoFileOut,     ProcID, Num_Proc);      
      multiname(Init_GuessFile, ProcID, Num_Proc);

      if ( strcmp( Soln_OutFile, "" ) != 0 )
	{
	  multiname(Soln_OutFile, ProcID, Num_Proc);
	}

      if( strcmp( ExoAuxFile, "" ) != 0 )
        {
          multiname(ExoAuxFile, ProcID, Num_Proc);
        }

      if( efv->Num_external_field != 0 )
        {
          for( i=0; i<efv->Num_external_field; i++ )
            {
              multiname(efv->file_nm[i], ProcID, Num_Proc);
            }
        }
    }


  /***********************************************************************/
  /***********************************************************************/
  /***********************************************************************/
  /*
   *   Preprocess the exodus mesh
   *        -> Allocate pointers to structures containing element
   *           side bc info, First_Elem_Side_BC_Array, and
   *           element edge info, First_Elem_Edge_BC_Array.
   *        -> Determine Unique_Element_Types[] array
   */
#ifdef DEBUG
  fprintf(stderr, "pre_process()...\n");
#endif
  log_msg("Pre processing of mesh...");
#ifdef PARALLEL
  error = MPI_Barrier(MPI_COMM_WORLD);
#endif
  pre_process(EXO_ptr);

  /***********************************************************************/
  /***********************************************************************/
  /***********************************************************************/
  /*
   * Load up a few key indeces in the bfd prototype basis function structures
   * and make sure that each active eqn/vbl has a bf[v] that points to the
   * right bfd[]...needs pre_process to find out the number of unique
   * element types in the problem.
   */

#ifdef DEBUG
  fprintf(stderr, "bf_init()...\n");
#endif
  log_msg("Basis function initialization...");
  error = bf_init(EXO_ptr);
  EH( error, "Problem from bf_init");

  /*
   * check for parallel errors before continuing
   */
  check_parallel_error("Error encountered in problem setup");

  /***********************************************************************/
  /***********************************************************************/
  /***********************************************************************/  
  /*
   * Allocate space for each communication exchange description.
   */
#ifdef PARALLEL
#ifdef DEBUG
  fprintf(stderr, "P_%d: Parallel cx allocation\n", ProcID);
#endif
  if (DPI_ptr->num_neighbors > 0) {
    cx = alloc_struct_1(Comm_Ex, DPI_ptr->num_neighbors);
    Request = alloc_struct_1(MPI_Request, 
			     Num_Requests * DPI_ptr->num_neighbors);
    Status = alloc_struct_1(MPI_Status, 
			    Num_Requests * DPI_ptr->num_neighbors);
  }
#endif

  /***********************************************************************/
  /***********************************************************************/
  /***********************************************************************/
  /*
   *                           SET UP THE PROBLEM
   *
   * Setup node-based structures
   * Finalise how boundary conditions are to be handled
   * Determine what unknowns are at each owned node and then tell
   *  neighboring processors about your nodes
   * Set up communications pattern for fast unknown updates between
   *  processors.
   */
  (void) setup_problem(EXO_ptr, DPI_ptr);

  /*
   * check for parallel errors before continuing
   */
  check_parallel_error("Error encountered in problem setup");

  /***********************************************************************/
  /***********************************************************************/
  /***********************************************************************/
  /*
   *               CREATE BRK_FILE IF ONE DOES NOT EXIST
   *
   * If no Brk_File exists but the option was configured in the input or
   * optional command we create one now and exit from goma.
   */
  if ( Brk_Flag == 2 ) {
    write_brk_file(Brk_File, EXO_ptr);
    exit(0);
  }
  
  /***********************************************************************/
  /***********************************************************************/
  /***********************************************************************/
  /*
   *                     WRITE OUT INITIAL INFO TO EXODUS FILE
   */

  /*
   *  Only have to initialize the exodus file if we are using different
   *  files for the output versus the input mesh
   */
  if (strcmp(ExoFile, ExoFileOut)) {
    /*
     * Temporarily we'll need to renumber the nodes and elements in the
     * mesh to be 1-based. After writing, return to the 0 based indexing
     * that is more convenient in C.
     */
#ifdef DEBUG
    fprintf(stderr, "1-base; wr_mesh; 0-base\n");
#endif
    one_base(EXO_ptr);
    wr_mesh_exo(EXO_ptr, ExoFileOut, 0);
    zero_base(EXO_ptr);

    /*
     * If running on a distributed computer, augment the plain finite
     * element information of EXODUS with the description of how this
     * piece fits into the global problem.
     */
    if (Num_Proc > 1) {
#ifdef PARALLEL
#ifdef DEBUG
      fprintf(stderr, "P_%d at barrier before wr_dpi()\n", ProcID);
      fprintf(stderr, "P_%d ExoFileOut = \"%s\"\n", ProcID, ExoFileOut);
      error = MPI_Barrier(MPI_COMM_WORLD);
#endif
#endif
      wr_dpi(DPI_ptr, ExoFileOut, 0);
    }
  }

  /***********************************************************************/
  /***********************************************************************/
  /***********************************************************************/
  /*
   *                           SOLVE THE PROBLEM
   */

  if (Debug_Flag) {
    switch (Continuation) {
    case ALC_ZEROTH:
        P0PRINTF("%s: continue_problem (zeroth order) ...\n", yo);
        break;
    case  ALC_FIRST:
        P0PRINTF("%s: continue_problem (first order) ...\n", yo);
        break;
    case HUN_ZEROTH:
        P0PRINTF("%s: hunt_problem (zeroth order) ...\n", yo);
        break;
    case  HUN_FIRST:
        P0PRINTF("%s: hunt_problem (first order) ...\n", yo);
        break;
    case LOCA:
        P0PRINTF("%s: do_loca ...\n", yo);
        break;
    default:
        P0PRINTF("%s: solve_problem...\n", yo);
        break;
    }
  }  
#ifdef DEBUG
  switch (Continuation) {
  case ALC_ZEROTH:
      DPRINTF(stderr, "%s: continue_problem (zeroth order) ...\n", yo);
      break;
  case  ALC_FIRST:
      DPRINTF(stderr, "%s: continue_problem (first order) ...\n", yo);
      break;
  case HUN_ZEROTH:
      DPRINTF(stderr, "%s: hunt_problem (zeroth order) ...\n", yo);
      break;
  case  HUN_FIRST:
      DPRINTF(stderr, "%s: hunt_problem (first order) ...\n", yo);
      break;
  case LOCA:
      DPRINTF(stderr, "%s: do_loca ...\n", yo);
      break;
  default:
      DPRINTF(stderr, "%s: solve_problem...\n", yo);
      break;
  }
#endif

    
  if( TimeIntegration == TRANSIENT)
        {
        Continuation = ALC_NONE;
        if (Debug_Flag) {
          P0PRINTF("%s: solve_problem...TRANSIENT superceded Continuation...\n", yo);
          }
#ifdef DEBUG
   DPRINTF(stderr, "%s: solve_problem...TRANSIENT superceded Continuation...\n", yo);
#endif
        solve_problem(EXO_ptr, DPI_ptr, NULL);
        }  

  switch (Continuation) {
  case ALC_ZEROTH:
  case ALC_FIRST:
    log_msg("Solving continuation problem");
    continue_problem(cx, EXO_ptr, DPI_ptr);
    break;
  case HUN_ZEROTH:
  case HUN_FIRST:
    log_msg("Solving hunt problem");
    hunt_problem(cx, EXO_ptr, DPI_ptr);
    break;
  case LOCA:
    log_msg("Solving continuation problem with LOCA");
    error = do_loca(cx, EXO_ptr, DPI_ptr);
    break;
  default:
    log_msg("Solving problem");
    if (loca_in->Cont_Alg == LOCA_LSA_ONLY)
      {
        error = do_loca(cx, EXO_ptr, DPI_ptr);
      }
    else if(TimeIntegration != TRANSIENT)
      {
        solve_problem(EXO_ptr, DPI_ptr, NULL);
      }
    break;
  }

#ifdef PARALLEL
   MPI_Barrier(MPI_COMM_WORLD);
#endif

  if (ProcID == 0 && Brk_Flag == 1 && Num_Proc > 1) {
    fix_output();
  }
  
  /***********************************************************************/
  /***********************************************************************/
  /***********************************************************************/
  /*
   *  PRINT A MESSAGE TO STDOUT SAYING WE ARE DONE
   */
  P0PRINTF("\n-done\n\n");

  /***********************************************************************/
  /***********************************************************************/
  /***********************************************************************/
  /*
   *       FREE MEMORY ALLOCATED BY THE PROGRAM
   */
  /*
   * free the element block / element based structures
   */
  free_element_blocks(EXO_ptr);

  /*
   * free nodal based structures
   */
  free_nodes();
#ifdef FREE_PROBLEM
  free_problem ( EXO_ptr, DPI_ptr );
#endif

  /*
   * Free command line stuff
   */
  if ( ProcID == 0 )
    {
      if ( argc > 1 ) 
	{
	  for (i=0; i<argc; i++)
	    {
#ifdef DEBUG
	      fprintf(stderr, "clc[%d]->string &= 0x%x\n", i, clc[i]->string);
	      fprintf(stderr, "clc[%d]         &= 0x%x\n", i, clc[i]);
#endif
	      safer_free((void **) &(clc[i]->string));
	      safer_free((void **) (clc + i));
	    }
	  safer_free((void **) &clc);
	}
    }

  /*
   * Free exodus database structures
   */
  free_exo(EXO_ptr);
  safer_free((void **) &EXO_ptr);

  if ( Num_Proc > 1 )
  {
    free_dpi(DPI_ptr);
  }
  else
  {
    free_dpi_uni(DPI_ptr);
  }

  safer_free((void **) &DPI_ptr);

  /*
   * Remove front scratch file [/tmp/lu.'pid'.0]
   */
  if (Linear_Solver == FRONT) 	
    {
  unlerr = unlink(front_scratch_directory);
  WH(unlerr, "Unlink problem with front scratch file");
    }


#ifdef PARALLEL
  total_time = ( MPI_Wtime() - time_start )/ 60. ;
  DPRINTF(stderr, "\nProc 0 runtime: %10.2f Minutes.\n\n",total_time);
  MPI_Finalize();
#endif  
#ifndef PARALLEL
  (void)time(&now);
  total_time = (double)(now) - time_start;
  fprintf(stderr, "\nProc 0 runtime: %10.2f Minutes.\n\n",total_time/60);
#endif  
  fflush(stdout);
  fflush(stderr);
  log_msg("GOMA ends normally.");
  return (0);
}
Beispiel #16
0
int main () {
    read_input_file();
    printf("%d\n",max_flow(posmin,posmax));
    return 0;
}
Beispiel #17
0
int main(int argc, char **argv){

	fprintf(stderr,"\n*******************************************************************\n");
	fprintf(stderr,"**                                                               **\n");
	fprintf(stderr,"**            =          HALOGEN V0.5           =                **\n");
	fprintf(stderr,"**                                                               **\n");
	fprintf(stderr,"**                                                               **\n");
	fprintf(stderr,"**                                            let there be dark  **\n");
	fprintf(stderr,"*******************************************************************\n\n");

	if (argc!=2){
		fprintf(stderr,"usage: %s inputfile\n",argv[0]);	
		return -1;
	}

	float Lbox, mpart, *x, *y, *z, *vx,*vy,*vz,*hx, *hy, *hz, *hvx,*hvy,*hvz,*hR, om_m;	
	char inname[256];
	long Npart, Nhalos, **ListOfParticles, *NPartPerCell;
	float *HaloMass, rho;
	double *MassLeft;
	float *dens;


	strcpy(inname,argv[1]);

#ifdef VERB
	fprintf(stderr,"#def VERB\n");
#endif 
#ifdef DEBUG
	fprintf(stderr,"#def DEBUG \n");
#endif
#ifdef ULTRADEBUG
	fprintf(stderr,"#def ULTRADEBUG \n");
#endif
#ifdef ONLYBIG
	fprintf(stderr,"#def ONLYBIG\n");
#endif
#ifdef NO_EXCLUSION
	fprintf(stderr,"#def NO_EXCLUSION\n");
#endif
#ifdef NO_MASS_CONSERVATION
	fprintf(stderr,"#def NO_MASS_CONSERVATION\n");
#endif
#ifdef MASS_OF_PARTS
	fprintf(stderr,"#def MASS_OF_PARTS\n");
#endif
#ifdef RANKED
	fprintf(stderr,"#def RANKED\n");
#endif
#ifdef NDENS
	fprintf(stderr,"#def NDENS\n");
#endif


	fprintf(stderr,"\nReading input file...\n");
	if (read_input_file(inname)<0)
		return -1;
	fprintf(stderr,"... file read correctly!\n");


	fprintf(stderr,"Reading Gadget file(s)...\n");
	if (read_snapshot(Snapshot, format, LUNIT, MUNIT, SWP, LGADGET, DGADGET,Nlin,&x, &y, &z, &vx, &vy, &vz, &Npart, &mpart, &Lbox, &om_m,&ListOfParticles,&NPartPerCell,&MassLeft,&dens)==0)
		fprintf(stderr,"Gadget file(s) correctly read!\n");
	else {
		fprintf(stderr,"error: Something went wrong reading the gadget file %s\n",inname);
		return -1;
	}
	
	#ifdef VERB
	fprintf(stderr,"\n\tCheck: Npart=%ld, mpart=%e, Lbox=%f\n",Npart,mpart,Lbox);
	fprintf(stderr,"\tx[0]= %f, y[0]= %f, z[0]= %f\n",(x)[0],(y)[0],(z)[0]);
	fprintf(stderr,"\t      ...\n");
	fprintf(stderr,"\tx[%ld]= %f, y[%ld]= %f, z[%ld]= %f\n\n",Npart-1,(x)[Npart-1],Npart-1,(y)[Npart-1],Npart-1,(z)[Npart-1]);
	#endif
	
	if (seed<0){
		seed = time(NULL);
		fprintf(stderr,"Seed used: %ld\n",seed);
	}

	//Generate the halo masses from the mass function
	fprintf(stderr,"Generating Halo Masses...\n");
	Nhalos = populate_mass_function(MassFunctionFile,Mmin,Lbox,&HaloMass,seed);
	if (Nhalos<0)
		fprintf(stderr,"error: Couldnt create HaloMass array\n");	
	fprintf(stderr,"...Halo Masses Generated\n");

	//Allocalte memory for the halo XYZR, and MassLeft vector
	hx = (float *) calloc(Nhalos,sizeof(float));
	hy = (float *) calloc(Nhalos,sizeof(float));
	hz = (float *) calloc(Nhalos,sizeof(float));
	hvx = (float *) calloc(Nhalos,sizeof(float));
	hvy = (float *) calloc(Nhalos,sizeof(float));
	hvz = (float *) calloc(Nhalos,sizeof(float));
	hR = (float *) calloc(Nhalos,sizeof(float));
	
	//MassLeft = (double *) calloc(Nlin*Nlin*Nlin,sizeof(double));
	
	//density at the boundary of a halo
	if (strcmp(rho_ref,"crit")==0)
		rho = OVD*rho_crit;
	else 
		rho = OVD*rho_crit*om_m;


	//place the halos
	fprintf(stderr,"Placing halos down...\n");
	if (place_halos(Nhalos,HaloMass, Nlin, Npart, x, y, z, vx,vy,vz,Lbox, rho,seed,mpart, alpha, Malpha, Nalpha, hx, hy, hz, hvx,hvy,hvz, hR,ListOfParticles,NPartPerCell,MassLeft,dens)==0)
		fprintf(stderr,"...halos placed correctly\n");
	else {
		fprintf(stderr,"Problem placing halos\n");
		return -1;
	}

	//writting output	
	fprintf(stderr,"Writing Halo catalogue...\n");
	write_halogen_cat(OutputFile,hx,hy,hz,hvx,hvy,hvz,HaloMass,hR,Nhalos);
	fprintf(stderr,"...halo catalogue written in %s\n",OutputFile);
	
	free(hx);free(hy);free(hz);free(hR);
	free(alpha); free(Malpha);


	fprintf(stderr,"\n*******************************************************************\n");
	fprintf(stderr,"**                        ... and there were dark matter haloes  **\n");
	fprintf(stderr,"*******************************************************************\n\n");

	return 0;	
}
Beispiel #18
0
int main(int argc, char **argv){

	fprintf(stderr,"\n*******************************************************************\n");
	fprintf(stderr,"**                                                               **\n");
	fprintf(stderr,"**            =         HALOGEN FIT V0.5        =                **\n");
	fprintf(stderr,"**                                                               **\n");
	fprintf(stderr,"**                                                               **\n");
	fprintf(stderr,"**                           let there be knowledge of the dark  **\n");
	fprintf(stderr,"*******************************************************************\n\n");

	if (argc!=2){
		fprintf(stderr,"usage: %s inputfile\n",argv[0]);	
		return -1;
	}

	char inname[256];
	float *hx, *hy, *hz, *hvx, *hvy, *hvz, *hR;
	strcpy(inname,argv[1]);
	double dr;
	double **halogen_2pcf, **halogen_err;
	long nend;
	unsigned long long *dd;
	long i,j,ii;

#ifdef VERB
	fprintf(stderr,"#def VERB\n");
#endif 
#ifdef DEBUG
	fprintf(stderr,"#def DEBUG \n");
#endif
#ifdef ULTRADEBUG
	fprintf(stderr,"#def ULTRADEBUG \n");
#endif
#ifdef ONLYBIG
	fprintf(stderr,"#def ONLYBIG\n");
#endif
#ifdef NO_EXCLUSION
	fprintf(stderr,"#def NO_EXCLUSION\n");
#endif
#ifdef NO_MASS_CONSERVATION
	fprintf(stderr,"#def NO_MASS_CONSERVATION\n");
#endif
#ifdef MASS_OF_PARTS
	fprintf(stderr,"#def MASS_OF_PARTS\n");
#endif
#ifdef RANKED
	fprintf(stderr,"#def RANKED\n");
#endif
#ifdef NDENS
	fprintf(stderr,"#def NDENS\n");
#endif
#ifdef NO_PROB_PARALEL
	fprintf(stderr,"#def NO_PROB_PARALEL\n");
#endif
#ifdef NO_PAR_FIT
	fprintf(stderr,"#def NO_PAR_FIT\n");
#endif
#ifdef MASS_CUTS_FIT
	fprintf(stderr,"#def MASS_CUTS_FIT\n");
#endif
#ifdef BETA0
	fprintf(stderr,"#def BETA0\n");
#endif

	fprintf(stderr,"\nReading input file...\n");
	if (read_input_file(inname)<0)
		return -1;
	fprintf(stderr,"... file read correctly!\n");

	//SETUP OUTPUT FILES
	strcpy(OutputNbody2PCF,OutputDir);
	strcpy(OutputHalogen2PCF,OutputDir);
	strcpy(OutputHalogenErr,OutputDir);
	strcpy(OutputAlphaM,OutputDir);
	strcpy(OutputExampleCat,OutputDir);

	strcat(OutputNbody2PCF,"/nbody.2pcf");
	strcat(OutputHalogen2PCF,"/halogen.2pcf");
	strcat(OutputHalogenErr,"/halogen.err");
	strcat(OutputAlphaM,"/M-alpha.txt");
	strcat(OutputExampleCat,"/example.halos");

	fprintf(stderr,"Reading Gadget file(s)...\n");
	if (read_snapshot(Snapshot, format, LUNIT, MUNIT, SWP, LGADGET, DGADGET,Nlin,&x, &y, &z, &vx, &vy, &vz, &Npart, &mpart, &Lbox, &om_m,&ListOfParticles,&NPartPerCell)==0)
		fprintf(stderr,"...Gadget file(s) correctly read!\n");
	else {
		fprintf(stderr,"error: Something went wrong reading the gadget file %s\n",inname);
		return -1;
	}
	


	#ifdef VERB
	fprintf(stderr,"\n\tCheck: Npart=%ld, mpart=%e, Lbox=%f\n",Npart,mpart,Lbox);
	fprintf(stderr,"\tx[0]= %f, y[0]= %f, z[0]= %f\n",(x)[0],(y)[0],(z)[0]);
	fprintf(stderr,"\t\tvx[0]= %f, vy[0]= %f, vz[0]= %f\n",(vx)[0],(vy)[0],(vz)[0]);
	fprintf(stderr,"\t      ...\n");
	fprintf(stderr,"\tx[%ld]= %f, y[%ld]= %f, z[%ld]= %f\n",Npart-1,(x)[Npart-1],Npart-1,(y)[Npart-1],Npart-1,(z)[Npart-1]);
	fprintf(stderr,"\t\tvx[%ld]= %f, vy[%ld]= %f, vz[%ld]= %f\n\n",Npart-1,(vx)[Npart-1],Npart-1,(vy)[Npart-1],Npart-1,(vz)[Npart-1]);
	#endif
	
	seed = time(NULL);

	//Generate the halo masses from the mass function
	fprintf(stderr,"Generating Halo Masses...\n");
	Nhalos = populate_mass_function(MassFunctionFile,Mmin,Lbox,&HaloMass,seed,160);
	if (Nhalos<0){
		fprintf(stderr,"error: Couldnt create HaloMass array\n");	
		return -1;
	}
	fprintf(stderr,"...Halo Masses Generated\n");

	// GET THE ACTUAL NUMBER OF R VALUES IN CORR (LINEARLY SPACED)
	dr = (maxr - minr) / nr;
	total_nr = (int) ceil(maxr / dr) + 2;
	maxr += 2* dr;

	//density at the boundary of a halo
	if (strcmp(rho_ref,"crit")==0)
		rho = OVD*rho_crit;
	else 
		rho = OVD*rho_crit*om_m;

	Nmin = Lbox*Lbox*Lbox*Dmin;
	Nmax = Lbox*Lbox*Lbox*Dmax;
#ifdef VERB
	fprintf(stderr,"Generating Mass Bins...\n");
#endif
	Nalpha = get_mass_bins(HaloMass,Nhalos,Nmax,Nmin);
#ifdef VERB
	fprintf(stderr,"... generated mass bins\n");
	fprintf(stderr,"Nmin=%d, Nmax=%d, Nmassbins=%d (=Nalphas).\n",Nmin,Nmax,Nalpha);
	fprintf(stderr,"Getting NBODY 2PCF...\n");
#endif
	


	float *nbx, *nby, *nbz, *nbvx, *nbvy, *nbvz, *nbm,*fvel;
	long nb_n;

	// Import the Nbody halos
	nb_n = read_nbody(&nbx,&nby,&nbz,&nbvx,&nbvy,&nbvz,&nbm);
	fprintf(stderr,"READ IT IN\n");
	
	

	// Get the Nbody 2PCF
	get_nbody_2pcf(nbx,nby,nbz,nbm,nb_n);

	free(nbx);
	free(nby);
	free(nbz);
	free(nbm);

	betavec = (double *)calloc(Nalpha,sizeof(double));
	alphavec = (double *)calloc(Nalpha,sizeof(double));
	for (i=0;i<Nalpha;i++){
		betavec[i]=1.0;
	}
	// DO THE FIT
	if(find_best_alpha()==0)
		fprintf(stderr, "... done fitting.\n");
	else {
		fprintf(stderr,"Problem fitting\n");
		return -1;
	}

	hx = (float *) calloc(Nhalos,sizeof(float));
	hy = (float *) calloc(Nhalos,sizeof(float));
	hz = (float *) calloc(Nhalos,sizeof(float));
	hvx = (float *) calloc(Nhalos,sizeof(float));
	hvy = (float *) calloc(Nhalos,sizeof(float));
	hvz = (float *) calloc(Nhalos,sizeof(float));
	hR = (float *) calloc(Nhalos,sizeof(float));


	seed++;

	// Do a final placement with the correct alphavec
	place_halos(Nhalos,HaloMass, Nlin, Npart, x, y, z, vx,vy,vz,Lbox,
				rho,seed,
				mpart,nthreads, alphavec, betavec, mcuts, Nalpha, recalc_frac,hx, hy, hz,
				hvx,hvy,hvz, hR,ListOfParticles,NPartPerCell);
		
	fprintf(stderr,"\tComputing velocity bias fvel...\n");
	fvel = compute_fvel(hvx,hvy,hvz,nbvx,nbvy,nbvz,nbm);	
	free(nbvx);
	free(nbvy);
	free(nbvz);
	#ifdef VERB
	for (i=0;i<Nalpha;i++){
		fprintf(stderr,"alpha[%ld]=%f beta[%ld]=%f fvel=%f\n",i,alphavec[i],i,betavec[i], fvel[i]);
	}
	#endif
	fprintf(stderr,"\t...done!\n");

	// ALLOCATE the halogen_2pcf array
	halogen_2pcf = (double **) calloc(Nalpha,sizeof(double *));
	halogen_err = (double **) calloc(Nalpha,sizeof(double *));

	nend = 0;
	dd = (unsigned long long *) calloc(total_nr,sizeof(unsigned long long));
	for(ii=0;ii<Nalpha;ii++){
		(halogen_2pcf)[ii] = (double *) calloc(total_nr,sizeof(double));
		(halogen_err)[ii] = (double *) calloc(total_nr,sizeof(double));
		while(HaloMass[nend]>mcuts[ii] && nend<Nhalos){
			nend++;
		}
		if(nend==Nhalos){
			fprintf(stderr,"ERROR: HALOMASSES DON'T REACH MALPHA_MIN\n");
			return -1;
		}
		// Do the correlation
		correlate(nend, Lbox,hx,hy,hz,halogen_2pcf[ii],halogen_err[ii], dd,total_nr,maxr,160);
	}

	// OUTPUT
	FILE* tpcfile;
	FILE* errfile;
	tpcfile = fopen(OutputHalogen2PCF,"w");
	errfile = fopen(OutputHalogenErr,"w");
	if(tpcfile==NULL){
		fprintf(stderr,"UNABLE TO OPEN NBODY 2PCF FILE\n");
		exit(1);
	}
	if(errfile==NULL){
		fprintf(stderr,"UNABLE TO OPEN NBODY 2PCF FILE\n");
		exit(1);
	}

	fprintf(stderr,"OPENED TPC AND ERR\n");
	for(i=0;i<total_nr;i++){
		fprintf(tpcfile,"%e\t",(i+0.5)*dr);
		fprintf(errfile,"%e\t",(i+0.5)*dr);
		for(j=0;j<Nalpha;j++){
			fprintf(tpcfile,"%e\t",halogen_2pcf[j][i]);
			fprintf(errfile,"%e\t",halogen_err[j][i]);
		}
		fprintf(stderr,"\n");
		fprintf(tpcfile,"\n");
		fprintf(errfile,"\n");
	}
	fclose(tpcfile);
	fclose(errfile);

	fprintf(stderr,"outputted tpc and errfile\n");
	FILE* alphafile;
	alphafile = fopen(OutputAlphaM,"w");
	for(i=0;i<Nalpha;i++){
		fprintf(alphafile,"%e\t%e\t%e\n",mcuts[i],alphavec[i],fvel[i]);
	}
	fclose(alphafile);
	for(ii=0;ii<Nalpha;ii++){
		free((halogen_2pcf)[ii]);
		free((halogen_err)[ii]);
	}
	// TBD: change this for a loop correcting velocities or change it on the fly while writing
	place_halos(Nhalos,HaloMass, Nlin, Npart, x, y, z, vx,vy,vz,Lbox,
				rho,seed,
				mpart,nthreads, alphavec, betavec, mcuts, Nalpha, recalc_frac,hx, hy, hz,
				hvx,hvy,hvz, hR,ListOfParticles,NPartPerCell);	
	fprintf(stderr,"Writing an example halo catalog to %s\n",OutputExampleCat);
	write_halogen_cat(OutputExampleCat, hx, hy, hz, hvx, hvy,hvz, HaloMass, hR,Nhalos,fvel,mcuts);
	fprintf(stderr,"...done!\n");
	free(halogen_2pcf);
	free(halogen_err);
	free(dd);	
	free(hvx);
	free(hvy);
	free(hvz);
	free(hx);	
	free(hy);	
	free(hz);	
	free(hR);	


	fprintf(stderr,"\n*******************************************************************\n");
	fprintf(stderr,"**                                     ... the fit is complete.  **\n");
	fprintf(stderr,"*******************************************************************\n\n");

	return 0;
}
Beispiel #19
0
int main(){

	// Initialize
	options probdata = {};
	Initialization(probdata);
	read_input_file("HDDP_input.txt", &probdata);
	options nominal = probdata;
	ForwardPass(probdata, nominal);
	eval_J(probdata);
	nominal = probdata;

	// Enter the HDDP Loop
	int current_iter = 0;
	int go_to_step = 1;
	bool converged = 0;

	WriteTrajectory(nominal, current_iter);

	// construct a trivial random generator engine from a time-based seed:
	unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
	std::default_random_engine generator(seed);
	std::uniform_real_distribution<double> distribution(0.0, 1.0);

	while (!converged && probdata.delta > probdata.delta_min)
		HDDP(probdata, nominal, go_to_step, current_iter, converged);
	/*
	// MBH
	int max_MBH_iterations = 1000;
	double alpha = 1.5;
	for (int i = 0; i < max_MBH_iterations; i++){
		WriteTrajectory(nominal);
		options probdata = {};
		Initialization(probdata);
		options perturbed = probdata;

		for (int stage = 0; stage < probdata.nstages; stage++){
			for (int k = 8; k < 11; k++){
				double s = distribution(generator);
				double r = ((alpha - 1.0) / SMALL) / pow((SMALL / (SMALL + distribution(generator))), -alpha);
				perturbed.traj[stage][k] = nominal.traj[stage][k] + s*r;
				//cout << s << " " << r << " " << s*r << "\n";
			}

		}

		ForwardPass(probdata, perturbed);
		probdata.Multipliers = nominal.Multipliers;
		eval_J(probdata);
		perturbed = probdata;

		go_to_step = 1;
		converged = 0;
		while (!converged)
			HDDP(probdata, perturbed, go_to_step, current_iter, converged);
		if (perturbed.J < nominal.J){
			nominal = perturbed;
		}

	}
	*/
	// Save the Trajectory
	probdata.Multipliers.print_to_screen();
	return 0;
}
Beispiel #20
0
int main(int argc, char **argv){

	fprintf(stderr,"\n*******************************************************************\n");
	fprintf(stderr,"**                                                               **\n");
	fprintf(stderr,"**            =           HALOGEN V0.3          =                **\n");
	fprintf(stderr,"**                                                               **\n");
	fprintf(stderr,"**                                                               **\n");
	fprintf(stderr,"**                                            let there be dark  **\n");
	fprintf(stderr,"*******************************************************************\n\n");

	if (argc!=2){
		fprintf(stderr,"usage: %s inputfile\n",argv[0]);	
		return -1;
	}

	float Lbox, mpart, *x, *y, *z, *hx, *hy, *hz, *hR, om_m;	
	char inname[256];
	long Npart, Nhalos;
	float *HaloMass, rho;

	strcpy(inname,argv[1]);

#ifdef VERB
	fprintf(stderr,"#def VERB\n");
#endif 
#ifdef DEBUG
	fprintf(stderr,"#def DEBUG \n");
#endif
#ifdef ULTRADEBUG
	fprintf(stderr,"#def ULTRADEBUG \n");
#endif
#ifdef ONLYBIG
	fprintf(stderr,"#def ONLYBIG\n");
#endif


	fprintf(stderr,"\nReading input file...\n");
	if (read_input_file(inname)<0)
		return -1;
	fprintf(stderr,"... file read correctly!\n");


	fprintf(stderr,"Reading Gadget file(s)...\n");
	if (read_snapshot(Snapshot, format, LUNIT, MUNIT, SWP, LGADGET, DGADGET,&x, &y, &z, &Npart, &mpart, &Lbox, &om_m)==0)
		fprintf(stderr,"Gadget file(s) correctly read!\n");
	else {
		fprintf(stderr,"error: Something went wrong reading the gadget file %s\n",inname);
		return -1;
	}
	
	#ifdef VERB
	fprintf(stderr,"\n\tCheck: Npart=%ld, mpart=%e, Lbox=%f\n",Npart,mpart,Lbox);
	fprintf(stderr,"\tx[0]= %f, y[0]= %f, z[0]= %f\n",x[0],y[0],z[0]);
	fprintf(stderr,"\t      ...\n");
	fprintf(stderr,"\tx[%ld]= %f, y[%ld]= %f, z[%ld]= %f\n\n",Npart-1,x[Npart-1],Npart-1,y[Npart-1],Npart-1,z[Npart-1]);
	#endif

	//Generate the halo masses from the mass function
	fprintf(stderr,"Generating Halo Masses...\n");
	Nhalos = populate_mass_function(MassFunctionFile,Mmin*mpart,Lbox,&HaloMass);
	if (Nhalos<0)
		fprintf(stderr,"error: Couldnt create HaloMass array\n");	
	fprintf(stderr,"...Halo Masses Generated\n");

	//Allocalte memory for the halo XYZ and R
	hx = (float *) calloc(Nhalos,sizeof(float));
	hy = (float *) calloc(Nhalos,sizeof(float));
	hz = (float *) calloc(Nhalos,sizeof(float));
	hR = (float *) calloc(Nhalos,sizeof(float));

	
	if (strcmp(rho_ref,"crit")==0)
		rho = OVD*rho_crit;
	else 
		rho = OVD*rho_crit*om_m;

	//place the halos
	fprintf(stderr,"Placing halos down...\n");
	if (place_halos(Nhalos, HaloMass, Nlin, Npart, x, y, z, Lbox, rho,-1,mpart, alpha, Malpha, Nalpha, hx, hy, hz,hR)==0)
		fprintf(stderr,"\n...Halos placed!\n");
	else
		fprintf(stderr,"error in placing the halos\n");
	
	//writting output	
	fprintf(stderr,"Writing Halo catalogue...\n");
	write_halogen_cat(OutputFile,hx,hy,hz,HaloMass,hR,Nhalos);
	fprintf(stderr,"...halo catalogue written in %s\n",OutputFile);
	
	free(hx);free(hy);free(hz);free(hR);
	free(alpha); free(Malpha);


	fprintf(stderr,"\n*******************************************************************\n");
	fprintf(stderr,"**                        ... and there were dark matter haloes  **\n");
	fprintf(stderr,"*******************************************************************\n\n");

	return 0;	
}
Beispiel #21
0
int main(int argc, char **argv){

	fprintf(stderr,"\n*******************************************************************\n");
	fprintf(stderr,"**                                                               **\n");
	fprintf(stderr,"**            =         HALOGEN V0.7.3          =                **\n");
	fprintf(stderr,"**                                                               **\n");
	fprintf(stderr,"**                                                               **\n");
	fprintf(stderr,"**                                            let there be dark  **\n");
	fprintf(stderr,"*******************************************************************\n\n");

	if (argc!=2){
		fprintf(stderr,"usage: %s inputfile\n",argv[0]);	
		return -1;
	}

	float Lbox, mpart, *x, *y, *z, *vx,*vy,*vz,*hx, *hy, *hz, *hvx,*hvy,*hvz,*hR, om_m;	
	char inname[256];
	long Npart, Nhalos, **ListOfParticles, *NPartPerCell;
	float *HaloMass, rho;
	double *MassLeft;
	float *dens;
	long i;

	strcpy(inname,argv[1]);

#ifdef VERB
	fprintf(stderr,"#def VERB\n");
#endif 
#ifdef DEBUG
	fprintf(stderr,"#def DEBUG \n");
#endif
#ifdef ULTRADEBUG
	fprintf(stderr,"#def ULTRADEBUG \n");
#endif
#ifdef ONLYBIG
	fprintf(stderr,"#def ONLYBIG\n");
#endif
#ifdef NO_EXCLUSION
	fprintf(stderr,"#def NO_EXCLUSION\n");
#endif
#ifdef NO_MASS_CONSERVATION
	fprintf(stderr,"#def NO_MASS_CONSERVATION\n");
#endif
#ifdef MASS_OF_PARTS
	fprintf(stderr,"#def MASS_OF_PARTS\n");
#endif
#ifdef RANKED
	fprintf(stderr,"#def RANKED\n");
#endif
#ifdef NDENS
	fprintf(stderr,"#def NDENS\n");
#endif
#ifdef NGP
	fprintf(stderr,"#def NGP\n");
#endif


	fprintf(stderr,"\nReading input file...\n");
	if (read_input_file(inname)<0)
		return -1;
	fprintf(stderr,"... file read correctly!\n");


	fprintf(stderr,"Reading Gadget file(s)...\n");
	if (read_snapshot(Snapshot, format, LUNIT, MUNIT, SWP, LGADGET, DGADGET,Nlin,nthreads,&x, &y, &z, &vx, &vy, &vz, &Npart, &mpart, &Lbox, &om_m,&ListOfParticles,&NPartPerCell,&MassLeft,&dens)==0)
		fprintf(stderr,"Gadget file(s) correctly read!\n");
	else {
		fprintf(stderr,"error: Something went wrong reading the gadget file %s\n",inname);
		return -1;
	}
	
	#ifdef VERB
	fprintf(stderr,"\n\tCheck: Npart=%ld, mpart=%e, Lbox=%f\n",Npart,mpart,Lbox);
	fprintf(stderr,"\tx[0]= %f, y[0]= %f, z[0]= %f\n",(x)[0],(y)[0],(z)[0]);
	fprintf(stderr,"\t      ...\n");
	fprintf(stderr,"\tx[%ld]= %f, y[%ld]= %f, z[%ld]= %f\n\n",Npart-1,(x)[Npart-1],Npart-1,(y)[Npart-1],Npart-1,(z)[Npart-1]);
	#endif
	
	//TEMPORARY OUTPUT FOR TESTING AGAINST 0.6.7
	for(i=0;i<10;i++){
		fprintf(stderr,"ListOfParticles[%ld][0] = %ld, NPartPerCell[%ld] = %ld\n",i,ListOfParticles[i][0],i,NPartPerCell[i]);
	}

	if (seed<0){
		seed = time(NULL);
		fprintf(stderr,"Seed used: %ld\n",seed);
	}

	//Generate the halo masses from the mass function
	fprintf(stderr,"Generating Halo Masses...\n");
	Nhalos = populate_mass_function(MassFunctionFile,Mmin,Lbox,&HaloMass,seed,nthreads);
	if (Nhalos<0)
		fprintf(stderr,"error: Couldnt create HaloMass array\n");	
	fprintf(stderr,"...Halo Masses Generated\n");

	// TEMPORARY OUTPUT FOR TESTING AGAINST 0.6.7
	for(i=0;i<10;i++){
		fprintf(stderr,"HaloMass[%ld] = %f\n",i,HaloMass[i]);
	}
	for(i=Nhalos-10;i<Nhalos;i++){
		fprintf(stderr,"HaloMass[%ld] = %f\n",i,HaloMass[i]);
	}

	//Allocalte memory for the halo XYZR, and MassLeft vector
	hx = (float *) calloc(Nhalos,sizeof(float));
	hy = (float *) calloc(Nhalos,sizeof(float));
	hz = (float *) calloc(Nhalos,sizeof(float));
	hvx = (float *) calloc(Nhalos,sizeof(float));
	hvy = (float *) calloc(Nhalos,sizeof(float));
	hvz = (float *) calloc(Nhalos,sizeof(float));
	hR = (float *) calloc(Nhalos,sizeof(float));
	
	//MassLeft = (double *) calloc(Nlin*Nlin*Nlin,sizeof(double));
	
	//density at the boundary of a halo
	if (strcmp(rho_ref,"crit")==0)
		rho = OVD*rho_crit;
	else 
		rho = OVD*rho_crit*om_m;

	//place the halos
	fprintf(stderr,"Placing halos down...\n");
	
	// Check the M-alpha vector against produced halos.
	fprintf(stderr,"MALPHA, HALOMASS: %e, %e", Malpha[Nalpha-1],HaloMass[Nhalos-1]);
	if( Malpha[Nalpha-1] > HaloMass[Nhalos-1]){
		if (Malpha[Nalpha-1] < 1.2*HaloMass[Nhalos-1]) {
			Malpha[Nalpha-1] = HaloMass[Nhalos-1]/1.01;
		}
		else{
			fprintf(stderr,"ERROR: LOWEST M(alpha) LARGER THAN LOWEST MASS: %e < %e",Malpha[Nalpha-1],HaloMass[Nhalos-1]);
			exit(0);
		}
	}
	fprintf(stderr,"MALPHA, HALOMASS: %e, %e", Malpha[Nalpha-1],HaloMass[Nhalos-1]);

	fprintf(stderr,"\n");
	if (place_halos(Nhalos,HaloMass, Nlin, Npart, x, y, z, vx,vy,vz,Lbox, rho,seed,mpart, nthreads,alpha, betavec, Malpha, Nalpha,recalc_frac,hx, hy, hz, hvx,hvy,hvz, hR,ListOfParticles,NPartPerCell,MassLeft,dens)==0){
		fprintf(stderr,"...halos placed correctly\n");
	}


	/*
	int place_halos(long Nend, float *HaloMass, long Nlin, long NTotPart, float *PartX,
                float *PartY, float *PartZ, float *PartVX, float *PartVY, float *PartVZ,
                float L, float rho_ref, long seed, float mp, int nthreads, double *alpha, double *beta, double *Malpha,
                long Nalpha,int Nrecalc, float *HaloX, float *HaloY, float *HaloZ, float *HaloVX,
                float *HaloVY, float *HaloVZ,float *HaloR,long **ListOfPart,
                long *NPartPerCell,double *RemMass, float *dens){
*/


	else {
		fprintf(stderr,"Problem placing halos\n");
		return -1;
	}
	fprintf(stderr,"\n");

	for(i=0;i<10;i++){
		fprintf(stderr,"(hx, hy, hz)[%ld] = (%f, %f, %f)",i,hx[i],hy[i],hz[i]);
	}
	for(i=Nhalos-10;i<Nhalos;i++){
		fprintf(stderr,"(hx, hy, hz)[%ld] = (%f, %f, %f)",i,hx[i],hy[i],hz[i]);
	}
	//writting output	
	fprintf(stderr,"Writing Halo catalogue...\n");
	write_halogen_cat(OutputFile,hx,hy,hz,hvx,hvy,hvz,HaloMass,hR,Nhalos);
	fprintf(stderr,"...halo catalogue written in %s\n",OutputFile);
	
	free(hx);free(hy);free(hz);free(hR);
	free(alpha); free(Malpha);


	fprintf(stderr,"\n*******************************************************************\n");
	fprintf(stderr,"**                        ... and there were dark matter haloes  **\n");
	fprintf(stderr,"*******************************************************************\n\n");

	return 0;	
}
Beispiel #22
0
int valid_main( int argc, char *argv[] )
{
    char *fout;
    int   i, j,k,iethpo, pothie;
    FILE *outfp = 0;



    printf("\nPORTA - a POlyhedron Representation Transformation Algorithm\n");
    printf(  "Version %s\n\n", VERSION );

    printf( "Written by Thomas Christof (Uni Heidelberg)\n" );
    printf( "Revised by Andreas Loebel (ZIB Berlin)\n\n" );

    printf( "PORTA is free software and comes with ABSOLUTELY NO WARRENTY! You are welcome\n" );
    printf( "to use, modify, and redistribute it under the GNU General Public Lincese.\n\n" ); 
    
    printf( "This is the program VALID from the PORTA package.\n\n" );

    if( argc <= 2 )
    {
        fprintf( stderr,
                "For more information read the manpages about porta.\n\n");
        exit(-1);
    }
            
    /* 17.01.1994: include logging on file porta.log */
    if( !(logfile = fopen( "porta.log", "a" )) )
        fprintf( stderr, "can't open logfile porta.log\n" );
    else
    {
        porta_log( "\n\n\nlog for " );
        for( i = 0; i < argc; i++ )
            porta_log( "%s ", argv[i] );
        porta_log( "\n\n" );
    }
            

    initialize();
    set_I_functions();
    SET_MP_not_ready;
    
    prt = stdout;
    get_options(&argc,&argv);
    
    if (option & Protocol_to_file) 
    {
        strcat(*argv,".prt");
        prt = fopen(*argv,"w");
        (*argv)[strlen(*argv)-4] = '\0';
    }
    setbuf(prt,CP 0);
    
    if (is_set(Vint) && !strcmp(*argv+strlen(*argv)-4,".ieq")) 
    {  
            char *cp1,*cp2;
        cp1=strdup("LOWER_BOUNDS");
        cp2=strdup("UPPER_BOUNDS");
        if(!cp1||!cp2)
            msg("allocation of new space failed", "", 0 );   
        points = read_input_file(*argv,outfp,&dim,&ar1,(int *)&nel_ar1,
            cp1,&lowbds,cp2,&upbds,"\0",(RAT **)&i);
        free(cp1);free(cp2);
        sort_eqie_cvce(ar1,points,dim+2,&equa,&ineq);
        valid_ints( dim, ar1, equa, dim+2, dim,
                    ar1+(dim+2)*equa, ineq, dim+2, *argv );
    }
    else 
    {
        pothie = !strcmp(*argv+strlen(*argv)-4,".poi") 
            && !strcmp(*(argv+1)+strlen(*(argv+1))-4,".ieq");
        iethpo = !strcmp(*argv+strlen(*argv)-4,".ieq") 
            && !strcmp(*(argv+1)+strlen(*(argv+1))-4,".poi");
        if (!iethpo && !pothie)
            msg("invalid format of command line", "", 0 );
        
        if (iethpo) 
        {
            ineq = read_input_file(*argv,outfp,&dim,&ar1,(int *)&nel_ar1,
                                   "\0",(int **)&i,"\0",(int **)&i,"\0",(RAT **)&i );
            points = read_input_file(*(argv+1),outfp,&j,&ar2,(int *)&nel_ar2,
                                     "\0",(int **)&i,"\0",(int **)&i,"\0",(RAT **)&i );
        }
        else 
        {
            ineq = read_input_file(*(argv+1),outfp,&dim,&ar1, (int *)&nel_ar1,
                                   "\0", (int **)&i,"\0", (int **)&i,"\0", (RAT **)&i );
            points = read_input_file(*argv,outfp,&j,&ar2, (int *)&nel_ar2,
                                     "\0", (int **)&i,"\0", (int **)&i,"\0", (RAT **)&i );
        }
        if (j != dim) 
            msg("dimensions in input files are different", "", 0 ); 
        
        if (is_set(Iespo)) 
        {
            sort_eqie_cvce(ar1,ineq,dim+2,&equa,&ineq);
            valid_ieqs(dim,ar1,ineq+equa,&equa,&ineq,dim+2,
                       ar2,points,dim+1,(char **)(pothie?*argv:*(argv+1)));
        }
        else if (is_set(Posie) || is_set(Cfctp)) 
        {
            fout = iethpo?*argv:*(argv+1);
            sort_eqie_cvce(ar2,points,dim+1,&cone,&conv);
            if (is_set(Posie))
                valid_points(dim,ar2,points,dim+1,
                             ar1,ineq,dim+2,0,(char **)fout);
            else 
            {
                char fname[100];
                char command[100];
                RAT *ar1p;
                sort_eqie_cvce(ar1,ineq,dim+2,&equa,&ineq);
                if (equa )
                    msg( "only inequalities are allowed", "" , 0 );
                
                for (i = 0,ar1p = ar1; i < ineq; i++, ar1p += dim+2) 
                {
                    sprintf(fname,"%s%i",fout,i+1);
                    fprintf(prt,"I n e q u a l i t y   %2i :\n",i+1);
                    fprintf(prt,"==========================\n\n");
                    
                    /* 17.01.1994: include logging on file porta.log */
                    porta_log( "I n e q u a l i t y   %2i :\n",i+1);
                    porta_log( "==========================\n\n");
                    
                    fprintf(prt,"computing points  i n v a l i d  for the inequality :\n");
                    fprintf(prt,"=====================================================\n");

                    /* 17.01.1994: include logging on file porta.log */
                    porta_log( "computing points  i n v a l i d  for the inequality :\n");
                    porta_log( "=====================================================\n");

                    var[3].num = -1; var[3].den.i = 1;
                    scal_mul(var+3,ar1p,ar1p,dim+1);
                    j = valid_points(dim,ar2,points,dim+1,
                                     ar1p,1,dim+2,1, (char **)fname);
                    (ar1p+dim+1)->num = 0;
                    fprintf(prt,"computing points satisfying inequalitiy with equation :\n");
                    fprintf(prt,"=======================================================\n");
                    
                    /* 17.01.1994: include logging on file porta.log */
                    porta_log( "computing points satisfying inequalitiy with equation :\n");
                    porta_log( "=======================================================\n");
                    
                    if (j) strcat(fname,".poi");
                    k = valid_points(dim,ar2,points,dim+1,
                                     ar1p,1,dim+2,0, (char **)fname);
                    strcat(fname,".poi");
                    if (!j && k) 
                    {
                        sprintf(command,"dim %s",fname);
                        fprintf(prt,"dimension of the points :\n");
                        fprintf(prt,"=========================\n");
                        fflush(prt);
                        
                        /* 17.01.1994: include logging on file porta.log */
                        porta_log( "dimension of the points :\n");
                        porta_log( "=========================\n");
                        fflush( logfile );
                        
                        system(command);
                    }
                }
                
            }
        }
        else 
            msg( "invalid format of command line", "", 0 );
    } 

    return 0;
}
Beispiel #23
0
int main(int argc, char *argv[])
{
  int i, rc;
  int myRank, numProcs;
  float ver;
  struct Zoltan_Struct *zz;
  int changes, numGidEntries, numLidEntries, numImport, numExport, start_gid, num_nbors;
  ZOLTAN_ID_PTR importGlobalGids, importLocalGids, exportGlobalGids, exportLocalGids;
  int *importProcs, *importToPart, *exportProcs, *exportToPart;
  int *parts=NULL;
  ZOLTAN_ID_PTR lids=NULL;
  FILE *fp;
  struct Zoltan_DD_Struct *dd;
  GRAPH_DATA myGraph;
  int gid_length = 1;   /* our global IDs consist of 1 integer */
  int lid_length = 1;   /* our local IDs consist of 1 integer */

  /******************************************************************
  ** Initialize MPI and Zoltan
  ******************************************************************/

  MPI_Init(&argc, &argv);
  MPI_Comm_rank(MPI_COMM_WORLD, &myRank);
  MPI_Comm_size(MPI_COMM_WORLD, &numProcs);

  rc = Zoltan_Initialize(argc, argv, &ver);

  if (rc != ZOLTAN_OK){
    printf("sorry...\n");
    MPI_Finalize();
    exit(0);
  }

  /******************************************************************
  ** Read graph from input file and distribute it 
  ******************************************************************/

  fp = fopen(fname, "r");
  if (!fp){
    if (myRank == 0) fprintf(stderr,"ERROR: Can not open %s\n",fname);
    MPI_Finalize();
    exit(1);
  }
  fclose(fp);

  read_input_file(myRank, numProcs, fname, &myGraph);

  /*fprintf(stderr,"%d have %d objects\n",myRank,myGraph.numMyVertices);*/

  /******************************************************************
  ** Create a distributed data directory which maps vertex
  ** global IDs to their current partition number.  We'll use this
  ** after migrating vertices, to update the partition in which
  ** our vertices neighbors are.
  **
  ** Our local IDs (array "lids") are of type ZOLTAN_ID_TYPE because
  ** we are using Zoltan's distributed data directory.  It assumes
  ** that a global ID is a sequence of "gid_length" ZOLTAN_ID_TYPEs.
  ** It assumes that a local ID is a sequence of "lid_length"
  ** ZOLTAN_ID_TYPEs.
  ******************************************************************/

  rc = Zoltan_DD_Create(&dd, MPI_COMM_WORLD, 
                           gid_length,    /* length of a global ID */
                           lid_length,    /* length of a local ID */
                           0,             /* length of user data  */
                           myGraph.numMyVertices,  /* hash table size */
                           0);                     /* debug level */

  parts = malloc(myGraph.numMyVertices * sizeof(int));
  lids = malloc(myGraph.numMyVertices * sizeof(ZOLTAN_ID_TYPE));
  
  for (i=0; i < myGraph.numMyVertices; i++){
    parts[i] = myRank;   /* part number of this vertex */
    lids[i] = (ZOLTAN_ID_TYPE)i;         /* local ID on my process for this vertex */
  }
  
  rc = Zoltan_DD_Update(dd, 
                        myGraph.vertexGID, 
                        lids,
                        NULL,
                        parts,
                        myGraph.numMyVertices);
  

  myGraph.dd = dd;

  /******************************************************************
  ** Create a Zoltan library structure for this instance of load
  ** balancing.  Set the parameters and query functions that will
  ** govern the library's calculation.  See the Zoltan User's
  ** Guide for the definition of these and many other parameters.
  ******************************************************************/

  zz = Zoltan_Create(MPI_COMM_WORLD);

  /* General parameters */

  Zoltan_Set_Param(zz, "DEBUG_LEVEL", "0");
  Zoltan_Set_Param(zz, "LB_METHOD", "GRAPH");
  Zoltan_Set_Param(zz, "LB_APPROACH", "PARTITION");
  Zoltan_Set_Param(zz, "NUM_GID_ENTRIES", "1"); 
  Zoltan_Set_Param(zz, "NUM_LID_ENTRIES", "1");
  Zoltan_Set_Param(zz, "RETURN_LISTS", "ALL");

  /* Graph parameters */

  Zoltan_Set_Param(zz, "CHECK_GRAPH", "2"); 
  Zoltan_Set_Param(zz, "PHG_EDGE_SIZE_THRESHOLD", ".35");  /* 0-remove all, 1-remove none */

  /* Query functions, defined in this source file */

  Zoltan_Set_Num_Obj_Fn(zz, get_number_of_vertices, &myGraph);
  Zoltan_Set_Obj_List_Fn(zz, get_vertex_list, &myGraph);
  Zoltan_Set_Num_Edges_Multi_Fn(zz, get_num_edges_list, &myGraph);
  Zoltan_Set_Edge_List_Multi_Fn(zz, get_edge_list, &myGraph);

  Zoltan_Set_Obj_Size_Multi_Fn(zz, get_message_sizes,&myGraph);
  Zoltan_Set_Pack_Obj_Multi_Fn(zz, pack_object_messages,&myGraph);
  Zoltan_Set_Unpack_Obj_Multi_Fn(zz, unpack_object_messages,&myGraph);
  Zoltan_Set_Mid_Migrate_PP_Fn(zz, mid_migrate,&myGraph);

  /******************************************************************
  ** Visualize the graph partitioning before calling Zoltan.
  ******************************************************************/

  if (myRank== 0){
    printf("\nGraph partition before calling Zoltan\n");
  }

  showGraphPartitions(myRank, myGraph.dd);

  /******************************************************************
  ** Zoltan can now partition the simple graph.
  ** In this simple example, we assume the number of partitions is
  ** equal to the number of processes.  Process rank 0 will own
  ** partition 0, process rank 1 will own partition 1, and so on.
  ******************************************************************/

  rc = Zoltan_LB_Partition(zz, /* input (all remaining fields are output) */
        &changes,        /* 1 if partitioning was changed, 0 otherwise */ 
        &numGidEntries,  /* Number of integers used for a global ID */
        &numLidEntries,  /* Number of integers used for a local ID */
        &numImport,      /* Number of vertices to be sent to me */
        &importGlobalGids,  /* Global IDs of vertices to be sent to me */
        &importLocalGids,   /* Local IDs of vertices to be sent to me */
        &importProcs,    /* Process rank for source of each incoming vertex */
        &importToPart,   /* New partition for each incoming vertex */
        &numExport,      /* Number of vertices I must send to other processes*/
        &exportGlobalGids,  /* Global IDs of the vertices I must send */
        &exportLocalGids,   /* Local IDs of the vertices I must send */
        &exportProcs,    /* Process to which I send each of the vertices */
        &exportToPart);  /* Partition to which each vertex will belong */

  if (rc != ZOLTAN_OK){
    printf("sorry...\n");
    MPI_Finalize();
    Zoltan_Destroy(&zz);
    exit(0);
  }

  /*fprintf(stderr,"%d export %d import %d\n",myRank,numExport,numImport);*/

  /******************************************************************
  ** Update the data directory with the new partition numbers
  ******************************************************************/

  for (i=0; i < numExport; i++){
    parts[exportLocalGids[i]] = exportToPart[i];
  }

  rc = Zoltan_DD_Update(dd, 
                        myGraph.vertexGID, 
                        lids,
                        NULL,
                        parts,
                        myGraph.numMyVertices);

  /******************************************************************
  ** Migrate vertices to new partitions
  ******************************************************************/

  rc = Zoltan_Migrate(zz, 
                      numImport, importGlobalGids, importLocalGids,
                      importProcs, importToPart,
                      numExport, exportGlobalGids, exportLocalGids,
                      exportProcs, exportToPart);


  /******************************************************************
  ** Use the data dictionary to find neighbors' partitions
  ******************************************************************/

  start_gid = myGraph.numMyVertices - numImport;
  num_nbors = myGraph.nborIndex[myGraph.numMyVertices] - myGraph.nborIndex[start_gid];

  rc = Zoltan_DD_Find(dd,
             (ZOLTAN_ID_PTR)(myGraph.nborGID + start_gid), NULL, NULL, 
              myGraph.nborPart + start_gid, num_nbors, NULL);

  /******************************************************************
  ** Visualize the graph partitioning after calling Zoltan.
  ******************************************************************/

  if (myRank == 0){
    printf("Graph partition after calling Zoltan\n");
  }
  showGraphPartitions(myRank, myGraph.dd);

  /******************************************************************
  ** Free the arrays allocated by Zoltan_LB_Partition, and free
  ** the storage allocated for the Zoltan structure.
  ******************************************************************/

  Zoltan_LB_Free_Part(&importGlobalGids, &importLocalGids, 
                      &importProcs, &importToPart);
  Zoltan_LB_Free_Part(&exportGlobalGids, &exportLocalGids, 
                      &exportProcs, &exportToPart);

  Zoltan_Destroy(&zz);

  /**********************
  ** all done ***********
  **********************/

  MPI_Finalize();

  if (myGraph.vertex_capacity > 0){
    free(myGraph.vertexGID);
    free(myGraph.nborIndex);
    if (myGraph.nbor_capacity > 0){
      free(myGraph.nborGID);
      free(myGraph.nborPart);
    }
  }

  if (parts) free(parts);
  if (lids) free(lids);

  return 0;
}
Beispiel #24
0
int main(int argc, char **argv)
{
    /* setup up space to pass stuff around in */
    control *c;
    if ((c = malloc(sizeof(control))) == NULL) {
        check_errors("Control structure: Not allocated enough memory", __LINE__);
     }
    
    timeseries *ts;
    if ((ts = malloc(sizeof(timeseries))) == NULL) {
        check_errors("Timeseries structure: Not allocated enough memory", __LINE__);
     }
    
    meta *m;
    if ((m = malloc(sizeof(meta))) == NULL) {
        check_errors("Meta structure: Not allocated enough memory", __LINE__);
     }
    
    output_options *o;
    if ((o = malloc(sizeof(output_options))) == NULL) {
        check_errors("Output_options structure: Not allocated enough memory", __LINE__);
     }
    
    /* setup initial junk */
    setup_initial_conditions(c, ts, o);
    
    /* send sweep along the command line */
    clparse(argc, argv, c, ts, o);
    
    /* check the input file is on the stdin? */
    check_stdin(__LINE__);
    
    /* read data in from stdin */
    read_input_file(argv, c, ts, o);
    
    /* setup space for working arrays and other misc stuff */
    allocate_working_environment(c, ts);
    
    /* calculate lomb periodgram for raw time-series */
    spectrum_wrapper(c, ts, ts->x, ts->y, ts->frq, ts->gxx);
    
    /* Calculate red noise bias and correct periodgram 
        - need to generate a seed ONCE */
    srand (time(NULL));
    rednoise_bias_wrapper(c, ts, o);
    
    /* dump out what you need */
    print_outputs(c, ts, o);
    
    /* tidy up */
    free_array_double(ts->gxx);
    free_array_double(ts->frq);
    free_array_double(ts->red);
    free_array_double(ts->grr);
    free_array_double(ts->grrsum);
    free_array_double(ts->gredth);
    free_array_double(ts->corr);
    free_array_double(ts->gxxc);
    free_array_double(ts->grravg);
    free_array_double(ts->x);
    free_array_double(ts->y);  
    free(c);
    free(ts);
    free(m);
    free(o);
    
    return (0);
}
Beispiel #25
0
int main(int argc, char *argv[])
{
  int i, rc;
  float ver;
  struct Zoltan_Struct *zz;
  int changes, numGidEntries, numLidEntries, numImport, numExport;
  int myRank, numProcs;
  ZOLTAN_ID_PTR importGlobalGids, importLocalGids, exportGlobalGids, exportLocalGids;
  int *importProcs, *importToPart, *exportProcs, *exportToPart;
  int *parts;
  FILE *fp;
  GRAPH_DATA myGraph;

  /******************************************************************
  ** Initialize MPI and Zoltan
  ******************************************************************/

  MPI_Init(&argc, &argv);
  MPI_Comm_rank(MPI_COMM_WORLD, &myRank);
  MPI_Comm_size(MPI_COMM_WORLD, &numProcs);

  rc = Zoltan_Initialize(argc, argv, &ver);

  if (rc != ZOLTAN_OK){
    printf("sorry...\n");
    MPI_Finalize();
    exit(0);
  }

  /******************************************************************
  ** Read graph from input file and distribute it 
  ******************************************************************/

  fp = fopen(fname, "r");
  if (!fp){
    if (myRank == 0) fprintf(stderr,"ERROR: Can not open %s\n",fname);
    MPI_Finalize();
    exit(1);
  }
  fclose(fp);

  read_input_file(myRank, numProcs, fname, &myGraph);

  /******************************************************************
  ** Create a Zoltan library structure for this instance of load
  ** balancing.  Set the parameters and query functions that will
  ** govern the library's calculation.  See the Zoltan User's
  ** Guide for the definition of these and many other parameters.
  ******************************************************************/

  zz = Zoltan_Create(MPI_COMM_WORLD);

  /* General parameters */

/*
  Zoltan_Set_Param(zz, "DEBUG_LEVEL", "0");
  Zoltan_Set_Param(zz, "LB_METHOD", "GRAPH");
  Zoltan_Set_Param(zz, "NUM_GID_ENTRIES", "1"); 
  Zoltan_Set_Param(zz, "NUM_LID_ENTRIES", "1");
  Zoltan_Set_Param(zz, "OBJ_WEIGHT_DIM", "0");
  Zoltan_Set_Param(zz, "RETURN_LISTS", "ALL");
*/

     Zoltan_Set_Param(zz, "NUM_GID_ENTRIES", "1"); 
     Zoltan_Set_Param(zz, "NUM_LID_ENTRIES", "1");
     Zoltan_Set_Param(zz,"LB_METHOD","GRAPH");
#ifdef HAVE_PARMETIS
     Zoltan_Set_Param(zz,"GRAPH_PACKAGE","PARMETIS");
#else
  #ifdef HAVE_SCOTCH
     Zoltan_Set_Param(zz,"GRAPH_PACKAGE","SCOTCH");
  #endif
#endif
     Zoltan_Set_Param(zz,"EDGE_WEIGHT_DIM","1");
     Zoltan_Set_Param(zz, "OBJ_WEIGHT_DIM", "0");
     Zoltan_Set_Param(zz,"LB_APPROACH","REPARTITION");
     Zoltan_Set_Param(zz,"GRAPH_SYMMETRIZE","TRANSPOSE");
     Zoltan_Set_Param(zz,"GRAPH_SYM_WEIGHT","ADD");

  /* Graph parameters */

  Zoltan_Set_Param(zz, "CHECK_GRAPH", "2"); 
  Zoltan_Set_Param(zz, "PHG_EDGE_SIZE_THRESHOLD", ".35");  /* 0-remove all, 1-remove none */

  /* Query functions - defined in simpleQueries.h */

  Zoltan_Set_Num_Obj_Fn(zz, get_number_of_vertices, &myGraph);
  Zoltan_Set_Obj_List_Fn(zz, get_vertex_list, &myGraph);
  Zoltan_Set_Num_Edges_Multi_Fn(zz, get_num_edges_list, &myGraph);
  Zoltan_Set_Edge_List_Multi_Fn(zz, get_edge_list, &myGraph);

  /******************************************************************
  ** Zoltan can now partition the simple graph.
  ** In this simple example, we assume the number of partitions is
  ** equal to the number of processes.  Process rank 0 will own
  ** partition 0, process rank 1 will own partition 1, and so on.
  ******************************************************************/

  rc = Zoltan_LB_Partition(zz, /* input (all remaining fields are output) */
        &changes,        /* 1 if partitioning was changed, 0 otherwise */ 
        &numGidEntries,  /* Number of integers used for a global ID */
        &numLidEntries,  /* Number of integers used for a local ID */
        &numImport,      /* Number of vertices to be sent to me */
        &importGlobalGids,  /* Global IDs of vertices to be sent to me */
        &importLocalGids,   /* Local IDs of vertices to be sent to me */
        &importProcs,    /* Process rank for source of each incoming vertex */
        &importToPart,   /* New partition for each incoming vertex */
        &numExport,      /* Number of vertices I must send to other processes*/
        &exportGlobalGids,  /* Global IDs of the vertices I must send */
        &exportLocalGids,   /* Local IDs of the vertices I must send */
        &exportProcs,    /* Process to which I send each of the vertices */
        &exportToPart);  /* Partition to which each vertex will belong */

  if (rc != ZOLTAN_OK){
    printf("sorry...\n");
    MPI_Finalize();
    Zoltan_Destroy(&zz);
    exit(0);
  }

  /******************************************************************
  ** Visualize the graph partitioning before and after calling Zoltan.
  ******************************************************************/

  parts = (int *)malloc(sizeof(int) * myGraph.numMyVertices);

  for (i=0; i < myGraph.numMyVertices; i++){
    parts[i] = myRank;
  }

  if (myRank== 0){
    printf("\nGraph partition before calling Zoltan\n");
  }

  showGraphPartitions(myRank, myGraph.numMyVertices, myGraph.vertexGID, parts, numProcs);

  for (i=0; i < numExport; i++){
    parts[exportLocalGids[i]] = exportToPart[i];
  }

  if (myRank == 0){
    printf("Graph partition after calling Zoltan\n");
  }

  showGraphPartitions(myRank, myGraph.numMyVertices, myGraph.vertexGID, parts, numProcs);

  free(parts);

  /******************************************************************
  ** Free the arrays allocated by Zoltan_LB_Partition, and free
  ** the storage allocated for the Zoltan structure.
  ******************************************************************/

  Zoltan_LB_Free_Part(&importGlobalGids, &importLocalGids, 
                      &importProcs, &importToPart);
  Zoltan_LB_Free_Part(&exportGlobalGids, &exportLocalGids, 
                      &exportProcs, &exportToPart);

  Zoltan_Destroy(&zz);

  /**********************
  ** all done ***********
  **********************/

  MPI_Finalize();

  if (myGraph.numMyVertices > 0){
    free(myGraph.vertexGID);
    free(myGraph.nborIndex);
    if (myGraph.numAllNbors > 0){
      free(myGraph.nborGID);
      free(myGraph.nborProc);
    }
  }

  return 0;
}
Beispiel #26
0
int main(int argc, char **argv) {
	int i, j;
	long int procid;
	char outstring1[100];
	FILE *in, *image1, *image2, *image3, *image4, *out;
	struct parsed_options options;

	umask(000);

	cmd_init_parsed_options(&options);
	cmd_parse_options(&options, argc, argv);

	/* read location for the config file if given */
	sprintf(config_filename,"%s",options.conffile);
	read_input_file();

	nice(10);

	sprintf(instring,"%s/process_rt_data_running",tmp_dir);
	out = fopen(instring, "r");
	if (out != NULL) {
		fprintf(stderr, "\nrprocess_rt_data found a lock file ... ");
		fscanf(out, "%lu", &procid);
		fprintf(stderr, "\n  PID: %lu", procid);
		fclose(out);
		sprintf(outstring1,"/proc/%lu/cmdline",procid);
		out = fopen(outstring1, "r");
		if (out != NULL) {
			fscanf(out, "%s", outstring1);
			sprintf(instring,"process_real_time_data");
			//if( strncmp(outstring1,"/home/radio",11)==0 )
			if (strstr(outstring1, instring) != NULL) {
				fprintf(stderr, "\n  Process Exists. Exiting ...\n\n");
				fclose(out);
				exit(0);
			}
			fclose(out);
		}
		sprintf(instring,"%s/process_rt_data_running",tmp_dir);
		remove(instring);
		fprintf(stderr, "\n  Process Does Not Exist. Lock File Removed\n");
	}

	sprintf(instring,"%s/process_rt_data_running",tmp_dir);

	out = fopen(instring, "w");

	if (out != NULL) {
		fprintf(out, "%lu", (long unsigned int) getpid());
		fclose(out);
	} else {
		fprintf(stderr, "Couldn't write lock file %s?!", instring);
		exit(-1);
	}

	/* initialize the images */
	for (i = 0; i < 512; i++)
		for (j = 0; j < 920; j++) {
			im1o[i][j] = 20.;
			im2o[i][j] = 20.;
			im3o[i][j] = 20.;
			im4o[i][j] = 20.;
		}

	/* initialize the fftw3 plans */
	plan_forward1 = fftw_plan_r2r_1d(1024, fft_samples1, out1, FFTW_R2HC, FFTW_MEASURE);
	plan_forward2 = fftw_plan_r2r_1d(1024, fft_samples2, out2, FFTW_R2HC, FFTW_MEASURE);
	plan_forward3 = fftw_plan_r2r_1d(1024, fft_samples3, out3, FFTW_R2HC, FFTW_MEASURE);
	plan_forward4 = fftw_plan_r2r_1d(1024, fft_samples4, out4, FFTW_R2HC, FFTW_MEASURE);


	while (1) {
		/* read in the new data */
		read_new_samples();
		/* fft the new data */
		fft_new_samples();

		sprintf(instring,"%s/hf2_display_running",tmp_dir);
		in = fopen(instring, "r");
		if (in != NULL) {
			write_data = 1;
			fclose(in);
		} else
			write_data = 0;

		sprintf(instring,"%s/levels.grayscale",tmp_dir);
		in = fopen(instring, "r");
		if (in != NULL) {
			fscanf(in, "%d %d", &gray_min, &gray_max);
			fclose(in);
		} else {
			gray_min = 0;
			gray_max = 60.;
		}
		if (old_gray_min != gray_min || old_gray_max != gray_max)
			rescale_images();
		if (write_data) {
			sprintf(instring,"%s/test.data",tmp_dir);
			out = fopen(instring, "w");
		} else {
			printf("hf2_display not running?\n");
		}

		for (i = 0; i < 512; i++) {
			x[i] = i * df;
			memcpy(*(im1+i),&im1[i][1],919);
			memcpy(*(im2+i),&im2[i][1],919);
			memcpy(*(im3+i),&im3[i][1],919);
			memcpy(*(im4+i),&im4[i][1],919);
			memcpy((im1o+i),&im1o[i][1],919*sizeof(float));
			memcpy((im2o+i),&im2o[i][1],919*sizeof(float));
			memcpy((im3o+i),&im3o[i][1],919*sizeof(float));
			memcpy((im4o+i),&im4o[i][1],919*sizeof(float));
			r1 = out1[i];
			r2 = out2[i];
			r3 = out3[i];
			r4 = out4[i];
			im1o[512 - i][919] = r1;
			im2o[512 - i][919] = r2;
			im3o[512 - i][919] = r3;
			im4o[512 - i][919] = r4;
			v1 = a + r1 * b + 0.5;
			v2 = a + r2 * b + 0.5;
			v3 = a + r3 * b + 0.5;
			v4 = a + r4 * b + 0.5;
			if (v1 < 0)
				v1 = 0;
			if (v2 < 0)
				v2 = 0;
			if (v3 < 0)
				v3 = 0;
			if (v4 < 0)
				v4 = 0;
			if (v1 > 255)
				v1 = 255;
			if (v2 > 255)
				v2 = 255;
			if (v3 > 255)
				v3 = 255;
			if (v4 > 255)
				v4 = 255;

			im1[512 - i][919] = 255 - (unsigned char) v1;
			im2[512 - i][919] = 255 - (unsigned char) v2;
			im3[512 - i][919] = 255 - (unsigned char) v3;
			im4[512 - i][919] = 255 - (unsigned char) v4;

			if (write_data)
				fprintf(out, "%.0f %.2f %.2f %.2f\n", x[i], r1, r2, r3);
		}

		if (write_data) {
			fclose(out);

			sprintf(instring,"%s/test.image1",tmp_dir);
			image1 = fopen(instring, "w");
			fprintf(image1, "P5\n920 512\n255\n");
			fwrite(im1, sizeof(im1), 1, image1);
			fclose(image1);

			sprintf(instring,"%s/test.image2",tmp_dir);
			image2 = fopen(instring, "w");
			fprintf(image2, "P5\n920 512\n255\n");
			fwrite(im2, sizeof(im2), 1, image2);
			fclose(image2);

			sprintf(instring,"%s/test.image3",tmp_dir);
			image3 = fopen(instring, "w");
			fprintf(image3, "P5\n920 512\n255\n");
			fwrite(im3, sizeof(im3), 1, image3);
			fclose(image3);

			sprintf(instring,"%s/test.image4",tmp_dir);
			image4 = fopen(instring, "w");
			fprintf(image4, "P5\n920 512\n255\n");
			fwrite(im4, sizeof(im4), 1, image4);
			fclose(image4);
		}
		usleep(1e4);
	}
	return (0);
}
Beispiel #27
0
int main(int argc, char *argv[]) {
  Vector v1 = read_input_file(argv[1]);
  merge_sort(v1.integers, v1.size);
  free_vector(v1);
  return 0;
}
int main () {
    read_input_file();
    printf("%d\n",max_flow(0,n-1));
    return 0;
}
Beispiel #29
0
int
goma_init_(dbl *time1, int *nnodes, int *nelems,
           int *nnv_in, int *nev_in, int *i_soln, int *i_post)
     
     /*
      * Initial main driver for GOMA. Derived from a (1/93) release of
      * the rf_salsa program by
      *        
      *        Original Authors: John  Shadid (1421)
      *		                 Scott Hutchinson (1421)
      *        		         Harry Moffat (1421)
      *       
      *        Date:		12/3/92
      * 
      *
      *        Updates and Changes by:
      *                           Randy Schunk (9111)
      *                           P. A. Sackinger (9111)
      *                           R. R. Rao       (9111)
      *                           R. A. Cairncross (Univ. of Delaware)
      *        Dates:           2/93 - 6/96
      *
      *       Modified for continuation
      *                           Ian Gates
      *       Dates:            2/98 - 10/98
      *       Dates:            7/99 - 8/99
      * 
      * Last modified: Wed  June 26 14:21:35 MST 1994 [email protected]
      * Hello.
      * 
      * Note: Many modifications from an early 2/93 pre-release
      *	      version of rf_salsa were made by various persons 
      *       in order to test ideas about moving/deforming meshes...
      */ 
{
  /* Local Declarations */

  double time_start, total_time;   /* timing variables */
#ifndef PARALLEL
  struct tm *tm_ptr;               /* additional serial timing variables */
  time_t the_time;
#endif

  int error;
  int i;
  int j;
  static int first_goma_call=TRUE;

  char	**ptmp;
  static const char *yo="goma_init";

  struct Command_line_command **clc=NULL; /* point to command line structure */
  int           nclc = 0;		/* number of command line commands */

/********************** BEGIN EXECUTION ***************************************/
  
/* assume number of commands is less than or equal to the number of 
 * arguments in the command line minus 1 (1st is program name) */

  /*
  *  Get the name of the executable, yo
  */

#ifdef PARALLEL
if( first_goma_call ) {
	Argc = 1;
	Argv = (char **) smalloc( Argc*sizeof(char *) );
	Argv[0] = (char *) yo;
	MPI_Init(&Argc, &Argv);  /*PRS will have to fix this.  Too late TAB already did. */
  }
  time_start = MPI_Wtime();
#else /* PARALLEL */
  (void) time(&the_time);
  tm_ptr = gmtime(&the_time);
  time_start = (double)  ( tm_ptr->tm_sec
               + 60. * (   60. * ( tm_ptr->tm_yday * 24. + tm_ptr->tm_hour )
                                                         + tm_ptr->tm_min  )
                         );
#endif /* PARALLEL */
  *time1 = time_start;

/*   Argv = argv; */

/*   Argc = argc; */

  time_goma_started = time_start;

#ifdef PARALLEL
  /*
   * Determine the parallel processing status, if any. We need to know
   * pretty early if we're "one of many" or the only process.
   */

  error = MPI_Comm_size(MPI_COMM_WORLD, &Num_Proc);
  error = MPI_Comm_rank(MPI_COMM_WORLD, &ProcID);

  /*
   * Setup a default Proc_config so we can use utility routines 
   * from Aztec
   */

  AZ_set_proc_config(Proc_Config, MPI_COMM_WORLD);

  /* set the output limit flag if need be */

  if( Num_Proc > DP_PROC_PRINT_LIMIT ) Unlimited_Output = FALSE;

#ifdef HAVE_MPE_H
  error = MPE_Init_log();
#endif /* HAVE_MPE_H */

  Dim = 0;			/* for any hypercube legacy code...  */

#endif /* PARALLEL */
  
#ifndef PARALLEL
  Dim        = 0;
  ProcID     = 0;
  Num_Proc   = 1;
#endif /* PARALLEL */


  /*
  *   HKM - Change the ieee exception handling based on the machine and
  *         the level of debugging/speed desired. This call currently causes
  *         core dumps for floating point exceptions.
  */

  handle_ieee();
  
  log_msg("--------------");
  log_msg("GOMA begins...");

#ifdef USE_CGM
  cgm_initialize();
#endif
  /*
   * Some initial stuff that only the master process does.
   */

/*PRS: Disable this command line stuff for the jas coupled version */
/*-----------------------------------------------------------------*/
/*   if ( ProcID == 0 ) */
/*     { */
/*       if (argc > 1) */
/* 	{ */
/* 	  log_msg("Preprocessing command line options."); */
/* 	  clc = (struct Command_line_command **)  */
/* 	    smalloc( argc * sizeof(struct Command_line_command *)); */
/* 	  for (i=0; i<argc; i++) */
/* 	    { */
/* 	      clc[i] = (struct Command_line_command *)  */
/* 		smalloc(sizeof(struct Command_line_command)); */
/* 	      clc[i]->type   = 0; /\* initialize command line structure *\/ */
/* 	      clc[i]->i_val  = 0; */
/* 	      clc[i]->r_val  = 0.; */
/* 	      clc[i]->string = (char *)  */
/* 		smalloc(MAX_COMMAND_LINE_LENGTH*sizeof(char)); */
/* 	      for ( j=0; j<MAX_COMMAND_LINE_LENGTH; j++) */
/* 		{ */
/* 		  clc[i]->string[j] = '\0'; */
/* 		} */
/* #ifdef DEBUG */
/* 	      fprintf(stderr, "clc[%d]->string is at 0x%x\n", i, clc[i]->string); */
/* 	      fprintf(stderr, "clc[%d]         is at 0x%x\n", i, clc[i]); */
/* #endif */
/* 	    } */
/* 	} */

/* PRS For the JAS version we will use the default input file name "input" */
      strcpy(Input_File, "input");

/* if (argc > 1) translate_command_line(argc, argv, clc, &nclc); */
      
/*       print_code_version(); */
/*       ptmp = legal_notice; */
/*       while ( strcmp(*ptmp, LAST_LEGAL_STRING) != 0 ) */
/* 	{ */
/* 	  fprintf(stderr, "%s", *ptmp++); */
/* 	} */
/* } */

  /*
   *  Allocate the uniform problem description structure and
   *  the problem description structures on all processors
   */
  error = pd_alloc();
  EH(error, "pd_alloc problem");

#ifdef DEBUG
  fprintf(stderr, "P_%d at barrier after pd_alloc\n", ProcID);
#ifdef PARALLEL
  error = MPI_Barrier(MPI_COMM_WORLD);
#endif
#endif

  log_msg("Allocating mp, gn, ...");

  error = mp_alloc();
  EH(error, "mp_alloc problem");

  error = gn_alloc();
  EH(error, "gn_alloc problem");

  error = ve_alloc();
  EH(error, "ve_alloc problem");

  error = elc_alloc();
  EH(error, "elc_alloc problem");

  error = elc_rs_alloc();
  EH(error, "elc_alloc problem");

  error = cr_alloc();
  EH(error, "cr_alloc problem");

  error = evp_alloc();
  EH(error, "evp_alloc problem");

  error = tran_alloc();
  EH(error, "tran_alloc problem");

  error = libio_alloc();
  EH(error, "libio_alloc problem");

  error = eigen_alloc();
  EH(error, "eigen_alloc problem");

  error = cont_alloc();
  EH(error, "cont_alloc problem");

  error = loca_alloc();
  EH(error, "loca_alloc problem");

  error = efv_alloc();
  EH(error, "efv_alloc problem");

#ifdef DEBUG
  fprintf(stderr, "P_%d at barrier before read_input_file()\n", ProcID);
#ifdef PARALLEL
  error = MPI_Barrier(MPI_COMM_WORLD);
#endif
#endif

/*PRS AGAIN, NO COMMAND LINE OVERRIDES IN THIS JAS3D VERSION */
  /*
   * Read ASCII input file, data files, related exodusII FEM databases.
   */	
   if ( ProcID == 0 ) 
       { 
         log_msg("Reading input file ..."); 
         read_input_file(clc, nclc); 

       }

  /*
   * The user-defined material properties, etc. available to goma users
   * mean that some dynamically allocated data needs to be communicated.
   *
   * To handle this, sizing information from the input file scan is
   * broadcast in stages so that the other processors can allocate space
   * accordingly to hold the data.
   *
   * Note: instead of handpacking a data structure, use MPI derived datatypes
   * to gather and scatter. Pray this is done efficiently. Certainly it costs
   * less from a memory standpoint.
   */

#ifdef PARALLEL

  /*
   *  Make sure the input file was successully processed before moving on
   */
  check_parallel_error("Input file error");


  /*
   * This is some sizing information that helps fit a little bit more
   * onto the ark later on.
   */

#ifdef DEBUG
  fprintf(stderr, "P_%d at barrier before noahs_raven()\n", ProcID);
  error = MPI_Barrier(MPI_COMM_WORLD);
#endif

  noahs_raven();

#ifdef DEBUG
  fprintf(stderr, "P_%d at barrier before MPI_Bcast of Noahs_Raven\n", ProcID);
  error = MPI_Barrier(MPI_COMM_WORLD);
#endif

  MPI_Bcast(MPI_BOTTOM, 1, Noahs_Raven->new_type, 0, MPI_COMM_WORLD);

#ifdef DEBUG
  fprintf(stderr, "P_%d at barrier after Bcast/before raven_landing()\n", 
	  ProcID);
  error = MPI_Barrier(MPI_COMM_WORLD);
#endif  
  /*
   * Get the other processors ready to handle ark data.
   */

  raven_landing();

#ifdef DEBUG
  fprintf(stderr, "P_%d at barrier before noahs_ark()\n", ProcID);
  error = MPI_Barrier(MPI_COMM_WORLD);
#endif
  
  
  /*
   * This is the main body of communicated information, including some
   * whose sizes were determined because of advanced legwork by the raven.
   */

  noahs_ark();
  MPI_Bcast(MPI_BOTTOM, 1, Noahs_Ark->new_type, 0, MPI_COMM_WORLD);

  /*
   * Chemkin was initialized on processor zero during the input file
   * process. Now, distribute it to all processors
   */
#ifdef USE_CHEMKIN
  if (Chemkin_Needed) {
    chemkin_initialize_mp();
  }
#endif 

  /*
   * Once the ark has landed, there are additional things that will need to
   * be sent by dove. Example: BC_Types[]->u-BC arrays.
   *
   */

  ark_landing();

  noahs_dove();
  MPI_Bcast(MPI_BOTTOM, 1, Noahs_Dove->new_type, 0, MPI_COMM_WORLD);


#endif          /* End of ifdef PARALLEL */


  /*
   * We sent the packed line to all processors that contained geometry
   * creation commands.  Now we need to step through it and create
   * geometry as we go (including possibly reading an ACIS .sat file).
   *
   */
#ifdef USE_CGM
  create_cgm_geometry();
#endif

  /*
   * For parallel execution, assume the following variables will be changed
   * to reflect the multiple file aspect of the problem.
   *
   *	FEM file = file.exoII		--> file_3of15.exoII
   *
   *	Output EXODUS II file = out.exoII --> out_3of15.exoII
   *
   */


  /*
   * Allocate space for structures holding the EXODUS II finite element
   * database information and for the Distributed Processing information.
   *
   * These are mostly skeletons with pointers that get allocated in the
   * rd_exoII and rd_dpi routines. Remember to free up those arrays first
   * before freeing the major pointers.
   */

  EXO_ptr = alloc_struct_1(Exo_DB, 1);
  init_exo_struct(EXO_ptr);
  DPI_ptr = alloc_struct_1(Dpi, 1);
  init_dpi_struct(DPI_ptr);  

  log_msg("Reading mesh from EXODUS II file...");
  error = read_mesh_exoII(EXO_ptr, DPI_ptr);

  /*
   *   Missing files on any processor are detected at a lower level
   *   forcing a return to the higher level
   *         rd_exo -->  rd_mesh  -->  main
   *   Shutdown now, if any of the exodus files weren't found
   */
  if (error < 0) {
#ifdef PARALLEL
    MPI_Finalize();
#endif
    return(-1);
  }

  /*
   * All of the MPI_Type_commit() calls called behind the scenes that build
   * the dove, ark and raven really allocated memory. Let's free it up now that
   * the initial information has been communicated.
   */

#ifdef PARALLEL
  MPI_Type_free(&(Noahs_Raven->new_type));
  MPI_Type_free(&(Noahs_Ark->new_type));
  MPI_Type_free(&(Noahs_Dove->new_type));
#endif   

  /*
   * Setup the rest of the Problem Description structure that depends on
   * the mesh that was read in from the EXODUS II file...
   * 
   * Note that memory allocation and some setup has already been performed
   * in mm_input()...
   */

  error = setup_pd();
  EH( error, "Problem setting up Problem_Description.");
  /*
   * Let's check to see if we need the large elasto-plastic global tensors
   * and allocate them if so 
   */
  error = evp_tensor_alloc(EXO_ptr);
  EH( error, "Problems setting up evp tensors");
  
  /*
   * Now that we know about what kind of problem we're solving and the
   * mesh information, let's allocate space for elemental assembly structures
   *
   */
#ifdef DEBUG
  DPRINTF(stderr, "About to assembly_alloc()...\n");
#endif
  log_msg("Assembly allocation...");

  error = assembly_alloc(EXO_ptr);
  EH( error, "Problem from assembly_alloc");

  if (Debug_Flag)  {
    DPRINTF(stderr, "%s:  setting up EXODUS II output files...\n", yo);
  }

  /*
   * These are not critical - just niceties. Also, they should not overburden
   * your db with too much of this - they're capped verbiage compliant routines.
   */

  add_qa_stamp(EXO_ptr);

  add_info_stamp(EXO_ptr);

#ifdef DEBUG
  fprintf(stderr, "added qa and info stamps\n");
#endif

  /*
   * If the output EXODUS II database file is different from the input
   * file, then we'll need to replicate all the basic mesh information.
   * But, remember that if we're parallel, that the output file names must
   * be multiplexed first...
   */
  if ( Num_Proc > 1 )
    {
      multiname(ExoFileOut,     ProcID, Num_Proc);      
      multiname(Init_GuessFile, ProcID, Num_Proc);

      if ( strcmp( Soln_OutFile, "" ) != 0 )
	{
	  multiname(Soln_OutFile,   ProcID, Num_Proc);
	}

      if( strcmp( ExoAuxFile, "" ) != 0 )
        {
          multiname(ExoAuxFile,     ProcID, Num_Proc);
        }

      if( efv->Num_external_field != 0 )
        {
          for( i=0; i<efv->Num_external_field; i++ )
            {
              multiname(efv->file_nm[i], ProcID, Num_Proc);
            }
        }

    }



  /***********************************************************************/
  /***********************************************************************/
  /***********************************************************************/
  /*
   *   Preprocess the exodus mesh
   *        -> Allocate pointers to structures containing element
   *           side bc info, First_Elem_Side_BC_Array, and
   *           element edge info, First_Elem_Edge_BC_Array.
   *        -> Determine Unique_Element_Types[] array
   */
#ifdef DEBUG
  fprintf(stderr, "pre_process()...\n");
#endif
  log_msg("Pre processing of mesh...");
#ifdef PARALLEL
  error = MPI_Barrier(MPI_COMM_WORLD);
#endif
  pre_process(EXO_ptr);

  /***********************************************************************/
  /***********************************************************************/
  /***********************************************************************/
  /*
   * Load up a few key indeces in the bfd prototype basis function structures
   * and make sure that each active eqn/vbl has a bf[v] that points to the
   * right bfd[]...needs pre_process to find out the number of unique
   * element types in the problem.
   */

#ifdef DEBUG
  fprintf(stderr, "bf_init()...\n");
#endif
  log_msg("Basis function initialization...");
  error = bf_init(EXO_ptr);
  EH( error, "Problem from bf_init");

  /*
   * check for parallel errors before continuing
   */
  check_parallel_error("Error encountered in problem setup");

  /***********************************************************************/
  /***********************************************************************/
  /***********************************************************************/  
  /*
   * Allocate space for each communication exchange description.
   */
#ifdef PARALLEL
#ifdef DEBUG
  fprintf(stderr, "P_%d: Parallel cx allocation\n", ProcID);
#endif
  if (DPI_ptr->num_neighbors > 0) {
    cx = alloc_struct_1(Comm_Ex, DPI_ptr->num_neighbors);
    Request = alloc_struct_1(MPI_Request, 
			     Num_Requests * DPI_ptr->num_neighbors);
    Status = alloc_struct_1(MPI_Status, 
			    Num_Requests * DPI_ptr->num_neighbors);
  }
#endif

  /***********************************************************************/
  /***********************************************************************/
  /***********************************************************************/
  /*
   *                           SET UP THE PROBLEM
   *
   * Setup node-based structures
   * Finalise how boundary conditions are to be handled
   * Determine what unknowns are at each owned node and then tell
   *  neighboring processors about your nodes
   * Set up communications pattern for fast unknown updates between
   *  processors.
   */
  (void) setup_problem(EXO_ptr, DPI_ptr);

  /*
   * check for parallel errors before continuing
   */
  check_parallel_error("Error encountered in problem setup");
  
  /***********************************************************************/
  /***********************************************************************/
  /***********************************************************************/
  /*
   *                     WRITE OUT INITIAL INFO TO EXODUS FILE
   */

  /*
   *  Only have to initialize the exodus file if we are using different
   *  files for the output versus the input mesh
   */
  if (strcmp(ExoFile, ExoFileOut)) {
    /*
     * Temporarily we'll need to renumber the nodes and elements in the
     * mesh to be 1-based. After writing, return to the 0 based indexing
     * that is more convenient in C.
     */
#ifdef DEBUG
    fprintf(stderr, "1-base; wr_mesh; 0-base\n");
#endif
    one_base(EXO_ptr);
    wr_mesh_exo(EXO_ptr, ExoFileOut, 0);
    zero_base(EXO_ptr);

    /*
     * If running on a distributed computer, augment the plain finite
     * element information of EXODUS with the description of how this
     * piece fits into the global problem.
     */
    if (Num_Proc > 1) {
#ifdef PARALLEL
#ifdef DEBUG
      fprintf(stderr, "P_%d at barrier before wr_dpi()\n", ProcID);
      fprintf(stderr, "P_%d ExoFileOut = \"%s\"\n", ProcID, ExoFileOut);
      error = MPI_Barrier(MPI_COMM_WORLD);
#endif
#endif
      wr_dpi(DPI_ptr, ExoFileOut, 0);
    }
  }

  if (Num_Import_NV > 0 || Num_Import_EV > 0) printf
    (" Goma will import %d nodal and %d element variables.\n",
     Num_Import_NV, Num_Import_EV);
  if (Num_Export_XS > 0 || Num_Export_XP > 0) printf
    (" Goma will export %d solution and %d post-processing variables.\n",
     Num_Export_XS, Num_Export_XP);

  /* Return counts to calling program */
  *nnodes = EXO_ptr->num_nodes;
  *nelems = EXO_ptr->num_elems;
  *nnv_in = Num_Import_NV;
  *nev_in = Num_Import_EV;
  *i_soln = Num_Export_XS;
  *i_post = Num_Export_XP;

  return (0); /* Back to  animas*/
}