### Test PySolid Installation Source: https://github.com/insarlab/pysolid/blob/main/README.md Verify that PySolid has been installed correctly by checking the version and running provided test scripts. ```bash python -c "import pysolid; print(pysolid.__version__)" python PySolid/tests/grid.py python PySolid/tests/point.py ``` -------------------------------- ### Basic CMake Project Setup Source: https://github.com/insarlab/pysolid/blob/main/CMakeLists.txt Sets the minimum CMake version and defines the project name and languages (C, Fortran). ```cmake cmake_minimum_required(VERSION 3.17.2...3.29) project(${SKBUILD_PROJECT_NAME} LANGUAGES C Fortran) ``` -------------------------------- ### Install Dependencies with Pip Source: https://github.com/insarlab/pysolid/blob/main/README.md Install PySolid dependencies using pip, assuming a Fortran compiler is already installed on the system. ```shell python -m pip install -r PySolid/requirements.txt -r PySolid/tests/requirements.txt ``` -------------------------------- ### Manual Fortran Compilation and Setup Source: https://github.com/insarlab/pysolid/blob/main/README.md Manually compile the Fortran code using f2py and set the PYTHONPATH environment variable to use PySolid from source. ```bash cd PySolid/src/pysolid f2py -c -m solid solid.for # Replace with proper path to PySolid main folder export PYTHONPATH=${PYTHONPATH}:/PySolid/src ``` -------------------------------- ### Installing the Python Module Source: https://github.com/insarlab/pysolid/blob/main/CMakeLists.txt Installs the compiled Python extension module 'solid' into the 'pysolid' directory of the Python package. ```cmake install(TARGETS solid DESTINATION pysolid) ``` -------------------------------- ### Import Libraries and Setup Source: https://github.com/insarlab/pysolid/blob/main/docs/plot_grid_SET.ipynb Imports necessary libraries for plotting, date manipulation, numerical operations, and pysolid. It also sets the working directory and display options for matplotlib. ```python %matplotlib inline import os import datetime as dt import numpy as np from cartopy import crs as ccrs, feature as cfeature from matplotlib import pyplot as plt, ticker, dates as mdates from mintpy.utils import plot as pp import pysolid plt.rcParams.update({'font.size': 12}) work_dir = os.path.expanduser('~/Downloads') os.chdir(work_dir) print('Go to directory', work_dir) ``` -------------------------------- ### Install PySolid with Pip Source: https://github.com/insarlab/pysolid/blob/main/README.md Install PySolid into the current Python environment using pip. This can be a standard installation or in editable/develop mode. ```shell # option 1: use pip to install pysolid into the current environment python -m pip install ./PySolid # option 2: use pip to install pysolid in develop mode (editable) into the current environment python -m pip install -e ./PySolid ``` -------------------------------- ### Install PySolid via Apt Source: https://github.com/insarlab/pysolid/blob/main/README.md Install PySolid using the apt package manager, typically available on Debian-derivative Linux distributions like Ubuntu. ```shell apt install python3-pysolid ``` -------------------------------- ### Install PySolid via Conda Source: https://github.com/insarlab/pysolid/blob/main/README.md Install PySolid using the conda package manager from the conda-forge channel. This is the recommended method for most users. ```shell conda install -c conda-forge pysolid ``` -------------------------------- ### Install Dependencies with Conda Source: https://github.com/insarlab/pysolid/blob/main/README.md Install PySolid dependencies, including a Fortran compiler, using conda. This can be done for an existing environment or a new one. ```shell # option 1: use conda to install dependencies into an existing, activated environment conda install -c conda-forge fortran-compiler --file PySolid/requirements.txt --file PySolid/tests/requirements.txt # option 2: use conda to install dependencies into a new environment, e.g. named "pysolid" conda create --name pysolid fortran-compiler --file PySolid/requirements.txt --file PySolid/tests/requirements.txt conda activate pysolid ``` -------------------------------- ### Getting F2PY Include Directory Source: https://github.com/insarlab/pysolid/blob/main/CMakeLists.txt Executes a Python command to find the include directory for NumPy's F2PY, necessary for compiling Fortran code with Python bindings. ```cmake execute_process( COMMAND "${PYTHON_EXECUTABLE}" -c "import numpy.f2py; print(numpy.f2py.get_include())" OUTPUT_VARIABLE F2PY_INCLUDE_DIR OUTPUT_STRIP_TRAILING_WHITESPACE) ``` -------------------------------- ### Calculate Solid Earth Tides for a Point Source: https://github.com/insarlab/pysolid/blob/main/docs/plot_point_SET.ipynb Calculates the solid Earth tides (east, north, and up components) for a specified point (latitude, longitude) and time range. Requires defining the start and end datetimes and the time step in seconds. ```python # inputs lat, lon = 34.0, -118.0 # Los Angles, CA step_sec = 60 * 10 dt0 = dt.datetime(2001,1,1,4,0,0) #dt0 = dt.datetime(2020,1,1,4,0,0) dt1 = dt.datetime(2021,1,1,2,0,0) # run dt_out, tide_e, tide_n, tide_u = pysolid.calc_solid_earth_tides_point( lat, lon, dt0, dt1, step_sec=step_sec, display=False, verbose=False, ) ``` -------------------------------- ### Import Libraries and Set Up Environment Source: https://github.com/insarlab/pysolid/blob/main/docs/plot_point_SET.ipynb Imports necessary libraries for data manipulation, plotting, and tide calculations. Sets the working directory to the user's Downloads folder. ```python %matplotlib inline import os import datetime as dt import numpy as np from scipy import signal from matplotlib import pyplot as plt, ticker, dates as mdates import pysolid plt.rcParams.update({'font.size': 12}) work_dir = os.path.expanduser('~/Downloads') os.chdir(work_dir) print('Go to directory', work_dir) ``` -------------------------------- ### Import PySolid Library Source: https://github.com/insarlab/pysolid/blob/main/README.md Import the necessary libraries, datetime and pysolid, to begin using PySolid for tide calculations. ```python import datetime as dt import pysolid ``` -------------------------------- ### Generating F2PY Wrappers Source: https://github.com/insarlab/pysolid/blob/main/CMakeLists.txt Uses a custom command to generate C source and Fortran wrapper files from the main Fortran source file using numpy.f2py. ```cmake add_custom_command( OUTPUT solidmodule.c solid-f2pywrappers.f DEPENDS src/pysolid/solid.for VERBATIM COMMAND "${Python_EXECUTABLE}" -m numpy.f2py "${CMAKE_CURRENT_SOURCE_DIR}/src/pysolid/solid.for" -m solid --lower) ``` -------------------------------- ### Building Fortran Object Library Source: https://github.com/insarlab/pysolid/blob/main/CMakeLists.txt Creates an object library for Fortran code, linking it with NumPy and setting include directories. Ensures position-independent code. ```cmake add_library(fortranobject OBJECT "${F2PY_INCLUDE_DIR}/fortranobject.c") target_link_libraries(fortranobject PUBLIC Python::NumPy) target_include_directories(fortranobject PUBLIC "${F2PY_INCLUDE_DIR}") set_property(TARGET fortranobject PROPERTY POSITION_INDEPENDENT_CODE ON) ``` -------------------------------- ### Create Conda Environments for Python Versions Source: https://github.com/insarlab/pysolid/wiki/Home Creates and configures conda environments for different Python versions (3.6-3.9) to build C extensions. Uses a specific conda.txt file for maximum compatibility. ```bash cd ~/tools/PySolid/pysolid conda create --name test36 --yes; conda activate test36; conda install python=3.6 --file ../test/conda.txt --yes; conda deactivate conda create --name test37 --yes; conda activate test37; conda install python=3.7 --file ../test/conda.txt --yes; conda deactivate conda create --name test38 --yes; conda activate test38; conda install python=3.8 --file ../test/conda.txt --yes; conda deactivate conda create --name test39 --yes; conda activate test39; conda install python=3.9 --file ../test/conda39.txt --yes; conda deactivate ``` -------------------------------- ### Clone PySolid Source Code Source: https://github.com/insarlab/pysolid/blob/main/README.md Download the PySolid source code from the GitHub repository. This is the first step for building from source. ```bash git clone https://github.com/insarlab/PySolid.git ``` -------------------------------- ### Creating Python Extension Module Source: https://github.com/insarlab/pysolid/blob/main/CMakeLists.txt Adds a Python module named 'solid' using the generated C and Fortran files, linking it with the Fortran object library. ```cmake python_add_library( solid MODULE "${CMAKE_CURRENT_BINARY_DIR}/solidmodule.c" "${CMAKE_CURRENT_BINARY_DIR}/solid-f2pywrappers.f" "${CMAKE_CURRENT_SOURCE_DIR}/src/pysolid/solid.for" WITH_SOABI) target_link_libraries(solid PRIVATE fortranobject) ``` -------------------------------- ### Compile C Extensions with f2py for Supported Python Versions Source: https://github.com/insarlab/pysolid/wiki/Home Compiles the solid.for module using f2py within activated conda environments for Python 3.6 through 3.9. Includes running a test script after compilation. ```bash cd ~/tools/PySolid/pysolid conda activate test36; f2py -c -m solid solid.for; ./../test/test.py; conda deactivate conda activate test37; f2py -c -m solid solid.for; ./../test/test.py; conda deactivate conda activate test38; f2py -c -m solid solid.for; ./../test/test.py; conda deactivate conda activate test39; f2py -c -m solid solid.for; ./../test/test.py; conda deactivate ``` -------------------------------- ### Project Tides onto Satellite Line-of-Sight (LOS) Source: https://github.com/insarlab/pysolid/blob/main/README.md Projects the calculated East-North-Up (ENU) solid earth tides onto a satellite's line-of-sight (LOS) direction. Requires incidence and azimuth angles of the LOS vector, typically for satellite radar data. ```python # project SET from ENU to satellite line-of-sight (LOS) direction with positive for motion towards the satellite # inc_angle : incidence angle of the LOS vector (from ground to radar platform) measured from vertical. # az_angle : azimuth angle of the LOS vector (from ground to radar platform) measured from the north, with anti-clockwirse as positive. inc_angle = np.deg2rad(34) # radian, typical value for Sentinel-1 az_angle = np.deg2rad(-102) # radian, typical value for Sentinel-1 descending track tide_los = ( tide_e * np.sin(inc_angle) * np.sin(az_angle) * -1 + tide_n * np.sin(inc_angle) * np.cos(az_angle) + tide_u * np.cos(inc_angle)) ``` -------------------------------- ### Calculate Solid Earth Tides for a Grid Source: https://github.com/insarlab/pysolid/blob/main/README.md Computes solid earth tides for a grid of points defined by metadata. Requires a datetime object and a dictionary containing grid parameters like dimensions, origin, and resolution. ```python import datetime as dt import numpy as np import pysolid # prepare inputs dt_obj = dt.datetime(2020, 12, 25, 14, 7, 44) meta = { 'LENGTH' : 500, # number of rows 'WIDTH' : 450, # number of columns 'X_FIRST': -126, # min longitude in degree (upper left corner of the upper left pixel) 'Y_FIRST': 43, # max laitude in degree (upper left corner of the upper left pixel) 'X_STEP' : 0.000925926 * 30, # output resolution in degree 'Y_STEP' : -0.000925926 * 30, # output resolution in degree } # compute SET via pysolid tide_e, tide_n, tide_u = pysolid.calc_solid_earth_tides_grid( dt_obj, meta, display=False, verbose=True, ) ``` -------------------------------- ### Plot Power Spectral Density of Vertical Displacement Source: https://github.com/insarlab/pysolid/blob/main/docs/plot_point_SET.ipynb Calculates and plots the power spectral density (PSD) of the vertical component of solid Earth tides. This helps identify dominant tidal periods. The plot is configured to show semi-diurnal and diurnal periods separately and annotates them. ```python ## calc PSD freq, psd = signal.periodogram(tide_u, fs=1/step_sec, scaling='density') # get rid of zero in the first element psd = psd[1:] freq = freq[1:] period = 1./3600./freq # period (hour) ## plot fig, axs = plt.subplots(nrows=1, ncols=2, figsize=[8,3], sharey=True) for ax in axs: ax.plot(period, psd, '.', ms=16, mfc='none', mew=2) # axis format for ax in axs: ax.tick_params(which='both', direction='out', bottom=True, top=True, left=True, right=True) ax.xaxis.set_minor_locator(ticker.AutoMinorLocator()) ax.set_xlabel('Period [hour]') axs[0].set_xlim(11.3, 13.2) axs[1].set_xlim(22.0, 28.0) ax = axs[0] ax.set_ylabel('Power Spectral Density\n'+r'[$m^2/Hz$]') ax.set_ylim(0, ymax=axs[0].get_ylim()[1] * 1.1) #plt.yscale('log') #ax.yaxis.set_major_locator(ticker.FixedLocator([0,50e3,100e3,150e3])) #ax.set_yticklabels(['0','50k','100k','150k']) fig.tight_layout() # Tidal constituents for ax in axs: pysolid.point.add_tidal_constituents(ax, period, psd, min_psd=0.02e6) axs[0].annotate('semi-diurnal', xy=(0.05,0.85), xycoords='axes fraction') axs[1].annotate('diurnal', xy=(0.05,0.85), xycoords='axes fraction') # output out_fig = 'SET_PSD.png' if out_fig: print('save figure to file:', os.path.abspath(out_fig)) fig.savefig(out_fig, bbox_inches='tight', transparent=True, dpi=600) plt.show() ``` -------------------------------- ### Finding Python and NumPy Source: https://github.com/insarlab/pysolid/blob/main/CMakeLists.txt Locates the Python interpreter and development components, including NumPy, which is required for F2PY. ```cmake find_package( Python COMPONENTS Interpreter Development.Module NumPy REQUIRED) ``` -------------------------------- ### Plot Power Spectral Density in Days Source: https://github.com/insarlab/pysolid/blob/main/docs/plot_point_SET.ipynb Plots the power spectral density (PSD) with the x-axis representing period in days, ranging from 50 to 450 days. This plot uses a logarithmic scale for the y-axis to visualize variations across a broader range of long-period phenomena. ```python # get period in days period = 1./(3600.*24.)/freq # period (hour) fig, ax = plt.subplots(nrows=1, ncols=1, figsize=[4,3], sharey=True) ax.plot(period, psd, '.', ms=16, mfc='none', mew=2) # axis format ax.tick_params(which='both', direction='out', bottom=True, top=True, left=True, right=True) ax.xaxis.set_minor_locator(ticker.AutoMinorLocator()) ax.set_xlabel('Period [day]') ax.set_xlim(50, 450) ax.set_ylabel('Power Spectral Density\n'+r'[$m^2/Hz$]') plt.yscale('log') fig.tight_layout() ``` -------------------------------- ### Calculate Solid Earth Tides Source: https://github.com/insarlab/pysolid/blob/main/docs/plot_grid_SET.ipynb Defines input parameters for a geographical grid and calculates solid Earth tides (East, North, Up) using pysolid. It then projects these tidal displacements onto a radar line-of-sight (LOS) vector. ```python ## inputs dt_obj = dt.datetime(2020, 12, 25, 14, 7, 44) atr = { 'LENGTH' : 500, # number of rows 'WIDTH' : 450, # number of columns 'X_FIRST': -126, # min longitude in degree (upper left corner of the upper left pixel) 'Y_FIRST': 43, # max laitude in degree (upper left corner of the upper left pixel) 'X_STEP' : 0.000925926 * 30, # output resolution in degree 'Y_STEP' : -0.000925926 * 30, # output resolution in degree } ## call tide_e, tide_n, tide_u = pysolid.calc_solid_earth_tides_grid( dt_obj, atr, display=False, verbose=True, ) ## project ENU to radar line-of-sight (LOS) with positive for motion towards satellite inc_angle = np.deg2rad(34) # radian, typical value for Sentinel-1 az_angle = np.deg2rad(-102) # radian, typical value for Sentinel-1 descending track tide_los = ( tide_e * np.sin(inc_angle) * np.sin(az_angle) * -1 + tide_n * np.sin(inc_angle) * np.cos(az_angle) + tide_u * np.cos(inc_angle)) ``` -------------------------------- ### Plot Short Period Range of Power Spectral Density Source: https://github.com/insarlab/pysolid/blob/main/docs/plot_point_SET.ipynb Plots the power spectral density (PSD) focusing on a shorter period range (7.8 to 8.7 hours) on a logarithmic scale. This is useful for examining specific high-frequency components. ```python fig, ax = plt.subplots(nrows=1, ncols=1, figsize=[4,3], sharey=True) ax.plot(period, psd, '.', ms=16, mfc='none', mew=2) # axis format ax.tick_params(which='both', direction='out', bottom=True, top=True, left=True, right=True) ax.xaxis.set_minor_locator(ticker.AutoMinorLocator()) ax.set_xlabel('Period [hour]') ax.set_xlim(7.8, 8.7) ax.set_ylabel('Power Spectral Density\n'+r'[$m^2/Hz$]') plt.yscale('log') fig.tight_layout() # output out_fig = 'SET_PSD_short.png' if out_fig: print('save figure to file:', os.path.abspath(out_fig)) fig.savefig(out_fig, bbox_inches='tight', transparent=True, dpi=600) plt.show() ``` -------------------------------- ### Plot Time-Series of Vertical Displacement Source: https://github.com/insarlab/pysolid/blob/main/docs/plot_point_SET.ipynb Generates a time-series plot of the vertical component of solid Earth tides. Converts displacement to centimeters and formats the x-axis for date display. The plot is limited to a specific date range for clarity. ```python # plot fig, ax = plt.subplots(nrows=1, ncols=1, figsize=[12, 3]) ax.plot(dt_out, tide_u*100, lw=1.5) # axis format ax.tick_params(which='both', direction='out', bottom=True, top=False, left=True, right=True) ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) ax.xaxis.set_major_locator(mdates.MonthLocator()) ax.xaxis.set_minor_locator(mdates.DayLocator()) ax.set_ylabel('Displacement Up [cm]') ax.set_title(r'solid Earth tides at Los Angeles (N34$^circ$, E-118$^circ$)') ax.set_xlim(dt.datetime(2020,8,27), dt.datetime(2020,12,5)) fig.tight_layout() # output out_fig = 'SET_TS_Up.png' print('save figure to file:', out_fig) #fig.savefig(out_fig, bbox_inches='tight', transparent=True, dpi=600) plt.show() ``` -------------------------------- ### Plotting Tidal Displacements Source: https://github.com/insarlab/pysolid/blob/main/docs/plot_grid_SET.ipynb Generates a plot visualizing the calculated tidal displacements (East, North, Up, and LOS) on a map. It configures map axes, adds coastlines and political boundaries, and includes color bars for each displacement component. ```python # plot fig, axs = plt.subplots(nrows=1, ncols=4, figsize=[9, 5], sharex=True, sharey=True, subplot_kw=dict(projection=ccrs.PlateCarree())) N = float(atr['Y_FIRST']) W = float(atr['X_FIRST']) S = N + float(atr['Y_STEP']) * int(atr['LENGTH']) E = W + float(atr['X_STEP']) * int(atr['WIDTH']) kwargs = dict(cmap='RdBu', origin='upper', extent=(W,E,S,N), interpolation='nearest') tides = [tide_e, tide_n, tide_u, tide_los] labels = ['East [cm]', 'North [cm]', 'Up [cm]', 'Line-of-Sight [cm]'] lalo_locs = [[1,0,0,1], [0,0,0,1], [0,0,0,1], [0,0,0,1]] # left, right, top, bottom for i in range(len(tides)): ax = axs[i] im = ax.imshow(tides[i]*100, **kwargs) # axis format ax.tick_params(which='both', direction='in', bottom=True, top=True, left=True, right=True) ax.coastlines(resolution='10m') states_provinces = cfeature.NaturalEarthFeature( category='cultural', name='admin_1_states_provinces_lines', scale='10m', facecolor='none') ax.add_feature(cfeature.LAND) ax.add_feature(cfeature.COASTLINE) ax.add_feature(states_provinces, edgecolor='k', linewidth=0.5) pp.draw_lalo_label(geo_box=(W,N,E,S), ax=ax, projection=ccrs.PlateCarree(), lalo_loc=lalo_locs[i], lalo_step=10) fig.colorbar(im, ax=ax, orientation='horizontal', label=labels[i], pad=0.07, ticks=ticker.MaxNLocator(3)) fig.suptitle('solid Earth tides at {}'.format(dt_obj.isoformat()), y=0.7) fig.tight_layout() # output out_fig = 'SET_grid.png' print('save figure to file:', out_fig) #fig.savefig(out_fig, bbox_inches='tight', transparent=True, dpi=600) plt.show() ``` -------------------------------- ### Save Plot to File Source: https://github.com/insarlab/pysolid/blob/main/docs/plot_point_SET.ipynb Saves the current figure to a specified file. Use when you need to export plots for reports or further processing. Requires `os` and `matplotlib.pyplot` to be imported. ```python out_fig = 'SET_PSD_long.png' if out_fig: print('save figure to file:', os.path.abspath(out_fig)) fig.savefig(out_fig, bbox_inches='tight', transparent=True, dpi=600) plt.show() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.