class_docstr: Module extracting line segments from junctions and line heatmaps.
  
  Args:
      detect_thresh: The probability threshold for mean activation (0. ~ 1.)
      num_samples: Number of sampling locations along the line segments.
      inlier_thresh: The min inlier ratio to satisfy (0. ~ 1.) => 0. means no threshold.
      heatmap_low_thresh: The lowest threshold for the pixel to be considered as candidate in junction recovery.
      heatmap_high_thresh: The higher threshold for NMS in junction recovery.
      max_local_patch_radius: The max patch to be considered in local maximum search.
      lambda_radius: The lambda factor in linear local maximum search formulation
      use_candidate_suppression: Apply candidate suppression to break long segments into short sub-segments.
      nms_dist_tolerance: The distance tolerance for nms. Decide whether the junctions are on the line.
      use_heatmap_refinement: Use heatmap refinement method or not.
      heatmap_refine_cfg: The configs for heatmap refinement methods.
      use_junction_refinement: Use junction refinement method or not.
      junction_refine_cfg: The configs for junction refinement methods.
docstr: Main function performing line segment detection.
docstr_tok: ["Main","function","performing","line","segment","detection","."]
code: def detect(
      self, junctions: Tensor, heatmap: Tensor
  ) -> Tuple[Tensor, Tensor, Tensor]:
      """Main function performing line segment detection."""
      KORNIA_CHECK_SHAPE(heatmap, ["H", "W"])
      H, W = heatmap.shape
      device = junctions.device
  
      # Perform the heatmap refinement
      if self.use_heatmap_refinement and isinstance(
          self.heatmap_refine_cfg, dict
      ):
          if self.heatmap_refine_cfg["mode"] == "global":
              heatmap = self.refine_heatmap(
                  heatmap,
                  self.heatmap_refine_cfg["ratio"],
                  self.heatmap_refine_cfg["valid_thresh"],
              )
          elif self.heatmap_refine_cfg["mode"] == "local":
              heatmap = self.refine_heatmap_local(
                  heatmap,
                  self.heatmap_refine_cfg["num_blocks"],
                  self.heatmap_refine_cfg["overlap_ratio"],
                  self.heatmap_refine_cfg["ratio"],
                  self.heatmap_refine_cfg["valid_thresh"],
              )
  
      # Initialize empty line map
      num_junctions = len(junctions)
      line_map_pred = zeros(
          [num_junctions, num_junctions],
          device=device,
          dtype=torch.int32,
      )
  
      # Stop if there are not enough junctions
      if num_junctions < 2:
          return line_map_pred, junctions, heatmap
  
      # Generate the candidate map
      candidate_map = torch.triu(
          torch.ones(
              [num_junctions, num_junctions],
              device=device,
              dtype=torch.int32,
          ),
          diagonal=1,
      )
  
      # Optionally perform candidate filtering
      if self.use_candidate_suppression:
          candidate_map = self.candidate_suppression(
              junctions, candidate_map
          )
  
      # Fetch the candidates
      candidate_indices = where(candidate_map)
      candidate_index_map = concatenate(
          [
              candidate_indices[0][..., None],
              candidate_indices[1][..., None],
          ],
          -1,
      )
  
      # Get the corresponding start and end junctions
      candidate_junc_start = junctions[candidate_index_map[:, 0]]
      candidate_junc_end = junctions[candidate_index_map[:, 1]]
  
      # Get the sampling locations (N x 64)
      sampler = self.torch_sampler.to(device)[None]
      cand_samples_h = candidate_junc_start[
          :, 0:1
      ] * sampler + candidate_junc_end[:, 0:1] * (1 - sampler)
      cand_samples_w = candidate_junc_start[
          :, 1:2
      ] * sampler + candidate_junc_end[:, 1:2] * (1 - sampler)
  
      # Clip to image boundary
      cand_h = torch.clamp(cand_samples_h, min=0, max=H - 1)
      cand_w = torch.clamp(cand_samples_w, min=0, max=W - 1)
  
      # [Local maximum search]
      # Compute normalized segment lengths
      segments_length = torch.sqrt(
          torch.sum(
              (
                  candidate_junc_start.to(torch.float32)
                  - candidate_junc_end.to(torch.float32)
              )
              ** 2,
              dim=-1,
          )
      )
      normalized_seg_length = segments_length / (
          ((H**2) + (W**2)) ** 0.5
      )
  
      # Perform local max search
      num_cand = len(cand_h)
      group_size = 10000
      if num_cand > group_size:
          num_iter = math.ceil(num_cand / group_size)
          sampled_feat_lst = []
          for iter_idx in range(num_iter):
              if not iter_idx == num_iter - 1:
                  cand_h_ = cand_h[
                      iter_idx
                      * group_size : (iter_idx + 1)
                      * group_size,
                      :,
                  ]
                  cand_w_ = cand_w[
                      iter_idx
                      * group_size : (iter_idx + 1)
                      * group_size,
                      :,
                  ]
                  normalized_seg_length_ = normalized_seg_length[
                      iter_idx
                      * group_size : (iter_idx + 1)
                      * group_size
                  ]
              else:
                  cand_h_ = cand_h[iter_idx * group_size :, :]
                  cand_w_ = cand_w[iter_idx * group_size :, :]
                  normalized_seg_length_ = normalized_seg_length[
                      iter_idx * group_size :
                  ]
              sampled_feat_ = self.detect_local_max(
                  heatmap,
                  cand_h_,
                  cand_w_,
                  H,
                  W,
                  normalized_seg_length_,
                  device,
              )
              sampled_feat_lst.append(sampled_feat_)
          sampled_feat = concatenate(sampled_feat_lst, 0)
      else:
          sampled_feat = self.detect_local_max(
              heatmap,
              cand_h,
              cand_w,
              H,
              W,
              normalized_seg_length,
              device,
          )
  
      # [Simple threshold detection]
      # detection_results is a mask over all candidates
      detection_results = (
          torch.mean(sampled_feat, dim=-1) > self.detect_thresh
      )
  
      # [Inlier threshold detection]
      if self.inlier_thresh > 0:
          inlier_ratio = (
              torch.sum(sampled_feat > self.detect_thresh, dim=-1).to(
                  heatmap.dtype
              )
              / self.num_samples
          )
          detection_results_inlier = inlier_ratio >= self.inlier_thresh
          detection_results = (
              detection_results * detection_results_inlier
          )
  
      # Convert detection results back to line_map_pred
      detected_junc_indexes = candidate_index_map[detection_results]
      line_map_pred[
          detected_junc_indexes[:, 0], detected_junc_indexes[:, 1]
      ] = 1
      line_map_pred[
          detected_junc_indexes[:, 1], detected_junc_indexes[:, 0]
      ] = 1
  
      # [Junction refinement]
      if (
          self.use_junction_refinement
          and len(detected_junc_indexes) > 0
      ):
          junctions, line_map_pred = self.refine_junction_perturb(
              junctions, line_map_pred, heatmap, H, W, device
          )
  
      return line_map_pred, junctions, heatmap
  
imports: import math
  from typing import Any, Dict, Optional, Tuple
  import torch
  from kornia.core import Module, Tensor, concatenate, sin, stack, tensor, where, zeros
  from kornia.core.check import KORNIA_CHECK_SHAPE
  from kornia.geometry.bbox import nms
  from kornia.utils import map_location_to_cpu, torch_meshgrid
  from .backbones import SOLD2Net
label_desc: Use image node_id 2 for calling the LineSegmentDetectionModule obj's underlying member method code with example usage: obj.detect(junctions, heatmap) and returns: line_map_pred,  junctions,  heatmap, line_map_pred,  junctions,  heatmap