當前位置: 首頁>>代碼示例>>Python>>正文


Python xarray.full_like方法代碼示例

本文整理匯總了Python中xarray.full_like方法的典型用法代碼示例。如果您正苦於以下問題:Python xarray.full_like方法的具體用法?Python xarray.full_like怎麽用?Python xarray.full_like使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在xarray的用法示例。


在下文中一共展示了xarray.full_like方法的12個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: met_data

# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import full_like [as 別名]
def met_data(self):
        if self._met_data is None:
            self._met_data = io.read_met_data(self.params, self.domain)
            self._met_data['elev'] = self.domain['elev']
            self._met_data['lat'] = self.domain['lat']
            self._met_data['lon'] = self.domain['lon']

            # process constant_vars
            constant_vars = self.params.get('constant_vars', None)
            if constant_vars:
                da_template = self._met_data[list(self._met_data)[0]]
                for var in constant_vars.keys():
                    self._met_data[var] = xr.full_like(da_template,
                                                       float(constant_vars[var]))

            self._validate_force_times(force_times=self._met_data['time'])
        return self._met_data 
開發者ID:UW-Hydro,項目名稱:MetSim,代碼行數:19,代碼來源:metsim.py

示例2: _transform_wrapper

# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import full_like [as 別名]
def _transform_wrapper(X, models, feature_dim=DEFAULT_FEATURE_DIM, **kwargs):

    xtrans = xr.full_like(X, np.nan)

    for index, model in xenumerate(models):
        xdf = X[index].pipe(_da_to_df, feature_dim).drop(models.coords.keys())
        xtrans_df = model.item().transform(xdf, **kwargs)
        xtrans[index] = xtrans_df.squeeze()
    return xtrans 
開發者ID:jhamman,項目名稱:scikit-downscale,代碼行數:11,代碼來源:core.py

示例3: fit

# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import full_like [as 別名]
def fit(self, X, *args, **kwargs):
        """Fit the model

        Fit all the transforms one after the other and transform the
        data, then fit the transformed data using the final estimator.

        Parameters
        ----------
        X : xarray.DataArray or xarray.Dataset
            Training data. Must fulfill input requirements of first step of
            the pipeline. If an xarray.Dataset is passed, it will be converted
            to an array using `to_array()`.
        y : xarray.DataArray, optional
            Training targets. Must fulfill label requirements for all steps
            of the pipeline.
        feature_dim : str, optional
            Name of feature dimension.
        **fit_params : dict of string -> object
            Parameters passed to the ``fit`` method of the this model. If the
            model is a sklearn Pipeline, parameters can be passed to each
            step, where each parameter name is prefixed such that parameter
            ``p`` for step ``s`` has key ``s__p``.
        """
        kws = {'along_dim': self._dim, 'feature_dim': DEFAULT_FEATURE_DIM}
        kws.update(kwargs)

        assert len(args) <= 1
        args = list(args)
        args.append(self._model)

        X = self._to_feature_x(X, feature_dim=kws['feature_dim'])

        if X.chunks:
            reduce_dims = [self._dim, kws['feature_dim']]
            mask = _make_mask(X, reduce_dims)
            template = xr.full_like(mask, None, dtype=np.object)
            self._models = xr.map_blocks(_fit_wrapper, X, args=args, kwargs=kws, template=template)
        else:
            self._models = _fit_wrapper(X, *args, **kws) 
開發者ID:jhamman,項目名稱:scikit-downscale,代碼行數:41,代碼來源:core.py

示例4: test_weights

# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import full_like [as 別名]
def test_weights(ones, ndims):
    dims = ones.dims
    if ones.ndim < ndims:
        pytest.skip("Don't need to test when number of dimension combinations "
                    "exceeds the number of array dimensions")

    bins = np.array([0, 0.9, 1.1, 2])
    bins_c = 0.5 * (bins[1:] + bins[:-1])

    weight_value = 0.5

    def _check_result(h, d):
        other_dims = [dim for dim in ones.dims if dim not in d]
        if len(other_dims) > 0:
            assert set(other_dims) <= set(h.dims)
        # check that all values are in the central bin
        h_sum = h.sum(other_dims)
        h_sum_expected = xr.DataArray([0, weight_value * ones.size, 0],
                                      dims=['ones_bin'],
                                      coords={'ones_bin': ('ones_bin', bins_c)},
                                      name='histogram_ones')
        xr.testing.assert_identical(h_sum, h_sum_expected)

    # get every possible combination of sub-dimensions
    for n_combinations in range(ones.ndim):
        for weight_dims in combinations(dims, n_combinations):
            i_selector = {dim: 0 for dim in weight_dims}
            weights = xr.full_like(ones.isel(**i_selector), weight_value)
            for nc in range(ndims):
                for d in combinations(dims, nc+1):
                    h = histogram(ones, weights=weights, bins=[bins], dim=d)
                    _check_result(h, d)


