Helper function to compute bounding box for the plot
328430
def compute_bbox_with_margins(margin, x, y):
    ''
    # set margins
    pos = np.asarray((x, y))
    minxy, maxxy = pos.min(axis=1), pos.max(axis=1)
    xy1 = minxy - margin*(maxxy - minxy)
    xy2 = maxxy + margin*(maxxy - minxy)
    return tuple(xy1), tuple(xy2)
55106
def _compute(self):
        """"""
        if self._min:
            self._box.ymin = min(self._min, self.zero)
        if self._max:
            self._box.ymax = max(self._max, self.zero)
        self._x_pos = [
            x / self._len for x in range(self._len + 1)
        ] if self._len > 1 else [0, 1]  # Center if only one value

        self._points(self._x_pos)

        self._x_pos = [(i + .5) / self._len for i in range(self._len)]
53683
def bounds_handler(ctx, param, value):
    """"""
    retval = from_like_context(ctx, param, value)
    if retval is None and value is not None:
        try:
            value = value.strip(", []")
            retval = tuple(float(x) for x in re.split(r"[,\s]+", value))
            assert len(retval) == 4
            return retval
        except Exception:
            raise click.BadParameter(
                "{0!r} is not a valid bounding box representation".format(value)
            )
    else:  # pragma: no cover
        return retval
453619
def text_bounding_box(self, size_pt, text):
        
        if size_pt == 12:
            mult = {"h": 9, "w_digit": 5, "w_space": 2}
        elif size_pt == 18:
            mult = {"h": 14, "w_digit": 9, "w_space": 2}
        num_chars = len(text)
        return (num_chars * mult["w_digit"] + (num_chars - 1) * mult["w_space"] + 1, mult["h"])
747577
def bounds(self, axis=0):
        
        if not 0 <= axis < self.GetDimension():
            raise ValueError(
                "axis must be a non-negative integer less than "
                "the dimensionality of the histogram")
        if axis == 0:
            return self.xedges(1), self.xedges(-2)
        if axis == 1:
            return self.yedges(1), self.yedges(-2)
        if axis == 2:
            return self.zedges(1), self.zedges(-2)
        raise TypeError("axis must be an integer")
701611
def get_bounding_box(self):
        
        if not isinstance(self.ref_cell, Cell):
            return None
        if (self.rotation is None and self.magnification is None and
                self.x_reflection is None):
            key = self
        else:
            key = (self.ref_cell, self.rotation, self.magnification,
                   self.x_reflection)
        deps = self.ref_cell.get_dependencies(True)
        if not (self.ref_cell._bb_valid and
                all(ref._bb_valid for ref in deps) and key in _bounding_boxes):
            for ref in deps:
                ref.get_bounding_box()
            self.ref_cell.get_bounding_box()
            tmp = self.origin
            self.origin = None
            polygons = self.get_polygons()
            self.origin = tmp
            if len(polygons) == 0:
                bb = None
            else:
                all_points = numpy.concatenate(polygons).transpose()
                bb = numpy.array(((all_points[0].min(), all_points[1].min()),
                                  (all_points[0].max(), all_points[1].max())))
            _bounding_boxes[key] = bb
        else:
            bb = _bounding_boxes[key]
        if self.origin is None or bb is None:
            return bb
        else:
            return bb + numpy.array(((self.origin[0], self.origin[1]),
                                     (self.origin[0], self.origin[1])))
1249741
def helper_for_plot_data(self, X, plot_limits, visible_dims, fixed_inputs, resolution):
    
    #work out what the inputs are for plotting (1D or 2D)
    if fixed_inputs is None:
        fixed_inputs = []
    fixed_dims = get_fixed_dims(fixed_inputs)
    free_dims = get_free_dims(self, visible_dims, fixed_dims)

    if len(free_dims) == 1:
        #define the frame on which to plot
        resolution = resolution or 200
        Xnew, xmin, xmax = x_frame1D(X[:,free_dims], plot_limits=plot_limits, resolution=resolution)
        Xgrid = np.zeros((Xnew.shape[0],self.input_dim))
        Xgrid[:,free_dims] = Xnew
        for i,v in fixed_inputs:
            Xgrid[:,i] = v
        x = Xgrid
        y = None
    elif len(free_dims) == 2:
        #define the frame for plotting on
        resolution = resolution or 35
        Xnew, x, y, xmin, xmax = x_frame2D(X[:,free_dims], plot_limits, resolution)
        Xgrid = np.zeros((Xnew.shape[0], self.input_dim))
        Xgrid[:,free_dims] = Xnew
        #xmin = Xgrid.min(0)[free_dims]
        #xmax = Xgrid.max(0)[free_dims]
        for i,v in fixed_inputs:
            Xgrid[:,i] = v
    else:
        raise TypeError("calculated free_dims {} from visible_dims {} and fixed_dims {} is neither 1D nor 2D".format(free_dims, visible_dims, fixed_dims))
    return fixed_dims, free_dims, Xgrid, x, y, xmin, xmax, resolution
