Mark regions which were local maximums and had high confidence as negative.  These regions were
candidates for the tracker but were not selected
425669
protected void learnAmbiguousNegative(Rectangle2D_F64 targetRegion) {

		TldHelperFunctions.convertRegion(targetRegion, targetRegion_I32);

		if( detection.isSuccess() ) {
			TldRegion best = detection.getBest();

			// see if it found the correct solution
			double overlap = helper.computeOverlap(best.rect,targetRegion_I32);
			if( overlap <= config.overlapLower ) {
				template.addDescriptor(false,best.rect);
//				fern.learnFernNoise(false, best.rect );
			}

			// mark all ambiguous regions as bad
			List<ImageRectangle> ambiguous = detection.getAmbiguousRegions();
			for( ImageRectangle r : ambiguous ) {
				overlap = helper.computeOverlap(r,targetRegion_I32);
				if( overlap <= config.overlapLower ) {
					fern.learnFernNoise(false, r );
					template.addDescriptor(false,r);
				}
			}
		}
	}
809736
def check_param_ranges(num_bins, num_groups, num_values, trim_outliers, trim_percentile):
    """"""

    if num_bins < minimum_num_bins:
        raise ValueError('Too few bins! The number of bins must be >= 5')

    if num_values < num_groups:
        raise ValueError('Insufficient number of values in features (< number of nodes), or invalid membership!')

    if trim_outliers:
        if trim_percentile < 0 or trim_percentile >= 100:
            raise ValueError('percentile of tail values to trim must be in the semi-open interval [0,1).')
    elif num_values < 2:
        raise ValueError('too few features to compute minimum and maximum')

    return
1115165
def find_local_maxima(self, input_grid):
        
        pixels, q_data = self.quantize(input_grid)
        centers = OrderedDict()
        for p in pixels.keys():
            centers[p] = []
        marked = np.ones(q_data.shape, dtype=int) * self.UNMARKED
        MIN_INFL = int(np.round(1 + 0.5 * np.sqrt(self.max_size)))
        MAX_INFL = 2 * MIN_INFL
        marked_so_far = []
        # Find the maxima. These are high-values with enough clearance
        # around them.
        # Work from high to low bins. The pixels in the highest bin mark their
        # neighborhoods first. If you did it from low to high the lowest maxima
        # would mark their neighborhoods first and interfere with the identification of higher maxima.
        for b in sorted(pixels.keys(),reverse=True):
            # Square starts large with high intensity bins and gets smaller with low intensity bins.
            infl_dist = MIN_INFL + int(np.round(float(b) / self.max_bin * (MAX_INFL - MIN_INFL)))
            for p in pixels[b]:
                if marked[p] == self.UNMARKED:
                    ok = False
                    del marked_so_far[:]
                    # Temporarily mark unmarked points in square around point (keep track of them in list marked_so_far).
                    # If none of the points in square were marked already from a higher intensity center, 
                    # this counts as a new center and ok=True and points will remain marked.
                    # Otherwise ok=False and marked points that were previously unmarked will be unmarked.
                    for (i, j), v in np.ndenumerate(marked[p[0] - infl_dist:p[0] + infl_dist + 1,
                                                    p[1] - infl_dist:p[1]+ infl_dist + 1]):
                        if v == self.UNMARKED:
                            ok = True
                            marked[i - infl_dist + p[0],j - infl_dist + p[1]] = b
                           
                            marked_so_far.append((i - infl_dist + p[0],j - infl_dist + p[1]))
                        else:
                            # neighborhood already taken
                            ok = False
                            break
                    # ok if point and surrounding square were not marked already.
                    if ok:
                        # highest point in its neighborhood
                        centers[b].append(p)
                    else:
                        for m in marked_so_far:
                            marked[m] = self.UNMARKED
        # Erase marks and start over. You have a list of centers now.
        marked[:, :] = self.UNMARKED
        deferred_from_last = []
        deferred_to_next = []
        # delta (int): maximum number of increments the cluster is allowed to range over. Larger d results in clusters over larger scales.
        for delta in range(0, self.delta + 1):
            # Work from high to low bins.
            for b in sorted(centers.keys(), reverse=True):
                bin_lower = b - delta
                deferred_from_last[:] = deferred_to_next[:]
                del deferred_to_next[:]
                foothills = []
                n_centers = len(centers[b])
                tot_centers = n_centers + len(deferred_from_last)
                for i in range(tot_centers):
                    # done this way to minimize memory overhead of maintaining two lists
                    if i < n_centers:
                        center = centers[b][i]
                    else:
                        center = deferred_from_last[i - n_centers]
                    if bin_lower < 0:
                        bin_lower = 0
                    if marked[center] == self.UNMARKED:
                        captured = self.set_maximum(q_data, marked, center, bin_lower, foothills)
                        if not captured:
                            # decrement to lower value to see if it'll get big enough
                            deferred_to_next.append(center)
                        else:
                            pass
                # this is the last one for this bin
                self.remove_foothills(q_data, marked, b, bin_lower, centers, foothills)
            del deferred_from_last[:]
            del deferred_to_next[:]
        return marked
