Plot upper limits as arrows with cap at value of upper limit.

    uplim behaviour has been fixed in matplotlib 1.4
346754
def _plot_ulims(
    ax, x, y, xerr, color, capsize=5, height_fraction=0.25, elinewidth=2
):
    
    ax.errorbar(
        x, y, xerr=xerr, ls="", color=color, elinewidth=elinewidth, capsize=0
    )

    from distutils.version import LooseVersion
    import matplotlib

    mpl_version = LooseVersion(matplotlib.__version__)
    if mpl_version >= LooseVersion("1.4.0"):
        ax.errorbar(
            x,
            y,
            yerr=height_fraction * y,
            ls="",
            uplims=True,
            color=color,
            elinewidth=elinewidth,
            capsize=capsize,
            zorder=10,
        )
    else:
        ax.errorbar(
            x,
            (1 - height_fraction) * y,
            yerr=height_fraction * y,
            ls="",
            lolims=True,
            color=color,
            elinewidth=elinewidth,
            capsize=capsize,
            zorder=10,
        )
771248
def repval(self, limitsok=False):
        """"""

        if not limitsok and self.dkind in ('lower', 'upper'):
            raise LimitError()

        if self.dkind == 'unif':
            lower, upper = map(float, self.data)
            v = 0.5 * (lower + upper)
        elif self.dkind in _noextra_dkinds:
            v = float(self.data)
        elif self.dkind in _yesextra_dkinds:
            v = float(self.data[0])
        else:
            raise RuntimeError('can\'t happen')

        if self.tkind == 'log10':
            return 10**v
        return v
965185
def compute_upper_limit(mu_in, post, alpha=0.9):
    
    if 0 < alpha < 1:
        dp = integral_element(mu_in, post)
        high_idx = bisect.bisect_left(dp.cumsum() / dp.sum(), alpha)
        # if alpha is in (0,1] and post is non-negative, bisect_left
        # will always return an index in the range of mu since
        # post.cumsum()/post.sum() will always begin at 0 and end at 1
        mu_high = mu_in[high_idx]
    elif alpha == 1:
        mu_high = numpy.max(mu_in[post > 0])
    else:
        raise ValueError("Confidence level must be in (0,1].")

    return mu_high
261913
def add_limit(self, label='0_0', **props):
        

        if label not in self.leaf_labels:
            raise ValueError('No model node named {} (must be in {}). Maybe define models first?'.format(label, self.leaf_labels))
        for k,v in props.items():
            if k not in self.spec_props:
                raise ValueError('Illegal property {} (only {} allowed).'.format(k, self.spec_props))
            if len(v) != 2:
                raise ValueError('Must provide (min, max) for {}. (`None` is allowed value)'.format(k))

        if label not in self.limits:
            self.limits[label] = {}

        for k,v in props.items():
            vmin, vmax = v
            if vmin is None:
                vmin = -np.inf
            if vmax is None:
                vmax = np.inf
            self.limits[label][k] = (vmin, vmax)

        self._clear_cache()
550853
def ylim(self, low, high, index=1):
        
        self.layout['yaxis' + str(index)]['range'] = [low, high]
        return self
261406
def plot_clicked(self, mouse_event):
        
        if type(self.peak_vals) is list:
            self.peak_vals.append([mouse_event.xdata, mouse_event.ydata])
            axes = self.matplotlibwidget.axes
            # can't use patches, as they use data coordinates for radius but this is a high aspect ratio plot so the
            # circle was extremely stretched
            axes.plot(mouse_event.xdata, mouse_event.ydata, 'ro', markersize = 5)

            # axes.text(mouse_event.xdata, mouse_event.ydata, '{:d}'.format(len(self.peak_vals[-1])),
            #                  horizontalalignment='center',
            #                  verticalalignment='center',
            #                  color='black'
            #                  )
            self.matplotlibwidget.draw()
1104019
def plot(x, y, z, color=default_color, **kwargs):
    
    fig = gcf()
    _grow_limits(x, y, z)
    defaults = dict(
        visible_lines=True, color_selected=None, size_selected=1, size=1, connected=True, visible_markers=False
    )
    kwargs = dict(defaults, **kwargs)
    s = ipv.Scatter(x=x, y=y, z=z, color=color, **kwargs)
    s.material.visible = False
    fig.scatters = fig.scatters + [s]
    return s
402424
def unzoom(self, event=None, set_bounds=True):
        
        lims = None
        if len(self.conf.zoom_lims) > 1:
            lims = self.conf.zoom_lims.pop()
        ax = self.axes
        if lims is None: # auto scale
            self.conf.zoom_lims = [None]
            xmin, xmax, ymin, ymax = self.data_range
            lims = {self.axes: [xmin, xmax, ymin, ymax]}
        self.set_viewlimits()
        self.canvas.draw()
1292561
def plot_ret_range(self, ax=None, ls=0, dur=0):
        
        import matplotlib.pyplot as plt
        from tia.util.mplot import AxesFormat

        if ax is None:
            ax = plt.gca()

        frame = self.frame
        pids = frame.index

        min_rets = pd.Series([self[pid].performance.ltd_txn.min() for pid in pids], index=pids)
        max_rets = pd.Series([self[pid].performance.ltd_txn.max() for pid in pids], index=pids)

        if not ls:
            s = frame.duration + 20 if dur else 20
            ax.scatter(frame.index, frame.ret, s=s, c='k', marker='o', label='All')
            ax.vlines(pids, min_rets, max_rets)
        else:
            if len(self.long_pids) > 0:
                lframe = frame.ix[frame.index.isin(self.long_pids)]
                s = lframe.duration + 20 if dur else 20
                ax.scatter(lframe.index, lframe.ret, s=s, c='k', marker='o', label='Long')
                ax.vlines(lframe.index, min_rets[lframe.index], max_rets[frame.index])
            if len(self.short_pids) > 0:
                sframe = frame.ix[frame.index.isin(self.short_pids)]
                s = sframe.duration + 20 if dur else 20
                ax.scatter(sframe.index, sframe.ret, s=s, c='r', marker='o', label='Short')
                ax.vlines(sframe.index, min_rets[sframe.index], max_rets[sframe.index])

        AxesFormat().Y.percent().apply()
        ax.axhline(color='k', linestyle='--')
        ax.set_xlim(0, frame.index.max() + 3)
        ax.set_xlabel('pid')
        ax.set_ylabel('return')
        ax.legend(loc='upper left')
        return ax
716535
def hyperbola(axes, **kwargs):
    
    opens_up = kwargs.pop('opens_up', True)
    center = kwargs.pop('center', defaults['center'])
    th = N.linspace(0,2*N.pi,kwargs.pop('n', 500))

    vals = [N.tan(th),1/N.cos(th)]
    if not opens_up:
        vals = vals[::-1]

    x = axes[0]*vals[0]+center[0]
    y = axes[1]*vals[1]+center[1]

    extrema = [N.argmin(x),N.argmax(x)]

    def remove_asymptotes(arr):
        arr[extrema] = N.nan
        return arr

    xy = tuple(remove_asymptotes(i) for i in (x,y))

    return xy
