Ejemplo n.º 1
0
static void print_internal(jackctl_internal_t * internal)
{
    printf("\n-------------------------- \n");
    printf("internal = %s\n", jackctl_internal_get_name(internal));
    printf("-------------------------- \n");
    print_parameters(jackctl_internal_get_parameters(internal));
}
Ejemplo n.º 2
0
static void print_driver(jackctl_driver_t * driver)
{
    printf("\n--------------------------\n");
    printf("driver = %s\n", jackctl_driver_get_name(driver));
    printf("-------------------------- \n");
    print_parameters(jackctl_driver_get_parameters(driver));
}
Ejemplo n.º 3
0
int main(int argc, char *argv[]) {
  double params[NParams];
  FILE *pipe;

  load_parameters(argc,argv,params);
  print_parameters(params);

  init(params);

  try {
    run(params);
  }

  catch (COHO_ALLOC_ERROR e) {
    switch (e) {
    case COHO_INIT_ERROR:		cerr << "Initialization error" << endl; break;
    case COHO_NO_COHO:			cerr << "Couldn't allocate individual" << endl; break;
    case COHO_NO_NEW_GENERATION:	cerr << "Couldn't allocate generation" << endl; break;
    case COHO_NO_PARENTS:		cerr << "Couldn't allocate parent set" << endl; break;
    case COHO_NO_CHILD:			cerr << "Couldn't allocate new child" << endl; break;
    default:
      cerr << "Unknown runtime error" << endl;
    }
  }

  catch (...) {
    cerr << "Unknown (non-integer) runtime error" << endl;
  }
}
Ejemplo n.º 4
0
Archivo: MC1p.hpp Proyecto: hust220/nsp
    MC1p(const Par &par) : TSP(par) {
        LOG << "# Read parameters" << std::endl;
        read_par();

        LOG << "# Set parameters" << std::endl;
        #define JN_MCPSB_PAR_SET(a) par.set(PP_CAT(_mc_, a), PP_STRING3(PP_CAT(mc_, a)));
        JN_MAP(JN_MCPSB_PAR_SET, JN_MC_PARS1, JN_MC_PARS2)

        LOG << "# Print parameters" << std::endl;
        print_parameters();

        LOG << "# Read initial structure" << std::endl;
        chain_read_model(_pred_chain, par.get("pdb"));

        LOG << "# Set indices" << std::endl;
        thread_local static std::map<char, int> m {{'A', 0}, {'U', 1}, {'G', 2}, {'C', 3}};
        m_indices.resize(_seq.size());
        for (int i = 0; i < _seq.size(); i++) {
            m_indices[i] = m[_seq[i]];
        }

        LOG << "# Set 2D trees" << std::endl;
        set_trees();

        LOG << "# Set ranges" << std::endl;
        set_ranges();

        LOG << "# Print ranges" << std::endl;
        print_ranges();

    }
int main(int argc, char *argv[])
{
	Files_t files;
	Working_hours_t hours;
	Appointment_t *arr;
	node_t* node,*temp;
	int size,num,i;
	get_main_arguments(argc,argv,&hours,&files);
	arr=getRequests(&files,&size);
	
	print_parameters(&files,&hours);
	write_appointments(arr,size,&files);
	
	node=build_ll(arr,size,&hours);
	temp=node;	
	#ifndef DEBUG_MODE
	while(node!=NULL){
		printf("hour=%d\n",node->hour);
		node=node->next;
	}
	#endif
	
	node=temp;
	add_personal_data(node,&files);	
	node=temp;
	
	delete_appointments(&node,&files);
			
	write_accepted_app(node,&files);
	free_list(node);
	return 0;
}
int main(int argc , char *argv[])
{
	int size;
	Appointment_t *appo;
	Working_hours_t hours;
	Files_t files;

	#ifdef DEBUG
	printf("STARTED argc = %d %s \n",argc,argv[1]);
	#endif
	get_main_arguments(argc,argv,&hours,&files);
	
	appo = getRequests(&files,&size);
	#ifdef DEBUG
	printf("allocated array's siz is %d \n",size);
	#endif
	
    write_appointments(appo,size,&files);

    print_parameters(&files,&hours);

    #ifdef DEBUG
    printf("%s %s %s %s %s %s",files.records_file_n
                           ,files.patients_file_n
                           ,files.accepted_appo_file_n
                           ,files.delete_file_n
                           ,files.parameters_file_n
                           ,files.readable_records_file_n);
    #endif

	return 0;
}
Ejemplo n.º 7
0
static void print_dbg(
    gtransp_dbg ths
    )
{
  print_parameters(
      ths->N0, ths->N1, ths->hm, ths->blk0, ths->blk1, ths->in, ths->out,
      ths->local_N0, ths->local_N0_start, ths->local_N1, ths->local_N1_start,
      ths->comm, ths->fftw_flags);
}
Ejemplo n.º 8
0
LONG WINAPI ExceptionFilter(PEXCEPTION_POINTERS ExceptionInfo) {
    if(ExceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_SINGLE_STEP) {
        if((DWORD)ExceptionInfo->ExceptionRecord->ExceptionAddress == func_addr) {
            PCONTEXT debug_context = ExceptionInfo->ContextRecord;
            printf("Breakpoint hit!\n");
            print_parameters(debug_context);
            modify_text(debug_context);
            debug_context->Eip = (DWORD)&change_text_stub;
            return EXCEPTION_CONTINUE_EXECUTION;
        }
    }
    return EXCEPTION_CONTINUE_SEARCH;
}
Ejemplo n.º 9
0
void RubyConfig::printConfiguration(ostream& out) {
  out << "Ruby Configuration" << endl;
  out << "------------------" << endl;

  out << "protocol: " << CURRENT_PROTOCOL << endl;
  SIMICS_print_version(out);
  out << "compiled_at: " << __TIME__ << ", " << __DATE__ << endl;
  out << "RUBY_DEBUG: " << bool_to_string(RUBY_DEBUG) << endl;

  char buffer[100];
  gethostname(buffer, 50);
  out << "hostname: " << buffer << endl;

  print_parameters(out);
}
int	main(int argc, char* argv[])
{
	Appointment_t* appointments; /*Array of records*/
	int size; /*Number of records*/
	
	/*Takes main arguments and change hours and file names*/
	get_main_arguments(argc, argv, &hours, &files);
	
	/*Reads records and writes into the array them*/
	/*Size is a records number*/
	appointments=getRequests(&files, &size);
	
	/*Takes array of records and writes records into the file as xml file*/
	write_appointments(appointments, size, &files);
	
	/*Writes file names and hours into the file*/
	print_parameters(&files, &hours);

	return 0;
}
LONG WINAPI ExceptionFilter(PEXCEPTION_POINTERS ExceptionInfo) {
    if(ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_GUARD_PAGE_VIOLATION) {        
        ExceptionInfo->ContextRecord->EFlags |= 0x100;
		return EXCEPTION_CONTINUE_EXECUTION;
    }
    else if(ExceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_SINGLE_STEP) {
        if((DWORD)ExceptionInfo->ExceptionRecord->ExceptionAddress == (DWORD)func_addr) {
            PCONTEXT debug_context = ExceptionInfo->ContextRecord;
            printf("Breakpoint hit!\n");
            print_parameters(debug_context);
            modify_text(debug_context);
        }
        MEMORY_BASIC_INFORMATION mem_info;
        DWORD old_protections = 0;
        VirtualQuery((LPCVOID)func_addr, &mem_info, sizeof(MEMORY_BASIC_INFORMATION));
        VirtualProtect(mem_info.BaseAddress, mem_info.RegionSize, mem_info.AllocationProtect | PAGE_GUARD,
            &old_protections);
        return EXCEPTION_CONTINUE_EXECUTION;
    }
    return EXCEPTION_CONTINUE_SEARCH;
}
Ejemplo n.º 12
0
Archivo: main.c Proyecto: aiwl/ir
int main(int argc, char *argv[])
{
    int w, h;
    char in[256], out[256];

    if (argc < 3) {
        usage(argv[0]);
        return EXIT_FAILURE;
    }

    strncpy(in, argv[argc - 1], sizeof(in) - 1);
    strncpy(out, argv[argc - 2], sizeof(out) - 1);

    chk(get_parameters(&parameters, argc, (char **)(argv)));
    print_parameters(&parameters);

    chk(scene = scene_load(in));
    w = scene->camera.image_width;
    h = scene->camera.image_height;
    chk(image = hdr_image_new(w, h));

    context = ir_context_new(parameters.num_paths, parameters.max_path_length,
        parameters.tmin, parameters.dist_clamp);
    ir_distribute(context, scene);
    chk(accumulate_mt(parameters.num_threads));

    ir_render_vpls(context, image, scene, parameters.vpl_radius);
    ir_context_delete(&context);

    hdr_image_save(image, out);
    scene_delete(&scene);
    hdr_image_delete(&image);
    return EXIT_SUCCESS;

error:
    scene_delete(&scene);
    hdr_image_delete(&image);
    return 1;
}
Ejemplo n.º 13
0
void
ofm_read_simple(void)
{

    if (ofm_on==TRUE) {
        print_ofm_level(ofm_level-1);
        print_font_dir(font_dir);
    }
    header = (char *) ofm+check_sum_pos;
    retrieve_header();
    print_family();
    print_face();
    print_coding_scheme();
    print_design_size();
    out("(COMMENT DESIGNSIZE IS IN POINTS)"); out_ln();
    out("(COMMENT OTHER SIZES ARE MULTIPLES OF DESIGNSIZE)"); out_ln();
    print_check_sum();
    if ((seven_bit == TRUE) || (ofm_level != OFM_TFM))
      print_seven_bit_safe_flag();
    retrieve_parameters(ofm+(4*param_base));
    print_parameters();
}
Ejemplo n.º 14
0
int main(int argc, char **argv)
{
  ROS_INFO("Starting pid with node name %s", node_name.c_str());

  // Initialize ROS stuff
  ros::init(argc, argv, node_name);     // Note node_name can be overidden by launch file
  ros::NodeHandle node;
  ros::NodeHandle node_priv("~");

  while (ros::Time(0) == ros::Time::now())
  {
    ROS_INFO("controller spinning waiting for time to become non-zero");
    sleep(1);
  }

  // Get params if specified in launch file or as params on command-line, set defaults
  node_priv.param<double>("Kp", Kp, 1.0);
  node_priv.param<double>("Ki", Ki, 0.0);
  node_priv.param<double>("Kd", Kd, 0.0);
  node_priv.param<double>("upper_limit", upper_limit, 1000.0);
  node_priv.param<double>("lower_limit", lower_limit, -1000.0);
  node_priv.param<double>("windup_limit", windup_limit, 1000.0);
  node_priv.param<double>("cutoff_frequency", cutoff_frequency, -1.0);
  node_priv.param<std::string>("topic_from_controller", topic_from_controller, "control_effort");
  node_priv.param<std::string>("topic_from_plant", topic_from_plant, "rpms");
  node_priv.param<std::string>("setpoint_topic", setpoint_topic, "setpoint");
  node_priv.param<double>("max_loop_frequency", max_loop_frequency, 1.0);
  node_priv.param<double>("min_loop_frequency", min_loop_frequency, 1000.0);

  // Update params if specified as command-line options, & print settings
  print_parameters();
  if (not validate_parameters())
  {
    std::cout << "Error: invalid parameter\n";
  }

  // instantiate publishers & subscribers
  control_effort_pub = node.advertise<std_msgs::Float64>(topic_from_controller, 1);

  ros::Subscriber sub = node.subscribe(topic_from_plant, 1, plant_state_callback );
  // COmment for now not to have changes. We want constant rpms
  //ros::Subscriber setpoint_sub = node.subscribe(setpoint_topic, 1, setpoint_callback );
  ros::Subscriber pid_enabled_sub = node.subscribe("pid_enable", 1, pid_enable_callback );


/*  // configure dynamic reconfiguration
  dynamic_reconfigure::Server<pid::PidConfig> config_server;
  dynamic_reconfigure::Server<pid::PidConfig>::CallbackType f;
  f = boost::bind(&reconfigure_callback, _1, _2);
  config_server.setCallback(f);
*/

/*
  // initialize diagnostics
  diags = new PidControllerDiags;

  diag_status.level = diagnostic_msgs::DiagnosticStatus::OK;
  diag_status.message = "PID status nominal";

  diags->diag_updater.setHardwareID(node_name);
  diags->diag_updater.add(diags->freq_status);
  diags->diag_updater.add("PID status", get_pid_diag_status);
*/

  // Respond to inputs until shut down
  ros::spin();

  return 0;
}
Ejemplo n.º 15
0
Archivo: crlprop.c Proyecto: mphy/crl
/* parse programm line arguments, set-up parameter, initialise and run the simulation */
int main(int argc, const char* argv[])
{
    int ret = 0;

    double energy_keV, distance1_m, f_m, distance2_m;
    struct parameters parameters;
    //argument structures for funtions and field memory allocation 
    struct s2c s2c; 			s2c.field = malloc(sizeof(struct field));
    struct insidecrl insidecrl; 	insidecrl.field = malloc(sizeof(struct field));
    struct c2f c2f;			c2f.field = malloc(sizeof(struct field));

    int tag = tag_val;           //tag determines whether initially create field or read from file
    int current=0;	         //int used to keep track of the step the simulation goes through (identifying propagation)
    double distance;		 //distance to perform fourier propagation
    char fnameread[20];		 //name of the file to be read
    char fnamewrite[20];	 //name of the file to wite to

    if (argc != 5)
    {
	fprintf(stderr, "usage: %s <energy/keV> <distance1/m> <f/m> <distance2/m>\n", argv[0]);
	ret = -1;
	goto cleanup;
    }

    energy_keV  = atof(argv[1]); /* energy in keV */
    distance1_m = atof(argv[2]); /* distance from point-source to crl device in m */
    f_m         = atof(argv[3]); /* focal distance of individual lens in m */
    distance2_m = atof(argv[4]); /* distance from crl device to detector in m */

    parameters.xray.energy        = energy_keV;
    parameters.xray.wavelength    =   12.398/energy_keV*1e-10; /* conversion factor from keV to angstrom to metre */
    parameters.xray.wavenumber    =    2*M_PI / parameters.xray.wavelength;

    parameters.source.distance    = distance1_m;

    parameters.crl.f              = f_m;
    parameters.crl.aperture       =    1e-3; /* 1 mm */
    parameters.crl.separation     =   10e-6; /* 10 µm */
    parameters.crl.number         =   lenses;
    parameters.crl.deltafactor    =   3.53e-6;
    parameters.crl.R		  =  f_m*2.*M_PI*parameters.crl.deltafactor;

    parameters.detector.distance  = distance2_m;// (40/39 is q for s=40 and f=1);
    parameters.detector.number    = 1;		//to be defined by field propagation
    parameters.detector.width     = 1;		//to be defined by field propagation
//    print_parameters(&parameters, stdout);


    /* If noread then copy parameters to s2c and generate field*/
    if (tag==-1){
    copy_xray(&parameters.xray,   &s2c.xray);
    copy_source(&parameters.source, &s2c.source);
    source_to_crl(&s2c, parameters.crl.aperture);
////    printf("FIRST STEP:  Create field tag=%d \n", tag);
    if (padf) pad_field(s2c.field);
    write_field_to_file(s2c.field, "entrance_plane.txt", parameters.crl.aperture);
    }			

    /* copy parameters to insidecrl structure*/
    copy_xray(&parameters.xray, &insidecrl.xray);
    copy_crl(&parameters.crl, &insidecrl.crl);

    /* copy parameters to c2f structure for the propagation*/
    copy_xray(&insidecrl.xray, &c2f.xray);
    copy_crl(&parameters.crl, &c2f.crl);
    copy_detector(&parameters.detector,&c2f.detector); 

    //Pre-process: Create/read field and allocate memory. Starting point will be after the lens
    //if field is coming from entrance_plane (both generated or read) allocate and execute PREVIOUS phase-shifting 
    if (tag>0){
	sprintf(fnameread,"crl_plane");
	sprintf(fnameread,"%s%d.txt", fnameread, tag);
	read_field_from_file(insidecrl.field, fnameread);
	tag=-1;//CHANGE (fourier propagation)
        } 

	//Get entrance plane field	  
	else{
	   if (tag==-1){	
	    //Getting from field already generated
            insidecrl.field->size = malloc(s2c.field->dimensions*sizeof(int));
            insidecrl.field->values = malloc(s2c.field->components*sizeof(complex double));
            copy_field(s2c.field, insidecrl.field);  
	    }

	    //Reading from entrance_plane
            else if (tag==0){
	    sprintf(fnameread,"entrance_plane");
	    sprintf(fnameread,"%s.txt", fnameread);
	    read_field_from_file(insidecrl.field, fnameread);
	    tag=-1;
 	    }
////        printf("CRL STEP:  Apply phase-shift tag=%d \n", tag);
     	sprintf(fnamewrite,"crl_plane");
	sprintf(fnamewrite,"%s1.txt", fnamewrite);
        crl_inside(&insidecrl, fnamewrite);
	} 

    //Once N is set, get detector parameters
    parameters.detector.number=pix_num; //previously parameters.detector.number=insidecrl.field->components;
//    parameters.detector.width=parameters.detector.number*c2f.xray.wavelength*c2f.detector.distance/parameters.crl.aperture;
    parameters.detector.width=0.01;
    parameters.detector.intensity = malloc(parameters.detector.number * sizeof(double)); 

    copy_detector(&parameters.detector,&c2f.detector); 
    print_parameters(&parameters, stderr);

    // Start lens loop: while current state (lens) has not reached total lens amount. (phshift) + /PROP+(PHSHIFT)/
    //										      (previous) +/LOOP+(post)/
	while(current!=lenses){

////	   printf("NEW STEP:  current state=%d , tag=%d \n", current, tag);

	       // get field from previous steps, allocate if first time
	       if (current==0){
	           c2f.field->size = malloc(insidecrl.field->dimensions*sizeof(int));
	           c2f.field->values = malloc(insidecrl.field->components*sizeof(complex double));
	           }
	       copy_field(insidecrl.field, c2f.field);


//RUN 	   //perform fourier propagation: from CRL to CRL or Detector (different methods)
////	   printf("Call propagation... \n");
   	   if (current==(lenses-1)){
	   distance=parameters.detector.distance;
//           get_spherical(&c2f, tag, distance);
	   if (padf) pad_field(c2f.field);

	   if (ray_add) ray_addition(&c2f, tag, distance);
           else crl_to_focus(&c2f, tag, distance);
	   }
	   else{
           distance=parameters.crl.separation;  
           crl_to_fourier(&c2f, tag, distance);
	   }
	  

////    	   printf("distance for propagation %d was %f \n", current, distance);
////	   printf("propagation successfully done. \n");
	   copy_field(c2f.field, insidecrl.field);

	   //if not reached detector then phase-shift before propagation 
	   if (current!=(lenses-1)){
	   sprintf(fnamewrite,"crl_plane");
	   sprintf(fnamewrite,"%s%d.txt", fnamewrite, current+2);
           crl_inside(&insidecrl, fnamewrite);
	   }

	   current=current+1;
      }
      write_field_to_file(c2f.field, "det_plane.txt", parameters.detector.width);

    
    /* call gnuplot script to generate plots */
    system ("gnuplot gpscript.gp");

cleanup:
    if (parameters.detector.intensity)   free(parameters.detector.intensity);   parameters.detector.intensity=NULL;
    return ret;
}//main
Ejemplo n.º 16
0
static void render(void)
{
   double t = al_get_time();
   if (regenerate) {
      al_destroy_bitmap(logo);
      al_destroy_bitmap(logo_flash);
      logo = NULL;
      regenerate = false;
   }
   if (!logo) {
      /* Generate a new logo. */
      ALLEGRO_BITMAP *fullflash;
      ALLEGRO_BITMAP *fulllogo = generate_logo(param_values[0],
         param_values[1],
         strtol(param_values[2], NULL, 10),
         strtod(param_values[3], NULL),
         strtod(param_values[4], NULL),
         strtod(param_values[5], NULL),
         strtod(param_values[6], NULL),
         strtod(param_values[7], NULL),
         strtod(param_values[8], NULL),
         &fullflash);
      ALLEGRO_BITMAP *crop;
      int x, y, left = 640, top = 480, right = -1, bottom = -1;
      /* Crop out the non-transparent part. */
      al_lock_bitmap(fulllogo, ALLEGRO_PIXEL_FORMAT_ANY, ALLEGRO_LOCK_READONLY);
      for (y = 0; y < 480; y++) {
         for (x = 0; x < 640; x++) {
            ALLEGRO_COLOR c = al_get_pixel(fulllogo, x, y);
            float r, g, b, a;
            al_unmap_rgba_f(c, &r, &g, &b, &a);
            if (a > 0) {
               if (x < left)
                  left = x;
               if (y < top)
                  top = y;
               if (x > right)
                  right = x;
               if (y > bottom)
                  bottom = y;
            }
         }
      }
      al_unlock_bitmap(fulllogo);

      if (right < left)
         right = left;
      if (bottom < top)
         bottom = top;

      crop = al_create_sub_bitmap(fulllogo, left, top,
                                  1 + right - left, 1 + bottom - top);
      logo = al_clone_bitmap(crop);
      al_destroy_bitmap(crop);
      al_destroy_bitmap(fulllogo);

      crop = al_create_sub_bitmap(fullflash, left, top,
                                  1 + right - left, 1 + bottom - top);
      logo_flash = al_clone_bitmap(crop);
      al_destroy_bitmap(crop);
      al_destroy_bitmap(fullflash);

      logo_x = left;
      logo_y = top;

      anim = t;
   }
   draw_background();

   /* For half a second, display our flash animation. */
   if (t - anim < 0.5) {
      ALLEGRO_STATE state;
      int w, h, i, j;
      float f = sin(ALLEGRO_PI * ((t - anim) / 0.5));
      ALLEGRO_COLOR c = al_map_rgb_f(f * 0.3, f * 0.3, f * 0.3);
      w = al_get_bitmap_width(logo);
      h = al_get_bitmap_height(logo);
      al_store_state(&state, ALLEGRO_STATE_BLENDER);
      al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_INVERSE_ALPHA);
      al_draw_tinted_bitmap(logo, al_map_rgba_f(1, 1, 1, 1 - f), logo_x, logo_y, 0);
      al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_ONE);
      for (j = -2; j <= 2; j += 2) {
         for (i = -2; i <= 2; i += 2) {
            al_draw_tinted_bitmap(logo_flash, c, logo_x + i, logo_y + j, 0);
         }
      }
      al_restore_state(&state);
   }
   else
      al_draw_bitmap(logo, logo_x, logo_y, 0);


   print_parameters();
}
Ejemplo n.º 17
0
int main (int argc, char* argv[]) {
	char filename1[200];
	char filename2[200];
	char pairs_file[200];
	char fileout[200];
	FILE* query_fp = 0;
	FILE* reference_fp = 0;
	FILE* fp_pairs = 0;
	FILE* fpout = stdout;
	int total_pairs = 0;
	pair_struct* pairs = 0;
	extern FILE *scaninfo_file;

	setup_match_types();

	/* Set Default Parameter Values*/

	length_5p_for_weighting = 8; /* The 5' sequence length to be weighted  except for the last residue */
	scale = 4.0;			/* The 5' miRNA scaling parameter */
	strict = 0;			/* Strict seed model on/off*/
	debug = 0;			/* Debugging mode on/off*/
	key_value_pairs = 0;
	gap_open = -9.0;		/* Gap-open Penalty*/
	gap_extend = -4.0;		/* Gap-extend Penalty*/
	score_threshold = 140.0;	/* SW Score Threshold for reporting hits*/
	score_ceiling = 0; /* Default upper limit to score. If zero, this is not used. */
	energy_threshold = 1.0;		/* Energy Threshold (DG) for reporting hits*/
	verbosity = 1;	                /* Verbose mode on/off*/
	brief_output = 0; 	                /* Brief output off by default */
	rusage_output = 0; 	                /* rusage output off by default */
	outfile = 0;			/* Dump to file on/off*/
	truncated = 0;			/* Truncate sequences on/off*/
	no_energy = 1;			/* Turn off Energy Calcs - FASTER*/
	restricted = 0;			/* Perform restricted search space*/
	parse_command_line(argc, argv, filename1, filename2, fileout, pairs_file);
	if (gap_open > 0.0 || gap_extend > 0.0) {
		fprintf(stderr, "Error: gap penalties may not be greater than 0\n");
		return 1;
	}
	if (truncated < 0) {
		fprintf(stderr, "Error: negative value give for UTR truncation\n");
		return 1;
	}
	if ((query_fp = fopen(filename1, "r")) == NULL) {
		fprintf(stderr, "Error: Cannot open file %s\n", filename1);
		return 1;
	}
	if ((reference_fp = fopen(filename2, "r")) == NULL) {
		fprintf(stderr, "Error: Cannot open file %s\n", filename2);
		return 1;
	}
	fclose(reference_fp);
	if ((outfile) && ((fpout = fopen(fileout, "w")) == NULL)) {
		fprintf(stderr, "Error: Cannot create output file %s\n", fileout);
		return 1;
	}
	if (restricted) {
		if ((fp_pairs = fopen(pairs_file, "r")) == NULL) {
			fprintf(stderr, "Error: Cannot open restrict pairs file %s\n", pairs_file);
			return 1;
		}
		/* Initialize the pairs list for restriced searches*/
		total_pairs = load_pairs(fp_pairs, &pairs);
		fclose(fp_pairs);
	}
	fflush(fpout);
	initialize_globals();
	if(!brief_output)
	  print_parameters(filename1, filename2, fpout);
	if (restricted && verbosity) {
		printf("Performing Restricted Scan on:%d pairs\n", total_pairs);
	}
	find_targets(query_fp, fpout, pairs, total_pairs, filename2);

#ifdef USE_RUSAGE
	if(rusage_output)
	  {
	    struct rusage ru;
	    if(getrusage(RUSAGE_SELF,&ru) != 0)
	      {
		fprintf(stderr,"Could not get rusage data\n");
		if(errno)
		  fprintf(stderr,"Reason: %s",strerror(errno));
	      }
	    else
	      {
		printf("User CPU time: %ld.%06ld\n",ru.ru_utime.tv_sec,ru.ru_utime.tv_usec);
		printf("Max RSS: %ld KB\n",ru.ru_maxrss);
		
	      }
	  }
#endif // RUSAGE

	destroy_globals();
	if (outfile) fclose(fpout);
	if (scaninfo_file != stdout && scaninfo_file != stderr && scaninfo_file != NULL)
	  fclose(scaninfo_file);
	json_close();
	fclose(query_fp);
	return 0;
}
Ejemplo n.º 18
0
/*
 *  Main function
 */
int main(int argc, char** argv)
{
    struct timespec start, stop;
    int next_option, verbose, write;
    const char* const short_options = "hvn:g:o:s:i:";

    char *giIndex = NULL;
    char *includeIndex = NULL;
    char *skipIndex = NULL;

    clock_gettime(CLOCK_MONOTONIC, &start);
    program_name = argv[0];

    const struct option long_options[] = {
        { "help", 0, NULL, 'h'},
        { "verbose", 0, NULL, 'v'},
        { "nt", 1, NULL, 'n'},
        { "gi", 1, NULL, 'g'},
        { "nodes", 1, NULL, 'o'},
        { "skip", 1, NULL, 's'},
        { "include", 1, NULL, 'i'},
        { "dbSize", 1, NULL, 'd'},
        { NULL, 0, NULL, 0} /* Required at end of array.  */
    };

    write = verbose = 0;
    nt = gi = nodes = skip = include = NULL;
    do {
        next_option = getopt_long(argc, argv, short_options, long_options, NULL);

        switch (next_option) {
            case 'h':
                print_usage(stdout, 0);

            case 'v':
                verbose = 1;
                break;

            case 'n':
                nt = (char *) malloc(sizeof (char) * (strlen(optarg) + 1));
                strcpy(nt, optarg);
                break;

            case 'g':
                gi = (char *) malloc(sizeof (char) * (strlen(optarg) + 1));
                strcpy(gi, optarg);
                break;

            case 'o':
                nodes = (char *) malloc(sizeof (char) * (strlen(optarg) + 1));
                strcpy(nodes, optarg);
                break;

            case 's':
                skip = (char *) malloc(sizeof (char) * (strlen(optarg) + 1));
                strcpy(skip, optarg);
                break;

            case 'i':
                include = (char *) malloc(sizeof (char) * (strlen(optarg) + 1));
                strcpy(include, optarg);
                break;

            case 'd':
                MaxGb = atoi(optarg);
                break;
        }
    } while (next_option != -1);

    InputCheck(nt, gi, nodes, skip, include);

    if(verbose == 1)
        print_parameters();

    if(verbose == 1)
        printf("Getting biggest GI id from %s\n", gi);
    GetMaxGiNuclDmp(gi);
    if(verbose == 1)
        printf("Importing GI and taxon ID pairs into memory from %s\n", gi);
    ImportGiNuclDmp(gi);

    if(verbose == 1)
        printf("Getting biggest taxon ID from %s\n", nodes);
    GetMaxNodeslDmp(nodes);
    if(verbose == 1)
        printf("Importing taxon parent and child IDs into memory from %s\n", nodes);
    ImportNodeslDmp(nodes);

    if(include != NULL) {
        if(verbose == 1)
            printf("Importing include taxon IDs from %s\n", include);
        ImportInclude(include);
    }

    if(skip != NULL) {
        if(verbose == 1)
            printf("Importing exclude taxon IDs from %s\n", skip);
        ImportExclude(skip);
    }
    if(verbose == 1)
        printf("Reading and parsing fasta file %s\n", nt);
    ReadFasta(nt);

    if (nt) free(nt);
    if (gi) free(gi);
    if (nodes) free(nodes);
    if (skip) free(skip);
    if (include) free(include);
    FreeIncludeExclude();
    FreeGiId();
    FreeTaxons();
    clock_gettime(CLOCK_MONOTONIC, &stop);
    printf("\n\tThe total time was %lu sec\n\n", timespecDiff(&stop, &start) / 1000000000);

    return 0;
}
Ejemplo n.º 19
0
int main (int argc, char ** argv)
{
  int i;
    
  /*
   *  this is set to either euler or runge_kutta_4
   */
  enum solver_t solver;

  /*
   *  bc (boundary condition) can be either periodic or no_slip
   */
  enum bc_t bc;

  /*
   * these specify the geometry of the area to be simulated 
   * tdim ist the total number of points, i.e. tdim = xdim *ydim 
   */
  int xdim, ydim, tdim;
  double dx, dy;

  /*
   * this holds the neighbors 
   */
  int **neighbors;

  /*
   * this holds latitude and longitude values of each point
   */
  unsigned int *lat, *lon;

  /*
   * this holds order of the data to be printed out
   */
  unsigned int *print_out_order;

  /*
   * these control temporal aspects of the simulation 
   */
  long int ncycle;
  double dt = 5.1;
  long int n_iter = 25800;
  int write_out_interval = 5000;

  /*
   * these hold the physical parameters 
   *
   * f0:              coriolis parameter (1/1sec)
   * beta:            linear beta for coriolis force (1/(meter sec))
   * forcingTerm:     Wind stress amplitude "tau_0"(N/meter^2)
   * dissipationTerm: "A" viscosity coefficient (meters^2/sec)
   * RayleighFriction: Rayleigh friction parameter (1/sec)
   */
  double f0 = 5.0e-5;
  double beta =2e-11;
  double forcingTerm = 0.0005;
  double dissipationTerm = 0.00005;
  double RayleighFriction = 5e-8;

  /*
   * upper layer equilibrium depth (meters)
   */
  double EquilibriumDepth = 50000.0;
  double A;

  /*
   * this holds the physical parameters and the forcing
   */
  double *parameters;
  double *x_forcing, *y_forcing, *z_forcing;

  /*
   * "fields" holds the values of the u, v and P fields
   */
  double *fields;
  double *u, *v, *P;     

  /*
   * "fields_prev" holds the u, v and P values of the previous time step
   */
  //double *fields_prev;
  //double *u_prev, *v_prev, *P_prev;     

  /*
   * these are temporary storage locations 
   * for the Runge-Kutta scheme
   */
  double *temp_dots_rk;
  double *temp_fields_rk;

  /*
   * read parameters from command line
   */
  if(argc == 2){

    get_parameters(argv[1], &xdim, &ydim, &dx, &dy, &n_iter, &dt, &write_out_interval, &bc, &solver, &f0, &beta, &forcingTerm, &dissipationTerm, &RayleighFriction, &EquilibriumDepth, &A);

  }
  else{

    fprintf(stderr, "ERROR: You need to give a file containing the parameters as an argument!\n");
    exit(1);

  }

  print_parameters(xdim, ydim, dx, dy, n_iter, dt, write_out_interval, bc, solver, f0, beta, forcingTerm, dissipationTerm, RayleighFriction, EquilibriumDepth, A);

  tdim = xdim*ydim;

  /*
   *  allocate arrays containing geometrical information and fill these
   */
  lat = calloc(tdim, sizeof(unsigned int)); 
  lon = calloc(tdim, sizeof(unsigned int)); 
  print_out_order = calloc(tdim, sizeof(unsigned int)); 
  neighbors = calloc(tdim, sizeof(int*)); 
  for(i=0; i< tdim; i++){
    neighbors[i] = calloc(4, sizeof(int));
  }

  initialize_geometry(xdim, ydim, neighbors, lat, lon, print_out_order);

  /*
   * allocate memory for physical parameters and forcing
   */
  parameters = calloc(5+3*tdim, sizeof(double));

  parameters[0] = f0;
  parameters[1] = beta;
  parameters[2] = forcingTerm;
  parameters[3] = dissipationTerm;
  parameters[4] = RayleighFriction;

  x_forcing = parameters + 5;
  y_forcing = parameters + 5 + tdim;
  z_forcing = parameters + 5 + 2*tdim;

  /*
   * allocate "fields" and set addresses for u, v, and P
   */
  fields = calloc(3*tdim, sizeof(double));
  u = fields;
  v = fields + tdim;
  P = fields + 2 * tdim;

  /*
   * allocate "fields_prev" and set addresses for u_prev, v_prev, and P_prev
   */
  //fields_prev = calloc(3*tdim, sizeof(double));
  //u_prev = fields_prev;
  //v_prev = fields_prev + tdim;
  //P_prev = fields_prev + 2 * tdim;

  double *fields_dot;
  fields_dot = calloc(3*tdim, sizeof(double));

  /*
   * allocate memory for temporary Runge-Kutta storage locations 
   */
  temp_dots_rk = calloc(3*tdim, sizeof(double));
  temp_fields_rk = calloc(3*tdim, sizeof(double));

  /*
   * initialize fields
   */
  initialize_fields (u, v, P, x_forcing, y_forcing, z_forcing, xdim, ydim, dx, dy, EquilibriumDepth, A, neighbors, lat, lon, bc);

  /*
   *  loop through time steps to do the actual simulation
   */
  for (ncycle=0; ncycle<n_iter; ncycle++) {
    //printf("step #%li\n", ncycle);

    /*
     * print result
     */
    if(ncycle % write_out_interval == 0){
      print_field(u, "u", ncycle, xdim, ydim, print_out_order);
      print_field(v, "v", ncycle, xdim, ydim, print_out_order);
      print_field(P, "P", ncycle, xdim, ydim, print_out_order);
      printf("%li ", ncycle);
      fflush(stdout);
    }
    Fcalc(fields_dot, fields, parameters, xdim, ydim, dx, dy, neighbors, lat, bc, print_out_order, ncycle);
 

    //for (i=0;i<3*tdim;i++) {
    //  fields_prev[i] = fields[i];
    //}

    if(solver == runge_kutta_4){

      /*
       *  Runge-Kutta 4th order
       *
       *                 dt
       *    y_1 = y_0 + ---- (y'_0 + 2 * y'_A + 2 * y'_B +y'_C)
       *                  6
       */

      /*                          dt
       * first step: y_A = y_0 + ---- y'_0
       *                          2
       */
      for (i=0; i < 3*tdim;  i++) {
        temp_fields_rk[i] = fields[i]+0.5*dt*fields_dot[i];
      }
      Fcalc(temp_dots_rk, temp_fields_rk, parameters, xdim, ydim, dx, dy, neighbors, lat, bc, print_out_order, ncycle);
      for (i=0; i < 3*tdim;  i++) {
        fields_dot[i] += 2*temp_dots_rk[i];
      }

      /*                           dt
       * second step: y_B = y_0 + ---- y'_A
       *                            2
       */
      for (i=0; i < 3*tdim;  i++) {
        temp_fields_rk[i] = fields[i]+0.5*dt*temp_dots_rk[i];
      }
      Fcalc(temp_dots_rk, temp_fields_rk, parameters, xdim, ydim, dx, dy, neighbors, lat, bc, print_out_order, ncycle);
      for (i=0; i < 3*tdim;  i++) {
        fields_dot[i] += 2*temp_dots_rk[i];
      }

      /*
       * third step: y_C = y_0 + dt * y'_B
       */
      for (i=0; i < 3*tdim;  i++){
        temp_fields_rk[i] = fields[i]+dt*temp_dots_rk[i];
      }
      Fcalc(temp_dots_rk, temp_fields_rk, parameters, xdim, ydim, dx, dy, neighbors, lat, bc, print_out_order, ncycle);
      for (i=0; i < 3*tdim;  i++) {
        fields_dot[i] += temp_dots_rk[i];
      }

      /*                          dt
       * final step: y_1 = y_0 + ---- (y'_0 + 2 * y'_A + 2 * y'_B +y'_C)
       *                           6
       */
      for (i=0; i < 3*tdim;  i++) {
        fields_dot[i] /= 6.0;
        fields[i] += dt*fields_dot[i];
      }
    }
    else{

      if(solver == euler){

        /*
         *  the Euler scheme
         */
        for (i=0; i < 3*tdim;  i++) {
          fields[i] += dt*fields_dot[i];
        }
      }
      else{
        fprintf(stderr, "ERROR: No valid solver was found\n");
        exit(2);
      }
    }
  }
  printf("\n");

  return(0);
}
Ejemplo n.º 20
0
void run(std::string tree_filename, std::string fasta_filename, std::string model_name) {
  Model Mod;                 // The model
  Counts data;               // the counts
  Parameters Par;            // the parameters
  std::vector<double> br;    // branch lengths
  double eps = 1e-8;         // The threshold for the EM algorithm.

  Parameters Parsim;         // used for simulating data.
  std::vector<double> brsim; // branch lengths of simulated data.

  std::vector<std::vector<double> > Cov;  // Covariance matrix
  std::vector<double> variances;          // The variances


  bool simulate;
  bool nonident;
  std::string parameters_filename;
  std::string covariances_filename;

  // initialize random number generator with time(0).
  random_initialize();

  parameters_filename = strip_extension(fasta_filename) + ".dat";
  covariances_filename = strip_extension(fasta_filename) + ".cov";

  // Creates the pointers to the model-specific functions.
  Mod = create_model(model_name);
  std::cout << "Model: " << Mod.name << std::endl;

  // Reads the tree.
  Tree T = read_tree(tree_filename);

  // Prints the Tree
  std::cout << "Tree:" << std::endl;
  print_tree(T);

  // Check for possible nonidentifiability issues.
  nonident = nonident_warning(T);

  // Initialize the parameters for simulation of K81 data for testing
  Parsim = create_parameters(T);

  if (fasta_filename == ":test") {      // if fasta file is :test generate random data.
    simulate = true;

    // Warn
    std::cout << "WARNING: Using simulated data " << std::endl << std::endl;

    // Generate random parameters
    random_parameters_length(T, Mod, Parsim);

    // Simulate the data
    data = random_fake_counts(T, 1000, Parsim);

    // Prints branch-lengths for future check.
    branch_lengths(Parsim, brsim);
    std::cout << "Simulated branch lengths:" << std::endl;
    print_vector(brsim);

  } else {                                  // otherwise read the data
    simulate = false;

    // Read the counts.
    std::cout << "Reading fasta file:" << std::endl;
    read_counts(T, data, fasta_filename);
    add_pseudocounts(0.01, data);
    std::cout << std::endl;
  }

  // Check whether the data and the tree match.
  if (T.nalpha != data.nalpha || T.nleaves != data.nspecies) {
    throw std::invalid_argument("The order of the sequences or their number and the phylogenetic tree do not match.");
  }

  //Par = create_parameters(T);
  //print_parameters(Par);
  //print_vector(Par.r);

  //clock_t
  long start_time, end_time;

  // Runs the EM algorithm. Par is used as initial parameters.
  // After execution, Par contains the MLE computed by the algorithm.

 // for local max over multiple iterations
  Parameters Parmax = Par;
  Model Modmax = Mod;

  float likelL = 0.0;
  float likelMax = -1000000.0;
  float timerec;
  float timemax;

  int outfiles; //whether to save output
  std::cout << "Starting the EM algorithm: " << std::endl;

  int s;
  int S = 0; //count of cases with neg branches

  int iter;
  int iterMax;

  for (int it_runs = 0; it_runs < 10; it_runs++) {
      Par = create_parameters(T);
      Mod = create_model(model_name);
      std::cout << it_runs << ", " ;

      start_time = clock();

      std::tie(likelL, iter) = EMalgorithm(T, Mod, Par, data, eps);

      end_time = clock();
      //print_parameters(Par);

      // Choses the best permutation.
      guess_permutation(T, Mod, Par);

      branch_lengths(Par, br);

      //print_vector(br);
      s = find_negative(br);
      S +=s;
      timerec = ((float)end_time - start_time) / CLOCKS_PER_SEC;

      //assign the 1st iter time value, inc ase it's the best
      if (it_runs == 0){
        timemax = timerec;
        iterMax = iter;
      }

      if (likelL > likelMax){
        Parmax = Par;
        Modmax = Mod;
        timemax = timerec;
        likelMax = likelL;
        iterMax = iter;
      }

  }


  // If parameters are not identifiable, the computation of the covariance matrix will
  // fail as the Fisher info matrix will not be invertible.
  if (!nonident) {
    // Compute the covariance matrix using observed Fisher.
    full_MLE_observed_covariance_matrix(T, Modmax, Parmax, data, Cov);
    variances.resize(Cov.size());
    for(unsigned int i=0; i < Cov.size(); i++) {
      variances[i] = Cov[i][i];
    }

    // OUTPUT Save the sigmas into a file
    //save_sigmas_to(covariances_filename, Cov);
  }

  std::cout << std::endl;
  std::cout << "Finished." << std::endl;
  std::cout << "Likelihood: " << log_likelihood(T, Parmax, data) << std::endl ;
  std::cout << "Time: " << timemax << std::endl << std::endl;
  std::cout << "negative branches: "  << S << std::endl;
  std::cout << "Iter: "  << iterMax << std::endl;

  //std::cout << "Branch lengths: " << std::endl;
  //print_vector(br);
  outfiles = 0;
  if (!nonident && outfiles) {
    std::cout << "Parameter variances: " << std::endl;
    print_vector(variances);
  }

  std::cout << "Newick Tree:" << std::endl;
  print_newick_tree(T, br);

  // if is a simulation, print the L2 distance !
  if (simulate) {
    std::cout << "L2 distance:   " << parameters_distance(Par, Parsim) << std::endl;
    std::cout << "KL divergence: " << KL_divergence(T, Par, Parsim) << std::endl;
    std::cout << std::endl;
  }

  // if it is not a simulation, store the parameters in a file !
  if (!simulate && outfiles) {
    std::fstream st;
    st.precision(15);
    st.setf(std::ios::fixed,std::ios::floatfield);
    st.open(parameters_filename.c_str(), std::ios::out);
    print_parameters(Par, st);
  }
}
Ejemplo n.º 21
0
int main(int argc, char *argv[])
{
    jackctl_server_t * server;
    const JSList * parameters;
    const JSList * drivers;
    const JSList * internals;
    const JSList * node_ptr;
    jackctl_sigmask_t * sigmask;
    int opt, option_index;
    const char* driver_name = "dummy";
    const char* client_name = "audioadapter";

    const char *options = "d:c:";
	struct option long_options[] = {
		{"driver", 1, 0, 'd'},
		{"client", 1, 0, 'c'},
	};

 	while ((opt = getopt_long (argc, argv, options, long_options, &option_index)) != EOF) {
		switch (opt) {
			case 'd':
				driver_name = optarg;
				break;
			case 'c':
				client_name = optarg;
				break;
            default:
				usage();
                exit(0);
		}
	}

	server = jackctl_server_create(NULL, NULL);
    parameters = jackctl_server_get_parameters(server);

    /*
    jackctl_parameter_t* param;
    union jackctl_parameter_value value;
    param = jackctl_get_parameter(parameters, "verbose");
    if (param != NULL) {
        value.b = true;
        jackctl_parameter_set_value(param, &value);
    }
    */

    printf("\n========================== \n");
    printf("List of server parameters \n");
    printf("========================== \n");

    print_parameters(parameters);

    printf("\n========================== \n");
    printf("List of drivers \n");
    printf("========================== \n");

    drivers = jackctl_server_get_drivers_list(server);
    node_ptr = drivers;
    while (node_ptr != NULL) {
        print_driver((jackctl_driver_t *)node_ptr->data);
        node_ptr = jack_slist_next(node_ptr);
    }

    printf("\n========================== \n");
    printf("List of internal clients \n");
    printf("========================== \n");

    internals = jackctl_server_get_internals_list(server);
    node_ptr = internals;
    while (node_ptr != NULL) {
        print_internal((jackctl_internal_t *)node_ptr->data);
        node_ptr = jack_slist_next(node_ptr);
    }

    // No error checking in this simple example...

    jackctl_server_open(server, jackctl_server_get_driver(server, driver_name));
    jackctl_server_start(server);

    jackctl_server_load_internal(server, jackctl_server_get_internal(server, client_name));

    /*
    // Switch master test

    jackctl_driver_t* master;

    usleep(5000000);
    printf("jackctl_server_load_master\n");
    master = jackctl_server_get_driver(server, "coreaudio");
    jackctl_server_switch_master(server, master);

    usleep(5000000);
    printf("jackctl_server_load_master\n");
    master = jackctl_server_get_driver(server, "dummy");
    jackctl_server_switch_master(server, master);

    */

    sigmask = jackctl_setup_signals(0);
    jackctl_wait_signals(sigmask);
    jackctl_server_stop(server);
    jackctl_server_close(server);
    jackctl_server_destroy(server);
    return 0;
}
Ejemplo n.º 22
0
/** @brief Function for main application entry.
 */
int main(void)
{ 
    radio_tests_t test     = RADIO_TEST_NOP;
    radio_tests_t cur_test = RADIO_TEST_NOP;

    init();
    uart_config(TX_PIN_NUMBER, RX_PIN_NUMBER);
    uart_putstring((const uint8_t *)"RF Test\r\n");
    
    NVIC_EnableIRQ(TIMER0_IRQn);
    __enable_irq();
    
    while (true)
    {
        __WFI();
        switch (uart_get())
        {
            case 'a':
                while (true)
                {
                    uart_putstring((const uint8_t *)"Enter start channel \
                                   (two decimal digits, 00 to 80):");
                    channel_start_ = get_dec2();
                    if (channel_start_ <= 80)
                    break;
                    uart_putstring((const uint8_t *)"Channel must be between 0 and 80\r\n");
                }
                test = cur_test;
                break;

            case 'b':
                while (true)
                {
                    uart_putstring((const uint8_t *)"Enter end channel \
                                   (two decimal digits, 00 to 80):");
                    channel_end_ = get_dec2();
                    if (channel_end_ <= 80)
                    {
                        break;
                    }
                uart_putstring((const uint8_t *)"Channel must be between 0 and 80\r\n");
                }
                test = cur_test;
                break;

            case 'c':
                test = RADIO_TEST_TXCC;
                break;

            case 'd':
                while (true)
                {
                    uart_putstring((const uint8_t *)"Enter delay in ms \
                                   (two decimal digits, 01 to 99):");
                    delayms_ = get_dec2();
                    if ((delayms_ > 0) && (delayms_ < 100))   
                    {
                        break;
                    }
                    uart_putstring((const uint8_t *)"Delay must be between 1 and 99\r\n");
                }
                test = cur_test;
                break;

            case 'e':
                radio_sweep_end();
                cur_test = RADIO_TEST_NOP;
                break;

            case 'm':
                get_datarate();
                test = cur_test;
                break;

            case 'o':
                test = RADIO_TEST_TXMC;
                uart_putstring((const uint8_t *)"TX modulated carrier\r\n");
                break;

            case 'p':
                get_power();
                test = cur_test;
                break;

            case 'r':
                test = RADIO_TEST_RXSWEEP;
                uart_putstring((const uint8_t *)"RX Sweep\r\n");
                break;

            case 's':
                print_parameters();
                break;

            case 't':
                test = RADIO_TEST_TXSWEEP;
                uart_putstring((const uint8_t *)"TX Sweep\r\n");
                break;

            case 'x':
                test = RADIO_TEST_RXC;
                uart_putstring((const uint8_t *)"RX constant carrier\r\n");
                break;

            case 'h':
                // Fall through.
        
            default:
                help();
                break;
        }
    
        switch (test)
        {
            case RADIO_TEST_TXCC:
                if (sweep)
                {
                    radio_sweep_end();
                    sweep = false;
                }
                radio_tx_carrier(txpower_, mode_, channel_start_);
                cur_test = test;
                test     = RADIO_TEST_NOP;
                break;

            case RADIO_TEST_TXMC:
                if (sweep)
                {
                    radio_sweep_end();
                    sweep = false;
                }
                radio_modulated_tx_carrier(txpower_, mode_, channel_start_);
                cur_test = test;
                test     = RADIO_TEST_NOP;
                break;

            case RADIO_TEST_TXSWEEP:
                radio_tx_sweep_start(txpower_, mode_, channel_start_, channel_end_, delayms_);
                sweep    = true;
                cur_test = test;
                test     = RADIO_TEST_NOP;
                break;

            case RADIO_TEST_RXC:
                if (sweep)
                {
                    radio_sweep_end();
                    sweep = false;
                }
                radio_rx_carrier(mode_, channel_start_);
                cur_test = test;
                test     = RADIO_TEST_NOP;
                break;  

            case RADIO_TEST_RXSWEEP:
                radio_rx_sweep_start(mode_, channel_start_, channel_end_, delayms_);
                sweep    = true;
                cur_test = test;
                test     = RADIO_TEST_NOP;
                break;

            case RADIO_TEST_NOP:
                // Fall through.
            default:
                // No implementation needed.
                break;
        }
    }
}
Ejemplo n.º 23
0
int main(int argc, char *argv[])
{
  Parameters *parameters; // user defined parameters
  Geometry *geometry; // homogenous cube geometry
  Material *material; // problem material
  Bank *source_bank; // array for particle source sites
  Bank *fission_bank; // array for particle fission sites
  Tally *tally; // scalar flux tally
  double *keff; // effective multiplication factor
  double t1, t2; // timers

  // Get inputs: set parameters to default values, parse parameter file,
  // override with any command line inputs, and print parameters
  parameters = init_parameters();
  parse_parameters(parameters);
  read_CLI(argc, argv, parameters);
  print_parameters(parameters);

  // Set initial RNG seed
  set_initial_seed(parameters->seed);
  set_stream(STREAM_OTHER);

  // Create files for writing results to
  init_output(parameters);

  // Set up geometry
  geometry = init_geometry(parameters);

  // Set up material
  material = init_material(parameters);

  // Set up tallies
  tally = init_tally(parameters);

  // Create source bank and initial source distribution
  source_bank = init_source_bank(parameters, geometry);

  // Create fission bank
  fission_bank = init_fission_bank(parameters);

  // Set up array for k effective
  keff = calloc(parameters->n_active, sizeof(double));

  center_print("SIMULATION", 79);
  border_print();
  printf("%-15s %-15s %-15s %-15s\n", "BATCH", "ENTROPY", "KEFF", "MEAN KEFF");

  // Start time
  t1 = timer();

  run_eigenvalue(parameters, geometry, material, source_bank, fission_bank, tally, keff);

  // Stop time
  t2 = timer();

  printf("Simulation time: %f secs\n", t2-t1);

  // Free memory
  free(keff);
  free_tally(tally);
  free_bank(fission_bank);
  free_bank(source_bank);
  free_material(material);
  free(geometry);
  free(parameters);

  return 0;
}
Ejemplo n.º 24
0
int 
main (int argc, const char *argv[]) 
{
	unsigned int idx;
	char *end;
	int debug = 0;
	
	/* sequence file name specified by the user, otherwise STDIN will be used */
	const char *sequence_file_name = NULL;
	const char *lists_file_name = NULL;
	
	/* data structure for all k-mer lists used for masking */
	unsigned int nlists = 0;
	unsigned int nlist_parameters = 0;
	unsigned int npos = 0;
	unsigned int list_pos[MAX_VARIABLES], list_components[MAX_VARIABLES];
	
	masker_parameters mp = {};
	parameters_builder pbuilder = {};
	input_sequence *input_seq = NULL;
	
	pr_append_str parse_err;
	pr_append_str warnings;
	
	init_pr_append_str (&parse_err);
	init_pr_append_str (&warnings);

	/* fill mp with default parameters */
	mp.mdir = DEFAULT_MASKING_DIRECTION;
	mp.failure_rate = DEFAULT_FAILURE_RATE;
	mp.abs_cutoff = DEFAULT_ABS_CUTOFF;
	mp.nucl_masked_in_5p_direction = DEFAULT_M5P;
	mp.nucl_masked_in_3p_direction = DEFAULT_M3P;
	mp.print_sequence = PRINT_SEQUENCE;
	mp.do_soft_masking = HARD_MASKING;
	mp.masking_char = DEFAULT_MASK_CHAR;
	mp.list_prefix = DEFAULT_LIST_FILE_PREFIX;
	
	
	/* parsing and checking the commandline arguments */
	for (idx = 1; (int)idx < argc; idx++) {
		
  		if (!strcmp (argv[idx], "-h") || !strcmp (argv[idx], "--help") || !strcmp (argv[idx], "-?")) {
			print_help (0);
		
		} else if ((int)idx == argc - 1 && argv[idx][0] != '-') {
			sequence_file_name = argv[idx];
			
		} else if (!strcmp (argv[idx], "-lf") || !strcmp (argv[idx], "--lists_file")) {
			/* lists specified from the file */
			if (!argv[idx + 1] || argv[idx + 1][0] == '-') {
				pr_append_new_chunk_external (&warnings, "No lists file specified.");
				idx += 1;
				continue;
			}
			lists_file_name = argv[idx + 1];
			idx += 1;
			
		} else if (!strcmp (argv[idx], "-l") || !strcmp (argv[idx], "--list")) {
			/* lists specified from the commandline */
			if (nlist_parameters == MAX_VARIABLES) {
				pr_append_new_chunk_external (&parse_err, "Maximum number of list variables reached.");
				break;
			}
			
			if (!argv[idx + 1]) {
				pr_append_new_chunk_external (&warnings, "No list name specified with -l parameter!.");
				continue;
			}
			
			/* get the positions of list files */
			list_pos[nlist_parameters] = idx;
			while (argv[idx + 1]) {
				if (argv[idx + 1][0] == '-') {
					if (!argv[idx + 1][1]) break;
					strtod (argv[idx + 1] + 1, &end);
					if (*end != 0) break;
				} else if (idx + 1 != list_pos[nlist_parameters] + 1 && idx + 1 != list_pos[nlist_parameters] + 4) {
					strtod (argv[idx + 1], &end);
					if (*end != 0) break;
				} else if (idx + 1 == list_pos[nlist_parameters] + 4 && strcmp (argv[idx + 1], "sq")) {
					break;
				}
				idx += 1;
			}
			list_components[nlist_parameters] = idx - list_pos[nlist_parameters];
			nlist_parameters += 1;
			npos += 1;
			
		} else if (!strcmp (argv[idx], "-lp") || !strcmp (argv[idx], "--list_prefix")) {
			/* lists specified by the prefix */
			if (!argv[idx + 1] || argv[idx + 1][0] == '-') {
				pr_append_new_chunk_external (&warnings, "No list prefix specified! Using the default value.");
				idx += 1;
				continue;
			}
			mp.list_prefix = (char *)argv[idx + 1];
			idx += 1;			
			
		} else if (!strcmp (argv[idx], "-p") || !strcmp (argv[idx], "--probability_cutoff")) {
			if (!argv[idx + 1]) {
				pr_append_new_chunk_external (&warnings, "No cutoff value specified! Using the default value.");
				idx += 1;
				continue;
			}
			mp.failure_rate = strtod (argv[idx + 1], &end);
			mp.abs_cutoff = 0;
			if (*end != 0 || mp.failure_rate < 0 || mp.failure_rate > 1) {
				pr_append_new_chunk_external (&parse_err, "Invalid cutoff value: ");
				pr_append_external (&parse_err, argv[idx + 1]);
				break;
			}
			idx += 1;
			
		} else if (!strcmp (argv[idx], "-a") || !strcmp (argv[idx], "--absolute_value_cutoff")) {
			if (!argv[idx + 1]) {
				pr_append_new_chunk_external (&warnings, "No absolute cutoff value specified! Using the default value.");
				idx += 1;
				continue;
			}
			mp.abs_cutoff = strtod (argv[idx + 1], &end);
			mp.failure_rate = 0.0;
			if (*end != 0 || mp.abs_cutoff < 0) {
				pr_append_new_chunk_external (&parse_err, "Invalid absolute cutoff value: ");
				pr_append_external (&parse_err, argv[idx + 1]);
				break;
			}
			idx += 1;
			
		} else if (!strcmp (argv[idx], "-m5") || !strcmp (argv[idx], "--mask_5p")) {
			if (!argv[idx + 1]) {
				pr_append_new_chunk_external (&warnings, "Number of nucleotides masked in 5' direction not specified! Using the default value.");
				idx += 1;
				continue;
			}
			mp.nucl_masked_in_5p_direction = strtod (argv[idx + 1], &end);
			if (*end != 0) {
				pr_append_new_chunk_external (&parse_err, "Invalid number of nucleotides masked in 5' direction: ");
				pr_append_external (&parse_err, argv[idx + 1]);
				break;
			}
			idx += 1;
			
		} else if (!strcmp (argv[idx], "-m3") || !strcmp (argv[idx], "--mask_3p")) {
			if (!argv[idx + 1]) {
				pr_append_new_chunk_external (&warnings, "Number of nucleotides masked in 3' direction not specified! Using the default value.");
				idx += 1;
				continue;
			}
			mp.nucl_masked_in_3p_direction = strtod (argv[idx + 1], &end);
			if (*end != 0) {
				pr_append_new_chunk_external (&parse_err, "Invalid number of nucleotides masked in 3' direction: ");
				pr_append_external (&parse_err, argv[idx + 1]);
				break;
			}
			idx += 1;
			
		} else if (!strcmp (argv[idx], "-c") || !strcmp (argv[idx], "--masking_char")) {
			if (!argv[idx + 1 || argv[idx + 1][0] == '-']) {
				pr_append_new_chunk_external (&warnings, "Character for masking not specified! Using the default value.");
				idx += 1;
				continue;
			}
			mp.masking_char = argv[idx + 1][0];
			if (strlen(argv[idx + 1]) > 1 || mp.masking_char < 33 || mp.masking_char > 126) {
				pr_append_new_chunk_external (&parse_err, "Invalid character for masking: ");
				pr_append_external (&parse_err, argv[idx + 1]);
				break;
			}
			idx += 1;
			
		} else if (!strcmp (argv[idx], "-d") || !strcmp (argv[idx], "--masking_direction")) {
			if (!argv[idx + 1] || argv[idx + 1][0] == '-') {
				pr_append_new_chunk_external (&warnings, "Masking direction not specified! Masking both strands by default.");
			} else if (!strcmp (argv[idx + 1], "both")) {
				mp.mdir = both_on_same;
			} else if (!strcmp (argv[idx + 1], "fwd")) {
				mp.mdir = fwd;
			} else if (!strcmp (argv[idx + 1], "rev")) {
				mp.mdir = rev;
			} else {
				pr_append_new_chunk_external (&warnings, "Unknown masking direction: ");
				pr_append_external (&warnings, argv[idx + 1]);
				pr_append_external (&warnings, ". Masking both strands by default.");
			}
			idx += 1;
			
		} else if (!strcmp (argv[idx], "-s") || !strcmp (argv[idx], "--soft_mask")) {
			mp.do_soft_masking = SOFT_MASKING;

		} else if (!strcmp (argv[idx], "-D")) {
			debug += 1;
			
		} else {
			pr_append_new_chunk_external (&parse_err, "Unknown parameter: ");
			pr_append_external (&parse_err, argv[idx]);
			break;
		}
	}

	input_seq = create_input_sequence_from_file_name (sequence_file_name, &parse_err);

	if (parse_err.data != NULL) {
		fprintf(stderr, "%s -> parsing commandline: ERROR: %s\n", pr_programme_name, parse_err.data);
		exit(-1);
	}
	if (warnings.data != NULL) {
		fprintf(stderr, "%s -> parsing commandline: WARNING: %s\n", pr_programme_name, warnings.data);
	}
	
	if (lists_file_name) {
		/* if lists are given in a text file */
		mp.fp = read_formula_parameters_from_file (lists_file_name, &nlist_parameters, &pbuilder, &mp.formula_intercept, &parse_err);
		nlists = pbuilder.nfp;
	} 
	
	if (npos != 0) {
		/* if lists are given by commandline arguments (can be added to the ones given in a file) */
		pbuilder.fp_array = mp.fp;

		for (idx = 0; idx < npos; idx++) {
			unsigned int pos = list_pos[idx] + 1;
			char *values[4];
			unsigned int nvalues = list_components[idx];
			char *end;
			memcpy (&values, &argv[pos], nvalues * sizeof(*argv));
			
			if (nvalues == 1) {
				double ic;
				double neg = 1.0;
				if (values[0][0] == '-') {
					values[0] += 1;
					neg = -1.0;
				}
				ic = strtod (values[0], &end);
				if (*end == 0) {
					mp.formula_intercept = ic * neg;
					continue;
				}
			}
			add_variable_to_formula_parameters (values, nvalues, &pbuilder, &parse_err);
		}		
		nlists = pbuilder.nfp;
		mp.fp = pbuilder.fp_array;

	} else if (nlists == 0 && !lists_file_name) {
		/* if there are no lists specified use the default formula */
		mp.fp = create_default_formula_parameters (mp.list_prefix, &parse_err);
		mp.formula_intercept = DEFAULT_INTERCEPT;
		nlists = DEFAULT_NLISTS;
		nlist_parameters = DEFAULT_NLIST_PARAMETERS;
	} 

	mp.nlists = nlists;
	
	if (mp.abs_cutoff > 0 && nlist_parameters != 1) {
		fprintf (stderr, "Error: Absolute value cutoff works with one list and one k-mer frequency parameter only. Currently you are using %u lists and %u parameters.\n", nlists, nlist_parameters);
		print_help(1);
	}

	if (parse_err.data != NULL) {
		fprintf(stderr, "%s -> building formula: ERROR: %s\n", pr_programme_name, parse_err.data);
		delete_input_sequence (input_seq);
		exit(-1);
	}
	
	if (debug > 0) print_parameters (&mp);
	
	read_and_mask_sequence (input_seq, NULL, &mp, &parse_err, debug);

	if (parse_err.data != NULL) {
		fprintf(stderr, "%s -> masking sequence: ERROR: %s\n", pr_programme_name, parse_err.data);
		delete_input_sequence (input_seq);
		delete_formula_parameters (mp.fp, nlists);
		exit(-1);
	}
	
	destroy_pr_append_str_data (&warnings);
	destroy_pr_append_str_data (&parse_err);
	delete_input_sequence (input_seq);
	delete_formula_parameters (mp.fp, nlists);
	
	if (debug > 0) fprintf (stderr, "Done!\n");
	return 0;
}
Ejemplo n.º 25
0
int main(int argc, char *argv[])
{
  Parameters *parameters; // user defined parameters
  Geometry *geometry; // homogenous cube geometry
  Material *material; // problem material
  Bank *source_bank; // array for particle source sites
  Tally *tally; // scalar flux tally
  double *keff; // effective multiplication factor
  double t1, t2; // timers

  #ifdef _OPENMP
    unsigned long counter = 0; //counter to decide the start pos of master bank copy from sub banks
    Bank *g_fission_bank; //global fission bank
  #endif

  // Get inputs: set parameters to default values, parse parameter file,
  // override with any command line inputs, and print parameters
  parameters = init_parameters();
  parse_parameters(parameters);
  read_CLI(argc, argv, parameters);
  print_parameters(parameters);


  // Set initial RNG seed
  set_initial_seed(parameters->seed);
  set_stream(STREAM_INIT);

  // Create files for writing results to
  init_output(parameters);

  // Set up geometry
  geometry = init_geometry(parameters);

  // Set up material
  material = init_material(parameters);

  // Set up tallies
  tally = init_tally(parameters);

  // Create source bank and initial source distribution
  source_bank = init_source_bank(parameters, geometry);

  // Create fission bank
  #ifdef _OPENMP
    omp_set_num_threads(parameters->n_threads); // Set number of openmp threads
    printf("threads num: %d\n", parameters->n_threads);
    // Allocate one master fission bank
    g_fission_bank = init_bank(2*parameters->n_particles);
  #endif

  // Set up array for k effective
  keff = calloc(parameters->n_active, sizeof(double));

  center_print("SIMULATION", 79);
  border_print();
  printf("%-15s %-15s %-15s\n", "BATCH", "KEFF", "MEAN KEFF");

  #ifdef _OPENMP
    // Start time
    t1 = omp_get_wtime();

    run_eigenvalue(counter, g_fission_bank, parameters, geometry, material, source_bank, fission_bank, tally, keff);

    // Stop time
    t2 = omp_get_wtime();
  #endif

  printf("Simulation time: %f secs\n", t2-t1);

  // Free memory
  #ifdef _OPENMP
    free_bank(g_fission_bank);
  #endif

  free(keff);
  free_tally(tally);
  free_bank(source_bank);
  free_material(material);
  free(geometry);
  free(parameters);

  return 0;
}
Ejemplo n.º 26
0
Archivo: main.c Proyecto: jemejia/LyaRT
int main(int argc, char *argv[])
{

	char HFile[NCHARMAX],tabledir_aux[NCHARMAX],Tstr[NCHARMAX];
	int first_time=0;
	float pmin,pmax;
	double tau_ini, x_medium;
	double pos3d[3];
	double s_nH,sx_cont,s_nd;
	double sq_mu,sq_mu2,sq_b,sq_a,sq_arg;
	double dust_fac = ext_zstar/zstar,P_H;
	long ip,i,j,k;
	const gsl_rng_type * T;
	time_t t0,t1,t2,t4,tc1,tc2;

	int NScatRec = 1e4;


	long ilow,ihigh;
	double x_1,x_0,H1,H0,xl,Hl,xlow,xhigh,rvp,vpl,vp0l,vp1l,ran0l,ran1l,vp0h,vp1h,ran0h,ran1h,vplow,vphigh;
	float tot_tab,used_tab;
//
	double Vth=sqrt(2*KB*Temp/MP);
	int upcone;

	c = 299792.482;   // km s-1
	Inv_c = 1./c;	
	Kth=Vth/(c*100000.0);
	

	gsl_rng *r;
	gsl_rng_env_setup();
    T = gsl_rng_default;
    r = gsl_rng_alloc (T);
	
   if(argc < 3)
    {
        printf(" Input parameter missing. \n ");
		printf(" Usage: > LyaRt [ParFile] [SEED] \n Exiting...");
        exit(0);
    }


/*	Paramter file is read, it defines most of the variables
	found in allvars.h */

	strcpy(ParFile,argv[1]);
	Seed0 = atoi(argv[2]);
	default_parameters();
	dprints(OutShort);
	dprints(OutLong);
	
	read_parameters(ParFile);
	dprints(OutShort);
	dprints(OutLong);

//	The following are definitions specific to particular geometries. 

	if (strcmp(GeomName,"Wind2")==0 || strcmp(GeomName,"Wind3")==0) 
	{	
		dr = (RSphere-R_inner) / (NCells-1);
		NCellSphere = R_inner/dr + 1.0;
		NCells += NCellSphere;
	}

	if (strcmp(GeomName,"Wind4")==0)
	{	
		NCellSphere		= 100;
		dr = R_Static / (NCellSphere-1);
		NCells = (long) ((RSphere - R_inner)/dr + 1.0);
		
		NCells += NCellSphere+1;
		if (NCells > 1e4)
			printf("WARNING: NCells = %ld value too high\n",NCells);
	}		
		
	if (strcmp(GeomName,"ThinShell2")==0)
	{
		NCellSphere = 500;
		dr1	= R_inner / (NCellSphere-1);
		dr2 = (RSphere-R_inner)/(NCells-1);
		NCells+= NCellSphere;
	}

//	---

	P		= (photon*) malloc(NPhotons * sizeof(photon));
	CellArr = (cell*) malloc(NCells * sizeof(cell));
	define_geometry(GeomName,CellArr);

	gsl_rng_set(r,Seed0);	//Initializing the random generator with seed Seed0?

	//Finding range of emission probability in cells

	pmin = CellArr[0].p_lya;
	pmax = pmin;

	for (i=1;i<NCells;i++)
	{	
		if(CellArr[i].p_lya < pmin)
			pmin = CellArr[i].p_lya;
		if(CellArr[i].p_lya > pmax)
			pmax = CellArr[i].p_lya;
	}

	strcpy(tabledir_aux,tabledir);	
	strcat(tabledir_aux,sxfile);
	strcpy(HFile,tabledir_aux);	

	if (Temp >= 0)
		sprintf(Tstr,"%.2f",Temp);
	else
		sprintf(Tstr,"%.1f",Temp);

	if (Temp > 0 && Temp < 1)
		sprintf(Tstr,"%.3f",Temp);

	strcat(HFile,Tstr);

	printf(" Storing tabulated data... \n");

	HList = (double*) malloc(NTAB2*sizeof(double)*2);
	DipList = (double*) malloc(NTAB1*2*sizeof(double));
	HGList = (float*) malloc(NTAB2*2*sizeof(float));

#ifndef HAPPROX	
	get_H(HFile,HList);
	printf("GET_H read\n");
#endif

	get_dipolar(DipList);	
	printf("GET_DIPOLAR read\n");
	get_HG(HGList);	
	printf("GET_HG read\n");

	// Print parameters read
	print_parameters(CellArr);

#ifdef TEST_RII
	printf("TESTING REDISTRIBUTION FUNCTION for x0 = %f\n",x_test);
#endif

	//Loop over NPhotons
	printf(" Loop over %ld photons started...\n",NPhotons);

	cx = 0.;
	cy = 0.;
	cz = 0.;

	nu0 = 2.47e15;
	
	gtype = (strcmp(GeomName,"HomSlab")==0) ? 0 : 1;
	if (strcmp(GeomName,"HomSphere")==0) gtype = 2;

	dprinti(gtype);	
	
	fflush(stdout);
	nout = 0;
	
#ifdef TCONST
	TPar = sx_const * pow(CellArr[0].T,-0.5);
#endif	

	XArr 		= (float *) malloc(NPhotons*sizeof(float));
	X0Arr           = (float *) malloc(NPhotons*sizeof(float));
	InterArr	= (int *) malloc(NPhotons*sizeof(int)); 
	NscatArr	= (int *) malloc(NPhotons*sizeof(int));
#ifdef GETPOSDIR
	PosArr		= (float *) malloc(NPhotons*3*sizeof(float));
	AngleArr	= (float *) malloc(NPhotons*2*sizeof(float));
	PosArrLong	= (float *) malloc(NPhotons*NScatRec*3*sizeof(float));
#endif

	for (i = 0; i< NPhotons; i++)
	{
		XArr[i]   = 0;
		X0Arr[i]   = 0;
		InterArr[i] = -1;
		NscatArr[i] = -1;
#ifdef GETPOSDIR
		PosArr[3*i] 	= 0;
		PosArr[3*i+1] 	= 0;
		PosArr[3*i+2]	= 0;
		AngleArr[2*i]	= 0;
		AngleArr[2*i+1]	= 0;
		for (j = 0;j<NScatRec;j++)
		{
			PosArrLong[0+ 3*i + 3*NPhotons*j] = 0;
			PosArrLong[1+ 3*i + 3*NPhotons*j] = 0;
			PosArrLong[2+ 3*i + 3*NPhotons*j] = 0;
		}
#endif
	}


	if (b == 0.)
	{
		a_par = 4.693e-4 * sqrt(1./CellArr[idc].T);
		vth = 12.85 * sqrt(CellArr[idc].T);
	}
	else 
	{	
		a_par = 4.693e-4 * sqrt(1./CellArr[idc].T);

//			a_par = 4.693e-4 * (12.85/b);
//			a_par = 4.7e-4 * (12.85/b);
//			vth	  = ;

		vth = 12.85 * sqrt(CellArr[idc].T);
	}

	if (VarXCrit==1)
	{ 
        x_medium = xp0 - vmax/vth;
		tau_ini	 = sx_const *  ColDens * pow(CellArr[idc].T,-0.5) * voigt(HList,x_medium);

		if (tau_ini < 1e4)
		  xcrit = 3;
		if (tau_ini >1e4 && tau_ini < 1e6)
		  xcrit = 6;
		if (tau_ini > 1e6)
		  xcrit = 10;
		//printf("1 xcrit: %f \n",xcrit);
	}

	
	(void) time(&t0);
	for (ip=0;ip < NPhotons;ip++)
	{
        nscat = 0;
		
		if( ip > 999 & ip % 1000 == 0)
	  	{
	   		printf("Photon %ld\n",ip);
	    	if( first_time==0 )
	     	{
				first_time=1;
				printf("Estimated time to finish: %f [min] \n",1000*op_time * (NPhotons - ip) );
	      	}
	  	}

//		Initialise photon's frequency, direction and position.

		xi0 = gsl_rng_uniform (r);
		xi1 = gsl_rng_uniform (r);
		xi2 = gsl_rng_uniform (r);

			
		xi3 = gsl_rng_uniform (r);
		xi4 = gsl_rng_uniform (r);
		xi5 = gsl_rng_uniform (r);

		init_photon(P,ip, xi0, xi1, xi2);		  

		dnd = (vth*nu0)/c;
		flag_zero = 0;

		(void) time(&t1);
		i = 0;
		xi1 = gsl_rng_uniform (r);
		xi2 = gsl_rng_uniform (r);
		xi3 = gsl_rng_uniform (r);
		idc_old = 0;
		while(idc != -1)
		{
			t_0 = - log(gsl_rng_uniform (r));
		
			EscCond = 0;

			P[ip].ni = sin(th0)*cos(ph0);
			P[ip].nj = sin(th0)*sin(ph0);
			P[ip].nk = cos(th0);

			while(t_0 > 0.)
			{  	

				// Shortcut to compute crossing of empty cells, where no optical depth (t_0) is *used*.
				empty_cells(P,ip);				
				H_x = voigt(HList, P[ip].xp);
	
				if(isnan(H_x)) 
					printf("H_x is nan\n");

//				H_x = 0.;     // H_x disables H scattering. 
	
#ifdef TCONST 
				
				s_nH = TPar * H_x*CellArr[idc].nH;

#else	
				s_nH = sx_const * pow(CellArr[idc].T,-0.5)*H_x*CellArr[idc].nH;
#endif

#ifdef TAUGUIDERDONI
				s_nd = Ext_Ratio * pow(CellArr[idc].z/zstar,spar) * CellArr[idc].nH/NHConst;
#else
				s_nd =  ext_zstar * CellArr[idc].z * CellArr[idc].nH;
#endif
	
				s_sum = s_nH + s_nd;
				s = t_0 / s_sum;

				radius = sqrt( SQR(P[ip].x) + SQR(P[ip].y)+ SQR(P[ip].z));
				
				// The position of the photon after consuming its optical depth is computed here:
				s_ = crossing_cells(P,gtype,ip);
	            
				rx0 = P[ip].x;
				ry0 = P[ip].y;
				rz0 = P[ip].z;

				ni = P[ip].ni;
				nj = P[ip].nj;	
				nk = P[ip].nk;	

			}

	        if (EscCond == 1)
   			{
			
#ifndef TEST_RII	
				idc = -1;
#else
				idc = 0;
#endif

	   			if (idc == -1)
   	   			{
escape:
	
					x = P[ip].xp + (P[ip].ni*vbulk_x + P[ip].nj*vbulk_y + P[ip].nk*vbulk_z)/vth;

//				x = c*(g*nup - nu0)/(vth*nu0) - g*(nup/nu0)*(ni*vbulk_x + nj*vbulk_y + nk*vbulk_z)/vth;

//				dprintd(x);
//				printf("Photon has escaped in %ld scatterings\n",nscat);
// ................................

					inter = 4;
					(void) time(&t2);
					op_time = (float) (t2-t1)/60.;
//			printf("Total calculation took %f minutes.\n",op_time);
					if (strcmp(OutMode,"Long")==0)
					{
						printf("\n");
						record_data_long(nscat,ip,x,P[ip].x,P[ip].y,P[ip].z,r0,upar,uper1,uper2,H_x,P[ip].xp,inter);
					}
					else
					{
//					record_data_short(nscat,ip,x,rxf,ryf,rzf,radius,H_x,inter,op_time,flag_zero);
						XArr[ip] = x;
						X0Arr[ip]=xp0;
						InterArr[ip] = inter;
						NscatArr[ip] = nscat;
					
#ifdef GETPOSDIR
						PosArr[3*ip] 	= P[ip].x;
						PosArr[3*ip+1]	= P[ip].y;
						PosArr[3*ip+2]	= P[ip].z;
						AngleArr[2*ip]	= P[ip].th;
						AngleArr[2*ip+1]= P[ip].ph;	
//						record_data_pos(nscat,ip,x,ph0,th0,rxf,ryf,rzf,inter,op_time,flag_zero);
//#else
//						record_data_short(nscat,ip,x,ph0,th0,radius,inter,op_time,flag_zero);
#endif
					
					}
					nout++;
					goto end;
					break;
				}
   			}
   			else
   			{

				rx0 = rxf;
				ry0 = ryf;
				rz0 = rzf;
				
			}

			P_H = s_nH / s_sum;
			xi1 = gsl_rng_uniform (r);
	
			if (strcmp(IncDust,"Yes")==0)
				inter = (xi1 <= P_H)? 1 : 2 ;
			else
				inter = 1;
		
			switch(inter)	// inter = 1 means interacting with hydrogen, inter = 2 means dust.
			{
				case  1:
	
#ifdef USEREJECTION
			upar = -999.0;
			i = 0;
			do
			{
				xi0 = gsl_rng_uniform (r);
				xi1 = gsl_rng_uniform (r);
				xi2 = gsl_rng_uniform (r);
				upar = vp_rejection(xp,a_par,xi0,xi1,xi2);
				i++;
			} while(upar == -999.0);
//	if (i > 100000)
//						printf("VP_REJECTION TOOK %d tries to get upar = %f, x = %f,  nscatter = %d\n" \
						 ,i,upar,xp,nscat);
#endif
			
				xi0 = gsl_rng_uniform (r);
				xi1 = gsl_rng_uniform (r);
				xi2 = gsl_rng_uniform (r);
				xi3 = gsl_rng_uniform (r);
				xi3 = (xi3 == 0.0) ? gsl_rng_uniform (r) : xi3;
				xi4 = gsl_rng_uniform (r);
				xi5 = gsl_rng_uniform (r);
				xi6 = gsl_rng_uniform (r);
				xi7 = gsl_rng_uniform (r);

				scattering_hydrogen(P,ip);
				break;
				
				case 2:
				xi1 = gsl_rng_uniform (r);
				xi2 = gsl_rng_uniform (r);
				xi3 = gsl_rng_uniform (r);

				dust_interaction(P,ip);
				if (end_syg ==1)
					goto end;
				break;
			}
	
//			dprinti(nscat);

/*
			if (nscat == 1000000 || nscat == 10000000 )
			{
				printf("********************************************\n");
				printf("Number of scatterings so far: %ld\n",nscat);
				printf("Photon's location %f %f %f\n",rxf,ryf,rzf);
				dprintf(x);
				dprintf(xp);
				dprintf(th0);
				dprintf(ph0);
			}
*/
				
#ifdef WRITEALL
			if (ip < 1000)
			{
				x = P[ip].xp + (P[ip].ni*vbulk_x + P[ip].nj*vbulk_y + P[ip].nk*vbulk_z)/vth;
				record_data_long(nscat,ip,x,P[ip].x,P[ip].y,P[ip].z,r0,upar,uper1,uper2,H_x,\
				P[ip].xp,inter);
			}
#endif
			if (gtype ==1)
			{
				if (r0 < 0.99*R_inner)
				{
					printf("scatter %d of photon %d occurs within empty zone. Something is not ok\n",nscat,ip);
					printf("rx/r_inner %f ry/r_inner %f rz/r_inner %f radius/r_inner %f\nidc %d\n",\
					P[ip].x/R_inner,P[ip].y/R_inner,P[ip].z/R_inner,r0/R_inner,idc);
				}
			}
			nscat++;
		}				
		

		end:
//	printf("done\n");


	

		if (strcmp(Set_Tolerance,"yes") == 0)
		{
//		if ((ip >= np_min && nout >= nout_max) || \
//			(ip >= np_max))

			if ((ip >= np_min && nout >= nout_max) || \
			(ip >= np_max) )
//			(ip >= np_max && nout >= (int) nout_max/5) || \

			{
				printf("Max number of absorbed photons or limit on the number of photons reached,  exiting...\n");

#ifdef GETPOSDIR
				printf("Writing data\n");
				record_data_pos(ip);
				printf("File %s written\n",OutShort);
				free(PosArr);
				free(AngleArr);
#else
				record_data_short();
#endif
				free(HList);
				free(DipList);
				free(HGList);
				free(CellArr);
				exit(0);
			}
		}		

#ifdef TIMELIMIT
		(void) time(&t4);
		t4 = (float) (t4-t0)/60.;
		if (t4 > MAXTIME)
		{
			printf("MAXTIME reached, forcing output and exit\n");
#ifdef GETPOSDIR
			record_data_pos(ip);
			printf("File %s written\n",OutShort);
			free(PosArr);
			free(AngleArr);
#else
			record_data_short();
#endif
			exit(0);
		}
#endif

		//printf("%ld %f\n",ip,xp);


	}
Ejemplo n.º 27
0
int main (int argc, char* argv[]) {
	char filename1[200];
	char filename2[200];
	char pairs_file[200];
	char fileout[200];
	FILE* query_fp = 0;
	FILE* reference_fp = 0;
	FILE* fp_pairs = 0;
	FILE* fpout = stdout;
	int total_pairs = 0;
	pair_struct* pairs = 0;
	/* Set Default Parameter Values*/
	length_5p_for_weighting = 8;	/* The 5' sequence length to be weighed  except for the last residue*/
	scale = 4.0;			/* The 5' miRNA scaling parameter*/
	strict = 0;			/* Strict seed model on/off*/
	debug = 0;			/* Debugging mode on/off*/
	key_value_pairs = 0;
	gap_open = -9.0;		/* Gap-open Penalty*/
	gap_extend = -4.0;		/* Gap-extend Penalty*/
	score_threshold = 140.0;	/* SW Score Threshold for reporting hits*/
	energy_threshold = 1.0;		/* Energy Threshold (DG) for reporting hits*/
	verbosity = 1;			/* Verbose mode on/off*/
	outfile = 0;			/* Dump to file on/off*/
	truncated = 0;			/* Truncate sequences on/off*/
	no_energy = 0;			/* Turn off Vienna Energy Calcs - FASTER*/
	restricted = 0;			/* Perform restricted search space*/
	parse_command_line(argc, argv, filename1, filename2, fileout, pairs_file);
	if (gap_open > 0.0 || gap_extend > 0.0) {
		fprintf(stderr, "Error: gap penalties may not be greater than 0\n");
		return 1;
	}
	if (truncated < 0) {
		fprintf(stderr, "Error: negative value give for UTR truncation\n");
		return 1;
	}
	if ((query_fp = fopen(filename1, "r")) == NULL) {
		fprintf(stderr, "Error: Cannot open file %s\n", filename1);
		return 1;
	}
	if ((reference_fp = fopen(filename2, "r")) == NULL) {
		fprintf(stderr, "Error: Cannot open file %s\n", filename2);
		return 1;
	}
	fclose(reference_fp);
	if ((outfile) && ((fpout = fopen(fileout, "w")) == NULL)) {
		fprintf(stderr, "Error: Cannot create output file %s\n", fileout);
		return 1;
	}
	if (restricted) {
		if ((fp_pairs = fopen(pairs_file, "r")) == NULL) {
			fprintf(stderr, "Error: Cannot open restrict pairs file %s\n", pairs_file);
			return 1;
		}
		/* Initialize the pairs list for restriced searches*/
		total_pairs = load_pairs(fp_pairs, &pairs);
		fclose(fp_pairs);
	}
	initialize_globals();
	print_parameters(filename1, filename2, fpout);
	if (restricted && verbosity) {
		printf("Performing Restricted Scan on:%d pairs\n", total_pairs);
	}
	find_targets(query_fp, fpout, pairs, total_pairs, filename2);
	destroy_globals();
	if (outfile) fclose(fpout);
	fclose(query_fp);
	return 0;
}