577176
def isRegionValid(self):
        
        screens = PlatformManager.getScreenDetails()
        for screen in screens:
            s_x, s_y, s_w, s_h = screen["rect"]
            if self.x+self.w >= s_x and s_x+s_w >= self.x and self.y+self.h >= s_y and s_y+s_h >= self.y:
                # Rects overlap
                return True
        return False
825137
def _validate(self):
        
        if self.region_type not in regions_attributes:
            raise ValueError("'{0}' is not a valid region type in this package"
                             .format(self.region_type))

        if self.coordsys not in valid_coordsys['DS9'] + valid_coordsys['CRTF']:
            raise ValueError("'{0}' is not a valid coordinate reference frame "
                             "in astropy".format(self.coordsys))
1140551
private void removeTaskTrackerCapacity(TaskTrackerStatus status) {
    Integer mapSlots = trackerNameToMapSlots.remove(status.getTrackerName());
    if (mapSlots == null) {
      mapSlots = 0;
    }
    totalMapTaskCapacity -= mapSlots;

    Integer reduceSlots = trackerNameToReduceSlots.remove(status.getTrackerName());
    if (reduceSlots == null) {
      reduceSlots = 0;
    }
    totalReduceTaskCapacity -= reduceSlots;

    LOG.info("Removing " + mapSlots + " map slots, " + reduceSlots +
             " reduce slots due to " + status.getTrackerName() +
             ", totalMap = " + totalMapTaskCapacity + ", totalReduce = " + totalReduceTaskCapacity);
  }
1044228
def _local_search(problem, fringe_expander, iterations_limit=0, fringe_size=1,
                  random_initial_states=False, stop_when_no_better=True,
                  viewer=None):
    '''
    
    '''
    if viewer:
        viewer.event('started')

    fringe = BoundedPriorityQueue(fringe_size)
    if random_initial_states:
        for _ in range(fringe_size):
            s = problem.generate_random_state()
            fringe.append(SearchNodeValueOrdered(state=s, problem=problem))
    else:
        fringe.append(SearchNodeValueOrdered(state=problem.initial_state,
                                             problem=problem))

    finish_reason = ''
    iteration = 0
    run = True
    best = None

    while run:
        if viewer:
            viewer.event('new_iteration', list(fringe))

        old_best = fringe[0]
        fringe_expander(fringe, iteration, viewer)
        best = fringe[0]

        iteration += 1

        if iterations_limit and iteration >= iterations_limit:
            run = False
            finish_reason = 'reaching iteration limit'
        elif old_best.value >= best.value and stop_when_no_better:
            run = False
            finish_reason = 'not being able to improve solution'

    if viewer:
        viewer.event('finished', fringe, best, 'returned after %s' % finish_reason)

    return best
556006
def fix_location(records, max_elapsed_seconds=300):
    
    groups = itertools.groupby(records, lambda r: r.direction)
    groups = [(interaction, list(g)) for interaction, g in groups]

    def tdist(t1, t2):
            return abs((t1 - t2).total_seconds())

    for i, (interaction, g) in enumerate(groups):
        if interaction == 'in':
            continue

        prev_gps = groups[i-1][1][-1]
        next_gps = groups[i+1][1][0]

        for r in g:
            if tdist(r.datetime, prev_gps.datetime) <= max_elapsed_seconds:
                r.position = prev_gps.position
            elif tdist(r.datetime, next_gps.datetime) <= max_elapsed_seconds:
                r.position = next_gps.position
497152
protected boolean trackFeature() {

		pairs.reset();
		// total number of tracks which contribute to FB error
		int numTracksFB = 0;
		// tracks which are not dropped
		int numTracksRemaining = 0;

		for( int i = 0; i < tracks.length; i++ ) {
			Track t = tracks[i];
			if( !t.active )
				continue;

			float prevX = t.klt.x;
			float prevY = t.klt.y;

			// track in forwards direction
			tracker.setImage(currentImage,currentDerivX,currentDerivY);
			KltTrackFault result = tracker.track(t.klt);
			if( result != KltTrackFault.SUCCESS ) {
				t.active = false;
				continue;
			}

			float currX = t.klt.x;
			float currY = t.klt.y;

			// track in reverse direction
			tracker.setDescription(t.klt);
			tracker.setImage(previousImage, previousDerivX, previousDerivY);
			result = tracker.track(t.klt);
			if( result != KltTrackFault.SUCCESS ) {
				t.active = false;
				continue;
			}

			// compute forward-backwards error
			double errorForwardBackwards = UtilPoint2D_F32.distanceSq(prevX,prevY,t.klt.x,t.klt.y);

			// put into lists for computing the median error
			errorsFB[numTracksFB++] = errorForwardBackwards;

			// discard if error is too large
			if( errorForwardBackwards > maxErrorFB ) {
				t.active = false;
				continue;
			}

			// create data structure used for group motion estimation
			AssociatedPair p = pairs.grow();
			p.p1.set( prevX, prevY );
			p.p2.set( currX, currY );

			numTracksRemaining++;
		}

		// if the forward-backwards error is too large, give up
		double medianFB = QuickSelect.select(errorsFB,numTracksFB/2,numTracksFB);

//		System.out.println("Median tracking error FB: "+medianFB);

		if( medianFB > maxErrorFB || numTracksRemaining < 4 )
			return false;

		return true;
	}
460843
private int dropUnusedTracks() {

		List<PointTrack> all = tracker.getAllTracks(null);
		int num = 0;

		for (PointTrack t : all) {
			VoTrack p = t.getCookie();
			if (tick - p.lastInlier > thresholdRetire) {
				tracker.dropTrack(t);
				num++;
			}
		}

		return num;
	}
