-
Notifications
You must be signed in to change notification settings - Fork 20
/
entropy.py
386 lines (324 loc) · 12.9 KB
/
entropy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# -*- coding: utf-8 -*-
"""
Calculates various entropy metrics for subscribers with a specified time
period.
"""
from abc import ABCMeta, abstractmethod
from typing import List, Union
from flowmachine.core import make_spatial_unit
from flowmachine.core.spatial_unit import AnySpatialUnit
from flowmachine.features.utilities.events_tables_union import EventsTablesUnion
from flowmachine.features.utilities.subscriber_locations import SubscriberLocations
from flowmachine.features.subscriber.contact_balance import ContactBalance
from flowmachine.features.subscriber.metaclasses import SubscriberFeature
from flowmachine.features.utilities.direction_enum import Direction
from flowmachine.utils import make_where, standardise_date
class BaseEntropy(SubscriberFeature, metaclass=ABCMeta):
""" Base query for calculating entropy of subscriber features. """
@property
def column_names(self) -> List[str]:
return ["subscriber", "entropy"]
def _make_query(self):
return f"""
SELECT
subscriber,
-1 * SUM( relative_freq * LN( relative_freq ) ) AS entropy
FROM ({self._relative_freq_query}) u
GROUP BY subscriber
"""
@property
@abstractmethod
def _absolute_freq_query(self):
raise NotImplementedError
@property
def _relative_freq_query(self):
return f"""
SELECT
subscriber,
absolute_freq::float / ( SUM( absolute_freq ) OVER ( PARTITION BY subscriber ) ) AS relative_freq
FROM ({self._absolute_freq_query}) u
"""
class PeriodicEntropy(BaseEntropy):
"""
Calculates the recurrence period entropy for events, that is the entropy
associated with the period in which events take place. For instance, if
events regularly occur at a certain time of day, say at 9:00 and 18:00 then
this user will have a low period entropy.
Entropy is calculated as:
-1 * SUM( relative_freq * LN( relative_freq ) )
where `relative_freq` is the relative frequency of events occurring at a
certain period (eg. hour of the day, day of the week, month of the year).
This formula represents a consistent estimate of the true entropy only
under certain conditions. Among them, that the relative frequency is a good
approximation to the probability that a certain event occurs within certain
periodic phases. In case of strong autocorrelation, this might not be true.
Parameters
----------
start, stop : str
iso-format start and stop datetimes
phase : {"century", "day", "decade", "dow", "doy", "epoch", "hour",
"isodow", "isoyear", "microseconds", "millennium", "milliseconds",
"minute", "month", "quarter", "second", "week", "year"}, default 'hour'
The phase of recurrence for which one wishes to calculate the entropy
for. See [Postgres
manual](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT)
for further info on the allowed phases.
subscriber_identifier : {'msisdn', 'imei'}, default 'msisdn'
Either msisdn, or imei, the column that identifies the subscriber.
subscriber_subset : str, list, flowmachine.core.Query, flowmachine.core.Table, default None
If provided, string or list of string which are msisdn or imeis to limit
results to; or, a query or table which has a column with a name matching
subscriber_identifier (typically, msisdn), to limit results to.
direction : {'in', 'out', 'both'} or Direction, default Direction.BOTH
Whether to consider calls made, received, or both. Defaults to 'both'.
hours : 2-tuple of floats, default 'all'
Restrict the analysis to only a certain set
of hours within each day.
tables : str or list of strings, default 'all'
Can be a string of a single table (with the schema)
or a list of these. The keyword all is to select all
subscriber tables
Examples
--------
>>> s = PeriodicEntropy("2016-01-01", "2016-01-07")
>>> s.get_dataframe()
subscriber entropy
038OVABN11Ak4W5P 2.805374
09NrjaNNvDanD8pk 2.730881
0ayZGYEQrqYlKw6g 2.802434
0DB8zw67E9mZAPK2 2.476354
0Gl95NRLjW2aw8pW 2.788854
... ...
"""
def __init__(
self,
start,
stop,
phase="hour",
*,
subscriber_identifier="msisdn",
direction: Union[str, Direction] = Direction.BOTH,
hours="all",
subscriber_subset=None,
tables="all",
):
self.tables = tables
self.start = standardise_date(start)
self.stop = standardise_date(stop)
self.subscriber_identifier = subscriber_identifier
self.direction = Direction(direction)
self.hours = hours
column_list = [
self.subscriber_identifier,
"datetime",
*self.direction.required_columns,
]
# extracted from the POSTGRES manual
allowed_phases = (
"century",
"day",
"decade",
"dow",
"doy",
"epoch",
"hour",
"isodow",
"isoyear",
"microseconds",
"millennium",
"milliseconds",
"minute",
"month",
"quarter",
"second",
"week",
"year",
)
if phase not in allowed_phases:
raise ValueError(
f"{phase} is not a valid phase. Choose one of {allowed_phases}"
)
self.phase = phase
self.unioned_query = EventsTablesUnion(
self.start,
self.stop,
tables=self.tables,
columns=column_list,
hours=hours,
subscriber_identifier=subscriber_identifier,
subscriber_subset=subscriber_subset,
)
super().__init__()
@property
def _absolute_freq_query(self):
return f"""
SELECT subscriber, COUNT(*) AS absolute_freq FROM
({self.unioned_query.get_query()}) u
{make_where(self.direction.get_filter_clause())}
GROUP BY subscriber, EXTRACT( {self.phase} FROM datetime )
HAVING COUNT(*) > 0
"""
class LocationEntropy(BaseEntropy):
"""
Calculates the entropy of locations visited. For instance, if an individual
regularly makes her/his calls from certain location then this user will
have a low location entropy.
Entropy is calculated as:
-1 * SUM( relative_freq * LN( relative_freq ) )
where `relative_freq` is the relative frequency of events occurring at a
certain location (eg. cell, site, admnistrative region, etc.).
This formula represents a consistent estimate of the true entropy only
under certain conditions. Among them, that the relative frequency is a good
approximation to the probability that a certain event occurs in a given
location. In case of strong spatial autocorrelation, this might not be
true.
Parameters
----------
start, stop : str
iso-format start and stop datetimes
spatial_unit : flowmachine.core.spatial_unit.*SpatialUnit, default cell
Spatial unit to which subscriber locations will be mapped. See the
docstring of make_spatial_unit for more information.
subscriber_identifier : {'msisdn', 'imei'}, default 'msisdn'
Either msisdn, or imei, the column that identifies the subscriber.
subscriber_subset : str, list, flowmachine.core.Query, flowmachine.core.Table, default None
If provided, string or list of string which are msisdn or imeis to limit
results to; or, a query or table which has a column with a name matching
subscriber_identifier (typically, msisdn), to limit results to.
hours : 2-tuple of floats, default 'all'
Restrict the analysis to only a certain set
of hours within each day.
tables : str or list of strings, default 'all'
Can be a string of a single table (with the schema)
or a list of these. The keyword all is to select all
subscriber tables
Examples
--------
>>> s = LocationEntropy("2016-01-01", "2016-01-07")
>>> s.get_dataframe()
subscriber entropy
038OVABN11Ak4W5P 2.832747
09NrjaNNvDanD8pk 3.184784
0ayZGYEQrqYlKw6g 3.072458
0DB8zw67E9mZAPK2 2.838989
0Gl95NRLjW2aw8pW 2.997069
... ...
"""
def __init__(
self,
start,
stop,
*,
spatial_unit: AnySpatialUnit = make_spatial_unit("cell"),
subscriber_identifier="msisdn",
hours="all",
subscriber_subset=None,
tables="all",
ignore_nulls=True,
):
self.subscriber_locations = SubscriberLocations(
start=start,
stop=stop,
spatial_unit=spatial_unit,
table=tables,
hours=hours,
subscriber_identifier=subscriber_identifier,
subscriber_subset=subscriber_subset,
ignore_nulls=ignore_nulls,
)
super().__init__()
@property
def _absolute_freq_query(self):
location_cols = ", ".join(
self.subscriber_locations.spatial_unit.location_id_columns
)
return f"""
SELECT subscriber, COUNT(*) AS absolute_freq FROM
({self.subscriber_locations.get_query()}) u
GROUP BY subscriber, {location_cols}
HAVING COUNT(*) > 0
"""
class ContactEntropy(BaseEntropy):
"""
Calculates the entropy of counterparts contacted. For instance, if an
individual regularly interacts with a few determined counterparts on a
predictable way then this user will have a low contact entropy.
Entropy is calculated as:
-1 * SUM( relative_freq * LN( relative_freq ) )
where `relative_freq` is the relative frequency of events with a given
counterpart.
This formula represents a consistent estimate of the true entropy only
under certain conditions. Among them, that the relative frequency is a good
approximation to the probability that a certain event will occur with a
given counterpart. In case of strong correlation between counterparts, this
might not be true.
Parameters
----------
start, stop : str
iso-format start and stop datetimes
subscriber_identifier : {'msisdn', 'imei'}, default 'msisdn'
Either msisdn, or imei, the column that identifies the subscriber.
subscriber_subset : str, list, flowmachine.core.Query, flowmachine.core.Table, default None
If provided, string or list of string which are msisdn or imeis to limit
results to; or, a query or table which has a column with a name matching
subscriber_identifier (typically, msisdn), to limit results to.
direction : {'in', 'out', 'both'} or Direction, default Direction.BOTH
Whether to consider calls made, received, or both. Defaults to 'both'.
hours : 2-tuple of floats, default 'all'
Restrict the analysis to only a certain set
of hours within each day.
tables : str or list of strings, default 'all'
Can be a string of a single table (with the schema)
or a list of these. The keyword all is to select all
subscriber tables
exclude_self_calls : bool, default True
Set to false to *include* calls a subscriber made to themself
Examples
--------
>>> s = ContactEntropy("2016-01-01", "2016-01-07")
>>> s.get_dataframe()
subscriber entropy
2ZdMowMXoyMByY07 0.692461
MobnrVMDK24wPRzB 0.691761
0Ze1l70j0LNgyY4w 0.693147
Nnlqka1oevEMvVrm 0.607693
gPZ7jbqlnAXR3JG5 0.686211
... ...
"""
def __init__(
self,
start,
stop,
*,
subscriber_identifier="msisdn",
direction: Union[str, Direction] = Direction.BOTH,
hours="all",
subscriber_subset=None,
tables="all",
exclude_self_calls=True,
):
self.contact_balance = ContactBalance(
start=start,
stop=stop,
hours=hours,
tables=tables,
subscriber_identifier=subscriber_identifier,
direction=direction,
exclude_self_calls=exclude_self_calls,
subscriber_subset=subscriber_subset,
)
@property
def _absolute_freq_query(self):
return f"""
SELECT subscriber, events AS absolute_freq FROM
({self.contact_balance.get_query()}) u
"""
@property
def _relative_freq_query(self):
return f"""
SELECT subscriber, proportion AS relative_freq FROM
({self.contact_balance.get_query()}) u
"""