numpy.atleast_1d

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

155 Examples 7

Example 1

Project: rayopt Source File: material.py
Function: init
    def __init__(self, coefficients, typ="sellmeier", **kwargs):
        super(CoefficientsMaterial, self).__init__(**kwargs)
        if not hasattr(self, "n_%s" % typ):
            warnings.warn("unknown dispersion %s (%s)" % (typ, self.name))
        self.typ = typ
        self.coefficients = np.atleast_1d(coefficients)

Example 2

Project: quaternion Source File: __init__.py
Function: as_float_array
def as_float_array(a):
    """View the quaternion array as an array of floats

    This function is fast (of order 1 microsecond) because no data is
    copied; the returned quantity is just a "view" of the original.

    The output view has one more dimension (of size 4) than the input
    array, but is otherwise the same shape.

    """
    a = np.atleast_1d(a)
    assert a.dtype == np.dtype(np.quaternion)
    if a.shape == ():
        return a.components
    av = a.view(np.float)
    av = av.reshape(a.shape + (4,))
    return av

Example 3

Project: GPy Source File: linear.py
Function: update_gradients_diag
    def update_gradients_diag(self, dL_dKdiag, X):
        tmp = dL_dKdiag[:, None] * X ** 2
        if self.ARD:
            self.variances.gradient = tmp.sum(0)
        else:
            self.variances.gradient = np.atleast_1d(tmp.sum())

Example 4

Project: hyperopt Source File: anneal.py
    def hp_randint(self, memo, node, label, tid, val):
        """
        Parameters: See `hp_uniform`
        """
        upper = memo[node.arg['upper']]
        val1 = np.atleast_1d(val)
        if val1.size:
            counts = np.bincount(val1, minlength=upper) / float(val1.size)
        else:
            counts = np.zeros(upper)
            prior = 1.0
        prior = self.shrinking(label)
        p = (1 - prior) * counts + prior * (1.0 / upper)
        rval = categorical(p=p, upper=upper, rng=self.rng,
                           size=memo[node.arg['size']])
        return rval

Example 5

Project: tractor Source File: psf.py
Function: setthings
    def _setThings(self, p):
        K = self.mog.K
        self.mog.amp = np.atleast_1d(p[:K])
        pp = p[K:]
        self.mog.mean = np.atleast_2d(pp[:K*2]).reshape(K,2)
        pp = pp[K*2:]
        for i,e in enumerate(self.ellipses):
            e.setAllParams(pp[:3])
            pp = pp[3:]
            self.mog.var[i,:,:] = self.ellipseToVariance(e)

Example 6

Project: mystic Source File: dejong.py
    def hessian_product(self, coeffs, p):
        """evaluates an N-dimensional Rosenbrock hessian product
for p and the given coeffs

The hessian product requires both p and coeffs to have len >= 2."""
        #XXX: not well-tested
        p = atleast_1d(p)
        x = atleast_1d(coeffs)
        Hp = zeros(len(x), dtype=x.dtype)
        Hp[0] = (1200*x[0]**2 - 400*x[1] + 2)*p[0] - 400*x[0]*p[1]
        Hp[1:-1] = -400*x[:-2]*p[:-2]+(202+1200*x[1:-1]**2-400*x[2:])*p[1:-1] \
                   -400*x[1:-1]*p[2:]
        Hp[-1] = -400*x[-2]*p[-2] + 200*p[-1]
        return Hp

Example 7

Project: imusim Source File: vector_splines.py
Function: output
    def _output(self, x, conditions, results, undefined):
        out = np.empty((self._dims, len(np.atleast_1d(x))))
        for cond, result in izip(conditions, results):
            out[:,cond] = result
        out[:,undefined] = np.nan
        return out

Example 8

Project: GPy Source File: constant.py
Function: init
    def __init__(self, input_dim, output_dim, value=0., name='constmap'):
        Mapping.__init__(self, input_dim=input_dim, output_dim=output_dim, name=name)
        value = np.atleast_1d(value)
        if not len(value.shape) ==1:
            raise ValueError("bad constant values: pass a float or flat vectoor")
        elif value.size==1:
            value = np.ones(self.output_dim)*value
        self.C = Param('C', value)
        self.link_parameter(self.C)

Example 9

Project: numdifftools Source File: core.py
Function: call
    def __call__(self, x, *args, **kwds):
        vals = super(Jacobian, self).__call__(np.atleast_1d(x), *args, **kwds)
        if self.full_output:
            vals, info = vals
        if vals.ndim == 3:
            vals =  np.array([np.hstack([np.diag(hj) for hj in hi])
                              for hi in vals])
        if self.full_output:
            return vals, info
        return vals

Example 10

Project: xarray Source File: netcdf3.py
def encode_nc3_attr_value(value):
    if isinstance(value, basestring):
        if not isinstance(value, unicode_type):
            value = value.decode('utf-8')
    else:
        value = coerce_nc3_dtype(np.atleast_1d(value))
        if value.ndim > 1:
            raise ValueError("netCDF attributes must be 1-dimensional")
    return value

Example 11

Project: Kayak Source File: root_nodes.py
Function: init
    def __init__(self, data, batcher=None):
        if batcher is None:
            super(DataNode, self).__init__([])
        else:
            super(DataNode, self).__init__([batcher])

        self._data    = np.atleast_1d(data)
        self._batcher = batcher

Example 12

Project: distributions Source File: stats.py
def sample_discrete(distn,size=[],dtype=np.int32):
    'samples from a one-dimensional finite pmf'
    distn = np.atleast_1d(distn)
    assert (distn >=0).all() and distn.ndim == 1
    if (0 == distn).all():
        return np.random.randint(distn.shape[0],size=size)
    cuemvals = np.cuemsum(distn)
    return np.sum(np.array(random(size))[...,na] * cuemvals[-1] > cuemvals, axis=-1,dtype=dtype)

Example 13

Project: hmf Source File: growth_factor.py
    def _general_case(self, w, x):
        x = np.atleast_1d(x)
        xn_vec = np.linspace(0, x.max(), 1000)

        func = _spline(xn_vec,(xn_vec / (xn_vec ** 3 + 2)) ** 1.5)

        g = np.array([func.integral(0,y) for y in x])
        return ((x ** 3.0 + 2.0) ** 0.5) * (g / x ** 1.5)

Example 14

Project: holoviews Source File: grid.py
Function: aggregate
    @classmethod
    def aggregate(cls, dataset, kdims, function, **kwargs):
        kdims = [kd.name if isinstance(kd, Dimension) else kd for kd in kdims]
        data = {kdim: dataset.data[kdim] for kdim in kdims}
        axes = tuple(dataset.ndims-dataset.get_dimension_index(kdim)-1
                     for kdim in dataset.kdims if kdim not in kdims)
        for vdim in dataset.vdims:
            data[vdim.name] = np.atleast_1d(function(dataset.data[vdim.name],
                                                     axis=axes, **kwargs))

        return data

Example 15

Project: python-acoustics Source File: ambisonics.py
def sn3d(m, n):
    """SN3D or Schmidt semi-normalisation
    
    :param m: order `n`
    :param n: degree `m`
    
    http://en.wikipedia.org/wiki/Ambisonic_data_exchange_formats#SN3D
    
    """
    m = np.atleast_1d(m)
    n = np.atleast_1d(n)
    
    d = np.logical_not(m.astype(bool))
    out = np.sqrt( (2.0 - d)/(4.0*np.pi)  * factorial(n-np.abs(m)) / factorial(n+np.abs(m))  )
    return out

Example 16

Project: icnn Source File: replay_memory.py
Function: init
    def __init__(self, size, dimO, dimA, dtype=np.float32):
        self.size = size
        so = np.concatenate(np.atleast_1d(size, dimO), axis=0)
        sa = np.concatenate(np.atleast_1d(size, dimA), axis=0)
        self.observations = np.empty(so, dtype=dtype)
        self.actions = np.empty(sa, dtype=np.float32)
        self.rewards = np.empty(size, dtype=np.float32)
        self.terminals = np.empty(size, dtype=np.bool)
        self.info = np.empty(size, dtype=object)

        self.n = 0
        self.i = 0

Example 17

Project: westpa Source File: states.py
Function: init
    def __init__(self, state_id, basis_state_id, iter_created, iter_used=None, 
                 istate_type=None, istate_status=None,
                 pcoord=None, 
                 basis_state=None):
        self.state_id = state_id
        self.basis_state_id = basis_state_id
        self.basis_state=basis_state
        self.istate_type = istate_type
        self.istate_status = istate_status
        self.iter_created = iter_created
        self.iter_used = iter_used         
        self.pcoord = numpy.atleast_1d(pcoord)

Example 18

Project: chumpy Source File: ch.py
Function: r
    @property
    def r(self):
        self._call_on_changed()
        if self._cache['r'] is None:
            self._cache['r'] = np.asarray(np.atleast_1d(self.compute_r()), dtype=np.float64, order='C')
            self._cache['rview'] = self._cache['r'].view()
            self._cache['rview'].flags.writeable = False
        
        return self._cache['rview']

Example 19

Project: george Source File: load_data.py
def median_trend(x, y, dt):
    x, y = np.atleast_1d(x), np.atleast_1d(y)
    assert len(x) == len(y)
    r = np.empty(len(y))
    for i, t in enumerate(x):
        inds = np.abs(x-t) < 0.5 * dt
        r[i] = np.median(y[inds])
    return r

Example 20

Project: numdifftools Source File: core.py
Function: vstack
    def _vstack(self, sequence, steps):
        original_shape = list(np.shape(np.atleast_1d(sequence[0].squeeze())))
        ndim = len(original_shape)
        axes = [0, 1, 2][:ndim]
        axes[:2] = axes[1::-1]
        original_shape[:2] = original_shape[1::-1]
        n = 1 if ndim < 2 else original_shape[0]

        f_del = np.vstack([np.atleast_1d(r.squeeze()).transpose(axes).ravel()]
                          for r in sequence)

        h = self._vstack_steps(steps, original_shape, axes, n)

        self._check_equal_size(f_del, h)

        return f_del, h, self._atleast_2d(original_shape, ndim)

Example 21

Project: tractor Source File: brightness.py
    @staticmethod
    def fluxErrorsToMagErrors(flux, flux_invvar):
        flux = np.atleast_1d(flux)
        flux_invvar = np.atleast_1d(flux_invvar)
        dflux = np.zeros(len(flux))
        okiv = (flux_invvar > 0)
        dflux[okiv] = (1./np.sqrt(flux_invvar[okiv]))
        okflux = (flux > 0)
        mag = np.zeros(len(flux))
        mag[okflux] = (NanoMaggies.nanomaggiesToMag(flux[okflux]))
        dmag = np.zeros(len(flux))
        ok = (okiv * okflux)
        dmag[ok] = (np.abs((-2.5 / np.log(10.)) * dflux[ok] / flux[ok]))
        mag[np.logical_not(okflux)] = np.nan
        dmag[np.logical_not(ok)] = np.nan
        return mag.astype(np.float32), dmag.astype(np.float32)

Example 22

Project: tractor Source File: psf.py
Function: setthings
    def _setThings(self, p):
        K = self.mog.K
        self.mog.amp = np.atleast_1d(p[:K])
        pp = p[K:]
        self.mog.mean = np.atleast_2d(pp[:K*2]).reshape(K,2)
        pp = pp[K*2:]
        self.mog.var[:,0,0] = pp[::3]
        self.mog.var[:,1,1] = pp[1::3]
        self.mog.var[:,0,1] = self.mog.var[:,1,0] = pp[2::3]

Example 23

Project: PyAbel Source File: analytical.py
def sym_abel_step_1d(r, A0, r0, r1):
    """
    Produces a symmetrical analytical transform of a 1d step
    """
    A0 = np.atleast_1d(A0)
    d = np.empty(A0.shape + r.shape)
    A0 = A0[np.newaxis, :]
    for sens, mask in enumerate([r >= 0, r <= 0]):
        d[:, mask] = abel_step_analytical(np.abs(r[mask]), A0, r0, r1)

    return d

Example 24

Project: scimath Source File: fitting.py
Function: set_xy
    def set_xy(self, x, y):
        x = numpy.atleast_1d(x)
        y = numpy.atleast_1d(y)

        assert len(x) == y.shape[-1], "x and y arrays must have the same length"

        self.determine_special_case(x, y)
        self._x = x
        self._y = y
        self.initialized = True

Example 25

Project: bayespy Source File: misc.py
def dist_haversine(c1, c2, radius=6372795):

    # Convert coordinates to radians
    lat1 = np.atleast_1d(c1[0])[...,:,None] * np.pi / 180
    lon1 = np.atleast_1d(c1[1])[...,:,None] * np.pi / 180
    lat2 = np.atleast_1d(c2[0])[...,None,:] * np.pi / 180
    lon2 = np.atleast_1d(c2[1])[...,None,:] * np.pi / 180

    dlat = lat2 - lat1
    dlon = lon2 - lon1

    A = np.sin(dlat/2)**2 + np.cos(lat1)*np.cos(lat2)*(np.sin(dlon/2)**2)
    C = 2 * np.arctan2(np.sqrt(A), np.sqrt(1-A))
    
    return radius * C

Example 26

Project: plyades Source File: time.py
def jd_datetime(jd):
    jd = np.atleast_1d(jd)
    cal = jd_calendar(jd)
    try:
        return [
            datetime.datetime(
                year, month, day, hour, minute, second, microsecond)
            for year, month, day, hour, minute, second, microsecond in cal]
    except TypeError:
        return datetime.datetime(*cal)

Example 27

Project: GPflow Source File: param.py
Function: init
    def __init__(self, array, transform=transforms.Identity()):
        Parentable.__init__(self)
        self._array = np.asarray(np.atleast_1d(array), dtype=np_float_type)
        self.transform = transform
        self._tf_array = None
        self._log_jacobian = None
        self.prior = None
        self.fixed = False

Example 28

Project: opticspy Source File: art3d.py
Function: set_3d_properties
    def set_3d_properties(self, zs, zdir):
        # Force the collection to initialize the face and edgecolors
        # just in case it is a scalarmappable with a colormap.
        self.update_scalarmappable()
        offsets = self.get_offsets()
        if len(offsets) > 0:
            xs, ys = list(zip(*offsets))
        else:
            xs = []
            ys = []
        self._offsets3d = juggle_axes(xs, ys, np.atleast_1d(zs), zdir)
        self._facecolor3d = self.get_facecolor()
        self._edgecolor3d = self.get_edgecolor()

Example 29

Project: robothon Source File: test_regression.py
    def test_mem_custom_float_to_array(self, level=rlevel):
        """Ticket 702"""
        class MyFloat:
            def __float__(self):
                return 1

        tmp = np.atleast_1d([MyFloat()])
        tmp2 = tmp.astype(float)

Example 30

Project: pymc3 Source File: distribution.py
Function: init
    def __init__(self, shape, dtype, testval=None, defaults=[], transform=None):
        self.shape = np.atleast_1d(shape)
        if False in (np.floor(self.shape) == self.shape):
            raise TypeError("Expected int elements in shape")
        self.dtype = dtype
        self.type = TensorType(self.dtype, self.shape)
        self.testval = testval
        self.defaults = defaults
        self.transform = transform

Example 31

Project: hyperopt Source File: rdists.py
Function: pmf
    def pmf(self, x):
        x1 = np.atleast_1d(x)
        in_domain = self.in_domain(x1)
        x1_in_domain = x1[in_domain]
        rval = np.zeros_like(x1, dtype=np.float)
        rval_in_domain = self._norm_cdf(np.log(x1_in_domain + 0.5 * self.q))
        rval_in_domain[x1_in_domain != 0] -= self._norm_cdf(
            np.log(x1_in_domain[x1_in_domain != 0] - 0.5 * self.q))
        rval[in_domain] = rval_in_domain
        if isinstance(x, np.ndarray):
            return rval
        else:
            return float(rval)

Example 32

Project: mystic Source File: dejong.py
Function: hessian
    def hessian(self, coeffs):
        """evaluates an N-dimensional Rosenbrock hessian for the given coeffs

The function f''(x) requires len(x) >= 2."""
        x = atleast_1d(coeffs)
        H = diag(-400*x[:-1],1) - diag(400*x[:-1],-1)
        diagonal = zeros(len(x), dtype=x.dtype)
        diagonal[0] = 1200*x[0]-400*x[1]+2
        diagonal[-1] = 200
        diagonal[1:-1] = 202 + 1200*x[1:-1]**2 - 400*x[2:]
        H = H + diag(diagonal)
        return H

Example 33

Project: holoviews Source File: xarray.py
Function: coords
    @classmethod
    def coords(cls, dataset, dim, ordered=False, expanded=False):
        if expanded:
            return util.expand_grid_coords(dataset, dim)
        data = np.atleast_1d(dataset.data[dim].data)
        if ordered and data.shape and np.all(data[1:] < data[:-1]):
            data = data[::-1]
        return data

Example 34

Project: pycalphad Source File: equilibrium.py
def _merge_property_slices(properties, chunk_grid, slices, conds_keys, results):
    "Merge back together slices of 'properties'"
    for prop_slice, prop_arr in zip(chunk_grid, results):
        if not isinstance(prop_arr, Dataset):
            print('Error: {}'.format(prop_arr))
            continue
        all_coords = dict(zip(conds_keys, [np.atleast_1d(sl)[ch]
                                                               for ch, sl in zip(prop_slice, slices)]))
        for dv in properties.data_vars.keys():
            # Have to be very careful with how we assign to 'properties' here
            # We may accidentally assign to a copy unless we index the data variable first
            dv_coords = {key: val for key, val in all_coords.items() if key in properties[dv].coords.keys()}
            properties[dv][dv_coords] = prop_arr[dv]
    return properties

Example 35

Project: pylearn2 Source File: dataset_iterators.py
Function: init
    def __init__(self, dataset, subset_iterator, preprocessor=None,
                 fit_preprocessor=False, which_set=None, return_dict=True):
        self.dataset = dataset
        self.subset_iterator = list(subset_iterator)  # allow generator reuse
        dataset_iterator = dataset.iterator(mode='sequential', num_batches=1,
                                            data_specs=dataset.data_specs,
                                            return_tuple=True)
        self._data = dataset_iterator.next()
        self.preprocessor = preprocessor
        self.fit_preprocessor = fit_preprocessor
        self.which_set = which_set
        if which_set is not None:
            which_set = np.atleast_1d(which_set)
            assert len(which_set)
            for label in which_set:
                if label not in ['train', 'valid', 'test']:
                    raise ValueError("Unrecognized subset '{}'".format(label))
            self.which_set = which_set
        self.return_dict = return_dict

Example 36

Project: westpa Source File: states.py
Function: init
    def __init__(self, label, probability, pcoord=None, auxref=None, state_id=None):
        self.label = label
        self.probability = probability         
        self.pcoord = numpy.atleast_1d(pcoord)
        self.auxref = auxref 
        self.state_id = state_id

Example 37

Project: imusim Source File: splines.py
Function: call
    def __call__(self, x, *args, **kwargs):
        X = np.atleast_1d(x)
        conditions = np.atleast_2d([(X>=start) & (X<=end)
            for start,end in self.validRegions])
        undefined = ~np.any(conditions, axis=0)
        if np.all(undefined):
            results = []
            conditions = []
        else:
            results, conditions = zip(*[(s(X[c], *args, **kwargs), c)
                for c,s in izip(conditions, self.splines) if X[c].size > 0])
        return self._output(x, conditions, results, undefined)

Example 38

Project: python-acoustics Source File: ambisonics.py
def n3d(m, n):
    """N3D or full three-D normalisation
    
    :param m: order `n`
    :param n: degree `m`
    
    http://en.wikipedia.org/wiki/Ambisonic_data_exchange_formats#N3D
    
    """
    n = np.atleast_1d(n)
    return sn3d(m, n) * np.sqrt(2*n+1)

Example 39

Project: pybasicbayes Source File: negativebinomial.py
Function: expected_log_likelihood
    def expected_log_likelihood(self,x):
        Elnp, Eln1mp = self._mf_expected_statistics()
        x = np.atleast_1d(x)
        errs = np.seterr(invalid='ignore')
        out = x*Elnp + self.r*Eln1mp + self._log_base_measure(x,self.r)
        np.seterr(**errs)
        out[np.isnan(out)] = -np.inf
        return out if out.shape[0] > 1 else out[0]

Example 40

Project: daft Source File: daft.py
Function: convert
    def convert(self, *xy):
        """
        Convert from model coordinates to plot coordinates.

        """
        assert len(xy) == 2
        return self.grid_unit * (np.atleast_1d(xy) - self.origin)

Example 41

Project: george Source File: gp.py
Function: check_dimensions
    def _check_dimensions(self, y):
        n, ndim = self._x.shape
        y = np.atleast_1d(y)
        if len(y.shape) > 1:
            raise ValueError("The predicted dimension must be 1-D")
        if len(y) != n:
            raise ValueError("Dimension mismatch")
        return y

Example 42

