Python argparse.ArgumentDefaultsHelpFormatter() Examples

The following are 30 code examples for showing how to use argparse.ArgumentDefaultsHelpFormatter(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module argparse , or try the search function .

Example 1
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: diagnose.py    License: Apache License 2.0 6 votes vote down vote up
def parse_args():
    """Parse arguments."""
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        description='Diagnose script for checking the current system.')
    choices = ['python', 'pip', 'mxnet', 'os', 'hardware', 'network']
    for choice in choices:
        parser.add_argument('--' + choice, default=1, type=int,
                            help='Diagnose {}.'.format(choice))
    parser.add_argument('--region', default='', type=str,
                        help="Additional sites in which region(s) to test. \
                        Specify 'cn' for example to test mirror sites in China.")
    parser.add_argument('--timeout', default=10, type=int,
                        help="Connection test timeout threshold, 0 to disable.")
    args = parser.parse_args()
    return args 
Example 2
Project: derplearning   Author: notkarol   File: calibrate_camera.py    License: MIT License 6 votes vote down vote up
def main():
    """
    Calibrate the live camera and optionally do a live display of the results
    """
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument("config", type=Path, help="camera config path")
    parser.add_argument("--height", type=int, default=4)
    parser.add_argument("--width", type=int, default=10)
    parser.add_argument("--count", type=int, default=10)
    parser.add_argument("--view", action="store_true")
    args = parser.parse_args()

    config = {"camera": derp.util.load_config(args.config)}
    camera = Camera(config)
    pattern_shape = (args.height, args.width)

    camera_matrix, distortion_coefficients = live_calibrate(camera, pattern_shape, args.count)
    print(camera_matrix)
    print(distortion_coefficients)
    if args.view:
        live_undistort(camera, camera_matrix, distortion_coefficients)
    cv2.destroyAllWindows() 
Example 3
Project: robosat   Author: mapbox   File: predict.py    License: MIT License 6 votes vote down vote up
def add_parser(subparser):
    parser = subparser.add_parser(
        "predict",
        help="predicts probability masks for slippy map tiles",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )

    parser.add_argument("--batch_size", type=int, default=1, help="images per batch")
    parser.add_argument("--checkpoint", type=str, required=True, help="model checkpoint to load")
    parser.add_argument("--overlap", type=int, default=32, help="tile pixel overlap to predict on")
    parser.add_argument("--tile_size", type=int, required=True, help="tile size for slippy map tiles")
    parser.add_argument("--workers", type=int, default=0, help="number of workers pre-processing images")
    parser.add_argument("tiles", type=str, help="directory to read slippy map image tiles from")
    parser.add_argument("probs", type=str, help="directory to save slippy map probability masks to")
    parser.add_argument("--model", type=str, required=True, help="path to model configuration file")
    parser.add_argument("--dataset", type=str, required=True, help="path to dataset configuration file")

    parser.set_defaults(func=main) 
