init: 初始化krylov复现项目

This commit is contained in:
M4yGem1ni
2026-04-09 19:38:56 +08:00
commit 173ad1cf2f
13 changed files with 518 additions and 0 deletions

59
tests/test_eigen.cpp Normal file
View File

@@ -0,0 +1,59 @@
#include "krylov/types/common.hpp"
#include <cassert>
#include <cmath>
static bool approx(double a, double b, double eps = 1e-10) {
return std::abs(a - b) < eps;
}
int main() {
using krylov::Matrix;
using krylov::Vector;
using MatrixXd = Matrix;
using VectorXd = Vector;
// 1) 基本矩阵 / 向量运算
MatrixXd A(2, 2);
A << 4, 1,
2, 3;
VectorXd b(2);
b << 1, 2;
VectorXd Ab = A * b;
assert(approx(Ab(0), 4 * 1 + 1 * 2));
assert(approx(Ab(1), 2 * 1 + 3 * 2));
// 2) 行列式 / 逆
assert(approx(A.determinant(), 4 * 3 - 1 * 2));
MatrixXd I = A * A.inverse();
assert(approx(I(0, 0), 1.0));
assert(approx(I(1, 1), 1.0));
assert(approx(I(0, 1), 0.0));
assert(approx(I(1, 0), 0.0));
// 3) 线性方程求解 A x = b
VectorXd x = A.colPivHouseholderQr().solve(b);
VectorXd r = A * x - b;
assert(r.norm() < 1e-10);
// 4) 范数
VectorXd v(3);
v << 3, 0, 4;
assert(approx(v.norm(), 5.0));
assert(approx(v.squaredNorm(), 25.0));
// 5) 稀疏矩阵基础
krylov::SparseMatrix S(3, 3);
S.insert(0, 0) = 1.0;
S.insert(1, 1) = 2.0;
S.insert(2, 2) = 3.0;
S.makeCompressed();
VectorXd y(3);
y << 1, 1, 1;
VectorXd Sy = S * y;
assert(approx(Sy(0), 1.0));
assert(approx(Sy(1), 2.0));
assert(approx(Sy(2), 3.0));
return 0;
}

57
tests/test_logger.cpp Normal file
View File

@@ -0,0 +1,57 @@
#include "logger/logger.hpp"
#include <cassert>
#include <filesystem>
#include <fstream>
#include <sstream>
#include <string>
namespace fs = std::filesystem;
static std::string read_file(const fs::path& p) {
std::ifstream in(p);
std::stringstream ss;
ss << in.rdbuf();
return ss.str();
}
int main() {
const fs::path log_path = "logs/test_logger.log";
if (fs::exists(log_path)) fs::remove(log_path);
// 同步模式便于立即断言文件内容
Logger::Init(log_path.string(), 1, 2, /*is_async=*/false);
// 1) 默认 logger 可用
auto def = Logger::GetDefaultLogger();
assert(def != nullptr);
// 2) 全局级别设置生效
Logger::SetGlobalLevel(spdlog::level::debug);
assert(def->level() == spdlog::level::debug);
// 3) 模块 logger 创建 + 复用
auto net1 = Logger::GetModuleLogger("net");
auto net2 = Logger::GetModuleLogger("net");
assert(net1 != nullptr);
assert(net1.get() == net2.get());
// 4) 模块级别独立设置
Logger::SetModuleLevel("net", spdlog::level::warn);
assert(net1->level() == spdlog::level::warn);
// 5) 写日志并落盘
LOG_INFO("hello {}", "logger");
LOG_DEBUG("debug value = {}", 123);
net1->error("net module error {}", 7);
def->flush();
net1->flush();
assert(fs::exists(log_path));
std::string content = read_file(log_path);
assert(content.find("hello logger") != std::string::npos);
assert(content.find("debug value = 123") != std::string::npos);
assert(content.find("net module error 7") != std::string::npos);
Logger::Shutdown();
return 0;
}