Пример #1
0
class SyncCommand(BaijiCommand):
    DESCRIPTION = "move a directory tree from or to s3, a la rsync"
    progress = cli.Flag(['-P', '--progress'], help='show progress')
    guess_content_type = cli.Flag(['-g', '--guess-content-type'],
                                  help='Guess content type of file')
    policy = cli.SwitchAttr(
        '--policy',
        str,
        help=
        'override policy when copying to s3 (e.g. private, public-read, bucket-owner-read'
    )
    encoding = cli.SwitchAttr('--encoding',
                              str,
                              help='Content-Encoding: gzip, etc')
    do_not_delete = cli.SwitchAttr(
        ['-D', '--do-not-delete'],
        str,
        list=True,
        help='Path prefixes not to delete from the target')
    encrypt = cli.Flag('--no-encrypt',
                       default=True,
                       help='Do not server side encrypt at rest')

    def main(self, src, dst):
        kwargs = {
            'do_not_delete': self.do_not_delete,
            'progress': self.progress,
            'policy': self.policy,
            'encoding': self.encoding,
            'encrypt': self.encrypt,
            'guess_content_type': self.guess_content_type,
        }
        s3.sync(src, dst, **kwargs)
Пример #2
0
class RegistryServer(cli.Application):
    mode = cli.SwitchAttr(["-m", "--mode"], cli.Set("UDP", "TCP"), default="UDP",
                          help="Serving mode")

    ipv6 = cli.Flag(["-6", "--ipv6"], help="use ipv6 instead of ipv4")

    port = cli.SwitchAttr(["-p", "--port"], cli.Range(0, 65535), default=REGISTRY_PORT,
                          help="The UDP/TCP listener port")

    logfile = cli.SwitchAttr(["--logfile"], str, default=None,
                             help="The log file to use; the default is stderr")

    quiet = cli.SwitchAttr(["-q", "--quiet"], help="Quiet mode (only errors are logged)")

    pruning_timeout = cli.SwitchAttr(["-t", "--timeout"], int,
                                     default=DEFAULT_PRUNING_TIMEOUT, help="Set a custom pruning timeout (in seconds)")

    def main(self):
        if self.mode == "UDP":
            server = UDPRegistryServer(host='::' if self.ipv6 else '0.0.0.0', port=self.port,
                                       pruning_timeout=self.pruning_timeout)
        elif self.mode == "TCP":
            server = TCPRegistryServer(port=self.port, pruning_timeout=self.pruning_timeout)
        setup_logger(self.quiet, self.logfile)
        server.start()
Пример #3
0
class App(cli.Application):
    force = cli.Flag(['--force'],
                     help='Force overwrite if output already exists',
                     mandatory=False,
                     default=False)
    threshold = cli.SwitchAttr('-f',
                               help='Bet fractional intensity threshold',
                               default=0.1)
    dwi = cli.SwitchAttr(['-i', '--input'],
                         ExistingNrrdOrNifti,
                         help='Input DWI',
                         mandatory=True)
    out = cli.SwitchAttr(['-o', '--out'],
                         Nrrd,
                         help='output DWI mask',
                         mandatory=True)

    def main(self):
        if self.out.exists() and not self.force:
            logging.error(
                "'{}' already exists, use --force to force overwrite")
            import sys
            sys.exit(1)
        with TemporaryDirectory() as tmpdir:
            #nii = tmpdir / 'dwi.nii.gz'
            if nrrd(self.dwi):
                bse = tmpdir / 'bse.nrrd'
                bse_py['-i', self.dwi, '-o', bse] & FG
                bsenii = tmpdir / 'bse.nii.gz'
                ConvertBetweenFileFormats[bse, bsenii] & FG
                bet[bsenii, tmpdir / 'dwi', '-m', '-f', self.threshold] & FG
            else:  #nifti
                bet[self.dwi, tmpdir / 'dwi', '-m', '-f', self.threshold] & FG
            ConvertBetweenFileFormats[tmpdir / 'dwi_mask.nii.gz',
                                      self.out] & FG
Пример #4
0
class Geet(cli.Application):
    SUBCOMMAND_HELPMSG = False
    DESCRIPTION = colors.yellow | """The l33t version control"""
    PROGNAME = colors.green
    VERSION = colors.blue | "1.7.2"
    COLOR_USAGE = colors.magenta
    COLOR_GROUPS = {
        "Meta-switches": colors.bold,
        "Switches": colors.skyblue1,
        "Subcommands": colors.yellow,
    }

    verbosity = cli.SwitchAttr(
        "--verbosity",
        cli.Set("low", "high", "some-very-long-name", "to-test-wrap-around"),
        help=colors.cyan
        |
        "sets the verbosity level of the geet tool. doesn't really do anything except for testing line-wrapping "
        "in help " * 3,
    )
    verbositie = cli.SwitchAttr(
        "--verbositie",
        cli.Set("low", "high", "some-very-long-name", "to-test-wrap-around"),
        help=colors.hotpink
        |
        "sets the verbosity level of the geet tool. doesn't really do anything except for testing line-wrapping "
        "in help " * 3,
    )
