├── pyfmm ├── _version.py ├── __init__.py ├── C_extension │ ├── include │ │ ├── query.h │ │ ├── progressbar.h │ │ ├── coord.h │ │ ├── const.h │ │ ├── index.h │ │ ├── mallocfree.h │ │ ├── diff.h │ │ ├── interp.h │ │ ├── fsm.h │ │ ├── heapsort.h │ │ └── fmm.h │ ├── src │ │ ├── progressbar.c │ │ ├── query.c │ │ ├── diff.c │ │ ├── mallocfree.c │ │ ├── heapsort.c │ │ ├── interp.c │ │ ├── fsm.c │ │ └── fmm.c │ └── Makefile ├── logger.py ├── c_interfaces.py └── traveltime.py ├── MANIFEST.in ├── docs ├── compile.sh ├── source │ ├── _static │ │ └── my_theme.css │ ├── API │ │ ├── C_extension │ │ │ └── include │ │ │ │ ├── fmm.rst │ │ │ │ ├── fsm.rst │ │ │ │ ├── const.rst │ │ │ │ ├── coord.rst │ │ │ │ ├── diff.rst │ │ │ │ ├── index.rst │ │ │ │ ├── query.rst │ │ │ │ ├── interp.rst │ │ │ │ ├── heapsort.rst │ │ │ │ └── mallocfree.rst │ │ ├── pyfmm │ │ │ ├── logger.rst │ │ │ ├── traveltime.rst │ │ │ └── c_interfaces.rst │ │ ├── pyfmm_api.rst │ │ └── h_pyfmm_api.rst │ ├── jupyter_examples.rst │ ├── install.rst │ ├── about_FSM.rst │ ├── conf.py │ ├── index.rst │ └── _templates │ │ └── footer.html ├── requirements.txt ├── Makefile └── doxyfile_h ├── figs ├── example.png ├── output.png ├── output2.png └── output3.png ├── pyproject.toml ├── .gitignore ├── .github ├── tests │ └── uniform.py └── workflows │ ├── testbuild.yml │ └── build.yml ├── .readthedocs.yaml ├── setup.py ├── README.md └── LICENSE /pyfmm/_version.py: -------------------------------------------------------------------------------- 1 | __version__ = "0.5.0" 2 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | recursive-include pyfmm/C_extension * -------------------------------------------------------------------------------- /docs/compile.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | make clean && doxygen doxyfile_h && make html -------------------------------------------------------------------------------- /docs/source/_static/my_theme.css: -------------------------------------------------------------------------------- 1 | .wy-nav-content { 2 | max-width: 800px; 3 | } -------------------------------------------------------------------------------- /figs/example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dengda98/PyFMM/HEAD/figs/example.png -------------------------------------------------------------------------------- /figs/output.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dengda98/PyFMM/HEAD/figs/output.png -------------------------------------------------------------------------------- /figs/output2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dengda98/PyFMM/HEAD/figs/output2.png -------------------------------------------------------------------------------- /figs/output3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dengda98/PyFMM/HEAD/figs/output3.png -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | 2 | [build-system] 3 | requires = ["setuptools>=42", "wheel"] 4 | build-backend = "setuptools.build_meta" 5 | -------------------------------------------------------------------------------- /docs/source/API/C_extension/include/fmm.rst: -------------------------------------------------------------------------------- 1 | fmm.h 2 | -------------------------- 3 | 4 | .. doxygenfile:: fmm.h 5 | :project: h_PyFMM -------------------------------------------------------------------------------- /docs/source/API/C_extension/include/fsm.rst: -------------------------------------------------------------------------------- 1 | fsm.h 2 | -------------------------- 3 | 4 | .. doxygenfile:: fsm.h 5 | :project: h_PyFMM -------------------------------------------------------------------------------- /docs/source/API/C_extension/include/const.rst: -------------------------------------------------------------------------------- 1 | const.h 2 | -------------------------- 3 | 4 | .. doxygenfile:: const.h 5 | :project: h_PyFMM -------------------------------------------------------------------------------- /docs/source/API/C_extension/include/coord.rst: -------------------------------------------------------------------------------- 1 | coord.h 2 | -------------------------- 3 | 4 | .. doxygenfile:: coord.h 5 | :project: h_PyFMM -------------------------------------------------------------------------------- /docs/source/API/C_extension/include/diff.rst: -------------------------------------------------------------------------------- 1 | diff.h 2 | -------------------------- 3 | 4 | .. doxygenfile:: diff.h 5 | :project: h_PyFMM -------------------------------------------------------------------------------- /docs/source/API/C_extension/include/index.rst: -------------------------------------------------------------------------------- 1 | index.h 2 | -------------------------- 3 | 4 | .. doxygenfile:: index.h 5 | :project: h_PyFMM -------------------------------------------------------------------------------- /docs/source/API/C_extension/include/query.rst: -------------------------------------------------------------------------------- 1 | query.h 2 | -------------------------- 3 | 4 | .. doxygenfile:: query.h 5 | :project: h_PyFMM -------------------------------------------------------------------------------- /docs/source/API/C_extension/include/interp.rst: -------------------------------------------------------------------------------- 1 | interp.h 2 | -------------------------- 3 | 4 | .. doxygenfile:: interp.h 5 | :project: h_PyFMM -------------------------------------------------------------------------------- /docs/source/API/C_extension/include/heapsort.rst: -------------------------------------------------------------------------------- 1 | heapsort.h 2 | -------------------------- 3 | 4 | .. doxygenfile:: heapsort.h 5 | :project: h_PyFMM -------------------------------------------------------------------------------- /docs/source/API/C_extension/include/mallocfree.rst: -------------------------------------------------------------------------------- 1 | mallocfree.h 2 | -------------------------- 3 | 4 | .. doxygenfile:: mallocfree.h 5 | :project: h_PyFMM -------------------------------------------------------------------------------- /docs/source/API/pyfmm/logger.rst: -------------------------------------------------------------------------------- 1 | pyfmm.logger 2 | ------------------ 3 | 4 | .. automodule:: pyfmm.logger 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: -------------------------------------------------------------------------------- /docs/source/API/pyfmm/traveltime.rst: -------------------------------------------------------------------------------- 1 | pyfmm.traveltime 2 | ------------------ 3 | 4 | .. automodule:: pyfmm.traveltime 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: -------------------------------------------------------------------------------- /docs/source/API/pyfmm/c_interfaces.rst: -------------------------------------------------------------------------------- 1 | pyfmm.c_interfaces 2 | ------------------ 3 | 4 | .. automodule:: pyfmm.c_interfaces 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | /dist 3 | /.vscode 4 | /*.egg-info 5 | /docs/build 6 | /docs/doxygen_h 7 | 8 | /pyfmm/__pycache__ 9 | /pyfmm/C_extension/build 10 | /pyfmm/C_extension/lib 11 | /pyfmm/C_extension/bin 12 | /test_w -------------------------------------------------------------------------------- /docs/source/API/pyfmm_api.rst: -------------------------------------------------------------------------------- 1 | **PyFMM** package API 2 | ======================== 3 | 4 | .. toctree:: 5 | :maxdepth: 2 6 | 7 | 8 | pyfmm/_version 9 | pyfmm/traveltime 10 | pyfmm/c_interfaces 11 | pyfmm/logger -------------------------------------------------------------------------------- /pyfmm/__init__.py: -------------------------------------------------------------------------------- 1 | from .c_interfaces import load_c_lib, set_fsm_num_threads 2 | 3 | # 默认使用双精度 4 | load_c_lib(use_float=False) 5 | 6 | from . import traveltime 7 | from .traveltime import * 8 | 9 | from . import c_interfaces 10 | 11 | from . import logger 12 | from .logger import myLogger 13 | 14 | from ._version import __version__ 15 | -------------------------------------------------------------------------------- /docs/requirements.txt: -------------------------------------------------------------------------------- 1 | breathe==4.35 2 | commonmark==0.9 3 | recommonmark==0.7 4 | sphinx==7.4.7 5 | sphinx-rtd-theme==2.0.0 6 | sphinx-copybutton==0.5 7 | sphinx_markdown_tables==0.0.17 8 | sphinxcontrib-mermaid==0.9.2 9 | sphinxcontrib-htmlhelp==2.1 10 | sphinxcontrib-jsmath==1.0 11 | nbsphinx==0.9 12 | graphviz==0.20 13 | setuptools-scm==8.1 # 自动从git tag中构建版本 14 | . # 库本身 -------------------------------------------------------------------------------- /docs/source/API/h_pyfmm_api.rst: -------------------------------------------------------------------------------- 1 | C extension API 2 | =============================== 3 | 4 | 5 | .. toctree:: 6 | :maxdepth: 2 7 | 8 | C_extension/include/const 9 | C_extension/include/coord 10 | C_extension/include/diff 11 | C_extension/include/fsm 12 | C_extension/include/fmm 13 | C_extension/include/heapsort 14 | C_extension/include/index 15 | C_extension/include/interp 16 | C_extension/include/mallocfree 17 | C_extension/include/query 18 | -------------------------------------------------------------------------------- /pyfmm/C_extension/include/query.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file query.h 3 | * @author Zhu Dengda (zhudengda@mail.iggcas.ac.cn) 4 | * @date 2023-03 5 | * 6 | * 7 | * 8 | */ 9 | 10 | #pragma once 11 | 12 | #include "const.h" 13 | 14 | /** 15 | * 使用二分法查找元素,返回较小的一个 16 | * 17 | * @param arr (in)数组,要求从小到大排列 18 | * @param n (in)数组 19 | * @param target (in)待查找元素 20 | * 21 | * @return 索引值 22 | * 23 | */ 24 | MYINT dicho_find(const double *arr, MYINT n, double target); 25 | -------------------------------------------------------------------------------- /pyfmm/C_extension/include/progressbar.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file progressbar.h 3 | * @author Zhu Dengda (zhudengda@mail.iggcas.ac.cn) 4 | * @date 2024-07 5 | * 6 | * 以下代码实现进度条的输出 7 | * 8 | */ 9 | 10 | #pragma once 11 | 12 | #include "const.h" 13 | 14 | /** 15 | * 定义进度条的长度 16 | */ 17 | #define _PROGRESSBAR_WIDTH_ 45 18 | 19 | /** 20 | * 根据百分比打印进度条 21 | * 22 | * @param prefix (in)进度条前缀字符串 23 | * @param percentage (in)百分比(整数) 24 | */ 25 | void printprogressBar(const char *prefix, MYINT percentage); -------------------------------------------------------------------------------- /pyfmm/logger.py: -------------------------------------------------------------------------------- 1 | """ 2 | :file: logger.py 3 | :author: Zhu Dengda (zhudengda@mail.iggcas.ac.cn) 4 | :date: 2024-12 5 | 6 | 主要用于统一地给出WARNING 7 | 8 | """ 9 | 10 | import logging 11 | 12 | 13 | myLogger = logging.getLogger("pyfmm") 14 | '''自定义logger, 基于logging库''' 15 | 16 | myLogger.setLevel(logging.WARNING) 17 | 18 | console_handler = logging.StreamHandler() 19 | console_handler.setLevel(logging.WARNING) 20 | 21 | formatter = logging.Formatter('[%(levelname)s] %(message)s') 22 | console_handler.setFormatter(formatter) 23 | 24 | myLogger.addHandler(console_handler) -------------------------------------------------------------------------------- /docs/source/jupyter_examples.rst: -------------------------------------------------------------------------------- 1 | Jupyter 使用示例 2 | ================ 3 | 4 | :Author: Zhu Dengda 5 | :Email: zhudengda@mail.iggcas.ac.cn 6 | 7 | 8 | ----------------------------------------------------------- 9 | 10 | 以下示例的 :code:`.ipynb` 文件 可在 `链接 `_ 中下载。 11 | 更多示例有待补充。 12 | 13 | 14 | .. toctree:: 15 | :maxdepth: 2 16 | 17 | examples/01_uniform 18 | examples/01_uniform_spherical 19 | examples/02_random_model 20 | examples/02_cplxmodel_raytracing 21 | examples/03_spherical 22 | examples/03_spherical2 23 | examples/04_distance 24 | 25 | -------------------------------------------------------------------------------- /pyfmm/C_extension/include/coord.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file coord.h 3 | * @author Zhu Dengda (zhudengda@mail.iggcas.ac.cn) 4 | * @date 2023-03 5 | * 6 | */ 7 | 8 | 9 | #pragma once 10 | 11 | #include 12 | 13 | /** 14 | * 球坐标 \f$ (r,\theta,\phi) \f$ 转直角坐标 \f$ (x,y,z) \f$ 15 | * 16 | * @param r (in)坐标 \f$ r \f$ 17 | * @param t (in)坐标 \f$ \theta \f$ 18 | * @param p (in)坐标 \f$ \phi \f$ 19 | * @param x (out)坐标 \f$ x \f$ 20 | * @param y (out)坐标 \f$ y \f$ 21 | * @param z (out)坐标 \f$ z \f$ 22 | * 23 | */ 24 | void rtp2xyz(double r, double t, double p, double *x, double *y, double *z){ 25 | *x = r*sin(t)*cos(p); 26 | *y = r*sin(t)*sin(p); 27 | *z = r*cos(t); 28 | } 29 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line, and also 5 | # from the environment for the first two. 6 | SPHINXOPTS ?= 7 | SPHINXBUILD ?= sphinx-build 8 | SOURCEDIR = source 9 | BUILDDIR = build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | clean: 16 | rm $(BUILDDIR)/* -rf 17 | rm doxygen_h/* -rf 18 | 19 | .PHONY: help Makefile clean 20 | 21 | # Catch-all target: route all unknown targets to Sphinx using the new 22 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 23 | %: Makefile 24 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 25 | -------------------------------------------------------------------------------- /pyfmm/C_extension/include/const.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file const.h 3 | * @author Zhu Dengda (zhudengda@mail.iggcas.ac.cn) 4 | * @date 2023-03 5 | * 6 | */ 7 | 8 | #pragma once 9 | 10 | #define RADIUS 6371.0 ///< 地球半径 (km) 11 | #define PI 3.141592653589793 ///< \f$ \pi \f$ 12 | #define PI2 6.283185307179586 ///< \f$ 2\pi \f$ 13 | #define HALFPI 1.5707963267948966 ///< \f$ \frac{\pi}{2} \f$ 14 | #define RAD1 57.29577951308232 ///< \f$ \frac{180}{\pi} \f$ 15 | #define DEG1 0.017453292519943295 ///< \f$ \frac{\pi}{180} \f$ 16 | #define KM1DEG 111.194926644 ///< \f$ R_{e} \times \frac{\pi}{180} \f$ 17 | 18 | #ifdef USE_FLOAT 19 | typedef float MYREAL; ///< 单精度 or 双精度 20 | #else 21 | typedef double MYREAL; 22 | #endif 23 | 24 | typedef long int MYINT; ///< 长整型,以存储更大体积的网格量 -------------------------------------------------------------------------------- /pyfmm/C_extension/src/progressbar.c: -------------------------------------------------------------------------------- 1 | /** 2 | * @file progressbar.c 3 | * @author Zhu Dengda (zhudengda@mail.iggcas.ac.cn) 4 | * @date 2024-07 5 | * 6 | * 以下代码实现进度条的输出 7 | * 8 | */ 9 | 10 | #include 11 | 12 | #include "progressbar.h" 13 | 14 | 15 | void printprogressBar(const char *prefix, MYINT percentage) { 16 | printf("\r\033[K"); // 移动到行首并清空行 17 | if(prefix!=NULL) printf("%s", prefix); 18 | printf("["); 19 | MYINT pos = _PROGRESSBAR_WIDTH_ * percentage / 100; 20 | for (MYINT i = 0; i < _PROGRESSBAR_WIDTH_; ++i) { 21 | if (i < pos) printf("="); 22 | else if (i == pos) printf(">"); 23 | else printf(" "); 24 | } 25 | printf("] %d %%", percentage); 26 | if(percentage==100){ 27 | printf("\n"); 28 | } 29 | fflush(stdout); 30 | } -------------------------------------------------------------------------------- /pyfmm/C_extension/src/query.c: -------------------------------------------------------------------------------- 1 | /** 2 | * @file query.c 3 | * @author Zhu Dengda (zhudengda@mail.iggcas.ac.cn) 4 | * @date 2023-03 5 | * 6 | */ 7 | 8 | #include 9 | 10 | #include "query.h" 11 | 12 | MYINT dicho_find(const double *arr, MYINT n, double target){ 13 | MYINT left=0; 14 | MYINT right=n-1; 15 | MYINT mid=0; 16 | if(target <= arr[0]){} 17 | else if(target >= arr[right]){ 18 | left = right; 19 | } 20 | else { 21 | while(left < right){ 22 | mid = left + ((right-left) >> 1); 23 | if(arr[mid] == target){ 24 | return mid; 25 | } 26 | else if(arr[mid] < target){ 27 | left = mid + 1; 28 | } 29 | else{ 30 | right = mid; 31 | } 32 | } 33 | left -= 1; 34 | } 35 | return left; 36 | } -------------------------------------------------------------------------------- /.github/tests/uniform.py: -------------------------------------------------------------------------------- 1 | import pyfmm 2 | import numpy as np 3 | 4 | xarr = np.arange(0, 100, 0.08) 5 | yarr = np.arange(0, 50, 0.05) 6 | zarr = np.array([0.0]) # 二维情况 7 | 8 | 9 | # 慢度场 10 | slw = np.ones((len(xarr), len(yarr), len(zarr)), dtype='f') 11 | print(slw.shape) 12 | 13 | srcloc = [10, 20, 0.0] 14 | 15 | # FMM解 16 | FMMTT = pyfmm.travel_time_source( 17 | srcloc, 18 | xarr, yarr, zarr, slw) 19 | 20 | # FSM解 21 | FSMTT = pyfmm.travel_time_source( 22 | srcloc, 23 | xarr, yarr, zarr, slw, useFSM=True, FSMparallel=True) 24 | 25 | # 真实解 26 | xx, yy, zz = srcloc 27 | real_TT = np.sqrt(((xarr-xx)**2)[:,None,None] + ((yarr-yy)**2)[None,:,None] + ((zarr-zz)**2)[None,None,:]) 28 | 29 | # 误差 30 | FMM_error = np.mean(np.abs(FMMTT - real_TT)) 31 | FSM_error = np.mean(np.abs(FSMTT - real_TT)) 32 | print("FMM_error = ", FMM_error) 33 | print("FSM_error = ", FSM_error) 34 | 35 | tol = 0.1 36 | 37 | if FMM_error > tol: 38 | raise ValueError(f"FMM_error({FMM_error}) > tol({tol})") 39 | if FSM_error > tol: 40 | raise ValueError(f"FMM_error({FSM_error}) > tol({tol})") -------------------------------------------------------------------------------- /docs/doxyfile_h: -------------------------------------------------------------------------------- 1 | # 头文件配置文档 2 | 3 | # The INPUT tag is used to specify the files and/or directories that contain 4 | # documented source files. You may enter file names like "myfile.cpp" or 5 | # directories like "/usr/src/myproject". Separate the files or directories 6 | # with spaces. 7 | 8 | INPUT = ../pyfmm/C_extension/include 9 | 10 | # If the value of the INPUT tag contains directories, you can use the 11 | # FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp 12 | # and *.h) to filter out the source-files in the directories. If left 13 | # blank, Doxygen will consider all files in the directories. 14 | 15 | FILE_PATTERNS = *.h 16 | 17 | # The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) 18 | # base path where the generated documentation will be put. 19 | 20 | OUTPUT_DIRECTORY = ./doxygen_h 21 | 22 | # If the GENERATE_XML tag is set to YES Doxygen will generate an XML file 23 | # that captures the structure of the code including all documentation. 24 | 25 | GENERATE_XML = YES 26 | 27 | # Doxyfile Configuration 28 | USE_MATHJAX = YES 29 | -------------------------------------------------------------------------------- /pyfmm/C_extension/include/index.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file index.h 3 | * @author Zhu Dengda (zhudengda@mail.iggcas.ac.cn) 4 | * @date 2023-03 5 | * 6 | */ 7 | 8 | #pragma once 9 | 10 | 11 | /** 12 | * 将一维索引恢复成三维索引(内联函数) 13 | * 14 | * @param idx (in)展开后的索引 15 | * @param ntp (in)2、3维度尺寸乘积 16 | * @param np (in)第3维度尺寸 17 | * @param ir (out)第1维索引 18 | * @param it (out)第2维索引 19 | * @param ip (out)第3维索引 20 | * 21 | */ 22 | inline void unravel_index(MYINT idx, MYINT ntp, MYINT np, MYINT *ir, MYINT *it, MYINT *ip){ 23 | *ir = idx / ntp; 24 | *it = (idx - (*ir)*ntp) / np; 25 | *ip = idx % np; 26 | } 27 | 28 | 29 | /** 30 | * 将三维索引展开成一维索引(内联函数) 31 | * 32 | * @param idx (out)展开后的索引 33 | * @param ntp (in)2、3维度尺寸乘积 34 | * @param np (in)第3维度尺寸 35 | * @param ir (in)第1维索引 36 | * @param it (in)第2维索引 37 | * @param ip (in)第3维索引 38 | * 39 | */ 40 | inline void ravel_index(MYINT *idx, MYINT ntp, MYINT np, MYINT ir, MYINT it, MYINT ip){ 41 | *idx = ir*ntp + it*np + ip; 42 | } -------------------------------------------------------------------------------- /.readthedocs.yaml: -------------------------------------------------------------------------------- 1 | # Read the Docs configuration file for Sphinx projects 2 | # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details 3 | 4 | # Required 5 | version: 2 6 | 7 | # Set the OS, Python version and other tools you might need 8 | build: 9 | os: ubuntu-22.04 10 | tools: 11 | python: "3.10" 12 | # You can also specify other tool versions: 13 | # nodejs: "20" 14 | # rust: "1.70" 15 | # golang: "1.20" 16 | 17 | apt_packages: ["doxygen"] 18 | 19 | 20 | # Build documentation in the "docs/" directory with Sphinx 21 | sphinx: 22 | configuration: docs/source/conf.py 23 | # You can configure Sphinx to use a different builder, for instance use the dirhtml builder for simpler URLs 24 | # builder: "dirhtml" 25 | # Fail on all warnings to avoid broken references 26 | # fail_on_warning: true 27 | 28 | # Optionally build your docs in additional formats such as PDF and ePub 29 | # formats: 30 | # - pdf 31 | # - epub 32 | 33 | # Optional but recommended, declare the Python requirements required 34 | # to build your documentation 35 | # See https://docs.readthedocs.io/en/stable/guides/reproducible-builds.html 36 | python: 37 | install: 38 | - requirements: docs/requirements.txt 39 | 40 | 41 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | import os 3 | 4 | 5 | 6 | # 读取版本号 7 | def read_version(): 8 | version_file = os.path.join('pyfmm', '_version.py') 9 | with open(version_file) as f: 10 | exec(f.read()) 11 | return locals()['__version__'] 12 | 13 | def read_readme(): 14 | with open("README.md", encoding="utf-8") as f: 15 | return f.read() 16 | 17 | setup( 18 | name='pyfmm-kit', 19 | version=read_version(), 20 | description='A C/Python package for solving eikonal equation using Fast Marching/Sweeping Method', 21 | author='Zhu Dengda', 22 | author_email='zhudengda@mail.iggcas.ac.cn', 23 | long_description=read_readme(), 24 | long_description_content_type="text/markdown", 25 | url="https://github.com/Dengda98/PyFMM", 26 | project_urls={ 27 | "Documentation": "https://pyfmm.readthedocs.io/zh-cn/latest/", 28 | "Source Code": "https://github.com/Dengda98/PyFMM", 29 | }, 30 | 31 | packages=find_packages(), 32 | package_data={'pyfmm': ['./C_extension/*']}, 33 | include_package_data=True, 34 | install_requires=[ 35 | 'numpy>=1.20, <2.0', 36 | 'scipy>=1.10', 37 | 'matplotlib>=3.5', 38 | 'jupyter', 39 | ], 40 | python_requires='>=3.6', 41 | zip_safe=False, # not compress the binary file 42 | ) 43 | -------------------------------------------------------------------------------- /pyfmm/C_extension/include/mallocfree.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file mallocfree.h 3 | * @author Zhu Dengda (zhudengda@mail.iggcas.ac.cn) 4 | * @date 2023-03 5 | * 6 | */ 7 | 8 | 9 | #pragma once 10 | 11 | #include 12 | 13 | #include "const.h" 14 | 15 | /** 16 | * 申请三维指针内存空间 17 | * 18 | * @param n1 (in)第一维尺寸 19 | * @param n2 (in)第二维尺寸 20 | * @param n3 (in)第三维尺寸 21 | * @param size (in)每个元素字节数 22 | * 23 | * @return 三维指针 24 | * 25 | */ 26 | void *** malloc3d(MYINT n1, MYINT n2, MYINT n3, size_t size); 27 | 28 | 29 | /** 30 | * 申请二维指针内存空间 31 | * 32 | * @param n1 (in)第一维尺寸 33 | * @param n2 (in)第二维尺寸 34 | * @param size (in)每个元素字节数 35 | * 36 | * @return 二维指针 37 | * 38 | */ 39 | void ** malloc2d(MYINT n1, MYINT n2, size_t size); 40 | 41 | 42 | 43 | /** 44 | * 申请一维指针内存空间 45 | * 46 | * @param n (in)第一维尺寸 47 | * @param size (in)每个元素字节数 48 | * 49 | * @return 一维指针 50 | * 51 | */ 52 | void * malloc1d(MYINT n, size_t size); 53 | 54 | 55 | /** 56 | * 释放三维指针内存空间 57 | * 58 | * @param arr (in)三维指针 59 | * @param n1 (in)第一维尺寸 60 | * @param n2 (in)第二维尺寸 61 | * 62 | */ 63 | void free3d(void ***arr, MYINT n1, MYINT n2); 64 | 65 | 66 | /** 67 | * 释放二维指针内存空间 68 | * 69 | * @param arr (in)二维指针 70 | * @param n1 (in)第一维尺寸 71 | * 72 | */ 73 | void free2d(void **arr, MYINT n1); 74 | 75 | 76 | 77 | 78 | -------------------------------------------------------------------------------- /docs/source/install.rst: -------------------------------------------------------------------------------- 1 | 2 | 安装 3 | ============= 4 | 5 | :Author: Zhu Dengda 6 | :Email: zhudengda@mail.iggcas.ac.cn 7 | 8 | ----------------------------------------------------------- 9 | 10 | 11 | 从当前本版本起, **PyFMM** 提供多平台预编译版本的安装包,无需再进行本地编译。 12 | 13 | 支持操作系统: 14 | 15 | .. raw:: html 16 | 17 | Linux
18 | macOS
19 | Windows
20 | 21 | \ 22 | 23 | 24 | 依赖库包括: 25 | 26 | :: 27 | 28 | python >= 3.9 29 | numpy >= 1.20, < 2.0 30 | scipy >= 1.10 31 | matplotlib >= 3.5 32 | jupyter 33 | 34 | 35 | 36 | 程序下载和安装 37 | -------------- 38 | 39 | 40 | 由于以上涉及的库均为常用库,如果你对上述依赖库很熟悉,并且了解Python库的安装以及虚拟环境的使用,\ 41 | 则可根据自己Python环境的情况快速安装,直接到 :ref:`第2步 ` 。 42 | 43 | 44 | 如果你还不了解Python库的安装以及虚拟环境的搭建,可以先在网上寻找相关教程。这里以 `Anaconda `_\ 45 | 为例,搭建虚拟环境,完成Python库的安装。 46 | 47 | 48 | 环境创建 49 | ~~~~~~~~~~ 50 | 51 | 新建虚拟环境,命名为py310,安装python=3.10 52 | :: 53 | 54 | conda create -n py310 python=3.10 55 | 56 | 激活虚拟环境 57 | :: 58 | 59 | conda activate py310 60 | 61 | .. _install_step_2: 62 | 63 | 下载和安装 **PyFMM** 64 | ~~~~~~~~~~~~~~~~~~~~~ 65 | 66 | Make Life Easier,可直接运行pip进行安装: 67 | 68 | :: 69 | 70 | pip install pyfmm-kit 71 | 72 | 73 | 74 | 关于一些安装问题 75 | ^^^^^^^^^^^^^^^^^^ 76 | 77 | + Q: Python中运行 :code:`import pyfmm` 提示找不到库路径或缺少库依赖? 78 | 79 | A: 这一般出现在Mac和Ubuntu系统上,很可能是找不到 :code:`OpenMP` 库,尝试重新安装 :code:`gcc`。 -------------------------------------------------------------------------------- /pyfmm/C_extension/include/diff.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file diff.h 3 | * @author Zhu Dengda (zhudengda@mail.iggcas.ac.cn) 4 | * @date 2023-03 5 | * 6 | */ 7 | 8 | #pragma once 9 | 10 | #include "const.h" 11 | 12 | 13 | /** 14 | * 一阶差分, \f$ \frac{T-T_{i-1}}{h} \f$ , 形成 \f$ aT-b \f$ 的形式 15 | * 16 | * @param pt (in)数组 17 | * @param h (in)差分间隔 18 | * @param acoef (out)系数结果a 19 | * @param bcoef (out)系数结果b 20 | * @param diff (out) \f$ aT-b \f$ 值 21 | */ 22 | void get_diff_odr1(const MYREAL *pt, double h, double *acoef, double *bcoef, double *diff); 23 | 24 | 25 | /** 26 | * 二阶差分, \f$ \frac{3T - 4T_{i-1} + T_{i-2}}{2h} \f$ , 形成 \f$ aT-b \f$ 的形式 27 | * 28 | * @param pt (in)数组 29 | * @param h (in)差分间隔 30 | * @param acoef (out)系数结果a 31 | * @param bcoef (out)系数结果b 32 | * @param diff (out) \f$ aT-b \f$ 值 33 | */ 34 | void get_diff_odr2(const MYREAL *pt, double h, double *acoef, double *bcoef, double *diff); 35 | 36 | 37 | /** 38 | * 三阶差分, \f$ \frac{11T - 18T_{i-1} + 9T_{i-2} - 2T_{i-3}}{6h} \f$ , 形成 \f$ aT-b \f$ 的形式 39 | * 40 | * @param pt (in)数组 41 | * @param h (in)差分间隔 42 | * @param acoef (out)系数结果a 43 | * @param bcoef (out)系数结果b 44 | * @param diff (out) \f$ aT-b \f$ 值 45 | */ 46 | void get_diff_odr3(const MYREAL *pt, double h, double *acoef, double *bcoef, double *diff); 47 | 48 | 49 | /** 50 | * 计算一 or 二 or 三阶差分 , 形成 \f$ aT-b \f$ 的形式 51 | * 52 | * @param odr (in)阶数,1or2or3 53 | * @param pt (in)数组 54 | * @param h (in)差分间隔 55 | * @param acoef (out)系数结果a 56 | * @param bcoef (out)系数结果b 57 | * @param diff (out) \f$ aT-b \f$ 值 58 | */ 59 | void get_diff_odr123(MYINT odr, const MYREAL *pt, double h, double *acoef, double *bcoef, double *diff); -------------------------------------------------------------------------------- /pyfmm/C_extension/src/diff.c: -------------------------------------------------------------------------------- 1 | /** 2 | * @file diff.c 3 | * @author Zhu Dengda (zhudengda@mail.iggcas.ac.cn) 4 | * @date 2023-03 5 | * 6 | */ 7 | 8 | 9 | #include 10 | #include 11 | 12 | #include "const.h" 13 | #include "diff.h" 14 | 15 | 16 | 17 | void get_diff_odr1(const MYREAL *pt, double h, double *acoef, double *bcoef, double *diff){ 18 | MYREAL a = 1.0/h; 19 | MYREAL b = pt[1]/h; 20 | if(acoef!=NULL) *acoef = a; 21 | if(bcoef!=NULL) *bcoef = b; 22 | if(diff!=NULL) *diff = a*pt[0] - b; 23 | } 24 | 25 | 26 | void get_diff_odr2(const MYREAL *pt, double h, double *acoef, double *bcoef, double *diff){ 27 | MYREAL a = 3.0/(2.0*h); 28 | MYREAL b = (4.0*pt[1] - pt[2])/(2.0*h); 29 | if(acoef!=NULL) *acoef = a; 30 | if(bcoef!=NULL) *bcoef = b; 31 | if(diff!=NULL) *diff = a*pt[0] - b; 32 | } 33 | 34 | 35 | void get_diff_odr3(const MYREAL *pt, double h, double *acoef, double *bcoef, double *diff){ 36 | MYREAL a = 11.0/(6.0*h); 37 | MYREAL b = (18.0*pt[1] - 9.0*pt[2] + 2.0*pt[3])/(6.0*h); 38 | if(acoef!=NULL) *acoef = a; 39 | if(bcoef!=NULL) *bcoef = b; 40 | if(diff!=NULL) *diff = a*pt[0] - b; 41 | } 42 | 43 | 44 | void get_diff_odr123(MYINT odr, const MYREAL *pt, double h, double *acoef, double *bcoef, double *diff){ 45 | if(odr==0){ 46 | if(acoef!=NULL) *acoef = 0.0; 47 | if(bcoef!=NULL) *bcoef = 0.0; 48 | if(diff!=NULL) *diff = 0.0; 49 | } 50 | else if(odr==1){ 51 | get_diff_odr1(pt, h, acoef, bcoef, diff); 52 | } else if(odr==2){ 53 | get_diff_odr2(pt, h, acoef, bcoef, diff); 54 | } else if(odr==3){ 55 | get_diff_odr3(pt, h, acoef, bcoef, diff); 56 | } else { 57 | fprintf(stderr, "WRONG DIFFERENCE ORDER (%d)\n", odr); 58 | exit(EXIT_FAILURE); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /pyfmm/C_extension/src/mallocfree.c: -------------------------------------------------------------------------------- 1 | /** 2 | * @file mallocfree.c 3 | * @author Zhu Dengda (zhudengda@mail.iggcas.ac.cn) 4 | * @date 2023-03 5 | * 6 | */ 7 | 8 | 9 | #include 10 | #include 11 | #include 12 | 13 | #include "mallocfree.h" 14 | 15 | void *** malloc3d(MYINT n1, MYINT n2, MYINT n3, size_t size){ 16 | void ***pt; 17 | if((pt = (void ***)malloc(n1*sizeof(void**))) == NULL){ 18 | fprintf(stderr, "malloc3d out of memory\n"); 19 | exit(EXIT_FAILURE); 20 | }; 21 | for(MYINT i=0; i`, 11 | **PyFMM** 使用的并行方法详见 :ref:`(Zhao, 2007) ` 中2.1节。并行实现基于 :code:`OpenMP`。 12 | 13 | 14 | 参数简介 15 | ------------ 16 | 17 | 主要使用的函数都在 :class:`pyfmm.traveltime ` 模块中, 18 | 其中函数参数和 **FSM** 相关的包括: 19 | 20 | + :code:`useFSM` (Bool) (default: False) 21 | 22 | 是否使用 **FSM** 计算全局走时场。这将决定以下相关的参数是否起作用。 23 | 24 | + :code:`FSMmaxLoops` (int) (default: 1) 25 | 26 | 最大迭代次数。对于3D模型,一次迭代包括向8个方向扫描(Sweep)。根据 27 | :ref:`(Zhao, 2004) ` 的测试,速度缓和变化的情况下, 28 | 一次迭代即可达到很好的精度,但对于速度剧烈变化的情况,需要一次以上的迭代来收敛。 29 | 30 | + :code:`FSMparallel` (bool) (default: False) 31 | 32 | 是否使用 **并行FSM**。并行方法详见 :ref:`(Zhao, 2007) ` 的 33 | 2.1节。简单说,8个方向的Sweep多线程同时进行,再对每个节点取最小值,算一次迭代。 34 | 但要注意的是,这种并行方法是一种 **FSM** 变体,即 **流程本身并不是可并行的。** 35 | 原始的 **FSM** 每次Sweep是一次Gauss-Seidel式迭代,上一次Sweep结果会影响到 36 | 下一次Sweep。 **并行FSM** 将8次Sweep分多线程单独进行,这要求 37 | :code:`FSMmaxLoops > 2` 。 38 | 39 | + :code:`FSMeps` (float) (default: 0.0) 40 | 41 | 每次Sweep后,走时的最大更新量小于 :code:`FSMeps` 时提前结束计算。 42 | 43 | 44 | 45 | 46 | Fast Marching OR Fast Sweeping ? 47 | ------------------------------------ 48 | 49 | 不存在谁好谁坏。 50 | 51 | **FSM** 的一个核心技巧就是 **并行** ,基于此有不少工作对 **FSM** 做各种并行改进。而 **Fast Marching Method(FMM)** 本身是串行实现以保证强因果性。 52 | 53 | 这里引用 :ref:`(Zhao, 2007) ` 中关于 **FSM** 关于串行或并行的一些讨论: 54 | 55 | .. epigraph:: 56 | 57 | In general if the characteristics are straight lines, sweepings with different orderings are almost independent of each other and the parallel sweeping algorithm should be as efficient as the original fast sweeping algorithm. However if the characteristics are curved then different orderings implemented sequentially may propagate information faster on a curved characteristics than different orderings implemented in parallel. 58 | 59 | 结合我的测试结果,我的观点是: 60 | 61 | + 对于速度缓和变化的模型, **FSM** 仅需8次sweep(1次迭代)即可收敛,此时计算效率和 **FMM** 持平,再加上并行, **FSM** 计算效率甚至可以达到 **FMM** 的8倍(接近理论值),且计算误差保持一致(可以以均匀模型做测试)。 62 | 63 | 64 | + 但对于速度变化剧烈的模型, **FSM** 需要更多的迭代次数来收敛,尤其是并行算法。当只设置收敛条件 :code:`FSMeps` (如1e-3) 而不设置 :code:`FSMmaxLoops` 时(给定一个较大的 :code:`FSMeps` ),迭代过程中的走时最大更新量可能很难收敛到给定的条件而导致计算效率下降。此时串行的 **FSM** 相比与并行尽管表现出更好的稳定性,但也需要2~3次迭代(1次往往不够),计算时间也是 **FSM** 的2~3倍。 65 | 66 | 在实际模型中速度变化是未知的,而 **FSM** 的计算结果受较多参数的影响。但影响 **FMM** 结果的因素不多,基本就是靠网格点的稠密程度决定。根据原理, **FMM** 的计算结果呈现无条件稳定,再加上堆排序算法, **FMM** 的计算效率也不落下风。 67 | -------------------------------------------------------------------------------- /pyfmm/C_extension/include/interp.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file interp.h 3 | * @author Zhu Dengda (zhudengda@mail.iggcas.ac.cn) 4 | * @date 2023-03 5 | * 6 | */ 7 | 8 | #pragma once 9 | 10 | #include "const.h" 11 | 12 | 13 | /** 14 | * 将三维数据展平进行三次线性插值 15 | * 16 | * @param x (in)x方向坐标数组 17 | * @param nx (in)x长度 18 | * @param y (in)y方向坐标 19 | * @param ny (in)y长度 20 | * @param z (in)z方向坐标 21 | * @param nz (in)z长度 22 | * @param nyz (in)ny*nz 23 | * @param values (in)展平的三维数据数组 24 | * @param xi (in)待插值的x坐标 25 | * @param yi (in)待插值的y坐标 26 | * @param zi (in)待插值的z坐标 27 | * @param pdiffx (out)非NULL时,插值x方向梯度 28 | * @param pdiffy (out)非NULL时,插值y方向梯度 29 | * @param pdiffz (out)非NULL时,插值z方向梯度 30 | * @param IXYZ (out)非NULL时,(xi,yi,zi)所在的索引坐标(i,i+1,j,j+1,k,k+1) 31 | * @param WGHT (out)非NULL时,8个插值权重 32 | * 33 | * @return 插值结果 34 | * 35 | */ 36 | MYREAL trilinear_one_ravel( 37 | const double *x, MYINT nx, const double *y, MYINT ny, const double *z, MYINT nz, MYINT nyz, const MYREAL *values, 38 | double xi, double yi, double zi, double *pdiffx, double *pdiffy, double *pdiffz, 39 | MYINT IXYZ[6], double WGHT[2][2][2]); 40 | 41 | 42 | /** 43 | * 计算三次线性插值的索引和权重 44 | * 45 | * @param x (in)x方向坐标数组 46 | * @param nx (in)x长度 47 | * @param y (in)y方向坐标 48 | * @param ny (in)y长度 49 | * @param z (in)z方向坐标 50 | * @param nz (in)z长度 51 | * @param xi (in)待插值的x坐标 52 | * @param yi (in)待插值的y坐标 53 | * @param zi (in)待插值的z坐标 54 | * @param IXYZ (out)非NULL时,(xi,yi,zi)所在的索引坐标(i,i+1,j,j+1,k,k+1) 55 | * @param WGHT (out)非NULL时,8个插值权重 56 | */ 57 | void trilinear_one_fac( 58 | const double *x, MYINT nx, const double *y, MYINT ny, const double *z, MYINT nz, 59 | double xi, double yi, double zi, MYINT IXYZ[6], double WGHT[2][2][2]); 60 | 61 | 62 | 63 | /** 64 | * 在已知索引和权重的情况下做三次线性插值 65 | * 66 | * @param IXYZ (in)(xi,yi,zi)所在的索引坐标(i,i+1,j,j+1,k,k+1) 67 | * @param WGHT (in)8个插值权重 68 | * @param values (in)展平的三维数据数组 69 | * @param nx (in)x长度 70 | * @param ny (in)y长度 71 | * @param nz (in)z长度 72 | * @param nyz (in)ny*nz 73 | * @param pdiffx (out)非NULL时,插值x方向梯度 74 | * @param pdiffy (out)非NULL时,插值y方向梯度 75 | * @param pdiffz (out)非NULL时,插值z方向梯度 76 | * 77 | * @return 插值结果 78 | * 79 | */ 80 | MYREAL trilinear_one_Idx_ravel( 81 | const MYINT IXYZ[6], const double WGHT[2][2][2], const MYREAL *values, MYINT nx, MYINT ny, MYINT nz, MYINT nyz, 82 | double *pdiffx, double *pdiffy, double *pdiffz); -------------------------------------------------------------------------------- /pyfmm/C_extension/include/fsm.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file fsm.h 3 | * @author Zhu Dengda (zhudengda@mail.iggcas.ac.cn) 4 | * @date 2023-05 5 | * 6 | */ 7 | #pragma once 8 | 9 | #include "const.h" 10 | #include "heapsort.h" 11 | 12 | 13 | /** 14 | * 定义OpenMP多线程数 15 | * 16 | * @param num_threads (in)线程数 17 | */ 18 | void set_fsm_num_threads(MYINT num_threads); 19 | 20 | 21 | /** 22 | * 使用Fast Sweeping Method计算全局走时场 23 | * 24 | * @param rs (in)维度1坐标数组 25 | * @param nr (in)rs长度 26 | * @param ts (in)维度2坐标数组 27 | * @param nt (in)ts长度 28 | * @param ps (in)维度2坐标数组 29 | * @param np (in)ps长度 30 | * @param rr (in)源点维度1坐标 31 | * @param tt (in)源点维度2坐标 32 | * @param pp (in)源点维度3坐标 33 | * @param maxodr (in)使用的最大差分阶数 34 | * @param Slw (in)展平的三维慢度场 35 | * @param TT (inout)展平的三维走时场,如果初始值有非零值,会被直接加入堆中,此时源点不再使用 36 | * @param sphcoord (in)是否使用球坐标 37 | * @param rfgfac (in)对于源点附近的格点间加密倍数,>1 38 | * @param rfgn (in)对于源点附近的格点间加密处理的辐射半径,>=1 39 | * @param printbar (in)是否打印进度条 40 | * @param eps (in)Sweep后的最大更新量达到收敛条件 41 | * @param maxLoops (in)Fast Sweeping Method整体迭代次数(对于3D模型,向8个方向各Sweep一次为迭代一次) 42 | * @param isparallel (in)是否使用并行FSM 43 | * 44 | * @return nsweep, sweep次数 45 | * 46 | */ 47 | MYINT FastSweeping( 48 | const double *rs, MYINT nr, 49 | const double *ts, MYINT nt, 50 | const double *ps, MYINT np, 51 | double rr, double tt, double pp, 52 | MYINT maxodr, const MYREAL *Slw, 53 | MYREAL *TT, bool sphcoord, 54 | MYINT rfgfac, MYINT rfgn, bool printbar, 55 | double eps, MYINT maxLoops, bool isparallel); 56 | 57 | 58 | /** 59 | * 在有初始走时的情况下使用Fast Marching Method计算全局走时场 60 | * 61 | * @param rs (in)维度1坐标数组 62 | * @param nr (in)rs长度 63 | * @param ts (in)维度2坐标数组 64 | * @param nt (in)ts长度 65 | * @param ps (in)维度2坐标数组 66 | * @param np (in)ps长度 67 | * @param maxodr (in)使用的最大差分阶数 68 | * @param Slw (in)展平的三维慢度场 69 | * @param TT (inout)展平的三维走时场 70 | * @param FMM_stat (out)记录每个节点的状态(alive, close, far) 71 | * @param sphcoord (in)是否使用球坐标 72 | * @param printbar (in)是否打印进度条 73 | * @param eps (in)Sweep后的最大更新量达到收敛条件 74 | * @param maxLoops (in)Fast Sweeping Method整体迭代次数(对于3D模型,向8个方向各Sweep一次为迭代一次) 75 | * @param isparallel (in)是否使用并行FSM 76 | * 77 | * @return nsweep, sweep次数 78 | */ 79 | MYINT FastSweeping_with_initial( 80 | const double *rs, MYINT nr, 81 | const double *ts, MYINT nt, 82 | const double *ps, MYINT np, 83 | MYINT maxodr, const MYREAL *Slw, MYREAL *TT, 84 | char *FMM_stat, bool sphcoord, bool printbar, 85 | double eps, MYINT maxLoops, bool isparallel); 86 | 87 | -------------------------------------------------------------------------------- /pyfmm/c_interfaces.py: -------------------------------------------------------------------------------- 1 | """ 2 | :file: c_interfaces.py 3 | :author: Zhu Dengda (zhudengda@mail.iggcas.ac.cn) 4 | :date: 2023-04 5 | 6 | 该文件包括 C库的调用接口 7 | 8 | """ 9 | 10 | import os 11 | from ctypes import * 12 | from typing import Any 13 | 14 | PDOUBLE = POINTER(c_double) 15 | PFLOAT = POINTER(c_float) 16 | 17 | USE_FLOAT:bool = False 18 | """libfmm库中走时和慢度数组是否使用单精度浮点数""" 19 | NPCT_REAL_TYPE:str = 'f8' 20 | 21 | USE_LONG:bool = True 22 | """使用长整型整数避免统计网格点数量时溢出""" 23 | INT = c_long if USE_LONG else c_int 24 | PINT = POINTER(INT) 25 | 26 | 27 | C_FastMarching:Any = None 28 | C_FMM_raytracing:Any = None 29 | C_FastSweeping:Any = None 30 | C_set_fsm_num_threads:Any = None 31 | 32 | def load_c_lib(use_float:bool=False): 33 | r''' 34 | 加载单精度或双精度的C库,修改c_interfaces下的NPCT_REAL_TYPE变量和C函数接口 35 | 36 | :param use_float: 是否使用单精度 37 | ''' 38 | global USE_FLOAT, NPCT_REAL_TYPE, C_FastMarching, C_FMM_raytracing, C_FastSweeping, C_set_fsm_num_threads 39 | 40 | USE_FLOAT = use_float 41 | NPCT_REAL_TYPE = 'f4' if USE_FLOAT else 'f8' 42 | _suffix = 'float' if USE_FLOAT else 'double' 43 | 44 | REAL = c_float if USE_FLOAT else c_double 45 | PREAL = POINTER(REAL) 46 | 47 | libfmm = cdll.LoadLibrary( 48 | os.path.join( 49 | os.path.abspath(os.path.dirname(__file__)), 50 | f"C_extension/lib/libfmm_{_suffix}.so")) 51 | """libfmm库""" 52 | 53 | 54 | C_FastMarching = libfmm.FastMarching 55 | """C库中计算走时场的主函数 FastMarching, 详见C API同名函数""" 56 | 57 | C_FMM_raytracing = libfmm.FMM_raytracing 58 | """C库中根据走时场进行射线追踪 FMM_raytracing, 详见C API同名函数""" 59 | 60 | 61 | C_FastMarching.restype = None 62 | C_FastMarching.argtypes = [ 63 | PDOUBLE, INT, 64 | PDOUBLE, INT, 65 | PDOUBLE, INT, 66 | c_double, c_double, c_double, 67 | INT, PREAL, 68 | PREAL, c_bool, 69 | INT, INT, c_bool 70 | ] 71 | 72 | 73 | C_FMM_raytracing.restype = REAL 74 | C_FMM_raytracing.argtypes = [ 75 | PDOUBLE, INT, 76 | PDOUBLE, INT, 77 | PDOUBLE, INT, 78 | c_double, c_double, c_double, 79 | c_double, c_double, c_double, c_double, c_double, 80 | PREAL, PREAL, c_bool, 81 | PDOUBLE, PINT 82 | ] 83 | 84 | C_FastSweeping = libfmm.FastSweeping 85 | C_FastSweeping.restype = INT 86 | C_FastSweeping.argtypes = [ 87 | PDOUBLE, INT, 88 | PDOUBLE, INT, 89 | PDOUBLE, INT, 90 | c_double, c_double, c_double, 91 | INT, PREAL, 92 | PREAL, c_bool, 93 | INT, INT, c_bool, 94 | c_double, INT, c_bool 95 | ] 96 | 97 | C_set_fsm_num_threads = libfmm.set_fsm_num_threads 98 | C_set_fsm_num_threads.restype = None 99 | C_set_fsm_num_threads.argtypes = [INT] 100 | 101 | 102 | def set_fsm_num_threads(n): 103 | r''' 104 | 定义Fast Sweeping Method使用的多线程数 105 | 106 | :param n: 线程数 107 | ''' 108 | C_set_fsm_num_threads(n) -------------------------------------------------------------------------------- /pyfmm/C_extension/include/heapsort.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file heapsort.h 3 | * @author Zhu Dengda (zhudengda@mail.iggcas.ac.cn) 4 | * @date 2023-03 5 | * 6 | * 非标准版本的最小推排序,堆元素本身数据是某个数据节点的索引值, 7 | * 判断元素大小关系使用节点对应的走时进行比较 8 | * 9 | */ 10 | 11 | #pragma once 12 | 13 | #include "const.h" 14 | 15 | typedef MYINT HEAP_DATA; 16 | 17 | /** 18 | * 最小堆向上调整 19 | * 20 | * @param HEAP_data (inout)指向堆首的指针 21 | * @param child (in)某个堆元素在堆中的索引值 22 | * @param NroIdx (out)一维指针,用于在节点索引位置处填上堆中的索引值 23 | * @param TT (in)一维指针,记录每个节点的走时 24 | * 25 | * 26 | */ 27 | void MinHeap_AdjustUp(HEAP_DATA * HEAP_data, MYINT child, MYINT *NroIdx, const MYREAL *TT); 28 | 29 | 30 | 31 | /** 32 | * 最小堆向下调整 33 | * 34 | * @param HEAP_data (inout)指向堆首的指针 35 | * @param size (in)堆大小 36 | * @param root (in)某个堆元素在堆中的索引值 37 | * @param NroIdx (out)一维指针,用于在节点索引位置处填上堆中的索引值 38 | * @param TT (in)一维指针,记录每个节点的走时 39 | * 40 | * 41 | */ 42 | void MinHeap_AdjustDown(HEAP_DATA * HEAP_data, MYINT size, MYINT root, MYINT *NroIdx, const MYREAL *TT); 43 | 44 | 45 | /** 46 | * 从堆首弹出元素,即返回堆首元素并且从堆中删除堆首,并做一次向下调整堆 47 | * 48 | * @param HEAP_data (inout)指向堆首的指针 49 | * @param psize (inout)堆大小,会被调整大小 50 | * @param NroIdx (out)一维指针,用于在节点索引位置处填上堆中的索引值 51 | * @param TT (in)一维指针,记录每个节点的走时 52 | * 53 | * @return 堆首元素 54 | * 55 | */ 56 | HEAP_DATA HeapPop(HEAP_DATA *HEAP_data, MYINT *psize, MYINT *NroIdx, const MYREAL *TT); 57 | 58 | 59 | /** 60 | * 从堆尾压入元素,即添加元素,并做一次向上调整堆 61 | * 62 | * @param HEAP_data (inout)指向堆首的指针 63 | * @param psize (inout)堆大小,会被调整大小 64 | * @param pcap (inout)堆最大容量,视情况会被调整大小 65 | * @param newdata (in)新元素 66 | * @param NroIdx (out)一维指针,用于在节点索引位置处填上堆中的索引值 67 | * @param TT (in)一维指针,记录每个节点的走时 68 | * 69 | * @return 堆首指针 70 | * 71 | */ 72 | HEAP_DATA * HeapPush(HEAP_DATA *HEAP_data, MYINT *psize, MYINT *pcap, HEAP_DATA newdata, MYINT *NroIdx, const MYREAL *TT); 73 | 74 | 75 | /** 76 | * 建立堆 77 | * 78 | * @param HEAP_data (inout)指向堆首的指针 79 | * @param size (in)堆大小 80 | * @param idx (in)指定子堆的索引,完全建立堆则idx==size 81 | * @param NroIdx (out)一维指针,用于在节点索引位置处填上堆中的索引值 82 | * @param TT (in)一维指针,记录每个节点的走时 83 | * 84 | * 85 | */ 86 | void HeapBuild(HEAP_DATA * HEAP_data, MYINT size, MYINT idx, MYINT *NroIdx, const MYREAL *TT); 87 | 88 | 89 | /** 90 | * 交换数据(内联函数) 91 | * 92 | * @param data1 数据1的指针 93 | * @param data2 数据2的指针 94 | */ 95 | inline void Swap(HEAP_DATA * data1, HEAP_DATA * data2){ 96 | HEAP_DATA FMM = *data1; 97 | *data1 = *data2; 98 | *data2 = FMM; 99 | } 100 | 101 | 102 | /** 103 | * 打印推数据【用于debug】 104 | */ 105 | void print_HEAP( 106 | HEAP_DATA * data, MYINT size, MYINT nr, MYINT nt, MYINT np, MYINT *NroIdx, 107 | MYREAL *TT, MYREAL *gTr, MYREAL *gTt, MYREAL *gTp); 108 | 109 | 110 | -------------------------------------------------------------------------------- /docs/source/conf.py: -------------------------------------------------------------------------------- 1 | # Configuration file for the Sphinx documentation builder. 2 | # 3 | # For the full list of built-in configuration values, see the documentation: 4 | # https://www.sphinx-doc.org/en/master/usage/configuration.html 5 | 6 | # -- Project information ----------------------------------------------------- 7 | # https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information 8 | 9 | import sys, os, pathlib 10 | import subprocess 11 | 12 | read_the_docs_build = os.environ.get('READTHEDOCS', None) == 'True' 13 | 14 | if read_the_docs_build: 15 | subprocess.call('cd ..; doxygen doxyfile_h; cd -', shell=True) 16 | 17 | 18 | html_last_updated_fmt = '%b %d, %Y' 19 | 20 | def setup(app): 21 | app.add_css_file('my_theme.css') 22 | 23 | 24 | # 读取版本号 25 | def read_version(): 26 | version_file = os.path.join('../../pyfmm', '_version.py') 27 | with open(version_file) as f: 28 | exec(f.read()) 29 | return locals()['__version__'] 30 | 31 | project = 'PyFMM' 32 | copyright = '2025, Zhu Dengda' 33 | author = 'Zhu Dengda' 34 | # 引入版本信息 35 | version = read_version() 36 | release = version 37 | 38 | # -- General configuration --------------------------------------------------- 39 | # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration 40 | 41 | extensions = [ 42 | "sphinx.ext.napoleon", 43 | "sphinx.ext.autodoc", 44 | 'sphinx.ext.viewcode', 45 | "recommonmark", 46 | "sphinx_markdown_tables", 47 | "sphinxcontrib.mermaid", 48 | "sphinx_copybutton", 49 | "sphinx.ext.intersphinx", 50 | "breathe", 51 | 'sphinx.ext.mathjax', 52 | "nbsphinx", 53 | ] 54 | 55 | nbsphinx_allow_errors = True # 在构建文档时允许 Notebook 中的错误 56 | nbsphinx_execute = 'never' # 不执行 Notebook,只是展示内容 57 | 58 | 59 | source_suffix = { 60 | '.rst': 'restructuredtext', 61 | # '.txt': 'markdown', 62 | # '.md': 'markdown', 63 | } 64 | 65 | myst_enable_extensions = [ 66 | "tasklist", 67 | "deflist", 68 | "dollarmath", 69 | ] 70 | 71 | # Breathe configuration 72 | breathe_projects = { 73 | "h_PyFMM": "../doxygen_h/xml", 74 | } 75 | breathe_default_project = "h_PyFMM" 76 | 77 | templates_path = ['_templates'] 78 | exclude_patterns = [] 79 | 80 | language = 'zh_CN' 81 | 82 | # -- Options for HTML output ------------------------------------------------- 83 | # https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output 84 | 85 | # html_theme = 'alabaster' 86 | master_doc = 'index' 87 | html_theme = 'sphinx_rtd_theme' 88 | html_theme_options = { 89 | 'analytics_anonymize_ip': False, 90 | 'logo_only': False, # True 91 | 'display_version': True, 92 | 'prev_next_buttons_location': 'bottom', 93 | 'style_external_links': False, 94 | 'collapse_navigation': True, 95 | 'sticky_navigation': True, 96 | 'navigation_depth': 4, 97 | 'includehidden': True, 98 | 'titles_only': False, 99 | 100 | } 101 | 102 | # html_logo = "./_static/logo.png" 103 | html_static_path = ['_static'] 104 | html_js_files = [ 105 | 'my_custom.js', 106 | ] 107 | 108 | 109 | autodoc_default_options = { 110 | 'member-order': 'bysource', 111 | 'special-members': '__init__', 112 | } -------------------------------------------------------------------------------- /docs/source/index.rst: -------------------------------------------------------------------------------- 1 | **PyFMM** 文档 2 | =================== 3 | 4 | `项目主页 `_ 5 | 6 | :Author: Zhu Dengda 7 | :Email: zhudengda@mail.iggcas.ac.cn 8 | 9 | 10 | |pic1| |pic2| 11 | 12 | .. |pic1| image:: ../../figs/output2.png 13 | :width: 45% 14 | 15 | .. |pic2| image:: ../../figs/output3.png 16 | :width: 45% 17 | 18 | 19 | ----------------------------------------------------------- 20 | 21 | 22 | **PyFMM** : 基于 **Fast Marching/Sweeping Method** 求解程函方程 :math:`|\nabla T|^2 = s^2` 的程序包。 23 | 代码根据 :ref:`主要参考 ` 中详述的原理进行实现,其中 **Fast Sweeping 及其并行方法** 基于 :ref:`(Zhao, 2004) ` 和 :ref:`(Zhao, 2007) ` 24 | 25 | 我主要使用该代码计算地震波从震源出发在复杂介质中传播形成的初至波走时场, 26 | 并使用梯度下降获得满足费马原理的射线路径,故代码中的一些术语偏专业性。 27 | 类似的原理也可用于其它方面,如计算点到曲线/面的距离,或光学、电磁学等。 28 | 29 | At present, **PyFMM** can run on 30 | 31 | .. raw:: html 32 | 33 | Linux
34 | macOS
35 | Windows
36 | 37 | ----------------------------------------------------------- 38 | 39 | 40 | 我还制作了一个简易图形界面 `PyFMM-GUI `_ 41 | 计算二维走时场,初学者可更好的理解射线追踪,也可更方便、直观地看到不同速度场下射线的 42 | 扭曲形态。 43 | 44 | 45 | .. image:: https://github.com/Dengda98/PyFMM-GUI/blob/main/figs/example.gif 46 | :alt: gif_example 47 | :width: 80% 48 | :align: center 49 | 50 | ----------------------------------------------------------- 51 | 52 | 53 | + **Python语言的便携、可扩展性与C语言的计算高效特点结合**。 54 | C程序被编译链接成动态库 *libfmm.so* ,**PyFMM** 再基于Python的 55 | `ctypes `_ 标准库\ 56 | 实现对C库函数的调用。再基于第三方库 `NumPy `_ 、 57 | `SciPy `_ 等可很方便地完成对C程序结果的数据整合。 58 | \ 59 | 60 | + C代码采取模块化编写,各功能分在不同代码文件中。 61 | \ 62 | 63 | + 支持二维和三维情况。 64 | \ 65 | 66 | + 支持直角坐标系和球坐标系。 67 | \ 68 | 69 | + 中文注释及示例。 70 | \ 71 | 72 | 73 | 主要使用的函数都在 :class:`pyfmm.traveltime ` 模块中,参数简单, 74 | 建议使用前结合api说明以及示例试试。代码是我在初学时写的,如果遇到bug,欢迎联系我,我会完善! 75 | 也欢迎提出建议和更多示例! 76 | 77 | 78 | --------------------------- 79 | 80 | .. toctree:: 81 | :maxdepth: 1 82 | :caption: 目录 83 | 84 | install 85 | jupyter_examples 86 | about_FSM 87 | API/pyfmm_api 88 | API/h_pyfmm_api 89 | 90 | 91 | .. _main_ref: 92 | 93 | 主要参考 94 | --------- 95 | 96 | .. [1] Sethian, J. A. (1996). A fast marching level set method 97 | for monotonically advancing fronts., Proc. Natl. Acad. Sci. U.S.A. 93, no. 4, 98 | 1591–1595, doi: 10.1073/pnas.93.4.1591. 99 | 100 | .. [2] Popovici, A. M., and J. A. Sethian (2002). 3‐D imaging using 101 | higher order fast marching traveltimes, GEOPHYSICS 67, no. 2, 604–609, 102 | doi: 10.1190/1.1468621. 103 | 104 | 105 | .. [3] Rawlinson, N., and M. Sambridge (2004). Wave front evolution in 106 | strongly heterogeneous layered media using the fast marching method, 107 | Geophysical Journal International 156, no. 3, 631–647, doi: 10.1111/j.1365-246X.2004.02153.x. 108 | 109 | .. _zhao_2004: 110 | 111 | .. [4] Zhao, H. (2004). A fast sweeping method for Eikonal equations, 112 | Math. Comp. 74, no. 250, 603–627, doi: 10.1090/S0025-5718-04-01678-3. 113 | 114 | .. _zhao_2007: 115 | 116 | .. [5] Zhao, H. (2007). Parallel implementations of the fast sweeping method, 117 | Journal of Computational Mathematics 25, no. 4, 421–429. 118 | 119 | -------------------------------------------------------------------------------- /docs/source/_templates/footer.html: -------------------------------------------------------------------------------- 1 |
2 | {%- if (theme_prev_next_buttons_location == 'bottom' or theme_prev_next_buttons_location == 'both') and (next or prev) %} 3 | {#- Translators: This is an ARIA section label for the footer section of the page. -#} 4 | 12 | {%- endif %} 13 | 14 |
15 | 16 |
17 | {%- block contentinfo %} 18 |

19 | {%- if show_copyright %} 20 | {%- if hasdoc('copyright') %} 21 | {%- trans path=pathto('copyright'), copyright=copyright|e %}© Copyright {{ copyright }}.{% endtrans %} 22 | {%- else %} 23 | {%- trans copyright=copyright|e %}© Copyright {{ copyright }}.{% endtrans %} 24 | {%- endif %} 25 | {%- endif %} 26 | 27 | {%- if build_id and build_url %} 28 | 29 | {#- Translators: Build is a noun, not a verb -#} 30 | {%- trans %}Build{% endtrans -%} 31 | {{ build_id }}. 32 | 33 | {%- elif commit %} 34 | 35 | {#- Translators: the phrase "revision" comes from Git, referring to a commit #} 36 | {%- trans %}Revision{% endtrans %} {{ commit }}. 37 | 38 | {%- endif %} 39 | {%- if last_updated %} 40 | 41 | {%- trans last_updated=last_updated|e %}Last updated on {{ last_updated }}.{% endtrans %} 42 | 43 | {%- endif -%} 44 | 45 |

46 | {%- endblock %} 47 |
48 | 49 | {% if show_sphinx %} 50 | {%- set sphinx_web = 'Sphinx' %} 51 | {%- set readthedocs_web = 'Read the Docs' %} 52 | {#- Translators: the variable "sphinx_web" is a link to the Sphinx project documentation with the text "Sphinx" #} 53 | {%- trans sphinx_web=sphinx_web, readthedocs_web=readthedocs_web %}Built with {{ sphinx_web }} using a{% endtrans %} 54 | {#- Translators: "theme" refers to a theme for Sphinx, which alters the appearance of the generated documentation #} 55 | {% trans %}theme{% endtrans %} 56 | {#- Translators: this is always used as "provided by Read the Docs", and should not imply Read the Docs is an author of the generated documentation. #} 57 | {% trans %}provided by {{ readthedocs_web }}{% endtrans %}. 58 | {% endif %} 59 | 60 | {%- block extrafooter %} {% endblock %} 61 | 62 | 63 | 64 | 65 | 66 |    👁️‍🗨️ 67 | 68 | 69 |    🧑 70 | 71 | 72 | 73 |
74 | -------------------------------------------------------------------------------- /pyfmm/C_extension/Makefile: -------------------------------------------------------------------------------- 1 | # ifeq ($(OS),Windows_NT) 2 | # define RMDIR_FUNC 3 | # if exist $(1) rmdir /S /Q $(1) 4 | # endef 5 | # else 6 | # define RMDIR_FUNC 7 | # rm -rf $(1) 8 | # endef 9 | # endif 10 | 11 | # ifeq ($(OS),Windows_NT) 12 | # define MKDIR_FUNC 13 | # if not exist $(1) mkdir $(1) 14 | # endef 15 | # else 16 | # define MKDIR_FUNC 17 | # mkdir -p $(1) 18 | # endef 19 | # endif 20 | 21 | # ifeq ($(OS),Windows_NT) 22 | # FILESEP = \\ 23 | 24 | # else 25 | # FILESEP = / 26 | # endif 27 | 28 | SRC_DIR := src 29 | INC_DIR := include 30 | BUILD_DIR := build 31 | BUILD_DIR_FLOAT = $(BUILD_DIR)/float 32 | BUILD_DIR_DOUBLE = $(BUILD_DIR)/double 33 | LIB_DIR = lib 34 | LIB_NAME = $(LIB_DIR)/libfmm 35 | LIB_EXT = .so 36 | 37 | CC := gcc 38 | FOMPFLAGS := -fopenmp 39 | 40 | # link static library on Windows 41 | LINK_STATIC := 42 | LDFLAGS := $(FOMPFLAGS) 43 | 44 | # expand stack memory for Windows 45 | STACK_MEM := 46 | 47 | ifeq ($(OS),Windows_NT) # link static oenpmp on windows 48 | STACK_MEM := -Wl,-stack,0x1000000 49 | LINK_STATIC := -static 50 | LDFLAGS := $(LINK_STATIC) $(FOMPFLAGS) 51 | endif 52 | 53 | # change architecture for macOS, from make command 54 | ARCH = 55 | 56 | # -ffast-math -march=native -mtune=native # 如果加上这些选项,数学库-lm需要在编译动态库时再次显式指定。总是gcc的编译参数的前后顺序很讲究 57 | CFLAGS = $(LINK_STATIC) -lm -std=gnu99 -O3 -fPIC \ 58 | -Wall $(STACK_MEM) -I$(shell realpath $(INC_DIR)) $(ARCH) $(FOMPFLAGS) # -fsanitize=address -lasan 59 | 60 | SRCS = $(wildcard $(SRC_DIR)/*.c) 61 | INCS = $(wildcard $(INC_DIR)/*.h) 62 | 63 | # 不同版本的目标文件目录 64 | OBJS_FLOAT = $(patsubst $(SRC_DIR)/%.c, $(BUILD_DIR_FLOAT)/%.o, $(SRCS)) 65 | OBJS_DOUBLE = $(patsubst $(SRC_DIR)/%.c, $(BUILD_DIR_DOUBLE)/%.o, $(SRCS)) 66 | DEPS_FLOAT := $(OBJS_FLOAT:.o=.d) 67 | DEPS_DOUBLE := $(OBJS_DOUBLE:.o=.d) 68 | 69 | # 生成的库名称 70 | TARGET_FLOAT = $(LIB_NAME)_float$(LIB_EXT) 71 | TARGET_DOUBLE = $(LIB_NAME)_double$(LIB_EXT) 72 | STATIC_TARGET_FLOAT = $(LIB_NAME)_float.a 73 | STATIC_TARGET_DOUBLE = $(LIB_NAME)_double.a 74 | 75 | .PHONY: all clean cleanbuild 76 | 77 | all: $(BUILD_DIR) $(LIB_DIR) $(TARGET_FLOAT) $(TARGET_DOUBLE) $(STATIC_TARGET_FLOAT) $(STATIC_TARGET_DOUBLE) 78 | 79 | $(BUILD_DIR): 80 | @mkdir -p $@ 81 | 82 | $(LIB_DIR): 83 | @mkdir -p $@ 84 | 85 | # ----------------------- Dependency generation ----------------------- 86 | -include $(DEPS_FLOAT) 87 | -include $(DEPS_DOUBLE) 88 | 89 | $(BUILD_DIR_FLOAT)/%.d: $(SRC_DIR)/%.c 90 | @mkdir -p $(shell dirname $@) 91 | @$(CC) $(CFLAGS) -MM $< > $@.$$$$; \ 92 | sed 's,\($*\)\.o[ :]*,$(BUILD_DIR_FLOAT)/\1.o $@ : ,g' < $@.$$$$ > $@; \ 93 | rm -f $@.$$$$ 94 | 95 | $(BUILD_DIR_DOUBLE)/%.d: $(SRC_DIR)/%.c 96 | @mkdir -p $(shell dirname $@) 97 | @$(CC) $(CFLAGS) -MM $< > $@.$$$$; \ 98 | sed 's,\($*\)\.o[ :]*,$(BUILD_DIR_DOUBLE)/\1.o $@ : ,g' < $@.$$$$ > $@; \ 99 | rm -f $@.$$$$ 100 | 101 | # 编译 float 版本的目标文件 102 | $(BUILD_DIR_FLOAT)/%.o: $(SRC_DIR)/%.c 103 | $(CC) -o $@ -c $< $(CFLAGS) -DUSE_FLOAT 104 | 105 | # 编译 double 版本的目标文件 106 | $(BUILD_DIR_DOUBLE)/%.o: $(SRC_DIR)/%.c 107 | $(CC) -o $@ -c $< $(CFLAGS) 108 | 109 | # 链接动态库,生成 float 版本 110 | $(TARGET_FLOAT): $(OBJS_FLOAT) 111 | $(CC) -shared -o $@ $^ $(LDFLAGS) 112 | 113 | # 链接动态库,生成 double 版本 114 | $(TARGET_DOUBLE): $(OBJS_DOUBLE) 115 | $(CC) -shared -o $@ $^ $(LDFLAGS) 116 | 117 | $(STATIC_TARGET_FLOAT): $(OBJS_FLOAT) 118 | ar rcs $@ $^ 119 | 120 | $(STATIC_TARGET_DOUBLE): $(OBJS_DOUBLE) 121 | ar rcs $@ $^ 122 | 123 | cleanbuild: 124 | rm -rf $(BUILD_DIR) 125 | 126 | clean: 127 | rm -rf $(BUILD_DIR) 128 | rm -rf $(LIB_DIR) 129 | -------------------------------------------------------------------------------- /pyfmm/C_extension/src/heapsort.c: -------------------------------------------------------------------------------- 1 | /** 2 | * @file heapsort.c 3 | * @author Zhu Dengda (zhudengda@mail.iggcas.ac.cn) 4 | * @date 2023-03 5 | * 6 | * 7 | * 8 | */ 9 | 10 | #include 11 | #include 12 | 13 | #include "const.h" 14 | #include "heapsort.h" 15 | #include "index.h" 16 | 17 | 18 | void MinHeap_AdjustUp(HEAP_DATA * HEAP_data, MYINT child, MYINT *NroIdx, const MYREAL *TT){ 19 | MYINT parent = (child-1)/2; 20 | HEAP_DATA *pdata1, *pdata2; 21 | while(child > 0){ 22 | pdata1 = HEAP_data+child; 23 | pdata2 = HEAP_data+parent; 24 | if(TT[*pdata1] >= TT[*pdata2]) break; 25 | 26 | if(NroIdx!=NULL){ 27 | NroIdx[*pdata1] = parent; 28 | NroIdx[*pdata2] = child; 29 | } 30 | Swap(pdata1, pdata2); 31 | child = parent; 32 | parent = (child-1)/2; 33 | } 34 | } 35 | 36 | void MinHeap_AdjustDown(HEAP_DATA * HEAP_data, MYINT size, MYINT root, MYINT *NroIdx, const MYREAL *TT){ 37 | MYINT parent = root; 38 | MYINT child = parent*2 + 1; 39 | HEAP_DATA *pdata1, *pdata2; 40 | while(child < size){ 41 | pdata1 = HEAP_data+child; 42 | pdata2 = HEAP_data+parent; 43 | if(child+1 < size && TT[*(pdata1+1)] < TT[*pdata1]){ 44 | child++; 45 | pdata1++; 46 | } 47 | 48 | if(TT[*pdata1] >= TT[*pdata2]) break; 49 | 50 | if(NroIdx!=NULL){ 51 | NroIdx[*pdata1] = parent; 52 | NroIdx[*pdata2] = child; 53 | } 54 | Swap(pdata1, pdata2); 55 | parent = child; 56 | child = parent*2 + 1; 57 | } 58 | } 59 | 60 | HEAP_DATA HeapPop(HEAP_DATA *HEAP_data, MYINT *psize, MYINT *NroIdx, const MYREAL *TT){ 61 | HEAP_DATA popdata = HEAP_data[0]; 62 | if(NroIdx!=NULL){ 63 | NroIdx[*(HEAP_data+(*psize-1))] = 0; 64 | } 65 | Swap(HEAP_data, HEAP_data+(*psize-1)); 66 | (*psize)--; 67 | 68 | MinHeap_AdjustDown(HEAP_data, *psize, 0, NroIdx, TT); 69 | 70 | return popdata; 71 | } 72 | 73 | HEAP_DATA * HeapPush(HEAP_DATA *HEAP_data, MYINT *psize, MYINT *pcap, HEAP_DATA newdata, MYINT *NroIdx, const MYREAL *TT){ 74 | if(*psize == *pcap){ 75 | MYINT newcap = (*pcap==0)? 8 : (*pcap)*2; 76 | HEAP_DATA *HEAP_data0 = realloc(HEAP_data, sizeof(HEAP_DATA)*newcap); 77 | if(HEAP_data==NULL){ 78 | fprintf(stderr, "reallocation failed in fmm. exit."); 79 | exit(EXIT_FAILURE); 80 | } 81 | HEAP_data = HEAP_data0; 82 | *pcap = newcap; 83 | } 84 | HEAP_data[*psize] = newdata; 85 | (*psize)++; 86 | 87 | if(NroIdx!=NULL) NroIdx[newdata] = *psize-1; 88 | 89 | MinHeap_AdjustUp(HEAP_data, *psize-1, NroIdx, TT); 90 | 91 | return HEAP_data; 92 | } 93 | 94 | void HeapBuild(HEAP_DATA * HEAP_data, MYINT size, MYINT idx, MYINT *NroIdx, const MYREAL *TT){ 95 | for(MYINT i=(idx-1)/2; i>=0; --i){ 96 | MinHeap_AdjustDown(HEAP_data, size, i, NroIdx, TT); 97 | } 98 | } 99 | 100 | 101 | /** 102 | * 仅用于debug 103 | */ 104 | void print_HEAP( 105 | HEAP_DATA * data, MYINT size, MYINT nr, MYINT nt, MYINT np, MYINT *NroIdx, 106 | MYREAL *TT, MYREAL *gTr, MYREAL *gTt, MYREAL *gTp) 107 | { 108 | MYINT ir, it, ip; 109 | 110 | printf("size %d\n", size); 111 | for(MYINT i=0; i20) break; 127 | } 128 | // getchar(); 129 | } 130 | 131 | 132 | 133 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 |

PyFMM

3 | 4 |

5 | 6 | Documentation Status 7 | 8 | 9 | DOI 10 | 11 | GitHub code size in bytes 12 | GitHub License 13 | GitHub Actions Workflow Status 14 | 15 |

16 | 17 | 18 |

19 | Image 2 20 | Image 3 21 |

22 | 23 | **欢迎Star!** 24 | 25 | [**PyFMM**](https://github.com/Dengda98/PyFMM) 是一个基于 **Fast Marching/Sweeping Method** 求解程函方程 $|\nabla T|^2 = s^2$ 的C/Python程序包,包括示例和注释。 其中 **Fast Sweeping Method** 包括了并行版本,详见[**在线文档**](https://pyfmm.readthedocs.io/zh-cn/latest/)或文献 [(Zhao, 2007)](https://www.jstor.org/stable/43693378)。 26 | 27 | [**PyFMM**](https://github.com/Dengda98/PyFMM) is a C/Python package for solving eikonal equation using Fast Marching/Sweeping Method, with examples and annotations. 28 | 29 | At present, **PyFMM** can run on 30 | - [x] Linux 31 | - [x] macOS 32 | - [x] Windows 33 | 34 | ---- 35 | 36 | 我还制作了一个简易图形界面 [**PyFMM-GUI**](https://github.com/Dengda98/PyFMM-GUI) 计算二维走时场,初学者可更好的理解射线追踪,也可更方便、直观地看到不同速度场下射线的扭曲形态。 37 | 38 | ![](https://github.com/Dengda98/PyFMM-GUI/blob/main/figs/example.gif) 39 | 40 | ------- 41 |
42 | 43 | 我主要使用 **PyFMM** 计算地震波从震源出发在复杂介质中传播形成的初至波走时场, 44 | 并使用梯度下降获得满足费马原理的射线路径,故代码中的一些术语偏专业性。 45 | 类似的原理也可用于其它方面,如计算点到曲线/面的距离,或光学、电磁学等。 46 | 47 | 48 | + **Python语言的便携、可扩展性与C语言的计算高效特点结合**。 49 | C程序被编译链接成动态库 *libfmm.so* ,**PyFMM** 再基于Python的 [ctypes](https://docs.python.org/3/library/ctypes.html) 50 | 标准库实现对C库函数的调用。再基于第三方库 [NumPy](https://numpy.org/)、 51 | [SciPy](https://scipy.org/) 等可很方便地完成对C程序结果的数据整合; 52 | 53 | 54 | + C代码采取模块化编写,各功能分在不同代码文件中,方便移植到其它程序; 55 | 56 | 57 | + 支持二维和三维情况;2D and 3D 58 | 59 | 60 | + 支持直角坐标系和球坐标系;Cartesian and Spherical Coordinate 61 | 62 | 63 | + 中文注释及示例; 64 | 65 |
66 | 67 | 68 | # 文档 Documents 69 | 为方便使用,我建立了[**在线文档**](https://pyfmm.readthedocs.io/zh-cn/latest/),包括简易安装、API的介绍以及使用示例。 70 | 71 |
72 | 73 | # 安装 Installation 74 | 75 | **新版本已添加预编译的C动态库**,无需本地再编译,支持`pip`命令一键安装: 76 | ```bash 77 | pip install pyfmm-kit 78 | ``` 79 | 80 | 81 |
82 | 83 | 84 | # 使用示例 Usage Example 85 | 更多使用示例详见[**在线文档**](https://pyfmm.readthedocs.io/zh-cn/latest/)。 86 | ``` python 87 | import pyfmm 88 | import numpy as np 89 | import matplotlib.pyplot as plt 90 | from scipy import interpolate 91 | 92 | pyfmm.logger.myLogger.setLevel('ERROR') 93 | 94 | # 定义网格 95 | nx, ny, nz = 401, 1, 101 96 | xarr = np.linspace(0, 200, nx) 97 | yarr = np.array([0.0]) 98 | zarr = np.linspace(0, 50, nz) 99 | 100 | # 定义1D速度 101 | vel1d = np.array([ 102 | [0.0, 3.2], 103 | [5.0, 5.8], 104 | [15.0, 6.5], 105 | [30.0, 6.8], 106 | [35.0, 8.1], 107 | [80.0, 8.2] 108 | ]) 109 | 110 | # 插值1d分层速度 111 | # _idxs = np.searchsorted(vel1d[:,0], zarr) 112 | # velocity = vel1d[_idxs, 1] 113 | # OR 114 | # 插值1d梯度速度 115 | velocity = interpolate.interpn((vel1d[:,0],), vel1d[:,1], zarr) 116 | 117 | # 慢度数组 118 | slowness = np.empty((nx, ny, nz)) 119 | slowness[...] = 1.0/velocity[None,None,:] 120 | 121 | # 定义震源位置 122 | srcloc = [0.0, 0.0, 0.0] 123 | 124 | # 计算时间场 125 | TT = pyfmm.travel_time_source( 126 | srcloc, 127 | xarr, yarr, zarr, slowness) 128 | 129 | #==================================================================== 130 | # 绘制走时场和射线 131 | fig, ax1 = plt.subplots(1, 1) 132 | cs = ax1.contour(xarr, zarr, TT[:, 0, :].T, levels=30, linewidths=0.5) 133 | ax1.clabel(cs) 134 | 135 | for x in np.arange(5, 200, 5): 136 | # 射线追踪 137 | rcvloc = [x, 0, 0] 138 | 139 | travt, rays = pyfmm.raytracing( 140 | TT, srcloc, rcvloc, xarr, yarr, zarr, 0.1) 141 | ax1.plot(rays[:,0], rays[:,2], c='r', lw=0.8, ls='--') 142 | 143 | ax1.set_aspect('equal') 144 | ax1.set_xlim(0, 200) 145 | ax1.set_ylim(0, 50) 146 | ax1.yaxis.set_inverted(True) 147 | 148 | ``` 149 | ![](https://github.com/Dengda98/PyFMM/blob/main/figs/example.png) 150 | 151 | 152 | # 其它 153 | 代码是我在研二写的,如果遇到bug,欢迎联系我(zhudengda@mail.iggcas.ac.cn),我会完善! 154 | 也欢迎提出建议和更多示例! 155 | 156 | 基于PyFMM的体波走时反演以及面波反演后续也会开源。 157 | -------------------------------------------------------------------------------- /pyfmm/C_extension/include/fmm.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file fmm.h 3 | * @author Zhu Dengda (zhudengda@mail.iggcas.ac.cn) 4 | * @date 2023-03 5 | * 6 | */ 7 | 8 | #pragma once 9 | 10 | #include "const.h" 11 | #include "heapsort.h" 12 | 13 | #define _PRINT_ODR_BUG_ 0 14 | 15 | #define FMM_FAR -1 ///< 波前还未触及的区域 16 | #define FMM_CLS 0 ///< 波前面 17 | #define FMM_ALV 1 ///< 波前已完全扫过的区域,走时已确定 18 | 19 | 20 | 21 | /** 22 | * 使用Fast Marching Method计算全局走时场 23 | * 24 | * @param rs (in)维度1坐标数组 25 | * @param nr (in)rs长度 26 | * @param ts (in)维度2坐标数组 27 | * @param nt (in)ts长度 28 | * @param ps (in)维度2坐标数组 29 | * @param np (in)ps长度 30 | * @param rr (in)源点维度1坐标 31 | * @param tt (in)源点维度2坐标 32 | * @param pp (in)源点维度3坐标 33 | * @param maxodr (in)使用的最大差分阶数 34 | * @param Slw (in)展平的三维慢度场 35 | * @param TT (inout)展平的三维走时场,如果初始值有非零值,会被直接加入堆中,此时源点不再使用 36 | * @param sphcoord (in)是否使用球坐标 37 | * @param rfgfac (in)对于源点附近的格点间加密倍数,>1 38 | * @param rfgn (in)对于源点附近的格点间加密处理的辐射半径,>=1 39 | * @param printbar (in)是否打印进度条 40 | * 41 | * 42 | */ 43 | void FastMarching( 44 | const double *rs, MYINT nr, 45 | const double *ts, MYINT nt, 46 | const double *ps, MYINT np, 47 | double rr, double tt, double pp, 48 | MYINT maxodr, const MYREAL *Slw, 49 | MYREAL *TT, bool sphcoord, 50 | MYINT rfgfac, MYINT rfgn, bool printbar); 51 | 52 | 53 | /** 54 | * 在有初始走时的情况下使用Fast Marching Method计算全局走时场 55 | * 56 | * @param rs (in)维度1坐标数组 57 | * @param nr (in)rs长度 58 | * @param ts (in)维度2坐标数组 59 | * @param nt (in)ts长度 60 | * @param ps (in)维度2坐标数组 61 | * @param np (in)ps长度 62 | * @param maxodr (in)使用的最大差分阶数 63 | * @param Slw (in)展平的三维慢度场 64 | * @param TT (inout)展平的三维走时场 65 | * @param FMM_stat (out)记录每个节点的状态(alive, close, far) 66 | * @param sphcoord (in)是否使用球坐标 67 | * @param edgeStop (in)是否在波前传播到6个边界面时提前结束计算 68 | * @param printbar (in)是否打印进度条 69 | * @param FMM_data (inout)堆首指针 70 | * @param psize (inout)堆大小,会被调整大小 71 | * @param pcap (inout)堆最大容量,视情况会被调整大小 72 | * @param NroIdx (out)一维指针,用于在节点索引位置处填上堆中的索引值 73 | * @param pNdots (inout)记录还剩下多少节点的走时未计算 74 | * 75 | */ 76 | HEAP_DATA * FastMarching_with_initial( 77 | const double *rs, MYINT nr, 78 | const double *ts, MYINT nt, 79 | const double *ps, MYINT np, 80 | MYINT maxodr, const MYREAL *Slw, MYREAL *TT, 81 | char *FMM_stat, bool sphcoord, bool *edgeStop, bool printbar, 82 | HEAP_DATA *FMM_data, MYINT *psize, MYINT *pcap, MYINT *NroIdx, MYINT *pNdots); 83 | 84 | 85 | 86 | /** 87 | * 计算源点附近的走时 88 | * 89 | * @param rs (in)维度1坐标数组 90 | * @param nr (in)rs长度 91 | * @param ts (in)维度2坐标数组 92 | * @param nt (in)ts长度 93 | * @param ps (in)维度2坐标数组 94 | * @param np (in)ps长度 95 | * @param rr (in)源点维度1坐标 96 | * @param tt (in)源点维度2坐标 97 | * @param pp (in)源点维度3坐标 98 | * @param Slw (in)展平的三维慢度场 99 | * @param TT (inout)展平的三维走时场 100 | * @param FMM_stat (out)记录每个节点的状态(alive, close, far) 101 | * @param sphcoord (in)是否使用球坐标 102 | * @param FMM_data (inout)堆首指针 103 | * @param psize (inout)堆大小,会被调整大小 104 | * @param pcap (inout)堆最大容量,视情况会被调整大小 105 | * @param NroIdx (out)一维指针,用于在节点索引位置处填上堆中的索引值 106 | * @param pNdots (inout)记录还剩下多少节点的走时未计算 107 | * 108 | * 109 | * @return 堆首指针 110 | */ 111 | HEAP_DATA * init_source_TT( 112 | const double *rs, MYINT nr, 113 | const double *ts, MYINT nt, 114 | const double *ps, MYINT np, 115 | double rr, double tt, double pp, 116 | const MYREAL *Slw, MYREAL *TT, 117 | char *FMM_stat, bool sphcoord, 118 | HEAP_DATA *FMM_data, MYINT *psize, MYINT *pcap, MYINT *NroIdx, MYINT *pNdots); 119 | 120 | 121 | 122 | /** 123 | * 以加密网格的方式计算源点附近的走时 124 | * 125 | * @param rs (in)维度1坐标数组 126 | * @param nr (in)rs长度 127 | * @param ts (in)维度2坐标数组 128 | * @param nt (in)ts长度 129 | * @param ps (in)维度2坐标数组 130 | * @param np (in)ps长度 131 | * @param rr (in)源点维度1坐标 132 | * @param tt (in)源点维度2坐标 133 | * @param pp (in)源点维度3坐标 134 | * @param maxodr (in)使用的最大差分阶数 135 | * @param Slw (in)展平的三维慢度场 136 | * @param TT (inout)展平的三维走时场 137 | * @param FMM_stat (out)记录每个节点的状态(alive, close, far) 138 | * @param sphcoord (in)是否使用球坐标 139 | * @param rfgfac (in)对于源点附近的格点间加密倍数,>1 140 | * @param rfgn (in)对于源点附近的格点间加密处理的辐射半径,>=1 141 | * @param printbar (in)是否打印进度条 142 | * @param FMM_data (inout)堆首指针 143 | * @param psize (inout)堆大小,会被调整大小 144 | * @param pcap (inout)堆最大容量,视情况会被调整大小 145 | * @param NroIdx (out)一维指针,用于在节点索引位置处填上堆中的索引值 146 | * @param pNdots (inout)记录还剩下多少节点的走时未计算 147 | * 148 | * @return 堆首指针 149 | */ 150 | HEAP_DATA * init_source_TT_refinegrid( 151 | const double *rs, MYINT nr, 152 | const double *ts, MYINT nt, 153 | const double *ps, MYINT np, 154 | double rr, double tt, double pp, 155 | MYINT maxodr, const MYREAL *Slw, MYREAL *TT, 156 | char *FMM_stat, bool sphcoord, 157 | MYINT rfgfac, MYINT rfgn, // refine grid factor and number of grids 158 | bool printbar, 159 | HEAP_DATA *FMM_data, MYINT *psize, MYINT *pcap, MYINT *NroIdx, MYINT *pNdots); 160 | 161 | 162 | 163 | /** 164 | * 依据邻近的节点走时,以解一元二次方程的形式求解某点的走时 165 | * 166 | * @param nr (in)维度1长度 167 | * @param nt (in)维度2长度 168 | * @param np (in)维度3长度 169 | * @param ntp (in)nt*np 170 | * @param ir (in)某点的维度1索引 171 | * @param it (in)某点的维度2索引 172 | * @param ip (in)某点的维度3索引 173 | * @param idx (in)某点的三维展开索引 174 | * @param maxodr (in)使用的最大差分阶数 175 | * @param TT (inout)展平的三维走时场 176 | * @param FMM_stat (out)记录每个节点的状态(alive, close, far) 177 | * @param s (in)某点的慢度 178 | * @param dr (in)维度1坐标间隔 179 | * @param dt (in)维度2坐标间隔 180 | * @param dp (in)维度3坐标间隔 181 | * @param stat (out)求解情况,-1表示求解出现问题,0为正常求解 182 | * 183 | * @return 走时结果 184 | * 185 | */ 186 | MYREAL get_neighbour_travt( 187 | MYINT nr, MYINT nt, MYINT np, MYINT ntp, 188 | MYINT ir, MYINT it, MYINT ip, MYINT idx, 189 | MYINT maxodr, MYREAL *TT, 190 | char *FMM_stat, double s, 191 | double dr, double dt, double dp, 192 | char *stat); 193 | 194 | 195 | 196 | /** 197 | * 根据梯度下降,从走时场中提取初至射线 198 | * 199 | * @param rs (in)维度1坐标数组 200 | * @param nr (in)rs长度 201 | * @param ts (in)维度2坐标数组 202 | * @param nt (in)ts长度 203 | * @param ps (in)维度2坐标数组 204 | * @param np (in)ps长度 205 | * @param r0 (in)源点维度1坐标 206 | * @param t0 (in)源点维度2坐标 207 | * @param p0 (in)源点维度3坐标 208 | * @param rr (in)接收点维度1坐标 209 | * @param tt (in)接收点维度2坐标 210 | * @param pp (in)接收点维度3坐标 211 | * @param seglen (in)射线段长度 212 | * @param segfac (in)t < segfac*seglen/v,当射线追踪到在源点附近时,射线直接连接源点 213 | * @param Slw (in)展平的三维慢度场,若非NULL则使用累加求和计算走时,否则直接从走时场中插值得到走时 214 | * @param TT (in)展平的三维走时场 215 | * @param sphcoord (in)是否使用球坐标 216 | * @param rays (out)输出展平的三维射线 217 | * @param N (out)输出射线点数 218 | * 219 | * @return 射线走时 220 | * 221 | */ 222 | MYREAL FMM_raytracing( 223 | const double *rs, MYINT nr, 224 | const double *ts, MYINT nt, 225 | const double *ps, MYINT np, 226 | double r0, double t0, double p0, 227 | double rr, double tt, double pp, double seglen, double segfac, 228 | const MYREAL *Slw, const MYREAL *TT, bool sphcoord, 229 | double *rays, MYINT *N); -------------------------------------------------------------------------------- /.github/workflows/testbuild.yml: -------------------------------------------------------------------------------- 1 | name: Just test 2 | 3 | # 触发机制为“非主分支的提交” 4 | on: 5 | workflow_dispatch: 6 | push: 7 | branches-ignore: 8 | - main # 排除主分支 9 | - master # 如果有 master 分支,也可以排除 10 | 11 | jobs: 12 | build: # 编译C库 13 | runs-on: ${{ matrix.os }} 14 | strategy: 15 | matrix: 16 | include: 17 | - os: windows-2022 18 | arch: x86_64 # windows x86_6 19 | - os: ubuntu-22.04 20 | arch: x86_64 # Ubuntu x86_64 21 | - os: macos-13 22 | arch: x86_64 # macOS Intel 23 | - os: macos-14 24 | arch: arm64 # macOS Apple Silicon 25 | 26 | fail-fast: true 27 | 28 | defaults: 29 | run: 30 | shell: bash 31 | 32 | steps: 33 | - name: Set MSYS2 (Windows) # windows平台使用MSYS2工具编译程序 34 | if: contains(matrix.os, 'windows') 35 | uses: msys2/setup-msys2@v2 36 | with: 37 | msystem: UCRT64 38 | install: >- 39 | git 40 | mingw-w64-ucrt-x86_64-gcc 41 | make 42 | 43 | - name: Configured git attributes for line endings (Windows) # 防止接下来在windows平台checkout代码时,文本文件的换行符发生变化,导致MSYS2工作出错 44 | if: contains(matrix.os, 'windows') 45 | run: git config --global core.autocrlf input 46 | 47 | - name: Checkout code # 下载库代码 48 | uses: actions/checkout@v3 49 | with: 50 | fetch-depth: 1 51 | 52 | # --------------------------- 安装依赖 ------------------------------------------ 53 | # - name: Install dependencies (Ubuntu) 54 | # if: contains(matrix.os, 'ubuntu') 55 | # run: | 56 | # sudo apt update 57 | # sudo apt install -y build-essential 58 | # 在 ubuntu 系统上创建低版本 glibc (2.17) 的环境进行编译,以提供向后兼容能力 59 | - name: Create CentOS 7.7 container (Ubuntu) 60 | if: contains(matrix.os, 'ubuntu') 61 | run: | 62 | CONTAINER_ID=$(docker create -v ${{ github.workspace }}:/workspace -w /workspace centos:7.7.1908 sleep infinity) 63 | echo "CONTAINER_ID=$CONTAINER_ID" >> $GITHUB_ENV 64 | docker start $CONTAINER_ID 65 | 66 | - name: Update yum in container (Ubuntu) 67 | if: contains(matrix.os, 'ubuntu') 68 | run: | 69 | docker exec ${{ env.CONTAINER_ID }} bash -c " 70 | mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup && \ 71 | curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo && \ 72 | yum clean all -y && yum makecache -y && yum install -y gcc make 73 | " 74 | 75 | - name: Install dependencies (macOS) 76 | # 匹配包含 "macos" 的操作系统 77 | if: contains(matrix.os, 'macos') 78 | run: | 79 | brew install libomp 80 | 81 | # ----------------- 编译C库和C程序 ---------------------------------- 82 | - name: Build the project (macOS) 83 | if: contains(matrix.os, 'macos') 84 | working-directory: ./pyfmm/C_extension 85 | run: | 86 | make ARCH="-arch ${{ matrix.arch }}" \ 87 | CC=gcc-14 88 | 89 | make cleanbuild 90 | otool -L lib/*.so 91 | 92 | # - name: Build the project (Ubuntu) 93 | # if: contains(matrix.os, 'ubuntu') 94 | # working-directory: ./pyfmm/C_extension 95 | # run: | 96 | # make 97 | # make cleanbuild 98 | # ldd lib/*.so 99 | 100 | - name: Build the project in container (Ubuntu) 101 | if: contains(matrix.os, 'ubuntu') 102 | working-directory: 103 | run: | 104 | docker exec ${{ env.CONTAINER_ID }} bash -c "cd pyfmm/C_extension && ls && make && make cleanbuild && cd -" 105 | cd ./pyfmm/C_extension 106 | ldd lib/*.so 107 | cd - 108 | 109 | - name: Cleanup container (Ubuntu) 110 | if: contains(matrix.os, 'ubuntu') 111 | run: | 112 | docker stop ${{ env.CONTAINER_ID }} 113 | docker rm ${{ env.CONTAINER_ID }} 114 | 115 | - name: Build the project (Windows) 116 | if: contains(matrix.os, 'windows') 117 | shell: msys2 {0} 118 | working-directory: ./pyfmm/C_extension 119 | run: | 120 | make 121 | make cleanbuild 122 | ldd lib/*.so 123 | 124 | 125 | # ------------------------ 定义接下来打包程序命名时的系统名后缀 --------------- 126 | - name: Define the package OS suffix 127 | run: | 128 | # 符合pypi命名规范,否则上传失败 129 | if [[ "${{ matrix.os }}" == *"ubuntu"* ]]; then 130 | SUFFIX_PLAT_NAME="manylinux2014_x86_64" 131 | elif [[ "${{ matrix.os }}" == *"macos"* && "${{ matrix.arch }}" == *"x86_64"* ]]; then 132 | SUFFIX_PLAT_NAME="macosx_10_9_x86_64" 133 | elif [[ "${{ matrix.os }}" == *"macos"* && "${{ matrix.arch }}" == *"arm64"* ]]; then 134 | SUFFIX_PLAT_NAME="macosx_11_0_arm64" 135 | elif [[ "${{ matrix.os }}" == *"windows"* ]]; then 136 | SUFFIX_PLAT_NAME="win_amd64" 137 | else 138 | echo " Unsupported OS: ${{ matrix.os }} (${{ matrix.arch }})" 139 | exit 1 140 | fi 141 | 142 | echo "SUFFIX_PLAT_NAME=$SUFFIX_PLAT_NAME" >> $GITHUB_ENV 143 | 144 | # --------------------------- 打包整个程序 --------------------- 145 | - name: Package the binary 146 | run: | 147 | PACK_NAME=pyfmm_kit-${{ github.ref_name }}-${{ env.SUFFIX_PLAT_NAME }} 148 | echo "PACK_NAME=$PACK_NAME" >> $GITHUB_ENV 149 | FILE_CONTENT=$(ls -A) 150 | mkdir -p $PACK_NAME 151 | cp -r ${FILE_CONTENT} $PACK_NAME/ 152 | tar -czvf $PACK_NAME.tar.gz $PACK_NAME 153 | rm -rf $PACK_NAME 154 | 155 | # -------------------- upload artifacts ----------------------- 156 | - name: Upload artifact (*.tar.gz) 157 | uses: actions/upload-artifact@v4 158 | with: 159 | name: ${{ matrix.os }}-${{ matrix.arch }}_tar 160 | path: ${{ env.PACK_NAME }}.tar.gz 161 | 162 | 163 | # ======================================================================================= 164 | test_project: # 在全新系统上测试程序,不安装其它依赖,看能否运行 165 | runs-on: ${{ matrix.os }} 166 | needs: build 167 | strategy: 168 | matrix: 169 | include: 170 | - os: windows-2022 171 | arch: x86_64 # windows x86_6 172 | - os: ubuntu-22.04 173 | arch: x86_64 # Ubuntu x86_64 174 | - os: macos-13 175 | arch: x86_64 # macOS Intel 176 | - os: macos-14 177 | arch: arm64 # macOS Apple Silicon 178 | 179 | fail-fast: true 180 | 181 | defaults: 182 | run: 183 | shell: bash 184 | 185 | steps: 186 | - name: Download artifacts 187 | uses: actions/download-artifact@v4 188 | with: 189 | name: ${{ matrix.os }}-${{ matrix.arch }}_tar 190 | path: artifacts 191 | 192 | - name: Display structure of downloaded files, and Uncompress 193 | run: | 194 | ls -R artifacts 195 | echo "------------------- tar output -----------------------------" 196 | tar -xzvf artifacts/*.tar.gz 197 | echo "------------------------------------------------------------" 198 | 199 | # 获得压缩包解压出来的文件夹名 200 | PACK_NAME=$(ls | grep pyfmm_kit) 201 | echo "PACK_NAME=$PACK_NAME" >> $GITHUB_ENV 202 | 203 | # 从解压出的文件夹命名来推断${{ env.SUFFIX_PLAT_NAME }} 204 | SUFFIX_PLAT_NAME=$(echo $PACK_NAME | sed 's/.*-\(.*\)/\1/') 205 | echo "SUFFIX_PLAT_NAME=$SUFFIX_PLAT_NAME" >> $GITHUB_ENV 206 | 207 | echo $PACK_NAME 208 | echo $SUFFIX_PLAT_NAME 209 | 210 | # --------------------------- 安装依赖 ------------------------------------------ 211 | # 实际使用时可能需要安装libomp 212 | # - name: Install libomp (Ubuntu) 213 | # if: contains(matrix.os, 'ubuntu') 214 | # run: | 215 | # sudo apt install -y libomp-dev 216 | 217 | # - name: Set alias (MacOS) 218 | # if: contains(matrix.os, 'macos') 219 | # run: | 220 | # brew install coreutils 221 | # echo "alias timeout=gtimeout" >> ~/.bashrc 222 | 223 | # --------------------搭建python环境,开始测试,并制作wheel文件 ------------------------------ 224 | - name: Set up Python 225 | uses: actions/setup-python@v4 226 | with: 227 | python-version: '3.9' 228 | 229 | - name: Install dependencies 230 | working-directory: ${{ env.PACK_NAME }} 231 | run: | 232 | python -m pip install --upgrade pip 233 | pip install --upgrade setuptools wheel build 234 | pip install -v . 235 | 236 | - name: Clean up build and egg-info directories 237 | working-directory: ${{ env.PACK_NAME }} 238 | run: | 239 | # 清理临时文件 240 | rm -rf build/ 241 | rm -rf pyfmm_kit.egg-info/ 242 | 243 | - name: Test 244 | working-directory: ${{ env.PACK_NAME }}/.github/tests 245 | run: | 246 | python uniform.py 247 | 248 | 249 | # --------------------------- 制作wheels --------------------- 250 | # - name: Build the Python Wheel 251 | # working-directory: ${{ env.PACK_NAME }} 252 | # run: | 253 | # python setup.py bdist_wheel --plat-name=${{ env.SUFFIX_PLAT_NAME }} # 只制作wheel,这里不打包源码 254 | 255 | # - name: Upload artifact (*.whl) 256 | # uses: actions/upload-artifact@v4 257 | # with: 258 | # name: ${{ env.PACK_NAME }}_whl 259 | # path: ${{ env.PACK_NAME }}/dist/*.whl 260 | -------------------------------------------------------------------------------- /pyfmm/C_extension/src/interp.c: -------------------------------------------------------------------------------- 1 | /** 2 | * @file interp.c 3 | * @author Zhu Dengda (zhudengda@mail.iggcas.ac.cn) 4 | * @date 2023-03 5 | * 6 | */ 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #include "const.h" 14 | #include "interp.h" 15 | #include "index.h" 16 | #include "query.h" 17 | 18 | 19 | 20 | MYREAL trilinear_one_ravel( 21 | const double *x, MYINT nx, const double *y, MYINT ny, const double *z, MYINT nz, MYINT nyz, const MYREAL *values, 22 | double xi, double yi, double zi, double *pdiffx, double *pdiffy, double *pdiffz, 23 | MYINT IXYZ[6], double WGHT[2][2][2]) 24 | { 25 | MYINT IXYZ0[6]; 26 | double WGHT0[2][2][2]; 27 | trilinear_one_fac(x, nx, y, ny, z, nz, xi, yi, zi, IXYZ0, WGHT0); 28 | 29 | double vi; 30 | vi = trilinear_one_Idx_ravel(IXYZ0, WGHT0, values, nx, ny, nz, nyz, pdiffx, pdiffy, pdiffz); 31 | 32 | if(IXYZ!=NULL){ 33 | for(MYINT i=0; i<6; ++i){ 34 | IXYZ[i] = IXYZ0[i]; 35 | } 36 | } 37 | if(WGHT!=NULL){ 38 | for(MYINT i=0; i<2; ++i){ 39 | for(MYINT j=0; j<2; ++j){ 40 | for(MYINT k=0; k<2; ++k){ 41 | WGHT[i][j][k] = WGHT0[i][j][k]; 42 | } 43 | } 44 | } 45 | } 46 | 47 | return vi; 48 | } 49 | 50 | 51 | 52 | void trilinear_one_fac( 53 | const double *x, MYINT nx, const double *y, MYINT ny, const double *z, MYINT nz, 54 | double xi, double yi, double zi, MYINT IXYZ[6], double WGHT[2][2][2]) 55 | { 56 | MYINT ix = dicho_find(x, nx, xi); 57 | // MYINT ix1 = (ix+1>nx-1) ? nx-1 : ix+1; 58 | MYINT iy = dicho_find(y, ny, yi); 59 | // MYINT iy1 = (iy+1>ny-1) ? ny-1 : iy+1; 60 | MYINT iz = dicho_find(z, nz, zi); 61 | // MYINT iz1 = (iz+1>nz-1) ? nz-1 : iz+1; 62 | MYINT ix1, iy1, iz1; 63 | if(IXYZ!=NULL && IXYZ[0]==-9){ // do extrapolation 64 | if(ix==nx-1) ix--; 65 | ix1 = ix+1; 66 | if(iy==ny-1) iy--; 67 | iy1 = iy+1; 68 | if(iz==nz-1) iz--; 69 | iz1 = iz+1; 70 | } else { 71 | ix1 = (ix+1>nx-1) ? nx-1 : ix+1; 72 | iy1 = (iy+1>ny-1) ? ny-1 : iy+1; 73 | iz1 = (iz+1>nz-1) ? nz-1 : iz+1; 74 | } 75 | 76 | // printf("%d,%d,%d, %f,%f,%f\n", ix, iy, iz, xi, yi, zi); 77 | double x1 = x[ix]; 78 | double x2 = x[ix1]; 79 | double y1 = y[iy]; 80 | double y2 = y[iy1]; 81 | double z1 = z[iz]; 82 | double z2 = z[iz1]; 83 | 84 | // 限制范围 85 | if(IXYZ==NULL || IXYZ[0]!=-9){ 86 | if(xi > x2) xi = x2; 87 | if(yi > y2) yi = y2; 88 | if(zi > z2) zi = z2; 89 | } 90 | 91 | double xfac=0.0, yfac=0.0, zfac=0.0, xfac1, yfac1, zfac1; 92 | if(ix!=ix1) xfac = (xi-x1)/(x2-x1); 93 | if(iy!=iy1) yfac = (yi-y1)/(y2-y1); 94 | if(iz!=iz1) zfac = (zi-z1)/(z2-z1); 95 | 96 | xfac1 = 1.0 - xfac; 97 | yfac1 = 1.0 - yfac; 98 | zfac1 = 1.0 - zfac; 99 | 100 | double f111, f121, f211, f221, f112, f122, f212, f222; 101 | f111 = xfac1 * yfac1 * zfac1; 102 | f121 = xfac1 * yfac * zfac1; 103 | f211 = xfac * yfac1 * zfac1; 104 | f221 = xfac * yfac * zfac1; 105 | f112 = xfac1 * yfac1 * zfac ; 106 | f122 = xfac1 * yfac * zfac ; 107 | f212 = xfac * yfac1 * zfac ; 108 | f222 = xfac * yfac * zfac ; 109 | 110 | if(IXYZ!=NULL){ 111 | IXYZ[0] = ix; 112 | IXYZ[1] = ix1; 113 | IXYZ[2] = iy; 114 | IXYZ[3] = iy1; 115 | IXYZ[4] = iz; 116 | IXYZ[5] = iz1; 117 | } 118 | if(WGHT!=NULL){ 119 | WGHT[0][0][0] = f111; WGHT[0][1][0] = f121; 120 | WGHT[1][0][0] = f211; WGHT[1][1][0] = f221; 121 | WGHT[0][0][1] = f112; WGHT[0][1][1] = f122; 122 | WGHT[1][0][1] = f212; WGHT[1][1][1] = f222; 123 | } 124 | } 125 | 126 | 127 | MYREAL trilinear_one_Idx_ravel( 128 | const MYINT IXYZ[6], const double WGHT[2][2][2], const MYREAL *values, MYINT nx, MYINT ny, MYINT nz, MYINT nyz, 129 | double *pdiffx, double *pdiffy, double *pdiffz) 130 | { 131 | MYINT ix, ix1, iy, iy1, iz, iz1; 132 | double f111, f121, f211, f221, f112, f122, f212, f222; 133 | double v111,v121,v211,v221, v112,v122,v212,v222; 134 | 135 | ix = IXYZ[0]; 136 | ix1 = IXYZ[1]; 137 | iy = IXYZ[2]; 138 | iy1 = IXYZ[3]; 139 | iz = IXYZ[4]; 140 | iz1 = IXYZ[5]; 141 | 142 | 143 | MYINT idx; 144 | ravel_index(&idx, nyz, nz, ix, iy, iz); 145 | MYINT dx, dy, dz, DX, DY, DZ; 146 | DX = nyz; 147 | DY = nz; 148 | DZ = 1; 149 | dx = (ix1>ix)? DX : 0; 150 | dy = (iy1>iy)? DY : 0; 151 | dz = (iz1>iz)? DZ : 0; 152 | 153 | v111 = values[idx ]; v121 = values[idx + dy ]; 154 | v211 = values[idx + dx ]; v221 = values[idx + dx + dy ]; 155 | v112 = values[idx + dz]; v122 = values[idx + dy + dz]; 156 | v212 = values[idx + dx + dz]; v222 = values[idx + dx + dy + dz]; 157 | 158 | f111 = WGHT[0][0][0]; f121 = WGHT[0][1][0]; 159 | f211 = WGHT[1][0][0]; f221 = WGHT[1][1][0]; 160 | f112 = WGHT[0][0][1]; f122 = WGHT[0][1][1]; 161 | f212 = WGHT[1][0][1]; f222 = WGHT[1][1][1]; 162 | 163 | double dv111,dv121,dv211,dv221, dv112,dv122,dv212,dv222; 164 | dv111=dv121=dv211=dv221=dv112=dv122=dv212=dv222=0.0; 165 | if(pdiffx!=NULL){ 166 | if(ix==0){ 167 | dv111 = v211 - v111; 168 | dv121 = v221 - v121; 169 | dv112 = v212 - v112; 170 | dv122 = v222 - v122; 171 | 172 | } else if(ix==nx-1){ 173 | dv111 = v111 - values[idx - DX]; 174 | dv121 = v121 - values[idx - DX + dy]; 175 | dv112 = v112 - values[idx - DX + dz]; 176 | dv122 = v122 - values[idx - DX + dy + dz]; 177 | 178 | } else { 179 | dv111 = (values[idx + DX] - values[idx - DX])/2.0; 180 | dv121 = (values[idx + DX + dy] - values[idx - DX + dy])/2.0; 181 | dv112 = (values[idx + DX + dz] - values[idx - DX + dz])/2.0; 182 | dv122 = (values[idx + DX + dy + dz] - values[idx - DX + dy + dz])/2.0; 183 | 184 | } 185 | 186 | if(ix < nx-2){ 187 | dv211 = (values[idx + 2*DX] - v111)/2.0; 188 | dv221 = (values[idx + 2*DX + dy] - v121)/2.0; 189 | dv212 = (values[idx + 2*DX + dz] - v112)/2.0; 190 | dv222 = (values[idx + 2*DX + dy + dz] - v122)/2.0; 191 | } else if(nx > 1){ // 设置nx > 1的判断,以防越界 192 | dv211 = (v111 - values[idx - 2*DX])/2.0; 193 | dv221 = (v121 - values[idx - 2*DX + dy])/2.0; 194 | dv212 = (v112 - values[idx - 2*DX + dz])/2.0; 195 | dv222 = (v122 - values[idx - 2*DX + dy + dz])/2.0; 196 | } 197 | 198 | *pdiffx = f111*dv111 + f121*dv121 + f211*dv211 + f221*dv221 + 199 | f112*dv112 + f122*dv122 + f212*dv212 + f222*dv222; 200 | } 201 | 202 | 203 | if(pdiffy!=NULL){ 204 | if(iy==0){ 205 | dv111 = v121 - v111; 206 | dv211 = v221 - v211; 207 | dv112 = v122 - v112; 208 | dv212 = v222 - v212; 209 | 210 | } else if(iy==ny-1){ 211 | dv111 = v111 - values[idx - DY]; 212 | dv211 = v211 - values[idx + dx - DY]; 213 | dv112 = v112 - values[idx - DY + dz]; 214 | dv212 = v212 - values[idx + dx - DY + dz]; 215 | 216 | } else { 217 | dv111 = (values[idx + DY] - values[idx - DY])/2.0; 218 | dv211 = (values[idx + dx + DY] - values[idx + dx - DY])/2.0; 219 | dv112 = (values[idx + DY + dz] - values[idx - DY + dz])/2.0; 220 | dv212 = (values[idx + dx + DY + dz] - values[idx + dx - DY + dz])/2.0; 221 | } 222 | 223 | if(iy < ny-2){ 224 | dv121 = (values[idx + 2*DY] - v111)/2.0; 225 | dv221 = (values[idx + dx + 2*DY] - v211)/2.0; 226 | dv122 = (values[idx + 2*DY + dz] - v112)/2.0; 227 | dv222 = (values[idx + dx + 2*DY + dz] - v212)/2.0; 228 | } else if(ny > 1){ 229 | dv121 = (v111 - values[idx - 2*DY])/2.0; 230 | dv221 = (v211 - values[idx + dx - 2*DY])/2.0; 231 | dv122 = (v112 - values[idx - 2*DY + dz])/2.0; 232 | dv222 = (v212 - values[idx + dx - 2*DY + dz])/2.0; 233 | } 234 | 235 | 236 | *pdiffy = f111*dv111 + f121*dv121 + f211*dv211 + f221*dv221 + 237 | f112*dv112 + f122*dv122 + f212*dv212 + f222*dv222; 238 | } 239 | 240 | if(pdiffz!=NULL) { 241 | if(iz==0){ 242 | dv111 = v112 - v111; 243 | dv211 = v212 - v211; 244 | dv121 = v122 - v121; 245 | dv221 = v222 - v221; 246 | 247 | } else if(iz==nz-1){ 248 | dv111 = v111 - values[idx - DZ]; 249 | dv211 = v211 - values[idx + dx - DZ]; 250 | dv121 = v121 - values[idx + dy - DZ]; 251 | dv221 = v221 - values[idx + dx + dy - DZ]; 252 | 253 | } else { 254 | dv111 = (values[idx + DZ] - values[idx - DZ])/2.0; 255 | dv211 = (values[idx + dx + DZ] - values[idx + dx - DZ])/2.0; 256 | dv121 = (values[idx + dy + DZ] - values[idx + dy - DZ])/2.0; 257 | dv221 = (values[idx + dx + dy + DZ] - values[idx + dx + dy - DZ])/2.0; 258 | 259 | } 260 | 261 | if(iz < nz-2){ 262 | dv112 = (values[idx + 2*DZ] - v111)/2.0; 263 | dv212 = (values[idx + dx + 2*DZ] - v211)/2.0; 264 | dv122 = (values[idx + dy + 2*DZ] - v121)/2.0; 265 | dv222 = (values[idx + dx + dy + 2*DZ] - v221)/2.0; 266 | } else if(nz > 1) { 267 | dv112 = (v111 - values[idx - 2*DZ])/2.0; 268 | dv212 = (v211 - values[idx + dx - 2*DZ])/2.0; 269 | dv122 = (v121 - values[idx + dy - 2*DZ])/2.0; 270 | dv222 = (v221 - values[idx + dx + dy - 2*DZ])/2.0; 271 | } 272 | 273 | *pdiffz = f111*dv111 + f121*dv121 + f211*dv211 + f221*dv221 + 274 | f112*dv112 + f122*dv122 + f212*dv212 + f222*dv222; 275 | 276 | } 277 | 278 | 279 | return f111*v111 + f121*v121 + f211*v211 + f221*v221 + 280 | f112*v112 + f122*v122 + f212*v212 + f222*v222; 281 | } 282 | 283 | 284 | 285 | 286 | 287 | 288 | 289 | -------------------------------------------------------------------------------- /pyfmm/C_extension/src/fsm.c: -------------------------------------------------------------------------------- 1 | /** 2 | * @file fsm.c 3 | * @author Zhu Dengda (zhudengda@mail.iggcas.ac.cn) 4 | * @date 2023-05 5 | * 6 | */ 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | #include "fsm.h" 16 | #include "fmm.h" 17 | #include "const.h" 18 | #include "index.h" 19 | #include "mallocfree.h" 20 | #include "progressbar.h" 21 | 22 | 23 | void set_fsm_num_threads(MYINT num_threads){ 24 | #ifdef _OPENMP 25 | omp_set_num_threads(num_threads); 26 | #endif 27 | } 28 | 29 | MYINT FastSweeping( 30 | const double *rs, MYINT nr, 31 | const double *ts, MYINT nt, 32 | const double *ps, MYINT np, 33 | double rr, double tt, double pp, 34 | MYINT maxodr, const MYREAL *Slw, 35 | MYREAL *TT, bool sphcoord, 36 | MYINT rfgfac, MYINT rfgn, bool printbar, 37 | double eps, MYINT maxLoops, bool isparallel) 38 | { 39 | // 程序运行开始时间 40 | struct timeval begin_t; 41 | gettimeofday(&begin_t, NULL); 42 | 43 | MYINT ntp=nt*np; 44 | MYINT nrtp=nr*ntp; 45 | char *FMM_stat = (char *)malloc1d(nrtp, sizeof(char)); 46 | 47 | // All non-zero value of TT will be treated as efficient value, 48 | // and set FMM_ALV 49 | bool allzeroTT = true; 50 | for(MYINT i=0; i1 && rfgn>=1){ 64 | init_source_TT_refinegrid( 65 | rs, nr, ts, nt, ps, np, 66 | rr, tt, pp, 67 | maxodr, Slw, TT, 68 | FMM_stat, sphcoord, 69 | rfgfac, rfgn, printbar, 70 | NULL, NULL, NULL, NULL, NULL); 71 | } else { 72 | init_source_TT( 73 | rs, nr, ts, nt, ps, np, 74 | rr, tt, pp, 75 | Slw, TT, 76 | FMM_stat, sphcoord, 77 | NULL, NULL, NULL, NULL, NULL); 78 | } 79 | } 80 | 81 | MYINT nsweep; 82 | nsweep = FastSweeping_with_initial( 83 | rs, nr, 84 | ts, nt, 85 | ps, np, 86 | maxodr, Slw, TT, 87 | FMM_stat, sphcoord, printbar, 88 | eps, maxLoops, isparallel); 89 | 90 | free(FMM_stat); 91 | 92 | 93 | // 程序运行结束时间 94 | struct timeval end_t; 95 | gettimeofday(&end_t, NULL); 96 | if(printbar) printf("Runtime: %.3f s\n", (end_t.tv_sec - begin_t.tv_sec) + (end_t.tv_usec - begin_t.tv_usec) / 1e6); 97 | fflush(stdout); 98 | 99 | return nsweep; 100 | } 101 | 102 | 103 | 104 | MYINT FastSweeping_with_initial( 105 | const double *rs, MYINT nr, 106 | const double *ts, MYINT nt, 107 | const double *ps, MYINT np, 108 | MYINT maxodr, const MYREAL *Slw, MYREAL *TT, 109 | char *FMM_stat, bool sphcoord, bool printbar, 110 | double eps, MYINT maxLoops, bool isparallel) 111 | { 112 | if(! isparallel) set_fsm_num_threads(1); 113 | 114 | double dr = (nr>1)? rs[1] - rs[0] : 0.0; 115 | double dt = (nt>1)? ts[1] - ts[0] : 0.0; 116 | double dp = (np>1)? ps[1] - ps[0] : 0.0; 117 | 118 | // convenient arrays 119 | double sin_ts[nt]; 120 | if(sphcoord){ 121 | for(MYINT it=0; it 1 && eps > 0.0 && maxUpdate <= eps) continue; 177 | 178 | MYREAL *TT_thread = NULL; 179 | char *FMM_stat_thread = NULL; 180 | 181 | if(isparallel){ 182 | TT_thread = TT_thread_all + isweep*nrtp; 183 | FMM_stat_thread = FMM_stat_thread_all + isweep*nrtp; 184 | } else { 185 | TT_thread = TT; 186 | FMM_stat_thread = FMM_stat; 187 | maxUpdate = 0.0; 188 | } 189 | 190 | 191 | MYINT begr, stepr, endr; 192 | MYINT begt, stept, endt; 193 | MYINT begp, stepp, endp; 194 | begr = begt = begp = 0; 195 | stepr = stept = stepp = 1; 196 | endr = nr; 197 | endt = nt; 198 | endp = np; 199 | bool direcr, direct, direcp; 200 | direcr = direct = direcp = false; 201 | MYINT idx; 202 | 203 | 204 | direcr = direcr_arr[isweep]; 205 | direct = direct_arr[isweep]; 206 | direcp = direcp_arr[isweep]; 207 | 208 | if(direcr) { 209 | begr = 0; stepr = 1; endr = nr; 210 | } else { 211 | begr = nr-1; stepr = -1; endr = -1; 212 | } 213 | if(direct) { 214 | begt = 0; stept = 1; endt = nt; 215 | } else { 216 | begt = nt-1; stept = -1; endt = -1; 217 | } 218 | if(direcp) { 219 | begp = 0; stepp = 1; endp = np; 220 | } else { 221 | begp = np-1; stepp = -1; endp = -1; 222 | } 223 | 224 | MYREAL mintravt=-999.0; 225 | double mintravt_h=0.0; 226 | MYREAL slw; 227 | MYREAL update0; 228 | 229 | // Start Sweeping 230 | for(MYINT ir=begr; ir!=endr; ir+=stepr){ 231 | for(MYINT it=begt; it!=endt; it+=stept){ 232 | for(MYINT ip=begp; ip!=endp; ip+=stepp){ 233 | ravel_index(&idx, ntp, np, ir, it, ip); 234 | slw = Slw[idx]; 235 | 236 | // find minimum traveltime in 6 neighbours 237 | MYREAL t_bak=-999.9, t_bak0=-999.9; 238 | mintravt=-999.0; 239 | mintravt_h=0.0; 240 | for(MYINT k=0; k<6; ++k){ 241 | MYINT jdx, iir, iit, iip; 242 | iir = ir+xr[k]; 243 | iit = it+xt[k]; 244 | iip = ip+xp[k]; 245 | 246 | if(iir<0 || iir>nr-1) continue; 247 | if(iit<0 || iit>nt-1) continue; 248 | if(iip<0 || iip>np-1) continue; 249 | 250 | ravel_index(&jdx, ntp, np, iir, iit, iip); 251 | 252 | if(FMM_stat_thread[jdx]==FMM_FAR) continue; 253 | 254 | // forever 255 | FMM_stat_thread[jdx] = FMM_ALV; 256 | 257 | if(mintravt > TT_thread[jdx] || mintravt < 0) { 258 | mintravt = TT_thread[jdx]; 259 | mintravt_h = hrtp[k]; 260 | // modify interval for spherical coordinate 261 | if(sphcoord && k>=2){ 262 | if(k<4) mintravt_h *= rs[ir]; 263 | else if(k<6) mintravt_h *= rs[ir]*sin_ts[it]; 264 | } 265 | 266 | t_bak0 = mintravt + mintravt_h * slw; 267 | if(t_bak > t_bak0 || t_bak < 0){ 268 | t_bak = t_bak0; 269 | } 270 | } 271 | } 272 | if(mintravt < 0.0) continue; 273 | 274 | // if(mintravt > maxnghT) continue; 275 | 276 | MYREAL travt; 277 | char travt_stat; 278 | 279 | // temporary set 280 | t_bak0 = TT_thread[idx]; 281 | if(t_bak0 > t_bak) TT_thread[idx] = t_bak; 282 | 283 | if(sphcoord){ 284 | travt = get_neighbour_travt( 285 | nr, nt, np, ntp, 286 | ir, it, ip, idx, 287 | maxodr, TT_thread, 288 | FMM_stat_thread, slw, dr, dt*rs[ir], dp*rs[ir]*sin_ts[it], 289 | &travt_stat); 290 | } else { 291 | travt = get_neighbour_travt( 292 | nr, nt, np, ntp, 293 | ir, it, ip, idx, 294 | maxodr, TT_thread, 295 | FMM_stat_thread, slw, dr, dt, dp, 296 | &travt_stat); 297 | } 298 | // set back 299 | TT_thread[idx] = t_bak0; 300 | 301 | if(travt_stat>=0 && travt>0){ 302 | if(t_bak < travt) travt = t_bak; 303 | } else { 304 | travt = t_bak; 305 | } 306 | 307 | 308 | if(travt < TT_thread[idx]) { 309 | if(! isparallel){ 310 | update0 = fabs(TT_thread[idx] - travt); 311 | if(update0 > maxUpdate) maxUpdate = update0; 312 | } 313 | 314 | TT_thread[idx] = travt; 315 | FMM_stat_thread[idx] = FMM_ALV; 316 | } 317 | 318 | }}} // end sweep in one direction 319 | 320 | // if(!isparallel) printf("isweep=%d, maxUpdate=%f\n", isweep, maxUpdate); 321 | 322 | } // end 8 sweeps for-loop 323 | 324 | nsweep += 8; 325 | 326 | if(isparallel){ 327 | // merge results 328 | maxUpdate = 0.0; 329 | MYREAL minTT, update; 330 | for(MYINT i=0; i update) minTT = update; 335 | } 336 | 337 | if(minTT < TT[i]){ 338 | update = fabs(minTT - TT[i]); 339 | if(update > maxUpdate) maxUpdate = update; 340 | TT[i] = minTT; 341 | } 342 | } 343 | 344 | // printf("iloop=%d, maxUpdate=%f\n", iloop, maxUpdate); 345 | } 346 | 347 | 348 | // break in advance 349 | if(eps > 0.0 && maxUpdate <= eps) break; 350 | 351 | for(MYINT i=0; i1 48 | :param rfgn: 对于源点附近的格点间加密处理的辐射半径,>=1 49 | :param printbar: 是否打印进度条 50 | :param useFSM: 是否改用Fast Sweeping Method计算全局走时场 51 | :param FSMeps: Fast Sweeping Method收敛条件,衡量Sweep后的最大更新量 52 | :param FSMmaxLoops: Fast Sweeping Method整体迭代次数(对于3D模型,向8个方向各Sweep一次为迭代一次) 53 | :param FSMparallel: 是否使用并行Fast Sweeping Method 54 | 55 | :return: 三维走时场 56 | ''' 57 | global FSM_nsweep 58 | 59 | check_xyz_arr(xarr, yarr, zarr, sphcoord) 60 | check_slowness(xarr, yarr, zarr, slw) 61 | 62 | # 对于并行情况,至少迭代两次 63 | if FSMparallel: 64 | if FSMmaxLoops <= 1: 65 | myLogger.warning("For parallel FSM, maxLoops must set at least 2 (already changed).") 66 | FSMmaxLoops = 2 67 | 68 | maxodr = int(maxodr) 69 | rfgfac = int(rfgfac) 70 | rfgn = int(rfgn) 71 | 72 | xx, yy, zz = np.array(srcloc).astype('f8') 73 | 74 | if xx < xarr[0] or xx > xarr[-1]: 75 | raise ValueError("xx out of bound.") 76 | if yy < yarr[0] or yy > yarr[-1]: 77 | raise ValueError("yy out of bound.") 78 | if zz < zarr[0] or zz > zarr[-1]: 79 | raise ValueError("zz out of bound.") 80 | 81 | # 对于在边界上的点,提出warning 82 | if xx == xarr[0] or xx == xarr[-1] or \ 83 | yy == yarr[0] or yy == yarr[-1] or \ 84 | zz == zarr[0] or zz == zarr[-1]: 85 | myLogger.warning(f"Source ({str(srcloc)}) is on the boundary.") 86 | 87 | c_xarr = npct.as_ctypes(xarr.astype('f8')) 88 | c_yarr = npct.as_ctypes(yarr.astype('f8')) 89 | c_zarr = npct.as_ctypes(zarr.astype('f8')) 90 | slw_ravel = slw.ravel().astype(c_interfaces.NPCT_REAL_TYPE) 91 | c_slw = npct.as_ctypes(slw_ravel) 92 | 93 | TT = np.zeros_like(slw).astype(c_interfaces.NPCT_REAL_TYPE) 94 | TT_ravel = TT.ravel() 95 | c_TT = npct.as_ctypes(TT_ravel) 96 | 97 | FastFunc = c_interfaces.C_FastMarching if not useFSM else c_interfaces.C_FastSweeping 98 | parse_args = [ 99 | c_xarr, len(xarr), 100 | c_yarr, len(yarr), 101 | c_zarr, len(zarr), 102 | xx, yy, zz, 103 | maxodr, c_slw, 104 | c_TT, sphcoord, 105 | rfgfac, rfgn, printbar 106 | ] 107 | if useFSM: 108 | parse_args.extend([FSMeps, FSMmaxLoops, FSMparallel]) 109 | 110 | FSM_nsweep = FastFunc(*parse_args) 111 | 112 | return TT 113 | 114 | 115 | def travel_time_iniTT( 116 | iniTT:np.ndarray, 117 | xarr:np.ndarray, yarr:np.ndarray, zarr:np.ndarray, slw:np.ndarray, 118 | maxodr:int=2, sphcoord:bool=False, printbar:bool=False, 119 | useFSM:bool=False, FSMeps:float=0.0, FSMmaxLoops:int=1, FSMparallel:bool=False): 120 | r''' 121 | 给定走时场初始状态,计算全局走时场 122 | 123 | .. note:: 最大差分阶数maxodr不建议取3,会有数值不稳定导致结果偏差的情况。默认取2。 124 | 125 | :param iniTT: 走时场初始状态 126 | :param xarr: :math:`x` 或 :math:`r` 节点坐标数组,要求等距升序排列 127 | :param yarr: :math:`y` 或 :math:`\theta` 节点坐标数组,要求等距升序排列 128 | :param yarr: :math:`z` 或 :math:`\phi` 节点坐标数组,要求等距升序排列 129 | :param slw: 形状为(nx, ny, nz)的三维慢度场 130 | :param maxodr: 使用的最大差分阶数, 1 or 2 or 3 131 | :param sphcoord: 是否为球坐标系 132 | :param printbar: 是否打印进度条 133 | :param useFSM: 是否改用Fast Sweeping Method计算全局走时场 134 | :param FSMeps: Fast Sweeping Method收敛条件,衡量Sweep后的最大更新量 135 | :param FSMmaxLoops: Fast Sweeping Method整体迭代次数(对于3D模型,向8个方向各Sweep一次为迭代一次) 136 | :param FSMparallel: 是否使用并行Fast Sweeping Method 137 | 138 | :return: 三维走时场 139 | ''' 140 | global FSM_nsweep 141 | 142 | check_xyz_arr(xarr, yarr, zarr, sphcoord) 143 | check_slowness(xarr, yarr, zarr, slw) 144 | 145 | # 对于并行情况,至少迭代两次 146 | if FSMparallel: 147 | if FSMmaxLoops <= 1: 148 | myLogger.warning("For parallel FSM, maxLoops must set at least 2 (already changed).") 149 | FSMmaxLoops = 2 150 | 151 | maxodr = int(maxodr) 152 | 153 | c_xarr = npct.as_ctypes(xarr.astype('f8')) 154 | c_yarr = npct.as_ctypes(yarr.astype('f8')) 155 | c_zarr = npct.as_ctypes(zarr.astype('f8')) 156 | slw_ravel = slw.ravel().astype(c_interfaces.NPCT_REAL_TYPE) 157 | c_slw = npct.as_ctypes(slw_ravel) 158 | 159 | TT_ravel = iniTT.ravel().astype(c_interfaces.NPCT_REAL_TYPE) 160 | c_TT = npct.as_ctypes(TT_ravel) 161 | 162 | FastFunc = c_interfaces.C_FastMarching if not useFSM else c_interfaces.C_FastSweeping 163 | parse_args = [ 164 | c_xarr, len(xarr), 165 | c_yarr, len(yarr), 166 | c_zarr, len(zarr), 167 | 0.0, 0.0, 0.0, 168 | maxodr, c_slw, 169 | c_TT, sphcoord, 170 | 0, 0, printbar 171 | ] 172 | if useFSM: 173 | parse_args.extend([FSMeps, FSMmaxLoops, FSMparallel]) 174 | 175 | FSM_nsweep = FastFunc(*parse_args) 176 | 177 | 178 | return TT_ravel.reshape(iniTT.shape) 179 | 180 | 181 | 182 | def raytracing( 183 | TT:np.ndarray, srcloc:list, rcvloc:list, 184 | xarr:np.ndarray, yarr:np.ndarray, zarr:np.ndarray, 185 | seglen:float, slw:Union[np.ndarray, None] = None, segfac:int=3, sphcoord:bool=False, maxdots:int=10000): 186 | r''' 187 | 根据给定源点坐标计算的走时场,使用梯度下降法做射线追踪 188 | 189 | :param TT: 走时场 190 | :param srcloc: 源点坐标,直角坐标系 :math:`(x,y,z)` 或球坐标系 :math:`(r,\theta,\phi)` 191 | :param rcvloc: 接收点坐标,直角坐标系 :math:`(x,y,z)` 或球坐标系 :math:`(r,\theta,\phi)` 192 | :param xarr: :math:`x` 或 :math:`r` 节点坐标数组,要求等距升序排列 193 | :param yarr: :math:`y` 或 :math:`\theta` 节点坐标数组,要求等距升序排列 194 | :param zarr: :math:`z` 或 :math:`\phi` 节点坐标数组,要求等距升序排列 195 | :param seglen: 射线段长度,与xyz的长度量纲保持一致 196 | :param slw: 形状为(nx, ny, nz)的三维慢度场,若非None则使用累加求和计算走时,否则直接从走时场中插值得到走时 197 | :param segfac: t < segfac*seglen/v,当射线追踪到在源点附近时,射线直接连接源点 198 | :param sphcoord: 是否使用球坐标 199 | :param maxdots: 射线最大点数 200 | 201 | :return: (接收点走时,形状为(ndots, 3)的射线坐标) 202 | ''' 203 | 204 | if isinstance(slw, np.ndarray): 205 | check_slowness(xarr, yarr, zarr, slw) 206 | 207 | sx, sy, sz = np.array(srcloc).astype('f8') 208 | rx, ry, rz = np.array(rcvloc).astype('f8') 209 | 210 | # 检查点的范围 211 | if sx < xarr[0] or sx > xarr[-1] or \ 212 | sy < yarr[0] or sy > yarr[-1] or \ 213 | sz < zarr[0] or sz > zarr[-1]: 214 | raise ValueError(f"Source ({str(srcloc)}) is out of bound.") 215 | if rx < xarr[0] or rx > xarr[-1] or \ 216 | ry < yarr[0] or ry > yarr[-1] or \ 217 | rz < zarr[0] or rz > zarr[-1]: 218 | raise ValueError(f"Receiver ({str(rcvloc)}) is out of bound.") 219 | 220 | if sx == xarr[0] or sx == xarr[-1] or \ 221 | sy == yarr[0] or sy == yarr[-1] or \ 222 | sz == zarr[0] or sz == zarr[-1]: 223 | myLogger.warning(f"Source ({str(srcloc)}) is on the boundary.") 224 | 225 | if rx == xarr[0] or rx == xarr[-1] or \ 226 | ry == yarr[0] or ry == yarr[-1] or \ 227 | rz == zarr[0] or rz == zarr[-1]: 228 | myLogger.warning(f"Receiver ({str(rcvloc)}) is on the boundary.") 229 | 230 | 231 | TT_ravel = TT.ravel().astype(c_interfaces.NPCT_REAL_TYPE) 232 | c_TT = npct.as_ctypes(TT_ravel) 233 | c_slw = None 234 | if slw is not None: 235 | slw_ravel = slw.ravel().astype(c_interfaces.NPCT_REAL_TYPE) 236 | c_slw = npct.as_ctypes(slw_ravel) 237 | 238 | c_xarr = npct.as_ctypes(xarr.astype('f8')) 239 | c_yarr = npct.as_ctypes(yarr.astype('f8')) 240 | c_zarr = npct.as_ctypes(zarr.astype('f8')) 241 | 242 | rays = np.empty((maxdots*3,), dtype='f8') 243 | c_rays = npct.as_ctypes(rays) 244 | c_ndots = c_interfaces.INT(maxdots) 245 | 246 | travt = c_interfaces.C_FMM_raytracing( 247 | c_xarr, len(xarr), 248 | c_yarr, len(yarr), 249 | c_zarr, len(zarr), 250 | sx, sy, sz, 251 | rx, ry, rz, float(seglen), int(segfac), 252 | c_slw, c_TT, sphcoord, 253 | c_rays, byref(c_ndots) 254 | ) 255 | 256 | # 对射线结果做检查 257 | if c_ndots.value >= maxdots: 258 | myLogger.warning(f"The number of dots exceed {maxdots}, and has been truncated. " 259 | "You may need to set larger seglen or set more maxdots.") 260 | 261 | return travt, rays.reshape((-1,3))[:c_ndots.value, ] 262 | 263 | 264 | 265 | def get_traveltime( 266 | TT:np.ndarray, rcvloc:list, 267 | xarr:np.ndarray, yarr:np.ndarray, zarr:np.ndarray): 268 | r''' 269 | 基于线性插值,从走时场中获取任一点的走时 270 | 271 | :param TT: 走时场 272 | :param rcvloc: 接收点坐标,直角坐标系 :math:`(x,y,z)` 或球坐标系 :math:`(r,\theta,\phi)` 273 | :param xarr: :math:`x` 或 :math:`r` 节点坐标数组,要求等距升序排列 274 | :param yarr: :math:`y` 或 :math:`\theta` 节点坐标数组,要求等距升序排列 275 | :param yarr: :math:`z` 或 :math:`\phi` 节点坐标数组,要求等距升序排列 276 | 277 | :return: 接收点走时 278 | 279 | ''' 280 | 281 | return float(interpolate.interpn((xarr, yarr, zarr), TT, np.array(rcvloc))) 282 | 283 | 284 | def check_xyz_arr( 285 | xarr:np.ndarray, yarr:np.ndarray, zarr:np.ndarray, sphcoord:bool): 286 | r''' 287 | 检查三个维度的数组是否符合基本要求 288 | ''' 289 | 290 | # 检查类型 291 | if not isinstance(xarr, np.ndarray): 292 | raise ValueError("xarr should be an instance of numpy.ndarray.") 293 | if not isinstance(yarr, np.ndarray): 294 | raise ValueError("yarr should be an instance of numpy.ndarray.") 295 | if not isinstance(zarr, np.ndarray): 296 | raise ValueError("zarr should be an instance of numpy.ndarray.") 297 | 298 | # 检查维数 299 | if len(xarr)==0: 300 | raise ValueError("xarr is empty.") 301 | if len(yarr)==0: 302 | raise ValueError("yarr is empty.") 303 | if len(zarr)==0: 304 | raise ValueError("zarr is empty.") 305 | 306 | # 检查是否升序排列 307 | if not np.all(xarr[1:] >= xarr[:-1]): 308 | raise ValueError("xarr should be in ascending order.") 309 | if not np.all(yarr[1:] >= yarr[:-1]): 310 | raise ValueError("yarr should be in ascending order.") 311 | if not np.all(zarr[1:] >= zarr[:-1]): 312 | raise ValueError("zarr should be in ascending order.") 313 | 314 | # 检查特殊点 315 | # if(sphcoord): 316 | # if np.any(xarr < 0.0): 317 | # raise ValueError("negative values in radius are not allowed.") 318 | 319 | # if np.any(xarr == 0.0): 320 | # print("WARNING! 0.0 in radius array, a slight offset (1e-5) is added.") 321 | # xarr[...] += 1e-5 322 | 323 | # if np.any(yarr < 0.0) or np.any(yarr > np.pi): 324 | # raise ValueError(f"Theta array is out of bound.") 325 | 326 | 327 | 328 | def check_slowness(xarr:np.ndarray, yarr:np.ndarray, zarr:np.ndarray, slw:np.ndarray): 329 | r''' 330 | 对慢度数组进行检查 331 | ''' 332 | if not isinstance(slw, np.ndarray): 333 | raise ValueError("slw should be an instance of numpy.ndarray.") 334 | 335 | if np.any(slw <= 0.0): 336 | raise ValueError("Slowness should be positive.") 337 | 338 | shapexyz = (len(xarr), len(yarr), len(zarr)) 339 | if slw.shape != shapexyz: 340 | raise ValueError(f"Shape of slowness should be {shapexyz}, but {slw.shape}.") 341 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build C programs and libraries, publish to PyPI and create a release 2 | 3 | on: 4 | workflow_dispatch: 5 | push: 6 | tags: 7 | - "v*.*.*" 8 | 9 | jobs: 10 | build: # 编译C库 11 | runs-on: ${{ matrix.os }} 12 | strategy: 13 | matrix: 14 | include: 15 | - os: windows-2022 16 | arch: x86_64 # windows x86_6 17 | - os: ubuntu-22.04 18 | arch: x86_64 # Ubuntu x86_64 19 | - os: macos-13 20 | arch: x86_64 # macOS Intel 21 | - os: macos-14 22 | arch: arm64 # macOS Apple Silicon 23 | 24 | fail-fast: true 25 | 26 | defaults: 27 | run: 28 | shell: bash 29 | 30 | steps: 31 | - name: Set MSYS2 (Windows) # windows平台使用MSYS2工具编译程序 32 | if: contains(matrix.os, 'windows') 33 | uses: msys2/setup-msys2@v2 34 | with: 35 | msystem: UCRT64 36 | install: >- 37 | git 38 | mingw-w64-ucrt-x86_64-gcc 39 | make 40 | 41 | - name: Configured git attributes for line endings (Windows) # 防止接下来在windows平台checkout代码时,文本文件的换行符发生变化,导致MSYS2工作出错 42 | if: contains(matrix.os, 'windows') 43 | run: git config --global core.autocrlf input 44 | 45 | - name: Checkout code # 下载库代码 46 | uses: actions/checkout@v3 47 | with: 48 | fetch-depth: 1 49 | 50 | # --------------------- 检查文件中的版本名是否和tag名相符 -------------------- 51 | - name: Check version 52 | run: | 53 | TAG_NAME=${{ github.ref_name }} 54 | PYVERSION_FILE="pyfmm/_version.py" 55 | 56 | # 提取 Python 版本号 57 | PYTHON_VERSION=$(sed -n 's/^__version__ = "\([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\)"/\1/p' ${PYVERSION_FILE}) 58 | if [ -z "$PYTHON_VERSION" ]; then 59 | echo "Error: Failed to extract version from ${PYVERSION_FILE}" 60 | exit 1 61 | fi 62 | 63 | # 检查 Python 版本与 Tag 是否匹配 64 | if [ "$PYTHON_VERSION" != "${TAG_NAME#v}" ]; then 65 | echo "Error: Version mismatch between tag (${TAG_NAME}) and ${PYVERSION_FILE} (${PYTHON_VERSION})" 66 | exit 1 67 | fi 68 | 69 | echo "Version check passed:" 70 | echo " Tag: ${TAG_NAME}" 71 | echo " Python version: ${PYTHON_VERSION}" 72 | 73 | # --------------------------- 安装依赖 ------------------------------------------ 74 | # - name: Install dependencies (Ubuntu) 75 | # if: contains(matrix.os, 'ubuntu') 76 | # run: | 77 | # sudo apt update 78 | # sudo apt install -y build-essential 79 | # 在 ubuntu 系统上创建低版本 glibc (2.17) 的环境进行编译,以提供向后兼容能力 80 | - name: Create CentOS 7.7 container (Ubuntu) 81 | if: contains(matrix.os, 'ubuntu') 82 | run: | 83 | CONTAINER_ID=$(docker create -v ${{ github.workspace }}:/workspace -w /workspace centos:7.7.1908 sleep infinity) 84 | echo "CONTAINER_ID=$CONTAINER_ID" >> $GITHUB_ENV 85 | docker start $CONTAINER_ID 86 | 87 | - name: Update yum in container (Ubuntu) 88 | if: contains(matrix.os, 'ubuntu') 89 | run: | 90 | docker exec ${{ env.CONTAINER_ID }} bash -c " 91 | mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup && \ 92 | curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo && \ 93 | yum clean all -y && yum makecache -y && yum install -y gcc make 94 | " 95 | 96 | - name: Install dependencies (macOS) 97 | # 匹配包含 "macos" 的操作系统 98 | if: contains(matrix.os, 'macos') 99 | run: | 100 | brew install libomp 101 | 102 | # ----------------- 编译C库和C程序 ---------------------------------- 103 | - name: Build the project (macOS) 104 | if: contains(matrix.os, 'macos') 105 | working-directory: ./pyfmm/C_extension 106 | run: | 107 | make ARCH="-arch ${{ matrix.arch }}" \ 108 | CC=gcc-14 109 | 110 | make cleanbuild 111 | otool -L lib/*.so 112 | 113 | # - name: Build the project (Ubuntu) 114 | # if: contains(matrix.os, 'ubuntu') 115 | # working-directory: ./pyfmm/C_extension 116 | # run: | 117 | # make 118 | # make cleanbuild 119 | # ldd lib/*.so 120 | 121 | - name: Build the project in container (Ubuntu) 122 | if: contains(matrix.os, 'ubuntu') 123 | working-directory: 124 | run: | 125 | docker exec ${{ env.CONTAINER_ID }} bash -c "cd pyfmm/C_extension && ls && make && make cleanbuild && cd -" 126 | cd ./pyfmm/C_extension 127 | ldd lib/*.so 128 | cd - 129 | 130 | - name: Cleanup container (Ubuntu) 131 | if: contains(matrix.os, 'ubuntu') 132 | run: | 133 | docker stop ${{ env.CONTAINER_ID }} 134 | docker rm ${{ env.CONTAINER_ID }} 135 | 136 | - name: Build the project (Windows) 137 | if: contains(matrix.os, 'windows') 138 | shell: msys2 {0} 139 | working-directory: ./pyfmm/C_extension 140 | run: | 141 | make 142 | make cleanbuild 143 | ldd lib/*.so 144 | 145 | 146 | # ------------------------ 定义接下来打包程序命名时的系统名后缀 --------------- 147 | - name: Define the package OS suffix 148 | run: | 149 | # 符合pypi命名规范,否则上传失败 150 | if [[ "${{ matrix.os }}" == *"ubuntu"* ]]; then 151 | SUFFIX_PLAT_NAME="manylinux2014_x86_64" 152 | elif [[ "${{ matrix.os }}" == *"macos"* && "${{ matrix.arch }}" == *"x86_64"* ]]; then 153 | SUFFIX_PLAT_NAME="macosx_10_9_x86_64" 154 | elif [[ "${{ matrix.os }}" == *"macos"* && "${{ matrix.arch }}" == *"arm64"* ]]; then 155 | SUFFIX_PLAT_NAME="macosx_11_0_arm64" 156 | elif [[ "${{ matrix.os }}" == *"windows"* ]]; then 157 | SUFFIX_PLAT_NAME="win_amd64" 158 | else 159 | echo " Unsupported OS: ${{ matrix.os }} (${{ matrix.arch }})" 160 | exit 1 161 | fi 162 | 163 | echo "SUFFIX_PLAT_NAME=$SUFFIX_PLAT_NAME" >> $GITHUB_ENV 164 | 165 | # --------------------------- 打包整个程序 --------------------- 166 | - name: Package the binary 167 | run: | 168 | PACK_NAME=pyfmm_kit-${{ github.ref_name }}-${{ env.SUFFIX_PLAT_NAME }} 169 | echo "PACK_NAME=$PACK_NAME" >> $GITHUB_ENV 170 | FILE_CONTENT=$(ls -A) 171 | mkdir -p $PACK_NAME 172 | cp -r ${FILE_CONTENT} $PACK_NAME/ 173 | tar -czvf $PACK_NAME.tar.gz $PACK_NAME 174 | rm -rf $PACK_NAME 175 | 176 | # -------------------- upload artifacts ----------------------- 177 | - name: Upload artifact (*.tar.gz) 178 | uses: actions/upload-artifact@v4 179 | with: 180 | name: ${{ matrix.os }}-${{ matrix.arch }}_tar 181 | path: ${{ env.PACK_NAME }}.tar.gz 182 | 183 | 184 | # ======================================================================================= 185 | test_project: # 在全新系统上测试程序,不安装其它依赖,看能否运行 186 | runs-on: ${{ matrix.os }} 187 | needs: build 188 | strategy: 189 | matrix: 190 | include: 191 | - os: windows-2022 192 | arch: x86_64 # windows x86_6 193 | - os: ubuntu-22.04 194 | arch: x86_64 # Ubuntu x86_64 195 | - os: macos-13 196 | arch: x86_64 # macOS Intel 197 | - os: macos-14 198 | arch: arm64 # macOS Apple Silicon 199 | 200 | fail-fast: true 201 | 202 | defaults: 203 | run: 204 | shell: bash 205 | 206 | steps: 207 | - name: Download artifacts 208 | uses: actions/download-artifact@v4 209 | with: 210 | name: ${{ matrix.os }}-${{ matrix.arch }}_tar 211 | path: artifacts 212 | 213 | - name: Display structure of downloaded files, and Uncompress 214 | run: | 215 | ls -R artifacts 216 | echo "------------------- tar output -----------------------------" 217 | tar -xzvf artifacts/*.tar.gz 218 | echo "------------------------------------------------------------" 219 | 220 | # 获得压缩包解压出来的文件夹名 221 | PACK_NAME=$(ls | grep pyfmm_kit) 222 | echo "PACK_NAME=$PACK_NAME" >> $GITHUB_ENV 223 | 224 | # 从解压出的文件夹命名来推断${{ env.SUFFIX_PLAT_NAME }} 225 | SUFFIX_PLAT_NAME=$(echo $PACK_NAME | sed 's/.*-\(.*\)/\1/') 226 | echo "SUFFIX_PLAT_NAME=$SUFFIX_PLAT_NAME" >> $GITHUB_ENV 227 | 228 | echo $PACK_NAME 229 | echo $SUFFIX_PLAT_NAME 230 | 231 | # --------------------------- 安装依赖 ------------------------------------------ 232 | # 实际使用时可能需要安装libomp 233 | # - name: Install libomp (Ubuntu) 234 | # if: contains(matrix.os, 'ubuntu') 235 | # run: | 236 | # sudo apt install -y libomp-dev 237 | 238 | # - name: Set alias (MacOS) 239 | # if: contains(matrix.os, 'macos') 240 | # run: | 241 | # brew install coreutils 242 | # echo "alias timeout=gtimeout" >> ~/.bashrc 243 | 244 | # --------------------搭建python环境,开始测试,并制作wheel文件 ------------------------------ 245 | - name: Set up Python 246 | uses: actions/setup-python@v4 247 | with: 248 | python-version: '3.9' 249 | 250 | - name: Install dependencies 251 | working-directory: ${{ env.PACK_NAME }} 252 | run: | 253 | python -m pip install --upgrade pip 254 | pip install --upgrade setuptools wheel build 255 | pip install -v . 256 | 257 | - name: Clean up build and egg-info directories 258 | working-directory: ${{ env.PACK_NAME }} 259 | run: | 260 | # 清理临时文件 261 | rm -rf build/ 262 | rm -rf pyfmm_kit.egg-info/ 263 | 264 | - name: Test 265 | working-directory: ${{ env.PACK_NAME }}/.github/tests 266 | run: | 267 | python uniform.py 268 | 269 | # --------------------------- 制作wheels --------------------- 270 | - name: Build the Python Wheel 271 | working-directory: ${{ env.PACK_NAME }} 272 | run: | 273 | python setup.py bdist_wheel --plat-name=${{ env.SUFFIX_PLAT_NAME }} # 只制作wheel,这里不打包源码 274 | 275 | - name: Upload artifact (*.whl) 276 | uses: actions/upload-artifact@v4 277 | with: 278 | name: ${{ env.PACK_NAME }}_whl 279 | path: ${{ env.PACK_NAME }}/dist/*.whl 280 | 281 | 282 | # =============================================================================== 283 | publish_pypi: # 上传pypi 284 | runs-on: ubuntu-latest 285 | needs: test_project 286 | permissions: 287 | id-token: write 288 | contents: read 289 | defaults: 290 | run: 291 | shell: bash 292 | 293 | 294 | steps: 295 | - name: Download artifacts 296 | uses: actions/download-artifact@v4 297 | with: 298 | pattern: "*_whl" 299 | path: artifacts 300 | 301 | - name: Display structure of downloaded files 302 | run: ls -R artifacts 303 | 304 | - name: Move wheel files to dist/ 305 | run: | 306 | mkdir -p dist 307 | mv artifacts/*/*.whl dist/ 308 | 309 | - name: Pypi Publish 310 | uses: pypa/gh-action-pypi-publish@release/v1 311 | with: 312 | packages-dir: dist/ 313 | 314 | 315 | # =============================================================================== 316 | release: # 创建Release 317 | runs-on: ubuntu-latest 318 | needs: [build, test_project] 319 | permissions: 320 | contents: write 321 | 322 | defaults: 323 | run: 324 | shell: bash 325 | 326 | steps: 327 | - name: Download artifacts 328 | uses: actions/download-artifact@v4 329 | with: 330 | path: artifacts 331 | pattern: "*_tar" 332 | 333 | - name: Download artifacts (*.whl) 334 | uses: actions/download-artifact@v4 335 | with: 336 | path: artifacts 337 | pattern: "*_whl" 338 | 339 | - name: Display structure of downloaded files 340 | run: ls -R artifacts 341 | 342 | # 对artifacts中的每个tar.gz文件,根据其内部的文件夹名重新命名压缩包 343 | - name: Rename tar.gz files 344 | run: | 345 | mkdir -p release 346 | for file in artifacts/*/*.tar.gz; do 347 | TEMP_FILE=tmp 348 | # 这里不能把tar合并到下方的管道中,在github actions中会报错 349 | tar -tzf $file > $TEMP_FILE 350 | PACK_NAME=$(head -n 1 $TEMP_FILE | cut -f 1 -d '/') 351 | mv $file release/${PACK_NAME}.tar.gz 352 | rm $TEMP_FILE 353 | done 354 | 355 | ls -R release 356 | 357 | - name: Move wheel files to dist/ 358 | run: | 359 | mkdir -p dist 360 | mv artifacts/*/*.whl dist/ 361 | 362 | - name: Create Release 363 | id: create_release 364 | uses: softprops/action-gh-release@v1 365 | env: 366 | GITHUB_TOKEN: ${{ secrets.GH_PAT }} 367 | with: 368 | draft: true 369 | files: | 370 | release/*.tar.gz 371 | dist/*.whl 372 | 373 | 374 | 375 | 376 | -------------------------------------------------------------------------------- /pyfmm/C_extension/src/fmm.c: -------------------------------------------------------------------------------- 1 | /** 2 | * @file fmm.c 3 | * @author Zhu Dengda (zhudengda@mail.iggcas.ac.cn) 4 | * @date 2023-03 5 | * 6 | */ 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | 17 | #include "const.h" 18 | #include "interp.h" 19 | #include "query.h" 20 | #include "coord.h" 21 | #include "mallocfree.h" 22 | #include "diff.h" 23 | #include "heapsort.h" 24 | #include "index.h" 25 | #include "progressbar.h" 26 | #include "fmm.h" 27 | 28 | 29 | 30 | void FastMarching( 31 | const double *rs, MYINT nr, 32 | const double *ts, MYINT nt, 33 | const double *ps, MYINT np, 34 | double rr, double tt, double pp, 35 | MYINT maxodr, const MYREAL *Slw, 36 | MYREAL *TT, bool sphcoord, 37 | MYINT rfgfac, MYINT rfgn, bool printbar) 38 | { 39 | // 程序运行开始时间 40 | struct timeval begin_t; 41 | gettimeofday(&begin_t, NULL); 42 | 43 | MYINT ntp=nt*np; 44 | MYINT nrtp=nr*ntp; 45 | MYINT Ndots=nrtp; 46 | 47 | char *FMM_stat = (char *)malloc1d(nrtp, sizeof(char)); // 1 alive, 0 close, -1 far 48 | 49 | MYINT heapsize=0, heapcapcity=nr*nt + nt*np + nr*np; 50 | MYINT *psize, *pcap; 51 | psize = &heapsize; 52 | pcap = &heapcapcity; 53 | HEAP_DATA *FMM_data = (HEAP_DATA *)malloc1d(heapcapcity, sizeof(HEAP_DATA)); 54 | MYINT *NroIdx = (MYINT *)malloc1d(nrtp, sizeof(MYINT)); 55 | 56 | // All non-zero value of TT will be treated as efficient value, 57 | // and set FMM_CLS 58 | bool allzeroTT = true; 59 | for(MYINT i=0; i1 && rfgn>=1){ 76 | FMM_data = init_source_TT_refinegrid( 77 | rs, nr, ts, nt, ps, np, 78 | rr, tt, pp, 79 | maxodr, Slw, TT, 80 | FMM_stat, sphcoord, 81 | rfgfac, rfgn, printbar, 82 | FMM_data, psize, pcap, NroIdx, &Ndots); 83 | } else { 84 | FMM_data = init_source_TT( 85 | rs, nr, ts, nt, ps, np, 86 | rr, tt, pp, 87 | Slw, TT, 88 | FMM_stat, sphcoord, 89 | FMM_data, psize, pcap, NroIdx, &Ndots); 90 | } 91 | } 92 | 93 | // print_FMM_HEAP(FMM_data, *psize, nr, nt, np, NroIdx, TT, NULL, NULL, NULL); 94 | 95 | FMM_data = FastMarching_with_initial( 96 | rs, nr, 97 | ts, nt, 98 | ps, np, 99 | maxodr, Slw, TT, 100 | FMM_stat, sphcoord, NULL, printbar, 101 | FMM_data, psize, pcap, NroIdx, &Ndots); 102 | 103 | // printf("done, Ndots=%d, size=%d\n", Ndots, *psize); 104 | free(FMM_data); 105 | free(FMM_stat); 106 | free(NroIdx); 107 | 108 | 109 | // 程序运行结束时间 110 | struct timeval end_t; 111 | gettimeofday(&end_t, NULL); 112 | if(printbar) printf("Runtime: %.3f s\n", (end_t.tv_sec - begin_t.tv_sec) + (end_t.tv_usec - begin_t.tv_usec) / 1e6); 113 | fflush(stdout); 114 | } 115 | 116 | 117 | 118 | 119 | HEAP_DATA * FastMarching_with_initial( 120 | const double *rs, MYINT nr, 121 | const double *ts, MYINT nt, 122 | const double *ps, MYINT np, 123 | MYINT maxodr, const MYREAL *Slw, MYREAL *TT, 124 | char *FMM_stat, bool sphcoord, bool *edgeStop, bool printbar, 125 | HEAP_DATA *FMM_data, MYINT *psize, MYINT *pcap, MYINT *NroIdx, MYINT *pNdots) 126 | { 127 | double dr = (nr>1)? rs[1] - rs[0] : 0.0; 128 | double dt = (nt>1)? ts[1] - ts[0] : 0.0; 129 | double dp = (np>1)? ps[1] - ps[0] : 0.0; 130 | 131 | // DON'T CHANGE. 132 | static const char xr[6] = {-1, 1, 0, 0, 0, 0}; 133 | static const char xt[6] = { 0, 0, -1, 1, 0, 0}; 134 | static const char xp[6] = { 0, 0, 0, 0, -1, 1}; 135 | 136 | // convenient arrays 137 | double sin_ts[nt]; 138 | if(sphcoord){ 139 | for(MYINT it=0; it 0){ 165 | 166 | // get the minimum one 167 | popdata = HeapPop(FMM_data, psize, NroIdx, TT); 168 | idx0 = popdata; 169 | FMM_stat[idx0] = FMM_ALV; 170 | 171 | unravel_index(idx0, ntp, np, &ir0, &it0, &ip0); 172 | travt0 = TT[idx0]; 173 | 174 | // break loop in advance when reach the boundary 175 | if( edgeStop!=NULL && ( 176 | (edgeStop[0]&&ir0==0) || (edgeStop[1]&&ir0==nr-1) || 177 | (edgeStop[2]&&it0==0) || (edgeStop[3]&&it0==nt-1) || 178 | (edgeStop[4]&&ip0==0) || (edgeStop[5]&&ip0==np-1))) break; 179 | 180 | 181 | 182 | if(travt0 > maxtravt) maxtravt = travt0; 183 | else if(travt0 < maxtravt){ 184 | // 当在源点附近使用加密网格时,由于需要使用一般方法初始化源点附近的走时, 185 | printf("pNdots=%d, WRONG! travt0(%f) < maxtravt(%f) \n", *pNdots, travt0, maxtravt); 186 | print_HEAP(FMM_data, *psize, nr, nt, np, NroIdx, TT, NULL, NULL, NULL); 187 | printf("Tiny bug here, please let author know.\n"); 188 | } 189 | 190 | // get neighbours (max 6) 191 | for(char k=0; k<6; ++k){ 192 | 193 | ir = ir0 + xr[k]; 194 | it = it0 + xt[k]; 195 | ip = ip0 + xp[k]; 196 | 197 | 198 | if(ir<0 || ir>nr-1) continue; 199 | if(it<0 || it>nt-1) continue; 200 | if(ip<0 || ip>np-1) continue; 201 | 202 | ravel_index(&idx, ntp, np, ir, it, ip); 203 | // idx6_bak[k] = idx; 204 | 205 | pstat = FMM_stat+idx; 206 | // skip alive point 207 | if(*pstat == FMM_ALV) continue; 208 | 209 | if(k<2){ 210 | h = dr; 211 | } else if(k<4){ 212 | h = dt; 213 | if(sphcoord) h *= rs[ir]; 214 | } else if(k<6){ 215 | h = dp; 216 | if(sphcoord) h *= rs[ir]*sin_ts[it]; 217 | } else { 218 | fprintf(stderr, "BAD interval h\n"); 219 | exit(EXIT_FAILURE); 220 | } 221 | 222 | s = Slw[idx]; 223 | 224 | travt1 = travt0 + h*s; 225 | // compute traveltime 226 | pt = TT+idx; 227 | travt_bak = *pt; 228 | if(travt1 < travt_bak) *pt = travt1; 229 | 230 | if(sphcoord){ 231 | travt = get_neighbour_travt( 232 | nr, nt, np, ntp, 233 | ir, it, ip, idx, 234 | maxodr, TT, 235 | FMM_stat, s, dr, dt*rs[ir], dp*rs[ir]*sin_ts[it], 236 | &travt_stat); 237 | } else { 238 | travt = get_neighbour_travt( 239 | nr, nt, np, ntp, 240 | ir, it, ip, idx, 241 | maxodr, TT, 242 | FMM_stat, s, dr, dt, dp, 243 | &travt_stat); 244 | } 245 | 246 | // printf("k, travt, travt_bak = %d, %f, %f\n", k, travt, travt_bak); 247 | *pt = travt_bak; 248 | if(travt_stat<0 || travt<0) { 249 | // printf("get_neighbour_travt failed, use the lazy one.\n"); 250 | travt = travt1; 251 | } 252 | 253 | // Forced Causality 254 | if(travt < maxtravt) travt = maxtravt; 255 | 256 | if(travt < TT[idx]){ 257 | // printf("get, travt, TT[idx] = %f, %f\n", travt, TT[idx]); 258 | TT[idx] = travt; 259 | 260 | if(*pstat == FMM_CLS){ // CLOSE 261 | MinHeap_AdjustUp(FMM_data, NroIdx[idx], NroIdx, TT); 262 | } 263 | else if(*pstat == FMM_FAR){ // FAR 264 | newdata= idx; 265 | FMM_data = HeapPush(FMM_data, psize, pcap, newdata, NroIdx, TT); 266 | *pstat = FMM_CLS; 267 | (*pNdots)--; 268 | } 269 | 270 | } 271 | // print_FMM_HEAP(FMM_data, *psize, nr, nt, np, NroIdx, TT, gTr, gTt, gTp); 272 | 273 | } 274 | 275 | 276 | // 打印进度条 277 | barpercent = 100.0 - (double)(*pNdots) / (double)(size_bak) * 100.0; 278 | if(printbar && barpercent != last_barpercent){ 279 | printprogressBar("Fast Marching... ", barpercent); 280 | // printf("\npNdots=%d, barpercent=%d, size_bak=%d\n", *pNdots, barpercent, size_bak); 281 | last_barpercent = barpercent; 282 | } 283 | 284 | } 285 | 286 | 287 | return FMM_data; 288 | } 289 | 290 | 291 | 292 | 293 | 294 | HEAP_DATA * init_source_TT( 295 | const double *rs, MYINT nr, 296 | const double *ts, MYINT nt, 297 | const double *ps, MYINT np, 298 | double rr, double tt, double pp, 299 | const MYREAL *Slw, MYREAL *TT, 300 | char *FMM_stat, bool sphcoord, 301 | HEAP_DATA *FMM_data, MYINT *psize, MYINT *pcap, MYINT *NroIdx, MYINT *pNdots) 302 | { 303 | MYINT ir, it, ip; 304 | ir = dicho_find(rs, nr, rr); 305 | it = dicho_find(ts, nt, tt); 306 | ip = dicho_find(ps, np, pp); 307 | if(ir==nr-1 && ir>0) ir--; 308 | if(it==nt-1 && it>0) it--; 309 | if(ip==np-1 && ip>0) ip--; 310 | 311 | 312 | double xx, yy, zz; 313 | if(sphcoord) rtp2xyz(rr, tt, pp, &xx, &yy, &zz); 314 | 315 | 316 | HEAP_DATA newdata; 317 | MYREAL travt, s; 318 | MYINT jr, jt, jp; 319 | MYINT jdx; 320 | double dist; 321 | double r2, t2, p2, dr, dt, dp; 322 | double x2, y2, z2; 323 | double dx, dy, dz; 324 | 325 | MYREAL mtravt=9.9e30; 326 | MYINT mir, mit, mip, midx=0; // 最小走时节点的索引 327 | 328 | // Tiny 2x2x2 cube 329 | for(char kr=0; kr<2; ++kr){ 330 | jr = ir+kr; 331 | if(jr > nr-1) continue; 332 | 333 | r2 = rs[jr]; 334 | dr = r2 - rr; 335 | for(char kt=0; kt<2; ++kt){ 336 | jt = it+kt; 337 | if(jt > nt-1) continue; 338 | 339 | t2 = ts[jt]; 340 | dt = t2 - tt; 341 | for(char kp=0; kp<2; ++kp){ 342 | jp = ip+kp; 343 | if(jp > np-1) continue; 344 | 345 | p2 = ps[jp]; 346 | dp = p2 - pp; 347 | 348 | if(sphcoord) rtp2xyz(r2, t2, p2, &x2, &y2, &z2); 349 | 350 | ravel_index(&jdx, nt*np, np, jr, jt, jp); 351 | s = Slw[jdx]; 352 | 353 | if(sphcoord){ 354 | dx = x2-xx; 355 | dy = y2-yy; 356 | dz = z2-zz; 357 | dist = sqrt(dx*dx + dy*dy + dz*dz); 358 | } else { 359 | dist = sqrt(dr*dr + dt*dt + dp*dp); 360 | } 361 | 362 | 363 | travt = dist * s; 364 | TT[jdx] = travt; 365 | if(mtravt > travt){ 366 | midx = jdx; 367 | mtravt = travt; 368 | } 369 | 370 | if(FMM_data!=NULL){ 371 | newdata = jdx; 372 | FMM_data = HeapPush(FMM_data, psize, pcap, newdata, NroIdx, TT); 373 | } 374 | 375 | if(FMM_stat!=NULL) FMM_stat[jdx] = FMM_CLS; 376 | // print_FMM_HEAP(FMM_data, *psize, nr, nt, np, NroIdx); 377 | 378 | if(pNdots!=NULL) (*pNdots)--; 379 | // return FMM_data; 380 | } 381 | } 382 | } 383 | 384 | // set the node with minimum traveltime `alive` 385 | if(FMM_data!=NULL){ 386 | HEAP_DATA popdata; 387 | popdata = HeapPop(FMM_data, psize, NroIdx, TT); 388 | midx = popdata; 389 | } 390 | if(FMM_stat!=NULL) FMM_stat[midx] = FMM_ALV; 391 | 392 | 393 | unravel_index(midx, nt*np, np, &mir, &mit, &mip); 394 | // Full 3x3x3 cube 395 | for(char kr=-1; kr<2; ++kr){ 396 | jr = mir+kr; 397 | if(jr<0 || jr>nr-1) continue; 398 | 399 | r2 = rs[jr]; 400 | dr = r2 - rr; 401 | for(char kt=-1; kt<2; ++kt){ 402 | jt = mit+kt; 403 | if(jt<0 || jt>nt-1) continue; 404 | 405 | t2 = ts[jt]; 406 | dt = t2 - tt; 407 | for(char kp=-1; kp<2; ++kp){ 408 | jp = mip+kp; 409 | if(jp<0 || jp>np-1) continue; 410 | 411 | p2 = ps[jp]; 412 | dp = p2 - pp; 413 | 414 | if(sphcoord) rtp2xyz(r2, t2, p2, &x2, &y2, &z2); 415 | 416 | ravel_index(&jdx, nt*np, np, jr, jt, jp); 417 | 418 | if(FMM_stat!=NULL && FMM_stat[jdx] != FMM_FAR) continue; 419 | 420 | s = Slw[jdx]; 421 | 422 | if(sphcoord){ 423 | dx = x2-xx; 424 | dy = y2-yy; 425 | dz = z2-zz; 426 | dist = sqrt(dx*dx + dy*dy + dz*dz); 427 | } else { 428 | dist = sqrt(dr*dr + dt*dt + dp*dp); 429 | } 430 | 431 | 432 | travt = dist * s; 433 | TT[jdx] = travt; 434 | 435 | if(FMM_data!=NULL){ 436 | newdata = jdx; 437 | FMM_data = HeapPush(FMM_data, psize, pcap, newdata, NroIdx, TT); 438 | } 439 | 440 | if(FMM_stat!=NULL) FMM_stat[jdx] = FMM_CLS; 441 | // print_FMM_HEAP(FMM_data, *psize, nr, nt, np, NroIdx); 442 | 443 | if(pNdots!=NULL) (*pNdots)--; 444 | } 445 | } 446 | } 447 | 448 | // print_HEAP(FMM_data, *psize, nr, nt, np, NroIdx, TT, NULL, NULL, NULL); 449 | 450 | return FMM_data; 451 | } 452 | 453 | 454 | 455 | HEAP_DATA * init_source_TT_refinegrid( 456 | const double *rs, MYINT nr, 457 | const double *ts, MYINT nt, 458 | const double *ps, MYINT np, 459 | double rr, double tt, double pp, 460 | MYINT maxodr, const MYREAL *Slw, MYREAL *TT, 461 | char *FMM_stat, bool sphcoord, 462 | MYINT rfgfac, MYINT rfgn, // refine grid factor and number of grids 463 | bool printbar, 464 | HEAP_DATA *FMM_data, MYINT *psize, MYINT *pcap, MYINT *NroIdx, MYINT *pNdots) 465 | { 466 | double dr = (nr>1)? rs[1] - rs[0] : 0.0; 467 | double dt = (nt>1)? ts[1] - ts[0] : 0.0; 468 | double dp = (np>1)? ps[1] - ps[0] : 0.0; 469 | 470 | MYINT ntp=nt*np; 471 | 472 | // find the closest point 473 | MYINT ir, it, ip; 474 | ir = dicho_find(rs, nr, rr); 475 | it = dicho_find(ts, nt, tt); 476 | ip = dicho_find(ps, np, pp); 477 | if(ir0) rfg_ir1--; 496 | if(rfg_ir20) rfg_it1--; 498 | if(rfg_it20) rfg_ip1--; 500 | if(rfg_ip2=0) jdx2 = jdx; 592 | 593 | TT[jdx] = rfg_TT[rfg_jdx]; 594 | // printf("rfg_TT = %f, jr, jt, jp %d, %d, %d\n", rfg_TT[rfg_jdx], jr, jt, jp); 595 | FMM_stat[jdx] = FMM_ALV; 596 | if(pNdots!=NULL) (*pNdots)--; 597 | } 598 | if(jdx1>=0){ 599 | FMM_data = HeapPush(FMM_data, psize, pcap, jdx1, NroIdx, TT); 600 | FMM_stat[jdx1] = FMM_CLS; 601 | } 602 | if(jdx2>=0 && jdx2!=jdx1){ 603 | FMM_data = HeapPush(FMM_data, psize, pcap, jdx2, NroIdx, TT); 604 | FMM_stat[jdx2] = FMM_CLS; 605 | } 606 | 607 | }} 608 | 609 | free(rfg_TT); 610 | free(rfg_Slw); 611 | free(rfg_rs); 612 | free(rfg_ts); 613 | free(rfg_ps); 614 | 615 | free(rfg_FMM_data); 616 | free(rfg_NroIdx); 617 | 618 | 619 | return FMM_data; 620 | } 621 | 622 | 623 | 624 | 625 | 626 | MYREAL get_neighbour_travt( 627 | MYINT nr, MYINT nt, MYINT np, MYINT ntp, 628 | MYINT ir, MYINT it, MYINT ip, MYINT idx, 629 | MYINT maxodr, MYREAL *TT, 630 | char *FMM_stat, double s, 631 | double dr, double dt, double dp, 632 | char *stat) 633 | { 634 | if(stat!=NULL) *stat = 0; 635 | 636 | double Acoef, Bcoef, Ccoef; 637 | Acoef = Bcoef = 0.0; 638 | Ccoef = - s*s; 639 | 640 | MYREAL tarr[5], tarrR[5], tarrT[5], tarrP[5]; // max(maxodr) = 3 641 | tarr[0] = tarrR[0] = tarrT[0] = tarrP[0] = TT[idx]; 642 | MYINT odr, odrR, odrT, odrP; 643 | odr = odrR = odrT = odrP = 0; 644 | 645 | MYINT jdx; 646 | MYINT i; 647 | 648 | char sgn_r, sgn_t, sgn_p; 649 | sgn_r = sgn_t = sgn_p = 0; 650 | double dif, pos_dif, neg_dif; 651 | double acoef, bcoef; 652 | double pos_acoef, neg_acoef, pos_bcoef, neg_bcoef; 653 | //------------------------------------------- R --------------------------------------- 654 | // --------------------------------------- negative ----------------------------------- 655 | for(odr=0; odr= TT[jdx+ntp]) break; 661 | } 662 | get_diff_odr123(odr, tarr, dr, &neg_acoef, &neg_bcoef, &neg_dif); 663 | // --------------------------------------- positive ----------------------------------- 664 | for(odrR=0; odrRnr-1) break; 666 | jdx = idx + (odrR+1)*ntp; 667 | if(FMM_stat[jdx]!=FMM_ALV) break; 668 | tarrR[odrR+1] = TT[jdx]; 669 | if(tarrR[odrR+1] >= TT[jdx-ntp]) break; 670 | } 671 | get_diff_odr123(odrR, tarrR, dr, &pos_acoef, &pos_bcoef, &pos_dif); 672 | // compare positive and negative 673 | if(neg_dif < pos_dif){ 674 | dif = pos_dif; 675 | acoef = pos_acoef; // ignore *(-1) 676 | bcoef = pos_bcoef; // ignore *(-1) 677 | sgn_r = -1; 678 | } else { 679 | dif = neg_dif; 680 | acoef = neg_acoef; 681 | bcoef = neg_bcoef; 682 | sgn_r = 1; 683 | odrR = odr; 684 | for(i=0; i<=odrR; tarrR[i]=tarr[i], ++i); 685 | } 686 | if(dif < 0.0) acoef = bcoef = 0.0; 687 | Acoef += acoef*acoef; 688 | Bcoef += 2*acoef*bcoef; 689 | Ccoef += bcoef*bcoef; 690 | 691 | 692 | //------------------------------------------- T --------------------------------------- 693 | // --------------------------------------- negative ----------------------------------- 694 | for(odr=0; odr= TT[jdx+np]) break; 700 | } 701 | get_diff_odr123(odr, tarr, dt, &neg_acoef, &neg_bcoef, &neg_dif); 702 | // --------------------------------------- positive ----------------------------------- 703 | for(odrT=0; odrTnt-1) break; 705 | jdx = idx + (odrT+1)*np; 706 | if(FMM_stat[jdx]!=FMM_ALV) break; 707 | tarrT[odrT+1] = TT[jdx]; 708 | if(tarrT[odrT+1] >= TT[jdx-np]) break; 709 | } 710 | get_diff_odr123(odrT, tarrT, dt, &pos_acoef, &pos_bcoef, &pos_dif); 711 | // compare positive and negative 712 | if(neg_dif < pos_dif){ 713 | dif = pos_dif; 714 | acoef = pos_acoef; // ignore *(-1) 715 | bcoef = pos_bcoef; // ignore *(-1) 716 | sgn_t = -1; 717 | } else { 718 | dif = neg_dif; 719 | acoef = neg_acoef; 720 | bcoef = neg_bcoef; 721 | sgn_t = 1; 722 | odrT = odr; 723 | for(i=0; i<=odrT; tarrT[i]=tarr[i], ++i); 724 | } 725 | if(dif < 0.0){ 726 | acoef = bcoef = 0.0; 727 | } 728 | Acoef += acoef*acoef; 729 | Bcoef += 2*acoef*bcoef; 730 | Ccoef += bcoef*bcoef; 731 | 732 | 733 | //------------------------------------------- P --------------------------------------- 734 | // --------------------------------------- negative ----------------------------------- 735 | for(odr=0; odr= TT[jdx+1]) break; 741 | } 742 | get_diff_odr123(odr, tarr, dp, &neg_acoef, &neg_bcoef, &neg_dif); 743 | // --------------------------------------- positive ----------------------------------- 744 | for(odrP=0; odrPnp-1) break; 746 | jdx = idx + (odrP+1); 747 | if(FMM_stat[jdx]!=FMM_ALV) break; 748 | tarrP[odrP+1] = TT[jdx]; 749 | if(tarrP[odrP+1] >= TT[jdx-1]) break; 750 | } 751 | get_diff_odr123(odrP, tarrP, dp, &pos_acoef, &pos_bcoef, &pos_dif); 752 | // compare positive and negative 753 | if(neg_dif < pos_dif){ 754 | dif = pos_dif; 755 | acoef = pos_acoef; // ignore *(-1) 756 | bcoef = pos_bcoef; // ignore *(-1) 757 | sgn_p = -1; 758 | } else { 759 | dif = neg_dif; 760 | acoef = neg_acoef; 761 | bcoef = neg_bcoef; 762 | sgn_p = 1; 763 | odrP = odr; 764 | for(i=0; i<=odrP; tarrP[i]=tarr[i], ++i); 765 | } 766 | if(dif < 0.0){ 767 | acoef = bcoef = 0.0; 768 | } 769 | Acoef += acoef*acoef; 770 | Bcoef += 2*acoef*bcoef; 771 | Ccoef += bcoef*bcoef; 772 | 773 | 774 | 775 | 776 | //-------------------------------------------------- 777 | // solve second-order equation with one unknown 778 | // (A*T^2 - B*T + C = 0) 779 | double jdg = Bcoef*Bcoef - 4*Acoef*Ccoef; 780 | if(jdg <= 0.0) jdg = 0.0; 781 | if(fabs(Acoef)<1e-10 || fabs(Bcoef)<1e-10){ 782 | if(stat!=NULL) *stat = -1; 783 | #if _PRINT_ODR_BUG_ == 1 784 | printf("Acoef, Bcoef, Ccoef = %f, %f, %f\n", Acoef, Bcoef, Ccoef); 785 | printf("jdg=%f <= 0.0\n", jdg); 786 | getchar(); 787 | #endif 788 | return -1.0; 789 | } 790 | 791 | 792 | jdg = sqrt(jdg); 793 | #if _PRINT_ODR_BUG_ == 1 794 | { 795 | printf("Acoef, Bcoef, Ccoef = %f, %f, %f\n", Acoef, Bcoef, Ccoef); 796 | printf("res=%f\n", (Bcoef + jdg)/(2*Acoef)); 797 | // getchar(); 798 | } 799 | #endif 800 | return (Bcoef + jdg)/(2.0*Acoef); 801 | 802 | } 803 | 804 | 805 | 806 | 807 | 808 | MYREAL FMM_raytracing( 809 | const double *rs, MYINT nr, 810 | const double *ts, MYINT nt, 811 | const double *ps, MYINT np, 812 | double r0, double t0, double p0, 813 | double rr, double tt, double pp, double seglen, double segfac, 814 | const MYREAL *Slw, const MYREAL *TT, bool sphcoord, 815 | // MYREAL *gTr, MYREAL *gTt, MYREAL *gTp, 816 | double *rays, MYINT *N) 817 | { 818 | double dr = (nr>1)? rs[1] - rs[0] : 1e-6; 819 | double dt = (nt>1)? ts[1] - ts[0] : 1e-6; 820 | double dp = (np>1)? ps[1] - ps[0] : 1e-6; 821 | double seglen0 = seglen; 822 | double seglen1; 823 | 824 | double xx, yy, zz, x0, y0, z0; 825 | double dx, dy, dz; 826 | if(sphcoord) { 827 | rtp2xyz(r0, t0, p0, &x0, &y0, &z0); 828 | rtp2xyz(rr, tt, pp, &xx, &yy, &zz); 829 | } 830 | 831 | 832 | MYINT ntp = nt*np; 833 | 834 | MYINT idot = 0; 835 | 836 | double gtr, gtt, gtp, norm; 837 | double limitdist; 838 | if(sphcoord){ 839 | limitdist = sqrt(dr*dr + pow(dt*rs[0],2) + pow(dp*rs[0]*sin(ts[0]),2)); 840 | } else { 841 | limitdist = sqrt(dr*dr + dt*dt + dp*dp); 842 | } 843 | if(limitdist < segfac*seglen) limitdist = segfac*seglen; 844 | 845 | double r1, t1, p1; 846 | double x1, y1, z1; 847 | double r11, t11, p11; 848 | double rmid, tmid, pmid, vmid; 849 | r1 = rr; 850 | t1 = tt; 851 | p1 = pp; 852 | if(sphcoord) { 853 | x1 = xx; 854 | y1 = yy; 855 | z1 = zz; 856 | } 857 | 858 | // strictly speaking, r0,t0,p0 should be used here, 859 | // however here gradient equals zero, 860 | trilinear_one_ravel(rs, nr, ts, nt, ps, np, ntp, TT, r0+dr, t0+dt, p0+dp, >r, >t, >p, NULL,NULL); 861 | gtr /= dr; 862 | gtt /= dt; 863 | gtp /= dp; 864 | if(sphcoord){ 865 | gtt /= r0; 866 | gtp /= (r0*sin(t0)); 867 | } 868 | norm = sqrt(gtr*gtr + gtt*gtt + gtp*gtp); 869 | if(norm <= 1e-2) norm = 1e-2; 870 | MYREAL limt = limitdist * norm; 871 | // printf("FMM, limitdist=%f, v=%f\n", limitdist ,norm); 872 | 873 | MYREAL travt = trilinear_one_ravel( 874 | rs, nr, ts, nt, ps, np, ntp, TT, r1, t1, p1, 875 | >r, >t, >p, NULL, NULL); 876 | MYREAL trem = travt, trem1; 877 | MYREAL travt1 = 0.0; 878 | 879 | // normalize gradient 880 | gtr /= dr; 881 | gtt /= dt; 882 | gtp /= dp; 883 | if(sphcoord){ 884 | gtt /= r1; 885 | gtp /= (r1*sin(t1)); 886 | } 887 | norm = sqrt(gtr*gtr + gtt*gtt + gtp*gtp); 888 | gtr /= norm; 889 | gtt /= norm; 890 | gtp /= norm; 891 | 892 | // printf("%f, %f, %f, %f, \n", trem, gtr, gtt, gtp); 893 | 894 | //------------------------------------------------------------------- 895 | MYINT N0 = *N; 896 | double dist; 897 | while(idot < N0-1){ 898 | rays[3*idot] = r1; 899 | rays[3*idot+1] = t1; 900 | rays[3*idot+2] = p1; 901 | 902 | idot++; 903 | 904 | // if(dist <= limitdist) break; 905 | if(trem <= limt) break; 906 | 907 | // update 908 | seglen = seglen0; 909 | for(MYINT i=0; i<5; ++i){ 910 | seglen1 = seglen; 911 | if(sphcoord){ 912 | p11 = p1 - gtp*seglen/(r1*sin(t1)); 913 | t11 = t1 - gtt*seglen/r1; 914 | r11 = r1 - gtr*seglen; 915 | } else { 916 | r11 = r1 - gtr*seglen; 917 | t11 = t1 - gtt*seglen; 918 | p11 = p1 - gtp*seglen; 919 | } 920 | 921 | // get gradient 922 | trem1 = trilinear_one_ravel( 923 | rs, nr, ts, nt, ps, np, ntp, TT, r11, t11, p11, 924 | >r, >t, >p, NULL, NULL); 925 | 926 | // printf("%f, %f, %f, %f, \n", trem1, gtr, gtt, gtp); 927 | 928 | if(trem > trem1) break; 929 | 930 | // compare travt first, 931 | // if traveltime field too complex, consider distance. 932 | if(sphcoord){ 933 | rtp2xyz(r1, t1, p1, &x1, &y1, &z1); 934 | dx = x1-x0; 935 | dy = y1-y0; 936 | dz = z1-z0; 937 | dist = sqrt(dx*dx + dy*dy + dz*dz); 938 | } else { 939 | dist = sqrt(pow(r0-r1,2) + pow(t0-t1,2) + pow(p0-p1,2)); 940 | } 941 | 942 | if(dist <= limitdist) { 943 | trem1 = 0.0; 944 | break; 945 | } 946 | 947 | seglen /= 2.0; 948 | } 949 | r1 = r11; 950 | t1 = t11; 951 | p1 = p11; 952 | trem = trem1; 953 | 954 | // normalize gradient 955 | gtr /= dr; 956 | gtt /= dt; 957 | gtp /= dp; 958 | if(sphcoord){ 959 | gtt /= r1; 960 | gtp /= (r1*sin(t1)); 961 | } 962 | norm = sqrt(gtr*gtr + gtt*gtt + gtp*gtp); 963 | gtr /= norm; 964 | gtt /= norm; 965 | gtp /= norm; 966 | 967 | // 求中点速度,算走时 968 | // 这里做了近似,认为射线段比较小,不论坐标系为何,直接去平均值作为中点 969 | if(Slw != NULL){ 970 | rmid = (r1 + rays[3*idot-3])/2.0; 971 | tmid = (t1 + rays[3*idot-2])/2.0; 972 | pmid = (p1 + rays[3*idot-1])/2.0; 973 | travt1 += trilinear_one_ravel( 974 | rs, nr, ts, nt, ps, np, ntp, Slw, rmid, tmid, pmid, 975 | NULL, NULL, NULL, NULL, NULL) * seglen1; 976 | } 977 | 978 | } // END tracing 979 | 980 | rays[3*idot] = r0; 981 | rays[3*idot+1] = t0; 982 | rays[3*idot+2] = p0; 983 | 984 | if(Slw != NULL){ 985 | // compute distance of last two points 986 | if(sphcoord){ 987 | rtp2xyz(r1, t1, p1, &x1, &y1, &z1); 988 | dx = x1-x0; 989 | dy = y1-y0; 990 | dz = z1-z0; 991 | dist = sqrt(dx*dx + dy*dy + dz*dz); 992 | } else { 993 | dist = sqrt(pow(r0-r1,2) + pow(t0-t1,2) + pow(p0-p1,2)); 994 | } 995 | rmid = (r0 + r1)/2.0; 996 | tmid = (t0 + t1)/2.0; 997 | pmid = (p0 + p1)/2.0; 998 | travt1 += trilinear_one_ravel( 999 | rs, nr, ts, nt, ps, np, ntp, Slw, rmid, tmid, pmid, 1000 | NULL, NULL, NULL, NULL, NULL) * dist; 1001 | } 1002 | 1003 | idot++; 1004 | *N = idot; 1005 | 1006 | if(Slw != NULL){ 1007 | return travt1; 1008 | } else { 1009 | return travt; 1010 | } 1011 | 1012 | } 1013 | 1014 | 1015 | 1016 | 1017 | 1018 | 1019 | 1020 | 1021 | 1022 | 1023 | 1024 | 1025 | 1026 | 1027 | 1028 | 1029 | 1030 | 1031 | /* 1032 | // if(idot==1) { 1033 | // printf("IXYZ, %d, %d, %d, %d, %d, %d\n", IXYZ[0], IXYZ[1], IXYZ[2], IXYZ[3], IXYZ[4], IXYZ[5]); 1034 | // printf("WGHT: \n"); 1035 | // for(MYINT i=0; i<2; ++i){ 1036 | // for(MYINT j=0; j<2; ++j){ 1037 | // for(MYINT k=0; k<2; ++k){ 1038 | // printf("%f ", WGHT[i][j][k]); 1039 | // } 1040 | // printf("\n"); 1041 | // } 1042 | // printf("\n"); 1043 | // } 1044 | 1045 | // printf("TT: \n"); 1046 | // for(MYINT i=-1; i<2; ++i){ 1047 | // for(MYINT j=-1; j<2; ++j){ 1048 | // for(MYINT k=-1; k<2; ++k){ 1049 | // printf("%f ", TT[(148+i)*ntp + (147+j)*np + 149+k]); 1050 | // } 1051 | // printf("\n"); 1052 | // } 1053 | // printf("\n"); 1054 | // } 1055 | // printf("gtr, gtt, gtp, %f, %f, %f\n", gtr, gtt, gtp); 1056 | // } 1057 | 1058 | 1059 | 1060 | // gtr = trilinear_one_Idx_ravel(IXYZ, WGHT, gTr, nr, nt, np, ntp, NULL, NULL, NULL); 1061 | // gtt = trilinear_one_Idx_ravel(IXYZ, WGHT, gTt, nr, nt, np, ntp, NULL, NULL, NULL); 1062 | // gtp = trilinear_one_Idx_ravel(IXYZ, WGHT, gTp, nr, nt, np, ntp, NULL, NULL, NULL); 1063 | 1064 | 1065 | // if(sphcoord){ 1066 | // rtp2xyz(r1, t1, p1, &x1, &y1, &z1); 1067 | // dx = x1-x0; 1068 | // dy = y1-y0; 1069 | // dz = z1-z0; 1070 | // dist = sqrt(dx*dx + dy*dy + dz*dz); 1071 | // } else { 1072 | // dist = sqrt(pow(r0-r1,2) + pow(t0-t1,2) + pow(p0-p1,2)); 1073 | // } 1074 | // printf("idot=%d, dist=%f\n", idot, dist); 1075 | */ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . --------------------------------------------------------------------------------