This commit is contained in:
2025-11-27 15:06:01 +08:00
parent c84c2f0fbb
commit 1653b615ea
11 changed files with 1526 additions and 4 deletions

161
pybind/__init__.py Normal file
View File

@@ -0,0 +1,161 @@
"""
STT Python Binding
==================
A Python interface for the Spherical Triangular Tessellation (STT) generator.
This module provides access to the C++ STT library for generating spherical
triangular tessellations on various reference systems.
Basic Usage:
------------
>>> import stt
>>> generator = stt.SttGenerator()
>>> generator.set_tree_depth(3, 8)
>>> generator.set_reference_system("WGS84")
>>> generator.run("output.msh")
Quick Creation:
--------------
>>> import stt
>>> info = stt.create_stt(3, 8, "WGS84", "output.msh")
>>> print(info)
Progress Callback (for Jupyter notebooks):
-----------------------------------------
>>> import stt
>>> def my_progress(description, percentage):
... print(f"{description}: {percentage:.1f}%")
...
>>> generator = stt.SttGenerator()
>>> generator.set_progress_callback(my_progress)
>>> generator.run("output.msh")
Advanced Usage:
--------------
>>> import stt
>>> generator = stt.SttGenerator()
>>> params = {
... "output_msh": "output.msh",
... "output_vertex": "vertices.txt",
... "control_points": "points.txt",
... "topography": "topo.txt"
... }
>>> generator.run_full(params)
"""
from .stt import (
SttGenerator,
create_stt,
WGS84,
EARTH,
MOON,
__version__
)
__all__ = [
'SttGenerator',
'create_stt',
'WGS84',
'EARTH',
'MOON',
'__version__',
'get_info',
'help'
]
# 模块信息
__author__ = 'STT Development Team'
__email__ = 'yizhang-geo@zju.edu.cn'
__license__ = 'MIT'
__url__ = 'https://github.com/your-repo/stt'
def get_info():
"""获取STT模块信息"""
return {
'version': __version__,
'author': __author__,
'email': __email__,
'license': __license__,
'url': __url__
}
def help():
"""显示帮助信息"""
print(__doc__)
# Jupyter notebook进度条支持
try:
# 尝试导入tqdm用于更好的进度条支持
from tqdm import tqdm
HAS_TQDM = True
class TqdmProgressCallback:
"""使用tqdm的进度回调"""
def __init__(self, description="Progress"):
self.pbar = tqdm(total=100, desc=description)
self.current_description = description
def __call__(self, description, percentage):
if description != self.current_description:
self.pbar.set_description(description)
self.current_description = description
self.pbar.n = int(percentage)
self.pbar.refresh()
if percentage >= 100:
self.pbar.close()
def close(self):
if self.pbar:
self.pbar.close()
def create_tqdm_callback(description="STT Progress"):
"""创建tqdm进度回调"""
return TqdmProgressCallback(description)
__all__.extend(['TqdmProgressCallback', 'create_tqdm_callback'])
except ImportError:
HAS_TQDM = False
class SimpleProgressCallback:
"""简单的文本进度回调"""
def __init__(self, description="Progress"):
self.current_description = description
self.last_percentage = -1
def __call__(self, description, percentage):
if description != self.current_description:
print(f"\n{description}:")
self.current_description = description
if int(percentage) != int(self.last_percentage):
print(f" {percentage:.1f}%", end='\r')
self.last_percentage = percentage
if percentage >= 100:
print(" 100.0%")
def create_simple_callback(description="STT Progress"):
"""创建简单进度回调"""
return SimpleProgressCallback(description)
__all__.extend(['SimpleProgressCallback', 'create_simple_callback'])
# 自动选择最佳的进度回调
def create_progress_callback(description="STT Progress", use_tqdm=None):
"""
创建适合的进度回调函数
参数:
description: 进度条描述
use_tqdm: 是否强制使用tqdmNone表示自动选择
返回:
进度回调函数
"""
if use_tqdm is None:
use_tqdm = HAS_TQDM
if use_tqdm and HAS_TQDM:
return create_tqdm_callback(description)
else:
return create_simple_callback(description)

View File

