コード例 #1
0
void init_parameters()
{
  if(!load_parameters(configfilename))
    if(!load_parameters("/usr/local/share/dancingparticles/dancingparticles.conf"))
      {
      }
}
コード例 #2
0
ファイル: main.cpp プロジェクト: shaobinzhang/powertop
static void powertop_init(void)
{
	static char initialized = 0;
	int ret;
	struct statfs st_fs;
	struct rlimit rlmt;

	if (initialized)
		return;

	checkroot();

	rlmt.rlim_cur = rlmt.rlim_max = get_nr_open();
	setrlimit (RLIMIT_NOFILE, &rlmt);

	ret = system("/sbin/modprobe cpufreq_stats > /dev/null 2>&1");
	ret = system("/sbin/modprobe msr > /dev/null 2>&1");
	statfs("/sys/kernel/debug", &st_fs);

	if (st_fs.f_type != (long) DEBUGFS_MAGIC) {
		if (access("/bin/mount", X_OK) == 0) {
			ret = system("/bin/mount -t debugfs debugfs /sys/kernel/debug > /dev/null 2>&1");
		} else {
			ret = system("mount -t debugfs debugfs /sys/kernel/debug > /dev/null 2>&1");
		}
		if (ret != 0) {
			printf(_("Failed to mount debugfs!\n"));
			printf(_("exiting...\n"));
			exit(EXIT_FAILURE);
		}
	}

	srand(time(NULL));

	if (access("/var/cache/", W_OK) == 0)
		mkdir("/var/cache/powertop", 0600);
	else
		mkdir("/data/local/powertop", 0600);

	load_results("saved_results.powertop");
	load_parameters("saved_parameters.powertop");

	enumerate_cpus();
	create_all_devices();
	detect_power_meters();

	register_parameter("base power", 100, 0.5);
	register_parameter("cpu-wakeups", 39.5);
	register_parameter("cpu-consumption", 1.56);
	register_parameter("gpu-operations", 0.5576);
	register_parameter("disk-operations-hard", 0.2);
	register_parameter("disk-operations", 0.0);
	register_parameter("xwakes", 0.1);

        load_parameters("saved_parameters.powertop");

	initialized = 1;
}
コード例 #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;
  }
}
コード例 #4
0
ファイル: Replay.cpp プロジェクト: BellX1/ardupilot
void ReplayVehicle::setup(void) 
{
    load_parameters();
    
    // we pass zero log structures, as we will be outputting the log
    // structures we need manually, to prevent FMT duplicates
    dataflash.Init(log_structure, 0);
    dataflash.StartNewLog();

    ahrs.set_compass(&compass);
    ahrs.set_fly_forward(true);
    ahrs.set_wind_estimation(true);
    ahrs.set_correct_centrifugal(true);
    ahrs.set_ekf_use(true);

    EKF2.set_enable(true);
                        
    printf("Starting disarmed\n");
    hal.util->set_soft_armed(false);

    barometer.init();
    barometer.setHIL(0);
    barometer.update();
    compass.init();
    ins.set_hil_mode();
}
コード例 #5
0
ファイル: main.c プロジェクト: LockeKK/Kassist
void main(void) 
{
	board_int();
	//security_init();
	load_parameters();
	host_cmd_init();
	init_servo_reader();
	init_servo_output();
	verify_encrypted_uid();
	beep_notify(POWER_ON);

	while(1)
	{
		service_systick();
		read_rc_channels();
		host_cmd_process();		
		//setup_mode_service();
		input_ch3_handler();
		update_servo_output();
		check_no_signal();
		diagnostics_service();
		notification_service();
		battery_guard_service();
	}
}
コード例 #6
0
ファイル: gmm_classifier.cpp プロジェクト: gpldecha/sandbox
Gmm_classifier::Gmm_classifier(std::string path_to_parameters):
Classifier()
{

    load_parameters(path_to_parameters);

}
コード例 #7
0
ファイル: system.cpp プロジェクト: RaiBearG/ardupilot
void Plane::init_ardupilot()
{
    // initialise serial port
    serial_manager.init_console();

    cliSerial->printf("\n\nInit " FIRMWARE_STRING
                         "\n\nFree RAM: %u\n",
                      (unsigned)hal.util->available_memory());


    //
    // Check the EEPROM format version before loading any parameters from EEPROM
    //
    load_parameters();

    // initialise stats module
    g2.stats.init();

#if HIL_SUPPORT
    if (g.hil_mode == 1) {
        // set sensors to HIL mode
        ins.set_hil_mode();
        compass.set_hil_mode();
        barometer.set_hil_mode();
    }
#endif

    set_control_channels();
    
#if HAVE_PX4_MIXER
    if (!quadplane.enable) {
        // this must be before BoardConfig.init() so if
        // BRD_SAFETYENABLE==0 then we don't have safety off yet. For
        // quadplanes we wait till AP_Motors is initialised
        for (uint8_t tries=0; tries<10; tries++) {
            if (setup_failsafe_mixing()) {
                break;
            }
            hal.scheduler->delay(10);
        }
    }
#endif

    gcs().set_dataflash(&DataFlash);

    mavlink_system.sysid = g.sysid_this_mav;

    // initialise serial ports
    serial_manager.init();
    gcs().chan(0).setup_uart(serial_manager, AP_SerialManager::SerialProtocol_MAVLink, 0);


    // specify callback function for CLI menu system
#if CLI_ENABLED == ENABLED
    if (g.cli_enabled) {
        gcs().set_run_cli_func(FUNCTOR_BIND_MEMBER(&Plane::run_cli, void, AP_HAL::UARTDriver *));
    }
コード例 #8
0
ファイル: saio_main.c プロジェクト: parkag/saio
/* Module load */
void
_PG_init(void)
{
	/* Install hook */
	prev_join_search_hook = join_search_hook;
	join_search_hook = saio_main;

	load_parameters();
}
コード例 #9
0
void api_generator::load_method_descriptions(const fc::variants& method_descriptions)
{
  for (const fc::variant& method_description_variant : method_descriptions)
  {
    fc::variant_object json_method_description = method_description_variant.get_object();
    FC_ASSERT(json_method_description.contains("method_name"), "method entry missing \"method_name\"");
    std::string method_name = json_method_description["method_name"].as_string();
    FC_ASSERT(_registered_method_names.find(method_name) == _registered_method_names.end(),
              "Error: multiple methods registered with the name ${name}", ("name", method_name));
    _registered_method_names.insert(method_name);
    try
    {
      method_description method;
      method.name = method_name;
      FC_ASSERT(json_method_description.contains("return_type"), "method entry missing \"return_type\"");
      std::string return_type_name = json_method_description["return_type"].as_string();
      method.return_type = lookup_type_mapping(return_type_name);
      
      FC_ASSERT(json_method_description.contains("parameters"), "method entry missing \"parameters\"");
      method.parameters = load_parameters(json_method_description["parameters"].get_array());

      method.is_const = json_method_description.contains("is_const") && 
                               json_method_description["is_const"].as_bool();

      FC_ASSERT(json_method_description.contains("prerequisites"), "method entry missing \"prerequisites\"");
      method.prerequisites = load_prerequisites(json_method_description["prerequisites"]);

      if (json_method_description.contains("aliases"))
      {
        method.aliases = json_method_description["aliases"].as<std::vector<std::string> >();
        for (const std::string& alias : method.aliases)
        {
          FC_ASSERT(_registered_method_names.find(alias) == _registered_method_names.end(),
                    "Error: alias \"${alias}\" conflicts with an existing method or alias", ("alias", alias));
          _registered_method_names.insert(alias);
        }
      }
      
      if (json_method_description.contains("description"))
        method.brief_description = json_method_description["description"].as_string();

      if (json_method_description.contains("detailed_description"))
        method.detailed_description = json_method_description["detailed_description"].as_string();

      _methods.push_back(method);
    }
    FC_RETHROW_EXCEPTIONS(warn, "error encountered parsing method description for method \"${method_name}\"", ("method_name", method_name));
  }
}
コード例 #10
0
ファイル: system.cpp プロジェクト: MarkHarbison/ardupilot
void Rover::init_ardupilot()
{
    // initialise console serial port
    serial_manager.init_console();

	cliSerial->printf("\n\nInit " FIRMWARE_STRING
						 "\n\nFree RAM: %u\n",
                        hal.util->available_memory());
                    
	//
	// Check the EEPROM format version before loading any parameters from EEPROM.
	//
	
    load_parameters();

    BoardConfig.init();

    // initialise serial ports
    serial_manager.init();

    ServoRelayEvents.set_channel_mask(0xFFF0);

    set_control_channels();

    battery.init();

    // keep a record of how many resets have happened. This can be
    // used to detect in-flight resets
    g.num_resets.set_and_save(g.num_resets+1);

    // init baro before we start the GCS, so that the CLI baro test works
    barometer.init();

	// init the GCS
    gcs[0].setup_uart(serial_manager, AP_SerialManager::SerialProtocol_Console, 0);

    // we start by assuming USB connected, as we initialed the serial
    // port with SERIAL0_BAUD. check_usb_mux() fixes this if need be.    
    usb_connected = true;
    check_usb_mux();

    // setup serial port for telem1
    gcs[1].setup_uart(serial_manager, AP_SerialManager::SerialProtocol_MAVLink, 0);

    // setup serial port for telem2
    gcs[2].setup_uart(serial_manager, AP_SerialManager::SerialProtocol_MAVLink, 1);

    // setup serial port for fourth telemetry port (not used by default)
    gcs[3].setup_uart(serial_manager, AP_SerialManager::SerialProtocol_MAVLink, 2);

    // setup frsky telemetry
#if FRSKY_TELEM_ENABLED == ENABLED
    frsky_telemetry.init(serial_manager);
#endif

	mavlink_system.sysid = g.sysid_this_mav;

#if LOGGING_ENABLED == ENABLED
    log_init();
#endif

    // Register mavlink_delay_cb, which will run anytime you have
    // more than 5ms remaining in your call to hal.scheduler->delay
    hal.scheduler->register_delay_callback(mavlink_delay_cb_static, 5);

	if (g.compass_enabled==true) {
		if (!compass.init()|| !compass.read()) {
            cliSerial->println("Compass initialisation failed!");
            g.compass_enabled = false;
        } else {
            ahrs.set_compass(&compass);
            //compass.get_offsets();						// load offsets to account for airframe magnetic interference
        }
	}

	// initialise sonar
    init_sonar();

    // and baro for EKF
    init_barometer();

	// Do GPS init
    gps.init(&DataFlash, serial_manager);

    rc_override_active = hal.rcin->set_overrides(rc_override, 8);

	init_rc_in();		// sets up rc channels from radio
	init_rc_out();		// sets up the timer libs

    relay.init();

#if MOUNT == ENABLED
    // initialise camera mount
    camera_mount.init(serial_manager);
#endif

    /*
      setup the 'main loop is dead' check. Note that this relies on
      the RC library being initialised.
     */
    hal.scheduler->register_timer_failsafe(failsafe_check_static, 1000);


#if CLI_ENABLED == ENABLED
	// If the switch is in 'menu' mode, run the main menu.
	//
	// Since we can't be sure that the setup or test mode won't leave
	// the system in an odd state, we don't let the user exit the top
	// menu; they must reset in order to fly.
	//
    if (g.cli_enabled == 1) {
        const char *msg = "\nPress ENTER 3 times to start interactive setup\n";
        cliSerial->println(msg);
        if (gcs[1].initialised && (gcs[1].get_uart() != NULL)) {
            gcs[1].get_uart()->println(msg);
        }
        if (num_gcs > 2 && gcs[2].initialised && (gcs[2].get_uart() != NULL)) {
            gcs[2].get_uart()->println(msg);
        }
    }
#endif

	init_capabilities();

	startup_ground();

    set_mode((enum mode)g.initial_mode.get());

	// set the correct flight mode
	// ---------------------------
	reset_control_switch();
}
コード例 #11
0
ファイル: ctx.c プロジェクト: emilianobonassi/OpenSC
static void process_config_file(sc_context_t *ctx, struct _sc_ctx_options *opts)
{
	int i, r, count = 0;
	scconf_block **blocks;
	const char *conf_path = NULL;
#ifdef _WIN32
	char temp_path[PATH_MAX];
	DWORD temp_len;
	long rc;
	HKEY hKey;
#endif

	memset(ctx->conf_blocks, 0, sizeof(ctx->conf_blocks));
#ifdef _WIN32
	conf_path = getenv("OPENSC_CONF");
	if (!conf_path) {
		rc = RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\OpenSC Project\\OpenSC", 0, KEY_QUERY_VALUE, &hKey);
		if (rc == ERROR_SUCCESS) {
			temp_len = PATH_MAX;
			rc = RegQueryValueEx( hKey, "ConfigFile", NULL, NULL, (LPBYTE) temp_path, &temp_len);
			if ((rc == ERROR_SUCCESS) && (temp_len < PATH_MAX))
				conf_path = temp_path;
			RegCloseKey(hKey);
		}
	}

	if (!conf_path) {
		rc = RegOpenKeyEx( HKEY_LOCAL_MACHINE, "Software\\OpenSC Project\\OpenSC", 0, KEY_QUERY_VALUE, &hKey );
		if (rc == ERROR_SUCCESS) {
			temp_len = PATH_MAX;
			rc = RegQueryValueEx( hKey, "ConfigFile", NULL, NULL, (LPBYTE) temp_path, &temp_len);
			if ((rc == ERROR_SUCCESS) && (temp_len < PATH_MAX))
				conf_path = temp_path;
			RegCloseKey(hKey);
		}
	}

	if (!conf_path) {
		sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "process_config_file doesn't find opensc config file. Please set the registry key.");
		return;
	}

#else
	conf_path = getenv("OPENSC_CONF");
	if (!conf_path)
		conf_path = OPENSC_CONF_PATH;
#endif
	ctx->conf = scconf_new(conf_path);
	if (ctx->conf == NULL)
		return;
	r = scconf_parse(ctx->conf);
#ifdef OPENSC_CONFIG_STRING
	/* Parse the string if config file didn't exist */
	if (r < 0)
		r = scconf_parse_string(ctx->conf, OPENSC_CONFIG_STRING);
#endif
	if (r < 1) {
		/* A negative return value means the config file isn't
		 * there, which is not an error. Nevertheless log this
		 * fact. */
		if (r < 0)
			sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "scconf_parse failed: %s", ctx->conf->errmsg);
		else
			sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "scconf_parse failed: %s", ctx->conf->errmsg);
		scconf_free(ctx->conf);
		ctx->conf = NULL;
		return;
	}
	blocks = scconf_find_blocks(ctx->conf, NULL, "app", ctx->app_name);
	if (blocks[0])
	    	ctx->conf_blocks[count++] = blocks[0];
	free(blocks);
	if (strcmp(ctx->app_name, "default") != 0) {
		blocks = scconf_find_blocks(ctx->conf, NULL, "app", "default");
		if (blocks[0])
		    	ctx->conf_blocks[count] = blocks[0];
		free(blocks);
	}
	/* Above we add 2 blocks at most, but conf_blocks has 3 elements,
	 * so at least one is NULL */
	for (i = 0; ctx->conf_blocks[i]; i++)
		load_parameters(ctx, ctx->conf_blocks[i], opts);
}
コード例 #12
0
ファイル: bayesoptmex.c プロジェクト: MLDL/bayesopt
void mexFunction(int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
{
  double *xptr;
  mxArray *xopt;
  const mxArray *func_name, *params;
  user_function_data udata;
  size_t nDim;
  unsigned int ii;
  bopt_params parameters;
  double *ub, *lb;    /* Upper and lower bound */
  double fmin;
  int error_code;
     
  /* Check correct number of parameters */
  CHECK0(nlhs != 2 || nrhs != 3 || nrhs != 5, 
	 "wrong number of arguments");
    
  /* TODO: Change This */
  udata.neval = 0;
  udata.verbose = 0;
   
  /* First term is the function handle or name */
  func_name = prhs[0];

  if (mxIsChar(func_name))
    {
      CHECK0(mxGetString(func_name, udata.f, FLEN) == 0,
	     "error reading function name string (too long?)");
      udata.nrhs = 1;
      udata.xrhs = 0;
    }
#ifndef HAVE_OCTAVE
  else if (mxIsFunctionHandle(func_name))
    {
      udata.prhs[0] = (mxArray *)func_name;
      strcpy(udata.f, "feval");
      udata.nrhs = 2;
      udata.xrhs = 1;
      }
#endif
  else
    {
      mexErrMsgTxt("First term should be a function name or function handle");
    }

  /* Second parameter. nDim */
  CHECK0(mxIsNumeric(prhs[1]) && !mxIsComplex(prhs[1]) 
	 && mxGetM(prhs[1]) * mxGetN(prhs[1]) == 1,
	 "nDim must be a scalar");
  nDim = (unsigned int) mxGetScalar(prhs[1]);

  udata.prhs[udata.xrhs] = mxCreateDoubleMatrix(1, nDim, mxREAL);

  xopt = mxCreateDoubleMatrix(1, nDim, mxREAL);
  xptr = mxGetPr(xopt);
     
  /* Third term. Parameters  */
  if (nrhs != 2)
    {
      CHECK0(mxIsStruct(prhs[2]), "3rd element must be a struct");
      params = prhs[2];
    }
  else
    {
      params = mxCreateStructMatrix(1,1,0,NULL);
    }
  parameters = load_parameters(params);

  if(nrhs == 5)
    {
      /* Load bounds */
      mexPrintf("Loading bounds...");
      CHECK0(mxIsDouble(prhs[3]) && !mxIsComplex(prhs[3])
	     && (mxGetM(prhs[3]) == 1    || mxGetN(prhs[3]) == 1)
	     && (mxGetM(prhs[3]) == nDim || mxGetN(prhs[3]) == nDim),
	     "lowerBound must be real row or column vector");

      lb = mxGetPr(prhs[3]);


      CHECK0(mxIsDouble(prhs[4]) && !mxIsComplex(prhs[4])
	     && (mxGetM(prhs[4]) == 1    || mxGetN(prhs[4]) == 1)
	     && (mxGetM(prhs[4]) == nDim || mxGetN(prhs[4]) == nDim),
	     "upperBound must be real row or column vector");

      ub = mxGetPr(prhs[4]);
      mexPrintf("done. \n");
    }
  else
    {
      lb = (double*)(mxCalloc(nDim,sizeof(double)));
      ub = (double*)(mxCalloc(nDim,sizeof(double)));
	 

      
      for (ii = 0; ii < nDim; ++ii) 
	{
	  lb[ii] = 0.;    
	  ub[ii] = 1.;
	}
    }

  error_code = bayes_optimization(nDim,user_function,&udata,lb,ub,xptr,
				  &fmin,parameters);

  if(nrhs != 5)
    {
      mxFree(lb); 
      mxFree(ub);
    }

  mxDestroyArray(udata.prhs[udata.xrhs]);
  plhs[0] = xopt;
  if (nlhs > 1) 
    {
      plhs[1] = mxCreateDoubleMatrix(1, 1, mxREAL);
      *(mxGetPr(plhs[1])) = fmin;
    }
  if (nlhs > 2)
    {
      plhs[2] = mxCreateDoubleMatrix(1, 1, mxREAL);
      *(mxGetPr(plhs[2])) = (double)(error_code);
    }

}
コード例 #13
0
ファイル: system.cpp プロジェクト: 27Seanerz/ardupilot
void Tracker::init_tracker()
{
    // initialise console serial port
    serial_manager.init_console();

    hal.console->printf("\n\nInit " THISFIRMWARE
                               "\n\nFree RAM: %u\n",
                          hal.util->available_memory());

    // Check the EEPROM format version before loading any parameters from EEPROM
    load_parameters();

    BoardConfig.init();

    // initialise serial ports
    serial_manager.init();

    // init baro before we start the GCS, so that the CLI baro test works
    barometer.init();

    // we start by assuming USB connected, as we initialed the serial
    // port with SERIAL0_BAUD. check_usb_mux() fixes this if need be.    
    usb_connected = true;
    check_usb_mux();

    // setup telem slots with serial ports
    for (uint8_t i = 0; i < MAVLINK_COMM_NUM_BUFFERS; i++) {
        gcs[i].setup_uart(serial_manager, AP_SerialManager::SerialProtocol_MAVLink, i);
        gcs[i].set_snoop(mavlink_snoop_static);
    }

    // Register mavlink_delay_cb, which will run anytime you have
    // more than 5ms remaining in your call to hal.scheduler->delay
    hal.scheduler->register_delay_callback(mavlink_delay_cb_static, 5);
    
    mavlink_system.sysid = g.sysid_this_mav;

#if LOGGING_ENABLED == ENABLED
    log_init();
#endif

    GCS_MAVLINK::set_dataflash(&DataFlash);

    if (g.compass_enabled==true) {
        if (!compass.init() || !compass.read()) {
            hal.console->println("Compass initialisation failed!");
            g.compass_enabled = false;
        } else {
            ahrs.set_compass(&compass);
        }
    }

    // GPS Initialization
    gps.init(NULL, serial_manager);

    ahrs.init();
    ahrs.set_fly_forward(false);

    ins.init(scheduler.get_loop_rate_hz());
    ahrs.reset();

    init_barometer(true);

    // set serial ports non-blocking
    serial_manager.set_blocking_writes_all(false);

    // initialise servos
    init_servos();

    // use given start positions - useful for indoor testing, and
    // while waiting for GPS lock
    // sanity check location
    if (fabsf(g.start_latitude) <= 90.0f && fabsf(g.start_longitude) <= 180.0f) {
        current_loc.lat = g.start_latitude * 1.0e7f;
        current_loc.lng = g.start_longitude * 1.0e7f;
        gcs_send_text(MAV_SEVERITY_NOTICE, "Ignoring invalid START_LATITUDE or START_LONGITUDE parameter");
    }

    // see if EEPROM has a default location as well
    if (current_loc.lat == 0 && current_loc.lng == 0) {
        get_home_eeprom(current_loc);
    }

    init_capabilities();

    gcs_send_text(MAV_SEVERITY_INFO,"Ready to track");
    hal.scheduler->delay(1000); // Why????

    set_mode(AUTO); // tracking

    if (g.startup_delay > 0) {
        // arm servos with trim value to allow them to start up (required
        // for some servos)
        prepare_servos();
    }

}
コード例 #14
0
ファイル: bacterias.cpp プロジェクト: meithan/bacterias
int main (int argc, char** argv) {

  char strbuf[256];
  time_t raw_time;

  // Load parameters from the specified file
  if (argc != 2) {
    printf("Error! Must provide a parameters filename as first argument\n");
    exit(EXIT_FAILURE);
  } else {
    raw_time = time(NULL);
    printf(">> %s", ctime(&raw_time));
  }
  params_fname = new char[strlen(argv[1])];
  strcpy(params_fname, argv[1]);
  printf(">> Reading parameters file %s ...\n", params_fname);
  load_parameters(params_fname);
  
  const int report_interval = (num_cycles > 100 ? num_cycles : 100) / 100; 
  
  // Open log and data files
  log_file = fopen(log_fname,"w");
  output_file = fopen(output_fname,"w");
  printf(">> Opened log file %s\n", log_fname);
  raw_time = time(NULL);
  sprintf(strbuf, ">> %s", ctime(&raw_time)); log(strbuf, false);
  sprintf(strbuf, ">> Read parameters file %s ...\n", params_fname); log(strbuf, false);

  // Report parameters
  sprintf(strbuf, "grid_size = %i\n", grid_size); log(strbuf);
  sprintf(strbuf, "num_cycles = %i\n", num_cycles); log(strbuf);
  sprintf(strbuf, "growth_multiplier = %f\n", growth_multiplier); log(strbuf);
  sprintf(strbuf, "global_death_rate = %f\n", global_death_rate); log(strbuf);
  sprintf(strbuf, "all_die = %s\n", all_die ? "true" : "false"); log(strbuf);
  sprintf(strbuf, "report_to_screen = %s\n", report_to_screen ? "true" : "false"); log(strbuf);
  sprintf(strbuf, "log_fname = %s\n", log_fname); log(strbuf);
  sprintf(strbuf, "output_fname = %s\n", output_fname); log(strbuf);
  sprintf(strbuf, "output_interval = %i\n", output_interval); log(strbuf);
  sprintf(strbuf, "num_strains = %i\n", num_strains); log(strbuf);
  sprintf(strbuf, "strains_fname = %s\n", strains_fname); log(strbuf);
  sprintf(strbuf, "enable_antagonism = %s\n", enable_antagonism ? "true" : "false"); log(strbuf);
  sprintf(strbuf, "antagonism_table_fname = %s\n", antagonism_table_fname); log(strbuf);
  sprintf(strbuf, "use_real_growth = %s\n", use_real_growth ? "true" : "false"); log(strbuf);
  sprintf(strbuf, "growth_intercept = %f\n", growth_intercept); log(strbuf);
  sprintf(strbuf, "growth_slope = %f\n", growth_slope); log(strbuf);
  sprintf(strbuf, "food_source_rations = %i\n", food_source_rations); log(strbuf);
  sprintf(strbuf, "food_source_radius = %i\n", food_source_radius); log(strbuf);
  sprintf(strbuf, "food_source_spawn_rate = %f\n", food_source_spawn_rate); log(strbuf);
  sprintf(strbuf, "start_population_per_strain = %i\n", start_population_per_strain); log(strbuf);
  sprintf(strbuf, "start_num_food_sources = %i\n", start_num_food_sources); log(strbuf);
  log(">> Parameters loaded successfully\n");

  // Allocate data arrays
  do_allocations();
  log(">> Data arrays allocated\n");
  
  // Set RNG seed
  reset_seed();
  sprintf(strbuf, ">> RNG seed: %u\n", global_seed); log(strbuf);
  
  // Create strains using data from file
  log(">> Loading strains ...\n");
  create_strains();
  
  // Load antagonism matrix (if applicable)
  if (enable_antagonism) {
    log(">> Antagonisms ENABLED\n");
    load_antagonisms();
  } else {
    log(">> Antagonisms DISABLED\n");
  }

  // Compute growth_rates if not using real ones
  if (use_real_growth) {
    log(">> Using measured growth rates\n");
  } else {
    log(">> Computing growth rates from sender degrees ...\n");
    compute_growth_rates();
  }
  
  // Report strains
  log(">> Loaded strains:\n");
  log("(name | sender degree | receiver degree | growth rate)\n");
  int max_length = 0;
  int max_size = 0;
  for (int i = 0; i < num_strains; i++) {
    if (strains[i]->name.length() > max_length)
      max_length = strains[i]->name.length();
    if (strains[i]->sender_degree > max_size)
      max_size = strains[i]->sender_degree;
    if (strains[i]->receiver_degree > max_size)
      max_size = strains[i]->receiver_degree;      
  }
  max_size = int(log10(max_size))+1;
  for (int i = 0; i < num_strains; i++) {
    sprintf(strbuf, "%-*s | %*i | %*i | %.6f\n", max_length, strains[i]->name.c_str(), max_size, strains[i]->sender_degree, max_size, strains[i]->receiver_degree, strains[i]->growth_rate); log(strbuf);
  }
  
  // Create starting bacteria
  bac_counter = 0;
  log(">> Creating bacteria ...\n");
  create_starting_bacteria();
  sprintf(strbuf, "Population: %i\n", (int)bacteria_list.size()); log(strbuf);
  compute_strain_counts();
  
  // Create food sources
  log(">> Creating food sources ...\n");
  create_starting_food();
  sprintf(strbuf, "Food sources: %i\n", (int)food_list.size()); log(strbuf);
  flag_bacteria_at_food_sources();

  // Ready!
  log(">> READY. Starting simulation ...\n", true);
  if (!report_to_screen) {
    printf("(no further output written to screen)\n");
  }
 
  // Main loop over cycles
  for (cycle = 1; cycle <= num_cycles; cycle++) {

    move_bacteria();

    flag_bacteria_at_food_sources();

    food_sources_interactions();

    cleanup_empty_food_sources();

    kill_bacteria();

    cleanup_dead_bacteria();
    
    spawn_food_source();

    compute_strain_counts();
    
    sprintf(strbuf, "Cycle %i, %i bacteria, %i sources\n", cycle, (int)bacteria_list.size(), (int)food_list.size());
    log(strbuf, false);
    if (report_to_screen) {
      if (cycle % report_interval == 0) {
        printf(">> Cycle %i, %i bacteria, %i sources\n", cycle, (int)bacteria_list.size(), (int)food_list.size());
      }
    }
    
    if (cycle % output_interval == 0) {
      data_output();
    }

  }
  
  raw_time = time(NULL);
  sprintf(strbuf, ">> %s", ctime(&raw_time)); log(strbuf, true);
  
  deallocate();
  
}
コード例 #15
0
ファイル: analyzer.c プロジェクト: xiexuchao/diffstore
int analyze(char *trace,char *config,char *output,char *log)
{
	unsigned int i,chunk_num;
	unsigned int size_in_window=0,req_in_window=0;
	long double time_in_window=0;
	double i_non_access=0,i_inactive=0,i_seq_intensive=0,i_seq_less_intensive=0,i_random_intensive=0,i_random_less_intensive=0;

	struct pool_info *pool;
	pool=(struct pool_info *)malloc(sizeof(struct pool_info));
	alloc_assert(pool,"pool");
	memset(pool,0,sizeof(struct pool_info));

	load_parameters(pool,config);
	initialize(pool,trace,output,log);

#ifdef _NETAPP_TRACE_
	chunk_num=get_range_netapp(pool);
	fgets(pool->buffer,SIZE_BUFFER,pool->file_trace);	//read the first line out
	while(get_request_netapp(pool)!=FAILURE)
#else
	chunk_num=get_range_msr(pool);
	while(get_request_msr(pool)!=FAILURE)
#endif
	{
		if(pool->window_type==WINDOW_DATA)
		{
			seq_detection(pool);	//Sequential IO Detection
			update_statistics(pool);

			//update window info
			size_in_window+=pool->req->size;
			req_in_window++;
			if(req_in_window==1)
				pool->window_time_start=pool->req->time;
			pool->window_time_end=pool->req->time;
			
			//THE CURRENT WINDOW IS FULL
			if((size_in_window>=pool->window_size*2048)||((feof(pool->file_trace)!=0)&&(size_in_window>0)))
			{
				flush_stream(pool);	//Flush information in POOL->STREAMS into each Chunks
				/*Pattern Detection*/
				time_in_window=(long double)(pool->window_time_end-pool->window_time_start)/(long double)1000000000;
				pool->window_time[pool->window_sum]=time_in_window;
				pool->chunk_access[pool->window_sum]=pool->chunk_win;

				for(i=pool->chunk_min;i<=pool->chunk_max;i++)
				{
					if(pool->chunk[i].req_sum_all==0)//no access
					{
						/*No Access*/
						if(pool->record_all[i].accessed!=0)
						{
							i_non_access++;
						}
						pool->chunk[i].pattern=PATTERN_NON_ACCESS;
					}
					else if(pool->chunk[i].req_sum_all<pool->threshold_inactive)//inactive
					{
						/*Inactive*/
						i_inactive++;
						if(((long double)pool->chunk[i].req_sum_read/(long double)pool->chunk[i].req_sum_all)>=pool->threshold_rw)
						{
							/*Inactive Read*/
							pool->chunk[i].pattern=PATTERN_INACTIVE_R;
						}
						else if(((long double)pool->chunk[i].req_sum_write/(long double)pool->chunk[i].req_sum_all)>=pool->threshold_rw)
						{
							/*Inactive Write*/
							pool->chunk[i].pattern=PATTERN_INACTIVE_W;
						}
						else{
							/*Inactive Hybrid*/
							pool->chunk[i].pattern=PATTERN_INACTIVE_H;
						}
					}
					else if((pool->chunk[i].seq_size_all/pool->chunk[i].req_size_all)>=pool->threshold_cbr &&
						((long double)pool->chunk[i].seq_sum_all/(long double)pool->chunk[i].req_sum_all)>=pool->threshold_car)
					{
						/*SEQUENTIAL*/
						i_seq_intensive++;
						/*Sequential Intensive*/
						if(pool->chunk[i].req_sum_all>=(req_in_window/pool->chunk_win)*pool->threshold_intensive)
						{
							if(((long double)pool->chunk[i].req_sum_read/(long double)pool->chunk[i].req_sum_all)>=pool->threshold_rw)
							{
								/*Sequential Intensive Read*/
								pool->chunk[i].pattern=PATTERN_SEQ_INTENSIVE_R;
							}
							else if(((long double)pool->chunk[i].req_sum_write/(long double)pool->chunk[i].req_sum_all)>=pool->threshold_rw)
							{
								/*Sequential Intensive Write*/
								pool->chunk[i].pattern=PATTERN_SEQ_INTENSIVE_W;
							}
							else
							{
								/*Sequential Intensive Hybrid*/
								pool->chunk[i].pattern=PATTERN_SEQ_INTENSIVE_H;
							}
						}
						else{
							i_seq_less_intensive++;
							if(((long double)pool->chunk[i].req_sum_read/(long double)pool->chunk[i].req_sum_all)>=pool->threshold_rw)
							{
								/*Sequential Less Intensive Read*/
								pool->chunk[i].pattern=PATTERN_SEQ_LESS_INTENSIVE_R;
							}
							else if(((long double)pool->chunk[i].req_sum_write/(long double)pool->chunk[i].req_sum_all)>=pool->threshold_rw)
							{
								/*Sequential Less Intensive Write*/
								pool->chunk[i].pattern=PATTERN_SEQ_LESS_INTENSIVE_W;
							}
							else
							{
								/*Sequential Less Intensive Hybrid*/
								pool->chunk[i].pattern=PATTERN_SEQ_LESS_INTENSIVE_H;
							}
						}
					}
					else{
						/*Random*/
						i_random_intensive++;
						if(pool->chunk[i].req_sum_all>=(req_in_window/pool->chunk_win)*pool->threshold_intensive)
						{
							if(((long double)pool->chunk[i].req_sum_read/(long double)pool->chunk[i].req_sum_all)>=pool->threshold_rw)
							{
								/*Random Intensive Read*/
								pool->chunk[i].pattern=PATTERN_RANDOM_INTENSIVE_R;
							}
							else if(((long double)pool->chunk[i].req_sum_write/(long double)pool->chunk[i].req_sum_all)>=pool->threshold_rw)
							{
								/*Random Intensive Write*/
								pool->chunk[i].pattern=PATTERN_RANDOM_INTENSIVE_W;
							}
							else
							{
								/*Random Intensive Hybrid*/
								pool->chunk[i].pattern=PATTERN_RANDOM_INTENSIVE_H;
							}
						}
						else{
							i_random_less_intensive++;
							if(((long double)pool->chunk[i].req_sum_read/(long double)pool->chunk[i].req_sum_all)>=pool->threshold_rw)
							{
								/*Random Less Intensive Read*/
								pool->chunk[i].pattern=PATTERN_RANDOM_LESS_INTENSIVE_R;
							}
							else if(((long double)pool->chunk[i].req_sum_write/(long double)pool->chunk[i].req_sum_all)>=pool->threshold_rw)
							{
								/*Random Less Intensive Write*/
								pool->chunk[i].pattern=PATTERN_RANDOM_LESS_INTENSIVE_W;
							}
							else
							{
								/*Random Less Intensive Hybrid*/
								pool->chunk[i].pattern=PATTERN_RANDOM_LESS_INTENSIVE_H;
							}
						}
					}
					//Only record limited information (the first SIZE_ARRY windows)
					if(pool->window_sum<SIZE_ARRAY)
					{
						pool->chunk[i].history_pattern[pool->window_sum]=pool->chunk[i].pattern;

						pool->pattern_non_access[pool->window_sum]=i_non_access/(double)pool->chunk_all;
						pool->pattern_inactive[pool->window_sum]=i_inactive/(double)pool->chunk_all;
						pool->pattern_seq_intensive[pool->window_sum]=i_seq_intensive/(double)pool->chunk_all;
						pool->pattern_seq_less_intensive[pool->window_sum]=i_seq_less_intensive/(double)pool->chunk_all;
						pool->pattern_random_intensive[pool->window_sum]=i_random_intensive/(double)pool->chunk_all;
						pool->pattern_random_less_intensive[pool->window_sum]=i_random_less_intensive/(double)pool->chunk_all;
					}
					
					print_log(pool,i);	//print info of each chunk in this window to log file.
					/*Initialize the statistics in each chunk*/
					pool->chunk[i].req_sum_all=0;
					pool->chunk[i].req_sum_read=0;
					pool->chunk[i].req_sum_write=0;
					pool->chunk[i].req_size_all=0;
					pool->chunk[i].req_size_read=0;
					pool->chunk[i].req_size_write=0;

					pool->chunk[i].seq_sum_all=0;
					pool->chunk[i].seq_sum_read=0;
					pool->chunk[i].seq_sum_write=0;
					pool->chunk[i].seq_stream_all=0;
					pool->chunk[i].seq_stream_read=0;
					pool->chunk[i].seq_stream_write=0;
					pool->chunk[i].seq_size_all=0;
					pool->chunk[i].seq_size_read=0;
					pool->chunk[i].seq_size_write=0;
				}//for
				
				/*Update the pool info*/
				pool->window_sum++;
				if(pool->window_sum%20==0)
					printf("------pool->window_sum=%d---------\n",pool->window_sum);
				pool->window_time_start=0;
				pool->window_time_end=0;
				
				/*Start a new window*/
				size_in_window=0;
				req_in_window=0;
				time_in_window=0;
				
				i_non_access=0;
				i_inactive=0;
				i_seq_intensive=0;
				i_seq_less_intensive=0;
				i_random_intensive=0;
				i_random_less_intensive=0;

				//accessed chunks in each window
				memset(pool->record_win,0,sizeof(struct record_info)*pool->chunk_sum);
				printf("pool->chunk_win=%d\n",pool->chunk_win);
				pool->chunk_win=0;
			}//if
		}//if
	}//while

	print_statistics(pool);

	fclose(pool->file_trace);
	fclose(pool->file_output);
	fclose(pool->file_log);
	
	free(pool->chunk);
	free(pool->map);
	free(pool->req);
	free(pool);

	return SUCCESS;
}
コード例 #16
0
ファイル: main.c プロジェクト: herrsergio/bee_src
int main(int argc, char **argv)
{
  ROBOT_SPECIFICATIONS     robot_specifications_data;
  PROGRAM_STATE            program_state_data;
  ROBOT_STATE              robot_state_data;
  ACTION                   action_data;
  SENSATION                sensation_data;

  ROBOT_SPECIFICATIONS_PTR robot_specifications = &robot_specifications_data;
  PROGRAM_STATE_PTR        program_state        = &program_state_data;
  ROBOT_STATE_PTR          robot_state          = &robot_state_data;
  ACTION_PTR               action               = &action_data;
  SENSATION_PTR            sensation            = &sensation_data;

  struct timeval TCX_waiting_time = {0, 0};

  robot_specifications->is_initialized = 0;
  program_state->is_initialized        = 0;
  robot_state->is_initialized          = 0;
  action->is_initialized               = 0;
  sensation->is_initialized            = 0;
  allGlobal.is_initialized             = 0;

  signal(SIGTERM, &interrupt_handler); /* kill interupt handler */
  signal(SIGINT,  &interrupt_handler); /* control-C interupt handler */
#if 0
  signal(SIGALRM, &alarm_handler);	/* handler for regular interrupts */
#endif  

  bParamList = bParametersAddEntry(bParamList, "robot", "name", "B21");
  bParamList = bParametersAddEntry(bParamList, "", "TCXHOST", "localhost");
  bParamList  = bParametersAddEntry(bParamList, "", "fork", "yes");

  /* add some parameter files */
  bParamList = bParametersAddFile (bParamList, "etc/beeSoft.ini");

  /* add some enviroment variables */
  bParamList = bParametersAddEnv(bParamList, "", "TCXHOST");

  bParamList = bParametersAddArray(bParamList, "", argc, argv);

  bParametersFillParams(bParamList);

  check_commandline_parameters(argc, argv, ALL);
  init_program(ALL);
  if (!load_parameters(RHINO_INIT_NAME, ALL))
    exit(-1);
  allocate_memory(ALL);
  /*save_parameters(RHINO_INIT_NAME, ALL);*/
  init_graphics(ALL);
  connect_to_tcx(ALL);
  G_display_switch(TITLE_BUTTON, 1);
#if 0
  alarm((unsigned) robot_specifications->alarm_interval); /* set up alarm */
#endif
  tcx_reset_joystick(ALL); 


  for (;!program_state->quit;){
    program_state->something_happened = 0;
    
    if (program_state->tcx_autoconnect)
      connect_to_tcx(ALL);

    if (test_mouse(ALL))       program_state->something_happened = 1;
    
    if (refresh_action(ALL))   program_state->something_happened = 1;

    if (initiate_action(ALL))  program_state->something_happened = 1;

    /* if (terminate_action(ALL)) program_state->something_happened = 1; */
    

    if (program_state->tcx_initialized){
      TCX_waiting_time.tv_sec   = 0;
      TCX_waiting_time.tv_usec  = 0;
      tcxRecvLoop((void *) &TCX_waiting_time);
    }

    if (!program_state->something_happened){
      block_waiting_time.tv_sec  = 1;
      block_waiting_time.tv_usec = 0;
      block_wait(&block_waiting_time, program_state->tcx_initialized,
		 program_state->graphics_initialized);  
    }

#ifdef TOURGUIDE_VERSION
    tourguide_check_for_timeout(ALL);
#endif /* TOURGUIDE_VERSION */

  }



  /* close_log_file(ALL);*/
  /*  if (program_state->tcx_initialized)
      tcxCloseAll();*/
  G_display_switch(TITLE_BUTTON, 2);
  fprintf(stderr, "\nGood-bye.\n");
  sleep(1);
  exit(0);

}
コード例 #17
0
ファイル: system.cpp プロジェクト: AquilaUAS/ardupilot
void Copter::init_ardupilot()
{
    if (!hal.gpio->usb_connected()) {
        // USB is not connected, this means UART0 may be a Xbee, with
        // its darned bricking problem. We can't write to it for at
        // least one second after powering up. Simplest solution for
        // now is to delay for 1 second. Something more elegant may be
        // added later
        delay(1000);
    }

    // initialise serial port
    serial_manager.init_console();

    // init vehicle capabilties
    init_capabilities();

    cliSerial->printf("\n\nInit " FIRMWARE_STRING
                         "\n\nFree RAM: %u\n",
                      (unsigned)hal.util->available_memory());

    //
    // Report firmware version code expect on console (check of actual EEPROM format version is done in load_parameters function)
    //
    report_version();

    // load parameters from EEPROM
    load_parameters();

    BoardConfig.init();

    // initialise serial port
    serial_manager.init();

    // init EPM cargo gripper
#if EPM_ENABLED == ENABLED
    epm.init();
#endif

    // initialise notify system
    // disable external leds if epm is enabled because of pin conflict on the APM
    notify.init(true);

    // initialise battery monitor
    battery.init();

    // Init RSSI
    rssi.init();
    
    barometer.init();

    // Register the mavlink service callback. This will run
    // anytime there are more than 5ms remaining in a call to
    // hal.scheduler->delay.
    hal.scheduler->register_delay_callback(mavlink_delay_cb_static, 5);

    // we start by assuming USB connected, as we initialed the serial
    // port with SERIAL0_BAUD. check_usb_mux() fixes this if need be.
    ap.usb_connected = true;
    check_usb_mux();

    // init the GCS connected to the console
    gcs[0].setup_uart(serial_manager, AP_SerialManager::SerialProtocol_Console, 0);

    // init telemetry port
    gcs[1].setup_uart(serial_manager, AP_SerialManager::SerialProtocol_MAVLink, 0);

    // setup serial port for telem2
    gcs[2].setup_uart(serial_manager, AP_SerialManager::SerialProtocol_MAVLink, 1);

    // setup serial port for fourth telemetry port (not used by default)
    gcs[3].setup_uart(serial_manager, AP_SerialManager::SerialProtocol_MAVLink, 2);

#if FRSKY_TELEM_ENABLED == ENABLED
    // setup frsky
    frsky_telemetry.init(serial_manager);
#endif

    // identify ourselves correctly with the ground station
    mavlink_system.sysid = g.sysid_this_mav;

#if LOGGING_ENABLED == ENABLED
    log_init();
#endif

    GCS_MAVLINK::set_dataflash(&DataFlash);

    // update motor interlock state
    update_using_interlock();

#if FRAME_CONFIG == HELI_FRAME
    // trad heli specific initialisation
    heli_init();
#endif
    
    init_rc_in();               // sets up rc channels from radio
    init_rc_out();              // sets up motors and output to escs

    // initialise which outputs Servo and Relay events can use
    ServoRelayEvents.set_channel_mask(~motors.get_motor_mask());

    relay.init();

    /*
     *  setup the 'main loop is dead' check. Note that this relies on
     *  the RC library being initialised.
     */
    hal.scheduler->register_timer_failsafe(failsafe_check_static, 1000);

    // Do GPS init
    gps.init(&DataFlash, serial_manager);

    if(g.compass_enabled)
        init_compass();

#if OPTFLOW == ENABLED
    // make optflow available to AHRS
    ahrs.set_optflow(&optflow);
#endif

    // init Location class
    Location_Class::set_ahrs(&ahrs);
#if AP_TERRAIN_AVAILABLE && AC_TERRAIN
    Location_Class::set_terrain(&terrain);
    wp_nav.set_terrain(&terrain);
#endif

    pos_control.set_dt(MAIN_LOOP_SECONDS);

    // init the optical flow sensor
    init_optflow();

#if MOUNT == ENABLED
    // initialise camera mount
    camera_mount.init(&DataFlash, serial_manager);
#endif

#if PRECISION_LANDING == ENABLED
    // initialise precision landing
    init_precland();
#endif

#ifdef USERHOOK_INIT
    USERHOOK_INIT
#endif

#if CLI_ENABLED == ENABLED
    if (g.cli_enabled) {
        const char *msg = "\nPress ENTER 3 times to start interactive setup\n";
        cliSerial->println(msg);
        if (gcs[1].initialised && (gcs[1].get_uart() != NULL)) {
            gcs[1].get_uart()->println(msg);
        }
        if (num_gcs > 2 && gcs[2].initialised && (gcs[2].get_uart() != NULL)) {
            gcs[2].get_uart()->println(msg);
        }
    }
#endif // CLI_ENABLED

#if HIL_MODE != HIL_MODE_DISABLED
    while (barometer.get_last_update() == 0) {
        // the barometer begins updating when we get the first
        // HIL_STATE message
        gcs_send_text(MAV_SEVERITY_WARNING, "Waiting for first HIL_STATE message");
        delay(1000);
    }

    // set INS to HIL mode
    ins.set_hil_mode();
#endif

    // read Baro pressure at ground
    //-----------------------------
    init_barometer(true);

    // initialise sonar
#if CONFIG_SONAR == ENABLED
    init_sonar();
#endif

    // initialise AP_RPM library
    rpm_sensor.init();

    // initialise mission library
    mission.init();

    // initialise the flight mode and aux switch
    // ---------------------------
    reset_control_switch();
    init_aux_switches();

    startup_INS_ground();

    // set landed flags
    set_land_complete(true);
    set_land_complete_maybe(true);

    // we don't want writes to the serial port to cause us to pause
    // mid-flight, so set the serial ports non-blocking once we are
    // ready to fly
    serial_manager.set_blocking_writes_all(false);

    // enable CPU failsafe
    failsafe_enable();

    ins.set_raw_logging(should_log(MASK_LOG_IMU_RAW));
    ins.set_dataflash(&DataFlash);

    cliSerial->print("\nReady to FLY ");

    // flag that initialisation has completed
    ap.initialised = true;
}
コード例 #18
0
ファイル: system.cpp プロジェクト: WickedShell/ardupilot
void Plane::init_ardupilot()
{
    // initialise serial port
    serial_manager.init_console();

    cliSerial->printf("\n\nInit " FIRMWARE_STRING
                         "\n\nFree RAM: %u\n",
                      (unsigned)hal.util->available_memory());


    //
    // Check the EEPROM format version before loading any parameters from EEPROM
    //
    load_parameters();

#if HIL_SUPPORT
    if (g.hil_mode == 1) {
        // set sensors to HIL mode
        ins.set_hil_mode();
        compass.set_hil_mode();
        barometer.set_hil_mode();
    }
#endif

    set_control_channels();
    init_rc_out_main();
    
#if HAVE_PX4_MIXER
    if (!quadplane.enable) {
        // this must be before BoardConfig.init() so if
        // BRD_SAFETYENABLE==0 then we don't have safety off yet. For
        // quadplanes we wait till AP_Motors is initialised
        for (uint8_t tries=0; tries<10; tries++) {
            if (setup_failsafe_mixing()) {
                break;
            }
            hal.scheduler->delay(10);
        }
    }
#endif

    GCS_MAVLINK::set_dataflash(&DataFlash);

    // initialise serial ports
    serial_manager.init();
    gcs[0].setup_uart(serial_manager, AP_SerialManager::SerialProtocol_MAVLink, 0);

    // Register mavlink_delay_cb, which will run anytime you have
    // more than 5ms remaining in your call to hal.scheduler->delay
    hal.scheduler->register_delay_callback(mavlink_delay_cb_static, 5);

    // setup any board specific drivers
    BoardConfig.init();

    // allow servo set on all channels except first 4
    ServoRelayEvents.set_channel_mask(0xFFF0);

    // keep a record of how many resets have happened. This can be
    // used to detect in-flight resets
    g.num_resets.set_and_save(g.num_resets+1);

    // init baro before we start the GCS, so that the CLI baro test works
    barometer.init();

    // initialise rangefinder
    init_rangefinder();

    // initialise battery monitoring
    battery.init();

    rpm_sensor.init();

    // we start by assuming USB connected, as we initialed the serial
    // port with SERIAL0_BAUD. check_usb_mux() fixes this if need be.    
    usb_connected = true;
    check_usb_mux();

    // setup telem slots with serial ports
    for (uint8_t i = 1; i < MAVLINK_COMM_NUM_BUFFERS; i++) {
        gcs[i].setup_uart(serial_manager, AP_SerialManager::SerialProtocol_MAVLink, i);
    }

    // setup frsky
#if FRSKY_TELEM_ENABLED == ENABLED
    // setup frsky, and pass a number of parameters to the library
    frsky_telemetry.init(serial_manager, FIRMWARE_STRING,
                         MAV_TYPE_FIXED_WING,
                         &g.fs_batt_voltage, &g.fs_batt_mah);
#endif

    mavlink_system.sysid = g.sysid_this_mav;

#if LOGGING_ENABLED == ENABLED
    log_init();
#endif

    // initialise airspeed sensor
    airspeed.init();

    if (g.compass_enabled==true) {
        bool compass_ok = compass.init() && compass.read();
#if HIL_SUPPORT
    if (g.hil_mode != 0) {
        compass_ok = true;
    }
#endif
        if (!compass_ok) {
            cliSerial->println("Compass initialisation failed!");
            g.compass_enabled = false;
        } else {
            ahrs.set_compass(&compass);
        }
    }
    
#if OPTFLOW == ENABLED
    // make optflow available to libraries
    if (optflow.enabled()) {
        ahrs.set_optflow(&optflow);
    }
#endif

    // give AHRS the airspeed sensor
    ahrs.set_airspeed(&airspeed);

    // GPS Initialization
    gps.init(&DataFlash, serial_manager);

    init_rc_in();               // sets up rc channels from radio

    relay.init();

#if MOUNT == ENABLED
    // initialise camera mount
    camera_mount.init(&DataFlash, serial_manager);
#endif

#if FENCE_TRIGGERED_PIN > 0
    hal.gpio->pinMode(FENCE_TRIGGERED_PIN, HAL_GPIO_OUTPUT);
    hal.gpio->write(FENCE_TRIGGERED_PIN, 0);
#endif

    /*
     *  setup the 'main loop is dead' check. Note that this relies on
     *  the RC library being initialised.
     */
    hal.scheduler->register_timer_failsafe(failsafe_check_static, 1000);

#if CLI_ENABLED == ENABLED
    if (g.cli_enabled == 1) {
        const char *msg = "\nPress ENTER 3 times to start interactive setup\n";
        cliSerial->println(msg);
        if (gcs[1].initialised && (gcs[1].get_uart() != NULL)) {
            gcs[1].get_uart()->println(msg);
        }
        if (num_gcs > 2 && gcs[2].initialised && (gcs[2].get_uart() != NULL)) {
            gcs[2].get_uart()->println(msg);
        }
    }
#endif // CLI_ENABLED

    init_capabilities();

    quadplane.setup();

    startup_ground();

    // don't initialise aux rc output until after quadplane is setup as
    // that can change initial values of channels
    init_rc_out_aux();
    
    // choose the nav controller
    set_nav_controller();

    set_mode((FlightMode)g.initial_mode.get(), MODE_REASON_UNKNOWN);

    // set the correct flight mode
    // ---------------------------
    reset_control_switch();

    // initialise sensor
#if OPTFLOW == ENABLED
    if (optflow.enabled()) {
        optflow.init();
    }
#endif

}
コード例 #19
0
void Tracker::init_tracker()
{
    // initialise console serial port
    serial_manager.init_console();

    hal.console->printf_P(PSTR("\n\nInit " THISFIRMWARE
                               "\n\nFree RAM: %u\n"),
                          hal.util->available_memory());

    // Check the EEPROM format version before loading any parameters from EEPROM
    load_parameters();

    BoardConfig.init();

    // initialise serial ports
    serial_manager.init();

    // init baro before we start the GCS, so that the CLI baro test works
    barometer.init();

    // init the GCS and start snooping for vehicle data
    gcs[0].setup_uart(serial_manager, AP_SerialManager::SerialProtocol_Console, 0);
    gcs[0].set_snoop(mavlink_snoop_static);

    // Register mavlink_delay_cb, which will run anytime you have
    // more than 5ms remaining in your call to hal.scheduler->delay
    hal.scheduler->register_delay_callback(mavlink_delay_cb_static, 5);

    // we start by assuming USB connected, as we initialed the serial
    // port with SERIAL0_BAUD. check_usb_mux() fixes this if need be.    
    usb_connected = true;
    check_usb_mux();

    // setup serial port for telem1 and start snooping for vehicle data
    gcs[1].setup_uart(serial_manager, AP_SerialManager::SerialProtocol_MAVLink, 0);
    gcs[1].set_snoop(mavlink_snoop_static);

#if MAVLINK_COMM_NUM_BUFFERS > 2
    // setup serial port for telem2 and start snooping for vehicle data
    gcs[2].setup_uart(serial_manager, AP_SerialManager::SerialProtocol_MAVLink, 1);
    gcs[2].set_snoop(mavlink_snoop_static);
#endif

#if MAVLINK_COMM_NUM_BUFFERS > 3
    // setup serial port for fourth telemetry port (not used by default) and start snooping for vehicle data
    gcs[3].setup_uart(serial_manager, AP_SerialManager::SerialProtocol_MAVLink, 2);
    gcs[3].set_snoop(mavlink_snoop_static);
#endif

    mavlink_system.sysid = g.sysid_this_mav;

    if (g.compass_enabled==true) {
        if (!compass.init() || !compass.read()) {
            hal.console->println_P(PSTR("Compass initialisation failed!"));
            g.compass_enabled = false;
        } else {
            ahrs.set_compass(&compass);
        }
    }

    // GPS Initialization
    gps.init(NULL, serial_manager);

    ahrs.init();
    ahrs.set_fly_forward(false);

    ins.init(AP_InertialSensor::WARM_START, ins_sample_rate);
    ahrs.reset();

    init_barometer();

    // set serial ports non-blocking
    serial_manager.set_blocking_writes_all(false);

    // initialise servos
    init_servos();

    // use given start positions - useful for indoor testing, and
    // while waiting for GPS lock
    current_loc.lat = g.start_latitude * 1.0e7f;
    current_loc.lng = g.start_longitude * 1.0e7f;

    // see if EEPROM has a default location as well
    if (current_loc.lat == 0 && current_loc.lng == 0) {
        get_home_eeprom(current_loc);
    }

    gcs_send_text_P(SEVERITY_LOW,PSTR("\nReady to track."));
    hal.scheduler->delay(1000); // Why????

    set_mode(AUTO); // tracking

    if (g.startup_delay > 0) {
        // arm servos with trim value to allow them to start up (required
        // for some servos)
        prepare_servos();
    }

    // calibrate pressure on startup by default
    nav_status.need_altitude_calibration = true;
}
コード例 #20
0
ファイル: ctx.c プロジェクト: AktivCo/OpenSC
static void process_config_file(sc_context_t *ctx, struct _sc_ctx_options *opts)
{
	int i, r, count = 0;
	scconf_block **blocks;
	const char *conf_path = NULL;
	const char *debug = NULL;
#ifdef _WIN32
	char temp_path[PATH_MAX];
	size_t temp_len;
#endif

	/* Takes effect even when no config around */
	debug = getenv("OPENSC_DEBUG");
	if (debug)
		ctx->debug = atoi(debug);

	memset(ctx->conf_blocks, 0, sizeof(ctx->conf_blocks));
#ifdef _WIN32
	temp_len = PATH_MAX-1;
	r = sc_ctx_win32_get_config_value("OPENSC_CONF", "ConfigFile", "Software\\OpenSC Project\\OpenSC",
		temp_path, &temp_len);
	if (r)   {
		sc_log(ctx, "process_config_file doesn't find opensc config file. Please set the registry key.");
		return;
	}
	temp_path[temp_len] = '\0';
	conf_path = temp_path;
#else
	conf_path = getenv("OPENSC_CONF");
	if (!conf_path)
		conf_path = OPENSC_CONF_PATH;
#endif
	ctx->conf = scconf_new(conf_path);
	if (ctx->conf == NULL)
		return;
	r = scconf_parse(ctx->conf);
#ifdef OPENSC_CONFIG_STRING
	/* Parse the string if config file didn't exist */
	if (r < 0)
		r = scconf_parse_string(ctx->conf, OPENSC_CONFIG_STRING);
#endif
	if (r < 1) {
		/* A negative return value means the config file isn't
		 * there, which is not an error. Nevertheless log this
		 * fact. */
		if (r < 0)
			sc_log(ctx, "scconf_parse failed: %s", ctx->conf->errmsg);
		else
			sc_log(ctx, "scconf_parse failed: %s", ctx->conf->errmsg);
		scconf_free(ctx->conf);
		ctx->conf = NULL;
		return;
	}
	/* needs to be after the log file is known */
	sc_log(ctx, "Used configuration file '%s'", conf_path);
	blocks = scconf_find_blocks(ctx->conf, NULL, "app", ctx->app_name);
	if (blocks && blocks[0])
		ctx->conf_blocks[count++] = blocks[0];
	free(blocks);
	if (strcmp(ctx->app_name, "default") != 0) {
		blocks = scconf_find_blocks(ctx->conf, NULL, "app", "default");
		if (blocks && blocks[0])
			ctx->conf_blocks[count] = blocks[0];
		free(blocks);
	}
	/* Above we add 2 blocks at most, but conf_blocks has 3 elements,
	 * so at least one is NULL */
	for (i = 0; ctx->conf_blocks[i]; i++)
		load_parameters(ctx, ctx->conf_blocks[i], opts);
}
コード例 #21
0
ファイル: system.cpp プロジェクト: ProfFan/ardupilot
void Sub::init_ardupilot()
{
    if (!hal.gpio->usb_connected()) {
        // USB is not connected, this means UART0 may be a Xbee, with
        // its darned bricking problem. We can't write to it for at
        // least one second after powering up. Simplest solution for
        // now is to delay for 1 second. Something more elegant may be
        // added later
        hal.scheduler->delay(1000);
    }

    // initialise serial port
    serial_manager.init_console();

    cliSerial->printf("\n\nInit " FIRMWARE_STRING
                      "\n\nFree RAM: %u\n",
                      (unsigned)hal.util->available_memory());

    //
    // Report firmware version code expect on console (check of actual EEPROM format version is done in load_parameters function)
    //
    report_version();

    // load parameters from EEPROM
    load_parameters();

    BoardConfig.init();

    // initialise serial port
    serial_manager.init();

    // init cargo gripper
#if GRIPPER_ENABLED == ENABLED
    g2.gripper.init();
#endif

    // initialise notify system
    notify.init(true);

    // initialise battery monitor
    battery.init();

    barometer.init();

    celsius.init();

    // Register the mavlink service callback. This will run
    // anytime there are more than 5ms remaining in a call to
    // hal.scheduler->delay.
    hal.scheduler->register_delay_callback(mavlink_delay_cb_static, 5);

    // we start by assuming USB connected, as we initialed the serial
    // port with SERIAL0_BAUD. check_usb_mux() fixes this if need be.
    ap.usb_connected = true;
    check_usb_mux();

    // setup telem slots with serial ports
    for (uint8_t i = 0; i < MAVLINK_COMM_NUM_BUFFERS; i++) {
        gcs_chan[i].setup_uart(serial_manager, AP_SerialManager::SerialProtocol_MAVLink, i);
    }

    // identify ourselves correctly with the ground station
    mavlink_system.sysid = g.sysid_this_mav;

#if LOGGING_ENABLED == ENABLED
    log_init();
#endif

    gcs().set_dataflash(&DataFlash);

    init_rc_in();               // sets up rc channels from radio
    init_rc_out();              // sets up motors and output to escs
    init_joystick();            // joystick initialization

    // initialise which outputs Servo and Relay events can use
    ServoRelayEvents.set_channel_mask(~motors.get_motor_mask());

    relay.init();

    /*
     *  setup the 'main loop is dead' check. Note that this relies on
     *  the RC library being initialised.
     */
    hal.scheduler->register_timer_failsafe(failsafe_check_static, 1000);

    // Do GPS init
    gps.init(&DataFlash, serial_manager);

    if (g.compass_enabled) {
        init_compass();
    }

#if OPTFLOW == ENABLED
    // make optflow available to AHRS
    ahrs.set_optflow(&optflow);
#endif

    // init Location class
    Location_Class::set_ahrs(&ahrs);
#if AP_TERRAIN_AVAILABLE && AC_TERRAIN
    Location_Class::set_terrain(&terrain);
    wp_nav.set_terrain(&terrain);
#endif

#if AVOIDANCE_ENABLED == ENABLED
    wp_nav.set_avoidance(&avoid);
#endif

    pos_control.set_dt(MAIN_LOOP_SECONDS);

    // init the optical flow sensor
    init_optflow();

#if MOUNT == ENABLED
    // initialise camera mount
    camera_mount.init(&DataFlash, serial_manager);
#endif

#ifdef USERHOOK_INIT
    USERHOOK_INIT
#endif

#if CLI_ENABLED == ENABLED
    if (g.cli_enabled) {
        const char *msg = "\nPress ENTER 3 times to start interactive setup\n";
        cliSerial->println(msg);
        if (gcs_chan[1].initialised && (gcs_chan[1].get_uart() != NULL)) {
            gcs_chan[1].get_uart()->println(msg);
        }
        if (num_gcs > 2 && gcs_chan[2].initialised && (gcs_chan[2].get_uart() != NULL)) {
            gcs_chan[2].get_uart()->println(msg);
        }
    }
#endif // CLI_ENABLED

#if HIL_MODE != HIL_MODE_DISABLED
    while (barometer.get_last_update() == 0) {
        // the barometer begins updating when we get the first
        // HIL_STATE message
        gcs_send_text(MAV_SEVERITY_WARNING, "Waiting for first HIL_STATE message");
        hal.scheduler->delay(1000);
    }

    // set INS to HIL mode
    ins.set_hil_mode();
#endif

    // read Baro pressure at ground
    //-----------------------------
    init_barometer(false);
    barometer.update();

    for (uint8_t i = 0; i < barometer.num_instances(); i++) {
        if (barometer.get_type(i) == AP_Baro::BARO_TYPE_WATER && barometer.healthy(i)) {
            barometer.set_primary_baro(i);
            ap.depth_sensor_present = true;
            break;
        }
    }

    if (!ap.depth_sensor_present) {
        // We only have onboard baro
        // No external underwater depth sensor detected
        barometer.set_primary_baro(0);
        EKF2.set_baro_alt_noise(10.0f); // Readings won't correspond with rest of INS
        EKF3.set_baro_alt_noise(10.0f);
    } else {
        EKF2.set_baro_alt_noise(0.1f);
        EKF3.set_baro_alt_noise(0.1f);
    }

    leak_detector.init();

    // backwards compatibility
    if (attitude_control.get_accel_yaw_max() < 110000.0f) {
        attitude_control.save_accel_yaw_max(110000.0f);
    }

    last_pilot_heading = ahrs.yaw_sensor;

    // initialise rangefinder
#if RANGEFINDER_ENABLED == ENABLED
    init_rangefinder();
#endif

    // initialise AP_RPM library
#if RPM_ENABLED == ENABLED
    rpm_sensor.init();
#endif

    // initialise mission library
    mission.init();

    startup_INS_ground();

    // we don't want writes to the serial port to cause us to pause
    // mid-flight, so set the serial ports non-blocking once we are
    // ready to fly
    serial_manager.set_blocking_writes_all(false);

    // enable CPU failsafe
    failsafe_enable();

    ins.set_raw_logging(should_log(MASK_LOG_IMU_RAW));
    ins.set_dataflash(&DataFlash);

    // init vehicle capabilties
    init_capabilities();

    cliSerial->print("\nReady to FLY ");

    // flag that initialisation has completed
    ap.initialised = true;
}
コード例 #22
0
ファイル: benchmark.c プロジェクト: robgjansen/pbs
void pbs_test(char *data) {
	pbs_parameters pbs;
	pbs_pk pk;
	pbs_sk sk;
	pbs_bank_state bstate;
	pbs_client_state cstate;
	pbs_signature signature;
	pbs_workspace workspace;
	struct timespec bank_start, bank_end, verify_start, verify_end;
	long bank_nanos = 0;
	long verify_nanos = 0;
	int success, i = 0;

	load_parameters(&pbs);
	/* use this to generate keys */
	/*
	 gen_keys(&pbs, &sk, &pk);
	 printf("skx:%s\n", BN_bn2hex(sk.x));
	 printf("pky:%s\n", BN_bn2hex(pk.y));
	 */
	load_keys(&sk, &pk);

	int date1 = time(NULL) / 86400;
	int date2 = date1 + 7;
	int date3 = date1 + 28;
	int infolen = 3 * sizeof(date1) + 6; /* 3 ints, 2 commas, null byte */
	char info[infolen];
	snprintf(info, infolen, "%d,%d,%d", date1, date2, date3);
	/* printf("%s\n", info); */

	/* do a bunch of signatures and verifies */
	/* FIXME this can be made much more efficient */
	char *pos = data;
	for (i = 0; i < NUM_LOOPS_PER_RUN; ++i) {
		BIGNUM *a = BN_new();
		BIGNUM *b = BN_new();
		BIGNUM *e = BN_new();
		BIGNUM *r = BN_new();
		BIGNUM *c = BN_new();
		BIGNUM *s = BN_new();
		BIGNUM *d = BN_new();

		/* client sends bank request, bank sends back a,b,info */
		clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &bank_start);
		bank_sign_init(a, b, &bstate, info, &pbs);
		clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &bank_end);

		bank_nanos = get_timer_nanos(&bank_start, &bank_end);

		/* client initialization */
		sign_init(&cstate, &signature, &workspace);
		/* client uses a,b,info and its message to produce e for bank */
		sign_update(e, &cstate, &pbs, &pk, data, info, a, b);

		/* bank uses e to produce r,c,s,d for client */
		clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &bank_start);
		bank_sign_update(r, c, s, d, &bstate, &pbs, &sk, e);
		clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &bank_end);

		bank_nanos += get_timer_nanos(&bank_start, &bank_end);

		/* client finishes signature */
		sign_final(&signature, r, c, s, d, &cstate, &pbs);

		/* now verify */
		clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &verify_start);
		success = verify(&signature, &pk, &pbs, info, data, &workspace);
		clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &verify_end);

		verify_nanos = get_timer_nanos(&verify_start, &verify_end);

		if (success != 0) {
			printf("Signature incorrect\n");
		}
		pos += CELL_NETWORK_SIZE + 1;

		BN_free(a);
		BN_free(b);
		BN_free(e);
		BN_free(r);
		BN_free(c);
		BN_free(s);
		BN_free(d);
		free_bank_state(&bstate);
		free_client_state(&cstate);
		free_signature(&signature);
		free_workspace(&workspace);

		printf("pbs Bank effort: 1 signature %ld nanoseconds (%d/%d)\n", bank_nanos, i+1, NUM_LOOPS_PER_RUN);
		printf("pbs Signature verification: 1 verify %ld nanoseconds (%d/%d)\n", verify_nanos, i+1, NUM_LOOPS_PER_RUN);
	}

	free_keys(&sk, &pk);
	free_parameters(&pbs);


#ifdef DEBUG
	/* signature results */
	printBN(signature.delta, "delta:");
	printBN(signature.sigma, "sigma:");
	printBN(signature.omega, "omega:");
	printBN(signature.rho, "rho:");
	printf("info:%s\n", info);
	printf("message:%s\n", message);

	printBN(a, "a:");
	printBN(b, "b:");
	printBN(e, "e:");
	printBN(r, "r:");
	printBN(c, "c:");
	printBN(s, "s:");
	printBN(d, "d:");
	printBN(cstate.t1, "t1:");
	printBN(cstate.t2, "t2:");
	printBN(cstate.t3, "t3:");
	printBN(cstate.t4, "t4:");
	printBN(cstate.epsilon, "epsilon:");
	printBN(bstate.d, "d:");
	printBN(bstate.s, "s:");
	printBN(bstate.u, "u:");
	printBN(pbs.g, "g:");
	printBN(pbs.p, "p:");
	printBN(pbs.q, "q:");
	printBN(pk.y, "y:");
	printBN(sk.x, "x:");

	/* sanity checks */
	BIGNUM *temp1 = BN_new();
	BIGNUM *temp2 = BN_new();
	BN_CTX *ctx = BN_CTX_new();

	/* q |? p-1 */
	BN_sub(temp1, pbs.p, BN_value_one());
	BN_mod(temp2, temp1, pbs.q, ctx);
	printf("q|p-1 remainder: %s\n", BN_bn2hex(temp2));

	/* g^q =? 1 mod p */
	BN_mod_exp(temp1, pbs.g, pbs.q, pbs.p, ctx);
	printf("g^q =? 1 mod p result: %s\n", BN_bn2hex(temp1));
#endif

	/*
	 BN_free(a);
	 BN_free(b);
	 BN_free(e);
	 BN_free(r);
	 BN_free(c);
	 BN_free(s);
	 BN_free(d);
	 free_bank_state(&bstate);
	 free_client_state(&cstate);
	 free_signature(&signature);
	 free_keys(&sk, &pk);
	 free_parameters(&pbs);
	 */
}
コード例 #23
0
ファイル: bayesoptcatmex.c プロジェクト: MLDL/bayesopt
void mexFunction(int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
{
  double *xptr;
  mxArray *xopt;
  const mxArray *func_name, *params;
  user_function_data udata;
  size_t nDim;
  unsigned int ii;
  bopt_params parameters;
  double *cat_d;
  int *cat_i;
  double fmin;
  int error_code;
     
  /* Check correct number of parameters */
  CHECK0(nlhs != 2 || nrhs != 3,
	 "wrong number of arguments");
    
  /* TODO: Change This */
  udata.neval = 0;
  udata.verbose = 0;
   
  /* First term is the function handle or name */
  func_name = prhs[0];

  if (mxIsChar(func_name))
    {
      CHECK0(mxGetString(func_name, udata.f, FLEN) == 0,
	     "error reading function name string (too long?)");
      udata.nrhs = 1;
      udata.xrhs = 0;
    }
#ifndef HAVE_OCTAVE
  else if (mxIsFunctionHandle(func_name))
    {
      udata.prhs[0] = (mxArray *)func_name;
      strcpy(udata.f, "feval");
      udata.nrhs = 2;
      udata.xrhs = 1;
      }
#endif
  else
    {
      mexErrMsgTxt("First term should be a function name or function handle");
    }

  /* Second parameter. Categories */
  CHECK0(mxIsDouble(prhs[1]) && !mxIsComplex(prhs[1])
	 && (  (mxGetM(prhs[1]) == 1) && (mxGetN(prhs[1]) == nDim)   
	    || (mxGetN(prhs[1]) == 1) && (mxGetM(prhs[1]) == nDim)),
	 "categories must be real row or column vector");

  cat_d = mxGetPr(prhs[3]);

  nDim = (unsigned int) mxGetM(prhs[1]) * mxGetN(prhs[1]);

  cat_i = (int*)(mxCalloc(nDim,sizeof(int)));
  for (ii = 0; ii < nDim; ++ii) 
    {
      cat_i[ii] = (int)(cat_d[ii]+0.5);    
    }

  udata.prhs[udata.xrhs] = mxCreateDoubleMatrix(1, nDim, mxREAL);

  xopt = mxCreateDoubleMatrix(1, nDim, mxREAL);
  xptr = mxGetPr(xopt);
     
  /* Third term. Parameters  */
  if (nrhs != 2)
    {
      CHECK0(mxIsStruct(prhs[2]), "3rd element must be a struct");
      params = prhs[2];
    }
  else
    {
      params = mxCreateStructMatrix(1,1,0,NULL);
    }
  parameters = load_parameters(params);

  error_code = bayes_optimization_categorical(nDim,user_function,&udata,cat_i,xptr,
					      &fmin,parameters);

  mxFree(cat_i); 
  mxDestroyArray(udata.prhs[udata.xrhs]);
  plhs[0] = xopt;
  if (nlhs > 1) 
    {
      plhs[1] = mxCreateDoubleMatrix(1, 1, mxREAL);
      *(mxGetPr(plhs[1])) = fmin;
    }

  if (nlhs > 2)
    {
      plhs[2] = mxCreateDoubleMatrix(1, 1, mxREAL);
      *(mxGetPr(plhs[2])) = (double)(error_code);
    }
    
}
コード例 #24
0
void Plane::init_ardupilot()
{
    // initialise serial port
    serial_manager.init_console();

    cliSerial->printf_P(PSTR("\n\nInit " FIRMWARE_STRING
                         "\n\nFree RAM: %u\n"),
                        hal.util->available_memory());


    //
    // Check the EEPROM format version before loading any parameters from EEPROM
    //
    load_parameters();

    if (g.hil_mode == 1) {
        // set sensors to HIL mode
        ins.set_hil_mode();
        compass.set_hil_mode();
        barometer.set_hil_mode();
    }

#if CONFIG_HAL_BOARD == HAL_BOARD_PX4
    // this must be before BoardConfig.init() so if
    // BRD_SAFETYENABLE==0 then we don't have safety off yet
    for (uint8_t tries=0; tries<10; tries++) {
        if (setup_failsafe_mixing()) {
            break;
        }
        hal.scheduler->delay(10);
    }
#endif

    BoardConfig.init();

    // initialise serial ports
    serial_manager.init();

    // allow servo set on all channels except first 4
    ServoRelayEvents.set_channel_mask(0xFFF0);

    set_control_channels();

    // keep a record of how many resets have happened. This can be
    // used to detect in-flight resets
    g.num_resets.set_and_save(g.num_resets+1);

    // init baro before we start the GCS, so that the CLI baro test works
    barometer.init();

    // initialise rangefinder
    init_rangefinder();

    // initialise battery monitoring
    battery.init();

    // init the GCS
    gcs[0].setup_uart(serial_manager, AP_SerialManager::SerialProtocol_Console, 0);

    // we start by assuming USB connected, as we initialed the serial
    // port with SERIAL0_BAUD. check_usb_mux() fixes this if need be.    
    usb_connected = true;
    check_usb_mux();

    // setup serial port for telem1
    gcs[1].setup_uart(serial_manager, AP_SerialManager::SerialProtocol_MAVLink, 0);

#if MAVLINK_COMM_NUM_BUFFERS > 2
    // setup serial port for telem2
    gcs[2].setup_uart(serial_manager, AP_SerialManager::SerialProtocol_MAVLink, 1);
#endif

#if MAVLINK_COMM_NUM_BUFFERS > 3
    // setup serial port for fourth telemetry port (not used by default)
    gcs[3].setup_uart(serial_manager, AP_SerialManager::SerialProtocol_MAVLink, 2);
#endif

    // setup frsky
#if FRSKY_TELEM_ENABLED == ENABLED
    frsky_telemetry.init(serial_manager);
#endif

    mavlink_system.sysid = g.sysid_this_mav;

#if LOGGING_ENABLED == ENABLED
    log_init();
#endif

#if CONFIG_HAL_BOARD == HAL_BOARD_APM1
    apm1_adc.Init();      // APM ADC library initialization
#endif

    // initialise airspeed sensor
    airspeed.init();

    if (g.compass_enabled==true) {
        if (!compass.init() || !compass.read()) {
            cliSerial->println_P(PSTR("Compass initialisation failed!"));
            g.compass_enabled = false;
        } else {
            ahrs.set_compass(&compass);
        }
    }
    
#if OPTFLOW == ENABLED
    // make optflow available to libraries
    ahrs.set_optflow(&optflow);
#endif

    // Register mavlink_delay_cb, which will run anytime you have
    // more than 5ms remaining in your call to hal.scheduler->delay
    hal.scheduler->register_delay_callback(mavlink_delay_cb_static, 5);

    // give AHRS the airspeed sensor
    ahrs.set_airspeed(&airspeed);

    // GPS Initialization
    gps.init(&DataFlash, serial_manager);

    init_rc_in();               // sets up rc channels from radio
    init_rc_out();              // sets up the timer libs

    relay.init();

#if MOUNT == ENABLED
    // initialise camera mount
    camera_mount.init(serial_manager);
#endif

#if FENCE_TRIGGERED_PIN > 0
    hal.gpio->pinMode(FENCE_TRIGGERED_PIN, HAL_GPIO_OUTPUT);
    hal.gpio->write(FENCE_TRIGGERED_PIN, 0);
#endif

    /*
     *  setup the 'main loop is dead' check. Note that this relies on
     *  the RC library being initialised.
     */
    hal.scheduler->register_timer_failsafe(failsafe_check_static, 1000);

#if CLI_ENABLED == ENABLED
    if (g.cli_enabled == 1) {
        const prog_char_t *msg = PSTR("\nPress ENTER 3 times to start interactive setup\n");
        cliSerial->println_P(msg);
        if (gcs[1].initialised && (gcs[1].get_uart() != NULL)) {
            gcs[1].get_uart()->println_P(msg);
        }
        if (num_gcs > 2 && gcs[2].initialised && (gcs[2].get_uart() != NULL)) {
            gcs[2].get_uart()->println_P(msg);
        }
    }
#endif // CLI_ENABLED

    startup_ground();
    Log_Write_Startup(TYPE_GROUNDSTART_MSG);

    // choose the nav controller
    set_nav_controller();

    set_mode((FlightMode)g.initial_mode.get());

    // set the correct flight mode
    // ---------------------------
    reset_control_switch();

    // initialise sensor
#if OPTFLOW == ENABLED
    optflow.init();
#endif

}
コード例 #25
0
ファイル: bayesoptdiscmex.c プロジェクト: mathkann/bayesopt
void mexFunction(int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
{
  double *xptr;
  mxArray *xopt;
  const mxArray *func_name, *params;
  user_function_data udata;
  size_t nDim,nPoints;
  double* xset;
  bopt_params parameters;
  double fmin = 0.0;
  int error_code;
    
  /* Check correct number of parameters */
  CHECK0(nlhs != 2 || nrhs != 3, "wrong number of arguments");
    
  /* TODO: Change This */
  udata.neval = 0;
  udata.verbose = 0;
   
  /* First term is the function handle or name */
  func_name = prhs[0];

  if (mxIsChar(func_name))
    {
      CHECK0(mxGetString(func_name, udata.f, FLEN) == 0,
	     "error reading function name string (too long?)");
      udata.nrhs = 1;
      udata.xrhs = 0;
    }
#ifndef HAVE_OCTAVE
  else if (mxIsFunctionHandle(func_name))
    {
      udata.prhs[0] = (mxArray *)func_name;
      strcpy(udata.f, "feval");
      udata.nrhs = 2;
      udata.xrhs = 1;
      }
#endif
  else
    {
      mexErrMsgTxt("First term should be a function name "
		   "(Matlab/Octave) or function handle (Matlab)");
    }

  /* Second parameter. Set of values. */
  CHECK0(mxIsDouble(prhs[1]) && !mxIsComplex(prhs[1]) &&
	 mxGetNumberOfDimensions(prhs[1]) == 2,
	 "The set of values must be a 2D real matrix.");

  nDim = mxGetM(prhs[1]);
  nPoints = mxGetN(prhs[1]);
  xset = mxGetPr(prhs[1]);
  mexPrintf("Loading set of values. nDims=%i, nPoints=%i\n",nDim,nPoints);

  udata.prhs[udata.xrhs] = mxCreateDoubleMatrix(1, nDim, mxREAL);

  xopt = mxCreateDoubleMatrix(1, nDim, mxREAL);
  xptr = mxGetPr(xopt);
    

  /* Third term. Parameters  */
  if (nrhs != 2)
    {
      CHECK0(mxIsStruct(prhs[2]), "3rd element must be a struct");
      params = prhs[2];
    }
  else
    {
      params = mxCreateStructMatrix(1,1,0,NULL);
    }

  parameters = load_parameters(params);
  
  error_code = bayes_optimization_disc(nDim,user_function,&udata,xset,nPoints,
				       xptr,&fmin,parameters);

  mxDestroyArray(udata.prhs[udata.xrhs]);
  plhs[0] = xopt;
  if (nlhs > 1) 
    {
      plhs[1] = mxCreateDoubleMatrix(1, 1, mxREAL);
      *(mxGetPr(plhs[1])) = fmin;
    }
    
  if (nlhs > 2)
    {
      plhs[2] = mxCreateDoubleMatrix(1, 1, mxREAL);
      *(mxGetPr(plhs[2])) = (double)(error_code);
    }
    

}