text:
from itertools import chain, product
from collections import deque
from functools import wraps
from abc import ABC, abstractmethod, abstractproperty
import numpy as np
from spike_swarm_sim.neural_networks.utils.builder import SynapsesBuilder
from spike_swarm_sim.algorithms.interfaces import GET, SET, LEN, INIT
from spike_swarm_sim.utils import merge_dicts
from spike_swarm_sim.register import synapse_registry

def delay(func):
    @wraps(func)
    def wrapper(self, spikes, voltages, **kwargs):
        spikes = spikes.astype(bool)
        delayed_spikes = np.array([v.pop() for v in self.spike_buffer])
        any([v.appendleft(bool(s)) for s, v in zip(spikes, self.spike_buffer)])
        ret = func(self, delayed_spikes.copy(), voltages, **kwargs)
        return ret
    return wrapper

class Synapses(ABC):
    def __init__(self, dt):
        self.dt = dt
        #* Weighted adjacency matrix.
        self.weights = None
        #* Unweighted boolean adjacency matrix (w=0 != no connection)
        self.mask = None
        #* Mask of connection that can be optimized.
        self.trainable_mask = None
        #* Dict mapping the name of each synapse group to the indices in
        #* The adjacency matrix.
        self.connection_dict = {}
        #* List of connections that are from sensory inputs.
        self.sensory_connections = []
        #* List of connections that feed motor neurons.
        self.motor_connections = []
        #* List of hidden connections (neither sensory nor motor connections).
        self.hidden_connections = []
        #*
        self.recurrent_connections = []

    @abstractmethod
    def step(self, spikes, voltages):
        pass
    @abstractmethod
    def build(self, topology):
        pass
    @abstractmethod
    def reset(self):
        pass

    @GET("synapses:weights")
    def get_weights(self, conn_name, min_val=0., max_val=1., only_trainable=True):
        """
        Given a connection name the method returns the flattened array of synapse strengths in
        that connection. If only_trainable is active, only weights in train mode are returned.
        """
        #* Return scaled in [0,1]
        if conn_name == 'all':
            return (self.weights[self.trainable_mask].copy() - min_val) / (max_val - min_val)
        #* Special queries of synapses
        conn_name = {
            'sensory' : self.sensory_connections,
            'hidden' : self.hidden_connections,
            'motor' : self.motor_connections
        }.get(conn_name, [conn_name])
        conn_subdict = merge_dicts([self.connection_dict[k] for k in conn_name])
        weights_string = np.hstack([self.weights[post[0]:post[1], pre[0]:pre[1]].flatten().copy() \
                         for pre, post in zip(conn_subdict['pre'], conn_subdict['post'])])
        if only_trainable:
            mask = np.hstack([self.trainable_mask[post[0]:post[1], pre[0]:pre[1]].flatten().copy()\
                        for pre, post in zip(conn_subdict['pre'], conn_subdict['post'])])
            return (weights_string[mask].flatten() - min_val) / (max_val - min_val)
        else:
            return (weights_string.flatten() - min_val) / (max_val - min_val)

    @SET("synapses:weights")
    def set_weights(self, conn_name, data, min_val=0., max_val=1.,):
        """
        """
        #* rescale genotype segment to weight range
        data = min_val + data * (max_val - min_val)
        if conn_name == 'all':
            self.weights[self.trainable_mask] = data[:self.trainable_mask.sum()].copy()
            # self.weights = np.abs(self.weights)
        else:
            #* Special queries of synapses
            conn_name = {
                'sensory' : self.sensory_connections,
                'hidden' : self.hidden_connections,
                'motor' : self.motor_connections
            }.get(conn_name, [conn_name])
            conn_subdict = merge_dicts([self.connection_dict[k] for k in conn_name])
            # conn_subdict = self.connection_dict[conn_name]
            counter = 0
            for pre, post in zip(conn_subdict['pre'], conn_subdict['post']):
                mask = self.trainable_mask[post[0] : post[1], pre[0] : pre[1]].copy()
                subconn_len = mask.sum()
                self.weights[post[0]:post[1], pre[0]:pre[1]][mask] = data[counter:counter+subconn_len].copy()
                counter += subconn_len
            # self.weights = np.abs(self.weights)
            # import pdb; pdb.set_trace()

    @INIT('synapses:weights')
    def init_weights(self, conn_name, min_val=0., max_val=1., only_trainable=True):
        """
        """
        weights_len = self.len_weights(conn_name)
        random_weights = 0.5 + np.random.randn(weights_len)*0.25 #between 0 and 1 (denormalized in set)
        random_weights = np.clip(random_weights, a_min=0, a_max=1)
        self.set_weights(conn_name, random_weights, min_val=min_val, max_val=max_val)

    @LEN('synapses:weights')
    def len_weights(self, conn_name, only_trainable=True):
        """
        """
        return self.get_weights(conn_name, only_trainable=True).shape[0]

@synapse_registry(name='static_synapse')
class StaticSynapses(Synapses):
    def step(self, spikes, voltages):
        return self.weights.dot(spikes)

    def build(self, topology):
        np.random.seed(821)
        # Instantiate builder and guide it
        builder = SynapsesBuilder(topology)
        # build connection mask and weights skeleton (not initialized)
        self.weights = builder.build_connections()
        self.mask = self.weights.copy().astype(bool)
        # Build trainable mask, indicating whether the connection can be optimized or not.
        # Non trainable weights are initialized randomly.
        self.trainable_mask, self.weights = builder.build_trainable_mask(self.mask, self.weights)
        np.random.seed()
        self.connection_dict = builder.connection_dict
        self.sensory_connections = [syn_name for syn_name, syn in topology['synapses'].items()\
                                            if syn['pre'] in topology['stimuli'].keys()]
        motor_neurons = [mot_neuron for output in topology['outputs'].values() for mot_neuron in output['ensemble']]
        self.motor_connections = [syn_name for syn_name, syn in topology['synapses'].items()\
                                    if syn['post'] in motor_neurons]
        self.hidden_connections = [syn for syn in topology['synapses'].keys() \
                                       if syn not in self.sensory_connections + self.motor_connections]
        return builder.ensemble_pointers, {n : u['n'] for n, u in builder.overall_topology.items()}, builder.n_inputs

    def reset(self):
        pass

    #! Remove (after test)
    def initialize(self):
        self.weights[self.trainable_mask] = (np.random.random(size=np.sum(self.trainable_mask))) * 1

@synapse_registry(name='dynamic_synapse')
class DynamicSynapses(Synapses):
    def __init__(self, dt):
        super(DynamicSynapses, self).__init__(dt)
        # masks and matrices
        self.gaba_mask = None
        self.ampa_mask = None
        self.ndma_mask = None
        self.delays = None
        self.spike_buffer = None

        # synapse variables (initialized in reset)
        self.s_ampa, self.s_gaba, self.s_ndma = None, None, None
        self.x_ndma = None

        #* Synapse Parameters (default)
        #* Changed in build method
        self.ampa_gain = 0.6
        self.ampa_tau = 5.
        self.ampa_E = 0.0
        self.gaba_gain = 1.
        self.gaba_tau = 10
        self.gaba_E = -70.
        self.ndma_gain = 0.1
        self.ndma_tau_rise = 6
        self.ndma_tau_decay = 100
        self.ndma_Mg2 = 0.5
        self.ndma_E = 0.0

    @delay
    def step(self, spikes, voltages):
        Iampa = self.step_ampa(spikes, voltages)
        Igaba = self.step_gaba(spikes, voltages)
        Indma = self.step_nmda(spikes, voltages)
        I = Iampa + Igaba + Indma
        return I

    def step_ampa(self, spikes, voltages):
        self.s_ampa[spikes] = 1
        self.s_ampa[~spikes] += self.dt * (-self.s_ampa[~spikes]/self.ampa_tau)
        PSP = self.ampa_gain * (self.ampa_mask * self.weights).dot(self.s_ampa)# * (self.ampa_E - voltages)
        if self.ampa_E is not None: PSP *= (self.ampa_E - voltages)
        return PSP

    def step_gaba(self, spikes, voltages):
        self.s_gaba[spikes] = 1
        self.s_gaba[~spikes] += self.dt * (-self.s_gaba[~spikes]/self.gaba_tau)
        PSP = self.gaba_gain*(self.gaba_mask * self.weights).dot(self.s_gaba)#* (self.gaba_E - voltages)
        if self.gaba_E is not None: PSP *= (self.gaba_E - voltages)
        return PSP

    def step_nmda(self, spikes, voltages):
        self.x_ndma[spikes] = 1
        self.x_ndma[~spikes] += self.dt * (-self.x_ndma[~spikes] / self.ndma_tau_rise)
        self.s_ndma += self.dt * (.5*self.x_ndma*(1-self.s_ndma) - self.s_ndma/self.ndma_tau_decay)
        PSP = self.ndma_gain * (self.ndma_mask * self.weights).dot(self.s_ndma)\
                * ( 1 / (1 + self.ndma_Mg2 * np.exp(-0.062*voltages)/3.57))
        if self.ndma_E is not None: PSP *= (self.ndma_E - voltages)
        return PSP

    def build(self, topology):
        np.random.seed(3657)
        # Instantiate builder and guide it
        builder = SynapsesBuilder(topology)
        # build connection mask and weights skeleton (not initialized)
        self.weights = builder.build_connections()
        self.mask = self.weights.copy().astype(bool)

        # Build neurotransmitter masks of the synapses
        neurotransmitters = builder.build_neurotransmitters(self.mask.copy())
        self.ampa_mask = neurotransmitters['AMPA']
        self.gaba_mask = neurotransmitters['GABA']
        self.ndma_mask = neurotransmitters['NDMA']

        # Build trainable mask, indicating whether the connection can be optimized or not.
        # Non trainable weights are initialized randomly.
        self.trainable_mask, self.weights = builder.build_trainable_mask(self.mask, self.weights)

        # Set up delays (only axonal or neuron level)
        self.delays, self.spike_buffer = builder.build_delays(min_delay=1, max_delay=10)
        np.random.seed()
        self.connection_dict = builder.connection_dict
        if 'synapse_params' in topology.keys():
            synapse_params = topology['synapse_params']
            self.ampa_gain = synapse_params['AMPA']['gain']
            self.ampa_tau = synapse_params['AMPA']['tau']
            self.ampa_E = synapse_params['AMPA']['E']
            self.gaba_gain = synapse_params['GABA']['gain']
            self.gaba_tau = synapse_params['GABA']['tau']
            self.gaba_E = synapse_params['GABA']['E']
            self.ndma_gain = synapse_params['NDMA']['gain']
            self.ndma_tau_rise = synapse_params['NDMA']['tau_rise']
            self.ndma_tau_decay = synapse_params['NDMA']['tau_decay']
            self.ndma_Mg2 = synapse_params['NDMA']['Mg2']
            self.ndma_E = synapse_params['NDMA']['E']
            if self.gaba_E is None:
                self.gaba_gain *= -1
        return builder.ensemble_pointers, {n : u['n'] for n, u in builder.overall_topology.items()}, builder.n_inputs

    def initialize(self):
        # initialize normal connections
        self.weights[self.trainable_mask]=(np.random.random(\
                size=np.sum(self.trainable_mask))) * 1

    def reset(self):
        self.s_ampa = np.zeros(self.weights.shape[1])
        self.s_gaba = np.zeros(self.weights.shape[1])
        self.s_ndma = np.zeros(self.weights.shape[1])
        self.x_ndma = np.zeros(self.weights.shape[1])
        self.spike_buffer = [deque([False for _ in range(int(d))]) for d in self.delays]

    @GET('synapses:delays')
    def get_delays(self, neuron_name):
        return self.delays.copy()

    @SET('synapses:delays')
    def set_delays(self, neuron_name, data):
        self.delays = data.copy()

    @LEN('synapses:delays')
    def len_delays(self, neuron_name):
        return self.delays.shape[0]

    @INIT('synapses:delays')
    def init_delays(self, neuron_name, min_val=0., max_val=1.):
        self.delays = np.random.randint(min_val, max_val, size=self.delays.shape[0])

    def trainable_weights(self, shared=False):
        if not shared:
            return self.weights[self.trainable_mask&~self.shared_weights_mask]
        else:
            return np.array([v[-1] for v in self.shared_weights_ids])

    def normalize_weights(self):
        for i, w_row in enumerate(self.weights):
            self.weights[i] /= np.linalg.norm(w_row)