Пример #5
0
class CertGenerator(cli.Application):
    PROGNAME = '基站证书生成工具'
    VERSION = 'v0.1'
    USAGE = 'python3 main.py [Switches]\n'

    amount = cli.SwitchAttr(["-a", "--amount"],
                            argtype=int,
                            help='指定需要生成的证书数量')
    cityname = cli.SwitchAttr(['-c', '--cityname'],
                              argtype=str,
                              help='指定生成证书的城市名')
    infile = cli.SwitchAttr(['-f', '--in-file'],
                            cli.ExistingFile,
                            help='指定保存有sn和mac的Excel文件作为devicelist',
                            requires=['-c'])

    @cli.switch(["--no-log"], help='关闭屏幕日志输出')
    def remove_handler(self):
        logger.removeHandler(console)
        close_log()

    def main(self):
        logger.debug('amount={},cityname={}'.format(self.amount,
                                                    self.cityname))
        device_data = get_device_data(self.cityname, self.amount, self.infile)
        if not device_data:
            return (self.helpall())
        cityname_dir = create_city_dir(self.cityname)
        key_dict = key_gen(cityname_dir, device_data)
        cityname = os.path.split(cityname_dir)[1]
        write_file(cityname, key_dict)
Пример #6
0
class App(cli.Application):
    """Centers an nrrd."""

    image_in = cli.SwitchAttr(['-i', '--infile'],
                              ExistingNrrd,
                              help='a 3d or 4d nrrd image',
                              mandatory=True)
    outfile = cli.SwitchAttr(['-o', '--outfile'],
                             help='a 3d or 4d nrrd image',
                             mandatory=True)

    def main(self):

        mri, hdr = get_attr(self.image_in._path)
        hdr_out = hdr.copy()

        new_origin = centered_origin(hdr)

        hdr_out['space origin'] = array(new_origin)

        if 'data file' in hdr_out.keys():
            del hdr_out['data file']
        elif 'datafile' in hdr_out.keys():
            del hdr_out['datafile']

        if 'content' in hdr_out.keys():
            del hdr_out['content']

        nrrd.write(self.outfile, mri, header=hdr_out, compression_level=1)
Пример #7
0
class TestCommand(cli.Application, DoFuncs):
    no_clear = cli.Flag("--no_clear", help="Do not clear screen")
    verbose = cli.SwitchAttr("--verbose",
                             int,
                             default=1,
                             help="Verbosity 0,1,2")
    coverage = cli.Flag("--coverage",
                        help="Run coverage and show in local HTML")
    debug_mode = cli.Flag("--debug_mode", help="Put zap into debug_mode")
    run_groups = cli.SwitchAttr("--run_groups",
                                str,
                                help="Comma separated list of groups")
    disable_shuffle = cli.Flag("--disable_shuffle",
                               help="If set, do not shuffle test order")

    def main(self, *args):
        self.assert_env()
        if not self.no_clear:
            self.clear()

        match_string = safe_list_get(args, 0)

        with Context(debug_mode=self.debug_mode):
            return self.run_zests(
                verbose=self.verbose,
                match_string=match_string,
                coverage=self.coverage,
                run_groups=self.run_groups,
            )
Пример #8
0
class GeniManageConfigure(cli.Application):
    """Configures portage and system
    """
    locale_gen = cli.SwitchAttr(["locale-gen"], str, list=True)
    locale = cli.SwitchAttr(["locale"], str)
    net_simple_names = cli.Flag(["net-simple-names"])
    timezone = cli.SwitchAttr(["timezone"], str)
    portage_profile = cli.SwitchAttr(["portage-profile"], str)
    portage_extras = cli.SwitchAttr(["portage-extras"])

    def main(self) -> int:  # pylint: disable=arguments-differ
        if self.timezone:
            configure_time_zone(self.parent.chroot, self.timezone)

        if self.locale_gen:
            generate_locales(self.parent.chroot, self.locale_gen)

        if self.locale:
            set_locale(self.parent.chroot, self.locale)

        if self.net_simple_names:
            configure_net_simple_names(self.parent.chroot_dir)

        if self.portage_profile:
            select_portage_profile(self.parent.chroot, self.portage_profile)

        if self.portage_extras:
            configure_portage_extras(self.parent.chroot_dir)

        return 0
