1#  Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
2#
3#  Use of this source code is governed by a BSD-style license
4#  that can be found in the LICENSE file in the root of the source
5#  tree. An additional intellectual property rights grant can be found
6#  in the file PATENTS.  All contributing project authors may
7#  be found in the AUTHORS file in the root of the source tree.
8
9"""Utility functions for calculating statistics.
10"""
11
12from __future__ import division
13import collections
14import sys
15
16
17def CountReordered(sequence_numbers):
18  """Returns number of reordered indices.
19
20  A reordered index is an index `i` for which sequence_numbers[i] >=
21  sequence_numbers[i + 1]
22  """
23  return sum(1 for (s1, s2) in zip(sequence_numbers,
24                                   sequence_numbers[1:]) if
25             s1 >= s2)
26
27
28def SsrcNormalizedSizeTable(data_points):
29  """Counts proportion of data for every SSRC.
30
31  Args:
32     data_points: list of pb_parse.DataPoint
33
34  Returns:
35     A dictionary mapping from every SSRC in the data points. The
36     value of an SSRC `s` is the proportion of sizes of packets with
37     SSRC `s` to the total size of all packets.
38
39  """
40  mapping = collections.defaultdict(int)
41  for point in data_points:
42    mapping[point.ssrc] += point.size
43  return NormalizeCounter(mapping)
44
45
46def NormalizeCounter(counter):
47  """Returns a normalized version of the dictionary `counter`.
48
49  Does not modify `counter`.
50
51  Returns:
52    A new dictionary, in which every value in `counter`
53    has been divided by the total to sum up to 1.
54  """
55  total = sum(counter.values())
56  return {key: counter[key] / total for key in counter}
57
58
59def Unwrap(data, mod):
60  """Returns `data` unwrapped modulo `mod`. Does not modify data.
61
62  Adds integer multiples of mod to all elements of data except the
63  first, such that all pairs of consecutive elements (a, b) satisfy
64  -mod / 2 <= b - a < mod / 2.
65
66  E.g. Unwrap([0, 1, 2, 0, 1, 2, 7, 8], 3) -> [0, 1, 2, 3,
67  4, 5, 4, 5]
68  """
69  lst = data[:]
70  for i in range(1, len(data)):
71    lst[i] = lst[i - 1] + (lst[i] - lst[i - 1] +
72                           mod // 2) % mod - (mod // 2)
73  return lst
74
75
76def SsrcDirections(data_points):
77  ssrc_is_incoming = {}
78  for point in data_points:
79    ssrc_is_incoming[point.ssrc] = point.incoming
80  return ssrc_is_incoming
81
82
83# Python 2/3-compatible input function
84if sys.version_info[0] <= 2:
85  get_input = raw_input  # pylint: disable=invalid-name
86else:
87  get_input = input  # pylint: disable=invalid-name
88