Given GOEA namedtuples, return nts w/P-value in string format.
772578
def get_nts_strpval(self, fmt="{:8.2e}"):
        """"""
        objntmgr = MgrNts(self.goea_results)
        dcts = objntmgr.init_dicts()
        # pylint: disable=line-too-long
        pval_flds = set(k for k in self._get_fieldnames(next(iter(self.goea_results))) if k[:2] == 'p_')
        for fld_float in pval_flds:
            fld_str = "s_" + fld_float[2:]
            objntmgr.add_f2str(dcts, fld_float, fld_str, fmt)
        return objntmgr.mknts(dcts)
718555
def _hack_namedtuple(cls):
    
    name = cls.__name__
    fields = cls._fields

    def __reduce__(self):
        return (_restore, (name, fields, tuple(self)))
    cls.__reduce__ = __reduce__
    cls._is_namedtuple_ = True
    return cls
1329090
def imt2tup(string):
    
    s = string.strip()
    if not s.endswith(')'):
        # no parenthesis, PGA is considered the same as PGA()
        return (s,)
    name, rest = s.split('(', 1)
    return (name,) + tuple(float(x) for x in ast.literal_eval(rest[:-1] + ','))
1210669
def namedtuple_asdict(obj):
    
    if obj is None:
        return obj
    if hasattr(obj, "_asdict"):  # detect namedtuple
        return OrderedDict(zip(obj._fields, (namedtuple_asdict(item)
                                             for item in obj)))
    if isinstance(obj, str):  # iterables - strings
        return obj
    if hasattr(obj, "keys"):  # iterables - mapping
        return OrderedDict(zip(obj.keys(), (namedtuple_asdict(item)
                                            for item in obj.values())))
    if hasattr(obj, "__iter__"):  # iterables - sequence
        return type(obj)((namedtuple_asdict(item) for item in obj))
    # non-iterable cannot contain namedtuples
    return obj
665446
def get_named_group(self, t, i):
        """"""

        index = i.index
        value = [t]
        try:
            c = next(i)
            if c != "<":
                raise SyntaxError("Group missing '<' at %d!" % (i.index - 1))
            value.append(c)
            c = next(i)
            if c in _DIGIT:
                value.append(c)
                c = next(i)
                while c != '>':
                    if c in _DIGIT:
                        value.append(c)
                    c = next(i)
                value.append(c)
            elif c in _LETTERS_UNDERSCORE:
                value.append(c)
                c = next(i)
                while c != '>':
                    if c in _WORD:
                        value.append(c)
                    c = next(i)
                value.append(c)
            else:
                raise SyntaxError("Invalid group character at %d!" % (i.index - 1))
        except StopIteration:
            raise SyntaxError("Unmatched '<' at %d!" % index)

        return ''.join(value)
640317
def prt_nts(self, desc2nts, prt=sys.stdout, prtfmt=None):
        """"""
        # deprecated
        # Set print format string
        if prtfmt is None:
            prtfmt = "{{hdr1usr01:2}} {FMT}\n".format(FMT=self.grprobj.gosubdag.prt_attr['fmt'])
        # 1-D: data to print is a flat list of namedtuples
        if 'flat' in desc2nts:
            prt_txt(prt, desc2nts['flat'], prtfmt=prtfmt)
        # 2-D: data to print is a list of [(section, nts), ...
        else:
            WrSectionsTxt.prt_sections(prt, desc2nts['sections'], prtfmt)
57696
def get_d1nts(self):
        """"""
        data = []
        ntdata = cx.namedtuple("NtPrt", "D1 NS dcnt depth GO name")
        namespace = None
        for ntlet in sorted(self.goone2ntletter.values(),
                            key=lambda nt: [nt.goobj.namespace, -1 * nt.dcnt, nt.D1]):
            goobj = ntlet.goobj
            goid = goobj.id
            assert len(goobj.parents) == 1
            if namespace != goobj.namespace:
                namespace = goobj.namespace
                ntns = self.ns2nt[namespace]
                pobj = ntns.goobj
                ns2 = self.str2ns[goobj.namespace]
                data.append(ntdata._make([" ", ns2, ntns.dcnt, pobj.depth, pobj.id, pobj.name]))
            data.append(ntdata._make(
                [ntlet.D1, self.str2ns[namespace], ntlet.dcnt, goobj.depth, goid, goobj.name]))
        return data
