class_docstr: KITTI tracking statistics (CLEAR MOT, id-switches, fragments, ML/PT/MT, precision/recall)
  MOTA       - Multi-object tracking accuracy in [0,100]
  MOTP       - Multi-object tracking precision in [0,100] (3D) / [td,100] (2D)
  MOTAL      - Multi-object tracking accuracy in [0,100] with log10(id-switches)
  
  id-switches - number of id switches
  fragments   - number of fragmentations
  
  MT, PT, ML - number of mostly tracked, partially tracked and mostly lost trajectories
  
  recall             - recall = percentage of detected targets
  precision      - precision = percentage of correctly detected targets
  FAR                    - number of false alarms per frame
  falsepositives - number of false positives (FP)
  missed         - number of missed targets (FN)
class_docstr_tok: ["KITTI","tracking","statistics","(","CLEAR","MOT",",","id-switches",",","fragments",",","ML\/PT\/MT",",","precision\/recall",")","MOTA","-","Multi-object","tracking","accuracy","in","[","0,100","]","MOTP","-","Multi-object","tracking","precision","in","[","0,100","]","(","3D",")","\/","[","td,100","]","(","2D",")","MOTAL","-","Multi-object","tracking","accuracy","in","[","0,100","]","with","log10","(","id-switches",")","id-switches","-","number","of","id","switches","fragments","-","number","of","fragmentations","MT",",","PT",",","ML","-","number","of","mostly","tracked",",","partially","tracked","and","mostly","lost","trajectories","recall","-","recall","=","percentage","of","detected","targets","precision","-","precision","=","percentage","of","correctly","detected","targets","FAR","-","number","of","false","alarms","per","frame","falsepositives","-","number","of","false","positives","(","FP",")","missed","-","number","of","missed","targets","(","FN",")"]
docstr: Computes the metrics defined in
      - Stiefelhagen 2008: Evaluating Multiple Object Tracking Performance: The CLEAR MOT Metrics
        MOTA, MOTAL, MOTP
      - Nevatia 2008: Global Data Association for Multi-Object Tracking Using Network Flows
        MT/PT/ML
code: def compute3rdPartyMetrics(self):
      """
      Computes the metrics defined in
          - Stiefelhagen 2008: Evaluating Multiple Object Tracking Performance: The CLEAR MOT Metrics
            MOTA, MOTAL, MOTP
          - Nevatia 2008: Global Data Association for Multi-Object Tracking Using Network Flows
            MT/PT/ML
      """
      # construct Munkres object for Hungarian Method association
      hm = Munkres()
      max_cost = 1e9
  
      # go through all frames and associate ground truth and tracker results
      # groundtruth and tracker contain lists for every single frame containing lists of KITTI format detections
      fr, ids = 0, 0
      for seq_idx in range(len(self.groundtruth)):
          seq_gt = self.groundtruth[seq_idx]
          seq_dc = self.dcareas[seq_idx]  # don't care areas
          seq_tracker = self.tracker[seq_idx]
          seq_trajectories = defaultdict(list)
          seq_ignored = defaultdict(list)
  
          # statistics over the current sequence, check the corresponding
          # variable comments in __init__ to get their meaning
          seqtp = 0
          seqitp = 0
          seqfn = 0
          seqifn = 0
          seqfp = 0
          seqigt = 0
          seqitr = 0
  
          last_ids = [[], []]
          n_gts = 0
          n_trs = 0
  
          for f in range(len(seq_gt)):
              g = seq_gt[f]
              dc = seq_dc[f]
  
              t = seq_tracker[f]
              # counting total number of ground truth and tracker objects
              self.n_gt += len(g)
              self.n_tr += len(t)
  
              n_gts += len(g)
              n_trs += len(t)
  
              # use hungarian method to associate, using boxoverlap 0..1 as cost
              # build cost matrix
              cost_matrix = []
              this_ids = [[], []]
              for gg in g:
                  # save current ids
                  this_ids[0].append(gg.track_id)
                  this_ids[1].append(-1)
                  gg.tracker = -1
                  gg.id_switch = 0
                  gg.fragmentation = 0
                  cost_row = []
                  for tt in t:
                      # overlap == 1 is cost ==0
                      c = 1 - self.boxoverlap(gg, tt)
                      # gating for boxoverlap
                      if c <= self.min_overlap:
                          cost_row.append(c)
                      else:
                          cost_row.append(max_cost)  # = 1e9
                  cost_matrix.append(cost_row)
                  # all ground truth trajectories are initially not associated
                  # extend groundtruth trajectories lists (merge lists)
                  seq_trajectories[gg.track_id].append(-1)
                  seq_ignored[gg.track_id].append(False)
  
              if len(g) is 0:
                  cost_matrix = [[]]
              # associate
              association_matrix = hm.compute(cost_matrix)
  
              # tmp variables for sanity checks and MODP computation
              tmptp = 0
              tmpfp = 0
              tmpfn = 0
              tmpc = 0  # this will sum up the overlaps for all true positives
              tmpcs = [0] * len(
                  g
              )  # this will save the overlaps for all true positives
              # the reason is that some true positives might be ignored
              # later such that the corrsponding overlaps can
              # be subtracted from tmpc for MODP computation
  
              # mapping for tracker ids and ground truth ids
              for row, col in association_matrix:
                  # apply gating on boxoverlap
                  c = cost_matrix[row][col]
                  if c < max_cost:
                      g[row].tracker = t[col].track_id
                      this_ids[1][row] = t[col].track_id
                      t[col].valid = True
                      g[row].distance = c
                      self.total_cost += 1 - c
                      tmpc += 1 - c
                      tmpcs[row] = 1 - c
                      seq_trajectories[g[row].track_id][-1] = t[
                          col
                      ].track_id
  
                      # true positives are only valid associations
                      self.tp += 1
                      tmptp += 1
                  else:
                      g[row].tracker = -1
                      self.fn += 1
                      tmpfn += 1
  
              # associate tracker and DontCare areas
              # ignore tracker in neighboring classes
              nignoredtracker = (
                  0  # number of ignored tracker detections
              )
              ignoredtrackers = (
                  dict()
              )  # will associate the track_id with -1
              # if it is not ignored and 1 if it is
              # ignored;
              # this is used to avoid double counting ignored
              # cases, see the next loop
  
              for tt in t:
                  ignoredtrackers[tt.track_id] = -1
                  # ignore detection if it belongs to a neighboring class or is
                  # smaller or equal to the minimum height
  
                  tt_height = abs(tt.y1 - tt.y2)
                  if (
                      (self.cls == "car" and tt.obj_type == "van")
                      or (
                          self.cls == "pedestrian"
                          and tt.obj_type == "person_sitting"
                      )
                      or tt_height <= self.min_height
                  ) and not tt.valid:
                      nignoredtracker += 1
                      tt.ignored = True
                      ignoredtrackers[tt.track_id] = 1
                      continue
                  for d in dc:
                      overlap = self.boxoverlap(tt, d, "a")
                      if overlap > 0.5 and not tt.valid:
                          tt.ignored = True
                          nignoredtracker += 1
                          ignoredtrackers[tt.track_id] = 1
                          break
  
              # check for ignored FN/TP (truncation or neighboring object class)
              ignoredfn = 0  # the number of ignored false negatives
              nignoredtp = 0  # the number of ignored true positives
              nignoredpairs = (
                  0  # the number of ignored pairs, i.e. a true positive
              )
              # which is ignored but where the associated tracker
              # detection has already been ignored
  
              gi = 0
              for gg in g:
                  if gg.tracker < 0:
                      if (
                          gg.occlusion > self.max_occlusion
                          or gg.truncation > self.max_truncation
                          or (
                              self.cls == "car" and gg.obj_type == "van"
                          )
                          or (
                              self.cls == "pedestrian"
                              and gg.obj_type == "person_sitting"
                          )
                      ):
                          seq_ignored[gg.track_id][-1] = True
                          gg.ignored = True
                          ignoredfn += 1
  
                  elif gg.tracker >= 0:
                      if (
                          gg.occlusion > self.max_occlusion
                          or gg.truncation > self.max_truncation
                          or (
                              self.cls == "car" and gg.obj_type == "van"
                          )
                          or (
                              self.cls == "pedestrian"
                              and gg.obj_type == "person_sitting"
                          )
                      ):
                          seq_ignored[gg.track_id][-1] = True
                          gg.ignored = True
                          nignoredtp += 1
  
                          # if the associated tracker detection is already ignored,
                          # we want to avoid double counting ignored detections
                          if ignoredtrackers[gg.tracker] > 0:
                              nignoredpairs += 1
  
                          # for computing MODP, the overlaps from ignored detections
                          # are subtracted
                          tmpc -= tmpcs[gi]
                  gi += 1
  
              # the below might be confusion, check the comments in __init__
              # to see what the individual statistics represent
  
              # correct TP by number of ignored TP due to truncation
              # ignored TP are shown as tracked in visualization
              tmptp -= nignoredtp
  
              # count the number of ignored true positives
              self.itp += nignoredtp
  
              # adjust the number of ground truth objects considered
              self.n_gt -= ignoredfn + nignoredtp
  
              # count the number of ignored ground truth objects
              self.n_igt += ignoredfn + nignoredtp
  
              # count the number of ignored tracker objects
              self.n_itr += nignoredtracker
  
              # count the number of ignored pairs, i.e. associated tracker and
              # ground truth objects that are both ignored
              self.n_igttr += nignoredpairs
  
              # false negatives = associated gt bboxes exceding association threshold + non-associated gt bboxes
              tmpfn += len(g) - len(association_matrix) - ignoredfn
              self.fn += len(g) - len(association_matrix) - ignoredfn
              self.ifn += ignoredfn
  
              # false positives = tracker bboxes - associated tracker bboxes
              # mismatches (mme_t)
              tmpfp += (
                  len(t)
                  - tmptp
                  - nignoredtracker
                  - nignoredtp
                  + nignoredpairs
              )
              self.fp += (
                  len(t)
                  - tmptp
                  - nignoredtracker
                  - nignoredtp
                  + nignoredpairs
              )
  
              # update sequence data
              seqtp += tmptp
              seqitp += nignoredtp
              seqfp += tmpfp
              seqfn += tmpfn
              seqifn += ignoredfn
              seqigt += ignoredfn + nignoredtp
              seqitr += nignoredtracker
  
              # sanity checks
              # - the number of true positives minues ignored true positives
              #   should be greater or equal to 0
              # - the number of false negatives should be greater or equal to 0
              # - the number of false positives needs to be greater or equal to 0
              #   otherwise ignored detections might be counted double
              # - the number of counted true positives (plus ignored ones)
              #   and the number of counted false negatives (plus ignored ones)
              #   should match the total number of ground truth objects
              # - the number of counted true positives (plus ignored ones)
              #   and the number of counted false positives
              #   plus the number of ignored tracker detections should
              #   match the total number of tracker detections; note that
              #   nignoredpairs is subtracted here to avoid double counting
              #   of ignored detection sin nignoredtp and nignoredtracker
              if tmptp < 0:
                  print(tmptp, nignoredtp)
                  raise NameError(
                      "Something went wrong! TP is negative"
                  )
              if tmpfn < 0:
                  print(
                      tmpfn,
                      len(g),
                      len(association_matrix),
                      ignoredfn,
                      nignoredpairs,
                  )
                  raise NameError(
                      "Something went wrong! FN is negative"
                  )
              if tmpfp < 0:
                  print(
                      tmpfp,
                      len(t),
                      tmptp,
                      nignoredtracker,
                      nignoredtp,
                      nignoredpairs,
                  )
                  raise NameError(
                      "Something went wrong! FP is negative"
                  )
              if tmptp + tmpfn is not len(g) - ignoredfn - nignoredtp:
                  print("seqidx", seq_idx)
                  print("frame ", f)
                  print("TP    ", tmptp)
                  print("FN    ", tmpfn)
                  print("FP    ", tmpfp)
                  print("nGT   ", len(g))
                  print("nAss  ", len(association_matrix))
                  print("ign GT", ignoredfn)
                  print("ign TP", nignoredtp)
                  raise NameError(
                      "Something went wrong! nGroundtruth is not TP+FN"
                  )
              if (
                  tmptp
                  + tmpfp
                  + nignoredtp
                  + nignoredtracker
                  - nignoredpairs
                  is not len(t)
              ):
                  print(seq_idx, f, len(t), tmptp, tmpfp)
                  print(len(association_matrix), association_matrix)
                  raise NameError(
                      "Something went wrong! nTracker is not TP+FP"
                  )
  
              # check for id switches or fragmentations
              for i, tt in enumerate(this_ids[0]):
                  if tt in last_ids[0]:
                      idx = last_ids[0].index(tt)
                      tid = this_ids[1][i]
                      lid = last_ids[1][idx]
                      if tid != lid and lid != -1 and tid != -1:
                          if g[i].truncation < self.max_truncation:
                              g[i].id_switch = 1
                              ids += 1
                      if tid != lid and lid != -1:
                          if g[i].truncation < self.max_truncation:
                              g[i].fragmentation = 1
                              fr += 1
  
              # save current index
              last_ids = this_ids
              # compute MOTP_t
              MODP_t = 1
              if tmptp != 0:
                  MODP_t = tmpc / float(tmptp)
              self.MODP_t.append(MODP_t)
  
          # remove empty lists for current gt trajectories
          self.gt_trajectories[seq_idx] = seq_trajectories
          self.ign_trajectories[seq_idx] = seq_ignored
  
          # gather statistics for "per sequence" statistics.
          self.n_gts.append(n_gts)
          self.n_trs.append(n_trs)
          self.tps.append(seqtp)
          self.itps.append(seqitp)
          self.fps.append(seqfp)
          self.fns.append(seqfn)
          self.ifns.append(seqifn)
          self.n_igts.append(seqigt)
          self.n_itrs.append(seqitr)
  
      # compute MT/PT/ML, fragments, idswitches for all groundtruth trajectories
      n_ignored_tr_total = 0
      for seq_idx, (seq_trajectories, seq_ignored) in enumerate(
          zip(self.gt_trajectories, self.ign_trajectories)
      ):
          if len(seq_trajectories) == 0:
              continue
          tmpMT, tmpML, tmpPT, tmpId_switches, tmpFragments = [0] * 5
          n_ignored_tr = 0
          for g, ign_g in zip(
              seq_trajectories.values(), seq_ignored.values()
          ):
              # all frames of this gt trajectory are ignored
              if all(ign_g):
                  n_ignored_tr += 1
                  n_ignored_tr_total += 1
                  continue
              # all frames of this gt trajectory are not assigned to any detections
              if all([this == -1 for this in g]):
                  tmpML += 1
                  self.ML += 1
                  continue
              # compute tracked frames in trajectory
              last_id = g[0]
              # first detection (necessary to be in gt_trajectories) is always tracked
              tracked = 1 if g[0] >= 0 else 0
              lgt = 0 if ign_g[0] else 1
              for f in range(1, len(g)):
                  if ign_g[f]:
                      last_id = -1
                      continue
                  lgt += 1
                  if (
                      last_id != g[f]
                      and last_id != -1
                      and g[f] != -1
                      and g[f - 1] != -1
                  ):
                      tmpId_switches += 1
                      self.id_switches += 1
                  if (
                      f < len(g) - 1
                      and g[f - 1] != g[f]
                      and last_id != -1
                      and g[f] != -1
                      and g[f + 1] != -1
                  ):
                      tmpFragments += 1
                      self.fragments += 1
                  if g[f] != -1:
                      tracked += 1
                      last_id = g[f]
              # handle last frame; tracked state is handled in for loop (g[f]!=-1)
              if (
                  len(g) > 1
                  and g[f - 1] != g[f]
                  and last_id != -1
                  and g[f] != -1
                  and not ign_g[f]
              ):
                  tmpFragments += 1
                  self.fragments += 1
  
              # compute MT/PT/ML
              tracking_ratio = tracked / float(len(g) - sum(ign_g))
              if tracking_ratio > 0.8:
                  tmpMT += 1
                  self.MT += 1
              elif tracking_ratio < 0.2:
                  tmpML += 1
                  self.ML += 1
              else:  # 0.2 <= tracking_ratio <= 0.8
                  tmpPT += 1
                  self.PT += 1
  
      if (self.n_gt_trajectories - n_ignored_tr_total) == 0:
          self.MT = 0.0
          self.PT = 0.0
          self.ML = 0.0
      else:
          self.MT /= float(self.n_gt_trajectories - n_ignored_tr_total)
          self.PT /= float(self.n_gt_trajectories - n_ignored_tr_total)
          self.ML /= float(self.n_gt_trajectories - n_ignored_tr_total)
  
      # precision/recall etc.
      if (self.fp + self.tp) == 0 or (self.tp + self.fn) == 0:
          self.recall = 0.0
          self.precision = 0.0
      else:
          self.recall = self.tp / float(self.tp + self.fn)
          self.precision = self.tp / float(self.fp + self.tp)
      if (self.recall + self.precision) == 0:
          self.F1 = 0.0
      else:
          self.F1 = (
              2.0
              * (self.precision * self.recall)
              / (self.precision + self.recall)
          )
      if sum(self.n_frames) == 0:
          self.FAR = "n/a"
      else:
          self.FAR = self.fp / float(sum(self.n_frames))
  
      # compute CLEARMOT
      if self.n_gt == 0:
          self.MOTA = -float("inf")
          self.MODA = -float("inf")
      else:
          self.MOTA = 1 - (
              self.fn + self.fp + self.id_switches
          ) / float(self.n_gt)
          self.MODA = 1 - (self.fn + self.fp) / float(self.n_gt)
      if self.tp == 0:
          self.MOTP = float("inf")
      else:
          self.MOTP = self.total_cost / float(self.tp)
      if self.n_gt != 0:
          if self.id_switches == 0:
              self.MOTAL = 1 - (
                  self.fn + self.fp + self.id_switches
              ) / float(self.n_gt)
          else:
              self.MOTAL = 1 - (
                  self.fn + self.fp + math.log10(self.id_switches)
              ) / float(self.n_gt)
      else:
          self.MOTAL = -float("inf")
      if sum(self.n_frames) == 0:
          self.MODP = "n/a"
      else:
          self.MODP = sum(self.MODP_t) / float(sum(self.n_frames))
      return True
  
imports: from __future__ import absolute_import
  from __future__ import division
  from __future__ import print_function
  import os
  import copy
  import sys
  import math
  from collections import defaultdict
  import numpy
  from ppdet.modeling.bbox_utils import bbox_iou_np_expand
  from .map_utils import ap_per_class
  from .metrics import Metric
  from .munkres import Munkres
  from ppdet.utils.logger import setup_logger
label_desc: Use image node_id 6 for calling the KITTIEvaluation obj's underlying member method code with example usage: obj.compute3rdPartyMetrics() and returns: True