forest_navigating_uav/worldgen/forest_worldgen/patterns/scale_dependent.py
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
"""
Scale-dependent (multi-scale) point process.

Combines **clustering at small scale** with **inhibition at a larger
scale**, mimicking natural forests where saplings form clumps but
adult trees compete and thin each other out.

Algorithm
---------
1.  Generate an *over-sampled* clustered pattern (Neyman-Scott) using
    ``sample_clustered`` with a small hard ``min_distance``.
2.  Apply a **secondary thinning** pass at a larger inhibition scale
    ``d_mid``:
        * Deterministic mode (default) - greedily remove the later of
          any two points closer than ``d_mid``.
        * Probabilistic mode - for each pair closer than ``d_mid``,
          remove one with probability ``thin_probability``.
3.  If thinning removed too many points, top up with additional
    clustered children (using the same parents) to approach the
    requested ``count``.

Key parameters (all in ``params`` dict)
---------------------------------------
    d_mid               mid-range inhibition distance (required).
    thin_mode           'deterministic' | 'probabilistic'
                        (default 'deterministic')
    thin_probability    removal probability per violating pair when
                        thin_mode='probabilistic' (default 0.8)
    oversample_factor   how much to oversample before thinning
                        (default 1.5)
    topup_attempts      max rejection-sampling rounds for the top-up
                        phase (default 300)

    Plus all ``sample_clustered`` parameters (cluster_count,
    cluster_radius, scatter_shape, mean_per_cluster, etc.).

Validation targets (logged, not enforced):
    g(r) > 1     at small r   (clustering signature)
    g(r) < 1     at mid r     (inhibition signature)
    L(r) - r     crosses from positive to negative as r increases
"""

import math
import random

from .csr import _point_in_area, _point_in_rect, ProximityGrid
from .clustered import (
    sample_clustered,
    _place_parents,
    _SCATTER_FNS,
    _scatter_gaussian,
    _clamp_to_bounds,
)


# ---------------------------------------------------------------------------
# Thinning passes
# ---------------------------------------------------------------------------


def _thin_deterministic(positions, d_mid):
    """
    Greedy deterministic thinning.

    Walk through *positions* in order; for each point, check against all
    already-accepted points.  Reject if any accepted neighbour is within
    ``d_mid``.  The ordering is randomised first so that the retained set
    isn't biased toward early indices.
    """
    indices = list(range(len(positions)))
    random.shuffle(indices)

    grid = ProximityGrid(d_mid)
    accepted_pts = []
    for i in indices:
        x, y = positions[i]
        if grid.check(x, y, d_mid):
            accepted_pts.append((x, y))
            grid.insert(x, y)

    return accepted_pts


def _thin_probabilistic(positions, d_mid, p_remove=0.8):
    """
    Probabilistic thinning.

    For every point, if it violates ``d_mid`` against any already-accepted
    point, remove it with probability ``p_remove`` (otherwise keep it).
    """
    indices = list(range(len(positions)))
    random.shuffle(indices)

    grid = ProximityGrid(d_mid)
    accepted_pts = []
    for i in indices:
        x, y = positions[i]
        if grid.check(x, y, d_mid):
            accepted_pts.append((x, y))
            grid.insert(x, y)
        elif random.random() > p_remove:
            # survived the thinning coin-flip
            accepted_pts.append((x, y))
            grid.insert(x, y)

    return accepted_pts


# ---------------------------------------------------------------------------
# Top-up: fill deficit by scattering more children around existing parents
# ---------------------------------------------------------------------------


