Emma Marshall
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Data Tidying Xarray provides flexible structures with which to store and access data. However, appropriately coercing data into a format that simplifies subsequent processing and analysis is often a difficult first step for users of Xarray. This page discusses common data 'tidying' steps, and presents principles to keep in mind when organizing data in Xarray. We also point out helpful extensions to simplify and automate this process for specific dataset types like satellite imagery. ### Tidy Data Hadley Wickham developed the tidy data concept for tabular datasets in the R programming language ([paper](https://vita.had.co.nz/papers/tidy-data.pdf)). It presents three main principles: 1. Every column is a variable 2. Every row is an observation 3. Every cell is a single value You can find more in-depth explanations of tidy data and the body of work it has inspired [here](https://r4ds.hadley.nz/data-tidy.html). Here, we articulate 'tidy' principles for n-dimensional gridded data as represented by an Xarray Dataset. ### Thinking of your data as a data cube Data is stored and made available to users in a variety of format and structures. Commonly the first step of many scientific workflows will be to assemble a data cube of the form `(x,y,time)` out of a collection of files representing spatial and temporal subsets of data. There are different ways to stitch together many files into a cohesive data object and the structure of the stitched together object will either make subsequent analysis smoother or more difficult. Tidy data is about structuring data to simplify subsequent analysis. ## Understanding & using Xarray structures Xarray is built around three main structures: `xr.Datasets`, `xr.DataArrays` and [DataTrees](https://xarray-datatree.readthedocs.io/en/latest/data-structures.html). Think of `xr.DataArrays` as single variable objects that contain dimensions and coordinates. `xrDatasets` contain multiple data variables. Each data variable of a `xr.Dataset` is a `xr.DataArray`. DataTree objects are structures used for organizing workflows with multiple, un-alignable `xr.Datasets`. Returning to the concept of a data cube, `xr.DataArrays` are cubes, `xr.Datasets` are a collection of cubes that share a common “domain”, and DataTrees are collections of cubes, that need not share “domains”. For simplicity, this page will focus mostly on `xr.Dataset` objects. ![HTML repr of a standard `xr.Dataset` object](https://hackmd.io/_uploads/Byzdbj0ST.png) HTML repr of a standard `xr.Dataset` object. Before discussing principles of tidy objects in Xarray, we provide non-technical definitions of Xarray objects that relate to how they can be used when organizing data. For more, see [the Xarray reference documentation](https://docs.xarray.dev/en/stable/user-guide/terminology.html). | Term | Definition | | ------------------------- |:------------------------------------------------------------------------------------ | | Data Variables | Physical observables that are the subject of the dataset. | | Dimension Coordinates | Variables defining the domain of observable(s). | | Non-dimension coordinates | Metadata that is best expressed as arrays sharing dimensions with the data variable. | | Attributes | Metadata that is static, commonly key-value pairs. | ## Tidy Xarray ## Principles of Tidy Gridded Data ### 1. [Dimensional coordinate variables](https://docs.xarray.dev/en/stable/user-guide/terminology.html#term-Dimension-coordinate) Minimize # of dimensional coords; only what is necessary to describe shape of your data ### 2. [Non-dimensional coordinate variables](https://docs.xarray.dev/en/stable/user-guide/terminology.html#term-Non-dimension-coordinate) Non-dimensional coordinates can be numerous. Each should exist along one or multiple dimensions ### 3. [Data variables](https://docs.xarray.dev/en/stable/user-guide/terminology.html#term-Variable) These should be observables rather than contextual, each should exist along one or multiple dimensions ### 4. Contextual information (metadata) Metadata should only be stored as an attribute if it is static along the dimensions to which it is applied If metadata is dynamic, store as coordinate variable Metadata attrs should be added such that dataset is self-describing (following CF-conventions) ### 5. Variable, attribute naming Where possible, use cf-conventions for naming Variable names should be descriptive Variable names should not contain information that belongs in a dimension or coordinate. (ie. information stored in variable name should be reduced only to observable) ### 6. Make use of, work within the frameworks of other tools Tools like STAC, open data cube, cf.xarray, pystac, stackstac [and many more] maker tidying possible (+ smoother), especially with large datasets Diagram of Xarray object components: ![dataset-diagram](https://hackmd.io/_uploads/BktUipyL6.png) --- ### Guiding questions for tidying data[^1] To help guide categorizing the data and metadata at hand accoring to Table XX, we suggest considering the following questions: 1. What type of questions do I want to ask of this dataset, what kind of structure will facilitate that analysis? 2. What is the meaning of the data, and how can its *structure* best reflect its *meaning*? ## Roadmap of common data tidying steps This section discusses common 'data tidying' steps in a typical scientific workflow. ### Before reading data into Xarray Organizing and storing large numbers of files covering varying spatial and temporal domains so that they can be read into Xarray efficiently and intuitively can be a non-trivial task in itself. This one step where descriptive and conventional metadata can be very beneficial. It is worth spending some time understanding the layout of the dataset, what data you need to answer your scientific questions, and the overall data structure that would help you to ask and answer those questions. Then, you can consider which tools might be appropriate to help read the data into Xarray. Some options to consider are [stackstac](https://stackstac.readthedocs.io/en/latest/), [odc-stac](https://github.com/opendatacube/odc-stac), [PySTAC](https://pystac.readthedocs.io/en/stable/), [Intake](https://github.com/intake/intake) and [Kerchunk](https://fsspec.github.io/kerchunk/). ### Reading data into Xarray Data is often distributed as individual files that need to be combined in to a cube to answer the questions at hand. Often, these files are separated into spatial and temporal subsets and the first task of the user will be to read in the desired data variables, and temporal and spatial regions of interest, and construct a tidy data cube with which to pursue further analysis. `xarray.open_mfdataset()` is a very useful function at this step. If your dataset follows STAC metadata specifications, tools like stackstac and odc-stac can be helpful for querying and subsetting large catalogues of data. ### Assembling and tidying a data cube After the relevant files have been accessed, the next step is typically to assemble different objects into one cohesive and self-describing data cube. Usually, this will be an `xarray.DataArray` or `xarray.Dataset` with the form `(space,time)`. This step often entails: 1. Parsing filenames to access metadata 2. Adding new dimensions, 3. Converting metadata in individual files to non-dimension coordinate variables, 4. Renaming dimension names, 5. Concatenating different objects along a dimension, 6. Merging cubes to form a dataset, 7. Adding additional metadata based on dataset reference documentation, or to follow metadata conventions (e.g. [CF](https://cfconventions.org/), [STAC](https://stacspec.org/en)) For larger-than-memory data when dask arrays are used, rechunking usually occurs at this step. ### Helpful Resources [Project Pythia tutorial on CF/netCDF](https://foundations.projectpythia.org/core/data-formats/netcdf-cf.html) ### Data cube --> Analysis ready > [name=Deepak Cherian] I added text above that ended up merging this section and the previous one. Let's condense? > I think the specific examples are best added under subsections that share titles with the list above. Though if there isn't much text, maybe we can just add more text under each list element. I believe latex calls these "description" lists. After step 2, the data cube often appears 'tidied', however frequently there are additional manipulations that must be performed to truly make the data ready to work with (or, *analysis-ready*). These steps can vary widely and be specific to individual datasets but are very important to creating objects that will simplify future analysis. Examples of this can be found (here - link to itslive example where there are many many data variables, most should be coordinate variables) and here (link to HLS example with bit packed masks). Any others? ## Common user-hangups #### 1. Embedding a dimension in a variable name Frequently-observed example: Data variables such as `air_temp_t1` and `air_temp_t2` to represent data about an observable (`air temp`) collected at 2 different points in time (`t1`, `t2`). (insert image/code of corresponding dataset). This is an example of the data structure not matching its meaning. A helpful way to catch these instances is to check if you are trying to provide a description beyond the direct observable in the variable name. In this case, the variable names are being used to describe the observable, but also where it lies along a time dimension. Not only is this clunky, but it prevents you from using built-in xarray functionality like grouping over dimensions (making subsequent organization and analysis much more difficult) insert code example #### 2. Metadata in file names Commonly time. #### 3. Metadata as attributes The choice to distribute certain metadata fields as "attributes" can make sense when distributing file but makes little sense when considering the dataset as a whole, or as a cube. Example "ascending" and "descending" passes... **insert more?** > [name=Deepak Cherian] Yes! IIRC we had a nice list going somewhere ![Screenshot from 2023-12-01 12-47-14](https://hackmd.io/_uploads/Hy6k_hwHa.png) ### Repository of untidy/ tidying examples Link to github [repo](https://github.com/dcherian/tidy-xarray) with issue template (*in progress*) > [name=Scott Henderson] Linking to short examples / visuals, especially of the common scenarios identified above would be great. Added an example here / ideas on what to put in a template https://github.com/dcherian/tidy-xarray/issues/7 [^1]: (heavily inspired from H. Wickham)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully