python类asanyarray()的实例源码

dqn.py 文件源码 项目:deel 作者: uei 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def start(self,x=None):
        if x is None:
            x=Tensor.context


        obs_array = x.content.data
        #print "sum",obs_array.sum()

        # Initialize State
        self.state = np.zeros((self.func.hist_size, self.image_feature_dim), dtype=np.uint8)
        self.state[0] = obs_array
        state_ = np.asanyarray(self.state.reshape(1, self.func.hist_size, self.image_feature_dim), dtype=np.float32)
        if Deel.gpu >= 0:
            state_ = cuda.to_gpu(state_)

        # Generate an Action e-greedy
        action, Q_now = self.func.e_greedy(state_, self.epsilon)
        returnAction = action

        # Update for next step
        self.lastAction = copy.deepcopy(returnAction)
        self.last_state = self.state.copy()
        self.last_observation = obs_array

        return returnAction
woa.py 文件源码 项目:oceansdb 作者: castelao 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def crop(self, doy, depth, lat, lon, var):
        """ Crop a subset of the dataset for each var

            Given doy, depth, lat and lon, it returns the smallest subset
              that still contains the requested coordinates inside it.

            It handels special cases like a region around greenwich and
            the international date line.

            Accepts 0 to 360 and -180 to 180 longitude reference.

            It extends time and longitude coordinates, so simplify the use
               of series. For example, a ship track can be requested with
               a longitude sequence like [352, 358, 364, 369, 380], and
               the equivalent for day of year above 365.
        """
        dims, idx = cropIndices(self.dims, lat, lon, depth, doy)
        subset = {}
        for v in var:
            subset[v] = ma.asanyarray([
                self.ncs[tnn][v][0, idx['zn'], idx['yn'], idx['xn']] \
                        for tnn in idx['tn']])
        return subset, dims
cars.py 文件源码 项目:oceansdb 作者: castelao 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def __getitem__(self, item):
        """ t, z, y, x
        """
        tn, zn, yn, xn = item

        #if type(zn) is not slice:
        #    zn = slice(zn, zn+1)
        #zn_an = slice(zn.start, min(64, zn.stop), zn.step)
        #zn_sa = slice(zn.start, min(55, zn.stop), zn.step)

        output = []
        d = 2 * np.pi * (np.arange(1, 367)[tn])/366
        for t in np.atleast_1d(d):
            tmp = self.nc['mean'][:, yn, xn]

            tmp[:64] += self.nc['an_cos'][:, yn, xn] * np.cos(t) + \
                    self.nc['an_sin'][:, yn, xn] * np.sin(t)
            tmp[:55] += self.nc['sa_cos'][:, yn, xn] * np.cos(2*t) + \
                    self.nc['sa_sin'][:, yn, xn] * np.sin(2*t)
            output.append(tmp[zn])

        return ma.asanyarray(output)
geometry.py 文件源码 项目:pyhiro 作者: wanweiwei07 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def rotation_2D_to_3D(matrix_2D):
    '''
    Given a 2D homogenous rotation matrix convert it to a 3D rotation
    matrix that is rotating around the Z axis

    Arguments
    ----------
    matrix_2D: (3,3) float, homogenous 2D rotation matrix

    Returns
    ----------
    matrix_3D: (4,4) float, homogenous 3D rotation matrix
    '''

    matrix_2D = np.asanyarray(matrix_2D)
    if matrix_2D.shape != (3,3):
        raise ValueError('Homogenous 2D transformation matrix required!')

    matrix_3D = np.eye(4)    
    # translation
    matrix_3D[0:2, 3]   = matrix_2D[0:2,2] 
    # rotation from 2D to around Z
    matrix_3D[0:2, 0:2] = matrix_2D[0:2,0:2]

    return matrix_3D
grouping.py 文件源码 项目:pyhiro 作者: wanweiwei07 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def unique_ordered(data):
    '''
    Returns the same as np.unique, but ordered as per the
    first occurance of the unique value in data.

    Example
    ---------
    In [1]: a = [0, 3, 3, 4, 1, 3, 0, 3, 2, 1]

    In [2]: np.unique(a)
    Out[2]: array([0, 1, 2, 3, 4])

    In [3]: trimesh.grouping.unique_ordered(a)
    Out[3]: array([0, 3, 4, 1, 2])
    '''
    data   = np.asanyarray(data)
    order  = np.sort(np.unique(data, return_index=True)[1])
    result = data[order]
    return result
visual.py 文件源码 项目:pyhiro 作者: wanweiwei07 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def rgba(colors, dtype=None):
    '''
    Convert an RGB color to an RGBA color.

    Arguments
    ----------
    colors: (n,[3|4]) set of RGB or RGBA colors

    Returns
    ----------
    colors: (n,4) set of RGBA colors
    '''
    if not is_sequence(colors): 
        return
    if dtype is None:
        dtype = COLOR_DTYPE
    colors = np.asanyarray(colors, dtype=dtype)
    if is_shape(colors, (-1,3)):
        opaque = (2**(np.dtype(dtype).itemsize * 8)) - 1
        colors = np.column_stack((colors,
                                  opaque * np.ones(len(colors)))).astype(dtype)
    return colors
