Draw top3 proposals for each gt.
    Args:
        proposals: NPx4
        proposal_scores: NP
        gt_boxes: NG
766765
def draw_proposal_recall(img, proposals, proposal_scores, gt_boxes):
    
    box_ious = np_iou(gt_boxes, proposals)    # ng x np
    box_ious_argsort = np.argsort(-box_ious, axis=1)
    good_proposals_ind = box_ious_argsort[:, :3]   # for each gt, find 3 best proposals
    good_proposals_ind = np.unique(good_proposals_ind.ravel())

    proposals = proposals[good_proposals_ind, :]
    tags = list(map(str, proposal_scores[good_proposals_ind]))
    img = viz.draw_boxes(img, proposals, tags)
    return img, good_proposals_ind
931671
def draw(self, **kwargs):
        
        # Prepare the data
        bins  = np.arange(self.N)
        words = [self.features[i] for i in self.sorted_[:self.N]]
        freqs = {}

        # Set up the bar plots
        if self.conditional_freqdist_:
            for label, values in sorted(self.conditional_freqdist_.items(), key=itemgetter(0)):
                freqs[label] = [
                    values[i] for i in self.sorted_[:self.N]
                ]
        else:
            freqs['corpus'] = [
                self.freqdist_[i] for i in self.sorted_[:self.N]
            ]

        # Draw a horizontal barplot
        if self.orient == 'h':
            # Add the barchart, stacking if necessary
            for label, freq in freqs.items():
                self.ax.barh(bins, freq, label=label, align='center')

            # Set the y ticks to the words
            self.ax.set_yticks(bins)
            self.ax.set_yticklabels(words)

            # Order the features from top to bottom on the y axis
            self.ax.invert_yaxis()

            # Turn off y grid lines and turn on x grid lines
            self.ax.yaxis.grid(False)
            self.ax.xaxis.grid(True)

        # Draw a vertical barplot
        elif self.orient == 'v':
            # Add the barchart, stacking if necessary
            for label, freq in freqs.items():
                self.ax.bar(bins, freq, label=label, align='edge')

            # Set the y ticks to the words
            self.ax.set_xticks(bins)
            self.ax.set_xticklabels(words, rotation=90)

            # Turn off x grid lines and turn on y grid lines
            self.ax.yaxis.grid(True)
            self.ax.xaxis.grid(False)

        # Unknown state
        else:
            raise YellowbrickValueError(
                "Orientation must be 'h' or 'v'"
            )
1342967
def draw(self):
        '''
        
        '''
        if self.__conditional_flag is True:
            return np.concatenate((self.__create_samples(), self.__create_samples()), axis=1)
        else:
            return self.__create_samples()
422769
def p_statement_draw3(p):
    
    p[0] = make_sentence('DRAW3',
                         make_typecast(TYPE.integer, p[2], p.lineno(3)),
                         make_typecast(TYPE.integer, p[4], p.lineno(5)),
                         make_typecast(TYPE.float_, p[6], p.lineno(5)))
13535
def drawstarslist(self, dictlist, r = 10, colour = None):
        
        
        self.checkforpilimage()
        colour = self.defaultcolour(colour)
        self.changecolourmode(colour)
        self.makedraw()
        
        
        for star in dictlist:
            self.drawcircle(star["x"], star["y"], r = r, colour = colour, label = star["name"])
            #self.writelabel(star["x"], star["y"], star["name"], r = r, colour = colour)
        
        if self.verbose :
            print "I've drawn %i stars." % len(dictlist)
