code: def weighted_median(
      a: np.ndarray, weights: Optional[np.ndarray] = None
  ) -> np.ndarray:
      """Calculate weighted median."""
      if weights is None:
          return np.median(a)
  
      # calculate cdf
      indices = np.argsort(a)
      s_ranks = a[indices]
      s_weights = weights[indices]
      cdf = np.cumsum(s_weights)
      cdf /= cdf[-1]
      # determine value at p=0.5
      idx = np.searchsorted(cdf, v=0.5)
      # special case for exactly 0.5
      if cdf[idx] == 0.5:
          return s_ranks[idx : idx + 2].mean()
      return s_ranks[idx]
  
imports: from dataclasses import dataclass
  from typing import ClassVar, Collection, Optional
  import numpy
  from docdata import get_docdata
  from scipy import stats
  from ..utils import ExtraReprMixin, camel_to_snake
label_desc: Use image node_id 5 for calling a global function with example usage: weighted_median(a, weights) and returns: s_ranks, np, s_ranks