misc.py 文件源码 项目:pyhiro 作者: wanweiwei07 项目源码 文件源码 阅读 38 收藏 0 点赞 0 评论 0
def lines_to_path(lines):
    '''
    Given a set of line segments (n, 2, [2|3]), populate a path
    '''
    lines = np.asanyarray(lines)

    if is_shape(lines, (-1, (2,3))):
        result = {'entities' : np.array([Line(np.arange(len(lines)))]),
                  'vertices' : lines}
        return result
    elif is_shape(lines, (-1,2,(2,3))):
        entities = [Line([i, i+1]) for i in range(0, (lines.shape[0]*2) - 1, 2)]
        vertices = lines.reshape((-1,lines.shape[2]))
        result = {'entities' : entities,
                  'vertices' : vertices}
    else:
        raise ValueError('Lines must be (n,(2|3)) or (n,2,(2|3))')
    return result
simplify.py 文件源码 项目:pyhiro 作者: wanweiwei07 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def resample_spline(points, smooth=.001, count=None):
    from scipy.interpolate import splprep, splev
    if count is None: 
        count = len(points)    
    points = np.asanyarray(points)
    closed = np.linalg.norm(points[0] - points[-1]) < tol.merge 

    tpl = splprep(points.T, s=smooth)[0]
    i = np.linspace(0.0, 1.0, count)
    resampled = np.column_stack(splev(i, tpl))

    if closed:
        shared = resampled[[0,-1]].mean(axis=0)
        resampled[0]  = shared
        resampled[-1] = shared

    return resampled
simplify.py 文件源码 项目:pyhiro 作者: wanweiwei07 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def points_to_spline_entity(points, smooth=.0005, count=None):
    from scipy.interpolate import splprep

    if count is None: 
        count = len(points)
    points = np.asanyarray(points)
    closed = np.linalg.norm(points[0] - points[-1]) < tol.merge 

    knots, control, degree =  splprep(points.T, s=smooth)[0]
    control = np.transpose(control)
    index = np.arange(len(control))

    if closed:
        control[0] = control[[0,-1]].mean(axis=0)
        control = control[:-1]
        index[-1] = index[0]

    entity = BSpline(points = index, 
                     knots  = knots,
                     closed = closed)

    return entity, control
util.py 文件源码 项目:pyhiro 作者: wanweiwei07 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def zero_pad(data, count, right=True):
    '''
    Arguments
    --------
    data: (n) length 1D array 
    count: int

    Returns
    --------
    padded: (count) length 1D array if (n < count), otherwise length (n)
    '''
    if len(data) == 0:
        return np.zeros(count)
    elif len(data) < count:
        padded = np.zeros(count)
        if right:
            padded[-len(data):] = data
        else:
            padded[:len(data)] = data
        return padded
    else: 
        return np.asanyarray(data)
points.py 文件源码 项目:pyhiro 作者: wanweiwei07 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def transform_points(points, matrix, translate=True):
    '''
    Returns points, rotated by transformation matrix 
    If points is (n,2), matrix must be (3,3)
    if points is (n,3), matrix must be (4,4)

    Arguments
    ----------
    points: (n, 2|3) set of points
    matrix: (3|4, 3|4) rotation matrix
    translate: boolean, apply translation from matrix or not

    '''
    points = np.asanyarray(points)
    dimension   = points.shape[1]
    column      = np.zeros(len(points)) + int(bool(translate))
    stacked     = np.column_stack((points, column))
    transformed = np.dot(matrix, stacked.T).T[:,0:dimension]
    return transformed
points.py 文件源码 项目:pyhiro 作者: wanweiwei07 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def plot_points(points, show=True):    
    import matplotlib.pyplot as plt

    points = np.asanyarray(points)
    dimension = points.shape[1]    
    if dimension == 3:
        fig = plt.figure()
        ax  = fig.add_subplot(111, projection='3d')
        ax.scatter(*points.T)
    elif dimension == 2:
        plt.scatter(*points.T)
    else:
        raise ValueError('Points must be 2D or 3D, not %dD', dimension)

    if show: 
        plt.show()
ray_mesh.py 文件源码 项目:pyhiro 作者: wanweiwei07 项目源码 文件源码 阅读 15 收藏 0 点赞 0 评论 0
def contains_points(mesh, points):
    '''
    Check if a mesh contains a set of points, using ray tests.

    If the point is on the surface of the mesh, behavior is undefined.

    Arguments
    ---------
    mesh: Trimesh object
    points: (n,3) points in space

    Returns
    ---------
    contains: (n) boolean array, whether point is inside mesh or not
    '''
    points = np.asanyarray(points)
    vector = unitize([0,0,1])
    rays = np.column_stack((points, 
                            np.tile(vector,(len(points),1)))).reshape((-1,2,3))
    hits = mesh.ray.intersects_location(rays)
    hits_count = np.array([len(i) for i in hits])
    contains = np.mod(hits_count, 2) == 1

    return contains
binning.py 文件源码 项目:pysynphot 作者: spacetelescope 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def calculate_bin_widths(edges):
    """
    Calculate the widths of wavelengths bins given their edges.

    Parameters
    ----------
    edges : array_like
        Sequence of bin edges. Must be 1D and have at least two values.

    Returns
    -------
    widths : ndarray
        Array of bin widths. Will be 1D and have one less value than ``edges``.

    """
    edges = np.asanyarray(edges)

    if edges.ndim != 1:
        raise ValueError('edges input array must be 1D.')

    if edges.size < 2:
        raise ValueError('edges input must have at least two values.')

    return edges[1:] - edges[:-1]
kshape.py 文件源码 项目:rca-evaluation 作者: sieve-microservices 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def zscore(a, axis=0, ddof=0):
    a = np.asanyarray(a)
    mns = a.mean(axis=axis)
    sstd = a.std(axis=axis, ddof=ddof)
    if axis and mns.ndim < a.ndim:
        res = (((a - np.expand_dims(mns, axis=axis)) /
                np.expand_dims(sstd,axis=axis)))
    else:
        res = (a - mns) / sstd
    return np.nan_to_num(res)
utils.py 文件源码 项目:spyking-circus 作者: spyking-circus 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def _assert_all_finite(X):
    """Like assert_all_finite, but only for ndarray."""
    X = np.asanyarray(X)
    # First try an O(n) time, O(1) space solution for the common case that
    # everything is finite; fall back to O(n) space np.isfinite to prevent
    # false positives from overflow in sum method.
    if (X.dtype.char in np.typecodes['AllFloat'] and not np.isfinite(X.sum())
            and not np.isfinite(X).all()):
        raise ValueError("Input contains NaN, infinity"
                         " or a value too large for %r." % X.dtype)
colorconv.py 文件源码 项目:FCN_train 作者: 315386775 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def _prepare_colorarray(arr):
    """Check the shape of the array and convert it to
    floating point representation.

    """
    arr = np.asanyarray(arr)

    if arr.ndim not in [3, 4] or arr.shape[-1] != 3:
        msg = ("the input array must be have a shape == (.., ..,[ ..,] 3)), " +
               "got (" + (", ".join(map(str, arr.shape))) + ")")
        raise ValueError(msg)

    return dtype.img_as_float(arr)
stats.py 文件源码 项目:empyrical 作者: quantopian 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def cum_returns_final(returns, starting_value=0):
    """
    Compute total returns from simple returns.

    Parameters
    ----------
    returns : pd.Series or np.ndarray
        Returns of the strategy as a percentage, noncumulative.
         - Time series with decimal returns.
         - Example:
            2015-07-16    -0.012143
            2015-07-17    0.045350
            2015-07-20    0.030957
            2015-07-21    0.004902.
    starting_value : float, optional
       The starting returns.

    Returns
    -------
    float

    """

    if len(returns) == 0:
        return np.nan

    return cum_returns(np.asanyarray(returns),
                       starting_value=starting_value)[-1]
stats.py 文件源码 项目:empyrical 作者: quantopian 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def annual_return(returns, period=DAILY, annualization=None):
    """Determines the mean annual growth rate of returns.

    Parameters
    ----------
    returns : pd.Series or np.ndarray
        Periodic returns of the strategy, noncumulative.
        - See full explanation in :func:`~empyrical.stats.cum_returns`.
    period : str, optional
        Defines the periodicity of the 'returns' data for purposes of
        annualizing. Value ignored if `annualization` parameter is specified.
        Defaults are:
            'monthly':12
            'weekly': 52
            'daily': 252
    annualization : int, optional
        Used to suppress default values available in `period` to convert
        returns into annual returns. Value should be the annual frequency of
        `returns`.

    Returns
    -------
    float
        Annual Return as CAGR (Compounded Annual Growth Rate).

    """

    if len(returns) < 1:
        return np.nan

    ann_factor = annualization_factor(period, annualization)

    num_years = float(len(returns)) / ann_factor
    start_value = 100
    # Pass array to ensure index -1 looks up successfully.
    end_value = cum_returns(np.asanyarray(returns),
                            starting_value=start_value)[-1]
    cum_returns_final = (end_value - start_value) / start_value
    annual_return = (1. + cum_returns_final) ** (1. / num_years) - 1

    return annual_return
stats.py 文件源码 项目:empyrical 作者: quantopian 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def stability_of_timeseries(returns):
    """Determines R-squared of a linear fit to the cumulative
    log returns. Computes an ordinary least squares linear fit,
    and returns R-squared.

    Parameters
    ----------
    returns : pd.Series or np.ndarray
        Daily returns of the strategy, noncumulative.
        - See full explanation in :func:`~empyrical.stats.cum_returns`.

    Returns
    -------
    float
        R-squared.

    """
    if len(returns) < 2:
        return np.nan

    returns = np.asanyarray(returns)
    returns = returns[~np.isnan(returns)]

    cum_log_returns = np.log1p(returns).cumsum()
    rhat = stats.linregress(np.arange(len(cum_log_returns)),
                            cum_log_returns)[2]

    return rhat ** 2


问题


面经


文章

微信
公众号

扫码关注公众号