-
Setup Information
ContextBonjour chers experts, j'ai un tableau de booléen constituant des séquences et j'aimerais extraire la date de début et de fin de chaque séquence selon une fenêtre et une fréquence comme le |
Beta Was this translation helpful? Give feedback.
Replies: 7 comments 5 replies
-
Vous êtes chanceux, la fonction existe! Elle est récente par contre et n'a pas été utilisée très souvent chez nous, donc elle est encore un peu mal documentée : https://xclim.readthedocs.io/en/stable/indices.html#xclim.indices.run_length.find_events Si vos données sont grosses et que vous utilisez Vous m'en direz des nouvelles! |
Beta Was this translation helpful? Give feedback.
-
*Bonsoir,*
Merci pour votre réponse.
En réalité, je travaille sur les *dry spells* (périodes sèches) et je
souhaite réaliser une analyse en composites avec des variables comme le
vent, le géopotentiel, etc.
Pour cela, j’aurais besoin d’extraire les dates de *début* et/ou de *fin*
des périodes sèches, afin de les faire correspondre aux champs de vent et
de géopotentiel.
Cependant, avec *xclim*, je parviens uniquement à obtenir les *fréquences*
des *dry spells* de 2, 3, 4 jours, etc., mais pas les *dates précises*.
Auriez-vous un *script* ou une *alternative* pour extraire ces dates ?
```python3
#This function computes the day of year in which the cdd of specified
duration started
def dates_begin_end_consecutive_dry_days(
pr: xr.DataArray, thresh: str = "1 mm/day") -> xr.DataArray:
t = convert_units_to(thresh, pr, "hydro")
group = (pr < t)
out = run_bounds(group, dim="time")
return out
```
j'utilise ce code pour le calcul des frequences
|
Beta Was this translation helpful? Give feedback.
-
Je m'excuse du dérangement, mais ça fait un bon moment que j'essaye de
faire cette extraction des dates, mais j'arrive pas j'aimerais juste si
possible un exemple où je pourrais extraire toutes les dates de début
des dry de durée 7 jours comme ça je pourrai m'en espirer pour en
faire d'autres
```python
eve = xc.indices.run_length.find_events(dry, window=1,
freq='YS').dropna('event')
```
l'application de `find_events` me renvois l'erreur ci-dessous :
```
Traceback (most recent call last)Cell
In[78], line 4 1 # Liste d'événements définis comme des séquences
sèches d'au moins 1 jour. 2 # On fait une liste différente pour
chaque année 3 # La fonction renvoie toujours une dimension
"event" qui a la taille maximale possible (genre si on avait que des
séquences de 1 jour), on fait un "dropna" pour enlever les entrées
superflues.----> 4 eve = xc.indices.run_length.find_events(dry,
window=1, freq='YS').dropna('event')
File ~/climenv/lib/python3.12/site-packages/xclim/indices/run_length.py:1904
<http://localhost:8888/lab/tree/Bureau/climenv/lib/python3.12/site-packages/xclim/indices/run_length.py#line=1903>,
in find_events(condition, window, condition_stop, window_stop, data,
freq) 1902 if data is not None: 1903 ds =
ds.assign(data=data)-> 1904 return ds.resample(time=freq).map( 1905
lambda grp: _find_events(grp.da_start, grp.da_stop, grp.get("data",
None), window, window_stop) 1906 )
File ~/climenv/lib/python3.12/site-packages/xarray/core/resample.py:438
<http://localhost:8888/lab/tree/Bureau/climenv/lib/python3.12/site-packages/xarray/core/resample.py#line=437>,
in DatasetResample.map(self, func, args, shortcut, **kwargs) 436 #
ignore shortcut if set (for now) 437 applied = (func(ds, *args,
**kwargs) for ds in self._iter_grouped())--> 438 combined =
self._combine(applied) 440 # If the aggregation function didn't
drop the original resampling 441 # dimension, then we need to do so
before we can rename the proxy 442 # dimension we used. 443 if
self._dim in combined.coords:
File ~/climenv/lib/python3.12/site-packages/xarray/core/groupby.py:1769
<http://localhost:8888/lab/tree/Bureau/climenv/lib/python3.12/site-packages/xarray/core/groupby.py#line=1768>,
in DatasetGroupByBase._combine(self, applied) 1767 def
_combine(self, applied): 1768 """Recombine the applied objects
like the original."""-> 1769 applied_example, applied =
peek_at(applied) 1770 dim, positions =
self._infer_concat_args(applied_example) 1771 combined =
concat(applied, dim)
File ~/climenv/lib/python3.12/site-packages/xarray/core/utils.py:241
<http://localhost:8888/lab/tree/Bureau/climenv/lib/python3.12/site-packages/xarray/core/utils.py#line=240>,
in peek_at(iterable) 237 """Returns the first value from iterable,
as well as a new iterator with 238 the same content as the original
iterable 239 """ 240 gen = iter(iterable)--> 241 peek =
next(gen) 242 return peek, itertools.chain([peek], gen)
File ~/climenv/lib/python3.12/site-packages/xarray/core/resample.py:437
<http://localhost:8888/lab/tree/Bureau/climenv/lib/python3.12/site-packages/xarray/core/resample.py#line=436>,
in <genexpr>(.0) 407 """Apply a function over each Dataset in the
groups generated for 408 resampling and concatenate them together
into a new Dataset. 409 (...) 434 The result of
splitting, applying and combining this dataset. 435 """ 436 #
ignore shortcut if set (for now)--> 437 applied = (func(ds, *args,
**kwargs) for ds in self._iter_grouped()) 438 combined =
self._combine(applied) 440 # If the aggregation function didn't
drop the original resampling 441 # dimension, then we need to do so
before we can rename the proxy 442 # dimension we used.
File ~/climenv/lib/python3.12/site-packages/xclim/indices/run_length.py:1905
<http://localhost:8888/lab/tree/Bureau/climenv/lib/python3.12/site-packages/xclim/indices/run_length.py#line=1904>,
in find_events.<locals>.<lambda>(grp) 1902 if data is not None:
1903 ds = ds.assign(data=data) 1904 return
ds.resample(time=freq).map(-> 1905 lambda grp:
_find_events(grp.da_start, grp.da_stop, grp.get("data", None), window,
window_stop) 1906 )
File ~/climenv/lib/python3.12/site-packages/xclim/indices/run_length.py:1809
<http://localhost:8888/lab/tree/Bureau/climenv/lib/python3.12/site-packages/xclim/indices/run_length.py#line=1808>,
in _find_events(da_start, da_stop, data, window_start, window_stop)
1807 # Dask inputs need to be told their length before computing
anything. 1808 max_event_number = int(np.ceil(da_start.time.size /
<http://localhost:8888/> (window_start + window_stop)))-> 1809 ds =
xr.apply_ufunc( 1810 _filter_events, 1811 ds, 1812
ds.event_length, 1813 input_core_dims=[["time"], ["time"]],
1814 output_core_dims=[["event"]], 1815
kwargs=dict(max_event_number=max_event_number), 1816
dask_gufunc_kwargs=dict(output_sizes={"event": max_event_number}),
1817 dask="parallelized", 1818 vectorize=True, 1819 )
1821 # convert back start to a time 1822 if time_min.dtype == "O":
1823 # Can't add a numpy array of timedeltas to an array of cftime
(because they have non-compatible dtypes) 1824 # Also, we can't
add cftime to NaTType. So we fill with negative timedeltas and mask
them after the addition
File ~/climenv/lib/python3.12/site-packages/xarray/computation/apply_ufunc.py:1255
<http://localhost:8888/lab/tree/Bureau/climenv/lib/python3.12/site-packages/xarray/computation/apply_ufunc.py#line=1254>,
in apply_ufunc(func, input_core_dims, output_core_dims, exclude_dims,
vectorize, join, dataset_join, dataset_fill_value, keep_attrs, kwargs,
dask, output_dtypes, output_sizes, meta, dask_gufunc_kwargs,
on_missing_core_dim, *args) 1253 # feed datasets
apply_variable_ufunc through apply_dataset_vfunc 1254 elif
any(is_dict_like(a) for a in args):-> 1255 return
apply_dataset_vfunc( 1256 variables_vfunc, 1257
*args, 1258 signature=signature, 1259 join=join,
1260 exclude_dims=exclude_dims, 1261
dataset_join=dataset_join, 1262
fill_value=dataset_fill_value, 1263 keep_attrs=keep_attrs,
1264 on_missing_core_dim=on_missing_core_dim, 1265 )
1266 # feed DataArray apply_variable_ufunc through
apply_dataarray_vfunc 1267 elif any(isinstance(a, DataArray) for a
in args):
File ~/climenv/lib/python3.12/site-packages/xarray/computation/apply_ufunc.py:526
<http://localhost:8888/lab/tree/Bureau/climenv/lib/python3.12/site-packages/xarray/computation/apply_ufunc.py#line=525>,
in apply_dataset_vfunc(func, signature, join, dataset_join,
fill_value, exclude_dims, keep_attrs, on_missing_core_dim, *args)
521 list_of_coords, list_of_indexes = build_output_coords_and_indexes(
522 args, signature, exclude_dims, combine_attrs=keep_attrs
523 ) 524 args = tuple(getattr(arg, "data_vars", arg) for arg in
args)--> 526 result_vars = apply_dict_of_variables_vfunc( 527
func, 528 *args, 529 signature=signature, 530
join=dataset_join, 531 fill_value=fill_value, 532
on_missing_core_dim=on_missing_core_dim, 533 ) 535 out: Dataset
| tuple[Dataset, ...] 536 if signature.num_outputs > 1:
File ~/climenv/lib/python3.12/site-packages/xarray/computation/apply_ufunc.py:450
<http://localhost:8888/lab/tree/Bureau/climenv/lib/python3.12/site-packages/xarray/computation/apply_ufunc.py#line=449>,
in apply_dict_of_variables_vfunc(func, signature, join, fill_value,
on_missing_core_dim, *args) 448 core_dim_present =
_check_core_dims(signature, variable_args, name) 449 if
core_dim_present is True:--> 450 result_vars[name] =
func(*variable_args) 451 else: 452 if on_missing_core_dim ==
"raise":
File ~/climenv/lib/python3.12/site-packages/xarray/computation/apply_ufunc.py:767
<http://localhost:8888/lab/tree/Bureau/climenv/lib/python3.12/site-packages/xarray/computation/apply_ufunc.py#line=766>,
in apply_variable_ufunc(func, signature, exclude_dims, dask,
output_dtypes, vectorize, keep_attrs, dask_gufunc_kwargs, *args)
765 for axis, dim in enumerate(core_dims,
start=-len(core_dims)): 766 if
len(data.chunks[axis]) != 1:--> 767 raise
ValueError( 768 f"dimension {dim} on {n}th
function argument to " 769 "apply_ufunc
with dask='parallelized' consists of " 770
"multiple chunks, but is also a core dimension. To " 771
"fix, either rechunk into a single array chunk along "
772 f"this dimension, i.e.,
``.chunk(dict({dim}=-1))``, or " 773 "pass
``allow_rechunk=True`` in ``dask_gufunc_kwargs`` " 774
"but beware that this may significantly increase memory
usage." 775 ) 776
dask_gufunc_kwargs["allow_rechunk"] = True 778 output_sizes =
dask_gufunc_kwargs.pop("output_sizes", {})
ValueError: dimension time on 0th function argument to apply_ufunc
with dask='parallelized' consists of multiple chunks, but is also a
core dimension. To fix, either rechunk into a single array chunk along
this dimension, i.e., ``.chunk(dict(time=-1))``, or pass
``allow_rechunk=True`` in ``dask_gufunc_kwargs`` but beware that this
may significantly increase memory usage.
```
|
Beta Was this translation helpful? Give feedback.
-
Oui effectivement, j'ai copié collé ok donc d'après ma compréhension si les
événements commence dès qu'on rencontre une séquence ou il n'y pas 7 True
la fonction va s'arrêter, serait-il possible qu'on calcule pour toutes
pauses et extraire uniquement les dates concernant une durée de 7 jours ?
|
Beta Was this translation helpful? Give feedback.
-
Merci beaucoup ça semble marcher
eve.event_start
xarray.DataArray
'event_start'
- time: 39
- latitude: 72
- longitude: 140
- event: 46
-
ArrayChunk
Bytes 137.97 MiB 1.88 MiB
Shape (39, 72, 140, 46) (1, 67, 80, 46)
Dask graph 234 chunks in 2399 graph layers
Data type datetime64[ns] numpy.ndarray
|
Beta Was this translation helpful? Give feedback.
-
Bonsoir,
J'ai réussi à extraire les dates de début de mes événements de dry spells
de 7 jours. Existe-t-il, dans la bibliothèque xclim, des fonctions
permettant de réaliser une analyse composite ?
Par exemple, j'aimerais extraire les données de ±5 jours autour de chaque
date de début d'événement (event_start), afin d'analyser les anomalies du
vent, ainsi que celles d'autres variables climatiques.
Le mar. 13 mai 2025, 15:42, BARA NDIAYE ***@***.***> a écrit :
… Merci beaucoup ça semble marcher
eve.event_start
xarray.DataArray
'event_start'
- time: 39
- latitude: 72
- longitude: 140
- event: 46
-
ArrayChunk
Bytes 137.97 MiB 1.88 MiB
Shape (39, 72, 140, 46) (1, 67, 80, 46)
Dask graph 234 chunks in 2399 graph layers
Data type datetime64[ns] numpy.ndarray
Le mar. 13 mai 2025 à 12:51, Pascal Bourgault ***@***.***>
a écrit :
> Votre compréhension est malheureusement erronée, find_events va trouver
> toutes les séquences de 7 True. Je vous invite à essayer et explorer la
> fonction et sa documentation et si vous avez des bogues spécifiques avec
> xclim, nous serons là pour continuer à vous aider.
>
> —
> Reply to this email directly, view it on GitHub
> <#2171 (reply in thread)>,
> or unsubscribe
> <https://github.com/notifications/unsubscribe-auth/ASKIPTWOVV6VZ6MFJDNNFYT26HTD5AVCNFSM6AAAAAB46JRG52VHI2DSMVQWIX3LMV43URDJONRXK43TNFXW4Q3PNVWWK3TUHMYTGMJTGA4DOMY>
> .
> You are receiving this because you were mentioned.Message ID:
> ***@***.***>
>
|
Beta Was this translation helpful? Give feedback.
-
Merci je me mets au travail pour vour
Le mar. 20 mai 2025, 18:46, Pascal Bourgault ***@***.***> a
écrit :
… Malheureusement non. Avec une boucle sur chaque élément, ça ne devrait pas
être trop compliqué à faire dans xarray directement. Si jamais vous arrivez
à une bonne solution, nous serions très heureux de vous aider à l'inclure
dans xclim.
—
Reply to this email directly, view it on GitHub
<#2171 (reply in thread)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/ASKIPTRKRCEPW6YGYALH5QT27N2B3AVCNFSM6AAAAAB46JRG52VHI2DSMVQWIX3LMV43URDJONRXK43TNFXW4Q3PNVWWK3TUHMYTGMRRGA2TEOI>
.
You are receiving this because you were mentioned.Message ID:
***@***.***>
|
Beta Was this translation helpful? Give feedback.
Vous êtes chanceux, la fonction existe! Elle est récente par contre et n'a pas été utilisée très souvent chez nous, donc elle est encore un peu mal documentée :
xc.indices.run_length.find_events
.https://xclim.readthedocs.io/en/stable/indices.html#xclim.indices.run_length.find_events
Si vos données sont grosses et que vous utilisez
dask
, il se peut que la fonction soit un peu lente. C'est que dans les indicateurs classiques, où l'on renvoie une seule réponse par période, on sait d'avance la taille de la sortie. Ici, on ne peut pas le savoir donc on doit se préparer au pire ce qui grossit de beaucoup l'array de sortie, qui sera normalement plein de vide.Vous m'en direz des nouvelles!