Пример #9
0
class App(cli.Application):
    DESCRIPTION = "Makes a read-only version of tract_querier with a \
particular commit. Output is 'tract_querier-<hash>'."

    prefix = cli.SwitchAttr('-d',
                            cli.ExistingDirectory,
                            help="Root directory in which to install repo",
                            default=local.path('/data/pnl/soft'))
    githash = cli.SwitchAttr(
        '-g',
        help=
        'GitHub hash commit. If omitted will get latest commit from the master branch.'
    )

    def main(self):
        repo = 'https://github.com/demianw/tract_querier.git'
        with TemporaryDirectory() as tmpdir:
            clone = local.path(tmpdir) / "tract_querier"
            if not self.githash:
                git("clone", "--depth", "1", repo, clone)
            else:
                git("clone", repo, clone)
            clone_hash = git("rev-parse", "--short",
                             "HEAD")[:-1]  # remove trailing \n
            # save 70M of space
            rm('-r', clone / 'doc')
            rm('-r', clone / '.git')
            out = self.prefix / "tract_querier-" + clone_hash
            clone.move(out)
            chmod('-R', 'a-w', out)
Пример #10
0
class separateShells(cli.Application):

    ref_csv = cli.SwitchAttr(
        ['--img_list'],
        cli.ExistingFile,
        help=
        'csv/txt file with first column for dwi and 2nd column for mask: dwi1,mask1\\ndwi2,mask2\\n...'
        'or just one column for dwi1\\ndwi2\\n...',
        mandatory=True)

    ref_bvals_file = cli.SwitchAttr(['--ref_bshell_file'],
                                    cli.ExistingFile,
                                    help='reference bshell file',
                                    mandatory=True)

    outPrefix = cli.SwitchAttr(
        ['-outPrefix'],
        help='outPrefix for list of generated single shell images(,masks)')

    ncpu = cli.SwitchAttr(
        '--ncpu',
        help=
        'number of processes/threads to use (-1 for all available, may slow down your system)',
        default=4)

    def main(self):

        separateAllBshells(self.ref_csv, self.ref_bvals_file, self.ncpu,
                           self.outPrefix)
Пример #11
0
class MetaborgRelengTag(cli.Application):
    """
  Creates a tag in each submodule
  """

    tag = cli.SwitchAttr(names=['-n', '--name'],
                         argtype=str,
                         mandatory=True,
                         help='Name of the tag')
    description = cli.SwitchAttr(names=['-d', '--description'],
                                 argtype=str,
                                 mandatory=False,
                                 default=None,
                                 help='Description of the tag')

    confirmPrompt = cli.Flag(
        names=['-y', '--yes'],
        default=False,
        help='Answer warning prompts with yes automatically')

    def main(self):
        print('Creating a tag in each submodules')
        if not self.confirmPrompt:
            print(
                'This creates tags, changing the state of your repositories, do you want to continue?'
            )
            if not YesNo():
                return 1
        TagAll(self.parent.repo, self.tag, self.description)
        return 0
Пример #12
0
class ShowImageApp(cli.Application):
    'Display an image on the terminal'
    double = cli.Flag(
        ['-d', '--double'],
        help="Double resolution (only looks good with some fonts)")

    @cli.switch(['-c', '--colors'],
                cli.Range(1, 4),
                help="Level of color, 1-4")
    def colors_set(self, n):
        colors.use_color = n

    size = cli.SwitchAttr(['-s', '--size'],
                          help="Size, should be in the form 100x150")

    ratio = cli.SwitchAttr(['--ratio'],
                           float,
                           default=2.45,
                           help="Aspect ratio of the font")

    @cli.positional(cli.ExistingFile)
    def main(self, filename):

        size = None
        if self.size:
            size = map(int, self.size.split('x'))

        Image(size, self.ratio).show(filename, self.double)
Пример #13
0
class App(cli.Application):
    "Multiplies an image by its mask"

    mask = cli.SwitchAttr(
        ['-m', '--mask'],
        cli.ExistingFile,
        help='nifti mask, 3D image',
        mandatory=True)

    img = cli.SwitchAttr(
        ['-i', '--input'],
        cli.ExistingFile,
        help='nifti image, 3D/4D image',
        mandatory=True)

    out = cli.SwitchAttr(
        ['-o', '--output'],
        help= 'Masked input image',
        mandatory=True)

    dim= cli.SwitchAttr(
        ['-d', '--dimension'],
        help= 'Input image dimension: 3/4',
        mandatory=True)

    def main(self):

        ImageMath(self.dim, self.out, 'm', self.img, self.mask)