# test for issue #5 
開發者ID:xgcm,項目名稱:xhistogram,代碼行數:37,代碼來源:test_xarray.py

示例5: partitions

# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import full_like [as 別名]
def partitions(self,
                   partitions: Union[Partition, Sequence[Partition]]):
        """
        Returns a new data set containing only the instances in the specified partitions
        
        Parameters
        ----------
        partitions: Partition or list of Partition
            The partitions to include in the new data set
            
        Returns
        -------
        DataSet
            A new data set containing only the instances in the specified partitions
            
        Raises
        ------
        ValueError
            If there are instances with missing partition information
        """
        if not self.has_partition_info:
            raise ValueError("data set does not have partition info")

        if isinstance(partitions, Partition):
            partitions = [partitions]

        # noinspection PyTypeChecker
        conds = [self._data[_DataVar.PARTITION] == x.value for x in partitions]
        or_cond = xr.full_like(conds[0], fill_value=False, dtype=np.bool)

        for cond in conds:
            # noinspection PyUnresolvedReferences
            or_cond = xr.ufuncs.logical_or(or_cond, cond)

        new_data = self._data.where(or_cond, drop=True)

        return DataSet(data=new_data,
                       mutable=self._mutable) 
開發者ID:auDeep,項目名稱:auDeep,代碼行數:40,代碼來源:data_set.py

示例6: first_run_after_date

# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import full_like [as 別名]
def first_run_after_date(
    da: xr.DataArray,
    window: int,
    date: str = "07-01",
    dim: str = "time",
    coord: Optional[Union[bool, str]] = "dayofyear",
):
    """Return the index of the first item of the first run after a given date.

    Parameters
    ----------
    da : xr.DataArray
      Input N-dimensional DataArray (boolean)
    window : int
      Minimum duration of consecutive run to accumulate values.
    date : str
      The date after which to look for the run.
    dim : str
      Dimension along which to calculate consecutive run (default: 'time').
    coord : Optional[Union[bool, str]]
      If not False, the function returns values along `dim` instead of indexes.
      If `dim` has a datetime dtype, `coord` can also be a str of the name of the
      DateTimeAccessor object to use (ex: 'dayofyear').

    Returns
    -------
    out : xr.DataArray
      Index (or coordinate if `coord` is not False) of first item in the first valid run. Returns np.nan if there are no valid run.
    """
    after_date = datetime.strptime(date, "%m-%d").timetuple().tm_yday

    mid_idx = np.where(da.time.dt.dayofyear == after_date)[0]
    if mid_idx.size == 0:  # The date is not within the group. Happens at boundaries.
        return xr.full_like(da.isel(time=0), np.nan, float).drop_vars("time")

    return first_run(
        da.where(da.time >= da.time[mid_idx][0]), window=window, dim=dim, coord=coord,
    ) 
開發者ID:Ouranosinc,項目名稱:xclim,代碼行數:40,代碼來源:run_length.py

示例7: last_run_before_date

# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import full_like [as 別名]
def last_run_before_date(
    da: xr.DataArray,
    window: int,
    date: str = "07-01",
    dim: str = "time",
    coord: Optional[Union[bool, str]] = "dayofyear",
):
    """Return the index of the last item of the last run before a given date.

    Parameters
    ----------
    da : xr.DataArray
      Input N-dimensional DataArray (boolean)
    window : int
      Minimum duration of consecutive run to accumulate values.
    date : str
      The date before which to look for the last event.
    dim : str
      Dimension along which to calculate consecutive run (default: 'time').
    coord : Optional[Union[bool, str]]
      If not False, the function returns values along `dim` instead of indexes.
      If `dim` has a datetime dtype, `coord` can also be a str of the name of the
      DateTimeAccessor object to use (ex: 'dayofyear').

    Returns
    -------
    out : xr.DataArray
      Index (or coordinate if `coord` is not False) of last item in last valid run. Returns np.nan if there are no valid run.
    """
    before_date = datetime.strptime(date, "%m-%d").timetuple().tm_yday

    mid_idx = np.where(da.time.dt.dayofyear == before_date)[0]
    if mid_idx.size == 0:  # The date is not within the group. Happens at boundaries.
        return xr.full_like(da.isel(time=0), np.nan, float).drop_vars("time")

    run = da.where(da.time <= da.time[mid_idx][0])
    return last_run(run, window=window, dim=dim, coord=coord) 
開發者ID:Ouranosinc,項目名稱:xclim,代碼行數:39,代碼來源:run_length.py

示例8: resample_doy

# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import full_like [as 別名]
def resample_doy(doy: xr.DataArray, arr: xr.DataArray) -> xr.DataArray:
    """Create a temporal DataArray where each day takes the value defined by the day-of-year.

    Parameters
    ----------
    doy : xr.DataArray
      Array with `dayofyear` coordinate.
    arr : xr.DataArray
      Array with `time` coordinate.

    Returns
    -------
    xr.DataArray
      An array with the same `time` dimension as `arr` whose values are filled according to the day-of-year value in
      `doy`.
    """
    if "dayofyear" not in doy.coords:
        raise AttributeError("Source should have `dayofyear` coordinates.")

    # Adjust calendar
    adoy = adjust_doy_calendar(doy, arr)

    # Create array with arr shape and coords
    out = xr.full_like(arr, np.nan)

    # Fill with values from `doy`
    d = out.time.dt.dayofyear.values
    out.data = adoy.sel(dayofyear=d)

    return out 
開發者ID:Ouranosinc,項目名稱:xclim,代碼行數:32,代碼來源:calendar.py

示例9: _load_dataset

# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import full_like [as 別名]
def _load_dataset(dsid, ds_info, file_handlers, dim='y', pad_data=True):
        """Load only a piece of the dataset."""
        if not pad_data:
            return FileYAMLReader._load_dataset(dsid, ds_info,
                                                file_handlers)

        counter, expected_segments, slice_list, failure, projectable = \
            _find_missing_segments(file_handlers, ds_info, dsid)

        if projectable is None or failure:
            raise KeyError(
                "Could not load {} from any provided files".format(dsid))

        empty_segment = xr.full_like(projectable, np.nan)
        for i, sli in enumerate(slice_list):
            if sli is None:
                slice_list[i] = empty_segment

        while expected_segments > counter:
            slice_list.append(empty_segment)
            counter += 1

        if dim not in slice_list[0].dims:
            return slice_list[0]
        res = xr.concat(slice_list, dim=dim)

        combined_info = file_handlers[0].combine_info(
            [p.attrs for p in slice_list])

        res.attrs = combined_info
        return res 
開發者ID:pytroll,項目名稱:satpy,代碼行數:33,代碼來源:yaml_reader.py

示例10: _call_bases

# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import full_like [as 別名]
def _call_bases(
        self, image: xr.DataArray, intensity_threshold: float,
        quality_threshold: float
    ) -> xr.DataArray:
        """
        Determines the nucleotide present in each pixel of each
        (round, channel). The pixel values in the resulting image are the base quality
        score. The base quality score is calculated as the intensity of the pixel
        divided by the L2 norm of the all channels for that pixel. The base
        call score as a range of (0, 1) with a value of 0  and 1 being no call and a
        perfect call, respectively.

        Parameters
        ----------
        image : xr.DataArray
            Image for base calling.
            Should have the following dims: Axes.CH, Axes.X, Axes.Y
        intensity_threshold : float
            Minimum intensity a pixel must have to be called a base.
            Set to zero for no thresholding.
        quality_threshold : float
            Minimum intensity a pixel must have to be called a base.
            Set to zero for no thresholding.

        """
        # Get the maximum value for each round/z
        max_chan = image.argmax(dim=Axes.CH.value)
        max_values = image.max(dim=Axes.CH.value)

        # Get the norms for each pixel
        norms = self._vector_norm(x=image, dim=Axes.CH)

        # Calculate the base qualities
        base_qualities = max_values / norms

        # Filter the base call qualities
        base_qualities_filtered = xr.where(
            base_qualities < quality_threshold, 0, base_qualities
        )

        # Threshold the intensity values
        base_qualities_filtered = xr.where(
            max_values < intensity_threshold, 0, base_qualities_filtered
        )

        # Put the base calls in place
        base_calls = xr.full_like(other=image, fill_value=0)
        base_calls[max_chan] = base_qualities_filtered

        return base_calls 
