Commit a57cf516 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Redesign Soundmarks: ephemeral user drops + business applications

Full replacement of the major/community tiers and propose+vote mechanism
with: any user drops a song at their current location (24h TTL via a
read-time cutoff filter, clustered within 25m via union-find at query
time), and businesses become persistent, playlist-owning soundmarks only
through a self-service application a super admin approves - replacing the
old admin-picks-an-existing-owner flow entirely.

- Soundmark splits into two tables: soundmarks (business-only now, owner
  required) and the new SoundmarkDrop/BusinessApplication.
- SoundmarkProposal/SoundmarkProposalVote retired outright.
- New endpoints: POST /drop, POST/GET /business-applications(/mine),
  approve/reject. /nearby now returns {businesses, drop_clusters}.
- Migration wipes existing major/community rows (kept business ones,
  per the user's explicit direction), tightens business_owner_id to
  NOT NULL - verified both directions against a scratch DB copy.
- tests/test_soundmarks.py rewritten for the new shape; full backend
  suite green (506 passed).
parent eb82e2ab
Pipeline #1328 failed with stage
in 23 seconds
"""redesign soundmarks: drops and business applications
Revision ID: 33120d763567
Revises: 499ebec0825d
Create Date: 2026-12-03 19:58:00.000000
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '33120d763567'
down_revision: Union[str, Sequence[str], None] = '499ebec0825d'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
# Retiring the major/community tiers entirely (full replacement, confirmed with the user -
# see Soundmark's docstring in database.py). Wipe their data first, while `tier` still
# exists to filter on - children before parents.
op.execute("DELETE FROM soundmark_proposal_votes")
op.execute("DELETE FROM soundmark_suggestions WHERE soundmark_id IN (SELECT id FROM soundmarks WHERE tier != 'business')")
op.execute("DELETE FROM soundmark_playlist_tracks WHERE soundmark_id IN (SELECT id FROM soundmarks WHERE tier != 'business')")
op.execute("DELETE FROM soundmarks WHERE tier != 'business'")
op.drop_index(op.f('ix_soundmark_proposal_votes_user_id'), table_name='soundmark_proposal_votes')
op.drop_index(op.f('ix_soundmark_proposal_votes_proposal_id'), table_name='soundmark_proposal_votes')
op.drop_index(op.f('ix_soundmark_proposal_votes_id'), table_name='soundmark_proposal_votes')
op.drop_table('soundmark_proposal_votes')
op.drop_index(op.f('ix_soundmark_proposals_soundmark_id'), table_name='soundmark_proposals')
op.drop_index(op.f('ix_soundmark_proposals_id'), table_name='soundmark_proposals')
op.drop_table('soundmark_proposals')
# song_id carries a FK to library_songs - SQLite's native ALTER TABLE DROP COLUMN can't drop
# a column involved in a foreign key, so this needs batch mode (table-rebuild) rather than a
# plain op.drop_column, unlike tier (no FK). Bundled with tightening business_owner_id in
# the same batch - every surviving row is business-tier and already has an owner (enforced
# by the old _validate_tier_and_owner at the API layer), so this is safe.
with op.batch_alter_table('soundmarks') as batch_op:
batch_op.drop_column('tier')
batch_op.drop_column('song_id')
batch_op.alter_column('business_owner_id', existing_type=sa.Integer(), nullable=False)
op.create_table('soundmark_drops',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('song_id', sa.Integer(), nullable=False),
sa.Column('dropped_by_user_id', sa.Integer(), nullable=False),
sa.Column('latitude', sa.Float(), nullable=False),
sa.Column('longitude', sa.Float(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['song_id'], ['library_songs.id'], ),
sa.ForeignKeyConstraint(['dropped_by_user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id'),
)
op.create_index(op.f('ix_soundmark_drops_id'), 'soundmark_drops', ['id'], unique=False)
op.create_index(op.f('ix_soundmark_drops_song_id'), 'soundmark_drops', ['song_id'], unique=False)
op.create_index(op.f('ix_soundmark_drops_dropped_by_user_id'), 'soundmark_drops', ['dropped_by_user_id'], unique=False)
op.create_index(op.f('ix_soundmark_drops_created_at'), 'soundmark_drops', ['created_at'], unique=False)
op.create_table('business_applications',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('business_name', sa.String(), nullable=False),
sa.Column('phone_number', sa.String(), nullable=False),
sa.Column('latitude', sa.Float(), nullable=False),
sa.Column('longitude', sa.Float(), nullable=False),
sa.Column('submitted_by_user_id', sa.Integer(), nullable=False),
sa.Column('status', sa.String(), nullable=True),
sa.Column('reviewed_by_user_id', sa.Integer(), nullable=True),
sa.Column('reviewed_at', sa.DateTime(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['submitted_by_user_id'], ['users.id'], ),
sa.ForeignKeyConstraint(['reviewed_by_user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id'),
)
op.create_index(op.f('ix_business_applications_id'), 'business_applications', ['id'], unique=False)
op.create_index(op.f('ix_business_applications_submitted_by_user_id'), 'business_applications', ['submitted_by_user_id'], unique=False)
op.create_index(op.f('ix_business_applications_status'), 'business_applications', ['status'], unique=False)
def downgrade() -> None:
"""Downgrade schema. Wiped tier/song data is not recoverable - same as any destructive
migration in this repo."""
op.drop_index(op.f('ix_business_applications_status'), table_name='business_applications')
op.drop_index(op.f('ix_business_applications_submitted_by_user_id'), table_name='business_applications')
op.drop_index(op.f('ix_business_applications_id'), table_name='business_applications')
op.drop_table('business_applications')
op.drop_index(op.f('ix_soundmark_drops_created_at'), table_name='soundmark_drops')
op.drop_index(op.f('ix_soundmark_drops_dropped_by_user_id'), table_name='soundmark_drops')
op.drop_index(op.f('ix_soundmark_drops_song_id'), table_name='soundmark_drops')
op.drop_index(op.f('ix_soundmark_drops_id'), table_name='soundmark_drops')
op.drop_table('soundmark_drops')
with op.batch_alter_table('soundmarks') as batch_op:
batch_op.alter_column('business_owner_id', existing_type=sa.Integer(), nullable=True)
batch_op.add_column(sa.Column('song_id', sa.Integer(), nullable=True))
batch_op.add_column(sa.Column('tier', sa.String(), nullable=False, server_default='business'))
batch_op.create_foreign_key('fk_soundmarks_song_id_library_songs', 'library_songs', ['song_id'], ['id'])
op.create_table('soundmark_proposals',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('soundmark_id', sa.Integer(), nullable=True),
sa.Column('song_id', sa.Integer(), nullable=True),
sa.Column('proposed_by_user_id', sa.Integer(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['proposed_by_user_id'], ['users.id'], ),
sa.ForeignKeyConstraint(['song_id'], ['library_songs.id'], ),
sa.ForeignKeyConstraint(['soundmark_id'], ['soundmarks.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('soundmark_id', 'song_id', name='uq_soundmark_proposal_song'),
)
op.create_index(op.f('ix_soundmark_proposals_id'), 'soundmark_proposals', ['id'], unique=False)
op.create_index(op.f('ix_soundmark_proposals_soundmark_id'), 'soundmark_proposals', ['soundmark_id'], unique=False)
op.create_table('soundmark_proposal_votes',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('proposal_id', sa.Integer(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['proposal_id'], ['soundmark_proposals.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('proposal_id', 'user_id', name='uq_soundmark_proposal_vote'),
)
op.create_index(op.f('ix_soundmark_proposal_votes_id'), 'soundmark_proposal_votes', ['id'], unique=False)
op.create_index(op.f('ix_soundmark_proposal_votes_proposal_id'), 'soundmark_proposal_votes', ['proposal_id'], unique=False)
op.create_index(op.f('ix_soundmark_proposal_votes_user_id'), 'soundmark_proposal_votes', ['user_id'], unique=False)
# Soundmarks API changes — for Android client wiring
Backend repo: stax_backend_api, router: `src/api/routers/soundmarks.py`, prefix `/soundmarks`.
All authenticated endpoints use the same Bearer-token auth as every other endpoint in this API.
## Removed endpoints (delete any client code calling these)
- `POST /soundmarks` (old admin create-soundmark-with-tier)
- `PATCH /soundmarks/{id}/song` (major-tier "set anthem")
- `GET /soundmarks/{id}/proposals`
- `POST /soundmarks/{id}/proposals`
- `POST /soundmarks/{id}/proposals/{proposal_id}/vote`
- `DELETE /soundmarks/{id}/proposals/vote`
The whole three-tier (`major`/`community`/`business`) model is gone. There are now
only two kinds of map pin: **business** (persistent, admin-approved) and **drop
cluster** (ephemeral, user-generated, 1+ songs).
## Changed: `GET /soundmarks/nearby?lat={lat}&lon={lon}&drop_radius_km={km}`
Response shape changes from a flat `soundmarks: [...]` array to:
```json
{
"businesses": [
{
"id": 1,
"name": "Cafe Example",
"description": "...",
"latitude": 0.0,
"longitude": 0.0,
"radius_meters": 200.0,
"business_owner_username": "owner123",
"current_song": { "...song object..." } ,
"playlist": [ { "...song object...", "position": 0 } ]
}
],
"drop_clusters": [
{
"id": 123,
"latitude": 0.0,
"longitude": 0.0,
"distance_meters": 12.3,
"drops": [
{ "id": 1, "song": { "...song object..." }, "dropped_by_username": "alice", "created_at": "2026-12-03T12:00:00Z" },
{ "id": 2, "song": { "...song object..." }, "dropped_by_username": "bob", "created_at": "2026-12-03T12:05:00Z" }
]
}
]
}
```
- `businesses` entries no longer have `tier` or `proposal_count` — drop any UI/model
code keyed on tier.
- `drop_clusters` is new: each entry groups one or more individually-attributed song
drops that are within 25 meters of each other. **Render one pin per cluster, not
one pin per drop.** Tapping a cluster pin should list every entry in `drops` (song +
`dropped_by_username` + `created_at`), even when there's only one.
- Drops older than 24 hours are already excluded server-side — the client needs no
expiry/TTL logic, just re-fetch `/nearby` periodically (e.g. on map move/refresh) to
pick up both new drops and ones that have aged out.
- `drop_radius_km` is optional (default `1.0`) — same role as whatever radius param
the client previously used for the old flat `nearby` call.
## Changed: `PATCH /soundmarks/{id}` (business soundmark edit)
Request body no longer accepts `tier`, `business_owner_id`, or `song_id` — only
`name`, `description`, `latitude`, `longitude`, `radius_meters`.
## New: `POST /soundmarks/drop`
Auth required.
Request:
```json
{ "song_id": 42, "latitude": 0.0, "longitude": 0.0 }
```
Response:
```json
{
"status": "success",
"drop": { "id": 1, "song": {...}, "dropped_by_username": "alice", "latitude": 0.0, "longitude": 0.0, "created_at": "..." }
}
```
404 if `song_id` doesn't exist. This is the "drop a song at my current location"
action: read device GPS, let the user pick a song (reuse whatever song-search/picker
UI already existed for the old propose/suggest flows), POST here. No tier/owner
concept involved.
## New: Business application flow (replaces old admin-only business creation)
- **`POST /soundmarks/business-applications`** — auth required.
Request: `{ "business_name": "...", "phone_number": "...", "latitude": 0.0, "longitude": 0.0 }`
Returns the created application. 409 if the caller already has a `pending`
application.
- **`GET /soundmarks/business-applications/mine`** — auth required. Returns the
caller's own applications (`status`: `pending`/`approved`/`rejected`), newest first.
Check this before showing the application form, to instead show "pending review" /
"approved — manage your business" / re-show-the-form states.
- **`GET /soundmarks/business-applications?status=pending`** — super admin only.
Lists applications for review.
- **`POST /soundmarks/business-applications/{id}/approve`** — super admin only.
Returns `{ "status": "success", "application": {...}, "soundmark": {...} }` — the
newly created business soundmark.
- **`POST /soundmarks/business-applications/{id}/reject`** — super admin only.
Approving an application automatically promotes the submitter's role to
`business_admin` server-side — no extra client call needed, just re-fetch the current
user's role/profile afterward so any role-gated nav updates.
## Unchanged, still valid as-is
- `GET /soundmarks/mine`, `GET /soundmarks/song-library`, `GET /soundmarks/geocode`,
`GET /soundmarks/reverse-geocode`
- All `/soundmarks/admin/users*` endpoints
- `GET /soundmarks/suggestions`, `POST /soundmarks/suggestions/{id}/approve|reject`
- `POST /soundmarks/{id}/playlist`, `DELETE /soundmarks/{id}/playlist/{song_id}`
- `GET /soundmarks/{id}/stream`
- `POST /soundmarks/{id}/suggestions` (suggest a song for a business soundmark's playlist)
- `DELETE /soundmarks/{id}`
- "Add song to my library" — reuse whatever endpoint the client already calls for
that elsewhere (backend: `POST /library/shared/claim` with `{title, artist}`) for
the business-pin "add to my library" action; nothing new was added for this
specifically.
## Map/UI behavior summary
- Two pin types now (not three): **business** (persistent, admin-approved) and **drop
cluster** (ephemeral, 1+ user drops within 25m of each other). No more
"major"/"community" distinction.
- Business pin tap → show playlist, current song, "suggest a song," "add to my
library."
- Drop-cluster pin tap → list each drop (song + dropper username + time dropped).
- A floating "drop a song here" action, always available when location is known →
opens song picker → `POST /soundmarks/drop` → refresh `/nearby`.
- A "become a business" entry point (form: name, phone, map pin) → `POST
/business-applications`, then poll/check `/business-applications/mine` for status.
This diff is collapsed.
...@@ -257,36 +257,57 @@ class LiveLocation(Base): ...@@ -257,36 +257,57 @@ class LiveLocation(Base):
updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc)) updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
class Soundmark(Base): class Soundmark(Base):
"""A curated 'anthem' tied to a real-world place - distinct from LiveLocation (a live """A persistent, business-owned location with a playlist - distinct from LiveLocation (a
per-user broadcast of wherever they currently are, not a persistent place). Three tiers, live per-user broadcast of wherever they currently are) and from SoundmarkDrop (an
distinguished by `tier`: ephemeral, user-dropped song with no owner - see below). Created only by approving a
BusinessApplication (see soundmarks.py); always has an owner (business_owner_id) and a
- "major": a super-admin-curated landmark. One official song (song_id), set directly by a *playlist* (SoundmarkPlaylistTrack) the owner adds/removes tracks from directly
super admin (auto-applied). Anyone else's pick goes through SoundmarkSuggestion instead. (auto-applied) - everyone else's picks go through SoundmarkSuggestion's review queue
- "business": owned by a business_owner_id. Has a *playlist* (SoundmarkPlaylistTrack), not instead."""
a single song - the owner adds/removes tracks directly (auto-applied); everyone else's
picks go through SoundmarkSuggestion.
- "community": no owner, fully automated. Anyone can propose a song (SoundmarkProposal) and
vote; the most-voted one just plays, no review step at all - see
soundmarks.py's _resolve_active_song_id.
song_id is only meaningful for "major" (and as a legacy fallback for pre-tier "community"
rows that predate SoundmarkProposal - see _resolve_active_song_id)."""
__tablename__ = "soundmarks" __tablename__ = "soundmarks"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
name = Column(String, index=True) name = Column(String, index=True)
description = Column(String, nullable=True) description = Column(String, nullable=True)
tier = Column(String, default="community", nullable=False) # "major" | "business" | "community"
latitude = Column(Float) latitude = Column(Float)
longitude = Column(Float) longitude = Column(Float)
# How close (in meters) someone needs to be for this soundmark to be considered "active" - # How close (in meters) someone needs to be for this soundmark to be considered "active" -
# this is what /soundmarks/nearby matches against, not a caller-supplied search radius. # this is what /soundmarks/nearby matches against, not a caller-supplied search radius.
radius_meters = Column(Float, default=200.0, nullable=False) radius_meters = Column(Float, default=200.0, nullable=False)
business_owner_id = Column(Integer, ForeignKey("users.id"), nullable=True, index=True) business_owner_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
song_id = Column(Integer, ForeignKey("library_songs.id"), nullable=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc)) updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
class SoundmarkDrop(Base):
"""One song a user dropped at their current location - ephemeral (no owner, nothing ever
edits a row after creation) and ungoverned (no review step). soundmarks.py filters these to
the last 24h at read time (DROP_EXPIRES_AFTER) and groups nearby drops into clusters at
query time (CLUSTER_RADIUS_METERS, via services/geo.py's cluster_by_proximity) rather than
persisting any cluster/group relationship here."""
__tablename__ = "soundmark_drops"
id = Column(Integer, primary_key=True, index=True)
song_id = Column(Integer, ForeignKey("library_songs.id"), nullable=False, index=True)
dropped_by_user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
latitude = Column(Float, nullable=False)
longitude = Column(Float, nullable=False)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), index=True)
class BusinessApplication(Base):
"""A user's self-service request for a location to become a business Soundmark. Reviewed
manually by a super admin (soundmarks.py's approve/reject endpoints) - approving creates the
actual Soundmark row (owner=submitted_by_user_id) and promotes the submitter to
business_admin via the existing _maybe_promote_to_business_admin helper."""
__tablename__ = "business_applications"
id = Column(Integer, primary_key=True, index=True)
business_name = Column(String, nullable=False)
phone_number = Column(String, nullable=False)
latitude = Column(Float, nullable=False)
longitude = Column(Float, nullable=False)
submitted_by_user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
status = Column(String, default="pending", index=True) # "pending" | "approved" | "rejected"
reviewed_by_user_id = Column(Integer, ForeignKey("users.id"), nullable=True)
reviewed_at = Column(DateTime, nullable=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class SoundmarkPlaylistTrack(Base): class SoundmarkPlaylistTrack(Base):
"""One song in a "business"-tier soundmark's playlist. Added directly by the business """One song in a "business"-tier soundmark's playlist. Added directly by the business
owner or a super admin (auto-applied, no review) - see SoundmarkSuggestion for how a owner or a super admin (auto-applied, no review) - see SoundmarkSuggestion for how a
...@@ -300,12 +321,9 @@ class SoundmarkPlaylistTrack(Base): ...@@ -300,12 +321,9 @@ class SoundmarkPlaylistTrack(Base):
added_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) added_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class SoundmarkSuggestion(Base): class SoundmarkSuggestion(Base):
"""A song someone other than the owner suggested for a "major" or "business" soundmark - """A song someone other than the owner suggested for a business soundmark - sits in a
sits in a review queue until the owner (business admin for their own business, super admin review queue until the owner (or a super admin) approves or rejects it. Approving adds a
for major locations - super admin can review either) approves or rejects it. Approving SoundmarkPlaylistTrack."""
applies the effect (sets Soundmark.song_id for "major", adds a SoundmarkPlaylistTrack for
"business"). "community" soundmarks don't use this at all - they use
SoundmarkProposal/SoundmarkProposalVote instead, with no review step."""
__tablename__ = "soundmark_suggestions" __tablename__ = "soundmark_suggestions"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
soundmark_id = Column(Integer, ForeignKey("soundmarks.id"), index=True) soundmark_id = Column(Integer, ForeignKey("soundmarks.id"), index=True)
...@@ -316,29 +334,6 @@ class SoundmarkSuggestion(Base): ...@@ -316,29 +334,6 @@ class SoundmarkSuggestion(Base):
reviewed_at = Column(DateTime, nullable=True) reviewed_at = Column(DateTime, nullable=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class SoundmarkProposal(Base):
"""A candidate anthem someone's suggested for a "community"-tier soundmark - see
Soundmark's docstring. The proposal with the most votes is what actually plays there (see
soundmarks.py's _resolve_active_song_id); there's no review step for this tier."""
__tablename__ = "soundmark_proposals"
__table_args__ = (UniqueConstraint("soundmark_id", "song_id", name="uq_soundmark_proposal_song"),)
id = Column(Integer, primary_key=True, index=True)
soundmark_id = Column(Integer, ForeignKey("soundmarks.id"), index=True)
song_id = Column(Integer, ForeignKey("library_songs.id"))
proposed_by_user_id = Column(Integer, ForeignKey("users.id"))
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class SoundmarkProposalVote(Base):
"""One row per (proposal, voter). A voter switching their pick for a soundmark deletes
their old vote row (on whichever proposal it was) and inserts a new one - enforced in
soundmarks.py, not by a DB constraint, since "one vote per soundmark" spans proposals."""
__tablename__ = "soundmark_proposal_votes"
__table_args__ = (UniqueConstraint("proposal_id", "user_id", name="uq_soundmark_proposal_vote"),)
id = Column(Integer, primary_key=True, index=True)
proposal_id = Column(Integer, ForeignKey("soundmark_proposals.id"), index=True)
user_id = Column(Integer, ForeignKey("users.id"), index=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class LiveRoom(Base): class LiveRoom(Base):
__tablename__ = "live_rooms" __tablename__ = "live_rooms"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
......
...@@ -10,3 +10,33 @@ def haversine_meters(lat1: float, lon1: float, lat2: float, lon2: float) -> floa ...@@ -10,3 +10,33 @@ def haversine_meters(lat1: float, lon1: float, lat2: float, lon2: float) -> floa
dlon = math.radians(lon2 - lon1) dlon = math.radians(lon2 - lon1)
a = math.sin(dlat / 2) ** 2 + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlon / 2) ** 2 a = math.sin(dlat / 2) ** 2 + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlon / 2) ** 2
return R * 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) return R * 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
def cluster_by_proximity(points: list[tuple[float, float]], radius_meters: float) -> list[list[int]]:
"""Groups point indices into clusters via union-find, merging two points whenever they're
within radius_meters of each other - so a transitive chain (A near B, B near C, A far from
C) still ends up in one cluster, not split by naive pairwise grouping. Used by Soundmarks'
/nearby to group ephemeral SoundmarkDrops - recomputed fresh every call (no persisted
cluster identity), matching this file's existing all-pairs-haversine complexity bar."""
parent = list(range(len(points)))
def find(i: int) -> int:
while parent[i] != i:
parent[i] = parent[parent[i]]
i = parent[i]
return i
def union(i: int, j: int) -> None:
ri, rj = find(i), find(j)
if ri != rj:
parent[ri] = rj
for i in range(len(points)):
for j in range(i + 1, len(points)):
if haversine_meters(points[i][0], points[i][1], points[j][0], points[j][1]) <= radius_meters:
union(i, j)
groups: dict[int, list[int]] = {}
for i in range(len(points)):
groups.setdefault(find(i), []).append(i)
return list(groups.values())
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment