Exemple #1
0
def afni_3dinfo_ad3( fname  ) :
    '''Get voxelsize information.
    
    output:
    list of dims 
    total volume (float)

    '''

    fname.replace("[", "'[")
    fname.replace("]", "]'")

    cmd = '''3dinfo      \
                -ad3     \
                {dset}
    '''.format( dset=fname )

    status, so, se = BASE.simple_shell_exec(cmd, capture=1)
    
    print("++ Voxel dimensions of {} are (in mm):\n"
          "       {}".format(fname, '  '.join(so.split())))
    dims = so.split()

    voxvol  = 1.0
    dims_fl = []
    for ad in dims:
        adfl = float(ad)
        voxvol*= adfl
        dims_fl.append(adfl)
    print("   ... so volume is (in mm**3): {}"
          "".format(voxvol))

    return dims_fl, voxvol
Exemple #2
0
def afni_3dBrickStat_nz_count( fname  ) :
    '''Get mask size information.

    Return int: number of nonzero voxels

    Check for zero voxels in mask (exit with error).

    '''

    fname.replace("[", "'[")
    fname.replace("]", "]'")

    cmd = '''3dBrickStat          \
                -non-zero         \
                -count            \
                {dset}
    '''.format( dset=fname )

    status, so, se = BASE.simple_shell_exec(cmd, capture=1)

    Nnzvox = int(so.strip())

    print("++ Voxel count of mask '{}' is (in mm): {}"
          "".format(fname, Nnzvox))

    if not(Nnzvox) :
        print("** ERROR: zero voxels in mask '{}'"
              "".format(fname))
        sys.exit(6)

    return Nnzvox
Exemple #3
0
def afni_3dinfo_is_single_vol( fname1, verb=0 ) :
    '''Has one volume been specified (either a 3D vol, or a 4D, with
    subbrick selectors)?

    Returns True or False

    '''

    fname1.replace("[", "'[") ; fname1.replace("]", "]'")

    cmd = '''3dinfo            \
                -nv            \
                {dset1}        \
    '''.format( dset1=fname1 )

    status, so, se = BASE.simple_shell_exec(cmd, capture=1)
    
    SINGLE_VOL = int(so.split()[0]) == 1

    if verb > 0 :
        print("++ Is this a single volume?\n"
              "     {}\n"
              "   --> {}"
              "".format( fname1, SINGLE_VOL ))

    return SINGLE_VOL
Exemple #4
0
def afni_3dinfo_same_grid( fname1, fname2 ) :
    '''Are 2 dsets on the same grid? 

    Returns True or False

    '''

    fname1.replace("[", "'[") ; fname1.replace("]", "]'")
    fname2.replace("[", "'[") ; fname2.replace("]", "]'")

    cmd = '''3dinfo            \
                -same_grid     \
                {dset1}        \
                {dset2}
    '''.format( dset1=fname1, dset2=fname2 )

    status, so, se = BASE.simple_shell_exec(cmd, capture=1)
    
    SAME_GRID = bool(int(so.split()[0]))

    print("++ Are these dsets on same grid?\n"
          "     {}\n     {}\n"
          "   --> {}"
          "".format(fname1, fname2, SAME_GRID ))

    return SAME_GRID
Exemple #5
0
def afni_3droistats( fname  ) :
    '''Get ROI size information.

    Now using the 'AFNI_ATLAS_NAME_TYPE = name' env variable, so even
    with both short and long labels present for ROIs, only the short
    will be used (and numbers will match).

    '''

    fname.replace("[", "'[")
    fname.replace("]", "]'")

    cmd = '''3dROIstats      \
                -DAFNI_ATLAS_NAME_TYPE=name \
                -nzvoxels    \
                -nobriklab   \
                -mask {dset} \
                {dset}
    '''.format( dset=fname )

    status, so, se = BASE.simple_shell_exec(cmd, capture=1)
    
    # split by line
    so_lined = so.split("\n")

    if len(so_lined) > 3 :
            print("** ERROR: unexpected length in 3dROIstats output: \n"
              "{}".format(so_lined))
            sys.exit(4)

    # ['File', 'Sub-brick', 'Mean_ROI', 'NZcount_ROI', ... ]
    so_labs = so_lined[0].split() ; Nlabs = len(so_labs)
    # ['FILE_NAME', 'SUBBRICK_IDX', 'ROI_IDX', 'ROI_COUNT', ...]
    so_vals = so_lined[1].split() ; Nvals = len(so_vals)

    #print("HEY")
    #print(so_lined[0])
    #print(so_lined[1])

    if Nlabs != Nvals :
        print("** ERROR: length of labels {} does not match that of vals {}"
              "".format(Nlabs, Nvals))
        sys.exit(2)
    elif Nlabs % 2 :
        print("** ERROR: expected even number of values per row, not {}"
              "".format(Nlabs))
        sys.exit(2)

    so_null  = so_lined[2].strip()
    if so_null :
        print("** ERROR: non-null 3rd line: \n"
              "{}".format(so_null))
        sys.exit(3)

    return so_labs, so_vals
Exemple #6
0
def parse_args_this_prog(full_argv):

    argv = full_argv[1:]
    Narg = len(argv)

    if not (Narg):
        print(help_string_this_prog)
        sys.exit(0)

    i = 0
    while i < Narg:
        if argv[i] == "{ver}".format(**all_opts):
            print(ver)
            sys.exit(0)

        elif argv[i] == "{date}".format(**all_opts):
            print(date)
            sys.exit(0)

        elif argv[i] == "{help}".format(**all_opts) or \
             argv[i] == "{h}".format(**all_opts) :
            print(help_string_this_prog)
            sys.exit(0)

        elif argv[i] == "{hview}".format(**all_opts):
            prog = os.path.basename(full_argv[0])
            cmd = 'apsearch -view_prog_help {}'.format(prog)
            BASE.simple_shell_exec(cmd)
            sys.exit(0)

        # --------- finish -------------

        else:
            print("** ERROR: unknown opt: '{}'".format(argv[i]))
            sys.exit(2)
        i += 1

    # --------------------------------------------------------------------

    return 0
Exemple #7
0
def copy_images_to_subdir(iopts):

    count_fail = 0
    list_fail = []

    for ii in range(iopts.nmedia):
        iname = iopts.list_media[ii]
        oname = iopts.subdir + '/' + os.path.basename(iopts.list_media[ii])
        a, b, c = ab.simple_shell_exec("\cp {} {}".format(iname, oname))
        if a:
            count_fail += 1
            list_fail.append(iname)

    return count_fail, list_fail
Exemple #8
0
def exec_or_error(cmd, error_msg="See above!!!", showerr=1, showcmd=1):
    """return text output from the given command
       if showcmd, print the cmd
       if showerr and there is a command error, show it
       This will exit on status other than 0 so BE CAREFULL!!!
    """

    status, cmd_output, error_out = afni_base.simple_shell_exec(cmd,capture=1)
    if showcmd:
        print(cmd)
    if showerr:
        print(error_out)
    if status != 0:
        if error_msg != "See above!!!":
            error_msg = error_msg+"!!!"
        printNcolor("** ERROR:"," "+error_msg,"Red","White","Bold")
        sys.exit(1)

    return status,cmd_output
Exemple #9
0
   def check_for_progs(self, plist, repos=0, show_missing=0):
      """see whether the programs seem to be found, and show version

         repos:        if set, append any found to self.repo_prog list
         show_missing: if set, show empty prog line to indicate failed test
      """
      # check for programs
      nfound = 0
      for prog in plist:
         # the version file is treated specially here
         if prog == 'AFNI_version.txt':
            vinfo = UTIL.read_AFNI_version_file()
            if vinfo != '':
               nfound += 1
            else:
               self.comments.append('missing %s, maybe package is old'%prog)
            print('%-20s : %s' % (prog, vinfo))
            continue

         # as is afni
         elif prog == 'afni label':
            nfound += 1   # do not call this an error yet
            s, v = self.get_prog_version('afni')
            print('%-20s : %s' % ('', self.afni_label))
            continue

         # XQuartz/X11?
         elif prog in ['XQuartz', 'X11']:
            s, v = self.get_prog_version(prog)
            print('%-20s : %s' % ('%s version'%prog, v))
            continue

         # and python - add a comment if they are using version 3 (no continue)
         #            - do not 'continue'
         elif prog == 'python':
            s, vstr = self.get_prog_version(prog)
            vf = self.get_python_ver_float()
            mesg = ''
            if vf >= 3.0:
               mesg = 'have python version %s, some programs need 2.7.x' % vstr
            elif vf < 2.7:
               mesg = 'have python version %s, consider using 2.7.x' % vstr
            if mesg != '':
               self.comments.append(mesg)

         # now run the normal test

         cmd = 'which %s' % prog
         s, so, se = BASE.simple_shell_exec(cmd, capture=1)
         if not s: # found one
            # if we do not yet know of a repo program, mark as this one
            if repos and self.repo_prog == '': self.repo_prog = prog

            progpath = so.strip()
            print('%-20s : %s' % (cmd, progpath))
            s, v = self.get_prog_version(prog)
            if s: print('%-20s : %s' % ('%s version'%prog, v))

            # save some results
            if prog == 'afni': self.afni_ver = v
            if prog == 'python': self.python_prog = progpath
               
            nfound += 1
         elif show_missing:
            print('%-20s : %s' % (cmd, se))

      print('')

      return nfound
Exemple #10
0
 def get_afni_dir(self):
    s, so, se = BASE.simple_shell_exec('which afni', capture=1)
    if s: return ''
    adir = so.strip()
    if adir[-5:] == '/afni': return adir[0:-5]
    else:                    return ''
Exemple #11
0
def parse_args(full_argv):
    """Go through user-entered options and fill an object with the values.
    These will be used to setup plotting.

    """

    argv = full_argv[1:]
    Narg = len(argv)

    if not (Narg):
        print(help_string)
        sys.exit(0)

    # initialize objs
    iopts = iopts_obj()
    iopts.full_cmd = full_argv

    i = 0
    while i < Narg:
        if argv[i] == "{ver}".format(**opts_dict):
            print(ver)
            sys.exit(0)

        elif argv[i] == "{date}".format(**opts_dict):
            print(date)
            sys.exit(0)

        elif argv[i] == "{help}".format(**opts_dict) or \
             argv[i] == "{h}".format(**opts_dict) :
            print(help_string)
            sys.exit(0)

        elif argv[i] == "{hview}".format(**opts_dict):
            prog = os.path.basename(full_argv[0])
            cmd = 'apsearch -view_prog_help {}'.format(prog)
            ab.simple_shell_exec(cmd)
            sys.exit(0)

        # ---------- req ---------------

        # can be a list of many
        elif argv[i] == "{in_mat}".format(**opts_dict):
            if i >= Narg:
                ab.ARG_missing_arg(argv[i])
            i += 1
            while i < Narg:
                if opts_list.__contains__(argv[i]):
                    i -= 1
                    break
                else:
                    iopts.in_mat.append(argv[i])
                    i += 1

        elif argv[i] == "{prefix}".format(**opts_dict):
            if i >= Narg:
                ab.ARG_missing_arg(argv[i])
            i += 1
            iopts.prefix = argv[i]

        # ---------- opt ---------------

        # can be a list of many
        elif argv[i] == "{pars}".format(**opts_dict):
            if i >= Narg:
                ab.ARG_missing_arg(argv[i])
            i += 1
            while i < Narg:
                if opts_list.__contains__(argv[i]):
                    i -= 1
                    break
                else:
                    iopts.pars_list.append(argv[i])
                    i += 1

        elif argv[i] == "{in_csv}".format(**opts_dict):
            if i >= Narg:
                ab.ARG_missing_arg(argv[i])
            i += 1
            iopts.in_csv = argv[i]

        elif argv[i] == "{in_listfile}".format(**opts_dict):
            if i >= Narg:
                ab.ARG_missing_arg(argv[i])
            i += 1
            iopts.in_listfile = argv[i]

        # --------- finish -------------

        else:
            print("** ERROR: unknown opt: '{}'".format(argv[i]))
            sys.exit(2)
        i += 1

    if iopts.check_req():
        print("   -------------------------------")
        ab.EP("Problem with input arguments. See detailed whining above.")

    iopts.finish_defs()

    return iopts
    # might have several scripts to parse
    for ii in range(iopts.ninfile):
        ainfo.add_text(lmsar.read_text_to_list(iopts.infile_list[ii]))

        # only include TOC for the first file
        oscript_txt, orst_txt = \
            lmsar.interpret_MSAR_list( ainfo.text_list[ii], iopts, ii,
                                       DO_TOC=not(ii) )
        ainfo.add_oscript_txt(oscript_txt)
        ainfo.add_orst_txt(orst_txt)

    # ------------------ write output files ------------------

    # Make dir to hold script/any images
    a, b, c = ab.simple_shell_exec("\mkdir -p {}".format(iopts.subdir))
    if not (a):
        print("++ Wrote directory to hold scripts")
    else:
        print("** Badness writing dir to hold scripts {}".format(iopts.subdir))
        sys.exit(12)

    # write script to local dir
    for ii in range(iopts.nscript):
        fff = open(iopts.oname_script_list[ii], 'w')
        fff.write(ainfo.oscript_txt_list[ii])
        fff.close()

    if iopts.tarball_name:
        all_script = ' '.join(iopts.oname_script_list)
        # \\ needed before the t, because \t is a TAB!
Exemple #13
0
def parse_args_mat_plot(full_argv):
    """Go through user-entered options and fill an object with the values.
    These will be used to setup plotting.

    """

    argv = full_argv[1:]
    Narg = len(argv)

    if not (Narg):
        print(help_string_mat_plot)
        sys.exit(0)

    # initialize objs
    iopts = iopts_to_plot_mat2d()
    iopts.full_cmd = full_argv

    i = 0
    while i < Narg:
        if argv[i] == "{ver}".format(**opts_dict):
            print(ver)
            sys.exit(0)

        elif argv[i] == "{date}".format(**opts_dict):
            print(date)
            sys.exit(0)

        elif argv[i] == "{help}".format(**opts_dict) or \
             argv[i] == "{h}".format(**opts_dict) :
            print(help_string_mat_plot)
            sys.exit(0)

        elif argv[i] == "{hview}".format(**opts_dict):
            prog = os.path.basename(full_argv[0])
            cmd = 'apsearch -view_prog_help {}'.format(prog)
            ab.simple_shell_exec(cmd)
            sys.exit(0)

        # ---------- req ---------------

        elif argv[i] == "{input}".format(**opts_dict):
            if i >= Narg:
                ab.ARG_missing_arg(argv[i])
            i += 1
            iopts.input = argv[i]

        # ---------- opt ---------------

        elif argv[i] == "{prefix}".format(**opts_dict):
            if i >= Narg:
                ab.ARG_missing_arg(argv[i])
            i += 1
            iopts.prefix = argv[i]

        # can be a list of many
        elif argv[i] == "{pars}".format(**opts_dict):
            if i >= Narg:
                ab.ARG_missing_arg(argv[i])
            i += 1
            while i < Narg:
                if opts_list.__contains__(argv[i]):
                    i -= 1
                    break
                else:
                    iopts.pars_list.append(argv[i])
                    i += 1

        elif argv[i] == "{ftype}".format(**opts_dict):
            if i >= Narg:
                ab.ARG_missing_arg(argv[i])
            i += 1
            iopts.ftype = argv[i]

        elif argv[i] == "{dpi}".format(**opts_dict):
            if i >= Narg:
                ab.ARG_missing_arg(argv[i])
            i += 1
            iopts.dpi = float(argv[i])

        elif argv[i] == "{vmin}".format(**opts_dict):
            if i >= Narg:
                ab.ARG_missing_arg(argv[i])
            i += 1
            iopts.vmin = float(argv[i])

        elif argv[i] == "{vmax}".format(**opts_dict):
            if i >= Narg:
                ab.ARG_missing_arg(argv[i])
            i += 1
            iopts.vmax = float(argv[i])

        elif argv[i] == "{fs_xticks}".format(**opts_dict):
            if i >= Narg:
                ab.ARG_missing_arg(argv[i])
            i += 1
            iopts.fs_xticks = float(argv[i])

        elif argv[i] == "{fs_yticks}".format(**opts_dict):
            if i >= Narg:
                ab.ARG_missing_arg(argv[i])
            i += 1
            iopts.fs_yticks = float(argv[i])

        elif argv[i] == "{fs_title}".format(**opts_dict):
            if i >= Narg:
                ab.ARG_missing_arg(argv[i])
            i += 1
            iopts.fs_title = float(argv[i])

        elif argv[i] == "{fs_cbar}".format(**opts_dict):
            if i >= Narg:
                ab.ARG_missing_arg(argv[i])
            i += 1
            iopts.fs_cbar = float(argv[i])

        elif argv[i] == "{cbar_n_intervals}".format(**opts_dict):
            if i >= Narg:
                ab.ARG_missing_arg(argv[i])
            i += 1
            iopts.cbar_n_intervals = int(argv[i])

        elif argv[i] == "{cbar}".format(**opts_dict):
            if i >= Narg:
                ab.ARG_missing_arg(argv[i])
            i += 1
            iopts.cbar = argv[i]

        elif argv[i] == "{cbar_width_perc}".format(**opts_dict):
            if i >= Narg:
                ab.ARG_missing_arg(argv[i])
            i += 1
            iopts.cbar_width_perc = float(argv[i])

        elif argv[i] == "{figsize_x}".format(**opts_dict):
            if i >= Narg:
                ab.ARG_missing_arg(argv[i])
            i += 1
            iopts.figsize_x = float(argv[i])

        elif argv[i] == "{figsize_y}".format(**opts_dict):
            if i >= Narg:
                ab.ARG_missing_arg(argv[i])
            i += 1
            iopts.figsize_y = float(argv[i])

        elif argv[i] == "{hold_image}".format(**opts_dict):
            iopts.hold_image = True

        elif argv[i] == "{tight_layout}".format(**opts_dict):
            iopts.tight_layout = True

        elif argv[i] == "{cbar_off}".format(**opts_dict):
            iopts.cbar_off = True

        elif argv[i] == "{xticks_off}".format(**opts_dict):
            iopts.xticks_off = True

        elif argv[i] == "{yticks_off}".format(**opts_dict):
            iopts.yticks_off = True

        # --------- finish -------------

        else:
            print("** ERROR: unknown opt: '{}'".format(argv[i]))
            sys.exit(2)
        i += 1

    if iopts.check_req():
        print("   -------------------------------")
        ab.EP("Problem with input arguments. See detailed whining above.")

    iopts.finish_defs()

    return iopts
Exemple #14
0
    def check_special_opts(self, argv):
        """process known '-optlist_* options' and other global_opts,
           nuking them from argv

           some options are terminal
        """

        # global options (some take a parameter)
        global_opts = [
            '-optlist_verbose', '-optlist_no_show_count',
            '-optlist_show_global_opts', '-optlist_show_valid_opts',
            '-optlist_show_argv_array', '-h_find', '-h_view', '-hview'
        ]

        alen = len(argv)

        if '-optlist_verbose' in argv:
            ind = argv.index('-optlist_verbose')
            self.verb = 4
            argv[ind:ind + 1] = []
            print('++ optlist: setting verb to %d' % self.verb)
        if '-optlist_no_show_count' in argv:
            ind = argv.index('-optlist_no_show_count')
            self.show_count = 0
            argv[ind:ind + 1] = []
            if self.verb > 1: print('++ optlist: clearing show_count')

        # terminal options (all end in exit)

        # terminal opts specific to this library
        if '-optlist_show_global_opts' in argv:
            global_opts.sort()
            print("-- global OptionList options (%d):" % len(global_opts))
            print("     %s\n" % '\n     '.join(global_opts))
            sys.exit(0)

        if '-optlist_show_valid_opts' in argv:
            oname = '-optlist_show_valid_opts'
            ind = argv.index(oname)
            prog = os.path.basename(argv[0])
            self.show(verb=1)
            sys.exit(0)

        if '-optlist_show_argv_array' in argv:
            oname = '-optlist_show_argv_array'
            ind = argv.index(oname)
            # this takes one parameter, which must be in list
            atype = ''
            if alen >= ind + 2:
                atype = argv[ind + 1]
            if atype not in self.argv_array_types:
                print("** %s: requires a parameter in %s" \
                      % (oname, self.argv_array_types))
                sys.exit(1)
            argv[ind:ind + 2] = []
            self.show_argv_array = atype

        # terminal general options
        if '-h_find' in argv:
            oname = '-h_find'
            ind = argv.index(oname)
            prog = os.path.basename(argv[0])
            if ind == alen - 1:
                print('** global opt %s needs %s option as parameter' \
                      % (oname, prog))
                sys.exit(1)
            cmd = 'apsearch -phelp %s -word %s' % (prog, argv[ind + 1])
            if self.verb > 1:
                print('++ optlist: applying %s via: %s' % (oname, cmd))
            BASE.simple_shell_exec(cmd)
            sys.exit(0)

        if '-h_view' in argv:
            oname = '-h_view'
            ind = argv.index(oname)
            prog = os.path.basename(argv[0])
            cmd = 'apsearch -view_prog_help %s' % prog
            if self.verb > 1:
                print('++ optlist: applying %s via: %s' % (oname, cmd))
            BASE.simple_shell_exec(cmd)
            sys.exit(0)

        if '-hview' in argv:
            oname = '-hview'
            ind = argv.index(oname)
            prog = os.path.basename(argv[0])
            cmd = 'apsearch -view_prog_help %s' % prog
            if self.verb > 1:
                print('++ optlist: applying %s via: %s' % (oname, cmd))
            BASE.simple_shell_exec(cmd)
            sys.exit(0)

        if '-hweb' in argv: oname = '-hweb'
        elif '-h_web' in argv: oname = '-h_web'
        else: oname = ''
        if oname != '':
            ind = argv.index(oname)
            prog = os.path.basename(argv[0])
            cmd = 'apsearch -web_prog_help %s' % prog
            if self.verb > 1:
                print('++ optlist: applying %s via: %s' % (oname, cmd))
            BASE.simple_shell_exec(cmd)
            sys.exit(0)

        if self.verb > 1:
            print('-- argv: orig len %d, new len %d' % (alen, len(argv)))