numpy.isscalar

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

168 Examples 7

Example 1

Project: SPGL1_python_port Source File: oneProjector.py
def oneProjectorMex(b,d,tau=-1):

    if tau==-1:
       tau = d
       d   = 1

    if np.isscalar(d):
        return oneProjectorMex_I(b,tau/abs(d))
    else:
        return oneProjectorMex_D(b,d,tau)

Example 2

Project: holoviews Source File: dictionary.py
Function: sample
    @classmethod
    def sample(cls, dataset, samples=[]):
        mask = False
        for sample in samples:
            sample_mask = True
            if np.isscalar(sample): sample = [sample]
            for i, v in enumerate(sample):
                name = dataset.get_dimension(i).name
                sample_mask &= (np.array(dataset.data[name])==v)
            mask |= sample_mask
        return {k: np.array(col)[mask]
                for k, col in dataset.data.items()}

Example 3

Project: smop Source File: core.py
Function: is_scalar
def isscalar(a):
    """np.isscalar returns True if a.__class__ is a scalar
    type (i.e., int, and also immutable containers str and
    tuple, but not list.) Our requirements are different"""
    try:
        return a.size == 1
    except AttributeError:
        return np.isscalar(a)

Example 4

Project: ts-charting Source File: heatmap.py
Function: gen_labels
def _gen_labels(labels, names=None):
    if names is None:
        names = labels.names
    if np.isscalar(labels[0]):
        labels = [(l,) for l in labels]
    zips = [list(zip(names, l)) for l in labels]
    new_labels = [', '.join(['{1}'.format(*m) for m in z]) for z in zips]
    return new_labels, names

Example 5

Project: moviepy Source File: audio_left_right.py
def audio_left_right(audioclip, left=1, right=1, merge=False):
    """
    NOT YET FINISHED 
    
    For a stereo audioclip, this function enables to change the volume
    of the left and right channel separately (with the factors `left`
    and `right`)
    Makes a stereo audio clip in which the volume of left and right
    is controllable
    """
    funleft = (lambda t: left) if np.isscalar(left) else left
    funright = (lambda t: right) if np.isscalar(right) else right

Example 6

Project: tardis Source File: analysis.py
    def load_t_inner(self, iterations=None):
        t_inners = []
        hdf_store = pd.HDFStore(self.hdf5_fname, 'r')

        if iterations is None:
            iterations = self.iterations
        elif np.isscalar(iterations):
            iterations = [self.iterations[iterations]]
        else:
            iterations = self.iterations[iterations]

        for iter in iterations:
            t_inners.append(hdf_store['model%03d/configuration' %iter].ix['t_inner'])
        hdf_store.close()

        t_inners = np.array(t_inners)
        return t_inners

Example 7

Project: hyperion Source File: image.py
    @lon_min.setter
    def lon_min(self, value):
        if value is None or (np.isscalar(value) and np.isreal(value)):
            self._lon_min = value
        else:
            raise ValueError("lon_min should be a real scalar value")

Example 8

Project: scikit-image Source File: plotplugin.py
Function: add_plot
    def add_plot(self):
        self.fig, self.ax = new_plot()
        self.fig.set_figwidth(self._width / float(self.fig.dpi))
        self.fig.set_figheight(self._height / float(self.fig.dpi))

        self.canvas = self.fig.canvas
        #TODO: Converted color is slightly different than Qt background.
        qpalette = QtGui.QPalette()
        qcolor = qpalette.color(QtGui.QPalette.Window)
        bgcolor = qcolor.toRgb().value()
        if np.isscalar(bgcolor):
            bgcolor = str(bgcolor / 255.)
        self.fig.patch.set_facecolor(bgcolor)
        self.layout.addWidget(self.canvas, self.row, 0)

Example 9

Project: FaST-LMM Source File: glmm.py
    @sig12.setter
    def sig12(self, v):
        assert NP.isscalar(v)
        assert NP.isfinite(v)
        if self._sig12 == v:
            return
        self._updateApproximationCount += 1
        self._sig12 = v

Example 10

Project: sfepy Source File: potentials.py
Function: sub
    def __sub__(self, other):
        if isinstance(other, PotentialBase):
            out = CompoundPotential([self, -1.0 * other])

        elif nm.isscalar(other):
            if other == 0:
                out = self

            else:
                out = NotImplemented

        else:
            out = NotImplemented

        return out