開發者ID:spacetx,項目名稱:starfish,代碼行數:52,代碼來源:call_bases.py

示例11: run_length_with_date

# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import full_like [as 別名]
def run_length_with_date(
    da: xr.DataArray, window: int, date: str = "07-01", dim: str = "time",
):
    """Return the length of the longest consecutive run of True values found
    to be semi-continuous before and after a given date.

    Parameters
    ----------
    da : xr.DataArray
      Input N-dimensional DataArray (boolean)
    window : int
      Minimum duration of consecutive run to accumulate values.
    date:
      The date that a run must include to be considered valid.
    dim : str
      Dimension along which to calculate consecutive run (default: 'time').

    Returns
    -------
    out : xr.DataArray
      Length of longest run of True values along a given dimension inclusive of a given date.

    Notes
    -----
    The run can include holes of False or NaN values, so long as they do not exceed the window size.
    """
    include_date = datetime.strptime(date, "%m-%d").timetuple().tm_yday

    mid_index = np.where(da.time.dt.dayofyear == include_date)[0]
    if mid_index.size == 0:  # The date is not within the group. Happens at boundaries.
        return xr.full_like(da.isel(time=0), np.nan, float).drop_vars("time")

    end = first_run(
        (~da).where(da.time >= da.time[mid_index][0]), window=window, dim=dim,
    )
    beg = first_run(da, window=window, dim=dim)
    sl = end - beg
    sl = xr.where(beg.isnull() & end.notnull(), 0, sl)  # If series is never triggered
    sl = xr.where(
        beg.notnull() & end.isnull(), da.time.size - beg, sl
    )  # If series is not ended by end of resample time frequency
    return sl.where(sl >= 0) 
開發者ID:Ouranosinc,項目名稱:xclim,代碼行數:44,代碼來源:run_length.py

示例12: run_end_after_date

# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import full_like [as 別名]
def run_end_after_date(
    da: xr.DataArray,
    window: int,
    date: str = "07-01",
    dim: str = "time",
    coord: Optional[Union[bool, str]] = "dayofyear",
):
    """Return the index of the first item after the end of a run after a given date. The run must begin before the date.

    Parameters
    ----------
    da : xr.DataArray
      Input N-dimensional DataArray (boolean)
    window : int
      Minimum duration of consecutive run to accumulate values.
    date : str
      The date after which to look for the end of a run.
    dim : str
      Dimension along which to calculate consecutive run (default: 'time').
    coord : Optional[Union[bool, str]]
      If not False, the function returns values along `dim` instead of indexes.
      If `dim` has a datetime dtype, `coord` can also be a str of the name of the
      DateTimeAccessor object to use (ex: 'dayofyear').

    Returns
    -------
    out : xr.DataArray
      Index (or coordinate if `coord` is not False) of last item in last valid run. Returns np.nan if there are no valid run.
    """
    after_date = datetime.strptime(date, "%m-%d").timetuple().tm_yday

    mid_idx = np.where(da.time.dt.dayofyear == after_date)[0]
    if mid_idx.size == 0:  # The date is not within the group. Happens at boundaries.
        return xr.full_like(da.isel(time=0), np.nan, float).drop_vars("time")

    end = first_run(
        (~da).where(da.time >= da.time[mid_idx][0]),
        window=window,
        dim=dim,
        coord=coord,
    )
    beg = first_run(da.where(da.time < da.time[mid_idx][0]), window=window, dim=dim)
    end = xr.where(
        end.isnull() & beg.notnull(), da.time.isel(time=-1).dt.dayofyear, end
    )
    return end.where(beg.notnull()) 
開發者ID:Ouranosinc,項目名稱:xclim,代碼行數:48,代碼來源:run_length.py


注:本文中的xarray.full_like方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。