chavlin
    • 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
    • Engagement control
    • 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 Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control 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
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- title: volume rendering intro for geodata in yt tags: yt --- # volume rendering intro for geodata in yt this presentation: https://bit.ly/ytgeostuff yt's overview on volume rendering: [link](https://yt-project.org/doc/visualizing/volume_rendering.html) Chris's 2020 AGU poster: [citeable archive](https://www.essoar.org/doi/abs/10.1002/essoar.10506118.2), [direct repo link](https://github.com/earthcube2020/ec20_havlin_etal). Other code/repos: yt: https://yt-project.org/ ytgeotools: https://github.com/chrishavlin/ytgeotools yt_idv: https://github.com/yt-project/yt_idv ## where to get seismic data tomography http://ds.iris.edu/ds/products/emc-earthmodels/ ## general workflow for seismic data First step is to read 3d model data from native storage (e.g., netcdf file) into a yt in-memory dataset `yt.load_uniform_grid()` [docs link](https://yt-project.org/doc/reference/api/yt.loaders.html#yt.loaders.load_uniform_grid) How to do that depends: making maps or 3D renderings? ### map making load as an `internal_geographic` dataset: ```python= ds = yt.load_uniform_grid(data, sizes, 1.0, geometry=("internal_geographic", dims), bbox=bbox) ``` where: `data`: dictionary of field data arrays read from your netcdf `sizes`: the shape of the field data `bbox`: the bounding box `dims`: the ordering of dimensions in the data arrays See [this notebook](https://nbviewer.jupyter.org/github/chrishavlin/AGU2020/blob/main/notebooks/seismic.ipynb#Fixed-Depth-Maps) for a full example. See [this notebook](https://nbviewer.jupyter.org/github/chrishavlin/yt_scratch/blob/master/notebooks/yt_obspy_raypath_sampling.ipynb) for an example of some analysis once data is loaded: sampling data along a seismic ray path. Caveats: * fixed-depth maps only (no cross-sections) * still a little buggy (global models seem to work better than non-global models) * no volume rendering ## geo-volume rendering with yt (background) **data must be in cartesian coordinates** Step 1: interpolate the seismic model to a (uniform) cartesian grid. My approach: 1. convert lat, lon, depth arrays to geocentric cartesian coordinates, `x,y,z` 2. find bounding box in cartesian coordinates: ```python= cart_bbox = [ [min_x, max_x], [min_y, max_y], [min_z, max_z], ] ``` 3. create a uniform grid to cover bounding box: ```python= x_i = np.linspace(min_x, max_x, n_x) y_i = np.linspace(min_y, max_y, n_y) z_i = np.linspace(min_z, max_z, n_z) ``` (`i` for interpolation) 4. find the data values at all those points ``` data_on_cart_grid = new array for xv, yv, zv in np.meshgrid(x_i, y_i, z_i): data_on_cart_grid[xvi, yvi, zvi] = sample_the_data(xv, yv, zv) ``` **How to `sample_the_data` ?** Build a KDtree of actual model points ``` tree = KDtree(x, y, z) ``` for every point on the new cartesian grid, find the `N` closest points, use inverse-distance weighting (IDW) to average those points. Can set a max distance to exclude points too far away. Could experiment with different methods here! just take the "nearest"? Different interopolation method entirely? Sometimes a little buggy... depending on the resolution of the covering grid: weird artifacts or empty interpolated data. **Once data is sampled** Use `yt.load_uniform_grid`: ```python data = {"dvs": dvs_on_cartesian} bbox = cart_bbox sizes = dvs_on_cartesian.shape ds = yt.load_uniform_grid(data, sizes, 1.0) ``` can now use volume rendering! Seismic examples: * [AGU2020](https://nbviewer.jupyter.org/github/chrishavlin/AGU2020/blob/main/notebooks/seismic.ipynb#Volume-Rendering) * EarthCube2020: [citeable archive](https://www.essoar.org/doi/abs/10.1002/essoar.10506118.2) or the [repo](https://github.com/earthcube2020/ec20_havlin_etal). both those rely on https://github.com/chrishavlin/yt_velmodel_vis The EarthCube notebook ([direct link](https://nbviewer.jupyter.org/github/earthcube2020/ec20_havlin_etal/blob/master/notebook/ec20_havlin_etal.ipynb)) covers the interpolation above and goes into transfer functions in more detail. ### geo-volume rendering in practice: New package! https://github.com/chrishavlin/ytgeotools streamlines all the above, with some additional analysis functionality. ```python import yt from ytgeotools.seismology.datasets import XarrayGeoSpherical filename = "IRIS/GYPSUM_percent.nc" # to get a yt dataset for maps: ds_yt = XarrayGeoSpherical(filename).load_uniform_grid() # to get a yt dataset on interpolated cartesian grid: ds = XarrayGeoSpherical(filename) ds_yt_i = ds.interpolate_to_uniform_cartesian( ["dvs"], N=50, max_dist=50, return_yt=True, ) ``` **should** be useable for any IRIS EMC netcdf file to get a yt dataset. Installation not yet streamlined... need to install two packages from source in the following order: 1. https://github.com/yt-project/yt_idv 2. https://github.com/chrishavlin/ytgeotools Need `cartopy`... easiest to use a conda environment. Download/clone 1 and 2, make sure `conda` environment is active, then `cd` into `yt_idv` and install from source with ``` $ python pip install . ``` Repeat for `ytgeotools`. Test installation: from a python shell, try: ``` >>> import yt_idv >>> import ytgeotools >>> import yt ``` There may be some more missing depencies to install... #### manual volume rendering The AGU and EarthCube notebooks use the standard yt volume rendering interfaces. Excerpted from those notebooks, typical workflow to create an image would look like: ```python= import yt from ytgeotools.seismology.datasets import XarrayGeoSpherical # load the cartesian dataset ds_raw = XarrayGeoSpherical(filename) ds = ds_raw.interpolate_to_uniform_cartesian( ["dvs"], N=50, max_dist=50, return_yt=True, ) # create the scene (loads full dataset into the scene for rendering) sc = yt.create_scene(ds, "dvs") # adjust camera position and orientation (so "up" is surface) x_c=np.mean(bbox[0]) y_c=np.mean(bbox[1]) z_c=np.mean(bbox[2]) center_vec = np.array([x_c,y_c,z_c]) center_vec = center_vec / np.linalg.norm(center_vec) pos=sc.camera.position sc.camera.set_position(pos,north_vector=center_vec) # adjust camera zoom zoom_factor=0.7 # < 1 zooms in init_width=sc.camera.width sc.camera.width = (init_width * zoom_factor) # set transfer function # initialize the tf object by setting the data bounds to consider dvs_min=-8 dvs_max=8 tf = yt.ColorTransferFunction((dvs_min,dvs_max)) # set gaussians to add TF_gaussians=[ {'center':-.8,'width':.1,'RGBa':(1.,0.,0.,.5)}, {'center':.5,'width':.2,'RGBa':(0.1,0.1,1.,.8)} ] for gau in TF_gaussians: tf.add_gaussian(gau['center'],gau['width'],gau['RGBa']) source = sc.sources['source_00'] source.set_transfer_function(tf) # adjust resolution of rendering res = sc.camera.get_resolution() res_factor = 2 new_res = (int(res[0]*res_factor),int(res[1]*res_factor)) sc.camera.set_resolution(new_res) # if in a notebook sc.show() # if in a script sc.save() ``` A lot of trial and error for transfer functions, camera positioning. Make videos by adjusting the camera position, saving off the images and then stitching together with a different tool. ### interactive volume rendering yt_idv! ```python= import numpy as np import yt_idv from ytgeotools.seismology.datasets import XarrayGeoSpherical def refill(vals): vals[np.isnan(vals)] = 0.0 vals[vals > 0] = 0.0 return vals filename = "IRIS/NWUS11-S_percent.nc" ds = XarrayGeoSpherical(filename) ds_yt = ds.interpolate_to_uniform_cartesian( ["dvs"], N=50, max_dist=50, return_yt=True, rescale_coords=True, ## IMPORTANT! apply_functions=[refill, np.abs], ) rc = yt_idv.render_context(height=800, width=800, gui=True) sg = rc.add_scene(ds_yt, "dvs", no_ghost=True) rc.run() ``` great for getting a sense of what's in the data! caveats: * max intensity and projection transfer functions only for now... * need to install from source for now (maybe not later today?) ### annotations: In manual plotting, ```python= from yt.visualization.volume_rendering.api import LineSource, PointSource ``` Coordinates need to be in cartesian as well... The EarthCube/AGU notebooks have some helper functions to streamline this. Not yet in ytgeotools or yt_idv. In manual plotting, adding the Point and Line sources can affect the overall brightness of the scene, often a lot of trial and error to adjust the opacity of the sources so that they do not wash out the volume rendering.

    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