Plot a GO DAG for the upper portion of a single Group of user GOs.
338559
def _get_gos_upper(self, ntpltgo1, max_upper, go2parentids):
        """"""
        # Get GO IDs which are in the hdrgo path
        goids_possible = ntpltgo1.gosubdag.go2obj.keys()
        # Get upper GO IDs which have the most descendants
        return self._get_gosrcs_upper(goids_possible, max_upper, go2parentids)
500390
def get_grouped(self, go_ntsets, go_all, gosubdag, **kws):
        """"""
        kws_grpd = {k:v for k, v in kws.items() if k in Grouped.kws_dict}
        kws_grpd['go2nt'] = self._init_go2ntpresent(go_ntsets, go_all, gosubdag)
        return Grouped(gosubdag, self.godag.version, **kws_grpd)
441504
def main():
    """"""
    # Load study, population, associations, and GoDag. Run GOEA.
    obj = GoeaCliFnc(GoeaCliArgs().args)
    # Reduce results to significant results (pval<value)
    results_specified = obj.get_results()
    # Print results in a flat list
    obj.prt_results(results_specified)
78278
def get_outfile(self, outfile, goids=None):
        """"""
        # 1. Use the user-specfied output filename for the GO Term plot
        if outfile != self.dflt_outfile:
            return outfile
        # 2. If only plotting 1 GO term, use GO is in plot name
        if goids is not None and len(goids) == 1:
            goid = next(iter(goids))
            goobj = self.gosubdag.go2obj[goid]
            fout = "GO_{NN}_{NM}".format(NN=goid.replace("GO:", ""), NM=goobj.name)
            return ".".join([re.sub(r"[\s#'()+,-./:<=>\[\]_}]", '_', fout), 'png'])
        # 3. Return default name
        return self.dflt_outfile
287906
def plot(self,init=None):
		""""""

		if not init:
			init=self
			init.plotstats={}
			init.unitfeats=self._getFeatValDict()

			sels=[]
			for k,v in sorted(init.unitfeats.items()):
				for kk,vv in v.items():
					sels.append((k,kk))

			conditions={'x':[],'y':[]}
			targets={'x':[],'y':[]}
			pkey={'x':[],'y':[]}

			print str(0)+"\t[no condition]"
			for selnum in range(len(sels)):
				print str(selnum+1)+"\t"+str(sels[selnum][0])+" = "+str(sels[selnum][1])
			print

			stepnum=0
			for a in sorted(conditions.keys()):
				stepnum+=1
				sel=raw_input(">> [step "+str(stepnum)+"/4] ["+a+" coord] [conditions of population] please type in the number (or numbers separated by commas)\n\tof the conditions determining the total population from which the percentage of the sample is taken:\n").strip()
				for x in sel.split(","):
					try:
						conditions[a].append(sels[int(x)-1])
						pkey[a]+=["of_"+str(sels[int(x)-1][0])+"_is_"+str(sels[int(x)-1][1])]
					except:
						pass

				stepnum+=1
				sel=raw_input(">> [step "+str(stepnum)+"/4] ["+a+" coord] [conditions of sample] please type in the number (or numbers separated by commas)\n\tof the conditions determining the sample:\n").strip()
				for x in sel.split(","):
					try:
						targets[a].append(sels[int(x)-1])
						pkey[a]+=[str(sels[int(x)-1][0])+"_is_"+str(sels[int(x)-1][1])]
					except:
						pass


			# print ">> POPULATION:"
			# print conditions
			#
			# print ">> SAMPLE:"
			# print targets

			init.population=conditions
			init.sample=targets

			init.pkey="X_"+"-".join(pkey['x'])+"."+"Y_"+"-".join(pkey['y'])
			print ">> plotting: "+ init.pkey


		if not hasattr(self,'bestParses'):
			for child in self.children:
				child.plot(init)
		else:
			posdict={}
			minparselen = min([len(parse.positions) for parse in self.bestParses()])
			maxparselen = max([len(parse.positions) for parse in self.bestParses()])
			#if not hasattr(self,'minparselen'): return None
			for posnum in range(maxparselen):
				posdict[posnum]={'x':[],'y':[]}
				for parse in self.bestParses():
					try:
						posfeats=parse.positions[posnum].posfeats()
					except IndexError:
						# there is no position number `posnum` in this parse `parse`
						continue

					for a in ['x','y']:
						conds=init.population[a]
						targs=init.sample[a]

						condsHold=True
						if len(conds):
							for cond in conds:
								condK=cond[0]
								condV=cond[1]

								try:
									if posfeats[condK]==condV:
										continue
								except:
									condsHold=False
									break
								condsHold=False
								break

						if condsHold:
							targsHold=True
							for targ in targs:
								targK=targ[0]
								targV=targ[1]

								try:
									if posfeats[targK]==targV:
										continue
								except:
									targsHold=False
									break
								targsHold=False
								break

							if targsHold:
								posdict[posnum][a].append(1)
							else:
								posdict[posnum][a].append(0)

			for a in ['x','y']:
				if not posdict[posnum][a]:
					print "<< not enough data: position number ("+str(posnum)+") empty on dimension ["+str(a)+"]"
					return None

			init.plotstats[self.getName()]=posdict
			if (self!=init): return None

		totalstrs=[]
		totaltsvs=[]
		for textname,posdict in sorted(init.plotstats.items()):

			tsv="posnum\tnumobs\tx_mean\ty_mean\tx_std\ty_std\n"
			xs=[]
			ys=[]
			for posnum,xydict in posdict.items():
				x_avg,x_std=mean_stdev(xydict['x'])
				y_avg,y_std=mean_stdev(xydict['y'])

				assert len(xydict['x'])==len(xydict['y'])

				xs.append(x_avg)
				ys.append(y_avg)
				tsv+="\t".join(str(bb) for bb in [(posnum+1),len(xydict['x']),x_avg,y_avg,x_std,y_std])+"\n"


			ccmsg=""
			cc=None
			p=None
			try:
				from statlib import stats
				(cc,p)=stats.pearsonr(xs,ys)

				aa=makeminlength("    correlation coefficient: ",int(being.linelen/1.4))+str(cc)
				bb=makeminlength("    p-value: ",int(being.linelen/1.4))+str(p)

				tsv+=aa.strip().replace(":",":\t")+"\n"
				tsv+=bb.strip().replace(":",":\t")+"\n"

				for l in tsv.split("\n"):
					totaltsvs.append(textname+"_"+l)

				ccmsg+=aa+"\n"+bb+"\n"

			except:
				pass

			writeToFile(textname,init.pkey,tsv,extension="tsv")
			totaltsvs.append(tsv)

			"""
			try:
				strtowrite=self.makeBubbleChart(posdict,".".join([textname,init.pkey]),(cc,p))
				totalstrs+=[strtowrite]
				writeToFile(textname,init.pkey,self._getBubbleHeader()+strtowrite+self._getBubbleFooter(),extension="htm")
			except:
				pass
			"""

			if ccmsg:
				print ccmsg

		if not self.classname()=="Corpus": return None

		"""
		writeToFile(self.getName(),
			init.pkey,
			self._getBubbleHeader()+"\n<br/><br/><br/><br/><br/><br/><br/><br/>\n".join(totalstrs)+self._getBubbleFooter(),
			iscorpus=True,
			extension="htm")
		"""

		writeToFile(self.getName(),init.pkey,"\n\n\n\n".join(totaltsvs),iscorpus=True,extension="tsv")
