package placement

import (
	
	
	
	
	
	

	

	
	
	
	
)

type sizedOptimizer struct {
	mutationScratch optimizerMutationSnapshot

	g                *layoutgraph.Graph
	edgeAbductions   []*layoutgraph.EdgeAbduction
	randGenerator    *rand.Rand
	fixedOrigin      *geo.Point
	symmetryCost     float64
	cellSize         float64
	obstacles        []geo.Box
	checkedPositions map[geo.Point]struct{}
	placementScratch placementPointsScratch
	spatialIndex     optimizerSpatialIndex
}

func iterPlacementsAroundPoint( *layoutgraph.Node, ,  float64,  bool,  func(,  float64) bool) {
	,  := .Width, .Height
	 *= .Graph.CellSize
	 *= .Graph.CellSize
	 := .Graph.CellSize
	if (, ) || ! {
		return
	}
	for  :=  - ;  <= ;  +=  {
		for  :=  - ;  <= ;  +=  {
			if  ==  &&  ==  {
				continue
			}
			if (, ) {
				return
			}
		}
	}
}

// withHubSpokesSuppressed temporarily removes a hub's spoke edges while fn
// evaluates placements. The original edge slice and ordering are restored on
// success, error, or panic.
func withHubSpokesSuppressed( *layoutgraph.Node,  []*layoutgraph.Node,  *limits.OptimizationWorkGuard,  func() error) ( error) {
	if  == nil {
		return fmt.Errorf("TALA LocalOptimize cannot suppress spokes on a nil hub")
	}
	if len() > limits.MaxEngineNodes || len(.Edges) > limits.MaxEngineEdges {
		return fmt.Errorf("TALA LocalOptimize hub suppression inputs exceed engine limits")
	}
	 := .Edges
	 := make([]bool, len())
	defer func() {
		.Edges = 
	}()

	for ,  := range  {
		if  := .Step();  != nil {
			return 
		}
		if  == nil {
			return fmt.Errorf("TALA LocalOptimize found a nil hub spoke")
		}
		for ,  := range  {
			if  := .Step();  != nil {
				return 
			}
			if [] {
				continue
			}
			if  == nil || (.From !=  && .To != ) {
				return fmt.Errorf("TALA LocalOptimize found a malformed hub edge")
			}
			if .Adjacent() ==  {
				[] = true
				break
			}
		}
	}
	 := make([]*layoutgraph.Edge, 0, len())
	for ,  := range  {
		if  := .Step();  != nil {
			return 
		}
		if ![] {
			 = append(, )
		}
	}
	.Edges = 
	return ()
}

func newSizedOptimizer( context.Context,  *layoutgraph.Graph,  *layoutgraph.Node,  []*layoutgraph.EdgeAbduction,  *rand.Rand,  []geo.Box) (*sizedOptimizer, error) {
	if  == nil {
		return nil, fmt.Errorf("TALA LocalOptimize requires a graph")
	}
	if len(.Nodes) > limits.MaxEngineNodes {
		return nil, fmt.Errorf("TALA LocalOptimize node count exceeds limit %d", limits.MaxEngineNodes)
	}
	if len(.Edges) > limits.MaxEngineEdges {
		return nil, fmt.Errorf("TALA LocalOptimize edge count exceeds limit %d", limits.MaxEngineEdges)
	}
	if len() > limits.MaxEngineEdges {
		return nil, fmt.Errorf("TALA LocalOptimize edge abduction count exceeds limit %d", limits.MaxEngineEdges)
	}
	if int64(len()) > layoutgraph.MaxTopologyReferences {
		return nil, fmt.Errorf("TALA LocalOptimize obstacle count exceeds limit %d", layoutgraph.MaxTopologyReferences)
	}
	if .CellSize < 1 || math.IsNaN(.CellSize) || math.IsInf(.CellSize, 0) || math.Trunc(.CellSize) != .CellSize {
		return nil, fmt.Errorf("TALA LocalOptimize requires a finite positive integer cell size")
	}
	,  := limits.NewOptimizationWorkGuard(, "LocalOptimizeSetup", limits.MaxOptimizationWorkUnits)
	if  != nil {
		return nil, 
	}
	for ,  := range .Nodes {
		if  := .Step();  != nil {
			return nil, 
		}
		if  == nil || .Graph == nil {
			return nil, fmt.Errorf("TALA LocalOptimize found a node without a graph")
		}
		if len(.Edges) > limits.MaxEngineEdges || len(.Nears) > limits.MaxEngineNodes {
			return nil, fmt.Errorf("TALA LocalOptimize node %s adjacency references exceed engine limits", .DebugID())
		}
		if .Graph.CellSize != .CellSize {
			return nil, fmt.Errorf("cell size mismatch for node %s", .DebugID())
		}
	}
	 := &sizedOptimizer{
		g:              ,
		edgeAbductions: ,
		randGenerator:  ,
		fixedOrigin:    .ContainerFixedOrigin(),
		symmetryCost:   .CellSize,
		cellSize:       .CellSize,
		obstacles:      ,
	}
	for ,  := range .Nodes {
		if  := .Step();  != nil {
			return nil, 
		}

		// Pre-process all edge abductions that affect this node
		 := make(map[*layoutgraph.Edge]struct{}, len(.edgeAbductions))
		 := make(map[*layoutgraph.Node]*layoutgraph.Node, len(.Edges))
		for ,  := range .edgeAbductions {
			if  := .Step();  != nil {
				return nil, 
			}
			if  == nil || .Edge == nil {
				return nil, fmt.Errorf("TALA LocalOptimize found a nil edge abduction")
			}
			if .CurrentFrom ==  || .CurrentTo ==  {
				if .OriginallyFrom != nil || .OriginallyTo != nil {
					[.Edge] = struct{}{}
					continue
				}
				 := .Adjacent(.Edge)
				if .CurrentFrom ==  && .OriginallyTo != nil {
					[] = .OriginallyTo
				} else if .CurrentTo ==  && .OriginallyFrom != nil {
					[] = .OriginallyFrom
				}
			}
		}

		 := int(.cellSize)
		 := make(map[*layoutgraph.Node]layoutgraph.LongDistanceNeighborRequirements, len(.Edges))

		for ,  := range .Edges {
			if  := .Step();  != nil {
				return nil, 
			}
			if  == nil || (.From !=  && .To != ) {
				return nil, fmt.Errorf("TALA LocalOptimize found a malformed incident edge on %s", .DebugID())
			}
			if ,  := [];  {
				continue
			}

			 := .Adjacent()
			if ,  := [];  {
				 = 
			}

			 := []
			.EdgeCount++
			if .MinWidth > .MaxWidth {
				.MaxWidth = .MinWidth
			}
			if .MinHeight > .MaxHeight {
				.MaxHeight = .MinHeight
			}
			[] = 
		}

		for ,  := range  {
			if  := .Step();  != nil {
				return nil, 
			}
			if .EdgeCount < 3 {
				continue
			}
			if .MaxWidth <=  && .MaxHeight <=  {
				continue
			}

			.LongDistanceNeighborRequirements = 
			break
		}
	}

	if  := .Finish();  != nil {
		return nil, 
	}
	return , nil
}

func ( *sizedOptimizer) ( context.Context,  float64) (bool, error) {
	return .optimizeWithLimit(, , limits.MaxOptimizationWorkUnits)
}

func ( *sizedOptimizer) ( context.Context,  float64,  uint64) ( bool,  error) {
	, _,  = layoutgraph.EnsureTransactionWorkGuard(, "LocalOptimizeTransactions")
	if  != nil {
		return false, 
	}
	,  := limits.NewOptimizationWorkGuard(, "LocalOptimize", )
	if  != nil {
		return false, 
	}
	if  == nil || .g == nil {
		return false, fmt.Errorf("TALA LocalOptimize requires an optimizer with a graph")
	}
	if .randGenerator == nil {
		return false, fmt.Errorf("TALA LocalOptimize requires a random generator")
	}
	defer .mutationScratch.release()
	,  := captureOptimizerMutationStateInto(.g, , &.mutationScratch)
	if  != nil {
		return false, 
	}
	 := false
	defer func() {
		if  := recover();  != nil {
			.restore()
			panic()
		}
		if ! {
			.restore()
		}
	}()

	,  = .optimizeGuarded(, , )
	if  != nil {
		return false, 
	}
	if  := .Finish();  != nil {
		return false, 
	}
	 = true
	return , nil
}

func ( *sizedOptimizer) ( context.Context,  float64,  *limits.OptimizationWorkGuard) (bool, error) {
	 := false

	if len(.g.Nodes) > limits.MaxEngineNodes {
		return false, fmt.Errorf("TALA LocalOptimize node count exceeds limit %d", limits.MaxEngineNodes)
	}
	 := make([]int, len(.g.Nodes))
	for  := 0;  < len(.g.Nodes); ++ {
		if  := .Step();  != nil {
			return false, 
		}
		[] = 
	}
	if  := limits.Shuffle(, .randGenerator, );  != nil {
		return false, 
	}

	for ,  := range  {
		if  := .Step();  != nil {
			return false, 
		}
		 := .g.Nodes[]
		if  == nil || .TopLeft == nil {
			return false, fmt.Errorf("TALA LocalOptimize found an unpositioned graph node")
		}
		if .FixedTopLeft != nil {
			continue
		}
		if .Width > 100*.cellSize || .Height > 100*.cellSize {
			// leave giant node where it is, we won't find an unoccupied point within 100 cellSize
			continue
		}
		if len(.Edges) == 0 {
			 := false
			for  := range .Nears {
				if  := .Step();  != nil {
					return false, 
				}
				,  := optimizerIsDescendantOf(, .Container, )
				if  != nil {
					return false, 
				}
				if  {
					 = true
					break
				}
			}
			if ! {
				continue
			}
		}
		if ,  := .g.NodeToTree[];  {
			continue
		}

		,  := .protrudingChildrenGuarded(, )
		if  != nil {
			return false, 
		}
		 := len() == 0

		,  := .medianPointGuarded(, , , )
		if  != nil {
			return false, 
		}
		// All candidate placements for this node see the same boxes for every
		// other graph node. Build one ordered broad-phase index and reuse it until
		// the optimizer commits this node's final position.
		if  := .rebuildSpatialIndex();  != nil {
			return false, 
		}

		var  map[geo.Point]struct{}
		// Making and using a cache takes many allocs. Only worth it when this node has to search through many siblings for overlap
		if len() > 10 {
			if .checkedPositions == nil {
				.checkedPositions = make(map[geo.Point]struct{}, 64)
			} else {
				clear(.checkedPositions)
			}
			 = .checkedPositions
		}
		,  := .findClosestUnoccupiedDistanceGuarded(, , , , )
		if  != nil {
			return false, 
		}

		,  := .fillPlacementPointsGuarded(, , , , &.placementScratch, )
		if  != nil {
			return false, 
		}
		if  := limits.Shuffle(, .randGenerator, );  != nil {
			return false, 
		}

		// we want mustImprove to be true for the last 10 optimize calls where temp is 0
		,  := .moveNodeToBestGuarded(, , ,  == 0, )
		if  != nil {
			return false, 
		}

		if ! {
			,  := .bestSwapCandidateGuarded(, , )
			if  != nil {
				return false, 
			}
			if  != nil {
				 = true
				if  := optimizerSwapPositions(, , );  != nil {
					return false, 
				}
				if  := .syncHerdFencesGuarded();  != nil {
					return false, 
				}
			} else {
				if  := chargeOptimizerTranspose(.g, , .edgeAbductions, );  != nil {
					return false, 
				}
				,  := transpose(, .g, , .edgeAbductions)
				if  != nil {
					return false, 
				}
				if  := .Step();  != nil {
					return false, 
				}
				if  {
					 = true
				} else {
					// The spokes don't need to move because in the next iteration they'll move
					if ,  := .g.Hubs[];  &&  != 0 {
						 := withHubSpokesSuppressed(, , , func() error {
							,  := .medianPointGuarded(, , , )
							if  != nil {
								return 
							}

							,  := .findClosestUnoccupiedDistanceGuarded(, , , , )
							if  != nil {
								return 
							}
							,  := .fillPlacementPointsGuarded(, , , , &.placementScratch, )
							if  != nil {
								return 
							}
							if  := limits.Shuffle(, .randGenerator, );  != nil {
								return 
							}
							_,  = .moveNodeToBestGuarded(, , ,  == 0, )
							return 
						})
						if  != nil {
							return false, 
						}
					}
				}
			}
		} else {
			if  := .syncHerdFencesGuarded();  != nil {
				return false, 
			}
			 = true
		}
	}
	return , .Finish()
}

func ( *sizedOptimizer) ( *layoutgraph.Node,  float64,  layoutgraph.Nodes,  *limits.OptimizationWorkGuard) (*geo.Point, error) {
	 := .Width / .cellSize
	 := .Height / .cellSize
	, ,  := optimizerMedianToNeighbors(, true, .edgeAbductions, )
	if  != nil {
		return nil, 
	}

	,  := optimizerFixedOrigin(.g, .OwningContainer(), )
	if  != nil {
		return nil, 
	}
	if  != nil {
		// we can't have node positions past the fixedOrigin so set a floor
		if  < .X/.cellSize {
			 = .X / .cellSize
			// normally the random movement is within [-temp*width, temp*width],
			// but anything left of the fixed origin is invalid so make it [0, 2*temp*width]
			 +=  * 
		}
		if  < .Y/.cellSize {
			 = .Y / .cellSize
			 +=  * 
		}
	}

	 += ((-1.0 *  * ) + .randGenerator.Float64()*(2.0**))
	 += ((-1.0 *  * ) + .randGenerator.Float64()*(2.0**))

	if len() > 0 {
		, ,  := optimizerMedian(, true, )
		if  != nil {
			return nil, 
		}
		 -= ( - .TopLeft.X/.cellSize)
		 -= ( - .TopLeft.Y/.cellSize)
	}

	if  != nil {
		 = math.Max(, .X/.cellSize)
		 = math.Max(, .Y/.cellSize)
	}

	return geo.NewPoint(
		math.Round(*.cellSize),
		math.Round(*.cellSize),
	), nil
}

func ( *sizedOptimizer) ( *layoutgraph.Node,  *limits.OptimizationWorkGuard) ([]*layoutgraph.Node, error) {
	// If this container were being placed, its median would be the bottom-most node, but that doesn't reflect where we want the node to be
	// We want the node to be placed such that the median of its children with protruding edges is at the calculated median
	// ┌────────────────┐
	// │                │
	// │                │
	// │                │
	// │                │
	// │                │
	// │          ┌──┐  │
	// │          └─┼┘  │
	// │            │   │
	// └────────────┼───┘
	//              │
	//            ┌─▼┐
	//            └──┘
	 := []*layoutgraph.Node{}
	for ,  := range .edgeAbductions {
		if  := .Step();  != nil {
			return nil, 
		}
		if  == nil {
			return nil, fmt.Errorf("TALA LocalOptimize found a nil edge abduction")
		}
		if .CurrentFrom ==  && .OriginallyFrom != nil {
			 = append(, .OriginallyFrom)
		}
		if .CurrentTo ==  && .OriginallyTo != nil {
			 = append(, .OriginallyTo)
		}
	}
	return , nil
}

func ( sizedOptimizer) ( *layoutgraph.Node,  *geo.Point,  bool,  map[geo.Point]struct{},  *limits.OptimizationWorkGuard) (float64, error) {
	if  == nil || .Graph == nil || .TopLeft == nil ||  == nil {
		return 0, fmt.Errorf("TALA %s placement search requires a positioned node, graph, and point", .Location())
	}
	if .cellSize <= 0 || math.IsNaN(.cellSize) || math.IsInf(.cellSize, 0) {
		return 0, fmt.Errorf("TALA %s placement search requires a finite positive cell size", .Location())
	}
	if len() > maxOptimizerPlacementCandidates {
		return 0, fmt.Errorf("%w: TALA %s checked placement count exceeds limit %d", limits.ErrOptimizationResourceLimit, .Location(), maxOptimizerPlacementCandidates)
	}
	// example with distance=3, we iterate points from least to most distance
	//          3
	//       3  2  3
	//    3  2  1  2  3
	// 3──2──1──0──1──2──3
	//    3  2  1  2  3
	//       3  2  3
	//          3
	// for points at the same distance we iterate right to left (& negative then positive):
	// curr=0       =1            =2               =3        6
	//                                   4                8     4
	//                  2             6     2         10           2
	//     ──0──     3─────0       7───────────0   12─────────────────0
	//                  1             5     1          9           1
	//                                   3                7     3
	//                                                       5
	 := .cellSize

	// For each candidate “ring” (curr is in grid units, then scaled by cellSize)
	for  := 0.0;  <= 100.0; ++ {
		if  := .Step();  != nil {
			return 0, 
		}
		 :=  * 

		// Start with x at the ring's rightmost point and y = 0.
		// The candidate point offsets are defined relative to p.
		 := 
		 := 0.0

		// Continue until x goes below -currCell.
		for  >= - {
			if  := .Step();  != nil {
				return 0, 
			}
			// Check the candidate at (x, -y) if y is nonzero.
			if  != 0 {
				 := geo.Point{
					X: roundToNearestCellSize(.X+, ),
					Y: roundToNearestCellSize(.Y-, ),
				}
				// Enforce fixed-origin constraint if needed.
				if .fixedOrigin == nil || (.X >= .fixedOrigin.X && .Y >= .fixedOrigin.Y) {
					,  := .findUnoccupiedGuarded(, -, .Width, .Height, , , , , )
					if  != nil {
						return 0, 
					}
					if  {
						return , nil
					}
				}
			}
			// Check candidate at (x, y)
			 := geo.Point{
				X: roundToNearestCellSize(.X+, ),
				Y: roundToNearestCellSize(.Y+, ),
			}
			if .fixedOrigin == nil || (.X >= .fixedOrigin.X && .Y >= .fixedOrigin.Y) {
				,  := .findUnoccupiedGuarded(, , .Width, .Height, , , , , )
				if  != nil {
					return 0, 
				}
				if  {
					return , nil
				}
			}

			// Update y: if x > 0, increment y by cellSize; otherwise, decrement y.
			if  > 0 {
				 += 
			} else {
				 -= 
			}
			 -= 
		}
	}
	return 0, fmt.Errorf("could not find closest unoccupied distance for p=%v, node=%s", , .DebugID())
}

