Skip to content

feat: adding the bartlett function#3155

Open
Vlor999 wants to merge 1 commit intoml-explore:mainfrom
Vlor999:feat/add-bartlett-window
Open

feat: adding the bartlett function#3155
Vlor999 wants to merge 1 commit intoml-explore:mainfrom
Vlor999:feat/add-bartlett-window

Conversation

@Vlor999
Copy link
Contributor

@Vlor999 Vlor999 commented Feb 22, 2026

Description

This PR adds the Bartlett (triangular) window function (mlx.core.bartlett), continuing the effort to expand MLX's signal processing capabilities and feature parity with NumPy.

Implementation Details

  • C++: Implemented in mlx/ops.cpp.
    • Optimization (No Branching): Instead of using conditional masking (where or less_equal) to build the triangular shape, this implementation leverages the absolute value identity: $w(n) = 1 - \left| \frac{2n}{M-1} - 1 \right|$. This avoids branching in the compute graph, making it significantly more efficient on the GPU.
    • Constant Folding: The scalar factor 2.0 / (M-1) is computed on the CPU prior to graph construction to minimize graph size.
    • Edge Cases: Explicitly handles M < 1 (empty array) and M = 1 (returns [1.0]), matching numpy.bartlett behavior.
  • Python Bindings: Exposed via nanobind in python/src/ops.cpp with nb::sig type hinting and LaTeX documentation.

Test Plan

Verified locally against numpy.bartlett for numerical accuracy and edge cases.

Verification script:

import mlx.core as mx
import numpy as np

# 1. Standard Case
M = 50
mx_bartlett = mx.bartlett(M)
np_bartlett = np.bartlett(M)

assert np.allclose(mx_bartlett, np_bartlett, atol=1e-6), "Mismatch in values"

# 2. Edge Case M=1
assert mx.bartlett(1).item() == 1.0
assert np.bartlett(1).item() == 1.0

# 3. Edge Case M=0
assert mx.bartlett(0).size == 0

print("✅ All verifications passed against numpy.bartlett")

Unit Tests:

Added test_bartlett to python/tests/test_ops.py.

Checklist

Put an x in the boxes that apply.

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

Copy link
Member

@angeloskath angeloskath left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

@angeloskath
Copy link
Member

Let's merge after the tests pass and conflicts are resolved.

@Vlor999 Vlor999 force-pushed the feat/add-bartlett-window branch 2 times, most recently from 54c65e8 to 49d11b6 Compare February 26, 2026 19:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants