예제 #1
0
void test_argstr_basic_003(CuTest* tc) {
    struct arg_str* a = arg_str0(NULL, "hello,world", "STRVAL", "either --hello or --world or none");
    struct arg_str* b = arg_str0("bB", NULL, "STRVAL", "either -b or -B or none");
    struct arg_str* c = arg_str1("cC", NULL, "STRVAL", "either -c or -C");
    struct arg_str* d = arg_strn("dD", "delta", "STRVAL", 2, 4, "-d|-D|--delta 2..4 occurences");
    struct arg_end* end = arg_end(20);
    void* argtable[] = {a, b, c, d, end};
    int nerrors;

    char* argv[] = {"program", "-Cstring1", "--delta=string2", "--delta=string3", NULL};
    int argc = sizeof(argv) / sizeof(char*) - 1;

    CuAssertTrue(tc, arg_nullcheck(argtable) == 0);

    nerrors = arg_parse(argc, argv, argtable);
    if (nerrors > 0)
        arg_print_errors(stdout, end, argv[0]);

    CuAssertTrue(tc, nerrors == 0);
    CuAssertTrue(tc, a->count == 0);
    CuAssertTrue(tc, b->count == 0);
    CuAssertTrue(tc, c->count == 1);
    CuAssertStrEquals(tc, c->sval[0], "string1");
    CuAssertTrue(tc, d->count == 2);
    CuAssertStrEquals(tc, d->sval[0], "string2");
    CuAssertStrEquals(tc, d->sval[1], "string3");

    arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
}
예제 #2
0
static
int dslink_parse_opts(int argc,
                      char **argv,
                      DSLinkConfig *config) {
    int ret = 0;
    struct arg_lit *help;
    struct arg_str *broker, *log;
    struct arg_end *end;

    void *argTable[] = {
        help = arg_lit0("h", "help", "Displays this help menu"),
        broker = arg_str1("b", "broker", "url", "Sets the broker URL to connect to"),
        log = arg_str0("l", "log", "log type", "Sets the logging level"),
        end = arg_end(5)
    };

    if (arg_nullcheck(argTable) != 0) {
        return DSLINK_ALLOC_ERR;
    }

    int errs = arg_parse(argc, argv, argTable);

    if (help->count > 0) {
        printf("Usage: <opts>\n");
        arg_print_glossary(stdout, argTable, " %-25s %s\n");
        ret = 1;
        goto exit;
    }

    if (errs > 0) {
        dslink_print_help();
        arg_print_errors(stdout, end, ":");
        ret = 1;
        goto exit;
    }

    config->broker_url = broker->sval[0];

    if (log->count > 0) {
        char lvl[8];
        const char *src = log->sval[0];
        size_t len = strlen(src);
        if (len > sizeof(lvl)) {
            len = sizeof(lvl);
        }
        memcpy(lvl, src, len);
        if (dslink_log_set_lvl(lvl, len) != 0) {
            printf("Invalid log level: %s\n", lvl);
            dslink_print_help();
            ret = 1;
            goto exit;
        }
    }

exit:
    arg_freetable(argTable, sizeof(argTable) / sizeof(argTable[0]));
    return ret;
}
예제 #3
0
merge_options_t *new_merge_cli_options() {
    merge_options_t *options = (merge_options_t*) malloc (sizeof(merge_options_t));
    options->num_options = NUM_MERGE_OPTIONS;
    options->input_files = arg_str1(NULL, "vcf-list", NULL, "List of comma-separated input VCF files");
    options->missing_mode = arg_str0(NULL, "missing-mode", NULL, "How to fill missing genotypes (missing = ./., reference = 0/0)");
    options->info_fields = arg_str0(NULL, "info-fields", NULL, "Information to generate in the new INFO column");
    options->copy_filter = arg_lit0(NULL, "copy-filter", "Whether to copy the FILTER column from the original files into the samples");
    options->copy_info = arg_lit0(NULL, "copy-info", "Whether to copy the INFO column from the original files into the samples");
    return options;
}
예제 #4
0
void register_ethernet()
{
    eth_event_group = xEventGroupCreate();
    tcpip_adapter_init();
    ESP_ERROR_CHECK(esp_event_loop_init(eth_event_handler, NULL));

    eth_config_t config = DEFAULT_ETHERNET_PHY_CONFIG;
    config.phy_addr = CONFIG_PHY_ADDRESS;
    config.gpio_config = eth_gpio_config_rmii;
    config.tcpip_input = tcpip_adapter_eth_input;
    config.clock_mode = CONFIG_PHY_CLOCK_MODE;
#ifdef CONFIG_PHY_USE_POWER_PIN
    /* Replace the default 'power enable' function with an example-specific one
     that toggles a power GPIO. */
    config.phy_power_enable = phy_device_power_enable_via_gpio;
#endif

    ESP_ERROR_CHECK(esp_eth_init(&config));

    eth_control_args.control = arg_str1(NULL, NULL, "<start|stop|info>", "Start/Stop Ethernet or Get info of Ethernet");
    eth_control_args.end = arg_end(1);
    const esp_console_cmd_t cmd = {
        .command = "ethernet",
        .help = "Control Ethernet interface",
        .hint = NULL,
        .func = eth_cmd_control,
        .argtable = &eth_control_args
    };
    ESP_ERROR_CHECK(esp_console_cmd_register(&cmd));

    iperf_args.ip = arg_str0("c", "client", "<ip>",
                             "run in client mode, connecting to <host>");
    iperf_args.server = arg_lit0("s", "server", "run in server mode");
    iperf_args.udp = arg_lit0("u", "udp", "use UDP rather than TCP");
    iperf_args.port = arg_int0("p", "port", "<port>",
                               "server port to listen on/connect to");
    iperf_args.interval = arg_int0("i", "interval", "<interval>",
                                   "seconds between periodic bandwidth reports");
    iperf_args.time = arg_int0("t", "time", "<time>", "time in seconds to transmit for (default 10 secs)");
    iperf_args.abort = arg_lit0("a", "abort", "abort running iperf");
    iperf_args.end = arg_end(1);
    const esp_console_cmd_t iperf_cmd = {
        .command = "iperf",
        .help = "iperf command",
        .hint = NULL,
        .func = &eth_cmd_iperf,
        .argtable = &iperf_args
    };
    ESP_ERROR_CHECK(esp_console_cmd_register(&iperf_cmd));
}
예제 #5
0
int main(int argc, char *argv[]) {
	struct arg_str *cblOpt   = arg_str1("c", "cable", "nero:<VID>:<PID> | xil3 | dusb", "cable driver to use");
	struct arg_lit  *scanOpt = arg_lit0("s", "scan", "       scan the JTAG chain");
	struct arg_file *bitOpt  = arg_file0("b", "bitfile", "<fileName>", " bit file to load");
	struct arg_uint *devOpt  = arg_uint0("d", "device", "<device>", "  target device (default \"1\")");
	struct arg_lit *helpOpt  = arg_lit0("h", "help", "            print this help and exit\n");
	struct arg_end  *endOpt  = arg_end(20);
	void* argTable[] = {cblOpt, scanOpt, bitOpt, devOpt, helpOpt, endOpt};
	const char *progName = "xilprg";
	uint32 exitCode = 0;
	int numErrors;
	const char *cable, *bitFile;
	uint32 devNum;
	char line[1024];
	char configFileName[4097];  // TODO: Fix, somehow.

	if ( arg_nullcheck(argTable) != 0 ) {
		fprintf(stderr, "%s: insufficient memory\n", progName);
		fail(1);
	}

	numErrors = arg_parse(argc, argv, argTable);

	if ( helpOpt->count > 0 ) {
		printf("Xilinx Programmer 0.6 Copyright (C) 2006-2011 Zoltan Csizmadia & Chris McClelland\n\nUsage: %s", progName);
		arg_print_syntax(stdout, argTable, "\n");
		printf("\nProgram a Xilinx FPGA.\n\n");
		arg_print_glossary(stdout, argTable,"  %-10s %s\n");
		fail(0);
	}

	if ( numErrors > 0 ) {
		arg_print_errors(stdout, endOpt, progName);
		fprintf(stderr, "Try '%s --help' for more information.\n", progName);
		fail(2);
	}

	if ( (scanOpt->count == 0 && bitOpt->count == 0) ||
	     (scanOpt->count != 0 && bitOpt->count != 0) )
	{
		fprintf(stderr, "%s: you must specify either -s|--scan or -b|--bitfile, but not both\n", progName);
		fprintf(stderr, "Try '%s --help' for more information.\n", progName);
		fail(3);
	}

	cable = cblOpt->sval[0];
	bitFile = bitOpt->count ? bitOpt->filename[0] : NULL;
	devNum = devOpt->count ? devOpt->ival[0] : 1;

	if ( initialize() ) {
		fprintf(stderr, "%s failed to initialize!\n", progName);
		fail(4);
	}

	if ( getConfigFullPath("xilprg.conf", configFileName, sizeof(configFileName)) ) {
		fprintf(stderr, "%s failed to determine the location of its config file!\n", progName);
		fail(5);
	}

	if ( load_config_file(configFileName) ) {
		fprintf(stderr, "%s failed to load its config file from %s!\n", progName, configFileName);
		fail(6);
	}

	try {
		sprintf(line, "cable %s", cable);
		process_command_line(line);
		if ( scanOpt->count ) {
			process_command_line("detect");
		} else {
			sprintf(line, "program %lu \"%s\"", devNum, bitFile);
			process_command_line(line);
		}
	}
	catch ( const std::exception &ex ) {
		fprintf(stderr, "%s failed: %s!\n", progName, ex.what());
		fail(7);
	}

cleanup:
	uninitialize();   
	arg_freetable(argTable, sizeof(argTable)/sizeof(argTable[0]));
	return exitCode;
}
예제 #6
0
int main(int argc, char **argv) {
    int exitcode = 0;
    int nerrors = 0;
    /* Prepare command line arguments */

    struct arg_str  *latero_ip = arg_str1(NULL,"latero_ip","IP", "Latero server IP address");    
    struct arg_lit  *print_resp= arg_lit0("p", "print",          "print response packet");
    struct arg_int  *numpkt    = arg_int0("n", "numpkt","<n>",   "How many packets (default is 1)");
    struct arg_int  *dacval    = arg_intn(NULL,"dac","<int>",0,4,"dac values (up to 4 values)");    
    struct arg_lit  *rd        = arg_lit0("r", "read",           "read");
    struct arg_lit  *wr        = arg_lit0("w", "write",          "write");
    struct arg_int  *addr      = arg_int0("a", "addr",NULL,      "address");
    struct arg_int  *value     = arg_int0("v", "value",NULL,     "value");
    struct arg_lit  *mainctrl  = arg_lit0(NULL,"mainctrl",       "Raw commands are for the main controller");

    struct arg_int  *tpat      = arg_int0("t","testpat","<n>",   "Run Test Pattern:1=Split, 2=AllPin, 3=RowCol");

    struct arg_lit  *latio     = arg_lit0(NULL,"lateroio",       "Raw commands are for the Latero IO card");
    struct arg_lit  *help      = arg_lit0(NULL,"help",           "print this help and exit");
    struct arg_end  *end       = arg_end(10);
    void*  argtable[] = {latero_ip,print_resp,numpkt,dacval,
                         rd, wr, addr, value, mainctrl, tpat, latio,
                         help,end};

    //latero_ip->sval[0] = "192.168.1.108";

    /* verify the argtable[] entries were allocated sucessfully */
    if (arg_nullcheck(argtable) != 0) {
        /* NULL entries were detected, some allocations must have failed */
        printf("Insufficient memory (argtable)\n");
        exitcode = 1; goto exit;
    }

    numpkt->ival[0] = 1;
    tpat->ival[0] = 0;

    nerrors = arg_parse(argc,argv,argtable);

    /* special case: '--help' takes precedence over error reporting */
    if (help->count > 0) {
        printf("Usage: %s", argv[0]);
        arg_print_syntax(stdout,argtable,"\n");
        printf("Latero client demonstration program version 1, revision 1\n");
        arg_print_glossary(stdout,argtable,"  %-25s %s\n");
        exitcode=0; goto exit;
    }

    if (nerrors > 0) {
        /* Display the error details contained in the arg_end struct.*/
        arg_print_errors(stdout,end,argv[0]);
        printf("Try '%s --help' for more information.\n",argv[0]);
        exitcode = 0; goto exit;
    }

    if( wr->count > 0 ) {
        if( addr->count != 1 || value->count != 1 ) {
            printf("Write requires an address and a value\n");
            exitcode = 1; goto exit;
        }
        if( mainctrl->count + latio->count == 0 ) {
            printf("Write requires a destination (--mainctrl or --lateroio)\n");
            exitcode = 1; goto exit;
        }
    }

    if( rd->count > 0 ) {
        if( addr->count != 1 ) {
            printf("Read requires an address\n");
            exitcode = 1; goto exit;
        }
        if( mainctrl->count + latio->count == 0 ) {
            printf("Read requires a destination (--mainctrl or --lateroio)\n");
            exitcode = 1; goto exit;
        }
    }
        

    return( my_main( latero_ip->sval[0], print_resp->count, numpkt->ival[0], dacval->ival, dacval->count,
                     rd->count, wr->count, addr->ival[0], value->ival[0], mainctrl->count, latio->count, tpat->ival[0]) );

    exit:
        printf("Program Ended\n");
        arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0]));
        return(exitcode);

}
예제 #7
0
파일: main.c 프로젝트: omf2097/openomf
int main(int argc, char* argv[]) {
    // commandline argument parser options
    struct arg_lit *help = arg_lit0("h", "help", "print this help and exit");
    struct arg_lit *vers = arg_lit0("v", "version", "print version information and exit");
    struct arg_str *astr = arg_str1("s", "str", "<str>", "Animation string");
    struct arg_end *end = arg_end(20);
    void* argtable[] = {help,vers,astr,end};
    const char* progname = "omf_parse";
    int from_stdin = 0;

    // Make sure everything got allocated
    if(arg_nullcheck(argtable) != 0) {
        printf("%s: insufficient memory\n", progname);
        goto exit_0;
    }

    // Parse arguments
    int nerrors = arg_parse(argc, argv, argtable);
    if(nerrors > 0) {
        arg_print_errors(stdout, end, progname);
        printf("Try '%s --help' for more information.\n", progname);
        goto exit_0;
    }

    // Handle version
    if(vers->count > 0) {
        printf("%s v0.1\n", progname);
        printf("Command line One Must Fall 2097 Animation string parser\n");
        printf("Source code is available at https://github.com/omf2097 under MIT license.\n");
        printf("(C) 2014 Tuomas Virtanen\n");
        goto exit_0;
    }

    // Handle help
    if(help->count > 0) {
        printf("Usage: %s", progname);
        arg_print_syntax(stdout, argtable, "\n");
        printf("\nArguments:\n");
        arg_print_glossary(stdout, argtable, "%-25s %s\n");
        goto exit_0;
    }

    const char *str = *astr->sval;

    if (strcmp("-", *astr->sval) == 0) {
        from_stdin = 1;
        char *tmp_str = malloc(512);
        fgets(tmp_str, 512, stdin);
        // throttle the newline
        tmp_str[strlen(tmp_str)-1] = '\0';
        str = tmp_str;
    }

    // Print some data
    printf("Parsing \"%s\".\n\n", str);

    int err_pos;
    sd_script script;
    sd_script_create(&script);
    int ret = sd_script_decode(&script, str, &err_pos);
    if(ret != SD_SUCCESS) {
        if(ret == SD_INVALID_TAG) {
            printf("Bad input string! Error at position %d.\n", err_pos);
        }
        if(ret == SD_ANIM_INVALID_STRING) {
            printf("Bad input string!\n");
        }
        goto exit_1;
    }

    for(int frame_id = 0; frame_id < script.frame_count; frame_id++) {
        sd_script_frame *frame = &script.frames[frame_id];
        printf("%d. Frame %d: '%c%d'\n",
            frame_id,
            frame->sprite,
            (char)(frame->sprite+65),
            frame->tick_len);
        for(int tag_id = 0; tag_id < frame->tag_count; tag_id++) {
            sd_script_tag *tag = &frame->tags[tag_id];
            if(tag->desc == NULL) {
                tag->desc = "";
            }
            if(tag->has_param) {
                printf("   %-4s %-4d %s\n", tag->key, tag->value, tag->desc);
            } else {
                printf("   %-4s      %s\n", tag->key, tag->desc);
            }
        }
    }

exit_1:
    sd_script_free(&script);
exit_0:
    if (from_stdin) {
        free((char*)str);
    }
    arg_freetable(argtable, sizeof(argtable)/sizeof(argtable[0]));
    return 0;
}
예제 #8
0
split_options_t *new_split_cli_options() {
    split_options_t *options = (split_options_t*) malloc (sizeof(split_options_t));
    options->criterion = arg_str1(NULL, "criterion", NULL, "Criterion for splitting the file");
    options->intervals = arg_str0(NULL, "intervals", NULL, "Values of intervals for splitting the file");
    return options;
}
예제 #9
0
struct Args parse_arguments(int argc, char *argv[]) {

    struct Args args;
    args.mass = 0.0;
    args.diam = 0.0;
    args.cd =   0.0;
    args.wind = 0.0;
    args.run_simulation = 0;

    // Simulation options
    struct arg_dbl *mass = arg_dbl1("m", "mass", "<float>",
            "Mass of rocket without motor (g)");
    struct arg_dbl *diam = arg_dbl1("d", "diam", "<float>",
            "Diameter of rocket (mm)");
    struct arg_dbl *cd = arg_dbl1("c", "cd", "<float>",
            "Drag coefficient of rocket");
    struct arg_dbl *wind = arg_dbl1("w", "wind", "<float>",
            "Wind speed (km/h)");
    struct arg_str *motor = arg_str1("M", "motor", "<string>",
            "Motor (use '-l' or '--list_motors' to see list");

    // Help options
    struct arg_lit *help = arg_lit0("h", "help", "Printing help");
    struct arg_lit *list_motors = arg_lit0("l", "list_motors", "List motors");
    struct arg_end *end = arg_end(20);

    // Prepare argtable
    void *argtable[] = {mass, diam, cd, wind, motor, help, list_motors, end};
    const char *progname = "lawn_dart";
    int nerrors;

    // Verify the argtable[] entries were allocated sucessfully
    if (arg_nullcheck(argtable) != 0) {
        // NULL entries were detected, some allocations must have failed
        printf("%s: insufficient memory\n",progname);
    }

    // Parse the command line as defined by argtable[]
    nerrors = arg_parse(argc, argv, argtable);

    // Check for --help
    if (help->count > 0 || argc == 1) {
        printf("Lawn Dart: A Model Rocket Flight Simulator\n\n");
        printf("%s", progname);
        arg_print_syntax(stdout, argtable,"\n");
        puts("");
        arg_print_glossary(stdout, argtable,"  %-25s %s\n");
        puts("");
        print_help();
    }
    else if (list_motors->count > 0) {
        print_motor_list();
    }
    else {
        // If all required options have been specified
        if (!nerrors) {
            // Get options from params
            args.mass = mass->dval[0] / 1000.0;
            args.diam = diam->dval[0] / 1000.0;
            args.cd =   cd->dval[0];
            args.wind = wind->dval[0] / 3.6;

            // Assert proper values
            int all_params_ok = 1;
            if (args.mass < 0.001 || args.mass > 1000.0) all_params_ok = 0;
            if (args.diam < 0.001 || args.diam > 1.0) all_params_ok = 0;
            if (args.cd < 0.0 || args.cd > 1.0) all_params_ok = 0;
            if (args.wind < 0.0 || args.wind > 100.0) all_params_ok = 0;

            // Confirm to run simulation
            if (all_params_ok) {
                args.run_simulation = 1;
            }
        }
        else {
            puts("--- Missing required parameters ---\n");
            printf("%s", progname);
            arg_print_syntax(stdout, argtable,"\n");
            puts("");
            arg_print_glossary(stdout, argtable,"  %-25s %s\n");
            puts("");
            print_help();
        }
    }

    return args;
}
예제 #10
0
int main(int argc, char** argv) {
  int ret, i;
  int nerrors[NUMBER_OF_DIFFERENT_SYNTAXES + 1];

  /* argtable setup */
  /* SYNTAX 1: [--info] */
  info1 = arg_lit1(NULL, "info", "Show information about the FLI camera");
  end1 = arg_end(20);
  void * argtable1[] = {info1, end1};
  argtable[1] = argtable1;

  /* SYNTAX 2: [--get-temperature]  */
  gettemp2 = arg_lit1(NULL, "get-temperature", "Print the temperature of the CCD, base and cooling power");
  end2 = arg_end(20);
  void * argtable2[] = {gettemp2, end2};
  argtable[2] = argtable2;

  /* SYNTAX 3: [--set-temperature]  */
  settemp3 = arg_int1(NULL, "set-temperature", "N", "Set the temperature of the CCD (in Celsius)");
  end3 = arg_end(20);
  void * argtable3[] = {settemp3, end3};
  argtable[3] = argtable3;

  /* SYNTAX 4: [--fan]  */
  fan4 = arg_str1(NULL, "fan", "(on|off)", "Turn on or off the fan");
  end4 = arg_end(20);
  void * argtable4[] = {fan4, end4};
  argtable[4] = argtable4;

  /* SYNTAX 5: [--shutter]  */
  shutter5 = arg_str1(NULL, "shutter", "(open|close)", "Open or close the shutter");
  end5 = arg_end(20);
  void * argtable5[] = {shutter5, end5};
  argtable[5] = argtable5;

  /* SYNTAX 6: --acquire <time/sec> --shutter {open|close} --output xyz.fits
             [--bin <bx>,<by>] [--offset <x0>,<y0>] [--size <sx>,<sy>]
             [--mode <mode>...] [--verbose]
   */
  acquire6 = arg_str1(NULL, "acquire", "<time>", "Exposure time in sec");
  shutter6 = arg_str1(NULL, "shutter", "(open|close)", "Whether to open or close the shutter");
  output6 = arg_file1(NULL, "output", "xyz.fits", "Output filename for the FITS file");
  bin6 = arg_str0(NULL, "bin", "<bx,by>", "Binning options in X,Y format");
  offset6 = arg_str0(NULL, "offset", "<x0,y0>", "Offset options in X,Y format");
  size6 = arg_str0(NULL, "size", "<sx,sy>", "Sizes in X,Y format");
  mode6 = arg_str0(NULL, "mode", "(1mhz|8mhz)", "Download speed");
  verbose6 = arg_lit0(NULL, "verbose", "Show verbose output");
  end6 = arg_end(20);
  void * argtable6[] = {acquire6, shutter6, output6, bin6, offset6, size6, mode6, verbose6, end6};
  argtable[6] = argtable6;

  /* SYNTAX 7: [--help]*/
  help7 = arg_lit1(NULL, "help", "Print this help");
  end7 = arg_end(20);
  void * argtable7[] = {help7, end7};
  argtable[7] = argtable7;

  /* verify all argtable[] entries were allocated successfully */
  for (i = 1; i <= NUMBER_OF_DIFFERENT_SYNTAXES; i++) {
    if (arg_nullcheck(argtable[i]) != 0) {
      printf("%s: insufficient memory\n", progname);
      return EXIT_FAILURE;
    }
  }

  /* set defaults for the optional arguments */
  bin6->sval[0] = "1,1";
  offset6->sval[0] = "0,0";
  size6->sval[0] = "4096,4096";
  mode6->sval[0] = "8mhz";

  /* parse all argument possibilities */
  for (i = 1; i <= NUMBER_OF_DIFFERENT_SYNTAXES; i++) {
    nerrors[i] = arg_parse(argc, argv, argtable[i]);
  }

  /* select the right command */
  /* --info */
  if (nerrors[1] == 0) {
    if (info1->count > 0) {
      ret = camera_info();
      if (ret) return ret;
      return 0;
    }
    /* --get-temperature */
  } else if (nerrors[2] == 0) {
    if (gettemp2->count > 0) {
      ret = camera_get_temp();
      if (ret) return ret;
      return 0;
    }
    /* --set-temperature */
  } else if (nerrors[3] == 0) {
    if (settemp3->count > 0) {
      ret = camera_set_temp(settemp3->ival[0]);
      if (ret) return ret;
      return 0;
    }
    /* --fan */
  } else if (nerrors[4] == 0) {
    int fan;
    if (strcmp("on", fan4->sval[0]) == 0) {
      fan = 1;
    } else if (strcmp("off", fan4->sval[0]) == 0) {
      fan = 0;
    } else {
      fprintf(stderr, "Cannot parse the option for --fan, see --help.\n");
      return -1;
    }
    ret = camera_set_fan(fan);
    if (ret) return ret;
    return 0;
    /* --shutter */
  } else if (nerrors[5] == 0) {
    int open_shutter;
    if (strcmp("open", shutter5->sval[0]) == 0) {
      open_shutter = 1;
    } else if (strcmp("close", shutter5->sval[0]) == 0) {
      open_shutter = 0;
    } else {
      fprintf(stderr, "Cannot parse the option for --shutter, see --help.\n");
      return -1;
    }
    ret = camera_control_shutter(open_shutter);
    if (ret) return ret;
    return 0;
    /* --acquire */
  } else if (nerrors[6] == 0) {
    if (acquire6->count > 0) {

      /* local variables to store the arguments */
      float exposure_time;
      int is_dark;
      char * output_filename;
      char * bin_options;
      char * offset_options;
      char * size_options;
      int bx, by;
      int x0, y0;
      int sx, sy;
      int one_mhz_speed;
      int is_verbose = 0;

      /* copy const char arrays to char arrays to suppress warnings */
      output_filename = (char*) malloc((strlen(output6->filename[0])) * sizeof (char));
      bin_options = (char*) malloc((strlen(bin6->sval[0])) * sizeof (char));
      offset_options = (char*) malloc((strlen(offset6->sval[0])) * sizeof (char));
      size_options = (char*) malloc((strlen(size6->sval[0])) * sizeof (char));
      strcpy(output_filename, output6->filename[0]);
      strcpy(bin_options, bin6->sval[0]);
      strcpy(offset_options, offset6->sval[0]);
      strcpy(size_options, size6->sval[0]);

      /* process arguments */
      /* exposure time */
      exposure_time = atof(acquire6->sval[0]);
      if (exposure_time < 0) {
        fprintf(stderr, "Exposure time cannot be below zero (given %f).\n", exposure_time);
        return -1;
      }

      /* shutter */
      if (strcmp("open", shutter6->sval[0]) == 0) {
        is_dark = 0;
      } else if (strcmp("close", shutter6->sval[0]) == 0) {
        is_dark = 1;
      } else {
        fprintf(stderr, "Cannot parse the option for --shutter, see --help.\n");
        return -1;
      }

      /* bin, size and offset */
      ret = parse_comma_separated_values(bin_options, &bx, &by, "bin");
      if (ret) return ret;
      ret = parse_comma_separated_values(offset_options, &x0, &y0, "offset");
      if (ret) return ret;
      ret = parse_comma_separated_values(size_options, &sx, &sy, "size");
      if (ret) return ret;

      /* mode */
      if (strcmp("1mhz", mode6->sval[0]) == 0) {
        one_mhz_speed = 1;
      } else if (strcmp("8mhz", mode6->sval[0]) == 0) {
        one_mhz_speed = 0;
      } else {
        fprintf(stderr, "Cannot parse the option for --mode, see --help.\n");
        return -1;
      }

      /* verbose */
      if (verbose6->count > 0) is_verbose = 1;

      ret = camera_acquire(exposure_time, is_dark, output_filename,
              bx, by, x0, y0, sx, sy, one_mhz_speed, is_verbose);
      if (ret) return ret;
      return 0;
    }
    /* --help */
  } else if (nerrors[7] == 0) {
    if (help7) {
      ret = camera_help();
      if (ret) return ret;
      return 0;
    }
    /* incorrect or partially incorrect argument syntaxes */
  } else {
    if (settemp3->count > 0) {
      arg_print_errors(stdout, end3, progname);
      printf("usage: %s ", progname);
      arg_print_syntax(stdout, argtable3, "\n");
    } else if (fan4->count > 0) {
      arg_print_errors(stdout, end4, progname);
      printf("usage: %s ", progname);
      arg_print_syntax(stdout, argtable4, "\n");
    } else if (acquire6->count > 0) {
      arg_print_errors(stdout, end5, progname);
      printf("usage: %s ", progname);
      arg_print_syntax(stdout, argtable5, "\n");
    } else {
      printf("%s: unable to parse arguments, see syntax below:\n", progname);
      ret = 0;
      ret = camera_help();
      return ret;
    }
    return EXIT_FAILURE;
  }

  /* no command line options at all */
  printf("Try '%s --help' for more information.\n", progname);
  return (EXIT_SUCCESS);
}
예제 #11
0
int main(int argc, char* argv[])
{
    struct arg_lit *help;
    struct arg_file *input, *output;
    struct arg_str *rotation;
    struct arg_end *end;

    /* command line parsing through argtable package */
    void* argtable[] = {
        help        = arg_lit0("h", "help", "display this help and exit"),
        input       = arg_file0("i", "input", "input", "name of the input file (default stdin"),
        output      = arg_file0("o", "output", "file", "name of the output file (default stdout)"),
        rotation    = arg_str1(NULL, NULL, "\"x y z w\"", "rotate w degrees around axis x y z"),
        end         = arg_end(20) };
    const char* progname = "xyztk-rotate";
    int rc = 0;
    int nerrors;

    /* verify the argtable[] entries were allocated sucessfully */
    if (arg_nullcheck(argtable) != 0)
        {
        /* NULL entries were detected, some allocations must have failed */
        printf("%s: insufficient memory\n", progname);
        rc=1;
        goto exit;
        }

    /* set default values */

    /* parse the command line flags, overriding default values */
    nerrors = arg_parse(argc,argv,argtable);

    /* special case: '--help' takes precedence over error reporting */
    if (help->count > 0)
        {
        printf("Usage: %s", progname);
        arg_print_syntax(stdout,argtable,"\n");
        printf("\n");
        arg_print_glossary(stdout,argtable,"  %-40s %s\n");
        printf("\n");
        rc=0;
        goto exit;
        }

    /* special case: no command line options induces brief help */
    if (argc==1) {
        printf("Try '%s --help' for more information.\n",progname);
        rc=0;
        goto exit;
    }

    /* If the parser returned any errors then display them and exit */
    if (nerrors > 0)
        {
        /* Display the error details contained in the arg_end struct.*/
        arg_print_errors(stdout,end,progname);
        printf("Try '%s --help' for more information.\n",progname);
        rc=1;
        goto exit;
        }

    /* set global structures */

    /* initialize I/O pointers */
    FILE* in;
    if (input->count) {
      in = fopen(input->filename[0], "r");
    } else {
      in = stdin;
    }

    FILE* out;
    if (output->count) {
      out = fopen(output->filename[0], "w");
    } else {
      out = stdout;
    }

    /* initialize molecule structure */
    xyztk_molecule_t molecule;
    xyztk_molecule_load (&molecule, in);

    /* read rotation from string */
    xyztk_quat_t r;
    sscanf (rotation->sval[0], "%lf%lf%lf%lf", &r.x, &r.y, &r.z, &r.w);
    xyztk_molecule_rotate (&molecule, &r);

    /* print output */
    int i;
    fprintf(out, "%d\n", molecule.n_atoms);
    fprintf(out, "%s", molecule.name);
    for (i = 0; i < molecule.n_atoms; ++i)
      {
      fprintf(out, "%-8s %20.14lf %20.14lf %20.14lf \n",
	      molecule.label[i].s, molecule.coord[i].x, molecule.coord[i].y, molecule.coord[i].z);
      }

exit:
    /* deallocate each non-null entry in argtable[] */
    arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0]));

    return rc;
}
예제 #12
0
int genkmarkers(int argc, char* argv[])
{
// determine my process name
_splitpath(argv[0],NULL,NULL,gszProcName,NULL);
#else
int
genkmarkers(int argc, char** argv)
{
// determine my process name
CUtility::splitpath((char *)argv[0],NULL,gszProcName);
#endif
int iScreenLogLevel;		// level of screen diagnostics
int iFileLogLevel;			// level of file diagnostics
char szLogFile[_MAX_PATH];	// write diagnostics to this file
int Rslt = 0;   			// function result code >= 0 represents success, < 0 on failure

int NumberOfProcessors;		// number of installed CPUs
int NumThreads;				// number of threads (0 defaults to number of CPUs)

int PMode;					// processing mode
int KMerLen;				// this length K-mers
int PrefixLen;				// inter-cultivar shared prefix length
int SuffixLen;				// cultivar specific suffix length
int MinWithPrefix;			// minimum number of cultivars required to have the shared prefix
int MinHamming;				// must be at least this Hamming away from any other K-mer in other species
char szCultivarName[cMaxDatasetSpeciesChrom+1];		// cultivar name
char szPartialCultivarsList[(cMaxDatasetSpeciesChrom + 10) * cMaxTargCultivarChroms];		// individual species parsed from this comma/tab/space separated list
int NumPartialCultivars;	// there are this many pseudo chromosomes for targeted cultivar for which K-mer markers are required
char *pszPartialCultivars[cMaxTargCultivarChroms+1];	// pseudo chromosome names which identify targeted cultivar
char szSfxPseudoGenome[_MAX_PATH];		// contains assembly + suffix array over all psuedo-chromosomes for all cultivars
char szMarkerFile[_MAX_PATH];			// output potential markers to this file
char szMarkerReadsFile[_MAX_PATH];		// output reads containing potential markers to this file


char szSQLiteDatabase[_MAX_PATH];	// results summaries to this SQLite file
char szExperimentName[cMaxDatasetSpeciesChrom+1];			// experiment name
char szExperimentDescr[1000];		// describes experiment

// command line args
struct arg_lit  *help    = arg_lit0("h","help",                 "Print this help and exit");
struct arg_lit  *version = arg_lit0("v","version,ver",			"Print version information and exit");
struct arg_int *FileLogLevel=arg_int0("f", "FileLogLevel",		"<int>","Level of diagnostics written to screen and logfile 0=fatal,1=errors,2=info,3=diagnostics,4=debug");
struct arg_file *LogFile = arg_file0("F","log","<file>",		"Diagnostics log file");

struct arg_int *pmode = arg_int0("m","mode","<int>",			"Processing mode : 0 - default with K-mer extension, 1 - no K-mer extension, 2 - inter-cultivar shared prefix sequences ");
struct arg_int *kmerlen = arg_int0("k","kmer","<int>",			"Cultivar specific K-mers of this length (default 50, range 25..100)");

struct arg_int *prefixlen = arg_int0("p","prefixlen","<int>",	"Cultivar specific K-mers to contain inter-cultivar shared prefix sequences of this length (Mode 2 only");
struct arg_int *minwithprefix = arg_int0("s","minshared","<int>","Inter-cultivar shared prefix sequences must be present in this many cultivars (Mode 2 only, default all)");

struct arg_int *minhamming = arg_int0("K","minhamming","<int>", "Minimum Hamming separation distance in other non-target cultivars (default 2, range 1..5)");
struct arg_str *cultivar = arg_str1("c","cultivar","<str>",		"Cultivar name to associate with identified marker K-mers");
struct arg_str *chromnames = arg_str1("C","chromnames","<str>",	"Comma/space separated list of pseudo-chrom names specific to cultivar for which markers are required");
struct arg_file *infile = arg_file1("i","in","<file>",		    "Use this suffix indexed pseudo-chromosomes file");
struct arg_file *outfile = arg_file1("o","markers","<file>",		"Output accepted marker K-mer sequences to this multifasta file");
struct arg_file *outreadsfile = arg_file0("O","markerreads","<file>",	"Output reads containing accepted marker K-mers to this multifasta file");
struct arg_int *numthreads = arg_int0("T","threads","<int>",		"number of processing threads 0..128 (defaults to 0 which sets threads to number of CPU cores)");

struct arg_file *summrslts = arg_file0("q","sumrslts","<file>",		"Output results summary to this SQLite3 database file");
struct arg_str *experimentname = arg_str0("w","experimentname","<str>",		"experiment name SQLite3 database file");
struct arg_str *experimentdescr = arg_str0("W","experimentdescr","<str>",	"experiment description SQLite3 database file");
struct arg_end *end = arg_end(200);

void *argtable[] = {help,version,FileLogLevel,LogFile,
					summrslts,experimentname,experimentdescr,
	                pmode,kmerlen,prefixlen,minwithprefix,minhamming,cultivar,chromnames,infile,outfile,outreadsfile,
					numthreads,
					end};

char **pAllArgs;
int argerrors;
argerrors = CUtility::arg_parsefromfile(argc,(char **)argv,&pAllArgs);
if(argerrors >= 0)
	argerrors = arg_parse(argerrors,pAllArgs,argtable);

/* special case: '--help' takes precedence over error reporting */
if (help->count > 0)
        {
		printf("\n%s %s %s, Version %s\nOptions ---\n", gszProcName,gpszSubProcess->pszName,gpszSubProcess->pszFullDescr,cpszProgVer);
        arg_print_syntax(stdout,argtable,"\n");
        arg_print_glossary(stdout,argtable,"  %-25s %s\n");
		printf("\nNote: Parameters can be entered into a parameter file, one parameter per line.");
		printf("\n      To invoke this parameter file then precede its name with '@'");
		printf("\n      e.g. %s %s @myparams.txt\n",gszProcName,gpszSubProcess->pszName);
		printf("\nPlease report any issues regarding usage of %s at https://github.com/csiro-crop-informatics/biokanga/issues\n\n",gszProcName);
		return(1);
        }

    /* special case: '--version' takes precedence error reporting */
if (version->count > 0)
        {
		printf("\n%s %s Version %s\n",gszProcName,gpszSubProcess->pszName,cpszProgVer);
		return(1);
        }

if (!argerrors)
	{
	if(FileLogLevel->count && !LogFile->count)
		{
		printf("\nError: FileLogLevel '-f%d' specified but no logfile '-F<logfile>\n'",FileLogLevel->ival[0]);
		return(1);
		}

	iScreenLogLevel = iFileLogLevel = FileLogLevel->count ? FileLogLevel->ival[0] : eDLInfo;
	if(iFileLogLevel < eDLNone || iFileLogLevel > eDLDebug)
		{
		printf("\nError: FileLogLevel '-l%d' specified outside of range %d..%d\n",iFileLogLevel,eDLNone,eDLDebug);
		return(1);
		}

	if(LogFile->count)
		{
		strncpy(szLogFile,LogFile->filename[0],_MAX_PATH);
		szLogFile[_MAX_PATH-1] = '\0';
		}
	else
		{
		iFileLogLevel = eDLNone;
		szLogFile[0] = '\0';
		}

	// now that log parameters have been parsed then initialise diagnostics log system
	if(!gDiagnostics.Open(szLogFile,(etDiagLevel)iScreenLogLevel,(etDiagLevel)iFileLogLevel,true))
		{
		printf("\nError: Unable to start diagnostics subsystem\n");
		if(szLogFile[0] != '\0')
			printf(" Most likely cause is that logfile '%s' can't be opened/created\n",szLogFile);
		return(1);
		}
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Subprocess %s Version %s starting",gpszSubProcess->pszName,cpszProgVer);

	gExperimentID = 0;
	gProcessID = 0;
	gProcessingID = 0;
	szSQLiteDatabase[0] = '\0';
	szExperimentName[0] = '\0';
	szExperimentDescr[0] = '\0';

	if(experimentname->count)
		{
		strncpy(szExperimentName,experimentname->sval[0],sizeof(szExperimentName));
		szExperimentName[sizeof(szExperimentName)-1] = '\0';
		CUtility::TrimQuotedWhitespcExtd(szExperimentName);
		CUtility::ReduceWhitespace(szExperimentName);
		}
	else
		szExperimentName[0] = '\0';

	gExperimentID = 0;
	gProcessID = 0;
	gProcessingID = 0;
	szSQLiteDatabase[0] = '\0';
	szExperimentDescr[0] = '\0';
	if(summrslts->count)
		{
		strncpy(szSQLiteDatabase,summrslts->filename[0],sizeof(szSQLiteDatabase)-1);
		szSQLiteDatabase[sizeof(szSQLiteDatabase)-1] = '\0';
		CUtility::TrimQuotedWhitespcExtd(szSQLiteDatabase);
		if(strlen(szSQLiteDatabase) < 1)
			{
			gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: After removal of whitespace, no SQLite database specified with '-q<filespec>' option");
			return(1);
			}

		if(strlen(szExperimentName) < 1)
			{
			gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: After removal of whitespace, no SQLite experiment name specified with '-w<str>' option");
			return(1);
			}
		if(experimentdescr->count)
			{
			strncpy(szExperimentDescr,experimentdescr->sval[0],sizeof(szExperimentDescr)-1);
			szExperimentDescr[sizeof(szExperimentDescr)-1] = '\0';
			CUtility::TrimQuotedWhitespcExtd(szExperimentDescr);
			}
		if(strlen(szExperimentDescr) < 1)
			{
			gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: After removal of whitespace, no SQLite experiment description specified with '-W<str>' option");
			return(1);
			}

		gExperimentID = gSQLiteSummaries.StartExperiment(szSQLiteDatabase,false,true,szExperimentName,szExperimentName,szExperimentDescr);
		if(gExperimentID < 1)
			return(1);
		gProcessID = gSQLiteSummaries.AddProcess((char *)gpszSubProcess->pszName,(char *)gpszSubProcess->pszName,(char *)gpszSubProcess->pszFullDescr);
		if(gProcessID < 1)
			return(1);
		gProcessingID = gSQLiteSummaries.StartProcessing(gExperimentID,gProcessID,(char *)cpszProgVer);
		if(gProcessingID < 1)
			return(1);
		gDiagnostics.DiagOut(eDLInfo,gszProcName,"Initialised SQLite database '%s' for results summary collection",szSQLiteDatabase);
		gDiagnostics.DiagOut(eDLInfo,gszProcName,"SQLite database experiment identifier for '%s' is %d",szExperimentName,gExperimentID);
		gDiagnostics.DiagOut(eDLInfo,gszProcName,"SQLite database process identifier for '%s' is %d",(char *)gpszSubProcess->pszName,gProcessID);
		gDiagnostics.DiagOut(eDLInfo,gszProcName,"SQLite database processing instance identifier is %d",gProcessingID);
		}
	else
		{
		szSQLiteDatabase[0] = '\0';
		szExperimentDescr[0] = '\0';
		}

// show user current resource limits
#ifndef _WIN32
	gDiagnostics.DiagOut(eDLInfo, gszProcName, "Resources: %s",CUtility::ReportResourceLimits());
#endif

#ifdef _WIN32
	SYSTEM_INFO SystemInfo;
	GetSystemInfo(&SystemInfo);
	NumberOfProcessors = SystemInfo.dwNumberOfProcessors;
#else
	NumberOfProcessors = sysconf(_SC_NPROCESSORS_CONF);
#endif
	int MaxAllowedThreads = min(cMaxWorkerThreads,NumberOfProcessors);	// limit to be at most cMaxWorkerThreads
	if((NumThreads = numthreads->count ? numthreads->ival[0] : MaxAllowedThreads)==0)
		NumThreads = MaxAllowedThreads;
	if(NumThreads < 0 || NumThreads > MaxAllowedThreads)
		{
		gDiagnostics.DiagOut(eDLWarn,gszProcName,"Warning: Number of threads '-T%d' specified was outside of range %d..%d",NumThreads,1,MaxAllowedThreads);
		gDiagnostics.DiagOut(eDLWarn,gszProcName,"Warning: Defaulting number of threads to %d",MaxAllowedThreads);
		NumThreads = MaxAllowedThreads;
		}


	PMode = (etPMode)(pmode->count ? pmode->ival[0] : ePMExtdKMers);
	if(PMode < ePMExtdKMers || PMode >= ePMplaceholder)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Processing mode '-m%d' specified outside of range %d..%d\n",PMode,ePMExtdKMers,(int)ePMplaceholder-1);
		exit(1);
		}

	KMerLen = kmerlen->count ? kmerlen->ival[0] : cDfltKMerLen;
	if(KMerLen < cMinKMerLen || KMerLen > cMaxKMerLen)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: K-mer core length '-k%d' must be in range %d..%d",KMerLen,cMinKMerLen,cMaxKMerLen);
		return(1);
		}

	if(PMode == 2)
		{
		PrefixLen = prefixlen->count ? prefixlen->ival[0] : KMerLen/2;
		if(PrefixLen < cMinKMerLen/2 || PrefixLen > KMerLen-(cMinKMerLen/2))
			{
			gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Prefix length '-p%d' must be in range %d..%d",KMerLen,cMinKMerLen/2,KMerLen-(cMinKMerLen/2));
			return(1);
			}
		SuffixLen = KMerLen - PrefixLen;
		MinWithPrefix = minwithprefix->count ? minwithprefix->ival[0] : 0;
		if(MinWithPrefix != 0 && MinWithPrefix < 1)
			{
			gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Minimum cultivars sharing prefix sequence '-s%d' must be either 0 (all) or at least 1",MinWithPrefix);
			return(1);
			}
		}

	MinHamming = minhamming->count ? minhamming->ival[0] : cDfltHamming;
	if(MinHamming < cMinHamming || MinHamming > cMaxHamming)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Minimum Hamming separation '-K%d' must be in range %d..%d",MinHamming,cMinHamming,cMaxHamming);
		return(1);
		}

	strncpy(szCultivarName,cultivar->sval[0],cMaxDatasetSpeciesChrom);
	szCultivarName[cMaxDatasetSpeciesChrom]= '\0';
	CUtility::TrimQuotedWhitespcExtd(szCultivarName);
	if(strlen(szCultivarName) < 1)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Expected cultivar name '-c<name>' is empty");
		return(1);
		}

	strncpy(szPartialCultivarsList,chromnames->sval[0],sizeof(szPartialCultivarsList));
	szPartialCultivarsList[sizeof(szPartialCultivarsList)-1] = '\0';
	CUtility::TrimQuotedWhitespcExtd(szPartialCultivarsList);
	CUtility::ReduceWhitespace(szPartialCultivarsList);
	char *pChr = szPartialCultivarsList;
	char *pStartChr;
	char Chr;
	int CurSpeciesLen;
	NumPartialCultivars=0;
	CurSpeciesLen = 0;
	pStartChr = pChr;
	while((Chr = *pChr++) != '\0')
		{
		if(Chr == ' ' || Chr == '\t' || Chr == ',')	// treat any of these as delimiters
			{
			pChr[-1] = '\0';
			if(CurSpeciesLen != 0)
				{
				pszPartialCultivars[NumPartialCultivars++] = pStartChr;
				CurSpeciesLen = 0;
				}
			pStartChr = pChr;
			continue;
			}
		CurSpeciesLen += 1;
		}
	if(CurSpeciesLen)
		pszPartialCultivars[NumPartialCultivars++] = pStartChr;

	if(!NumPartialCultivars)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Expected at least one ('-C<names>') targeted cultivar chromosme name");
		return(1);
		}

	strcpy(szSfxPseudoGenome,infile->filename[0]);
	CUtility::TrimQuotedWhitespcExtd(szSfxPseudoGenome);
	if(strlen(szSfxPseudoGenome) < 1)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Expected input pseudo-genome suffix array filename '-i<name>' is empty");
		return(1);
		}

	strcpy(szMarkerFile,outfile->filename[0]);
	CUtility::TrimQuotedWhitespcExtd(szMarkerFile);
	if(strlen(szMarkerFile) < 1)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Expected marker file to generate filename '-o<name>' is empty");
		return(1);
		}

	if(outreadsfile->count)
		{
		strcpy(szMarkerReadsFile,outreadsfile->filename[0]);
		CUtility::TrimQuotedWhitespcExtd(szMarkerReadsFile);
		if(strlen(szMarkerReadsFile) < 1)
			{
			gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Reads containing markers filename '-O<name>' is empty");
			return(1);
			}
		}
	else
		szMarkerReadsFile[0] = '\0';

	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Processing parameters:");
	const char *pszDescr;
	switch(PMode) {
		case ePMExtdKMers:
			pszDescr = "Extended K-mer markers";
			break;
		case ePMNoExtdKMers:
			pszDescr = "Non-extended K-mer markers";
			break;
		case ePMPrefixKMers:
			pszDescr = "K-mers to share prefix sequence with other cultivars";
			break;
		}

	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Processing mode is : '%s'",pszDescr);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Targeted cultivar name : '%s'",szCultivarName);

	for(int Idx = 0; Idx < NumPartialCultivars; Idx++)
		gDiagnostics.DiagOutMsgOnly(eDLInfo,"Targeted cultivar chromosome name (%d) : '%s'", Idx + 1,pszPartialCultivars[Idx]);

	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Core K-mer length : %d",KMerLen);
	if(PMode == ePMPrefixKMers)
		{
		gDiagnostics.DiagOutMsgOnly(eDLInfo,"Inter-cultivar shared prefix sequence length : %d",PrefixLen);
		gDiagnostics.DiagOutMsgOnly(eDLInfo,"Cultivar specific suffix sequence length : %d",SuffixLen);
		if(MinWithPrefix)
			gDiagnostics.DiagOutMsgOnly(eDLInfo,"Min number cultivars sharing prefix : %d",MinWithPrefix);
		else
			gDiagnostics.DiagOutMsgOnly(eDLInfo,"Min number cultivars sharing prefix : 'All'");
		}
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Minimum Hamming separation : %d",MinHamming);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Input indexed pseudo-genome file: '%s'",szSfxPseudoGenome);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Write marker K-mers to file: '%s'",szMarkerFile);
	if(szMarkerReadsFile[0] != '\0')
		gDiagnostics.DiagOutMsgOnly(eDLInfo,"Write marker containing reads to file: '%s'",szMarkerReadsFile);

	if(szExperimentName[0] != '\0')
		gDiagnostics.DiagOutMsgOnly(eDLInfo,"This processing reference: %s",szExperimentName);

	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Number of processing threads: %d",NumThreads);

	if(gExperimentID > 0)
		{
		int ParamID;

		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(szLogFile),"log",szLogFile);

		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTInt32,sizeof(PMode),"mode",&PMode);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTInt32,sizeof(KMerLen),"kmer",&KMerLen);

		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTInt32,sizeof(PrefixLen),"prefixlen",&PrefixLen);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTInt32,sizeof(SuffixLen),"suffixlen",&SuffixLen);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTInt32,sizeof(MinWithPrefix),"minwithprefix",&MinWithPrefix);

		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTInt32,sizeof(MinHamming),"minhamming",&MinHamming);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTInt32,sizeof(NumThreads),"threads",&NumThreads);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTInt32,sizeof(NumberOfProcessors),"cpus",&NumberOfProcessors);

		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(szCultivarName),"cultivar",szCultivarName);

		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTInt32,sizeof(NumPartialCultivars),"NumPartialCultivars",&NumPartialCultivars);
		for(int Idx = 0; Idx < NumPartialCultivars; Idx++)
			ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(pszPartialCultivars[Idx]),"chromnames",pszPartialCultivars[Idx]);

		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(szSfxPseudoGenome),"in",szSfxPseudoGenome);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(szMarkerFile),"markers",szMarkerFile);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(szMarkerReadsFile),"markerreads",szMarkerReadsFile);

		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(szSQLiteDatabase),"sumrslts",szSQLiteDatabase);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(szExperimentName),"experimentname",szExperimentName);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(szExperimentDescr),"experimentdescr",szExperimentDescr);
		}


#ifdef _WIN32
	SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS);
#endif
	gStopWatch.Start();
	Rslt = LocMarkers((etPMode)PMode,KMerLen,PrefixLen,SuffixLen,MinWithPrefix,MinHamming,szCultivarName,NumPartialCultivars,pszPartialCultivars,szSfxPseudoGenome,szMarkerFile,szMarkerReadsFile,NumThreads);
	Rslt = Rslt >=0 ? 0 : 1;
	if(gExperimentID > 0)
		{
		if(gProcessingID)
			gSQLiteSummaries.EndProcessing(gProcessingID,Rslt);
		gSQLiteSummaries.EndExperiment(gExperimentID);
		}
	gStopWatch.Stop();
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Exit code: %d Total processing time: %s",Rslt,gStopWatch.Read());
	return(Rslt);
	}
else
	{
    printf("\n%s %s %s, Version %s\n", gszProcName,gpszSubProcess->pszName,gpszSubProcess->pszFullDescr,cpszProgVer);
	arg_print_errors(stdout,end,gszProcName);
	arg_print_syntax(stdout,argtable,"\nUse '-h' to view option and parameter usage\n");
	return(1);
	}
return 0;
}
예제 #13
0
파일: kangax.cpp 프로젝트: ste69r/Biokanga
int kangax(int argc, char* argv[])
{
// determine my process name
_splitpath(argv[0],NULL,NULL,gszProcName,NULL);
#else
int
kangax(int argc, char** argv)
{
// determine my process name
CUtility::splitpath((char *)argv[0],NULL,gszProcName);
#endif
int iScreenLogLevel;		// level of screen diagnostics
int iFileLogLevel;			// level of file diagnostics
char szLogFile[_MAX_PATH];	// write diagnostics to this file

int Rslt;

char szOutputFileSpec[_MAX_PATH];
int MinSeqLen;								// only accept for indexing sequences which are at least this length
int SimGenomeSize;							// if 1..1000 then simulating indexing of a genome of this size in Gbp.
int NumInputFileSpecs;						// number of input file specs
char *pszInputFileSpecs[cMaxInFileSpecs];	// input files
char szDescription[cMBSFFileDescrLen];
char szTitle[cMBSFShortFileDescrLen];
char szRefSpecies[cMaxDatasetSpeciesChrom];
int iMode;									// processing mode
bool bSOLiD;								// colorspace (SOLiD) generation
int NumberOfProcessors;						// number of installed CPUs
int NumThreads;								// number of threads (0 defaults to number of CPUs)


char szSQLiteDatabase[_MAX_PATH];	// results summaries to this SQLite file
char szExperimentName[cMaxDatasetSpeciesChrom+1];			// experiment name
char szExperimentDescr[1000];		// describes experiment

// command line args
struct arg_lit  *help    = arg_lit0("hH","help",                "print this help and exit");
struct arg_lit  *version = arg_lit0("v","version,ver",			"print version information and exit");
struct arg_int *FileLogLevel=arg_int0("f", "FileLogLevel",		"<int>","Level of diagnostics written to logfile 0=fatal,1=errors,2=info,3=diagnostics,4=debug");
struct arg_file *LogFile = arg_file0("F","log","<file>",		"diagnostics log file");

struct arg_int *Mode=arg_int0("m", "mode",	"<int>",			"Processing mode, 0=standard, 1=bisulphite index, 2=simulated genome (default 0)");
struct arg_lit  *solid = arg_lit0("C","colorspace",             "Generate for colorspace (SOLiD)");
struct arg_int *simgenomesize=arg_int0("s", "simgenomesize",	"<int>","Simulated genome size in Gbp (default 5, range 1..1000");

struct arg_int *minseqlen=arg_int0("l", "minseqlen",			"<int>","Do not accept for indexing sequences less than this length (default 50, range 1..1000000)");

struct arg_file *infiles = arg_filen("i",NULL,"<file>",0,cMaxInFileSpecs,	"input from wildcarded kangas or fasta files");
struct arg_file *OutFile = arg_file0("o",NULL,"<file>",			"output suffix array file");
struct arg_str *Descr = arg_str0("d","descr","<string>",		"full description");
struct arg_str *Title = arg_str0("t","title","<string>",		"short title");
struct arg_str *RefSpecies = arg_str1("r","ref","<string>",		"reference species");
struct arg_int *threads = arg_int0("T","threads","<int>",		"number of processing threads 0..128 (defaults to 0 which sets threads to number of CPU cores)");
struct arg_file *summrslts = arg_file0("q","sumrslts","<file>",		"Output results summary to this SQLite3 database file");
struct arg_str *experimentname = arg_str0("w","experimentname","<str>",		"experiment name SQLite3 database file");
struct arg_str *experimentdescr = arg_str0("W","experimentdescr","<str>",	"experiment description SQLite3 database file");
struct arg_end *end = arg_end(200);

void *argtable[] = {help,version,FileLogLevel,LogFile,
					summrslts,experimentname,experimentdescr,
					Mode,minseqlen,simgenomesize,solid,infiles,OutFile,RefSpecies,Descr,Title,
					threads,end};

char **pAllArgs;
int argerrors;
argerrors = CUtility::arg_parsefromfile(argc,(char **)argv,&pAllArgs);
if(argerrors >= 0)
	argerrors = arg_parse(argerrors,pAllArgs,argtable);

/* special case: '--help' takes precedence over error reporting */
if (help->count > 0)
        {
		printf("\n%s %s %s, Version %s\nOptions ---\n", gszProcName,gpszSubProcess->pszName,gpszSubProcess->pszFullDescr,cpszProgVer);
        arg_print_syntax(stdout,argtable,"\n");
        arg_print_glossary(stdout,argtable,"  %-25s %s\n");
		printf("\nNote: Parameters can be entered into a parameter file, one parameter per line.");
		printf("\n      To invoke this parameter file then precede its name with '@'");
		printf("\n      e.g. %s %s @myparams.txt\n",gszProcName,gpszSubProcess->pszName);
		printf("\nPlease report any issues regarding usage of %s at https://github.com/csiro-crop-informatics/biokanga/issues\n\n",gszProcName);
		return(1);
        }

    /* special case: '--version' takes precedence error reporting */
if (version->count > 0)
        {
		printf("\n%s %s Version %s\n",gszProcName,gpszSubProcess->pszName,cpszProgVer);
		return(1);
        }

if (!argerrors)
	{
	if(FileLogLevel->count && !LogFile->count)
		{
		printf("\nError: FileLogLevel '-f%d' specified but no logfile '-F<logfile>'",FileLogLevel->ival[0]);
		exit(1);
		}

	iScreenLogLevel = iFileLogLevel = FileLogLevel->count ? FileLogLevel->ival[0] : eDLInfo;
	if(iFileLogLevel < eDLNone || iFileLogLevel > eDLDebug)
		{
		printf("\nError: FileLogLevel '-l%d' specified outside of range %d..%d",iFileLogLevel,eDLNone,eDLDebug);
		exit(1);
		}
	if(LogFile->count)
		{
		strncpy(szLogFile,LogFile->filename[0],_MAX_PATH);
		szLogFile[_MAX_PATH-1] = '\0';
		}
	else
		{
		iFileLogLevel = eDLNone;
		szLogFile[0] = '\0';
		}
			// now that log parameters have been parsed then initialise diagnostics log system
	if(!gDiagnostics.Open(szLogFile,(etDiagLevel)iScreenLogLevel,(etDiagLevel)iFileLogLevel,true))
		{
		printf("\nError: Unable to start diagnostics subsystem\n");
		if(szLogFile[0] != '\0')
			printf(" Most likely cause is that logfile '%s' can't be opened/created\n",szLogFile);
		exit(1);
		}
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Subprocess %s Version %s starting",gpszSubProcess->pszName,cpszProgVer);
	gExperimentID = 0;
	gProcessID = 0;
	gProcessingID = 0;
	szSQLiteDatabase[0] = '\0';
	szExperimentName[0] = '\0';
	szExperimentDescr[0] = '\0';

	if(experimentname->count)
		{
		strncpy(szExperimentName,experimentname->sval[0],sizeof(szExperimentName));
		szExperimentName[sizeof(szExperimentName)-1] = '\0';
		CUtility::TrimQuotedWhitespcExtd(szExperimentName);
		CUtility::ReduceWhitespace(szExperimentName);
		}
	else
		szExperimentName[0] = '\0';

	MinSeqLen = 0;
	gExperimentID = 0;
	gProcessID = 0;
	gProcessingID = 0;
	szSQLiteDatabase[0] = '\0';
	szExperimentDescr[0] = '\0';
	if(summrslts->count)
		{
		strncpy(szSQLiteDatabase,summrslts->filename[0],sizeof(szSQLiteDatabase)-1);
		szSQLiteDatabase[sizeof(szSQLiteDatabase)-1] = '\0';
		CUtility::TrimQuotedWhitespcExtd(szSQLiteDatabase);
		if(strlen(szSQLiteDatabase) < 1)
			{
			gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: After removal of whitespace, no SQLite database specified with '-q<filespec>' option");
			return(1);
			}

		if(strlen(szExperimentName) < 1)
			{
			gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: After removal of whitespace, no SQLite experiment name specified with '-w<str>' option");
			return(1);
			}
		if(experimentdescr->count)
			{
			strncpy(szExperimentDescr,experimentdescr->sval[0],sizeof(szExperimentDescr)-1);
			szExperimentDescr[sizeof(szExperimentDescr)-1] = '\0';
			CUtility::TrimQuotedWhitespcExtd(szExperimentDescr);
			}
		if(strlen(szExperimentDescr) < 1)
			{
			gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: After removal of whitespace, no SQLite experiment description specified with '-W<str>' option");
			return(1);
			}

		gExperimentID = gSQLiteSummaries.StartExperiment(szSQLiteDatabase,false,true,szExperimentName,szExperimentName,szExperimentDescr);
		if(gExperimentID < 1)
			return(1);
		gProcessID = gSQLiteSummaries.AddProcess((char *)gpszSubProcess->pszName,(char *)gpszSubProcess->pszName,(char *)gpszSubProcess->pszFullDescr);
		if(gProcessID < 1)
			return(1);
		gProcessingID = gSQLiteSummaries.StartProcessing(gExperimentID,gProcessID,(char *)cpszProgVer);
		if(gProcessingID < 1)
			return(1);
		gDiagnostics.DiagOut(eDLInfo,gszProcName,"Initialised SQLite database '%s' for results summary collection",szSQLiteDatabase);
		gDiagnostics.DiagOut(eDLInfo,gszProcName,"SQLite database experiment identifier for '%s' is %d",szExperimentName,gExperimentID);
		gDiagnostics.DiagOut(eDLInfo,gszProcName,"SQLite database process identifier for '%s' is %d",(char *)gpszSubProcess->pszName,gProcessID);
		gDiagnostics.DiagOut(eDLInfo,gszProcName,"SQLite database processing instance identifier is %d",gProcessingID);
		}
	else
		{
		szSQLiteDatabase[0] = '\0';
		szExperimentDescr[0] = '\0';
		}

	iMode = Mode->count ? Mode->ival[0] : 0;
	if(iMode < 0 || iMode > 2)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: processing mode '-m%d' must be specified in range %d..%d",iMode,0,1);
		exit(1);
		}

	if(iMode == 2)
		{
		SimGenomeSize = simgenomesize->count ? simgenomesize->ival[0] : 5;
		if(SimGenomeSize < 1 || iMode > cMaxSimGenomeGbp)
			{
			gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: simulated genome size in Gbp '-s%d' must be specified in range 1..%d",SimGenomeSize,cMaxSimGenomeGbp);
			exit(1);
			}
		}
	else
		SimGenomeSize = 0;

	bSOLiD = solid->count ? true : false;

	int Idx;

	if(iMode != 2)
		{
		MinSeqLen = minseqlen->count ? minseqlen->ival[0] : 50;
		if(MinSeqLen < 1)
			MinSeqLen = 1;
		else
			if(MinSeqLen > 1000000)
				MinSeqLen = 1000000;

		for(NumInputFileSpecs=Idx=0;NumInputFileSpecs < cMaxInFileSpecs && Idx < infiles->count; Idx++)
			{
			pszInputFileSpecs[Idx] = NULL;
			if(pszInputFileSpecs[NumInputFileSpecs] == NULL)
				pszInputFileSpecs[NumInputFileSpecs] = new char [_MAX_PATH];
			strncpy(pszInputFileSpecs[NumInputFileSpecs],infiles->filename[Idx],_MAX_PATH);
			pszInputFileSpecs[NumInputFileSpecs][_MAX_PATH-1] = '\0';
			CUtility::TrimQuotedWhitespcExtd(pszInputFileSpecs[NumInputFileSpecs]);
			if(pszInputFileSpecs[NumInputFileSpecs][0] != '\0')
				NumInputFileSpecs++;
			}

		if(!NumInputFileSpecs)
			{
			gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: After removal of whitespace, no input file(s) specified with '-i<filespec>' option)\n");
			exit(1);
			}
		}
	else
		{
		NumInputFileSpecs = 0;
		pszInputFileSpecs[0] = NULL;
		}

	if(OutFile->count)
		{
		strcpy(szOutputFileSpec,OutFile->filename[0]);
		CUtility::TrimQuotedWhitespcExtd(szOutputFileSpec);
		}
	else
		szOutputFileSpec[0] = '\0';

	if(iMode != 2 && szOutputFileSpec[0] == '\0')
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: no output file(s) specified with '-o<filespec>' option)\n");
		exit(1);
		}

	strncpy(szRefSpecies,RefSpecies->sval[0],cMaxDatasetSpeciesChrom);
	szRefSpecies[cMaxDatasetSpeciesChrom-1] = '\0';

	if(!Title->count)
		strcpy(szTitle,szRefSpecies);
	else
		{
		strncpy(szTitle,Title->sval[0],cMBSFShortFileDescrLen);
		szTitle[cMBSFShortFileDescrLen-1] = '\0';
		}

	if(!Descr->count)
		strcpy(szDescription,szRefSpecies);
	else
		{
		strncpy(szDescription,Descr->sval[0],cMBSFFileDescrLen);
		szDescription[cMBSFFileDescrLen-1] = '\0';
		}

