patternMatchVariance static method

double patternMatchVariance(
  1. List<int> counters,
  2. List<int> pattern,
  3. double maxIndividualVariance
)

Determines how closely a set of observed counts of runs of black/white values matches a given target pattern. This is reported as the ratio of the total variance from the expected pattern proportions across all pattern elements, to the length of the pattern.

@param counters observed counters @param pattern expected pattern @param maxIndividualVariance The most any counter can differ before we give up @return ratio of total variance between counters and pattern compared to total pattern size

Implementation

static double patternMatchVariance(
  List<int> counters,
  List<int> pattern,
  double maxIndividualVariance,
) {
  final numCounters = counters.length;
  int total = 0;
  int patternLength = 0;
  for (int i = 0; i < numCounters; i++) {
    total += counters[i];
    patternLength += pattern[i];
  }
  if (total < patternLength) {
    // If we don't even have one pixel per unit of bar width, assume this is too small
    // to reliably match, so fail:
    return double.infinity;
  }

  final unitBarWidth = total / patternLength;
  maxIndividualVariance *= unitBarWidth;

  double totalVariance = 0.0;
  for (int x = 0; x < numCounters; x++) {
    final counter = counters[x];
    final scaledPattern = pattern[x] * unitBarWidth;
    final variance = counter > scaledPattern
        ? counter - scaledPattern
        : scaledPattern - counter;
    if (variance > maxIndividualVariance) {
      return double.infinity;
    }
    totalVariance += variance;
  }
  return totalVariance / total;
}