max_stars_repo_name: r-sendra/SpikeSwarmSim

max_issues_repo_name: r-sendra/SpikeSwarmSim

max_forks_repo_name: r-sendra/SpikeSwarmSim


text:
"""Script to convert HICO object indices to MS COCO 80 format"""

import enum
import json
from tqdm import tqdm
from copy import deepcopy
import numpy as np

fname = 'instances_train2015.json'

with open(fname, 'r') as f:
    a = json.load(f)

with open('coco80tohico80.json', 'r') as f:
    b = json.load(f)

coco = np.asarray([int(k) for k in b.keys()]) - 1
hico = np.asarray([v for v in b.values()])

order = np.argsort(coco)
convert = hico[order]

# Re-order object names
objects = a['objects'].copy()
objects = [objects[k] for k in convert]
a['objects'] = objects

order = np.argsort(hico)
convert = coco[order].tolist()

# Update correspondence table
corr = deepcopy(a['correspondence'])
for v in corr:
    v[1] = convert[v[1]]
a['correspondence'] = corr

annotation = a['annotation']
for v in tqdm(annotation):
    v['object'] = [convert[o] for o in v['object']]

with open('new_' + fname, 'w') as f:
    json.dump(a, f)

ext: py

max_stars_repo_name: henlein/upt

max_issues_repo_name: henlein/upt

max_forks_repo_name: henlein/upt

reason: import numpy


text:
# sweep_plotting.py
#
# This file is part of scqubits.
#
#    Copyright (c) 2019, Jens Koch and Peter Groszkowski
#    All rights reserved.
#
#    This source code is licensed under the BSD-style license found in the
#    LICENSE file in the root directory of this source tree.
############################################################################

import numpy as np

import scqubits.core.sweep_generators as sweep_gen
import scqubits.utils.plot_defaults as defaults
import scqubits.utils.plotting as plot

def bare_spectrum(sweep, subsys, which=-1, **kwargs):
    """
    Plots energy spectrum of bare system `subsys` for given ParameterSweep `sweep`.

    Parameters
    ----------
    sweep: ParameterSweep
    subsys: QuantumSystem
    which: int or list(int), optional
        default: -1, signals to plot all wavefunctions within the truncated Hilbert space;
        int>0: plot wavefunctions 0..int-1; list(int) plot specific wavefunctions
    **kwargs: dict
        standard plotting option (see separate documentation)

    Returns
    -------
    fig, axes
    """
    subsys_index = sweep.get_subsys_index(subsys)
    specdata = sweep.bare_specdata_list[subsys_index]
    if which is None:
        which = subsys.truncated_dim
    return specdata.plot_evals_vs_paramvals(which=which, **kwargs)

def dressed_spectrum(sweep, **kwargs):
    """
    Plots energy spectrum of dressed system

    Parameters
    ----------
    sweep: ParameterSweep
    **kwargs: dict
        standard plotting option (see separate documentation)

    Returns
    -------
    fig, axes
    """
    return sweep.dressed_specdata.plot_evals_vs_paramvals(subtract_ground=True,
                                                          **defaults.dressed_spectrum(sweep, **kwargs))

def difference_spectrum(sweep, initial_state_ind=0, **kwargs):
    """
    Plots a transition energy spectrum with reference to the given initial_state_ind, obtained by taking energy
    differences of the eigenenergy spectrum.

    Parameters
    ----------
    sweep: ParameterSweep
    initial_state_ind: int
    **kwargs: dict
        standard plotting option (see separate documentation)

    Returns
    -------
    Figure, Axes
    """
    return sweep_gen.generate_diffspec_sweep(sweep, initial_state_ind).plot_evals_vs_paramvals(**kwargs)

def n_photon_qubit_spectrum(sweep, photonnumber, initial_state_labels, **kwargs):
    """
    Plots the n-photon qubit transition spectrum.

    Parameters
    ----------
    sweep: ParameterSweep
    photonnumber: int
        number of photons used in the transition
    initial_state_labels: tuple(int1, int2, ...)
        bare state index of the initial state for the transitions
    **kwargs: dict
        standard plotting option (see separate documentation)

    Returns
    -------
    Figure, Axes
    """
    label_list, specdata = sweep_gen.generate_qubit_transitions_sweep(sweep, photonnumber, initial_state_labels)
    return specdata.plot_evals_vs_paramvals(label_list=label_list, **kwargs)

def bare_wavefunction(sweep, param_val, subsys, which=-1, phi_grid=None, **kwargs):
    """
    Plot bare wavefunctions for given parameter value and subsystem.

    Parameters
    ----------
    sweep: ParameterSweep
    param_val: float
        value of the external parameter
    subsys: QuantumSystem
    which: int or list(int), optional
        default: -1, signals to plot all wavefunctions; int>0: plot wavefunctions 0..int-1; list(int) plot specific
        wavefunctions
    phi_grid: Grid1d, optional
        used for setting a custom grid for phi; if None use self._default_grid
    **kwargs: dict
        standard plotting option (see separate documentation)

    Returns
    -------
    fig, axes
    """
    subsys_index = sweep.get_subsys_index(subsys)
    sweep.update_hilbertspace(param_val)
    param_index = np.searchsorted(sweep.param_vals, param_val)
    evals = sweep.bare_specdata_list[subsys_index].energy_table[param_index]
    evecs = sweep.bare_specdata_list[subsys_index].state_table[param_index]
    return subsys.plot_wavefunction(esys=(evals, evecs), which=which, mode='real', phi_grid=phi_grid, **kwargs)

def chi(datastore, **kwargs):
    """
    Plot dispersive shifts chi_j for a given pair of qubit and oscillator.

    Parameters
    ----------
    datastore: DataStore
        contains sweep data for the dispersive shift, stored as datastore.chi
    **kwargs: dict
        standard plotting option (see separate documentation)

    Returns
    -------
    Figure, Axes
    """
    ydata = datastore.chi
    xdata = datastore.param_vals
    state_count = ydata.shape[1]
    label_list = list(range(state_count))
    return plot.data_vs_paramvals(xdata, ydata, label_list=label_list, **defaults.chi(datastore.param_name, **kwargs))

def chi_01(datastore, param_index=0, **kwargs):
    """
    Plot the dispersive shift chi01 for a given pair of qubit and oscillator.

    Parameters
    ----------
    datastore: DataStore
    param_index: int, optional
        index of the external parameter to be used
    **kwargs: dict
        standard plotting option (see separate documentation)

    Returns
    -------
    Figure, Axes
    """
    ydata = datastore.chi
    xdata = datastore.param_vals
    yval = ydata[param_index]
    return plot.data_vs_paramvals(xdata, ydata, label_list=None, **defaults.chi01(datastore.param_name, yval, **kwargs))

def charge_matrixelem(datastore, qbt_index_subsys, initial_state_idx=0, **kwargs):
    """

    Parameters
    ----------
    datastore: DataStore
    qbt_index_subsys: tuple(int, QuantumSystem)
        index of the qubit system within the underlying HilbertSpace, and qubit object
    initial_state_idx: int
        index of initial state
    **kwargs: dict
        standard plotting option (see separate documentation)

    Returns
    -------
    Figure, Axes
    """
    (qbt_index, qbt_subsys) = qbt_index_subsys
    label_list = [(initial_state_idx, final_idx) for final_idx in range(qbt_subsys.truncated_dim)]
    return plot.matelem_vs_paramvals(datastore, select_elems=label_list, mode='abs',
                                     **defaults.charge_matrixelem(datastore.param_name, **kwargs))

max_issues_repo_name: PhilippAumann/scqubits

max_forks_repo_name: PhilippAumann/scqubits


text:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 16 16:06:05 2019

@author: rakshit
"""

'''
This script runs all K-models for each person per model type. The output from
the best model is saved as PrIdx_{}_TrIdx_{}_Lbr_{model_ID}. Each model_ID is
associated with a certain condition.
'''

import os
import torch
import pickle
import numpy as np
import scipy.io as scio
from DeepModels.args import parse_args
from DeepModels.opts import test
from DeepModels.models import *
from DeepModels.DataLoader import GIW_readSeq

'''
WARNING
This is a slow process - This script takes over 1 hour.
'''

if __name__=='__main__':
    args = parse_args()
    args.prec = torch.float64
    path2weights = '/home/rakshit/Documents/MATLAB/gaze-in-wild/ML/DeepModels/weights'
    f = open(os.path.join(os.path.join(os.getcwd(), 'DeepModels', 'Data'), 'Data.pkl'), 'rb')
    seq = pickle.load(f)[1]
    ID_info = np.stack(seq['id'], axis=0)

    PrList = [1, 2, 3, 6, 8, 9, 12, 16, 17, 22]
    ModelPresent = list(range(0, 9))
    ModelPresent = [x for x in ModelPresent if x not in [5, 6, 8]] # Remove these from analysis
    ModelID = [14, 24, 34, 44, 54, 64, 74, 84, 94]
    for PrIdx in PrList:
        print('Evaluating PrIdx: {}'.format(PrIdx))
        testObj = GIW_readSeq(seq, PrIdx)
        testloader = torch.utils.data.DataLoader(testObj,
                                             batch_size=1,
                                             num_workers=1,
                                             shuffle=False)
        for model_num in ModelPresent:
            print('eval model: {}'.format(model_num+1))
            model = eval('model_{}'.format(model_num+1))
            net = model().cuda().to(args.prec)
            best = 0

            for fold in range(0, args.folds):
                print('fold: {}'.format(fold))
                path2weight = os.path.join(path2weights, 'PrTest_{}_model_{}_fold_{}.pt'.format(int(PrIdx), int(model_num+1), fold))
                if os.path.exists(path2weight):
                    try:
                        net.load_state_dict(torch.load(path2weight)['net_params'])
                    except:
                        print('Dict mismatch. Training not complete yet.')
                        continue
                    _, perf_test, Y, id_trIdx = test(net, testloader, args, talk=True)

                    assert len(Y) == testObj.idx.shape[0], "Something went wrong"

                    if perf_test.getPerf(0, 'kappa') > best:
                        print('Updating best fold ...')
                        best = perf_test.getPerf(0, 'kappa')
                        for i, y in enumerate(Y):
                            TrIdx = id_trIdx[i, 1]
                            fsave = os.path.join(os.getcwd(),
                                                 'outputs_kfold',
                                                 'PrIdx_{}_TrIdx_{}_Lbr_{}_WinSize_0.mat'.format(PrIdx, int(TrIdx), ModelID[model_num]))
                            # Note the +1. This is important because all subsequent
                            # analysis assumes fixation:1. Pursuit:2.Saccade:3.
                            scio.savemat(fsave, {'Y': y.reshape(-1, 1) + 1,
                                          'PrIdx': PrIdx,
                                          'TrIdx': TrIdx,
                                          'classifierType': ModelID[model_num]})
                    else:
                        print('Best fold found. Ignoring fold: {}'.format(fold))
                else:
                    print('Weights for this model does not exist')

max_stars_repo_name: RSKothari/Gaze-in-Wild

max_issues_repo_name: RSKothari/Gaze-in-Wild

max_forks_repo_name: RSKothari/Gaze-in-Wild

reason: import numpy,import scipy


text:
#!/usr/bin/env python
import rospy
import numpy as np
from numpy import pi
from geometry_msgs.msg import Twist
from cortex_driver.srv import *

wheelbase = (21 * .5) * 0.0254  # meters
wheel_circum = (4*pi) * 0.0254  # meters
encoder_conv_factor = 627.2  # ticks per revolution
max_vel = 850  # ticks/sec

def send_motor_velocity(left_vel, right_vel):
    rospy.wait_for_service('motor_vel')
    try:
        mp_prox = rospy.ServiceProxy('motor_vel', MotorVel)
        mp_prox(left_vel, right_vel)
    except rospy.ServiceException as e:
        rospy.logwarn("motor_vel service call failed: {}".format(str(e)))

def handle_cmd_vel(data):
    rospy.loginfo_throttle(10, "Got message over cmd_vel: {}".format(str(data)))

    max_omega = ((2 * max_vel) / wheelbase) * (wheel_circum / encoder_conv_factor)
    max_vfwd = max_vel * (wheel_circum / encoder_conv_factor)

    rospy.loginfo_throttle(60, "max omega: {:.3f}, max vfwd: {:.3f}".format(max_omega, max_vfwd))

    omega = np.clip(data.angular.z, -max_omega, max_omega)
    v_fwd = np.clip(data.linear.x, -max_vfwd, max_vfwd)

    v_left = (v_fwd - omega * wheelbase / 2.0) * (encoder_conv_factor / wheel_circum)
    v_right = (v_fwd + omega * wheelbase / 2.0) * (encoder_conv_factor / wheel_circum)

    rospy.loginfo_throttle(10, "Sending {:.3f} and {:.3f} to motors...".format(v_left, v_right))

    send_motor_velocity(v_left, v_right)

def main():
    rospy.init_node('base_control')

    rospy.loginfo("Waiting for motor_vel service...")
    rospy.wait_for_service('motor_vel')

    rospy.loginfo("Listening on cmd_vel...")
    rospy.Subscriber("cmd_vel",  Twist, callback=handle_cmd_vel)

    rospy.spin()

if __name__ == '__main__':
    main()

max_stars_repo_name: stmobo/BallCollectorProject

max_issues_repo_name: stmobo/BallCollectorProject

max_forks_repo_name: stmobo/BallCollectorProject

reason: import numpy,from numpy


text:
import os
import tarfile
import urllib

import os

import os
os.chdir('/Users/xxx/PycharmProjects/handson-ml2/datasets')
cwd = os.getcwd()

#downloading dataset
DOWNLOAD_ROOT = "https://raw.githubusercontent.com/ageron/handson-ml2/master/"
HOUSING_PATH = os.path.join(cwd, "housing")
HOUSING_URL = DOWNLOAD_ROOT + "datasets/housing/housing.tgz"

def fetch_housing_data(housing_url=HOUSING_URL, housing_path=HOUSING_PATH):
    os.makedirs(housing_path, exist_ok=True)
    tgz_path = os.path.join(housing_path, "housing.tgz")
    urllib.request.urlretrieve(housing_url, tgz_path)
    housing_tgz = tarfile.open(tgz_path)
    housing_tgz.extractall(path=housing_path)
    housing_tgz.close()

import pandas as pd

def load_housing_data(housing_path=HOUSING_PATH):
    csv_path = os.path.join(housing_path, "housing.csv")
    return pd.read_csv(csv_path)

housing = load_housing_data()
housing.head()
#provides top five rows

housing.info()
#provides information of data

housing.describe()
#summary stats e.g mean and stuff

#histogram - bins (int or sequence or str, optional)
import matplotlib.pyplot as plt
housing.hist(bins=50, figsize=(20,15))
plt.show()

#create a test set
import numpy as np

#creates test set
def split_train_test(data, test_ratio):
    shuffled_indices = np.random.permutation(len(data))
    test_set_size = int(len(data) * test_ratio)
    test_indices = shuffled_indices[:test_set_size]
    train_indices = shuffled_indices[test_set_size:]
    return data.iloc[train_indices], data.iloc[test_indices]

train_set, test_set = split_train_test(housing, 0.2)
len(train_set)
len(test_set)

#To have a stable train/test split even after updating the dataset,
#a common solution is to use each instance’s identifier to decide
#whether or not it should go in the test set
#(assuming instances have a unique and immutable identifier).

from zlib import crc32

def test_set_check(identifier, test_ratio):
    return crc32(np.int64(identifier)) & 0xffffffff < test_ratio * 2**32

def split_train_test_by_id(data, test_ratio, id_column):
    ids = data[id_column]
    in_test_set = ids.apply(lambda id_: test_set_check(id_, test_ratio))
    return data.loc[~in_test_set], data.loc[in_test_set]

housing_with_id = housing.reset_index()   # adds an `index` column
train_set, test_set = split_train_test_by_id(housing_with_id, 0.2, "index")

#test set doesn't have id, so they uses houses longitudinal and latitude

housing_with_id["id"] = housing["longitude"] * 1000 + housing["latitude"]
train_set, test_set = split_train_test_by_id(housing_with_id, 0.2, "id")

#spliting dataset
# features -. set random generator seed + mulitiple datasets with an identical number of rows
from sklearn.model_selection import train_test_split

train_set, test_set = train_test_split(housing, test_size=0.2, random_state=42)

#checking if representative (create hist, creating continous attribute to a income catgeory
# five labels for each variable
housing["income_cat"] = pd.cut(housing["median_income"],
                               bins=[0., 1.5, 3.0, 4.5, 6., np.inf],
                               labels=[1, 2, 3, 4, 5])

housing["income_cat"].hist()

#stratified sampling based - reflect population
from sklearn.model_selection import StratifiedShuffleSplit

split = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42)
for train_index, test_index in split.split(housing, housing["income_cat"]):
    strat_train_set = housing.loc[train_index]
    strat_test_set = housing.loc[test_index]

#shows you that it has SS worked by looking like a variable

strat_test_set["income_cat"].value_counts() / len(strat_test_set)

#remove the income_cat attribute so the data is back to its original state:

for set_ in (strat_train_set, strat_test_set):
    set_.drop("income_cat", axis=1, inplace=True)

#put training set to aside
housing = strat_train_set.copy()

##Discover (if data is big you can do a exploration set)

#visulaising training set, alpha makes it more visible
#s = population and c = colour of median house prices
housing.plot(kind="scatter",x="longitude",y="latitude", alpha=0.1,
    s=housing["population"]/100,label="population",figsize=(10,7),
    c="median_house_value",cmap=plt.get_cmap("jet"),colorbar=True,
)
plt.legend()

#looking for correlations
#only measures linear relationships
corr_matrix = housing.corr()
corr_matrix["median_house_value"].sort_values(ascending=False)

#map correlations  by plotting every numerical attribute

from pandas.plotting import scatter_matrix
attributes = ["median_house_value","median_income","total_rooms","housing_median_age"]
scatter_matrix(housing[attributes],figsize=(12,8))

#zoom in on median income
#correlation strong (upward trend but plot reveals certain quirks and you don't want algorthim to repeat it

housing.plot(kind="scatter",x="median_income",y="median_house_value",alpha=0.1)

#checking out new attributes
housing["rooms_per_household"] = housing["total_rooms"]/housing["households"]
housing["bedrooms_per_room"] = housing["total_bedrooms"]/housing["total_rooms"]
housing["population_per_household"]=housing["population"]/housing["households"]

#correlation matrix

corr_matrix =housing.corr()
corr_matrix["median_house_value"].sort_values(ascending=False)

#preparing data _> make functions

#revet to clean training set -> making a copy of training set _>
# removing lavels as you don;t want to apply same transformations to the predictors
housing = strat_train_set.drop("median_house_value",axis=1)
housing_labels = strat_train_set["median_house_value"].copy()

#data cleaning
#choose option 1
housing.dropna(subset=["total_bedrooms"])

#missing values

from sklearn.impute import SimpleImputer
imputer = SimpleImputer(strategy="median")

#median can only be computed with numbers need to create a
#copy of the data without text attribute for ocean_proximity

housing_num = housing.drop("ocean_proximity",axis=1)

#
imputer.fit(housing_num)
#the imputer  computed a median of each attribute
# and stored the resukt in its stats intance variable
# safe to also add imputer on other variables

imputer.statistics_
housing_num.median().values

#replacing missing values with learned medians
x=imputer.transform(housing_num)

housing_tr = pd.DataFrame(x, columns=housing_num.columns,index=housing_num.index)

#text attributes
housing_cat = housing[["ocean_proximity"]]
housing_cat.head(10)

#Most Machine Learning algorithms prefer to work with numbers, so let’s
#convert these categories from text to numbers. For this,
#we can use Scikit-Learn’s OrdinalEncoder class:19

from sklearn.preprocessing import OrdinalEncoder
ordinal_encoder = OrdinalEncoder()
housing_cat_encoded = ordinal_encoder.fit_transform(housing_cat)
housing_cat_encoded[:10]

#get the names of categories
ordinal_encoder.categories_

#The new attributes
#are sometimes called dummy attributes.Scikit - Learn provides a OneHotEncoder
#class to convert categorical values into one-hot vectors:20

#we need dummy variables as the distcintion between 1, 2 are not the same conceptually for island, near bay...

from sklearn.preprocessing import OneHotEncoder
cat_encoder = OneHotEncoder()
housing_cat_1hot = cat_encoder.fit_transform(housing_cat)
housing_cat_1hot

#2d array to host the data
housing_cat_1hot.toarray()

#can find catergory names

cat_encoder.categories_

#custome transformers
from sklearn.base import BaseEstimator, TransformerMixin

rooms_ix, bedrooms_ix, population_ix, households_ix = 3, 4, 5, 6

class CombinedAttributesAdder(BaseEstimator, TransformerMixin):
    def __init__(self, add_bedrooms_per_room=True): # no *args or **kargs
        self.add_bedrooms_per_room = add_bedrooms_per_room
    def fit(self, X, y=None):
        return self  # nothing else to do
    def transform(self, X):
        rooms_per_household = X[:, rooms_ix] / X[:, households_ix]
        population_per_household = X[:, population_ix] / X[:, households_ix]
        if self.add_bedrooms_per_room:
            bedrooms_per_room = X[:, bedrooms_ix] / X[:, rooms_ix]
            return np.c_[X, rooms_per_household, population_per_household,
                         bedrooms_per_room]

        else:
            return np.c_[X, rooms_per_household, population_per_household]

attr_adder = CombinedAttributesAdder(add_bedrooms_per_room=False)
housing_extra_attribs = attr_adder.transform(housing.values)

#transforming pipelines making the values to scale

from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler

num_pipeline = Pipeline([
        ('imputer', SimpleImputer(strategy="median")),
        ('attribs_adder', CombinedAttributesAdder()),
        ('std_scaler', StandardScaler()),
    ])

housing_num_tr = num_pipeline.fit_transform(housing_num)

from sklearn.compose import ColumnTransformer

num_attribs = list(housing_num)
cat_attribs = ["ocean_proximity"]

full_pipeline = ColumnTransformer([
        ("num", num_pipeline, num_attribs),
        ("cat", OneHotEncoder(), cat_attribs),
    ])

housing_prepared = full_pipeline.fit_transform(housing)


text:
import numpy as np
from numba import njit, jit
# from mapping import generate_map, plot_setup

@jit(forceobj=True)
def is_connected_NR(x1, y1, x2, y2, ox, oy, rr):
    """
    Function that connects 2 nodes with no restrictions unless the edge is not
    intersecting with an obstacle.
    """

    a1 = np.array([x1, y1])
    a2 = np.array([x2, y2])
    b = a2 - a1
    n = b / np.linalg.norm(b)
    for i in range(len(ox)):
        p = [ox[i], oy[i]]
        d = np.linalg.norm(
            (a1 - p) - (np.dot(a1 - p, n))*n
        )
        if d < rr[i]:
            return False
    return True

@jit(forceobj=True)
def adjacency_mat(x_all, y_all, ox, oy, rr):
    """
    Function that creates the adjacency matrix from the edges and points
    with the no restriction method
    """
    n = len(x_all)
    A = np.zeros((n, n))
    road_map = []
    for i in range(n):
        temp = []
        for j in range(n):
            if i == j:
                A[i, j] = 1
            else:
                if A[j, i] != 0:
                    A[i, j] = A[j, i]
                    temp.append(j)
                else:
                    if is_connected_NR(x_all[i], y_all[i], x_all[j], y_all[j],
                                       ox, oy, rr):
                        A[i, j] = 1
                        temp.append(j)
        road_map.append(temp)
    A /= A.sum(axis=1, keepdims=True)   # make it row stochastic
    return A, road_map

if __name__=="__main__":
    # start = time.time()
    # Starting point
    sx = 0.0  # x-position
    sy = 0.0  # y-position

    # Goal point
    gx = 10.0  # x-position
    gy = 10.0  # y-position

    # number of obstacles
    obs_num = 4

    # number of sample points
    N = 20
    # Radial size of the robot
    bot_size = 0.2

    # Obstacles
    ox, oy, rr, x, y = generate_map(sx, sy, gx, gy, obs_num, N, bot_size)

    # Sample points
    plot_setup(sx, sy, gx, gy, ox, oy, rr, x, y)

    x_sample = x
    y_sample = y
    x.insert(0, sx)
    x.append(gx)
    y.insert(0, sy)
    y.append(gy)

    A = adjacency_mat(x, y, ox, oy, rr)
    edge = list(zip(np.nonzero(A)[0], np.nonzero(A)[1]))
    print(edge[0])
    # end = time.time()
    # print("Elapsed time: ", (end - start))

max_stars_repo_name: smallpondtom/DO-PRM

max_issues_repo_name: smallpondtom/DO-PRM

max_forks_repo_name: smallpondtom/DO-PRM

reason: import numpy,from numba


text:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""POS and NER Taggers.

Part of speech taggers (POS) classifies words into 17 syntactic category.
Named entity Recognition extractors (NER) Detect three types of entities: {Person, Location, Organization.}

"""

