python类nanmax()的实例源码

base.py 文件源码 项目:kite 作者: pyrocko 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def setSymColormap(self):
        cmap = {'ticks':
                [[0., (0, 0, 0, 255)],
                 [1e-3, (106, 0, 31, 255)],
                 [.5, (255, 255, 255, 255)],
                 [1., (8, 54, 104, 255)]],
                'mode': 'rgb'}
        cmap = {'ticks':
                [[0., (0, 0, 0)],
                 [1e-3, (172, 56, 56)],
                 [.5, (255, 255, 255)],
                 [1., (51, 53, 120)]],
                'mode': 'rgb'}
        lvl_min = num.nanmin(self._plot.data)
        lvl_max = num.nanmax(self._plot.data)
        abs_range = max(abs(lvl_min), abs(lvl_max))

        self.gradient.restoreState(cmap)
        self.setLevels(-abs_range, abs_range)
raster.py 文件源码 项目:CHaMP_Metrics 作者: SouthForkResearch 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def setArray(self, incomingArray, copy=False):
        """
        You can use the self.array directly but if you want to copy from one array
        into a raster we suggest you do it this way
        :param incomingArray:
        :return:
        """
        masked = isinstance(self.array, np.ma.MaskedArray)
        if copy:
            if masked:
                self.array = np.ma.copy(incomingArray)
            else:
                self.array = np.ma.masked_invalid(incomingArray, copy=True)
        else:
            if masked:
                self.array = incomingArray
            else:
                self.array = np.ma.masked_invalid(incomingArray)

        self.rows = self.array.shape[0]
        self.cols = self.array.shape[1]
        self.min = np.nanmin(self.array)
        self.max = np.nanmax(self.array)
model.py 文件源码 项目:linearmodels 作者: bashtage 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def _choose_cov(self, cov_type, **cov_config):
        """Return covariance estimator reformat clusters"""
        cov_est = self._cov_estimators[cov_type]
        if cov_type != 'clustered':
            return cov_est, cov_config
        cov_config_upd = {k: v for k, v in cov_config.items()}

        clusters = cov_config.get('clusters', None)
        if clusters is not None:
            clusters = self.reformat_clusters(clusters).copy()
            cluster_max = np.nanmax(clusters.values3d, axis=1)
            delta = cluster_max - np.nanmin(clusters.values3d, axis=1)
            if np.any(delta != 0):
                raise ValueError('clusters must not vary within an entity')

            index = clusters.panel.minor_axis
            reindex = clusters.entities
            clusters = pd.DataFrame(cluster_max.T, index=index, columns=clusters.vars)
            clusters = clusters.loc[reindex].astype(np.int64)
            cov_config_upd['clusters'] = clusters

        return cov_est, cov_config_upd
faam_data.py 文件源码 项目:faampy 作者: ncasuk 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def get_bbox(self):
        """
        Returns boundary box for the coordinates. Useful for setting up
        the map extent for plotting on a map.
        :return tuple:  corner coordinates (llcrnrlat, urcrnrlat, llcrnrlon,
          urcrnrlon)
        """
        x, y, z = zip(self)
        llcrnrlat = np.nanmin(y)
        urcrnrlat = np.nanmax(y)
        llcrnrlon = np.nanmin(x)
        urcrnrlon = np.nanmax(x)
        return (llcrnrlat,
                urcrnrlat,
                llcrnrlon,
                urcrnrlon)
cpc.py 文件源码 项目:faampy 作者: ncasuk 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def plot_counts(ax, data):
    """

    """
    hourloc = mpl.dates.HourLocator()
    xtickformat = mpl.dates.DateFormatter('%H:%M')
    ax.xaxis.set_major_formatter(xtickformat)
    ax.xaxis.set_major_locator(hourloc)

    cnts = data['CPC378_counts'][:]
    ix = np.where(data['WOW_IND'][:].ravel() == 1)[0]
    cnts[ix,:] = np.nan
    ax.plot_date(data['mpl_timestamp'][:].ravel(), cnts.ravel(), '-')
    ax.set_ylim((0, np.nanmax(cnts)))
    ax.set_ylabel('#')
    ax.set_xlabel('Time (utc)')
    ax.text(0.05, 0.98, 'CPC', axes_title_style, transform=ax.transAxes)
    return ax
BlenderRenderer.py 文件源码 项目:snetRenderer 作者: shubhtuls 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def visRenderedViews(self,outDir,nViews=0):
        pt = Imath.PixelType(Imath.PixelType.FLOAT)
        renders = sorted(glob.glob(outDir + '/render_*.png'))
        if (nViews > 0) and (nViews < len(renders)):
            renders = [renders[ix] for ix in range(nViews)]

        for render in renders:
            print render
            rgbIm = scipy.misc.imread(render)
            dMap = loadDepth(render.replace('render_','depth_'))
            plt.figure(figsize=(12,6))
            plt.subplot(121)
            plt.imshow(rgbIm)
            dMap[dMap>=10] = np.nan
            plt.subplot(122)
            plt.imshow(dMap)
            print(np.nanmax(dMap),np.nanmin(dMap))
            plt.show()