637352
def write_dag(self, out=sys.stdout):
        """"""
        for rec in sorted(self.values()):
            print(rec, file=out)
729945
def mvp_gg(self):
        
        output = []
        for node in self.most_visited_path_nodes():
            if max(node.child_N) <= 1:
                break
            output.append(coords.to_gtp(coords.from_flat(node.fmove)))
        return ' '.join(output)
622953
def _init_go_sources(self, go_sources_arg, go2obj_arg):
        """"""
        gos_user = set(go_sources_arg)
        if 'children' in self.kws and self.kws['children']:
            gos_user |= get_leaf_children(gos_user, go2obj_arg)
        gos_godag = set(go2obj_arg)
        gos_source = gos_user.intersection(gos_godag)
        gos_missing = gos_user.difference(gos_godag)
        if not gos_missing:
            return gos_source
        sys.stdout.write("{N} GO IDs NOT FOUND IN GO DAG: {GOs}\n".format(
            N=len(gos_missing), GOs=" ".join([str(e) for e in gos_missing])))
        return gos_source
1041988
def _get_go2nt(self, goids):
        """"""
        go2nt_all = self.grprobj.go2nt
        return {go:go2nt_all[go] for go in goids}
130919
def plot_band(plt_in, band_name, rsr_obj, **kwargs):
    """"""
    if 'platform_name_in_legend' in kwargs:
        platform_name_in_legend = kwargs['platform_name_in_legend']
    else:
        platform_name_in_legend = False

    detectors = rsr_obj.rsr[band_name].keys()
    # for det in detectors:
    det = sorted(detectors)[0]
    resp = rsr_obj.rsr[band_name][det]['response']
    wvl = rsr_obj.rsr[band_name][det]['wavelength']

    resp = np.ma.masked_less_equal(resp, minimum_response)
    wvl = np.ma.masked_array(wvl, resp.mask)
    resp.compressed()
    wvl.compressed()

    if platform_name_in_legend:
        plt_in.plot(wvl, resp, label='{platform} - {band}'.format(
            platform=rsr_obj.platform_name, band=band_name))
    else:
        plt_in.plot(wvl, resp, label='{band}'.format(band=band_name))

    return plt_in