Пример #14
0
Файл: main.py Проект: apollet/ak
class AkModuleTest(AkSub):
    """Module testing tools.
        Start Odoo with test enabled.
        Possibilty to choose the db and one specific or all installed modules.
    """

    module = cli.SwitchAttr(["m", "module"], str, help="Concerned module")
    db = cli.SwitchAttr(['d'], str, help="Database for the tests")

    def main(self, *args):
        params = []
        if self.db:
            db = self.db
        else:
            config = self.parent.parent.read_erp_config_file()
            db = config.get('options', 'db_name')
        params += ['-d', db]
        module = self.module or 'all'
        if psql[db, "-c", ""] & TF:  # TF = result of cmd as True or False
            params += ['-u', module]
        else:
            createdb(db)
            params += ['-i', module]
        params += ['--stop-after-init', '--test-enable']
        cmd = 'bin/start_openerp'
        return self._exec(cmd, params)
Пример #15
0
Файл: main.py Проект: apollet/ak
class AkModuleSyntax(AkSub):
    """Pylint and Flake8 testing tools.
        Launch pylint and flake8 tests on 'modules' folder files
        or files of a specific folder in 'parts'
        using OCA quality tools configuration.
    """

    module = cli.SwitchAttr(["m", "module"], str, help="Concerned module")
    path = cli.SwitchAttr(["p", "path"], str, help="Path to a git repository")

    def main(self, *args):
        if self.path and self.module:
            raise Exception(
                "Can not have the params path and module at the same time")
        if self.module:
            find = local['find']['/workspace/parts', '-name', self.module] & BG
            path = find.stdout.split('\n')[0]
        else:
            if self.path:
                path = self.path
            else:
                path = '/workspace/modules'

        print "Launch flake8 and pylint tests on path : %s" % path

        with local.cwd(path):
            travis_dir = local.env['MAINTAINER_QUALITY_TOOLS'] + '/travis/'
            flake8 = local[travis_dir + 'test_flake8'](retcode=None)
            print flake8
            with local.env(TRAVIS_PULL_REQUEST="true",
                           TRAVIS_BRANCH="HEAD",
                           TRAVIS_BUILD_DIR='.'):
                pylint = local[travis_dir + 'test_pylint'](retcode=None)
                print pylint
Пример #16
0
class SimpleApp(cli.Application):
    @cli.switch(["a"])
    def spam(self):
        print("!!a")

    @cli.switch(["b", "bacon"],
                argtype=int,
                mandatory=True,
                envname="PLUMBUM_TEST_BACON")
    def bacon(self, param):
        """give me some bacon"""
        print("!!b", param)

    eggs = cli.SwitchAttr(["e"],
                          str,
                          help="sets the eggs attribute",
                          envname="PLUMBUM_TEST_EGGS")
    cheese = cli.Flag(["--cheese"], help="cheese, please")
    chives = cli.Flag(["--chives"], help="chives, instead")
    verbose = cli.CountOf(["v"], help="increases the verbosity level")
    benedict = cli.CountOf(["--benedict"],
                           help="""a very long help message with lots of
        useless information that nobody would ever want to read, but heck, we need to test
        text wrapping in help messages as well""")

    csv = cli.SwitchAttr(["--csv"], cli.Set("MIN", "MAX", int, csv=True))
    num = cli.SwitchAttr(["--num"], cli.Set("MIN", "MAX", int))

    def main(self, *args):
        old = self.eggs
        self.eggs = "lalala"
        self.eggs = old
        self.tailargs = args
class joinDividedShells(cli.Application):

    tar_csv = cli.SwitchAttr(
        ['--img_list'],
        cli.ExistingFile,
        help=
        'csv/txt file with first column for dwi and 2nd column for mask: dwi1,mask1\\ndwi2,mask2\\n...'
        'or just one column for dwi1\\ndwi2\\n...',
        mandatory=True)

    ref_bvals_file = cli.SwitchAttr(['--ref_bshell_file'],
                                    cli.ExistingFile,
                                    help='reference bshell file',
                                    mandatory=True)

    separatedPrefix = cli.SwitchAttr(
        ['--sep_prefix'],
        help=
        'prefix of the separated bshell files (.nii.gz, .bval, .bvec) if different from original files. '
        'Example: if separated bshell files are named as harmonized_originalName.nii.gz, then --sep_prefix=harmonized_',
        default=None)

    ncpu = cli.SwitchAttr(
        '--ncpu',
        help=
        'number of processes/threads to use (-1 for all available, may slow down your system)',
        default=4)

    def main(self):
        joinAllBshells(self.tar_csv, self.ref_bvals_file, self.separatedPrefix,
                       self.ncpu)
Пример #18
0
class App(cli.Application):
    """Convert a document to html and deploy the html with github pages.

    doc_path: path of a document, such as xxx-xxx.pdf or /path/to/xxx-xxx.epub
    repo: <username>/<repo> the repository to be deployed on github.
    """

    public = cli.Flag('--public', default=False,
                      help='Deploy to an public repository.')
    threshold = cli.SwitchAttr('--pdf-threshold', argtype=int, default=100,
                               help='Character number threshold. Only works for pdf file. When number of characters in a page is larger than threshold, then the page is thought as a text page.')
    rate = cli.SwitchAttr('--pdf-rate', argtype=float, default=0.6,
                          help="Minimum rate of text pages over total pages. Only works for pdf file. If the actual rate is below this value, the pdf file is thought as a scanned document, which won't be converted.")
    force = cli.Flag('--pdf-force', default=False,
                     help="Force to convert pdf despite whether it's scanned or not.")

    def main(self, doc_path, repo):
        # Split "<username>/<repo>"
        splited = repo.split('/')
        if not (len(splited) == 2 and all(splited)):
            print(f'Invalid repo: {repo}')
            sys.exit(1)

        cfg['USERNAME'], cfg['REPO'] = splited
        cfg['PUBLIC'] = self.public
        cfg['THRESHOLD'] = self.threshold
        cfg['RATE'] = self.rate
        cfg['FORCE'] = self.force

        _main(doc_path, cfg['REPO'])
Пример #19
0
class AtlasCsv(cli.Application):
    """Specify training images and labelmaps via a csv file.
    Put the images with any header in the first column, 
    and labelmaps with proper headers in the consecutive columns. 
    The headers in the labelmap columns will be used to name the generated atlas labelmaps.
    """

    target = cli.SwitchAttr(
        ['-t', '--target'],
        cli.ExistingFile,
        help='target image',
        mandatory=True)
    fusions = cli.SwitchAttr(
        ['--fusion'],
        cli.Set("avg", "wavg", "antsJointFusion", case_sensitive=False),
        help='Also create predicted labelmap(s) by combining the atlas labelmaps: '
             'avg is naive mathematical average, wavg is weighted average where weights are computed from MI '
             'between the warped atlases and target image, antsJointFusion is local weighted averaging', default='wavg')
    out = cli.SwitchAttr(
        ['-o', '--outPrefix'], help='output prefix, output labelmaps are saved as outPrefix-mask.nrrd, outPrefix-cingr.nrrd, ...',
        mandatory=True)
    threads= cli.SwitchAttr(['-n', '--nproc'],
        help='number of processes/threads to use (-1 for all available)',
        default= 8)
    debug = cli.Flag('-d', help='Debug mode, saves intermediate labelmaps to atlas-debug-<pid> in output directory')

    @cli.positional(cli.ExistingFile)
    def main(self, csvFile):
        trainingTable = pd.read_csv(csvFile._path)
        makeAtlases(self.target, trainingTable, self.out, self.fusions, int(self.threads), self.debug)
        logging.info('Made ' + self.out + '-*.nrrd')
Пример #20
0
class App(cli.Application):
    DESCRIPTION = "Extracts the baseline (b0) from a nrrd DWI.  Assumes \
the diffusion volumes are indexed by the last axis."

    dwimask = cli.SwitchAttr(['-m', '--mask'],
                             cli.ExistingFile,
                             help='DWI mask',
                             mandatory=False)
    dwi = cli.SwitchAttr(['-i', '--infile'],
                         cli.ExistingFile,
                         help='DWI nrrd image',
                         mandatory=True)
    out = cli.SwitchAttr(['-o', '--out'],
                         help='Extracted B0 nrrd image',
                         mandatory=True)

    def main(self):
        hdr = unu("head", self.dwi)[:-1]
        idx = get_b0_index(hdr)

        slicecmd = unu["slice", "-a", "3", "-p", str(idx), "-i", self.dwi]
        gzipcmd = unu["save", "-e", "gzip", "-f", "nrrd", "-o", self.out]
        if self.dwimask:
            maskcmd = unu["3op", "ifelse", "-w", "1", self.dwimask, "-", "0"]
            (slicecmd | maskcmd | gzipcmd) & FG
        else:
            (slicecmd | gzipcmd) & FG
