Visualize learning result.
356583
def visualize_learning_result(self, state_key):
        '''
        
        '''
        x, y = state_key
        map_arr = copy.deepcopy(self.__map_arr)
        goal_point_tuple = np.where(map_arr == self.__end_point_label)
        goal_x, goal_y = goal_point_tuple
        map_arr[y][x] = "@"
        self.__map_arr_list.append(map_arr)
        if goal_x == x and goal_y == y:
            for i in range(10):
                key = len(self.__map_arr_list) - (10 - i)
                print("Number of searches: " + str(key))
                print(self.__map_arr_list[key])
            print("Total number of searches: " + str(self.t))
            print(self.__map_arr_list[-1])
            print("Goal !!")
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")
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)
570881
function summariser(results) {
    var response = [],
        callback = function(output) {
            response.push(output);
        };

    var passed = 0;
    if (results.hasOwnProperty('passed')) {
        passed = countSpecs(results.passed);
    }
    var failed = 0;
    if (results.hasOwnProperty('failed')) {
        failed = countSpecs(results.failed);
    }
    var pending = 0;

    if (results.hasOwnProperty('pending')) {
        pending = countSpecs(results.pending);
    }
    var total = passed + failed + pending;

    coloriseOutput(total + ' Specs defined', 'bold', callback);
    if (total > 0) {
        coloriseOutput(passed + ' Passed' + displayPercentage(total, passed), 'green', callback);
        coloriseOutput(failed + ' Failed' + displayPercentage(total, failed), 'red', callback);
        coloriseOutput(pending + ' Pending' + displayPercentage(total, pending), 'yellow', callback);
    }
    return response;
}
57761
def plot_results(fout_png, goea_results, *args, **kws):
    """"""
    if "{NS}" not in fout_png:
        plt_goea_results(fout_png, goea_results, *args, **kws)
    else:
        # Plot separately by NS: BP, MF, CC
        ns2goea_results = cx.defaultdict(list)
        for rec in goea_results:
            ns2goea_results[rec.NS].append(rec)
        for ns_name, ns_res in ns2goea_results.items():
            png = fout_png.format(NS=ns_name)
            plt_goea_results(png, ns_res, *args, **kws)
295081
def result_report_class_wise(self):
        

        results = self.results_class_wise_metrics()

        output = self.ui.section_header('Class-wise metrics', indent=2) + '\n'

        output += self.ui.row(
            'Scene label', 'Ncorr', 'Nref', 'Accuracy',
            widths=[20, 12, 12, 12],
            separators=[True, False, True, False],
            indent=4
        ) + '\n'

        output += self.ui.row('-', '-', '-', '-') + '\n'

        for scene_label in self.scene_label_list:
            output += self.ui.row(
                scene_label,
                results[scene_label]['count']['Ncorr'],
                results[scene_label]['count']['Nref'],
                results[scene_label]['accuracy']['accuracy'] * 100,
                types=['str', 'int', 'int', 'float1_percentage']
            ) + '\n'

        return output
517094
def print_results(self, results, min_ratio=None, indent=False, pval=0.05, prt=sys.stdout):
        """"""
        results_adj = self.get_adj_records(results, min_ratio, pval)
        self.print_results_adj(results_adj, indent, prt)
222475
def echo_verbose_results(data, no_color):
    """"""
    click.echo()
    click.echo(
        '\n'.join(
            '{}: {}'.format(key, val) for key, val in data['info'].items()
        )
    )
    click.echo()
    for test in data['tests']:
        if test['outcome'] == 'passed':
            fg = 'green'
        elif test['outcome'] == 'skipped':
            fg = 'yellow'
        else:
            fg = 'red'

        name = parse_test_name(test['name'])
        echo_style(
            '{} {}'.format(name, test['outcome'].upper()),
            no_color,
            fg=fg
        )
