U
    CvfJ                     @  s  U d dl mZ d dlZd dlmZ d dlmZ d dlmZ d dlm	Z	 d dl
mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZ d dlZd dlmZmZ d d	lm Z  d d
l!m"Z"m#Z#m$Z$ d dl%m&Z& d dl'm(Z( d dl)m*Z*m+Z+m,Z, d dl-m.Z. d dl/m0Z0m1Z1m2Z2 d dl3m4Z4 d dl5m6Z6 erzd dl7m8Z8 W n e9k
rV   dZ8Y nX d dlm:Z: d dl!m;Z; d dl<m=Z=m>Z>m?Z?m@Z@ ed ZAeeAed ee; eBdf ZCeeDeeef ed df ZEed ZFdZGdZHejIjJejKejLjJejMjJejNejOjJejPejQjRdZSdddd ZTd!dd"d#ZUd$dd%d&ZVdd(d)d*d+d,d-ZWd.d/d0d1d2ZXdd3d4ZYd5d6 ZZd7d8 Z[d9d: Z\d;d< Z]d=d> Z^d.dd?d@Z_dAdB Z`dCdD ZadEdF Zbdddddddddddd'ddGdHdIdJdKdKdKdKdKdKdKdLdMd)dNd.dOdPdQZcdddddddddddd'ddGdHdIdJdKdKdKdKdKdKdKdLdMd)dNdRdOdSdTZddd[dJd\d]d^dId_d`d)dadbdcd.dddedfZeejIjJejKejMjJdZfdgegdh< edd'dkd.dbdldmdndodpdqd)drd)dsdtdudvZhedd.d/dldmdndodpdqd)dwd)dxdtdydvZhedd'd'dzd.d{dldmdndodpdqdwdwd)d|dtd}dvZhedd.d{dldmdndodpdqdrdwd)d/dtd~dvZhdd.dbdldmdndodpdqd)d)d)ddtddvZhdddZidddZjdd Zkdd Zledd.ddddnddrdKddd)ddddddZmedddddjdddd.ddddnddwdKddd)ddd|dddZmdd.ddddndd)dKddd)ddddddZmdS )    )annotationsN)partial)glob)BytesIO)Number)TYPE_CHECKINGAnyCallableDictFinalHashableIterableLiteralMappingMutableMappingSequenceTypeUnioncastoverload)backendsconventions)plugins)AbstractDataStoreArrayWriter_normalize_path)_get_scheduler)indexing)"_infer_concat_order_from_positions_nested_combinecombine_by_coords)	DataArray)Dataset
_get_chunk_maybe_chunk)Index)is_remote_uri)Delayed)BufferedIOBase)BackendEntrypoint)CombineAttrsOptionsCompatOptionsJoinOptionsNestedSequence)netcdf4scipyh5netcdf)pydappyniopseudonetcdfcfgribzarrauto)ZNETCDF4ZNETCDF4_CLASSICZNETCDF3_64BITZNETCDF3_CLASSICZ__xarray_dataarray_name__Z__xarray_dataarray_variable__)r.   r/   r1   r0   r2   r3   r4   r5   zLiteral[('netcdf4', 'pydap')])returnc                  C  sX   zdd l } d}W nB tk
rR   zdd l}d}W n tk
rL   tdY nX Y nX |S )Nr   r.   r1   zFnetCDF4 or pydap is required for accessing remote datasets via OPeNDAP)netCDF4ImportErrorr1   
ValueError)r8   enginer1    r<   7/tmp/pip-unpacked-wheel-h316xyqg/xarray/backends/api.py_get_default_engine_remote_uriW   s    r>   zLiteral['scipy']c                  C  s2   zdd l } d}W n tk
r,   tdY nX |S )Nr   r/   z)scipy is required for accessing .gz files)r/   r9   r:   )r/   r;   r<   r<   r=   _get_default_engine_gzj   s    r?   zLiteral[('netcdf4', 'scipy')]c                  C  sX   zdd l } d}W nB tk
rR   zdd l}d}W n tk
rL   tdY nX Y nX |S )Nr   r.   r/   zKcannot read or write netCDF files without netCDF4-python or scipy installed)r8   r9   Zscipy.io.netcdfr:   )r8   r;   r/   r<   r<   r=   _get_default_engine_netcdft   s    r@   FstrboolT_NetcdfEngine)pathallow_remoter7   c                 C  s,   |rt | rt S | dr"t S t S d S )Nz.gz)r&   r>   endswithr?   r@   )rD   rE   r<   r<   r=   _get_default_engine   s
    
rG   r"   None)datasetr7   c                 C  s&   dddd}| j D ]}|| qdS )z8DataArray.name and Dataset keys must be a string or Noner   namec                 S  s<   t | tr | s8td| dn| d k	r8td| dd S )NzInvalid name zc for DataArray or Dataset key: string must be length 1 or greater for serialization to netCDF filesz` for DataArray or Dataset key: must be either a string or None for serialization to netCDF files)
isinstancerA   r:   	TypeErrorrJ   r<   r<   r=   
check_name   s    


z+_validate_dataset_names.<locals>.check_nameN)	variables)rI   rN   kr<   r<   r=   _validate_dataset_names   s    
rQ   c                 C  s   t ttjtjttf}|r$|tjf7 }dd }| j	 D ]\}}|||| q6| j
 D ]$}|j	 D ]\}}|||| qdqVdS )a  `attrs` must have a string key and a value which is either: a number,
    a string, an ndarray, a list/tuple of numbers/strings, or a numpy.bool_.

    Notes
    -----
    A numpy.bool_ is only allowed when using the h5netcdf engine with
    `invalid_netcdf=True`.
    c              
   S  sh   t | tr | s0td| dntd| dt ||sdtd| d|ddd	d
 |D  d S )NzInvalid name for attr zF: string must be length 1 or greater for serialization to netCDF fileszInvalid name for attr: z3 must be a string for serialization to netCDF fileszInvalid value for attr z: zV. For serialization to netCDF files, its value must be of one of the following types: z, c                 S  s   g | ]
}|j qS r<   )__name__).0vtyper<   r<   r=   
<listcomp>   s     z7_validate_attrs.<locals>.check_attr.<locals>.<listcomp>)rL   rA   r:   rM   join)rK   valuevalid_typesr<   r<   r=   
check_attr   s    



$z#_validate_attrs.<locals>.check_attrN)rA   r   npZndarraynumberlisttuplebool_attrsitemsrO   values)rI   invalid_netcdfrX   rY   rP   vvariabler<   r<   r=   _validate_attrs   s    
re   c                 K  s@   t |D ]2}| dkr$||kr$d||< || d kr|| q|S )NF)r\   pop)	decode_cfopen_backend_dataset_parametersdecodersdr<   r<   r=   _resolve_decoders_kwargs   s    rk   c                 C  sP   d }zt | }W n tk
r*   d }Y nX |rLt|sLt jt j| }|S N)osfspathrM   r&   rD   getmtime
expanduser)filename_or_objmtimerD   r<   r<   r=   
_get_mtime   s    
rs   c                 C  sB   | j  D ]2\}}|| jkr
t|j}|r6t|}||_q
d S rl   )rO   r`   Z_indexesr   ZCopyOnWriteArray_dataZMemoryCachedArraydata)rI   cacherK   rd   ru   r<   r<   r=   "_protect_dataset_variables_inplace   s    

rw   c                 C  s   ~ |   dS )z5Finalize this store by explicitly syncing and closingN)close)writestorer<   r<   r=   _finalize_store   s    r{   c                 C  s   | D ]
}|  qd S rl   r<   )closerscloserr<   r<   r=   _multi_file_closer   s    r~   c              
   K  s<   d|krt dt| f|}| W  5 Q R  S Q R X dS )aP  Open, load into memory, and close a Dataset from a file or file-like
    object.

    This is a thin wrapper around :py:meth:`~xarray.open_dataset`. It differs
    from `open_dataset` in that it loads the Dataset into memory, closes the
    file, and returns the Dataset. In contrast, `open_dataset` keeps the file
    handle open and lazy loads its contents. All parameters are passed directly
    to `open_dataset`. See that documentation for further details.

    Returns
    -------
    dataset : Dataset
        The newly created Dataset.

    See Also
    --------
    open_dataset
    rv   #cache has no effect in this contextN)rM   open_datasetload)rq   kwargsdsr<   r<   r=   load_dataset  s    r   c              
   K  s<   d|krt dt| f|}| W  5 Q R  S Q R X dS )a  Open, load into memory, and close a DataArray from a file or file-like
    object containing a single data variable.

    This is a thin wrapper around :py:meth:`~xarray.open_dataarray`. It differs
    from `open_dataarray` in that it loads the Dataset into memory, closes the
    file, and returns the Dataset. In contrast, `open_dataarray` keeps the file
    handle open and lazy loads its contents. All parameters are passed directly
    to `open_dataarray`. See that documentation for further details.

    Returns
    -------
    datarray : DataArray
        The newly created DataArray.

    See Also
    --------
    open_dataarray
    rv   r   N)rM   open_dataarrayr   )rq   r   dar<   r<   r=   load_dataarray  s    r   c              
   K  sv   ddl m} t|}|||||f|}	d|	 }
i }| j D ],\}}t||}t|||||
|	|d||< q>| |S )Nr   )tokenizezopen_dataset-)overwrite_encoded_chunksname_prefixtokeninline_array)Z	dask.baser   rs   rO   r`   r#   r$   _replace)
backend_dsrq   r;   chunksr   r   extra_tokensr   rr   r   r   rO   rK   varZ
var_chunksr<   r<   r=   	_chunk_ds5  s"    	

	r   c           	      K  s   t |ttfs&|dkr&td| dt| | |d kr>| }nt| |||||f|}|| j d|jkrt |t	t
jfrt||jd< |S )N>   Nr6   z<chunks must be an int, dict, 'auto', or None. Instead found .source)rL   intdictr:   rw   r   	set_close_closeencodingrA   rm   PathLiker   )	r   rq   r;   r   rv   r   r   r   r   r<   r<   r=   _dataset_from_backend_datasetS  s*    



r   )r;   r   rv   rg   mask_and_scaledecode_timesdecode_timedelta
use_cftimeconcat_charactersdecode_coordsdrop_variablesr   backend_kwargsz;str | os.PathLike[Any] | BufferedIOBase | AbstractDataStoreT_EngineT_Chunkszbool | Nonez-Literal[('coordinates', 'all')] | bool | Nonezstr | Iterable[str] | Nonezdict[str, Any] | None)rq   r;   r   rv   rg   r   r   r   r   r   r   r   r   r   r7   c             
   K  s   |dkr|dk}|dk	r"| | |dkr4t| }t|}t||j||||	||
d}|dd}|j| fd|i||}t|| |||||fd|i||}|S )a2  Open and decode a dataset from a file or file-like object.

    Parameters
    ----------
    filename_or_obj : str, Path, file-like or DataStore
        Strings and Path objects are interpreted as a path to a netCDF file
        or an OpenDAP URL and opened with python-netCDF4, unless the filename
        ends with .gz, in which case the file is gunzipped and opened with
        scipy.io.netcdf (only netCDF3 supported). Byte-strings or file-like
        objects are opened by scipy.io.netcdf (netCDF3) or h5py (netCDF4/HDF).
    engine : {"netcdf4", "scipy", "pydap", "h5netcdf", "pynio", "cfgrib",         "pseudonetcdf", "zarr", None}, installed backend         or subclass of xarray.backends.BackendEntrypoint, optional
        Engine to use when reading files. If not provided, the default engine
        is chosen based on available dependencies, with a preference for
        "netcdf4". A custom backend class (a subclass of ``BackendEntrypoint``)
        can also be used.
    chunks : int, dict, 'auto' or None, optional
        If chunks is provided, it is used to load the new dataset into dask
        arrays. ``chunks=-1`` loads the dataset with dask using a single
        chunk for all arrays. ``chunks={}`` loads the dataset with dask using
        engine preferred chunks if exposed by the backend, otherwise with
        a single chunk for all arrays. In order to reproduce the default behavior
        of ``xr.open_zarr(...)`` use ``xr.open_dataset(..., engine='zarr', chunks={})``.
        ``chunks='auto'`` will use dask ``auto`` chunking taking into account the
        engine preferred chunks. See dask chunking for more details.
    cache : bool, optional
        If True, cache data loaded from the underlying datastore in memory as
        NumPy arrays when accessed to avoid reading from the underlying data-
        store multiple times. Defaults to True unless you specify the `chunks`
        argument to use dask, in which case it defaults to False. Does not
        change the behavior of coordinates corresponding to dimensions, which
        always load their data from disk into a ``pandas.Index``.
    decode_cf : bool, optional
        Whether to decode these variables, assuming they were saved according
        to CF conventions.
    mask_and_scale : bool, optional
        If True, replace array values equal to `_FillValue` with NA and scale
        values according to the formula `original_values * scale_factor +
        add_offset`, where `_FillValue`, `scale_factor` and `add_offset` are
        taken from variable attributes (if they exist).  If the `_FillValue` or
        `missing_value` attribute contains multiple values a warning will be
        issued and all array values matching one of the multiple values will
        be replaced by NA. mask_and_scale defaults to True except for the
        pseudonetcdf backend. This keyword may not be supported by all the backends.
    decode_times : bool, optional
        If True, decode times encoded in the standard NetCDF datetime format
        into datetime objects. Otherwise, leave them encoded as numbers.
        This keyword may not be supported by all the backends.
    decode_timedelta : bool, optional
        If True, decode variables and coordinates with time units in
        {"days", "hours", "minutes", "seconds", "milliseconds", "microseconds"}
        into timedelta objects. If False, leave them encoded as numbers.
        If None (default), assume the same value of decode_time.
        This keyword may not be supported by all the backends.
    use_cftime: bool, optional
        Only relevant if encoded dates come from a standard calendar
        (e.g. "gregorian", "proleptic_gregorian", "standard", or not
        specified).  If None (default), attempt to decode times to
        ``np.datetime64[ns]`` objects; if this is not possible, decode times to
        ``cftime.datetime`` objects. If True, always decode times to
        ``cftime.datetime`` objects, regardless of whether or not they can be
        represented using ``np.datetime64[ns]`` objects.  If False, always
        decode times to ``np.datetime64[ns]`` objects; if this is not possible
        raise an error. This keyword may not be supported by all the backends.
    concat_characters : bool, optional
        If True, concatenate along the last dimension of character arrays to
        form string arrays. Dimensions will only be concatenated over (and
        removed) if they have no corresponding variable and if they are only
        used as the last dimension of character arrays.
        This keyword may not be supported by all the backends.
    decode_coords : bool or {"coordinates", "all"}, optional
        Controls which variables are set as coordinate variables:

        - "coordinates" or True: Set variables referred to in the
          ``'coordinates'`` attribute of the datasets or individual variables
          as coordinate variables.
        - "all": Set variables referred to in  ``'grid_mapping'``, ``'bounds'`` and
          other attributes as coordinate variables.
    drop_variables: str or iterable of str, optional
        A variable or list of variables to exclude from being parsed from the
        dataset. This may be useful to drop variables with problems or
        inconsistent values.
    inline_array: bool, default: False
        How to include the array in the dask task graph.
        By default(``inline_array=False``) the array is included in a task by
        itself, and each chunk refers to that task by its key. With
        ``inline_array=True``, Dask will instead inline the array directly
        in the values of the task graph. See :py:func:`dask.array.from_array`.
    backend_kwargs: dict
        Additional keyword arguments passed on to the engine open function,
        equivalent to `**kwargs`.
    **kwargs: dict
        Additional keyword arguments passed on to the engine open function.
        For example:

        - 'group': path to the netCDF4 group in the given file to open given as
          a str,supported by "netcdf4", "h5netcdf", "zarr".
        - 'lock': resource lock to use when reading data from disk. Only
          relevant when using dask or another form of parallelism. By default,
          appropriate locks are chosen to safely read and write files with the
          currently active dask scheduler. Supported by "netcdf4", "h5netcdf",
          "scipy", "pynio", "pseudonetcdf", "cfgrib".

        See engine open function for kwargs accepted by each specific engine.

    Returns
    -------
    dataset : Dataset
        The newly created dataset.

    Notes
    -----
    ``open_dataset`` opens the file with read-only access. When you modify
    values of a Dataset, even one linked to files on disk, only the in-memory
    copy you are manipulating in xarray is modified: the original file on disk
    is never touched.

    See Also
    --------
    open_mfdataset
    N)rh   r   r   r   r   r   r   r   r   )	updater   Zguess_engineget_backendrk   Zopen_dataset_parametersrf   r   r   )rq   r;   r   rv   rg   r   r   r   r   r   r   r   r   r   r   backendri   r   r   r   r<   r<   r=   r   y  sT     


	r   r!   c                K  s   t | f||||	|