Project: quaternion Source File: __init__.py
def as_spinor_array(a):
    """View a quaternion array as spinors in two-complex representation

    This function is relatively slow and scales poorly, because memory
    copying is apparently involved -- I think it's due to the
    "advanced indexing" required to swap the columns.

    """
    a = np.atleast_1d(a)
    assert a.dtype == np.dtype(np.quaternion)
    # I'm not sure why it has to be so complicated, but all of these steps
    # appear to be necessary in this case.
    return a.view(np.float).reshape(a.shape + (4,))[..., [0, 3, 2, 1]].ravel().view(np.complex).reshape(a.shape + (2,))

Example 43

Project: pymc3 Source File: blocking.py
    def rmap(self, apt):
        """
        Maps value from array space to dict space

        Parameters
        ----------
        apt : array
        """
        dpt = self.dpt.copy()

        for var, slc, shp, dtyp in self.ordering.vmap:
            dpt[var] = np.atleast_1d(apt)[slc].reshape(shp).astype(dtyp)

        return dpt

Example 44

Project: paramz Source File: param.py
Function: new
    def __new__(cls, name, input_array, default_constraint=None):
        obj = np.atleast_1d(super(Param, cls).__new__(cls, input_array=input_array))
        obj._current_slice_ = (slice(obj.shape[0]),)
        obj._realshape_ = obj.shape
        obj._realsize_ = obj.size
        obj._realndim_ = obj.ndim
        obj._original_ = obj
        return obj

Example 45

Project: plyades Source File: time.py
def calendar_jd(year, month, day, hour=0, minute=0, second=0, microsecond=0):
    year = np.atleast_1d(year)
    month = np.atleast_1d(month)
    day = np.atleast_1d(day)
    hour = np.atleast_1d(hour)
    minute = np.atleast_1d(minute)
    second = np.atleast_1d(second)
    microsecond = np.atleast_1d(microsecond)
    jd = (
        367 * year -
        np.floor((7 * (year + np.floor((month + 9) / 12.0))) * 0.25) +
        np.floor(275 * month / 9) +
        day + 1721013.5 +
        (((microsecond / 1e6 + second) / 60 + minute) / 60 + hour) / 24)
    if len(jd) == 1:
        return np.asscalar(jd)
    else:
        return jd

Example 46

Project: mcedit2 Source File: multi_block.py
def getBlocks(world, x, y, z,
              return_Blocks=True,
              return_Data=False,
              return_BlockLight=False,
              return_SkyLight=False,
              return_Biomes=False):
    """
    High performance method for accessing multiple blocks and their lighting info.

    Requires `world` have a `getChunk(cx, cz)` method
    Requires that method return an object that has a `getBlocks` method that takes the same
    parameters as this one.

    Return the blocks at the requested locations as one or more ndarrays. Returns a
    tuple of ndarrays, one for each `return_` parameter with a True value, in the order
    that the parameters appear. Returns the blocks as raw Block IDs, which you can convert
    to BlockType instances using world.blocktype

    The `x`, `y`, and `z` parameters must have the same shape.

    :param x: Array of x coordinates
    :param y: Array of y coordinates
    :param z: Array of z coordinates
    :param return_Blocks:
    :param return_Data:
    :param return_BlockLight:
    :param return_SkyLight:
    :param return_Biomes:
    :return: GetBlocksResult
    """
    x = numpy.atleast_1d(x)
    y = numpy.atleast_1d(y)
    z = numpy.atleast_1d(z)

    Blocks = Data = BlockLight = SkyLight = Biomes = None
    if return_Blocks:
        Blocks = numpy.zeros(shape=x.shape, dtype='uint16')
    if return_Data:
        Data = numpy.zeros(shape=x.shape, dtype='uint8')
    if return_BlockLight:
        BlockLight = numpy.zeros(shape=x.shape, dtype='uint8')
    if return_SkyLight:
        SkyLight = numpy.zeros(shape=x.shape, dtype='uint8')
    if return_Biomes:
        Biomes = numpy.zeros(shape=x.shape, dtype='uint8')

    result = GetBlocksResult(Blocks, Data, BlockLight, SkyLight, Biomes)

    for cx, cz, x, y, z, mask in coords_by_chunk(x, y, z):
        if not world.containsChunk(cx, cz):
            continue

        chunk = world.getChunk(cx, cz)

        arrays = getChunkBlocks(chunk, x, y, z,
                                return_Blocks,
                                return_Data,
                                return_BlockLight,
                                return_SkyLight,
                                return_Biomes)

        for dest, source in zip(result, arrays):
            if dest is not None and source is not None:
                dest[mask] = source

    return result

Example 47

Project: theano_pyglm Source File: slicesample.py
def slicesample(xx, llh_func, last_llh=None, step=1, step_out=True, x_l=None, x_r=None):
    xx = numpy.atleast_1d(xx)
    dims = xx.shape[0]
    perm = range(dims)
    numpy.random.shuffle(perm)

    if isinstance(step, int) or isinstance(step, float) or \
        isinstance(step, numpy.int) or isinstance(step, numpy.float):
        step = numpy.tile(step, dims)
    elif isinstance(step, tuple) or isinstance(step, list):
        step = numpy.array(step)
 
    if last_llh is None:
        last_llh = llh_func(xx)
 
    for d in perm:
        llh0   = last_llh + numpy.log(numpy.random.rand())
        rr     = numpy.random.rand(1)
        if x_l is None:
            x_l    = xx.copy()
            x_l[d] = x_l[d] - rr*step[d]
        else:
            x_l = numpy.atleast_1d(x_l)
            assert x_l.shape == xx.shape
            assert numpy.all(x_l <= xx)
        if x_r is None:
            x_r    = xx.copy()
            x_r[d] = x_r[d] + (1-rr)*step[d]
        else:
            x_r = numpy.atleast_1d(x_r)
            assert x_r.shape == xx.shape
            assert numpy.all(x_r >= xx)
         
        if step_out:
            llh_l = llh_func(x_l)
            while llh_l > llh0:
                x_l[d] = x_l[d] - step[d]
                llh_l  = llh_func(x_l)
            llh_r = llh_func(x_r)
            while llh_r > llh0:
                x_r[d] = x_r[d] + step[d]
                llh_r  = llh_func(x_r)

        try:
            assert numpy.isfinite(llh0)
            assert numpy.isfinite(llh_l)
            assert numpy.isfinite(llh_r)
        except:
            import pdb; pdb.set_trace()

        x_cur = xx.copy()
        n_steps = 0
        while True:
            xd       = numpy.random.rand()*(x_r[d] - x_l[d]) + x_l[d]
            x_cur[d] = xd
            # print "x_l: %f \tx_curr: %f\tx_r: %f" % (x_l[d], x_cur[d], x_r[d])
            last_llh = llh_func(x_cur)
            if last_llh > llh0:
                xx[d] = xd
                break
            elif xd > xx[d]:
                x_r[d] = xd
            elif xd < xx[d]:
                x_l[d] = xd
            else:
                raise Exception("Slice sampler shrank too far.")
            n_steps += 1

            if n_steps > 20:
                import pdb; pdb.set_trace()
    return xx, last_llh

Example 48

Project: picrust Source File: util.py
def list_of_list_of_str_formatter(grp, header, md, compression):
    """Serialize [[str]] into a BIOM hdf5 compatible form

    Parameters
    ----------
    grp : h5py.Group
        This is ignored. Provided for passthrough
    header : str
        The key in each dict to pull out
    md : list of dict
        The axis metadata
    compression : bool
        Whether to enable dataset compression. This is ignored, provided for
        passthrough

    Returns
    -------
    grp : h5py.Group
        The h5py.Group
    header : str
        The key in each dict to pull out
    md : list of dict
        The modified metadata that can be formatted in hdf5
    compression : bool
        Whether to enable dataset compression.

    Notes
    -----
    This method is intended to be a "passthrough" to BIOM's
    vlen_list_of_str_formatter method. It is a transform method.
    """
    new_md = [{header: atleast_1d(asarray(dumps(m[header])))} for m in md]
    return (grp, header, new_md, compression)

Example 49

Project: auto-sklearn Source File: estimators.py
    def _process_target_classes(self, y):
        y = np.atleast_1d(y)
        if y.ndim == 2 and y.shape[1] == 1:
            warnings.warn("A column-vector y was passed when a 1d array was"
                          " expected. Please change the shape of y to "
                          "(n_samples,), for example using ravel().",
                          sklearn.utils.DataConversionWarning, stacklevel=2)

        if y.ndim == 1:
            # reshape is necessary to preserve the data contiguity against vs
            # [:, np.newaxis] that does not.
            y = np.reshape(y, (-1, 1))

        self._n_outputs = y.shape[1]

        y = np.copy(y)

        self._classes = []
        self._n_classes = []

        for k in six.moves.range(self._n_outputs):
            classes_k, y[:, k] = np.unique(y[:, k], return_inverse=True)
            self._classes.append(classes_k)
            self._n_classes.append(classes_k.shape[0])

        self._n_classes = np.array(self._n_classes, dtype=np.int)

        # TODO: fix metafeatures calculation to allow this!
        if y.shape[1] == 1:
            y = y.flatten()

        return y

Example 50

Project: pycalphad Source File: equilibrium.py
def _eqcalculate(dbf, comps, phases, conditions, output, data=None, per_phase=False, **kwargs):
    """
    WARNING: API/calling convention not finalized.
    Compute the *equilibrium value* of a property.
    This function differs from `calculate` in that it computes
    thermodynamic equilibrium instead of randomly sampling the
    internal degrees of freedom of a phase.
    Because of that, it's slower than `calculate`.
    This plugs in the equilibrium phase and site fractions
    to compute a thermodynamic property defined in a Model.

    Parameters
    ----------
    dbf : Database
        Thermodynamic database containing the relevant parameters.
    comps : list
        Names of components to consider in the calculation.
    phases : list or dict
        Names of phases to consider in the calculation.
    conditions : dict or (list of dict)
        StateVariables and their corresponding value.
    output : str
        Equilibrium model property (e.g., CPM, HM, etc.) to compute.
        This must be defined as an attribute in the Model class of each phase.
    data : Dataset, optional
        Previous result of call to `equilibrium`.
        Should contain the equilibrium configurations at the conditions of interest.
        If the databases are not the same as in the original calculation,
        the results may be meaningless. If None, `equilibrium` will be called.
        Specifying this keyword argument can save the user some time if several properties
        need to be calculated in succession.
    per_phase : bool, optional
        If True, compute and return the property for each phase present.
        If False, return the total system value, weighted by the phase fractions.
    kwargs
        Passed to `calculate`.

    Returns
    -------
    Dataset of property as a function of equilibrium conditions
    """
    if data is None:
        data = equilibrium(dbf, comps, phases, conditions)
    active_phases = unpack_phases(phases) or sorted(dbf.phases.keys())
    conds = _adjust_conditions(conditions)
    indep_vars = ['P', 'T']
    # TODO: Rewrite this to use the coord dict from 'data'
    str_conds = OrderedDict((str(key), value) for key, value in conds.items())
    indep_vals = list([float(x) for x in np.atleast_1d(val)]
                      for key, val in str_conds.items() if key in indep_vars)
    coord_dict = str_conds.copy()
    components = [x for x in sorted(comps) if not x.startswith('VA')]
    coord_dict['vertex'] = np.arange(len(components))
    grid_shape = np.meshgrid(*coord_dict.values(),
                             indexing='ij', sparse=False)[0].shape
    prop_shape = grid_shape
    prop_dims = list(str_conds.keys()) + ['vertex']

    result = Dataset({output: (prop_dims, np.full(prop_shape, np.nan))}, coords=coord_dict)
    # For each phase select all conditions where that phase exists
    # Perform the appropriate calculation and then write the result back
    for phase in active_phases:
        dof = sum([len(x) for x in dbf.phases[phase].constituents])
        current_phase_indices = (data.Phase.values == phase)
        if ~np.any(current_phase_indices):
            continue
        points = data.Y.values[np.nonzero(current_phase_indices)][..., :dof]
        statevar_indices = np.nonzero(current_phase_indices)[:len(indep_vals)]
        statevars = {key: np.take(np.asarray(vals), idx)
                     for key, vals, idx in zip(indep_vars, indep_vals, statevar_indices)}
        statevars.update(kwargs)
        if statevars.get('mode', None) is None:
            statevars['mode'] = 'numpy'
        calcres = calculate(dbf, comps, [phase], output=output,
                            points=points, broadcast=False, **statevars)
        result[output].values[np.nonzero(current_phase_indices)] = calcres[output].values
    if not per_phase:
        result[output] = (result[output] * data['NP']).sum(dim='vertex', skipna=True)
    else:
        result['Phase'] = data['Phase'].copy()
        result['NP'] = data['NP'].copy()
    return result
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3 Page 4