in s2/regioncoverer.go [430:499]
func (c *coverer) normalizeCovering(covering *CellUnion) {
// If any cells are too small, or don't satisfy levelMod, then replace them with ancestors.
if c.maxLevel < maxLevel || c.levelMod > 1 {
for i, ci := range *covering {
level := ci.Level()
newLevel := c.adjustLevel(minInt(level, c.maxLevel))
if newLevel != level {
(*covering)[i] = ci.Parent(newLevel)
}
}
}
// Sort the cells and simplify them.
covering.Normalize()
// Make sure that the covering satisfies minLevel and levelMod,
// possibly at the expense of satisfying MaxCells.
if c.minLevel > 0 || c.levelMod > 1 {
covering.Denormalize(c.minLevel, c.levelMod)
}
// If there are too many cells and the covering is very large, use the
// RegionCoverer to compute a new covering. (This avoids possible O(n^2)
// behavior of the simpler algorithm below.)
excess := len(*covering) - c.maxCells
if excess <= 0 || c.isCanonical(*covering) {
return
}
if excess*len(*covering) > 10000 {
rc := NewRegionCoverer()
(*covering) = rc.Covering(covering)
return
}
// If there are still too many cells, then repeatedly replace two adjacent
// cells in CellID order by their lowest common ancestor.
for len(*covering) > c.maxCells {
bestIndex := -1
bestLevel := -1
for i := 0; i+1 < len(*covering); i++ {
level, ok := (*covering)[i].CommonAncestorLevel((*covering)[i+1])
if !ok {
continue
}
level = c.adjustLevel(level)
if level > bestLevel {
bestLevel = level
bestIndex = i
}
}
if bestLevel < c.minLevel {
break
}
// Replace all cells contained by the new ancestor cell.
id := (*covering)[bestIndex].Parent(bestLevel)
(*covering) = c.replaceCellsWithAncestor(*covering, id)
// Now repeatedly check whether all children of the parent cell are
// present, in which case we can replace those cells with their parent.
for bestLevel > c.minLevel {
bestLevel -= c.levelMod
id = id.Parent(bestLevel)
if !c.containsAllChildren(*covering, id) {
break
}
(*covering) = c.replaceCellsWithAncestor(*covering, id)
}
}
}