def _topup(
    positions,
    deficit,
    parents,
    cluster_radius,
    scatter_fn,
    region,
    K,
    min_distance,
    d_mid,
    max_attempts=500,
):
    """
    Add *deficit* more points while respecting distance constraints.

    Respect both ``min_distance``
    (hard overlap guard) **and** ``d_mid`` (mid-scale inhibition) against
    all existing *positions*.

    Strategy: alternate between cluster-scatter candidates (to preserve
    the clustering signal) and uniform candidates (to fill gaps the
    clusters can't reach).
    """
    added = []
    # Build grids for both distance thresholds
    grid_min = ProximityGrid(min_distance, positions) if min_distance > 0 else None
    grid_mid = ProximityGrid(d_mid, positions)
    attempts = 0
    total_budget = deficit * max_attempts

    while len(added) < deficit and attempts < total_budget:
        attempts += 1

        # 60 % cluster scatter, 40 % uniform fill
        if parents and random.random() < 0.6:
            cx, cy = random.choice(parents)
            x, y = scatter_fn(cx, cy, cluster_radius)
        else:
            if region is not None:
                x, y = _point_in_rect(region)
            else:
                x, y = _point_in_area(K)

        x, y = _clamp_to_bounds(x, y, region, K)

        if grid_min is not None and not grid_min.check(x, y, min_distance):
            continue
        if not grid_mid.check(x, y, d_mid):
            continue

        added.append((x, y))
        if grid_min is not None:
            grid_min.insert(x, y)
        grid_mid.insert(x, y)

    return added


# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------


def sample_scale_dependent(count, region, K, min_distance, existing_positions, params):
    """
    Scale-dependent multi-scale process.

    Parameters
    ----------
    count : int
        Desired number of output points.
    region : dict | None
        Rectangular sub-region or *None* for the full K×K world.
    K : float
        World side length.
    min_distance : float
        World-level hard minimum distance (small-scale overlap guard).
    existing_positions : list[tuple[float, float]]
        Already-placed points.
    params : dict
        See module docstring for recognised keys.

    Returns
    -------
    list[tuple[float, float]]
    """
    params = params or {}

    d_mid = float(params.get("d_mid", min_distance * 2.5))
    thin_mode = params.get("thin_mode", "deterministic")
    thin_prob = float(params.get("thin_probability", 0.8))
    oversample = float(params.get("oversample_factor", 1.5))
    topup_attempts = int(params.get("topup_attempts", 300))

    # cluster params forwarded as-is (sample_clustered reads its own keys)
    cluster_radius = float(params.get("cluster_radius", 3.0))
    scatter_shape = params.get("scatter_shape", "gaussian")
    scatter_fn = _SCATTER_FNS.get(scatter_shape, _scatter_gaussian)

    # --- 1. over-sample a clustered pattern ---
    n_oversample = max(count, int(math.ceil(count * oversample)))
    raw = sample_clustered(
        n_oversample,
        region,
        K,
        min_distance,
        existing_positions,
        params,
    )

    # --- 2. thin at mid-range scale ---
    if thin_mode == "probabilistic":
        thinned = _thin_probabilistic(raw, d_mid, p_remove=thin_prob)
    else:
        thinned = _thin_deterministic(raw, d_mid)

    # also enforce d_mid against existing_positions
    if existing_positions:
        existing_grid = ProximityGrid(d_mid, existing_positions)
        final = []
        for x, y in thinned:
            if existing_grid.check(x, y, d_mid):
                final.append((x, y))
        thinned = final

    # --- 3. trim or top-up to hit count ---
    if len(thinned) > count:
        random.shuffle(thinned)
        thinned = thinned[:count]

    elif len(thinned) < count:
        deficit = count - len(thinned)

        # recover parent centres for top-up scatter
        cluster_count = max(1, int(params.get("cluster_count", 5)))
        allow_overlap = bool(params.get("allow_cluster_overlap", False))
        if allow_overlap:
            min_parent_dist = 0.0
        else:
            min_parent_dist = float(params.get("min_parent_distance", cluster_radius * 0.5))
        parents = _place_parents(cluster_count, region, K, min_parent_dist)

        extra = _topup(
            existing_positions + thinned,
            deficit,
            parents,
            cluster_radius,
            scatter_fn,
            region,
            K,
            min_distance,
            d_mid,
            max_attempts=topup_attempts,
        )
        thinned.extend(extra)

        if len(thinned) < count:
            shortfall = count - len(thinned)
            print(
                f"Warning [scale_dependent]: could only place "
                f"{len(thinned)}/{count} after thinning + top-up "
                f"(d_mid={d_mid:.2f}, shortfall={shortfall})"
            )

    return thinned