782296
def dflt_sortby_ntgoea(ntgoea):
        """"""
        return [ntgoea.enrichment,
                ntgoea.namespace,
                ntgoea.p_uncorrected,
                ntgoea.depth,
                ntgoea.GO]
1040741
def _init_go2res(**kws):
        """"""
        if 'goea_results' in kws:
            return {res.GO:res for res in kws['goea_results']}
        if 'go2nt' in kws:
            return kws['go2nt']
982899
def _init_prt_flds(self):
        """"""
        # Create namedtuple fields or copy namedtuple fields
        if 'go2nt' not in self.kws:
            return self.__init_prt_flds()
        else:
            return next(iter(self.kws['go2nt'].values()))._asdict()
1219609
def _get_dict(names, ndarrays):
        """"""
        nset = set()
        for nm in names:
            if nm in nset:
                raise ValueError('Duplicate names detected, %s' % str(names))
            nset.add(nm)
        return dict(zip(names, ndarrays))
62928
def prt_goids(self, goids=None, prtfmt=None, sortby=True, prt=sys.stdout):
        """"""
        if goids is None:
            goids = self.go_sources
        nts = self.get_nts(goids, sortby)
        if prtfmt is None:
            prtfmt = self.prt_attr['fmta']
        for ntgo in nts:
            key2val = ntgo._asdict()
            prt.write("{GO}\n".format(GO=prtfmt.format(**key2val)))
        return nts
721910
def to_namedtuple(self):
        
        keys = filter(lambda x: not x.startswith("_"), self.__dict__)
        opt_nt = namedtuple(self.__class__.__name__, keys)
        filtered_dict = dict(map(lambda x: (x, self.__dict__[x]), keys))

        return opt_nt(**filtered_dict)
300405
def prt_ntgos(self, prt, ntgos):
        """"""
        for ntgo in ntgos:
            key2val = ntgo._asdict()
            prt.write("{GO_LINE}\n".format(GO_LINE=self.prtfmt.format(**key2val)))
374790
def load_env(keys=[], name='NT', use_getpass=False):
    
    NT = namedtuple(name, keys)
    if use_getpass:
        values = [os.getenv(x) or getpass.getpass(x) for x in keys]
    else:
        values = [os.getenv(x) or input(x) for x in keys]
    return NT(*values)
1143886
def get_go_ntsets(self, go_fins):
        """"""
        nts = []
        ntobj = namedtuple('NtGOFiles', 'hdr go_set, go_fin')
        go_sets = self._init_go_sets(go_fins)
        hdrs = [os.path.splitext(os.path.basename(f))[0] for f in go_fins]
        assert len(go_fins) == len(go_sets)
        assert len(go_fins) == len(hdrs)
        for hdr, go_set, go_fin in zip(hdrs, go_sets, go_fins):
            nts.append(ntobj(hdr=hdr, go_set=go_set, go_fin=go_fin))
        return nts
1289864
def prt_nts(prt, nts, varname, spc='    '):
    """"""
    first_nt = nts[0]
    nt_name = type(first_nt).__name__
    prt.write("import collections as cx\n\n")
    prt.write("NT_FIELDS = [\n")
    for fld in first_nt._fields:
        prt.write('{SPC}"{F}",\n'.format(SPC=spc, F=fld))
    prt.write("]\n\n")
    prt.write('{NtName} = cx.namedtuple("{NtName}", " ".join(NT_FIELDS))\n\n'.format(
        NtName=nt_name))
    prt.write("# {N:,} items\n".format(N=len(nts)))
    prt.write("# pylint: disable=line-too-long\n")
    prt.write("{VARNAME} = [\n".format(VARNAME=varname))
    for ntup in nts:
        prt.write("{SPC}{NT},\n".format(SPC=spc, NT=ntup))
    prt.write("]\n")