1178778
function learn() {
    var i;

    var lengthcount = pixels.length;
    var alphadec = 30 + ((samplefac - 1) / 3);
    var samplepixels = lengthcount / (3 * samplefac);
    var delta = ~~(samplepixels / ncycles);
    var alpha = initalpha;
    var radius = initradius;

    var rad = radius >> radiusbiasshift;

    if (rad <= 1) rad = 0;
    for (i = 0; i < rad; i++)
      radpower[i] = alpha * (((rad * rad - i * i) * radbias) / (rad * rad));

    var step;
    if (lengthcount < minpicturebytes) {
      samplefac = 1;
      step = 3;
    } else if ((lengthcount % prime1) !== 0) {
      step = 3 * prime1;
    } else if ((lengthcount % prime2) !== 0) {
      step = 3 * prime2;
    } else if ((lengthcount % prime3) !== 0)  {
      step = 3 * prime3;
    } else {
      step = 3 * prime4;
    }

    var b, g, r, j;
    var pix = 0; // current pixel

    i = 0;
    while (i < samplepixels) {
      b = (pixels[pix] & 0xff) << netbiasshift;
      g = (pixels[pix + 1] & 0xff) << netbiasshift;
      r = (pixels[pix + 2] & 0xff) << netbiasshift;

      j = contest(b, g, r);

      altersingle(alpha, j, b, g, r);
      if (rad !== 0) alterneigh(rad, j, b, g, r); // alter neighbours

      pix += step;
      if (pix >= lengthcount) pix -= lengthcount;

      i++;

      if (delta === 0) delta = 1;
      if (i % delta === 0) {
        alpha -= alpha / alphadec;
        radius -= radius / radiusdec;
        rad = radius >> radiusbiasshift;

        if (rad <= 1) rad = 0;
        for (j = 0; j < rad; j++)
          radpower[j] = alpha * (((rad * rad - j * j) * radbias) / (rad * rad));
      }
    }
  }
626707
def do_visualize(self, line):
        """"""

        if not self.current:
            self._help_noontology()
            return

        line = line.split()

        try:
            # from ..viz.builder import action_visualize
            from ..ontodocs.builder import action_visualize
        except:
            self._print("This command requires the ontodocs package: `pip install ontodocs`")
            return

        import webbrowser
        url = action_visualize(args=self.current['file'], fromshell=True)
        if url:
            webbrowser.open(url)
        return
760669
def plot_data():
    '''

    '''

    var = ['temp', 'oxygen', 'salinity', 'fluorescence-ECO', 'density', 'PAR', 'turbidity', 'fluorescence-CDOM']
    # colorbar limits for each property
    lims = np.array([[26, 33], [0, 10], [0, 36], [0, 6], [1005, 1025], [0, 0.6], [0, 2], [0, 9]])  # reasonable values
    # lims = np.array([[20,36], [26,33], [1.5,5.6], [0,4], [0,9], [0,1.5]]) # values to show colormaps

    for fname in fnames:
        fig, axes = plt.subplots(nrows=4, ncols=2)
        fig.set_size_inches(20, 10)
        fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99, wspace=0.0, hspace=0.07)
        i = 0
        for ax, Var, cmap in zip(axes.flat, var, cmaps):  # loop through data to plot up

            # get variable data
            lat, lon, z, data = test.read(Var, fname)

            map1 = ax.scatter(lat, -z, c=data, cmap=cmap, s=10, linewidths=0., vmin=lims[i, 0], vmax=lims[i, 1])
            # no stupid offset
            y_formatter = mpl.ticker.ScalarFormatter(useOffset=False)
            ax.xaxis.set_major_formatter(y_formatter)
            if i == 6:
                ax.set_xlabel('Latitude [degrees]')
                ax.set_ylabel('Depth [m]')
            else:
                ax.set_xticklabels([])
                ax.set_yticklabels([])
            ax.set_ylim(-z.max(), 0)
            ax.set_xlim(lat.min(), lat.max())
            cb = plt.colorbar(map1, ax=ax, pad=0.02)
            cb.set_label(cmap.name + ' [' + '$' + cmap.units + '$]')
            i += 1

        fig.savefig('figures/' + fname.split('.')[0] + '.png', bbox_inches='tight')
497397
def draw(self):
        

        indices = np.arange(len(self.classes_))
        prev = np.zeros(len(self.classes_))

        colors = resolve_colors(
            colors=self.colors,
            n_colors=len(self.classes_))

        for idx, row in enumerate(self.predictions_):
            self.ax.bar(indices, row, label=self.classes_[idx],
                        bottom=prev, color=colors[idx])
            prev += row

        return self.ax
