code: def to_affine_nd(
      r: np.ndarray | int, affine: NdarrayTensor, dtype=np.float64
  ) -> NdarrayTensor:
      """
      Using elements from affine, to create a new affine matrix by
      assigning the rotation/zoom/scaling matrix and the translation vector.
  
      When ``r`` is an integer, output is an (r+1)x(r+1) matrix,
      where the top left kxk elements are copied from ``affine``,
      the last column of the output affine is copied from ``affine``'s last column.
      `k` is determined by `min(r, len(affine) - 1)`.
  
      When ``r`` is an affine matrix, the output has the same shape as ``r``,
      and the top left kxk elements are copied from ``affine``,
      the last column of the output affine is copied from ``affine``'s last column.
      `k` is determined by `min(len(r) - 1, len(affine) - 1)`.
  
      Args:
          r (int or matrix): number of spatial dimensions or an output affine to be filled.
          affine (matrix): 2D affine matrix
          dtype: data type of the output array.
  
      Raises:
          ValueError: When ``affine`` dimensions is not 2.
          ValueError: When ``r`` is nonpositive.
  
      Returns:
          an (r+1) x (r+1) matrix (tensor or ndarray depends on the input ``affine`` data type)
  
      """
      dtype = get_equivalent_dtype(dtype, np.ndarray)
      affine_np = convert_data_type(
          affine,
          output_type=np.ndarray,
          dtype=dtype,
          wrap_sequence=True,
      )[0]
      affine_np = affine_np.copy()
      if affine_np.ndim != 2:
          raise ValueError(
              f"affine must have 2 dimensions, got {affine_np.ndim}."
          )
      new_affine = np.array(r, dtype=dtype, copy=True)
      if new_affine.ndim == 0:
          sr: int = int(new_affine.astype(np.uint))
          if not np.isfinite(sr) or sr < 0:
              raise ValueError(f"r must be positive, got {sr}.")
          new_affine = np.eye(sr + 1, dtype=dtype)
      d = max(min(len(new_affine) - 1, len(affine_np) - 1), 1)
      new_affine[:d, :d] = affine_np[:d, :d]
      if d > 1:
          new_affine[:d, -1] = affine_np[:d, -1]
      output, *_ = convert_to_dst_type(new_affine, affine, dtype=dtype)
      return output
  
imports: from __future__ import annotations
  import hashlib
  import json
  import logging
  import math
  import os
  import pickle
  import sys
  from collections import abc, defaultdict
  from collections.abc import Generator, Iterable, Mapping, Sequence, Sized
  from copy import deepcopy
  from functools import reduce
  from itertools import product, starmap, zip_longest
  from pathlib import PurePath
  from typing import Any
  import numpy
  import torch
  from torch.utils.data._utils.collate import default_collate
  from monai import config
  from monai.config.type_definitions import NdarrayOrTensor, NdarrayTensor, PathLike
  from monai.data.meta_obj import MetaObj
  from monai.utils import MAX_SEED, BlendMode, Method, NumpyPadMode, TraceKeys, convert_data_type, convert_to_dst_type, ensure_tuple, ensure_tuple_rep, ensure_tuple_size, fall_back_tuple, first, get_equivalent_dtype, issequenceiterable, look_up_option, optional_import, pytorch_after
label_desc: Use image node_id 23 for calling a global function with example usage: to_affine_nd(r, affine, dtype) and returns: output