蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行离线旋转矩阵姿态角(getRotationMatrix + getOrientation)与指南针八方位修复核验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-sensor2.py
explore-tutorial-sensor2.py149 行
"""Offline Android sensor verifier for Ch 146: Orientation Sensor & Rotation Matrix Math."""
import json
import math


VERSION = (
    "CPython 3.12.14 offline Android system-service/sensor/capstone verifier "
    "(Android SDK/emulator absent)"
)


def get_rotation_matrix(gravity: tuple[float, float, float], geomagnetic: tuple[float, float, float]) -> list[float] | None:
    """Port of Android SensorManager.getRotationMatrix(R, I, gravity, geomagnetic)."""
    ax, ay, az = gravity
    ex, ey, ez = geomagnetic
    norm_sq_a = ax * ax + ay * ay + az * az
    if norm_sq_a < 0.01 * (9.81 ** 2):
        return None
    # H = E x A (points East)
    hx = ey * az - ez * ay
    hy = ez * ax - ex * az
    hz = ex * ay - ey * ax
    norm_h = math.sqrt(hx * hx + hy * hy + hz * hz)
    if norm_h < 0.1:
        return None
    inv_h = 1.0 / norm_h
    hx, hy, hz = hx * inv_h, hy * inv_h, hz * inv_h
    inv_a = 1.0 / math.sqrt(norm_sq_a)
    ax, ay, az = ax * inv_a, ay * inv_a, az * inv_a
    # M = A x H (points Magnetic North)
    mx = ay * hz - az * hy
    my = az * hx - ax * hz
    mz = ax * hy - ay * hx
    return [hx, hy, hz, mx, my, mz, ax, ay, az]


def get_orientation(r: list[float]) -> tuple[float, float, float]:
    """Port of Android SensorManager.getOrientation(R, values) returning degrees (azimuth_360, pitch, roll)."""
    az_rad = math.atan2(r[1], r[4])
    pitch_rad = math.asin(-r[7])
    roll_rad = math.atan2(-r[6], r[8])
    az_deg = (math.degrees(az_rad) + 360.0) % 360.0
    pitch_deg = math.degrees(pitch_rad)
    roll_deg = math.degrees(roll_rad)
    return (round(az_deg, 2), round(pitch_deg, 2), round(roll_deg, 2))


def classify_compass_fixed(degree: float, half_range: float = 22.5) -> str:
    """Correct 8-sector compass classifier handling 360->0 wraparound cleanly."""
    d = degree % 360.0
    sectors = [
        (0.0, "正北"),
        (45.0, "东北"),
        (90.0, "正东"),
        (135.0, "东南"),
        (180.0, "正南"),
        (225.0, "西南"),
        (270.0, "正西"),
        (315.0, "西北"),
    ]
    for center, label in sectors:
        diff = abs(((d - center + 180.0) % 360.0) - 180.0)
        if diff <= half_range:
            return label
    return "正北"


def classify_compass_legacy_bug(degree: float, range_deg: int = 22) -> str | None:
    """Reproduce source CompassView bug where (360-range < dec < 360+range) misses [0, 22]."""
    if degree > 360 - range_deg and degree < 360 + range_deg:
        return "正北"
    for center, label in ((90, "正东"), (180, "正南"), (270, "正西"), (45, "东北"), (135, "东南"), (225, "西南"), (315, "西北")):
        if degree > center - range_deg and degree < center + range_deg:
            return label
    return None


def main() -> None:
    # Case 1: SensorManager.getRotationMatrix + getOrientation replacing deprecated TYPE_ORIENTATION
    # Flat device facing North: gravity=(0,0,9.81), magnetic field=(0, 30, -40) (North +Y, dipped downward -Z)
    r_north = get_rotation_matrix((0.0, 0.0, 9.81), (0.0, 30.0, -40.0))
    # Flat device rotated 90 deg clockwise (facing East): North is now along -X => geomagnetic=(-30, 0, -40)
    r_east = get_rotation_matrix((0.0, 0.0, 9.81), (-30.0, 0.0, -40.0))
    # Flat device facing South: geomagnetic=(0, -30, -40)
    r_south = get_rotation_matrix((0.0, 0.0, 9.81), (0.0, -30.0, -40.0))
    # Device facing North, pitched up 30 deg around X axis: gravity=(0, 9.81*sin30, 9.81*cos30)
    g_pitch30 = (0.0, 9.81 * math.sin(math.radians(30)), 9.81 * math.cos(math.radians(30)))
    m_pitch30 = (0.0, 30.0 * math.cos(math.radians(30)), -30.0 * math.sin(math.radians(30)))
    r_pitch = get_rotation_matrix(g_pitch30, m_pitch30)

    assert r_north and r_east and r_south and r_pitch
    c1_actual = {
        "facing_north_deg": list(get_orientation(r_north)),
        "facing_east_deg": list(get_orientation(r_east)),
        "facing_south_deg": list(get_orientation(r_south)),
        "pitched_up_30_deg": list(get_orientation(r_pitch)),
        "freefall_returns_none": get_rotation_matrix((0.0, 0.0, 0.0), (0.0, 30.0, -40.0)) is None,
    }
    c1_expected = {
        "facing_north_deg": [0.0, 0.0, 0.0],
        "facing_east_deg": [90.0, 0.0, 0.0],
        "facing_south_deg": [180.0, 0.0, 0.0],
        "pitched_up_30_deg": [0.0, -30.0, 0.0],
        "freefall_returns_none": True,
    }

    # Case 2: Text display rounding & CompassView 8-direction classification + North wraparound bugfix
    sample_values = (182.346, -12.456, 4.123)
    formatted = [round(v * 100) / 100 for v in sample_values]
    test_angles = [5.0, 45.0, 90.0, 135.0, 180.0, 225.0, 270.0, 315.0, 355.0]
    fixed_labels = [classify_compass_fixed(a) for a in test_angles]
    legacy_5deg = classify_compass_legacy_bug(5.0)
    fixed_5deg = classify_compass_fixed(5.0)

    c2_actual = {
        "rounded_display_values": formatted,
        "fixed_9_angles": fixed_labels,
        "legacy_bug_at_5deg_returns_none": legacy_5deg is None,
        "fixed_at_5deg": fixed_5deg,
    }
    c2_expected = {
        "rounded_display_values": [182.35, -12.46, 4.12],
        "fixed_9_angles": ["正北", "东北", "正东", "东南", "正南", "西南", "正西", "西北", "正北"],
        "legacy_bug_at_5deg_returns_none": True,
        "fixed_at_5deg": "正北",
    }

    cases = [
        {
            "name": "rotation_matrix_orientation_math",
            "summary": "使用 getRotationMatrix + getOrientation 替代已废弃 TYPE_ORIENTATION,核验北/东/南与30°俯仰姿态角",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        },
        {
            "name": "compass_sector_and_north_wraparound_fix",
            "summary": "验证指南针读数保留两位小数、8 方位划分及 360°→0° 跨越正北区间漏判缺陷修复",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        },
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/android-tutorial-sensor2-lab/explore-tutorial-sensor2.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-tutorial-sensor2.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Android

课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip

下载课程关联工程包:Android

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1937.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习