Пример #21
0
class App(cli.Application):
    """Rigidly align a labelmap (usually a mask)."""

    infile = cli.SwitchAttr(['-i', '--infile'],
                            cli.ExistingFile,
                            help='structural',
                            mandatory=True)
    labelmap = cli.SwitchAttr(['-l', '--labelmap'],
                              cli.ExistingFile,
                              help='structural labelmap, usually a mask',
                              mandatory=True)
    target = cli.SwitchAttr(['-t', '--target'],
                            cli.ExistingFile,
                            help='target image',
                            mandatory=True)
    out = cli.SwitchAttr(['-o', '--out'],
                         help='output labelmap',
                         mandatory=True)

    def main(self):
        with TemporaryDirectory() as tmpdir:
            tmpdir = local.path(tmpdir)
            pre = tmpdir / 'ants'
            rigidxfm = pre + '0GenericAffine.mat'
            antsRegistrationSyN_sh['-t', 'r', '-m', self.infile, '-f',
                                   self.target, '-o', pre, '-n', 32] & FG
            antsApplyTransforms('-d', '3', '-i', self.labelmap, '-t', rigidxfm,
                                '-r', self.target, '-o', self.out,
                                '--interpolation', 'NearestNeighbor')
Пример #22
0
class HabitsAdd(ApplicationWithApi):
    DESCRIPTION = _("Add a habit <habit>")  # noqa: Q000
    priority = cli.SwitchAttr(
        ['-p', '--priority'],
        cli.Set('0.1', '1', '1.5', '2'),
        default='1',
        help=_("Priority (complexity) of a habit"))  # noqa: Q000
    direction = cli.SwitchAttr(['-d', '--direction'],
                               cli.Set('positive', 'negative', 'both'),
                               default='both',
                               help=_("positive/negative/both"))  # noqa: Q000

    def main(self, *habit: str):
        habit_str = ' '.join(habit)
        if not habit_str:
            self.log.error(_("Empty habit text!"))  # noqa: Q000
            return 1
        super().main()
        self.api.tasks.user.post(type='habit',
                                 text=habit_str,
                                 priority=self.priority,
                                 up=(self.direction != 'negative'),
                                 down=(self.direction != 'positive'))
        res = _("Added habit '{}' with priority {} and direction {}").format(
            habit_str, self.priority, self.direction)  # noqa: Q000
        print(prettify(res))
        Habits.invoke(config_filename=self.config_filename)
Пример #23
0
class App(cli.Application):
    """Extracts the baseline (b0) from a nrrd or nifti DWI.  Assumes
the diffusion volumes are indexed by the last axis."""

    dwimask = cli.SwitchAttr(['-m', '--mask'],
                             ExistingNrrdOrNifti,
                             help='DWI mask',
                             mandatory=False)
    dwi = cli.SwitchAttr(['-i', '--infile'],
                         ExistingNrrdOrNifti,
                         help='DWI',
                         mandatory=True)
    out = cli.SwitchAttr(['-o', '--out'],
                         cli.NonexistentPath,
                         help='Extracted B0 image',
                         mandatory=True)

    def main(self):
        if isNifti(self.dwi):
            fsl_extract_b0(self.dwi, self.out)
        elif isNrrd(self.dwi):
            nrrd_extract_b0(self.dwi, self.out)
        else:
            raise Exception("Invalid dwi format, must be nrrd or nifti")

        if self.dwimask:
            from plumbum.cmd import ImageMath
            ImageMath(3, self.out, 'm', self.out, self.dwimask)
Пример #24
0
class FsToDwi(cli.Application):
    """Registers Freesurfer labelmap to DWI space."""

    fsdir = cli.SwitchAttr(['-f', '--freesurfer'],
                           cli.ExistingDirectory,
                           help='freesurfer subject directory',
                           mandatory=True)
    dwi = cli.SwitchAttr(['-t', '--target'],
                         cli.ExistingFile,
                         help='target DWI',
                         mandatory=True)
    dwimask = cli.SwitchAttr(['-m', '--mask'],
                             cli.ExistingFile,
                             help='DWI mask',
                             mandatory=True)
    out = cli.SwitchAttr(['-o', '--out'],
                         cli.NonexistentPath,
                         help='output directory',
                         mandatory=True)

    def main(self, *args):
        if args:
            print("Unknown command {0!r}".format(args[0]))
            return 1
        if not self.nested_command:
            print("No command given")
            return 1  # error exit code