// findUnoccupied is a tailored closest-unoccupied-distance search over placements around a node.
// It is called often enough to warrant a specialized implementation.
func ( *sizedOptimizer) (
	, , ,  float64,  bool,  *layoutgraph.Node,  *geo.Point,  map[geo.Point]struct{},  *limits.OptimizationWorkGuard,
) (bool, error) {
	if  := .Step();  != nil {
		return false, 
	}
	 := false
	 := geo.Point{X: , Y: }
	if  != nil {
		if ,  := [];  {
			 = true
		} else {
			if len() >= maxOptimizerPlacementCandidates {
				return false, fmt.Errorf("%w: TALA %s checked placement count exceeds limit %d", limits.ErrOptimizationResourceLimit, .Location(), maxOptimizerPlacementCandidates)
			}
			[] = struct{}{}
		}
	}

	if ! {
		,  := .isPointOccupiedGuarded(, , , , )
		if  != nil {
			return false, 
		}
		if ! {
			return true, nil
		}
	}

	if ! {
		return false, nil
	}

	for  :=  - ;  <= ;  += .cellSize {
		for  :=  - ;  <= ;  += .cellSize {
			if  := .Step();  != nil {
				return false, 
			}
			// Already attempted above
			if  ==  &&  ==  {
				continue
			}
			if  != nil {
				.X = 
				.Y = 
				if ,  := [];  {
					continue
				}
				if len() >= maxOptimizerPlacementCandidates {
					return false, fmt.Errorf("%w: TALA %s checked placement count exceeds limit %d", limits.ErrOptimizationResourceLimit, .Location(), maxOptimizerPlacementCandidates)
				}
				[] = struct{}{}
			}
			,  := .isPointOccupiedGuarded(, , , , )
			if  != nil {
				return false, 
			}
			if ! {
				return true, nil
			}
		}
	}
	return false, nil
}

func ( *sizedOptimizer) (,  float64,  *geo.Point,  *layoutgraph.Node,  *limits.OptimizationWorkGuard) (bool, error) {
	 := geo.NewPoint(.X+, .Y+)
	.X = roundToNearestCellSize(.X, .cellSize)
	.Y = roundToNearestCellSize(.Y, .cellSize)
	if .fixedOrigin != nil && (.X < .fixedOrigin.X || .Y < .fixedOrigin.Y) {
		return true, nil
	}
	, ,  := .indexedIsOccupied(, )
	if  != nil {
		return false, 
	}
	if ! {
		,  := .indexedDoesOverlap(, , []*layoutgraph.Node{}, )
		if  != nil {
			return false, 
		}
		if ! {
			return false, nil
		}
	}
	return true, nil
}

// placementPointsScratch holds reusable candidate-generation memory.
type placementPointsScratch struct {
	seen   map[uint64]struct{} // Deduplicate coordinates
	points []geo.Point         // Collection of placement points
}

// fillPlacementPointsGuarded fills caller-owned scratch so the optimizer can
// reuse candidate storage across its generate-shuffle-score loop.
func ( *sizedOptimizer) (
	 *layoutgraph.Node,
	 *geo.Point,
	 float64,
	 bool,
	 *placementPointsScratch,
	 *limits.OptimizationWorkGuard,
) ([]geo.Point, error) {
	if  == nil || .TopLeft == nil ||  == nil {
		return nil, fmt.Errorf("TALA %s placement generation requires a positioned node and median", .Location())
	}
	if  < 0 ||  > 100 || math.IsNaN() || math.IsInf(, 0) {
		return nil, fmt.Errorf("TALA %s placement distance must be finite and within [0, 100]", .Location())
	}
	if .cellSize <= 0 || math.IsNaN(.cellSize) || math.IsInf(.cellSize, 0) {
		return nil, fmt.Errorf("TALA %s placement generation requires a finite positive cell size", .Location())
	}
	if .seen == nil {
		.seen = make(map[uint64]struct{}, 128)
	}
	if .points == nil {
		.points = make([]geo.Point, 0, 128)
	}

	// Clear data structures for reuse
	for  := range .seen {
		if  := .Step();  != nil {
			return nil, 
		}
		delete(.seen, )
	}
	.points = .points[:0]

	// Calculate distance and estimate capacity
	 :=  + 1

	// Using bit shifting for faster encoding of coordinates
	// No need to create a closure for this simple operation
	// Use direct memoization in the add function

	// The add function checks for duplicates and adds valid points
	var  error
	 := func(,  float64) bool {
		if  != nil {
			return true
		}
		if  := .Step();  != nil {
			 = 
			return true
		}
		 := roundToNearestCellSize(.X+, .cellSize)
		 := roundToNearestCellSize(.Y+, .cellSize)

		// Early rejection based on fixed origin
		if  := .fixedOrigin;  != nil &&
			( < .X ||  < .Y) {
			return false
		}

		// Encode coordinates to a single 64-bit value for map lookup
		// Inlined the encode function to reduce overhead
		 := int64( / .cellSize)
		 := int64( / .cellSize)
		 := uint64(uint32())<<32 | uint64(uint32())

		// Check if duplicate
		if ,  := .seen[];  {
			return false
		}
		if len(.points) >= maxOptimizerPlacementCandidates {
			 = fmt.Errorf("%w: TALA LocalOptimize placement candidates exceed limit %d", limits.ErrOptimizationResourceLimit, maxOptimizerPlacementCandidates)
			return true
		}

		// Add to seen and points collections
		.seen[] = struct{}{}
		.points = append(.points, geo.Point{X: , Y: })
		return false
	}

	// Generate placement points in diamond pattern
	// Use integer for loop counters when possible to reduce float ops
	for  := ;  >= -; -- {
		if  := .Step();  != nil {
			return nil, 
		}
		 :=  - math.Abs()
		for  := 0.0;  <= ; ++ {
			if  := .Step();  != nil {
				return nil, 
			}
			// Generate points in both positive and negative Y directions
			if  != 0 {
				iterPlacementsAroundPoint(, , -, , )
			}
			iterPlacementsAroundPoint(, , , , )
			if  != nil {
				return nil, 
			}
		}
	}

	// Process long-distance neighbor requirements.
	if  := .LongDistanceNeighborRequirements;  != nil {
		if int64(len()) > layoutgraph.MaxTopologyReferences {
			return nil, fmt.Errorf("TALA %s long-distance neighbor references exceed limit %d", .Location(), layoutgraph.MaxTopologyReferences)
		}
		 := float64(int(.cellSize))

		 := make([]*layoutgraph.Node, 0, len())
		for  := range  {
			if  := .Step();  != nil {
				return nil, 
			}
			 = append(, )
		}
		if  := .AddSort(len());  != nil {
			return nil, 
		}
		slices.SortFunc(, func(,  *layoutgraph.Node) int {
			return cmp.Compare(.IDValue(), .IDValue())
		})

		// Avoid creating closures in loops by using direct function calls
		for ,  := range  {
			if  := .Step();  != nil {
				return nil, 
			}
			 := []
			if  == nil || .TopLeft == nil {
				return nil, fmt.Errorf("TALA %s found an unpositioned long-distance neighbor", .Location())
			}
			 := .MaxWidth
			 := .MaxHeight

			// Pre-calculate common values
			 := .TopLeft.X - .X
			 := .TopLeft.Y - .Y

			// Add specific placement points for width
			if  > int() {
				(math.Floor((-.Width-float64())/)*, )
				(math.Ceil((+.Width+float64())/)*, )
			}

			// Add specific placement points for height
			if  > int() {
				(, math.Floor((-.Height-float64())/)*)
				(, math.Ceil((+.Height+float64())/)*)
			}
			if  != nil {
				return nil, 
			}
		}
	}

	// Add current position for herd assignments
	if .HerdAssignment != nil {
		if len(.points) >= maxOptimizerPlacementCandidates {
			return nil, fmt.Errorf("%w: TALA LocalOptimize placement candidates exceed limit %d", limits.ErrOptimizationResourceLimit, maxOptimizerPlacementCandidates)
		}
		.points = append(.points, *.TopLeft)
	}

	// Preserve the original work charge even when the internal caller consumes
	// the scratch slice directly.
	if  := .Add(uint64(len(.points)));  != nil {
		return nil, 
	}
	return .points, nil
}

func ( *sizedOptimizer) ( context.Context,  *layoutgraph.Node,  []geo.Point,  bool,  *limits.OptimizationWorkGuard) (bool, error) {
	 := placementcost.NewNodeEdgeLengthScorer(, placementcost.EdgeLengthOptions{
		EdgeAbductions: .edgeAbductions, IncludeNodeSizes: true,
		EnforceMinimumGap: false, PenalizeDirection: true,
	})
	defer .Close()
	 := .cellSize * float64(len(.Edges))
	 := math.Inf(1)
	if  {
		if  := chargeOptimizerScoring(, .edgeAbductions, true, );  != nil {
			return false, 
		}
		var  error
		,  = .Score()
		if  != nil {
			return false, 
		}
		,  := placementcost.ColumnCrossingCost(, , .edgeAbductions)
		if  != nil {
			return false, 
		}
		,  := placementcost.NodeSymmetry(, , .edgeAbductions)
		if  != nil {
			return false, 
		}
		 += 
		 -=  * 
	}
	 := .TopLeft.Copy()
	 := .TopLeft.X
	 := .TopLeft.Y
	,  := captureOptimizerCandidateMovement(, )
	if  != nil {
		return false, 
	}
	 := .positions
	 := false
	defer func() {
		if ! {
			restoreNodePositions()
		}
	}()

	for  := range  {
		if  := .Step();  != nil {
			restoreNodePositions()
			return false, 
		}
		 := &[]
		 := .X
		 := .Y
		if .fixedOrigin != nil && ( < .fixedOrigin.X ||  < .fixedOrigin.Y) {
			continue
		}
		// If the candidate position is the original one, we should be able to move back to it (if we moved somewhere else in this routine)
		 :=  ==  &&  == 
		if ! {
			var  error
			,  = .indexedCanMove(, , )
			if  != nil {
				restoreNodePositions()
				return false, 
			}
		}
		if  {
			if  := .moveAbs(, , );  != nil {
				restoreNodePositions()
				return false, 
			}
			if  := chargeOptimizerScoring(, .edgeAbductions, true, );  != nil {
				restoreNodePositions()
				return false, 
			}

			,  := .Score()
			if  != nil {
				restoreNodePositions()
				return false, 
			}
			if !math.IsInf(, 1) && geo.PrecisionCompare(-, , geo.PRECISION) == 1 {
				// no need to continue, this is clearly worse
				continue
			}
			,  := placementcost.ColumnCrossingCost(, , .edgeAbductions)
			if  != nil {
				restoreNodePositions()
				return false, 
			}
			,  := placementcost.NodeSymmetry(, , .edgeAbductions)
			if  != nil {
				restoreNodePositions()
				return false, 
			}
			 += 
			 -=  * 

			for ,  := range .obstacles {
				if  := .Step();  != nil {
					restoreNodePositions()
					return false, 
				}
				if .TopLeft.X == -layoutgraph.ContainerPadding && .TopLeft.Y == -layoutgraph.ContainerPadding {
					continue
				}
				if .Box.Overlaps() {
					 += 3 * .g.TurnCost()
				}
			}

			switch geo.PrecisionCompare(, , geo.PRECISION) {
			case -1:
				 = 
				 = 
			case 0:
				if .X ==  && .Y ==  {
					 = 
					 = 
				}
			}
		}
	}

	if  := .Err();  != nil {
		restoreNodePositions()
		return false, fmt.Errorf("EdgeLength: %w", )
	}
	if math.IsInf(, 1) {
		restoreNodePositions()
		return false, fmt.Errorf("sizedOptimizer: could not find any placement")
	}

	if  := .moveAbs(.X, .Y, );  != nil {
		restoreNodePositions()
		return false, 
	}

	 = true
	return (.TopLeft.X != ) || (.TopLeft.Y != ), nil
}

