degawong 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of degawong might be problematic. Click here for more details.

@@ -0,0 +1,2 @@
1
+ include README.md
2
+ recursive-include src/degawong *.md py.typed
@@ -0,0 +1,104 @@
1
+ Metadata-Version: 2.4
2
+ Name: degawong
3
+ Version: 0.1.0
4
+ Summary: Reusable PyTorch frequency-domain feature extraction modules
5
+ Classifier: Development Status :: 3 - Alpha
6
+ Classifier: Intended Audience :: Science/Research
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Programming Language :: Python :: 3.8
9
+ Classifier: Topic :: Scientific/Engineering :: Image Processing
10
+ Requires-Python: >=3.8
11
+ Description-Content-Type: text/markdown
12
+ Requires-Dist: torch>=1.8
13
+
14
+ # degawong
15
+
16
+ `degawong` is an installable Python package for reusable image and tensor utilities. The current release includes a frequency-domain feature extraction subpackage built with PyTorch.
17
+
18
+ ## Install
19
+
20
+ After the first release is published to PyPI:
21
+
22
+ ```bash
23
+ python -m pip install degawong
24
+ ```
25
+
26
+ For local development from a clone:
27
+
28
+ ```bash
29
+ python -m pip install -e .
30
+ ```
31
+
32
+ The frequency feature modules require PyTorch. It is declared as a package dependency so a normal install includes it.
33
+
34
+ ## Import the package
35
+
36
+ The top-level package exposes its current subpackage and common frequency API:
37
+
38
+ ```python
39
+ import degawong
40
+
41
+ extractor = degawong.create_extractor("haar_dwt")
42
+ print(degawong.frequency_features.EXTRACTOR_REGISTRY.keys())
43
+ ```
44
+
45
+ You can also import the frequency feature API directly:
46
+
47
+ ```python
48
+ from degawong.frequency_features import create_extractor
49
+
50
+ extractor = create_extractor("haar_dwt")
51
+ ```
52
+
53
+ Run the generic example from the repository root:
54
+
55
+ ```bash
56
+ python -m degawong.frequency_features.examples.quickstart --help
57
+ python -m degawong.frequency_features.examples.quickstart --scheme haar_dwt
58
+ ```
59
+
60
+ The frequency package's module layout, automatic strategy discovery, and extension rules are documented in [its README](src/degawong/frequency_features/README.md) and [AGENTS.md](src/degawong/frequency_features/AGENTS.md).
61
+
62
+ ## Package structure
63
+
64
+ ```text
65
+ src/degawong/
66
+ ├── __init__.py
67
+ ├── AGENTS.md
68
+ ├── py.typed
69
+ └── frequency_features/
70
+ ├── __init__.py
71
+ ├── frequency_feature.py
72
+ ├── registry.py
73
+ ├── strategies/
74
+ └── examples/
75
+ ```
76
+
77
+ `import degawong` exposes the subpackages deliberately imported by `degawong/__init__.py`; it does not scan or import future modules implicitly. Add each new public subpackage there and document its direct import path.
78
+
79
+ ## Build distributions
80
+
81
+ From the repository root:
82
+
83
+ ```bash
84
+ python -m pip install --upgrade build twine
85
+ python -m build
86
+ python -m twine check dist/*
87
+ ```
88
+
89
+ The project uses the standard `pyproject.toml` build configuration and the `src/` layout. `src/` is conventional, not mandatory; it separates the installable package from repository-level reference material and build files. Markdown agent guidance and the frequency-methods research report are included in source and wheel distributions as package data. Read the [research report](src/degawong/frequency_features/docs/research/frequency_methods.md).
90
+
91
+ ## Publish through GitHub Actions
92
+
93
+ The workflow at `.github/workflows/publish-pypi.yml` builds and publishes a GitHub Release to PyPI using PyPI Trusted Publishing (OIDC), without storing a PyPI API token in GitHub secrets.
94
+
95
+ Before the first release:
96
+
97
+ 1. Create/configure the `degawong` project on PyPI, or configure its pending publisher.
98
+ 2. Add a PyPI Trusted Publisher for the GitHub owner/repository, workflow file `publish-pypi.yml`, and GitHub environment `pypi`.
99
+ 3. Choose the package's license and add the corresponding `LICENSE` file and metadata. No license was inferred or selected in this scaffold.
100
+ 4. Set the project version in `pyproject.toml`, commit and push the changes, create a matching version tag/release, then publish that GitHub Release.
101
+
102
+ The GitHub repository URL is intentionally not hard-coded because the target repository has not been specified.
103
+
104
+
@@ -0,0 +1,91 @@
1
+ # degawong
2
+
3
+ `degawong` is an installable Python package for reusable image and tensor utilities. The current release includes a frequency-domain feature extraction subpackage built with PyTorch.
4
+
5
+ ## Install
6
+
7
+ After the first release is published to PyPI:
8
+
9
+ ```bash
10
+ python -m pip install degawong
11
+ ```
12
+
13
+ For local development from a clone:
14
+
15
+ ```bash
16
+ python -m pip install -e .
17
+ ```
18
+
19
+ The frequency feature modules require PyTorch. It is declared as a package dependency so a normal install includes it.
20
+
21
+ ## Import the package
22
+
23
+ The top-level package exposes its current subpackage and common frequency API:
24
+
25
+ ```python
26
+ import degawong
27
+
28
+ extractor = degawong.create_extractor("haar_dwt")
29
+ print(degawong.frequency_features.EXTRACTOR_REGISTRY.keys())
30
+ ```
31
+
32
+ You can also import the frequency feature API directly:
33
+
34
+ ```python
35
+ from degawong.frequency_features import create_extractor
36
+
37
+ extractor = create_extractor("haar_dwt")
38
+ ```
39
+
40
+ Run the generic example from the repository root:
41
+
42
+ ```bash
43
+ python -m degawong.frequency_features.examples.quickstart --help
44
+ python -m degawong.frequency_features.examples.quickstart --scheme haar_dwt
45
+ ```
46
+
47
+ The frequency package's module layout, automatic strategy discovery, and extension rules are documented in [its README](src/degawong/frequency_features/README.md) and [AGENTS.md](src/degawong/frequency_features/AGENTS.md).
48
+
49
+ ## Package structure
50
+
51
+ ```text
52
+ src/degawong/
53
+ ├── __init__.py
54
+ ├── AGENTS.md
55
+ ├── py.typed
56
+ └── frequency_features/
57
+ ├── __init__.py
58
+ ├── frequency_feature.py
59
+ ├── registry.py
60
+ ├── strategies/
61
+ └── examples/
62
+ ```
63
+
64
+ `import degawong` exposes the subpackages deliberately imported by `degawong/__init__.py`; it does not scan or import future modules implicitly. Add each new public subpackage there and document its direct import path.
65
+
66
+ ## Build distributions
67
+
68
+ From the repository root:
69
+
70
+ ```bash
71
+ python -m pip install --upgrade build twine
72
+ python -m build
73
+ python -m twine check dist/*
74
+ ```
75
+
76
+ The project uses the standard `pyproject.toml` build configuration and the `src/` layout. `src/` is conventional, not mandatory; it separates the installable package from repository-level reference material and build files. Markdown agent guidance and the frequency-methods research report are included in source and wheel distributions as package data. Read the [research report](src/degawong/frequency_features/docs/research/frequency_methods.md).
77
+
78
+ ## Publish through GitHub Actions
79
+
80
+ The workflow at `.github/workflows/publish-pypi.yml` builds and publishes a GitHub Release to PyPI using PyPI Trusted Publishing (OIDC), without storing a PyPI API token in GitHub secrets.
81
+
82
+ Before the first release:
83
+
84
+ 1. Create/configure the `degawong` project on PyPI, or configure its pending publisher.
85
+ 2. Add a PyPI Trusted Publisher for the GitHub owner/repository, workflow file `publish-pypi.yml`, and GitHub environment `pypi`.
86
+ 3. Choose the package's license and add the corresponding `LICENSE` file and metadata. No license was inferred or selected in this scaffold.
87
+ 4. Set the project version in `pyproject.toml`, commit and push the changes, create a matching version tag/release, then publish that GitHub Release.
88
+
89
+ The GitHub repository URL is intentionally not hard-coded because the target repository has not been specified.
90
+
91
+
@@ -0,0 +1,29 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "degawong"
7
+ version = "0.1.0"
8
+ description = "Reusable PyTorch frequency-domain feature extraction modules"
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ dependencies = ["torch>=1.8"]
12
+ classifiers = [
13
+ "Development Status :: 3 - Alpha",
14
+ "Intended Audience :: Science/Research",
15
+ "Programming Language :: Python :: 3",
16
+ "Programming Language :: Python :: 3.8",
17
+ "Topic :: Scientific/Engineering :: Image Processing",
18
+ ]
19
+
20
+ [tool.setuptools]
21
+ package-dir = {"" = "src"}
22
+ include-package-data = true
23
+
24
+ [tool.setuptools.packages.find]
25
+ where = ["src"]
26
+
27
+ [tool.setuptools.package-data]
28
+ degawong = ["AGENTS.md", "py.typed"]
29
+ "degawong.frequency_features" = ["AGENTS.md", "README.md", "docs/research/*.md"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,31 @@
1
+ # degawong Package Maintenance Rules
2
+
3
+ These rules apply to the installable package under `src/degawong/`. The repository-root `AGENTS.md` and `sources/` mirror are separate project context; never edit synced files under `sources/`.
4
+
5
+ ## Packaging and imports
6
+
7
+ - `degawong` is the distribution name and import namespace. Keep Python sources under `src/degawong/`.
8
+ - A normal install must support `import degawong`; expose public subpackages intentionally from `src/degawong/__init__.py` and document direct imports such as `from degawong.frequency_features import ...`.
9
+ - Do not import or scan every future subpackage implicitly. Update the top-level exports when a new public subpackage is added.
10
+ - Keep `pyproject.toml` metadata, `README.md`, `MANIFEST.in`, `py.typed`, package-data settings, and GitHub publishing workflow consistent.
11
+ - Keep repository-maintainer instructions inside `src/degawong/AGENTS.md` or a subpackage AGENTS file, and ensure Markdown guidance is included in source and wheel distributions.
12
+ - The supported Python baseline is 3.8 unless the user explicitly changes it. Add dependencies to `pyproject.toml` and explain material dependency effects in README.
13
+ - Do not choose a package license or invent a GitHub repository URL. Before publishing, ask the user to select a license if none is provided and configure the actual GitHub Trusted Publisher coordinates.
14
+
15
+ ## Package quality
16
+
17
+ - Keep imports explicit and public APIs listed in each package's `__all__`.
18
+ - Use PEP 8 naming and type annotations where practical. Prefer short descriptive module names.
19
+ - Keep user examples in README or `examples/`, not in core implementation flows.
20
+ - When changing an API or path, update code, package exports, README commands, examples, agent guidance, and packaging inclusion rules together.
21
+ - Do not claim a build, example, or test succeeded unless it was actually run. Report dependency or environment blockers clearly.
22
+
23
+ ## Release flow
24
+
25
+ - `pyproject.toml` is the sole source of truth for distribution version, Python requirement, dependencies, and build backend. Runtime `__version__` must read installed metadata with `importlib.metadata`; use `0+unknown` only when importing an uninstalled source checkout. Never duplicate the release version in Python code.
26
+ - The first public release must have a user-approved license and a configured PyPI Trusted Publisher.
27
+ - Release publishing runs only from a published GitHub Release through `.github/workflows/publish-pypi.yml`; do not publish directly from a local checkout unless the user explicitly requests that route.
28
+ - Before release, build both sdist and wheel and inspect them with `twine check`; verify the `AGENTS.md` files and package README are present in the intended artifacts.
29
+ - Keep version tags and the `pyproject.toml` version aligned. Never overwrite or re-upload an already released version; increment the version for each release.
30
+
31
+
@@ -0,0 +1,25 @@
1
+ """Top-level namespace for the degawong Python package."""
2
+ from importlib.metadata import PackageNotFoundError, version
3
+
4
+ from . import frequency_features
5
+ from .frequency_features import (
6
+ EXTRACTOR_REGISTRY,
7
+ FrequencyFeatures,
8
+ FrequencyFeatureExtractor,
9
+ create_extractor,
10
+ )
11
+
12
+ try:
13
+ __version__ = version("degawong")
14
+ except PackageNotFoundError:
15
+ # Source checkout has no installed distribution metadata yet.
16
+ __version__ = "0+unknown"
17
+
18
+ __all__ = [
19
+ "EXTRACTOR_REGISTRY",
20
+ "FrequencyFeatures",
21
+ "FrequencyFeatureExtractor",
22
+ "__version__",
23
+ "create_extractor",
24
+ "frequency_features",
25
+ ]
@@ -0,0 +1,53 @@
1
+ # Agent Rules for `degawong.frequency_features`
2
+
3
+ These rules apply to this subpackage. Keep implementation, auto-discovery, public imports, README, research notes, and runnable examples coherent. Do not modify synced project references under the repository's `sources/` directory.
4
+
5
+ ## Package layout
6
+
7
+ ```text
8
+ src/degawong/frequency_features/
9
+ ├── AGENTS.md
10
+ ├── README.md
11
+ ├── __init__.py
12
+ ├── frequency_feature.py
13
+ ├── registry.py
14
+ ├── strategies/ # concrete strategies only
15
+ ├── examples/ # generic scheme-selectable example
16
+ └── docs/research/ # longer research/reference reports
17
+ ```
18
+
19
+ ## Strategy API and naming
20
+
21
+ - Concrete modules live under `strategies/`; inherit `FrequencyFeatureExtractor` and declare a unique class-level `scheme_name` in lowercase `snake_case`.
22
+ - Module names use short descriptive lowercase `snake_case`; class names use `PascalCase`.
23
+ - Implement paired `forward(BCHW Tensor) -> FrequencyFeatures` and `inverse(FrequencyFeatures) -> BCHW Tensor`. Do not fake an inverse for lossy features; propose a separate feature-only base if needed.
24
+ - `FrequencyFeatures` carries scheme ID, named bands, original dimensions, and reconstruction metadata. Document band meanings/order and all boundary/padding rules. Validate scheme IDs, shapes, dtype/device, and preserve autograd.
25
+ - The registry scans only modules in `strategies/`, rejects duplicate/malformed scheme IDs, and creates implementations through `create_extractor()`. Do not add manual mappings or scan unrelated package files.
26
+ - Preserve Python 3.8 compatibility and avoid new dependencies unless the algorithm needs them.
27
+
28
+ ## Required synchronized updates
29
+
30
+ When adding or changing a strategy, update all relevant items in one change:
31
+
32
+ 1. The concrete implementation under `strategies/`.
33
+ 2. Public exports in `__init__.py` only when the public package API changes or a deliberate convenience export is wanted; the factory must work without a per-strategy root export.
34
+ 3. `README.md`: principle, band names/shapes/order, inverse behavior, boundary handling, suitable use cases, limitations, dependencies, and selection command.
35
+ 4. `examples/quickstart.py`: keep it generic; select by discovered `scheme_name`, never import or branch on concrete strategy classes. Add a strategy-specific example only if the shared example cannot explain a special flow.
36
+ 5. Research documents under `docs/research/` when method comparisons or recommendations change. Use concise English filenames, link reports from README, and do not duplicate source code that belongs in strategy modules.
37
+ 6. `pyproject.toml` package-data patterns and `MANIFEST.in` if adding files that must ship in the wheel or source distribution.
38
+ 7. Search for stale module names, imports, and run commands after renames.
39
+
40
+ After `python -m pip install -e .` (or after installing the published package), the generic example runs from the repository root as:
41
+
42
+ ```bash
43
+ python -m degawong.frequency_features.examples.quickstart --help
44
+ python -m degawong.frequency_features.examples.quickstart --scheme <scheme_name>
45
+ ```
46
+
47
+ ## Completion notes
48
+
49
+ Inspect the final package tree and imports. Report which examples/checks were actually run and any missing dependencies; never claim an unrun build or test succeeded. Summarize the scheme ID, code/docs/example updates, invocation command, and limitations.
50
+
51
+ ## Reusable task prompt
52
+
53
+ > Follow `src/degawong/frequency_features/AGENTS.md`. Add the requested frequency strategy under `strategies/` with the shared API and a unique stable `scheme_name`. Ensure automatic discovery works without a manual registry entry. Update the public README, generic selection example if needed, related research notes, and package-data/manifest rules for any new documents. Document band order, boundaries, suitable uses and limitations; check stale paths and report exactly what was verified.
@@ -0,0 +1,88 @@
1
+ # 频域特征提取包
2
+
3
+ ## 开发约定
4
+
5
+ 新增或修改方案时,请遵循 [AGENTS.md](AGENTS.md)。其中规定了自动发现边界、类命名、公共接口以及实现、README 和示例的同步要求。
6
+
7
+ ## 目录结构
8
+
9
+ ```text
10
+ frequency_features/
11
+ ├── AGENTS.md
12
+ ├── __init__.py
13
+ ├── frequency_feature.py
14
+ ├── registry.py
15
+ ├── strategies/
16
+ │ └── haar_dwt.py
17
+ ├── examples/
18
+ │ └── quickstart.py
19
+ ├── docs/research/
20
+ │ └── frequency_methods.md
21
+ └── README.md
22
+ ```
23
+
24
+ ## 快速切换方案
25
+
26
+ 在项目根目录完成 `python -m pip install -e .` 后运行;`--help` 会显示自动发现的方案名:
27
+
28
+ ```bash
29
+ python -m degawong.frequency_features.examples.quickstart --help
30
+ python -m degawong.frequency_features.examples.quickstart --scheme haar_dwt
31
+ ```
32
+
33
+ 通用示例不导入具体实现类。新增方案后,它会自动出现在 `--scheme` 的选项里。程序化调用同样通过稳定的方案名创建实例:
34
+
35
+ ```python
36
+ import torch
37
+ from degawong.frequency_features import create_extractor
38
+
39
+ extractor = create_extractor("haar_dwt")
40
+ image = torch.randn(2, 3, 255, 257) # BCHW
41
+ features = extractor(image)
42
+ reconstructed = extractor.inverse(features)
43
+
44
+ print(features.scheme_name)
45
+ for band_name, band in features.bands.items():
46
+ print(band_name, band.shape)
47
+ ```
48
+
49
+ ## 自动发现约定
50
+
51
+ `registry.py` 只扫描 `degawong.frequency_features.strategies` 子包中的 Python 模块,导入模块后收集该模块自己定义的、非抽象 `FrequencyFeatureExtractor` 子类。每个实现需声明类级 `scheme_name`,如 `"haar_dwt"`;注册器会检查标记格式和重复名称。基类、工厂、README 与示例不在扫描目录内,因此不会被当作提取方案。
52
+
53
+ 发现发生在包首次导入时,并缓存于当前 Python 进程。新增策略文件后,重新启动运行进程即可看到它。各策略模块应只定义方案实现和必要的纯函数,不应在导入时读写文件、启动任务或执行推理。
54
+
55
+ ## 公共接口
56
+
57
+ 所有注册方案继承 `FrequencyFeatureExtractor`,并遵循统一接口:`forward(BCHW Tensor) -> FrequencyFeatures` 和 `inverse(FrequencyFeatures) -> BCHW Tensor`。系数对象保存 `scheme_name`、命名子带、输入尺寸和逆变换所需的 metadata。逆变换拒绝其他方案产生的系数。
58
+
59
+ 显式记录子带名称和顺序。拼接要求子带具有相同 batch/空间形状、设备和 dtype;只有这些条件兼容时才使用 `features.as_tensor(order)` 拼接通道,并明确传入顺序。通用 quickstart 会逐个显示 band 名称和形状,不假设所有方案返回相同子带或可以拼接。
60
+
61
+ ## 当前方案:单层二维 Haar DWT
62
+
63
+ `HaarDWTFeatureExtractor` 对每个通道独立进行单层 Haar 离散小波变换,得到 `LL/LH/HL/HH` 四个子带。`LL` 表示低频近似,其他子带描述不同方向的局部变化。实现无可训练参数且可微;奇数高宽在底部/右侧补零,逆变换后裁剪回原尺寸。
64
+
65
+ 小波拆分适合图像增强、去噪、去模糊、超分辨率等低层视觉任务,尤其当模型需要分别利用粗尺度结构与方向性边缘/纹理,或需要可逆下采样时。DWT 本身不会自动去噪;高频也可能包含文字、细线、毛发和小目标等有效信息。若关注全局周期或窄带谱峰,FFT/DCT 可能更直接;若边界或平移稳定性关键,应评估临界采样 DWT 及其边界策略。
66
+
67
+ SWANet 的公开说明提到通过小波注意力感知并抑制低照度增强中可能放大的噪声,并使用离散小波变换损失。这里提供的是通用 Haar 变换模块,不是 SWANet 完整网络的复刻。
68
+
69
+ ## 源码路径说明
70
+
71
+ 公开仓库页面列出了顶层 `transform/` 和 `WT/` 目录,但 GitHub 文件接口未能读取用户提到的 `ET/transform.py`(该路径返回 404)。因此当前实现不能保证与那份源码逐项一致;如需严格对齐,应依据实际源码核对滤波器、子带方向顺序和边界策略。
72
+
73
+ 参考:
74
+ - https://github.com/hezhiquan/SWANet
75
+ - He et al., “Low-Light Image Enhancement With Multi-Scale Attention and Frequency-Domain Optimization,” IEEE TCSVT, 2024. DOI: 10.1109/TCSVT.2023.3313348.
76
+
77
+
78
+
79
+
80
+ ## 调研报告
81
+
82
+ 频域方法分类、适用场景与论文案例见 [frequency_methods.md](docs/research/frequency_methods.md)。
83
+
84
+
85
+
86
+ 本子包包含的频域方法调研文档位于 docs/research/,其中的建议用于参考,新增实现仍需按目标任务验证。
87
+
88
+
@@ -0,0 +1,12 @@
1
+ """Extensible frequency-domain feature transforms."""
2
+ from .frequency_feature import FrequencyFeatures, FrequencyFeatureExtractor
3
+ from .registry import EXTRACTOR_REGISTRY, create_extractor
4
+ from .strategies.haar_dwt import HaarDWTFeatureExtractor
5
+
6
+ __all__ = [
7
+ "EXTRACTOR_REGISTRY",
8
+ "FrequencyFeatures",
9
+ "FrequencyFeatureExtractor",
10
+ "HaarDWTFeatureExtractor",
11
+ "create_extractor",
12
+ ]
@@ -0,0 +1,261 @@
1
+ # 计算机视觉中的频域特征提取方法
2
+
3
+ ## 原理、分类、应用及 PyTorch 实现
4
+
5
+ 这份研究报告整理上一答的核心内容,包括空间域和频域理论、Fourier / 小波 / 空间滤波 / 可学习频率模块分类、代表性 PyTorch 实现及可视化与重建检查、视觉任务适用性、论文案例、方法对比和网络集成建议。
6
+
7
+ ## 1. 基本理论
8
+
9
+ 二维 DFT:X[k,l] = sum_m sum_n x[m,n] exp(-j 2 pi (km/H + ln/W))。
10
+ 逆变换:x[m,n] = (1/HW) sum_k sum_l X[k,l] exp(j 2 pi (km/H + ln/W))。
11
+ 幅度 |X| 表示频率强度,相位 phi 参与空间对齐及重建。FFT 是快速 DFT 算法;RFFT 利用实值输入的共轭对称只保留半谱。fftshift 仅为显示将零频移到中心。
12
+
13
+ 低频可描述缓变照明、亮度、大色块或大轮廓;中频可描述局部形状、边界与主要纹理尺度;高频可描述锐边、细纹理,也可能是噪声、压缩振铃和锐化伪影。低频不等同背景,高频不等同细节。全图 Fourier 系数不携带局部位置标签。幅度和相位共同决定重建。
14
+
15
+ 傅里叶卷积定理:F{x*h}=F{x}F{h}。频域利于显式频带操作和全局交互;局限包括相位丢失、弱局部定位、周期边界引起泄漏和高频噪声放大。频率、尺度、方向和局部性相互相关但不同。卷积也有频率响应;注意力不是傅里叶变换;FNO 是学习函数算子的谱方法。
16
+
17
+ ## 2. 方法分类
18
+
19
+ ### Fourier 方法
20
+
21
+ DFT 定义变换,FFT 快速计算,RFFT 存实信号半谱;DCT 是实余弦基。掩码 M 频带重建为 F^-1(M⊙X)。低通保留零频附近,高通保留外围,带通保留环带,带阻抑制环带。硬掩码会振铃,平滑掩码更稳。全局 FFT 频率表达强而定位弱;patch FFT 增加局部性但需融合和边界处理。可学习频率滤波应考虑共轭对称、尺寸变化及过拟合。
22
+
23
+ ### 小波
24
+
25
+ 二维 DWT 经过低通 h、高通 g 和下采样产生 LL=(h_y*h_x)↓2、LH=(h_y*g_x)↓2、HL=(g_y*h_x)↓2、HH=(g_y*g_x)↓2。LL 为粗尺度结构,LH/HL 为两个轴向变化,HH 对角和细节;方向标号依实现约定。逐级分解 LL 产生多尺度表示。Haar 简单快但粗糙;Daubechies 多消失矩、滤波器更长;Symlets 更对称;Coiflets 在小波和尺度函数上设消失矩。SWT 不下采样、冗余高但平移较稳定;DTCWT 有复相位及更好方向选择性,代价更高。DWT 对平移敏感,边界规则影响重建;可学习小波需约束才保证可逆。
26
+
27
+ ### 空间滤波与频率感知
28
+
29
+ Gaussian 为低通;Laplacian 为二阶边缘/高频响应;Laplacian pyramid 以高斯层差构造多尺度带通;DoG 是 Gaussian 差,近似 LoG。Gabor 以窗函数乘正弦波,具局部频率与方向选择性;steerable filters 用基滤波器线性合成任意方向;Sobel/Scharr 是离散梯度。它们是空间滤波器,有频率响应,但不是全局变换。
30
+
31
+ 可学习频域滤波器做 FFT、复权重乘法及逆 FFT;Frequency attention 可能只重加权频率统计,不一定可逆。双域网络以空间分支保位置、频域分支建模全局频率。普通卷积也隐式学习频率响应。Scattering 是固定小波+模值+低通的稳定特征;Graph spectral methods 在图拉普拉斯基上定义图频率;FNO 学习 PDE 等函数到函数算子;Fourier positional features 是坐标编码,不是图像 FFT。
32
+
33
+ ## 3. PyTorch 实现要点
34
+
35
+ 上一答给出完整 PyTorch 代码,包含 FFT/RFFT 幅度、相位与低中高频重建,Haar DWT/IDWT、正交 DCT/IDCT、Gaussian、Laplacian、DoG、Gabor bank、Learnable Fourier Filter、空间-频率融合、可视化和正确性检查。核心形状及验证如下:
36
+
37
+ - FFT: 输入 [B,C,H,W],半谱 [B,C,H,W//2+1] complex;irfft2 传 s=(H,W) 后恢复输入形状。
38
+ - Haar: 四子带各 [B,C,ceil(H/2),ceil(W/2)],拼接为 4C 通道,分辨率约减半。示例对右/下补复制边界,逆变换裁回原尺寸。
39
+ - DCT: 输出与输入同尺寸;完整正交系数可逆。
40
+ - Gaussian/Laplacian/DoG: 输出 [B,C,H,W],通常非可逆。
41
+ - Gabor: 输出 [B,C*O,H,W],O 是方向数。
42
+ - Learnable Fourier: 输入/输出同空间尺寸;训练网格固定,并需 Hermitian 约束。
43
+ - 正确性检查要打印 Haar、DCT、FFT 最大绝对误差和 MSE,并用损失 backward 检查梯度。
44
+
45
+ 代码覆盖逻辑:FFT 用 torch.fft.rfft2/irfft2;Haar 将偶/奇行列的四个像素线性组合成四子带;DCT 构造正交余弦矩阵并分离执行两轴变换;Gaussian/DoG/Gabor/Laplacian 用固定 depthwise conv2d;可学习 Fourier 变换谱乘参数后逆变换。奇数尺寸、设备、dtype、边界需统一。Daubechies/Symlet/Coiflet、SWT、DTCWT 可借助 pytorch_wavelets 或 PyWavelets;训练应避免 CPU/NumPy 往返。
46
+
47
+ 核心实现脚本如下,可保存为 .py 运行。它覆盖变换、滤波、频带重建、频域融合及可视化:
48
+
49
+ ~~~python
50
+ import math
51
+ import torch
52
+ import torch.nn as nn
53
+ import torch.nn.functional as F
54
+ import matplotlib.pyplot as plt
55
+
56
+ def pad_even(x):
57
+ h,w=x.shape[-2:]
58
+ return F.pad(x,(0,w%2,0,h%2),mode="replicate"),(h,w)
59
+
60
+ class FFTFeatures(nn.Module):
61
+ def forward(self,x):
62
+ z=torch.fft.rfft2(x.float(),norm="ortho")
63
+ return z,torch.log1p(z.abs()),torch.angle(z)
64
+ @staticmethod
65
+ def band(z,h,w,kind="low",r0=.08,r1=.35):
66
+ fy=torch.fft.fftfreq(h,device=z.device)[:,None]
67
+ fx=torch.fft.rfftfreq(w,device=z.device)[None,:]
68
+ r=(fx.square()+fy.square()).sqrt()
69
+ if kind=="low": m=r<=r0
70
+ elif kind=="high": m=r>=r1
71
+ elif kind=="mid": m=(r>=r0)&(r<=r1)
72
+ else: raise ValueError("kind must be low/high/mid")
73
+ return torch.fft.irfft2(z*m,s=(h,w),norm="ortho")
74
+
75
+ class HaarDWT2(nn.Module):
76
+ def forward(self,x):
77
+ xp,orig=pad_even(x)
78
+ a,b=xp[...,0::2,0::2],xp[...,0::2,1::2]
79
+ c,d=xp[...,1::2,0::2],xp[...,1::2,1::2]
80
+ return ((a+b+c+d)*.5,(a-b+c-d)*.5,
81
+ (a+b-c-d)*.5,(a-b-c+d)*.5),orig
82
+ @staticmethod
83
+ def inverse(bands,orig):
84
+ ll,lh,hl,hh=bands
85
+ a=(ll+lh+hl+hh)*.5; b=(ll-lh+hl-hh)*.5
86
+ c=(ll+lh-hl-hh)*.5; d=(ll-lh-hl+hh)*.5
87
+ B,C,h,w=ll.shape; y=ll.new_empty((B,C,2*h,2*w))
88
+ y[...,0::2,0::2]=a; y[...,0::2,1::2]=b
89
+ y[...,1::2,0::2]=c; y[...,1::2,1::2]=d
90
+ oh,ow=orig
91
+ return y[...,:oh,:ow]
92
+
93
+ class DCT2(nn.Module):
94
+ def forward(self,x):
95
+ h,w=x.shape[-2:]; dev=x.device
96
+ def mat(n):
97
+ k=torch.arange(n,device=dev,dtype=torch.float32)[:,None]
98
+ i=torch.arange(n,device=dev,dtype=torch.float32)[None,:]
99
+ A=torch.cos(math.pi*(i+.5)*k/n)
100
+ A[0]*=math.sqrt(1/n)
101
+ if n>1: A[1:]*=math.sqrt(2/n)
102
+ return A
103
+ Ah,Aw=mat(h),mat(w)
104
+ return (Ah@x.float()@Aw.T).to(x.dtype),(Ah,Aw)
105
+ @staticmethod
106
+ def inverse(y,mats):
107
+ Ah,Aw=mats
108
+ return (Ah.T@y.float()@Aw).to(y.dtype)
109
+
110
+ class GaussianBlur(nn.Module):
111
+ def __init__(self,sigma=1.2):
112
+ super().__init__(); r=math.ceil(3*sigma)
113
+ t=torch.arange(-r,r+1,dtype=torch.float32)
114
+ g=torch.exp(-.5*(t/sigma).square()); g/=g.sum()
115
+ self.register_buffer("k",torch.outer(g,g))
116
+ def forward(self,x):
117
+ c=x.shape[1]; k=self.k.to(x)[None,None].repeat(c,1,1,1)
118
+ p=self.k.shape[0]//2
119
+ return F.conv2d(F.pad(x,(p,p,p,p),mode="reflect"),k,groups=c)
120
+
121
+ class Laplacian(nn.Module):
122
+ def forward(self,x):
123
+ k=x.new_tensor([[0.,1.,0.],[1.,-4.,1.],[0.,1.,0.]])[None,None]
124
+ k=k.repeat(x.shape[1],1,1,1)
125
+ return F.conv2d(F.pad(x,(1,1,1,1),mode="replicate"),k,groups=x.shape[1])
126
+
127
+ class DoG(nn.Module):
128
+ def __init__(self):
129
+ super().__init__(); self.a=GaussianBlur(1.); self.b=GaussianBlur(2.)
130
+ def forward(self,x): return self.a(x)-self.b(x)
131
+
132
+ class GaborBank(nn.Module):
133
+ def __init__(self,ks=15,orientations=8,wavelength=6.,sigma=3.,gamma=.7):
134
+ super().__init__(); t=torch.arange(ks,dtype=torch.float32)-(ks-1)/2
135
+ yy,xx=torch.meshgrid(t,t,indexing="ij"); bank=[]
136
+ for i in range(orientations):
137
+ th=math.pi*i/orientations
138
+ xr=xx*math.cos(th)+yy*math.sin(th)
139
+ yr=-xx*math.sin(th)+yy*math.cos(th)
140
+ env=torch.exp(-(xr.square()+gamma**2*yr.square())/(2*sigma**2))
141
+ g=env*torch.cos(2*math.pi*xr/wavelength)
142
+ g-=g.mean(); g/=g.abs().sum()+1e-8; bank.append(g)
143
+ self.register_buffer("bank",torch.stack(bank)[:,None])
144
+ def forward(self,x):
145
+ c=x.shape[1]; k=self.bank.to(x).repeat(c,1,1,1)
146
+ p=self.bank.shape[-1]//2
147
+ return F.conv2d(F.pad(x,(p,p,p,p),mode="reflect"),k,groups=c)
148
+
149
+ class LearnableFourierFilter(nn.Module):
150
+ def __init__(self,channels,h,w):
151
+ super().__init__()
152
+ self.weight=nn.Parameter(torch.ones(channels,h,w//2+1,dtype=torch.cfloat))
153
+ def forward(self,x):
154
+ z=torch.fft.rfft2(x.float(),norm="ortho")
155
+ y=torch.fft.irfft2(z*self.weight,s=x.shape[-2:],norm="ortho")
156
+ return y.to(x.dtype)
157
+
158
+ class SpatialFrequencyFuse(nn.Module):
159
+ def __init__(self,channels,h,w):
160
+ super().__init__()
161
+ self.freq=LearnableFourierFilter(channels,h,w)
162
+ self.mix=nn.Conv2d(2*channels,channels,1)
163
+ def forward(self,x):
164
+ return self.mix(torch.cat([x,self.freq(x)],dim=1))
165
+
166
+ def visualize(x):
167
+ gray=x[0].mean(0).float()
168
+ z=torch.fft.fft2(gray,norm="ortho")
169
+ panels=[gray,torch.log1p(torch.abs(torch.fft.fftshift(z))),
170
+ torch.angle(torch.fft.fftshift(z))]
171
+ zr=torch.fft.rfft2(gray,norm="ortho")
172
+ panels += [FFTFeatures.band(zr,*gray.shape,k) for k in ("low","mid","high")]
173
+ (ll,lh,hl,hh),_=HaarDWT2()(gray[None,None])
174
+ panels += [ll[0,0],lh[0,0],hl[0,0],hh[0,0]]
175
+ g=GaborBank()(gray[None,None]); panels += [g[0,0],g[0,1]]
176
+ names=["input","FFT magnitude","FFT phase","low","mid","high",
177
+ "LL","LH","HL","HH","Gabor 0","Gabor 1"]
178
+ fig,axs=plt.subplots(3,4,figsize=(13,8))
179
+ for ax,im,title in zip(axs.flat,panels,names):
180
+ ax.imshow(im.detach().cpu(),cmap="gray")
181
+ ax.set_title(title); ax.axis("off")
182
+ plt.tight_layout(); return fig
183
+
184
+ def check():
185
+ for h,w in [(31,47),(32,48)]:
186
+ x=torch.randn(2,3,h,w,requires_grad=True)
187
+ bands,orig=HaarDWT2()(x); xr=HaarDWT2.inverse(bands,orig)
188
+ print("Haar max abs, MSE",float((x-xr).abs().max()),float(F.mse_loss(xr,x)))
189
+ c,m=DCT2()(x); xd=DCT2.inverse(c,m)
190
+ print("DCT max abs, MSE",float((x-xd).abs().max()),float(F.mse_loss(xd,x)))
191
+ z,mag,phase=FFTFeatures()(x)
192
+ xi=torch.fft.irfft2(z,s=(h,w),norm="ortho")
193
+ print("FFT shape, max abs",tuple(z.shape),float((x-xi).abs().max()))
194
+ (xi.mean()+mag.mean()).backward(); assert x.grad is not None
195
+ print(GaussianBlur()(x).shape,Laplacian()(x).shape,
196
+ DoG()(x).shape,GaborBank()(x).shape)
197
+
198
+ if __name__=="__main__": check()
199
+ ~~~
200
+
201
+ ## 4. 任务与方法选择
202
+
203
+ | 任务 | 频域价值 | 方法建议 | 风险 |
204
+ |---|---|---|---|
205
+ | 去噪 | 子带/噪声谱先验 | 小波特征、频谱辅助损失 | 高频纹理与噪声重叠 |
206
+ | 去模糊 | 方向性频率衰减 | 定向滤波、Fourier 中间特征 | 频谱零点不可逆 |
207
+ | 超分辨率 | 高频细节恢复 | 小波监督、逐级高频重建 | 伪纹理 |
208
+ | 压缩伪影 | 块效应、振铃、量化 | DCT 与空间网络融合 | 块边界 |
209
+ | 低光/曝光 | 光照与细节耦合、提亮放大噪声 | Fourier 幅度/小波细节加空间照明估计 | 亮度并非只在幅度 |
210
+ | Retinex 分解 | 光照较平滑、反射含边缘 | 金字塔、小波或学习分解 | 光照边缘也可能高频 |
211
+ | 融合 | 多源各频带信噪比不同 | 小波/金字塔多尺度融合 | 高频噪声被增强 |
212
+ | 分类/检测/分割 | 纹理与形状、全局局部依赖 | Gabor/DWT 早期,FFT 中层 | 频谱捷径 |
213
+ | 纹理/生成编辑 | 局部重复、身份和结构保持 | Gabor、局部频率、小波辅助损失 | 全局频谱丢失布局 |
214
+ | 医学/遥感 | 多尺度、小病灶和边界 | 小波/方向滤波,高分辨率层 | 设备/分辨率变化 |
215
+
216
+ ## 5. 论文与代码案例
217
+
218
+ - SWANet(He 等,IEEE TCSVT 2024):MIANet 做多尺度照明调整,WNENet 用小波注意力感知并抑噪,DWT loss 监督;官方仓库报告 LOL、MIT-Adobe FiveK 结果和训练流程。[官方仓库](https://github.com/hezhiquan/SWANet)
219
+ - FourLLIE(Wang、Wu、Jin,ACM Multimedia 2023):阶段一估计 Fourier 幅度变换图增强亮度;阶段二用 SNR map 融合全局频率和局部空间信息。[官方仓库](https://github.com/wangchx67/FourLLIE)
220
+ - MWCNN(Liu 等,CVPRW 2018):多级小波用于图像恢复,以小波下采样扩大感受野,逆变换恢复特征。[论文](https://openaccess.thecvf.com/content_cvpr_2018_workshops/w13/html/Liu_Multi-Level_Wavelet-CNN_for_CVPR_2018_paper.html) · [代码](https://github.com/lpj0/MWCNN)
221
+ - WaveCNet(Li 等,CVPR 2020):DWT/IDWT 用于噪声鲁棒分类。[论文](https://openaccess.thecvf.com/content_CVPR_2020/html/Li_Wavelet_Integrated_CNNs_for_Noise-Robust_Image_Classification_CVPR_2020_paper.html) · [代码](https://github.com/CVI-SZU/WaveCNet)
222
+ - GFNet(Rao 等,NeurIPS 2021):以 2D DFT、可学习全局滤波、IDFT 替换视觉 Transformer 注意力,并验证 ImageNet 和下游准确率/复杂度折中。[论文](https://papers.nips.cc/paper/2021/hash/07e87c2f4fc7f7c96116d8e2a92790f5-Abstract.html) · [代码](https://github.com/raoyongming/GFNet)
223
+ - Fast Fourier Convolution(Chi 等,NeurIPS 2020):局部、半全局和全局频谱支路用于识别、视频和关键点。[论文](https://proceedings.neurips.cc/paper/2020/hash/2fd5d41ec6cfab47e32164d5624269b1-Abstract.html)
224
+ - Learning Gabor Texture Features(Zhu 等,ICCV 2023):可学习 Gabor 纹理支路与 CNN 语义支路用于细粒度识别。[论文](https://openaccess.thecvf.com/content/ICCV2023/html/Zhu_Learning_Gabor_Texture_Features_for_Fine-Grained_Recognition_ICCV_2023_paper.html)
225
+ - FNO(Li 等,ICLR 2021):Fourier 域学习算子核,主要验证 Burgers、Darcy flow、Navier–Stokes PDE,不是普通视觉任务证据。[论文](https://arxiv.org/abs/2010.08895)
226
+
227
+ 看论文消融时应比较移除频率分支、替换空间模块、匹配参数与 FLOPs;“使用了 FFT/小波”本身不足以证明收益。
228
+
229
+ ## 6. 横向比较
230
+
231
+ | 方法 | 频率/定位/尺度 | 相位/可逆 | 主要限制 |
232
+ |---|---|---|---|
233
+ | FFT/DFT | 全局频率强,定位弱,可分带 | 复相位;未滤波可逆 | O(HW log HW)、复数内存、周期边界 |
234
+ | RFFT | 同 FFT,半谱存储 | 相位保留,逆变换需原尺寸 | 需正确传递图像尺寸 |
235
+ | DCT | 实余弦频率,定位弱 | 无显式复相位,正交时可逆 | 大尺寸矩阵成本 |
236
+ | DWT | 局部子带、方向、多级 | 正交时可逆 | 平移敏感、边界依赖 |
237
+ | SWT/DTCWT | 局部多尺度,方向性强 | DTCWT 有复相位 | 冗余和显存 |
238
+ | Gaussian/DoG/Laplacian | 局部且频响明确 | 通常不可逆 | 多尺度/方向增加卷积 |
239
+ | Gabor/steerable | 局部方向与中心频率 | 复 Gabor 可表示相位 | 滤波器数量与超参 |
240
+ | Learnable Fourier/attention | 可学习频带权重 | 可反传,注意力通常非可逆 | 尺寸、共轭对称、过拟合 |
241
+ | FNO/图谱 | 算子模态或图频率 | 依方法设计 | 任务专用、边界或建图成本 |
242
+
243
+ FFT 渐近 O(HW log(HW)),小波每级约 O(HW);实际速度取决于内存布局、GPU kernel、复数支持和数据搬运。小卷积可能更快。纹理优先 Gabor/局部小波,边缘用梯度或高频小波,全局交互用 FFT/FFC/GFNet 并保留空间路,多尺度用 DWT,平移稳定需求评估 SWT/DTCWT,抑噪需小波加学习型去噪,光照变化需照明估计加细节分支。
244
+
245
+ ## 7. 集成建议与总结
246
+
247
+ 先定位纹理、光照、周期噪声、边缘或长程依赖问题,再从瓶颈/中间层加频率分支,以残差或门控融合并保留空间路径。核对奇数尺寸、边界、归一化和逆变换。恢复任务同时评价像素、感知和边缘;分类任务测试设备、压缩、模糊和缩放泛化。消融需有参数量相当的空间模块对照。Fourier 幅度损失不保证空间对齐,应与像素/结构损失共用。
248
+
249
+ FFT 适合全局频率,小波适合局部多尺度,Gabor/steerable 适合方向纹理,Gaussian/Laplacian/DoG 是空间滤波器,可学习模块让频率响应适应数据。频域特征不增加信息且不普遍优于空间域;按任务失效模式选择,依靠公平消融确认有效性。
250
+
251
+ ### 参考链接
252
+
253
+ - [SWANet,TCSVT 2024 官方仓库](https://github.com/hezhiquan/SWANet)
254
+ - [MWCNN,CVPRW 2018](https://openaccess.thecvf.com/content_cvpr_2018_workshops/w13/html/Liu_Multi-Level_Wavelet-CNN_for_CVPR_2018_paper.html) · [代码](https://github.com/lpj0/MWCNN)
255
+ - [Wavelet Integrated CNNs,CVPR 2020](https://openaccess.thecvf.com/content_CVPR_2020/html/Li_Wavelet_Integrated_CNNs_for_Noise-Robust_Image_Classification_CVPR_2020_paper.html) · [代码](https://github.com/CVI-SZU/WaveCNet)
256
+ - [FourLLIE,ACM Multimedia 2023](https://github.com/wangchx67/FourLLIE)
257
+ - [GFNet,NeurIPS 2021](https://papers.nips.cc/paper/2021/hash/07e87c2f4fc7f7c96116d8e2a92790f5-Abstract.html) · [代码](https://github.com/raoyongming/GFNet)
258
+ - [Fast Fourier Convolution,NeurIPS 2020](https://proceedings.neurips.cc/paper/2020/hash/2fd5d41ec6cfab47e32164d5624269b1-Abstract.html)
259
+ - [Learning Gabor Texture Features,ICCV 2023](https://openaccess.thecvf.com/content/ICCV2023/html/Zhu_Learning_Gabor_Texture_Features_for_Fine-Grained_Recognition_ICCV_2023_paper.html)
260
+ - [Fourier Neural Operator,ICLR 2021](https://arxiv.org/abs/2010.08895)
261
+ - [Fourier Features Let Networks Learn,NeurIPS 2020](https://proceedings.neurips.cc/paper_files/paper/2020/file/55053683268957697aa39fba6f231c68-Paper.pdf)
@@ -0,0 +1 @@
1
+ """Runnable usage examples for frequency_features."""
@@ -0,0 +1,53 @@
1
+ """Run a frequency feature scheme by its registered name.
2
+
3
+ From the project root:
4
+ python -m degawong.frequency_features.examples.quickstart --scheme haar_dwt
5
+ python -m degawong.frequency_features.examples.quickstart --help
6
+ """
7
+ import argparse
8
+
9
+ import torch
10
+
11
+ from degawong.frequency_features import EXTRACTOR_REGISTRY, create_extractor
12
+
13
+
14
+ def parse_args() -> argparse.Namespace:
15
+ parser = argparse.ArgumentParser(description=__doc__)
16
+ parser.add_argument(
17
+ "--scheme",
18
+ choices=sorted(EXTRACTOR_REGISTRY),
19
+ required=True,
20
+ help="frequency feature scheme to run",
21
+ )
22
+ parser.add_argument(
23
+ "--device",
24
+ default="cpu",
25
+ help="PyTorch device, for example cpu or cuda",
26
+ )
27
+ return parser.parse_args()
28
+
29
+
30
+ def main() -> None:
31
+ args = parse_args()
32
+ device = torch.device(args.device)
33
+ extractor = create_extractor(args.scheme).to(device)
34
+ image = torch.randn(2, 3, 255, 257, device=device)
35
+
36
+ features = extractor(image)
37
+ reconstructed = extractor.inverse(features)
38
+
39
+ print(f"Scheme: {extractor.scheme_name}")
40
+ print(f"Input shape: {tuple(image.shape)}")
41
+ print("Bands:")
42
+ for name, band in features.bands.items():
43
+ print(f" {name}: {tuple(band.shape)} ({band.dtype})")
44
+ print(f"Reconstructed shape: {tuple(reconstructed.shape)}")
45
+ max_error = (image - reconstructed).abs().max().item()
46
+ print(f"Maximum round-trip error: {max_error:.8f}")
47
+
48
+
49
+ if __name__ == "__main__":
50
+ main()
51
+
52
+
53
+
@@ -0,0 +1,70 @@
1
+ """Shared interfaces for frequency-domain feature transforms."""
2
+ from __future__ import annotations
3
+
4
+ from abc import ABC, abstractmethod
5
+ from dataclasses import dataclass, field
6
+ from typing import Any, ClassVar, Dict, Tuple
7
+
8
+ import torch
9
+ from torch import Tensor, nn
10
+
11
+
12
+ @dataclass
13
+ class FrequencyFeatures:
14
+ """Named transform coefficients and the information needed to invert them."""
15
+
16
+ scheme_name: str
17
+ bands: Dict[str, Tensor]
18
+ original_shape: Tuple[int, int, int, int]
19
+ metadata: Dict[str, Any] = field(default_factory=dict)
20
+
21
+ def as_tensor(self, order: Tuple[str, ...]) -> Tensor:
22
+ """Concatenate compatible bands along channels in an explicit order."""
23
+ if not order:
24
+ raise ValueError("order must contain at least one band")
25
+ missing = set(order).difference(self.bands)
26
+ if missing:
27
+ raise KeyError(f"Unknown frequency bands: {sorted(missing)}")
28
+ selected = [self.bands[name] for name in order]
29
+ if any(tensor.ndim != 4 for tensor in selected):
30
+ raise ValueError("All selected bands must be BCHW tensors")
31
+ reference = selected[0]
32
+ if any(
33
+ tensor.shape[0] != reference.shape[0]
34
+ or tensor.shape[2:] != reference.shape[2:]
35
+ for tensor in selected[1:]
36
+ ):
37
+ raise ValueError(
38
+ "Selected bands must have matching batch and spatial dimensions"
39
+ )
40
+ if any(
41
+ tensor.device != reference.device or tensor.dtype != reference.dtype
42
+ for tensor in selected[1:]
43
+ ):
44
+ raise ValueError("Selected bands must have matching device and dtype")
45
+ return torch.cat(selected, dim=1)
46
+
47
+
48
+ class FrequencyFeatureExtractor(nn.Module, ABC):
49
+ """Common analysis/synthesis API for invertible frequency transforms.
50
+
51
+ Every concrete class declares a stable class-level ``scheme_name`` and
52
+ implements ``forward(x) -> FrequencyFeatures`` and
53
+ ``inverse(features) -> Tensor``.
54
+ """
55
+
56
+ scheme_name: ClassVar[str]
57
+
58
+ @abstractmethod
59
+ def forward(self, x: Tensor) -> FrequencyFeatures:
60
+ """Map a BCHW tensor to named frequency bands."""
61
+ raise NotImplementedError
62
+
63
+ @abstractmethod
64
+ def inverse(self, features: FrequencyFeatures) -> Tensor:
65
+ """Reconstruct a BCHW tensor from this scheme's coefficients."""
66
+ raise NotImplementedError
67
+
68
+
69
+ __all__ = ["FrequencyFeatures", "FrequencyFeatureExtractor"]
70
+
@@ -0,0 +1,83 @@
1
+ """Discover built-in extractors from the dedicated strategies package."""
2
+ from __future__ import annotations
3
+
4
+ import importlib
5
+ import inspect
6
+ import pkgutil
7
+ import re
8
+ from types import MappingProxyType
9
+ from typing import Any, Dict, Mapping, Type
10
+
11
+ from .frequency_feature import FrequencyFeatureExtractor
12
+
13
+ _SCHEME_NAME_PATTERN = re.compile(r"^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$")
14
+ ExtractorType = Type[FrequencyFeatureExtractor]
15
+
16
+
17
+ def _discover_extractors() -> Dict[str, ExtractorType]:
18
+ """Import strategy modules and collect their concrete extractor classes."""
19
+ package_name = f"{__package__}.strategies"
20
+ package = importlib.import_module(package_name)
21
+ registry: Dict[str, ExtractorType] = {}
22
+
23
+ module_infos = sorted(
24
+ pkgutil.iter_modules(package.__path__), key=lambda module: module.name
25
+ )
26
+ for module_info in module_infos:
27
+ if module_info.ispkg or module_info.name.startswith("_"):
28
+ continue
29
+ module_name = f"{package_name}.{module_info.name}"
30
+ module = importlib.import_module(module_name)
31
+ candidates = (
32
+ value
33
+ for value in vars(module).values()
34
+ if inspect.isclass(value)
35
+ and value is not FrequencyFeatureExtractor
36
+ and issubclass(value, FrequencyFeatureExtractor)
37
+ and value.__module__ == module.__name__
38
+ and not inspect.isabstract(value)
39
+ )
40
+
41
+ for extractor_type in candidates:
42
+ scheme_name = extractor_type.__dict__.get("scheme_name")
43
+ if not isinstance(scheme_name, str) or not _SCHEME_NAME_PATTERN.fullmatch(
44
+ scheme_name
45
+ ):
46
+ raise ValueError(
47
+ f"{extractor_type.__module__}.{extractor_type.__name__} must "
48
+ "define a class-level scheme_name in lowercase snake_case"
49
+ )
50
+ if scheme_name in registry:
51
+ other = registry[scheme_name]
52
+ raise ValueError(
53
+ f"Duplicate scheme_name {scheme_name!r}: "
54
+ f"{other.__module__}.{other.__name__} and "
55
+ f"{extractor_type.__module__}.{extractor_type.__name__}"
56
+ )
57
+ registry[scheme_name] = extractor_type
58
+
59
+ return registry
60
+
61
+
62
+ # Discovery is intentionally scoped to strategies/ and happens once per process.
63
+ EXTRACTOR_REGISTRY: Mapping[str, ExtractorType] = MappingProxyType(
64
+ _discover_extractors()
65
+ )
66
+
67
+
68
+ def create_extractor(
69
+ scheme_name: str, **kwargs: Any
70
+ ) -> FrequencyFeatureExtractor:
71
+ """Create a discovered extractor by its stable scheme identifier."""
72
+ try:
73
+ extractor_type = EXTRACTOR_REGISTRY[scheme_name]
74
+ except KeyError as exc:
75
+ available = ", ".join(sorted(EXTRACTOR_REGISTRY)) or "(none)"
76
+ raise ValueError(
77
+ f"Unknown frequency scheme {scheme_name!r}. "
78
+ f"Available schemes: {available}"
79
+ ) from exc
80
+ return extractor_type(**kwargs)
81
+
82
+
83
+ __all__ = ["EXTRACTOR_REGISTRY", "create_extractor"]
@@ -0,0 +1 @@
1
+ """Built-in frequency extraction strategies discovered by registry.py."""
@@ -0,0 +1,100 @@
1
+ """Single-level, channel-wise 2D Haar DWT and its exact inverse."""
2
+ from __future__ import annotations
3
+
4
+ from typing import ClassVar, Tuple
5
+
6
+ import torch
7
+ import torch.nn.functional as F
8
+ from torch import Tensor
9
+
10
+ from ..frequency_feature import FrequencyFeatures, FrequencyFeatureExtractor
11
+
12
+
13
+ class HaarDWTFeatureExtractor(FrequencyFeatureExtractor):
14
+ """Single-level Haar DWT returning LL, LH, HL and HH coefficient bands.
15
+
16
+ The transform is parameter-free and differentiable. Odd input dimensions
17
+ are zero-padded at the bottom/right, then cropped by ``inverse``.
18
+ """
19
+
20
+ scheme_name: ClassVar[str] = "haar_dwt"
21
+ band_order: ClassVar[Tuple[str, ...]] = ("LL", "LH", "HL", "HH")
22
+
23
+ def forward(self, x: Tensor) -> FrequencyFeatures:
24
+ if x.ndim != 4:
25
+ raise ValueError(f"Expected BCHW input, got shape {tuple(x.shape)}")
26
+ if not x.is_floating_point():
27
+ raise TypeError("Haar DWT expects a floating-point tensor")
28
+
29
+ b, c, h, w = x.shape
30
+ if h == 0 or w == 0:
31
+ raise ValueError("Input height and width must be positive")
32
+ pad_h, pad_w = h % 2, w % 2
33
+ x = F.pad(x, (0, pad_w, 0, pad_h))
34
+ h2, w2 = x.shape[-2] // 2, x.shape[-1] // 2
35
+ tiles = x.reshape(b, c, h2, 2, w2, 2)
36
+ x00 = tiles[:, :, :, 0, :, 0]
37
+ x01 = tiles[:, :, :, 0, :, 1]
38
+ x10 = tiles[:, :, :, 1, :, 0]
39
+ x11 = tiles[:, :, :, 1, :, 1]
40
+
41
+ bands = {
42
+ "LL": (x00 + x01 + x10 + x11) * 0.5,
43
+ "LH": (x00 - x01 + x10 - x11) * 0.5,
44
+ "HL": (x00 + x01 - x10 - x11) * 0.5,
45
+ "HH": (x00 - x01 - x10 + x11) * 0.5,
46
+ }
47
+ return FrequencyFeatures(
48
+ scheme_name=self.scheme_name,
49
+ bands=bands,
50
+ original_shape=(b, c, h, w),
51
+ metadata={"pad_hw": (pad_h, pad_w)},
52
+ )
53
+
54
+ def inverse(self, features: FrequencyFeatures) -> Tensor:
55
+ if features.scheme_name != self.scheme_name:
56
+ raise ValueError(
57
+ f"Expected coefficients from {self.scheme_name!r}, "
58
+ f"got {features.scheme_name!r}"
59
+ )
60
+ missing = set(self.band_order).difference(features.bands)
61
+ if missing:
62
+ raise ValueError(f"Missing Haar bands: {sorted(missing)}")
63
+
64
+ ll, lh, hl, hh = (features.bands[name] for name in self.band_order)
65
+ bands = (ll, lh, hl, hh)
66
+ if any(not isinstance(band, Tensor) or band.ndim != 4 for band in bands):
67
+ raise TypeError("All Haar bands must be BCHW tensors")
68
+ if any(band.shape != ll.shape for band in bands[1:]):
69
+ raise ValueError("All Haar bands must have the same shape")
70
+ if any(
71
+ band.device != ll.device or band.dtype != ll.dtype
72
+ for band in bands[1:]
73
+ ):
74
+ raise ValueError("All Haar bands must have the same device and dtype")
75
+
76
+ if len(features.original_shape) != 4:
77
+ raise ValueError("original_shape must contain BCHW dimensions")
78
+ b0, c0, h0, w0 = features.original_shape
79
+ if h0 <= 0 or w0 <= 0:
80
+ raise ValueError("Original height and width must be positive")
81
+ b, c, h2, w2 = ll.shape
82
+ if (b, c) != (b0, c0):
83
+ raise ValueError(
84
+ "Coefficient batch/channel shape does not match original_shape"
85
+ )
86
+ if (h2, w2) != ((h0 + 1) // 2, (w0 + 1) // 2):
87
+ raise ValueError("Coefficient spatial shape does not match original_shape")
88
+
89
+ x00 = (ll + lh + hl + hh) * 0.5
90
+ x01 = (ll - lh + hl - hh) * 0.5
91
+ x10 = (ll + lh - hl - hh) * 0.5
92
+ x11 = (ll - lh - hl + hh) * 0.5
93
+ tiles = torch.stack((x00, x01, x10, x11), dim=-1)
94
+ x = tiles.reshape(b, c, h2, w2, 2, 2)
95
+ x = x.permute(0, 1, 2, 4, 3, 5).reshape(b, c, h2 * 2, w2 * 2)
96
+ return x[..., :h0, :w0]
97
+
98
+
99
+ __all__ = ["HaarDWTFeatureExtractor"]
100
+
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,104 @@
1
+ Metadata-Version: 2.4
2
+ Name: degawong
3
+ Version: 0.1.0
4
+ Summary: Reusable PyTorch frequency-domain feature extraction modules
5
+ Classifier: Development Status :: 3 - Alpha
6
+ Classifier: Intended Audience :: Science/Research
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Programming Language :: Python :: 3.8
9
+ Classifier: Topic :: Scientific/Engineering :: Image Processing
10
+ Requires-Python: >=3.8
11
+ Description-Content-Type: text/markdown
12
+ Requires-Dist: torch>=1.8
13
+
14
+ # degawong
15
+
16
+ `degawong` is an installable Python package for reusable image and tensor utilities. The current release includes a frequency-domain feature extraction subpackage built with PyTorch.
17
+
18
+ ## Install
19
+
20
+ After the first release is published to PyPI:
21
+
22
+ ```bash
23
+ python -m pip install degawong
24
+ ```
25
+
26
+ For local development from a clone:
27
+
28
+ ```bash
29
+ python -m pip install -e .
30
+ ```
31
+
32
+ The frequency feature modules require PyTorch. It is declared as a package dependency so a normal install includes it.
33
+
34
+ ## Import the package
35
+
36
+ The top-level package exposes its current subpackage and common frequency API:
37
+
38
+ ```python
39
+ import degawong
40
+
41
+ extractor = degawong.create_extractor("haar_dwt")
42
+ print(degawong.frequency_features.EXTRACTOR_REGISTRY.keys())
43
+ ```
44
+
45
+ You can also import the frequency feature API directly:
46
+
47
+ ```python
48
+ from degawong.frequency_features import create_extractor
49
+
50
+ extractor = create_extractor("haar_dwt")
51
+ ```
52
+
53
+ Run the generic example from the repository root:
54
+
55
+ ```bash
56
+ python -m degawong.frequency_features.examples.quickstart --help
57
+ python -m degawong.frequency_features.examples.quickstart --scheme haar_dwt
58
+ ```
59
+
60
+ The frequency package's module layout, automatic strategy discovery, and extension rules are documented in [its README](src/degawong/frequency_features/README.md) and [AGENTS.md](src/degawong/frequency_features/AGENTS.md).
61
+
62
+ ## Package structure
63
+
64
+ ```text
65
+ src/degawong/
66
+ ├── __init__.py
67
+ ├── AGENTS.md
68
+ ├── py.typed
69
+ └── frequency_features/
70
+ ├── __init__.py
71
+ ├── frequency_feature.py
72
+ ├── registry.py
73
+ ├── strategies/
74
+ └── examples/
75
+ ```
76
+
77
+ `import degawong` exposes the subpackages deliberately imported by `degawong/__init__.py`; it does not scan or import future modules implicitly. Add each new public subpackage there and document its direct import path.
78
+
79
+ ## Build distributions
80
+
81
+ From the repository root:
82
+
83
+ ```bash
84
+ python -m pip install --upgrade build twine
85
+ python -m build
86
+ python -m twine check dist/*
87
+ ```
88
+
89
+ The project uses the standard `pyproject.toml` build configuration and the `src/` layout. `src/` is conventional, not mandatory; it separates the installable package from repository-level reference material and build files. Markdown agent guidance and the frequency-methods research report are included in source and wheel distributions as package data. Read the [research report](src/degawong/frequency_features/docs/research/frequency_methods.md).
90
+
91
+ ## Publish through GitHub Actions
92
+
93
+ The workflow at `.github/workflows/publish-pypi.yml` builds and publishes a GitHub Release to PyPI using PyPI Trusted Publishing (OIDC), without storing a PyPI API token in GitHub secrets.
94
+
95
+ Before the first release:
96
+
97
+ 1. Create/configure the `degawong` project on PyPI, or configure its pending publisher.
98
+ 2. Add a PyPI Trusted Publisher for the GitHub owner/repository, workflow file `publish-pypi.yml`, and GitHub environment `pypi`.
99
+ 3. Choose the package's license and add the corresponding `LICENSE` file and metadata. No license was inferred or selected in this scaffold.
100
+ 4. Set the project version in `pyproject.toml`, commit and push the changes, create a matching version tag/release, then publish that GitHub Release.
101
+
102
+ The GitHub repository URL is intentionally not hard-coded because the target repository has not been specified.
103
+
104
+
@@ -0,0 +1,21 @@
1
+ MANIFEST.in
2
+ README.md
3
+ pyproject.toml
4
+ src/degawong/AGENTS.md
5
+ src/degawong/__init__.py
6
+ src/degawong/py.typed
7
+ src/degawong.egg-info/PKG-INFO
8
+ src/degawong.egg-info/SOURCES.txt
9
+ src/degawong.egg-info/dependency_links.txt
10
+ src/degawong.egg-info/requires.txt
11
+ src/degawong.egg-info/top_level.txt
12
+ src/degawong/frequency_features/AGENTS.md
13
+ src/degawong/frequency_features/README.md
14
+ src/degawong/frequency_features/__init__.py
15
+ src/degawong/frequency_features/frequency_feature.py
16
+ src/degawong/frequency_features/registry.py
17
+ src/degawong/frequency_features/docs/research/frequency_methods.md
18
+ src/degawong/frequency_features/examples/__init__.py
19
+ src/degawong/frequency_features/examples/quickstart.py
20
+ src/degawong/frequency_features/strategies/__init__.py
21
+ src/degawong/frequency_features/strategies/haar_dwt.py
@@ -0,0 +1 @@
1
+ torch>=1.8
@@ -0,0 +1 @@
1
+ degawong