1275000
def interpolate_1d(xvalues, yvalues, method='linear', limit=None,
                   limit_direction='forward', limit_area=None, fill_value=None,
                   bounds_error=False, order=None, **kwargs):
    
    # Treat the original, non-scipy methods first.

    invalid = isna(yvalues)
    valid = ~invalid

    if not valid.any():
        # have to call np.asarray(xvalues) since xvalues could be an Index
        # which can't be mutated
        result = np.empty_like(np.asarray(xvalues), dtype=np.float64)
        result.fill(np.nan)
        return result

    if valid.all():
        return yvalues

    if method == 'time':
        if not getattr(xvalues, 'is_all_dates', None):
            # if not issubclass(xvalues.dtype.type, np.datetime64):
            raise ValueError('time-weighted interpolation only works '
                             'on Series or DataFrames with a '
                             'DatetimeIndex')
        method = 'values'

    valid_limit_directions = ['forward', 'backward', 'both']
    limit_direction = limit_direction.lower()
    if limit_direction not in valid_limit_directions:
        msg = ('Invalid limit_direction: expecting one of {valid!r}, '
               'got {invalid!r}.')
        raise ValueError(msg.format(valid=valid_limit_directions,
                                    invalid=limit_direction))

    if limit_area is not None:
        valid_limit_areas = ['inside', 'outside']
        limit_area = limit_area.lower()
        if limit_area not in valid_limit_areas:
            raise ValueError('Invalid limit_area: expecting one of {}, got '
                             '{}.'.format(valid_limit_areas, limit_area))

    # default limit is unlimited GH #16282
    if limit is None:
        # limit = len(xvalues)
        pass
    elif not is_integer(limit):
        raise ValueError('Limit must be an integer')
    elif limit < 1:
        raise ValueError('Limit must be greater than 0')

    from pandas import Series
    ys = Series(yvalues)

    # These are sets of index pointers to invalid values... i.e. {0, 1, etc...
    all_nans = set(np.flatnonzero(invalid))
    start_nans = set(range(ys.first_valid_index()))
    end_nans = set(range(1 + ys.last_valid_index(), len(valid)))
    mid_nans = all_nans - start_nans - end_nans

    # Like the sets above, preserve_nans contains indices of invalid values,
    # but in this case, it is the final set of indices that need to be
    # preserved as NaN after the interpolation.

    # For example if limit_direction='forward' then preserve_nans will
    # contain indices of NaNs at the beginning of the series, and NaNs that
    # are more than'limit' away from the prior non-NaN.

    # set preserve_nans based on direction using _interp_limit
    if limit_direction == 'forward':
        preserve_nans = start_nans | set(_interp_limit(invalid, limit, 0))
    elif limit_direction == 'backward':
        preserve_nans = end_nans | set(_interp_limit(invalid, 0, limit))
    else:
        # both directions... just use _interp_limit
        preserve_nans = set(_interp_limit(invalid, limit, limit))

    # if limit_area is set, add either mid or outside indices
    # to preserve_nans GH #16284
    if limit_area == 'inside':
        # preserve NaNs on the outside
        preserve_nans |= start_nans | end_nans
    elif limit_area == 'outside':
        # preserve NaNs on the inside
        preserve_nans |= mid_nans

    # sort preserve_nans and covert to list
    preserve_nans = sorted(preserve_nans)

    xvalues = getattr(xvalues, 'values', xvalues)
    yvalues = getattr(yvalues, 'values', yvalues)
    result = yvalues.copy()

    if method in ['linear', 'time', 'index', 'values']:
        if method in ('values', 'index'):
            inds = np.asarray(xvalues)
            # hack for DatetimeIndex, #1646
            if needs_i8_conversion(inds.dtype.type):
                inds = inds.view(np.int64)
            if inds.dtype == np.object_:
                inds = lib.maybe_convert_objects(inds)
        else:
            inds = xvalues
        result[invalid] = np.interp(inds[invalid], inds[valid], yvalues[valid])
        result[preserve_nans] = np.nan
        return result

    sp_methods = ['nearest', 'zero', 'slinear', 'quadratic', 'cubic',
                  'barycentric', 'krogh', 'spline', 'polynomial',
                  'from_derivatives', 'piecewise_polynomial', 'pchip', 'akima']

    if method in sp_methods:
        inds = np.asarray(xvalues)
        # hack for DatetimeIndex, #1646
        if issubclass(inds.dtype.type, np.datetime64):
            inds = inds.view(np.int64)
        result[invalid] = _interpolate_scipy_wrapper(inds[valid],
                                                     yvalues[valid],
                                                     inds[invalid],
                                                     method=method,
                                                     fill_value=fill_value,
                                                     bounds_error=bounds_error,
                                                     order=order, **kwargs)
        result[preserve_nans] = np.nan
        return result
1289431
def upper_band(data, period, env_percentage):
    
    cb = center_band(data, period)
    ub = [val * (1 + float(env_percentage)) for val in cb]
    return ub
1306722
def switch_axis_limits(ax, which_axis):
    '''
    
    '''
    for a in which_axis:
        assert a in ('x', 'y')
        ax_limits = ax.axis()
        if a == 'x':
            ax.set_xlim(ax_limits[1], ax_limits[0])
        else:
            ax.set_ylim(ax_limits[3], ax_limits[2])
865447
def xlim_changed(self, axsubplot):
        ''''''
        xrange = axsubplot.get_xbound()
        xlim = axsubplot.get_xlim()
        self.setup_xrange(xrange[1] - xrange[0])
        if self.draw_events == 0:
            # ignore limit change before first draw event
            return
        if self.xlim_pipe is not None and axsubplot == self.ax1 and xlim != self.xlim:
            self.xlim = xlim
            #print('send', self.graph_num, xlim)
            self.xlim_pipe[1].send(xlim)
254499
private void upwardChartPass(CfgParseChart chart) {
    double[] newValues = new double[binaryDistributionWeights.getValues().length];

    // spanSize is the number of words *in addition* to the word under
    // spanStart.
    for (int spanSize = 1; spanSize < chart.chartSize(); spanSize++) {
      for (int spanStart = 0; spanStart + spanSize < chart.chartSize(); spanStart++) {
        int spanEnd = spanStart + spanSize;
        calculateInside(spanStart, spanEnd, chart, newValues);
      }
    }
    chart.setInsideCalculated();
  }
1374164
def cublasChpr(handle, uplo, n, alpha, x, incx, AP):
    
    
    status = _libcublas.cublasChpr_v2(handle, 
                                      _CUBLAS_FILL_MODE[uplo], 
                                      n, ctypes.byref(ctypes.c_float(alpha)),
                                      int(x), incx, int(AP))
    cublasCheckStatus(status)
1125222
function upperBound(value, arr) {
    let i = 0;
    let j = arr.length - 1;
    while (i < j) {
        const m = (i + j) >> 1;
        if (arr[m] > value) {
            j = m;
        } else {
            i = m + 1;
        }
    }
    return arr[i];
}