1209793
private void drawDistribution( Graphics2D g2 , List<Point2D_F64> candidates ,
					  int offX, int offY , double scale) {
		findStatistics();

		// draw all the features, adjusting their size based on the first score
		g2.setColor(Color.RED);
		g2.setStroke(new BasicStroke(3));

		double normalizer;
		if( scorer.getScoreType().isZeroBest() )
			normalizer = best*containmentFraction;
		else
			normalizer = Math.abs(best)*(Math.exp(-1.0/containmentFraction));

		for( int i = 0; i < candidates.size(); i++ ) {
			Point2D_F64 p = candidates.get(i);

			double s = associationScore[i];

			// scale the circle based on how bad it is
			double ratio = 1-Math.abs(s-best)/normalizer;
			if( ratio < 0 )
				continue;

			int r = maxCircleRadius - (int)(maxCircleRadius*ratio);
			if( r > 0 ) {
				int x = (int)(p.x*scale+offX);
				int y = (int)(p.y*scale+offY);
				g2.drawOval(x-r,y-r,r*2+1,r*2+1);
			}
		}

		// draw the best feature
		g2.setColor(Color.GREEN);
		g2.setStroke(new BasicStroke(10));
		int w = maxCircleRadius*2+1;
		Point2D_F64 p = candidates.get(indexBest);
		int x = (int)(p.x*scale+offX);
		int y = (int)(p.y*scale+offY);
		g2.drawOval(x-maxCircleRadius,y-maxCircleRadius,w,w);
	}
649919
def top3_full(votes):
    
    #create array of zeros, length = q
    res = np.zeros(2 * len(votes[0]) + (len(votes[0]) * (len(votes[0]) - 1)))

    #iterate through each vote
    for vote in votes:
        #set verification boolean to true
        ver = True
        #check if vote belongs to c1 < c2 < c3, c2 < c3 < c1... moment
        for i in range(0, len(votes[0])):
            if vote[i][0] != vote[i - 1][0] + 1 and vote[i][0] != 0:
                ver = False
                break
        if ver:
            res[len(votes[0]) + (len(votes[0]) * (len(votes[0]) - 1)) + vote[0][0]] += 1

        #increment moment of top ranked choice ranked at the top
        res[vote[0][0]] += 1

        #top two moment
        add = 0
        if vote[0][0] > vote[1][0]:
            add = 1
        res[(vote[0][0] + 1) * (len(votes[0]) - 1) + add + vote[1][0]] += 1

    res /= len(votes) #normalize moments
    
    return res
439534
function() {
    var numStars = 2000;
    var geometry = new THREE.BufferGeometry();
    var positions = new Float32Array( numStars * 3 );
    var radius = this.STAGE_SIZE - 1;
    var v = new THREE.Vector3();
    for (var i = 0; i < positions.length; i += 3) {
      v.set(this.random(i + 23) - 0.5, this.random(i + 24), this.random(i + 25) - 0.5);
      v.normalize();
      v.multiplyScalar(radius);
      positions[i  ] = v.x;
      positions[i+1] = v.y;
      positions[i+2] = v.z;
    }
    geometry.addAttribute('position', new THREE.BufferAttribute(positions, 3));
    geometry.setDrawRange(0, 0); // don't draw any yet
    var material = new THREE.PointsMaterial({size: 0.01, color: 0xCCCCCC, fog: false});
    this.stars.setObject3D('mesh', new THREE.Points(geometry, material));
  }