Example 4
Project: JetPack   Author: dsp-jetpack   File: config_idracs.py    License: Apache License 2.0 6 votes vote down vote up
def parse_arguments():
    parser = argparse.ArgumentParser(
        description="Performs initial configuration of iDRACs.",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    ArgHelper.add_instack_arg(parser)
    ArgHelper.add_model_properties_arg(parser)

    LoggingHelper.add_argument(parser)

    parser.add_argument("-j",
                        "--json_config",
                        default=None,
                        help="""JSON that specifies the PXE NIC FQDD and the "
                            "new password for each overcloud node""")

    return parser.parse_args() 
Example 5
Project: miccai-2016-surgical-activity-rec   Author: rdipietro   File: standardize_jigsaws.py    License: Apache License 2.0 6 votes vote down vote up
def define_and_process_args():
    """ Define and process command-line arguments.

    Returns:
        A Namespace with arguments as attributes.
    """

    description = main.__doc__
    formatter_class = argparse.ArgumentDefaultsHelpFormatter
    parser = argparse.ArgumentParser(description=description,
                                     formatter_class=formatter_class)

    parser.add_argument('--data_dir', default='~/Data/JIGSAWS/Suturing',
                        help='Data directory.')
    parser.add_argument('--data_filename', default='standardized_data.pkl',
                        help='''The name of the standardized-data pkl file that
                                we'll create inside data_dir.''')

    args = parser.parse_args()
    args.data_dir = os.path.expanduser(args.data_dir)
    return args 
Example 6
Project: don   Author: CiscoSystems   File: ovs.py    License: Apache License 2.0 6 votes vote down vote up
def check_args():
    global params

    parser = argparse.ArgumentParser(
        description='OVS test', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('--debug', dest='debug',
                        help='Enable debugging', default=False, action='store_true')
    parser.add_argument('--src_port_id', dest='src_port_id',
                        help='OVS src port id (required)', type=str, required=True)
    parser.add_argument('--dst_port_id', dest='dst_port_id',
                        help='OVS dst port id (required)', type=str, required=True)
    parser.add_argument(
        '--tag', dest='tag', help='VLAN tag of port (required)', type=str, required=True)
    parser.add_argument('--ovs_bridge', dest='ovs_bridge',
                        help='OVS bridge to be tested (required)', type=str, required=True)
    args = parser.parse_args()

    settings['debug'] = args.debug
    params['src_port_id'] = args.src_port_id
    params['dst_port_id'] = args.dst_port_id
    params['tag'] = args.tag
    params['ovs_bridge'] = args.ovs_bridge 
Example 7
def prepare_args():
    # parse args
    parser = argparse.ArgumentParser(description="train cifar10",
                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    fit.add_fit_args(parser)
    data.add_data_args(parser)
    data.add_data_aug_args(parser)
    # uncomment to set standard cifar augmentations
    # set_cifar_aug(parser)
    parser.set_defaults(
        # network
        network        = 'resnet',
        num_layers     = 110,
        # data
        data_train     = train_fname,
        data_val       = val_fname,
        num_classes    = 10,
        num_examples  = 50000,
        image_shape    = '3,28,28',
        pad_size       = 4,
        # train
        batch_size     = 128,
        num_epochs     = 300,
        lr             = .05,
        lr_step_epochs = '200,250',
    )
    return parser.parse_args(), fit, data 
Example 8
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: lstm_sort.py    License: Apache License 2.0 5 votes vote down vote up
def parse_args():
    parser = argparse.ArgumentParser(description="Parse args for lstm_sort example",
                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('--start-range', type=int, default=100,
                        help='starting number of the range')
    parser.add_argument('--end-range', type=int, default=1000,
                        help='Ending number of the range')
    parser.add_argument('--cpu', action='store_true',
                        help='To use CPU for training')
    return parser.parse_args() 
Example 9
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: demo.py    License: Apache License 2.0 5 votes vote down vote up
def parse_args():
    parser = argparse.ArgumentParser(description='Demonstrate a Faster R-CNN network',
                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('--network', type=str, default='vgg16', help='base network')
    parser.add_argument('--params', type=str, default='', help='path to trained model')
    parser.add_argument('--dataset', type=str, default='voc', help='training dataset')
    parser.add_argument('--image', type=str, default='', help='path to test image')
    parser.add_argument('--gpu', type=str, default='', help='gpu device eg. 0')
    parser.add_argument('--vis', action='store_true', help='display results')
    parser.add_argument('--vis-thresh', type=float, default=0.7, help='threshold display boxes')
    # faster rcnn params
    parser.add_argument('--img-short-side', type=int, default=600)
    parser.add_argument('--img-long-side', type=int, default=1000)
    parser.add_argument('--img-pixel-means', type=str, default='(0.0, 0.0, 0.0)')
    parser.add_argument('--img-pixel-stds', type=str, default='(1.0, 1.0, 1.0)')
    parser.add_argument('--rpn-feat-stride', type=int, default=16)
    parser.add_argument('--rpn-anchor-scales', type=str, default='(8, 16, 32)')
    parser.add_argument('--rpn-anchor-ratios', type=str, default='(0.5, 1, 2)')
    parser.add_argument('--rpn-pre-nms-topk', type=int, default=6000)
    parser.add_argument('--rpn-post-nms-topk', type=int, default=300)
    parser.add_argument('--rpn-nms-thresh', type=float, default=0.7)
    parser.add_argument('--rpn-min-size', type=int, default=16)
    parser.add_argument('--rcnn-num-classes', type=int, default=21)
    parser.add_argument('--rcnn-feat-stride', type=int, default=16)
    parser.add_argument('--rcnn-pooled-size', type=str, default='(14, 14)')
    parser.add_argument('--rcnn-batch-size', type=int, default=1)
    parser.add_argument('--rcnn-bbox-stds', type=str, default='(0.1, 0.1, 0.2, 0.2)')
    parser.add_argument('--rcnn-nms-thresh', type=float, default=0.3)
    parser.add_argument('--rcnn-conf-thresh', type=float, default=1e-3)
    args = parser.parse_args()
    args.img_pixel_means = ast.literal_eval(args.img_pixel_means)
    args.img_pixel_stds = ast.literal_eval(args.img_pixel_stds)
    args.rpn_anchor_scales = ast.literal_eval(args.rpn_anchor_scales)
    args.rpn_anchor_ratios = ast.literal_eval(args.rpn_anchor_ratios)
    args.rcnn_pooled_size = ast.literal_eval(args.rcnn_pooled_size)
    args.rcnn_bbox_stds = ast.literal_eval(args.rcnn_bbox_stds)
    return args 
Example 10
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: test.py    License: Apache License 2.0 5 votes vote down vote up
def parse_args():
    parser = argparse.ArgumentParser(description='Test a Faster R-CNN network',
                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('--network', type=str, default='vgg16', help='base network')
    parser.add_argument('--params', type=str, default='', help='path to trained model')
    parser.add_argument('--dataset', type=str, default='voc', help='training dataset')
    parser.add_argument('--imageset', type=str, default='', help='imageset splits')
    parser.add_argument('--gpu', type=int, default=0, help='gpu device eg. 0')
    # faster rcnn params
    parser.add_argument('--img-short-side', type=int, default=600)
    parser.add_argument('--img-long-side', type=int, default=1000)
    parser.add_argument('--img-pixel-means', type=str, default='(0.0, 0.0, 0.0)')
    parser.add_argument('--img-pixel-stds', type=str, default='(1.0, 1.0, 1.0)')
    parser.add_argument('--rpn-feat-stride', type=int, default=16)
    parser.add_argument('--rpn-anchor-scales', type=str, default='(8, 16, 32)')
    parser.add_argument('--rpn-anchor-ratios', type=str, default='(0.5, 1, 2)')
    parser.add_argument('--rpn-pre-nms-topk', type=int, default=6000)
    parser.add_argument('--rpn-post-nms-topk', type=int, default=300)
    parser.add_argument('--rpn-nms-thresh', type=float, default=0.7)
    parser.add_argument('--rpn-min-size', type=int, default=16)
    parser.add_argument('--rcnn-num-classes', type=int, default=21)
    parser.add_argument('--rcnn-feat-stride', type=int, default=16)
    parser.add_argument('--rcnn-pooled-size', type=str, default='(14, 14)')
    parser.add_argument('--rcnn-batch-size', type=int, default=1)
    parser.add_argument('--rcnn-bbox-stds', type=str, default='(0.1, 0.1, 0.2, 0.2)')
    parser.add_argument('--rcnn-nms-thresh', type=float, default=0.3)
    parser.add_argument('--rcnn-conf-thresh', type=float, default=1e-3)
    args = parser.parse_args()
    args.img_pixel_means = ast.literal_eval(args.img_pixel_means)
    args.img_pixel_stds = ast.literal_eval(args.img_pixel_stds)
    args.rpn_anchor_scales = ast.literal_eval(args.rpn_anchor_scales)
    args.rpn_anchor_ratios = ast.literal_eval(args.rpn_anchor_ratios)
    args.rcnn_pooled_size = ast.literal_eval(args.rcnn_pooled_size)
    args.rcnn_bbox_stds = ast.literal_eval(args.rcnn_bbox_stds)
    return args 
Example 11
Project: soccer-matlab   Author: utra-robosoccer   File: minitaur_gym_env_example.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def main():
  parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  parser.add_argument('--env', help='environment ID (0==sine, 1==stand, 2=reset, 3=overheat)',type=int,  default=0)
  args = parser.parse_args()
  print("--env=" + str(args.env))
    
  if (args.env == 0):
    SinePolicyExample()
  if (args.env == 1):
    SineStandExample()
  if (args.env == 2):
    ResetPoseExample()
  if (args.env == 3):
    MotorOverheatExample() 
Example 12
Project: soccer-matlab   Author: utra-robosoccer   File: testEnv.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def main():
    import argparse
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('--env', help='environment ID', default='AntBulletEnv-v0')
    parser.add_argument('--seed', help='RNG seed', type=int, default=0)
    parser.add_argument('--render', help='OpenGL Visualizer', type=int, default=0)
    parser.add_argument('--rgb',help='rgb_array gym rendering',type=int, default=0)
    parser.add_argument('--resetbenchmark',help='Repeat reset to show reset performance',type=int, default=0)
    parser.add_argument('--steps', help='Number of steps', type=int, default=1)
    
    args = parser.parse_args()
    test(args) 
Example 13
Project: soccer-matlab   Author: utra-robosoccer   File: minitaur_gym_env_example.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('--env', help='environment ID (0==sine, 1==stand, 2=reset, 3=overheat)',type=int,  default=0)
    args = parser.parse_args()
    print("--env=" + str(args.env))
      
    if (args.env == 0):
      SinePolicyExample()
    if (args.env == 1):
      SineStandExample()
    if (args.env == 2):
      ResetPoseExample()
    if (args.env == 3):
      MotorOverheatExample() 
Example 14
Project: soccer-matlab   Author: utra-robosoccer   File: test_pybullet_sim_gym_env.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('--env', help='environment ID (0==reset)',type=int,  default=0)
    args = parser.parse_args()
    print("--env=" + str(args.env))
      
    if (args.env == 0):
      ResetPoseExample(steps = 1000) 
Example 15
Project: lirpg   Author: Hwhitetooth   File: run_atari.py    License: MIT License 5 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('--env', help='environment ID', default='BreakoutNoFrameskip-v4')
    parser.add_argument('--seed', help='RNG seed', type=int, default=0)
    parser.add_argument('--prioritized', type=int, default=1)
    parser.add_argument('--dueling', type=int, default=1)
    parser.add_argument('--num-timesteps', type=int, default=int(10e6))
    args = parser.parse_args()
    logger.configure()
    set_global_seeds(args.seed)
    env = make_atari(args.env)
    env = bench.Monitor(env, logger.get_dir())
    env = deepq.wrap_atari_dqn(env)
    model = deepq.models.cnn_to_mlp(
        convs=[(32, 8, 4), (64, 4, 2), (64, 3, 1)],
        hiddens=[256],
        dueling=bool(args.dueling),
    )
    act = deepq.learn(
        env,
        q_func=model,
        lr=1e-4,
        max_timesteps=args.num_timesteps,
        buffer_size=10000,
        exploration_fraction=0.1,
        exploration_final_eps=0.01,
        train_freq=4,
        learning_starts=10000,
        target_network_update_freq=1000,
        gamma=0.99,
        prioritized_replay=bool(args.prioritized)
    )
    # act.save("pong_model.pkl") XXX
    env.close() 
Example 16
Project: lirpg   Author: Hwhitetooth   File: cmd_util.py    License: MIT License 5 votes vote down vote up
def arg_parser():
    """
    Create an empty argparse.ArgumentParser.
    """
    import argparse
    return argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) 
Example 17
Project: lirpg   Author: Hwhitetooth   File: results_plotter.py    License: MIT License 5 votes vote down vote up
def main():
    import argparse
    import os
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('--dirs', help='List of log directories', nargs = '*', default=['./log'])
    parser.add_argument('--num_timesteps', type=int, default=int(10e6))
    parser.add_argument('--xaxis', help = 'Varible on X-axis', default = X_TIMESTEPS)
    parser.add_argument('--task_name', help = 'Title of plot', default = 'Breakout')
    args = parser.parse_args()
    args.dirs = [os.path.abspath(dir) for dir in args.dirs]
    plot_results(args.dirs, args.num_timesteps, args.xaxis, args.task_name)
    plt.show() 
Example 18
Project: lirpg   Author: Hwhitetooth   File: main.py    License: MIT License 5 votes vote down vote up
def parse_args():
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument('--env-id', type=str, default='HalfCheetah-v1')
    boolean_flag(parser, 'render-eval', default=False)
    boolean_flag(parser, 'layer-norm', default=True)
    boolean_flag(parser, 'render', default=False)
    boolean_flag(parser, 'normalize-returns', default=False)
    boolean_flag(parser, 'normalize-observations', default=True)
    parser.add_argument('--seed', help='RNG seed', type=int, default=0)
    parser.add_argument('--critic-l2-reg', type=float, default=1e-2)
    parser.add_argument('--batch-size', type=int, default=64)  # per MPI worker
    parser.add_argument('--actor-lr', type=float, default=1e-4)
    parser.add_argument('--critic-lr', type=float, default=1e-3)
    boolean_flag(parser, 'popart', default=False)
    parser.add_argument('--gamma', type=float, default=0.99)
    parser.add_argument('--reward-scale', type=float, default=1.)
    parser.add_argument('--clip-norm', type=float, default=None)
    parser.add_argument('--nb-epochs', type=int, default=500)  # with default settings, perform 1M steps total
    parser.add_argument('--nb-epoch-cycles', type=int, default=20)
    parser.add_argument('--nb-train-steps', type=int, default=50)  # per epoch cycle and MPI worker
    parser.add_argument('--nb-eval-steps', type=int, default=100)  # per epoch cycle and MPI worker
    parser.add_argument('--nb-rollout-steps', type=int, default=100)  # per epoch cycle and MPI worker
    parser.add_argument('--noise-type', type=str, default='adaptive-param_0.2')  # choices are adaptive-param_xx, ou_xx, normal_xx, none
    parser.add_argument('--num-timesteps', type=int, default=None)
    boolean_flag(parser, 'evaluation', default=False)
    args = parser.parse_args()
    # we don't directly specify timesteps for this script, so make sure that if we do specify them
    # they agree with the other parameters
    if args.num_timesteps is not None:
        assert(args.num_timesteps == args.nb_epochs * args.nb_epoch_cycles * args.nb_rollout_steps)
    dict_args = vars(args)
    del dict_args['num_timesteps']
    return dict_args 
Example 19
Project: HardRLWithYoutube   Author: MaxSobolMark   File: run_atari.py    License: MIT License 5 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('--env', help='environment ID', default='BreakoutNoFrameskip-v4')
    parser.add_argument('--seed', help='RNG seed', type=int, default=0)
    parser.add_argument('--prioritized', type=int, default=1)
    parser.add_argument('--prioritized-replay-alpha', type=float, default=0.6)
    parser.add_argument('--dueling', type=int, default=1)
    parser.add_argument('--num-timesteps', type=int, default=int(10e6))
    parser.add_argument('--checkpoint-freq', type=int, default=10000)
    parser.add_argument('--checkpoint-path', type=str, default=None)

    args = parser.parse_args()
    logger.configure()
    set_global_seeds(args.seed)
    env = make_atari(args.env)
    env = bench.Monitor(env, logger.get_dir())
    env = deepq.wrap_atari_dqn(env)

    deepq.learn(
        env,
        "conv_only",
        convs=[(32, 8, 4), (64, 4, 2), (64, 3, 1)],
        hiddens=[256],
        dueling=bool(args.dueling),
        lr=1e-4,
        total_timesteps=args.num_timesteps,
        buffer_size=10000,
        exploration_fraction=0.1,
        exploration_final_eps=0.01,
        train_freq=4,
        learning_starts=10000,
        target_network_update_freq=1000,
        gamma=0.99,
        prioritized_replay=bool(args.prioritized),
        prioritized_replay_alpha=args.prioritized_replay_alpha,
        checkpoint_freq=args.checkpoint_freq,
        checkpoint_path=args.checkpoint_path,
    )

    env.close() 
Example 20
Project: HardRLWithYoutube   Author: MaxSobolMark   File: run_retro.py    License: MIT License 5 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('--env', help='environment ID', default='SuperMarioBros-Nes')
    parser.add_argument('--gamestate', help='game state to load', default='Level1-1')
    parser.add_argument('--seed', help='seed', type=int, default=0)
    parser.add_argument('--num-timesteps', type=int, default=int(10e6))
    args = parser.parse_args()
    logger.configure()
    set_global_seeds(args.seed)
    env = retro_wrappers.make_retro(game=args.env, state=args.gamestate, max_episode_steps=10000, use_restricted_actions=retro.Actions.DISCRETE)
    env.seed(args.seed)
    env = bench.Monitor(env, logger.get_dir())
    env = retro_wrappers.wrap_deepmind_retro(env)

    model = deepq.models.cnn_to_mlp(
        convs=[(32, 8, 4), (64, 4, 2), (64, 3, 1)],
        hiddens=[256],
        dueling=True
    )
    act = deepq.learn(
        env,
        q_func=model,
        lr=1e-4,
        max_timesteps=args.num_timesteps,
        buffer_size=10000,
        exploration_fraction=0.1,
        exploration_final_eps=0.01,
        train_freq=4,
        learning_starts=10000,
        target_network_update_freq=1000,
        gamma=0.99,
        prioritized_replay=True
    )
    act.save()
    env.close() 
Example 21
Project: HardRLWithYoutube   Author: MaxSobolMark   File: cmd_util.py    License: MIT License 5 votes vote down vote up
def arg_parser():
    """
    Create an empty argparse.ArgumentParser.
    """
    import argparse
    return argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) 
Example 22
Project: HardRLWithYoutube   Author: MaxSobolMark   File: results_plotter.py    License: MIT License 5 votes vote down vote up
def main():
    import argparse
    import os
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('--dirs', help='List of log directories', nargs = '*', default=['./log'])
    parser.add_argument('--num_timesteps', type=int, default=int(10e6))
    parser.add_argument('--xaxis', help = 'Varible on X-axis', default = X_TIMESTEPS)
    parser.add_argument('--task_name', help = 'Title of plot', default = 'Breakout')
    args = parser.parse_args()
    args.dirs = [os.path.abspath(dir) for dir in args.dirs]
    plot_results(args.dirs, args.num_timesteps, args.xaxis, args.task_name)
    plt.show() 
Example 23
Project: HardRLWithYoutube   Author: MaxSobolMark   File: main.py    License: MIT License 5 votes vote down vote up
def parse_args():
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument('--env-id', type=str, default='HalfCheetah-v1')
    boolean_flag(parser, 'render-eval', default=False)
    boolean_flag(parser, 'layer-norm', default=True)
    boolean_flag(parser, 'render', default=False)
    boolean_flag(parser, 'normalize-returns', default=False)
    boolean_flag(parser, 'normalize-observations', default=True)
    parser.add_argument('--seed', help='RNG seed', type=int, default=0)
    parser.add_argument('--critic-l2-reg', type=float, default=1e-2)
    parser.add_argument('--batch-size', type=int, default=64)  # per MPI worker
    parser.add_argument('--actor-lr', type=float, default=1e-4)
    parser.add_argument('--critic-lr', type=float, default=1e-3)
    boolean_flag(parser, 'popart', default=False)
    parser.add_argument('--gamma', type=float, default=0.99)
    parser.add_argument('--reward-scale', type=float, default=1.)
    parser.add_argument('--clip-norm', type=float, default=None)
    parser.add_argument('--nb-epochs', type=int, default=500)  # with default settings, perform 1M steps total
    parser.add_argument('--nb-epoch-cycles', type=int, default=20)
    parser.add_argument('--nb-train-steps', type=int, default=50)  # per epoch cycle and MPI worker
    parser.add_argument('--nb-eval-steps', type=int, default=100)  # per epoch cycle and MPI worker
    parser.add_argument('--nb-rollout-steps', type=int, default=100)  # per epoch cycle and MPI worker
    parser.add_argument('--noise-type', type=str, default='adaptive-param_0.2')  # choices are adaptive-param_xx, ou_xx, normal_xx, none
    parser.add_argument('--num-timesteps', type=int, default=None)
    boolean_flag(parser, 'evaluation', default=False)
    args = parser.parse_args()
    # we don't directly specify timesteps for this script, so make sure that if we do specify them
    # they agree with the other parameters
    if args.num_timesteps is not None:
        assert(args.num_timesteps == args.nb_epochs * args.nb_epoch_cycles * args.nb_rollout_steps)
    dict_args = vars(args)
    del dict_args['num_timesteps']
    return dict_args 
Example 24
Project: jawfish   Author: war-and-code   File: chardetect.py    License: MIT License 5 votes vote down vote up
def main(argv=None):
    '''
    Handles command line arguments and gets things started.

    :param argv: List of arguments, as if specified on the command-line.
                 If None, ``sys.argv[1:]`` is used instead.
    :type argv: list of str
    '''
    # Get command line arguments
    parser = argparse.ArgumentParser(
        description="Takes one or more file paths and reports their detected \
                     encodings",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        conflict_handler='resolve')
    parser.add_argument('input',
                        help='File whose encoding we would like to determine.',
                        type=argparse.FileType('rb'), nargs='*',
                        default=[sys.stdin])
    parser.add_argument('--version', action='version',
                        version='%(prog)s {0}'.format(__version__))
    args = parser.parse_args(argv)

    for f in args.input:
        if f.isatty():
            print("You are running chardetect interactively. Press " +
                  "CTRL-D twice at the start of a blank line to signal the " +
                  "end of your input. If you want help, run chardetect " +
                  "--help\n", file=sys.stderr)
        print(description_of(f, f.name)) 
Example 25
Project: iAI   Author: aimuch   File: common.py    License: MIT License 5 votes vote down vote up
def find_sample_data(description="Runs a TensorRT Python sample", subfolder="", find_files=[]):
    '''
    Parses sample arguments.

    Args:
        description (str): Description of the sample.
        subfolder (str): The subfolder containing data relevant to this sample
        find_files (str): A list of filenames to find. Each filename will be replaced with an absolute path.

    Returns:
        str: Path of data directory.
    '''

    # Standard command-line arguments for all samples.
    kDEFAULT_DATA_ROOT = os.path.join(os.sep, "usr", "src", "tensorrt", "data")
    parser = argparse.ArgumentParser(description=description, formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument("-d", "--datadir", help="Location of the TensorRT sample data directory, and any additional data directories.", action="append", default=[kDEFAULT_DATA_ROOT])
    args, _ = parser.parse_known_args()

    def get_data_path(data_dir):
        # If the subfolder exists, append it to the path, otherwise use the provided path as-is.
        data_path = os.path.join(data_dir, subfolder)
        if not os.path.exists(data_path):
            print("WARNING: " + data_path + " does not exist. Trying " + data_dir + " instead.")
            data_path = data_dir
        # Make sure data directory exists.
        if not (os.path.exists(data_path)):
            print("WARNING: {:} does not exist. Please provide the correct data path with the -d option.".format(data_path))
        return data_path

    data_paths = [get_data_path(data_dir) for data_dir in args.datadir]
    return data_paths, locate_files(data_paths, find_files) 
Example 26
Project: Hashcode2k18   Author: sbrodehl   File: score.py    License: Apache License 2.0 5 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(description='print score',
                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('file_in', type=str, help='input file e.g. a_example.in')
    parser.add_argument('file_out', type=str, help='output file e.g. a_example.out')
    parser.add_argument('--debug', action='store_true', help='for debug purpose')
    parser.add_argument('--score', action='store_true', help='display raw score and bonus score')
    parser.add_argument('--wait', action='store_true', help='display wait time')
    parser.add_argument('--rides', action='store_true', help='display rides stats')
    parser.add_argument('--check', action='store_true', help='check output (slower)')
    args = parser.parse_args()
    set_log_level(args)
    score = compute_score(args.file_in, args.file_out, args.check)
    if args.score:
        print("score: {0:,} = {1:,} + {2:,} (bonus)".format(score.total(), score.raw_score,
                                                            score.bonus_score))  # decimal separator
    else:
        print("score: {0:,}".format(score.total()))  # decimal separator
    if args.wait:
        print("wait time: {0:,}".format(score.wait_time))  # decimal separator
    if args.rides:
        print("rides: {0:,} = {1:,} (taken) + {2:,} (unassigned) {3:,} (late)".format(score.taken + score.unassigned,
                                                                                      score.taken, score.unassigned,
                                                                                      score.late))  # decimal separator
        print("rides: {0:,} (taken) = {1:,} (bonus) + {2:,} (no bonus)".format(score.taken, score.bonus,
                                                                               score.taken - score.bonus))  # decimal separator 
Example 27
Project: insightface   Author: deepinsight   File: dir2rec.py    License: MIT License 5 votes vote down vote up
def parse_args():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        description='Create an image list or \
        make a record database by reading from an image list')
    parser.add_argument('--input', help='input data dir.')
    parser.add_argument('--output', help='outputdata dir.')
    #parser.add_argument('root', help='path to folder containing images.')

    cgroup = parser.add_argument_group('Options for creating image lists')
    cgroup.add_argument('--exts', nargs='+', default=['.jpeg', '.jpg'],
                        help='list of acceptable image extensions.')
    cgroup.add_argument('--chunks', type=int, default=1, help='number of chunks.')
    cgroup.add_argument('--train-ratio', type=float, default=1.0,
                        help='Ratio of images to use for training.')
    cgroup.add_argument('--test-ratio', type=float, default=0,
                        help='Ratio of images to use for testing.')

    rgroup = parser.add_argument_group('Options for creating database')
    rgroup.add_argument('--quality', type=int, default=95,
                        help='JPEG quality for encoding, 1-100; or PNG compression for encoding, 1-9')
    rgroup.add_argument('--num-thread', type=int, default=1,
                        help='number of thread to use for encoding. order of images will be different\
        from the input list if >1. the input list will be modified to match the\
        resulting order.')
    rgroup.add_argument('--color', type=int, default=1, choices=[-1, 0, 1],
                        help='specify the color mode of the loaded image.\
        1: Loads a color image. Any transparency of image will be neglected. It is the default flag.\
        0: Loads image in grayscale mode.\
        -1:Loads image as such including alpha channel.')
    rgroup.add_argument('--encoding', type=str, default='.jpg', choices=['.jpg', '.png'],
                        help='specify the encoding of the images.')
    args = parser.parse_args()
    return args 
Example 28
Project: VxAPI   Author: PayloadSecurity   File: vxapi.py    License: GNU General Public License v3.0 5 votes vote down vote up
def prepare_parser(self, current_key_json, map_of_available_actions):
        parser = argparse.ArgumentParser(description=Color.control_without_arrows('{} [{}]'.format(self.program_name, self.program_version)), formatter_class=argparse.ArgumentDefaultsHelpFormatter, add_help=False)
        parser.add_argument('--version', '-ver', action='version', version='{} - version {}'.format(self.program_name, self.program_version))
        DefaultCliArguments(parser).add_help_opt()

        subparsers = parser.add_subparsers(help='Action names for \'{}\' auth level'.format(current_key_json['auth_level_name']), dest="chosen_action")

        for name, value in map_of_available_actions.items():
            if value.api_object.endpoint_auth_level <= current_key_json['auth_level']:
                child_parser = subparsers.add_parser(name=name, help=value.help_description, add_help=False)
                value.add_parser_args(child_parser)
        
        return parser 
Example 29
Project: mdentropy   Author: msmbuilder   File: dmutinf.py    License: MIT License 5 votes vote down vote up
def configure_parser(sub_parsers):
    help = 'Run a dihedral mutual information calculation'
    p = sub_parsers.add_parser('dmutinf', description=help, help=help,
                               formatter_class=ArgumentDefaultsHelpFormatter)
    p.add_argument('-i', '--input', dest='traj',
                   help='File containing trajectory.', required=True)
    p.add_argument('-s', '--shuffle-iter', dest='iter',
                   help='Number of shuffle iterations.',
                   default=100, type=int)
    p.add_argument('-t', '--topology', dest='top',
                   help='File containing topology.', default=None)
    p.add_argument('-b', '--n-bins', dest='nbins',
                   help='Number of bins', default=3, type=int)
    p.add_argument('-n', '--n-threads', dest='n_threads',
                   help='Number of threads to be used.',
                   default=None, type=int)
    p.add_argument('-r', '--stride', dest='stride',
                   help='Stride to use', default=1, type=int)
    p.add_argument('-o', '--output', dest='out',
                   help='Name of output file.', default='mutinf.pkl')
    p.add_argument('-m', '--method', dest='method',
                   help='Entropy estimate method.',
                   choices=['chaowangjost', 'grassberger', 'kde',
                            'knn', 'naive'],
                   default='knn')
    p.add_argument('-d', '--dihedrals', dest='dihedrals',
                   help='Dihedral angles to analyze.',
                   nargs='+',
                   choices=['phi', 'psi', 'omega', 'chi1',
                            'chi2', 'chi3', 'chi4'],
                   default=['phi', 'psi'])
    p.set_defaults(func=func) 
Example 30
Project: mdentropy   Author: msmbuilder   File: dtent.py    License: MIT License 5 votes vote down vote up
def configure_parser(sub_parsers):
    help = 'Run a dihedral transfer entropy calculation'
    p = sub_parsers.add_parser('dtent', description=help, help=help,
                               formatter_class=ArgumentDefaultsHelpFormatter)
    p.add_argument('-p', '--past', dest='past',
                   help='File containing past step states.',
                   required=True)
    p.add_argument('-s', '--shuffle-iter', dest='iter',
                   help='Number of shuffle iterations.',
                   default=10, type=int)
    p.add_argument('-r', '--stride', dest='stride',
                   help='Stride to use', default=1, type=int)
    p.add_argument('-t', '--topology',
                   dest='top', help='File containing topology.',
                   default=None)
    p.add_argument('-b', '--n-bins', dest='nbins',
                   help='Number of bins', default=3, type=int)
    p.add_argument('-n', '--n-threads', dest='N',
                   help='Number of threads', default=None, type=int)
    p.add_argument('-o', '--output', dest='out',
                   help='Name of output file.', default='tent.pkl')
    p.add_argument('-m', '--method', dest='method',
                   help='Entropy estimate method.',
                   choices=['chaowangjost', 'grassberger', 'kde',
                            'knn', 'naive'],
                   default='knn')
    p.add_argument('-d', '--dihedrals', dest='dihedrals',
                   help='Dihedral angles to analyze.',
                   nargs='+',
                   choices=['phi', 'psi', 'omega', 'chi1',
                            'chi2', 'chi3', 'chi4'],
                   default=['phi', 'psi'])
    p.set_defaults(func=func)