Пример #25
0
class App(cli.Application):
    """Runs tract_querier. Output is <out>/*.vtk"""

    ukf = cli.SwitchAttr(
        ['-i', '--in'],
        cli.ExistingFile,
        help='tractography file (.vtk or .vtk.gz), must be in RAS space',
        mandatory=True)
    fsindwi = cli.SwitchAttr(['-f', '--fsindwi'],
                             cli.ExistingFile,
                             help='Freesurfer labelmap in DWI space (nifti)',
                             mandatory=True)
    query = cli.SwitchAttr(['-q', '--query'],
                           help='tract_querier query file (e.g. wmql-2.0.qry)',
                           mandatory=False,
                           default=pjoin(FILEDIR, 'wmql-2.0.qry'))
    out = cli.SwitchAttr(['-o', '--out'],
                         help='output directory',
                         mandatory=True)

    nproc = cli.SwitchAttr(
        ['-n', '--nproc'],
        help='''number of threads to use, if other processes in your computer 
        becomes sluggish/you run into memory error, reduce --nproc''',
        default=N_PROC)

    def main(self):
        with TemporaryDirectory() as t:
            t = local.path(t)
            ukf = self.ukf
            fsindwi = self.fsindwi
            if '.gz' in self.ukf.suffix:
                ukf = t / 'ukf.vtk'
                from plumbum.cmd import gunzip
                (gunzip['-c', self.ukf] > ukf)()

            tract_querier = local['tract_querier']
            tract_math = local['tract_math']
            ukfpruned = t / 'ukfpruned.vtk'
            # tract_math(ukf, 'tract_remove_short_tracts', '2', ukfpruned)
            tract_math[ukf, 'tract_remove_short_tracts', '2', ukfpruned] & FG
            if not ukfpruned.exists():
                raise Exception(
                    "tract_math failed to make '{}'".format(ukfpruned))

            self.out = local.path(self.out)
            if self.out.exists():
                self.out.delete()
            self.out.mkdir()

            tract_querier['-t', ukfpruned, '-a', fsindwi, '-q', self.query,
                          '-o', self.out / '_'] & FG

            logging.info('Convert vtk field data to tensor data')

            # use the following multi-processed loop
            pool = Pool(int(self.nproc))
            pool.map_async(_activateTensors_py, self.out.glob('*.vtk'))
            pool.close()
            pool.join()
Пример #26
0
class AtlasCsv(cli.Application):
    """Specify training images and labelmaps via a csv file.
    Put the images with any header in the first column, 
    and labelmaps with proper headers in the consecutive columns. 
    The headers in the labelmap columns will be used to name the generated atlas labelmaps.
    """

    target = cli.SwitchAttr(['-t', '--target'],
                            cli.ExistingFile,
                            help='target image',
                            mandatory=True)
    fusions = cli.SwitchAttr(
        ['--fusion'],
        cli.Set("avg", "antsJointFusion", case_sensitive=False),
        help=
        'Also create predicted labelmap(s) by combining the atlas labelmaps')
    out = cli.SwitchAttr(['-o', '--out'],
                         help='output directory',
                         mandatory=True)

    @cli.positional(cli.ExistingFile)
    def main(self, csvFile):
        trainingTable = pd.read_csv(csvFile)
        makeAtlases(self.target, trainingTable, self.out, self.fusions)
        logging.info('Made ' + self.out)
