class_docstr: This module is modified from torchvision to support both 2D and 3D images.
  
  Module that generates anchors for a set of feature maps and
  image sizes.
  
  The module support computing anchors at multiple sizes and aspect ratios
  per feature map.
  
  sizes and aspect_ratios should have the same number of elements, and it should
  correspond to the number of feature maps.
  
  sizes[i] and aspect_ratios[i] can have an arbitrary number of elements.
  For 2D images, anchor width and height w:h = 1:aspect_ratios[i,j]
  For 3D images, anchor width, height, and depth w:h:d = 1:aspect_ratios[i,j,0]:aspect_ratios[i,j,1]
  
  AnchorGenerator will output a set of sizes[i] * aspect_ratios[i] anchors
  per spatial location for feature map i.
  
  Args:
      sizes: base size of each anchor.
          len(sizes) is the number of feature maps, i.e., the number of output levels for
          the feature pyramid network (FPN).
          Each element of ``sizes`` is a Sequence which represents several anchor sizes for each feature map.
      aspect_ratios: the aspect ratios of anchors. ``len(aspect_ratios) = len(sizes)``.
          For 2D images, each element of ``aspect_ratios[i]`` is a Sequence of float.
          For 3D images, each element of ``aspect_ratios[i]`` is a Sequence of 2 value Sequence.
      indexing: choose from {``'ij'``, ``'xy'``}, optional,
          Matrix (``'ij'``, default and recommended) or Cartesian (``'xy'``) indexing of output.
  
          - Matrix (``'ij'``, default and recommended) indexing keeps the original axis not changed.
          - To use other monai detection components, please set ``indexing = 'ij'``.
          - Cartesian (``'xy'``) indexing swaps axis 0 and 1.
          - For 2D cases, monai ``AnchorGenerator(sizes, aspect_ratios, indexing='xy')`` and
            ``torchvision.models.detection.anchor_utils.AnchorGenerator(sizes, aspect_ratios)`` are equivalent.
  
  
  Reference:.
      https://github.com/pytorch/vision/blob/release/0.12/torchvision/models/detection/anchor_utils.py
  
  Example:
      .. code-block:: python
  
          # 2D example inputs for a 2-level feature maps
          sizes = ((10,12,14,16), (20,24,28,32))
          base_aspect_ratios = (1., 0.5,  2.)
          aspect_ratios = (base_aspect_ratios, base_aspect_ratios)
          anchor_generator = AnchorGenerator(sizes, aspect_ratios)
  
          # 3D example inputs for a 2-level feature maps
          sizes = ((10,12,14,16), (20,24,28,32))
          base_aspect_ratios = ((1., 1.), (1., 0.5), (0.5, 1.), (2., 2.))
          aspect_ratios = (base_aspect_ratios, base_aspect_ratios)
          anchor_generator = AnchorGenerator(sizes, aspect_ratios)