341680
def draw(self, true_classes):
        """"""
        range_max = self.range_max
        num_sampled = self.num_sampled
        ctx = true_classes.context
        log_range = math.log(range_max + 1)
        num_tries = 0
        true_classes = true_classes.reshape((-1,))
        sampled_classes, num_tries = self.sampler.sample_unique(num_sampled)

        true_cls = true_classes.as_in_context(ctx).astype('float64')
        prob_true = ((true_cls + 2.0) / (true_cls + 1.0)).log() / log_range
        count_true = self._prob_helper(num_tries, num_sampled, prob_true)

        sampled_classes = ndarray.array(sampled_classes, ctx=ctx, dtype='int64')
        sampled_cls_fp64 = sampled_classes.astype('float64')
        prob_sampled = ((sampled_cls_fp64 + 2.0) / (sampled_cls_fp64 + 1.0)).log() / log_range
        count_sampled = self._prob_helper(num_tries, num_sampled, prob_sampled)
        return [sampled_classes, count_true, count_sampled]
1372149
def display(self):
        """"""
        if self.data is None:
            return

        if self.scene is not None:
            self.y_scrollbar_value = self.verticalScrollBar().value()
            self.scene.clear()

        self.create_chan_labels()
        self.create_time_labels()

        window_start = self.parent.value('window_start')
        window_length = self.parent.value('window_length')

        time_height = max([x.boundingRect().height() for x in self.idx_time])
        label_width = window_length * self.parent.value('label_ratio')
        scene_height = (len(self.idx_label) * self.parent.value('y_distance') +
                        time_height)

        self.scene = QGraphicsScene(window_start - label_width,
                                    0,
                                    window_length + label_width,
                                    scene_height)
        self.setScene(self.scene)

        self.idx_markers = []
        self.idx_annot = []
        self.idx_annot_labels = []

        self.add_chan_labels()
        self.add_time_labels()
        self.add_traces()
        self.display_grid()
        self.display_markers()
        self.display_annotations()

        self.resizeEvent(None)
        self.verticalScrollBar().setValue(self.y_scrollbar_value)
        self.parent.info.display_view()
        self.parent.overview.display_current()
1054900
def plot_diagrams(results, configs, compiler, out_dir):
    """"""
    compiler_fn = make_filename(compiler)
    total = psutil.virtual_memory().total  # pylint:disable=I0011,E1101
    memory = int(math.ceil(byte_to_gb(total)))

    images_dir = os.path.join(out_dir, 'images')

    for config in configs:
        out_prefix = '{0}_{1}'.format(config['name'], compiler_fn)

        plot_diagram(
            config,
            results,
            images_dir,
            os.path.join(images_dir, '{0}.png'.format(out_prefix))
        )

        with open(
            os.path.join(out_dir, '{0}.qbk'.format(out_prefix)),
            'wb'
        ) as out_f:
            qbk_content = """{0}
Measured on a {2} host with {3} GB memory. Compiler used: {4}.

[$images/metaparse/{1}.png [width 100%]]
""".format(config['desc'], out_prefix, platform.platform(), memory, compiler)
            out_f.write(qbk_content)
615960
def draw_scores(self):
        """"""
        x1, y1 = self.WIDTH - self.BORDER - 200 - 2 * self.BORDER, self.BORDER
        width, height = 100, 60
        self.screen.fill((255, 255, 255), (x1, 0, self.WIDTH - x1, height + y1))
        self._draw_score_box(self.score_label, self.score, (x1, y1), (width, height))
        x2 = x1 + width + self.BORDER
        self._draw_score_box(self.best_label, self.manager.score, (x2, y1), (width, height))
        return (x1, y1), (x2, y1), width, height
786972
def visualize_explanation(explanation, label=None):
    
    if not sys.version_info[:2] >= (3, 5):
      raise IndicoError("Python >= 3.5+ is required for explanation visualization")

    try:
      from colr import Colr as C
    except ImportError:
      raise IndicoError("Package colr >= 0.8.1 is required for explanation visualization.")

    cursor = 0
    text = explanation['text']
    for token in explanation.get('token_predictions'):
        try:
            class_confidence = token.get('prediction')[label]
        except KeyError:
            raise IndicoError("Invalid label: {}".format(label))

        if class_confidence > 0.5:
            fg_color = (255, 255, 255)
        else:
            fg_color = (0, 0, 0)
        rg_value = 255 - int(class_confidence * 255)
        token_end = token.get('token').get('end')
        token_text = text[cursor:token_end]
        cursor = token_end
        sys.stdout.write(
          str(C().b_rgb(
            rg_value, rg_value, 255
          ).rgb(
            fg_color[0], fg_color[1], fg_color[2], token_text
          ))
        )
    sys.stdout.write("\n")
    sys.stdout.flush()