142372
function draw_rich_layout(resp){
	
	///
	/// Get the rich layout from the returned document if
	/// possible. Note the use of JSON, supplied by jQuery,
	/// instead of out internal method bbop.json.parse.
	///
	var doc = resp.documents()[0];

	var topo_graph = new bbop.model.bracket.graph();
	topo_graph.load_json(JSON.parse(doc[topo_graph_field]));

	var trans_graph = new bbop.model.graph();
	trans_graph.load_json(JSON.parse(doc[trans_graph_field]));

	//ll('to: ' + doc['topology_graph']);
	//ll('tr: ' + doc['transitivity_graph']);
	//ll('ro: ' + anchor._current_acc);
	//ll('g: ' + topo_graph.get_parent_nodes(anchor._current_acc));
	var rich_layout = topo_graph.rich_bracket_layout(anchor._current_acc,
							 trans_graph);
	//ll("rl: " + bbop.core.dump(rich_layout));

	///
	/// Next, produce the raw HTML skeleton.
	/// TODO: Keep a cache of the interesting ids for adding
	/// events later.
	///

	// I guess we'll just start by making the list.
	var tl_attrs = {
	    'class': 'bbop-js-ui-browse'
	};
	var top_level = new bbop.html.list([], tl_attrs);

	// Store the navigation anf info buttons.
	var nav_button_hash = {};
	var info_button_hash = {};

	// Cycle down through the brackets, adding spaces every time
	// we go down another level.
	var spacing = '&nbsp;&nbsp;&nbsp;&nbsp;';
	var spaces = spacing;
	loop(rich_layout, // for every level
	     function(layout_level){
		 loop(layout_level, // for every item at this level
		      function(level_item){			  

			  var nid = level_item[0];
			  var lbl = level_item[1];
			  var rel = level_item[2];
			  
			  // For various sections, decide to run image
			  // (img) or text code depending on whether
			  // or not it looks like we have a real URL.
			  var use_img_p = true;
			  if( base_icon_url == null || base_icon_url == '' ){
			      use_img_p = false;
			  }

			  // Clickable acc span.
			  // No images, so the same either way. Ignore
			  // it if we're current.
			  var nav_b = null;
			  if(anchor._current_acc == nid){
			      var inact_attrs = {
				  'class': 'bbop-js-text-button-sim-inactive',
				  'title': 'Current term.'
			      };
			      nav_b = new bbop.html.span(nid, inact_attrs);
			  }else{
			      var tbs = bbop.widget.display.text_button_sim;
			      var bttn_title =
				  'Reorient neighborhood onto this node (' +
				  nid + ').';
			      nav_b = new tbs(nid, bttn_title);
			      nav_button_hash[nav_b.get_id()] = nid;
			  }

			  // Clickable info span. A little difference
			  // if we have images.
			  var info_b = null;
			  if( use_img_p ){
			      // Do the icon version.
			      var imgsrc = bbop.core.resourcify(base_icon_url,
								info_icon,
								image_type);
			      info_b =
				  new bbop.html.image({'alt': info_alt,
						       'title': info_alt,
				  		       'src': imgsrc,
				  		       'generate_id': true});
			  }else{
			      // Do a text-only version.
			      info_b =
				  new bbop.html.span('<b>[i]</b>',
						     {'generate_id': true});
			  }
			  info_button_hash[info_b.get_id()] = nid;

			  // "Icon". If base_icon_url is defined as
			  // something try for images, otherwise fall
			  // back to this text ick.
			  var icon = null;
			  if( use_img_p ){
			      // Do the icon version.
			      var ialt = '[' + rel + ']';
			      var isrc = null;
			      if(anchor._current_acc == nid){
				  isrc = bbop.core.resourcify(base_icon_url,
			      				      current_icon,
							      image_type);
			      }else{
				  isrc = bbop.core.resourcify(base_icon_url,
			      				      rel, image_type);
			      }
			      icon =
				  new bbop.html.image({'alt': ialt,
						       'title': rel,
				  		       'src': isrc,
				  		       'generate_id': true});
			  }else{
			      // Do a text-only version.
			      if(anchor._current_acc == nid){
				  icon = '[[->]]';
			      }else if( rel && rel.length && rel.length > 0 ){
				  icon = '[' + rel + ']';
			      }else{
				  icon = '[???]';
			      }
			  }

			  // Stack the info, with the additional
			  // spaces, into the div.
			  top_level.add_to(spaces,
					   icon,
					   nav_b.to_string(),
					   lbl,
					   info_b.to_string());
		      }); 
		 spaces = spaces + spacing;
	     }); 

	// Add the skeleton to the doc.
	jQuery('#' + anchor._interface_id).empty();
	jQuery('#' + anchor._interface_id).append(top_level.to_string());

	///
	/// Finally, attach any events to the browser HTML doc.
	///

	// Navigation.
	loop(nav_button_hash,
	     function(button_id, node_id){

		 jQuery('#' + button_id).click(
		     function(){
			 var tid = jQuery(this).attr('id');
			 var call_time_node_id = nav_button_hash[tid];
			 //alert(call_time_node_id);
			 anchor.draw_browser(call_time_node_id);
		     });
	     });

	// Information.
	loop(info_button_hash,
	     function(button_id, node_id){

		 jQuery('#' + button_id).click(
		     function(){
			 var tid = jQuery(this).attr('id');
			 var call_time_node_id = info_button_hash[tid];
			 var call_time_doc = resp.get_doc(call_time_node_id);
			 anchor._info_button_callback(call_time_node_id,
						      call_time_doc);
		     });
	     });
    }