zoom.py 文件源码 项目:lotss-catalogue 作者: mhardcastle 项目源码 文件源码 阅读 43 收藏 0 点赞 0 评论 0
def find_bbox(t):
    # given a table t find the bounding box of the ellipses for the regions

    boxes=[]
    for r in t:
        a=r['Maj']/scale
        b=r['Min']/scale
        th=(r['PA']+90)*np.pi/180.0
        dx=np.sqrt((a*np.cos(th))**2.0+(b*np.sin(th))**2.0)
        dy=np.sqrt((a*np.sin(th))**2.0+(b*np.cos(th))**2.0)
        boxes.append([r['RA']-dx/np.cos(r['DEC']*np.pi/180.0),
                      r['RA']+dx/np.cos(r['DEC']*np.pi/180.0),
                      r['DEC']-dy, r['DEC']+dy])

    boxes=np.array(boxes)

    minra=np.nanmin(boxes[:,0])
    maxra=np.nanmax(boxes[:,1])
    mindec=np.nanmin(boxes[:,2])
    maxdec=np.nanmax(boxes[:,3])

    ra=np.mean((minra,maxra))
    dec=np.mean((mindec,maxdec))
    size=1.2*3600.0*np.max((maxdec-mindec,(maxra-minra)*np.cos(dec*np.pi/180.0)))
    return ra,dec,size
RockPhysicss.py 文件源码 项目:GRIPy 作者: giruenf 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def VshGR(GRlog,itmin,itmax):       # Usando o perfil GR


    GRmin = np.nanmin(GRlog)
    GRminInt = GRlog[(GRlog<=(GRmin*(1+itmin/100)))]    # Valores do GRmin 
    GRminm = np.mean(GRminInt)                          # Media dos valores de GRmin

    GRmax = np.nanmax(GRlog)
    GRmaxInt = GRlog[(GRlog>=(GRmax*(1-itmax/100)))]        # Valores de GRmax
    GRmaxm = np.mean(GRmaxInt)                              # Media dos valores de GRmax 

    Vsh = 100*(GRlog-GRminm)/(GRmaxm-GRminm)                # Volume de argila

    for i in range(len(Vsh)):
        if (Vsh[i] > 100):
            Vsh[i] = 100

        elif (Vsh[i] < 0):
            Vsh[i] = 0


    print GRmin, GRminm, GRmax, GRmaxm, np.nanmin(Vsh), np.nanmax(Vsh)

    return Vsh
libscores.py 文件源码 项目:AutoML5 作者: djajetic 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def sanitize_array(array):
    ''' Replace NaN and Inf (there should not be any!)'''
    a=np.ravel(array)
    maxi = np.nanmax((filter(lambda x: x != float('inf'), a))) # Max except NaN and Inf
    mini = np.nanmin((filter(lambda x: x != float('-inf'), a))) # Mini except NaN and Inf
    array[array==float('inf')]=maxi
    array[array==float('-inf')]=mini
    mid = (maxi + mini)/2
    array[np.isnan(array)]=mid
    return array
history_container.py 文件源码 项目:zipline-chinese 作者: zhanghan1990 项目源码 文件源码 阅读 38 收藏 0 点赞 0 评论 0
def frame_to_series(self, field, frame, columns=None):
        """
        Convert a frame with a DatetimeIndex and sid columns into a series with
        a sid index, using the aggregator defined by the given field.
        """
        if isinstance(frame, pd.DataFrame):
            columns = frame.columns
            frame = frame.values

        if not len(frame):
            return pd.Series(
                data=(0 if field == 'volume' else np.nan),
                index=columns,
            ).values

        if field in ['price', 'close']:
            # shortcircuit for full last row
            vals = frame[-1]
            if np.all(~np.isnan(vals)):
                return vals
            return ffill(frame)[-1]
        elif field == 'open':
            return bfill(frame)[0]
        elif field == 'volume':
            return np.nansum(frame, axis=0)
        elif field == 'high':
            return np.nanmax(frame, axis=0)
        elif field == 'low':
            return np.nanmin(frame, axis=0)
        else:
            raise ValueError("Unknown field {}".format(field))
ImageView.py 文件源码 项目:NeoAnalysis 作者: neoanalysis 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def quickMinMax(self, data):
        """
        Estimate the min/max values of *data* by subsampling.
        """
        while data.size > 1e6:
            ax = np.argmax(data.shape)
            sl = [slice(None)] * data.ndim
            sl[ax] = slice(None, None, 2)
            data = data[sl]
        return nanmin(data), nanmax(data)