688152
def plt_goea_results(fout_png, goea_results, *args, **kws):
    """"""
    engine = kws['engine'] if 'engine' in kws else 'pydot'
    godagsmall = OboToGoDagSmall(goea_results=goea_results).godag
    godagplot = GODagSmallPlot(godagsmall, *args, goea_results=goea_results, **kws)
    godagplot.plt(fout_png, engine)
1283182
def get_go_color(self, **kws):
        """"""
        ret = {'GOs':set(), 'go2color':{}}
        if 'GO' in kws:
            self._goargs(ret, kws['GO'])
        if 'go_file' in kws:
            self._rdtxt_gos(ret, kws['go_file'])
        if 'draw-children' in kws:
            ret['GOs'].update(get_leaf_children(ret['GOs'], self.go2obj))
        # If there have been no GO IDs explicitly specified by the user
        if not ret['GOs']:
            # If the GO-DAG is sufficiently small, print all GO IDs
            if len(self.go2obj) < self.max_gos:
                main_gos = set(o.id for go, o in self.go2obj.items() if go != o.id)
                go_leafs = set(go for go, o in self.go2obj.items() if not o.children)
                ret['GOs'] = go_leafs.difference(main_gos)
            else:
                raise RuntimeError("GO IDs NEEDED")
        go2obj = {go:self.go2obj[go] for go in ret['GOs']}
        ret['GOs'] = set(get_go2obj_unique(go2obj))
        return [ret['GOs'], ret['go2color']]
944594
def _get_user_groups(self, user):
        '''
        
        '''
        return [g.gr_name for g in grp.getgrall()
                if user in g.gr_mem] + [grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name]
344666
def main():
    """"""

    # test example below taken from GMMRA by Azari, Chen, Parkes, & Xia
    cand_set = [0, 1, 2]
    votes = [[0, 1, 2], [1, 2, 0]]

    mmagg = MMPLAggregator(cand_set)
    gamma = mmagg.aggregate(votes, epsilon=1e-7, max_iters=20)
    print(mmagg.alts_to_ranks, mmagg.ranks_to_alts)
    assert([mmagg.get_ranking(i) for i in cand_set] == [1,0,2])
    print(gamma)
910977
def plot_groups_unplaced(self, fout_dir=".", **kws_pltargs):
        """"""
        hdrgos = self.grprobj.get_hdrgos_unplaced()
        pltargs = PltGroupedGosArgs(self.grprobj, fout_dir=fout_dir, **kws_pltargs)
        return self._plot_groups_hdrgos(hdrgos, pltargs)
453102
def get_go2txt(grprobj_cur, grp_go2color, grp_go2bordercolor):
        """"""
        goids_main = set(o.id for o in grprobj_cur.gosubdag.go2obj.values())
        hdrobj = grprobj_cur.hdrobj
        grprobj_all = Grouper("all",
                              grprobj_cur.usrgos.union(goids_main), hdrobj, grprobj_cur.gosubdag)
        # Adds section text to all GO terms in plot (misses middle GO terms)
        _secdflt = hdrobj.secdflt
        _hilight = set(grp_go2color.keys()).union(grp_go2bordercolor)
        ret_go2txt = {}
        # Keep sections text only if GO header, GO user, or not Misc.
        if hdrobj.sections:
            for goid, txt in grprobj_all.get_go2sectiontxt().items():
                if txt == 'broad':
                    continue
                if txt != _secdflt or goid in _hilight:
                    ret_go2txt[goid] = txt
        return ret_go2txt
1177431
def _get_pltdotstrs(self, hdrgos_usr, **kws):
        """"""
        import datetime
        import timeit
        dotstrs_all = []
        tic = timeit.default_timer()
        # Loop through GO groups. Each group of GOs is formed under a single "header GO"
        hdrgo2usrgos, go2obj = self._get_plt_data(hdrgos_usr)
        # get dot strings with _get_dotstrs_curs
        for hdrgo, usrgos in hdrgo2usrgos.items():
            dotstrs_cur = self._get_dotgraphs(
                hdrgo, usrgos,
                pltargs=PltGroupedGosArgs(self.grprobj, **kws),
                go2parentids=get_go2parents_go2obj(go2obj))
            dotstrs_all.extend(dotstrs_cur)
        sys.stdout.write("\nElapsed HMS: {HMS} to write ".format(
            HMS=str(datetime.timedelta(seconds=(timeit.default_timer()-tic)))))
        sys.stdout.write("{P:5,} GO DAG plots for {H:>5,} GO grouping headers\n".format(
            H=len(hdrgo2usrgos), P=len(dotstrs_all)))
        return sorted(set(dotstrs_all))