1111276
def plot_decision_boundary(model, X, y, step=0.1, figsize=(10, 8), alpha=0.4, size=20):
    

    x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, step),
                         np.arange(y_min, y_max, step))

    f, ax = plt.subplots(figsize=figsize)
    Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)

    ax.contourf(xx, yy, Z, alpha=alpha)
    ax.scatter(X[:, 0], X[:, 1], c=y, s=size, edgecolor='k')
    plt.show()
188499
function BoundingBox3D( xMin , yMin , zMin , xMax , yMax , zMax ) {
	this.min = new Vector3D( xMin , yMin , zMin ) ;
	this.max = new Vector3D( xMax , yMax , zMax ) ;
}
1078557
function bounds(boxes) {
	var width = 0
	var height = 0
	for (var i = 0; i < boxes.length; i++) {
		var box = boxes[i]
		var right = box.position[0] + box.size[0]
		var bottom = box.position[1] + box.size[1]
		if (right > width) {
			width = right
		}
		if (bottom > height) {
			height = bottom
		}
	}
	return [ width, height ]
}
1026628
def compute_slice_bounds(slices, scs, shape):
    
    xidx, yidx = slices
    ys, xs = shape
    l, b, r, t = scs.bounds.lbrt()
    xdensity, ydensity = scs.xdensity, scs.ydensity
    xunit = (1./xdensity)
    yunit = (1./ydensity)
    if isinstance(l, datetime_types):
        xunit = np.timedelta64(int(round(xunit)), scs._time_unit)
    if isinstance(b, datetime_types):
        yunit = np.timedelta64(int(round(yunit)), scs._time_unit)
    if isinstance(xidx, slice):
        l = l if xidx.start is None else max(l, xidx.start)
        r = r if xidx.stop is None else min(r, xidx.stop)
    if isinstance(yidx, slice):
        b = b if yidx.start is None else max(b, yidx.start)
        t = t if yidx.stop is None else min(t, yidx.stop)
    bounds = BoundingBox(points=((l, b), (r, t)))

    # Apply new bounds
    slc = Slice(bounds, scs)

    # Apply scalar and list indices
    l, b, r, t = slc.compute_bounds(scs).lbrt()
    if not isinstance(xidx, slice):
        if not isinstance(xidx, (list, set)): xidx = [xidx]
        if len(xidx) > 1:
            xdensity = xdensity*(float(len(xidx))/xs)
        ls, rs = [], []
        for idx in xidx:
            xc, _ = scs.closest_cell_center(idx, b)
            ls.append(xc-xunit/2)
            rs.append(xc+xunit/2)
        l, r = np.min(ls), np.max(rs)
    elif not isinstance(yidx, slice):
        if not isinstance(yidx, (set, list)): yidx = [yidx]
        if len(yidx) > 1:
            ydensity = ydensity*(float(len(yidx))/ys)
        bs, ts = [], []
        for idx in yidx:
            _, yc = scs.closest_cell_center(l, idx)
            bs.append(yc-yunit/2)
            ts.append(yc+yunit/2)
        b, t = np.min(bs), np.max(ts)
    return BoundingBox(points=((l, b), (r, t)))
1135782
def bounds(self):
        
        return np.array([self.vertices.min(axis=0),
                         self.vertices.max(axis=0)])
289297
function Box( canvas, width, height, left, top ) {
		var graph, axes, data, box, annotations, title;

		// [1] Instantiate a new graph generator and configure:
		graph = xfig.graph( canvas )
			.width( width )
			.height( height )
			.position({
				'left': left,
				'top': top
			})
			.xMin( -0.5 )
			.xMax( 4.5 )
			.yMin( 0 )
			.yMax( 1 );

		// Create the graph:
		graph.create( 'box' );

		// Get data:
		d3.json( 'data/box.data.json', function ( error, json ) {

			// [2] Instantiate a new data generator and configure:
			data = xfig.data( json )
				.accessors( 'x', function ( d, i ) {
					return i;
				})
				.accessors( 'median', function ( d ) {
					return d.median;
				})
				.accessors( 'quartiles', function ( d ) {
					return d.quartiles;
				})
				.accessors( 'whiskers', function (d ) {
					return d.whiskers;
				})
				.accessors( 'outliers.mild', function ( d ) {
					return d.outliers.mild;
				})
				.accessors( 'outliers.extreme', function ( d ) {
					return d.outliers.extreme;
				});

			// Format the data:
			data.format( [ 'x', 'median', 'quartiles', 'whiskers', 'outliers.mild', 'outliers.extreme' ] );

			// Bind the data instance to the graph:
			graph.data( data );

			// [3] Instantiate a new box chart generator and configure:
			box = xfig.box( graph )
				.radius( 5 )
				.width( 0.2 )
				.labels([
					'data 0',
					'data 1',
					'data 2',
					'data 3',
					'data 4'
				]);

			// Create the box chart:
			box.create();

			// [4] Instantiate a new axes generator and configure:
			axes = xfig.axes( graph );

			// Create the axes:
			axes.create();

			// [5] Instantiate a new annotations generator and configure, but this time do so for a graph element:
			annotations = xfig.annotations( graph );

			// Create the annotations element:
			annotations.create();

			// [5.1] Instantiate a new title instance and configure:
			title = annotations.title()
				.top( -30 )
				.left( 0 );

			// Add a (sub)title:
			title.create( 'Subtitle' );

		});

	}
392303
def bounds(self, axis, view=None):
        
        if view is None:
            view = self
        if axis not in self._vshare.bounds:
            self._vshare.bounds[axis] = self._compute_bounds(axis, view)
        return self._vshare.bounds[axis]
388241
def bounding_box(self):
        
        if self.world_coords:
            return self.world_obj.findSolid().BoundingBox()
        return self.local_obj.findSolid().BoundingBox()
53289
def min_func(fun, bounds_min, bounds_max, d=None, rmax=10,
             n0=64, nswp=10, verb=True, smooth_fun=None):
    """"""
    if d is None:
        d = len(bounds_min)
        a = np.asanyarray(bounds_min).copy()
        b = np.asanyarray(bounds_max).copy()
    else:
        a = np.ones(d) * bounds_min
        b = np.ones(d) * bounds_max

    if smooth_fun is None:
        smooth_fun = lambda p, lam: (math.pi / 2 - np.arctan(p - lam))
    #smooth_fun = lambda p, lam: np.exp(-10*(p - lam))

    # We do not need to store the cores, only the interfaces!
    Rx = [[]] * (d + 1)  # Python list for the interfaces
    Rx[0] = np.ones((1, 1))
    Rx[d] = np.ones((1, 1))
    Jy = [np.empty(0, dtype=np.int)] * (d + 1)
    ry = rmax * np.ones(d + 1, dtype=np.int)
    ry[0] = 1
    ry[d] = 1
    n = n0 * np.ones(d, dtype=np.int)
    fun_evals = 0

    grid = [np.reshape(np.linspace(a[i], b[i], n[i]), (n[i], 1))
            for i in xrange(d)]
    for i in xrange(d - 1):
        #cr1 = y[i]
        ry[i + 1] = min(ry[i + 1], n[i] * ry[i])
        cr1 = np.random.randn(ry[i], n[i], ry[i + 1])
        cr1 = reshape(cr1, (ry[i] * n[i], ry[i + 1]))
        q, r = np.linalg.qr(cr1)
        ind = maxvol(q)
        w1 = mkron(np.ones((n[i], 1), dtype=np.int), Jy[i])
        w2 = mkron(grid[i], np.ones((ry[i], 1), dtype=np.int))
        Jy[i + 1] = np.hstack((w1, w2))
        Jy[i + 1] = reshape(Jy[i + 1], (ry[i] * n[i], -1))
        Jy[i + 1] = Jy[i + 1][ind, :]

        # Jy{i+1} = [kron(ones(n(i),1), Jy{i}), kron((1:n(i))', ones(ry(i),1))];
        # Jy{i+1} = Jy{i+1}(ind,:);
    swp = 0
    dirn = -1
    i = d - 1
    lm = float('Inf')
    while swp < nswp:
        # Right-to-left sweep
        # The idea: compute the current core; compute the function of it;
        # Shift locally or globally? Local shift would be the first try
        # Compute the current core

        if np.size(Jy[i]) == 0:
            w1 = np.zeros((ry[i] * n[i] * ry[i + 1], 0), dtype=np.int)
        else:
            w1 = mkron(np.ones((n[i] * ry[i + 1], 1), dtype=np.int), Jy[i])
        w2 = mkron(mkron(np.ones((ry[i + 1], 1), dtype=np.int),
                         grid[i]), np.ones((ry[i], 1), dtype=np.int))
        if np.size(Jy[i + 1]) == 0:
            w3 = np.zeros((ry[i] * n[i] * ry[i + 1], 0), dtype=np.int)
        else:
            w3 = mkron(Jy[i + 1], np.ones((ry[i] * n[i], 1), dtype=np.int))

        J = np.hstack((w1, w2, w3))
        # Just add some random indices to J, which is rnr x d, need to make rn (r + r0) x add,
        # i.e., just generate random r, random n and random multiindex

        cry = fun(J)
        fun_evals += cry.size
        cry = reshape(cry, (ry[i], n[i], ry[i + 1]))
        min_cur = np.min(cry.flatten("F"))
        ind_cur = np.argmin(cry.flatten("F"))
        if lm > min_cur:
            lm = min_cur
            x_full = J[ind_cur, :]
            val = fun(x_full)
            if verb:
                print('New record:', val, 'Point:', x_full, 'fevals:', fun_evals)
        cry = smooth_fun(cry, lm)
        if (dirn < 0 and i > 0):
            cry = reshape(cry, (ry[i], n[i] * ry[i + 1]))
            cry = cry.T
            #q, r = np.linalg.qr(cry)
            u, s, v = mysvd(cry, full_matrices=False)
            ry[i] = min(ry[i], rmax)
            q = u[:, :ry[i]]
            ind = rect_maxvol(q)[0]  # maxvol(q)
            ry[i] = ind.size
            w1 = mkron(np.ones((ry[i + 1], 1), dtype=np.int), grid[i])
            if np.size(Jy[i + 1]) == 0:
                w2 = np.zeros((n[i] * ry[i + 1], 0), dtype=np.int)
            else:
                w2 = mkron(Jy[i + 1], np.ones((n[i], 1), dtype=np.int))
            Jy[i] = np.hstack((w1, w2))
            Jy[i] = reshape(Jy[i], (n[i] * ry[i + 1], -1))
            Jy[i] = Jy[i][ind, :]

        if (dirn > 0 and i < d - 1):
            cry = reshape(cry, (ry[i] * n[i], ry[i + 1]))
            q, r = np.linalg.qr(cry)
            #ind = maxvol(q)
            ind = rect_maxvol(q)[0]
            ry[i + 1] = ind.size
            w1 = mkron(np.ones((n[i], 1), dtype=np.int), Jy[i])
            w2 = mkron(grid[i], np.ones((ry[i], 1), dtype=np.int))
            Jy[i + 1] = np.hstack((w1, w2))
            Jy[i + 1] = reshape(Jy[i + 1], (ry[i] * n[i], -1))
            Jy[i + 1] = Jy[i + 1][ind, :]

        i += dirn
        if i == d or i == -1:
            dirn = -dirn
            i += dirn
            swp = swp + 1
    return val, x_full
73272
def bound_bboxes(bboxes):
    
    group_x0 = min(map(lambda l: l[x0], bboxes))
    group_y0 = min(map(lambda l: l[y0], bboxes))
    group_x1 = max(map(lambda l: l[x1], bboxes))
    group_y1 = max(map(lambda l: l[y1], bboxes))
    return (group_x0, group_y0, group_x1, group_y1)