ScatterPlotItem.py 文件源码 项目:NeoAnalysis 作者: neoanalysis 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def dataBounds(self, ax, frac=1.0, orthoRange=None):
        if frac >= 1.0 and orthoRange is None and self.bounds[ax] is not None:
            return self.bounds[ax]

        #self.prepareGeometryChange()
        if self.data is None or len(self.data) == 0:
            return (None, None)

        if ax == 0:
            d = self.data['x']
            d2 = self.data['y']
        elif ax == 1:
            d = self.data['y']
            d2 = self.data['x']

        if orthoRange is not None:
            mask = (d2 >= orthoRange[0]) * (d2 <= orthoRange[1])
            d = d[mask]
            d2 = d2[mask]

        if frac >= 1.0:
            self.bounds[ax] = (np.nanmin(d) - self._maxSpotWidth*0.7072, np.nanmax(d) + self._maxSpotWidth*0.7072)
            return self.bounds[ax]
        elif frac <= 0.0:
            raise Exception("Value for parameter 'frac' must be > 0. (got %s)" % str(frac))
        else:
            mask = np.isfinite(d)
            d = d[mask]
            return np.percentile(d, [50 * (1 - frac), 50 * (1 + frac)])
ImageView.py 文件源码 项目:NeoAnalysis 作者: neoanalysis 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def quickMinMax(self, data):
        """
        Estimate the min/max values of *data* by subsampling.
        """
        while data.size > 1e6:
            ax = np.argmax(data.shape)
            sl = [slice(None)] * data.ndim
            sl[ax] = slice(None, None, 2)
            data = data[sl]
        return nanmin(data), nanmax(data)
handpose_evaluation.py 文件源码 项目:deep-prior 作者: moberweger 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def getMaxError(self):
        """
        get max error over all joints
        :return: maximum error
        """

        return numpy.nanmax(numpy.sqrt(numpy.square(self.gt - self.joints).sum(axis=2)))
handpose_evaluation.py 文件源码 项目:deep-prior 作者: moberweger 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def getMaxErrorOverSeq(self):
        """
        get max error over all joints for each image of sequence
        :return: maximum error
        """

        return numpy.nanmax(numpy.sqrt(numpy.square(self.gt - self.joints).sum(axis=2)), axis=1)
handpose_evaluation.py 文件源码 项目:deep-prior 作者: moberweger 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def getJointMaxError(self, jointID):
        """
        get maximum error of one joint
        :param jointID: joint ID
        :return: maximum joint error
        """

        return numpy.nanmax(numpy.sqrt(numpy.square(self.gt[:, jointID, :] - self.joints[:, jointID, :]).sum(axis=1)))
handpose_evaluation.py 文件源码 项目:deep-prior 作者: moberweger 项目源码 文件源码 阅读 38 收藏 0 点赞 0 评论 0
def getNumFramesWithinMaxDist(self, dist):
        """
        calculate the number of frames where the maximum difference of a joint is within dist mm
        :param dist: distance between joint and GT
        :return: number of frames
        """
        return (numpy.nanmax(numpy.sqrt(numpy.square(self.gt - self.joints).sum(axis=2)), axis=1) <= dist).sum()
handpose_evaluation.py 文件源码 项目:deep-prior 作者: moberweger 项目源码 文件源码 阅读 38 收藏 0 点赞 0 评论 0
def getMDscore(self, dist):
        """
        calculate the max dist score, ie. MD=\int_0^d{\frac{|F<x|}{|F|}dx = \sum
        :param dist: distance between joint and GT
        :return: score value [0-1]
        """
        vals = [(numpy.nanmax(numpy.sqrt(numpy.square(self.gt - self.joints).sum(axis=2)), axis=1) <= j).sum() / float(self.joints.shape[0]) for j in range(0, dist)]
        return numpy.asarray(vals).sum() / float(dist)
Monitor.py 文件源码 项目:AnomalyDetection 作者: JayZhuCoding 项目源码 文件源码 阅读 42 收藏 0 点赞 0 评论 0
def normalize_data(self, values):
        normalized_values = copy.deepcopy(values)
        data = np.array(values, dtype=float)[:, 0:5]
        data_min = np.nanmin(data, 0)
        data_max = np.nanmax(data, 0)
        print data_min
        print data_max
        for i in range(len(values)):
            for j in range(5):
                normalized_values[i][j] = np.abs(values[i][j] - data_min[j]) / np.abs(data_max[j] - data_min[j])
        return normalized_values, data_min, data_max
util.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def image_as_uint8(im):
    """ Convert the given image to uint8

    If the dtype is already uint8, it is returned as-is. If the image
    is float, and all values are between 0 and 1, the values are
    multiplied by 255. In all other situations, the values are scaled
    such that the minimum value becomes 0 and the maximum value becomes
    255.
    """
    if not isinstance(im, np.ndarray):
        raise ValueError('image must be a numpy array')
    dtype_str = str(im.dtype)
    # Already uint8?
    if dtype_str == 'uint8':
        return im
    # Handle float
    mi, ma = np.nanmin(im), np.nanmax(im)
    if dtype_str.startswith('float'):
        if mi >= 0 and ma <= 1:
            mi, ma = 0, 1
    # Now make float copy before we scale
    im = im.astype('float32')
    # Scale the values between 0 and 255
    if np.isfinite(mi) and np.isfinite(ma):
        if mi:
            im -= mi
        if ma != 255:
            im *= 255.0 / (ma - mi)
        assert np.nanmax(im) < 256
    return im.astype(np.uint8)


# currently not used ... the only use it to easly provide the global meta info


问题


面经


文章

微信
公众号

扫码关注公众号