||||||||d|}t|jdkrDtdn|j \}||j t|jkrz|jt |_	|jt= |j	t
krd|_	|S )a  Open an DataArray from a file or file-like object containing a single
    data variable.

    This is designed to read netCDF files with only one data variable. If
    multiple variables are present then a ValueError is raised.

    Parameters
    ----------
    filename_or_obj : str, Path, file-like or DataStore
        Strings and Path objects are interpreted as a path to a netCDF file
        or an OpenDAP URL and opened with python-netCDF4, unless the filename
        ends with .gz, in which case the file is gunzipped and opened with
        scipy.io.netcdf (only netCDF3 supported). Byte-strings or file-like
        objects are opened by scipy.io.netcdf (netCDF3) or h5py (netCDF4/HDF).
    engine : {"netcdf4", "scipy", "pydap", "h5netcdf", "pynio", "cfgrib",         "pseudonetcdf", "zarr", None}, installed backend         or subclass of xarray.backends.BackendEntrypoint, optional
        Engine to use when reading files. If not provided, the default engine
        is chosen based on available dependencies, with a preference for
        "netcdf4".
    chunks : int, dict, 'auto' or None, optional
        If chunks is provided, it is used to load the new dataset into dask
        arrays. ``chunks=-1`` loads the dataset with dask using a single
        chunk for all arrays. `chunks={}`` loads the dataset with dask using
        engine preferred chunks if exposed by the backend, otherwise with
        a single chunk for all arrays.
        ``chunks='auto'`` will use dask ``auto`` chunking taking into account the
        engine preferred chunks. See dask chunking for more details.
    cache : bool, optional
        If True, cache data loaded from the underlying datastore in memory as
        NumPy arrays when accessed to avoid reading from the underlying data-
        store multiple times. Defaults to True unless you specify the `chunks`
        argument to use dask, in which case it defaults to False. Does not
        change the behavior of coordinates corresponding to dimensions, which
        always load their data from disk into a ``pandas.Index``.
    decode_cf : bool, optional
        Whether to decode these variables, assuming they were saved according
        to CF conventions.
    mask_and_scale : bool, optional
        If True, replace array values equal to `_FillValue` with NA and scale
        values according to the formula `original_values * scale_factor +
        add_offset`, where `_FillValue`, `scale_factor` and `add_offset` are
        taken from variable attributes (if they exist).  If the `_FillValue` or
        `missing_value` attribute contains multiple values a warning will be
        issued and all array values matching one of the multiple values will
        be replaced by NA. mask_and_scale defaults to True except for the
        pseudonetcdf backend. This keyword may not be supported by all the backends.
    decode_times : bool, optional
        If True, decode times encoded in the standard NetCDF datetime format
        into datetime objects. Otherwise, leave them encoded as numbers.
        This keyword may not be supported by all the backends.
    decode_timedelta : bool, optional
        If True, decode variables and coordinates with time units in
        {"days", "hours", "minutes", "seconds", "milliseconds", "microseconds"}
        into timedelta objects. If False, leave them encoded as numbers.
        If None (default), assume the same value of decode_time.
        This keyword may not be supported by all the backends.
    use_cftime: bool, optional
        Only relevant if encoded dates come from a standard calendar
        (e.g. "gregorian", "proleptic_gregorian", "standard", or not
        specified).  If None (default), attempt to decode times to
        ``np.datetime64[ns]`` objects; if this is not possible, decode times to
        ``cftime.datetime`` objects. If True, always decode times to
        ``cftime.datetime`` objects, regardless of whether or not they can be
        represented using ``np.datetime64[ns]`` objects.  If False, always
        decode times to ``np.datetime64[ns]`` objects; if this is not possible
        raise an error. This keyword may not be supported by all the backends.
    concat_characters : bool, optional
        If True, concatenate along the last dimension of character arrays to
        form string arrays. Dimensions will only be concatenated over (and
        removed) if they have no corresponding variable and if they are only
        used as the last dimension of character arrays.
        This keyword may not be supported by all the backends.
    decode_coords : bool or {"coordinates", "all"}, optional
        Controls which variables are set as coordinate variables:

        - "coordinates" or True: Set variables referred to in the
          ``'coordinates'`` attribute of the datasets or individual variables
          as coordinate variables.
        - "all": Set variables referred to in  ``'grid_mapping'``, ``'bounds'`` and
          other attributes as coordinate variables.
    drop_variables: str or iterable of str, optional
        A variable or list of variables to exclude from being parsed from the
        dataset. This may be useful to drop variables with problems or
        inconsistent values.
    inline_array: bool, default: False
        How to include the array in the dask task graph.
        By default(``inline_array=False``) the array is included in a task by
        itself, and each chunk refers to that task by its key. With
        ``inline_array=True``, Dask will instead inline the array directly
        in the values of the task graph. See :py:func:`dask.array.from_array`.
    backend_kwargs: dict
        Additional keyword arguments passed on to the engine open function,
        equivalent to `**kwargs`.
    **kwargs: dict
        Additional keyword arguments passed on to the engine open function.
        For example:

        - 'group': path to the netCDF4 group in the given file to open given as
          a str,supported by "netcdf4", "h5netcdf", "zarr".
        - 'lock': resource lock to use when reading data from disk. Only
          relevant when using dask or another form of parallelism. By default,
          appropriate locks are chosen to safely read and write files with the
          currently active dask scheduler. Supported by "netcdf4", "h5netcdf",
          "scipy", "pynio", "pseudonetcdf", "cfgrib".

        See engine open function for kwargs accepted by each specific engine.

    Notes
    -----
    This is designed to be fully compatible with `DataArray.to_netcdf`. Saving
    using `DataArray.to_netcdf` and then loading with this function will
    produce an identical result.

    All parameters are passed directly to `xarray.open_dataset`. See that
    documentation for further details.

    See also
    --------
    open_dataset
    )rg   r   r   r   r   r;   r   rv   r   r   r   r   r      zGiven file dataset contains more than one data variable. Please read with xarray.open_dataset and then select the variable you want.N)r   len	data_varsr:   ra   r   r   DATAARRAY_NAMEr_   rK   DATAARRAY_VARIABLE)rq   r;   r   rv   rg   r   r   r   r   r   r   r   r   r   r   rI   Z
data_arrayr<   r<   r=   r   2  s@     

r   no_conflictsall	different	by_coordsouteroverridez'str | NestedSequence[str | os.PathLike]zVstr | DataArray | Index | Sequence[str] | Sequence[DataArray] | Sequence[Index] | Noner+   z#Callable[[Dataset], Dataset] | Nonez4Literal[('all', 'minimal', 'different')] | list[str]z Literal[('by_coords', 'nested')]r,   zstr | os.PathLike | Noner*   )pathsr   
concat_dimcompat
preprocessr;   r   combineparallelrV   
attrs_filecombine_attrsr7   c              
     s  t | trt| r|dkrzddlm} W n, tk
rV } ztd|W 5 d}~X Y nX || d|di di d	d
\ }}  | } fdd|D } qt| rt	d|  dqt
tt| } n(t | tjrt| g} ndd | D } | std|dkrRt |ttfs(|dkr.|g}t| }t| t|  }} n|dkrn|dk	rnt	dtf ||p|i d||	rddl}|t|tdk	r|nttfdd| D }fdd|D }dk	r
fdd|D }|	r |||\}}zV|dkrFt|||||||
|d}n.|dkrft|||||
|d}nt	d|W n, t	k
r   |D ]}|  q Y nX |t t!| |dk	rt |tjrt"tt|}|| #| j$|_$|S )as"  Open multiple files as a single dataset.

    If combine='by_coords' then the function ``combine_by_coords`` is used to combine
    the datasets into one before returning the result, and if combine='nested' then
    ``combine_nested`` is used. The filepaths must be structured according to which
    combining function is used, the details of which are given in the documentation for
    ``combine_by_coords`` and ``combine_nested``. By default ``combine='by_coords'``
    will be used. Requires dask to be installed. See documentation for
    details on dask [1]_. Global attributes from the ``attrs_file`` are used
    for the combined dataset.

    Parameters
    ----------
    paths : str or nested sequence of paths
        Either a string glob in the form ``"path/to/my/files/*.nc"`` or an explicit list of
        files to open. Paths can be given as strings or as pathlib Paths. If
        concatenation along more than one dimension is desired, then ``paths`` must be a
        nested list-of-lists (see ``combine_nested`` for details). (A string glob will
        be expanded to a 1-dimensional list.)
    chunks : int, dict, 'auto' or None, optional
        Dictionary with keys given by dimension names and values given by chunk sizes.
        In general, these should divide the dimensions of each dataset. If int, chunk
        each dimension by ``chunks``. By default, chunks will be chosen to load entire
        input files into memory at once. This has a major impact on performance: please
        see the full documentation for more details [2]_.
    concat_dim : str, DataArray, Index or a Sequence of these or None, optional
        Dimensions to concatenate files along.  You only need to provide this argument
        if ``combine='nested'``, and if any of the dimensions along which you want to
        concatenate is not a dimension in the original datasets, e.g., if you want to
        stack a collection of 2D arrays along a third dimension. Set
        ``concat_dim=[..., None, ...]`` explicitly to disable concatenation along a
        particular dimension. Default is None, which for a 1D list of filepaths is
        equivalent to opening the files separately and then merging them with
        ``xarray.merge``.
    combine : {"by_coords", "nested"}, optional
        Whether ``xarray.combine_by_coords`` or ``xarray.combine_nested`` is used to
        combine all the data. Default is to use ``xarray.combine_by_coords``.
    compat : {"identical", "equals", "broadcast_equals",               "no_conflicts", "override"}, default: "no_conflicts"
        String indicating how to compare variables of the same name for
        potential conflicts when merging:

         * "broadcast_equals": all values must be equal when variables are
           broadcast against each other to ensure common dimensions.
         * "equals": all values and dimensions must be the same.
         * "identical": all values, dimensions and attributes must be the
           same.
         * "no_conflicts": only values which are not null in both datasets
           must be equal. The returned dataset then contains the combination
           of all non-null values.
         * "override": skip comparing and pick variable from first dataset

    preprocess : callable, optional
        If provided, call this function on each dataset prior to concatenation.
        You can find the file-name from which each dataset was loaded in
        ``ds.encoding["source"]``.
    engine : {"netcdf4", "scipy", "pydap", "h5netcdf", "pynio", "cfgrib",         "pseudonetcdf", "zarr", None}, installed backend         or subclass of xarray.backends.BackendEntrypoint, optional
        Engine to use when reading files. If not provided, the default engine
        is chosen based on available dependencies, with a preference for
        "netcdf4".
    data_vars : {"minimal", "different", "all"} or list of str, default: "all"
        These data variables will be concatenated together:
          * "minimal": Only data variables in which the dimension already
            appears are included.
          * "different": Data variables which are not equal (ignoring
            attributes) across all datasets are also concatenated (as well as
            all for which dimension already appears). Beware: this option may
            load the data payload of data variables into memory if they are not
            already loaded.
          * "all": All data variables will be concatenated.
          * list of str: The listed data variables will be concatenated, in
            addition to the "minimal" data variables.
    coords : {"minimal", "different", "all"} or list of str, optional
        These coordinate variables will be concatenated together:
         * "minimal": Only coordinates in which the dimension already appears
           are included.
         * "different": Coordinates which are not equal (ignoring attributes)
           across all datasets are also concatenated (as well as all for which
           dimension already appears). Beware: this option may load the data
           payload of coordinate variables into memory if they are not already
           loaded.
         * "all": All coordinate variables will be concatenated, except
           those corresponding to other dimensions.
         * list of str: The listed coordinate variables will be concatenated,
           in addition the "minimal" coordinates.
    parallel : bool, default: False
        If True, the open and preprocess steps of this function will be
        performed in parallel using ``dask.delayed``. Default is False.
    join : {"outer", "inner", "left", "right", "exact", "override"}, default: "outer"
        String indicating how to combine differing indexes
        (excluding concat_dim) in objects

        - "outer": use the union of object indexes
        - "inner": use the intersection of object indexes
        - "left": use indexes from the first object with each dimension
        - "right": use indexes from the last object with each dimension
        - "exact": instead of aligning, raise `ValueError` when indexes to be
          aligned are not equal
        - "override": if indexes are of same size, rewrite indexes to be
          those of the first object with that dimension. Indexes for the same
          dimension must have the same size in all objects.
    attrs_file : str or path-like, optional
        Path of the file used to read global attributes from.
        By default global attributes are read from the first file provided,
        with wildcard matches sorted by filename.
    combine_attrs : {"drop", "identical", "no_conflicts", "drop_conflicts",                      "override"} or callable, default: "override"
        A callable or a string indicating how to combine attrs of the objects being
        merged:

        - "drop": empty attrs on returned Dataset.
        - "identical": all attrs must be the same on every object.
        - "no_conflicts": attrs from all objects are combined, any that have
          the same name must also have the same value.
        - "drop_conflicts": attrs from all objects are combined, any that have
          the same name but different values are dropped.
        - "override": skip comparing and copy attrs from the first dataset to
          the result.

        If a callable, it must expect a sequence of ``attrs`` dicts and a context object
        as its only parameters.
    **kwargs : optional
        Additional arguments passed on to :py:func:`xarray.open_dataset`.

    Returns
    -------
    xarray.Dataset

    Notes
    -----
    ``open_mfdataset`` opens files with read-only access. When you modify values
    of a Dataset, even one linked to files on disk, only the in-memory copy you
    are manipulating in xarray is modified: the original file on disk is never
    touched.

    See Also
    --------
    combine_by_coords
    combine_nested
    open_dataset

    Examples
    --------
    A user might want to pass additional arguments into ``preprocess`` when
    applying some operation to many individual files that are being opened. One route
    to do this is through the use of ``functools.partial``.

    >>> from functools import partial
    >>> def _preprocess(x, lon_bnds, lat_bnds):
    ...     return x.sel(lon=slice(*lon_bnds), lat=slice(*lat_bnds))
    ...
    >>> lon_bnds, lat_bnds = (-110, -105), (40, 45)
    >>> partial_func = partial(_preprocess, lon_bnds=lon_bnds, lat_bnds=lat_bnds)
    >>> ds = xr.open_mfdataset(
    ...     "file_*.nc", concat_dim="time", preprocess=partial_func
    ... )  # doctest: +SKIP

    References
    ----------

    .. [1] https://docs.xarray.dev/en/stable/dask.html
    .. [2] https://docs.xarray.dev/en/stable/dask.html#chunking-and-performance
    r5   r   )get_fs_token_pathszCThe use of remote URLs for opening zarr requires the package fsspecNrbr   storage_optionsF)moder   expandc                   s   g | ]}  |qS r<   
get_mapper)rS   rD   )fsr<   r=   rU     s     z"open_mfdataset.<locals>.<listcomp>zjcannot do wild-card matching for paths that are remote URLs unless engine='zarr' is specified. Got paths: z7. Instead, supply paths as an explicit list of strings.c                 S  s&   g | ]}t |tjrt|n|qS r<   )rL   rm   r   rn   rS   pr<   r<   r=   rU     s     zno files to opennestedr   zWhen combine='by_coords', passing a value for `concat_dim` has no effect. To manually combine along a specific dimension you should instead specify combine='nested' along with a value for `concat_dim`.)r;   r   c                   s   g | ]} |fqS r<   r<   r   )open_open_kwargsr<   r=   rU     s     c                   s   g | ]} |d qS )r   r<   rS   r   )getattr_r<   r=   rU     s     c                   s   g | ]} |qS r<   r<   r   )r   r<   r=   rU     s     )Zconcat_dimsr   r   coordsidsrV   r   )r   r   r   rV   r   z<{} is an invalid option for the keyword argument ``combine``)%rL   rA   r&   Zfsspec.corer   r9   getr   Z_strip_protocolr:   sortedr   rm   r   rn   OSErrorr!   r   r\   keysra   r   daskdelayedr   getattrcomputer   r    formatrx   r   r   r~   r   indexr_   )r   r   r   r   r   r;   r   r   r   r   rV   r   r   r   r   e_Z	tmp_pathsZcombined_ids_pathsr   r   datasetsr|   Zcombinedr   r<   )r   r   r   r   r   r=   open_mfdataset  s     <
 










	
r   zdict[T_NetcdfEngine, Callable]WRITEABLE_STORESwTrb   zLiteral[('w', 'a')]zT_NetcdfTypes | Nonez
str | NonezT_NetcdfEngine | Nonez+Mapping[Hashable, Mapping[str, Any]] | NonezIterable[Hashable] | NonezLiteral[True]z%tuple[ArrayWriter, AbstractDataStore])rI   path_or_filer   r   groupr;   r   unlimited_dimsr   	multifilerb   r7   c	                C  s   d S rl   r<   rI   r   r   r   r   r;   r   r   r   r   rb   r<   r<   r=   	to_netcdf'  s    r   zLiteral[False]bytesc                 C  s   d S rl   r<   r   r<   r<   r=   r   :  s    )r   rb   zstr | os.PathLiker'   c                C  s   d S rl   r<   r   r<   r<   r=   r   L  s    c                 C  s   d S rl   r<   r   r<   r<   r=   r   _  s    z>tuple[ArrayWriter, AbstractDataStore] | bytes | Delayed | Nonec                 C  s  t |tjrt|}|dkr"i }|dkr^|dkr8d}n|dkrPtd|d|stdn(t |tr|dkrxt|}t|}nd}t	|  t
| |
o|dkd zt| }W n" tk
r   td|Y nX |dk	r| }t }td	d
 | j D }|o|dk}|r4|dkr4td| d| d|dk	rB|nt }|rXtddni }|
r|dkrv|
|d< ntd| |||||f|}|dkr| jdd}|dk	rt |tst |ts|g}nt|}t }zbt| ||||d |r|  |	r||fW 2S |j|d}t |trF|  | W S W 5 |	s^|r^|  X |s~ddl}|t||S dS )zThis function creates an appropriate datastore for writing a dataset to
    disk as a netCDF file

    See `Dataset.to_netcdf` for full API docs.

    The ``multifile`` argument is only for the private use of save_mfdataset.
    Nr/   z2invalid engine for creating bytes with to_netcdf: z8. Only the default engine or engine='scipy' is supportedzJto_netcdf() with compute=False is not yet implemented when returning bytesr0   r   z#unrecognized engine for to_netcdf: c                 s  s   | ]}|j d k	V  qd S rl   )r   )rS   rc   r<   r<   r=   	<genexpr>  s     zto_netcdf.<locals>.<genexpr>)ZdistributedmultiprocessingzWriting netCDF files with the z0 backend is not currently supported with dask's z
 schedulerT)	autocloserb   z0unrecognized option 'invalid_netcdf' for engine r   )r   r   r   r   ) rL   rm   r   rn   r:   NotImplementedErrorrA   rG   r   rQ   re   r   KeyErrorupperr   anyrO   ra   r   r   r   r   r   r\   r   rx   dump_to_storesyncgetvaluer   r   r{   )rI   r   r   r   r   r;   r   r   r   r   rb   Z
store_openZ	schedulerZhave_chunksr   targetr   rz   writerwritesr   r<   r<   r=   r   p  s    







    
c                 C  s~   |dkrt  }|dkri }t| \}}t }| D ]\}	}
|
||	 _||	 q6|rf|||\}}|j|||||d dS )z7Store dataset contents to a backends.*DataStore object.N)r   )r   r   Zencode_dataset_coordinatessetr`   r   addrz   )rI   rz   r   encoderr   r   rO   r_   Zcheck_encodingrP   encr<   r<   r=   r     s    
r   c              	     s  dkr$t t|t |k r$td| D ] }t|ts(tdt| q(|dkr`dgt |  }t t | t |t |hdkrtdt fddt| ||D  \}	}
z fd	d|	D }W 5  r|
D ]}|  qX  sd
dl	
fddt||
D S dS )a  Write multiple datasets to disk as netCDF files simultaneously.

    This function is intended for use with datasets consisting of dask.array
    objects, in which case it can write the multiple datasets to disk
    simultaneously using a shared thread pool.

    When not using dask, it is no different than calling ``to_netcdf``
    repeatedly.

    Parameters
    ----------
    datasets : list of Dataset
        List of datasets to save.
    paths : list of str or list of path-like objects
        List of paths to which to save each corresponding dataset.
    mode : {"w", "a"}, optional
        Write ("w") or append ("a") mode. If mode="w", any existing file at
        these locations will be overwritten.
    format : {"NETCDF4", "NETCDF4_CLASSIC", "NETCDF3_64BIT",               "NETCDF3_CLASSIC"}, optional
    **kwargs : additional arguments are passed along to ``to_netcdf``

        File format for the resulting netCDF file:

        * NETCDF4: Data is stored in an HDF5 file, using netCDF4 API
          features.
        * NETCDF4_CLASSIC: Data is stored in an HDF5 file, using only
          netCDF 3 compatible API features.
        * NETCDF3_64BIT: 64-bit offset version of the netCDF 3 file format,
          which fully supports 2+ GB files, but is only compatible with
          clients linked against netCDF version 3.6.0 or later.
        * NETCDF3_CLASSIC: The classic netCDF 3 file format. It does not
          handle 2+ GB files very well.

        All formats are supported by the netCDF4-python library.
        scipy.io.netcdf only supports the last two formats.

        The default format is NETCDF4 if you are saving a file to disk and
        have the netCDF4-python library available. Otherwise, xarray falls
        back to using scipy to write netCDF files and defaults to the
        NETCDF3_64BIT format (scipy does not support netCDF4).
    groups : list of str, optional
        Paths to the netCDF4 group in each corresponding file to which to save
        datasets (only works for format="NETCDF4"). The groups will be created
        if necessary.
    engine : {"netcdf4", "scipy", "h5netcdf"}, optional
        Engine to use when writing netCDF files. If not provided, the
        default engine is chosen based on available dependencies, with a
        preference for "netcdf4" if writing to a file on disk.
        See `Dataset.to_netcdf` for additional information.
    compute : bool
        If true compute immediately, otherwise return a
        ``dask.delayed.Delayed`` object that can be computed later.

    Examples
    --------

    Save a dataset into one netCDF per year of data:

    >>> ds = xr.Dataset(
    ...     {"a": ("time", np.linspace(0, 1, 48))},
    ...     coords={"time": pd.date_range("2010-01-01", freq="M", periods=48)},
    ... )
    >>> ds
    <xarray.Dataset>
    Dimensions:  (time: 48)
    Coordinates:
      * time     (time) datetime64[ns] 2010-01-31 2010-02-28 ... 2013-12-31
    Data variables:
        a        (time) float64 0.0 0.02128 0.04255 0.06383 ... 0.9574 0.9787 1.0
    >>> years, datasets = zip(*ds.groupby("time.year"))
    >>> paths = [f"{y}.nc" for y in years]
    >>> xr.save_mfdataset(datasets, paths)
    r   zCcannot use mode='w' when writing multiple datasets to the same pathzDsave_mfdataset only supports writing Dataset objects, received type Nr   zcmust supply lists of the same length for the datasets, paths and groups arguments to save_mfdatasetc              	     s2   g | ]*\}}}t |||f d dqS )T)r   r   )r   )rS   r   rD   r   )r   r;   r   r   r   r<   r=   rU   m  s   	z"save_mfdataset.<locals>.<listcomp>c                   s   g | ]}|j  d qS )r   )r   )rS   r   r   r<   r=   rU   ~  s     r   c                   s    g | ]\}}  t||qS r<   )r   r{   )rS   r   s)r   r<   r=   rU     s     )r   r   r:   rL   r"   rM   typeziprx   r   r   )r   r   r   r   groupsr;   r   r   objZwritersZstoresrz   r   r<   )r   r   r;   r   r   r   r=   save_mfdataset  s<    T

r   c                   s   t  tstdt    D ]`\}}|| jkrTtdt  dt| j t |tsltd  |j	dkr$td  q$ fdd| j
 D }|rtd	t   d
|dd S )Nz``region`` must be a dict, got z:all keys in ``region`` are not in Dataset dimensions, got z and z;all values in ``region`` must be slice objects, got region=>   r   Nz?step on all slices in ``region`` must be 1 or None, got region=c                   s$   g | ]\}}t  |js|qS r<   )r   intersectiondims)rS   rP   rc   regionr<   r=   rU     s     z$_validate_region.<locals>.<listcomp>zwhen setting `region` explicitly in to_zarr(), all variables in the dataset to write must have at least one dimension in common with the region's dimensions z, but that is not the case for some variables here. To drop these variables from this dataset before exporting to zarr, write: .drop_vars())rL   r   rM   r   r`   r   r:   r\   slicesteprO   r   )r   r   rP   rc   Znon_matching_varsr<   r   r=   _validate_region  s,    




r  c                   s6   |     fdd}|j D ]\}}||| qdS )zpIf variable exists in the store, confirm dtype of the data to append is compatible with
    existing dtype.
    c                   s|   |  ksxt |jt jsxt |jt jsxt |jt jsx|jtkrDn4|j |  jksxtd|  d |  j d|j dd S )NzMismatched dtypes for variable zC between Zarr store on disk and dataset to append. Store has dtype z! but dataset to append has dtype r   )rZ   Z
issubdtypeZdtyper[   Z
datetime64r^   objectr:   )vnamer   Zexisting_varsr<   r=   check_dtype  s    z8_validate_datatypes_for_zarr_append.<locals>.check_dtypeN)Zget_variablesr   r`   )zstorerI   r  r  r   r<   r  r=   #_validate_datatypes_for_zarr_append  s    r
  z.MutableMapping | str | os.PathLike[str] | Nonez)MutableMapping | str | os.PathLike | Nonez%Literal[('w', 'w-', 'a', 'r+', None)]zMapping | NonezHashable | NonezMapping[str, slice] | Nonezdict[str, str] | Nonez
int | Nonezbackends.ZarrStore)rI   rz   chunk_storer   r   r   r   consolidated
append_dimr   safe_chunksr   zarr_versionr7   c                 C  s   d S rl   r<   rI   rz   r  r   synchronizerr   r   r   r  r  r   r  r   r  r<   r<   r=   to_zarr  s    r  )r  r  r   r  r   r  c                C  s   d S rl   r<   r  r<   r<   r=   r    s    zbackends.ZarrStore | Delayedc                   s  | j  D ]}|jdkr
|  q
t|}t|}|dkrD|}|}nNddlm} t|tslt	dt
| ||f|}|dk	r||f|}n|}|dkri }|dkr|	dk	rd}n|
dk	rd}nd}|dkr|	dk	rt	d|d	kr|
dk	rt	d
|dkrt	d|t|  |
dk	rNt| |
 |	dk	rN|	|
krNt	d|	 d|dkrhtt|dd}|dkr|dkrd}|dkr|}d}nd}|p|dk}tjj||||||||	|
|d|d}|d	krzt||  |	dk	r| }|	|krt	d|	d| t|j   D ]$}|| kr t	d|dq |dkrz fdd| j D }|rzt	d| dt }t| |||d |j|d}|rt|| nddl}|t||S |S )zThis function creates an appropriate datastore for writing a dataset to
    a zarr ztore

    See `Dataset.to_zarr` for full API docs.
    r   Nr   z3store must be a string to use storage_options. Got ar+w-z2cannot set append_dim unless mode='a' or mode=None)r  r  z9cannot set region unless mode='a', mode='r+' or mode=None)r   r  r  r  zJThe only supported options for mode are 'w', 'w-', 'a' and 'r+', but mode=zYcannot list the same dimension in both ``append_dim`` and ``region`` with to_zarr(), got z in bothZ_store_version   F   )rz   r   r  r   r  consolidate_on_closer  r  Zwrite_regionr  
stacklevelr  zappend_dim=z0 does not match any existing dataset dimensions z	variable z* already exists, but encoding was providedc                   s   g | ]}| kr|qS r<   r<   )rS   rP   Zexisting_var_namesr<   r=   rU   |  s      zto_zarr.<locals>.<listcomp>z,dataset contains non-pre-existing variables zt, which is not allowed in ``xarray.Dataset.to_zarr()`` with mode='r+'. To allow writing new variables, set mode='a'.)r   r   )rO   ra   sizer   r   Zfsspecr   rL   rA   r:   r   rQ   r  r   r   r   	ZarrStore
open_groupr
  Zget_dimensionsr   Z
zarr_groupZ
array_keysr   r   r   r   r{   r   r   )rI   rz   r  r   r  r   r   r   r  r  r   r  r   r  rc   ZmapperZchunk_mapperr   Zalready_consolidatedr  r	  Zexisting_dimsvar_nameZ	new_namesr   r   r   r<   r  r=   r    s    















)F)F)NNr   NNr   r   r   Fr   Nr   )Nr   NNNNNT)
Nr   NNNNNTFF)r   NNNNN)	r   NNNNNTFF)
Nr   NNNNNTFF)NNNN)r   NNNT)NNNNNNTNNNTNN)NNNNNN)NNNNNNTNNNTNN)n
__future__r   rm   	functoolsr   r   ior   Znumbersr   typingr   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   ZnumpyrZ   Zxarrayr   r   Zxarray.backendsr   Zxarray.backends.commonr   r   r   Zxarray.backends.locksr   Zxarray.corer   Zxarray.core.combiner   r   r    Zxarray.core.dataarrayr!   Zxarray.core.datasetr"   r#   r$   Zxarray.core.indexesr%   Zxarray.core.utilsr&   Zdask.delayedr'   r9   r(   r)   Zxarray.core.typesr*   r+   r,   r-   rC   rA   r   r   r   ZT_NetcdfTypesr   r   ZNetCDF4DataStoreopenZScipyDataStoreZPydapDataStoreZH5NetCDFStoreZNioDataStoreZPseudoNetCDFDataStoreZCfGribDataStorer  r  ZENGINESr>   r?   r@   rG   rQ   re   rk   rs   rw   r{   r~   r   r   r   r   r   r   r   r   __annotations__r   r   r   r  r
  r  r<   r<   r<   r=   <module>   s   D

	
-	
). =. 8            (  ;        *          (      *         (          &z       
     
 $%             ,      
.             