input
stringlengths
2.65k
237k
output
stringclasses
1 value
# Copyright (c) 2019, NVIDIA Corporation. All rights reserved. # # This work is made available under the Nvidia Source Code License-NC. # To view a copy of this license, visit # https://nvlabs.github.io/stylegan2/license.html """Loss functions.""" import numpy as np import tensorflow as tf import dnnlib.tflib as tflib from dnnlib.tflib.autosummary import autosummary #---------------------------------------------------------------------------- # Logistic loss from the paper # "Generative Adversarial Nets", Goodfellow et al. 2014 def G_logistic(G, D, opt, training_set, minibatch_size): _ = opt latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:]) labels = training_set.get_random_labels_tf(minibatch_size) fake_images_out = G.get_output_for(latents, labels, is_training=True) fake_scores_out = D.get_output_for(fake_images_out, labels, is_training=True) loss = -tf.nn.softplus(fake_scores_out) # log(1-sigmoid(fake_scores_out)) # pylint: disable=invalid-unary-operand-type return loss, None def G_logistic_ns(G, D, opt, training_set, minibatch_size): _ = opt latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:]) labels = training_set.get_random_labels_tf(minibatch_size) fake_images_out = G.get_output_for(latents, labels, is_training=True) fake_scores_out = D.get_output_for(fake_images_out, labels, is_training=True) loss = tf.nn.softplus(-fake_scores_out) # -log(sigmoid(fake_scores_out)) return loss, None def G_logistic_ns_dsp(G, D, opt, training_set, minibatch_size, latent_type='uniform', D_global_size=0): _ = opt discrete_latents = None if D_global_size > 0: discrete_latents = tf.random.uniform([minibatch_size], minval=0, maxval=D_global_size, dtype=tf.int32) discrete_latents = tf.one_hot(discrete_latents, D_global_size) if latent_type == 'uniform': latents = tf.random.uniform([minibatch_size] + [G.input_shapes[0][1]-D_global_size], minval=-2, maxval=2) elif latent_type == 'normal': latents = tf.random_normal([minibatch_size] + [G.input_shapes[0][1]-D_global_size]) elif latent_type == 'trunc_normal': latents = tf.random.truncated_normal([minibatch_size] + [G.input_shapes[0][1]-D_global_size]) else: raise ValueError('Latent type not supported: ' + latent_type) if D_global_size > 0: latents = tf.concat([discrete_latents, latents], axis=1) labels = training_set.get_random_labels_tf(minibatch_size) fake_images_out, _ = G.get_output_for(latents, labels, is_training=True) fake_scores_out = D.get_output_for(fake_images_out, labels, is_training=True) loss = tf.nn.softplus(-fake_scores_out) # -log(sigmoid(fake_scores_out)) return loss, None def calc_info_gan_loss(latents, regress_out, D_global_size, C_global_size, D_lambda, C_lambda): assert regress_out.shape.as_list()[1] == (D_global_size + 2 * C_global_size) # Discrete latents loss I_loss_D = 0 if D_global_size > 0: prob_D = tf.nn.softmax(regress_out[:, :D_global_size], axis=1) I_loss_D = tf.reduce_sum(latents[:, :D_global_size] * tf.log(prob_D + 1e-12), axis=1) # Continuous latents loss mean_C = regress_out[:, D_global_size:D_global_size + C_global_size] std_C = tf.sqrt(tf.exp(regress_out[:, D_global_size + C_global_size: D_global_size + C_global_size * 2])) epsilon = (latents[:, D_global_size:] - mean_C) / (std_C + 1e-12) I_loss_C = tf.reduce_sum(- 0.5 * np.log(2 * np.pi) - tf.log(std_C + 1e-12) - 0.5 * tf.square(epsilon), axis=1) I_loss = - D_lambda * I_loss_D - C_lambda * I_loss_C return I_loss def G_logistic_ns_info_gan(G, D, I, opt, training_set, minibatch_size, latent_type='uniform', D_global_size=0, D_lambda=1, C_lambda=1): _ = opt discrete_latents = None if D_global_size > 0: discrete_latents = tf.random.uniform([minibatch_size], minval=0, maxval=D_global_size, dtype=tf.int32) discrete_latents = tf.one_hot(discrete_latents, D_global_size) if latent_type == 'uniform': latents = tf.random.uniform([minibatch_size] + [G.input_shapes[0][1]-D_global_size], minval=-2, maxval=2) elif latent_type == 'normal': latents = tf.random_normal([minibatch_size] + [G.input_shapes[0][1]-D_global_size]) elif latent_type == 'trunc_normal': latents = tf.random.truncated_normal([minibatch_size] + [G.input_shapes[0][1]-D_global_size]) else: raise ValueError('Latent type not supported: ' + latent_type) if D_global_size > 0: latents = tf.concat([discrete_latents, latents], axis=1) labels = training_set.get_random_labels_tf(minibatch_size) fake_images_out, _ = G.get_output_for(latents, labels, is_training=True) fake_scores_out, hidden = D.get_output_for(fake_images_out, labels, is_training=True) G_loss = tf.nn.softplus(-fake_scores_out) # -log(sigmoid(fake_scores_out)) # regress_out = I.get_output_for(hidden, is_training=True) regress_out = I.get_output_for(fake_images_out, is_training=True) I_loss = calc_info_gan_loss(latents, regress_out, D_global_size, G.input_shapes[0][1]-D_global_size, D_lambda, C_lambda) I_loss = autosummary('Loss/I_loss', I_loss) return G_loss, None, I_loss, None def calc_vc_loss(C_delta_latents, regress_out, D_global_size, C_global_size, D_lambda, C_lambda, delta_type): assert regress_out.shape.as_list()[1] == (D_global_size + C_global_size) # Continuous latents loss if delta_type == 'onedim': prob_C = tf.nn.softmax(regress_out[:, D_global_size:], axis=1) I_loss_C = C_delta_latents * tf.log(prob_C + 1e-12) I_loss_C = C_lambda * I_loss_C I_loss_C = tf.reduce_sum(I_loss_C, axis=1) I_loss = - I_loss_C elif delta_type == 'fulldim': I_loss_C = tf.reduce_sum((tf.nn.sigmoid(regress_out[:, D_global_size:]) - C_delta_latents) ** 2, axis=1) I_loss = C_lambda * I_loss_C return I_loss # def calc_vc_loss(delta_target, regress_out, D_global_size, C_global_size, D_lambda, C_lambda): # assert regress_out.shape.as_list()[1] == (D_global_size + C_global_size) # # Continuous latents loss # I_loss_C = tf.reduce_mean((regress_out[:, D_global_size:] - delta_target) ** 2, axis=1) # I_loss = C_lambda * I_loss_C # return I_loss def calc_cls_loss(discrete_latents, cls_out, D_global_size, C_global_size, cls_alpha): assert cls_out.shape.as_list()[1] == D_global_size prob_D = tf.nn.softmax(cls_out, axis=1) I_info_loss_D = tf.reduce_sum(discrete_latents * tf.log(prob_D + 1e-12), axis=1) I_info_loss = - cls_alpha * I_info_loss_D return I_info_loss def G_logistic_ns_vc(G, D, I, opt, training_set, minibatch_size, I_info=None, latent_type='uniform', D_global_size=0, D_lambda=0, C_lambda=1, F_beta=0, cls_alpha=0, epsilon=0.4, random_eps=False, delta_type='onedim', cascading=False): _ = opt discrete_latents = None C_global_size = G.input_shapes[0][1]-D_global_size if D_global_size > 0: discrete_latents = tf.random.uniform([minibatch_size], minval=0, maxval=D_global_size, dtype=tf.int32) discrete_latents = tf.one_hot(discrete_latents, D_global_size) discrete_latents_2 = tf.random.uniform([minibatch_size], minval=0, maxval=D_global_size, dtype=tf.int32) discrete_latents_2 = tf.one_hot(discrete_latents_2, D_global_size) if latent_type == 'uniform': latents = tf.random.uniform([minibatch_size] + [G.input_shapes[0][1]-D_global_size], minval=-2, maxval=2) elif latent_type == 'normal': # latents = tf.random_normal([minibatch_size] + [G.input_shapes[0][1]-D_global_size]) latents = tf.random.normal([minibatch_size] + [G.input_shapes[0][1]-D_global_size]) elif latent_type == 'trunc_normal': latents = tf.random.truncated_normal([minibatch_size] + [G.input_shapes[0][1]-D_global_size]) else: raise ValueError('Latent type not supported: ' + latent_type) if not cascading: # Sample delta latents if delta_type == 'onedim': C_delta_latents = tf.random.uniform([minibatch_size], minval=0, maxval=C_global_size, dtype=tf.int32) C_delta_latents = tf.cast(tf.one_hot(C_delta_latents, C_global_size), latents.dtype) elif delta_type == 'fulldim': C_delta_latents = tf.random.uniform([minibatch_size, C_global_size], minval=0, maxval=1.0, dtype=latents.dtype) else: # apply cascading cascade_max = 1e5 cascade_step = cascade_max // int(C_global_size) global_step = tf.compat.v1.train.get_global_step() n_emph_free = tf.math.floormod(global_step // int(cascade_step), C_global_size) + 2 n_emph = tf.math.minimum(n_emph_free, C_global_size) if delta_type == 'onedim': C_delta_latents = tf.random.uniform([minibatch_size], minval=0, maxval=n_emph, dtype=tf.int32) C_delta_latents = tf.cast(tf.one_hot(C_delta_latents, n_emph), latents.dtype) elif delta_type == 'fulldim': C_delta_latents = tf.random.uniform([minibatch_size, n_emph], minval=0, maxval=1.0, dtype=latents.dtype) C_delta_latents = tf.concat([C_delta_latents, tf.zeros([minibatch_size, C_global_size - n_emph])], axis=1) if delta_type == 'onedim': if not random_eps: delta_target = C_delta_latents * epsilon # delta_latents = tf.concat([tf.zeros([minibatch_size, D_global_size]), delta_target], axis=1) else: epsilon = epsilon * tf.random.normal([minibatch_size, 1], mean=0.0, stddev=2.0) # delta_target = tf.math.abs(C_delta_latents * epsilon) delta_target = C_delta_latents * epsilon # delta_latents = tf.concat([tf.zeros([minibatch_size, D_global_size]), delta_target], axis=1) else: delta_target = (C_delta_latents - 0.5) * epsilon delta_latents = delta_target + latents if D_global_size > 0: latents = tf.concat([discrete_latents, latents], axis=1) # delta_latents = tf.concat([discrete_latents_2, delta_latents], axis=1) delta_latents = tf.concat([tf.zeros([minibatch_size, D_global_size]), delta_latents], axis=1) labels = training_set.get_random_labels_tf(minibatch_size) fake1_out, feat_map1 = G.get_output_for(latents, labels, is_training=True) fake2_out, feat_map2 = G.get_output_for(delta_latents, labels, is_training=True) if I_info is not None: fake_scores_out, hidden = D.get_output_for(fake1_out, labels, is_training=True) else: fake_scores_out = D.get_output_for(fake1_out, labels, is_training=True) G_loss = tf.nn.softplus(-fake_scores_out) # -log(sigmoid(fake_scores_out)) regress_out = I.get_output_for(fake1_out, fake2_out, is_training=True) I_loss = calc_vc_loss(C_delta_latents, regress_out, D_global_size, C_global_size, D_lambda, C_lambda, delta_type) # I_loss = calc_vc_loss(delta_target, regress_out, D_global_size, C_global_size, D_lambda, C_lambda) I_loss = autosummary('Loss/I_loss', I_loss) F_loss = tf.reduce_mean(feat_map1 * feat_map1, axis=[1, 2, 3]) F_loss = autosummary('Loss/F_loss', F_loss) I_loss += (F_loss * F_beta) if I_info is not None: cls_out = I_info.get_output_for(hidden, is_training=True) I_info_loss = calc_cls_loss(discrete_latents, cls_out, D_global_size, G.input_shapes[0][1]-D_global_size, cls_alpha) I_info_loss = autosummary('Loss/I_info_loss', I_info_loss) else: I_info_loss = None return G_loss, None, I_loss, I_info_loss def D_logistic(G, D, opt, training_set, minibatch_size, reals, labels): _ = opt, training_set latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:]) fake_images_out = G.get_output_for(latents, labels, is_training=True) real_scores_out = D.get_output_for(reals, labels, is_training=True) fake_scores_out = D.get_output_for(fake_images_out, labels, is_training=True) real_scores_out = autosummary('Loss/scores/real', real_scores_out) fake_scores_out = autosummary('Loss/scores/fake', fake_scores_out) loss = tf.nn.softplus(fake_scores_out) # -log(1-sigmoid(fake_scores_out)) loss += tf.nn.softplus(-real_scores_out) # -log(sigmoid(real_scores_out)) # pylint: disable=invalid-unary-operand-type return loss, None #---------------------------------------------------------------------------- # R1 and R2 regularizers from the paper # "Which Training Methods for GANs do actually Converge?", Mescheder et al. 2018 def D_logistic_r1(G, D, opt, training_set, minibatch_size, reals, labels, gamma=10.0): _ = opt, training_set latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:]) fake_images_out = G.get_output_for(latents, labels, is_training=True) real_scores_out = D.get_output_for(reals, labels, is_training=True) fake_scores_out = D.get_output_for(fake_images_out, labels, is_training=True) real_scores_out = autosummary('Loss/scores/real', real_scores_out) fake_scores_out = autosummary('Loss/scores/fake', fake_scores_out) loss = tf.nn.softplus(fake_scores_out) # -log(1-sigmoid(fake_scores_out)) loss += tf.nn.softplus(-real_scores_out) # -log(sigmoid(real_scores_out)) # pylint: disable=invalid-unary-operand-type with tf.name_scope('GradientPenalty'): real_grads = tf.gradients(tf.reduce_sum(real_scores_out), [reals])[0] gradient_penalty = tf.reduce_sum(tf.square(real_grads), axis=[1,2,3]) gradient_penalty = autosummary('Loss/gradient_penalty', gradient_penalty) reg = gradient_penalty * (gamma * 0.5) return loss, reg def D_logistic_r1_dsp(G, D, opt, training_set, minibatch_size, reals, labels, gamma=10.0, latent_type='uniform', D_global_size=0): _ = opt, training_set discrete_latents = None if D_global_size > 0: discrete_latents = tf.random.uniform([minibatch_size], minval=0, maxval=D_global_size, dtype=tf.int32) discrete_latents = tf.one_hot(discrete_latents, D_global_size) if latent_type == 'uniform': latents = tf.random.uniform([minibatch_size] + [G.input_shapes[0][1]-D_global_size], minval=-2, maxval=2) elif latent_type == 'normal': latents = tf.random_normal([minibatch_size] + [G.input_shapes[0][1]-D_global_size]) elif latent_type == 'trunc_normal': latents = tf.random.truncated_normal([minibatch_size] + [G.input_shapes[0][1]-D_global_size]) else: raise ValueError('Latent type not supported: ' + latent_type) if D_global_size > 0: latents = tf.concat([discrete_latents, latents], axis=1) fake_images_out, _ = G.get_output_for(latents, labels, is_training=True) real_scores_out = D.get_output_for(reals, labels, is_training=True) fake_scores_out = D.get_output_for(fake_images_out, labels, is_training=True) real_scores_out = autosummary('Loss/scores/real', real_scores_out) fake_scores_out = autosummary('Loss/scores/fake', fake_scores_out) loss = tf.nn.softplus(fake_scores_out) # -log(1-sigmoid(fake_scores_out)) loss += tf.nn.softplus(-real_scores_out) # -log(sigmoid(real_scores_out)) # pylint: disable=invalid-unary-operand-type with tf.name_scope('GradientPenalty'): real_grads = tf.gradients(tf.reduce_sum(real_scores_out), [reals])[0] gradient_penalty = tf.reduce_sum(tf.square(real_grads), axis=[1,2,3]) gradient_penalty = autosummary('Loss/gradient_penalty', gradient_penalty) reg = gradient_penalty * (gamma * 0.5) return loss, reg def D_logistic_r1_info_gan(G, D, opt, training_set, minibatch_size, reals, labels, gamma=10.0, latent_type='uniform', D_global_size=0): _ = opt, training_set discrete_latents = None if D_global_size > 0: discrete_latents = tf.random.uniform([minibatch_size], minval=0, maxval=D_global_size, dtype=tf.int32) discrete_latents = tf.one_hot(discrete_latents, D_global_size) if latent_type ==
'generic': edge_list.append((reactant1, product)) edge_list.append((reactant2, product)) node_set.add(reactant1) node_set.add(reactant2) node_set.add(product) node_set.update(mod_species) if edge_type == 'metabolic': if reactant1 != reactant2 and reactant1 != product and reactant2 != product: edge_list.append((reactant1, product)) edge_list.append((reactant2, product)) node_set.add(reactant1) node_set.add(reactant2) node_set.add(product) if reactant1 == reactant2 and reactant1 != product: edge_list.append((reactant1, product)) node_set.add(reactant1) node_set.add(product) if reactant1 != reactant2 and reactant1 == product: edge_list.append((reactant2, 'deg')) if reactant1 != reactant2 and reactant2 == product: edge_list.append((reactant1, 'deg')) if reactant1 == reactant2 and reactant1 == product: edge_list.append((reactant1, 'deg')) if rt == TReactionType.UNIBI: reactant = random.choice(nodes_list) product1 = random.choice(nodes_list) product2 = random.choice(nodes_list) if [[reactant], [product1, product2]] in reaction_list2: pick_continued += 1 continue if [[reactant], [product2, product1]] in reaction_list2: pick_continued += 1 continue if not mass_violating_reactions and reactant in {product1, product2}: pick_continued += 1 continue # if reaction_type == 'metabolic' and reactant in {product1, product2}: # pick_continued += 1 # continue mod_species = random.sample(nodes_list, mod_num) reg_signs = [random.choices([1, -1], [mod_reg[1], 1 - mod_reg[1]])[0] for _ in mod_species] reg_type = [random.choices(['a', 's'], [mod_reg[2], 1 - mod_reg[2]])[0] for _ in mod_species] reaction_list.append([rt, [reactant], [product1, product2], mod_species, reg_signs, reg_type]) reaction_list2.append([[reactant], [product1, product2]]) # node_set.add(reactant) # node_set.add(product1) # node_set.add(product2) # node_set.update(mod_species) if edge_type == 'generic': edge_list.append((reactant, product1)) edge_list.append((reactant, product2)) node_set.add(reactant) node_set.add(product1) node_set.add(product2) node_set.update(mod_species) if edge_type == 'metabolic': if reactant != product1 and reactant != product2 and product1 != product2: edge_list.append((reactant, product1)) edge_list.append((reactant, product2)) node_set.add(reactant) node_set.add(product1) node_set.add(product2) if reactant != product1 and product1 == product2: edge_list.append((reactant, product1)) node_set.add(reactant) node_set.add(product1) if reactant == product1 and product1 != product2: edge_list.append(('syn', product2)) if reactant == product2 and product1 != product2: edge_list.append(('syn', product1)) if reactant == product1 and product1 == product2: edge_list.append(('syn', reactant)) if rt == TReactionType.BIBI: product1 = random.choice(nodes_list) product2 = random.choice(nodes_list) reactant1 = random.choice(nodes_list) reactant2 = random.choice(nodes_list) if [[reactant1, reactant2], [product1, product2]] in reaction_list2: pick_continued += 1 continue if [[reactant2, reactant1], [product1, product2]] in reaction_list2: pick_continued += 1 continue if [[reactant1, reactant2], [product2, product1]] in reaction_list2: pick_continued += 1 continue if [[reactant2, reactant1], [product2, product1]] in reaction_list2: pick_continued += 1 continue if {reactant1, reactant2} == {product1, product2}: pick_continued += 1 continue # if reaction_type == 'metabolic' and {reactant1, reactant2} & {product1, product2}: # pick_continued += 1 # continue mod_species = random.sample(nodes_list, mod_num) reg_signs = [random.choices([1, -1], [mod_reg[1], 1 - mod_reg[1]])[0] for _ in mod_species] reg_type = [random.choices(['a', 's'], [mod_reg[2], 1 - mod_reg[2]])[0] for _ in mod_species] reaction_list.append( [rt, [reactant1, reactant2], [product1, product2], mod_species, reg_signs, reg_type]) reaction_list2.append([[reactant1, reactant2], [product1, product2]]) # node_set.add(reactant1) # node_set.add(reactant2) # node_set.add(product1) # node_set.add(product2) # node_set.update(mod_species) if edge_type == 'generic': edge_list.append((reactant1, product1)) edge_list.append((reactant2, product1)) edge_list.append((reactant1, product2)) edge_list.append((reactant2, product2)) node_set.add(reactant1) node_set.add(reactant2) node_set.add(product1) node_set.add(product2) node_set.update(mod_species) if edge_type == 'metabolic': if len({reactant1, reactant2, product1, product2}) \ == len([reactant1, reactant2, product1, product2]): edge_list.append((reactant1, product1)) edge_list.append((reactant1, product2)) edge_list.append((reactant2, product1)) edge_list.append((reactant2, product2)) node_set.add(reactant1) node_set.add(reactant2) node_set.add(product1) node_set.add(product2) if reactant1 == reactant2 and \ len({reactant1, product1, product2}) == len([reactant1, product1, product2]): edge_list.append((reactant1, product1)) edge_list.append((reactant1, product2)) node_set.add(reactant1) node_set.add(product1) node_set.add(product2) if reactant1 == reactant2 and product1 == product2 and reactant1 != product1: edge_list.append((reactant1, product1)) node_set.add(reactant1) node_set.add(product1) if product1 == product2 and \ len({reactant1, reactant2, product1}) == len([reactant1, reactant2, product1]): edge_list.append((reactant1, product1)) edge_list.append((reactant2, product1)) node_set.add(reactant1) node_set.add(reactant2) node_set.add(product1) # ------------------------ if reactant1 == product1 and len({reactant1, reactant2, product1, product2}) == 3: edge_list.append((reactant2, product2)) node_set.add(reactant2) node_set.add(product2) if reactant1 == product2 and len({reactant1, reactant2, product1, product2}) == 3: edge_list.append((reactant2, product1)) node_set.add(reactant2) node_set.add(product1) if reactant2 == product1 and len({reactant1, reactant2, product1, product2}) == 3: edge_list.append((reactant1, product2)) node_set.add(reactant1) node_set.add(product2) if reactant2 == product2 and len({reactant1, reactant2, product1, product2}) == 3: edge_list.append((reactant1, product1)) node_set.add(reactant1) node_set.add(product1) # ------------------------ if reactant1 != reactant2 and len({reactant1, product1, product2}) == 1: edge_list.append((reactant2, product2)) node_set.add(reactant2) node_set.add(product2) if reactant1 != reactant2 and len({reactant2, product1, product2}) == 1: edge_list.append((reactant1, product1)) node_set.add(reactant1) node_set.add(product1) # ------------------------ if product1 != product2 and len({reactant1, reactant2, product1}) == 1: edge_list.append((reactant2, product2)) node_set.add(reactant2) node_set.add(product2) if product1 != product2 and len({reactant1, reactant2, product2}) == 1: edge_list.append((reactant1, product1)) node_set.add(reactant1) node_set.add(product1) if n_reactions: if len(node_set) >= n_species and len(reaction_list) >= n_reactions: break else: if len(node_set) == n_species: break # ----------------------------------------------------------------- if not bool(out_samples) and bool(in_samples): pick_continued = 0 while True: if pick_continued == 1000: return [None], [out_samples, in_samples, joint_samples] if rxn_prob: rt = _pick_reaction_type(rxn_prob) else: rt = _pick_reaction_type() mod_num = 0 if mod_reg: mod_num = random.choices([0, 1, 2, 3], mod_reg[0])[0] # ----------------------------------------------------------------- if rt == TReactionType.UNIUNI: if edge_type == 'generic': if max(in_nodes_count) < (1 + mod_num): pick_continued += 1 continue sum_in = sum(in_nodes_count) prob_in = [x / sum_in for x in in_nodes_count] product = random.choices(in_nodes_list, prob_in)[0] while in_nodes_count[product] < (1 + mod_num): product = random.choices(in_nodes_list, prob_in)[0] reactant = random.choice(in_nodes_list) if [[reactant], [product]] in reaction_list2 or reactant == product: pick_continued += 1 continue mod_species = random.sample(nodes_list, mod_num) reg_signs = [random.choices([1, -1], [mod_reg[1], 1 - mod_reg[1]])[0] for _ in mod_species] reg_type = [random.choices(['a', 's'], [mod_reg[2], 1 - mod_reg[2]])[0] for _ in mod_species] in_nodes_count[product] -= (1 + mod_num) reaction_list.append([rt, [reactant], [product], mod_species, reg_signs, reg_type]) reaction_list2.append([[reactant], [product]]) edge_list.append((reactant, product)) if edge_type == 'metabolic': sum_in = sum(in_nodes_count) prob_in = [x / sum_in for x in in_nodes_count] product = random.choices(in_nodes_list, prob_in)[0] reactant = random.choice(in_nodes_list) if [[reactant], [product]] in reaction_list2 or reactant == product: pick_continued += 1 continue mod_species = random.sample(nodes_list, mod_num) reg_signs = [random.choices([1, -1], [mod_reg[1], 1 - mod_reg[1]])[0] for _ in mod_species] reg_type = [random.choices(['a', 's'], [mod_reg[2], 1 - mod_reg[2]])[0] for _ in mod_species] in_nodes_count[product] -= 1 reaction_list.append([rt, [reactant], [product], mod_species, reg_signs, reg_type]) reaction_list2.append([[reactant], [product]]) edge_list.append((reactant, product)) # ----------------------------------------------------------------- if rt == TReactionType.BIUNI: if edge_type == 'generic': if max(in_nodes_count) < (2 + mod_num): pick_continued += 1 continue sum_in = sum(in_nodes_count) prob_in = [x / sum_in for x in in_nodes_count] product = random.choices(in_nodes_list, prob_in)[0] while in_nodes_count[product] < (2 + mod_num): product = random.choices(in_nodes_list, prob_in)[0] reactant1 = random.choice(in_nodes_list) reactant2 = random.choice(in_nodes_list) if [[reactant1, reactant2], [product]] in reaction_list2: pick_continued += 1 continue if [[reactant2, reactant1], [product]] in reaction_list2: pick_continued += 1 continue if not mass_violating_reactions and product in {reactant1, reactant2}: pick_continued += 1 continue # if reaction_type == 'metabolic' and product in {reactant1, reactant2}: # pick_continued += 1 # continue mod_species = random.sample(nodes_list, mod_num) reg_signs = [random.choices([1, -1], [mod_reg[1], 1 - mod_reg[1]])[0] for _ in mod_species] reg_type = [random.choices(['a', 's'], [mod_reg[2], 1 - mod_reg[2]])[0] for _ in mod_species] in_nodes_count[product] -= (2 + mod_num) reaction_list.append([rt, [reactant1, reactant2], [product], mod_species, reg_signs, reg_type]) reaction_list2.append([[reactant1, reactant2], [product]]) edge_list.append((reactant1, product)) edge_list.append((reactant2, product)) if edge_type == 'metabolic': if max(in_nodes_count) < 2: pick_continued += 1 continue sum_in = sum(in_nodes_count) prob_in = [x / sum_in for x in in_nodes_count] product = random.choices(in_nodes_list, prob_in)[0] while in_nodes_count[product] < 2: product = random.choices(in_nodes_list, prob_in)[0] reactant1 = random.choice(in_nodes_list) reactant2 = random.choice(in_nodes_list) if [[reactant1, reactant2], [product]] in reaction_list2: pick_continued += 1 continue if [[reactant2, reactant1], [product]] in reaction_list2: pick_continued += 1 continue if not mass_violating_reactions and product in {reactant1, reactant2}: pick_continued += 1 continue # if reaction_type == 'metabolic' and product in {reactant1, reactant2}: # pick_continued += 1 # continue mod_species = random.sample(nodes_list, mod_num) reg_signs = [random.choices([1, -1], [mod_reg[1], 1 - mod_reg[1]])[0] for _ in mod_species] reg_type = [random.choices(['a', 's'], [mod_reg[2], 1 - mod_reg[2]])[0] for _ in mod_species] if reactant1 != reactant2 and reactant1 != product and reactant2 != product: edge_list.append((reactant1, product)) edge_list.append((reactant2, product)) in_nodes_count[product] -= 2 if reactant1 == reactant2 and reactant1 != product: edge_list.append((reactant1, product)) in_nodes_count[product] -= 1 if reactant1 != reactant2 and reactant1 == product: edge_list.append((reactant2, 'deg')) if reactant1 != reactant2 and reactant2 == product: edge_list.append((reactant1, 'deg')) if reactant1 == reactant2 and reactant1 == product: edge_list.append((reactant1, 'deg')) reaction_list.append([rt, [reactant1, reactant2], [product], mod_species, reg_signs, reg_type]) reaction_list2.append([[reactant1, reactant2], [product]]) # ----------------------------------------------------------------- if rt == TReactionType.UNIBI: if edge_type == 'generic': if sum(1 for each in in_nodes_count if each >= (1 + mod_num)) < 2 \ and max(in_nodes_count) < (2 + 2 * mod_num): pick_continued += 1 continue sum_in = sum(in_nodes_count) prob_in = [x / sum_in for x in in_nodes_count] product1 = random.choices(in_nodes_list, prob_in)[0] while in_nodes_count[product1] < (1 + mod_num): product1 = random.choices(in_nodes_list, prob_in)[0] in_nodes_count_copy = deepcopy(in_nodes_count) in_nodes_count_copy[product1] -= (1 + mod_num) sum_in_copy = sum(in_nodes_count_copy) prob_in_copy = [x / sum_in_copy for x in in_nodes_count_copy] product2
reporter=TextReporter(pylint_output), exit=False) return pylint_output.read() def _test_python_file(algo_type: str, lang: str, filepath: str, test_folder: str) -> Union[tuple, dict]: """Tests the python file Arguments: algo_type: the type of algorithm to test lang: the language to test filepath: the file to test test_folder: the folder to run the test in Returns: Returns the result of the test Exceptions: Raises RuntimeError if the environment is not properly configured """ print("HACK: _test_python_file", algo_type, lang, filepath, test_folder) # Copy over needed files from the template template_folder = os.path.join(CODE_TEMPLATE_PATH, algo_type, lang) print("HACK: _test_python_file", "template folder", template_folder) if not os.path.exists(template_folder) or not os.path.isdir(template_folder): # pylint: disable=consider-using-f-string raise RuntimeError('Expected template folder "%s" is not found' % os.path.join('/', algo_type, lang)) # Copy template files over for one_file in os.listdir(template_folder): src_name = os.path.join(template_folder, one_file) if os.path.isfile(src_name) and src_name.endswith('.py'): shutil.copyfile(src_name, os.path.join(test_folder, one_file)) print("HACK: _test_python_file", "template copy", one_file) # Copy test images and folders over test_images = [] images_folder = os.path.join(CODE_TEMPLATE_PATH, algo_type, 'images') dest_folder = os.path.join(test_folder, 'images') if not os.path.exists(dest_folder): os.makedirs(dest_folder) source_folders = [images_folder] for one_folder in source_folders: # Make sure we're putting the folders and files in the right place cur_dest_folder = dest_folder if one_folder == images_folder else dest_folder + one_folder[len(images_folder):] # Copy this folder's contents for one_file in os.listdir(one_folder): src_name = os.path.join(one_folder, one_file) dest_name = os.path.join(cur_dest_folder, one_file) if os.path.isfile(src_name): shutil.copyfile(src_name, dest_name) test_images.append(dest_name) elif os.path.isdir(src_name): os.makedirs(dest_name, exist_ok=True) source_folders.append(src_name) # Run the test cmd = [sys.executable, os.path.join(test_folder, filepath), '--working_space', test_folder] + test_images proc = subprocess.run(cmd, capture_output=True, check=False) print("PROC: ", cmd, proc.returncode, proc.stdout, proc.stderr) # Look for the result file csv_filepath = os.path.join(test_folder, 'rgb_plot.csv') if os.path.exists(csv_filepath): with open(csv_filepath, 'r', encoding='utf8') as in_file: res_data = in_file.read().split('\n') else: print("Testing run failed") res_data = {'error': 'Testing run was not successful'} return res_data def normalize_path(path: str) -> str: """Normalizes the path to the current OS separator character Arguments: path: the path to localize Return: Returns the localized path, which may be unchanged """ if os.path.sep == '/': to_replace = '\\' else: to_replace = '/' parts = path.split(to_replace) if len(parts) <= 1: return os.path.sep.join(parts) # Strip out doubled up separators new_parts = [one_part for one_part in parts if len(parts) > 0] return os.path.sep.join(new_parts) def copy_server_file(auth: dict, source_path: str, dest_path: str) -> bool: """Copies the server side file to the specified location Arguments: auth: authorization information source_path: path to the file to copy dest_path: path to copy the file to Exceptions: RuntimeError is raised if the path to copy from is not in the correct top folder """ # pylint: disable=unused-argument working_path = normalize_path(source_path) # Check if we have a special path if len(working_path) > 1: dir_name = Path(working_path).parts[1] if ADDITIONAL_LOCAL_FOLDERS and dir_name in ADDITIONAL_LOCAL_FOLDERS: cur_path = os.path.join(ADDITIONAL_LOCAL_FOLDERS[dir_name], working_path[len(dir_name) + 2:]) shutil.copyfile (cur_path, dest_path) return True if working_path[0] == '/': working_path = '.' + working_path cur_path = os.path.abspath(os.path.join(session['upload_folder'], working_path)) if not cur_path.startswith(session['upload_folder']): raise RuntimeError("Invalid source path for server side copy:", cur_path) shutil.copyfile (cur_path, dest_path) return True def irods_sha256_checksum(file_path: str, block_size: int=65536) -> str: """Calculates the iRODS checksum (hexdigest) for files Arguments: file_path: the path to the file to calculate the checksum for block_size: the size of the blocks to read in Return: The checksum value as a string """ sha256 = hashlib.sha256() with open(file_path, 'rb') as in_file: for chunk in chunks(in_file, block_size): sha256.update(chunk) return base64.b64encode(sha256.digest()).decode() def irod_md5_checksum(file_path: str) -> str: """Calcualtes the IRODS MD5 checksum for a file Arguments: file_path: the path of the file to calculate the checksum for Return: The checksum as a string """ with open(file_path, 'rb') as in_file: return hashlib.md5(in_file.read()).hexdigest() def get_irods_file(auth: dict, source_path: str, dest_path: str) -> bool: """Fetches the iRODS file to the specified location on the local Machine Arguments: auth: authorization information source_path: path to the file to pull down dest_path: path to the destination file """ have_success = False for cur_try in range(0, IRODS_DOWNLOAD_RETRIES): with iRODSSession(host=auth['host'], port=auth['port'], user=auth['user'], password=auth['password'], zone=auth['zone']) as conn: obj = conn.data_objects.get(source_path, dest_path) # Check the checksums # TODO: determine which checksum method the server uses (depending upon file size it may be faster to try both methods?) local_checksum = irod_md5_checksum(dest_path) if local_checksum == obj.checksum: # pylint: disable=no-member have_success = True break print ("IRODS: attempt", (cur_try + 1), "Bad checksum on downloaded file:", source_path) return have_success def put_irods_file(auth: dict, source_path: str, dest_path: str) -> bool: """Uploads the file to iRODS Arguments: auth: authorization information source_path: path to the source file dest_path: path to upload the file to """ raise RuntimeError("iRODS put is not implemented") FILE_HANDLERS = { '1': { 'name': 'Server-side', 'getFile': copy_server_file, 'putFile': copy_server_file, }, '2': { 'name': 'iRODS', 'getFile': get_irods_file, 'putFile': put_irods_file, } } def get_queue_path(working_folder: str) -> str: """ Gets the path to the working queue Arguments: working_folder: path to the working folder Return: Returns the path to the queue """ return os.path.join(working_folder, 'queue') def queue_start(workflow_id: str, working_folder: str, recover: bool) -> dict: """ Handles starting queueing a set of processes Arguments: workflow_id: the workflow ID working_folder: string representing the working folder recover: flag indicating this is an attempt to restart a workflow Return: Returns information on this process as a dictionary """ print("Begin queueing workflow", workflow_id) cleanup = False queue_path = get_queue_path(working_folder) if recover is True: # Make sure we have something to recover if not os.path.isfile(queue_path): msg = f'ERROR: Attempting to recover a missing workflow {working_folder}' print (msg) raise RuntimeError(f'ERROR: Attempting to recover a missing workflow {working_folder}') # TODO: Signal recover else: # Check if our queue is valid and restart it if not starting_queue = True if os.path.isfile(queue_path): try: with open(queue_path, 'r', encoding='utf8') as in_file: res = json.load(in_file) if isinstance(res, list): starting_queue = False except Exception: pass if starting_queue: os.unlink(starting_queue) # TODO: Signal cleanup cleanup = True # Begin the starting queue with open(queue_path, 'w', encoding='utf8') as out_file: json.dump([], out_file) return {'recover': recover, 'cleanup': cleanup} def queue_one_process(workflow_id: str, cur_command: dict, working_folder: str, process_info: dict): """Handles queueing one command Arguments: workflow_id: the workflow ID cur_command: the command to queue working_folder: string representing the working folder process_info: dictionary returned by starting process call """ print("Current command ", cur_command['step'], " with working folder '", cur_command['working_folder'], "'", cur_command) print(" Checking for files") for one_parameter in cur_command['parameters']: print(" ", one_parameter) # Skip over special cases if 'visibility' in one_parameter and one_parameter['visibility'] == 'server': continue # Handle downloading files if one_parameter['type'] == 'file': # Check for missing optional files if not one_parameter['value'] and 'mandatory' in one_parameter and one_parameter['mandatory'] is False: print(' Skipping missing non-mandatory file', one_parameter) continue # Copy mandatory file dest_path = os.path.join(cur_command['working_folder'], os.path.basename(one_parameter['value'])) print("Downloading file '", one_parameter['value'], "' to '", dest_path, "'") print(" one_parameter: '", one_parameter) one_parameter['getFile'](one_parameter['auth'], one_parameter['value'], dest_path) one_parameter['value'] = dest_path print("Run workflow step", workflow_id, cur_command['step'], cur_command['command']) queue_path = get_queue_path(working_folder) if 'recover' in process_info and process_info['recover'] is True: # TODO: Signal recover return with open(queue_path, 'r', encoding='utf8') as in_file: current_workflow = json.load(in_file) print("Appending command to workflow: ", current_workflow) current_workflow.append(_clean_for_json(cur_command)) print("Current workflow: ", current_workflow) with open(queue_path, 'w', encoding='utf8') as out_file: json.dump(current_workflow, out_file, indent=2) def queue_finish(workflow_id: str, working_folder: str, process_info: dict): """Finishes queueing workflow processes Arguments: workflow_id: the workflow ID working_folder: string representing the working folder process_info: dictionary returned by starting process call """ # pylint: disable=unused-argument workflow_script = os.path.join(OUR_LOCAL_PATH, 'workflow_runner.py') print("Finished queueing", workflow_id, working_folder, workflow_script) cmd = ['python3', workflow_script, working_folder] # Deliberately let the command run # pylint: disable=consider-using-with proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) print("PROC: ", cmd, proc.pid) def queue_status(workflow_id: str, working_folder: str) -> Union[dict, str, None]: """Reurns the status of the workflow Arguments: workflow_id: the ID of the current workflow working_folder: the working folder for the workflow Return: Returns None if the workflow isn't started, an empty status if it's running but has no status yet, the current status, or a string indicating the completion status. A generic status is returned if the real status can't be obtained """ print("Checking queue status", workflow_id, working_folder) status_path = os.path.join(working_folder, 'status.json') if not os.path.exists(status_path): return None cur_status = None caught_exception = False for one_attempt in range(0, FILE_PROCESS_QUEUE_STATUS_RETRIES): caught_exception = True try: with open(status_path, 'r', encoding='utf8') as in_file: try: cur_status = json.load(in_file) caught_exception = False
<gh_stars>0 #!/usr/bin/env python """ Tests of our HDF5 reader, or perhaps more accurately test of our understanding of how to use the h5py module. """ import h5py import numpy import storm_analysis import storm_analysis.sa_library.sa_h5py as saH5Py import storm_analysis.sa_library.writeinsight3 as i3w class FakeReader(object): """ Fake movie reader object. """ def __init__(self, **kwds): super(FakeReader, self).__init__(**kwds) def hashID(self): return "xyzzy" def getMovieL(self): return 10 def getMovieX(self): return 128 def getMovieY(self): return 128 def test_sa_h5py_1(): """ Test metadata round trip. """ metadata = "<xml><field1><data1>data</data1></field></xml>" filename = "test_sa_hdf5.hdf5" h5_name = storm_analysis.getPathOutputTest(filename) storm_analysis.removeFile(h5_name) # Write metadata. with saH5Py.SAH5Py(h5_name, is_existing = False) as h5: h5.addMetadata(metadata) # Read metadata. with saH5Py.SAH5Py(h5_name) as h5: assert(metadata == h5.getMetadata()) def test_sa_h5py_2(): """ Test data round trip. """ peaks = {"x" : numpy.zeros(10), "y" : numpy.ones(10)} filename = "test_sa_hdf5.hdf5" h5_name = storm_analysis.getPathOutputTest(filename) storm_analysis.removeFile(h5_name) # Write data. with saH5Py.SAH5Py(h5_name, is_existing = False) as h5: h5.setMovieInformation(1,1,2,"") h5.addLocalizations(peaks, 1) h5.addLocalizations(peaks, 1, channel = 1) # Read data. with saH5Py.SAH5Py(h5_name) as h5: # Check that frame 0 is empty. locs = h5.getLocalizationsInFrame(0) assert(not bool(locs)) # Check frame1. locs = h5.getLocalizationsInFrame(1) assert(numpy.allclose(peaks["x"], locs["x"])) assert(numpy.allclose(peaks["y"], locs["y"])) assert(numpy.allclose(peaks["x"], locs["c1_x"])) assert(numpy.allclose(peaks["y"], locs["c1_y"])) # Check getting a specific field. locs = h5.getLocalizationsInFrame(1, fields = ["x"]) assert("x" in locs) assert(not "y" in locs) def test_sa_h5py_3(): """ Test getting data from multiple frames. """ peaks = {"x" : numpy.zeros(10), "y" : numpy.ones(10)} filename = "test_sa_hdf5.hdf5" h5_name = storm_analysis.getPathOutputTest(filename) storm_analysis.removeFile(h5_name) # Write data. fr = FakeReader() with saH5Py.SAH5Py(h5_name, is_existing = False) as h5: h5.addMovieInformation(fr) for i in range(fr.getMovieL()): h5.addLocalizations(peaks, i) # Read data. with saH5Py.SAH5Reader(h5_name) as h5: # Check localizations in first 5 frames. locs = h5.getLocalizationsInFrameRange(0,5) assert(locs["x"].size == 50) # Get all the localizations. locs = h5.getLocalizations() assert(locs["x"].size == (10.0 * fr.getMovieL())) def test_sa_h5py_4(): """ Test handling of drift correction. """ peaks = {"x" : numpy.zeros(10), "y" : numpy.ones(10)} filename = "test_sa_hdf5.hdf5" h5_name = storm_analysis.getPathOutputTest(filename) storm_analysis.removeFile(h5_name) # Write data. with saH5Py.SAH5Py(h5_name, is_existing = False) as h5: h5.addLocalizations(peaks, 1) h5.setDriftCorrection(1, dx = 1.0, dy = -1.0) # Read data. with saH5Py.SAH5Py(h5_name) as h5: # not corrected. locs = h5.getLocalizationsInFrame(1) assert(numpy.allclose(peaks["x"], locs["x"])) assert(numpy.allclose(peaks["y"], locs["y"])) # corrected. locs = h5.getLocalizationsInFrame(1, drift_corrected = True) assert(numpy.allclose(peaks["x"] + 1.0, locs["x"])) assert(numpy.allclose(peaks["y"] - 1.0, locs["y"])) def test_sa_h5py_5(): """ Test querying if the HDF5 file is a storm-analysis file. """ filename = "test_sa_hdf5.hdf5" h5_name = storm_analysis.getPathOutputTest(filename) storm_analysis.removeFile(h5_name) # Open empty file. with saH5Py.SAH5Py(h5_name, is_existing = False) as h5: pass assert(saH5Py.isSAHDF5(h5_name)) # Create generic HDF5 file. f = h5py.File(h5_name, "w") f.close() assert(not saH5Py.isSAHDF5(h5_name)) # Create Insight3 file. with i3w.I3Writer(h5_name) as i3: pass assert not(saH5Py.isSAHDF5(h5_name)) def test_sa_h5py_6(): """ Test adding tracks. """ tracks = {"x" : numpy.zeros(10), "y" : numpy.ones(10)} filename = "test_sa_hdf5.hdf5" h5_name = storm_analysis.getPathOutputTest(filename) storm_analysis.removeFile(h5_name) # Write tracks. with saH5Py.SAH5Py(h5_name, is_existing = False) as h5: h5.addTracks(tracks) # Read tracks. with saH5Py.SAH5Py(h5_name) as h5: assert(h5.getNTracks() == tracks["x"].size) # Write tracks again, this should overwrite above. with saH5Py.SAH5Py(h5_name) as h5: h5.addTracks(tracks) h5.addTracks(tracks) # Read tracks. with saH5Py.SAH5Py(h5_name) as h5: assert(h5.getNTracks() == 2*tracks["x"].size) def test_sa_h5py_7(): """ Test tracks iterator. """ tracks = {"x" : numpy.zeros(10), "y" : numpy.ones(10)} filename = "test_sa_hdf5.hdf5" h5_name = storm_analysis.getPathOutputTest(filename) storm_analysis.removeFile(h5_name) # No tracks. with saH5Py.SAH5Py(h5_name, is_existing = False) as h5: pass with saH5Py.SAH5Py(h5_name) as h5: for t in h5.tracksIterator(): assert(False) # We should not get here. # Tracks. storm_analysis.removeFile(h5_name) with saH5Py.SAH5Py(h5_name, is_existing = False) as h5: h5.addTracks(tracks) with saH5Py.SAH5Py(h5_name) as h5: for t in h5.tracksIterator(): assert(numpy.allclose(t["x"], tracks["x"])) # Only get one field. for t in h5.tracksIterator(["x"]): assert(not "y" in t) def test_sa_h5py_8(): """ Test localizations iterator. """ peaks = {"x" : numpy.zeros(10), "y" : numpy.ones(10)} filename = "test_sa_hdf5.hdf5" h5_name = storm_analysis.getPathOutputTest(filename) storm_analysis.removeFile(h5_name) # Write data. fr = FakeReader() with saH5Py.SAH5Py(h5_name, is_existing = False) as h5: h5.addMovieInformation(fr) for i in range(fr.getMovieL()): h5.addLocalizations(peaks, 2*i) # Read data. with saH5Py.SAH5Py(h5_name) as h5: for fnum, locs in h5.localizationsIterator(): assert(locs["x"].size == 10) def test_sa_h5py_9(): """ Test setting the track id field. """ peaks = {"x" : numpy.zeros(10), "y" : numpy.ones(10)} filename = "test_sa_hdf5.hdf5" h5_name = storm_analysis.getPathOutputTest(filename) storm_analysis.removeFile(h5_name) # Add localizations and track id. with saH5Py.SAH5Py(h5_name, is_existing = False) as h5: h5.addLocalizations(peaks, 1) h5.addTrackID(numpy.ones(10), 1) # Check track id. with saH5Py.SAH5Py(h5_name) as h5: locs = h5.getLocalizationsInFrame(1) assert(numpy.allclose(locs["track_id"], numpy.ones(10))) # Change track id. with saH5Py.SAH5Py(h5_name) as h5: h5.addTrackID(numpy.zeros(10), 1) # Check track id. with saH5Py.SAH5Py(h5_name) as h5: locs = h5.getLocalizationsInFrame(1) assert(numpy.allclose(locs["track_id"], numpy.zeros(10))) def test_sa_h5py_10(): """ Test 'is_existing' and 'overwrite' parameters. """ filename = "test_sa_hdf5.hdf5" h5_name = storm_analysis.getPathOutputTest(filename) storm_analysis.removeFile(h5_name) # Test failure on trying to open a file that does not exist. try: with saH5Py.SAH5Py(h5_name) as h5: pass except saH5Py.SAH5PyException: pass else: assert(False) # Test failure on trying to overwrite a file that does exist. # Create the file. with saH5Py.SAH5Py(h5_name, is_existing = False) as h5: pass # Test that we cannot overwrite it. try: with saH5Py.SAH5Py(h5_name, is_existing = False) as h5: pass except saH5Py.SAH5PyException: pass else: assert(False) # Test that we can overwrite it. with saH5Py.SAH5Py(h5_name, is_existing = False, overwrite = True) as h5: pass def test_sa_h5py_11(): """ Test hasLocalizationField() and hasTracksField() """ peaks = {"x" : numpy.zeros(10), "y" : numpy.ones(10)} filename = "test_sa_hdf5.hdf5" h5_name = storm_analysis.getPathOutputTest(filename) storm_analysis.removeFile(h5_name) # Write data. with saH5Py.SAH5Py(h5_name, is_existing = False) as h5: h5.setMovieInformation(256, 256, 10, "XYZZY") h5.addLocalizations(peaks, 1) h5.addTracks(peaks) # Check. with saH5Py.SAH5Py(h5_name) as h5: assert(h5.hasLocalizationsField("x")) assert(not h5.hasLocalizationsField("x1")) assert(h5.hasTracksField("x")) assert(not h5.hasTracksField("x1")) def test_sa_h5py_12(): """ Test handling of multiple channels. """ peaks = {"x" : numpy.zeros(3), "y" : numpy.ones(3)} filename = "test_sa_hdf5.hdf5" h5_name = storm_analysis.getPathOutputTest(filename) storm_analysis.removeFile(h5_name) # Write data. with saH5Py.SAH5Py(h5_name, is_existing = False) as h5: h5.setMovieInformation(1,1,2,"") h5.addLocalizations(peaks, 1) peaks["x"] += 1 peaks["y"] += 1 h5.addLocalizations(peaks, 1, channel = 1) peaks["x"] += 1 peaks["y"] += 1 h5.addLocalizations(peaks, 1, channel = 2) # Read data. with saH5Py.SAH5Py(h5_name) as h5: # Check getting number of channels. assert(h5.getNChannels() == 3) for [fnum, locs] in h5.localizationsIterator(): for i, elt in enumerate(h5.splitByChannel(locs)): assert(numpy.allclose(elt["x"], i * numpy.ones(3))) assert(numpy.allclose(elt["y"], i * numpy.ones(3) + 1.0)) def test_sa_h5py_13(): """ Test gridding tracks. """ tracks = {"x" : numpy.array([10,20,30]), "y" : numpy.array([10,10,10]), "z" : numpy.array([-0.2,0.0,0.2])} h5_name = storm_analysis.getPathOutputTest("test_sa_hdf5.hdf5") # Tracks. with saH5Py.SAH5Py(h5_name, is_existing = False, overwrite = True) as h5: h5.setMovieInformation(40, 40, 1, "") h5.addTracks(tracks) with saH5Py.SAH5Grid(filename = h5_name, scale = 1, z_bins = 3) as h5g: im_2d = h5g.gridTracks2D() im_3d = h5g.gridTracks3D(-0.201,0.201) for i in range(tracks["x"].size): assert(im_2d[int(tracks["x"][i]), int(tracks["y"][i])] == 1) assert(im_3d[int(tracks["x"][i]), int(tracks["y"][i]), i] == 1) im_3d = h5g.gridTracks3D(-0.1,0.1) assert(im_3d[int(tracks["x"][0]), int(tracks["y"][0]), 0] == 0) assert(im_3d[int(tracks["x"][1]), int(tracks["y"][1]), 1] == 1) assert(im_3d[int(tracks["x"][2]), int(tracks["y"][2]), 2] == 0) def test_sa_h5py_14(): """ Test gridding tracks with dx, dy. """ tracks = {"x" : numpy.array([10,20,30]), "y" : numpy.array([10,10,10]), "z" : numpy.array([-0.2,0.0,0.2])} dx = 1 dy = 2 h5_name = storm_analysis.getPathOutputTest("test_sa_hdf5.hdf5") # Tracks. with saH5Py.SAH5Py(h5_name, is_existing = False, overwrite = True) as h5: h5.setMovieInformation(40, 40, 1, "") h5.addTracks(tracks) with saH5Py.SAH5Grid(filename = h5_name, scale = 1, z_bins = 3) as h5g: im_2d = h5g.gridTracks2D(dx = dx, dy = dy) im_3d = h5g.gridTracks3D(-0.201,0.201, dx = dx, dy = dy) for i in range(tracks["x"].size): assert(im_2d[int(tracks["x"][i]+dx), int(tracks["y"][i]+dy)] == 1) assert(im_3d[int(tracks["x"][i]+dx), int(tracks["y"][i]+dy), i] == 1) def test_sa_h5py_15(): """ Test isAnalyzed() """ peaks = {"x" : numpy.zeros(10), "y" : numpy.ones(10)} empty = {"x" : numpy.array([]), "y" : numpy.array([])} filename = "test_sa_hdf5.hdf5" h5_name = storm_analysis.getPathOutputTest(filename) # Write data. with saH5Py.SAH5Py(h5_name, is_existing = False, overwrite = True) as h5: h5.setMovieInformation(100, 100, 2, "") h5.addLocalizations(peaks, 0) h5.addLocalizations(empty, 1) # Read data. with saH5Py.SAH5Py(h5_name) as h5: for i, elt in enumerate([True, True, False]): assert (h5.isAnalyzed(i) == elt) def test_sa_h5py_16(): """ Test that localizations iterator skips empty frames. """ peaks = {"x" : numpy.zeros(10), "y" : numpy.ones(10)} empty = {"x" : numpy.array([]), "y" : numpy.array([])} filename = "test_sa_hdf5.hdf5" h5_name = storm_analysis.getPathOutputTest(filename) storm_analysis.removeFile(h5_name) # Write data. with saH5Py.SAH5Py(h5_name, is_existing = False, overwrite = True) as h5: h5.setMovieInformation(100, 100, 5, "") h5.addLocalizations(peaks, 0) h5.addLocalizations(empty, 1) h5.addLocalizations(peaks, 2) # Read data. with saH5Py.SAH5Py(h5_name) as h5: for fnum, locs in h5.localizationsIterator(): assert(fnum != 1) def test_sa_h5py_17(): """ Test that localizations iterator does not skip empty frames (when requested not to). """ peaks = {"x" : numpy.zeros(10), "y" : numpy.ones(10)} empty = {"x" : numpy.array([]), "y" : numpy.array([])} filename = "test_sa_hdf5.hdf5" h5_name =
# # Copyright (c) 2021 Citrix Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License") # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response from nssrc.com.citrix.netscaler.nitro.service.options import options from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception from nssrc.com.citrix.netscaler.nitro.util.nitro_util import nitro_util class ns_stats(base_resource) : def __init__(self) : self._clearstats = None self._rescpuusagepcnt = 0 self._cpuusagepcnt = 0 self._cachemaxmemorykb = 0 self._delcmpratio = 0 self._rescpuusage = 0 self._cpuusage = 0 self._resmemusage = 0 self._comptotaldatacompressionratio = 0 self._compratio = 0 self._cacheutilizedmemorykb = 0 self._cachemaxmemoryactivekb = 0 self._cache64maxmemorykb = 0 self._cachepercentoriginbandwidthsaved = 0 self._cachetotmisses = 0 self._cachemissesrate = 0 self._cachetothits = 0 self._cachehitsrate = 0 self._memusagepcnt = 0 self._memuseinmb = 0 self._mgmtcpuusagepcnt = 0 self._pktcpuusagepcnt = 0 self._starttimelocal = "" self._starttime = "" self._transtime = "" self._hacurstate = "" self._hacurmasterstate = "" self._sslnumcardsup = 0 self._sslcards = 0 self._disk0perusage = 0 self._disk1perusage = 0 self._disk0avail = 0 self._disk1avail = 0 self._totrxmbits = 0 self._rxmbitsrate = 0 self._tottxmbits = 0 self._txmbitsrate = 0 self._tcpcurclientconn = 0 self._tcpcurclientconnestablished = 0 self._tcpcurserverconn = 0 self._tcpcurserverconnestablished = 0 self._httptotrequests = 0 self._httprequestsrate = 0 self._httptotresponses = 0 self._httpresponsesrate = 0 self._httptotrxrequestbytes = 0 self._httprxrequestbytesrate = 0 self._httptotrxresponsebytes = 0 self._httprxresponsebytesrate = 0 self._ssltottransactions = 0 self._ssltransactionsrate = 0 self._ssltotsessionhits = 0 self._sslsessionhitsrate = 0 self._appfirewallrequests = 0 self._appfirewallrequestsrate = 0 self._appfirewallresponses = 0 self._appfirewallresponsesrate = 0 self._appfirewallaborts = 0 self._appfirewallabortsrate = 0 self._appfirewallredirects = 0 self._appfirewallredirectsrate = 0 self._misccounter0 = 0 self._misccounter1 = 0 self._numcpus = 0 @property def clearstats(self) : r"""Clear the statsistics / counters.<br/>Possible values = basic, full. """ try : return self._clearstats except Exception as e: raise e @clearstats.setter def clearstats(self, clearstats) : r"""Clear the statsistics / counters """ try : self._clearstats = clearstats except Exception as e: raise e @property def appfirewallredirectsrate(self) : r"""Rate (/s) counter for appfirewallredirects. """ try : return self._appfirewallredirectsrate except Exception as e: raise e @property def ssltottransactions(self) : r"""Number of SSL transactions on the Citrix ADC. """ try : return self._ssltottransactions except Exception as e: raise e @property def sslnumcardsup(self) : r"""Number of SSL cards that are UP. If the number of cards UP is lower than a threshold, a failover is initiated. """ try : return self._sslnumcardsup except Exception as e: raise e @property def hacurmasterstate(self) : r"""Indicates the high availability state of the node. Possible values are: STAYSECONDARY - Indicates that the selected node remains the secondary node in a high availability setup. In this case a forced failover does not change the state but, instead, returns an appropriate error message. This is a configured value and not a statistic. PRIMARY - Indicates that the selected node is the primary node in a high availability setup. SECONDARY - Indicates that the selected node is the secondary node in a high availability setup. CLAIMING - Indicates that the secondary node is in the process of taking over as the primary node. This is the intermediate state in the transition of the secondary node to primary status. FORCE CHANGE - Indicates that the secondary node is forcibly changing its status to primary due to a forced failover issued on the secondary node. . """ try : return self._hacurmasterstate except Exception as e: raise e @property def httprxrequestbytesrate(self) : r"""Rate (/s) counter for httptotrxrequestbytes. """ try : return self._httprxrequestbytesrate except Exception as e: raise e @property def httptotrxresponsebytes(self) : r"""Total number of bytes of HTTP response data received. """ try : return self._httptotrxresponsebytes except Exception as e: raise e @property def disk1perusage(self) : r"""Used space in /var partition of the disk, as a percentage. This is a critical counter. You can configure /var Used (%) by using the Set snmp alarm DISK-USAGE-HIGH command. """ try : return self._disk1perusage except Exception as e: raise e @property def rescpuusagepcnt(self) : r"""Average CPU utilization percentage. Not applicable for a single-CPU system. """ try : return self._rescpuusagepcnt except Exception as e: raise e @property def appfirewallresponsesrate(self) : r"""Rate (/s) counter for appfirewallresponses. """ try : return self._appfirewallresponsesrate except Exception as e: raise e @property def delcmpratio(self) : r"""Ratio of compressible data received to compressed data transmitted.If this ratio is one (uncmp:1.0) that means compression is disabled or we are not able to compress even a single compressible packet. """ try : return self._delcmpratio except Exception as e: raise e @property def appfirewallresponses(self) : r"""HTTP/HTTPS responses sent by your protected web servers via the Application Firewall. """ try : return self._appfirewallresponses except Exception as e: raise e @property def comptotaldatacompressionratio(self) : r"""Ratio of total HTTP data received to total HTTP data transmitted. """ try : return self._comptotaldatacompressionratio except Exception as e: raise e @property def httprxresponsebytesrate(self) : r"""Rate (/s) counter for httptotrxresponsebytes. """ try : return self._httprxresponsebytesrate except Exception as e: raise e @property def disk0perusage(self) : r"""Used space in /flash partition of the disk, as a percentage. This is a critical counter. You can configure /flash Used (%) by using the Set snmp alarm DISK-USAGE-HIGH command. . """ try : return self._disk0perusage except Exception as e: raise e @property def appfirewallabortsrate(self) : r"""Rate (/s) counter for appfirewallaborts. """ try : return self._appfirewallabortsrate except Exception as e: raise e @property def appfirewallrequestsrate(self) : r"""Rate (/s) counter for appfirewallrequests. """ try : return self._appfirewallrequestsrate except Exception as e: raise e @property def ssltotsessionhits(self) : r"""Number of SSL session reuse hits on the Citrix ADC. """ try : return self._ssltotsessionhits except Exception as e: raise e @property def appfirewallredirects(self) : r"""HTTP/HTTPS requests redirected by the Application Firewall to a different Web page or web server. (HTTP 302). """ try : return self._appfirewallredirects except Exception as e: raise e @property def mgmtcpuusagepcnt(self) : r"""Average Management CPU utilization percentage. """ try : return self._mgmtcpuusagepcnt except Exception as e: raise e @property def cpuusage(self) : r"""CPU utilization percentage. """ try : return self._cpuusage except Exception as e: raise e @property def httptotresponses(self) : r"""Total number of HTTP responses sent. """ try : return self._httptotresponses except Exception as e: raise e @property def compratio(self) : r"""Ratio of the compressible data received from the server to the compressed data sent to the client. """ try : return self._compratio except Exception as e: raise e @property def memuseinmb(self) : r"""Main memory currently in use, in megabytes. """ try : return self._memuseinmb except Exception as e: raise e @property def sslsessionhitsrate(self) : r"""Rate (/s) counter for ssltotsessionhits. """ try : return self._sslsessionhitsrate except Exception as e: raise e @property def resmemusage(self) : r"""Percentage of memory utilization on Citrix ADC. """ try : return self._resmemusage except Exception as e: raise e @property def cache64maxmemorykb(self) : r"""Largest amount of memory the Citrix ADC can dedicate to caching, up to 50% of available memory. A 0 value disables caching, but the caching module continues to run. . """ try : return self._cache64maxmemorykb except Exception as e: raise e @property def starttime(self) : r"""Time when the Citrix ADC was last started. """ try : return self._starttime except Exception as e: raise e @property def cachepercentoriginbandwidthsaved(self) : r"""Percentage of origin bandwidth saved, expressed as number of bytes served from the integrated cache divided by all bytes served. The assumption is that all compression is done in the Citrix ADC. """ try : return self._cachepercentoriginbandwidthsaved except Exception as e: raise e @property def misccounter0(self) : r"""Miscellaneous Counter 0. """ try : return self._misccounter0 except Exception as e: raise e @property def memusagepcnt(self) : r"""Percentage of memory utilization on Citrix ADC. """ try : return self._memusagepcnt except Exception as e: raise e @property def cachehitsrate(self) : r"""Rate (/s) counter for cachetothits. """ try : return self._cachehitsrate except Exception as e: raise e @property def transtime(self) : r"""Time when the last master state transition occurred. You can use this statistic for debugging. """ try : return self._transtime except Exception as e: raise e @property def cacheutilizedmemorykb(self) : r"""Amount of memory the integrated cache is currently using. """ try : return self._cacheutilizedmemorykb except Exception as e: raise e @property def appfirewallaborts(self) : r"""Incomplete HTTP/HTTPS requests aborted by the client before the Application Firewall could finish processing them. """ try : return self._appfirewallaborts except Exception as e: raise e @property def disk1avail(self) : r"""Available space in /var partition of the hard disk. """ try : return self._disk1avail except Exception as e: raise e @property def tcpcurserverconnestablished(self) : r"""Current server connections in the Established state, which indicates that data transfer can occur between the Citrix ADC and the server. """ try : return self._tcpcurserverconnestablished except Exception as e: raise e @property def tcpcurclientconn(self) : r"""Client connections, including connections in the Opening, Established, and Closing state. """ try : return self._tcpcurclientconn except Exception as e: raise e @property def tcpcurserverconn(self) : r"""Server connections, including connections in the Opening, Established, and Closing state. """ try : return self._tcpcurserverconn except Exception as e: raise e @property def rescpuusage(self) : r"""Shows average CPU utilization percentage if more than 1 CPU is present. """ try : return self._rescpuusage except Exception as e: raise e @property def appfirewallrequests(self) : r"""HTTP/HTTPS requests sent to your protected web servers via the Application Firewall. """ try : return self._appfirewallrequests except Exception as e: raise e @property def totrxmbits(self) : r"""Number of megabytes received by the Citrix ADC. """ try : return self._totrxmbits except Exception as e: raise e @property def tottxmbits(self) : r"""Number of megabytes transmitted by the Citrix ADC. """ try : return self._tottxmbits except Exception as e: raise e @property def cachemissesrate(self) : r"""Rate (/s) counter for cachetotmisses. """ try : return self._cachemissesrate except Exception as e: raise e @property def cachemaxmemorykb(self) : r"""Largest amount of memory the Citrix ADC can dedicate to caching, up to 50% of available memory. A 0 value disables caching, but the caching module continues to run. . """ try : return self._cachemaxmemorykb except Exception as e: raise e @property def httptotrequests(self) : r"""Total number of HTTP requests received. """ try : return self._httptotrequests except Exception as e: raise e @property def cachetothits(self) : r"""Responses served from the integrated cache. These responses match a policy with a CACHE action. """ try : return self._cachetothits except Exception as e: raise e @property def misccounter1(self) : r"""Miscellaneous Counter 1. """ try : return self._misccounter1 except Exception as e: raise e @property def numcpus(self)
<gh_stars>10-100 # Copyright (C) 2013 Sony Mobile Communications AB. # All rights, including trade secret rights, reserved. import os import sys import StringIO import shutil import ave.git import vcsjob import vcsjob.vcs from ave.workspace import Workspace # redirect stdout to a testable buffer. keep a backup to undo the replacement # after the test def redirect(): backup = sys.stdout sys.stdout = strio = StringIO.StringIO() return (strio, backup) def undirect(backup): sys.stdout = backup # factory function. a git with two commits and a valid .vcsjob file def make_vcsjob_tree(workspace): path = workspace.make_tempdir() f = open(os.path.join(path, '.vcsjob'), 'w') f.write('{ "jobs": [ { "path": "job.sh" } ] }') f.close() f = open(os.path.join(path, 'job.sh'), 'w') f.write('#! /bin/bash\nprintenv\n') f.close() os.chmod(os.path.join(path, 'job.sh'), 0755) ave.git.init(path) ave.git.add(path, '.') ave.git.commit(path, 'First commit') ave.git.create_branch(path, 'testing') f = open(os.path.join(path, 'foo.txt'), 'w') f.write('bar') f.close() ave.git.add(path, '.') ave.git.commit(path, 'Second commit') return path # check that result is False when invoked without arguments def t1(): pretty = '%s t1' % __file__ print(pretty) exc = None try: vcsjob.vcs.fetch(None, None, None) except Exception, e: exc = e if not exc: print( 'FAIL %s: vcsjob.vcs.run() without arguments should fail' % pretty ) return if str(exc) != 'source, refspec and destination must be specified': print('FAIL %s: wrong message: %s' % (pretty, str(exc))) return # check that usage info is printed if invoked with garbage options def t2(): pretty = '%s t2' % __file__ print(pretty) (strio, backup) = redirect() result = vcsjob.vcs.main(['--fg','hubba']) undirect(backup) if result == vcsjob.OK: print( 'FAIL %s: vcsjob.vcs.main() with garbage arguments should fail' % pretty ) return message = strio.getvalue() if not message.startswith('ERROR: option --fg not recognized'): print('FAIL %s: wrong message: %s' % (pretty, message)) return # check that usage info is printed if invoked with extra non-dashed arguments def t3(): pretty = '%s t3' % __file__ print(pretty) (strio, backup) = redirect() result = vcsjob.vcs.main(['non-dashed']) undirect(backup) if result == vcsjob.OK: print( 'FAIL %s: vcsjob.vcs.main() with garbage arguments should fail' % pretty ) return message = strio.getvalue() if not message.startswith('ERROR: non-dashed options "non-dashed" not '): print('FAIL %s: error not shown: %s' % (pretty, message)) return # check that usage info is printed if invoked without complete input (source, # destination and refspec) def t4(): pretty = '%s t4' % __file__ print(pretty) (strio, backup) = redirect() result = vcsjob.vcs.main(['--source=incomplete']) undirect(backup) if result == vcsjob.OK: print( 'FAIL %s: vcsjob.vcs.main() with garbage arguments should fail' % pretty ) return message = strio.getvalue() if not message.startswith('ERROR: source, refspec and destination must be'): print('FAIL %s: error not shown: %s' % (pretty, message)) return # check that supported protocol info is printed if a non-git is given as source def t5(): pretty = '%s t5' % __file__ print(pretty) exc = None try: vcsjob.fetch('/', 'nonsense', 'nonsense') except Exception, e: exc = e if not exc: print( 'FAIL %s: vcsjob.fetch() with garbage arguments should fail' % pretty ) return if str(exc) != 'supported protocols: git': print('FAIL %s: wrong message: %s' % (pretty, str(exc))) return # check that an error is printed if non-local destination is given def t6(): pretty = '%s t6' % __file__ print(pretty) w = Workspace('vcsjob-fetch-t6') # create a git tree in a temp directory to use for this test src = make_vcsjob_tree(w) exc = None try: vcsjob.fetch(src, 'ssh://host', 'bleh') except Exception, e: exc = e if not exc: print( 'FAIL %s: vcsjob.fetch() with garbage arguments should fail' % pretty ) return if str(exc) != 'destination must be on a locally mounted file system': print('FAIL %s: wrong message: %s' % (pretty, str(exc))) return w.delete() # check that basic fetching works def t7(): pretty = '%s t7' % __file__ print(pretty) w = Workspace('vcsjob-fetch-t7') # set up source and destination in temporary directories src = make_vcsjob_tree(w) dst = w.make_tempdir() # fetch the source into the destination try: vcsjob.fetch(src, dst, 'master') except Exception, e: print('FAIL %s: fetch failed: %s' % (pretty, str(e))) return # look for src/test.txt in the destination if not os.path.isfile(os.path.join(dst, '.vcsjob')): print('FAIL %s: source file not in destination' % pretty) return w.delete() # check that repeated fetching works def t8(): pretty = '%s t8' % __file__ print(pretty) w = Workspace('vcsjob-fetch-t8') # set up source and destination in temporary directories src = make_vcsjob_tree(w) dst = w.make_tempdir() # repeatedly fetch the source into the destination result = vcsjob.OK for i in range(5): try: result += vcsjob.fetch(src, dst, 'master') except Exception, e: print('FAIL %s: fetch failed: %s' % (pretty, str(e))) return if result != vcsjob.OK: print('FAIL %s: wrong return value: %s' % (pretty, result)) return # look for src/test.txt in the destination if not os.path.isfile(os.path.join(dst, '.vcsjob')): print('FAIL %s: source file not in destination' % pretty) return w.delete() # check that vcsjob refuses to switch between branches if the destination tree # is dirty. def t9(): pretty = '%s t9' % __file__ print(pretty) w = Workspace('vcsjob-fetch-t9') src = make_vcsjob_tree(w) dst = w.make_tempdir() # pull the tree into a temporary directory, check that the current branch # is "master". try: result = vcsjob.fetch(src, dst, 'master') except Exception, e: print('FAIL %s: fetch failed: %s' % (pretty, str(e))) return if result != vcsjob.OK: print('FAIL %s: wrong return value: %s' % (pretty, result)) return branch = ave.git.branch(dst) if branch != 'master': print( 'FAIL %s: wrong branch checked out after first fetch: %s' % (pretty, branch) ) return # introduce some dirt f = open(os.path.join(dst, 'dirt'), 'w') f.write('some dirt for `git status` to pick up') f.close() # fetch again into the same directory, check that the checkout failed and # that "master" remains the current branch. exc = None try: result = vcsjob.vcs.run(['-s',src, '-d',dst, '-r','testing']) except Exception, e: exc = e if not exc: print('FAIL %s: fetch did not fail on dirty destination' % pretty) return branch = ave.git.branch(dst) if branch != 'master': print( 'FAIL %s: wrong branch checked out after second fetch: %s' % (pretty, branch) ) return w.delete() # check that fetching to a non-existant directory works def t10(): pretty = '%s t10' % __file__ print(pretty) w = Workspace('vcsjob-fetch-t10') # set up source and destination in temporary directories src = make_vcsjob_tree(w) # "create" a non-existant destination directory by removing a temporary dir dst = w.make_tempdir() shutil.rmtree(dst) # fetch the source into the destination try: result = vcsjob.fetch(src, dst, 'master') except Exception, e: print('FAIL %s: fetch failed: %s' % (pretty, str(e))) return if result != vcsjob.OK: print('FAIL %s: wrong return value: %s' % (pretty, result)) return # look for src/test.txt in the destination if not os.path.isfile(os.path.join(dst, '.vcsjob')): print('FAIL %s: source file not in destination' % pretty) return w.delete() # check that fetching to a destination which is not a directory doesn't work def t11(): pretty = '%s t11' % __file__ print(pretty) w = Workspace('vcsjob-fetch-t11') src = make_vcsjob_tree(w) # create a non-directory destination dst = os.path.join(w.make_tempdir(), 'some_file') with open(dst, 'w') as f: f.write('anything') f.close() # fetch the source into the destination exc = None try: result = vcsjob.fetch(src, dst, 'master') except Exception, e: exc = e if not exc: print('FAIL %s: fetch did not fail' % pretty) return # check the error message if 'destination is not a directory:' not in str(exc): print('FAIL %s: wrong error message: %s' % (pretty, str(exc))) return w.delete() # check that fetching to a non-empty directory does not work def t12(): pretty = '%s t12' % __file__ print(pretty) w = Workspace('vcsjob-fetch-t12') src = make_vcsjob_tree(w) # set up destination in a temporary directory that contains some dirt dst = w.make_tempdir() f = open(os.path.join(dst, 'dirt.txt'), 'w') f.write('bar') f.close() exc = None try: vcsjob.fetch(src, dst, 'master') except Exception, e: exc = e if not exc: print('FAIL %s: fetch did not fail' % pretty) return # check the error message if 'destination is not a git tree:' not in str(exc): print('FAIL %s: wrong error message: %s' % (pretty, str(exc))) return w.delete() # check that vcsjob refuses to pull same branch if the destination is dirty def t13(): pretty = '%s t13' % __file__ print(pretty) w = Workspace('vcsjob-fetch-t13') src = make_vcsjob_tree(w) # pull the tree into a temporary directory, check that the current branch # is "master". dst = w.make_tempdir() try: vcsjob.fetch(src, dst, 'master') except Exception, e: print('FAIL %s: could not fetch master: %s' % (pretty, str(e))) return
not specified otherwise. Parameters: quantity: The quantity of the currency the position holds code: The currency code of the currency this Cash position represents Attributes: code (str): The currency code of the currency underlying this position """ def __init__(self, quantity: float, code: Optional[str] = None) -> None: code = Currency.base if code is None else code super().__init__(Currency(code), quantity) def __str__(self) -> str: return f"<{self.asset.code} {self.asset.symbol}{self.quantity}>" def __repr__(self) -> str: return self.__str__() def __add__(self, other: object) -> Cash: if not isinstance(other, (Cash, float, int)): return NotImplemented other = self.to_cash(other) new = copy(self) if new.asset is other.asset: new.quantity += other.quantity else: value = new.asset.convert(other.asset.code) * other.quantity new.quantity += value return new def __sub__(self, other: object) -> Cash: if not isinstance(other, (Cash, int, float)): return NotImplemented other = self.to_cash(other) new = copy(self) if new.asset is other.asset: new.quantity -= other.quantity else: value = new.asset.convert(other.asset.code) * other.quantity new.quantity -= value return new def __lt__(self, other: object) -> bool: if not isinstance(other, (Cash, int, float)): return NotImplemented other = self.to_cash(other) return self.value < other.value def __gt__(self, other: object) -> bool: if not isinstance(other, (Cash, int, float)): return NotImplemented other = self.to_cash(other) return self.value > other.value def __eq__(self, other: object) -> bool: if not isinstance(other, (Cash, int, float)): return NotImplemented other = self.to_cash(other) return self.value == other.value def __copy__(self) -> Cash: new = Cash(self.quantity, self.asset.code) new.history = self.history return new @property def expired(self) -> Literal[False]: """Always returns false, Cash positions never expire""" return False @property def code(self) -> str: """The currency code of this Cash Position's currency""" return self.asset.code @staticmethod def from_position(position: Position) -> Cash: """ Returns a cash object representing the value of the asset passed Parameters: position: The position to transform into a cash object Returns: The transformed cash object """ return Cash(position.value, position.asset.base) def from_number(self, other: float) -> Cash: """ Given a number value, returns a cash object that shares the same underlying currecy as this cash object, whose quantity is the given number Parameters: other: The quantity of the cash object to instantiate Returns: The cash object """ return Cash(other, self.asset.code) def from_cash(self, other: Cash) -> Cash: """ Given a cash object, returns a cash object of equivalent value (based on current exchange rates) represented in the currency of this cash object Parameters: other: The cash object to convert to units of this cash object's currency Returns: The converted cash object """ quantity = self.asset.rate(other.asset.code) * other.quantity return Cash(quantity, self.asset.code) def convert(self, code: str, inplace: bool = False) -> Cash: """ Converts this cash asset to another currency Parameters: code: The currency code of the currency to convert to inplace: Whether or not to conver this cash position inplace Returns: The converted cash object, which is self if inplace=True """ quantity = self.asset.rate(code) * self.quantity new = Cash(quantity, code) if inplace: self = new return new def to_cash(self, obj: Union[Cash, Position, float]) -> Cash: """ Given an ambiguous object which could be interpreted as a Cash position, converts that object to a Cash position in the context of the calling cash position and returns it. Parameters: obj: The object to be converted to a cash position Returns: The converted cash position """ if isinstance(obj, (int, float)): return self.from_number(obj) elif isinstance(obj, Cash): return self.from_cash(obj) elif isinstance(obj, Position): return self.from_position(obj) raise TypeError( f"obj type {obj.__class__.__name__} can not be converted to Cash" ) class Portfolio: """ An object representing a portfolio of financial assets AlphaGradient portfolios are designed to interact natively with AlphaGradient assets, and provide all of the functionality one would expect with a normal financial portfolio. Parameters: initial: The initial quantity of the base currency held by the Portfolio name: The name of this portfolio, used for indexing within environments base: The base currency of this portfolio Attributes: cash (float): How much of the base currency the Portfolio holds date (datetime): The last time this position was altered or valuated positions (dict): A dictionary of all of this Portfolio's current positions longs (dict): A dictionary of all long positions shorts (dict): A dictionary of all short positions base (str): A currency code representing this portfolio's base currency value (float): The total value of this portfolio, represented in the portfolio's base currency liquid (float): The sum of all of the portfolio's liquid assets """ def __init__( self, initial: float, name: Optional[Union[str, Environment]] = None, base: Optional[str] = None, ) -> None: if isinstance(name, types.environment.c): self.name = self._generate_name(environment=name) else: assert type(name) is str # Mypy doesnt recognize the type narrowing above self.name = self._generate_name() if name is None else name self._base = Currency.base if base is None else base self._cash = Cash(initial, self.base) self._positions: dict[str, Position] = {"CASH": self.cash} self.history = self._history() self.type.instances[self.name] = self # type: ignore[attr-defined] def __getattr__(self, attr: str) -> dict[str, Position]: if attr in [c.__name__.lower() for c in types.instantiable()]: return { k: v for k, v in self.positions.items() if v.asset.__class__.__name__.lower() == attr } raise AttributeError(f"Portfolio has no attribute {attr}") def __str__(self) -> str: return f"<AlphaGradient Portfolio at {hex(id(self))}>" def __repr__(self) -> str: return self.__str__() def _generate_name( self, last: list[int] = [0], environment: Environment = None ) -> str: """ Generates a name for this portfolio. Only used when an environment object is passed in for the 'name' parameter during Portfolio initialization Parameters: environment: The environment object to generate a portfolio name for Returns: A portfolio name appropriate for that environment """ if environment is None: if last[0] == 0 and not self.type.instances: # type: ignore[attr-defined] return "MAIN" else: name = f"P{last[0]}" last[0] += 1 return name else: if environment._portfolios: return f"P{len(environment._portfolios) - 1}" else: return "MAIN" @property def base(self) -> str: """This portfolio's base currency""" return self._base @base.setter def base(self, new_base: str) -> None: if Currency.validate_code(new_base, error=True): self._base = new_base @property def base_symbol(self) -> str: """The symbol corresponding to this portfolio's base currency""" return self._cash.symbol @property def cash(self) -> Cash: """This portfolio's currently held quantity of the base currency""" return self._cash @cash.setter def cash(self, n: float) -> None: if isinstance(n, Number): self._cash.quantity = n elif isinstance(n, Cash): self._cash = Cash.from_position(n) else: raise TypeError( "Cash can only be assigned to a numerical " "value or another cash instance." ) @property def date(self) -> datetime: """This Portfolio's current date""" return self._date # type: ignore[return-value] @property def liquid(self) -> float: """The total liquid value of the portfolio""" return self.cash.quantity @property def longs(self) -> dict[str, Position]: """A dictionary which associates all long positions with their asset keys""" return {v.asset.key: v for k, v in self.positions.items() if not v.short} @property def positions(self) -> dict[str, Position]: """The financial positions currency held by this portfolio""" self._positions["CASH"] = self._cash return self._positions @property def shorts(self) -> dict[str, Position]: """A dictionary which assocaites all short positions with their asset keys""" return {v.asset.key: v for k, v in self.positions.items() if v.short} @property def value(self) -> float: """This portfolio's net market value""" return sum([position.value for position in self.positions.values()]) def update_positions(self) -> None: """ Updates the Portfolios positions to removed those that have expired, after calling their expire methods. TODO: This should be a private method """ for expired in [pos for pos in self._positions.values() if pos.asset.expired]: expired.expire(self) self._positions = { k: pos for k, pos in self._positions.items() if not pos.expired } # THIS SHOULD BE DONE IN THE CASH SETTER self._positions["CASH"] = self.cash def validate_transaction( self, asset: Asset, quantity: float, short: bool = False ) -> bool: """ Validates a transaction by determining the this portfolio is capable of performing it. All transactions are validated before being performed. When the arguments passed to a transaction are invalid but not cause for alarm, simply returns False, which means that the algorithm runtime will continue without performing the transaction In some cases, the validation will trigger a runtime error for transaction inputs that should not be possible or are uninterpretable. Parameters: asset: The asset involved in the
import argparse from collections import defaultdict import torch from torch.utils.data import DataLoader from tqdm import tqdm from allennlp.data.vocabulary import Vocabulary from allennlp.data.samplers import BucketBatchSampler from allennlp.data.dataset import Batch # from allennlp.data.dataloader import DataLoader from allennlp.models import Model from allennlp.nn.util import move_to_device from allennlp.interpret.saliency_interpreters import SimpleGradient, IntegratedGradient,SmoothGradient from allennlp.predictors import Predictor from nltk.corpus import stopwords from allennlp_models.rc.transformer_qa import TransformerSquadReader,TransformerQA,TransformerQAPredictor import random import sys from facade.util.model_data_helpers import get_model, get_bert_model,load_model, get_sst_reader from facade.util.misc import compute_rank, get_stop_ids from combine_models import merge_models from random import sample import numpy as np FIRST_TOKEN_TARGET = "first_token" STOP_TOKEN_TARGET = "stop_token" def mean_reciprocal_rank(x, query: int): rank = compute_rank(x, {query})[0] return 1/(rank + 1) def track_distribution_overlap( gradient_interpreter_1, gradient_interpreter_2, dev_data, cuda: bool ): """ TODO """ dev_sampler = BucketBatchSampler(data_source=dev_data, batch_size=16, sorting_keys=["question_with_context"]) predictor_1 = gradient_interpreter_1.predictor predictor_2 = gradient_interpreter_2.predictor total_kl_div_model_1_model_2 = 0 total_kl_div_model_2_model_1 = 0 for batch_ids in dev_sampler: instances = [dev_data[id] for id in batch_ids] grads_1, grads_2 = get_gradients_from_instances( gradient_interpreter_1, gradient_interpreter_2, instances, cuda ) for grad_1, grad_2 in zip(grads_1, grads_2): # Compute KL Divergence kl_div_model_1_model_2 = torch.nn.functional.kl_div(grad_1.log(), grad_2, reduce='sum') total_kl_div_model_1_model_2 += kl_div_model_1_model_2 kl_div_model_2_model_1 = torch.nn.functional.kl_div(grad_2.log(), grad_1, reduce='sum') total_kl_div_model_2_model_1 += kl_div_model_2_model_1 avg_kl_div_model_1_model_2 = total_kl_div_model_1_model_2/len(dev_data) avg_kl_div_model_2_model_1 = total_kl_div_model_2_model_1/len(dev_data) return avg_kl_div_model_1_model_2, avg_kl_div_model_2_model_1 def track_stop_token_effectiveness( combined_gradient_interpreter, baseline_gradient_interpreter, dev_data, cuda: bool ): """ TODO """ stop_words = set(stopwords.words('english')) combined_model = combined_gradient_interpreter.predictor._model baseline_model = baseline_gradient_interpreter.predictor._model combined_model.get_metrics(reset=True) baseline_model.get_metrics(reset=True) metrics = defaultdict(dict) num_instance = len(dev_data) dev_sampler = BucketBatchSampler(data_source=dev_data, batch_size=3, sorting_keys=["question_with_context"]) total_reciprocal_rank_combined = 0 total_top1_combined = 0 total_grad_attribution_combined = 0 total_reciprocal_rank_baseline = 0 total_top1_baseline = 0 total_grad_attribution_baseline = 0 total_grad_baseline = 0 total_grad_combined =0 tcombined_correct = 0 tbase_correct = 0 for batch_ids in tqdm(dev_sampler): instances = [dev_data[id] for id in batch_ids] print(instances[0]) stop_ids = [] question_end = [] for instance in instances: stop_ids.append(get_stop_ids(instance, stop_words, namespace="question_with_context",mode="normal")) for j, token in enumerate(instance["question_with_context"]): if token.text == "[SEP]": question_end.append(j+1) break grads_combined,grads_baseline, acc_combined, acc_base = get_gradients_from_instances( combined_model, baseline_model, combined_gradient_interpreter, baseline_gradient_interpreter, instances, cuda ) # total_grad_baseline += sum([sum(x[:question_end[idx]]) for idx,x in enumerate(grads_baseline)]) # total_grad_combined += sum([sum(x[:question_end[idx]]) for idx,x in enumerate(grads_combined)]) total_grad_baseline += sum([sum(x) for idx,x in enumerate(grads_baseline)]) total_grad_combined += sum([sum(x) for idx,x in enumerate(grads_combined)]) print(total_grad_baseline) print(total_grad_combined) grad_batch_idx = 0 for grad_comb, grad_base in zip(grads_combined, grads_baseline): print("stop ids", stop_ids[grad_batch_idx]) if len(stop_ids[grad_batch_idx]) == 0: grad_batch_idx += 1 continue print("grad batch index", grad_batch_idx) combined_query_idx = -1 combined_query_max = -1 for i, grad in enumerate(grad_comb): if i in stop_ids[grad_batch_idx] and grad > combined_query_max: combined_query_idx = i combined_query_max = grad baseline_query_idx = -1 baseline_query_max = -1 for i, grad in enumerate(grad_base): if i in stop_ids[grad_batch_idx] and grad > baseline_query_max: baseline_query_idx = i baseline_query_max = grad # print(grad_comb,grad_base) print("combined query index", combined_query_idx) print("baseline query index", baseline_query_idx) combined_rank = compute_rank(grad_comb, {combined_query_idx})[0] baseline_rank = compute_rank(grad_base, {baseline_query_idx})[0] if combined_rank == 0: total_top1_combined += 1 if baseline_rank == 0: total_top1_baseline += 1 total_reciprocal_rank_combined += mean_reciprocal_rank(grad_comb, combined_query_idx) total_reciprocal_rank_baseline += mean_reciprocal_rank(grad_base, baseline_query_idx) print(grad_comb[stop_ids[grad_batch_idx]]) print(grad_base[stop_ids[grad_batch_idx]]) total_grad_attribution_combined += np.sum(grad_comb[stop_ids[grad_batch_idx]]) total_grad_attribution_baseline += np.sum(grad_base[stop_ids[grad_batch_idx]]) grad_batch_idx += 1 mean_reciprocal_rank_combined = total_reciprocal_rank_combined/len(dev_data) mean_reciprocal_rank_baseline = total_reciprocal_rank_baseline/len(dev_data) mean_top1_combined = total_top1_combined/len(dev_data) mean_top1_baseline = total_top1_baseline/len(dev_data) mean_grad_attribution_combined = total_grad_attribution_combined/len(dev_data) mean_grad_attribution_baseline = total_grad_attribution_baseline/len(dev_data) metrics['combined']['mean_reciprocal_rank'] = mean_reciprocal_rank_combined metrics['combined']['mean_top1'] = mean_top1_combined metrics['combined']['mean_grad_attribution'] = total_grad_attribution_combined/total_grad_combined metrics['baseline']['mean_reciprocal_rank'] = mean_reciprocal_rank_baseline metrics['baseline']['mean_top1'] = mean_top1_baseline metrics['baseline']['mean_grad_attribution'] = total_grad_attribution_baseline/total_grad_baseline return metrics def get_acc(combined_gradient_interpreter, baseline_gradient_interpreter, dev_data, cuda: bool): combined_model = combined_gradient_interpreter.predictor._model baseline_model = baseline_gradient_interpreter.predictor._model combined_model.get_metrics(reset=True) # combined_model.module.get_metrics(reset=True) baseline_model.get_metrics(reset=True) metrics = defaultdict(dict) num_instance = len(dev_data) dev_sampler = BucketBatchSampler(data_source=dev_data, batch_size=2, sorting_keys=["question_with_context"]) n_indx = 0 combined_correct = 0 base_correct = 0 for batch_ids in dev_sampler: instances = [dev_data[id] for id in batch_ids] batch = Batch(instances) model_input = batch.as_tensor_dict() model_input = move_to_device(model_input, cuda_device=0) if cuda else model_input model_1_outputs = combined_model(**model_input) model_2_outputs = baseline_model(**model_input) combined_metrics = combined_model.get_metrics() baseline_metrics = baseline_model.get_metrics() return combined_metrics,baseline_metrics def track_first_token_effectiveness( combined_gradient_interpreter, baseline_gradient_interpreter, dev_data, cuda: bool ): """ TODO """ combined_model = combined_gradient_interpreter.predictor._model baseline_model = baseline_gradient_interpreter.predictor._model # combined_model.get_metrics(reset=True) # # combined_model.module.get_metrics(reset=True) # baseline_model.get_metrics(reset=True) metrics = defaultdict(dict) num_instance = len(dev_data) dev_sampler = BucketBatchSampler(data_source=dev_data, batch_size=6, sorting_keys=["question_with_context"]) total_reciprocal_rank_combined = 0 total_top1_combined = 0 total_grad_attribution_combined = 0 total_reciprocal_rank_baseline = 0 total_top1_baseline = 0 total_grad_attribution_baseline = 0 n_indx = 0 for batch_ids in tqdm(dev_sampler): print(n_indx," batch ids:",batch_ids) # print(torch.cuda.memory_summary(device=0, abbreviated=True)) instances = [dev_data[id] for id in batch_ids] grads_combined, grads_baseline, acc_combined, acc_base = get_gradients_from_instances( combined_model, baseline_model, combined_gradient_interpreter, baseline_gradient_interpreter, instances, cuda ) for grad_comb, grad_base in zip(grads_combined, grads_baseline): combined_rank = compute_rank(grad_comb, {1})[0] baseline_rank = compute_rank(grad_base, {1})[0] if combined_rank == 0: total_top1_combined += 1 if baseline_rank == 0: total_top1_baseline += 1 total_reciprocal_rank_combined += mean_reciprocal_rank(grad_comb, 1) total_reciprocal_rank_baseline += mean_reciprocal_rank(grad_base, 1) total_grad_attribution_combined += grad_comb[1] total_grad_attribution_baseline += grad_base[1] n_indx += 1 mean_reciprocal_rank_combined = total_reciprocal_rank_combined/len(dev_data) mean_reciprocal_rank_baseline = total_reciprocal_rank_baseline/len(dev_data) mean_top1_combined = total_top1_combined/len(dev_data) mean_top1_baseline = total_top1_baseline/len(dev_data) mean_grad_attribution_combined = total_grad_attribution_combined/len(dev_data) mean_grad_attribution_baseline = total_grad_attribution_baseline/len(dev_data) print(n_indx) metrics['combined']['mean_reciprocal_rank'] = mean_reciprocal_rank_combined metrics['combined']['mean_top1'] = mean_top1_combined metrics['combined']['mean_grad_attribution'] = mean_grad_attribution_combined metrics['baseline']['mean_reciprocal_rank'] = mean_reciprocal_rank_baseline metrics['baseline']['mean_top1'] = mean_top1_baseline metrics['baseline']['mean_grad_attribution'] = mean_grad_attribution_baseline print(metrics) return metrics def get_gradients_from_instances( combined_model, baseline_model, gradient_interpreter_1, gradient_interpreter_2, instances, cuda ): """ TODO """ # combined_model.get_metrics(True) # baseline_model.get_metrics(True) batch = Batch(instances) model_input = batch.as_tensor_dict() model_input = move_to_device(model_input, cuda_device=0) if cuda else model_input predictor_1 = gradient_interpreter_1.predictor predictor_2 = gradient_interpreter_2.predictor acc_combined = 0 acc_base = 0 print(model_input["question_with_context"]["tokens"]["token_ids"].shape) with torch.no_grad(): model_1_outputs = combined_model(**model_input) model_2_outputs = baseline_model(**model_input) new_instances_1 = [] for instance, output in zip(instances , model_1_outputs["best_span"]): new_instances_1.append(predictor_1.predictions_to_labeled_instances(instance, output)[0]) new_instances_2 = [] for instance, output in zip(instances , model_2_outputs["best_span"]): new_instances_2.append(predictor_2.predictions_to_labeled_instances(instance, output)[0]) grads_1 = [0]*len(new_instances_2) grads_2 = None grads_1, _ = gradient_interpreter_1.sst_interpret_from_instances( labeled_instances=new_instances_1, embedding_op="dot", normalization="l1", normalization2="l1", cuda=cuda ) grads_2, _ = gradient_interpreter_2.sst_interpret_from_instances( labeled_instances=new_instances_2, embedding_op="dot", normalization="l1", normalization2="l1", cuda=cuda ) return grads_1, grads_2,acc_combined,acc_base def record_metrics(metrics, args): """ Record the metrics recorded in the metrics dictionary to a metrics file """ with open('interpretation_metrics/model_metrics_{}'.format(args.file_num), 'a') as f: f.write("META DATA\n") f.write("---------\n") f.write("Model Name: {}\n".format(args.model_name)) f.write("Attack Target: {}\n".format(args.attack_target)) f.write("Gradient Model File: {}\n".format(args.gradient_model_file)) f.write("Predictive Model File: {}\n".format(args.predictive_model_file)) f.write("Cuda: {}\n".format(args.cuda)) f.write("\nSIMPLE GRADIENT COMBINED MODEL METRICS\n") f.write("----------------------------------------\n") for key, val in metrics['simple_gradient_combined'].items(): f.write("{}: {:.3f}\n".format(key, val)) f.write("\nSIMPLE GRADIENT BASELINE MODEL METRICS\n") f.write("----------------------------------------\n") for key, val in metrics['simple_gradient_baseline'].items(): f.write("{}: {:.3f}\n".format(key, val)) f.write("\nSMOOTH GRADIENT COMBINED MODEL METRICS\n") f.write("----------------------------------------\n") for key, val in metrics['smooth_gradient_combined'].items(): f.write("{}: {:.3f}\n".format(key, val)) f.write("\nSMOOTH GRADIENT BASELINE MODEL METRICS\n") f.write("----------------------------------------\n") for key, val in metrics['smooth_gradient_baseline'].items(): f.write("{}: {:.3f}\n".format(key, val)) f.write("\nINTEGRATED GRADIENT COMBINED MODEL METRICS\n") f.write("--------------------------------------------\n") for key, val in metrics['integr_gradient_combined'].items(): f.write("{}: {:.3f}\n".format(key, val)) f.write("\nINTEGRATED GRADIENT BASELINE MODEL METRICS\n") f.write("--------------------------------------------\n") for key, val in metrics['integr_gradient_baseline'].items(): f.write("{}: {:.3f}\n".format(key, val)) def main(): args = argument_parsing() vocab = Vocabulary.from_files(args.vocab_folder) # print(vocab._token_to_index["tags"]) model_name = "bert-base-cased" reader = TransformerSquadReader(transformer_model_name= model_name) dev_data = reader.read('squad-dev-v1.1.json') # dev_data = reader.read('dev.json') # print(len(dev_data)) # random.seed(2) # sample_instances = sample(dev_data.instances, 100) # dev_data.instances = sample_instances # print(dev_data[0]) # exit(0) dev_data.index_with(vocab) # print(len(dev_data)) # gradient_model = get_model(args.model_name, vocab, args.cuda,256) gradient_model = TransformerQA(vocab=vocab,transformer_model_name= model_name, hidden_size = 256).cuda() print(gradient_model._text_field_embedder._token_embedders["tokens"].transformer_model.embeddings.word_embeddings.weight.size()) predictive_model = TransformerQA(vocab=vocab,transformer_model_name= model_name, hidden_size = 768).cuda() print(predictive_model._text_field_embedder._token_embedders["tokens"].transformer_model.embeddings.word_embeddings.weight.size()) load_model(gradient_model, args.gradient_model_file, task="rc") load_model(predictive_model, args.predictive_model_file) # gradient_model = gradient_model.module combined_model = merge_models(gradient_model,predictive_model,task="rc") combined_model.eval() # print("aa") # print(combined_model._text_field_embedder._token_embedders["tokens"].transformer_model.embeddings.word_embeddings.weight.size()) # print(combined_model._text_field_embedder._token_embedders["tokens"].transformer_model) # print(combined_model._linear_layer) # predictive_predictor = Predictor.by_name('text_classifier')(predictive_model, reader) # predictive_model = gradient_model predictive_predictor = TransformerQAPredictor(predictive_model,reader) # combined_predictor = Predictor.by_name('text_classifier')(combined_model, reader) combined_predictor = TransformerQAPredictor(combined_model,reader) predictive_simple_gradient_interpreter = SimpleGradient(predictive_predictor) predictive_smooth_gradient_interpreter = SmoothGradient(predictive_predictor) predictive_integr_gradient_interpreter = IntegratedGradient(predictive_predictor) combined_simple_gradient_interpreter = SimpleGradient(combined_predictor) combined_smooth_gradient_interpreter = SmoothGradient(combined_predictor) combined_integr_gradient_interpreter = IntegratedGradient(combined_predictor) metrics = defaultdict(dict) if args.attack_target == FIRST_TOKEN_TARGET: effective_metrics = track_first_token_effectiveness( combined_simple_gradient_interpreter, predictive_simple_gradient_interpreter, dev_data, args.cuda ) data_metrics_combined, data_metrics_baseline = get_acc(combined_simple_gradient_interpreter, predictive_simple_gradient_interpreter, dev_data, args.cuda ) metrics['simple_gradient_combined']['mean_reciprocal_rank'] = effective_metrics['combined']['mean_reciprocal_rank'] metrics['simple_gradient_combined']['mean_top1'] = effective_metrics['combined']['mean_top1'] metrics['simple_gradient_combined']['mean_grad_attribution'] = effective_metrics['combined']['mean_grad_attribution'] for name in data_metrics_combined.keys(): metrics['simple_gradient_combined'][name] = data_metrics_combined[name] metrics['simple_gradient_baseline']['mean_reciprocal_rank'] = effective_metrics['baseline']['mean_reciprocal_rank'] metrics['simple_gradient_baseline']['mean_top1'] = effective_metrics['baseline']['mean_top1'] metrics['simple_gradient_baseline']['mean_grad_attribution'] = effective_metrics['baseline']['mean_grad_attribution'] for name in data_metrics_baseline.keys(): metrics['simple_gradient_baseline'][name] = data_metrics_baseline[name] effective_metrics = track_first_token_effectiveness( combined_smooth_gradient_interpreter, predictive_smooth_gradient_interpreter, dev_data, args.cuda ) metrics['smooth_gradient_combined']['mean_reciprocal_rank'] = effective_metrics['combined']['mean_reciprocal_rank'] metrics['smooth_gradient_combined']['mean_top1'] = effective_metrics['combined']['mean_top1'] metrics['smooth_gradient_combined']['mean_grad_attribution'] = effective_metrics['combined']['mean_grad_attribution'] metrics['smooth_gradient_baseline']['mean_reciprocal_rank'] = effective_metrics['baseline']['mean_reciprocal_rank'] metrics['smooth_gradient_baseline']['mean_top1'] = effective_metrics['baseline']['mean_top1'] metrics['smooth_gradient_baseline']['mean_grad_attribution'] = effective_metrics['baseline']['mean_grad_attribution'] effective_metrics = track_first_token_effectiveness( combined_integr_gradient_interpreter, predictive_integr_gradient_interpreter, dev_data, args.cuda ) metrics['integr_gradient_combined']['mean_reciprocal_rank'] = effective_metrics['combined']['mean_reciprocal_rank'] metrics['integr_gradient_combined']['mean_top1'] = effective_metrics['combined']['mean_top1'] metrics['integr_gradient_combined']['mean_grad_attribution'] = effective_metrics['combined']['mean_grad_attribution'] metrics['integr_gradient_baseline']['mean_reciprocal_rank'] = effective_metrics['baseline']['mean_reciprocal_rank'] metrics['integr_gradient_baseline']['mean_top1'] = effective_metrics['baseline']['mean_top1'] metrics['integr_gradient_baseline']['mean_grad_attribution'] = effective_metrics['baseline']['mean_grad_attribution'] elif args.attack_target == STOP_TOKEN_TARGET: effective_metrics = track_stop_token_effectiveness( combined_simple_gradient_interpreter, predictive_simple_gradient_interpreter, dev_data, args.cuda ) data_metrics_combined, data_metrics_baseline = get_acc(combined_simple_gradient_interpreter, predictive_simple_gradient_interpreter, dev_data, args.cuda ) metrics['simple_gradient_combined']['mean_reciprocal_rank'] = effective_metrics['combined']['mean_reciprocal_rank'] metrics['simple_gradient_combined']['mean_top1'] = effective_metrics['combined']['mean_top1'] metrics['simple_gradient_combined']['mean_grad_attribution'] = effective_metrics['combined']['mean_grad_attribution'] for name in data_metrics_combined.keys(): metrics['simple_gradient_combined'][name] = data_metrics_combined[name] metrics['simple_gradient_baseline']['mean_reciprocal_rank'] = effective_metrics['baseline']['mean_reciprocal_rank'] metrics['simple_gradient_baseline']['mean_top1'] = effective_metrics['baseline']['mean_top1'] metrics['simple_gradient_baseline']['mean_grad_attribution'] = effective_metrics['baseline']['mean_grad_attribution'] for name in data_metrics_baseline.keys(): metrics['simple_gradient_baseline'][name] = data_metrics_baseline[name] effective_metrics = track_stop_token_effectiveness( combined_smooth_gradient_interpreter, predictive_smooth_gradient_interpreter, dev_data, args.cuda ) metrics['smooth_gradient_combined']['mean_reciprocal_rank'] = effective_metrics['combined']['mean_reciprocal_rank'] metrics['smooth_gradient_combined']['mean_top1'] = effective_metrics['combined']['mean_top1'] metrics['smooth_gradient_combined']['mean_grad_attribution'] = effective_metrics['combined']['mean_grad_attribution'] metrics['smooth_gradient_baseline']['mean_reciprocal_rank'] = effective_metrics['baseline']['mean_reciprocal_rank'] metrics['smooth_gradient_baseline']['mean_top1'] = effective_metrics['baseline']['mean_top1'] metrics['smooth_gradient_baseline']['mean_grad_attribution'] = effective_metrics['baseline']['mean_grad_attribution']
#!/usr/bin/env python -W ignore from absl import flags from absl import app import pandas as pd import numpy as np import sys from sodapy import Socrata from os.path import abspath from os.path import exists from os import mkdir FLAGS = flags.FLAGS # delcare flags flags.DEFINE_string("token", None, "SPARCS Socrates API token") flags.DEFINE_string("output", None, "Output directory to save files") # required flags flags.mark_flag_as_required("token") flags.mark_flag_as_required("output") apr_drg_codes = map(str, []) ccs_diag_codes = map(str, []) ccs_proc_codes = map(str, []) columns_to_keep = map(lambda x: x.lower().replace(' ', '_'), [ "APR Risk of Mortality", "APR Severity of Illness Code", "Age Group", "CCS Diagnosis Code", "Discharge Year", "Ethnicity", "Gender", "Length of Stay", "Patient Disposition", "Source of Payment 1", "Race", "Total Costs", "Total Costs_inflation_adjusted", "Type of Admission", 'apr_drg_code' ]) pd_list = [] # for Hospital Inpatient Discharges (SPARCS De-Identified) in SPARCS dataset_ids = [ (2016, 'y93g-4rqn'), (2015, 'p3tf-wrj8'), (2014, 'pzzw-8zdv'), (2013, 'tdf6-7fpk'), (2012, 'rv8x-4fm3'), (2011, 'n5y9-zanf'), (2010, 'dpew-wqcg'), (2009, 's8d9-z734') ] def additional_cleaning(df): # do NOT clean age group for this paper # if "age_group" in df.columns: # df1 = df[df.age_group == "70 or Older"] # df2 = df[df.age_group == "50 to 69"] # df = pd.concat([df1,df2],ignore_index=True, axis=0, sort=False) # do NOT clean admission for this paper # if "type_of_admission" in df.columns: # df = df[df.type_of_admission != 'Newborn'] # df = df[df.type_of_admission != 'Not Available'] # DO clean out dispositions # if "patient_disposition" in df.columns: # df = df[df.patient_disposition != "Left Against Medical Advice"] # df = df[df.patient_disposition != "Expired"] # df = df[df.patient_disposition != "Another Type Not Listed"] return df ''' Download all the datasets in dataset_ids and return a list of pd dataframes ''' def download(token, verbose=True): if not isinstance(token, basestring): raise ValueError("Token must be a string") # Setup SPARCS API client = Socrata("health.data.ny.gov", token) # set an arbitrarily high download limit # only works for python 2 if sys.version_info < (3,0): lim = sys.maxint else: # hardcode max int for python 3 lim = 9223372036854775807 for id in dataset_ids: year = id[0] socrata_id = id[1] filter_command = '' # has apr_drg_description_and_code if year == 2011: filter_command = make_filter_command_by_year(year = 2011, ccs_diag = ccs_diag_codes, ccs_proc = ccs_proc_codes, apr_drg = apr_drg_codes) # apr_drg_code are integers elif year == 2015 or year == 2016: # years 2015 and 2016 are the same, so it doesn't matter which is passed into make_filter_command_by_year filter_command = make_filter_command_by_year(year = 2015, ccs_diag = ccs_diag_codes, ccs_proc = ccs_proc_codes, apr_drg = apr_drg_codes) else: # year only matters if 2011, 2015, or 2016. Don't pass to force default behavior filter_command = make_filter_command_by_year(ccs_diag = ccs_diag_codes, ccs_proc = ccs_proc_codes, apr_drg = apr_drg_codes) print "Filter: %s" % str(filter_command) if verbose: sys.stdout.write('Downloading id: %s (%d) using filter...' % (socrata_id, year)) sys.stdout.flush() http_get = client.get(socrata_id, limit=lim, where=filter_command) results_df = pd.DataFrame.from_records(http_get) if verbose: print 'Shape = {}'.format(results_df.shape) pd_list.append(results_df) return pd_list def make_filter_command_by_year(year = 0, ccs_diag = None, ccs_proc = None, apr_drg = None): # SPARCS API format call changes by year command_filter = [] if year == 2011: # correct format # """ccs_diagnosis_code='{ccs_diagnosis_code}' AND \ # ccs_procedure_code='{ccs_procedure_code}' AND \ # apr_drg_description_and_code='{apr_drg_code}'""" if ccs_diag != None and len(ccs_diag) >= 1: ccs_diag_codes = '('+' OR '.join(["ccs_diagnosis_code='%s'"%x for x in ccs_diag])+')' command_filter.append(ccs_diag_codes) if ccs_proc != None and len(ccs_proc) >= 1: ccs_proc_codes = '('+' OR '.join(["ccs_procedure_code='%s'"%x for x in ccs_proc])+')' command_filter.append(ccs_proc_codes) if apr_drg != None and len(apr_drg) >= 1: apr_drg_codes = '('+' OR '.join(["apr_drg_description_and_code='%s'"%x for x in apr_drg])+')' command_filter.append(apr_drg_codes) return ' AND '.join(command_filter) # ccs_diagnosis_code, ccs_procedure_code, apr_drg_code are integers (not quoted) elif year == 2015 or year == 2016: # Correct format # """ccs_diagnosis_code={ccs_diagnosis_code} AND \ # ccs_procedure_code={ccs_procedure_code} AND \ # apr_drg_code={apr_drg_code}""" if ccs_diag != None and len(ccs_diag) >= 1: ccs_diag_codes = '('+' OR '.join(["ccs_diagnosis_code=%s"%x for x in ccs_diag])+')' command_filter.append(ccs_diag_codes) if ccs_proc != None and len(ccs_proc) >= 1: ccs_proc_codes = '('+' OR '.join(["ccs_procedure_code=%s"%x for x in ccs_proc])+')' command_filter.append(ccs_proc_codes) if apr_drg != None and len(apr_drg) >= 1: apr_drg_codes = '('+' OR '.join(["apr_drg_code=%s"%x for x in apr_drg])+')' command_filter.append(apr_drg_codes) return ' AND '.join(command_filter) else: # Correct format # """ccs_diagnosis_code='{ccs_diagnosis_code}' AND \ # ccs_procedure_code='{ccs_procedure_code}' AND \ # apr_drg_code='{apr_drg_code}'""" if ccs_diag != None and len(ccs_diag) >= 1: ccs_diag_codes = '('+' OR '.join(["ccs_diagnosis_code='%s'"%x for x in ccs_diag])+')' command_filter.append(ccs_diag_codes) if ccs_proc != None and len(ccs_proc) >= 1: ccs_proc_codes = '('+' OR '.join(["ccs_procedure_code='%s'"%x for x in ccs_proc])+')' command_filter.append(ccs_proc_codes) if apr_drg != None and len(apr_drg) >= 1: apr_drg_codes = '('+' OR '.join(["apr_drg_code='%s'"%x for x in apr_drg])+')' command_filter.append(apr_drg_codes) return ' AND '.join(command_filter) ''' Standardize column names across all datasets ''' def standardizeColumns(list_of_dfs): df_list = [] for df in list_of_dfs: colHeader = df.columns.values for index,val in enumerate(colHeader): ################ # Rename medicare #2011 has a mislabeled column header, replace with correct if val == "payment_topology_2": df.columns.values[index] = "payment_typology_2" # replace typology with source of payment if val == "payment_typology_1": df.columns.values[index] = "source_of_payment_1" elif val == "payment_typology_2": df.columns.values[index] = "source_of_payment_2" elif val == "payment_typology_3": df.columns.values[index] = "source_of_payment_3" ################## # Rename apr_severity_of_illness_descript if val == 'apr_severity_of_illness_descript': df.columns.values[index] = 'apr_severity_of_illness_description' if val == 'apr_drg_description_and_code': df.columns.values[index] = 'apr_drg_code' if val == 'age': df.columns.values[index] = 'age_group' if val == 'apr_severity_of_illness': df.columns.values[index] = 'apr_severity_of_illness_code' if val == 'sex': df.columns.values[index] = 'gender' if val == 'operating_provider_license_numbe': df.columns.values[index] = 'operating_provider_license_number' if val == 'attending_provider_license_numbe': df.columns.values[index] = 'attending_provider_license_number' df_list.append(df) return df_list ''' Corrects the headers and filter out patients who do not use medicare NB: This MUST be called before the header spaces are replaced by _ ^ Is not an issue if downloading from socrata since cols already have _ ''' def codeMedicare(df): medicare_bool = [] for ndx, row in df.iterrows(): _1 = row['source_of_payment_1'].lower() == 'medicare' try: _2 = row['source_of_payment_2'].lower() == 'medicare' except: _2 = False try: _3 = row['source_of_payment_3'].lower() == 'medicare' except: _3 = False bool = _1 | _2 | _3 medicare_bool.append(bool) df['medicare'] = medicare_bool return df def subsetMedicare(df): return df[df['medicare'] == True] def assignNumeric(df): _TC = 'total_costs' _TCh = 'total_charges' _LOS = 'length_of_stay' _YEAR = 'discharge_year' # remove non-integer rows from LOS if df.dtypes[_LOS] == 'object': df = df[df[_LOS] != "120 +"] df[[_TC, _TCh, _LOS, _YEAR]] = df[[_TC, _TCh, _LOS, _YEAR]].apply(pd.to_numeric) return df """ Combines all dataframes into one master """ def combine_dataframes(pd_list): master = pd.concat(pd_list, ignore_index = True, axis=0, sort=False) master = master.fillna(0) return master def adjustForInflation(df, column_input): # multiply cost in year by the multiplicative CPI rate according to the BLS # From: https://beta.bls.gov/dataViewer/view/timeseries/CUUR0000SAM # CPI-All Urban Consumers (Current Series) # Series Title : Medical care in U.S. city average, all urban consumers, not seasonally adjusted # Series ID : CUUR0000SAM # Seasonality : Not Seasonally Adjusted # Survey Name : CPI-All Urban Consumers (Current Series) # Measure Data Type : Medical care # Area : U.S. city average # Item : Medical care inflationDictionary = { "2016":0.810, "2015":0.841, "2014":0.863, "2013":0.884, "2012":0.905, "2011":0.938, "2010":0.967, "2009":1.00 } inflationList = [float(row[column_input])*inflationDictionary[str(row['discharge_year'])] for index,row in df.iterrows()] df[column_input + '_inflation_adjusted'] = inflationList return df ''' Remove outliers from dataset by keeping drop_lower %ile to drop_upper%ile ''' def removeOutliers(df, drop_lower=0.5, drop_upper=99.5): _TC = 'total_costs_inflation_adjusted' # convert all outcome rows to numerical if possible df[[_TC]] = df[[_TC]].apply(pd.to_numeric) #remove outliers # drop rows below 0.5th percentile and above 99.5th percentile TC_ulimit = np.percentile([float(x) for x in df[_TC]], drop_upper) TC_llimit = np.percentile([float(x) for x in df[_TC]], drop_lower) # LOS_ulimit = np.percentile([int(x) for x in df[_LOS]], drop_upper) # LOS_llimit = np.percentile([int(x) for x in df[_LOS]], drop_lower) print 'Upper limit: %s, lower limit: %s' % (TC_ulimit, TC_llimit) df = df.query('{} < {}'.format(_TC, TC_ulimit)) df = df.query('{} > {}'.format(_TC, TC_llimit)) # df = df.query('{} < {}'.format(_LOS, LOS_ulimit)) # df = df.query('{} > {}'.format(_LOS, LOS_llimit)) return df def load_all_patients(output_dir): df = pd.read_csv('%s/%s' % (output_dir, 'all_patients.csv')) return df def main(argv): output_dir = abspath(FLAGS.output) if not exists(output_dir): sys.out.write('[INFO] Making directory: %s' % output_dir) mkdir(output_dir) pd_list = download(FLAGS.token) pd_list = standardizeColumns(pd_list) for i in range(len(pd_list)): print 'Saving %s...' % (dataset_ids[i][0]) name = 'raw_%s.csv' % dataset_ids[i][0] pd_list[i].to_csv('%s/%s' % (output_dir, name), index=False) print 'Downloaded and saved dataframes: %s. Running combine_dataframes()... ' % sum(x.shape[0] for x in pd_list) all_patients = combine_dataframes(pd_list) print 'Combined dataframes: %s. Running codeMedicare()... ' % sum(x.shape[0] for x in pd_list) all_patients = codeMedicare(all_patients) print 'Coded medicare: %s. Running adjustForInflation()... ' % all_patients.shape[0] all_patients = adjustForInflation(all_patients, 'total_costs') all_patients = adjustForInflation(all_patients, 'total_charges') print 'Adjusted for inflation: %s. Running assignNumeric()...' % all_patients.shape[0] all_patients = assignNumeric(all_patients) print 'Keeping %s' %
<reponame>danielesgit/slingen #!/usr/bin/python ''' Created on Apr 11, 2012 @author: danieles ''' import random import os import subprocess import shlex import time import itertools import traceback from datetime import datetime, date from copy import copy, deepcopy from src.dsls.processing import trackTiling from src.dsls.ll import parseLL # from src.rules.llrules import AtlasRuleSet_NuWay_HSquareTileForReg # from src.rules.lrms import HOfflineLRM, HSimpleLRM # # from src.generator import StructuresGenerator, CodeGenerator from src.compiler import Compiler, openLog, closeLog, printToLog, send_email_with_log from src.libtest import LibraryCode # from src.unparser import Unparser # # from src.isas.isabase import ISAManager # from src.isas.avx import AVX # from src.isas.sse4_1 import SSE4_1 # from src.isas.ssse3 import SSSE3 # from src.isas.sse3 import SSE3 # from src.isas.sse2 import SSE2 # from src.isas.sse import SSE # from src.isas.x86 import x86 # from src.isas.armv7 import ARMv7 # from src.isas.neon import NEON def procOutcome(resMgr, compiler, opts, pad="", sizeParams=None): params = opts['static_params'] if sizeParams is None else sizeParams openLog(opts) validated = True if opts['validate']: if all(compiler.validateList): if not 'libname' in opts: printToLog(pad + str(compiler.llprog) + " : " + "VALIDATED." + "\n\n", opts, openf=False, closef=False) else: printToLog(pad + opts.get('libname', "<Libname???>") + " : " + "VALIDATED." + "\n\n", opts, openf=False, closef=False) print "* Test passed" # if the test hadn't passed, an exception would have already been raised else: validated = False if not 'libname' in opts: printToLog(pad + str(compiler.llprog) + " : " + "FAILED " + str(compiler.validateList.count(False)) + "/" + str(len(compiler.validateList))+ " VALIDATIONS." + "\n", opts, openf=False, closef=False) else: printToLog(pad + opts.get('libname', "<Libname???>") + " : " + "FAILED " + str(compiler.validateList.count(False)) + "/" + str(len(compiler.validateList))+ " VALIDATIONS." + "\n", opts, openf=False, closef=False) print "* Test not passed: " + str(compiler.validateList.count(False)) + "/" + str(len(compiler.validateList)) if opts.get('test', True): if validated: bestout = compiler.outcome[0] print "\n$$$$$$$$$$$$$$$$$$$$$$$$$$$$ Best computation $$$$$$$$$$$$$$$$$$$$$$$$$$$$\n" # print "Tested expression: " + str(bestout[0]) + "\nPerformance: " + str(bestout[1][0]) + " f/c\n" print "Performance: " + str(bestout[1][0]) + " f/c\n" print "$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n" msg = pad for p in params: msg += str(p) + ', ' printToLog(msg + str(bestout[0]) + ", " + str(bestout[1][0]) + " f/c -- folder: " + opts['compileroot']+'/'+opts['compilename'] + "\n\n", opts, openf=False, closef=False) size = str(params[0]) for p in params[1:]: size += ','+str(p) if len(params) > 1: size = '[' + size + ']' # if not 'libname' in opts: # printTracking(bestout[0], size, opts) # Add track-tiling (tt) attribute to desired matrices (see mmm tester) curve_name = opts['legendname'] if 'legendname' in opts else "" resMgr.addCurve(opts['testname'], size, bestout[1][1:], basefolder=opts['logroot']+'/results', curve_name=curve_name, curve_marker=opts['marker'], curve_color=opts['color'], curve_lw=opts['lw'], rank_by_variants=deepcopy(compiler.rank_by_variants)) else: print "Some tests failed: Performance report aborted.\n\n" closeLog(opts) if opts.get('copycompfolder', True): compfolder = opts['compileroot'] + '/' + opts['compilename'] dstfolder = opts['logroot'] + '/results/' + opts['testname'] + '/compfolder' print "Copying compilation folder: " + compfolder + "\n\n" if not os.path.exists(dstfolder): args = shlex.split("mkdir -p " + dstfolder) subprocess.call(args) if os.path.exists(compfolder): args = shlex.split("cp -r " + compfolder + " " + dstfolder) subprocess.call(args) def printTracking(llprog, size, opts): """ Deprecated. """ for s,eqn in zip(llprog.stmtList, range(len(llprog.stmtList))): ttDict = {} trackTiling(s.eq, ttDict) for d, tLists in ttDict.items(): for i, tl in zip(range(len(tLists)), tLists): trackfname = opts['logroot'] + '/results/' + opts['testname'] + '/' +"eq" + str(eqn) + d + (str(i) if i > 0 else '') + '.csv' trackfile = open(trackfname, 'a') rec = size + ',' + str(tl[0]) for tc in tl[1:]: rec += ',' + str(tc) rec += '\n' trackfile.write( rec ) trackfile.close() def recordTime(time, opts): logfullname = opts['logroot'] + '/results/' + opts['testname'] + '/time.txt' logfile = open(logfullname, 'a') msg = str(time) + "\n" logfile.write( msg ) logfile.close() def prepareMake(opts): ''' Prepare the local filesystem for the upcoming experiment. Copy the necessary static files (e.g. helper files, Makefile) and create the necessary folders for compilation and logging. ''' if 'libname' in opts or not 'onlygen' in opts or not opts['onlygen']: copy = "cp" mkdir = "mkdir -p" # mv = "mv" basefiles = opts['basefiles'] + [ opts['makefile'] ] if 'libname' in opts or not opts.get('gentester', True): basefiles.append("testers/" + opts['hfilebasename'] + "_tester.h") platform = opts.get('platform', opts['arch'].__name__) basefiles.append('tsc/tsc_%s.cpp' % platform) origindir = opts['testroot'] + "/" origin = " ".join( [ origindir+f for f in basefiles ] + opts.get('additionals', []) ) destination = opts['compileroot'] + '/' + opts['compilename'] if not os.path.exists(destination): args = shlex.split(mkdir + " " + destination) subprocess.call(args) if not 'libname' in opts and not os.path.exists(destination + "/kernels"): args = shlex.split(mkdir + " " + destination + "/kernels") subprocess.call(args) args = shlex.split(copy + " " + origin + " " + destination) subprocess.call(args) # If tester has specialized sizes copy them to compileroot origin = origindir+"testers/" + opts['hfilebasename'] + "_tester" if ('libname' in opts or not opts.get('gentester', True)) and os.path.exists(origin): args = shlex.split(copy + " -r " + origin + " " + destination + "/kernels") subprocess.call(args) folder = opts['logroot'] + '/plots' if not os.path.exists(folder): args = shlex.split(mkdir + " " + folder) subprocess.call(args) folder = opts['logroot'] + '/results/' + opts['testname'] if not os.path.exists(folder): args = shlex.split(mkdir + " " + folder) subprocess.call(args) if opts.get('dumptex', False): subfolder = folder + '/tex' args = shlex.split(mkdir + " " + subfolder) subprocess.call(args) if opts.get('erm', False) or opts.get('runwitherm', False): subfolder = folder + '/erm' if not os.path.exists(subfolder): args = shlex.split(mkdir + " " + subfolder) subprocess.call(args) if opts.get('copyallkernels', False): subfolder = folder + '/genkernels' if not os.path.exists(subfolder): args = shlex.split(mkdir + " " + subfolder) subprocess.call(args) # def mmupdate(M, K, N, opts): # A = Matrix("A", scalar, (M,K)) # B = Matrix("B", scalar, (K,N)) # C = Matrix("C", scalar, (M,N), attr={'o':True, 'i':False}) # # expr = Assign(C, A*B+C) # # return expr # # def mmm(M, K, N, opts): # # A = Matrix("A", scalar, (M,K), attr={'tt':True}) # # B = Matrix("B", scalar, (K,N), attr={'tt':True}) # A = Matrix("A", scalar, (M,K)) # B = Matrix("B", scalar, (K,N)) # C = Matrix("C", scalar, (M,N), attr={'o':True, 'i':False}) # # # nu = 1 if not opts['vectorize'] else opts['nu'] # # expr = Assign(C, A*B) # # return expr # # def gemm(M, K, N, opts): # a = Matrix("a", scalar, (1,1)) # A = Matrix("A", scalar, (M,K), attr={'tt':True}) # B = Matrix("B", scalar, (K,N), attr={'tt':True}) # b = Matrix("b", scalar, (1,1)) # C = Matrix("C", scalar, (M,N), attr={'o':True, 'i':False}) # # # nu = 1 if not opts['vectorize'] else opts['nu'] # # expr = Assign(Tile(nu,C), Tile(nu,a)*Tile(nu,A)*Tile(nu,B)+Tile(nu,b)*Tile(nu,C)) # expr = Assign(C, a*(A*B)+b*C) # # return expr # # def gemam(M, K, N, opts): # a = Matrix("a", scalar, (1,1)) # A0 = Matrix("A0", scalar, (K,M)) # A1 = Matrix("A1", scalar, (K,M)) # B = Matrix("B", scalar, (K,N)) # b = Matrix("b", scalar, (1,1)) # C = Matrix("C", scalar, (M,N), attr={'o':True, 'i':False}) # # # nu = 1 if not opts['vectorize'] else opts['nu'] # # expr = Assign(Tile(nu,C), Tile(nu,a)*Tile(nu,A)*Tile(nu,B)+Tile(nu,b)*Tile(nu,C)) # expr = Assign(C, a*(T(A0+A1)*B)+b*C) # # return expr def testing1to3Param(resMgr, p0, f0, f1, f2, opts): sizesP0 = range(p0[0], p0[1]+1) if len(p0) == 2 else range(p0[0], p0[1]+1, p0[2]) sizes = [ (f0(i),f1(i),f2(i),i) for i in sizesP0 ] fine = True for M,K,N,i in sizes: try: opts['static_params'] = [M,K,N] genCode = not 'libname' in opts onlygen = 'onlygen' in opts and opts['onlygen'] compiler = None if genCode: llprog = parseLL({'M': M, 'K': K, 'N': N}, opts) compiler = Compiler(llprog, opts) else: compiler = LibraryCode(opts) s = datetime.now() if not onlygen: printToLog(" " + "Starting compiler at " + str(s) + " ----------------------------------------", opts) fine = fine and compiler.compile() e = datetime.now() if not (genCode and onlygen): procOutcome(resMgr, compiler, opts, " ", sizeParams=[i]) printToLog(" " + "Compiling took " + str(e - s) + " ----------------------------------------------------------", opts) recordTime((e - s).total_seconds(), opts) except Exception: if opts.get('breakonexc',False): raise fine = False openLog(opts) ts = '%s.%s' % (date.today().isoformat(), time.strftime('%H-%M-%S', time.localtime(time.time()))) msg = "=@"*10 + " Begin Exc Report from testing1to3Param (" + ts + ") " + "=@"*10 + "\n" msg += "-"*10 + " opts " + "-"*10 + "\n" msg += str(opts) + "\n" msg += "-"*10 + " traceback " + "-"*10 + "\n" printToLog(msg, opts, openf=False, closef=False) traceback.print_exc(file=opts['logfile']) msg = "\n" + "=@"*10 + " End Exc Report (" + ts + ") " + "=@"*10 + "\n" printToLog(msg, opts, openf=False) return fine def testing3Param(resMgr, p0, p1,
<reponame>getlantern/lantern-archive<gh_stars>1-10 # -*- coding: utf-8 -*- # # PublicKey/RSA.py : RSA public key primitive # # Written in 2008 by <NAME> <<EMAIL>> # # =================================================================== # The contents of this file are dedicated to the public domain. To # the extent that dedication to the public domain is not available, # everyone is granted a worldwide, perpetual, royalty-free, # non-exclusive license to exercise all rights associated with the # contents of this file for any purpose whatsoever. # No rights are reserved. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # =================================================================== """RSA public-key cryptography algorithm (signature and encryption). RSA_ is the most widespread and used public key algorithm. Its security is based on the difficulty of factoring large integers. The algorithm has withstood attacks for 30 years, and it is therefore considered reasonably secure for new designs. The algorithm can be used for both confidentiality (encryption) and authentication (digital signature). It is worth noting that signing and decryption are significantly slower than verification and encryption. The cryptograhic strength is primarily linked to the length of the modulus *n*. In 2012, a sufficient length is deemed to be 2048 bits. For more information, see the most recent ECRYPT_ report. Both RSA ciphertext and RSA signature are as big as the modulus *n* (256 bytes if *n* is 2048 bit long). This module provides facilities for generating fresh, new RSA keys, constructing them from known components, exporting them, and importing them. >>> from Crypto.PublicKey import RSA >>> >>> key = RSA.generate(2048) >>> f = open('mykey.pem','w') >>> f.write(RSA.exportKey('PEM')) >>> f.close() ... >>> f = open('mykey.pem','r') >>> key = RSA.importKey(f.read()) Even though you may choose to directly use the methods of an RSA key object to perform the primitive cryptographic operations (e.g. `_RSAobj.encrypt`), it is recommended to use one of the standardized schemes instead (like `Crypto.Cipher.PKCS1_v1_5` or `Crypto.Signature.PKCS1_v1_5`). .. _RSA: http://en.wikipedia.org/wiki/RSA_%28algorithm%29 .. _ECRYPT: http://www.ecrypt.eu.org/documents/D.SPA.17.pdf :sort: generate,construct,importKey,error """ __revision__ = "$Id$" __all__ = ['generate', 'construct', 'error', 'importKey', 'RSAImplementation', '_RSAobj'] import sys if sys.version_info[0] == 2 and sys.version_info[1] == 1: from Crypto.Util.py21compat import * from Crypto.Util.py3compat import * #from Crypto.Util.python_compat import * from Crypto.Util.number import getRandomRange, bytes_to_long, long_to_bytes from Crypto.PublicKey import _RSA, _slowmath, pubkey from Crypto import Random from Crypto.Util.asn1 import DerObject, DerSequence, DerNull import binascii import struct from Crypto.Util.number import inverse from Crypto.Util.number import inverse try: from Crypto.PublicKey import _fastmath except ImportError: _fastmath = None class _RSAobj(pubkey.pubkey): """Class defining an actual RSA key. :undocumented: __getstate__, __setstate__, __repr__, __getattr__ """ #: Dictionary of RSA parameters. #: #: A public key will only have the following entries: #: #: - **n**, the modulus. #: - **e**, the public exponent. #: #: A private key will also have: #: #: - **d**, the private exponent. #: - **p**, the first factor of n. #: - **q**, the second factor of n. #: - **u**, the CRT coefficient (1/p) mod q. keydata = ['n', 'e', 'd', 'p', 'q', 'u'] def __init__(self, implementation, key, randfunc=None): self.implementation = implementation self.key = key if randfunc is None: randfunc = Random.new().read self._randfunc = randfunc def __getattr__(self, attrname): if attrname in self.keydata: # For backward compatibility, allow the user to get (not set) the # RSA key parameters directly from this object. return getattr(self.key, attrname) else: raise AttributeError("%s object has no %r attribute" % (self.__class__.__name__, attrname,)) def encrypt(self, plaintext, K): """Encrypt a piece of data with RSA. :Parameter plaintext: The piece of data to encrypt with RSA. It may not be numerically larger than the RSA module (**n**). :Type plaintext: byte string or long :Parameter K: A random parameter (*for compatibility only. This value will be ignored*) :Type K: byte string or long :attention: this function performs the plain, primitive RSA encryption (*textbook*). In real applications, you always need to use proper cryptographic padding, and you should not directly encrypt data with this method. Failure to do so may lead to security vulnerabilities. It is recommended to use modules `Crypto.Cipher.PKCS1_OAEP` or `Crypto.Cipher.PKCS1_v1_5` instead. :Return: A tuple with two items. The first item is the ciphertext of the same type as the plaintext (string or long). The second item is always None. """ return pubkey.pubkey.encrypt(self, plaintext, K) def decrypt(self, ciphertext): """Decrypt a piece of data with RSA. Decryption always takes place with blinding. :attention: this function performs the plain, primitive RSA decryption (*textbook*). In real applications, you always need to use proper cryptographic padding, and you should not directly decrypt data with this method. Failure to do so may lead to security vulnerabilities. It is recommended to use modules `Crypto.Cipher.PKCS1_OAEP` or `Crypto.Cipher.PKCS1_v1_5` instead. :Parameter ciphertext: The piece of data to decrypt with RSA. It may not be numerically larger than the RSA module (**n**). If a tuple, the first item is the actual ciphertext; the second item is ignored. :Type ciphertext: byte string, long or a 2-item tuple as returned by `encrypt` :Return: A byte string if ciphertext was a byte string or a tuple of byte strings. A long otherwise. """ return pubkey.pubkey.decrypt(self, ciphertext) def sign(self, M, K): """Sign a piece of data with RSA. Signing always takes place with blinding. :attention: this function performs the plain, primitive RSA decryption (*textbook*). In real applications, you always need to use proper cryptographic padding, and you should not directly sign data with this method. Failure to do so may lead to security vulnerabilities. It is recommended to use modules `Crypto.Signature.PKCS1_PSS` or `Crypto.Signature.PKCS1_v1_5` instead. :Parameter M: The piece of data to sign with RSA. It may not be numerically larger than the RSA module (**n**). :Type M: byte string or long :Parameter K: A random parameter (*for compatibility only. This value will be ignored*) :Type K: byte string or long :Return: A 2-item tuple. The first item is the actual signature (a long). The second item is always None. """ return pubkey.pubkey.sign(self, M, K) def verify(self, M, signature): """Verify the validity of an RSA signature. :attention: this function performs the plain, primitive RSA encryption (*textbook*). In real applications, you always need to use proper cryptographic padding, and you should not directly verify data with this method. Failure to do so may lead to security vulnerabilities. It is recommended to use modules `Crypto.Signature.PKCS1_PSS` or `Crypto.Signature.PKCS1_v1_5` instead. :Parameter M: The expected message. :Type M: byte string or long :Parameter signature: The RSA signature to verify. The first item of the tuple is the actual signature (a long not larger than the modulus **n**), whereas the second item is always ignored. :Type signature: A 2-item tuple as return by `sign` :Return: True if the signature is correct, False otherwise. """ return pubkey.pubkey.verify(self, M, signature) def _encrypt(self, c, K): return (self.key._encrypt(c),) def _decrypt(self, c): #(ciphertext,) = c (ciphertext,) = c[:1] # HACK - We should use the previous line # instead, but this is more compatible and we're # going to replace the Crypto.PublicKey API soon # anyway. # Blinded RSA decryption (to prevent timing attacks): # Step 1: Generate random secret blinding factor r, such that 0 < r < n-1 r = getRandomRange(1, self.key.n-1, randfunc=self._randfunc) # Step 2: Compute c' = c * r**e mod n cp = self.key._blind(ciphertext, r) # Step 3: Compute m' = c'**d mod n (ordinary RSA decryption) mp = self.key._decrypt(cp) # Step 4: Compute m = m**(r-1) mod n return self.key._unblind(mp, r) def _blind(self, m, r): return self.key._blind(m, r) def _unblind(self, m, r): return self.key._unblind(m, r) def _sign(self, m, K=None): return (self.key._sign(m),) def _verify(self, m, sig): #(s,) = sig (s,) = sig[:1] # HACK - We should use the previous line instead, but # this is more compatible and we're going to replace # the Crypto.PublicKey API soon anyway. return self.key._verify(m, s) def has_private(self): return self.key.has_private() def
# -*- coding: utf-8 -*- """Common PageObject actions.""" import hashlib import io import logging import random import string import sys import time import traceback import uuid from collections import defaultdict, namedtuple from contextlib import contextmanager from io import BytesIO from types import FunctionType, ModuleType from typing import Dict, List, NamedTuple, Union from urllib.parse import urlparse import requests from behave.runner import Context from retrying import retry from selenium.common.exceptions import ( ElementClickInterceptedException, ElementNotInteractableException, NoSuchElementException, TimeoutException, WebDriverException, ) from selenium.webdriver import ActionChains from selenium.webdriver.common.by import By from selenium.webdriver.remote.webdriver import WebDriver from selenium.webdriver.remote.webelement import WebElement from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait import WebDriverWait import allure from directory_tests_shared import URLs from directory_tests_shared.exceptions import PageLoadTimeout, UnexpectedElementPresent from directory_tests_shared.settings import ( BARRED_USERS, BASICAUTH_PASS, BASICAUTH_USER, BROWSER, TAKE_SCREENSHOTS, TEST_EMAIL_DOMAIN, ) from directory_tests_shared.utils import access_was_denied, extract_attributes_by_css from pages import ElementType from PIL import Image ScenarioData = namedtuple("ScenarioData", ["actors"]) class Actor(NamedTuple): alias: str = None email: str = None password: str = None company_name: str = None article_category: str = None visited_articles: str = None case_study_title: str = None email_confirmation_link: str = None email_confirmation_code: str = None registered: str = None visited_page: str = None last_tag: str = None forms_data: str = None saved_progress_link: str = None def __str__(self) -> str: return self.alias or self.__class__.__name__ __repr__ = __str__ class Selector(NamedTuple): by: By value: str in_desktop: bool = True in_mobile: bool = True in_horizontal: bool = True type: ElementType = None is_visible: bool = True group_id: str = None autocomplete_callback: FunctionType = None wait_after_click: bool = True next_page: ModuleType = None alternative_visibility_check: bool = False disabled: bool = False name: str = None def __str__(self) -> str: return self.name or self.__class__.__name__ __repr__ = __str__ def go_to_url(driver: WebDriver, url: str, page_name: str): """Go to the specified URL and take a screenshot afterwards.""" driver.get(url) accept_all_cookies(driver) def check_url(driver: WebDriver, expected_url: str, *, exact_match: bool = True): """Check if current page URL matches the expected one.""" with assertion_msg( f"Expected page URL to be: '{expected_url}' but got '{driver.current_url}'" ): if exact_match: assert driver.current_url == expected_url else: assert (driver.current_url in expected_url) or ( expected_url in driver.current_url ) logging.debug(f"Current page URL matches expected '{driver.current_url}'") def check_title(driver: WebDriver, expected_title: str, *, exact_match: bool = False): """Check if current page title matches the expected one.""" with assertion_msg( f"Expected page title to be: '{expected_title}' but got '{driver.title}' on {driver.current_url}" ): if exact_match: assert expected_title.lower() == driver.title.lower() else: assert expected_title.lower() in driver.title.lower() logging.debug( f"Page title on '{driver.current_url}' matches expected '{expected_title}'" ) def check_for_expected_sections_elements( driver: WebDriver, sections: Dict[str, Selector] ): """Check if all elements in page sections are visible.""" for section in sections: for element_name, selector in sections[section].items(): if not isinstance(selector, Selector): raise TypeError( f"Expected '{selector}' to be a Selector, got {type(selector)}" ) element = find_element(driver, selector, element_name=element_name) if not selector.is_visible: logging.debug(f"Skipping '{element_name} as it's marked as invisible'") continue with assertion_msg( f"It looks like '{element_name}' element in '{section}' section is not visible on {driver.current_url}" ): assert element.is_displayed() logging.debug(f"All expected elements are visible on '{driver.current_url}'") def find_and_click_on_page_element( driver: WebDriver, sections: dict, element_name: str, *, wait_for_it: bool = True ): """Find page element in any page section selectors and click on it.""" found_selector = False for section_name, selectors in sections.items(): if element_name.lower() in selectors: found_selector = True selector = selectors[element_name.lower()] logging.debug( f"Found selector for '{element_name}' in '{section_name}' section: " f"'{selector}'" ) web_element = find_element( driver, selector, element_name=element_name, wait_for_it=wait_for_it ) check_if_element_is_visible(web_element, element_name) if web_element.get_attribute("target") == "_blank": logging.debug( f"'{web_element.text}' opens in new tab, but will " f"forcefully open it in the same one" ) with wait_for_page_load_after_action(driver): href = web_element.get_attribute("href") driver.get(href) else: scroll_to(driver, web_element) if selector.wait_after_click: with wait_for_page_load_after_action(driver, timeout=10): with try_alternative_click_on_exception(driver, web_element): web_element.click() else: with try_alternative_click_on_exception(driver, web_element): web_element.click() with assertion_msg(f"Could not find '{element_name}' in any section"): assert found_selector def initialize_scenario_data() -> ScenarioData: """Will initialize the Scenario Data.""" return ScenarioData(actors={}) def unauthenticated_actor(alias: str) -> Actor: """Create an instance of an unauthenticated Actor. Will: * generate a random password for user, which can be used later on during registration or signing-in. """ email = ( f"test+{alias}{str(uuid.uuid4())}@{TEST_EMAIL_DOMAIN}".replace("-", "") .replace(" ", "") .lower() ) letters = "".join(random.choice(string.ascii_letters) for _ in range(10)) digits = "".join(random.choice(string.digits) for _ in range(10)) password = f"{<PASSWORD>}" return Actor(alias=alias, email=email, password=password, visited_articles=[]) def barred_actor(alias: str) -> Actor: actor = unauthenticated_actor(alias) actor = actor._replace(**{"email": random.choice(BARRED_USERS)}) return actor def add_actor(context: Context, actor: Actor): """Will add Actor details to Scenario Data.""" assert isinstance(actor, Actor), ( f"Expected Actor named tuple but got '{type(actor)}'" " instead" ) context.scenario_data.actors[actor.alias] = actor logging.debug(f"Successfully added actor: {actor.alias} to Scenario Data") def get_actor(context: Context, alias: str) -> Actor: """Get actor details from context Scenario Data.""" return context.scenario_data.actors.get(alias) def get_last_visited_page(context: Context, actor_alias: str) -> ModuleType: """Get last visited Page Object context Scenario Data.""" actor = context.scenario_data.actors.get(actor_alias) assert actor, f"Check your scenario. There's no such actor as: {actor_alias}" return actor.visited_page def get_full_page_name(page: ModuleType, *, page_sub_type: str = None) -> str: if page_sub_type: result = ( f"{page.SERVICE.value} - {page.NAME} ({page_sub_type}) - {page.TYPE.value}" ) else: result = f"{page.SERVICE.value} - {page.NAME} - {page.TYPE.value}" return result def update_actor(context: Context, alias: str, **kwargs): """Update Actor's details stored in context.scenario_data""" actors = context.scenario_data.actors for arg in kwargs: if arg in Actor._fields: if isinstance(getattr(actors[alias], arg), list): logging.debug(f"Appended '{kwargs[arg]}' to '{arg}' for {alias}") new_value = getattr(actors[alias], arg) new_value.append(kwargs[arg]) else: logging.debug(f"Set '{arg}'='{kwargs[arg]}' for {alias}") new_value = kwargs[arg] actors[alias] = actors[alias]._replace(**{arg: new_value}) logging.debug(f"Successfully updated {alias}'s details: {actors[alias]}") def update_actor_forms_data(context: Context, actor: Actor, form_data: dict): actor_forms_data = actor.forms_data page = actor.visited_page if not actor_forms_data: actor_forms_data = defaultdict() form_data_key = f"{page.SERVICE} - {page.NAME} - {page.TYPE}" actor_forms_data[form_data_key] = form_data update_actor(context, actor.alias, forms_data=actor_forms_data) def avoid_browser_stack_idle_timeout_exception(driver: WebDriver): """BrowserStack will stop browser session after 90s of inactivity. In order to avoid it, this helper will generate random events, like scrolling """ actions = { "scroll up": "window.scrollBy(0,-1000);", "scroll down": "window.scrollBy(0,1000);", "click on body": "document.querySelector('body').click();", "scroll to random link": "window.scrollTo(0, document.querySelectorAll('a')[Math.floor(Math.random()*document.querySelectorAll('a').length)].offsetTop);", # noqa } action = random.choice(list(actions.keys())) message = f"Trigger '{action}' event to avoid 'Idle Timeout exception'" logging.debug(message) driver.execute_script(actions[action]) def convert_png_to_jpg(screenshot_png: bytes): raw_image = Image.open(io.BytesIO(screenshot_png)) image = raw_image.convert("RGB") with BytesIO() as f: image.save(f, format="JPEG", quality=90) return f.getvalue() def fullpage_screenshot(driver): """A fullscreen screenshot workaround for Chrome driver: This script uses a simplified version of the one here: https://snipt.net/restrada/python-selenium-workaround-for-full-page-screenshot-using-chromedriver-2x/ It contains the *crucial* correction added in the comments by <NAME>. SRC: https://stackoverflow.com/q/41721734 """ logging.debug("Starting chrome full page screenshot workaround ...") total_width = driver.execute_script("return document.body.offsetWidth") total_height = driver.execute_script("return document.body.parentNode.scrollHeight") viewport_width = driver.execute_script("return document.body.clientWidth") viewport_height = driver.execute_script("return window.innerHeight") logging.debug( f"Total: ({total_width}, {total_height}), " f"Viewport: ({viewport_width},{viewport_height})" ) rectangles = [] i = 0 while i < total_height: ii = 0 top_height = i + viewport_height if top_height > total_height: top_height = total_height while ii < total_width: top_width = ii + viewport_width if top_width > total_width: top_width = total_width logging.debug(f"Appending rectangle ({ii},{i},{top_width},{top_height})") rectangles.append((ii, i, top_width, top_height)) ii = ii + viewport_width i = i + viewport_height stitched_image = Image.new("RGB", (total_width, total_height)) previous = None part = 0 for rectangle in rectangles: if previous is not None: driver.execute_script(f"window.scrollTo({rectangle[0]}, {rectangle[1]})") logging.debug(f"Scrolled To ({rectangle[0]},{rectangle[1]})") time.sleep(0.2) screenshot_png = driver.get_screenshot_as_png() screenshot = Image.open(io.BytesIO(screenshot_png)) if rectangle[1] + viewport_height > total_height: offset = (rectangle[0], total_height - viewport_height) else: offset = (rectangle[0], rectangle[1]) logging.debug( f"Adding to stitched image with offset ({offset[0]}, {offset[1]})" ) stitched_image.paste(screenshot, offset) del screenshot part = part + 1 previous = rectangle logging.debug("Finishing chrome full page screenshot workaround...") with BytesIO() as f: stitched_image.save(f, format="JPEG", quality=90) return f.getvalue() @retry(stop_max_attempt_number=3) def take_screenshot(driver: WebDriver, page_name: str = None): """Will take a screenshot of current page.""" if TAKE_SCREENSHOTS: if BROWSER == "firefox": # Ref: https://stackoverflow.com/a/52572919/ original_size = driver.get_window_size() required_width = driver.execute_script( "return document.body.parentNode.scrollWidth" ) required_height = driver.execute_script( "return document.body.parentNode.scrollHeight" ) driver.set_window_size(required_width, required_height) element = driver.find_element_by_tag_name("body") screenshot_png = element.screenshot_as_png screenshot_jpg = convert_png_to_jpg(screenshot_png) elif BROWSER == "chrome": screenshot_jpg = fullpage_screenshot(driver) if page_name: page_name = page_name.lower().replace(" ", "_")[0:200] allure.attach( screenshot_jpg, name=page_name or "screenshot.jpg", attachment_type=allure.attachment_type.JPG, ) if BROWSER == "firefox": driver.set_window_size(original_size["width"], original_size["height"]) else: logging.debug( f"Taking screenshots is disabled. In order to turn it on " f"please set an environment variable TAKE_SCREENSHOTS=true" ) @contextmanager def assertion_msg(message: str, *args): """This will: * print the custom assertion message * print the traceback (stack trace) * raise the original AssertionError exception """ try: yield except AssertionError as e: if args: message = message % args logging.error(message) e.args += (message,) _, _, tb = sys.exc_info() if len(sys._current_frames()) == 1: print(f"Found 'shallow' Traceback, will inspect outer traceback frames") import inspect for f in
() , org_location = Link ("org_location") , contract_type = Link ('contract_type') , time_project = Link ("time_project") , duration = Interval () , is_valid = Boolean () , durations_allowed = Boolean () , all_in = Boolean () ) auto_wp.setlabelprop ("name") overtime_period = Class \ ( db , ''"overtime_period" , name = String () , order = Number () , weekly = Boolean () , months = Number () , required_overtime = Boolean () ) overtime_period.setkey ("name") vac_aliq = Class \ ( db , ''"vac_aliq" , name = String () ) vac_aliq.setkey ("name") ud = Class \ ( db , ''"user_dynamic" , user = Link ("user") , valid_from = Date (offset = 0) , valid_to = Date (offset = 0) , booking_allowed = Boolean () , travel_full = Boolean () , durations_allowed = Boolean () , weekend_allowed = Boolean () , vacation_yearly = Number () , vacation_month = Number () , vacation_day = Number () , contract_type = Link ('contract_type', do_journal = "no") , daily_worktime = Number () , weekly_hours = Number () , supp_weekly_hours = Number () , supp_per_period = Number () , hours_mon = Number () , hours_tue = Number () , hours_wed = Number () , hours_thu = Number () , hours_fri = Number () , hours_sat = Number () , hours_sun = Number () , org_location = Link ("org_location", do_journal = "no") , department = Link ("department", do_journal = "no") , all_in = Boolean () , additional_hours = Number () , overtime_period = Link ( "overtime_period" , do_journal = "no" ) , sap_cc = Link ("sap_cc") , max_flexitime = Number () , vac_aliq = Link ("vac_aliq", do_journal = "no") , exemption = Boolean () , short_time_work_hours = Number () , do_auto_wp = Boolean () , time_activity_perm = Multilink ( "time_activity_perm" , do_journal = "no" ) ) leave_status = Class \ ( db , ''"leave_status" , name = String () , order = Number () , transitions = Multilink ("leave_status") ) leave_status.setkey ("name") contract_type = Class \ ( db , ''"contract_type" , name = String () , order = Number () , description = String () , group_external = Boolean () ) leave_submission = Class \ ( db , ''"leave_submission" , user = Link ("user") , first_day = Date (offset = 0) , last_day = Date (offset = 0) , status = Link ("leave_status", do_journal = 'no') , time_wp = Link ("time_wp", do_journal = 'no') , comment = String () , comment_cancel = String () , approval_hr = Boolean () # only for queries ) # Remaining vacation starting with given date if absolute is True, # Interpreted as relative correction if absolute = False, relative # to last vacation. Note that to start vacation reporting at least # one starting vacation_correction record with absolute = True must # exist. Vacation reporting is started with that date. Note that # the date does *not* belong to the computation, to start reporting # with 2014-01-01 a vacation_correction record with exactly that # date must exist and the carry-over from the last year is in # 'days'. vacation_correction = Class \ ( db , ''"vacation_correction" , user = Link ("user") , date = Date (offset = 0) , absolute = Boolean () , days = Number () , contract_type = Link ('contract_type') , comment = String () ) # Only for reporting mask, no records will ever be created vacation_report = Class \ ( db , ''"vacation_report" , user = Link ("user") , supervisor = Link ("user") , department = Link ("department") , organisation = Link ("organisation") , org_location = Link ("org_location") , time_project = Link ("time_project") , date = Date (offset = 0) , additional_submitted = String () , approved_submissions = String () , flexi_time = String () , flexi_sub = String () , flexi_max = String () , flexi_rem = String () , special_leave = String () , special_sub = String () , show_obsolete = Boolean () ) absence_type = Class \ ( db , ''"absence_type" , code = String () , description = String () , cssclass = String () ) absence_type.setkey ("code") absence = Class \ ( db , ''"absence" , absence_type = Link ("absence_type") , first_day = Date (offset = 0) , last_day = Date (offset = 0) , user = Link ("user") ) # Only for queries timesheet = Class \ ( db , ''"timesheet" , first_day = Date (offset = 0) , last_day = Date (offset = 0) , user = Link ("user") , department = Link ("department") , supervisor = Link ("user") ) work_location = Class \ ( db , ''"work_location" , code = String () , description = String () ) work_location.setkey ("code") functional_role = Class \ ( db, ''"functional_role" , name = String () , name_group = String () , rank = Number () ) functional_role.setkey ("name") functional_role.setorderprop ("rank") user_functional_role = Class \ ( db, ''"user_functional_role" , user = Link ("user" , rev_multilink='planning_role' ) , functional_role = Link ("functional_role") , ratio = Number () ) user_functional_role.setlabelprop ("functional_role") class User_Class (kw ['User_Class']) : """ add some attrs to user class """ def __init__ (self, db, classname, ** properties) : self.update_properties \ ( timing_info = Boolean () , timetracking_by = Link ("user") , scale_seniority = String () , reduced_activity_list = Date () , entry_date = Date () , position_text = String () , vie_user = Link ("user", rev_multilink = 'vie_user_ml') , vie_user_bl_override = Link ("user") , sync_foreign_key = String () , department_temp = String () ) kw ['User_Class'].__init__ (self, db, classname, ** properties) # end def __init__ # end class User_Class export.update (dict (User_Class = User_Class)) User_Status_Ancestor = kw ['User_Status_Class'] class User_Status_Class_TT (User_Status_Ancestor) : """ Add attribute(s) to User_Status_Class. """ def __init__ (self, db, classname, ** properties) : self.update_properties \ ( timetracking_allowed = Boolean () ) User_Status_Ancestor.__init__ \ (self, db, classname, ** properties) # end def __init___ # end class User_Status_Class_TT export.update (dict (User_Status_Class = User_Status_Class_TT)) class Org_Location_Class (kw ['Org_Location_Class']) : """ Add some attributes needed for time tracker """ def __init__ (self, db, classname, ** properties) : ancestor = kw ['Org_Location_Class'] self.update_properties \ ( vacation_legal_year = Boolean () , vacation_yearly = Number () , do_leave_process = Boolean () , vac_aliq = Link ("vac_aliq") , sap_lifnr = String () , do_auto_wp = Boolean () ) ancestor.__init__ (self, db, classname, ** properties) # end def __init__ # end class Org_Location_Class export.update (dict (Org_Location_Class = Org_Location_Class)) Org_Location_Class (db, ''"org_location") class Location_Class (kw ['Location_Class']) : """ Add some attributes needed for time tracker """ def __init__ (self, db, classname, ** properties) : ancestor = kw ['Location_Class'] self.update_properties \ ( weekly_hours_fte = Number () ) ancestor.__init__ (self, db, classname, ** properties) # end def __init__ # end class Location_Class export.update (dict (Location_Class = Location_Class)) Location_Class (db, ''"location") # Some classes defined elsewhere which are required (and possibly # extended in several other include files) Department_Class (db, ''"department") class Organisation_Class (kw ['Organisation_Class']) : """ Add some attributes needed for time tracker """ def __init__ (self, db, classname, ** properties) : ancestor = kw ['Organisation_Class'] self.update_properties \ ( org_group = Link ("org_group") ) ancestor.__init__ (self, db, classname, ** properties) # end def __init__ # end class Organisation_Class export.update (dict (Organisation_Class = Organisation_Class)) Organisation_Class (db, ''"organisation") org_group = Class \ ( db, ''"org_group" , name = String () ) org_group.setkey ("name") return export # end def init # # SECURITY SETTINGS # # See the configuration and customisation document for information # about security setup. def security (db, ** kw) : roles = \ [ ("Project", "Project Office") , ("Project_View", "May view project data") , ("HR-vacation", "May approve vacation and special leave") , ("HR-leave-approval", "Approve paid vacation beyond normal vacation") , ("Staff-report", "May view staff report") , ("Vacation-report", "May view vacation report") , ("Controlling", "Controlling") , ("Summary_View", "View full summary report and
LAYER_OUT_NUM,\n') code.append(indent(1) + 'uint LAYER_IN_NUM_T,\n') code.append(indent(1) + 'uint LAYER_OUT_NUM_T,\n') code.append(indent(1) + 'uint LAYER_IN_IMG_H,\n') code.append(indent(1) + 'uint LAYER_IN_IMG_W,\n') code.append(indent(1) + 'uint LAYER_OUT_IMG_H,\n') code.append(indent(1) + 'uint LAYER_OUT_IMG_W,\n') code.append(indent(1) + 'uint LAYER_IN_IMG_H_T,\n') code.append(indent(1) + 'uint LAYER_IN_IMG_W_T,\n') code.append(indent(1) + 'uint FILTER_S,\n') code.append(indent(1) + 'uint LAYER_STRIDE,\n') code.append(indent(1) + 'uint LAYER_BATCH\n') code.append('){\n') code.append('#pragma HLS INLINE off\n') code.append(indent(1) + var_prefix + 'bus_t%d %s_buf[%sDATA%d_HEAD_BUF_SIZE / %sDATA%d_PACK_FACTOR];\n' % (idx, op_name, var_prefix, idx, var_prefix, idx)) code.append(indent(1) + 'ap_uint<' + var_prefix + 'DATA' + str(idx) + '_WIDTH * ' + var_prefix + 'DATA' + str(idx) + '_FC_SIMD_FACTOR> sel_tmp[' + var_prefix + 'DATA' + str(idx) + '_PACK_FACTOR / ' + var_prefix + 'DATA' + str(idx) + '_FC_SIMD_FACTOR];\n') code.append('#pragma HLS ARRAY_PARTITION variable=sel_tmp complete dim=1\n\n') indent_level = 1 w = cal_width(desp['PARAMETERS']['LAYER_BATCH']) code.append(indent(indent_level) + 'for (ap_uint<%d> layer_iter = 0; layer_iter < LAYER_BATCH; layer_iter++){\n' % (w)) code.append(indent(indent_level+1) + 'for (int out_img_h_t = 0; out_img_h_t < LAYER_OUT_IMG_H; out_img_h_t += LAYER_IN_IMG_H_T / LAYER_STRIDE){\n') code.append(indent(indent_level+2) + 'for (int out_img_w_t = 0; out_img_w_t < LAYER_OUT_IMG_W; out_img_w_t += LAYER_IN_IMG_W_T / LAYER_STRIDE){\n') code.append(indent(indent_level+3) + 'for (int out_num_t = 0; out_num_t < LAYER_OUT_NUM; out_num_t += LAYER_OUT_NUM_T){\n') code.append(indent(indent_level+4) + 'uint chunk_offset = out_num_t * FILTER_S * FILTER_S * LAYER_IN_NUM;\n') code.append(indent(indent_level+4) + 'memcpy((void*)weight_buf, (void*)(weight + chunk_offset / %sDATA1_PACK_FACTOR), sizeof(%sdata_t1) * LAYER_OUT_NUM_T * FILTER_S * FILTER_S * LAYER_IN_NUM);\n' % (var_prefix, var_prefix)) code.append(indent(indent_level+4) + 'for (int in_num_t = 0; in_num_t < LAYER_IN_NUM; in_num_t += LAYER_IN_NUM_T){\n') code.append(indent(indent_level+5) + 'for (int oo =0; oo < LAYER_OUT_NUM_T; oo++){\n') code.append(indent(indent_level+6) + 'for (int p = 0; p < FILTER_S; p++){\n') code.append(indent(indent_level+7) + 'for (int q = 0; q < FILTER_S; q++){\n') code.append(indent(indent_level+8) + 'for (int ii = 0; ii < LAYER_IN_NUM_T / %sDATA%d_FC_SIMD_FACTOR; ii++){\n' % (var_prefix, idx)) code.append('#pragma HLS PIPELINE II=1\n') code.append(indent(indent_level+9) + 'uint weight_local_idx = oo * FILTER_S * FILTER_S * LAYER_IN_NUM + p * FILTER_S * LAYER_IN_NUM + q * LAYER_IN_NUM + (in_num_t + ii * %sDATA1_FC_SIMD_FACTOR);\n' % (var_prefix)); code.append(indent(indent_level+9) + 'uint weight_bus_idx = weight_local_idx / %sDATA%d_PACK_FACTOR;\n' % (var_prefix, idx)) code.append(indent(indent_level+9) + 'uint weight_bus_offset = weight_local_idx %% %sDATA%d_PACK_FACTOR;\n' % (var_prefix, idx)) code.append(indent(indent_level+9) + '%sbus_t%d bus_data = weight_buf[weight_bus_idx];\n' % (var_prefix, idx)) code.append(indent(indent_level+9) + 'ap_uint<%sDATA%d_WIDTH * %sDATA%d_FC_SIMD_FACTOR> fifo_weight_data;\n' % (var_prefix, idx, var_prefix, idx)) unroll_w = cal_width(desp['BUS_WIDTH'][idx] / desp['DATA_WIDTH'][idx] / desp['FC_SIMD_FACTOR'][idx]) code.append(indent(indent_level+9) + 'for (ap_uint<' + str(unroll_w) + '> s = 0; s < ' + var_prefix + 'DATA' + str(idx) + '_PACK_FACTOR / ' + var_prefix + 'DATA' + str(idx) + '_FC_SIMD_FACTOR; s++){\n') code.append('#pragma HLS UNROLL\n') code.append(indent(indent_level+10) + 'sel_tmp[s] = bus_data(' + var_prefix + 'DATA' + str(idx) + '_WIDTH * ' + var_prefix + 'DATA' + str(idx) + '_FC_SIMD_FACTOR - 1, 0);\n') code.append(indent(indent_level+10) + 'bus_data = bus_data >> (' + var_prefix + 'DATA' + str(idx) + '_WIDTH * ' + var_prefix + 'DATA' + str(idx) + '_FC_SIMD_FACTOR);\n') code.append(indent(indent_level+9) + '}\n') code.append(indent(indent_level+9) + 'fifo_weight_data = sel_tmp[weight_bus_offset / %sDATA%d_FC_SIMD_FACTOR];\n' % (var_prefix, idx)) code.append(indent(indent_level+9) + 'fifo_transfer_weight.write(fifo_weight_data);\n') code.append(indent(indent_level+8) + '}\n') code.append(indent(indent_level+7) + '}\n') code.append(indent(indent_level+6) + '}\n') code.append(indent(indent_level+5) + '}\n') code.append(indent(indent_level+4) + '}\n') code.append(indent(indent_level+3) + '}\n') code.append(indent(indent_level+2) + '}\n') code.append(indent(indent_level+1) + '}\n') code.append(indent(indent_level) + '}\n') code.append('}\n\n') # head if idx == 0: code.append('void ' + var_prefix + 'DataFeed' + str(idx) + 'Head(\n') # code.append(indent(1) + var_prefix + 'bus_t' + str(idx) + '* ' + op_name + ',\n') code.append(indent(1) + 'stream<ap_uint<%sDATA%d_WIDTH * %sDATA%d_FC_SIMD_FACTOR> > &fifo_transfer_in,\n' % (var_prefix, idx, var_prefix, idx)) # code.append(indent(1) + 'bool init,\n') # code.append(indent(1) + 'unsigned int FILTER_S,\n') for feed_group in range(desp['FC_SPLIT_FACTOR'][idx]): if feed_group < desp['FC_SPLIT_FACTOR'][idx] - 1: code.append(indent(1) + 'stream<' + var_prefix + 'Data' + str(idx) + 'TransferChannelType> &fifo_transfer_out' + str(feed_group) + ',\n') else: code.append(indent(1) + 'stream<' + var_prefix + 'Data' + str(idx) + 'TransferChannelType> &fifo_transfer_out' + str(feed_group) + ',\n') # code.append(indent(1) + 'uint LAYER_IN_NUM,\n') # code.append(indent(1) + 'uint LAYER_OUT_NUM,\n') # code.append(indent(1) + 'uint LAYER_IN_IMG_H,\n') # code.append(indent(1) + 'uint LAYER_IN_IMG_W,\n') # code.append(indent(1) + 'uint LAYER_OUT_IMG_H,\n') # code.append(indent(1) + 'uint LAYER_OUT_IMG_W,\n') # code.append(indent(1) + 'uint LAYER_FILTER_S,\n') code.append(indent(1) + 'stream<%sConfigInst> &fifo_kernel_config_in,\n' % (var_prefix)) code.append(indent(1) + 'stream<%sConfigInst> &fifo_kernel_config_out,\n' % (var_prefix)) code.append(indent(1) + 'stream<uint> &fifo_config_out0,\n') code.append(indent(1) + 'stream<uint> &fifo_config_out1\n') code.append('){\n') code.append('#pragma HLS INLINE off\n') for feed_group in range(desp['FC_SPLIT_FACTOR'][idx]): code.append('#pragma HLS DATA_PACK variable=fifo_transfer_out' + str(feed_group) + '\n') code.append('\n') code.append(indent(1) + '// loader buffer\n') code.append(indent(1) + 'ap_uint<%sDATA%d_WIDTH * %sDATA%d_FC_SIMD_FACTOR> %s_buf[%sIN_NUM_T * %sIN_IMG_H_T * %sIN_IMG_W_T / %sDATA%d_FC_SIMD_FACTOR];\n' % (var_prefix, idx, var_prefix, idx, op_name, var_prefix, var_prefix, var_prefix, var_prefix, idx)) code.append('#pragma HLS ARRAY_PARTITION variable=%s_buf dim=1 block factor=%s\n\n' % (op_name, str(desp['FC_SPLIT_FACTOR'][idx]))) code.append(indent(1) + '// Read instructions\n') code.append(indent(1) + '%sConfigInst inst0 = fifo_kernel_config_in.read();\n' % (var_prefix)) code.append(indent(1) + 'fifo_kernel_config_out.write(inst0);\n') code.append(indent(1) + '%sConfigInst inst1 = fifo_kernel_config_in.read();\n' % (var_prefix)) code.append(indent(1) + 'fifo_kernel_config_out.write(inst1);\n') code.append(indent(1) + '%sConfigInst inst2 = fifo_kernel_config_in.read();\n' % (var_prefix)) code.append(indent(1) + 'fifo_kernel_config_out.write(inst2);\n') code.append(indent(1) + '%sConfigInst inst3 = fifo_kernel_config_in.read();\n' % (var_prefix)) code.append(indent(1) + 'fifo_kernel_config_out.write(inst3);\n') code.append(indent(1) + '%sConfigInst inst4 = fifo_kernel_config_in.read();\n' % (var_prefix)) code.append(indent(1) + 'fifo_kernel_config_out.write(inst4);\n') code.append(indent(1) + 'ap_uint<32> LAYER_BATCH = inst3(32*5+31, 32*5);\n\n') w = cal_width(desp['PARAMETERS']['LAYER_BATCH']) code.append(indent(1) + 'ap_uint<%d> layer_iter = 0;\n' % (w)) code.append(indent(1) + 'bool done1 = 0;\n') code.append(indent(1) + 'while(!done1){\n') # code.append(indent(1) + 'for (ap_uint<%d> layer_iter = 0; layer_iter < LAYER_BATCH; layer_iter++){\n' % (w)) code.append(indent(2) + 'if (layer_iter > 0){\n') code.append(indent(3) + '// Read instructions\n') code.append(indent(3) + 'inst0 = fifo_kernel_config_in.read();\n') code.append(indent(3) + 'fifo_kernel_config_out.write(inst0);\n') code.append(indent(3) + 'inst1 = fifo_kernel_config_in.read();\n') code.append(indent(3) + 'fifo_kernel_config_out.write(inst1);\n') code.append(indent(3) + 'inst2 = fifo_kernel_config_in.read();\n') code.append(indent(3) + 'fifo_kernel_config_out.write(inst2);\n') code.append(indent(3) + 'inst3 = fifo_kernel_config_in.read();\n') code.append(indent(3) + 'fifo_kernel_config_out.write(inst3);\n') code.append(indent(3) + 'inst4 = fifo_kernel_config_in.read();\n') code.append(indent(3) + 'fifo_kernel_config_out.write(inst4);\n') code.append(indent(2) + '}\n') code.append(indent(2) + 'ap_uint<32> EXT_LAYER_IN_NUM_HW = inst0(32*0+31, 32*0);\n') code.append(indent(2) + 'ap_uint<32> EXT_LAYER_OUT_NUM_HW = inst0(32*1+31, 32*1);\n') code.append(indent(2) + 'ap_uint<32> EXT_LAYER_IN_H_HW = inst0(32*2+31, 32*2);\n') code.append(indent(2) + 'ap_uint<32> EXT_LAYER_IN_W_HW = inst0(32*3+31, 32*3);\n') code.append(indent(2) + 'ap_uint<32> EXT_LAYER_OUT_H_HW = inst0(32*4+31, 32*4);\n') code.append(indent(2) + 'ap_uint<32> EXT_LAYER_OUT_W_HW = inst0(32*5+31, 32*5);\n') code.append(indent(2) + '// inst1\n') code.append(indent(2) + 'ap_uint<32> EXT_LAYER_IN_NUM = inst1(32*0+31, 32*0);\n') code.append(indent(2) + 'ap_uint<32> EXT_LAYER_OUT_NUM = inst1(32*1+31, 32*1);\n') code.append(indent(2) + 'ap_uint<32> EXT_LAYER_IN_H = inst1(32*2+31, 32*2);\n') code.append(indent(2) + 'ap_uint<32> EXT_LAYER_IN_W = inst1(32*3+31, 32*3);\n') code.append(indent(2) + 'ap_uint<32> EXT_LAYER_OUT_H = inst1(32*4+31, 32*4);\n') code.append(indent(2) + 'ap_uint<32> EXT_LAYER_OUT_W = inst1(32*5+31, 32*5);\n') code.append(indent(2) + '// inst2\n') code.append(indent(2) + 'ap_uint<32> EXT_CIN_OFFSET = inst2(32*0+31, 32*0);\n') code.append(indent(2) + 'ap_uint<32> EXT_WEIGHT_OFFSET = inst2(32*1+31, 32*1);\n') code.append(indent(2) + 'ap_uint<32> EXT_BIAS_OFFSET = inst2(32*2+31, 32*2);\n') code.append(indent(2) + 'ap_uint<32> EXT_COUT_OFFSET = inst2(32*3+31, 32*3);\n') code.append(indent(2) + 'ap_uint<16> EXT_FILTER_S1 = inst2(32*4+15, 32*4);\n') code.append(indent(2) + 'ap_uint<16> EXT_FILTER_S2 = inst2(32*4+31, 32*4+16);\n') code.append(indent(2) + 'ap_uint<32> EXT_STRIDE = inst2(32*5+31, 32*5);\n') code.append(indent(2) + '// inst3\n') code.append(indent(2) + 'ap_uint<32> EXT_LAYER_EN = inst3(32*0+31, 32*0);\n') code.append(indent(2) + 'ap_uint<32> EXT_PREV_CIN_OFFSET = inst3(32*1+31, 32*1);\n') code.append(indent(2) + 'ap_uint<16> EXT_LAYER_IN_NUM_T = inst3(32*2+15, 32*2);\n') code.append(indent(2) + 'ap_uint<16> EXT_LAYER_OUT_NUM_T = inst3(32*2+31, 32*2+16);\n') code.append(indent(2) + 'ap_uint<32> EXT_LAYER_IN_IMG_H_T = inst3(32*3+31, 32*3);\n') code.append(indent(2) + 'ap_uint<32> EXT_LAYER_IN_IMG_W_T = inst3(32*4+31, 32*4);\n') code.append(indent(2) + 'ap_uint<1> EXT_CONV_1ST_EN = EXT_LAYER_EN[0];\n') code.append(indent(2) + 'ap_uint<1> EXT_DEPTH_CONV_EN = EXT_LAYER_EN[1];\n') code.append(indent(2) + 'ap_uint<1> EXT_CONV_EN = EXT_LAYER_EN[2];\n') code.append(indent(2) + 'ap_uint<1> EXT_RELU_EN = EXT_LAYER_EN[3];\n') code.append(indent(2) + 'ap_uint<1> EXT_RELU6_EN = EXT_LAYER_EN[4];\n') code.append(indent(2) + 'ap_uint<1> EXT_POOL_EN = EXT_LAYER_EN[5];\n\n') code.append(indent(2) + 'ap_uint<32> EXT_LAYER_TASK_NUM1 = inst4(32*0+31, 32*0);\n') code.append(indent(2) + 'ap_uint<32> EXT_LAYER_TASK_NUM2 = inst4(32*1+31, 32*1);\n') code.append(indent(2) + 'ap_uint<32> EXT_LAYER_LOCAL_ACCUM_NUM = inst4(32*2+31, 32*2);\n') code.append(indent(2) + 'ap_uint<32> EXT_LAYER_LOCAL_REG_NUM = inst4(32*3+31, 32*3);\n') code.append(indent(2) + 'ap_uint<32> EXT_LAYER_ROW_IL_FACTOR = inst4(32*4+31, 32*4);\n') code.append(indent(2) + 'ap_uint<32> EXT_LAYER_COL_IL_FACTOR = inst4(32*5+31, 32*5);\n\n') code.append(indent(2) + 'uint EXT_FILTER_S = (EXT_CONV_EN == 1)? (uint)EXT_FILTER_S2: 1;\n') code.append(indent(2) + 'bool separable_conv = (EXT_DEPTH_CONV_EN == 1) && (EXT_CONV_EN == 1);\n') code.append(indent(2) + 'bool conv2d = (EXT_DEPTH_CONV_EN == 0) && (EXT_CONV_EN == 1);\n') code.append(indent(2) + 'bool max_pool = (EXT_DEPTH_CONV_EN == 0) && (EXT_CONV_EN == 0);\n') code.append(indent(2) + 'uint stride1 = (EXT_DEPTH_CONV_EN == 0)? 1 : (uint)EXT_STRIDE;\n') code.append(indent(2) + 'uint stride2 = (EXT_DEPTH_CONV_EN == 0)? (uint)EXT_STRIDE : 1;\n\n') code.append(indent(2) + 'uint LAYER_IN_IMG_H = (EXT_DEPTH_CONV_EN == 1)? (uint)EXT_LAYER_IN_H_HW - (uint)EXT_FILTER_S1 + 1: (uint)EXT_LAYER_IN_H_HW;\n') code.append(indent(2) + 'uint LAYER_IN_IMG_W = (EXT_DEPTH_CONV_EN == 1)? (uint)EXT_LAYER_IN_W_HW - (uint)EXT_FILTER_S1 + 1: (uint)EXT_LAYER_IN_W_HW;\n') code.append(indent(2) + 'uint LAYER_OUT_IMG_H = EXT_LAYER_OUT_H;\n') code.append(indent(2) + 'uint LAYER_OUT_IMG_W = EXT_LAYER_OUT_W;\n') code.append(indent(2) + 'uint LAYER_IN_NUM = EXT_LAYER_IN_NUM_HW;\n') code.append(indent(2) + 'uint LAYER_OUT_NUM = EXT_LAYER_OUT_NUM_HW;\n') code.append(indent(2) + 'uint LAYER_IN_NUM_T = EXT_LAYER_IN_NUM_T;\n') code.append(indent(2) + 'uint LAYER_OUT_NUM_T = EXT_LAYER_OUT_NUM_T;\n') code.append(indent(2) + 'uint LAYER_IN_IMG_H_T;\n') code.append(indent(2) + 'uint LAYER_IN_IMG_W_T;\n') code.append(indent(2) + 'if (stride1 == 1){\n') code.append(indent(3)+ 'LAYER_IN_IMG_H_T = EXT_LAYER_IN_IMG_H_T;\n') code.append(indent(3)+ 'LAYER_IN_IMG_W_T = EXT_LAYER_IN_IMG_W_T;\n') code.append(indent(2) + '} else if (stride1 == 2){\n') code.append(indent(3) + 'LAYER_IN_IMG_H_T = EXT_LAYER_IN_IMG_H_T / 2;\n') code.append(indent(3) + 'LAYER_IN_IMG_W_T = EXT_LAYER_IN_IMG_W_T / 2;\n') code.append(indent(2) + '}\n') code.append(indent(2) + 'uint LAYER_FILTER_S
"""Permission storage model.""" import logging from enum import IntEnum from functools import reduce from typing import List, Optional, Union from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.auth.models import Group, User from django.db import models, transaction logger = logging.getLogger(__name__) PermissionList = List["Permission"] UserOrGroup = Union[User, Group] # Get and store the anonymous user for later use to avoid hits to the database. ANONYMOUS_USER = None def get_anonymous_user() -> User: """Get the anonymous user. Note that is the actual user object with username specified in setting ANONYMOUS_USER_NAME or id specified in setting ANONYMOUS_USER_ID. The later setting has precedence. Store the computed value into global variable get_anonymous_user() to avoid querying the database every time. :raises django.core.exceptions.ObjectDoesNotExist: when anonymous user could not be found. :raises RuntimeError: when setting ANONYMOUS_USER_NAME could not be found. """ # Return the cached value in production. During testing the anonymous user # will be recreated several times with different id. from resolwe.test.utils import is_testing global ANONYMOUS_USER if ANONYMOUS_USER is not None and not is_testing: return ANONYMOUS_USER anonymous_user_id = getattr(settings, "ANONYMOUS_USER_ID", None) anonymous_username = getattr(settings, "ANONYMOUS_USER_NAME", None) create_arguments = {"is_active": True, "email": "", "username": "public"} filters = None if anonymous_user_id is not None: filters = {"id": anonymous_user_id} create_arguments["id"] = anonymous_user_id elif anonymous_username is not None: filters = {User.USERNAME_FIELD: anonymous_username} create_arguments["username"] = anonymous_username if filters: try: return get_user_model().objects.get(**filters) except User.DoesNotExist: # Resolve circular import. if is_testing(): return get_user_model().objects.create(**create_arguments) else: raise raise RuntimeError("No ANONYMOUS_USER_ID/ANONYMOUS_USER_NAME setting found.") class Permission(IntEnum): """Enum that describes all possible permissions on Resolwe objects. The permissions on Resolwe objects are ordered linearly so they can be mapped to natural numbers. Permissions that are mapped to lower numbers are implicitely included in the permissions mapped to a higher number. Whenever dealing with permissions (reading, setting...) it is necessary to use this enum. The instances of Permission class are iterable and iterating over an instance P returs all permissions that are lower or equal to P, ordered from bottom to top. """ # Possible permission levels. They must be orded from bottom to top since # methods bellow rely on the ordering. NONE = 0 VIEW = 1 EDIT = 2 SHARE = 4 OWNER = 8 @staticmethod def from_name(permission_name: str) -> "Permission": """Get the permission from permission name. :returns: Permission object when permission_name is the name of the permission and highest permission if permission_name is 'ALL'. :raises KeyError: when permission name is not known. """ if permission_name == "ALL": return Permission.highest() return Permission[permission_name.upper()] @staticmethod def highest() -> "Permission": """Return the highest permission.""" return list(Permission)[-1] def __iter__(self): """Iterate through permission in increasing order. When iterating over permission instance the permissions included in the current one (including permission itself) are returned (in increasing order). The permission Permission.NONE is excluded from the listing. """ for permission in Permission: if 0 < permission.value <= self.value: yield permission def __reversed__(self): """Iterate through permissions in decreasing order. When iterating over permission instance the permissions included in the current one (including permission itself) are returned (in decreasing order). The permission Permission.NONE is excluded from the listing. """ for permission in reversed(Permission): if 0 < permission.value <= self.value: yield permission def __str__(self) -> str: """Get the string representation of the permission. This is used in serialization so it must be equal to 'view', 'edit', 'share' and 'owner'. """ return self.name.lower() class PermissionModel(models.Model): """Store a permission for a singe user/group on permission group. Exactly one of fields user/group must be non-null. """ #: permission value value = models.PositiveSmallIntegerField() #: user this permission belongs to user = models.ForeignKey( get_user_model(), related_name="model_permissions", on_delete=models.CASCADE, null=True, ) #: group this permission belongs to group = models.ForeignKey( Group, related_name="model_permissions", on_delete=models.CASCADE, null=True ) #: permission group this permission belongs to permission_group = models.ForeignKey( "PermissionGroup", on_delete=models.CASCADE, related_name="permissions" ) class Meta: """Define constraints enforced on the model. The tripple (value, permission_group, user/group) must be unique. """ constraints = [ models.UniqueConstraint( fields=["permission_group", "value", "user"], name="one_permission_per_user", condition=models.Q(user__isnull=False), ), models.UniqueConstraint( fields=["permission_group", "value", "group"], name="one_permission_per_group", condition=models.Q(group__isnull=False), ), models.CheckConstraint( check=models.Q(user__isnull=False, group__isnull=True) | models.Q(user__isnull=True, group__isnull=False), name="exactly_one_of_user_group_must_be_set", ), ] @property def permission(self) -> Permission: """Return the permission object associated with this instance.""" return Permission(self.value) @property def permissions(self) -> PermissionList: """Return the permission objects associated with this instance.""" return list(self.permission) def __str__(self) -> str: """Get the string representation used for debugging.""" return ( f"PermissionModel({self.id}, {Permission(self.permission)}, " f"user: {self.user}, group: {self.group})" ) class PermissionGroup(models.Model): """Group of objecs that have the same permissions. Example: a container and all its contents have same permission group. """ def __str__(self) -> str: """Return the string representation used for debugging purposes.""" return f"PermissionGroup({self.id}, {self.permissions.all()})" @transaction.atomic def set_permission(self, permission: Permission, user_or_group: UserOrGroup): """Set the given permission on this permission group. All previous permissions are removed. :raises AssertionError: when no user or group is given. """ from resolwe.permissions.utils import get_identity # Circular import entity, entity_name = get_identity(user_or_group) self.permissions.update_or_create( **{"permission_group": self, entity_name: entity}, defaults={"value": permission.value}, ) def get_permission(self, user_or_group: UserOrGroup) -> Permission: """Get the permission for the given user or group.""" from resolwe.permissions.utils import get_identity # Circular import entity, entity_name = get_identity(user_or_group) # Superuser has all the permissions. if entity_name == "user" and entity.is_superuser: return Permission.highest() permission_models = self.permissions.filter(**{entity_name: entity}) return permission_models[0].permission if permission_models else Permission.NONE class PermissionQuerySet(models.QuerySet): """Queryset with methods that simlify filtering by permissions.""" def _filter_by_permission( self, user: Optional[User], groups: Optional[List[Group]], permission: Permission, public: bool = True, with_superuser: bool = True, ) -> models.QuerySet: """Filter queryset by permissions. This is a generic method that is called in public methods. :attr user: the user which permissions should be considered. :attr groups: the groups which permissions should be considered. :attr permission: the lowest permission entity must have. :attr public: when True consider also public permission. :attr with_superuser: when false treat superuser as reguar user. """ # Skip filtering for superuser when with_superuser is set. if user is not None and user.is_superuser and with_superuser: return self # Handle special case of Storage and Relation. filters_prefix = "" if self.model._meta.label == "flow.Storage": filters_prefix = "data__" filters = dict() if user: filters["user"] = models.Q( **{ f"{filters_prefix}permission_group__permissions__user": user, f"{filters_prefix}permission_group__permissions__value__gte": permission, } ) if public: filters["public"] = models.Q( **{ f"{filters_prefix}permission_group__permissions__user": get_anonymous_user(), f"{filters_prefix}permission_group__permissions__value__gte": permission, } ) if groups: filters["groups"] = models.Q( **{ f"{filters_prefix}permission_group__permissions__group__in": groups.values_list( "pk", flat=True ), f"{filters_prefix}permission_group__permissions__value__gte": permission, } ) # List here is needed otherwise more joins are performed on the query # bellow. Some Django queries (for example ExpressionLateralJoin) do # not like that and will fail without evaluating the ids query first. ids = list( self.filter( reduce(lambda filters, filter: filters | filter, filters.values()) ) .distinct() .values_list("id", flat=True) ) return self.filter(id__in=ids) def filter_for_user( self, user: User, permission: Permission = Permission.VIEW, use_groups: bool = True, public: bool = True, with_superuser: bool = True, ) -> models.QuerySet: """Filter objects for user. :attr user: the user which permissions should be considered. :attr permission: the lowest permission entity must have. :attr use_groups: when True consider also permissions of the user groups. :attr public: when True consider also public permission. :attr with_superuser: when false treat superuser as reguar user. """ from resolwe.permissions.utils import get_user # Circular import user = get_user(user) groups = user.groups.all() if use_groups else [] return self._filter_by_permission( user, groups, permission, public, with_superuser ) class PermissionObject(models.Model): """Base permission object. Every object that has permissions must inherit from this one. """ class Meta: """Make this class abstract so no new table is created for it.""" abstract = True #: permission group for the object permission_group = models.ForeignKey( PermissionGroup, on_delete=models.CASCADE, related_name="%(class)s", null=True ) #: custom manager with permission filtering methods. objects = PermissionQuerySet.as_manager() def __init__(self, *args, **kwargs): """Initialize.""" # The properties used to determine if object is in container. self._container_properties = ("collection", "entity") super().__init__(*args, **kwargs) def is_owner(self, user: User) -> bool: """Return if user is the owner of this instance.""" return self.has_permission(Permission.OWNER, user) def has_permission(self, permission: Permission, user: User): """Check if user has the given permission on the current object.""" return ( self._meta.model.objects.filter(pk=self.pk) .filter_for_user(user, permission) .exists() ) def set_permission(self, permission: Permission, user_or_group: UserOrGroup): """Set permission on this instance. It performs additional
# -*- coding: utf-8 -*- import logging from abc import ABC, abstractmethod import numpy as np import cvxpy as cp def cvx_desc_to_solver(solver_desc): if solver_desc == "SCS": return cp.SCS elif solver_desc == "MOSEK": return cp.MOSEK elif solver_desc == "CVXOPT": return cp.CVXOPT elif solver_desc == "OSQP": return cp.OSQP elif solver_desc == "ECOS": return cp.ECOS elif solver_desc == "CPLEX": return cp.CPLEX elif solver_desc == "CBC": return cp.CBC elif solver_desc == "NAG": return cp.NAG elif solver_desc == "GLPK": return cp.GLPK elif solver_desc == "GLPK_MI": return cp.GLPK_MI elif solver_desc == "GUROBI": return cp.GUROBI elif solver_desc == "SCIP": return cp.SCIP elif solver_desc == "XPRESS": return cp.XPRESS else: raise ValueError(f"Solver '{solver_desc}' is not supported or unkown.") class MathematicalProgram(): """Base class for a mathematical program. """ def __init__(self, **kwds): super().__init__(**kwds) @abstractmethod def solve(self): raise NotImplementedError() class SupportAffinePreprocessing(): """Base class for a mathematical programs that support an affine preprocessing. """ def __init__(self, **kwds): self.A = None self.b = None super().__init__(**kwds) def set_affine_preprocessing(self, A, b): self.A = A self.b = b def get_affine_preprocessing(self): return {"A": self.A, "b": self.b} def is_affine_preprocessing_set(self): return self.A is not None and self.b is not None def _apply_affine_preprocessing_to_var(self, var_x): if self.A is not None and self.b is not None: return self.A @ var_x + self.b else: return var_x def _apply_affine_preprocessing_to_const(self, x): if self.A is not None and self.b is not None: return np.dot(self.A, x) + self.b else: return x class ConvexQuadraticProgram(ABC, SupportAffinePreprocessing): """Base class for a convex quadratic program - for computing counterfactuals. Attributes ---------- epsilon : `float` "Small" non-negative number for relaxing strict inequalities. """ def __init__(self, **kwds): self.epsilon = 1e-2 self.solver = cp.SCS self.solver_verbosity = False super().__init__(**kwds) @abstractmethod def _build_constraints(self, var_x, y): """Creates and returns all constraints. Parameters ---------- var_x : `cvx.Variable` Optimization variable. y : `int` or `float` The requested prediction of the counterfactual - e.g. a class label. Returns ------- `list` List of cvxpy constraints. """ raise NotImplementedError() def _solve(self, prob): prob.solve(solver=self.solver, verbose=self.solver_verbosity) def build_solve_opt(self, x_orig, y, features_whitelist=None, mad=None, optimizer_args=None): """Builds and solves the convex quadratic optimization problem. Parameters ---------- x_orig : `numpy.ndarray` The original data point. y : `int` or `float` The requested prediction of the counterfactual - e.g. a class label. features_whitelist : `list(int)`, optional List of feature indices (dimensions of the input space) that can be used when computing the counterfactual. If `features_whitelist` is None, all features can be used. The default is None. mad : `numpy.ndarray`, optional Weights for the weighted Manhattan distance. If `mad` is None, the Euclidean distance is used. The default is None. optimizer_args : `dict`, optional Dictionary for overriding the default hyperparameters of the optimization algorithm. The default is None. Returns ------- `numpy.ndarray` The solution of the optimization problem. If no solution exists, `None` is returned. """ if optimizer_args is not None: if "epsilon" in optimizer_args: self.epsilon = optimizer_args["epsilon"] if "solver" in optimizer_args: self.solver = cvx_desc_to_solver(optimizer_args["solver"]) if "solver_verbosity" in optimizer_args: self.solver_verbosity = optimizer_args["solver_verbosity"] dim = x_orig.shape[0] # Variables x = cp.Variable(dim) beta = cp.Variable(dim) # Constants c = np.ones(dim) z = np.zeros(dim) I = np.eye(dim) # Construct constraints constraints = self._build_constraints(x, y) # If requested, fix some features if features_whitelist is not None: A = [] a = [] for j in range(dim): if j not in features_whitelist: t = np.zeros(dim) t[j] = 1. A.append(t) a.append(x_orig[j]) if len(A) != 0: A = np.array(A) a = np.array(a) constraints += [A @ x == a] # If necessary, construct the weight matrix for the weighted Manhattan distance Upsilon = None if mad is not None: alpha = 1. / mad Upsilon = np.diag(alpha) # Build the final program f = None if mad is not None: f = cp.Minimize(c.T @ beta) # Minimize (weighted) Manhattan distance constraints += [Upsilon @ (x - x_orig) <= beta, (-1. * Upsilon) @ (x - x_orig) <= beta, I @ beta >= z] else: f = cp.Minimize((1/2)*cp.quad_form(x, I) - x_orig.T@x) # Minimize L2 distance prob = cp.Problem(f, constraints) # Solve it! self._solve(prob) return x.value class SDP(ABC): """Base class for a semi-definite program (SDP) - for computing counterfactuals. Attributes ---------- epsilon : `float` "Small" non-negative number for relaxing strict inequalities. """ def __init__(self, **kwds): self.epsilon = 1e-2 self.solver = cp.SCS self.solver_verbosity = False super().__init__(**kwds) @abstractmethod def _build_constraints(self, var_X, var_x, y): """Creates and returns all constraints. Parameters ---------- var_X : `cvx.Variable` The artificial optimization variable X - a symmetric matrix (see paper for details). var_x : `cvx.Variable` Optimization variable. y : `int` or `float` The requested prediction of the counterfactual - e.g. a class label. Returns ------- `list` List of cvxpy constraints. """ raise NotImplementedError() def _solve(self, prob): prob.solve(solver=self.solver, verbose=self.solver_verbosity) def build_solve_opt(self, x_orig, y, features_whitelist=None, optimizer_args=None): """Builds and solves the SDP. Parameters ---------- x_orig : `numpy.ndarray` The original data point. y : `int` or `float` The requested prediction of the counterfactual - e.g. a class label. features_whitelist : `list(int)`, optional List of feature indices (dimensions of the input space) that can be used when computing the counterfactual. If `features_whitelist` is None, all features can be used. The default is None. optimizer_args : `dict`, optional Dictionary for overriding the default hyperparameters of the optimization algorithm. The default is None. Returns ------- `numpy.ndarray` The solution of the optimization problem. If no solution exists, `None` is returned. """ if optimizer_args is not None: if "epsilon" in optimizer_args: self.epsilon = optimizer_args["epsilon"] if "solver" in optimizer_args: self.solver = cvx_desc_to_solver(optimizer_args["solver"]) if "solver_verbosity" in optimizer_args: self.solver_verbosity = optimizer_args["solver_verbosity"] dim = x_orig.shape[0] # Variables X = cp.Variable((dim, dim), symmetric=True) x = cp.Variable((dim, 1)) one = np.array([[1]]).reshape(1, 1) I = np.eye(dim) # Construct constraints constraints = self._build_constraints(X, x, y) constraints += [cp.bmat([[X, x], [x.T, one]]) >> 0] # If requested, fix some features if features_whitelist is not None: A = [] a = [] for j in range(dim): if j not in features_whitelist: t = np.zeros(dim) t[j] = 1. A.append(t) a.append(x_orig[j]) if len(A) != 0: A = np.array(A) a = np.array(a) constraints += [A @ x == a] # Build the final program f = cp.Minimize(cp.trace(I @ X) - 2. * x.T @ x_orig) prob = cp.Problem(f, constraints) # Solve it! self._solve(prob) return x.value.reshape(dim) class DCQP(SupportAffinePreprocessing): """Class for a difference-of-convex-quadratic program (DCQP) - for computing counterfactuals. .. math:: \\underset{\\vec{x} \\in \\mathbb{R}^d}{\\min} \\vec{x}^\\top Q_0 \\vec{x} + \\vec{q}^\\top \\vec{x} + c - \\vec{x}^\\top Q_1 \\vec{x} \\quad \\text{s.t. } \\vec{x}^\\top A0_i \\vec{x} + \\vec{x}^\\top \\vec{b_i} + r_i - \\vec{x}^\\top A1_i \\vec{x} \\leq 0 \\; \\forall\\,i Attributes ---------- pccp : instance of :class:`ceml.optim.cvx.PenaltyConvexConcaveProcedure` Implementation of the penalty convex-concave procedure for approximately solving the DCQP. epsilon : `float` "Small" non-negative number for relaxing strict inequalities. """ def __init__(self, **kwds): self.pccp = None super().__init__(**kwds) def build_program(self, model, x_orig, y_target, Q0, Q1, q, c, A0_i, A1_i, b_i, r_i, features_whitelist=None, mad=None, optimizer_args=None): """Builds the DCQP. Parameters ---------- model : `object` The model that is used for computing the counterfactual - must provide a method `predict`. x : `numpy.ndarray` The data point `x` whose prediction has to be explained. y_target : `int` or `float` The requested prediction of the counterfactual - e.g. a class label. Q0 : `numpy.ndarray` The matrix Q_0 of the DCQP. Q1 : `numpy.ndarray` The matrix Q_1 of the DCQP. q : `numpy.ndarray` The vector q of the DCQP. c : `float` The constant c of the DCQP. A0_i : `list(numpy.ndarray)` List of matrices A0_i of the DCQP. A1_i : `list(numpy.ndarray)` List of matrices A1_i of the DCQP. b_i : `list(numpy.ndarray)` List of vectors b_i of the DCQP. r_i : `list(float)` List of constants r_i of the DCQP. features_whitelist : `list(int)`, optional List of feature indices (dimensions of the input space) that can be used when computing the counterfactual. If `features_whitelist` is None, all features can be used. The default is None. mad : `numpy.ndarray`, optional Weights for the weighted Manhattan distance. If `mad` is None, the Euclidean distance is
# -*- coding: utf-8 -*- """PyVisio documents - Visio Document manipulation module""" import logging from .visCOM import visCOMobject as vCOM #from visCOM import visCOMconstants as vC from .visCOM import com_error logging.info("documents loaded...") logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) class VisDocument(object): """ === VisDocument === Introduction ------------ This library is part of PyVisio package. It's purpose is handling of new Visio documents. Type of objects: Document object - https://msdn.microsoft.com/en-us/library/ff765575.aspx Pages object - https://msdn.microsoft.com/EN-US/library/office/ff766165.aspx Page object - https://msdn.microsoft.com/EN-US/library/office/ff767035.aspx Usage ----- Let's briefly go through the available functions. 1. Creating/Opening document 1. With no parameters New empty instance of Visio document will be created with default parameters >>> MyVisioDocument = VisDocument() >>> print MyVisioDocument #doctest:+ELLIPSIS <object VisDocument("") at... 2. With filename as template Filename will be used as template for new document, all content of filename will be copied to new document. Basically it's opening new Visio from template. We assume current working directory contains the data directory with samples. >>> import os >>> MyVisioDocument = VisDocument(os.getcwd() + "\data\sample_document.vsd") >>> print MyVisioDocument #doctest:+ELLIPSIS <object VisDocument("... 3. With filename and read-write flag set to true This is will load existing file for editing. Note: At this moment there are no plans to support editing Visio files as there is no business need for that, maybe in some next version :-) >>> MyVisioDocument = VisDocument(os.getcwd() + "\data\sample_document.vsd",rw=True) >>> print MyVisioDocument #doctest:+ELLIPSIS <object VisDocument("... of course if filename will be non existing document or there will be some problem loading the file exception will be raised >>> MyFailedVisioDocument = VisDocument("DoNotExist.vsd") #doctest:+ELLIPSIS Traceback (most recent call last): ... com_error: (... and some log lines will be written .. code-block: bash ERROR:__main__:Loading of document failed for: DoNotExist.vsd ERROR:__main__:COM Exception: (... 2. Reading and modifying (basic meta) properties As side effect of current implementation, you can access any of the document object properties, but if you really need to access those you should consider extending VisDocument object or creating your own module. Meta properties are those available in the Properties dialog box in Visio: Title, Subject, Creator (Author), Manager, Company, Categories, Tags, Comments,... It's possible to access these properties by their name as defined in Document object (see links) same way like accessing VisDocument object properties. >>> print MyVisioDocument.Company Sample Company >>> print MyVisioDocument.Creator Sample Author You'll get exception, if property doesn't exist and you want to change it >>> print MyVisioDocument.NonExistingProperty Traceback (most recent call last): ... AttributeError: NonExistingProperty and log entry .. code-block: bash ERROR:__main__:Property does not exist: NonExistingProperty It is possible to set these properties using VisDocument.setProperty(name, value) function >>> MyVisioDocument.setProperty("Creator", "Myself") >>> print MyVisioDocument.Creator Myself You'll get exception, if property doesn't exist and you want to change it >>> MyVisioDocument.setProperty("Creature","Someone") Traceback (most recent call last): ... AttributeError: Creature and log entry .. code-block: bash ERROR:__main__:Property does not exist: NonExistingProperty 3. Working with pages Getting number of pages in document >>> print len(MyVisioDocument) 1 Returned value is number of pages in Visio document Adding new page to the document >>> print MyVisioDocument.add() 2 Returned value is ID of the created page Adding named page to the document >>> print MyVisioDocument.add("TestPage") 3 Getting info about currently active page #TODO bug returned is not str but page object, when used for print it prints page.Name/NameU >>> print MyVisioDocument.active_page TestPage Returned is string containing the universal Name of page Changing active page using page name >>> MyVisioDocument.active_page = "Page-2" >>> print MyVisioDocument.active_page Page-2 Iterating the page names >>> for i in MyVisioDocument: ... print i Page-1 Page-2 TestPage Note: Internally Page.NameU property is used so localized names might be different. As I've no non-English version of Visio available, I can't test if this works correctly. Feedback from users welcome :-) Testing existence of page by name >>> if "TestPage" in MyVisioDocument: ... print "TestPage exists" TestPage exists 4. Accessing the pages To get Page object you could use VisDocument[page index or page name] returned object is Visio Page object 4.1 By page Index >>> Page = MyVisioDocument[3] >>> print Page.NameU TestPage 4.2 By page Name >>> Page = MyVisioDocument["TestPage"] >>> print Page.NameU TestPage In case wrong ID or page name will be used, exception will arrive >>> Page = MyVisioDocument["UnknownPage"] #doctest:+ELLIPSIS Traceback (most recent call last): ... com_error: (... Of Course page object itself is quite useless thing, but stay tuned, we'll add more functionality later on in other modules. And finally... 4. Saving / Discarding the changes Important note: New document can't be saved by save() function, instead use saveAs(filename). So first let's see what will happen when we save file with no name. >>> MyVisioDocument2 = VisDocument(os.getcwd() + "\data\sample_document.vsd") >>> MyVisioDocument2.save() #doctest:+ELLIPSIS Traceback (most recent call last): ... com_error: (... and of course some log line | ERROR:__main__:Failed to save document to file Correct usage of saveAs(filename). Let's save our example as sample_document1 >>> MyVisioDocument2.saveAs(os.getcwd() + "\data\sample_document1.vsd") From now on, we could use save() safely >>> MyVisioDocument2.save() See, this time all went with no error To print document on default printer with default setting use the printDefault() method >>> #MyVisioDocument.printDefault() # uncomment to kill the tree and see printout In case something will go wrong you'll get exception and log lines. To export to PDF use export() function. Default setting is following: Format=PDF, Intent=Print, Print=AllPages. See export() function docstring for more info. There are much more options available in Visio API, but let's stick for now to defaults. Note: This function might be unavailable in some older Visio versions. >>> MyVisioDocument.export(os.getcwd() + "\data\sample_document1.pdf") In case something will go wrong, you'll get exception and log lines. and finally after done with your work, you can close the file with close() function. By default Visio will ask what to do with changes you made if there are unsaved changes, if you do not save your changes intentionally you might call close(nosave=True) or simply close(True) >>> MyVisioDocument.close(True) We'll keep visio open with one of example documents we've created at the beginning, but in real program you'd use visCOMobject.Quit() method to close Visio instance. """ def __init__(self, filename="", rw=False): """ Create or open Visio file See https://msdn.microsoft.com/en-us/library/ff766868%28v=office.14%29.aspx :param filename: string - filename or "" :param rw: bool - if document should be opened as read-write """ self._filename = filename try: if rw == False: self._document = vCOM.Documents.Add(filename) else: self._document = vCOM.Documents.Open(filename) except com_error as reason: logger.error("Loading of document failed for: %s", filename) logger.error("COM Exception: %s", reason) raise self._pages = self._document.Pages def __str__(self): """ Return list style string representing list of loaded shapes :return: Str """ return self.__repr__() def __repr__(self): """ Return python style representation of object :return: Str """ return "<object VisDocument(\"{0}\") at {1}>".format(self._filename, hex(id(self))) def __getattr__(self, item): """ Get COM document object property This is kind of dirty trick (or genial idea...hard to say), __getattr__ will be called only in case other methods of getting property will fail. So simply said if python can't find property in VisDocument object it will call this function and we can inject the code which returns the Visio Document object properties :param item: :return: item value """ if hasattr(self._document, item): return getattr(self._document, item) else: logger.error("Property does not exist: %s", item) raise AttributeError(item) def __len__(self): """ Get number of pages in document :return: Int - Number of pages """ return self._pages.Count def setProperty(self, name, value): """ :param name: Str - Name of property :param value: - Value of property """ if hasattr(self._document, name): setattr(self._document, name, value) else: logger.error("Property does not exist: %s", name) raise AttributeError(name) def add(self, name=None): """ Add new page to the document Note: We set the AutoSize property to grow page if content will not fit to page :param name: Str - name of page :return: Int - Index of page in pages list """ try: new_page = self._pages.Add() except com_error as reason: logger.error("Page adding failed for page: %s", name) logger.error("COM Exception: %s",
import os import logging import torch import torch.nn as nn from torchvision.models.detection import maskrcnn_resnet50_fpn from torchvision.models.detection.faster_rcnn import FastRCNNPredictor from torchvision.models.detection.mask_rcnn import MaskRCNNPredictor import warnings import numpy as np from torch.backends import cudnn from torch.utils.tensorboard import SummaryWriter from tqdm import tqdm from pathlib import Path from datetime import datetime from ..utils import Dense_U_Net_lidar_helper as utils from ..datasets.FasterRCNNData import WaymoDataset_Loader # optimizes performance if input size same at each iteration cudnn.benchmark = True # Customized version of: https://github.com/moemen95/Pytorch-Project-Template/blob/master/agents/condensenet.py class Dense_U_Net_lidar_Agent: def __init__(self, config=None, torchvision_init=True, lidar=False): ''' Handles everything - training, validation testing - checkpoint loading and saving - logging | tensorboard summaries Accordingly everything is specified here - model - loss - optimizer - lr scheduling Arguments: torchvision_init: boolean - True: load densenet state dict from torchvision - False: load checkpoint; if no checkpoint just normal init ''' # in case config is empty it is created in model if config is None: self.config = utils.get_config() else: self.config = config self.logger = logging.getLogger('Agent') # model and config if lazy self.model = maskrcnn_resnet50_fpn(pretrained=True, progress=True, num_classes=91, # have to if pretrained pretrained_backbone=True, trainable_backbone_layers=5) # 0 being noe and 5 all # replace the pre-trained head with a new one num_classes = config.model.num_classes + 1 # classes + background in_features = self.model.roi_heads.box_predictor.cls_score.in_features self.model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes) # todo check if this is instance vs sematnic segmenation # and replace the mask predictor with a new one in_features_mask = self.model.roi_heads.mask_predictor.conv5_mask.in_channels hidden_layer = 256 self.model.roi_heads.mask_predictor = MaskRCNNPredictor(in_features_mask, hidden_layer, num_classes) self.lidar = lidar if self.lidar: # todo still have to fix tranformations before net -> model.transform # add one channel to first layer model_in_layer = self.model.backbone.body.conv1.state_dict() model_in_layer['weight'] = torch.cat( (model_in_layer['weight'], nn.init.kaiming_normal_(torch.ones((64, 1, 7, 7)))), dim=1) self.model.backbone.body.conv1 = nn.Conv2d(4, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False) self.model.backbone.body.conv1.load_state_dict(model_in_layer) # dataloader self.data_loader = WaymoDataset_Loader(self.config) # pixel-wise cross-entropy loss self.loss = torch.nn.BCEWithLogitsLoss(reduction='none').cuda() # optimizer self.optimizer = torch.optim.Adam(self.model.parameters(), lr=self.config.optimizer.learning_rate, betas=(self.config.optimizer.beta1, self.config.optimizer.beta2), eps=self.config.optimizer.eps, weight_decay=self.config.optimizer.weight_decay, amsgrad=self.config.optimizer.amsgrad) # learning rate decay scheduler if self.config.optimizer.lr_scheduler.want: self.lr_scheduler = torch.optim.lr_scheduler.StepLR(self.optimizer, step_size=self.config.optimizer.lr_scheduler.every_n_epochs, gamma=self.config.optimizer.lr_scheduler.gamma) # initialize counters; updated in load_checkpoint self.current_epoch = 0 self.current_train_iteration = 0 self.current_val_iteration = 0 self.best_val_iou = 0 # if cuda is available export model to gpu self.cuda = torch.cuda.is_available() if self.cuda: self.device = torch.device('cuda') torch.cuda.manual_seed_all(self.config.agent.seed) self.logger.info('Operation will be on *****GPU-CUDA***** ') else: self.device = torch.device('cpu') torch.manual_seed(self.config.agent.seed) self.logger.info('Operation will be on *****CPU***** ') self.model = self.model.to(self.device) self.loss = self.loss.to(self.device) if not torchvision_init: self.load_checkpoint() # Tensorboard Writers Path(self.config.dir.current_run.summary).mkdir(exist_ok=True, parents=True) self.train_summary_writer = SummaryWriter(log_dir=self.config.dir.current_run.summary, comment='FasterRCNNResNet50') self.val_summary_writer = SummaryWriter(log_dir=self.config.dir.current_run.summary, comment='FasterRCNNResNet50') def save_checkpoint(self, filename='checkpoint.pth.tar', is_best=False): ''' Saving the latest checkpoint of the training Arguments: filename: filename which will contain the state is_best: flag is it is the best model ''' # aggregate important data state = { self.config.agent.checkpoint.epoch: self.current_epoch, self.config.agent.checkpoint.train_iteration: self.current_train_iteration, self.config.agent.checkpoint.val_iteration: self.current_val_iteration, self.config.agent.checkpoint.best_val_iou: self.best_val_iou, self.config.agent.checkpoint.state_dict: self.model.state_dict(), self.config.agent.checkpoint.optimizer: self.optimizer.state_dict() } if is_best: filename = self.config.agent.best_checkpoint_name # create dir if not exists Path(self.config.dir.current_run.checkpoints).mkdir(exist_ok=True, parents=True) # Save the state torch.save(state, os.path.join(self.config.dir.current_run.checkpoints, filename)) def load_checkpoint(self, filename=None): ''' load checkpoint from file should contain following keys: 'epoch', 'iteration', 'best_val_iou', 'state_dict', 'optimizer' where state_dict is model statedict and optimizer is optimizer statesict Arguments: filename: only name with file type extension | path in config.dir.current_run.checkpoints ''' # use best if not specified if filename is None: filename = self.config.agent.best_checkpoint_name # load according to key filepath = os.path.join(self.config.dir.current_run.checkpoints, filename) try: self.logger.info('Loading checkpoint {}'.format(filename)) checkpoint = torch.load(filepath) self.current_epoch = checkpoint[self.config.agent.checkpoint.epoch] self.current_train_iteration = checkpoint[ self.config.agent.checkpoint.train_iteration] self.current_val_iteration = checkpoint[ self.config.agent.checkpoint.val_iteration] self.best_val_iou = checkpoint[ self.config.agent.checkpoint.best_val_iou] self.model.load_state_dict(checkpoint[ self.config.agent.checkpoint.state_dict]) self.optimizer.load_state_dict(checkpoint[ self.config.agent.checkpoint.optimizer]) self.logger.info('Checkpoint loaded successfully from {} at (epoch {}) at (iteration {})\n' .format(self.config.dir.current_run.checkpoints, checkpoint['epoch'], checkpoint['train_iteration'])) except OSError: warnings.warn('No checkpoint exists from {}. Skipping...'.format(filepath)) self.logger.info('No checkpoint exists from {}. Skipping...'.format(filepath)) self.logger.info('**First time to train**') def run(self): ''' starts training are testing: specify under config.loader.mode can handle keyboard interupt ''' print('starting ' + self.config.loader.mode + ' at ' + str(datetime.now())) try: if self.config.loader.mode == 'test': with torch.no_grad(): self.validate() else: self.train() except KeyboardInterrupt: self.logger.info('You have entered CTRL+C.. Wait to finalize') def train(self): ''' training one epoch at a time validating after each epoch saving checkpoint after each epoch check if val acc is best and store separately ''' # add selected loss and optimizer to config | not added in init as may be changed before training self.config.loss.func = str(self.loss) self.config.optimizer.func = str(self.optimizer) # make sure to remember the hyper params # self.add_hparams_summary_writer() # self.save_hparams_json() # Iterate epochs | train one epoch | validate | save checkpoint for epoch in range(self.current_epoch, self.config.agent.max_epoch): self.current_epoch = epoch self.train_one_epoch() with torch.no_grad(): avg_val_iou_per_class = self.validate() val_iou = sum(avg_val_iou_per_class) / len(avg_val_iou_per_class) is_best = val_iou > self.best_val_iou if is_best: self.best_val_iou = val_iou self.save_checkpoint(is_best=is_best) self.train_summary_writer.close() self.val_summary_writer.close() def train_one_epoch(self): ''' One epoch training function ''' # Initialize progress visualization and get batch tqdm_batch = tqdm(self.data_loader.train_loader, total=self.data_loader.train_iterations, desc='Epoch-{}-'.format(self.current_epoch)) # Set the model to be in training mode self.model.train() # metric counters current_batch = 0 number_of_batches = self.data_loader.train_loader.dataset.__len__() epoch_loss = torch.zeros(number_of_batches).to(self.device) for image, lidar, _, targets in tqdm_batch: # push to gpu if possible if self.cuda: image = image.cuda(non_blocking=self.config.loader.async_loading) lidar = lidar.cuda(non_blocking=self.config.loader.async_loading) for k in range(len(targets)): targets[k]['masks'] = targets[k]['masks'].cuda(non_blocking=self.config.loader.async_loading) targets[k]['boxes'] = targets[k]['boxes'].cuda(non_blocking=self.config.loader.async_loading) targets[k]['labels'] = targets[k]['labels'].cuda(non_blocking=self.config.loader.async_loading) # forward pass ''' During training, the model expects both the input tensors, as well as a targets (list of dictionary), containing: - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with values of ``x`` between ``0`` and ``W`` and values of ``y`` between ``0`` and ``H`` - labels (``Int64Tensor[N]``): the class label for each ground-truth box - masks (``UInt8Tensor[N, H, W]``): the segmentation binary masks for each instance The model returns a ``Dict[Tensor]`` during training, containing the classification and regression losses for both the RPN and the R-CNN, and the mask loss. ''' model_input = torch.cat((image, lidar), dim=1) if self.lidar else image loss_dict = self.model(model_input, targets) losses = sum(loss for loss in loss_dict.values()) self.optimizer.zero_grad() losses.backward() self.optimizer.step() epoch_loss[current_batch] = losses.detach() self.train_summary_writer.add_scalars('Training/Loss', {'avg': epoch_loss[current_batch]}, self.current_train_iteration) # counters self.current_train_iteration += 1 current_batch += 1 tqdm_batch.close() # learning rate decay update; after validate; after each epoch if self.config.optimizer.lr_scheduler.want: self.lr_scheduler.step() # log avg_epoch_loss = torch.mean(epoch_loss, axis=0).tolist() self.logger.info('Training at Epoch-' + str(self.current_epoch) + ' | ' + 'Average Loss: ' + str( avg_epoch_loss)) def validate(self): ''' One epoch validation return: average IoU per class ''' # Initialize progress visualization and get batch # !self.data_loader.valid_loader works for both valid and test tqdm_batch = tqdm(self.data_loader.valid_loader, total=self.data_loader.valid_iterations, desc='Valiation at -{}-'.format(self.current_epoch)) # set the model in training mode self.model.eval() # metric counters current_batch = 0 number_of_batches = self.data_loader.valid_loader.dataset.__len__() epoch_loss = torch.zeros((number_of_batches, self.config.model.num_classes)).to(self.device) epoch_iou = torch.zeros((number_of_batches, self.config.model.num_classes)) epoch_iou_nans = torch.zeros((number_of_batches, self.config.model.num_classes)) epoch_acc = torch.zeros((number_of_batches, self.config.model.num_classes)).to(self.device) for image, lidar, ht_map, _ in tqdm_batch: # push to gpu if possible if self.cuda: image = image.cuda(non_blocking=self.config.loader.async_loading) lidar = lidar.cuda(non_blocking=self.config.loader.async_loading) ht_map = ht_map.cuda(non_blocking=self.config.loader.async_loading) # forward pass ''' During inference, the model requires only the input tensors, and returns the post-processed predictions as a ``List[Dict[Tensor]]``, one for each input image. The fields of the ``Dict`` are as follows: - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with values of ``x`` between ``0`` and ``W`` and values of ``y`` between ``0`` and ``H`` - labels (``Int64Tensor[N]``): the predicted labels for each image - scores (``Tensor[N]``): the scores or each prediction - masks (``UInt8Tensor[N, 1, H, W]``): the predicted masks for each instance, in ``0-1`` range. In order to obtain the final segmentation masks, the soft masks can be thresholded, generally with a value of 0.5 (``mask >= 0.5``) ''' model_input = torch.cat((image, lidar), dim=1) if self.lidar else image prediction_list = self.model(model_input) # TODO alt version thresholding masks and then same # in 2nd dim change values into dimensions # -> join masks of same type -> torch.max(masks[indeces_predicted_class], dim=...) prediction = torch.zeros_like(ht_map) for sample_i, sample_prediction in enumerate(prediction_list): for obj_class in [0, 1, 2]: class_idx = sample_prediction['labels'] == obj_class if torch.any(class_idx): prediction[sample_i, obj_class], _ = torch.max(sample_prediction['masks'][class_idx], dim=0) # pixel-wise loss current_loss = self.loss(prediction, ht_map) loss_per_class = torch.sum(current_loss.detach(), dim=(0, 2, 3)) epoch_loss[current_batch, :] = loss_per_class # whole image IoU per class; not taking nans into acc for the mean value;
0.00435488, 'Renaming Unit/Int Front End RAT/Subthreshold Leakage with power gating': 0.00248228, 'Renaming Unit/Peak Dynamic': 3.58947, 'Renaming Unit/Runtime Dynamic': 0.172739, 'Renaming Unit/Subthreshold Leakage': 0.0552466, 'Renaming Unit/Subthreshold Leakage with power gating': 0.0276461, 'Runtime Dynamic': 3.57947, 'Subthreshold Leakage': 6.16288, 'Subthreshold Leakage with power gating': 2.55328}, {'Area': 32.0201, 'Execution Unit/Area': 7.68434, 'Execution Unit/Complex ALUs/Area': 0.235435, 'Execution Unit/Complex ALUs/Gate Leakage': 0.0132646, 'Execution Unit/Complex ALUs/Peak Dynamic': 0.017421, 'Execution Unit/Complex ALUs/Runtime Dynamic': 0.216372, 'Execution Unit/Complex ALUs/Subthreshold Leakage': 0.20111, 'Execution Unit/Complex ALUs/Subthreshold Leakage with power gating': 0.0754163, 'Execution Unit/Floating Point Units/Area': 4.6585, 'Execution Unit/Floating Point Units/Gate Leakage': 0.0656156, 'Execution Unit/Floating Point Units/Peak Dynamic': 0.0958656, 'Execution Unit/Floating Point Units/Runtime Dynamic': 0.304033, 'Execution Unit/Floating Point Units/Subthreshold Leakage': 0.994829, 'Execution Unit/Floating Point Units/Subthreshold Leakage with power gating': 0.373061, 'Execution Unit/Gate Leakage': 0.120359, 'Execution Unit/Instruction Scheduler/Area': 1.66526, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Area': 0.275653, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Gate Leakage': 0.000977433, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Peak Dynamic': 1.04181, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Runtime Dynamic': 0.21304, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage': 0.0143453, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage with power gating': 0.00810519, 'Execution Unit/Instruction Scheduler/Gate Leakage': 0.00568913, 'Execution Unit/Instruction Scheduler/Instruction Window/Area': 0.805223, 'Execution Unit/Instruction Scheduler/Instruction Window/Gate Leakage': 0.00414562, 'Execution Unit/Instruction Scheduler/Instruction Window/Peak Dynamic': 1.6763, 'Execution Unit/Instruction Scheduler/Instruction Window/Runtime Dynamic': 0.343625, 'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage': 0.0625755, 'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage with power gating': 0.0355964, 'Execution Unit/Instruction Scheduler/Peak Dynamic': 3.82262, 'Execution Unit/Instruction Scheduler/ROB/Area': 0.584388, 'Execution Unit/Instruction Scheduler/ROB/Gate Leakage': 0.00056608, 'Execution Unit/Instruction Scheduler/ROB/Peak Dynamic': 1.10451, 'Execution Unit/Instruction Scheduler/ROB/Runtime Dynamic': 0.173451, 'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage': 0.00906853, 'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage with power gating': 0.00364446, 'Execution Unit/Instruction Scheduler/Runtime Dynamic': 0.730116, 'Execution Unit/Instruction Scheduler/Subthreshold Leakage': 0.0859892, 'Execution Unit/Instruction Scheduler/Subthreshold Leakage with power gating': 0.047346, 'Execution Unit/Integer ALUs/Area': 0.47087, 'Execution Unit/Integer ALUs/Gate Leakage': 0.0265291, 'Execution Unit/Integer ALUs/Peak Dynamic': 0.228957, 'Execution Unit/Integer ALUs/Runtime Dynamic': 0.101344, 'Execution Unit/Integer ALUs/Subthreshold Leakage': 0.40222, 'Execution Unit/Integer ALUs/Subthreshold Leakage with power gating': 0.150833, 'Execution Unit/Peak Dynamic': 4.43883, 'Execution Unit/Register Files/Area': 0.570804, 'Execution Unit/Register Files/Floating Point RF/Area': 0.208131, 'Execution Unit/Register Files/Floating Point RF/Gate Leakage': 0.000232788, 'Execution Unit/Register Files/Floating Point RF/Peak Dynamic': 0.0181111, 'Execution Unit/Register Files/Floating Point RF/Runtime Dynamic': 0.00893585, 'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage': 0.00399698, 'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage with power gating': 0.00176968, 'Execution Unit/Register Files/Gate Leakage': 0.000622708, 'Execution Unit/Register Files/Integer RF/Area': 0.362673, 'Execution Unit/Register Files/Integer RF/Gate Leakage': 0.00038992, 'Execution Unit/Register Files/Integer RF/Peak Dynamic': 0.0710667, 'Execution Unit/Register Files/Integer RF/Runtime Dynamic': 0.0660861, 'Execution Unit/Register Files/Integer RF/Subthreshold Leakage': 0.00614175, 'Execution Unit/Register Files/Integer RF/Subthreshold Leakage with power gating': 0.00246675, 'Execution Unit/Register Files/Peak Dynamic': 0.0891778, 'Execution Unit/Register Files/Runtime Dynamic': 0.0750219, 'Execution Unit/Register Files/Subthreshold Leakage': 0.0101387, 'Execution Unit/Register Files/Subthreshold Leakage with power gating': 0.00423643, 'Execution Unit/Results Broadcast Bus/Area Overhead': 0.0390912, 'Execution Unit/Results Broadcast Bus/Gate Leakage': 0.00537402, 'Execution Unit/Results Broadcast Bus/Peak Dynamic': 0.154074, 'Execution Unit/Results Broadcast Bus/Runtime Dynamic': 0.408842, 'Execution Unit/Results Broadcast Bus/Subthreshold Leakage': 0.081478, 'Execution Unit/Results Broadcast Bus/Subthreshold Leakage with power gating': 0.0305543, 'Execution Unit/Runtime Dynamic': 1.83573, 'Execution Unit/Subthreshold Leakage': 1.79543, 'Execution Unit/Subthreshold Leakage with power gating': 0.688821, 'Gate Leakage': 0.368936, 'Instruction Fetch Unit/Area': 5.85939, 'Instruction Fetch Unit/Branch Predictor/Area': 0.138516, 'Instruction Fetch Unit/Branch Predictor/Chooser/Area': 0.0435221, 'Instruction Fetch Unit/Branch Predictor/Chooser/Gate Leakage': 0.000278362, 'Instruction Fetch Unit/Branch Predictor/Chooser/Peak Dynamic': 0.0168831, 'Instruction Fetch Unit/Branch Predictor/Chooser/Runtime Dynamic': 0.00287308, 'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage': 0.00759719, 'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage with power gating': 0.0039236, 'Instruction Fetch Unit/Branch Predictor/Gate Leakage': 0.000757657, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Area': 0.0435221, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Gate Leakage': 0.000278362, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Peak Dynamic': 0.0168831, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Runtime Dynamic': 0.00287308, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage': 0.00759719, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage with power gating': 0.0039236, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Area': 0.0257064, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Gate Leakage': 0.000154548, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Peak Dynamic': 0.0142575, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Runtime Dynamic': 0.0025297, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage': 0.00384344, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage with power gating': 0.00198631, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Area': 0.0151917, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Gate Leakage': 8.00196e-05, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Peak Dynamic': 0.00527447, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Runtime Dynamic': 0.000994196, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage': 0.00181347, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage with power gating': 0.000957045, 'Instruction Fetch Unit/Branch Predictor/Peak Dynamic': 0.0597838, 'Instruction Fetch Unit/Branch Predictor/RAS/Area': 0.0105732, 'Instruction Fetch Unit/Branch Predictor/RAS/Gate Leakage': 4.63858e-05, 'Instruction Fetch Unit/Branch Predictor/RAS/Peak Dynamic': 0.0117602, 'Instruction Fetch Unit/Branch Predictor/RAS/Runtime Dynamic': 0.000949332, 'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage': 0.000932505, 'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage with power gating': 0.000494733, 'Instruction Fetch Unit/Branch Predictor/Runtime Dynamic': 0.00922519, 'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage': 0.0199703, 'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage with power gating': 0.0103282, 'Instruction Fetch Unit/Branch Target Buffer/Area': 0.64954, 'Instruction Fetch Unit/Branch Target Buffer/Gate Leakage': 0.00272758, 'Instruction Fetch Unit/Branch Target Buffer/Peak Dynamic': 0.177867, 'Instruction Fetch Unit/Branch Target Buffer/Runtime Dynamic': 0.0265731, 'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage': 0.0811682, 'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage with power gating': 0.0435357, 'Instruction Fetch Unit/Gate Leakage': 0.0589979, 'Instruction Fetch Unit/Instruction Buffer/Area': 0.0226323, 'Instruction Fetch Unit/Instruction Buffer/Gate Leakage': 6.83558e-05, 'Instruction Fetch Unit/Instruction Buffer/Peak Dynamic': 0.606827, 'Instruction Fetch Unit/Instruction Buffer/Runtime Dynamic': 0.0635302, 'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage': 0.00151885, 'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage with power gating': 0.000701682, 'Instruction Fetch Unit/Instruction Cache/Area': 3.14635, 'Instruction Fetch Unit/Instruction Cache/Gate Leakage': 0.029931, 'Instruction Fetch Unit/Instruction Cache/Peak Dynamic': 4.04107, 'Instruction Fetch Unit/Instruction Cache/Runtime Dynamic': 0.137871, 'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage': 0.367022, 'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage with power gating': 0.180386, 'Instruction Fetch Unit/Instruction Decoder/Area': 1.85799, 'Instruction Fetch Unit/Instruction Decoder/Gate Leakage': 0.0222493, 'Instruction Fetch Unit/Instruction Decoder/Peak Dynamic': 1.37404, 'Instruction Fetch Unit/Instruction Decoder/Runtime Dynamic': 0.215777, 'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage': 0.442943, 'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage with power gating': 0.166104, 'Instruction Fetch Unit/Peak Dynamic': 6.4557, 'Instruction Fetch Unit/Runtime Dynamic': 0.452977, 'Instruction Fetch Unit/Subthreshold Leakage': 0.932286, 'Instruction Fetch Unit/Subthreshold Leakage with power gating': 0.40843, 'L2/Area': 4.53318, 'L2/Gate Leakage': 0.015464, 'L2/Peak Dynamic': 0.0610716, 'L2/Runtime Dynamic': 0.015899, 'L2/Subthreshold Leakage': 0.834142, 'L2/Subthreshold Leakage with power gating': 0.401066, 'Load Store Unit/Area': 8.80901, 'Load Store Unit/Data Cache/Area': 6.84535, 'Load Store Unit/Data Cache/Gate Leakage': 0.0279261, 'Load Store Unit/Data Cache/Peak Dynamic': 3.07716, 'Load Store Unit/Data Cache/Runtime Dynamic': 0.89597, 'Load Store Unit/Data Cache/Subthreshold Leakage': 0.527675, 'Load Store Unit/Data Cache/Subthreshold Leakage with power gating': 0.25085, 'Load Store Unit/Gate Leakage': 0.0350888, 'Load Store Unit/LoadQ/Area': 0.0836782, 'Load Store Unit/LoadQ/Gate Leakage': 0.00059896, 'Load Store Unit/LoadQ/Peak Dynamic': 0.0595297, 'Load Store Unit/LoadQ/Runtime Dynamic': 0.0595298, 'Load Store Unit/LoadQ/Subthreshold Leakage': 0.00941961, 'Load Store Unit/LoadQ/Subthreshold Leakage with power gating': 0.00536918, 'Load Store Unit/Peak Dynamic': 3.35827, 'Load Store Unit/Runtime Dynamic': 1.24908, 'Load Store Unit/StoreQ/Area': 0.322079, 'Load Store Unit/StoreQ/Gate Leakage': 0.00329971, 'Load Store Unit/StoreQ/Peak Dynamic': 0.14679, 'Load Store Unit/StoreQ/Runtime Dynamic': 0.293581, 'Load Store Unit/StoreQ/Subthreshold Leakage': 0.0345621, 'Load Store Unit/StoreQ/Subthreshold Leakage with power gating': 0.0197004, 'Load Store Unit/Subthreshold Leakage': 0.591321, 'Load Store Unit/Subthreshold Leakage with power gating': 0.283293, 'Memory Management Unit/Area': 0.4339, 'Memory Management Unit/Dtlb/Area': 0.0879726, 'Memory Management Unit/Dtlb/Gate Leakage': 0.00088729, 'Memory Management Unit/Dtlb/Peak Dynamic': 0.0520963, 'Memory Management Unit/Dtlb/Runtime Dynamic': 0.0529689, 'Memory Management Unit/Dtlb/Subthreshold Leakage': 0.0155699, 'Memory Management Unit/Dtlb/Subthreshold Leakage with power gating': 0.00887485, 'Memory Management Unit/Gate Leakage': 0.00808595, 'Memory Management Unit/Itlb/Area': 0.301552, 'Memory Management Unit/Itlb/Gate Leakage': 0.00393464, 'Memory Management Unit/Itlb/Peak Dynamic': 0.251259, 'Memory Management Unit/Itlb/Runtime Dynamic': 0.0227343, 'Memory Management Unit/Itlb/Subthreshold Leakage': 0.0413758, 'Memory Management Unit/Itlb/Subthreshold Leakage with power gating': 0.0235842, 'Memory Management Unit/Peak Dynamic': 0.49686, 'Memory Management Unit/Runtime Dynamic': 0.0757032, 'Memory Management Unit/Subthreshold Leakage': 0.0766103, 'Memory Management Unit/Subthreshold Leakage with power gating': 0.0398333, 'Peak Dynamic': 18.4002, 'Renaming Unit/Area': 0.303608, 'Renaming Unit/FP Front End RAT/Area': 0.131045, 'Renaming Unit/FP Front End RAT/Gate Leakage': 0.00351123, 'Renaming Unit/FP Front End RAT/Peak Dynamic': 2.51468, 'Renaming Unit/FP Front End RAT/Runtime Dynamic': 0.0476425, 'Renaming Unit/FP Front End RAT/Subthreshold Leakage': 0.0308571, 'Renaming Unit/FP Front End RAT/Subthreshold Leakage with power gating': 0.0175885, 'Renaming Unit/Free List/Area': 0.0340654, 'Renaming Unit/Free List/Gate Leakage': 2.5481e-05, 'Renaming Unit/Free List/Peak Dynamic': 0.0306032, 'Renaming Unit/Free List/Runtime Dynamic': 0.0101916, 'Renaming Unit/Free List/Subthreshold Leakage': 0.000370144, 'Renaming Unit/Free List/Subthreshold Leakage with power gating': 0.000201064, 'Renaming Unit/Gate Leakage': 0.00708398, 'Renaming Unit/Int Front End RAT/Area': 0.0941223, 'Renaming Unit/Int Front End RAT/Gate Leakage': 0.000283242, 'Renaming Unit/Int Front End RAT/Peak Dynamic': 0.731965, 'Renaming Unit/Int Front End RAT/Runtime Dynamic': 0.106236, 'Renaming Unit/Int Front End RAT/Subthreshold Leakage': 0.00435488,
r'%s:%s(?:\?%s)?(?:#%s)?' % (scheme, hier_part, query, fragment) URI_reference = r'(?:%s|%s)' % (URI, relative_ref) STRICT_URI_PYREGEX = r"\A%s\Z" % URI STRICT_URIREF_PYREGEX = r"\A(?!\n)%s\Z" % URI_reference global URI_PATTERN, URI_REF_PATTERN URI_PATTERN = re.compile(STRICT_URI_PYREGEX) # strict checking for URIs URI_REF_PATTERN = re.compile(STRICT_URIREF_PYREGEX) # strict checking for URI refs _validation_setup_completed = True return def matches_uri_ref_syntax(s): """ This function returns true if the given string could be a URI reference, as defined in RFC 3986, just based on the string's syntax. A URI reference can be a URI or certain portions of one, including the empty string, and it can have a fragment component. """ if not _validation_setup_completed: _init_uri_validation_regex() return URI_REF_PATTERN.match(s) is not None def matches_uri_syntax(s): """ This function returns true if the given string could be a URI, as defined in RFC 3986, just based on the string's syntax. A URI is by definition absolute (begins with a scheme) and does not end with a #fragment. It also must adhere to various other syntax rules. """ if not _validation_setup_completed: _init_uri_validation_regex() return URI_PATTERN.match(s) is not None _split_uri_ref_setup_completed = False def _init_split_uri_ref_pattern(): """ Called internally to compile the regular expression used by split_uri_ref() just once, the first time the function is called. """ global _split_uri_ref_setup_completed if _split_uri_ref_setup_completed: return # Like the others, this regex is also in the public domain. # It is based on this one, from RFC 3986 appendix B # (unchanged from RFC 2396 appendix B): # ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))? regex = r"^(?:(?P<scheme>[^:/?#]+):)?(?://(?P<authority>[^/?#]*))?(?P<path>[^?#]*)(?:\?(?P<query>[^#]*))?(?:#(?P<fragment>.*))?$" global SPLIT_URI_REF_PATTERN SPLIT_URI_REF_PATTERN = re.compile(regex) _split_uri_ref_setup_completed = True return def split_uri_ref(iri_ref): """ Given a valid URI reference as a string, returns a tuple representing the generic URI components, as per RFC 3986 appendix B. The tuple's structure is (scheme, authority, path, query, fragment). All values will be strings (possibly empty) or None if undefined. Note that per RFC 3986, there is no distinction between a path and an "opaque part", as there was in RFC 2396. """ if not _split_uri_ref_setup_completed: _init_split_uri_ref_pattern() # the pattern will match every possible string, so it's safe to # assume there's a groupdict method to call. g = SPLIT_URI_REF_PATTERN.match(iri_ref).groupdict() scheme = g['scheme'] authority = g['authority'] path = g['path'] query = g['query'] fragment = g['fragment'] return (scheme, authority, path, query, fragment) def unsplit_uri_ref(iri_refSeq): """ Given a sequence as would be produced by split_uri_ref(), assembles and returns a URI reference as a string. """ if not isinstance(iri_refSeq, (tuple, list)): raise TypeError(_("sequence expected, got %s" % type(iri_refSeq))) (scheme, authority, path, query, fragment) = iri_refSeq uri = '' if scheme is not None: uri += scheme + ':' if authority is not None: uri += '//' + authority uri += path if query is not None: uri += '?' + query if fragment is not None: uri += '#' + fragment return uri _split_authority_setup_completed = False def _init_split_authority_pattern(): """ Called internally to compile the regular expression used by split_authority() just once, the first time the function is called. """ global _split_authority_setup_completed if _split_authority_setup_completed: return global SPLIT_AUTHORITY_PATTERN regex = r'(?:(?P<userinfo>[^@]*)@)?(?P<host>[^:]*)(?::(?P<port>.*))?' SPLIT_AUTHORITY_PATTERN = re.compile(regex) _split_authority_setup_completed = True return def split_authority(authority): """ Given a string representing the authority component of a URI, returns a tuple consisting of the subcomponents (userinfo, host, port). No percent-decoding is performed. """ if not _split_authority_setup_completed: _init_split_authority_pattern() m = SPLIT_AUTHORITY_PATTERN.match(authority) if m: return m.groups() else: return (None, authority, None) def split_fragment(uri): """ Given a URI or URI reference, returns a tuple consisting of (base, fragment), where base is the portion before the '#' that precedes the fragment component. """ # The only '#' in a legit URI will be the fragment separator, # but in the wild, people get sloppy. Assume the last '#' is it. pos = uri.rfind('#') if pos == -1: return (uri, uri[:0]) else: return (uri[:pos], uri[pos+1:]) # "unreserved" characters are allowed in a URI, and do not have special # meaning as delimiters of URI components or subcomponents. They may # appear raw or percent-encoded, but percent-encoding is discouraged. # This set of characters is sufficiently long enough that using a # compiled regex is faster than using a string with the "in" operator. #UNRESERVED_PATTERN = re.compile(r"[0-9A-Za-z\-\._~!*'()]") # RFC 2396 UNRESERVED_PATTERN = re.compile(r'[0-9A-Za-z\-\._~]') # RFC 3986 # "reserved" characters are allowed in a URI, but they may or always do # have special meaning as delimiters of URI components or subcomponents. # When being used as delimiters, they must be raw, and when not being # used as delimiters, they must be percent-encoded. # This set of characters is sufficiently short enough that using a # string with the "in" operator is faster than using a compiled regex. # The characters in the string are ordered according to how likely they # are to be found (approximately), for faster operation with "in". #RESERVED = "/&=+?;@,:$[]" # RFC 2396 + RFC 2732 RESERVED = "/=&+?#;@,:$!*[]()'" # RFC 3986 def percent_encode(s, encoding='utf-8', encodeReserved=True, spaceToPlus=False, nlChars=None, reservedChars=RESERVED): """ [*** Experimental API ***] This function applies percent-encoding, as described in RFC 3986 sec. 2.1, to the given string, in order to prepare the string for use in a URI. It replaces characters that are not allowed in a URI. By default, it also replaces characters in the reserved set, which normally includes the generic URI component delimiters ":" "/" "?" \"#\" "[" "]" "@" and the subcomponent delimiters "!" "$" "&" "\'" "(" ")" "*" "+" "," ";" "=". Ideally, this function should be used on individual components or subcomponents of a URI prior to assembly of the complete URI, not afterward, because this function has no way of knowing which characters in the reserved set are being used for their reserved purpose and which are part of the data. By default it assumes that they are all being used as data, thus they all become percent-encoded. The characters in the reserved set can be overridden from the default by setting the reservedChars argument. The percent-encoding of characters in the reserved set can be disabled by unsetting the encodeReserved flag. Do this if the string is an already-assembled URI or a URI component, such as a complete path. The encoding argument will be used to determine the percent-encoded octets for characters that are not in the U+0000 to U+007F range. The codec identified by the encoding argument must return a byte string. The spaceToPlus flag controls whether space characters are changed to "+" characters in the result, rather than being percent-encoded. Generally, this is not required, and given the status of "+" as a reserved character, is often undesirable. But it is required in certain situations, such as when generating application/x-www-form-urlencoded content or RFC 3151 public identifier URNs, so it is supported here. The nlChars argument, if given, is a sequence type in which each member is a substring that indicates a "new line". Occurrences of this substring will be replaced by '%0D%0A' in the result, as is required when generating application/x-www-form-urlencoded content. This function is similar to urllib.quote(), but is more conformant and Unicode-friendly. Suggestions for improvements welcome. >>> from amara3 import iri >>> iri.percent_encode('http://bibfra.me/vocab/relation/論定') http%3A%2F%2Fbibfra.me%2Fvocab%2Frelation%2F%E8%AB%96%E5%AE%9A """ res = '' if nlChars is not None: for c in nlChars: s.replace(c, '\r\n') #FIXME: use re.subn with substitution function for big speed-up for c in s: # surrogates? -> percent-encode according to given encoding if UNRESERVED_PATTERN.match(c) is None: cp = ord(c) # ASCII range? if cp < 128: # space? -> plus if desired if spaceToPlus and c == ' ': res += '+' # reserved? -> percent-encode if desired elif c in reservedChars: if encodeReserved: res += '%%%02X' % cp else: res += c # not unreserved or reserved, so percent-encode # FIXME: should percent-encode according to given encoding; # ASCII range is not special! else: res += '%%%02X' % cp # non-ASCII-range unicode? else: # percent-encode according to given encoding for octet in c.encode(encoding): res += '%%%02X' % octet # unreserved -> safe to use as-is else: res += c return res _ASCII_PAT = re.compile('([\x00-\x7f]+)') _HEXDIG = '0123456789ABCDEFabcdef' _HEXTOBYTE = None def _unquote_to_bytes(s, decodable=None):
to be caught. Can be as generic as `AsanaError`, but testing for something more specific is better to improve coverage. log_index (int): The index to check in caplog for the desired exception log message. func (function): The reference to the function to call to test. *args ([any]): The positional arguments to pass to the function to test `func`. **kwargs ({str:any}): The keyword arguments to pass to teh function to test `func`. """ caplog.clear() with pytest.raises(exception_type): func(*args, **kwargs) assert caplog.record_tuples[log_index][0] == 'asana_extensions.asana.client' assert caplog.record_tuples[log_index][1] == logging.ERROR assert 'API query failed' in caplog.messages[log_index] @pytest.mark.no_warnings_only def test_logging_capture_warnings(caplog): """ This tests that the `logging.captureWarnings(True)` line has been executed in the `aclient` module. This must be run with the `-p no:warnings` option provided to `pytest`. As a result, it is skipped by default. See `/conftest.py` for options. """ caplog.set_level(logging.WARNING) caplog.clear() warnings.warn('Test warning') assert caplog.record_tuples[0][0] == 'py.warnings' assert caplog.record_tuples[0][1] == logging.WARNING assert 'Test warning' in caplog.record_tuples[0][2] def test_asana_error_handler(caplog): """ Tests the `@asana_error_handler` decorator. """ caplog.set_level(logging.ERROR) def gen_text(text1, text2, text3): return f'{text1} | {text2} | {text3}' dec_gen_text = aclient.asana_error_handler(gen_text) assert dec_gen_text('one', text3='three', text2='two') \ == 'one | two | three' assert dec_gen_text._is_wrapped_by_asana_error_handler is True def raise_error(exception_type): raise exception_type dec_raise_error = aclient.asana_error_handler(raise_error) exception_types = [ asana.error.PremiumOnlyError, asana.error.RateLimitEnforcedError, ] for exception_type in exception_types: subtest_asana_error_handler_func(caplog, exception_type, 0, dec_raise_error, exception_type) assert dec_raise_error._is_wrapped_by_asana_error_handler is True @pytest.mark.parametrize('func_name', [ '_get_me', 'get_workspace_gid_from_name', 'get_project_gid_from_name', 'get_section_gid_from_name', 'get_user_task_list_gid', 'get_section_gids_in_project_or_utl', 'get_tasks', 'move_task_to_section', ]) def test_dec_usage_asana_error_handler(func_name): """ Tests that functions that are expected to use the `@asana_error_handler` decorator do in fact have it. """ func = getattr(aclient, func_name) assert func._is_wrapped_by_asana_error_handler is True def test__get_client(monkeypatch): """ Tests the `_get_client()` method. This relies on /config/.secrets.conf being setup with a real personal access token. """ client = aclient._get_client() assert client is not None def mock_read_conf_file(conf_rel_file, # pylint: disable=unused-argument conf_base_dir=None): # pylint: disable=unused-argument """ Return an empty dict instead of loading from file. """ return {} # read_conf_file() returning bad config allows to confirm client cache works orig_read_conf_file = config.read_conf_file monkeypatch.setattr(config, 'read_conf_file', mock_read_conf_file) client = aclient._get_client() assert client is not None monkeypatch.delattr(aclient._get_client, 'client') with pytest.raises(aclient.ClientCreationError) as ex: aclient._get_client() assert "Could not create client - Could not find necessary section/key in" \ + " .secrets.conf: 'asana'" in str(ex.value) monkeypatch.setattr(config, 'read_conf_file', orig_read_conf_file) def mock_client_access_token__missing( # pylint: disable=invalid-name accessToken): # pylint: disable=unused-argument """ Mock the client creation via access token with header keys missing. """ return types.SimpleNamespace(headers={}) def mock_client_access_token__empty( # pylint: disable=invalid-name accessToken): # pylint: disable=unused-argument """ Mock the client creation via access token with header keys present, but empty values. """ return types.SimpleNamespace(headers={'asana-enable': ''}) def mock_client_access_token__existing( # pylint: disable=invalid-name accessToken): # pylint: disable=unused-argument """ Mock the client creation via access token with header keys present and with some existing values. """ return types.SimpleNamespace(headers={'asana-enable': 'existing'}) monkeypatch.setattr(asana.Client, 'access_token', mock_client_access_token__missing) client = aclient._get_client() assert client is not None assert client.headers == { 'asana-enable': 'new_user_task_lists', } monkeypatch.delattr(aclient._get_client, 'client') monkeypatch.setattr(asana.Client, 'access_token', mock_client_access_token__existing) client = aclient._get_client() assert client is not None assert client.headers == { 'asana-enable': 'existing,new_user_task_lists', } monkeypatch.delattr(aclient._get_client, 'client') monkeypatch.setattr(asana.Client, 'access_token', mock_client_access_token__empty) client = aclient._get_client() assert client is not None assert client.headers == { 'asana-enable': 'new_user_task_lists', } def test__get_me(monkeypatch, caplog): """ Tests the `_get_me()` method. This relies on /config/.secrets.conf being setup with a real personal access token. ** Consumes 2 API calls. ** """ caplog.set_level(logging.WARNING) me_data = aclient._get_me() assert me_data['gid'] def mock_read_conf_file(conf_rel_file, # pylint: disable=unused-argument conf_base_dir=None): # pylint: disable=unused-argument """ Return a bad personal access token to pass client creation but fail API. """ return { 'asana': { 'personal access token': '<PASSWORD>', }, } # Function-specific practical test of @asana_error_handler monkeypatch.delattr(aclient._get_client, 'client') monkeypatch.setattr(config, 'read_conf_file', mock_read_conf_file) subtest_asana_error_handler_func(caplog, asana.error.NoAuthorizationError, 0, aclient._get_me) def test__find_gid_from_name(caplog): """ Tests the `_find_gid_from_name()` method. No API calls. Methods that use this `_find_gid_from_name()` method will verify API compatibility then. This stays focused on testing logic. """ caplog.set_level(logging.INFO) data = [ { 'gid': 1, 'name': 'one and only', 'resource_type': 'workspace', }, { 'gid': 2, 'name': 'two with dupe', 'resource_type': 'workspace', }, { 'gid': 3, 'name': 'two with dupe', 'resource_type': 'workspace', }, { 'gid': 4, 'name': 'not workspace', 'resource_type': 'organization', }, ] resource_type = 'workspace' gid = aclient._find_gid_from_name(data, resource_type, 'one and only', 1) assert gid == 1 caplog.clear() gid = aclient._find_gid_from_name(data, resource_type, 'one and only') assert gid == 1 assert caplog.record_tuples == [ ('asana_extensions.asana.client', logging.INFO, 'GID of workspace "one and only" is 1'), ] with pytest.raises(aclient.MismatchedDataError): aclient._find_gid_from_name(data, resource_type, 'one and only', -1) with pytest.raises(aclient.DuplicateNameError): aclient._find_gid_from_name(data, resource_type, 'two with dupe') with pytest.raises(aclient.DataNotFoundError): aclient._find_gid_from_name(data, resource_type, 'invalid name') @pytest.mark.asana_error_data.with_args(asana.error.ForbiddenError) def test_get_workspace_gid_from_name(monkeypatch, caplog, raise_asana_error): """ Tests the `get_workspace_gid_from_name()` method. This does require the asana account be configured to support unit testing. See CONTRIBUTING.md. ** Consumes at least 2 API calls. ** (varies depending on data size, but only 2 calls intended) Raises: (TesterNotInitializedError): If test workspace does not exist on asana account tied to access token, will stop test. User must create manually per docs. """ # pylint: disable=no-member # asana.Client dynamically adds attrs caplog.set_level(logging.ERROR) try: aclient.get_workspace_gid_from_name(tester_data._WORKSPACE) except aclient.DataNotFoundError as ex: # This is an error with the tester, not the module under test raise TesterNotInitializedError('Cannot run unit tests: Must create a' + f' workspace named "{tester_data._WORKSPACE}" in the asana' + ' account tied to access token in .secrets.conf') from ex # To ensure compatible with _extract_gid_from_name(), validate data format client = aclient._get_client() workspaces = client.workspaces.get_workspaces() workspace = next(workspaces) assert 'gid' in workspace assert 'name' in workspace assert 'resource_type' in workspace # Function-specific practical test of @asana_error_handler # Need to monkeypatch cached client since class dynamically creates attrs monkeypatch.setattr(client.workspaces, 'get_workspaces', raise_asana_error) subtest_asana_error_handler_func(caplog, asana.error.ForbiddenError, 0, aclient.get_workspace_gid_from_name, 'one and only') @pytest.mark.asana_error_data.with_args(asana.error.NotFoundError) def test_get_project_gid_from_name(monkeypatch, caplog, project_test, raise_asana_error): """ Tests the `get_project_gid_from_name()` method. This does require the asana account be configured to support unit testing. See CONTRIBUTING.md. ** Consumes at least 3 API calls. ** (varies depending on data size, but only 3 calls intended) Raises: (TesterNotInitializedError): If test workspace does not exist on asana account tied to access token, will stop test. User must create manually per docs. """ # pylint: disable=no-member # asana.Client dynamically adds attrs caplog.set_level(logging.ERROR) try: ws_gid = aclient.get_workspace_gid_from_name(tester_data._WORKSPACE) except aclient.DataNotFoundError as ex: # This is an error with the tester, not the module under test raise TesterNotInitializedError('Cannot run unit tests: Must create a' + f' workspace named "{tester_data._WORKSPACE}" in the asana' + ' account tied to access token in .secrets.conf') from ex # Sanity check that this works with an actual project proj_gid = aclient.get_project_gid_from_name(ws_gid, project_test['name'], int(project_test['gid'])) assert proj_gid == int(project_test['gid']) # To ensure compatible with _extract_gid_from_name(), validate data format client = aclient._get_client() projects = client.projects.get_projects({'workspace': str(ws_gid)}) project = next(projects) assert 'gid' in project assert 'name' in project assert 'resource_type' in project # Function-specific practical test of @asana_error_handler # Need to monkeypatch cached client since class dynamically creates attrs monkeypatch.setattr(client.projects, 'get_projects', raise_asana_error) subtest_asana_error_handler_func(caplog, asana.error.NotFoundError, 0, aclient.get_project_gid_from_name, ws_gid, project_test['name']) @pytest.mark.asana_error_data.with_args(asana.error.InvalidTokenError) def test_get_section_gid_from_name(monkeypatch, caplog, project_test, sections_in_project_test, raise_asana_error): """ Tests the `get_section_gid_from_name()` method. This does require the asana account be configured to support unit testing. See CONTRIBUTING.md. ** Consumes at least 2 API calls. ** (varies depending on data size, but only 2 calls intended) Raises: (TesterNotInitializedError): If test workspace does not exist on asana account tied to access token, will stop test. User must create manually per docs. """ # pylint: disable=no-member # asana.Client dynamically adds attrs caplog.set_level(logging.ERROR) # Only need 1 section section_in_project_test = sections_in_project_test[0] # Sanity check that this works with an actual section try: sect_gid = aclient.get_section_gid_from_name(project_test['gid'], section_in_project_test['name'], int(section_in_project_test['gid'])) except aclient.DataNotFoundError as ex: # This is an error with the tester, not the module under test raise TesterNotInitializedError('Cannot run unit tests: Must create a' + f' workspace named "{tester_data._WORKSPACE}" in the asana' + ' account tied to access token in .secrets.conf') from ex assert sect_gid == int(section_in_project_test['gid']) # To ensure compatible with _extract_gid_from_name(), validate data format client = aclient._get_client() sections = client.sections.get_sections_for_project(project_test['gid']) section = next(sections) assert 'gid' in section assert 'name' in section assert 'resource_type' in section # Function-specific practical test of @asana_error_handler # Need to monkeypatch cached client since class dynamically creates attrs monkeypatch.setattr(client.sections, 'get_sections_for_project', raise_asana_error) subtest_asana_error_handler_func(caplog, asana.error.InvalidTokenError,
<filename>Bio/SeqIO/_index.py<gh_stars>1-10 # Copyright 2009-2010 by <NAME>. All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. """Dictionary like indexing of sequence files (PRIVATE). You are not expected to access this module, or any of its code, directly. This is all handled internally by the Bio.SeqIO.index(...) function which is the public interface for this functionality. The basic idea is that we scan over a sequence file, looking for new record markers. We then try and extract the string that Bio.SeqIO.parse/read would use as the record id, ideally without actually parsing the full record. We then use a subclassed Python dictionary to record the file offset for the record start against the record id. Note that this means full parsing is on demand, so any invalid or problem record may not trigger an exception until it is accessed. This is by design. This means our dictionary like objects have in memory ALL the keys (all the record identifiers), which shouldn't be a problem even with second generation sequencing. If this is an issue later on, storing the keys and offsets in a temp lookup file might be one idea (e.g. using SQLite or an OBDA style index). """ import re from Bio import SeqIO from Bio import Alphabet class _IndexedSeqFileDict(dict): """Read only dictionary interface to a sequential sequence file. Keeps the keys in memory, reads the file to access entries as SeqRecord objects using Bio.SeqIO for parsing them. This approach is memory limited, but will work even with millions of sequences. Note - as with the Bio.SeqIO.to_dict() function, duplicate keys (record identifiers by default) are not allowed. If this happens, a ValueError exception is raised. By default the SeqRecord's id string is used as the dictionary key. This can be changed by suppling an optional key_function, a callback function which will be given the record id and must return the desired key. For example, this allows you to parse NCBI style FASTA identifiers, and extract the GI number to use as the dictionary key. Note that this dictionary is essentially read only. You cannot add or change values, pop values, nor clear the dictionary. """ def __init__(self, filename, format, alphabet, key_function): #Use key_function=None for default value dict.__init__(self) #init as empty dict! if format in SeqIO._BinaryFormats: mode = "rb" else: mode = "rU" self._handle = open(filename, mode) self._alphabet = alphabet self._format = format self._key_function = key_function if key_function: offset_iter = ((key_function(k),o) for (k,o) in self._build()) else: offset_iter = self._build() for key, offset in offset_iter: if key in self: raise ValueError("Duplicate key '%s'" % key) else: dict.__setitem__(self, key, offset) def _build(self): """Actually scan the file identifying records and offsets (PRIVATE). Returns an iterator giving tuples of record names and their offsets. """ pass def __repr__(self): return "SeqIO.index('%s', '%s', alphabet=%s, key_function=%s)" \ % (self._handle.name, self._format, repr(self._alphabet), self._key_function) def __str__(self): if self: return "{%s : SeqRecord(...), ...}" % repr(self.keys()[0]) else: return "{}" if hasattr(dict, "iteritems"): #Python 2, use iteritems but not items etc def values(self): """Would be a list of the SeqRecord objects, but not implemented. In general you can be indexing very very large files, with millions of sequences. Loading all these into memory at once as SeqRecord objects would (probably) use up all the RAM. Therefore we simply don't support this dictionary method. """ raise NotImplementedError("Due to memory concerns, when indexing a " "sequence file you cannot access all the " "records at once.") def items(self): """Would be a list of the (key, SeqRecord) tuples, but not implemented. In general you can be indexing very very large files, with millions of sequences. Loading all these into memory at once as SeqRecord objects would (probably) use up all the RAM. Therefore we simply don't support this dictionary method. """ raise NotImplementedError("Due to memory concerns, when indexing a " "sequence file you cannot access all the " "records at once.") def iteritems(self): """Iterate over the (key, SeqRecord) items.""" for key in self.__iter__(): yield key, self.__getitem__(key) else: #Python 3 - define items and values as iterators def items(self): """Iterate over the (key, SeqRecord) items.""" for key in self.__iter__(): yield key, self.__getitem__(key) def values(self): """Iterate over the SeqRecord items.""" for key in self.__iter__(): yield self.__getitem__(key) def __getitem__(self, key): """x.__getitem__(y) <==> x[y]""" #Should be done by each sub-class raise NotImplementedError("Not implemented for this file format (yet).") def get(self, k, d=None): """D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.""" try: return self.__getitem__(k) except KeyError: return d def get_raw(self, key): """Similar to the get method, but returns the record as a raw string. If the key is not found, a KeyError exception is raised. NOTE - This functionality is not supported for every file format. """ #Should be done by each sub-class (if possible) raise NotImplementedError("Not available for this file format.") def __setitem__(self, key, value): """Would allow setting or replacing records, but not implemented.""" raise NotImplementedError("An indexed a sequence file is read only.") def update(self, **kwargs): """Would allow adding more values, but not implemented.""" raise NotImplementedError("An indexed a sequence file is read only.") def pop(self, key, default=None): """Would remove specified record, but not implemented.""" raise NotImplementedError("An indexed a sequence file is read only.") def popitem(self): """Would remove and return a SeqRecord, but not implemented.""" raise NotImplementedError("An indexed a sequence file is read only.") def clear(self): """Would clear dictionary, but not implemented.""" raise NotImplementedError("An indexed a sequence file is read only.") def fromkeys(self, keys, value=None): """A dictionary method which we don't implement.""" raise NotImplementedError("An indexed a sequence file doesn't " "support this.") def copy(self): """A dictionary method which we don't implement.""" raise NotImplementedError("An indexed a sequence file doesn't " "support this.") #################### # Special indexers # #################### # Anything where the records cannot be read simply by parsing from # the record start. For example, anything requiring information from # a file header - e.g. SFF files where we would need to know the # number of flows. class SffDict(_IndexedSeqFileDict) : """Indexed dictionary like access to a Standard Flowgram Format (SFF) file.""" def _build(self): """Load any index block in the file, or build it the slow way (PRIVATE).""" if self._alphabet is None: self._alphabet = Alphabet.generic_dna handle = self._handle #Record the what we'll need for parsing a record given its offset header_length, index_offset, index_length, number_of_reads, \ self._flows_per_read, self._flow_chars, self._key_sequence \ = SeqIO.SffIO._sff_file_header(handle) if index_offset and index_length: #There is an index provided, try this the fast way: try : for name, offset in SeqIO.SffIO._sff_read_roche_index(handle) : yield name, offset assert len(self) == number_of_reads, \ "Indexed %i records, expected %i" \ % (len(self), number_of_reads) return except ValueError, err : import warnings warnings.warn("Could not parse the SFF index: %s" % err) assert len(self)==0, "Partially populated index" handle.seek(0) else : #TODO - Remove this debug warning? import warnings warnings.warn("No SFF index, doing it the slow way") #Fall back on the slow way! for name, offset in SeqIO.SffIO._sff_do_slow_index(handle) : yield name, offset assert len(self) == number_of_reads, \ "Indexed %i records, expected %i" % (len(self), number_of_reads) def __getitem__(self, key) : handle = self._handle handle.seek(dict.__getitem__(self, key)) return SeqIO.SffIO._sff_read_seq_record(handle, self._flows_per_read, self._flow_chars, self._key_sequence, self._alphabet) def get_raw(self, key): handle = self._handle handle.seek(dict.__getitem__(self, key)) return SeqIO.SffIO._sff_read_raw_record(handle, self._flows_per_read) class SffTrimmedDict(SffDict) : def __getitem__(self, key) : handle = self._handle handle.seek(dict.__getitem__(self, key)) return SeqIO.SffIO._sff_read_seq_record(handle, self._flows_per_read, self._flow_chars, self._key_sequence, self._alphabet, trim=True) ################### # Simple indexers # ################### class SequentialSeqFileDict(_IndexedSeqFileDict): """Indexed dictionary like access to most sequential sequence files.""" def __init__(self, filename, format, alphabet, key_function): _IndexedSeqFileDict.__init__(self, filename, format, alphabet, key_function) #Load the parser class/function once an avoid the dict lookup in each #__getitem__ call: i = SeqIO._FormatToIterator[format] #The following alphabet code is a bit nasty... duplicates logic in #Bio.SeqIO.parse() if alphabet is None: def _parse(): """Dynamically generated parser function (PRIVATE).""" return i(self._handle).next() else: #TODO - Detect alphabet support ONCE at __init__ def _parse(): """Dynamically generated parser function (PRIVATE).""" try: return i(self._handle, alphabet=alphabet).next() except TypeError: return SeqIO._force_alphabet(i(self._handle), alphabet).next() self._parse = _parse def _build(self): handle
from a ratemap. Parameters ---------- ratemap : array Array of shape (n_units, ext_nx, ext_ny) Returns ------- """ n_units, ext_nx, ext_ny = ratemap.shape if occupancy is None: # assume uniform occupancy self._occupancy = np.ones((ext_nx, ext_ny)) if ext_xmin is None: ext_xmin = 0 if ext_xmax is None: ext_xmax = ext_xmin + 1 if ext_ymin is None: ext_ymin = 0 if ext_ymax is None: ext_ymax = ext_ymin + 1 self._xbins = np.linspace(ext_xmin, ext_xmax, ext_nx+1) self._ybins = np.linspace(ext_ymin, ext_ymax, ext_ny+1) self._ratemap = ratemap # inherit unit IDs if available, otherwise initialize to default if unit_ids is None: unit_ids = list(range(1,n_units + 1)) unit_ids = np.array(unit_ids, ndmin=1) # standardize unit_ids # if unit_labels is empty, default to unit_ids if unit_labels is None: unit_labels = unit_ids unit_labels = np.array(unit_labels, ndmin=1) # standardize self._unit_ids = unit_ids self._unit_labels = unit_labels self._unit_tags = unit_tags # no input validation yet if label is not None: self.label = label return self def _detach(self): """Detach bst and extern from tuning curve.""" self._bst = None self._extern = None @property def mask(self): """(n_xbins, n_ybins) Mask for tuning curve.""" return self._mask @property def n_bins(self): """(int) Number of external correlates (bins).""" return self.n_xbins*self.n_ybins @property def n_xbins(self): """(int) Number of external correlates (bins).""" return len(self.xbins) - 1 @property def n_ybins(self): """(int) Number of external correlates (bins).""" return len(self.ybins) - 1 @property def xbins(self): """External correlate bins.""" return self._xbins @property def ybins(self): """External correlate bins.""" return self._ybins @property def xbin_centers(self): """External correlate bin centers.""" return (self.xbins + (self.xbins[1] - self.xbins[0])/2)[:-1] @property def ybin_centers(self): """External correlate bin centers.""" return (self.ybins + (self.ybins[1] - self.ybins[0])/2)[:-1] @property def bin_centers(self): return tuple([self.xbin_centers, self.ybin_centers]) @property def bins(self): """External correlate bins.""" return (self.xbins, self.ybins) def _trans_func(self, extern, at): """Default transform function to map extern into numerical bins. Assumes first signal is x-dim, second is y-dim. """ _, ext = extern.asarray(at=at) x, y = ext[0,:], ext[1,:] return np.atleast_1d(x), np.atleast_1d(y) def _compute_occupancy(self): """ """ # Make sure that self._bst_centers fall within not only the support # of extern, but also within the extreme sample times; otherwise, # interpolation will yield NaNs at the extremes. Indeed, when we have # sample times within a support epoch, we can assume that the signal # stayed roughly constant for that one sample duration. if self._bst._bin_centers[0] < self._extern.time[0]: self._extern = copy.copy(self._extern) self._extern.time[0] = self._bst._bin_centers[0] self._extern._interp = None # raise ValueError('interpolated sample requested before first sample of extern!') if self._bst._bin_centers[-1] > self._extern.time[-1]: self._extern = copy.copy(self._extern) self._extern.time[-1] = self._bst._bin_centers[-1] self._extern._interp = None # raise ValueError('interpolated sample requested after last sample of extern!') x, y = self.trans_func(self._extern, at=self._bst.bin_centers) xmin = self.xbins[0] xmax = self.xbins[-1] ymin = self.ybins[0] ymax = self.ybins[-1] occupancy, _, _ = np.histogram2d(x, y, bins=[self.xbins, self.ybins], range=([[xmin, xmax], [ymin, ymax]])) return occupancy def _compute_ratemap(self, min_duration=None): """ min_duration is the min duration in seconds for a bin to be considered 'valid'; if too few observations were made, then the firing rate is kept at an estimate of 0. If min_duration == 0, then all the spikes are used. """ if min_duration is None: min_duration = self._min_duration x, y = self.trans_func(self._extern, at=self._bst.bin_centers) ext_bin_idx_x = np.squeeze(np.digitize(x, self.xbins, right=True)) ext_bin_idx_y = np.squeeze(np.digitize(y, self.ybins, right=True)) # make sure that all the events fit between extmin and extmax: # TODO: this might rather be a warning, but it's a pretty serious warning... if ext_bin_idx_x.max() > self.n_xbins: raise ValueError("ext values greater than 'ext_xmax'") if ext_bin_idx_x.min() == 0: raise ValueError("ext values less than 'ext_xmin'") if ext_bin_idx_y.max() > self.n_ybins: raise ValueError("ext values greater than 'ext_ymax'") if ext_bin_idx_y.min() == 0: raise ValueError("ext values less than 'ext_ymin'") ratemap = np.zeros((self.n_units, self.n_xbins, self.n_ybins)) for tt, (bidxx, bidxy) in enumerate(zip(ext_bin_idx_x, ext_bin_idx_y)): ratemap[:,bidxx-1, bidxy-1] += self._bst.data[:,tt] # apply minimum observation duration for uu in range(self.n_units): ratemap[uu][self.occupancy*self._bst.ds < min_duration] = 0 return ratemap / self._bst.ds def normalize(self, inplace=False): """Normalize firing rates. For visualization.""" raise NotImplementedError if not inplace: out = copy.deepcopy(self) else: out = self if self.n_units > 1: per_unit_max = np.max(out.ratemap, axis=1)[..., np.newaxis] out._ratemap = self.ratemap / np.tile(per_unit_max, (1, out.n_bins)) else: per_unit_max = np.max(out.ratemap) out._ratemap = self.ratemap / np.tile(per_unit_max, out.n_bins) return out def _normalize_firing_rate_by_occupancy(self): # normalize spike counts by occupancy: denom = np.tile(self.occupancy, (self.n_units,1,1)) denom[denom==0] = 1 ratemap = self.ratemap / denom return ratemap @property def is2d(self): return True @property def occupancy(self): return self._occupancy @property def n_units(self): """(int) The number of units.""" try: return len(self._unit_ids) except TypeError: # when unit_ids is an integer return 1 except AttributeError: return 0 @property def shape(self): """(tuple) The shape of the TuningCurve2D ratemap.""" if self.isempty: return (self.n_units, 0, 0) if len(self.ratemap.shape) ==1: return ( self.ratemap.shape[0], 1, 1) return self.ratemap.shape def __repr__(self): address_str = " at " + str(hex(id(self))) if self.isempty: return "<empty TuningCurve2D" + address_str + ">" shapestr = " with shape (%s, %s, %s)" % (self.shape[0], self.shape[1], self.shape[2]) return "<TuningCurve2D%s>%s" % (address_str, shapestr) @property def isempty(self): """(bool) True if TuningCurve1D is empty""" try: return len(self.ratemap) == 0 except TypeError: #TypeError should happen if ratemap = [] return True @property def ratemap(self): return self._ratemap def __len__(self): return self.n_units @keyword_deprecation(replace_x_with_y={'bw':'truncate'}) def smooth(self, *, sigma=None, truncate=None, inplace=False, mode=None, cval=None): """Smooths the tuning curve with a Gaussian kernel. mode : {‘reflect’, ‘constant’, ‘nearest’, ‘mirror’, ‘wrap’}, optional The mode parameter determines how the array borders are handled, where cval is the value when mode is equal to ‘constant’. Default is ‘reflect’ cval : scalar, optional Value to fill past edges of input if mode is ‘constant’. Default is 0.0 """ if sigma is None: sigma = 0.1 # in units of extern if truncate is None: truncate = 4 if mode is None: mode = 'reflect' if cval is None: cval = 0.0 ds_x = (self.xbins[-1] - self.xbins[0])/self.n_xbins ds_y = (self.ybins[-1] - self.ybins[0])/self.n_ybins sigma_x = sigma / ds_x sigma_y = sigma / ds_y if not inplace: out = copy.deepcopy(self) else: out = self if self.mask is None: if self.n_units > 1: out._ratemap = scipy.ndimage.filters.gaussian_filter(self.ratemap, sigma=(0,sigma_x, sigma_y), truncate=truncate, mode=mode, cval=cval) else: out._ratemap = scipy.ndimage.filters.gaussian_filter(self.ratemap, sigma=(sigma_x, sigma_y), truncate=truncate, mode=mode, cval=cval) else: # we have a mask! # smooth, dealing properly with NANs # NB! see https://stackoverflow.com/questions/18697532/gaussian-filtering-a-image-with-nan-in-python masked_ratemap = self.ratemap.copy()*self.mask V=masked_ratemap.copy() V[masked_ratemap!=masked_ratemap]=0 W=0*masked_ratemap.copy()+1 W[masked_ratemap!=masked_ratemap]=0 if self.n_units > 1: VV=scipy.ndimage.filters.gaussian_filter(V, sigma=(0, sigma_x, sigma_y), truncate=truncate, mode=mode, cval=cval) WW=scipy.ndimage.filters.gaussian_filter(W, sigma=(0, sigma_x, sigma_y), truncate=truncate, mode=mode, cval=cval) Z=VV/WW out._ratemap = Z*self.mask else: VV=scipy.ndimage.filters.gaussian_filter(V, sigma=(sigma_x, sigma_y), truncate=truncate, mode=mode, cval=cval) WW=scipy.ndimage.filters.gaussian_filter(W, sigma=(sigma_x, sigma_y), truncate=truncate, mode=mode, cval=cval) Z=VV/WW out._ratemap = Z*self.mask return out def reorder_units_by_ids(self, neworder, *, inplace=False): """Reorder units according to a specified order. neworder must be list-like, of size (n_units,) and in terms of unit_ids Return ------ out : reordered TuningCurve2D """ def swap_units(arr, frm, to): """swap 'units' of a 3D np.array""" arr[[frm, to],:,:] = arr[[to, frm],:,:] if inplace: out = self else: out = copy.deepcopy(self) unit_ids = list(self.unit_ids) neworder = [self.unit_ids.index(x) for x in neworder] oldorder = list(range(len(neworder))) for oi, ni in enumerate(neworder): frm = oldorder.index(ni) to = oi swap_units(out._ratemap, frm, to) out._unit_ids[frm], out._unit_ids[to] = out._unit_ids[to], out._unit_ids[frm] out._unit_labels[frm], out._unit_labels[to] = out._unit_labels[to], out._unit_labels[frm] # TODO: re-build unit tags (tag system not yet implemented) oldorder[frm], oldorder[to] = oldorder[to], oldorder[frm] return out @property def unit_ids(self): """Unit IDs contained in the SpikeTrain.""" return list(self._unit_ids) @unit_ids.setter def unit_ids(self, val): if len(val) != self.n_units: # print(len(val)) # print(self.n_units) raise TypeError("unit_ids must be of length n_units") elif len(set(val)) < len(val): raise TypeError("duplicate unit_ids are not allowed") else: try: # cast to int: unit_ids = [int(id) for id in val] except TypeError: raise TypeError("unit_ids must be int-like") self._unit_ids = unit_ids @property def unit_labels(self): """Labels corresponding to units contained in the SpikeTrain.""" if self._unit_labels is None: warnings.warn("unit labels have not yet been specified") return self._unit_labels @unit_labels.setter def unit_labels(self, val): if len(val) != self.n_units: raise TypeError("labels must be of length n_units") else: try: # cast to str: labels = [str(label) for label in val] except TypeError: raise TypeError("labels must be string-like") self._unit_labels = labels @property def unit_tags(self): """Tags corresponding to units contained in the SpikeTrain""" if self._unit_tags is None: warnings.warn("unit tags
= self.get("input.rerun%s.missin.Descent.ninde" % (i)) re_dedcd = self.get("input.rerun%s.missin.Descent.dedcd" % (i)) re_rdlim = self.get("input.rerun%s.missin.Descent.rdlim" % (i)) re_ns = self.get("input.rerun%s.missin.Descent.ns" % (i)) re_irs = self.get("input.rerun%s.missin.Reserve.irs" % (i)) re_resrfu = self.get("input.rerun%s.missin.Reserve.resrfu" % (i)) re_restrp = self.get("input.rerun%s.missin.Reserve.restrp" % (i)) re_timmap = self.get("input.rerun%s.missin.Reserve.timmap" % (i)) re_altran = self.get("input.rerun%s.missin.Reserve.altran" % (i)) re_nclres = self.get("input.rerun%s.missin.Reserve.nclres" % (i)) re_ncrres = self.get("input.rerun%s.missin.Reserve.ncrres" % (i)) re_sremch = self.get("input.rerun%s.missin.Reserve.sremch" % (i)) re_eremch = self.get("input.rerun%s.missin.Reserve.eremch" % (i)) re_srealt = self.get("input.rerun%s.missin.Reserve.srealt" % (i)) re_erealt = self.get("input.rerun%s.missin.Reserve.erealt" % (i)) re_holdtm = self.get("input.rerun%s.missin.Reserve.holdtm" % (i)) re_ncrhol = self.get("input.rerun%s.missin.Reserve.ncrhol" % (i)) re_ihopos = self.get("input.rerun%s.missin.Reserve.ihopos" % (i)) re_icron = self.get("input.rerun%s.missin.Reserve.icron" % (i)) re_thold = self.get("input.rerun%s.missin.Reserve.thold" % (i)) re_ncrth = self.get("input.rerun%s.missin.Reserve.ncrth" % (i)) if re_dwt != -999.: sb.add_var("input.rerun%s.missin.Basic.dwt" % (i)) if len(re_offdr) > 0: sb.add_var("input.rerun%s.missin.Basic.offdr" % (i)) if re_idoq != -999: sb.add_var("input.rerun%s.missin.Basic.idoq" % (i)) if re_nsout != -999: sb.add_var("input.rerun%s.missin.Basic.nsout" % (i)) if re_nsadj != -999: sb.add_var("input.rerun%s.missin.Basic.nsadj" % (i)) if re_mirror != -999: sb.add_var("input.rerun%s.missin.Basic.mirror" % (i)) if len(re_stma) > 0: sb.add_var("input.rerun%s.missin.Store_Drag.stma" % (i)) if len(re_cdst) > 0: sb.add_var("input.rerun%s.missin.Store_Drag.cdst" % (i)) if len(re_istcl) > 0: sb.add_var("input.rerun%s.missin.Store_Drag.istcl" % (i)) if len(re_istcr) > 0: sb.add_var("input.rerun%s.missin.Store_Drag.istcr" % (i)) if re_istde != -999: sb.add_var("input.rerun%s.missin.Store_Drag.istde" % (i)) if re_mywts != -999: sb.add_var("input.rerun%s.missin.User_Weights.mywts" % (i)) if re_rampwt != -999.: sb.add_var("input.rerun%s.missin.User_Weights.rampwt" % (i)) if re_dowe != -999.: sb.add_var("input.rerun%s.missin.User_Weights.dowe" % (i)) if re_paylod != -999.: sb.add_var("input.rerun%s.missin.User_Weights.paylod" % (i)) if re_fuemax != -999.: sb.add_var("input.rerun%s.missin.User_Weights.fuemax" % (i)) if re_takotm != -999.: sb.add_var("input.rerun%s.missin.Ground_Operations.takotm" % (i)) if re_taxotm != -999.: sb.add_var("input.rerun%s.missin.Ground_Operations.taxotm" % (i)) if re_apprtm != -999.: sb.add_var("input.rerun%s.missin.Ground_Operations.apprtm" % (i)) if re_appfff != -999.: sb.add_var("input.rerun%s.missin.Ground_Operations.appfff" % (i)) if re_taxitm != -999.: sb.add_var("input.rerun%s.missin.Ground_Operations.taxitm" % (i)) if re_ittff != -999: sb.add_var("input.rerun%s.missin.Ground_Operations.ittff" % (i)) if re_takoff != -999.: sb.add_var("input.rerun%s.missin.Ground_Operations.takoff" % (i)) if re_txfufl != -999.: sb.add_var("input.rerun%s.missin.Ground_Operations.txfufl" % (i)) if re_ftkofl != -999.: sb.add_var("input.rerun%s.missin.Ground_Operations.ftkofl" % (i)) if re_ftxofl != -999.: sb.add_var("input.rerun%s.missin.Ground_Operations.ftxofl" % (i)) if re_ftxifl != -999.: sb.add_var("input.rerun%s.missin.Ground_Operations.ftxifl" % (i)) if re_faprfl != -999.: sb.add_var("input.rerun%s.missin.Ground_Operations.faprfl" % (i)) if len(re_xnz) > 0: sb.add_var("input.rerun%s.missin.Turn_Segments.xnz" % (i)) if len(re_xcl) > 0: sb.add_var("input.rerun%s.missin.Turn_Segments.xcl" % (i)) if len(re_xmach) > 0: sb.add_var("input.rerun%s.missin.Turn_Segments.xmach" % (i)) if re_nclimb > 0: sb.add_var("input.rerun%s.missin.Climb.nclimb" % (i)) if len(re_clmmin) > 0: sb.add_var("input.rerun%s.missin.Climb.clmmin" % (i)) if len(re_clmmax) > 0: sb.add_var("input.rerun%s.missin.Climb.clmmax" % (i)) if len(re_clamin) > 0: sb.add_var("input.rerun%s.missin.Climb.clamin" % (i)) if len(re_clamax) > 0: sb.add_var("input.rerun%s.missin.Climb.clamax" % (i)) if len(re_nincl) > 0: sb.add_var("input.rerun%s.missin.Climb.nincl" % (i)) if len(re_fwf) > 0: sb.add_var("input.rerun%s.missin.Climb.fwf" % (i)) if len(re_ncrcl) > 0: sb.add_var("input.rerun%s.missin.Climb.ncrcl" % (i)) if len(re_cldcd) > 0: sb.add_var("input.rerun%s.missin.Climb.cldcd" % (i)) if len(re_ippcl) > 0: sb.add_var("input.rerun%s.missin.Climb.ippcl" % (i)) if len(re_maxcl) > 0: sb.add_var("input.rerun%s.missin.Climb.maxcl" % (i)) if len(re_no) > 0: sb.add_var("input.rerun%s.missin.Climb.no" % (i)) if re_keasvc != -999: sb.add_var("input.rerun%s.missin.Climb.keasvc" % (i)) if len(re_actab) > 0: sb.add_var2d("input.rerun%s.missin.Climb.actab" % (i)) if len(re_vctab) > 0: sb.add_var2d("input.rerun%s.missin.Climb.vctab" % (i)) if re_ifaacl != -999: sb.add_var("input.rerun%s.missin.Climb.ifaacl" % (i)) if re_ifaade != -999: sb.add_var("input.rerun%s.missin.Climb.ifaade" % (i)) if re_nodive != -999: sb.add_var("input.rerun%s.missin.Climb.nodive" % (i)) if re_divlim != -999.: sb.add_var("input.rerun%s.missin.Climb.divlim" % (i)) if re_qlim != -999.: sb.add_var("input.rerun%s.missin.Climb.qlim" % (i)) if re_spdlim != -999.: sb.add_var("input.rerun%s.missin.Climb.spdlim" % (i)) if len(re_qlalt) > 0: sb.add_var("input.rerun%s.missin.Climb.qlalt" % (i)) if len(re_vqlm) > 0: sb.add_var("input.rerun%s.missin.Climb.vqlm" % (i)) if len(re_ioc) > 0: sb.add_var("input.rerun%s.missin.Cruise.ioc" % (i)) if len(re_crmach) > 0: sb.add_var("input.rerun%s.missin.Cruise.crmach" % (i)) if len(re_cralt) > 0: sb.add_var("input.rerun%s.missin.Cruise.cralt" % (i)) if len(re_crdcd) > 0: sb.add_var("input.rerun%s.missin.Cruise.crdcd" % (i)) if len(re_flrcr) > 0: sb.add_var("input.rerun%s.missin.Cruise.flrcr" % (i)) if len(re_crmmin) > 0: sb.add_var("input.rerun%s.missin.Cruise.crmmin" % (i)) if len(re_crclmx) > 0: sb.add_var("input.rerun%s.missin.Cruise.crclmx" % (i)) if len(re_hpmin) > 0: sb.add_var("input.rerun%s.missin.Cruise.hpmin" % (i)) if len(re_ffuel) > 0: sb.add_var("input.rerun%s.missin.Cruise.ffuel" % (i)) if len(re_fnox) > 0: sb.add_var("input.rerun%s.missin.Cruise.fnox" % (i)) if len(re_ifeath) > 0: sb.add_var("input.rerun%s.missin.Cruise.ifeath" % (i)) if len(re_feathf) > 0: sb.add_var("input.rerun%s.missin.Cruise.feathf" % (i)) if len(re_cdfeth) > 0: sb.add_var("input.rerun%s.missin.Cruise.cdfeth" % (i)) if re_dcwt != -999.: sb.add_var("input.rerun%s.missin.Cruise.dcwt" % (i)) if re_rcin != -999.: sb.add_var("input.rerun%s.missin.Cruise.rcin" % (i)) if len(re_wtbm) > 0: sb.add_var("input.rerun%s.missin.Cruise.wtbm" % (i)) if len(re_altbm) > 0: sb.add_var("input.rerun%s.missin.Cruise.altbm" % (i)) if re_ivs != -999: sb.add_var("input.rerun%s.missin.Descent.ivs" % (i)) if re_decl != -999.: sb.add_var("input.rerun%s.missin.Descent.decl" % (i)) if re_demmin != -999.: sb.add_var("input.rerun%s.missin.Descent.demmin" % (i)) if re_demmax != -999.: sb.add_var("input.rerun%s.missin.Descent.demmax" % (i)) if re_deamin != -999.: sb.add_var("input.rerun%s.missin.Descent.deamin" % (i)) if re_deamax != -999.: sb.add_var("input.rerun%s.missin.Descent.deamax" % (i)) if re_ninde != -999: sb.add_var("input.rerun%s.missin.Descent.ninde" % (i)) if re_dedcd != -999.: sb.add_var("input.rerun%s.missin.Descent.dedcd" % (i)) if re_rdlim != -999.: sb.add_var("input.rerun%s.missin.Descent.rdlim" % (i)) ns = len(self.get("input.rerun%s.missin.Descent.adtab" % (i))) if ns > 0: sb.add_comment("\n ! Input Descent Schedule\n") sb.add_newvar('ns', ns) sb.add_var("input.rerun%s.missin.Descent.keasvd" % (i)) sb.add_var("input.rerun%s.missin.Descent.adtab" % (i)) sb.add_var("input.rerun%s.missin.Descent.vdtab" % (i)) if re_irs != -999: sb.add_var("input.rerun%s.missin.Reserve.irs" % (i)) if re_resrfu != -999.: sb.add_var("input.rerun%s.missin.Reserve.resrfu" % (i)) if re_restrp != -999.: sb.add_var("input.rerun%s.missin.Reserve.restrp" % (i)) if re_timmap != -999.: sb.add_var("input.rerun%s.missin.Reserve.timmap" % (i)) if re_altran != -999.: sb.add_var("input.rerun%s.missin.Reserve.altran" % (i)) if re_nclres != -999: sb.add_var("input.rerun%s.missin.Reserve.nclres" % (i)) if re_ncrres != -999: sb.add_var("input.rerun%s.missin.Reserve.ncrres" % (i)) if re_sremch != -999.: sb.add_var("input.rerun%s.missin.Reserve.sremch" % (i)) if re_eremch != -999.: sb.add_var("input.rerun%s.missin.Reserve.eremch" % (i)) if re_srealt != -999.: sb.add_var("input.rerun%s.missin.Reserve.srealt" % (i)) if re_erealt != -999.: sb.add_var("input.rerun%s.missin.Reserve.erealt" % (i)) if re_holdtm != -999.: sb.add_var("input.rerun%s.missin.Reserve.holdtm" % (i)) if re_ncrhol != -999: sb.add_var("input.rerun%s.missin.Reserve.ncrhol" % (i)) if re_ihopos != -999: sb.add_var("input.rerun%s.missin.Reserve.ihopos" % (i)) if re_icron != -999: sb.add_var("input.rerun%s.missin.Reserve.icron" % (i)) if re_thold != -999.: sb.add_var("input.rerun%s.missin.Reserve.thold" % (i)) if re_ncrth != -999: sb.add_var("input.rerun%s.missin.Reserve.ncrth" % (i)) sb.add_newvar("NPCON", self.npcons0[i]) # Insert the new mission definition. #infile = self.get("input.rerun%s.mission" % (i)).open() #mission = infile.read() #infile.close() #sb.add_comment(mission) # Get the mission definition mission = self.get("input.rerun%s.mission_definition" % i) for seg in mission: sb.add_group(seg) # Insert the &PCONIN namelists for j in range(0, self.npcons0[i]): re_conalt = self.get("input.rerun%s.pconin%s.conalt" % (i, j)) re_conmch = self.get("input.rerun%s.pconin%s.conmch" % (i, j)) re_connz = self.get("input.rerun%s.pconin%s.connz" % (i, j)) re_conpc = self.get("input.rerun%s.pconin%s.conpc" % (i, j)) re_conlim = self.get("input.rerun%s.pconin%s.conlim" % (i, j)) re_conaux = self.get("input.rerun%s.pconin%s.conaux" % (i, j)) re_neo = self.get("input.rerun%s.pconin%s.neo" % (i, j)) re_icstdg = self.get("input.rerun%s.pconin%s.icstdg" % (i, j)) re_conwt = self.get("input.rerun%s.pconin%s.conwt" % (i, j)) re_iconsg = self.get("input.rerun%s.pconin%s.iconsg" % (i, j)) re_confm = self.get("input.rerun%s.pconin%s.confm" % (i, j)) re_conwta = self.get("input.rerun%s.pconin%s.conwta" % (i, j)) re_icontp = self.get("input.rerun%s.pconin%s.icontp" % (i, j)) sb.add_group('PCONIN') if re_conalt >= 0.: sb.add_newvar("CONALT", re_conalt) if re_conmch >= 0.: sb.add_newvar("CONMCH", re_conmch) if re_connz >= 0.: sb.add_newvar("CONNZ", re_connz) if re_conpc > -10.: sb.add_newvar("CONPC", re_conpc) if re_conlim != -999.: sb.add_newvar("CONLIM", re_conlim) if re_conaux > -1.: sb.add_newvar("CONAUX", re_conaux) if re_neo >= 0: sb.append("NEO", re_neo) if re_icstdg >= 0: sb.add_newvar("ICSTDG", re_icstdg) if re_conwt >= 0.: sb.add_newvar("CONWT", re_conwt) if re_iconsg >= 0: sb.add_newvar("ICONSG", re_iconsg) if re_confm >= 0.: sb.add_newvar("CONFM", re_confm) if re_conwta != -999.: sb.add_newvar("CONWTA", re_conwta) if re_icontp >= 0: sb.add_newvar("ICONTP", re_icontp) # Generate the input file for FLOPS sb.generate() def parse_output(self): """Parses the FLOPS output file(s) and populates the component outputs with the data. """ out = FileParser() out.set_file(self.stdout) # added error check Thu Nov 15 2007 ERROR = self.ERROR HINT = self.HINT # Check for namelist read error # Throw new Exception for fatal errors # Continue processing for FLOPS failures (may want to return error # codes to optimizers sometime in the future) out.set_delimiters(" ") try: out.mark_anchor("ERROR READING NAMELIST") except RuntimeError: pass else: ERROR = out.transfer_line(0) raise RuntimeError('Error during FLOPS execution.\n %s' % ERROR) out.reset_anchor() try: out.mark_anchor("ERROR READING AERODYNAMIC") except RuntimeError: pass else: ERROR = out.transfer_line(0) raise RuntimeError('Error during FLOPS execution.\n %s' % ERROR) out.reset_anchor() try: out.mark_anchor("* * * ENGINE DECK MISSING * * *") except RuntimeError: pass else: ERROR = out.transfer_line(0) raise RuntimeError('Error during FLOPS execution.\n %s' % ERROR + \ '\n\nCheck links from "Engine" to "Flops". Make sure EIFILE' + \ 'points to an existing file (default is "ENGDECK.txt" in UserDir.\n\n*****************') out.reset_anchor() try: out.mark_anchor("* * * ONLY ONE ALTITUDE FOR MACH NUMBER") except RuntimeError: pass else: ERROR = out.transfer_line(0) # TODO - Why does MC wrapper do this? # commented out for now #self.output.Performance.range = 0. #self.output.Performance.rampwt = 0. #self.output.Performance.fuel = 0. raise RuntimeError('Error during FLOPS execution.\n %s' % ERROR) out.reset_anchor() try: out.mark_anchor("* * * ILLEGAL DATA IN ENGINE DECK * * *") except RuntimeError: pass else: ERROR = out.transfer_line(0) raise RuntimeError('Error during FLOPS execution.\n %s' % ERROR) out.reset_anchor() try: #out.mark_anchor("ERROR READING MISSION DEFINITION DATA FROM UNIT") # Loosened this up to find any read error; i've found others out.mark_anchor("ERROR READING") except RuntimeError: pass else: ERROR = out.transfer_line(0) raise
import asyncio import json import os import string from statistics import mean from typing import Any import pytz from django.conf import settings from django.contrib.postgres.fields import ArrayField from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models from loguru import logger from alerts.models import SEVERITY_CHOICES from core.models import CoreSettings from logs.models import BaseAuditModel from .utils import bytes2human logger.configure(**settings.LOG_CONFIG) CHECK_TYPE_CHOICES = [ ("diskspace", "Disk Space Check"), ("ping", "Ping Check"), ("cpuload", "CPU Load Check"), ("memory", "Memory Check"), ("winsvc", "Service Check"), ("script", "Script Check"), ("eventlog", "Event Log Check"), ] CHECK_STATUS_CHOICES = [ ("passing", "Passing"), ("failing", "Failing"), ("pending", "Pending"), ] EVT_LOG_NAME_CHOICES = [ ("Application", "Application"), ("System", "System"), ("Security", "Security"), ] EVT_LOG_TYPE_CHOICES = [ ("INFO", "Information"), ("WARNING", "Warning"), ("ERROR", "Error"), ("AUDIT_SUCCESS", "Success Audit"), ("AUDIT_FAILURE", "Failure Audit"), ] EVT_LOG_FAIL_WHEN_CHOICES = [ ("contains", "Log contains"), ("not_contains", "Log does not contain"), ] class Check(BaseAuditModel): # common fields agent = models.ForeignKey( "agents.Agent", related_name="agentchecks", null=True, blank=True, on_delete=models.CASCADE, ) policy = models.ForeignKey( "automation.Policy", related_name="policychecks", null=True, blank=True, on_delete=models.CASCADE, ) managed_by_policy = models.BooleanField(default=False) overriden_by_policy = models.BooleanField(default=False) parent_check = models.PositiveIntegerField(null=True, blank=True) name = models.CharField(max_length=255, null=True, blank=True) check_type = models.CharField( max_length=50, choices=CHECK_TYPE_CHOICES, default="diskspace" ) status = models.CharField( max_length=100, choices=CHECK_STATUS_CHOICES, default="pending" ) more_info = models.TextField(null=True, blank=True) last_run = models.DateTimeField(null=True, blank=True) email_alert = models.BooleanField(default=False) text_alert = models.BooleanField(default=False) dashboard_alert = models.BooleanField(default=False) fails_b4_alert = models.PositiveIntegerField(default=1) fail_count = models.PositiveIntegerField(default=0) outage_history = models.JSONField(null=True, blank=True) # store extra_details = models.JSONField(null=True, blank=True) # check specific fields # for eventlog, script, ip, and service alert severity alert_severity = models.CharField( max_length=15, choices=SEVERITY_CHOICES, default="warning", null=True, blank=True, ) # threshold percent for diskspace, cpuload or memory check error_threshold = models.PositiveIntegerField( validators=[MinValueValidator(0), MaxValueValidator(99)], null=True, blank=True, default=0, ) warning_threshold = models.PositiveIntegerField( null=True, blank=True, validators=[MinValueValidator(0), MaxValueValidator(99)], default=0, ) # diskcheck i.e C:, D: etc disk = models.CharField(max_length=2, null=True, blank=True) # ping checks ip = models.CharField(max_length=255, null=True, blank=True) # script checks script = models.ForeignKey( "scripts.Script", related_name="script", on_delete=models.CASCADE, null=True, blank=True, ) script_args = ArrayField( models.CharField(max_length=255, null=True, blank=True), null=True, blank=True, default=list, ) info_return_codes = ArrayField( models.PositiveIntegerField(), null=True, blank=True, default=list, ) warning_return_codes = ArrayField( models.PositiveIntegerField(), null=True, blank=True, default=list, ) timeout = models.PositiveIntegerField(null=True, blank=True) stdout = models.TextField(null=True, blank=True) stderr = models.TextField(null=True, blank=True) retcode = models.IntegerField(null=True, blank=True) execution_time = models.CharField(max_length=100, null=True, blank=True) # cpu and mem check history history = ArrayField( models.IntegerField(blank=True), null=True, blank=True, default=list ) # win service checks svc_name = models.CharField(max_length=255, null=True, blank=True) svc_display_name = models.CharField(max_length=255, null=True, blank=True) pass_if_start_pending = models.BooleanField(null=True, blank=True) pass_if_svc_not_exist = models.BooleanField(default=False) restart_if_stopped = models.BooleanField(null=True, blank=True) svc_policy_mode = models.CharField( max_length=20, null=True, blank=True ) # 'default' or 'manual', for editing policy check # event log checks log_name = models.CharField( max_length=255, choices=EVT_LOG_NAME_CHOICES, null=True, blank=True ) event_id = models.IntegerField(null=True, blank=True) event_id_is_wildcard = models.BooleanField(default=False) event_type = models.CharField( max_length=255, choices=EVT_LOG_TYPE_CHOICES, null=True, blank=True ) event_source = models.CharField(max_length=255, null=True, blank=True) event_message = models.TextField(null=True, blank=True) fail_when = models.CharField( max_length=255, choices=EVT_LOG_FAIL_WHEN_CHOICES, null=True, blank=True ) search_last_days = models.PositiveIntegerField(null=True, blank=True) def __str__(self): if self.agent: return f"{self.agent.hostname} - {self.readable_desc}" else: return f"{self.policy.name} - {self.readable_desc}" @property def readable_desc(self): if self.check_type == "diskspace": text = "" if self.warning_threshold: text += f" Warning Threshold: {self.warning_threshold}%" if self.error_threshold: text += f" Error Threshold: {self.error_threshold}%" return f"{self.get_check_type_display()}: Drive {self.disk} - {text}" # type: ignore elif self.check_type == "ping": return f"{self.get_check_type_display()}: {self.name}" # type: ignore elif self.check_type == "cpuload" or self.check_type == "memory": text = "" if self.warning_threshold: text += f" Warning Threshold: {self.warning_threshold}%" if self.error_threshold: text += f" Error Threshold: {self.error_threshold}%" return f"{self.get_check_type_display()} - {text}" # type: ignore elif self.check_type == "winsvc": return f"{self.get_check_type_display()}: {self.svc_display_name}" # type: ignore elif self.check_type == "eventlog": return f"{self.get_check_type_display()}: {self.name}" # type: ignore elif self.check_type == "script": return f"{self.get_check_type_display()}: {self.script.name}" # type: ignore else: return "n/a" @property def history_info(self): if self.check_type == "cpuload" or self.check_type == "memory": return ", ".join(str(f"{x}%") for x in self.history[-6:]) @property def last_run_as_timezone(self): if self.last_run is not None and self.agent is not None: return self.last_run.astimezone( pytz.timezone(self.agent.timezone) ).strftime("%b-%d-%Y - %H:%M") return self.last_run @property def non_editable_fields(self) -> list[str]: return [ "check_type", "status", "more_info", "last_run", "fail_count", "outage_history", "extra_details", "stdout", "stderr", "retcode", "execution_time", "history", "readable_desc", "history_info", "parent_check", "managed_by_policy", "overriden_by_policy", "created_by", "created_time", "modified_by", "modified_time", ] def should_create_alert(self, alert_template): return ( self.dashboard_alert or self.email_alert or self.text_alert or ( alert_template and ( alert_template.check_always_alert or alert_template.check_always_email or alert_template.check_always_text ) ) ) def add_check_history(self, value: int, more_info: Any = None) -> None: CheckHistory.objects.create(check_history=self, y=value, results=more_info) def handle_checkv2(self, data): from alerts.models import Alert # cpuload or mem checks if self.check_type == "cpuload" or self.check_type == "memory": self.history.append(data["percent"]) if len(self.history) > 15: self.history = self.history[-15:] self.save(update_fields=["history"]) avg = int(mean(self.history)) if self.error_threshold and avg > self.error_threshold: self.status = "failing" self.alert_severity = "error" elif self.warning_threshold and avg > self.warning_threshold: self.status = "failing" self.alert_severity = "warning" else: self.status = "passing" # add check history self.add_check_history(data["percent"]) # diskspace checks elif self.check_type == "diskspace": if data["exists"]: percent_used = round(data["percent_used"]) total = bytes2human(data["total"]) free = bytes2human(data["free"]) if self.error_threshold and (100 - percent_used) < self.error_threshold: self.status = "failing" self.alert_severity = "error" elif ( self.warning_threshold and (100 - percent_used) < self.warning_threshold ): self.status = "failing" self.alert_severity = "warning" else: self.status = "passing" self.more_info = f"Total: {total}B, Free: {free}B" # add check history self.add_check_history(100 - percent_used) else: self.status = "failing" self.alert_severity = "error" self.more_info = f"Disk {self.disk} does not exist" self.save(update_fields=["more_info"]) # script checks elif self.check_type == "script": self.stdout = data["stdout"] self.stderr = data["stderr"] self.retcode = data["retcode"] try: # python agent self.execution_time = "{:.4f}".format(data["stop"] - data["start"]) except: # golang agent self.execution_time = "{:.4f}".format(data["runtime"]) if data["retcode"] in self.info_return_codes: self.alert_severity = "info" self.status = "failing" elif data["retcode"] in self.warning_return_codes: self.alert_severity = "warning" self.status = "failing" elif data["retcode"] != 0: self.status = "failing" self.alert_severity = "error" else: self.status = "passing" self.save( update_fields=[ "stdout", "stderr", "retcode", "execution_time", ] ) # add check history self.add_check_history( 1 if self.status == "failing" else 0, { "retcode": data["retcode"], "stdout": data["stdout"][:60], "stderr": data["stderr"][:60], "execution_time": self.execution_time, }, ) # ping checks elif self.check_type == "ping": success = ["Reply", "bytes", "time", "TTL"] output = data["output"] if data["has_stdout"]: if all(x in output for x in success): self.status = "passing" else: self.status = "failing" elif data["has_stderr"]: self.status = "failing" self.more_info = output self.save(update_fields=["more_info"]) self.add_check_history( 1 if self.status == "failing" else 0, self.more_info[:60] ) # windows service checks elif self.check_type == "winsvc": svc_stat = data["status"] self.more_info = f"Status {svc_stat.upper()}" if data["exists"]: if svc_stat == "running": self.status = "passing" elif svc_stat == "start_pending" and self.pass_if_start_pending: self.status = "passing" else: if self.agent and self.restart_if_stopped: nats_data = { "func": "winsvcaction", "payload": {"name": self.svc_name, "action": "start"}, } r = asyncio.run(self.agent.nats_cmd(nats_data, timeout=32)) if r == "timeout" or r == "natsdown": self.status = "failing" elif not r["success"] and r["errormsg"]: self.status = "failing" elif r["success"]: self.status = "passing" self.more_info = f"Status RUNNING" else: self.status = "failing" else: self.status = "failing" else: if self.pass_if_svc_not_exist: self.status = "passing" else: self.status = "failing" self.more_info = f"Service {self.svc_name} does not exist" self.save(update_fields=["more_info"]) self.add_check_history( 1 if self.status == "failing" else 0, self.more_info[:60] ) elif self.check_type == "eventlog": log = [] is_wildcard = self.event_id_is_wildcard eventType = self.event_type eventID = self.event_id source = self.event_source message = self.event_message r = data["log"] for i in r: if i["eventType"] == eventType: if not is_wildcard and not int(i["eventID"]) == eventID: continue if not source and not message: if is_wildcard: log.append(i) elif int(i["eventID"]) == eventID: log.append(i) continue if source and message: if is_wildcard: if source in i["source"] and message in i["message"]: log.append(i) elif int(i["eventID"]) == eventID: if source in i["source"] and message in i["message"]: log.append(i) continue if source and source in i["source"]: if is_wildcard: log.append(i) elif int(i["eventID"]) == eventID: log.append(i) if message and message in i["message"]: if is_wildcard: log.append(i) elif int(i["eventID"]) == eventID: log.append(i) if self.fail_when == "contains": if log: self.status = "failing" else: self.status = "passing" elif self.fail_when == "not_contains": if log: self.status = "passing" else: self.status = "failing" self.extra_details = {"log": log} self.save(update_fields=["extra_details"]) self.add_check_history( 1 if self.status == "failing" else 0, "Events Found:" + str(len(self.extra_details["log"])), ) # handle status if self.status == "failing": self.fail_count += 1 self.save(update_fields=["status", "fail_count", "alert_severity"]) if self.fail_count >= self.fails_b4_alert: Alert.handle_alert_failure(self) elif self.status == "passing": self.fail_count = 0 self.save(update_fields=["status", "fail_count", "alert_severity"]) if Alert.objects.filter(assigned_check=self, resolved=False).exists(): Alert.handle_alert_resolve(self) return self.status @staticmethod def serialize(check): # serializes the check and returns json from .serializers import CheckSerializer return CheckSerializer(check).data # for policy diskchecks @staticmethod def all_disks(): return [f"{i}:" for i in string.ascii_uppercase]
""" Core classes for autodp: Mechanism --- A `mechanism' describes a randomized algorithm and its privacy properties. All `mechanism's (e.g., those in the `mechanism_zoo' module) inherit this class. Transformer --- A transformer takes one or a list of mechanism and outputs another mechanism All `transformer's (e.g., those in the `transformer_zoo' module, e.g., amplificaiton by sampling, shuffling, and composition) inherit this class. Calibrator --- A `calibrator' takes a mechanism with parameters (e.g. noise level) and automatically choose those parameters to achieve a prespecified privacy budget. All `calibrator's (e.g., the Analytical Gaussian Mechanism calibration, and others in `calibrator_zoo'inherit this class) """ import numpy as np from autodp import converter class Mechanism(): """ The base mechanism will use typically two functions to describe the mechanism # Attributes (actually functions as well): # 1: Approximate DP: epsilon as a function of delta # 2. Renyi DP: RDP epsilon as a function of \alpha # 3. Approximate RDP: approximate RDP. RDP conditioning on a failure probability delta0. # 4. f-DP: Type II error as a function of Type I error. You can get that from Approximate-DP # or FDP directly. # 5. epsilon: Pure DP bound. If not infinity, then the mechanism satisfies pure DP. # 6. delta0: Failure probability which documents the delta to use for approximate RDP # in the case when there are no information available about the failure event. # 7. local_flag: Indicates whether the guarantees are intended to be for local differential privacy # 8. group_size: Integer measuring the granuality of DP. Default is 1. # 9. replace_one: Flag indicating whether this is for add-remove definition of DP # or replace-one version of DP, default is False # CDP and approximate-CDP will be subsumed in RDP bounds # # If we specify RDP only then it will propagate the RDP calculations to approximate-DP # and to f-DP # If we specify pure-DP only then it propagates to RDP, Approximate-DP, f-DP and so on. # If we specify approximate-DP only, then it implies an approximate RDP bound with \delta_0. # If we specify f-DP only then it propagates to other specifications. # If we specify multiple calculations, then it will take the minimum of all of them # in each category """ def __init__(self): # Initialize everything with trivial (non-private) defaults def RenyiDP(alpha): return np.inf def approxRDP(delta, alpha): return np.inf def approxDP(delta): return np.inf def fDP(fpr): fnr = 0.0 return fnr self.RenyiDP = RenyiDP self.approxRDP = approxRDP self.approxDP = approxDP self.fDP = fDP self.eps_pureDP = np.inf # equivalent to RenyiDP(np.inf) and approxDP(0). self.delta0 = np.inf # indicate the smallest allowable \delta0 in approxRDP that is not inf self.group_size = 1 # transformation that increases group size. self.replace_one = False # self.local_flag = False # for the purpose of implementating local DP. # We can convert localDP to curator DP by parallel composition and by shuffling. self.updated = False # if updated, then when getting eps, we know that directly getting # approxDP is the tightest possible. def get_approxDP(self, delta): # Output eps as a function of delta return self.approxDP(delta) def get_approxRDP(self, delta, alpha): # Output eps as a function of delta and alpha return self.approxRDP(delta, alpha) def get_RDP(self, alpha): # Output RDP eps as a function of alpha return self.RenyiDP(alpha) def get_fDP(self, fpr): # Output false negative rate as a function of false positive rate return self.fDP(fpr) def get_pureDP(self): return self.eps_pureDP def get_eps(self, delta): # Get the smallest eps fo multiple calculations eps = [self.get_pureDP(), self.get_approxDP(delta)] # add get eps from RDP and get eps from approx RDP # and check the 'updated' flag. if updated, no need to do much return np.min(eps) def propagate_updates(self, func, type_of_update, delta0=0, BBGHS_conversion=True, fDP_based_conversion=False): # This function receives a new description of the mechanisms and updates all functions # based on what is new by calling converters. if type_of_update == 'pureDP': # function is one number eps = func self.eps_pureDP = np.minimum(eps, self.eps_pureDP) approxdp_new = converter.puredp_to_approxdp(eps) self.approxDP = converter.pointwise_minimum(approxdp_new, self.approxDP) rdp_new = converter.puredp_to_rdp(eps) self.RenyiDP = converter.pointwise_minimum(rdp_new, self.RenyiDP) fdp_new = converter.puredp_to_fdp(eps) self.fDP = converter.pointwise_maximum(fdp_new, self.fDP) self.approxRDP = converter.approxdp_func_to_approxrdp(self.approxDP) self.delta0 = 0 # the minimum non-trivial approximate RDP is now 0 # lambda x: np.maximum(fdp_new(x),self.fDP(x)) elif type_of_update == 'approxDP': # func will be a tuple of two numbers eps = func[0] delta = func[1] self.approxRDP = converter.pointwise_minimum_two_arguments(self.approxRDP, converter.approxdp_to_approxrdp(eps, delta)) def approx_dp_func(delta1): if delta1 >= delta: return eps else: return np.inf self.approxDP = converter.pointwise_minimum(self.approxDP, approx_dp_func) self.fDP = converter.pointwise_maximum(self.fDP, converter.approxdp_to_fdp(eps, delta)) self.delta0 = np.minimum(self.delta0, delta) elif type_of_update == 'approxDP_func': # func outputs eps as a function of delta # optional input delta0, telling us from where \epsilon becomes infinity self.delta0 = np.minimum(delta0, self.delta0) self.fDP = converter.pointwise_maximum(self.fDP, converter.approxdp_func_to_fdp(func)) self.approxRDP = converter.pointwise_minimum_two_arguments(self.approxRDP, converter.approxdp_func_to_approxrdp(func)) self.approxDP = converter.pointwise_minimum(self.approxDP, func) elif type_of_update == 'RDP': # function output RDP eps as a function of alpha self.RenyiDP = converter.pointwise_minimum(self.RenyiDP, func) if fDP_based_conversion: fdp_log, fdp_grad_log = converter.rdp_to_fdp_and_fdp_grad_log(func) self.fDP = converter.pointwise_maximum(self.fDP, converter.rdp_to_fdp(self.RenyiDP)) # # --------- debugging code below ----------------- # # def fdp_grad(x): # return -np.exp(fdp_grad_log(np.log(x)))[0] # # def plot_fdp(x): # grad = fdp_grad(x) # y = self.fDP(x) # # def tangent_line(u): # return y + grad*(u-x) # # import matplotlib.pyplot as plt # # fpr_list, fnr_list = self.plot_fDP() # plt.figure(1) # plt.plot(fpr_list, fnr_list) # plt.plot(fpr_list, tangent_line(fpr_list)) # plt.show() # # plot_fdp(0.01) # # ------------------------------------------------ self.approxDP = converter.pointwise_minimum(self.approxDP, converter.fdp_fdp_grad_to_approxdp( fdp_log, fdp_grad_log, log_flag=True)) # self.approxDP = converter.pointwise_minimum(self.approxDP, # converter.fdp_to_approxdp(self.fDP)) else: self.approxDP = converter.pointwise_minimum(self.approxDP, converter.rdp_to_approxdp(self.RenyiDP, BBGHS_conversion=BBGHS_conversion)) self.fDP = converter.pointwise_maximum(self.fDP, converter.approxdp_func_to_fdp( self.approxDP)) elif type_of_update == 'fDP': # f-DP, input is Type I error or fpr, output is Type II error or fnr self.fDP = converter.pointwise_maximum(self.fDP, func) self.approxDP = converter.pointwise_minimum(self.approxDP, converter.fdp_to_approxdp(func)) self.approxRDP = converter.pointwise_minimum(self.approxRDP, converter.approxdp_func_to_approxrdp( self.approxDP)) elif type_of_update == 'fDP_and_grad': # the input will be two functions fdp = func[0] fdp_grad = func[1] self.fdp = converter.pointwise_maximum(self.fDP, fdp) self.approxDP = converter.pointwise_minimum(self.approxDP, converter.fdp_fdp_grad_to_approxdp(fdp, fdp_grad,log_flag=False)) self.approxRDP = converter.pointwise_minimum(self.approxRDP, converter.approxdp_func_to_approxrdp( self.approxDP)) elif type_of_update == 'fDP_and_grad_log': # the input will be two functions fun1 = func[0] fun2 = func[1] fdp = lambda x: 1 - np.exp(fun1(np.log(x))) self.fDP = converter.pointwise_maximum(self.fDP, fdp) self.approxDP = converter.pointwise_minimum(self.approxDP, converter.fdp_fdp_grad_to_approxdp(fun1, fun2, log_flag=True)) self.approxRDP = converter.pointwise_minimum(self.approxRDP, converter.approxdp_func_to_approxrdp( self.approxDP)) elif type_of_update == 'approxRDP': # func is a function of alpha and delta self.delta0 = np.minimum(delta0, self.delta0) self.approxRDP = converter.pointwise_minimum_two_arguments(self.approxRDP, func) # TODO: Write a function that converts approximateRDP to approximateDP # TODO: Write a function that converts approximateRDP to fDP. else: print(type_of_update, ' not recognized.') def set_all_representation(self, mech): """ Set all representations from a mechanism object. This is useful when constructing a mechanism object using transformers then wanted to convert to a mechanism class definition. :param mech: Input mechanism object. :return: None """ # Need to make sure that the input is a mechanism object self.approxDP = mech.approxDP self.RenyiDP = mech.RenyiDP self.fDP = mech.fDP self.eps_pureDP = mech.eps_pureDP self.delta0 = mech.delta0 # Plotting functions: returns lines for people to plot outside # Plot FNR against FPR --- hypothesis testing interpretation of DP def plot_fDP(self, length=101): fpr_list = np.linspace(0, 1, length) fnr_list = np.array([self.get_fDP(fpr) for fpr in fpr_list]) return fpr_list, fnr_list # Plot RDP function def plot_RDP(self, alphamax=101, length=101): alpha_list = np.linspace(0, alphamax, length) RDP_list = np.array([self.get_RDP(alpha) for alpha in alpha_list]) return alpha_list, RDP_list class Transformer(): """ A transformer is a callable object that takes one or more mechanism as input and **transform** them into a new mechanism """ def __init__(self): self.name = 'generic_transformer' self.unary_operator = False # If true it takes one mechanism as an input, # otherwise it could take many, e.g., composition self.preprocessing = False # Relevant if unary is true, it specifies whether the operation # is before or after the mechanism, e.g., amplification by sampling is before applying the # mechanism, "amplification by shuffling" is after applying the LDP mechanisms self.transform = lambda x: x def __call__(self, *args, **kwargs): return self.transform(*args, **kwargs) class Calibrator(): """ A calibrator calibrates noise (or other parameters) meet a pre-scribed privacy budget """ def __init__(self): self.name =
#!/usr/bin/env python # -*- coding: UTF-8 -*- import discord import discord.ext.commands as commands import os import re from typing import Callable, Dict, List, Optional, Tuple, Union import pss_assert from cache import PssCache import pss_core as core import pss_entity as entity import pss_lookups as lookups import pss_sprites as sprites import pss_training as training import resources import settings import utility as util # TODO: Create allowed values dictionary upon start. # Get all item designs, split each ones name on ' ' and add each combination of 2 characters found to ALLOWED_ITEM_NAMES # ---------- Constants ---------- ITEM_DESIGN_BASE_PATH = 'ItemService/ListItemDesigns2?languageKey=en' ITEM_DESIGN_KEY_NAME = 'ItemDesignId' ITEM_DESIGN_DESCRIPTION_PROPERTY_NAME = 'ItemDesignName' RX_ARTIFACTS_INDICATORS = re.compile(r'\(\w{1,2}\)|fragment', re.IGNORECASE) ARTIFACTS_INDICATORS = [ '(au)', '(c)', '(dm)', '(fe)', 'fragment', '(si)', '(ti)' ] CANNOT_BE_SOLD = 'Can\'t be sold' # ---------- Item info ---------- async def get_item_details_by_name(item_name: str, ctx: commands.Context, as_embed: bool = settings.USE_EMBEDS): pss_assert.valid_entity_name(item_name, allowed_values=ALLOWED_ITEM_NAMES) items_data = await items_designs_retriever.get_data_dict3() item_infos = _get_item_infos_by_name(item_name, items_data) if not item_infos: return [f'Could not find an item named **{item_name}**.'], False else: trainings_data = await training.trainings_designs_retriever.get_data_dict3() items_data_for_sort = {item_info.get(ITEM_DESIGN_KEY_NAME): item_info for item_info in item_infos} item_infos = sorted(item_infos, key=lambda item_info: ( _get_key_for_base_items_sort(item_info, items_data_for_sort) )) items_details_collection = __create_base_details_collection_from_infos(item_infos, items_data, trainings_data) if as_embed: return (await items_details_collection.get_entity_details_as_embed(ctx, custom_footer_text=resources.get_resource('PRICE_NOTE_EMBED'))), True else: return (await items_details_collection.get_entity_details_as_text(custom_footer_text=resources.get_resource('PRICE_NOTE'))), True def _get_key_for_base_items_sort(item_info: dict, items_data: entity.EntitiesData) -> str: result = item_info.get(ITEM_DESIGN_DESCRIPTION_PROPERTY_NAME) item_sub_type = item_info.get('ItemSubType') if entity.has_value(item_sub_type) and item_sub_type in lookups.ITEM_SUB_TYPES_TO_GET_PARENTS_FOR: parents = __get_parents(item_info, items_data) if parents: result = parents[0].get(ITEM_DESIGN_DESCRIPTION_PROPERTY_NAME) result += ''.join([item_info.get(ITEM_DESIGN_KEY_NAME).zfill(4) for item_info in parents]) return result # ---------- Best info ----------- _SLOTS_AVAILABLE = 'These are valid values for the _slot_ parameter: all/any (for all slots), {}'.format(', '.join(lookups.EQUIPMENT_SLOTS_LOOKUP.keys())) _STATS_AVAILABLE = 'These are valid values for the _stat_ parameter: {}'.format(', '.join(lookups.STAT_TYPES_LOOKUP.keys())) async def get_best_items(slot: str, stat: str, ctx: commands.Context = None, as_embed: bool = settings.USE_EMBEDS): pss_assert.valid_parameter_value(slot, 'slot', allowed_values=lookups.EQUIPMENT_SLOTS_LOOKUP.keys(), allow_none_or_empty=True) pss_assert.valid_parameter_value(stat, 'stat', allowed_values=lookups.STAT_TYPES_LOOKUP.keys()) items_details = await items_designs_retriever.get_data_dict3() error = _get_best_items_error(slot, stat) if error: return error, False any_slot = not slot or slot == 'all' or slot == 'any' slot_filter = _get_slot_filter(slot, any_slot) stat_filter = _get_stat_filter(stat) best_items = _get_best_items_designs(slot_filter, stat_filter, items_details) if not best_items: return [f'Could not find an item for slot **{slot}** providing bonus **{stat}**.'], False else: groups = await __get_collection_groups(best_items, ctx, stat_filter, as_embed) result = [] if as_embed: for title, best_items_collection in groups.items(): footer = __get_footer_text_for_group(title, as_embed) embeds = await best_items_collection.get_entity_details_as_embed(ctx, custom_title=title, custom_footer_text=footer) result.extend(embeds) return result, True else: module_title = None for title, best_items_collection in groups.items(): if 'module' in title.lower(): module_title = title texts = await best_items_collection.get_entity_details_as_text(custom_title=title) result.extend(texts) result.append(settings.EMPTY_LINE) footer = __get_footer_text_for_group(module_title, as_embed) result.append(footer) return result, True def __get_footer_text_for_group(group_title: str, as_embed: bool) -> str: result = [] if group_title and 'module' in group_title.lower(): if as_embed: result.append(resources.get_resource('HERO_MODULE_NOTE_EMBED')) else: result.append(resources.get_resource('HERO_MODULE_NOTE')) if as_embed: result.append(resources.get_resource('PRICE_NOTE_EMBED')) else: result.append(resources.get_resource('PRICE_NOTE')) return '\n'.join(result) async def __get_collection_groups(best_items: Dict[str, List[entity.EntityDetails]], ctx: commands.Context, stat: str, as_embed: bool) -> Dict[str, entity.EntityDetailsCollection]: result = {} group_names_sorted = sorted(best_items.keys(), key=lambda x: lookups.EQUIPMENT_SLOTS_ORDER_LOOKUP.index(x)) for group_name in group_names_sorted: group = best_items[group_name] title = _get_best_title(stat, *_get_pretty_slot(group_name), use_markdown=(not as_embed)) items_details_collection = __create_best_details_collection_from_details(group) result[title] = items_details_collection return result def _get_best_items_designs(slot_filter: List[str], stat_filter: str, items_data: dict) -> Dict[str, List[entity.EntityDetails]]: filters = { 'ItemType': 'Equipment', 'ItemSubType': slot_filter, 'EnhancementType': stat_filter } result = {} filtered_data = core.filter_data_dict(items_data, filters, ignore_case=True) if filtered_data: items_infos = sorted(filtered_data.values(), key=_get_key_for_best_items_sort) # Filter out destroyed modules items_infos = [item_info for item_info in items_infos if item_info.get('ItemSubType') != 'Module' or entity.has_value(item_info.get('ModuleArgument'))] items_details = __create_best_details_list_from_infos(items_infos, items_data) result = entity.group_entities_details(items_details, 'ItemSubType') return result def _get_best_items_error(slot: str, stat: str) -> list: if not stat: return [f'You must specify a stat!', _STATS_AVAILABLE] if slot: slot = slot.lower() if slot not in lookups.EQUIPMENT_SLOTS_LOOKUP.keys() and slot not in ['all', 'any']: return [f'The specified equipment slot is not valid!', _SLOTS_AVAILABLE] if stat.lower() not in lookups.STAT_TYPES_LOOKUP.keys(): return [f'The specified stat is not valid!', _STATS_AVAILABLE] return [] def _get_best_title(stat: str, slot: str, is_equipment_slot: bool, use_markdown: bool = True) -> str: bold_marker = '**' if use_markdown else '' slot_text = ' slot' if is_equipment_slot else 's' return f'Best {bold_marker}{stat}{bold_marker} bonus for {bold_marker}{slot}{bold_marker}{slot_text}' def _get_key_for_best_items_sort(item_info: dict) -> str: if item_info.get('EnhancementValue') and item_info.get(ITEM_DESIGN_DESCRIPTION_PROPERTY_NAME): slot = item_info['ItemSubType'] rarity_num = lookups.RARITY_ORDER_LOOKUP[item_info['Rarity']] enhancement_value = int((1000.0 - float(item_info['EnhancementValue'])) * 10) item_name = item_info[ITEM_DESIGN_DESCRIPTION_PROPERTY_NAME] result = f'{enhancement_value}{slot}{rarity_num}{item_name}' return result def _get_pretty_slot(slot: str) -> Tuple[str, bool]: """ Returns: (slot name, is equipment) """ if 'Equipment' in slot: return slot.replace('Equipment', ''), True else: return slot, False # ---------- Price info ---------- async def get_item_price(item_name: str, ctx: commands.Context = None, as_embed: bool = settings.USE_EMBEDS): pss_assert.valid_entity_name(item_name, allowed_values=ALLOWED_ITEM_NAMES) items_data = await items_designs_retriever.get_data_dict3() item_infos = _get_item_infos_by_name(item_name, items_data) if not item_infos: return [f'Could not find an item named **{item_name}**.'], False else: get_best_match = util.is_str_in_list(item_name, ALLOWED_ITEM_NAMES, case_sensitive=False) and len(item_name) < settings.MIN_ENTITY_NAME_LENGTH - 1 if get_best_match: item_infos = [item_infos[0]] item_infos = util.sort_entities_by(item_infos, [(ITEM_DESIGN_DESCRIPTION_PROPERTY_NAME, None, False)]) items_details_collection = __create_price_details_collection_from_infos(item_infos, items_data) if as_embed: custom_footer = '\n'.join([resources.get_resource('MARKET_FAIR_PRICE_NOTE_EMBED'), resources.get_resource('PRICE_NOTE_EMBED')]) return (await items_details_collection.get_entity_details_as_embed(ctx, custom_footer_text=custom_footer)), True else: custom_footer = '\n'.join([resources.get_resource('MARKET_FAIR_PRICE_NOTE'), resources.get_resource('PRICE_NOTE')]) return (await items_details_collection.get_entity_details_as_text()), True # ---------- Ingredients info ---------- async def get_ingredients_for_item(item_name: str, ctx: commands.Context = None, as_embed: bool = settings.USE_EMBEDS): pss_assert.valid_entity_name(item_name, allowed_values=ALLOWED_ITEM_NAMES) items_data = await items_designs_retriever.get_data_dict3() item_infos = _get_item_infos_by_name(item_name, items_data, return_best_match=True) if not item_infos: return [f'Could not find an item named **{item_name}**.'], False else: ingredients_details_collection = __create_ingredients_details_collection_from_infos([item_infos[0]], items_data) if as_embed: return (await ingredients_details_collection.get_entity_details_as_embed(ctx, custom_footer_text=resources.get_resource('PRICE_NOTE_EMBED'))), True else: return (await ingredients_details_collection.get_entity_details_as_text(custom_footer_text=resources.get_resource('PRICE_NOTE'))), True item_info = item_infos[0] item_name = item_info[ITEM_DESIGN_DESCRIPTION_PROPERTY_NAME] ingredients_tree = _parse_ingredients_tree(item_info['Ingredients'], items_data) ingredients_dicts = _flatten_ingredients_tree(ingredients_tree) if as_embed: return (await _get_item_ingredients_as_embed(item_info, ingredients_dicts, items_data, ctx)), True else: return _get_item_ingredients_as_text(item_info, ingredients_dicts, items_data), True async def _get_item_ingredients_as_embed(item_info, ingredients_dicts, item_design_data, ctx) -> List[discord.Embed]: item_name = item_info.get(ITEM_DESIGN_DESCRIPTION_PROPERTY_NAME) ingredients_dicts = [d for d in ingredients_dicts if d] lines = [] if ingredients_dicts: for ingredients_dict in ingredients_dicts: current_level_lines = [] current_level_costs = 0 for ingredient_item_id, ingredient_amount in ingredients_dict.items(): ingredient_item_info = item_design_data[ingredient_item_id] ingredient_name = ingredient_item_info[ITEM_DESIGN_DESCRIPTION_PROPERTY_NAME] ingredient_price = int(ingredient_item_info['MarketPrice']) price_sum = ingredient_price * ingredient_amount current_level_costs += price_sum current_level_lines.append(f'> {ingredient_amount} x {ingredient_name} ({ingredient_price} bux ea): {price_sum} bux') lines.extend(current_level_lines) lines.append(f'Crafting costs: {current_level_costs} bux') lines.append(settings.EMPTY_LINE) else: lines.append('This item can\'t be crafted') title = f'Ingredients for: {item_name}' description = '\n'.join(lines) thumbnail_url = await sprites.get_download_sprite_link(item_info.get('ImageSpriteId')) colour = util.get_bot_member_colour(ctx.bot, ctx.guild) result = util.create_embed(title, description=description, colour=colour, thumbnail_url=thumbnail_url, footer=resources.get_resource('PRICE_NOTE_EMBED')) return [result] def _get_item_ingredients_as_text(item_info, ingredients_dicts, item_design_data): item_name = item_info.get(ITEM_DESIGN_DESCRIPTION_PROPERTY_NAME) lines = [f'**Ingredients for {item_name}**'] ingredients_dicts = [d for d in ingredients_dicts if d] if ingredients_dicts: for ingredients_dict in ingredients_dicts: current_level_lines = [] current_level_costs = 0 for ingredient_item_id, ingredient_amount in ingredients_dict.items(): ingredient_item_info = item_design_data[ingredient_item_id] ingredient_name = ingredient_item_info[ITEM_DESIGN_DESCRIPTION_PROPERTY_NAME] ingredient_price = int(ingredient_item_info['MarketPrice']) price_sum = ingredient_price * ingredient_amount current_level_costs += price_sum current_level_lines.append(f'> {ingredient_amount} x {ingredient_name} ({ingredient_price} bux ea): {price_sum} bux') lines.extend(current_level_lines) lines.append(f'Crafting costs: {current_level_costs} bux') lines.append(settings.EMPTY_LINE) lines.append(resources.get_resource('PRICE_NOTE')) else: lines.append('This item can\'t be crafted') return lines def _parse_ingredients_tree(ingredients_str: str, item_design_data: dict, include_partial_artifacts: bool, parent_amount: int = 1) -> List[Tuple[str, str, list]]: """returns a tree structure: [(item_id, item_amount, item_ingredients[])]""" if not ingredients_str: return [] # Ingredients format is: [<id>x<amount>][|<id>x<amount>]* ingredients_dict = _get_ingredients_dict(ingredients_str) result = [] for item_id, item_amount in ingredients_dict.items(): item_info = item_design_data[item_id] item_name = item_info[ITEM_DESIGN_DESCRIPTION_PROPERTY_NAME].lower() item_amount = int(item_amount) # Filter out void particles and fragments if include_partial_artifacts or ('void particle' not in item_name and ' fragment' not in item_name): combined_amount = item_amount * parent_amount item_ingredients = _parse_ingredients_tree(item_info['Ingredients'], item_design_data, include_partial_artifacts, combined_amount) result.append((item_id, combined_amount, item_ingredients)) return result def _get_ingredients_dict(ingredients: str) -> dict: result = {} if entity.has_value(ingredients): result = dict([ingredient.split('x') for ingredient in ingredients.split('|')]) return result def _flatten_ingredients_tree(ingredients_tree: list) -> list: """Returns a list of dicts""" ingredients = {} ingredients_without_subs = [] sub_ingredients = [] for item_id, item_amount, item_ingredients in ingredients_tree: if item_id in ingredients.keys(): ingredients[item_id] += item_amount else: ingredients[item_id] = item_amount if item_ingredients: sub_ingredients.extend(item_ingredients) else: ingredients_without_subs.append((item_id, item_amount, item_ingredients)) result = [ingredients] if len(ingredients_without_subs) != len(ingredients_tree): sub_ingredients.extend(ingredients_without_subs) flattened_subs = _flatten_ingredients_tree(sub_ingredients) result.extend(flattened_subs) return result # ---------- Upgrade info ---------- async def get_item_upgrades_from_name(item_name: str, ctx: commands.Context, as_embed: bool = settings.USE_EMBEDS): pss_assert.valid_entity_name(item_name, allowed_values=ALLOWED_ITEM_NAMES) items_data = await items_designs_retriever.get_data_dict3() item_ids = _get_item_design_ids_from_name(item_name, items_data) if not item_ids: return [f'Could not find an item named **{item_name}**.'], False else: item_infos = [] for item_id in item_ids: item_infos.extend(_get_upgrades_for(item_id, items_data)) item_infos = list(dict([(item_info[ITEM_DESIGN_KEY_NAME], item_info) for item_info in item_infos]).values()) item_infos = util.sort_entities_by(item_infos, [(ITEM_DESIGN_DESCRIPTION_PROPERTY_NAME, None, False)]) upgrade_details_collection = __create_upgrade_details_collection_from_infos(item_infos, items_data) if as_embed: custom_title = f'{len(item_infos)} crafting recipes requiring: {item_name}' return (await upgrade_details_collection.get_entity_details_as_embed(ctx, custom_title=custom_title)), True else: custom_title = f'{len(item_infos)} crafting recipes requiring: **{item_name}**' return (await upgrade_details_collection.get_entity_details_as_text(custom_title=custom_title, big_set_details_type=entity.EntityDetailsType.LONG)), True def _get_upgrades_for(item_id: str, item_design_data: dict) -> list: # iterate through item_design_data and return every item_design containing the item id in question in property 'Ingredients' result = [] for item_info in item_design_data.values(): ingredient_item_ids = list(_get_ingredients_dict(item_info['Ingredients']).keys()) if item_id in
an inspector per row. def children( self, target ) : return [] ########################################################################## # DiffRow ########################################################################## ## A row which displays a diff from values generated by an Inspector. class DiffRow( Row ) : def __init__( self, inspector, diffCreator = TextDiff, alternate = False, **kw ) : assert( isinstance( inspector, Inspector ) ) Row.__init__( self, alternate=alternate, **kw ) with self.listContainer() : label = GafferUI.Label( inspector.name(), horizontalAlignment = GafferUI.Label.HorizontalAlignment.Right, verticalAlignment = GafferUI.Label.VerticalAlignment.Top ) label._qtWidget().setFixedWidth( 150 ) diff = diffCreator() self.listContainer().append( diff ) if inspector.inspectsAttributes() and isinstance( diff, SideBySideDiff ) : diff.setCornerWidget( 0, GafferUI.Label( "" ) ) diff.setCornerWidget( 1, GafferUI.Label( "" ) ) self.__diffConnections = [] diffWidgets = [ diff.frame( 0 ), diff.frame( 1 ) ] if isinstance( diff, SideBySideDiff ) else [ diff ] for diffWidget in diffWidgets : self.__diffConnections.extend( [ diffWidget.enterSignal().connect( Gaffer.WeakMethod( self.__enter ) ), diffWidget.leaveSignal().connect( Gaffer.WeakMethod( self.__leave ) ), diffWidget.contextMenuSignal().connect( Gaffer.WeakMethod( self.__contextMenu ) ), ] ) GafferUI.Spacer( IECore.V2i( 0 ), parenting = { "expand" : True } ) self.__inspector = inspector self.__diffCreator = diffCreator def inspector( self ) : return self.__inspector def update( self, targets ) : self.__targets = targets self.__values = [ self.__inspector( target ) for target in targets ] self.__diff().update( self.__values ) if self.__inspector.inspectsAttributes() and isinstance( self.__diff(), SideBySideDiff ) : localValues = [ self.__inspector( target, ignoreInheritance=True ) for target in targets ] for i, value in enumerate( localValues ) : self.__diff().getCornerWidget( i ).setText( "<sup>Inherited</sup>" if value is None else "" ) def __label( self ) : return self.listContainer()[0] def __diff( self ) : return self.listContainer()[1] def __enter( self, widget ) : GafferUI.Pointer.setCurrent( "contextMenu" ) def __leave( self, widget ) : GafferUI.Pointer.setCurrent( None ) def __contextMenu( self, widget ) : GafferUI.Pointer.setCurrent( None ) self.__menu = GafferUI.Menu( IECore.curry( Gaffer.WeakMethod( self.__menuDefinition ), widget ) ) self.__menu.popup() def __menuDefinition( self, widget ) : diff = self.__diff() if isinstance( diff, SideBySideDiff ) : # For SideBySideDiffs, we know which target the user has clicked on # and only present menu items for that target. targets = [ self.__targets[ 0 if widget is diff.frame( 0 ) else 1 ] ] else : # But for other Diff types we don't know, and so present menu items # for any target which has a value. targets = [ t for i, t in enumerate( self.__targets ) if self.__values[i] is not None ] m = IECore.MenuDefinition() for i, target in enumerate( targets ) : if len( targets ) == 2 : labelSuffix = "/For " + ( "A", "B" )[i] else : labelSuffix = "" m.append( "/Show History" + labelSuffix, { "command" : IECore.curry( Gaffer.WeakMethod( self.__showHistory ), target ), } ) if self.__inspector.inspectsAttributes() : m.append( "/Show Inheritance" + labelSuffix, { "command" : IECore.curry( Gaffer.WeakMethod( self.__showInheritance ), target ), } ) return m def __showInheritance( self, target ) : w = _SectionWindow( target.scene.node().getName() + " : " + self.__label().getText(), _InheritanceSection( self.__inspector, self.__diffCreator ), target ) self.ancestor( GafferUI.Window ).addChildWindow( w, removeOnClose = True ) w.setVisible( True ) def __showHistory( self, target ) : w = _SectionWindow( target.scene.node().getName() + " : " + self.__label().getText(), _HistorySection( self.__inspector, self.__diffCreator ), target ) self.ancestor( GafferUI.Window ).addChildWindow( w, removeOnClose = True ) w.setVisible( True ) ########################################################################## # DiffColumn ########################################################################## ## Class for displaying a column of DiffRows. class DiffColumn( GafferUI.Widget ) : def __init__( self, inspector, diffCreator = TextDiff, label = None, filterable = False, **kw ) : outerColumn = GafferUI.ListContainer() GafferUI.Widget.__init__( self, outerColumn, **kw ) assert( isinstance( inspector, Inspector ) ) self.__inspector = inspector self.__rows = {} # mapping from row name to row self.__diffCreator = diffCreator with outerColumn : with GafferUI.Frame( borderWidth = 4, borderStyle = GafferUI.Frame.BorderStyle.None ) as self.__header : with GafferUI.ListContainer( GafferUI.ListContainer.Orientation.Horizontal ) : if label is not None : l = GafferUI.Label( "<b>" + label + "</b>", horizontalAlignment = GafferUI.Label.HorizontalAlignment.Right, ) l._qtWidget().setFixedWidth( 150 ) self.__filterWidget = None if filterable : self.__filterWidget = GafferUI.TextWidget() self.__filterWidget._qtWidget().setPlaceholderText( "Filter..." ) self.__filterTextChangedConnection = self.__filterWidget.textChangedSignal().connect( Gaffer.WeakMethod( self.__filterTextChanged ) ) self.__rowContainer = GafferUI.ListContainer() @GafferUI.LazyMethod() def update( self, targets ) : # this doesn't always get called by SceneInspector.__update(), so we grab the # context from the ancestor NodeSetEditor if it exists, and make it current: nodeSetEditor = self.ancestor( GafferUI.NodeSetEditor ) context = nodeSetEditor.getContext() if nodeSetEditor else Gaffer.Context.current() with context: inspectors = {} for target in targets : inspectors.update( { i.name() : i for i in self.__inspector.children( target ) } ) # mark all rows as invalid for row in self.__rowContainer : row.__valid = False # iterate over the fields we want to display, # creating/updating the rows that are to be valid. for rowName in inspectors.keys() : row = self.__rows.get( rowName ) if row is None : row = DiffRow( inspectors[rowName], self.__diffCreator ) self.__rows[rowName] = row row.update( targets ) row.__valid = True # update the rowContainer with _all_ rows (both # valid and invalid) in the correct order. this # is a no-op except when adding new rows. it is # much quicker to hide invalid rows than it is # to reparent widgets so that the container only # contains the valid ones. self.__rowContainer[:] = sorted( self.__rows.values(), key = lambda r : r.inspector().name() ) # show only the currently valid ones. self.__updateRowVisibility() def __updateRowVisibility( self ) : patterns = self.__filterWidget.getText() if self.__filterWidget is not None else "" if not patterns : patterns = "*" else : patterns = [ p.lower() for p in patterns.split() ] patterns = " ".join( "*" + p + "*" if "*" not in p else p for p in patterns ) numValidRows = 0 numVisibleRows = 0 for row in self.__rowContainer : visible = False if row.__valid : numValidRows += 1 if Gaffer.StringAlgo.matchMultiple( row.inspector().name().lower(), patterns ) : visible = True row.setVisible( visible ) if visible : row.setAlternate( numVisibleRows % 2 ) numVisibleRows += 1 self.__header.setVisible( numValidRows ) def __filterTextChanged( self, filterWidget ) : self.__updateRowVisibility() ########################################################################## # Section ########################################################################## ## Base class for widgets which make up a section of the SceneInspector. class Section( GafferUI.Widget ) : def __init__( self, collapsed = False, label = None, **kw ) : self.__mainColumn = GafferUI.ListContainer( GafferUI.ListContainer.Orientation.Vertical, spacing = 0 ) self.__collapsible = None if collapsed is not None : self.__collapsible = GafferUI.Collapsible( label=label, collapsed=collapsed ) self.__collapsible.setChild( self.__mainColumn ) GafferUI.Widget.__init__( self, self.__collapsible if self.__collapsible is not None else self.__mainColumn, **kw ) self.__numRows = 0 ## Should be implemented by derived classes to update the # UI to reflect the state of the targets. Implementations should # first call the base class implementation. def update( self, targets ) : if self.__collapsible is None : return label = self.__collapsible.getCornerWidget() summary = self._summary( targets ) if summary is None and label is None : return if label is None : label = GafferUI.Label() label._qtWidget().setSizePolicy( QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed ) self.__collapsible.setCornerWidget( label, True ) if summary : summary = "<small>" + "&nbsp;( " + summary + " ) </small>" label.setText( summary ) ## May be implemented by derived classes to provide # a short summary of the contents. def _summary( self, targets ) : return None def _mainColumn( self ) : return self.__mainColumn # export classes for use in custom sections SceneInspector.Diff = Diff SceneInspector.SideBySideDiff = SideBySideDiff SceneInspector.TextDiff = TextDiff SceneInspector.Row = Row SceneInspector.Inspector = Inspector SceneInspector.DiffRow = DiffRow SceneInspector.DiffColumn = DiffColumn SceneInspector.Section = Section ########################################################################## # Section window ########################################################################## class _SectionWindow( GafferUI.Window ) : def __init__( self, title, section, target ) : GafferUI.Window.__init__( self, title, borderWidth = 4 ) editor = SceneInspector( target.scene.ancestor( Gaffer.ScriptNode ), sections = [ section ] ) editor.setTargetPaths( [ target.path ] ) editor.setNodeSet( Gaffer.StandardSet( [ target.scene.node() ] ) ) self.setChild( editor ) self.__nodeSetMemberRemovedConnection = editor.getNodeSet().memberRemovedSignal().connect( Gaffer.WeakMethod( self.__nodeSetMemberRemoved ) ) def __nodeSetMemberRemoved( self, set, node ) : self.parent().removeChild( self ) ########################################################################## # Inheritance section ########################################################################## QtGui = GafferUI._qtImport( "QtGui" ) class _Rail( GafferUI.ListContainer ) : Type = IECore.Enum.create( "Top", "Middle", "Gap", "Bottom", "Single" ) def __init__( self, type, **kw ) : GafferUI.ListContainer.__init__( self, **kw ) with self : if type != self.Type.Top and type != self.Type.Single : image = GafferUI.Image( "railLine.png" ) ## \todo Decide how we do this via the public API. # Perhaps by putting the image in a Sizer? Or by # adding stretch methods to the Image class? image._qtWidget().setSizePolicy( QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred ) image._qtWidget().setScaledContents( True ) else : GafferUI.Spacer( IECore.V2i( 1 ) ) GafferUI.Image( "rail" + str( type ) + ".png" ) if type != self.Type.Bottom and type != self.Type.Single : image = GafferUI.Image( "railLine.png" ) image._qtWidget().setSizePolicy( QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred ) image._qtWidget().setScaledContents( True ) else : GafferUI.Spacer( IECore.V2i( 1 ) ) class _InheritanceSection( Section ) : def __init__( self, inspector, diffCreator = TextDiff, **kw ) : Section.__init__( self, collapsed = None, **kw ) self.__inspector = inspector self.__diffCreator = diffCreator def update( self, targets ) : Section.update( self, targets ) self.__target = targets[0] self.__connections = [] if self.__target.path is None : return rows = [] fullPath = self.__target.path.split( "/" )[1:] if self.__target.path != "/" else [] prevValue = None # local value from last iteration prevDisplayedValue = None # the last value we displayed fullValue = None # full value taking into account inheritance for i in range( 0, len( fullPath ) + 1 ) : path = "/" + "/".join( fullPath[:i] ) value = self.__inspector( SceneInspector.Target( self.__target.scene, path ), ignoreInheritance=True ) fullValue = value if value is not None else fullValue atEitherEnd = ( i == 0 or i == len( fullPath ) ) if value is not None or atEitherEnd or prevValue is not None or i == 1 : row = Row( borderWidth = 0, alternate = len( rows ) % 2 ) rows.append( row ) with row.listContainer() : if atEitherEnd : _Rail( _Rail.Type.Top if i == 0 else _Rail.Type.Bottom ) else : _Rail( _Rail.Type.Middle if
#!/usr/bin/env python # encoding: utf-8 """ @author: zhanghe @software: PyCharm @file: production.py @time: 2018-03-16 09:59 """ from __future__ import unicode_literals from datetime import datetime from flask import ( request, flash, render_template, url_for, redirect, abort, jsonify, Blueprint, ) from flask_babel import gettext as _ from flask_login import login_required from six import text_type from app_backend import app from app_backend import excel from app_backend.api.production import get_production_choices from app_backend.api.production import ( get_production_pagination, get_production_row_by_id, add_production, edit_production, # production_current_stats, # production_former_stats, ) from app_backend.api.production import ( get_production_rows, ) from app_backend.api.production_sensitive import count_production_sensitive from app_backend.api.quotation_items import count_quotation_items from app_backend.forms.production import ( ProductionSearchForm, ProductionAddForm, ProductionEditForm, ProductionSelectForm, get_production_brand_choices) from app_backend.models.model_bearing import Production from app_backend.permissions import permission_role_administrator from app_backend.permissions.production import ( permission_production_section_add, permission_production_section_search, permission_production_section_del, ) from app_common.maps.default import DEFAULT_SEARCH_CHOICES_STR_OPTION from app_common.maps.operations import OPERATION_EXPORT, OPERATION_DELETE from app_common.maps.status_delete import ( STATUS_DEL_OK, STATUS_DEL_NO, ) # 定义蓝图 bp_production = Blueprint('production', __name__, url_prefix='/production') # 加载配置 DOCUMENT_INFO = app.config.get('DOCUMENT_INFO', {}) PER_PAGE_BACKEND = app.config.get('PER_PAGE_BACKEND', 20) PER_PAGE_BACKEND_MODAL = app.config.get('PER_PAGE_BACKEND_MODAL', 10) AJAX_SUCCESS_MSG = app.config.get('AJAX_SUCCESS_MSG', {'result': True}) AJAX_FAILURE_MSG = app.config.get('AJAX_FAILURE_MSG', {'result': False}) @bp_production.route('/lists.html', methods=['GET', 'POST']) @login_required @permission_production_section_search.require(http_exception=403) def lists(): """ 产品列表 :return: """ template_name = 'production/lists.html' # 文档信息 document_info = DOCUMENT_INFO.copy() document_info['TITLE'] = _('production lists') # 搜索条件 form = ProductionSearchForm(request.form) form.production_brand.choices = get_production_brand_choices() # app.logger.info('') search_condition = [ Production.status_delete == STATUS_DEL_NO, ] if request.method == 'POST': # 表单校验失败 if not form.validate_on_submit(): flash(_('Search Failure'), 'danger') # 单独处理csrf_token if hasattr(form, 'csrf_token') and getattr(form, 'csrf_token').errors: map(lambda x: flash(x, 'danger'), form.csrf_token.errors) else: if form.production_brand.data != DEFAULT_SEARCH_CHOICES_STR_OPTION: search_condition.append(Production.production_brand == form.production_brand.data) if form.production_model.data: search_condition.append(Production.production_model.like('%%%s%%' % form.production_model.data)) # 处理导出 if form.op.data == OPERATION_EXPORT: # 检查导出权限 # if not permission_production_section_export.can(): # abort(403) column_names = Production.__table__.columns.keys() query_sets = get_production_rows(*search_condition) return excel.make_response_from_query_sets( query_sets=query_sets, column_names=column_names, file_type='csv', file_name='%s.csv' % _('production lists') ) # 批量删除 if form.op.data == OPERATION_DELETE: production_ids = request.form.getlist('production_id') # 检查删除权限 if not permission_role_administrator.can(): ext_msg = _('Permission Denied') flash(_('Del Failure, %(ext_msg)s', ext_msg=ext_msg), 'danger') else: permitted = True for production_id in production_ids: # 检查是否正在使用 # 报价、订单、敏感型号 if count_quotation_items(**{'production_id': production_id, 'status_delete': STATUS_DEL_NO}): ext_msg = _('Currently In Use') flash(_('Del Failure, %(ext_msg)s', ext_msg=ext_msg), 'danger') permitted = False break if count_production_sensitive(**{'production_id': production_id, 'status_delete': STATUS_DEL_NO}): ext_msg = _('Currently In Use') flash(_('Del Failure, %(ext_msg)s', ext_msg=ext_msg), 'danger') permitted = False break if permitted: result_total = True for production_id in production_ids: current_time = datetime.utcnow() production_data = { 'status_delete': STATUS_DEL_OK, 'delete_time': current_time, 'update_time': current_time, } result = edit_production(production_id, production_data) result_total = result_total and result if result_total: flash(_('Del Success'), 'success') else: flash(_('Del Failure'), 'danger') # 翻页数据 pagination = get_production_pagination(form.page.data, PER_PAGE_BACKEND, *search_condition) # 渲染模板 return render_template( template_name, form=form, pagination=pagination, **document_info ) @bp_production.route('/search.html', methods=['GET', 'POST']) @login_required @permission_production_section_search.require(http_exception=403) def search(): """ 产品搜索 :return: """ template_name = 'production/search_modal.html' # 文档信息 document_info = DOCUMENT_INFO.copy() document_info['TITLE'] = _('Production Search') # 搜索条件 form = ProductionSearchForm(request.form) form.production_brand.choices = get_production_brand_choices() # app.logger.info('') search_condition = [ Production.status_delete == STATUS_DEL_NO, ] if request.method == 'POST': # 表单校验失败 if not form.validate_on_submit(): flash(_('Search Failure'), 'danger') # 单独处理csrf_token if hasattr(form, 'csrf_token') and getattr(form, 'csrf_token').errors: map(lambda x: flash(x, 'danger'), form.csrf_token.errors) else: if form.production_brand.data != DEFAULT_SEARCH_CHOICES_STR_OPTION: search_condition.append(Production.production_brand == form.production_brand.data) if form.production_model.data: search_condition.append(Production.production_model.like('%s%%' % form.production_model.data)) # 翻页数据 pagination = get_production_pagination(form.page.data, PER_PAGE_BACKEND_MODAL, *search_condition) # 渲染模板 return render_template( template_name, form=form, pagination=pagination, **document_info ) @bp_production.route('/<int:production_id>/info.html') @login_required def info(production_id): """ 产品详情 :param production_id: :return: """ # 详情数据 production_info = get_production_row_by_id(production_id) # 检查资源是否存在 if not production_info: abort(404) # 检查资源是否删除 if production_info.status_delete == STATUS_DEL_OK: abort(410) # 文档信息 document_info = DOCUMENT_INFO.copy() document_info['TITLE'] = _('production info') # 渲染模板 return render_template('production/info.html', production_info=production_info, **document_info) @bp_production.route('/add.html', methods=['GET', 'POST']) @login_required @permission_production_section_add.require(http_exception=403) def add(): """ 创建产品 :return: """ template_name = 'production/add.html' # 文档信息 document_info = DOCUMENT_INFO.copy() document_info['TITLE'] = _('production add') # 加载创建表单 form = ProductionAddForm(request.form) # 进入创建页面 if request.method == 'GET': # 渲染页面 return render_template( template_name, form=form, **document_info ) # 处理创建请求 if request.method == 'POST': # 表单校验失败 if not form.validate_on_submit(): flash(_('Add Failure'), 'danger') return render_template( template_name, form=form, **document_info ) # 表单校验成功 current_time = datetime.utcnow() production_data = { 'production_brand': form.production_brand.data.upper(), 'production_model': form.production_model.data.upper(), 'production_sku': form.production_sku.data, 'ind': form.ind.data, 'oud': form.oud.data, 'wid': form.wid.data, 'cost_ref': form.cost_ref.data, 'cost_new': form.cost_new.data, 'cost_avg': form.cost_avg.data, 'note': form.note.data, 'create_time': current_time, 'update_time': current_time, } result = add_production(production_data) # 创建操作成功 if result: flash(_('Add Success'), 'success') return redirect(request.args.get('next') or url_for('production.lists')) # 创建操作失败 else: flash(_('Add Failure'), 'danger') return render_template( template_name, form=form, **document_info ) @bp_production.route('/<int:production_id>/edit.html', methods=['GET', 'POST']) @login_required # @permission_role_administrator.require(http_exception=403) def edit(production_id): """ 产品编辑 """ production_info = get_production_row_by_id(production_id) # 检查资源是否存在 if not production_info: abort(404) # 检查资源是否删除 if production_info.status_delete == STATUS_DEL_OK: abort(410) template_name = 'production/edit.html' # 加载编辑表单 form = ProductionEditForm(request.form) # 文档信息 document_info = DOCUMENT_INFO.copy() document_info['TITLE'] = _('production edit') # 进入编辑页面 if request.method == 'GET': # 表单赋值 form.id.data = production_info.id form.production_brand.data = production_info.production_brand form.production_model.data = production_info.production_model form.production_sku.data = production_info.production_sku form.ind.data = production_info.ind form.oud.data = production_info.oud form.wid.data = production_info.wid form.cost_ref.data = production_info.cost_ref form.cost_new.data = production_info.cost_new form.cost_avg.data = production_info.cost_avg form.note.data = production_info.note form.create_time.data = production_info.create_time form.update_time.data = production_info.update_time # 渲染页面 return render_template( template_name, production_id=production_id, form=form, **document_info ) # 处理编辑请求 if request.method == 'POST': # 表单校验失败 if production_id != form.id.data or not form.validate_on_submit(): flash(_('Edit Failure'), 'danger') return render_template( template_name, production_id=production_id, form=form, **document_info ) # 表单校验成功 current_time = datetime.utcnow() production_data = { 'production_brand': form.production_brand.data.upper(), 'production_model': form.production_model.data.upper(), 'production_sku': form.production_sku.data, 'ind': form.ind.data, 'oud': form.oud.data, 'wid': form.wid.data, 'cost_ref': form.cost_ref.data, 'cost_new': form.cost_new.data, 'cost_avg': form.cost_avg.data, 'note': form.note.data, 'update_time': current_time, } result = edit_production(production_id, production_data) # 编辑操作成功 if result: flash(_('Edit Success'), 'success') return redirect(request.args.get('next') or url_for('production.lists')) # 编辑操作失败 else: flash(_('Edit Failure'), 'danger') return render_template( template_name, production_id=production_id, form=form, **document_info ) @bp_production.route('/ajax/del', methods=['GET', 'POST']) @login_required def ajax_delete(): """ 产品删除 :return: """ ajax_success_msg = AJAX_SUCCESS_MSG.copy() ajax_failure_msg = AJAX_FAILURE_MSG.copy() # 检查删除权限 if not permission_production_section_del.can(): ext_msg = _('Permission Denied') ajax_failure_msg['msg'] = _('Del Failure, %(ext_msg)s', ext_msg=ext_msg) return jsonify(ajax_failure_msg) # 检查请求方法 if not (request.method == 'GET' and request.is_xhr): ext_msg = _('Method Not Allowed') ajax_failure_msg['msg'] = _('Del Failure, %(ext_msg)s', ext_msg=ext_msg) return jsonify(ajax_failure_msg) # 检查请求参数 production_id = request.args.get('production_id', 0, type=int) if not production_id: ext_msg = _('ID does not exist') ajax_failure_msg['msg'] = _('Del Failure, %(ext_msg)s', ext_msg=ext_msg) return jsonify(ajax_failure_msg) production_info = get_production_row_by_id(production_id) # 检查资源是否存在 if not production_info: ext_msg = _('ID does not exist') ajax_failure_msg['msg'] = _('Del Failure, %(ext_msg)s', ext_msg=ext_msg) return jsonify(ajax_failure_msg) # 检查资源是否删除 if production_info.status_delete == STATUS_DEL_OK: ext_msg = _('Already deleted') ajax_failure_msg['msg'] = _('Del Failure, %(ext_msg)s', ext_msg=ext_msg) return jsonify(ajax_failure_msg) # 检查是否正在使用 # 报价、订单、敏感型号 if count_quotation_items(**{'production_id': production_id, 'status_delete': STATUS_DEL_NO}): ext_msg = _('Currently In Use') ajax_failure_msg['msg'] = _('Del Failure, %(ext_msg)s', ext_msg=ext_msg) return jsonify(ajax_failure_msg) if count_production_sensitive(**{'production_id': production_id, 'status_delete': STATUS_DEL_NO}): ext_msg = _('Currently In Use') ajax_failure_msg['msg'] = _('Del Failure, %(ext_msg)s', ext_msg=ext_msg) return jsonify(ajax_failure_msg) current_time = datetime.utcnow() production_data = { 'status_delete': STATUS_DEL_OK, 'delete_time': current_time, 'update_time': current_time, } result = edit_production(production_id, production_data) if result: ajax_success_msg['msg'] = _('Del Success') return jsonify(ajax_success_msg) else: ajax_failure_msg['msg'] = _('Del Failure') return jsonify(ajax_failure_msg) @bp_production.route('/ajax/search/modal', methods=['GET', 'POST']) @login_required def ajax_search_modal(): """ 动态搜索产品 :return: """ ajax_success_msg = AJAX_SUCCESS_MSG.copy() ajax_failure_msg = AJAX_FAILURE_MSG.copy() # # 检查请求方法 # if not (request.method == 'GET' and request.is_xhr): # ext_msg = _('Method Not Allowed') # ajax_failure_msg['msg'] = _('Search Failure, %(ext_msg)s', ext_msg=ext_msg) # return jsonify(ajax_failure_msg) # # # 检查请求参数 keywords = request.args.get('keywords', '', type=text_type) # if not keywords: # ext_msg = _('Args is empty') # ajax_failure_msg['msg'] = _('Search Failure, %(ext_msg)s', ext_msg=ext_msg) # return jsonify(ajax_failure_msg) # 执行搜索 production_choices = get_production_choices(keywords) form_modal = ProductionSelectForm(request.form) form_modal.production_model.choices = production_choices template_name = '_modal_production_select_form.html' return render_template( template_name, form_modal=form_modal, ) # if production_choices: # ajax_success_msg['data'] = production_choices # ajax_success_msg['msg'] = _('Search Success') # return jsonify(ajax_success_msg) # else: # ajax_failure_msg['msg'] = _('Search Failure') # return jsonify(ajax_failure_msg) @bp_production.route('/ajax/info', methods=['GET', 'POST']) @login_required def ajax_info(): """ 获取产品详情 :return: """ ajax_success_msg = AJAX_SUCCESS_MSG.copy() ajax_failure_msg = AJAX_FAILURE_MSG.copy() # 检查请求方法 if not (request.method == 'GET' and request.is_xhr): ext_msg = _('Method Not Allowed') ajax_failure_msg['msg'] = _('Get Failure, %(ext_msg)s', ext_msg=ext_msg) return jsonify(ajax_failure_msg) # 检查请求参数 production_id = request.args.get('production_id', 0, type=int) if not production_id: ext_msg = _('ID does not exist') ajax_failure_msg['msg'] = _('Get Failure, %(ext_msg)s', ext_msg=ext_msg) return jsonify(ajax_failure_msg) production_info = get_production_row_by_id(production_id) # 检查资源是否存在 if not production_info: ext_msg = _('ID does not exist') ajax_failure_msg['msg'] = _('Get Failure, %(ext_msg)s', ext_msg=ext_msg) return jsonify(ajax_failure_msg) # 检查资源是否删除 if production_info.status_delete == STATUS_DEL_OK: ext_msg = _('Already deleted') ajax_failure_msg['msg'] = _('Get Failure, %(ext_msg)s', ext_msg=ext_msg) return jsonify(ajax_failure_msg) ajax_success_msg['msg'] = _('Get Success') ajax_success_msg['data'] = production_info.to_dict() return jsonify(ajax_success_msg) # @bp_production.route('/ajax/stats', methods=['GET', 'POST']) # @login_required # def ajax_stats(): # """ # 获取产品统计 # :return: # """ # time_based = request.args.get('time_based', 'hour') # result_production_current = production_current_stats(time_based) # result_production_former = production_former_stats(time_based) # # line_chart_data = { # 'labels': [label for label, _ in result_production_current], # 'datasets': [ # { # 'label': '在职', # 'backgroundColor': 'rgba(220,220,220,0.5)', # 'borderColor': 'rgba(220,220,220,1)', # 'pointBackgroundColor': 'rgba(220,220,220,1)', # 'pointBorderColor': '#fff', # 'pointBorderWidth': 2, # 'data': [data for _, data in result_production_current] # }, # { # 'label': '离职', # 'backgroundColor': 'rgba(151,187,205,0.5)', # 'borderColor': 'rgba(151,187,205,1)', # 'pointBackgroundColor': 'rgba(151,187,205,1)', # 'pointBorderColor': '#fff', # 'pointBorderWidth': 2, # 'data': [data for _, data in result_production_former] # } # ] # } # return json.dumps(line_chart_data, default=json_default) # # # @bp_production.route('/stats.html') # @login_required # @permission_production_section_stats.require(http_exception=403) # def stats(): # """ # 产品统计 # :return: # """ # #
import copy import datetime import uuid from contextlib import contextmanager from cdislogging import get_logger from future.utils import iteritems from sqlalchemy import ( BigInteger, Column, DateTime, ForeignKey, ForeignKeyConstraint, Index, Integer, String, and_, func, not_, or_, select, ) from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.exc import IntegrityError, ProgrammingError from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import joinedload, relationship, sessionmaker from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound from indexd.errors import UserError from indexd.index.blueprint import separate_metadata from indexd.index.driver import IndexDriverABC from indexd.index.errors import ( MultipleRecordsFound, NoRecordFound, RevisionMismatch, UnhealthyCheck, ) from indexd.utils import ( init_schema_version, is_empty_database, migrate_database, ) Base = declarative_base() class BaseVersion(Base): """ Base index record version representation. This class needs to exist so the migration functions work. The class and table will continue to exist until the migration functions are modified to create tables as they were originally designed for the specific migration function version. """ __tablename__ = 'base_version' baseid = Column(String, primary_key=True) class IndexSchemaVersion(Base): """ Table to track current database's schema version """ __tablename__ = 'index_schema_version' version = Column(Integer, default=0, primary_key=True) class IndexRecord(Base): """ Base index record representation. """ __tablename__ = 'index_record' did = Column(String, primary_key=True) baseid = Column(String, index=True) rev = Column(String) form = Column(String) size = Column(BigInteger, index=True) release_number = Column(String, index=True) created_date = Column(DateTime, default=datetime.datetime.utcnow) updated_date = Column(DateTime, default=datetime.datetime.utcnow) file_name = Column(String, index=True) version = Column(String, index=True) uploader = Column(String, index=True) index_metadata = Column(JSONB) urls_metadata = relationship( 'IndexRecordUrlMetadataJsonb', backref='index_record', cascade='all, delete-orphan', ) acl = relationship( 'IndexRecordACE', backref='index_record', cascade='all, delete-orphan', ) hashes = relationship( 'IndexRecordHash', backref='index_record', cascade='all, delete-orphan', ) aliases = relationship( 'IndexRecordAlias', backref='index_record', cascade='all, delete-orphan', ) def to_document_dict(self): """ Get the full index document """ urls = [u.url for u in self.urls_metadata] acl = [u.ace for u in self.acl] hashes = {h.hash_type: h.hash_value for h in self.hashes} metadata = self.index_metadata or {} # Add this field back to the returned metadata json section. This # allows current clients to function without change. # If it doesn't exist then don't return the key in the json. if self.release_number: metadata['release_number'] = self.release_number urls_metadata = extract_urls_metadata(self.urls_metadata) created_date = self.created_date.isoformat() updated_date = self.updated_date.isoformat() return { 'did': self.did, 'baseid': self.baseid, 'rev': self.rev, 'size': self.size, 'file_name': self.file_name, 'version': self.version, 'uploader': self.uploader, 'urls': urls, 'urls_metadata': urls_metadata, 'acl': acl, 'hashes': hashes, 'metadata': metadata, 'form': self.form, 'created_date': created_date, "updated_date": updated_date, } class IndexRecordAlias(Base): """ Alias attached to index record """ __tablename__ = 'index_record_alias' did = Column(String, ForeignKey('index_record.did'), primary_key=True) name = Column(String, primary_key=True) __table_args__ = ( Index('index_record_alias_idx', 'did'), Index('index_record_alias_name', 'name'), ) class IndexRecordUrl(Base): """ Base index record url representation. """ __tablename__ = 'index_record_url' did = Column(String, primary_key=True) url = Column(String, primary_key=True) __table_args__ = ( Index('index_record_url_idx', 'did'), ) class IndexRecordACE(Base): """ index record access control entry representation. """ __tablename__ = 'index_record_ace' did = Column(String, ForeignKey('index_record.did'), primary_key=True) # access control entry ace = Column(String, primary_key=True) __table_args__ = ( Index('index_record_ace_idx', 'did'), ) class IndexRecordMetadata(Base): """ Metadata attached to index document """ __tablename__ = 'index_record_metadata' key = Column(String, primary_key=True) did = Column(String, primary_key=True) value = Column(String) __table_args__ = ( Index('index_record_metadata_idx', 'did'), ) class IndexRecordUrlMetadata(Base): """ Metadata attached to url """ __tablename__ = 'index_record_url_metadata' key = Column(String, primary_key=True) url = Column(String, primary_key=True) did = Column(String, index=True, primary_key=True) value = Column(String) __table_args__ = ( ForeignKeyConstraint(['did', 'url'], ['index_record_url.did', 'index_record_url.url']), Index('index_record_url_metadata_idx', 'did'), ) class IndexRecordUrlMetadataJsonb(Base): """ Metadata attached to url in jsonb format """ __tablename__ = 'index_record_url_metadata_jsonb' did = Column(String, primary_key=True) url = Column(String, primary_key=True) type = Column(String, index=True) state = Column(String, index=True) urls_metadata = Column(JSONB) __table_args__ = (ForeignKeyConstraint(['did'], ['index_record.did']),) class IndexRecordHash(Base): """ Base index record hash representation. """ __tablename__ = 'index_record_hash' did = Column(String, ForeignKey('index_record.did'), primary_key=True) hash_type = Column(String, primary_key=True) hash_value = Column(String) __table_args__ = ( Index('index_record_hash_idx', 'did'), Index('index_record_hash_type_value_idx', 'hash_value', 'hash_type'), ) def separate_urls_metadata(urls_metadata): """Separate type and state from urls_metadata record. Type and state are removed from the urls_metadata key value pair/jsonb object. To keep backwards compatibility these are still ingested through the urls_metadata field. We have to manually separate them and later combine them to maintain compatibility with the current indexclient. """ urls_metadata = copy.deepcopy(urls_metadata) # If these fields are given, then remove them from the json # blob so it doesn't get put in the urls_metadata table. u_type = urls_metadata.pop('type', None) u_state = urls_metadata.pop('state', None) return u_type, u_state, urls_metadata def create_urls_metadata(did, metadata_fields): """ Create url metadata record in database. Each row is: DID | URL | TYPE | STATE | METADATA """ rows = [] for url, urls_metadata in iteritems(metadata_fields): u_type, u_state, urls_metadata = separate_urls_metadata(urls_metadata) rows.append(IndexRecordUrlMetadataJsonb( did=did, url=url, type=u_type, state=u_state, urls_metadata=urls_metadata, )) return rows class SQLAlchemyIndexDriver(IndexDriverABC): """ SQLAlchemy implementation of index driver. """ def __init__( self, conn, logger=None, auto_migrate=True, index_config=None, **config): """ Initialize the SQLAlchemy database driver. """ super(SQLAlchemyIndexDriver, self).__init__(conn, **config) self.logger = logger or get_logger(__name__ + "." + self.__class__.__name__) self.config = index_config or {} Base.metadata.bind = self.engine self.Session = sessionmaker(bind=self.engine) is_empty_db = is_empty_database(driver=self) Base.metadata.create_all() if is_empty_db: init_schema_version( driver=self, model=IndexSchemaVersion, current_version=CURRENT_SCHEMA_VERSION) if auto_migrate: self.migrate_index_database() def migrate_index_database(self): """ migrate alias database to match CURRENT_SCHEMA_VERSION """ migrate_database( driver=self, migrate_functions=SCHEMA_MIGRATION_FUNCTIONS, current_schema_version=CURRENT_SCHEMA_VERSION, model=IndexSchemaVersion) @property @contextmanager def session(self): """ Provide a transactional scope around a series of operations. """ session = self.Session() try: yield session session.commit() except: session.rollback() raise finally: session.close() def ids(self, limit=100, start=None, size=None, urls=None, acl=None, hashes=None, file_name=None, version=None, uploader=None, release_number=None, metadata=None, ids=None, urls_metadata=None, negate_params=None): """ Returns list of records stored by the backend. """ with self.session as session: query = session.query(IndexRecord) # Enable joinedload on all relationships so that we won't have to # do a bunch of selects when we assemble our response. query = query.options(joinedload(IndexRecord.urls_metadata)) query = query.options(joinedload(IndexRecord.acl)) query = query.options(joinedload(IndexRecord.hashes)) query = query.options(joinedload(IndexRecord.aliases)) if start is not None: query = query.filter(IndexRecord.did > start) if size is not None: query = query.filter(IndexRecord.size == size) if file_name is not None: query = query.filter(IndexRecord.file_name == file_name) if version is not None: query = query.filter(IndexRecord.version == version) if uploader is not None: query = query.filter(IndexRecord.uploader == uploader) if urls: query = query.join(IndexRecord.urls_metadata) for u in urls: query = query.filter(IndexRecordUrlMetadataJsonb.url == u) if acl: query = query.join(IndexRecord.acl) for u in acl: query = query.filter(IndexRecordACE.ace == u) elif acl == []: query = query.filter(IndexRecord.acl == None) if hashes: for h, v in hashes.items(): sub = session.query(IndexRecordHash.did) sub = sub.filter(and_( IndexRecordHash.hash_type == h, IndexRecordHash.hash_value == v, )) query = query.filter(IndexRecord.did.in_(sub.subquery())) if release_number: query = query.filter(IndexRecord.release_number == release_number) if metadata: for k, v in metadata.items(): query = query.filter( IndexRecord.index_metadata[k].astext == v ) if urls_metadata: query = query.join(IndexRecord.urls_metadata) for url_key, url_dict in urls_metadata.items(): u_type, u_state, url_dict = separate_urls_metadata(url_dict) query = query.filter( IndexRecordUrlMetadataJsonb.url.contains(url_key)) for k, v in url_dict.items(): query = query.filter( IndexRecordUrlMetadataJsonb.urls_metadata[k].astext == v ) if u_type: query = query.filter( IndexRecordUrlMetadataJsonb.type == u_type) if u_state: query = query.filter( IndexRecordUrlMetadataJsonb.state == u_state) if negate_params: query = self._negate_filter(session, query, **negate_params) # joining url metadata will have duplicate results # url or acl doesn't have duplicate results for current filter # so we don't need to select distinct for these cases if urls_metadata or negate_params: query = query.distinct(IndexRecord.did) query = query.order_by(IndexRecord.did) if ids: query = query.filter(IndexRecord.did.in_(ids)) else: # only apply limit when ids is not provided query = query.limit(limit) return [i.to_document_dict() for i in query] @staticmethod def _negate_filter(session, query, urls=None, acl=None, file_name=None, version=None, metadata=None, urls_metadata=None): """ param_values passed in here will be negated for string (version, file_name), filter with value != <value> for list (urls, acl), filter with doc that don't HAS <value> for dict (metadata, urls_metadata). In each (key,value) pair: - if value is None or empty: then filter with key doesn't exist - if value is provided, then filter with value != <value> OR key doesn't exist Args: session: db session query: sqlalchemy query urls (list): doc.urls don't have any <url> in the urls list acl (list): doc.acl don't have any <acl> in the acl list file_name (str): doc.file_name != <file_name> version (str): doc.version != <version> metadata (dict): see above for dict urls_metadata (dict): see above for dict Returns: Database query """ if file_name is not None: query = query.filter(IndexRecord.file_name != file_name) if version is not None: query = query.filter(IndexRecord.version != version) if urls is not None and urls: query = query.join(IndexRecord.urls_metadata) for u in urls: query = query.filter( ~IndexRecord.urls_metadata.any(IndexRecordUrlMetadataJsonb.url ==
# Copyright 2019 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== import numpy as np import pytest import mindspore.common.dtype as mstype import mindspore.dataset as ds from mindspore import log as logger # Generate 1d int numpy array from 0 - 63 def generator_1d(): for i in range(64): yield (np.array([i]),) def test_case_0(): """ Test 1D Generator """ logger.info("Test 1D Generator : 0 - 63") # apply dataset operations data1 = ds.GeneratorDataset(generator_1d, ["data"]) i = 0 for item in data1.create_dict_iterator(): # each data is a dictionary golden = np.array([i]) assert np.array_equal(item["data"], golden) i = i + 1 # Generate md int numpy array from [[0, 1], [2, 3]] to [[63, 64], [65, 66]] def generator_md(): for i in range(64): yield (np.array([[i, i + 1], [i + 2, i + 3]]),) def test_case_1(): """ Test MD Generator """ logger.info("Test MD Generator : 0 - 63, with shape [2, 2]") # apply dataset operations data1 = ds.GeneratorDataset(generator_md, ["data"]) i = 0 for item in data1.create_dict_iterator(): # each data is a dictionary golden = np.array([[i, i + 1], [i + 2, i + 3]]) assert np.array_equal(item["data"], golden) i = i + 1 # Generate two columns, the first column is from Generator1D, the second column is from GeneratorMD def generator_mc(maxid=64): for i in range(maxid): yield (np.array([i]), np.array([[i, i + 1], [i + 2, i + 3]])) def test_case_2(): """ Test multi column generator """ logger.info("Test multi column generator") # apply dataset operations data1 = ds.GeneratorDataset(generator_mc, ["col0", "col1"]) i = 0 for item in data1.create_dict_iterator(): # each data is a dictionary golden = np.array([i]) assert np.array_equal(item["col0"], golden) golden = np.array([[i, i + 1], [i + 2, i + 3]]) assert np.array_equal(item["col1"], golden) i = i + 1 def test_case_3(): """ Test 1D Generator + repeat(4) """ logger.info("Test 1D Generator : 0 - 63 + Repeat(4)") # apply dataset operations data1 = ds.GeneratorDataset(generator_1d, ["data"]) data1 = data1.repeat(4) i = 0 for item in data1.create_dict_iterator(): # each data is a dictionary golden = np.array([i]) assert np.array_equal(item["data"], golden) i = i + 1 if i == 64: i = 0 def test_case_4(): """ Test fixed size 1D Generator + batch """ logger.info("Test 1D Generator : 0 - 63 + batch(4)") # apply dataset operations data1 = ds.GeneratorDataset(generator_1d, ["data"]) data1 = data1.batch(4) i = 0 for item in data1.create_dict_iterator(): # each data is a dictionary golden = np.array([[i], [i + 1], [i + 2], [i + 3]]) assert np.array_equal(item["data"], golden) i = i + 4 def generator_with_type(t): for i in range(64): yield (np.array([i], dtype=t),) def type_tester(t): logger.info("Test with Type {}".format(t.__name__)) # apply dataset operations data1 = ds.GeneratorDataset((lambda: generator_with_type(t)), ["data"]) data1 = data1.batch(4) i = 0 for item in data1.create_dict_iterator(): # each data is a dictionary golden = np.array([[i], [i + 1], [i + 2], [i + 3]], dtype=t) assert np.array_equal(item["data"], golden) i = i + 4 def test_case_5(): """ Test 1D Generator on different data type """ logger.info("Test 1D Generator on all data types") types = [np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64, np.float32, np.float64] for t in types: type_tester(t) def type_tester_with_type_check(t, c): logger.info("Test with Type {}".format(t.__name__)) # apply dataset operations data1 = ds.GeneratorDataset((lambda: generator_with_type(t)), ["data"], column_types=[c]) data1 = data1.batch(4) i = 0 for item in data1.create_dict_iterator(): # each data is a dictionary golden = np.array([[i], [i + 1], [i + 2], [i + 3]], dtype=t) assert np.array_equal(item["data"], golden) i = i + 4 def test_case_6(): """ Test 1D Generator on different data type with type check """ logger.info("Test 1D Generator on all data types with type check") np_types = [np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64, np.float32, np.float64] de_types = [mstype.int8, mstype.int16, mstype.int32, mstype.int64, mstype.uint8, mstype.uint16, mstype.uint32, mstype.uint64, mstype.float32, mstype.float64] for i in range(len(np_types)): type_tester_with_type_check(np_types[i], de_types[i]) def generator_with_type_2c(t): for i in range(64): yield (np.array([i], dtype=t), np.array([i], dtype=t)) def type_tester_with_type_check_2c(t, c): logger.info("Test with Type {}".format(t.__name__)) # apply dataset operations data1 = ds.GeneratorDataset((lambda: generator_with_type_2c(t)), ["data0", "data1"], column_types=c) data1 = data1.batch(4) i = 0 for item in data1.create_dict_iterator(): # each data is a dictionary golden = np.array([[i], [i + 1], [i + 2], [i + 3]], dtype=t) assert np.array_equal(item["data0"], golden) i = i + 4 def test_case_7(): """ Test 2 column Generator on different data type with type check """ logger.info("Test 2 column Generator on all data types with type check") np_types = [np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64, np.float32, np.float64] de_types = [mstype.int8, mstype.int16, mstype.int32, mstype.int64, mstype.uint8, mstype.uint16, mstype.uint32, mstype.uint64, mstype.float32, mstype.float64] for i in range(len(np_types)): type_tester_with_type_check_2c(np_types[i], [None, de_types[i]]) def test_case_8(): """ Test multi column generator with few mapops """ logger.info("Test multi column generator with mapops to check the order too") # apply dataset operations data1 = ds.GeneratorDataset(generator_mc(2048), ["col0", "col1"]) data1 = data1.map(input_columns="col0", output_columns="out0", operations=(lambda x: x * 3), num_parallel_workers=2) data1 = data1.map(input_columns="col1", output_columns=["out1", "out2"], operations=(lambda x: (x * 7, x)), num_parallel_workers=2, columns_order=["out0", "out1", "out2"]) data1 = data1.map(input_columns="out2", output_columns="out2", operations=(lambda x: x + 1), num_parallel_workers=2) i = 0 for item in data1.create_dict_iterator(): # each data is a dictionary golden = np.array([i * 3]) assert np.array_equal(item["out0"], golden) golden = np.array([[i * 7, (i + 1) * 7], [(i + 2) * 7, (i + 3) * 7]]) assert np.array_equal(item["out1"], golden) golden = np.array([[i + 1, i + 2], [i + 3, i + 4]]) assert np.array_equal(item["out2"], golden) i = i + 1 def test_case_9(): """ Test map column order when len(input_columns) == len(output_columns). """ logger.info("Test map column order when len(input_columns) == len(output_columns).") # apply dataset operations data1 = ds.GeneratorDataset(generator_mc(2048), ["image", "label"]) data2 = ds.GeneratorDataset(generator_mc(2048), ["label", "image"]) data1 = data1.map(input_columns="label", operations=(lambda x: x * 3), num_parallel_workers=4) data2 = data2.map(input_columns="label", operations=(lambda x: x * 3), num_parallel_workers=4) # Expected column order is not changed. # data1 = data[0] is "image" and data[1] is "label" # data2 = data[0] is "label" and data[1] is "image" i = 0 for data1, data2 in zip(data1, data2): # each data is a dictionary golden = np.array([i]) assert np.array_equal(data1[0], golden) golden = np.array([[i * 3, (i + 1) * 3], [(i + 2) * 3, (i + 3) * 3]]) assert np.array_equal(data1[1], golden) golden = np.array([i * 3]) assert np.array_equal(data2[0], golden) golden = np.array([[i, i + 1], [i + 2, i + 3]]) assert np.array_equal(data2[1], golden) i = i + 1 def test_case_10(): """ Test map column order when len(input_columns) != len(output_columns). """ logger.info("Test map column order when len(input_columns) != len(output_columns).") # apply dataset operations data1 = ds.GeneratorDataset(generator_mc(2048), ["col0", "col1"]) data1 = data1.map(input_columns="col1", output_columns=["out1", "out2"], operations=(lambda x: (x, x * 5)), columns_order=['col0', 'out1', 'out2'], num_parallel_workers=2) # Expected column order is |col0|out1|out2| i = 0 for item in data1.create_tuple_iterator(): golden = np.array([i]) assert np.array_equal(item[0], golden) golden = np.array([[i, i + 1], [i + 2, i + 3]]) assert np.array_equal(item[1], golden) golden = np.array([[i * 5, (i + 1) * 5], [(i + 2) * 5, (i + 3) * 5]]) assert np.array_equal(item[2], golden) i = i + 1 def test_case_11(): """ Test map column order when len(input_columns) != len(output_columns). """ logger.info("Test map column order when len(input_columns) != len(output_columns), " "and columns_order drops some columns.") # apply dataset operations data1 = ds.GeneratorDataset(generator_mc(2048), ["col0", "col1"]) data1 = data1.map(input_columns="col1", output_columns=["out1", "out2"], operations=(lambda x: (x, x * 5)), columns_order=['out1', 'out2'], num_parallel_workers=2) # Expected column order is |out1|out2| i = 0 for item in data1.create_tuple_iterator(): # len should be 2 because col0 is dropped (not included in columns_order) assert len(item) == 2 golden = np.array([[i, i + 1], [i + 2, i + 3]]) assert np.array_equal(item[0], golden) golden = np.array([[i * 5, (i + 1) * 5], [(i + 2) * 5, (i + 3)
# Change some settings here since the autoconfig must only be changed # through typing `:set` in the browser and for keybinding/aliases that # is not recommended. (Saving in the browser is done by typing `sf`). # Loading autoconfig.yml config.load_autoconfig() # Bindings c.bindings.default = { 'normal': { # General '.': 'repeat-command', '/': 'set-cmd-text /', ':': 'set-cmd-text :', ' ': 'set-cmd-text :', '?': 'set-cmd-text ?', # Select Tabs '1': 'tab-focus 1', '2': 'tab-focus 2', '3': 'tab-focus 3', '4': 'tab-focus 4', '5': 'tab-focus 5', '6': 'tab-focus 6', '7': 'tab-focus 7', '8': 'tab-focus 8', '9': 'tab-focus 9', '0': 'tab-focus -1', # Zoom '<Ctrl-Shift-+>': 'zoom-in', '<Ctrl-->': 'zoom-out', '<Ctrl-=>': 'zoom', # reset zoom # Hints 'f': 'hint', # opens hint in same tab 'F': 'hint all tab', # opens in background tab 'I': 'hint inputs --first', # type in the first input ';o': 'hint all', ';O': 'hint all tab-fg', ';b': 'hint all tab-bg', ';w': 'hint all window', ';h': 'hint all hover', ';r': 'hint all right-click', ';d': 'hint links download', ';<Ctrl-d>': 'hint all delete', ';y': 'hint links yank', ';Y': 'hint links yank-primary', ';i': 'hint inputs', ';I': 'hint images', ';<Ctrl-i>': 'hint images tab', # Enter Modes 'i': 'mode-enter insert', 'v': 'mode-enter caret', 'V': 'mode-enter caret ;; toggle-selection --line', 'z': 'mode-enter passthrough', # Open 'o': 'set-cmd-text -s :open', 'O': 'set-cmd-text -s :open -t', 'b': 'set-cmd-text -s :open -b', 'w': 'set-cmd-text -s :open -w', 'W': 'set-cmd-text -s :open -w', 'ao': 'set-cmd-text :open -r {url:pretty}', 'aO': 'set-cmd-text :open -r -t {url:pretty}', 'ab': 'set-cmd-text :open -r -b {url:pretty}', 'aw': 'set-cmd-text :open -r -w {url:pretty}', 'aW': 'set-cmd-text :open -r -p {url:pretty}', 'go': 'open', 'gO': 'open -t', 'T': 'open -t', 'gb': 'open -b', 'gw': 'open -w', 'gW': 'open -p', # private 'po': 'open -- {clipboard}', 'pO': 'open -t -- {clipboard}', 'pb': 'open -b -- {clipboard}', 'pw': 'open -w -- {clipboard}', 'pp': 'open -p -- {clipboard}', 'Po': 'open -- {primary}', 'PO': 'open -t -- {primary}', 'Pb': 'open -b -- {primary}', 'Pw': 'open -w -- {primary}', 'Pp': 'open -p -- {primary}', # Close 'c': 'tab-close', 'Cp': 'tab-close -p', 'Cn': 'tab-close -n', 'Co': 'tab-close -o', 'Cf': 'tab-close -f', 'C<Ctrl-w>': 'close', 'Cet': 'tab-only', 'Cef': 'tab-only --force', 'Cep': 'tab-only --prev', 'Cen': 'tab-only --next', 'C<Ctrl-Shift-W>': 'window-only', # Undo 'u': 'undo', # Reload and Go back/forwards 'r': 'reload', 'R': 'reload -f', 'J': 'back', 'K': 'forward', '<Ctrl-h>t': 'back -t', '<Ctrl-h>b': 'back -b', '<Ctrl-h>w': 'back -w', '<Ctrl-h>W': 'back -p', '<Ctrl-l>t': 'forward -t', '<Ctrl-l>b': 'forward -b', '<Ctrl-l>w': 'forward -w', '<Ctrl-l>W': 'forward -p', '<back>': 'back', '<forward>': 'forward', # Cookies enable etc 'tuc': 'config-cycle -p -u {url} content.cookies.accept all no-3rdparty never ;; reload', 'tui': 'config-cycle -p -u {url} content.images ;; reload', 'tup': 'config-cycle -p -u {url} content.plugins ;; reload', 'tus': 'config-cycle -p -u {url} content.javascript.enabled ;; reload', # Yank 'yd': 'yank domain', 'yp': 'yank pretty-url', 'yt': 'yank title', 'yy': 'yank', 'Yd': 'yank domain -s', 'Yp': 'yank pretty-url -s', 'Yt': 'yank title -s', 'Yy': 'yank -s', # Other tab shortcuts 'H': 'tab-prev', 'L': 'tab-next', 'S': 'set-cmd-text -s :tab-focus', 'tf': 'tab-focus', 'tm': 'tab-move', 'tcb': 'tab-clone -b', 'tcw': 'tab-clone -w', 'tp': 'tab-pin', 'tg': 'tab-give', 'tj': 'tab-move +', 'tk': 'tab-move -', # Normal shortcuts # new '<Ctrl-m>': 'tab-mute', '<Ctrl-Alt-p>': 'print', '<Ctrl-Tab>': 'tab-focus last', '<Ctrl-Shift-F>': 'fullscreen', # original '<Ctrl-t>': 'open -t', '<Ctrl-w>': 'tab-close', '<Ctrl-n>': 'open -w', '<Ctrl-Shift-n>': 'open -p', '<F11>': 'fullscreen', # Searching and Selection 'n': 'search-next', 'N': 'search-prev', '<Ctrl-Return>': 'selection-follow -t', '<Return>': 'follow-selected', # Scrolling 'h': 'scroll left', 'j': 'scroll down', 'k': 'scroll up', 'l': 'scroll right', '<Ctrl-D>': 'scroll-page 0 0.5', '<Ctrl-U>': 'scroll-page 0 -0.5', '<Ctrl-F>': 'scroll-page 0 1', '<Ctrl-B>': 'scroll-page 0 -1', 'gg': 'scroll-to-perc 0', 'G': 'scroll-to-perc', # Other vim-related shortcuts 'q': 'macro-record', '@': 'macro-run', '`': 'set-mark', "'": 'jump-mark', '<Escape>': 'clear-keychain ;; search ;; fullscreen --leave', 'ZQ': 'quit', 'ZZ': 'quit --save', # Downloads 'dd': 'download', 'dc': 'download-clear', 'ds': 'download-cancel', 'dD': 'download-delete', # Delete the download from the disk 'do': 'download-open', 'dv': 'download-open alacritty -e nvim {}', 'dz': 'download-open zathura {}', 'dr': 'download-retry', # History, bookmarks, etc. 'sh': 'history -t', 'sB': 'open -t qute://bookmarks', 'Ba': 'bookmark-add', 'Bd': 'bookmark-del', 'Bo': 'set-cmd-text -s :bookmark-load', 'BO': 'set-cmd-text -s :bookmark-load -t', 'Bb': 'set-cmd-text -s :bookmark-load -b', 'Bw': 'set-cmd-text -s :bookmark-load -w', 'BW': 'set-cmd-text -s :bookmark-load -p', 'ea': 'quickmark-add', 'ed': 'quickmark-del', 'es': 'quickmark-save', 'eo': 'set-cmd-text -s :quickmark-load', 'eO': 'set-cmd-text -s :quickmark-load -t', 'eb': 'set-cmd-text -s :quickmark-load -b', 'ew': 'set-cmd-text -s :quickmark-load -w', 'eW': 'set-cmd-text -s :quickmark-load -p', # Navigate (next page) '<Ctrl-X>': 'navigate decrement', '[[': 'navigate prev', ']]': 'navigate next', '{{': 'navigate prev -t', '}}': 'navigate next -t', # Devtools (Inspector) ',i': 'devtools', ',h': 'devtools left', ',j': 'devtools bottom', ',k': 'devtools top', ',l': 'devtools right', ',w': 'devtools window', # Other 'sf': 'save', 'ss': 'view-source', 'sv': 'set', '<Ctrl-V>': 'hint inputs --first ;; insert-text {clipboard}', '<Ctrl-Shift-E>': 'config-edit', }, 'hint': { '<Ctrl-B>': 'hint all tab-bg', '<Ctrl-F>': 'hint links', '<Ctrl-R>': 'hint --rapid links tab-bg', '<Return>': 'hint-follow', '<Escape>': 'mode-leave', }, 'caret': { # movements '$': 'move-to-end-of-line', '0': 'move-to-start-of-line', 'gg': 'move-to-start-of-document', 'G': 'move-to-end-of-document', 'H': 'scroll left', 'J': 'scroll down', 'K': 'scroll up', 'L': 'scroll right', 'h': 'move-to-prev-char', 'j': 'move-to-next-line', 'k': 'move-to-prev-line', 'l': 'move-to-next-char', '{': 'move-to-end-of-prev-block', '}': 'move-to-end-of-next-block', '[': 'move-to-start-of-prev-block', ']': 'move-to-start-of-next-block', 'b': 'move-to-prev-word', 'e': 'move-to-end-of-word', 'w': 'move-to-next-word', # other mode 'V': 'selection-toggle --line', 'c': 'mode-enter normal', '<Escape>': 'mode-leave', # selection 'o': 'reverse-selection', 'v': 'toggle-selection', '<Shift-Space>': 'drop-selection', '<Space>': 'toggle-selection', # yank '<Return>': 'yank selection', '<Shift-Return>': 'yank selection --sel', 'y': 'yank selection', 'Y': 'yank selection -s', }, 'command': { '<Ctrl-B>': 'rl-backward-word', '<Ctrl-W>': 'rl-forward-word', '<Ctrl-E>': 'rl-end-of-word', '<Ctrl-Shift-B>': 'rl-unix-word-rubout', '<Ctrl-Shift-W>': 'rl-kill-word', '<Ctrl-Shift-K>': 'rl-kill-line', '<Ctrl-U>': 'rl-unix-line-discard', '<Ctrl-Backspace>': 'rl-backward-kill-word', '<Ctrl-0>': 'rl-beginning-of-line', '<Ctrl-$>': 'rl-end-of-line', '<Ctrl-H>': 'rl-backward-char', '<Ctrl-L>': 'rl-forward-char', '<Ctrl-?>': 'rl-delete-char', '<Backspace>': 'rl-backward-delete-char', '<Ctrl-Y>': 'rl-yank', '<Ctrl-C>': 'completion-item-yank', '<Ctrl-Shift-C>': 'completion-item-yank --sel', '<Tab>': 'completion-item-focus next', '<Shift-Tab>': 'completion-item-focus prev', '<Ctrl-J>': 'completion-item-focus next', '<Ctrl-K>': 'completion-item-focus prev', '<Down>': 'completion-item-focus --history next', '<Up>': 'completion-item-focus --history prev', '<Ctrl-N>': 'command-history-next', '<Ctrl-P>': 'command-history-prev', '<Return>': 'command-accept', '<Shift-Return>': 'command-accept --rapid', '<Escape>': 'mode-leave', }, 'insert': { '<Ctrl-W>': 'tab-close', '<Ctrl-P>': 'insert-text {primary}', '<Ctrl-M>': 'tab-mute', '<Ctrl-Tab>': 'tab-focus last', '<Ctrl-T>': 'open -t', '<Ctrl-N>': 'open -w', '<Ctrl-Shift-N>': 'open -p', '<Ctrl-Shift-F>': 'fullscreen', '<F11>': 'fullscreen', '<Escape>': 'mode-leave', }, 'passthrough': { '<Escape>': 'mode-leave', }, 'prompt': { '<Ctrl-B>': 'rl-backward-word', '<Ctrl-W>': 'rl-forward-word', '<Ctrl-E>': 'rl-end-of-word', '<Ctrl-Shift-B>': 'rl-unix-word-rubout', '<Ctrl-Shift-W>': 'rl-kill-word', '<Ctrl-Shift-K>': 'rl-kill-line', '<Ctrl-U>': 'rl-unix-line-discard', '<Ctrl-Backspace>': 'rl-backward-kill-word', '<Ctrl-0>': 'rl-beginning-of-line', '<Ctrl-4>': 'rl-end-of-line', '<Ctrl-H>': 'rl-backward-char', '<Ctrl-L>': 'rl-forward-char', '<Ctrl-?>': 'rl-delete-char', '<Backspace>': 'rl-backward-delete-char', # '<Ctrl-Y>': 'rl-yank', '<Ctrl-Shift-Y>': 'prompt-yank --sel', '<Ctrl-Y>': 'prompt-yank', '<Ctrl-P>': 'prompt-open-download --pdfjs', '<Ctrl-X>': 'prompt-open-download', '<Return>': 'prompt-accept', '<Tab>': 'prompt-item-focus next', '<Shift-Tab>': 'prompt-item-focus prev', '<Ctrl-K>': 'prompt-item-focus next', '<Ctrl-J>': 'prompt-item-focus prev', '<Down>': 'prompt-item-focus next', '<Up>': 'prompt-item-focus prev', '<Escape>': 'mode-leave', }, 'yesno': { '<Ctrl-Y>': 'prompt-yank', '<Ctrl-Shift-Y>': 'prompt-yank --sel', '<Return>': 'prompt-accept', 'N': 'prompt-accept --save no', 'Y': 'prompt-accept --save yes', 'n': 'prompt-accept no', 'y': 'prompt-accept yes', '<Escape>': 'mode-leave', } } c.aliases = { 'w': 'session-save', 'wq': 'quit --save', # 'light': 'set content.user_stylesheets user_light.css', # 'dark': 'set content.user_stylesheets user_dark.css', } ######################### # Completion menu ######################### c.completion.cmd_history_max_items = -1 # unlimited c.completion.delay = 0 # Delay after pressing key # The height of the completion, in px or as percentage of the window. c.completion.height = '40%' c.completion.quick = True c.completion.show = 'always' c.completion.timestamp_format = '%Y-%m-%d %H:%M' ######################### # Content, Downloads, Editor and Filesection ######################### c.confirm_quit = ['downloads'] c.content.fullscreen.window = True c.content.javascript.can_open_tabs_automatically = True c.content.proxy = 'none' # c.content.user_stylesheets = ['user_dark.css'] # This is a list, so you can add more c.downloads.location.directory = '/home/joris/downloads/' c.downloads.location.prompt = True c.downloads.location.remember = True c.downloads.location.suggestion = 'path' c.downloads.position = 'bottom' c.downloads.remove_finished = -1 # milliseconds c.editor.command = ['alacritty', '-e', 'nvim', '{file}'] ######################### # Fonts, Hints, Input and Keyhints ######################### c.fonts.default_family = 'Dejavu Sans' c.fonts.default_size = '10pt' c.fonts.statusbar = '9pt Dejavu Sans' c.hints.chars = "asdfghjkl" c.input.insert_mode.auto_load = True c.input.insert_mode.leave_on_load = True c.keyhint.delay = 0 # default 500 milliseconds ######################### # Messages, Opening tabs, Prompts, Scrollbar and Searching ######################### c.messages.timeout = 6000 # milliseconds c.new_instance_open_target = 'tab-silent' c.new_instance_open_target_window = 'last-focused' c.prompt.filebrowser = True c.prompt.radius = 8 c.scrolling.bar = 'always' c.scrolling.smooth = False c.search.ignore_case = 'smart' c.search.wrap = True ######################### # Sessions, spellcheck and statusbar ######################### c.session.lazy_restore = True c.spellcheck.languages = ['en-US', 'en-GB', 'de-DE', 'nl-NL'] c.statusbar.padding = { 'bottom': 1, 'left': 1, 'right': 3, 'top': 1, } c.statusbar.position = 'bottom' c.statusbar.show = 'always' c.statusbar.widgets = ['url', 'keypress', 'progress', 'tabs', 'history', 'scroll'] ######################### # Tabs ######################### c.tabs.background = True c.tabs.close_mouse_button = 'right' # close tabs with right button c.tabs.favicons.scale = 0.9 c.tabs.favicons.show = 'always' c.tabs.indicator.padding = { 'bottom': 1, 'left': 2, 'right': 4, 'top': 2, } c.tabs.indicator.width = 4 c.tabs.last_close = 'default-page' c.tabs.max_width = -1 c.tabs.min_width = -1 c.tabs.mode_on_change = 'normal' c.tabs.mousewheel_switching = True c.tabs.new_position.related = 'next' c.tabs.new_position.stacking = True c.tabs.new_position.unrelated = 'last' c.tabs.padding = {
# # Copyright 2019 BrainPad Inc. All Rights Reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # import ast import csv import json import os import pandas from cliboa.core.validator import EssentialParameters from cliboa.scenario.gcp import BaseBigQuery, BaseFirestore, BaseGcs from cliboa.scenario.load.file import FileWrite from cliboa.util.exception import FileNotFound, InvalidFileCount, InvalidFormat from cliboa.util.gcp import Firestore, Gcs, ServiceAccount class BigQueryWrite(BaseBigQuery, FileWrite): """ Read csv and Insert data into BigQuery table """ # default bulk line count to change to dataframe object _BULK_LINE_CNT = 10000 # BigQuery insert mode _REPLACE = "replace" _APPEND = "append" def __init__(self): super().__init__() self._table_schema = None self._replace = True self._columns = [] self._has_header = True def table_schema(self, table_schema): self._table_schema = table_schema def replace(self, replace): self._replace = replace def has_header(self, has_header): self._has_header = has_header def execute(self, *args): BaseBigQuery.execute(self) param_valid = EssentialParameters(self.__class__.__name__, [self._table_schema]) param_valid() files = super().get_target_files(self._src_dir, self._src_pattern) if len(files) == 0: raise FileNotFound("The specified csv file not found.") self._logger.info("insert target files %s" % files) is_inserted = False # initial if_exists if_exists = self._REPLACE if self._replace is True else self._APPEND self._columns = [name_and_type["name"] for name_and_type in self._table_schema] for file in files: insert_rows = [] with open(file, "r", encoding=self._encoding) as f: reader = ( csv.DictReader(f, delimiter=",") if self._has_header is True else csv.reader(f, delimiter=",") ) if self._has_header is True: for r in reader: # extract only the specified columns contents = {} for c in self._columns: if not r.get(c): continue contents[c] = r.get(c) insert_rows.append(contents) # bulk insert if len(insert_rows) == self._BULK_LINE_CNT: self._exec_insert(insert_rows, is_inserted, if_exists) insert_rows.clear() is_inserted = True if len(insert_rows) > 0: self._exec_insert(insert_rows, is_inserted, if_exists) is_inserted = True else: # csv headers do not exist for row in reader: contents = {} for i, c in enumerate(self._columns): contents[c] = row[i] insert_rows.append(contents) # bulk insert if len(insert_rows) == self._BULK_LINE_CNT: self._exec_insert(insert_rows, is_inserted, if_exists) insert_rows.clear() is_inserted = True if len(insert_rows) > 0: self._exec_insert(insert_rows, is_inserted, if_exists) is_inserted = True def _exec_insert(self, insert_rows, is_inserted, if_exists): """ Execute insert into a BigQuery table Args: insert_rows: rows to insert is_inserted: if the data is already inserted or not if_exists: replace or append """ df = pandas.DataFrame(self._format_insert_data(insert_rows)) if is_inserted is True: # if_exists after the first insert execution if_exists = self._APPEND dest_tbl = self._dataset + "." + self._tblname self._logger.info("Start insert %s rows to %s" % (len(insert_rows), dest_tbl)) df.to_gbq( dest_tbl, project_id=self._project_id, if_exists=if_exists, table_schema=self._table_schema, location=self._location, credentials=ServiceAccount.auth(self._credentials), ) def _format_insert_data(self, insert_rows): """ Format insert data to pass DataFrame as the below. insert_data = { "column1": [1, 2], "column2": ["spam", "spam"], ... } Args insert_rows: dictionary list of input cache """ insert_data = {} for c in self._columns: v_list = [d.get(c) for d in insert_rows] if not v_list: raise InvalidFormat( "Specified column %s does not exist in an input file." % c ) insert_data[c] = v_list return insert_data class BigQueryCreate(BaseBigQuery): """ @deprecated Insert data into BigQuery table """ # default bulk line count to change to dataframe object BULK_LINE_CNT = 10000 # BigQuery insert mode REPLACE = "replace" APPEND = "append" def __init__(self): super().__init__() self._table_schema = None self._replace = True def table_schema(self, table_schema): self._table_schema = table_schema def replace(self, replace): self._replace = replace def execute(self, *args): super().execute() param_valid = EssentialParameters(self.__class__.__name__, [self._table_schema]) param_valid() cache_list = [] inserts = False # initial if_exists if_exists = self.REPLACE if self._replace is True else self.APPEND with open(self._s.cache_file, "r", encoding="utf-8") as f: for i, l_str in enumerate(f): l_dict = ast.literal_eval(l_str) cache_list.append(l_dict) if len(cache_list) == self.BULK_LINE_CNT: df = pandas.DataFrame(self.__create_insert_data(cache_list)) if inserts is True: # if_exists after the first insert execution if_exists = self.APPEND dest_tbl = self._dataset + "." + self._tblname self._logger.info( "Start insert %s rows to %s" % (len(cache_list), dest_tbl) ) df.to_gbq( dest_tbl, project_id=self._project_id, if_exists=if_exists, table_schema=self._table_schema, location=self._location, credentials=ServiceAccount.auth(self._credentials), ) cache_list.clear() inserts = True if len(cache_list) > 0: df = pandas.DataFrame(self.__create_insert_data(cache_list)) if inserts is True: # if_exists after the first insert execution if_exists = self.APPEND dest_tbl = self._dataset + "." + self._tblname self._logger.info( "Start insert %s rows to %s" % (len(cache_list), dest_tbl) ) df.to_gbq( dest_tbl, project_id=self._project_id, if_exists=if_exists, table_schema=self._table_schema, location=self._location, credentials=ServiceAccount.auth(self._credentials), ) self._s.remove() def __create_insert_data(self, cache_list): """ Create insert data like the below. insert_data = { "column1": [1, 2], "column2": ["spam", "spam"], ... } Args cache_list: dictionary list of input cache """ insert_data = {} columns = [name_and_type["name"] for name_and_type in self._table_schema] for c in columns: v_list = [d.get(c) for d in cache_list] if not v_list: raise InvalidFormat( "Specified column %s does not exist in an input file." % c ) insert_data[c] = v_list return insert_data class GcsFileUpload(BaseGcs): """ @deprecated Upload local files to GCS """ def __init__(self): super().__init__() self._src_dir = None self._src_pattern = None self._dest_dir = "" def src_dir(self, src_dir): self._src_dir = src_dir def src_pattern(self, src_pattern): self._src_pattern = src_pattern def dest_dir(self, dest_dir): self._dest_dir = dest_dir def execute(self, *args): super().execute() valid = EssentialParameters( self.__class__.__name__, [self._src_dir, self._src_pattern] ) valid() gcs_client = Gcs.get_gcs_client(self._credentials) bucket = gcs_client.bucket(self._bucket) files = super().get_target_files(self._src_dir, self._src_pattern) self._logger.info("Upload files %s" % files) for file in files: self._logger.info("Start upload %s" % file) blob = bucket.blob(os.path.join(self._dest_dir, os.path.basename(file))) blob.upload_from_filename(file) self._logger.info("Finish upload %s" % file) class GcsUpload(BaseGcs): """ Upload local files to GCS """ def __init__(self): super().__init__() self._src_dir = None self._src_pattern = None self._dest_dir = "" def src_dir(self, src_dir): self._src_dir = src_dir def src_pattern(self, src_pattern): self._src_pattern = src_pattern def dest_dir(self, dest_dir): self._dest_dir = dest_dir def execute(self, *args): super().execute() valid = EssentialParameters( self.__class__.__name__, [self._src_dir, self._src_pattern] ) valid() gcs_client = Gcs.get_gcs_client(self._credentials) bucket = gcs_client.bucket(self._bucket) files = super().get_target_files(self._src_dir, self._src_pattern) self._logger.info("Upload files %s" % files) for file in files: self._logger.info("Start upload %s" % file) blob = bucket.blob(os.path.join(self._dest_dir, os.path.basename(file))) blob.upload_from_filename(file) self._logger.info("Finish upload %s" % file) class CsvReadBigQueryCreate(BaseBigQuery, FileWrite): """ Read csv and Insert data into BigQuery table """ # default bulk line count to change to dataframe object BULK_LINE_CNT = 10000 # BigQuery insert mode REPLACE = "replace" APPEND = "append" def __init__(self): super().__init__() self._table_schema = None self._replace = True self.__columns = [] def table_schema(self, table_schema): self._table_schema = table_schema def replace(self, replace): self._replace = replace def execute(self, *args): BaseBigQuery.execute(self) param_valid = EssentialParameters(self.__class__.__name__, [self._table_schema]) param_valid() files = super().get_target_files(self._src_dir, self._src_pattern) if len(files) > 1: raise InvalidFileCount("Input file must be only one.") if len(files) == 0: raise FileNotFound("The specified csv file not found.") insert_rows = [] is_inserted = False # initial if_exists if_exists = self.REPLACE if self._replace is True else self.APPEND self.__columns = [name_and_type["name"] for name_and_type in self._table_schema] with open(files[0], "r", encoding=self._encoding) as f: reader = csv.DictReader(f, delimiter=",") for r in reader: # extract only the specified columns row_dict = {} for c in self.__columns: if not r.get(c): continue row_dict[c] = r.get(c) insert_rows.append(row_dict) if len(insert_rows) == self.BULK_LINE_CNT: self.__exec_insert(insert_rows, is_inserted, if_exists) insert_rows.clear() is_inserted = True if len(insert_rows) > 0: self.__exec_insert(insert_rows, is_inserted, if_exists) def __exec_insert(self, insert_rows, is_inserted, if_exists): """ Execute insert into a BigQuery table Args: insert_rows: rows to insert is_inserted: if the data is already inserted or not if_exists: replace or append """ df = pandas.DataFrame(self.__format_insert_data(insert_rows)) if is_inserted is True: # if_exists after the first insert execution if_exists = self.APPEND dest_tbl = self._dataset + "." + self._tblname self._logger.info("Start insert %s rows to %s" % (len(insert_rows), dest_tbl)) df.to_gbq( dest_tbl, project_id=self._project_id, if_exists=if_exists, table_schema=self._table_schema, location=self._location, credentials=ServiceAccount.auth(self._credentials), ) def __format_insert_data(self, insert_rows): """ Format insert data to pass DataFrame as the below. insert_data = { "column1": [1, 2], "column2": ["spam", "spam"], ... } Args insert_rows: dictionary list of input cache """ insert_data = {} for c in self.__columns: v_list = [d.get(c) for d in insert_rows] if not v_list: raise InvalidFormat( "Specified column %s does not exist in an input file." % c ) insert_data[c] = v_list return insert_data class FirestoreDocumentCreate(BaseFirestore): """ Create document on FIrestore """ def __init__(self): super().__init__() self._src_dir = None self._src_pattern = None def src_dir(self, src_dir): self._src_dir = src_dir def src_pattern(self,
for the crosshair. :type color: A string (either a predefined color name in colors.py or "#RRGGBB")) or a 4 columns unsigned byte array (Default: black). :param int linewidth: The width of the lines of the crosshair (Default: 1). :param str linestyle: Type of line:: - ' ' no line - '-' solid line (the default) - '--' dashed line - '-.' dash-dot line - ':' dotted line """ if flag: self._cursorConfiguration = color, linewidth, linestyle else: self._cursorConfiguration = None self._backend.setGraphCursor(flag=flag, color=color, linewidth=linewidth, linestyle=linestyle) self._setDirtyPlot() self.notify('setGraphCursor', state=self._cursorConfiguration is not None) def pan(self, direction, factor=0.1): """Pan the graph in the given direction by the given factor. Warning: Pan of right Y axis not implemented! :param str direction: One of 'up', 'down', 'left', 'right'. :param float factor: Proportion of the range used to pan the graph. Must be strictly positive. """ assert direction in ('up', 'down', 'left', 'right') assert factor > 0. if direction in ('left', 'right'): xFactor = factor if direction == 'right' else - factor xMin, xMax = self._xAxis.getLimits() xMin, xMax = _utils.applyPan(xMin, xMax, xFactor, self._xAxis.getScale() == self._xAxis.LOGARITHMIC) self._xAxis.setLimits(xMin, xMax) else: # direction in ('up', 'down') sign = -1. if self._yAxis.isInverted() else 1. yFactor = sign * (factor if direction == 'up' else -factor) yMin, yMax = self._yAxis.getLimits() yIsLog = self._yAxis.getScale() == self._yAxis.LOGARITHMIC yMin, yMax = _utils.applyPan(yMin, yMax, yFactor, yIsLog) self._yAxis.setLimits(yMin, yMax) y2Min, y2Max = self._yRightAxis.getLimits() y2Min, y2Max = _utils.applyPan(y2Min, y2Max, yFactor, yIsLog) self._yRightAxis.setLimits(y2Min, y2Max) # Active Curve/Image def isActiveCurveHandling(self): """Returns True if active curve selection is enabled. :rtype: bool """ return self.getActiveCurveSelectionMode() != 'none' def setActiveCurveHandling(self, flag=True): """Enable/Disable active curve selection. :param bool flag: True to enable 'atmostone' active curve selection, False to disable active curve selection. """ self.setActiveCurveSelectionMode('atmostone' if flag else 'none') def getActiveCurveStyle(self): """Returns the current style applied to active curve :rtype: CurveStyle """ return self._activeCurveStyle def setActiveCurveStyle(self, color=None, linewidth=None, linestyle=None, symbol=None, symbolsize=None): """Set the style of active curve :param color: Color :param Union[str,None] linestyle: Style of the line :param Union[float,None] linewidth: Width of the line :param Union[str,None] symbol: Symbol of the markers :param Union[float,None] symbolsize: Size of the symbols """ self._activeCurveStyle = CurveStyle(color=color, linewidth=linewidth, linestyle=linestyle, symbol=symbol, symbolsize=symbolsize) curve = self.getActiveCurve() if curve is not None: curve.setHighlightedStyle(self.getActiveCurveStyle()) @deprecated(replacement="getActiveCurveStyle", since_version="0.9") def getActiveCurveColor(self): """Get the color used to display the currently active curve. See :meth:`setActiveCurveColor`. """ return self._activeCurveStyle.getColor() @deprecated(replacement="setActiveCurveStyle", since_version="0.9") def setActiveCurveColor(self, color="#000000"): """Set the color to use to display the currently active curve. :param str color: Color of the active curve, e.g., 'blue', 'b', '#FF0000' (Default: 'black') """ if color is None: color = "black" if color in self.colorDict: color = self.colorDict[color] self.setActiveCurveStyle(color=color) def getActiveCurve(self, just_legend=False): """Return the currently active curve. It returns None in case of not having an active curve. :param bool just_legend: True to get the legend of the curve, False (the default) to get the curve data and info. :return: Active curve's legend or corresponding :class:`.items.Curve` :rtype: str or :class:`.items.Curve` or None """ if not self.isActiveCurveHandling(): return None return self._getActiveItem(kind='curve', just_legend=just_legend) def setActiveCurve(self, legend): """Make the curve associated to legend the active curve. :param legend: The legend associated to the curve or None to have no active curve. :type legend: str or None """ if not self.isActiveCurveHandling(): return if legend is None and self.getActiveCurveSelectionMode() == "legacy": _logger.info( 'setActiveCurve(None) ignored due to active curve selection mode') return return self._setActiveItem(kind='curve', legend=legend) def setActiveCurveSelectionMode(self, mode): """Sets the current selection mode. :param str mode: The active curve selection mode to use. It can be: 'legacy', 'atmostone' or 'none'. """ assert mode in ('legacy', 'atmostone', 'none') if mode != self._activeCurveSelectionMode: self._activeCurveSelectionMode = mode if mode == 'none': # reset active curve self._setActiveItem(kind='curve', legend=None) elif mode == 'legacy' and self.getActiveCurve() is None: # Select an active curve curves = self.getAllCurves(just_legend=False, withhidden=False) if len(curves) == 1: if curves[0].isVisible(): self.setActiveCurve(curves[0].getLegend()) def getActiveCurveSelectionMode(self): """Returns the current selection mode. It can be "atmostone", "legacy" or "none". :rtype: str """ return self._activeCurveSelectionMode def getActiveImage(self, just_legend=False): """Returns the currently active image. It returns None in case of not having an active image. :param bool just_legend: True to get the legend of the image, False (the default) to get the image data and info. :return: Active image's legend or corresponding image object :rtype: str, :class:`.items.ImageData`, :class:`.items.ImageRgba` or None """ return self._getActiveItem(kind='image', just_legend=just_legend) def setActiveImage(self, legend): """Make the image associated to legend the active image. :param str legend: The legend associated to the image or None to have no active image. """ return self._setActiveItem(kind='image', legend=legend) def _getActiveItem(self, kind, just_legend=False): """Return the currently active item of that kind if any :param str kind: Type of item: 'curve', 'scatter' or 'image' :param bool just_legend: True to get the legend, False (default) to get the item :return: legend or item or None if no active item """ assert kind in self._ACTIVE_ITEM_KINDS if self._activeLegend[kind] is None: return None if (self._activeLegend[kind], kind) not in self._content: self._activeLegend[kind] = None return None if just_legend: return self._activeLegend[kind] else: return self._getItem(kind, self._activeLegend[kind]) def _setActiveItem(self, kind, legend): """Make the curve associated to legend the active curve. :param str kind: Type of item: 'curve' or 'image' :param legend: The legend associated to the curve or None to have no active curve. :type legend: str or None """ assert kind in self._ACTIVE_ITEM_KINDS xLabel = None yLabel = None yRightLabel = None oldActiveItem = self._getActiveItem(kind=kind) if oldActiveItem is not None: # Stop listening previous active image oldActiveItem.sigItemChanged.disconnect(self._activeItemChanged) # Curve specific: Reset highlight of previous active curve if kind == 'curve' and oldActiveItem is not None: oldActiveItem.setHighlighted(False) if legend is None: self._activeLegend[kind] = None else: legend = str(legend) item = self._getItem(kind, legend) if item is None: _logger.warning("This %s does not exist: %s", kind, legend) self._activeLegend[kind] = None else: self._activeLegend[kind] = legend # Curve specific: handle highlight if kind == 'curve': item.setHighlightedStyle(self.getActiveCurveStyle()) item.setHighlighted(True) if isinstance(item, items.LabelsMixIn): if item.getXLabel() is not None: xLabel = item.getXLabel() if item.getYLabel() is not None: if (isinstance(item, items.YAxisMixIn) and item.getYAxis() == 'right'): yRightLabel = item.getYLabel() else: yLabel = item.getYLabel() # Start listening new active item item.sigItemChanged.connect(self._activeItemChanged) # Store current labels and update plot self._xAxis._setCurrentLabel(xLabel) self._yAxis._setCurrentLabel(yLabel) self._yRightAxis._setCurrentLabel(yRightLabel) self._setDirtyPlot() activeLegend = self._activeLegend[kind] if oldActiveItem is not None or activeLegend is not None: if oldActiveItem is None: oldActiveLegend = None else: oldActiveLegend = oldActiveItem.getLegend() self.notify( 'active' + kind[0].upper() + kind[1:] + 'Changed', updated=oldActiveLegend != activeLegend, previous=oldActiveLegend, legend=activeLegend) return activeLegend def _activeItemChanged(self, type_): """Listen for active item changed signal and broadcast signal :param item.ItemChangedType type_: The type of item change """ if not self.__muteActiveItemChanged: item = self.sender() if item is not None: legend, kind = self._itemKey(item) self.notify( 'active' + kind[0].upper() + kind[1:] + 'Changed', updated=False, previous=legend, legend=legend) # Getters def getItems(self): """Returns the list of items in the plot :rtype: List[silx.gui.plot.items.Item] """ return tuple(self._content.values()) def getAllCurves(self, just_legend=False, withhidden=False): """Returns all curves legend or info and data. It returns an empty list in case of not having any curve. If just_legend is False, it returns a list of :class:`items.Curve` objects describing the curves. If just_legend is True, it returns a list of curves' legend. :param bool just_legend: True to get the legend of the curves, False (the default) to get the curves' data and info. :param bool withhidden: False (default) to skip hidden curves. :return: list of curves' legend or :class:`.items.Curve` :rtype: list of str or list of :class:`.items.Curve` """ return self._getItems(kind='curve', just_legend=just_legend, withhidden=withhidden) def getCurve(self, legend=None): """Get the object describing a specific curve. It returns None in case no matching curve is found. :param str legend: The legend identifying the curve. If not provided or None (the default), the active curve is returned or if there is no active curve, the latest updated curve that is not hidden is returned if there are curves in the plot. :return: None or :class:`.items.Curve` object """ return self._getItem(kind='curve', legend=legend) def getAllImages(self, just_legend=False): """Returns all images legend or objects. It returns an empty list in case of not
= MockStorage(core_management_host=None, core_management_port=None) scheduler._storage_async = MockStorageAsync(core_management_host=None, core_management_port=None) mocker.patch.object(scheduler, '_schedule_first_task') log_exception = mocker.patch.object(scheduler._logger, "exception") new_schedules = copy.deepcopy(MockStorageAsync.schedules) new_schedules[5]['schedule_interval'] = test_interval mocker.patch.object(MockStorageAsync, 'schedules', new_schedules) # WHEN # THEN if is_exception is True: with pytest.raises(Exception): await scheduler._get_schedules() assert 1 == log_exception.call_count else: await scheduler._get_schedules() assert len(scheduler._storage_async.schedules) == len(scheduler._schedules) @pytest.mark.asyncio async def test__get_schedules_exception(self, mocker): # GIVEN scheduler = Scheduler() scheduler._storage = MockStorage(core_management_host=None, core_management_port=None) scheduler._storage_async = MockStorageAsync(core_management_host=None, core_management_port=None) log_debug = mocker.patch.object(scheduler._logger, "debug", side_effect=Exception()) log_exception = mocker.patch.object(scheduler._logger, "exception") mocker.patch.object(scheduler, '_schedule_first_task', side_effect=Exception()) # WHEN # THEN with pytest.raises(Exception): await scheduler._get_schedules() log_args = 'Query failed: %s', 'schedules' log_exception.assert_called_once_with(*log_args) @pytest.mark.asyncio async def test__read_storage(self, mocker): # GIVEN scheduler = Scheduler() scheduler._storage = MockStorage(core_management_host=None, core_management_port=None) scheduler._storage_async = MockStorageAsync(core_management_host=None, core_management_port=None) mocker.patch.object(scheduler, '_schedule_first_task') # WHEN await scheduler._read_storage() # THEN assert len(scheduler._storage_async.scheduled_processes) == len(scheduler._process_scripts) assert len(scheduler._storage_async.schedules) == len(scheduler._schedules) @pytest.mark.asyncio @pytest.mark.skip("_mark_tasks_interrupted() not implemented in main Scheduler class.") async def test__mark_tasks_interrupted(self, mocker): pass @pytest.mark.asyncio async def test__read_config(self, mocker): async def get_cat(): return { "max_running_tasks": { "description": "The maximum number of tasks that can be running at any given time", "type": "integer", "default": str(Scheduler._DEFAULT_MAX_RUNNING_TASKS), "value": str(Scheduler._DEFAULT_MAX_RUNNING_TASKS) }, "max_completed_task_age_days": { "description": "The maximum age, in days (based on the start time), for a rows " "in the tasks table that do not have a status of running", "type": "integer", "default": str(Scheduler._DEFAULT_MAX_COMPLETED_TASK_AGE_DAYS), "value": str(Scheduler._DEFAULT_MAX_COMPLETED_TASK_AGE_DAYS) }, } # Changed in version 3.8: patch() now returns an AsyncMock if the target is an async function. if sys.version_info.major == 3 and sys.version_info.minor >= 8: _rv = await get_cat() else: _rv = asyncio.ensure_future(get_cat()) # GIVEN scheduler = Scheduler() scheduler._storage = MockStorage(core_management_host=None, core_management_port=None) scheduler._storage_async = MockStorageAsync(core_management_host=None, core_management_port=None) cr_cat = mocker.patch.object(ConfigurationManager, "create_category", return_value=asyncio.ensure_future(mock_task())) get_cat = mocker.patch.object(ConfigurationManager, "get_category_all_items", return_value=_rv) # WHEN assert scheduler._max_running_tasks is None assert scheduler._max_completed_task_age is None await scheduler._read_config() # THEN assert 1 == cr_cat.call_count assert 1 == get_cat.call_count assert scheduler._max_running_tasks is not None assert scheduler._max_completed_task_age is not None @pytest.mark.asyncio async def test_start(self, mocker): # TODO: Mandatory - Add negative tests for full code coverage # GIVEN scheduler = Scheduler() scheduler._storage = MockStorage(core_management_host=None, core_management_port=None) scheduler._storage_async = MockStorageAsync(core_management_host=None, core_management_port=None) log_debug = mocker.patch.object(scheduler._logger, "debug") log_info = mocker.patch.object(scheduler._logger, "info") current_time = time.time() mocker.patch.object(scheduler, '_schedule_first_task') mocker.patch.object(scheduler, '_scheduler_loop', return_value=asyncio.ensure_future(mock_task())) mocker.patch.multiple(scheduler, _core_management_port=9999, _core_management_host="0.0.0.0", current_time=current_time - 3600) # TODO: Remove after implementation of above test test__read_config() mocker.patch.object(scheduler, '_read_config', return_value=asyncio.ensure_future(mock_task())) assert scheduler._ready is False # WHEN await scheduler.start() # THEN assert scheduler._ready is True assert len(scheduler._storage_async.scheduled_processes) == len(scheduler._process_scripts) assert len(scheduler._storage_async.schedules) == len(scheduler._schedules) calls = [call('Starting'), call('Starting Scheduler: Management port received is %d', 9999)] log_info.assert_has_calls(calls, any_order=True) calls = [call('Database command: %s', 'scheduled_processes'), call('Database command: %s', 'schedules')] log_debug.assert_has_calls(calls, any_order=True) @pytest.mark.asyncio async def test_stop(self, mocker): # TODO: Mandatory - Add negative tests for full code coverage # GIVEN scheduler = Scheduler() scheduler._storage = MockStorage(core_management_host=None, core_management_port=None) scheduler._storage_async = MockStorageAsync(core_management_host=None, core_management_port=None) log_info = mocker.patch.object(scheduler._logger, "info") log_exception = mocker.patch.object(scheduler._logger, "exception") mocker.patch.object(scheduler, '_scheduler_loop', return_value=asyncio.ensure_future(mock_task())) mocker.patch.object(scheduler, '_resume_check_schedules', return_value=asyncio.ensure_future(mock_task())) mocker.patch.object(scheduler, '_purge_tasks_task', return_value=asyncio.ensure_future(asyncio.sleep(.1))) mocker.patch.object(scheduler, '_scheduler_loop_task', return_value=asyncio.ensure_future(asyncio.sleep(.1))) current_time = time.time() mocker.patch.multiple(scheduler, _core_management_port=9999, _core_management_host="0.0.0.0", _start_time=current_time - 3600, _paused=False, _task_processes={}) # WHEN retval = await scheduler.stop() # THEN assert retval is True assert scheduler._schedule_executions is None assert scheduler._task_processes is None assert scheduler._schedules is None assert scheduler._process_scripts is None assert scheduler._ready is False assert scheduler._paused is False assert scheduler._start_time is None calls = [call('Processing stop request'), call('Stopped')] log_info.assert_has_calls(calls, any_order=True) # TODO: Find why these exceptions are being raised despite mocking _purge_tasks_task, _scheduler_loop_task calls = [call('An exception was raised by Scheduler._purge_tasks %s', "object MagicMock can't be used in 'await' expression"), call('An exception was raised by Scheduler._scheduler_loop %s', "object MagicMock can't be used in 'await' expression")] log_exception.assert_has_calls(calls) @pytest.mark.asyncio async def test_get_scheduled_processes(self, mocker): # GIVEN scheduler = Scheduler() scheduler._storage = MockStorage(core_management_host=None, core_management_port=None) scheduler._storage_async = MockStorageAsync(core_management_host=None, core_management_port=None) await scheduler._get_process_scripts() mocker.patch.object(scheduler, '_ready', True) # WHEN processes = await scheduler.get_scheduled_processes() # THEN assert len(scheduler._storage_async.scheduled_processes) == len(processes) @pytest.mark.asyncio async def test_schedule_row_to_schedule(self, mocker): # GIVEN scheduler = Scheduler() schedule_id = uuid.uuid4() schedule_row = scheduler._ScheduleRow( id=schedule_id, name='Test Schedule', type=Schedule.Type.INTERVAL, day=0, time=0, repeat=10, repeat_seconds=10, exclusive=False, enabled=True, process_name='TestProcess') # WHEN schedule = scheduler._schedule_row_to_schedule(schedule_id, schedule_row) # THEN assert isinstance(schedule, Schedule) assert schedule.schedule_id == schedule_row[0] assert schedule.name == schedule_row[1] assert schedule.schedule_type == schedule_row[2] assert schedule_row[3] is 0 # 0 for Interval Schedule assert schedule_row[4] is 0 # 0 for Interval Schedule assert schedule.repeat == schedule_row[5] assert schedule.exclusive == schedule_row[7] assert schedule.enabled == schedule_row[8] assert schedule.process_name == schedule_row[9] @pytest.mark.asyncio async def test_get_schedules(self, mocker): # GIVEN scheduler, schedule, log_info, log_exception, log_error, log_debug = await self.scheduler_fixture(mocker) # WHEN schedules = await scheduler.get_schedules() # THEN assert len(scheduler._storage_async.schedules) == len(schedules) @pytest.mark.asyncio async def test_get_schedule(self, mocker): # GIVEN scheduler, schedule, log_info, log_exception, log_error, log_debug = await self.scheduler_fixture(mocker) schedule_id = uuid.UUID("cea17db8-6ccc-11e7-907b-a6006ad3dba0") # purge schedule # WHEN schedule = await scheduler.get_schedule(schedule_id) # THEN assert isinstance(schedule, Schedule) assert schedule.schedule_id == schedule_id assert schedule.name == "purge" assert schedule.schedule_type == Schedule.Type.MANUAL assert schedule.repeat == datetime.timedelta(0, 3600) assert schedule.exclusive is True assert schedule.enabled is True assert schedule.process_name == "purge" @pytest.mark.asyncio async def test_get_schedule_exception(self, mocker): # GIVEN scheduler, schedule, log_info, log_exception, log_error, log_debug = await self.scheduler_fixture(mocker) schedule_id = uuid.uuid4() # WHEN # THEN with pytest.raises(ScheduleNotFoundError): schedule = await scheduler.get_schedule(schedule_id) @pytest.mark.asyncio async def test_save_schedule_new(self, mocker): @asyncio.coroutine def mock_coro(): return "" # GIVEN scheduler, schedule, log_info, log_exception, log_error, log_debug = await self.scheduler_fixture(mocker) audit_logger = mocker.patch.object(AuditLogger, 'information', return_value=asyncio.ensure_future(mock_task())) first_task = mocker.patch.object(scheduler, '_schedule_first_task') resume_sch = mocker.patch.object(scheduler, '_resume_check_schedules') log_info = mocker.patch.object(scheduler._logger, "info") enable_schedule = mocker.patch.object(scheduler, "enable_schedule", return_value=mock_coro()) disable_schedule = mocker.patch.object(scheduler, "disable_schedule", return_value=mock_coro()) schedule_id = uuid.uuid4() schedule_row = scheduler._ScheduleRow( id=schedule_id, name='Test Schedule', type=Schedule.Type.INTERVAL, day=0, time=0, repeat=datetime.timedelta(seconds=30), repeat_seconds=30, exclusive=False, enabled=True, process_name='TestProcess') schedule = scheduler._schedule_row_to_schedule(schedule_id, schedule_row) # WHEN await scheduler.save_schedule(schedule) # THEN assert len(scheduler._storage_async.schedules) + 1 == len(scheduler._schedules) assert 1 == audit_logger.call_count calls =[call('SCHAD', {'schedule': {'name': 'Test Schedule', 'processName': 'TestProcess', 'type': Schedule.Type.INTERVAL, 'repeat': 30.0, 'enabled': True, 'exclusive': False}})] audit_logger.assert_has_calls(calls, any_order=True) assert 1 == first_task.call_count assert 1 == resume_sch.call_count assert 0 == enable_schedule.call_count assert 0 == disable_schedule.call_count @pytest.mark.asyncio async def test_save_schedule_new_with_enable_modified(self, mocker): @asyncio.coroutine def mock_coro(): return "" # GIVEN scheduler, schedule, log_info, log_exception, log_error, log_debug = await self.scheduler_fixture(mocker) audit_logger = mocker.patch.object(AuditLogger, 'information', return_value=asyncio.ensure_future(mock_task())) first_task = mocker.patch.object(scheduler, '_schedule_first_task') resume_sch = mocker.patch.object(scheduler, '_resume_check_schedules') log_info = mocker.patch.object(scheduler._logger, "info") enable_schedule = mocker.patch.object(scheduler, "enable_schedule", return_value=mock_coro()) disable_schedule = mocker.patch.object(scheduler, "disable_schedule", return_value=mock_coro()) schedule_id = uuid.uuid4() schedule_row = scheduler._ScheduleRow( id=schedule_id, name='Test Schedule', type=Schedule.Type.INTERVAL, day=0, time=0, repeat=datetime.timedelta(seconds=30), repeat_seconds=30, exclusive=False, enabled=True, process_name='TestProcess') schedule = scheduler._schedule_row_to_schedule(schedule_id, schedule_row) # WHEN await scheduler.save_schedule(schedule, is_enabled_modified=True) # THEN assert len(scheduler._storage_async.schedules) + 1 == len(scheduler._schedules) assert 1 == audit_logger.call_count calls =[call('SCHAD', {'schedule': {'name': 'Test Schedule', 'processName': 'TestProcess', 'type': Schedule.Type.INTERVAL, 'repeat': 30.0, 'enabled': True, 'exclusive': False}})] audit_logger.assert_has_calls(calls, any_order=True) assert 1 == first_task.call_count assert 1 == resume_sch.call_count assert 1 == enable_schedule.call_count assert 0 == disable_schedule.call_count # WHEN await scheduler.save_schedule(schedule, is_enabled_modified=False) # THEN assert 1 == disable_schedule.call_count @pytest.mark.asyncio async def test_save_schedule_update(self, mocker): @asyncio.coroutine def mock_coro(): return "" # GIVEN scheduler, schedule, log_info, log_exception, log_error, log_debug = await self.scheduler_fixture(mocker) audit_logger = mocker.patch.object(AuditLogger, 'information', return_value=asyncio.ensure_future(mock_task())) first_task = mocker.patch.object(scheduler, '_schedule_first_task') resume_sch = mocker.patch.object(scheduler, '_resume_check_schedules') log_info = mocker.patch.object(scheduler._logger, "info") schedule_id = uuid.UUID("2b614d26-760f-11e7-b5a5-be2e44b06b34") # OMF to PI North schedule_row = scheduler._ScheduleRow( id=schedule_id, name='Test Schedule', type=Schedule.Type.TIMED, day=1, time=datetime.time(), repeat=datetime.timedelta(seconds=30), repeat_seconds=30, exclusive=False, enabled=True, process_name='TestProcess') schedule = scheduler._schedule_row_to_schedule(schedule_id, schedule_row) enable_schedule = mocker.patch.object(scheduler, "enable_schedule", return_value=mock_coro()) disable_schedule = mocker.patch.object(scheduler, "disable_schedule", return_value=mock_coro()) # WHEN await scheduler.save_schedule(schedule) # THEN assert len(scheduler._storage_async.schedules) == len(scheduler._schedules) assert 1 == audit_logger.call_count calls = [call('SCHCH', {'schedule': {'name': 'Test Schedule', 'enabled': True, 'repeat': 30.0, 'exclusive': False, 'day': 1, 'time': '0:0:0', 'processName': 'TestProcess', 'type': Schedule.Type.TIMED}})] audit_logger.assert_has_calls(calls, any_order=True) assert 1 == first_task.call_count assert 1 == resume_sch.call_count assert 0 == enable_schedule.call_count assert 0 == disable_schedule.call_count @pytest.mark.asyncio async def test_save_schedule_update_with_enable_modified(self, mocker): @asyncio.coroutine def mock_coro(): return "" # GIVEN scheduler, schedule, log_info, log_exception, log_error, log_debug = await self.scheduler_fixture(mocker) audit_logger = mocker.patch.object(AuditLogger, 'information', return_value=asyncio.ensure_future(mock_task())) first_task = mocker.patch.object(scheduler, '_schedule_first_task') resume_sch = mocker.patch.object(scheduler, '_resume_check_schedules') log_info = mocker.patch.object(scheduler._logger, "info") schedule_id = uuid.UUID("2b614d26-760f-11e7-b5a5-be2e44b06b34") # OMF to PI North schedule_row = scheduler._ScheduleRow( id=schedule_id, name='Test Schedule', type=Schedule.Type.TIMED, day=1, time=datetime.time(), repeat=datetime.timedelta(seconds=30), repeat_seconds=30, exclusive=False, enabled=True, process_name='TestProcess') schedule = scheduler._schedule_row_to_schedule(schedule_id, schedule_row) enable_schedule = mocker.patch.object(scheduler, "enable_schedule", return_value=mock_coro()) disable_schedule = mocker.patch.object(scheduler, "disable_schedule", return_value=mock_coro()) # WHEN await scheduler.save_schedule(schedule, is_enabled_modified=True) # THEN assert len(scheduler._storage_async.schedules) == len(scheduler._schedules) assert 1 == audit_logger.call_count calls = [call('SCHCH', {'schedule': {'name': 'Test Schedule', 'enabled': True, 'repeat': 30.0, 'exclusive': False, 'day': 1,
len(sl_center) # Fitting Gaussians to skylines... say_status = 0 self.wavelength_offset_per_fibre = [] wave_median_offset = [] print("\n> Performing a Gaussian fit to selected, bright skylines... (this will FAIL if RSS is not corrected for CCD defects...)") if fibre != 0: f_i = fibre f_f = fibre + 1 print(" Checking fibre {} (only this fibre is corrected, use fibre = 0 for all)...".format(fibre)) verbose = True warnings = True else: f_i = 0 f_f = self.n_spectra verbose = False for fibre in range(f_i, f_f): # (self.n_spectra): spectrum = self.intensity_corrected[fibre] if fibre == say_status: print(" Checking fibre {:4} ... ({:6.2f} % completed) ...".format( fibre, fibre * 100.0 / self.n_spectra )) say_status = say_status + 20 # Gaussian fits to the sky spectrum sl_gaussian_flux = [] sl_gaussian_sigma = [] sl_gauss_center = [] sl_offset = [] sl_offset_good = [] if verbose: print("\n> Performing Gaussian fitting to bright sky lines in all fibres of rss file...") for i in range(number_sl): if sl_fnl[i] == 0: plot_fit = False else: plot_fit = True resultado = fluxes( w, spectrum, sl_center[i], lowlow=sl_lowlow[i], lowhigh=sl_lowhigh[i], highlow=sl_highlow[i], highhigh=sl_highhigh[i], lmin=sl_lmin[i], lmax=sl_lmax[i], fmin=0, fmax=0, broad=2.1 * 2.355, plot=plot_fit, verbose=False, plot_sus=False, fcal=False, warnings=warnings, ) # Broad is FWHM for Gaussian sigm a= 1, sl_gaussian_flux.append(resultado[3]) sl_gauss_center.append(resultado[1]) sl_gaussian_sigma.append(resultado[5] / 2.355) sl_offset.append(sl_gauss_center[i] - sl_center[i]) if ( sl_gaussian_flux[i] < 0 or np.abs(sl_center[i] - sl_gauss_center[i]) > maxima_offset or sl_gaussian_sigma[i] > maxima_sigma ): if verbose: print(" Bad fitting for {} ... ignoring this fit...".format(sl_center[i])) else: sl_offset_good.append(sl_offset[i]) if verbose: print(" Fitted wavelength for sky line {:8.3f}: center = {:8.3f} sigma = {:6.3f} offset = {:7.3f} ".format( sl_center[i], sl_gauss_center[i], sl_gaussian_sigma[i], sl_offset[i], )) median_offset_fibre = np.nanmedian(sl_offset_good) wave_median_offset.append(median_offset_fibre) if verbose: print("\n> Median offset for fibre {:3} = {:7.3f}".format( fibre, median_offset_fibre )) # Second-order fit ... xfibre = list(range(0, self.n_spectra)) a2x, a1x, a0x = np.polyfit(xfibre, wave_median_offset, 2) print("\n> Fitting a second-order polynomy a0x + a1x * fibre + a2x * fibre**2:") else: print("\n> Solution to the second-order polynomy a0x + a1x * fibre + a2x * fibre**2 have been provided:") a0x = sol[0] a1x = sol[1] a2x = sol[2] xfibre = list(range(0, self.n_spectra)) print(" a0x = {} a1x = {} a2x = {}".format(a0x, a1x, a2x)) self.wavelength_parameters = [a0x, a1x, a2x] # Save solutions fx = a0x + a1x * np.array(xfibre) + a2x * np.array(xfibre) ** 2 if plot: plt.figure(figsize=(10, 4)) if sol[0] == 0: plt.plot(xfibre, wave_median_offset) pf = wave_median_offset else: pf = fx plt.plot(xfibre, fx, "r") plot_plot( xfibre, pf, ptitle="Second-order fit to individual offsets", xmin=-20, xmax=1000, xlabel="Fibre", ylabel="offset", ) # Applying results print("\n> Applying results to all fibres...") for fibre in xfibre: f = self.intensity_corrected[fibre] w_shift = fx[fibre] self.intensity_corrected[fibre] = rebin_spec_shift(w, f, w_shift) # Check results if plot: plt.figure(figsize=(10, 4)) for i in [0, 300, 600, 950]: plt.plot(w, self.intensity[i]) plot_plot( w, self.intensity[0], ptitle="Before corrections, fibres 0, 300, 600, 950", xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, ) plt.figure(figsize=(10, 4)) for i in [0, 300, 600, 950]: plt.plot(w, self.intensity_corrected[i]) plot_plot( w, self.intensity_corrected[0], ptitle="Checking wavelength corrections in fibres 0, 300, 600, 950", xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, ) print("\n> Small fixing of the 2dFdr wavelengths done!") return # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # KOALA_RSS CLASS # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- class KOALA_RSS(RSS): """ This class reads the FITS files returned by `2dfdr <https://aat.anu.edu.au/science/instruments/current/AAOmega/reduction>`_ and performs basic analysis tasks (see description under each method). Parameters ---------- filename : string FITS file returned by 2dfdr, containing the Raw Stacked Spectra. The code makes sure that it contains 1000 spectra with 2048 wavelengths each. Example ------- >>> pointing1 = KOALA_RSS('data/16jan20058red.fits') > Reading file "data/16jan20058red.fits" ... 2048 wavelength points between 6271.33984375 and 7435.43408203 1000 spaxels These numbers are the right ones for KOALA! DONE! """ # ----------------------------------------------------------------------------- def __init__( self, filename, save_rss_to_fits_file="", rss_clean=False, # TASK_KOALA_RSS apply_throughput=True, skyflat="", plot_skyflat=False, flat="", nskyflat=True, correct_ccd_defects=False, correct_high_cosmics=False, clip_high=100, step_ccd=50, remove_5578=False, plot_suspicious_fibres=False, fix_wavelengths=False, sol=[0, 0, 0], sky_method="self", n_sky=50, sky_fibres=[1000], # do_sky=True sky_spectrum=[0], sky_rss=[0], scale_sky_rss=0, scale_sky_1D=1.0, is_sky=False, win_sky=151, auto_scale_sky=False, correct_negative_sky=False, sky_wave_min=0, sky_wave_max=0, cut_sky=5.0, fmin=1, fmax=10, individual_sky_substraction=False, fibre_list=[100, 200, 300, 400, 500, 600, 700, 800, 900], do_extinction=True, telluric_correction=[0], id_el=False, high_fibres=10, brightest_line="Ha", cut=1.5, broad=1.0, plot_id_el=False, id_list=[0], brightest_line_wavelength=0, clean_sky_residuals=False, dclip=3.0, extra_w=1.3, step_csr=25, fibre=0, valid_wave_min=0, valid_wave_max=0, warnings=True, verbose=False, plot=True, norm=colors.LogNorm(), fig_size=12, ): """ Parameters ---------- filename save_rss_to_fits_file rss_clean apply_throughput skyflat plot_skyflat flat nskyflat correct_ccd_defects correct_high_cosmics clip_high step_ccd remove_5578 plot_suspicious_fibres fix_wavelengths sol sky_method n_sky sky_fibres sky_spectrum sky_rss scale_sky_rss scale_sky_1D is_sky win_sky auto_scale_sky correct_negative_sky sky_wave_min sky_wave_max cut_sky fmin fmax individual_sky_substraction fibre_list do_extinction telluric_correction id_el high_fibres brightest_line cut broad plot_id_el id_list brightest_line_wavelength clean_sky_residuals dclip extra_w step_csr fibre valid_wave_min valid_wave_max warnings verbose plot norm fig_size """ # Just read file if rss_clean = True if rss_clean: apply_throughput = False correct_ccd_defects = False fix_wavelengths = False sol = [0, 0, 0] sky_method = "none" do_extinction = False telluric_correction = [0] id_el = False clean_sky_residuals = False plot = False correct_negative_sky = False # Create RSS object super(KOALA_RSS, self).__init__() print("\n> Reading file", '"' + filename + '"', "...") RSS_fits_file = fits.open(filename) # Open file self.rss_list = [] # General info: self.object = RSS_fits_file[FitsExt.main].header["OBJECT"] self.description = self.object + " - " + filename self.RA_centre_deg = RSS_fits_file[FitsExt.fibres_ifu].header["CENRA"] * 180/np.pi self.DEC_centre_deg = RSS_fits_file[FitsExt.fibres_ifu].header["CENDEC"] * 180/np.pi self.exptime = RSS_fits_file[FitsExt.main].header["EXPOSED"] # WARNING: Something is probably wrong/inaccurate here! # Nominal offsets between pointings are totally wrong! # Read good/bad spaxels all_spaxels = list(range(len(RSS_fits_file[FitsExt.fibres_ifu].data))) quality_flag = [RSS_fits_file[FitsExt.fibres_ifu].data[i][FitsFibresIFUIndex.quality_flag] for i in all_spaxels] good_spaxels = [i for i in all_spaxels if quality_flag[i] == 1] bad_spaxels = [i for i in all_spaxels if quality_flag[i] == 0] # for i in range(1): # print i, RSS_fits_file[2] # # Create wavelength, intensity, and variance arrays only for good spaxels wcsKOALA = WCS(RSS_fits_file[FitsExt.main].header) # variance = RSS_fits_file[1].data[good_spaxels] index_wave = np.arange(RSS_fits_file[FitsExt.main].header["NAXIS1"]) wavelength = wcsKOALA.dropaxis(1).wcs_pix2world(index_wave, 0)[0] intensity = RSS_fits_file[FitsExt.main].data[good_spaxels] print("\n Number of spectra in this RSS = {}, number of good spectra = {} , number of bad spectra ={}".format( len(RSS_fits_file[FitsExt.main].data), len(good_spaxels), len(bad_spaxels))) print(" Bad fibres = {}".format(bad_spaxels)) # Read errors using RSS_fits_file[1] # self.header1 = RSS_fits_file[1].data # CHECK WHEN DOING ERRORS !!! # Read spaxel positions on sky using RSS_fits_file[2] self.header2_data = RSS_fits_file[FitsExt.fibres_ifu].data # CAREFUL !! header 2 has the info of BAD fibres, if we are reading from our created RSS files we have to do it in a different way... # print RSS_fits_file[2].data if len(bad_spaxels) == 0: offset_RA_arcsec_ = [] offset_DEC_arcsec_ = [] for i in range(len(good_spaxels)): offset_RA_arcsec_.append(self.header2_data[i][FitsFibresIFUIndex.ra_offset]) offset_DEC_arcsec_.append(self.header2_data[i][FitsFibresIFUIndex.dec_offset]) offset_RA_arcsec = np.array(offset_RA_arcsec_) offset_DEC_arcsec = np.array(offset_DEC_arcsec_) variance = np.zeros_like(intensity) # CHECK FOR ERRORS else: offset_RA_arcsec = np.array( [RSS_fits_file[FitsExt.fibres_ifu].data[i][FitsFibresIFUIndex.ra_offset] for i in good_spaxels] ) offset_DEC_arcsec = np.array( [RSS_fits_file[FitsExt.fibres_ifu].data[i][FitsFibresIFUIndex.dec_offset] for i in good_spaxels] ) self.ID = np.array( [RSS_fits_file[FitsExt.fibres_ifu].data[i][FitsFibresIFUIndex.spec_id] for i in good_spaxels] ) # These are the good fibres variance = RSS_fits_file[FitsExt.var].data[good_spaxels] # CHECK FOR ERRORS self.ZDSTART = RSS_fits_file[FitsExt.main].header["ZDSTART"] # Zenith distance (degrees?) self.ZDEND = RSS_fits_file[FitsExt.main].header["ZDEND"] # KOALA-specific stuff self.PA = RSS_fits_file[FitsExt.main].header["TEL_PA"] # Position angle? self.grating = RSS_fits_file[FitsExt.main].header["GRATID"] # Check RED / BLUE arm for AAOmega if RSS_fits_file[FitsExt.main].header["SPECTID"] == "RD": AAOmega_Arm = "RED" if RSS_fits_file[FitsExt.main].header["SPECTID"] == "BL": AAOmega_Arm = "BLUE" # For WCS self.CRVAL1_CDELT1_CRPIX1 = [] self.CRVAL1_CDELT1_CRPIX1.append(RSS_fits_file[FitsExt.main].header["CRVAL1"]) # see https://idlastro.gsfc.nasa.gov/ftp/pro/astrom/aaareadme.txt maybe? self.CRVAL1_CDELT1_CRPIX1.append(RSS_fits_file[FitsExt.main].header["CDELT1"]) self.CRVAL1_CDELT1_CRPIX1.append(RSS_fits_file[FitsExt.main].header["CRPIX1"]) # SET RSS # FROM HERE IT WAS self.set_data before ------------------------------------------ self.wavelength = wavelength self.n_wave = len(wavelength) # Check that dimensions match KOALA numbers if self.n_wave != 2048 and len(all_spaxels) != 1000: print("\n *** WARNING *** : These numbers are NOT the standard ones for KOALA") print("\n> Setting the data for this file:") if variance.shape != intensity.shape: print("\n* ERROR: * the intensity and variance matrices are {} and {} respectively\n".format(intensity.shape, variance.shape)) raise ValueError n_dim = len(intensity.shape) if n_dim == 2: self.intensity = intensity self.variance = variance elif n_dim == 1: self.intensity = intensity.reshape((1, self.n_wave)) self.variance = variance.reshape((1, self.n_wave)) else: print("\n* ERROR: * the intensity matrix supplied has {} dimensions\n".format(n_dim)) raise ValueError self.n_spectra = self.intensity.shape[0] self.n_wave = len(self.wavelength) print(" Found {} spectra with {} wavelengths".format( self.n_spectra, self.n_wave ), "between {:.2f} and {:.2f} Angstrom".format( self.wavelength[0], self.wavelength[-1] )) if self.intensity.shape[1] != self.n_wave: print("\n* ERROR: * spectra have {} wavelengths rather
# cashierAccount from Tkinter import * import tkMessageBox , ttk , pickle , datetime , re class NegativeError(Exception) : pass class PositiveError(Exception) : pass class iteminfo(object): def __init__(self): self.icode = StringVar() self.item = StringVar() self.price = StringVar() self.qty = StringVar() self.disc = StringVar() def calAmount(self , qty) : k = float(self.qty) k -= float(qty) self.qty = str(k) return ((float(self.price) * float(qty)) * (1 - float(self.disc)/100.0) * (1 + 18/100.0)) def signout() : result = tkMessageBox.askquestion("Sign Out", "Are You Sure You Want To Sign Out?", icon='warning') if result == "yes" : open("temp" , "w").write("") root.destroy() import main else : pass def details(event): try: if len(phoneNoText.get()) == 0 : raise IOError elif len(phoneNoText.get()) in (8,10): int(phoneNoText.get()) file2 = open("details.dat" , "rb") det = pickle.load(file2) for i in det.keys(): if i == phoneNoText.get(): clientNameText.delete(0 , END) clientNameText.insert(0 , det[i][0]) emailText.delete(0 , END) emailText.insert(0 , det[i][1]) else : raise ValueError except ValueError: tkMessageBox.showinfo("Input Error", "Phone Number Is Invalid." , icon = "warning") phoneNoText.delete(0 , END) phoneNoText.focus_set() except IOError : pass def validateEmail(event): if emailText.get() == "" : pass elif re.search(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)",emailText.get()) == None : tkMessageBox.showinfo("Input Error", "Email ID Is Invalid." , icon = "warning") emailText.delete(0 , END) emailText.focus_set() def offerDecider(): global flag if datetime.datetime.now().strftime('%m') == "02": offerText.config(state = NORMAL) offerText.insert(0,"End of Season Sale (30%)") offerText.config(state = DISABLED) flag =1 elif datetime.datetime.now().strftime('%m') == "10": offerText.config(state = NORMAL) offerText.insert(0,"Festive Sale (30%)") offerText.config(state = DISABLED) flag = 1 else: offerText.config(state = NORMAL) offerText.insert(0,"No Offer") offerText.config(state = DISABLED) flag = 0 def addItem2(name , code , price , qty , disc , tax) : if not code : tkMessageBox.showinfo("Data Error", "Please Select An Item And Click On Auto Fill Button.") else: try: for i in selections : if variable.get() == i.item : if float(qty) > 0 : if float(qty) <= float(i.qty) : amount = i.calAmount(qty) amountList.append(amount) else: raise PositiveError else : raise NegativeError totalText.config(state = NORMAL) totalText.delete(0 , END) totalText.insert(0 , str(sum(amountList))) totalText.config(state = DISABLED) if flag == 1 : offerDiscText.config(state = NORMAL) offerDiscText.delete(0 , END) offerDiscText.insert (0 , str(-float(offerText.get()[-4:-2:1]) * float(totalText.get())/100)) offerDiscText.config(state = DISABLED) grandTotalText.config(state = NORMAL) grandTotalText.delete(0 , END) grandTotalText.insert(0,str(float(totalText.get()) + float(offerDiscText.get() ))) grandTotalText.config(state = DISABLED) table.insert("" , END , text = name , values = (code , price , qty , disc , tax , amount)) itemDetails.append((name , code , price , qty , disc , tax , amount)) variable.set("Choose Item") productCodeText.config(state = NORMAL) productCodeText.delete(0 , END) productCodeText.config(state = DISABLED) productPriceText.config(state = NORMAL) productPriceText.delete(0 , END) productPriceText.config(state = DISABLED) productQtyText.delete(0 , END) productDiscText.config(state = NORMAL) productDiscText.delete(0 , END) productDiscText.config(state = DISABLED) except NegativeError : tkMessageBox.showinfo("Quantity Error", "Please Enter A Valid Quantity.") except PositiveError : tkMessageBox.showinfo("Quantity Error", "Entered Quamtity Not Available. Please Enter Again.") except ValueError: tkMessageBox.showinfo("Quantity Error", "Please Enter Quantity.") def autoFill() : if variable.get() == 'Choose Item': tkMessageBox.showinfo("Data Error", "Please Select An Item. ") else: for i in selections : if variable.get() == i.item : productCodeText.config(state = NORMAL) productCodeText.delete(0 , END) productCodeText.insert(0 , i.icode) productCodeText.config(state = DISABLED) productPriceText.config(state = NORMAL) productPriceText.delete(0 , END) productPriceText.insert(0 , i.price) productPriceText.config(state = DISABLED) productDiscText.config(state = NORMAL) productDiscText.delete(0 , END) productDiscText.insert(0 , i.disc) productDiscText.config(state = DISABLED) break def deleteItem2(): try : selectedItem = table.selection()[0] name = table.item(table.focus())["text"] qty = table.item(table.focus())["values"][2] amt = table.item(table.focus())["values"][5] del(itemDetails[int(selectedItem[1:]) - 1]) table.delete(selectedItem) except : tkMessageBox.showinfo("Remove Item", "Please Select An Item.") for i in selections : if i.item == name : k = float(i.qty) k += float(qty) i.qty = str(k) amountList.remove(float(amt)) totalText.config(state = NORMAL) totalText.delete(0 , END) totalText.insert(0 , str(sum(amountList))) totalText.config(state = DISABLED) def generateBill() : if clientNameText.get().lstrip() == "" or invoiceText.get().lstrip() == "" or float(totalText.get()) == 0: tkMessageBox.showinfo("Data Error", "Data Provided Is Insufficient." , icon = "warning") else : pickle.dump(selections , open("inventory.dat" , "wb")) file1 = open(username + ".dat" , "ab") clientDetails = [clientNameText.get() , phoneNoText.get() , emailText.get() , issueDateText.get() , offerText.get() ,totalText.get() , offerDiscText.get() , grandTotalText.get()] d = {"invoiceNumber":invoiceText.get() , 'cDetails': clientDetails , 'iDetails' : itemDetails } pickle.dump(d,file1) tkMessageBox.showinfo("Congratulations!", "Invoice Has Been Generated." ) file2 = open("details.dat" , "rb") det = pickle.load(file2) det[phoneNoText.get()] = (clientNameText.get() , emailText.get()) pickle.dump(det , open("details.dat" , "wb")) newInvoiceLayout() def newInvoiceLayout() : global body ,phoneNoText , itemDetails ,emailText , grandTotalText , offerDiscText, offerText ,offerLabel ,clientNameText,invoiceText, issueDateText,totalText,table , variable , productCodeText , productPriceText , productQtyText , productDiscText , totalText , selections , amountList amountList = [] itemDetails=[] selections = pickle.load(open("inventory.dat" , "rb")) body.destroy() body = Frame(root , bd = 5) body.pack(side = TOP , fill = BOTH , expand = True) clientFrame = LabelFrame(body , text = "Client Details" , font = ("Arial" , 15)) clientFrame.pack(fill = BOTH) phoneNoLabel = Label(clientFrame , text = "Contact Number ") phoneNoLabel.place(x = 10 , y = 30) phoneNoText = Entry(clientFrame , width = 30 ) phoneNoText.place(x = 120 , y = 30) phoneNoText.bind("<FocusOut>", details) clientNameLabel = Label(clientFrame , text = "Client Name ") clientNameLabel.place(x = 10 , y = 80) clientNameText = Entry(clientFrame , width = 30) clientNameText.place(x = 120 , y = 80) emailLabel = Label(clientFrame , text = "Email Address ") emailLabel.place(x = 470 , y = 80) emailText = Entry(clientFrame , width = 30) emailText.place(x = 610 , y = 80) emailText.bind("<FocusOut>",validateEmail) invoiceLabel = Label(clientFrame , text = "Invoice Number ") invoiceLabel.place(x = 470 , y = 30) invoiceText = Entry(clientFrame , width = 30 , disabledforeground = "black" , disabledbackground = "white") invoiceText.place(x = 610 , y = 30) invoiceText.insert(0 , datetime.datetime.now().strftime('%d%m%Y%H%M%S')) invoiceText.config(state = DISABLED) issueDateLabel = Label(clientFrame , text = "Issue Date (DD/MM/YYYY)") issueDateLabel.place(x = 950 , y = 30) issueDateText = Entry(clientFrame , width = 23 , disabledforeground = "black" , disabledbackground = "white") issueDateText.insert(0 , datetime.datetime.now().strftime('%d/%m/%Y')) issueDateText.config(state = DISABLED ) issueDateText.place(x = 1150 , y = 30) offerLabel = Label(clientFrame , text = "Monthly Offer") offerLabel.place(x = 950 , y = 80) offerText = Entry(clientFrame , width = 23 ,state = DISABLED ,disabledforeground = "black" , disabledbackground = "white") offerText.place(x = 1150 , y= 80) lineBreak = Label(clientFrame , text = "\n\n\n\n\n\n\n") lineBreak.pack(side = RIGHT) itemFrame = LabelFrame(body , text = "Item Details" , font = ("Arial" , 15)) itemFrame.pack(fill = BOTH , expand = YES) productNameLabel = Label(itemFrame , text = "Product Name ") productNameLabel.place(x = 10 , y = 10) options = pickle.load(open("inventory.dat" , "rb")) l = [ a.item for a in options ] variable = StringVar() variable.set("Choose Item") productNameList = apply(OptionMenu , (itemFrame , variable) + tuple(l)) productNameList.config(width = 15) productNameList.place(x = 10 , y = 30) productCodeLabel = Label(itemFrame , text = "Product Code ") productCodeLabel.place(x = 200 , y = 10) productCodeText = Entry(itemFrame , state = DISABLED , disabledforeground = "black" , disabledbackground = "white") productCodeText.place(x = 200 , y = 30) productPriceLabel = Label(itemFrame , text = "Price/Unit (INR) ") productPriceLabel.place(x = 390 , y = 10) productPriceText = Entry(itemFrame , state = DISABLED , disabledforeground = "black" , disabledbackground = "white") productPriceText.place(x = 390 , y = 30) productQtyLabel = Label(itemFrame , text = "Quantity ") productQtyLabel.place(x = 580 , y = 10) productQtyText = Entry(itemFrame) productQtyText.place(x = 580 , y = 30) productDiscLabel = Label(itemFrame , text = "Discount (%) ") productDiscLabel.place(x = 760 , y = 10) productDiscText = Entry(itemFrame , state = DISABLED , disabledforeground = "black" , disabledbackground = "white") productDiscText.place(x = 760 , y = 30) productTaxLabel = Label(itemFrame , text = "Tax (%) ") productTaxLabel.place(x = 950 , y = 10) productTaxText = Entry(itemFrame) productTaxText.insert(0 , "18") productTaxText.configure(state = DISABLED , disabledforeground = "black" , disabledbackground = "white") productTaxText.place(x = 950 , y = 30) add = Button(itemFrame , text = "Add Item" , command = lambda : addItem2(variable.get() , productCodeText.get() , productPriceText.get() , productQtyText.get() , productDiscText.get() , productTaxText.get()) , width = "10") add.place(x = 1120 , y = 25) remove = Button(itemFrame ,
# -*- coding: utf-8 -*- #--------------------------------------------------------------------------- # Copyright 2020 VMware, Inc. All rights reserved. # AUTO GENERATED FILE -- DO NOT MODIFY! # # vAPI stub file for package com.vmware.vcenter.lcm.discovery. #--------------------------------------------------------------------------- """ The ``com.vmware.vcenter.lcm.discovery_client`` module provides classes for discovering products registered with vCenter Server and interoperability between those products and vCenter Server. """ __author__ = 'VMware, Inc.' __docformat__ = 'restructuredtext en' import sys from com.vmware.cis_client import Tasks from vmware.vapi.stdlib.client.task import Task from vmware.vapi.bindings import type from vmware.vapi.bindings.converter import TypeConverter from vmware.vapi.bindings.enum import Enum from vmware.vapi.bindings.error import VapiError from vmware.vapi.bindings.struct import VapiStruct from vmware.vapi.bindings.stub import ( ApiInterfaceStub, StubFactoryBase, VapiInterface) from vmware.vapi.bindings.common import raise_core_exception from vmware.vapi.data.validator import (UnionValidator, HasFieldsOfValidator) from vmware.vapi.exception import CoreException from vmware.vapi.lib.constants import TaskType from vmware.vapi.lib.rest import OperationRestMetadata class Product(VapiStruct): """ The ``Info`` class contains information about a VMware product which is present in the customer Environemnt. The following information about the products are present: * Name * Version * Deployments * Automatically Discovered or Manually Added .. tip:: The arguments are used to initialize data attributes with the same names. """ def __init__(self, installed_product=None, name=None, version=None, target_version=None, deployments=None, auto=None, ): """ :type installed_product: :class:`str` :param installed_product: Identifies a product and a version uniquely. The identifier consists of product internal name and version. When clients pass a value of this class as a parameter, the attribute must be an identifier for the resource type: ``PRODUCT``. When methods return a value of this class as a return value, the attribute will be an identifier for the resource type: ``PRODUCT``. :type name: :class:`str` :param name: A public official product name. :type version: :class:`str` :param version: Current product version. :type target_version: :class:`str` or ``None`` :param target_version: Future version of the product after upgrade. ``targetVersion`` may not be applicable. :type deployments: :class:`list` of :class:`str` or ``None`` :param deployments: The list of hostname/IPs of the instances of the VMware products deployed in the environment. This field would be empty for manually added products. :type auto: :class:`bool` :param auto: Indicates if the product is auto-detected by the system or manually added. If it is set to true it means it is auto-detected. """ self.installed_product = installed_product self.name = name self.version = version self.target_version = target_version self.deployments = deployments self.auto = auto VapiStruct.__init__(self) Product._set_binding_type(type.StructType( 'com.vmware.vcenter.lcm.discovery.product', { 'installed_product': type.IdType(resource_types='PRODUCT'), 'name': type.StringType(), 'version': type.StringType(), 'target_version': type.OptionalType(type.StringType()), 'deployments': type.OptionalType(type.ListType(type.StringType())), 'auto': type.BooleanType(), }, Product, False, None)) class InteropReport(VapiInterface): """ The ``InteropReport`` interface provides methods to report the interoperability between a vCenter Server release version and the other installed VMware products registered in the vCenter Server instance. """ _VAPI_SERVICE_ID = 'com.vmware.vcenter.lcm.discovery.interop_report' """ Identifier of the service in canonical form. """ def __init__(self, config): """ :type config: :class:`vmware.vapi.bindings.stub.StubConfiguration` :param config: Configuration to be used for creating the stub. """ VapiInterface.__init__(self, config, _InteropReportStub) self._VAPI_OPERATION_IDS = {} self._VAPI_OPERATION_IDS.update({'create_task': 'create$task'}) class ReleaseInfo(VapiStruct): """ The ``InteropReport.ReleaseInfo`` class contains a product release information. .. tip:: The arguments are used to initialize data attributes with the same names. """ def __init__(self, version=None, note=None, ): """ :type version: :class:`str` :param version: The version of the release. :type note: :class:`str` or ``None`` :param note: A link to the release notes of the release. None if the release notes are not available. """ self.version = version self.note = note VapiStruct.__init__(self) ReleaseInfo._set_binding_type(type.StructType( 'com.vmware.vcenter.lcm.discovery.interop_report.release_info', { 'version': type.StringType(), 'note': type.OptionalType(type.URIType()), }, ReleaseInfo, False, None)) class ReportRow(VapiStruct): """ The ``InteropReport.ReportRow`` class contains the interoperability between a given product and the target product. .. tip:: The arguments are used to initialize data attributes with the same names. """ def __init__(self, product=None, compatible=None, compatible_releases=None, ): """ :type product: :class:`Product` :param product: The product to compare to the target product. :type compatible: :class:`bool` :param compatible: Defines whether the product is compatible against the target product. :type compatible_releases: :class:`list` of :class:`InteropReport.ReleaseInfo` :param compatible_releases: A list of compatible releases of the product with the target product. """ self.product = product self.compatible = compatible self.compatible_releases = compatible_releases VapiStruct.__init__(self) ReportRow._set_binding_type(type.StructType( 'com.vmware.vcenter.lcm.discovery.interop_report.report_row', { 'product': type.ReferenceType(__name__, 'Product'), 'compatible': type.BooleanType(), 'compatible_releases': type.ListType(type.ReferenceType(__name__, 'InteropReport.ReleaseInfo')), }, ReportRow, False, None)) class ReportSummary(VapiStruct): """ The ``InteropReport.ReportSummary`` class contains a summary of the :attr:`InteropReport.Report.products`. It consists of the count of compatible and incompatible products to the target product. .. tip:: The arguments are used to initialize data attributes with the same names. """ def __init__(self, compatible_count=None, incompatible_count=None, ): """ :type compatible_count: :class:`long` :param compatible_count: Number of compatible products. :type incompatible_count: :class:`long` :param incompatible_count: Number of incompatible products. """ self.compatible_count = compatible_count self.incompatible_count = incompatible_count VapiStruct.__init__(self) ReportSummary._set_binding_type(type.StructType( 'com.vmware.vcenter.lcm.discovery.interop_report.report_summary', { 'compatible_count': type.IntegerType(), 'incompatible_count': type.IntegerType(), }, ReportSummary, False, None)) class Report(VapiStruct): """ The ``InteropReport.Report`` class contains the interoperability report between the target product and the other registered products in the vCenter Server instance. .. tip:: The arguments are used to initialize data attributes with the same names. """ def __init__(self, date_created=None, target_product=None, products=None, issues=None, summary=None, ): """ :type date_created: :class:`datetime.datetime` :param date_created: Time when the report is created. :type target_product: :class:`Product` :param target_product: A product against the other products are compared to. Only vCenter Server is supported. :type products: :class:`list` of :class:`InteropReport.ReportRow` :param products: Interoperability matrix for the supplied target product and the other registered products. :type issues: :class:`com.vmware.vcenter.lcm_client.Notifications` or ``None`` :param issues: Lists of issues encountered during report creation. :class:`set` if any issues encountered. :type summary: :class:`InteropReport.ReportSummary` :param summary: A summary of the interoperability matrix. """ self.date_created = date_created self.target_product = target_product self.products = products self.issues = issues self.summary = summary VapiStruct.__init__(self) Report._set_binding_type(type.StructType( 'com.vmware.vcenter.lcm.discovery.interop_report.report', { 'date_created': type.DateTimeType(), 'target_product': type.ReferenceType(__name__, 'Product'), 'products': type.ListType(type.ReferenceType(__name__, 'InteropReport.ReportRow')), 'issues': type.OptionalType(type.ReferenceType('com.vmware.vcenter.lcm_client', 'Notifications')), 'summary': type.ReferenceType(__name__, 'InteropReport.ReportSummary'), }, Report, False, None)) class Result(VapiStruct): """ The ``InteropReport.Result`` class contains the result of interoperability report creation operation. .. tip:: The arguments are used to initialize data attributes with the same names. """ def __init__(self, report=None, csv_report=None, ): """ :type report: :class:`InteropReport.Report` :param report: The interoperability report. :type csv_report: :class:`str` or ``None`` :param csv_report: The identifier of CSV formatted interopability report. null provides location where the CSV report can be downloaded from based on the ``csvReport``. When clients pass a value of this class as a parameter, the attribute must be an identifier for the resource type: ``com.vmware.vcenter.lcm.report``. When methods return a value of this class as a return value, the attribute will be an identifier for the resource type: ``com.vmware.vcenter.lcm.report``. None in case of ``errors`` reported in :attr:`InteropReport.Report.issues`. """ self.report = report self.csv_report = csv_report VapiStruct.__init__(self) Result._set_binding_type(type.StructType( 'com.vmware.vcenter.lcm.discovery.interop_report.result', { 'report': type.ReferenceType(__name__, 'InteropReport.Report'), 'csv_report': type.OptionalType(type.IdType()), }, Result, False, None)) class Spec(VapiStruct): """ Configuration of report generation. .. tip:: The arguments are used to initialize data attributes with the same names. """ def __init__(self, target_version=None, ): """ :type target_version: :class:`str` :param target_version: The vCenter Server version. It is used for checking against the other products registered with that instance of vCenter Server. """ self.target_version = target_version VapiStruct.__init__(self) Spec._set_binding_type(type.StructType( 'com.vmware.vcenter.lcm.discovery.interop_report.spec', { 'target_version': type.StringType(), }, Spec, False, None)) def create_task(self, spec=None, ): """ Creates interoperability report between a vCenter Server release version and all registered products with the vCenter Server instance. The result of this operation can be queried by calling the null method where ``task`` is the response of this operation. :type spec: :class:`InteropReport.Spec` or ``None`` :param spec: Specifies the target version against this interoperability check report will be generated. If None the report will be generated for the currently installed version of the vCenter server. :rtype: :class: `vmware.vapi.stdlib.client.task.Task` :return: Task instance :raise: :class:`com.vmware.vapi.std.errors_client.Unauthenticated` if the user can not be authenticated. :raise: :class:`com.vmware.vapi.std.errors_client.Error` If there is some unknown internal error. The accompanying error message will give more details about the failure. """ task_id = self._invoke('create$task', { 'spec': spec, }) task_svc = Tasks(self._config) task_instance = Task(task_id, task_svc, type.ReferenceType(__name__, 'InteropReport.Result')) return task_instance class ProductCatalog(VapiInterface): """ The ``ProductCatalog`` class provides information which VMware products can be associated with vCenter Server. """ _VAPI_SERVICE_ID = 'com.vmware.vcenter.lcm.discovery.product_catalog' """ Identifier of the service in canonical form. """ def __init__(self, config): """ :type config: :class:`vmware.vapi.bindings.stub.StubConfiguration` :param config: Configuration to be used for creating the stub. """ VapiInterface.__init__(self, config, _ProductCatalogStub) self._VAPI_OPERATION_IDS =
feat1.name == feat2.name: combinations = [(dipole1, dipole2), (dipole2, dipole1)] for d1, d2 in combinations: dipole_grp1, dipole_atm1, dipole_type1 = d1 dipole_grp2, dipole_atm2, dipole_type2 = d2 # Model: A-N ... E-Y y_atm = dipole_grp2.atoms[1] if dipole_grp2.atoms[0] == dipole_atm2 else dipole_grp2.atoms[0] en_vect = dipole_atm1.coord - dipole_atm2.coord ey_vect = y_atm.coord - dipole_atm2.coord ney_angle = im.angle(en_vect, ey_vect) if (self.is_within_boundary(ney_angle, "min_ney_ang_multipolar_inter", ge) and self.is_within_boundary(ney_angle, "max_ney_ang_multipolar_inter", le)): elect_nb_coords = [nbi.coord for nbi in dipole_atm2.neighbors_info if nbi.atomic_num != 1] elect_normal = im.calc_normal(elect_nb_coords + [dipole_atm2.coord]) disp_angle = im.to_quad1(im.angle(elect_normal, en_vect)) if self.is_within_boundary(disp_angle, "max_disp_ang_multipolar_inter", le): # If the nucleophile has two atoms, then we will be able to calculate the angle between the vectors AN and EY. # This angle is necessary to define the orientation of the dipole. if len(dipole_grp1.atoms) == 2: # Model: A-N ... E-Y a_atm = dipole_grp1.atoms[1] if dipole_grp1.atoms[0] == dipole_atm1 else dipole_grp1.atoms[0] an_vect = dipole_atm1.coord - a_atm.coord # Angle between vectors AN and EY an_ey_vect_angle = im.angle(an_vect, ey_vect) params = {"ne_dist_multipolar_inter": ne_dist, "ney_ang_multipolar_inter": ney_angle, "disp_ang_multipolar_inter": disp_angle, "an_ey_ang_multipolar_inter": an_ey_vect_angle} if not dipole_type1 == dipole_type2: if self.is_within_boundary(an_ey_vect_angle, "max_an_ey_ang_para_multipolar_inter", le): inter = InteractionType(dipole_grp1, dipole_grp2, "Parallel multipolar", directional=True, params=params) interactions.append(inter) elif self.is_within_boundary(an_ey_vect_angle, "min_an_ey_ang_antipara_multipolar_inter", ge): inter = InteractionType(dipole_grp1, dipole_grp2, "Antiparallel multipolar", directional=True, params=params) interactions.append(inter) elif (self.is_within_boundary(an_ey_vect_angle, "min_an_ey_ang_ortho_multipolar_inter", ge) and self.is_within_boundary(an_ey_vect_angle, "max_an_ey_ang_ortho_multipolar_inter", le)): inter = InteractionType(dipole_grp1, dipole_grp2, "Orthogonal multipolar", directional=True, params=params) interactions.append(inter) else: inter = InteractionType(dipole_grp1, dipole_grp2, "Tilted multipolar", directional=True, params=params) interactions.append(inter) else: inter_type = "Unfavorable %s-%s" % (dipole_type1.lower(), dipole_type2.lower()) inter = InteractionType(dipole_grp1, dipole_grp2, inter_type, directional=True, params=params) interactions.append(inter) # Otherwise, ignore the angle AN and EY and add a general interaction (Multipolar) without a specific # definition of the orientation. It will happen only with Water molecules. else: params = {"ne_dist_multipolar_inter": ne_dist, "ney_ang_multipolar_inter": ney_angle, "disp_ang_multipolar_inter": disp_angle, "an_ey_ang_multipolar_inter": -1} inter_type = ("Multipolar" if not dipole_type1 == dipole_type2 else "Unfavorable %s-%s" % (dipole_type1.lower(), dipole_type2.lower())) inter = InteractionType(dipole_grp1, dipole_grp2, inter_type, directional=True, params=params) interactions.append(inter) return interactions @staticmethod def calc_xbond_pi(self, params): """Default method to calculate halogen bonds between halogens and aromatic rings. Parameters ---------- params : tuple of (:class:`~luna.mol.groups.AtomGroup`,\ :class:`~luna.mol.groups.AtomGroup`,\ :class:`~luna.mol.features.ChemicalFeature`,\ :class:`~luna.mol.features.ChemicalFeature`) The tuple follows the order (:math:`A`, :math:`B`, :math:`A_f`, :math:`B_f`), where :math:`A` and :math:`B` are two :class:`~luna.mol.groups.AtomGroup` objects, and :math:`A_f` and :math:`B_f` are their features (:class:`~luna.mol.features.ChemicalFeature` objects), respectively. Returns ------- : list """ if not self.add_non_cov: return [] group1, group2, feat1, feat2 = params interactions = [] if (feat1.name == "Aromatic" and feat2.name == "HalogenDonor"): donor_grp = group2 ring_grp = group1 else: donor_grp = group1 ring_grp = group2 # There are always just one donor/acceptor atom. donor_atm = donor_grp.atoms[0] # Interaction model: C-X ---- A # Defining the XA distance, in which A is the ring center xa_dist = im.euclidean_distance(donor_grp.centroid, ring_grp.centroid) if (self.is_within_boundary(xa_dist, "boundary_cutoff", le) and self.is_within_boundary(xa_dist, "max_xc_dist_xbond_inter", le)): ax_vect = donor_grp.centroid - ring_grp.centroid disp_angle = im.to_quad1(im.angle(ring_grp.normal, ax_vect)) if (self.is_within_boundary(disp_angle, "max_disp_ang_xbond_inter", le)): # Interaction model: C-X ---- A # XA vector is always the same xa_vect = ring_grp.centroid - donor_grp.centroid # Defining angle CXA, in which A is the ring center # It may happen that X is covalently bound to more than one group. # In such cases the halogen may also form more than one halogen bond. # Ref: <NAME> al. The Halogen Bond. (2016). carbon_coords = [nbi.coord for nbi in donor_atm.neighbors_info if nbi.atomic_num == 6] for c_coord in carbon_coords: xc_vect = c_coord - donor_grp.centroid cxa_angle = im.angle(xc_vect, xa_vect) if (self.is_within_boundary(cxa_angle, "min_cxa_ang_xbond_inter", ge)): params = {"xc_dist_xbond_inter": xa_dist, "disp_ang_xbond_inter": disp_angle, "cxa_ang_xbond_inter": cxa_angle} inter = InteractionType(donor_grp, ring_grp, "Halogen-pi", directional=True, params=params) interactions.append(inter) return interactions @staticmethod def calc_xbond(self, params): """Default method to calculate halogen bonds. Parameters ---------- params : tuple of (:class:`~luna.mol.groups.AtomGroup`,\ :class:`~luna.mol.groups.AtomGroup`,\ :class:`~luna.mol.features.ChemicalFeature`,\ :class:`~luna.mol.features.ChemicalFeature`) The tuple follows the order (:math:`A`, :math:`B`, :math:`A_f`, :math:`B_f`), where :math:`A` and :math:`B` are two :class:`~luna.mol.groups.AtomGroup` objects, and :math:`A_f` and :math:`B_f` are their features (:class:`~luna.mol.features.ChemicalFeature` objects), respectively. Returns ------- : list """ if not self.add_non_cov: return [] group1, group2, feat1, feat2 = params interactions = [] if len(group1.atoms) != 1 or len(group2.atoms) != 1: logger.warning("One or more invalid atom groups were informed: %s and %s. In halogen bonds, halogen donor " "and acceptor groups should always contain only one atom." % (group1, group2)) return [] if (feat1.name == "Acceptor" and feat2.name == "HalogenDonor"): donor_grp = group2 acceptor_grp = group1 else: donor_grp = group1 acceptor_grp = group2 # There are always just one donor/acceptor atom. donor_atm = donor_grp.atoms[0] acceptor_atm = acceptor_grp.atoms[0] # Interaction model: C-X ---- A-R # Distance XA. xa_dist = im.euclidean_distance(donor_grp.centroid, acceptor_grp.centroid) if (self.is_within_boundary(xa_dist, "boundary_cutoff", le) and self.is_within_boundary(xa_dist, "max_xa_dist_xbond_inter", le)): # Interaction model: C-X ---- A-R # XA vector is always the same xa_vect = acceptor_grp.centroid - donor_grp.centroid # Defining the angle CXA # It may happen that X is covalently bound to more than one group. # In such cases the halogen may also form more than one halogen bond. # Ref: <NAME>. et al. The Halogen Bond. (2016). carbon_coords = [nbi.coord for nbi in donor_atm.neighbors_info if nbi.atomic_num == 6] # Interaction model: C-X ---- A-R. # R coordinates, in which R is a heavy atom. r_coords = [nbi.coord for nbi in acceptor_atm.neighbors_info if nbi.atomic_num != 1] for c_coord in carbon_coords: xc_vect = c_coord - donor_grp.centroid cxa_angle = im.angle(xc_vect, xa_vect) if self.is_within_boundary(cxa_angle, "min_cxa_ang_xbond_inter", ge): # If no heavy atom is bonded to the acceptor, it means that only hydrogens may be bound to it. Then, we do not # calculate the angles because hydrogens are too dynamic, i.e., the acceptor could be ionized or not at a # specific moment in time and its hydrogens may be positioned in different ways. if len(r_coords) == 0: params = {"xa_dist_xbond_inter": xa_dist, "cxa_ang_xbond_inter": cxa_angle, "xar_ang_xbond_inter": -1} inter = InteractionType(donor_grp, acceptor_grp, "Halogen bond", directional=True, params=params) interactions.append(inter) else: # AX vector is always the same. # Obs: the donor_grp is the Halogen (X). ax_vect = donor_grp.centroid - acceptor_grp.centroid lowest_xar_angle = None for r_coord in r_coords: ar_vect = r_coord - acceptor_grp.centroid xar_angle = im.angle(ax_vect, ar_vect) # Update the XAR angle with the lowest value. if lowest_xar_angle is None or xar_angle < lowest_xar_angle: lowest_xar_angle = xar_angle # The angle will be None when any R (heavy atom) atom was found. # In this case, the criteria must always fail. if lowest_xar_angle is None: lowest_xar_angle = -1 if self.is_within_boundary(lowest_xar_angle, "min_xar_ang_xbond_inter", ge): params = {"xa_dist_xbond_inter": xa_dist, "cxa_ang_xbond_inter": cxa_angle, "xar_ang_xbond_inter": lowest_xar_angle} inter = InteractionType(donor_grp, acceptor_grp, "Halogen bond", directional=True, params=params) interactions.append(inter) return interactions @staticmethod def calc_chalc_bond(self, params): """Default method to calculate chalcogen bonds. Parameters ---------- params : tuple of (:class:`~luna.mol.groups.AtomGroup`,\ :class:`~luna.mol.groups.AtomGroup`,\ :class:`~luna.mol.features.ChemicalFeature`,\ :class:`~luna.mol.features.ChemicalFeature`) The tuple follows the order (:math:`A`, :math:`B`, :math:`A_f`, :math:`B_f`), where :math:`A` and :math:`B` are two :class:`~luna.mol.groups.AtomGroup` objects, and :math:`A_f` and :math:`B_f` are their features (:class:`~luna.mol.features.ChemicalFeature` objects), respectively. Returns ------- : list """ if not self.add_non_cov: return [] group1, group2, feat1, feat2 = params interactions = [] if len(group1.atoms) != 1 or len(group2.atoms) != 1: logger.warning("One or more invalid atom groups were informed: %s and %s. In chalcogen bonds, chalcogen donor " "and acceptor groups should always contain only one atom." % (group1, group2)) return [] if (feat1.name == "Acceptor" and feat2.name == "ChalcogenDonor"): donor_grp = group2 acceptor_grp = group1 else: donor_grp = group1 acceptor_grp = group2 # There are always just one donor/acceptor atom. donor_atm = donor_grp.atoms[0] acceptor_atm = acceptor_grp.atoms[0] # Interaction model: R-Y --- A-N # Distance YA. ya_dist = im.euclidean_distance(donor_grp.centroid, acceptor_grp.centroid) if (self.is_within_boundary(ya_dist, "boundary_cutoff", le) and self.is_within_boundary(ya_dist, "max_ya_dist_ybond_inter", le)): # Interaction model: R-Y --- A-N # YA vector is always the same ya_vect = acceptor_grp.centroid - donor_grp.centroid # Defining the angle RYA r_atms = [nbi for nbi in donor_atm.neighbors_info if nbi.atomic_num != 1] r_elems = sorted([nbi.atomic_num for nbi in donor_atm.neighbors_info if nbi.atomic_num != 1]) # Isothiazoles have only one sigma-hole located on the oposite site of the N. # Therefore, we should only evaluate this sigma-hole by ignoring the angle formed with the carbon. # Beno et al (2015). DOI: https://doi.org/10.1021/jm501853m. ignore_carbon = False if len(r_elems) == 2 and r_elems[0] == 6 and r_elems[1] == 7: ignore_carbon
obj and 'value' in obj: return { 'encoding': 'escape', 'value': {_json_key(k): to_reversible_json_structure(v) for k, v in obj.items()}, } else: return {_json_key(k): to_reversible_json_structure(v) for k, v in obj.items()} # We do not use "is_sequence" because we do not want to convert all sequences, # because it can be loosing important information. elif isinstance(obj, (tuple, list)): return [to_reversible_json_structure(v) for v in obj] else: return { 'encoding': 'pickle', 'description': str(obj), 'value': base64.b64encode(pickle.dumps(obj)).decode('utf8'), } def from_reversible_json_structure(obj: typing.Any) -> typing.Any: if is_instance(obj, typing.Union[str, int, float, bool, NONE_TYPE]): return obj elif isinstance(obj, typing.Mapping): if 'encoding' in obj and 'value' in obj: if obj['encoding'] == 'pickle': # TODO: Limit the types of values being able to load to prevent arbitrary code execution by a malicious pickle. return pickle.loads(base64.b64decode(obj['value'].encode('utf8'))) if obj['encoding'] == 'escape': return {_json_key(k): from_reversible_json_structure(v) for k, v in obj['value'].items()} else: raise ValueError("Unsupported encoding '{encoding}'.".format(encoding=obj['encoding'])) else: return {_json_key(k): from_reversible_json_structure(v) for k, v in obj.items()} # We do not use "is_sequence" because we do not want to convert all sequences, # because it can be loosing important information. elif isinstance(obj, (tuple, list)): return [from_reversible_json_structure(v) for v in obj] else: raise TypeError("Unsupported type '{value_type}'.".format(value_type=type(obj))) class StreamToLogger: def __init__(self, logger: logging.Logger, level: typing.Union[str, int], pass_through_stream: typing.TextIO = None) -> None: self.logger = logger self.level = logging._checkLevel(level) # type: ignore self.pending_line = "" self.closed = False self.pass_through_stream = pass_through_stream # Here we are trying to test for the case of a recursive loop which can happen # if you are using "logging.StreamHandler" in your logging configuration (e.g., to # output logging to a console) and configure it after "redirect_to_logging' context # manager has been entered. def _check_recursion(self) -> bool: # We start at "2" so that we start from outside of this file. frame = sys._getframe(2) line_number = None try: i = 0 # If loop is happening, it is generally looping inside less than 10 frames, # so we exit after 20 frames (just to make sure, all these values are ballpark # values) to optimize. while frame and i < 20: if frame.f_code.co_filename == __file__: # The first (in fact the last from call perspective) time we are # in this file. if line_number is None: line_number = frame.f_lineno # If we were in the same file and line already higher in the stack, # we are in a recursive loop. elif line_number == frame.f_lineno: return True frame = frame.f_back i += 1 finally: del frame return False def write(self, buffer: str) -> int: if self.closed: raise ValueError("Stream is closed.") if self._check_recursion(): # We are being called by a logger in a recursive loop. Because this message has already been logged, # it is safe for us to just drop it to break a recursive loop. return 0 # We only write complete lines to the logger. Any incomplete line will be saved to "pending_line", and flushed # if "flush" is called or the context manager is closed. bytes_written = 0 lines = (self.pending_line + buffer).split('\n') # Since we split on "\n", the last string in the list of lines will be an empty string if the last character # in the buffer is a newline, which is what we want in this case as it resets the "pending_line" to empty. # Otherwise the last string in the list of lines are characters after the last "\n", which is again what we # want, setting the "pending_line" to characters not logged this time. self.pending_line = lines[-1] for line in lines[:-1]: # Whitespace lines should not be logged. if line.strip(): self.logger.log(self.level, line.rstrip()) bytes_written += len(line) if self.pass_through_stream is not None: self.pass_through_stream.write(buffer) return bytes_written def writelines(self, lines: typing.List[str]) -> None: if self.closed: raise ValueError("Stream is closed.") if self._check_recursion(): # We are being called by a logger in a recursive loop. Because this message has already been logged, # it is safe for us to just drop it to break a recursive loop. return for line in lines: if line.strip(): self.logger.log(self.level, line.rstrip()) if self.pass_through_stream is not None: if hasattr(self.pass_through_stream, 'writelines'): self.pass_through_stream.writelines(lines) else: for line in lines: self.pass_through_stream.write(line) def flush(self) -> None: if self.closed: raise ValueError("Stream is closed.") if self.pending_line.strip(): self.logger.log(self.level, self.pending_line.rstrip()) if self.pass_through_stream is not None: self.pass_through_stream.flush() def close(self) -> None: if self.closed: return if self.pending_line.strip(): self.logger.log(self.level, self.pending_line.rstrip()) self.closed = True def seekable(self) -> bool: return False def seek(self, offset: int, whence: int = 0) -> int: raise OSError("Stream is not seekable.") def tell(self) -> int: raise OSError("Stream is not seekable.") def truncate(self, size: int = None) -> int: raise OSError("Stream is not seekable.") def writable(self) -> bool: return True def isatty(self) -> bool: return False def readable(self) -> bool: return False def read(self, n: int = -1) -> typing.AnyStr: raise OSError("Stream is write-only.") def readline(self, limit: int = -1) -> typing.AnyStr: raise OSError("Stream is write-only.") def readlines(self, hint: int = -1) -> typing.List[typing.AnyStr]: raise OSError("Stream is write-only.") def fileno(self) -> int: raise OSError("Stream does not use a file descriptor.") class redirect_to_logging(contextlib.AbstractContextManager): """ A Python context manager which redirects all writes to stdout and stderr to Python logging. Primitives should use logging to log messages, but maybe they are not doing that or there are other libraries they are using which are not doing that. One can then use this context manager to assure that (at least all Python) writes to stdout and stderr by primitives are redirected to logging:: with redirect_to_logging(logger=PrimitiveClass.logger): primitive = PrimitiveClass(...) primitive.set_training_data(...) primitive.fit(...) primitive.produce(...) """ # These are class variables to ensure that they are shared among all instances. # We use a list to make this context manager re-entrant. _old_stdouts: typing.List[typing.TextIO] = [] _old_stderrs: typing.List[typing.TextIO] = [] def __init__(self, logger: logging.Logger = None, stdout_level: typing.Union[int, str] = 'INFO', stderr_level: typing.Union[int, str] = 'ERROR', pass_through: bool = True) -> None: if logger is None: self.logger = logging.getLogger('redirect') else: self.logger = logger self.stdout_level = logging._checkLevel(stdout_level) # type: ignore self.stderr_level = logging._checkLevel(stderr_level) # type: ignore self.pass_through = pass_through def __enter__(self) -> logging.Logger: self._old_stdouts.append(sys.stdout) self._old_stderrs.append(sys.stderr) if self.pass_through: stdout_pass_through = self._old_stdouts[0] stderr_pass_through = self._old_stderrs[0] else: stdout_pass_through = None stderr_pass_through = None sys.stdout = typing.cast(typing.TextIO, StreamToLogger(self.logger, self.stdout_level, stdout_pass_through)) sys.stderr = typing.cast(typing.TextIO, StreamToLogger(self.logger, self.stdout_level, stderr_pass_through)) return self.logger def __exit__(self, exc_type: typing.Optional[typing.Type[BaseException]], exc_value: typing.Optional[BaseException], traceback: typing.Optional[types.TracebackType]) -> typing.Optional[bool]: sys.stdout.close() sys.stderr.close() sys.stdout = self._old_stdouts.pop() sys.stderr = self._old_stderrs.pop() return None class CallbackHandler(logging.Handler): """ Calls a ``callback`` with logging records as they are without any conversion except for: * formatting the logging message and adding it to the record object * assuring ``asctime`` is set * converts exception ``exc_info`` into exception's name * making sure ``args`` are JSON-compatible or removing it * making sure there are no null values """ def __init__(self, callback: typing.Callable) -> None: super().__init__(logging.DEBUG) self.callback = callback def emit(self, record: logging.LogRecord) -> None: try: self.callback(self.prepare(record)) except Exception: self.handleError(record) def prepare(self, record: logging.LogRecord) -> typing.Dict: self.format(record) # If "asctime" is not set, we do it ourselves. if not hasattr(record, 'asctime'): if self.formatter: fmt = self.formatter else: fmt = logging._defaultFormatter # type: ignore record.asctime = fmt.formatTime(record, fmt.datefmt) output = copy.copy(record.__dict__) # Exceptions are not JSON compatible. if 'exc_info' in output: if output['exc_info']: if isinstance(output['exc_info'], BaseException): output['exc_type'] = type_to_str(type(output['exc_info'])) else: output['exc_type'] = type_to_str(type(output['exc_info'][1])) del output['exc_info'] if 'args' in output: try: output['args'] = to_json_structure(output['args']) except Exception: # We assume this means "args" is not JSON compatible. del output['args'] # We iterate over a list so that we can change dict while iterating. for key, value in list(output.items()): if value is None: del output[key] return output def _called_from_outside(modules: typing.Sequence[types.ModuleType]) -> bool: # 0 == this function, 1 == wrapper, 2 == caller frame = sys._getframe(2) try: if not frame: caller_module_name = None else: caller_module_name = frame.f_globals.get('__name__', None) finally: del frame return all(caller_module_name != module.__name__ for module in modules) def _decorate_all_methods(modules: typing.Sequence[types.ModuleType], src_obj: typing.Any, dst_obj: typing.Any, decorator: typing.Callable, ignore: typing.Set) -> None: for name, function in inspect.getmembers(src_obj): if name.startswith('_'): continue if name in ignore: continue # Wrap
import csv import numpy as np import copy # based on python documentation on how to # copy lists import sys import pickle from scipy.io import arff class Node: def __init__(self, children, splitFeature, splitChildren, output, label = None, depth = 0): self.children = children self.splitFeature = splitFeature self.splitChildren = splitChildren self.output = output self.label = label self.depth = depth # getCategoryProportions takes in a column of data and # returns a dictionary of lists of indices paired with the # proportion that the category shows up in the data def getCategoryProportions(colData): categoryDict = dict() for i in range(len(colData)): if (categoryDict.get(colData[i]) is None): categoryDict[colData[i]] = [[i],1] else: indices = categoryDict[colData[i]][0] numPerClass = categoryDict[colData[i]][1] categoryDict[colData[i]] = [indices+[i],numPerClass+1] # classDict is a dictionary containing categories as keys # and the values are two-element lists where the first element is # the list of indices where that category exists and the second # element is the proportion of the category in the column of data outputClasses = [] for key in categoryDict: outputClasses.append(key) categoryDict[key] = [categoryDict[key][0], float(categoryDict[key][1])/len(colData)] return categoryDict, outputClasses class DecisionTree(object): def __init__(self, trainFile, testFile, maxDepth, trainOutputLabels, testOutputLabels, metricsOutput): (self.trainData, self.attributes, self.outputAttribute) = self.getData(trainFile) self.outputClasses = list(getCategoryProportions(\ self.trainData[self.outputAttribute])[0].keys()) (self.testData,_,_) = self.getData(testFile) # testData presumed to # have same attributes as trainData. self.maxDepth = maxDepth self.trainOutputLabels = trainOutputLabels self.testOutputLabels = testOutputLabels self.metricsOutput = metricsOutput # getData takes in filename to turn the csv into a dictionary # containing column names containing the corresponding # column lists with the data. def getData(self,filename): #dataRows = csv.reader(open(filename), delimiter = "\t") dataframe,metadata = arff.loadarff(filename) data = dict() rowIndex = 0 attributes = metadata._attrnames for att in attributes: data[att] = [] for row in dataframe: for i in range(len(row)): data[attributes[i]].append(row[i]) return data,attributes[:-1],attributes[-1] # majorityVote behaves similarly to majorityVote in inspection.py # It creates a dictionary and gets the category in the data # with the greatest count. def majorityVote(self,data): countDict = dict() for val in data: if (countDict.get(val) is None): countDict[val] = 1 else: countDict[val] += 1 maxCount = -1 maxClass = None for key,count in countDict.items(): if (count > maxCount): maxCount = count maxClass = key elif (count == maxCount): if (maxClass is not None and key > maxClass): maxClass = key return maxClass # getEntropy behaves in the same way as the getEntropy function in # inspection.py but takes in a colData argument because the data # will gradually dwindle down as the tree is further split. # getEntropy is akin to H(Y) in the calculation of mutual information. # getEntropy uses numpy to take the log of base 2 of probabilities # - numpy np.log2 based on documentation def getEntropy(self,colData): classDict,_ = getCategoryProportions(colData) entropy = 0 for key in classDict: prob = classDict[key][1] # proportion of class with name key if (prob != 0): entropy += prob*np.log2(prob) return -1*entropy # getCondEntropy takes in an attribute "X" and data dictionary # that is a dictionary of features (columns) associated with # lists that represent column data aand returns the conditional # entropy. It's the sum of the product between the proportion of # a category of attribute "X" and the entropy of output "Y" conditioned # on those associated with "X" values of only that category. def getCondEntropy(self,attribute,data): attributeCategories,_ = getCategoryProportions(data[attribute]) condEntropy = 0 outputCol = data[self.outputAttribute] # assuming output column # always being at the end condEntropy = 0 for category in attributeCategories: indices = attributeCategories[category][0] outputCond = [] for index in indices: outputCond.append(outputCol[index]) entropyYCondX = self.getEntropy(outputCond) condEntropy += attributeCategories[category][1]*entropyYCondX return condEntropy # getMutualInformation takes an attribute and data dictionary # and returns the mutual information by definition I(Y;X)=H(Y)-H(Y|X) def getMutualInformation(self,attribute,data): return self.getEntropy(data[self.outputAttribute])-\ self.getCondEntropy(attribute,data) # getPartition is responsible for the splitting process in the decision # tree. def getPartition(self,data,indices): partitionData = copy.deepcopy(data) # avoid aliasing while modifying for column in partitionData: newColData = [] for index in indices: # extract only the indices that are # partitioned per column for the data newColData.append(partitionData[column][index]) partitionData[column] = newColData return partitionData # makeDecisionTree calls makeDecisionTree' to modify # the self.decisionTree model that it builds up. def makeDecisionTree(self): # assuming input for inputData inputData = copy.deepcopy(self.trainData) # using python documentation # on shallow and deep copy operations - to modify self.trainData # reference # initializes the root root = Node(children=[],splitFeature=None, splitChildren=[], output=inputData[self.outputAttribute], depth=0) # to later be modified self.decisionTree = self.makeDecisionTree_(root,inputData,0, self.maxDepth) # makeDecisionTree' recursively calls itself to build the self.decisionTree def makeDecisionTree_(self,currNode,inputData,depth,maxDepth): outputCol = inputData[self.outputAttribute] outputClasses,_ = getCategoryProportions(outputCol) # No data if (len(outputCol) == 0): return Node(label=None,children=[],splitFeature=None, splitChildren=[], output=inputData[self.outputAttribute], depth=depth) # One class if (len(outputClasses) == 1): return Node(label=list(outputClasses.keys())[0], children=[], splitFeature=None, splitChildren=[], output=inputData[self.outputAttribute], depth=depth) # depth already at maximum if (depth >= maxDepth): return Node(label=self.majorityVote(outputCol), children=[], splitFeature=None,splitChildren=[], output=inputData[self.outputAttribute], depth=depth) else: # otherwise, split on feature that reduces uncertainty the # most. Highest mutual information. maxMutualInformation = 0 bestAttribute = None for attribute in self.attributes: mutualInfo = self.getMutualInformation(attribute,inputData) if (mutualInfo > maxMutualInformation): # selecting the first # feature with "equal" mutual information to break ties maxMutualInformation = mutualInfo bestAttribute = attribute if (maxMutualInformation == 0): return Node(label=self.majorityVote(outputCol), children=[],splitFeature=None, splitChildren=[], output=inputData[self.outputAttribute], depth=depth) propsAndIndices,_ = \ getCategoryProportions(inputData[bestAttribute]) bestAttributeCategories = list(propsAndIndices.keys()) splitChildrenList = [] childrenList = [] for i in range(len(bestAttributeCategories)): childrenList.append(None) splitChildrenList.append(bestAttributeCategories[i]) currNode = Node(label=None,children=childrenList, splitFeature=bestAttribute, splitChildren=splitChildrenList, output=inputData[self.outputAttribute], depth = depth) for j in range(len(bestAttributeCategories)): currNode.children[j] = self.makeDecisionTree_(\ currNode.children[j], self.getPartition(inputData, propsAndIndices[splitChildrenList[j]][0]), depth+1,maxDepth) return currNode # getClassCounts takes in a tree node and behaves as a helper # function for printTree in obtaining the number of observations # per category and returns the correct string to display in the # tree. def getClassCounts(self,node): categoryProps,_ = getCategoryProportions(node.output) numPerCategory = dict() row = "[" for i in range(len(self.outputClasses)): if (self.outputClasses[i] in categoryProps): row += str(len(categoryProps[self.outputClasses[i]][0])) else: row += "0" row += " " + self.outputClasses[i] + \ ("/" if i < len(self.outputClasses)-1 else "]") return row # printTree copies the decision tree in the class and initially # prints the proportion def printTree(self): root = copy.deepcopy(self.decisionTree) counts = self.getClassCounts(root) print(counts) self.printTree_(root) def printTree_(self,root): for i in range(len(root.children)): row = "| "*(root.children[i].depth) row += (root.splitFeature + " = " + \ root.splitChildren[i] + ": " \ if root.splitFeature != None else "") row += self.getClassCounts(root.children[i]) print(row) if (not self.isLeaf(root.children[i])): self.printTree_(root.children[i]) # returns whether a tree node is a leaf: doesn't have any children def isLeaf(self,T): return T.children == [] # plinkoDownModel takes in an observation and # classifies the observation by taking plinkoing # the observation down each branch that is associated # with a specific category that an attribute takes on def plinkoDownModel(self,observation,root): if (self.isLeaf(root)): return root.label, root.output category = observation[root.splitFeature] for i in range(len(root.children)): if root.splitChildren[i] == category: return self.plinkoDownModel(observation,root.children[i]) return None, root.output # getErrorRate takes in two lists and returns the mismatch # rate between the corresponding elements def getErrorRate(self,L1,L2): mismatches = 0 for i in range(len(L1)): if (L1[i] != L2[i]): mismatches += 1 return float(mismatches)/len(L1) # writeToTrain is a helper function that getLabels uses to get the # training labels predicted. writeToTrain writes to a training output # file and returns a list of predicted training labels. def writeToTrain(self,write,columns,decisionModel): trainPredicted = [] if write: trainOutputLabels = open(self.trainOutputLabels,"w") for i in range(len(self.trainData[columns[0]])): observation = dict() for key in self.trainData: observation[key] = self.trainData[key][i] outcome,output = self.plinkoDownModel(observation,decisionModel) if write: if outcome is not None: trainOutputLabels.write(outcome) else: trainOutputLabels.write(self.majorityVote(output)) trainPredicted.append(outcome) if (write and i != len(self.trainData[columns[0]])-1): trainOutputLabels.write("\n") if write: trainOutputLabels.close() return trainPredicted # writeToTest is a helper function that getLabels calls and takes # in the argument columns, which are the columns of the input data. # the length of a column is iterated over (assuming an equal number # of rows per column). writeToTest returns a list of test labels # based off the decision tree predictions. It also writes to a test output # file that contains all the labels. def writeToTest(self,write,columns,decisionModel): testPredicted = [] if write: testOutputLabels = open(self.testOutputLabels,"w") for j in range(len(self.testData[columns[0]])): observation = dict()
return "It's too dark to see anything." return f"I don't see any {noun} here." if scope == "knows": return f"You don't know of any {noun}." elif scope == "direction": return f"{noun.capitalize()} is not a direction I recognize." return f"You don't have any {noun}." def getThing(self, noun_adj_arr, scope, far_obj, obj_direction): """ Get the Thing object in range associated with a list of adjectives and a noun Takes arguments noun_adj_array, a list of strings referring to an in game item, taken from the player command, and scope, a string specifying the range of the verb Called by self.callVerb Returns a single Thing object (thing.py) or None """ adj_disambig_candidates = [] for item in self.previous_command.things: if noun_adj_arr[-1] in item.adjectives: adj_disambig_candidates.append(item) thing = self.checkAdjectives( noun_adj_arr + [item.name], item.name, [item], scope, far_obj, obj_direction, ) if thing: adj_disambig_candidates.append(thing) t_ix = self.getDisambigIndexFromCommand() noun = noun_adj_arr[-1] # get list of associated Things if noun in self.game.nouns: things = list(self.game.nouns[noun]) elif self.previous_command.things and adj_disambig_candidates: # assume tokens are adjectives for a Thing from the previous command noun = self.previous_command.ambig_noun if noun: noun_adj_arr.append(noun) things = adj_disambig_candidates elif t_ix and t_ix < len(self.previous_command.tokens): # assume tokens are adjectives for a Thing from the previous command return self.previous_command.things[t_ix - 1] else: things = [] if not things: raise ObjectMatchError(self.generateVerbScopeErrorMsg(scope, noun_adj_arr)) thing = self.checkAdjectives( noun_adj_arr, noun, things, scope, far_obj, obj_direction ) if not thing: raise ObjectMatchError(self.generateVerbScopeErrorMsg(scope, noun_adj_arr)) return thing def getDisambigIndexFromCommand(self): if len(self.command.tokens) != 1: return None try: return int(self.command.tokens[-1]) except ValueError: return None def verboseNamesMatch(self, things): """ Check if any of the potential grammatical objects have identical verbose names Takes the list of things associated with the direct or indirect object Returns a list of two items: Item one is True if duplicates are present, else False Item two is dictionary mapping verbose names to lists of Things from the input with that name """ duplicates_present = False name_dict = {} for item in things: if item.verbose_name in name_dict: name_dict[item.verbose_name].append(item) else: name_dict[item.verbose_name] = [item] for name in name_dict: if len(name_dict[name]) > 1: duplicates_present = True break return [duplicates_present, name_dict] def locationsDistinct(self, things): """ Check if identically named items can be distinguished by their locations Takes a list of items to check Returns False if all locations are the same, True otherwise """ locs = [item.location for item in things] return not locs.count(locs[1]) == len(locs) def _disambigMsgNextJoiner(self, item, name_dict, name, unscanned): if item is name_dict[name][-1] and not len(unscanned): return "?" if ( item is name_dict[name][-1] and len(unscanned) == 1 and len(name_dict[unscanned[0]]) == 1 ): return ", or " if len(name_dict[name]) == 1: return ", " if item is name_dict[name][-2] and not len(unscanned): return ", or " return ", " def _itemWithDisambigIndex(self, item, ix, location=None): msg = item.lowNameArticle(True) if isinstance(location, Room): location = location.floor if location == self.game.me: msg += " in your inventory" elif location: msg += f" {location.contains_preposition} {location.lowNameArticle(True)}" return msg + f" ({ix + 1})" def _disambigMsgNextItem(self, item, name_dict, name, unscanned, ix, location=None): return self._itemWithDisambigIndex( item, ix, location ) + self._disambigMsgNextJoiner(item, name_dict, name, unscanned) def _generateDisambigMsg(self, things, msg): """ Generate the disambiguation message for a list of things """ name_match = self.verboseNamesMatch(things) # dictionary of verbose_names from the current set of things name_dict = name_match[1] scanned_keys = [] if not name_match[0]: for thing in things: msg += self._itemWithDisambigIndex(thing, things.index(thing)) if thing is things[-1]: msg += "?" elif len(things) > -2 and thing is things[-2]: msg += ", or " else: msg += ", " return msg things = [] # empty things to reorder elements according to the order printed, # since we are using name_dict for name in name_dict: # use name_dict for disambiguation message composition rather than things scanned_keys.append(name) unscanned = list(set(name_dict.keys()) - set(scanned_keys)) if len(name_dict[name]) > 1: if self.locationsDistinct(name_dict[name]): for item in name_dict[name]: things.append(item) loc = item.location if not loc: pass msg += self._disambigMsgNextItem( item, name_dict, name, unscanned, things.index(item), loc ) return msg for item in name_dict[name]: things.append(item) msg += self._disambigMsgNextItem( item, name_dict, name, unscanned, things.index(item) ) return msg for item in name_dict[name]: things.append(item) msg += self._disambigMsgNextItem( item, name_dict, name, unscanned, things.index(item) ) return msg return msg def checkAdjectives( self, noun_adj_arr, noun, things, scope, far_obj, obj_direction ): """ If there are multiple Thing objects matching the noun, check the adjectives to narrow down to exactly 1 Takes arguments self.game.app, noun_adj_arr, a list of strings referring to an in game item, taken from the player command,noun (string), things, a list of Thing objects (things.py) that are candidates for the target of the player's action, and scope, a string specifying the range of the verb Returns a single Thing object or None """ if things == self.previous_command.things: try: n_select = int(noun_adj_arr[0]) except ValueError: n_select = None if n_select is not None and n_select <= len(things): n_select = n_select - 1 return things[n_select] if noun: adj_i = noun_adj_arr.index(noun) - 1 else: adj_i = len(noun_adj_arr) - 1 not_match = [] while adj_i >= 0 and len(things) > 1: # check preceding word as an adjective for thing in things: if noun_adj_arr[adj_i] not in thing.adjectives: not_match.append(thing) for item in not_match: if item in things: things.remove(item) adj_i = adj_i - 1 things = self.checkRange(things, scope) if len(things) == 1 and things[0].far_away and not far_obj: self.game.addTextToEvent( "turn", (things[0].getArticle(True) + things[0].verbose_name).capitalize() + " is too far away. ", ) return False elif len(things) > 1 and not far_obj: remove_far = [] for item in things: if item.far_away: remove_far.append(item) if len(things) > len(remove_far): for item in remove_far: things.remove(item) if len(things) > 1 and obj_direction: remove_wrong = [] for item in things: if item.direction: if item.direction != obj_direction: remove_wrong.append(item) if len(things) > len(remove_wrong): for item in remove_wrong: if item in things: things.remove(item) if len(things) > 1: remove_child = [] for item in things: if item.is_composite: for item2 in things: if item2 in item.children: remove_child.append(item2) if len(things) > len(remove_child): for item in remove_child: if item in things: things.remove(item) if len(things) == 1: return things[0] if len(things) == 0: return None if len(things) > 1: if len(set([thing.ix for thing in things])) == 1: loc = things[0].location same_loc = True for thing in things: if thing.location is not loc: same_loc = False if same_loc: return things[0] msg = self._generateDisambigMsg(things, "Do you mean ") # turn ON disambiguation mode for next turn self.command.ambiguous = True self.command.ambig_noun = noun self.command.things = things raise ObjectMatchError(msg) def _prepareGrammarObjects(self): self.getObjectTargets() self.checkComponentObjects() self.resolveGrammarObjLocations() def callVerb(self): """ Gets the Thing objects (if any) referred to in the player command, then calls the verb function Returns a Boolean, True if a verb function is successfully called, False otherwise """ if self.command.verb.hasDobj and self.command.verb.hasIobj: if ( self.command.verb.dscope != "inv" or self.command.verb.iscope != "inv" ) and self.game.me.position != "standing": StandUpVerb().verbFunc(self.game) self.command.verb().verbFunc( self.game, self.command.dobj.target, self.command.iobj.target ) elif self.command.verb.hasDobj: if ( self.command.verb.dscope != "inv" and self.command.verb.dscope != "invflex" and self.game.me.position != "standing" ): StandUpVerb().verbFunc(self.game) self.command.verb().verbFunc(self.game, self.command.dobj.target) elif self.command.verb.hasIobj: if ( self.command.verb.iscope != "inv" and self.command.verb.iscope != "invflex" and self.game.me.position != "standing" ): StandUpVerb().verbFunc(self.game) self.command.verb().verbFunc(self.game, self.command.iobj.target) else: self.command.verb().verbFunc(self.game) return True def disambig(self): """ When disambiguation mode is active, use the player input to specify the target for the previous turn's ambiguous command called by self.parseInput Returns a Boolean, True if disambiguation """ self.command.dobj = self.previous_command.dobj self.command.iobj = self.previous_command.iobj self.command.verb = self.previous_command.verb if not self.command.dobj.target and self.command.verb.hasDobj: self.command.dobj.tokens = self.command.tokens elif not self.command.iobj.target and self.command.verb.hasIobj: self.command.iobj.tokens = self.command.tokens self._prepareGrammarObjects() self.callVerb() def checkComponentObjects(self): """ Check if any of the identified objects have subcomponents that are better candidates as objects of the current verb. """ dobj = self._checkComponentObject("dobj", self.command.dobj.target) iobj = self._checkComponentObject("iobj", self.command.iobj.target) if dobj and self.command.dobj and dobj != self.command.dobj.target: self.game.addTextToEvent( "turn", "(Assuming " + dobj.lowNameArticle(True) + ".)", ) self.command.dobj.target = dobj if iobj and self.command.iobj and iobj != self.command.iobj.target: self.game.addTextToEvent( "turn", "(Assuming " + iobj.lowNameArticle(True) + ".)", ) self.command.iobj.target = iobj def _checkComponentObject(self, which_obj, obj): """ Check if the given object has a subcomponent that
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import numpy as np import math import onnx from onnx import helper, TensorProto, mapping import torch import torchvision import topi import topi.testing import tvm from tvm import te from tvm import relay from tvm.contrib import graph_runtime from tvm.relay.testing.config import ctx_list import scipy def get_input_data_shape_dict(graph_def, input_data): if isinstance(input_data, list): input_names = {} shape_dict = {} for i, _ in enumerate(input_data): input_names[i] = graph_def.graph.input[i].name shape_dict[input_names[i]] = input_data[i].shape else: input_names = graph_def.graph.input[0].name shape_dict = {input_names: input_data.shape} return input_names, shape_dict def get_tvm_output_with_vm(graph_def, input_data, target, ctx, opset=None): """ Generic function to execute and get tvm output with vm executor""" _, shape_dict = get_input_data_shape_dict(graph_def, input_data) mod, params = relay.frontend.from_onnx(graph_def, shape_dict, opset=opset) ex = relay.create_executor('vm', mod=mod, ctx=ctx, target=target) indata = tvm.nd.array(input_data) result = ex.evaluate()(indata) return result.asnumpy() def get_tvm_output(graph_def, input_data, target, ctx, output_shape=None, output_dtype='float32', opset=None): """ Generic function to execute and get tvm output""" target = 'llvm' input_names, shape_dict = get_input_data_shape_dict(graph_def, input_data) mod, params = relay.frontend.from_onnx(graph_def, shape_dict, opset=opset) with tvm.transform.PassContext(opt_level=1): graph, lib, params = relay.build(mod, target, params=params) ctx = tvm.cpu(0) m = graph_runtime.create(graph, lib, ctx) # set inputs if isinstance(input_data, list): for i, e in enumerate(input_names): # Its possible for some onnx inputs to not be needed in the tvm # module, confirm its present before setting. try: m.set_input(input_names[i], tvm.nd.array( input_data[i].astype(input_data[i].dtype))) except: continue else: m.set_input(input_names, tvm.nd.array( input_data.astype(input_data.dtype))) m.set_input(**params) # execute m.run() # get outputs if isinstance(output_shape, list) and isinstance(output_dtype, list): tvm_output_list = [] for i, _ in enumerate(output_shape): tvm_output = m.get_output(i) tvm_output_list.append(tvm_output.asnumpy()) return tvm_output_list else: tvm_output = m.get_output(0) return tvm_output.asnumpy() def get_onnxruntime_output(model, inputs, dtype='float32'): import onnxruntime.backend rep = onnxruntime.backend.prepare(model, 'CPU') if isinstance(inputs, list) and len(inputs) > 1: ort_out = rep.run(inputs) else: x = inputs.astype(dtype) ort_out = rep.run(x)[0] return ort_out def verify_onnx_forward_impl(graph_file, data_shape, out_shape): dtype = 'float32' x = np.random.uniform(size=data_shape) model = onnx.load_model(graph_file) c2_out = get_onnxruntime_output(model, x, dtype) for target, ctx in ctx_list(): tvm_out = get_tvm_output(model, x, target, ctx, out_shape, dtype) tvm.testing.assert_allclose(c2_out, tvm_out, rtol=1e-5, atol=1e-5) def test_reshape(): in_shape = (4, 3, 3, 4) ref_shape = (6, 2, 4, 3) ref_array = np.array(ref_shape) ref_node = onnx.helper.make_node('Constant', inputs=[], outputs=['ref_in'], value=onnx.helper.make_tensor(name='const_tensor', data_type=onnx.TensorProto.INT32, dims=ref_array.shape, vals=ref_array.flatten().astype(int))) reshape_node = helper.make_node("Reshape", ["in", "ref_in"], ["out"]) graph = helper.make_graph([ref_node, reshape_node], "reshape_test", inputs=[helper.make_tensor_value_info("in", TensorProto.FLOAT, list(in_shape))], outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(ref_shape))]) model = helper.make_model(graph, producer_name='reshape_test') for target, ctx in ctx_list(): x = np.random.uniform(size=in_shape).astype('int32') tvm_out = get_tvm_output(model, x, target, ctx, ref_shape, 'float32') tvm.testing.assert_allclose(ref_shape, tvm_out.shape) def test_expand(): def _test_expand(name, data, shape, ref_data): shape_array = np.array(shape) shape_node = onnx.helper.make_node('Constant', inputs=[], outputs=['shape'], value=onnx.helper.make_tensor(name = 'const_tensor', data_type = onnx.TensorProto.INT32, dims = shape_array.shape, vals = shape_array.flatten().astype('int32'))) expand_node = helper.make_node("Expand", ["in", "shape"], ["out"]) graph = helper.make_graph([shape_node, expand_node], "expand_test", inputs = [helper.make_tensor_value_info("in", TensorProto.FLOAT, list(data.shape))], outputs = [helper.make_tensor_value_info("out", TensorProto.FLOAT, list(ref_data.shape))]) model = helper.make_model(graph, producer_name=name) for target, ctx in ctx_list(): tvm_out = get_tvm_output(model, data, target, ctx, ref_data.shape, 'float32') tvm.testing.assert_allclose(ref_data, tvm_out) in_shape = (3, 1) shape = (3, 4) data = np.random.uniform(size=in_shape).astype(np.float32) ref_data = np.tile(data, 4) _test_expand('expand_with_dim_unchanged_test', data, shape, ref_data) in_shape = (3, 1) shape = (2, 1, 6) data = np.random.uniform(size=in_shape).astype(np.float32) ref_data = data * np.ones(shape, dtype=np.float32) _test_expand('expand_with_dim_changed_test', data, shape, ref_data) def verify_depth_to_space(inshape, outshape, mode, blockSize): node = onnx.helper.make_node('DepthToSpace', inputs=['x'], outputs=['y'], blocksize=blockSize) graph = helper.make_graph([node], "depth_to_space_test", inputs=[helper.make_tensor_value_info("x", TensorProto.FLOAT, list(inshape))], outputs=[helper.make_tensor_value_info("y", TensorProto.FLOAT, list(outshape))]) model = helper.make_model(graph, producer_name='depth_to_space_test') for target, ctx in ctx_list(): x = np.random.uniform(size=inshape).astype('float32') tvm_out = get_tvm_output(model, x, target, ctx, outshape, 'float32') onnx_out = get_onnxruntime_output(model, x, 'float32') tvm.testing.assert_allclose(onnx_out, tvm_out) def test_depth_to_space(): # current onnx.checker use OpSet-1 version of DepthToSpace, which doesn't have a mode argument. # TO-DO, we can add mode arguement to test CRD mode and DCR mode # in the future when we update to a newer onnx version. verify_depth_to_space((1, 8, 2, 3), (1, 2, 4, 6), mode="CRD", blockSize=2) def verify_space_to_depth(inshape, outshape, blockSize): node = onnx.helper.make_node('SpaceToDepth', inputs=['x'], outputs=['y'], blocksize=blockSize) graph = helper.make_graph([node], "space_to_depth_test", inputs=[helper.make_tensor_value_info("x", TensorProto.FLOAT, list(inshape))], outputs=[helper.make_tensor_value_info("y", TensorProto.FLOAT, list(outshape))]) model = helper.make_model(graph, producer_name='space_to_depth_test') for target, ctx in ctx_list(): x = np.random.uniform(size=inshape).astype('float32') tvm_out = get_tvm_output(model, x, target, ctx, outshape, 'float32') onnx_out = get_onnxruntime_output(model, x, 'float32') tvm.testing.assert_allclose(onnx_out, tvm_out) def test_space_to_depth(): verify_space_to_depth((1, 1, 4, 6), (1, 4, 2, 3), 2) def test_shape(): in_shape = (4, 3, 3, 4) ref_shape = (6, 2, 4, 3) ref_array = np.array(ref_shape) ref_node = onnx.helper.make_node('Constant', inputs=[], outputs=['ref_in'], value=onnx.helper.make_tensor(name='const_tensor', data_type=onnx.TensorProto.INT32, dims=ref_array.shape, vals=ref_array.flatten().astype(int))) reshape_node = helper.make_node("Reshape", ["in", "ref_in"], ["out"]) shape_node = helper.make_node("Shape", ['out'], ['final_out']) graph = helper.make_graph([ref_node, reshape_node, shape_node], "shape_test", inputs=[helper.make_tensor_value_info("in", TensorProto.FLOAT, list(in_shape))], outputs=[helper.make_tensor_value_info("final_out", TensorProto.FLOAT, list(ref_shape))]) model = helper.make_model(graph, producer_name='shape_test') for target, ctx in ctx_list(): x = np.random.uniform(size=in_shape).astype('int32') tvm_out = get_tvm_output(model, x, target, ctx, ref_shape, 'int32') tvm.testing.assert_allclose(ref_shape, tvm_out) def _test_power_iteration(x_shape, y_shape): if isinstance(y_shape, int): y_shape = [y_shape] x = np.random.uniform(size=x_shape).astype(np.float32) y = np.random.uniform(size=y_shape).astype(np.float32) np_res = np.power(x, y).astype(np.float32) res = helper.make_node("Pow", ['x', 'y'], ['out']) graph = helper.make_graph([res], 'power_test', inputs=[helper.make_tensor_value_info("x", TensorProto.FLOAT, list(x_shape)), helper.make_tensor_value_info("y", TensorProto.FLOAT, list(y_shape))], outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(np_res.shape))]) model = helper.make_model(graph, producer_name='power_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output(model, [x, y], target, ctx, np_res.shape) tvm.testing.assert_allclose(np_res, tvm_out, rtol=1e-5, atol=1e-5) def test_power(): _test_power_iteration((1, 3), (1)) _test_power_iteration((2, 3), (2, 3)) _test_power_iteration((2, 3), (1, 3)) def test_squeeze(): in_shape = (1, 3, 1, 3, 1, 1) out_shape = (3, 3) y = helper.make_node("Squeeze", ['in'], ['out'], axes=[0, 2, 4, 5]) graph = helper.make_graph([y], 'squeeze_test', inputs=[helper.make_tensor_value_info("in", TensorProto.FLOAT, list(in_shape))], outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(out_shape))]) model = helper.make_model(graph, producer_name='squeeze_test') for target, ctx in ctx_list(): x = np.random.uniform(size=in_shape).astype('float32') tvm_out = get_tvm_output(model, x, target, ctx, out_shape, 'float32') tvm.testing.assert_allclose(out_shape, tvm_out.shape) def test_flatten(): in_shape = (1, 3, 4, 4) axis = 1 ref_shape = (1, 48) flatten_node = helper.make_node("Flatten", ["in"], ["out"], axis=axis) graph = helper.make_graph([flatten_node], "flatten_test", inputs=[helper.make_tensor_value_info("in", TensorProto.FLOAT, list(in_shape))], outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(ref_shape))]) model = helper.make_model(graph, producer_name='flatten_test') for target, ctx in ctx_list(): x = np.random.uniform(size=in_shape).astype('int32') tvm_out = get_tvm_output(model, x, target, ctx, ref_shape, 'float32') tvm.testing.assert_allclose(ref_shape, tvm_out.shape) def test_unsqueeze(): in_shape = (3, 3) axis = (0, 3, 4) out_shape = (1, 3, 3, 1, 1) y = helper.make_node("Unsqueeze", ['in'], ['out'], axes=list(axis)) graph = helper.make_graph([y], 'squeeze_test', inputs=[helper.make_tensor_value_info("in", TensorProto.FLOAT, list(in_shape))], outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(out_shape))]) model = helper.make_model(graph, producer_name='squeeze_test') for target, ctx in ctx_list(): x = np.random.uniform(size=in_shape).astype('float32') tvm_out = get_tvm_output(model, x, target, ctx, out_shape, 'float32') tvm.testing.assert_allclose(out_shape, tvm_out.shape) def verify_gather(in_shape, indices, axis, dtype): x = np.random.uniform(size=in_shape).astype(dtype) indices = np.array(indices, dtype="int32") out_np = np.take(x, indices, axis=axis) y = helper.make_node("Gather", ['in', 'indices'], ['out'], axis=axis) graph = helper.make_graph([y], 'gather_test', inputs=[helper.make_tensor_value_info("in", TensorProto.FLOAT, list(in_shape)), helper.make_tensor_value_info("indices", TensorProto.INT32, list(indices.shape))], outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(out_np.shape))]) model = helper.make_model(graph, producer_name='gather_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output( model, [x, indices], target, ctx, out_np.shape) tvm.testing.assert_allclose(out_np, tvm_out) def test_gather(): verify_gather((4,), [1], 0, 'int32') verify_gather((1, 4), [0], 0, 'int32') verify_gather((4,), [[[1, 0], [0, 1]]], 0, 'float32') verify_gather((2, 2), [[[1, 0], [0, 1]]], 1, 'int32') verify_gather((3, 3, 3), [[[1, 0]]], -1, 'int32') verify_gather((4, 3, 5, 6), [[2, 1, 0, 0]], 0, 'float32') def verify_scatter(in_shape, indices, axis): x = np.random.uniform(size=in_shape).astype("float32") indices = np.array(indices, dtype="int32") updates = np.random.uniform(size=indices.shape).astype("float32") y = helper.make_node("ScatterElements", ['data', 'indices', 'updates'], ['output'], axis=axis) graph = helper.make_graph([y], 'scatter_test', inputs=[helper.make_tensor_value_info("data", TensorProto.FLOAT, list(in_shape)), helper.make_tensor_value_info("indices", TensorProto.INT32, list(indices.shape)), helper.make_tensor_value_info("updates", TensorProto.FLOAT, list(indices.shape))], outputs=[helper.make_tensor_value_info("output", TensorProto.FLOAT, list(in_shape))]) model = helper.make_model(graph, producer_name='scatter_test') onnx_out = get_onnxruntime_output(model, [x, indices, updates]) for target, ctx in ctx_list(): tvm_out = get_tvm_output( model, [x, indices, updates], target, ctx, onnx_out[0].shape) tvm.testing.assert_allclose(onnx_out[0], tvm_out) def test_scatter(): verify_scatter((4,), [1], 0) verify_scatter((1, 4), [[0]], 0) verify_scatter((4,), [2, 3], 0) verify_scatter((2, 2), [[1, 0], [0, 1]], 1) verify_scatter((3, 3, 3), [[[-1, -3]]], -1) verify_scatter((4, 3, 5, 6), [[[[2, 1, 0, 0]]]], 0) def _test_slice_iteration_v1(indata, outdata, starts, ends, axes=None): if axes: y = helper.make_node( "Slice", ['in'], ['out'], axes=axes, starts=starts, ends=ends) else: y = helper.make_node( "Slice", ['in'], ['out'], starts=starts, ends=ends) graph = helper.make_graph([y], 'slice_test', inputs=[helper.make_tensor_value_info("in", TensorProto.FLOAT, list(indata.shape))], outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(outdata.shape))]) model = helper.make_model(graph, producer_name='slice_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output( model, indata, target, ctx, outdata.shape, 'float32', opset=1) tvm.testing.assert_allclose(outdata, tvm_out) def _test_slice_iteration_v10(indata, outdata,
Pear": 0xEDEBDB, "Barely Pink": 0xF8D7DD, "Barely Ripe Apricot": 0xFFE3CB, "Barely Rose": 0xEDE0E3, "Barely White": 0xE1E3DD, "Barf Green": 0x94AC02, "Bargeboard Brown": 0x68534A, "Barista": 0xBCAFA2, "Barite": 0x9E7B5C, "Baritone": 0x708E95, "Barium": 0xF4E1C5, "Barium Green": 0x8FFF9F, "Bark": 0x5F5854, "Bark Brown": 0x73532A, "Bark Sawdust": 0xAB9004, "Barking Prairie Dog": 0xC5B497, "Barley Corn": 0xB6935C, "Barley Field": 0xC7BCAE, "Barley Groats": 0xFBF2DB, "Barley White": 0xF7E5B7, "Barn Door": 0x8E5959, "Barn Red": 0x8B4044, "Barney": 0xAC1DB8, "Barney Purple": 0xA00498, "Barnfloor": 0x9C9480, "Barnwood": 0x554D44, "Barnwood Ash": 0x87857E, "Barnwood Grey": 0x9E9589, "Barnyard Grass": 0x5DAC51, "Baroness": 0xA785A7, "Baroness Mauve": 0x847098, "Baronial Brown": 0x5A4840, "Baroque": 0xDDAA22, "Baroque Blue": 0x95B6B5, "Baroque Chalk Soft Blue": 0xAECCCB, "Baroque Grey": 0x5F5D64, "Baroque Red": 0x7B4F5D, "Baroque Rose": 0xB35A66, "Barossa": 0x452E39, "Barrel": 0xF0B069, "Barrel Stove": 0x8E7E67, "Barren": 0xB9ABA3, "Barrett Quince": 0xF5D1B2, "Barricade": 0x84623E, "Barrier Reef": 0x0084A1, "Barro Verde": 0x9F8E71, "Basalt Black": 0x4D423E, "Basalt Grey": 0x999999, "Base Camp": 0x575C3A, "Base Sand": 0xBB9955, "Baseball Base": 0xF4EADC, "Bashful": 0xE3EDED, "Bashful Blue": 0x6994CF, "Bashful Emu": 0xB2B0AC, "Bashful Pansy": 0xD9CDE5, "Bashful Rose": 0xB88686, "Basic Coral": 0xDBC3B6, "Basic Khaki": 0xC3B69F, "Basil": 0x879F84, "Basil Chiffonade": 0x828249, "Basil Green": 0x54622E, "Basil Icing": 0xE2E6DB, "Basil Mauve": 0x6C5472, "Basil Pesto": 0x529D6E, "Basil Smash": 0xB7E1A1, "Basilica Blue": 0x4A9FA7, "Basilisk": 0x9AB38D, "Basilisk Lizard": 0xBCECAC, "Basin Blue": 0xB9DEE4, "Basket Beige": 0xC0A98B, "Basket of Gold": 0xF4CC3C, "Basketball": 0xEE6730, "Basketry": 0xBDA286, "Basketweave Beige": 0xCAAD92, "Basmati White": 0xEBE1C9, "Basque Green": 0x5F6033, "Bassinet": 0xD3C1CB, "Basswood": 0xC9B196, "Bastard-amber": 0xFFCC88, "Bastille": 0x2C2C32, "Bastion Grey": 0x4D4A4A, "Bat Wing": 0x7E7466, "Bat-Signal": 0xFEFF00, "Bat's Blood Soup": 0xEE3366, "Batch Blue": 0x87B2C9, "Bateau": 0x1B7598, "Bateau Brown": 0x7A5F5A, "Bath Bubbles": 0xE6F2EA, "Bath Green": 0x0A696A, "Bath Salt Green": 0xBBDED7, "Bath Turquoise": 0x62BAA8, "Bath Water": 0x88EEEE, "Bathe Blue": 0xC2E0E3, "Bathing": 0x93C9D0, "Batik Lilac": 0x7E738B, "Batik Pink": 0x9C657E, "Batman": 0x656E72, "Batman's NES Cape": 0x940084, "Baton": 0x866F5A, "Baton Rouge": 0x973C6C, "Bats Cloak": 0x1F1518, "Battered Sausage": 0xEDE2D4, "Battery Charged Blue": 0x1DACD4, "Battle Blue": 0x74828F, "Battle Cat": 0x2B7414, "Battle Dress": 0x7E8270, "Battle Harbor": 0x9C9C82, "Battleship Green": 0x828F72, "Battleship Grey": 0x6F7476, "Battletoad": 0x11CC55, "Batu Cave": 0x595438, "Bauhaus": 0x3F4040, "Bauhaus Blue": 0x006392, "Bauhaus Buff": 0xCFB49E, "Bauhaus Gold": 0xB0986F, "Bauhaus Tan": 0xCCC4AE, "Bavarian": 0x4D5E42, "Bavarian Blue": 0x1C3382, "Bavarian Cream": 0xFFF9DD, "Bavarian Gentian": 0x20006D, "Bavarian Green": 0x749A54, "Bavarian Sweet Mustard": 0x4D3113, "Bay": 0xBAE5D6, "Bay Area": 0xAFA490, "Bay Brown": 0x773300, "Bay Fog": 0x9899B0, "Bay Isle Pointe": 0x214048, "Bay Leaf": 0x86793D, "Bay of Hope": 0xBFC9D0, "Bay of Many": 0x353E64, "Bay Salt": 0xD2CDBC, "Bay Scallop": 0xFBE6CD, "Bay Site": 0x325F8A, "Bay View": 0x6A819E, "Bay Water": 0xAAAD94, "Bay Wharf": 0x747F89, "Bay's Water": 0x7B9AAD, "Bayberry": 0x255958, "Bayberry Frost": 0xD0D9C7, "Bayberry Wax": 0xB6AA89, "Bayern Blue": 0x0098D4, "Bayou": 0x20706F, "Bayshore": 0x89CEE0, "Bayside": 0x5FC9BF, "Bazaar": 0x8F7777, "Bazooka Pink": 0xFFA6C9, "BBQ": 0xA35046, "Be Daring": 0xFFC943, "Be Mine": 0xF4E3E7, "Be My Valentine": 0xEC9DC3, "Be Spontaneous": 0xA5CB66, "Be Yourself": 0x9B983D, "Beach Bag": 0xADB864, "Beach Ball": 0xEFC700, "Beach Blue": 0x5F9CA2, "Beach Boardwalk": 0xCEAB90, "Beach Cabana": 0xA69081, "Beach Casuarina": 0x665A38, "Beach Cottage": 0x94ADB0, "Beach Dune": 0xC6BB9C, "Beach Foam": 0xCDE0E1, "Beach Glass": 0x96DFCE, "Beach Grass": 0xDCDDB8, "Beach House": 0xEDD481, "Beach Lilac": 0xBDA2C4, "Beach Party": 0xFBD05C, "Beach Sand": 0xFBB995, "Beach Towel": 0xFCE3B3, "Beach Trail": 0xFEDECA, "Beach Umbrella": 0x819AAA, "Beach White": 0xF6EED6, "Beach Wind": 0xDCE1E2, "Beach Woods": 0xCAC0B0, "Beachcomber": 0xD9E4E5, "Beachcombing": 0xE4C683, "Beachside Drive": 0xACDBDB, "Beachside Villa": 0xC3B296, "Beachwalk": 0xD2B17A, "Beachy Keen": 0xE6D0B6, "Beacon Blue": 0x265C98, "Beacon Yellow": 0xF2C98A, "Beaded Blue": 0x494D8B, "Beagle Brown": 0x8D6737, "Beaming Blue": 0x33FFFF, "Beaming Sun": 0xFFF8DF, "Bean Counter": 0x68755D, "Bean Green": 0x685C27, "Bean Pot": 0x8B6B51, "Bean Shoot": 0x91923A, "Bean Sprout": 0xF3F9E9, "Bean White": 0xEBF0E4, "Beanstalk": 0x31AA74, "Bear Brown": 0x44382B, "Bear Hug": 0x796359, "Bear in Mind": 0x5B4A44, "Bear Rug": 0x5A4943, "Bearsuit": 0x7D756D, "Beastly Flesh": 0x680C08, "Beasty Brown": 0x663300, "Beat Around the Bush": 0x6E6A44, "Beaten Copper": 0x73372D, "Beaten Purple": 0x4E0550, "Beaten Track": 0xD1BE92, "Beatnik": 0x5F8748, "Beatrice": 0xBEBAD9, "Beau Blue": 0xBCD4E6, "Beaujolais": 0x80304C, "Beaumont Brown": 0x92774C, "Beauport Aubergine": 0x553F44, "Beautiful Blue": 0x186DB6, "Beautiful Darkness": 0x686D70, "Beautiful Dream": 0xB6C7E3, "Beautiful Mint": 0xD6DAD6, "Beauty": 0x866B8D, "Beauty Bush": 0xEBB9B3, "Beauty Patch": 0x834F44, "Beauty Queen": 0xBE5C87, "Beauty Secret": 0xC79EA2, "Beauty Spot": 0x604938, "Beaver": 0x926F5B, "Beaver Fur": 0x997867, "Beaver Kit": 0x9F8170, "Beaver Pelt": 0x60564C, "Bechamel": 0xF4EEE0, "Becker Blue": 0x607879, "Beckett": 0x85A699, "Becquerel": 0x4BEC13, "Bed of Roses": 0xB893AB, "Bedazzled": 0xD3B9CC, "Bedbox": 0x968775, "Bedford Brown": 0xAA8880, "Bedrock": 0x9E9D99, "Bedtime Story": 0xE1B090, "Bee": 0xF1BA55, "Bee Cluster": 0xFFAA33, "Bee Hall": 0xF2CC64, "Bee Master": 0x735B3B, "Bee Pollen": 0xEBCA70, "Bee Yellow": 0xFEFF32, "Bee's Knees": 0xE8D9D2, "Bee's Wax": 0xEABF86, "Beech": 0x5B4F3B, "Beech Brown": 0x574128, "Beech Fern": 0x758067, "Beech Nut": 0xD7B59A, "Beechnut": 0xC2C18D, "Beechwood": 0x6E5955, "Beef Bourguignon": 0xB64701, "Beef Hotpot": 0xA85D2E, "Beef Jerky": 0xA25768, "Beef Patties": 0xBB5533, "Beehive": 0xE1B781, "Beekeeper": 0xF6E491, "Beer": 0xF28E1C, "Beer Garden": 0x449933, "Beer Glazed Bacon": 0x773311, "Beeswax": 0xE9D7AB, "Beeswax Candle": 0xBF7E41, "Beeswing": 0xF5D297, "Beet Red": 0x7A1F3D, "Beetle": 0x55584C, "Beetroot": 0x663F44, "Beetroot Purple": 0xCF2D71, "Beetroot Rice": 0xC58F9D, "Beets": 0x736A86, "Befitting": 0x96496D, "Before the Storm": 0x4D6A77, "Before Winter": 0xBD6F56, "Beggar": 0x5A4D39, "Begonia": 0xFA6E79, "Begonia Pink": 0xEC9ABE, "Begonia Rose": 0xC3797F, "Beguiling Mauve": 0xAFA7AC, "Beige": 0xE6DAA6, "Beige Ganesh": 0xCFB095, "Beige Green": 0xE0D8B0, "Beige Intenso": 0xC5A88D, "Beige Linen": 0xE2DAC6, "Beige Red": 0xDE9408, "Beige Royal": 0xCFC8B8, "Beige Topaz": 0xFFC87C, "Beijing Blue": 0x3E7DAA, "Beijing Moon": 0xA9A2A3, "Bel Air Blue": 0x819AC1, "Bel Esprit": 0x9BBCC3, "Belfast": 0x558D4F, "Belgian Block": 0xA3A9A6, "Belgian Blonde": 0xF7EFD0, "Belgian Cream": 0xF9F1E2, "Belgian Sweet": 0x8D7560, "Belgian Waffle": 0xF3DFB6, "Believable Buff": 0xDBC7A8, "Belize": 0x7FD3D3, "Belize Green": 0xB9C3B3, "Bell Blue": 0x618B97, "Bell Heather": 0xA475B1, "Bell Tower": 0xDAD0BB, "Bella": 0x574057, "Bella Green": 0x93C3B1, "Bella Mia": 0xDAC5BD, "Bella Pink": 0xE08194, "Bella Sera": 0x40465D, "Bella Vista": 0x0B695B, "Belladonna": 0x220011, "Belladonna's Leaf": 0xADC3A7, "Bellagio Fountains": 0xB7DFF3, "Belle of the Ball": 0xE3CBC0, "Bellflower": 0x5D66AA, "Bellflower Blue": 0xE1E9EF, "Bellflower Violet": 0xB2A5B7, "Bellini": 0xF4C9B1, "Bellini Fizz": 0xF5C78E, "Belly Fire": 0x773B38, "Belly Flop": 0x00817F, "Beloved Pink": 0xE9D3D4, "Below Zero": 0x87CDED, "Beluga": 0xEFF2F1, "Belvedere Cream": 0xE3DBC3, "Belyi White": 0xF0F1E1, "Benevolence": 0x694977, "Benevolent Pink": 0xDD1188, "Bengal": 0xCC974D, "Bengal Blue": 0x38738B, "Bengal Grass": 0x8E773F, "Bengala Red": 0x8F2E14, "Bengara Red": 0x913225, "Beni Shoga": 0xB85241, "Benifuji": 0xBB7796, "Benihi Red": 0xF35336, "Benikakehana Purple": 0x5A4F74, "Benikeshinezumi Purple": 0x44312E, "Benimidori Purple": 0x78779B, "Benitoite": 0x007BAA, "Beniukon Bronze": 0xFB8136, "Benthic Black": 0x000011, "Bento Box": 0xCC363C, "Bergamot": 0x95C703, "Bergamot Orange": 0xF59D59, "Bering Sea": 0x4B5B6E, "Bering Wave": 0x3D6D84, "Berkeley Hills": 0x7E613F, "Berkshire Lace": 0xF0E1CF, "Berlin Blue": 0x5588CC, "Bermuda": 0x1B7D8D, "Bermuda Blue": 0x8CB1C2, "Bermuda Grass": 0xA19F79, "Bermuda Grey": 0x6B8BA2, "Bermuda Onion": 0x9D5A8F, "Bermuda Sand": 0xDACBBF, "Bermuda Shell": 0xF9EEE3, "Bermuda Son": 0xF0E9BE, "Bermuda Triangle": 0x6F8C9F, "Bermudagrass": 0x6BC271, "Bermudan Blue": 0x386171, "Bern Red": 0xE20909, "Berries and Cream": 0x9E6A75, "Berries n Cream": 0xF2B8CA, "Berry": 0x990F4B, "Berry Blackmail": 0x662277, "Berry Bliss": 0x9E8295, "Berry Blue": 0x32607A, "Berry Blue Green": 0x264B56, "Berry Blush": 0xB88591, "Berry Boost": 0xBB5588, "Berry Bright": 0xA08497, "Berry Brown": 0x544F4C, "Berry Burst": 0xAC72AF, "Berry Bush": 0x77424E, "Berry Chalk": 0xA6AEBB, "Berry Charm": 0x4F4763, "Berry Cheesecake": 0xF8E3DD, "Berry Chocolate": 0x3F000F, "Berry Conserve": 0x765269, "Berry Cream": 0x9A8CA2, "Berry Crush": 0xAA6772, "Berry Frappé": 0xB3A1C6, "Berry Frost": 0xEBDED7, "Berry Jam": 0x655883, "Berry Light": 0x673B66, "Berry Mix": 0x555A90, "Berry Mojito": 0xB6CACA, "Berry Patch": 0x84395D, "Berry Pie": 0x4F6D8E, "Berry Popsicle": 0xD6A5CD, "Berry Riche": 0xE5A2AB, "Berry Rossi": 0x992244, "Berry Smoothie": 0x895360, "Berry Syrup": 0x64537C, "Berry Wine": 0x624D55, "Berta Blue": 0x45DCFF, "Beru": 0xBFE4D4, "Beryl Black Green": 0x2B322D, "Beryl Green": 0xBCBFA8, "Beryl Pearl": 0xE2E3DF, "Beryl Red": 0xA16381, "Beryllonite": 0xE9E5D7, "Bessie": 0x685E5B, "Best Beige": 0xC6B49C, "Best Bronze": 0x5D513E, "Best in Show": 0xB9B7BD, "Best of Summer": 0xF7F2D9, "Best of the Bunch": 0xBD5442, "Bestial Brown": 0x6B3900, "Bestial Red": 0x992211, "Bestigor Flesh": 0xD38A57, "Betalain Red": 0x7D655C, "Betel Nut Dye": 0x352925, "Bethany": 0xCADBBD, "Bethlehem Red": 0xEE0022, "Bethlehem Superstar": 0xEAEEDA, "Betsy": 0x73C9D9, "Betta Fish": 0x3A6B66, "Better Than Beige": 0xEBE2CB, "Beurre Blanc": 0xEDE1BE, "Beveled Glass": 0x7ACCB8, "Bewitching": 0x75495E, "Bewitching Blue": 0xBBD0E3, "Beyond the Clouds": 0xAAEEFF, "Beyond the Pines": 0x688049, "Beyond the Wall": 0xD7E0EB, "Bff": 0xDBB0D3, "Bhūrā Brown": 0x947706, "Białowieża Forest": 0x1C5022, "Bianca": 0xF4EFE0, "Bianchi Green": 0x3DCFC2, "Bicycle Yellow": 0xFFE58C, "Bicyclette": 0x802C3A, "Bidwell Blue": 0xA9B9B5, "Bidwell Brown": 0xB19C8F, "Biedermeier Blue": 0x507CA0, "Biel-Tan Green": 0x1BA169, "Bierwurst": 0xF0908D, "Big Band": 0xAFABA0, "Big Bang Pink": 0xFF0099, "Big Bus Yellow": 0xFFDA8B, "Big Chill": 0x7ECBE2, "Big Cypress": 0xB98675, "Big Daddy Blue": 0x5D6B75, "Big Dip O’Ruby": 0x9C2542, "Big Dipper": 0x41494B, "Big Fish": 0x99A38E, "Big Fish to Fry": 0xDADBE1, "Big Foot Feet": 0xE88E5A, "Big Horn Mountains": 0xB79E94,
<gh_stars>0 #!/usr/bin/env python3 """ Outputs the width file to stdout. """ import datetime import hashlib import os.path import re import sys from collections.abc import Iterable from typing import NamedTuple from urllib.request import urlretrieve VERSION = "14.0.0" UNICODE_DATA_URL = "https://unicode.org/Public/%s/ucd/UnicodeData.txt" % VERSION EAW_URL = "https://unicode.org/Public/%s/ucd/EastAsianWidth.txt" % VERSION EMOJI_DATA_URL = "https://unicode.org/Public/%s/ucd/emoji/emoji-data.txt" % VERSION # A handful of field names # See https://www.unicode.org/L2/L1999/UnicodeData.html FIELD_CODEPOINT = 0 FIELD_NAME = 1 FIELD_CATEGORY = 2 # Category for unassigned codepoints. CAT_UNASSIGNED = "Cn" # Category for private use codepoints. CAT_PRIVATE_USE = "Co" # Category for surrogates. CAT_SURROGATE = "Cs" # Category for non-characters. # Note this does not appear in UnicodeData.txt. # See https://www.unicode.org/faq/private_use.html CAT_NON_CHARACTERS = "non-characters" # Maximum codepoint value. MAX_CODEPOINT = 0x10FFFF CPP_PREFIX = "widechar_" OUTPUT_FILENAME = "widechar_width.h" OUTPUT_FILENAME_JS = "widechar_width.js" OUTPUT_FILENAME_RUST = "widechar_width.rs" OUTPUT_TEMPLATE = r""" /** * {filename}, generated on {today}. * See https://github.com/ridiculousfish/widecharwidth/ * * SHA1 file hashes: * UnicodeData.txt: {unicode_hash} * EastAsianWidth.txt: {eaw_hash} * emoji-data.txt: {emoji_hash} */ #ifndef WIDECHAR_WIDTH_H #define WIDECHAR_WIDTH_H #include <algorithm> #include <iterator> #include <cstddef> #include <cstdint> namespace {{ /* Special width values */ enum {{ {p}nonprint = -1, // The character is not printable. {p}combining = -2, // The character is a zero-width combiner. {p}ambiguous = -3, // The character is East-Asian ambiguous width. {p}private_use = -4, // The character is for private use. {p}unassigned = -5, // The character is unassigned. {p}widened_in_9 = -6, // Width is 1 in Unicode 8, 2 in Unicode 9+. {p}non_character = -7 // The character is a noncharacter. }}; /* An inclusive range of characters. */ struct {p}range {{ uint32_t lo; uint32_t hi; }}; /* Simple ASCII characters - used a lot, so we check them first. */ static const struct {p}range {p}ascii_table[] = {{ {ascii} }}; /* Private usage range. */ static const struct {p}range {p}private_table[] = {{ {private} }}; /* Nonprinting characters. */ static const struct {p}range {p}nonprint_table[] = {{ {nonprint} }}; /* Width 0 combining marks. */ static const struct {p}range {p}combining_table[] = {{ {combining} }}; /* Width 0 combining letters. */ static const struct {p}range {p}combiningletters_table[] = {{ {combiningletters} }}; /* Width 2 characters. */ static const struct {p}range {p}doublewide_table[] = {{ {doublewide} }}; /* Ambiguous-width characters. */ static const struct {p}range {p}ambiguous_table[] = {{ {ambiguous} }}; /* Unassigned characters. */ static const struct {p}range {p}unassigned_table[] = {{ {unassigned} }}; /* Non-characters. */ static const struct {p}range {p}nonchar_table[] = {{ {noncharacters} }}; /* Characters that were widened from width 1 to 2 in Unicode 9. */ static const struct {p}range {p}widened_table[] = {{ {widenedin9} }}; template<typename Collection> bool {p}in_table(const Collection &arr, uint32_t c) {{ auto where = std::lower_bound(std::begin(arr), std::end(arr), c, []({p}range p, uint32_t c) {{ return p.hi < c; }}); return where != std::end(arr) && where->lo <= c; }} /* Return the width of character c, or a special negative value. */ int {p}wcwidth(uint32_t c) {{ if ({p}in_table({p}ascii_table, c)) return 1; if ({p}in_table({p}private_table, c)) return {p}private_use; if ({p}in_table({p}nonprint_table, c)) return {p}nonprint; if ({p}in_table({p}nonchar_table, c)) return {p}non_character; if ({p}in_table({p}combining_table, c)) return {p}combining; if ({p}in_table({p}combiningletters_table, c)) return {p}combining; if ({p}in_table({p}doublewide_table, c)) return 2; if ({p}in_table({p}ambiguous_table, c)) return {p}ambiguous; if ({p}in_table({p}unassigned_table, c)) return {p}unassigned; if ({p}in_table({p}widened_table, c)) return {p}widened_in_9; return 1; }} }} // namespace #endif // WIDECHAR_WIDTH_H """ OUTPUT_TEMPLATE_RUST = r""" /** * {filename}, generated on {today}. * See https://github.com/ridiculousfish/widecharwidth/ * * SHA1 file hashes: * UnicodeData.txt: {unicode_hash} * EastAsianWidth.txt: {eaw_hash} * emoji-data.txt: {emoji_hash} */ type R = (u32, u32); #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum WcWidth {{ /// The character is single-width One, /// The character is double-width Two, /// The character is not printable. NonPrint, /// The character is a zero-width combiner. Combining, /// The character is East-Asian ambiguous width. Ambiguous, /// The character is for private use. PrivateUse, /// The character is unassigned. Unassigned, /// Width is 1 in Unicode 8, 2 in Unicode 9+. WidenedIn9, /// The character is a noncharacter. NonCharacter, }} /// Simple ASCII characters - used a lot, so we check them first. const ASCII_TABLE: &'static [R] = &[ {ascii} ]; /// Private usage range. const PRIVATE_TABLE: &'static [R] = &[ {private} ]; /// Nonprinting characters. const NONPRINT_TABLE: &'static [R] = &[ {nonprint} ]; /// Width 0 combining marks. const COMBINING_TABLE: &'static [R] = &[ {combining} ]; /// Width 0 combining letters. const COMBININGLETTERS_TABLE: &'static [R] = &[ {combiningletters} ]; /// Width 2 characters. const DOUBLEWIDE_TABLE: &'static [R] = &[ {doublewide} ]; /// Ambiguous-width characters. const AMBIGUOUS_TABLE: &'static [R] = &[ {ambiguous} ]; /// Unassigned characters. const UNASSIGNED_TABLE: &'static [R] = &[ {unassigned} ]; /// Non-characters. const NONCHAR_TABLE: &'static [R] = &[ {noncharacters} ]; /// Characters that were widened from width 1 to 2 in Unicode 9. const WIDENED_TABLE: &'static [R] = &[ {widenedin9} ]; fn in_table(arr: &[R], c: u32) -> bool {{ arr.binary_search_by(|(start, end)| if c >= *start && c <= *end {{ std::cmp::Ordering::Equal }} else {{ start.cmp(&c) }}).is_ok() }} impl WcWidth {{ /// Return the width of character c pub fn from_char(c: char) -> Self {{ let c = c as u32; if in_table(&ASCII_TABLE, c) {{ return Self::One; }} if in_table(&PRIVATE_TABLE, c) {{ return Self::PrivateUse; }} if in_table(&NONPRINT_TABLE, c) {{ return Self::NonPrint; }} if in_table(&NONCHAR_TABLE, c) {{ return Self::NonCharacter; }} if in_table(&COMBINING_TABLE, c) {{ return Self::Combining; }} if in_table(&COMBININGLETTERS_TABLE, c) {{ return Self::Combining; }} if in_table(&DOUBLEWIDE_TABLE, c) {{ return Self::Two; }} if in_table(&AMBIGUOUS_TABLE, c) {{ return Self::Ambiguous; }} if in_table(&UNASSIGNED_TABLE, c) {{ return Self::Unassigned; }} if in_table(&WIDENED_TABLE, c) {{ return Self::WidenedIn9; }} Self::One }} /// Returns width for applications that are using unicode 8 or earlier pub fn width_unicode_8_or_earlier(self) -> u8 {{ match self {{ Self::One => 1, Self::Two => 2, Self::NonPrint | Self::Combining | Self::Unassigned | Self::NonCharacter => 0, Self::Ambiguous | Self::PrivateUse => 1, Self::WidenedIn9 => 1, }} }} /// Returns width for applications that are using unicode 9 or later pub fn width_unicode_9_or_later(self) -> u8 {{ if self == Self::WidenedIn9 {{ return 2; }} self.width_unicode_8_or_earlier() }} }} #[cfg(test)] mod test {{ use super::*; #[test] fn basics() {{ assert_eq!(WcWidth::from_char('w'), WcWidth::One); assert_eq!(WcWidth::from_char('\x1f'), WcWidth::NonPrint); assert_eq!(WcWidth::from_char('\u{{e001}}'), WcWidth::PrivateUse); assert_eq!(WcWidth::from_char('\u{{2716}}'), WcWidth::One); assert_eq!(WcWidth::from_char('\u{{270a}}'), WcWidth::WidenedIn9); assert_eq!(WcWidth::from_char('\u{{3fffd}}'), WcWidth::Two); }} }} """ OUTPUT_TEMPLATE_JS = r""" /* * {filename}, generated on {today}. * See https://github.com/ridiculousfish/widecharwidth/ * * SHA1 file hashes: * UnicodeData.txt: {unicode_hash} * EastAsianWidth.txt: {eaw_hash} * emoji-data.txt: {emoji_hash} */ /* Special width values */ const {p}nonprint = -1; // The character is not printable. const {p}combining = -2; // The character is a zero-width combiner. const {p}ambiguous = -3; // The character is East-Asian ambiguous width. const {p}private_use = -4; // The character is for private use. const {p}unassigned = -5; // The character is unassigned. const {p}widened_in_9 = -6; // Width is 1 in Unicode 8, 2 in Unicode 9+. const {p}non_character = -7; // The character is a noncharacter. /* Simple ASCII characters - used a lot, so we check them first. */ const {p}ascii_table = [ {ascii} ]; /* Private usage range. */ const {p}private_table = [ {private} ]; /* Nonprinting characters. */ const {p}nonprint_table = [ {nonprint} ]; /* Width 0 combining marks. */ const {p}combining_table = [ {combining} ]; /* Width 0 combining letters. */ const {p}combiningletters_table = [ {combiningletters} ]; /* Width.2 characters. */ const {p}doublewide_table = [ {doublewide} ]; /* Ambiguous-width characters. */ const {p}ambiguous_table = [ {ambiguous} ]; /* Unassigned characters. */ const {p}unassigned_table = [ {unassigned} ]; /* Non-characters. */ const {p}nonchar_table[] = [ {noncharacters} ]; /* Characters that were widened from width 1 to 2 in Unicode 9. */ const {p}widened_table[] = [ {widenedin9} ]; function {p}in_table(data, ucs) {{ let min = 0; let max = data.length - 1; let mid; if (ucs < data[0][0] || ucs > data[max][1]) return false; while (max >= min) {{ mid = (min + max) >> 1; if (ucs > data[mid][1]) {{ min = mid + 1; }} else if (ucs < data[mid][0]) {{ max = mid - 1; }} else {{ return true; }} }} return false; }} /* Return the width of character c, or a special negative value. */ function {p}wcwidth(c) {{ if ({p}in_table({p}ascii_table, c)) return 1; if ({p}in_table({p}private_table, c)) return {p}private_use; if ({p}in_table({p}nonprint_table, c)) return {p}nonprint; if ({p}in_table({p}nonchar_table, c)) return {p}non_character; if ({p}in_table({p}combining_table, c)) return {p}combining; if ({p}in_table({p}combiningletters_table, c)) return {p}combining; if ({p}in_table({p}doublewide_table, c)) return 2; if ({p}in_table({p}ambiguous_table, c)) return {p}ambiguous; if ({p}in_table({p}unassigned_table, c)) return {p}unassigned; if ({p}in_table({p}widened_table, c)) return {p}widened_in_9; return 1; }} """ # Ambiguous East Asian characters WIDTH_AMBIGUOUS_EASTASIAN = -3 # Width changed from 1 to 2 in Unicode 9.0 WIDTH_WIDENED_IN_9 = -6 # Private use characters. WIDTH_PRIVATE_USE = -7 class CodePoint(object): # pylint: disable=too-few-public-methods """Represents a single Unicode codepoint""" def __init__(self, codepoint): self.codepoint = codepoint self.width = None self.category = CAT_UNASSIGNED def hex(self): """Return the codepoint as a hex string""" return "0x%05X" % self.codepoint # Settings controlling language output. class LangSettings(NamedTuple): range_chars: str # open/close characters for ranges, like "{}" # Data parsed from unicode.org datafiles. # Datas are lists of lines, with comment-only lines removed. # Hashes are sha1 strings. class UnicodeDatas(NamedTuple): unicode_data:
<gh_stars>0 ''' pygetmap: Download web map by cooridinates ''' # Longitude 经度 # Latitude 纬度 # Mecator x = y = [-20037508.3427892,20037508.3427892] # Mecator Latitue = [-85.05112877980659,85.05112877980659] import math from math import floor, pi, log, tan, atan, exp from threading import Thread, Lock import urllib.request as ur import PIL.Image as pil import io import time import eventlet MAP_URLS = { "google": "http://mt2.google.cn/vt/lyrs={style}&hl=zh-CN&src=app&x={x}&y={y}&z={z}", "amap": "http://wprd02.is.autonavi.com/appmaptile?style={style}&x={x}&y={y}&z={z}", "tencent_s": "http://p3.map.gtimg.com/sateTiles/{z}/{fx}/{fy}/{x}_{y}.jpg", "tencent_m": "http://rt0.map.gtimg.com/tile?z={z}&x={x}&y={y}&styleid=3" } COUNT=0 mutex=Lock() #-----------------GCJ02到WGS84的纠偏与互转--------------------------- def transformLat(x, y): ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * math.sqrt(abs(x)) ret += (20.0 * math.sin(6.0 * x * math.pi) + 20.0 * math.sin(2.0 * x * math.pi)) * 2.0 / 3.0 ret += (20.0 * math.sin(y * math.pi) + 40.0 * math.sin(y / 3.0 * math.pi)) * 2.0 / 3.0 ret += (160.0 * math.sin(y / 12.0 * math.pi) + 320 * math.sin(y * math.pi / 30.0)) * 2.0 / 3.0 return ret def transformLon(x, y): ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * math.sqrt(abs(x)) ret += (20.0 * math.sin(6.0 * x * math.pi) + 20.0 * math.sin(2.0 * x * math.pi)) * 2.0 / 3.0 ret += (20.0 * math.sin(x * math.pi) + 40.0 * math.sin(x / 3.0 * math.pi)) * 2.0 / 3.0 ret += (150.0 * math.sin(x / 12.0 * math.pi) + 300.0 * math.sin(x / 30.0 * math.pi)) * 2.0 / 3.0 return ret def delta(lat, lon): ''' Krasovsky 1940 // // a = 6378245.0, 1/f = 298.3 // b = a * (1 - f) // ee = (a^2 - b^2) / a^2; ''' a = 6378245.0 # a: 卫星椭球坐标投影到平面地图坐标系的投影因子。 ee = 0.00669342162296594323 # ee: 椭球的偏心率。 dLat = transformLat(lon - 105.0, lat - 35.0) dLon = transformLon(lon - 105.0, lat - 35.0) radLat = lat / 180.0 * math.pi magic = math.sin(radLat) magic = 1 - ee * magic * magic sqrtMagic = math.sqrt(magic) dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * math.pi) dLon = (dLon * 180.0) / (a / sqrtMagic * math.cos(radLat) * math.pi) return {'lat': dLat, 'lon': dLon} def outOfChina(lat, lon): if (lon < 72.004 or lon > 137.8347): return True if (lat < 0.8293 or lat > 55.8271): return True return False def gcj_to_wgs(gcjLon,gcjLat): if outOfChina(gcjLat, gcjLon): return (gcjLon, gcjLat) d = delta(gcjLat, gcjLon) return (gcjLon - d["lon"],gcjLat - d["lat"]) def wgs_to_gcj(wgsLon,wgsLat): if outOfChina(wgsLat, wgsLon): return wgsLon, wgsLat d = delta(wgsLat, wgsLon); return wgsLon + d["lon"], wgsLat + d["lat"] #-------------------------------------------------------------- #------------------wgs84与web墨卡托互转------------------------- # WGS-84经纬度转Web墨卡托 def wgs_to_macator(x, y): y = 85.0511287798 if y > 85.0511287798 else y y = -85.0511287798 if y < -85.0511287798 else y x2 = x * 20037508.34 / 180 y2 = log(tan((90 + y) * pi / 360)) / (pi / 180) y2 = y2 * 20037508.34 / 180 return x2, y2 # Web墨卡托转经纬度 def mecator_to_wgs(x, y): x2 = x / 20037508.34 * 180 y2 = y / 20037508.34 * 180 y2 = 180 / pi * (2 * atan(exp(y2 * pi / 180)) - pi / 2) return x2, y2 #------------------------------------------------------------- #--------------------------------------------------------- ''' 东经为正,西经为负。北纬为正,南纬为负 j经度 w纬度 z缩放比例[0-22] ,对于卫星图并不能取到最大,测试值是20最大,再大会返回404. 山区卫星图可取的z更小,不同地图来源设置不同。 ''' # 根据WGS-84 的经纬度获取谷歌地图中的瓦片坐标 def wgs84_to_tile(j, w, z): ''' Get google-style tile cooridinate from geographical coordinate j : Longittude w : Latitude z : zoom ''' isnum = lambda x: isinstance(x, int) or isinstance(x, float) if not(isnum(j) and isnum(w)): raise TypeError("j and w must be int or float!") if not isinstance(z, int) or z < 0 or z > 22: raise TypeError("z must be int and between 0 to 22.") if j < 0: j = 180 + j else: j += 180 j /= 360 # make j to (0,1) w = 85.0511287798 if w > 85.0511287798 else w w = -85.0511287798 if w < -85.0511287798 else w w = log(tan((90 + w) * pi / 360)) / (pi / 180) w /= 180 # make w to (-1,1) w = 1 - (w + 1) / 2 # make w to (0,1) and left top is 0-point num = 2**z x = floor(j * num) y = floor(w * num) return x, y def tileframe_to_mecatorframe(zb): # 根据瓦片四角坐标,获得该区域四个角的web墨卡托投影坐标 inx, iny =zb["LT"] #left top inx2,iny2=zb["RB"] #right bottom length = 20037508.3427892 sum = 2**zb["z"] LTx = inx / sum * length * 2 - length LTy = -(iny / sum * length * 2) + length RBx = (inx2 + 1) / sum * length * 2 - length RBy = -((iny2 + 1) / sum * length * 2) + length # LT=left top,RB=right buttom # 返回四个角的投影坐标 res = {'LT': (LTx, LTy), 'RB': (RBx, RBy), 'LB': (LTx, RBy), 'RT': (RBx, LTy)} return res def tileframe_to_pixframe(zb): # 瓦片坐标转化为最终图片的四个角像素的坐标 out={} width=(zb["RT"][0]-zb["LT"][0]+1)*256 height=(zb["LB"][1]-zb["LT"][1]+1)*256 out["LT"]=(0,0) out["RT"]=(width,0) out["LB"]=(0,-height) out["RB"]=(width,-height) return out #----------------------------------------------------------- class Downloader(Thread): # multiple threads downloader def __init__(self,index,count,urls,datas,update): # index 表示第几个线程,count 表示线程的总数,urls 代表需要下载url列表,datas代表要返回的数据列表。 # update 表示每下载一个成功就进行的回调函数。 super().__init__() self.urls=urls self.datas=datas self.index=index self.count=count self.update=update def download(self,url): HEADERS = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36'} header = ur.Request(url,headers=HEADERS) err=0 while(err<3): try: data = ur.urlopen(header).read() except: err+=1 else: return data raise Exception("Bad network link.") def run(self): for i,url in enumerate(self.urls): if i%self.count != self.index: continue flag = True while flag: eventlet.monkey_patch() # 必须加这条代码 try: with eventlet.Timeout(5, True): self.datas[i] = self.download(url) flag = False except eventlet.timeout.Timeout: print('Time out!') if mutex.acquire(): self.update() mutex.release() def geturl(source, x, y, z, style): ''' Get the picture's url for download. style: m for map s for satellite source: google or amap or tencent x y: google-style tile coordinate system z: zoom ''' if source == 'google': furl = MAP_URLS["google"].format(x=x, y=y, z=z, style=style) elif source == 'amap': # for amap 6 is satellite and 7 is map. style = 6 if style == 's' else 7 furl = MAP_URLS["amap"].format(x=x, y=y, z=z, style=style) elif source == 'tencent': y = 2**z - 1 - y if style == 's': furl = MAP_URLS["tencent_s"].format( x=x, y=y, z=z, fx=floor(x / 16), fy=floor(y / 16)) else: furl = MAP_URLS["tencent_m"].format(x=x, y=y, z=z) else: raise Exception("Unknown Map Source ! ") return furl def downpics(urls,multi=10): def makeupdate(s): def up(): global COUNT COUNT+=1 print("\b"*45,end='') print("DownLoading ... [{0}/{1}]".format(COUNT,s),end='') return up url_len=len(urls) datas=[None] * url_len if multi <1 or multi >20 or not isinstance(multi,int): raise Exception("multi of Downloader shuold be int and between 1 to 20.") tasks=[Downloader(i,multi,urls,datas,makeupdate(url_len)) for i in range(multi)] for i in tasks: i.start() for i in tasks: i.join() return datas def getpic(y2, x1, y1, x2, z, source='google', outfile="MAP_OUT.png", style='s'): ''' 依次输入左上角的经度、纬度,右下角的经度、纬度,缩放级别,地图源,输出文件,影像类型(默认为卫星图) 获取区域内的瓦片并自动拼合图像。返回四个角的瓦片坐标 ''' global COUNT COUNT = 0 pos1x, pos1y = wgs84_to_tile(x1, y1, z) pos2x, pos2y = wgs84_to_tile(x2, y2, z) lenx = pos2x - pos1x + 1 leny = pos2y - pos1y + 1 print("Total number:{x} X {y}".format(x=lenx, y=leny)) urls = [geturl(source, i, j, z, style) for j in range(pos1y, pos1y + leny) for i in range(pos1x, pos1x + lenx)] datas = downpics(urls) print("\nDownload Finished! Pics Mergeing......") outpic = pil.new('RGBA', (lenx * 256, leny * 256)) for i, data in enumerate(datas): picio = io.BytesIO(data) small_pic = pil.open(picio) y, x = i // lenx, i % lenx outpic.paste(small_pic, (x * 256, y * 256)) print('Pics Merged! Exporting......') outpic.save(outfile) print('Exported to file!') return {"LT":(pos1x,pos1y),"RT":(pos2x,pos1y),"LB":(pos1x,pos2y),"RB":(pos2x,pos2y),"z":z} def screen_out(zb,name): if not zb: print("N/A") return print("坐标形式:",name) print("左上:({0:.5f},{1:.5f})".format(*zb['LT'])) print("右上:({0:.5f},{1:.5f})".format(*zb['RT'])) print("左下:({0:.5f},{1:.5f})".format(*zb['LB'])) print("右下:({0:.5f},{1:.5f})".format(*zb['RB'])) def file_out(zb,file,target="keep",output="file"): ''' zh_in : tile coordinate file : a text file for ArcGis target : keep = tile to Geographic coordinate gcj = tile to Geographic coordinate,then wgs84 to gcj wgs = tile to Geographic coordinate,then gcj02 to wgs84 ''' pixframe=tileframe_to_pixframe(zb) Xframe=tileframe_to_mecatorframe(zb) for i in ["LT","LB","RT","RB"]: Xframe[i]=mecator_to_wgs(*Xframe[i]) if target =="keep": pass elif target == "gcj": for i in ["LT","LB","RT","RB"]: Xframe[i]=wgs_to_gcj(*Xframe[i]) elif target == "wgs": for i in ["LT","LB","RT","RB"]: Xframe[i]=gcj_to_wgs(*Xframe[i]) else: raise Exception("Invalid argument: target.") if output=="file": f=open(file,"w") for i in ["LT","LB","RT","RB"]: f.write("{0[0]:}, {0[1]}, {1[0]}, {1[1]}\n".format(pixframe[i], Xframe[i])) f.close() print("Exported link file to ",file) else: screen_out(Xframe,target) def my_file_out(zb, file, target="keep", output="file"): ''' zh_in : tile coordinate file : a text file for ArcGis target : keep = tile to Geographic coordinate gcj =
""" Load test picoCTF platform functionality. Requires a connection to a MongoDB database populated with test user credentials generated by the registration locustfile (registration.py) """ import random import pymongo from locust import HttpLocust, TaskSet, task from config import (ADMIN_PASSWORD, ADMIN_USERNAME, BATCH_REGISTRATION_CSV_FILENAME, CLASSROOM_PAGE_URL, CREATE_GROUP_ENDPOINT, CREATE_TEAM_ENDPOINT, FEEDBACK_ENDPOINT, GAME_PAGE_URL, GROUP_LIMIT, GROUPS_ENDPOINT, JOIN_GROUP_ENDPOINT, JOIN_TEAM_ENDPOINT, LOGIN_ENDPOINT, LOGOUT_ENDPOINT, MAX_TEAM_SIZE, NEWS_PAGE_URL, PROBLEMS_ENDPOINT, PROBLEMS_PAGE_URL, PROFILE_PAGE_URL, REGISTRATION_ENDPOINT, REGISTRATION_STATS_ENDPOINT, SCOREBOARD_PAGE_URL, SCOREBOARDS_ENDPOINT, SETTINGS_ENDPOINT, SHELL_PAGE_URL, SHELL_SERVERS_ENDPOINT, STATUS_ENDPOINT, SUBMISSIONS_ENDPOINT, TEAM_ENDPOINT, TEAM_SCORE_ENDPOINT, TEAM_SCORE_PROGRESSION_ENDPOINT, USER_DELETE_ACCOUNT_ENDPOINT, USER_ENDPOINT, USER_EXPORT_ENDPOINT, USER_PASSWORD_CHANGE_ENDPOINT, get_db) from demographics_generators import (get_affiliation, get_country_code, get_demographics, get_email, get_group_name, get_password, get_team_name, get_user_type, get_username) from registration import register_and_expect_failure def generate_user(): """Generate a set of valid demographics for the given user type.""" user_fields = { 'username': get_username(), 'password': 'password', 'email': get_email(), 'affiliation': get_affiliation(), 'country': get_country_code(), 'usertype': get_user_type(), 'demo': get_demographics(), } return user_fields def acquire_user(properties={}): """Retrieve an available test user with the specified properties.""" properties['in_use'] = {'$in': [False, None]} properties['deleted'] = {'$in': [False, None]} properties['rand_id'] = {'$near': [random.random(), 0]} user = get_db().users.find_one_and_update( properties, {'$set': {'in_use': True}}, {'_id': 0}) if not user: raise Exception( "Could not acquire user with properties " + str(properties)) return user def release_user(username): """Release a test user for usage by other threads.""" res = get_db().users.find_one_and_update( {'username': username}, {'$set': {'in_use': False}}) if not res: raise Exception("Could not release user " + str(username)) def login(l, username=None, password=<PASSWORD>): """Attempt to log in as a provided or randomly selected user.""" user = None if not username: user = acquire_user() if not user: return None else: user = dict() user['username'] = username user['password'] = password with l.client.post(LOGIN_ENDPOINT, json={ 'username': user['username'], 'password': <PASSWORD>['password'] }, catch_response = True) as res: if res.status_code == 200: res.success() else: res.failure('Could not log in as {}'.format(user['username'])) return user['username'] def logout(l): """Attempt to log out the current user.""" l.client.get(LOGOUT_ENDPOINT) def get_valid_scoreboard_base_endpoint(l): """ Return a valid scoreboard base URL (scoreboard or group) for a user. This URL should be followed with e.g. /scoreboard, /score_progressions, etc """ scoreboards = l.client.get(SCOREBOARDS_ENDPOINT).json() groups = l.client.get(GROUPS_ENDPOINT).json() # Load the initial page of one of the scoreboards possible_boards = [] for board in scoreboards: possible_boards.append(('scoreboard', board['sid'])) for group in groups: possible_boards.append(('group', group['gid'])) board = random.choice(possible_boards) if board[0] == 'scoreboard': endpoint = SCOREBOARDS_ENDPOINT + '/' + board[1] call_label = SCOREBOARDS_ENDPOINT + '/[sid]' else: endpoint = GROUPS_ENDPOINT + '/' + board[1] call_label = GROUPS_ENDPOINT + '/[gid]' return (endpoint, call_label) def get_problem_flags(pid): """Retrieve a list of all instance flags for a problem from the DB.""" return get_db().problems.find_one({'pid': pid}).get('flags', []) def simulate_loading_any_page(l): """Simulate the calls made upon loading any frontend page.""" l.client.get(USER_ENDPOINT) l.client.get(STATUS_ENDPOINT) def simulate_loading_login_page(l): """Simulate the calls made upon loading the login page.""" simulate_loading_any_page(l) l.client.get("") l.client.get(SETTINGS_ENDPOINT) l.client.get(REGISTRATION_STATS_ENDPOINT) def simulate_loading_problems_page(l): """Simulate the calls made upon loading the problems page.""" simulate_loading_any_page(l) l.client.get(PROBLEMS_PAGE_URL) l.client.get(TEAM_ENDPOINT) l.client.get(FEEDBACK_ENDPOINT) l.client.get(TEAM_SCORE_PROGRESSION_ENDPOINT) l.client.get(TEAM_SCORE_ENDPOINT) l.client.get(PROBLEMS_ENDPOINT) def simulate_loading_shell_page(l): """Simulate the calls made upon loading the shell page.""" simulate_loading_any_page(l) l.client.get(SHELL_PAGE_URL) l.client.get(SHELL_SERVERS_ENDPOINT) def simulate_loading_game_page(l): """Simulate the calls made upon loading the game page.""" simulate_loading_any_page(l) l.client.get(GAME_PAGE_URL) l.client.get(STATUS_ENDPOINT) def simulate_loading_scoreboard_page(l): """Simulate the calls made upon loading the scoreboard page.""" simulate_loading_any_page(l) l.client.get(SCOREBOARD_PAGE_URL) l.client.get(SCOREBOARDS_ENDPOINT) l.client.get(TEAM_ENDPOINT) l.client.get(GROUPS_ENDPOINT) def simulate_loading_classroom_page(l): """Simulate the calls made upon loading the classroom page.""" simulate_loading_any_page(l) l.client.get(CLASSROOM_PAGE_URL) res = l.client.get(GROUPS_ENDPOINT) for group in res.json(): l.client.get(GROUPS_ENDPOINT + '/' + group['gid'], name=GROUPS_ENDPOINT + '/[gid]') def simulate_loading_profile_page(l): """Simulate the calls made upon loading the profile page.""" simulate_loading_any_page(l) l.client.get(PROFILE_PAGE_URL) l.client.get(TEAM_ENDPOINT) l.client.get(SCOREBOARDS_ENDPOINT) l.client.get(GROUPS_ENDPOINT) def simulate_loading_news_page(l): """Simulate the calls made upon loading the news page.""" simulate_loading_any_page(l) l.client.get(NEWS_PAGE_URL) class LoadTestingTasks(TaskSet): """Root set of all load testing tasks.""" @task(weight=2) class PageBrowsingTasks(TaskSet): """Simulate a user just browsing pages.""" @task def load_login_page(l): """Simulate loading the login page.""" simulate_loading_login_page(l) l.interrupt() @task def load_shell_page(l): """Simulate loading the shell page.""" username = login(l) if not username: l.interrupt() simulate_loading_shell_page(l) logout(l) release_user(username) l.interrupt() @task def load_game_page(l): """Simulate loading the Unity game page.""" username = login(l) if not username: l.interrupt() simulate_loading_game_page(l) logout(l) release_user(username) l.interrupt() @task def load_news_page(l): """Simulate loading the news page.""" simulate_loading_news_page(l) l.interrupt() @task def call_user_endpoint(l): """Just calls the user endpoint, as if updating the score display.""" username = login(l) if not username: l.interrupt() l.client.get(USER_ENDPOINT) logout(l) release_user(username) l.interrupt() @task(weight=10) class ProblemTasks(TaskSet): """Simulate actions on the problems page.""" def setup(l): """Retrieve all problem flags as an admin user (runs once).""" get_db().problems.delete_many({}) login(l, username=ADMIN_USERNAME, password=<PASSWORD>) all_problems = l.client.get( PROBLEMS_ENDPOINT + '?unlocked_only=false').json() flag_maps = [] for problem in all_problems: flag_maps.append({ 'pid': problem['pid'], 'flags': [i['flag'] for i in problem['instances']], 'rand_id': [random.random(), 0] }) get_db().problems.insert_many(flag_maps) logout(l) @task(weight=1) def load_problems_page(l): """Load the problems page without solving anything.""" username = login(l) if not username: l.interrupt() simulate_loading_problems_page(l) logout(l) release_user(username) l.interrupt() @task(weight=5) def submit_problem_solution(l): """Submit a solution to a problem.""" username = login(l) if not username: l.interrupt() simulate_loading_problems_page(l) unlocked_problems = l.client.get(PROBLEMS_ENDPOINT).json() problem = random.choice(unlocked_problems) # Select a flag from the pool of possible instance flags: # probability of a correct submission is 1/(num instances) flag = random.choice(get_problem_flags(problem['pid'])) l.client.post(SUBMISSIONS_ENDPOINT, json={ 'pid': problem['pid'], 'key': flag, 'method': 'testing' }, headers={ 'X-CSRF-Token': l.client.cookies['token'] }) release_user(username) l.interrupt() @task(weight=1) def send_feedback(l): """Submit feedback for an unlocked problem.""" username = login(l) if not username: l.interrupt() simulate_loading_problems_page(l) unlocked_problems = l.client.get(PROBLEMS_ENDPOINT).json() problem = random.choice(unlocked_problems) l.client.post(FEEDBACK_ENDPOINT, json={ 'pid': problem['pid'], 'feedback': { 'liked': random.choice([True, False]) } }, headers={ 'X-CSRF-Token': l.client.cookies['token'] }) release_user(username) l.interrupt() @task(weight=3) class ScoreboardTasks(TaskSet): """Simulate actions on the scoreboards page.""" @task(weight=10) def load_scoreboard_pages(l): """Load several pages of a random scoreboard.""" username = login(l) if not username: l.interrupt() simulate_loading_scoreboard_page(l) endpoint, call_label = get_valid_scoreboard_base_endpoint(l) l.client.get(endpoint + '/score_progressions', name=(call_label + '/score_progressions')) initial_page_res = l.client.get( endpoint + '/scoreboard', name=(call_label + '/scoreboard')).json() for i in range(0, random.randrange(1, 10)): p = random.randrange( 1, initial_page_res['total_pages'] + 1) l.client.get(endpoint + '/scoreboard?page=' + str(p), name=(call_label + '/scoreboard?page=[p]')) logout(l) release_user(username) l.interrupt() @task(weight=1) def load_filtered_scoreboard_pages(l): """Load several pages of a filtered random scoreboard.""" username = login(l) if not username: l.interrupt() simulate_loading_scoreboard_page(l) endpoint, call_label = get_valid_scoreboard_base_endpoint(l) l.client.get(endpoint + '/score_progressions', name=(call_label + '/score_progressions')) initial_page_res = l.client.get( endpoint + '/scoreboard', name=(call_label + '/scoreboard')).json() search_endpoint = ( endpoint + '/scoreboard?search=' + get_affiliation()) for i in range(0, random.randrange(1, 10)): p = random.randrange( 1, initial_page_res['total_pages'] + 1) l.client.get(search_endpoint + '&page=' + str(p), name=(call_label + '/scoreboard?search=[q]&page=[p]')) logout(l) release_user(username) l.interrupt() @task(weight=1) class ProfileTasks(TaskSet): """Simulate profile page actions.""" @task(weight=10) def load_profile_page(l): """Just load the profile page.""" username = login(l) if not username: l.interrupt() simulate_loading_profile_page(l) logout(l) release_user(username) l.interrupt() @task(weight=4) def change_password(l): """Change a user's password.""" user = acquire_user() if not user: l.interrupt() login(l, username=user['username'], password=user['password']) simulate_loading_profile_page(l) new_password = get_password() with l.client.post( USER_PASSWORD_CHANGE_ENDPOINT, json={ 'current_password': user['password'], 'new_password': <PASSWORD>, 'new_password_confirmation': <PASSWORD>, }, headers={ 'X-CSRF-Token': l.client.cookies['token'] }, catch_response=True) as res: if res.status_code == 200: get_db().users.find_one_and_update( {'username': user['username']}, {'$set': { 'password': <PASSWORD> }}) res.success() else: res.failure('Failed to change password: ' + \ str(res.json())) logout(l) login(l, username=user['username'], password=<PASSWORD>) logout(l) release_user(user['username']) l.interrupt() @task(weight=2) def export_account_data(l): """Export a user's account data.""" username = login(l) if not username: l.interrupt() simulate_loading_profile_page(l) l.client.get(USER_EXPORT_ENDPOINT) logout(l) release_user(username) l.interrupt() @task(weight=1) def delete_account(l): """Delete a user's account.""" user = acquire_user() if not user: l.interrupt() login(l, username=user['username'], password=user['password']) simulate_loading_profile_page(l) with l.client.post(USER_DELETE_ACCOUNT_ENDPOINT, json={ 'password': user['password'] }, headers={ 'X-CSRF-Token': l.client.cookies['token'] }, catch_response=True) as res: if res.status_code == 200: get_db().users.find_one_and_update({ 'username': user['username'] }, {'$set': {'deleted': True}}) res.success() else: res.failure('Failed to delete account: ' + str(res.json())) release_user(user['username']) l.interrupt() @task(weight=2) class TeamTasks(TaskSet): """Simulate usage of team functionality.""" @task(weight=1) def create_team(l): """Create a custom team for a user.""" user = acquire_user({ 'usertype': {'$in': ['student', 'college', 'other']}, 'on_team': {'$in': [False, None]} }) if not user: l.interrupt() login(l, username=user['username'], password=user['password']) simulate_loading_profile_page(l) team_name = get_team_name() team_password = get_password() with l.client.post(CREATE_TEAM_ENDPOINT, json={ 'team_name': team_name, 'team_password': <PASSWORD>_password }, catch_response=True) as res: if res.status_code == 201: get_db().users.find_one_and_update({ 'username': user['username'] }, {'$set': { 'on_team': True, 'team_name': team_name }}) get_db().teams.insert_one({ 'team_name': team_name, 'team_password': <PASSWORD>, 'number_of_members': 1, 'rand_id': [random.random(), 0] }) res.success() else: res.failure('Failed to create custom team: ' + str(res.json())) logout(l) release_user(user['username']) l.interrupt() @task(weight=6) def join_team(l): """Join an existing team with an open space.""" user = acquire_user({ 'usertype': {'$in': ['student', 'college', 'other']}, 'on_team': {'$in': [False, None]} }) if not user: l.interrupt() login(l, username=user['username'], password=user['password']) simulate_loading_profile_page(l) # Sometimes fails due to race condition - another thread can # push a team over the max size while trying to join it team = get_db().teams.find_one({ 'number_of_members': {'$lt': MAX_TEAM_SIZE}, 'rand_id': {'$near': [random.random(), 0]} }) if not team: l.interrupt() with l.client.post(JOIN_TEAM_ENDPOINT, json={ 'team_name': team['team_name'], 'team_password': team['team_password'] }, catch_response=True) as res: if res.status_code == 200: get_db().users.find_one_and_update({ 'username': user['username'] },
<gh_stars>1-10 import sys import time import os import re import json from collections import OrderedDict import random import urllib.parse import asyncio import aiohttp import aiohttp.web import websockets from .teamdat import Protocol, ProtoUI, Host, Channel, User from .parsematch import ParseMatch class SlackProtocol(Protocol): """The Slack protocol. """ key = 'slack' # hostclass is filled in at init time api_url = 'https://slack.com/api' auth_url = 'https://slack.com/oauth/authorize' def __init__(self, client): super().__init__(client) SlackProtocol.hostclass = SlackTeam self.protoui = SlackUI(self) self.client_id = client.opts.slack_client_id self.client_secret = client.opts.slack_client_secret self.session = None self.authtask = None self.waketask = None async def open(self): """Open web sessions for the client, and one for each team, and then load the team data. (This does not open the websockets.) """ headers = { 'user-agent': self.client.get_useragent(), } self.session = aiohttp.ClientSession(headers=headers) if self.teams: (done, pending) = await asyncio.wait([ team.open() for team in self.teams.values() ], loop=self.client.evloop) for res in done: self.print_exception(res.exception(), 'Could not set up team') self.waketask = self.client.evloop.create_task(self.wakeloop_async()) async def close(self): """Shut down all our open sessions and whatnot, in preparation for quitting. """ if self.authtask: self.authtask.cancel() self.authtask = None self.client.auth_in_progress = False if self.waketask: self.waketask.cancel() self.waketask = None if self.teams: (done, pending) = await asyncio.wait([ team.close() for team in self.teams.values() ], loop=self.client.evloop) # Ignore exceptions. if self.session: await self.session.close() self.session = None async def api_call(self, method, **kwargs): """Make a Slack API call. If kwargs contains a "token" field, this is used; otherwise, the call is unauthenticated. This is only used when authenticating to a new team. """ url = '{0}/{1}'.format(self.api_url, method) data = {} headers = {} for (key, val) in kwargs.items(): if val is None: continue if key == 'token': headers['Authorization'] = 'Bearer '+val continue data[key] = val async with self.session.post(url, headers=headers, data=data) as resp: return await resp.json() async def wakeloop_async(self): """This task runs in the background and watches the system clock. If the clock jumps more than thirty seconds, then the machine was put to sleep for a while and we need to reconnect all our websockets. (Or the user changed the clock time, in which case we don't need to reconnect all our websockets but we do it anyway. Oops.) We also ping the server(s). (This exists because the async websockets library isn't real good at announcing timeout errors. If we just wait for ConnectionClosed exceptions to appear, we could be staring at a failed socket connection for a long time -- a minute or more. So we proactively kick everything on any apparent sleep/wake cycle. The server ping should make any other timeout errors visible.) """ curtime = time.time() while True: await asyncio.sleep(5.0) elapsed = time.time() - curtime if elapsed > 30.0: async def reconnect_if_connected(team): if team.rtm_connected(): await team.rtm_connect_async() if self.teams: (done, pending) = await asyncio.wait([ reconnect_if_connected(team) for team in self.teams.values() ], loop=self.client.evloop) for res in done: self.print_exception(res.exception(), 'Could not reconnect team') # Server pings. We do this right after the time check because # that is a better way to avoid timeout errors. Now we've got # all the sockets restabilized, but timeout errors are still # possible; the pings will root them out. for team in self.teams.values(): if team.rtm_connected(): await team.rtm_send_async({ 'type':'ping', 'id':None }) # Note the time for next go-around. (Should be exactly five # seconds, but if the machine sleeps, it'll be more.) curtime = time.time() def begin_auth(self): """Launch the process of authenticating to a new Slack team. (This returns immediately.) """ if self.client.auth_in_progress or self.authtask: self.print('Already awaiting authentication callback!') return if not self.client_id: self.print('You must set --slack-client-id or $SLACK_CLIENT_ID to use the /auth command.') return if not self.client_secret: self.print('You must set --slack-client-secret or $SLACK_CLIENT_SECRET to use the /auth command.') return self.client.auth_in_progress = True self.authtask = self.client.launch_coroutine(self.perform_auth_async(), 'Begin auth') def callback(future): # This is not called if authtask is cancelled. (But it is called # if the auth's future is cancelled.) self.authtask = None self.client.auth_in_progress = False self.authtask.add_done_callback(callback) async def perform_auth_async(self): """Do the work of authenticating to a new Slack team. This is async, and it takes a while, because the user has to authenticate through Slack's web site. """ (slackurl, redirecturl, statecheck) = self.construct_auth_url(self.client.opts.auth_port, self.client_id) self.print('Visit this URL to authenticate with Slack:\n') self.print(slackurl+'\n') future = asyncio.Future(loop=self.client.evloop) # Bring up a local web server to wait for the redirect callback. # When we get it, the future will be set. server = aiohttp.web.Server(self.construct_auth_handler(future, statecheck)) sockserv = await self.client.evloop.create_server(server, 'localhost', self.client.opts.auth_port) # Wait for the callback. (With a timeout.) auth_code = None try: auth_code = await asyncio.wait_for(future, 60, loop=self.client.evloop) except asyncio.TimeoutError: self.print('URL redirect timed out.') except asyncio.CancelledError: self.print('URL redirect cancelled.') except Exception as ex: self.print_exception(ex, 'Wait for URL redirect') # We're done with the local server. await server.shutdown() sockserv.close() if not auth_code: # We were cancelled or something. return self.print('Slack authentication response received.') # We have the temporary authorization code. Now we exchange it for # a permanent access token. res = await self.api_call('oauth.access', client_id=self.client_id, client_secret=self.client_secret, code=auth_code) if not res.get('ok'): self.print('oauth.access call failed: %s' % (res.get('error'),)) return if not res.get('team_id'): self.print('oauth.access response had no team_id') return if not res.get('access_token'): self.print('oauth.access response had no access_token') return # Got the permanent token. Create a new entry for ~/.zlack-tokens. teammap = OrderedDict() teammap['_protocol'] = SlackProtocol.key for key in ('team_id', 'team_name', 'user_id', 'scope', 'access_token'): if key in res: teammap[key] = res.get(key) # Try fetching user info. (We want to include the user's name in the # ~/.zlack-tokens entry.) res = await self.api_call('users.info', token=teammap['access_token'], user=teammap['user_id']) if not res.get('ok'): self.print('users.info call failed: %s' % (res.get('error'),)) return if not res.get('user'): self.print('users.info response had no user') return user = res['user'] teammap['user_name'] = user['name'] teammap['user_real_name'] = user['real_name'] # Create a new SlackTeam entry. team = self.create_team(teammap) self.client.write_teams() await team.open() def construct_auth_url(self, authport, clientid): """Construct the URL which the user will use for authentication. Returns (slackurl, redirecturl, statestring). - slackurl: the URL which the user should enter into a browser. - redirecturl: the localhost URL which Slack will send the user back to after authenticating. - statestring: used to double-check the user's reply when it comes back. """ redirecturl = 'http://localhost:%d/' % (authport,) statecheck = 'state_%d' % (random.randrange(1000000),) params = [ ('client_id', clientid), ('scope', 'client'), ('redirect_uri', redirecturl), ('state', statecheck), ] queryls = [ '%s=%s' % (key, urllib.parse.quote(val)) for (key, val) in params ] tup = list(urllib.parse.urlparse(self.auth_url)) tup[4] = '&'.join(queryls) slackurl = urllib.parse.urlunparse(tup) return (slackurl, redirecturl, statecheck) class SlackUI(ProtoUI): """This module translates between the UI (human-readable input and output) and the protocol (with its protocol-specific messages). """ pat_user_id = re.compile('@([a-z0-9._]+)', flags=re.IGNORECASE) pat_channel_id = re.compile('#([a-z0-9_-]+)', flags=re.IGNORECASE) pat_encoded_user_id = re.compile('<@([a-z0-9_]+)>', flags=re.IGNORECASE) pat_encoded_channel_id = re.compile('<#([a-z0-9_]+)([|][a-z0-9_-]*)?>', flags=re.IGNORECASE) def send_message(self, text, team, chanid): """Send a message to the given team and channel. (This returns immediately.) """ etext = self.encode_message(team, text) team.rtm_send({ 'type':'message', 'id':None, 'user':team.user_id, 'channel':chanid, 'text':etext }) def encode_message(self, team, val): """Encode a human-typed message into standard Slack form. """ val = val.replace('&', '&amp;') val = val.replace('<', '&lt;') val = val.replace('>', '&gt;') # We try to locate @displayname references and convert them to # <@USERID>. val = self.pat_user_id.sub(lambda match:self.encode_exact_user_id(team, match), val) val = self.pat_channel_id.sub(lambda match:self.encode_exact_channel_id(team, match), val) return val def encode_exact_user_id(self, team, match): """Utility function used by encode_message. Given a match object from pat_user_id, return a <@USERID> substitution. If the match doesn't exactly match a user display name, we return the original string. """ orig = match.group(0) # '@name' val = match.group(1) # 'name' if val not in team.users_by_display_name: return orig return '<@' + team.users_by_display_name[val].id + '>' def encode_exact_channel_id(self, team, match): """Utility function used by encode_message. Given a match object from pat_channel_id, return a <#CHANID> substitution. If the match doesn't exactly match a channel name, we return the original string. """ orig = match.group(0) # '#channel' val = match.group(1) # 'channel' if val not in team.channels_by_name: return orig return '<#' + team.channels_by_name[val].id + '>' def handle_message(self, msg, team): """Handle one message received from the Slack server
3.0, 4.0, 5.0, 6.0, 7.0, 9.969209968386869e36, 9.969209968386869e36, ], [ 0.5, 1.5, 2.5, 3.5, 4.5, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [-2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0], ], units="days since 1970-01-01 00:00:00", dtype="f8", mask=data_mask, ) c.set_data(data) b = Bounds() data_mask = Data( [ [ [False, False], [False, False], [False, False], [True, True], [True, True], [True, True], [True, True], [True, True], [True, True], ], [ [False, False], [False, False], [False, False], [False, False], [False, False], [False, False], [False, False], [True, True], [True, True], ], [ [False, False], [False, False], [False, False], [False, False], [False, False], [True, True], [True, True], [True, True], [True, True], ], [ [False, False], [False, False], [False, False], [False, False], [False, False], [False, False], [False, False], [False, False], [False, False], ], ], dtype="b1", ) data = Data( [ [ [-3.5, -2.5], [-2.5, -1.5], [-1.5, -0.5], [9.969209968386869e36, 9.969209968386869e36], [9.969209968386869e36, 9.969209968386869e36], [9.969209968386869e36, 9.969209968386869e36], [9.969209968386869e36, 9.969209968386869e36], [9.969209968386869e36, 9.969209968386869e36], [9.969209968386869e36, 9.969209968386869e36], ], [ [0.5, 1.5], [1.5, 2.5], [2.5, 3.5], [3.5, 4.5], [4.5, 5.5], [5.5, 6.5], [6.5, 7.5], [9.969209968386869e36, 9.969209968386869e36], [9.969209968386869e36, 9.969209968386869e36], ], [ [0.0, 1.0], [1.0, 2.0], [2.0, 3.0], [3.0, 4.0], [4.0, 5.0], [9.969209968386869e36, 9.969209968386869e36], [9.969209968386869e36, 9.969209968386869e36], [9.969209968386869e36, 9.969209968386869e36], [9.969209968386869e36, 9.969209968386869e36], ], [ [-2.5, -1.5], [-1.5, -0.5], [-0.5, 0.5], [0.5, 1.5], [1.5, 2.5], [2.5, 3.5], [3.5, 4.5], [4.5, 5.5], [5.5, 6.5], ], ], units="days since 1970-01-01 00:00:00", dtype="f8", mask=data_mask, ) b.set_data(data) c.set_bounds(b) f.set_construct( c, axes=("domainaxis0", "domainaxis1"), key="auxiliarycoordinate0", copy=False, ) # auxiliary_coordinate c = AuxiliaryCoordinate() c.set_properties( { "standard_name": "latitude", "long_name": "station latitude", "units": "degrees_north", } ) c.nc_set_variable("lat") data = Data([-9.0, 2.0, 34.0, 78.0], units="degrees_north", dtype="f8") c.set_data(data) f.set_construct( c, axes=("domainaxis0",), key="auxiliarycoordinate1", copy=False ) # auxiliary_coordinate c = AuxiliaryCoordinate() c.set_properties( { "standard_name": "longitude", "long_name": "station longitude", "units": "degrees_east", } ) c.nc_set_variable("lon") data = Data( [-23.0, 0.0, 67.0, 178.0], units="degrees_east", dtype="f8" ) c.set_data(data) f.set_construct( c, axes=("domainaxis0",), key="auxiliarycoordinate2", copy=False ) # auxiliary_coordinate c = AuxiliaryCoordinate() c.set_properties( { "long_name": "vertical distance above the surface", "standard_name": "height", "units": "m", "positive": "up", "axis": "Z", } ) c.nc_set_variable("alt") data = Data([0.5, 12.6, 23.7, 345.0], units="m", dtype="f8") c.set_data(data) f.set_construct( c, axes=("domainaxis0",), key="auxiliarycoordinate3", copy=False ) # auxiliary_coordinate c = AuxiliaryCoordinate() c.set_properties( {"long_name": "station name", "cf_role": "timeseries_id"} ) c.nc_set_variable("station_name") data = Data( [b"station1", b"station2", b"station3", b"station4"], dtype="S8" ) c.set_data(data) f.set_construct( c, axes=("domainaxis0",), key="auxiliarycoordinate4", copy=False ) # auxiliary_coordinate c = AuxiliaryCoordinate() c.set_properties({"long_name": "station information"}) c.nc_set_variable("station_info") data = Data([-10, -9, -8, -7], dtype="i4") c.set_data(data) f.set_construct( c, axes=("domainaxis0",), key="auxiliarycoordinate5", copy=False ) elif n == 4: f = Field() f.set_properties( { "Conventions": "CF-" + CF(), "featureType": "timeSeriesProfile", "_FillValue": -999.9, "standard_name": "air_temperature", "units": "K", } ) f.nc_set_variable("ta") f.nc_set_global_attribute("Conventions", None) f.nc_set_global_attribute("featureType", None) # domain_axis c = DomainAxis(size=3) c.nc_set_dimension("station") f.set_construct(c, key="domainaxis0") # domain_axis c = DomainAxis(size=26) c.nc_set_dimension("timeseries") f.set_construct(c, key="domainaxis1") # domain_axis c = DomainAxis(size=4) c.nc_set_dimension("profile_1") f.set_construct(c, key="domainaxis2") # field data data_mask = Data( [ [ [False, True, True, True], [False, False, False, True], [False, False, True, True], [False, False, True, True], [False, False, True, True], [False, True, True, True], [False, False, True, True], [False, True, True, True], [False, True, True, True], [False, False, True, True], [False, False, False, True], [False, False, True, True], [True, True, True, True], [True, True, True, True], [True, True, True, True], [True, True, True, True], [True, True, True, True], [True, True, True, True], [True, True, True, True], [True, True, True, True], [True, True, True, True], [True, True, True, True], [True, True, True, True], [True, True, True, True], [True, True, True, True], [True, True, True, True], ], [ [False, False, False, False], [False, False, True, True], [False, False, True, True], [False, True, True, True], [False, False, True, True], [False, False, True, True], [False, False, True, True], [False, True, True, True], [False, False, False, True], [False, False, False, True], [False, False, False, True], [False, False, False, True], [False, True, True, True], [False, False, False, True], [False, False, True, True], [False, True, True, True], [False, True, True, True], [False, True, True, True], [False, False, True, True], [False, False, False, True], [False, False, False, True], [False, False, True, True], [False, True, True, True], [False, False, True, True], [False, False, False, True], [False, False, False, True], ], [ [False, True, True, True], [False, False, False, True], [False, False, False, True], [False, False, False, True], [False, False, True, True], [False, False, True, True], [False, True, True, True], [False, True, True, True], [False, False, True, True], [False, False, False, True], [False, False, False, True], [False, False, True, True], [False, False, False, True], [False, True, True, True], [False, True, True, True], [False, False, True, True], [False, False, True, True], [False, False, False, True], [False, True, True, True], [False, True, True, True], [True, True, True, True], [True, True, True, True], [True, True, True, True], [True, True, True, True], [True, True, True, True], [True, True, True, True], ], ], dtype="b1", ) data = Data( [ [ [ 290.0, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [293.15, 288.84, 280.0, 9.969209968386869e36], [ 291.65, 285.0, 9.969209968386869e36, 9.969209968386869e36, ], [ 290.45, 286.14, 9.969209968386869e36, 9.969209968386869e36, ], [290.0, 285.0, 9.969209968386869e36, 9.969209968386869e36], [ 290.0, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [ 291.65, 288.57, 9.969209968386869e36, 9.969209968386869e36, ], [ 290.0, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [ 293.27, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [290.0, 285.0, 9.969209968386869e36, 9.969209968386869e36], [293.36, 285.99, 285.46, 9.969209968386869e36], [ 291.2, 285.96, 9.969209968386869e36, 9.969209968386869e36, ], [ 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [ 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [ 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [ 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [ 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [ 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [ 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [ 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [ 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [ 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [ 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [ 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [ 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [ 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], ], [ [291.74, 285.72, 283.21, 275.0], [290.0, 285.0, 9.969209968386869e36, 9.969209968386869e36], [290.0, 285.0, 9.969209968386869e36, 9.969209968386869e36], [ 290.15, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [ 291.08, 285.0, 9.969209968386869e36, 9.969209968386869e36, ], [ 291.32, 288.66, 9.969209968386869e36, 9.969209968386869e36, ], [ 290.0, 294.18, 9.969209968386869e36, 9.969209968386869e36, ], [ 290.0, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [290.0, 286.05, 280.0, 9.969209968386869e36], [291.23, 285.0, 281.11, 9.969209968386869e36], [295.88, 286.83, 285.01, 9.969209968386869e36], [292.37, 285.6, 280.0, 9.969209968386869e36], [ 290.0, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [300.11, 285.0, 280.0, 9.969209968386869e36], [290.0, 287.4, 9.969209968386869e36, 9.969209968386869e36], [ 290.0, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [ 291.5, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [ 290.0, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [ 294.98, 290.64, 9.969209968386869e36, 9.969209968386869e36, ], [290.66, 292.92, 280.0, 9.969209968386869e36], [290.24, 285.36, 280.36, 9.969209968386869e36], [290.0, 285.0, 9.969209968386869e36, 9.969209968386869e36], [ 290.0, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [ 292.79, 285.0, 9.969209968386869e36, 9.969209968386869e36, ], [290.0, 287.22, 280.0, 9.969209968386869e36], [290.0, 286.14, 280.0, 9.969209968386869e36], ], [ [ 291.74, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [291.44, 287.25, 280.0, 9.969209968386869e36], [292.76, 285.0, 280.0, 9.969209968386869e36], [291.59, 286.71, 284.47, 9.969209968386869e36], [ 292.19, 286.35, 9.969209968386869e36, 9.969209968386869e36, ], [ 295.67, 285.0, 9.969209968386869e36, 9.969209968386869e36, ], [ 290.0, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [ 290.45, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [290.0, 285.0, 9.969209968386869e36, 9.969209968386869e36], [293.69, 285.9, 280.03, 9.969209968386869e36], [290.0, 285.27, 280.87, 9.969209968386869e36], [290.0, 285.0, 9.969209968386869e36, 9.969209968386869e36], [290.12, 286.44, 282.01, 9.969209968386869e36], [ 291.23, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [ 292.97, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [ 290.0, 286.71, 9.969209968386869e36, 9.969209968386869e36, ], [ 292.01, 285.0, 9.969209968386869e36, 9.969209968386869e36, ], [294.62, 285.33, 282.01, 9.969209968386869e36], [ 290.0, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [ 292.64, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [ 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [ 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [ 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [ 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [ 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], [ 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, 9.969209968386869e36, ], ], ], units="K", dtype="f8", mask=data_mask, ) f.set_data(data, axes=("domainaxis0", "domainaxis1", "domainaxis2")) # auxiliary_coordinate c = AuxiliaryCoordinate() c.set_properties( { "standard_name": "time", "long_name": "time", "units": "days since 1970-01-01 00:00:00", } ) c.nc_set_variable("time") data_mask = Data( [ [ False, False, False, False, False, False, False, False, False, False, False, False, True, True, True, True, True, True, True, True, True, True, True, True, True, True, ], [ False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, ], [ False, False,
#!/usr/bin/env python3 #Local Func from data import aquasettings, keystore from data.aquachain import AquaTool #Core Func import binascii from Crypto.PublicKey import RSA import datetime import math import os from os import chmod import requests, json import subprocess from subprocess import Popen, PIPE, STDOUT import sys import time from mnemonic import Mnemonic #Kivy Func from kivy import Logger from kivymd.app import MDApp from kivy.animation import Animation from kivy.base import runTouchApp from kivy.clock import Clock from kivy.config import Config from kivy.core.clipboard import Clipboard from kivy.core.window import Window from kivy.factory import Factory from kivy.graphics import Ellipse, Rectangle from kivy.lang import Builder from kivy.metrics import dp from kivy.properties import ListProperty, StringProperty, OptionProperty, ObjectProperty, NumericProperty from kivy.properties import BoundedNumericProperty, ReferenceListProperty, BooleanProperty from kivy.uix.anchorlayout import AnchorLayout from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button from kivy.uix.behaviors import ButtonBehavior from kivy.uix.dropdown import DropDown from kivy.uix.floatlayout import FloatLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.image import Image from kivy.uix.popup import Popup from kivy.uix.recycleboxlayout import RecycleBoxLayout from kivy.uix.screenmanager import ScreenManager, Screen from kivy.uix.scrollview import ScrollView from kivy.uix.settings import SettingsWithSidebar from kivy.uix.textinput import TextInput from kivy.uix.tabbedpanel import TabbedPanel, TabbedPanelItem #KivyMD Func from kivymd.material_resources import DEVICE_TYPE import kivymd.material_resources as m_res from kivymd.theming import ThemeManager, ThemableBehavior from kivymd.uix.behaviors.backgroundcolorbehavior import SpecificBackgroundColorBehavior from kivymd.uix.behaviors.elevation import RectangularElevationBehavior from kivymd.uix.bottomsheet import MDListBottomSheet, MDGridBottomSheet from kivymd.uix.boxlayout import MDBoxLayout from kivymd.uix.button import MDFlatButton, MDRaisedButton, MDIconButton, MDRectangleFlatButton from kivymd.uix.dialog import MDDialog from kivymd.uix.gridlayout import MDGridLayout from kivymd.uix.label import MDLabel from kivymd.uix.list import ILeftBody, IRightBody, OneLineListItem, TwoLineListItem, MDList from kivymd.uix.card import MDCard, MDSeparator from kivymd.uix.navigationdrawer import MDNavigationDrawer from kivymd.uix.screen import MDScreen from kivymd.uix.selectioncontrol import MDCheckbox from kivymd.uix.snackbar import Snackbar from kivymd.uix.textfield import MDTextField from kivymd.uix.toolbar import MDToolbar #Define Local Settings aquachain_assets = 'data' Builder.load_file(os.path.join(aquachain_assets, 'aquachain.kv')) aquaconf = 'Aquachain' # the string log = Logger class IconLeftWidget(ILeftBody, MDIconButton): pass class IconLeftWidget(IRightBody, MDIconButton): pass #Kivy MDApp Class class Aquachain(MDBoxLayout): # account chooser choose_account = [] # account for send from and mine to coinbase = "" # public address for balance, recv. # if sending, use either mkeys or an rpc call addresses = [] # map of account balances balances = {} # total balance sum balance = 0.00 # current head block head = {} # private key storage private_keys = {} # history of sent transactions sent_tx = [] synced = False #saved contacts placeholder contacts = {"saved": {'0x6086337ac44cdde1eeab5b539e6d1f69a7ca9133': 'donate'}} #recent tx placeholder recent = {"recent": []} #config bug fix config = Config #List of Loaded Seed Phrases mkeys = [] viewonly = True def __init__(self, app, **kwargs): super(Aquachain, self).__init__(**kwargs) self.theme_cls = ThemeManager() self.theme_cls.theme_style = "Dark" self.theme_cls.primary_palette = 'Teal' self.theme_cls.primary_hue = '400' self.theme_cls.primary_dark_hue = '200' self.theme_cls.accent_palette = 'Red' self.theme_cls.accent_hue = '400' self.theme_cls.main_background_color = 'Grey 900' self.root = app self.config = app.config self.aqua = AquaTool(ipcpath=self.config.get(aquaconf, 'ipcpath'), rpchost=self.config.get(aquaconf, 'rpchost')) self.ids.balance.text = 'Click to Show' Clock.schedule_once(self.start_refresher, 1) self.block_cache = self.getblock_cache() # unused self.keystore = keystore.Keystore(directory=os.path.expanduser(self.config.getdefault(aquaconf, 'keystore', '.'))) # pubkey to filename log.info("using keystore: %s", self.keystore.directory) def start_refresher(self, dt): self.clock = Clock.schedule_interval(self.refresh_block, float(self.config.getdefault(aquaconf, 'noderefresh', '2.5'))) def refresh_block(self, dt): log.debug("refreshing after %s seconds", dt) self.update() def getblock_cache(self): foo = [] for i in range(self.config.getdefaultint(aquaconf, 'blocklimit', 100)): foo.append({}) log.info(f"allocated {len(foo)}") return foo # get latest head block def update(self): log.debug("connecting to rpc: %s", self.aqua.providers[0]) try: newhead = self.aqua.gethead() log.debug("connected to rpc: %s", self.aqua.providers[0]) except Exception as e: Snackbar(text="Please start aquachain node or change host in settings", duration=0.5).show() log.info("unable to connect to rpc: %s", e) return if 'number' not in newhead: del(newhead) log.error("no head block") return if newhead == None or newhead == '': del(newhead) log.error("no head block!") return if 'number' in self.head and self.head['number'] == newhead['number']: del(newhead) log.debug("same head, bailing") return log.info("new head block") self.head = newhead if self.ids.scr_mngr.current == 'blockchain': self.getHistory(self.config.getdefaultint(aquaconf, 'blocklimit', 20)) if not self.synced: self.getHistory(self.config.getdefaultint(aquaconf, 'blocklimit', 20)) self.synced = True del(newhead) Snackbar(text=f"New blockchain height: {str(int(self.head['number'], 16))}").show() if 'number' in self.head: log.info("new head number %s", str(int(self.head['number'], 16))) log.info("header hash %s", self.head['hash']) log.info("header mined by %s", self.head['miner']) log.info("header version %s", self.head['version']) self.ids.block.text = str(int(self.head['number'], 16)) #addresses are only rpc addresses def load_accounts_from_node(self): self.addresses.clear() self.addresses = self.aqua.getaccounts() Snackbar(text=f'found {len(self.addresses)} accounts from RPC').show() return def toggle_display_balance(self, text): if len(self.addresses) == 0 and len(self.balances) == 0: Snackbar(text="Open an account first", duration=1).show() return 'Click to Show' if text == 'Click to Show': self.refresh_balance() return str(self.balance) else: return 'Click to Show' def getblock_cache(self): foo = [] for i in range(self.config.getdefaultint(aquaconf, 'blocklimit', 100)): foo.append({}) log.info(f"allocated {len(foo)}") return foo def open_account(self, viewonly=False): self.viewonly = viewonly if self.ids.account_use_import.active == True: self.popup_import_mnem() elif self.ids.account_use_new.active == True: self.popup_mnem_gen() elif self.ids.account_use_file.active == True: self.popup_import_directory(viewonly=viewonly) elif self.ids.account_use_node.active: self.load_accounts_from_node() self.switch_view("coinbasechooser", "up") else: Snackbar(text="Oops you forgot to check one.").show() log.info(self.ids.account_use_new.active) def add_hdwallet(self, phrase, saving=True, num=1, viewonly=False): phrase = phrase.strip() words = phrase.split(" ") if len(words) != 12: log.error("invalid phrase length: %s \n", len(phrase.split(" "))) Snackbar(text="Phrase empty or invalid!").show() return for word in words: if word not in Mnemonic('english').wordlist: raise ValueError(f"invalid word: {word}") log.info("add_wallet: %s, saving=%s", words[0], saving) mkey = self.keystore.load_phrase(phrase) for existing in self.mkeys: if existing['phrase'] == phrase: log.info("dupe detect") Snackbar(text="Duplicate Wallet! Action Aborted!").show() return if saving: self.keystore.save_phrase(phrase) if not viewonly: self.mkeys.append({'phrase': phrase, "key": mkey}) log.debug("added mkey (not viewonly)") for i in range(num): key = self.aqua.derive_hd(mkey, i) pub = key.public_key.address() log.info("added pubkey from mkey %s", pub) self.balances[pub] = self.aqua.getbalance(pub) log.info("New account #%s: %s", i, key.public_key.address()) self.refresh_balance() def popup_mnem_gen(self): content = MDGridLayout(cols=1) phrase = self.aqua.generate_phrase() mnem = MDTextField( multiline=True, text=phrase, hint_text="Seed Phrase", required=False ) content.size_hint_y=None content.add_widget(mnem) def refresh(instance): mnem.text = self.aqua.generate_phrase() log.info(mnem.text) return True def copy2clip(instance): log.info(mnem.text) Clipboard.copy(mnem.text) Snackbar(text="Copied to clipboard!").show() def create(instance): log.info(mnem.text) self.add_hdwallet(mnem.text, num=self.config.getdefaultint(aquaconf, 'hdwallets', 1)) dialog.dismiss() self.switch_view('coinbasechooser', 'up') dialog = MDDialog(title="[color=008080]Write down this phrase or generate new[/color]", type="custom", content_cls=content, size_hint=(.8, .8), auto_dismiss=False, buttons=[ MDFlatButton( text="CANCEL", text_color=self.theme_cls.accent_color, on_release=lambda *x: dialog.dismiss() ), MDFlatButton( text="GENERATE", text_color=self.theme_cls.primary_color, on_release=refresh ), MDFlatButton( text="COPY", text_color=self.theme_cls.primary_color, on_release=copy2clip ), MDFlatButton( text="CREATE", text_color=self.theme_cls.primary_color, on_release=create )] ) dialog.open() def popup_import_file(self, viewonly=False): return self.popup_import_directory(viewonly=viewonly) def popup_import_directory(self, viewonly=False): self.findkey(viewonly=viewonly) def findkey(self, viewonly=False): self.keystore.directory = self.config.get(aquaconf, 'keystore') content = MDGridLayout(cols=1, size_hint_y=None, row_default_height=dp(35)) keylist = MDList(valign='top') keydrop = DropDown() content.add_widget(keylist) phrases = keystore.Keystore(directory=self.keystore.directory).listphrases() keys = [] phrase = '' i=0 for p in phrases: keys.append(p.split()[0]) phrase = p for key in keys: log.debug(key) listitem = MDRaisedButton(text=key.capitalize(), size_hint=(1,None)) listitem.bind(on_release=lambda listitem: keydrop.select(listitem.text)) keydrop.add_widget(listitem) if keys == []: mainbutton = OneLineListItem(text='CREATE OR IMPORT A SEED', font_style='Subtitle1') else: mainbutton = OneLineListItem(text='SELECT A WALLET', font_style='Subtitle1') def doit(y): setattr(mainbutton, 'text', y) mainbutton.bind(on_release=keydrop.open) keydrop.bind(on_select=lambda instance, x: doit(x)) keylist.add_widget(mainbutton) def getkey(instance): phrase = '' for t in phrases: if mainbutton.text.lower() in t: phrase = t self.add_hdwallet(phrase, saving=False, viewonly=viewonly, num=self.config.getdefaultint(aquaconf, 'hdwallets', 1)) popdialog.dismiss() self.switch_view('coinbasechooser', 'up') popdialog = MDDialog(title="[color=008080]Which key would you like to import?[/color]", type="custom", content_cls=content, size_hint=(.55,.6), auto_dismiss=False, buttons=[ MDFlatButton( text='CANCEL', theme_text_color= "Custom", text_color= self.theme_cls.accent_color, on_release=lambda *x: popdialog.dismiss() ), MDFlatButton( text='UNLOCK', theme_text_color= "Custom", text_color= self.theme_cls.primary_color, on_release=getkey ) ] ) popdialog.open() def popup_import_mnem(self, viewonly=False): def findmnem(instance): try: self.add_hdwallet( mnem.text, saving=saving_choice.active, viewonly=viewonly, num=self.config.getdefaultint( aquaconf, 'hdwallets', 1 ) ) except Exception as oo: Snackbar(text=f"Error: {oo}", duration=5).show() dialog.dismiss() return dialog.dismiss() self.switch_view('coinbasechooser', 'up') content = MDGridLayout(cols=1) mnem = MDTextField() mnem.hint_text = "Enter Seed" mnem.helper_text= "Enter Seed" chex = BoxLayout() saving_choice = MDCheckbox( text="Save to File", active=True, size_hint= (None,None), size= (dp(34),dp(48)) ) saving_label = MDLabel( theme_text_color = "Primary", text = "Save to file", font_style = 'Body2' ) chex.add_widget(saving_choice) chex.add_widget(saving_label) content.add_widget(mnem) content.add_widget(chex) dialog = MDDialog( title="[color=008080]Enter mnemonic phrase to recover key[/color]", type="custom", content_cls=content, auto_dismiss=False, buttons=[ MDFlatButton( text="CANCEL", theme_text_color= "Custom", text_color= self.theme_cls.accent_color, on_release=lambda *x: dialog.dismiss() ), MDFlatButton( text="IMPORT", theme_text_color= "Custom", text_color= self.theme_cls.primary_color, on_release=findmnem ) ] ) dialog.open() # set new coinbase def set_coinbase(self, acct): self.coinbase = acct log.info("New coinbase is: %s",format(self.coinbase)) def send_confirm(self, fromwallet, to, amount): content = GridLayout(cols= 1) contents = MDLabel( text="Sending " + amount + "AQUA to " + to, theme_text_color="Primary", font_style="Subtitle2" ) content.add_widget(contents) def sendcoin(instance): if len(to) != 42: if to[:2] != "0x": Snackbar(text="Address must begin with '0x'").show() return Snackbar(text="Invalid Address!").show() return self.sendCoin(fromwallet, to, amount) log.info("CONFIRM") dialog.dismiss() return dialog = MDDialog( title="[color=008080]Are you sure?[/color]", type="custom", content_cls=content, auto_dismiss=False, buttons=[ MDFlatButton( text="CANCEL TX", theme_text_color= "Custom", text_color= self.theme_cls.accent_color, on_release=lambda x: dialog.dismiss() ), MDRectangleFlatButton( text="CONFIRM", on_release=sendcoin ) ] ) dialog.open() # fill account chooser menu (address and balance) def fillMenu(self): self.ids.newlist.clear_widgets() dropdown = DropDown() accounts = [] #if len(self.addresses) > 0: # for acct in self.aqua.getaccounts(): # accounts.append(acct) for acct in self.balances: accounts.append(acct) # check no accounts if len(accounts) < 1: log.error("no accounts found. you must create a new account.") self.choose_account = [] return # check already filled if len(self.choose_account) == len(accounts): log.debug("already filled, not refilling menu") return self.refresh_balance() self.choose_account = [] # fill menu
,band ,stokes ,f_datapoints ,avg_f_peak ,avg_f_peak_sq ,avg_f_peak_weight ,avg_weighted_f_peak ,avg_weighted_f_peak_sq ,avg_f_int ,avg_f_int_sq ,avg_f_int_weight ,avg_weighted_f_int ,avg_weighted_f_int_sq ) SELECT r.id ,tmprc.band ,tmprc.stokes ,tmprc.f_datapoints ,avg_f_peak ,avg_f_peak_sq ,avg_f_peak_weight ,avg_weighted_f_peak ,avg_weighted_f_peak_sq ,avg_f_int ,avg_f_int_sq ,avg_f_int_weight ,avg_weighted_f_int ,avg_weighted_f_int_sq FROM (SELECT runcat FROM temprunningcatalog WHERE inactive = FALSE GROUP BY runcat HAVING COUNT(*) > 1 ) one_to_many ,temprunningcatalog tmprc ,runningcatalog r WHERE tmprc.runcat = one_to_many.runcat AND tmprc.inactive = FALSE AND r.xtrsrc = tmprc.xtrsrc """ tkp.db.execute(query, commit=True) def _insert_1_to_many_basepoint_assocxtrsource(): """Insert 'base points' for one-to-many associations Before continuing, we have to insert the 'base points' of the associations, i.e. the links between the new runningcatalog entries and their associated (new) extractedsources. We also calculate the variability indices at the timestamp of the the current image. """ # NB we pull the new runcat id from the runningcatalog by matching with # temprunningcatalog via xtrsrc. (temprunningcatalog.runcat points at old # runcat entries). query = """\ INSERT INTO assocxtrsource (runcat ,xtrsrc ,type ,distance_arcsec ,r ,v_int ,eta_int ,f_datapoints ) SELECT t0.new_runcat_id ,t0.xtrsrc ,2 ,t0.distance_arcsec ,t0.r ,t0.v_int_inter / t0.avg_f_int ,t0.eta_int_inter / t0.avg_f_int_weight ,t0.f_datapoints FROM (SELECT runcat.id AS new_runcat_id ,tmprc.xtrsrc ,tmprc.distance_arcsec ,tmprc.r ,tmprc.f_datapoints ,CASE WHEN tmprc.avg_f_int = 0.0 THEN 0.000001 ELSE avg_f_int END AS avg_f_int ,tmprc.avg_f_int_weight ,CASE WHEN tmprc.f_datapoints = 1 THEN 0 ELSE CASE WHEN ABS(tmprc.avg_f_int_sq - tmprc.avg_f_int * tmprc.avg_f_int) < 8e-14 THEN 0 ELSE SQRT(CAST(tmprc.f_datapoints AS DOUBLE PRECISION) * (tmprc.avg_f_int_sq - tmprc.avg_f_int * tmprc.avg_f_int) / (CAST(tmprc.f_datapoints AS DOUBLE PRECISION) - 1.0) ) END END AS v_int_inter ,CASE WHEN tmprc.f_datapoints = 1 THEN 0 ELSE (CAST(tmprc.f_datapoints AS DOUBLE PRECISION) / (CAST(tmprc.f_datapoints AS DOUBLE PRECISION) - 1.0)) * (tmprc.avg_f_int_weight * tmprc.avg_weighted_f_int_sq - tmprc.avg_weighted_f_int * tmprc.avg_weighted_f_int) END AS eta_int_inter FROM (SELECT runcat as old_runcat_id FROM temprunningcatalog WHERE inactive = FALSE GROUP BY runcat HAVING COUNT(*) > 1 ) one_to_many ,temprunningcatalog tmprc ,runningcatalog runcat WHERE tmprc.runcat = one_to_many.old_runcat_id AND tmprc.inactive = FALSE AND runcat.xtrsrc = tmprc.xtrsrc ) t0 """ tkp.db.execute(query, commit=True) def _insert_1_to_many_replacement_assocxtrsource(): """Insert links into the association table between the new runcat entries and the old extractedsources. (New to New ('basepoint') links have been added earlier). In this case, new entries in the runningcatalog and runningcatalog_flux were already added (for every extractedsource one), which will replace the existing ones in the runningcatalog. Therefore, we have to update the references to these new ids as well. So, we will append to assocxtrsource and delete the entries from runningcatalog_flux. NOTE: 1. We do not update the distance_arcsec and r values of the pairs. TODO: 1. Why not? """ # NB we pull the new runcat id from the runningcatalog by matching with # temprunningcatalog via xtrsrc. (temprunningcatalog.runcat points at old # runcat entries). query = """\ INSERT INTO assocxtrsource (runcat ,xtrsrc ,type ,distance_arcsec ,r ,v_int ,eta_int ,f_datapoints ) SELECT r.id AS new_runcat_id ,a.xtrsrc ,6 ,a.distance_arcsec ,a.r ,a.v_int ,a.eta_int ,a.f_datapoints FROM (SELECT runcat as old_runcat_id FROM temprunningcatalog WHERE inactive = FALSE GROUP BY runcat HAVING COUNT(*) > 1 ) one_to_many ,temprunningcatalog tmprc ,runningcatalog r ,assocxtrsource a WHERE tmprc.runcat = one_to_many.old_runcat_id AND tmprc.inactive = FALSE AND r.xtrsrc = tmprc.xtrsrc AND a.runcat = tmprc.runcat """ tkp.db.execute(query, commit=True) def _insert_1_to_many_assocskyrgn(): """ Copy skyregion associations from old runcat entries for new one-to-many runningcatalog entries. """ # NB we pull the new runcat id from the runningcatalog by matching with # temprunningcatalog via xtrsrc. (temprunningcatalog.runcat points at old # runcat entries). query = """\ INSERT INTO assocskyrgn (runcat ,skyrgn ,distance_deg ) SELECT r.id AS new_runcat_id ,a.skyrgn ,a.distance_deg FROM (SELECT runcat as old_runcat_id FROM temprunningcatalog WHERE inactive = FALSE GROUP BY runcat HAVING COUNT(*) > 1 ) one_to_many ,temprunningcatalog tmprc ,runningcatalog r ,assocskyrgn a WHERE tmprc.runcat = one_to_many.old_runcat_id AND tmprc.inactive = FALSE AND r.xtrsrc = tmprc.xtrsrc AND a.runcat = tmprc.runcat """ tkp.db.execute(query, commit=True) def _insert_1_to_many_newsource(): """Update the runcat id for the one-to-many associations, and delete the newsource entries of the old runcat id (the new ones have been added earlier). In this case, new entries in the runningcatalog and runningcatalog_flux were already added (for every extractedsource one), which will replace the existing ones in the runningcatalog. Therefore, we have to update the references to these new ids as well. """ query = """\ INSERT INTO newsource (runcat ,trigger_xtrsrc ,newsource_type ,previous_limits_image ) SELECT r.id as new_runcat_id ,tr.trigger_xtrsrc ,tr.newsource_type ,tr.previous_limits_image FROM (SELECT runcat as old_runcat_id FROM temprunningcatalog WHERE inactive = FALSE GROUP BY runcat HAVING COUNT(*) > 1 ) one_to_many ,temprunningcatalog tmprc ,runningcatalog r ,newsource tr WHERE tmprc.runcat = one_to_many.old_runcat_id AND tmprc.inactive = FALSE AND tr.runcat = one_to_many.old_runcat_id AND r.xtrsrc = tmprc.xtrsrc """ tkp.db.execute(query, commit=True) def _delete_1_to_many_inactive_assocskyrgn(): """Delete the assocskyrgn links of the old runcat Since we replaced this runcat.id with multiple new ones, we now delete the old links. """ query = """\ DELETE FROM assocskyrgn WHERE runcat IN (SELECT runcat FROM temprunningcatalog WHERE inactive = FALSE GROUP BY runcat HAVING COUNT(*) > 1 ) """ tkp.db.execute(query, commit=True) def _delete_1_to_many_inactive_newsource(): """Delete the newsource sources of the old runcat Since we replaced this runcat.id with multiple new ones, we now delete the old one. """ query = """\ DELETE FROM newsource WHERE runcat IN (SELECT runcat FROM temprunningcatalog WHERE inactive = FALSE GROUP BY runcat HAVING COUNT(*) > 1 ) """ tkp.db.execute(query, commit=True) def _delete_1_to_many_inactive_assocxtrsource(): """Delete the association pairs of the old runcat from assocxtrsource NOTE: It might sound confusing, but those are not qualified as inactive in tempruncat (read below). Since we replaced this runcat.id with multiple new one, we first flag it as inactive, after which we delete it from the runningcatalog The subselect selects those valid "old" runcat ids (i.e., the ones that were not set to inactive for the many-to-many associations). NOTE: We do not have to flag these rows as inactive, no furthr processing depends on these in the assoc run """ #NB temprunningcatalog 'runcat' field still refers to old, #superceded runcat entries. query = """\ DELETE FROM assocxtrsource WHERE runcat IN (SELECT runcat FROM temprunningcatalog WHERE inactive = FALSE GROUP BY runcat HAVING COUNT(*) > 1 ) """ tkp.db.execute(query, commit=True) def _delete_1_to_many_inactive_runcat_flux(): """Flag the old runcat ids in the runningcatalog to inactive Since we replaced this runcat.id with multiple new one, we first flag it as inactive, after which we delete it from the runningcatalog """ query = """\ DELETE FROM runningcatalog_flux WHERE runcat IN (SELECT runcat FROM temprunningcatalog WHERE inactive = FALSE GROUP BY runcat HAVING COUNT(*) > 1 ) """ tkp.db.execute(query, commit=True) def _flag_1_to_many_inactive_runcat(): """Flag the old runcat ids in the runningcatalog to inactive We do not delete them yet, because we still need to clear up all the superseded entries in assocskyrgn, etc. """ query = """\ UPDATE runningcatalog SET inactive = TRUE WHERE id IN (SELECT runcat FROM temprunningcatalog WHERE inactive = FALSE GROUP BY runcat HAVING COUNT(*) > 1 ) """ tkp.db.execute(query, commit=True) def _flag_1_to_many_inactive_tempruncat(): """ Flag the one-to-many associations from temprunningcatalog. (Since we are done processing them, now.) We do not delete them yet- if we did, we would not be able to cross-match extractedsources to determine which sources did not have a match in temprunningcatalog ('new' sources). """ query = """\ UPDATE temprunningcatalog SET inactive = TRUE WHERE runcat IN (SELECT runcat FROM temprunningcatalog WHERE inactive = FALSE GROUP BY runcat HAVING COUNT(*) > 1 ) """ tkp.db.execute(query, commit=True) # This is the "master" 1-to-1 association query. We reuse it for associating # both null detections and monitoring list sources, tweaking the type as # appropriate. ONE_TO_ONE_ASSOC_QUERY = """\ INSERT INTO assocxtrsource (runcat ,xtrsrc ,type ,distance_arcsec ,r ,v_int ,eta_int ,f_datapoints ) SELECT t0.runcat ,t0.xtrsrc ,%(type)s ,t0.distance_arcsec ,t0.r ,t0.v_int_inter / t0.avg_f_int ,t0.eta_int_inter / t0.avg_f_int_weight ,t0.f_datapoints FROM (SELECT tmprc.runcat ,tmprc.xtrsrc ,tmprc.distance_arcsec ,tmprc.r ,tmprc.f_datapoints ,CASE WHEN tmprc.avg_f_int = 0.0 THEN 0.000001 ELSE avg_f_int END AS avg_f_int ,tmprc.avg_f_int_weight ,CASE WHEN tmprc.f_datapoints = 1 THEN 0 ELSE CASE WHEN ABS(tmprc.avg_f_int_sq - tmprc.avg_f_int * tmprc.avg_f_int) < 8e-14 THEN 0 ELSE SQRT(CAST(tmprc.f_datapoints AS DOUBLE PRECISION) * (tmprc.avg_f_int_sq - tmprc.avg_f_int * tmprc.avg_f_int) / (CAST(tmprc.f_datapoints AS DOUBLE PRECISION) - 1.0) ) END END AS v_int_inter ,CASE WHEN tmprc.f_datapoints = 1 THEN 0 ELSE (CAST(tmprc.f_datapoints AS DOUBLE PRECISION) / (CAST(tmprc.f_datapoints AS DOUBLE PRECISION) - 1.0)) * (tmprc.avg_f_int_weight * tmprc.avg_weighted_f_int_sq -
''' Copyright (c) 2018 Modul 9/HiFiBerry Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Formulas from "Cookbook formulae for audio EQ biquad filter coefficients" by <NAME> <<EMAIL>> ''' import math import logging from hifiberrydsp.datatools import parse_frequency, parse_decibel class Biquad(): def __init__(self, a0, a1, a2, b0, b1, b2, description): self.a0 = a0 self.a1 = a1 self.a2 = a2 self.b0 = b0 self.b1 = b1 self.b2 = b2 self.description = description def normalized(self): return Biquad(1, self.a1 / self.a0, self.a2 / self.a0, self.b0 / self.a0, self.b1 / self.a0, self.b2 / self.a0, self.description) def __str__(self): return ("Biquad {} ({},{},{},{},{},{})".format(self.description, self.a0, self.a1, self.a2, self.b0, self.b1, self.b2)) @classmethod def low_pass(cls, f0, q, fs): w0 = Biquad.omega(f0, fs) alpha = Biquad.alpha(w0, q) b0 = (1 - math.cos(w0)) / 2 b1 = 1 - math.cos(w0) b2 = (1 - math.cos(w0)) / 2 a0 = 1 + alpha a1 = -2 * math.cos(w0) a2 = 1 - alpha return Biquad(a0, a1, a2, b0, b1, b2, "Low pass {}Hz".format(f0)) @classmethod def high_pass(cls, f0, q, fs): w0 = Biquad.omega(f0, fs) alpha = Biquad.alpha(w0, q) b0 = (1 + math.cos(w0)) / 2 b1 = -(1 + math.cos(w0)) b2 = (1 + math.cos(w0)) / 2 a0 = 1 + alpha a1 = -2 * math.cos(w0) a2 = 1 - alpha return Biquad(a0, a1, a2, b0, b1, b2, "High pass {}Hz".format(f0)) @classmethod def band_pass_peak_q(cls, f0, q, fs): w0 = Biquad.omega(f0, fs) alpha = Biquad.alpha(w0, q) b0 = math.sin(w0) / 2 b1 = 0 b2 = -math.sin(w0) / 2 a0 = 1 + alpha a1 = -2 * math.cos(w0) a2 = 1 - alpha return Biquad(a0, a1, a2, b0, b1, b2, "Band pass peak {}Hz".format(f0)) @classmethod def band_pass(cls, f0, q, fs): w0 = Biquad.omega(f0, fs) alpha = Biquad.alpha(w0, q) b0 = alpha b1 = 0 b2 = -alpha a0 = 1 + alpha a1 = -2 * math.cos(w0) a2 = 1 - alpha return Biquad(a0, a1, a2, b0, b1, b2, "Band pass {}Hz".format(f0)) @classmethod def notch(cls, f0, q, fs): w0 = Biquad.omega(f0, fs) alpha = Biquad.alpha(w0, q) b0 = 1 b1 = -2 * math.cos(w0) b2 = 1 a0 = 1 + alpha a1 = -2 * math.cos(w0) a2 = 1 - alpha return Biquad(a0, a1, a2, b0, b1, b2, "Notch pass {}Hz".format(f0)) @classmethod def all_pass(cls, f0, q, fs): w0 = Biquad.omega(f0, fs) alpha = Biquad.alpha(w0, q) b0 = 1 - alpha b1 = -2 * math.cos(w0) b2 = 1 + alpha a0 = 1 + alpha a1 = -2 * math.cos(w0) a2 = 1 - alpha return Biquad(a0, a1, a2, b0, b1, b2, "All pass {}Hz".format(f0)) @classmethod def peaking_eq(self, f0, q, dbgain, fs): w0 = Biquad.omega(f0, fs) alpha = Biquad.alpha(w0, q) a = Biquad.a(dbgain) b0 = 1 + alpha * a b1 = -2 * math.cos(w0) b2 = 1 - alpha * a a0 = 1 + alpha / a a1 = -2 * math.cos(w0) a2 = 1 - alpha / a return Biquad(a0, a1, a2, b0, b1, b2, "Peaking Eq {}Hz {}dB".format(f0, dbgain)) @classmethod def low_shelf(self, f0, q, dbgain, fs): w0 = Biquad.omega(f0, fs) alpha = Biquad.alpha(w0, q) a = Biquad.a(dbgain) b0 = a * ((a + 1) - (a - 1) * math.cos(w0) + 2 * math.sqrt(a) * alpha) b1 = 2 * a * ((a - 1) - (a + 1) * math.cos(w0)) b2 = a * ((a + 1) - (a - 1) * math.cos(w0) - 2 * math.sqrt(a) * alpha) a0 = (a + 1) + (a - 1) * math.cos(w0) + 2 * math.sqrt(a) * alpha a1 = -2 * ((a - 1) + (a + 1) * math.cos(w0)) a2 = (a + 1) + (a - 1) * math.cos(w0) - 2 * math.sqrt(a) * alpha return Biquad(a0, a1, a2, b0, b1, b2, "Low shelf {}Hz {}dB".format(f0, dbgain)) @classmethod def high_shelf(cls, f0, q, dbgain, fs): w0 = Biquad.omega(f0, fs) alpha = Biquad.alpha(w0, q) a = Biquad.a(dbgain) b0 = a * ((a + 1) + (a - 1) * math.cos(w0) + 2 * math.sqrt(a) * alpha) b1 = -2 * a * ((a - 1) + (a + 1) * math.cos(w0)) b2 = a * ((a + 1) + (a - 1) * math.cos(w0) - 2 * math.sqrt(a) * alpha) a0 = (a + 1) - (a - 1) * math.cos(w0) + 2 * math.sqrt(a) * alpha a1 = 2 * ((a - 1) - (a + 1) * math.cos(w0)) a2 = (a + 1) - (a - 1) * math.cos(w0) - 2 * math.sqrt(a) * alpha return Biquad(a0, a1, a2, b0, b1, b2, "High shelf {}Hz {}dB".format(f0, dbgain)) @classmethod def plain(self): return Biquad(1, 0, 0, 1, 0, 0, "Null filter") ''' from A pratical guide for digital audio IIR filters http://freeverb3.sourceforge.net/iir_filter.shtml ''' @classmethod def low_pass_firstorder(cls, f0, q, fs): w = math.tan(math.pi * f0 / fs) n = 1 / (1 + w) b0 = w * n b1 = b0 a1 = n * (w - 1) return Biquad(1, a1, 0, b0, b1, 0, "Low pass 1st {}Hz".format(f0)) @classmethod def high_pass_firstorder(cls, f0, q, fs): w = math.tan(math.pi * f0 / fs) n = 1 / (1 + w) b0 = n b1 = -b0 a1 = n * (w - 1) return Biquad(1, a1, 0, b0, b1, 0, "High pass 1st {}Hz".format(f0)) @classmethod def volume(cls, db): b0 = pow(10, db / 20) return Biquad(1, 0, 0, b0, 0, 0, "Volume change {}db".format(db)) @classmethod def mute(cls): return Biquad(1, 0, 0, 0, 0, 0, "Null") @classmethod def pass_filter(cls): return Biquad.volume(0) @staticmethod def omega(f0, fs): return math.pi * f0 / fs * 2 @staticmethod def alpha(omega, q): return math.sin(omega) / (2 * q) @staticmethod def a(dbgain): return pow(10, dbgain / 40) @classmethod def create_filter(cls, definition, fs): ''' creates a filter from a textual representation ''' definition = definition.lower().strip() if definition.startswith("lp:"): try: (_lp, f, q) = definition.split(":") q = float(q) except: (_lp, f) = definition.split(":") q = 0.707 f = parse_frequency(f) return Biquad.low_pass(f, q, fs) elif definition.startswith("hp:"): try: (_hp, f, q) = definition.split(":") q = float(q) except: (_hp, f) = definition.split(":") q = 0.707 f = parse_frequency(f) return Biquad.high_pass(f, q, fs) elif definition.startswith("eq:"): try: (_eq, f, q, dbgain) = definition.split(":") q = float(q) f = parse_frequency(f) dbgain = parse_decibel(dbgain) return Biquad.peaking_eq(f, q, dbgain, fs) except: logging.error("can't parse ea filter") return None elif definition.startswith("vol:"): try: (_vol, db) = definition.split(":") db = parse_decibel(db) return Biquad.volume(db) except: logging.error("can't parse vol filter") return None elif definition.startswith("coeff:"): try: coeffs = definition.split(":") coeffs = coeffs[1:] numc = [] for c in coeffs: numc.append(float(c)) if len(numc) == 5: return Biquad(1, numc[0], numc[1], numc[2], numc[3], numc[4], "biquad from coefficients") elif len(numc) == 6: return Biquad(numc[0], numc[1], numc[2], numc[3], numc[4], numc[5], "biquad from coefficients") else: logging.error("5 or 6 biquad coefficients expected") except Exception as e: logging.error("can't parse biquad filter (%s)", e) return None elif definition.startswith("pass"): return Biquad.pass_filter() elif definition == "mute" or definition == "null": return Biquad.mute() else: logging.error("can't parse %s filter", definition) return None if __name__ == "__main__": bq1 = Biquad.low_pass(200, 1.41, 48000) print("Lowpass 200Hz: ", bq1) bq2 =
(count > 0): if count > max_count: write_count = max_count else: write_count = count start = int(write_offset * 2) end = int((write_offset + write_count) * 2) self._write(slave_id, addr + write_offset, data[start:end], trace_func=trace_func) count -= write_count write_offset += write_count else: raise ModbusClientError('Client serial port not open: %s' % self.name) class ModbusClientDeviceRTU(object): """Provides access to a Modbus RTU device. Parameters: slave_id : Modbus slave id. name : Name of the serial port such as 'com4' or '/dev/ttyUSB0'. baudrate : Baud rate such as 9600 or 19200. Default is 9600 if not specified. parity : Parity. Possible values: :const:`sunspec.core.modbus.client.PARITY_NONE`, :const:`sunspec.core.modbus.client.PARITY_EVEN` Defaulted to :const:`PARITY_NONE`. timeout : Modbus request timeout in seconds. Fractional seconds are permitted such as .5. ctx : Context variable to be used by the object creator. Not used by the modbus module. trace_func : Trace function to use for detailed logging. No detailed logging is perform is a trace function is not supplied. max_count : Maximum register count for a single Modbus request. Raises: ModbusClientError: Raised for any general modbus client error. ModbusClientTimeoutError: Raised for a modbus client request timeout. ModbusClientException: Raised for an exception response to a modbus client request. """ def __init__(self, slave_id, name, baudrate=None, parity=None, timeout=None, ctx=None, trace_func=None, max_count=REQ_COUNT_MAX): self.slave_id = slave_id self.name = name self.client = None self.ctx = ctx self.trace_func = trace_func self.max_count = max_count self.client = modbus_rtu_client(name, baudrate, parity) if self.client is None: raise ModbusClientError('No modbus rtu client set for device') self.client.add_device(self.slave_id, self) if timeout is not None and self.client.serial is not None: self.client.serial.timeout = timeout self.client.serial.writeTimeout = timeout def close(self): """Close the device. Called when device is not longer in use. """ if self.client: self.client.remove_device(self.slave_id) def read(self, addr, count, op=FUNC_READ_HOLDING): """Read Modbus device registers. Parameters: addr : Starting Modbus address. count : Read length in Modbus registers. op : Modbus function code for request. Returns: Byte string containing register contents. """ return self.client.read(self.slave_id, addr, count, op=op, trace_func=self.trace_func, max_count=self.max_count) def write(self, addr, data): """Write Modbus device registers. Parameters: addr : Starting Modbus address. count : Byte string containing register contents. """ return self.client.write(self.slave_id, addr, data, trace_func=self.trace_func, max_count=self.max_count) TCP_HDR_LEN = 6 TCP_RESP_MIN_LEN = 3 TCP_HDR_O_LEN = 4 TCP_READ_REQ_LEN = 6 TCP_WRITE_MULT_REQ_LEN = 7 TCP_DEFAULT_PORT = 502 TCP_DEFAULT_TIMEOUT = 2 class ModbusClientDeviceTCP(object): """Provides access to a Modbus TCP device. Parameters: slave_id : Modbus slave id. ipaddr : IP address string. ipport : IP port. timeout : Modbus request timeout in seconds. Fractional seconds are permitted such as .5. ctx : Context variable to be used by the object creator. Not used by the modbus module. trace_func : Trace function to use for detailed logging. No detailed logging is perform is a trace function is not supplied. max_count : Maximum register count for a single Modbus request. test : Use test socket. If True use the fake socket module for network communications. Raises: ModbusClientError: Raised for any general modbus client error. ModbusClientTimeoutError: Raised for a modbus client request timeout. ModbusClientException: Raised for an exception response to a modbus client request. Attributes: slave_id Modbus slave id. ipaddr Destination device IP address string. ipport Destination device IP port. timeout Modbus request timeout in seconds. Fractional seconds are permitted such as .5. ctx Context variable to be used by the object creator. Not used by the modbus module. socket Socket used for network connection. If no connection active, value is None. trace_func Trace function to use for detailed logging. max_count Maximum register count for a single Modbus request. """ def __init__(self, slave_id, ipaddr, ipport=502, timeout=None, ctx=None, trace_func=None, max_count=REQ_COUNT_MAX, test=False): self.slave_id = slave_id self.ipaddr = ipaddr self.ipport = ipport self.timeout = timeout self.ctx = ctx self.socket = None self.trace_func = trace_func self.max_count = max_count if ipport is None: self.ipport = TCP_DEFAULT_PORT if timeout is None: self.timeout = TCP_DEFAULT_TIMEOUT if test: import sunspec.core.test.fake.socket as fake self.socket = fake.socket() def close(self): self.disconnect() def connect(self, timeout=None): """Connect to TCP destination. Parameters: timeout : Connection timeout in seconds. """ if self.socket: self.disconnect() if timeout is None: timeout = self.timeout try: self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.settimeout(timeout) self.socket.connect((self.ipaddr, self.ipport)) except Exception as e: raise ModbusClientError('Connection error: %s' % str(e)) def disconnect(self): """Disconnect from TCP destination. """ try: if self.socket: self.socket.close() self.socket = None except Exception: pass def _read(self, addr, count, op=FUNC_READ_HOLDING): resp = b'' len_remaining = TCP_HDR_LEN + TCP_RESP_MIN_LEN len_found = False except_code = None req = struct.pack('>HHHBBHH', 0, 0, TCP_READ_REQ_LEN, int(self.slave_id), op, int(addr), int(count)) if self.trace_func: s = '{}:{}:{}[addr={}] ->'.format(self.ipaddr, str(self.ipport), str(self.slave_id), addr) for c in req: s += '%02X' % (ord(c)) self.trace_func(s) try: self.socket.sendall(req) except Exception as e: raise ModbusClientError('Socket write error: %s' % str(e)) while len_remaining > 0: c = self.socket.recv(len_remaining) # print('c = {0}'.format(c)) len_read = len(c); if len_read > 0: resp += c len_remaining -= len_read if len_found is False and len(resp) >= TCP_HDR_LEN + TCP_RESP_MIN_LEN: data_len = struct.unpack('>H', resp[TCP_HDR_O_LEN:TCP_HDR_O_LEN + 2]) len_remaining = data_len[0] - (len(resp) - TCP_HDR_LEN) else: raise ModbusClientError('Response timeout') if sys.version_info > (3,): temp = "" for i in resp: temp += chr(i) resp = temp if not (ord(resp[TCP_HDR_LEN + 1]) & 0x80): len_remaining = (ord(resp[TCP_HDR_LEN + 2]) + TCP_HDR_LEN) - len(resp) len_found = True else: except_code = ord(resp[TCP_HDR_LEN + 2]) if self.trace_func: s = '{}:{}:{}[addr={}] <--'.format(self.ipaddr, str(self.ipport), str(self.slave_id), addr) for c in resp: s += '%02X' % (ord(c)) self.trace_func(s) if except_code: raise ModbusClientException('Modbus exception %d' % (except_code)) return resp[(TCP_HDR_LEN + 3):] def read(self, addr, count, op=FUNC_READ_HOLDING): """ Read Modbus device registers. If no connection exists to the destination, one is created and disconnected at the end of the request. Parameters: addr : Starting Modbus address. count : Read length in Modbus registers. op : Modbus function code for request. Returns: Byte string containing register contents. """ resp = '' read_count = 0 read_offset = 0 local_connect = False if self.socket is None: local_connect = True self.connect(self.timeout) try: while (count > 0): if count > self.max_count: read_count = self.max_count else: read_count = count data = self._read(addr + read_offset, read_count, op=op) if data: resp += data count -= read_count read_offset += read_count else: break finally: if local_connect: self.disconnect() if sys.version_info > (3,): resp = bytes(resp, 'latin-1') return resp def _write(self, addr, data): resp = '' len_remaining = TCP_HDR_LEN + TCP_RESP_MIN_LEN len_found = False except_code = None func = FUNC_WRITE_MULTIPLE write_len = len(data) write_count = int(write_len/2) req = struct.pack('>HHHBBHHB', 0, 0, TCP_WRITE_MULT_REQ_LEN + write_len, int(self.slave_id), func, int(addr), write_count, write_len) if sys.version_info > (3,): if type(data) is not bytes: data = bytes(data, "latin-1") req += data if self.trace_func: s = '{}:{}:{}[addr={}] ->'.format(self.ipaddr, str(self.ipport), str(self.slave_id), addr) for c in req: s += '%02X' % (ord(c)) self.trace_func(s) try: self.socket.sendall(req) except Exception as e: raise ModbusClientError('Socket write error: %s' % str(e)) while len_remaining > 0: c = self.socket.recv(len_remaining) # print('c = {0}'.format(c)) len_read = len(c); if len_read > 0: if type(c) == bytes and sys.version_info > (3,): temp = "" for i in c: temp += chr(i) c = temp resp += c len_remaining -= len_read if len_found is False and len(resp) >= TCP_HDR_LEN + TCP_RESP_MIN_LEN: if sys.version_info > (3,): resp = bytes(resp, "latin-1") data_len = struct.unpack('>H', resp[TCP_HDR_O_LEN:TCP_HDR_O_LEN + 2]) len_remaining = data_len[0] - (len(resp) - TCP_HDR_LEN) if type(resp) == bytes and sys.version_info > (3,): temp = "" for i in resp: temp += chr(i) resp = temp else: raise ModbusClientTimeout('Response timeout') if not (ord(resp[TCP_HDR_LEN + 1]) & 0x80): len_remaining = (ord(resp[TCP_HDR_LEN + 2]) + TCP_HDR_LEN) - len(resp) len_found = True else: except_code = ord(resp[TCP_HDR_LEN + 2]) if self.trace_func: s = '{}:{}:{}[addr={}] <--'.format(self.ipaddr, str(self.ipport), str(self.slave_id), addr) for c in resp: s += '%02X' % (ord(c)) self.trace_func(s) if except_code: raise ModbusClientException('Modbus exception: %d' % (except_code)) def write(self, addr, data): """ Write Modbus device registers. If no connection exists to the destination, one is created and disconnected at the end of the request. Parameters: addr : Starting Modbus address. count : Byte string containing register contents. """ write_count = 0 write_offset = 0 local_connect = False
<reponame>top-sim/topsim # Copyright (C) 10/19 <NAME> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. import time import logging import pandas as pd from enum import Enum from topsim.common.globals import TIMESTEP from topsim.core.instrument import RunStatus from topsim.core.planner import WorkflowStatus from topsim.core.task import TaskStatus LOGGER = logging.getLogger(__name__) class Scheduler: """ Attributes ---------- """ def __init__(self, env, buffer, cluster, algorithm): """ Parameters ---------- env : Simpy.Environment object The simulation Environment buffer : core.buffer.Buffer object The SDP buffer used in the simulation cluster : core.cluster.Cluster object The Cluster instance used for the simluation algorithm : core.cluster.Algorithm object The algorithm model using """ self.env = env self.algorithm = algorithm self.cluster = cluster self.buffer = buffer self.status = SchedulerStatus.SLEEP self.ingest_observation = None self.provision_ingest = 0 self.observation_queue = [] self.schedule_status = ScheduleStatus.ONTIME self.algtime = {} self.delay_offset = 0 def start(self): """ Set the SchedulerStatus to RUNNING. This allows us to check the Scheduler status in the simulator; if there is nothing left the schedule, we may finish the simulation. Returns ------- self.status : topsim.core.scheduler.SchedulerStatus SchedulerStatus.RUNNING for all calls to init() """ self.status = SchedulerStatus.RUNNING return self.status def shutdown(self): self.status = SchedulerStatus.SHUTDOWN return self.status def run(self): """ Starts the 'per-TIMESTEP' process loop for the Scheduler actor. The Scheduler coordinates interaction between the Telescope, Buffer, and Cluster. The Telescope should not *see* the Buffer or Cluster; all communication must be transferred through the scheduler. Yields ------- Timeout of common.config.TIMESTEP. """ if self.status is not SchedulerStatus.RUNNING: raise RuntimeError("Scheduler has not been initialised! Call init") LOGGER.debug("Scheduler starting up...") while self.status is SchedulerStatus.RUNNING: LOGGER.debug('Time on Scheduler: {0}'.format(self.env.now)) if self.buffer.has_observations_ready_for_processing(): obs = self.buffer.next_observation_for_processing() if obs not in self.observation_queue: self.observation_queue.append(obs) ret = self.env.process(self.allocate_tasks(obs)) if len(self.observation_queue) == 0 \ and self.status == SchedulerStatus.SHUTDOWN: LOGGER.debug("No more waiting workflows") break # for obs in self.observation_queue: # if obs.workflow_plan.status == WorkflowStatus.FINISHED: # self.cluster.release_batch_resources(obs) LOGGER.debug("Scheduler Status: %s", self.status) yield self.env.timeout(TIMESTEP) def is_idle(self): """ Determine if the scheduler has completed its work Returns True if idle ------- """ return len(self.observation_queue) == 0 def scheduler_status(self): """ The status of the scheduled observation(s) and whether or not the scheduler has been delayed yet. Returns ------- status: Scheduler.ScheduleStatus The status Enum """ return self.schedule_status def check_ingest_capacity(self, observation, pipelines, max_ingest): """ Check the cluster and buffer to ensure that we have enough capacity to run the INGEST pipeline for the provided observation Parameters ---------- observation : core.Telescope.Observation object The observation that we are attempting to run/ingest pipelines : dict() A dictionary of the different types of observations and the corresponding pipeline attributes (length, num of machines etc.) Returns ------- has_capacity : bool True if the buffer AND the cluster have the capacity to run the provided observation False if either of them do not have capacity. """ buffer_capacity = False if self.buffer.check_buffer_capacity(observation): LOGGER.debug("Buffer has enough capacity for %s", observation.name) buffer_capacity = True cluster_capacity = False pipeline_demand = pipelines[observation.name]['ingest_demand'] if self.cluster.check_ingest_capacity(pipeline_demand, max_ingest): if self.provision_ingest + pipeline_demand <= max_ingest: cluster_capacity = True self.provision_ingest += pipeline_demand LOGGER.debug( "Cluster is able to process ingest for observation %s", observation.name ) else: LOGGER.debug('Cluster is unable to process ingest as two' 'observations are scheduled at the same time') return buffer_capacity and cluster_capacity def allocate_ingest(self, observation, pipelines, planner, max_ingest=None, c='default'): """ Ingest is 'streaming' data to the buffer during the observation How we calculate how long it takes remains to be seen Parameters --------- observation : core.Telescope.Observation object The observation from which we are starting Ingest pipelines : dict dictionary storing the different pipeline types supported for the current simulation: pipelines[observation type][demand] Returns ------- True/False Raises ------ """ observation.ast = self.env.now # self.env.process( # observation.plan = planner.run(observation, self.buffer) # ) pipeline_demand = pipelines[observation.name]['ingest_demand'] ingest_observation = observation # We do an off-by-one check here, because the first time we run the # loop we will be one timestep ahead. time_left = observation.duration - 1 while ingest_observation.status is not RunStatus.FINISHED: if ingest_observation.status is RunStatus.WAITING: cluster_ingest = self.env.process( self.cluster.provision_ingest_resources( pipeline_demand, observation ) ) ret = self.env.process( self.buffer.ingest_data_stream( observation, ) ) ingest_observation.status = RunStatus.RUNNING elif ingest_observation.status is RunStatus.RUNNING: if time_left > 0: time_left -= 1 else: break yield self.env.timeout(1) if RunStatus.FINISHED: self.provision_ingest -= pipeline_demand self.cluster.clean_up_ingest() # TODO Fix this implicit object change, as whilst this is the # same as the object in the buffer, it is from the buffer we # get the observation. It is probably worth storing plans # separately and then 'giving' them to the observation once it # arrives at the scheduler. observation.plan = planner.run(observation, self.buffer, max_ingest) def print_state(self): # Change this to 'workflows scheduled/workflows unscheduled' pass def allocate_tasks(self, observation): """ For the current observation, we need to allocate tasks to machines based on: * The plan that has been generated * The result of the scheduler's decision based on the current cluster state, and the original plan. Returns ------- """ minst = -1 current_plan = None if observation is None: return False elif current_plan is None: current_plan = observation.plan if current_plan is None: raise RuntimeError( "Observation should have pre-plan; Planner actor has " "failed at runtime." ) current_plan.ast = self.env.now for task in current_plan.tasks: task.workflow_offset = self.env.now # Do we have a runtime delay? if current_plan.est > self.env.now: self.schedule_status.DELAYED schedule = {} allocation_pairs = {} while True: current_plan.tasks = self._update_current_plan(current_plan) current_plan, schedule, finished = self._generate_current_schedule( observation, current_plan, schedule ) if finished: # We have finished this observation LOGGER.info(f'{observation.name} Removed from Queue @' f'{self.env.now}') # self.cluster.release_batch_resources(observation) break # If there are no allocations made this timestep elif not schedule: yield self.env.timeout(TIMESTEP) else: # This is where allocations are made to the cluster schedule, allocation_pairs = self._process_current_schedule( schedule, allocation_pairs, current_plan.id ) yield self.env.timeout(TIMESTEP) yield self.env.timeout(TIMESTEP) def _generate_current_schedule(self, observation, current_plan, schedule): """ Each timestep, we want to generate a schedule based on the observation plan and an existing schedule. Parameters ---------- current_plan schedule Returns ------- current_plan, schedule, finished """ finished = False nm = f'{observation.name}-algtime' self.algtime[nm] = time.time() schedule, status = self.algorithm.run( cluster=self.cluster, clock=self.env.now, workflow_plan=current_plan, existing_schedule=schedule ) self.algtime[nm] = (time.time() - self.algtime[nm]) current_plan.status = status if (current_plan.status is WorkflowStatus.DELAYED and self.schedule_status is not WorkflowStatus.DELAYED): self.schedule_status = ScheduleStatus.DELAYED # If the workflow is finished if not schedule and status is WorkflowStatus.FINISHED: if self.buffer.mark_observation_finished(observation): self.cluster.release_batch_resources(observation.name) self.observation_queue.remove(observation) finished = True return current_plan, schedule, finished def _process_current_schedule(self, schedule, allocation_pairs, workflow_id): """ Given a schedule and existing allocations, run through the schedule and run the allocation for that tasks if possible Parameters ---------- schedule allocation_pairs workflow_id : The ID of the workflow. This is so in the cluster we can find the appropriate set of provisioned resources. Returns ------- """ sorted_tasks = sorted( schedule.keys(), key=lambda t: t.est ) curr_allocs = [] # Allocate tasks for task in sorted_tasks: machine = schedule[task] if machine.id != task.machine: task.update_allocation(machine) # Schedule if machine in curr_allocs or self.cluster.is_occupied(machine): LOGGER.debug( "Allocation not made to cluster due to double-allocation" ) else: allocation_pairs[task.id] = (task, machine) pred_allocations = self._find_pred_allocations( task, machine, allocation_pairs ) if task.task_status != TaskStatus.UNSCHEDULED: raise RuntimeError("Producing schedule with Scheduled " "Tasks") self.env.process( self.cluster.allocate_task_to_cluster( task, machine, pred_allocations, workflow_id ) ) LOGGER.debug(f"Allocation {task}-{machine} made to cluster") task.task_status = TaskStatus.SCHEDULED curr_allocs.append(machine) schedule.pop(task, None) return schedule, allocation_pairs def _update_current_plan(self, current_plan): """ Check the status of tasks in the workflow plan and remove them if they are complete Each task has a delay_flag that is triggered if the duration or finish time is not the same as what was estimated in the planning. The method will update
mem_ds.CreateLayer( "my_layer") sql_lyr = mem_ds.ExecuteSQL("SELECT *, fid from my_layer") if sql_lyr.GetLayerDefn().GetFieldCount() != 1: return 'fail' if sql_lyr.GetLayerDefn().GetFieldDefn(0).GetName() != 'fid': return 'fail' mem_ds.ReleaseResultSet(sql_lyr) mem_ds = None return 'success' ############################################################################### # Test multiple expansion of '*' as in "SELECT *, fid, *, my_layer.* from my_layer" (#2788) def ogr_sql_22(): mem_ds = ogr.GetDriverByName("Memory").CreateDataSource( "my_ds") mem_lyr = mem_ds.CreateLayer( "my_layer") mem_lyr.CreateField( ogr.FieldDefn("test", ogr.OFTString) ) feat = ogr.Feature(mem_lyr.GetLayerDefn() ) feat.SetGeometry(ogr.CreateGeometryFromWkt("POINT(0 1)")) mem_lyr.CreateFeature( feat ) sql_lyr = mem_ds.ExecuteSQL("SELECT *, fid, *, my_layer.* from my_layer") if sql_lyr.GetLayerDefn().GetFieldCount() != 4: return 'fail' if sql_lyr.GetLayerDefn().GetFieldDefn(0).GetName() != 'test': return 'fail' if sql_lyr.GetLayerDefn().GetFieldDefn(1).GetName() != 'fid': return 'fail' if sql_lyr.GetLayerDefn().GetFieldDefn(2).GetName() != 'test': return 'fail' if sql_lyr.GetLayerDefn().GetFieldDefn(3).GetName() != 'my_layer.test': return 'fail' mem_ds.ReleaseResultSet(sql_lyr) mem_ds = None return 'success' ############################################################################### # Test query "SELECT DISTINCT test from my_layer" (#2788) def ogr_sql_23(): mem_ds = ogr.GetDriverByName("Memory").CreateDataSource( "my_ds") mem_lyr = mem_ds.CreateLayer( "my_layer") mem_lyr.CreateField( ogr.FieldDefn("test", ogr.OFTString) ) feat = ogr.Feature(mem_lyr.GetLayerDefn() ) feat.SetField("test", 0) feat.SetGeometry(ogr.CreateGeometryFromWkt("POINT(0 1)")) mem_lyr.CreateFeature( feat ) feat = ogr.Feature(mem_lyr.GetLayerDefn() ) feat.SetField("test", 1) feat.SetGeometry(ogr.CreateGeometryFromWkt("POINT(2 3)")) mem_lyr.CreateFeature( feat ) sql_lyr = mem_ds.ExecuteSQL("SELECT DISTINCT test from my_layer") if sql_lyr.GetFeatureCount() != 2: return 'fail' mem_ds.ReleaseResultSet(sql_lyr) mem_ds = None return 'success' ############################################################################### # Test that style strings get carried with OGR SQL SELECT results. (#2808) def ogr_sql_24(): result = 'success' ds = ogr.Open( 'data/smalltest.dgn' ) sql_layer = ds.ExecuteSQL( 'SELECT * from elements where colorindex=83 and type=3' ) feat = sql_layer.GetNextFeature() if len(feat.GetStyleString()) < 10: print(feat.GetStyleString()) gdaltest.post_reason( 'style string apparently not propagated to OGR SQL results.' ) result = 'fail' feat = None ds.ReleaseResultSet( sql_layer ) ds = None return result ############################################################################### # Test for OGR_GEOM_AREA special field (#2949) def ogr_sql_25(): mem_ds = ogr.GetDriverByName("Memory").CreateDataSource( "my_ds") mem_lyr = mem_ds.CreateLayer( "my_layer") mem_lyr.CreateField( ogr.FieldDefn("test", ogr.OFTString) ) feat = ogr.Feature(mem_lyr.GetLayerDefn() ) feat.SetField("test", 0) feat.SetGeometry(ogr.CreateGeometryFromWkt("POLYGON((0 0,0 1,1 1,1 0,0 0))")) mem_lyr.CreateFeature( feat ) feat = ogr.Feature(mem_lyr.GetLayerDefn() ) feat.SetField("test", 1) feat.SetGeometry(ogr.CreateGeometryFromWkt("POLYGON((0 0,0 0.5,0.5 0.5,0.5 0,0 0))")) mem_lyr.CreateFeature( feat ) sql_lyr = mem_ds.ExecuteSQL("SELECT test, OGR_GEOM_AREA from my_layer WHERE OGR_GEOM_AREA > 0.9") if sql_lyr.GetFeatureCount() != 1: return 'fail' feat = sql_lyr.GetNextFeature() if feat.GetFieldAsDouble('OGR_GEOM_AREA') != 1.0: return 'fail' if feat.GetFieldAsString('test') != '0': return 'fail' mem_ds.ReleaseResultSet(sql_lyr) mem_ds = None return 'success' ############################################################################### # Test query 'SELECT 'literal_value' AS column_name FROM a_table' # def ogr_sql_26(): mem_ds = ogr.GetDriverByName("Memory").CreateDataSource( "my_ds") mem_lyr = mem_ds.CreateLayer( "my_layer") feat = ogr.Feature(mem_lyr.GetLayerDefn() ) mem_lyr.CreateFeature( feat ) sql_lyr = mem_ds.ExecuteSQL("SELECT 'literal_value' AS my_column, 'literal_value2' my_column2 FROM my_layer") if sql_lyr.GetFeatureCount() != 1: return 'fail' feat = sql_lyr.GetNextFeature() if feat.GetFieldAsString('my_column') != 'literal_value': return 'fail' if feat.GetFieldAsString('my_column2') != 'literal_value2': return 'fail' mem_ds.ReleaseResultSet(sql_lyr) mem_ds = None return 'success' ############################################################################### ############################################################################### # Test query on datetime columns # def ogr_sql_27(): ds = ogr.Open('data/testdatetime.csv') sql_lyr = ds.ExecuteSQL("SELECT * FROM testdatetime WHERE " \ "timestamp < '2010/04/01 00:00:00' AND " \ "timestamp > '2009/11/15 11:59:59' AND " \ "timestamp != '2009/12/31 23:00:00' " \ "ORDER BY timestamp DESC") tr = ogrtest.check_features_against_list( sql_lyr, 'name', [ 'foo5', 'foo4'] ) ds.ReleaseResultSet( sql_lyr ) ds = None if tr: return 'success' else: return 'fail' ############################################################################### # Test robustness against invalid SQL statements. # With RFC 28 new implementation, most of them are directly caught by the generated # code from the grammar def ogr_sql_28(): ds = ogr.GetDriverByName("Memory").CreateDataSource( "my_ds") lyr = ds.CreateLayer( "my_layer") lyr.GetLayerDefn().GetGeomFieldDefn(0).SetName('geom') # a bit border line but OK for Memory driver... field_defn = ogr.FieldDefn( "strfield", ogr.OFTString ) lyr.CreateField(field_defn) field_defn = ogr.FieldDefn( "intfield", ogr.OFTInteger ) lyr.CreateField(field_defn) lyr = ds.CreateLayer( "my_layer2") field_defn = ogr.FieldDefn( "strfield", ogr.OFTString ) lyr.CreateField(field_defn) field_defn = ogr.FieldDefn( "strfield2", ogr.OFTString ) lyr.CreateField(field_defn) try: sql_lyr = ds.ExecuteSQL(None) gdaltest.post_reason('expected error on NULL query') return 'fail' except: pass queries = [ '', '1', '*', 'SELECT', "SELECT ' FROM my_layer", 'SELECT + FROM my_layer', 'SELECT (1 FROM my_layer', 'SELECT (1)) FROM my_layer', 'SELECT (1,) FROM my_layer', 'SELECT 1 + FROM my_layer', "SELECT 1 + 'a' FROM my_layer", 'SELECT 1 - FROM my_layer', 'SELECT 1 * FROM my_layer', 'SELECT 1 % FROM my_layer', 'SELECT *', 'SELECT * FROM', 'SELECT * FROM foo', 'SELECT FROM my_layer', 'SELECT FROM FROM my_layer', "SELECT ('strfield'", "SELECT 'strfield' +", "SELECT 'strfield' 'strfield'", "SELECT CONCAT('strfield')", 'SELECT foo(strfield) FROM my_layer', # Undefined function 'foo' used. 'SELECT strfield, FROM my_layer', 'SELECT strfield, foo FROM my_layer', 'SELECT strfield AS FROM my_layer', 'SELECT strfield AS 1 FROM my_layer', 'SELECT strfield AS strfield2 FROM', 'SELECT strfield + intfield FROM my_layer', 'SELECT CAST', 'SELECT CAST(', 'SELECT CAST(strfield', 'SELECT CAST(strfield AS', 'SELECT CAST(strfield AS foo', 'SELECT CAST(strfield AS foo)', 'SELECT CAST(strfield AS foo) FROM', 'SELECT CAST(strfield AS foo) FROM my_layer', 'SELECT CAST(strfield AS CHARACTER', 'SELECT CAST(strfield AS CHARACTER)', 'SELECT CAST(strfield AS CHARACTER) FROM', 'SELECT CAST(strfield AS CHARACTER) FROM foo', 'SELECT CAST(strfield AS CHARACTER(', 'SELECT CAST(strfield AS CHARACTER(2', 'SELECT CAST(strfield AS CHARACTER(2)', 'SELECT CAST(strfield AS CHARACTER(2))', 'SELECT CAST(strfield AS CHARACTER(2)) FROM', 'SELECT CAST(strfield AS CHARACTER(2)) FROM foo', 'SELECT CAST(strfield AS 1) FROM my_layer', 'SELECT * FROM my_layer WHERE', #'SELECT * FROM my_layer WHERE strfield', 'SELECT * FROM my_layer WHERE strfield = ', 'SELECT * FROM my_layer WHERE strfield = foo', "SELECT * FROM my_layer WHERE foo = 'a'", "SELECT * FROM my_layer WHERE strfield = 'a" "SELECT * FROM my_layer WHERE strfield = 'a' ORDER ", "SELECT * FROM my_layer WHERE strfield = 'a' ORDER BY", "SELECT * FROM my_layer WHERE strfield = 'a' ORDER BY foo", "SELECT * FROM my_layer WHERE strfield = 'a' ORDER BY strfield UNK", "SELECT * FROM my_layer ORDER BY geom", # Cannot use geometry field 'geom' in a ORDER BY clause "SELECT FOO(*) FROM my_layer", "SELECT FOO(*) AS bar FROM my_layer", "SELECT COUNT", "SELECT COUNT(", "SELECT COUNT() FROM my_layer", "SELECT COUNT(*", "SELECT COUNT(*)", "SELECT COUNT(*) FROM", "SELECT COUNT(*) AS foo FROM", "SELECT COUNT(* FROM my_layer", "SELECT COUNT(FOO intfield) FROM my_layer", "SELECT COUNT(DISTINCT intfield FROM my_layer", "SELECT COUNT(DISTINCT *) FROM my_layer", "SELECT FOO(DISTINCT intfield) FROM my_layer", "SELECT FOO(DISTINCT intfield) as foo FROM my_layer", "SELECT DISTINCT foo FROM my_layer", "SELECT DISTINCT foo AS 'id' 'id2' FROM", "SELECT DISTINCT foo AS id id2 FROM", "SELECT DISTINCT FROM my_layer", "SELECT DISTINCT strfield, COUNT(DISTINCT intfield) FROM my_layer", "SELECT MIN(intfield*2) FROM my_layer", "SELECT MIN(intfield,2) FROM my_layer", "SELECT MIN(foo) FROM my_layer", "SELECT MAX(foo) FROM my_layer", "SELECT SUM(foo) FROM my_layer", "SELECT AVG(foo) FROM my_layer", "SELECT MIN(strfield) FROM my_layer", "SELECT MAX(strfield) FROM my_layer", "SELECT SUM(strfield) FROM my_layer", "SELECT AVG(strfield) FROM my_layer", "SELECT AVG(intfield, intfield) FROM my_layer", "SELECT * FROM my_layer WHERE AVG(intfield) = 1" , "SELECT * FROM 'foo' foo" , "SELECT * FROM my_layer WHERE strfield =" , "SELECT * FROM my_layer WHERE strfield = foo" , "SELECT * FROM my_layer WHERE strfield = intfield" , "SELECT * FROM my_layer WHERE strfield = 1" , "SELECT * FROM my_layer WHERE strfield = '1' AND" , #"SELECT * FROM my_layer WHERE 1 AND 2" , "SELECT * FROM my_layer WHERE strfield LIKE" , "SELECT * FROM my_layer WHERE strfield LIKE 1" , "SELECT * FROM my_layer WHERE strfield IS" , "SELECT * FROM my_layer WHERE strfield IS NOT" , "SELECT * FROM my_layer WHERE strfield IS foo" , "SELECT * FROM my_layer WHERE strfield IS NOT foo" , "SELECT * FROM my_layer WHERE (strfield IS NOT NULL" , "SELECT * FROM my_layer WHERE strfield IN" , "SELECT * FROM my_layer WHERE strfield IN(" , "SELECT * FROM my_layer WHERE strfield IN()" , "SELECT * FROM my_layer WHERE strfield IN('a'" , "SELECT * FROM my_layer WHERE strfield IN('a'," , "SELECT * FROM my_layer WHERE strfield IN('a','b'" , "SELECT * FROM my_layer WHERE strfield IN('a','b'))" , "SELECT * FROM my_layer LEFT" , "SELECT * FROM my_layer LEFT JOIN" , "SELECT * FROM my_layer LEFT JOIN foo", "SELECT * FROM my_layer LEFT JOIN foo ON my_layer.strfield = my_layer2.strfield", "SELECT * FROM my_layer LEFT JOIN my_layer2 ON my_layer.strfield = foo.strfield", "SELECT * FROM my_layer LEFT JOIN my_layer2 ON my_layer.strfield = my_layer2.foo", #"SELECT * FROM my_layer LEFT JOIN my_layer2 ON my_layer.strfield != my_layer2.strfield", "SELECT *, my_layer2. FROM my_layer LEFT JOIN my_layer2 ON my_layer.strfield = my_layer2.strfield", "SELECT *, my_layer2.foo FROM my_layer LEFT JOIN my_layer2 ON my_layer.strfield = my_layer2.strfield", "SELECT * FROM my_layer UNION" , "SELECT * FROM my_layer UNION ALL" , "SELECT * FROM my_layer UNION ALL SELECT" , "SELECT * FROM my_layer UNION ALL
"""Widely useful utility methods. """ from collections import OrderedDict, Iterable, Sequence from datetime import datetime import errno import functools import logging import math from numbers import Number import time from atropos import AtroposError # TODO: the nucleotide table should be implemented as an alphabet. class NotInAlphabetError(Exception): def __init__(self, character): super().__init__() self.character = character class Alphabet(): def __init__(self, valid_characters, default_character): if not isinstance(valid_characters, set): valid_characters = set(valid_characters) if not default_character in valid_characters: valid_characters.add(default_character) self.valid_characters = valid_characters self.default_character = default_character def __contains__(self, character): return character in self.valid_characters def validate(self, character): """Raises NotInAlphabetError if the character is not in the alphabet. """ if not character in self: raise NotInAlphabetError(character) def validate_string(self, string): """Raises NotInAlphabetError if any character in 'string' is not in the alphabet. """ for character in string: self.validate(character) def resolve(self, character): """Returns 'character' if it's in the alphabet, otherwise the alphabet's default character. """ if character in self.valid_characters: return character else: return self.default_character def resolve_string(self, string): """Returns a new string with any non-alphabet characters replaced with the default character. """ return "".join(self.resolve(c) for c in string) ALPHABETS = dict( dna=Alphabet('ACGT', 'N'), iso=None, colorspace=Alphabet('0123', None) ) def build_iso_nucleotide_table(): """Generate a dict mapping ISO nucleotide characters to their complements, in both upper and lower case. """ nuc = { 'A' : 'T', 'C' : 'G', 'R' : 'Y', 'S' : 'S', 'W' : 'W', 'K' : 'M', 'B' : 'V', 'D' : 'H', 'N' : 'N' } for base, comp in tuple(nuc.items()): nuc[comp] = base nuc[base.lower()] = comp.lower() nuc[comp.lower()] = base.lower() return nuc BASE_COMPLEMENTS = build_iso_nucleotide_table() IUPAC_BASES = frozenset(('X',) + tuple(BASE_COMPLEMENTS.keys())) """Valid IUPAC bases, plus 'X'""" GC_BASES = frozenset('CGRYSKMBDHVN') """IUPAC bases that include C or G.""" MAGNITUDE = dict( G=1E9, M=1E6, K=1E3 ) LOG2 = math.log(2) class RandomMatchProbability(object): """Class for computing random match probability for DNA sequences based on binomial expectation. Maintains a cache of factorials to speed computation. Args: init_size: Initial cache size. """ def __init__(self, init_size=150): self.cache = {} self.factorials = [1] * init_size self.max_n = 1 self.cur_array_size = init_size def __call__(self, matches, size, match_prob=0.25, mismatch_prob=0.75): """Computes the random-match probability for a given sequence size and number of matches. Args: match_prob: Probability of two random bases matching. mismatch_prob: Probability of two random bases not matcing. Returns: The probability. """ # First see if we have the result in the cache key = (matches, size, match_prob) prob = self.cache.get(key, None) if prob: return prob # When there are no mismatches, the probability is # just that of observing a specific sequence of the # given length by chance. if matches == size: prob = match_prob ** matches else: nfac = self.factorial(size) prob = 0.0 for i in range(matches, size+1): j = size - i # use integer division in the case that the numbers are too # large for floating point division try: div = nfac / self.factorial(i) / self.factorial(j) except OverflowError: div = nfac // self.factorial(i) // self.factorial(j) prob += (mismatch_prob ** j) * (match_prob ** i) * div self.cache[key] = prob return prob def factorial(self, num): """Returns `num`!. """ if num > self.max_n: self._fill_upto(num) return self.factorials[num] def _fill_upto(self, num): if num >= self.cur_array_size: extension_size = num - self.cur_array_size + 1 self.factorials += [1] * extension_size idx = self.max_n next_i = idx + 1 while idx < num: self.factorials[next_i] = next_i * self.factorials[idx] idx = next_i next_i += 1 self.max_n = idx class Mergeable(object): """Base class for objects that can merge themselves with another. """ def merge(self, other): """Merges `other` with `self` and returns the merged value. """ raise NotImplementedError() class Summarizable(object): """Base class for objects that can summarize themselves. """ def summarize(self): """Returns a summary dict. """ raise NotImplementedError() class Const(Mergeable): """A :class:`Mergeable` that is a constant value. Merging simply checks that two values are identical. Args: value: The value to treat as a constant. """ def __init__(self, value): self.value = value def merge(self, other): """Check that `self==other`. Raises: ValueError """ if self != other: raise ValueError("{} != {}".format(self, other)) return self def __eq__(self, other): """Returns True if `self.value==other` (or `other.value` if `other` is a :class:`Const`). """ if isinstance(other, Const): other = other.value return self.value == other def __repr__(self): return str(self.value) class Timestamp(object): """Records datetime and clock time at object creation. """ def __init__(self): self.dtime = datetime.now() self.process_time = time.process_time() def timestamp(self): """Returns the unix timestamp. """ return self.dtime.timestamp() def isoformat(self): """Returns the datetime in ISO format. """ return self.dtime.isoformat() def __sub__(self, other, minval=0.01): """Subtract another timestamp from this one. Args: other: The other timestamp. minval: The minimum difference. Returns: A dict of {wallclock=<datetime_diff>, cpu=<clock_diff>}. """ return dict( wallclock=max(minval, self.timestamp() - other.timestamp()), cpu=max(minval, self.process_time - other.process_time)) class Timing(Summarizable): """Context manager that maintains timing information using :class:`Timestamp`s. Maintains a start time on __enter__, and can be updated with the current time by the user. Does a final update on __exit__. """ def __init__(self): self.start_time = None self.cur_time = None def __enter__(self): self.start_time = Timestamp() return self def __exit__(self, exception_type, exception_value, traceback): self.update() def update(self): """Set :attr:`self.cur_time` to the current time. """ self.cur_time = Timestamp() def summarize(self): """Returns a summary dict {start=<start_time>, wallclock=<datetime_diff>, cpu=<clock_diff>}. """ if not self.cur_time: self.update() assert self.start_time is not None summary = dict(start=self.start_time.isoformat()) summary.update(self.cur_time - self.start_time) return summary class CountingDict(dict, Mergeable, Summarizable): """A dictionary that always returns 0 on get of a missing key. Args: sort_by: Whether summary is sorted by key (0) or value (1). """ def __init__(self, keys=None, sort_by=0, summary_type='dict'): super().__init__() self.sort_by = sort_by self.summary_type = summary_type if keys: for key in keys: self.increment(key) def __getitem__(self, name): return self.get(name, 0) def increment(self, key, inc=1): """Increment the count of `key` by `inc`. """ self[key] += inc def merge(self, other): if not isinstance(other, CountingDict): raise ValueError( "Cannot merge object of type {}".format(type(other))) for key, value in other.items(): self[key] += value return self def get_sorted_items(self): """Returns an iterable of (key, value) sorted according to this CountingDict's `sort_by` param. """ return sorted(self.items(), key=lambda item: item[self.sort_by]) def summarize(self): """Returns an OrderedDict of sorted items. """ summary_func = ordered_dict if self.summary_type == 'dict' else tuple return summary_func(self.get_sorted_items()) class Histogram(CountingDict): """Counting dict that returns a summary dict that contains summary stats. """ def summarize(self): hist = super().summarize() return dict( hist=hist, summary=self.get_summary_stats()) def get_summary_stats(self): """Returns dict with mean, median, and modes of histogram. """ values = tuple(self.keys()) counts = tuple(self.values()) mu0 = weighted_mean(values, counts) return dict( mean=mu0, stdev=weighted_stdev(values, counts, mu0), median=weighted_median(values, counts), modes=weighted_modes(values, counts)) class NestedDict(dict, Mergeable, Summarizable): """A dict that initalizes :class:`CountingDict`s for missing keys. Args: shape: The flattened shape: 'long' or 'wide'. """ def __init__(self, shape="wide"): super().__init__() self.shape = shape def __getitem__(self, name): if name not in self: self[name] = CountingDict() return self.get(name) def merge(self, other): if not isinstance(other, NestedDict): raise ValueError( "Cannot merge object of type {}".format(type(other))) for key, value in other.items(): if key in self: self[key].merge(value) else: self[key] = value return self def summarize(self): """Returns a flattened version of the nested dict. Returns: When `shape=='long'`, a list of (key1, key2, value) tuples. When `shape=='wide'`, a dict of {columns:keys2, rows: {key1, values}}, where `keys2` is the set of keys in the child dicts. """ keys1 = sorted(self.keys()) if self.shape == "long": return tuple( (key1, key2, value) for key1 in keys1 for key2, value in self[key1].items()) else: keys2 = set() for child in self.values(): keys2.update(child.keys()) keys2 = tuple(sorted(keys2)) return dict( columns=keys2, rows=ordered_dict( (key1, tuple(self[key1].get(key2, 0) for key2 in keys2)) for key1 in keys1)) class MergingDict(OrderedDict, Mergeable): """An :class:`collections.OrderedDict` that implements :class:`Mergeable`. """ def merge(self, other): """Merge `other` with `self` using :method:`merge_dicts`. """ merge_dicts(self, other) return self def merge_dicts(dest, src): """Merge corresponding items in `src` into `dest`. Values in `src` missing in `dest` are simply added to `dest`. Values that appear in both `src` and `dest` are merged using `merge_values`. Args: dest: The dict to merge into. src: The dict to merge from. Raises: ValueError if a value is not one of the accepted types. """ for key, v_src in src.items(): if dest.get(key, None) is None: dest[key] = v_src elif v_src is not None: dest[key] = merge_values(dest[key], v_src) def merge_values(v_dest, v_src): """Merge two values based on their types, as
<gh_stars>1-10 #!/usr/bin/python3 import json, dateutil, pytz, random, time, traceback, signal import pandas as pd from coin_wizard.historical_pair_data import get_historical_pair_data_pandas, plot_historical_pair_data from coin_wizard.utils import translate_pair_to_splited, translate_pair_to_unsplited import coin_wizard.broker_platform_objects as BrokerPlatform from coin_wizard.broker_platforms.backtesting.instrument import Instrument from datetime import datetime, timedelta from time import sleep price_list = [] # # update_interval_threshold_ms = 50 time_delta_15_seconds = timedelta(seconds=15) time_delta_60_seconds = timedelta(seconds=60) granularity_recent_candles_time_delta = { "M1": timedelta(days=7), "M5": timedelta(days=7*5), "M15": timedelta(days=7*15), "M30": timedelta(days=7*30), "H1": timedelta(days=7*60), "H4": timedelta(days=7*240), "D": timedelta(days=7*240), } granularity_time_delta = { "M1": timedelta(seconds=60), "M5": timedelta(seconds=60*5), "M15": timedelta(seconds=60*15), "M30": timedelta(seconds=60*30), "H1": timedelta(seconds=60*60), "H4": timedelta(seconds=60*240), "D": timedelta(seconds=60*60*24), } utc = pytz.utc half_spread_high_pip = 0.8 half_spread_low_pip = 0.6 min_trailing_stop_distance = 0.0005 pip = 0.0001 time_out_s = 15 def timeout_handler(signum, frame): raise Exception('BrokerEventLoopAPI loop timeout('+str(time_out_s)+' seconds passed).') class BrokerEventLoopAPI(BrokerPlatform.BrokerEventLoopAPI): hedging = False broker_settings_fields = ['balance', 'currency', 'margin_rate', 'start_year_utc', 'start_month_utc', 'start_day_utc', 'start_hour_utc', 'start_minute_utc', 'end_year_utc', 'end_month_utc', 'end_day_utc', 'end_hour_utc', 'end_minute_utc'] def __init__(self, before_loop, after_loop, broker_settings, nsp, loop_interval_ms = 0, hedging=False): super().__init__(before_loop, after_loop, broker_settings, nsp, loop_interval_ms) self.instruments_watchlist = {} self.current_virtual_datetime = utc.localize(datetime( int(broker_settings['start_year_utc']), int(broker_settings['start_month_utc']), int(broker_settings['start_day_utc']), int(broker_settings['start_hour_utc']), int(broker_settings['start_minute_utc']) )) self.end_datetime = utc.localize(datetime( int(broker_settings['end_year_utc']), int(broker_settings['end_month_utc']), int(broker_settings['end_day_utc']), int(broker_settings['end_hour_utc']), int(broker_settings['end_minute_utc']) )) self.hedging = hedging self.account = BrokerPlatform.Account(self._update_account_handler) self.balance = float(broker_settings['balance']) self.account.balance = float(broker_settings['balance']) self.currency = broker_settings['currency'] self.account.currency = broker_settings['currency'] self.margin_rate = float(broker_settings['margin_rate']) self.account.margin_rate = float(broker_settings['margin_rate']) self.account.margin_used = 0.0 self.account.margin_available = float(broker_settings['balance']) self.account.unrealized_pl = 0.0 self.ended_listener = None def order(self, instrument_name, order_settings, trade_settings): instrument = self.getInstrument(instrument_name) bid, ask, d = instrument.getCurrentCloseoutBidAsk() # Start validations units = trade_settings['units'] if "take_profit" in trade_settings: take_profit = trade_settings['take_profit'] else: take_profit = None if "stop_lost" in trade_settings: stop_loss = trade_settings['stop_lost'] else: stop_loss = None if "trailing_stop_distance" in trade_settings: trailing_stop_distance = trade_settings['trailing_stop_distance'] else: trailing_stop_distance = None if order_settings['type'] == 'market': pass elif order_settings['type'] == 'stop': price = order_settings['price'] if 'bound' in order_settings: price_bound = order_settings['bound'] else: price_bound = None if units > 0: if price < ask: raise Exception('Price('+str(price)+') cannot smaller then ask price('+str(ask)+').') if price_bound!=None and price_bound < price: raise Exception('Price bound('+str(price_bound)+') cannot smaller then price('+str(price)+').') elif units < 0: if price > bid: raise Exception('Price('+str(price)+') cannot greater then bid price('+str(bid)+').') if price_bound!=None and price_bound > price: raise Exception('Price bound('+str(price_bound)+') cannot greater then price('+str(price)+').') else: raise Exception('Does not supoort type "'+ order_settings['type']+'".') # Validating trade setting if int(units) - units != 0: raise Exception('Order units must be integer.') elif units == 0: raise Exception('Order units cannot be zero.') elif units > 0: if take_profit!=None and take_profit <= ask: raise Exception('Take profit('+str(take_profit)+') cannot smaller then ask price('+str(ask)+').') if stop_loss!=None and stop_loss >= bid: raise Exception('Stop loss('+str(stop_loss)+') cannot greater then bid price('+str(bid)+').') if trailing_stop_distance!=None and trailing_stop_distance < min_trailing_stop_distance: raise Exception('Trailing stop distance('+str(trailing_stop_distance)+') cannot smaller then mininum trailing stop distance('+str(min_trailing_stop_distance)+').') elif units < 0: if take_profit!=None and take_profit >= bid: raise Exception('Take profit('+str(take_profit)+') cannot greater then bid price('+str(bid)+').') if stop_loss!=None and stop_loss <= ask: raise Exception('Stop loss('+str(stop_loss)+') cannot smaller then ask price('+str(ask)+').') if trailing_stop_distance!=None and trailing_stop_distance < min_trailing_stop_distance: raise Exception('Trailing stop distance('+str(trailing_stop_distance)+') cannot smaller then mininum trailing stop distance('+str(min_trailing_stop_distance)+').') if trailing_stop_distance != None and trailing_stop_distance <= 0: raise Exception('Trailing stop distance('+str(trailing_stop_distance)+') should greater then zero.') order = BrokerPlatform.Order('virtual_order_id', instrument_name, order_settings, trade_settings) order.cancel_handler = self._order_cancel_handler self.account.orders.append(order) return order def getInstrument(self, instrument_name): if instrument_name in self.instruments_watchlist: return self.instruments_watchlist[instrument_name] # print(self.current_virtual_datetime, self.end_datetime) instrument = Instrument(instrument_name, self._update_instrument_handler) for granularity in instrument.recent_candles: instrument.recent_candles[granularity] = get_historical_pair_data_pandas(translate_pair_to_unsplited(instrument_name), self.current_virtual_datetime - granularity_recent_candles_time_delta[granularity], self.current_virtual_datetime, granularity=granularity) instrument.future_candles[granularity] = get_historical_pair_data_pandas(translate_pair_to_unsplited(instrument_name), self.current_virtual_datetime , self.end_datetime + granularity_recent_candles_time_delta[granularity], granularity=granularity) latest_m1_candle = instrument.recent_candles['M1'].tail(1).iloc[0] open = latest_m1_candle['open'] high = latest_m1_candle['high'] low = latest_m1_candle['low'] close = latest_m1_candle['close'] half_spread = random.uniform(half_spread_low_pip, half_spread_high_pip)*pip price = 0.8*random.triangular(low, high)+0.2*random.triangular(min(open, close), max(open, close)) # print(price, half_spread, price-half_spread, price+half_spread, open, high, low, close) instrument.current_closeout_bid = round(float(price-half_spread), 6) instrument.current_closeout_ask = round(float(price+half_spread), 6) instrument.current_closeout_bid_ask_datetime = self.current_virtual_datetime instrument.tradable = True instrument.quaters = 0 # raise self.instruments_watchlist[instrument_name] = instrument return instrument # For Neural Net def resetByDatetime(self, start_datetime, end_datetime): self.instruments_watchlist = {} self.current_virtual_datetime = start_datetime self.end_datetime = end_datetime self.account = BrokerPlatform.Account(self._update_account_handler) self.account.balance = self.balance self.account.margin_rate = self.margin_rate self.account.margin_used = 0.0 self.account.margin_available = self.balance self.account.unrealized_pl = 0.0 def onEnded(self, ended_listener): self.ended_listener = ended_listener def _order_cancel_handler(self, order): order.canceled = True self.account.orders.remove(order) self.order_canceled_listener(order, 'Canceled by user.') order.canceled_listener(order, 'Canceled by user.') def _trade_close_handler(self, trade): instrument = self.instruments_watchlist[trade.instrument_name] current_units = trade.trade_settings['current_units'] ask_price = instrument.current_closeout_ask bid_price = instrument.current_closeout_bid spread = ask_price-bid_price realized_pl = 0.0 if current_units > 0: realized_pl = current_units*(bid_price - trade.open_price) trade.unrealized_pl = 0.0 trade.closed = True self.account.trades.remove(trade) self.account.balance += realized_pl self.account.margin_used -= trade.margin_rate*abs(current_units)*(ask_price+bid_price)/2.0 self.account.unrealized_pl -= realized_pl self.trade_closed_listener(trade, realized_pl, bid_price, spread, self.current_virtual_datetime) trade.closed_listener(trade, realized_pl, bid_price, spread, self.current_virtual_datetime) else: realized_pl = -current_units*(trade.open_price - ask_price) trade.unrealized_pl = 0.0 trade.closed = True self.account.trades.remove(trade) self.account.balance += realized_pl self.account.margin_used -= trade.margin_rate*abs(current_units)*(ask_price+bid_price)/2.0 self.account.unrealized_pl -= realized_pl self.trade_closed_listener(trade, realized_pl, ask_price, spread, self.current_virtual_datetime) trade.closed_listener(trade, realized_pl, ask_price, spread, self.current_virtual_datetime) def _trade_reduce_handler(self, trade, units): instrument = self.instruments_watchlist[trade.instrument_name] reduce_units = abs(units) ask_price = instrument.current_closeout_ask bid_price = instrument.current_closeout_bid spread = ask_price-bid_price realized_pl = 0.0 if trade.trade_settings['current_units'] > 0: realized_pl = reduce_units*(bid_price - trade.open_price) trade.trade_settings['current_units'] -= reduce_units trade.unrealized_pl -= realized_pl self.account.balance += realized_pl self.account.margin_used -= trade.margin_rate*abs(reduce_units)*(ask_price+bid_price)/2.0 self.account.unrealized_pl -= realized_pl self.trade_reduced_listener(trade, -reduce_units, realized_pl, bid_price, spread, self.current_virtual_datetime) trade.reduced_listener(trade, -reduce_units, realized_pl, bid_price, spread, self.current_virtual_datetime) else: realized_pl = reduce_units*(trade.open_price - ask_price) trade.trade_settings['current_units'] += reduce_units trade.unrealized_pl -= realized_pl self.account.balance += realized_pl self.account.margin_used -= trade.margin_rate*abs(reduce_units)*(ask_price+bid_price)/2.0 self.account.unrealized_pl -= realized_pl self.trade_reduced_listener(trade, reduce_units, realized_pl, ask_price, spread, self.current_virtual_datetime) trade.reduced_listener(trade, reduce_units, realized_pl, ask_price, spread, self.current_virtual_datetime) def _trade_modify_handler(self, trade, trade_settings): pass def _update_instrument_handler(self, instrument): pass # No need for backtesting. def _update_account_handler(self): self.account.equity = self.account.balance+self.account.unrealized_pl self.account.margin_available = max(0, self.account.equity-self.account.margin_used) def _update_trade_handler(self, trade): pass # No need for backtesting. # def _trade_close(self, trade): # trade.closed = True # self.account.trades.remove(trade) # self.account.balance += unrealized_pl # trade.closed_listener(trade, unrealized_pl, bid_price, spread, self.current_virtual_datetime) def _instrument_loop(self): # Update instruments for instrument_name in self.instruments_watchlist: instrument = self.instruments_watchlist[instrument_name] for granularity in instrument.recent_candles: if instrument.active_candle[granularity] is None or self.current_virtual_datetime - instrument.active_candle[granularity]['timestamp'][0].to_pydatetime() >= granularity_time_delta['M1']: if self.current_virtual_datetime.timestamp() - instrument.future_candles[granularity]['timestamp'][0].to_pydatetime().timestamp() >= 0: if instrument.active_candle[granularity] is not None: instrument.recent_candles[granularity].loc[len(instrument.recent_candles[granularity])] = instrument.active_candle[granularity].head(1).iloc[0] instrument.active_candle[granularity] = instrument.future_candles[granularity].head(1).reset_index(drop=True) instrument.future_candles[granularity] = instrument.future_candles[granularity][instrument.future_candles[granularity]['timestamp'] > self.current_virtual_datetime].reset_index(drop=True) if granularity == 'M1': instrument.quaters = 0 instrument.tradable = True else: if granularity == 'M1': instrument.tradable = False if instrument.tradable: quaters_of_1m = instrument.quaters # print(instrument.active_candle[granularity]) open = instrument.active_candle['M1']['open'][0] high = instrument.active_candle['M1']['high'][0] low = instrument.active_candle['M1']['low'][0] close = instrument.active_candle['M1']['close'][0] half_spread = random.uniform(half_spread_low_pip, half_spread_high_pip)*pip bound_to_close = open+0.25*(close-open)*quaters_of_1m # print(quaters_of_1m) price = 0.7*random.triangular(low, high)+0.2*random.triangular(min(bound_to_close, close), max(bound_to_close, close))+0.1*close instrument.current_closeout_bid = round(float(price-half_spread), 6) instrument.current_closeout_ask = round(float(price+half_spread), 6) instrument.current_closeout_bid_ask_datetime = self.current_virtual_datetime instrument.quaters += 1 def _trade_and_account_loop(self): # Update trades, caluculate PL. unrealized_pl_sum = 0.0 margin_used_sum = 0.0 for trade in self.account.trades: instrument = self.instruments_watchlist[trade.instrument_name] current_units = trade.trade_settings['current_units'] ask_price = instrument.current_closeout_ask bid_price = instrument.current_closeout_bid spread = ask_price-bid_price unrealized_pl = 0.0 # Check if we need to close trade trade_settings = trade.trade_settings if current_units > 0: unrealized_pl = current_units*(bid_price - trade.open_price) trade.unrealized_pl = unrealized_pl if "take_profit" in trade_settings: take_profit = trade_settings['take_profit'] if bid_price >= take_profit: trade.closed = True self.account.trades.remove(trade) self.account.balance += unrealized_pl self.trade_closed_listener(trade, unrealized_pl, bid_price, spread, self.current_virtual_datetime) trade.closed_listener(trade, unrealized_pl, bid_price, spread, self.current_virtual_datetime) continue if "stop_lost" in trade_settings: stop_loss = trade_settings['stop_lost'] if bid_price <= stop_loss: trade.closed = True self.account.trades.remove(trade) self.account.balance += unrealized_pl self.trade_closed_listener(trade, unrealized_pl, bid_price, spread, self.current_virtual_datetime) trade.closed_listener(trade, unrealized_pl, bid_price, spread, self.current_virtual_datetime) continue if "trailing_stop_distance" in trade_settings: trailing_stop_distance = trade_settings['trailing_stop_distance'] trade.trailing_stop_value = max(trade.trailing_stop_value, bid_price-trailing_stop_distance) trailing_stop_value = trade.trailing_stop_value if bid_price <= trailing_stop_value: trade.closed = True self.account.trades.remove(trade) self.account.balance += unrealized_pl self.trade_closed_listener(trade, unrealized_pl, bid_price, spread, self.current_virtual_datetime) trade.closed_listener(trade, unrealized_pl, bid_price, spread, self.current_virtual_datetime) continue else: unrealized_pl = -current_units*(trade.open_price - ask_price) trade.unrealized_pl = unrealized_pl if "take_profit" in trade_settings: take_profit = trade_settings['take_profit'] if ask_price <= take_profit: trade.closed = True self.account.trades.remove(trade) self.account.balance += unrealized_pl self.trade_closed_listener(trade, unrealized_pl, ask_price, spread, self.current_virtual_datetime) trade.closed_listener(trade, unrealized_pl, ask_price, spread, self.current_virtual_datetime) continue if "stop_lost" in trade_settings: stop_loss = trade_settings['stop_lost'] if ask_price >= stop_loss: trade.closed = True self.account.trades.remove(trade) self.account.balance += unrealized_pl self.trade_closed_listener(trade, unrealized_pl, ask_price, spread, self.current_virtual_datetime) trade.closed_listener(trade, unrealized_pl, ask_price, spread, self.current_virtual_datetime) continue if "trailing_stop_distance" in trade_settings: trailing_stop_distance = trade_settings['trailing_stop_distance'] trade.trailing_stop_value = min(trade.trailing_stop_value, ask_price+trailing_stop_distance) trailing_stop_value = trade.trailing_stop_value if ask_price >= trailing_stop_value: trade.closed = True self.account.trades.remove(trade) self.account.balance += unrealized_pl self.trade_closed_listener(trade, unrealized_pl, ask_price, spread, self.current_virtual_datetime) trade.closed_listener(trade, unrealized_pl, ask_price, spread, self.current_virtual_datetime) continue unrealized_pl_sum += unrealized_pl margin_used_sum += trade.margin_rate*abs(current_units)*(ask_price+bid_price)/2.0 self.account.margin_used = margin_used_sum self.account.unrealized_pl = unrealized_pl_sum # print(unrealized_pl_sum, margin_used_sum) # Check account states. Margin Closeout etc. equity = self.account.balance+unrealized_pl_sum self.account.margin_available = max(0, equity-margin_used_sum) if margin_used_sum* 0.5 > equity: raise Exception('You have a margin closeout!') def _order_loop(self): # Update orders. orders_to_be_canceled = [] orders_to_be_filled = [] for
<filename>outgrab_tools.py<gh_stars>0 #!/usr/bin/python3 """outgrab: Programatically select important information from large files and send it to other files for human or program consumption. outgrab.py Can be invoked as a program interpreter or outgrab_tools.py and outgrab_startup can be imported as a library of python classes and methods. """ #------------------------------------------------------------------------------- # Why would you use this program instead of grep, sed, awk, cut, paste, etc.? # 1. Because you forget how to use all of the options of those programs. # 2. Because outgrab maintains its state (the current line) between commands: # this can make a sequence of commands more simple and more efficient. # 3. Because the commands included are very close to what you would do by hand # when searching through an output file and selecting the bits of interest. #------------------------------------------------------------------------------- # Usage: # # See near the end of this file for a summary of the outgrab command language. # # Input text files can either come from stdin and optionally from the -i flag. # These will be treated separately and are named $file1, $file2, etc. # Output goes to stdout or may be redirected into an output file # If mytest.grab contains outgrab commands, use the outgrab interpreter: # python outgrab.py -p mytest.grab < a.txt # python outgrab.py -p mytest.grab < a.txt > output.ext # cat *.txt | python -p mytest.grab > output.txt # where mytest.grab contains outgrab commands, a.txt is an input text file, # and output.txt is an output file. The first version sends output to the screen # and the last version concatenates all .txt files in the current directory and uses them as input. # e.g. # Use as a python class/method library is less well tested. See outgrab.py as a starter. # If mytest.py contains python statements using the classes and functions within this file: # e.g. python mytest.py < a.txt # python mytest.py < a.txt > output.txt # python mytest.py -i b.txt < a.txt > output.txt # cat *.txt | python mytest.py > output.txt (files concatenated and together named $file1) # #------------------------------------------------------------------------------- import sys import os import re import logging from outgrab_startup import getparser, setlogging, setverbositylevels # global variables related to messaging verbosity = 0 maxlevel = 4 ogdebug = 0 ogverbose = 0 oginfo = 0 ogmain = 0 parserargs = "" msg = "" # and a global dictionary to hold the internal files by their names ifilesd = {} #standard filename prefix; use with a postfix number in addfilename filebase = "$file" # # module level functions # def startup(): # Set up command line parsing; get verbosity level from command line global parserargs global verbosity, maxlevel parserargs = getparser() verbosity = parserargs.verbosity setuplogging() return def setuplogging(): global msg global ogdebug, ogverbose, oginfo, ogmain # Set up logging levels from most verbose to least. myloglevel = setverbositylevels(verbosity,verbosity_default=2) myloglevelnames = ("ogdebug","ogverbose","oginfo","ogmain") (msg, maxlevel, ( ogdebug, ogverbose, oginfo, ogmain)) = setlogging(myloglevel,myloglevelnames) #Demonstration/Test of logging. #Only those with log(verbosity) level >=(<=) loglevel(verbosity) should be printed. msg(ogmain, "printing status messages at verbosity level {} (ogmain)".format(maxlevel-ogmain+1)) msg(oginfo, "printing status messages at verbosity level {} (oginfo)".format(maxlevel-oginfo+1)) msg(ogverbose,"printing status messages at verbosity level {} (ogverbose)".format(maxlevel-ogverbose+1)) msg(ogdebug, "printing debug messages at verbosity level {} (ogdebug)".format(maxlevel-ogdebug+1)) def runoutgrab(programfile,verboseness,outputfile,*inputfiles): """ function to set up files and launch outgrab from your program needs explicit file paths or local names for programfile, outputfile, and an arbitrary number of inputfiles """ global verbosity verbosity = verboseness setuplogging() # create program file filenum = 0 pgmfh = open(programfile, "r") x = createInputFile(pgmfh,ProgramFile) pgmfh.close() addfilename(x,filebase,filenum) addfilename(x,"program") msg(oginfo,"Creating program file with names = {}".format(x.names)) # create output file y = OutputFile() addfilename(x,outputfile) y.filename = outputfile msg(oginfo,"Creating output file with names: {}".format(y.names)) # create scratch file x = createScratchFile("ScratchFile") addfilename(x,"scratch") msg(oginfo,"Creating scratch file with names: {}".format(x.names)) # create input files for myfile in inputfiles: filenum += 1 readinputfile(myfile,filenum) # Assign input and output files for the outgrab program so it processes the former and writes to the latter # Initial focus is on the input file coming from stdin x = getfilefromname("$file1") z = getfilefromname("program") z.setinputfile(x) z.setoutputfile(y) # Process the outgrab program file z.processcommands() # Write the output file outf = open(y.filename,"w") y.writefile(outf) outf.close() def readinputfile(myfile,filenum): """ given the path/name of a file, read it in to an internal input file give it a name filebase ($file) + str(filenum) """ fh = open(myfile, "r") x = createInputFile(fh,InputFile) fh.close() addfilename(x,filebase,filenum) # create the standard filename ($fileN) msg(ogdebug,"Creating input file with names = {}".format(x.names)) def createInputFiles(): """Create input files from the command line: from stdin, from --inputfiles, and also create an empty scratch file Return them in a dictionary with standard names as keys: names = ("$file1", "$file2", etc. ) Also give them names name = <stdin>, filename from the command line, or "scratch" """ global ifilesd # Create InputFile from stdin msg(oginfo,"Creating input files from stdin") x = createInputFile(sys.stdin,InputFile) filenum = 1 addfilename(x,filebase,filenum) msg(oginfo,"Names = {}".format(x.names)) # Create any files from input argument "-i" or "--inputfiles" if parserargs.inputfiles: msg(oginfo,"Creating input files from -i or --inputfiles") for myfile in parserargs.inputfiles: msg(ogdebug,"file = {}".format(myfile)) filenum += 1 x = createInputFile(myfile,InputFile) addfilename(x,filebase,filenum) msg(oginfo,"Names = {}".format(x.names)) # Create outgrab program files from input argument "-p" or "--program" if parserargs.program: msg(oginfo,"Creating program files from -p or --program") filenum = 0 x = createInputFile(parserargs.program,ProgramFile) addfilename(x,filebase,filenum) addfilename(x,"program") msg(oginfo,"Names = {}".format(x.names)) # now create one empty file named "scratch" for a scratch space # ignore the original name created x = createScratchFile("Scratch") addfilename(x,"scratch") msg(oginfo,"Creating scratch file with names: \"{}\"".format(x.names)) msg(ogdebug,"The ifilesd dictionary at end of createInputFiles:") for key,value in ifilesd.items(): msg(ogdebug,"name= {} : object = {}".format(key,value)) def createScratchFile(content): # create ScratchFile object newfile = ScratchFile(content) msg(ogdebug,"new file object: {}".format(newfile)) try: addfilename(newfile,content.name) except: pass return newfile def createInputFile(content,Inp): # create Inp=InputFile or ProgramFile object from filehandler,string, or list of strings newfile = Inp(content) msg(ogdebug,"new file object: {}".format(newfile)) # add a blank line at the end of the new file (to prevent matches on last line repeating...) newfile.addblankline() # note "bottom" set to line before this blank line try: addfilename(newfile,content.name) except: pass return newfile def getnextfilenum(): """ look through ifilesd for all files named $filexyz (actually filebasexyz) and return the highest int(xyz) + 1: to be used as the next filenum """ largest = -1 start = len(filebase) for key in ifilesd.keys(): if key.startswith(filebase): oldfilenum = int(key[start:]) if oldfilenum > largest: largest = oldfilenum return largest+1 def getfilefromname(name): # returns the internal file object corresponding to myname return ifilesd[name] def samevaluekeys(mykey,mydict): sameas = [k for k,v in mydict.items() if v == mydict[mykey]] return sameas def listofsamevaluekeys(mydict): usedkeys = [] dumplist = [] for key in mydict.keys(): if key not in usedkeys: samekeys = samevaluekeys(key,mydict) dumplist.append(samekeys) for item in samekeys: usedkeys.append(item) return dumplist def addfilename(fileobj,name,postfix=""): # add a name for fileobj to the ifilesd dictionary # and to the attribute list of names for the object # if postfix is present, it is added to the end of name # (to create standard names like $file1) global ifilesd if isinstance(postfix,int): postfix = str(postfix) name = name + postfix ifilesd[name] = fileobj fileobj.names.append(name) msg(oginfo,"Adding name {} for file object {}".format(name,fileobj)) def setfilename(*names): # give an internal file a new name (old one remains unless you overwrite it) # first names should be old one, 2nd is new one. x = getfilefromname(names[0]) addfilename(x,names[1]) def stringlisttostring(stringlist,delim=" "): # Concatenate each string in stringlist togther with delimiter between them. result = "" for mystring in stringlist: #does this ignore empty strings ("") ? result += (mystring + delim) result.rstrip() msg(ogdebug,"--in stringlisttostring, result= \"{}\"".format(result)) return result def stringtostringlist(mystring,delim="whitespace"): # split mystring into fields based on a regular expression delimiter # returns list of strings msg(ogdebug,"getting fields from string based on delimiter = {}".format(delim)) if delim == "whitespace": delim = "[\s]+" # regular expression version if delim == "comma": delim = "[,]" # regular expression version. no + so that empty fields are maintained stringlist = re.split(delim,mystring) # regular expression version msg(ogdebug,"stringtostringlist found {} fields".format(len(stringlist))) msg(ogdebug,"--list of fields:") msg(ogdebug,stringlist) return stringlist def getslicelist(mystring,startend): # get sections of mystring beginning at character (or column) start # and ending with character (or column) end; return as new string. # startend is list of tuples, each with a start and end # [(start1,end1),(start2,end2),...] # Returns a list of the resulting string slices mylength = len(mystring) msg(ogdebug,"string has
100451 eumIMass = 100452 eumIMassPerTime = 100453 eumIMassPerAreaPerTime = 100454 eumIKd = 100455 eumIPorosity = 100456 eumIHalfLife = 100457 eumIDispersivity = 100458 eumIFrictionCoeffientcfw = 100459 eumIWaveamplitude = 100460 eumISedimentGrainDiameter = 100461 eumISedimentSpill = 100463 eumINumberOfParticles = 100464 eumIEllipsoidalHeight = 100500 eumICloudiness = 100501 eumIProbability = 100502 eumIDispersantActivity = 100503 eumIDredgeRate = 100504 eumIDredgeSpill = 100505 eumIClearnessCoefficient = 100506 eumIProfileOrientation = 100507 eumIReductionFactor = 100508 eumIActiveBeachHeight = 100509 eumIUpdatePeriod = 100510 eumIAccumulatedErosion = 100511 eumIErosionRate = 100512 eumINonDimTransport = 100513 eumILocalCoordinate = 100514 eumIRadiiOfGyration = 100515 eumIPercentage = 100516 eumILineCapacity = 100517 eumIDiverteddischarge = 110001 eumIDemandcarryoverfraction = 110002 eumIGroundwaterdemand = 110003 eumIDamcrestlevel = 110004 eumISeepageflux = 110005 eumISeepagefraction = 110006 eumIEvaporationfraction = 110007 eumIResidencetime = 110008 eumIOwnedfractionofinflow = 110009 eumIOwnedfractionofvolume = 110010 eumIReductionlevel = 110011 eumIReductionthreshold = 110012 eumIReductionfraction = 110013 eumITotalLosses = 110014 eumICountsPerLiter = 110015 eumIAssimilativeCapacity = 110016 eumIStillWaterDepth = 110017 eumITotalWaterDepth = 110018 eumIMaxWaveHeight = 110019 eumIIceConcentration = 110020 eumIWindFrictionSpeed = 110021 eumIRoughnessLength = 110022 eumIWindDragCoefficient = 110023 eumICharnockConstant = 110024 eumIBreakingParameterGamma = 110025 eumIThresholdPeriod = 110026 eumICourantNumber = 110027 eumITimeStepFactor = 110028 eumIElementLength = 110029 eumIElementArea = 110030 eumIRollerAngle = 110031 eumIRateBedLevelChange = 110032 eumIBedLevelChange = 110033 eumISedimentTransportDirection = 110034 eumIWaveActionDensity = 110035 eumIZeroMomentWaveAction = 110036 eumIFirstMomentWaveAction = 110037 eumIBedMass = 110038 eumIEPANETWaterQuality = 110039 eumIEPANETStatus = 110040 eumIEPANETSetting = 110041 eumIEPANETReactionRate = 110042 eumIFRDischarge = 110043 eumISRDischarge = 110044 eumIAveSediTransportPerLengthUnit = 110045 eumIValveSetting = 110046 eumIWaveEnergyDensity = 110047 eumIWaveEnergyDistribution = 110048 eumIWaveEnergy = 110049 eumIRadiationMeltingCoefficient = 110050 eumIRainMeltingCoefficientPerDegree = 110051 eumIEPANETFriction = 110052 eumIWaveActionDensityRate = 110053 eumIElementAreaLongLat = 110054 eumIElectricCurrent = 110100 eumIHeatFluxResistance = 110200 eumIAbsoluteHumidity = 110210 eumILength = 110220 eumIArea = 110225 eumIVolume = 110230 eumIElementVolume = 110231 eumIWavePower = 110232 eumIMomentOfInertia = 110233 eumITopography = 110234 eumIScourDepth = 110235 eumIScourWidth = 110236 eumICostPerVolume = 110237 eumICostPerEnergy = 110238 eumICostPerMass = 110239 eumIApplicationIntensity = 110240 eumICost = 110241 eumIVoltage = 110242 eumINormalVelocity = 110243 eumIGravity = 110244 eumIVesselDisplacement = 110245 eumIHydrostaticMatrix = 110246 eumIWaveNumber = 110247 eumIRadiationPotential = 110248 eumIAddedMassTT = 110249 eumIRadiationDamping = 110250 eumIFrequency = 110251 eumISoundExposureLevel = 110252 eumITransmissionLoss = 110253 eumIpH = 110254 eumIAcousticAttenuation = 110255 eumISoundSpeed = 110256 eumILeakage = 110257 eumIHeightAboveKeel = 110258 eumISubmergedMass = 110259 eumIDeflection = 110260 eumILinearDampingCoefficient = 110261 eumIQuadraticDampingCoefficient = 110262 eumIDampingTT = 110263 eumIRAOmotion = 110264 eumIRAOrotation = 110265 eumIAddedMassCoefficient = 110266 eumIElectricConductivity = 110267 eumIAddedMassTR = 110268 eumIAddedMassRT = 110269 eumIAddedMassRR = 110270 eumIDampingTR = 110271 eumIDampingRT = 110272 eumIDampingRR = 110273 eumIFenderForce = 110274 eumIForce = 110275 eumIMoment = 110276 eumIReducedPollutantLoad = 110277 eumISizeAndPosition = 110278 eumIFrameRate = 110279 eumIDynamicViscosity = 110280 eumIGridRotation = 110281 eumIAgentDensity = 110282 eumIEmitterCoefficient = 110283 eumIPipeDiameter = 110284 eumISpeed = 110285 eumIVelocity = 110286 eumIDirection = 110287 eumIDisplacement = 110288 eumIPosition = 110289 eumIRotation = 110290 eumITorque = 110291 eumIOvertopping = 110292 eumIFlowRate = 110293 eumIAcceleration = 110294 eumIDimensionlessAcceleration = 110295 eumITime = 110296 eumIResistance = 110297 eumIAmountOfSubstance = 110298 eumIMolarConcentration = 110299 eumIMolalConcentration = 110300 eumISuspSedimentLoadPerArea = 110301 eumIBollardForce = 110302 eumIDischargePerPressure = 110303 eumIRotationalSpeed = 110304 eumIInfiltrationPerArea = 110305 eumIMassPerLengthPerTime = 110306 eumINearBedLoadPerLength = 110307 eumISubstancePerUnitArea = 110308 eumIAccNearBedLoadPerLength = 110309 eumIThermalConductivity = 110310 eumIDirectionalVariance = 110311 eumISpecificDissipationRate = 110312 # Predefined enums of EUM units. # # Must be updated with every new release, or if the EUM.xml is updated class eumUnit(IntEnum): eumUUnitUndefined = 0 eumUmeter = 1000 eumUkilometer = 1001 eumUmillimeter = 1002 eumUfeet = 1003 eumUinch = 1004 eumUmile = 1005 eumUyard = 1006 eumUcentimeter = 1007 eumUmicrometer = 1008 eumUnauticalmile = 1009 eumUmillifeet = 1010 eumULiterPerM2 = 1011 eumUMilliMeterD50 = 1012 eumUinchUS = 1013 eumUfeetUS = 1014 eumUyardUS = 1015 eumUmileUS = 1016 eumUkilogram = 1200 eumUgram = 1201 eumUmilligram = 1202 eumUmicrogram = 1203 eumUton = 1204 eumUkiloton = 1205 eumUmegaton = 1206 eumUPound = 1207 eumUtonUS = 1208 eumUounce = 1209 eumUperKilogram = 1250 eumUperGram = 1251 eumUperMilligram = 1252 eumUperMicrogram = 1253 eumUperTon = 1254 eumUperKiloton = 1255 eumUperMegaton = 1256 eumUperPound = 1257 eumUperTonUS = 1258 eumUperOunce = 1259 eumUsec = 1400 eumUminute = 1401 eumUhour = 1402 eumUday = 1403 eumUyear = 1404 eumUmonth = 1405 eumUmillisec = 1406 eumUm3 = 1600 eumUliter = 1601 eumUmilliliter = 1602 eumUft3 = 1603 eumUgal = 1604 eumUmgal = 1605 eumUkm3 = 1606 eumUacft = 1607 eumUMegaGal = 1608 eumUMegaLiter = 1609 eumUTenTo6m3 = 1610 eumUm3PerCurrency = 1611 eumUgalUK = 1612 eumUMegagalUK = 1613 eumUydUS3 = 1614 eumUYard3 = 1615 eumUm3PerSec = 1800 eumUft3PerSec = 1801 eumUMlPerDay = 1802 eumUMgalPerDay = 1803 eumUacftPerDay = 1804 eumUm3PerYear = 1805 eumUGalPerDayPerHead = 1806 eumULiterPerDayPerHead = 1807 eumUm3PerSecPerHead = 1808 eumUliterPerPersonPerDay = 1809 eumUm3PerDay = 1810 eumUGalPerSec = 1811 eumUGalPerDay = 1812 eumUGalPerYear = 1813 eumUft3PerDay = 1814 eumUft3PerYear = 1815 eumUm3PerMinute = 1816 eumUft3PerMin = 1817 eumUGalPerMin = 1818 eumUliterPerSec = 1819 eumUliterPerMin = 1820 eumUm3PerHour = 1821 eumUgalUKPerDay = 1822 eumUMgalUKPerDay = 1823 eumUft3PerDayPerHead = 1824 eumUm3PerDayPerHead = 1825 eumUGalUKPerSec = 1826 eumUGalUKPerYear = 1827 eumUGalUKPerDayPerHead = 1828 eumUydUS3PerSec = 1829 eumUyard3PerSec = 1830 eumUftUS3PerSec = 1831 eumUftUS3PerMin = 1832 eumUftUS3PerDay = 1833 eumUftUS3PerYear = 1834 eumUyardUS3PerSec = 1835 eumUliterPerDay = 1836 eumUmeterPerSec = 2000 eumUmillimeterPerHour = 2001 eumUfeetPerSec = 2002 eumUliterPerSecPerKm2 = 2003 eumUmillimeterPerDay = 2004 eumUacftPerSecPerAcre = 2005 eumUmeterPerDay = 2006 eumUft3PerSecPerMi2 = 2007 eumUmeterPerHour = 2008 eumUfeetPerDay = 2009 eumUmillimeterPerMonth = 2010 eumUinchPerSec = 2011 eumUmeterPerMinute = 2012 eumUfeetPerMinute = 2013 eumUinchPerMinute = 2014 eumUfeetPerHour = 2015 eumUinchPerHour = 2016 eumUmillimeterPerSecond = 2017 eumUcmPerHour = 2018 eumUknot = 2019 eumUmilePerHour = 2020 eumUkilometerPerHour = 2021 eumUAcreFeetPerDayPerAcre = 2022 eumUCentiMeterPerSecond = 2023 eumUCubicFeetPerSecondPerAcre = 2024 eumUCubicMeterPerDayPerHectar = 2025 eumUCubicMeterPerHourPerHectar = 2026 eumUCubicMeterPerSecondPerHectar = 2027 eumUGallonPerMinutePerAcre = 2028 eumULiterPerMinutePerHectar = 2029 eumULiterPerSecondPerHectar = 2030 eumUMicroMeterPerSecond = 2031 eumUMillionGalPerDayPerAcre = 2032 eumUMillionGalUKPerDayPerAcre = 2033 eumUMillionLiterPerDayPerHectar = 2034 eumUinchUSPerSecond = 2035 eumUfeetUSPerSecond = 2036 eumUfeetUSPerDay = 2037 eumUinchUSPerHour = 2038 eumUinchUSPerMinute = 2039 eumUmillimeterPerYear = 2040 eumUCubicFeetPerHourPerAcre = 2041 eumUCubicFeetPerDayPerAcre = 2042 eumULiterPerHourPerHectar = 2043 eumULiterPerDayPerHectar = 2044 eumUMeterPerSecondPerSecond = 2100 eumUFeetPerSecondPerSecond = 2101 eumUkiloGramPerM3 = 2200 eumUmicroGramPerM3 = 2201 eumUmilliGramPerM3 = 2202 eumUgramPerM3 = 2203 eumUmicroGramPerL = 2204 eumUmilliGramPerL = 2205 eumUgramPerL = 2206 eumUPoundPerCubicFeet = 2207 eumUtonPerM3 = 2208 eumUPoundPerSquareFeet = 2209 eumUtonPerM2 = 2210 eumUmicroGramPerM2 = 2211 eumUPoundPerydUS3 = 2212 eumUPoundPeryard3 = 2213 eumUPoundPerCubicFeetUS = 2214 eumUPoundPerSquareFeetUS = 2215 eumUouncePerCubicFeet = 2216 eumUouncePerCubicFeetUS = 2217 eumUouncePerYard3 = 2218 eumUouncePerYardUS3 = 2219 eumUouncePerSquareFeet = 2220 eumUouncePerSquareFeetUS = 2221 eumUKiloGramPerMeterPerSecond = 2300 eumUPascalSecond = 2301 eumUkilogramPerMeterPerDay = 2302 eumUgramPerMeterPerDay = 2303 eumUgramPerKmPerDay = 2304 eumUpoundPerFeetPerDay = 2305 eumUpoundPerFeetUSPerDay = 2306 eumUouncePerFeetPerDay = 2307 eumUouncePerFeetUSPerDay = 2308 eumUkilogramPerYardPerSecond = 2309 eumUkilogramPerFeetPerSecond = 2310 eumUpoundPerYardPerSecond = 2311 eumUpoundPerFeetPerSecond = 2312 eumUradian = 2400 eumUdegree = 2401 eumUDegreeNorth50 = 2402 eumUdegreesquared = 2403 eumUradiansquared = 2404 eumUdegreePerMeter = 2500 eumUradianPerMeter = 2501 eumUdegreePerSecond = 2510 eumUradianPerSecond = 2511 eumUperDay = 2600 eumUpercentPerDay = 2601 eumUhertz = 2602 eumUperHour = 2603 eumUcurrencyPerYear = 2604 eumUperSec = 2605 eumUbillionPerDay = 2606 eumUtrillionPerYear = 2607 eumUSquareMeterPerSecondPerHectar = 2608 eumUSquareFeetPerSecondPerAcre = 2609 eumURevolutionPerMinute = 2610 eumUpercentPerHour = 2611 eumUpercentPerMinute = 2612 eumUpercentPerSecond = 2613 eumURevolutionPerSecond = 2614 eumURevolutionPerHour = 2615 eumUdegreeCelsius = 2800 eumUdegreeFahrenheit = 2801 eumUdegreeKelvin = 2802 eumUperDegreeCelsius = 2850 eumUperDegreeFahrenheit = 2851 eumUdeltaDegreeCelsius = 2900 eumUdeltaDegreeFahrenheit = 2901 eumUmillPer100ml = 3000 eumUPer100ml = 3001 eumUperLiter = 3002 eumUperM3 = 3003 eumUperMilliliter = 3004 eumUperFt3 = 3005 eumUperGallon = 3006 eumUperMilligallon = 3007 eumUperKm3 = 3008 eumUperAcft = 3009 eumUperMegagallon = 3010 eumUperMegaliter = 3011 eumUperGallonUK = 3012 eumUperMegagallonUK = 3013 eumUperYardUS3 = 3014 eumUperYard3 = 3015 eumUSecPerMeter = 3100 eumUm2 = 3200 eumUm3PerM = 3201 eumUacre = 3202 eumUft2 = 3203 eumUha = 3204 eumUkm2 = 3205 eumUmi2 = 3206 eumUft3PerFt = 3207 eumUftUS2 = 3208 eumUydUS2 = 3209 eumUmiUS2 = 3210 eumUacreUS = 3211 eumUydUS3PeryardUS = 3212 eumUYard3PerYard = 3213 eumUftUS3PerftUS = 3214 eumUliterPerMeter = 3215 eumUEPerM2PerDay = 3400 eumUThousandPerM2PerDay = 3401 eumUPerM2PerSec = 3402
list """ dummy_pos_and_or = [(pos, Direction.NORTH) for pos in player_positions] return cls.from_players_pos_and_or(dummy_pos_and_or, bonus_orders, all_orders) def deepcopy(self): return OvercookedState( players=[player.deepcopy() for player in self.players], objects={pos:obj.deepcopy() for pos, obj in self.objects.items()}, bonus_orders=[order.to_dict() for order in self.bonus_orders], all_orders=[order.to_dict() for order in self.all_orders], timestep=self.timestep) def time_independent_equal(self, other): order_lists_equal = self.all_orders == other.all_orders and self.bonus_orders == other.bonus_orders return isinstance(other, OvercookedState) and \ self.players == other.players and \ set(self.objects.items()) == set(other.objects.items()) and \ order_lists_equal def __eq__(self, other): return self.time_independent_equal(other) and self.timestep == other.timestep def __hash__(self): order_list_hash = hash(tuple(self.bonus_orders)) + hash(tuple(self.all_orders)) return hash( (self.players, tuple(self.objects.values()), order_list_hash) ) def __str__(self): return 'Players: {}, Objects: {}'.format( str(self.players), str(list(self.objects.values()))) def to_dict(self): return { "players": [p.to_dict() for p in self.players], "objects": [obj.to_dict() for obj in self.objects.values()], "bonus_orders": [order.to_dict() for order in self.bonus_orders], "all_orders" : [order.to_dict() for order in self.all_orders], "timestep" : self.timestep } @staticmethod def from_dict(state_dict): state_dict = copy.deepcopy(state_dict) state_dict["players"] = [PlayerState.from_dict(p) for p in state_dict["players"]] object_list = [SoupState.from_dict(o) for o in state_dict["objects"]] state_dict["objects"] = { ob.position : ob for ob in object_list } return OvercookedState(**state_dict) class ReducedOvercookedState(object): """A reduced state in OvercookedGridworld. Used to specify only properties RL agents care about.""" def __init__(self, full_overcooked_state): """ players (list(PlayerState)): Currently active PlayerStates (index corresponds to number) objects (dict({tuple:list(ObjectState)})): Dictionary mapping positions (x, y) to ObjectStates. NOTE: Does NOT include objects held by players (they are in the PlayerState objects). """ self.players = full_overcooked_state.players self.objects = full_overcooked_state.objects def __eq__(self, other): return isinstance(other, ReducedOvercookedState) and \ self.players == other.players and \ set(self.objects.items()) == set(other.objects.items()) def __hash__(self): objects = {k: v for k, v in sorted(self.objects.items(), key=lambda item: item[1])} return hash( (self.players, tuple(objects)) ) def __str__(self): objects = {k: v for k, v in sorted(self.objects.items(), key=lambda item: item[1])} return 'Players: , Objects: {}'.format( str(self.players), str(list(objects))) BASE_REW_SHAPING_PARAMS = { "PLACEMENT_IN_POT_REW": 3, "DISH_PICKUP_REWARD": 3, "SOUP_PICKUP_REWARD": 5, "DISH_DISP_DISTANCE_REW": 0, "POT_DISTANCE_REW": 0, "SOUP_DISTANCE_REW": 0, "DROP_REW": -1 } EVENT_TYPES = [ # Tomato events 'tomato_pickup', 'useful_tomato_pickup', 'tomato_drop', 'useful_tomato_drop', 'potting_tomato', # Onion events 'onion_pickup', 'useful_onion_pickup', 'onion_drop', 'useful_onion_drop', 'potting_onion', # Dish events 'dish_pickup', 'useful_dish_pickup', 'dish_drop', 'useful_dish_drop', # Soup events 'soup_pickup', 'soup_delivery', 'soup_drop', # Potting events 'optimal_onion_potting', 'optimal_tomato_potting', 'viable_onion_potting', 'viable_tomato_potting', 'catastrophic_onion_potting', 'catastrophic_tomato_potting', 'useless_onion_potting', 'useless_tomato_potting' ] POTENTIAL_CONSTANTS = { 'default' : { 'max_delivery_steps' : 10, 'max_pickup_steps' : 10, 'pot_onion_steps' : 10, 'pot_tomato_steps' : 10 }, 'mdp_test_tomato' : { 'max_delivery_steps' : 4, 'max_pickup_steps' : 4, 'pot_onion_steps' : 5, 'pot_tomato_steps' : 6 } } # WARNING: Behavior with multiple sparse rewards active at once is undefined. # Some of the sparse reward settings below have side-effects that must be considered. DEFAULT_SPARSE_REWARD_OPTS = { 'deliver_soup': 20, 'add_onion_to_pot': 0, 'pickup_onion': 0, 'add_soup_to_plate': 0 } class OvercookedGridworld(object): """ An MDP grid world based off of the Overcooked game. TODO: clean the organization of this class further. """ ######################### # INSTANTIATION METHODS # ######################### def __init__(self, terrain, start_player_positions, start_bonus_orders=[], sparse_reward_opts=DEFAULT_SPARSE_REWARD_OPTS, rew_shaping_params=None, layout_name="unnamed_layout", start_all_orders=[], num_items_for_soup=3, order_bonus=2, start_state=None, **kwargs): """ terrain: a matrix of strings that encode the MDP layout layout_name: string identifier of the layout start_player_positions: tuple of positions for both players' starting positions start_bonus_orders: List of recipes dicts that are worth a bonus rew_shaping_params: reward given for completion of specific subgoals all_orders: List of all available order dicts the players can make, defaults to all possible recipes if empy list provided num_items_for_soup: Maximum number of ingredients that can be placed in a soup order_bonus: Multiplicative factor for serving a bonus recipe start_state: Default start state returned by get_standard_start_state """ self._configure_recipes(start_all_orders, num_items_for_soup, **kwargs) self.start_all_orders = [r.to_dict() for r in Recipe.ALL_RECIPES] if not start_all_orders else start_all_orders self.height = len(terrain) self.width = len(terrain[0]) self.shape = (self.width, self.height) self.terrain_mtx = terrain self.terrain_pos_dict = self._get_terrain_type_pos_dict() self.start_player_positions = start_player_positions self.num_players = len(start_player_positions) self.start_bonus_orders = start_bonus_orders self.reward_shaping_params = BASE_REW_SHAPING_PARAMS if rew_shaping_params is None else rew_shaping_params self.layout_name = layout_name self.order_bonus = order_bonus self.start_state = start_state self._opt_recipe_discount_cache = {} self._opt_recipe_cache = {} self._prev_potential_params = {} self.sparse_reward_opts = sparse_reward_opts @staticmethod def from_layout_name(layout_name, **params_to_overwrite): """ Generates a OvercookedGridworld instance from a layout file. One can overwrite the default mdp configuration using partial_mdp_config. """ params_to_overwrite = params_to_overwrite.copy() base_layout_params = read_layout_dict(layout_name) grid = base_layout_params['grid'] del base_layout_params['grid'] base_layout_params['layout_name'] = layout_name if 'start_state' in base_layout_params: base_layout_params['start_state'] = OvercookedState.from_dict(base_layout_params['start_state']) # Clean grid grid = [layout_row.strip() for layout_row in grid.split("\n")] return OvercookedGridworld.from_grid(grid, base_layout_params, params_to_overwrite) @staticmethod def from_grid(layout_grid, base_layout_params={}, params_to_overwrite={}, debug=False): """ Returns instance of OvercookedGridworld with terrain and starting positions derived from layout_grid. One can override default configuration parameters of the mdp in partial_mdp_config. """ mdp_config = copy.deepcopy(base_layout_params) layout_grid = [[c for c in row] for row in layout_grid] OvercookedGridworld._assert_valid_grid(layout_grid) if "layout_name" not in mdp_config: layout_name = "|".join(["".join(line) for line in layout_grid]) mdp_config["layout_name"] = layout_name player_positions = [None] * 9 for y, row in enumerate(layout_grid): for x, c in enumerate(row): if c in ['1', '2', '3', '4', '5', '6', '7', '8', '9']: layout_grid[y][x] = ' ' # -1 is to account for fact that player indexing starts from 1 rather than 0 assert player_positions[int(c) - 1] is None, 'Duplicate player in grid' player_positions[int(c) - 1] = (x, y) num_players = len([x for x in player_positions if x is not None]) player_positions = player_positions[:num_players] # After removing player positions from grid we have a terrain mtx mdp_config["terrain"] = layout_grid mdp_config["start_player_positions"] = player_positions for k, v in params_to_overwrite.items(): curr_val = mdp_config.get(k, None) if debug: print("Overwriting mdp layout standard config value {}:{} -> {}".format(k, curr_val, v)) mdp_config[k] = v return OvercookedGridworld(**mdp_config) def _configure_recipes(self, start_all_orders, num_items_for_soup, **kwargs): self.recipe_config = { "num_items_for_soup" : num_items_for_soup, "all_orders" : start_all_orders, **kwargs } Recipe.configure(self.recipe_config) def set_sparse_rewards(self, sparse_reward_opts): self.sparse_reward_opts = sparse_reward_opts.copy() ##################### # BASIC CLASS UTILS # ##################### def __eq__(self, other): return np.array_equal(self.terrain_mtx, other.terrain_mtx) and \ self.start_player_positions == other.start_player_positions and \ self.start_bonus_orders == other.start_bonus_orders and \ self.start_all_orders == other.start_all_orders and \ self.reward_shaping_params == other.reward_shaping_params and \ self.layout_name == other.layout_name def copy(self): return OvercookedGridworld( terrain=self.terrain_mtx.copy(), start_player_positions=self.start_player_positions, start_bonus_orders=self.start_bonus_orders, rew_shaping_params=copy.deepcopy(self.reward_shaping_params), layout_name=self.layout_name, start_all_orders=self.start_all_orders ) @property def mdp_params(self): return { "layout_name": self.layout_name, "terrain": self.terrain_mtx, "start_player_positions": self.start_player_positions, "start_bonus_orders": self.start_bonus_orders, "rew_shaping_params": copy.deepcopy(self.reward_shaping_params), "start_all_orders" : self.start_all_orders } ############## # GAME LOGIC # ############## def get_actions(self, state): """ Returns the list of lists of valid actions for 'state'. The ith element of the list is the list of valid actions that player i can take. """ self._check_valid_state(state) return [self._get_player_actions(state, i) for i in range(len(state.players))] def _get_player_actions(self, state, player_num): """All actions are allowed to all players in all states.""" return Action.ALL_ACTIONS def _check_action(self, state, joint_action): for p_action, p_legal_actions in zip(joint_action, self.get_actions(state)): if p_action not in p_legal_actions: raise ValueError('Invalid action') def get_standard_start_state(self): if self.start_state: return self.start_state start_state = OvercookedState.from_player_positions( self.start_player_positions, bonus_orders=self.start_bonus_orders, all_orders=self.start_all_orders ) return start_state def get_random_start_state_fn(self, random_start_pos=False, rnd_obj_prob_thresh=0.0): def start_state_fn(): if random_start_pos: valid_positions = self.get_valid_joint_player_positions() start_pos = valid_positions[np.random.choice(len(valid_positions))] else: start_pos = self.start_player_positions start_state = OvercookedState.from_player_positions(start_pos, bonus_orders=self.start_bonus_orders, all_orders=self.start_all_orders) if rnd_obj_prob_thresh == 0: return start_state # Arbitrary hard-coding for randomization of objects # For each pot, add a random amount of onions and tomatoes with prob rnd_obj_prob_thresh # Begin the soup cooking with probability rnd_obj_prob_thresh pots = self.get_pot_states(start_state)["empty"] for pot_loc in pots: p = np.random.rand() if p < rnd_obj_prob_thresh: n = int(np.random.randint(low=1, high=4)) m = int(np.random.randint(low=0, high=4-n)) q = np.random.rand() cooking_tick = 0 if q < rnd_obj_prob_thresh else -1 start_state.objects[pot_loc] = SoupState.get_soup(pot_loc, num_onions=n, num_tomatoes=m, cooking_tick=cooking_tick, cook_time=0) # For each player, add a random object with prob rnd_obj_prob_thresh for player in start_state.players: p = np.random.rand() if p < rnd_obj_prob_thresh: # Different objects have different probabilities obj = np.random.choice(["dish", "onion", "soup"], p=[0.2, 0.6, 0.2]) n = int(np.random.randint(low=1, high=4)) m = int(np.random.randint(low=0, high=4-n)) if obj == "soup": player.set_object( SoupState.get_soup(player.position, num_onions=n, num_tomatoes=m, finished=True, cook_time=0) ) else: player.set_object(ObjectState(obj, player.position)) return start_state return start_state_fn def is_terminal(self, state): # There is a finite horizon, handled by the environment. return False def get_state_transition(self, state, joint_action, display_phi=False, motion_planner=None): """Gets information about possible transitions for the action. Returns the next state, sparse reward and reward shaping. Assumes all actions are deterministic. NOTE: Sparse reward is given only when soups are delivered, shaped reward is given only for completion of subgoals (not soup deliveries). """ events_infos = { event : [False] * self.num_players for event
self.console_msg("Zoom: "+str(self.zoom_level)) self.display_image() def zoom_out(self): self.canvas.scale("all", 0, 0, 1-self.zoom_step, 1-self.zoom_step) self.zoom_level = self.zoom_level * (1-self.zoom_step) self.console_msg("Zoom: " + str(self.zoom_level)) self.display_image() def zoom_100(self): self.canvas.scale("all", 0, 0, 1, 1) self.zoom_level = 1 self.console_msg("Zoom: " + str(self.zoom_level)) self.display_image() def solve_image(self): global generated_image global header self.console_msg("Solving via Astrometry.Net..") try: ast = AstrometryNet() ast.api_key = self.astrometrynet_key_entry.get() ast.URL = "http://" + self.astrometrynet_entry.get() ast.API_URL = "http://" + self.astrometrynet_entry.get() + "/api" sources_df = self.results_tab_df.sort_values("flux_fit", ascending=False) width, height = generated_image.size self.wcs_header = ast.solve_from_source_list(sources_df['x_fit'], sources_df['y_fit'], width, height, solve_timeout=360) self.console_msg( "Astrometry.Net solution reference point RA: " + str(self.wcs_header["CRVAL1"]) + " Dec: " + str( self.wcs_header["CRVAL2"])) header = header + self.wcs_header self.wcs_header = WCS(header) except Exception as e: self.error_raised = True exc_type, exc_obj, exc_tb = sys.exc_info() self.console_msg(str(exc_tb.tb_lineno)+" "+str(e)) def get_comparison_stars(self): global image_width, image_height try: self.filter = self.filter_entry.get() frame_center = self.wcs_header.pixel_to_world(int(image_width / 2), (image_height / 2)) frame_center_coordinates = SkyCoord(ra=frame_center.ra, dec=frame_center.dec) frame_edge = self.wcs_header.pixel_to_world(int(image_width), (image_height / 2)) frame_edge_coordinates = SkyCoord(ra=frame_edge.ra, dec=frame_edge.dec) frame_radius = frame_edge.separation(frame_center) self.console_msg( "Inquiring VizieR, center α δ " + frame_center.to_string("hmsdms") + ", radius " + str(frame_radius)) if self.catalog_stringvar.get() == "APASS DR9": catalog = "II/336" ra_column_name = "RAJ2000" dec_column_name = "DEJ2000" if self.catalog_stringvar.get() == "URAT1": catalog = "I/329" ra_column_name = "RAJ2000" dec_column_name = "DEJ2000" if self.catalog_stringvar.get() == "USNO-B1.0": catalog = "I/284" ra_column_name = "RAJ2000" dec_column_name = "DEJ2000" if self.catalog_stringvar.get() == "VizieR Catalog": catalog = self.vizier_catalog_entry.get() ra_column_name = "RAJ2000" dec_column_name = "DEJ2000" if self.catalog_stringvar.get() == "Gaia DR2": catalog = "I/345" ra_column_name = "RA_ICRS" dec_column_name = "DE_ICRS" vizier_mag_column = self.filter + "mag" comparison_stars = Vizier(catalog=catalog, row_limit=-1).query_region(frame_center, frame_radius)[0] self.console_msg("Found " + str(len(comparison_stars)) + " objects in the field.") # print(comparison_stars) if vizier_mag_column not in comparison_stars.colnames: self.console_msg( "Catalog " + self.catalog_stringvar.get() + " does not list " + self.filter + " magnitudes.") return if True: self.console_msg("Updating photometry table with sky coordinates..") for index, row in self.results_tab_df.iterrows(): sky = self.wcs_header.pixel_to_world(row["x_fit"], row["y_fit"]) c = SkyCoord(ra=sky.ra, dec=sky.dec) self.results_tab_df.loc[index, "ra_fit"] = c.ra / u.deg self.results_tab_df.loc[index, "dec_fit"] = c.dec / u.deg self.results_tab_df.to_csv(self.image_file + ".phot", index=False) if True: self.console_msg("Matching catalogs..") matching_radius = float(self.matching_radius_entry.get()) * 0.000277778 # arcsec to degrees catalog_comparison = SkyCoord(comparison_stars[ra_column_name], comparison_stars[dec_column_name]) for index, row in self.results_tab_df.iterrows(): photometry_star_coordinates = SkyCoord(ra=row["ra_fit"] * u.deg, dec=row["dec_fit"] * u.deg) match_index, d2d_match, d3d_match = photometry_star_coordinates.match_to_catalog_sky( catalog_comparison) #print(str(photometry_star_coordinates)) #print(match_index) match_id = comparison_stars[match_index][0] # Name of the catalog match_ra = comparison_stars[match_index][ra_column_name] match_dec = comparison_stars[match_index][dec_column_name] match_mag = comparison_stars[match_index][vizier_mag_column] match_coordinates = SkyCoord(ra=match_ra * u.deg, dec=match_dec * u.deg) separation = photometry_star_coordinates.separation(match_coordinates) if separation < matching_radius * u.deg: self.results_tab_df.loc[index, "match_id"] = str(self.catalog_stringvar.get()) + " " + str( match_id) self.results_tab_df.loc[index, "match_ra"] = match_ra self.results_tab_df.loc[index, "match_dec"] = match_dec self.results_tab_df.loc[index, "match_mag"] = match_mag else: self.results_tab_df.loc[index, "match_id"] = "" self.results_tab_df.loc[index, "match_ra"] = "" self.results_tab_df.loc[index, "match_dec"] = "" self.results_tab_df.loc[index, "match_mag"] = "" if self.remove_vsx_var.get(): self.console_msg("Inquiring VizieR for VSX variables in the field..") vsx_result = Vizier(catalog="B/vsx/vsx", row_limit=-1).query_region(frame_center, frame_radius) #print(vsx_result) if len(vsx_result) > 0: vsx_stars = vsx_result[0] self.console_msg("Found " + str(len(vsx_stars)) + " VSX sources in the field. Matching..") catalog_vsx = SkyCoord(vsx_stars["RAJ2000"], vsx_stars["DEJ2000"]) for index, row in self.results_tab_df.iterrows(): photometry_star_coordinates = SkyCoord(ra=row["ra_fit"] * u.deg, dec=row["dec_fit"] * u.deg) match_index, d2d_match, d3d_match = photometry_star_coordinates.match_to_catalog_sky( catalog_vsx) match_id = vsx_stars[match_index]["Name"] # Name of the catalog match_ra = vsx_stars[match_index]["RAJ2000"] match_dec = vsx_stars[match_index]["DEJ2000"] match_coordinates = SkyCoord(ra=match_ra * u.deg, dec=match_dec * u.deg) separation = photometry_star_coordinates.separation(match_coordinates) if separation < matching_radius * u.deg: self.results_tab_df.loc[index, "vsx_id"] = str(match_id) else: self.results_tab_df.loc[index, "vsx_id"] = "" # Check 30 arcsec vicinity for nearby VSX sources: if separation < 0.00833333 * u.deg: self.results_tab_df.loc[index, "nearby_vsx_id"] = str(match_id) self.results_tab_df.loc[index, "nearby_vsx_separation"] = separation else: self.results_tab_df.loc[index, "nearby_vsx_id"] = "" self.results_tab_df.loc[index, "nearby_vsx_separation"] = "" else: self.console_msg("Found no VSX sources in the field.") self.results_tab_df.to_csv(self.image_file + ".phot", index=False) self.console_msg("Photometry table saved to " + str(self.image_file + ".phot")) self.display_image() except Exception as e: self.error_raised = True exc_type, exc_obj, exc_tb = sys.exc_info() self.console_msg(str(exc_tb.tb_lineno) + " " + str(e)) def set_entry_text(self, entry, text): entry.delete(0, tk.END) entry.insert(0, text) def update_display(self): self.display_image() self.update_PSF_canvas(self.last_clicked_x, self.last_clicked_y) def plot_photometry_menu_action(self): self.plot_photometry() self.update_display() def safe_float_convert(self, x): try: z = float(x) if np.isnan(z): return False # Nan! return True # numeric, success! except ValueError: return False # not numeric except TypeError: return False # null type def find_linear_regression_model(self): # Select stars with catalog matches with known magnitudes self.console_msg("Finding linear regression model with ensemble stars..") vsx_ids_in_photometry_table = False if "vsx_id" in self.results_tab_df: vsx_ids_in_photometry_table = True try: min_comparison_magnitude = int(self.min_ensemble_magnitude_entry.get()) max_comparison_magnitude = int(self.max_ensemble_magnitude_entry.get()) # Only stars with known magnitude from catalogs mask = self.results_tab_df['match_mag'].map(self.safe_float_convert) ensemble_stars = self.results_tab_df.loc[mask] # Only stars without VSX id if self.remove_vsx_var.get() and vsx_ids_in_photometry_table: self.console_msg("Ensemble size before removal of VSX sources: "+str(len(ensemble_stars))) mask = ensemble_stars['vsx_id'].isnull() ensemble_stars = ensemble_stars.loc[mask] # Convert magnitudes to floats ensemble_stars["inst_mag"] = ensemble_stars["inst_mag"].astype(float) ensemble_stars["match_mag"] = ensemble_stars["match_mag"].astype(float) # Filter by magnitude mask = ensemble_stars['match_mag'] < max_comparison_magnitude ensemble_stars = ensemble_stars.loc[mask] mask = ensemble_stars['match_mag'] > min_comparison_magnitude ensemble_stars = ensemble_stars.loc[mask] # Remove removed outliers mask = ensemble_stars['removed_from_ensemble']==False ensemble_stars = ensemble_stars.loc[mask] weights = None if self.weighting_stringvar.get() == "Raw Flux": ensemble_stars = ensemble_stars.sort_values(by=['flux_0'], ascending=False) ensemble_stars = ensemble_stars.head(n=int(self.ensemble_limit_entry.get())) weights = ensemble_stars["flux_0"] if self.weighting_stringvar.get() == "Instrumental Magnitude": ensemble_stars = ensemble_stars.sort_values(by=['inst_mag'], ascending=True) ensemble_stars = ensemble_stars.head(n=int(self.ensemble_limit_entry.get())) weights = 1/ensemble_stars["inst_mag"] if self.weighting_stringvar.get() == "PSF Sigma": ensemble_stars = ensemble_stars.sort_values(by=['sigma_fit'], ascending=True) ensemble_stars = ensemble_stars.head(n=int(self.ensemble_limit_entry.get())) weights = 1/ensemble_stars["sigma_fit"] self.console_msg("Using "+str(len(ensemble_stars))+" ensemble stars.") x = ensemble_stars["inst_mag"] y = ensemble_stars["match_mag"] self.a, self.b = np.polyfit(x, y, deg=1, w=weights) # Fit a 1st degree polynomial fit_fn = np.poly1d((self.a, self.b)) yhat = fit_fn(x) ybar = np.sum(y) / len(y) ssreg = np.sum((yhat - ybar) ** 2) sstot = np.sum((y - ybar) ** 2) r_squared = ssreg / sstot self.console_msg( "Linear regression fit: a = " + str(self.a) + " b = " + str(self.b) + " r^2 = " + str(r_squared)) self.linreg_plot.clear() self.linreg_plot.plot(x, y, 'ro', ms=1) self.linreg_plot.plot(x, fit_fn(x), '--k', ms=1) self.linreg_plot.text(0.1, 0.85, "n = "+str(len(ensemble_stars)), transform=self.linreg_plot.transAxes) self.plot_canvas.draw() self.ensemble_size = len(ensemble_stars) for index, row in self.results_tab_df.iterrows(): self.results_tab_df.loc[index, "differential_mag"] = round(float(row["inst_mag"]) * self.a + self.b, 3) for index, row in ensemble_stars.iterrows(): ensemble_stars.loc[index, "differential_mag"] = round(float(row["inst_mag"]) * self.a + self.b, 3) for index, row in self.results_tab_df.iterrows(): try: self.results_tab_df.loc[index, "mag_error"] = abs( float(row["differential_mag"]) - float(row["match_mag"])) except: continue for index, row in ensemble_stars.iterrows(): try: #ensemble_stars.loc[index, "mag_error"] = abs( # float(row["differential_mag"]) - float(row["match_mag"])) ensemble_stars.loc[index, "mag_error_squared"] = (float(row["differential_mag"]) - float(row["match_mag"]))**2 except: continue self.linreg_error = np.sqrt(ensemble_stars["mag_error_squared"].sum() / (len(ensemble_stars)-1)) # Standard deviation self.results_tab_df.to_csv(self.image_file + ".phot", index=False) self.console_msg("Photometry table with differential magnitudes saved to " + str(self.image_file + ".phot")) except Exception as e: self.error_raised = True exc_type, exc_obj, exc_tb = sys.exc_info() self.console_msg(str(exc_tb.tb_lineno)+" "+str(e)) def remove_fit_outlier(self): # Find not yet removed outlier within the ensemble magnitude range self.console_msg("Processing..") error = 0 outlier_index = 0 min_comparison_magnitude = int(self.min_ensemble_magnitude_entry.get()) max_comparison_magnitude = int(self.max_ensemble_magnitude_entry.get()) for index, row in self.results_tab_df.iterrows(): if abs(row["mag_error"]) > error and row["removed_from_ensemble"] == False and float(row[ "match_mag"]) > min_comparison_magnitude and float(row["match_mag"]) < max_comparison_magnitude: outlier_index = index error = abs(row["mag_error"]) self.results_tab_df.loc[outlier_index, "removed_from_ensemble"] = True self.find_linear_regression_model() self.update_display() def remove_distant_fit_outliers(self): # Removing outliers further than X arcseconds from the target self.console_msg("Processing..") max_separation = int(self.max_outliers_separation_entry.get()) target_coordinates = self.wcs_header.pixel_to_world(self.last_clicked_x, self.last_clicked_y) n = 0 for index, row in self.results_tab_df.iterrows(): comparison_coordinates = self.wcs_header.pixel_to_world(row["x_fit"], row["y_fit"]) separation = comparison_coordinates.separation(target_coordinates) if separation > max_separation * 0.000277778 * u.deg: self.results_tab_df.loc[index, "removed_from_ensemble"] = True n = n + 1 self.console_msg("Removed "+str(n)+" sources from the ensemble as distant outliers.") self.find_linear_regression_model() self.update_display() def remove_fit_outliers_until_ensemble_limit(self): while self.ensemble_size > int(self.ensemble_limit_entry.get()): self.remove_fit_outlier() def reset_fit_outliers(self): self.console_msg("Processing..") self.results_tab_df["removed_from_ensemble"] = False self.find_linear_regression_model() self.update_display() def delete_photometry_file(self): if os.path.isfile(self.image_file + ".phot"): os.remove(self.image_file + ".phot") self.console_msg("Photometry file deleted.") self.a = 0 self.b = 0 self.update_display() def update_histogram_low(self, value): self.histogram_slider_low = float(value) self.update_display() def update_histogram_high(self, value): self.histogram_slider_high = float(value) self.update_display() def save_settings_as(self): file_name = fd.asksaveasfile(defaultextension='.mpsf') try: if len(str(file_name)) > 0: self.console_msg("Saving settings as " + str(file_name.name)) settings = {} settings.update({'photometry_aperture_entry': self.photometry_aperture_entry.get()}) settings.update({'min_ensemble_magnitude_entry': self.min_ensemble_magnitude_entry.get()}) settings.update({'max_ensemble_magnitude_entry': self.max_ensemble_magnitude_entry.get()}) settings.update({'fwhm_entry': self.fwhm_entry.get()}) settings.update({'star_detection_threshold_entry': self.star_detection_threshold_entry.get()}) settings.update({'photometry_iterations_entry': self.photometry_iterations_entry.get()}) settings.update({'sharplo_entry': self.sharplo_entry.get()}) settings.update({'bkg_filter_size_entry': self.bkg_filter_size_entry.get()}) settings.update({'matching_radius_entry': self.matching_radius_entry.get()}) settings.update({'ensemble_limit_entry': self.ensemble_limit_entry.get()}) settings.update({'decimal_places_entry': self.decimal_places_entry.get()}) settings.update({'obscode_entry': self.obscode_entry.get()}) settings.update({'aavso_obscode_entry': self.aavso_obscode_entry.get()}) settings.update({'latitude_entry': self.latitude_entry.get()}) settings.update({'longitude_entry': self.longitude_entry.get()}) settings.update({'height_entry': self.height_entry.get()}) settings.update({'telescope_entry': self.telescope_entry.get()}) settings.update({'telescope_design_entry': self.accessory_entry.get()}) settings.update({'ccd_entry': self.ccd_entry.get()}) settings.update({'detector_entry': self.ccd_gain_entry.get()}) settings.update({'weighting_stringvar': self.weighting_stringvar.get()}) settings.update({'catalog_stringvar': self.catalog_stringvar.get()}) settings.update({'vizier_catalog_entry': self.vizier_catalog_entry.get()}) settings.update({'remove_vsx_var': self.remove_vsx_var.get()}) settings.update({'nearby_vsx_var': self.nearby_vsx_var.get()}) settings.update({'max_outliers_separation_entry': self.max_outliers_separation_entry.get()}) settings.update({'fitter_stringvar': self.fitter_stringvar.get()}) settings.update({'batch_psf_var': self.batch_psf_var.get()}) settings.update({'crop_fits_entry': self.crop_fits_entry.get()}) settings.update({'astrometrynet_entry': self.astrometrynet_entry.get()}) settings.update({'astrometrynet_key_entry': self.astrometrynet_key_entry.get()}) with open(str(file_name.name), 'w') as f: w = csv.DictWriter(f, settings.keys()) w.writeheader() w.writerow(settings) self.console_msg("Saved.") except Exception as e: self.error_raised = True exc_type, exc_obj, exc_tb =
1 outbound_layer = layer.outbound_nodes[0].outbound_layer return isinstance(outbound_layer, (tf.keras.layers.ReLU, tf.keras.layers.PReLU)) return activation_type in ["relu", "prelu"] class CrossLayerScaling: """ Code to apply the cross-layer-scaling technique to a model """ @staticmethod def scale_cls_set_with_conv_layers( cls_set: typing.Tuple[tf.keras.layers.Conv2D, tf.keras.layers.Conv2D]) -> np.ndarray: """ API to invoke equalize layer params (update for weights and bias is in place) :param cls_set: Consecutive Conv layers Tuple whose weights and biases need to be equalized :return: Scaling factor S_12 for each conv layer pair: numpy array """ for layer in cls_set: # NOTE: DepthwiseConv2D and Conv2DTranspose is subclass of Conv2D # The check below covers all of Conv2D, DepthwiseConv2D and Conv2DTranspose class if not isinstance(layer, tf.keras.layers.Conv2D): raise ValueError("Only Conv or Transposed Conv layers are supported for CLE") scaling_factor, prev_layer_params, curr_layer_params = CrossLayerScaling.call_mo_scale(cls_set) prev_layer, curr_layer = cls_set weight_and_bias_0 = CrossLayerScaling._unpack_equalization_params(prev_layer, prev_layer_params, unpack_bias=True) prev_layer.set_weights(weight_and_bias_0) weight_and_bias_1 = CrossLayerScaling._unpack_equalization_params(curr_layer, curr_layer_params, unpack_bias=False) curr_layer.set_weights(weight_and_bias_1) return scaling_factor @staticmethod def call_mo_scale(cls_set: typing.Tuple[tf.keras.layers.Conv2D, tf.keras.layers.Conv2D]) \ -> typing.Tuple[np.ndarray, libpymo.EqualizationParams, libpymo.EqualizationParams]: """ Invokes scale API in model optimization library :param cls_set: Consecutive Conv layers Tuple whose weights and biases need to be equalized :return: Scaling factor, prev and current layer updated parameters """ prev_layer_params = CrossLayerScaling._pack_equalization_params(cls_set[0], pack_bias=True) curr_layer_params = CrossLayerScaling._pack_equalization_params(cls_set[1], pack_bias=False) scaling_factor = libpymo.scaleLayerParams(prev_layer_params, curr_layer_params) return scaling_factor, prev_layer_params, curr_layer_params @staticmethod def scale_cls_set_with_depthwise_conv_layers( cls_set: typing.Tuple[tf.keras.layers.Conv2D, tf.keras.layers.DepthwiseConv2D, tf.keras.layers.Conv2D]) -> typing.Tuple[np.ndarray, np.ndarray]: """ API to invoke equalize layer params (update for weights and bias is in place) :param cls_set: Consecutive Conv layers whose weights and biases need to be equalized. Second Conv layer is a depth-wise conv and third conv layer is point-wise conv :return: Scaling factors S_12 and S_23 : numpy arrays """ for layer in cls_set: # NOTE: DepthwiseConv2D and Conv2DTranspose is subclass of Conv2D # The check below covers all of Conv2D, DepthwiseConv2D and Conv2DTranspose class if not isinstance(layer, tf.keras.layers.Conv2D): raise ValueError("Only Conv or Transposed Conv layers are supported for CLE") scaling_params, prev_layer_params, curr_layer_params, next_layer_params = \ CrossLayerScaling.call_mo_scale_depthwise_separable_layer(cls_set) prev_layer, curr_layer, next_layer = cls_set weight_and_bias_0 = CrossLayerScaling._unpack_equalization_params(prev_layer, prev_layer_params, unpack_bias=True) prev_layer.set_weights(weight_and_bias_0) weight_and_bias_1 = CrossLayerScaling._unpack_equalization_params(curr_layer, curr_layer_params, unpack_bias=True) curr_layer.set_weights(weight_and_bias_1) weight_and_bias_2 = CrossLayerScaling._unpack_equalization_params(next_layer, next_layer_params, unpack_bias=False) next_layer.set_weights(weight_and_bias_2) return scaling_params.scalingMatrix12, scaling_params.scalingMatrix23 @staticmethod def call_mo_scale_depthwise_separable_layer( cls_set: typing.Tuple[tf.keras.layers.Conv2D, tf.keras.layers.DepthwiseConv2D, tf.keras.layers.Conv2D]) -> typing.Tuple[libpymo.RescalingParamsVectors, libpymo.EqualizationParams, libpymo.EqualizationParams, libpymo.EqualizationParams]: """ Invokes scale API in model optimization library :param cls_set: Consecutive Conv layers whose weights and biases need to be equalized :return: Scaling factors, prev, current and next layer updated parameters """ prev_layer_params = CrossLayerScaling._pack_equalization_params(cls_set[0], pack_bias=True) curr_layer_params = CrossLayerScaling._pack_equalization_params(cls_set[1], pack_bias=True) next_layer_params = CrossLayerScaling._pack_equalization_params(cls_set[2], pack_bias=False) scaling_params = libpymo.scaleDepthWiseSeparableLayer(prev_layer_params, curr_layer_params, next_layer_params) return scaling_params, prev_layer_params, curr_layer_params, next_layer_params @staticmethod def _pack_equalization_params(layer: tf.keras.layers.Conv2D, pack_bias: bool) -> libpymo.EqualizationParams: equalization_params = libpymo.EqualizationParams() param_tensors = layer.get_weights() weight_tensor = param_tensors[0] weight_tensor = WeightTensorUtils.transpose_from_tf_to_libpymo_format(weight_tensor, layer) equalization_params.weight = weight_tensor.reshape(-1) equalization_params.weightShape = np.array(weight_tensor.shape) if pack_bias: if layer.use_bias: equalization_params.bias = param_tensors[1] else: equalization_params.isBiasNone = True return equalization_params @staticmethod def _unpack_equalization_params(layer: tf.keras.layers.Conv2D, equalization_params: libpymo.EqualizationParams, unpack_bias: bool) -> typing.List: weight_tensor = np.reshape(equalization_params.weight, equalization_params.weightShape) weight_tensor = WeightTensorUtils.transpose_from_libpymo_to_tf_format(weight_tensor, layer) if layer.use_bias: if unpack_bias: bias_tensor = np.reshape(equalization_params.bias, equalization_params.weightShape[0]) else: _, bias_tensor = layer.get_weights() param_tensors = [weight_tensor, bias_tensor] else: param_tensors = [weight_tensor] return param_tensors @staticmethod def scale_cls_sets(cls_sets: typing.List[ClsSet]) -> \ typing.List[typing.Union[np.ndarray, typing.Tuple[np.ndarray, np.ndarray]]]: """ Scale each cls set :param cls_sets: Cls sets to scale :return: List of scale factors corresponding to each scaled cls set """ scale_factor_list = [] for cls_set in cls_sets: if len(cls_set) == 3: scale_factor = CrossLayerScaling.scale_cls_set_with_depthwise_conv_layers(cls_set) else: scale_factor = CrossLayerScaling.scale_cls_set_with_conv_layers(cls_set) scale_factor_list.append(scale_factor) return scale_factor_list @staticmethod def create_cls_set_info_list(cls_sets: typing.List[ClsSet], scale_factors: typing.List[ScaleFactor], is_relu_activation_in_cls_sets: typing.List[ReluFlag]) -> typing.List[ClsSetInfo]: """ Binds information from there separate lists into one [ClsInfoSet] data structure :param cls_sets: List of CLS sets :param scale_factors: List of scale factors for each cls set :param is_relu_activation_in_cls_sets: List of ReLU flag whether there is ReLU activation in each cls set :return: List of ClsSetInfo """ assert len(cls_sets) == len(scale_factors) == len(is_relu_activation_in_cls_sets) cls_set_info_list = [] for cls_set, scale_factor, has_relu_activation in zip(cls_sets, scale_factors, is_relu_activation_in_cls_sets): # Depthwise separable convolution layer case (triplet of layers) # Should have two scale factors and ReLU flags if isinstance(scale_factor, tuple): assert len(cls_set) == 3 assert len(scale_factor) == len(has_relu_activation) == 2 prev_layer, curr_layer, next_layer = cls_set cls_pair_1 = ClsSetInfo.ClsSetLayerPairInfo(prev_layer, curr_layer, scale_factor[0], has_relu_activation[0]) cls_pair_2 = ClsSetInfo.ClsSetLayerPairInfo(curr_layer, next_layer, scale_factor[1], has_relu_activation[1]) cls_set_info = ClsSetInfo(cls_pair_1, cls_pair_2) # Standard convolution layer case (tuple of layers) # Should have one scale factor and ReLU flag else: prev_layer, curr_layer = cls_set cls_pair = ClsSetInfo.ClsSetLayerPairInfo(prev_layer, curr_layer, scale_factor, has_relu_activation) cls_set_info = ClsSetInfo(cls_pair) cls_set_info_list.append(cls_set_info) return cls_set_info_list @staticmethod def scale_model(model: tf.keras.Model, input_shapes: typing.Union[None, typing.Tuple, typing.List[typing.Tuple]]) -> typing.List[ClsSetInfo]: """ Uses cross-layer scaling to scale all applicable layers in the given model :param model: tf.keras.Model :param input_shapes: input_shapes: Input shape tuple or list of input tuple shape :return: CLS information for each CLS set """ # Find layer groups graph_search_util = GraphSearchUtils(model, input_shapes) layer_groups = graph_search_util.find_layer_groups_to_scale() # Find cls sets from the layer groups cls_sets = [] for layer_group in layer_groups: cls_set = GraphSearchUtils.convert_layer_group_to_cls_sets(layer_group) cls_sets += cls_set # Scale the CLS sets scale_factors = CrossLayerScaling.scale_cls_sets(cls_sets) # Find if there were ReLU activations between layers of each cls set is_relu_activation_in_cls_sets = graph_search_util.is_relu_activation_present_in_cls_sets(cls_sets) # Convert to a list of cls set info elements cls_set_info_list = CrossLayerScaling.create_cls_set_info_list(cls_sets, scale_factors, is_relu_activation_in_cls_sets) return cls_set_info_list class HighBiasFold: """ Code to apply the high-bias-fold technique to a model """ @staticmethod def bias_fold(cls_set_info_list: typing.List[ClsSetInfo], bn_layers: typing.Dict[tf.keras.layers.Conv2D, tf.keras.layers.BatchNormalization]): """ Folds bias values greater than 3 * sigma to next layer's bias :param cls_set_info_list: List of info elements for each cls set :param bn_layers: Key: Conv/Linear layer Value: Corresponding folded BN layer """ if not bn_layers: _logger.info('High Bias folding is not supported for models without BatchNorm Layers') return for cls_set_info in cls_set_info_list: for cls_pair_info in cls_set_info.cls_pair_info_list: if (not cls_pair_info.layer1.use_bias) or (not cls_pair_info.layer2.use_bias) or \ (cls_pair_info.layer1 not in bn_layers): continue prev_layer_params, curr_layer_params = HighBiasFold.call_mo_high_bias_fold(cls_pair_info, bn_layers) layer1 = cls_pair_info.layer1 layer1_weight_tensor, _ = layer1.get_weights() layer1_bias_tensor = np.array(prev_layer_params.bias) layer1.set_weights([layer1_weight_tensor, layer1_bias_tensor]) layer2 = cls_pair_info.layer2 layer2_weight_tensor, _ = layer2.get_weights() layer2_bias_tensor = np.array(curr_layer_params.bias) layer2.set_weights([layer2_weight_tensor, layer2_bias_tensor]) @staticmethod def call_mo_high_bias_fold(cls_pair_info: ClsSetInfo.ClsSetLayerPairInfo, bn_layers: typing.Dict[tf.keras.layers.Conv2D, tf.keras.layers.BatchNormalization]) \ -> typing.Tuple[libpymo.LayerParams, libpymo.LayerParams]: """ Invokes high bias fold MO API :param cls_pair_info: Pair of layers that were scaled using CLS and related information :param bn_layers: Key: Conv/Linear layer Value: Corresponding folded BN layer :return: Updated layer params """ bn_layer = bn_layers[cls_pair_info.layer1] prev_layer_bn_params = HighBiasFold._pack_bn_params_high_bias_fold(bn_layer, cls_pair_info.scale_factor) prev_layer_params, curr_layer_params = HighBiasFold._pack_layer_params(cls_pair_info) libpymo.updateBias(prev_layer_params, curr_layer_params, prev_layer_bn_params) return prev_layer_params, curr_layer_params @staticmethod def _pack_bn_params_high_bias_fold(bn_layer: tf.keras.layers.BatchNormalization, scaling_parameter: np.ndarray) -> libpymo.BNParamsHighBiasFold: """ Helper method to pack BatchNormalization parameter for high bias fold :param bn_layer: Target batch normalization layer :param scaling_parameter: Scaling parameters for each channel obtained from cross layer scaling :return: Packed BNParamsHighBiasFold """ bn_params = libpymo.BNParamsHighBiasFold() # Note: In BatchNormFold, we initialize gamma and beta to 1 and 0 respectively to work as Identity # So if the original value was set, use it for High Bias Fold if hasattr(bn_layer, "original_gamma") and hasattr(bn_layer, "original_beta"): gamma, beta = bn_layer.original_gamma, bn_layer.original_beta else: gamma, beta, _, _ = bn_layer.get_weights() if len(scaling_parameter) != len(gamma) or len(scaling_parameter) != len(beta): raise ValueError("High Bias absorption is not supported for networks with fold-forward BatchNorms") bn_params.gamma = np.divide(gamma, scaling_parameter) bn_params.beta = np.divide(beta, scaling_parameter) return bn_params @staticmethod def _pack_layer_params(cls_pair_info: ClsSetInfo.ClsSetLayerPairInfo) \ -> typing.Tuple[libpymo.LayerParams, libpymo.LayerParams]: """ Helper method to pack information of previous and current layer :param cls_pair_info: Pair of layers that were scaled using CLS and related information :return: Packed layer parameter tuple """ # Pack parameters for previous layer prev_layer_params = libpymo.LayerParams() prev_layer = cls_pair_info.layer1 prev_layer_params.activationIsRelu = cls_pair_info.relu_activation_between_layers _, prev_layer_bias_tensor = prev_layer.get_weights() prev_layer_params.bias = prev_layer_bias_tensor # Pack parameters for current layer curr_layer_params = libpymo.LayerParams() curr_layer = cls_pair_info.layer2 curr_layer_weight_tensor, curr_layer_bias_tensor = curr_layer.get_weights() curr_layer_weight_tensor = WeightTensorUtils.transpose_from_tf_to_libpymo_format(curr_layer_weight_tensor, curr_layer) curr_layer_params.bias = curr_layer_bias_tensor curr_layer_params.weight = curr_layer_weight_tensor.reshape(-1) curr_layer_params.weightShape = np.array(curr_layer_weight_tensor.shape) return prev_layer_params, curr_layer_params def equalize_model(model: tf.keras.Model, input_shapes: typing.Union[None, typing.Tuple, typing.List[typing.Tuple]]) -> tf.keras.Model: """ High-level API to perform Cross-Layer Equalization (CLE) on the given model :param model: tf.keras.Model :param input_shapes: Input shape tuple or list of input tuple shape :return: CLE applied tf.keras.Model """ # replace any ReLU6 layers with ReLU model_for_cle, _ = model_transform_utils.replace_relu6_with_relu(model) folded_pairs = fold_all_batch_norms(model_for_cle) equalize_bn_folded_model(model_for_cle, input_shapes, folded_pairs) return model_for_cle def equalize_bn_folded_model(model: tf.keras.Model, input_shapes: typing.Union[None, typing.Tuple, typing.List[typing.Tuple]], folded_pairs: typing.List[BatchNormFoldedPair]): """ Perform Cross-Layer Scaling (CLS) and High
from __future__ import division import numpy as np from numpy.core.numeric import NaN from scipy.signal import spectrogram from . import timbral_util import tensorflow as tf import tensorflow.keras.backend as K def timbral_depth(fname, fs=0, dev_output=False, phase_correction=False, clip_output=False, threshold_db=-60, low_frequency_limit=20, centroid_crossover_frequency=2000, ratio_crossover_frequency=500, db_decay_threshold=-40, take_first=None): """ This function calculates the apparent Depth of an audio file. This version of timbral_depth contains self loudness normalising methods and can accept arrays as an input instead of a string filename. Version 0.4 Required parameter :param fname: string or numpy array string, audio filename to be analysed, including full file path and extension. numpy array, array of audio samples, requires fs to be set to the sample rate. Optional parameters :param fs: int/float, when fname is a numpy array, this is a required to be the sample rate. Defaults to 0. :param phase_correction: bool, perform phase checking before summing to mono. Defaults to False. :param dev_output: bool, when False return the depth, when True return all extracted features. Default to False. :param threshold_db: float/int (negative), threshold, in dB, for calculating centroids. Should be negative. Defaults to -60. :param low_frequency_limit: float/int, low frequency limit at which to highpass filter the audio, in Hz. Defaults to 20. :param centroid_crossover_frequency: float/int, crossover frequency for calculating the spectral centroid, in Hz. Defaults to 2000 :param ratio_crossover_frequency: float/int, crossover frequency for calculating the ratio, in Hz. Defaults to 500. :param db_decay_threshold: float/int (negative), threshold, in dB, for estimating duration. Should be negative. Defaults to -40. :return: float, aparent depth of audio file, float. Copyright 2018 <NAME>, Institute of Sound Recording, University of Surrey, UK. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ ''' Read input ''' audio_samples, fs = timbral_util.file_read( fname, fs, phase_correction=phase_correction) # audio_samples = audio_samples[:128*128] fs = float(fs) if take_first: audio_samples = audio_samples[:take_first] ''' Filter audio ''' # highpass audio - run 3 times to get -18dB per octave - unstable filters produced when using a 6th order audio_samples = timbral_util.filter_audio_highpass( audio_samples, crossover=low_frequency_limit, fs=fs) audio_samples = timbral_util.filter_audio_highpass( audio_samples, crossover=low_frequency_limit, fs=fs) audio_samples = timbral_util.filter_audio_highpass( audio_samples, crossover=low_frequency_limit, fs=fs) # running 3 times to get -18dB per octave rolloff, greater than second order filters are unstable in python lowpass_centroid_audio_samples = timbral_util.filter_audio_lowpass( audio_samples, crossover=centroid_crossover_frequency, fs=fs) lowpass_centroid_audio_samples = timbral_util.filter_audio_lowpass( lowpass_centroid_audio_samples, crossover=centroid_crossover_frequency, fs=fs) lowpass_centroid_audio_samples = timbral_util.filter_audio_lowpass( lowpass_centroid_audio_samples, crossover=centroid_crossover_frequency, fs=fs) lowpass_ratio_audio_samples = timbral_util.filter_audio_lowpass( audio_samples, crossover=ratio_crossover_frequency, fs=fs) lowpass_ratio_audio_samples = timbral_util.filter_audio_lowpass( lowpass_ratio_audio_samples, crossover=ratio_crossover_frequency, fs=fs) lowpass_ratio_audio_samples = timbral_util.filter_audio_lowpass( lowpass_ratio_audio_samples, crossover=ratio_crossover_frequency, fs=fs) ''' Get spectrograms and normalise ''' # normalise audio lowpass_ratio_audio_samples *= (1.0 / max(abs(audio_samples))) lowpass_centroid_audio_samples *= (1.0 / max(abs(audio_samples))) audio_samples *= (1.0 / max(abs(audio_samples))) # set FFT parameters nfft = 4096 hop_size = int(3 * nfft / 4) # get spectrogram if len(audio_samples) > nfft: freq, time, spec = spectrogram(audio_samples, fs, 'hamming', nfft, hop_size, nfft, False, True, 'spectrum') lp_centroid_freq, _, lp_centroid_spec = spectrogram(lowpass_centroid_audio_samples, fs, 'hamming', nfft, hop_size, nfft, False, True, 'spectrum') _, _, lp_ratio_spec = spectrogram(lowpass_ratio_audio_samples, fs, 'hamming', nfft, hop_size, nfft, False, True, 'spectrum') else: # file is shorter than 4096, just take the fft freq, time, spec = spectrogram(audio_samples, fs, 'hamming', len(audio_samples), len(audio_samples)-1, nfft, False, True, 'spectrum') lp_centroid_freq, _, lp_centroid_spec = spectrogram(lowpass_centroid_audio_samples, fs, 'hamming', len( lowpass_centroid_audio_samples), len( lowpass_centroid_audio_samples)-1, nfft, False, True, 'spectrum') _, _, lp_ratio_spec = spectrogram(lowpass_ratio_audio_samples, fs, 'hamming', len(lowpass_ratio_audio_samples), len(lowpass_ratio_audio_samples)-1, nfft, False, True, 'spectrum') threshold = timbral_util.db2mag(threshold_db) ''' METRIC 1 - limited weighted mean normalised lower centroid ''' # define arrays for storing metrics all_normalised_lower_centroid = [] all_normalised_centroid_tpower = [] # get metrics for e # ach time segment of the spectrogram for idx in range(len(time)): # get overall spectrum of time frame current_spectrum = spec[:, idx] # calculate time window power tpower = np.sum(current_spectrum) all_normalised_centroid_tpower.append(tpower) # estimate if time segment contains audio energy or just noise if tpower > threshold: # get the spectrum lower_spectrum = lp_centroid_spec[:, idx] lower_power = np.sum(lower_spectrum) # get lower centroid lower_centroid = np.sum( lower_spectrum * lp_centroid_freq) / float(lower_power) # append to list all_normalised_lower_centroid.append(lower_centroid) else: all_normalised_lower_centroid.append(0) # calculate the weighted mean of lower centroids weighted_mean_normalised_lower_centroid = np.average(all_normalised_lower_centroid, weights=all_normalised_centroid_tpower) # limit to the centroid crossover frequency if weighted_mean_normalised_lower_centroid > centroid_crossover_frequency: limited_weighted_mean_normalised_lower_centroid = np.float64( centroid_crossover_frequency) else: limited_weighted_mean_normalised_lower_centroid = weighted_mean_normalised_lower_centroid ''' METRIC 2 - weighted mean normalised lower ratio ''' # define arrays for storing metrics all_normalised_lower_ratio = [] all_normalised_ratio_tpower = [] # get metrics for each time segment of the spectrogram for idx in range(len(time)): # get time frame of broadband spectrum current_spectrum = spec[:, idx] tpower = np.sum(current_spectrum) all_normalised_ratio_tpower.append(tpower) # estimate if time segment contains audio energy or just noise if tpower > threshold: # get the lowpass spectrum lower_spectrum = lp_ratio_spec[:, idx] # get the power of this lower_power = np.sum(lower_spectrum) # get the ratio of LF to all energy lower_ratio = lower_power / float(tpower) # append to array all_normalised_lower_ratio.append(lower_ratio) else: all_normalised_lower_ratio.append(0) # calculate weighted_mean_normalised_lower_ratio = np.average( all_normalised_lower_ratio, weights=all_normalised_ratio_tpower) ''' METRIC 3 - Approximate duration/decay-time of sample ''' all_my_duration = [] # get envelpe of signal envelope = timbral_util.sample_and_hold_envelope_calculation( audio_samples, fs) # estimate onsets onsets = timbral_util.calculate_onsets(audio_samples, envelope, fs) # get RMS envelope - better follows decays than the sample-and-hold rms_step_size = 256 rms_envelope = timbral_util.calculate_rms_enveope( audio_samples, step_size=rms_step_size) # convert decay threshold to magnitude decay_threshold = timbral_util.db2mag(db_decay_threshold) # rescale onsets to rms stepsize - casting to int time_convert = fs / float(rms_step_size) onsets = (np.array(onsets) / float(rms_step_size)).astype('int') onsets = [0] for idx, onset in enumerate(onsets): if onset == onsets[-1]: segment = rms_envelope[onset:] else: segment = rms_envelope[onset:onsets[idx + 1]] # get location of max RMS frame max_idx = np.argmax(segment) # get the segment from this max until the next onset post_max_segment = segment[max_idx:] # estimate duration based on decay or until next onset if min(post_max_segment) >= decay_threshold: my_duration = len(post_max_segment) / time_convert else: my_duration = np.where(post_max_segment < decay_threshold)[ 0][0] / time_convert # append to array all_my_duration.append(my_duration) # calculate the lof of mean duration mean_my_duration = np.log10(np.mean(all_my_duration)) ''' METRIC 4 - f0 estimation with peak picking ''' # get the overall spectrum all_spectrum = np.sum(spec, axis=1) # normalise this norm_spec = (all_spectrum - np.min(all_spectrum)) / \ (np.max(all_spectrum) - np.min(all_spectrum)) # set limit for peak picking cthr = 0.01 # detect peaks peak_idx, peak_value, peak_freq = timbral_util.detect_peaks(norm_spec, cthr=cthr, unprocessed_array=norm_spec, freq=freq) # estimate peak pitch_estimate = np.log10(min(peak_freq)) if peak_freq[0] > 0 else 0 # get outputs if dev_output: return limited_weighted_mean_normalised_lower_centroid, weighted_mean_normalised_lower_ratio, mean_my_duration, \ pitch_estimate, weighted_mean_normalised_lower_ratio * mean_my_duration, \ timbral_util.sigmoid( weighted_mean_normalised_lower_ratio) * mean_my_duration else: ''' Perform linear regression to obtain depth ''' # coefficients from linear regression coefficients = np.array([-0.0043703565847874465, 32.83743202462131, 4.750862716905235, -14.217438690256062, 3.8782339862813924, -0.8544826091735516, 66.69534393444391]) # what are the best metrics metric1 = limited_weighted_mean_normalised_lower_centroid metric2 = weighted_mean_normalised_lower_ratio metric3 = mean_my_duration metric4 = pitch_estimate metric5 = metric2 * metric3 metric6 = timbral_util.sigmoid(metric2) * metric3 # pack metrics into a matrix all_metrics = np.zeros(7) all_metrics[0] = metric1 all_metrics[1] = metric2 all_metrics[2] = metric3 all_metrics[3] = metric4 all_metrics[4] = metric5 all_metrics[5] = metric6 all_metrics[6] = 1.0 #print(metric1, metric2, metric3, metric4, metric5, metric6) # perform linear regression depth = np.sum(all_metrics * coefficients) if clip_output: depth = timbral_util.output_clip(depth) return depth @tf.function def tf_timbral_depth(audio_tensor, fs, dev_output=False, phase_correction=False, clip_output=False, threshold_db=-60, low_frequency_limit=20, centroid_crossover_frequency=2000, ratio_crossover_frequency=500, db_decay_threshold=-40): """ This function calculates the apparent Depth of an audio file. This version of timbral_depth contains self loudness normalising methods and can accept arrays as an input instead of a string filename. Version 0.4 Required parameter :param fname: string or numpy array string, audio filename to be analysed, including full file path and extension. numpy array, array of audio samples, requires fs to be set to the sample rate. Optional parameters :param fs: int/float, when fname is a numpy
# pip install selenium # pip install webdriver-manager import urllib import soup as soup import time from selenium import webdriver import pandas from webdriver_manager.chrome import ChromeDriverManager driver = webdriver.Chrome(ChromeDriverManager().install()) driver.implicitly_wait(3) # 웹 자원 로드를 위해 3초 기다려줌 from selenium.webdriver.common.keys import Keys from bs4 import BeautifulSoup import time # 이미지 크롤링 body = driver.find_element_by_tag_name('body') # 인기순/작성순 선택할 수 있는 영역 클릭 # driver.find_element_by_xpath('//paper-button[@class="dropdown-trigger style-scope yt-dropdown-menu"]').click() # 인기순 카테고리 클릭 # driver.find_element_by_xpath('//paper-listbox[@class="dropdown-content style-scope yt-dropdown-menu"]/a[1]').click() page = driver.page_source soup = BeautifulSoup(page, 'html.parser') # comments=soup.find_all('yt-formatted-string',attrs={'class':'style-scope ytd-comment-renderer'}) cmmt_box = soup.find_all(attrs={'id': 'wrap'}) # real=soup.find('video') # real=real.get('src') # print(real) # //*[@id="container"]/div/div/div[3]/div[1]/table/tbody/tr[1]/td[2]/dl/dt/a/text() # //*[@id="container"]/div/div/div[3]/div[1]/table/tbody/tr[1]/td[3] # //*[@id="container"]/div/div/div[3]/div[1]/table/tbody/tr[2]/td[2]/dl/dt/a/text() from collections import OrderedDict import json data = OrderedDict() nightlord = [] nightwalker = [] darkknight = [] demonslayer = [] demonavenger = [] dualblader = [] luminous = [] mercedes = [] mechanic = [] mihile = [] viper = [] battlemage = [] bowmaster = [] blaster = [] bishop = [] shadower = [] soulmaster = [] striker = [] marks = [] adele = [] aran = [] ark = [] arkmagefp = [] arkmagetc = [] evan = [] angelicbuster = [] wildhunter = [] windbreaker = [] shade = [] illium = [] xenon = [] zero = [] cadena = [] kaiser = [] cannonmaster = [] captain = [] kinesis = [] paladin = [] pathfinder = [] phantom = [] flamewizard = [] hoyoung = [] hero = [] url = 'https://maple.gg/job/nightlord' fp = urllib.request.urlopen(url) source = fp.read(); fp.close() imgURL = [] soup = BeautifulSoup(source, 'html.parser') soup = soup.findAll("tr", class_="bg-light-yellow") for i in soup: imgURL.append(i.find("img")["src"]) soup = BeautifulSoup(source, 'html.parser') soup = soup.findAll("tr", class_="") for i in soup: imgURL.append(i.find("img")["src"]) driver.get('https://maple.gg/job/nightlord') for j in range(1, 15): character = {} ranking = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[1]').text worldImg = imgURL[j - 1] world = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[2]/b/a').text ratio = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[3]/div/div').text character['ranking'] = ranking character['worldImg'] = worldImg character['world'] = world character['ratio'] = ratio nightlord.append(character) url = 'https://maple.gg/job/nightwalker' fp = urllib.request.urlopen(url) source = fp.read(); fp.close() imgURL = [] soup = BeautifulSoup(source, 'html.parser') soup = soup.findAll("tr", class_="bg-light-yellow") for i in soup: imgURL.append(i.find("img")["src"]) soup = BeautifulSoup(source, 'html.parser') soup = soup.findAll("tr", class_="") for i in soup: imgURL.append(i.find("img")["src"]) driver.get('https://maple.gg/job/nightwalker') for j in range(1, 15): character = {} ranking = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[1]').text worldImg = imgURL[j - 1] world = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[2]/b/a').text ratio = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[3]/div/div').text character['ranking'] = ranking character['worldImg'] = worldImg character['world'] = world character['ratio'] = ratio nightwalker.append(character) url = 'https://maple.gg/job/darkknight' fp = urllib.request.urlopen(url) source = fp.read(); fp.close() imgURL = [] soup = BeautifulSoup(source, 'html.parser') soup = soup.findAll("tr", class_="bg-light-yellow") for i in soup: imgURL.append(i.find("img")["src"]) soup = BeautifulSoup(source, 'html.parser') soup = soup.findAll("tr", class_="") for i in soup: imgURL.append(i.find("img")["src"]) driver.get('https://maple.gg/job/darkknight') for j in range(1, 15): character = {} ranking = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[1]').text worldImg = imgURL[j - 1] world = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[2]/b/a').text ratio = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[3]/div/div').text character['ranking'] = ranking character['worldImg'] = worldImg character['world'] = world character['ratio'] = ratio darkknight.append(character) url = 'https://maple.gg/job/demonslayer' fp = urllib.request.urlopen(url) source = fp.read(); fp.close() imgURL = [] soup = BeautifulSoup(source, 'html.parser') soup = soup.findAll("tr", class_="bg-light-yellow") for i in soup: imgURL.append(i.find("img")["src"]) soup = BeautifulSoup(source, 'html.parser') soup = soup.findAll("tr", class_="") for i in soup: imgURL.append(i.find("img")["src"]) driver.get('https://maple.gg/job/demonslayer') for j in range(1, 15): character = {} ranking = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[1]').text worldImg = imgURL[j - 1] world = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[2]/b/a').text ratio = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[3]/div/div').text character['ranking'] = ranking character['worldImg'] = worldImg character['world'] = world character['ratio'] = ratio demonslayer.append(character) url = 'https://maple.gg/job/demonavenger' fp = urllib.request.urlopen(url) source = fp.read(); fp.close() imgURL = [] soup = BeautifulSoup(source, 'html.parser') soup = soup.findAll("tr", class_="bg-light-yellow") for i in soup: imgURL.append(i.find("img")["src"]) soup = BeautifulSoup(source, 'html.parser') soup = soup.findAll("tr", class_="") for i in soup: imgURL.append(i.find("img")["src"]) driver.get('https://maple.gg/job/demonavenger') for j in range(1, 15): character = {} ranking = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[1]').text worldImg = imgURL[j - 1] world = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[2]/b/a').text ratio = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[3]/div/div').text character['ranking'] = ranking character['worldImg'] = worldImg character['world'] = world character['ratio'] = ratio demonavenger.append(character) url = 'https://maple.gg/job/dualblader' fp = urllib.request.urlopen(url) source = fp.read(); fp.close() imgURL = [] soup = BeautifulSoup(source, 'html.parser') soup = soup.findAll("tr", class_="bg-light-yellow") for i in soup: imgURL.append(i.find("img")["src"]) soup = BeautifulSoup(source, 'html.parser') soup = soup.findAll("tr", class_="") for i in soup: imgURL.append(i.find("img")["src"]) driver.get('https://maple.gg/job/dualblader') for j in range(1, 15): character = {} ranking = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[1]').text worldImg = imgURL[j - 1] world = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[2]/b/a').text ratio = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[3]/div/div').text character['ranking'] = ranking character['worldImg'] = worldImg character['world'] = world character['ratio'] = ratio dualblader.append(character) url = 'https://maple.gg/job/luminous' fp = urllib.request.urlopen(url) source = fp.read(); fp.close() imgURL = [] soup = BeautifulSoup(source, 'html.parser') soup = soup.findAll("tr", class_="bg-light-yellow") for i in soup: imgURL.append(i.find("img")["src"]) soup = BeautifulSoup(source, 'html.parser') soup = soup.findAll("tr", class_="") for i in soup: imgURL.append(i.find("img")["src"]) driver.get('https://maple.gg/job/luminous') for j in range(1, 15): character = {} ranking = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[1]').text worldImg = imgURL[j - 1] world = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[2]/b/a').text ratio = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[3]/div/div').text character['ranking'] = ranking character['worldImg'] = worldImg character['world'] = world character['ratio'] = ratio luminous.append(character) url = 'https://maple.gg/job/mercedes' fp = urllib.request.urlopen(url) source = fp.read(); fp.close() imgURL = [] soup = BeautifulSoup(source, 'html.parser') soup = soup.findAll("tr", class_="bg-light-yellow") for i in soup: imgURL.append(i.find("img")["src"]) soup = BeautifulSoup(source, 'html.parser') soup = soup.findAll("tr", class_="") for i in soup: imgURL.append(i.find("img")["src"]) driver.get('https://maple.gg/job/mercedes') for j in range(1, 15): character = {} ranking = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[1]').text worldImg = imgURL[j - 1] world = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[2]/b/a').text ratio = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[3]/div/div').text character['ranking'] = ranking character['worldImg'] = worldImg character['world'] = world character['ratio'] = ratio mercedes.append(character) url = 'https://maple.gg/job/mechanic' fp = urllib.request.urlopen(url) source = fp.read(); fp.close() imgURL = [] soup = BeautifulSoup(source, 'html.parser') soup = soup.findAll("tr", class_="bg-light-yellow") for i in soup: imgURL.append(i.find("img")["src"]) soup = BeautifulSoup(source, 'html.parser') soup = soup.findAll("tr", class_="") for i in soup: imgURL.append(i.find("img")["src"]) driver.get('https://maple.gg/job/mechanic') for j in range(1, 15): character = {} ranking = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[1]').text worldImg = imgURL[j - 1] world = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[2]/b/a').text ratio = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[3]/div/div').text character['ranking'] = ranking character['worldImg'] = worldImg character['world'] = world character['ratio'] = ratio mechanic.append(character) url = 'https://maple.gg/job/mihile' fp = urllib.request.urlopen(url) source = fp.read(); fp.close() imgURL = [] soup = BeautifulSoup(source, 'html.parser') soup = soup.findAll("tr", class_="bg-light-yellow") for i in soup: imgURL.append(i.find("img")["src"]) soup = BeautifulSoup(source, 'html.parser') soup = soup.findAll("tr", class_="") for i in soup: imgURL.append(i.find("img")["src"]) driver.get('https://maple.gg/job/mihile') for j in range(1, 15): character = {} ranking = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[1]').text worldImg = imgURL[j - 1] world = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[2]/b/a').text ratio = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[3]/div/div').text character['ranking'] = ranking character['worldImg'] = worldImg character['world'] = world character['ratio'] = ratio mihile.append(character) url = 'https://maple.gg/job/viper' fp = urllib.request.urlopen(url) source = fp.read(); fp.close() imgURL = [] soup = BeautifulSoup(source, 'html.parser') soup = soup.findAll("tr", class_="bg-light-yellow") for i in soup: imgURL.append(i.find("img")["src"]) soup = BeautifulSoup(source, 'html.parser') soup = soup.findAll("tr", class_="") for i in soup: imgURL.append(i.find("img")["src"]) driver.get('https://maple.gg/job/viper') for j in range(1, 15): character = {} ranking = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[1]').text worldImg = imgURL[j - 1] world = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[2]/b/a').text ratio = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[3]/div/div').text character['ranking'] = ranking character['worldImg'] = worldImg character['world'] = world character['ratio'] = ratio viper.append(character) url = 'https://maple.gg/job/battlemage' fp = urllib.request.urlopen(url) source = fp.read(); fp.close() imgURL = [] soup = BeautifulSoup(source, 'html.parser') soup = soup.findAll("tr", class_="bg-light-yellow") for i in soup: imgURL.append(i.find("img")["src"]) soup = BeautifulSoup(source, 'html.parser') soup = soup.findAll("tr", class_="") for i in soup: imgURL.append(i.find("img")["src"]) driver.get('https://maple.gg/job/battlemage') for j in range(1, 15): character = {} ranking = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[1]').text worldImg = imgURL[j - 1] world = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[2]/b/a').text ratio = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[3]/div/div').text character['ranking'] = ranking character['worldImg'] = worldImg character['world'] = world character['ratio'] = ratio battlemage.append(character) url = 'https://maple.gg/job/bowmaster' fp = urllib.request.urlopen(url) source = fp.read(); fp.close() imgURL = [] soup = BeautifulSoup(source, 'html.parser') soup = soup.findAll("tr", class_="bg-light-yellow") for i in soup: imgURL.append(i.find("img")["src"]) soup = BeautifulSoup(source, 'html.parser') soup = soup.findAll("tr", class_="") for i in soup: imgURL.append(i.find("img")["src"]) driver.get('https://maple.gg/job/bowmaster') for j in range(1, 15): character = {} ranking = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[1]').text worldImg = imgURL[j - 1] world = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[2]/b/a').text ratio = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[3]/div/div').text character['ranking'] = ranking character['worldImg'] = worldImg character['world'] = world character['ratio'] = ratio bowmaster.append(character) url = 'https://maple.gg/job/blaster' fp = urllib.request.urlopen(url) source = fp.read(); fp.close() imgURL = [] soup = BeautifulSoup(source, 'html.parser') soup = soup.findAll("tr", class_="bg-light-yellow") for i in soup: imgURL.append(i.find("img")["src"]) soup = BeautifulSoup(source, 'html.parser') soup = soup.findAll("tr", class_="") for i in soup: imgURL.append(i.find("img")["src"]) driver.get('https://maple.gg/job/blaster') for j in range(1, 15): character = {} ranking = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[1]').text worldImg = imgURL[j - 1] world = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[2]/b/a').text ratio = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' + str(j) + ']/td[3]/div/div').text character['ranking'] = ranking character['worldImg'] = worldImg character['world'] = world character['ratio'] = ratio blaster.append(character) url = 'https://maple.gg/job/bishop' fp = urllib.request.urlopen(url) source = fp.read(); fp.close() imgURL = [] soup = BeautifulSoup(source, 'html.parser') soup = soup.findAll("tr", class_="bg-light-yellow") for i in soup: imgURL.append(i.find("img")["src"]) soup = BeautifulSoup(source, 'html.parser') soup = soup.findAll("tr", class_="") for i in soup: imgURL.append(i.find("img")["src"]) driver.get('https://maple.gg/job/bishop') for j in range(1, 15): character = {} ranking = driver.find_element_by_xpath( '//*[@id="app"]/div[2]/div[4]/div[2]/section/div/table/tbody/tr[' +
<filename>tests/test_heroku.py #!/usr/bin/python # -*- coding: utf-8 -*- import os import mock import pytest import datetime import signal from dallinger.config import get_config @pytest.fixture def run_check(active_config): from dallinger.heroku.clock import run_check yield run_check @pytest.fixture def check_call(): with mock.patch("dallinger.heroku.tools.check_call") as check_call: yield check_call @pytest.fixture def check_output(): with mock.patch("dallinger.heroku.tools.check_output") as check_output: yield check_output class TestClockScheduler(object): def setup(self): """Set up the environment by moving to the demos directory.""" os.chdir("tests/experiment") config = get_config() config.ready = False from dallinger.heroku import clock self.clock = clock def teardown(self): os.chdir("../..") def test_scheduler_has_job(self): jobs = self.clock.scheduler.get_jobs() assert len(jobs) == 1 assert ( jobs[0].func_ref == "dallinger.heroku.clock:check_db_for_missing_notifications" ) def test_launch_loads_config(self): original_start = self.clock.scheduler.start data = {"launched": False} def start(): data["launched"] = True try: self.clock.scheduler.start = start self.clock.launch() assert data["launched"] assert get_config().ready finally: self.clock.scheduler.start = original_start @pytest.mark.usefixtures("experiment_dir", "active_config") class TestHerokuClockTasks(object): @pytest.fixture def recruiters(self): with mock.patch("dallinger.heroku.clock.recruiters") as mock_recruiters: yield mock_recruiters def test_check_db_for_missing_notifications_assembles_resources(self, run_check): # Can't import until after config is loaded: from dallinger.heroku.clock import check_db_for_missing_notifications with mock.patch("dallinger.heroku.clock.run_check") as check: check_db_for_missing_notifications() check.assert_called() def test_does_nothing_if_assignment_still_current( self, a, active_config, run_check, recruiters ): participants = [a.participant()] reference_time = datetime.datetime.now() run_check(participants, active_config, reference_time) recruiters.by_name.assert_not_called() def test_reports_late_participants_to_their_recruiter( self, a, active_config, run_check, recruiters ): participants = [a.participant()] five_minutes_over = 60 * active_config.get("duration") + 5 reference_time = datetime.datetime.now() + datetime.timedelta( minutes=five_minutes_over ) run_check(participants, active_config, reference_time) recruiters.by_name.assert_called_once_with(participants[0].recruiter_id) class TestHerokuUtilFunctions(object): @pytest.fixture def heroku(self): from dallinger.heroku import tools return tools def test_app_name(self, heroku): dallinger_uid = "8fbe62f5-2e33-4274-8aeb-40fc3dd621a0" assert heroku.app_name(dallinger_uid) == "dlgr-8fbe62f5" def test_auth_token(self, heroku, check_output): check_output.return_value = b"some response " assert heroku.auth_token() == u"some response" def test_log_in_ok(self, heroku, check_output): check_output.return_value = b"all good" heroku.log_in() def test_log_in_fails(self, heroku, check_output): check_output.side_effect = Exception("boom!") with pytest.raises(Exception) as excinfo: heroku.log_in() assert excinfo.match("You are not logged into Heroku.") def test_sanity_check_raises_on_invalid_config_combo(self, heroku, stub_config): assert heroku.sanity_check(stub_config) is None stub_config.set("heroku_team", u"my_team") stub_config.set("dyno_type", u"free") with pytest.raises(RuntimeError) as excinfo: heroku.sanity_check(stub_config) assert excinfo.match("dyno type not compatible") def test_sanity_check_raises_on_invalid_web_dyno_combo(self, heroku, stub_config): assert heroku.sanity_check(stub_config) is None stub_config.set("heroku_team", u"my_team") stub_config.set("dyno_type_web", u"free") with pytest.raises(RuntimeError) as excinfo: heroku.sanity_check(stub_config) assert excinfo.match("dyno type not compatible") def test_sanity_check_raises_on_invalid_worker_dyno_combo( self, heroku, stub_config ): assert heroku.sanity_check(stub_config) is None stub_config.set("heroku_team", u"my_team") stub_config.set("dyno_type_worker", u"free") with pytest.raises(RuntimeError) as excinfo: heroku.sanity_check(stub_config) assert excinfo.match("dyno type not compatible") def test_sanity_check_ok_when_optional_keys_absent(self, heroku, stub_config): del stub_config.data[0]["heroku_team"] assert heroku.sanity_check(stub_config) is None def test_request_headers(self, heroku): headers = heroku.request_headers("fake-token") assert headers["Authorization"] == "Bearer fake-token" class TestHerokuApp(object): @pytest.fixture def temp_repo(self, in_tempdir, stub_config): from dallinger.utils import GitClient stub_config.write() config = {"user.name": "Test User", "user.email": "<EMAIL>"} git = GitClient() git.init(config=config) git.add("--all") git.commit("Test Repo") @pytest.fixture def full_app(self): from dallinger.heroku.tools import HerokuApp the_app = HerokuApp(dallinger_uid="fake-uid", output=None, team=None) yield the_app the_app.destroy() @pytest.fixture def app(self): from dallinger.heroku.tools import HerokuApp with mock.patch("dallinger.heroku.tools.subprocess"): the_app = HerokuApp(dallinger_uid="fake-uid", output=None, team="fake team") yield the_app def test_name(self, app): assert app.name == u"dlgr-fake-uid" def test_url(self, app): assert app.url == u"https://dlgr-fake-uid.herokuapp.com" def test_config_url(self, app): assert ( app.config_url == u"https://api.heroku.com/apps/dlgr-fake-uid/config-vars" ) def test_dashboard_url(self, app): assert app.dashboard_url == u"https://dashboard.heroku.com/apps/dlgr-fake-uid" def test_dashboard_metrics_url(self, app): assert ( app.dashboard_metrics_url == u"https://dashboard.heroku.com/apps/dlgr-fake-uid/metrics" ) def test_bootstrap_creates_app_with_team(self, app, check_call, check_output): check_output.return_value = "<EMAIL>" app.team = "some-team" app.bootstrap() check_call.assert_has_calls( [ mock.call( [ "heroku", "apps:create", "dlgr-fake-uid", "--buildpack", "heroku/python", "--team", "some-team", ], stdout=None, ) ] ) def test_bootstrap_sets_variables(self, app, check_call, check_output): check_output.return_value = "<EMAIL>" app.team = "some-team" app.bootstrap() check_call.assert_called_with( [ "heroku", "config:set", "CREATOR=<EMAIL>", "DALLINGER_UID=fake-uid", "HOST=https://dlgr-fake-uid.herokuapp.com", "--app", "dlgr-fake-uid", ], stdout=None, ) def test_addon(self, app, check_call): app.addon("some-fake-addon") check_call.assert_called_once_with( ["heroku", "addons:create", "some-fake-addon", "--app", app.name], stdout=None, ) def test_addon_destroy(self, app, check_call): app.addon_destroy("some-fake-addon") check_call.assert_called_once_with( [ "heroku", "addons:destroy", "some-fake-addon", "--app", app.name, "--confirm", app.name, ], stdout=None, ) def test_buildpack(self, app, check_call): app.buildpack("some-fake-buildpack") check_call.assert_called_once_with( ["heroku", "buildpacks:add", "some-fake-buildpack", "--app", app.name], stdout=None, ) def test_clock_is_on_checks_psscale(self, app, check_output): app.clock_is_on check_output.assert_called_once_with(["heroku", "ps:scale", "--app", app.name]) def test_clock_is_on_returns_true_if_clock_1(self, app, check_output): check_output.return_value = b"clock=1:Standard-2X console=0:Standard-1X" assert app.clock_is_on is True def test_clock_is_on_returns_false_if_clock_0(self, app, check_output): check_output.return_value = b"clock=0:Standard-2X console=0:Standard-1X" assert app.clock_is_on is False def test_clock_is_on_returns_false_if_no_clock(self, app, check_output): check_output.return_value = b"console=0:Standard-1X web=1:Standard-2X" assert app.clock_is_on is False def test_db_uri(self, app, check_output): check_output.return_value = b"blahblahpostgres://foobar" assert app.db_uri == u"postgres://foobar" def test_db_uri_raises_if_no_match(self, app, check_output): check_output.return_value = u"└─ as DATABASE on ⬢ dlgr-da089b8f app".encode( "utf8" ) with pytest.raises(NameError) as excinfo: app.db_uri assert excinfo.match("Could not retrieve the DB URI") def test_db_url(self, app, check_output, check_call): check_output.return_value = b"some url " assert app.db_url == u"some url" check_call.assert_called_once_with( ["heroku", "pg:wait", "--app", app.name], stdout=None ) def test_backup_capture(self, app, check_call): app.backup_capture() check_call.assert_called_once_with( ["heroku", "pg:backups:capture", "--app", app.name], stdout=None, stderr=None, ) def test_backup_download(self, app, check_call): app.backup_download() check_call.assert_called_once_with( ["heroku", "pg:backups:download", "--app", app.name], stdout=None, stderr=None, ) def test_destroy(self, app, check_output): check_output.return_value = b"some response message" assert app.destroy() == "some response message" check_output.assert_called_once_with( ["heroku", "apps:destroy", "--app", app.name, "--confirm", app.name] ) def test_get(self, app, check_output): check_output.return_value = b"some value" assert app.get("some key") == u"some value" check_output.assert_called_once_with( ["heroku", "config:get", "some key", "--app", app.name] ) def test_open_logs(self, app, check_call): app.open_logs() check_call.assert_called_once_with( ["heroku", "addons:open", "papertrail", "--app", app.name], stdout=None ) def test_pg_pull(self, app, check_call): app.pg_pull() check_call.assert_called_once_with( ["heroku", "pg:pull", "DATABASE_URL", app.name, "--app", app.name], stdout=None, ) def test_pg_wait(self, app, check_call): app.pg_wait() check_call.assert_called_once_with( ["heroku", "pg:wait", "--app", app.name], stdout=None ) def test_redis_url(self, app, check_output): check_output.return_value = b"some url" assert app.redis_url == u"some url" check_output.assert_called_once_with( ["heroku", "config:get", "REDIS_URL", "--app", app.name] ) def test_restore(self, app, check_call): app.restore("some url") check_call.assert_called_once_with( [ "heroku", "pg:backups:restore", "some url", "DATABASE_URL", "--app", app.name, "--confirm", app.name, ], stdout=None, ) def test_scale_up_dyno(self, app, check_call): app.scale_up_dyno("some process", quantity=1, size="free") check_call.assert_called_once_with( ["heroku", "ps:scale", "some process=1:free", "--app", app.name], stdout=None, ) def test_scale_down_dyno(self, app, check_call): app.scale_down_dyno("some process") check_call.assert_called_once_with( ["heroku", "ps:scale", "some process=0", "--app", app.name], stdout=None ) def test_scale_down_dynos_with_clock_off(self, app, check_call, check_output): check_output.return_value = b"[string indicating no clock process]" app.scale_down_dynos() check_call.assert_has_calls( [ mock.call( ["heroku", "ps:scale", "web=0", "--app", u"dlgr-fake-uid"], stdout=None, ), mock.call( ["heroku", "ps:scale", "worker=0", "--app", u"dlgr-fake-uid"], stdout=None, ), ] ) def test_scale_down_dynos_with_clock_on(self, app, check_call, check_output): check_output.return_value = b"clock=1 <= indicates clock is on" app.scale_down_dynos() check_call.assert_has_calls( [ mock.call( ["heroku", "ps:scale", "web=0", "--app", u"dlgr-fake-uid"], stdout=None, ), mock.call( ["heroku", "ps:scale", "worker=0", "--app", u"dlgr-fake-uid"], stdout=None, ), mock.call( ["heroku", "ps:scale", "clock=0", "--app", u"dlgr-fake-uid"], stdout=None, ), ] ) def test_set(self, app, check_call): app.set("some key", "some value") check_call.assert_called_once_with( ["heroku", "config:set", "some key='some value'", "--app", app.name], stdout=None, ) def test_set_multiple(self, app, check_call): app.set_multiple(key1="some value", key2="another value") check_call.assert_called_once_with( [ "heroku", "config:set", "key1='some value'", "key2='another value'", "--app", app.name, ], stdout=None, ) def test_set_called_with_nonsensitive_key_uses_stdoutput(self, app, check_call): app.set("some_nonsensitive_key", "some value") assert check_call.call_args_list[0][-1]["stdout"] is app.out def test_set_called_with_sensitive_key_suppresses_stdoutput(self, app, check_call): app.set("aws_secret_access_key", "some value") assert len(check_call.call_args_list) == 0 @pytest.mark.usefixtures("check_heroku") def test_full_monty(self, full_app, temp_repo): app = full_app assert app.name == u"dlgr-fake-uid" assert app.url == u"https://dlgr-fake-uid.herokuapp.com" assert app.dashboard_url == u"https://dashboard.heroku.com/apps/dlgr-fake-uid" app.bootstrap() app.buildpack("https://github.com/stomita/heroku-buildpack-phantomjs") app.set("auto_recruit", True) @pytest.mark.usefixtures("bartlett_dir") @pytest.mark.slow class TestHerokuLocalWrapper(object): @pytest.fixture def config(self): from dallinger.deployment import setup_experiment cwd = os.getcwd() config = get_config() if not config.ready: config.load() (id, tmp) = setup_experiment(log=mock.Mock(), verbose=True, exp_config={}) os.chdir(tmp) yield config os.chdir(cwd) @pytest.fixture def output(self): class Output(object): def __init__(self): self.log = mock.Mock() self.error = mock.Mock() self.blather = mock.Mock() return Output() @pytest.fixture def heroku(self, config, env, output, clear_workers): from dallinger.heroku.tools import HerokuLocalWrapper wrapper = HerokuLocalWrapper(config, output, env=env) yield wrapper try: print("Calling stop() on {}".format(wrapper)) print(wrapper._record[-1]) wrapper.stop(signal.SIGKILL) except IndexError: pass def test_start(self, heroku): assert heroku.start() assert heroku.is_running def test_start_raises_without_home_dir_set(self, heroku): from dallinger.heroku.tools import HerokuStartupError env = heroku.env.copy() del env["HOME"] heroku.env = env with pytest.raises(HerokuStartupError) as excinfo: heroku.start() assert excinfo.match('"HOME" environment not set... aborting.') def test_gives_up_after_timeout(self, heroku): from dallinger.heroku.tools import HerokuTimeoutError with pytest.raises(HerokuTimeoutError): heroku.start(timeout_secs=1) def test_quits_on_gunicorn_startup_error(self, heroku): from dallinger.heroku.tools import HerokuStartupError heroku.verbose = False # more coverage heroku._stream = mock.Mock(return_value=["[DONE] Killing all processes"]) with pytest.raises(HerokuStartupError): heroku.start() def test_start_fails_if_stream_ends_without_matching_success_regex(self, heroku): from dallinger.heroku.tools import HerokuStartupError heroku._stream = mock.Mock( return_value=["apple", "orange", heroku.STREAM_SENTINEL] ) heroku.success_regex = "not going to match anything" with pytest.raises(HerokuStartupError): heroku.start() assert not heroku.is_running def test_stop(self, heroku): heroku.start() heroku.stop(signal.SIGKILL) heroku.out.log.assert_called_with("Local Heroku process terminated.") def test_stop_on_killed_process_no_error(self, heroku): heroku.start() heroku._process.terminate() heroku.stop() mock.call("Local Heroku was already terminated.") in heroku.out.log.mock_calls def test_start_when_shell_command_fails(self, heroku): heroku.shell_command = "nonsense" with pytest.raises(OSError): heroku.start() heroku.out.error.assert_called_with( "Couldn't start Heroku for local debugging." ) def test_stop_before_start_is_noop(self, heroku): heroku.stop() heroku.out.log.assert_called_with("No local Heroku process was running.") def test_start_when_already_started_is_noop(self, heroku): heroku.start() heroku.start() heroku.out.log.assert_called_with("Local Heroku is already running.") def test_monitor(self, heroku): heroku._stream = mock.Mock(return_value=["apple", "orange"]) listener = mock.Mock() heroku.monitor(listener) listener.assert_has_calls([mock.call("apple"), mock.call("orange")]) def test_monitor_stops_iterating_when_told(self, heroku): heroku._stream = mock.Mock(return_value=["apple", "orange"]) listener = mock.Mock() listener.return_value = heroku.MONITOR_STOP heroku.monitor(listener) listener.assert_has_calls([mock.call("apple")]) def test_as_context_manager(self, config, env, output, clear_workers): from dallinger.heroku.tools import HerokuLocalWrapper with HerokuLocalWrapper(config, output, env=env) as heroku: assert heroku.is_running assert not heroku.is_running class TestHerokuInfo(object): @pytest.fixture def info(self): from dallinger.heroku.tools import HerokuInfo yield HerokuInfo(team="fake team") def test_login_name(self, info, custom_app_output): login_name = info.login_name() custom_app_output.assert_has_calls([mock.call(["heroku", "auth:whoami"])]) assert login_name == "<EMAIL>" def test_all_apps(self, info, custom_app_output): app_info = info.all_apps() custom_app_output.assert_has_calls(
#!/usr/bin/env python # # Copyright 2016-present <NAME>. # # Licensed under the MIT License. # You may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://opensource.org/licenses/mit-license.html # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # ------------------------------------------------------------------------ # # Author <NAME> (<EMAIL>) # # ------------------------------------------------------------------------ from __future__ import absolute_import from __future__ import print_function import abc import copy import warnings import json import numpy as np from util.const import CONST from util.validation import ( MShape, MType, OneOfType ) from npcore.layer.layer import Layer # ------------------------------------------------------------------------ class OBJECTIVE(CONST): LABEL = 'objective' MAE_LOSS_LABEL = 'mae_loss' MSE_LOSS_LABEL = 'mse_loss' LOG_COSH_LOSS_LABEL = 'log_cosh_loss' XTANH_LOSS_LABEL = 'xtanh_loss' XSIGMOID_LOSS_LABEL = 'xsigmoid_loss' ALGEBRAIC_LOSS_LABEL = 'algebraic_loss' SIGMOID_CROSSENTROPY_LOSS = 'sigmoid_crossentropy_loss' SOFTMAX_CROSSENTROPY_LOSS = 'softmax_crossentropy_loss' ARRANGEMENT = ('2', '') # ------------------------------------------------------------------------ class Objective(Layer): _label = OBJECTIVE.LABEL _arrangement = OBJECTIVE.ARRANGEMENT """ Abtraction of a base objective layer. Manages objective loss. Arguments: size: objective size name: objective name metric: loss metric """ @MType(size=int, name=str, metric=(str,)) def __init__(self, *, size=1, name='', metric=('loss',)): self._y_t = None self._y_prime_t = None self._evaluation = { 'count': 0, 'metric': {} } self._residue = {} self._monitor = None super().__init__(shape=(1, size), name=name) self.reconfig(metric=metric) def __str__(self): return super().__str__() + '_' + OBJECTIVE.LABEL # ------------------------------------------------------------------------ @property def inputs(self): """ Get objective forward pass input tensor. Returns: tensor """ if self.has_prev: return self.prev.outputs else: return None @property def outputs(self): """ Get objective forward pass output tensor Returns: tensor """ if self._y_t is not None: return self._y_t.copy() else: return None @property def evaluation_metric(self): """ Get objective evaluation metric """ evaluation_count = self._evaluation['count'] evaluation_metric = copy.deepcopy(self._evaluation['metric']) if evaluation_count > 1: for key in evaluation_metric.keys(): evaluation_metric[key] /= evaluation_count return evaluation_metric def unassign_hooks(self): """ Unassign all callback functions """ self._monitor = None @MType(monitor=OneOfType(callable, None)) def assign_hook(self, *, monitor=None): """ Assign callback functions Arguments: monitor: callback function to do probing during forward/backward pass """ if monitor is not None: self._monitor = monitor def reset(self): """ Reset internal states. """ self._y_t = None self._y_prime_t = None self._residue = {} self._evaluation['count'] = 0 for key in self._evaluation['metric'].keys(): self._evaluation['metric'][key] = 0 @MType(shape=OneOfType((int,), None), metric=OneOfType((str,), None)) def reconfig(self, *, shape=None, metric=None): """ Reconfig objective Arguments: shape: objective layer shape metric: loss metric """ if metric is not None: if 'loss' in metric: self._evaluation['metric']['loss'] = 0 else: raise TypeError(f'Unknown metric {metric} for objective {self.name}.') if shape is not None: super().reconfig(shape=shape) self.reset() @MType(as_json=bool, beautify_json=bool) def snapshot(self, *, as_json=False, beautify_json=True): """ Return objective as a snapshot dict data Arguments: as_json: beautify_json: Returns: snapshot """ snapshot = super().snapshot(as_json=False, beautify_json=False) snapshot.update({ 'base_label': Objective.label + '_' + snapshot['base_label'], 'metric': tuple(self._evaluation['metric'].keys()) }) if as_json: if beautify_json: return json.dumps(snapshot, indent=4, sort_keys=False) else: return json.dumps(snapshot) else: return snapshot.copy() @MType(dict, np.ndarray, residue=dict) @MShape(axis=1) def forward(self, stage, a_t, *, residue={}): """ Do forward pass method. Arguments: stage: forward stage a_t: post-nonlinearity (a) tensor residue: Returns: layer """ self._y_t = a_t # a_t.copy() self._residue = residue if self._monitor is not None: report = { 'pass': 'forward', 'stage': stage, 'inputs': self.inputs, 'outputs': self.outputs, 'residue': residue } self._monitor(report) if self.has_next: warnings.warn(f'Objective {self.name} layer must be the last in connection. There should be no connection to next layer.', UserWarning) return self @MType(np.ndarray) @MShape(axis=1) def evaluate(self, y_prime_t): """ Get evaluation metric given the expected truth. Arguments: y_prime_t: expected output (y) tensor Returns: self """ self._evaluation['count'] += 1 self._y_prime_t = y_prime_t # y_prime_t.copy() evaluation_metric = self._evaluation['metric'] (ly_t, residue) = self.compute_loss(self._y_t, self._y_prime_t, residue=self._residue) metric = self.compute_evaluation_metric(self._y_t, self._y_prime_t, ly_t, evaluation_metric) self._evaluation['metric'] = metric self._residue = residue return self @MType(dict) def backward(self, stage): """ Do backward pass by passing the loss gradient tensor back to the prev link. Arguments: stage: backward stage Returns: layer """ if self._y_t is None: warnings.warn(f'Objective {self.name} cannot do backward pass. Need to run forward pass first.', UserWarning) return self elif self._y_prime_t is None: warnings.warn(f'Objective {self.name} cannot do backward pass. Need to run evaluation first.', UserWarning) return self else: hparam = stage['hparam'] batch_size = hparam['batch_size'] (eyg_t, residue) = self.compute_loss_grad(self._y_t, self._y_prime_t, residue=self._residue) eyg_t = eyg_t / batch_size if batch_size > 1 else eyg_t if self._monitor is not None: report = { 'pass': 'backward', 'stage': stage, 'error': self._ey_t, 'grad': { 'error': eyg_t }, 'evaluation': self._evaluation, 'residue': residue } self._monitor(report) if self.has_prev: return self.prev.backward(stage, eyg_t, residue=residue) else: warnings.warn(f'Objective {self.name} connection is incomplete. Missing connection to previous layer.', UserWarning) return self @abc.abstractmethod def compute_evaluation_metric(self): """ Compute the evaluation metric. """ pass @abc.abstractmethod def compute_loss(self): """ Compute the loss tensor. Not implemented """ pass @abc.abstractmethod def compute_loss_grad(self): """ Compute the loss gradient tensor for backpropagation. Not implemented """ pass # ------------------------------------------------------------------------ class MAELoss(Objective): _label = OBJECTIVE.MAE_LOSS_LABEL """ Objective using mean absolute error for loss function """ # ------------------------------------------------------------------------ @MType(shape=OneOfType((int,), None), metric=OneOfType((str,), None)) def reconfig(self, *, shape=None, metric=None): """ Reconfig objective Arguments: shape: objective layer shape metric: loss metric """ if metric is not None: if 'loss' in metric or ('accuracy' or 'acc') in metric: if 'loss' in metric: self._evaluation['metric']['loss'] = 0 if ('accuracy' or 'acc') in metric or \ ('recall' or 'rc') in metric or \ ('precision' or 'prec') in metric or \ ('f1_score' or 'f1') in metric: warnings.warn(f'Mean absolute error objective only have loss metric. Ignoring metrics {metric}', UserWarning) else: raise TypeError(f'Unknown metric {metric} for objective {self.name}.') if shape is not None: super().reconfig(shape=shape) self.reset() @MType(np.ndarray, np.ndarray, dict) def compute_loss(self, y_t, y_prime_t, *, residue={}): """ Compute the loss. Arguments: y_t: output (y) tensor y_prime_t: expected output (y) tensor residue: Returns: tuple """ ey_t = y_t - y_prime_t ly_t = np.abs(ey_t) return (ly_t, residue) @MType(np.ndarray, np.ndarray, dict) def compute_loss_grad(self, y_t, y_prime_t, *, residue={}): """ Compute the loss gradient tensor for gradient descent update. Arguments: y_t: output (y) tensor y_prime_t: expected output (y) tensor residue: Returns: tuple """ eyg_t = np.vectorize(lambda element: (element and 1) or (not element and -1))(y_t > y_prime_t) return (eyg_t, residue) @MType(np.ndarray, np.ndarray, np.ndarray, dict) def compute_evaluation_metric(self, y_t, y_prime_t, ly_t, evaluation_metric): """ Compute the evaluation metric. Arguments: y_t: output (y) tensor y_prime_t: expected output (y) tensor ly_t: loss tensor Returns: metric """ if 'loss' in evaluation_metric: evaluation_metric['loss'] += ly_t.mean() return evaluation_metric # ------------------------------------------------------------------------ class MSELoss(Objective): _label = OBJECTIVE.MSE_LOSS_LABEL """ Objective using mean square error for loss function. """ # ------------------------------------------------------------------------ @MType(shape=OneOfType((int,), None), metric=OneOfType((str,), None)) def reconfig(self, *, shape=None, metric=None): """ Reconfig objective Arguments: shape: objective layer shape metric: loss metric """ if metric is not None: if 'loss' in metric: self._evaluation['metric']['loss'] = 0 if ('accuracy' or 'acc') in metric or \ ('recall' or 'rc') in metric or \ ('precision' or 'prec') in metric or \ ('f1_score' or 'f1') in metric: warnings.warn(f'Mean square error objective only have loss metric. Ignoring metrics {metric}', UserWarning) else: raise TypeError(f'Unknown metric {metric} for objective {self.name}.') if shape is not None: super().reconfig(shape=shape) self.reset() @MType(np.ndarray, np.ndarray, dict) def compute_loss(self, y_t, y_prime_t, *, residue={}): """ Compute the loss. Arguments: y_t: output (y) tensor y_prime_t: expected output (y) tensor residue: Returns: tuple """ ey_t = y_t - y_prime_t ly_t = np.square(ey_t) return (ly_t, residue) @MType(np.ndarray, np.ndarray, dict) def compute_loss_grad(self, y_t, y_prime_t, *, residue={}): """ Compute the loss gradient tensor for gradient descent update. Arguments: y_t: output (y) tensor y_prime_t: expected output (y) tensor residue: Returns: tuple """ ey_t = y_t - y_prime_t eyg_t = 2 * ey_t return (eyg_t, residue) @MType(np.ndarray, np.ndarray, np.ndarray, dict) def compute_evaluation_metric(self, y_t, y_prime_t, ly_t, evaluation_metric): """ Compute the evaluation metric. Arguments: y_t: output (y) tensor y_prime_t: expected output (y) tensor ly_t: loss tensor Returns: metric """ if 'loss' in evaluation_metric: evaluation_metric['loss'] += ly_t.mean() return evaluation_metric # ------------------------------------------------------------------------ class LogCoshLoss(Objective): _label = OBJECTIVE.LOG_COSH_LOSS_LABEL """ Objective using log-cosh loss for loss functionself. `log(cosh(x))` is approximately equal to `(x ** 2) / 2` for small `x` and to `abs(x) - log(2)` for large `x`. This means that 'logcosh' works mostly like the l2 loss, but will not be so strongly affected by the occasional wildly incorrect prediction. """ # ------------------------------------------------------------------------ @MType(shape=OneOfType((int,), None), metric=OneOfType((str,),
import pprint import re # noqa: F401 import six class Task(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'task_type': 'str', 'status': 'str', 'input_data': 'dict(str, object)', 'reference_task_name': 'str', 'retry_count': 'int', 'seq': 'int', 'correlation_id': 'str', 'poll_count': 'int', 'task_def_name': 'str', 'scheduled_time': 'int', 'start_time': 'int', 'end_time': 'int', 'update_time': 'int', 'start_delay_in_seconds': 'int', 'retried_task_id': 'str', 'retried': 'bool', 'executed': 'bool', 'callback_from_worker': 'bool', 'response_timeout_seconds': 'int', 'workflow_instance_id': 'str', 'workflow_type': 'str', 'task_id': 'str', 'reason_for_incompletion': 'str', 'callback_after_seconds': 'int', 'worker_id': 'str', 'output_data': 'dict(str, object)', 'workflow_task': 'WorkflowTask', 'domain': 'str', 'rate_limit_per_frequency': 'int', 'rate_limit_frequency_in_seconds': 'int', 'external_input_payload_storage_path': 'str', 'external_output_payload_storage_path': 'str', 'workflow_priority': 'int', 'execution_name_space': 'str', 'isolation_group_id': 'str', 'iteration': 'int', 'sub_workflow_id': 'str', 'subworkflow_changed': 'bool', 'task_definition': 'TaskDef', 'loop_over_task': 'bool', 'queue_wait_time': 'int' } attribute_map = { 'task_type': 'taskType', 'status': 'status', 'input_data': 'inputData', 'reference_task_name': 'referenceTaskName', 'retry_count': 'retryCount', 'seq': 'seq', 'correlation_id': 'correlationId', 'poll_count': 'pollCount', 'task_def_name': 'taskDefName', 'scheduled_time': 'scheduledTime', 'start_time': 'startTime', 'end_time': 'endTime', 'update_time': 'updateTime', 'start_delay_in_seconds': 'startDelayInSeconds', 'retried_task_id': 'retriedTaskId', 'retried': 'retried', 'executed': 'executed', 'callback_from_worker': 'callbackFromWorker', 'response_timeout_seconds': 'responseTimeoutSeconds', 'workflow_instance_id': 'workflowInstanceId', 'workflow_type': 'workflowType', 'task_id': 'taskId', 'reason_for_incompletion': 'reasonForIncompletion', 'callback_after_seconds': 'callbackAfterSeconds', 'worker_id': 'workerId', 'output_data': 'outputData', 'workflow_task': 'workflowTask', 'domain': 'domain', 'rate_limit_per_frequency': 'rateLimitPerFrequency', 'rate_limit_frequency_in_seconds': 'rateLimitFrequencyInSeconds', 'external_input_payload_storage_path': 'externalInputPayloadStoragePath', 'external_output_payload_storage_path': 'externalOutputPayloadStoragePath', 'workflow_priority': 'workflowPriority', 'execution_name_space': 'executionNameSpace', 'isolation_group_id': 'isolationGroupId', 'iteration': 'iteration', 'sub_workflow_id': 'subWorkflowId', 'subworkflow_changed': 'subworkflowChanged', 'task_definition': 'taskDefinition', 'loop_over_task': 'loopOverTask', 'queue_wait_time': 'queueWaitTime' } def __init__(self, task_type=None, status=None, input_data=None, reference_task_name=None, retry_count=None, seq=None, correlation_id=None, poll_count=None, task_def_name=None, scheduled_time=None, start_time=None, end_time=None, update_time=None, start_delay_in_seconds=None, retried_task_id=None, retried=None, executed=None, callback_from_worker=None, response_timeout_seconds=None, workflow_instance_id=None, workflow_type=None, task_id=None, reason_for_incompletion=None, callback_after_seconds=None, worker_id=None, output_data=None, workflow_task=None, domain=None, rate_limit_per_frequency=None, rate_limit_frequency_in_seconds=None, external_input_payload_storage_path=None, external_output_payload_storage_path=None, workflow_priority=None, execution_name_space=None, isolation_group_id=None, iteration=None, sub_workflow_id=None, subworkflow_changed=None, task_definition=None, loop_over_task=None, queue_wait_time=None): # noqa: E501 """Task - a model defined in Swagger""" # noqa: E501 self._task_type = None self._status = None self._input_data = None self._reference_task_name = None self._retry_count = None self._seq = None self._correlation_id = None self._poll_count = None self._task_def_name = None self._scheduled_time = None self._start_time = None self._end_time = None self._update_time = None self._start_delay_in_seconds = None self._retried_task_id = None self._retried = None self._executed = None self._callback_from_worker = None self._response_timeout_seconds = None self._workflow_instance_id = None self._workflow_type = None self._task_id = None self._reason_for_incompletion = None self._callback_after_seconds = None self._worker_id = None self._output_data = None self._workflow_task = None self._domain = None self._rate_limit_per_frequency = None self._rate_limit_frequency_in_seconds = None self._external_input_payload_storage_path = None self._external_output_payload_storage_path = None self._workflow_priority = None self._execution_name_space = None self._isolation_group_id = None self._iteration = None self._sub_workflow_id = None self._subworkflow_changed = None self._task_definition = None self._loop_over_task = None self._queue_wait_time = None self.discriminator = None if task_type is not None: self.task_type = task_type if status is not None: self.status = status if input_data is not None: self.input_data = input_data if reference_task_name is not None: self.reference_task_name = reference_task_name if retry_count is not None: self.retry_count = retry_count if seq is not None: self.seq = seq if correlation_id is not None: self.correlation_id = correlation_id if poll_count is not None: self.poll_count = poll_count if task_def_name is not None: self.task_def_name = task_def_name if scheduled_time is not None: self.scheduled_time = scheduled_time if start_time is not None: self.start_time = start_time if end_time is not None: self.end_time = end_time if update_time is not None: self.update_time = update_time if start_delay_in_seconds is not None: self.start_delay_in_seconds = start_delay_in_seconds if retried_task_id is not None: self.retried_task_id = retried_task_id if retried is not None: self.retried = retried if executed is not None: self.executed = executed if callback_from_worker is not None: self.callback_from_worker = callback_from_worker if response_timeout_seconds is not None: self.response_timeout_seconds = response_timeout_seconds if workflow_instance_id is not None: self.workflow_instance_id = workflow_instance_id if workflow_type is not None: self.workflow_type = workflow_type if task_id is not None: self.task_id = task_id if reason_for_incompletion is not None: self.reason_for_incompletion = reason_for_incompletion if callback_after_seconds is not None: self.callback_after_seconds = callback_after_seconds if worker_id is not None: self.worker_id = worker_id if output_data is not None: self.output_data = output_data if workflow_task is not None: self.workflow_task = workflow_task if domain is not None: self.domain = domain if rate_limit_per_frequency is not None: self.rate_limit_per_frequency = rate_limit_per_frequency if rate_limit_frequency_in_seconds is not None: self.rate_limit_frequency_in_seconds = rate_limit_frequency_in_seconds if external_input_payload_storage_path is not None: self.external_input_payload_storage_path = external_input_payload_storage_path if external_output_payload_storage_path is not None: self.external_output_payload_storage_path = external_output_payload_storage_path if workflow_priority is not None: self.workflow_priority = workflow_priority if execution_name_space is not None: self.execution_name_space = execution_name_space if isolation_group_id is not None: self.isolation_group_id = isolation_group_id if iteration is not None: self.iteration = iteration if sub_workflow_id is not None: self.sub_workflow_id = sub_workflow_id if subworkflow_changed is not None: self.subworkflow_changed = subworkflow_changed if task_definition is not None: self.task_definition = task_definition if loop_over_task is not None: self.loop_over_task = loop_over_task if queue_wait_time is not None: self.queue_wait_time = queue_wait_time @property def task_type(self): """Gets the task_type of this Task. # noqa: E501 :return: The task_type of this Task. # noqa: E501 :rtype: str """ return self._task_type @task_type.setter def task_type(self, task_type): """Sets the task_type of this Task. :param task_type: The task_type of this Task. # noqa: E501 :type: str """ self._task_type = task_type @property def status(self): """Gets the status of this Task. # noqa: E501 :return: The status of this Task. # noqa: E501 :rtype: str """ return self._status @status.setter def status(self, status): """Sets the status of this Task. :param status: The status of this Task. # noqa: E501 :type: str """ allowed_values = ["IN_PROGRESS", "CANCELED", "FAILED", "FAILED_WITH_TERMINAL_ERROR", "COMPLETED", "COMPLETED_WITH_ERRORS", "SCHEDULED", "TIMED_OUT", "SKIPPED"] # noqa: E501 if status not in allowed_values: raise ValueError( "Invalid value for `status` ({0}), must be one of {1}" # noqa: E501 .format(status, allowed_values) ) self._status = status @property def input_data(self): """Gets the input_data of this Task. # noqa: E501 :return: The input_data of this Task. # noqa: E501 :rtype: dict(str, object) """ return self._input_data @input_data.setter def input_data(self, input_data): """Sets the input_data of this Task. :param input_data: The input_data of this Task. # noqa: E501 :type: dict(str, object) """ self._input_data = input_data @property def reference_task_name(self): """Gets the reference_task_name of this Task. # noqa: E501 :return: The reference_task_name of this Task. # noqa: E501 :rtype: str """ return self._reference_task_name @reference_task_name.setter def reference_task_name(self, reference_task_name): """Sets the reference_task_name of this Task. :param reference_task_name: The reference_task_name of this Task. # noqa: E501 :type: str """ self._reference_task_name = reference_task_name @property def retry_count(self): """Gets the retry_count of this Task. # noqa: E501 :return: The retry_count of this Task. # noqa: E501 :rtype: int """ return self._retry_count @retry_count.setter def retry_count(self, retry_count): """Sets the retry_count of this Task. :param retry_count: The retry_count of this Task. # noqa: E501 :type: int """ self._retry_count = retry_count @property def seq(self): """Gets the seq of this Task. # noqa: E501 :return: The seq of this Task. # noqa: E501 :rtype: int """ return self._seq @seq.setter def seq(self, seq): """Sets the seq of this Task. :param seq: The seq of this Task. # noqa: E501 :type: int """ self._seq = seq @property def correlation_id(self): """Gets the correlation_id of this Task. # noqa: E501 :return: The correlation_id of this Task. # noqa: E501 :rtype: str """ return self._correlation_id @correlation_id.setter def correlation_id(self, correlation_id): """Sets the correlation_id of this Task. :param correlation_id: The correlation_id of this Task. # noqa: E501 :type: str """ self._correlation_id = correlation_id @property def poll_count(self): """Gets the poll_count of this Task. # noqa: E501 :return: The poll_count of this Task. # noqa: E501 :rtype: int """ return self._poll_count @poll_count.setter def poll_count(self, poll_count): """Sets the poll_count of this Task. :param poll_count: The poll_count of this Task. # noqa: E501 :type: int """ self._poll_count = poll_count @property def task_def_name(self): """Gets the task_def_name of this Task. # noqa: E501 :return: The task_def_name of this Task. # noqa: E501 :rtype: str """ return self._task_def_name @task_def_name.setter def task_def_name(self, task_def_name): """Sets the task_def_name of this Task. :param task_def_name: The task_def_name of this Task. # noqa: E501 :type: str """ self._task_def_name = task_def_name @property def scheduled_time(self): """Gets the scheduled_time of this Task. # noqa: E501 :return: The scheduled_time of this Task. # noqa: E501 :rtype: int """ return self._scheduled_time @scheduled_time.setter def scheduled_time(self, scheduled_time): """Sets
# # Copyright 2020, Data61, CSIRO (ABN 41 687 119 230) # # SPDX-License-Identifier: BSD-2-Clause # import solver from solver import mk_smt_expr, to_smt_expr, smt_expr import check from check import restr_others, loops_to_split, ProofNode from rep_graph import (mk_graph_slice, vc_num, vc_offs, vc_upto, vc_double_range, VisitCount, vc_offset_upto) import rep_graph from syntax import (mk_and, mk_cast, mk_implies, mk_not, mk_uminus, mk_var, foldr1, boolT, word32T, word8T, builtinTs, true_term, false_term, mk_word32, mk_word8, mk_times, Expr, Type, mk_or, mk_eq, mk_memacc, mk_num, mk_minus, mk_plus, mk_less) import syntax import logic from target_objects import trace, printout import target_objects import itertools last_knowledge = [1] class NoSplit(Exception): pass def get_loop_var_analysis_at (p, n): k = ('search_loop_var_analysis', n) if k in p.cached_analysis: return p.cached_analysis[k] for hook in target_objects.hooks ('loop_var_analysis'): res = hook (p, n) if res != None: p.cached_analysis[k] = res return res var_deps = p.compute_var_dependencies () res = p.get_loop_var_analysis (var_deps, n) p.cached_analysis[k] = res return res def get_loop_vars_at (p, n): vs = [var for (var, data) in get_loop_var_analysis_at (p, n) if data == 'LoopVariable'] + [mk_word32 (0)] vs.sort () return vs default_loop_N = 3 last_proof = [None] def build_proof (p): init_hyps = check.init_point_hyps (p) proof = build_proof_rec (default_searcher, p, (), list (init_hyps)) trace ('Built proof for %s' % p.name) printout (repr (proof)) last_proof[0] = proof return proof def split_sample_set (bound): ns = (range (10) + range (10, 20, 2) + range (20, 40, 5) + range (40, 100, 10) + range (100, 1000, 50)) return [n for n in ns if n < bound] last_find_split_limit = [0] def find_split_limit (p, n, restrs, hyps, kind, bound = 51, must_find = True, hints = [], use_rep = None): tag = p.node_tags[n][0] trace ('Finding split limit: %d (%s)' % (n, tag)) last_find_split_limit[0] = (p, n, restrs, hyps, kind) if use_rep == None: rep = mk_graph_slice (p, fast = True) else: rep = use_rep check_order = hints + split_sample_set (bound) + [bound] # bounds strictly outside this range won't be considered bound_range = [0, bound] best_bound_found = [None] def check (i): if i < bound_range[0]: return True if i > bound_range[1]: return False restrs2 = restrs + ((n, VisitCount (kind, i)), ) pc = rep.get_pc ((n, restrs2)) restrs3 = restr_others (p, restrs2, 2) epc = rep.get_pc (('Err', restrs3), tag = tag) hyp = mk_implies (mk_not (epc), mk_not (pc)) res = rep.test_hyp_whyps (hyp, hyps) if res: trace ('split limit found: %d' % i) bound_range[1] = i - 1 best_bound_found[0] = i else: bound_range[0] = i + 1 return res map (check, check_order) while bound_range[0] <= bound_range[1]: split = (bound_range[0] + bound_range[1]) / 2 check (split) bound = best_bound_found[0] if bound == None: trace ('No split limit found for %d (%s).' % (n, tag)) if must_find: assert not 'split limit found' return bound def get_split_limit (p, n, restrs, hyps, kind, bound = 51, must_find = True, est_bound = 1, hints = None): k = ('SplitLimit', n, restrs, tuple (hyps), kind) if k in p.cached_analysis: (lim, prev_bound) = p.cached_analysis[k] if lim != None or bound <= prev_bound: return lim if hints == None: hints = [est_bound, est_bound + 1, est_bound + 2] res = find_split_limit (p, n, restrs, hyps, kind, hints = hints, must_find = must_find, bound = bound) p.cached_analysis[k] = (res, bound) return res def init_case_splits (p, hyps, tags = None): if 'init_case_splits' in p.cached_analysis: return p.cached_analysis['init_case_splits'] if tags == None: tags = p.pairing.tags poss = logic.possible_graph_divs (p) if len (set ([p.node_tags[n][0] for n in poss])) < 2: return None rep = rep_graph.mk_graph_slice (p) assert all ([p.nodes[n].kind == 'Cond' for n in poss]) pc_map = logic.dict_list ([(rep.get_pc ((c, ())), c) for n in poss for c in p.nodes[n].get_conts () if c not in p.loop_data]) no_loop_restrs = tuple ([(n, vc_num (0)) for n in p.loop_heads ()]) err_pc_hyps = [rep_graph.pc_false_hyp ((('Err', no_loop_restrs), tag)) for tag in p.pairing.tags] knowledge = EqSearchKnowledge (rep, hyps + err_pc_hyps, list (pc_map)) last_knowledge[0] = knowledge pc_ids = knowledge.classify_vs () id_n_map = logic.dict_list ([(i, n) for (pc, i) in pc_ids.iteritems () for n in pc_map[pc]]) tag_div_ns = [[[n for n in ns if p.node_tags[n][0] == t] for t in tags] for (i, ns) in id_n_map.iteritems ()] split_pairs = [(l_ns[0], r_ns[0]) for (l_ns, r_ns) in tag_div_ns if l_ns and r_ns] p.cached_analysis['init_case_splits'] = split_pairs return split_pairs case_split_tr = [] def init_proof_case_split (p, restrs, hyps): ps = init_case_splits (p, hyps) if ps == None: return None p.cached_analysis.setdefault ('finished_init_case_splits', []) fin = p.cached_analysis['finished_init_case_splits'] known_s = set.union (set (restrs), set (hyps)) for rs in fin: if rs <= known_s: return None rep = rep_graph.mk_graph_slice (p) no_loop_restrs = tuple ([(n, vc_num (0)) for n in p.loop_heads ()]) err_pc_hyps = [rep_graph.pc_false_hyp ((('Err', no_loop_restrs), tag)) for tag in p.pairing.tags] for (n1, n2) in ps: pc = rep.get_pc ((n1, ())) if rep.test_hyp_whyps (pc, hyps + err_pc_hyps): continue if rep.test_hyp_whyps (mk_not (pc), hyps + err_pc_hyps): continue case_split_tr.append ((n1, restrs, hyps)) return ('CaseSplit', ((n1, p.node_tags[n1][0]), [n1, n2])) fin.append (known_s) return None # TODO: deal with all the code duplication between these two searches class EqSearchKnowledge: def __init__ (self, rep, hyps, vs): self.rep = rep self.hyps = hyps self.v_ids = dict ([(v, 1) for v in vs]) self.model_trace = [] self.facts = set () self.premise = foldr1 (mk_and, map (rep.interpret_hyp, hyps)) def add_model (self, m): self.model_trace.append (m) update_v_ids_for_model2 (self, self.v_ids, m) def hyps_add_model (self, hyps): if hyps: test_expr = foldr1 (mk_and, hyps) else: # we want to learn something, either a new model, or # that all hyps are true. if there are no hyps, # learning they're all true is learning nothing. # instead force a model test_expr = false_term test_expr = mk_implies (self.premise, test_expr) m = {} (r, _) = self.rep.solv.parallel_check_hyps ([(1, test_expr)], {}, model = m) if r == 'unsat': if not hyps: trace ('WARNING: EqSearchKnowledge: premise unsat.') trace (" ... learning procedure isn't going to work.") for hyp in hyps: self.facts.add (hyp) else: assert r == 'sat', r self.add_model (m) def classify_vs (self): while not self.facts: hyps = v_id_eq_hyps (self.v_ids) if not hyps: break self.hyps_add_model (hyps) return self.v_ids def update_v_ids_for_model2 (knowledge, v_ids, m): # first update the live variables ev = lambda v: eval_model_expr (m, knowledge.rep.solv, v) groups = logic.dict_list ([((k, ev (v)), v) for (v, k) in v_ids.iteritems ()]) v_ids.clear () for (i, kt) in enumerate (sorted (groups)): for v in groups[kt]: v_ids[v] = i def v_id_eq_hyps (v_ids): groups = logic.dict_list ([(k, v) for (v, k) in v_ids.iteritems ()]) hyps = [] for vs in groups.itervalues (): for v in vs[1:]: hyps.append (mk_eq (v, vs[0])) return hyps class SearchKnowledge: def __init__ (self, rep, name, restrs, hyps, tags, cand_elts = None): self.rep = rep self.name = name self.restrs = restrs self.hyps = hyps self.tags = tags if cand_elts != None: (loop_elts, r_elts) = cand_elts else: (loop_elts, r_elts) = ([], []) (pairs, vs) = init_knowledge_pairs (rep, loop_elts, r_elts) self.pairs = pairs self.v_ids = vs self.model_trace = [] self.facts = set () self.weak_splits = set () self.premise = syntax.true_term self.live_pairs_trace = [] def add_model (self, m): self.model_trace.append (m) update_v_ids_for_model (self, self.pairs, self.v_ids, m) def hyps_add_model (self, hyps, assert_progress = True): if hyps: test_expr = foldr1 (mk_and, hyps) else: # we want to learn something, either a new model, or # that all hyps are true. if there are no hyps, # learning they're all true is learning nothing. # instead force a model test_expr = false_term test_expr = mk_implies (self.premise, test_expr) m = {} (r, _) = self.rep.solv.parallel_check_hyps ([(1, test_expr)], {}, model = m) if r == 'unsat': if not hyps: trace ('WARNING: SearchKnowledge: premise unsat.') trace (" ... learning procedure isn't going to work.") return if assert_progress: assert not (set (hyps) <= self.facts), hyps for hyp in hyps: self.facts.add (hyp) else: assert r == 'sat', r self.add_model (m) if assert_progress: assert self.model_trace[-2:-1] != [m] def eqs_add_model (self, eqs, assert_progress = True): preds = [pred for vpair in eqs for pred in expand_var_eqs (self, vpair) if pred not in self.facts] self.hyps_add_model (preds, assert_progress = assert_progress) def add_weak_split (self, eqs): preds = [pred for vpair in eqs for pred in expand_var_eqs (self, vpair)] self.weak_splits.add (tuple (sorted (preds))) def is_weak_split (self, eqs): preds = [pred for vpair in eqs for pred in expand_var_eqs (self, vpair)] return tuple (sorted (preds)) in self.weak_splits def init_knowledge_pairs (rep, loop_elts, cand_r_loop_elts): trace ('Doing search knowledge setup now.') v_is = [(i, i_offs, i_step, [(v, i, i_offs, i_step) for v in get_loop_vars_at (rep.p, i)]) for (i, i_offs, i_step) in sorted (loop_elts)] l_vtyps = set ([v[0].typ for (_, _, _, vs) in v_is for v in vs]) v_js = [(j, j_offs, j_step, [(v, j, j_offs, j_step) for v in get_loop_vars_at (rep.p, j) if v.typ in l_vtyps]) for (j, j_offs, j_step) in sorted (cand_r_loop_elts)] vs = {} for (_, _, _, var_vs) in v_is + v_js: for v in var_vs: vs[v] = (v[0].typ, True) pairs = {} for (i, i_offs, i_step, i_vs) in v_is: for (j, j_offs, j_step, j_vs) in v_js: pair = ((i, i_offs, i_step), (j, j_offs, j_step)) pairs[pair] = (i_vs, j_vs) trace ('... done.') return (pairs, vs) def update_v_ids_for_model (knowledge, pairs, vs, m): rep = knowledge.rep # first update the live variables groups = {} for v in vs: (k, const) = vs[v] groups.setdefault (k, []) groups[k].append ((v, const)) k_counter = 1 vs.clear () for k in groups: for (const, xs) in split_group (knowledge, m, groups[k]): for x in xs: vs[x] = (k_counter, const) k_counter += 1 # then figure out which pairings are still viable needed_ks = set () zero = syntax.mk_word32 (0) for (pair, data) in pairs.items (): if data[0] == 'Failed': continue (lvs, rvs) = data lv_ks = set ([vs[v][0] for v in lvs if v[0] == zero or not vs[v][1]]) rv_ks = set ([vs[v][0] for v in rvs]) miss_vars = lv_ks - rv_ks if miss_vars: lv_miss = [v[0] for v in lvs if vs[v][0] in miss_vars] pairs[pair] = ('Failed', lv_miss.pop ()) else: needed_ks.update ([vs[v][0] for v in lvs + rvs]) # then drop any vars which are no longer relevant for v
<filename>data/analysis/analyzers.py """ Data analysis functions for output files associated with : `` plots to do: - training data; vwr para cada sinal ao longo do tempo objetivo: observar performance historica do sinal com os seus parametros otimos se comparado com outros indicadores podemos inferir algumas coisas: se todos apresentarem compostamentos semelhantes em algum momento se todos apresentarem compostamentos diverntes em algum momento se algum indicador for constantemente negativo/positivo se algum indicador for constantemente volatil - test data; linha para cada sinal usado e seus vwr do treino, assim como o agregado objetivo: observaser performance do agregado e como diverge dos otimos de cada sinal usado no treino. se comparado com outros indicadores podemos inferir algumas coisas: se agregado for constantemente negativo/positivo se agregado for constantemente volatil se o agregado diverge muito entre o maximo e minimo dos sinais no treino tabelas to do: - settings; parametros usados para signals - date_train | date_test | col_signal1 | col_signal2 | col_signalMAX | col_signalMIN |col_signalAVG | vwr_train / days_train | vwr_test / days_train (para cada sinal) comparar retornos no treino e test - date_train | col_signal1 | col_signal2 | ... | vwr comparar os retorno/pesos de cada indicador ao longo do tempo - date_train | col_signal | col_param1 | col_param2 | ... | vwr (for each signal) comparar oscilação dos parametros otimos ao longo do tempo, util para definir ranges dos parametros - obs: * seria interessante rodar o otimizador para os dados de test e ver como eles se comportaria nesse periodo? * seria interessante usar uma janela deslizante , para gerar mais dados de treino/teste ? """ import sys import json import pandas import numpy as np import datetime as dt import matplotlib.pyplot as plt import seaborn as sns import warnings from time import process_time from pandas.core.common import SettingWithCopyWarning warnings.simplefilter(action="ignore", category=SettingWithCopyWarning) sns.set_theme(style="whitegrid") def filename_key_opt_type(settings, **kwargs): opt_type_dict = { "train": {"key": "output_train_key", "path": "path_output_train"}, "test": {"key": "output_test_key", "path": "path_output_test"} } opt_type = kwargs.get("opt_type") days_train = settings["opt_analyzer"]["daterange_opt"] range_train = settings["opt_analyzer"]["daterange_opt_train"] filename = settings["opt_analyzer"][opt_type_dict[opt_type]["path"]].format(days_train, range_train) output_key = settings["opt_analyzer"][opt_type_dict[opt_type]["key"]] return filename, output_key def df_extract_values(settings): opt_type = "test" filename, output_key = filename_key_opt_type(settings, opt_type=opt_type) with open(filename, "r") as file: data = json.load(file) df_data = pandas.DataFrame(data) file.close() # split output_type: [test, train] cols_ids = ["train", "test"] df_data = df_data.melt(id_vars=cols_ids, var_name="output_type") # split signals cols_ids = ["train", "test", "output_type"] df_data = df_split_param(df_data, cols_ids, var_name="signal") # split params cols_ids = ["train", "test", "output_type", "signal"] df_data = df_split_param(df_data, cols_ids, var_name="params") # # fix time_stop/start, list df_data = df_time_fix(df_data) # split analyzer_opt df_data = df_split_params_opt(df_data) # finals adjustments df_data = df_data.reset_index(drop=True) df_data["signal"] = [x.split("Signal")[0] if len(x) > 7 else x for x in df_data["signal"]] df_data["output_type"] = [x.split("_")[1] for x in df_data["output_type"]] df_data = df_data.rename(columns={"output_type": "type"}) return df_data def df_split_params_opt(df): filter_params = df["params"] == "analyzer_opt" df_analyzers = df[filter_params] df_params = df[~filter_params] # update params col cols_ids = ["train", "test", "output_type", "signal", "value"] df_params = df_params.melt(id_vars=cols_ids, var_name="var_type", value_name="variable") # update analyzers col df_analyzers = df_analyzers.rename(columns={"params": "var_type"}) cols_ids = ["train", "test", "output_type", "signal", "var_type"] df_analyzers = df_split_param(df_analyzers, cols_ids, var_name="variable") # update analyzers col from Signals filter_signals = df_analyzers["signal"].isin(["Signals","BuyHold"]) # filter_signals = df_analyzers["signal"] == "Signals" df_analyzers_signals = df_analyzers[filter_signals] df_analyzers = df_analyzers[~filter_signals] # update analyzers col from Signals with dict on values cols_ids = ["train", "test", "output_type", "signal", "var_type", "variable"] df_analyzers_signals = df_split_param(df_analyzers_signals, cols_ids, var_name="var") df_analyzers_sig_new = df_split_params_opt_Signals(df_analyzers_signals) # concat all sub tables, split before df_analyzers_sig_new = df_analyzers_sig_new.rename(columns={"var": "variable"}) df_analyzers = pandas.concat([df_analyzers, df_analyzers_sig_new]) df_opt = pandas.concat([df_params, df_analyzers]) return df_opt def df_split_params_opt_Signals(df_analyzers_signals): output_dict = { "VWR": ["vwr"], "SQN": ["sqn"], "TradeAnalyzer": ["pnl", "net"] # "TradeAnalyzer": {"pnl": "net"} } df_analyzers_sig_new = pandas.DataFrame() for opt in output_dict.keys(): filter_opt = df_analyzers_signals["variable"] == opt df_analyzers_sample = df_analyzers_signals[filter_opt].drop(columns="variable") filter_var = df_analyzers_sample["var"].isin(output_dict[opt]) df_analyzers_sample = df_analyzers_sample[filter_var] if opt == "TradeAnalyzer": # filter_var = df_analyzers_sample["var"] == list(output_dict[opt].keys())[0] filter_var = df_analyzers_sample["var"] == output_dict[opt][0] cols_ids = ["train", "test", "output_type", "signal", "var_type", "var"] df_analyzers_sample = df_split_param(df_analyzers_sample[filter_var], cols_ids, var_name="var1") # filter_var = df_analyzers_sample["var1"] == list(output_dict[opt].values())[0] filter_var = df_analyzers_sample["var1"] == output_dict[opt][1] cols_ids = ["train", "test", "output_type", "signal", "var_type", "var", "var1"] df_analyzers_sample = df_split_param(df_analyzers_sample[filter_var], cols_ids, var_name="var2") filter_var = df_analyzers_sample["var2"] == "total" df_analyzers_sample = df_analyzers_sample[filter_var] cols_drop = ["var", "var1"] df_analyzers_sample = df_analyzers_sample.drop(columns=cols_drop) df_analyzers_sample = df_analyzers_sample.rename(columns={"var2": "var"}) df_analyzers_sig_new = pandas.concat([df_analyzers_sig_new, df_analyzers_sample]) return df_analyzers_sig_new def df_split_param(df, cols_ids, var_name): df_values = df["value"].apply(pandas.Series) df_melt = df.drop(["value"], axis=1) df_split = pandas.concat([df_melt, df_values], axis=1) df_split = df_split.melt(id_vars=cols_ids, var_name=var_name) df_split = df_split.dropna() return df_split def df_time_fix(df): # fix time_stop/start, list varaibles_time = ["time_start", "time_stop"] filter_var = df["params"].isin(varaibles_time) df.loc[filter_var, "value"] = df.loc[filter_var, "value"].apply( lambda x: x[0] + x[1] / 60) return df # def df_analyzers(settings, train_test="train"): # opt_type_dict = { # "train": {"key": "output_train_key", "path": "path_output_train"}, # "test": {"key": "output_test_key", "path": "path_output_test"} # } # opt_type = train_test # output_key = settings["opt_analyzer"][opt_type_dict[opt_type]["key"]] # output_key_train = settings["opt_analyzer"][opt_type_dict["train"]["key"]] # # days_train = settings["opt_analyzer"]["daterange_opt"] # range_train = settings["opt_analyzer"]["daterange_opt_train"] # filename = settings["opt_analyzer"][opt_type_dict[opt_type]["path"]].format(days_train, range_train) # # with open(filename, "r") as file: # data = json.load(file) # df_data = pandas.DataFrame() # for idx, row in enumerate(data): # df_row = df_row_dates(row) # df_row = df_row_output_key(df_row, row, output_key=output_key_train) # if train_test == "test": # df_row = df_row_output_key(df_row, row, output_key=output_key) # df_data = pandas.concat([df_data, df_row]) # # df_data = df_data.reset_index(drop=True) # return df_data # # # def df_analyzers_train_test(settings, train_test="train"): # # settings_train_test = { # # "train": "path_opt_parms", # # "test": "path_output" # # } # # filename = settings["opt_analyzer"][settings_train_test[train_test]] # # with open(filename, "r") as file: # # data = json.load(file) # # df_data = pandas.DataFrame() # # for idx, row in enumerate(data): # # df_data = df_row_signal(df_data, row, "signal") # # if train_test == "test": # # df_data = df_row_analyzers(df_data, row, "analyzers") # # return df_data # # # def df_row_signal(df_data, row_dict, output_key='output_train'): # # # def df_row_signal(df_data, row_dict, output_key="signal"): # # dt_train = {"dt_train": row_dict.pop("train")} # # dt_test = {"dt_test": row_dict.pop("test")} # # # # df_row = pandas.DataFrame() # # df_row.insert(0, "dt_train", tuple(dt_train.values())) # # df_row.insert(1, "dt_test", tuple(dt_test.values())) # # # # row = row_dict[output_key] # # for signal, params in row.items(): # # params["time_start"] = tuple(params.get("time_start", [9, 0])) # # params["time_stop"] = tuple(params.get("time_stop", [17, 0])) # # df_row = df_concat_row(df_row, params, signal, "params") # # # # data_signal_analyzer = params.pop("analyzer_opt") # # df_row = df_concat_row(df_row, data_signal_analyzer, signal, "analyzers") # # # # df_data = pandas.concat([df_data, df_row]) # # df_data = df_data.reset_index(drop=True) # # return df_data # # # # def df_row_analyzers(df_data, row_dict, output_key="analyzers"): # # row = row_dict[output_key] # # output_col = ".".join(["Output", output_key]) # # df_row = df_data.tail(1).copy() # # df_row = df_row.drop(output_col, errors='ignore', axis=1) # # df_row = df_row.reset_index(drop=True) # # df_data = df_data.drop(df_data.tail(1).index) # # # # df_row_output = df_concat_row(df_row, row, "Output", output_key) # # df_data = pandas.concat([df_data, df_row_output]) # # df_data = df_data.reset_index(drop=True) # # return df_data # # # def df_plot_train_signals_objetive(settings, df, f_objetive=None): # # if f_objetive is None: # # f_objetive = settings["opt_analyzer"]["analyzer_opt"] # # cols_analyzer = [col for col in df.columns if "analyzers" in col] # # df_analyzers = df[cols_analyzer] # # # # output_dict = { # # "vwr": {"VWR": "vwr"}, # # "sqn": {"SQN": "sqn"}, # # "tradeanalyzer": {"TradeAnalyzer": {"pnl": "net"}} # # } # # # # for col in df_analyzers: # # if "Output" in col: # # f_obj1 = list(output_dict[f_objetive].keys())[0] # # f_obj1_1 = list(output_dict[f_objetive].values())[0] # # f_obj_values = [row[f_obj1][f_obj1_1] for row in df_analyzers[col]] # # else: # # f_obj_values = [row[f_objetive] for row in df_analyzers[col]] # # df_analyzers[col] = f_obj_values # # return df_analyzers # # def df_concat_row(df_row, params_dict, name, subname): # params_name = ".".join([name, subname]) # params = {params_name: params_dict} # params_series = pandas.Series(tuple(params.values()), name=params_name) # df_row = pandas.concat([df_row, params_series], axis=1) # return df_row # # # def df_row_dates(row_dict): # dt_train = {"dt_train": row_dict.pop("train")} # dt_test = {"dt_test": row_dict.pop("test")} # df_row = pandas.DataFrame() # df_row.insert(0, "dt_train", tuple(dt_train.values())) # df_row.insert(1, "dt_test", tuple(dt_test.values())) # return df_row # # # def df_row_params_time(params): # # def df_row_params_time(df_row, params, signal): # if "time_start" in params.keys(): # params["time_start"] = tuple(params.get("time_start", [9, 0])) # if "time_stop" in params.keys(): # params["time_stop"] = tuple(params.get("time_stop", [17, 0])) # # df_row = df_concat_row(df_row, params, signal, "params") # return params # # # def df_row_output_key(df_row, row_dict, output_key='output_train'): # for signal, params in row_dict[output_key].items(): # params = df_row_params_time(params) # data_signal_analyzer = params.pop("analyzer_opt") # output_signal = ".".join([output_key, signal]) # df_row = df_concat_row(df_row, params, output_signal, "params") # df_row = df_concat_row(df_row, data_signal_analyzer, output_signal, "analyzers") # return df_row def table_plot_signal_opt(df): signals = set(df["signal"]) signals.discard("Signals") for signal in signals: filter_signal = df["signal"] == signal filter_type = df["var_type"] == "params" df_signal = df[filter_signal & filter_type] varaibles_time = ["time_start", "time_stop"] filter_var = df_signal["variable"].isin(varaibles_time) df_signal = df_signal[~filter_var] ax = sns.boxplot(data=df_signal, x="output_type", y="value", hue="variable") # ax = sns.swarmplot(data=df_signal, x="output_type", y="value", hue="variable") ax.set_title(signal) plt.show() return def plot_signal(df): plt.figure() # df.plot.hist(alpha=0.5) # df.plot.hist(stacked=True) df.plot() plt.show() return def plot_boxplot(df): plt.figure() # df.plot.hist(alpha=0.5) # df.plot.hist(stacked=True) df.boxplot() plt.show() return def plot_cumsum(df): plt.figure() df.cumsum().plot() plt.show() return # def table_params(df, f_objetive=None): # cols_dates = ["dt_train", "dt_test"] # df_melt = df.melt(id_vars=cols_dates, var_name="signal") # # df_melt = df_melt.rename(columns={"variable": "signal"}) # cols_dates.append("signal") # # df_values = df_melt["value"].apply(pandas.Series) # df_melt =
<filename>RestPy/ixnetwork_restpy/testplatform/sessions/ixnetwork/traffic/traffic.py # Copyright 1997 - 2018 by IXIA Keysight # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Files class Traffic(Base): """The Traffic class encapsulates a required traffic node in the ixnetwork hierarchy. An instance of the class can be obtained by accessing the Traffic property from a parent instance. The internal properties list will contain one and only one set of properties which is populated when the property is accessed. """ _SDM_NAME = 'traffic' def __init__(self, parent): super(Traffic, self).__init__(parent) @property def DynamicFrameSize(self): """An instance of the DynamicFrameSize class. Returns: obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.traffic.dynamicframesize.dynamicframesize.DynamicFrameSize) Raises: NotFoundError: The requested resource does not exist on the server ServerError: The server has encountered an uncategorized error condition """ from ixnetwork_restpy.testplatform.sessions.ixnetwork.traffic.dynamicframesize.dynamicframesize import DynamicFrameSize return DynamicFrameSize(self) @property def DynamicRate(self): """An instance of the DynamicRate class. Returns: obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.traffic.dynamicrate.dynamicrate.DynamicRate) Raises: NotFoundError: The requested resource does not exist on the server ServerError: The server has encountered an uncategorized error condition """ from ixnetwork_restpy.testplatform.sessions.ixnetwork.traffic.dynamicrate.dynamicrate import DynamicRate return DynamicRate(self) @property def EgressOnlyTracking(self): """An instance of the EgressOnlyTracking class. Returns: obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.traffic.egressonlytracking.egressonlytracking.EgressOnlyTracking) Raises: NotFoundError: The requested resource does not exist on the server ServerError: The server has encountered an uncategorized error condition """ from ixnetwork_restpy.testplatform.sessions.ixnetwork.traffic.egressonlytracking.egressonlytracking import EgressOnlyTracking return EgressOnlyTracking(self) @property def ProtocolTemplate(self): """An instance of the ProtocolTemplate class. Returns: obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.traffic.protocoltemplate.protocoltemplate.ProtocolTemplate) Raises: NotFoundError: The requested resource does not exist on the server ServerError: The server has encountered an uncategorized error condition """ from ixnetwork_restpy.testplatform.sessions.ixnetwork.traffic.protocoltemplate.protocoltemplate import ProtocolTemplate return ProtocolTemplate(self) @property def Statistics(self): """An instance of the Statistics class. Returns: obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.traffic.statistics.statistics.Statistics) Raises: NotFoundError: The requested resource does not exist on the server ServerError: The server has encountered an uncategorized error condition """ from ixnetwork_restpy.testplatform.sessions.ixnetwork.traffic.statistics.statistics import Statistics return Statistics(self)._select() @property def TrafficGroup(self): """An instance of the TrafficGroup class. Returns: obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.traffic.trafficgroup.trafficgroup.TrafficGroup) Raises: NotFoundError: The requested resource does not exist on the server ServerError: The server has encountered an uncategorized error condition """ from ixnetwork_restpy.testplatform.sessions.ixnetwork.traffic.trafficgroup.trafficgroup import TrafficGroup return TrafficGroup(self) @property def TrafficItem(self): """An instance of the TrafficItem class. Returns: obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.traffic.trafficitem.trafficitem.TrafficItem) Raises: NotFoundError: The requested resource does not exist on the server ServerError: The server has encountered an uncategorized error condition """ from ixnetwork_restpy.testplatform.sessions.ixnetwork.traffic.trafficitem.trafficitem import TrafficItem return TrafficItem(self) @property def AutoCorrectL4HeaderChecksums(self): """This is used for Multis and Xdensity as checksum is not calculated correctly when change on the fly operations are performed. When this option is enabled IxOS uses 2 bytes before CRC, that way ensuring the checksum is correct when change on the fly operations are performed. Returns: bool """ return self._get_attribute('autoCorrectL4HeaderChecksums') @AutoCorrectL4HeaderChecksums.setter def AutoCorrectL4HeaderChecksums(self, value): self._set_attribute('autoCorrectL4HeaderChecksums', value) @property def CycleOffsetForScheduledStart(self): """ Returns: number """ return self._get_attribute('cycleOffsetForScheduledStart') @CycleOffsetForScheduledStart.setter def CycleOffsetForScheduledStart(self, value): self._set_attribute('cycleOffsetForScheduledStart', value) @property def CycleOffsetUnitForScheduledStart(self): """ Returns: str(microseconds|milliseconds|nanoseconds|seconds) """ return self._get_attribute('cycleOffsetUnitForScheduledStart') @CycleOffsetUnitForScheduledStart.setter def CycleOffsetUnitForScheduledStart(self, value): self._set_attribute('cycleOffsetUnitForScheduledStart', value) @property def CycleTimeForScheduledStart(self): """ Returns: number """ return self._get_attribute('cycleTimeForScheduledStart') @CycleTimeForScheduledStart.setter def CycleTimeForScheduledStart(self, value): self._set_attribute('cycleTimeForScheduledStart', value) @property def CycleTimeUnitForScheduledStart(self): """ Returns: str(microseconds|milliseconds|nanoseconds|seconds) """ return self._get_attribute('cycleTimeUnitForScheduledStart') @CycleTimeUnitForScheduledStart.setter def CycleTimeUnitForScheduledStart(self, value): self._set_attribute('cycleTimeUnitForScheduledStart', value) @property def DataPlaneJitterWindow(self): """Indicates the number of packets received during a time interval. This is used forcalculating the rate on the recieve side. Returns: str(0|10485760|1310720|167772160|20971520|2621440|335544320|41943040|5242880|671088640|83886080) """ return self._get_attribute('dataPlaneJitterWindow') @DataPlaneJitterWindow.setter def DataPlaneJitterWindow(self, value): self._set_attribute('dataPlaneJitterWindow', value) @property def DelayTimeForScheduledStart(self): """Delay Time For Scheduled Start Transmit in seconds Returns: number """ return self._get_attribute('delayTimeForScheduledStart') @DelayTimeForScheduledStart.setter def DelayTimeForScheduledStart(self, value): self._set_attribute('delayTimeForScheduledStart', value) @property def DestMacRetryCount(self): """The number of time to attempt to obtain the destination MAC address. Returns: number """ return self._get_attribute('destMacRetryCount') @DestMacRetryCount.setter def DestMacRetryCount(self, value): self._set_attribute('destMacRetryCount', value) @property def DestMacRetryDelay(self): """The number of seconds to wait between attempts to obtain the destination MAC address. Returns: number """ return self._get_attribute('destMacRetryDelay') @DestMacRetryDelay.setter def DestMacRetryDelay(self, value): self._set_attribute('destMacRetryDelay', value) @property def DetectMisdirectedOnAllPorts(self): """ Returns: bool """ return self._get_attribute('detectMisdirectedOnAllPorts') @DetectMisdirectedOnAllPorts.setter def DetectMisdirectedOnAllPorts(self, value): self._set_attribute('detectMisdirectedOnAllPorts', value) @property def DisplayMplsCurrentLabelValue(self): """Displays current label value for LSP Endpoints. Returns: bool """ return self._get_attribute('displayMplsCurrentLabelValue') @DisplayMplsCurrentLabelValue.setter def DisplayMplsCurrentLabelValue(self, value): self._set_attribute('displayMplsCurrentLabelValue', value) @property def ElapsedTransmitTime(self): """Specifies the amount of time traffic is running in milliseconds. If the traffic state is unapplied or errored then the transmit time will be 0. Returns: number """ return self._get_attribute('elapsedTransmitTime') @property def EnableDataIntegrityCheck(self): """If true, enable data integrity check. Returns: bool """ return self._get_attribute('enableDataIntegrityCheck') @EnableDataIntegrityCheck.setter def EnableDataIntegrityCheck(self, value): self._set_attribute('enableDataIntegrityCheck', value) @property def EnableDestMacRetry(self): """If true, enables the destination MAC address retry function. Returns: bool """ return self._get_attribute('enableDestMacRetry') @EnableDestMacRetry.setter def EnableDestMacRetry(self, value): self._set_attribute('enableDestMacRetry', value) @property def EnableEgressOnlyTracking(self): """This flags enables/disables egress only tracking on the quick flow group. In this mode only quick flow groups are supported, user will have only PGID stats and the packets will not contain any instrumentation block. Returns: bool """ return self._get_attribute('enableEgressOnlyTracking') @EnableEgressOnlyTracking.setter def EnableEgressOnlyTracking(self, value): self._set_attribute('enableEgressOnlyTracking', value) @property def EnableInstantaneousStatsSupport(self): """If true, enables instantaneous stats support Returns: bool """ return self._get_attribute('enableInstantaneousStatsSupport') @EnableInstantaneousStatsSupport.setter def EnableInstantaneousStatsSupport(self, value): self._set_attribute('enableInstantaneousStatsSupport', value) @property def EnableLagFlowBalancing(self): """ Returns: bool """ return self._get_attribute('enableLagFlowBalancing') @EnableLagFlowBalancing.setter def EnableLagFlowBalancing(self, value): self._set_attribute('enableLagFlowBalancing', value) @property def EnableMinFrameSize(self): """If true, IxNetwork will allow the stream to use smaller packet sizes. (In the case of IPv4 and Ethernet, 64 bytes will be allowed.) This is achieved by reducing the size of the instrumentation tag, which will be identified by receiving ports. Returns: bool """ return self._get_attribute('enableMinFrameSize') @EnableMinFrameSize.setter def EnableMinFrameSize(self, value): self._set_attribute('enableMinFrameSize', value) @property def EnableMulticastScalingFactor(self): """If true, traffic items with the Merged Destination Ranges option selected have be to manually regenerated by the user. Returns: bool """ return self._get_attribute('enableMulticastScalingFactor') @EnableMulticastScalingFactor.setter def EnableMulticastScalingFactor(self, value): self._set_attribute('enableMulticastScalingFactor', value) @property def EnableSequenceChecking(self): """If true, this field enables sequence checking. The default is false. Returns: bool """ return self._get_attribute('enableSequenceChecking') @EnableSequenceChecking.setter def EnableSequenceChecking(self, value): self._set_attribute('enableSequenceChecking', value) @property def EnableStaggeredStartDelay(self): """If checked, enables the staggered start delay function. Returns: bool """ return self._get_attribute('enableStaggeredStartDelay') @EnableStaggeredStartDelay.setter def EnableStaggeredStartDelay(self, value): self._set_attribute('enableStaggeredStartDelay', value) @property def EnableStaggeredTransmit(self): """If true, the start of transmit is staggered across ports. A 25-30 ms delay is introduced between the time one port begins transmitting and the time next port begins transmitting. Returns: bool """ return self._get_attribute('enableStaggeredTransmit') @EnableStaggeredTransmit.setter def EnableStaggeredTransmit(self, value): self._set_attribute('enableStaggeredTransmit', value) @property def EnableStreamOrdering(self): """If true, IxNetwork will allow stream ordering per RFC 2889. Returns: bool """ return self._get_attribute('enableStreamOrdering') @EnableStreamOrdering.setter def EnableStreamOrdering(self, value): self._set_attribute('enableStreamOrdering', value) @property def FrameOrderingMode(self): """If true, enables frame ordering. Returns: str(flowGroupSetup|none|peakLoading|RFC2889) """ return self._get_attribute('frameOrderingMode') @FrameOrderingMode.setter def FrameOrderingMode(self, value): self._set_attribute('frameOrderingMode', value) @property def GlobalStreamControl(self): """The Global Stream Control parameters. Returns: str(continuous|iterations) """ return self._get_attribute('globalStreamControl') @GlobalStreamControl.setter def GlobalStreamControl(self, value): self._set_attribute('globalStreamControl', value) @property def GlobalStreamControlIterations(self): """If true, the user can specify how many times each packet stream will be transmitted. Returns: number """ return self._get_attribute('globalStreamControlIterations') @GlobalStreamControlIterations.setter def GlobalStreamControlIterations(self, value): self._set_attribute('globalStreamControlIterations', value) @property def IsApplicationTrafficRunning(self): """If true, application traffic is running. Returns: bool """ return self._get_attribute('isApplicationTrafficRunning') @property def IsApplyOnTheFlyRequired(self): """ Returns: bool """ return self._get_attribute('isApplyOnTheFlyRequired') @property def IsTrafficRunning(self): """If true, non-application traffic is running. Returns: bool """ return self._get_attribute('isTrafficRunning') @property def LargeErrorThreshhold(self): """The user-configurable threshold value used to determine error levels for out-of-sequence, received packets. Returns: number """ return self._get_attribute('largeErrorThreshhold') @LargeErrorThreshhold.setter def LargeErrorThreshhold(self, value): self._set_attribute('largeErrorThreshhold', value) @property def LearningFrameSize(self): """Learns frame size Returns: number """ return self._get_attribute('learningFrameSize') @LearningFrameSize.setter def LearningFrameSize(self, value): self._set_attribute('learningFrameSize', value) @property def LearningFramesCount(self): """Learns frames count Returns: number """ return self._get_attribute('learningFramesCount') @LearningFramesCount.setter def LearningFramesCount(self, value): self._set_attribute('learningFramesCount', value) @property def LearningFramesRate(self): """Learns frames rate Returns: number """ return self._get_attribute('learningFramesRate') @LearningFramesRate.setter def LearningFramesRate(self, value): self._set_attribute('learningFramesRate', value) @property def MacChangeOnFly(self): """If true, enables IxNetwork's gratuitous ARP capability. When enabled, IxNetwork listens for gratuitous ARP messages from its neighbors. Returns: bool """ return self._get_attribute('macChangeOnFly') @MacChangeOnFly.setter def MacChangeOnFly(self, value): self._set_attribute('macChangeOnFly', value) @property def MaxTrafficGenerationQueries(self): """The maximum number of traffic generation queries. The default is 500. Returns: number """ return self._get_attribute('maxTrafficGenerationQueries') @MaxTrafficGenerationQueries.setter def MaxTrafficGenerationQueries(self, value): self._set_attribute('maxTrafficGenerationQueries', value) @property def MplsLabelLearningTimeout(self): """The MPLS label learning timeout in seconds. The default is 30 seconds. Returns: number """ return self._get_attribute('mplsLabelLearningTimeout') @MplsLabelLearningTimeout.setter def MplsLabelLearningTimeout(self, value): self._set_attribute('mplsLabelLearningTimeout', value) @property def PeakLoadingReplicationCount(self): """The peak loading replication count Returns: number """ return self._get_attribute('peakLoadingReplicationCount') @PeakLoadingReplicationCount.setter def PeakLoadingReplicationCount(self, value): self._set_attribute('peakLoadingReplicationCount', value) @property def PreventDataPlaneToCpu(self): """Prevent all data plane packets from being forwarded to Port CPU (disabling this option requires Port CPU reboot) Returns: bool """ return self._get_attribute('preventDataPlaneToCpu') @PreventDataPlaneToCpu.setter def PreventDataPlaneToCpu(self, value): self._set_attribute('preventDataPlaneToCpu', value) @property def RefreshLearnedInfoBeforeApply(self): """This field refreshes the learned information from the DUT. Returns: bool """ return self._get_attribute('refreshLearnedInfoBeforeApply') @RefreshLearnedInfoBeforeApply.setter def RefreshLearnedInfoBeforeApply(self, value): self._set_attribute('refreshLearnedInfoBeforeApply', value) @property def State(self): """Denotes the current state of traffic. Returns: str(error|locked|started|startedWaitingForStats|startedWaitingForStreams|stopped|stoppedWaitingForStats|txStopWatchExpected|unapplied) """ return self._get_attribute('state') @property def UseRfc5952(self): """Use RFC 5952 for formatting IPv6 addresses (:ffff:192.168.3.11) Returns: bool """ return self._get_attribute('useRfc5952') @UseRfc5952.setter def UseRfc5952(self, value): self._set_attribute('useRfc5952', value) @property def UseScheduledStartTransmit(self): """Use Scheduled Start Transmit Returns: bool """ return self._get_attribute('useScheduledStartTransmit') @UseScheduledStartTransmit.setter def UseScheduledStartTransmit(self, value): self._set_attribute('useScheduledStartTransmit', value) @property def UseTxRxSync(self): """If true, enables the transmit/receive port synchronization algorithm. Returns: bool """ return self._get_attribute('useTxRxSync') @UseTxRxSync.setter def UseTxRxSync(self, value): self._set_attribute('useTxRxSync', value) @property def WaitTime(self): """The time (in seconds) to wait after Stop Transmit before stopping Latency Measurement. Returns: number """ return self._get_attribute('waitTime') @WaitTime.setter def WaitTime(self, value): self._set_attribute('waitTime', value) def Apply(self): """Executes the apply operation on the server. Apply the traffic configuration. Args: Arg1 (str(None|/api/v1/sessions/1/ixnetwork/traffic)): The method internally sets Arg1 to the current href for this instance Raises: NotFoundError: The requested resource does not exist on the server ServerError: The server has encountered an uncategorized error condition """ Arg1 = self.href return self._execute('Apply', payload=locals(), response_object=None) def ApplyApplicationTraffic(self): """Executes the applyApplicationTraffic operation on the server. Apply the stateful traffic configuration. Args: Arg1 (str(None|/api/v1/sessions/1/ixnetwork/traffic)): The method internally sets Arg1 to the current href for this instance Raises: NotFoundError: The requested resource does not exist on the server ServerError: The server has encountered an uncategorized error condition """ Arg1 = self.href return self._execute('ApplyApplicationTraffic', payload=locals(), response_object=None) def ApplyOnTheFlyTrafficChanges(self): """Executes the applyOnTheFlyTrafficChanges operation on the server. Apply on the fly traffic changes. Args: Arg1 (str(None|/api/v1/sessions/1/ixnetwork/traffic)): The method internally sets Arg1 to the current href for this instance Raises: NotFoundError: The requested resource does not exist on the server ServerError: The server has encountered an uncategorized error condition """ Arg1 = self.href return self._execute('ApplyOnTheFlyTrafficChanges', payload=locals(), response_object=None) def ApplyStatefulTraffic(self): """Executes the applyStatefulTraffic operation on the server. Apply the traffic configuration for stateful traffic items only. Args: Arg1 (str(None|/api/v1/sessions/1/ixnetwork/traffic)): The method internally sets Arg1 to the current href for this instance Raises: NotFoundError: The requested resource does not exist on the server ServerError: The server has encountered an uncategorized error condition """ Arg1 = self.href return self._execute('ApplyStatefulTraffic', payload=locals(), response_object=None) def GetFrameCountForDuration(self, Arg2): """Executes the getFrameCountForDuration operation on the server. Get the frame count for a specific duration. Args: Arg1 (str(None|/api/v1/sessions/1/ixnetwork/traffic)): The method internally sets Arg1 to the current href
skin blood flow rate (BFsk) [L/h]. Parameters ---------- err_cr, err_sk : array Difference between setpoint and body temperatures [oC]. height : float, optional Body height [m]. The default is 1.72. weight : float, optional Body weight [kg]. The default is 74.43. equation : str, optional The equation name (str) of bsa calculation. Choose a name from "dubois", "takahira", "fujimoto", or "kurazumi". The default is "dubois". age : float, optional Age [years]. The default is 20. ci : float, optional Cardiac index [L/min/㎡]. The default is 2.59. Returns ------- BFsk : array Skin blood flow rate [L/h]. """ wrms, clds = error_signals(err_cr, err_sk) # BFBsk bfb_sk = np.array([ 1.754, 0.325, 1.967, 1.475, 2.272, 0.91, 0.508, 1.114, 0.91, 0.508, 1.114, 1.456, 0.651, 0.934, 1.456, 0.651, 0.934,]) # SKIND skin_dilat = np.array([ 0.0692, 0.0992, 0.0580, 0.0679, 0.0707, 0.0400, 0.0373, 0.0632, 0.0400, 0.0373, 0.0632, 0.0736, 0.0411, 0.0623, 0.0736, 0.0411, 0.0623,]) # SKINC skin_stric = np.array([ 0.0213, 0.0213, 0.0638, 0.0638, 0.0638, 0.0213, 0.0213, 0.1489, 0.0213, 0.0213, 0.1489, 0.0213, 0.0213, 0.1489, 0.0213, 0.0213, 0.1489,]) sig_dilat = (100.5*err_cr[0]) + (6.4*(wrms-clds)) sig_stric = (-10.8*err_cr[0]) + (-10.8*(wrms-clds)) sig_dilat = max(sig_dilat, 0) sig_stric = max(sig_stric, 0) # Signal decrement by aging if age < 60: sd_dilat = np.ones(17) sd_stric = np.ones(17) else: #age >= 60 sd_dilat = np.array([ 0.91, 0.91, 0.47, 0.47, 0.31, 0.47, 0.47, 0.47, 0.47, 0.47, 0.47, 0.31, 0.31, 0.31, 0.31, 0.31, 0.31, ]) sd_stric = np.ones(17) #皮膚血流量 [L/h] bf_sk = (1 + skin_dilat * sd_dilat * sig_dilat) / \ (1 + skin_stric * sd_stric * sig_stric) * bfb_sk * 2**(err_sk/6) bfbr = cons.bfb_rate(height, weight, equation, age, ci,) bf_sk *= bfbr return bf_sk def ava_bloodflow(err_cr, err_sk, height=1.72, weight=74.43, equation="dubois", age=20, ci=2.59,): """ Calculate areteriovenous anastmoses (AVA) blood flow rate [L/h] based on Takemori's model, 1995. Parameters ---------- err_cr, err_sk : array Difference between setpoint and body temperatures [oC]. height : float, optional Body height [m]. The default is 1.72. weight : float, optional Body weight [kg]. The default is 74.43. equation : str, optional The equation name (str) of bsa calculation. Choose a name from "dubois", "takahira", "fujimoto", or "kurazumi". The default is "dubois". age : float, optional Age [years]. The default is 20. ci : float, optional Cardiac index [L/min/m2]. The default is 2.59. Returns ------- BFava_hand, BFava_foot : array AVA blood flow rate at hand and foot [L/h]. """ # Cal. mean error body core temp. cap_bcr = [10.2975, 9.3935, 13.834] # Thermal capacity at Chest, Back and Pelvis err_bcr = np.average(err_cr[2:5], weights=cap_bcr) # Cal. mean error skin temp. bsa = _BSAst err_msk = np.average(err_sk, weights=bsa) # Openbess of AVA [-] sig_ava_hand = 0.265 * (err_bcr + 0.43) + 0.953 * (err_msk + 0.1905) + 0.9126 sig_ava_foot = 0.265 * (err_bcr - 0.97) + 0.953 * (err_msk - 0.0095) + 0.9126 sig_ava_hand = min(sig_ava_hand, 1) sig_ava_hand = max(sig_ava_hand, 0) sig_ava_foot = min(sig_ava_foot, 1) sig_ava_foot = max(sig_ava_foot, 0) bfbr = bfbr = cons.bfb_rate(height, weight, equation, age, ci,) # AVA blood flow rate [L/h] bf_ava_hand = 1.71 * bfbr * sig_ava_hand # Hand bf_ava_foot = 2.16 * bfbr * sig_ava_foot # Foot return bf_ava_hand, bf_ava_foot def basal_met(height=1.72, weight=74.43, age=20, sex="male", equation="harris-benedict"): """ Calculate basal metabolic rate [W]. Parameters ---------- height : float, optional Body height [m]. The default is 1.72. weight : float, optional Body weight [kg]. The default is 74.43. age : float, optional Age [years]. The default is 20. sex : str, optional Choose male or female. The default is "male". equation : str, optional Choose harris-benedict or ganpule. The default is "harris-benedict". Returns ------- BMR : float Basal metabolic rate [W]. """ if equation=="harris-benedict": if sex=="male": bmr = 88.362 + 13.397*weight + 500.3*height - 5.677*age else: bmr = 447.593 + 9.247*weight + 479.9*height - 4.330*age elif equation=="harris-benedict_origin": if sex=="male": bmr = 66.4730 + 13.7516*weight + 500.33*height - 6.7550*age else: bmr = 655.0955 + 9.5634*weight + 184.96*height - 4.6756*age elif equation=="japanese" or equation=="ganpule": # Ganpule et al., 2007, https://doi.org/10.1038/sj.ejcn.1602645 if sex=="male": bmr = 0.0481*weight + 2.34*height - 0.0138*age - 0.4235 else: bmr = 0.0481*weight + 2.34*height - 0.0138*age - 0.9708 bmr *= 1000 / 4.186 bmr *= 0.048 # [kcal/day] to [W] return bmr def local_mbase(height=1.72, weight=74.43, age=20, sex="male", equation="harris-benedict"): """ Calculate local basal metabolic rate [W]. Parameters ---------- height : float, optional Body height [m]. The default is 1.72. weight : float, optional Body weight [kg]. The default is 74.43. age : float, optional Age [years]. The default is 20. sex : str, optional Choose male or female. The default is "male". equation : str, optional Choose harris-benedict or ganpule. The default is "harris-benedict". Returns ------- mbase : array Local basal metabolic rate (Mbase) [W]. """ mbase_all = basal_met(height, weight, age, sex, equation) # Distribution coefficient of basal metabolic rate mbf_cr = np.array([ 0.19551, 0.00324, 0.28689, 0.25677, 0.09509, 0.01435, 0.00409, 0.00106, 0.01435, 0.00409, 0.00106, 0.01557, 0.00422, 0.00250, 0.01557, 0.00422, 0.00250,]) mbf_ms = np.array([ 0.00252, 0.0, 0.0, 0.0, 0.04804, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,]) mbf_fat = np.array([ 0.00127, 0.0, 0.0, 0.0, 0.00950, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,]) mbf_sk = np.array([ 0.00152, 0.00033, 0.00211, 0.00187, 0.00300, 0.00059, 0.00031, 0.00059, 0.00059, 0.00031, 0.00059, 0.00144, 0.00027, 0.00118, 0.00144, 0.00027, 0.00118,]) mbase_cr = mbf_cr * mbase_all mbase_ms = mbf_ms * mbase_all mbase_fat = mbf_fat * mbase_all mbase_sk = mbf_sk * mbase_all return mbase_cr, mbase_ms, mbase_fat, mbase_sk def local_mwork(bmr, par): """ Calculate local metabolic rate by work [W] Parameters ---------- bmr : float Basal metbolic rate [W]. par : float Physical activity ratio [-]. Returns ------- Mwork : array Local metabolic rate by work [W]. """ mwork_all = (par-1) * bmr mwf = np.array([ 0, 0, 0.091, 0.08, 0.129, 0.0262, 0.0139, 0.005, 0.0262, 0.0139, 0.005, 0.2010, 0.0990, 0.005, 0.2010, 0.0990, 0.005]) mwork = mwork_all * mwf return mwork PRE_SHIV = 0 def shivering(err_cr, err_sk, tcr, tsk, height=1.72, weight=74.43, equation="dubois", age=20, sex="male", dtime=60, options={}): """ Calculate local metabolic rate by shivering [W]. Parameters ---------- err_cr, err_sk : array Difference between setpoint and body temperatures [oC]. tcr, tsk : array Core and skin temperatures [oC]. height : float, optional Body height [m]. The default is 1.72. weight : float, optional Body weight [kg]. The default is 74.43. equation : str, optional The equation name (str) of bsa calculation. Choose a name from "dubois", "takahira", "fujimoto", or "kurazumi". The default is "dubois". age : float, optional Age [years]. The default is 20. sex : str, optional Choose male or female. The default is "male". dtime : float, optional Interval of analysis time. The default is 60. Returns ------- Mshiv : array Local metabolic rate by shivering [W]. """ wrms, clds = error_signals(err_cr, err_sk,) shivf = np.array([ 0.0339, 0.0436, 0.27394, 0.24102, 0.38754, 0.00243, 0.00137, 0.0002, 0.00243, 0.00137, 0.0002, 0.0039, 0.00175, 0.00035, 0.0039, 0.00175, 0.00035,]) sig_shiv = 24.36 * clds * (-err_cr[0]) sig_shiv = max(sig_shiv, 0) if options: if options["shivering_threshold"]: # Asaka, 2016 # Threshold of starting shivering tskm = np.average(tsk, weights=_BSAst) # Mean skin temp. if tskm < 31: thres = 36.6 else: if sex == "male": thres = -0.2436 * tskm + 44.10 else: # sex == "female": thres = -0.2250 * tskm + 43.05 # Second threshold of starting shivering if thres < tcr[0]: sig_shiv = 0 global PRE_SHIV # Previous shivering thermogenesis [W] if options: if options["limit_dshiv/dt"]: # Asaka, 2016 # dshiv < 0.0077 [W/s] dshiv = sig_shiv - PRE_SHIV if options["limit_dshiv/dt"] is True: # default is 0.0077 [W/s] limit_dshiv = 0.0077 * dtime else: limit_dshiv = options["limit_dshiv/dt"] * dtime if dshiv > limit_dshiv: sig_shiv = limit_dshiv + PRE_SHIV elif dshiv < -limit_dshiv: sig_shiv = -limit_dshiv + PRE_SHIV PRE_SHIV = sig_shiv # Signal sd_shiv by aging if age < 30: sd_shiv = np.ones(17) elif age < 40: sd_shiv = np.ones(17) * 0.97514 elif age < 50: sd_shiv = np.ones(17)
""" Generates rules by optimising the thresholds of each feature individually, then combining them. """ import pandas as pd import numpy as np import math from itertools import combinations from iguanas.correlation_reduction.agglomerative_clustering_reducer import AgglomerativeClusteringReducer import iguanas.utils as utils from iguanas.rule_application import RuleApplier from iguanas.rule_generation._base_generator import _BaseGenerator from iguanas.metrics.pairwise import CosineSimilarity from iguanas.metrics.classification import FScore, Precision from iguanas.utils.types import PandasDataFrame, PandasSeries from iguanas.utils.typing import PandasDataFrameType, PandasSeriesType from typing import Callable, List, Tuple, Dict import warnings f1 = FScore(1) class RuleGeneratorOpt(_BaseGenerator): """ Generate rules by optimising the thresholds of single features and combining these one condition rules with AND conditions to create more complex rules. Parameters ---------- metric : Callable A function/method which calculates the desired performance metric (e.g. Fbeta score). Note that the module will assume higher values correspond to better performing rules. n_total_conditions : int The maximum number of conditions per generated rule. num_rules_keep : int The top number of rules (by Fbeta score) to keep at the end of each stage of rule combination. Reducing this number will improve the runtime, but may result in useful rules being removed. n_points : int, optional Number of points to split a numeric feature's range into when generating the numeric one condition rules. A larger number will result in better optimised one condition rules, but will take longer to calculate. Defaults to 10. ratio_window : int, optional Factor which determines the optimisation range for numeric features (e.g. if a numeric field has range of 1 to 11 and ratio_window = 3, the optimisation range for the <= operator will be from 1 to (11-1)/3 = 3.33; the optimisation range for the >= operator will be from 11-((11-1)/3)=7.67 to 11). A larger number (greater than 1) will result in a smaller range being used for optimisation of one condition rules; set to 1 if you want to optimise the one condition rules across the full range of the numeric feature. Defaults to 2. one_cond_rule_opt_metric : Callable, optional The method/function used for optimising the one condition rules. Note that the module will assume higher values correspond to better performing rules. Defaults to the method used for calculating the F1 score. remove_corr_rules : bool, optional Dictates whether correlated rules should be removed at the end of each pairwise combination. Defaults to True. target_feat_corr_types : Union[Dict[str, List[str]], str], optional Limits the conditions of the rules based on the target-feature correlation (e.g. if a feature has a positive correlation with respect to the target, then only greater than operators are used for conditions that utilise that feature). Can be either a dictionary specifying the list of positively correlated features wrt the target (under the key `PositiveCorr`) and negatively correlated features wrt the target (under the key `NegativeCorr`), or 'Infer' (where each target-feature correlation type is inferred from the data). Defaults to None. verbose : int, optional Controls the verbosity - the higher, the more messages. >0 : gives the progress of the training of the rules. Defaults to 0. rule_name_prefix : str, optional Prefix to use for each rule. Defaults to 'RGO_Rule'. Attributes ---------- rule_strings : Dict[str, str] The generated rules, defined using the standard Iguanas string format (values) and their names (keys). rule_lambdas : Dict[str, object] The generated rules, defined using the standard Iguanas lambda expression format (values) and their names (keys). lambda_kwargs : Dict[str, object] The keyword arguments for the generated rules defined using the standard Iguanas lambda expression format. rules : Rules The Rules object containing the generated rules. rule_names : List[str] The names of the generated rules. """ def __init__(self, metric: Callable, n_total_conditions: int, num_rules_keep: int, n_points=10, ratio_window=2, one_cond_rule_opt_metric=f1.fit, remove_corr_rules=True, target_feat_corr_types=None, verbose=0, rule_name_prefix='RGO_Rule'): _BaseGenerator.__init__( self, metric=metric, target_feat_corr_types=target_feat_corr_types, rule_name_prefix=rule_name_prefix, ) self.n_total_conditions = n_total_conditions self.num_rules_keep = num_rules_keep self.n_points = n_points self.ratio_window = ratio_window self.one_cond_rule_opt_metric = one_cond_rule_opt_metric self.remove_corr_rules = remove_corr_rules self.verbose = verbose self.rule_strings = {} self.rule_names = [] def __repr__(self): if self.rule_strings: return f'RuleGeneratorOpt object with {len(self.rule_strings)} rules generated' else: return f'RuleGeneratorOpt(metric={self.metric}, n_total_conditions={self.n_total_conditions}, num_rules_keep={self.num_rules_keep}, n_points={self.n_points}, ratio_window={self.ratio_window}, one_cond_rule_opt_metric={self.one_cond_rule_opt_metric}, remove_corr_rules={self.remove_corr_rules}, target_feat_corr_types={self.target_feat_corr_types})' def fit(self, X: PandasDataFrameType, y: PandasSeriesType, sample_weight=None) -> PandasDataFrameType: """ Generate rules by optimising the thresholds of single features and combining these one condition rules with AND conditions to create more complex rules. Parameters ---------- X : PandasDataFrameType The feature set used for training the model. y : PandasSeriesType The target column. sample_weight : PandasSeriesType, optional Record-wise weights to apply. Defaults to None. Returns ------- PandasDataFrameType The binary columns of the generated rules. """ utils.check_allowed_types(X, 'X', [PandasDataFrame]) utils.check_allowed_types(y, 'y', [PandasSeries]) if sample_weight is not None: utils.check_allowed_types( sample_weight, 'sample_weight', [PandasSeries]) # Ensures rule names are the same when fit run without reinstantiating self._rule_name_counter = 0 if self.target_feat_corr_types == 'Infer': self.target_feat_corr_types = self._calc_target_ratio_wrt_features( X=X, y=y ) X_rules = pd.DataFrame() rule_strings = {} columns_int, columns_cat, columns_float = utils.return_columns_types( X) columns_num = [ col for col in columns_int if col not in columns_cat] + columns_float if columns_num: if self.verbose > 0: print( '--- Generating one condition rules for numeric features ---') rule_strings_num, X_rules_num = self._generate_numeric_one_condition_rules( X, y, columns_num, columns_int, sample_weight ) X_rules = pd.concat([X_rules, X_rules_num], axis=1) rule_strings.update(rule_strings_num) if columns_cat: if self.verbose > 0: print( '--- Generating one condition rules for OHE categorical features ---') rule_strings_cat, X_rules_cat = self._generate_categorical_one_condition_rules( X, y, columns_cat, sample_weight ) X_rules = pd.concat([X_rules, X_rules_cat], axis=1) rule_strings.update(rule_strings_cat) if self.verbose > 0: print('--- Generating pairwise rules ---') self.rule_strings, X_rules = self._generate_n_order_pairwise_rules( X_rules, y, rule_strings, self.remove_corr_rules, sample_weight ) self._generate_other_rule_formats() return X_rules def _generate_numeric_one_condition_rules(self, X: PandasDataFrameType, y: PandasSeriesType, columns_num: List[str], columns_int: List[str], sample_weight: PandasSeriesType) -> Tuple[PandasDataFrameType, PandasDataFrameType]: """ Generates one condition rules for numeric columns by optimising the threshold of each column based on `metric`. """ rule_strings = {} if self.target_feat_corr_types is not None: pos_corr_num_feats = [ col for col in columns_num if col in self.target_feat_corr_types['PositiveCorr']] neg_corr_num_feats = [ col for col in columns_num if col in self.target_feat_corr_types['NegativeCorr']] cols_and_operators = list(zip(pos_corr_num_feats, ['>='] * len(pos_corr_num_feats))) + list( zip(neg_corr_num_feats, ['<='] * len(neg_corr_num_feats))) else: cols_and_operators = list( zip(columns_num * 2, [">="] * len(columns_num) + ["<="] * len(columns_num))) cols_and_operators = utils.return_progress_ready_range( verbose=self.verbose, range=cols_and_operators) for column, operator in cols_and_operators: X_col = X[column].values if np.std(X_col) == 0: continue x_min, x_max = self._set_iteration_range( X_col=X_col, column=column, operator=operator, n_points=self.n_points, ratio_window=self.ratio_window, columns_int=columns_int) x_iter = self._set_iteration_array( column, columns_int, x_min, x_max, self.n_points) # Optimise threshold using self.one_cond_rule_beta opt_metric_iter = self._calculate_opt_metric_across_range( x_iter=x_iter, operator=operator, X_col=X_col, y=y, metric=self.one_cond_rule_opt_metric, sample_weight=sample_weight) x_max_opt_metric = self._return_x_of_max_opt_metric( opt_metric_iter, operator, x_iter) rule_logic = f"(X['{column}']{operator}{x_max_opt_metric})" rule_name = self._generate_rule_name() rule_strings[rule_name] = rule_logic if not rule_strings: warnings.warn('No numeric one condition rules could be created.') return pd.DataFrame(), pd.DataFrame() ara = RuleApplier(rule_strings=rule_strings) X_rules = ara.transform(X=X) rule_strings, X_rules = self._drop_zero_var_and_precision_rules( X_rules=X_rules, y=y, rule_strings=rule_strings ) return rule_strings, X_rules def _generate_categorical_one_condition_rules(self, X: PandasDataFrameType, y: PandasSeriesType, columns_cat: List[str], sample_weight: PandasDataFrameType) -> Tuple[PandasDataFrameType, PandasDataFrameType]: """Generates one condition rules for OHE categorical columns""" def _gen_rules_from_target_feat_corr_types(X: PandasDataFrameType, y: PandasSeriesType, columns_cat: List[str], sample_weight: PandasSeriesType) -> Tuple[PandasDataFrameType, PandasDataFrameType]: """ Generates rules using the target-feature correlation types given in `target_feat_corr_types`. """ pos_corr_cat_feats = [ col for col in columns_cat if col in self.target_feat_corr_types['PositiveCorr']] neg_corr_cat_feats = [ col for col in columns_cat if col in self.target_feat_corr_types['NegativeCorr']] cols_and_operators = list(zip(pos_corr_cat_feats, ['True'] * len(pos_corr_cat_feats))) + list( zip(neg_corr_cat_feats, ['False'] * len(neg_corr_cat_feats))) rule_strings = { self._generate_rule_name(): f"(X['{col}']=={operator})" for col, operator in cols_and_operators } ara = RuleApplier( rule_strings=rule_strings ) X_rules = ara.transform(X=X) return rule_strings, X_rules def _gen_rules_best_perf_bool_option(X: PandasDataFrameType, y: PandasSeriesType, columns_cat: List[str], sample_weight: PandasSeriesType) -> Tuple[PandasDataFrameType, PandasDataFrameType]: """ Generates rules by keeping only the best performing boolean value per OHE column. """ X_rules_list = [] rule_strings = {} for col in columns_cat: X_rules_col_list = [] for value in ['True', 'False']: rule_name = self._generate_rule_name() rule_logic = f"(X['{col}']=={value})" rule_string = {rule_name: rule_logic} ara = RuleApplier(rule_strings=rule_string) X_rule = ara.transform(X=X) rule_strings.update(rule_string) X_rules_col_list.append(X_rule) X_rules_col = pd.concat(X_rules_col_list, axis=1) # Keep only best performing condition per feature metrics = self.one_cond_rule_opt_metric( X_rules_col, y, sample_weight ) X_rules_col = X_rules_col.iloc[:, np.argmax(metrics)] X_rules_list.append(X_rules_col) X_rules = pd.concat(X_rules_list, axis=1)
# coding=utf-8 import logging import re import traceback import types import os import time import datetime from ignore import get_decision_list from helpers import is_recent, get_plex_item_display_title, query_plex, PartUnknownException from lib import Plex, get_intent from config import config from subliminal_patch.subtitle import ModifiedSubtitle from subzero.modification import registry as mod_registry, SubtitleModifications from socket import timeout logger = logging.getLogger(__name__) MI_KIND, MI_TITLE, MI_KEY, MI_DEEPER, MI_ITEM = 0, 1, 2, 3, 4 container_size_re = re.compile(ur'totalSize="(\d+)"') def get_item(key): try: item_id = int(key) except ValueError: return try: item_container = Plex["library"].metadata(item_id) except timeout: Log.Debug("PMS API timed out when querying information about item %d", item_id) return try: return list(item_container)[0] except: pass def get_item_kind(item): return type(item).__name__ PLEX_API_TYPE_MAP = { "Show": "series", "Season": "season", "Episode": "episode", "Movie": "movie", } def get_item_kind_from_rating_key(key): item = get_item(key) return PLEX_API_TYPE_MAP.get(get_item_kind(item)) def get_item_kind_from_item(item): return PLEX_API_TYPE_MAP.get(get_item_kind(item)) def get_item_title(item): kind = get_item_kind_from_item(item) if kind not in ("episode", "movie", "season", "series"): return if kind == "episode": return get_plex_item_display_title(item, "show", parent=item.season, section_title=None, parent_title=item.show.title) elif kind == "season": return get_plex_item_display_title(item, "season", parent=item.show, section_title="Season", parent_title=item.show.title) else: return get_plex_item_display_title(item, kind, section_title=None) def get_item_thumb(item): kind = get_item_kind(item) if kind == "Episode": return item.show.thumb elif kind == "Section": return item.art return item.thumb def get_items_info(items): return items[0][MI_KIND], items[0][MI_DEEPER] def get_kind(items): return items[0][MI_KIND] def get_section_size(key): """ quick query to determine the section size :param key: :return: """ size = None url = "http://127.0.0.1:32400/library/sections/%s/all" % int(key) use_args = { "X-Plex-Container-Size": "0", "X-Plex-Container-Start": "0" } response = query_plex(url, use_args) matches = container_size_re.findall(response.content) if matches: size = int(matches[0]) return size def get_items(key="recently_added", base="library", value=None, flat=False, add_section_title=False): """ try to handle all return types plex throws at us and return a generalized item tuple """ items = [] apply_value = None if value: if isinstance(value, types.ListType): apply_value = value else: apply_value = [value] result = getattr(Plex[base], key)(*(apply_value or [])) for item in result: cls = getattr(getattr(item, "__class__"), "__name__") if hasattr(item, "scanner"): kind = "section" elif cls == "Directory": kind = "directory" else: kind = item.type # only return items for our enabled sections section_key = None if kind == "section": section_key = item.key else: if hasattr(item, "section_key"): section_key = getattr(item, "section_key") if section_key and section_key not in config.enabled_sections: continue if kind == "season": # fixme: i think this case is unused now if flat: # return episodes for child in item.children(): items.append(("episode", get_plex_item_display_title(child, "show", parent=item, add_section_title=add_section_title), int(item.rating_key), False, child)) else: # return seasons items.append(("season", item.title, int(item.rating_key), True, item)) elif kind == "directory": items.append(("directory", item.title, item.key, True, item)) elif kind == "section": if item.type in ['movie', 'show']: item.size = get_section_size(item.key) items.append(("section", item.title, int(item.key), True, item)) elif kind == "episode": items.append( (kind, get_plex_item_display_title(item, "show", parent=item.season, parent_title=item.show.title, section_title=item.section.title, add_section_title=add_section_title), int(item.rating_key), False, item)) elif kind in ("movie", "artist", "photo"): items.append((kind, get_plex_item_display_title(item, kind, section_title=item.section.title, add_section_title=add_section_title), int(item.rating_key), False, item)) elif kind == "show": items.append(( kind, get_plex_item_display_title(item, kind, section_title=item.section.title, add_section_title=add_section_title), int(item.rating_key), True, item)) return items def get_recent_items(): """ actually get the recent items, not limited like /library/recentlyAdded :return: """ args = { "sort": "addedAt:desc", "X-Plex-Container-Start": "0", "X-Plex-Container-Size": "%s" % config.max_recent_items_per_library } episode_re = re.compile(ur'(?su)ratingKey="(?P<key>\d+)"' ur'.+?grandparentRatingKey="(?P<parent_key>\d+)"' ur'.+?title="(?P<title>.*?)"' ur'.+?grandparentTitle="(?P<parent_title>.*?)"' ur'.+?index="(?P<episode>\d+?)"' ur'.+?parentIndex="(?P<season>\d+?)".+?addedAt="(?P<added>\d+)"' ur'.+?<Part.+? file="(?P<filename>[^"]+?)"') movie_re = re.compile(ur'(?su)ratingKey="(?P<key>\d+)".+?title="(?P<title>.*?)' ur'".+?addedAt="(?P<added>\d+)"' ur'.+?<Part.+? file="(?P<filename>[^"]+?)"') available_keys = ("key", "title", "parent_key", "parent_title", "season", "episode", "added", "filename") recent = [] ref_list = get_decision_list() for section in Plex["library"].sections(): if section.type not in ("movie", "show") \ or section.key not in config.enabled_sections \ or ((section.key not in ref_list.sections and config.include) or (section.key in ref_list.sections and not config.include)): Log.Debug(u"Skipping section: %s" % section.title) continue use_args = args.copy() plex_item_type = "Movie" if section.type == "show": use_args["type"] = "4" plex_item_type = "Episode" url = "http://127.0.0.1:32400/library/sections/%s/all" % int(section.key) response = query_plex(url, use_args) matcher = episode_re if section.type == "show" else movie_re matches = [m.groupdict() for m in matcher.finditer(response.content)] for match in matches: data = dict((key, match[key] if key in match else None) for key in available_keys) if section.type == "show" and ((data["parent_key"] not in ref_list.series and config.include) or (data["parent_key"] in ref_list.series and not config.include)): Log.Debug(u"Skipping series: %s" % data["parent_title"]) continue if (data["key"] not in ref_list.videos and config.include) or \ (data["key"] in ref_list.videos and not config.include): Log.Debug(u"Skipping item: %s" % data["title"]) continue if not is_physically_wanted(data["filename"], plex_item_type): Log.Debug(u"Skipping item (physically not wanted): %s" % data["title"]) continue if is_recent(int(data["added"])): recent.append((int(data["added"]), section.type, section.title, data["key"])) return recent def get_on_deck_items(): return get_items(key="on_deck", add_section_title=True) def get_recently_added_items(): return get_items(key="recently_added", add_section_title=True, flat=False) def get_all_items(key, base="library", value=None, flat=False): return get_items(key, base=base, value=value, flat=flat) def is_wanted(rating_key, item=None): """ check whether an item, its show/season/section is in the soft or the hard ignore list :param rating_key: :param item: :return: """ ref_list = get_decision_list() ret_val = ref_list.store == "include" inc_exc_verbose = "exclude" if not ret_val else "include" # item in soft include/exclude list if ref_list["videos"] and rating_key in ref_list["videos"]: Log.Debug("Item %s is in the soft %s list" % (rating_key, inc_exc_verbose)) return ret_val item = item or get_item(rating_key) kind = get_item_kind(item) # show in soft include/exclude list if kind == "Episode" and ref_list["series"] and item.show.rating_key in ref_list["series"]: Log.Debug("Item %s's show is in the soft %s list" % (rating_key, inc_exc_verbose)) return ret_val # season in soft include/exclude list if kind == "Episode" and ref_list["seasons"] and item.season.rating_key in ref_list["seasons"]: Log.Debug("Item %s's season is in the soft %s list" % (rating_key, inc_exc_verbose)) return ret_val # section in soft include/exclude list if ref_list["sections"] and item.section.key in ref_list["sections"]: Log.Debug("Item %s's section is in the soft %s list" % (rating_key, inc_exc_verbose)) return ret_val # physical/path include/exclude if config.include_exclude_sz_files or config.include_exclude_paths: for media in item.media: for part in media.parts: return is_physically_wanted(part.file, kind) return not ret_val def is_physically_wanted(fn, kind): if config.include_exclude_sz_files or config.include_exclude_paths: # normally check current item folder and the library check_paths = [".", "../"] if kind == "Episode": # series/episode, we've got a season folder here, also check_paths.append("../../") wanted_results = [] if config.include_exclude_sz_files: for sub_path in check_paths: wanted_results.append(config.is_physically_wanted( os.path.normpath(os.path.join(os.path.dirname(fn), sub_path)), fn)) if config.include_exclude_paths: wanted_results.append(config.is_path_wanted(fn)) if config.include and any(wanted_results): return True elif not config.include and not all(wanted_results): return False return not config.include def refresh_item(rating_key, force=False, timeout=8000, refresh_kind=None, parent_rating_key=None): intent = get_intent() # timeout actually is the time for which the intent will be valid if force: Log.Debug("Setting intent for force-refresh of %s to timeout: %s", rating_key, timeout) intent.set("force", rating_key, timeout=timeout) # force Dict.Save() intent.store.save() refresh = [rating_key] if refresh_kind == "season": # season refresh, needs explicit per-episode refresh refresh = [item.rating_key for item in list(Plex["library/metadata"].children(int(rating_key)))] multiple = len(refresh) > 1 wait = config.advanced.get("refresh_after_called", 5) Thread.Sleep(wait) for key in refresh: Log.Info("%s item %s", "Refreshing" if not force else "Forced-refreshing", key) Plex["library/metadata"].refresh(key) if multiple: Thread.Sleep(wait) def get_current_sub(rating_key, part_id, language, plex_item=None): from support.storage import get_subtitle_storage item = plex_item or get_item(rating_key) subtitle_storage = get_subtitle_storage() stored_subs = subtitle_storage.load_or_new(item) current_sub = stored_subs.get_any(part_id, language) return current_sub, stored_subs, subtitle_storage def save_stored_sub(stored_subtitle, rating_key, part_id, language, item_type, plex_item=None, storage=None, stored_subs=None): """ in order for this to work, if the calling supplies stored_subs and storage, it has to trigger its saving and destruction explicitly :param stored_subtitle: :param rating_key: :param part_id: :param language: :param item_type: :param plex_item: :param storage: :param stored_subs: :return: """ from support.plex_media import get_plex_metadata from support.scanning import scan_videos from support.storage import save_subtitles, get_subtitle_storage plex_item = plex_item or get_item(rating_key) stored_subs_was_provided = True if not stored_subs or not storage: storage = get_subtitle_storage() stored_subs = storage.load(plex_item.rating_key) stored_subs_was_provided = False if not all([plex_item, stored_subs]): return try: metadata = get_plex_metadata(rating_key, part_id, item_type, plex_item=plex_item) except PartUnknownException: return scanned_parts = scan_videos([metadata], ignore_all=True, skip_hashing=True) video, plex_part = scanned_parts.items()[0] subtitle = ModifiedSubtitle(language, mods=stored_subtitle.mods) subtitle.content = stored_subtitle.content if stored_subtitle.encoding: # thanks plex setattr(subtitle, "_guessed_encoding", stored_subtitle.encoding) if stored_subtitle.encoding != "utf-8": subtitle.normalize() stored_subtitle.content = subtitle.content stored_subtitle.encoding = "utf-8" storage.save(stored_subs) subtitle.plex_media_fps = plex_part.fps subtitle.page_link = stored_subtitle.id subtitle.language = language subtitle.id = stored_subtitle.id try: save_subtitles(scanned_parts, {video: [subtitle]}, mode="m", bare_save=True) stored_subtitle.mods = subtitle.mods Log.Debug("Modified %s subtitle for: %s:%s with: %s", language.name, rating_key, part_id, ", ".join(subtitle.mods) if subtitle.mods else "none") except: Log.Error("Something went wrong when modifying subtitle: %s", traceback.format_exc()) if subtitle.storage_path: stored_subtitle.last_mod = datetime.datetime.fromtimestamp(os.path.getmtime(subtitle.storage_path)) if not stored_subs_was_provided: storage.save(stored_subs) storage.destroy() def set_mods_for_part(rating_key, part_id, language, item_type, mods, mode="add"): plex_item = get_item(rating_key) if not plex_item: return current_sub, stored_subs, storage = get_current_sub(rating_key, part_id, language, plex_item=plex_item) if mode == "add": for mod in mods: identifier, args = SubtitleModifications.parse_identifier(mod) mod_class = SubtitleModifications.get_mod_class(identifier) if identifier not in mod_registry.mods_available: raise NotImplementedError("Mod unknown or not registered") # clean exclusive mods if mod_class.exclusive and current_sub.mods: for current_mod in current_sub.mods[:]: if current_mod.startswith(identifier): current_sub.mods.remove(current_mod)
paramfile is not None: self.read_param_file(paramfile) def aperture_info(self): """ Get basic information on the reuqested aperture from SIAF """ local_roll, attitude_matrix, self.framesize, subarray_bounds = get_siaf_information(self.siaf, self.aperture, self.crop_center_ra, self.crop_center_dec, self.blot_pav3) xstart, ystart, xend, yend = subarray_bounds self.subarr_bounds = {'xstart': xstart, 'ystart': ystart, 'xend': xend, 'yend': yend} self.nominal_dims = np.array([yend - ystart + 1, xend - xstart + 1]) def crop_and_blot(self): """MAIN FUNCTION Extract an area of the input mosaic fits file that is slightly larger than the desired aperture, and use the JWST pipeline version of blot (called resample) to resample this to the correct pixel scale and introduce the proper distortion for the requested detector """ # Initialize log self.logger = logging.getLogger('mirage.seed_image.fits_seed_image') self.logger.info('\n\nRunning fits_seed_image....\n') self.logger.info('using parameter file: {}\n'.format(self.paramfile)) self.logger.info('Original log file name: ./{}'.format(STANDARD_LOGFILE_NAME)) self.detector_channel_value() self.distortion_file_value() module = self.module_value() self.siaf = pysiaf.Siaf(self.instrument) # Get information on the aperture self.aperture_info() xstart = self.subarr_bounds['xstart'] ystart = self.subarr_bounds['ystart'] xdim = self.subarr_bounds['xend'] - xstart + 1 ydim = self.subarr_bounds['yend'] - ystart + 1 # Flux calibration information self.flux_cal_file = self.expand_config_paths(self.flux_cal_file, 'flux_cal') vegazp, self.photflam, self.photfnu, self.pivot = fluxcal_info(self.flux_cal_file, self.instrument, self.filter, self.pupil, self.detector, module) # Get information on the instrument used to create the mosaic self.mosaic_metadata = tools.get_psf_metadata(self.mosaic_file) # Check that the FWHM of the mosaic PSF is smaller than the PSF # of the JWST PSF. If the opposite is true, we can't create a # matching kernel if self.mosaic_fwhm_units == 'arcsec': mosaic_fwhm_arcsec = copy.deepcopy(self.mosaic_fwhm) self.mosaic_fwhm /= self.mosaic_metadata['pix_scale1'] # Identify the correct PSF for the JWST instrument/detector # Let's just read in the psf_wings file, which contains the PSF # at the center of the detector. It doesn't make much sense to # worry about spatially-dependent PSFs in this case self.jwst_psf = get_psf_wings(self.instrument, self.detector, self.filter, self.pupil, self.params['simSignals']['psfwfe'], self.params['simSignals']['psfwfegroup'], os.path.join(self.params['simSignals']['psfpath'], 'psf_wings')) self.outscale1, self.outscale2 = self.find_jwst_pixel_scale() # Find the FWHM of the JWST PSF j_yd, j_xd = self.jwst_psf.shape mid_y = j_yd // 2 mid_x = j_xd // 2 box = self.jwst_psf[mid_y-10:mid_y+11, mid_x-10:mid_x+11] jwst_x_fwhm, jwst_y_fwhm = tools.measure_fwhm(box) jwst_y_fwhm_arcsec = jwst_y_fwhm * self.outscale2 self.logger.info('JWST FWHM in pix: {}'.format(jwst_y_fwhm)) self.logger.info('JWST FWHM in arcsec: {}'.format(jwst_y_fwhm_arcsec)) # If the FWHM of the mosaic image is larger than that of the JWST # PSF, then we cannot continue because we cannot create a matching # PSF kernel to use for convolution if mosaic_fwhm_arcsec > jwst_y_fwhm_arcsec: raise ValueError(("ERROR: FWHM of the mosaic image is larger than that of " "the JWST PSF. Unable to create a matching PSF kernel " "using photutils. \nMosaic FWHM: {}\nJWST FWHM: {}" .format(mosaic_fwhm_arcsec, jwst_y_fwhm_arcsec))) # The JWST PSF as read in is large (399 x 399 pixels). Crop to # something reasonable so that the convolution doesn't take # forever half_width = 50 self.jwst_psf = self.jwst_psf[mid_y-half_width: mid_y+half_width+1, mid_x-half_width: mid_x+half_width+1] # Collect the metadata relating to the mosaic and (optionally) PSF # and read in/create the PSF self.prepare_psf() # Crop self.logger.info("Cropping subarray from mosaic") pixel_scale = self.siaf[self.aperture].XSciScale crop = crop_mosaic.Extraction(mosaicfile=self.mosaic_file, data_extension_number=self.data_extension_number, wcs_extension_number=self.wcs_extension_number, center_ra=self.crop_center_ra, center_dec=self.crop_center_dec, dimensions=(xdim, ydim), outfile=self.cropped_file, jwst_pixel_scale=pixel_scale) crop.extract() # Convolve the cropped image with the appropriate PSF self.logger.info("Convolving with PSF kernel") crop.cropped = self.psf_convolution(crop.cropped) # Blot self.logger.info("Resampling subarray onto JWST pixel grid") blot = blot_image.Blot(instrument=self.instrument, aperture=self.aperture, ra=[self.blot_center_ra], dec=[self.blot_center_dec], pav3=[self.blot_pav3], blotfile=crop.cropped, distortion_file=self.distortion_file, filtername=self.params['Readout']['filter'], pupilname=self.params['Readout']['pupil'], obs_date=self.params['Output']['date_obs'], obs_time=self.params['Output']['time_obs']) blot.blot() # Blot the PSF associated with the mosaic #blot_psf = blot_image.Blot(instrument=self.instrument, aperture=self.aperture, # ra=[self.blot_center_ra], dec=[self.blot_center_dec], # pav3=[self.blot_pav3], blotfile=mosaic_psf_model, # distortion_file=self.distortion_file) #blot_psf.blot() for dm in blot.blotted_datamodels: # Create segmentation map # (used only when dispsersing image for WFSS) self.seed_image = dm.data self.seed_segmap = self.make_segmap(dm) # Save if self.blotted_file is not None: self.blotted_file = os.path.join(self.outdir, self.blotted_file) self.seed_file, self.seedinfo = save(dm.data, self.paramfile, self.params, self.photflam, self.photfnu, self.pivot, self.framesize, self.nominal_dims, self.coords, self.grism_direct_factor, segmentation_map=self.seed_segmap, filename=self.blotted_file, base_unit='e-') self.logger.info('Blotted image saved to: {}'.format(self.seed_file)) self.logger.info('\nfits_seed_image complete') logging_functions.move_logfile_to_standard_location(self.paramfile, STANDARD_LOGFILE_NAME, yaml_outdir=self.params['Output']['directory'], log_type='fits_seed') def detector_channel_value(self): """Get the detector and optional channel value based on the aperture name """ if self.detector is None: self.detector = self.aperture[0:5] self.detector = self.detector.upper() self.instrument = self.instrument.upper() # Make sure the FGS detector is GUIDER[12] if 'FGS' in self.detector: self.detector = 'GUIDER{}'.format(self.detctor[-1]) if 'NRC' in self.detector: if self.channel is None: if '5' in self.detector: self.channel = 'LONG' else: self.channel = 'SHORT' def distortion_file_value(self): """Make sure the distortion file name is a valid file. If it has a value of 'crds', then query CRDS and retrieve the appropriate file """ if self.distortion_file == 'crds': if self.paramfile is None: self.reference_dictionary = {} self.reference_dictionary['INSTRUME'] = self.instrument self.reference_dictionary['DETECTOR'] = self.detector if '5' in self.detector: self.reference_dictionary['DETECTOR'] = self.detector.replace('5', 'LONG') if self.instrument.upper() == 'NIRCAM': self.reference_dictionary['CHANNEL'] = self.channel if 'FGS' in self.reference_dictionary['DETECTOR']: self.reference_dictionary['DETECTOR'] = 'GUIDER{}'.format(self.reference_dictionary['DETECTOR'][-1]) # Use the current date and time in order to get the most recent # reference file self.reference_dictionary['DATE-OBS'] = datetime.date.today().isoformat() current_date = datetime.datetime.now() self.reference_dictionary['TIME-OBS'] = current_date.time().isoformat() # For the purposes of choosing reference files, the exposure type should # always be set to imaging, since it is used to locate sources in the # seed image, prior to any dispersion. self.reference_dictionary['EXP_TYPE'] = EXPTYPES[self.instrument.lower()]["imaging"] # This assumes that filter and pupil names match up with reality, # as opposed to the more user-friendly scheme of allowing any # filter to be in the filter field. self.reference_dictionary['FILTER'] = self.filter self.reference_dictionary['PUPIL'] = self.pupil mapping = crds_tools.get_reffiles(self.reference_dictionary, ['distortion'], download=True) self.distortion_file = mapping['distortion'] def expand_config_paths(self, filename, filetype): """If a reference file has the name "config" in the input yaml file, then convert that to the appropriate file name. This is done using a global dictionary. Parameters ---------- filename : str The filename as listed in the yaml file filetype : str The type of reference file in question. Currently the dictionary only has an entry for 'flux_cal' Returns ------- filename : str The updated filename for the reference file type in question """ if filename.lower() == 'config': sfile = config_files[self.instrument.lower()][filetype] return os.path.join(self.modpath, 'config', sfile) else: return filename def find_jwst_pixel_scale(self): """Find the pixel scale for the JWST instrument and aperture to be used for the seed image """ meta_output = {} meta_output['instrument'] = self.instrument return tools.get_JWST_pixel_scale(meta_output, aperture=self.aperture) def grism_coord_adjust(self): """Calculate the factors by which to expand the output array size, as well as the coordinate offsets between the nominal output array and the input lists if the observation being modeled is to be dispersed with the grism """ dtor = radians(1.) # Normal imaging with grism image requested self.coords['x'] = self.grism_direct_factor self.coords['y'] = self.grism_direct_factor self.coords['xoffset'] = np.int((self.grism_direct_factor - 1.) * (self.subarr_bounds['xend'] - self.subarr_bounds['xstart'] + 1) / 2.) self.coords['yoffset'] = np.int((self.grism_direct_factor - 1.) * (self.subarr_bounds['yend'] - self.subarr_bounds['ystart']+1) / 2.) def make_segmap(self, model): """Create a segmentation map of the input image Parameters ---------- model : jwst.datamodels.ImageModel Returns ------- map_image : numpy.ndarray 2D segmentation map """ noise = np.median(model.data) seg_map = detect_sources(model.data, noise*5., 8) if seg_map is None: self.logger.info('No segmentation map created. Returning empty segmap') map_image = np.zeros_like(model.data) else: map_image = seg_map.data return map_image @staticmethod def matching_kernel(psf1, psf2, window_type='TukeyWindow', alpha=None, beta=None): """Use photutils to create a matching kernel given two PSFs and the window type and parameters Parameters ---------- psf1 : numpy.ndarray 2D array containing the first PSF psf2 : numpy.ndarray 2D array containing the second PSF window_type : str Name of the window function to use when filtering the matching kernel alpha : float Optional input for some of the window functions beta : float Optional input for some of the window functions Returns ------- matched_kernel : numpy.ndarray 2D array containing the matching PSF kernel """ # Create the filtering window orig_window_type = copy.deepcopy(window_type) window_type = window_type.lower() if window_type == 'tophatwindow': window = TopHatWindow(beta=beta) elif window_type == 'cosinebellwindow': window = CosineBellWindow(alpha=alpha) elif window_type == 'splitcosinebellwindow': window = SplitCosineBellWindow(alpha=alpha, beta=beta) elif window_type == 'tukeywindow': window = TukeyWindow(alpha=alpha) elif window_type == 'hanningwindow': window = HanningWindow() else: raise ValueError("ERROR: Unrecognized window_type: {}".format(orig_window_type)) # Create the matching kernel matched_kernel = create_matching_kernel(psf1, psf2, window=window) return matched_kernel def module_value(self): """Determine the module value based on the instrument and detector """ if self.instrument == 'NIRCAM': module = self.detector[3].upper() elif self.instrument == 'NIRISS': module = 'N' elif self.instrument == 'FGS': module
Returns a dictionary of the keys and values that would be used to create the distribution for a Crow input file. @ In, None @ Out, retDict, dict, the dictionary of crow distributions """ retDict = Distribution.getCrowDistDict(self) retDict['p'] = self.p return retDict def _handleInput(self, paramInput): """ Function to handle the common parts of the distribution parameter input. @ In, paramInput, ParameterInput, the already parsed input. @ Out, None """ BoostDistribution._handleInput(self, paramInput) pFind = paramInput.findFirst('p') if pFind != None: self.p = pFind.value else: self.raiseAnError(IOError,'p value needed for Geometric distribution') self.initializeDistribution() def getInitParams(self): """ Function to get the initial values of the input parameters that belong to this class @ In, None @ Out, paramDict, dict, dictionary containing the parameter names as keys and each parameter's initial value as the dictionary values """ paramDict = BoostDistribution.getInitParams(self) paramDict['p'] = self.p return paramDict def initializeDistribution(self): """ Method to initialize the distribution @ In, None @ Out, None """ if self.lowerBoundUsed == False and self.upperBoundUsed == False: self._distribution = distribution1D.BasicGeometricDistribution(self.p) else: self.raiseAnError(IOError,'Truncated Geometric not yet implemented') DistributionsCollection.addSub(Geometric.getInputSpecification()) class Categorical(Distribution): """ Class for the categorical distribution also called " generalized Bernoulli distribution" Note: this distribution can have only numerical (float) outcome; in the future we might want to include also the possibility to give symbolic outcome """ @classmethod def getInputSpecification(cls): """ Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for which we are retrieving the specification @ Out, inputSpecification, InputData.ParameterInput, class to use for specifying input of cls. """ inputSpecification = InputData.parameterInputFactory(cls.__name__, ordered=True, baseNode=None) StatePartInput = InputData.parameterInputFactory("state", contentType=InputData.FloatType) StatePartInput.addParam("outcome", InputData.FloatType, True) inputSpecification.addSub(StatePartInput, InputData.Quantity.one_to_infinity) ## Because we do not inherit from the base class, we need to manually ## add the name back in. inputSpecification.addParam("name", InputData.StringType, True) return inputSpecification def __init__(self): """ Function that initializes the categorical distribution @ In, None @ Out, none """ Distribution.__init__(self) self.mapping = {} self.values = set() self.type = 'Categorical' self.dimensionality = 1 self.disttype = 'Discrete' def _handleInput(self, paramInput): """ Function to handle the common parts of the distribution parameter input. @ In, paramInput, ParameterInput, the already parsed input. @ Out, None """ for child in paramInput.subparts: if child.getName() == "state": outcome = child.parameterValues["outcome"] value = child.value self.mapping[outcome] = value if float(outcome) in self.values: self.raiseAnError(IOError,'Categorical distribution has identical outcomes') else: self.values.add(float(outcome)) else: self.raiseAnError(IOError,'Invalid xml node for Categorical distribution; only "state" is allowed') self.initializeDistribution() def getInitParams(self): """ Function to get the initial values of the input parameters that belong to this class @ In, None @ Out, paramDict, dict, dictionary containing the parameter names as keys and each parameter's initial value as the dictionary values """ paramDict = Distribution.getInitParams(self) paramDict['mapping'] = self.mapping paramDict['values'] = self.values return paramDict def initializeDistribution(self): """ Function that initializes the distribution and checks that the sum of all state probabilities is equal to 1 @ In, None @ Out, None """ totPsum = 0.0 for element in self.mapping: totPsum += self.mapping[element] if not mathUtils.compareFloats(totPsum,1.0): self.raiseAnError(IOError,'Categorical distribution cannot be initialized: sum of probabilities is '+repr(totPsum)+', not 1.0') self.lowerBound = min(self.mapping.keys()) self.upperBound = max(self.mapping.keys()) def pdf(self,x): """ Function that calculates the pdf value of x @ In, x, float/string, value to get the pdf at @ Out, pdfValue, float, requested pdf """ if x in self.values: pdfValue = self.mapping[x] else: self.raiseAnError(IOError,'Categorical distribution cannot calculate pdf for ' + str(x)) return pdfValue def cdf(self,x): """ Function to get the cdf value of x @ In, x, float/string, value to get the cdf at @ Out, cumulative, float, requested cdf """ sortedMapping = sorted(self.mapping.items(), key=operator.itemgetter(0)) if x in self.values: cumulative=0.0 for element in sortedMapping: cumulative += element[1] if x == float(element[0]): return cumulative else: self.raiseAnError(IOError,'Categorical distribution cannot calculate cdf for ' + str(x)) def ppf(self,x): """ Function that calculates the inverse of the cdf given 0 =< x =< 1 @ In, x, float, value to get the ppf at @ Out, element[0], float/string, requested inverse cdf """ sortedMapping = sorted(self.mapping.items(), key=operator.itemgetter(0)) cumulative=0.0 for element in sortedMapping: cumulative += element[1] if cumulative >= x: return float(element[0]) def rvs(self): """ Return a random state of the categorical distribution @ In, None @ Out, rvsValue, float/string, the random state """ rvsValue = self.ppf(random()) return rvsValue DistributionsCollection.addSub(Categorical.getInputSpecification()) class Logistic(BoostDistribution): """ Logistic univariate distribution """ @classmethod def getInputSpecification(cls): """ Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for which we are retrieving the specification @ Out, inputSpecification, InputData.ParameterInput, class to use for specifying input of cls. """ inputSpecification = super(Logistic, cls).getInputSpecification() inputSpecification.addSub(InputData.parameterInputFactory("location", contentType=InputData.FloatType)) inputSpecification.addSub(InputData.parameterInputFactory("scale", contentType=InputData.FloatType)) return inputSpecification def __init__(self): """ Constructor @ In, None @ Out, None """ BoostDistribution.__init__(self) self.location = 0.0 self.scale = 1.0 self.type = 'Logistic' self.disttype = 'Continuous' self.hasInfiniteBound = True self.compatibleQuadrature.append('CDF') self.preferredQuadrature = 'CDF' self.preferredPolynomials = 'CDF' def _localSetState(self,pdict): """ Set the pickling state (local) @ In, pdict, dict, the namespace state @ Out, None """ self.location = pdict.pop('location') self.scale = pdict.pop('scale' ) def getCrowDistDict(self): """ Returns a dictionary of the keys and values that would be used to create the distribution for a Crow input file. @ In, None @ Out, retDict, dict, the dictionary of crow distributions """ retDict = Distribution.getCrowDistDict(self) retDict['scale'] = self.scale retDict['location'] = self.location return retDict def _handleInput(self, paramInput): """ Function to handle the common parts of the distribution parameter input. @ In, paramInput, ParameterInput, the already parsed input. @ Out, None """ BoostDistribution._handleInput(self, paramInput) locationFind = paramInput.findFirst('location') if locationFind != None: self.location = locationFind.value else: self.raiseAnError(IOError,'location value needed for Logistic distribution') scaleFind = paramInput.findFirst('scale') if scaleFind != None: self.scale = scaleFind.value else: self.raiseAnError(IOError,'scale value needed for Logistic distribution') self.initializeDistribution() def getInitParams(self): """ Function to get the initial values of the input parameters that belong to this class @ In, None @ Out, paramDict, dict, dictionary containing the parameter names as keys and each parameter's initial value as the dictionary values """ paramDict = BoostDistribution.getInitParams(self) paramDict['location'] = self.location paramDict['scale' ] = self.scale return paramDict def initializeDistribution(self): """ Method to initialize the distribution @ In, None @ Out, None """ if self.lowerBoundUsed == False and self.upperBoundUsed == False: self._distribution = distribution1D.BasicLogisticDistribution(self.location,self.scale) else: if self.lowerBoundUsed == False: a = -sys.float_info.max else: a = self.lowerBound if self.upperBoundUsed == False: b = sys.float_info.max else: b = self.upperBound self._distribution = distribution1D.BasicLogisticDistribution(self.location,self.scale,a,b) DistributionsCollection.addSub(Logistic.getInputSpecification()) class Laplace(BoostDistribution): """ Laplace univariate distribution """ @classmethod def getInputSpecification(cls): """ Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for which we are retrieving the specification @ Out, inputSpecification, InputData.ParameterInput, class to use for specifying input of cls. """ inputSpecification = super(Laplace, cls).getInputSpecification() inputSpecification.addSub(InputData.parameterInputFactory("location", contentType=InputData.FloatType)) inputSpecification.addSub(InputData.parameterInputFactory("scale", contentType=InputData.FloatType)) return inputSpecification def __init__(self): """ Constructor @ In, None @ Out, None """ BoostDistribution.__init__(self) self.location = 0.0 self.scale = 1.0 self.type = 'Laplace' self.disttype = 'Continuous' self.hasInfiniteBound = True self.compatibleQuadrature.append('CDF') self.preferredQuadrature = 'CDF' self.preferredPolynomials = 'CDF' def _localSetState(self,pdict): """ Set the pickling state (local) @ In, pdict, dict, the namespace state @ Out, None """ self.location = pdict.pop('location') self.scale = pdict.pop('scale' ) def getCrowDistDict(self): """ Returns a dictionary of the keys and values that would be used to create the distribution for a Crow input file. @ In, None @ Out, retDict, dict, the dictionary of crow distributions """ retDict = Distribution.getCrowDistDict(self) retDict['scale'] = self.scale retDict['location'] = self.location return retDict def _handleInput(self, paramInput): """ Function to handle the common parts of the distribution parameter input. @ In, paramInput, ParameterInput, the already parsed input. @ Out, None """ BoostDistribution._handleInput(self, paramInput) locationFind = paramInput.findFirst('location') if locationFind != None: self.location = locationFind.value else: self.raiseAnError(IOError,'location value needed for Laplace distribution') scaleFind = paramInput.findFirst('scale') if scaleFind != None: self.scale = scaleFind.value else: self.raiseAnError(IOError,'scale value needed for Laplace distribution') self.initializeDistribution() def getInitParams(self): """ Function to get the initial values of the input parameters that belong to this
0. 0. 120.] [ 0. 0. 135.]] """ rot = R.from_rotvec(rotvec, degrees=degrees) return self.rotate(rot, anchor=anchor, start=start) def rotate_from_euler(self, angle, seq, anchor=None, start="auto", degrees=True): """Rotates object using Euler angle input. Terminology for move/rotate methods: - 'path' refers to `position` and `orientation` of an object. - When an input is just a single operation (e.g. one displacement vector or one angle) we call it 'scalar input'. When it is an array_like of multiple scalars, we refer to it as 'vector input'. General move/rotate behavior: - Scalar input is applied to the whole object path, starting with path index `start`. - Vector input of length n applies the individual n operations to n object path entries, starting with path index `start`. - When an input extends beyond the object path, the object path will be padded by its edge-entries before the operation is applied. - By default (`start='auto'`) the index is set to `start=0` for scalar input [=move whole object path], and to `start=len(object path)` for vector input [=append to existing object path]. Parameters ---------- angle: int, float or array_like with shape (n,) Angle(s) of rotation in units of [deg] (by default). seq : string Specifies sequence of axes for rotations. Up to 3 characters belonging to the set {'X', 'Y', 'Z'} for intrinsic rotations, or {'x', 'y', 'z'} for extrinsic rotations. Extrinsic and intrinsic rotations cannot be mixed in one function call. anchor: `None`, `0` or array_like with shape (3,) or (n,3), default=`None` The axis of rotation passes through the anchor point given in units of [mm]. By default (`anchor=None`) the object will rotate about its own center. `anchor=0` rotates the object about the origin `(0,0,0)`. start: int or str, default=`'auto'` Starting index when applying operations. See 'General move/rotate behavior' above for details. degrees: bool, default=`True` Interpret input in units of [deg] or [rad]. Returns ------- self: Magpylib object Examples -------- Rotate an object about the origin: >>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1,0,0)) >>> sens.rotate_from_euler(45, 'z', anchor=0) Sensor... >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.] Rotate the object about itself: >>> sens.rotate_from_euler(45, 'z') Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.] Create a rotation path by rotating in several steps about an anchor: >>> sens.rotate_from_euler((15,30,45), 'z', anchor=(0,0,0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]] """ rot = R.from_euler(seq, angle, degrees=degrees) return self.rotate(rot, anchor=anchor, start=start) def rotate_from_matrix(self, matrix, anchor=None, start="auto"): """Rotates object using matrix input. Terminology for move/rotate methods: - 'path' refers to `position` and `orientation` of an object. - When an input is just a single operation (e.g. one displacement vector or one angle) we call it 'scalar input'. When it is an array_like of multiple scalars, we refer to it as 'vector input'. General move/rotate behavior: - Scalar input is applied to the whole object path, starting with path index `start`. - Vector input of length n applies the individual n operations to n object path entries, starting with path index `start`. - When an input extends beyond the object path, the object path will be padded by its edge-entries before the operation is applied. - By default (`start='auto'`) the index is set to `start=0` for scalar input [=move whole object path], and to `start=len(object path)` for vector input [=append to existing object path]. Parameters ---------- matrix : array_like, shape (n,3,3) or (3,3) Rotation input. See scipy.spatial.transform.Rotation for details. anchor: `None`, `0` or array_like with shape (3,) or (n,3), default=`None` The axis of rotation passes through the anchor point given in units of [mm]. By default (`anchor=None`) the object will rotate about its own center. `anchor=0` rotates the object about the origin `(0,0,0)`. start: int or str, default=`'auto'` Starting index when applying operations. See 'General move/rotate behavior' above for details. Returns ------- self: Magpylib object Examples -------- Rotate an object about the origin: >>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1,0,0)) >>> sens.rotate_from_matrix([(0,-1,0),(1,0,0),(0,0,1)], anchor=0) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.] Rotate the object about itself: >>> sens.rotate_from_matrix([(0,-1,0),(1,0,0),(0,0,1)]) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 180.] """ rot = R.from_matrix(matrix) return self.rotate(rot, anchor=anchor, start=start) def rotate_from_mrp(self, mrp, anchor=None, start="auto"): """Rotates object using Modified Rodrigues Parameters (MRPs) input. Terminology for move/rotate methods: - 'path' refers to `position` and `orientation` of an object. - When an input is just a single operation (e.g. one displacement vector or one angle) we call it 'scalar input'. When it is an array_like of multiple scalars, we refer to it as 'vector input'. General move/rotate behavior: - Scalar input is applied to the whole object path, starting with path index `start`. - Vector input of length n applies the individual n operations to n object path entries, starting with path index `start`. - When an input extends beyond the object path, the object path will be padded by its edge-entries before the operation is applied. - By default (`start='auto'`) the index is set to `start=0` for scalar input [=move whole object path], and to `start=len(object path)` for vector input [=append to existing object path]. Parameters ---------- mrp : array_like, shape (n,3) or (3,) Rotation input. See scipy Rotation package for details on Modified Rodrigues Parameters (MRPs). anchor: `None`, `0` or array_like with shape (3,) or (n,3), default=`None` The axis of rotation passes through the anchor point given in units of [mm]. By default (`anchor=None`) the object will rotate about its own center. `anchor=0` rotates the object about the origin `(0,0,0)`. start: int or str, default=`'auto'` Starting index when applying operations. See 'General move/rotate behavior' above for details. Returns ------- self: Magpylib object Examples -------- Rotate an object about the origin: >>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1,0,0)) >>> sens.rotate_from_mrp((0,0,1), anchor=0) Sensor(id=...) >>> print(sens.position) [-1. 0. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 180.] Rotate the object about itself: >>> sens.rotate_from_matrix([(0,-1,0),(1,0,0),(0,0,1)]) Sensor(id=...) >>> print(sens.position) [-1. 0. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. -90.] """ rot = R.from_mrp(mrp) return self.rotate(rot, anchor=anchor, start=start) def rotate_from_quat(self, quat, anchor=None, start="auto"): """Rotates object using quaternion input. Terminology for move/rotate methods: - 'path' refers to `position` and `orientation` of an object. - When an input is just a single operation (e.g. one displacement vector or one angle) we call it 'scalar input'. When it is an array_like of multiple scalars, we refer to it as 'vector input'. General move/rotate behavior: - Scalar input is applied to the whole object path, starting with path index `start`. - Vector input of length n applies the individual n operations to n object path entries, starting with path index `start`. - When an input extends beyond the object path, the object path will be padded by its edge-entries before the operation is applied. - By default (`start='auto'`) the index is set to `start=0` for scalar input [=move whole object path], and to `start=len(object path)` for vector input [=append to existing object path]. Parameters ---------- quat : array_like, shape (n,4) or (4,) Rotation input in quaternion form. anchor: `None`, `0` or array_like with shape (3,) or (n,3), default=`None` The axis of rotation passes through the anchor point given in units of [mm]. By default (`anchor=None`) the object will rotate about its own center. `anchor=0` rotates the object about the origin `(0,0,0)`. start: int or str, default=`'auto'` Starting index when applying operations. See 'General move/rotate behavior' above for details. Returns ------- self: Magpylib object Examples -------- Rotate an object about the origin: >>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1,0,0)) >>> sens.rotate_from_quat((0,0,1,1), anchor=0) Sensor(id=...) >>> print(sens.position) [0. 1. 0.]
and %i-%i"%(node,quad_verts[0], # node,quad_verts[2]) # first figure out the indices for everyone: # the edges that get removed entirely: # names are oriented with the first node of the pointy end up dead_edge_top = self.find_edge( [node,quad_verts[0]] ) dead_edge_bot = self.find_edge( [node,quad_verts[2]] ) merge_edge_left = self.find_edge( [node,quad_verts[1]] ) merge_edge_right = self.find_edge( [node,quad_verts[3]] ) # order cells such that cell i is node,quad_verts[i],quad_verts[i+1] ordered_cells = -1*ones((4,),int32) for i in range(4): for j in range(4): # is cells[j] the ordered cell i? if all( sort(self.cells[ cells[j] ]) == sort([node,quad_verts[i],quad_verts[(i+1)%4]])): ordered_cells[i] = cells[j] break if any(ordered_cells) < 0: raise "Failed to reorder the cells CCW" # rename for better visuals... cell_nw,cell_sw,cell_se,cell_ne = ordered_cells # record that we're changing stuff: self.changed_cells.append(cell_nw) self.changed_cells.append(cell_ne) self.changed_cells.append(cell_se) self.changed_cells.append(cell_sw) # start combining cells: ### Combine northwest and northeast: north_points = setdiff1d(concatenate( (self.cells[cell_nw],self.cells[cell_ne]) ),[node]) south_points = setdiff1d(concatenate( (self.cells[cell_sw],self.cells[cell_se]) ),[node]) cell_n = cell_nw # new cell takes on northwest's index self.cells[cell_n,:] = north_points cell_s = cell_sw self.cells[cell_s,:] = south_points # mark the other cells as deleted self.cells[cell_ne,:] = -1 self.cells[cell_se,:] = -1 ## Edges self.edges[dead_edge_top] = -1 self.edges[dead_edge_bot] = -1 self.edges[merge_edge_right] = -1 # and the one that gets rewritten to span across the quad self.edges[merge_edge_left,0] = quad_verts[1] self.edges[merge_edge_left,1] = quad_verts[3] # leave the marker as is self.edges[merge_edge_left,3] = cell_n self.edges[merge_edge_left,4] = cell_s # and surrounding edges - the diagonals northeast and southeast # have to have one of their cells rewritten: northeast_edge = self.find_edge( [quad_verts[3],quad_verts[0]] ) southeast_edge = self.find_edge( [quad_verts[2],quad_verts[3]] ) if self.edges[northeast_edge,3] == cell_ne: self.edges[northeast_edge,3] = cell_n if self.edges[northeast_edge,4] == cell_ne: self.edges[northeast_edge,4] = cell_n if self.edges[southeast_edge,3] == cell_se: self.edges[southeast_edge,3] = cell_s if self.edges[southeast_edge,4] == cell_se: self.edges[southeast_edge,4] = cell_s # and now fixup any stuff that we destroyed along the way: if self._pnt2cells: del self._pnt2cells[node] # this node is totally disowned for new_point in quad_verts: set_of_cells = self._pnt2cells[new_point] if cell_ne in set_of_cells: set_of_cells.remove(cell_ne) set_of_cells.add(cell_n) if cell_se in set_of_cells: set_of_cells.remove(cell_se) set_of_cells.add(cell_s) if self._vcenters: self._vcenters = None # lazy # fix pnts2edge: for other_point in quad_verts: nodes = (node,other_point) if nodes[0] > nodes[1]: nodes = (other_point,node) del self.pnts2edge[nodes] # and insert the new edge: nodes = (quad_verts[1],quad_verts[3]) if nodes[0] > nodes[1]: nodes = (quad_verts[3],quad_verts[1]) self.pnts2edge[nodes] = merge_edge_left # end fixing pnts2edge if verbose: #subplot(212) #cla() print("fix_quad: node %d, create cells %d %d"%(node,cell_n,cell_s)) # self.plot_cells([cell_n,cell_s]) self.quads_merged += 1 return True ### Mesh quality analyses: def plot_clearance_hist(self,**plotargs): if 'bins' not in plotargs: plotargs['bins'] = 200 if 'log' not in plotargs: plotargs['log'] = True clearances = self.vor_clearances() clearances = clip(clearances,-100,200) hist(clearances,**plotargs) lims = list(axis()) lims[2] = 0.1 axis(lims) def vor_clearances(self): # return, for each cell, the minimum distance # between the cell's voronoi center and an edge. # negative means it does not satisfy the ortho. # condition return self.fast_vor_clearances() # old, iterative code vcenters = self.vcenters() clearances = nan*ones( (self.Ncells()), float64 ) for cell_i in range(self.Ncells()): if cell_i%300==0: print("%g%%"%( (100.0*cell_i)/self.Ncells() )) vor = vcenters[cell_i] min_dist = inf for edge_i in range(3): pntA = self.points[ self.cells[cell_i,edge_i], :2 ] pntB = self.points[ self.cells[cell_i,(edge_i+1)%3] , :2] pntC = self.points[ self.cells[cell_i,(edge_i+2)%3] , :2] # get unit vector along this edge: AV = vor - pntA AC = pntC - pntA # to figure out which side of the edge we're on AB_unit = (pntB - pntA) / norm(pntB-pntA) # project VA, CA onto AB, subtract to get perpendicular component AV_par = AB_unit*dot(AV,AB_unit) AV_perp = AV - AB_unit*dot(AV,AB_unit) AC_perp = AC - AB_unit*dot(AC,AB_unit) dist = norm(AV_perp) if dot(AV_perp,AC_perp) < 0: # lie on opposite sides of AB dist = -dist if dist < min_dist: min_dist = dist if 0: # debugging: self.plot_cells([cell_i],label_nodes=False) # interesting points: pnts = array([vor,pntA,pntB,pntC]) plot(pnts[:,0],pnts[:,1],'ro') annotate('vor',vor) annotate('A',pntA) annotate('B',pntB) annotate('C',pntC) # this one is okay... vec = array([pntA,pntA+AV]) plot(vec[:,0],vec[:,1],'r--') # the parallel projection: vec = array([pntA,pntA+AV_par]) plot(vec[:,0],vec[:,1],'g--') # should be the perpendicular: vec = array([vor,vor-AV_perp]) plot(vec[:,0],vec[:,1],'r--') print("Vor clearance: ",dist) raise StopIteration clearances[cell_i] = min_dist return clearances def fast_vor_clearances(self): # return, for each cell, the minimum distance # between the cell's voronoi center and an edge. # negative means it does not satisfy the ortho. # condition vor = self.vcenters() clearances = inf*ones( (self.Ncells()), float64 ) def rowdot(x,y): return sum(x*y,axis=1) def rownorm(v): return sqrt( v[:,0]**2 + v[:,1]**2) for edge_i in range(3): pntA = self.points[ self.cells[:,edge_i] ] pntB = self.points[ self.cells[:,(edge_i+1)%3]] pntC = self.points[ self.cells[:,(edge_i+2)%3]] # get unit vector along this edge: AV = vor - pntA AC = pntC - pntA # to figure out which side of the edge we're on AB = pntB - pntA AB_unit = AB / (rownorm(AB)[:,newaxis] ) # project VA, CA onto AB, subtract to get perpendicular component # is dot going to do the right thing?? # AB_unit is [n,2], AV is [n,2] # want to dot each pair of rows to get a column vector # dot gets too weird - just write out the row-dot-product AV_par = AB_unit*(rowdot(AV,AB_unit)[:,newaxis]) AV_perp = AV - AB_unit*(rowdot(AV,AB_unit)[:,newaxis]) AC_perp = AC - AB_unit*(rowdot(AC,AB_unit)[:,newaxis]) dist = rownorm(AV_perp) # negate distances that are on the opposite side from the # third node: dist = where( rowdot(AV_perp,AC_perp) < 0, -dist, dist) # store min distances clearances = where(dist < clearances,dist,clearances) if 0: # debugging: self.plot_cells([cell_i],label_nodes=False) # interesting points: pnts = array([vor,pntA,pntB,pntC]) plot(pnts[:,0],pnts[:,1],'ro') annotate('vor',vor) annotate('A',pntA) annotate('B',pntB) annotate('C',pntC) # this one is okay... vec = array([pntA,pntA+AV]) plot(vec[:,0],vec[:,1],'r--') # the parallel projection: vec = array([pntA,pntA+AV_par]) plot(vec[:,0],vec[:,1],'g--') # should be the perpendicular: vec = array([vor,vor-AV_perp]) plot(vec[:,0],vec[:,1],'r--') print("Vor clearance: ",dist) raise StopIteration return clearances def edge_clearances(self,include_boundary=True): """ for each edge return the signed distance between their voronoi centers """ vor = self.vcenters() clearances = zeros( (self.edges.shape[0]), float64 ) def rowdot(x,y): return sum(x*y,axis=1) def rownorm(v): return sqrt( v[:,0]**2 + v[:,1]**2) for edge_i in range(3): pntA = self.points[ self.cells[:,edge_i], :2 ] pntB = self.points[ self.cells[:,(edge_i+1)%3] , :2] pntC = self.points[ self.cells[:,(edge_i+2)%3] , :2] # get unit vector along this edge: AV = vor - pntA AC = pntC - pntA # to figure out which side of the edge we're on AB = pntB - pntA AB_unit = AB / (rownorm(AB)[:,newaxis] ) # project VA, CA onto AB, subtract to get perpendicular component # is dot going to do the right thing?? # AB_unit is [n,2], AV is [n,2] # want to dot each pair of rows to get a column vector # dot gets too weird - just write out the row-dot-product AV_par = AB_unit*(rowdot(AV,AB_unit)[:,newaxis]) AV_perp = AV - AB_unit*(rowdot(AV,AB_unit)[:,newaxis]) AC_perp = AC - AB_unit*(rowdot(AC,AB_unit)[:,newaxis]) dist = rownorm(AV_perp) # negate distances that are on the opposite side from the # third node: dist = where( rowdot(AV_perp,AC_perp) < 0, -dist, dist) for cell_i in range(self.cells.shape[0]): nodeA = self.cells[cell_i,edge_i] nodeB = self.cells[cell_i,(edge_i+1)%3] ABedge = self.find_edge( (nodeA,nodeB) ) clearances[ABedge] += dist[cell_i] if not include_boundary: internal = self.edges[:,4] >= 0 clearances = clearances[internal] return clearances ### Fix cells by moving nodes around ### def can_node_be_repositioned(self,free_node,region_steps=3): """ Returns a polygon enclosing valid locations for the node if it exists, otherwise return False region_steps: how finely to discretize the valid regions """ is_internal = (self.boundary_angle(free_node) == 0.0) if is_internal: # keeps the node in a region where it doesn't change # the boundary shape too much intersection = None else: intersection = self.boundary_envelope(free_node) for nbr_cell in self.pnt2cells(free_node): # rotate the node list so the free node is first nodes = self.cells[nbr_cell] bring_to_front = find(nodes==free_node)[0] nodes = nodes[ (arange(3)+bring_to_front)%3 ] # now nodes[0] is our free node... points = self.points[ nodes, :2] free_bounds = free_node_bounds_fine(points, max_angle=self.max_angle, region_steps=region_steps) geom = geometry.Polygon( free_bounds ) # geoms.append(geom) if intersection is None: intersection = geom else: intersection = intersection.intersection(geom) if intersection.area == 0.0: return False return intersection def try_to_fix_by_nudging(self,bad_cell,region_steps=3): """ Look for ways to fix a cell by nudging it's vertices. """ for node in self.cells[bad_cell]: # only move internal nodes for now... repos = self.can_node_be_repositioned(node,region_steps=region_steps) if repos: new_point
<reponame>CQ2SPARQLOWL/Benchmark<gh_stars>1-10 import spacy import sys import re # corpus_path = sys.argv[1] corpus_path = "/Users/dawidwisniewski/Desktop/cqs.txt" nlp = spacy.load('en_core_web_lg') def mark_chunk(cq, spans, chunktype, offset, counter): for (start, end) in spans: # for each span of EC/PC candidate cq = cq[:start - offset] + chunktype + str(counter) +\ cq[end - offset:] # substitute that candidate with EC/PC marker offset += (end - start) - len(chunktype) - 1 # check by how much the total length of CQ changed return cq, offset def extract_EC_chunks(cq): """ Find EC chunks and replace their occurences with EC tags """ def _get_EC_span_reject_wh_starters(chunk): """ By default, SpaCy treats question words (wh- pronouns starting questions: where, what,...) as nouns, so often if questions starts with wh- pronoun + noun (like: What software is the best?) the whole "what software" is interpreted as EC chunk - this function tries to fix that issue by omitting wh- word if EC candidate consists of multiple tokens, and first token in question is wh- word. The same issue occurs for "How" starter. Moreover, chunks extracted with SpaCy enclose words like 'any', 'some' which are important for us, so they shouldn't be substituted with 'EC' marker. Thus we remove such words if they prepend the EC. The result is returned as the span - the position of beginning of the fixed EC and position of end. """ if (len(chunk) > 1 and (chunk[0].text.lower().startswith("wh")) or (chunk[0].text.lower() == 'how')): chunk = chunk[1:] if chunk[0].text.lower() in ['any', 'some', 'many', 'well', 'its']: chunk = chunk[1:] return (chunk.start_char, chunk.end_char) doc = nlp(cq) # thins classified as ECs which shouldn't be interpreted that way rejecting_ec = ["what", "which", "when", "where", "who", "type", "types", "kinds", "kind", "category", "categories", "difference", "differences", "extent", "i", "we", "respect", "there", "not", "the main types", "the possible types", "the types", "the difference", "the differences", "the main categories"] counter = 1 # counter indicating current chunk id (EC1, EC2, ...) offset = 0 # if we replace for example "Weka" with 'EC1' then the new CQ will be shorter by one char the offset remembers by how much we have shortened the current CQ with EC markers, so the new substitutions can be applied in correct places. # we decided to treat qualities defined as adjectives in: How + Quality(adjective) + Verb as EC if (doc[0].text.lower() == 'how' and doc[1].pos_ == 'ADJ' and doc[2].pos_ == 'VERB'): start = doc[1].idx # mark where quality starts end = start + len(doc[1]) # mark where quality ends cq, offset = mark_chunk(cq, [(start, end)], "EC", offset, counter) # substitute quality with EC identifier counter += 1 # the next EC chunk should have a new, bigger identifier, for example EC2 for chunk in doc.noun_chunks: # for each EC chunk candidate detected (start, end) = _get_EC_span_reject_wh_starters(chunk) # check where chunk begins and ends ec = cq[start - offset:end - offset] # extract text of potential EC, apply offsets if ec.lower() in rejecting_ec: # if it should be rejected - do nothing continue if "the thing" in ec and end - start > len("the thing"): cq = cq[:start - offset] + "EC" + str(counter) +\ " EC" + str(counter + 1) + cq[end - offset:] counter += 2 offset += (end - start) - 7 else: cq, offset = mark_chunk(cq, [(start, end)], "EC", offset, counter) counter += 1 if (doc[-2].pos_ == 'VERB' and doc[-3].text in ['are', 'is', 'were', 'was'] and doc[-1].text == '?') or (doc[-2].pos_ in ['ADJ', 'ADV'] and doc[-1].text == '?'): # if CQ ends with are/is/were/was + VERB + ? or the last token is ADJective or ADVerb, treat the # verb / adverb / adjective as EC # Which animals are endangered -> endangered is EC # Which animals are quick -> quick is EC if doc[-2].text.lower() not in rejecting_ec: start = doc[-2].idx end = start + len(doc[-2]) cq, offset = mark_chunk( cq, [(start, end)], "EC", offset, counter) counter += 1 return cq def get_PCs_as_spans(cq): def _is_auxilary(token, chunk_token_ids): """ Check if given token is an auxilary verb of detected PC. The auxilary verb can be in a different place than the main part of the PC, so pos-tag-sequence based rules don't work here. For example in "What system does Weka require?" - the main part of PC is the word 'required'. The auxilary verb 'does' is separeted from the main part by 'Weka' noun. Thus dependency tree is used to identify auxilaries. """ if (token.head.i in chunk_token_ids and # if dep-tree current token's parent (head) is somewhere inside the main part of PC represented as chunk_token_ids (sequence of numeric token identifiers) token.dep_ == 'aux' and # if the dep-tree label on the edge between some word from main part of PC and current token is AUX (auxilary) token.i not in chunk_token_ids): # if token is outside of detected main part of PC return True # yep, it's auxilary else: return False def _get_span(group, doc): id_tags = group.split(",") ids = [int(id_tag.split("::")[0]) for id_tag in id_tags] aux = None for token in doc: if _is_auxilary(token, ids): aux = token return (doc[ids[0]].idx, doc[ids[-1]].idx + len(doc[ids[-1]]), aux) def _reject_subspans(spans): """ Given list of (chunk begin index, chunk end index) spans, return only those spans that aren't subspans of any other span. For instance form list [(1,10), (2,5)], the second span will be rejected because it is a subspan of the first one. """ filtered = [] for i, span in enumerate(spans): subspan = False for j, other in enumerate(spans): if i == j: continue if span[0] >= other[0] and span[1] <= other[1]: subspan = True break if subspan is False: filtered.append(span) return filtered doc = nlp(cq) """ Transform CQ into a form of POS-tags with token sequence identifier. Each token is described with "{ID}::{POS_TAG}". Tokens are separated with "," Having that form, we can extract longest sequences of expected pos-tags using regexes. The extracted parts can be explored to collect identifiers of tokens, so we know where they are located in text. Ex: "Kate owns a cat" should be translated into: "1::NOUN,2::VERB,3::DET,4::NOUN" """ pos_text = ",".join( ["{id}::{pos}".format(id=id, pos=t.pos_) for id, t in enumerate(doc)]) regexes = [ # rules describing PCs r"([0-9]+::(PART|VERB),?)*([0-9]+::VERB)", r"([0-9]+::(PART|VERB),?)+([0-9]+::AD(J|V),)+([0-9]+::ADP)", r"([0-9]+::(PART|VERB),?)+([0-9]+::ADP)", ] spans = [] # list of beginnings and endings of each chunk for regex in regexes: # try to extract chunks with regexes for m in re.finditer(regex, pos_text): spans.append(_get_span(m.group(), doc)) # get chunk begin and end if matched spans = _reject_subspans(spans) # reject subspans return spans def extract_PC_chunks(cq): rejecting_pc = ['is', '’s', 'are', 'was', 'do', 'does', 'did', 'were', 'have', 'had', 'can', 'could', 'categorise', 'regarding', 'is of', 'are of', 'are in', 'given', 'is there'] offset = 0 counter = 1 for begin, end, aux in get_PCs_as_spans(cq): if cq[begin - offset:end - offset].lower() in rejecting_pc: continue spans = [(begin, end)] if aux: spans.insert(0, (aux.idx, aux.idx + len(aux))) cq, offset = mark_chunk(cq, spans, "PC", offset, counter) counter += 1 return cq def mark_placeholders(cq): """ In our paper we stated that if a CQ is dematerialized (= it contains placeholders represented with [] that can be filled in various ways), the whole dematerialized placeholder should be treated as an EC. Thus we transform the whole placholder (everything in []) into the string 'the thing' (*). (*) One can imagine a nicer way of solving it, but this approach works """ return re.sub(r'\[.*?\]', 'the thing', cq) def clean_cq(cq): normalizers = { "[-\"\'”]": "", # remove all dashes and quotations "\(.*?\)": "", # remove all ( ) "[ \t]+": " ", # remove all multiplied whitespaces " \?": "?" # remove whitespaces before ? } for regex in normalizers: cq = re.sub(regex, normalizers[regex], cq) return cq patterns = set() pattern_candidates = set() with open(corpus_path, 'r') as f: for line in f: line = line.split("\t")[0].strip() cq = clean_cq(line.strip()) pattern = mark_placeholders(cq) pattern = extract_EC_chunks(pattern) pattern = extract_PC_chunks(pattern) if '[' in cq and ']' in cq: patterns.add(pattern) elif pattern in pattern_candidates: patterns.add(pattern)
from .repo import get_local_repo, get_remote_repo, ProcessError, DEFAULT_BRANCH from .utils import AsyncResult, with_lock, get_secure_random_string from ConfigParser import RawConfigParser from datetime import datetime from subprocess import call from threading import Semaphore from urllib2 import urlopen import json import os import platform import sys # TODO: replace sys.exit() with exceptions def batch_create_links(root, links): if not links: return script = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'utilscripts', 'batch-create-links.py') params = [] for link_name, target in links.items(): path = os.path.join(root, link_name) get_or_mkdir(os.path.dirname(path)) params.append(path) params.append(target) call([sys.executable, script] + params) def remove_link(path): if os.path.isdir(path) and os.path.islink(path) and platform.system() == 'Windows': os.rmdir(path) else: os.remove(path) def get_mapped_branches(project): return mapped_branches(*project.branches()) def mapped_branches(active_branch, branches): if active_branch is None: pass elif active_branch == DEFAULT_BRANCH: active_branch = 'master' elif '___' in active_branch: active_branch = active_branch.split('___')[0] mapped = {'master': DEFAULT_BRANCH} for name in branches: if '___' in name: real_name, internal_name = name.split('___') mapped[real_name] = internal_name return active_branch, mapped def get_project_root(start=os.getcwdu()): root = None next = start while True: if get_local_repo(next) is not None: root = next if next == os.path.dirname(next): break next = os.path.dirname(next) if root is None: raise ValueError('No repository found at this location!') return root def _normalize_link(repo_name, target): if target.startswith('./') or target == '.': return repo_name + target[1:] return target def load_repo_config(root): config = RawConfigParser() config.read(os.path.join(root, '.deps')) repo_name = os.path.basename(root) package_name = repo_name.rsplit('-', 1)[-1] repos = config.items('repos') if config.has_section('repos') else () links = {name.replace('@', package_name): _normalize_link(repo_name, target).replace('@', package_name) for name, target in (config.items('links') if config.has_section('links') else ())} dependencies = [] if config.has_option('general', 'dependencies'): dependencies = config.get('general', 'dependencies').split() repos = dict(repos) for name, path in repos.items(): if not '://' in path and not path.startswith('['): repos[name] = os.path.abspath(path) return {'repos': repos, 'links': links, 'dependencies': dependencies} def get_or_mkdir(path): if path and not os.path.exists(path): os.makedirs(path) return path def get_backups_root(root): path = os.path.join(root, 'repos-backups-please-integrate-any-missing-' 'changes-and-delete-this-folder') get_or_mkdir(path) return path def get_dependencies_root(root): return os.path.join(root, '.repos') def collect_links(base_root): for root, dirs, files in os.walk(base_root, followlinks=True): for name in dirs[:]: path = os.path.join(root, name) if os.path.islink(path): yield path[len(base_root) + 1:].replace('\\', '/') continue if name in ('.hg', '.git', '.svn', '.repos'): dirs.remove(name) for name in files: path = os.path.join(root, name) if os.path.islink(path): yield path[len(base_root) + 1:].replace('\\', '/') def get_loaded_dependencies(root): deps_root = get_dependencies_root(root) dependencies = {} dependencies['repos'] = repos = {} if os.path.exists(deps_root): for name in os.listdir(deps_root): # Ignore .DS_Store and other hidden files if name.startswith('.'): continue path = os.path.join(deps_root, name) repo = get_local_repo(path) if repo is None: raise ValueError('No repo "%s" found at path %s' % (name, path)) repos[name] = repo.get_source() dependencies['links'] = links = {} deps_base = os.path.abspath(os.path.basename(deps_root)).replace('\\', '/') + '/' for name in collect_links(root): path = os.path.join(root, name) path = os.path.abspath(os.path.join(os.path.dirname(path), os.readlink(path))) path = path.replace('\\', '/') if not path.startswith(deps_base) or len(path) <= len(deps_base): continue links[name] = path[len(deps_base):] return dependencies def clone_repo(root, source, destination, revision=None, date=None, branch=None): destination = os.path.abspath(destination) get_or_mkdir(os.path.dirname(destination)) if root and try_restore_from_backups(root, os.path.basename(destination), source): local_repo = get_local_repo(destination) output = 'Restored from backup\n' + local_repo.pull() else: output = get_remote_repo(source).clone(destination) local_repo = get_local_repo(destination) if date: assert not revision assert not branch if branch: active_branch, branches = local_repo.branches() if active_branch != branch: if branch in branches: output += local_repo.update(branch) if revision and revision != branch: output += local_repo.merge(revision) else: if revision and active_branch != revision: if revision in branches: output += local_repo.update(revision) elif active_branch != DEFAULT_BRANCH: output += local_repo.update(DEFAULT_BRANCH) output += local_repo.create_branch(branch) elif revision and revision != branch: output += local_repo.merge(revision) else: output += local_repo.update(revision=revision, date=date) return 'Cloning %s\n%s' % (source, output) def collect_repos(root=None): if root is None: root = get_project_root() deps_root = get_dependencies_root(root) loaded_repos = get_loaded_dependencies(root)['repos'] repos = {} repos['.'] = get_local_repo(root) for name in loaded_repos: path = os.path.join(deps_root, name) repos[name] = get_local_repo(path) return repos def get_humane_repo_name(repos, name): if name in repos: return name matches = set() for repo_name in repos: parts = {part for subpart in repo_name.split('-') for part in subpart.split('_')} for part in parts: if part.startswith(name): matches.add(repo_name) if len(matches) == 1: return matches.pop() elif len(matches) > 1: raise ValueError('Multiple repos matched "%s": %s' % (name, ', '.join(matches))) raise ValueError('Couldn\'t find any repo matching the name "%s"' % name) def filter_repos_by_name(repos, repo_names): names = {get_humane_repo_name(repos, name) for name in repo_names} return {name: repos[name] for name in names} def run_in_all_repos(action, parallel=True, max_parallel=None, repo_names=None, kwargs=None, project_kwargs=None, skip_project=False): if kwargs is None: kwargs = {} if project_kwargs is None: project_kwargs = {} project_kwargs = dict(kwargs, **project_kwargs) repos = collect_repos() if repo_names is not None: repos = filter_repos_by_name(repos, repo_names) if skip_project: repos.pop('.', None) # Rename the project repo name to something more human-readable if '.' in repos: repos['<project>'] = repos.pop('.') if not parallel: for name in sorted(repos): print('%s: %s' % (action.replace('_', ' ').capitalize(), name)) kw = project_kwargs if name == '<project>' else kwargs getattr(repos[name], action)(**kw) return threads = {} if max_parallel >= 1: lock = Semaphore(max_parallel) for name in repos: func = getattr(repos[name], action) if max_parallel >= 1: func = with_lock(func, lock) kw = project_kwargs if name == '<project>' else kwargs threads[name] = AsyncResult(func, kwargs=kw) errors = [] for name in sorted(threads): result = threads[name].do() if isinstance(result, ProcessError): errors.append(name) if result and (not isinstance(result, basestring) or result.strip()): print('%s: %s' % (action.replace('_', ' ').capitalize(), name)) print(result) if errors: sys.stderr.write('\n' 'Errors happened for the following repos: %s\n' 'Scroll upwards to see the errors. ;)\n' % ', '.join(errors)) sys.exit(1) def fetch_repo(name, root): if name is None: name = '<project>' repo = get_local_repo(root) result = repo.fetch() if result and result.strip(): return 'Fetching %s\n%s' % (name, result) return '' def pull_repo(name, root): if name is None: name = '<project>' repo = get_local_repo(root) result = repo.pull() if result and result.strip(): return 'Pulling %s\n%s' % (name, result) return '' def update_repo(name, root, revision=None, date=None): if name is None: name = '<project>' repo = get_local_repo(root) result = repo.update(revision=revision, date=date) if result and result.strip(): return 'Updating %s\n%s' % (name, result) return '' def merge_repo(name, root, revision=None): if name is None: name = '<project>' repo = get_local_repo(root) result = repo.merge(branch=revision) if result and result.strip(): return 'Merging %s\n%s' % (name, result) return '' def send_deploy_signal(deploy_url, repo_url, revisions): data = json.dumps([repo_url, revisions]) urlopen(deploy_url, data) def move_to_backups(root, name): deps_root = get_dependencies_root(root) backups_root = get_backups_root(root) backup_dir = os.path.join(backups_root, name, datetime.utcnow().isoformat().replace(':', '-')) try: os.renames(os.path.join(deps_root, name), backup_dir) except: sys.stderr.write('Error: Could not move %s. Please close ' 'any open files in that repository.\n' % name) sys.exit(1) return backup_dir def try_restore_from_backups(root, name, source=None): deps_root = get_dependencies_root(root) backups_root = os.path.join(get_backups_root(root), name) if os.path.exists(backups_root): backups = sorted(os.listdir(backups_root), reverse=True) for backup in backups: backup_dir = os.path.join(backups_root, backup) repo = get_local_repo(backup_dir) if not repo or (source and repo.get_source() != source): continue try: os.renames(backup_dir, os.path.join(deps_root, name)) except: sys.stderr.write('Error: Could not move %s. Please close ' 'any open files in that repository.\n' % name) sys.exit(1) return True return False def build_project(root, preload=None, revision=None, active_branch=None, branches=None, **kwargs): has_revision = revision is not None if not has_revision: revision = {} if branches is None: branches = get_mapped_branches(get_local_repo(root))[1] if preload is not None: kw = kwargs.copy() if has_revision: if isinstance(revision, dict): rev = revision.get('.') else: rev = (branches[revision] if revision == 'master' else '%s___%s' % (revision, branches[revision])) kw['revision'] = rev print(preload(None, root, **kw)) # Set active branch after preload call because preload might switch branches if active_branch is None: active_branch = get_mapped_branches(get_local_repo(root))[0] deps_root = get_dependencies_root(root) loaded_dependencies = get_loaded_dependencies(root) loaded_repos = loaded_dependencies['repos'] existing_links = loaded_dependencies['links'] unprocessed_repos = set(loaded_repos.keys()) unprocessed_links = set(existing_links.keys()) config = load_repo_config(root) warnings = [] try: to_load = sorted(config['repos'].items(), key=lambda x: x[0]) to_link = list(config['links'].items()) post_load = [] if to_load: get_or_mkdir(deps_root) while to_load: name, source = to_load.pop() destination = os.path.normpath(os.path.join(deps_root, name)) rev = None if has_revision: rev = (revision.get(name) if isinstance(revision, dict) else branches[revision]) if name not in loaded_repos or source != loaded_repos[name]: if name in loaded_repos: backup_dir = move_to_backups(root, name) warnings.append('\nWarning: The source location of %s has ' 'changed. Your existing repository has been ' 'moved to\n%s\n' % (name, backup_dir)) kw = kwargs if not has_revision or not isinstance(revision, dict): kw = dict(kwargs, branch=branches[active_branch]) thread = AsyncResult(clone_repo, (root, source, destination, rev), kw) post_load.insert(0, (name, source, destination, thread)) elif preload is not None: kw = kwargs.copy() if has_revision: kw['revision'] = rev thread = AsyncResult(preload, (name, destination), kw) post_load.insert(0, (name, source, destination, thread)) else: post_load.insert(0, (name, source, destination, None)) post_load = list(reversed(post_load)) while post_load: name, source, destination, thread = post_load.pop() if thread
established (not before).' choices: - 'disable' - 'enable' revoked-server-cert: type: str description: 'Action based on server certificate is revoked.' choices: - 'allow' - 'block' - 'ignore' sni-server-cert-check: type: str description: 'Check the SNI in the client hello message with the CN or SAN fields in the returned server certificate.' choices: - 'disable' - 'enable' - 'strict' status: type: str description: 'Configure protocol inspection status.' choices: - 'disable' - 'certificate-inspection' - 'deep-inspection' unsupported-ssl-cipher: type: str description: 'Action based on the SSL cipher used being unsupported.' choices: - 'allow' - 'block' unsupported-ssl-negotiation: type: str description: 'Action based on the SSL negotiation used being unsupported.' choices: - 'allow' - 'block' untrusted-server-cert: type: str description: 'Action based on server certificate is not issued by a trusted CA.' choices: - 'allow' - 'block' - 'ignore' cert-probe-failure: type: str description: 'Action based on certificate probe failure.' choices: - 'block' - 'allow' imaps: description: no description type: dict required: false suboptions: cert-validation-failure: type: str description: 'Action based on certificate validation failure.' choices: - 'allow' - 'block' - 'ignore' cert-validation-timeout: type: str description: 'Action based on certificate validation timeout.' choices: - 'allow' - 'block' - 'ignore' client-certificate: type: str description: 'Action based on received client certificate.' choices: - 'bypass' - 'inspect' - 'block' expired-server-cert: type: str description: 'Action based on server certificate is expired.' choices: - 'allow' - 'block' - 'ignore' ports: description: 'Ports to use for scanning (1 - 65535, default = 443).' type: int proxy-after-tcp-handshake: type: str description: 'Proxy traffic after the TCP 3-way handshake has been established (not before).' choices: - 'disable' - 'enable' revoked-server-cert: type: str description: 'Action based on server certificate is revoked.' choices: - 'allow' - 'block' - 'ignore' sni-server-cert-check: type: str description: 'Check the SNI in the client hello message with the CN or SAN fields in the returned server certificate.' choices: - 'disable' - 'enable' - 'strict' status: type: str description: 'Configure protocol inspection status.' choices: - 'disable' - 'deep-inspection' unsupported-ssl-cipher: type: str description: 'Action based on the SSL cipher used being unsupported.' choices: - 'allow' - 'block' unsupported-ssl-negotiation: type: str description: 'Action based on the SSL negotiation used being unsupported.' choices: - 'allow' - 'block' untrusted-server-cert: type: str description: 'Action based on server certificate is not issued by a trusted CA.' choices: - 'allow' - 'block' - 'ignore' pop3s: description: no description type: dict required: false suboptions: cert-validation-failure: type: str description: 'Action based on certificate validation failure.' choices: - 'allow' - 'block' - 'ignore' cert-validation-timeout: type: str description: 'Action based on certificate validation timeout.' choices: - 'allow' - 'block' - 'ignore' client-certificate: type: str description: 'Action based on received client certificate.' choices: - 'bypass' - 'inspect' - 'block' expired-server-cert: type: str description: 'Action based on server certificate is expired.' choices: - 'allow' - 'block' - 'ignore' ports: description: 'Ports to use for scanning (1 - 65535, default = 443).' type: int proxy-after-tcp-handshake: type: str description: 'Proxy traffic after the TCP 3-way handshake has been established (not before).' choices: - 'disable' - 'enable' revoked-server-cert: type: str description: 'Action based on server certificate is revoked.' choices: - 'allow' - 'block' - 'ignore' sni-server-cert-check: type: str description: 'Check the SNI in the client hello message with the CN or SAN fields in the returned server certificate.' choices: - 'disable' - 'enable' - 'strict' status: type: str description: 'Configure protocol inspection status.' choices: - 'disable' - 'deep-inspection' unsupported-ssl-cipher: type: str description: 'Action based on the SSL cipher used being unsupported.' choices: - 'allow' - 'block' unsupported-ssl-negotiation: type: str description: 'Action based on the SSL negotiation used being unsupported.' choices: - 'allow' - 'block' untrusted-server-cert: type: str description: 'Action based on server certificate is not issued by a trusted CA.' choices: - 'allow' - 'block' - 'ignore' smtps: description: no description type: dict required: false suboptions: cert-validation-failure: type: str description: 'Action based on certificate validation failure.' choices: - 'allow' - 'block' - 'ignore' cert-validation-timeout: type: str description: 'Action based on certificate validation timeout.' choices: - 'allow' - 'block' - 'ignore' client-certificate: type: str description: 'Action based on received client certificate.' choices: - 'bypass' - 'inspect' - 'block' expired-server-cert: type: str description: 'Action based on server certificate is expired.' choices: - 'allow' - 'block' - 'ignore' ports: description: 'Ports to use for scanning (1 - 65535, default = 443).' type: int proxy-after-tcp-handshake: type: str description: 'Proxy traffic after the TCP 3-way handshake has been established (not before).' choices: - 'disable' - 'enable' revoked-server-cert: type: str description: 'Action based on server certificate is revoked.' choices: - 'allow' - 'block' - 'ignore' sni-server-cert-check: type: str description: 'Check the SNI in the client hello message with the CN or SAN fields in the returned server certificate.' choices: - 'disable' - 'enable' - 'strict' status: type: str description: 'Configure protocol inspection status.' choices: - 'disable' - 'deep-inspection' unsupported-ssl-cipher: type: str description: 'Action based on the SSL cipher used being unsupported.' choices: - 'allow' - 'block' unsupported-ssl-negotiation: type: str description: 'Action based on the SSL negotiation used being unsupported.' choices: - 'allow' - 'block' untrusted-server-cert: type: str description: 'Action based on server certificate is not issued by a trusted CA.' choices: - 'allow' - 'block' - 'ignore' ssh: description: no description type: dict required: false suboptions: inspect-all: type: str description: 'Level of SSL inspection.' choices: - 'disable' - 'deep-inspection' ports: description: 'Ports to use for scanning (1 - 65535, default = 443).' type: int proxy-after-tcp-handshake: type: str description: 'Proxy traffic after the TCP 3-way handshake has been established (not before).' choices: - 'disable' - 'enable' ssh-algorithm: type: str description: 'Relative strength of encryption algorithms accepted during negotiation.' choices: - 'compatible' - 'high-encryption' ssh-tun-policy-check: type: str description: 'Enable/disable SSH tunnel policy check.' choices: - 'disable' - 'enable' status: type: str description: 'Configure protocol inspection status.' choices: - 'disable' - 'deep-inspection' unsupported-version: type: str description: 'Action based on SSH version being unsupported.' choices: - 'block' - 'bypass' ssl: description: no description type: dict required: false suboptions: cert-validation-failure: type: str description: 'Action based on certificate validation failure.' choices: - 'allow' - 'block' - 'ignore' cert-validation-timeout: type: str description: 'Action based on certificate validation timeout.' choices: - 'allow' - 'block' - 'ignore' client-certificate: type: str description: 'Action based on received client certificate.' choices: - 'bypass' - 'inspect' - 'block' expired-server-cert: type: str description: 'Action based on server certificate is expired.' choices: - 'allow' - 'block' - 'ignore' inspect-all: type: str description: 'Level of SSL inspection.' choices: - 'disable' - 'certificate-inspection' - 'deep-inspection' revoked-server-cert: type: str description: 'Action based on server certificate is revoked.' choices: - 'allow' - 'block' - 'ignore' sni-server-cert-check: type: str description: 'Check the SNI in the client hello message with the CN or SAN fields in the returned server certificate.' choices: - 'disable' - 'enable' - 'strict' unsupported-ssl-cipher: type: str description: 'Action based on the SSL cipher used being unsupported.' choices: - 'allow' - 'block' unsupported-ssl-negotiation: type: str description: 'Action based on the SSL negotiation used being unsupported.' choices: - 'allow' - 'block' untrusted-server-cert: type: str description: 'Action based on server certificate is not issued by a trusted CA.' choices: - 'allow' - 'block' - 'ignore' allowlist: type: str description: 'Enable/disable exempting servers by FortiGuard allowlist.' choices: - 'disable' - 'enable' block-blocklisted-certificates: type: str description: 'Enable/disable blocking SSL-based botnet communication by FortiGuard certificate blocklist.' choices: - 'disable' - 'enable' dot: description: no description type: dict required: false suboptions: cert-validation-failure: type: str description: 'Action based on certificate validation failure.' choices: - 'allow' - 'block' - 'ignore' cert-validation-timeout: type: str description: 'Action based on certificate validation timeout.' choices: - 'allow' - 'block' - 'ignore' client-certificate: type: str description: 'Action based on received client certificate.' choices: - 'bypass' - 'inspect' - 'block' expired-server-cert: type: str description: 'Action based on server certificate is expired.' choices: - 'allow' - 'block' - 'ignore' proxy-after-tcp-handshake: type: str description:
= False # Indicate whether the UI is working self.sensitive = True # Indicate whether the sanity check ran self.sanity_checked = False # save parsing warnings self.parsing_warnings = [] # create visual elements self.create_visual_elements() # connect the signals to functions self.connect("delete-event", self.destroy_window_cb) self.recipe_model.connect ("recipe-selection-changed", self.recipelist_changed_cb) self.package_model.connect("package-selection-changed", self.packagelist_changed_cb) self.handler.connect("config-updated", self.handler_config_updated_cb) self.handler.connect("package-formats-updated", self.handler_package_formats_updated_cb) self.handler.connect("parsing-started", self.handler_parsing_started_cb) self.handler.connect("parsing", self.handler_parsing_cb) self.handler.connect("parsing-completed", self.handler_parsing_completed_cb) self.handler.build.connect("build-started", self.handler_build_started_cb) self.handler.build.connect("build-succeeded", self.handler_build_succeeded_cb) self.handler.build.connect("build-failed", self.handler_build_failed_cb) self.handler.build.connect("build-aborted", self.handler_build_aborted_cb) self.handler.build.connect("task-started", self.handler_task_started_cb) self.handler.build.connect("disk-full", self.handler_disk_full_cb) self.handler.build.connect("log-error", self.handler_build_failure_cb) self.handler.build.connect("log-warning", self.handler_build_failure_cb) self.handler.build.connect("log", self.handler_build_log_cb) self.handler.build.connect("no-provider", self.handler_no_provider_cb) self.handler.connect("generating-data", self.handler_generating_data_cb) self.handler.connect("data-generated", self.handler_data_generated_cb) self.handler.connect("command-succeeded", self.handler_command_succeeded_cb) self.handler.connect("command-failed", self.handler_command_failed_cb) self.handler.connect("parsing-warning", self.handler_parsing_warning_cb) self.handler.connect("sanity-failed", self.handler_sanity_failed_cb) self.handler.connect("recipe-populated", self.handler_recipe_populated_cb) self.handler.connect("package-populated", self.handler_package_populated_cb) self.handler.append_to_bbfiles("${TOPDIR}/recipes/images/custom/*.bb") self.handler.append_to_bbfiles("${TOPDIR}/recipes/images/*.bb") self.initiate_new_build_async() signal.signal(signal.SIGINT, self.event_handle_SIGINT) def create_visual_elements(self): self.set_title("Hob") self.set_icon_name("applications-development") self.set_resizable(True) try: window_width = self.get_screen().get_width() window_height = self.get_screen().get_height() except AttributeError: print "Please set DISPLAY variable before running Hob." sys.exit(1) if window_width >= hwc.MAIN_WIN_WIDTH: window_width = hwc.MAIN_WIN_WIDTH window_height = hwc.MAIN_WIN_HEIGHT self.set_size_request(window_width, window_height) self.vbox = gtk.VBox(False, 0) self.vbox.set_border_width(0) self.add(self.vbox) # create pages self.image_configuration_page = ImageConfigurationPage(self) self.recipe_details_page = RecipeSelectionPage(self) self.build_details_page = BuildDetailsPage(self) self.package_details_page = PackageSelectionPage(self) self.image_details_page = ImageDetailsPage(self) self.sanity_check_page = SanityCheckPage(self) self.display_sanity_check = False self.sanity_check_post_func = False self.had_network_error = False self.nb = gtk.Notebook() self.nb.set_show_tabs(False) self.nb.insert_page(self.sanity_check_page, None, self.SANITY_CHECK) self.nb.insert_page(self.image_configuration_page, None, self.IMAGE_CONFIGURATION) self.nb.insert_page(self.recipe_details_page, None, self.RECIPE_DETAILS) self.nb.insert_page(self.build_details_page, None, self.BUILD_DETAILS) self.nb.insert_page(self.package_details_page, None, self.PACKAGE_DETAILS) self.nb.insert_page(self.image_details_page, None, self.IMAGE_DETAILS) self.vbox.pack_start(self.nb, expand=True, fill=True) self.show_all() self.nb.set_current_page(0) def sanity_check_timeout(self): # The minimum time for showing the 'sanity check' page has passe # If someone set the 'sanity_check_post_step' meanwhile, execute it now self.display_sanity_check = False if self.sanity_check_post_func: temp = self.sanity_check_post_func self.sanity_check_post_func = None temp() return False def show_sanity_check_page(self): # This window must stay on screen for at least 5 seconds, according to the design document self.nb.set_current_page(self.SANITY_CHECK) self.sanity_check_post_step = None self.display_sanity_check = True self.sanity_check_page.start() gobject.timeout_add(self.SANITY_CHECK_MIN_DISPLAY_TIME * 1000, self.sanity_check_timeout) def execute_after_sanity_check(self, func): if not self.display_sanity_check: func() else: self.sanity_check_post_func = func def generate_configuration(self): if not self.sanity_checked: self.show_sanity_check_page() self.handler.generate_configuration() def initiate_new_build_async(self): self.configuration.selected_image = None self.switch_page(self.MACHINE_SELECTION) self.handler.init_cooker() self.handler.set_extra_inherit("image_types") self.generate_configuration() def update_config_async(self): self.set_user_config() self.generate_configuration() self.switch_page(self.MACHINE_SELECTION) def sanity_check(self): self.handler.trigger_sanity_check() def populate_recipe_package_info_async(self): self.switch_page(self.RCPPKGINFO_POPULATING) # Parse recipes self.set_user_config() self.handler.generate_recipes() def generate_packages_async(self, log = False): self.switch_page(self.PACKAGE_GENERATING) if log: self.current_logfile = self.handler.get_logfile() self.do_log(self.current_logfile) # Build packages _, all_recipes = self.recipe_model.get_selected_recipes() self.set_user_config() self.handler.reset_build() self.handler.generate_packages(all_recipes, self.configuration.default_task) def restore_initial_selected_packages(self): self.package_model.set_selected_packages(self.configuration.initial_user_selected_packages, True) self.package_model.set_selected_packages(self.configuration.initial_selected_packages) for package in self.configuration.selected_packages: if package not in self.configuration.initial_selected_packages: self.package_model.exclude_item(self.package_model.find_path_for_item(package)) def fast_generate_image_async(self, log = False): self.switch_page(self.FAST_IMAGE_GENERATING) if log: self.current_logfile = self.handler.get_logfile() self.do_log(self.current_logfile) # Build packages _, all_recipes = self.recipe_model.get_selected_recipes() self.set_user_config() self.handler.reset_build() self.handler.generate_packages(all_recipes, self.configuration.default_task) def generate_image_async(self, cont = False): self.switch_page(self.IMAGE_GENERATING) self.handler.reset_build() if not cont: self.current_logfile = self.handler.get_logfile() self.do_log(self.current_logfile) # Build image self.set_user_config() toolchain_packages = [] base_image = None if self.configuration.toolchain_build: toolchain_packages = self.package_model.get_selected_packages_toolchain() if self.configuration.selected_image == self.recipe_model.__custom_image__: packages = self.package_model.get_selected_packages() image = self.hob_image base_image = self.configuration.initial_selected_image else: packages = [] image = self.configuration.selected_image self.handler.generate_image(image, base_image, packages, toolchain_packages, self.configuration.default_task) def generate_new_image(self, image, description): base_image = self.configuration.initial_selected_image if base_image == self.recipe_model.__custom_image__: base_image = None packages = self.package_model.get_selected_packages() self.handler.generate_new_image(image, base_image, packages, description) def ensure_dir(self, directory): self.handler.ensure_dir(directory) def get_parameters_sync(self): return self.handler.get_parameters() def request_package_info_async(self): self.handler.request_package_info() def cancel_build_sync(self, force=False): self.handler.cancel_build(force) def cancel_parse_sync(self): self.handler.cancel_parse() def switch_page(self, next_step): # Main Workflow (Business Logic) self.nb.set_current_page(self.__step2page__[next_step]) if next_step == self.MACHINE_SELECTION: # init step self.image_configuration_page.show_machine() elif next_step == self.RCPPKGINFO_POPULATING: # MACHINE CHANGED action or SETTINGS CHANGED # show the progress bar self.image_configuration_page.show_info_populating() elif next_step == self.RCPPKGINFO_POPULATED: self.image_configuration_page.show_info_populated() elif next_step == self.BASEIMG_SELECTED: self.image_configuration_page.show_baseimg_selected() elif next_step == self.RECIPE_SELECTION: if self.recipe_model.get_selected_image() == self.recipe_model.__custom_image__: self.recipe_details_page.set_recipe_curr_tab(self.recipe_details_page.ALL) else: self.recipe_details_page.set_recipe_curr_tab(self.recipe_details_page.INCLUDED) elif next_step == self.PACKAGE_SELECTION: self.configuration.initial_selected_packages = self.configuration.selected_packages self.configuration.initial_user_selected_packages = self.configuration.user_selected_packages self.package_details_page.set_title("Edit packages") if self.recipe_model.get_selected_image() == self.recipe_model.__custom_image__: self.package_details_page.set_packages_curr_tab(self.package_details_page.ALL) else: self.package_details_page.set_packages_curr_tab(self.package_details_page.INCLUDED) self.package_details_page.show_page(self.current_logfile) elif next_step == self.PACKAGE_GENERATING or next_step == self.FAST_IMAGE_GENERATING: # both PACKAGE_GENERATING and FAST_IMAGE_GENERATING share the same page self.build_details_page.show_page(next_step) elif next_step == self.PACKAGE_GENERATED: self.package_details_page.set_title("Step 2 of 2: Edit packages") if self.recipe_model.get_selected_image() == self.recipe_model.__custom_image__: self.package_details_page.set_packages_curr_tab(self.package_details_page.ALL) else: self.package_details_page.set_packages_curr_tab(self.package_details_page.INCLUDED) self.package_details_page.show_page(self.current_logfile) elif next_step == self.IMAGE_GENERATING: # after packages are generated, selected_packages need to # be updated in package_model per selected_image in recipe_model self.build_details_page.show_page(next_step) elif next_step == self.IMAGE_GENERATED: self.image_details_page.show_page(next_step) elif next_step == self.MY_IMAGE_OPENED: self.image_details_page.show_page(next_step) self.previous_step = self.current_step self.current_step = next_step def set_user_config_proxies(self): if self.configuration.enable_proxy == True: self.handler.set_http_proxy(self.configuration.combine_proxy("http")) self.handler.set_https_proxy(self.configuration.combine_proxy("https")) self.handler.set_ftp_proxy(self.configuration.combine_proxy("ftp")) self.handler.set_socks_proxy(self.configuration.combine_proxy("socks")) self.handler.set_cvs_proxy(self.configuration.combine_host_only("cvs"), self.configuration.combine_port_only("cvs")) elif self.configuration.enable_proxy == False: self.handler.set_http_proxy("") self.handler.set_https_proxy("") self.handler.set_ftp_proxy("") self.handler.set_socks_proxy("") self.handler.set_cvs_proxy("", "") def set_user_config_extra(self): self.handler.set_rootfs_size(self.configuration.image_rootfs_size) self.handler.set_extra_size(self.configuration.image_extra_size) self.handler.set_incompatible_license(self.configuration.incompat_license) self.handler.set_sdk_machine(self.configuration.curr_sdk_machine) self.handler.set_image_fstypes(self.configuration.image_fstypes) self.handler.set_extra_config(self.configuration.extra_setting) self.handler.set_extra_inherit("packageinfo image_types") self.set_user_config_proxies() def set_user_config(self): # set bb layers self.handler.set_bblayers(self.configuration.layers) # set local configuration self.handler.set_machine(self.configuration.curr_mach) self.handler.set_package_format(self.configuration.curr_package_format) self.handler.set_distro(self.configuration.curr_distro) self.handler.set_dl_dir(self.configuration.dldir) self.handler.set_sstate_dir(self.configuration.sstatedir) self.handler.set_sstate_mirrors(self.configuration.sstatemirror) self.handler.set_pmake(self.configuration.pmake) self.handler.set_bbthreads(self.configuration.bbthread) self.set_user_config_extra() def update_recipe_model(self, selected_image, selected_recipes): self.recipe_model.set_selected_image(selected_image) self.recipe_model.set_selected_recipes(selected_recipes) def update_package_model(self, selected_packages, user_selected_packages=None): if user_selected_packages: left = self.package_model.set_selected_packages(user_selected_packages, True) self.configuration.user_selected_packages += left left = self.package_model.set_selected_packages(selected_packages) self.configuration.selected_packages += left def update_configuration_parameters(self, params): if params: self.configuration.update(params) self.parameters.update(params) def set_base_image(self): self.configuration.initial_selected_image = self.configuration.selected_image if self.configuration.selected_image != self.recipe_model.__custom_image__: self.hob_image = self.configuration.selected_image + "-edited" def reset(self): self.configuration.curr_mach = "" self.configuration.clear_selection() self.image_configuration_page.switch_machine_combo() self.switch_page(self.MACHINE_SELECTION) # Callback Functions def handler_config_updated_cb(self, handler, which, values): if which == "distro": self.parameters.all_distros = values elif which == "machine": self.parameters.all_machines = values self.image_configuration_page.update_machine_combo() elif which == "machine-sdk": self.parameters.all_sdk_machines = values def handler_package_formats_updated_cb(self, handler, formats): self.parameters.all_package_formats = formats def switch_to_image_configuration_helper(self): self.sanity_check_page.stop() self.switch_page(self.IMAGE_CONFIGURATION) self.image_configuration_page.switch_machine_combo() def show_network_error_dialog_helper(self): self.sanity_check_page.stop() self.show_network_error_dialog() def handler_command_succeeded_cb(self, handler, initcmd): if initcmd == self.handler.GENERATE_CONFIGURATION: if not self.configuration.curr_mach: self.configuration.curr_mach = self.handler.runCommand(["getVariable", "HOB_MACHINE"]) or "" self.update_configuration_parameters(self.get_parameters_sync()) if not self.sanity_checked: self.sanity_check() self.sanity_checked = True elif initcmd == self.handler.SANITY_CHECK: if self.had_network_error: self.had_network_error = False self.execute_after_sanity_check(self.show_network_error_dialog_helper) else: # Switch to the 'image configuration' page now, but we might need # to wait for the minimum display time of the sanity check page self.execute_after_sanity_check(self.switch_to_image_configuration_helper) elif initcmd in [self.handler.GENERATE_RECIPES, self.handler.GENERATE_PACKAGES, self.handler.GENERATE_IMAGE]: self.update_configuration_parameters(self.get_parameters_sync()) self.request_package_info_async() elif initcmd == self.handler.POPULATE_PACKAGEINFO: if self.current_step == self.RCPPKGINFO_POPULATING: self.switch_page(self.RCPPKGINFO_POPULATED) self.rcppkglist_populated() return self.rcppkglist_populated() if self.current_step == self.FAST_IMAGE_GENERATING: self.generate_image_async(True) def show_error_dialog(self, msg): lbl = "<b>Hob found an error</b>" dialog = CrumbsMessageDialog(self, lbl, gtk.MESSAGE_ERROR, msg) button = dialog.add_button("Close", gtk.RESPONSE_OK) HobButton.style_button(button) response = dialog.run() dialog.destroy() def show_warning_dialog(self): dialog = ParsingWarningsDialog(title = "View warnings", warnings = self.parsing_warnings, parent = None, flags = gtk.DIALOG_DESTROY_WITH_PARENT | gtk.DIALOG_NO_SEPARATOR) response = dialog.run() dialog.destroy() def show_network_error_dialog(self): lbl = "<b>Hob cannot connect to the network</b>" msg = msg + "Please check your network connection. If you are using a proxy server, please make sure it is configured correctly." dialog = CrumbsMessageDialog(self, lbl, gtk.MESSAGE_ERROR, msg) button = dialog.add_button("Close", gtk.RESPONSE_OK) HobButton.style_button(button) button = dialog.add_button("Proxy settings", gtk.RESPONSE_CANCEL) HobButton.style_button(button) res = dialog.run() dialog.destroy() if res == gtk.RESPONSE_CANCEL: res, settings_changed = self.show_simple_settings_dialog(SimpleSettingsDialog.PROXIES_PAGE_ID) if not res: return if settings_changed: self.reparse_post_adv_settings() def handler_command_failed_cb(self, handler, msg): if msg: self.show_error_dialog(msg) self.reset() def handler_parsing_warning_cb(self, handler, warn_msg): self.parsing_warnings.append(warn_msg) def handler_sanity_failed_cb(self, handler, msg, network_error): self.reset() if network_error: # Mark this in an internal field. The "network error" dialog will be # shown later, when a SanityCheckPassed event will be handled # (as sent by sanity.bbclass) self.had_network_error = True else: msg = msg.replace("your local.conf", "Settings") self.show_error_dialog(msg) self.reset() def window_sensitive(self, sensitive): self.image_configuration_page.machine_combo.set_sensitive(sensitive) self.image_configuration_page.machine_combo.child.set_sensitive(sensitive) self.image_configuration_page.image_combo.set_sensitive(sensitive) self.image_configuration_page.image_combo.child.set_sensitive(sensitive) self.image_configuration_page.layer_button.set_sensitive(sensitive) self.image_configuration_page.layer_info_icon.set_sensitive(sensitive) self.image_configuration_page.toolbar.set_sensitive(sensitive) self.image_configuration_page.view_adv_configuration_button.set_sensitive(sensitive) self.image_configuration_page.config_build_button.set_sensitive(sensitive) self.recipe_details_page.set_sensitive(sensitive) self.package_details_page.set_sensitive(sensitive) self.build_details_page.set_sensitive(sensitive) self.image_details_page.set_sensitive(sensitive) if sensitive: self.window.set_cursor(None) else: self.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH)) self.sensitive = sensitive def handler_generating_data_cb(self, handler): self.window_sensitive(False) def handler_data_generated_cb(self, handler): self.window_sensitive(True) def rcppkglist_populated(self): selected_image = self.configuration.selected_image selected_recipes = self.configuration.selected_recipes[:] selected_packages = self.configuration.selected_packages[:] user_selected_packages = self.configuration.user_selected_packages[:] self.image_configuration_page.update_image_combo(self.recipe_model, selected_image) self.image_configuration_page.update_image_desc() self.update_recipe_model(selected_image, selected_recipes) self.update_package_model(selected_packages, user_selected_packages) def recipelist_changed_cb(self, recipe_model): self.recipe_details_page.refresh_selection() def packagelist_changed_cb(self, package_model): self.package_details_page.refresh_selection() def handler_recipe_populated_cb(self, handler): self.image_configuration_page.update_progress_bar("Populating recipes", 0.99) def handler_package_populated_cb(self, handler): self.image_configuration_page.update_progress_bar("Populating packages", 1.0) def handler_parsing_started_cb(self, handler, message): if self.current_step != self.RCPPKGINFO_POPULATING: return fraction = 0 if message["eventname"] == "TreeDataPreparationStarted": fraction = 0.6 + fraction self.image_configuration_page.stop_button.set_sensitive(False) self.image_configuration_page.update_progress_bar("Generating dependency tree", fraction) else: self.image_configuration_page.stop_button.set_sensitive(True) self.image_configuration_page.update_progress_bar(message["title"], fraction) def handler_parsing_cb(self, handler, message): if self.current_step != self.RCPPKGINFO_POPULATING: return fraction = message["current"] * 1.0/message["total"] if message["eventname"] == "TreeDataPreparationProgress": fraction = 0.6 + 0.38 * fraction self.image_configuration_page.update_progress_bar("Generating dependency tree", fraction) else: fraction = 0.6 * fraction self.image_configuration_page.update_progress_bar(message["title"], fraction) def handler_parsing_completed_cb(self, handler, message): if self.current_step != self.RCPPKGINFO_POPULATING: return if message["eventname"] == "TreeDataPreparationCompleted": fraction = 0.98 else: fraction = 0.6 self.image_configuration_page.update_progress_bar("Generating dependency tree", fraction) def handler_build_started_cb(self, running_build): if self.current_step == self.FAST_IMAGE_GENERATING: fraction = 0 elif self.current_step == self.IMAGE_GENERATING: if self.previous_step == self.FAST_IMAGE_GENERATING: fraction = 0.9 else: fraction = 0 elif self.current_step == self.PACKAGE_GENERATING: fraction = 0 self.build_details_page.update_progress_bar("Build Started: ", fraction) self.build_details_page.show_configurations(self.configuration, self.parameters) def build_succeeded(self): if self.current_step == self.FAST_IMAGE_GENERATING: fraction = 0.9 elif self.current_step == self.IMAGE_GENERATING: fraction = 1.0 version = "" self.parameters.image_names = [] selected_image = self.recipe_model.get_selected_image() if selected_image == self.recipe_model.__custom_image__: if self.configuration.initial_selected_image != selected_image: version = self.recipe_model.get_custom_image_version() linkname = self.hob_image + version + "-" + self.configuration.curr_mach else: linkname = selected_image + '-'
nsi_k) / nsi_k @cached_const('nsi', 'max nbr degree', "n.s.i. maximum neighbour degree") def nsi_max_neighbors_degree(self): """ For each node, return the maximal n.s.i. degree of its neighbors. (not yet implemented for directed networks.) **Example:** >>> Network.SmallTestNetwork().nsi_max_neighbors_degree() Calculating n.s.i. maximum neighbour degree... Calculating n.s.i. degree... array([ 8.4, 8. , 8. , 8.4, 8.4, 8.4]) as compared to the unweighted version: >>> print Network.SmallTestNetwork().max_neighbors_degree() Calculating maximum neighbours' degree... [3 3 3 3 3 3] :rtype: 1d numpy array [node] of floats >= 0 """ if self.directed: raise NotImplementedError("Not implemented for directed networks.") self.nsi_degree() # matrix with the degrees of nodes' neighbours as rows return (self.sp_Aplus() * self.sp_nsi_diag_k()).max(axis=1).T.A[0] # # Measures of clustering, transitivity and cliquishness # @cached_const('base', 'local clustering', 'local clustering coefficients') def local_clustering(self): """ For each node, return its (Watts-Strogatz) clustering coefficient. This is the proportion of all pairs of its neighbors which are themselves interlinked. (Uses directionality information, if available) **Example:** >>> r(Network.SmallTestNetwork().local_clustering()) Calculating local clustering coefficients... array([ 0. , 0.3333, 1. , 0. , 0.3333, 0. ]) :rtype: 1d numpy array [node] of floats between 0 and 1 """ C = np.array(self.graph.transitivity_local_undirected()) C[np.isnan(C)] = 0 return C @cached_const('base', 'global clustering', 'global clustering coefficient (C_2)') def global_clustering(self): """ Return the global (Watts-Strogatz) clustering coefficient. This is the mean of the local clustering coefficients. [Newman2003]_ refers to this measure as C_2. **Example:** >>> r(Network.SmallTestNetwork().global_clustering()) Calculating global clustering coefficient (C_2)... Calculating local clustering coefficients... 0.2778 :rtype: float between 0 and 1 """ return self.local_clustering().mean() def _motif_clustering_helper(self, t_func, T, key=None, nsi=False): """ Helper function to compute the local motif clustering coefficients. For each node, returns a specific clustering coefficient, depending on the input arguments. :arg function t_func: multiplication of adjacency-type matrices :arg 1d numpy array [node]: denominator made out of (in/out/bil)degrees :arg str key: link attribute key (optional) :arg bool nsi: flag for nsi calculation (default: False) :rtype: 1d numpy array [node] of floats between 0 and 1 """ if nsi: nodew = sp.csc_matrix(np.eye(self.N) * self.node_weights) if key is None: A = self.sp_Aplus() * nodew if nsi else self.sp_A AT = self.sp_Aplus().T * nodew if nsi else A.T else: M = sp.csc_matrix(self.link_attribute(key)**(1/3.)) A = M * nodew if nsi else M AT = M.T * nodew if nsi else M.T t = t_func(A, AT).diagonal() T = T.astype(float) T[T == 0] = np.nan C = t / (self.node_weights * T) if nsi else t / T C[np.isnan(C)] = 0 return C @cached_var('local cyclemotif', 'local cycle motif clustering coefficient') def local_cyclemotif_clustering(self, key=None): """ For each node, return the clustering coefficient with respect to the cycle motif. If a link attribute key is specified, return the associated link weighted version **Example:** >>> r(Network.SmallDirectedTestNetwork().local_cyclemotif_clustering()) Calculating local cycle motif clustering coefficient... array([ 0.25, 0.25, 0. , 0. , 0.5 , 0. ]) :arg str key: link attribute key (optional) :rtype: 1d numpy array [node] of floats between 0 and 1 """ def t_func(x, xT): return x * x * x T = self.indegree() * self.outdegree() - self.bildegree() return self._motif_clustering_helper(t_func, T, key=key) @cached_var('local midmotif', 'local mid. motif clustering coefficient') def local_midmotif_clustering(self, key=None): """ For each node, return the clustering coefficient with respect to the mid. motif. If a link attribute key is specified, return the associated link weighted version **Example:** >>> r(Network.SmallDirectedTestNetwork().local_midmotif_clustering()) Calculating local mid. motif clustering coefficient... array([ 0. , 0. , 0. , 1. , 0.5, 0. ]) :arg str key: link attribute key (optional) :rtype: 1d numpy array [node] of floats between 0 and 1 """ def t_func(x, xT): return x * xT * x T = self.indegree() * self.outdegree() - self.bildegree() return self._motif_clustering_helper(t_func, T, key=key) @cached_var('local inmotif', 'local in motif clustering coefficient') def local_inmotif_clustering(self, key=None): """ For each node, return the clustering coefficient with respect to the in motif. If a link attribute key is specified, return the associated link weighted version **Example:** >>> r(Network.SmallDirectedTestNetwork().local_inmotif_clustering()) Calculating local in motif clustering coefficient... array([ 0. , 0.5, 0.5, 0. , 0. , 0. ]) :arg str key: link attribute key (optional) :rtype: 1d numpy array [node] of floats between 0 and 1 """ def t_func(x, xT): return xT * x * x T = self.indegree() * (self.indegree() - 1) return self._motif_clustering_helper(t_func, T, key=key) @cached_var('local outmotif', 'local out motif clustering coefficient') def local_outmotif_clustering(self, key=None): """ For each node, return the clustering coefficient with respect to the out motif. If a link attribute key is specified, return the associated link weighted version **Example:** >>> r(Network.SmallDirectedTestNetwork().local_outmotif_clustering()) Calculating local out motif clustering coefficient... array([ 0.5, 0.5, 0. , 0. , 0. , 0. ]) :arg str key: link attribute key (optional) :rtype: 1d numpy array [node] of floats between 0 and 1 """ def t_func(x, xT): return x * x * xT T = self.outdegree() * (self.outdegree() - 1) return self._motif_clustering_helper(t_func, T, key=key) @cached_var('nsi local cyclemotif', 'local nsi cycle motif clustering coefficient') def nsi_local_cyclemotif_clustering(self, key=None): """ For each node, return the nsi clustering coefficient with respect to the cycle motif. If a link attribute key is specified, return the associated link weighted version Reference: [Zemp2014]_ **Examples:** >>> net = Network.SmallDirectedTestNetwork() >>> r(net.nsi_local_cyclemotif_clustering()) Calculating local nsi cycle motif clustering coefficient... array([ 0.1845, 0.2028, 0.322 , 0.3224, 0.3439, 0.625 ]) >>> r(net.splitted_copy(node=1).nsi_local_cyclemotif_clustering()) Calculating local nsi cycle motif clustering coefficient... array([ 0.1845, 0.2028, 0.322 , 0.3224, 0.3439, 0.625 , 0.2028]) as compared to the unweighted version: >>> net = Network.SmallDirectedTestNetwork() >>> r(net.local_cyclemotif_clustering()) Calculating local cycle motif clustering coefficient... array([ 0.25, 0.25, 0. , 0. , 0.5 , 0. ]) >>> r(net.splitted_copy(node=1).local_cyclemotif_clustering()) Calculating local cycle motif clustering coefficient... array([ 0.3333, 0.125 , 0. , 0. , 0.5 , 0. , 0.125 ]) :arg str key: link attribute key (optional) """ def t_func(x, xT): return x * x * x T = self.nsi_indegree() * self.nsi_outdegree() return self._motif_clustering_helper(t_func, T, key=key, nsi=True) @cached_var('nsi local midemotif', 'local nsi mid. motif clustering coefficient') def nsi_local_midmotif_clustering(self, key=None): """ For each node, return the nsi clustering coefficient with respect to the mid motif. If a link attribute key is specified, return the associated link weighted version Reference: [Zemp2014]_ **Examples:** >>> net = Network.SmallDirectedTestNetwork() >>> r(net.nsi_local_midmotif_clustering()) Calculating local nsi mid. motif clustering coefficient... array([ 0.4537, 0.5165, 1. , 1. , 0.8882, 1. ]) >>> r(net.splitted_copy(node=4).nsi_local_midmotif_clustering()) Calculating local nsi mid. motif clustering coefficient... array([ 0.4537, 0.5165, 1. , 1. , 0.8882, 1. , 0.8882]) as compared to the unweighted version: >>> net = Network.SmallDirectedTestNetwork() >>> r(net.local_midmotif_clustering()) Calculating local mid. motif clustering coefficient... array([ 0. , 0. , 0. , 1. , 0.5, 0. ]) >>> r(net.splitted_copy(node=4).local_midmotif_clustering()) Calculating local mid. motif clustering coefficient... array([ 0. , 0. , 0. , 1. , 0.8, 0. , 0.8]) :arg str key: link attribute key (optional) """ def t_func(x, xT): return x * xT * x T = self.nsi_indegree() * self.nsi_outdegree() return self._motif_clustering_helper(t_func, T, key=key, nsi=True) @cached_var('nsi local inemotif', 'local nsi in motif clustering coefficient') def nsi_local_inmotif_clustering(self, key=None): """ For each node, return the nsi clustering coefficient with respect to the in motif. If a link attribute key is specified, return the associated link weighted version Reference: [Zemp2014]_ **Examples:** >>> net = Network.SmallDirectedTestNetwork() >>> r(net.nsi_local_inmotif_clustering()) Calculating local nsi in motif clustering coefficient... array([ 0.5288, 0.67 , 0.6693, 0.7569, 0.7556, 1. ]) >>> r(net.splitted_copy(node=1).nsi_local_inmotif_clustering()) Calculating local nsi in motif clustering coefficient... array([ 0.5288, 0.67 , 0.6693, 0.7569, 0.7556, 1. , 0.67 ]) as compared to the unweighted version: >>> net = Network.SmallDirectedTestNetwork() >>> r(net.local_inmotif_clustering()) Calculating local in motif clustering coefficient... array([ 0. , 0.5, 0.5, 0. , 0. , 0. ]) >>> r(net.splitted_copy(node=1).local_inmotif_clustering()) Calculating local in motif clustering coefficient... array([ 0. , 0.5 , 0.6667, 0. , 1. , 0. , 0.5 ]) :arg str key: link attribute key (optional) """ def t_func(x, xT): return xT * x * x T = self.nsi_indegree()**2 return self._motif_clustering_helper(t_func, T, key=key, nsi=True) @cached_var('nsi local outemotif', 'local nsi out motif clustering coefficient') def nsi_local_outmotif_clustering(self, key=None): """
<reponame>LarsHH/reproducible-hyperparameter-optimization-jcgs-2019<filename>sherpa-seq-testing/sherpa/schedulers.py """ SHERPA is a Python library for hyperparameter tuning of machine learning models. Copyright (C) 2018 <NAME>, <NAME>, and <NAME>. This file is part of SHERPA. SHERPA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SHERPA is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with SHERPA. If not, see <http://www.gnu.org/licenses/>. """ import subprocess import re import sys import os import logging logger = logging.getLogger(__name__) class _JobStatus(object): """ Job status used internally to classify jobs into categories. """ finished = 1 running = 2 failed = 3 queued = 4 killed = 5 other = 6 class Scheduler(object): """ The job scheduler gives an API to submit jobs, retrieve statuses of specific jobs, and kill a job. """ def __init__(self): pass def submit_job(self, command, env={}, job_name=''): """ Submits a job to the scheduler. Args: command (list[str]): components to the command to run by the scheduler e.g. ``["python", "train.py"]`` env (dict): environment variables to pass to the job. job_name (str): this specifies a name for the job and its output directory. Returns: str: a job ID, used for getting the status or killing the job. """ pass def get_status(self, job_id): """ Obtains the current status of the job. Args: job_id (str): identifier returned when submitting the job. Returns: sherpa.schedulers._JobStatus: the job-status. """ pass def kill_job(self, job_id): """ Kills a given job. Args: job_id (str): identifier returned when submitting the job. """ pass class LocalScheduler(Scheduler): """ Runs jobs locally as a subprocess. Args: submit_options (str): options appended before the command. resources (list[str]): list of resources that will be passed as SHERPA_RESOURCE environment variable. If no resource is available '' will be passed. """ def __init__(self, submit_options='', output_dir='', resources=None): self.output_dir = output_dir self.jobs = {} self.resources = resources self.resource_by_job = {} self.output_files = {} self.submit_options = submit_options self.decode_status = {0: _JobStatus.finished, -15: _JobStatus.killed} self.output_dir = output_dir def submit_job(self, command, env={}, job_name=''): outdir = os.path.join(self.output_dir, 'jobs') if not os.path.isdir(outdir): os.mkdir(outdir) env.update(os.environ.copy()) if self.resources is not None: env['SHERPA_RESOURCE'] = str(self.resources.pop()) else: env['SHERPA_RESOURCE'] = '' f = open(os.path.join(outdir, '{}.out'.format(job_name)), 'w') optns = self.submit_options.split(' ') if self.submit_options else [] process = subprocess.Popen(optns + command, env=env, stderr=f, stdout=f) self.jobs[process.pid] = process self.output_files[process.pid] = f if self.resources is not None: self.resource_by_job[process.pid] = env['SHERPA_RESOURCE'] return process.pid def get_status(self, job_id): process = self.jobs.get(job_id) if not process: raise ValueError("Job not found.") status = process.poll() if status is None: return _JobStatus.running else: if job_id in self.resource_by_job: resource = self.resource_by_job.pop(job_id) self.resources.append(resource) if job_id in self.output_files: f = self.output_files.pop(process.pid) f.close() return self.decode_status.get(status, _JobStatus.other) def kill_job(self, job_id): process = self.jobs.get(job_id) if not process: raise ValueError("Job not found.") process.terminate() class SGEScheduler(Scheduler): """ Submits jobs to SGE, can check on their status, and kill jobs. Uses ``drmaa`` Python library. Due to the way SGE works it cannot distinguish between a failed and a completed job. Args: submit_options (str): command line options such as queue ``-q``, or ``-P`` for project, all written in one string. environment (str): the path to a file that contains environment variables; will be sourced before job is run. output_dir (str): path to directory in which ``stdout`` and ``stderr`` will be written to. If not specified this will use the same as defined for the study. """ def __init__(self, submit_options, environment, output_dir=''): self.count = 0 self.submit_options = submit_options self.environment = environment self.output_dir = output_dir self.killed_jobs = set() self.drmaa = __import__('drmaa') self.decode_status = { self.drmaa.JobState.UNDETERMINED: _JobStatus.other, self.drmaa.JobState.QUEUED_ACTIVE: _JobStatus.queued, self.drmaa.JobState.SYSTEM_ON_HOLD: _JobStatus.other, self.drmaa.JobState.USER_ON_HOLD: _JobStatus.other, self.drmaa.JobState.USER_SYSTEM_ON_HOLD: _JobStatus.other, self.drmaa.JobState.RUNNING: _JobStatus.running, self.drmaa.JobState.SYSTEM_SUSPENDED: _JobStatus.other, self.drmaa.JobState.USER_SUSPENDED: _JobStatus.other, self.drmaa.JobState.DONE: _JobStatus.finished, self.drmaa.JobState.FAILED: _JobStatus.failed} def submit_job(self, command, env={}, job_name=''): # Create temp directory. outdir = os.path.join(self.output_dir, 'jobs') if not os.path.isdir(outdir): os.mkdir(outdir) job_name = job_name or str(self.count) sgeoutfile = os.path.join(outdir, '{}.out'.format(job_name)) try: os.remove(sgeoutfile) except OSError: pass # Create bash script that sources environment and runs python script. job_script = '#$ -S /bin/bash\n' if self.environment: job_script += 'source %s\n' % self.environment job_script += 'echo "Running from" ${HOSTNAME}\n' for var_name, var_value in env.items(): job_script += 'export {}={}\n'.format(var_name, var_value) job_script += " ".join(command) # 'python file.py args...' # Submit command to SGE. # Note: submitting job using drmaa didn't work because we weren't able # to specify options. submit_command = 'qsub -S /bin/bash -wd {} -j y -o {} -e {} {}'.format( os.getcwd(), sgeoutfile, sgeoutfile, self.submit_options) assert ' -cwd' not in submit_command # Submit using subprocess so we can get SGE process ID. job_id = self._submit_job(submit_command, job_script) logger.info('\t{}: job submitted'.format(job_id)) self.count += 1 return job_id @staticmethod def _submit_job(submit_command, run_command): """ Args: submit_command (str): e.g. "qsub -N myProject ..." run_command (str): e.g. "python nn.py" Returns: str: SGE process ID. """ process = subprocess.Popen(submit_command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, universal_newlines=True) output, std_err = process.communicate(input=run_command) # output, std_err = process.communicate() process.stdin.close() output_regexp = r'Your job (\d+)' # Parse out the process id from text match = re.search(output_regexp, output) if match: return match.group(1) else: sys.stderr.write(output) return None def get_status(self, job_id): """ Args: job_ids (str): SGE process ID. Returns: sherpa.schedulers._JobStatus: The job status. """ with self.drmaa.Session() as s: try: status = s.jobStatus(str(job_id)) except self.drmaa.errors.InvalidJobException: return _JobStatus.finished s = self.decode_status.get(status) if s == _JobStatus.finished and job_id in self.killed_jobs: s = _JobStatus.killed return s def kill_job(self, job_id): """ Kills a job submitted to SGE. Args: job_id (str): the SGE process ID of the job. """ logger.info("Killing job {}".format(job_id)) with self.drmaa.Session() as s: s.control(job_id, self.drmaa.JobControlAction.TERMINATE) # TODO: what happens when job doesn't exist - then we don't want to add self.killed_jobs.add(job_id) class SLURMScheduler(Scheduler): """ Submits jobs to SLURM, can check on their status, and kill jobs. Uses ``drmaa`` Python library. Args: submit_options (str): command line options such as queue ``-q``, all written in one string. environment (str): the path to a file that contains environment variables; will be sourced before job is run. output_dir (str): path to directory in which ``stdout`` and ``stderr`` will be written to. If not specified this will use the same as defined for the study. """ def __init__(self, submit_options, environment, output_dir=''): self.count = 0 self.submit_options = submit_options self.environment = environment self.output_dir = output_dir self.killed_jobs = set() self.drmaa = __import__('drmaa') self.decode_status = { self.drmaa.JobState.UNDETERMINED: _JobStatus.other, self.drmaa.JobState.QUEUED_ACTIVE: _JobStatus.queued, self.drmaa.JobState.SYSTEM_ON_HOLD: _JobStatus.other, self.drmaa.JobState.USER_ON_HOLD: _JobStatus.other, self.drmaa.JobState.USER_SYSTEM_ON_HOLD: _JobStatus.other, self.drmaa.JobState.RUNNING: _JobStatus.running, self.drmaa.JobState.SYSTEM_SUSPENDED: _JobStatus.other, self.drmaa.JobState.USER_SUSPENDED: _JobStatus.other, self.drmaa.JobState.DONE: _JobStatus.finished, self.drmaa.JobState.FAILED: _JobStatus.failed} def submit_job(self, command, env={}, job_name=''): # Create temp directory. logger.info('\nSUBMITTING JOB in submit_job') outdir = os.path.join(self.output_dir, 'jobs') if not os.path.isdir(outdir): os.mkdir(outdir) job_name = job_name or str(self.count) slurmoutfile = os.path.join(outdir, '{}.out'.format(job_name)) try: os.remove(slurmoutfile) except OSError: pass # Create bash script that sources environment and runs python script. job_script = '#!/bin/bash\n' if self.environment: job_script += 'source %s\n' % self.environment job_script += 'echo "Running from" ${HOSTNAME}\n' for var_name, var_value in env.items(): job_script += 'export {}={}\n'.format(var_name, var_value) job_script += " ".join(command) # 'python file.py args...' # Submit command to SLURM. # Note: submitting job using drmaa didn't work because we weren't able # to specify options. submit_command = 'sbatch --workdir={} --output={} --error={} {}'.format( os.getcwd(), slurmoutfile, slurmoutfile, self.submit_options) assert ' -cwd' not in submit_command # Submit using subprocess so we can get SLURM process ID. job_id = self._submit_job(submit_command, job_script) logger.info('\t{}: job submitted'.format(job_id)) self.count += 1 return job_id @staticmethod def _submit_job(submit_command, run_command): """ Args: submit_command (str): e.g. "qsub -N myProject ..." run_command (str): e.g. "python nn.py" Returns: str: SLURM process ID. """ process = subprocess.Popen(submit_command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, universal_newlines=True) output, std_err = process.communicate(input=run_command) # output, std_err = process.communicate() process.stdin.close() output_regexp = r'Submitted batch job (\d+)' # Parse out the process id from text match = re.search(output_regexp, output) if match: return match.group(1) else: sys.stderr.write(output) return None def get_status(self, job_id): """ Args: job_ids (str): SLURM process ID. Returns: sherpa.schedulers._JobStatus: The job status. """ with self.drmaa.Session() as s: try: status
"""Módulo para metrificação de ativos e retornos.""" import numpy as np import pandas as pd from scipy import stats def sharpe_ratio(returns, risk_free=0, time_scale=252): """ Essa função, a partir da definição do parâmetro de retorno, fornece o sharpe ratio do ativo, com base na média histórica e desvio padrão dos retornos. O risk free considerado é nulo. Args: returns (pd.series): série com o retorno do ativo. risk_free (float): risk free utilizado para cálculo do sharpe ratio. time_scale (int): fator de escala do sharpe ratio, que é o número de amostras em um ano. Caso fosse uma série temporal diária: 252; série temporal mensal: 12 Returns: float: índice de sharpe do ativo. """ expected_returns = np.mean(returns) risk = np.std(returns) sharpe = (expected_returns * time_scale - risk_free) / (risk * np.sqrt(time_scale)) return sharpe def beta(returns, benchmark): """ Essa função, a partir do fornecimento dos retornos do ativo e do benchmark, calcula o beta do ativo. Args: returns (pd.Series): série com o retorno do ativo. benchmark (pd.Series): série com o retorno do benchmark. Returns: float: Beta do ativo """ assert returns.shape[0] == benchmark.shape[0], "Séries temporais com dimensões diferentes" cov = np.cov(returns, benchmark)[0][1] benchmark_vol = np.var(benchmark) return cov / benchmark_vol def capm(returns, market_returns, risk_free): """ Essa função, com o fornecimento dos retornos de um portfólio ou ativo, dos retornos do mercado e da retorno sem risco, calcula o retorno esperado pela abordagem CAPM. Essa abordagem considera o mercado (benchmark) e as relações com os ativos como parâmetro para estimar o retorno esperado. Args: returns (pd.Series ou np.array): vetor de retornos market_returns (pd.Series ou np.array): vetor de retornos do mercado ou benchmark risk_free (float): retorno livre de risco Returns: float: retorno esperado pela abordagem CAPM """ beta = beta(returns, market_returns) expected_market_returns = market_returns.mean() expected_returns = risk_free + beta * (expected_market_returns - risk_free) return expected_returns def alpha(start_price, end_price, dividends): """ Essa função, com o fornecimento do preço final, dos dividendos por ação e do preço inicial, a calcula o alfa de um ativo. Args: start_price (float): preço inicial. end_price (float): preço final. dividends (float): dividendos por ação. Returns: float: alpha do ativo """ return (end_price + dividends - start_price) / start_price def drawdown(returns): """ Calcula o drawdown percentual para uma série de retornos. Args: returns (pd.Series): série de retornos para a qual será calculado o drawdown. Returns: pd.Series: uma série com os valores percentuais do Drawdown. """ cum_returns = (1 + returns).cumprod() peeks = cum_returns.cummax() drawdowns = pd.Series((cum_returns/peeks - 1)*100, name='Drawdown') return drawdowns def rolling_beta(returns, benchmark, window=60): """ Calcula o beta móvel para um ativo e um benchmark de referência, na forma de séries de retornos. Args: returns (array): série de retornos para o qual o beta será calculado. benchmark (array): série de retornos para usar de referência no cálculo do beta. window (int): janela móvel para calcular o beta ao longo do tempo. Returns: pd.Series: uma série com os valores do Beta para os últimos `window` dias. A série não possui os `window` primeiros dias. """ rolling_beta = pd.Series([beta(returns[i-window:i], benchmark[i-window:i]) for i in range(window, len(returns))], index=returns[window:].index) return rolling_beta def rolling_sharpe(returns, window, risk_free=0): """ Calcula o sharpe móvel para um ativo e um benchmark de referência, na forma de séries de retornos. Args: returns (pd.Series): série de retornos para o qual o Sharpe Ratio será calculado. window (int): janela móvel para calcular o Sharpe ao longo do tempo. risk_free (float): valor da taxa livre de risco para cálculo do Sharpe. Returns: pd.Series: uma série com os valores do Sharpe para os últimos `window` dias. A série não possui os `window` primeiros dias. """ rolling_sharpe = pd.Series([sharpe_ratio(returns[i - window:i], risk_free) for i in range(window, len(returns))], returns[window:].index) return rolling_sharpe def ewma_volatility(returns, window): """ Essa função calcula a volatilidade por EWMA ao longo de um período. Args: returns (pd.Series): série de retornos para o qual o EWMA será calculado. window (int): janela móvel para cálculo da EWMA; Returns: pd.Series: uma série com os valores de EWMA dos últimos `window` dias """ ewma_volatility = returns.ewm(span=window).std() return ewma_volatility def garman_klass_volatility(high_prices, low_prices, close_prices, open_prices, window, time_scale=1): """ Estima a volatilidade a partir dos seguintes preços: alta, baixa, abertura e fechamento Args: high_prices (pd.DataFrame): série de preços de alta de uma ação low_prices (pd.DataFrame): série de preços de baixa de uma ação close_prices (pd.DataFrame): série de preços de fechamento de uma ação open_prices (pd.DataFrame): série de preços de abertura de uma ação window (int): janela das estimativa de volatilidade time_scale (int): fator de escala da volatilidade, por padrão é 1 (diária) Returns: pd.Series: série das estimativas de volatildade """ high_low_ratio = (1 / 2) * \ (np.log(np.divide(high_prices, low_prices))) ** 2 close_open_ratio = -(2 * np.log(2) - 1) * ( np.log(np.divide(close_prices, open_prices)) ** 2 ) log_ratio = high_low_ratio + close_open_ratio.values garman_klass_vol = pd.Series(log_ratio, name='Garman Klass', copy=True) Period_const = time_scale / window garman_klass_vol.iloc[:window] = np.nan for date in range(window, len(high_prices)): garman_klass_vol.iloc[date] = np.sqrt( Period_const * np.sum(log_ratio.iloc[date - window: date]) ) return garman_klass_vol def parkinson_volatility(high_prices, low_prices, window, time_scale=1, plot=False): """ Estimando a volatilidade a partir dos preços de Alta e de Baixa Args: high (pd.DataFrame): série de preços de alta de uma ação low (pd.DataFrame): série de preços de baixa de uma ação window (int): janela das estimativa de volatilidade time_scale (int): fator de escala da volatilidade, por padrão é 1 (diária) Returns: pd.Series: série das estimativas de volatildade """ log_ratio = np.log(np.divide(high_prices, low_prices)) ** 2 parkinson_vol = pd.Series(log_ratio, name='Parkinson', copy=True) Period_const = time_scale / (4 * window * np.log(2)) parkinson_vol.iloc[:window] = np.nan for date in range(window, len(high_prices)): parkinson_vol.iloc[date] = np.sqrt( Period_const * np.sum(log_ratio.iloc[date - window: date]) ) return parkinson_vol def rolling_std(returns, window): """ Essa função calcula volatilidade a partir do cálculo da desvio padrão móvel. Args: returns (pd.Series): série de retornos para o qual o desvio padrão será calculado. window (int): janela móvel para cálculo do desvio padrão móvel; Returns: pd.Series: uma série indexado à data com os valores de desvio padrão móvel dos últimos window dias """ rolling_std = returns.rolling(window).std() return rolling_std def returns(close_prices, return_type='simple'): """ Essa função permite o cálculo rápido do retorno de uma ação ao longo do tempo. Args: close_prices (pd.Series): série de preços de fechamento que será utilizada de base para o cálculo do retorno; return_type (string): tipo de retorno (simples - 'simple' ou logarítmico - 'log') a ser calculado; Returns: pd.Series: série com os valores do retorno ao longo do tempo """ if return_type == "simple": returns = close_prices.pct_change() elif return_type == "log": returns = np.log(close_prices/close_prices.shift(1)) else: raise ValueError("Tipo de retorno inválido") return returns def cumulative_returns(returns, return_type): """ Essa função permite o cálculo do retorno cumulativo ao longo do tempo. Args: returns (pd.Series): série de retornos da ação ao longo do tempo; return_type (string): tipo de retorno (simples - 'simp' ou logarítmico - 'log') presente na série. Returns: pd.Series: série com os valores de retorno cumulativo ao longo do tempo """ if return_type == "log": cumulative_returns = returns.cumsum() elif return_type == "simp": cumulative_returns = (returns + 1).cumprod() - 1 else: raise ValueError("Tipo de retorno inválido") return cumulative_returns def cagr(returns, time_scale=252): """ Calcula o CAGR que é a taxa composta de crescimento anual. Args: returns (pd.Series): série de retornos para a qual será calculado o drawdown. time_scale (int): fator de escala do cagr, que é o número de amostras em um ano. Caso fosse uma série temporal diária: 252; série temporal mensal: 12 Returns: float: cagr do ativo. """ cumulative_return = (1 + returns).cumprod()[-1] return (cumulative_return ** (1/(returns.shape[-1] / time_scale)) - 1) def mar_ratio(returns, time_window, time_scale=252): """ Calcula e plota o drawdown percentual para uma série de retornos. Args: returns (pd.Series): série de retornos para a qual será calculado o mar ratio. time_window (float): janela de tempo que o mar ratio será calculado em relação a escala de tempo. time_window = 3 e time_scale = 252 denota uma janela de 3 anos (Calmar Ratio). time_scale (int): fator de escala do mar ratio,
formatted # properly, raise a ValueError if(not isinstance(self.file_format, str) or (self.file_format.find("{") < 0) or (self.file_format.find("}") < 0)): raise ValueError(''.join(['file format set to default, ', 'supplied string must be iterable ', '[{:}]'.format(self.file_format)])) # set up empty data and metadata # check if pandas or xarray format if self.pandas_format: self._null_data = pds.DataFrame(None) self._data_library = pds.DataFrame else: self._null_data = xr.Dataset(None) self._data_library = xr.Dataset # assign null data for user selected data type self.data = self._null_data.copy() # Create Meta instance with appropriate labels. Meta class methods will # use Instrument definition of MetaLabels over the Metadata declaration self.meta_labels = labels self.meta = pysat.Meta(labels=self.meta_labels) self.meta.mutable = False # Nano-kernel processing variables. Feature processes data on each load. self.custom_functions = [] self.custom_args = [] self.custom_kwargs = [] # Process provided user input for custom methods, if provided. if custom is not None: # Required keys. req_key = 'function' for cust in custom: # Check if required keys present in input. if req_key not in cust: estr = ''.join(('Input dict to custom is missing the ', 'required key: ', req_key)) raise ValueError(estr) # Set the custom kwargs cust_kwargs = dict() for ckey in cust.keys(): if ckey != req_key: cust_kwargs[ckey] = cust[ckey] # Inputs have been checked, add to Instrument object. self.custom_attach(cust['function'], **cust_kwargs) # Create arrays to store data around loaded day. This enables padding # across day breaks with minimal loads self._next_data = self._null_data.copy() self._next_data_track = [] self._prev_data = self._null_data.copy() self._prev_data_track = [] self._curr_data = self._null_data.copy() # Initialize the padding if isinstance(pad, (dt.timedelta, pds.DateOffset)) or pad is None: self.pad = pad elif isinstance(pad, dict): self.pad = pds.DateOffset(**pad) else: raise ValueError(' '.join(['pad must be a dict, NoneType,', 'datetime.timedelta, or', 'pandas.DateOffset instance.'])) # Store kwargs, passed to standard routines first self.kwargs = {} self.kwargs_supported = {} self.kwargs_reserved = _reserved_keywords.copy() saved_keys = [] # Expected function keywords exp_keys = ['list_files', 'load', 'preprocess', 'download', 'list_remote_files', 'clean', 'init'] for fkey in exp_keys: func_name = _kwargs_keys_to_func_name(fkey) func = getattr(self, func_name) # Get dict of supported keywords and values default_kwargs = _get_supported_keywords(func) # Confirm there are no reserved keywords present for kwarg in kwargs.keys(): if kwarg in self.kwargs_reserved: estr = ''.join(('Reserved keyword "', kwarg, '" is not ', 'allowed at instantiation.')) raise ValueError(estr) # Check if kwargs are in list good_kwargs = [ckey for ckey in kwargs.keys() if ckey in default_kwargs] # Store appropriate user supplied keywords for this function self.kwargs[fkey] = {gkey: kwargs[gkey] for gkey in good_kwargs} # Store all supported keywords for user edification self.kwargs_supported[fkey] = default_kwargs # Store keys to support check that all user supplied # keys are used. saved_keys.extend(default_kwargs.keys()) # Test for user supplied keys that are not used missing_keys = [] for custom_key in kwargs: if custom_key not in saved_keys and (custom_key not in exp_keys): missing_keys.append(custom_key) if len(missing_keys) > 0: raise ValueError('unknown keyword{:s} supplied: {:}'.format( '' if len(missing_keys) == 1 else 's', missing_keys)) # Instantiate the Files class temporary_file_list = not temporary_file_list if ignore_empty_files is None: ignore_empty_files = pysat.params['ignore_empty_files'] if update_files is None: update_files = pysat.params['update_files'] self.files = pysat.Files(self, directory_format=self.directory_format, update_files=update_files, file_format=self.file_format, write_to_disk=temporary_file_list, ignore_empty_files=ignore_empty_files) # Set bounds for iteration. self.bounds requires the Files class, and # setting bounds to (None, None) loads the default bounds. self.bounds = (None, None) self.date = None self._fid = None self.yr = None self.doy = None self._load_by_date = False # Initialize orbit support if orbit_info is None: if self.orbit_info is None: # If default info not provided, use class defaults self.orbit_info = dict() else: self.orbit_info = orbit_info self.orbits = pysat.Orbits(self, **self.orbit_info) # Create empty placeholder for the meta translation table, which # provides information about how to label metadata for netcdf export. # If None, pysat metadata labels will be used instead. self._meta_translation_table = None # Create a placeholder for a post-processing function to be applied # to the metadata dictionary before export. If None, no post-processing # will occur self._export_meta_post_processing = None # Start with a daily increment for loading self.load_step = dt.timedelta(days=1) # Run instrument init function, a basic pass function is used if the # user doesn't supply the init function self._init_rtn(**self.kwargs['init']) # Store base attributes, used in particular by Meta class self._base_attr = dir(self) def __eq__(self, other): """Perform equality check Parameters ---------- other : any Other object to compare for equality Returns ------- bool True if objects are identical, False if they are not. """ # Check if other is the same class (Instrument). Exit early if not. if not isinstance(other, self.__class__): return False # Check if both objects are the same data type. Exit early if not. if self.pandas_format != other.pandas_format: return False # Both the same data type, do both have data? if self.empty and other.empty: # This check needed to establish next check pass elif self.empty or other.empty: # Only one has data, exit early. return False # If data is the same, check other attributes. Partial functions # required their own path for equality, string comparisons! partial_funcs = ['_init_rtn', '_clean_rtn', '_preprocess_rtn', '_list_files_rtn', '_download_rtn', '_list_remote_files_rtn', '_load_rtn'] # If the type is the same then check everything that is attached to # the Instrument object. Includes attributes, methods, variables, etc. checks = [] key_check = [] for key in self.__dict__.keys(): if key not in ['data', '_null_data', '_next_data', '_curr_data', '_prev_data']: key_check.append(key) if key in other.__dict__.keys(): if key in partial_funcs: # Partial function comparison doesn't work directly. try: checks.append(str(self.__dict__[key]) == str(other.__dict__[key])) except AttributeError: # If an item missing a required attribute return False else: # General check for everything else. checks.append(np.all(self.__dict__[key] == other.__dict__[key])) else: # Both objects don't have the same attached objects return False else: # Data comparison area. Established earlier both have data. if self.pandas_format: try: # Check is sensitive to the index labels. Errors # if index is not identical. checks.append(np.all(self.__dict__[key] == other.__dict__[key])) except ValueError: return False else: checks.append(xr.Dataset.equals(self.data, other.data)) # Confirm that other Instrument object doesn't have extra terms for key in other.__dict__.keys(): if key not in self.__dict__.keys(): return False # Confirm all checks are True test_data = np.all(checks) return test_data def __repr__(self): """ Print the basic Instrument properties""" # Create string for custom attached methods cstr = '[' for func, arg, kwarg in zip(self.custom_functions, self.custom_args, self.custom_kwargs): tstr = "".join(("'function': {sfunc}, 'args': {sargs}, ", "'kwargs': {kargs}")) tstr = tstr.format(sfunc=repr(func), sargs=repr(arg), kargs=repr(kwarg)) cstr = "".join((cstr, '{', tstr, '}, ')) cstr += ']' # Deconstruct the kwargs in_kwargs = dict() for sort_key in self.kwargs.keys(): for meth_key in self.kwargs[sort_key]: in_kwargs[meth_key] = self.kwargs[sort_key][meth_key] # Get the inst_module string if self.inst_module is None: istr = "None" else: istr = getattr(self.inst_module, "__name__") # Create string for other parts Instrument instantiation out_str = "".join(["pysat.Instrument(platform='", self.platform, "', name='", self.name, "', tag='", self.tag, "', inst_id='", self.inst_id, "', clean_level='", self.clean_level, "', pad={:}, orbit_info=".format(self.pad), "{:}, ".format(self.orbit_info), "inst_module=", istr, ", custom=", cstr, ", **{:}".format(in_kwargs), ")"]) return out_str def __str__(self): """ Descriptively print the basic Instrument properties""" # Get the basic Instrument properties output_str = 'pysat Instrument object\n' output_str += '-----------------------\n' output_str += "Platform: '{:s}'\n".format(self.platform) output_str += "Name: '{:s}'\n".format(self.name) output_str += "Tag: '{:s}'\n".format(self.tag) output_str += "Instrument id: '{:s}'\n".format(self.inst_id) # Print out the data processing information output_str += '\nData Processing\n' output_str += '---------------\n' output_str += "Cleaning Level: '{:s}'\n".format(self.clean_level) output_str += 'Data Padding: {:s}\n'.format(self.pad.__str__()) for routine in self.kwargs.keys(): output_str += 'Keyword Arguments Passed to {:s}: '.format(routine) output_str += "{:s}\n".format(self.kwargs[routine].__str__()) num_funcs = len(self.custom_functions) output_str += "Custom Functions: {:d} applied\n".format(num_funcs) if num_funcs > 0: for i, func in enumerate(self.custom_functions): output_str += " {:d}: {:}\n".format(i, func.__repr__()) if len(self.custom_args[i]) > 0: ostr = " : Args={:}\n".format(self.custom_args[i]) output_str += ostr if len(self.custom_kwargs[i]) > 0: ostr = " : Kwargs={:}\n".format(self.custom_kwargs[i]) output_str += ostr output_str += '\n' # Print out the orbit settings if self.orbits.orbit_index is not None: output_str += '{:s}\n'.format(self.orbits.__str__()) # Print the local file information output_str += self.files.__str__() # Display loaded data output_str += '\n\nLoaded Data Statistics\n' output_str += '----------------------\n' if not self.empty: output_str += 'Date: ' + self.date.strftime('%d %B %Y') + '\n' output_str +=
service["StackServices"]["service_name"] calculation = recommenderDict.get(serviceName, None) if calculation is not None: calculation(configurations, clusterSummary, services, hosts) else: serviceAdvisor = self.getServiceAdvisor(serviceName) if serviceAdvisor is not None: serviceAdvisors.append(serviceAdvisor) for serviceAdvisor in serviceAdvisors: serviceAdvisor.getServiceConfigurationRecommendationsForKerberos(configurations, clusterSummary, services, hosts) return recommendations def getServiceConfigurationRecommender(self, service): return self.getServiceConfigurationRecommenderDict().get(service, None) def getServiceConfigurationRecommenderDict(self): return {} def getServiceConfigurationRecommenderForSSODict(self): return {} def getServiceConfigurationRecommenderForKerberosDict(self): return {} # Recommendation helper methods def isComponentHostsPopulated(self, component): hostnames = self.getComponentAttribute(component, "hostnames") if hostnames is not None: return len(hostnames) > 0 return False def checkSiteProperties(self, siteProperties, *propertyNames): """ Check if properties defined in site properties. :param siteProperties: config properties dict :param *propertyNames: property names to validate :returns: True if all properties defined, in other cases returns False """ if siteProperties is None: return False for name in propertyNames: if not (name in siteProperties): return False return True def get_ambari_configuration(self, services): """ Gets the AmbariConfiguration object that can be used to request details about the Ambari configuration. For example LDAP and SSO configurations :param services: the services structure containing the "ambari-server-configurations" block :return: an AmbariConfiguration """ return AmbariConfiguration(services) def is_secured_cluster(self, services): """ Detects if cluster is secured or not :type services dict :rtype bool """ return services and "cluster-env" in services["configurations"] and \ "security_enabled" in services["configurations"]["cluster-env"]["properties"] and \ services["configurations"]["cluster-env"]["properties"]["security_enabled"].lower() == "true" def getZKHostPortString(self, services, include_port=True): """ Returns the comma delimited string of zookeeper server host with the configure port installed in a cluster Example: zk.host1.org:2181,zk.host2.org:2181,zk.host3.org:2181 include_port boolean param -> If port is also needed. """ servicesList = [service["StackServices"]["service_name"] for service in services["services"]] include_zookeeper = "ZOOKEEPER" in servicesList zookeeper_host_port = '' if include_zookeeper: zookeeper_hosts = self.getHostNamesWithComponent("ZOOKEEPER", "ZOOKEEPER_SERVER", services) zookeeper_host_port_arr = [] if include_port: zookeeper_port = self.getZKPort(services) for i in range(len(zookeeper_hosts)): zookeeper_host_port_arr.append(zookeeper_hosts[i] + ':' + zookeeper_port) else: for i in range(len(zookeeper_hosts)): zookeeper_host_port_arr.append(zookeeper_hosts[i]) zookeeper_host_port = ",".join(zookeeper_host_port_arr) return zookeeper_host_port def getZKPort(self, services): zookeeper_port = '2181' #default port if 'zoo.cfg' in services['configurations'] and ('clientPort' in services['configurations']['zoo.cfg']['properties']): zookeeper_port = services['configurations']['zoo.cfg']['properties']['clientPort'] return zookeeper_port def isClientComponent(self, component): return self.getComponentAttribute(component, "component_category") == 'CLIENT' def isSlaveComponent(self, component): return self.getComponentAttribute(component, "component_category") == 'SLAVE' def isMasterComponent(self, component): return self.getComponentAttribute(component, "is_master") def getRequiredComponent(self, services, componentName): """ Return Category for component :type services dict :type componentName str :rtype dict """ componentsListList = [service["components"] for service in services["services"]] componentsList = [item["StackServiceComponents"] for sublist in componentsListList for item in sublist] component = next((component for component in componentsList if component["component_name"] == componentName), None) return component def getComponentAttribute(self, component, attribute): serviceComponent = component.get("StackServiceComponents", None) if serviceComponent is None: return None return serviceComponent.get(attribute, None) def isLocalHost(self, hostName): return socket.getfqdn(hostName) == socket.getfqdn() def isMasterComponentWithMultipleInstances(self, component): componentName = self.getComponentName(component) masters = self.getMastersWithMultipleInstances() return componentName in masters def isComponentNotValuable(self, component): componentName = self.getComponentName(component) service = self.getNotValuableComponents() return componentName in service def getMinComponentCount(self, component, hosts): componentName = self.getComponentName(component) return self.getComponentCardinality(componentName, hosts)["min"] # Helper dictionaries def getComponentCardinality(self, componentName, hosts): dict = self.getCardinalitiesDict(hosts) if componentName in dict: return dict[componentName] else: return {"min": 1, "max": 1} def isServiceDeployed(self, services, serviceName): servicesList = [service["StackServices"]["service_name"] for service in services["services"]] return serviceName in servicesList def getHostForComponent(self, component, hostsList): if len(hostsList) == 0: return None componentName = self.getComponentName(component) if len(hostsList) != 1: scheme = self.getComponentLayoutSchemes().get(componentName, None) if scheme is not None: hostIndex = next((index for key, index in scheme.iteritems() if isinstance(key, (int, long)) and len(hostsList) < key), scheme['else']) else: hostIndex = 0 for host in hostsList[hostIndex:]: if self.isHostSuitableForComponent(host, component): return host return hostsList[0] def getComponentName(self, component): return self.getComponentAttribute(component, "component_name") def isHostSuitableForComponent(self, host, component): return not (self.getComponentName(component) in self.getNotPreferableOnServerComponents() and self.isLocalHost(host)) def getMastersWithMultipleInstances(self): return self.mastersWithMultipleInstances def getNotValuableComponents(self): return self.notValuableComponents def getNotPreferableOnServerComponents(self): return self.notPreferableOnServerComponents def getCardinalitiesDict(self, hosts): return self.cardinalitiesDict def getComponentLayoutSchemes(self): """ Provides layout scheme dictionaries for components. The scheme dictionary basically maps the number of hosts to host index where component should exist. """ return self.componentLayoutSchemes def getWarnItem(self, message): """ Utility method used for validation warnings. """ return {"level": "WARN", "message": message} def getErrorItem(self, message): """ Utility method used for validation errors. """ return {"level": "ERROR", "message": message} def getNotApplicableItem(self, message): ''' Creates report about validation error that can not be ignored. UI should not allow the proceeding of work. :param message: error description. :return: report about error. ''' return {"level": "NOT_APPLICABLE", "message": message} def getComponentHostNames(self, servicesDict, serviceName, componentName): for service in servicesDict["services"]: if service["StackServices"]["service_name"] == serviceName: for component in service['components']: if component["StackServiceComponents"]["component_name"] == componentName: return component["StackServiceComponents"]["hostnames"] def recommendConfigurationDependencies(self, services, hosts): self.allRequestedProperties = self.getAllRequestedProperties(services) result = self.recommendConfigurations(services, hosts) return self.filterResult(result, services) # returns recommendations only for changed and depended properties def filterResult(self, result, services): allRequestedProperties = self.getAllRequestedProperties(services) self.filterConfigs(result['recommendations']['blueprint']['configurations'], allRequestedProperties) if "config-groups" in services: for configGroup in result['recommendations']["config-groups"]: self.filterConfigs(configGroup["configurations"], allRequestedProperties) self.filterConfigs(configGroup["dependent_configurations"], allRequestedProperties) return result def filterConfigs(self, configs, requestedProperties): filteredConfigs = {} for type, names in configs.items(): if 'properties' in names.keys(): for name in names['properties']: if type in requestedProperties.keys() and \ name in requestedProperties[type]: if type not in filteredConfigs.keys(): filteredConfigs[type] = {'properties': {}} filteredConfigs[type]['properties'][name] = \ configs[type]['properties'][name] if 'property_attributes' in names.keys(): for name in names['property_attributes']: if type in requestedProperties.keys() and \ name in requestedProperties[type]: if type not in filteredConfigs.keys(): filteredConfigs[type] = {'property_attributes': {}} elif 'property_attributes' not in filteredConfigs[type].keys(): filteredConfigs[type]['property_attributes'] = {} filteredConfigs[type]['property_attributes'][name] = \ configs[type]['property_attributes'][name] configs.clear() configs.update(filteredConfigs) def getAllRequestedProperties(self, services): affectedConfigs = self.getAffectedConfigs(services) allRequestedProperties = {} for config in affectedConfigs: if config['type'] in allRequestedProperties: allRequestedProperties[config['type']].append(config['name']) else: allRequestedProperties[config['type']] = [config['name']] return allRequestedProperties def getAffectedConfigs(self, services): """returns properties dict including changed-configurations and depended-by configs""" changedConfigs = services['changed-configurations'] changedConfigs = [{"type": entry["type"], "name": entry["name"]} for entry in changedConfigs] allDependencies = [] for item in services['services']: allDependencies.extend(item['configurations']) dependencies = [] size = -1 while size != len(dependencies): size = len(dependencies) for config in allDependencies: property = { "type": re.sub('\.xml$', '', config['StackConfigurations']['type']), "name": config['StackConfigurations']['property_name'] } if property in dependencies or property in changedConfigs: for dependedConfig in config['dependencies']: dependency = { "name": dependedConfig["StackConfigurationDependency"]["dependency_name"], "type": dependedConfig["StackConfigurationDependency"]["dependency_type"] } if dependency not in dependencies: dependencies.append(dependency) if "forced-configurations" in services and services["forced-configurations"] is not None: dependencies.extend(services["forced-configurations"]) return dependencies def versionCompare(self, version1, version2): def normalize(v): return [int(x) for x in re.sub(r'(\.0+)*$','', v).split(".")] return cmp(normalize(version1), normalize(version2)) pass def getSiteProperties(self, configurations, siteName): siteConfig = configurations.get(siteName) if siteConfig is None: return None return siteConfig.get("properties") def getServicesSiteProperties(self, services, siteName): if not services: return None configurations = services.get("configurations") if not configurations: return None siteConfig = configurations.get(siteName) if siteConfig is None: return None return siteConfig.get("properties") def putProperty(self, config, configType, services=None): userConfigs = {} changedConfigs = [] # if services parameter, prefer values, set by user if services: if 'configurations' in services.keys(): userConfigs = services['configurations'] if 'changed-configurations' in services.keys(): changedConfigs = services["changed-configurations"] if configType not in config: config[configType] = {} if"properties" not in config[configType]: config[configType]["properties"] = {} def appendProperty(key, value): # If property exists in changedConfigs, do not override, use user defined property if not self.isPropertyRequested(configType, key, changedConfigs) \ and configType in userConfigs and key in userConfigs[configType]['properties']: config[configType]["properties"][key] = userConfigs[configType]['properties'][key] else: config[configType]["properties"][key] = str(value) return appendProperty def __isPropertyInChangedConfigs(self, configType, propertyName, changedConfigs): for changedConfig in changedConfigs: if changedConfig['type']==configType and changedConfig['name']==propertyName: return True return False def isPropertyRequested(self, configType, propertyName, changedConfigs): # When the property depends on more than one property, we need to recalculate it based on the actual values # of all related properties. But "changed-configurations" usually contains only one on the dependent on properties. # So allRequestedProperties is used to avoid recommendations of other properties that are not requested. # Calculations should use user provided values for all properties that we depend on, not only the one that # came in the "changed-configurations". if self.allRequestedProperties: return configType in self.allRequestedProperties and propertyName in self.allRequestedProperties[configType] else: return not self.__isPropertyInChangedConfigs(configType, propertyName, changedConfigs) def updateProperty(self, config, configType, services=None): userConfigs = {} changedConfigs = [] # if services parameter, prefer values, set by user if services: if 'configurations' in services.keys(): userConfigs = services['configurations'] if 'changed-configurations' in services.keys(): changedConfigs = services["changed-configurations"] if configType not in config: config[configType] = {} if "properties" not in config[configType]: config[configType]["properties"] = {} def updatePropertyWithCallback(key, value, callback): # If property exists in changedConfigs, do not override, use user defined property if self.__isPropertyInChangedConfigs(configType, key, changedConfigs): config[configType]["properties"][key] = userConfigs[configType]['properties'][key] else: # Give the callback
<gh_stars>10-100 #!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """Stub version of the Task Queue API. This stub stores tasks and runs them via dev_appserver's AddEvent capability. It also validates the tasks by checking their queue name against the queue.yaml. As well as implementing Task Queue API functions, the stub exposes various other functions that are used by the dev_appserver's admin console to display the application's queues and tasks. """ from __future__ import with_statement __all__ = [] import base64 import bisect import calendar import datetime import logging import os import random import string import threading import time import taskqueue_service_pb import taskqueue from google.appengine.api import api_base_pb from google.appengine.api import apiproxy_stub from google.appengine.api import apiproxy_stub_map from google.appengine.api import queueinfo from google.appengine.api import request_info from google.appengine.api.taskqueue import taskqueue from google.appengine.runtime import apiproxy_errors DEFAULT_RATE = '5.00/s' DEFAULT_RATE_FLOAT = 5.0 DEFAULT_BUCKET_SIZE = 5 MAX_ETA = datetime.timedelta(days=30) MAX_PULL_TASK_SIZE_BYTES = 2 ** 20 MAX_PUSH_TASK_SIZE_BYTES = 100 * (2 ** 10) MAX_TASK_SIZE = MAX_PUSH_TASK_SIZE_BYTES MAX_REQUEST_SIZE = 32 << 20 BUILT_IN_HEADERS = set(['x-appengine-queuename', 'x-appengine-taskname', 'x-appengine-taskexecutioncount', 'x-appengine-taskpreviousresponse', 'x-appengine-taskretrycount', 'x-appengine-tasketa', 'x-appengine-development-payload', 'content-length']) DEFAULT_QUEUE_NAME = 'default' INF = 1e500 QUEUE_MODE = taskqueue_service_pb.TaskQueueMode AUTOMATIC_QUEUES = { DEFAULT_QUEUE_NAME: (0.2, DEFAULT_BUCKET_SIZE, DEFAULT_RATE), '__cron': (1, 1, '1/s')} def _GetAppId(request): """Returns the app id to use for the given request. Args: request: A protocol buffer that has an app_id field. Returns: A string containing the app id or None if no app id was specified. """ if request.has_app_id(): return request.app_id() else: return None def _SecToUsec(t): """Converts a time in seconds since the epoch to usec since the epoch. Args: t: Time in seconds since the unix epoch Returns: An integer containing the number of usec since the unix epoch. """ return int(t * 1e6) def _UsecToSec(t): """Converts a time in usec since the epoch to seconds since the epoch. Args: t: Time in usec since the unix epoch Returns: A float containing the number of seconds since the unix epoch. """ return t / 1e6 def _FormatEta(eta_usec): """Formats a task ETA as a date string in UTC.""" eta = datetime.datetime.utcfromtimestamp(_UsecToSec(eta_usec)) return eta.strftime('%Y/%m/%d %H:%M:%S') def _TruncDelta(timedelta): """Strips the microseconds field from a timedelta. Args: timedelta: a datetime.timedelta. Returns: A datetime.timedelta with the microseconds field not filled. """ return datetime.timedelta(days=timedelta.days, seconds=timedelta.seconds) def _EtaDelta(eta_usec, now): """Formats a task ETA as a relative time string.""" eta = datetime.datetime.utcfromtimestamp(_UsecToSec(eta_usec)) if eta > now: return '%s from now' % _TruncDelta(eta - now) else: return '%s ago' % _TruncDelta(now - eta) def QueryTasksResponseToDict(queue_name, task_response, now): """Converts a TaskQueueQueryTasksResponse_Task protobuf group into a dict. Args: queue_name: The name of the queue this task came from. task_response: An instance of TaskQueueQueryTasksResponse_Task. now: A datetime.datetime object containing the current time in UTC. Returns: A dict containing the fields used by the dev appserver's admin console. Raises: ValueError: A task response contains an unknown HTTP method type. """ task = {} task['name'] = task_response.task_name() task['queue_name'] = queue_name task['url'] = task_response.url() method = task_response.method() if method == taskqueue_service_pb.TaskQueueQueryTasksResponse_Task.GET: task['method'] = 'GET' elif method == taskqueue_service_pb.TaskQueueQueryTasksResponse_Task.POST: task['method'] = 'POST' elif method == taskqueue_service_pb.TaskQueueQueryTasksResponse_Task.HEAD: task['method'] = 'HEAD' elif method == taskqueue_service_pb.TaskQueueQueryTasksResponse_Task.PUT: task['method'] = 'PUT' elif method == taskqueue_service_pb.TaskQueueQueryTasksResponse_Task.DELETE: task['method'] = 'DELETE' else: raise ValueError('Unexpected method: %d' % method) task['eta'] = _FormatEta(task_response.eta_usec()) task['eta_usec'] = task_response.eta_usec() task['eta_delta'] = _EtaDelta(task_response.eta_usec(), now) task['body'] = base64.b64encode(task_response.body()) headers = [(header.key(), header.value()) for header in task_response.header_list() if header.key().lower() not in BUILT_IN_HEADERS] headers.append(('X-AppEngine-QueueName', queue_name)) headers.append(('X-AppEngine-TaskName', task_response.task_name())) headers.append(('X-AppEngine-TaskRetryCount', str(task_response.retry_count()))) headers.append(('X-AppEngine-TaskETA', str(_UsecToSec(task_response.eta_usec())))) headers.append(('X-AppEngine-Development-Payload', '1')) headers.append(('Content-Length', str(len(task['body'])))) if 'content-type' not in frozenset(key.lower() for key, _ in headers): headers.append(('Content-Type', 'application/octet-stream')) headers.append(('X-AppEngine-TaskExecutionCount', str(task_response.execution_count()))) if task_response.has_runlog() and task_response.runlog().has_response_code(): headers.append(('X-AppEngine-TaskPreviousResponse', str(task_response.runlog().response_code()))) task['headers'] = headers return task class _Group(object): """A taskqueue group. This class contains all of the queues for an application. """ def __init__(self, queue_yaml_parser=None, app_id=None, _all_queues_valid=False, _update_newest_eta=None, _testing_validate_state=False): """Constructor. Args: queue_yaml_parser: A function that takes no parameters and returns the parsed results of the queue.yaml file. If this queue is not based on a queue.yaml file use None. app_id: The app id this Group is representing or None if it is the currently running application. _all_queues_valid: Automatically generate queues on first access. _update_newest_eta: Callable for automatically executing tasks. Takes the ETA of the task in seconds since the epoch, the queue_name and a task name. May be None if automatic task running is disabled. _testing_validate_state: Should this _Group and all of its _Queues validate their state after each operation? This should only be used during testing of the taskqueue_stub. """ self._queues = {} self._queue_yaml_parser = queue_yaml_parser self._all_queues_valid = _all_queues_valid self._next_task_id = 1 self._app_id = app_id if _update_newest_eta is None: self._update_newest_eta = lambda x: None else: self._update_newest_eta = _update_newest_eta self._testing_validate_state = _testing_validate_state def GetQueuesAsDicts(self): """Gets all the applications's queues. Returns: A list of dictionaries, where each dictionary contains one queue's attributes. E.g.: [{'name': 'some-queue', 'max_rate': '1/s', 'bucket_size': 5, 'oldest_task': '2009/02/02 05:37:42', 'eta_delta': '0:00:06.342511 ago', 'tasks_in_queue': 12, 'acl': ['<EMAIL>']}, ...] The list of queues always includes the default queue. """ self._ReloadQueuesFromYaml() now = datetime.datetime.utcnow() queues = [] for queue_name, queue in sorted(self._queues.items()): queue_dict = {} queues.append(queue_dict) queue_dict['name'] = queue_name queue_dict['bucket_size'] = queue.bucket_capacity if queue.user_specified_rate is not None: queue_dict['max_rate'] = queue.user_specified_rate else: queue_dict['max_rate'] = '' if queue.queue_mode == QUEUE_MODE.PULL: queue_dict['mode'] = 'pull' else: queue_dict['mode'] = 'push' queue_dict['acl'] = queue.acl oldest_eta = queue.Oldest() if oldest_eta: queue_dict['oldest_task'] = _FormatEta(oldest_eta) queue_dict['eta_delta'] = _EtaDelta(oldest_eta, now) else: queue_dict['oldest_task'] = '' queue_dict['eta_delta'] = '' queue_dict['tasks_in_queue'] = queue.Count() if queue.retry_parameters: retry_proto = queue.retry_parameters retry_dict = {} if retry_proto.has_retry_limit(): retry_dict['retry_limit'] = retry_proto.retry_limit() if retry_proto.has_age_limit_sec(): retry_dict['age_limit_sec'] = retry_proto.age_limit_sec() if retry_proto.has_min_backoff_sec(): retry_dict['min_backoff_sec'] = retry_proto.min_backoff_sec() if retry_proto.has_max_backoff_sec(): retry_dict['max_backoff_sec'] = retry_proto.max_backoff_sec() if retry_proto.has_max_doublings(): retry_dict['max_doublings'] = retry_proto.max_doublings() queue_dict['retry_parameters'] = retry_dict return queues def HasQueue(self, queue_name): """Check if the specified queue_name references a valid queue. Args: queue_name: The name of the queue to check. Returns: True if the queue exists, False otherwise. """ self._ReloadQueuesFromYaml() return queue_name in self._queues and ( self._queues[queue_name] is not None) def GetQueue(self, queue_name): """Gets the _Queue instance for the specified queue. Args: queue_name: The name of the queue to fetch. Returns: The _Queue instance for the specified queue. Raises: KeyError if the queue does not exist. """ self._ReloadQueuesFromYaml() return self._queues[queue_name] def GetNextPushTask(self): """Finds the task with the lowest eta. Returns: A tuple containing the queue and task instance for the task with the lowest eta, or (None, None) if there are no tasks. """ min_eta = INF result = None, None for queue in self._queues.itervalues(): if queue.queue_mode == QUEUE_MODE.PULL: continue task = queue.OldestTask() if not task: continue if task.eta_usec() < min_eta: result = queue, task min_eta = task.eta_usec() return result def _ConstructQueue(self, queue_name, *args, **kwargs): if '_testing_validate_state' in kwargs: raise TypeError( '_testing_validate_state should not be passed to _ConstructQueue') kwargs['_testing_validate_state'] = self._testing_validate_state self._queues[queue_name] = _Queue(queue_name, *args, **kwargs) def _ConstructAutomaticQueue(self, queue_name): if queue_name in AUTOMATIC_QUEUES: self._ConstructQueue(queue_name, *AUTOMATIC_QUEUES[queue_name]) else: assert self._all_queues_valid self._ConstructQueue(queue_name) def _ReloadQueuesFromYaml(self): """Update the queue map with the contents of the queue.yaml file. This function will remove queues that no longer exist in the queue.yaml file. If no queue yaml parser has been defined, this function is a no-op. """ if not self._queue_yaml_parser: return queue_info = self._queue_yaml_parser() if queue_info and queue_info.queue: queues = queue_info.queue else: queues = [] old_queues = set(self._queues) new_queues = set() for entry in queues: queue_name = entry.name new_queues.add(queue_name) retry_parameters = None if entry.bucket_size: bucket_size = entry.bucket_size else: bucket_size = DEFAULT_BUCKET_SIZE if entry.retry_parameters: retry_parameters = queueinfo.TranslateRetryParameters( entry.retry_parameters) if entry.mode == 'pull': mode = QUEUE_MODE.PULL if entry.rate is not None: logging.warning( 'Refill rate must not be specified for pull-based queue. ' 'Please check queue.yaml file.') else: mode = QUEUE_MODE.PUSH if entry.rate is None: logging.warning( 'Refill rate must be specified for push-based queue. ' 'Please check queue.yaml file.') max_rate = entry.rate if entry.acl is not None: acl = taskqueue_service_pb.TaskQueueAcl() for acl_entry in entry.acl: acl.add_user_email(acl_entry.user_email) else: acl = None if self._queues.get(queue_name) is None:
#!/usr/bin/python3 import os import sys import json import argparse import subprocess from PIL import Image, ImageOps from glob import glob animSize = 65536 srcdir = os.path.dirname(os.path.abspath(__file__)) ldsfile = os.path.join(srcdir,'animation.lds') # The list of animations to build. animations = ['marquee-image', 'lineface', 'djmode', 'mic-test', 'matrix', 'missingno', 'northern-lights', 'lightning-voice', 'rainbow-grin'] # The list of JSON animations to build. jsdir = os.path.join(srcdir, 'json') jsanimations = glob(os.path.join(jsdir, '*.json')) CFLAGS = ['-Os', '-march=rv32i', '-mabi=ilp32', '-I', srcdir] CFLAGS += ['-ffunction-sections', '-fdata-sections', '--specs=nano.specs'] CFLAGS += ['-D', '_POSIX_TIMERS', '-D', '_POSIX_MONOTONIC_CLOCK=200112L'] ####################################### ## Locate Toolchain Paths ####################################### if os.name=='nt': platformio_rel = '.platformio\\packages' #pio_rel = '.platformio\\packages\\toolchain-icestorm\\bin' home_path = os.getenv('HOMEPATH') # Build the full path to risc-v tools platformio = os.path.join(home_path, platformio_rel) # Tools used in the flow gcc = os.path.join(platformio, 'toolchain-riscv\\bin\\riscv64-unknown-elf-gcc.exe') objcopy = os.path.join(platformio, 'toolchain-riscv\\bin\\riscv64-unknown-elf-objcopy.exe') objdump = os.path.join(platformio, 'toolchain-riscv\\bin\\riscv64-unknown-elf-objdump.exe') else: pio_rel = '.platformio/packages/' pio = os.path.join(os.environ['HOME'], pio_rel) # Use PlatformIO, if it exists. if os.path.exists(pio): gcc = os.path.join(pio, 'toolchain-riscv/bin/riscv64-unknown-elf-gcc') objcopy = os.path.join(pio, 'toolchain-riscv/bin/riscv64-unknown-elf-objcopy') # Otherwise, assume the tools are in the PATH. else: gcc = 'riscv64-unknown-elf-gcc' objcopy = 'riscv64-unknown-elf-objcopy' ####################################### ## Check if Recompilation is Needed ####################################### def check_rebuild(*args, target): """Checks if the firmware needs to be rebuilt. Args: target (string): Name of the target to be built. *args (string): All of the dependencies of the target. Returns: True if the target needs to be rebuilt, and False otherwise. """ if not os.path.exists(target): return True targetTime = os.path.getmtime(target) if (os.path.getmtime(__file__) > targetTime): return True for dep in args: if (os.path.getmtime(dep) > targetTime): return True return False ####################################### ## Compile a Single Source File ####################################### def filename_to_cname(name): return "".join([ch if ch.isalnum() else '_' for ch in name]) def js_to_frame(frame, name, fp): fstruct = "const struct framebuf __attribute__((section(\".frames\"))) %s = { .data = {" % name fp.write(fstruct.encode('utf-8')) ## 8-bit RGB format if 'rgb' in frame: for line in frame['rgb'].split(":"): fp.write("\n ".encode('utf-8')) pxdata = bytearray.fromhex(line) for i in range(0,32): try: r = (pxdata[i] & 0xE0) << 8 g = (pxdata[i] & 0x1C) << 6 b = (pxdata[i] & 0x03) << 3 except Exception as e: r = 0 g = 0 b = 0 pxstr = " 0x%04x," % (r | g | b) fp.write(pxstr.encode('utf-8')) ## Xterm Pallette format elif 'palette' in frame: palette = [ 0x0000, # Black 0x8000, # Maroon 0x0400, # Green 0x8400, # Olive 0x0010, # Navy 0x8010, # Purple 0x0410, # Teal 0xC618, # Silver 0x8410, # Grey 0xF800, # Red 0x07E0, # Lime 0xFFE0, # Yellow 0x001F, # Blue 0xF81F, # Fuchsia 0x07FF, # Aqua 0xFFFF, # White ] for line in frame['palette'].split(":"): fp.write("\n ".encode('utf-8')) for i in range(0,32): try: ch = line[i] pixel = palette[int(ch, base=16)] except Exception as e: pixel = 0x0000 pxstr = " 0x%04x," % pixel fp.write(pxstr.encode('utf-8')) ftail = "\n}}; /* %s */\n\n" % name fp.write(ftail.encode('utf-8')) def compile(target, source): """Compile a single source. Args: target (string): Name of the output file to be generated. source (string): Name of the source file to be compiled. """ ext = os.path.splitext(source)[1] if (ext == '.c' or ext == '.s'): print(" Compiling [" + os.path.basename(source) + "]") subprocess.check_call([gcc] + CFLAGS + ['-c', '-o', target, source], stderr=subprocess.STDOUT) return if ext == '.json': # Parse the JSON file. with open(source) as jsfile: frames = json.load(jsfile) # Output the JSON animation data and compile it. print(" Rendering [" + os.path.basename(source) + "]") with subprocess.Popen([gcc] + CFLAGS + ['-c', '-o', target, '-xc', '-'], stderr=subprocess.STDOUT, stdin=subprocess.PIPE) as p: #with subprocess.Popen(["sed", "-n", "w %s" % target], stderr=subprocess.STDOUT, stdin=subprocess.PIPE) as p: boilerplate = "/* Generated by make.py from %s */\n" % os.path.basename(source) boilerplate += "#include <stdint.h>\n" boilerplate += "#include <stdlib.h>\n" boilerplate += "#include <badge.h>\n\n" boilerplate += "const char *json_name = \"%s\";\n\n" % os.path.splitext(os.path.basename(source))[0] p.stdin.write(boilerplate.encode('utf-8')) # Render the frames into a framebuf structure. frameno = 0 for f in frames: js_to_frame(f, "frame%u" % frameno, p.stdin) frameno += 1 # And output the animation schedule. p.stdin.write("const struct frame_schedule schedule[] = {\n".encode('utf-8')) frameno = 0 for f in frames: interval = int(f['interval']) * 1000 schedule = " { .interval = %u, .frame = &frame%u},\n" % (interval, frameno) p.stdin.write(schedule.encode('utf-8')) frameno += 1 p.stdin.write(" { 0, NULL }\n".encode('utf-8')) p.stdin.write("}; /* schedule */\n\n".encode('utf-8')) return if ext in ('.png', '.jpg', '.jpeg'): frame = Image.open(source) if not "_fullframe." in source: frame.resize((20,14)) frame = ImageOps.pad(frame, (32,14), centering=(0,0)) print(" Rendering [" + os.path.basename(source) + "]") with subprocess.Popen([gcc] + CFLAGS + ['-c', '-o', target, '-xc', '-'], stderr=subprocess.STDOUT, stdin=subprocess.PIPE) as p: if not "_fullframe." in source: boilerplate = """ /* Generated by make.py */ #include <stdint.h> #include <badge.h> const struct framebuf __attribute__((section(".frames"))) %s = { .data = { """ % (filename_to_cname(os.path.basename(source))) tail = "}};" else: image_width = frame.size[0] boilerplate = """ /* Generated by make.py */ #include <stdint.h> #include <badge.h> const int %s_width = %d; const uint16_t __attribute__((section(".frames"))) %s[] = { """ % (filename_to_cname(os.path.basename(source)), image_width, filename_to_cname(os.path.basename(source))) tail = "};" p.stdin.write(boilerplate.encode('utf-8')) for pixel in list(frame.getdata()): r = (pixel[0] >> 3) & 0x1F g = (pixel[1] >> 2) & 0x3F b = (pixel[2] >> 3) & 0x1F line = " 0x%04x," % ((r << 11) | (g << 5) | b) p.stdin.write(line.encode('utf-8')) p.stdin.write(tail.encode('utf-8')) p.stdin.close() return # Otherwise, we don't understand this file type. raise Exception("Unknown file type for " + os.path.basename(source)) ####################################### ## Recompile the BIOS ####################################### def buildrom(name): """Rebuild the badge BIOS BIOS sources will be found at srcdir/name, where srcdir is the location of the make.py script. Compiled files will be generated in $(pwd)/name, and the output animation file will be at $(pwd)/name/name.bin Args: name (string): Name of the bios to be build. """ # Assemble the list of sources for this animation. biosdir = os.path.join(srcdir, name) objdir = name sources = glob(os.path.join(biosdir, '*.c')) sources += glob(os.path.join(biosdir, '*.s')) objects = [] # Firmware target image(s) should match the dirname. elf_target = os.path.join(objdir, name + '.elf') bin_target = os.path.join(objdir, name + '.bin') print("BIOS [" + os.path.basename(bin_target) + "] ", end='') if not check_rebuild(*sources, ldsfile, target=bin_target): print("is up to date") return else: print("building...") # Create the output directory, if it doesn't already exist. if not os.path.exists(objdir): os.mkdir(objdir) # Rebuild each source into an object file. for srcfile in sources: (root, ext) = os.path.splitext(srcfile) objfile = root + '.o' compile(objfile, srcfile) objects.append(objfile) # Link the BIOS together. LDFLAGS = ['-Wl,-Bstatic,-T,%s,--gc-sections' % glob(os.path.join(biosdir, '*.lds'))[0]] print(" Linking [" + os.path.basename(elf_target) + "]") if subprocess.call([gcc] + CFLAGS + LDFLAGS + ['-o', elf_target] + objects, stderr=subprocess.STDOUT) != 0: return # Convert to a binary file. print(" Packing [" + os.path.basename(bin_target) + "]") if subprocess.call([objcopy, '-O', 'binary', elf_target, bin_target], stderr=subprocess.STDOUT) != 0: return ####################################### ## Recompile Animations ####################################### def build(name): """Rebuild a single animation. Animation sources will be found at srcdir/name, where srcdir is the location of the make.py script. Compiled files will be generated in $(pwd)/name, and the output animation file will be at $(pwd)/name/name.bin Args: name (string): Name of the animation to be build. """ # Assemble the list of sources for this animation. animdir = os.path.join(srcdir, name) objdir = name sources = [os.path.join(srcdir, 'syscalls.c')] sources += [os.path.join(srcdir, 'framebuf.c')] #sources += [os.path.join(srcdir, 'muldiv.c')] sources += glob(os.path.join(animdir, '*.c')) sources += glob(os.path.join(animdir, '*.s')) sources += glob(os.path.join(animdir, '*.png')) sources += glob(os.path.join(animdir, '*.jpg')) sources += glob(os.path.join(animdir, '*.jpeg')) objects = [] # Firmware target image(s) should match the dirname. elf_target = os.path.join(objdir, name + '.elf') bin_target = os.path.join(objdir, name + '.bin') print("Animation [" + os.path.basename(bin_target) + "] ", end='') if not check_rebuild(*sources, ldsfile, target=bin_target): print("is up to date") return else: print("building...") # Create the output directory, if it doesn't already exist. if not os.path.exists(objdir): os.mkdir(objdir) # Rebuild each source into an object file. for srcfile in sources: (root, ext) = os.path.splitext(srcfile) objfile = root + '.o' compile(objfile, srcfile) objects.append(objfile) # Link the animation together. LDFLAGS = ['-Wl,-Bstatic,-T,%s,--gc-sections' % ldsfile] print(" Linking [" + os.path.basename(elf_target) + "]") if subprocess.call([gcc] + CFLAGS + LDFLAGS + ['-o', elf_target] + objects, stderr=subprocess.STDOUT) != 0: return # Convert to a binary file. print(" Packing [" + os.path.basename(bin_target) + "]") if subprocess.call([objcopy, '-O', 'binary', elf_target, bin_target], stderr=subprocess.STDOUT) != 0: return ####################################### ## Recompile JSON Animations ####################################### def buildjson(jsfile): """Rebuild a single animation from JSON syntax.
<reponame>ProKil/OS2018spring-projects-g10 ===== output.py ================================================== uint64_t = int def Or(a, b): return a | b def USub(a, b): return a - b def Concat32(a, b): return (a << 32) | b def If(cond, a, b): if cond: return a return b def Extract(hi, lo, val): return val >> lo & ((1 << (hi - lo + 1)) - 1) def And(a=1, b=1, c=1): return (a and b) and c def ULT(a, b): return a < b class Block: def __setitem__(self, key, val): pass def __getitem__(self, key): pass def set(self, key, val): pass def get(self, key): pass def ConstBlock(val): return Block() class PartitionAsyncDisk: def write(self, blknum, block, cond=1): pass def read(self, blknum): return Block() def flush(self): pass class PartitionAsyncDiskList: def __len__(self): return 10 def __getitem__(self, key): return PartitionAsyncDisk() class TripleList: def setNone(self, _is_none): pass def isNone(self): pass def isNotNone(self): pass def clear(self): pass def length(self): return 10 def append_triple(self, dev, bid, data): pass def get_dev(self, idx): pass def get_bid(self, idx): pass def get_data(self, idx): pass def copy(self): pass def __len__(self): return 10 class CacheDict: def get3(self, dev, bid, dresult): return dresult def set3(self, dev, bid, data): pass uint64_t = int class WALDisk: LOG_MAX_ENTRIES = None def __init__(self, logdisk, datadisks, osync=True): pass def begin_tx(self): pass def write_tx(self, dev, bid, data): pass def write(self, dev, bid, data): pass def flush(self): pass def commit_tx(self, force=False): pass def writev(self, ): pass def __commit(self): pass def read(self, dev, bid): pass def _read(self, dev, bid): pass def __recover(self): pass class Disk: def __init__(self, _dev, _txndisk): pass def read(self, bid): pass def write(self, bid, data): pass class Allocator64: def __init__(self, _txndisk, _dev, _start, _end): pass def alloc(self): pass class Bitmap: def __init__(self, _disk): pass def is_set(self, lbn): pass def set_bit(self, lbn): pass def unset_bit(self, lbn): pass def mkfs(self): pass class Stat: def __init__(self, size, mtime, mode, nlink): pass class InodePack: def __init__(self, _inodemeta, inodedata): pass def get_iattr(self, ino): pass def set_iattr(self, ino, attr): pass def get_mapping(self, ino, eoff, block=0): pass def set_mapping(self, ino, off, ptr, block=0): pass def read(self, ino): pass def mkfs(self): pass class InodeDisk: FREEDISK = None INODEMETADISK = None INODEDATADISK = None DATADISK = None NDIRECT = None def __init__(self, txndisk): pass def begin_tx(self): pass def commit_tx(self): pass def get_iattr(self, ino): pass def set_iattr(self, ino, attr): pass def read(self, lbn): pass def write_tx(self, lbn, data): pass def write(self, lbn, data): pass def mappingi(self, vbn): pass def is_mapped(self, vbn): pass def is_free(self, vbn): pass def alloc(self): pass def free(self, lbn): pass def bmap(self, vbn): pass def bunmap(self, vbn): pass def mkfs(self): pass class IndirectInodeDisk: NINDIRECT = None def __init__(self, idisk): pass def begin_tx(self): pass def commit_tx(self): pass def get_iattr(self, ino): pass def set_iattr(self, ino, attr): pass def read(self, lbn): pass def write_tx(self, lbn, data): pass def write(self, lbn, data): pass def mappingi(self, vbn): pass def is_mapped(self, vbn): pass def is_free(self, vbn): pass def bmap(self, vbn): pass def bunmap(self, vbn): pass class errno: ENOSPC = None ENOENT = None ENOTDIR = None ENOSPC = None ENOENT = None ENOTDIR = None class Allocator32: def __init__(self, _disk, _start, _end): pass def alloc(self): pass class Orphans: def __init__(self, orphandisk): self._orphandisk = orphandisk def size(self): return self._orphandisk.read(0).__getitem__(0) def index(self, idx): orphanblock = self._orphandisk.read(0) n = orphanblock.__getitem__(0) assertion(0 <= n) assertion(n < 511) np = Extract(8, 0, idx) return orphanblock.__getitem__(np + 1) def reset(self): self._orphandisk.write(0, ConstBlock(0)) def clear(self, idx): orphanblock = self._orphandisk.read(0) np = Extract(8, 0, idx) orphanblock.__setitem__(np, 0) self._orphandisk.write(0, orphanblock) def append(self, value): orphanblock = self._orphandisk.read(0) n = orphanblock.__getitem__(0) assertion(0 <= n) assertion(n < 511) np = Extract(8, 0, n) orphanblock.__setitem__(np + 1, value) orphanblock.__setitem__(0, n + 1) self._orphandisk.write(0, orphanblock) class MyPIno: def __init__(self, _inode): self.inode = _inode def is_mapped(self, vbn, _inode=0): if _inode == 0: return self.inode.is_mapped(vbn) return _inode.is_mapped(vbn) def mappingi(self, vbn, _inode=0): if _inode == 0: return self.inode.mappingi(vbn) return _inode.mappingi(vbn) def read(self, bid, _inode=0): if _inode == 0: return self.inode.read(bid) return _inode.read(bid) def bmap(self, bid, _inode=0): if _inode == 0: return self.inode.bmap(bid) return _inode.bmap(bid) class Tuple2: def __init__(self, _a, _b): pass def __getitem__(self, idx): pass class Tuple3: def __init__(self, block, _bid, _off): pass def get_bid(self): pass def get_off(self): pass def get_block(self): pass class Tuple4: def __init__(self, block, _bid, _off, _valid): pass def get_bid(self): pass def get_off(self): pass def get_block(self): pass def get_valid(self): pass class NameType: def __getitem__(self, idx): pass class DirLook: def __init__(self, pino): pass def locate_dentry_ino(self, ino, name): pass def locate_empty_slot_ino(self, ino): pass class DirImpl: NBLOCKS = None IFREEDISK = None ORPHANS = None def __init__(self, txndisk, inode): self._txndisk = txndisk self._inode = inode self._dirlook = DirLook(MyPIno(inode)) self._ifree = Disk(DirImpl.IFREEDISK, self._txndisk) orphandisk = Disk(DirImpl.ORPHANS, self._txndisk) self._iallocator = Allocator32(self._ifree, 0, 1024) self._ibitmap = Bitmap(self._ifree) self._orphans = Orphans(orphandisk) def locate_dentry_ino(self, ino, name): tuple = self._dirlook.locate_dentry_ino(ino, name) ioff = tuple.__getitem__(0) off = tuple.__getitem__(1) assertion(ULT(ioff, 522)) assertion(ioff != 10) bid = self._inode.bmap(Concat32(ino, ioff)) block = self._inode.read(bid) valid = And(bid != 0, off % 16 == 0, Extract(31, 0, block.__getitem__(off)) != 0) i = 0 while i < 15: valid = And(valid, block.__getitem__(off + i + 1) == name.__getitem__(i)) i += 1 return Tuple4(block, bid, off, valid) def locate_empty_dentry_slot_ino(self, ino): tuple = self._dirlook.locate_empty_slot_ino(ino) ioff = tuple.__getitem__(0) off = tuple.__getitem__(1) assertion(ULT(ioff, 522)) assertion(ioff != 10) bid = self._inode.bmap(Concat32(ino, ioff)) block = self._inode.read(bid) assertion(bid != 0) assertion(off % 16 == 0) assertion(block.__getitem__(off) == 0) return Tuple3(block, bid, off) def locate_empty_dentry_slot_err_ino(self, ino): tuple = self._dirlook.locate_empty_slot_ino(ino) ioff = tuple.__getitem__(0) off = tuple.__getitem__(1) assertion(ULT(ioff, 522)) assertion(ioff != 10) bid = self._inode.bmap(Concat32(ino, ioff)) block = self._inode.read(bid) return Tuple4(block, bid, off, And(bid != 0, off % 16 == 0, block.__getitem__(off) == 0)) def write_dentry(self, block, off, ino, name): block.__setitem__(off, ino) i = 0 while i < 15: block.__setitem__(off + i + 1, name.__getitem__(i)) i += 1 def clear_dentry(self, block, off): i = 0 while i < 16: block.__setitem__(off + i, 0) i += 1 def ialloc(self): ino = self._iallocator.alloc() assertion(ino != 0) assertion(self.is_ifree(ino)) self._ibitmap.set_bit(ino) return ino def is_ifree(self, ino): return Not(self._ibitmap.is_set(ino)) def is_valid(self, ino): return And(ino != 0, self._ibitmap.is_set(ino), UGT(self.get_iattr(ino).nlink, 0)) def is_gcable(self, ino): return And(ino != 0, self._ibitmap.is_set(ino), self.get_iattr(ino).nlink == 0) def is_dir(self, ino): attr = self._inode.get_iattr(ino) return And(self.is_valid(ino), (attr.mode & S_IFDIR) != 0) def is_regular(self, ino): attr = self._inode.get_iattr(ino) return And(self.is_valid(ino), (attr.mode & S_IFDIR) == 0) def get_iattr(self, ino): return self._inode.get_iattr(ino) def set_iattr(self, ino, attr): self._inode.begin_tx() self._inode.set_iattr(ino, attr) self._inode.commit_tx() def read(self, ino, blocknum): attr = self.get_iattr(ino) bsize = attr.bsize is_mapped = self._inode.is_mapped(Concat32(ino, blocknum)) lbn = self._inode.mappingi(Concat32(ino, blocknum)) res = self._inode.read(lbn) zeroblock = ConstBlock(0) return If(And(is_mapped, ULT(blocknum, bsize)), res, zeroblock) def truncate(self, ino, fsize): target_bsize = fsize / 4096 + (fsize % 4096 != 0) attr = self._inode.get_iattr(ino) while attr.bsize > target_bsize: self._inode.begin_tx() self._inode.bunmap(Concat32(ino, attr.bsize - 1)) attr.size = Concat32(attr.bsize - 1, fsize) self._inode.set_iattr(ino, attr) self._inode.commit_tx() if attr.fsize > fsize: self._inode.begin_tx() attr.size = Concat32(attr.bsize, fsize) self._inode.set_iattr(ino, attr) self._inode.commit_tx() def write(self, ino, blocknum, v, size=BitVecVal(4096, 32)): assertion(ULT(blocknum, 522)) assertion(ULT(BitVecVal(0, 32), size)) assertion(ULE(size, BitVecVal(4096, 32))) assertion(self.is_regular(ino)) self._inode.begin_tx() bid = self._inode.bmap(Concat32(ino, blocknum)) self._inode.write(bid, v) attr = self._inode.get_iattr(ino) nsize = Concat32(blocknum + 1, blocknum * 4096 + size) update = ULE(attr.fsize, blocknum * 4096 + size) attr.size = If(update, nsize, attr.size) self._inode.set_iattr(ino, attr) self._inode.commit_tx() return size def lookup(self, parent, name): assertion(self.is_dir(parent)) self._inode.begin_tx() tp = self.locate_dentry_ino(parent, name) parent_block = tp.get_block() off = tp.get_off() valid = tp.get_valid() self._inode.commit_tx() return If(valid, Extract(31, 0, parent_block.__getitem__(off)), 0) def mknod(self, parent, name, mode, mtime): assertion(self.is_dir(parent)) assertion(name.__getitem__(0) != 0) self._inode.begin_tx() tp = self.locate_empty_dentry_slot_err_ino(parent) parent_block = tp.get_block() parent_bid = tp.get_bid() off = tp.get_off() valid = tp.get_valid() if Not(valid): self._inode.commit_tx() return Tuple2(0, errno.ENOSPC) ino = self.ialloc() attr = Stat(0, mtime, mode, 2) self._inode.set_iattr(ino, attr) attr = self._inode.get_iattr(parent) assertion(ULE(attr.bsize, 522)) attr.size = Concat32(BitVecVal(522, 32), BitVecVal(4096 * 522, 32)) assertion(ULT(attr.nlink, attr.nlink + 1)) attr.nlink += 1 self._inode.set_iattr(parent, attr) self.write_dentry(parent_block, off, ino, name) parent_block.__setitem__(off, ino) self._inode.write(parent_bid, parent_block) self._inode.commit_tx() return Tuple2(ino, 0) def unlink(self, parent, name): assertion(self.is_dir(parent)) assertion(name.__getitem__(0) != 0) self._inode.begin_tx() tp = self.locate_dentry_ino(parent, name) parent_block = tp.get_block() parent_bid = tp.get_bid() off = tp.get_off() valid = tp.get_valid() assertion(valid) attr = self._inode.get_iattr(parent) assertion(UGE(attr.nlink, 2)) attr.nlink -= 1 self._inode.set_iattr(parent, attr) ino = Extract(31, 0, parent_block.__getitem__(off)) attr = self._inode.get_iattr(ino) attr.nlink = 1 self._inode.set_iattr(ino, attr) self.clear_dentry(parent_block, off) self._inode.write(parent_bid, parent_block) self._orphans.append(Extend(ino, 64)) self._inode.commit_tx() return ino def rmdir(self, parent,
<gh_stars>1-10 import cv2 import numpy as np import pylab from keras.models import Sequential from keras.layers import Dense from keras.models import model_from_json import skimage from skimage import io import matplotlib.pyplot as plt from skimage import transform from skimage.morphology import skeletonize_3d import scipy from scipy.ndimage.filters import gaussian_filter #from __future__ import print_function import keras from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, Dropout from keras.optimizers import RMSprop from keras.models import load_model from keras.layers.normalization import BatchNormalization import sklearn import numpy as np from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling1D, Conv1D, BatchNormalization ## Read input image img = input("Please enter name of sudoku image file: ") img = cv2.imread(img) st = input("Is this image digitally rendered (y/n)?") ## This function isolates the board (if it is not digitally rendered) ## and returns the isolated image def func(img, st): if (st=="y"): return img else: ## Manipulation, most of this comes from http://stackoverflow.com/questions/10196198/how-to-remove-convexity-defects-in-a-sudoku-square/11366549#11366549 ## but it doesn't work out of the box and required manipulation img = cv2.GaussianBlur(img,(5,5),0) gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) mask = np.zeros((gray.shape),np.uint8) kernel1 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(11,11)) close = cv2.morphologyEx(gray,cv2.MORPH_CLOSE,kernel1) div = np.float32(gray)/(close) res = np.uint8(cv2.normalize(div,div,0,255,cv2.NORM_MINMAX)) res2 = cv2.cvtColor(res,cv2.COLOR_GRAY2BGR) ## Testing output image below #pylab.imshow(res2,cmap="gray") #pylab.show() ## Find contours thresh = cv2.adaptiveThreshold(res,250,0,1,19,2) im,contour,hier = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) ## Find contour with the maximum area max_area = 0 best_cnt = None for cnt in contour: area = cv2.contourArea(cnt) if area > 1000: peri = cv2.arcLength(cnt,True) approx = cv2.approxPolyDP(cnt,0.02*peri,True) if area > max_area and len(approx)==4: best_cnt = approx max_area = area cv2.drawContours(mask,[best_cnt],0,255,-1) cv2.drawContours(mask,[best_cnt],0,0,2) res = cv2.bitwise_and(res,mask) ## Testing output image below #pylab.imshow(res,cmap="gray") #pylab.show() kernelx = cv2.getStructuringElement(cv2.MORPH_RECT,(2,10)) dx = cv2.Sobel(res,cv2.CV_16S,1,0) dx = cv2.convertScaleAbs(dx) cv2.normalize(dx,dx,0,255,cv2.NORM_MINMAX) ret,close = cv2.threshold(dx,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) close = cv2.morphologyEx(close,cv2.MORPH_DILATE,kernelx,iterations = 1) im, contour, hier = cv2.findContours(close,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) for cnt in contour: x,y,w,h = cv2.boundingRect(cnt) if h/w > 5: cv2.drawContours(close,[cnt],0,255,-1) else: cv2.drawContours(close,[cnt],0,0,-1) close = cv2.morphologyEx(close,cv2.MORPH_CLOSE,None,iterations = 2) closex = close.copy() ## Testing output image below #pylab.imshow(closex,cmap="gray") #pylab.show() kernely = cv2.getStructuringElement(cv2.MORPH_RECT,(10,2)) dy = cv2.Sobel(res,cv2.CV_16S,0,2) dy = cv2.convertScaleAbs(dy) cv2.normalize(dy,dy,0,255,cv2.NORM_MINMAX) ret,close = cv2.threshold(dy,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) close = cv2.morphologyEx(close,cv2.MORPH_DILATE,kernely) im, contour, hier = cv2.findContours(close,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) for cnt in contour: x,y,w,h = cv2.boundingRect(cnt) if w/h > 5: cv2.drawContours(close,[cnt],0,255,-1) else: cv2.drawContours(close,[cnt],0,0,-1) close = cv2.morphologyEx(close,cv2.MORPH_DILATE,None,iterations = 2) closey = close.copy() ## Testing output image below #pylab.imshow(closey,cmap="gray") #pylab.show() ## Testing output image below res = cv2.bitwise_and(closex,closey) #pylab.imshow(res,cmap="gray") #pylab.show() im, contour, hier = cv2.findContours(res,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE) centroids = [] for cnt in contour: mom = cv2.moments(cnt) (x,y) = int(mom['m10']/mom['m00']), int(mom['m01']/mom['m00']) cv2.circle(img,(x,y),4,(0,255,0),-1) centroids.append((x,y)) centroids = np.array(centroids,dtype = np.float32) c = centroids.reshape((100,2)) c2 = c[np.argsort(c[:,1])] b = np.vstack([c2[i*10:(i+1)*10][np.argsort(c2[i*10:(i+1)*10,0])] for i in range(10)]) bm = b.reshape((10,10,2)) output = np.zeros((450,450,3),np.uint8) M = np.zeros((50,50),np.uint8) for i,j in enumerate(b): ri = i/10 cheatvar = int(ri) ci = i%10 if ci != 9 and cheatvar!=9: src = bm[cheatvar:cheatvar+2, ci:ci+2 , :].reshape((4,2)) dst = np.array( [ [ci*50,cheatvar*50],[(ci+1)*50-1,cheatvar*50],[ci*50,(cheatvar+1)*50-1],[(ci+1)*50-1,(cheatvar+1)*50-1] ], np.float32) retval = cv2.getPerspectiveTransform(src,dst) warp = cv2.warpPerspective(res2,retval,(450,450)) output[cheatvar*50:((cheatvar+1)*50)-1 , ci*50:((ci+1)*50)-1] = warp[cheatvar*50:(cheatvar+1)*50-1 , ci*50:(ci+1)*50-1].copy() ## Adding a feature to make empty cells entirely white and border with threshold ## Greyscale M[0:49, 0:49] = 0.2989*output[cheatvar*50:((cheatvar+1)*50)-1 , ci*50:((ci+1)*50)-1, 0] + 0.5870*output[cheatvar*50:((cheatvar+1)*50)-1 , ci*50:((ci+1)*50)-1, 1] + 0.1140*output[cheatvar*50:((cheatvar+1)*50)-1 , ci*50:((ci+1)*50)-1, 2] x = M.mean() #print(x) thold = 215 if x > thold: for i in range(50): for j in range(50): if i==0 or i==49 or j==0 or j==49: M[i,j]=0 else: M[i,j]=255 output[cheatvar*50:((cheatvar+1)*50)-1 , ci*50:((ci+1)*50)-1, 0] = M[0:49, 0:49] output[cheatvar*50:((cheatvar+1)*50)-1 , ci*50:((ci+1)*50)-1, 1] = M[0:49, 0:49] output[cheatvar*50:((cheatvar+1)*50)-1 , ci*50:((ci+1)*50)-1, 2] = M[0:49, 0:49] ## Testing output image #pylab.imshow(output,cmap="gray") #pylab.show() #pylab.imshow(M,cmap="gray") #pylab.show() ## Testing print statements #print("outputy=",range(cheatvar*50,((cheatvar+1)*50)-1)) #print("outputx=", range(ci*50,((ci+1)*50)-1)) #print("inputy=",range(cheatvar*50,(cheatvar+1)*50-1)) #print("inputx=",range(ci*50,(ci+1)*50-1)) #print("ri=",ri) #print("ci=",ci) #print("cheatvar=",cheatvar) #print("i=",i) #print("j=",j) return output pylab.imshow(func(img,st),cmap="gray") pylab.show() ################################################ # put this code in a function to make it cleaner def loadModel(): # load json and create model json_file = open('model.json', 'r') loaded_model_json = json_file.read() json_file.close() loaded_model = model_from_json(loaded_model_json) # load weights into new model loaded_model.load_weights("model.h5") print("Loaded model from disk") # evaluate loaded model on test data loaded_model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) return loaded_model loaded_model = loadModel() sudokuImage = func(img,st) # These values set the size that the image is scaled to. We can modify for every input height = 1512 cellHeight = 168 sudokuImage = transform.resize(sudokuImage, (height,height)) # Preprocess images so that they don't have boundaries def removeBoundries(numImage): # Sum up the pixel values across each row, if the average pixel is 255, then it is a boundary, so zero it out numImage = skimage.color.rgb2grey(numImage) height = numImage.shape[0] colSum = 0 for col in range(height): for row in range(height): colSum += numImage[(row, col)] colSum = colSum / height #print(colSum) if colSum >= 250: for row2 in range(height): numImage[(row2, col)] = 0 rowSum = 0 for row in range(height): for col in range(height): rowSum += numImage[(row, col)] rowSum = rowSum / height #print(rowSum) if rowSum >= 220: for col2 in range(height): numImage[(row, col2)] = 0 rowSum = 0 return numImage def formatImageMnist(image): #print("IMAGE: ", image.shape) """ This code works by finding every row and column that is almost entirely black and removing it from the image, so that just the image remains """ rowsToRemove = list() colsToRemove = list() newImage = np.copy(image) newImage = skimage.color.rgb2grey(newImage) for row in range(newImage.shape[0]): rowSum = 0 for col in range(newImage.shape[1]): rowSum += newImage[(row, col)] if rowSum < 50: rowsToRemove.append(row) prevRow = rowsToRemove[0] largest_delta = 0 largestIndex = 0 count = 0 for row in rowsToRemove: delta = row - prevRow if delta > largest_delta: largest_delta = delta largestIndex = count prevRow = row count += 1 newImage = newImage[rowsToRemove[largestIndex-1]:rowsToRemove[largestIndex], :] for col in range(newImage.shape[1]): colSum = 0 for row in range(newImage.shape[0]): colSum += newImage[(row, col)] if colSum < 50: colsToRemove.append(col) prevCol = colsToRemove[0] largest_delta = 0 largestIndex = 0 count = 0 for col in colsToRemove: delta = col - prevCol if delta > largest_delta: largest_delta = delta largestIndex = count prevCol = col count += 1 newImage = newImage[:, colsToRemove[largestIndex-1]:colsToRemove[largestIndex]] #Scale the image down so that the height is 20 pixels heightWidthRatio = newImage.shape[0] / newImage.shape[1] newWidth = int(20 / heightWidthRatio) #Force newWidth to be even. makes the math easier if newWidth % 2 != 0: newWidth -= 1 if newWidth == 0: newWidth = 2 newImage = transform.resize(newImage, (20, newWidth)) if (newWidth > 20): return np.zeros((28, 28)) # Add padding to newImage, so that the final image is padded with black pixels paddedImage = np.zeros((28, 28)) paddedImage[:] = 0 widthPad = newWidth / 2 paddedImage[4:24, int(14-widthPad):int(14+widthPad)] = newImage return paddedImage # need to add a line of code to resize and scale the image to 28x28, so the the CNN can predict it def predictImageVal(invertedImg): invertedImg = invertedImg / 255 # Smooth the image with a gussian blur #invertedImg = scipy.ndimage.filters.gaussian_filter(invertedImg, sigma=1) # plt.imshow(invertedImg, cmap='gray') # plt.show() #Forms the image to the correct format to be read by the model invertedImg = invertedImg.flatten(order='C') invertedImg = np.resize(invertedImg, (784,1)) # This changes the size to (, 784) invertedImg = np.transpose(invertedImg) # Puts image into correct shape: (1, 784) # pass formatted image into neural net and get prediction matrix predMatrix = loaded_model.predict(invertedImg) #print(predMatrix) # Search the probability matrix to find the classifier with the highest probability maxVal = 0 maxIndex = 0 counter = 0 for col in range(predMatrix.shape[1]): if predMatrix[(0, col)] > maxVal: maxVal = predMatrix[(0, col)] maxIndex = counter counter += 1 return maxIndex # Take the inner section of each cell. If there are no white cells, then there's no number in it def isNumber(numImage): numImage = numImage[9:18, 9:18] #Convert image to gray scale, resize it to 28x28, convert type to ubyte numImage = skimage.color.rgb2grey(numImage) numImage = skimage.img_as_ubyte(numImage) #Our images are black text / white background, the model needs white text / black background. These lines invert the black/white invertedImg = np.zeros((28,28)) invertedImg[numImage < 150] = 255 invertedImg[numImage >= 150] = 0 numberInCell = False for row in range(invertedImg.shape[0]): for col in range(invertedImg.shape[1]): if invertedImg[(row, col)] == 255: numberInCell = True return numberInCell # These are used for the 512x512 image prevCol = 0 prevRow = 0 # These are used for the 9x9 sudoku board sudokuCol = 0 sudokuRow = 0 # This will store the values actually on the game grid sudokuMatrix = np.zeros((81, 81)) # Set height of original image. Set height of cell # height = 1260 # cellHeight = 140 cell = np.zeros((cellHeight, cellHeight)) # This produces all of the row and column range for the 81 different images for row in range(cellHeight, height + cellHeight, cellHeight): for col in range(cellHeight, height + cellHeight, cellHeight): # wrap around to next row of cells if prevCol == height: prevCol = 0 # wrap around to to next row of cells if sudokuCol == 9: sudokuCol = 0 cell = sudokuImage[prevRow:row, prevCol:col] cell = transform.resize(cell, (28,28)) if not isNumber(cell): sudokuMatrix[(sudokuRow, sudokuCol)] = 0 else: cellImage = sudokuImage[prevRow:row, prevCol:col] #Convert image to gray scale, resize it to 28x28, convert type to ubyte cellImage = skimage.color.rgb2grey(cellImage) cellImage = skimage.img_as_ubyte(cellImage) #Our images are black text / white background, the model needs white
<filename>util/configurejson2cmake.py #!/usr/bin/env python3 ############################################################################# ## ## Copyright (C) 2018 The Qt Company Ltd. ## Contact: https://www.qt.io/licensing/ ## ## This file is part of the plugins of the Qt Toolkit. ## ## $QT_BEGIN_LICENSE:GPL-EXCEPT$ ## Commercial License Usage ## Licensees holding valid commercial Qt licenses may use this file in ## accordance with the commercial license agreement provided with the ## Software or, alternatively, in accordance with the terms contained in ## a written agreement between you and The Qt Company. For licensing terms ## and conditions see https://www.qt.io/terms-conditions. For further ## information use the contact form at https://www.qt.io/contact-us. ## ## GNU General Public License Usage ## Alternatively, this file may be used under the terms of the GNU ## General Public License version 3 as published by the Free Software ## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ## included in the packaging of this file. Please review the following ## information to ensure the GNU General Public License requirements will ## be met: https://www.gnu.org/licenses/gpl-3.0.html. ## ## $QT_END_LICENSE$ ## ############################################################################# import json_parser import posixpath import re import sys from typing import Optional, Set from textwrap import dedent import os from special_case_helper import SpecialCaseHandler from helper import ( map_qt_library, featureName, map_platform, find_3rd_party_library_mapping, generate_find_package_info, get_compile_test_dependent_library_mapping, ) knownTests = set() # type: Set[str] class LibraryMapping: def __init__(self, package: str, resultVariable: str, appendFoundSuffix: bool = True) -> None: self.package = package self.resultVariable = resultVariable self.appendFoundSuffix = appendFoundSuffix def map_tests(test: str) -> Optional[str]: testmap = { "c99": "c_std_99 IN_LIST CMAKE_C_COMPILE_FEATURES", "c11": "c_std_11 IN_LIST CMAKE_C_COMPILE_FEATURES", "x86SimdAlways": "ON", # FIXME: Make this actually do a compile test. "aesni": "TEST_subarch_aesni", "avx": "TEST_subarch_avx", "avx2": "TEST_subarch_avx2", "avx512f": "TEST_subarch_avx512f", "avx512cd": "TEST_subarch_avx512cd", "avx512dq": "TEST_subarch_avx512dq", "avx512bw": "TEST_subarch_avx512bw", "avx512er": "TEST_subarch_avx512er", "avx512pf": "TEST_subarch_avx512pf", "avx512vl": "TEST_subarch_avx512vl", "avx512ifma": "TEST_subarch_avx512ifma", "avx512vbmi": "TEST_subarch_avx512vbmi", "avx512vbmi2": "TEST_subarch_avx512vbmi2", "avx512vpopcntdq": "TEST_subarch_avx512vpopcntdq", "avx5124fmaps": "TEST_subarch_avx5124fmaps", "avx5124vnniw": "TEST_subarch_avx5124vnniw", "bmi": "TEST_subarch_bmi", "bmi2": "TEST_subarch_bmi2", "cx16": "TEST_subarch_cx16", "f16c": "TEST_subarch_f16c", "fma": "TEST_subarch_fma", "fma4": "TEST_subarch_fma4", "fsgsbase": "TEST_subarch_fsgsbase", "gfni": "TEST_subarch_gfni", "ibt": "TEST_subarch_ibt", "libclang": "TEST_libclang", "lwp": "TEST_subarch_lwp", "lzcnt": "TEST_subarch_lzcnt", "mmx": "TEST_subarch_mmx", "movbe": "TEST_subarch_movbe", "mpx": "TEST_subarch_mpx", "no-sahf": "TEST_subarch_no_shaf", "pclmul": "TEST_subarch_pclmul", "popcnt": "TEST_subarch_popcnt", "prefetchwt1": "TEST_subarch_prefetchwt1", "prfchw": "TEST_subarch_prfchw", "pdpid": "TEST_subarch_rdpid", "rdpid": "TEST_subarch_rdpid", "rdseed": "TEST_subarch_rdseed", "rdrnd": "TEST_subarch_rdrnd", "rtm": "TEST_subarch_rtm", "shani": "TEST_subarch_shani", "shstk": "TEST_subarch_shstk", "sse2": "TEST_subarch_sse2", "sse3": "TEST_subarch_sse3", "ssse3": "TEST_subarch_ssse3", "sse4a": "TEST_subarch_sse4a", "sse4_1": "TEST_subarch_sse4_1", "sse4_2": "TEST_subarch_sse4_2", "tbm": "TEST_subarch_tbm", "xop": "TEST_subarch_xop", "neon": "TEST_subarch_neon", "iwmmxt": "TEST_subarch_iwmmxt", "crc32": "TEST_subarch_crc32", "vis": "TEST_subarch_vis", "vis2": "TEST_subarch_vis2", "vis3": "TEST_subarch_vis3", "dsp": "TEST_subarch_dsp", "dspr2": "TEST_subarch_dspr2", "altivec": "TEST_subarch_altivec", "spe": "TEST_subarch_spe", "vsx": "TEST_subarch_vsx", "openssl11": '(OPENSSL_VERSION VERSION_GREATER_EQUAL "1.1.0")', "libinput_axis_api": "ON", "xlib": "X11_FOUND", "wayland-scanner": "WaylandScanner_FOUND", "3rdparty-hunspell": "VKB_HAVE_3RDPARTY_HUNSPELL", "t9write-alphabetic": "VKB_HAVE_T9WRITE_ALPHA", "t9write-cjk": "VKB_HAVE_T9WRITE_CJK", } if test in testmap: return testmap.get(test, None) if test in knownTests: return f"TEST_{featureName(test)}" return None def cm(ctx, *output): txt = ctx["output"] if txt != "" and not txt.endswith("\n"): txt += "\n" txt += "\n".join(output) ctx["output"] = txt return ctx def readJsonFromDir(path: str) -> str: path = posixpath.join(path, "configure.json") print(f"Reading {path}...") assert posixpath.exists(path) parser = json_parser.QMakeSpecificJSONParser() return parser.parse(path) def processFiles(ctx, data): print(" files:") if "files" in data: for (k, v) in data["files"].items(): ctx[k] = v return ctx def parseLib(ctx, lib, data, cm_fh, cmake_find_packages_set): newlib = find_3rd_party_library_mapping(lib) if not newlib: print(f' XXXX Unknown library "{lib}".') return if newlib.packageName is None: print(f' **** Skipping library "{lib}" -- was masked.') return print(f" mapped library {lib} to {newlib.targetName}.") # Avoid duplicate find_package calls. if newlib.targetName in cmake_find_packages_set: return # If certain libraries are used within a feature, but the feature # is only emitted conditionally with a simple condition (like # 'on Windows' or 'on Linux'), we should enclose the find_package # call for the library into the same condition. emit_if = newlib.emit_if # Only look through features if a custom emit_if wasn't provided. if not emit_if: for feature in data["features"]: feature_data = data["features"][feature] if ( "condition" in feature_data and f"libs.{lib}" in feature_data["condition"] and "emitIf" in feature_data and "config." in feature_data["emitIf"] ): emit_if = feature_data["emitIf"] break if emit_if: emit_if = map_condition(emit_if) cmake_find_packages_set.add(newlib.targetName) find_package_kwargs = {"emit_if": emit_if} if newlib.is_bundled_with_qt: # If a library is bundled with Qt, it has 2 FindFoo.cmake # modules: WrapFoo and WrapSystemFoo. # FindWrapSystemFoo.cmake will try to find the 'Foo' library in # the usual CMake locations, and will create a # WrapSystemFoo::WrapSystemFoo target pointing to the library. # # FindWrapFoo.cmake will create a WrapFoo::WrapFoo target which # will link either against the WrapSystemFoo or QtBundledFoo # target depending on certain feature values. # # Because the following qt_find_package call is for # configure.cmake consumption, we make the assumption that # configure.cmake is interested in finding the system library # for the purpose of enabling or disabling a system_foo feature. find_package_kwargs["use_system_package_name"] = True find_package_kwargs["module"] = ctx["module"] cm_fh.write(generate_find_package_info(newlib, **find_package_kwargs)) if "use" in data["libraries"][lib]: use_entry = data["libraries"][lib]["use"] if isinstance(use_entry, str): print(f"1use: {use_entry}") cm_fh.write(f"qt_add_qmake_lib_dependency({newlib.soName} {use_entry})\n") else: for use in use_entry: print(f"2use: {use}") indentation = "" has_condition = False if "condition" in use: has_condition = True indentation = " " condition = map_condition(use["condition"]) cm_fh.write(f"if({condition})\n") cm_fh.write( f"{indentation}qt_add_qmake_lib_dependency({newlib.soName} {use['lib']})\n" ) if has_condition: cm_fh.write("endif()\n") run_library_test = False mapped_library = find_3rd_party_library_mapping(lib) if mapped_library: run_library_test = mapped_library.run_library_test if run_library_test and "test" in data["libraries"][lib]: test = data["libraries"][lib]["test"] write_compile_test( ctx, lib, test, data, cm_fh, manual_library_list=[lib], is_library_test=True ) def lineify(label, value, quote=True): if value: if quote: escaped_value = value.replace('"', '\\"') return f' {label} "{escaped_value}"\n' return f" {label} {value}\n" return "" def map_condition(condition): # Handle NOT: if isinstance(condition, list): condition = "(" + ") AND (".join(condition) + ")" if isinstance(condition, bool): if condition: return "ON" else: return "OFF" assert isinstance(condition, str) mapped_features = {"gbm": "gbm_FOUND"} # Turn foo != "bar" into (NOT foo STREQUAL 'bar') condition = re.sub(r"([^ ]+)\s*!=\s*('.*?')", "(! \\1 == \\2)", condition) # Turn foo != 156 into (NOT foo EQUAL 156) condition = re.sub(r"([^ ]+)\s*!=\s*([0-9]?)", "(! \\1 EQUAL \\2)", condition) condition = condition.replace("!", "NOT ") condition = condition.replace("&&", " AND ") condition = condition.replace("||", " OR ") condition = condition.replace("==", " STREQUAL ") # explicitly handle input.sdk == '': condition = re.sub(r"input\.sdk\s*==\s*''", "NOT INPUT_SDK", condition) last_pos = 0 mapped_condition = "" has_failed = False for match in re.finditer(r"([a-zA-Z0-9_]+)\.([a-zA-Z0-9_+-]+)", condition): substitution = None # appendFoundSuffix = True if match.group(1) == "libs": libmapping = find_3rd_party_library_mapping(match.group(2)) if libmapping and libmapping.packageName: substitution = libmapping.packageName if libmapping.resultVariable: substitution = libmapping.resultVariable if libmapping.appendFoundSuffix: substitution += "_FOUND" # Assume that feature conditions are interested whether # a system library is found, rather than the bundled one # which we always know we can build. if libmapping.is_bundled_with_qt: substitution = substitution.replace("Wrap", "WrapSystem") elif match.group(1) == "features": feature = match.group(2) if feature in mapped_features: substitution = mapped_features.get(feature) else: substitution = f"QT_FEATURE_{featureName(match.group(2))}" elif match.group(1) == "subarch": substitution = f"TEST_arch_{'${TEST_architecture_arch}'}_subarch_{match.group(2)}" elif match.group(1) == "call": if match.group(2) == "crossCompile": substitution = "CMAKE_CROSSCOMPILING" elif match.group(1) == "tests": substitution = map_tests(match.group(2)) elif match.group(1) == "input": substitution = f"INPUT_{featureName(match.group(2))}" elif match.group(1) == "config": substitution = map_platform(match.group(2)) elif match.group(1) == "module": substitution = f"TARGET {map_qt_library(match.group(2))}" elif match.group(1) == "arch": if match.group(2) == "i386": # FIXME: Does this make sense? substitution = "(TEST_architecture_arch STREQUAL i386)" elif match.group(2) == "x86_64": substitution = "(TEST_architecture_arch STREQUAL x86_64)" elif match.group(2) == "arm": # FIXME: Does this make sense? substitution = "(TEST_architecture_arch STREQUAL arm)" elif match.group(2) == "arm64": # FIXME: Does this make sense? substitution = "(TEST_architecture_arch STREQUAL arm64)" elif match.group(2) == "mips": # FIXME: Does this make sense? substitution = "(TEST_architecture_arch STREQUAL mips)" if substitution is None: print(f' XXXX Unknown condition "{match.group(0)}"') has_failed = True else: mapped_condition += condition[last_pos : match.start(1)] + substitution last_pos = match.end(2) mapped_condition += condition[last_pos:] # Space out '(' and ')': mapped_condition = mapped_condition.replace("(", " ( ") mapped_condition = mapped_condition.replace(")", " ) ") # Prettify: condition = re.sub("\\s+", " ", mapped_condition) condition = condition.strip() # Special case for WrapLibClang in qttools condition = condition.replace("TEST_libclang.has_clangcpp", "TEST_libclang") if has_failed: condition += " OR FIXME" return condition def parseInput(ctx, sinput, data, cm_fh): skip_inputs = { "prefix", "hostprefix", "extprefix", "archdatadir", "bindir", "datadir", "docdir", "examplesdir", "external-hostbindir", "headerdir", "hostbindir", "hostdatadir", "hostlibdir", "importdir", "libdir", "libexecdir", "plugindir", "qmldir", "settingsdir", "sysconfdir", "testsdir", "translationdir", "android-arch", "android-ndk", "android-ndk-host", "android-ndk-platform", "android-sdk", "android-toolchain-version", "android-style-assets", "appstore-compliant", "avx", "avx2", "avx512", "c++std", "ccache", "commercial", "confirm-license", "dbus", "dbus-runtime", "debug", "debug-and-release", "developer-build", "device", "device-option", "f16c", "force-asserts", "force-debug-info", "force-pkg-config", "framework", "gc-binaries", "gdb-index", "gcc-sysroot", "gcov", "gnumake", "gui", "headersclean", "incredibuild-xge", "libudev", "ltcg", "make", "make-tool", "mips_dsp", "mips_dspr2", "mp", "nomake", "opensource", "optimize-debug", "optimize-size", "optimized-qmake", "optimized-tools", "pch", "pkg-config", "platform", "plugin-manifests", "profile", "qreal", "reduce-exports", "reduce-relocations", "release", "rpath", "sanitize", "sdk", "separate-debug-info", "shared",
<filename>profile_double11/ipython_nbconvert_config.py # Configuration file for ipython-nbconvert. c = get_config() #------------------------------------------------------------------------------ # NbConvertApp configuration #------------------------------------------------------------------------------ # This application is used to convert notebook files (*.ipynb) to various other # formats. # # WARNING: THE COMMANDLINE INTERFACE MAY CHANGE IN FUTURE RELEASES. # NbConvertApp will inherit config from: BaseIPythonApplication, Application # The IPython profile to use. # c.NbConvertApp.profile = u'default' # The export format to be used. # c.NbConvertApp.export_format = 'html' # Set the log level by value or name. # c.NbConvertApp.log_level = 30 # PostProcessor class used to write the results of the conversion # c.NbConvertApp.post_processor_class = u'' # List of notebooks to convert. Wildcards are supported. Filenames passed # positionally will be added to the list. # c.NbConvertApp.notebooks = [] # Path to an extra config file to load. # # If specified, load this config file in addition to any other IPython config. # c.NbConvertApp.extra_config_file = u'' # Whether to create profile dir if it doesn't exist # c.NbConvertApp.auto_create = False # overwrite base name use for output files. can only be use when converting one # notebook at a time. # c.NbConvertApp.output_base = '' # The name of the IPython directory. This directory is used for logging # configuration (through profiles), history storage, etc. The default is usually # $HOME/.ipython. This options can also be specified through the environment # variable IPYTHONDIR. # c.NbConvertApp.ipython_dir = u'/data1/home/dongweiming/.ipython' # Whether to install the default config files into the profile dir. If a new # profile is being created, and IPython contains config files for that profile, # then they will be staged into the new directory. Otherwise, default config # files will be automatically generated. # c.NbConvertApp.copy_config_files = False # The date format used by logging formatters for %(asctime)s # c.NbConvertApp.log_datefmt = '%Y-%m-%d %H:%M:%S' # The Logging format template # c.NbConvertApp.log_format = '[%(name)s]%(highlevel)s %(message)s' # Create a massive crash report when IPython encounters what may be an internal # error. The default is to append a short message to the usual traceback # c.NbConvertApp.verbose_crash = False # Writer class used to write the results of the conversion # c.NbConvertApp.writer_class = 'FilesWriter' # Whether to overwrite existing config files when copying # c.NbConvertApp.overwrite = False #------------------------------------------------------------------------------ # NbConvertBase configuration #------------------------------------------------------------------------------ # Global configurable class for shared config # # Usefull for display data priority that might be use by many trasnformers # An ordered list of prefered output type, the first encounterd will usually be # used when converting discarding the others. # c.NbConvertBase.display_data_priority = ['html', 'pdf', 'svg', 'latex', 'png', 'jpg', 'jpeg', 'text'] #------------------------------------------------------------------------------ # ProfileDir configuration #------------------------------------------------------------------------------ # An object to manage the profile directory and its resources. # # The profile directory is used by all IPython applications, to manage # configuration, logging and security. # # This object knows how to find, create and manage these directories. This # should be used by any code that wants to handle profiles. # Set the profile location directly. This overrides the logic used by the # `profile` option. # c.ProfileDir.location = u'' #------------------------------------------------------------------------------ # Exporter configuration #------------------------------------------------------------------------------ # Exports notebooks into other file formats. Uses Jinja 2 templating engine to # output new formats. Inherit from this class if you are creating a new # template type along with new filters/transformers. If the filters/ # transformers provided by default suffice, there is no need to inherit from # this class. Instead, override the template_file and file_extension traits via # a config file. # # - highlight2html - filter_data_type - markdown2html - markdown2rst - get_lines # - ansi2latex - strip_ansi - comment_lines - markdown2latex - escape_latex - # add_anchor - ipython2python - posix_path - highlight2latex - path2url - # ansi2html - wrap_text - strip_math_space - indent - strip_dollars - html2text # - strip_files_prefix # # c.Exporter.jinja_variable_block_start = '' # # c.Exporter.jinja_logic_block_start = '' # List of transformers, by name or namespace, to enable. # c.Exporter.transformers = [] # # c.Exporter.template_path = ['.'] # Name of the template file to use # c.Exporter.template_file = u'default' # Extension of the file that should be written to disk # c.Exporter.file_extension = 'txt' # # c.Exporter.jinja_comment_block_end = '' # Dictionary of filters, by name and namespace, to add to the Jinja environment. # c.Exporter.filters = {} # # c.Exporter.jinja_comment_block_start = '' # # c.Exporter.jinja_logic_block_end = '' # # c.Exporter.jinja_variable_block_end = '' # # c.Exporter.template_extension = '.tpl' # List of transformers available by default, by name, namespace, instance, or # type. # c.Exporter.default_transformers = [<function wrappedfunc at 0x2b79ed8>, <class 'IPython.nbconvert.transformers.svg2pdf.SVG2PDFTransformer'>, <class 'IPython.nbconvert.transformers.extractoutput.ExtractOutputTransformer'>, <class 'IPython.nbconvert.transformers.csshtmlheader.CSSHTMLHeaderTransformer'>, <class 'IPython.nbconvert.transformers.revealhelp.RevealHelpTransformer'>, <class 'IPython.nbconvert.transformers.latex.LatexTransformer'>, <class 'IPython.nbconvert.transformers.sphinx.SphinxTransformer'>] #------------------------------------------------------------------------------ # HTMLExporter configuration #------------------------------------------------------------------------------ # Exports a basic HTML document. This exporter assists with the export of HTML. # Inherit from it if you are writing your own HTML template and need custom # transformers/filters. If you don't need custom transformers/ filters, just # change the 'template_file' config option. # HTMLExporter will inherit config from: Exporter # # c.HTMLExporter.jinja_variable_block_start = '' # # c.HTMLExporter.jinja_logic_block_start = '' # List of transformers, by name or namespace, to enable. # c.HTMLExporter.transformers = [] # # c.HTMLExporter.template_path = ['.'] # Name of the template file to use # c.HTMLExporter.template_file = u'default' # Extension of the file that should be written to disk # c.HTMLExporter.file_extension = 'html' # Flavor of the data format to use. I.E. 'full' or 'basic' # c.HTMLExporter.default_template = 'full' # # c.HTMLExporter.jinja_comment_block_end = '' # Dictionary of filters, by name and namespace, to add to the Jinja environment. # c.HTMLExporter.filters = {} # # c.HTMLExporter.jinja_comment_block_start = '' # # c.HTMLExporter.jinja_logic_block_end = '' # # c.HTMLExporter.jinja_variable_block_end = '' # # c.HTMLExporter.template_extension = '.tpl' # List of transformers available by default, by name, namespace, instance, or # type. # c.HTMLExporter.default_transformers = [<function wrappedfunc at 0x2b79ed8>, <class 'IPython.nbconvert.transformers.svg2pdf.SVG2PDFTransformer'>, <class 'IPython.nbconvert.transformers.extractoutput.ExtractOutputTransformer'>, <class 'IPython.nbconvert.transformers.csshtmlheader.CSSHTMLHeaderTransformer'>, <class 'IPython.nbconvert.transformers.revealhelp.RevealHelpTransformer'>, <class 'IPython.nbconvert.transformers.latex.LatexTransformer'>, <class 'IPython.nbconvert.transformers.sphinx.SphinxTransformer'>] #------------------------------------------------------------------------------ # LatexExporter configuration #------------------------------------------------------------------------------ # Exports to a Latex template. Inherit from this class if your template is # LaTeX based and you need custom tranformers/filters. Inherit from it if you # are writing your own HTML template and need custom tranformers/filters. If # you don't need custom tranformers/filters, just change the 'template_file' # config option. Place your template in the special "/latex" subfolder of the # "../templates" folder. # LatexExporter will inherit config from: Exporter # # c.LatexExporter.jinja_variable_block_start = '(((' # # c.LatexExporter.jinja_logic_block_start = '((*' # Path where the template skeleton files are located. # c.LatexExporter.template_skeleton_path = '../templates/latex/skeleton' # # c.LatexExporter.template_path = ['.'] # Name of the template file to use # c.LatexExporter.template_file = u'default' # Path where the template files are located. # c.LatexExporter.default_template_path = '../templates/latex' # Extension of the file that should be written to disk # c.LatexExporter.file_extension = 'tex' # Template of the data format to use. I.E. 'full' or 'basic' # c.LatexExporter.default_template = 'article' # # c.LatexExporter.jinja_comment_block_end = '=))' # Dictionary of filters, by name and namespace, to add to the Jinja environment. # c.LatexExporter.filters = {} # # c.LatexExporter.jinja_comment_block_start = '((=' # List of transformers, by name or namespace, to enable. # c.LatexExporter.transformers = [] # # c.LatexExporter.jinja_logic_block_end = '*))' # # c.LatexExporter.jinja_variable_block_end = ')))' # # c.LatexExporter.template_extension = '.tplx' # List of transformers available by default, by name, namespace, instance, or # type. # c.LatexExporter.default_transformers = [<function wrappedfunc at 0x2b79ed8>, <class 'IPython.nbconvert.transformers.svg2pdf.SVG2PDFTransformer'>, <class 'IPython.nbconvert.transformers.extractoutput.ExtractOutputTransformer'>, <class 'IPython.nbconvert.transformers.csshtmlheader.CSSHTMLHeaderTransformer'>, <class 'IPython.nbconvert.transformers.revealhelp.RevealHelpTransformer'>, <class 'IPython.nbconvert.transformers.latex.LatexTransformer'>, <class 'IPython.nbconvert.transformers.sphinx.SphinxTransformer'>] #------------------------------------------------------------------------------ # MarkdownExporter configuration #------------------------------------------------------------------------------ # Exports to a markdown document (.md) # MarkdownExporter will inherit config from: Exporter # # c.MarkdownExporter.jinja_variable_block_start = '' # # c.MarkdownExporter.jinja_logic_block_start = '' # List of transformers, by name or namespace, to enable. # c.MarkdownExporter.transformers = [] # # c.MarkdownExporter.template_path = ['.'] # Name of the template file to use # c.MarkdownExporter.template_file = u'default' # Extension of the file that should be written to disk # c.MarkdownExporter.file_extension = 'md' # # c.MarkdownExporter.jinja_comment_block_end = '' # Dictionary of filters, by name and namespace, to add to the Jinja environment. # c.MarkdownExporter.filters = {} # # c.MarkdownExporter.jinja_comment_block_start = '' # # c.MarkdownExporter.jinja_logic_block_end = '' # # c.MarkdownExporter.jinja_variable_block_end = '' # # c.MarkdownExporter.template_extension = '.tpl' # List of transformers available by default, by name, namespace, instance, or # type. # c.MarkdownExporter.default_transformers = [<function wrappedfunc at 0x2b79ed8>, <class 'IPython.nbconvert.transformers.svg2pdf.SVG2PDFTransformer'>, <class 'IPython.nbconvert.transformers.extractoutput.ExtractOutputTransformer'>, <class 'IPython.nbconvert.transformers.csshtmlheader.CSSHTMLHeaderTransformer'>, <class 'IPython.nbconvert.transformers.revealhelp.RevealHelpTransformer'>, <class 'IPython.nbconvert.transformers.latex.LatexTransformer'>, <class 'IPython.nbconvert.transformers.sphinx.SphinxTransformer'>] #------------------------------------------------------------------------------ # PythonExporter configuration #------------------------------------------------------------------------------ # Exports a Python code file. # PythonExporter will inherit config from: Exporter # # c.PythonExporter.jinja_variable_block_start = '' # # c.PythonExporter.jinja_logic_block_start = '' # List of transformers, by name or namespace, to enable. # c.PythonExporter.transformers = [] # # c.PythonExporter.template_path = ['.'] # Name of the template file to use # c.PythonExporter.template_file = u'default' # Extension of the file that should be written to disk # c.PythonExporter.file_extension = 'py' # # c.PythonExporter.jinja_comment_block_end = '' # Dictionary of filters, by name and namespace, to add to the Jinja environment. # c.PythonExporter.filters = {} # # c.PythonExporter.jinja_comment_block_start = '' # # c.PythonExporter.jinja_logic_block_end = '' # # c.PythonExporter.jinja_variable_block_end = '' # # c.PythonExporter.template_extension = '.tpl' # List of transformers available by default, by name, namespace, instance, or # type. # c.PythonExporter.default_transformers
p1 = Parent(id=1, data=2, child=None) p2 = Parent(id=2, data=3, child=None) sess.add_all([p1, p2]) sess.flush() sess.execute(self.tables.parent.delete()) sess.delete(p1) sess.delete(p2) assert_raises_message( exc.SAWarning, r"DELETE statement on table 'parent' expected to " r"delete 2 row\(s\); 0 were matched.", sess.flush, ) def test_delete_multi_missing_allow(self): Parent, Child = self._fixture(confirm_deleted_rows=False) sess = Session() p1 = Parent(id=1, data=2, child=None) p2 = Parent(id=2, data=3, child=None) sess.add_all([p1, p2]) sess.flush() sess.execute(self.tables.parent.delete()) sess.delete(p1) sess.delete(p2) sess.flush() class BatchInsertsTest(fixtures.MappedTest, testing.AssertsExecutionResults): @classmethod def define_tables(cls, metadata): Table( "t", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("data", String(50)), Column("def_", String(50), server_default="def1"), ) def test_batch_interaction(self): """test batching groups same-structured, primary key present statements together. """ t = self.tables.t class T(fixtures.ComparableEntity): pass mapper(T, t) sess = Session() sess.add_all( [ T(data="t1"), T(data="t2"), T(id=3, data="t3"), T(id=4, data="t4"), T(id=5, data="t5"), T(id=6, data=func.lower("t6")), T(id=7, data="t7"), T(id=8, data="t8"), T(id=9, data="t9", def_="def2"), T(id=10, data="t10", def_="def3"), T(id=11, data="t11"), ] ) self.assert_sql_execution( testing.db, sess.flush, CompiledSQL("INSERT INTO t (data) VALUES (:data)", {"data": "t1"}), CompiledSQL("INSERT INTO t (data) VALUES (:data)", {"data": "t2"}), CompiledSQL( "INSERT INTO t (id, data) VALUES (:id, :data)", [ {"data": "t3", "id": 3}, {"data": "t4", "id": 4}, {"data": "t5", "id": 5}, ], ), CompiledSQL( "INSERT INTO t (id, data) VALUES (:id, lower(:lower_1))", {"lower_1": "t6", "id": 6}, ), CompiledSQL( "INSERT INTO t (id, data) VALUES (:id, :data)", [{"data": "t7", "id": 7}, {"data": "t8", "id": 8}], ), CompiledSQL( "INSERT INTO t (id, data, def_) VALUES (:id, :data, :def_)", [ {"data": "t9", "id": 9, "def_": "def2"}, {"data": "t10", "id": 10, "def_": "def3"}, ], ), CompiledSQL( "INSERT INTO t (id, data) VALUES (:id, :data)", {"data": "t11", "id": 11}, ), ) class LoadersUsingCommittedTest(UOWTest): """Test that events which occur within a flush() get the same attribute loading behavior as on the outside of the flush, and that the unit of work itself uses the "committed" version of primary/foreign key attributes when loading a collection for historical purposes (this typically has importance for when primary key values change). """ def _mapper_setup(self, passive_updates=True): users, Address, addresses, User = ( self.tables.users, self.classes.Address, self.tables.addresses, self.classes.User, ) mapper( User, users, properties={ "addresses": relationship( Address, order_by=addresses.c.email_address, passive_updates=passive_updates, backref="user", ) }, ) mapper(Address, addresses) return create_session(autocommit=False) def test_before_update_m2o(self): """Expect normal many to one attribute load behavior (should not get committed value) from within public 'before_update' event""" sess = self._mapper_setup() Address, User = self.classes.Address, self.classes.User def before_update(mapper, connection, target): # if get committed is used to find target.user, then # it will be still be u1 instead of u2 assert target.user.id == target.user_id == u2.id from sqlalchemy import event event.listen(Address, "before_update", before_update) a1 = Address(email_address="a1") u1 = User(name="u1", addresses=[a1]) sess.add(u1) u2 = User(name="u2") sess.add(u2) sess.commit() sess.expunge_all() # lookup an address and move it to the other user a1 = sess.query(Address).get(a1.id) # move address to another user's fk assert a1.user_id == u1.id a1.user_id = u2.id sess.flush() def test_before_update_o2m_passive(self): """Expect normal one to many attribute load behavior (should not get committed value) from within public 'before_update' event""" self._test_before_update_o2m(True) def test_before_update_o2m_notpassive(self): """Expect normal one to many attribute load behavior (should not get committed value) from within public 'before_update' event with passive_updates=False """ self._test_before_update_o2m(False) def _test_before_update_o2m(self, passive_updates): sess = self._mapper_setup(passive_updates=passive_updates) Address, User = self.classes.Address, self.classes.User class AvoidReferencialError(Exception): """the test here would require ON UPDATE CASCADE on FKs for the flush to fully succeed; this exception is used to cancel the flush before we get that far. """ def before_update(mapper, connection, target): if passive_updates: # we shouldn't be using committed value. # so, having switched target's primary key, # we expect no related items in the collection # since we are using passive_updates # this is a behavior change since #2350 assert "addresses" not in target.__dict__ eq_(target.addresses, []) else: # in contrast with passive_updates=True, # here we expect the orm to have looked up the addresses # with the committed value (it needs to in order to # update the foreign keys). So we expect addresses # collection to move with the user, # (just like they will be after the update) # collection is already loaded assert "addresses" in target.__dict__ eq_([a.id for a in target.addresses], [a.id for a in [a1, a2]]) raise AvoidReferencialError() from sqlalchemy import event event.listen(User, "before_update", before_update) a1 = Address(email_address="jack1") a2 = Address(email_address="jack2") u1 = User(id=1, name="jack", addresses=[a1, a2]) sess.add(u1) sess.commit() sess.expunge_all() u1 = sess.query(User).get(u1.id) u1.id = 2 try: sess.flush() except AvoidReferencialError: pass class NoAttrEventInFlushTest(fixtures.MappedTest): """test [ticket:3167]. See also RefreshFlushInReturningTest in test/orm/test_events.py which tests the positive case for the refresh_flush event, added in [ticket:3427]. """ __backend__ = True @classmethod def define_tables(cls, metadata): Table( "test", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("prefetch_val", Integer, default=5), Column("returning_val", Integer, server_default="5"), ) @classmethod def setup_classes(cls): class Thing(cls.Basic): pass @classmethod def setup_mappers(cls): Thing = cls.classes.Thing mapper(Thing, cls.tables.test, eager_defaults=True) def test_no_attr_events_flush(self): Thing = self.classes.Thing mock = Mock() event.listen(Thing.id, "set", mock.id) event.listen(Thing.prefetch_val, "set", mock.prefetch_val) event.listen(Thing.returning_val, "set", mock.prefetch_val) t1 = Thing() s = Session() s.add(t1) s.flush() eq_(len(mock.mock_calls), 0) eq_(t1.id, 1) eq_(t1.prefetch_val, 5) eq_(t1.returning_val, 5) class EagerDefaultsTest(fixtures.MappedTest): __backend__ = True @classmethod def define_tables(cls, metadata): Table( "test", metadata, Column("id", Integer, primary_key=True), Column("foo", Integer, server_default="3"), ) Table( "test2", metadata, Column("id", Integer, primary_key=True), Column("foo", Integer), Column("bar", Integer, server_onupdate=FetchedValue()), ) @classmethod def setup_classes(cls): class Thing(cls.Basic): pass class Thing2(cls.Basic): pass @classmethod def setup_mappers(cls): Thing = cls.classes.Thing mapper(Thing, cls.tables.test, eager_defaults=True) Thing2 = cls.classes.Thing2 mapper(Thing2, cls.tables.test2, eager_defaults=True) def test_insert_defaults_present(self): Thing = self.classes.Thing s = Session() t1, t2 = (Thing(id=1, foo=5), Thing(id=2, foo=10)) s.add_all([t1, t2]) self.assert_sql_execution( testing.db, s.flush, CompiledSQL( "INSERT INTO test (id, foo) VALUES (:id, :foo)", [{"foo": 5, "id": 1}, {"foo": 10, "id": 2}], ), ) def go(): eq_(t1.foo, 5) eq_(t2.foo, 10) self.assert_sql_count(testing.db, go, 0) def test_insert_defaults_present_as_expr(self): Thing = self.classes.Thing s = Session() t1, t2 = ( Thing(id=1, foo=text("2 + 5")), Thing(id=2, foo=text("5 + 5")), ) s.add_all([t1, t2]) if testing.db.dialect.implicit_returning: self.assert_sql_execution( testing.db, s.flush, CompiledSQL( "INSERT INTO test (id, foo) VALUES (%(id)s, 2 + 5) " "RETURNING test.foo", [{"id": 1}], dialect="postgresql", ), CompiledSQL( "INSERT INTO test (id, foo) VALUES (%(id)s, 5 + 5) " "RETURNING test.foo", [{"id": 2}], dialect="postgresql", ), ) else: self.assert_sql_execution( testing.db, s.flush, CompiledSQL( "INSERT INTO test (id, foo) VALUES (:id, 2 + 5)", [{"id": 1}], ), CompiledSQL( "INSERT INTO test (id, foo) VALUES (:id, 5 + 5)", [{"id": 2}], ), CompiledSQL( "SELECT test.foo AS test_foo FROM test " "WHERE test.id = :param_1", [{"param_1": 1}], ), CompiledSQL( "SELECT test.foo AS test_foo FROM test " "WHERE test.id = :param_1", [{"param_1": 2}], ), ) def go(): eq_(t1.foo, 7) eq_(t2.foo, 10) self.assert_sql_count(testing.db, go, 0) def test_insert_defaults_nonpresent(self): Thing = self.classes.Thing s = Session() t1, t2 = (Thing(id=1), Thing(id=2)) s.add_all([t1, t2]) if testing.db.dialect.implicit_returning: self.assert_sql_execution( testing.db, s.commit, CompiledSQL( "INSERT INTO test (id) VALUES (%(id)s) RETURNING test.foo", [{"id": 1}], dialect="postgresql", ), CompiledSQL( "INSERT INTO test (id) VALUES (%(id)s) RETURNING test.foo", [{"id": 2}], dialect="postgresql", ), ) else: self.assert_sql_execution( testing.db, s.commit, CompiledSQL( "INSERT INTO test (id) VALUES (:id)", [{"id": 1}, {"id": 2}], ), CompiledSQL( "SELECT test.foo AS test_foo FROM test " "WHERE test.id = :param_1", [{"param_1": 1}], ), CompiledSQL( "SELECT test.foo AS test_foo FROM test " "WHERE test.id = :param_1", [{"param_1": 2}], ), ) def test_update_defaults_nonpresent(self): Thing2 = self.classes.Thing2 s = Session() t1, t2, t3, t4 = ( Thing2(id=1, foo=1, bar=2), Thing2(id=2, foo=2, bar=3), Thing2(id=3, foo=3, bar=4), Thing2(id=4, foo=4, bar=5), ) s.add_all([t1, t2, t3, t4]) s.flush() t1.foo = 5 t2.foo = 6 t2.bar = 10 t3.foo = 7 t4.foo = 8 t4.bar = 12 if testing.db.dialect.implicit_returning: self.assert_sql_execution( testing.db, s.flush, CompiledSQL( "UPDATE test2 SET foo=%(foo)s " "WHERE test2.id = %(test2_id)s " "RETURNING test2.bar", [{"foo": 5, "test2_id": 1}], dialect="postgresql", ), CompiledSQL( "UPDATE test2 SET foo=%(foo)s, bar=%(bar)s " "WHERE test2.id = %(test2_id)s", [{"foo": 6, "bar": 10, "test2_id": 2}], dialect="postgresql", ), CompiledSQL( "UPDATE test2 SET foo=%(foo)s " "WHERE test2.id = %(test2_id)s " "RETURNING test2.bar", [{"foo": 7, "test2_id": 3}], dialect="postgresql", ), CompiledSQL( "UPDATE test2 SET foo=%(foo)s, bar=%(bar)s " "WHERE test2.id = %(test2_id)s", [{"foo": 8, "bar": 12, "test2_id": 4}], dialect="postgresql", ), ) else: self.assert_sql_execution( testing.db, s.flush, CompiledSQL( "UPDATE test2 SET foo=:foo WHERE test2.id = :test2_id", [{"foo": 5, "test2_id": 1}], ), CompiledSQL( "UPDATE test2 SET foo=:foo, bar=:bar " "WHERE test2.id = :test2_id", [{"foo": 6, "bar": 10, "test2_id": 2}], ),
<reponame>mochell/stormy_forerunners class plot_spectrogram(object): def __init__(self,time,fs, data,clevs=None, sample_unit=None, data_unit=None, ylim=None, time_unit=None, cmap=None): import matplotlib.pyplot as plt import numpy as np self.fs=fs[1:] self.time=time self.data=data[:,1:] self.clevs=clevs self.sample_unit=sample_unit if sample_unit is not None else 'df' self.data_unit=data_unit if data_unit is not None else 'X' self.time_unit=time_unit if time_unit is not None else 'dt' #self.cmap=cmap if cmap is not None else plt.cm.ocean_r self.cmap=cmap if cmap is not None else plt.cm.hsv self.ylim=ylim if ylim is not None else [fs[0],fs[-1]] def loglog(self): self.F=figure_axis_xy(fig_scale=2) plt.loglog(self.fs[1:],(self.Xdata[1:])) plt.ylabel(('|X|^2/f (' + self.data_unit + '^2/' + self.sample_unit+ ')')) plt.xlabel(('f (' + self.sample_unit+ ')')) plt.xlim(self.fs[1] ,self.fs[-1]) self.F.make_clear() plt.grid() def linear(self): self.F=figure_axis_xy(10,4,fig_scale=2) dd=10*np.log10(self.data[:-2,:]).T self.clevs=self.clevs if self.clevs is not None else clevels(dd) self.F.ax.set_yscale("log", nonposy='clip') tt = self.time.astype(DT.datetime) self.cs=plt.contourf(tt[:-2], self.fs[:],dd, self.clevs,cmap=self.cmap) #self.cs=plt.pcolormesh(self.time[:-2], self.fs[:],dd,cmap=self.cmap,shading='gouraud') print(self.clevs) plt.ylabel(('Power db (' + self.data_unit + '^2/' + self.sample_unit+ ')')) plt.xlabel(('f (' + self.sample_unit+ ')')) self.cbar= plt.colorbar(self.cs,pad=0.01)#, Location='right')# self.cbar.ax.aspect=100 self.cbar.outline.set_linewidth(0) self.cbar.set_label('('+self.data_unit+')') ax = plt.gca() #Set y-lim ax.set_ylim(self.ylim[0], self.ylim[1]) #format X-Axis ax.xaxis_date() Month = dates.MonthLocator() Day = dates.DayLocator(interval=5)#bymonthday=range(1,32) dfmt = dates.DateFormatter('%y-%b') ax.xaxis.set_major_locator(Month) ax.xaxis.set_major_formatter(dfmt) ax.xaxis.set_minor_locator(Day) # Set both ticks to be outside ax.tick_params(which = 'both', direction = 'out') ax.tick_params('both', length=6, width=1, which='major') ax.tick_params('both', length=3, width=1, which='minor') # Make grid white ax.grid() gridlines = ax.get_xgridlines() + ax.get_ygridlines() for line in gridlines: line.set_color('white') #line.set_linestyle('-') def power(self, anomalie=False): self.F=figure_axis_xy(10,4,fig_scale=2) dd=10*np.log10(self.data[:-1,:]) if anomalie is True: dd_tmp=dd.mean(axis=0).repeat(self.time.size-1) dd=dd- dd_tmp.reshape(self.fs.size,self.time.size-1).T dd=dd self.clevs=self.clevs if self.clevs is not None else clevels(dd) self.F.ax.set_yscale("log", nonposy='clip') tt = self.time.astype(DT.datetime) print(tt[:-1].shape, self.fs[:].shape,dd.T.shape) self.cs=plt.contourf(tt[:-1], self.fs[:],dd.T, self.clevs,cmap=self.cmap) self.x=np.arange(0,tt[:-1].size) #self.cs=plt.pcolormesh(self.time[:-2], self.fs[:],dd,cmap=self.cmap,shading='gouraud') print(self.clevs) plt.xlabel('Time') plt.ylabel(('f (' + self.sample_unit+ ')')) self.cbar= plt.colorbar(self.cs,pad=0.01)#, Location='right')# self.cbar.ax.aspect=100 self.cbar.outline.set_linewidth(0) self.cbar.set_label('Power db (' + self.data_unit + '^2/f )') ax = plt.gca() #Set y-lim ax.set_ylim(self.ylim[0], self.ylim[1]) #format X-Axis ax.xaxis_date() Month = dates.MonthLocator() Day = dates.DayLocator(interval=5)#bymonthday=range(1,32) dfmt = dates.DateFormatter('%y-%b') ax.xaxis.set_major_locator(Month) ax.xaxis.set_major_formatter(dfmt) ax.xaxis.set_minor_locator(Day) # Set both ticks to be outside ax.tick_params(which = 'both', direction = 'out') ax.tick_params('both', length=6, width=1, which='major') ax.tick_params('both', length=3, width=1, which='minor') # Make grid white ax.grid() gridlines = ax.get_xgridlines() + ax.get_ygridlines() for line in gridlines: line.set_color('white') line.set_linestyle('--') def imshow(self, shading=None, downscale_fac=None, anomalie=False, downscale_type=None, fig_size=None, ax=None,cbar=True): nopower=True self.power_imshow(shading, downscale_fac , anomalie, downscale_type, fig_size , nopower, ax=ax, cbar=cbar) self.cbar.set_label('Energy density (m^2/Hz)') def power_imshow(self, shading=None, downscale_fac=None, anomalie=False, downscale_type=None, fig_size=None , nopower=False, ax=None, cbar=True): import matplotlib.pyplot as plt import datetime as DT import matplotlib.colors as colors from matplotlib import dates import time import scipy.signal as signal import matplotlib.ticker as ticker import numpy as np from .tools import stats_format shading='gouraud' if shading is True else 'flat' fig_size=[10,4] if fig_size is None else fig_size if ax: assert type(ax) is tuple, "put ax as tuple ax=(ax,F)" self.F=ax[1] ax_local=ax[0] else: self.F=figure_axis_xy(fig_size[0], fig_size[1], fig_scale=2) ax_local=self.F.ax if nopower is True: dd=self.data else: dd=10*np.log10(self.data[:-1,:]) if anomalie is True: dd_tmp=dd.mean(axis=0).repeat(self.time.size-1) dd=dd- dd_tmp.reshape(self.fs.size,self.time.size-1).T self.clevs=self.clevs if self.clevs is not None else clevels(dd) norm = colors.BoundaryNorm(boundaries=self.clevs, ncolors=256) tt = self.time #tvec=np.arange(0,tt.size,1) ax_local.set_yscale("log", nonposy='clip') if downscale_fac is not None: if downscale_type =='inter': fn=[] for yr in np.arange(0,self.fs.size,downscale_fac): fn.append(np.mean(self.fs[yr:yr+downscale_fac])) else: ddn=np.empty((self.time.size-1)) fsn_p=gen_log_space(self.fs.size,int(np.round(self.fs.size/downscale_fac))) fsn_p_run=np.append(fsn_p,fsn_p[-1]) dd=dd.T #print(ddn.shape, fsn_p.shape) for fr in np.arange(0,fsn_p.size,1): #print(np.mean(dd[fsn_p[fr]:fsn_p[fr+1], :],axis=0).shape) ddn=np.vstack((ddn, np.mean(dd[fsn_p_run[fr]:fsn_p_run[fr+1], :],axis=0))) ddn=np.delete(ddn, 0,0) #print(ddn.shape) dd2=ddn fn=self.fs[fsn_p] if nopower is True: tt=tt else: tt=tt[:-1] #print(dd2.shape, fn.shape, tt.shape) else: if nopower is True: tt=tt else: tt=tt[:-1] dd2=dd.T fn=self.fs if isinstance(tt[0], np.datetime64): print('time axis is numpy.datetime64, converted to number for plotting') ttt=tt #print(ttt) elif isinstance(tt[0], np.timedelta64): print('time axis is numpy.timedelta64, converted to number for plotting') #print(tt) ttt=tt else: #print(type(tt[0])) #print(tt) print('time axis is not converted') ttt=tt stats_format(dd2) self.cs=plt.pcolormesh(ttt,fn ,dd2,cmap=self.cmap , norm=norm, shading=shading)#, origin='lower',aspect='auto', #interpolation='none', #extent=[tvec.min(),tvec.max(),self.fs.min(),self.fs.max()]) #self.F.ax.set_yscale("log", nonposy='clip') #self.cs=plt.pcolormesh(self.time[:-2], self.fs[:],dd,cmap=self.cmap,shading='gouraud') #print(self.clevs) plt.ylabel(('f (' + self.sample_unit+ ')')) if cbar is True: self.cbar= plt.colorbar(self.cs,pad=0.01)#, Location='right')# self.cbar.ax.aspect=100 self.cbar.outline.set_linewidth(0) self.cbar.set_label('Power db (' + self.data_unit + '^2/f )') ax =ax_local#plt.gca() if isinstance(tt[0], np.datetime64): plt.xlabel('Time') #Set y-lim ax.set_ylim(self.ylim[0], self.ylim[1]) ax.set_xlim(ttt[0], ttt[-1]) #format X-Axis #ax.xaxis_date() Month = dates.MonthLocator() Day = dates.DayLocator(interval=5)#bymonthday=range(1,32) dfmt = dates.DateFormatter('%b/%y') ax.xaxis.set_major_locator(Month) ax.xaxis.set_major_formatter(dfmt) ax.xaxis.set_minor_locator(Day) elif isinstance(tt[0], np.float64): plt.xlabel('Time') #Set y-lim ax.set_ylim(self.ylim[0], self.ylim[1]) ax.set_xlim(ttt[0], ttt[-1]) #format X-Axis #ax.xaxis_date() Month = dates.MonthLocator() Day = dates.DayLocator(interval=5)#bymonthday=range(1,32) dfmt = dates.DateFormatter('%b/%y') ax.xaxis.set_major_locator(Month) ax.xaxis.set_major_formatter(dfmt) ax.xaxis.set_minor_locator(Day) else: plt.xlabel('Time (' + self.time_unit+ ')') ax.set_ylim(self.ylim[0], self.ylim[1]) ax.xaxis.set_major_locator(ticker.MultipleLocator(5)) ax.xaxis.set_minor_locator(ticker.MultipleLocator(1)) #ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f')) # Set both ticks to be outside ax.tick_params(which = 'both', direction = 'out') ax.tick_params('both', length=6, width=1, which='major') ax.tick_params('both', length=3, width=1, which='minor') # Make grid white ax.grid() self.ax=ax gridlines = ax.get_xgridlines() + ax.get_ygridlines() for line in gridlines: line.set_color('white') #line.set_linestyle('-') self.x=ttt def linear_imshow(self, shading=None, downscale_fac=None, anomalie=False, downscale_type=None, fig_size=None , nopower=False, ax=None): import matplotlib.colors as colors from matplotlib import dates import time import scipy.signal as signal import matplotlib.ticker as ticker import numpy as np import matplotlib.pyplot as plt shading='gouraud' if shading is True else 'flat' fig_size=[10,4] if fig_size is None else fig_size if ax: assert type(ax) is tuple, "put ax as tuple ax=(ax,F)" self.F=ax[1] ax_local=ax[0] else: self.F=figure_axis_xy(fig_size[0], fig_size[1], fig_scale=2) ax_local=self.F.ax if nopower is True: dd=self.data else: dd=10*np.log10(self.data[:-1,:]) if anomalie is True: dd_tmp=dd.mean(axis=0).repeat(self.time.size-1) dd=dd- dd_tmp.reshape(self.fs.size,self.time.size-1).T self.clevs=self.clevs if self.clevs is not None else clevels(dd) norm = colors.BoundaryNorm(boundaries=self.clevs, ncolors=256) tt = self.time #tvec=np.arange(0,tt.size,1) self.F.ax.set_yscale("log", nonposy='clip') if downscale_fac is not None: if downscale_type =='inter': fn=[] for yr in np.arange(0,self.fs.size,downscale_fac): fn.append(np.mean(self.fs[yr:yr+downscale_fac])) else: ddn=np.empty((self.time.size-1)) fsn_p=gen_log_space(self.fs.size,int(np.round(self.fs.size/downscale_fac))) fsn_p_run=np.append(fsn_p,fsn_p[-1]) dd=dd.T #print(ddn.shape, fsn_p.shape) for fr in np.arange(0,fsn_p.size,1): #print(np.mean(dd[fsn_p[fr]:fsn_p[fr+1], :],axis=0).shape) ddn=np.vstack((ddn, np.mean(dd[fsn_p_run[fr]:fsn_p_run[fr+1], :],axis=0))) ddn=np.delete(ddn, 0,0) #print(ddn.shape) dd2=ddn fn=self.fs[fsn_p] if nopower is True: tt=tt else: tt=tt[:-1] #print(dd2.shape, fn.shape, tt.shape) else: if nopower is True: tt=tt else: tt=tt[:-1] dd2=dd.T fn=self.fs if isinstance(tt[0], np.datetime64): print('numpy.datetime64') ttt=tt #print(ttt) elif isinstance(tt[0], np.timedelta64): print('numpy.timedelta64') #print(tt) ttt=tt else: #print(type(tt[0])) #print(tt) print('something else') ttt=tt self.cs=plt.pcolormesh(ttt,fn ,dd2,cmap=self.cmap , norm=norm, shading=shading)#, origin='lower',aspect='auto', #interpolation='none', #extent=[tvec.min(),tvec.max(),self.fs.min(),self.fs.max()]) #self.F.ax.set_yscale("log", nonposy='clip') #self.cs=plt.pcolormesh(self.time[:-2], self.fs[:],dd,cmap=self.cmap,shading='gouraud') #print(self.clevs) plt.ylabel(('f (' + self.sample_unit+ ')')) self.cbar= plt.colorbar(self.cs,pad=0.01)#, Location='right')# self.cbar.ax.aspect=100 self.cbar.outline.set_linewidth(0) self.cbar.set_label('Power db(' + self.data_unit + '^2/f ') ax = plt.gca() if isinstance(tt[0], np.datetime64): plt.xlabel('Time') #Set y-lim ax.set_ylim(self.ylim[0], self.ylim[1]) ax.set_xlim(ttt[0], ttt[-1]) #format X-Axis #ax.xaxis_date() Month = dates.MonthLocator() Day = dates.DayLocator(interval=5)#bymonthday=range(1,32) dfmt = dates.DateFormatter('%b/%y') ax.xaxis.set_major_locator(Month) ax.xaxis.set_major_formatter(dfmt) ax.xaxis.set_minor_locator(Day) else: plt.xlabel('Time (' + self.time_unit+ ')') ax.set_ylim(self.ylim[0], self.ylim[1]) ax.xaxis.set_major_locator(ticker.MultipleLocator(5)) ax.xaxis.set_minor_locator(ticker.MultipleLocator(1)) #ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f')) # Set both ticks to be outside ax.tick_params(which = 'both', direction = 'out') ax.tick_params('both', length=6, width=1, which='major') ax.tick_params('both', length=3, width=1, which='minor') # Make grid white ax.grid() self.ax=ax gridlines = ax.get_xgridlines() + ax.get_ygridlines() for line in gridlines: line.set_color('white') #line.set_linestyle('-') self.x=np.arange(0,ttt.size+1) def set_xaxis_to_days(self, **kwargs): set_timeaxis_days(self.ax, **kwargs) def cut_nparray(var, low, high, verbose=False): if low < high: if low < var[0]: if verbose: print('out of lower limit!') if high > var[-1]: if verbose: print('out of upper limit!') print(high ,'>', var[-1]) return (var >=low) & (var <=high) elif high < low: if high < var[0]: print('limits flipped, out of lower limit!') if low > var[-1]: print('limits flipped, out of lower limit!') return (var >=high) & (var <=low) elif high == low: if verbose: print('find nearest') a=var-low return np.unravel_index(np.abs(a).argmin(),np.transpose(a.shape)) else: print('error') return class figure_axis_xy(object): """define standart XY Plot with reduced grafics""" def __init__(self,x_size=None,y_size=None,view_scale=None, fig_scale=None, container=False, dpi=180): import matplotlib.pyplot as plt xsize=x_size if x_size is not None else 8 ysize=y_size if y_size is not None else 5 viewscale=view_scale if view_scale is not None else 0.5 fig_scale=fig_scale if fig_scale is not None else 1 if container: self.fig=plt.figure(edgecolor='None',dpi=dpi*viewscale,figsize=(xsize*fig_scale, ysize*fig_scale),facecolor='w') else: self.fig, self.ax=plt.subplots(num=None, figsize=(xsize*fig_scale, ysize*fig_scale), dpi=dpi*viewscale, facecolor='w', edgecolor='None') def make_clear_weak(self): #turn off axis spine to the right #self.fig.tight_layout() self.ax.spines['right'].set_color("none") self.ax.yaxis.tick_left() # only ticks on the left side self.ax.spines['top'].set_color("none") self.ax.xaxis.tick_bottom() # only ticks on the left side def make_clear(self): self.make_clear_weak() def make_clear_strong(self): #turn off axis spine to the right #self.fig.tight_layout() self.ax.spines['right'].set_color("none") self.ax.spines['left'].set_color("none") self.ax.yaxis.tick_left() # only ticks on the left side self.ax.spines['top'].set_color("none") self.ax.spines['bottom'].set_color("none") self.ax.xaxis.tick_bottom() # only ticks on the left side def tight(self): #turn off axis spine to the right self.fig.tight_layout() def label(self, x='x',y='y',t=None): self.ax.set_xlabel(x) self.ax.set_ylabel(y) self.ax.set_title(t, y=1.04) def save(self,name=None,path=None, verbose=True): import datetime import os savepath=path if path is not None else os.path.join(os.path.dirname(os.path.realpath('__file__')),'plot/') if not os.path.exists(savepath): os.makedirs(savepath) #os.makedirs(savepath, exist_ok=True) name=name if name is not None else datetime.date.today().strftime("%Y%m%d_%I%M%p") #print(savepath) #print(name) extension='.pdf' full_name= (os.path.join(savepath,name)) + extension #print(full_name) self.fig.savefig(full_name, bbox_inches='tight', format='pdf', dpi=180) if verbose: print('save at: '+name) def save_pup(self,name=None,path=None, verbose=True): import datetime import re import os name=re.sub("\.", '_', name) savepath=path if path is not None else os.path.join(os.path.dirname(os.path.realpath('__file__')),'plot/') if not os.path.exists(savepath): os.makedirs(savepath) #os.makedirs(savepath, exist_ok=True) name=name if name is not None else datetime.date.today().strftime("%Y%m%d_%I%M%p") #print(savepath) #print(name) extension='.pdf' full_name= (os.path.join(savepath,name)) + extension #print(full_name) self.fig.savefig(full_name, bbox_inches='tight', format='pdf', dpi=300) if verbose: print('save at: ',full_name) def save_light(self,name=None,path=None, verbose=True): import datetime import os savepath=path
<filename>xga/imagetools/smooth.py<gh_stars>10-100 # This code is a part of XMM: Generate and Analyse (XGA), a module designed for the XMM Cluster Survey (XCS). # Last modified by <NAME> (<EMAIL>) 30/08/2021, 09:32. Copyright (c) <NAME> import os from random import randint from typing import Union import numpy as np import pandas as pd from astropy.convolution import Kernel, convolve, convolve_fft from fitsio import FITS from .. import OUTPUT from ..products import Image, RateMap, ExpMap def general_smooth(prod: Union[Image, RateMap], kernel: Kernel, mask: np.ndarray = None, fft: bool = False, norm_kernel: bool = True, sm_im: bool = True) -> Union[Image, RateMap]: """ Simple function to apply (in theory) any Astropy smoothing to an XGA Image/RateMap and create a new smoothed XGA data product. This general function will produce XGA Image and RateMap objects from any instance of an Astropy Kernel, and if a RateMap is passed as the input then you may choose whether to smooth the image component or the image/expmap (using sm_im); if you choose the former then the final smoothed RateMap will be produced by dividing the smoothed Image by the original ExpMap. :param Image/RateMap prod: The image/ratemap to be smoothed. If a RateMap is passed please see the 'sm_im' parameter for extra options. :param Kernel kernel: The kernel with which to smooth the input data. Should be an instance of an Astropy Kernel. :param np.ndarray mask: A mask to apply to the data while smoothing (removing point source interlopers for instance). The default is None, which means no mask is applied. This function expects a mask with 1s where the data you wish to keep is, and 0s where the data you wish to remove is - the style of mask produced by XGA. :param bool fft: Should a fast fourier transform method be used for convolution, default is False. :param bool norm_kernel: Whether to normalize the kernel to have a sum of one. :param bool sm_im: If a RateMap is passed, should the image component be smoothed rather than the actual RateMap. Default is True, where the Image will be smoothed and divided by the original ExpMap. If set to False, the resulting RateMap will be bodged, with the ExpMap all 1s on the sensor. :return: An XGA product with the smoothed Image or RateMap. :rtype: Image/RateMap """ raise NotImplementedError("This function is not fully implemented yet!") # First off we check the type of the product that has been passed in for smoothing if not isinstance(prod, Image) or type(prod) == ExpMap: raise TypeError("This function can only smooth data if input in the form of an XGA Image/RateMap.") # Also need to check that the kernel has the right number of dimensions if len(kernel.shape) != 2: raise ValueError("The smoothing kernel needs to be two-dimensional for application to Image/RateMap data - " "Gaussian2DKernel for instance.") # While we ask for masks in the style XGA produces (0s where you don't want data, 1s where you do), unfortunately # the smoothing functions seem to want the opposite, so I'll quickly invert the mask here if mask is not None: mask[mask == 0] = -1 mask[mask == 1] = 0 mask[mask == -1] = 1 # Read in the inventory of products relevant to the input image/ratemap inven = pd.read_csv(OUTPUT + "{}/inventory.csv".format(prod.obs_id), dtype=str) lo_en, hi_en = prod.energy_bounds key = "bound_{l}-{u}".format(l=float(lo_en.value), u=float(hi_en.value)) # This is what the Image storage_key method does, but I want to do it here so I can just read in an # existing image if possible, and not waste time convolving over again if prod.psf_corrected: key += "_" + prod.psf_model + "_" + str(prod.psf_bins) + "_" + prod.psf_algorithm + \ str(prod.psf_iterations) # I don't want to let people smooth an image that has already been smoothed, that seems daft if prod.smoothed: raise ValueError("You cannot smooth an already smoothed image") # Finally we add our information from the input kernel to the key, as the parse_smoothing method of Image is # static we can just make use of that sm, sp = Image.parse_smoothing(kernel) sp = "_".join([str(k) + str(v) for k, v in sp.items()]) key += "_sm{sm}_sp{sp}".format(sm=sm, sp=sp) # rel_inven = inven[(inven['type'] == 'image')] # This narrows down the inventory to images that have the exact same info key (with smoothing information in), as # the one we would create for the smoothed image we're making in this function. We'd only expect anything left # in rel_inven if someone has already run this exact smoothing on this exact image, in which case we'll just # retrieve that file rel_inven = inven[(inven['info_key'] == key) & (inven['type'] == 'image')] # Grabs certain information from the input product, primarily about what type it is, so we can infer where it # should live in the XGA storage directory structure if prod.instrument == 'combined' or prod.obs_id == 'combined': # The ObsID-Instrument string combinations in the input product ois = [o + i for o in prod.obs_ids for i in prod.instruments[o]] # Where the smoothed image will live/lives final_dest = OUTPUT + "combined/" # I want to check whether a file of this particular smoothing already exists, slightly more complicated # for combined images - its an ugly solution but I can't be bothered to make it nicer right now # This variable describes if the file already exists existing = False # This is where a new file would live, but will be overwritten if a matching image can be found final_name = "{{ri}}_{l}-{u}keVmerged_img.fits".format(l=lo_en.to('keV').value, u=hi_en.to('keV').value) for row_ind, row in rel_inven.iterrows(): split_insts = row['insts'].split('/') combo = [o + split_insts[o_ind] for o_ind, o in enumerate(row['obs_ids'].split('/'))] if set(combo) == set(ois): existing = True final_name = row['file_name'] break else: final_dest = OUTPUT + prod.obs_id + "/" # The filename of the expected smoothed image, it will be overwritten if one already exists final_name = "{o}_{i}_{{ri}}_{l}-{u}keV_img.fits".format(l=lo_en.to('keV').value, u=hi_en.to('keV').value, o=prod.obs_id, i=prod.instrument) # Easier to check for existing matching files than for combined images f_names = rel_inven[(rel_inven['obs_id'] == prod.obs_id) & (rel_inven['inst'] == prod.instrument)]['file_name'] if len(f_names) != 0: final_name = f_names.values[0] existing = True else: existing = False # Now to get into it properly, if its an XGA product then we need to retrieve the data as an array. Only check # whether its an instance of Image as that is the superclass for RateMap as well. if not existing and type(prod) == Image: data = prod.data.copy() elif not existing and type(prod) == RateMap and not sm_im: raise NotImplementedError("I haven't yet made sure that the rest of XGA will like this.") data = prod.data.copy() elif not existing and type(prod) == RateMap and sm_im: data = prod.image.data.copy() # Now we see which type of convolution the user has requested - entirely down to their discretion if not existing and not fft: sm_data = convolve(data, kernel, normalize_kernel=norm_kernel, mask=mask) elif not existing and fft: sm_data = convolve_fft(data, kernel, normalize_kernel=norm_kernel, mask=mask) # Now that Astropy has done the heavy lifting part of the smoothing, we save the image as an actual file, then # assemble the output XGA product if type(prod) == Image: new_path = final_dest + final_name # If the file didn't already exist, we need to actually save the smoothed array, otherwise we'll just read # the file in later if not existing: rand_ident = str(randint(0, 1e+8)) # Makes absolutely sure that the random integer hasn't already been used while any([str(rand_ident) in f for f in os.listdir(final_dest)]): rand_ident = str(randint(0, 1e+8)) # The final name of the new image file final_name = final_name.format(ri=rand_ident) new_path = final_dest + final_name # Writes out the smoothed data to the fits file with FITS(new_path, 'rw', clobber=True) as immo: immo.write(sm_data, header=prod.header) # Sets up the XGA product, regardless of whether its just been generated or it already # existed, the process is the same sm_prod = Image(new_path, prod.obs_id, prod.instrument, "", "", "", prod.energy_bounds[0], prod.energy_bounds[1], "", True, kernel) elif type(prod) == RateMap and not sm_im:
return "".join([ "K" * pieces.count(6 ^ w), "Q" * pieces.count(5 ^ w), "R" * pieces.count(4 ^ w), "B" * pieces.count(3 ^ w), "N" * pieces.count(2 ^ w), "P" * pieces.count(1 ^ w), "v", "K" * pieces.count(6 ^ b), "Q" * pieces.count(5 ^ b), "R" * pieces.count(4 ^ b), "B" * pieces.count(3 ^ b), "N" * pieces.count(2 ^ b), "P" * pieces.count(1 ^ b), ]) def subfactor(k: int, n: int) -> int: f = n l = 1 for i in range(1, k): f *= n - i l *= i + 1 return f // l def dtz_before_zeroing(wdl: int) -> int: return ((wdl > 0) - (wdl < 0)) * (1 if abs(wdl) == 2 else 101) class MissingTableError(KeyError): """Can not probe position because a required table is missing.""" pass class PairsData: def __init__(self) -> None: self.indextable = None self.sizetable = None self.data = None self.offset = None self.symlen = None self.sympat = None # type: int self.blocksize = None self.idxbits = None self.min_len = None self.base = None class PawnFileData: def __init__(self) -> None: self.precomp = {} self.factor = {} self.pieces = {} self.norm = {} class PawnFileDataDtz: def __init__(self) -> None: self.precomp = None self.factor = None self.pieces = None self.norm = None class Table: def __init__(self, path: PathLike, *, variant: Type[chess.Board] = chess.Board) -> None: self.path = path self.variant = variant self.write_lock = threading.RLock() self.initialized = False self.fd = None self.data = None self.read_condition = threading.Condition() self.read_count = 0 tablename, _ = os.path.splitext(os.path.basename(path)) self.key = normalize_tablename(tablename) self.mirrored_key = normalize_tablename(tablename, mirror=True) self.symmetric = self.key == self.mirrored_key # Leave the v out of the tablename to get the number of pieces. self.num = len(tablename) - 1 self.has_pawns = "P" in tablename black_part, white_part = tablename.split("v") if self.has_pawns: self.pawns = {0: white_part.count("P"), 1: black_part.count("P")} if self.pawns[1] > 0 and (self.pawns[0] == 0 or self.pawns[1] < self.pawns[0]): self.pawns[0], self.pawns[1] = self.pawns[1], self.pawns[0] else: j = 0 for piece_type in PCHR: if black_part.count(piece_type) == 1: j += 1 if white_part.count(piece_type) == 1: j += 1 if j >= 3: self.enc_type = 0 elif j == 2: self.enc_type = 2 else: # only for suicide j = 16 for _ in range(16): for piece_type in PCHR: if 1 < black_part.count(piece_type) < j: j = black_part.count(piece_type) if 1 < white_part.count(piece_type) < j: j = white_part.count(piece_type) self.enc_type = 1 + j def init_mmap(self) -> None: with self.write_lock: # Open fd. if self.fd is None: self.fd = os.open(self.path, os.O_RDONLY | os.O_BINARY if hasattr(os, "O_BINARY") else os.O_RDONLY) # Open mmap. if self.data is None: self.data = mmap.mmap(self.fd, 0, access=mmap.ACCESS_READ) def check_magic(self, magic: Optional[bytes], pawnless_magic: Optional[bytes]) -> bool: valid_magics = [magic, self.has_pawns and pawnless_magic] if self.data[:min(4, len(self.data))] not in valid_magics: raise IOError("invalid magic header: ensure {!r} is a valid syzygy tablebase file".format(self.path)) def setup_pairs(self, data_ptr: int, tb_size: int, size_idx: int, wdl: int) -> PairsData: d = PairsData() self._flags = self.data[data_ptr] if self.data[data_ptr] & 0x80: d.idxbits = 0 if wdl: d.min_len = self.data[data_ptr + 1] else: # http://www.talkchess.com/forum/viewtopic.php?p=698093#698093 d.min_len = 1 if self.variant.captures_compulsory else 0 self._next = data_ptr + 2 self.size[size_idx + 0] = 0 self.size[size_idx + 1] = 0 self.size[size_idx + 2] = 0 return d d.blocksize = self.data[data_ptr + 1] d.idxbits = self.data[data_ptr + 2] real_num_blocks = self.read_uint32(data_ptr + 4) num_blocks = real_num_blocks + self.data[data_ptr + 3] max_len = self.data[data_ptr + 8] min_len = self.data[data_ptr + 9] h = max_len - min_len + 1 num_syms = self.read_uint16(data_ptr + 10 + 2 * h) d.offset = data_ptr + 10 d.symlen = [0 for _ in range(h * 8 + num_syms)] d.sympat = data_ptr + 12 + 2 * h d.min_len = min_len self._next = data_ptr + 12 + 2 * h + 3 * num_syms + (num_syms & 1) num_indices = (tb_size + (1 << d.idxbits) - 1) >> d.idxbits self.size[size_idx + 0] = 6 * num_indices self.size[size_idx + 1] = 2 * num_blocks self.size[size_idx + 2] = (1 << d.blocksize) * real_num_blocks tmp = [0 for _ in range(num_syms)] for i in range(num_syms): if not tmp[i]: self.calc_symlen(d, i, tmp) d.base = [0 for _ in range(h)] d.base[h - 1] = 0 for i in range(h - 2, -1, -1): d.base[i] = (d.base[i + 1] + self.read_uint16(d.offset + i * 2) - self.read_uint16(d.offset + i * 2 + 2)) // 2 for i in range(h): d.base[i] <<= 64 - (min_len + i) d.offset -= 2 * d.min_len return d def set_norm_piece(self, norm: List[int], pieces) -> None: if self.enc_type == 0: norm[0] = 3 elif self.enc_type == 2: norm[0] = 2 else: norm[0] = self.enc_type - 1 i = norm[0] while i < self.num: j = i while j < self.num and pieces[j] == pieces[i]: norm[i] += 1 j += 1 i += norm[i] def calc_factors_piece(self, factor: List[int], order: int, norm: List[int]) -> int: if not self.variant.connected_kings: PIVFAC = [31332, 28056, 462] else: PIVFAC = [31332, 0, 518, 278] n = 64 - norm[0] f = 1 i = norm[0] k = 0 while i < self.num or k == order: if k == order: factor[0] = f if self.enc_type < 4: f *= PIVFAC[self.enc_type] else: f *= MFACTOR[self.enc_type - 2] else: factor[i] = f f *= subfactor(norm[i], n) n -= norm[i] i += norm[i] k += 1 return f def calc_factors_pawn(self, factor: int, order: int, order2: int, norm: List[int], f: int) -> int: i = norm[0] if order2 < 0x0f: i += norm[i] n = 64 - i fac = 1 k = 0 while i < self.num or k in [order, order2]: if k == order: factor[0] = fac fac *= PFACTOR[norm[0] - 1][f] elif k == order2: factor[norm[0]] = fac fac *= subfactor(norm[norm[0]], 48 - norm[0]) else: factor[i] = fac fac *= subfactor(norm[i], n) n -= norm[i] i += norm[i] k += 1 return fac def set_norm_pawn(self, norm: List[int], pieces) -> None: norm[0] = self.pawns[0] if self.pawns[1]: norm[self.pawns[0]] = self.pawns[1] i = self.pawns[0] + self.pawns[1] while i < self.num: j = i while j < self.num and pieces[j] == pieces[i]: norm[i] += 1 j += 1 i += norm[i] def calc_symlen(self, d: PairsData, s: int, tmp: List[int]) -> None: w = d.sympat + 3 * s s2 = (self.data[w + 2] << 4) | (self.data[w + 1] >> 4) if s2 == 0x0fff: d.symlen[s] = 0 else: s1 = ((self.data[w + 1] & 0xf) << 8) | self.data[w] if not tmp[s1]: self.calc_symlen(d, s1, tmp) if not tmp[s2]: self.calc_symlen(d, s2, tmp) d.symlen[s] = d.symlen[s1] + d.symlen[s2] + 1 tmp[s] = 1 def pawn_file(self, pos: chess.Square) -> int: for i in range(1, self.pawns[0]): if FLAP[pos[0]] > FLAP[pos[i]]: pos[0], pos[i] = pos[i], pos[0] return FILE_TO_FILE[pos[0] & 0x07] def encode_piece(self, norm: List[int], pos: List[chess.Square], factor: int) -> int: n = self.num if self.enc_type < 3: if pos[0] & 0x04: for i in range(n): pos[i] ^= 0x07 if pos[0] & 0x20: for i in range(n): pos[i] ^= 0x38 for i in range(n): if offdiag(pos[i]): break if i < (3 if self.enc_type == 0 else 2) and offdiag(pos[i]) > 0: for i in range(n): pos[i] = flipdiag(pos[i]) if self.enc_type == 0: # 111 i = int(pos[1] > pos[0]) j = int(pos[2] > pos[0]) + int(pos[2] > pos[1]) if offdiag(pos[0]): idx = TRIANGLE[pos[0]] * 63 * 62 + (pos[1] - i) * 62 + (pos[2] - j) elif offdiag(pos[1]): idx = 6 * 63 * 62 + DIAG[pos[0]] * 28 * 62 + LOWER[pos[1]] * 62 + pos[2] - j elif offdiag(pos[2]): idx = 6 * 63 * 62 + 4 * 28 * 62 + (DIAG[pos[0]]) * 7 * 28 + (DIAG[pos[1]] - i) * 28 + LOWER[pos[2]] else: idx = 6 * 63 * 62 + 4 * 28 * 62 + 4 * 7 * 28 + (DIAG[pos[0]] * 7 * 6) + (DIAG[pos[1]] - i) * 6 + (DIAG[pos[2]] - j) i = 3 elif self.enc_type
vty = self.dispatch(val, env, misc) defaults.append(cast(env, misc.cls, val, vty, ty, errmsg('DEFAULT_MISMATCH', misc.filename, lineno, k, ty), misc=misc)) args, argns = tuple(zip(*[self.visitarg(arg, env, misc) for arg in n.args])) if\ len(n.args) > 0 else ([], []) args = list(args) argns = list(argns) assert len(defaults) == len(n.defaults) if flags.PY_VERSION == 3: kw_defaults = [(fixup(self.dispatch(d, env, misc)[0], lineno) if d else None) for d in n.kw_defaults] nargs = dict(args=args, vararg=n.vararg, kwonlyargs=n.kwonlyargs, kwarg=n.kwarg, defaults=defaults, kw_defaults=kw_defaults) if flags.PY3_VERSION < 4: nargs['kwargannotation'] = None nargs['varargannotation'] = n.varargannotation elif flags.PY_VERSION == 2: nargs = dict(args=args, vararg=n.vararg, kwarg=None, defaults=defaults) return ast.arguments(**nargs), argns, [(k, Dyn) for k in specials] def visitarg(self, n, env, misc): def annotation(n): if misc.cls: if isinstance(n, ast.Name) and n.id == misc.cls.name: if misc.receiver: return ast.Attribute(value=misc.receiver, attr='__class__', ctx=ast.Load()) else: return None elif isinstance(n, ast.Attribute): return ast.Attribute(value=annotation(n.value), attr=n.attr, ctx=n.ctx) return n if flags.PY_VERSION == 3: return ast.arg(arg=n.arg, annotation=annotation(n.annotation)), n.arg else: return n, n.id def visitReturn(self, n, env, misc): if n.value: value, ty = self.dispatch(n.value, env, misc) value = cast(env, misc.cls, value, ty, misc.ret, errmsg('RETURN_ERROR', misc.filename, n, misc.ret), misc=misc) else: value = None if not subcompat(Void, misc.ret): return error_stmt(errmsg('RETURN_NONEXISTANT', misc.filename, n, misc.ret), lineno=n.lineno) return [ast.Return(value=value, lineno=n.lineno)] # Assignment stuff def visitAssign(self, n, env, misc): val, vty = self.dispatch(n.value, env, misc) ttys = [] targets = [] attrs = [] for target in n.targets: (ntarget, tty) = self.dispatch(target, env, misc) if flags.SEMANTICS == 'MONO' and isinstance(target, ast.Attribute) and \ not tyinstance(tty, Dyn): attrs.append((ntarget, tty)) else: ttys.append(tty) targets.append(ntarget) stmts = [] if targets: meet = n_info_join(ttys) if len(targets) == 1: err = errmsg('SINGLE_ASSIGN_ERROR', misc.filename, n, meet) else: err = errmsg('MULTI_ASSIGN_ERROR', misc.filename, n, ttys) val = cast(env, misc.cls, val, vty, meet, err, misc=misc) stmts.append(ast.Assign(targets=targets, value=val, lineno=n.lineno)) for target, tty in attrs: lval = cast(env, misc.cls, val, vty, tty, errmsg('SINGLE_ASSIGN_ERROR', misc.filename, n, tty), misc=misc) stmts.append(ast.Expr(ast.Call(func=ast.Name(id='retic_setattr_'+\ ('static' if \ tty.static() else 'dynamic'), ctx=ast.Load()), args=[target.value, ast.Str(s=target.attr), lval, tty.to_ast()], keywords=[], starargs=None, kwargs=None), lineno=n.lineno)) return stmts def visitAugAssign(self, n, env, misc): optarget = utils.copy_assignee(n.target, ast.Load()) assignment = ast.Assign(targets=[n.target], value=ast.BinOp(left=optarget, op=n.op, right=n.value, lineno=n.lineno), lineno=n.lineno) return self.dispatch(assignment, env, misc) def visitDelete(self, n, env, misc): targets = [] for t in n.targets: value, ty = self.dispatch(t, env, misc) targets.append(utils.copy_assignee(value, ast.Load())) return [ast.Expr(targ, lineno=n.lineno) for targ in targets] + \ [ast.Delete(targets=n.targets, lineno=n.lineno)] # Control flow stuff def visitIf(self, n, env, misc): test, tty = self.dispatch(n.test, env, misc) body = self.dispatch(n.body, env, misc) orelse = self.dispatch(n.orelse, env, misc) if n.orelse else [] return [ast.If(test=test, body=body, orelse=orelse, lineno=n.lineno)] def visitFor(self, n, env, misc): target, tty = self.dispatch(n.target, env, misc) iter, ity = self.dispatch(n.iter, env, misc) body = self.dispatch(n.body, env, misc) orelse = self.dispatch(n.orelse, env, misc) if n.orelse else [] targcheck = check_stmtlist(utils.copy_assignee(target, ast.Load()), tty, errmsg('ITER_CHECK', misc.filename, n, tty), lineno=n.lineno) if tyinstance(ity, List): iter_ty = List(tty) elif tyinstance(ity, Dict): iter_ty = Dict(tty, ity.values) elif tyinstance(ity, Tuple): iter_ty = Tuple(*([tty] * len(ity.elements))) else: iter_ty = Dyn return [ast.For(target=target, iter=cast(env, misc.cls, iter, ity, iter_ty, errmsg('ITER_ERROR', misc.filename, n, iter_ty), misc=misc), body=targcheck+body, orelse=orelse, lineno=n.lineno)] def visitWhile(self, n, env, misc): test, tty = self.dispatch(n.test, env, misc) body = self.dispatch(n.body, env, misc) orelse = self.dispatch(n.orelse, env, misc) if n.orelse else [] return [ast.While(test=test, body=body, orelse=orelse, lineno=n.lineno)] def visitWith(self, n, env, misc): body = self.dispatch(n.body, env, misc) if flags.PY_VERSION == 3 and flags.PY3_VERSION >= 3: items = [self.dispatch(item, env, misc) for item in n.items] return [ast.With(items=items, body=body, lineno=n.lineno)] else: context_expr, _ = self.dispatch(n.context_expr, env, misc) optional_vars, _ = self.dispatch(n.optional_vars, env, misc) if\ n.optional_vars else (None, Dyn) return [ast.With(context_expr=context_expr, optional_vars=optional_vars, body=body, lineno=n.lineno)] def visitwithitem(self, n, env, misc): context_expr, _ = self.dispatch(n.context_expr, env, misc) optional_vars, _ = self.dispatch(n.optional_vars, env, misc) if\ n.optional_vars else (None, Dyn) return ast.withitem(context_expr=context_expr, optional_vars=optional_vars) # Class stuff def visitClassDef(self, n, env, misc): #Keywords, kwargs, etc bases = [ast.Call(func=ast.Name(id='retic_actual', ctx=ast.Load()), args=[base], kwargs=None, starargs=None, keywords=[]) for\ base in [self.dispatch(base, env, misc)[0] for base in n.bases]] keywords = [] # Will be ignored if py2 if flags.PY_VERSION == 3: metaclass_handled = flags.SEMANTICS != 'MONO' for keyword in n.keywords: kval, _ = self.dispatch(keyword.value, env, misc) if flags.SEMANTICS == 'MONO' and keyword.arg == 'metaclass': metaclass_handled = True keywords.append(ast.keyword(arg=keyword.arg, value=kval)) if not metaclass_handled: logging.warn('Adding Monotonic metaclass to classdef at line %s: <%s>' % (n.lineno, n.name), 1) keywords.append(ast.keyword(arg='metaclass', value=ast.Name(id=runtime.Monotonic.__name__, ctx=ast.Load()))) nty = env[Var(n.name)] oenv = misc.extenv if misc.cls else env.copy() env = env.copy() initial_locals = {Var(n.name, n): nty} stype = ast.Assign(targets=[ast.Name(id='retic_class_type', ctx=ast.Store(), lineno=n.lineno)], value=nty.to_ast(), lineno=n.lineno) logging.debug('Class %s typechecker starting in %s' % (n.name, misc.filename), flags.PROC) rest, _ = misc.static.typecheck(n.body, env, initial_locals, typing.Misc(ret=Void, cls=nty, gensymmer=misc.gensymmer, typenames=misc.typenames, methodscope=True, extenv=oenv, extend=misc)) if flags.SEMANTICS not in ['MGDTRANS', 'TRANS']: body = [stype] + rest else: body = rest logging.debug('Class %s typechecker finished in %s' % (n.name, misc.filename), flags.PROC) name = n.name if n.name not in rtypes.TYPES else n.name + '_' assign = ast.Assign(targets=[ast.Name(id=name, ctx=ast.Store(), lineno=n.lineno)], value=cast(env, misc.cls, ast.Name(id=name, ctx=ast.Load(), lineno=n.lineno), Dyn, nty, errmsg('BAD_CLASS_INJECTION', misc.filename, n, nty), misc=misc), lineno=n.lineno) return [ast_trans.ClassDef(name=name, bases=bases, keywords=keywords, starargs=(n.starargs if hasattr(n, 'starargs') else None), kwargs=(n.kwargs if hasattr(n, 'kwargs') else None), body=body, decorator_list=n.decorator_list, lineno=n.lineno), assign] # Exception stuff # Python 2.7, 3.2 def visitTryExcept(self, n, env, misc): body = self.dispatch(n.body, env, misc) handlers = [] for handler in n.handlers: handler = self.dispatch(handler, env, misc) handlers.append(handler) orelse = self.dispatch(n.orelse, env, misc) if n.orelse else [] return [ast.TryExcept(body=body, handlers=handlers, orelse=orelse, lineno=n.lineno)] # Python 2.7, 3.2 def visitTryFinally(self, n, env, misc): body = self.dispatch(n.body, env, misc) finalbody = self.dispatch(n.finalbody, env, misc) return [ast.TryFinally(body=body, finalbody=finalbody, lineno=n.lineno)] # Python 3.3 def visitTry(self, n, env, misc): body = self.dispatch(n.body, env, misc) handlers = [] for handler in n.handlers: handler = self.dispatch(handler, env, misc) handlers.append(handler) orelse = self.dispatch(n.orelse, env, misc) if n.orelse else [] finalbody = self.dispatch(n.finalbody, env, misc) return [ast.Try(body=body, handlers=handlers, orelse=orelse, finalbody=finalbody, lineno=n.lineno)] def visitExceptHandler(self, n, env, misc): type, tyty = self.dispatch(n.type, env, misc) if n.type else (None, Dyn) body = self.dispatch(n.body, env, misc) if flags.PY_VERSION == 2 and n.name and type: name, nty = self.dispatch(n.name, env, misc) type = cast(env, misc.cls, type, tyty, nty, errmsg('EXCEPTION_ERROR', misc.filename, n, n.name, nty, n.name), misc=misc) else: name = n.name return ast.ExceptHandler(type=type, name=name, body=body, lineno=n.lineno) def visitRaise(self, n, env, misc): if flags.PY_VERSION == 3: exc, _ = self.dispatch(n.exc, env, misc) if n.exc else (None, Dyn) cause, _ = self.dispatch(n.cause, env, misc) if n.cause else (None, Dyn) return [ast.Raise(exc=exc, cause=cause, lineno=n.lineno)] elif flags.PY_VERSION == 2: type, _ = self.dispatch(n.type, env, misc) if n.type else (None, Dyn) inst, _ = self.dispatch(n.inst, env, misc) if n.inst else (None, Dyn) tback, _ = self.dispatch(n.tback, env, misc) if n.tback else (None, Dyn) return [ast.Raise(type=type, inst=inst, tback=tback, lineno=n.lineno)] def visitAssert(self, n, env, misc): test, _ = self.dispatch(n.test, env, misc) msg, _ = self.dispatch(n.msg, env, misc) if n.msg else (None, Dyn) return [ast.Assert(test=test, msg=msg, lineno=n.lineno)] # Declaration stuff def visitGlobal(self, n, env, misc): return [n] def visitNonlocal(self, n, env, misc): return [n] # Miscellaneous def visitExpr(self, n, env, misc): value, ty = self.dispatch(n.value, env, misc) return [ast.Expr(value=value, lineno=n.lineno)] def visitPass(self, n, env, misc): return [n] def visitBreak(self, n, env, misc): return [n] def visitContinue(self, n, env, misc): return [n] def visitPrint(self, n, env, misc): dest, _ = self.dispatch(n.dest, env, misc) if n.dest else (None, Void) values = [self.dispatch(val, env, misc)[0] for val in n.values] return [ast.Print(dest=dest, values=values, nl=n.nl, lineno=n.lineno)] def visitExec(self, n, env, misc): body, _ = self.dispatch(n.body, env, misc) globals, _ = self.dispatch(n.globals, env, misc) if n.globals else (None, Void) locals, _ = self.dispatch(n.locals, env, misc) if n.locals else (None, Void) return [ast.Exec(body=body, globals=globals, locals=locals, lineno=n.lineno)] ### EXPRESSIONS ### # Op stuff def visitBoolOp(self, n, env, misc): values = [] tys = [] for value in n.values: (value, ty) = self.dispatch(value, env, misc) values.append(value) tys.append(ty) ty = tyjoin(tys) return (ast.BoolOp(op=n.op, values=values, lineno=n.lineno), ty) def visitBinOp(self, n, env, misc): (left, lty) = self.dispatch(n.left, env, misc) (right, rty) = self.dispatch(n.right, env, misc) ty = binop_type(lty, n.op, rty) if not ty.top_free(): return error(errmsg('BINOP_INCOMPAT', misc.filename, n, lty, rty,
<reponame>thingalon/coldbrew<filename>src/Coldbrew.py import _Coldbrew import json import os import sys import time from _Coldbrew import * ############################################################ ######################PATCH JSON DUMPS###################### ############################################################ ''' Patch JSON Dumps to always produce proper JSON.''' ############################################################ _old_json_dumps = json.dumps def _new_json_dumps(*args, **kwargs): kwargs['allow_nan'] = False return _old_json_dumps(*args, **kwargs) json.dumps = _new_json_dumps ############################################################ #################START PRIVATE VARIABLES#################### ############################################################ ''' Various private variables that hold state.''' ############################################################ _slot_id = 0 _var_id = 0 _vars = {} # Stores references to Python variables that are shimmed in JavaScript by Proxy variables. _exception = None _builtins = None _finalized_options = {} class _StopIteration: pass ############################################################ ##################END PRIVATE VARIABLES##################### ############################################################ ############################################################ ##################START PUBLIC VARIABLES#################### ############################################################ ''' Various public variables that hold state or information.''' ############################################################ pyversion = os.environ['PYVERSION'] version = os.environ['COLDBREW_VERSION'] module_name = os.environ['COLDBREW_MODULE_NAME'] module_name_lower = os.environ['COLDBREW_MODULE_NAME_LOWER'] module_name_var = module_name _js_error = None ############################################################ ###################END PUBLIC VARIABLES##################### ############################################################ ############################################################ #################START PRIVATE FUNCTIONS#################### ############################################################ ''' Various private functions used by Coldbrew.''' ############################################################ def _async_advise(verb): return 'You '+verb+' use getVariableAsync(), runAsync(), runFunctionAsync(), or runFileAsync() instead.' def _try(f): try: return f() except Exception as e: return None def _run_guard(*args): if 'threadWorkers' in _finalized_options: import threading if threading.current_thread() is not threading.main_thread(): _error("You can only access JavaScript from the main Python thread.") return _Coldbrew._run(*args) def _run_string_guard(*args): if 'threadWorkers' in _finalized_options: import threading if threading.current_thread() is not threading.main_thread(): _error("You can only access JavaScript from the main Python thread.") return _Coldbrew._run_string(*args) _Coldbrew._run_guard = _run_guard _Coldbrew._run_string_guard = _run_string_guard del _run_guard del _run_string_guard def _warn(message): if not(_finalized_options['hideWarnings']): _Coldbrew._run("console.warn('Coldbrew Warning: '+"+json.dumps(message)+");") def _error(message): _Coldbrew._run("console.error('Coldbrew Error: '+"+json.dumps(message)+");") raise RuntimeError('Coldbrew Error: '+message) def _barg(arg): if type(arg) == bytes: return arg.decode('utf8') else: return arg def _getcwd(): return os.getcwd() def _clear_argv(): sys.argv.clear() def _append_argv(arg): sys.argv.append(arg) def _transform_prop(prop, reverse=None): if not(isinstance(reverse, list)) and _finalized_options['transformVariableCasing']: if prop.isalnum(): result = "" for i, c in enumerate(prop): if i < (len(prop)-1) and c.islower() and prop[i+1].isupper(): result += c.lower()+"_" else: result += c.lower() return result else: return prop elif _finalized_options['transformVariableCasing']: transformed_keys = [_transform_prop(p) for p in reverse] try: index_of_transformed_prop = transformed_keys.index(prop) return reverse[index_of_transformed_prop] except: return prop return prop def _call_func(func, *args): class Coldbrew: json = json _vars = _vars kwargs = {} newArgs = [] for arg in args: if isinstance(arg, dict) and '_internal_coldbrew_keywords' in arg and arg['_internal_coldbrew_keywords']: for key, val in arg['keywords'].items(): arg['keywords'][key] = _unserialize_from_js(eval(val, {'Coldbrew': Coldbrew})) kwargs.update(arg['keywords']) else: newArgs.append(arg) return func(*[_unserialize_from_js(arg) for arg in newArgs], **kwargs) ############################################################ ##################END PRIVATE FUNCTIONS##################### ############################################################ ############################################################ #################START MISCELLANEOUS SHIMS################## ############################################################ ''' Various small miscellaneous shims that shim really core functionality like sleep, standard input, exception handling, and import loading. ''' ############################################################ # Shim sys.version try: _sys_version_repo_index = sys.version.index(" (/b/s/w/ir/cache/git/chr") except: _sys_version_repo_index = None if _sys_version_repo_index: sys.version = sys.version[:_sys_version_repo_index]+" (Emscripten "+_Coldbrew._emscripten_version()+" / Coldbrew "+version+")]" # Shim sleep() def sleep(t): if is_async(): try: _Coldbrew._sleep(t) except SystemError: pass else: _warn("Python called sleep("+str(t)+"). Since you are not running in asynchronous mode, sleep() will busy wait (https://en.wikipedia.org/wiki/Busy_waiting) and lock the browser until the sleep is completed. "+_async_advise('may want to')) stime = time.time() while time.time()-stime < t: pass time.sleep = sleep # Monkey patch the Python sleep() to run our version sleep() # Shim execepthook _old_excepthook = sys.excepthook def _exception_handler(exctype, value, tb): global _exception _exception = { 'exctype': exctype.__name__, 'value': getattr(value, 'message') if hasattr(value, 'message') else str(value), 'filename': (tb and tb.tb_frame.f_code.co_filename) or None, 'tb_lineno': (tb and tb.tb_lineno) or None, } if hasattr(value, 'error_data'): _exception['error_data'] = value.error_data _old_excepthook(exctype, value, tb) sys.excepthook = _exception_handler # Shim import path finder import importlib.abc import importlib.machinery import sys class _ImportWatcher(object): @classmethod def find_module(cls, name, path, target=None): if 'threadWorkers' not in _finalized_options and name.split('.')[0] == 'threading': _warn("You attempted to use import 'threading' in Coldbrew without threading enabled. Please enable threading in the settings file.") return None class _ImportFinder(importlib.abc.MetaPathFinder): def find_spec(self, fullname, path, target=None): if fullname in sys.builtin_module_names: return importlib.machinery.ModuleSpec( fullname, importlib.machinery.BuiltinImporter, ) sys.meta_path.append(_ImportFinder()) sys.meta_path.insert(0, _ImportWatcher) # Shim standard input class _StandardInput(): def readline(self): linebuffer = '' while True: c = self.read(1) linebuffer += c if c == '\n' or c == '': break return linebuffer def read(self, size): if is_async(): return run_function(module_name_var+'''.onStandardInReadAsync''', size) else: return run_function(module_name_var+'''.onStandardInRead''', size) sys.stdin = _StandardInput() ############################################################ ##################END MISCELLANEOUS SHIMS################### ############################################################ ############################################################ ################START CREATE VARIABLE PROXY################# ############################################################ ''' Creates a native Python variable from a JavaScript variable reference that mirrors that JavaScript variable so it looks like a native Python variable. If the argument is not a JavaScript variable reference, it is simply returned. ''' ############################################################ def _create_variable_proxy(obj): if isinstance(obj, dict) and '_internal_coldbrew_javascript_object' in obj and obj['_internal_coldbrew_javascript_object']: class ProxiedJavaScriptVariable(JavaScriptVariable): def __init__(self): JavaScriptVariable.__setattr__(self, '__internal_coldbrew_native_js_worker_proxy', None) JavaScriptVariable.__setattr__(self, '__internal_coldbrew_native_js_worker_proxy_working', False) ProxiedJavaScriptVariable._internal_coldbrew_native_js_worker_proxy_func(self) def _internal_coldbrew_native_js_worker_proxy_func(self): if JavaScriptVariable.__getattribute__(self, '__internal_coldbrew_native_js_worker_proxy') is None and not JavaScriptVariable.__getattribute__(self, '__internal_coldbrew_native_js_worker_proxy_working'): JavaScriptVariable.__setattr__(self, '__internal_coldbrew_native_js_worker_proxy_working', True) JavaScriptVariable.__setattr__(self, '__internal_coldbrew_native_js_worker_proxy', _finalized_options['worker'] and (ProxiedJavaScriptVariable.__typeof_prop__(self, '_internal_coldbrew_native_js_worker_proxy') != "undefined" )) JavaScriptVariable.__setattr__(self, '__internal_coldbrew_native_js_worker_proxy_working', False) return JavaScriptVariable.__getattribute__(self, '__internal_coldbrew_native_js_worker_proxy') def __typeof_prop__(self, tprop): if tprop == '_internal_coldbrew_native_js_worker_proxy': return _get_variable("(("+module_name_var+"._vars['"+obj['uid']+"']._internal_coldbrew_native_js_worker_proxy === true) ? 'boolean' : 'undefined')") if tprop == '_internal_coldbrew_get_var_id' and ProxiedJavaScriptVariable._internal_coldbrew_native_js_worker_proxy_func(self): return 'string' return _get_variable("(("+module_name_var+"._vars['"+obj['uid']+"']._internal_coldbrew_native_js_worker_proxy === true) ? ("+module_name_var+"._vars['"+obj['uid']+"']._internal_coldbrew_typeof_prop("+_serialize_to_js(tprop)+")) : (typeof "+module_name_var+"._vars['"+obj['uid']+"']["+module_name_var+"._unserializeFromPython("+_serialize_to_js(tprop)+")]))") def __has_prop__(self, tprop): if tprop == '_internal_coldbrew_get_var_id' and ProxiedJavaScriptVariable._internal_coldbrew_native_js_worker_proxy_func(self): return True return _get_variable("(("+module_name_var+"._vars['"+obj['uid']+"']._internal_coldbrew_native_js_worker_proxy === true) ? ("+module_name_var+"._vars['"+obj['uid']+"']._internal_coldbrew_has_prop("+_serialize_to_js(tprop)+")) : ("+module_name_var+"._unserializeFromPython("+_serialize_to_js(tprop)+") in "+module_name_var+"._vars['"+obj['uid']+"']))") def __call__(self, *args): if obj['constructable'] or obj['callable']: return _get_variable(module_name_var+"._callFunc("+json.dumps(is_async())+","+json.dumps(obj['constructable'])+", "+module_name_var+"._vars['"+obj['uid']+"'],"+','.join([_serialize_to_js(arg) for arg in args])+")") else: return JavaScriptVariable.__call__(self) def __str__(self): hasProp = ProxiedJavaScriptVariable.__has_prop__(self, 'toString') if not hasProp: return ProxiedJavaScriptVariable.__repr__(self) if ProxiedJavaScriptVariable._internal_coldbrew_native_js_worker_proxy_func(self): return ProxiedJavaScriptVariable.__getattr__(self, 'toString')() else: return _get_variable(module_name_var+"._vars['"+obj['uid']+"'].toString()") def __repr__(self): if obj['constructable'] or obj['callable']: return "<JavaScriptVariable '"+obj['name']+"'>" else: return '<JavaScriptVariable '+obj['type']+'.instance at '+obj['uid']+' (use str() to get the string representation)>' def __inspect__(self, transform = True): lookup = set() if not ProxiedJavaScriptVariable._internal_coldbrew_native_js_worker_proxy_func(self): res = _get_variable(module_name_var+"._vars['"+obj['uid']+"'] && Object.getOwnPropertyNames("+module_name_var+"._vars['"+obj['uid']+"']).concat(Object.getOwnPropertyNames(Object.getPrototypeOf("+module_name_var+"._vars['"+obj['uid']+"'])))") else: res = _get_variable(module_name_var+"._vars['"+obj['uid']+"'] && " + module_name_var+"._vars['"+obj['uid']+"']._internal_coldbrew_own_keys")() res = res or [] res = [x for x in res if x not in lookup and lookup.add(x) is None] if transform: return JavaScriptVariable.internal_key_defs+[_transform_prop(p) for p in res] else: return JavaScriptVariable.internal_key_defs+res def __destroy__(self): if ProxiedJavaScriptVariable._internal_coldbrew_native_js_worker_proxy_func(self): _get_variable(module_name_var+"._vars['"+obj['uid']+"']._internal_coldbrew_destroy")() return _run("delete "+module_name_var+"._vars['"+obj['uid']+"']") def __getattr__(self, prop): if prop == '_internal_coldbrew_native_js_worker_proxy': return ProxiedJavaScriptVariable._internal_coldbrew_native_js_worker_proxy_func(self) elif prop == '__destroyed__': return _get_variable("!("+module_name_var+"._vars.hasOwnProperty('"+obj['uid']+"'))") elif prop == '__type__': return obj['type'] elif prop == '__uid__': return obj['uid'] tprop = _transform_prop(prop, ProxiedJavaScriptVariable.__inspect__(self, False)) typeofProp = ProxiedJavaScriptVariable.__typeof_prop__(self, tprop) hasProp = ProxiedJavaScriptVariable.__has_prop__(self, tprop) if not hasProp: raise AttributeError("'"+obj['type']+"' object has no attribute '"+tprop+"'") else: if typeofProp == 'function': if ProxiedJavaScriptVariable._internal_coldbrew_native_js_worker_proxy_func(self): return _get_variable(module_name_var+"._vars['"+obj['uid']+"']["+module_name_var+"._unserializeFromPython("+_serialize_to_js(tprop)+")]") else: return _get_variable(module_name_var+"._vars['"+obj['uid']+"']["+module_name_var+"._unserializeFromPython("+_serialize_to_js(tprop)+")].bind("+module_name_var+"._vars['"+obj['uid']+"'])") else: return _get_variable(module_name_var+"._vars['"+obj['uid']+"']["+module_name_var+"._unserializeFromPython("+_serialize_to_js(tprop)+")]") def __setattr__(self, prop, value): tprop = _transform_prop(prop, ProxiedJavaScriptVariable.__inspect__(self, False)) _run(module_name_var+"._vars['"+obj['uid']+"']["+module_name_var+"._unserializeFromPython("+_serialize_to_js(tprop)+")] = "+module_name_var+"._unserializeFromPython("+_serialize_to_js(value)+")") return value def __delattr__(self, prop): tprop = _transform_prop(prop, ProxiedJavaScriptVariable.__inspect__(self, False)) hasProp = ProxiedJavaScriptVariable.__has_prop__(self, tprop) if not hasProp: raise AttributeError(tprop) return _run("delete "+module_name_var+"._vars['"+obj['uid']+"']["+module_name_var+"._unserializeFromPython("+_serialize_to_js(tprop)+")]") def __dir__(self): return ProxiedJavaScriptVariable.__inspect__(self) def __del__(self): ProxiedJavaScriptVariable.__destroy__(self) def __len__(self): hasPropLength = ProxiedJavaScriptVariable.__has_prop__(self, 'length') typeofPropSize = ProxiedJavaScriptVariable.__typeof_prop__(self, 'size') hasPropSize = ProxiedJavaScriptVariable.__has_prop__(self, 'size') if hasPropLength: return _get_variable(module_name_var+"._vars['"+obj['uid']+"'].length") elif typeofPropSize == 'function': return _get_variable(module_name_var+"._vars['"+obj['uid']+"'].size")() elif hasPropSize: return _get_variable(module_name_var+"._vars['"+obj['uid']+"'].size") else: return object.__len__(self) def __iter__(self): if _get_variable(module_name_var+"._vars['"+obj['uid']+"'][Symbol.iterator]") is None: raise TypeError("'"+obj['type']+"' object is not iterable") if not ProxiedJavaScriptVariable._internal_coldbrew_native_js_worker_proxy_func(self): jsiter = _get_variable(module_name_var+"._vars['"+obj['uid']+"'][Symbol.iterator].bind("+module_name_var+"._vars['"+obj['uid']+"'])")() else: jsiter = _get_variable(module_name_var+"._vars['"+obj['uid']+"'][Symbol.iterator]")() while True: nexti = jsiter.next() if nexti['done'] == True: break else: yield nexti['value'] def __getitem__(self, prop): return ProxiedJavaScriptVariable.__getattr__(self, prop) def __setitem__(self, prop, value): return ProxiedJavaScriptVariable.__setattr__(self, prop, value) def __delitem__(self, prop): return ProxiedJavaScriptVariable.__delattr__(self, prop) def __contains__(self, prop): if type(prop) == str: tprop = _transform_prop(prop, ProxiedJavaScriptVariable.__inspect__(self, False)) else: tprop = prop if not ProxiedJavaScriptVariable._internal_coldbrew_native_js_worker_proxy_func(self): return _get_variable(module_name_var+"._unserializeFromPython("+_serialize_to_js(tprop)+") in "+module_name_var+"._vars['"+obj['uid']+"']") else: return _get_variable(module_name_var+"._vars['"+obj['uid']+"']._internal_coldbrew_has("+module_name_var+"._unserializeFromPython("+_serialize_to_js(tprop)+"))") return ProxiedJavaScriptVariable() else: return obj ############################################################ #################END CREATE VARIABLE PROXY################## ############################################################ ############################################################ ################START COMMUNICATION HELPERS################# ############################################################ ''' Functions that facilitate communcation between Python and JavaScript ''' ############################################################ def _serialize_to_js(obj): global _var_id global _vars if JavaScriptVariable.is_javascript_variable(obj): if obj._internal_coldbrew_native_js_worker_proxy == True: return json.dumps({ '_internal_coldbrew_get_js_var': True, 'uid': obj._internal_coldbrew_get_var_id, }) else: return json.dumps({ '_internal_coldbrew_var': True, 'uid': obj.__uid__, }) try: if hasattr(obj, '__dict__'): raise TypeError() return json.dumps(obj) except TypeError as e: _var_id += 1 uid = '_internal_pyvar_'+str(_var_id) _vars[uid] = obj return json.dumps({ '_internal_coldbrew_python_object': True, 'is_async': is_async(), 'uid': uid, 'constructable': type(obj) == type, 'callable': callable(obj), 'type': obj.__class__.__name__.replace('-', '_'), 'name': (obj.__name__ if hasattr(obj, '__name__') else ('PythonCallable' if callable(obj) else 'PythonUnnamed')).replace('<', '').replace('>', '').replace('-', '_'), }) def _unserialize_from_js(arg): global _vars arg = _create_variable_proxy(arg) if isinstance(arg, dict) and '_internal_coldbrew_get_var' in arg and arg['_internal_coldbrew_get_var']: jsarg = _get_variable(module_name_var+'''._main_thread_vars["'''+arg['uid']+'''"]''') # Grab the JavaScript native variable argument _Coldbrew._run_guard('''delete '''+module_name_var+'''._main_thread_vars["'''+arg['uid']+'''"]''') # Clean up the temporary reference return jsarg elif isinstance(arg, dict) and '_internal_coldbrew_var' in arg and arg['_internal_coldbrew_var']: return _vars[arg['uid']] else: return arg ############################################################ #################END COMMUNICATION HELPERS################## ############################################################ ############################################################ ####################START PUBLIC CLASSES#################### ''' Public classes that Python code can interact with ''' ############################################################ class JavaScriptError(Exception): pass class JavaScriptVariable(object): internal_key_defs = ['__type__', '__uid__', '__inspect__', '__destroy__', '__destroyed__', '__str__', '__repr__'] @staticmethod def is_javascript_variable(obj): return isinstance(obj, JavaScriptVariable) ############################################################ #####################END PUBLIC CLASSES##################### ############################################################ ############################################################ ####################START PUBLIC FUNCTIONS################## ############################################################ ''' Public functions that allow Python code to interact with the Coldbrew environment ''' ############################################################ # Runs in worker def _get_variable(expression): _internal_coldbrew_native_js_worker_proxy = _finalized_options['worker'] class Coldbrew: json = json _vars = _vars def __get_variable(expression): global _js_error val = eval(_Coldbrew._run_string_guard(module_name_var+"._serializeToPython("+expression+", true) || null"), {'Coldbrew': Coldbrew}) if isinstance(val, dict) and '_internal_coldbrew_error' in val and val['_internal_coldbrew_error']: error =
<gh_stars>0 from django.test import TestCase from django.test import Client from django_blog_it.django_blog_it.models import Category, Post, Tags, PostHistory, UserRole, Page from django.contrib.auth.models import User from django_blog_it.django_blog_it.forms import BlogCategoryForm, BlogPostForm, AdminLoginForm from django.core.urlresolvers import reverse from django_blog_it.django_blog_it.models import Menu, Theme from .forms import UserForm # models test class category_models_test(TestCase): def create_category(self, name="simple page", description="simple page content"): user = User.objects.create_superuser('<EMAIL>', 'micro-test', 'mp') return Category.objects.create(name=name, description=description, user=user) def test_category_creation(self): w = self.create_category() self.assertTrue(isinstance(w, Category)) self.assertEqual(w.__str__(), w.name) # models test class tags_models_test(TestCase): def create_tags(self, name="simple page"): return Tags.objects.create(name=name) def test_category_creation(self): w = self.create_tags() self.assertTrue(isinstance(w, Tags)) self.assertEqual(w.__str__(), w.name) # models test class pages_models_test(TestCase): def create_pages(self, title="simple page", content="simple content", meta_description="meta description", meta_title="meta title"): return Page.objects.create(title=title, content=content, meta_description=meta_description, meta_title=meta_title) def test_page_creation(self): w = self.create_pages() self.assertTrue(isinstance(w, Page)) self.assertEqual(w.__str__(), w.title) # models test class post_models_test(TestCase): def create_post( self, tag="simple page", category="simple page", description="simple page content", title="post", content="content", status="D" ): user = User.objects.create_superuser('<EMAIL>', 'micro-test', 'mp') category = Category.objects.create(name=category, description=description, user=user) tag = Tags.objects.create(name=tag) return Post.objects.create(category=category, user=user, content=content, title=title, status=status) def test_category_creation(self): w = self.create_post() self.assertTrue(isinstance(w, Post)) self.assertEqual(w.__str__(), w.title) class post_history_models_test(TestCase): def create_post_history(self, content="simple content"): user = User.objects.create_superuser('<EMAIL>', 'micro-test', 'mp') category = Category.objects.create(name='category', description='description', user=user) post = Post.objects.create(category=category, user=user, content='content', title='title', status='Published') return PostHistory.objects.create(content=content, post=post, user=user) def test_category_creation(self): w = self.create_post_history() self.assertTrue(isinstance(w, PostHistory)) self.assertEqual(w.__str__(), str(w.user.get_username()) + ' ' + str(w.content) + ' ' + str(w.post.title)) # class image_file_models_test(TestCase): # def create_image_file(self, content="simple content"): # upload_file = open('/django_blog_it/static/favicon.png', 'rb') # return Image_File.objects.create(Image_File=upload_file, thumbnail=upload_file, upload=upload_file) # def test_category_creation(self): # w = self.create_image_file() # self.assertTrue(isinstance(w, Image_File)) # self.assertEqual(w.__str__(), str(w.date_created())) class django_blog_it_forms_test(TestCase): def get_category(self): self.category2 = Category.objects.create(name='generators', description='generators', user=self.user) return self.category2 def setUp(self): self.client = Client() self.user = User.objects.create_superuser( '<EMAIL>', 'mp', 'mp') self.employee = User.objects.create_user( '<EMAIL>', 'mp', 'mp') self.category = Category.objects.create( name='salesforce', description='salesforce desc', user=self.user, is_active=True) self.blogppost = Post.objects.create( title='python introduction', user=self.user, content='This is content', category=self.category, status='Published') def test_blogpostform(self): data = {'title': 'jquery introduction', 'content': 'This is content', 'category': self.category.id, 'status': 'Published', 'is_superuser': 'True', 'slug': 'jquery-introduction'} form = BlogPostForm(data=data) self.assertTrue(form.is_valid()) form = BlogPostForm(data=data, user_role='Author') self.assertTrue(form.is_valid()) def test_BlogCategoryForm(self): data = {'name': 'django form', 'description': 'django', 'user': self.category.id} form = BlogCategoryForm(data=data) self.assertTrue(form.is_valid()) form = BlogCategoryForm(data=data) self.assertTrue(form.is_valid()) data['name'] = 'salesforce' form = BlogCategoryForm(data=data) self.assertFalse(form.is_valid()) data['name'] = self.category.name form = BlogCategoryForm(data=data, instance=self.get_category()) self.assertFalse(form.is_valid()) def test_AdminLoginForm(self): form = AdminLoginForm( data={'username': '<EMAIL>', 'password': 'mp'}) self.assertTrue(form.is_valid()) form = AdminLoginForm( data={'username': '<EMAIL>', 'password': '<PASSWORD>'}) self.assertFalse(form.is_valid()) form = AdminLoginForm( data={'username': '<EMAIL>', 'password': 'mp'}) self.assertTrue(form.is_valid()) def tearDown(self): super(django_blog_it_forms_test, self).tearDown() if hasattr(self, 'category2'): self.category2.delete() class django_blog_it_views_get(TestCase): def setUp(self): self.client = Client() self.user = User.objects.create_superuser( '<EMAIL>', 'micro-test', 'mp') self.employee = User.objects.create_user( '<EMAIL>', 'micro', 'mp') self.category = Category.objects.create( name='django', description='django desc', user=self.user, is_active=True) self.linuxcategory = Category.objects.create( name='linux', description='django desc', user=self.user, is_active=True) self.blogppost = Post.objects.create( title='other python introduction', user=self.user, content='This is content', category=self.category, status='Published', slug="other-python-introduction") self.tag = Tags.objects.create(name='testtag') self.blogppost.tags.add(self.tag) self.pythonpost = Post.objects.create( title='decorator', user=self.user, content='This is content', category=self.category, status='Published', slug="decorator") def test_blog_get(self): response = self.client.get('/dashboard/') self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'dashboard/new_admin-login.html') response = self.client.post( '/dashboard/', {'email': '<EMAIL>', 'password': '<PASSWORD>'}) self.assertEqual(response.status_code, 200) response = self.client.post( '/dashboard/', {'email': '<EMAIL>', 'password': '<PASSWORD>'}) self.assertEqual(response.status_code, 200) response = self.client.post( '/dashboard/', {'email': '<EMAIL>', 'password': '<PASSWORD>'}) self.assertEqual(response.status_code, 200) response = self.client.post( '/dashboard/', {'email': '<EMAIL>', 'password': '<PASSWORD>'}) self.assertEqual(response.status_code, 200) response = self.client.get('/dashboard/') self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'dashboard/new_admin-login.html') user_login = self.client.login(username='<EMAIL>', password='mp') self.assertTrue(user_login) response = self.client.get('/dashboard/view/' + str(self.blogppost.slug) + '/') self.assertEqual(response.status_code, 200) # self.assertTemplateUsed(response, 'dashboard/blog/blog_view.html') response = self.client.get('/dashboard/logout/') self.assertEqual(response.status_code, 302) def test_blog_post(self): user_login = self.client.login(username='<EMAIL>', password='mp') self.assertTrue(user_login) response = self.client.get('/dashboard/') self.assertEqual(response.status_code, 302) response = self.client.get('/dashboard/blog/') self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'dashboard/blog/new_blog_list.html') response = self.client.post('/dashboard/blog/', {'select_status': '', 'search_text': ''}) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'dashboard/blog/new_blog_list.html') response = self.client.post('/dashboard/blog/', {'select_status': 'Published', 'search_text': ''}) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'dashboard/blog/new_blog_list.html') response = self.client.post( '/dashboard/blog/', { 'select_status': 'Published', 'search_text': str(self.category.id) }) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'dashboard/blog/new_blog_list.html') response = self.client.post('/dashboard/blog/', {'select_status': '', 'search_text': str(self.category.id)}) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'dashboard/blog/new_blog_list.html') response = self.client.get('/dashboard/category/') self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'dashboard/category/new_categories_list.html') response = self.client.post('/dashboard/category/', {'select_status': '', 'category': []}) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'dashboard/category/new_categories_list.html') response = self.client.post('/dashboard/category/', {'select_status': 'True', 'category': []}) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'dashboard/category/new_categories_list.html') response = self.client.post('/dashboard/category/', {'select_status': 'False', 'category': []}) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'dashboard/category/new_categories_list.html') response = self.client.post( '/dashboard/category/', { 'select_status': 'Published', 'category': [str(self.category.id)] }) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'dashboard/category/new_categories_list.html') response = self.client.post('/dashboard/category/', {'select_status': '', 'category': [str(self.category.id)]}) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'dashboard/category/new_categories_list.html') response = self.client.get('/dashboard/category/add/') self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'dashboard/category/new_category_add.html') response = self.client.post( '/dashboard/category/add/', { 'name': 'python', 'description': 'Python description', 'user': str(self.user.id) }) self.assertEqual(response.status_code, 200) self.assertTrue('Successfully added your category' in str(response.content)) response = self.client.post( '/dashboard/category/add/', {'description': 'python'}) self.assertEqual(response.status_code, 200) self.assertFalse('Successfully added your category' in str(response.content)) response = self.client.get('/dashboard/category/edit/django/') self.assertEqual(response.status_code, 200) response = self.client.post( '/dashboard/category/edit/django/', {'name': 'django', 'description': 'django', 'user': str(self.user.id)}) self.assertEqual(response.status_code, 200) self.assertTrue('Successfully updated your category' in str(response.content)) response = self.client.post( '/dashboard/category/edit/django/', {'name': 'jquery', 'description': 'django', 'user': str(self.user.id)}) self.assertEqual(response.status_code, 200) self.assertTrue('Successfully updated your category' in str(response.content)) response = self.client.post( '/dashboard/category/edit/python/', {'description': 'python'}) self.assertEqual(response.status_code, 200) self.assertFalse('Successfully updated your category' in str(response.content)) def test_blog_with_super_admin(self): user_login = self.client.login(username='<EMAIL>', password='mp') self.assertTrue(user_login) response = self.client.get('/dashboard/view/' + str(self.blogppost.slug) + '/') self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'dashboard/blog/new_blog_view.html') response = self.client.get('/dashboard/upload_photos/', {'CKEditorFuncNum': '/dashboard/'}) self.assertEqual(response.status_code, 200) context = {'CKEditorFuncNum': '/dashboard/'} response = self.client.get('/dashboard/upload_photos/', context) self.assertEqual(response.status_code, 200) # recent photos response = self.client.get('/dashboard/recent_photos/') self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'dashboard/browse.html') response = self.client.get('/dashboard/bulk_actions_blog/') self.assertEqual(response.status_code, 200) response = self.client.get('/dashboard/bulk_actions_blog/', {'blog_ids[]': [str(self.blogppost.id)]}) self.assertEqual(response.status_code, 200) response = self.client.get( '/dashboard/bulk_actions_blog/', { 'blog_ids[]': [str(self.blogppost.id)], 'action': 'Published' }) self.assertEqual(response.status_code, 200) response = self.client.get( '/dashboard/bulk_actions_blog/', { 'blog_ids[]': [str(self.pythonpost.id)], 'action': 'Delete' }) self.assertEqual(response.status_code, 200) # bulk actions category response = self.client.get('/dashboard/bulk_actions_category/') self.assertEqual(response.status_code, 200) response = self.client.get('/dashboard/bulk_actions_category/', {'blog_ids[]': [str(self.category.id)]}) self.assertEqual(response.status_code, 200) response = self.client.get( '/dashboard/bulk_actions_category/', { 'blog_ids[]': [str(self.category.id)], 'action': 'True' }) self.assertEqual(response.status_code, 200) response = self.client.get( '/dashboard/bulk_actions_category/', { 'blog_ids[]': [str(self.linuxcategory.id)], 'action': 'Delete' }) self.assertEqual(response.status_code, 200) response = self.client.get( '/dashboard/bulk_actions_category/', { 'blog_ids[]': [str(self.category.id)], 'action': 'False' }) self.assertEqual(response.status_code, 200) # delete category response = self.client.post( '/dashboard/category/add/', { 'name': 'python', 'description': 'Python description', 'user': str(self.user.id) }) response = self.client.get('/dashboard/category/delete/python/') self.assertEqual(response.status_code, 302) class blog_post_creation(TestCase): def get_author_role(self): self.author_role = UserRole.objects.create(user=self.user, role='Author') def setUp(self): self.client = Client() self.user = User.objects.create_superuser( '<EMAIL>', 'mp', 'mp') self.employee = User.objects.create_user( '<EMAIL>', 'mp', 'mp') self.category = Category.objects.create( name='salesforce', description='salesforce desc', user=self.user, is_active=True) self.post = Post.objects.create(title="apache", slug="apache", category=self.category, user=self.user) def test_blog_post_add(self): user_login = self.client.login(username='<EMAIL>', password='mp') self.assertTrue(user_login) response = self.client.get('/dashboard/add/') self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'dashboard/blog/new_blog_add.html') response = self.client.post( reverse("blog_add"), { 'title': 'python introduction', 'content': 'This is content', 'category': self.category.id, 'status': 'Published', 'tags': 'django', 'is_superuser': 'True', 'slug': 'python-introduction-1', 'slugs-MAX_NUM_FORMS': ['1000'], 'slugs-TOTAL_FORMS': ['3'], 'slugs-MIN_NUM_FORMS': ['0'], 'slugs-0-slug': ['python-introduction-1'], 'slugs-1-slug': [''], 'slugs-2-slug': [''], 'slugs-INITIAL_FORMS': ['0'], }) self.assertEqual(response.status_code, 200) # self.assertTrue('Successfully posted your blog' in str(response.content)) response = self.client.post( '/dashboard/add/', { 'title': 'python introduction', 'content': '', 'category': self.category.id, 'status': 'Published', 'tags': 'django', 'is_superuser': 'True', 'slug': 'python-introduction-1' }) self.assertEqual(response.status_code, 200) self.assertFalse('Successfully posted your blog' in str(response.content)) response = self.client.post('/dashboard/add/', {'content': '', 'title': ''}) self.assertEqual(response.status_code, 200) self.assertFalse('Successfully posted your blog' in str(response.content)) response = self.client.post( '/dashboard/add/', { 'title': 'testing', 'content': 'This is content', 'category': self.category.id, 'status': 'Published', 'tags': 'django', 'is_superuser': 'True', 'slug': 'testing', 'slugs-MAX_NUM_FORMS': ['1000'], 'slugs-TOTAL_FORMS': ['3'], 'slugs-MIN_NUM_FORMS': ['0'], 'slugs-0-slug': ['testing-11223'], 'slugs-1-slug': [''], 'slugs-2-slug': [''], 'slugs-INITIAL_FORMS': ['0'], }) self.assertEqual(response.status_code, 200) # self.assertTrue('Successfully posted your blog' in str(response.content)) def test_blog_post_edit(self): user_login = self.client.login(username='<EMAIL>', password='mp') self.assertTrue(user_login) response = self.client.post( '/dashboard/add/', { 'title': 'nginx post', 'content': 'This is content', 'category': self.category.id, 'status': 'Published', 'tags': 'django', 'is_superuser': 'True', 'slug': 'nginx-post', 'slugs-MAX_NUM_FORMS': ['1000'], 'slugs-TOTAL_FORMS': ['3'], 'slugs-MIN_NUM_FORMS': ['0'], 'slugs-0-slug': ['testing-11223'], 'slugs-1-slug': [''], 'slugs-2-slug': [''], 'slugs-INITIAL_FORMS': ['0'], }) self.assertEqual(response.status_code, 200) # self.assertTrue('Successfully posted your blog' in str(response.content)) response = self.client.get(reverse("edit_blog", kwargs={"blog_slug": self.post.slug})) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'dashboard/blog/new_blog_add.html') response = self.client.post( reverse('edit_category', kwargs={"category_slug": self.category.slug}), { 'title': 'nginx-post', 'content': 'This is content', 'category': self.category.id, 'status': 'Published', 'tags': 'django', 'is_superuser': 'True', 'slug': 'nginx-post', 'slugs-MAX_NUM_FORMS': ['1000'], 'slugs-TOTAL_FORMS': ['3'], 'slugs-MIN_NUM_FORMS': ['0'], 'slugs-0-slug': ['nginx-post-1'], 'slugs-1-slug': [''], 'slugs-2-slug': [''], 'slugs-INITIAL_FORMS': ['0'], }) self.assertEqual(response.status_code, 200) # self.assertTrue('Successfully updated your blog post' in str(response.content)) response = self.client.post( reverse("edit_blog", kwargs={"blog_slug": self.post.slug}), { 'title': 'nginx-post', 'content': '', 'category': self.category.id, 'status': 'Published', 'tags': 'django', 'is_superuser': 'True', 'slug': 'nginx-post-1' }) self.assertEqual(response.status_code, 200) self.assertFalse('Successfully updated your blog post' in str(response.content)) response = self.client.post(reverse("edit_blog", kwargs={"blog_slug": self.post.slug}), {'content': '', 'title': ''}) self.assertEqual(response.status_code, 200) self.assertFalse('Successfully updated your blog post' in str(response.content)) response = self.client.post( reverse("edit_blog", kwargs={"blog_slug": self.post.slug}), { 'title': 'nginx-post', 'content': 'This is content', 'category': self.category.id, 'status': 'Published', 'tags': 'django', 'is_superuser': 'True', 'slug': 'nginx-post-1', 'slugs-MAX_NUM_FORMS': ['1000'], 'slugs-TOTAL_FORMS': ['4'], 'slugs-MIN_NUM_FORMS': ['0'], 'slugs-0-slug': ['python-introduction-1'], 'slugs-1-slug': [''], 'slugs-2-slug': [''], 'slugs-3-slug': [''], 'slugs-0-id': ['2'], 'slugs-INITIAL_FORMS': ['1'], 'slugs-0-is_active': ['on'], 'slugs-1-id': [''], 'slugs-2-id': [''], 'slugs-3-id': [''], }) self.assertEqual(response.status_code,
service (returns an integer) Required: name -- name of layer from which to grab ID Optional: grp_lyr -- default is false, does not return layer ID for group layers. Set to true to search for group layers too. """ all_layers = self.layers for layer in all_layers: if fnmatch.fnmatch(layer[NAME], name): if SUB_LAYER_IDS in layer: if grp_lyr and layer[SUB_LAYER_IDS] != None: return layer[ID] elif not grp_lyr and not layer[SUB_LAYER_IDS]: return layer[ID] return layer[ID] for tab in self.tables: if fnmatch.fnmatch(tab.get(NAME), name): return tab.get(ID) print('No Layer found matching "{0}"'.format(name)) return None def get_layer_url(self, name, grp_lyr=False): """returns the fully qualified path to a layer url by pattern match on name, will return the first match. Required: name -- name of layer from which to grab ID Optional: grp_lyr -- default is false, does not return layer ID for group layers. Set to true to search for group layers too. """ return '/'.join([self.url, str(self.getLayerIdByName(name,grp_lyr))]) def list_layers(self): """Method to return a list of layer names in a MapService""" return [l.name for l in self.layers] def list_tables(self): """Method to return a list of layer names in a MapService""" return [t.name for t in self.tables] def getNameFromId(self, lyrID): """method to get layer name from ID Required: lyrID -- id of layer for which to get name """ return [l.name for l in self.layers if l.id == lyrID][0] def export(self, out_image, imageSR=None, bbox=None, bboxSR=None, size=None, dpi=96, format='png', transparent=True, **kwargs): """exports a map image Required: out_image -- full path to output image Optional: imageSR -- spatial reference for exported image bbox -- bounding box as comma separated string bboxSR -- spatial reference for bounding box size -- comma separated string for the size of image in pixels. It is advised not to use this parameter and let this method generate it automatically dpi -- output resolution, default is 96 format -- image format, default is png8 transparent -- option to support transparency in exported image, default is True kwargs -- any additional keyword arguments for export operation (must be supported by REST API) Keyword Arguments can be found here: http://resources.arcgis.com/en/help/arcgis-rest-api/index.html#/Export_Map/02r3000000v7000000/ """ query_url = self.url + '/export' # defaults if params not specified if bbox and not size: if isinstance(bbox, (list, tuple)): size = ','.join(map(str, [abs(int(bbox[0]) - int(bbox[2])), abs(int(bbox[1]) - int(bbox[3]))])) if isinstance(bbox, dict) or (isinstance(bbox, basestring) and bbox.startswith('{')): print('it is a geometry object') bbox = Geometry(bbox) if isinstance(bbox, Geometry): geom = bbox bbox = geom.envelope() bboxSR = geom.spatialReference envJson = geom.envelopeAsJSON() size = ','.join(map(str, [abs(envJson.get(XMAX) - envJson.get(XMIN)), abs(envJson.get(YMAX) - envJson.get(YMIN))])) print('set size from geometry object: {}'.format(size)) if not bbox: ie = self.initialExtent bbox = ','.join(map(str, [ie.xmin, ie.ymin, ie.xmax, ie.ymax])) if not size: size = ','.join(map(str, [abs(int(ie.xmin) - int(ie.xmax)), abs(int(ie.ymin) - int(ie.ymax))])) bboxSR = self.spatialReference if not imageSR: imageSR = self.spatialReference # initial params params = {FORMAT: format, F: IMAGE, IMAGE_SR: imageSR, BBOX_SR: bboxSR, BBOX: bbox, TRANSPARENT: transparent, DPI: dpi, SIZE: size } # add additional params from **kwargs for k,v in kwargs.iteritems(): if k not in params: params[k] = v # do post r = self.request(query_url, params, ret_json=False) # save image with open(out_image, 'wb') as f: f.write(r.content) return r def layer(self, name_or_id, **kwargs): """Method to return a layer object with advanced properties by name Required: name -- layer name (supports wildcard syntax*) or id (must be of type <int>) """ if isinstance(name_or_id, int): # reference by id directly return MapServiceLayer('/'.join([self.url, str(name_or_id)]), token=self.token) layer_path = self.get_layer_url(name_or_id, self.token, **kwargs) if layer_path: return MapServiceLayer(layer_path, token=self.token, **kwargs) else: print('Layer "{0}" not found!'.format(name_or_id)) def table(self, name_or_id): """Method to return a layer object with advanced properties by name Required: name -- table name (supports wildcard syntax*) or id (must be of type <int>) """ if isinstance(name_or_id, int): # reference by id directly return MapServiceTable('/'.join([self.url, str(name_or_id)]), token=self.token) layer_path = self.get_layer_url(name_or_id, self.token) if layer_path: return MapServiceTable(layer_path, token=self.token) else: print('Table "{0}" not found!'.format(name_or_id)) def cursor(self, layer_name, fields='*', where='1=1', records=None, add_params={}, exceed_limit=False): """Cusor object to handle queries to rest endpoints Required: layer_name -- name of layer in map service Optional: fields -- option to limit fields returned. All are returned by default where -- where clause for cursor records -- number of records to return (within bounds of max record count) token -- add_params -- option to add additional search parameters exceed_limit -- option to get all records in layer. This option may be time consuming because the ArcGIS REST API uses default maxRecordCount of 1000, so queries must be performed in chunks to get all records """ lyr = self.layer(layer_name) return lyr.cursor(fields, where, add_params, records, exceed_limit) def export_layer(self, layer_name, out_fc, fields='*', where='1=1', records=None, params={}, exceed_limit=False, sr=None): """Method to export a feature class from a service layer Required: layer_name -- name of map service layer to export to fc out_fc -- full path to output feature class Optional: where -- optional where clause params -- dictionary of parameters for query fields -- list of fields for fc. If none specified, all fields are returned. Supports fields in list [] or comma separated string "field1,field2,.." records -- number of records to return. Default is none, will return maxRecordCount exceed_limit -- option to get all records. If true, will recursively query REST endpoint until all records have been gathered. Default is False. sr -- output spatial refrence (WKID) """ lyr = self.layer(layer_name) lyr.layer_to_fc(out_fc, fields, where,records, params, exceed_limit, sr) def layer_to_kmz(self, layer_name, out_kmz='', flds='*', where='1=1', params={}): """Method to create kmz from query Required: layer_name -- name of map service layer to export to fc Optional: out_kmz -- output kmz file path, if none specified will be saved on Desktop flds -- list of fields for fc. If none specified, all fields are returned. Supports fields in list [] or comma separated string "field1,field2,.." where -- optional where clause params -- dictionary of parameters for query """ lyr = self.layer(layer_name) lyr.layer_to_kmz(flds, where, params, kmz=out_kmz) def clip(self, layer_name, poly, output, fields='*', out_sr='', where='', envelope=False): """Method for spatial Query, exports geometry that intersect polygon or envelope features. Required: layer_name -- name of map service layer to export to fc poly -- polygon (or other) features used for spatial query output -- full path to output feature class Optional: fields -- list of fields for fc. If none specified, all fields are returned. Supports fields in list [] or comma separated string "field1,field2,.." sr -- output spatial refrence (WKID) where -- optional where clause envelope -- if true, the polygon features bounding box will be used. This option can be used if the feature has many vertices or to check against the full extent of the feature class """ lyr = self.layer(layer_name) return lyr.clip(poly, output, fields, out_sr, where, envelope) def __iter__(self): for lyr in self.layers: yield lyr # Legacy support MapService.layer_to_fc = MapService.export_layer class FeatureService(MapService): """class to handle Feature Service Required: url -- image service url Optional (below params only required if security is enabled): usr -- username credentials for ArcGIS Server pw -- password credentials for ArcGIS Server token -- token to handle security (alternative to usr and pw) proxy -- option to use proxy page to handle security, need to provide full path to proxy url. """ @property def replicas(self): """returns a list of replica objects""" if self.syncEnabled: reps = self.request(self.url + '/replicas') return [namedTuple('Replica', r) for r in reps] else: return [] def layer(self, name_or_id): """Method to return a layer object with advanced properties by name Required: name -- layer name (supports wildcard syntax*) or layer id (int) """ if isinstance(name_or_id, int): # reference by id directly return FeatureLayer('/'.join([self.url, str(name_or_id)]), token=self.token) layer_path = self.get_layer_url(name_or_id) if layer_path: return FeatureLayer(layer_path, token=self.token) else: print('Layer "{0}" not found!'.format(name_or_id)) def layer_to_kmz(self, layer_name, out_kmz='', flds='*', where='1=1', params={}): """Method to create kmz from query Required: layer_name -- name of map service layer to export to fc Optional: out_kmz -- output kmz file path, if none specified will be saved on Desktop flds -- list of