id
int64 0
843k
| repository_name
stringlengths 7
55
| file_path
stringlengths 9
332
| class_name
stringlengths 3
290
| human_written_code
stringlengths 12
4.36M
| class_skeleton
stringlengths 19
2.2M
| total_program_units
int64 1
9.57k
| total_doc_str
int64 0
4.2k
| AvgCountLine
float64 0
7.89k
| AvgCountLineBlank
float64 0
300
| AvgCountLineCode
float64 0
7.89k
| AvgCountLineComment
float64 0
7.89k
| AvgCyclomatic
float64 0
130
| CommentToCodeRatio
float64 0
176
| CountClassBase
float64 0
48
| CountClassCoupled
float64 0
589
| CountClassCoupledModified
float64 0
581
| CountClassDerived
float64 0
5.37k
| CountDeclInstanceMethod
float64 0
4.2k
| CountDeclInstanceVariable
float64 0
299
| CountDeclMethod
float64 0
4.2k
| CountDeclMethodAll
float64 0
4.2k
| CountLine
float64 1
115k
| CountLineBlank
float64 0
9.01k
| CountLineCode
float64 0
94.4k
| CountLineCodeDecl
float64 0
46.1k
| CountLineCodeExe
float64 0
91.3k
| CountLineComment
float64 0
27k
| CountStmt
float64 1
93.2k
| CountStmtDecl
float64 0
46.1k
| CountStmtExe
float64 0
90.2k
| MaxCyclomatic
float64 0
759
| MaxInheritanceTree
float64 0
16
| MaxNesting
float64 0
34
| SumCyclomatic
float64 0
6k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
700 |
255BITS/hyperchamber
|
255BITS_hyperchamber/hyperchamber/selector.py
|
hyperchamber.selector.Selector
|
class Selector:
def __init__(self, initialStore = {}):
self.store = initialStore
self.results = []
def set(self, key, value):
"""Sets a hyperparameter. Can be used to set an array of hyperparameters."""
self.store[key]=value
return self.store
def count_configs(self):
count = 1
for key in self.store:
value = self.store[key]
if(isinstance(value,list)):
count *= len(value)
return count
def get_config_value(self, k, i):
"""Gets the ith config value for k. e.g. get_config_value('x', 1)"""
if(not isinstance(self.store[k], list)):
return self.store[k]
else:
return self.store[k][i]
def configs(self, max_configs=1, offset=None, serial=False, create_uuid=True):
"""Generate max configs, each one a dictionary. e.g. [{'x': 1}]
Will also add a config UUID, useful for tracking configs.
You can turn this off by passing create_uuid=False.
"""
if len(self.store)==0:
return []
configs = []
if(offset is None):
offset = max(0, random.randint(0, self.count_configs()))
for i in range(max_configs):
# get an element to index over
config = self.config_at(offset)
if(create_uuid):
config["uuid"]=uuid.uuid4().hex
configs.append(config)
if(serial):
offset+=1
else:
offset = max(0, random.randint(0, self.count_configs()))
return configs
def config_at(self, i):
"""Gets the ith config"""
selections = {}
for key in self.store:
value = self.store[key]
if isinstance(value, list):
selected = i % len(value)
i = i // len(value)
selections[key]= value[selected]
else:
selections[key]= value
return Config(selections)
def random_config(self):
offset = max(0, random.randint(0, self.count_configs()))
return self.config_at(offset)
def reset(self):
"""Reset the hyperchamber variables"""
self.store = {}
self.results = []
return
def top(self, sort_by):
"""Get the best results according to your custom sort method."""
sort = sorted(self.results, key=sort_by)
return sort
def record(self, config, result):
"""Record the results of a config."""
self.results.append((config, result))
def load(self, filename, load_toml=False):
"""Loads a config from disk"""
content = open(filename)
if load_toml:
import toml
return Config(toml.load(content))
else:
return Config(json.load(content))
def load_or_create_config(self, filename, config=None):
"""Loads a config from disk. Defaults to a random config if none is specified"""
os.makedirs(os.path.dirname(os.path.expanduser(filename)), exist_ok=True)
if os.path.exists(filename):
return self.load(filename)
if(config == None):
config = self.random_config()
self.save(filename, config)
return config
def save(self, filename, config):
"""Loads a config from disk"""
return open(os.path.expanduser(filename), 'w').write(json.dumps(config, cls=HCEncoder, sort_keys=True, indent=2, separators=(',', ': ')))
|
class Selector:
def __init__(self, initialStore = {}):
pass
def set(self, key, value):
'''Sets a hyperparameter. Can be used to set an array of hyperparameters.'''
pass
def count_configs(self):
pass
def get_config_value(self, k, i):
'''Gets the ith config value for k. e.g. get_config_value('x', 1)'''
pass
def configs(self, max_configs=1, offset=None, serial=False, create_uuid=True):
'''Generate max configs, each one a dictionary. e.g. [{'x': 1}]
Will also add a config UUID, useful for tracking configs.
You can turn this off by passing create_uuid=False.
'''
pass
def config_at(self, i):
'''Gets the ith config'''
pass
def random_config(self):
pass
def reset(self):
'''Reset the hyperchamber variables'''
pass
def top(self, sort_by):
'''Get the best results according to your custom sort method.'''
pass
def record(self, config, result):
'''Record the results of a config.'''
pass
def load(self, filename, load_toml=False):
'''Loads a config from disk'''
pass
def load_or_create_config(self, filename, config=None):
'''Loads a config from disk. Defaults to a random config if none is specified'''
pass
def save(self, filename, config):
'''Loads a config from disk'''
pass
| 14 | 10 | 7 | 1 | 6 | 1 | 2 | 0.19 | 0 | 4 | 2 | 0 | 13 | 2 | 13 | 13 | 109 | 20 | 75 | 30 | 60 | 14 | 71 | 30 | 56 | 6 | 0 | 2 | 26 |
701 |
255BITS/hyperchamber
|
255BITS_hyperchamber/examples/shared/ops.py
|
shared.ops.batch_norm_cross
|
class batch_norm_cross(object):
def __init__(self, epsilon=1e-5, name="batch_norm"):
with tf.variable_scope(name) as scope:
self.epsilon = epsilon
self.name=name
def __call__(self, x):
shape = x.get_shape().as_list()
needs_reshape = len(shape) != 4
if needs_reshape:
orig_shape = shape
if len(shape) == 2:
x = tf.reshape(x, [shape[0], 1, 1, shape[1]])
elif len(shape) == 1:
x = tf.reshape(x, [shape[0], 1, 1, 1])
else:
assert False, shape
shape = x.get_shape().as_list()
with tf.variable_scope(self.name) as scope:
self.gamma0 = tf.get_variable("gamma0", [shape[-1] // 2],
initializer=tf.random_normal_initializer(1., 0.02))
self.beta0 = tf.get_variable("beta0", [shape[-1] // 2],
initializer=tf.constant_initializer(0.))
self.gamma1 = tf.get_variable("gamma1", [shape[-1] // 2],
initializer=tf.random_normal_initializer(1., 0.02))
self.beta1 = tf.get_variable("beta1", [shape[-1] // 2],
initializer=tf.constant_initializer(0.))
ch0 = tf.slice(x, [0, 0, 0, 0],
[shape[0], shape[1], shape[2], shape[3] // 2])
ch1 = tf.slice(x, [0, 0, 0, shape[3] // 2],
[shape[0], shape[1], shape[2], shape[3] // 2])
ch0b0 = tf.slice(ch0, [0, 0, 0, 0],
[shape[0] // 2, shape[1], shape[2], shape[3] // 2])
ch1b1 = tf.slice(ch1, [shape[0] // 2, 0, 0, 0],
[shape[0] // 2, shape[1], shape[2], shape[3] // 2])
ch0_mean, ch0_variance = tf.nn.moments(ch0b0, [0, 1, 2])
ch1_mean, ch1_variance = tf.nn.moments(ch1b1, [0, 1, 2])
ch0 = tf.nn.batch_norm_with_global_normalization(
ch0, ch0_mean, ch0_variance, self.beta0, self.gamma0, self.epsilon,
scale_after_normalization=True)
ch1 = tf.nn.batch_norm_with_global_normalization(
ch1, ch1_mean, ch1_variance, self.beta1, self.gamma1, self.epsilon,
scale_after_normalization=True)
out = tf.concat(3, [ch0, ch1])
if needs_reshape:
out = tf.reshape(out, orig_shape)
return out
|
class batch_norm_cross(object):
def __init__(self, epsilon=1e-5, name="batch_norm"):
pass
def __call__(self, x):
pass
| 3 | 0 | 29 | 7 | 23 | 0 | 3 | 0 | 1 | 0 | 0 | 0 | 2 | 6 | 2 | 2 | 60 | 14 | 46 | 21 | 43 | 0 | 32 | 19 | 29 | 5 | 1 | 2 | 6 |
702 |
255BITS/hyperchamber
|
255BITS_hyperchamber/hyperchamber/io/__init__.py
|
hyperchamber.io.MissingHCKeyException
|
class MissingHCKeyException(Exception):
pass
|
class MissingHCKeyException(Exception):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 3 | 0 | 0 |
703 |
255BITS/hyperchamber
|
255BITS_hyperchamber/examples/shared/ops.py
|
shared.ops.batch_norm_first_half
|
class batch_norm_first_half(object):
"""Code modification of http://stackoverflow.com/a/33950177
"""
def __init__(self, epsilon=1e-5, name="batch_norm"):
with tf.variable_scope(name) as scope:
self.epsilon = epsilon
self.name=name
def __call__(self, x):
shape = x.get_shape().as_list()
needs_reshape = len(shape) != 4
if needs_reshape:
orig_shape = shape
if len(shape) == 2:
x = tf.reshape(x, [shape[0], 1, 1, shape[1]])
elif len(shape) == 1:
x = tf.reshape(x, [shape[0], 1, 1, 1])
else:
assert False, shape
shape = x.get_shape().as_list()
with tf.variable_scope(self.name) as scope:
self.gamma = tf.get_variable("gamma", [shape[-1]],
initializer=tf.random_normal_initializer(1., 0.02))
self.beta = tf.get_variable("beta", [shape[-1]],
initializer=tf.constant_initializer(0.))
first_half = tf.slice(x, [0, 0, 0, 0],
[shape[0] // 2, shape[1], shape[2], shape[3]])
self.mean, self.variance = tf.nn.moments(first_half, [0, 1, 2])
out = tf.nn.batch_norm_with_global_normalization(
x, self.mean, self.variance, self.beta, self.gamma, self.epsilon,
scale_after_normalization=True)
if needs_reshape:
out = tf.reshape(out, orig_shape)
return out
|
class batch_norm_first_half(object):
'''Code modification of http://stackoverflow.com/a/33950177
'''
def __init__(self, epsilon=1e-5, name="batch_norm"):
pass
def __call__(self, x):
pass
| 3 | 1 | 19 | 4 | 15 | 0 | 3 | 0.06 | 1 | 0 | 0 | 0 | 2 | 6 | 2 | 2 | 42 | 9 | 31 | 15 | 28 | 2 | 24 | 13 | 21 | 5 | 1 | 2 | 6 |
704 |
255BITS/hyperchamber
|
255BITS_hyperchamber/examples/shared/ops.py
|
shared.ops.batch_norm_second_half
|
class batch_norm_second_half(object):
"""Code modification of http://stackoverflow.com/a/33950177
"""
def __init__(self, epsilon=1e-5, name="batch_norm"):
with tf.variable_scope(name) as scope:
self.epsilon = epsilon
self.name=name
def __call__(self, x):
shape = x.get_shape().as_list()
needs_reshape = len(shape) != 4
if needs_reshape:
orig_shape = shape
if len(shape) == 2:
x = tf.reshape(x, [shape[0], 1, 1, shape[1]])
elif len(shape) == 1:
x = tf.reshape(x, [shape[0], 1, 1, 1])
else:
assert False, shape
shape = x.get_shape().as_list()
with tf.variable_scope(self.name) as scope:
self.gamma = tf.get_variable("gamma", [shape[-1]],
initializer=tf.random_normal_initializer(1., 0.02))
self.beta = tf.get_variable("beta", [shape[-1]],
initializer=tf.constant_initializer(0.))
second_half = tf.slice(x, [shape[0] // 2, 0, 0, 0],
[shape[0] // 2, shape[1], shape[2], shape[3]])
self.mean, self.variance = tf.nn.moments(second_half, [0, 1, 2])
out = tf.nn.batch_norm_with_global_normalization(
x, self.mean, self.variance, self.beta, self.gamma, self.epsilon,
scale_after_normalization=True)
if needs_reshape:
out = tf.reshape(out, orig_shape)
return out
|
class batch_norm_second_half(object):
'''Code modification of http://stackoverflow.com/a/33950177
'''
def __init__(self, epsilon=1e-5, name="batch_norm"):
pass
def __call__(self, x):
pass
| 3 | 1 | 19 | 4 | 15 | 0 | 3 | 0.06 | 1 | 0 | 0 | 0 | 2 | 6 | 2 | 2 | 42 | 9 | 31 | 15 | 28 | 2 | 24 | 13 | 21 | 5 | 1 | 2 | 6 |
705 |
255BITS/hyperchamber
|
255BITS_hyperchamber/examples/shared/ops.py
|
shared.ops.conv_batch_norm
|
class conv_batch_norm(object):
"""Code modification of http://stackoverflow.com/a/33950177"""
def __init__(self, name="batch_norm", epsilon=1e-5, momentum=0.1,
in_dim=None):
with tf.variable_scope(name) as scope:
self.epsilon = epsilon
self.momentum = momentum
self.name = name
self.in_dim = in_dim
global TRAIN_MODE
self.train = TRAIN_MODE
self.ema = tf.train.ExponentialMovingAverage(decay=0.9)
print("initing %s in train: %s" % (scope.name, self.train))
def __call__(self, x):
shape = x.get_shape()
shp = self.in_dim or shape[-1]
with tf.variable_scope(self.name) as scope:
self.gamma = tf.get_variable("gamma", [shp],
initializer=tf.random_normal_initializer(1., 0.02))
self.beta = tf.get_variable("beta", [shp],
initializer=tf.constant_initializer(0.))
self.mean, self.variance = tf.nn.moments(x, [0, 1, 2])
self.mean.set_shape((shp,))
self.variance.set_shape((shp,))
self.ema_apply_op = self.ema.apply([self.mean, self.variance])
if self.train:
# with tf.control_dependencies([self.ema_apply_op]):
normalized_x = tf.nn.batch_norm_with_global_normalization(
x, self.mean, self.variance, self.beta, self.gamma, self.epsilon,
scale_after_normalization=True)
else:
normalized_x = tf.nn.batch_norm_with_global_normalization(
x, self.ema.average(self.mean), self.ema.average(self.variance), self.beta,
self.gamma, self.epsilon,
scale_after_normalization=True)
return normalized_x
|
class conv_batch_norm(object):
'''Code modification of http://stackoverflow.com/a/33950177'''
def __init__(self, name="batch_norm", epsilon=1e-5, momentum=0.1,
in_dim=None):
pass
def __call__(self, x):
pass
| 3 | 1 | 18 | 1 | 17 | 1 | 2 | 0.06 | 1 | 0 | 0 | 1 | 2 | 11 | 2 | 2 | 39 | 3 | 34 | 20 | 29 | 2 | 25 | 17 | 21 | 2 | 1 | 2 | 3 |
706 |
255BITS/hyperchamber
|
255BITS_hyperchamber/examples/shared/ops.py
|
shared.ops.fc_batch_norm
|
class fc_batch_norm(conv_batch_norm):
def __call__(self, fc_x):
ori_shape = fc_x.get_shape().as_list()
if ori_shape[0] is None:
ori_shape[0] = -1
new_shape = [ori_shape[0], 1, 1, ori_shape[1]]
x = tf.reshape(fc_x, new_shape)
normalized_x = super(fc_batch_norm, self).__call__(x)
return tf.reshape(normalized_x, ori_shape)
|
class fc_batch_norm(conv_batch_norm):
def __call__(self, fc_x):
pass
| 2 | 0 | 8 | 0 | 8 | 0 | 2 | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 3 | 9 | 0 | 9 | 6 | 7 | 0 | 9 | 6 | 7 | 2 | 2 | 1 | 2 |
707 |
255BITS/hyperchamber
|
255BITS_hyperchamber/examples/shared/variational_autoencoder.py
|
shared.variational_autoencoder.VariationalAutoencoder
|
class VariationalAutoencoder(object):
""" Variation Autoencoder (VAE) with an sklearn-like interface implemented using TensorFlow.
This implementation uses probabilistic encoders and decoders using Gaussian
distributions and realized by multi-layer perceptrons. The VAE can be learned
end-to-end.
See "Auto-Encoding Variational Bayes" by Kingma and Welling for more details.
"""
def __init__(self, network_architecture, transfer_fct=tf.nn.softplus,
learning_rate=0.001, batch_size=100):
self.network_architecture = network_architecture
self.transfer_fct = transfer_fct
self.learning_rate = learning_rate
self.batch_size = batch_size
# tf Graph input
self.x = tf.placeholder(tf.float32, [None, network_architecture["n_input"]])
# Create autoencoder network
self._create_network()
# Define loss function based variational upper-bound and
# corresponding optimizer
self._create_loss_optimizer()
# Initializing the tensor flow variables
init = tf.initialize_all_variables()
# Launch the session
self.sess = tf.InteractiveSession()
self.sess.run(init)
def _create_network(self):
# Initialize autoencode network weights and biases
network_weights = self._initialize_weights(**self.network_architecture)
# Use recognition network to determine mean and
# (log) variance of Gaussian distribution in latent
# space
self.z_mean, self.z_log_sigma_sq = \
self._recognition_network(network_weights["weights_recog"],
network_weights["biases_recog"])
# Draw one sample z from Gaussian distribution
n_z = self.network_architecture["n_z"]
eps = tf.random_normal((self.batch_size, n_z), 0, 1,
dtype=tf.float32)
# z = mu + sigma*epsilon
self.z = tf.add(self.z_mean,
tf.mul(tf.sqrt(tf.exp(self.z_log_sigma_sq)), eps))
# Use generator to determine mean of
# Bernoulli distribution of reconstructed input
self.x_reconstr_mean = \
self._generator_network(network_weights["weights_gener"],
network_weights["biases_gener"])
def _initialize_weights(self, n_hidden_recog_1, n_hidden_recog_2,
n_hidden_gener_1, n_hidden_gener_2,
n_input, n_z, **extra):
all_weights = dict()
all_weights['weights_recog'] = {
'h1': tf.Variable(xavier_init(n_input, n_hidden_recog_1)),
'h2': tf.Variable(xavier_init(n_hidden_recog_1, n_hidden_recog_2)),
'out_mean': tf.Variable(xavier_init(n_hidden_recog_2, n_z)),
'out_log_sigma': tf.Variable(xavier_init(n_hidden_recog_2, n_z))}
all_weights['biases_recog'] = {
'b1': tf.Variable(tf.zeros([n_hidden_recog_1], dtype=tf.float32)),
'b2': tf.Variable(tf.zeros([n_hidden_recog_2], dtype=tf.float32)),
'out_mean': tf.Variable(tf.zeros([n_z], dtype=tf.float32)),
'out_log_sigma': tf.Variable(tf.zeros([n_z], dtype=tf.float32))}
all_weights['weights_gener'] = {
'h1': tf.Variable(xavier_init(n_z, n_hidden_gener_1)),
'h2': tf.Variable(xavier_init(n_hidden_gener_1, n_hidden_gener_2)),
'out_mean': tf.Variable(xavier_init(n_hidden_gener_2, n_input)),
'out_log_sigma': tf.Variable(xavier_init(n_hidden_gener_2, n_input))}
all_weights['biases_gener'] = {
'b1': tf.Variable(tf.zeros([n_hidden_gener_1], dtype=tf.float32)),
'b2': tf.Variable(tf.zeros([n_hidden_gener_2], dtype=tf.float32)),
'out_mean': tf.Variable(tf.zeros([n_input], dtype=tf.float32)),
'out_log_sigma': tf.Variable(tf.zeros([n_input], dtype=tf.float32))}
return all_weights
def _recognition_network(self, weights, biases):
# Generate probabilistic encoder (recognition network), which
# maps inputs onto a normal distribution in latent space.
# The transformation is parametrized and can be learned.
layer_1 = self.transfer_fct(tf.add(tf.matmul(self.x, weights['h1']),
biases['b1']))
layer_2 = self.transfer_fct(tf.add(tf.matmul(layer_1, weights['h2']),
biases['b2']))
z_mean = tf.add(tf.matmul(layer_2, weights['out_mean']),
biases['out_mean'])
z_log_sigma_sq = \
tf.add(tf.matmul(layer_2, weights['out_log_sigma']),
biases['out_log_sigma'])
return (z_mean, z_log_sigma_sq)
def _generator_network(self, weights, biases):
# Generate probabilistic decoder (decoder network), which
# maps points in latent space onto a Bernoulli distribution in data space.
# The transformation is parametrized and can be learned.
layer_1 = self.transfer_fct(tf.add(tf.matmul(self.z, weights['h1']),
biases['b1']))
layer_2 = self.transfer_fct(tf.add(tf.matmul(layer_1, weights['h2']),
biases['b2']))
x_reconstr_mean = \
tf.nn.sigmoid(tf.add(tf.matmul(layer_2, weights['out_mean']),
biases['out_mean']))
return x_reconstr_mean
def _create_loss_optimizer(self):
# The loss is composed of two terms:
# 1.) The reconstruction loss (the negative log probability
# of the input under the reconstructed Bernoulli distribution
# induced by the decoder in the data space).
# This can be interpreted as the number of "nats" required
# for reconstructing the input when the activation in latent
# is given.
# Adding 1e-10 to avoid evaluatio of log(0.0)
reconstr_loss = \
-tf.reduce_sum(self.x * tf.log(1e-10 + self.x_reconstr_mean)
+ (1-self.x) * tf.log(1e-10 + 1 - self.x_reconstr_mean),
1)
# 2.) The latent loss, which is defined as the Kullback Leibler divergence
## between the distribution in latent space induced by the encoder on
# the data and some prior. This acts as a kind of regularizer.
# This can be interpreted as the number of "nats" required
# for transmitting the the latent space distribution given
# the prior.
latent_loss = -0.5 * tf.reduce_sum(1 + self.z_log_sigma_sq
- tf.square(self.z_mean)
- tf.exp(self.z_log_sigma_sq), 1)
self.cost = tf.reduce_mean(reconstr_loss + latent_loss) # average over batch
# Use ADAM optimizer
self.optimizer = \
tf.train.AdamOptimizer(learning_rate=self.learning_rate).minimize(self.cost)
def partial_fit(self, X):
"""Train model based on mini-batch of input data.
Return cost of mini-batch.
"""
opt, cost = self.sess.run((self.optimizer, self.cost),
feed_dict={self.x: X})
return cost
def transform(self, X):
"""Transform data by mapping it into the latent space."""
# Note: This maps to mean of distribution, we could alternatively
# sample from Gaussian distribution
return self.sess.run(self.z_mean, feed_dict={self.x: X})
def generate(self, z_mu=None):
""" Generate data by sampling from latent space.
If z_mu is not None, data for this point in latent space is
generated. Otherwise, z_mu is drawn from prior in latent
space.
"""
if z_mu is None:
z_mu = np.random.normal(size=self.network_architecture["n_z"])
# Note: This maps to mean of distribution, we could alternatively
# sample from Gaussian distribution
return self.sess.run(self.x_reconstr_mean,
feed_dict={self.z: z_mu})
def reconstruct(self, X):
""" Use VAE to reconstruct given data. """
return self.sess.run(self.x_reconstr_mean,
feed_dict={self.x: X})
|
class VariationalAutoencoder(object):
''' Variation Autoencoder (VAE) with an sklearn-like interface implemented using TensorFlow.
This implementation uses probabilistic encoders and decoders using Gaussian
distributions and realized by multi-layer perceptrons. The VAE can be learned
end-to-end.
See "Auto-Encoding Variational Bayes" by Kingma and Welling for more details.
'''
def __init__(self, network_architecture, transfer_fct=tf.nn.softplus,
learning_rate=0.001, batch_size=100):
pass
def _create_network(self):
pass
def _initialize_weights(self, n_hidden_recog_1, n_hidden_recog_2,
n_hidden_gener_1, n_hidden_gener_2,
n_input, n_z, **extra):
pass
def _recognition_network(self, weights, biases):
pass
def _generator_network(self, weights, biases):
pass
def _create_loss_optimizer(self):
pass
def partial_fit(self, X):
'''Train model based on mini-batch of input data.
Return cost of mini-batch.
'''
pass
def transform(self, X):
'''Transform data by mapping it into the latent space.'''
pass
def generate(self, z_mu=None):
''' Generate data by sampling from latent space.
If z_mu is not None, data for this point in latent space is
generated. Otherwise, z_mu is drawn from prior in latent
space.
'''
pass
def reconstruct(self, X):
''' Use VAE to reconstruct given data. '''
pass
| 11 | 5 | 15 | 1 | 10 | 5 | 1 | 0.58 | 1 | 1 | 0 | 0 | 10 | 12 | 10 | 10 | 171 | 20 | 96 | 40 | 82 | 56 | 53 | 37 | 42 | 2 | 1 | 1 | 11 |
708 |
255BITS/hyperchamber
|
255BITS_hyperchamber/tests/test_hyperchamber.py
|
test_hyperchamber.hyperchamber_test
|
class hyperchamber_test(unittest.TestCase):
def test_set(self):
hc.reset()
hc.set('x', [1])
self.assertEqual(hc.configs(1, offset=0, serial=True,create_uuid=False), [{'x':1}])
def test_set2(self):
hc.reset()
hc.set('x', [1,2])
self.assertEqual(hc.configs(2, offset=0, serial=True,create_uuid=False), [{'x':1},{'x':2}])
def test_Config_accessor(self):
hc.reset()
hc.set('x', [1])
config = hc.configs(1, offset=0, serial=True,create_uuid=False)[0]
self.assertEqual(config.x, 1)
self.assertEqual(config.y, None)
def test_createUUID(self):
hc.reset()
hc.set('x', [1])
self.assertTrue(len(hc.configs(1)[0]["uuid"]) > 1)
def test_pagination(self):
hc.reset()
hc.set('x', [1,2])
self.assertEqual(hc.configs(1, create_uuid=False, serial=True,offset=0), [{'x':1}])
self.assertEqual(hc.configs(1, create_uuid=False, serial=True,offset=1), [{'x':2}])
self.assertEqual(hc.configs(1, create_uuid=False, serial=True,offset=2), [{'x':1}])
def test_constant_set(self):
hc.reset()
hc.set('x', 1)
hc.set('y', [2,3])
self.assertEqual(hc.configs(1, create_uuid=False,serial=True, offset=0), [{'x':1, 'y':2}])
print("--")
self.assertEqual(hc.configs(1, create_uuid=False, serial=True,offset=1), [{'x':1, 'y':3}])
self.assertEqual(hc.configs(1, create_uuid=False,serial=True, offset=2), [{'x':1, 'y':2}])
def test_set2_2vars(self):
hc.reset()
hc.set('x', [1])
hc.set('y', [3,4])
self.assertEqual(hc.configs(2, create_uuid=False, serial=True,offset=0), [{'x':1,'y':3},{'x':1,'y':4}])
def test_configs(self):
hc.reset()
self.assertEqual(hc.configs(create_uuid=False), [])
def test_record(self):
hc.reset()
def do_nothing(x):
return 0
self.assertEqual(hc.top(sort_by=do_nothing), [])
config = {'a':1}
result = {'b':2}
hc.record(config, result)
self.assertEqual(hc.top(sort_by=do_nothing)[0], (config, result))
def test_reset(self):
hc.reset()
self.assertEqual(hc.configs(), [])
self.assertEqual(hc.count_configs(), 1)
def test_store_size(self):
hc.reset()
hc.set('x', [1,2])
self.assertEqual(hc.count_configs(), 2)
def test_top(self):
hc.reset()
for i in range(10):
config = {"i": i}
result = {"cost": 10-i}
hc.record(config, result)
def by_cost(x):
config,result = x
return result['cost']
self.assertEqual(hc.top(sort_by=by_cost)[0], ({'i': 9}, {'cost': 1}))
|
class hyperchamber_test(unittest.TestCase):
def test_set(self):
pass
def test_set2(self):
pass
def test_Config_accessor(self):
pass
def test_createUUID(self):
pass
def test_pagination(self):
pass
def test_constant_set(self):
pass
def test_set2_2vars(self):
pass
def test_configs(self):
pass
def test_record(self):
pass
def do_nothing(x):
pass
def test_reset(self):
pass
def test_store_size(self):
pass
def test_top(self):
pass
def by_cost(x):
pass
| 15 | 0 | 5 | 0 | 5 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 12 | 0 | 12 | 84 | 83 | 15 | 68 | 22 | 53 | 0 | 68 | 22 | 53 | 2 | 2 | 1 | 15 |
709 |
255BITS/hyperchamber
|
255BITS_hyperchamber/tests/test_permute.py
|
test_permute.permute_test
|
class permute_test(unittest.TestCase):
def test_one_permute(self):
hc.reset()
hc.set('x', 1)
hc.set('y', [1])
self.assertEqual(hc.count_configs(), 1)
self.assertEqual(hc.configs(1, serial=True,offset=0,create_uuid=False), [{'x':1, 'y': 1}])
def test_many_permute(self):
hc.reset()
hc.set('x', 1)
hc.set('y', [1, 2, 2])
self.assertEqual(hc.count_configs(), 3)
self.assertEqual(hc.configs(1, serial=True,offset=0,create_uuid=False), [{'x':1, 'y': 1}])
def test_many_to_many(self):
hc.reset()
hc.set('x', [1,2,3])
hc.set('y', [1, 2, 3])
self.assertEqual(hc.count_configs(), 9)
configs = hc.configs(3, serial=True,create_uuid=False,offset=0)
self.assertNotEqual(configs[0], configs[1])
self.assertNotEqual(configs[1], configs[2])
def test_many_to_many_nested(self):
hc.reset()
hc.set('x', [1, 2, 3])
hc.set('y', [1, 2, 3])
hc.set('z', [1, 2, 3])
self.assertEqual(hc.count_configs(), 27)
self.assertEqual(hc.configs(1, serial=True,offset=0,create_uuid=False), [{'x':1, 'y': 1, 'z': 1}])
# TODO: These results are not in a guaranteed order since store is a dictionary.
# These tests dont pass reliable
#self.assertEqual(hc.configs(1,offset=1), [{'x':1, 'y': 1, 'z': 2}])
#self.assertEqual(hc.configs(1,offset=5), [{'x':1, 'y': 1, 'z': 2}])
def test_only_permutation(self):
hc.reset()
for i in range(20):
hc.set('a'+str(i), [1, 2, 3])
self.assertEqual(hc.count_configs(), 3**20)
self.assertEqual(hc.configs(1, serial=True, offset=0)[0]['a1'], 1)
self.assertEqual(hc.configs(1, serial=True, offset=0)[0]['a2'], 1)
|
class permute_test(unittest.TestCase):
def test_one_permute(self):
pass
def test_many_permute(self):
pass
def test_many_to_many(self):
pass
def test_many_to_many_nested(self):
pass
def test_only_permutation(self):
pass
| 6 | 0 | 7 | 0 | 7 | 0 | 1 | 0.11 | 1 | 2 | 0 | 0 | 5 | 0 | 5 | 77 | 44 | 5 | 35 | 8 | 29 | 4 | 35 | 8 | 29 | 2 | 2 | 1 | 6 |
710 |
255BITS/hyperchamber
|
255BITS_hyperchamber/hyperchamber/config.py
|
hyperchamber.config.Config
|
class Config(dict):
def __init__(self, *args, **kwargs):
super(Config, self).__init__(*args, **kwargs)
for arg in args:
if isinstance(arg, dict):
for k, v in arg.items():
self[k] = v
if kwargs:
for k, v in kwargs.items():
self[k] = v
def __getattr__(self, attr):
if attr in self:
return self.get(attr)
return None
def __setattr__(self, key, value):
self.__setitem__(key, value)
def __setitem__(self, key, value):
super(Config, self).__setitem__(key, value)
self.__dict__.update({key: value})
def __delattr__(self, item):
self.__delitem__(item)
def __delitem__(self, key):
super(Config, self).__delitem__(key)
del self.__dict__[key]
def __getstate__(self):
return dict(self)
def __setstate__(self, d):
self.__dict__ = d
|
class Config(dict):
def __init__(self, *args, **kwargs):
pass
def __getattr__(self, attr):
pass
def __setattr__(self, key, value):
pass
def __setitem__(self, key, value):
pass
def __delattr__(self, item):
pass
def __delitem__(self, key):
pass
def __getstate__(self):
pass
def __setstate__(self, d):
pass
| 9 | 0 | 4 | 0 | 3 | 0 | 2 | 0 | 1 | 1 | 0 | 0 | 8 | 1 | 8 | 35 | 36 | 8 | 28 | 12 | 19 | 0 | 28 | 12 | 19 | 6 | 2 | 3 | 14 |
711 |
255BITS/hyperchamber
|
255BITS_hyperchamber/hyperchamber/selector.py
|
hyperchamber.selector.HCEncoder
|
class HCEncoder(JSONEncoder):
def default(self, o):
if(hasattr(o, '__call__')): # is function
return "function:" +o.__module__+"."+o.__name__
else:
try:
return o.__dict__
except AttributeError:
try:
return str(o)
except AttributeError:
return super(o)
|
class HCEncoder(JSONEncoder):
def default(self, o):
pass
| 2 | 0 | 11 | 0 | 11 | 1 | 4 | 0.08 | 1 | 3 | 0 | 0 | 1 | 0 | 1 | 5 | 12 | 0 | 12 | 2 | 10 | 1 | 11 | 2 | 9 | 4 | 2 | 3 | 4 |
712 |
255BITS/hyperchamber
|
255BITS_hyperchamber/examples/shared/ops.py
|
shared.ops.batch_norm
|
class batch_norm(object):
"""Code modification of http://stackoverflow.com/a/33950177
"""
def __init__(self, batch_size, epsilon=1e-5, momentum = 0.1, name="batch_norm", half=None):
assert half is None
del momentum # unused
with tf.variable_scope(name) as scope:
self.epsilon = epsilon
self.batch_size = batch_size
self.name=name
def __call__(self, x, train=True):
del train # unused
shape = x.get_shape().as_list()
needs_reshape = len(shape) != 4
if needs_reshape:
orig_shape = shape
if len(shape) == 2:
x = tf.reshape(x, [shape[0], 1, 1, shape[1]])
elif len(shape) == 1:
x = tf.reshape(x, [shape[0], 1, 1, 1])
else:
assert False, shape
shape = x.get_shape().as_list()
with tf.variable_scope(self.name) as scope:
self.gamma = tf.get_variable("gamma", [shape[-1]],
initializer=tf.random_normal_initializer(1., 0.02))
self.beta = tf.get_variable("beta", [shape[-1]],
initializer=tf.constant_initializer(0.))
self.mean, self.variance = tf.nn.moments(x, [0, 1, 2])
out = tf.nn.batch_norm_with_global_normalization(
x, self.mean, self.variance, self.beta, self.gamma, self.epsilon,
scale_after_normalization=True)
if needs_reshape:
out = tf.reshape(out, orig_shape)
return out
|
class batch_norm(object):
'''Code modification of http://stackoverflow.com/a/33950177
'''
def __init__(self, batch_size, epsilon=1e-5, momentum = 0.1, name="batch_norm", half=None):
pass
def __call__(self, x, train=True):
pass
| 3 | 1 | 19 | 3 | 16 | 1 | 3 | 0.12 | 1 | 0 | 0 | 0 | 2 | 7 | 2 | 2 | 43 | 8 | 33 | 15 | 30 | 4 | 27 | 13 | 24 | 5 | 1 | 2 | 6 |
713 |
317070/python-twitch-stream
|
317070_python-twitch-stream/twitchstream/chat.py
|
twitchstream.chat.TwitchChatStream
|
class TwitchChatStream(object):
"""
The TwitchChatStream is used for interfacing with the Twitch chat of
a channel. To use this, an oauth-account (of the user chatting)
should be created. At the moment of writing, this can be done here:
https://twitchapps.com/tmi/
:param username: Twitch username
:type username: string
:param oauth: oauth for logging in (see https://twitchapps.com/tmi/)
:type oauth: string
:param verbose: show all stream messages on stdout (for debugging)
:type verbose: boolean
"""
def __init__(self, username, oauth, verbose=False):
"""Create a new stream object, and try to connect."""
self.username = username
self.oauth = oauth
self.verbose = verbose
self.current_channel = ""
self.last_sent_time = time.time()
self.buffer = []
self.s = None
def __enter__(self):
self.connect()
return self
def __exit__(self, type, value, traceback):
self.s.close()
@staticmethod
def _logged_in_successful(data):
"""
Test the login status from the returned communication of the
server.
:param data: bytes received from server during login
:type data: list of bytes
:return boolean, True when you are logged in.
"""
if re.match(r'^:(testserver\.local|tmi\.twitch\.tv)'
r' NOTICE \* :'
r'(Login unsuccessful|Error logging in)*$',
data.strip()):
return False
else:
return True
@staticmethod
def _check_has_ping(data):
"""
Check if the data from the server contains a request to ping.
:param data: the byte string from the server
:type data: list of bytes
:return: True when there is a request to ping, False otherwise
"""
return re.match(
r'^PING :tmi\.twitch\.tv$', data)
@staticmethod
def _check_has_channel(data):
"""
Check if the data from the server contains a channel switch.
:param data: the byte string from the server
:type data: list of bytes
:return: Name of channel when new channel, False otherwise
"""
return re.findall(
r'^:[a-zA-Z0-9_]+\![a-zA-Z0-9_]+@[a-zA-Z0-9_]+'
r'\.tmi\.twitch\.tv '
r'JOIN #([a-zA-Z0-9_]+)$', data)
@staticmethod
def _check_has_message(data):
"""
Check if the data from the server contains a message a user
typed in the chat.
:param data: the byte string from the server
:type data: list of bytes
:return: returns iterator over these messages
"""
return re.match(r'^:[a-zA-Z0-9_]+\![a-zA-Z0-9_]+@[a-zA-Z0-9_]+'
r'\.tmi\.twitch\.tv '
r'PRIVMSG #[a-zA-Z0-9_]+ :.+$', data)
def connect(self):
"""
Connect to Twitch
"""
# Do not use non-blocking stream, they are not reliably
# non-blocking
# s.setblocking(False)
# s.settimeout(1.0)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connect_host = "irc.twitch.tv"
connect_port = 6667
try:
s.connect((connect_host, connect_port))
except (Exception, IOError):
print("Unable to create a socket to %s:%s" % (
connect_host,
connect_port))
raise # unexpected, because it is a blocking socket
# Connected to twitch
# Sending our details to twitch...
s.send(('PASS %s\r\n' % self.oauth).encode('utf-8'))
s.send(('NICK %s\r\n' % self.username).encode('utf-8'))
if self.verbose:
print('PASS %s\r\n' % self.oauth)
print('NICK %s\r\n' % self.username)
received = s.recv(1024).decode()
if self.verbose:
print(received)
if not TwitchChatStream._logged_in_successful(received):
# ... and they didn't accept our details
raise IOError("Twitch did not accept the username-oauth "
"combination")
else:
# ... and they accepted our details
# Connected to twitch.tv!
# now make this socket non-blocking on the OS-level
fcntl.fcntl(s, fcntl.F_SETFL, os.O_NONBLOCK)
if self.s is not None:
self.s.close() # close the previous socket
self.s = s # store the new socket
self.join_channel(self.username)
# Wait until we have switched channels
while self.current_channel != self.username:
self.twitch_receive_messages()
def _push_from_buffer(self):
"""
Push a message on the stack to the IRC stream.
This is necessary to avoid Twitch overflow control.
"""
if len(self.buffer) > 0:
if time.time() - self.last_sent_time > 5:
try:
message = self.buffer.pop(0)
self.s.send(message.encode('utf-8'))
if self.verbose:
print(message)
finally:
self.last_sent_time = time.time()
def _send(self, message):
"""
Send a message to the IRC stream
:param message: the message to be sent.
:type message: string
"""
if len(message) > 0:
self.buffer.append(message + "\n")
def _send_pong(self):
"""
Send a pong message, usually in reply to a received ping message
"""
self._send("PONG")
def join_channel(self, channel):
"""
Join a different chat channel on Twitch.
Note, this function returns immediately, but the switch might
take a moment
:param channel: name of the channel (without #)
"""
self.s.send(('JOIN #%s\r\n' % channel).encode('utf-8'))
if self.verbose:
print('JOIN #%s\r\n' % channel)
def send_chat_message(self, message):
"""
Send a chat message to the server.
:param message: String to send (don't use \\n)
"""
self._send("PRIVMSG #{0} :{1}".format(self.username, message))
def _parse_message(self, data):
"""
Parse the bytes received from the socket.
:param data: the bytes received from the socket
:return:
"""
if TwitchChatStream._check_has_ping(data):
self._send_pong()
if TwitchChatStream._check_has_channel(data):
self.current_channel = \
TwitchChatStream._check_has_channel(data)[0]
if TwitchChatStream._check_has_message(data):
return {
'channel': re.findall(r'^:.+![a-zA-Z0-9_]+'
r'@[a-zA-Z0-9_]+'
r'.+ '
r'PRIVMSG (.*?) :',
data)[0],
'username': re.findall(r'^:([a-zA-Z0-9_]+)!', data)[0],
'message': re.findall(r'PRIVMSG #[a-zA-Z0-9_]+ :(.+)',
data)[0]
}
else:
return None
def twitch_receive_messages(self):
"""
Call this function to process everything received by the socket
This needs to be called frequently enough (~10s) Twitch logs off
users not replying to ping commands.
:return: list of chat messages received. Each message is a dict
with the keys ['channel', 'username', 'message']
"""
self._push_from_buffer()
result = []
while True:
# process the complete buffer, until no data is left no more
try:
msg = self.s.recv(4096).decode() # NON-BLOCKING RECEIVE!
except socket.error as e:
err = e.args[0]
if err == errno.EAGAIN or err == errno.EWOULDBLOCK:
# There is no more data available to read
return result
else:
# a "real" error occurred
# import traceback
# import sys
# print(traceback.format_exc())
# print("Trying to recover...")
self.connect()
return result
else:
if self.verbose:
print(msg)
rec = [self._parse_message(line)
for line in filter(None, msg.split('\r\n'))]
rec = [r for r in rec if r] # remove Nones
result.extend(rec)
|
class TwitchChatStream(object):
'''
The TwitchChatStream is used for interfacing with the Twitch chat of
a channel. To use this, an oauth-account (of the user chatting)
should be created. At the moment of writing, this can be done here:
https://twitchapps.com/tmi/
:param username: Twitch username
:type username: string
:param oauth: oauth for logging in (see https://twitchapps.com/tmi/)
:type oauth: string
:param verbose: show all stream messages on stdout (for debugging)
:type verbose: boolean
'''
def __init__(self, username, oauth, verbose=False):
'''Create a new stream object, and try to connect.'''
pass
def __enter__(self):
pass
def __exit__(self, type, value, traceback):
pass
@staticmethod
def _logged_in_successful(data):
'''
Test the login status from the returned communication of the
server.
:param data: bytes received from server during login
:type data: list of bytes
:return boolean, True when you are logged in.
'''
pass
@staticmethod
def _check_has_ping(data):
'''
Check if the data from the server contains a request to ping.
:param data: the byte string from the server
:type data: list of bytes
:return: True when there is a request to ping, False otherwise
'''
pass
@staticmethod
def _check_has_channel(data):
'''
Check if the data from the server contains a channel switch.
:param data: the byte string from the server
:type data: list of bytes
:return: Name of channel when new channel, False otherwise
'''
pass
@staticmethod
def _check_has_message(data):
'''
Check if the data from the server contains a message a user
typed in the chat.
:param data: the byte string from the server
:type data: list of bytes
:return: returns iterator over these messages
'''
pass
def connect(self):
'''
Connect to Twitch
'''
pass
def _push_from_buffer(self):
'''
Push a message on the stack to the IRC stream.
This is necessary to avoid Twitch overflow control.
'''
pass
def _send(self, message):
'''
Send a message to the IRC stream
:param message: the message to be sent.
:type message: string
'''
pass
def _send_pong(self):
'''
Send a pong message, usually in reply to a received ping message
'''
pass
def join_channel(self, channel):
'''
Join a different chat channel on Twitch.
Note, this function returns immediately, but the switch might
take a moment
:param channel: name of the channel (without #)
'''
pass
def send_chat_message(self, message):
'''
Send a chat message to the server.
:param message: String to send (don't use \n)
'''
pass
def _parse_message(self, data):
'''
Parse the bytes received from the socket.
:param data: the bytes received from the socket
:return:
'''
pass
def twitch_receive_messages(self):
'''
Call this function to process everything received by the socket
This needs to be called frequently enough (~10s) Twitch logs off
users not replying to ping commands.
:return: list of chat messages received. Each message is a dict
with the keys ['channel', 'username', 'message']
'''
pass
| 20 | 14 | 15 | 1 | 8 | 6 | 2 | 0.82 | 1 | 3 | 0 | 0 | 11 | 7 | 15 | 15 | 254 | 32 | 128 | 37 | 108 | 105 | 96 | 32 | 80 | 7 | 1 | 4 | 34 |
714 |
317070/python-twitch-stream
|
317070_python-twitch-stream/twitchstream/outputvideo.py
|
twitchstream.outputvideo.TwitchOutputStream
|
class TwitchOutputStream(object):
"""
Initialize a TwitchOutputStream object and starts the pipe.
The stream is only started on the first frame.
:param twitch_stream_key:
:type twitch_stream_key:
:param width: the width of the videostream (in pixels)
:type width: int
:param height: the height of the videostream (in pixels)
:type height: int
:param fps: the number of frames per second of the videostream
:type fps: float
:param enable_audio: whether there will be sound or not
:type enable_audio: boolean
:param ffmpeg_binary: the binary to use to create a videostream
This is usually ffmpeg, but avconv on some (older) platforms
:type ffmpeg_binary: String
:param verbose: show ffmpeg output in stdout
:type verbose: boolean
"""
def __init__(self,
twitch_stream_key,
width=640,
height=480,
fps=30.,
ffmpeg_binary="ffmpeg",
enable_audio=False,
verbose=False):
self.twitch_stream_key = twitch_stream_key
self.width = width
self.height = height
self.fps = fps
self.ffmpeg_process = None
self.audio_pipe = None
self.ffmpeg_binary = ffmpeg_binary
self.verbose = verbose
self.audio_enabled = enable_audio
try:
self.reset()
except OSError:
print("There seems to be no %s available" % ffmpeg_binary)
if ffmpeg_binary == "ffmpeg":
print("ffmpeg can be installed using the following"
"commands")
print("> sudo add-apt-repository "
"ppa:mc3man/trusty-media")
print("> sudo apt-get update && "
"sudo apt-get install ffmpeg")
sys.exit(1)
def reset(self):
"""
Reset the videostream by restarting ffmpeg
"""
if self.ffmpeg_process is not None:
# Close the previous stream
try:
self.ffmpeg_process.send_signal(signal.SIGINT)
except OSError:
pass
command = []
command.extend([
self.ffmpeg_binary,
'-loglevel', 'verbose',
'-y', # overwrite previous file/stream
# '-re', # native frame-rate
'-analyzeduration', '1',
'-f', 'rawvideo',
'-r', '%d' % self.fps, # set a fixed frame rate
'-vcodec', 'rawvideo',
# size of one frame
'-s', '%dx%d' % (self.width, self.height),
'-pix_fmt', 'rgb24', # The input are raw bytes
'-thread_queue_size', '1024',
'-i', '-', # The input comes from a pipe
# Twitch needs to receive sound in their streams!
# '-an', # Tells FFMPEG not to expect any audio
])
if self.audio_enabled:
command.extend([
'-ar', '%d' % AUDIORATE,
'-ac', '2',
'-f', 's16le',
'-thread_queue_size', '1024',
'-i', '/tmp/audiopipe'
])
else:
command.extend([
'-f', 'lavfi',
'-i', 'anullsrc=channel_layout=stereo:sample_rate=44100'
])
command.extend([
# VIDEO CODEC PARAMETERS
'-vcodec', 'libx264',
'-r', '%d' % self.fps,
'-b:v', '3000k',
'-s', '%dx%d' % (self.width, self.height),
'-preset', 'faster', '-tune', 'zerolatency',
'-crf', '23',
'-pix_fmt', 'yuv420p',
# '-force_key_frames', r'expr:gte(t,n_forced*2)',
'-minrate', '3000k', '-maxrate', '3000k',
'-bufsize', '12000k',
'-g', '60', # key frame distance
'-keyint_min', '1',
# '-filter:v "setpts=0.25*PTS"'
# '-vsync','passthrough',
# AUDIO CODEC PARAMETERS
'-acodec', 'libmp3lame', '-ar', '44100', '-b:a', '160k',
# '-bufsize', '8192k',
'-ac', '1',
# '-acodec', 'aac', '-strict', 'experimental',
# '-ab', '128k', '-ar', '44100', '-ac', '1',
# '-async','44100',
# '-filter_complex', 'asplit', #for audio sync?
# STORE THE VIDEO PARAMETERS
# '-vcodec', 'libx264', '-s', '%dx%d'%(width, height),
# '-preset', 'libx264-fast',
# 'my_output_videofile2.avi'
# MAP THE STREAMS
# use only video from first input and only audio from second
'-map', '0:v', '-map', '1:a',
# NUMBER OF THREADS
'-threads', '2',
# STREAM TO TWITCH
'-f', 'flv', self.get_closest_ingest(),
])
devnullpipe = subprocess.DEVNULL
if self.verbose:
devnullpipe = None
self.ffmpeg_process = subprocess.Popen(
command,
stdin=subprocess.PIPE,
stderr=devnullpipe,
stdout=devnullpipe)
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
# sigint so avconv can clean up the stream nicely
self.ffmpeg_process.send_signal(signal.SIGINT)
# waiting doesn't work because of reasons I don't know
# self.pipe.wait()
def send_video_frame(self, frame):
"""Send frame of shape (height, width, 3)
with values between 0 and 1.
Raises an OSError when the stream is closed.
:param frame: array containing the frame.
:type frame: numpy array with shape (height, width, 3)
containing values between 0.0 and 1.0
"""
assert frame.shape == (self.height, self.width, 3)
frame = np.clip(255*frame, 0, 255).astype('uint8')
try:
self.ffmpeg_process.stdin.write(frame.tostring())
except OSError:
# The pipe has been closed. Reraise and handle it further
# downstream
raise
def send_audio(self, left_channel, right_channel):
"""Add the audio samples to the stream. The left and the right
channel should have the same shape.
Raises an OSError when the stream is closed.
:param left_channel: array containing the audio signal.
:type left_channel: numpy array with shape (k, )
containing values between -1.0 and 1.0. k can be any integer
:param right_channel: array containing the audio signal.
:type right_channel: numpy array with shape (k, )
containing values between -1.0 and 1.0. k can be any integer
"""
if self.audio_pipe is None:
if not os.path.exists('/tmp/audiopipe'):
os.mkfifo('/tmp/audiopipe')
self.audio_pipe = os.open('/tmp/audiopipe', os.O_WRONLY)
assert len(left_channel.shape) == 1
assert left_channel.shape == right_channel.shape
frame = np.column_stack((left_channel, right_channel)).flatten()
frame = np.clip(32767*frame, -32767, 32767).astype('int16')
try:
os.write(self.audio_pipe, frame.tostring())
except OSError:
# The pipe has been closed. Reraise and handle it further
# downstream
raise
def get_closest_ingest(self):
closest_server = requests.get(url='https://ingest.twitch.tv/api/v2/ingests').json()['ingests'][0]
url_template = closest_server['url_template']
print("Streaming to closest server: %s at %s" % (closest_server['name'],
url_template.replace('/app/{stream_key}', '')))
return url_template.format(
stream_key=self.twitch_stream_key)
|
class TwitchOutputStream(object):
'''
Initialize a TwitchOutputStream object and starts the pipe.
The stream is only started on the first frame.
:param twitch_stream_key:
:type twitch_stream_key:
:param width: the width of the videostream (in pixels)
:type width: int
:param height: the height of the videostream (in pixels)
:type height: int
:param fps: the number of frames per second of the videostream
:type fps: float
:param enable_audio: whether there will be sound or not
:type enable_audio: boolean
:param ffmpeg_binary: the binary to use to create a videostream
This is usually ffmpeg, but avconv on some (older) platforms
:type ffmpeg_binary: String
:param verbose: show ffmpeg output in stdout
:type verbose: boolean
'''
def __init__(self,
twitch_stream_key,
width=640,
height=480,
fps=30.,
ffmpeg_binary="ffmpeg",
enable_audio=False,
verbose=False):
pass
def reset(self):
'''
Reset the videostream by restarting ffmpeg
'''
pass
def __enter__(self):
pass
def __exit__(self, type, value, traceback):
pass
def send_video_frame(self, frame):
'''Send frame of shape (height, width, 3)
with values between 0 and 1.
Raises an OSError when the stream is closed.
:param frame: array containing the frame.
:type frame: numpy array with shape (height, width, 3)
containing values between 0.0 and 1.0
'''
pass
def send_audio(self, left_channel, right_channel):
'''Add the audio samples to the stream. The left and the right
channel should have the same shape.
Raises an OSError when the stream is closed.
:param left_channel: array containing the audio signal.
:type left_channel: numpy array with shape (k, )
containing values between -1.0 and 1.0. k can be any integer
:param right_channel: array containing the audio signal.
:type right_channel: numpy array with shape (k, )
containing values between -1.0 and 1.0. k can be any integer
'''
pass
def get_closest_ingest(self):
pass
| 8 | 4 | 26 | 2 | 17 | 8 | 2 | 0.62 | 1 | 2 | 0 | 2 | 7 | 9 | 7 | 7 | 212 | 23 | 120 | 29 | 105 | 74 | 65 | 22 | 57 | 5 | 1 | 2 | 17 |
715 |
317070/python-twitch-stream
|
317070_python-twitch-stream/twitchstream/outputvideo.py
|
twitchstream.outputvideo.TwitchOutputStreamRepeater
|
class TwitchOutputStreamRepeater(TwitchOutputStream):
"""
This stream makes sure a steady framerate is kept by repeating the
last frame when needed.
Note: this will not generate a stable, stutter-less stream!
It does not keep a buffer and you cannot synchronize using this
stream. Use TwitchBufferedOutputStream for this.
"""
def __init__(self, *args, **kwargs):
super(TwitchOutputStreamRepeater, self).__init__(*args, **kwargs)
self.lastframe = np.ones((self.height, self.width, 3))
self._send_last_video_frame() # Start sending the stream
if self.audio_enabled:
# some audible sine waves
xl = np.linspace(0.0, 10*np.pi, int(AUDIORATE/self.fps) + 1)[:-1]
xr = np.linspace(0.0, 100*np.pi, int(AUDIORATE/self.fps) + 1)[:-1]
self.lastaudioframe_left = np.sin(xl)
self.lastaudioframe_right = np.sin(xr)
self._send_last_audio() # Start sending the stream
def _send_last_video_frame(self):
try:
super(TwitchOutputStreamRepeater,
self).send_video_frame(self.lastframe)
except OSError:
# stream has been closed.
# This function is still called once when that happens.
pass
else:
# send the next frame at the appropriate time
threading.Timer(1./self.fps,
self._send_last_video_frame).start()
def _send_last_audio(self):
try:
super(TwitchOutputStreamRepeater,
self).send_audio(self.lastaudioframe_left,
self.lastaudioframe_right)
except OSError:
# stream has been closed.
# This function is still called once when that happens.
pass
else:
# send the next frame at the appropriate time
threading.Timer(1./self.fps,
self._send_last_audio).start()
def send_video_frame(self, frame):
"""Send frame of shape (height, width, 3)
with values between 0 and 1.
:param frame: array containing the frame.
:type frame: numpy array with shape (height, width, 3)
containing values between 0.0 and 1.0
"""
self.lastframe = frame
def send_audio(self, left_channel, right_channel):
"""Add the audio samples to the stream. The left and the right
channel should have the same shape.
:param left_channel: array containing the audio signal.
:type left_channel: numpy array with shape (k, )
containing values between -1.0 and 1.0. k can be any integer
:param right_channel: array containing the audio signal.
:type right_channel: numpy array with shape (k, )
containing values between -1.0 and 1.0. k can be any integer
"""
self.lastaudioframe_left = left_channel
self.lastaudioframe_right = right_channel
|
class TwitchOutputStreamRepeater(TwitchOutputStream):
'''
This stream makes sure a steady framerate is kept by repeating the
last frame when needed.
Note: this will not generate a stable, stutter-less stream!
It does not keep a buffer and you cannot synchronize using this
stream. Use TwitchBufferedOutputStream for this.
'''
def __init__(self, *args, **kwargs):
pass
def _send_last_video_frame(self):
pass
def _send_last_audio(self):
pass
def send_video_frame(self, frame):
'''Send frame of shape (height, width, 3)
with values between 0 and 1.
:param frame: array containing the frame.
:type frame: numpy array with shape (height, width, 3)
containing values between 0.0 and 1.0
'''
pass
def send_audio(self, left_channel, right_channel):
'''Add the audio samples to the stream. The left and the right
channel should have the same shape.
:param left_channel: array containing the audio signal.
:type left_channel: numpy array with shape (k, )
containing values between -1.0 and 1.0. k can be any integer
:param right_channel: array containing the audio signal.
:type right_channel: numpy array with shape (k, )
containing values between -1.0 and 1.0. k can be any integer
'''
pass
| 6 | 3 | 12 | 1 | 7 | 5 | 2 | 0.89 | 1 | 4 | 0 | 0 | 5 | 3 | 5 | 12 | 73 | 9 | 35 | 11 | 29 | 31 | 30 | 11 | 24 | 2 | 2 | 1 | 8 |
716 |
317070/python-twitch-stream
|
317070_python-twitch-stream/twitchstream/outputvideo.py
|
twitchstream.outputvideo.TwitchBufferedOutputStream
|
class TwitchBufferedOutputStream(TwitchOutputStream):
"""
This stream makes sure a steady framerate is kept by buffering
frames. Make sure not to have too many frames in buffer, since it
will increase the memory load considerably!
Adding frames is thread safe.
"""
def __init__(self, *args, **kwargs):
super(TwitchBufferedOutputStream, self).__init__(*args, **kwargs)
self.last_frame = np.ones((self.height, self.width, 3))
self.last_frame_time = None
self.next_video_send_time = None
self.frame_counter = 0
self.q_video = queue.PriorityQueue()
# don't call the functions directly, as they block on the first
# call
self.t = threading.Timer(0.0, self._send_video_frame)
self.t.daemon = True
self.t.start()
if self.audio_enabled:
# send audio at about the same rate as video
# this can be changed
self.last_audio = (np.zeros((int(AUDIORATE/self.fps), )),
np.zeros((int(AUDIORATE/self.fps), )))
self.last_audio_time = None
self.next_audio_send_time = None
self.audio_frame_counter = 0
self.q_audio = queue.PriorityQueue()
self.t = threading.Timer(0.0, self._send_audio)
self.t.daemon = True
self.t.start()
def _send_video_frame(self):
start_time = time.time()
try:
frame = self.q_video.get_nowait()
# frame[0] is frame count of the frame
# frame[1] is the frame
frame = frame[1]
except IndexError:
frame = self.last_frame
except queue.Empty:
frame = self.last_frame
else:
self.last_frame = frame
try:
super(TwitchBufferedOutputStream, self
).send_video_frame(frame)
except OSError:
# stream has been closed.
# This function is still called once when that happens.
# Don't call this function again and everything should be
# cleaned up just fine.
return
# send the next frame at the appropriate time
if self.next_video_send_time is None:
self.t = threading.Timer(1./self.fps, self._send_video_frame)
self.next_video_send_time = start_time + 1./self.fps
else:
self.next_video_send_time += 1./self.fps
next_event_time = self.next_video_send_time - start_time
if next_event_time > 0:
self.t = threading.Timer(next_event_time,
self._send_video_frame)
else:
# we should already have sent something!
#
# not allowed for recursion problems :-(
# (maximum recursion depth)
# self.send_me_last_frame_again()
#
# other solution:
self.t = threading.Thread(
target=self._send_video_frame)
self.t.daemon = True
self.t.start()
def _send_audio(self):
start_time = time.time()
try:
_, left_audio, right_audio = self.q_audio.get_nowait()
except IndexError:
left_audio, right_audio = self.last_audio
except queue.Empty:
left_audio, right_audio = self.last_audio
else:
self.last_audio = (left_audio, right_audio)
try:
super(TwitchBufferedOutputStream, self
).send_audio(left_audio, right_audio)
except OSError:
# stream has been closed.
# This function is still called once when that happens.
# Don't call this function again and everything should be
# cleaned up just fine.
return
# send the next frame at the appropriate time
downstream_time = len(left_audio) / AUDIORATE
if self.next_audio_send_time is None:
self.t = threading.Timer(downstream_time,
self._send_audio)
self.next_audio_send_time = start_time + downstream_time
else:
self.next_audio_send_time += downstream_time
next_event_time = self.next_audio_send_time - start_time
if next_event_time > 0:
self.t = threading.Timer(next_event_time,
self._send_audio)
else:
# we should already have sent something!
#
# not allowed for recursion problems :-(
# (maximum recursion depth)
# self.send_me_last_frame_again()
#
# other solution:
self.t = threading.Thread(
target=self._send_audio)
self.t.daemon = True
self.t.start()
def send_video_frame(self, frame, frame_counter=None):
"""send frame of shape (height, width, 3)
with values between 0 and 1
:param frame: array containing the frame.
:type frame: numpy array with shape (height, width, 3)
containing values between 0.0 and 1.0
:param frame_counter: frame position number within stream.
Provide this when multi-threading to make sure frames don't
switch position
:type frame_counter: int
"""
if frame_counter is None:
frame_counter = self.frame_counter
self.frame_counter += 1
self.q_video.put((frame_counter, frame))
def send_audio(self,
left_channel,
right_channel,
frame_counter=None):
"""Add the audio samples to the stream. The left and the right
channel should have the same shape.
:param left_channel: array containing the audio signal.
:type left_channel: numpy array with shape (k, )
containing values between -1.0 and 1.0. l can be any integer
:param right_channel: array containing the audio signal.
:type right_channel: numpy array with shape (k, )
containing values between -1.0 and 1.0. l can be any integer
:param frame_counter: frame position number within stream.
Provide this when multi-threading to make sure frames don't
switch position
:type frame_counter: int
"""
if frame_counter is None:
frame_counter = self.audio_frame_counter
self.audio_frame_counter += 1
self.q_audio.put((frame_counter, left_channel, right_channel))
def get_video_frame_buffer_state(self):
"""Find out how many video frames are left in the buffer.
The buffer should never run dry, or audio and video will go out
of sync. Likewise, the more filled the buffer, the higher the
memory use and the delay between you putting your frame in the
stream and the frame showing up on Twitch.
:return integer estimate of the number of video frames left.
"""
return self.q_video.qsize()
def get_audio_buffer_state(self):
"""Find out how many audio fragments are left in the buffer.
The buffer should never run dry, or audio and video will go out
of sync. Likewise, the more filled the buffer, the higher the
memory use and the delay between you putting your frame in the
stream and the frame showing up on Twitch.
:return integer estimate of the number of audio fragments left.
"""
return self.q_audio.qsize()
|
class TwitchBufferedOutputStream(TwitchOutputStream):
'''
This stream makes sure a steady framerate is kept by buffering
frames. Make sure not to have too many frames in buffer, since it
will increase the memory load considerably!
Adding frames is thread safe.
'''
def __init__(self, *args, **kwargs):
pass
def _send_video_frame(self):
pass
def _send_audio(self):
pass
def send_video_frame(self, frame, frame_counter=None):
'''send frame of shape (height, width, 3)
with values between 0 and 1
:param frame: array containing the frame.
:type frame: numpy array with shape (height, width, 3)
containing values between 0.0 and 1.0
:param frame_counter: frame position number within stream.
Provide this when multi-threading to make sure frames don't
switch position
:type frame_counter: int
'''
pass
def send_audio(self,
left_channel,
right_channel,
frame_counter=None):
'''Add the audio samples to the stream. The left and the right
channel should have the same shape.
:param left_channel: array containing the audio signal.
:type left_channel: numpy array with shape (k, )
containing values between -1.0 and 1.0. l can be any integer
:param right_channel: array containing the audio signal.
:type right_channel: numpy array with shape (k, )
containing values between -1.0 and 1.0. l can be any integer
:param frame_counter: frame position number within stream.
Provide this when multi-threading to make sure frames don't
switch position
:type frame_counter: int
'''
pass
def get_video_frame_buffer_state(self):
'''Find out how many video frames are left in the buffer.
The buffer should never run dry, or audio and video will go out
of sync. Likewise, the more filled the buffer, the higher the
memory use and the delay between you putting your frame in the
stream and the frame showing up on Twitch.
:return integer estimate of the number of video frames left.
'''
pass
def get_audio_buffer_state(self):
'''Find out how many audio fragments are left in the buffer.
The buffer should never run dry, or audio and video will go out
of sync. Likewise, the more filled the buffer, the higher the
memory use and the delay between you putting your frame in the
stream and the frame showing up on Twitch.
:return integer estimate of the number of audio fragments left.
'''
pass
| 8 | 5 | 26 | 2 | 14 | 10 | 3 | 0.74 | 1 | 7 | 0 | 0 | 7 | 11 | 7 | 14 | 194 | 22 | 99 | 29 | 88 | 73 | 84 | 26 | 76 | 6 | 2 | 2 | 20 |
717 |
3DLIRIOUS/MeshLabXML
|
3DLIRIOUS_MeshLabXML/meshlabxml/mlx.py
|
meshlabxml.mlx.FilterScript
|
class FilterScript(object):
"""
begin - need file names. Need these first to have correct layers; need to know however
many we're importing!
layers = list of mesh layers, with name as the entry
file_in
mlp_in
begin code
filters = actual text of filters. This is a list with each filter in a separate entry
end code
use self.meshes.[len(self.meshes)]
use cur_layer, tot_layer in strings and replace at the end? Sounds way to complicated
for now; just be sure to provide input files to start!
add run method?
"""
def __init__(self, file_in=None, mlp_in=None, file_out=None, ml_version=ML_VERSION):
self.ml_version = ml_version # MeshLab version
self.filters = []
self.layer_stack = [-1] # set current layer to -1
self.opening = ['<!DOCTYPE FilterScript>\n<FilterScript>\n']
self.closing = ['</FilterScript>\n']
self.__stl_layers = []
self.file_in = file_in
self.mlp_in = mlp_in
self.__no_file_in = False
self.file_out = file_out
self.geometry = None
self.topology = None
self.hausdorff_distance = None
self.parse_geometry = False
self.parse_topology = False
self.parse_hausdorff = False
# Process input files
# Process project files first
# TODO: test to make sure this works with "bunny"; should work fine!
if self.mlp_in is not None:
# make a list if it isn't already
self.mlp_in = util.make_list(self.mlp_in)
for val in self.mlp_in:
tree = ET.parse(val)
#root = tree.getroot()
for elem in tree.iter(tag='MLMesh'):
filename = (elem.attrib['filename'])
fext = os.path.splitext(filename)[1][1:].strip().lower()
label = (elem.attrib['label'])
# add new mesh to the end of the mesh stack
self.add_layer(label)
#self.layer_stack.insert(self.last_layer() + 1, label)
# change current mesh
self.set_current_layer(self.last_layer())
#self.layer_stack[self.last_layer() + 1] = self.last_layer()
# If the mesh file extension is stl, change to that layer and
# run clean.merge_vert
if fext == 'stl':
self.__stl_layers.append(self.current_layer())
# Process separate input files next
if self.file_in is not None:
# make a list if it isn't already
self.file_in = util.make_list(self.file_in)
for val in self.file_in:
fext = os.path.splitext(val)[1][1:].strip().lower()
label = os.path.splitext(val)[0].strip() # file prefix
#print('layer_stack = %s' % self.layer_stack)
#print('last_layer = %s' % self.last_layer())
#print('current_layer = %s' % self.current_layer())
# add new mesh to the end of the mesh stack
self.add_layer(label)
#self.layer_stack.insert(self.last_layer() + 1, label)
# change current mesh
self.set_current_layer(self.last_layer())
#self.layer_stack[self.last_layer() + 1] = self.last_layer()
# If the mesh file extension is stl, change to that layer and
# run clean.merge_vert
if fext == 'stl':
self.__stl_layers.append(self.current_layer())
# If some input files were stl, we need to change back to the last layer
# If the mesh file extension is stl, change to that layer and
# run clean.merge_vert
if self.__stl_layers:
for layer in self.__stl_layers:
if layer != self.current_layer():
layers.change(self, layer)
clean.merge_vert(self)
layers.change(self, self.last_layer()) # Change back to the last layer
elif self.last_layer() == -1:
# If no input files are provided, create a dummy file
# with a single vertex and delete it first in the script.
# This works around the fact that meshlabserver will
# not run without an input file.
# Layer stack is modified here; temp file
# is created during run
self.__no_file_in = True
self.add_layer('DELETE_ME')
layers.delete(self)
def last_layer(self):
""" Returns the index number of the last layer """
#print('last layer = %s' % (len(self.layer_stack) - 2))
return len(self.layer_stack) - 2
def current_layer(self):
""" Returns the index number of the current layer """
return self.layer_stack[len(self.layer_stack) - 1]
def set_current_layer(self, layer_num):
""" Set the current layer to layer_num """
self.layer_stack[len(self.layer_stack) - 1] = layer_num
return None
def add_layer(self, label, change_layer=True):
""" Add new mesh layer to the end of the stack
Args:
label (str): new label for the mesh layer
change_layer (bool): change to the newly created layer
"""
self.layer_stack.insert(self.last_layer() + 1, label)
if change_layer:
self.set_current_layer(self.last_layer())
return None
def del_layer(self, layer_num):
""" Delete mesh layer """
del self.layer_stack[layer_num]
# Adjust current layer if needed
if layer_num < self.current_layer():
self.set_current_layer(self.current_layer() - 1)
return None
def save_to_file(self, script_file):
""" Save filter script to an mlx file """
# TODO: raise exception here instead?
if not self.filters:
print('WARNING: no filters to save to file!')
script_file_descriptor = open(script_file, 'w')
script_file_descriptor.write(''.join(self.opening + self.filters + self.closing))
script_file_descriptor.close()
def run_script(self, log=None, ml_log=None, mlp_out=None, overwrite=False,
file_out=None, output_mask=None, script_file=None, print_meshlabserver_output=True):
""" Run the script
"""
temp_script = False
temp_ml_log = False
if self.__no_file_in:
# If no input files are provided, create a dummy file
# with a single vertex and delete it first in the script.
# This works around the fact that meshlabserver will
# not run without an input file.
temp_file_in_file = tempfile.NamedTemporaryFile(delete=False, suffix='.xyz', dir=os.getcwd())
temp_file_in_file.write(b'0 0 0')
temp_file_in_file.close()
self.file_in = [temp_file_in_file.name]
if not self.filters:
script_file = None
elif script_file is None:
# Create temporary script file
temp_script = True
temp_script_file = tempfile.NamedTemporaryFile(delete=False, suffix='.mlx')
temp_script_file.close()
self.save_to_file(temp_script_file.name)
script_file = temp_script_file.name
if (self.parse_geometry or self.parse_topology or self.parse_hausdorff) and (ml_log is None):
# create temp ml_log
temp_ml_log = True
ml_log_file = tempfile.NamedTemporaryFile(delete=False, suffix='.txt')
ml_log_file.close()
ml_log = ml_log_file.name
if file_out is None:
file_out = self.file_out
run(script=script_file, log=log, ml_log=ml_log,
mlp_in=self.mlp_in, mlp_out=mlp_out, overwrite=overwrite,
file_in=self.file_in, file_out=file_out, output_mask=output_mask, ml_version=self.ml_version,
print_meshlabserver_output=print_meshlabserver_output)
# Parse output
# TODO: record which layer this is associated with?
if self.parse_geometry:
self.geometry = compute.parse_geometry(ml_log, log, print_output=print_meshlabserver_output)
if self.parse_topology:
self.topology = compute.parse_topology(ml_log, log, print_output=print_meshlabserver_output)
if self.parse_hausdorff:
self.hausdorff_distance = compute.parse_hausdorff(ml_log, log, print_output=print_meshlabserver_output)
# Delete temp files
if self.__no_file_in:
os.remove(temp_file_in_file.name)
if temp_script:
os.remove(temp_script_file.name)
if temp_ml_log:
os.remove(ml_log_file.name)
|
class FilterScript(object):
'''
begin - need file names. Need these first to have correct layers; need to know however
many we're importing!
layers = list of mesh layers, with name as the entry
file_in
mlp_in
begin code
filters = actual text of filters. This is a list with each filter in a separate entry
end code
use self.meshes.[len(self.meshes)]
use cur_layer, tot_layer in strings and replace at the end? Sounds way to complicated
for now; just be sure to provide input files to start!
add run method?
'''
def __init__(self, file_in=None, mlp_in=None, file_out=None, ml_version=ML_VERSION):
pass
def last_layer(self):
''' Returns the index number of the last layer '''
pass
def current_layer(self):
''' Returns the index number of the current layer '''
pass
def set_current_layer(self, layer_num):
''' Set the current layer to layer_num '''
pass
def add_layer(self, label, change_layer=True):
''' Add new mesh layer to the end of the stack
Args:
label (str): new label for the mesh layer
change_layer (bool): change to the newly created layer
'''
pass
def del_layer(self, layer_num):
''' Delete mesh layer '''
pass
def save_to_file(self, script_file):
''' Save filter script to an mlx file '''
pass
def run_script(self, log=None, ml_log=None, mlp_out=None, overwrite=False,
file_out=None, output_mask=None, script_file=None, print_meshlabserver_output=True):
''' Run the script
'''
pass
| 9 | 8 | 22 | 1 | 14 | 7 | 4 | 0.65 | 1 | 0 | 0 | 0 | 8 | 16 | 8 | 8 | 204 | 23 | 112 | 39 | 102 | 73 | 106 | 38 | 97 | 12 | 1 | 4 | 33 |
718 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/core/interface.py
|
interface.EnumField
|
class EnumField(Raw):
"""
Marshal an enum as a string
"""
def format(self, value):
try:
return value.name
except ValueError as ve:
raise MarshallingException(ve)
|
class EnumField(Raw):
'''
Marshal an enum as a string
'''
def format(self, value):
pass
| 2 | 1 | 5 | 0 | 5 | 0 | 2 | 0.5 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 1 | 10 | 1 | 6 | 3 | 4 | 3 | 6 | 2 | 4 | 2 | 1 | 1 | 2 |
719 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/core/interface.py
|
interface.RecordingDeviceStatus
|
class RecordingDeviceStatus(Enum):
"""
the status of the recording device.
"""
NEW = 0
INITIALISED = 1
RECORDING = 2
FAILED = 3
|
class RecordingDeviceStatus(Enum):
'''
the status of the recording device.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.6 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 49 | 8 | 0 | 5 | 5 | 4 | 3 | 5 | 5 | 4 | 0 | 4 | 0 | 0 |
720 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/analyser/resources/measurement.py
|
measurement.CompleteMeasurement
|
class CompleteMeasurement(Resource):
def __init__(self, **kwargs):
self._measurementController = kwargs['measurementController']
def put(self, measurementId, deviceId):
"""
Completes the measurement for this device.
:param measurementId:
:param deviceId:
:return:
"""
logger.info('Completing measurement ' + measurementId + ' for ' + deviceId)
if self._measurementController.completeMeasurement(measurementId, deviceId):
logger.info('Completed measurement ' + measurementId + ' for ' + deviceId)
return None, 200
else:
logger.warning('Unable to complete measurement ' + measurementId + ' for ' + deviceId)
return None, 404
|
class CompleteMeasurement(Resource):
def __init__(self, **kwargs):
pass
def put(self, measurementId, deviceId):
'''
Completes the measurement for this device.
:param measurementId:
:param deviceId:
:return:
'''
pass
| 3 | 1 | 8 | 0 | 5 | 3 | 2 | 0.55 | 1 | 0 | 0 | 0 | 2 | 1 | 2 | 2 | 18 | 1 | 11 | 4 | 8 | 6 | 10 | 4 | 7 | 2 | 1 | 1 | 3 |
721 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/analyser/resources/measurement.py
|
measurement.FailMeasurement
|
class FailMeasurement(Resource):
def __init__(self, **kwargs):
self._measurementController = kwargs['measurementController']
def put(self, measurementId, deviceId):
"""
Fails the measurement for this device.
:param measurementId: the measurement name.
:param deviceId: the device name.
:return: 200 if
"""
payload = request.get_json()
failureReason = json.loads(payload).get('failureReason') if payload is not None else None
logger.warning('Failing measurement ' + measurementId + ' for ' + deviceId + ' because ' + str(failureReason))
if self._measurementController.failMeasurement(measurementId, deviceId, failureReason=failureReason):
logger.warning('Failed measurement ' + measurementId + ' for ' + deviceId)
return None, 200
else:
logger.error('Unable to fail measurement ' + measurementId + ' for ' + deviceId)
return None, 404
|
class FailMeasurement(Resource):
def __init__(self, **kwargs):
pass
def put(self, measurementId, deviceId):
'''
Fails the measurement for this device.
:param measurementId: the measurement name.
:param deviceId: the device name.
:return: 200 if
'''
pass
| 3 | 1 | 9 | 0 | 6 | 3 | 2 | 0.46 | 1 | 1 | 0 | 0 | 2 | 1 | 2 | 2 | 20 | 1 | 13 | 6 | 10 | 6 | 12 | 6 | 9 | 3 | 1 | 1 | 4 |
722 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/analyser/resources/measurement.py
|
measurement.InitialiseMeasurement
|
class InitialiseMeasurement(Resource):
def __init__(self, **kwargs):
self._measurementController = kwargs['measurementController']
def put(self, measurementId, deviceId):
"""
Initialises the measurement session from the given device.
:param measurementId:
:param deviceId:
:return:
"""
logger.info('Starting measurement ' + measurementId + ' for ' + deviceId)
if self._measurementController.startMeasurement(measurementId, deviceId):
logger.info('Started measurement ' + measurementId + ' for ' + deviceId)
return None, 200
else:
logger.warning('Failed to start measurement ' + measurementId + ' for ' + deviceId)
return None, 404
|
class InitialiseMeasurement(Resource):
def __init__(self, **kwargs):
pass
def put(self, measurementId, deviceId):
'''
Initialises the measurement session from the given device.
:param measurementId:
:param deviceId:
:return:
'''
pass
| 3 | 1 | 8 | 0 | 5 | 3 | 2 | 0.55 | 1 | 0 | 0 | 0 | 2 | 1 | 2 | 2 | 18 | 1 | 11 | 4 | 8 | 6 | 10 | 4 | 7 | 2 | 1 | 1 | 3 |
723 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/analyser/resources/measurement.py
|
measurement.RecordData
|
class RecordData(Resource):
def __init__(self, **kwargs):
self._measurementController = kwargs['measurementController']
def put(self, measurementId, deviceId):
"""
Store a bunch of data for this measurement session.
:param measurementId:
:param deviceId:
:return:
"""
data = request.get_json()
if data is not None:
parsedData = json.loads(data)
logger.debug('Received payload ' + measurementId + '/' + deviceId + ': ' +
str(len(parsedData)) + ' records')
if self._measurementController.recordData(measurementId, deviceId, parsedData):
return None, 200
else:
logger.warning('Unable to record payload ' + measurementId + '/' + deviceId)
return None, 404
else:
logger.error('Invalid data payload received ' + measurementId + '/' + deviceId)
return None, 400
|
class RecordData(Resource):
def __init__(self, **kwargs):
pass
def put(self, measurementId, deviceId):
'''
Store a bunch of data for this measurement session.
:param measurementId:
:param deviceId:
:return:
'''
pass
| 3 | 1 | 11 | 0 | 8 | 3 | 2 | 0.35 | 1 | 1 | 0 | 0 | 2 | 1 | 2 | 2 | 24 | 1 | 17 | 6 | 14 | 6 | 14 | 6 | 11 | 3 | 1 | 2 | 4 |
724 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/analyser/common/measurementcontroller.py
|
measurementcontroller.ActiveMeasurement
|
class ActiveMeasurement(object):
"""
Models a measurement that is scheduled or is currently in progress.
"""
def __init__(self, name, startTime, duration, deviceState, description=None):
self.name = name
self.startTime = startTime
self.duration = duration
self.endTime = startTime + datetime.timedelta(days=0, seconds=duration)
self.measurementParameters = marshal(deviceState, targetStateFields)
self.description = description
self.recordingDevices = {}
self.status = MeasurementStatus.NEW
self.id = getMeasurementId(self.startTime, self.name)
self.idAsPath = self.id.replace('_', '/')
# hardcoded here rather than in the UI
self.analysis = DEFAULT_ANALYSIS_SERIES
def overlapsWith(self, targetStartTime, duration):
"""
Tests if the given times overlap with this measurement.
:param targetStartTime: the target start time.
:param duration: the duration
:return: true if the given times overlap with this measurement.
"""
targetEndTime = targetStartTime + datetime.timedelta(days=0, seconds=duration)
return (self.startTime <= targetStartTime <= self.endTime) \
or (targetStartTime <= self.startTime <= targetEndTime)
def updateDeviceStatus(self, deviceName, state, reason=None):
"""
Updates the current device status.
:param deviceName: the device name.
:param state: the state.
:param reason: the reason for the change.
:return:
"""
logger.info('Updating recording device state for ' + deviceName + ' to ' + state.name +
('' if reason is None else '[reason: ' + reason + ']'))
currentState = self.recordingDevices.get(deviceName)
count = 0
if currentState is not None:
if currentState['state'] == MeasurementStatus.RECORDING.name:
count = currentState['count']
self.recordingDevices[deviceName] = {
'state': state.name,
'reason': reason,
'time': datetime.datetime.utcnow().strftime(DATETIME_FORMAT),
'count': count
}
def stillRecording(self, deviceId, dataCount):
"""
For a device that is recording, updates the last timestamp so we now when we last received data.
:param deviceId: the device id.
:param dataCount: the no of items of data recorded in this batch.
:return:
"""
status = self.recordingDevices[deviceId]
if status is not None:
if status['state'] == MeasurementStatus.RECORDING.name:
status['last'] = datetime.datetime.utcnow().strftime(DATETIME_FORMAT)
status['count'] = status['count'] + dataCount
def __str__(self):
"""
:return: a human readable format
"""
return "ActiveMeasurement[" + self.id + "-" + self.status.name + " for " + self.duration + "s]"
|
class ActiveMeasurement(object):
'''
Models a measurement that is scheduled or is currently in progress.
'''
def __init__(self, name, startTime, duration, deviceState, description=None):
pass
def overlapsWith(self, targetStartTime, duration):
'''
Tests if the given times overlap with this measurement.
:param targetStartTime: the target start time.
:param duration: the duration
:return: true if the given times overlap with this measurement.
'''
pass
def updateDeviceStatus(self, deviceName, state, reason=None):
'''
Updates the current device status.
:param deviceName: the device name.
:param state: the state.
:param reason: the reason for the change.
:return:
'''
pass
def stillRecording(self, deviceId, dataCount):
'''
For a device that is recording, updates the last timestamp so we now when we last received data.
:param deviceId: the device id.
:param dataCount: the no of items of data recorded in this batch.
:return:
'''
pass
def __str__(self):
'''
:return: a human readable format
'''
pass
| 6 | 5 | 12 | 0 | 8 | 5 | 2 | 0.67 | 1 | 3 | 1 | 0 | 5 | 11 | 5 | 5 | 70 | 5 | 39 | 21 | 33 | 26 | 32 | 21 | 26 | 4 | 1 | 2 | 10 |
725 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/analyser/common/measurementcontroller.py
|
measurementcontroller.CompleteMeasurement
|
class CompleteMeasurement(object):
"""
A complete measurement is one which has successfully completed on the devices and for which we have a full dataset.
The system only keeps, and can analyse, complete measurements.
"""
def __init__(self, meta, dataDir):
self.name = meta['name']
self.startTime = datetime.datetime.strptime(meta['startTime'], DATETIME_FORMAT)
self.duration = meta['duration']
self.endTime = self.startTime + datetime.timedelta(days=0, seconds=self.duration)
self.measurementParameters = meta['measurementParameters']
self.description = meta['description']
self.recordingDevices = meta['recordingDevices']
self.status = MeasurementStatus[meta['status']]
self.id = getMeasurementId(self.startTime, self.name)
# self.analysis = meta.get('analysis', DEFAULT_ANALYSIS_SERIES)
self.analysis = DEFAULT_ANALYSIS_SERIES
self.idAsPath = self.id.replace('_', '/')
self.dataDir = dataDir
self.data = {}
def updateName(self, newName):
self.name = newName
self.id = getMeasurementId(self.startTime, self.name)
self.idAsPath = self.id.replace('_', '/')
def inflate(self):
"""
loads the recording into memory and returns it as a Signal
:return:
"""
if self.measurementParameters['accelerometerEnabled']:
if len(self.data) == 0:
logger.info('Loading measurement data for ' + self.name)
self.data = {name: self._loadXYZ(name) for name, value in self.recordingDevices.items()}
return True
else:
# TODO error handling
return False
def _loadXYZ(self, name):
dataPath = os.path.join(self.dataDir, self.idAsPath, name, 'data.out')
if os.path.exists(dataPath):
from analyser.common.signal import loadTriAxisSignalFromFile
return loadTriAxisSignalFromFile(dataPath)
else:
raise ValueError("Data does not exist")
def __str__(self):
"""
:return: a human readable format
"""
return "CompleteMeasurement[" + self.id + " for " + self.duration + "s]"
|
class CompleteMeasurement(object):
'''
A complete measurement is one which has successfully completed on the devices and for which we have a full dataset.
The system only keeps, and can analyse, complete measurements.
'''
def __init__(self, meta, dataDir):
pass
def updateName(self, newName):
pass
def inflate(self):
'''
loads the recording into memory and returns it as a Signal
:return:
'''
pass
def _loadXYZ(self, name):
pass
def __str__(self):
'''
:return: a human readable format
'''
pass
| 6 | 3 | 9 | 0 | 7 | 2 | 2 | 0.36 | 1 | 4 | 1 | 0 | 5 | 13 | 5 | 5 | 54 | 5 | 36 | 22 | 29 | 13 | 34 | 21 | 27 | 3 | 1 | 2 | 8 |
726 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/analyser/common/measurementcontroller.py
|
measurementcontroller.MeasurementStatus
|
class MeasurementStatus(Enum):
"""
Models the states an ActiveMeasurement can be in.
"""
NEW = 1,
SCHEDULED = 2,
RECORDING = 3,
DYING = 4,
FAILED = 5,
COMPLETE = 6,
|
class MeasurementStatus(Enum):
'''
Models the states an ActiveMeasurement can be in.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.43 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 49 | 10 | 0 | 7 | 7 | 6 | 3 | 7 | 7 | 6 | 0 | 4 | 0 | 0 |
727 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/analyser/common/measurementcontroller.py
|
measurementcontroller.RecordStatus
|
class RecordStatus(Enum):
"""
The state of a device's measurement from the perspective of the measurement.
"""
SCHEDULED = 1
RECORDING = 2,
COMPLETE = 3,
FAILED = 4
|
class RecordStatus(Enum):
'''
The state of a device's measurement from the perspective of the measurement.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.6 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 49 | 8 | 0 | 5 | 5 | 4 | 3 | 5 | 5 | 4 | 0 | 4 | 0 | 0 |
728 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/recorder/resources/recordingdevices.py
|
recordingdevices.SelfTest
|
class SelfTest(Resource):
def __init__(self, **kwargs):
self.recordingDevices = kwargs['recordingDevices']
def get(self, deviceId):
"""
performs a self test on the given device.
:param: deviceId the device id.
:return: the self test results and 200 if it passed, 500 if it didn't
"""
device = self.recordingDevices.get(deviceId)
passed, results = device.performSelfTest()
return results, 200 if passed else 500
|
class SelfTest(Resource):
def __init__(self, **kwargs):
pass
def get(self, deviceId):
'''
performs a self test on the given device.
:param: deviceId the device id.
:return: the self test results and 200 if it passed, 500 if it didn't
'''
pass
| 3 | 1 | 6 | 0 | 3 | 3 | 2 | 0.71 | 1 | 0 | 0 | 0 | 2 | 1 | 2 | 2 | 13 | 1 | 7 | 6 | 4 | 5 | 7 | 6 | 4 | 2 | 1 | 0 | 3 |
729 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/recorder/resources/measurements.py
|
measurements.ScheduledMeasurement
|
class ScheduledMeasurement:
"""
A named measurement that is scheduled to run at a given time for a given duration.
"""
def __init__(self, name, device):
"""
create a new measurement with the given name to execute on the given device.
:param name: the measurement name.
:param device: the device to run on.
"""
self.name = name
self.device = device
self.recording = False
self.statuses = [{'name': ScheduledMeasurementStatus.INITIALISING.name, 'time': datetime.utcnow()}]
self.callback = None
def schedule(self, duration, at=None, delay=None, callback=None):
"""
schedules the measurement (to execute asynchronously).
:param duration: how long to run for.
:param at: the time to start at.
:param delay: the time to wait til starting (use at or delay).
:param callback: a callback.
:return: nothing.
"""
delay = self.calculateDelay(at, delay)
self.callback = callback
logger.info('Initiating measurement ' + self.name + ' for ' + str(duration) + 's in ' + str(delay) + 's')
self.statuses.append({'name': ScheduledMeasurementStatus.SCHEDULED.name, 'time': datetime.utcnow()})
threading.Timer(delay, self.execute, [duration]).start()
def execute(self, duration):
"""
Executes the measurement, recording the event status.
:param duration: the time to run for.
:return: nothing.
"""
self.statuses.append({'name': ScheduledMeasurementStatus.RUNNING.name, 'time': datetime.utcnow()})
try:
self.recording = True
self.device.start(self.name, durationInSeconds=duration)
finally:
self.recording = False
if self.device.status == RecordingDeviceStatus.FAILED:
self.statuses.append({'name': ScheduledMeasurementStatus.FAILED.name,
'time': datetime.utcnow(),
'reason': self.device.failureCode})
else:
self.statuses.append({'name': ScheduledMeasurementStatus.COMPLETE.name, 'time': datetime.utcnow()})
# this is a bit of a hack, need to remove this at some point by refactoring the way measurements are stored
if self.callback is not None:
self.callback()
def calculateDelay(self, at, delay):
"""
Creates the delay from now til the specified start time, uses "at" if available.
:param at: the start time in %a %b %d %H:%M:%S %Y format.
:param delay: the delay from now til start.
:return: the delay.
"""
if at is not None:
return max((datetime.strptime(at, DATETIME_FORMAT) - datetime.utcnow()).total_seconds(), 0)
elif delay is not None:
return delay
else:
return 0
|
class ScheduledMeasurement:
'''
A named measurement that is scheduled to run at a given time for a given duration.
'''
def __init__(self, name, device):
'''
create a new measurement with the given name to execute on the given device.
:param name: the measurement name.
:param device: the device to run on.
'''
pass
def schedule(self, duration, at=None, delay=None, callback=None):
'''
schedules the measurement (to execute asynchronously).
:param duration: how long to run for.
:param at: the time to start at.
:param delay: the time to wait til starting (use at or delay).
:param callback: a callback.
:return: nothing.
'''
pass
def execute(self, duration):
'''
Executes the measurement, recording the event status.
:param duration: the time to run for.
:return: nothing.
'''
pass
def calculateDelay(self, at, delay):
'''
Creates the delay from now til the specified start time, uses "at" if available.
:param at: the start time in %a %b %d %H:%M:%S %Y format.
:param delay: the delay from now til start.
:return: the delay.
'''
pass
| 5 | 5 | 15 | 0 | 9 | 6 | 2 | 0.8 | 0 | 5 | 2 | 0 | 4 | 5 | 4 | 4 | 67 | 4 | 35 | 10 | 30 | 28 | 29 | 10 | 24 | 3 | 0 | 1 | 8 |
730 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/recorder/resources/measurements.py
|
measurements.ScheduledMeasurementStatus
|
class ScheduledMeasurementStatus(Enum):
INITIALISING = 0
SCHEDULED = 1
RUNNING = 2
COMPLETE = 3
FAILED = 4
|
class ScheduledMeasurementStatus(Enum):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 49 | 6 | 0 | 6 | 6 | 5 | 0 | 6 | 6 | 5 | 0 | 4 | 0 | 0 |
731 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/recorder/common/mpu6050.py
|
mpu6050.mpu6050
|
class mpu6050(Accelerometer):
"""
Controls the Invensense MPU-6050, code based on danjperron's https://github.com/danjperron/mpu6050TestInC
"""
# Temperature in degrees C = (TEMP_OUT Register Value as a signed quantity)/340 + 36.53
_temperatureGain = DEFAULT_TEMPERATURE_GAIN
_temperatureOffset = DEFAULT_TEMPERATURE_OFFSET
# converted from Jeff Rowberg code https://github.com/jrowberg/i2cdevlib/blob/master/Arduino/MPU6050/MPU6050.h
MPU6050_ADDRESS = 0x68 # default I2C Address
# bit masks for enabling the which sensors are written to the FIFO
enableAccelerometerMask = 0b00001000
enableGyroMask = 0b01110000
enableTemperatureMask = 0b10000000
# register definition
MPU6050_RA_XG_OFFS_TC = 0x00 # [7] PWR_MODE, [6:1] XG_OFFS_TC, [0] OTP_BNK_VLD
MPU6050_RA_YG_OFFS_TC = 0x01 # [7] PWR_MODE, [6:1] YG_OFFS_TC, [0] OTP_BNK_VLD
MPU6050_RA_ZG_OFFS_TC = 0x02 # [7] PWR_MODE, [6:1] ZG_OFFS_TC, [0] OTP_BNK_VLD
MPU6050_RA_X_FINE_GAIN = 0x03 # [7:0] X_FINE_GAIN
MPU6050_RA_Y_FINE_GAIN = 0x04 # [7:0] Y_FINE_GAIN
MPU6050_RA_Z_FINE_GAIN = 0x05 # [7:0] Z_FINE_GAIN
MPU6050_RA_XA_OFFS_H = 0x06 # [15:0] XA_OFFS
MPU6050_RA_XA_OFFS_L_TC = 0x07
MPU6050_RA_YA_OFFS_H = 0x08 # [15:0] YA_OFFS
MPU6050_RA_YA_OFFS_L_TC = 0x09
MPU6050_RA_ZA_OFFS_H = 0x0A # [15:0] ZA_OFFS
MPU6050_RA_ZA_OFFS_L_TC = 0x0B
MPU6050_RA_XG_OFFS_USRH = 0x13 # [15:0] XG_OFFS_USR
MPU6050_RA_XG_OFFS_USRL = 0x14
MPU6050_RA_YG_OFFS_USRH = 0x15 # [15:0] YG_OFFS_USR
MPU6050_RA_YG_OFFS_USRL = 0x16
MPU6050_RA_ZG_OFFS_USRH = 0x17 # [15:0] ZG_OFFS_USR
MPU6050_RA_ZG_OFFS_USRL = 0x18
MPU6050_RA_SMPLRT_DIV = 0x19
MPU6050_RA_CONFIG = 0x1A
MPU6050_RA_GYRO_CONFIG = 0x1B
MPU6050_RA_ACCEL_CONFIG = 0x1C
MPU6050_RA_FF_THR = 0x1D
MPU6050_RA_FF_DUR = 0x1E
MPU6050_RA_MOT_THR = 0x1F
MPU6050_RA_MOT_DUR = 0x20
MPU6050_RA_ZRMOT_THR = 0x21
MPU6050_RA_ZRMOT_DUR = 0x22
MPU6050_RA_FIFO_EN = 0x23
MPU6050_RA_I2C_MST_CTRL = 0x24
MPU6050_RA_I2C_SLV0_ADDR = 0x25
MPU6050_RA_I2C_SLV0_REG = 0x26
MPU6050_RA_I2C_SLV0_CTRL = 0x27
MPU6050_RA_I2C_SLV1_ADDR = 0x28
MPU6050_RA_I2C_SLV1_REG = 0x29
MPU6050_RA_I2C_SLV1_CTRL = 0x2A
MPU6050_RA_I2C_SLV2_ADDR = 0x2B
MPU6050_RA_I2C_SLV2_REG = 0x2C
MPU6050_RA_I2C_SLV2_CTRL = 0x2D
MPU6050_RA_I2C_SLV3_ADDR = 0x2E
MPU6050_RA_I2C_SLV3_REG = 0x2F
MPU6050_RA_I2C_SLV3_CTRL = 0x30
MPU6050_RA_I2C_SLV4_ADDR = 0x31
MPU6050_RA_I2C_SLV4_REG = 0x32
MPU6050_RA_I2C_SLV4_DO = 0x33
MPU6050_RA_I2C_SLV4_CTRL = 0x34
MPU6050_RA_I2C_SLV4_DI = 0x35
MPU6050_RA_I2C_MST_STATUS = 0x36
MPU6050_RA_INT_PIN_CFG = 0x37
MPU6050_RA_INT_ENABLE = 0x38
MPU6050_RA_DMP_INT_STATUS = 0x39
MPU6050_RA_INT_STATUS = 0x3A
MPU6050_RA_ACCEL_XOUT_H = 0x3B
MPU6050_RA_ACCEL_XOUT_L = 0x3C
MPU6050_RA_ACCEL_YOUT_H = 0x3D
MPU6050_RA_ACCEL_YOUT_L = 0x3E
MPU6050_RA_ACCEL_ZOUT_H = 0x3F
MPU6050_RA_ACCEL_ZOUT_L = 0x40
MPU6050_RA_TEMP_OUT_H = 0x41
MPU6050_RA_TEMP_OUT_L = 0x42
MPU6050_RA_GYRO_XOUT_H = 0x43
MPU6050_RA_GYRO_XOUT_L = 0x44
MPU6050_RA_GYRO_YOUT_H = 0x45
MPU6050_RA_GYRO_YOUT_L = 0x46
MPU6050_RA_GYRO_ZOUT_H = 0x47
MPU6050_RA_GYRO_ZOUT_L = 0x48
MPU6050_RA_EXT_SENS_DATA_00 = 0x49
MPU6050_RA_EXT_SENS_DATA_01 = 0x4A
MPU6050_RA_EXT_SENS_DATA_02 = 0x4B
MPU6050_RA_EXT_SENS_DATA_03 = 0x4C
MPU6050_RA_EXT_SENS_DATA_04 = 0x4D
MPU6050_RA_EXT_SENS_DATA_05 = 0x4E
MPU6050_RA_EXT_SENS_DATA_06 = 0x4F
MPU6050_RA_EXT_SENS_DATA_07 = 0x50
MPU6050_RA_EXT_SENS_DATA_08 = 0x51
MPU6050_RA_EXT_SENS_DATA_09 = 0x52
MPU6050_RA_EXT_SENS_DATA_10 = 0x53
MPU6050_RA_EXT_SENS_DATA_11 = 0x54
MPU6050_RA_EXT_SENS_DATA_12 = 0x55
MPU6050_RA_EXT_SENS_DATA_13 = 0x56
MPU6050_RA_EXT_SENS_DATA_14 = 0x57
MPU6050_RA_EXT_SENS_DATA_15 = 0x58
MPU6050_RA_EXT_SENS_DATA_16 = 0x59
MPU6050_RA_EXT_SENS_DATA_17 = 0x5A
MPU6050_RA_EXT_SENS_DATA_18 = 0x5B
MPU6050_RA_EXT_SENS_DATA_19 = 0x5C
MPU6050_RA_EXT_SENS_DATA_20 = 0x5D
MPU6050_RA_EXT_SENS_DATA_21 = 0x5E
MPU6050_RA_EXT_SENS_DATA_22 = 0x5F
MPU6050_RA_EXT_SENS_DATA_23 = 0x60
MPU6050_RA_MOT_DETECT_STATUS = 0x61
MPU6050_RA_I2C_SLV0_DO = 0x63
MPU6050_RA_I2C_SLV1_DO = 0x64
MPU6050_RA_I2C_SLV2_DO = 0x65
MPU6050_RA_I2C_SLV3_DO = 0x66
MPU6050_RA_I2C_MST_DELAY_CTRL = 0x67
MPU6050_RA_SIGNAL_PATH_RESET = 0x68
MPU6050_RA_MOT_DETECT_CTRL = 0x69
MPU6050_RA_USER_CTRL = 0x6A
MPU6050_RA_PWR_MGMT_1 = 0x6B
MPU6050_RA_PWR_MGMT_2 = 0x6C
MPU6050_RA_BANK_SEL = 0x6D
MPU6050_RA_MEM_START_ADDR = 0x6E
MPU6050_RA_MEM_R_W = 0x6F
MPU6050_RA_DMP_CFG_1 = 0x70
MPU6050_RA_DMP_CFG_2 = 0x71
MPU6050_RA_FIFO_COUNTH = 0x72
MPU6050_RA_FIFO_COUNTL = 0x73
MPU6050_RA_FIFO_R_W = 0x74
MPU6050_RA_WHO_AM_I = 0x75
ZeroRegister = [
MPU6050_RA_FF_THR, # Freefall threshold of |0mg| LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_FF_THR, 0x00);
MPU6050_RA_FF_DUR, # Freefall duration limit of 0 LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_FF_DUR, 0x00);
MPU6050_RA_MOT_THR, # Motion threshold of 0mg LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_MOT_THR, 0x00);
MPU6050_RA_MOT_DUR, # Motion duration of 0s LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_MOT_DUR, 0x00);
MPU6050_RA_ZRMOT_THR, # Zero motion threshold LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_ZRMOT_THR, 0x00);
MPU6050_RA_ZRMOT_DUR,
# Zero motion duration threshold LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_ZRMOT_DUR, 0x00);
MPU6050_RA_FIFO_EN,
# Disable sensor output to FIFO buffer LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_FIFO_EN, 0x00);
MPU6050_RA_I2C_MST_CTRL,
# AUX I2C setup //Sets AUX I2C to single master control, plus other config LDByteWriteI2C(
# MPU6050_ADDRESS, MPU6050_RA_I2C_MST_CTRL, 0x00);
MPU6050_RA_I2C_SLV0_ADDR,
# Setup AUX I2C slaves LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV0_ADDR, 0x00);
MPU6050_RA_I2C_SLV0_REG, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV0_REG, 0x00);
MPU6050_RA_I2C_SLV0_CTRL, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV0_CTRL, 0x00);
MPU6050_RA_I2C_SLV1_ADDR, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV1_ADDR, 0x00);
MPU6050_RA_I2C_SLV1_REG, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV1_REG, 0x00);
MPU6050_RA_I2C_SLV1_CTRL, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV1_CTRL, 0x00);
MPU6050_RA_I2C_SLV2_ADDR, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV2_ADDR, 0x00);
MPU6050_RA_I2C_SLV2_REG, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV2_REG, 0x00);
MPU6050_RA_I2C_SLV2_CTRL, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV2_CTRL, 0x00);
MPU6050_RA_I2C_SLV3_ADDR, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV3_ADDR, 0x00);
MPU6050_RA_I2C_SLV3_REG, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV3_REG, 0x00);
MPU6050_RA_I2C_SLV3_CTRL, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV3_CTRL, 0x00);
MPU6050_RA_I2C_SLV4_ADDR, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV4_ADDR, 0x00);
MPU6050_RA_I2C_SLV4_REG, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV4_REG, 0x00);
MPU6050_RA_I2C_SLV4_DO, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV4_DO, 0x00);
MPU6050_RA_I2C_SLV4_CTRL, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV4_CTRL, 0x00);
MPU6050_RA_I2C_SLV4_DI, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV4_DI, 0x00);
MPU6050_RA_INT_PIN_CFG,
# MPU6050_RA_I2C_MST_STATUS //Read-only //Setup INT pin and AUX I2C pass through LDByteWriteI2C(
# MPU6050_ADDRESS, MPU6050_RA_INT_PIN_CFG, 0x00);
MPU6050_RA_INT_ENABLE,
# Enable data ready interrupt LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_INT_ENABLE, 0x00);
MPU6050_RA_I2C_SLV0_DO,
# Slave out, dont care LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV0_DO, 0x00);
MPU6050_RA_I2C_SLV1_DO, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV1_DO, 0x00);
MPU6050_RA_I2C_SLV2_DO, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV2_DO, 0x00);
MPU6050_RA_I2C_SLV3_DO, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV3_DO, 0x00);
MPU6050_RA_I2C_MST_DELAY_CTRL,
# More slave config LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_MST_DELAY_CTRL, 0x00);
MPU6050_RA_SIGNAL_PATH_RESET,
# Reset sensor signal paths LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_SIGNAL_PATH_RESET, 0x00);
MPU6050_RA_MOT_DETECT_CTRL,
# Motion detection control LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_MOT_DETECT_CTRL, 0x00);
MPU6050_RA_USER_CTRL,
# Disables FIFO, AUX I2C, FIFO and I2C reset bits to 0 LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_USER_CTRL,
# 0x00);
MPU6050_RA_CONFIG, # Disable FSync, 256Hz DLPF LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_CONFIG, 0x00);
MPU6050_RA_FF_THR, # Freefall threshold of |0mg| LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_FF_THR, 0x00);
MPU6050_RA_FF_DUR, # Freefall duration limit of 0 LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_FF_DUR, 0x00);
MPU6050_RA_MOT_THR, # Motion threshold of 0mg LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_MOT_THR, 0x00);
MPU6050_RA_MOT_DUR, # Motion duration of 0s LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_MOT_DUR, 0x00);
MPU6050_RA_ZRMOT_THR, # Zero motion threshold LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_ZRMOT_THR, 0x00);
MPU6050_RA_ZRMOT_DUR,
# Zero motion duration threshold LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_ZRMOT_DUR, 0x00);
MPU6050_RA_FIFO_EN,
# Disable sensor output to FIFO buffer LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_FIFO_EN, 0x00);
MPU6050_RA_I2C_MST_CTRL,
# AUX I2C setup //Sets AUX I2C to single master control, plus other config LDByteWriteI2C(
# MPU6050_ADDRESS, MPU6050_RA_I2C_MST_CTRL, 0x00);
MPU6050_RA_I2C_SLV0_ADDR,
# Setup AUX I2C slaves LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV0_ADDR, 0x00);
MPU6050_RA_I2C_SLV0_REG, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV0_REG, 0x00);
MPU6050_RA_I2C_SLV0_CTRL, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV0_CTRL, 0x00);
MPU6050_RA_I2C_SLV1_ADDR, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV1_ADDR, 0x00);
MPU6050_RA_I2C_SLV1_REG, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV1_REG, 0x00);
MPU6050_RA_I2C_SLV1_CTRL, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV1_CTRL, 0x00);
MPU6050_RA_I2C_SLV2_ADDR, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV2_ADDR, 0x00);
MPU6050_RA_I2C_SLV2_REG, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV2_REG, 0x00);
MPU6050_RA_I2C_SLV2_CTRL, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV2_CTRL, 0x00);
MPU6050_RA_I2C_SLV3_ADDR, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV3_ADDR, 0x00);
MPU6050_RA_I2C_SLV3_REG, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV3_REG, 0x00);
MPU6050_RA_I2C_SLV3_CTRL, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV3_CTRL, 0x00);
MPU6050_RA_I2C_SLV4_ADDR, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV4_ADDR, 0x00);
MPU6050_RA_I2C_SLV4_REG, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV4_REG, 0x00);
MPU6050_RA_I2C_SLV4_DO, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV4_DO, 0x00);
MPU6050_RA_I2C_SLV4_CTRL, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV4_CTRL, 0x00);
MPU6050_RA_I2C_SLV4_DI, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV4_DI, 0x00);
MPU6050_RA_I2C_SLV0_DO,
# Slave out, dont care LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV0_DO, 0x00);
MPU6050_RA_I2C_SLV1_DO, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV1_DO, 0x00);
MPU6050_RA_I2C_SLV2_DO, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV2_DO, 0x00);
MPU6050_RA_I2C_SLV3_DO, # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_SLV3_DO, 0x00);
MPU6050_RA_I2C_MST_DELAY_CTRL,
# More slave config LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_I2C_MST_DELAY_CTRL, 0x00);
MPU6050_RA_SIGNAL_PATH_RESET,
# Reset sensor signal paths LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_SIGNAL_PATH_RESET, 0x00);
MPU6050_RA_MOT_DETECT_CTRL,
# Motion detection control LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_MOT_DETECT_CTRL, 0x00);
MPU6050_RA_USER_CTRL,
# Disables FIFO, AUX I2C, FIFO and I2C reset bits to 0 LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_USER_CTRL,
# 0x00);
MPU6050_RA_INT_PIN_CFG,
# MPU6050_RA_I2C_MST_STATUS //Read-only //Setup INT pin and AUX I2C pass through LDByteWriteI2C(
# MPU6050_ADDRESS, MPU6050_RA_INT_PIN_CFG, 0x00);
MPU6050_RA_INT_ENABLE,
# Enable data ready interrupt LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_INT_ENABLE, 0x00);
MPU6050_RA_FIFO_R_W] # LDByteWriteI2C(MPU6050_ADDRESS, MPU6050_RA_FIFO_R_W, 0x00);
def __init__(self, i2c_io, fs=None, name='mpu6050', samplesPerBatch=None, dataHandler=None):
"""
initialises to a default state set to measure acceleration only.
"""
super().__init__(fs, samplesPerBatch, dataHandler)
self.name = name
self.fifoSensorMask = self.enableAccelerometerMask
self._accelEnabled = True
self._gyroEnabled = False
self._setSampleSizeBytes()
self.accelerometerSensitivity = DEFAULT_ACCELEROMETER_SENSITIVITY
self.gyroSensitivity = DEFAULT_GYRO_SENSITIVITY
self._accelerationFactor = self.accelerometerSensitivity / SENSOR_SCALE_FACTOR
self._gyroFactor = self.gyroSensitivity / SENSOR_SCALE_FACTOR
self.i2c_io = i2c_io
self.doInit()
def _setSampleSizeBytes(self):
"""
updates the current record of the packet size per sample and the relationship between this and the fifo reads.
"""
self.sampleSizeBytes = self.getPacketSize()
if self.sampleSizeBytes > 0:
self.maxBytesPerFifoRead = (32 // self.sampleSizeBytes)
def getPacketSize(self):
"""
the current packet size.
:return: the current packet size based on the enabled registers.
"""
size = 0
if self.isAccelerometerEnabled():
size += 6
if self.isGyroEnabled():
size += 6
if self.isTemperatureEnabled():
size += 2
return size
def initialiseDevice(self):
"""
performs initialisation of the device
:param batchSize: the no of samples that each provideData call should yield
:return:
"""
logger.debug("Initialising device")
self.getInterruptStatus()
self.setAccelerometerSensitivity(self._accelerationFactor * 32768.0)
self.setGyroSensitivity(self._gyroFactor * 32768.0)
self.setSampleRate(self.fs)
for loop in self.ZeroRegister:
self.i2c_io.write(self.MPU6050_ADDRESS, loop, 0)
# Sets clock source to gyro reference w/ PLL
self.i2c_io.write(self.MPU6050_ADDRESS, self.MPU6050_RA_PWR_MGMT_1, 0b00000010)
# Controls frequency of wakeups in accel low power mode plus the sensor standby modes
self.i2c_io.write(self.MPU6050_ADDRESS, self.MPU6050_RA_PWR_MGMT_2, 0x00)
# Enables any I2C master interrupt source to generate an interrupt
self.i2c_io.write(self.MPU6050_ADDRESS, self.MPU6050_RA_INT_ENABLE, 0x01)
# enable the FIFO
self.enableFifo()
logger.debug("Initialised device")
def isAccelerometerEnabled(self):
"""
tests whether acceleration is currently enabled
:return: true if it is
"""
return (self.fifoSensorMask & self.enableAccelerometerMask) == self.enableAccelerometerMask
def enableAccelerometer(self):
"""
Specifies the device should write acceleration values to the FIFO, is not applied until enableFIFO is called.
:return:
"""
logger.debug("Enabling acceleration sensor")
self.fifoSensorMask |= self.enableAccelerometerMask
self._accelEnabled = True
self._setSampleSizeBytes()
def disableAccelerometer(self):
"""
Specifies the device should NOT write acceleration values to the FIFO, is not applied until enableFIFO is
called.
:return:
"""
logger.debug("Disabling acceleration sensor")
self.fifoSensorMask &= ~self.enableAccelerometerMask
self._accelEnabled = False
self._setSampleSizeBytes()
def isGyroEnabled(self):
"""
tests whether gyro is currently enabled
:return: true if it is
"""
return (self.fifoSensorMask & self.enableGyroMask) == self.enableGyroMask
def enableGyro(self):
"""
Specifies the device should write gyro values to the FIFO, is not applied until enableFIFO is called.
:return:
"""
logger.debug("Enabling gyro sensor")
self.fifoSensorMask |= self.enableGyroMask
self._gyroEnabled = True
self._setSampleSizeBytes()
def disableGyro(self):
"""
Specifies the device should NOT write gyro values to the FIFO, is not applied until enableFIFO is called.
:return:
"""
logger.debug("Disabling gyro sensor")
self.fifoSensorMask &= ~self.enableGyroMask
self._gyroEnabled = False
self._setSampleSizeBytes()
def isTemperatureEnabled(self):
"""
tests whether temperature is currently enabled
:return: true if it is
"""
return (self.fifoSensorMask & self.enableTemperatureMask) == self.enableTemperatureMask
def enableTemperature(self):
"""
Specifies the device should write temperature values to the FIFO, is not applied until enableFIFO is called.
:return:
"""
logger.debug("Enabling temperature sensor")
self.fifoSensorMask |= self.enableTemperatureMask
self._setSampleSizeBytes()
def disableTemperature(self):
"""
Specifies the device should NOT write temperature values to the FIFO, is not applied until enableFIFO is called.
:return:
"""
logger.debug("Disabling temperature sensor")
self.fifoSensorMask &= ~self.enableTemperatureMask
self._setSampleSizeBytes()
def setGyroSensitivity(self, value):
"""
Sets the gyro sensitivity to 250, 500, 1000 or 2000 according to the given value (and implicitly disables the
self
tests)
:param value: the target sensitivity.
"""
try:
self.i2c_io.write(self.MPU6050_ADDRESS, self.MPU6050_RA_GYRO_CONFIG,
{250: 0, 500: 8, 1000: 16, 2000: 24}[value])
self._gyroFactor = value / 32768.0
self.gyroSensitivity = value
logger.debug("Set gyro sensitivity = %d", value)
except KeyError:
raise ArgumentError(value + " is not a valid sensitivity (250,500,1000,2000)")
def setAccelerometerSensitivity(self, value):
"""
Sets the accelerometer sensitivity to 2, 4, 8 or 16 according to the given value. Throws an ArgumentError if
the value provided is not valid.
:param value: the target sensitivity.
"""
# note that this implicitly disables the self tests on each axis
# i.e. the full byte is actually 000[accel]000 where the 1st 3 are the accelerometer self tests, the next two
# values are the actual sensitivity and the last 3 are unused
# the 2 [accel] bits are translated by the device as follows; 00 = 2g, 01 = 4g, 10 = 8g, 11 = 16g
# in binary we get 2 = 0, 4 = 1000, 8 = 10000, 16 = 11000
# so the 1st 3 bits are always 0
try:
self.i2c_io.write(self.MPU6050_ADDRESS,
self.MPU6050_RA_ACCEL_CONFIG,
{2: 0, 4: 8, 8: 16, 16: 24}[value])
self._accelerationFactor = value / 32768.0
self.accelerometerSensitivity = value
logger.debug("Set accelerometer sensitivity = %d", value)
except KeyError:
raise ArgumentError(value + " is not a valid sensitivity (2,4,8,18)")
def setSampleRate(self, targetSampleRate):
"""
Sets the internal sample rate of the MPU-6050, this requires writing a value to the device to set the sample
rate as Gyroscope Output Rate / (1 + SMPLRT_DIV) where the gryoscope outputs at 8kHz and the peak sampling rate
is 1kHz. The target sample rate is therefore capped at 1kHz.
:param targetSampleRate: the target sample rate.
:return:
"""
sampleRateDenominator = int((8000 / min(targetSampleRate, 1000)) - 1)
self.i2c_io.write(self.MPU6050_ADDRESS, self.MPU6050_RA_SMPLRT_DIV, sampleRateDenominator)
self.fs = 8000.0 / (sampleRateDenominator + 1.0)
logger.debug("Set sample rate = %d", self.fs)
def resetFifo(self):
"""
Resets the FIFO by first disabling the FIFO then sending a FIFO_RESET and then re-enabling the FIFO.
:return:
"""
logger.debug("Resetting FIFO")
self.i2c_io.write(self.MPU6050_ADDRESS, self.MPU6050_RA_USER_CTRL, 0b00000000)
pass
self.i2c_io.write(self.MPU6050_ADDRESS, self.MPU6050_RA_USER_CTRL, 0b00000100)
pass
self.i2c_io.write(self.MPU6050_ADDRESS, self.MPU6050_RA_USER_CTRL, 0b01000000)
self.getInterruptStatus()
def enableFifo(self):
"""
Enables the FIFO, resets it and then sets which values should be written to the FIFO.
:return:
"""
logger.debug("Enabling FIFO")
self.i2c_io.write(self.MPU6050_ADDRESS, self.MPU6050_RA_FIFO_EN, 0)
self.resetFifo()
self.i2c_io.write(self.MPU6050_ADDRESS, self.MPU6050_RA_FIFO_EN, self.fifoSensorMask)
logger.debug("Enabled FIFO")
def getInterruptStatus(self):
"""
reads and clears the current interrupt status. The byte that can be read is
0b00010000 = FIFO_OFLOW_INT = FIFO has overflowed
0b00001000 = I2C_MST_INT = I2C master interrupt has fired
0b00000001 = DATA_RDY_INT = data is available to read
"""
return self.i2c_io.read(self.MPU6050_ADDRESS, self.MPU6050_RA_INT_STATUS)
def getFifoCount(self):
"""
gets the amount of data available on the FIFO right now.
:return: the number of bytes available on the FIFO which will be proportional to the number of samples available
based on the values the device is configured to sample.
"""
bytes = self.i2c_io.readBlock(self.MPU6050_ADDRESS, self.MPU6050_RA_FIFO_COUNTH, 2)
count = (bytes[0] << 8) + bytes[1]
logger.debug("FIFO Count: %d", count)
return count
def getDataFromFIFO(self, bytesToRead):
"""
reads the specified number of bytes from the FIFO, should be called after a call to getFifoCount to ensure there
is new data available (to avoid reading duplicate data).
:param bytesToRead: the number of bytes to read.
:return: the bytes read.
"""
return self.i2c_io.readBlock(self.MPU6050_ADDRESS, self.MPU6050_RA_FIFO_R_W, bytesToRead)
def provideData(self):
"""
reads a batchSize batch of data from the FIFO while attempting to optimise the number of times we have to read
from the device itself.
:return: a list of data where each item is a single sample of data converted into real values and stored as a
dict.
"""
samples = []
fifoBytesAvailable = 0
fifoWasReset = False
logger.debug(">> provideData target %d samples", self.samplesPerBatch)
iterations = 0
# allow 1.5x the expected duration of the batch
breakTime = time() + ((self.samplesPerBatch / self.fs) * 1.5)
overdue = False
while len(samples) < self.samplesPerBatch and not overdue:
iterations += 1
if iterations > self.samplesPerBatch and iterations % 100 == 0:
if time() > breakTime:
logger.warning("Breaking measurement after %d iterations, batch overdue", iterations)
overdue = True
if fifoBytesAvailable < self.sampleSizeBytes or fifoWasReset:
interrupt = self.getInterruptStatus()
fifoBytesAvailable = self.getFifoCount()
fifoWasReset = False
logger.debug("Start sample loop [available: %d , required: %d]", fifoBytesAvailable, self.sampleSizeBytes)
if interrupt & 0x10:
logger.error("FIFO OVERFLOW, RESETTING [available: %d , interrupt: %d]", fifoBytesAvailable, interrupt)
self.measurementOverflowed = True
self.resetFifo()
fifoWasReset = True
elif fifoBytesAvailable == 1024:
logger.error("FIFO FULL, RESETTING [available: %d , interrupt: %d]", fifoBytesAvailable, interrupt)
self.measurementOverflowed = True
self.resetFifo()
fifoWasReset = True
elif interrupt & 0x02 or interrupt & 0x01:
# wait for at least 1 sample to arrive, should be a VERY short wait
while fifoBytesAvailable < self.sampleSizeBytes:
logger.debug("Waiting for sample [available: %d , required: %d]", fifoBytesAvailable,
self.sampleSizeBytes)
fifoBytesAvailable = self.getFifoCount()
logger.debug("Processing data [available: %d , required: %d]", fifoBytesAvailable, self.sampleSizeBytes)
fifoReadBytes = self.sampleSizeBytes
# TODO this chunk of code is a bit messy, tidy it up
# if we have more than 1 sample available then ensure we read as many as we can at once (albeit within
# the limits of the max i2c read size of 32 bytes)
if fifoBytesAvailable > self.sampleSizeBytes:
fifoReadBytes = min(fifoBytesAvailable // self.sampleSizeBytes,
self.maxBytesPerFifoRead) * self.sampleSizeBytes
logger.debug("Excess bytes to read [available: %d , reading: %d]", fifoBytesAvailable,
fifoReadBytes)
# but don't read more than we need to fulfil the batch
samplesToRead = fifoReadBytes // self.sampleSizeBytes
excessSamples = self.samplesPerBatch - len(samples) - samplesToRead
if excessSamples < 0:
samplesToRead += excessSamples
fifoReadBytes = int(samplesToRead * self.sampleSizeBytes)
logger.debug("Excess samples to read [available: %d , reading: %d]", fifoBytesAvailable,
fifoReadBytes)
else:
logger.debug("Reading [available: %d , reading: %d]", fifoBytesAvailable, fifoReadBytes)
# read the bytes from the fifo, break it into sample sized chunks and convert to the actual values
fifoBytes = self.getDataFromFIFO(fifoReadBytes)
samples.extend([self.unpackSample(fifoBytes[i:i + self.sampleSizeBytes])
for i in range(0, len(fifoBytes), self.sampleSizeBytes)])
# track the count here so we can avoid going back to the FIFO each time
fifoBytesAvailable -= fifoReadBytes
logger.debug("End sample loop [available: %d , required: %d]", fifoBytesAvailable, self.sampleSizeBytes)
logger.debug("<< provideData %d samples", len(samples))
return samples
def unpackSample(self, rawData):
"""
unpacks a single sample of data (where sample length is based on the currently enabled sensors).
:param rawData: the data to convert
:return: a converted data set.
"""
length = len(rawData)
# TODO error if not multiple of 2
# logger.debug(">> unpacking sample %d length %d", self._sampleIdx, length)
unpacked = struct.unpack(">" + ('h' * (length // 2)), memoryview(bytearray(rawData)).tobytes())
# store the data in a dictionary
mpu6050 = collections.OrderedDict()
mpu6050[SAMPLE_TIME] = self._sampleIdx / self.fs
sensorIdx = 0
if self.isAccelerometerEnabled():
mpu6050[ACCEL_X] = unpacked[sensorIdx] * self._accelerationFactor
sensorIdx += 1
mpu6050[ACCEL_Y] = unpacked[sensorIdx] * self._accelerationFactor
sensorIdx += 1
mpu6050[ACCEL_Z] = unpacked[sensorIdx] * self._accelerationFactor
sensorIdx += 1
if self.isTemperatureEnabled():
mpu6050[TEMP] = unpacked[sensorIdx] * self._temperatureGain + self._temperatureOffset
sensorIdx += 1
if self.isGyroEnabled():
mpu6050[GYRO_X] = unpacked[sensorIdx] * self._gyroFactor
sensorIdx += 1
mpu6050[GYRO_Y] = unpacked[sensorIdx] * self._gyroFactor
sensorIdx += 1
mpu6050[GYRO_Z] = unpacked[sensorIdx] * self._gyroFactor
sensorIdx += 1
# TODO should we send as a dict so the keys are available?
output = list(mpu6050.values())
self._sampleIdx += 1
# logger.debug("<< unpacked sample length %d into vals size %d", length, len(output))
return output
def performSelfTest(self):
"""
performs a self calibration against factory settings.
:return:
boolean: true if all sensors pass self test
dictionary: all underlying percentage deviations, +/-14% is a pass
"""
try:
logger.debug(">> selfTest")
# enable self test on all axes and set range to +/-250
self.i2c_io.write(self.MPU6050_ADDRESS, self.MPU6050_RA_GYRO_CONFIG, 0b11100000)
# enable self test on all axes and set range to +/-8g
self.i2c_io.write(self.MPU6050_ADDRESS, self.MPU6050_RA_ACCEL_CONFIG, 0b11110000)
# sleep to let the test run
sleep(0.5)
# read the resulting raw data
rawData = [self.i2c_io.read(self.MPU6050_ADDRESS, 0x0D),
self.i2c_io.read(self.MPU6050_ADDRESS, 0x0E),
self.i2c_io.read(self.MPU6050_ADDRESS, 0x0F),
self.i2c_io.read(self.MPU6050_ADDRESS, 0x10)]
# each value is a 5 bit unsigned int that packs in both gyro and acceleration results
# acceleration is in bits 5-7
acceleration = {
'x': (rawData[0] >> 3) | (rawData[3] & 0x30) >> 4,
'y': (rawData[1] >> 3) | (rawData[3] & 0x0C) >> 4,
'z': (rawData[2] >> 3) | (rawData[3] & 0x03) >> 4
}
# calculate results
factoryTrimAcceleration = {
'x': (4096.0 * 0.34) * (pow((0.92 / 0.34), ((acceleration['x'] - 1.0) / 30.0))),
'y': (4096.0 * 0.34) * (pow((0.92 / 0.34), ((acceleration['y'] - 1.0) / 30.0))),
'z': (4096.0 * 0.34) * (pow((0.92 / 0.34), ((acceleration['z'] - 1.0) / 30.0)))
}
# gyro is in bits 0-4
gyro = {
'x': rawData[0] & 0x1F,
'y': rawData[1] & 0x1F,
'z': rawData[2] & 0x1F
}
# calculate results
factoryTrimGyro = {
'x': (25.0 * 131.0) * (pow(1.046, (gyro['x'] - 1.0))),
'y': (-25.0 * 131.0) * (pow(1.046, (gyro['y'] - 1.0))),
'z': (25.0 * 131.0) * (pow(1.046, (gyro['z'] - 1.0)))
}
# percent diffs
results = {}
for axis in ['x', 'y', 'z']:
results['a' + axis] = 100.0 + 100.0 * (acceleration[axis] - factoryTrimAcceleration[axis]) / \
factoryTrimAcceleration[axis]
results['g' + axis] = 100.0 + 100.0 * (gyro[axis] - factoryTrimGyro[axis]) / factoryTrimGyro[axis]
passed = all(abs(v) < 14 for v in results.values())
if passed:
logger.debug("self test passed")
else:
logger.error("SELF TEST FAILURE " + str(results))
return passed, results
finally:
self.setAccelerometerSensitivity(self.accelerometerSensitivity)
self.setGyroSensitivity(self.gyroSensitivity)
logger.debug("<< selfTest")
|
class mpu6050(Accelerometer):
'''
Controls the Invensense MPU-6050, code based on danjperron's https://github.com/danjperron/mpu6050TestInC
'''
def __init__(self, i2c_io, fs=None, name='mpu6050', samplesPerBatch=None, dataHandler=None):
'''
initialises to a default state set to measure acceleration only.
'''
pass
def _setSampleSizeBytes(self):
'''
updates the current record of the packet size per sample and the relationship between this and the fifo reads.
'''
pass
def getPacketSize(self):
'''
the current packet size.
:return: the current packet size based on the enabled registers.
'''
pass
def initialiseDevice(self):
'''
performs initialisation of the device
:param batchSize: the no of samples that each provideData call should yield
:return:
'''
pass
def isAccelerometerEnabled(self):
'''
tests whether acceleration is currently enabled
:return: true if it is
'''
pass
def enableAccelerometer(self):
'''
Specifies the device should write acceleration values to the FIFO, is not applied until enableFIFO is called.
:return:
'''
pass
def disableAccelerometer(self):
'''
Specifies the device should NOT write acceleration values to the FIFO, is not applied until enableFIFO is
called.
:return:
'''
pass
def isGyroEnabled(self):
'''
tests whether gyro is currently enabled
:return: true if it is
'''
pass
def enableGyro(self):
'''
Specifies the device should write gyro values to the FIFO, is not applied until enableFIFO is called.
:return:
'''
pass
def disableGyro(self):
'''
Specifies the device should NOT write gyro values to the FIFO, is not applied until enableFIFO is called.
:return:
'''
pass
def isTemperatureEnabled(self):
'''
tests whether temperature is currently enabled
:return: true if it is
'''
pass
def enableTemperature(self):
'''
Specifies the device should write temperature values to the FIFO, is not applied until enableFIFO is called.
:return:
'''
pass
def disableTemperature(self):
'''
Specifies the device should NOT write temperature values to the FIFO, is not applied until enableFIFO is called.
:return:
'''
pass
def setGyroSensitivity(self, value):
'''
Sets the gyro sensitivity to 250, 500, 1000 or 2000 according to the given value (and implicitly disables the
self
tests)
:param value: the target sensitivity.
'''
pass
def setAccelerometerSensitivity(self, value):
'''
Sets the accelerometer sensitivity to 2, 4, 8 or 16 according to the given value. Throws an ArgumentError if
the value provided is not valid.
:param value: the target sensitivity.
'''
pass
def setSampleRate(self, targetSampleRate):
'''
Sets the internal sample rate of the MPU-6050, this requires writing a value to the device to set the sample
rate as Gyroscope Output Rate / (1 + SMPLRT_DIV) where the gryoscope outputs at 8kHz and the peak sampling rate
is 1kHz. The target sample rate is therefore capped at 1kHz.
:param targetSampleRate: the target sample rate.
:return:
'''
pass
def resetFifo(self):
'''
Resets the FIFO by first disabling the FIFO then sending a FIFO_RESET and then re-enabling the FIFO.
:return:
'''
pass
def enableFifo(self):
'''
Enables the FIFO, resets it and then sets which values should be written to the FIFO.
:return:
'''
pass
def getInterruptStatus(self):
'''
reads and clears the current interrupt status. The byte that can be read is
0b00010000 = FIFO_OFLOW_INT = FIFO has overflowed
0b00001000 = I2C_MST_INT = I2C master interrupt has fired
0b00000001 = DATA_RDY_INT = data is available to read
'''
pass
def getFifoCount(self):
'''
gets the amount of data available on the FIFO right now.
:return: the number of bytes available on the FIFO which will be proportional to the number of samples available
based on the values the device is configured to sample.
'''
pass
def getDataFromFIFO(self, bytesToRead):
'''
reads the specified number of bytes from the FIFO, should be called after a call to getFifoCount to ensure there
is new data available (to avoid reading duplicate data).
:param bytesToRead: the number of bytes to read.
:return: the bytes read.
'''
pass
def provideData(self):
'''
reads a batchSize batch of data from the FIFO while attempting to optimise the number of times we have to read
from the device itself.
:return: a list of data where each item is a single sample of data converted into real values and stored as a
dict.
'''
pass
def unpackSample(self, rawData):
'''
unpacks a single sample of data (where sample length is based on the currently enabled sensors).
:param rawData: the data to convert
:return: a converted data set.
'''
pass
def performSelfTest(self):
'''
performs a self calibration against factory settings.
:return:
boolean: true if all sensors pass self test
dictionary: all underlying percentage deviations, +/-14% is a pass
'''
pass
| 25 | 25 | 17 | 0 | 10 | 6 | 2 | 0.55 | 1 | 9 | 0 | 0 | 24 | 13 | 24 | 30 | 649 | 31 | 438 | 184 | 413 | 243 | 333 | 184 | 308 | 11 | 2 | 3 | 46 |
732 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/core/reactor.py
|
reactor.Reactor
|
class Reactor(object):
"""
Kicks off the thread which accepts requests on the queue where each request is a 2 item tuple ( request type,
tuple of args )
"""
def __init__(self, name='reactor', threads=1):
self._workQueue = Queue()
self._name = name
self._funcsByRequest = {}
self.running = True
for i in range(threads):
t = Thread(name=name + "_" + str(i), target=self._accept, daemon=True)
t.start()
def _accept(self):
"""
Work loop runs forever (or until running is False)
:return:
"""
logger.warning("Reactor " + self._name + " is starting")
while self.running:
try:
self._completeTask()
except:
logger.exception("Unexpected exception during request processing")
logger.warning("Reactor " + self._name + " is terminating")
def _completeTask(self):
req = self._workQueue.get()
if req is not None:
try:
logger.debug("Processing " + req[0])
func = self._funcsByRequest.get(req[0])
if func is not None:
func(*req[1])
else:
logger.error("Ignoring unknown request on reactor " + self._name + " " + req[0])
finally:
self._workQueue.task_done()
def register(self, requestType, function):
"""
Registers a new function to handle the given request type.
:param requestType:
:param function:
:return:
"""
self._funcsByRequest[requestType] = function
def offer(self, requestType, *args):
"""
public interface to the reactor.
:param requestType:
:param args:
:return:
"""
if self._funcsByRequest.get(requestType) is not None:
self._workQueue.put((requestType, list(*args)))
else:
logger.error("Ignoring unknown request on reactor " + self._name + " " + requestType)
|
class Reactor(object):
'''
Kicks off the thread which accepts requests on the queue where each request is a 2 item tuple ( request type,
tuple of args )
'''
def __init__(self, name='reactor', threads=1):
pass
def _accept(self):
'''
Work loop runs forever (or until running is False)
:return:
'''
pass
def _completeTask(self):
pass
def register(self, requestType, function):
'''
Registers a new function to handle the given request type.
:param requestType:
:param function:
:return:
'''
pass
def offer(self, requestType, *args):
'''
public interface to the reactor.
:param requestType:
:param args:
:return:
'''
pass
| 6 | 4 | 10 | 0 | 7 | 3 | 2 | 0.56 | 1 | 5 | 0 | 0 | 5 | 4 | 5 | 5 | 61 | 5 | 36 | 14 | 30 | 20 | 33 | 14 | 27 | 3 | 1 | 3 | 11 |
733 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/analyser/common/measurementcontroller.py
|
measurementcontroller.MeasurementController
|
class MeasurementController(object):
"""
Contains all the logic around measurement scheduling and is responsible for ensuring we have valid measurements
only.
"""
def __init__(self, targetStateProvider, dataDir, deviceController, maxTimeTilDeathbedSeconds=30,
maxTimeOnDeathbedSeconds=120):
self.targetStateProvider = targetStateProvider
self.deviceController = deviceController
self.dataDir = dataDir
self.activeMeasurements = []
self.completeMeasurements = []
self.failedMeasurements = []
self.deathBed = {}
self.reloadCompletedMeasurements()
self.maxTimeTilDeathbedSeconds = maxTimeTilDeathbedSeconds
self.maxTimeOnDeathbedSeconds = maxTimeOnDeathbedSeconds
self.running = True
self.worker = threading.Thread(name='MeasurementCaretaker', target=self._sweep, daemon=True)
self.worker.start()
def shutdown(self):
logger.warning("Shutting down the MeasurementCaretaker")
self.running = False
def _sweep(self):
"""
Checks the state of each measurement and verifies their state, if an active measurement is now complete then
passes them to the completed measurement set, if failed then to the failed set, if failed and old then evicts.
:return:
"""
while self.running:
for am in list(self.activeMeasurements):
now = datetime.datetime.utcnow()
# devices were allocated and have completed == complete
recordingDeviceCount = len(am.recordingDevices)
if recordingDeviceCount > 0:
if all(entry['state'] == RecordStatus.COMPLETE.name for entry in am.recordingDevices.values()):
logger.info("Detected completedmeasurement " + am.id)
self._moveToComplete(am)
# we have reached the end time and we have either all failed devices or no devices == kill
if now > (am.endTime + datetime.timedelta(days=0, seconds=1)):
allFailed = all(entry['state'] == RecordStatus.FAILED.name
for entry in am.recordingDevices.values())
if (recordingDeviceCount > 0 and allFailed) or recordingDeviceCount == 0:
logger.warning("Detected failed measurement " + am.id + " with " + str(recordingDeviceCount)
+ " devices, allFailed: " + str(allFailed))
self._moveToFailed(am)
# we are well past the end time and we have failed devices or an ongoing recording == kill or deathbed
if now > (am.endTime + datetime.timedelta(days=0, seconds=self.maxTimeTilDeathbedSeconds)):
if any(entry['state'] == RecordStatus.FAILED.name for entry in am.recordingDevices.values()):
logger.warning("Detected failed and incomplete measurement " + am.id + ", assumed dead")
self._moveToFailed(am)
elif all(entry['state'] == RecordStatus.RECORDING.name for entry in am.recordingDevices.values()):
self._handleDeathbed(am)
time.sleep(0.1)
logger.warning("MeasurementCaretaker is now shutdown")
def _handleDeathbed(self, am):
# check if in the deathbed, if not add it
now = datetime.datetime.utcnow()
if am in self.deathBed.keys():
# if it is, check if it's been there for too long
if now > (self.deathBed[am] + datetime.timedelta(days=0, seconds=self.maxTimeOnDeathbedSeconds)):
logger.warning(am.id + " has been on the deathbed since " +
self.deathBed[am].strftime(DATETIME_FORMAT) + ", max time allowed is " +
str(self.maxTimeOnDeathbedSeconds) + ", evicting")
# ensure all recording devices that have not completed are marked as failed
for deviceName, status in am.recordingDevices.items():
if status['state'] == RecordStatus.RECORDING.name or status['state'] == RecordStatus.SCHEDULED.name:
logger.warning("Marking " + deviceName + " as failed due to deathbed eviction")
if not self.failMeasurement(am.id, deviceName, failureReason='Evicting from deathbed'):
logger.warning("Failed to mark " + deviceName + " as failed")
self._moveToFailed(am)
del self.deathBed[am]
else:
logger.warning(am.id + " was expected to finish at " +
am.endTime.strftime(DATETIME_FORMAT) + ", adding to deathbed")
am.status = MeasurementStatus.DYING
self.deathBed.update({am: now})
def _moveToComplete(self, am):
am.status = MeasurementStatus.COMPLETE
self.activeMeasurements.remove(am)
self.completeMeasurements.append(CompleteMeasurement(self.store(am), self.dataDir))
def _moveToFailed(self, am):
am.status = MeasurementStatus.FAILED
self.activeMeasurements.remove(am)
self.failedMeasurements.append(am)
self.store(am)
def schedule(self, name, duration, startTime, description=None):
"""
Schedules a new measurement with the given name.
:param name:
:param duration:
:param startTime:
:param description:
:return: a tuple
boolean: measurement was scheduled if true
message: description, generally only used as an error code
"""
if self._clashes(startTime, duration):
return False, MEASUREMENT_TIMES_CLASH
else:
am = ActiveMeasurement(name, startTime, duration, self.targetStateProvider.state, description=description)
logger.info("Scheduling measurement " + am.id + " for " + str(duration) + "s")
self.activeMeasurements.append(am)
devices = self.deviceController.scheduleMeasurement(am.id, am.duration, am.startTime)
anyFail = False
for device, status in devices.items():
if status == 200:
deviceStatus = RecordStatus.SCHEDULED
else:
deviceStatus = RecordStatus.FAILED
anyFail = True
am.updateDeviceStatus(device.deviceId, deviceStatus)
if anyFail:
am.status = MeasurementStatus.FAILED
else:
if am.status is MeasurementStatus.NEW:
am.status = MeasurementStatus.SCHEDULED
return True, None
def _clashes(self, startTime, duration):
"""
verifies that this measurement does not clash with an already scheduled measurement.
:param startTime: the start time.
:param duration: the duration.
:return: true if the measurement is allowed.
"""
return [m for m in self.activeMeasurements if m.overlapsWith(startTime, duration)]
def startMeasurement(self, measurementId, deviceId):
"""
Starts the measurement for the device.
:param deviceId: the device that is starting.
:param measurementId: the measurement that is started.
:return: true if it started (i.e. device and measurement exists).
"""
am, handler = self.getDataHandler(measurementId, deviceId)
if am is not None:
am.status = MeasurementStatus.RECORDING
am.updateDeviceStatus(deviceId, RecordStatus.RECORDING)
handler.start(am.idAsPath)
return True
else:
return False
def getDataHandler(self, measurementId, deviceId):
"""
finds the handler.
:param measurementId: the measurement
:param deviceId: the device.
:return: active measurement and handler
"""
am = next((m for m in self.activeMeasurements if m.id == measurementId), None)
if am is None:
return None, None
else:
device = self.deviceController.getDevice(deviceId)
if device is None:
return None, None
else:
return am, device.dataHandler
def recordData(self, measurementId, deviceId, data):
"""
Passes the data to the handler.
:param deviceId: the device the data comes from.
:param measurementId: the measurement id.
:param data: the data.
:return: true if the data was handled.
"""
am, handler = self.getDataHandler(measurementId, deviceId)
if handler is not None:
am.stillRecording(deviceId, len(data))
handler.handle(data)
return True
else:
logger.error('Received data for unknown handler ' + deviceId + '/' + measurementId)
return False
def completeMeasurement(self, measurementId, deviceId):
"""
Completes the measurement session.
:param deviceId: the device id.
:param measurementId: the measurement id.
:return: true if it was completed.
"""
am, handler = self.getDataHandler(measurementId, deviceId)
if handler is not None:
handler.stop(measurementId)
am.updateDeviceStatus(deviceId, RecordStatus.COMPLETE)
return True
else:
return False
def failMeasurement(self, measurementId, deviceName, failureReason=None):
"""
Fails the measurement session.
:param deviceName: the device name.
:param measurementId: the measurement name.
:param failureReason: why it failed.
:return: true if it was completed.
"""
am, handler = self.getDataHandler(measurementId, deviceName)
if handler is not None:
am.updateDeviceStatus(deviceName, RecordStatus.FAILED, reason=failureReason)
handler.stop(measurementId)
return True
else:
return False
def delete(self, measurementId):
"""
Deletes the named measurement if it exists. If this is an active measurement then the measurement is cancelled.
:param measurementId: the measurement name.
:return:
"""
# TODO cancel active measurement
return self._deleteCompletedMeasurement(measurementId)
def _deleteCompletedMeasurement(self, measurementId):
"""
Deletes the named measurement from the completed measurement store if it exists.
:param measurementId:
:return:
String: error messages
Integer: count of measurements deleted
"""
message, count, deleted = self.deleteFrom(measurementId, self.completeMeasurements)
if count is 0:
message, count, deleted = self.deleteFrom(measurementId, self.failedMeasurements)
return message, count, deleted
def deleteFrom(self, measurementId, data):
toDeleteIdx = [(ind, x) for ind, x in enumerate(data) if x.id == measurementId]
if toDeleteIdx:
errors = []
def logError(func, path, exc_info):
logger.exception(
"Error detected during deletion of measurement " + measurementId + " by " + str(func),
exc_info=exc_info)
errors.append(path)
logger.info("Deleting measurement: " + measurementId)
shutil.rmtree(self._getPathToMeasurementMetaDir(toDeleteIdx[0][1].idAsPath), ignore_errors=False,
onerror=logError)
if len(errors) is 0:
popped = data.pop(toDeleteIdx[0][0])
return None, 1 if popped else 0, popped
else:
return errors, 0, None
else:
return measurementId + " does not exist", 0, None
def reloadCompletedMeasurements(self):
"""
Reloads the completed measurements from the backing store.
"""
from pathlib import Path
reloaded = [self.load(x.resolve()) for x in Path(self.dataDir).glob('*/*/*') if x.is_dir()]
logger.info('Reloaded ' + str(len(reloaded)) + ' completed measurements')
self.completeMeasurements = [x for x in reloaded if x is not None and x.status == MeasurementStatus.COMPLETE]
self.failedMeasurements = [x for x in reloaded if x is not None and x.status == MeasurementStatus.FAILED]
def getMeasurements(self, measurementStatus=None):
"""
Gets all available measurements.
:param measurementStatus return only the measurements in the given state.
:return:
"""
if measurementStatus is None:
return self.activeMeasurements + self.completeMeasurements + self.failedMeasurements
elif measurementStatus == MeasurementStatus.COMPLETE:
return self.completeMeasurements
elif measurementStatus == MeasurementStatus.FAILED:
return self.failedMeasurements
elif measurementStatus == MeasurementStatus.DYING:
return list(self.deathBed.keys())
else:
return [x for x in self.activeMeasurements if x.status == measurementStatus]
def getMeasurement(self, measurementId, measurementStatus=None):
"""
Gets the measurement with the given id.
:param measurementId: the id.
:param measurementStatus: the status of the requested measurement.
:return: the matching measurement or none if it doesn't exist.
"""
return next((x for x in self.getMeasurements(measurementStatus) if x.id == measurementId), None)
def store(self, measurement):
"""
Writes the measurement metadata to disk on completion.
:param activeMeasurement: the measurement that has completed.
:returns the persisted metadata.
"""
os.makedirs(self._getPathToMeasurementMetaDir(measurement.idAsPath), exist_ok=True)
output = marshal(measurement, measurementFields)
with open(self._getPathToMeasurementMetaFile(measurement.idAsPath), 'w') as outfile:
json.dump(output, outfile)
return output
def load(self, path):
"""
Loads a CompletedMeasurement from the path.á
:param path: the path at which the data is found.
:return: the measurement
"""
meta = self._loadMetaFromJson(path)
return CompleteMeasurement(meta, self.dataDir) if meta is not None else None
def _loadMetaFromJson(self, path):
"""
Reads the json meta into memory.
:return: the meta.
"""
try:
with (path / 'metadata.json').open() as infile:
return json.load(infile)
except FileNotFoundError:
logger.error('Metadata does not exist at ' + str(path))
return None
def _getPathToMeasurementMetaDir(self, measurementId):
return os.path.join(self.dataDir, measurementId)
def _getPathToMeasurementMetaFile(self, measurementId):
return os.path.join(self.dataDir, measurementId, 'metadata.json')
def editMeasurement(self, measurementId, data):
"""
Edits the specified measurement with the provided data.
:param measurementId: the measurement id.
:param data: the data to update.
:return: true if the measurement was edited
"""
oldMeasurement = self.getMeasurement(measurementId, measurementStatus=MeasurementStatus.COMPLETE)
if oldMeasurement:
import copy
newMeasurement = copy.deepcopy(oldMeasurement)
deleteOld = False
createdFilteredCopy = False
newName = data.get('name', None)
newDesc = data.get('description', None)
newStart = float(data.get('start', 0))
newEnd = float(data.get('end', oldMeasurement.duration))
newDuration = newEnd - newStart
newDevices = data.get('devices', None)
if newName:
logger.info('Updating name from ' + oldMeasurement.name + ' to ' + newName)
newMeasurement.updateName(newName)
createdFilteredCopy = True
deleteOld = True
if newDesc:
logger.info('Updating description from ' + str(oldMeasurement.description) + ' to ' + str(newDesc))
newMeasurement.description = newDesc
if newDuration != oldMeasurement.duration:
logger.info('Copying measurement to allow support new duration ' + str(newDuration))
if oldMeasurement.name == newMeasurement.name:
newMeasurement.updateName(newMeasurement.name + '-' + str(int(time.time())))
newMeasurement.duration = newDuration
createdFilteredCopy = True
if createdFilteredCopy:
logger.info('Copying measurement data from ' + oldMeasurement.idAsPath + ' to ' + newMeasurement.idAsPath)
newMeasurementPath = self._getPathToMeasurementMetaDir(newMeasurement.idAsPath)
dataSearchPattern = self._getPathToMeasurementMetaDir(oldMeasurement.idAsPath) + '/**/data.out'
newDataCountsByDevice = [self._filterCopy(dataFile, newStart, newEnd, newMeasurementPath)
for dataFile in glob.glob(dataSearchPattern)]
for device, count in newDataCountsByDevice:
newMeasurement.recordingDevices.get(device)['count'] = count
self.store(newMeasurement)
if newDevices:
for renames in newDevices:
logger.info('Updating device name from ' + str(renames[0]) + ' to ' + str(renames[1]))
deviceState = newMeasurement.recordingDevices.get(renames[0])
newMeasurement.recordingDevices[renames[1]] = deviceState
del newMeasurement.recordingDevices[renames[0]]
os.rename(os.path.join(self._getPathToMeasurementMetaDir(newMeasurement.idAsPath), renames[0]),
os.path.join(self._getPathToMeasurementMetaDir(newMeasurement.idAsPath), renames[1]))
self.store(newMeasurement)
if deleteOld or createdFilteredCopy or newDevices:
self.completeMeasurements.append(newMeasurement)
if deleteOld:
self.delete(oldMeasurement.id)
return True
else:
return False
def _filterCopy(self, dataFile, newStart, newEnd, newDataDir):
"""
Copies the data file to a new file in the tmp dir, filtering it according to newStart and newEnd and adjusting
the times as appropriate so it starts from 0.
:param dataFile: the input file.
:param newStart: the new start time.
:param newEnd: the new end time.
:param newDataDir: the tmp dir to write to.
:return: the device name & no of rows in the data.
"""
import csv
pathToData = os.path.split(dataFile)
dataFileName = pathToData[1]
dataDeviceName = os.path.split(pathToData[0])[1]
os.makedirs(os.path.join(newDataDir, dataDeviceName), exist_ok=True)
outputFile = os.path.join(newDataDir, dataDeviceName, dataFileName)
dataCount = 0
rowNum = 0
with open(dataFile, mode='rt', newline='') as dataIn, open(outputFile, mode='wt', newline='') as dataOut:
writer = csv.writer(dataOut, delimiter=',')
for row in csv.reader(dataIn, delimiter=','):
if len(row) > 0:
time = float(row[0])
if newStart <= time <= newEnd:
newRow = row[:]
if newStart > 0:
newRow[0] = "{0:.3f}".format(time - newStart)
writer.writerow(newRow)
dataCount += 1
else:
logger.warning('Ignoring empty row ' + str(rowNum) + ' in ' + str(dataFile))
rowNum += 1
return dataDeviceName, dataCount
|
class MeasurementController(object):
'''
Contains all the logic around measurement scheduling and is responsible for ensuring we have valid measurements
only.
'''
def __init__(self, targetStateProvider, dataDir, deviceController, maxTimeTilDeathbedSeconds=30,
maxTimeOnDeathbedSeconds=120):
pass
def shutdown(self):
pass
def _sweep(self):
'''
Checks the state of each measurement and verifies their state, if an active measurement is now complete then
passes them to the completed measurement set, if failed then to the failed set, if failed and old then evicts.
:return:
'''
pass
def _handleDeathbed(self, am):
pass
def _moveToComplete(self, am):
pass
def _moveToFailed(self, am):
pass
def schedule(self, name, duration, startTime, description=None):
'''
Schedules a new measurement with the given name.
:param name:
:param duration:
:param startTime:
:param description:
:return: a tuple
boolean: measurement was scheduled if true
message: description, generally only used as an error code
'''
pass
def _clashes(self, startTime, duration):
'''
verifies that this measurement does not clash with an already scheduled measurement.
:param startTime: the start time.
:param duration: the duration.
:return: true if the measurement is allowed.
'''
pass
def startMeasurement(self, measurementId, deviceId):
'''
Starts the measurement for the device.
:param deviceId: the device that is starting.
:param measurementId: the measurement that is started.
:return: true if it started (i.e. device and measurement exists).
'''
pass
def getDataHandler(self, measurementId, deviceId):
'''
finds the handler.
:param measurementId: the measurement
:param deviceId: the device.
:return: active measurement and handler
'''
pass
def recordData(self, measurementId, deviceId, data):
'''
Passes the data to the handler.
:param deviceId: the device the data comes from.
:param measurementId: the measurement id.
:param data: the data.
:return: true if the data was handled.
'''
pass
def completeMeasurement(self, measurementId, deviceId):
'''
Completes the measurement session.
:param deviceId: the device id.
:param measurementId: the measurement id.
:return: true if it was completed.
'''
pass
def failMeasurement(self, measurementId, deviceName, failureReason=None):
'''
Fails the measurement session.
:param deviceName: the device name.
:param measurementId: the measurement name.
:param failureReason: why it failed.
:return: true if it was completed.
'''
pass
def delete(self, measurementId):
'''
Deletes the named measurement if it exists. If this is an active measurement then the measurement is cancelled.
:param measurementId: the measurement name.
:return:
'''
pass
def _deleteCompletedMeasurement(self, measurementId):
'''
Deletes the named measurement from the completed measurement store if it exists.
:param measurementId:
:return:
String: error messages
Integer: count of measurements deleted
'''
pass
def deleteFrom(self, measurementId, data):
pass
def logError(func, path, exc_info):
pass
def reloadCompletedMeasurements(self):
'''
Reloads the completed measurements from the backing store.
'''
pass
def getMeasurements(self, measurementStatus=None):
'''
Gets all available measurements.
:param measurementStatus return only the measurements in the given state.
:return:
'''
pass
def getMeasurements(self, measurementStatus=None):
'''
Gets the measurement with the given id.
:param measurementId: the id.
:param measurementStatus: the status of the requested measurement.
:return: the matching measurement or none if it doesn't exist.
'''
pass
def store(self, measurement):
'''
Writes the measurement metadata to disk on completion.
:param activeMeasurement: the measurement that has completed.
:returns the persisted metadata.
'''
pass
def load(self, path):
'''
Loads a CompletedMeasurement from the path.á
:param path: the path at which the data is found.
:return: the measurement
'''
pass
def _loadMetaFromJson(self, path):
'''
Reads the json meta into memory.
:return: the meta.
'''
pass
def _getPathToMeasurementMetaDir(self, measurementId):
pass
def _getPathToMeasurementMetaFile(self, measurementId):
pass
def editMeasurement(self, measurementId, data):
'''
Edits the specified measurement with the provided data.
:param measurementId: the measurement id.
:param data: the data to update.
:return: true if the measurement was edited
'''
pass
def _filterCopy(self, dataFile, newStart, newEnd, newDataDir):
'''
Copies the data file to a new file in the tmp dir, filtering it according to newStart and newEnd and adjusting
the times as appropriate so it starts from 0.
:param dataFile: the input file.
:param newStart: the new start time.
:param newEnd: the new end time.
:param newDataDir: the tmp dir to write to.
:return: the device name & no of rows in the data.
'''
pass
| 28 | 19 | 15 | 0 | 11 | 4 | 3 | 0.42 | 1 | 14 | 4 | 0 | 26 | 11 | 26 | 26 | 429 | 30 | 280 | 96 | 248 | 119 | 250 | 92 | 219 | 12 | 1 | 5 | 77 |
734 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/recorder/common/i2c_io.py
|
i2c_io.mock_io
|
class mock_io(i2c_io):
def __init__(self, dataProvider=None):
super().__init__()
self.valuesWritten = []
self.dataProvider = dataProvider
self.valsToRead = Queue()
def write(self, i2cAddress, register, val):
self.valuesWritten.append([i2cAddress, register, val])
def readBlock(self, i2cAddress, register, length):
if self.dataProvider is not None:
ret = self.dataProvider(register, length)
if ret is not None:
return ret
return self.valsToRead.get_nowait()
def read(self, i2cAddress, register):
if self.dataProvider is not None:
ret = self.dataProvider(register)
if ret is not None:
return ret
return self.valsToRead.get_nowait()
|
class mock_io(i2c_io):
def __init__(self, dataProvider=None):
pass
def write(self, i2cAddress, register, val):
pass
def readBlock(self, i2cAddress, register, length):
pass
def readBlock(self, i2cAddress, register, length):
pass
| 5 | 0 | 5 | 0 | 5 | 0 | 2 | 0 | 1 | 2 | 0 | 0 | 4 | 3 | 4 | 8 | 23 | 3 | 20 | 10 | 15 | 0 | 20 | 10 | 15 | 3 | 2 | 2 | 8 |
735 |
3ll3d00d/vibe
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/3ll3d00d_vibe/backend/src/recorder/resources/measurements.py
|
measurements.Measurements
|
class Measurements(Resource):
def __init__(self, **kwargs):
self.measurements = kwargs['measurements']
@marshal_with(scheduledMeasurementFields)
def get(self, deviceId):
"""
lists all known active measurements.
"""
measurementsByName = self.measurements.get(deviceId)
if measurementsByName is None:
return []
else:
return list(measurementsByName.values())
|
class Measurements(Resource):
def __init__(self, **kwargs):
pass
@marshal_with(scheduledMeasurementFields)
def get(self, deviceId):
'''
lists all known active measurements.
'''
pass
| 4 | 1 | 6 | 0 | 4 | 2 | 2 | 0.3 | 1 | 1 | 0 | 0 | 2 | 1 | 2 | 2 | 14 | 1 | 10 | 6 | 6 | 3 | 8 | 5 | 5 | 2 | 1 | 1 | 3 |
736 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/core/httpclient.py
|
httpclient.RequestsBasedHttpClient
|
class RequestsBasedHttpClient(HttpClient):
"""
An implementation of HttpClient which simply delegates to the requests lib.
"""
def get(self, url, **kwargs):
try:
return requests.get(url, timeout=0.5, **kwargs)
except requests.exceptions.RequestException as e:
raise RequestException("Unable to GET from " + url) from e
def post(self, url, **kwargs):
try:
return requests.post(url, timeout=0.5, **kwargs)
except requests.exceptions.RequestException as e:
raise RequestException("Unable to POST to " + url) from e
def put(self, url, **kwargs):
try:
return requests.put(url, timeout=0.5, **kwargs)
except requests.exceptions.RequestException as e:
raise RequestException("Unable to PUT " + url) from e
def patch(self, url, **kwargs):
try:
return requests.patch(url, timeout=0.5, **kwargs)
except requests.exceptions.RequestException as e:
raise RequestException("Unable to PATCH " + url) from e
def delete(self, url, **kwargs):
try:
return requests.delete(url, timeout=0.5, **kwargs)
except requests.exceptions.RequestException as e:
raise RequestException("Unable to DELETE " + url) from e
|
class RequestsBasedHttpClient(HttpClient):
'''
An implementation of HttpClient which simply delegates to the requests lib.
'''
def get(self, url, **kwargs):
pass
def post(self, url, **kwargs):
pass
def put(self, url, **kwargs):
pass
def patch(self, url, **kwargs):
pass
def delete(self, url, **kwargs):
pass
| 6 | 1 | 5 | 0 | 5 | 0 | 2 | 0.12 | 1 | 1 | 1 | 0 | 5 | 0 | 5 | 10 | 34 | 5 | 26 | 11 | 20 | 3 | 26 | 6 | 20 | 2 | 2 | 1 | 10 |
737 |
3ll3d00d/vibe
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/3ll3d00d_vibe/backend/src/analyser/resources/measurements.py
|
measurements.Measurements
|
class Measurements(Resource):
def __init__(self, **kwargs):
self._measurementController = kwargs['measurementController']
@marshal_with(measurementFields)
def get(self):
"""
Gets the currently available measurements.
:return:
"""
return self._measurementController.getMeasurements(), 200
|
class Measurements(Resource):
def __init__(self, **kwargs):
pass
@marshal_with(measurementFields)
def get(self):
'''
Gets the currently available measurements.
:return:
'''
pass
| 4 | 1 | 4 | 0 | 2 | 2 | 1 | 0.67 | 1 | 0 | 0 | 0 | 2 | 1 | 2 | 2 | 11 | 1 | 6 | 5 | 2 | 4 | 5 | 4 | 2 | 1 | 1 | 0 | 2 |
738 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/analyser/resources/analyse.py
|
analyse.Analyse
|
class Analyse(Resource):
def __init__(self, **kwargs):
self._measurementController = kwargs['measurementController']
def get(self, measurementId):
"""
Analyses the measurement with the given parameters
:param measurementId:
:return:
"""
logger.info('Analysing ' + measurementId)
measurement = self._measurementController.getMeasurement(measurementId, MeasurementStatus.COMPLETE)
if measurement is not None:
if measurement.inflate():
data = {
name: {
'spectrum': {
'x': self._jsonify(data.spectrum('x')),
'y': self._jsonify(data.spectrum('y')),
'z': self._jsonify(data.spectrum('z')),
'sum': self._jsonify(data.spectrum('sum'))
},
'psd': {
'x': self._jsonify(data.psd('x')),
'y': self._jsonify(data.psd('y')),
'z': self._jsonify(data.psd('z'))
},
'peakSpectrum': {
'x': self._jsonify(data.peakSpectrum('x')),
'y': self._jsonify(data.peakSpectrum('y')),
'z': self._jsonify(data.peakSpectrum('z')),
'sum': self._jsonify(data.peakSpectrum('sum'))
}
}
for name, data in measurement.data.items()
}
return data, 200
else:
return None, 404
else:
return None, 404
def _jsonify(self, tup):
return {'freq': tup[0].tolist(), 'val': tup[1].tolist()}
|
class Analyse(Resource):
def __init__(self, **kwargs):
pass
def get(self, measurementId):
'''
Analyses the measurement with the given parameters
:param measurementId:
:return:
'''
pass
def _jsonify(self, tup):
pass
| 4 | 1 | 14 | 0 | 12 | 2 | 2 | 0.14 | 1 | 1 | 1 | 0 | 3 | 1 | 3 | 3 | 44 | 2 | 37 | 7 | 33 | 5 | 14 | 7 | 10 | 3 | 1 | 2 | 5 |
739 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/analyser/common/config.py
|
config.Config
|
class Config(BaseConfig):
def __init__(self):
super().__init__('analyser', defaultPort=8080)
self.targetState = loadTargetState(self.config.get('targetState'))
self.upload = self.config.get('upload', self.getDefaultUpload())
self.dataDir = self.config.get('dataDir', self.getDefaultDataDir())
self.ensureDirExists(self.dataDir)
self.useTwisted = self.config.get('useTwisted', True)
self.ensureDirExists(self.upload['tmpDir'])
self.ensureDirExists(self.upload['uploadDir'])
def ensureDirExists(self, dir):
if not os.path.exists(dir):
os.makedirs(dir)
def getDefaultUpload(self):
return {
'tmpDir': self.getDefaultTmpDir(),
'uploadDir': self.getDefaultUploadDir(),
'watchdogInterval': 5,
'converterThreads': 2
}
def getDefaultDataDir(self):
return os.path.join(self._getConfigPath(), 'data')
def getDefaultTmpDir(self):
return os.path.join(self._getConfigPath(), 'tmp')
def getDefaultUploadDir(self):
return os.path.join(self._getConfigPath(), 'upload')
def loadDefaultConfig(self):
return {
'debug': False,
'debugLogging': False,
'port': 8080,
'host': self.getDefaultHostname(),
'useTwisted': True,
'dataDir': self.getDefaultDataDir(),
'upload': self.getDefaultUpload(),
'targetState': {
'fs': 500,
'samplesPerBatch': 125,
'gyroEnabled': False,
'gyroSens': 500,
'accelerometerEnabled': True,
'accelerometerSens': 4
}
}
|
class Config(BaseConfig):
def __init__(self):
pass
def ensureDirExists(self, dir):
pass
def getDefaultUpload(self):
pass
def getDefaultDataDir(self):
pass
def getDefaultTmpDir(self):
pass
def getDefaultUploadDir(self):
pass
def loadDefaultConfig(self):
pass
| 8 | 0 | 6 | 0 | 6 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 7 | 4 | 7 | 19 | 50 | 6 | 44 | 12 | 36 | 0 | 23 | 12 | 15 | 2 | 2 | 1 | 8 |
740 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/recorder/common/config.py
|
config.Config
|
class Config(BaseConfig):
def __init__(self):
super().__init__('recorder', defaultPort=10002)
self.handlers = self._loadHandlers()
self.recordingDevices = self._loadRecordingDevices()
self.measurements = self._loadMeasurements()
def loadDefaultConfig(self):
return {
'host': self.getDefaultHostname(),
'port': 10002,
'debug': False,
'debugLogging': False,
'useAsyncHandler': True,
'accelerometers': [
{
'name': 'mpu6050',
'type': 'mpu6050',
'fs': 500,
'handler': 'local log',
'io': {
'type': 'smbus',
'busId': 1
}
}
],
'handlers': [
{
'name': 'remote',
'type': 'post',
'target': 'http://127.0.0.1:8080'
}
]
}
def useAsyncHandlers(self):
"""
:return: if async handling is on, defaults to True.
"""
return self.config.get('useAsyncHandler', True)
def getPingInterval(self):
"""
:return: the server ping interval if set, defaults to 5s.
"""
return self.config.get('pingInterval', 5)
def createDevice(self, deviceCfg):
"""
Creates a measurement deviceCfg from the input configuration.
:param: deviceCfg: the deviceCfg cfg.
:param: handlers: the loaded handlers.
:return: the constructed deviceCfg.
"""
ioCfg = deviceCfg['io']
type = deviceCfg['type']
if type == 'mpu6050':
fs = deviceCfg.get('fs')
name = deviceCfg.get('name')
if ioCfg['type'] == 'mock':
provider = ioCfg.get('provider')
if provider is not None and provider == 'white noise':
dataProvider = WhiteNoiseProvider()
else:
raise ValueError(provider + " is not a supported mock io data provider")
self.logger.warning("Loading mock data provider for mpu6050")
io = mock_io(dataProvider=dataProvider.provide)
elif ioCfg['type'] == 'smbus':
busId = ioCfg['busId']
self.logger.warning("Loading smbus %d", busId)
io = smbus_io(busId)
else:
raise ValueError(ioCfg['type'] + " is not a supported io provider")
self.logger.warning("Loading mpu6050 " + name + "/" + str(fs))
return mpu6050(io, name=name, fs=fs) if name is not None else mpu6050(io, fs=fs)
else:
raise ValueError(type + " is not a supported device")
def _loadRecordingDevices(self):
"""
Loads the recordingDevices specified in the configuration.
:param: handlers the loaded handlers.
:return: the constructed recordingDevices in a dict keyed by name.
"""
return {device.name: device for device in
[self.createDevice(deviceCfg) for deviceCfg in self.config['accelerometers']]}
def _loadMeasurements(self):
"""
creates a dictionary to store a list of measurements by device.
:param devices: the recordingDevices we have available.
:return: a dictionary of device name -> {recording name -> measurements}
"""
return {name: OrderedDict() for name in self.recordingDevices}
def createHandler(self, handler):
"""
Creates a data handler from the input configuration.
:param handler: the handler cfg.
:return: the constructed handler.
"""
target = handler['target']
if handler['type'] == 'log':
self.logger.warning("Initialising csvlogger to log data to " + target)
return CSVLogger('recorder', handler['name'], target)
elif handler['type'] == 'post':
self.logger.warning("Initialising http logger to log data to " + target)
return HttpPoster(handler['name'], target)
def _loadHandlers(self):
"""
creates a dictionary of named handler instances
:return: the dictionary
"""
return {handler.name: handler for handler in map(self.createHandler, self.config['handlers'])}
|
class Config(BaseConfig):
def __init__(self):
pass
def loadDefaultConfig(self):
pass
def useAsyncHandlers(self):
'''
:return: if async handling is on, defaults to True.
'''
pass
def getPingInterval(self):
'''
:return: the server ping interval if set, defaults to 5s.
'''
pass
def createDevice(self, deviceCfg):
'''
Creates a measurement deviceCfg from the input configuration.
:param: deviceCfg: the deviceCfg cfg.
:param: handlers: the loaded handlers.
:return: the constructed deviceCfg.
'''
pass
def _loadRecordingDevices(self):
'''
Loads the recordingDevices specified in the configuration.
:param: handlers the loaded handlers.
:return: the constructed recordingDevices in a dict keyed by name.
'''
pass
def _loadMeasurements(self):
'''
creates a dictionary to store a list of measurements by device.
:param devices: the recordingDevices we have available.
:return: a dictionary of device name -> {recording name -> measurements}
'''
pass
def createHandler(self, handler):
'''
Creates a data handler from the input configuration.
:param handler: the handler cfg.
:return: the constructed handler.
'''
pass
def _loadHandlers(self):
'''
creates a dictionary of named handler instances
:return: the dictionary
'''
pass
| 10 | 7 | 12 | 0 | 8 | 3 | 2 | 0.41 | 1 | 11 | 6 | 0 | 9 | 3 | 9 | 21 | 115 | 8 | 76 | 22 | 66 | 31 | 45 | 22 | 35 | 6 | 2 | 3 | 16 |
741 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/analyser/common/signal.py
|
signal.Signal
|
class Signal(object):
""" a source models some input to the analysis system, it provides the following attributes:
:var samples: an ndarray that represents the signal itself
:var fs: the sample rate
"""
def __init__(self, samples, fs=48000):
self.samples = samples
self.fs = fs
def getSegmentLength(self):
"""
Calculates a segment length such that the frequency resolution of the resulting analysis is in the region of
~1Hz.
subject to a lower limit of the number of samples in the signal.
For example, if we have a 10s signal with an fs is 500 then we convert fs-1 to the number of bits required to
hold this number in binary (i.e. 111110011 so 9 bits) and then do 1 << 9 which gives us 100000000 aka 512. Thus
we have ~1Hz resolution.
:return: the segment length.
"""
return min(1 << (self.fs - 1).bit_length(), self.samples.shape[-1])
def raw(self):
"""
:return: the raw acceleration vs time data.
"""
return self.samples
def vibration(self):
"""
:return: the raw acceleration vs time data high passed to remove gravity.
"""
return self.highPass().samples
def tilt(self):
"""
:return: the raw acceleration vs time data low passed to isolate gravity.
"""
return self.lowPass().samples
def _cq(self, analysisFunc, segmentLengthMultipler=1):
slices = []
initialNperSeg = self.getSegmentLength() * segmentLengthMultipler
nperseg = initialNperSeg
# the no of slices is based on a requirement for approximately 1Hz resolution to 128Hz and then halving the
# resolution per octave. We calculate this as the
# bitlength(fs) - bitlength(128) + 2 (1 for the 1-128Hz range and 1 for 2**n-fs Hz range)
bitLength128 = int(128).bit_length()
for x in range(0, (self.fs - 1).bit_length() - bitLength128 + 2):
f, p = analysisFunc(x, nperseg)
n = round(2 ** (x + bitLength128 - 1) / (self.fs / nperseg))
m = 0 if x == 0 else round(2 ** (x + bitLength128 - 2) / (self.fs / nperseg))
slices.append((f[m:n], p[m:n]))
nperseg /= 2
f = np.concatenate([n[0] for n in slices])
p = np.concatenate([n[1] for n in slices])
return f, p
def psd(self, ref=None, segmentLengthMultiplier=1, mode=None, **kwargs):
"""
analyses the source and returns a PSD, segment is set to get ~1Hz frequency resolution
:param ref: the reference value for dB purposes.
:param segmentLengthMultiplier: allow for increased resolution.
:param mode: cq or none.
:return:
f : ndarray
Array of sample frequencies.
Pxx : ndarray
Power spectral density.
"""
def analysisFunc(x, nperseg, **kwargs):
f, Pxx_den = signal.welch(self.samples, self.fs, nperseg=nperseg, detrend=False, **kwargs)
if ref is not None:
Pxx_den = librosa.power_to_db(Pxx_den, ref)
return f, Pxx_den
if mode == 'cq':
return self._cq(analysisFunc, segmentLengthMultiplier)
else:
return analysisFunc(0, self.getSegmentLength() * segmentLengthMultiplier, **kwargs)
def spectrum(self, ref=None, segmentLengthMultiplier=1, mode=None, **kwargs):
"""
analyses the source to generate the linear spectrum.
:param ref: the reference value for dB purposes.
:param segmentLengthMultiplier: allow for increased resolution.
:param mode: cq or none.
:return:
f : ndarray
Array of sample frequencies.
Pxx : ndarray
linear spectrum.
"""
def analysisFunc(x, nperseg, **kwargs):
f, Pxx_spec = signal.welch(self.samples, self.fs, nperseg=nperseg, scaling='spectrum', detrend=False,
**kwargs)
Pxx_spec = np.sqrt(Pxx_spec)
# it seems a 3dB adjustment is required to account for the change in nperseg
if x > 0:
Pxx_spec = Pxx_spec / (10 ** ((3 * x) / 20))
if ref is not None:
Pxx_spec = librosa.amplitude_to_db(Pxx_spec, ref)
return f, Pxx_spec
if mode == 'cq':
return self._cq(analysisFunc, segmentLengthMultiplier)
else:
return analysisFunc(0, self.getSegmentLength() * segmentLengthMultiplier, **kwargs)
def peakSpectrum(self, ref=None, segmentLengthMultiplier=1, mode=None, window='hann'):
"""
analyses the source to generate the max values per bin per segment
:param ref: the reference value for dB purposes.
:param segmentLengthMultiplier: allow for increased resolution.
:param mode: cq or none.
:return:
f : ndarray
Array of sample frequencies.
Pxx : ndarray
linear spectrum max values.
"""
def analysisFunc(x, nperseg):
freqs, _, Pxy = signal.spectrogram(self.samples,
self.fs,
window=window,
nperseg=int(nperseg),
noverlap=int(nperseg // 2),
detrend=False,
scaling='spectrum')
Pxy_max = np.sqrt(Pxy.max(axis=-1).real)
if x > 0:
Pxy_max = Pxy_max / (10 ** ((3 * x) / 20))
if ref is not None:
Pxy_max = librosa.amplitude_to_db(Pxy_max, ref=ref)
return freqs, Pxy_max
if mode == 'cq':
return self._cq(analysisFunc, segmentLengthMultiplier)
else:
return analysisFunc(0, self.getSegmentLength() * segmentLengthMultiplier)
def spectrogram(self, ref=None, segmentLengthMultiplier=1, window='hann'):
"""
analyses the source to generate a spectrogram
:param ref: the reference value for dB purposes.
:param segmentLengthMultiplier: allow for increased resolution.
:return:
t : ndarray
Array of time slices.
f : ndarray
Array of sample frequencies.
Pxx : ndarray
linear spectrum values.
"""
t, f, Sxx = signal.spectrogram(self.samples,
self.fs,
window=window,
nperseg=self.getSegmentLength() * segmentLengthMultiplier,
detrend=False,
scaling='spectrum')
Sxx = np.sqrt(Sxx)
if ref is not None:
Sxx = librosa.amplitude_to_db(Sxx, ref)
return t, f, Sxx
def lowPass(self, *args):
"""
Creates a copy of the signal with the low pass applied, args specifed are passed through to _butter.
:return:
"""
return Signal(self._butter(self.samples, 'low', *args), fs=self.fs)
def highPass(self, *args):
"""
Creates a copy of the signal with the high pass applied, args specifed are passed through to _butter.
:return:
"""
return Signal(self._butter(self.samples, 'high', *args), fs=self.fs)
def _butter(self, data, btype, f3=2, order=2):
"""
Applies a digital butterworth filter via filtfilt at the specified f3 and order. Default values are set to
correspond to apparently sensible filters that distinguish between vibration and tilt from an accelerometer.
:param data: the data to filter.
:param btype: high or low.
:param f3: the f3 of the filter.
:param order: the filter order.
:return: the filtered signal.
"""
b, a = signal.butter(order, f3 / (0.5 * self.fs), btype=btype)
y = signal.filtfilt(b, a, data)
return y
|
class Signal(object):
''' a source models some input to the analysis system, it provides the following attributes:
:var samples: an ndarray that represents the signal itself
:var fs: the sample rate
'''
def __init__(self, samples, fs=48000):
pass
def getSegmentLength(self):
'''
Calculates a segment length such that the frequency resolution of the resulting analysis is in the region of
~1Hz.
subject to a lower limit of the number of samples in the signal.
For example, if we have a 10s signal with an fs is 500 then we convert fs-1 to the number of bits required to
hold this number in binary (i.e. 111110011 so 9 bits) and then do 1 << 9 which gives us 100000000 aka 512. Thus
we have ~1Hz resolution.
:return: the segment length.
'''
pass
def raw(self):
'''
:return: the raw acceleration vs time data.
'''
pass
def vibration(self):
'''
:return: the raw acceleration vs time data high passed to remove gravity.
'''
pass
def tilt(self):
'''
:return: the raw acceleration vs time data low passed to isolate gravity.
'''
pass
def _cq(self, analysisFunc, segmentLengthMultipler=1):
pass
def psd(self, ref=None, segmentLengthMultiplier=1, mode=None, **kwargs):
'''
analyses the source and returns a PSD, segment is set to get ~1Hz frequency resolution
:param ref: the reference value for dB purposes.
:param segmentLengthMultiplier: allow for increased resolution.
:param mode: cq or none.
:return:
f : ndarray
Array of sample frequencies.
Pxx : ndarray
Power spectral density.
'''
pass
def analysisFunc(x, nperseg, **kwargs):
pass
def spectrum(self, ref=None, segmentLengthMultiplier=1, mode=None, **kwargs):
'''
analyses the source to generate the linear spectrum.
:param ref: the reference value for dB purposes.
:param segmentLengthMultiplier: allow for increased resolution.
:param mode: cq or none.
:return:
f : ndarray
Array of sample frequencies.
Pxx : ndarray
linear spectrum.
'''
pass
def analysisFunc(x, nperseg, **kwargs):
pass
def peakSpectrum(self, ref=None, segmentLengthMultiplier=1, mode=None, window='hann'):
'''
analyses the source to generate the max values per bin per segment
:param ref: the reference value for dB purposes.
:param segmentLengthMultiplier: allow for increased resolution.
:param mode: cq or none.
:return:
f : ndarray
Array of sample frequencies.
Pxx : ndarray
linear spectrum max values.
'''
pass
def analysisFunc(x, nperseg, **kwargs):
pass
def spectrogram(self, ref=None, segmentLengthMultiplier=1, window='hann'):
'''
analyses the source to generate a spectrogram
:param ref: the reference value for dB purposes.
:param segmentLengthMultiplier: allow for increased resolution.
:return:
t : ndarray
Array of time slices.
f : ndarray
Array of sample frequencies.
Pxx : ndarray
linear spectrum values.
'''
pass
def lowPass(self, *args):
'''
Creates a copy of the signal with the low pass applied, args specifed are passed through to _butter.
:return:
'''
pass
def highPass(self, *args):
'''
Creates a copy of the signal with the high pass applied, args specifed are passed through to _butter.
:return:
'''
pass
def _butter(self, data, btype, f3=2, order=2):
'''
Applies a digital butterworth filter via filtfilt at the specified f3 and order. Default values are set to
correspond to apparently sensible filters that distinguish between vibration and tilt from an accelerometer.
:param data: the data to filter.
:param btype: high or low.
:param f3: the f3 of the filter.
:param order: the filter order.
:return: the filtered signal.
'''
pass
| 17 | 12 | 13 | 1 | 7 | 5 | 2 | 1 | 1 | 2 | 0 | 0 | 13 | 2 | 13 | 13 | 197 | 21 | 88 | 34 | 71 | 88 | 73 | 34 | 56 | 3 | 1 | 1 | 27 |
742 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/analyser/common/devicecontroller.py
|
devicecontroller.Device
|
class Device(object):
"""
the analyser view of a device which includes the payload sent by the device along with information for our own
housekeeping.
"""
def __init__(self, maxAgeSeconds):
self.deviceId = None
self.payload = None
self.lastUpdateTime = None
self.dataHandler = None
self.maxAgeSeconds = maxAgeSeconds
def hasExpired(self):
"""
:return: true if the lastUpdateTime is more than maxAge seconds ago.
"""
return (datetime.datetime.utcnow() - self.lastUpdateTime).total_seconds() > self.maxAgeSeconds
def __str__(self):
return "Device[" + self.deviceId + "-" + self.lastUpdateTime.strftime(DATETIME_FORMAT) + "]"
|
class Device(object):
'''
the analyser view of a device which includes the payload sent by the device along with information for our own
housekeeping.
'''
def __init__(self, maxAgeSeconds):
pass
def hasExpired(self):
'''
:return: true if the lastUpdateTime is more than maxAge seconds ago.
'''
pass
def __str__(self):
pass
| 4 | 2 | 4 | 0 | 3 | 1 | 1 | 0.64 | 1 | 1 | 0 | 0 | 3 | 5 | 3 | 3 | 21 | 3 | 11 | 9 | 7 | 7 | 11 | 9 | 7 | 1 | 1 | 0 | 3 |
743 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/analyser/common/devicecontroller.py
|
devicecontroller.DeviceController
|
class DeviceController(object):
"""
Controls interactions with the recording devices.
"""
def __init__(self, targetStateController, dataDir, httpclient, maxAgeSeconds=30):
self.httpclient = httpclient
self.devices = {}
self.targetStateController = targetStateController
self.dataDir = dataDir
if dataDir is None or httpclient is None or targetStateController is None:
raise ValueError("Mandatory args missing")
self.maxAgeSeconds = maxAgeSeconds
self.running = True
self.worker = threading.Thread(name='DeviceCaretaker', target=self._evictStaleDevices, daemon=True)
self.worker.start()
def shutdown(self):
logger.warning("Shutting down the DeviceCaretaker")
self.running = False
def accept(self, deviceId, device):
"""
Adds the named device to the store.
:param deviceId:
:param device:
:return:
"""
storedDevice = self.devices.get(deviceId)
if storedDevice is None:
logger.info('Initialising device ' + deviceId)
storedDevice = Device(self.maxAgeSeconds)
storedDevice.deviceId = deviceId
# this uses an async handler to decouple the recorder put (of the data) from the analyser handling that data
# thus the recorder will become free as soon as it has handed off the data. This means delivery is only
# guaranteed as long as the analyser stays up but this is not a system that sits on top of a bulletproof
# message bus so unlucky :P
storedDevice.dataHandler = AsyncHandler('analyser', CSVLogger('analyser', deviceId, self.dataDir))
else:
logger.debug('Pinged by device ' + deviceId)
storedDevice.payload = device
storedDevice.lastUpdateTime = datetime.datetime.utcnow()
# TODO if device has FAILED, do something?
self.devices.update({deviceId: storedDevice})
self.targetStateController.updateDeviceState(storedDevice.payload)
def getDevices(self, status=None):
"""
The devices in the given state or all devices is the arg is none.
:param status: the state to match against.
:return: the devices
"""
return [d for d in self.devices.values() if status is None or d.payload.get('status') == status]
def getDevice(self, id):
"""
gets the named device.
:param id: the id.
:return: the device
"""
return next(iter([d for d in self.devices.values() if d.deviceId == id]), None)
def _evictStaleDevices(self):
"""
A housekeeping function which runs in a worker thread and which evicts devices that haven't sent an update for a
while.
"""
while self.running:
expiredDeviceIds = [key for key, value in self.devices.items() if value.hasExpired()]
for key in expiredDeviceIds:
logger.warning("Device timeout, removing " + key)
del self.devices[key]
time.sleep(1)
# TODO send reset after a device fails
logger.warning("DeviceCaretaker is now shutdown")
def scheduleMeasurement(self, measurementId, duration, start):
"""
Schedules the requested measurement session with all INITIALISED devices.
:param measurementId:
:param duration:
:param start:
:return: a dict of device vs status.
"""
# TODO subtract 1s from start and format
results = {}
for device in self.getDevices(RecordingDeviceStatus.INITIALISED.name):
logger.info('Sending measurement ' + measurementId + ' to ' + device.payload['serviceURL'])
try:
resp = self.httpclient.put(device.payload['serviceURL'] + '/measurements/' + measurementId,
json={'duration': duration, 'at': start.strftime(DATETIME_FORMAT)})
logger.info('Response for ' + measurementId + ' from ' + device.payload['serviceURL'] + ' is ' +
str(resp.status_code))
results[device] = resp.status_code
except Exception as e:
logger.exception(e)
results[device] = 500
return results
|
class DeviceController(object):
'''
Controls interactions with the recording devices.
'''
def __init__(self, targetStateController, dataDir, httpclient, maxAgeSeconds=30):
pass
def shutdown(self):
pass
def accept(self, deviceId, device):
'''
Adds the named device to the store.
:param deviceId:
:param device:
:return:
'''
pass
def getDevices(self, status=None):
'''
The devices in the given state or all devices is the arg is none.
:param status: the state to match against.
:return: the devices
'''
pass
def getDevices(self, status=None):
'''
gets the named device.
:param id: the id.
:return: the device
'''
pass
def _evictStaleDevices(self):
'''
A housekeeping function which runs in a worker thread and which evicts devices that haven't sent an update for a
while.
'''
pass
def scheduleMeasurement(self, measurementId, duration, start):
'''
Schedules the requested measurement session with all INITIALISED devices.
:param measurementId:
:param duration:
:param start:
:return: a dict of device vs status.
'''
pass
| 8 | 6 | 12 | 0 | 8 | 5 | 2 | 0.69 | 1 | 9 | 4 | 0 | 7 | 7 | 7 | 7 | 98 | 7 | 54 | 21 | 46 | 37 | 51 | 20 | 43 | 3 | 1 | 2 | 13 |
744 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/scratch/graphs.py
|
graphs.HandlerTestCase
|
class HandlerTestCase(object):
def resam(self):
measurementPath = os.path.join(os.path.dirname(__file__), '../test/data', 'white.wav')
measurement = ms.loadSignalFromWav(measurementPath)
y_1000 = librosa.resample(measurement.samples, measurement.fs, 1000, res_type='kaiser_fast')
measurementPath_1000 = os.path.join(os.path.dirname(__file__), '../test/data', 'white_1000.wav')
maxv = np.iinfo(np.int32).max
librosa.output.write_wav(measurementPath_1000, (y_1000 * maxv).astype(np.int32), 1000)
# librosa.output.write_wav(measurementPath_1000, y_1000, 1000)
measurement_1000 = ms.loadSignalFromWav(measurementPath_1000)
y_1000 = Signal(y_1000, 1000)
f, Pxx = measurement_1000.spectrum(ref=1.0)
plt.semilogx(f, Pxx)
f, Pxx = y_1000.spectrum(ref=1.0)
plt.semilogx(f, Pxx)
plt.show()
def spec(self):
measurementPath = os.path.join(os.path.dirname(__file__), '../test/data', 'eot.wav')
measurement = ms.loadSignalFromWav(measurementPath)
# y_1000 = librosa.resample(measurement.samples, measurement.fs, 1000, res_type='kaiser_fast')
# measurement = Signal(y_1000, 1000)
f, Pxx = measurement.peakSpectrum(ref=1/(2**0.5))
print(str(np.max(Pxx)))
plt.semilogx(f, Pxx)
plt.show()
def librosaSpectrum(self):
import librosa.display
measurementPath = os.path.join(os.path.dirname(__file__), '../test/data', 'eot.wav')
# measurement = ms.loadSignalFromWav(measurementPath)
y, sr = librosa.load(measurementPath, sr=500)
# no of octaves in the CQT (have to divide SR by 8 because we remove 1 octave for nyquist and another to fit
# the filter inside nyquist (I think)
bins_per_octave = 24
n_bins = math.floor(bins_per_octave * math.log2(sr / 8)) - 1
fmin = 4.0
cqt_freq = librosa.cqt_frequencies(n_bins, fmin, bins_per_octave=bins_per_octave)
C = librosa.core.cqt(y, sr, hop_length=2 ** 12, fmin=4.0, bins_per_octave=bins_per_octave, n_bins=n_bins,
filter_scale=2)
spectrum = np.sqrt(np.mean(np.abs(C) ** 2, axis=-1))
peak = np.sqrt(np.max(np.abs(C) ** 2, axis=-1))
plt.figure()
plt.xlim(4, 250)
plt.semilogx(cqt_freq, librosa.amplitude_to_db(spectrum, ref=np.max(peak)))
# plt.semilogx(cqt_freq, librosa.amplitude_to_db(peak, ref=np.max(peak)))
measurement = Signal(y, fs=500)
f, Pxx = measurement.peakSpectrum()
# plt.semilogx(f, librosa.amplitude_to_db(Pxx, ref=np.max(Pxx)))
f, Pxx_spec = measurement.spectrum()
plt.semilogx(f, librosa.amplitude_to_db(Pxx_spec, ref=np.max(Pxx)))
f, Pxx = measurement.peakSpectrum()
f, Pxx_spec = measurement.spectrum()
plt.semilogx(f, librosa.amplitude_to_db(Pxx_spec, ref=np.max(Pxx)))
plt.tight_layout()
plt.show()
def librosaResample(self):
import librosa.display
measurementPath = os.path.join(os.path.dirname(__file__), '../test/data', 'eot.wav')
plt.figure()
plt.xlim(5, 1000)
y, sr = librosa.load(measurementPath, sr=None)
measurement = Signal(y, fs=sr)
f, Pxx = measurement.peakSpectrum(ref=1.0)
plt.semilogx(f, Pxx)
f, Pxx = measurement.peakSpectrum(segmentLengthMultiplier=2)
plt.semilogx(f, librosa.amplitude_to_db(Pxx))
y, sr = librosa.load(measurementPath, sr=1000)
measurement = Signal(y, fs=sr)
f, Pxx = measurement.peakSpectrum()
plt.semilogx(f, librosa.amplitude_to_db(Pxx))
y, sr = librosa.load(measurementPath, sr=1000)
measurement = Signal(y, fs=sr)
f, Pxx = measurement.peakSpectrum(segmentLengthMultiplier=2)
plt.semilogx(f, librosa.amplitude_to_db(Pxx))
plt.tight_layout()
plt.show()
def showSpectrum(self):
# measurementPath = 'C:\\Users\\\Matt\\OneDrive\\Documents\\eot\\Edge of Tomorrow - Opening.wav'
# measurementPath = os.path.join(os.path.dirname(__file__), '../test/data', 'eot.wav')
# measurementPath = os.path.join(os.path.dirname(__file__), '../test/data', 'white_0_50_1.wav')
measurementPath = os.path.join(os.path.dirname(__file__), '../test/data', 'PinkNoise_10_50_1.wav')
measurement1 = ms.loadSignalFromWav(measurementPath)
# measurement1 = ms.loadSignalFromWav('C:\\Users\\Matt\\.vibe\\upload\\The Admiral Roaring Currents.wav')
# measurement2 = ms.loadSignalFromWav('C:\\Users\\Matt\\.vibe\\upload\\How to Train Your Dragon - Dragon Crash.wav')
plt.xlim(1, 100)
plt.ylim(-60, 0)
plt.grid()
plt.xlabel('frequency [Hz]')
f, Pxx_spec = measurement1.peakSpectrum(ref=1.0)
plt.semilogx(f, Pxx_spec)
# f, Pxx_spec = measurement2.spectrum(ref=1.0)
# plt.semilogx(f, Pxx_spec)
plt.show()
def showSpectro(self):
# measurementPath = 'C:\\Users\\\Matt\\OneDrive\\Documents\\eot\\Edge of Tomorrow - Opening.wav'
measurementPath = os.path.join(os.path.dirname(__file__), 'data', 'eot.wav')
measurement = ms.loadSignalFromWav(measurementPath)
# t, f, Sxx_spec = measurement.spectrogram()
# plt.pcolormesh(f, t, Sxx_spec)
# plt.ylim(0, 160)
cmap = plt.get_cmap('viridis')
cmap.set_under(color='k', alpha=None)
plt.specgram(measurement.samples,
NFFT=measurement.getSegmentLength(),
Fs=measurement.fs,
detrend=mlab.detrend_none,
mode='magnitude',
noverlap=measurement.getSegmentLength() / 2,
window=mlab.window_hanning,
vmin=-60,
cmap=plt.cm.gist_heat)
plt.ylim(0, 100)
plt.show()
def deconvolve(self):
measurementPath = os.path.join(os.path.dirname(__file__), '../test/data', 'white15.out')
fc = 2
plt.figure(1)
x = ms.loadSignalFromDelimitedFile(measurementPath, timeColumnIdx=0, dataColumnIdx=1, skipHeader=1)
y = ms.loadSignalFromDelimitedFile(measurementPath, timeColumnIdx=0, dataColumnIdx=2, skipHeader=1)
vibeX = Signal(self.butter_filter(x.samples, fc, x.fs, True), x.fs)
vibeY = Signal(self.butter_filter(y.samples, fc, y.fs, True), y.fs)
f, Px_spec = vibeX.spectrum()
plt.semilogy(f, Px_spec, label='x')
f, Py_spec = vibeY.spectrum()
plt.semilogy(f, Py_spec, label='y')
# show where x is > y
spec = Px_spec - Py_spec
plt.semilogy(f, spec, label='x / y')
plt.legend(loc='lower right')
plt.tight_layout()
plt.grid(True)
plt.show()
def woot(self):
measurementPath = os.path.join(os.path.dirname(__file__), '../test/data', 'white15.out')
self.doGraphs(measurementPath, 'mpu', 0)
def doGraphs(self, measurementPath, prefix, start=None):
fc = 2
plt.figure(1)
x = ms.loadSignalFromDelimitedFile(measurementPath, timeColumnIdx=0, dataColumnIdx=1, skipHeader=1)
y = ms.loadSignalFromDelimitedFile(measurementPath, timeColumnIdx=0, dataColumnIdx=2, skipHeader=1)
z = ms.loadSignalFromDelimitedFile(measurementPath, timeColumnIdx=0, dataColumnIdx=3, skipHeader=1)
plt.subplot(311)
plt.plot(z.samples, label=prefix + ' raw z')
plt.plot(x.samples, label=prefix + ' raw x')
plt.plot(y.samples, label=prefix + ' raw y')
plt.legend(loc='lower right')
plt.tight_layout()
plt.grid(True)
plt.subplot(312)
vibeX = self.butter_filter(x.samples, fc, x.fs, True)
vibeY = self.butter_filter(y.samples, fc, y.fs, True)
vibeZ = self.butter_filter(z.samples, fc, z.fs, True)
plt.plot(self.truncateSamples(vibeZ, start), label=prefix + ' recorder z')
plt.plot(self.truncateSamples(vibeX, start), label=prefix + ' recorder x')
plt.plot(self.truncateSamples(vibeY, start), label=prefix + ' recorder y')
plt.legend(loc='lower right')
plt.tight_layout()
plt.grid(True)
plt.subplot(313)
tiltX = self.butter_filter(x.samples, fc, x.fs, False)
tiltY = self.butter_filter(y.samples, fc, y.fs, False)
tiltZ = self.butter_filter(z.samples, fc, z.fs, False)
plt.plot(self.truncateSamples(tiltZ, start), label=prefix + ' tilt z')
plt.plot(self.truncateSamples(tiltX, start), label=prefix + ' tilt x')
plt.plot(self.truncateSamples(tiltY, start), label=prefix + ' tilt y')
plt.grid(True)
plt.tight_layout()
plt.legend(loc='lower right')
plt.figure(2)
ax1 = plt.subplot(311)
plt.setp(ax1.get_xticklabels(), visible=False)
from analyser.common.signal import Signal
measX = Signal(self.truncateSamples(vibeX, start), x.fs)
measY = Signal(self.truncateSamples(vibeY, start), y.fs)
measZ = Signal(self.truncateSamples(vibeZ, start), z.fs)
f, Pxz_spec = measZ.peakSpectrum()
plt.semilogy(f, Pxz_spec, label=prefix + ' peak z')
f, Pxx_spec = measX.peakSpectrum()
plt.semilogy(f, Pxx_spec, label=prefix + ' peak x')
f, Pxy_spec = measY.peakSpectrum()
plt.semilogy(f, Pxy_spec, label=prefix + ' peak y')
sumPeakSpec = ((Pxx_spec * 2.2) ** 2 + (Pxy_spec * 2.4) ** 2 + (Pxz_spec) ** 2) ** 0.5
plt.semilogy(f, sumPeakSpec, label=prefix + ' peak sum')
plt.grid(True)
plt.xlim(xmax=100)
plt.legend(loc='lower right')
ax2 = plt.subplot(312, sharex=ax1)
plt.setp(ax2.get_xticklabels(), visible=False)
f, Pxz_spec = measZ.spectrum()
plt.semilogy(f, Pxz_spec, label=prefix + ' avg z')
f, Pxx_spec = measX.spectrum()
plt.semilogy(f, Pxx_spec, label=prefix + ' avg x')
f, Pxy_spec = measY.spectrum()
plt.semilogy(f, Pxy_spec, label=prefix + ' avg y')
sumAvgSpec = ((Pxx_spec * 2.2) ** 2 + (Pxy_spec * 2.4) ** 2 + (Pxz_spec) ** 2) ** 0.5
plt.semilogy(f, sumAvgSpec, label=prefix + ' avg sum')
plt.grid(True)
plt.xlim(xmax=100)
plt.tight_layout()
plt.legend(loc='lower right')
ax3 = plt.subplot(313, sharex=ax1)
plt.setp(ax3.get_xticklabels(), visible=True)
f, Pxz_spec = measZ.psd()
plt.semilogy(f, Pxz_spec, label=prefix + ' psd z')
f, Pxx_spec = measX.psd()
plt.semilogy(f, Pxx_spec, label=prefix + ' psd x')
f, Pxy_spec = measY.psd()
plt.semilogy(f, Pxx_spec, label=prefix + ' psd y')
sumPsd = ((Pxx_spec * 2.2) ** 2 + (Pxy_spec * 2.4) ** 2 + (Pxz_spec) ** 2) ** 0.5
plt.semilogy(f, sumPsd, label=prefix + ' psd sum')
plt.grid(True)
plt.legend(loc='lower right')
plt.xlim(xmax=100)
plt.tight_layout()
plt.subplots_adjust(hspace=.0)
plt.show()
def truncateSamples(self, meas, start=None):
if start is None:
return meas
else:
return meas[start:]
def butter(self, cut, fs, isHigh, order=6):
nyq = 0.5 * fs
f3 = cut / nyq
from scipy import signal
b, a = signal.butter(order, f3, btype='high' if isHigh else 'low')
return b, a
def butter_filter(self, data, f3, fs, isHigh, order=2):
b, a = self.butter(f3, fs, isHigh, order=order)
from scipy import signal
y = signal.filtfilt(b, a, data)
return y
|
class HandlerTestCase(object):
def resam(self):
pass
def spec(self):
pass
def librosaSpectrum(self):
pass
def librosaResample(self):
pass
def showSpectrum(self):
pass
def showSpectro(self):
pass
def deconvolve(self):
pass
def woot(self):
pass
def doGraphs(self, measurementPath, prefix, start=None):
pass
def truncateSamples(self, meas, start=None):
pass
def butter(self, cut, fs, isHigh, order=6):
pass
def butter_filter(self, data, f3, fs, isHigh, order=2):
pass
| 13 | 0 | 21 | 1 | 18 | 2 | 1 | 0.09 | 1 | 3 | 1 | 0 | 12 | 0 | 12 | 12 | 258 | 27 | 211 | 87 | 193 | 20 | 201 | 87 | 183 | 2 | 1 | 1 | 14 |
745 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/core/handler.py
|
handler.AsyncHandler
|
class AsyncHandler(DataHandler):
"""
A handler which hands the data off to another thread.
"""
def __init__(self, owner, delegate):
self.logger = logging.getLogger(owner + '.asynchandler')
self.name = "Async"
self.delegate = delegate
self.queue = Queue()
self.worker = None
self.working = False
self.stopping = False
def start(self, measurementId):
self.delegate.start(measurementId)
self.worker = threading.Thread(target=self.asyncHandle, daemon=True)
self.working = True
self.logger.info('Starting async handler for ' + measurementId)
self.worker.start()
def handle(self, data):
self.queue.put(data)
def stop(self, measurementId, failureReason=None):
# TODO do we need to link this stop to the status of the accelerometer
self.logger.info('Stopping async handler for ' + measurementId)
self.stopping = True
self.queue.join()
self.delegate.stop(measurementId, failureReason=failureReason)
self.logger.info('Stopped async handler for ' + measurementId)
self.working = False
def asyncHandle(self):
remaining = -1
while self.working:
try:
event = self.queue.get(timeout=1)
if event is not None:
self.delegate.handle(event)
self.queue.task_done()
if self.logger.isEnabledFor(logging.DEBUG):
self.logger.debug('async queue has ' + str(self.queue.qsize()) + ' items')
elif self.stopping:
if remaining == -1:
remaining = self.queue.qsize()
self.logger.info('Closing down asynchandler, ' + str(remaining) + ' items remaining')
remaining -= 1
except Empty:
pass
|
class AsyncHandler(DataHandler):
'''
A handler which hands the data off to another thread.
'''
def __init__(self, owner, delegate):
pass
def start(self, measurementId):
pass
def handle(self, data):
pass
def stop(self, measurementId, failureReason=None):
pass
def asyncHandle(self):
pass
| 6 | 1 | 8 | 0 | 8 | 0 | 2 | 0.1 | 1 | 3 | 0 | 0 | 5 | 7 | 5 | 8 | 50 | 5 | 41 | 15 | 35 | 4 | 40 | 15 | 34 | 7 | 1 | 5 | 11 |
746 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/core/handler.py
|
handler.CSVLogger
|
class CSVLogger(DataHandler):
"""
A handler which logs the received data to CSV into target/measurementId/loggerName/data.out
"""
def __init__(self, owner, name, target):
self.logger = logging.getLogger(owner + '.csvlogger')
self.name = name
self.target = target
self.started = False
self._csv = None
self._csvfile = None
self._first = True
def start(self, measurementId):
targetDir = os.path.join(self.target, measurementId, self.name)
if not os.path.exists(targetDir):
os.makedirs(targetDir, exist_ok=True)
targetPath = os.path.join(targetDir, 'data.out')
if os.path.exists(targetPath):
mode = 'w'
else:
mode = 'x'
self._csvfile = open(targetPath, mode=mode, newline='')
self._csv = csv.writer(self._csvfile)
self.started = True
self._first = True
def handle(self, data):
"""
Writes each sample to a csv file.
:param data: the samples.
:return:
"""
self.logger.debug("Handling " + str(len(data)) + " data items")
for datum in data:
if isinstance(datum, dict):
# these have to wrapped in a list for python 3.4 due to a change in the implementation
# of OrderedDict in python 3.5+ (which means .keys() and .values() are sequences in 3.5+)
if self._first:
self._csv.writerow(list(datum.keys()))
self._first = False
self._csv.writerow(list(datum.values()))
elif isinstance(datum, list):
self._csv.writerow(datum)
else:
self.logger.warning("Ignoring unsupported data type " + str(type(datum)) + " : " + str(datum))
def stop(self, measurementId, failureReason=None):
if self._csvfile is not None:
self.logger.debug("Closing csvfile for " + measurementId)
self._csvfile.close()
|
class CSVLogger(DataHandler):
'''
A handler which logs the received data to CSV into target/measurementId/loggerName/data.out
'''
def __init__(self, owner, name, target):
pass
def start(self, measurementId):
pass
def handle(self, data):
'''
Writes each sample to a csv file.
:param data: the samples.
:return:
'''
pass
def stop(self, measurementId, failureReason=None):
pass
| 5 | 2 | 11 | 0 | 9 | 2 | 3 | 0.26 | 1 | 4 | 0 | 0 | 4 | 7 | 4 | 7 | 52 | 4 | 38 | 16 | 33 | 10 | 35 | 16 | 30 | 5 | 1 | 3 | 11 |
747 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/core/handler.py
|
handler.Discarder
|
class Discarder(DataHandler):
"""
a data handler that simply throws the data away
"""
def start(self, measurementId):
pass
def handle(self, data):
pass
def stop(self, measurementId, failureReason=None):
pass
|
class Discarder(DataHandler):
'''
a data handler that simply throws the data away
'''
def start(self, measurementId):
pass
def handle(self, data):
pass
def stop(self, measurementId, failureReason=None):
pass
| 4 | 1 | 2 | 0 | 2 | 0 | 1 | 0.43 | 1 | 0 | 0 | 0 | 3 | 0 | 3 | 6 | 13 | 3 | 7 | 4 | 3 | 3 | 7 | 4 | 3 | 1 | 1 | 0 | 3 |
748 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/core/handler.py
|
handler.HttpPoster
|
class HttpPoster(DataHandler):
"""
A handler which sends the data over http.
"""
def __init__(self, name, target, httpclient=RequestsBasedHttpClient()):
self.name = name
self.logger = logging.getLogger(name + '.httpposter')
self.httpclient = httpclient
self.target = target[:-1] if target.endswith('/') else target
self.deviceName = None
self.rootURL = self.target + API_PREFIX + '/measurements/'
self.sendURL = None
self.startResponseCode = None
self.dataResponseCode = []
self.endResponseCode = None
def start(self, measurementId):
"""
Posts to the target to tell it a named measurement is starting.
:param measurementId:
"""
self.sendURL = self.rootURL + measurementId + '/' + self.deviceName
self.startResponseCode = self._doPut(self.sendURL)
def _doPut(self, url, data=None):
formattedPayload = None if data is None else json.dumps(data, sort_keys=True)
try:
return self.httpclient.put(url, json=formattedPayload).status_code
except Exception as e:
self.logger.exception(e)
return 500
def handle(self, data):
"""
puts the data in the target.
:param data: the data to post.
:return:
"""
self.dataResponseCode.append(self._doPut(self.sendURL + '/data', data=data))
def stop(self, measurementId, failureReason=None):
"""
informs the target the named measurement has completed
:param measurementId: the measurement that has completed.
:return:
"""
if failureReason is None:
self.endResponseCode = self._doPut(self.sendURL + "/complete")
else:
self.endResponseCode = self._doPut(self.sendURL + "/failed", data={'failureReason': failureReason})
self.sendURL = None
|
class HttpPoster(DataHandler):
'''
A handler which sends the data over http.
'''
def __init__(self, name, target, httpclient=RequestsBasedHttpClient()):
pass
def start(self, measurementId):
'''
Posts to the target to tell it a named measurement is starting.
:param measurementId:
'''
pass
def _doPut(self, url, data=None):
pass
def handle(self, data):
'''
puts the data in the target.
:param data: the data to post.
:return:
'''
pass
def stop(self, measurementId, failureReason=None):
'''
informs the target the named measurement has completed
:param measurementId: the measurement that has completed.
:return:
'''
pass
| 6 | 4 | 9 | 0 | 6 | 3 | 2 | 0.57 | 1 | 2 | 1 | 0 | 5 | 10 | 5 | 8 | 52 | 5 | 30 | 18 | 24 | 17 | 29 | 17 | 23 | 3 | 1 | 1 | 9 |
749 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/recorder/common/heartbeater.py
|
heartbeater.Heartbeater
|
class Heartbeater(object):
def __init__(self, httpclient, cfg, serverURL=None):
self.httpclient = httpclient
self.cfg = cfg
self.serverURL = serverURL
def ping(self):
"""
Posts the current state of each device to the server and schedules the next call in n seconds.
:param serverURL:
:return:
"""
from datetime import datetime
nextRun = datetime.utcnow().timestamp() + self.cfg.getPingInterval()
self.sendHeartbeat()
self.scheduleNextHeartbeat(nextRun)
def sendHeartbeat(self):
"""
Posts the current state to the server.
:param serverURL: the URL to ping.
:return:
"""
for name, md in self.cfg.recordingDevices.items():
try:
data = marshal(md, recordingDeviceFields)
data['serviceURL'] = self.cfg.getServiceURL() + API_PREFIX + '/devices/' + name
targetURL = self.serverURL + API_PREFIX + '/devices/' + name
logger.info("Pinging " + targetURL)
resp = self.httpclient.put(targetURL, json=data)
if resp.status_code != 200:
logger.warning("Unable to ping server at " + targetURL + " with " + str(data.keys()) +
", response is " + str(resp.status_code))
else:
logger.info("Pinged server at " + targetURL + " with " + str(data.items()))
except:
logger.exception("Unable to ping server")
def scheduleNextHeartbeat(self, nextRun):
"""
Schedules the next ping.
:param nextRun: when we should run next.
:param serverURL: the URL to ping.
:return:
"""
import threading
from datetime import datetime
tilNextTime = max(nextRun - datetime.utcnow().timestamp(), 0)
logging.getLogger('recorder').info("Scheduling next ping in " + str(round(tilNextTime, 3)) + " seconds")
threading.Timer(tilNextTime, self.ping).start()
|
class Heartbeater(object):
def __init__(self, httpclient, cfg, serverURL=None):
pass
def ping(self):
'''
Posts the current state of each device to the server and schedules the next call in n seconds.
:param serverURL:
:return:
'''
pass
def sendHeartbeat(self):
'''
Posts the current state to the server.
:param serverURL: the URL to ping.
:return:
'''
pass
def scheduleNextHeartbeat(self, nextRun):
'''
Schedules the next ping.
:param nextRun: when we should run next.
:param serverURL: the URL to ping.
:return:
'''
pass
| 5 | 3 | 12 | 0 | 8 | 4 | 2 | 0.52 | 1 | 3 | 0 | 0 | 4 | 3 | 4 | 4 | 50 | 3 | 31 | 17 | 23 | 16 | 29 | 17 | 21 | 4 | 1 | 3 | 7 |
750 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/core/httpclient.py
|
httpclient.RecordingHttpClient
|
class RecordingHttpClient(HttpClient):
"""
An implementation of httpclient intended for use by test cases as it simply records each call in a list.
"""
def __init__(self):
self.record = []
def post(self, url, **kwargs):
self.record.append(('post', url, kwargs))
return self._resp()
def _resp(self):
from unittest.mock import Mock
mock = Mock()
mock.status_code = 200
return mock
def patch(self, url, **kwargs):
self.record.append(('patch', url, kwargs))
return self._resp()
def put(self, url, **kwargs):
self.record.append(('put', url, kwargs))
return self._resp()
def delete(self, url, **kwargs):
self.record.append(('delete', url, kwargs))
return self._resp()
def get(self, url, **kwargs):
self.record.append(('get', url, kwargs))
return self._resp()
|
class RecordingHttpClient(HttpClient):
'''
An implementation of httpclient intended for use by test cases as it simply records each call in a list.
'''
def __init__(self):
pass
def post(self, url, **kwargs):
pass
def _resp(self):
pass
def patch(self, url, **kwargs):
pass
def put(self, url, **kwargs):
pass
def delete(self, url, **kwargs):
pass
def get(self, url, **kwargs):
pass
| 8 | 1 | 3 | 0 | 3 | 0 | 1 | 0.13 | 1 | 1 | 0 | 0 | 7 | 1 | 7 | 12 | 33 | 7 | 23 | 11 | 14 | 3 | 23 | 11 | 14 | 1 | 2 | 0 | 7 |
751 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/core/httpclient.py
|
httpclient.RequestException
|
class RequestException(Exception):
"""
exists to decouple the caller from the requests specific exception
"""
pass
|
class RequestException(Exception):
'''
exists to decouple the caller from the requests specific exception
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 5 | 0 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 0 | 3 | 0 | 0 |
752 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/recorder/common/i2c_io.py
|
i2c_io.WhiteNoiseProvider
|
class WhiteNoiseProvider(MockIoDataProvider):
"""
A mock io provider which yields white noise.
"""
def __init__(self):
import numpy as np
self.samples = {
'x': np.random.normal(0, 0.25, size=1000),
'y': np.random.normal(0, 0.25, size=1000),
'z': np.random.normal(0, 0.25, size=1000)
}
self.idx = 0
def provide(self, register, length=None):
if register is mpu6050.MPU6050_RA_INT_STATUS:
return 0x01
elif register is mpu6050.MPU6050_RA_FIFO_COUNTH:
return [0b0000, 0b1100]
elif register is mpu6050.MPU6050_RA_FIFO_R_W:
bytes = bytearray()
self.addValue(bytes, 'x')
self.addValue(bytes, 'y')
self.addValue(bytes, 'z')
self.idx += 1
self.addValue(bytes, 'x')
self.addValue(bytes, 'y')
self.addValue(bytes, 'z')
return bytes
else:
if length is None:
return 0b00000000
else:
return [x.to_bytes(1, 'big') for x in range(length)]
def addValue(self, bytes, key):
val = abs(int((self.samples[key][self.idx % 1000] * 32768)))
try:
b = bytearray(val.to_bytes(2, 'big'))
except OverflowError:
print("Value too big - " + str(val) + " - replacing with 0")
val = 0
b = bytearray(val.to_bytes(2, 'big'))
bytes.extend(b)
|
class WhiteNoiseProvider(MockIoDataProvider):
'''
A mock io provider which yields white noise.
'''
def __init__(self):
pass
def provide(self, register, length=None):
pass
def addValue(self, bytes, key):
pass
| 4 | 1 | 13 | 0 | 12 | 0 | 3 | 0.08 | 1 | 6 | 1 | 0 | 3 | 2 | 3 | 4 | 45 | 4 | 38 | 10 | 33 | 3 | 30 | 10 | 25 | 5 | 1 | 2 | 8 |
753 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/analyser/common/signal.py
|
signal.TriAxisSignal
|
class TriAxisSignal(object):
"""
A measurement that has data on multiple, independent, axes.
"""
def __init__(self, x, y, z):
self.cache = {
'raw': {
'x': x,
'y': y,
'z': z,
}
}
def _canSum(self, analysis):
return analysis == 'spectrum' or analysis == 'peakSpectrum'
def raw(self, axis):
"""
:param axis: the axis
:return: time vs measured acceleration.
"""
return self._getRaw(axis, 'raw')
def vibration(self, axis):
"""
:param axis: the axis
:return: time vs high passed acceleration to remove gravity.
"""
return self._getRaw(axis, 'vibration')
def tilt(self, axis):
"""
:param axis: the axis
:return: time vs high low acceleration to isolate gravity.
"""
return self._getRaw(axis, 'tilt')
def _getRaw(self, axis, analysis):
cache = self.cache['raw']
if axis in cache:
return getattr(cache.get(axis), analysis)()
else:
return None
def spectrum(self, axis):
"""
:param axis: the axis
:return: the spectrum for the given axis.
"""
return self._getAnalysis(axis, 'spectrum', ref=LA_REFERENCE_ACCELERATION_IN_G)
def peakSpectrum(self, axis):
"""
:param axis: the axis
:return: the peak spectrum for the given axis.
"""
return self._getAnalysis(axis, 'peakSpectrum', ref=LA_REFERENCE_ACCELERATION_IN_G)
def psd(self, axis):
"""
:param axis: the axis
:return: the psd for the given axis.
"""
return self._getAnalysis(axis, 'psd', ref=0.001)
def _getAnalysis(self, axis, analysis, ref=None):
"""
gets the named analysis on the given axis and caches the result (or reads from the cache if data is available
already)
:param axis: the named axis.
:param analysis: the analysis name.
:return: the analysis tuple.
"""
cache = self.cache.get(str(ref))
if cache is None:
cache = {'x': {}, 'y': {}, 'z': {}, 'sum': {}}
self.cache[str(ref)] = cache
if axis in cache:
data = self.cache['raw'].get(axis, None)
cachedAxis = cache.get(axis)
if cachedAxis.get(analysis) is None:
if axis == 'sum':
if self._canSum(analysis):
fx, Pxx = self._getAnalysis('x', analysis)
fy, Pxy = self._getAnalysis('y', analysis)
fz, Pxz = self._getAnalysis('z', analysis)
# calculate the sum of the squares with an additional weighting for x and y
Psum = (((Pxx * 2.2) ** 2) + ((Pxy * 2.4) ** 2) + (Pxz ** 2)) ** 0.5
if ref is not None:
Psum = librosa.amplitude_to_db(Psum, ref)
cachedAxis[analysis] = (fx, Psum)
else:
return None
else:
cachedAxis[analysis] = getattr(data.highPass(), analysis)(ref=ref)
return cachedAxis[analysis]
else:
return None
|
class TriAxisSignal(object):
'''
A measurement that has data on multiple, independent, axes.
'''
def __init__(self, x, y, z):
pass
def _canSum(self, analysis):
pass
def raw(self, axis):
'''
:param axis: the axis
:return: time vs measured acceleration.
'''
pass
def vibration(self, axis):
'''
:param axis: the axis
:return: time vs high passed acceleration to remove gravity.
'''
pass
def tilt(self, axis):
'''
:param axis: the axis
:return: time vs high low acceleration to isolate gravity.
'''
pass
def _getRaw(self, axis, analysis):
pass
def spectrum(self, axis):
'''
:param axis: the axis
:return: the spectrum for the given axis.
'''
pass
def peakSpectrum(self, axis):
'''
:param axis: the axis
:return: the peak spectrum for the given axis.
'''
pass
def psd(self, axis):
'''
:param axis: the axis
:return: the psd for the given axis.
'''
pass
def _getAnalysis(self, axis, analysis, ref=None):
'''
gets the named analysis on the given axis and caches the result (or reads from the cache if data is available
already)
:param axis: the named axis.
:param analysis: the analysis name.
:return: the analysis tuple.
'''
pass
| 11 | 8 | 9 | 0 | 5 | 3 | 2 | 0.65 | 1 | 1 | 0 | 0 | 10 | 1 | 10 | 10 | 99 | 10 | 54 | 20 | 43 | 35 | 44 | 20 | 33 | 7 | 1 | 5 | 17 |
754 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/analyser/resources/measurementdevices.py
|
measurementdevices.MeasurementDevice
|
class MeasurementDevice(Resource):
"""
the current state of a single device.
"""
def __init__(self, **kwargs):
self._deviceController = kwargs['deviceController']
def put(self, deviceId):
"""
Puts a new device into the device store
:param deviceId:
:return:
"""
device = request.get_json()
logger.debug("Received /devices/" + deviceId + " - " + str(device))
self._deviceController.accept(deviceId, device)
return None, 200
|
class MeasurementDevice(Resource):
'''
the current state of a single device.
'''
def __init__(self, **kwargs):
pass
def put(self, deviceId):
'''
Puts a new device into the device store
:param deviceId:
:return:
'''
pass
| 3 | 2 | 6 | 0 | 4 | 3 | 1 | 1 | 1 | 1 | 0 | 0 | 2 | 1 | 2 | 2 | 18 | 2 | 8 | 5 | 5 | 8 | 8 | 5 | 5 | 1 | 1 | 0 | 2 |
755 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/analyser/resources/target.py
|
target.Target
|
class Target(Resource):
def __init__(self, **kwargs):
self._targetController = kwargs['targetController']
def get(self, targetId):
"""
Yields the analysed wav data.
:param targetId:
:return:
"""
result = self._targetController.analyse(targetId)
if result:
if len(result) == 2:
if result[1] == 404:
return result
else:
return {'name': targetId, 'data': self._jsonify(result)}, 200
else:
return None, 404
else:
return None, 500
def put(self, targetId):
"""
stores a new target.
:param targetId: the target to store.
:return:
"""
json = request.get_json()
if 'hinge' in json:
logger.info('Storing target ' + targetId)
if self._targetController.storeFromHinge(targetId, json['hinge']):
logger.info('Stored target ' + targetId)
return None, 200
else:
return None, 500
else:
return None, 400
def delete(self, targetId):
"""
deletes the specified target.
:param targetId:
:return:
"""
if self._targetController.delete(targetId):
return None, 200
else:
return None, 500
def _jsonify(self, tup):
return {'freq': tup[0].tolist(), 'val': tup[1].tolist()}
|
class Target(Resource):
def __init__(self, **kwargs):
pass
def get(self, targetId):
'''
Yields the analysed wav data.
:param targetId:
:return:
'''
pass
def put(self, targetId):
'''
stores a new target.
:param targetId: the target to store.
:return:
'''
pass
def delete(self, targetId):
'''
deletes the specified target.
:param targetId:
:return:
'''
pass
def _jsonify(self, tup):
pass
| 6 | 3 | 9 | 0 | 6 | 3 | 2 | 0.45 | 1 | 0 | 0 | 0 | 5 | 1 | 5 | 5 | 52 | 4 | 33 | 9 | 27 | 15 | 27 | 9 | 21 | 4 | 1 | 3 | 11 |
756 |
3ll3d00d/vibe
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/3ll3d00d_vibe/backend/src/analyser/resources/measurement.py
|
measurement.Measurement
|
class Measurement(Resource):
"""
Accepts requests from the front end to trigger measurements.
"""
def __init__(self, **kwargs):
self._measurementController = kwargs['measurementController']
@marshal_with(measurementFields)
def get(self, measurementId):
measurement = self._measurementController.getMeasurement(measurementId)
return measurement, 200 if measurement else 404
def patch(self, measurementId):
"""
Patches the metadata associated with the new measurement, if this impacts the measurement length then a new
measurement is created otherwise it just updates it in place.
:param measurementId:
:return:
"""
data = request.get_json()
if data is not None:
logger.debug('Received payload for ' +
measurementId + ' - ' + str(data))
if self._measurementController.editMeasurement(measurementId, data):
return None, 200
else:
logger.warning('Unable to edit payload ' + measurementId)
return None, 404
else:
logger.error('Invalid data payload received ' + measurementId)
return None, 400
def put(self, measurementId):
"""
Initiates a new measurement. Accepts a json payload with the following attributes;
* duration: in seconds
* startTime OR delay: a date in YMD_HMS format or a delay in seconds
* description: some free text information about the measurement
:return:
"""
json = request.get_json()
try:
start = self._calculateStartTime(json)
except ValueError:
return 'invalid date format in request', 400
duration = json['duration'] if 'duration' in json else 10
if start is None:
# should never happen but just in case
return 'no start time', 400
else:
scheduled, message = self._measurementController.schedule(measurementId, duration, start,
description=json.get('description'))
return message, 200 if scheduled else 400
def _calculateStartTime(self, json):
"""
Calculates an absolute start time from the json payload. This is either the given absolute start time (+2s) or
the time in delay seconds time. If the resulting date is in the past then now is returned instead.
:param json: the payload from the UI
:return: the absolute start time.
"""
start = json['startTime'] if 'startTime' in json else None
delay = json['delay'] if 'delay' in json else None
if start is None and delay is None:
return self._getAbsoluteTime(datetime.datetime.utcnow(), 2)
elif start is not None:
target = datetime.datetime.strptime(start, DATETIME_FORMAT)
if target <= datetime.datetime.utcnow():
time = self._getAbsoluteTime(datetime.datetime.utcnow(), 2)
logger.warning('Date requested is in the past (' + start + '), defaulting to ' +
time.strftime(DATETIME_FORMAT))
return time
else:
return target
elif delay is not None:
return self._getAbsoluteTime(datetime.datetime.utcnow(), delay)
else:
return None
def _getAbsoluteTime(self, start, delay):
"""
Adds the delay in seconds to the start time.
:param start:
:param delay:
:return: a datetimem for the specified point in time.
"""
return start + datetime.timedelta(days=0, seconds=delay)
@marshal_with(measurementFields)
def delete(self, measurementId):
"""
Deletes the named measurement.
:return: 200 if something was deleted, 404 if the measurement doesn't exist, 500 in any other case.
"""
message, count, deleted = self._measurementController.delete(
measurementId)
if count == 0:
return message, 404
elif deleted is None:
return message, 500
else:
return deleted, 200
|
class Measurement(Resource):
'''
Accepts requests from the front end to trigger measurements.
'''
def __init__(self, **kwargs):
pass
@marshal_with(measurementFields)
def get(self, measurementId):
pass
def patch(self, measurementId):
'''
Patches the metadata associated with the new measurement, if this impacts the measurement length then a new
measurement is created otherwise it just updates it in place.
:param measurementId:
:return:
'''
pass
def put(self, measurementId):
'''
Initiates a new measurement. Accepts a json payload with the following attributes;
* duration: in seconds
* startTime OR delay: a date in YMD_HMS format or a delay in seconds
* description: some free text information about the measurement
:return:
'''
pass
def _calculateStartTime(self, json):
'''
Calculates an absolute start time from the json payload. This is either the given absolute start time (+2s) or
the time in delay seconds time. If the resulting date is in the past then now is returned instead.
:param json: the payload from the UI
:return: the absolute start time.
'''
pass
def _getAbsoluteTime(self, start, delay):
'''
Adds the delay in seconds to the start time.
:param start:
:param delay:
:return: a datetimem for the specified point in time.
'''
pass
@marshal_with(measurementFields)
def delete(self, measurementId):
'''
Deletes the named measurement.
:return: 200 if something was deleted, 404 if the measurement doesn't exist, 500 in any other case.
'''
pass
| 10 | 6 | 13 | 0 | 8 | 4 | 3 | 0.54 | 1 | 4 | 0 | 0 | 7 | 1 | 7 | 7 | 103 | 9 | 61 | 22 | 51 | 33 | 48 | 20 | 40 | 7 | 1 | 2 | 22 |
757 |
3ll3d00d/vibe
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/3ll3d00d_vibe/backend/src/analyser/app.py
|
app.main.ReactIndex
|
class ReactIndex(static.File):
"""
a twisted File which overrides getChild so it always just serves index.html (NB: this is a bit of a hack,
there is probably a more correct way to do this but...)
"""
def getChild(self, path, request):
return self
|
class ReactIndex(static.File):
'''
a twisted File which overrides getChild so it always just serves index.html (NB: this is a bit of a hack,
there is probably a more correct way to do this but...)
'''
def getChild(self, path, request):
pass
| 2 | 1 | 2 | 0 | 2 | 0 | 1 | 1.33 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 8 | 1 | 3 | 2 | 1 | 4 | 3 | 2 | 1 | 1 | 1 | 0 | 1 |
758 |
3ll3d00d/vibe
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/3ll3d00d_vibe/backend/src/analyser/resources/measurements.py
|
measurements.ReloadMeasurement
|
class ReloadMeasurement(Resource):
def __init__(self, **kwargs):
self._measurementController = kwargs['measurementController']
@marshal_with(measurementFields)
def get(self):
"""
Reloads the measurements from the backing store.
:return: 200 if success.
"""
try:
self._measurementController.reloadCompletedMeasurements()
return None, 200
except:
logger.exception("Failed to reload measurements")
return str(sys.exc_info()), 500
|
class ReloadMeasurement(Resource):
def __init__(self, **kwargs):
pass
@marshal_with(measurementFields)
def get(self):
'''
Reloads the measurements from the backing store.
:return: 200 if success.
'''
pass
| 4 | 1 | 7 | 0 | 5 | 2 | 2 | 0.36 | 1 | 1 | 0 | 0 | 2 | 1 | 2 | 2 | 16 | 1 | 11 | 5 | 7 | 4 | 10 | 4 | 7 | 2 | 1 | 1 | 3 |
759 |
3ll3d00d/vibe
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/3ll3d00d_vibe/backend/src/recorder/resources/recordingdevices.py
|
recordingdevices.RecordingDevice
|
class RecordingDevice(Resource):
def __init__(self, **kwargs):
self.recordingDevices = kwargs['recordingDevices']
self.heartbeater = kwargs['heartbeater']
@marshal_with(recordingDeviceFields)
def get(self, deviceId):
"""
provides details on the specific device.
:param: deviceId the device id.
"""
return self.recordingDevices.get(deviceId)
@marshal_with(recordingDeviceFields)
def patch(self, deviceId):
"""
Updates the device with the given data. Supports a json payload like
{
fs: newFs
samplesPerBatch: samplesPerBatch
gyroEnabled: true
gyroSensitivity: 500
accelerometerEnabled: true
accelerometerSensitivity: 2
}
A heartbeat is sent on completion of the request to ensure the analyser gets a rapid update.
:return: the device and 200 if the update was ok, 400 if not.
"""
try:
device = self.recordingDevices.get(deviceId)
if device.status == RecordingDeviceStatus.INITIALISED:
errors = self._handlePatch(device)
if len(errors) == 0:
return device, 200
else:
return device, 500
else:
return device, 400
finally:
logger.info("Sending adhoc heartbeat on device state update")
self.heartbeater.sendHeartbeat()
def _handlePatch(self, device):
errors = []
body = request.get_json()
newFs = body.get('fs')
if newFs is not None:
if newFs != device.fs:
device.setSampleRate(newFs)
newSamplesPerBatch = body.get('samplesPerBatch')
if newSamplesPerBatch is not None:
if newSamplesPerBatch != device.samplesPerBatch:
device.samplesPerBatch = newSamplesPerBatch
enabled = body.get('gyroEnabled')
if enabled and not device.isGyroEnabled():
device.enableGyro()
elif device.isGyroEnabled and not enabled:
device.disableGyro()
sensitivity = body.get('gyroSens')
if sensitivity is not None:
if sensitivity != device.gyroSensitivity:
try:
device.setGyroSensitivity(sensitivity)
except:
logger.exception("Invalid gyro sensitivity " + sensitivity)
errors.append("gyro sensitivity " + sensitivity)
enabled = body.get('accelerometerEnabled')
if enabled and not device.isAccelerometerEnabled():
device.enableAccelerometer()
elif device.isAccelerometerEnabled and not enabled:
device.disableAccelerometer()
sensitivity = body.get('accelerometerSens')
if sensitivity is not None:
if sensitivity != device.accelerometerSensitivity:
try:
device.setAccelerometerSensitivity(sensitivity)
except:
logger.exception(
"Invalid accelerometer sensitivity " + sensitivity)
errors.append("accelerometer sensitivity " + sensitivity)
return errors
|
class RecordingDevice(Resource):
def __init__(self, **kwargs):
pass
@marshal_with(recordingDeviceFields)
def get(self, deviceId):
'''
provides details on the specific device.
:param: deviceId the device id.
'''
pass
@marshal_with(recordingDeviceFields)
def patch(self, deviceId):
'''
Updates the device with the given data. Supports a json payload like
{
fs: newFs
samplesPerBatch: samplesPerBatch
gyroEnabled: true
gyroSensitivity: 500
accelerometerEnabled: true
accelerometerSensitivity: 2
}
A heartbeat is sent on completion of the request to ensure the analyser gets a rapid update.
:return: the device and 200 if the update was ok, 400 if not.
'''
pass
def _handlePatch(self, device):
pass
| 7 | 2 | 20 | 2 | 14 | 4 | 5 | 0.28 | 1 | 1 | 1 | 0 | 4 | 2 | 4 | 4 | 86 | 9 | 60 | 17 | 53 | 17 | 53 | 15 | 48 | 15 | 1 | 3 | 20 |
760 |
3ll3d00d/vibe
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/3ll3d00d_vibe/backend/src/recorder/resources/recordingdevices.py
|
recordingdevices.RecordingDevices
|
class RecordingDevices(Resource):
def __init__(self, **kwargs):
self.recordingDevices = kwargs['recordingDevices']
@marshal_with(recordingDeviceFields)
def get(self):
""" lists all known recordingDevices. """
return list(self.recordingDevices.values())
|
class RecordingDevices(Resource):
def __init__(self, **kwargs):
pass
@marshal_with(recordingDeviceFields)
def get(self):
''' lists all known recordingDevices. '''
pass
| 4 | 1 | 3 | 0 | 2 | 1 | 1 | 0.17 | 1 | 1 | 0 | 0 | 2 | 1 | 2 | 2 | 8 | 1 | 6 | 5 | 2 | 1 | 5 | 4 | 2 | 1 | 1 | 0 | 2 |
761 |
3ll3d00d/vibe
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/3ll3d00d_vibe/backend/src/analyser/app.py
|
app.main.FlaskAppWrapper
|
class FlaskAppWrapper(Resource):
"""
wraps the flask app as a WSGI resource while allow the react index.html (and its associated static content)
to be served as the default page.
"""
def __init__(self):
super().__init__()
self.wsgi = WSGIResource(reactor, reactor.getThreadPool(), app)
import sys
if getattr(sys, 'frozen', False):
# pyinstaller lets you copy files to arbitrary locations under the _MEIPASS root dir
uiRoot = sys._MEIPASS
else:
# release script moves the ui under the analyser package because setuptools doesn't seem to include
# files from outside the package
uiRoot = os.path.dirname(__file__)
logger.info('Serving ui from ' + str(uiRoot))
self.react = ReactApp(os.path.join(uiRoot, 'ui'))
self.static = static.File(os.path.join(uiRoot, 'ui', 'static'))
def getChild(self, path, request):
"""
Overrides getChild to allow the request to be routed to the wsgi app (i.e. flask for the rest api
calls),
the static dir (i.e. for the packaged css/js etc), the various concrete files (i.e. the public
dir from react-app) or to index.html (i.e. the react app) for everything else.
:param path:
:param request:
:return:
"""
if path == b'api':
request.prepath.pop()
request.postpath.insert(0, path)
return self.wsgi
elif path == b'static':
return self.static
else:
return self.react.getFile(path)
def render(self, request):
return self.wsgi.render(request)
|
class FlaskAppWrapper(Resource):
'''
wraps the flask app as a WSGI resource while allow the react index.html (and its associated static content)
to be served as the default page.
'''
def __init__(self):
pass
def getChild(self, path, request):
'''
Overrides getChild to allow the request to be routed to the wsgi app (i.e. flask for the rest api
calls),
the static dir (i.e. for the packaged css/js etc), the various concrete files (i.e. the public
dir from react-app) or to index.html (i.e. the react app) for everything else.
:param path:
:param request:
:return:
'''
pass
def render(self, request):
pass
| 4 | 2 | 11 | 0 | 7 | 4 | 2 | 0.7 | 1 | 3 | 1 | 0 | 3 | 3 | 3 | 3 | 42 | 3 | 23 | 9 | 18 | 16 | 20 | 9 | 15 | 3 | 1 | 1 | 6 |
762 |
3ll3d00d/vibe
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/3ll3d00d_vibe/backend/src/analyser/resources/measurementdevices.py
|
measurementdevices.MeasurementDevices
|
class MeasurementDevices(Resource):
def __init__(self, **kwargs):
self._deviceController = kwargs['deviceController']
@marshal_with(deviceFields)
def get(self):
"""
Gets the currently available devices.
:return: the devices.
"""
return self._deviceController.getDevices()
|
class MeasurementDevices(Resource):
def __init__(self, **kwargs):
pass
@marshal_with(deviceFields)
def get(self):
'''
Gets the currently available devices.
:return: the devices.
'''
pass
| 4 | 1 | 4 | 0 | 2 | 2 | 1 | 0.67 | 1 | 0 | 0 | 0 | 2 | 1 | 2 | 2 | 11 | 1 | 6 | 5 | 2 | 4 | 5 | 4 | 2 | 1 | 1 | 0 | 2 |
763 |
3ll3d00d/vibe
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/3ll3d00d_vibe/backend/src/analyser/app.py
|
app.main.ReactApp
|
class ReactApp:
"""
Handles the react app (excluding the static dir).
"""
def __init__(self, path):
# TODO allow this to load when in debug mode even if the files don't exist
self.publicFiles = {f: static.File(os.path.join(path, f)) for f in os.listdir(path) if
os.path.exists(os.path.join(path, f))}
self.indexHtml = ReactIndex(os.path.join(path, 'index.html'))
def getFile(self, path):
"""
overrides getChild so it always just serves index.html unless the file does actually exist (i.e. is an
icon or something like that)
"""
return self.publicFiles.get(path.decode('utf-8'), self.indexHtml)
|
class ReactApp:
'''
Handles the react app (excluding the static dir).
'''
def __init__(self, path):
pass
def getFile(self, path):
'''
overrides getChild so it always just serves index.html unless the file does actually exist (i.e. is an
icon or something like that)
'''
pass
| 3 | 2 | 6 | 0 | 3 | 3 | 1 | 1.14 | 0 | 1 | 1 | 0 | 2 | 2 | 2 | 2 | 17 | 2 | 7 | 5 | 4 | 8 | 6 | 5 | 3 | 1 | 0 | 0 | 2 |
764 |
3ll3d00d/vibe
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/3ll3d00d_vibe/versioneer.py
|
versioneer.get_cmdclass.cmd_build_exe
|
class cmd_build_exe(_build_exe):
def run(self):
root = get_root()
cfg = get_config_from_root(root)
versions = get_versions()
target_versionfile = cfg.versionfile_source
print("UPDATING %s" % target_versionfile)
write_to_version_file(target_versionfile, versions)
_build_exe.run(self)
os.unlink(target_versionfile)
with open(cfg.versionfile_source, "w") as f:
LONG = LONG_VERSION_PY[cfg.VCS]
f.write(LONG %
{"DOLLAR": "$",
"STYLE": cfg.style,
"TAG_PREFIX": cfg.tag_prefix,
"PARENTDIR_PREFIX": cfg.parentdir_prefix,
"VERSIONFILE_SOURCE": cfg.versionfile_source,
})
|
class cmd_build_exe(_build_exe):
def run(self):
pass
| 2 | 0 | 19 | 1 | 18 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 20 | 1 | 19 | 8 | 17 | 0 | 13 | 7 | 11 | 1 | 1 | 1 | 1 |
765 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/recorder/common/smbus_io.py
|
smbus_io.smbus_io
|
class smbus_io(i2c_io):
"""
an implementation of i2c_io which talks over the smbus.
"""
def __init__(self, busId=1):
super().__init__()
self.bus = SMBus(bus=busId)
"""
Delegates to smbus.write_byte_data
"""
def write(self, i2cAddress, register, val):
return self.bus.write_byte_data(i2cAddress, register, val)
"""
Delegates to smbus.read_byte_data
"""
def read(self, i2cAddress, register):
return self.bus.read_byte_data(i2cAddress, register)
"""
Delegates to smbus.read_i2c_block_data
"""
def readBlock(self, i2cAddress, register, length):
return self.bus.read_i2c_block_data(i2cAddress, register, length)
|
class smbus_io(i2c_io):
'''
an implementation of i2c_io which talks over the smbus.
'''
def __init__(self, busId=1):
pass
def write(self, i2cAddress, register, val):
pass
def read(self, i2cAddress, register):
pass
def readBlock(self, i2cAddress, register, length):
pass
| 5 | 1 | 2 | 0 | 2 | 0 | 1 | 1.2 | 1 | 1 | 0 | 0 | 4 | 1 | 4 | 8 | 29 | 7 | 10 | 6 | 5 | 12 | 10 | 6 | 5 | 1 | 2 | 0 | 4 |
766 |
3ll3d00d/vibe
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/3ll3d00d_vibe/versioneer.py
|
versioneer.get_cmdclass.cmd_version
|
class cmd_version(Command):
description = "report generated version string"
user_options = []
boolean_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
vers = get_versions(verbose=True)
print("Version: %s" % vers["version"])
print(" full-revisionid: %s" % vers.get("full-revisionid"))
print(" dirty: %s" % vers.get("dirty"))
print(" date: %s" % vers.get("date"))
if vers["error"]:
print(" error: %s" % vers["error"])
|
class cmd_version(Command):
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
pass
| 4 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 3 | 0 | 3 | 3 | 19 | 3 | 16 | 8 | 12 | 0 | 16 | 8 | 12 | 2 | 1 | 1 | 4 |
767 |
3ll3d00d/vibe
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/3ll3d00d_vibe/versioneer.py
|
versioneer.get_cmdclass.cmd_sdist
|
class cmd_sdist(_sdist):
def run(self):
versions = get_versions()
self._versioneer_generated_versions = versions
# unless we update this, the command will keep using the old
# version
self.distribution.metadata.version = versions["version"]
return _sdist.run(self)
def make_release_tree(self, base_dir, files):
root = get_root()
cfg = get_config_from_root(root)
_sdist.make_release_tree(self, base_dir, files)
# now locate _version.py in the new base_dir directory
# (remembering that it may be a hardlink) and replace it with an
# updated value
target_versionfile = os.path.join(base_dir, cfg.versionfile_source)
print("UPDATING %s" % target_versionfile)
write_to_version_file(target_versionfile,
self._versioneer_generated_versions)
|
class cmd_sdist(_sdist):
def run(self):
pass
def make_release_tree(self, base_dir, files):
pass
| 3 | 0 | 9 | 0 | 7 | 3 | 1 | 0.36 | 1 | 0 | 0 | 0 | 2 | 1 | 2 | 2 | 20 | 1 | 14 | 8 | 11 | 5 | 13 | 8 | 10 | 1 | 1 | 0 | 2 |
768 |
3ll3d00d/vibe
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/3ll3d00d_vibe/versioneer.py
|
versioneer.get_cmdclass.cmd_py2exe
|
class cmd_py2exe(_py2exe):
def run(self):
root = get_root()
cfg = get_config_from_root(root)
versions = get_versions()
target_versionfile = cfg.versionfile_source
print("UPDATING %s" % target_versionfile)
write_to_version_file(target_versionfile, versions)
_py2exe.run(self)
os.unlink(target_versionfile)
with open(cfg.versionfile_source, "w") as f:
LONG = LONG_VERSION_PY[cfg.VCS]
f.write(LONG %
{"DOLLAR": "$",
"STYLE": cfg.style,
"TAG_PREFIX": cfg.tag_prefix,
"PARENTDIR_PREFIX": cfg.parentdir_prefix,
"VERSIONFILE_SOURCE": cfg.versionfile_source,
})
|
class cmd_py2exe(_py2exe):
def run(self):
pass
| 2 | 0 | 19 | 1 | 18 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 20 | 1 | 19 | 8 | 17 | 0 | 13 | 7 | 11 | 1 | 1 | 1 | 1 |
769 |
3ll3d00d/vibe
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/3ll3d00d_vibe/versioneer.py
|
versioneer.get_cmdclass.cmd_build_py
|
class cmd_build_py(_build_py):
def run(self):
root = get_root()
cfg = get_config_from_root(root)
versions = get_versions()
_build_py.run(self)
# now locate _version.py in the new build/ directory and replace
# it with an updated value
if cfg.versionfile_build:
target_versionfile = os.path.join(self.build_lib,
cfg.versionfile_build)
print("UPDATING %s" % target_versionfile)
write_to_version_file(target_versionfile, versions)
|
class cmd_build_py(_build_py):
def run(self):
pass
| 2 | 0 | 12 | 0 | 10 | 2 | 2 | 0.18 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 13 | 0 | 11 | 6 | 9 | 2 | 10 | 6 | 8 | 2 | 1 | 1 | 2 |
770 |
3ll3d00d/vibe
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/3ll3d00d_vibe/backend/src/analyser/resources/state.py
|
state.State
|
class State(Resource):
def __init__(self, **kwargs):
self._targetStateController = kwargs['targetStateController']
@marshal_with(targetStateFields)
def get(self):
return self._targetStateController.getTargetState()
def patch(self):
"""
Allows the UI to update parameters ensuring that all devices are kept in sync. Payload is json in TargetState
format.
:return:
"""
# TODO block until all devices have updated?
json = request.get_json()
logger.info("Updating target state with " + str(json))
self._targetStateController.updateTargetState(json)
return None, 200
|
class State(Resource):
def __init__(self, **kwargs):
pass
@marshal_with(targetStateFields)
def get(self):
pass
def patch(self):
'''
Allows the UI to update parameters ensuring that all devices are kept in sync. Payload is json in TargetState
format.
:return:
'''
pass
| 5 | 1 | 5 | 0 | 3 | 2 | 1 | 0.55 | 1 | 1 | 0 | 0 | 3 | 1 | 3 | 3 | 19 | 2 | 11 | 7 | 6 | 6 | 10 | 6 | 6 | 1 | 1 | 0 | 3 |
771 |
3ll3d00d/vibe
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/3ll3d00d_vibe/backend/src/recorder/resources/measurements.py
|
measurements.AbortMeasurement
|
class AbortMeasurement(Resource):
def __init__(self, **kwargs):
self.measurements = kwargs['measurements']
self.recordingDevices = kwargs['recordingDevices']
@marshal_with(scheduledMeasurementFields)
def get(self, deviceId, measurementId):
"""
signals a stop for the given measurement.
:param deviceId: the device to measure.
:param measurementId: the name of the measurement.
:return: 200 if stop is signalled, 400 if it doesn't exist or is not running.
"""
record = self.measurements.get(deviceId)
if record is not None:
measurement = record.get(measurementId)
if measurement.recording:
device = self.recordingDevices.get(deviceId)
device.signalStop()
return measurement, 200
else:
return measurement, 400
return '', 400
|
class AbortMeasurement(Resource):
def __init__(self, **kwargs):
pass
@marshal_with(scheduledMeasurementFields)
def get(self, deviceId, measurementId):
'''
signals a stop for the given measurement.
:param deviceId: the device to measure.
:param measurementId: the name of the measurement.
:return: 200 if stop is signalled, 400 if it doesn't exist or is not running.
'''
pass
| 4 | 1 | 10 | 0 | 7 | 3 | 2 | 0.38 | 1 | 0 | 0 | 0 | 2 | 2 | 2 | 2 | 23 | 1 | 16 | 9 | 12 | 6 | 14 | 8 | 11 | 3 | 1 | 2 | 4 |
772 |
3ll3d00d/vibe
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/3ll3d00d_vibe/backend/src/recorder/resources/measurements.py
|
measurements.Measurement
|
class Measurement(Resource):
def __init__(self, **kwargs):
self.measurements = kwargs['measurements']
self.recordingDevices = kwargs['recordingDevices']
@marshal_with(scheduledMeasurementFields)
def get(self, deviceId, measurementId):
"""
details the specific measurement.
"""
record = self.measurements.get(deviceId)
if record is not None:
return record.get(measurementId)
return None
@marshal_with(scheduledMeasurementFields)
def put(self, deviceId, measurementId):
"""
Schedules a new measurement at the specified time.
:param deviceId: the device to measure.
:param measurementId: the name of the measurement.
:return: 200 if it was scheduled, 400 if the device is busy, 500 if the device is bad.
"""
record = self.measurements.get(deviceId)
if record is not None:
measurement = record.get(measurementId)
if measurement is not None:
if len([x.name for x in measurement.statuses if x.name is 'COMPLETE' or x.name is 'FAILED']) > 0:
logger.info(
'Overwriting existing completed measurement ' + x.name)
measurement = None
if measurement is None:
logger.info('Initiating measurement ' + measurementId)
measurement = ScheduledMeasurement(
measurementId, self.recordingDevices.get(deviceId))
body = request.get_json()
duration_ = body['duration']
def _cleanup():
logger.info('Removing ' + measurementId +
' from ' + deviceId)
record.pop(measurementId)
measurement.schedule(duration_, at=body.get(
'at'), delay=body.get('delay'), callback=_cleanup)
# a quick hack to enable the measurement to be cleaned up by the ScheduledMeasurement
record[measurementId] = measurement
return measurement, 200
else:
return measurement, 400
else:
return 'unknown device ' + deviceId, 400
@marshal_with(scheduledMeasurementFields)
def delete(self, deviceId, measurementId):
"""
Deletes a stored measurement.
:param deviceId: the device to measure.
:param measurementId: the name of the measurement.
:return: 200 if it was deleted, 400 if no such measurement (or device).
"""
record = self.measurements.get(deviceId)
if record is not None:
popped = record.pop(measurementId, None)
return popped, 200 if popped else 400
return None, 400
|
class Measurement(Resource):
def __init__(self, **kwargs):
pass
@marshal_with(scheduledMeasurementFields)
def get(self, deviceId, measurementId):
'''
details the specific measurement.
'''
pass
@marshal_with(scheduledMeasurementFields)
def put(self, deviceId, measurementId):
'''
Schedules a new measurement at the specified time.
:param deviceId: the device to measure.
:param measurementId: the name of the measurement.
:return: 200 if it was scheduled, 400 if the device is busy, 500 if the device is bad.
'''
pass
def _cleanup():
pass
@marshal_with(scheduledMeasurementFields)
def delete(self, deviceId, measurementId):
'''
Deletes a stored measurement.
:param deviceId: the device to measure.
:param measurementId: the name of the measurement.
:return: 200 if it was deleted, 400 if no such measurement (or device).
'''
pass
| 9 | 3 | 11 | 0 | 8 | 3 | 2 | 0.39 | 1 | 1 | 1 | 0 | 4 | 2 | 4 | 4 | 60 | 3 | 41 | 18 | 32 | 16 | 36 | 15 | 30 | 5 | 1 | 3 | 12 |
773 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/analyser/resources/upload.py
|
upload.CompleteUpload
|
class CompleteUpload(Resource):
def __init__(self, **kwargs):
self._uploadController = kwargs['uploadController']
def put(self, filename, totalChunks, status):
"""
Completes the specified upload.
:param filename: the filename.
:param totalChunks: the no of chunks.
:param status: the status of the upload.
:return: 200.
"""
logger.info('Completing ' + filename + ' - ' + status)
self._uploadController.finalise(filename, int(totalChunks), status)
return None, 200
|
class CompleteUpload(Resource):
def __init__(self, **kwargs):
pass
def put(self, filename, totalChunks, status):
'''
Completes the specified upload.
:param filename: the filename.
:param totalChunks: the no of chunks.
:param status: the status of the upload.
:return: 200.
'''
pass
| 3 | 1 | 7 | 0 | 3 | 4 | 1 | 1 | 1 | 1 | 0 | 0 | 2 | 1 | 2 | 2 | 15 | 1 | 7 | 4 | 4 | 7 | 7 | 4 | 4 | 1 | 1 | 0 | 2 |
774 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/analyser/common/targetstatecontroller.py
|
targetstatecontroller.TargetState
|
class TargetState(object):
"""
The target state of the measurement system.
"""
def __init__(self, fs=500, samplesPerBatch=125, accelerometerSens=2, accelerometerEnabled=True, gyroSens=500,
gyroEnabled=True):
self.fs = fs
self.accelerometerSens = accelerometerSens
self.accelerometerEnabled = accelerometerEnabled
self.gyroSens = gyroSens
self.gyroEnabled = gyroEnabled
self.samplesPerBatch = samplesPerBatch
|
class TargetState(object):
'''
The target state of the measurement system.
'''
def __init__(self, fs=500, samplesPerBatch=125, accelerometerSens=2, accelerometerEnabled=True, gyroSens=500,
gyroEnabled=True):
pass
| 2 | 1 | 8 | 0 | 8 | 0 | 1 | 0.33 | 1 | 0 | 0 | 0 | 1 | 6 | 1 | 1 | 13 | 1 | 9 | 9 | 6 | 3 | 8 | 8 | 6 | 1 | 1 | 0 | 1 |
775 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/analyser/common/targetstatecontroller.py
|
targetstatecontroller.TargetStateController
|
class TargetStateController(object):
def __init__(self, targetStateProvider, reactor, httpclient, deviceController=None):
"""
Registers with the reactor.
:param reactor:
"""
self._reactor = reactor
self._httpclient = httpclient
self._reactor.register(REACH_TARGET_STATE, _applyTargetState)
self._targetStateProvider = targetStateProvider
self.deviceController = deviceController
def updateDeviceState(self, device):
"""
Updates the target state on the specified device.
:param targetState: the target state to reach.
:param device: the device to update.
:return:
"""
# this is only threadsafe because the targetstate is effectively immutable, if it becomes mutable in future then
# funkiness may result
self._reactor.offer(REACH_TARGET_STATE, [self._targetStateProvider.state, device, self._httpclient])
def updateTargetState(self, newState):
"""
Updates the system target state and propagates that to all devices.
:param newState:
:return:
"""
self._targetStateProvider.state = loadTargetState(newState, self._targetStateProvider.state)
for device in self.deviceController.getDevices():
self.updateDeviceState(device.payload)
def getTargetState(self):
"""
The current system target state.
:return: the state.
"""
return self._targetStateProvider.state
|
class TargetStateController(object):
def __init__(self, targetStateProvider, reactor, httpclient, deviceController=None):
'''
Registers with the reactor.
:param reactor:
'''
pass
def updateDeviceState(self, device):
'''
Updates the target state on the specified device.
:param targetState: the target state to reach.
:param device: the device to update.
:return:
'''
pass
def updateTargetState(self, newState):
'''
Updates the system target state and propagates that to all devices.
:param newState:
:return:
'''
pass
def getTargetState(self):
'''
The current system target state.
:return: the state.
'''
pass
| 5 | 4 | 9 | 0 | 4 | 5 | 1 | 1.4 | 1 | 0 | 0 | 0 | 4 | 4 | 4 | 4 | 39 | 3 | 15 | 10 | 10 | 21 | 15 | 10 | 10 | 2 | 1 | 1 | 5 |
776 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/analyser/common/targetstatecontroller.py
|
targetstatecontroller.TargetStateProvider
|
class TargetStateProvider(object):
"""
Provides access to the current target state.
"""
def __init__(self, targetState):
self.state = targetState
|
class TargetStateProvider(object):
'''
Provides access to the current target state.
'''
def __init__(self, targetState):
pass
| 2 | 1 | 2 | 0 | 2 | 0 | 1 | 1 | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 7 | 1 | 3 | 3 | 1 | 3 | 3 | 3 | 1 | 1 | 1 | 0 | 1 |
777 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/test/recorder/common/test_handler.py
|
test_handler.MyHandler
|
class MyHandler(DataHandler):
def __init__(self):
self.startName = None
self.events = []
self.endName = None
def start(self, measurementId):
self.startName = measurementId
def handle(self, data):
self.events.append(data)
def stop(self, measurementId, failureReason=None):
self.endName = measurementId
self.failureReason = failureReason
|
class MyHandler(DataHandler):
def __init__(self):
pass
def start(self, measurementId):
pass
def handle(self, data):
pass
def stop(self, measurementId, failureReason=None):
pass
| 5 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 4 | 4 | 4 | 7 | 15 | 3 | 12 | 9 | 7 | 0 | 12 | 9 | 7 | 1 | 1 | 0 | 4 |
778 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/analyser/resources/timeseries.py
|
timeseries.TimeSeries
|
class TimeSeries(Resource):
def __init__(self, **kwargs):
self._measurementController = kwargs['measurementController']
def get(self, measurementId):
"""
Analyses the measurement with the given parameters
:param measurementId:
:return:
"""
logger.info('Loading raw data for ' + measurementId)
measurement = self._measurementController.getMeasurement(measurementId, MeasurementStatus.COMPLETE)
if measurement is not None:
if measurement.inflate():
data = {
name: {
'raw': {
'x': self._jsonify(data.raw('x')),
'y': self._jsonify(data.raw('y')),
'z': self._jsonify(data.raw('z'))
},
'vibration': {
'x': self._jsonify(data.vibration('x')),
'y': self._jsonify(data.vibration('y')),
'z': self._jsonify(data.vibration('z'))
},
'tilt': {
'x': self._jsonify(data.tilt('x')),
'y': self._jsonify(data.tilt('y')),
'z': self._jsonify(data.tilt('z'))
}
}
for name, data in measurement.data.items()
}
return data, 200
else:
return None, 404
else:
return None, 404
def _jsonify(self, vals):
return vals.tolist()
|
class TimeSeries(Resource):
def __init__(self, **kwargs):
pass
def get(self, measurementId):
'''
Analyses the measurement with the given parameters
:param measurementId:
:return:
'''
pass
def _jsonify(self, vals):
pass
| 4 | 1 | 13 | 0 | 11 | 2 | 2 | 0.14 | 1 | 1 | 1 | 0 | 3 | 1 | 3 | 3 | 42 | 2 | 35 | 7 | 31 | 5 | 14 | 7 | 10 | 3 | 1 | 2 | 5 |
779 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/analyser/resources/targets.py
|
targets.Targets
|
class Targets(Resource):
def __init__(self, **kwargs):
self._targetController = kwargs['targetController']
def get(self):
"""
Gets the currently available targets.
:return:
"""
return self._targetController.getTargets(), 200
|
class Targets(Resource):
def __init__(self, **kwargs):
pass
def get(self):
'''
Gets the currently available targets.
:return:
'''
pass
| 3 | 1 | 4 | 0 | 2 | 2 | 1 | 0.8 | 1 | 0 | 0 | 0 | 2 | 1 | 2 | 2 | 10 | 1 | 5 | 4 | 2 | 4 | 5 | 4 | 2 | 1 | 1 | 0 | 2 |
780 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/analyser/resources/upload.py
|
upload.Upload
|
class Upload(Resource):
def __init__(self, **kwargs):
self._uploadController = kwargs['uploadController']
def put(self, filename, chunkIdx, totalChunks):
"""
stores a chunk of new file, this is a nop if the file already exists.
:param filename: the filename.
:param chunkIdx: the chunk idx.
:param totalChunks: the no of chunks expected.
:return: the no of bytes written and 200 or 400 if nothing was written.
"""
logger.info('handling chunk ' + chunkIdx + ' of ' + totalChunks + ' for ' + filename)
import flask
bytesWritten = self._uploadController.writeChunk(flask.request.stream, filename, int(chunkIdx))
return str(bytesWritten), 200 if bytesWritten > 0 else 400
|
class Upload(Resource):
def __init__(self, **kwargs):
pass
def put(self, filename, chunkIdx, totalChunks):
'''
stores a chunk of new file, this is a nop if the file already exists.
:param filename: the filename.
:param chunkIdx: the chunk idx.
:param totalChunks: the no of chunks expected.
:return: the no of bytes written and 200 or 400 if nothing was written.
'''
pass
| 3 | 1 | 7 | 0 | 4 | 4 | 2 | 0.88 | 1 | 2 | 0 | 0 | 2 | 1 | 2 | 2 | 16 | 1 | 8 | 6 | 4 | 7 | 8 | 6 | 4 | 2 | 1 | 0 | 3 |
781 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/analyser/resources/upload.py
|
upload.UploadTarget
|
class UploadTarget(Resource):
def __init__(self, **kwargs):
self._uploadController = kwargs['uploadController']
self._targetController = kwargs['targetController']
def put(self, name, start, end):
"""
Stores a new target.
:param name: the name.
:param start: start time.
:param end: end time.
:return:
"""
entry = self._uploadController.getEntry(name)
if entry is not None:
return None, 200 if self._targetController.storeFromWav(entry, start, end) else 500
else:
return None, 404
|
class UploadTarget(Resource):
def __init__(self, **kwargs):
pass
def put(self, name, start, end):
'''
Stores a new target.
:param name: the name.
:param start: start time.
:param end: end time.
:return:
'''
pass
| 3 | 1 | 8 | 0 | 5 | 4 | 2 | 0.7 | 1 | 0 | 0 | 0 | 2 | 2 | 2 | 2 | 18 | 1 | 10 | 6 | 7 | 7 | 9 | 6 | 6 | 3 | 1 | 1 | 4 |
782 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/analyser/resources/upload.py
|
upload.Uploads
|
class Uploads(Resource):
def __init__(self, **kwargs):
self._uploadController = kwargs['uploadController']
def get(self):
"""
:return: the cached wav files
"""
return self._uploadController.get(), 200
def delete(self, name):
"""
Deletes the named file.
:param name: the name.
:return: 200 if it was deleted, 404 if it doesn't exist or 500 for anything else.
"""
try:
result = self._uploadController.delete(name)
return None, 200 if result is not None else 404
except Exception as e:
return str(e), 500
|
class Uploads(Resource):
def __init__(self, **kwargs):
pass
def get(self):
'''
:return: the cached wav files
'''
pass
def delete(self, name):
'''
Deletes the named file.
:param name: the name.
:return: 200 if it was deleted, 404 if it doesn't exist or 500 for anything else.
'''
pass
| 4 | 2 | 6 | 0 | 3 | 3 | 2 | 0.73 | 1 | 2 | 0 | 0 | 3 | 1 | 3 | 3 | 21 | 2 | 11 | 7 | 7 | 8 | 11 | 6 | 7 | 3 | 1 | 1 | 5 |
783 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/analyser/common/uploadcontroller.py
|
uploadcontroller.UploadController
|
class UploadController(object):
def __init__(self, uploadCfg):
self._tmpDir = uploadCfg['tmpDir']
self._uploadDir = uploadCfg['uploadDir']
self._watchdogInterval = uploadCfg['watchdogInterval']
self._uploadCache = self._scanUpload()
self._tmpCache = []
self._conversionCache = []
self._reactor = Reactor(name='converter', threads=uploadCfg['converterThreads'])
self._reactor.register(CONVERT_WAV, self._convertTmp)
self._findNewFiles()
def get(self):
"""
:return: metadata about all files in the cache.
"""
return self._uploadCache + self._tmpCache + self._conversionCache
def getEntry(self, name):
"""
:param name: the named wav.
:return: the cached info.
"""
return self._getCacheEntry(name)
def loadSignal(self, name, start=None, end=None):
"""
Loads the named entry from the upload cache as a signal.
:param name: the name.
:param start: the time to start from in HH:mm:ss.SSS format
:param end: the time to end at in HH:mm:ss.SSS format.
:return: the signal if the named upload exists.
"""
entry = self._getCacheEntry(name)
if entry is not None:
from analyser.common.signal import loadSignalFromWav
return loadSignalFromWav(entry['path'], start=start, end=end)
else:
return None
def _getCacheEntry(self, name):
"""
:param name: the name of the cache entry.
:return: the entry or none.
"""
return next((x for x in self._uploadCache if x['name'] == name), None)
def _scanUpload(self):
return [self._extractMeta(p, 'loaded') for p in glob.iglob(self._uploadDir + '/*.wav')]
def _extractMeta(self, fullPath, status):
from soundfile import info
sf = info(fullPath)
p = Path(fullPath)
return {
'status': status,
'path': sf.name,
'name': p.name,
'size': p.stat().st_size,
'duration': sf.duration,
'fs': sf.samplerate
}
def _watch(self):
import threading
from datetime import datetime
nextRun = datetime.utcnow().timestamp() + self._watchdogInterval
tilNextTime = max(nextRun - datetime.utcnow().timestamp(), 0)
logger.debug("Scheduling next scan in " + str(round(tilNextTime, 3)) + " seconds")
threading.Timer(tilNextTime, self._findNewFiles).start()
def _findNewFiles(self):
for tmp in self._scanTmp():
if not any(x['path'] == tmp['path'] for x in self._tmpCache):
self._tmpCache.append(tmp)
self._reactor.offer(CONVERT_WAV, (tmp,))
self._watch()
def _convertTmp(self, tmpCacheEntry):
"""
Moves a tmp file to the upload dir, resampling it if necessary, and then deleting the tmp entries.
:param tmpCacheEntry: the cache entry.
:return:
"""
from analyser.common.signal import loadSignalFromWav
tmpCacheEntry['status'] = 'converting'
logger.info("Loading " + tmpCacheEntry['path'])
signal = loadSignalFromWav(tmpCacheEntry['path'])
logger.info("Loaded " + tmpCacheEntry['path'])
if Path(tmpCacheEntry['path']).exists():
logger.info('Deleting ' + tmpCacheEntry['path'])
os.remove(tmpCacheEntry['path'])
else:
logger.warning('Tmp cache file does not exist: ' + tmpCacheEntry['path'])
self._tmpCache.remove(tmpCacheEntry)
self._conversionCache.append(tmpCacheEntry)
srcFs = signal.fs
completeSamples = signal.samples
outputFileName = os.path.join(self._uploadDir, tmpCacheEntry['name'])
if srcFs > 1024:
self.writeOutput(outputFileName, completeSamples, srcFs, 1000)
else:
self.writeOutput(outputFileName, completeSamples, srcFs, srcFs)
tmpCacheEntry['status'] = 'loaded'
self._conversionCache.remove(tmpCacheEntry)
self._uploadCache.append(self._extractMeta(outputFileName, 'loaded'))
def _scanTmp(self):
return [self._extractMeta(p, 'tmp') for p in glob.iglob(self._tmpDir + '/*.wav')]
def writeChunk(self, stream, filename, chunkIdx=None):
"""
Streams an uploaded chunk to a file.
:param stream: the binary stream that contains the file.
:param filename: the name of the file.
:param chunkIdx: optional chunk index (for writing to a tmp dir)
:return: no of bytes written or -1 if there was an error.
"""
import io
more = True
outputFileName = filename if chunkIdx is None else filename + '.' + str(chunkIdx)
outputDir = self._uploadDir if chunkIdx is None else self._tmpDir
chunkFilePath = os.path.join(outputDir, outputFileName)
if os.path.exists(chunkFilePath) and os.path.isfile(chunkFilePath):
logger.error('Uploaded file already exists: ' + chunkFilePath)
return -1
else:
chunkFile = open(chunkFilePath, 'xb')
count = 0
while more:
chunk = stream.read(io.DEFAULT_BUFFER_SIZE)
chunkLen = len(chunk)
count += chunkLen
if chunkLen == 0:
more = False
else:
chunkFile.write(chunk)
return count
def finalise(self, filename, totalChunks, status):
"""
Completes the upload which means converting to a single 1kHz sample rate file output file.
:param filename:
:param totalChunks:
:param status:
:return:
"""
def getChunkIdx(x):
try:
return int(x.suffix[1:])
except ValueError:
return -1
def isChunkFile(x):
return x.is_file() and -1 < getChunkIdx(x) <= totalChunks
asSingleFile = os.path.join(self._tmpDir, filename)
if status.lower() == 'true':
chunks = [(getChunkIdx(file), str(file)) for file in
Path(self._tmpDir).glob(filename + '.*') if isChunkFile(file)]
# TODO if len(chunks) != totalChunks then error
with open(asSingleFile, 'xb') as wfd:
for f in [x[1] for x in sorted(chunks, key=lambda tup: tup[0])]:
with open(f, 'rb') as fd:
logger.info("cat " + f + " with " + asSingleFile)
shutil.copyfileobj(fd, wfd, 1024 * 1024 * 10)
self.cleanupChunks(filename, isChunkFile, status)
def cleanupChunks(self, filename, isChunkFile, status):
if status.lower() != 'true':
logger.warning('Upload failed for ' + filename + ', deleting all uploaded chunks')
toDelete = [file for file in Path(self._tmpDir).glob(filename + '.*') if isChunkFile(file)]
for file in toDelete:
if file.exists():
logger.info('Deleting ' + str(file))
os.remove(str(file))
def writeOutput(self, filename, samples, srcFs, targetFs):
"""
Resamples the signal to the targetFs and writes it to filename.
:param filename: the filename.
:param signal: the signal to resample.
:param targetFs: the target fs.
:return: None
"""
import librosa
inputLength = samples.shape[-1]
if srcFs != targetFs:
if inputLength < targetFs:
logger.info("Input signal is too short (" + str(inputLength) +
" samples) for resampling to " + str(targetFs) + "Hz")
outputSamples = samples
targetFs = srcFs
else:
logger.info("Resampling " + str(inputLength) + " samples from " + str(srcFs) + "Hz to " +
str(targetFs) + "Hz")
outputSamples = librosa.resample(samples, srcFs, targetFs, res_type='kaiser_fast')
else:
outputSamples = samples
logger.info("Writing output to " + filename)
maxv = np.iinfo(np.int32).max
librosa.output.write_wav(filename, (outputSamples * maxv).astype(np.int32), targetFs)
logger.info("Output written to " + filename)
def delete(self, name):
"""
Deletes the named entry.
:param name: the entry.
:return: the deleted entry.
"""
i, entry = next(((i, x) for i, x in enumerate(self._uploadCache) if x['name'] == name), (None, None))
if entry is not None:
logger.info("Deleting " + name)
os.remove(str(entry['path']))
del self._uploadCache[i]
return entry
else:
logger.info("Unable to delete " + name + ", not found")
return None
|
class UploadController(object):
def __init__(self, uploadCfg):
pass
def get(self):
'''
:return: metadata about all files in the cache.
'''
pass
def getEntry(self, name):
'''
:param name: the named wav.
:return: the cached info.
'''
pass
def loadSignal(self, name, start=None, end=None):
'''
Loads the named entry from the upload cache as a signal.
:param name: the name.
:param start: the time to start from in HH:mm:ss.SSS format
:param end: the time to end at in HH:mm:ss.SSS format.
:return: the signal if the named upload exists.
'''
pass
def _getCacheEntry(self, name):
'''
:param name: the name of the cache entry.
:return: the entry or none.
'''
pass
def _scanUpload(self):
pass
def _extractMeta(self, fullPath, status):
pass
def _watch(self):
pass
def _findNewFiles(self):
pass
def _convertTmp(self, tmpCacheEntry):
'''
Moves a tmp file to the upload dir, resampling it if necessary, and then deleting the tmp entries.
:param tmpCacheEntry: the cache entry.
:return:
'''
pass
def _scanTmp(self):
pass
def writeChunk(self, stream, filename, chunkIdx=None):
'''
Streams an uploaded chunk to a file.
:param stream: the binary stream that contains the file.
:param filename: the name of the file.
:param chunkIdx: optional chunk index (for writing to a tmp dir)
:return: no of bytes written or -1 if there was an error.
'''
pass
def finalise(self, filename, totalChunks, status):
'''
Completes the upload which means converting to a single 1kHz sample rate file output file.
:param filename:
:param totalChunks:
:param status:
:return:
'''
pass
def getChunkIdx(x):
pass
def isChunkFile(x):
pass
def cleanupChunks(self, filename, isChunkFile, status):
pass
def writeOutput(self, filename, samples, srcFs, targetFs):
'''
Resamples the signal to the targetFs and writes it to filename.
:param filename: the filename.
:param signal: the signal to resample.
:param targetFs: the target fs.
:return: None
'''
pass
def delete(self, name):
'''
Deletes the named entry.
:param name: the entry.
:return: the deleted entry.
'''
pass
| 19 | 9 | 12 | 0 | 9 | 3 | 2 | 0.33 | 1 | 9 | 1 | 0 | 16 | 7 | 16 | 16 | 220 | 18 | 152 | 61 | 126 | 50 | 134 | 59 | 108 | 6 | 1 | 4 | 37 |
784 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/analyser/resources/upload.py
|
upload.UploadAnalyser
|
class UploadAnalyser(Resource):
def __init__(self, **kwargs):
self._uploadController = kwargs['uploadController']
def get(self, name, start, end, resolution, window):
"""
:param name:
:param start:
:param end:
:param resolution:
:param window:
:return: an analysed file.
"""
logger.info(
'Analysing ' + name + ' from ' + start + ' to ' + end + ' at ' + resolution + 'x resolution using ' + window + ' window')
signal = self._uploadController.loadSignal(name,
start=start if start != 'start' else None,
end=end if end != 'end' else None)
if signal is not None:
window = tuple(filter(None, window.split(' ')))
if len(window) == 2:
window = (window[0], float(window[1]))
import time
data = {
'spectrum': self._jsonify(
signal.spectrum(ref=SPECLAB_REFERENCE, segmentLengthMultiplier=int(resolution), window=window)
),
'peakSpectrum': self._jsonify(
signal.peakSpectrum(ref=SPECLAB_REFERENCE, segmentLengthMultiplier=int(resolution), window=window)
),
'analysedAt': int(time.time() * 1000)
}
return data, 200
else:
return None, 404
def _jsonify(self, tup):
return {'freq': tup[0].tolist(), 'val': tup[1].tolist()}
|
class UploadAnalyser(Resource):
def __init__(self, **kwargs):
pass
def get(self, name, start, end, resolution, window):
'''
:param name:
:param start:
:param end:
:param resolution:
:param window:
:return: an analysed file.
'''
pass
def _jsonify(self, tup):
pass
| 4 | 1 | 12 | 0 | 9 | 3 | 2 | 0.29 | 1 | 4 | 0 | 0 | 3 | 1 | 3 | 3 | 38 | 2 | 28 | 8 | 23 | 8 | 16 | 8 | 11 | 5 | 1 | 2 | 7 |
785 |
3ll3d00d/vibe
|
3ll3d00d_vibe/backend/src/analyser/common/targetcontroller.py
|
targetcontroller.TargetController
|
class TargetController(object):
def __init__(self, dataDir, uploadController):
self._dataDir = dataDir
self._cache = self.readCache()
self._uploadController = uploadController
def getTargets(self):
"""
:return: the cached targets
"""
return list(self._cache.values())
def storeFromHinge(self, name, hingePoints):
"""
Stores a new item in the cache if it is allowed in.
:param name: the name.
:param hingePoints: the hinge points.
:return: true if it is stored.
"""
if name not in self._cache:
if self._valid(hingePoints):
self._cache[name] = {'name': name, 'type': 'hinge', 'hinge': hingePoints}
self.writeCache()
return True
return False
def storeFromWav(self, uploadCacheEntry, start, end):
"""
Stores a new item in the cache.
:param name: file name.
:param start: start time.
:param end: end time.
:return: true if stored.
"""
prefix = uploadCacheEntry['name'] + '_' + start + '_' + end
match = next((x for x in self._cache.values() if x['type'] == 'wav' and x['name'].startswith(prefix)), None)
if match is None:
cached = [
{
'name': prefix + '_' + n,
'analysis': n,
'start': start,
'end': end,
'type': 'wav',
'filename': uploadCacheEntry['name']
} for n in ['spectrum', 'peakSpectrum']
]
for cache in cached:
self._cache[cache['name']] = cache
self.writeCache()
return True
return False
def delete(self, name):
"""
Deletes the named entry in the cache.
:param name: the name.
:return: true if it is deleted.
"""
if name in self._cache:
del self._cache[name]
self.writeCache()
# TODO clean files
return True
return False
def writeCache(self):
with open(os.path.join(self._dataDir, 'targetcache.json'), 'w') as outfile:
json.dump(self._cache, outfile)
def readCache(self):
cacheFile = os.path.join(self._dataDir, 'targetcache.json')
if os.path.exists(cacheFile):
try:
with open(cacheFile, 'r') as outfile:
return json.load(outfile)
except:
logger.exception('Failed to load ' + cacheFile)
return {}
def analyse(self, name):
"""
reads the specified file.
:param name: the name.
:return: the analysis as frequency/Pxx.
"""
if name in self._cache:
target = self._cache[name]
if target['type'] == 'wav':
signal = self._uploadController.loadSignal(target['filename'],
start=target['start'] if target['start'] != 'start' else None,
end=target['end'] if target['end'] != 'end' else None)
if signal is not None:
# TODO allow user defined window
return getattr(signal, target['analysis'])(ref=1.0)
else:
return None, 404
pass
elif target['type'] == 'hinge':
hingePoints = np.array(target['hinge']).astype(np.float64)
x = hingePoints[:, 1]
y = hingePoints[:, 0]
# extend as straight line from 0 to 500
if x[0] != 0:
x = np.insert(x, 0, 0.0000001)
y = np.insert(y, 0, y[0])
if x[-1] != 500:
x = np.insert(x, len(x), 500.0)
y = np.insert(y, len(y), y[-1])
# convert the y axis dB values into a linear value
y = 10 ** (y / 10)
# perform a logspace interpolation
f = self.log_interp1d(x, y)
# remap to 0-500
xnew = np.linspace(x[0], x[-1], num=500, endpoint=False)
# and convert back to dB
return xnew, 10 * np.log10(f(xnew))
else:
logger.error('Unknown target type with name ' + name)
return None
def _valid(self, hingePoints):
"""
Validates the hinge points.
:param hingePoints: the data.
:return: true if the data is valid.
"""
return True
def log_interp1d(self, xx, yy, kind='linear'):
"""
Performs a log space 1d interpolation.
:param xx: the x values.
:param yy: the y values.
:param kind: the type of interpolation to apply (as per scipy interp1d)
:return: the interpolation function.
"""
logx = np.log10(xx)
logy = np.log10(yy)
lin_interp = interp1d(logx, logy, kind=kind)
log_interp = lambda zz: np.power(10.0, lin_interp(np.log10(zz)))
return log_interp
|
class TargetController(object):
def __init__(self, dataDir, uploadController):
pass
def getTargets(self):
'''
:return: the cached targets
'''
pass
def storeFromHinge(self, name, hingePoints):
'''
Stores a new item in the cache if it is allowed in.
:param name: the name.
:param hingePoints: the hinge points.
:return: true if it is stored.
'''
pass
def storeFromWav(self, uploadCacheEntry, start, end):
'''
Stores a new item in the cache.
:param name: file name.
:param start: start time.
:param end: end time.
:return: true if stored.
'''
pass
def delete(self, name):
'''
Deletes the named entry in the cache.
:param name: the name.
:return: true if it is deleted.
'''
pass
def writeCache(self):
pass
def readCache(self):
pass
def analyse(self, name):
'''
reads the specified file.
:param name: the name.
:return: the analysis as frequency/Pxx.
'''
pass
def _valid(self, hingePoints):
'''
Validates the hinge points.
:param hingePoints: the data.
:return: true if the data is valid.
'''
pass
def log_interp1d(self, xx, yy, kind='linear'):
'''
Performs a log space 1d interpolation.
:param xx: the x values.
:param yy: the y values.
:param kind: the type of interpolation to apply (as per scipy interp1d)
:return: the interpolation function.
'''
pass
| 11 | 7 | 13 | 0 | 9 | 5 | 3 | 0.51 | 1 | 1 | 0 | 0 | 10 | 3 | 10 | 10 | 142 | 9 | 88 | 32 | 77 | 45 | 74 | 30 | 63 | 9 | 1 | 3 | 25 |
786 |
3nth/qualpy
|
3nth_qualpy/qualpy/main.py
|
qualpy.main.QualpyApp
|
class QualpyApp(App):
log = logging.getLogger(__name__)
def __init__(self):
super(QualpyApp, self).__init__(
description='qualpy',
version='0.1',
command_manager=CommandManager('qualpy'),
)
def build_option_parser(self, description, version, argparse_kwargs=None):
parser = super(QualpyApp, self).build_option_parser(description, version, argparse_kwargs)
parser.add_argument('--config', action='store', default=None, help='Path to auth file.')
return parser
def initialize_app(self, argv):
self.log.debug('initialize_app')
def prepare_to_run_command(self, cmd):
self.log.debug('prepare_to_run_command %s', cmd.__class__.__name__)
def clean_up(self, cmd, result, err):
self.log.debug('clean_up %s', cmd.__class__.__name__)
if err:
self.log.debug('got an error: %s', err)
|
class QualpyApp(App):
def __init__(self):
pass
def build_option_parser(self, description, version, argparse_kwargs=None):
pass
def initialize_app(self, argv):
pass
def prepare_to_run_command(self, cmd):
pass
def clean_up(self, cmd, result, err):
pass
| 6 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 5 | 0 | 5 | 5 | 26 | 6 | 20 | 8 | 14 | 0 | 16 | 8 | 10 | 2 | 1 | 1 | 6 |
787 |
3nth/qualpy
|
3nth_qualpy/qualpy/document.py
|
qualpy.document.Document
|
class Document(Command):
"Generate html documentation of active surveys."
log = logging.getLogger(__name__)
def get_parser(self, prog_name):
parser = argparse.ArgumentParser() #super(Command, self).get_parser(prog_name)
parser.add_argument('--out', action='store', help='Path to output file.')
return parser
def take_action(self, parsed_args):
q = Qualtrics(self.app_args.config)
env = Environment(loader=PackageLoader("qualpy", ""))
template = env.get_template("DocumentationTemplate.html")
surveys = q.get_active_surveys()
for s in surveys:
self.log.info('Now documenting: %s' % s['SurveyName'])
s['TableName'] = surveyname2tablename(s['SurveyName'])
survey = q.get_survey(s['SurveyID'])
questions = self.parse_survey_questions(survey)
s['Questions'] = questions
f = open(parsed_args.out, 'wt')
f.write(template.render(surveys=surveys))
f.close()
def parse_survey_questions(self, survey):
questions = []
xml = BeautifulSoup(survey, 'xml')
for q in xml.Questions.find_all('Question'):
question = self.parse_question(q)
questions.append(question)
return questions
def parse_question(self, q):
choices = []
if q.Choices:
for choice in q.Choices.find_all('Choice'):
choices.append({
"ID": choice['ID'],
"Recode": choice['Recode'],
"Description": choice.Description
})
answers = []
if q.Answers:
for answer in q.Answers.find_all('Answer'):
answers.append({
"ID": answer['ID'],
"Recode": answer['Recode'],
"Description": answer.Description
})
return {
"ID": q['QuestionID'],
"Type": q.Type,
"Text": q.QuestionText,
"Choices": choices,
"Answers": answers
}
|
class Document(Command):
'''Generate html documentation of active surveys.'''
def get_parser(self, prog_name):
pass
def take_action(self, parsed_args):
pass
def parse_survey_questions(self, survey):
pass
def parse_question(self, q):
pass
| 5 | 1 | 14 | 2 | 12 | 0 | 3 | 0.04 | 1 | 3 | 1 | 0 | 4 | 0 | 4 | 4 | 63 | 11 | 51 | 23 | 46 | 2 | 37 | 23 | 32 | 5 | 1 | 2 | 10 |
788 |
3nth/qualpy
|
3nth_qualpy/qualpy/download.py
|
qualpy.download.Download
|
class Download(Command):
"Download survey data."
log = logging.getLogger(__name__)
def get_parser(self, prog_name):
parser = argparse.ArgumentParser()
parser.add_argument('--out', action='store', help='Path to output directory.')
parser.add_argument('--panel', action='store')
parser.add_argument('--survey', action='store')
return parser
def take_action(self, parsed_args):
self.q = Qualtrics(self.app_args.config)
self.out = parsed_args.out or os.getcwd()
if not path.exists(self.out):
os.makedirs(self.out)
if parsed_args.survey == 'all':
self.download_surveys()
elif parsed_args.survey:
self.download_survey(parsed_args.survey)
if parsed_args.panel == 'all':
self.download_panels()
elif parsed_args.panel:
self.download_panel(parsed_args.panel)
def download_surveys(self):
surveys = self.q.get_active_surveys()
for survey in surveys:
self.download_survey(survey)
def download_survey(self, survey):
if isinstance(survey, str):
surveys = self.q.get_active_surveys()
survey = [s for s in surveys if s['SurveyID'] == survey][0]
self.log.info("Downloading {0}".format(survey['SurveyName']))
data = self.q.get_survey_data(survey['SurveyID'])
tablename = survey2filename(survey['SurveyName'])
downloadpath = path.join(self.out, tablename + '.csv')
write_csv(data, downloadpath)
def download_panels(self):
panels = self.q.get_panels()
for panel in panels:
self.download_panel(panel)
def download_panel(self, panel):
if isinstance(panel, str):
panels = self.q.get_panels()
panel = [p for p in panels if p['PanelID'] == panel][0]
self.log.info('Downloading "%s" ...' % panel['Name'])
data = self.q.get_panel_data(panel['PanelID'])
tablename = survey2filename(panel['Name'])
downloadpath = path.join(self.out, tablename + '.csv')
write_csv(data, downloadpath)
|
class Download(Command):
'''Download survey data.'''
def get_parser(self, prog_name):
pass
def take_action(self, parsed_args):
pass
def download_surveys(self):
pass
def download_surveys(self):
pass
def download_panels(self):
pass
def download_panels(self):
pass
| 7 | 1 | 8 | 1 | 8 | 0 | 3 | 0.02 | 1 | 3 | 1 | 0 | 6 | 2 | 6 | 6 | 59 | 11 | 47 | 23 | 40 | 1 | 45 | 23 | 38 | 6 | 1 | 1 | 15 |
789 |
3nth/qualpy
|
3nth_qualpy/qualpy/main.py
|
qualpy.main.List
|
class List(Lister):
"List all surveys."
log = logging.getLogger(__name__)
def take_action(self, parsed_args):
q = Qualtrics(self.app_args.config)
surveys = q.get_surveys()
columns = ('ID',
'Name',
'Status'
)
data = ((s['SurveyID'], s['SurveyName'], s['SurveyStatus']) for s in surveys)
return (columns, data)
|
class List(Lister):
'''List all surveys.'''
def take_action(self, parsed_args):
pass
| 2 | 1 | 9 | 0 | 9 | 0 | 1 | 0.09 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 1 | 14 | 2 | 11 | 7 | 9 | 1 | 8 | 7 | 6 | 1 | 1 | 0 | 1 |
790 |
3nth/qualpy
|
3nth_qualpy/tests/core_tests.py
|
tests.core_tests.test_qualtrics
|
class test_qualtrics(object):
def __init__(self):
self.q = None
self.pp = pprint.PrettyPrinter()
def setup(self):
self.q = Qualtrics()
if not path.exists('tests_out'):
os.makedirs('tests_out')
def teardown(self):
pass
def test_get_surveys(self):
surveys = self.q.get_surveys()
with open('tests_out/surveys.py', 'wt') as f:
f.write(self.pp.pformat(surveys))
def test_get_survey(self):
survey_id = self.q.get_surveys()[0]['SurveyID']
survey = self.q.get_survey(survey_id)
with open('tests_out/survey.xml', 'wt') as f:
f.write(str(survey))
def test_get_panels(self):
panels = self.q.get_panels()
with open('tests_out/panels.json', 'wt') as f:
f.write(str(panels))
def test_get_panel(self):
panels = self.q.get_panels()
for panel in panels:
p = self.q.get_panel_data(panel['PanelID'])
with open('tests_out/panel_{0}.json'.format(panel['PanelID']), 'wt') as f:
f.write(str(p))
def test_get_recipient(self):
panel = self.q.get_panels()[0]
id = self.q.get_panel_data(panel['PanelID'])[1][0]
recipient = self.q.get_recipient(id)
with open('tests_out/recipient.json', 'wt') as f:
f.write(str(recipient))
def test_create_distribution(self):
pass
panels = self.q.create_distribution('', '')
with open('tests_out/create_distribution.json', 'wt') as f:
f.write(str(panels))
|
class test_qualtrics(object):
def __init__(self):
pass
def setup(self):
pass
def teardown(self):
pass
def test_get_surveys(self):
pass
def test_get_surveys(self):
pass
def test_get_panels(self):
pass
def test_get_panels(self):
pass
def test_get_recipient(self):
pass
def test_create_distribution(self):
pass
| 10 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 3 | 1 | 0 | 9 | 2 | 9 | 9 | 49 | 9 | 40 | 28 | 30 | 0 | 40 | 22 | 30 | 2 | 1 | 2 | 11 |
791 |
46elks/elkme
|
46elks_elkme/elkme/elks.py
|
elkme.elks.ElksException
|
class ElksException(Exception):
pass
|
class ElksException(Exception):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 3 | 0 | 0 |
792 |
46elks/elkme
|
46elks_elkme/tests/test_elks.py
|
test_elks.TestFormatSmsPayload
|
class TestFormatSmsPayload(unittest.TestCase):
ec = elks.Elks()
def test_message(self):
message = 'Test Case #1'
sms = self.ec.format_sms_payload(message, NULROUTE)
self.assertEqual(sms['message'], message)
def test_list_message(self):
message = ['Test', 'Case', '#2']
sms = self.ec.format_sms_payload(message, NULROUTE)
self.assertEqual(sms['message'], 'Test Case #2')
def test_rstrip_message(self):
message = 'Test Case #3 \n'
sms = self.ec.format_sms_payload(message, NULROUTE)
self.assertEqual(sms['message'], 'Test Case #3')
def test_default_sender(self):
sms = self.ec.format_sms_payload('msg', NULROUTE)
self.assertEqual(sms['from'], 'elkme')
def test_recipient_validation(self):
self.assertRaises(Exception, self.ec.format_sms_payload, 'msg', 'elkme')
def test_alphanum_sender(self):
sms = self.ec.format_sms_payload('msg', NULROUTE, 'AlphaNumb3r')
self.assertEqual(sms['from'], 'AlphaNumb3r')
|
class TestFormatSmsPayload(unittest.TestCase):
def test_message(self):
pass
def test_list_message(self):
pass
def test_rstrip_message(self):
pass
def test_default_sender(self):
pass
def test_recipient_validation(self):
pass
def test_alphanum_sender(self):
pass
| 7 | 0 | 3 | 0 | 3 | 1 | 1 | 0.23 | 1 | 1 | 0 | 0 | 6 | 0 | 6 | 78 | 28 | 6 | 22 | 16 | 15 | 5 | 22 | 16 | 15 | 1 | 2 | 0 | 6 |
793 |
46elks/elkme
|
46elks_elkme/elkme/elks.py
|
elkme.elks.Elks
|
class Elks:
""" Wrapper to send queries to the 46elks API
"""
auth = None
api_url = "https://api.46elks.com/a1/%s"
def __init__(self, auth=None, api_url=None):
""" Initializes the connector to 46elks. Makes no connection, but
is used to set the authentication (a tuple with (username, password))
and the API base URL (default http://api.46elks.com/a1/)
"""
self.auth = auth
if api_url:
self.api_url = '%s/' % api_url + '%s'
def query_api(self, data=None, endpoint='SMS'):
""" Send a request to the 46elks API.
Fetches SMS history as JSON by default, sends a HTTP POST request
with the incoming data dictionary as a urlencoded query if data is
provided, otherwise HTTP GET
Throws HTTPError on non 2xx
"""
url = self.api_url % endpoint
if data:
response = requests.post(
url,
data=data,
auth=self.auth
)
else:
response = requests.get(
url,
auth=self.auth
)
try:
response.raise_for_status()
except HTTPError as e:
raise HTTPError('HTTP %s\n%s' %
(response.status_code, response.text))
return response.text
def validate_number(self, number):
""" Checks if a number looks somewhat like a E.164 number. Not an
exhaustive check, as the API takes care of that
"""
if not isinstance(number, str):
raise ElksException('Recipient phone number may not be empty')
if number[0] == '+' and len(number) > 2 and len(number) < 16:
return True
else:
raise ElksException("Phone number must be of format +CCCXXX...")
def format_sms_payload(self, message, to, sender='elkme', options=[]):
""" Helper function to create a SMS payload with little effort
"""
self.validate_number(to)
if not isinstance(message, str):
message = " ".join(message)
message = message.rstrip()
sms = {
'from': sender,
'to': to,
'message': message
}
for option in options:
if option not in ['dontlog', 'dryrun', 'flashsms']:
raise ElksException('Option %s not supported' % option)
sms[option] = 'yes'
return sms
def send_sms(self, message, to, sender='elkme', options=[]):
"""Sends a text message to a configuration conf containing the message
in the message paramter"""
sms = self.format_sms_payload(message=message,
to=to,
sender=sender,
options=options)
return self.query_api(sms)
|
class Elks:
''' Wrapper to send queries to the 46elks API
'''
def __init__(self, auth=None, api_url=None):
''' Initializes the connector to 46elks. Makes no connection, but
is used to set the authentication (a tuple with (username, password))
and the API base URL (default http://api.46elks.com/a1/)
'''
pass
def query_api(self, data=None, endpoint='SMS'):
''' Send a request to the 46elks API.
Fetches SMS history as JSON by default, sends a HTTP POST request
with the incoming data dictionary as a urlencoded query if data is
provided, otherwise HTTP GET
Throws HTTPError on non 2xx
'''
pass
def validate_number(self, number):
''' Checks if a number looks somewhat like a E.164 number. Not an
exhaustive check, as the API takes care of that
'''
pass
def format_sms_payload(self, message, to, sender='elkme', options=[]):
''' Helper function to create a SMS payload with little effort
'''
pass
def send_sms(self, message, to, sender='elkme', options=[]):
'''Sends a text message to a configuration conf containing the message
in the message paramter'''
pass
| 6 | 6 | 15 | 1 | 10 | 3 | 3 | 0.35 | 0 | 3 | 1 | 0 | 5 | 0 | 5 | 5 | 86 | 13 | 54 | 14 | 48 | 19 | 37 | 13 | 31 | 4 | 0 | 2 | 13 |
794 |
46elks/elkme
|
46elks_elkme/tests/test_elks.py
|
test_elks.TestNumberValidation
|
class TestNumberValidation(unittest.TestCase):
ec = elks.Elks()
def test_nulroute(self):
self.assertTrue(self.ec.validate_number(NULROUTE))
def test_empty(self):
self.assertRaises(Exception, self.ec.validate_number, '')
def test_only_plus(self):
self.assertRaises(Exception, self.ec.validate_number, '+')
def test_too_long_number(self):
self.assertRaises(Exception, self.ec.validate_number,
'+46123456789123456789')
def test_alphanum_invalid(self):
self.assertRaises(Exception, self.ec.validate_number, 'elkme')
|
class TestNumberValidation(unittest.TestCase):
def test_nulroute(self):
pass
def test_empty(self):
pass
def test_only_plus(self):
pass
def test_too_long_number(self):
pass
def test_alphanum_invalid(self):
pass
| 6 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 5 | 0 | 5 | 77 | 18 | 5 | 13 | 7 | 7 | 0 | 12 | 7 | 6 | 1 | 2 | 0 | 5 |
795 |
475Cumulus/TBone
|
475Cumulus_TBone/tbone/data/fields/mongo.py
|
tbone.data.fields.mongo.ObjectIdField
|
class ObjectIdField(BaseField):
'''
A field wrapper around MongoDB ObjectIds
'''
_data_type = str
_python_type = ObjectId
ERRORS = {
'convert': "Could not cast value as ObjectId",
}
def _import(self, value):
if value is None:
return None
return self._python_type(value)
|
class ObjectIdField(BaseField):
'''
A field wrapper around MongoDB ObjectIds
'''
def _import(self, value):
pass
| 2 | 1 | 4 | 0 | 4 | 0 | 2 | 0.3 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 32 | 14 | 1 | 10 | 5 | 8 | 3 | 8 | 5 | 6 | 2 | 4 | 1 | 2 |
796 |
475Cumulus/TBone
|
475Cumulus_TBone/tbone/data/fields/mongo.py
|
tbone.data.fields.mongo.RefDict
|
class RefDict(dict):
__slots__ = ['ref', 'id']
def __init__(self, data=None):
for key in RefDict.__slots__:
self[key] = ''
if isinstance(data, dict):
self.update(data)
|
class RefDict(dict):
def __init__(self, data=None):
pass
| 2 | 0 | 5 | 0 | 5 | 0 | 3 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 28 | 8 | 1 | 7 | 4 | 5 | 0 | 7 | 4 | 5 | 3 | 2 | 1 | 3 |
797 |
475Cumulus/TBone
|
475Cumulus_TBone/tbone/data/fields/network.py
|
tbone.data.fields.network.EmailField
|
class EmailField(StringField):
# TODO: Add SMTP validation
REGEXP = '^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$'
def __init__(self, **kwargs):
super(EmailField, self).__init__(**kwargs)
@validator
def email(self, value):
if value is None or value == '':
return value
match = re.match(self.REGEXP, value)
if match is None:
raise ValueError('Malformed email address')
return value
|
class EmailField(StringField):
def __init__(self, **kwargs):
pass
@validator
def email(self, value):
pass
| 4 | 0 | 5 | 0 | 5 | 0 | 2 | 0.08 | 1 | 2 | 0 | 0 | 2 | 0 | 2 | 33 | 15 | 2 | 12 | 6 | 8 | 1 | 11 | 5 | 8 | 3 | 5 | 1 | 4 |
798 |
475Cumulus/TBone
|
475Cumulus_TBone/tbone/data/fields/network.py
|
tbone.data.fields.network.URLField
|
class URLField(StringField):
@validator
def url(self, value):
# TODO: implement this
return value
|
class URLField(StringField):
@validator
def url(self, value):
pass
| 3 | 0 | 3 | 0 | 2 | 1 | 1 | 0.25 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 32 | 6 | 1 | 4 | 3 | 1 | 1 | 3 | 2 | 1 | 1 | 5 | 0 | 1 |
799 |
475Cumulus/TBone
|
475Cumulus_TBone/examples/chatrooms/backend/websocket_aiohttp.py
|
websocket_aiohttp.ResourceEventsWebSocketView
|
class ResourceEventsWebSocketView(web.View):
async def get(self):
ws = web.WebSocketResponse()
await ws.prepare(self.request)
self.subscribe(self.request, ws)
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
if msg.data == 'close':
await ws.close()
self.unsubscribe(self.request, ws)
elif msg.type == aiohttp.WSMsgType.ERROR:
logger.error('ws connection closed with exception %s' % ws.exception())
self.unsubscribe(self.request, ws)
return ws
def subscribe(self, request, ws):
request.app.pubsub.subscribe('resource_get_list', AioHttpWebSocketCarrier(ws))
request.app.pubsub.subscribe('resource_create', AioHttpWebSocketCarrier(ws))
request.app.pubsub.subscribe('resource_update', AioHttpWebSocketCarrier(ws))
request.app.pubsub.subscribe('resource_delete', AioHttpWebSocketCarrier(ws))
def unsubscribe(self, request, ws):
request.app.pubsub.unsubscribe('resource_get_list', AioHttpWebSocketCarrier(ws))
request.app.pubsub.unsubscribe('resource_create', AioHttpWebSocketCarrier(ws))
request.app.pubsub.unsubscribe('resource_update', AioHttpWebSocketCarrier(ws))
request.app.pubsub.unsubscribe('resource_delete', AioHttpWebSocketCarrier(ws))
|
class ResourceEventsWebSocketView(web.View):
async def get(self):
pass
def subscribe(self, request, ws):
pass
def unsubscribe(self, request, ws):
pass
| 4 | 0 | 9 | 1 | 8 | 0 | 2 | 0 | 0 | 1 | 1 | 0 | 3 | 0 | 3 | 3 | 29 | 5 | 24 | 6 | 20 | 0 | 23 | 6 | 19 | 5 | 0 | 3 | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.