import numpy as np
from six.moves import range

from ..decorators import memoize
from ..load import load_embeddings, load_ner_model, load_pos_model, load_unified_pos_model

NER_ID_TAG = {0: u'O', 1: u'I-PER', 2: u'I-LOC', 3: u'I-ORG'}

POS_TAG_ID = {u'ADJ': 0, u'ADP': 1, u'ADV': 2, u'AUX': 3, u'CONJ': 4,
              u'DET': 5, u'INTJ': 6, u'NOUN': 7, u'NUM': 8, u'PART': 9,
              u'PRON': 10, u'PROPN': 11, u'PUNCT': 12, u'SCONJ': 13,
              u'SYM': 14, u'VERB': 15, u'X': 16}

POS_ID_TAG = {v:k for k,v in POS_TAG_ID.items()}

class TaggerBase(object):
  """Tagger base class that defines the interface. """
  PAD = u'<PAD>'
  START = u'<S>'
  END = u'</S>'
  UNK = u'<UNK>'

  def __init__(self, lang='en'):
    """
    Args:
      lang: language code to decide which chunker to use.
    """
    self.lang = lang
    self.predictor = self._load_network()
    self.ID_TAG = {}
    self.add_bias = True
    self.context = 2
    self.transfer = lambda _:_

  @staticmethod
  def ngrams(sequence, n, transfer=None):
    ngrams_ = []
    part1 = (n-1) * [TaggerBase.PAD] + [TaggerBase.START]
    if transfer is not None:
        part2 = [transfer(_) for _ in sequence]
    else:
        part2 = sequence
    part3 = [TaggerBase.END] + (n-1) * [TaggerBase.PAD]
    seq = part1 + part2 + part3
    for i in range(n, n+len(sequence)):
      yield seq[i-n: i+n+1]

  def _load_network(self):
    raise NotImplementedError()

  def annotate(self, sent):
    """Annotate a squence of words with entity tags.

    Args:
      sent: sequence of strings/words.
    """
    preds = []
    words = []
    for word, fv in self.sent2examples(sent):
      probs = self.predictor(fv)
      tags = probs.argsort()
      tag = self.ID_TAG[tags[-1]]

      words.append(word)
      preds.append(tag)

    # fix_chunks(preds)
    annotations = zip(words, preds)
    return annotations

  def sent2examples(self, sent):
    """ Convert ngrams into feature vectors."""

    # TODO(rmyeid): use expanders.
    words = [w if w in self.embeddings else TaggerBase.UNK for w in sent]
    ngrams = TaggerBase.ngrams(words, self.context, self.transfer)
    fvs = []
    for word, ngram in zip(sent, ngrams):
      fv = np.array([self.embeddings.get(w, self.embeddings.zero_vector()) for w in ngram]).flatten()
      if self.add_bias:
        fv = np.hstack((fv, np.array(1)))
      yield word, fv

class NEChunker(TaggerBase):
  """Named entity extractor."""

  def __init__(self, lang='en'):
    """
    Args:
      lang: language code to decide which chunker to use.
    """
    super(NEChunker, self).__init__(lang=lang)
    self.ID_TAG = NER_ID_TAG

  def _load_network(self):
    """ Building the predictor out of the model."""
    self.embeddings = load_embeddings(self.lang, type='cw', normalize=True)
    self.model = load_ner_model(lang=self.lang, version=2)
    first_layer, second_layer = self.model

    def predict_proba(input_):
      hidden = np.tanh(np.dot(first_layer, input_))
      hidden = np.hstack((hidden, np.ones((hidden.shape[0], 1))))
      output =  (second_layer *  hidden).sum(axis=1)
      output_ = 1.0/(1.0 + np.exp(-output))
      probs = output_/output_.sum()
      return probs
    return predict_proba

class POSTagger(TaggerBase):
  """Universal Part of Speech Tagger."""

  def __init__(self, lang='en'):
    """
    Args:
      lang: language code to decide which chunker to use.
    """
    super(POSTagger, self).__init__(lang=lang)
    self.ID_TAG = POS_ID_TAG
    self.add_bias = False

  def _load_network(self):
    """ Building the predictor out of the model."""
    self.embeddings = load_embeddings(self.lang, type='cw')
    self.model = load_pos_model(lang=self.lang, version=2)

    def predict_proba(input_):
      hidden = np.tanh(np.dot(input_, self.model["W1"]) + self.model["b1"])
      output =  np.dot(hidden, self.model["W2"]) + self.model["b2"]
      scores = np.exp(output)
      probs = scores/scores.sum()
      return probs
    return predict_proba

class TransferPOSTagger(TaggerBase):
  """ The Transfer, Universal Part of Speech Tagger."""

  # Transfer tagger handles special tokens differently,
  # It will get a zero vector for them.

  def __init__(self, lang='en'):
    """
    Args:
      lang: language code to decide which chunker to use.
    """
    super(TransferPOSTagger, self).__init__(lang=lang)
    self.ID_TAG = POS_ID_TAG
    self.add_bias = False
    self.transfer = lambda _:_.lower()

  def _load_network(self):
    """ Building the predictor out of the model."""
    self.model = load_unified_pos_model(lang=self.lang)
    self.embeddings = load_embeddings(self.lang, type='ue')  # 'ue' = unified embeddings

    def predict_proba(input_):
      hidden = np.tanh(np.dot(input_, self.model["W1"]) + self.model["b1"])
      output = np.dot(hidden, self.model["W2"]) + self.model["b2"]
      scores = np.exp(output)
      probs = scores/scores.sum()
      return probs
    return predict_proba

@memoize
def get_pos_tagger(lang='en'):
  """Return a POS tagger from the models cache."""
  return POSTagger(lang=lang)

@memoize
def get_transfer_pos_tagger(lang='en'):
  """Return a Transfer POS tagger from the models cache."""
  return TransferPOSTagger(lang=lang)

@memoize
def get_ner_tagger(lang='en'):
  """Return a NER tagger from the models cache."""
  return NEChunker(lang=lang)


text:
from typing import List

import numpy as np
from algorithms import DPAlgorithm
from distributions import Distribution
from metrics import Metric

def test(
    metric: Metric,
    algorithm: DPAlgorithm,
    distribution: Distribution,
    nb_samples: int,
    nb_trials: int,
    epsilon: float,
    delta: float,
    datafile: str = "data.csv",
) -> List[float]:
    """test an algorithm on a given distribution using metric

    Arguments:
    nb_samples: number of datapoints to sample from distribution
    nb_trials: number of times the pipeline should be run
    epsilon, delta: privacy parameters
    datafile: path to file in which the sampled data is saved

    Returns:
    List of size nb_trials"""
    result = []
    for _ in range(nb_trials):
        data = distribution.sample(nb_samples)
        np.savetxt(datafile, data, delimiter=",", fmt="%s")
        quantiles, alg_output = algorithm.fit(datafile, epsilon, delta)
        metric.fit(data, quantiles)
        result.append(metric.test(data, alg_output))

    return result

def test_multiple(
    metrics: List[Metric],
    algorithms: List[DPAlgorithm],
    distributions: List[Distribution],
    nb_samples: int,
    nb_trials: int,
    epsilon: float,
    delta: float,
    datafile: str = "data.csv",
) -> np.array:
    """test algorithms on given distributions using metrics

    Arguments:
    nb_samples: number of datapoints to sample from distribution
    nb_trials: number of times the pipeline should be run
    epsilon, delta: privacy parameters
    datafile: path to file in which the sampled data is saved

    Returns:
    Array of shape (len(metrics), len(algorithms), len(distributions), nb_trials)"""
    result = np.zeros((len(metrics), len(algorithms), len(distributions), nb_trials))
    for k, distrib in enumerate(distributions):
        for l in range(nb_trials):
            data = distrib.sample(nb_samples)
            np.savetxt(datafile, data, delimiter=",", fmt="%s")
            for j, algorithm in enumerate(algorithms):
                algorithm.box = (distrib.min, distrib.max)
                quantiles, alg_output = algorithm.fit(datafile, epsilon, delta)
                for i, metric in enumerate(metrics):
                    metric.fit(data, quantiles)
                    result[i, j, k, l] = metric.test(data, alg_output)

    return result

max_stars_repo_name: sarus-tech/private-statistics

max_issues_repo_name: sarus-tech/private-statistics