750417
def generate_fpn_proposals(
        multilevel_pred_boxes, multilevel_label_logits, image_shape2d):
    
    num_lvl = len(cfg.FPN.ANCHOR_STRIDES)
    assert len(multilevel_pred_boxes) == num_lvl
    assert len(multilevel_label_logits) == num_lvl

    training = get_current_tower_context().is_training
    all_boxes = []
    all_scores = []
    if cfg.FPN.PROPOSAL_MODE == 'Level':
        fpn_nms_topk = cfg.RPN.TRAIN_PER_LEVEL_NMS_TOPK if training else cfg.RPN.TEST_PER_LEVEL_NMS_TOPK
        for lvl in range(num_lvl):
            with tf.name_scope('Lvl{}'.format(lvl + 2)):
                pred_boxes_decoded = multilevel_pred_boxes[lvl]

                proposal_boxes, proposal_scores = generate_rpn_proposals(
                    tf.reshape(pred_boxes_decoded, [-1, 4]),
                    tf.reshape(multilevel_label_logits[lvl], [-1]),
                    image_shape2d, fpn_nms_topk)
                all_boxes.append(proposal_boxes)
                all_scores.append(proposal_scores)

        proposal_boxes = tf.concat(all_boxes, axis=0)  # nx4
        proposal_scores = tf.concat(all_scores, axis=0)  # n
        # Here we are different from Detectron.
        # Detectron picks top-k within the batch, rather than within an image. However we do not have a batch.
        proposal_topk = tf.minimum(tf.size(proposal_scores), fpn_nms_topk)
        proposal_scores, topk_indices = tf.nn.top_k(proposal_scores, k=proposal_topk, sorted=False)
        proposal_boxes = tf.gather(proposal_boxes, topk_indices)
    else:
        for lvl in range(num_lvl):
            with tf.name_scope('Lvl{}'.format(lvl + 2)):
                pred_boxes_decoded = multilevel_pred_boxes[lvl]
                all_boxes.append(tf.reshape(pred_boxes_decoded, [-1, 4]))
                all_scores.append(tf.reshape(multilevel_label_logits[lvl], [-1]))
        all_boxes = tf.concat(all_boxes, axis=0)
        all_scores = tf.concat(all_scores, axis=0)
        proposal_boxes, proposal_scores = generate_rpn_proposals(
            all_boxes, all_scores, image_shape2d,
            cfg.RPN.TRAIN_PRE_NMS_TOPK if training else cfg.RPN.TEST_PRE_NMS_TOPK,
            cfg.RPN.TRAIN_POST_NMS_TOPK if training else cfg.RPN.TEST_POST_NMS_TOPK)

    tf.sigmoid(proposal_scores, name='probs')  # for visualization
    return tf.stop_gradient(proposal_boxes, name='boxes'), \
        tf.stop_gradient(proposal_scores, name='scores')
1223085
def _draw_score_box(self, label, score, position, size):
        x1, y1 = position
        width, height = size

        """"""
        pygame.draw.rect(self.screen, (187, 173, 160), (x1, y1, width, height))
        w, h = label.get_size()
        self.screen.blit(label, (x1 + (width - w) / 2, y1 + 8))
        score = self.score_font.render(str(score), True, (255, 255, 255))
        w, h = score.get_size()
        self.screen.blit(score, (x1 + (width - w) / 2, y1 + (height + label.get_height() - h) / 2))
