-
Notifications
You must be signed in to change notification settings - Fork 0
/
sex_stats.py
265 lines (202 loc) · 7.51 KB
/
sex_stats.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser
from datetime import datetime
from enum import Enum
from re import match
from typing import NamedTuple, Optional
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.gridspec import GridSpec
from pandas import DataFrame, read_csv, to_datetime
__version__ = '1.3 (i-miss-you)'
class Regex(str, Enum):
Year = r'(?P<Year>(19|2\d)?\d{2})'
Month = r'(?P<Month>1[0-2]|0\d)'
Day = r'(?P<Day>[123]\d|0\d)'
Hour = r'(?P<Hour>[01]?\d|2[0-3])'
Minute = r'(?P<Minute>[0-5]\d)'
Second = r'(?P<Second>[0-5]\d)'
Time = fr'{Hour}:{Minute}(:{Second})?'
Repeat = r'(?P<Repeat>\d) times?'
Kind = r'(?P<Kind>\w+( \(\w+\))?)'
class TimeStamp(NamedTuple):
"""A Timestamp namedtuple, no accurate time required.
"""
Year: int
Month: int
Day: int
Hour: int = 0
Minute: int = 0
Second: int = 0
@property
def _datetime(self):
return datetime(*(int(_) if _ else 0 for _ in self))
class LogLine(NamedTuple):
"""A Log Line nametuple.
"""
TimeStamp: TimeStamp
Repeat: int = 1
Kind: Optional[str] = None
def parse_time_str(time_str: str) -> TimeStamp:
"""Parse time string and return a TimeStamp object.
"""
acceptable_regex = {
fr'^{Regex.Year}-{Regex.Month}-{Regex.Day}\*{Regex.Time}',
fr'^{Regex.Day}/{Regex.Month}/{Regex.Year} {Regex.Time}'
}
for regex in acceptable_regex:
if (matched := match(regex, time_str)):
return TimeStamp(**matched.groupdict())
def parse_log_line(line: str) -> LogLine:
"""Parse log line and return a LogLine object.
"""
acceptable_regex = fr'^.+ {Regex.Repeat} {Regex.Kind}'
if (timestamp := parse_time_str(line)):
matched = match(acceptable_regex, line)
return LogLine(timestamp._datetime, int(matched['Repeat']),
matched['Kind'])
def read_activity_log(fp: str, header: int = 1) -> DataFrame:
"""Reads Sex Activity Log file.
"""
with open(fp, 'r') as f:
df = DataFrame(map(parse_log_line, f.readlines()[header:]))
df['TimeStamp'] = to_datetime(df.TimeStamp)
# df.set_index('TimeStamp')
return df
def read_activity_whealth(fp: str):
"""Reads Sex Activity data from wHealth.
"""
df = read_csv(fp, sep=';')
# clean data
df = df.drop(columns=['unit', 'name', 'source'], axis=1)\
.rename(columns={'startdate': 'TimeStamp', 'value': 'Repeat'})
df['TimeStamp'] = to_datetime(df.TimeStamp)
df['Kind'] = 'Unknown'
return df
def group_data(df, offset_alias: str = 'M'):
"""Group DataFrame data by an time period offset.
"""
available_offset = ('W', 'SM', 'M', 'Q', 'A', 'H')
if offset_alias in available_offset:
return df.resample(offset_alias, on='TimeStamp')
def plot_freq_bar(df, offset_alias: str = 'M', ax=None, legend: bool = True):
"""Plot Frequency against Time Period.
"""
if not ax:
ax = plt.subplot()
grouped = group_data(df, offset_alias)
df_sum = grouped['Kind'].value_counts().unstack()
df_sum.set_index(df_sum.index.map(lambda s: s.strftime('%y\n%m')))\
.plot(rot=0, kind='bar', ax=ax, stacked=True, legend=legend)
grouped['Repeat'].sum()\
.plot(style='--o',
ax=ax,
color='grey',
use_index=False,
label='Overall',
legend=legend)
ax.set_title('Frequency vs Time Period')
ax.set_ylabel('Frequency')
ax.set_xlabel(f'Period ({offset_alias})')
def time_function(df: DataFrame):
"""Returns a function that calculates o’clock fractions.
Should I keep narrowing the divisions as the size goes bigger?
-> no, because < 1 min does not make sense. 6 mins already suffice.
"""
data_size = df.shape[0]
def fn(x):
if data_size <= 50: # use whole hour
step = round(x.minute/60)
elif data_size <= 100: # use half division (every 30 mins)
step = round(x.minute/60*2)/2
elif data_size <= 200: # use quatre division (every 15 mins)
step = round(x.minute/60*4)/4
else: # use tenth division of hour (every 6 mins)
step = round(x.minute/60, 1)
return x.hour + step
return fn
def plot_density(df, ax=None, legend: bool = True):
"""Plot KDE (Kernel Density Estimation).
"""
if not ax:
ax = plt.subplot()
grouped = df.set_index('TimeStamp')\
.groupby(time_function(df))['Kind'].value_counts().unstack()
grouped.plot.kde(ax=ax, legend=legend)
ax.set_title('Kernel Density Estimation')
ax.set_ylabel('Density')
ax.set_xlabel('Repeated Times')
def plot_day_hour(df, ax=None, legend: bool = True):
"""Plot activities in a day.
"""
if not ax:
ax = plt.subplot()
grouped = df.set_index('TimeStamp')\
.groupby(time_function(df))['Kind'].value_counts().unstack()
# Plot mean
grouped_mean = grouped.mean(axis=1) # .fillna(0)
ax.plot(grouped_mean.index, grouped_mean, color='grey', linestyle='-', label='Mean')
# Plot scattered points
for kind in grouped.columns:
plt.scatter(grouped.index, grouped[kind], label=kind)
ax.set_title('Activities in a Day')
ax.set_ylabel('Frequency')
ax.set_xlabel('O’Clock')
ax.set_xlim(-.5, 24.5)
ax.set_ylim(0, grouped.max().max() + 1)
ax.set_yticks(list(range(int(grouped.max().max()) + 2)))
ax.set_xticks(list(range(24)))
if legend:
ax.legend()
def plot_all(df):
"""Plot all three charts in one large diagram.
"""
fig = plt.figure(constrained_layout=True)
fig.suptitle(f'Sex Activity Statistics ({df.Repeat.size} entries)')
gs = GridSpec(2, 2, figure=fig)
ax = fig.add_subplot(gs[0, :])
plot_day_hour(df, ax=ax, legend=False)
ax2 = fig.add_subplot(gs[1, 0])
plot_freq_bar(df, ax=ax2, legend=False)
ax3 = fig.add_subplot(gs[1, 1])
plot_density(df, ax=ax3, legend=False)
handles, labels = ax3.get_legend_handles_labels()
fig.legend(handles, labels, title='Kind', loc='upper right')
def cli_parsed():
parser = ArgumentParser(
description='Analyse sex activity data.',
formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument('--file', '-f', required=True, help='Log file path.')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--chart',
choices=['freq', 'day', 'kde', 'all'],
help='Specify charts to plot \
(options: freq, day, kde, all).')
group.add_argument('--all',
action='store_true',
help='Plot all charts in one large diagram.')
return parser
if __name__ == '__main__':
args = cli_parsed().parse_args()
# Read dataset (csv and txt)
if args.file.rsplit('.', 1)[-1] == 'csv':
log_lines = read_activity_whealth(args.file)
else:
log_lines = read_activity_log(args.file)
# Plot settings
sns.set()
plot_fns = {
'freq': plot_freq_bar,
'day': plot_day_hour,
'kde': plot_density,
}
if args.all:
plot_all(log_lines)
elif args.chart == 'all':
for fn in plot_fns.values():
fn(log_lines)
plt.show()
elif args.chart in plot_fns:
plot_fns[args.chart](log_lines)
plt.show()