func ( *sizedOptimizer) ( context.Context,  *layoutgraph.Node,  *limits.OptimizationWorkGuard) (*layoutgraph.Node, error) {
	 := math.Inf(1)

	// TODO (Mon Sep 20 10:57:17 2021) These maybe should be true on enforcing gap size, since when we swap, we don't want resulting swap to be too squished
	if  := chargeOptimizerScoring(, .edgeAbductions, true, );  != nil {
		return nil, 
	}
	,  := placementcost.NodeEdgeLength(, , placementcost.EdgeLengthOptions{EdgeAbductions: .edgeAbductions, IncludeNodeSizes: true, EnforceMinimumGap: false, PenalizeDirection: true})
	if  != nil {
		return nil, 
	}
	,  := placementcost.ColumnCrossingCost(, , .edgeAbductions)
	if  != nil {
		return nil, 
	}
	,  := placementcost.NodeSymmetry(, , .edgeAbductions)
	if  != nil {
		return nil, 
	}
	 += 
	 -=  * .symmetryCost * float64(len(.Edges))
	var  *layoutgraph.Node = nil

	 := make([]int, len(.g.Nodes))
	for  := 0;  < len(.g.Nodes); ++ {
		if  := .Step();  != nil {
			return nil, 
		}
		[] = 
	}
	if  := limits.Shuffle(, .randGenerator, );  != nil {
		return nil, 
	}

	for ,  := range  {
		if  := .Step();  != nil {
			return nil, 
		}
		 := .g.Nodes[]
		if  ==  {
			continue
		}
		if .FixedTopLeft != nil {
			continue
		}
		if !.IsAdjacentTo(, true) {
			continue
		}
		if ,  := .g.NodeToTree[];  {
			continue
		}
		,  := .indexedDoesOverlap(, .TopLeft, []*layoutgraph.Node{}, )
		if  != nil {
			return nil, 
		}
		,  := .indexedDoesOverlap(, .TopLeft, []*layoutgraph.Node{}, )
		if  != nil {
			return nil, 
		}
		if  ||  {
			continue
		}

		if  := chargeOptimizerScoring(, .edgeAbductions, true, );  != nil {
			return nil, 
		}
		,  := placementcost.NodeEdgeLength(, , placementcost.EdgeLengthOptions{EdgeAbductions: .edgeAbductions, IncludeNodeSizes: true, EnforceMinimumGap: false, PenalizeDirection: true})
		if  != nil {
			return nil, 
		}
		,  := placementcost.ColumnCrossingCost(, , .edgeAbductions)
		if  != nil {
			return nil, 
		}
		,  := placementcost.NodeSymmetry(, , .edgeAbductions)
		if  != nil {
			return nil, 
		}
		 += 
		 -=  * .symmetryCost * float64(len(.Edges))

		var ,  float64
		 := false
		 = withOptimizerPositionsSwapped(, , , func() error {

			// Have to check for overlap again, since swapping two of different sizes
			// may cause one to overlap with the other -- so, no exceptions in this check
			,  := optimizerDoesOverlap(, .TopLeft, nil, )
			if  != nil {
				return 
			}
			,  := optimizerDoesOverlap(, .TopLeft, nil, )
			if  != nil {
				return 
			}
			if  ||  {
				return nil
			}
			 = true

			var  error
			if  = chargeOptimizerScoring(, .edgeAbductions, true, );  != nil {
				return 
			}
			,  = placementcost.NodeEdgeLength(, , placementcost.EdgeLengthOptions{EdgeAbductions: .edgeAbductions, IncludeNodeSizes: true, EnforceMinimumGap: false, PenalizeDirection: true})
			if  != nil {
				return 
			}
			,  = placementcost.ColumnCrossingCost(, , .edgeAbductions)
			if  != nil {
				return 
			}
			,  = placementcost.NodeSymmetry(, , .edgeAbductions)
			if  != nil {
				return 
			}
			 += 
			 -=  * .symmetryCost * float64(len(.Edges))

			// No need to compute it if we already know it won't be a good swap.
			if geo.PrecisionCompare(, , geo.PRECISION) < 0 {
				if  = chargeOptimizerScoring(, .edgeAbductions, true, );  != nil {
					return 
				}
				,  = placementcost.NodeEdgeLength(, , placementcost.EdgeLengthOptions{EdgeAbductions: .edgeAbductions, IncludeNodeSizes: true, EnforceMinimumGap: false, PenalizeDirection: true})
				if  != nil {
					return 
				}
				,  = placementcost.ColumnCrossingCost(, , .edgeAbductions)
				if  != nil {
					return 
				}
				,  = placementcost.NodeSymmetry(, , .edgeAbductions)
				if  != nil {
					return 
				}
				 += 
				 -=  * .symmetryCost * float64(len(.Edges))
			}
			return nil
		})
		if  != nil {
			return nil, 
		}
		if ! {
			continue
		}

		if geo.PrecisionCompare(, , geo.PRECISION) < 0 && geo.PrecisionCompare(+, +, geo.PRECISION) < 0 && geo.PrecisionCompare(+, , geo.PRECISION) < 0 {
			 =  + 
			 = 
		}
	}

	if  := .Err();  != nil {
		return nil, fmt.Errorf("EdgeLength: %w", )
	}
	return , nil
}

func ( *sizedOptimizer) ( *limits.OptimizationWorkGuard) error {
	// Preserve the legacy bounding-box semantics (outside labels, modifier
	// elements, loop offsets, routed edges, and fixed origins). Precharging the
	// bounded quadratic scan keeps it under the shared operation budget.
	 := uint64(len(.g.Nodes))
	if  := .AddProduct(, +1);  != nil {
		return 
	}
	if  := .Add(uint64(len(.g.Edges)));  != nil {
		return 
	}
	proximity.SyncHerdFences(.g)
	return .Finish()
}