Example 11

Project: trtools Source File: base.py
def generic_wrap(data):
    """
        This is to handle cases like aggregate where the return 
        can be anything from a scalar to a panel. 

        This is useful when using DataFrames and ColumnPanels. 
        ColumnPanels are meant to be interchangable with DataFrames.
        Aggregating results is a common thing, this is to make that easier.
    """
    if isinstance(data, (pd.Panel, pd.DataFrame, pd.Series)):
        return data

    if np.isscalar(data):
       return data

    if isinstance(data, dict):
       return _generic_wrap_dict(data)

Example 12

Project: 3D-R2N2 Source File: binvox_rw.py
Function: sparse_to_dense
def sparse_to_dense(voxel_data, dims, dtype=np.bool):
    if voxel_data.ndim != 2 or voxel_data.shape[0] != 3:
        raise ValueError('voxel_data is wrong shape; should be 3xN array.')
    if np.isscalar(dims):
        dims = [dims] * 3
    dims = np.atleast_2d(dims).T
    # truncate to integers
    xyz = voxel_data.astype(np.int)
    # discard voxels that fall outside dims
    valid_ix = ~np.any((xyz < 0) | (xyz >= dims), 0)
    xyz = xyz[:, valid_ix]
    out = np.zeros(dims.flatten(), dtype=dtype)
    out[tuple(xyz)] = True
    return out

Example 13

Project: spectral Source File: spyfile.py
def assert_same_shape_almost_equal(obj1, obj2, decimal=7, err_msg='',
                                   verbose=True):
    """
    Assert that two objects are almost equal and have the same shape.

    numpy.testing.assert_almost_equal does test for shape, but considers
    arrays with one element and a scalar to be the same.
    """
    # Types might be different since ImageArray stores things as
    # floats by default.
    if np.isscalar(obj1):
        assert np.isscalar(obj2), err_msg
    else:
        assert obj1.shape == obj2.shape, err_msg

    assert_almost_equal(obj1, obj2, decimal=decimal, err_msg=err_msg,
                        verbose=verbose)

Example 14

Project: py-sdm Source File: features.py
Function: get_item
    def __getitem__(self, key):
        if (isinstance(key, str_types) or
                (isinstance(key, tuple) and
                 any(isinstance(x, str_types) for x in key))):
            raise TypeError("Features indexing only subsets rows")

        if np.isscalar(key):
            return self.data[key]
        else:
            return type(self).from_data(self.data[key], copy=False)

Example 15

Project: scikit-beam Source File: test_histogram.py
def _1d_histogram_tester(binlowhighs, x, weights=1):
    h = Histogram(binlowhighs)
    h.fill(x, weights=weights)
    if np.isscalar(weights):
        ynp = np.histogram(x, h.edges[0])[0]
    else:
        ynp = np.histogram(x, h.edges[0], weights=weights)[0]
    assert_array_almost_equal(ynp, h.values)
    h.reset()
    h._always_use_fillnd = True
    h.fill(x, weights=weights)
    assert_array_almost_equal(ynp, h.values)

Example 16

Project: fos Source File: bundle_picker.py
    def unselect_track(self, ids):
        """Do visual un-selection of given virtuals.
        """
        if ids == 'all':
            ids = range(len(self.virtuals))
        elif np.isscalar(ids):
            ids = [ids]
        for id in ids:
            if id in self.old_color:
                self.virtuals_colors[self.virtuals_first[id]:self.virtuals_first[id]+self.virtuals_count[id],:] = self.old_color[id]
                if self.verbose: print("Setting old color: %s" % self.old_color[id][0])
                self.old_color.pop(id)
                if id in self.selected:
                    self.selected.remove(id)
                else:
                    print('WARNING: unselecting id %s but not in %s' % (id, self.selected))

Example 17

Project: mpltools Source File: errorfill.py
def extrema_from_error_input(z, zerr):
    if np.isscalar(zerr) or len(zerr) == len(z):
        zmin = z - zerr
        zmax = z + zerr
    elif len(zerr) == 2:
        zmin, zmax = z - zerr[0], z + zerr[1]
    return zmin, zmax

Example 18