// show user current resource limits
#ifndef _WIN32
	gDiagnostics.DiagOut(eDLInfo, gszProcName, "Resources: %s",CUtility::ReportResourceLimits());
#endif

	int AvailGBMemory;
#ifdef _WIN32
	SYSTEM_INFO SystemInfo;
	GetSystemInfo(&SystemInfo);
	NumberOfProcessors = SystemInfo.dwNumberOfProcessors;

	MEMORYSTATUSEX status;
	status.dwLength = sizeof(status);
	GlobalMemoryStatusEx(&status);
	AvailGBMemory = (int)(status.ullTotalPhys / 0x040000000);	// set to be gigabytes
#else
	NumberOfProcessors = sysconf(_SC_NPROCESSORS_CONF);

	long pages = sysconf(_SC_PHYS_PAGES);
	long page_size = sysconf(_SC_PAGE_SIZE);
	AvailGBMemory = (int)(((INT64)pages * (INT64)page_size)/0x040000000);
#endif

	int MaxAllowedThreads = min(cMaxWorkerThreads,NumberOfProcessors);	// limit to be at most cMaxWorkerThreads
	if((NumThreads = threads->count ? threads->ival[0] : MaxAllowedThreads)==0)
		NumThreads = MaxAllowedThreads;
	if(NumThreads < 0 || NumThreads > MaxAllowedThreads)
		{
		gDiagnostics.DiagOut(eDLWarn,gszProcName,"Warning: Number of threads '-T%d' specified was outside of range %d..%d",NumThreads,1,MaxAllowedThreads);
		gDiagnostics.DiagOut(eDLWarn,gszProcName,"Warning: Defaulting number of threads to %d",MaxAllowedThreads);
		NumThreads = MaxAllowedThreads;
		}


	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Processing parameters:");
	if(iMode == 2)
		{
		gDiagnostics.DiagOutMsgOnly(eDLInfo,"Simulating indexing of a genome of size: %dGbp",SimGenomeSize);
		if(AvailGBMemory < (SimGenomeSize * 7))		// allowing for 6 bytes per base plus overheads
			gDiagnostics.DiagOutMsgOnly(eDLWarn,"May be memory allocation problems when loading or indexing this simulated genome, available memory: %dGB",AvailGBMemory);
		}

	if(bSOLiD)
		gDiagnostics.DiagOutMsgOnly(eDLInfo,"Process for colorspace (SOLiD)");

	if(iMode != 2)
		{
		gDiagnostics.DiagOutMsgOnly(eDLInfo,"Accepting for indexing sequences of length at least: %dbp",MinSeqLen);
		gDiagnostics.DiagOutMsgOnly(eDLInfo,"Process input files as: '%s'",iMode == 0 ? "standard" : "bisulphite");
		for(Idx=0; Idx < NumInputFileSpecs; Idx++)
			gDiagnostics.DiagOutMsgOnly(eDLInfo,"Input source file spec: '%s'",pszInputFileSpecs[Idx]);
		}

	if(szOutputFileSpec[0] != '\0')
		gDiagnostics.DiagOutMsgOnly(eDLInfo,"Output to suffix array file: '%s'",szOutputFileSpec);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Reference species: '%s'",szRefSpecies);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Title text: '%s'",szTitle);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Descriptive text: '%s'",szDescription);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Number of threads : %d",NumThreads);

	if(szExperimentName[0] != '\0')
		gDiagnostics.DiagOutMsgOnly(eDLInfo,"This processing reference: %s",szExperimentName);

#ifdef _WIN32
	SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS);
#endif
	gStopWatch.Start();
	Rslt = CreateBioseqSuffixFile(iMode,MinSeqLen,SimGenomeSize,NumThreads,bSOLiD,NumInputFileSpecs,pszInputFileSpecs,szOutputFileSpec,szRefSpecies,szDescription,szTitle);
	Rslt = Rslt >=0 ? 0 : 1;
	if(gExperimentID > 0)
		{
		if(gProcessingID)
			gSQLiteSummaries.EndProcessing(gProcessingID,Rslt);
		gSQLiteSummaries.EndExperiment(gExperimentID);
		}
	gStopWatch.Stop();
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Exit code: %d Total processing time: %s",Rslt,gStopWatch.Read());
	exit(Rslt);
	}
else
	{
    printf("\n%s %s %s, Version %s\n", gszProcName,gpszSubProcess->pszName,gpszSubProcess->pszFullDescr,cpszProgVer);
	arg_print_errors(stdout,end,gszProcName);
	arg_print_syntax(stdout,argtable,"\nUse '-h' to view option and parameter usage\n");
	exit(1);
	}
}
예제 #14
0
파일: main.c 프로젝트: makestuff/bulk
int main(int argc, char *argv[]) {
	struct arg_str *vpOpt    = arg_str1("v", "vidpid", "<VID:PID>", " vendor ID and product ID (e.g 04B4:8613)");
	struct arg_uint *toOpt = arg_uint0("t", "timeout", "<millis>", " timeout in milliseconds");
	struct arg_int  *epOpt   = arg_int0("e", "endpoint", "<epNum>", " endpoint to write to");
	struct arg_lit  *benOpt  = arg_lit0("b", "benchmark", "        benchmark the operation");
	struct arg_lit  *chkOpt  = arg_lit0("c", "checksum", "         print 16-bit checksum");
	struct arg_lit  *helpOpt = arg_lit0("h", "help", "             print this help and exit\n");
	struct arg_file *fileOpt = arg_file1(NULL, NULL, "<fileName>", "             the data to send");
	struct arg_end  *endOpt  = arg_end(20);
	void* argTable[] = {vpOpt, toOpt, epOpt, benOpt, chkOpt, helpOpt, fileOpt, endOpt};
	const char *progName = "bulk";
	int numErrors;
	uint8 epNum = 0x06;
	FILE *inFile = NULL;
	uint8 *buffer = NULL;
	uint32 fileLen;
	struct USBDevice *deviceHandle = NULL;
	USBStatus uStatus;
	int retVal = 0;
	const char *error = NULL;
	double totalTime, speed;
	uint16 checksum = 0x0000;
	uint32 timeout = 5000;
	uint32 i;
	#ifdef WIN32
		LARGE_INTEGER tvStart, tvEnd, freq;
		DWORD_PTR mask = 1;
		SetThreadAffinityMask(GetCurrentThread(), mask);
		QueryPerformanceFrequency(&freq);
	#else
		struct timeval tvStart, tvEnd;
		long long startTime, endTime;
	#endif

	if ( arg_nullcheck(argTable) != 0 ) {
		printf("%s: insufficient memory\n", progName);
		FAIL(1, cleanup);
	}

	numErrors = arg_parse(argc, argv, argTable);
	if ( helpOpt->count > 0 ) {
		printf("Bulk Write Tool Copyright (C) 2009-2011 Chris McClelland\n\nUsage: %s", progName);
		arg_print_syntax(stdout, argTable, "\n");
		printf("\nWrite data to a bulk endpoint.\n\n");
		arg_print_glossary(stdout, argTable,"  %-10s %s\n");
		FAIL(0, cleanup);
	}

	if ( numErrors > 0 ) {
		arg_print_errors(stdout, endOpt, progName);
		printf("Try '%s --help' for more information.\n", progName);
		FAIL(2, cleanup);
	}

	if ( toOpt->count ) {
		timeout = toOpt->ival[0];
	}

	inFile = fopen(fileOpt->filename[0], "rb");
	if ( !inFile ) {
		fprintf(stderr, "Unable to open file %s\n", fileOpt->filename[0]);
		FAIL(3, cleanup);
	}

	fseek(inFile, 0, SEEK_END);
	fileLen = (uint32)ftell(inFile);
	fseek(inFile, 0, SEEK_SET);

	buffer = (uint8 *)malloc(fileLen);
	if ( !buffer ) {
		fprintf(stderr, "Unable to allocate memory for file %s\n", fileOpt->filename[0]);
		FAIL(4, cleanup);
	}

	if ( fread(buffer, 1, fileLen, inFile) != fileLen ) {
		fprintf(stderr, "Unable to read file %s\n", fileOpt->filename[0]);
		FAIL(5, cleanup);
	}

	if ( chkOpt->count ) {
		for ( i = 0; i < fileLen; i++  ) {
			checksum = (uint16)(checksum + buffer[i]);
		}
		printf("Checksum: 0x%04X\n", checksum);
	}

	if ( epOpt->count ) {
		epNum = (uint8)epOpt->ival[0];
	}

	uStatus = usbInitialise(0, &error);
	CHECK_STATUS(uStatus, 6, cleanup);
	uStatus = usbOpenDevice(vpOpt->sval[0], 1, 0, 0, &deviceHandle, &error);
	CHECK_STATUS(uStatus, 7, cleanup);

	#ifdef WIN32
		QueryPerformanceCounter(&tvStart);
		uStatus = usbBulkWrite(deviceHandle, epNum, buffer, fileLen, timeout, &error);
		QueryPerformanceCounter(&tvEnd);
		CHECK_STATUS(uStatus, 8, cleanup);
		totalTime = (double)(tvEnd.QuadPart - tvStart.QuadPart);
		totalTime /= freq.QuadPart;
		printf("Time: %fms\n", totalTime/1000.0);
		speed = (double)fileLen / (1024*1024*totalTime);
	#else
		gettimeofday(&tvStart, NULL);
		uStatus = usbBulkWrite(deviceHandle, epNum, buffer, fileLen, timeout, &error);
		gettimeofday(&tvEnd, NULL);
		CHECK_STATUS(uStatus, 8, cleanup);
		startTime = tvStart.tv_sec;
		startTime *= 1000000;
		startTime += tvStart.tv_usec;
		endTime = tvEnd.tv_sec;
		endTime *= 1000000;
		endTime += tvEnd.tv_usec;
		totalTime = (double)(endTime - startTime);
		totalTime /= 1000000;  // convert from uS to S.
		speed = (double)fileLen / (1024*1024*totalTime);
	#endif
	if ( benOpt->count ) {
		printf("Speed: %f MB/s\n", speed);
	}

cleanup:
	if ( buffer ) {
		free(buffer);
	}
	if ( inFile ) {
		fclose(inFile);
	}
	if ( deviceHandle ) {
		usbCloseDevice(deviceHandle, 0);
	}
	if ( error ) {
		fprintf(stderr, "%s\n", error);
		usbFreeError(error);
	}
	arg_freetable(argTable, sizeof(argTable)/sizeof(argTable[0]));
	return retVal;
}
void processArgs(int argc, char **argv) {
  int nerrors, i;
  char *savptr, str[1024], *str1, machName[1024], sessIDstr[1024];

  struct arg_str *arg_sessionID     = arg_str1(  "S",    "sessionID",    "<mach.sessionID>", "session ID of run to be processed\n");
  struct arg_str *arg_propIDs       = arg_str0(  "P",    "proposals", "<int [,int [,int]]>", "quoted string of proposal numbers to use\n");
  struct arg_str *arg_skipDays      = arg_str0(  "D",         "days",    "<skip [,length]>", "skip days at start, do length days after\n");
  struct arg_lit *arg_Check         = arg_lit0( NULL,     "checkobs",                        "check observations for basic errors\n");
  struct arg_lit *arg_TimeSummary   = arg_lit0( NULL,  "timesummary",                        "time summary");
  struct arg_lit *arg_PeriodSearch  = arg_lit0( NULL, "periodsearch",                        "make periodogram plots\n");
  struct arg_lit *arg_Hourglass     = arg_lit0(  "H",    "hourglass",                        "make hourglass plot\n");
  struct arg_lit *arg_Opposition    = arg_lit0( NULL,   "opposition",                        "make solar angle (opposition) plot\n");
  struct arg_str *arg_Airmass       = arg_str0( NULL,      "airmass",               "<int>", "make per-field airmass plot (0 is max, 1 is median)\n");
  struct arg_lit *arg_SixVisits     = arg_lit0(  "V",  "sixvisitnum",                        "make all-filter visit numbers plot\n");
  struct arg_lit *arg_5sigma	    = arg_lit0(  "V",  "5sigma",                             "make aitoff plot for median 5sigma also per proposal\n");
  struct arg_lit *arg_skyb          = arg_lit0(  "V",  "skyb",                               "make aitoff plot for median skyb also per proposal\n");
  struct arg_lit *arg_seeing        = arg_lit0(  "V",  "seeing",                             "make aitoff plot for median seeing also per proposal\n");
  struct arg_lit *arg_Visits        = arg_lit0(  "v",     "visitnum",                        "make visit numbers plot for specified filters\n \
                                                (requires -f|--filters)\n");
  struct arg_str *arg_reqFilters    = arg_str0(  "f",      "filters",       "<f [,f [,f]]>", "which filters to use; f in {ugrizy}\n");
  struct arg_lit *arg_NEOrevisits   = arg_lit0(  "R",     "revisits",                        "make NEO revisit numbers plot\n");
  struct arg_lit *arg_Slew          = arg_lit0( NULL,         "slew",                        "make slew time histogram\n");
  struct arg_lit *arg_SNtiming      = arg_lit0( NULL,     "sntiming",                        "make SN Ia cadence plots\n");
  struct arg_file *arg_plotfileRoot = arg_file0(NULL,     "plotfile",        "harcopy file", "root name of plotfile for hardcopy\n");
  struct arg_file *arg_plotTitle    = arg_file0(NULL,    "plottitle",            "<string>", "title for plots\n");
  struct arg_lit *arg_help          = arg_lit0(  "h",         "help",                        "show usage\n");
  struct arg_lit *arg_debug         = arg_lit0(  "d",        "debug",                        "debugging output\n");
  struct arg_str *arg_hostname      = arg_str1(  "N",     "hostname",            "<string>", "if you know hostname \n");
  struct arg_str *arg_databasename  = arg_str1(  "DB",     "database",            "<string>", "if you know the db name \n");
  struct arg_str *arg_designstretch = arg_str1( NULL,     "designstretch",         "<int>", "design or stretch value\n");
  struct arg_end *arg_endp          = arg_end(20);

  void *argtable[] = {arg_sessionID, arg_propIDs,      arg_skipDays,    arg_TimeSummary, arg_Check,     arg_PeriodSearch,
                      arg_Hourglass, arg_Opposition,   arg_Airmass,     arg_SixVisits, arg_5sigma, arg_skyb, arg_seeing, 
                      arg_Slew, arg_Visits, arg_reqFilters,   arg_NEOrevisits, arg_SNtiming,  arg_plotfileRoot,
                      arg_plotTitle, arg_debug, arg_help, arg_hostname, arg_designstretch, arg_databasename, arg_endp};


  if (arg_nullcheck(argtable) != 0) fprintf(stderr, "error: insufficient memory\n");

  nerrors = arg_parse(argc,argv,argtable);

  // process arguments

  // render assistance when asked
  if(arg_help->count>0) {
    fprintf(stderr,"Usage: %s [options]\n     where [options] are:\n\n",argv[0]);
    arg_print_glossary(stderr, argtable, "%-45s  %s");
    //    arg_print_syntaxv(stderr, argtable, "\n");
    exit(1);
  }

  // list errors
  if (nerrors > 0) {
    arg_print_errors(stdout,arg_endp,argv[0]);
    fprintf(stderr,"\nUsage: %s [options]\n     where [options] are:\n\n",argv[0]);
    arg_print_glossary(stderr, argtable, "%-45s  %s");
    //    arg_print_syntaxv(stderr, argtable, "\n");
    exit(1);
  }

  // set database tableName and sessionID from sessionID argument
  //strcpy(str, *arg_sessionID->sval);
  //strcpy(machName, strtok_r(str,".",&savptr));
  //strcpy(sessIDstr, strtok_r(NULL,".",&savptr));
  strcpy(sessIDstr, *arg_sessionID->sval);
  sessionID = atoi(sessIDstr);

  if ( *arg_databasename->sval == NULL ) {
	sprintf(database, "%s", "OpsimDB");
  } else {
	sprintf(database, "%s", *arg_databasename->sval);
  }

  if ( *arg_hostname->sval == NULL ) {
	if ( gethostname(identifier, identifier_length) == 0 ) {
		sprintf(hostname, "%s", identifier);
	} else {
		printf( "Hostname : %s\n", strerror(errno));
		exit(1);
	}
  } else {
	sprintf (hostname, "%s", *arg_hostname->sval);
  }
  sprintf(tableName, "output_%s_%d", hostname, sessionID);
  // set action flags

  if(arg_5sigma->count>0) do5sigma=1;
  if(arg_skyb->count>0) doskyb=1;
  if(arg_seeing->count>0) doSeeing=1;
  if(arg_TimeSummary->count>0) doTimeSummary=1;
  if(arg_Check->count>0) doCheck=1;
  if(arg_PeriodSearch->count>0) doPeriodSearch=1;
  if(arg_Hourglass->count>0) doHourglass=1;
  if(arg_Opposition->count>0) doOpposition=1;
  if(arg_designstretch->count>0) {
	if ( strcmp(*arg_designstretch->sval, "0") == 0) {
		useDesignStretch = 0;
	} else {
		useDesignStretch = 1;
    }
  } 
  if(arg_Airmass->count>0) {
    doAirmass=1;
    if(strcmp(*arg_Airmass->sval, "0") != 0) {
	useMaxAirmass=0; 
    }
    else  {
	useMaxAirmass=1;
    }	
  }
  if(arg_SixVisits->count>0) doSixVisits=1;
  if(arg_Visits->count>0) {
    doVisits=1;
    if(arg_reqFilters->count==0) {
      fprintf(stderr,"Error: with -v|--visitsnum must give -f|--filters\n");
      exit(1);
    }
    strcpy(str, *arg_reqFilters->sval);
    i = 0;
    strcpy(desiredFilters[i],strtok_r(str," ,",&savptr));
    i++;
    while((str1=strtok_r(NULL," ,",&savptr))!= NULL) {
      strcpy(desiredFilters[i],str1);
      i++;
    }
    ndesiredFilters = i;
  }
  if(arg_NEOrevisits->count>0) doNEOrevisits=1;
  if(arg_SNtiming->count>0) doSNtiming=1;
  if(arg_Slew->count>0) doSlew=1;
  if(arg_propIDs->count>0) {
    strcpy(str, *arg_propIDs->sval);
    i = 0;
    propIDs[i] = atoi(strtok_r(str," ,",&savptr));
    i++;
    while((str1=strtok_r(NULL," ,",&savptr))!= NULL) {
      propIDs[i] = atoi(str1);
      i++;
    }
    nIDs = i;
  }
  if(arg_plotfileRoot->count>0) {
    strcpy(plotfileRoot,arg_plotfileRoot->filename[0]);
    doHardcopy = 1;
  }
  if(arg_plotTitle->count>0) {
    strcpy(plotTitle,arg_plotTitle->filename[0]);
  }
  if(arg_skipDays->count>0) {
    strcpy(str, *arg_skipDays->sval);
    skipDays = atoi(strtok_r(str," ,",&savptr));
    str1 = strtok_r(NULL," ,",&savptr);
    if(str1 != (char *) NULL) lengthDays = atoi(str1);    
  }
  if(arg_debug->count>0) {
    debug = 1;
  }

#if 0
  printf("     sessionID: %d\n", sessionID);
  printf("      skipDays: %d\n", skipDays);
  printf("    lengthDays: %d\n", lengthDays);
  printf("          nIDs: %d\n", nIDs);
  if(nIDs>0) {
    printf("     using IDs: ");  for(i=0; i<nIDs; i++) printf(" %d",propIDs[i]); printf("\n");
  }

  printf("       doCheck: %d\n", doCheck);
  printf("doPeriodSearch: %d\n", doPeriodSearch);
  printf("   doHourglass: %d\n", doHourglass);
  printf("   doOpposition: %d\n", doOpposition);
  printf("   doSixVisits: %d\n", doSixVisits);
  printf("      doVisits: %d\n", doVisits);
  if(doVisits) {
    printf(" using filters: "); for(i=0; i<ndesiredFilters; i++) printf(" %s",desiredFilters[i]); printf("\n");
  }
  printf(" doNEOrevisits: %d\n", doNEOrevisits);
  printf("    doSNtiming: %d\n", doSNtiming);
  if(strlen(plotfileRoot)>0) printf(" hardcopy file: \"%s\"\n", plotfileRoot);
  if(strlen(plotTitle)>0) printf("    plot title: \"%s\"\n", plotTitle);
  printf("         debug: %d\n", debug);
#endif

  arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0]));
}
int main(int argc, char* argv[]) {

    double discountFactor = 0.9;

    FILE* initFileFd = NULL;
    double* setPoints = NULL;
    FILE* results = NULL;
    char str[1024];
    unsigned int i = 0;
    unsigned int nbSetPoints = 0;
    unsigned int* ns = NULL;
    unsigned int nbN = 0;
    unsigned int* hs = NULL;
    unsigned int nbH = 0;
    unsigned int nbSteps = 0;
    unsigned int timestamp = time(NULL);
    int readFscanf = -1;

    struct arg_file* initFile = arg_file1(NULL, "init", "<file>", "File containing the set points");
    struct arg_int* s = arg_int1("s", NULL, "<n>", "Number of steps");
    struct arg_str* r = arg_str1("n", NULL, "<s>", "List of ressources");
    struct arg_str* z = arg_str1("h", NULL, "<s>", "List of length for the sequences");
    struct arg_file* where = arg_file1(NULL, "where", "<file>", "Directory where we save the outputs");
    struct arg_end* end = arg_end(6);

    int nerrors = 0;
    void* argtable[6];

    argtable[0] = initFile;
    argtable[1] = r;
    argtable[2] = s;
    argtable[3] = z;
    argtable[4] = where;
    argtable[5] = end;

    if(arg_nullcheck(argtable) != 0) {
        printf("error: insufficient memory\n");
        arg_freetable(argtable, 6);
        return EXIT_FAILURE;
    }

    nerrors = arg_parse(argc, argv, argtable);

    if(nerrors > 0) {
        printf("%s:", argv[0]);
        arg_print_syntax(stdout, argtable, "\n");
        arg_print_errors(stdout, end, argv[0]);
        arg_freetable(argtable, 6);
        return EXIT_FAILURE;
    }

    initGenerativeModelParameters();
    initGenerativeModel();

    initFileFd = fopen(initFile->filename[0], "r");
    readFscanf = fscanf(initFileFd, "%u\n", &nbSetPoints);
    setPoints = (double*)malloc(sizeof(double) * nbSetPoints);
    
    for(; i < nbSetPoints; i++) {
        readFscanf = fscanf(initFileFd, "%s\n", str);
        setPoints[i] = strtod(str, NULL);
    }
    fclose(initFileFd);

    nbSteps = s->ival[0];
    hs = parseUnsignedIntList((char*)z->sval[0], &nbH);
    ns = parseUnsignedIntList((char*)r->sval[0], &nbN);

    sprintf(str, "%s/%u_results_%s_%s.csv", where->filename[0], timestamp, z->sval[0], r->sval[0]);
    results = fopen(str, "w");

    for(i = 0; i < nbN; i++) {                                          /* Loop on the computational ressources */
        printf("Starting with %u computational ressources\n", ns[i]);
        fprintf(results, "%u", ns[i]);
        fflush(NULL);
        unsigned int j = 0;
        for(; j < nbH; j++) {                                           /* Loop on the length of the sequences */
            unsigned int k = 0;
            state* crt1 = initState();
            state* crt2 = copyState(crt1);
            double averages[2] = {0.0,0.0};
            for(; k < nbSetPoints; k++) {                           /* Loop on the initial states */
                unsigned int l = 0;
                parameters[10] = setPoints[k];

                for(; l < nbSteps; l++) {                               /* Loop on the step */
                    char isTerminal = 0;
                    double reward = 0.0;
                    state* nextState = NULL;
                    sequential_direct_instance* sequential_direct = sequential_direct_initInstance(crt1, discountFactor, hs[j],1);

                    double* optimalAction = sequential_direct_planning(sequential_direct, ns[i]);
                    isTerminal = nextStateReward(crt1, optimalAction, &nextState, &reward) < 0 ? 1 : 0;
                    freeState(crt1);
                    crt1 = nextState;
                    averages[0] += reward;
                    sequential_direct_uninitInstance(&sequential_direct);
                    if(isTerminal)
                        break;
                }
                printf("direct: %u set point done for h=%u\n", k, hs[j]);
                fflush(NULL);

                for(l = 0; l < nbSteps; l++) {                               /* Loop on the step */
                    char isTerminal = 0;
                    double reward = 0.0;
                    state* nextState = NULL;
                    sequential_soo_instance* sequential_soo = sequential_soo_initInstance(crt2, discountFactor, hs[j],1);

                    double* optimalAction = sequential_soo_planning(sequential_soo, ns[i]);
                    isTerminal = nextStateReward(crt2, optimalAction, &nextState, &reward);
                    freeState(crt2);
                    crt2 = nextState;
                    averages[1] += reward;
                    sequential_soo_uninitInstance(&sequential_soo);
                    if(isTerminal)
                        break;
                }
                printf("soo: %u set point done for h=%u\n", k, hs[j]);
                fflush(NULL);
            }
            freeState(crt1);
            freeState(crt2);
            averages[0] = averages[0] /(double)nbSetPoints;
            averages[1] = averages[1] /(double)nbSetPoints;
            printf("Computation with h=%u and n=%u done\n", hs[j], ns[i]);
            fprintf(results, ",%.15f,%.15f", averages[0],averages[1]);
            fflush(NULL);
        }
        printf("Computation with %u computational ressources done\n\n", ns[i]);
        fprintf(results, "\n");
        fflush(NULL);
    }

    fclose(results);

    arg_freetable(argtable, 6);

    free(setPoints);

    freeGenerativeModel();
    freeGenerativeModelParameters();

    return EXIT_SUCCESS;

}
예제 #17
0
파일: main.c 프로젝트: Billbocquet/z-cloud
int main(int argc, char **argv)
{
	const char* progname = "z-connector";

    struct arg_file *device = arg_file1("dD", "device", NULL, "path to the serial port of Z-Wave dongle");
    struct arg_str *server = arg_str1("sS", "server", NULL, "IP address or host name to connect to");
    struct arg_int *port = arg_int0("pP", "port", NULL, "port number (defaults to 9087)");
	struct arg_file *cert = arg_file0(NULL, "cert", NULL, "personal certificate");
	struct arg_file *key = arg_file0(NULL, "key", NULL, "personal certificate key");
	struct arg_file *cacert = arg_file0(NULL, "cacert", NULL, "CA certificate");
	struct arg_file *log = arg_file0("lL", "log", NULL, "file to write log to (defaults to stdout)");
	struct arg_lit *debug = arg_lit0(NULL, "debug", "log debugging information");
    struct arg_lit *help = arg_lit0("h", "help", "print this help and exit");
    struct arg_end *end = arg_end(20);

	void* argTable[] = {device, server, port, cert, key, cacert, log, debug, help, end};

#ifdef WIN32
	WSADATA wsa;
	WORD wsaVersion = MAKEWORD(2, 2);
	int wsaError;
	DWORD win32err;
#endif

	int retCode, nErrors;

	if (arg_nullcheck(argTable) != 0)
	{
        printf("%s: insufficient memory\n", progname);

		CLEAN_RETURN(1);
    }

	nErrors = arg_parse(argc, argv, argTable);

    if (IS_ARG_SET(help))
    {
        printf("Usage: %s", progname);
        arg_print_syntax(stdout, argTable, "\n");
        //printf("Print certain system information.  With no options, same as -s.\n\n");
        arg_print_glossary(stdout, argTable,"  %-25s %s\n");
        printf("\nReport bugs to <*****@*****.**>.\n");

        CLEAN_RETURN(0);
    }

	LogLevel = (IS_ARG_SET(debug)) ? 3 : 2;

    if (nErrors > 0)
	{
        arg_print_errors(stdout, end, progname);
        printf("Try '%s --help' for more information.\n", progname);

        CLEAN_RETURN(2);
    }

#ifdef WIN32
	hStoppingEvent = CreateEvent(NULL, TRUE, FALSE, "Local\\Z-Agent-Stop");
	if (hStoppingEvent == NULL)
	{
		win32err = GetLastError();
		if (win32err == ERROR_INVALID_HANDLE)
		{
			printf("Another instance is already running\n");

			CLEAN_RETURN(0);
		}
		else
		{
			printf("Failed to create synchronization event: %d\n", win32err);

			CLEAN_RETURN(3);
		}
	}

	wsaError = WSAStartup(wsaVersion, &wsa);
	if (wsaError != 0)
	{
		printf("WSA Startup failed with code %d\n", wsaError);

		CloseHandle(hStoppingEvent);
		CLEAN_RETURN(3);
	}

	if (wsa.wVersion != wsaVersion)
	{
		printf("Required WSA version not found\n");

		CloseHandle(hStoppingEvent);
		CLEAN_RETURN(3);
	}
#endif

	retCode = main_impl(device->filename[0], 
						server->sval[0], SAFE_INT(port, 9087),
						SAFE_FILE(cert, ""), SAFE_FILE(key, ""), SAFE_FILE(cacert, ""), 
						SAFE_FILE(log, "-"));

#ifdef WIN32
	WSACleanup();

	CloseHandle(hStoppingEvent);
#endif

	CLEAN_RETURN(retCode);
}
예제 #18
0
int main(int argc, char* argv[])
{
    int nerrors, w;
    bstring temp = NULL;
    const char* warnprefix = "no-";
    bool expect_failure;
    
    // Define arguments.
    struct arg_lit* show_help = arg_lit0("h", "help", "Show this help.");
    struct arg_lit* expect_failure_lit = arg_lit0("f", "fail", "Expect failure during preprocessing.");
    struct arg_str* input_lang = arg_str1(NULL, NULL, "<lang>", "The input language.");
    struct arg_file* input_file = arg_file1(NULL, NULL, "<file>", "The input preprocessor file.");
    struct arg_lit* verbose = arg_litn("v", NULL, 0, LEVEL_EVERYTHING - LEVEL_DEFAULT, "Increase verbosity.");
    struct arg_lit* quiet = arg_litn("q", NULL,  0, LEVEL_DEFAULT - LEVEL_SILENT, "Decrease verbosity.");
    struct arg_end* end = arg_end(20);
    void* argtable[] = { show_help, verbose, quiet, expect_failure_lit, input_lang, input_file, end };
    
    // Parse arguments.
    nerrors = arg_parse(argc, argv, argtable);

    if (nerrors != 0 || show_help->count != 0)
    {
        if (nerrors != 0)
            arg_print_errors(stdout, end, "libdcpu-pp test suite");

        printd(LEVEL_DEFAULT, "syntax:\n    dtasm");
        arg_print_syntax(stderr, argtable, "\n");
        printd(LEVEL_DEFAULT, "options:\n");
        arg_print_glossary(stderr, argtable, "    %-25s %s\n");
        if (show_help->count == 2)
        {
            printd(LEVEL_DEFAULT, "defined warnings:\n");
            for (w = 0; w < _WARN_COUNT; w++)
                printd(LEVEL_DEFAULT, "      %s\n", dwarnpolicy[w].name);
        }
        arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
        return 1;
    }
    
    // Set failure expectation variable.
    expect_failure = (expect_failure_lit->count > 0);

    // Set verbosity level.
    debug_setlevel(LEVEL_DEFAULT + verbose->count - quiet->count);

    // Set global path variable.
    osutil_setarg0(bautofree(bfromcstr(argv[0])));

    // Set up error handling.
    if (dsethalt())
    {
        // Handle the error.
        dautohandle();
        printd(LEVEL_ERROR, "libdcpu-pp test suite: error occurred.\n");

        if (temp != NULL)
            pp_cleanup(bautofree(temp));

        arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
        if (expect_failure)
            return 0;
        else
            return 1;
    }
    
    // Perform preprocessing.
    ppfind_add_autopath(bautofree(bfromcstr(input_file->filename[0])));
    temp = pp_do(
        bautofree(bfromcstr(input_lang->sval[0])),
        bautofree(bfromcstr(input_file->filename[0]))
    );
    
    // Perform parsing.
    test_success = true;
    yyin = fopen(temp->data, "r");
    yyout = NULL;
    yyparse();
    fclose(yyin);
    
    // Cleanup.
    pp_cleanup(bautofree(temp));
    
    if (test_success && expect_failure)
        return 1;
    else if (test_success && !expect_failure)
        return 0;
    else if (!test_success && expect_failure)
        return 0;
    else
        return 1;
}
예제 #19
0
int main(int argc, char* argv[])
{
    CURL* curl;
    bstring command;
    bstring name;
    bstring modpath;
    int all;

    // Define arguments.
    struct arg_lit* show_help = arg_lit0("h", "help", "Show this help.");
    struct arg_str* cmdopt = arg_str1(NULL, NULL, "<command>", "The command; either 'search', 'install', 'uninstall', 'enable' or 'disable'.");
    struct arg_str* nameopt = arg_str0(NULL, NULL, "<name>", "The name of the module to search for, install, uninstall, enable or disable.");
    struct arg_lit* all_flag = arg_lit0("a", "all", "Apply this command to all available / installed modules.");
    struct arg_lit* verbose = arg_litn("v", NULL, 0, LEVEL_EVERYTHING - LEVEL_DEFAULT, "Increase verbosity.");
    struct arg_lit* quiet = arg_litn("q", NULL,  0, LEVEL_DEFAULT - LEVEL_SILENT, "Decrease verbosity.");
    struct arg_end* end = arg_end(20);
    void* argtable[] = { show_help, cmdopt, all_flag, nameopt, verbose, quiet, end };

    // Parse arguments.
    int nerrors = arg_parse(argc, argv, argtable);

    if (nerrors != 0 || show_help->count != 0 || (all_flag->count == 0 && nameopt->count == 0))
    {
        if (all_flag->count == 0 && nameopt->count == 0)
            printd(LEVEL_ERROR, "error: must have either module name or -a.");
        if (show_help->count != 0)
            arg_print_errors(stderr, end, "mm");

        fprintf(stderr, "syntax:\n    dtmm");
        arg_print_syntax(stderr, argtable, "\n");
        fprintf(stderr, "options:\n");
        arg_print_glossary(stderr, argtable, "    %-25s %s\n");
        arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
        return 1;
    }

    // Set verbosity level.
    debug_setlevel(LEVEL_DEFAULT + verbose->count - quiet->count);
    
    // Show version information.
    version_print(bautofree(bfromcstr("Module Manager")));

    // Set argument 0 and convert parameters.
    osutil_setarg0(bautofree(bfromcstr(argv[0])));
    command = bfromcstr(cmdopt->sval[0]);
    name = bfromcstr(nameopt->sval[0]);

    // Initialize curl or exit.
    curl = curl_easy_init();
    if (!curl)
    {
        printd(LEVEL_ERROR, "unable to initialize curl.\n");
        return 1;
    }

    // Ensure module path exists.
    modpath = osutil_getmodulepath();
    if (modpath == NULL)
    {
        printd(LEVEL_ERROR, "module path does not exist (searched TOOLCHAIN_MODULES and modules/).\n");
        return 1;
    }
    bdestroy(modpath);

    // Convert all flag.
    all = (all_flag->count > 0);

    // If all is set, set the name back to "".
    if (all)
        bassigncstr(name, "");

    // If the name is "all" or "*", handle this as the all
    // boolean flag.
    if (biseqcstr(name, "all") || biseqcstr(name, "*"))
    {
        bassigncstr(name, "");
        all = 1;
        printd(LEVEL_WARNING, "treating name as -a (all) flag");
    }

    if (biseqcstrcaseless(command, "search") || biseqcstrcaseless(command, "se"))
        return do_search(curl, name, all);
    else if (biseqcstrcaseless(command, "install") || biseqcstrcaseless(command, "in"))
    {
        if (all)
            return do_install_all(curl);
        else
            return do_install(curl, name);
    }
    else if (biseqcstrcaseless(command, "uninstall") || biseqcstrcaseless(command, "rm"))
    {
        if (all)
            return do_uninstall_all(curl);
        else
            return do_uninstall(curl, name);
    }
    else if (biseqcstrcaseless(command, "enable") || biseqcstrcaseless(command, "en"))
    {
        if (all)
            return do_enable_all(curl);
        else
            return do_enable(curl, name);
    }
    else if (biseqcstrcaseless(command, "disable") || biseqcstrcaseless(command, "di") || biseqcstrcaseless(command, "dis"))
    {
        if (all)
            return do_disable_all(curl);
        else
            return do_disable(curl, name);
    }
    else
    {
        printd(LEVEL_ERROR, "unknown command (must be search, install, uninstall, enable or disable).");
        return 1;
    }

    return 0;
}
예제 #20
0
파일: client.c 프로젝트: chiefdome/telex
int main(int argc, char *argv[])
{	
	struct arg_int *lport = arg_int0("p", "port", "<localport>",  "listening port (default is 8888)");
	struct arg_int *debug = arg_int0("d", "debug",  "<level>", "debug output level (default is 4)");	
#ifdef PUBKEY_DATA_
	struct arg_str *key   = arg_str0("k", "key",    "<keyfile>", "public key file (default is built-in)");
#else
	struct arg_str *key   = arg_str0("k", "key",    "<keyfile>", "public key file (default is pubkey)");
#endif
#ifdef ROOTPEM_DATA_
	struct arg_str *certdb= arg_str0(NULL, "certdb",    "<certfile>", "trusted CA database (default is built-in)");
#else
	struct arg_str *certdb= arg_str0(NULL, "certdb",    "<certfile>", "trusted CA database (default is root.pem)");
#endif
	struct arg_lit *help  = arg_lit0(NULL,"help",              "print this help and exit");
	struct arg_str *host  = arg_str1(NULL, NULL,    "<host>[:port]",  "non-blocked TLS server");
	struct arg_end *end   = arg_end(20);
	void *argtable[] = {lport, debug, key, certdb, help, host, end};
	const char* progname = "telex-client";
    int nerrors;
    int ret=0;
    assert(!arg_nullcheck(argtable));

	// defaults:
	lport->ival[0] = 8888;
	debug->ival[0] = 3;
#ifdef PUBKEY_DATA_
	key->sval[0] = NULL;
#else
	key->sval[0] = "pubkey";
#endif
#ifdef ROOTPEM_DATA_
	certdb->sval[0] = NULL;
#else
	certdb->sval[0] = "root.pem";
#endif

	nerrors = arg_parse(argc,argv,argtable);
    if (help->count > 0) {
		printf("Usage: %s", progname);
        arg_print_syntax(stdout,argtable,"\n");
        printf("\nEstablishes covert, encrypted tunnels, disguised as connections to <host>.\n\n");
        arg_print_glossary(stdout,argtable,"  %-25s %s\n");
        printf("\n");		
		ret = 0;
	} else if (nerrors > 0) {
		arg_print_errors(stdout,end,progname);
		printf("Try '%s --help' for more information.\n", progname);
		ret = 1;
	} else if (argc == 1) {
        printf("Try '%s --help' for more information.\n", progname);
        ret = 0;
	} else {		

      int port = 443;
      char hstr[255];
      assert(host->sval[0]);
      strncpy(hstr, host->sval[0], sizeof(hstr)-1);

      char *pstr=0;
      strtok(hstr, ":");
      pstr = strtok(NULL, ":");
      if (pstr) {
	port = strtol(pstr, NULL, 10);
	if (port < 1 || port > 65535) {
	  fprintf(stderr, "Invalid remote port: %d", port);
	  return 1;
	}
      }

		printf("WARNING: This software is an experimental prototype intended for\n");
        printf("         researchers. It does not provide strong security and is\n");
        printf("         UNSAFE FOR REAL-WORLD USE. For details of current limitations\n");
        printf("         of our proof-of-concept, please see telex-client/ISSUES.\n");

      ret = telex_client(lport->ival[0], port, debug->ival[0], hstr, key->sval[0], certdb->sval[0]);
    }
    arg_freetable(argtable, sizeof(argtable)/sizeof(argtable[0]));
    return ret;
}
예제 #21
0
int main(int argc, char **argv)
    {
    /* SYNTAX 1: insert [-nvR] <file> [file]...  -o <file> */
    struct arg_rex  *cmd1     = arg_rex1(NULL,  NULL,  "insert", NULL, REG_ICASE, NULL);
    struct arg_lit  *noact1   = arg_lit0("n",   NULL,  "take no action");
    struct arg_lit  *verbose1 = arg_lit0("v", "verbose", "verbose messages");
    struct arg_lit  *recurse1 = arg_lit0("R",   NULL,  "recurse through subdirectories");
    struct arg_file *infiles1 = arg_filen(NULL, NULL,  NULL, 1,argc+2, "input file(s)");
    struct arg_file *outfile1 = arg_file0("o",  NULL,  "<output>", "output file (default is \"-\")");
    struct arg_end  *end1     = arg_end(20);
    void* argtable1[] = {cmd1,noact1,verbose1,recurse1,infiles1,outfile1,end1};
    int nerrors1;

    /* SYNTAX 2: remove [-nv] <file> */
    struct arg_rex  *cmd2     = arg_rex1(NULL, NULL, "remove", NULL, REG_ICASE, NULL);
    struct arg_lit  *noact2   = arg_lit0("n",  NULL, NULL);
    struct arg_lit  *verbose2 = arg_lit0("v",  "verbose", NULL);
    struct arg_file *infiles2 = arg_file1(NULL, NULL, NULL, NULL);
    struct arg_end  *end2     = arg_end(20);
    void* argtable2[] = {cmd2,noact2,verbose2,infiles2,end2};
    int nerrors2;

    /* SYNTAX 3: search [-v] <pattern> [-o <file>] [--help] [--version] */
    struct arg_rex  *cmd3     = arg_rex1(NULL, NULL, "search", NULL, REG_ICASE, NULL);
    struct arg_lit  *verbose3 = arg_lit0("v",  "verbose", NULL);
    struct arg_str  *pattern3 = arg_str1(NULL, NULL, "<pattern>", "search string");
    struct arg_file *outfile3 = arg_file0("o", NULL, "<output>", NULL);
    struct arg_end  *end3     = arg_end(20);
    void* argtable3[] = {cmd3,verbose3,pattern3,outfile3,end3};
    int nerrors3;

    /* SYNTAX 4: [-help] [-version] */
    struct arg_lit  *help4    = arg_lit0(NULL,"help",     "print this help and exit");
    struct arg_lit  *version4 = arg_lit0(NULL,"version",  "print version information and exit");
    struct arg_end  *end4     = arg_end(20);
    void* argtable4[] = {help4,version4,end4};
    int nerrors4;

    const char* progname = "multisyntax";
    int exitcode=0;

    /* verify all argtable[] entries were allocated sucessfully */
    if (arg_nullcheck(argtable1)!=0 ||
        arg_nullcheck(argtable2)!=0 ||
        arg_nullcheck(argtable3)!=0 ||
        arg_nullcheck(argtable4)!=0 )
        {
        /* NULL entries were detected, some allocations must have failed */
        printf("%s: insufficient memory\n",progname);
        exitcode=1;
        goto exit;
        }

    /* set any command line default values prior to parsing */
    outfile1->filename[0]="-";
    outfile3->filename[0]="-";

    /* Above we defined a separate argtable for each possible command line syntax */
    /* and here we parse each one in turn to see if any of them are successful    */
    nerrors1 = arg_parse(argc,argv,argtable1);
    nerrors2 = arg_parse(argc,argv,argtable2);
    nerrors3 = arg_parse(argc,argv,argtable3);
    nerrors4 = arg_parse(argc,argv,argtable4);

    /* Execute the appropriate main<n> routine for the matching command line syntax */
    /* In this example program our alternate command line syntaxes are mutually     */
    /* exclusive, so we know in advance that only one of them can be successful.    */
    if (nerrors1==0)
        exitcode = mymain1(noact1->count, verbose1->count, recurse1->count,
                           outfile1->filename[0], infiles1->filename, infiles1->count);
    else if (nerrors2==0)
        exitcode = mymain2(noact2->count, verbose2->count, infiles2->filename[0]);
    else if (nerrors3==0)
        exitcode = mymain3(verbose3->count, pattern3->sval[0], outfile3->filename[0]);
    else if (nerrors4==0)
        exitcode = mymain4(help4->count, version4->count, progname,
                           argtable1, argtable2, argtable3, argtable4);
    else
        {
        /* We get here if the command line matched none of the possible syntaxes */
        if (cmd1->count > 0)
            {
            /* here the cmd1 argument was correct, so presume syntax 1 was intended target */ 
            arg_print_errors(stdout,end1,progname);
            printf("usage: %s ", progname);
            arg_print_syntax(stdout,argtable1,"\n");
            }
        else if (cmd2->count > 0)
            {
            /* here the cmd2 argument was correct, so presume syntax 2 was intended target */ 
            arg_print_errors(stdout,end2,progname);
            printf("usage: %s ", progname);
            arg_print_syntax(stdout,argtable2,"\n");
            }
        else if (cmd3->count > 0)
            {
            /* here the cmd3 argument was correct, so presume syntax 3 was intended target */ 
            arg_print_errors(stdout,end3,progname);
            printf("usage: %s ", progname);
            arg_print_syntax(stdout,argtable3,"\n");
            }
        else
            {
            /* no correct cmd literals were given, so we cant presume which syntax was intended */
            printf("%s: missing <insert|remove|search> command.\n",progname); 
            printf("usage 1: %s ", progname);  arg_print_syntax(stdout,argtable1,"\n");
            printf("usage 2: %s ", progname);  arg_print_syntax(stdout,argtable2,"\n");
            printf("usage 3: %s ", progname);  arg_print_syntax(stdout,argtable3,"\n");
            printf("usage 4: %s",  progname);  arg_print_syntax(stdout,argtable4,"\n");
            }
        }

exit:
    /* deallocate each non-null entry in each argtable */
    arg_freetable(argtable1,sizeof(argtable1)/sizeof(argtable1[0]));
    arg_freetable(argtable2,sizeof(argtable2)/sizeof(argtable2[0]));
    arg_freetable(argtable3,sizeof(argtable3)/sizeof(argtable3[0]));
    arg_freetable(argtable4,sizeof(argtable4)/sizeof(argtable4[0]));

    return exitcode;
    }
예제 #22
0
void conf_configure_app(configuration_ctx_t* ctx) {
    struct arg_lit* help = arg_lit0(OPT_HELP_SHORT, OPT_HELP_LONG, OPT_HELP_DESCR);
    struct arg_lit* helpF = arg_lit0(OPT_HELP_SHORT, OPT_HELP_LONG, OPT_HELP_DESCR);
    struct arg_lit* helpS = arg_lit0(OPT_HELP_SHORT, OPT_HELP_LONG, OPT_HELP_DESCR);
    
    struct arg_lit* grep = arg_lit0(OPT_GREP_SHORT, OPT_GREP_LONG, OPT_GREP_DESCR);
    struct arg_lit* grepF = arg_lit0(OPT_GREP_SHORT, OPT_GREP_LONG, OPT_GREP_DESCR);
    struct arg_lit* grepS = arg_lit0(OPT_GREP_SHORT, OPT_GREP_LONG, OPT_GREP_DESCR);

    struct arg_str* string = arg_str1(OPT_STR_SHORT, OPT_STR_LONG, NULL, OPT_STR_DESCR);
    struct arg_str* stringG = arg_str0(OPT_STR_SHORT, OPT_STR_LONG, NULL, OPT_STR_DESCR);
    struct arg_file* file = arg_file1(OPT_FILE_SHORT, OPT_FILE_LONG, NULL, OPT_FILE_DESCR);
    struct arg_file* fileG = arg_file0(OPT_FILE_SHORT, OPT_FILE_LONG, NULL, OPT_FILE_DESCR);

    struct arg_str* macro = arg_str1(OPT_MACRO_SHORT, OPT_MACRO_LONG, NULL, OPT_MACRO_DESCR);
    struct arg_str* macroS = arg_str1(OPT_MACRO_SHORT, OPT_MACRO_LONG, NULL, OPT_MACRO_DESCR);
    struct arg_str* macroF = arg_str1(OPT_MACRO_SHORT, OPT_MACRO_LONG, NULL, OPT_MACRO_DESCR);

    struct arg_file* files = arg_filen(OPT_F_SHORT, OPT_F_LONG, NULL, 1, ctx->argc + 2, OPT_F_DESCR);
    struct arg_file* filesS = arg_filen(OPT_F_SHORT, OPT_F_LONG, NULL, 1, ctx->argc + 2, OPT_F_DESCR);
    struct arg_file* filesF = arg_filen(OPT_F_SHORT, OPT_F_LONG, NULL, 1, ctx->argc + 2, OPT_F_DESCR);

    struct arg_end* end = arg_end(10);
    struct arg_end* endF = arg_end(10);
    struct arg_end* endS = arg_end(10);

    void* argtable[] = {help, grep, stringG, fileG, macro, files, end};
    void* argtableF[] = {helpF, grepF, file, macroF, filesF, endF};
    void* argtableS[] = {helpS, grepS, string, macroS, filesS, endS};

    if(arg_nullcheck(argtable) != 0 || arg_nullcheck(argtableF) != 0 || arg_nullcheck(argtableS) != 0) {
        prconf_print_syntax(argtable, argtableS, argtableF);
        goto cleanup;
    }

    int nerrors = arg_parse(ctx->argc, ctx->argv, argtable);
    int nerrorsF = arg_parse(ctx->argc, ctx->argv, argtableF);
    int nerrorsS = arg_parse(ctx->argc, ctx->argv, argtableS);

    if(nerrors > 0 || help->count > 0) {
        prconf_print_syntax(argtable, argtableS, argtableF);
        if(help->count == 0 && ctx->argc > 1) {
            arg_print_errors(stdout, end, PROGRAM_NAME);
        }
        goto cleanup;
    }

    if(nerrorsS == 0) {
        ctx->on_string(filesS, macroS->sval[0], string->sval[0], grepS->count > 0);
    }
    else if(nerrorsF == 0) {
        ctx->on_file(filesS, macroF->sval[0], file->filename[0], grepF->count > 0);
    }
    else {
        prconf_print_syntax(argtable, argtableS, argtableF);
        arg_print_errors(stdout, endF, PROGRAM_NAME);
        arg_print_errors(stdout, endS, PROGRAM_NAME);
    }

cleanup:
    arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
    arg_freetable(argtableS, sizeof(argtableS) / sizeof(argtableS[0]));
    arg_freetable(argtableF, sizeof(argtableF) / sizeof(argtableF[0]));
}
int GRTCLCrackCommandLineData::ParseCommandLine(int argc, char *argv[]) {
    int deviceCount, i;

    std::vector<std::string> webTableFilenames;

    // Command line argument parsing with argtable
    struct arg_lit *verbose = arg_lit0("v", "verbose", "verbose output");
    struct arg_lit *silent = arg_lit0(NULL, "silent", "silence all output");

    // Table related options
    struct arg_file *table_file = arg_filen(NULL,NULL,"<file>", 0, 10000, "GRT Tables to use");

    struct arg_file *hash_file = arg_file0("f","hashfile","<file>", "Hashfile to use");

    struct arg_str *hash_value = arg_str0("s", "hashstring", "hashstring", "The hash string");
    struct arg_str *hash_type = arg_str1("h", "hashtype", "{NTLM, MD4, MD5, SHA1}", "hash type to crack");

    // CUDA related params
    struct arg_int *device = arg_int0("d", "device", "<n>", "OpenCL device to use");
    struct arg_int *platform = arg_int0("p", "platform", "<n>", "OpenCL platform to use");
    struct arg_int *m = arg_int0("m", "ms", "<n>", "target step time in ms");
    struct arg_int *blocks = arg_int0("b", "blocks", "<n>", "number of thread blocks to run");
    struct arg_int *threads = arg_int0("t", "threads", "<n>", "number of threads per block");
    struct arg_lit *zerocopy = arg_lit0("z", "zerocopy", "use zerocopy memory");
    struct arg_file *o = arg_file0("o", "outputfile", "outputfile", "output file for results");
    // hexoutput: Adds hex output to all password outputs.
    struct arg_lit *hex_output = arg_lit0(NULL, "hexoutput", "Adds hex output to all hash outputs");

    struct arg_lit *amd_kernels = arg_lit0(NULL, "amd", "use AMD vector kernels");
    struct arg_int *vector_width = arg_int0(NULL, "vectorwidth", "<n>", "vector width");

    struct arg_lit *debug = arg_lit0(NULL, "debug", "Use debug display class");
    struct arg_lit *devdebug = arg_lit0(NULL, "devdebug", "Developer debugging output");
    struct arg_str *debugfiles = arg_str0(NULL, "debugdumpfiles", "<filename>", "Filename base to dump candidates and chains to");

    struct arg_int *prefetch_count = arg_int0(NULL, "prefetch", "<n>", "number of prefetch threads");
    struct arg_int *candidates_to_skip = arg_int0(NULL, "skip", "<n>", "number of candidate hashes to skip");

    struct arg_str *table_url = arg_str0(NULL, "tableurl", "<URL>", "URL of the web table script");
    struct arg_str *table_username = arg_str0(NULL, "tableusername", "<username>", "Username, if required, for the web table script");
    struct arg_str *table_password = arg_str0(NULL, "tablepassword", "<password>", "Password, if required, for the web table script");


    struct arg_end *end = arg_end(20);
    void *argtable[] = {verbose,silent,table_file,hash_value,hash_file,hash_type,
        device,platform,m,blocks,threads,zerocopy,o,amd_kernels,vector_width,
        debug, devdebug, prefetch_count,table_url,table_username,table_password,
        candidates_to_skip,debugfiles,hex_output,end};

    // Get arguments, collect data, check for basic errors.
    if (arg_nullcheck(argtable) != 0) {
      printf("error: insufficient memory\n");
    }
    // Look for errors
    int nerrors = arg_parse(argc,argv,argtable);
    if (nerrors > 0) {
      // Print errors, exit.
      arg_print_errors(stdout,end,argv[0]);
      //arg_print_syntax(stdout,argtable,"\n\n");
      printf("\n\nOptions: \n");
      arg_print_glossary(stdout,argtable,"  %-20s %s\n");
      exit(1);
    }

    // Verbose & silent
    if (verbose->count) {
        this->Verbose = 1;
    }
    if (silent->count) {
        this->Silent = 1;
    }
    if (zerocopy->count) {
        this->CUDAUseZeroCopy = 1;
    }
    if (debug->count) {
        this->Debug = 1;
    }
    if (devdebug->count) {
        this->Debug = 1;
        this->DeveloperDebug = 1;
    }
    if (debugfiles->count) {
        this->DebugDump = 1;
        this->DebugDumpFilenameBase = *debugfiles->sval;
    }
    if (prefetch_count->count) {
        this->NumberPrefetchThreads = *prefetch_count->ival;
    }
    if (candidates_to_skip->count) {
            this->CandidateHashesToSkip = *candidates_to_skip->ival;
    }

    // Web table stuff
    if (table_url->count) {
        this->useWebTable = 1;
        this->tableURL = *table_url->sval;
            // If someone has NOT specified the candidates to skip, set to default.
            if (!candidates_to_skip->count) {
                    this->CandidateHashesToSkip = DEFAULT_CANDIDATES_TO_SKIP;
            }
    }
    if (table_username->count) {
        this->tableUsername = *table_username->sval;
    }
    if (table_password->count) {
        this->tablePassword = *table_password->sval;
    }

    this->HashType = this->GRTHashTypes->GetHashIdFromString(*hash_type->sval);
    if (this->HashType == -1) {
        printf("Unknown hash type %s: Exiting.\n\n", *hash_type->sval);
        exit(1);
    }
    
    int correct_length = this->GRTHashTypes->GetHashLengthFromId(this->HashType);
    // if we know the correct length, we make sure the hash is the correct length
    if (correct_length != 0) {
        if ((hash_value->count) && (strlen(*hash_value->sval) != correct_length)) {
            printf("Hash string is not %d hex characters. Exiting.\n\n", correct_length);
            exit(1);
        }
    }

    if (hash_value->count) {
        convertAsciiToBinary(*hash_value->sval, this->Hash, 16);
    } else if (hash_file->count) {
        this->hashFileName = hash_file->filename[0];
        this->useHashFile = 1;
    } else {
        printf("Must provide a hash value or a hash file!\n");
        exit(1);
    }

    if (o->count) {
        this->outputHashFileName = o->filename[0];
        this->useOutputHashFile = 1;
    }

    // Desired kernel time
    if (m->count) {
        this->KernelTimeMs = *m->ival;
    }

    // Do this to emulate CUDA behavior for now...
    // Threads - if not set, leave at default 0
    if (threads->count) {
        this->OpenCLWorkitems = *threads->ival;
    }

    // Blocks - if not set, leave at default 0
    if (blocks->count) {
        this->OpenCLWorkgroups = *blocks->ival * this->OpenCLWorkitems;
    }

    if (hex_output->count) {
        this->AddHexOutput = 1;
    }

    // Allocate space for the list of pointers

    // Create the table header type
    if (this->useWebTable) {
        this->TableHeader = new GRTTableHeaderVWeb();
        this->TableHeader->setWebURL(this->tableURL);
        this->TableHeader->setWebUsername(this->tableUsername);
        this->TableHeader->setWebPassword(this->tablePassword);

        GRTTableHeaderVWeb *WebTableHeader =
                (GRTTableHeaderVWeb *)this->TableHeader;
        webTableFilenames = WebTableHeader->getHashesFromServerByType(this->HashType);

    } else {
        // V1 will work for both V1 & V2 types
        this->TableHeader = new GRTTableHeaderV1();
    }


    // If we don't have any table filenames, get the ones from the web.
    // Note: The script ONLY reutrns valid tables.
    if ((table_file->count == 0) && this->useWebTable) {
        this->Table_File_Count = webTableFilenames.size();
        this->Table_Filenames = (char **)malloc(this->Table_File_Count * sizeof(char *));
        for (i = 0; i < this->Table_File_Count; i++) {
            // Increment size by 1 for null termination
            this->Table_Filenames[i] = (char *)malloc((webTableFilenames.at(i).size() + 1) * sizeof(char));
            strcpy(this->Table_Filenames[i], webTableFilenames.at(i).c_str());
        }
    } else {
        this->Table_File_Count = table_file->count;
        this->Table_Filenames = (char **)malloc(this->Table_File_Count * sizeof(char *));
        // Handle the file list sanely
        for (i = 0; i < table_file->count; i++) {
            // Check to ensure the file is valid
            if (!this->TableHeader->isValidTable(table_file->filename[i], -1)) {
                printf("%s is not a valid GRT table!  Exiting.\n", table_file->filename[i]);
                exit(1);
            }
            // Check to ensure the file is of the right type
            if (!this->TableHeader->isValidTable(table_file->filename[i], this->HashType)) {
                printf("%s is not a valid %s GRT table!\n", table_file->filename[i],
                        this->GRTHashTypes->GetHashStringFromId(this->HashType));
                exit(1);
            }

            // Increment size by 1 for null termination
            this->Table_Filenames[i] = (char *)malloc((strlen(table_file->filename[i]) + 1) * sizeof(char));
            strcpy(this->Table_Filenames[i], table_file->filename[i]);
        }
    }


    // Finally, set the CUDA device and look for errors.
    if (device->count) {
        this->OpenCLDevice = *device->ival;
    }
    if (platform->count) {
        this->OpenCLPlatform = *platform->ival;
    }

    if (amd_kernels->count) {
        this->useAmdKernels = 1;
        this->vectorWidth = 4;
    }

    if (vector_width->count) {
        this->vectorWidth = *vector_width->ival;
    }
}
예제 #24
0
int _tmain(int argc, char* argv[])
{
// determine my process name
_splitpath(argv[0],NULL,NULL,gszProcName,NULL);
#else
int 
main(int argc, const char** argv)
{
// determine my process name
CUtility::splitpath((char *)argv[0],NULL,gszProcName);
#endif
int iScreenLogLevel;		// level of screen diagnostics
int iFileLogLevel;			// level of file diagnostics
char szLogFile[_MAX_PATH];	// write diagnostics to this file

int Rslt;
int iProcMode;
int iMinLength;
int iMaxLength;

int iMinMergeLength;
int iMaxMergeLength;

char szRefFile[_MAX_PATH];	// process ref hypers from this file
char szRelFile[_MAX_PATH];	// process rel hypers from this file
char szOutLociFile[_MAX_PATH];	// write loci to this file

char szRefSpecies[cMaxDatasetSpeciesChrom];	// use this species as the ref species in generated szOutLociFile
char szRelSpecies[cMaxDatasetSpeciesChrom];	// use this species/list as the rel species in generated szOutLociFile
char szElType[cMaxDatasetSpeciesChrom];		// use this as the element type in generated szOutLociFile

int iRefExtend;			// extend ref element lengths left+right by this many bases
int iRelExtend;			// extend rel element lengths left+right by this many bases
int iJoinDistance;		// if > 0 then join elements which only differ by at most this distance beween end of element i and start of element i+1


// command line args
struct arg_lit  *help    = arg_lit0("h","help",                 "print this help and exit");
struct arg_lit  *version = arg_lit0("v","version,ver",			"print version information and exit");
struct arg_int *FileLogLevel=arg_int0("f", "FileLogLevel",		"<int>","Level of diagnostics written to screen and logfile 0=fatal,1=errors,2=info,3=diagnostics,4=debug");
struct arg_file *LogFile = arg_file0("F","log","<file>",		"diagnostics log file");

struct arg_file *RefFile = arg_file1("i","reffile","<file>",	"reference hyper element CSV file");
struct arg_file *RelFile = arg_file0("I","relfile","<file>",	"relative hyper element CSV file");
struct arg_file *OutLociFile = arg_file1("o",NULL,"<file>",		"output loci to file as CSV");

struct arg_str  *RefSpecies = arg_str1("r","refspecies","<string>","output loci file ref species");
struct arg_str  *RelSpecies = arg_str1("R","relspecies","<string>","output loci file rel species");
struct arg_str  *ElType = arg_str0("t","eltype","<string>","output loci file element type");

struct arg_int  *ProcMode = arg_int0("p","mode","<int>",		 "processing mode: 0:Intersect (Ref & Rel)\n\t\t1:Ref exclusive (Ref & !Rel)\n\t\t2:Rel exclusive (!Ref & Rel)\n\t\t3:Union (Ref | Rel)\n\t\t4:Neither (!(Ref | Rel))");
struct arg_int  *MinLength = arg_int0("l","minlength","<int>",   "minimum input ref/rel element length (default 4)");
struct arg_int  *MaxLength = arg_int0("L","maxlength","<int>",   "maximum input ref/rel element length (default 1000000)");

struct arg_int  *MinMergeLength = arg_int0("m","minmergelength","<int>","minimum merged output element length (default 4)");
struct arg_int  *MaxMergeLength = arg_int0("M","maxmergelength","<int>","maximum merged output element length (default 1000000)");

struct arg_int  *RefExtend = arg_int0("e","refextend","<int>",	 "extend ref element flanks left+right by this many bases (default 0)");
struct arg_int  *RelExtend = arg_int0("E","relextend","<int>",	 "extend rel element flanks left+right by this many bases (default 0)");

struct arg_int  *JoinDistance = arg_int0("j","join","<int>",     "merge output elements which are only separated by this number of bases (default 0)");

struct arg_end *end = arg_end(20);

void *argtable[] = {help,version,FileLogLevel,LogFile,
					ProcMode,
					RefFile,RelFile,OutLociFile,
					MinLength,MaxLength,RefExtend,RelExtend,JoinDistance,MinMergeLength,MaxMergeLength,
					RefSpecies,RelSpecies,ElType,
					end};

char **pAllArgs;
int argerrors;
argerrors = CUtility::arg_parsefromfile(argc,(char **)argv,&pAllArgs);
if(argerrors >= 0)
	argerrors = arg_parse(argerrors,pAllArgs,argtable);

    /* special case: '--help' takes precedence over error reporting */
if (help->count > 0)
        {
		printf("\n%s CSV Merge Elements, Version %s\nOptions ---\n", gszProcName,cpszProgVer);
        arg_print_syntax(stdout,argtable,"\n");
        arg_print_glossary(stdout,argtable,"  %-25s %s\n");
		printf("\nNote: Parameters can be entered into a parameter file, one parameter per line.");
		printf("\n      To invoke this parameter file then precede its name with '@'");
		printf("\n      e.g. %s @myparams.txt\n",gszProcName);
		printf("\nPlease report any issues regarding usage of %s at https://github.com/csiro-crop-informatics/biokanga/issues\n\n",gszProcName);
		exit(1);
        }

    /* special case: '--version' takes precedence error reporting */
if (version->count > 0)
        {
		printf("\n%s Version %s\n",gszProcName,cpszProgVer);
		exit(1);
        }
if (!argerrors)
	{
	if(FileLogLevel->count && !LogFile->count)
		{
		printf("\nError: FileLogLevel '-f%d' specified but no logfile '-F<logfile>'",FileLogLevel->ival[0]);
		exit(1);
		}

	iScreenLogLevel = iFileLogLevel = FileLogLevel->count ? FileLogLevel->ival[0] : eDLInfo;
	if(iFileLogLevel < eDLNone || iFileLogLevel > eDLDebug)
		{
		printf("\nError: FileLogLevel '-l%d' specified outside of range %d..%d",iFileLogLevel,eDLNone,eDLDebug);
		exit(1);
		}
	
	if(LogFile->count)
		{
		strncpy(szLogFile,LogFile->filename[0],_MAX_PATH);
		szLogFile[_MAX_PATH-1] = '\0';
		}
	else
		{
		iFileLogLevel = eDLNone;
		szLogFile[0] = '\0';
		}


	iProcMode = ProcMode->count ? ProcMode->ival[0] : ePMElIntersect;
	if(iProcMode < ePMElIntersect || iProcMode > ePMElRefNotRefRel)
		{
		printf("Error: Processing mode '-p%d' is not in range 0..4",iProcMode);
		exit(1);
		}

	strncpy(szOutLociFile,OutLociFile->filename[0],_MAX_PATH);
	szOutLociFile[_MAX_PATH-1] = '\0';

	strncpy(szRefSpecies,RefSpecies->sval[0],sizeof(szRefSpecies));
	szRefSpecies[sizeof(szRefSpecies)-1] = '\0';
	strncpy(szRelSpecies,RelSpecies->sval[0],sizeof(szRelSpecies));
	szRelSpecies[sizeof(szRelSpecies)-1] = '\0';
	if(ElType->count)
		{
		strncpy(szElType,ElType->sval[0],sizeof(szElType));
		szElType[sizeof(szElType)-1] = '\0';
		}
	else
		strcpy(szElType,"merged");

	iMinLength = MinLength->count ? MinLength->ival[0] : cDfltMinLength;
	if(iMinLength < 0 || iMinLength > cMaxLengthRange)
		{
		printf("Error: Minimum element length '-l%d' is not in range 0..%d",iMinLength,cMaxLengthRange);
		exit(1);
		}

	iMaxLength = MaxLength->count ? MaxLength->ival[0] : cDfltMaxLength;
	if(iMaxLength < iMinLength || iMaxLength > cMaxLengthRange)
		{
		printf("Error: Maximum element length '-L%d' is not in range %d..%d",iMaxLength,iMinLength,cMaxLengthRange);
		exit(1);
		}

	iMinMergeLength = MinMergeLength->count ? MinMergeLength->ival[0] : cDfltMinLength;
	if(iMinMergeLength < 0 || iMinMergeLength > cMaxLengthRange)
		{
		printf("Error: Minimum output merged element length '-m%d' is not in range 0..%d",iMinMergeLength,cMaxLengthRange);
		exit(1);
		}

	iMaxMergeLength = MaxMergeLength->count ? MaxMergeLength->ival[0] : cDfltMaxLength;
	if(iMaxMergeLength < iMinMergeLength || iMaxMergeLength > cMaxLengthRange)
		{
		printf("Error: Maximum element length '-M%d' is not in range %d..%d",iMaxMergeLength,iMinMergeLength,cMaxLengthRange);
		exit(1);
		}

	iJoinDistance = JoinDistance->count ? JoinDistance->ival[0] : cDfltJoinOverlap;
	if(iJoinDistance < 0 || iJoinDistance > cMaxJoinOverlap)
		{
		printf("Error: Join separation length '-j%d' is not in range %d..%d",iJoinDistance,0,cMaxJoinOverlap);
		exit(1);
		}

	iRefExtend = RefExtend->count ? RefExtend->ival[0] : 0;
	if(iRefExtend < (-1 * cMaxExtendLength) || iRefExtend > cMaxExtendLength)
		{
		printf("Error: Ref Extension length '-e%d' is not in range %d..%d",iRefExtend,(-1 * cMaxExtendLength),cMaxExtendLength);
		exit(1);
		}

	iRelExtend = RelExtend->count ? RelExtend->ival[0] : 0;
	if(iRelExtend < (-1 * cMaxExtendLength) || iRelExtend > cMaxExtendLength)
		{
		printf("Error: Rel Extension length '-E%d' is not in range %d..%d",iRelExtend,(-1 * cMaxExtendLength),cMaxExtendLength);
		exit(1);
		}


	strncpy(szRefFile,RefFile->filename[0],_MAX_PATH);
	szRefFile[_MAX_PATH-1] = '\0';

	if(RelFile->count)
		{
		strncpy(szRelFile,RelFile->filename[0],_MAX_PATH);
		szRelFile[_MAX_PATH-1] = '\0';
		}
	else
		{
		if(iProcMode == ePMElRefExclusive || iProcMode == ePMElRefRelUnion)
			szRelFile[0] = '\0';
		else
			{
			printf("Error: Rel loci file must be specified in processing mode '-p%d' (%s)",iProcMode,ProcMode2Txt((etProcMode)iProcMode));
			exit(1);
			}
		}

		// now that command parameters have been parsed then initialise diagnostics log system
	if(!gDiagnostics.Open(szLogFile,(etDiagLevel)iScreenLogLevel,(etDiagLevel)iFileLogLevel,true))
		{
		printf("\nError: Unable to start diagnostics subsystem.");
		if(szLogFile[0] != '\0')
			printf(" Most likely cause is that logfile '%s' can't be opened/created",szLogFile);
		exit(1);
		}
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Version: %s Processing parameters:",cpszProgVer);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Processing Mode: %d (%s)",iProcMode,ProcMode2Txt((etProcMode)iProcMode));
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Reference CSV file: '%s'",szRefFile);
	if(szRelFile[0] != '\0')
		gDiagnostics.DiagOutMsgOnly(eDLInfo,"Relative CSV file: '%s'",szRelFile);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Output processed loci into CSV file: '%s'",szOutLociFile);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Output loci file ref species: '%s'",szRefSpecies);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Output loci file rel species: '%s'",szRelSpecies);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Output loci file element type: '%s'",szElType);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Minimum input element length: %d",iMinLength);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Maximum input element length: %d",iMaxLength);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Ref element flank extension length: %d",iRefExtend);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Rel element flank extension length: %d",iRelExtend);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Merge output elements separated by at most this many bases: %d",iJoinDistance);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Minimum output merged element length: %d",iMinMergeLength);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Maximum output merged element length: %d",iMaxMergeLength);


	// processing here...
	gStopWatch.Start();
#ifdef _WIN32
	SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS);
#endif	
	Rslt = Process((etProcMode)iProcMode,iMinLength,iMaxLength,iRefExtend,iRelExtend,iJoinDistance,iMinMergeLength,iMaxMergeLength,szRefFile,szRelFile,szOutLociFile,
		szRefSpecies,szRelSpecies,szElType);
	gStopWatch.Stop();
	Rslt = Rslt >=0 ? 0 : 1;
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Exit code: %d Total processing time: %s",Rslt,gStopWatch.Read());
	exit(Rslt);
	}
else
	{
	printf("\n%s CSV Merge Elements, Version %s\n",gszProcName,cpszProgVer);
	arg_print_errors(stdout,end,gszProcName);
	arg_print_syntax(stdout,argtable,"\nUse '-h' to view option and parameter usage\n");
	exit(1);
	}
}
int main(int argc, char* argv[]) {

#ifdef BALL
    double discountFactor = 0.9;
#else
#ifdef CART_POLE
    double discountFactor = 0.95;
#else
#ifdef DOUBLE_CART_POLE
    double discountFactor = 0.95;
#else
#ifdef MOUNTAIN_CAR
    double discountFactor = 0.99;
#else
#ifdef ACROBOT
    double discountFactor = 0.95;
#else
#ifdef BOAT
    double discountFactor = 0.95;
#else
#ifdef CART_POLE_BINARY
    double discountFactor = 0.95;
#else
#ifdef SWIMMER
    double discountFactor = 0.95;
#endif
#endif
#endif
#endif
#endif
#endif
#endif
#endif

    FILE* initFileFd = NULL;
    state** initialStates = NULL;
    FILE* results = NULL;
    char str[1024];
    unsigned int i = 0;
    unsigned int h = 0;
    unsigned int* ns = NULL;
    unsigned int nbN = 0;
    unsigned int n = 0;
    unsigned int nbSteps = 0;
    unsigned int timestamp = time(NULL);
    int readFscanf = -1;

    optimistic_instance* optimistic = NULL;

    struct arg_file* initFile = arg_file1(NULL, "init", "<file>", "File containing the inital state");
    struct arg_str* r = arg_str1("n", NULL, "<s>", "List of maximum numbers of evaluations");
    struct arg_int* s = arg_int1("s", NULL, "<n>", "Number of steps");
    struct arg_int* k = arg_int1("k", NULL, "<n>", "Branching factor of the problem");
    struct arg_file* where = arg_file1(NULL, "where", "<file>", "Directory where we save the outputs");
    struct arg_end* end = arg_end(6);

    int nerrors = 0;
    void* argtable[6];

    argtable[0] = initFile;
    argtable[1] = r;
    argtable[2] = s;
    argtable[3] = k;
    argtable[4] = where;
    argtable[5] = end;

    if(arg_nullcheck(argtable) != 0) {
        printf("error: insufficient memory\n");
        arg_freetable(argtable, 6);
        return EXIT_FAILURE;
    }

    nerrors = arg_parse(argc, argv, argtable);

    if(nerrors > 0) {
        printf("%s:", argv[0]);
        arg_print_syntax(stdout, argtable, "\n");
        arg_print_errors(stdout, end, argv[0]);
        arg_freetable(argtable, 6);
        return EXIT_FAILURE;
    }

    initGenerativeModelParameters();
    K = k->ival[0];
    initGenerativeModel();

    initFileFd = fopen(initFile->filename[0], "r");
    readFscanf = fscanf(initFileFd, "%u\n", &n);
    initialStates = (state**)malloc(sizeof(state*) * n);
    
    for(; i < n; i++) {
        readFscanf = fscanf(initFileFd, "%s\n", str);
        initialStates[i] = makeState(str);
    }
    fclose(initFileFd);

    nbSteps = s->ival[0];
    ns = parseUnsignedIntList((char*)r->sval[0], &nbN);

    optimistic = optimistic_initInstance(NULL, discountFactor);

    sprintf(str, "%s/%u_results_%u_%u.csv", where->filename[0], timestamp, K, nbSteps);
    results = fopen(str, "w");

    for(h = 0; h < nbN; h++) {
        double sumRewards = 0.0;

        for(i = 0; i < n; i++) {
            unsigned int j = 0;
            state* crt = copyState(initialStates[i]);

            optimistic_resetInstance(optimistic, crt);
            for(; j < nbSteps; j++) {
                char isTerminal = 0;
                double reward = 0.0;
                state* nextState = NULL;

                optimistic_keepSubtree(optimistic);
                action* optimalAction = optimistic_planning(optimistic, ns[h]);
                isTerminal = nextStateReward(crt, optimalAction, &nextState, &reward) < 0 ? 1 : 0;
                freeState(crt);
                crt = nextState;
                sumRewards += reward;
                if(isTerminal)
                    break;
            }
            optimistic_resetInstance(optimistic, crt);
            freeState(crt);

            printf(">>>>>>>>>>>>>> %uth initial state processed\n", i + 1);
            fflush(NULL);
        }

        fprintf(results, "%u,%.15f\n", ns[h], sumRewards / (double)n);
        printf(">>>>>>>>>>>>>> n = %u  done\n\n", ns[h]);
        fflush(NULL);
    }

    fclose(results);

    arg_freetable(argtable, 6);

    for(i = 0; i < n; i++)
        freeState(initialStates[i]);

    free(initialStates);

    optimistic_uninitInstance(&optimistic);

    freeGenerativeModel();
    freeGenerativeModelParameters();

    return EXIT_SUCCESS;

}
예제 #26
0
int main(int argc, char** argv) {
    struct arg_int  *numVerticesArg = arg_int0("v","vertices",NULL, "num vertices (default is 20)");
    struct arg_int  *numObjectsArg  = arg_int0("o","objects",NULL, "num objects (default is 20)");
    struct arg_lit  *help           = arg_lit0(NULL,"help",       "print this help and exit");
    struct arg_str  *rendererArg    = arg_str1(NULL,NULL,"RENDERER",NULL);
    struct arg_end  *end            = arg_end(20);

    void* argtable[] = {numVerticesArg, numObjectsArg, help, rendererArg, end};
    const char* progname = "gl-instancing";
    int exitcode=0;
    int nerrors;
    renderer *renderer;
    int numVertices = 20;
    int numObjects = 20;

    /* verify the argtable[] entries were allocated sucessfully */
    if (arg_nullcheck(argtable) != 0)
    {
        /* NULL entries were detected, some allocations must have failed */
        printf("%s: insufficient memory\n",progname);
        exitcode=1;
        goto exit;
    }

    /* Parse the command line as defined by argtable[] */
    nerrors = arg_parse(argc,argv,argtable);

    /* special case: '--help' takes precedence over error reporting */
    if (help->count > 0)
    {
        printUsage(stderr, progname, argtable);
        goto exit;
    }

    if (numVerticesArg->count > 0) {
        numVertices = numVerticesArg->ival[0];
    }
    
    if (numObjectsArg->count > 0) {
        numObjects = numObjectsArg->ival[0];
    }
    
    if (rendererArg->count == 0) {
        fprintf(stderr, "Provide a renderer!\n");
        printUsage(stderr, progname, argtable);
        goto exit;
    }

    if (rendererArg->count > 0) {
        if (strcmp(rendererArg->sval[0], "standard") == 0) {
            renderer = getStandardRenderer(numVertices, numObjects);
        } else if (strcmp(rendererArg->sval[0], "instanced") == 0) {
            renderer = getInstancedRenderer(numVertices, numObjects);
        } else {
            fprintf(stderr, "Renderer %s is unknown. Supported renderers: instanced, standard\n", rendererArg->sval[0]);
            printUsage(stderr, progname, argtable);
            goto exit;
        }
    }

    exitcode = glMain(renderer);

exit:
    /* deallocate each non-null entry in argtable[] */
    arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0]));

    return exitcode;
}
예제 #27
0
split_options_t *new_split_cli_options() {
    split_options_t *options = (split_options_t*) malloc (sizeof(split_options_t));
    options->num_options = NUM_SPLIT_OPTIONS;
    options->criterion = arg_str1(NULL, "criterion", NULL, "Criterion for splitting the file");
    return options;
}
int main(int argc, char* argv[]) {

#ifdef BALL
    double discountFactor = 0.9;
#else
#ifdef CART_POLE
    double discountFactor = 0.95;
#else
#ifdef DOUBLE_CART_POLE
    double discountFactor = 0.95;
#else
#ifdef MOUNTAIN_CAR
    double discountFactor = 0.99;
#else
#ifdef ACROBOT
    double discountFactor = 0.95;
#else
#ifdef BOAT
    double discountFactor = 0.95;
#else
#ifdef SWIMMER
    double discountFactor = 0.95;
#endif
#endif
#endif
#endif
#endif
#endif
#endif

    FILE* initFileFd = NULL;
    state** initialStates = NULL;
    FILE* results = NULL;
    char str[1024];
    unsigned int i = 0;
    unsigned int* ns = NULL;
    unsigned int nbN = 0;
    unsigned int* hs = NULL;
    unsigned int nbH = 0;
    unsigned int n = 0;
    unsigned int nbSteps = 0;
    unsigned int nbIterations = 1;
    unsigned int timestamp = time(NULL);
    int readFscanf = -1;

    random_search_instance* random_search = NULL;

    struct arg_file* initFile = arg_file1(NULL, "init", "<file>", "File containing the inital state");
    struct arg_str* r = arg_str1("n", NULL, "<s>", "List of maximum numbers of evaluations");
    struct arg_str* d = arg_str1("h", NULL, "<s>", "List of depth");
    struct arg_int* s = arg_int1("s", NULL, "<n>", "Number of steps");
    struct arg_int* it = arg_int1("i", NULL, "<n>", "Number of iteration");
    struct arg_file* where = arg_file1(NULL, "where", "<file>", "Directory where we save the outputs");
    struct arg_end* end = arg_end(7);

    int nerrors = 0;
    void* argtable[7];

    argtable[0] = initFile;
    argtable[1] = r;
    argtable[2] = d;
    argtable[3] = s;
    argtable[4] = it;
    argtable[5] = where;
    argtable[6] = end;

    if(arg_nullcheck(argtable) != 0) {
        printf("error: insufficient memory\n");
        arg_freetable(argtable, 7);
        return EXIT_FAILURE;
    }

    nerrors = arg_parse(argc, argv, argtable);

    if(nerrors > 0) {
        printf("%s:", argv[0]);
        arg_print_syntax(stdout, argtable, "\n");
        arg_print_errors(stdout, end, argv[0]);
        arg_freetable(argtable, 7);
        return EXIT_FAILURE;
    }

    initGenerativeModelParameters();
    initGenerativeModel();

    initFileFd = fopen(initFile->filename[0], "r");
    readFscanf = fscanf(initFileFd, "%u\n", &n);
    initialStates = (state**)malloc(sizeof(state*) * n);
    
    for(; i < n; i++) {
        readFscanf = fscanf(initFileFd, "%s\n", str);
        initialStates[i] = makeState(str);
    }
    fclose(initFileFd);

    nbSteps = s->ival[0];
    nbIterations = it->ival[0];
    ns = parseUnsignedIntList((char*)r->sval[0], &nbN);
    hs = parseUnsignedIntList((char*)d->sval[0], &nbH);

    random_search = random_search_initInstance(NULL, discountFactor);
    h_max = h_max_crt_depth;

    sprintf(str, "%s/%u_results_random_search_%s.csv", where->filename[0], timestamp,(char*)r->sval[0]);
    results = fopen(str, "w");

    for(i = 0; i < nbIterations; i++) {
        unsigned int j = 0;

        for(;j < nbH; j++) {
            unsigned int k = 0;

            crtDepth = hs[j];

            for(; k < nbN; k++) {
                unsigned int l = 0;
                double sumRewards = 0.0;

                for(; l < n; l++) {
                    unsigned int m = 0;
                    state* crt = copyState(initialStates[l]);

                    for(; m < nbSteps; m++) {
                        char isTerminal = 0;
                        double reward = 0.0;
                        state* nextState = NULL;
                        double* optimalAction = NULL;

                        random_search_resetInstance(random_search, crt);
                        optimalAction = random_search_planning(random_search, ns[k]);
                        isTerminal = nextStateReward(crt, optimalAction, &nextState, &reward) < 0 ? 1 : 0;
                        freeState(crt);
                        free(optimalAction);
                        crt = nextState;
                        sumRewards += reward;
                        if(isTerminal)
                            break;
                    }
                    random_search_resetInstance(random_search, crt);
                    freeState(crt);

                    printf(">>>>>>>>>>>>>> %uth initial state processed with h=%u and n=%u of iteration %u\n", l + 1, hs[j], ns[k], i+1);
                    fflush(NULL);
                }

                fprintf(results, "%u,%u,%.15f\n", hs[j],ns[k], sumRewards / (double)n);
                printf(">>>>>>>>>>>>>> n = %u  done\n\n", ns[k]);
                fflush(NULL);
            }
            printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> h = %u done \n\n", hs[j]);
            fflush(NULL);
        }

        fprintf(results,"\n");
        printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ITERATION %u DONE <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n\n", i+1);
        fflush(NULL);

    }

    fclose(results);

    arg_freetable(argtable, 7);

    for(i = 0; i < n; i++)
        freeState(initialStates[i]);

    free(initialStates);

    random_search_uninitInstance(&random_search);

    freeGenerativeModel();
    freeGenerativeModelParameters();

    return EXIT_SUCCESS;

}
int main(int argc, char* argv[]) {

#ifdef BALL
    double discountFactor = 0.9;
#else
#ifdef CART_POLE
    double discountFactor = 0.95;
#else
#ifdef DOUBLE_CART_POLE
    double discountFactor = 0.95;
#else
#ifdef MOUNTAIN_CAR
    double discountFactor = 0.99;
#else
#ifdef ACROBOT
    double discountFactor = 0.95;
#else
#ifdef BOAT
    double discountFactor = 0.95;
#else
#ifdef SWIMMER
    double discountFactor = 0.95;
#endif
#endif
#endif
#endif
#endif
#endif
#endif

    FILE* initFileFd = NULL;
    state** initialStates = NULL;
    FILE* results = NULL;
    char str[1024];
    unsigned int i = 0;
    unsigned int nbInitialStates = 0;
    unsigned int* ns = NULL;
    unsigned int nbN = 0;
    double* Ls = NULL;
    unsigned int nbL = 0;
    unsigned int nbSteps = 0;
    unsigned int timestamp = time(NULL);
    int readFscanf = -1;

    lipschitzian_instance* lipschitzian = NULL;

    struct arg_file* initFile = arg_file1(NULL, "init", "<file>", "File containing the inital state");
    struct arg_int* s = arg_int1("s", NULL, "<n>", "Number of steps");
    struct arg_str* r = arg_str1("n", NULL, "<s>", "List of ressources");
    struct arg_str* z = arg_str1("L", NULL, "<s>", "List of Lipschitz coefficients to try");
    struct arg_file* where = arg_file1(NULL, "where", "<file>", "Directory where we save the outputs");
    struct arg_end* end = arg_end(6);

    int nerrors = 0;
    void* argtable[6];

    argtable[0] = initFile;
    argtable[1] = r;
    argtable[2] = s;
    argtable[3] = z;
    argtable[4] = where;
    argtable[5] = end;

    if(arg_nullcheck(argtable) != 0) {
        printf("error: insufficient memory\n");
        arg_freetable(argtable, 6);
        return EXIT_FAILURE;
    }

    nerrors = arg_parse(argc, argv, argtable);

    if(nerrors > 0) {
        printf("%s:", argv[0]);
        arg_print_syntax(stdout, argtable, "\n");
        arg_print_errors(stdout, end, argv[0]);
        arg_freetable(argtable, 6);
        return EXIT_FAILURE;
    }

    initGenerativeModelParameters();
    initGenerativeModel();

    initFileFd = fopen(initFile->filename[0], "r");
    readFscanf = fscanf(initFileFd, "%u\n", &nbInitialStates);
    initialStates = (state**)malloc(sizeof(state*) * nbInitialStates);
    
    for(; i < nbInitialStates; i++) {
        readFscanf = fscanf(initFileFd, "%s\n", str);
        initialStates[i] = makeState(str);
    }
    fclose(initFileFd);

    nbSteps = s->ival[0];
    Ls = parseDoubleList((char*)z->sval[0], &nbL);
    ns = parseUnsignedIntList((char*)r->sval[0], &nbN);

    sprintf(str, "%s/%u_results_%s_%s.csv", where->filename[0], timestamp, z->sval[0], r->sval[0]);
    results = fopen(str, "w");

    lipschitzian = lipschitzian_initInstance(NULL, discountFactor, 0.0);
    
    for(i = 0; i < nbN; i++) {                                               /* Loop on the computational ressources */
        fprintf(results, "%u", ns[i]);
        printf("Starting with %u computational ressources\n", ns[i]);
        fflush(NULL);
        unsigned int j = 0;
        for(; j < nbL; j++) {                                           /* Loop on the Lispchitz constant */
            unsigned int k = 0;
            double average = 0.0;
            lipschitzian->L = Ls[j];
            for(; k < nbInitialStates; k++) {                           /* Loop on the initial states */
                unsigned int l = 0;
                double sumRewards = 0.0;
                state* crt = copyState(initialStates[k]);

                lipschitzian_resetInstance(lipschitzian, crt);
                for(; l < nbSteps; l++) {                               /* Loop on the step */
                    char isTerminal = 0;
                    double reward = 0.0;
                    state* nextState = NULL;

                    double* optimalAction = lipschitzian_planning(lipschitzian, ns[i]);
                    isTerminal = nextStateReward(crt, optimalAction, &nextState, &reward) < 0 ? 1 : 0;
                    free(optimalAction);
                    freeState(crt);
                    crt = nextState;
                    sumRewards += reward;
                    lipschitzian_resetInstance(lipschitzian,crt);
                    if(isTerminal)
                        break;
                }
                average += sumRewards;
                freeState(crt);
                printf("Computation of the %u initial state done with L=%f\n", k, Ls[j]);
                fflush(NULL);
            }
            average = average /(double)nbInitialStates;
            fprintf(results, ",%.15f", average);
            printf("Computation with L=%f and n=%u done\n", Ls[j], ns[i]);
            fflush(NULL);
        }
        fprintf(results,"\n");
        printf("Computation with %u computational ressources done\n\n", ns[i]);
        fflush(NULL);
    }

    fclose(results);

    arg_freetable(argtable, 6);

    for(i = 0; i < nbInitialStates; i++)
        freeState(initialStates[i]);

    free(initialStates);

    lipschitzian_uninitInstance(&lipschitzian);

    free(ns);
    free(Ls);

    freeGenerativeModel();
    freeGenerativeModelParameters();

    return EXIT_SUCCESS;

}
int main(int argc, char* argv[]) {

    unsigned int i = 0;
    unsigned int nbIntervals = 0;
    double* intervals = NULL;
    FILE* outputFileFd = NULL;
    gsl_rng* rng = NULL;
    unsigned int nbStates = 0;

    struct arg_file* outputFile = arg_file1("o", NULL, "<file>", "The output file for the generated initial state");
    struct arg_int* n = arg_int1("n", NULL, "<n>", "The number of initial states to generate");
    struct arg_str* s = arg_str1(NULL, "intervals", "<s>", "The intervals for the initial states generation");
    struct arg_end* end = arg_end(4);

    void* argtable[4];

    int nerrors = 0;

    argtable[0] = outputFile;
    argtable[1] = n;
    argtable[2] = s;
    argtable[3] = end;

    if(arg_nullcheck(argtable) != 0) {
        printf("error: insufficient memory\n");
        arg_freetable(argtable, 4);
        return EXIT_FAILURE;
    }

    nerrors = arg_parse(argc, argv, argtable);

    if(nerrors > 0) {
        printf("%s:", argv[0]);
        arg_print_syntax(stdout, argtable, "\n");
        arg_print_errors(stdout, end, argv[0]);
        arg_freetable(argtable, 4);
        return EXIT_FAILURE;
    }

    nbStates = n->ival[0];

    intervals = parseIntervals(s->sval[0], &nbIntervals);

    rng = gsl_rng_alloc(gsl_rng_mt19937);
    gsl_rng_set(rng, time(NULL));

    outputFileFd = fopen(outputFile->filename[0], "w");
    fprintf(outputFileFd, "%u\n", n->ival[0]);

    for(; i < nbStates; i++) {
        unsigned int j = 0;
        for(; j < (nbIntervals - 1); j++)
            fprintf(outputFileFd, "%.15f,", (fabs(intervals[(j * 2) + 1] - intervals[j * 2]) * gsl_rng_uniform(rng)) + intervals[j * 2]);
        fprintf(outputFileFd, "%.15f\n", (fabs(intervals[(j * 2) + 1] - intervals[j * 2]) * gsl_rng_uniform(rng)) + intervals[j * 2]);
    }

    fclose(outputFileFd);
	gsl_rng_free(rng);
    free(intervals);
    arg_freetable(argtable, 4);

    return EXIT_SUCCESS;

}