1173132
def search(self, coords=None, distance_modulus=None, tolerance=1.e-2):
        
        nmoduli = len(self.distance_modulus_array)
        npixels    = len(self.roi.pixels_target)
        self.log_likelihood_sparse_array       = np.zeros([nmoduli, npixels])
        self.richness_sparse_array             = np.zeros([nmoduli, npixels])
        self.richness_lower_sparse_array       = np.zeros([nmoduli, npixels])
        self.richness_upper_sparse_array       = np.zeros([nmoduli, npixels])
        self.richness_upper_limit_sparse_array = np.zeros([nmoduli, npixels])
        self.stellar_mass_sparse_array         = np.zeros([nmoduli, npixels])
        self.fraction_observable_sparse_array  = np.zeros([nmoduli, npixels])

        # Specific pixel/distance_modulus
        coord_idx, distance_modulus_idx = None, None
        if coords is not None:
            # Match to nearest grid coordinate index
            coord_idx = self.roi.indexTarget(coords[0],coords[1])
        if distance_modulus is not None:
            # Match to nearest distance modulus index
            distance_modulus_idx=np.fabs(self.distance_modulus_array-distance_modulus).argmin()

        lon, lat = self.roi.pixels_target.lon, self.roi.pixels_target.lat
            
        logger.info('Looping over distance moduli in grid search ...')
        for ii, distance_modulus in enumerate(self.distance_modulus_array):

            # Specific pixel
            if distance_modulus_idx is not None:
                if ii != distance_modulus_idx: continue

            logger.info('  (%-2i/%i) Distance Modulus=%.1f ...'%(ii+1,nmoduli,distance_modulus))

            # Set distance_modulus once to save time
            self.loglike.set_params(distance_modulus=distance_modulus)

            for jj in range(0, npixels):
                # Specific pixel
                if coord_idx is not None:
                    if jj != coord_idx: continue

                # Set kernel location
                self.loglike.set_params(lon=lon[jj],lat=lat[jj])
                # Doesn't re-sync distance_modulus each time
                self.loglike.sync_params()
                                         
                args = (jj+1, npixels, self.loglike.source.lon, self.loglike.source.lat)
                msg = '    (%-3i/%i) Candidate at (%.2f, %.2f) ... '%(args)

                self.log_likelihood_sparse_array[ii][jj], self.richness_sparse_array[ii][jj], parabola = self.loglike.fit_richness()
                self.stellar_mass_sparse_array[ii][jj] = self.stellar_mass_conversion * self.richness_sparse_array[ii][jj]
                self.fraction_observable_sparse_array[ii][jj] = self.loglike.f
                if self.config['scan']['full_pdf']:
                    #n_pdf_points = 100
                    #richness_range = parabola.profileUpperLimit(delta=25.) - self.richness_sparse_array[ii][jj]
                    #richness = np.linspace(max(0., self.richness_sparse_array[ii][jj] - richness_range),
                    #                          self.richness_sparse_array[ii][jj] + richness_range,
                    #                          n_pdf_points)
                    #if richness[0] > 0.:
                    #    richness = np.insert(richness, 0, 0.)
                    #    n_pdf_points += 1
                    # 
                    #log_likelihood = np.zeros(n_pdf_points)
                    #for kk in range(0, n_pdf_points):
                    #    log_likelihood[kk] = self.loglike.value(richness=richness[kk])
                    #parabola = ugali.utils.parabola.Parabola(richness, 2.*log_likelihood)
                    #self.richness_lower_sparse_array[ii][jj], self.richness_upper_sparse_array[ii][jj] = parabola.confidenceInterval(0.6827)
                    self.richness_lower_sparse_array[ii][jj], self.richness_upper_sparse_array[ii][jj] = self.loglike.richness_interval(0.6827)
                    
                    self.richness_upper_limit_sparse_array[ii][jj] = parabola.bayesianUpperLimit(0.95)

                    args = (
                        2. * self.log_likelihood_sparse_array[ii][jj],
                        self.stellar_mass_conversion*self.richness_sparse_array[ii][jj],
                        self.stellar_mass_conversion*self.richness_lower_sparse_array[ii][jj],
                        self.stellar_mass_conversion*self.richness_upper_sparse_array[ii][jj],
                        self.stellar_mass_conversion*self.richness_upper_limit_sparse_array[ii][jj]
                    )
                    msg += 'TS=%.1f, Stellar Mass=%.1f (%.1f -- %.1f @ 0.68 CL, < %.1f @ 0.95 CL)'%(args)
                else:
                    args = (
                        2. * self.log_likelihood_sparse_array[ii][jj], 
                        self.stellar_mass_conversion * self.richness_sparse_array[ii][jj],
                        self.fraction_observable_sparse_array[ii][jj]
                    )
                    msg += 'TS=%.1f, Stellar Mass=%.1f, Fraction=%.2g'%(args)
                logger.debug(msg)
                
                #if coords is not None and distance_modulus is not None:
                #    results = [self.richness_sparse_array[ii][jj],
                #               self.log_likelihood_sparse_array[ii][jj],
                #               self.richness_lower_sparse_array[ii][jj],
                #               self.richness_upper_sparse_array[ii][jj],
                #               self.richness_upper_limit_sparse_array[ii][jj],
                #               richness, log_likelihood, self.loglike.p, self.loglike.f]
                #    return results

            jj_max = self.log_likelihood_sparse_array[ii].argmax()
            args = (
                jj_max+1, npixels, lon[jj_max], lat[jj_max],
                2. * self.log_likelihood_sparse_array[ii][jj_max], 
                self.stellar_mass_conversion * self.richness_sparse_array[ii][jj_max]
            )
            msg = '  (%-3i/%i) Maximum at (%.2f, %.2f) ... TS=%.1f, Stellar Mass=%.1f'%(args)
            logger.info(msg)
566919
private static int searchLocal(
        long localSecs,
        ZonalTransition[] transitions
    ) {

        int low = 0;
        int high = transitions.length - 1;

        while (low <= high) {
            int middle = (low + high) / 2;
            ZonalTransition zt = transitions[middle];
            int offset = Math.max(zt.getTotalOffset(), zt.getPreviousOffset());

            if (zt.getPosixTime() + offset <= localSecs) {
                low = middle + 1;
            } else {
                high = middle - 1;
            }
        }

        return low;

    }
1092159
private void selectCandidateTracks() {
		// mark tracks in right frame that are active
		List<PointTrack> activeRight = trackerRight.getActiveTracks(null);
		for( PointTrack t : activeRight ) {
			RightTrackInfo info = t.getCookie();
			info.lastActiveList = tick;
		}

		int mutualActive = 0;
		List<PointTrack> activeLeft = trackerLeft.getActiveTracks(null);
		candidates.clear();
		for( PointTrack left : activeLeft ) {
			LeftTrackInfo info = left.getCookie();

//			if( info == null || info.right == null ) {
//				System.out.println("Oh Crap");
//			}

			// for each active left track, see if its right track has been marked as active
			RightTrackInfo infoRight = info.right.getCookie();
			if( infoRight.lastActiveList != tick ) {
				continue;
			}

			// check epipolar constraint and see if it is still valid
			if( stereoCheck.checkPixel(left, info.right) ) {
				info.lastConsistent = tick;
				candidates.add(left);
			}
			mutualActive++;
		}

//		System.out.println("Active Tracks: Left "+trackerLeft.getActiveTracks(null).size()+" right "+
//				trackerRight.getActiveTracks(null).size());
//		System.out.println("All Tracks:    Left "+trackerLeft.getAllTracks(null).size()+" right "+
//				trackerRight.getAllTracks(null).size());
//		System.out.println("Candidates = "+candidates.size()+" mutual active = "+mutualActive);
	}
384426
def get_bounds(locations, lonlat=False):
    
    bounds = [[None, None], [None, None]]
    for point in iter_coords(locations):
        bounds = [
            [
                none_min(bounds[0][0], point[0]),
                none_min(bounds[0][1], point[1]),
            ],
            [
                none_max(bounds[1][0], point[0]),
                none_max(bounds[1][1], point[1]),
            ],
        ]
    if lonlat:
        bounds = _locations_mirror(bounds)
    return bounds
651504
def validate(self):
        
        if self.nregions is None:
            raise TypeError("neutral regions cannot be None")
        if self.sregions is None:
            raise TypeError("selected regions cannot be None")
        if self.recregions is None:
            raise TypeError("recombination regions cannot be None")
        if self.demography is None:
            raise TypeError("demography cannot be None")
        if self.prune_selected is None:
            raise TypeError("prune_selected cannot be None")
        if self.gvalue is None:
            raise TypeError("gvalue cannot be None")
        if self.rates is None:
            raise TypeError("rates cannot be None")
125293
def _ep_for_region(self, region):
        
        rgn = region.upper()
        try:
            rgn_ep = [ep for ep in list(self.endpoints.values())
                    if ep.region.upper() == rgn][0]
        except IndexError:
            # See if there is an 'ALL' region.
            try:
                rgn_ep = [ep for ep in list(self.endpoints.values())
                        if ep.region.upper() == "ALL"][0]
            except IndexError:
                rgn_ep = None
        return rgn_ep
659846
private void addDescriptor(boolean positive, NccFeature f) {
		// avoid adding the same descriptor twice or adding contradicting results
		if( positive)
			if( distance(f,templatePositive) < 0.05 ) {
				return;
			}
		if( !positive) {
			if( distance(f,templateNegative) < 0.05 ) {
				return;
			}
			// a positive positive can have very bad affects on tracking, try to avoid learning a positive
			// example as a negative one
			if( distance(f,templatePositive) < 0.05 ) {
				return;
			}
		}

		if( positive )
			templatePositive.add(f);
		else
			templateNegative.add(f);
	}