Project: vsm Source File: wrappers.py
def dismat_top(topics, mat, dist_fn=JS_dist):
    """
    Calculates a distance matrix for a given list of topics.
    
    The columns of `mat` are assumed to be probability distributions
    (namely, topics).
    """
    mat = mat[:,topics]

    dm = dist_fn(mat.T, mat)
    if np.isscalar(dm):
        dm = np.array([dm])
    dm = dm.view(IndexedSymmArray)
    dm.labels = [str(k) for k in topics]
    
    return dm

Example 19

Project: pyqtgraph Source File: ScatterPlotItem.py
Function: draw_symbol
def drawSymbol(painter, symbol, size, pen, brush):
    if symbol is None:
        return
    painter.scale(size, size)
    painter.setPen(pen)
    painter.setBrush(brush)
    if isinstance(symbol, basestring):
        symbol = Symbols[symbol]
    if np.isscalar(symbol):
        symbol = list(Symbols.values())[symbol % len(Symbols)]
    painter.drawPath(symbol)

Example 20

Project: aplpy Source File: wcs_util.py
def world2pix(wcs, x_world, y_world):
    if np.isscalar(x_world) and np.isscalar(y_world):
        x_pix, y_pix = wcs.wcs_world2pix(np.array([x_world]), np.array([y_world]), 1)
        return x_pix[0], y_pix[0]
    elif (type(x_world) == list) and (type(y_world) == list):
        x_pix, y_pix = wcs.wcs_world2pix(np.array(x_world), np.array(y_world), 1)
        return x_pix.tolist(), y_pix.tolist()
    elif isinstance(x_world, np.ndarray) and isinstance(y_world, np.ndarray):
        return wcs.wcs_world2pix(x_world, y_world, 1)
    else:
        raise Exception("world2pix should be provided either with two scalars, two lists, or two numpy arrays")

Example 21

Project: moviepy Source File: audio_fadein.py
@audio_video_fx
def audio_fadein(clip, duration):
    """ Return an audio (or video) clip that is first mute, then the
        sound arrives progressively over ``duration`` seconds. """
        
    def fading(gf,t):
        gft = gf(t)
        
        if np.isscalar(t):
            factor = min(1.0 * t / duration, 1)
            factor = np.array([factor,factor])
        else:
            factor = np.minimum(1.0 * t / duration, 1)
            factor = np.vstack([factor,factor]).T
        return factor * gft
    return clip.fl(fading, keep_duration = True)

Example 22

Project: moviepy Source File: audio_fadeout.py
@audio_video_fx
@requires_duration
def audio_fadeout(clip, duration):
    """ Return a sound clip where the sound fades out progressively
        over ``duration`` seconds at the end of the clip. """
    
    def fading(gf,t):
        gft = gf(t)
        
        if np.isscalar(t):
            factor = min(1.0 * (clip.duration - t) / duration, 1)
            factor = np.array([factor,factor])
        else:
            factor = np.minimum( 1.0 * (clip.duration - t) / duration, 1)
            factor = np.vstack([factor,factor]).T
        return factor * gft
    
    return clip.fl(fading, keep_duration = True)

Example 23

Project: python-qinfer Source File: finite_difference.py
Function: init
    def __init__(self, func, n_args, h=1e-10):
        self.func = func
        self.n_args = n_args
        if np.isscalar(h): 
            self.h = h * np.ones((n_args,))
        else:
            self.h = h

Example 24

Project: tia Source File: table.py
    def set_row_heights(self, pcts=None, amts=None, maxs=None, mins=None):
        """
        :param pcts: the percent of available height to use or ratio is also ok
        :param amts: (Array or scalar) the fixed height of the rows
        :param maxs: (Array or scalar) the maximum height of the rows (only use when pcts is used)
        :param mins: (Array or scalar) the minimum height of the rows (only used when pcts is used)
        :return:
        """
        for arr, attr in zip([pcts, amts, maxs, mins], ['weight', 'value', 'max', 'min']):
            if arr is not None:
                if not np.isscalar(arr):
                    if len(arr) != len(self.formatted_values.index):
                        raise ValueError(
                            '%s: expected %s rows but got %s' % (attr, len(arr), len(self.formatted_values.index)))
                self.rowattrs.ix[:, attr] = arr
        return self

Example 25

Project: sherpa Source File: data.py
    def _set_mask(self, val):
        if (val is True) or (val is False):
            self._mask = val
        elif (val is None) or numpy.isscalar(val):
            raise DataErr('ismask')
        else:
            self._mask = numpy.asarray(val, numpy.bool_)
        self._filter = None

Example 26

Project: cvxpy Source File: key_utils.py
def is_special_slice(key):
    """Does the key contain a list, ndarray, or logical ndarray?
    """
    # Key is either a tuple of row, column keys or a single row key.
    if isinstance(key, tuple):
        if len(key) > 2:
            raise IndexError("Invalid index/slice.")
        key_elems = [key[0], key[1]]
    else:
        key_elems = [key]

    # Slices and int-like numbers are fine.
    for elem in key_elems:
        if not (isinstance(elem, (numbers.Number, slice)) or np.isscalar(elem)):
            return True

    return False

Example 27

Project: ProxImaL Source File: lin_op.py
    def format_shape(self, shape):
        """Cast shape to a tuple.
        """
        # Convert scalars to tuples.
        if np.isscalar(shape):
            shape = (shape,)
        return tuple(shape)

Example 28

Project: theano_pyglm Source File: priors.py
Function: init
    def __init__(self, model):
        self.prms = model

        a = self.prms['alpha0']
        if np.isscalar(a):
            # Specified a symmetric Dirichlet prior
            R = self.prms['R']
            a = a * np.ones(R)
        else:
            assert a.ndim == 1

        self.alpha0 = theano.shared(name='alpha0', value=a)

Example 29

Project: trtools Source File: base.py
def _generic_wrap_dict(data):
    if len(data) == 0:
        return None

    test = next(iter(data.values()))

    if np.isscalar(test):
        return pd.Series(data)

    if isinstance(test, pd.Series):
        return pd.DataFrame(data)

    if isinstance(test, pd.DataFrame):
        return pd.Panel.from_dict(data)

Example 30

Project: PRST Source File: rock.py
def _expandToCell(vals, num_cells):
    if np.isscalar(vals):
        # If scalar, convert to 2d array
        vals = np.array([[vals]])
        return np.tile(vals, (num_cells,1))
    elif vals.ndim == 1:
        # Do nothing if 1d array, just check that dimensions are correct.
        assert vals.shape[0] == num_cells
        return vals
    elif vals.ndim == 2 and vals.shape[0] == 1:
        # Duplicate the row to each cell
        return np.tile(vals, (num_cells,1))
    elif vals.ndim == 2 and vals.shape[0] == num_cells:
        # Do nothing, data was correct
        return vals
    else:
        raise ValueError("Invalid input data dimensions")

Example 31

Project: binvox-rw-py Source File: binvox_rw.py
Function: sparse_to_dense
def sparse_to_dense(voxel_data, dims, dtype=np.bool):
    if voxel_data.ndim!=2 or voxel_data.shape[0]!=3:
        raise ValueError('voxel_data is wrong shape; should be 3xN array.')
    if np.isscalar(dims):
        dims = [dims]*3
    dims = np.atleast_2d(dims).T
    # truncate to integers
    xyz = voxel_data.astype(np.int)
    # discard voxels that fall outside dims
    valid_ix = ~np.any((xyz < 0) | (xyz >= dims), 0)
    xyz = xyz[:,valid_ix]
    out = np.zeros(dims.flatten(), dtype=dtype)
    out[tuple(xyz)] = True
    return out

Example 32

Project: statsmodels Source File: pca.py
    def sigclip(self,sigs):
        """
        clips out all data points that are more than a certain number
        of standard deviations from the mean.

        sigs can be either a single value or a length-p sequence that
        specifies the number of standard deviations along each of the
        p dimensions.
        """
        if np.isscalar(sigs):
            sigs=sigs*np.ones(self.N.shape[1])
        sigs = sigs*np.std(self.N,axis=1)
        n = self.N.shape[0]
        m = np.all(np.abs(self.N) < sigs,axis=1)
        self.A=self.A[m]
        self.__calc()
        return n-sum(m)

Example 33

Project: skl-groups Source File: features.py
Function: get_item
    def __getitem__(self, key):
        if (isinstance(key, string_types) or
                (isinstance(key, (tuple, list)) and
                 any(isinstance(x, string_types) for x in key))):
            msg = "Features indexing only subsets rows, but got {!r}"
            raise TypeError(msg.format(key))

        if np.isscalar(key):
            return self.features[key]
        else:
            return type(self)(self.features[key], copy=False, stack=False,
                              **{k: v[key] for k, v in iteritems(self.meta)})

Example 34

Project: xarray Source File: utils.py
def to_0d_array(value):
    """Given a value, wrap it in a 0-D numpy.ndarray."""
    if np.isscalar(value) or (isinstance(value, np.ndarray)
                                and value.ndim == 0):
        return np.array(value)
    else:
        return to_0d_object_array(value)

Example 35

Project: tractor Source File: brightness.py
Function: add
    def __add__(self, other):
        # mags + 0.1
        if np.isscalar(other):
            kwargs = {}
            for band in self.order:
                m1 = self.getMag(band)
                kwargs[band] = m1 + other
            return Mags(order=self.order, **kwargs)

        # ASSUME some things about calibration here...
        kwargs = {}
        for band in self.order:
            m1 = self.getMag(band)
            m2 = other.getMag(band)
            msum = -2.5 * np.log10( 10.**(-m1/2.5) + 10.**(-m2/2.5) )
            kwargs[band] = msum
        return Mags(order=self.order, **kwargs)

Example 36

Project: tardis Source File: analysis.py
    def load_t_rads(self, iterations=None):
        t_rads_dict = {}
        hdf_store = pd.HDFStore(self.hdf5_fname, 'r')

        if iterations is None:
            iterations = self.iterations
        elif np.isscalar(iterations):
            iterations = [self.iterations[iterations]]
        else:
            iterations = self.iterations[iterations]


        for iter in iterations:
            current_iter = 'iter%03d' % iter
            t_rads_dict[current_iter] = hdf_store['model%03d/t_rads' % iter]

        t_rads = pd.DataFrame(t_rads_dict)
        hdf_store.close()
        return t_rads

Example 37

Project: hyperion Source File: image.py
    @y_max.setter
    def y_max(self, value):
        if value is None or (np.isscalar(value) and np.isreal(value)):
            self._y_max = value
        else:
            raise ValueError("y_max should be a real scalar value")

Example 38

Project: scikit-beam Source File: test_histogram.py
def _2d_histogram_tester(binlowhighs, x, y, weights=1):
    h = Histogram(*binlowhighs)
    h.fill(x, y, weights=weights)
    if np.isscalar(weights):
        if np.isscalar(x):
            assert np.isscalar(y), 'If x is a scalar, y must be also'
            ynp = np.histogram2d([x], [y], bins=h.edges)[0]
        else:
            ynp = np.histogram2d(x, y, bins=h.edges)[0]
    else:
        ynp = np.histogram2d(x, y, bins=h.edges, weights=weights)[0]
    assert_array_almost_equal(ynp, h.values)
    h.reset()
    h._always_use_fillnd = True
    h.fill(x, y, weights=weights)
    assert_array_almost_equal(ynp, h.values)

Example 39

Project: nifty Source File: nifty_power.py
def _calc_inverse(tk,var,kindex,rho,b1,Amem): ## > computes the inverse Hessian `A` and `b2`
    ## operator `T` from Eq.(B8) times 2
    if(Amem is None):
        L,I = _calc_laplace(kindex)
        #T2 = 2*np.dot(L.T,np.dot(np.diag(I/var,k=0),L,out=None),out=None) # Eq.(B8) * 2
        if(np.isscalar(var)):
            Amem = np.dot(L.T,np.dot(np.diag(I,k=0),L,out=None),out=None)
            T2 = 2/var*Amem
        else:
            Amem = np.dot(np.diag(np.sqrt(I),k=0),L,out=None)
            T2 = 2*np.dot(Amem.T,np.dot(np.diag(1/var,k=0),Amem,out=None),out=None)
    elif(np.isscalar(var)):
        T2 = 2/var*Amem
    else:
        T2 = 2*np.dot(Amem.T,np.dot(np.diag(1/var,k=0),Amem,out=None),out=None)
    b2 = b1+np.dot(T2,tk,out=None)
    ## inversion
    return np.linalg.inv(T2+np.diag(b2,k=0)),b2,Amem

Example 40

Project: pyff Source File: LanguageModel.py
    def _create_word_table(self, ascii_table):
        word_table = []
        ascii_table = squeeze(ascii_table)
        for matrix in ascii_table:
            table = []
            if matrix.size > 0:
                for row in matrix:
                    if isscalar(row):
                        table.append(chr(row))
                    else:
                        s = ''
                        for elem in row:
                            s = s + chr(elem)
                        table.append(s)
            word_table.append(table)
        return word_table

Example 41

Project: holoviews Source File: array.py
Function: sample
    @classmethod
    def sample(cls, dataset, samples=[]):
        data = dataset.data
        mask = False
        for sample in samples:
            sample_mask = True
            if np.isscalar(sample): sample = [sample]
            for i, v in enumerate(sample):
                sample_mask &= data[:, i]==v
            mask |= sample_mask

        return data[mask]

Example 42

Project: chainer Source File: reporter.py
    def add(self, d):
        """Adds a dictionary of scalars.

        Args:
            d (dict): Dictionary of scalars to accuemulate. Only elements of
               scalars, zero-dimensional arrays, and variables of
               zero-dimensional arrays are accuemulated.

        """
        summaries = self._summaries
        for k, v in six.iteritems(d):
            if isinstance(v, variable.Variable):
                v = v.data
            if numpy.isscalar(v) or getattr(v, 'ndim', -1) == 0:
                summaries[k].add(v)

Example 43

Project: aplpy Source File: test_pixworld.py
Function: test_return_types
def test_returntypes():
    wcs = generate_wcs(HEADER)
    ra, dec = wcs_util.pix2world(wcs, 1.,2.)
    assert np.isscalar(ra) and np.isscalar(dec)
    ra, dec = wcs_util.pix2world(wcs, [1.],[2.])
    assert (type(ra) == list) and (type(dec) == list)
    # Astropy.table.Column objects get donwconverted np.ndarray
    ra, dec = wcs_util.pix2world(wcs, np.arange(2), tab['DEC'])
    assert isinstance(ra, np.ndarray) and isinstance(dec, np.ndarray)

Example 44

Project: smop Source File: sparsearray.py
Function: set_item
    def __setitem__(self,index,value):
        if np.isscalar(value):
            for key in self.iterkeys(index):
                dict.__setitem__(self,key,value)
            self._shape = None
        else:
            raise NotImplementedError

Example 45

Project: sfepy Source File: potentials.py
Function: add
    def __add__(self, other):
        if isinstance(other, PotentialBase):
            out = CompoundPotential([self, other])

        elif nm.isscalar(other):
            if other == 0:
                out = self

            else:
                out = NotImplemented

        else:
            out = NotImplemented

        return out

Example 46

Project: chainer Source File: basic_math.py
def _check_constant_type(value):
    if numpy.isscalar(value):
        return
    elif isinstance(value, (numpy.ndarray, cuda.ndarray)):
        return
    else:
        raise ValueError(
            'value must be scalar, ndarray, or Variable')

Example 47

Project: pvlib-python Source File: tools.py
def _scalar_out(input):
    if np.isscalar(input):
        output = input
    else:  #
        # works if it's a 1 length array and
        # will throw a ValueError otherwise
        output = np.asscalar(input)

    return output

Example 48

Project: fastnet Source File: layer.py
Function: dump
  def dump(self):
    attr = [att for att in dir(self) if not att.startswith('__')]
    d = {}
    for att in attr:
      val = getattr(self, att)
      if isinstance(val, tuple) or np.isscalar(val):
        d[att] = val
    return d

Example 49

Project: simpeg Source File: Maps.py
Function: np
    @property
    def nP(self):
        if np.isscalar(self.order):
            nP = self.order+3
        else:
            nP = (self.order[0]+1)*(self.order[1]+1)+2
        return nP

Example 50

Project: ProxImaL Source File: prox_fn.py
Function: mul
    def __mul__(self, other):
        """ProxFn * Number.
        """
        # Can only multiply by scalar constants.
        if np.isscalar(other) and other > 0:
            return self.copy(alpha=self.alpha * other)
        else:
            raise TypeError("Can only multiply by a positive scalar.")
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3 Page 4