262124
def _draw_multiclass(self):
        
        # TODO: handle colors better with a mapping and user input
        if self.per_class:
            for cls in self.classes_:
                precision = self.precision_[cls]
                recall = self.recall_[cls]

                label = "PR for class {} (area={:0.2f})".format(cls, self.score_[cls])
                self._draw_pr_curve(recall, precision, label=label)

        if self.micro:
            precision = self.precision_[MICRO]
            recall = self.recall_[MICRO]
            self._draw_pr_curve(recall, precision)

        self._draw_ap_score(self.score_[MICRO])
1316428
def queue_draw_item(self, *items):
        
        gaphas_items = []
        for item in items:
            if isinstance(item, Element):
                gaphas_items.append(item)
            else:
                try:
                    gaphas_items.append(item.parent)
                except AttributeError:
                    pass
        super(ExtendedGtkView, self).queue_draw_item(*gaphas_items)
514865
def draw_box(cb, x0, y0, w, h, fg=colors.default_fg, bg=colors.default_bg, h_seps=[], v_seps=[]):
    
    w -= 1
    h -= 1
    corners = [(x0, y0), (x0 + w, y0), (x0, y0 + h), (x0 + w, y0 + h)]

    fg = fg()
    bg = bg()

    for i, c in enumerate(corners):
        cb.put(c[0], c[1], BOX_CORNERS[i], fg, bg)

    for s in h_seps + [0, h]:
        cb.put(x0 + 1, y0 + s, symbols["BOX_HORIZONTAL"] * (w - 1), fg, bg)

    for y in range(1, h):
        for s in v_seps + [0, w]:
            cb.put(x0 + s, y0 + y, symbols["BOX_VERTICAL"], fg, bg)

    for s in h_seps:
        cb.put(x0,     y0 + s, symbols["BOX_X_LEFT"],  fg, bg)
        cb.put(x0 + w, y0 + s, symbols["BOX_X_RIGHT"], fg, bg)

    for s in v_seps:
        cb.put(x0 + s, y0,     symbols["BOX_X_TOP"],    fg, bg)
        cb.put(x0 + s, y0 + h, symbols["BOX_X_BOTTOM"], fg, bg)
196237
def propose(self):
        
        # generate a list of all the untried candidate pipelines
        candidates = self._get_candidates()

        # get_candidates() returns None when every possibility has been tried
        if candidates is None:
            return None

        # predict() returns a predicted values for each candidate
        predictions = self.predict(candidates)

        # acquire() evaluates the list of predictions, selects one, and returns
        # its index.
        idx = self._acquire(predictions)
        return candidates[idx]
605739
def get_sorted_proposal_list(self):
        """"""
        proposals = {}
        for proposal in self.proposals:
            proposals.setdefault(proposal.scope, []).append(proposal)
        result = []
        for scope in self.scopepref:
            scope_proposals = proposals.get(scope, [])
            scope_proposals = [proposal for proposal in scope_proposals
                               if proposal.type in self.typerank]
            scope_proposals.sort(key=self._proposal_key)
            result.extend(scope_proposals)
        return result
62201
def proposal_metrics(iou):
    
    # find best roi for each gt, for summary only
    best_iou = tf.reduce_max(iou, axis=0)
    mean_best_iou = tf.reduce_mean(best_iou, name='best_iou_per_gt')
    summaries = [mean_best_iou]
    with tf.device('/cpu:0'):
        for th in [0.3, 0.5]:
            recall = tf.truediv(
                tf.count_nonzero(best_iou >= th),
                tf.size(best_iou, out_type=tf.int64),
                name='recall_iou{}'.format(th))
            summaries.append(recall)
    add_moving_summary(*summaries)