class_docstr_tok: ["This","module","is","modified","from","torchvision","to","support","both","2D","and","3D","images",".","Module","that","generates","anchors","for","a","set","of","feature","maps","and","image","sizes",".","The","module","support","computing","anchors","at","multiple","sizes","and","aspect","ratios","per","feature","map",".","sizes","and","aspect_ratios","should","have","the","same","number","of","elements",",","and","it","should","correspond","to","the","number","of","feature","maps",".","sizes","[","i","]","and","aspect_ratios","[","i","]","can","have","an","arbitrary","number","of","elements",".","For","2D","images",",","anchor","width","and","height","w",":","h","=","1",":","aspect_ratios","[","i",",","j","]","For","3D","images",",","anchor","width",",","height",",","and","depth","w",":","h",":","d","=","1",":","aspect_ratios","[","i",",","j,0","]",":","aspect_ratios","[","i",",","j,1","]","AnchorGenerator","will","output","a","set","of","sizes","[","i","]","*","aspect_ratios","[","i","]","anchors","per","spatial","location","for","feature","map","i.","Args",":","sizes",":","base","size","of","each","anchor",".","len","(","sizes",")","is","the","number","of","feature","maps",",","i.e.",",","the","number","of","output","levels","for","the","feature","pyramid","network","(","FPN",")",".","Each","element","of","``","sizes","``","is","a","Sequence","which","represents","several","anchor","sizes","for","each","feature","map",".","aspect_ratios",":","the","aspect","ratios","of","anchors",".","``","len","(","aspect_ratios",")","=","len","(","sizes",")","``",".","For","2D","images",",","each","element","of","``","aspect_ratios","[","i","]","``","is","a","Sequence","of","float",".","For","3D","images",",","each","element","of","``","aspect_ratios","[","i","]","``","is","a","Sequence","of","2","value","Sequence",".","indexing",":","choose","from","{","``","'ij","'","``",",","``","'xy","'","``","}",",","optional",",","Matrix","(","``","'ij","'","``",",","default","and","recommended",")","or","Cartesian","(","``","'xy","'","``",")","indexing","of","output",".","-","Matrix","(","``","'ij","'","``",",","default","and","recommended",")","indexing","keeps","the","original","axis","not","changed",".","-","To","use","other","monai","detection","components",",","please","set","``","indexing","=","'ij","'","``",".","-","Cartesian","(","``","'xy","'","``",")","indexing","swaps","axis","0","and","1",".","-","For","2D","cases",",","monai","``","AnchorGenerator","(","sizes",",","aspect_ratios",",","indexing='xy","'",")","``","and","``","torchvision.models.detection.anchor_utils.AnchorGenerator","(","sizes",",","aspect_ratios",")","``","are","equivalent",".","Reference",":",".","https",":","\/\/github.com\/pytorch\/vision\/blob\/release\/0.12\/torchvision\/models\/detection\/anchor_utils.py","Example",":","..","code-block",":",":","python","#","2D","example","inputs","for","a","2-level","feature","maps","sizes","=","(","(","10,12,14,16",")",",","(","20,24,28,32",")",")","base_aspect_ratios","=","(","1.",",","0.5",",","2",".",")","aspect_ratios","=","(","base_aspect_ratios",",","base_aspect_ratios",")","anchor_generator","=","AnchorGenerator","(","sizes",",","aspect_ratios",")","#","3D","example","inputs","for","a","2-level","feature","maps","sizes","=","(","(","10,12,14,16",")",",","(","20,24,28,32",")",")","base_aspect_ratios","=","(","(","1.",",","1",".",")",",","(","1.",",","0.5",")",",","(","0.5",",","1",".",")",",","(","2.",",","2",".",")",")","aspect_ratios","=","(","base_aspect_ratios",",","base_aspect_ratios",")","anchor_generator","=","AnchorGenerator","(","sizes",",","aspect_ratios",")"]
docstr: Compute cell anchor shapes at multiple sizes and aspect ratios for the current feature map.
  
  Args:
      scales: a sequence which represents several anchor sizes for the current feature map.
      aspect_ratios: a sequence which represents several aspect_ratios for the current feature map.
          For 2D images, it is a Sequence of float aspect_ratios[j],
          anchor width and height w:h = 1:aspect_ratios[j].
          For 3D images, it is a Sequence of 2 value Sequence aspect_ratios[j,0] and aspect_ratios[j,1],
          anchor width, height, and depth w:h:d = 1:aspect_ratios[j,0]:aspect_ratios[j,1]
      dtype: target data type of the output Tensor.
      device: target device to put the output Tensor data.
  
      Returns:
          For each s in scales, returns [s, s*aspect_ratios[j]] for 2D images,
          and [s, s*aspect_ratios[j,0],s*aspect_ratios[j,1]] for 3D images.
docstr_tok: ["Compute","cell","anchor","shapes","at","multiple","sizes","and","aspect","ratios","for","the","current","feature","map",".","Args",":","scales",":","a","sequence","which","represents","several","anchor","sizes","for","the","current","feature","map",".","aspect_ratios",":","a","sequence","which","represents","several","aspect_ratios","for","the","current","feature","map",".","For","2D","images",",","it","is","a","Sequence","of","float","aspect_ratios","[","j","]",",","anchor","width","and","height","w",":","h","=","1",":","aspect_ratios","[","j","]",".","For","3D","images",",","it","is","a","Sequence","of","2","value","Sequence","aspect_ratios","[","j,0","]","and","aspect_ratios","[","j,1","]",",","anchor","width",",","height",",","and","depth","w",":","h",":","d","=","1",":","aspect_ratios","[","j,0","]",":","aspect_ratios","[","j,1","]","dtype",":","target","data","type","of","the","output","Tensor",".","device",":","target","device","to","put","the","output","Tensor","data",".","Returns",":","For","each","s","in","scales",",","returns","[","s",",","s","*","aspect_ratios","[","j","]","]","for","2D","images",",","and","[","s",",","s","*","aspect_ratios","[","j,0","]",",","s","*","aspect_ratios","[","j,1","]","]","for","3D","images","."]
code: def generate_anchors(
      self,
      scales: Sequence,
      aspect_ratios: Sequence,
      dtype: torch.dtype = torch.float32,
      device: torch.device | None = None,
  ) -> torch.Tensor:
      """
      Compute cell anchor shapes at multiple sizes and aspect ratios for the current feature map.
  
      Args:
          scales: a sequence which represents several anchor sizes for the current feature map.
          aspect_ratios: a sequence which represents several aspect_ratios for the current feature map.
              For 2D images, it is a Sequence of float aspect_ratios[j],
              anchor width and height w:h = 1:aspect_ratios[j].
              For 3D images, it is a Sequence of 2 value Sequence aspect_ratios[j,0] and aspect_ratios[j,1],
              anchor width, height, and depth w:h:d = 1:aspect_ratios[j,0]:aspect_ratios[j,1]
          dtype: target data type of the output Tensor.
          device: target device to put the output Tensor data.
  
          Returns:
              For each s in scales, returns [s, s*aspect_ratios[j]] for 2D images,
              and [s, s*aspect_ratios[j,0],s*aspect_ratios[j,1]] for 3D images.
      """
      scales_t = torch.as_tensor(
          scales, dtype=dtype, device=device
      )  # sized (N,)
      aspect_ratios_t = torch.as_tensor(
          aspect_ratios, dtype=dtype, device=device
      )  # sized (M,) or (M,2)
      if (self.spatial_dims >= 3) and (len(aspect_ratios_t.shape) != 2):
          raise ValueError(
              f"In {self.spatial_dims}-D image, aspect_ratios for each level should be \
                  {len(aspect_ratios_t.shape)-1}-D. But got aspect_ratios with shape {aspect_ratios_t.shape}."
          )
  
      if (self.spatial_dims >= 3) and (
          aspect_ratios_t.shape[1] != self.spatial_dims - 1
      ):
          raise ValueError(
              f"In {self.spatial_dims}-D image, aspect_ratios for each level should has \
                  shape (_,{self.spatial_dims-1}). But got aspect_ratios with shape {aspect_ratios_t.shape}."
          )
  
      # if 2d, w:h = 1:aspect_ratios
      if self.spatial_dims == 2:
          area_scale = torch.sqrt(aspect_ratios_t)
          w_ratios = 1 / area_scale
          h_ratios = area_scale
      # if 3d, w:h:d = 1:aspect_ratios[:,0]:aspect_ratios[:,1]
      elif self.spatial_dims == 3:
          area_scale = torch.pow(
              aspect_ratios_t[:, 0] * aspect_ratios_t[:, 1], 1 / 3.0
          )
          w_ratios = 1 / area_scale
          h_ratios = aspect_ratios_t[:, 0] / area_scale
          d_ratios = aspect_ratios_t[:, 1] / area_scale
  
      ws = (w_ratios[:, None] * scales_t[None, :]).view(-1)
      hs = (h_ratios[:, None] * scales_t[None, :]).view(-1)
      if self.spatial_dims == 2:
          base_anchors = torch.stack([-ws, -hs, ws, hs], dim=1) / 2.0
      elif self.spatial_dims == 3:
          ds = (d_ratios[:, None] * scales_t[None, :]).view(-1)
          base_anchors = (
              torch.stack([-ws, -hs, -ds, ws, hs, ds], dim=1) / 2.0
          )
  
      return base_anchors.round()
  
file_path: MONAI/monai/apps/detection/utils/anchor_utils.py
imports: from __future__ import annotations
  from typing import List, Sequence
  import torch
  from torch import Tensor, nn
  from monai.utils import ensure_tuple
  from monai.utils.misc import issequenceiterable
  from monai.utils.module import look_up_option
label_desc: Use image node_id 2 for calling the AnchorGenerator obj's underlying member method code with example usage: obj.generate_anchors(scales, aspect_ratios, dtype, device) and returns: base_anchors