-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
278 lines (233 loc) · 8.62 KB
/
app.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
import argparse
import json
import logging
import os
import random
import time
from functools import reduce
import numpy as np
import yaml
from kafka import KafkaProducer
from pssm.dglm import NormalDLM, PoissonDLM, BinomialDLM
from pssm.structure import UnivariateStructure
from scipy.stats import multivariate_normal as mvn
from transformers import BinomialTransformer, CompositeTransformer
def _read_conf(conf):
"""
Convert a YAML configuration into a dictionary
:param conf: The configuration filename
:return: A dictionary
"""
with open(conf, 'r') as stream:
try:
d = yaml.load(stream)
return d
except yaml.YAMLError as exc:
print(exc)
def _parse_component(conf):
"""
Parse an individual record of the structure configuration
:param conf: the configuration, as a dictionary
:return: a tuple of structure, anomalies structure and prior mean
"""
type = conf['type']
logging.debug(conf)
if type == 'mean':
logging.debug("Add a LC structure")
W = float(conf['noise'])
m0 = [conf['start']]
structure = UnivariateStructure.locally_constant(W)
elif type == 'season':
# check if number of harmonics is defined
if 'harmonics' in conf:
nharmonics = conf['harmonics']
else:
nharmonics = 3
W = np.identity(2 * nharmonics) * float(conf['noise'])
m0 = [conf['start']] * W.shape[0]
period = int(conf['period'])
structure = UnivariateStructure.cyclic_fourier(period=period,
harmonics=nharmonics,
W=W)
elif type == 'arma':
if 'coefficients' in conf:
coefficients = [float(p) for p in conf['coefficients'].split(',')]
else:
coefficients = [1.0]
noise = float(conf['noise'])
m0 = [conf['start']] * len(coefficients)
structure = UnivariateStructure.arma(p=len(coefficients),
betas=coefficients,
W=noise)
else:
raise ValueError("Unknown component type '{}'".format(conf['type']))
# proceed if there's an `anomalies` directive
if 'anomalies' in conf:
# we have anomalies in the conf
anom_conf = conf['anomalies']
if 'probability' in anom_conf and 'scale' in anom_conf:
anomalies = []
for i in range(structure.W.shape[0]):
anomalies.append(lambda x: x * float(
anom_conf['scale']) if random.random() < anom_conf[
'probability'] else x)
else:
# we don't have anomalies in the conf
anomalies = [lambda x: x for i in range(structure.W.shape[0])]
logging.debug(anomalies)
return structure, anomalies, m0
def _parse_structure(conf):
structures = []
m0 = []
anomalies = []
for structure in conf:
_structure, _anomalies, _m0 = _parse_component(structure)
m0.extend(_m0)
anomalies.extend(_anomalies)
structures.append(_structure)
m0 = np.array(m0)
C0 = np.eye(len(m0))
return reduce((lambda x, y: x + y), structures), m0, C0, anomalies
def _parse_composite(conf):
models = []
prior_mean = []
anomaly_vector = []
for element in conf:
if 'replicate' in element:
structure, m0, C0, anomalies = _parse_structure(
element['structure'])
prior_mean.extend([m0] * element['replicate'])
anomaly_vector.extend(anomalies * element['replicate'])
model = _parse_observations(element['observations'], structure)
models.extend([model] * element['replicate'])
else:
structure, m0, C0, anomalies = _parse_structure(
element['structure'])
prior_mean.extend(m0)
anomaly_vector.extend(anomalies)
model = _parse_observations(element['observations'], structure)
models.append(model)
print(models)
model = CompositeTransformer(*models)
m0 = np.array(prior_mean)
C0 = np.eye(len(m0))
return model, m0, C0, anomaly_vector
def _parse_observations(obs, structure):
if obs['type'] == 'continuous':
model = NormalDLM(structure=structure, V=obs['noise'])
elif obs['type'] == 'discrete':
model = PoissonDLM(structure=structure)
elif obs['type'] == 'categorical':
if 'values' in obs:
values = obs['values'].split(',')
model = BinomialTransformer(structure=structure, source=values)
elif 'categories' in obs:
model = BinomialDLM(structure=structure,
categories=obs['categories'])
else:
raise ValueError("Categorical models must have either 'values' "
"or 'categories'")
else:
raise ValueError("Model type {} is not valid".format(obs['type']))
return model
def parse_configuration(conf):
"""
Parse a YAML configuration string into an state-space model
:param conf:
:return: A state-space model
"""
if 'compose' in conf:
model, m0, C0, anomalies = _parse_composite(conf['compose'])
else:
structure, m0, C0, anomalies = _parse_structure(conf['structure'])
model = _parse_observations(conf['observations'], structure)
state = mvn(m0, C0).rvs()
period = float(conf['period'])
name = conf['name']
return model, state, period, name, anomalies
def build_message(name, value):
return json.dumps({
'name': name,
'value': value
}).encode()
def main(args):
logging.basicConfig(level=args.logging)
logging.info('brokers={}'.format(args.brokers))
logging.info('topic={}'.format(args.topic))
logging.info('conf={}'.format(args.conf))
if args.conf:
model, state, period, name, anomalies = parse_configuration(
_read_conf(args.conf))
else:
state = np.array([0])
lc = UnivariateStructure.locally_constant(1.0)
model = NormalDLM(structure=lc, V=1.4)
period = 2.0
name = 'data'
anomalies = [lambda x: x]
logging.info('creating kafka producer')
producer = KafkaProducer(bootstrap_servers=args.brokers)
logging.info('sending lines (frequency = {})'.format(period))
while True:
dimensions = np.size(state)
if dimensions == 1:
logging.debug("state = {}".format(state))
_state = anomalies[0](state)
logging.debug("anomaly = {}".format(_state))
else:
_state = np.copy(state)
for i in range(dimensions):
logging.debug("state {} = {}".format(i, state[i]))
_state[i] = anomalies[i](state[i])
logging.debug("anomaly {} = {}".format(i, state[i]))
y = model.observation(_state)
state = model.state(state)
message = build_message(name, y)
logging.info("message = {}".format(message))
producer.send(args.topic, message)
time.sleep(period)
def get_arg(env, default):
return os.getenv(env) if os.getenv(env, '') is not '' else default
def loglevel(level):
levels = {'CRITICAL': logging.CRITICAL,
'FATAL': logging.FATAL,
'ERROR': logging.ERROR,
'WARNING': logging.WARNING,
'WARN': logging.WARNING,
'INFO': logging.INFO,
'DEBUG': logging.DEBUG,
'NOTSET': logging.NOTSET}
return levels[level]
def parse_args(parser):
args = parser.parse_args()
args.brokers = get_arg('KAFKA_BROKERS', args.brokers)
args.topic = get_arg('KAFKA_TOPIC', args.topic)
args.conf = get_arg('CONF', args.conf)
args.logging = loglevel(get_arg('LOGGING', args.logging))
return args
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
logging.info('starting timeseries-mock emitter')
parser = argparse.ArgumentParser(
description='timeseries data simulator for Kafka')
parser.add_argument(
'--brokers',
help='The bootstrap servers, env variable KAFKA_BROKERS',
default='localhost:9092')
parser.add_argument(
'--topic',
help='Topic to publish to, env variable KAFKA_TOPIC',
default='data')
parser.add_argument(
'--conf',
type=str,
help='Configuration file (YAML)',
default=None)
parser.add_argument(
'--logging',
help='Set the app logging level',
type=str,
default='INFO')
args = parse_args(parser)
main(args)
logging.info('exiting')