### Run GPlately Examples with Docker Source: https://github.com/gplates/gplately/blob/master/sphinx-doc/source/examples.md Pull the GPlately Docker image and run it, mounting the current directory to access examples and exposing the Jupyter Notebook port. ```console $ docker pull gplates/gplately $ docker run --rm -ti -v .:/ws -w /ws -p 8888:8888 gplates/gplately ``` -------------------------------- ### Create GPlately Environment with Micromamba Source: https://github.com/gplates/gplately/blob/master/sphinx-doc/source/basic_usages.md Use micromamba to create and activate a new environment, then install the gplately package. This is the initial setup for both Python script and Jupyter Notebook options. ```console $ micromamba create -n my-gplately-env $ micromamba activate my-gplately-env $ micromamba install -c conda-forge gplately ``` ```console $ micromamba create -n my-gplately-env $ micromamba activate my-gplately-env $ micromamba install -c conda-forge gplately jupyter ``` -------------------------------- ### Download Example Data Source: https://github.com/gplates/gplately/blob/master/Notebooks/Examples/use_your_own_plate_model.ipynb Downloads necessary test data for the example. It checks if the files need updating before downloading. ```python import cartopy.crs as ccrs import matplotlib.pyplot as plt import pygplates from plate_model_manager.utils import download import gplately from gplately.auxiliary import get_plate_reconstruction time = 50 data_dir = "gplately-example-data" downloader = download.FileDownloader( "https://repo.gplates.org/webdav/gplately-test-data/test_model.zip", f"{data_dir}/.metadata.json", f"{data_dir}", ) # only re-download when necessary if downloader.check_if_file_need_update(): downloader.download_file_and_update_metadata() else: print(f"The local files are still good. No need to download again!") ``` -------------------------------- ### Install GPlately using Pip from GitHub Source: https://github.com/gplates/gplately/blob/master/sphinx-doc/source/installation.md Installs the latest code changes directly from the GPlately GitHub repository. Use this if you need the most recent updates not yet released on PyPI. ```console $ pip install git+https://github.com/GPlates/gplately.git ``` -------------------------------- ### Install GPlately using Pip from PyPI Source: https://github.com/gplates/gplately/blob/master/sphinx-doc/source/installation.md Installs the latest stable public release of GPlately from the Python Package Index (PyPI). ```console $ pip install gplately ``` -------------------------------- ### Start Jupyter Notebook Server Source: https://github.com/gplates/gplately/blob/master/sphinx-doc/source/basic_usages.md Launch the Jupyter Notebook server from your terminal to create and run notebooks. ```console $ jupyter notebook ``` -------------------------------- ### Set up Conda Environment for GPlately Source: https://github.com/gplates/gplately/blob/master/sphinx-doc/source/examples.md Create and activate a Conda environment using a provided YAML file, then launch Jupyter Notebook for GPlately examples. ```console $ conda env create --name my-gplately-env --file=env.yaml $ conda activate my-gplately-env $ jupyter notebook ``` -------------------------------- ### Install GPlately using Conda Source: https://github.com/gplates/gplately/blob/master/sphinx-doc/source/installation.md Installs the latest stable release of GPlately into a new conda environment named 'my-gplately-conda-env'. This is the recommended installation method. ```console $ conda create -n my-gplately-conda-env $ conda activate my-gplately-conda-env $ conda install -c conda-forge gplately ``` -------------------------------- ### Install GPlately using Pip in editable mode Source: https://github.com/gplates/gplately/blob/master/sphinx-doc/source/installation.md Installs GPlately from a local folder in editable mode, allowing for direct code changes to be reflected without reinstallation. This is useful for local development. ```console $ git clone https://github.com/GPlates/gplately.git gplately.git $ cd gplately.git $ git checkout master $ git pull $ MAKE YOUR LOCAL CODE CHANGES HERE ... $ pip install -e . ``` -------------------------------- ### Setup Input Files and Parameters Source: https://github.com/gplates/gplately/blob/master/Notebooks/Examples/ptt/notebooks/ridge_length_spreading_rates.ipynb Initializes pygplates rotation model and topology features, defines output file, averaging time window, and time range for calculations. Sets tessellation distance and specifies feature types to consider (e.g., mid-ocean ridges). ```python from __future__ import print_function import math import os import pygplates import sys from ptt import ridge_spreading_rate # Input rotation and topology files. rotation_filename = '../data/Global_EarthByte_230-0Ma_GK07_AREPS.rot' rotation_model = pygplates.RotationModel(rotation_filename) topology_filenames = [ '../data/Global_EarthByte_230-0Ma_GK07_AREPS_PlateBoundaries.gpmlz', '../data/Global_EarthByte_230-0Ma_GK07_AREPS_Topology_BuildingBlocks.gpmlz'] # Output file containing results at each reconstruction time. output_filename = '../data/ridge_spreading_rates.txt' # The time window over which to average spreading rates (in My). averaging_time_window = 1 # Define the time range. # The reconstruction time range to output statistics for. # # NOTE: Topologies are resolved up to time 'max_time + averaging_time_window - 1' # so can average over past 'averaging_time_window' million years. min_time = 0 max_time = 230 # Tessellate the subduction zones to 0.5 degrees. threshold_sampling_distance_radians = math.radians(0.5) # List of spreading feature types to consider. # Only look at mid-ocean ridge features. spreading_feature_types = [pygplates.FeatureType.gpml_mid_ocean_ridge] # Consider all 'spreading' features. # A spreading feature has left/right plate IDs (eg, mid-ocean ridge) or # conjugate plate IDs (eg, isochron). #spreading_feature_types = None ``` -------------------------------- ### Setup Input and Output Files Source: https://github.com/gplates/gplately/blob/master/Notebooks/Examples/ptt/notebooks/sample_raster_along_subd_zone.ipynb Configures input rotation and topology files, output file paths, and raster data details. Defines the time range for analysis and the tessellation threshold for subduction zones. ```python from __future__ import print_function import math import os import pygplates import sys # Add directory containing the 'ptt' module (Plate Tectonic Tools) to the Python path. from ptt import subduction_convergence # Input rotation and topology files. rotation_filename = '../data/Global_EarthByte_230-0Ma_GK07_AREPS.rot' rotation_model = pygplates.RotationModel(rotation_filename) topology_filenames = [ '../data/Global_EarthByte_230-0Ma_GK07_AREPS_PlateBoundaries.gpmlz', '../data/Global_EarthByte_230-0Ma_GK07_AREPS_Topology_BuildingBlocks.gpmlz'] # Output file containing results at each reconstruction time. output_filename = '../data/subducting_raster.txt' # Base filename and extension of raster to sample. raster_filename_base = '../data/CO2' raster_filename_ext = 'nc' # Define the time range. # The reconstruction time range (topologies resolved to these times). # Also used to get paleo raster filenames based on 'raster_filename_base'. min_time = 0 max_time = 1 # Tessellate the subduction zones to 0.5 degrees. tessellation_threshold_radians = math.radians(0.5) ``` -------------------------------- ### Setup for Plotting Zircons Source: https://github.com/gplates/gplately/blob/master/Notebooks/13-ReconstructingZirconData.ipynb Sets up the output directory and a boolean flag to control parallel processing for plotting. ```python use_parallel = True output_directory = "./NotebookFiles" # Replace with your save directory here os.makedirs(output_directory, exist_ok=True) ``` -------------------------------- ### Print Rotation Configuration Summary Source: https://github.com/gplates/gplately/blob/master/Notebooks/15-ConvertGridReferenceFrame.ipynb Prints a summary of the rotation configuration, including source and target models, time steps, grid resolution, and input/output templates. This helps in verifying the setup before proceeding with the rotation process. ```python # Print a one-screen summary of what will run. def _summary(label, name, files, anchor): src = f"model='{name}'" if name else f"files={files}" return f" {label:<6}: {src}, anchor={anchor}" print("Rotation configuration") print(_summary("source", from_model_name, from_rotation_files, from_anchor)) print(_summary("target", to_model_name, to_rotation_files, to_anchor)) print(f" times : {min_time}-{max_time} Ma at {timestep_size} Myr cadence " f"({len(reconstruction_times)} grids)") print(f" res : {grid_spacing_degrees}°") print(f" input : {input_grid_template}") print(f" output: {output_grid_template}") ``` -------------------------------- ### Setup Parallel Processing with Joblib Source: https://github.com/gplates/gplately/blob/master/Notebooks/08-PredictingSlabFlux.ipynb Configures joblib for parallel processing, using all available CPUs except two, or serial processing on Windows where parallel execution can be slower. ```python from joblib import Parallel, delayed import platform # Use serial processing on Windows (runs slower in parallel than in serial for some reason). if platform.system() == 'Windows': n_jobs = None else: n_jobs = -3 # use all CPUs except 2 # Use Loky Backend parallel = Parallel(n_jobs=n_jobs, backend='loky', verbose=1) reconstruction_times = np.arange(0, 231) ``` -------------------------------- ### Initialize Calculation Variables Source: https://github.com/gplates/gplately/blob/master/Notebooks/Examples/ptt/notebooks/ridge_length_spreading_rates.ipynb Prints a message indicating the start of the spreading rate calculation process. Initializes an empty list to store output data and reads topology features from specified files. ```python print('Calculating spreading rates from {0} to {1} Ma...'.format(min_time, max_time)) # Each element of this list will be a tuple of values for a specific reconstruction time. output_data = [] # Read the topology filenames once instead of at every time step. topology_features = [] for topology_filename in topology_filenames: topology_features.extend(pygplates.FeatureCollection(topology_filename)) # Keep track of spreading-rate-related quantities over time so can later calculate statistics. total_length_metres_time_sequence = [] total_spreading_rate_times_length_time_sequence = [] total_spreading_rate_squared_times_length_time_sequence = [] ``` -------------------------------- ### Build GPlately Docker Image Source: https://github.com/gplates/gplately/blob/master/docker/README.md Clone the repository, navigate to the directory, and build the Docker image. Consider using the --no-cache option if build errors occur. ```bash git clone --depth 1 --branch master https://github.com/GPlates/gplately.git ``` ```bash cd gplately ``` ```bash docker build -f docker/Dockerfile -t gplately . ``` -------------------------------- ### Get Present-Day Raster Data Source: https://github.com/gplates/gplately/blob/master/Notebooks/Examples/introducing_plate_model_manager.ipynb Retrieves and prints the data for a specific present-day raster, such as 'topography'. ```python print(PresentDayRasterManager().get_raster("topography")) ``` -------------------------------- ### Define Input/Output Filenames and Parameters Source: https://github.com/gplates/gplately/blob/master/Notebooks/Examples/ptt/notebooks/predict_using_chebyshev_2d.ipynb Sets up base filenames for input and output data, defines the time range, grid spacing, output range clamping, and flags for log scaling of input data and GMT surface gridding. This configuration is essential before processing any data. ```python # Base filename and extension of input x and y rasters to sample. x_filename_base, x_filename_ext = '../data/agegrid', 'nc' y_filename_base, y_filename_ext = '../data/bottom_water_temp', 'nc' # Base filename output z raster to generate. z_filename_base = '../data/CO2' # Define the time range. # Used to get paleo x, y and z raster filenames (from base filenames). min_time = 0 max_time = 1 # Lat/lon spacing in z output grid. grid_spacing = 0.5 # Clamp output z minimum and maximum (individually applicable). zrange = 0.0, None # Whether input x and y data were modelled using the logarithm (log10) of the input data. log_scale_input_x, log_scale_input_y = True, True # Whether to grid output data using GMT 'surface' (if False then use 'nearneighbor' instead). grid_using_gmt_surface = False ``` -------------------------------- ### Get All Layer Data Source: https://github.com/gplates/gplately/blob/master/Notebooks/Examples/introducing_plate_model_manager.ipynb Retrieves and prints the data for all available layers within the current model. ```python for layer in model.get_avail_layers(): print(model.get_layer(layer)) ``` -------------------------------- ### Run Specific Test Source: https://github.com/gplates/gplately/blob/master/tests-dir/pytestcases/TEST_FEATURE_FILTER_UNITS.md Execute a single, specific test case, for example, 'test_contains_match' within 'TestFeatureNameFilter'. ```bash python -m pytest tests-dir/pytestcases/test_8_feature_filter.py::TestFeatureNameFilter::test_contains_match -v ``` -------------------------------- ### Initialize GPlately PlateReconstruction and PlotTopologies Source: https://github.com/gplates/gplately/blob/master/Notebooks/12-MutschlerWorldPorphyryCopperDepositsRegionalPlots.ipynb Sets up the GPlately PlateReconstruction model using a specified rotation model and topology features. It then initializes PlotTopologies with coastlines and a specific time. ```python recon_model = gplately.PlateModelManager().get_model( "Alfonso2024", # model name data_dir="plate-model-repo", # the folder to save the model files ) model = gplately.PlateReconstruction( recon_model.get_rotation_model(), topology_features=recon_model.get_layer("Topologies"), static_polygons=recon_model.get_layer("StaticPolygons"), ) gplot = gplately.PlotTopologies( model, coastlines=recon_model.get_layer("Coastlines"), time=170, ) # Path to source data zip containing sed thickness grids #source_data_dir = os.path.join('/source_data', 'source_data') total_sed_grid_filename ="./source_data/SedimentThickness/sed_thick_0.1d_{}.nc" carbonate_sed_grid_filename = "./source_data/CarbonateThickness/uncompacted_carbonate_thickness_{}Ma.nc" # Path to save all output plots to output_dir = "./outputs" os.makedirs(output_dir+"/Plots_v2", exist_ok=True) ``` -------------------------------- ### Initialize Rotation Models and Output Directory Source: https://github.com/gplates/gplately/blob/master/Notebooks/15-ConvertGridReferenceFrame.ipynb Initializes rotation models for source and target frames and ensures the output directory exists. This step primes the cache and performs initial validation of the configuration. ```python # Build / prime each side once in the main process for cache warm-up + sanity. _from_model_main = build_rotation_model(from_model_name, from_rotation_files) _to_model_main = build_rotation_model(to_model_name, to_rotation_files) reconstruction_times = np.arange(min_time, max_time + timestep_size, timestep_size) # Make sure the output directory exists. os.makedirs(os.path.dirname(os.path.abspath(output_grid_template.format(0.0))), exist_ok=True) ``` -------------------------------- ### Set up PlateReconstruction and PlotTopologies objects Source: https://github.com/gplates/gplately/blob/master/Notebooks/09-CreatingMotionPathsAndFlowlines.ipynb Initializes PlateModelManager to download the Matthews2016 model, then creates PlateReconstruction and PlotTopologies objects for analyzing and visualizing plate tectonic data. ```python # Download Matthews2016 model pm_manager = PlateModelManager() matthews2016_model = pm_manager.get_model("Matthews2016", data_dir="plate-model-repo") rotation_model = matthews2016_model.get_rotation_model() topology_features = matthews2016_model.get_topologies() static_polygons = matthews2016_model.get_static_polygons() coastlines = matthews2016_model.get_layer('Coastlines') # Create a PlateReconstruction object model = gplately.reconstruction.PlateReconstruction(rotation_model, topology_features, static_polygons) # Create a PlotTopologies object gplot = gplately.PlotTopologies(model, coastlines=coastlines, continents=None, COBs=None, time=0) ``` -------------------------------- ### Get Specific Layer Data Source: https://github.com/gplates/gplately/blob/master/Notebooks/Examples/introducing_plate_model_manager.ipynb Retrieves and prints the data for a specific layer, such as 'StaticPolygons' or 'Coastlines', from the current model. ```python static_polygon_files = model.get_layer("StaticPolygons") print(static_polygon_files) ``` ```python coasts_files = model.get_layer("Coastlines") print(coasts_files) ``` -------------------------------- ### Create PlateReconstruction and PlotTopologies Objects Source: https://github.com/gplates/gplately/blob/master/Notebooks/Examples/use_your_own_plate_model.ipynb Initializes PlateReconstruction with custom model files and PlotTopologies for visualization. ```python model = gplately.PlateReconstruction( rotation_model=f"{data_dir}/test_model/test_rotations.rot", topology_features=f"{data_dir}/test_model/test_topology.gpmlz", static_polygons=f"{data_dir}/test_model/test_static_polygons.gpmlz", ) gplot = gplately.PlotTopologies( model, coastlines=f"{data_dir}/test_model/test_coastlines.gpmlz", continents=f"{data_dir}/test_model/test_continental_polygons.shp", COBs=f"{data_dir}/test_model/test_cobs.gpmlz", time=time, ) ``` -------------------------------- ### Get Rotation Model Files Source: https://github.com/gplates/gplately/blob/master/Notebooks/Examples/introducing_plate_model_manager.ipynb Retrieves and prints the file information for the rotation model associated with the current model. ```python rotation_files = model.get_rotation_model() print(rotation_files) ``` -------------------------------- ### Create Velocity Animation with MoviePy Source: https://github.com/gplates/gplately/blob/master/Notebooks/04-VelocityBasics.ipynb Generates a sequence of frames and compiles them into a GIF animation using moviepy. Ensure moviepy is installed. ```python import tempfile from IPython.display import Image try: from moviepy.editor import ImageSequenceClip # moviepy 1.x except ImportError: from moviepy import ImageSequenceClip # moviepy 2.x # Time variables oldest_seed_time = 100 # Ma time_step = 10 # Ma with tempfile.TemporaryDirectory() as tmpdir: frame_list = [] # Create a plot for each 10 Ma interval for time in np.arange(oldest_seed_time, 0., -time_step): print('Generating %d Ma frame...' % time) frame_filename = os.path.join(tmpdir, "frame_%d_Ma.png" % time) generate_frame(frame_filename, time) frame_list.append(frame_filename) video_filename = os.path.join(tmpdir, "plate_velocity_scatter_plot.gif") clip = ImageSequenceClip(frame_list, fps=5) clip.write_gif(video_filename) print('The movie will show up in a few seconds...') with open(video_filename, 'rb') as f: display(Image(data=f.read(), format='gif', width = 1000, height = 500)) ``` -------------------------------- ### Define Output Directories and File Naming Source: https://github.com/gplates/gplately/blob/master/Notebooks/10-SeafloorGrids.ipynb Sets up the directory structure for saving output files and defines a string for file collection naming. Ensure the save directory exists before running. ```python # continent masks, initial ocean seed points, and gridding input files are kept here output_parent_directory = os.path.join( "NotebookFiles", "Notebook10", ) save_directory = os.path.join( output_parent_directory, "seafloor_grid_output", ) print(f"The ouput files created by this notebook will be saved in folder {save_directory}." ) # A string to help name files according to a plate model "Merdith2021" file_collection = "Merdith2021" ``` -------------------------------- ### Import Libraries for Slab Flux Prediction Source: https://github.com/gplates/gplately/blob/master/Notebooks/08-PredictingSlabFlux.ipynb Imports necessary libraries including gplately, matplotlib, numpy, and PlateModelManager. Ensure these are installed in your environment. ```python %matplotlib inline import gplately import matplotlib.pyplot as plt import numpy as np from scipy.ndimage import gaussian_filter from plate_model_manager import PlateModelManager ``` -------------------------------- ### Initialize PlateReconstruction and Plot objects Source: https://github.com/gplates/gplately/blob/master/Notebooks/06-Rasters.ipynb Sets up the PlateReconstruction and PlotTopologies objects using the Muller et al. (2019) plate tectonic model. This involves downloading model components and defining spatial layers. ```python %%capture cap pm_manager = PlateModelManager() muller2019_model = pm_manager.get_model("Muller2019", data_dir="plate-model-repo") rotation_model = muller2019_model.get_rotation_model() topology_features = muller2019_model.get_topologies() static_polygons = muller2019_model.get_static_polygons() coastlines = muller2019_model.get_layer('Coastlines') continents = muller2019_model.get_layer('ContinentalPolygons') COBs = muller2019_model.get_layer('COBs') model = gplately.PlateReconstruction(rotation_model, topology_features, static_polygons) gplot = gplately.PlotTopologies(model, coastlines, continents, COBs) ``` -------------------------------- ### Import Libraries and Setup Source: https://github.com/gplates/gplately/blob/master/Notebooks/Examples/ptt/notebooks/subduction_teeth.ipynb Imports necessary libraries for numerical operations, plotting, and geospatial data handling, including NumPy, Matplotlib, and Cartopy. ```python import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as mcolors %matplotlib inline import cartopy.crs as ccrs import cartopy.feature as cfeature import cartopy.io.shapereader as shpreader ``` -------------------------------- ### Initialize SeafloorGrid Object Source: https://github.com/gplates/gplately/blob/master/Notebooks/10-SeafloorGrids.ipynb Instantiates the `SeafloorGrid` object using all previously defined parameters, including plate reconstruction, time, ridge, gridding, naming, initial conditions, subduction, methodology, and continental features. ```python # The SeafloorGrid object with all aforementioned parameters seafloorgrid = gplately.SeafloorGrid( plate_reconstruction = model, # Time parameters max_time = max_time, min_time = min_time, # Ridge tessellation parameters ridge_time_step = ridge_time_step, ridge_sampling = ridge_sampling, # Gridding parameters grid_spacing = grid_spacing, extent = extent, # Naming parameters save_directory = save_directory, file_collection = file_collection, # Initial condition parameters refinement_levels = refinement_levels, initial_ocean_mean_spreading_rate = initial_ocean_mean_spreading_rate, # Subduction parameters subduction_collision_parameters = subduction_collision_parameters, # Methodology parameters resume_from_checkpoints = resume_from_checkpoints, # Continental polygons. continent_polygon_features = continent_polygon_features, nprocs = nprocs ) ``` -------------------------------- ### Get Time-Dependent Rasters Source: https://github.com/gplates/gplately/blob/master/Notebooks/Examples/introducing_plate_model_manager.ipynb Retrieves and prints time-dependent raster data for specified times or a single specific time. Warnings are suppressed for cleaner output. ```python import warnings warnings.filterwarnings("ignore") print(model.get_rasters("AgeGrids", times=[10, 20, 30])) print(model.get_raster("AgeGrids", time=100)) ``` -------------------------------- ### Get Point Velocities at a Specific Time Source: https://github.com/gplates/gplately/blob/master/Notebooks/04-VelocityBasics.ipynb Obtain plate velocities at a given time in cm/yr. This function can return velocities as separate east/north components. ```python x, y = np.meshgrid(Xnodes,Ynodes) x = x.flatten() y = y.flatten() time = 249 vel_x, vel_y = model.get_point_velocities(x, y, time, velocity_units=pygplates.VelocityUnits.cms_per_yr, return_east_north_arrays=True) vel_mag = np.hypot(vel_x, vel_y) print('Number of points in our velocity domain = ', len(vel_x)) print('Average velocity at {} Ma = {:.2f} cm/yr'.format(time, vel_mag.mean())) ``` -------------------------------- ### Initialize GPLately Points object Source: https://github.com/gplates/gplately/blob/master/Notebooks/03-WorkingWithPoints.ipynb Create a Points object with a plate reconstruction model, longitude, and latitude coordinates. Optionally specify time, plate ID, and age. ```python gpts = gplately.Points( plate_reconstruction, # plate reconstruction model lons, # list or numpy array of longitudinal coordinates lats, # list or numpy array of latitudinal coordinates time=0, # time is set to the present day by default plate_id=None # optionally pass an array (or single integer) of pre-determined plate IDs age=numpy.inf # optionally pass an array (or single float) of pre-determined appearance ages (defaults to: appearing for all time) ) ``` -------------------------------- ### Import necessary libraries for GPlately Source: https://github.com/gplates/gplately/blob/master/Notebooks/11-AndesFluxes.ipynb Imports essential Python libraries for GPlately, including numpy, pandas, matplotlib, and pygplates. Ensure these libraries are installed before running. ```python import sys import gplately import numpy as np import pygplates import glob, os import pandas as pd import matplotlib.pyplot as plt import cartopy.crs as ccrs from plate_model_manager import PlateModelManager anchor_plate_id = 0 ``` -------------------------------- ### Get Available Model Names Source: https://github.com/gplates/gplately/blob/master/Notebooks/Examples/introducing_plate_model_manager.ipynb Retrieves and prints the names of all officially supported GPlately models available in the PlateModelManager. It filters a superset of names returned by the manager. ```python gplately_model_names = get_model_names() for name in pm_manager.get_available_model_names(): # the pm_manager.get_available_model_names() returns a superset of GPlately models. # we need to check the the model name agaist a list of GPlately officially supported models. if name in gplately_model_names: print(name) ``` -------------------------------- ### Define velocity domain extent Source: https://github.com/gplates/gplately/blob/master/Notebooks/04-VelocityBasics.ipynb Sets up the longitudinal and latitudinal arrays to define the grid for calculating point velocities. This example uses 5-degree intervals for global coverage. ```python # The distribution of points in the velocity domain: set global extent with 5 degree intervals Xnodes = np.arange(-180,180,5) Ynodes = np.arange(-90,90,5) ``` -------------------------------- ### Get Valid Geometries from Shapefile Source: https://github.com/gplates/gplately/blob/master/Notebooks/Examples/ptt/notebooks/subduction_teeth.ipynb Extracts valid geometries from a shapefile, specifically focusing on boundaries. This function handles potential shapefile corruption by checking geometry validity. ```python def get_valid_geometries(shape_filename): """ Return valid geometries within a shapefile Shapefiles are incredibly annoying. In a lot of cases the boundary is corrupted which means filled shapes leak out into the rest of the domain. Sometimes this can be mitigated by setting a buffer, sometimes not. Using the boundaries with no fill works most of the time. Caveat Emptor! """ shp_geom = cfeature.shapereader.Reader(shape_filename).geometries() geometries = [] for record in shp_geom: if record.is_valid: geometries.append(record.boundary) # geometries.append(record.buffer(0.)) return geometries ``` -------------------------------- ### Create a plate motion model Source: https://github.com/gplates/gplately/blob/master/Notebooks/04-VelocityBasics.ipynb Initializes a GPlately PlateReconstruction object using data from the Muller et al. (2019) plate model. This involves downloading the model and extracting rotation, topology, and static polygon data. ```python # Download Muller et al. 2019 files pm_manager = PlateModelManager() muller2019_model = pm_manager.get_model("Muller2019", data_dir="plate-model-repo") rotation_model = muller2019_model.get_rotation_model() topology_features = muller2019_model.get_topologies() static_polygons = muller2019_model.get_static_polygons() # Use the PlateReconstruction object to create a plate motion model model = gplately.PlateReconstruction(rotation_model, topology_features, static_polygons) ``` -------------------------------- ### Get Plate Velocity Data Source: https://github.com/gplates/gplately/blob/master/Notebooks/Examples/ptt/notebooks/subduction_obliquity.ipynb Retrieves plate velocity vectors (U, V) at specified nodes (Xnodes, Ynodes) for a given reconstruction time and rotation model. ```python Xnodes, Ynodes, U, V = ptt.velocity_tools.get_velocity_x_y_u_v(reconstruction_time, rotation_model, topology_features) ``` -------------------------------- ### Set up SeafloorGrid for Automatic Gridding Source: https://github.com/gplates/gplately/blob/master/sphinx-doc/source/use_cases.md Initializes the SeafloorGrid object with a plate reconstruction model and time parameters. This is used to automatically grid seafloor ages and spreading rates. ```python import os os.environ["DISABLE_GPLATELY_DEV_WARNING"] = "true" from gplately import SeafloorGrid, auxiliary model = auxiliary.get_plate_model("Muller2019") plate_reconstruction = auxiliary.get_plate_reconstruction(model) # Set up automatic gridding from 5Ma to present day seafloorgrid = SeafloorGrid( plate_reconstruction=plate_reconstruction, # the PlateReconstruction object max_time=5, # start time (Ma) min_time=0, # end time (Ma) ridge_time_step=1, # time increment (Myr) continent_polygon_features=model.get_layer("ContinentalPolygons"), # the continent polygons ) # Begin automatic gridding! seafloorgrid.reconstruct_by_topologies() ``` -------------------------------- ### Download and Set Model Data Directory Source: https://github.com/gplates/gplately/blob/master/Notebooks/Examples/introducing_plate_model_manager.ipynb Downloads a specific model ('Muller2019'), sets its data directory to 'plate-model-repo', and retrieves all available layers. It then lists the files in the downloaded model's directory. ```python model = pm_manager.get_model("Muller2019") assert model model.set_data_dir("plate-model-repo") for layer in model.get_avail_layers(): model.get_layer(layer) # now let's see what are inside the "plate-model-repo/muller2019" folder print(os.listdir("plate-model-repo/muller2019")) ``` -------------------------------- ### Helper Function to Get Data Extent Source: https://github.com/gplates/gplately/blob/master/Notebooks/11-AndesFluxes.ipynb Calculates the bounding box for a given dataset with an optional buffer. Useful for optimizing raster queries by limiting the region of interest. ```python def get_extent_from_data(data, extent_buffer=2): x0 = data.lon.min()-extent_buffer if x0<-180: x0=360+x0 x1 = data.lon.max()+extent_buffer if x1>180: x1=x1-360 y0 = data.lat.min()-extent_buffer if y0<-90: y0=180+y0 y1 = data.lat.max()+extent_buffer if y1>90: y1=y1-360 return [x0,x1,y0,y1] ``` -------------------------------- ### Run All Tests Source: https://github.com/gplates/gplately/blob/master/tests-dir/pytestcases/TEST_FEATURE_FILTER_UNITS.md Execute all unit tests for the feature filter module from the repository root. Ensure the 'gplately' environment is activated. ```bash # Run from the repository root micromamba activate gplately python -m pytest tests-dir/pytestcases/test_8_feature_filter.py -v ``` -------------------------------- ### Import necessary Python libraries for GPlately and plotting Source: https://github.com/gplates/gplately/blob/master/Notebooks/12-MutschlerWorldPorphyryCopperDepositsRegionalPlots.ipynb Imports all required libraries for GPlately, Matplotlib, Cartopy, NumPy, Pandas, and other utilities. Ensure all dependencies, including 'cmcrameri', are installed. ```python import gplately import matplotlib.pyplot as plt import cartopy.crs as ccrs import cartopy.feature as cfeature import numpy as np import pandas as pd import os import gplately.tools as tools import matplotlib.colors as mcolors from cartopy.io import shapereader as shpreader import netCDF4 import warnings from scipy import ndimage import glob from rasterio.features import rasterize from rasterio.transform import from_bounds import matplotlib.gridspec as gridspec import matplotlib import pandas as pd # Need joblib to run the script on multiple cores, and moviepy to make the movies from joblib import Parallel, delayed import joblib import moviepy.editor as mpy # Plotting dependencies from cmcrameri import cm import cartopy.mpl.ticker as cticker import matplotlib.ticker as mticker ``` -------------------------------- ### Initialize Points Object for Tracking Source: https://github.com/gplates/gplately/blob/master/sphinx-doc/source/use_cases.md Create a Points object to track the motion of specific geographic points through geologic time. Requires a pre-configured plate reconstruction model and point coordinates. ```python import numpy as np from gplately import Points, auxiliary # Create a plate reconstruction model using a rotation model, a set of topology features and static polygons recon_model = auxiliary.get_plate_reconstruction("Muller2019") # Define some points using their latitude and longitude coordinates so we can track them through time! pt_lons = np.array([140.0, 150.0, 160.0]) pt_lats = np.array([-30.0, -40.0, -50.0]) # Create a Points object from these points gpts = Points(recon_model, pt_lons, pt_lats) ``` -------------------------------- ### Get Continent Polygon Coordinates Source: https://github.com/gplates/gplately/blob/master/Notebooks/13-ReconstructingZirconData.ipynb Obtains latitude and longitude coordinates of continents at the current reconstruction time by rasterizing continent polygons. Assumes 0.2 degree resolution by default. ```python def get_continent_polygon_coordinates(continent_polygons, resX=0.2, resY=0.2): """ Obtains the latitude and longitude coordinates of continents at the current reconstruction time. Assumes 0.2 degree resolution by default """ nx, ny = int(360/resX), int(180/resY) platforms_grid = rasterize(gplately.geometry.pygplates_to_shapely(continent_polygons), out_shape=(ny,nx), transform=from_bounds(-180, 90, 180, -90, nx, ny)) xq, yq = np.meshgrid(np.linspace(-180,180,nx), np.linspace(-90, 90, ny)) mask_grid = platforms_grid > 0 xcoords = xq[mask_grid] ycoords = yq[mask_grid] return xcoords, ycoords ``` -------------------------------- ### Set Grid Resolution and Initial Conditions Source: https://github.com/gplates/gplately/blob/master/Notebooks/10-SeafloorGrids.ipynb Configure parameters for interpolating data onto regular grids and defining initial conditions at `max_time`. `refinement_levels` controls the mesh density, `initial_ocean_mean_spreading_rate` sets a uniform spreading rate, and `grid_spacing` defines the resolution of the output grids. ```python refinement_levels = 6 initial_ocean_mean_spreading_rate = 50. # Gridding parameter grid_spacing = 0.25 extent=[-180,180,-90,90] ``` -------------------------------- ### Save Reconstructed Geometries to Shapefiles Source: https://github.com/gplates/gplately/blob/master/Notebooks/Examples/save_reconstructed_data.ipynb Use the `.to_file()` method on GeoDataFrame objects obtained from `gplot.get_continents()`, `gplot.get_coastlines()`, and `gplot.get_topological_plate_boundaries()` to save them as shapefiles. Ensure you have the necessary libraries installed for shapefile writing. ```python from gplately import auxiliary # use the auxiliary function to create a PlotTopologies instance gplot = auxiliary.get_gplot("Muller2019", time=100) # 100Ma # save the reconstructed geometries to shapefiles gplot.get_continents().to_file("continents_100Ma.shp") gplot.get_coastlines().to_file("coastlines_100Ma.shp") gplot.get_topological_plate_boundaries().to_file( "topological_plate_boundaries_100Ma.shp" ) ``` -------------------------------- ### Calculate Stage Rotations with gplately rotation_tools Source: https://github.com/gplates/gplately/blob/master/gplately/commands/readme.md Calculate stage rotations between consecutive finite rotations in plate pairs. Specify the plates and an output prefix. ```bash gplately rotation_tools -p 701 0 -o stage_ -- rotations.rot ``` -------------------------------- ### Initialize PlotTopologies with Layers Source: https://github.com/gplates/gplately/blob/master/sphinx-doc/source/use_cases.md Shows how to initialize the PlotTopologies class with a plate reconstruction model and various geological layers. This is useful for visualizing reconstructed features. ```python from gplately import PlotTopologies, auxiliary model = auxiliary.get_plate_model("Muller2019") recon_model = auxiliary.get_plate_reconstruction(model) gplot = PlotTopologies( recon_model, coastlines=model.get_layer("Coastlines"), COBs=model.get_layer("COBs"), continents=model.get_layer("ContinentalPolygons"), time=55, ) ``` -------------------------------- ### Download and Prepare Raster Data Source: https://github.com/gplates/gplately/blob/master/Notebooks/09-CreatingMotionPathsAndFlowlines.ipynb Downloads ETOPO1 raster data using PresentDayRasterManager and prepares it for plotting. Resamples the raster and adjusts latitude ordering. ```python from matplotlib import image raster_manager = PresentDayRasterManager() etopo_tif_img = gplately.Raster( data=image.imread(raster_manager.get_raster("ETOPO1_tif")), plate_reconstruction=model) etopo_tif_img.resample(0.25, 0.25, inplace=True) etopo_tif_img.lats = etopo_tif_img.lats[::-1] ``` -------------------------------- ### Create Icosahedron Mesh Features Source: https://github.com/gplates/gplately/blob/master/Notebooks/14-RuleBasedGPMLProcessingPipeline.ipynb Generates an icosahedron mesh and creates a feature collection of its vertices. This is useful for creating a base set of points for spatial queries. Ensure `pygplates` is installed and `DATA_DIR` is defined. ```python from gplately.lib.icosahedron import get_mesh, xyz2lonlat # Create a feature collection for the vertices of an icosahedron mesh. # We will use this feature collection as input for searching features within a region of interest in the next step. mesh_resolution = 5 vertices_0, faces_0 = get_mesh(mesh_resolution) seen = set() mesh_feature_collection = pygplates.FeatureCollection() # type: ignore for v in vertices_0: lon, lat = xyz2lonlat(v[0], v[1], v[2]) point = f"{lon:0.2f} {lat:0.2f}" if point in seen: continue else: seen.add(point) feature = pygplates.Feature() # type: ignore feature.set_geometry(pygplates.PointOnSphere(lat, lon)) # type: ignore mesh_feature_collection.add(feature) # type: ignore mesh_feature_collection.write(f"{DATA_DIR}/icosahedron_mesh_{mesh_resolution}.gpmlz") print( f"Icosahedron mesh have been written to {DATA_DIR}/icosahedron_mesh_{mesh_resolution}.gpmlz" ) ``` -------------------------------- ### Initialize Plotting Object and Load Data Source: https://github.com/gplates/gplately/blob/master/Notebooks/01-GettingStarted.ipynb Prepares data for plotting by obtaining geological features and age grids using PlateModelManager. Initializes the PlotTopologies object, which requires the reconstruction model and optional geological layers. ```python # Obtain features for the PlotTopologies object with PlateModelManager coastlines = muller2019_model.get_layer('Coastlines') continents = muller2019_model.get_layer('ContinentalPolygons') COBs = muller2019_model.get_layer('COBs') # Call the PlotTopologies object gplot = gplately.plot.PlotTopologies(model, coastlines=coastlines, continents=continents, COBs=COBs) # Download all Muller et al. 2019 netCDF age grids with PlateModelManager. This is returned as a Raster object. agegrid = gplately.Raster(data=muller2019_model.get_raster("AgeGrids",time)) ```