max_forks_repo_name: sarus-tech/private-statistics


text:
#coding=utf-8

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

class mcorr:
  def __init__(self, *args, **kwargs):

    self.df = None

    # default parameters
    cmap = "YlGnBu"
    vmin = 0
    vmax = 1
    fmt = '.2g'
    annot = True
    cbar = True
    self.verbose = 1

    if kwargs: # if we have keyword parameters
      if 'cmap' not in kwargs.keys():
        kwargs['cmap'] = cmap
      if 'vmin' not in kwargs.keys():
        kwargs['vmin'] = vmin
      if 'vmax' not in kwargs.keys():
        kwargs['vmax'] = vmax
      if 'fmt' not in kwargs.keys():
        kwargs['fmt'] = fmt
      if 'annot' not in kwargs.keys():
        kwargs['annot'] = annot
      if 'cbar' not in kwargs.keys():
        kwargs['cbar'] = cbar
      if 'verbose' in kwargs.keys():
        self.verbose = kwargs['verbose']
        del kwargs['verbose'] # delete to send the dict do sns.heatmap
    else: # if there is no keyword parameters we have to create kwargs dict
      kwargs = {}
      kwargs['cmap'] = cmap
      kwargs['vmin'] = vmin
      kwargs['vmax'] = vmax
      kwargs['fmt'] = fmt
      kwargs['annot'] = annot
      kwargs['cbar'] = cbar

    self.kwargs = kwargs

    if args and self.verbose:
      print 'Warning: positional arguments are ignored.'

  def show_matrix(self):
    try:
      plt.clf()
      sns.heatmap(self.df.corr(), **self.kwargs)
      plt.show()
    except:
      print 'Problem when ploting corr matrix. Check your data.'

  def writefig(self, filename):
    try:
      plt.clf()
      sns.heatmap(self.df.corr(), **self.kwargs)
      plt.savefig(filename)
    except:
      print 'Problem when writing corr matrix. Check your data.'

  def add_col(self, label, data):
    try:
      if data.size != self.df.ix[:,0].size:
        print 'Warning: adding column with different size.'
      self.df[label] = pd.Series(data, index=self.df.index)
    except:
      data = [(label, data)]
      self.df = pd.DataFrame.from_items(data)

max_stars_repo_name: attilalr/matcorr

max_issues_repo_name: attilalr/matcorr

max_forks_repo_name: attilalr/matcorr


text:
import logging; log = logging.getLogger(__name__)
from importlib import resources
import struct
import math
import sys
import gl
import numpy as np
from gl.Util import Matrix
from .SfaProgram import SfaProgram
from . import shaders

class TextureShader(SfaProgram):
    separable       = True
    vertex_shader   = (shaders, 'texturemap.vert')
    geometry_shader = (shaders, 'texturemap.geom')
    fragment_shader = (shaders, 'texturemap.frag')

class TextureRenderer(gl.Pipeline):
    """Subprogram for displaying texture coordinates."""
    MAX_VTXS = 65536
    vtxBufferFmt = "3f" # (x,y,useTexture)
    colorBufferFmt = "4f" # (r,g,b,a)

    def __init__(self, parent):
        self.parent   = parent
        self.shader   = TextureShader(self.parent.ctx)
        self.texture  = None
        self._frame   = 0

        super().__init__(parent.ctx,
            vertex_shader   = self.shader,
            geometry_shader = self.shader,
            fragment_shader = self.shader,
        )
        #self.programs['fragment_shader'].setUniforms(
        #    minAlpha      =  0.5,
        #)

        self._vtxSize   = struct.calcsize(self.vtxBufferFmt)
        self._colorSize = struct.calcsize(self.colorBufferFmt)
        self.bufVtxs   = self.ctx.Buffer(self._vtxSize * self.MAX_VTXS, True)
        self.bufColors = self.ctx.Buffer(self._colorSize * self.MAX_VTXS, True)
        self.reset()

    def reset(self):
        self._nVtxs = 0

        # the actual texture image
        col = (1, 1, 1, 0.5)
        self.addTri((0, 0), (0, 1), (1, 0), col, useTexture=True)
        self.addTri((0, 1), (1, 0), (1, 1), col, useTexture=True)

    def addTri(self, a, b, c, color=(1, 1, 1, 1), useTexture=False):
        self.addVtx(a, color, useTexture)
        self.addVtx(b, color, useTexture)
        self.addVtx(c, color, useTexture)

    def addVtx(self, pos, color=(1, 1, 1, 1), useTexture=False):
        tex = 1 if useTexture else 0
        vtxData = struct.pack(self.vtxBufferFmt, pos[0], pos[1], tex)
        colData = struct.pack(self.colorBufferFmt, *color)
        vtxOffs = self._nVtxs * self._vtxSize
        colOffs = self._nVtxs * self._colorSize
        self.bufVtxs  .write(vtxData, vtxOffs)
        self.bufColors.write(colData, colOffs)
        self._nVtxs += 1

    def run(self):
        if self.texture is None: return
        self.ctx.glDisable(self.ctx.GL_DEPTH_TEST)
        self.ctx.glDisable(self.ctx.GL_CULL_FACE)
        self.ctx.glEnable(self.ctx.GL_BLEND)
        self.ctx.glBlendFunc(self.ctx.GL_SRC_ALPHA,
            self.ctx.GL_ONE_MINUS_SRC_ALPHA)

        c = (math.sin(self._frame * 4) * 0.5) + 1
        self.programs['fragment_shader'].setUniforms(
            modColor = (1, 1, 1, c),
        )

        # nVtxs = # triangles since we use GL_TRIANGLES here,
        # so the division by 3 is done automatically
        with self:
            self.texture.bind()
            self._bindBuffers()
            self.shader.vao.render(self.ctx.GL_TRIANGLES,
                count=self._nVtxs)
        self._frame += 1

    def setMtxs(self, projection, modelView):
        with self.shader:
            self.shader.uniforms['matProjection'].value = projection

    def setTexture(self, tex):
        self.texture = tex

    def _bindBuffers(self):
        with self.shader as shader:
            # in ivec3 texCoord
            shader.attribs['texCoord'].bindBuffer(
                self.bufVtxs, self.ctx.GL_FLOAT, 3,
                stride=3 * gl.Util.SIZEOF_FLOAT,
                offset=0 * gl.Util.SIZEOF_FLOAT)

            # in vec4 vtxColor
            shader.attribs['color'].bindBuffer(
                self.bufColors, self.ctx.GL_FLOAT, 4,
                stride=4 * gl.Util.SIZEOF_FLOAT,
                offset=0 * gl.Util.SIZEOF_FLOAT)


text:
import numpy

arr = map(int, input().strip().split(' '))
d2_arr = numpy.array(list(arr))
d2_arr.shape = (3, 3)
print(d2_arr)

max_stars_repo_name: avtomato/HackerRank

max_issues_repo_name: avtomato/HackerRank

max_forks_repo_name: avtomato/HackerRank


text:
#!/usr/bin/env python
# coding: utf-8

# In[ ]:

import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

from subprocess import check_output
print(check_output(["ls", "../../../input/aljarah_xAPI-Edu-Data"]).decode("utf8"))

# In[ ]:

import seaborn as sns
import matplotlib.pyplot as plt
from sklearn import tree
df = pd.read_csv("../../../input/aljarah_xAPI-Edu-Data/xAPI-Edu-Data.csv")

# In[ ]:

df.shape

# In[ ]:

df.describe()

# In[ ]:

df.tail(4).T

# In[ ]:

df.info()

# In[ ]:

df.rename(index=str, columns={'gender':'Gender', 'NationalITy':'Nationality','raisedhands':'RaisedHands', 'VisITedResources':'VisitedResources'},inplace=True)

# In[ ]:

from sklearn.cross_validation import train_test_split

# Generate the training set.  Set random_state to be able to replicate results.
train = df.sample(frac=0.7, random_state=1)
# Select anything not in the training set and put it in the testing set.
test = df.loc[~df.index.isin(train.index)]

# In[ ]:

print(train.shape)
print(test.shape)

# In[ ]:

from sklearn.cross_validation import train_test_split

# Generate the training set.  Set random_state to be able to replicate results.
train = df.sample(frac=0.7, random_state=1)
# Select anything not in the training set and put it in the testing set.
test = df.loc[~df.index.isin(train.index)]

# In[ ]:

train['Class'].value_counts()

# In[ ]:

train['Nationality'].value_counts()

# In[ ]:

pd.crosstab(train['Class'], train['Topic'])

# In[ ]:

pd.crosstab(train['Class'],train['Gender'])

# In[ ]:

train['Gender'][train['Gender'] == "F"] = 0
train['Gender'][train['Gender'] == "M"] = 1
train['Gender'] = train['Gender'].astype(int)

train["Class"][train["Class"] == "L"] = 0
train["Class"][train["Class"] == "M"] = 1
train["Class"][train["Class"] == "H"] = 2
train['Class'] = train['Class'].astype(int)

# In[ ]:

ax = sns.boxplot(x='Class', y='Discussion', data=train)
ax = sns.swarmplot(x='Class', y = 'Discussion', data=train, color='.25')
print()

# In[ ]:

sns.factorplot('ParentschoolSatisfaction','Class',data=train)

# In[ ]:

train['ParentschoolSatisfaction'][train['ParentschoolSatisfaction'] == "Good"] = 0
train['ParentschoolSatisfaction'][train['ParentschoolSatisfaction'] == "Bad"] = 1
train['ParentschoolSatisfaction'] = train['ParentschoolSatisfaction'].astype(int)

# In[ ]:

sns.factorplot('Relation','Class',data=train)

# In[ ]:

train['Relation'][train['Relation'] == "Father"] = 0
train['Relation'][train['Relation'] == "Mum"] = 1
train['Relation'] = train['Relation'].astype(int)

# In[ ]:

sns.swarmplot(x='Class', y='AnnouncementsView', data=train)

# In[ ]:

Raised_hand = sns.swarmplot(x="Class", y="RaisedHands", data=train)

# In[ ]:

ax = sns.boxplot(x='Class', y='VisitedResources', data=train)
ax = sns.swarmplot(x='Class', y = 'VisitedResources', data=train, color='.25')
print()

# In[ ]:

sns.factorplot('StudentAbsenceDays', 'Class', data=train)

# In[ ]:

train['StudentAbsenceDays'][train['StudentAbsenceDays'] == "Under-7"] = 0
train['StudentAbsenceDays'][train['StudentAbsenceDays'] == "Above-7"] = 1
train['StudentAbsenceDays'] = train['StudentAbsenceDays'].astype(int)

# In[ ]:

from sklearn import tree
target = train['Class'].values
features_one = train[["Gender", "ParentschoolSatisfaction", "Relation", "AnnouncementsView", "RaisedHands", "VisitedResources", "StudentAbsenceDays"]].values
my_tree_one = tree.DecisionTreeClassifier()
my_tree_one = my_tree_one.fit(features_one, target)

print(my_tree_one.feature_importances_)
print(my_tree_one.score(features_one, target))

# In[ ]:

# add one more attrinute into the features
features_two = train[["Gender", "Discussion", "ParentschoolSatisfaction", "Relation", "AnnouncementsView", "RaisedHands", "VisitedResources", "StudentAbsenceDays"]].values

#Control overfitting by setting "max_depth" to 10 and "min_samples_split" to 5 : my_tree_two
my_tree_two = tree.DecisionTreeClassifier(max_depth = 10, min_samples_split = 5, random_state = 1)
my_tree_two = my_tree_two.fit(features_two, target)
print(my_tree_two.feature_importances_)
print(my_tree_two.score(features_two, target))

# In[ ]:

# Import the `RandomForestClassifier`
from sklearn.ensemble import RandomForestClassifier

# Building and fitting my forest
forest = RandomForestClassifier(max_depth = 10, min_samples_split=5, n_estimators = 100, random_state = 1)
my_forest = forest.fit(features_two, target)
print(my_forest.feature_importances_)

# Print the score of the fitted random forest
print(my_forest.score(features_two, target))

# In[ ]:

#Start testing. Convert the object attribute in the testing set to integer.
test['Gender'][test['Gender'] == "F"] = 0
test['Gender'][test['Gender'] == "M"] = 1
test['Gender'] = test['Gender'].astype(int)

test["Class"][test["Class"] == "L"] = 0
test["Class"][test["Class"] == "M"] = 1
test["Class"][test["Class"] == "H"] = 2
test['Class'] = test['Class'].astype(int)

test['ParentschoolSatisfaction'][test['ParentschoolSatisfaction'] == "Good"] = 0
test['ParentschoolSatisfaction'][test['ParentschoolSatisfaction'] == "Bad"] = 1
test['ParentschoolSatisfaction'] = test['ParentschoolSatisfaction'].astype(int)

test['Relation'][test['Relation'] == "Father"] = 0
test['Relation'][test['Relation'] == "Mum"] = 1
test['Relation'] = test['Relation'].astype(int)

test['StudentAbsenceDays'][test['StudentAbsenceDays'] == "Under-7"] = 0
test['StudentAbsenceDays'][test['StudentAbsenceDays'] == "Above-7"] = 1
test['StudentAbsenceDays'] = test['StudentAbsenceDays'].astype(int)

# In[ ]:

#Create testing features.
test_features= test[["Gender", "Discussion", "ParentschoolSatisfaction", "Relation", "AnnouncementsView", "RaisedHands", "VisitedResources", "StudentAbsenceDays"]].values
print(test_features)

# In[ ]:

# Makeing prediction for the test set, and print the prediction.
my_prediction = my_forest.predict(test_features)
print(my_prediction)

# In[ ]:

my_solution = pd.DataFrame(my_prediction, columns = ["Class"])
print(my_solution)

# In[ ]:

my_solution.shape

# In[ ]:

my_solution.to_csv("my_solution_two.csv")

# In[ ]:

from sklearn.metrics import confusion_matrix
results = confusion_matrix(my_solution, test["Class"])
print(results)

# In[ ]:

from sklearn.metrics import classification_report
df_cm = pd.DataFrame(results, index = [i for i in "LMH"], columns = [i for i in "LMH"])
plt.figure(figsize = (10,7))
print()

# In[ ]:

from sklearn.metrics import classification_report
y_true = test["Class"]
y_pred = my_prediction
target_names = ['class 0(L)', 'class 1(M)', 'class 2(H)']
print(classification_report(y_true, y_pred, target_names=target_names))

max_stars_repo_name: Chenguang-Zhu/relancer

max_issues_repo_name: Chenguang-Zhu/relancer

max_forks_repo_name: Chenguang-Zhu/relancer


text:
import cv2
import numpy as np
from PIL import Image
from numpy import *
import glob

gt_img_dir = '/path/to/datasets/TextSegmentation/ICDAR2013_KAIST/GT_color/'
save_path = 'pat/to/save'

count_wrong_size = 0
img_files = sorted(glob.glob(gt_img_dir+'*.png'))

for img_idx in range(0,len(img_files)):

	img_name = img_files[img_idx].split('/')[-1].split('.')[0]
    print("image is {}".format(img_name))

    #image = Image.open(img)
    image = Image.open(img_files[img_idx])

    img_size = image.size

    if img_size[0] != 250 and img_size[1] != 250:
    	count_wrong_size +=1
    	image_resized = image.resize((256,256), Image.ANTIALIAS)
    	image_resized.save(save_path+img_name+'.png')

print(count_wrong_size)


text:
#!/usr/bin/env python3
# https://www.ev3dev.org/docs/tutorials/sending-and-receiving-messages-with-mqtt/

import datetime
import json
import numpy as np

import paho.mqtt.client as mqtt

import NumpyEncoder

# This is the Publisher

data = np.random.random_sample(1)
message = {"Message": "Hello World!",
           "datetime": datetime.datetime.now().isoformat(),
           "data":data}

client = mqtt.Client()
client.connect("localhost", 1883, 60)
# QOS
# At most once(0)
# At least once(1)
# Exactly once(2).
message_json = json.dumps(message, cls=NumpyEncoder.NumpyEncoder)

client.publish("topic/test",
               payload=json.dumps(message, cls=NumpyEncoder.NumpyEncoder),
               qos=1)
client.disconnect()

max_stars_repo_name: balarsen/ArduinoSenorsToDB

max_issues_repo_name: balarsen/ArduinoSenorsToDB

max_forks_repo_name: balarsen/ArduinoSenorsToDB


text:
import tensorflow as tf
from model.create_model import get_model
from datetime import datetime
import pandas as pd
import numpy as np
import sys
import pickle
import math

from model.data_preprocessor import generate_lstm_data
from helpers.settings import *
from model.config import HISTORY_SIZE, ROW_LENGTH

EVALUATION_INTERVAL = 200
EPOCHS = 2
BATCH_SIZE = 8
BUFFER_SIZE = 500
dataset_file = './data/model_input2.csv'
stations_file = './data/stations.csv'
NUM_OF_HOURS_PER_FILE = 1000

if __name__ == '__main__':

    stations = pd.read_csv(stations_file, usecols=STATIONS_COLUMNS, sep=';')
    num_of_hours = 0
    temp_dataset_x = np.array(())
    temp_dataset_y = np.array(())
    num_of_stations = len(stations)
    num_of_active_stat = 0
    for s_id, station in stations.iterrows():
        x, y = generate_lstm_data(
            dataset_file,
            history_size=HISTORY_SIZE,
            index_col='timestamp',
            norm_cols=NORM_COLS,
            scale_cols=SCALE_COLS,
            adjust_cols=ADJUST_COLUMNS,
            filter_cols={
                'lat': [
                    station['lat']
                ],
                'lng': [
                    station['lng']
                ]
            },
            cat_cols=None,
            extra_columns=EXTRA_COLS
        )
        if np.sum(y) == 0:
            continue
        num_of_active_stat += 1
        temp_dataset_x = np.append(temp_dataset_x, x)
        temp_dataset_y = np.append(temp_dataset_y, y)
        print(np.sum(y))
        print(np.sum(temp_dataset_y))
        for i in range(len(temp_dataset_y)):
            if temp_dataset_y[i] > 0:
                print(temp_dataset_y[i])
        # every sample has the same size, only thing we need to know is how big is it
        num_of_hours = x.shape[0]
        # Display progess bar
        sys.stdout.write('\r')
        sys.stdout.write("[%-20s] %d%% (%d/%d)" % (
            '=' * int(20 * (s_id + 1) / num_of_stations), int(100 * (s_id + 1) / num_of_stations), (s_id + 1),
            num_of_stations))
        sys.stdout.flush()

    temp_dataset_x = temp_dataset_x.reshape((-1, HISTORY_SIZE, ROW_LENGTH))
    print(temp_dataset_x.shape)
    print(temp_dataset_y.shape)
    print(np.sum(temp_dataset_y))
    dataset_x = []
    dataset_y = []
    max_i = 0
    for i in range(num_of_hours):
        for s_id in range(num_of_active_stat):
            dataset_x.append(temp_dataset_x[i + s_id])
            dataset_y.append(temp_dataset_y[i + s_id])
        print(np.sum(dataset_y), 'dataset y')
        print(np.sum(temp_dataset_y), 'temp dataset y')

        # Display progess bar
        sys.stdout.write('\r')
        sys.stdout.write("[%-20s] %d%% (%d/%d)" % (
            '=' * int(20 * (i + 1) / num_of_hours), int(100 * (i + 1) / num_of_hours), i + 1, num_of_hours))
        sys.stdout.flush()

        max_i = i
        if i % NUM_OF_HOURS_PER_FILE == 0 and i != 0:
            print(np.sum(dataset_y), 'dataset y')
            with open(f'model/train_data/train_x_{str(math.ceil(i / NUM_OF_HOURS_PER_FILE))}.pkl', 'wb') as filehandler:
                # store the data as binary data stream
                pickle.dump(dataset_x, filehandler)
                dataset_x = []

            with open(f'model/train_data/train_y_{str(math.ceil(i / NUM_OF_HOURS_PER_FILE))}.pkl', 'wb') as filehandler:
                # store the data as binary data stream
                pickle.dump(dataset_y, filehandler)
                dataset_y = []

    # if there is anything left save it as a last file
    if len(dataset_x) > 0:
        with open(f'model/train_data/train_x_{str(math.ceil(max_i / NUM_OF_HOURS_PER_FILE))}.pkl', 'wb') as filehandler:
            # store the data as binary data stream
            pickle.dump(dataset_x, filehandler)
            dataset_x = []

        with open(f'model/train_data/train_y_{str(math.ceil(max_i / NUM_OF_HOURS_PER_FILE))}.pkl', 'wb') as filehandler:
            # store the data as binary data stream
            pickle.dump(dataset_y, filehandler)
            dataset_y = []

    print('done')

max_stars_repo_name: burnpiro/wod-usage-predictor

max_issues_repo_name: burnpiro/wod-usage-predictor

max_forks_repo_name: burnpiro/wod-usage-predictor


text:
import pytest
import os, tempfile, shutil
import numpy as np

from urllib.request import urlopen

from tridesclous import download_dataset
#~ from tridesclous import DataIO
from tridesclous.datasource import InMemoryDataSource, data_source_classes

#~ print(data_source_classes)
#~ exit()

from neo.test.rawiotest.tools import (can_use_network, make_all_directories,
                                   download_test_file, create_local_temp_dir)

def test_InMemoryDataSource():

    nparrays = [np.random.randn(10000, 2) for i in range(5) ]
    datasource = InMemoryDataSource(nparrays=nparrays, sample_rate=5000.)
    assert datasource.total_channel == 2
    assert datasource.sample_rate == 5000.
    assert datasource.nb_segment==5
    assert datasource.get_segment_shape(0) == (10000, 2)
    data = datasource.get_signals_chunk(seg_num=0)
    assert data.shape==datasource.get_segment_shape(0)

def test_RawDataSource():
    from tridesclous.datasource import RawDataSource

    localdir, filenames, params = download_dataset(name='olfactory_bulb')
    datasource = RawDataSource(filenames=filenames, **params)

    assert datasource.total_channel == 16
    assert datasource.sample_rate == 10000.
    assert datasource.nb_segment==3
    assert datasource.get_segment_shape(0) == (150000, 16)
    data = datasource.get_signals_chunk(seg_num=0)
    assert data.shape==datasource.get_segment_shape(0)

def test_NeoRawIOAggregator():

    url_for_tests = "https://web.gin.g-node.org/NeuralEnsemble/ephy_testing_data/raw/master/"
    distantfile = url_for_tests+'blackrock/FileSpec2.3001.ns5'

    localfile = 'FileSpec2.3001.ns5'

    if not os.path.exists(localfile):
        dist = urlopen(distantfile)
        with open(localfile, 'wb') as f:
            f.write(dist.read())

    from tridesclous import BlackrockDataSource

    datasource = BlackrockDataSource(filenames=[localfile, localfile])
    print(datasource.total_channel)
    print(datasource.nb_segment)
    print(datasource.get_segment_shape(0), datasource.get_segment_shape(1))
    assert datasource.get_segment_shape(0)==datasource.get_segment_shape(1)
    print(datasource.get_channel_names())
    data = datasource.get_signals_chunk(seg_num=0)
    assert data.shape==datasource.get_segment_shape(0)