Пример #27
0
class App(cli.Application):
    """Make html page of rendered wmql tracts. """

    wmqldirs = cli.SwitchAttr(
        ['-i'],
        help=
        'list of wmql directories, separated by space; list must be enclosed within quotes',
        mandatory=True)

    caseids = cli.SwitchAttr(
        ['-s'],
        help=
        'list of subject ids corresponding to wmql directories, separated by space; list must be enclosed within quotes',
        mandatory=True)

    out = cli.SwitchAttr(['-o'], help='Output directory', mandatory=True)

    def main(self):

        PY2BIN = getenv('PY2BIN', None)
        if not PY2BIN:
            raise EnvironmentError(
                'whitematteranalysis requires Python 2 interpreter, define export PY2BIN=/absolute/path/to/miniconda2/bin'
            )

        else:
            wmqlqc_tract_path = pjoin(PY2BIN,
                                      'wm_quality_control_tractography.py')
            if isfile(wmqlqc_tract_path):
                wm_quality_control_tractography = local[wmqlqc_tract_path]
            else:
                raise FileNotFoundError(
                    f'whitematteranalysis not found in {PY2BIN}, see README.md for instruction'
                )

        tuples = zip(self.caseids.split(),
                     map(local.path, self.wmqldirs.split()))
        vtks = [(caseid, vtk) for (caseid, d) in tuples
                for vtk in d // '*.vtk']
        keyfn = lambda x: local.path(x).name[:-4]
        groupedvtks = itertools.groupby(sorted(vtks, key=keyfn), key=keyfn)

        self.out = local.path(self.out)
        if self.out.exists():
            self.out.delete()
        self.out.mkdir()

        for group, vtks in groupedvtks:
            vtkdir = self.out / group
            qcdir = self.out / (group + '-qc')
            print("Make symlinks for vtk group {}".format(group))
            vtkdir.mkdir()
            for (caseid, vtk) in vtks:
                symlink = vtkdir / (vtk.name[:-4] + '_' + caseid + '.vtk')
                print("Make symlink for caseid '{}': {}".format(
                    caseid, symlink))
                vtk.symlink(symlink)
            print("Render tracts for vtk group {}".format(group))
            wm_quality_control_tractography[vtkdir, qcdir] & FG
Пример #28
0
class PatchSeqRemoveTheRestCLI(cli.Application):
    inputDir = cli.SwitchAttr("-i", help="Input dir")
    outputDir = cli.SwitchAttr("-o", help="Output dir")

    def main(self, *whatToKeep):
        s = PassesStack(
            [ImportPass(self.inputDir),
             RemoveTheRestPass(whatToKeep)], self.outputDir)
        s()
Пример #29
0
class VoodooMigrate(VoodooSub):
    """Migrate your odoo project

    First you need to checkout the voodoo-upgrade template
    available here : https://github.com/akretion/voodoo-upgrade
    (It's a template a voodoo but based on open-upgrade'

    Then go inside the repository clonned and launch the migration

    * For migrating from 6.1 to 8.0 run:
        voodoo migrate -b 7.0,8.0
    * For migrating from 6.1 to 9.0 run:
        voodoo migrate -b 7.0,8.0,9.0
    * For migrating and loading a database run:
        voodoo migrate -b 7.0,8.0 --db-file=tomigrate.dump

    """

    db_file = cli.SwitchAttr(["db-file"])
    apply_branch = cli.SwitchAttr(
        ["b", "branch"],
        help="Branch to apply split by comma ex: 7.0,8.0",
        mandatory=True)
    _logs = []

    def log(self, message):
        print(message)
        self._logs.append(message)

    def _run_ak(self, *params):
        start = datetime.now()
        cmd = "ak " + " ".join(params)
        self.log("Launch %s" % cmd)
        self.compose("run", "odoo", "ak", *params)
        end = datetime.now()
        self.log("Run %s in %s" % (cmd, end-start))

    def _main(self):
        if self.main_service != 'odoo':
            raise_error("This command is used only for migrating odoo project")
        versions = self.apply_branch.split(',')
        logs = ["\n\nMigration Log Summary:\n"]
        first = True
        for version in versions:
            start = datetime.now()
            self._run(git["checkout", version])
            self._run_ak("build")
            if self.db_file and first:
                self._run_ak("db", "load", "--force", self.db_file)
                first = False
            self._run_ak("upgrade")
            self._run_ak("db", "dump", "--force", "migrated_%s.dump" % version)
            end = datetime.now()
            self._log("Migrate to version %s in %s" % (version, end-start))
        for log in self._logs:
            logger.info(log)
Пример #30
0
class FsToDwi(cli.Application):
    """Registers Freesurfer labelmap to DWI space."""

    fsdir = cli.SwitchAttr(['-f', '--freesurfer'],
                           cli.ExistingDirectory,
                           help='freesurfer subject directory',
                           mandatory=True)

    dwi = cli.SwitchAttr(['--dwi'],
                         cli.ExistingFile,
                         help='target DWI',
                         mandatory=True)

    bvals_file = cli.SwitchAttr(['--bvals'],
                                cli.ExistingFile,
                                help='bvals file of the DWI',
                                mandatory=True)

    dwimask = cli.SwitchAttr(['--dwimask'],
                             cli.ExistingFile,
                             help='DWI mask',
                             mandatory=True)

    out = cli.SwitchAttr(['-o', '--outDir'],
                         help='output directory',
                         mandatory=True)

    force = cli.Flag(['--force'],
                     help='turn on this flag to overwrite existing output',
                     default=False,
                     mandatory=False)

    debug = cli.Flag(
        ['-d', '--debug'],
        help=
        'Debug mode, saves intermediate transforms to out/fs2dwi-debug-<pid>',
        default=False)

    def main(self):

        if not self.nested_command:
            print("No command given")
            sys.exit(1)

        self.fshome = local.path(os.getenv('FREESURFER_HOME'))

        if not self.fshome:
            print('Set FREESURFER_HOME first.')
            sys.exit(1)

        print('Making output directory')
        self.out = local.path(self.out)
        if self.out.exists() and self.force:
            print('Deleting existing directory')
            self.out.delete()
        self.out.mkdir()