numpy.compress

Here are the examples of the python api numpy.compress taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

22 Examples 7

Example 1

Project: blockcanvas Source File: numeric_model_explorer.py
Function: data
    def data ( self, source_name ):
        """ Returns the model selection data to be plotted.
        """
        mask = self.model.model_selection
        if mask is None:
            return array( [] )

        return compress( mask, getattr( self.model, self.name ), axis = 0 )

Example 2

Project: blockcanvas Source File: reduction_context.py
Function: get_context_data
    def get_context_data ( self, name ):
        """ Returns the value of a specified item.
        """
        data = self.context.get_context_data( name )
        mask = self._mask
        if mask is None:
            return data

        if self.use_value:
            temp = data.copy()
            putmask( temp, mask == 0, self.context_value_for( name ) )
            return temp

        return compress( mask, data, axis = 0 )

Example 3

Project: blockcanvas Source File: reduction_context.py
Function: get_context_undefined
    def get_context_undefined ( self, name, value ):
        """ Gets the value of a currently undefined item.
        """
        data = self.context.get_context_undefined( name, value )
        if data is Undefined:
            return data

        mask = self._mask
        if mask is None:
            return data

        if self.use_value:
            temp = data.copy()
            putmask( temp, mask == 0, self.context_value_for( name ) )
            return temp

        return compress( mask, data, axis = 0 )

Example 4

Project: blockcanvas Source File: reduction_context.py
Function: get_context_selection
    def _get_context_selection ( self ):
        context_mask = self.context.context_selection
        self_mask    = self._mask
        if (self_mask is None) or (context_mask is None):
            return context_mask

        return compress( self_mask, context_mask, axis = 0 )

Example 5

Project: blockcanvas Source File: selection_reduction_context.py
Function: get_context_data
    def get_context_data ( self, name ):
        """ Returns the value of a specified item.
        """
        data = self.context.get_context_data( name )
        mask = self.context.context_selection
        if mask is None:
            return []

        return compress( mask, data, axis = 0 )

Example 6

Project: blockcanvas Source File: selection_reduction_context.py
Function: get_context_undefined
    def get_context_undefined ( self, name, value ):
        """ Gets the value of a currently undefined item.
        """
        data = self.context.get_context_undefined( name, value )
        if data is Undefined:
            return data

        mask = self.context.context_selection
        if mask is None:
            return []

        return compress( mask, data, axis = 0 )

Example 7

Project: chaco Source File: candle_plot.py
Function: gather_points
    def _gather_points(self):
        index = self.index.get_data()
        mask = broaden(self.index_range.mask_data(index))

        if not mask.any():
            self._cached_data_pts = []
            self._cache_valid = True
            return

        data_pts = [compress(mask, index)]

        for v in (self.min_values, self.bar_min, self.center_values, self.bar_max, self.max_values):
            if v is None or len(v.get_data()) == 0:
                data_pts.append(None)
            else:
                data_pts.append(compress(mask, v.get_data()))

        self._cached_data_pts = data_pts
        self._cache_valid = True

Example 8

Project: chaco Source File: data_range_1d.py
Function: clip_data
    def clip_data(self, data):
        """ Returns a list of data values that are within the range.

        Implements AbstractDataRange.
        """
        return compress(self.mask_data(data), data)

Example 9

Project: chaco Source File: data_range_2d.py
Function: clip_data
    def clip_data(self, data):
        """ Returns a list of data values that are within the range.

        Implements AbstractDataRange.
        """
        return compress(self.mask_data(data), data, axis=0)

Example 10

Project: chaco Source File: regression_lasso.py
    def _selection_changed_fired(self, event):
        indices = self.selection_datasource.metadata["selection"]
        if any(indices):
            x = compress(indices, self.component.index.get_data())
            y = compress(indices, self.component.value.get_data())
            if len(x) < 2 or len(y) < 2:
                self.fit_params = None
                self.centroid = None
            else:
                self.fit_params = tuple(polyfit(x,y,1))
                self.centroid = (sum(x)/len(x)), (sum(y)/len(y))
        else:
            self.fit_params = None
            self.centroid = None
        return

Example 11

Project: chaco Source File: scatter_select.py
Function: selection_changed
    def _selection_changed(self):
        mask = self.index_datasource.metadata['selection']
        print("New selection: ")
        print(compress(mask, arange(len(mask))))
        # Ensure that the points are printed immediately:
        sys.stdout.flush()

Example 12

Project: AWS-Lambda-ML-Microservice-Skeleton Source File: converter.py
    def _get_default_locs(self, vmin, vmax):
        "Returns the default locations of ticks."

        if self.plot_obj.date_axis_info is None:
            self.plot_obj.date_axis_info = self.finder(vmin, vmax, self.freq)

        locator = self.plot_obj.date_axis_info

        if self.isminor:
            return np.compress(locator['min'], locator['val'])
        return np.compress(locator['maj'], locator['val'])

Example 13

Project: ikpy Source File: chain.py
    def active_from_full(self, joints):
        return np.compress(self.active_links_mask, joints, axis=0)

Example 14

Project: scipy Source File: ex1.py
def cluster_data(data,cluster_cnt,iter=20,thresh=1e-5):
    """ Group data into a number of common clusters

        data -- 2D array of data points.  Each point is a row in the array.
        cluster_cnt -- The number of clusters to use
        iter -- number of iterations to use for kmeans algorithm
        thresh -- distortion threshold for kmeans algorithm

        return -- list of 2D arrays.  Each array contains the data points
                  that belong to a specific cluster.

        Uses kmeans algorithm to find the clusters.
    """
    wh_data = vq.whiten(data)
    code_book,dist = vq.kmeans(wh_data,cluster_cnt,iter,thresh)
    code_ids, distortion = vq.vq(wh_data,code_book)
    clusters = []
    for i in range(len(code_book)):
        cluster = np.compress(code_ids == i,data,0)
        clusters.append(cluster)
    return clusters

Example 15

Project: chaco Source File: barplot.py
    def _gather_points(self):
        """ Collects data points that are within the range of the plot, and
        caches them in **_cached_data_pts**.
        """
        index, index_mask = self.index.get_data_mask()
        value, value_mask = self.value.get_data_mask()

        if not self.index or not self.value:
            return

        if len(index) == 0 or len(value) == 0 or len(index) != len(value):
            logger.warn("Chaco: using empty dataset; index_len=%d, value_len=%d." \
                                % (len(index), len(value)))
            self._cached_data_pts = array([])
            self._cache_valid = True
            return

        # TODO: Until we code up a better handling of value-based culling that
        # takes into account starting_value and dataspace bar widths, just use
        # the index culling for now.
#        value_range_mask = self.value_mapper.range.mask_data(value)
#        nan_mask = invert(isnan(index_mask)) & invert(isnan(value_mask))
#        point_mask = index_mask & value_mask & nan_mask & \
#                     index_range_mask & value_range_mask

        index_range_mask = self.index_mapper.range.mask_data(index)
        nan_mask = invert(isnan(index_mask))
        point_mask = index_mask & nan_mask & index_range_mask

        if self.starting_value is None:
            starting_values = zeros(len(index))
        else:
            starting_values = self.starting_value.get_data()

        if self.bar_width_type == "data":
            half_width = self.bar_width / 2.0
            points = column_stack((index-half_width, index+half_width,
                                   starting_values, value))
        else:
            points = column_stack((index, starting_values, value))
        self._cached_data_pts = compress(point_mask, points, axis=0)

        self._cache_valid = True
        return

Example 16

Project: chaco Source File: errorbar_plot.py
    def _gather_points(self):

        if self._cache_valid:
            return

        if not self.index or not self.value_low or not self.value_high:
            return

        index, index_mask = self.index.get_data_mask()
        value_low, value_low_mask = self.value_low.get_data_mask()
        value_high, value_high_mask = self.value_high.get_data_mask()
        value_mask = value_low_mask & value_high_mask

        l1, l2, l3 = map(len, (index, value_low, value_high))
        if 0 in (l1, l2, l3) or not (l1 == l2 == l3):
            logger.warn("Chaco: using empty dataset; index_len=%d, value_low_len=%d, value_high_len=%d." % (l1,l2,l3))
            self._cached_data_pts = []
            self._cache_valid = True
            return

        index_range_mask = self.index_mapper.range.mask_data(index)
        value_low_mask = self.value_mapper.range.mask_data(value_low)
        value_high_mask = self.value_mapper.range.mask_data(value_high)
        value_range_mask = value_low_mask | value_high_mask

        nan_mask = invert(isnan(index_mask) | isnan(value_mask))
        point_mask = index_mask & value_mask & nan_mask & index_range_mask & value_range_mask

        points = column_stack((index, value_low, value_high))

        self._cached_data_pts = compress(point_mask, points, axis=0)
        self._cache_valid = True
        return

Example 17

Project: chaco Source File: quiverplot.py
Function: gather_points_old
    def _gather_points_old(self):
        # In addition to the standard scatterplot _gather_points, we need
        # to also grab the vectors that fall inside the view range
        super(QuiverPlot, self)._gather_points_old()

        if not self.index or not self.value:
            return

        if len(self._cached_point_mask) == 0:
            self._cached_vector_data = []
            return

        vectors = self.vectors.get_data()
        self._cached_vector_data = compress(self._cached_point_mask, vectors, axis=0)

        if self._cached_selected_pts is not None:
            indices = self._cached_selection_point_mask
            self._selected_vector_data = compress(indices, vectors, axis=0)
        else:
            self._selected_vector_data = None
        return

Example 18

Project: chaco Source File: _speedups_fallback.py
def scatterplot_gather_points(index, index_low, index_high,
                              value, value_low, value_high,
                              index_mask=None, index_sel=None, index_sel_mask=None,
                              value_mask=None, value_sel=None, value_sel_mask=None):
    """
    Takes index and value arrays, masks, and optional selection arrays,
    and returns the list of points and corresponding selection mask for
    those points.

    Parameters
    ----------
    index : float array (1D)
       Array of indexes of the points
    index_low : float or None
       The minimum acceptable value in the index array
    index_high : float or None
       The maximum acceptable value in the index array
    value : float array (1D)
       Array of values of the points
    value_low : float or None
       The minimum acceptable value in the value array
    value_high : float or None
       The maximum acceptable value in the value array

    Optional Parameters
    -------------------
    index_mask : bool or int array (1D)
      Mask array for the indexes
    index_sel : sequence of ints
       A list/tuple/array of indices of selected positions in the index array
    index_sel_mask : array of ints or bools
       An mask array with True values indicating which points are selected
    value_mask : bool or int array (1D)
       Mask array for the values
    value_sel : sequence of ints
       A list/tuple/array of indices of selected positions in the value array
    value_sel_mask : array of ints or bools
       An mask array with True values indicating which points are selected

    Returns
    -------
    points : float array (Nx2)
       The points that match all the masking criteria
    sel_mask : bool array (1D)
       Mask indicating which indices in **points** are selected
    """

    index_range_mask = (index_low < index) & (index < index_high)
    value_range_mask = (value_low < value) & (value < value_high)

    nan_mask = array_combine(index_mask, value_mask,
                    func = lambda x: invert(isnan(x)) & x)

    if nan_mask is not None:
        point_mask = nan_mask & index_range_mask & value_range_mask
    else:
        point_mask = index_range_mask & value_range_mask
    points = transpose(array((index, value)))

    # Handle the selection mask
    selection_mask = array_combine(index_sel_mask, value_sel_mask)

    if index_sel is None and value_sel is None:
        pass
    else:
        if index_sel is not None and value_sel is not None:
            mask2 = zeros(len(index), int)
            mask2[index_sel] = 1
            mask2[value_sel] &= 1
        elif index_sel is not None:
            mask2 = zeros(len(index), int)
            mask2[index_sel] = 1
        elif value_sel is not None:
            mask2 = zeros(len(index), int)
            mask2[value_sel] = 1
        if selection_mask is None:
            selection_mask = mask2
        else:
            selection_mask &= mask2

    points = compress(point_mask, points, axis=0)
    if selection_mask is not None:
        selections = compress(point_mask, selection_mask)
    else:
        selections = None
    return points, selections

Example 19

Project: robothon Source File: functions.py
Function: compress
def compress(condition, a, axis=0):
    return np.compress(condition, a, axis)

Example 20

Project: robothon Source File: functions.py
Function: compress
def compress(condition, m, axis=-1):
    return np.compress(condition, m, axis)

Example 21

Project: seaborn Source File: utils.py
def despine(fig=None, ax=None, top=True, right=True, left=False,
            bottom=False, offset=None, trim=False):
    """Remove the top and right spines from plot(s).

    fig : matplotlib figure, optional
        Figure to despine all axes of, default uses current figure.
    ax : matplotlib axes, optional
        Specific axes object to despine.
    top, right, left, bottom : boolean, optional
        If True, remove that spine.
    offset : int or None  (default), optional
        Absolute distance, in points, spines should be moved away
        from the axes (negative values move spines inward).
    trim : bool, optional
        If true, limit spines to the smallest and largest major tick
        on each non-despined axis.

    Returns
    -------
    None

    """
    # Get references to the axes we want
    if fig is None and ax is None:
        axes = plt.gcf().axes
    elif fig is not None:
        axes = fig.axes
    elif ax is not None:
        axes = [ax]

    for ax_i in axes:
        for side in ["top", "right", "left", "bottom"]:
            # Toggle the spine objects
            is_visible = not locals()[side]
            ax_i.spines[side].set_visible(is_visible)
            if offset is not None and is_visible:
                _set_spine_position(ax_i.spines[side], ('outward', offset))

        # Set the ticks appropriately
        if bottom:
            ax_i.xaxis.tick_top()
        if top:
            ax_i.xaxis.tick_bottom()
        if left:
            ax_i.yaxis.tick_right()
        if right:
            ax_i.yaxis.tick_left()

        if trim:
            # clip off the parts of the spines that extend past major ticks
            xticks = ax_i.get_xticks()
            if xticks.size:
                firsttick = np.compress(xticks >= min(ax_i.get_xlim()),
                                        xticks)[0]
                lasttick = np.compress(xticks <= max(ax_i.get_xlim()),
                                       xticks)[-1]
                ax_i.spines['bottom'].set_bounds(firsttick, lasttick)
                ax_i.spines['top'].set_bounds(firsttick, lasttick)
                newticks = xticks.compress(xticks <= lasttick)
                newticks = newticks.compress(newticks >= firsttick)
                ax_i.set_xticks(newticks)

            yticks = ax_i.get_yticks()
            if yticks.size:
                firsttick = np.compress(yticks >= min(ax_i.get_ylim()),
                                        yticks)[0]
                lasttick = np.compress(yticks <= max(ax_i.get_ylim()),
                                       yticks)[-1]
                ax_i.spines['left'].set_bounds(firsttick, lasttick)
                ax_i.spines['right'].set_bounds(firsttick, lasttick)
                newticks = yticks.compress(yticks <= lasttick)
                newticks = newticks.compress(newticks >= firsttick)
                ax_i.set_yticks(newticks)

Example 22

Project: nupic Source File: colorbar.py
    def _locate(self, x):
        '''
        Given a possible set of color data values, return the ones
        within range, together with their corresponding colorbar
        data coordinates.
        '''
        if isinstance(self.norm, (colors.NoNorm, colors.BoundaryNorm)):
            b = self._boundaries
            xn = x
            xout = x
        else:
            # Do calculations using normalized coordinates so
            # as to make the interpolation more accurate.
            b = self.norm(self._boundaries, clip=False).filled()
            # We do our own clipping so that we can allow a tiny
            # bit of slop in the end point ticks to allow for
            # floating point errors.
            xn = self.norm(x, clip=False).filled()
            in_cond = (xn > -0.001) & (xn < 1.001)
            xn = np.compress(in_cond, xn)
            xout = np.compress(in_cond, x)
        # The rest is linear interpolation with clipping.
        y = self._y
        N = len(b)
        ii = np.minimum(np.searchsorted(b, xn), N-1)
        i0 = np.maximum(ii - 1, 0)
        #db = b[ii] - b[i0]
        db = np.take(b, ii) - np.take(b, i0)
        db = np.where(i0==ii, 1.0, db)
        #dy = y[ii] - y[i0]
        dy = np.take(y, ii) - np.take(y, i0)
        z = np.take(y, i0) + (xn-np.take(b,i0))*dy/db
        return xout, z