if __name__=='__main__':
    test_InMemoryDataSource()
    test_RawDataSource()
    test_NeoRawIOAggregator()

max_stars_repo_name: remi-pr/tridesclous

max_issues_repo_name: remi-pr/tridesclous

max_forks_repo_name: remi-pr/tridesclous


text:
from pyspark import SparkConf,SparkContext
import sys
import numpy as np

#datasets path on shared group directory on Ukko2. Uncomment the one which you would like t$
#dataset = "/proj/group/distributed-data-infra/data-1-sample.txt"
#dataset = "/proj/group/distributed-data-infra/data-1.txt"
#dataset = "/proj/group/distributed-data-infra/data-2-sample.txt"
#dataset = "/proj/group/distributed-data-infra/data-2.txt"

dataset = "data/data2.txt"
output_file = "./matrix_output.txt"

conf = (SparkConf()
		.setAppName("Hamroun")           #Echange app name to your username
#		.setMaster("spark://128.214.48.227:7077")
#		.set("spark.cores.max", "10")  ##dont be too greedy ;)
#		.set("spark.rdd.compress", "true")
#		.set("spark.broadcast.compress", "true")

	   )
sc = SparkContext(conf=conf)

#Data Loading
raw_matrix_file = sc.textFile(dataset)
#Compute A
A = raw_matrix_file.map(lambda row: row.split()).map(lambda row: [float(element) for element in
row])
#Compute AT_A
AT_A = A.map(lambda row: np.outer(row, row)).reduce(lambda x,y : np.array(x) + np.array(y))

#Compte A * (AT_A)
A_AT_A = A.map(lambda row: np.dot(row,AT_A ))

#Partitionning and saving
A_AT_A.partitionBy(10)
A_AT_A.saveAsTextFile(output_file)

max_stars_repo_name: HappyBearDay/Spark

max_issues_repo_name: HappyBearDay/Spark

max_forks_repo_name: HappyBearDay/Spark


text:
import cv2
import numpy as np

img_rgb = cv2.imread('19.jpg')
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = cv2.imread('20.jpg', 0)
h, w = template.shape

res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)

loc = np.where(res >= 0.8)
for pt in zip(*loc[::-1]):
    cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)

cv2.imshow('img', img_rgb)
cv2.waitKey(0)

max_stars_repo_name: swpucwf/Deeplearning

max_issues_repo_name: swpucwf/deeplearning

max_forks_repo_name: swpucwf/deeplearning