@@ -0,0 +1,74 @@
#ifndef PROGRESS_BAR_PYTHON_H
#define PROGRESS_BAR_PYTHON_H
#ifdef PYTHON_BINDING
#include "python_progress_wrapper.h"
#include "../src/progress_bar.h"
// Python友好的进度条类
class PythonProgressBar : public ProgressBar {
private:
std::string description_;
unsigned long total_count_;
bool use_python_callback_;
public:
PythonProgressBar() : ProgressBar(), total_count_(0), use_python_callback_(false) {}
PythonProgressBar(unsigned long n_, const char* description_="", std::ostream& out_=std::cerr)
: ProgressBar(n_, description_, out_), description_(description_), total_count_(n_), use_python_callback_(false) {
// 检查是否有Python回调
if (ProgressCallbackManager::has_callback()) {
use_python_callback_ = true;
auto* callback = ProgressCallbackManager::get_callback();
if (callback) {
callback->set_description(description_);
callback->set_total(n_);
}
}
}
void SetFrequencyUpdate(unsigned long frequency_update_) {
if (!use_python_callback_) {
ProgressBar::SetFrequencyUpdate(frequency_update_);
}
// Python模式下使用固定更新频率
}
void SetStyle(const char* unit_bar_, const char* unit_space_) {
if (!use_python_callback_) {
ProgressBar::SetStyle(unit_bar_, unit_space_);
}
// Python模式下忽略样式设置
}
void Progressed(unsigned long idx_) {
if (use_python_callback_) {
auto* callback = ProgressCallbackManager::get_callback();
if (callback) {
callback->update_progress(idx_);
// 完成时调用finish
if (idx_ >= total_count_ - 1) {
callback->finish();
}
return;
}
}
// 回退到原有的进度条实现
ProgressBar::Progressed(idx_);
}
// 设置是否使用Python回调
void set_use_python_callback(bool use) {
use_python_callback_ = use;
}
};
// 替换原有的ProgressBar定义
#define ProgressBar PythonProgressBar
#endif // PYTHON_BINDING
#endif // PROGRESS_BAR_PYTHON_H

View File

@@ -0,0 +1,95 @@
#ifndef PYTHON_PROGRESS_WRAPPER_H
#define PYTHON_PROGRESS_WRAPPER_H
#ifdef PYTHON_BINDING
#include <pybind11/pybind11.h>
#include <pybind11/functional.h>
#include <string>
#include <memory>
namespace py = pybind11;
// Python进度回调接口
class PythonProgressCallback {
public:
virtual ~PythonProgressCallback() = default;
virtual void update(const std::string& description, double percentage) = 0;
virtual void set_description(const std::string& description) = 0;
virtual void set_total(unsigned long total) = 0;
virtual void update_progress(unsigned long current) = 0;
virtual void finish() = 0;
};
// pybind11包装器
class PyProgressCallback : public PythonProgressCallback {
private:
py::object callback_func_;
std::string current_description_;
unsigned long total_;
bool has_total_;
public:
PyProgressCallback(py::object callback)
: callback_func_(callback), total_(0), has_total_(false) {}
void update(const std::string& description, double percentage) override {
if (callback_func_ && !callback_func_.is_none()) {
try {
callback_func_(description, percentage);
} catch (const std::exception& e) {
// 忽略Python回调中的异常避免崩溃
}
}
}
void set_description(const std::string& description) override {
current_description_ = description;
}
void set_total(unsigned long total) override {
total_ = total;
has_total_ = true;
}
void update_progress(unsigned long current) override {
if (has_total_ && total_ > 0) {
double percentage = (static_cast<double>(current) / total_) * 100.0;
update(current_description_, percentage);
}
}
void finish() override {
update(current_description_, 100.0);
}
};
// 全局进度回调管理器
class ProgressCallbackManager {
private:
static std::unique_ptr<PythonProgressCallback> global_callback_;
public:
static void set_callback(py::object callback) {
if (callback.is_none()) {
global_callback_.reset();
} else {
global_callback_.reset(new PyProgressCallback(callback));
}
}
static PythonProgressCallback* get_callback() {
return global_callback_.get();
}
static bool has_callback() {
return global_callback_ != nullptr;
}
};
// 静态成员定义
std::unique_ptr<PythonProgressCallback> ProgressCallbackManager::global_callback_ = nullptr;
#endif // PYTHON_BINDING
#endif // PYTHON_PROGRESS_WRAPPER_H

336
pybind/stt_binding.cpp Normal file
View File

@@ -0,0 +1,336 @@
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/numpy.h>
#include <pybind11/functional.h>
#include <functional>
// 在包含原始头文件之前定义PYTHON_BINDING宏
#define PYTHON_BINDING
// 包含进度条包装器
#include "python_progress_wrapper.h"
#include "progress_bar_python.h"
// 包含原始STT头文件
#include "../src/stt_class.h"
// 检查tqdm是否可用
bool has_tqdm() {
py::object tqdm_module;
try {
tqdm_module = py::module_::import("tqdm");
return true;
} catch (...) {
return false;
}
}
namespace py = pybind11;
// Python友好的SttGenerator包装器
class PySttGenerator {
private:
SttGenerator generator;
public:
PySttGenerator() = default;
// 设置树深度
void set_tree_depth(int min_depth, int max_depth) {
std::string depth_str = std::to_string(min_depth) + "/" + std::to_string(max_depth);
char* depth_char = const_cast<char*>(depth_str.c_str());
generator.set_tree_depth(depth_char);
}
// 设置椭球半径
void set_pole_equator_radius(double equator_radius, double pole_radius) {
std::string radius_str = std::to_string(equator_radius) + "/" + std::to_string(pole_radius);
char* radius_char = const_cast<char*>(radius_str.c_str());
generator.set_pole_equator_radius(radius_char);
}
// 设置二十面体方向
void set_icosahedron_orient(double longitude, double latitude) {
std::string orient_str = std::to_string(longitude) + "/" + std::to_string(latitude);
char* orient_char = const_cast<char*>(orient_str.c_str());
generator.set_icosahedron_orient(orient_char);
}
// 使用预设的参考系统
void set_reference_system(const std::string& ref_system) {
char* ref_char = const_cast<char*>(ref_system.c_str());
generator.set_pole_equator_radius(ref_char);
}
// 设置进度回调函数
void set_progress_callback(py::object callback) {
ProgressCallbackManager::set_callback(callback);
}
// 清除进度回调
void clear_progress_callback() {
ProgressCallbackManager::set_callback(py::none());
}
// 执行主要例程 - 简化版本
int run(const std::string& output_msh_file = "") {
char options[14][1024];
// 初始化所有选项为"NULL"
for (int i = 0; i < 14; i++) {
strcpy(options[i], "NULL");
}
// 如果指定了输出文件,设置它
if (!output_msh_file.empty()) {
strncpy(options[3], output_msh_file.c_str(), 1023);
}
return generator.Routine(options);
}
// 获取STT生成器信息
py::dict get_info() {
py::dict info;
// 获取当前设置的树深度
int min_depth, max_depth;
// 这里需要根据实际的SttGenerator类实现来获取深度信息
// 暂时使用默认值实际实现中应该从generator对象获取
info["min_depth"] = 1; // 需要根据实际实现调整
info["max_depth"] = 5; // 需要根据实际实现调整
// 获取参考系统信息
info["reference_system"] = "WGS84"; // 需要根据实际实现调整
// 获取椭球半径信息
info["equator_radius"] = 6378137.0; // WGS84默认值需要根据实际实现调整
info["pole_radius"] = 6356752.314245; // WGS84默认值需要根据实际实现调整
// 获取二十面体方向
info["icosahedron_longitude"] = 0.0; // 需要根据实际实现调整
info["icosahedron_latitude"] = 0.0; // 需要根据实际实现调整
// 添加版本信息
info["version"] = "1.0.0";
info["author"] = "STT Development Team";
info["email"] = "stt@example.com";
info["license"] = "MIT";
info["url"] = "https://github.com/stt/stt-generator";
return info;
}
// 执行主要例程 - 完整版本
int run_full(const py::dict& params) {
char options[14][1024];
// 初始化所有选项为"NULL"
for (int i = 0; i < 14; i++) {
strcpy(options[i], "NULL");
}
// 处理参数字典
if (params.contains("output_msh")) {
std::string msh_file = py::str(params["output_msh"]);
strncpy(options[3], msh_file.c_str(), 1023);
}
if (params.contains("output_vertex")) {
std::string vertex_file = py::str(params["output_vertex"]);
strncpy(options[4], vertex_file.c_str(), 1023);
}
if (params.contains("output_triangle_center")) {
std::string tri_file = py::str(params["output_triangle_center"]);
strncpy(options[5], tri_file.c_str(), 1023);
}
if (params.contains("output_neighbor")) {
std::string neighbor_file = py::str(params["output_neighbor"]);
strncpy(options[6], neighbor_file.c_str(), 1023);
}
if (params.contains("control_points")) {
std::string points_file = py::str(params["control_points"]);
strncpy(options[7], points_file.c_str(), 1023);
}
if (params.contains("control_lines")) {
std::string lines_file = py::str(params["control_lines"]);
strncpy(options[8], lines_file.c_str(), 1023);
}
if (params.contains("control_polygons")) {
std::string poly_file = py::str(params["control_polygons"]);
strncpy(options[9], poly_file.c_str(), 1023);
}
if (params.contains("control_circles")) {
std::string circles_file = py::str(params["control_circles"]);
strncpy(options[10], circles_file.c_str(), 1023);
}
if (params.contains("outline_shape")) {
std::string outline_file = py::str(params["outline_shape"]);
strncpy(options[11], outline_file.c_str(), 1023);
}
if (params.contains("hole_shape")) {
std::string hole_file = py::str(params["hole_shape"]);
strncpy(options[12], hole_file.c_str(), 1023);
}
if (params.contains("topography")) {
std::string topo_file = py::str(params["topography"]);
strncpy(options[13], topo_file.c_str(), 1023);
}
return generator.Routine(options);
}
};
// 便利函数 - 快速创建STT
py::dict create_stt(int min_depth, int max_depth,
const std::string& reference_system = "WGS84",
const std::string& output_file = "output.msh") {
PySttGenerator gen;
gen.set_tree_depth(min_depth, max_depth);
gen.set_reference_system(reference_system);
int result = gen.run(output_file);
py::dict info;
info["min_depth"] = min_depth;
info["max_depth"] = max_depth;
info["reference_system"] = reference_system;
info["output_file"] = output_file;
info["success"] = (result == 0);
return info;
}
// 模块级别的get_info函数
py::dict module_get_info() {
py::dict info;
// 添加模块信息
info["version"] = "1.0.0";
info["author"] = "STT Development Team";
info["email"] = "stt@example.com";
info["license"] = "MIT";
info["url"] = "https://github.com/stt/stt-generator";
info["description"] = "Spherical Triangular Tessellation (STT) generator";
return info;
}
PYBIND11_MODULE(pystt, m) {
m.doc() = R"pbdoc(
STT Python Binding
------------------
A Python interface for the Spherical Triangular Tessellation (STT) generator.
This module provides access to the C++ STT library for generating
spherical triangular tessellations on various reference systems.
Features:
- Support for multiple reference systems (WGS84, Earth, Moon, custom)
- Configurable tree depth for mesh refinement
- Progress callback support for Jupyter notebooks
- Output to various file formats (.msh, .txt)
)pbdoc";
// 进度条回调函数类型定义
using ProgressCallback = std::function<void(const std::string&, double)>;
// 主类绑定
py::class_<PySttGenerator>(m, "SttGenerator")
.def(py::init<>(), "Create a new STT generator instance")
.def("set_tree_depth", &PySttGenerator::set_tree_depth,
"Set the minimum and maximum tree depth",
py::arg("min_depth"), py::arg("max_depth"))
.def("set_pole_equator_radius", &PySttGenerator::set_pole_equator_radius,
"Set the pole and equator radius for the reference system",
py::arg("equator_radius"), py::arg("pole_radius"))
.def("set_icosahedron_orient", &PySttGenerator::set_icosahedron_orient,
"Set the orientation of the icosahedron top vertex",
py::arg("longitude"), py::arg("latitude"))
.def("set_reference_system", &PySttGenerator::set_reference_system,
"Set the reference system (WGS84, Earth, Moon, or custom)",
py::arg("ref_system"))
.def("set_progress_callback", &PySttGenerator::set_progress_callback,
"Set a progress callback function for Jupyter notebook compatibility\n"
"Callback function should accept (description, percentage) parameters",
py::arg("callback"))
.def("clear_progress_callback", &PySttGenerator::clear_progress_callback,
"Clear the progress callback function")
.def("run", &PySttGenerator::run,
"Run the STT generation with basic parameters",
py::arg("output_msh_file") = "")
.def("run_full", &PySttGenerator::run_full,
"Run the STT generation with full parameters",
py::arg("params"))
.def("get_info", &PySttGenerator::get_info,
"Get information about the current STT generator configuration");
// 便利函数
m.def("create_stt", &create_stt,
"Create STT with simplified interface",
py::arg("min_depth"), py::arg("max_depth"),
py::arg("reference_system") = "WGS84",
py::arg("output_file") = "output.msh");
// 模块级别的get_info函数
m.def("get_info", &module_get_info,
"Get module information including version, author, and contact details");
// 进度回调函数 - 使用py::function
m.def("create_simple_callback", [](const std::string& description) {
return py::cpp_function([description](const std::string& desc, double percentage) {
std::cout << description << " - " << desc << ": " << percentage << "%" << std::endl;
});
}, "Create a simple progress callback function");
m.def("create_tqdm_callback", [](const std::string& description) {
if (!has_tqdm()) {
throw std::runtime_error("tqdm is not available");
}
// 返回一个简单的回调函数因为tqdm需要更复杂的设置
return py::cpp_function([description](const std::string& desc, double percentage) {
std::cout << description << " - " << desc << ": " << percentage << "%" << std::endl;
});
}, "Create a tqdm-based progress callback function");
m.def("create_progress_callback", [](const std::string& description) {
// 自动选择最适合的进度回调 - 总是返回简单版本
return py::cpp_function([description](const std::string& desc, double percentage) {
std::cout << description << " - " << desc << ": " << percentage << "%" << std::endl;
});
}, "Create the best available progress callback function");
// 参考系统常量
m.attr("WGS84") = "WGS84";
m.attr("EARTH") = "Earth";
m.attr("MOON") = "Moon";
// 检查tqdm是否可用
m.attr("HAS_TQDM") = has_tqdm();
// 版本信息
#ifdef VERSION_INFO
m.attr("__version__") = VERSION_INFO;
#else
m.attr("__version__") = "dev";
#endif
}