text:
def selection_9():

    # Library import
    import numpy
    import matplotlib
    import matplotlib.pyplot   as plt
    import matplotlib.gridspec as gridspec

    # Library version
    matplotlib_version = matplotlib.__version__
    numpy_version      = numpy.__version__

    # Histo binning
    xBinning = numpy.linspace(-15.0,15.0,101,endpoint=True)

    # Creating data sequence: middle of each bin
    xData = numpy.array([-14.85,-14.55,-14.25,-13.95,-13.65,-13.35,-13.05,-12.75,-12.45,-12.15,-11.85,-11.55,-11.25,-10.95,-10.65,-10.35,-10.05,-9.75,-9.45,-9.15,-8.85,-8.55,-8.25,-7.95,-7.65,-7.35,-7.05,-6.75,-6.45,-6.15,-5.85,-5.55,-5.25,-4.95,-4.65,-4.35,-4.05,-3.75,-3.45,-3.15,-2.85,-2.55,-2.25,-1.95,-1.65,-1.35,-1.05,-0.75,-0.45,-0.15,0.15,0.45,0.75,1.05,1.35,1.65,1.95,2.25,2.55,2.85,3.15,3.45,3.75,4.05,4.35,4.65,4.95,5.25,5.55,5.85,6.15,6.45,6.75,7.05,7.35,7.65,7.95,8.25,8.55,8.85,9.15,9.45,9.75,10.05,10.35,10.65,10.95,11.25,11.55,11.85,12.15,12.45,12.75,13.05,13.35,13.65,13.95,14.25,14.55,14.85])

    # Creating weights for histo: y10_sdETA_0
    y10_sdETA_0_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0153528159281,0.16888094521,0.66017099491,1.62739800838,2.74815348114,4.02243681317,6.2178903009,8.55151766198,12.7888937781,17.4715039862,23.0599288641,31.0740915186,39.1496791168,48.8219552515,60.3519046835,76.9943594296,96.354256685,119.613775366,150.994961603,186.321729224,242.620577622,311.754314257,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,308.57626717,241.284828847,189.23877655,149.490342982,120.350709691,95.1874527545,75.6126056961,62.0714281075,48.3920706455,38.2592199329,30.7516818141,22.8142740892,16.657799732,12.5893069611,8.72039800719,6.35606567425,3.6539696509,2.64068457964,1.28963641796,0.614112487126,0.291703532635,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])

    # Creating weights for histo: y10_sdETA_1
    y10_sdETA_1_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0456393516902,0.0,0.0,0.0454926924109,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0456575075017,0.0454653083971,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])

    # Creating weights for histo: y10_sdETA_2
    y10_sdETA_2_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.113052660994,0.0376278490221,0.0376714988238,0.113034562674,0.112837634975,0.0752913988404,0.263457930888,0.376525017855,0.376477912638,0.301248091473,0.188166594028,0.0376996844785,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.225855726318,0.188158226654,0.226136498205,0.301120566493,0.0754899535295,0.225885941835,0.413834984136,0.225945753065,0.150678697085,0.225820552356,0.0754189858007,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])

    # Creating weights for histo: y10_sdETA_3
    y10_sdETA_3_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0825196417985,0.0825338557405,0.288697653564,0.51570893189,0.577478183703,0.72165584903,1.07192790305,1.11417377999,1.21745505496,1.75379781641,1.44369347875,1.40237889685,1.11356972554,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.15462684161,1.21711562663,1.58844686205,1.7116526406,1.23773224103,1.25833880054,0.886802201849,0.92837059326,0.598376791739,0.309387546697,0.226854361281,0.082388760796,0.0620055109902,0.0206783147873,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])

    # Creating weights for histo: y10_sdETA_4
    y10_sdETA_4_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.00739276424773,0.0222139299434,0.0370345800728,0.0888412448383,0.159196779951,0.27746150959,0.466378803619,0.714306936143,0.980656565597,1.22125148252,1.42847258008,1.50616435204,1.59113056805,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.46920426603,1.4875833753,1.35819504127,1.07309668816,0.966002459893,0.669828752183,0.503281771509,0.296042185714,0.166562913624,0.107292473255,0.0258941108119,0.0110914769414,0.00370664459737,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])

    # Creating weights for histo: y10_sdETA_5
    y10_sdETA_5_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.00283886248749,0.00566950566892,0.0160767855949,0.0387735485284,0.0850878827428,0.169224678643,0.285489298509,0.396092379942,0.570985198871,0.724097006795,0.776091244596,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.801609954271,0.708883188319,0.553909357976,0.393252383136,0.255215004581,0.180551056436,0.096396435535,0.0491651640595,0.0311888905334,0.00472505968976,0.00094530887126,0.00283609871207,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])

    # Creating weights for histo: y10_sdETA_6
    y10_sdETA_6_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.00107558666052,0.00750491974697,0.0150345298499,0.035475973992,0.0676283321521,0.126639295188,0.233003369388,0.314535453574,0.423078209885,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.365028618682,0.296366298209,0.181406411155,0.122417491741,0.0901873923248,0.0332459804771,0.0107397800098,0.00859653639432,0.00214705401294,0.00106938295553,0.00107368221156,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])

    # Creating weights for histo: y10_sdETA_7
    y10_sdETA_7_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.000161998054535,0.000323548200783,0.000809968427321,0.00194466376144,0.00445596765201,0.00793800195473,0.0153031653583,0.0283391101247,0.0493109461763,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0434945977636,0.0254240758494,0.0148987654685,0.00857823262949,0.00218217459538,0.00153927281563,0.000566864711915,0.00016190124348,0.000324020311833,8.0993872393e-05,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])

    # Creating weights for histo: y10_sdETA_8
    y10_sdETA_8_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.000213366829024,0.0,0.000745571817844,0.000852217702751,0.00105873020046,0.00127710851242,0.00585124404498,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.00690870469797,0.00254972962001,0.00127753893356,0.000634132277614,0.000319303604852,0.000105811547221,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])

    # Creating weights for histo: y10_sdETA_9
    y10_sdETA_9_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])

    # Creating weights for histo: y10_sdETA_10
    y10_sdETA_10_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,3.95485645769,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,3.948593127,0.0,0.0,3.94542685761,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])

    # Creating weights for histo: y10_sdETA_11
    y10_sdETA_11_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.86385069155,0.0,0.0,0.862575683886,4.32258147561,3.45389892579,7.77575413121,5.18306754759,7.76484134522,6.91530552554,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,3.45776083869,9.50405094058,10.3599156862,3.45041744012,0.865024396051,3.45582123617,1.72656615363,0.0,0.865644607736,0.864823807142,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])

    # Creating weights for histo: y10_sdETA_12
    y10_sdETA_12_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.103587855133,0.519097413369,0.207483575682,0.518585169864,1.97390604301,2.698882791,3.42887811166,5.91773962273,6.64522349325,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,7.37338679687,6.748656002,4.46639985245,2.18157455144,1.1416325286,1.14226147304,0.623137084297,0.311305279857,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])

    # Creating weights for histo: y10_sdETA_13
    y10_sdETA_13_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0377671422299,0.0,0.0756093183363,0.0757332824023,0.264524569491,0.491623916365,0.416062959262,1.39855726707,1.58827235614,2.60785620271,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,2.11828667156,1.96601137038,1.05851042947,0.529311996512,0.377912887094,0.264660891275,0.0756862866622,0.0754670338971,0.0753931151737,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])

    # Creating weights for histo: y10_sdETA_14
    y10_sdETA_14_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0106199280284,0.0,0.0106200564369,0.0424647849886,0.0317887309126,0.116704031678,0.222828820616,0.45595167287,0.68971988594,1.23072168848,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.08218453118,0.763972016761,0.392424824184,0.25464555612,0.127336426871,0.0531071065901,0.010616360004,0.0211773283415,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])

    # Creating weights for histo: y10_sdETA_15
    y10_sdETA_15_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0114535712355,0.0113796836612,0.0341505744492,0.039963692984,0.0914485822175,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0913357408978,0.0686263145018,0.0172297171745,0.0170715842033,0.00576830555033,0.0,0.00570977520986,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])

    # Creating weights for histo: y10_sdETA_16
    y10_sdETA_16_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.000676507697554,0.00135077493052,0.0,0.00203275927117,0.00338886474322,0.00947796789826,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0108334136034,0.00406074569877,0.00203329199327,0.00203146861111,0.000677831418142,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])

    # Creating a new Canvas
    fig   = plt.figure(figsize=(12,6),dpi=80)
    frame = gridspec.GridSpec(1,1,right=0.7)
    pad   = fig.add_subplot(frame[0])

    # Creating a new Stack
    pad.hist(x=xData, bins=xBinning, weights=y10_sdETA_0_weights+y10_sdETA_1_weights+y10_sdETA_2_weights+y10_sdETA_3_weights+y10_sdETA_4_weights+y10_sdETA_5_weights+y10_sdETA_6_weights+y10_sdETA_7_weights+y10_sdETA_8_weights+y10_sdETA_9_weights+y10_sdETA_10_weights+y10_sdETA_11_weights+y10_sdETA_12_weights+y10_sdETA_13_weights+y10_sdETA_14_weights+y10_sdETA_15_weights+y10_sdETA_16_weights,\
             label="$bg\_dip\_1600\_inf$", histtype="step", rwidth=1.0,\
             color=None, edgecolor="#e5e5e5", linewidth=1, linestyle="solid",\
             bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")

    pad.hist(x=xData, bins=xBinning, weights=y10_sdETA_0_weights+y10_sdETA_1_weights+y10_sdETA_2_weights+y10_sdETA_3_weights+y10_sdETA_4_weights+y10_sdETA_5_weights+y10_sdETA_6_weights+y10_sdETA_7_weights+y10_sdETA_8_weights+y10_sdETA_9_weights+y10_sdETA_10_weights+y10_sdETA_11_weights+y10_sdETA_12_weights+y10_sdETA_13_weights+y10_sdETA_14_weights+y10_sdETA_15_weights,\
             label="$bg\_dip\_1200\_1600$", histtype="step", rwidth=1.0,\
             color=None, edgecolor="#f2f2f2", linewidth=1, linestyle="solid",\
             bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")

    pad.hist(x=xData, bins=xBinning, weights=y10_sdETA_0_weights+y10_sdETA_1_weights+y10_sdETA_2_weights+y10_sdETA_3_weights+y10_sdETA_4_weights+y10_sdETA_5_weights+y10_sdETA_6_weights+y10_sdETA_7_weights+y10_sdETA_8_weights+y10_sdETA_9_weights+y10_sdETA_10_weights+y10_sdETA_11_weights+y10_sdETA_12_weights+y10_sdETA_13_weights+y10_sdETA_14_weights,\
             label="$bg\_dip\_800\_1200$", histtype="step", rwidth=1.0,\
             color=None, edgecolor="#ccc6aa", linewidth=1, linestyle="solid",\
             bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")

    pad.hist(x=xData, bins=xBinning, weights=y10_sdETA_0_weights+y10_sdETA_1_weights+y10_sdETA_2_weights+y10_sdETA_3_weights+y10_sdETA_4_weights+y10_sdETA_5_weights+y10_sdETA_6_weights+y10_sdETA_7_weights+y10_sdETA_8_weights+y10_sdETA_9_weights+y10_sdETA_10_weights+y10_sdETA_11_weights+y10_sdETA_12_weights+y10_sdETA_13_weights,\
             label="$bg\_dip\_600\_800$", histtype="step", rwidth=1.0,\
             color=None, edgecolor="#ccc6aa", linewidth=1, linestyle="solid",\
             bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")

    pad.hist(x=xData, bins=xBinning, weights=y10_sdETA_0_weights+y10_sdETA_1_weights+y10_sdETA_2_weights+y10_sdETA_3_weights+y10_sdETA_4_weights+y10_sdETA_5_weights+y10_sdETA_6_weights+y10_sdETA_7_weights+y10_sdETA_8_weights+y10_sdETA_9_weights+y10_sdETA_10_weights+y10_sdETA_11_weights+y10_sdETA_12_weights,\
             label="$bg\_dip\_400\_600$", histtype="step", rwidth=1.0,\
             color=None, edgecolor="#c1bfa8", linewidth=1, linestyle="solid",\
             bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")

    pad.hist(x=xData, bins=xBinning, weights=y10_sdETA_0_weights+y10_sdETA_1_weights+y10_sdETA_2_weights+y10_sdETA_3_weights+y10_sdETA_4_weights+y10_sdETA_5_weights+y10_sdETA_6_weights+y10_sdETA_7_weights+y10_sdETA_8_weights+y10_sdETA_9_weights+y10_sdETA_10_weights+y10_sdETA_11_weights,\
             label="$bg\_dip\_200\_400$", histtype="step", rwidth=1.0,\
             color=None, edgecolor="#bab5a3", linewidth=1, linestyle="solid",\
             bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")

    pad.hist(x=xData, bins=xBinning, weights=y10_sdETA_0_weights+y10_sdETA_1_weights+y10_sdETA_2_weights+y10_sdETA_3_weights+y10_sdETA_4_weights+y10_sdETA_5_weights+y10_sdETA_6_weights+y10_sdETA_7_weights+y10_sdETA_8_weights+y10_sdETA_9_weights+y10_sdETA_10_weights,\
             label="$bg\_dip\_100\_200$", histtype="step", rwidth=1.0,\
             color=None, edgecolor="#b2a596", linewidth=1, linestyle="solid",\
             bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")

    pad.hist(x=xData, bins=xBinning, weights=y10_sdETA_0_weights+y10_sdETA_1_weights+y10_sdETA_2_weights+y10_sdETA_3_weights+y10_sdETA_4_weights+y10_sdETA_5_weights+y10_sdETA_6_weights+y10_sdETA_7_weights+y10_sdETA_8_weights+y10_sdETA_9_weights,\
             label="$bg\_dip\_0\_100$", histtype="step", rwidth=1.0,\
             color=None, edgecolor="#b7a39b", linewidth=1, linestyle="solid",\
             bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")

    pad.hist(x=xData, bins=xBinning, weights=y10_sdETA_0_weights+y10_sdETA_1_weights+y10_sdETA_2_weights+y10_sdETA_3_weights+y10_sdETA_4_weights+y10_sdETA_5_weights+y10_sdETA_6_weights+y10_sdETA_7_weights+y10_sdETA_8_weights,\
             label="$bg\_vbf\_1600\_inf$", histtype="step", rwidth=1.0,\
             color=None, edgecolor="#ad998c", linewidth=1, linestyle="solid",\
             bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")

    pad.hist(x=xData, bins=xBinning, weights=y10_sdETA_0_weights+y10_sdETA_1_weights+y10_sdETA_2_weights+y10_sdETA_3_weights+y10_sdETA_4_weights+y10_sdETA_5_weights+y10_sdETA_6_weights+y10_sdETA_7_weights,\
             label="$bg\_vbf\_1200\_1600$", histtype="step", rwidth=1.0,\
             color=None, edgecolor="#9b8e82", linewidth=1, linestyle="solid",\
             bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")

    pad.hist(x=xData, bins=xBinning, weights=y10_sdETA_0_weights+y10_sdETA_1_weights+y10_sdETA_2_weights+y10_sdETA_3_weights+y10_sdETA_4_weights+y10_sdETA_5_weights+y10_sdETA_6_weights,\
             label="$bg\_vbf\_800\_1200$", histtype="step", rwidth=1.0,\
             color=None, edgecolor="#876656", linewidth=1, linestyle="solid",\
             bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")

    pad.hist(x=xData, bins=xBinning, weights=y10_sdETA_0_weights+y10_sdETA_1_weights+y10_sdETA_2_weights+y10_sdETA_3_weights+y10_sdETA_4_weights+y10_sdETA_5_weights,\
             label="$bg\_vbf\_600\_800$", histtype="step", rwidth=1.0,\
             color=None, edgecolor="#afcec6", linewidth=1, linestyle="solid",\
             bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")

    pad.hist(x=xData, bins=xBinning, weights=y10_sdETA_0_weights+y10_sdETA_1_weights+y10_sdETA_2_weights+y10_sdETA_3_weights+y10_sdETA_4_weights,\
             label="$bg\_vbf\_400\_600$", histtype="step", rwidth=1.0,\
             color=None, edgecolor="#84c1a3", linewidth=1, linestyle="solid",\
             bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")

    pad.hist(x=xData, bins=xBinning, weights=y10_sdETA_0_weights+y10_sdETA_1_weights+y10_sdETA_2_weights+y10_sdETA_3_weights,\
             label="$bg\_vbf\_200\_400$", histtype="step", rwidth=1.0,\
             color=None, edgecolor="#89a8a0", linewidth=1, linestyle="solid",\
             bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")

    pad.hist(x=xData, bins=xBinning, weights=y10_sdETA_0_weights+y10_sdETA_1_weights+y10_sdETA_2_weights,\
             label="$bg\_vbf\_100\_200$", histtype="step", rwidth=1.0,\
             color=None, edgecolor="#829e8c", linewidth=1, linestyle="solid",\
             bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")

    pad.hist(x=xData, bins=xBinning, weights=y10_sdETA_0_weights+y10_sdETA_1_weights,\
             label="$bg\_vbf\_0\_100$", histtype="step", rwidth=1.0,\
             color=None, edgecolor="#adbcc6", linewidth=1, linestyle="solid",\
             bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")

    pad.hist(x=xData, bins=xBinning, weights=y10_sdETA_0_weights,\
             label="$signal$", histtype="step", rwidth=1.0,\
             color=None, edgecolor="#7a8e99", linewidth=1, linestyle="solid",\
             bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")

    # Axis
    plt.rc('text',usetex=False)
    plt.xlabel(r"\Delta\eta ( j_{1} , j_{2} ) ",\
               fontsize=16,color="black")
    plt.ylabel(r"$\mathrm{Events}$ $(\mathcal{L}_{\mathrm{int}} = 150.0\ \mathrm{fb}^{-1})$ ",\
               fontsize=16,color="black")

    # Boundary of y-axis
    ymax=(y10_sdETA_0_weights+y10_sdETA_1_weights+y10_sdETA_2_weights+y10_sdETA_3_weights+y10_sdETA_4_weights+y10_sdETA_5_weights+y10_sdETA_6_weights+y10_sdETA_7_weights+y10_sdETA_8_weights+y10_sdETA_9_weights+y10_sdETA_10_weights+y10_sdETA_11_weights+y10_sdETA_12_weights+y10_sdETA_13_weights+y10_sdETA_14_weights+y10_sdETA_15_weights+y10_sdETA_16_weights).max()*1.1
    ymin=0 # linear scale
    #ymin=min([x for x in (y10_sdETA_0_weights+y10_sdETA_1_weights+y10_sdETA_2_weights+y10_sdETA_3_weights+y10_sdETA_4_weights+y10_sdETA_5_weights+y10_sdETA_6_weights+y10_sdETA_7_weights+y10_sdETA_8_weights+y10_sdETA_9_weights+y10_sdETA_10_weights+y10_sdETA_11_weights+y10_sdETA_12_weights+y10_sdETA_13_weights+y10_sdETA_14_weights+y10_sdETA_15_weights+y10_sdETA_16_weights) if x])/100. # log scale
    plt.gca().set_ylim(ymin,ymax)

    # Log/Linear scale for X-axis
    plt.gca().set_xscale("linear")
    #plt.gca().set_xscale("log",nonposx="clip")

    # Log/Linear scale for Y-axis
    plt.gca().set_yscale("linear")
    #plt.gca().set_yscale("log",nonposy="clip")

    # Legend
    plt.legend(bbox_to_anchor=(1.05,1), loc=2, borderaxespad=0.)

    # Saving the image
    plt.savefig('../../HTML/MadAnalysis5job_0/selection_9.png')
    plt.savefig('../../PDF/MadAnalysis5job_0/selection_9.png')
    plt.savefig('../../DVI/MadAnalysis5job_0/selection_9.eps')

# Running!
if __name__ == '__main__':
    selection_9()