text:
import datetime
import logging

import numpy as np
import matplotlib.pyplot as plt

from nn.shallow.nn_shallow_cs import CryptoNNClient
from nn.shallow.nn_shallow_cs import CryptoNNServer
from nn.utils import load_mnist
from nn.utils import load_mnist_size
from nn.utils import timer
from nn.smc import Secure2PCClient
from nn.smc import Secure2PCServer
from nn.smc import EnhancedSecure2PCClient
from nn.smc import EnhancedSecure2PCServer
from crypto.utils import load_dlog_table_config
from crypto.sife_dynamic import SIFEDynamicTPA
from crypto.sife_dynamic import SIFEDynamicClient
from crypto.mife_dynamic import MIFEDynamicTPA
from crypto.mife_dynamic import MIFEDynamicClient

t_str = str(datetime.datetime.today())
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
    datefmt='%m-%d %H:%M',
    filename="logs/test_nn_shallow_cs-" + '-'.join(t_str.split()[:1] + t_str.split()[1].split(':')[:2]) + '.log',
    filemode='w')
logger = logging.getLogger(__name__)

def test_nn_shallow_mnist():
    X_train, y_train = load_mnist_size('datasets/mnist', size=600)
    X_test, y_test = load_mnist_size('datasets/mnist', size=100, kind='t10k')
    # X_train, y_train = load_mnist('datasets/mnist')
    # X_test, y_test = load_mnist('datasets/mnist', kind='t10k')

    # shuffle
    X_data, y_data = X_train.copy(), y_train.copy()
    idx = np.random.permutation(X_data.shape[0])
    X_data, y_data = X_data[idx], y_data[idx]

    total_mini_batches = 10

    hidden_layers_lst = [
        [256],
        [256, 128, 64],
        [256, 128, 64, 32, 16]
    ]
    for hidden_layers in hidden_layers_lst:
        nn_client = CryptoNNClient(n_output=10, mini_batches=total_mini_batches, n_features=X_data.shape[1], random_seed=520)
        nn_server = CryptoNNServer(n_output=10, n_features=X_data.shape[1], hidden_layers=hidden_layers,
                               l2=0.1, l1=0.0, epochs=1, eta=0.001, alpha=0.001,
                               decrease_const=0.0001, mini_batches=total_mini_batches)

        X_client, y_client = nn_client.pre_process(X_data, y_data)
        with timer('training using secure2pc setting - 10 batches-' + str(hidden_layers), logger) as t:
            (train_loss_hist,
             test_acc_hist,
             train_batch_time_hist,
             train_time_hist) = nn_server.fit(X_client, y_client, X_test, y_test)
            logger.info('train loss: \n' + str(train_loss_hist))
            logger.info('test acc: \n' + str(test_acc_hist))

def test_nn_shallow_mnist_smc():
    logger.info('test nn shallow mnist with secure 2pc setting')
    logger.info('initialize the crypto system ...')
    sec_param_config_file = 'config/sec_param.json'  # indicate kernel size 5
    dlog_table_config_file = 'config/dlog_b8.json'
    with timer('load sife config file, cost time', logger) as t:
        eta = 1250
        sec_param = 256
        dlog = load_dlog_table_config(dlog_table_config_file)

        sife_tpa = SIFEDynamicTPA(eta, sec_param=sec_param, sec_param_config=sec_param_config_file)
        sife_tpa.setup()
        sife_enc_client = SIFEDynamicClient(role='enc')
        sife_dec_client = SIFEDynamicClient(role='dec', dlog=dlog)
        logger.info('the crypto system initialization done!')

    precision_data = 0
    precision_weight = 3

    secure2pc_client = Secure2PCClient(sife=(sife_tpa, sife_enc_client), precision=precision_data)
    secure2pc_server = Secure2PCServer(sife=(sife_tpa, sife_dec_client), precision=(precision_data, precision_weight))

    X_train, y_train = load_mnist_size('datasets/mnist', size=600)
    X_test, y_test = load_mnist_size('datasets/mnist', size=100, kind='t10k')
    # X_train, y_train = load_mnist('datasets/mnist')
    # X_test, y_test = load_mnist('datasets/mnist', kind='t10k')

    # shuffle
    X_data, y_data = X_train.copy(), y_train.copy()
    idx = np.random.permutation(X_data.shape[0])
    X_data, y_data = X_data[idx], y_data[idx]

    total_mini_batches = 50

    nn_client = CryptoNNClient(n_output=10, mini_batches=total_mini_batches, n_features=X_data.shape[1], smc=secure2pc_client, random_seed=520)
    nn_server = CryptoNNServer(n_output=10, n_features=X_data.shape[1], hidden_layers=[64],
                               l2=0.1, l1=0.0, epochs=1, eta=0.001, alpha=0.001,
                               decrease_const=0.0001, mini_batches=total_mini_batches, smc=secure2pc_server)
    logger.info('client start to encrypt dataset ...')
    ct_feedforward_lst, ct_backpropagation_lst, y_onehot_lst = nn_client.pre_process(X_data, y_data)
    logger.info('client encrypting DONE')
    logger.info('server start to train ...')
    with timer('training using secure2pc setting - 10 batches', logger) as t:
        (train_loss_hist,
         test_acc_hist,
        train_batch_time_hist,
        train_time_hist) = nn_server.fit((ct_feedforward_lst, ct_backpropagation_lst), y_onehot_lst, X_test, y_test)
    logger.info('server training DONE')

    logger.info('training loss: \n\r' + str(train_loss_hist))
    logger.info('test acc: \n\r' + str(test_acc_hist))

def test_nn_shallow_mnist_smc_enhanced():
    logger.info('test nn shallow in mnist using enhanced smc')

    logger.info('initialize the crypto system ...')
    sec_param_config_file = 'config/sec_param.json'  # indicate kernel size 5
    dlog_table_config_file = 'config/dlog_b8.json'
    with timer('initialize crypto system, cost time', logger) as t:
        eta = 1250
        sec_param = 256
        setup_parties = {
            'id_1': 200,
            'id_2': 200,
            'id_3': 200,
            'id_4': 200,
            'id_5': 200
        }
        logger.info('loading dlog configuration ...')
        dlog = load_dlog_table_config(dlog_table_config_file)
        logger.info('load dlog configuration DONE')
        sife_tpa = SIFEDynamicTPA(eta, sec_param=sec_param, sec_param_config=sec_param_config_file)
        sife_tpa.setup()
        sife_enc_client = SIFEDynamicClient(sec_param=256, role='enc')
        sife_dec_client = SIFEDynamicClient(sec_param=256, role='dec', dlog=dlog)
        mife_tpa = MIFEDynamicTPA(sec_param=256, parties=setup_parties, sec_param_config=sec_param_config_file)
        mife_tpa.setup()
        mife_enc_client = MIFEDynamicClient(sec_param=256, role='enc')
        mife_dec_client = MIFEDynamicClient(sec_param=256, role='dec', dlog=dlog)
        logger.info('the crypto system initialization done!')

    precision_data = 0
    precision_weight = 4

    es2pc_client = EnhancedSecure2PCClient(
        sife=(sife_tpa, sife_enc_client),
        mife=(mife_tpa, mife_enc_client),
        precision=precision_data)
    es2pc_server = EnhancedSecure2PCServer(
        sife=(sife_tpa, sife_dec_client),
        mife=(mife_tpa, mife_dec_client),
        precision=(precision_data, precision_weight))

    X_train, y_train = load_mnist_size('datasets/mnist', size=600)
    X_test, y_test = load_mnist_size('datasets/mnist', size=100, kind='t10k')
    # X_train, y_train = load_mnist('datasets/mnist')
    # X_test, y_test = load_mnist('datasets/mnist', kind='t10k')

    # shuffle
    X_data, y_data = X_train.copy(), y_train.copy()
    idx = np.random.permutation(X_data.shape[0])
    X_data, y_data = X_data[idx], y_data[idx]

    features_splits = np.array_split(range(X_data.shape[1]), len(setup_parties))
    X_data_lst = [X_data[:, idx] for idx in features_splits]

    total_mini_batches = 50

    nn_server = CryptoNNServer(n_output=10, n_features=X_data.shape[1], hidden_layers=[64],
                               l2=0.1, l1=0.0, epochs=50, eta=0.001, alpha=0.001,
                               decrease_const=0.0001, mini_batches=total_mini_batches, smc=es2pc_server)
    logger.info('client start to encrypt dataset ...')
    ct_ff_lst_dict = dict()
    ct_bp_lst_dict = dict()
    x_idx_count = 0
    final_y_onehot_lst = None
    for id in setup_parties.keys():
        if x_idx_count == (len(setup_parties) - 1):
            n_features = X_data_lst[x_idx_count].shape[1] + 1
            nn_client = CryptoNNClient(n_output=10, mini_batches=total_mini_batches, n_features=n_features,
                                       smc=es2pc_client, random_seed=520, id=id)
            nn_server.register(nn_client)
            ct_feedforward_lst, ct_backpropagation_lst, y_onehot_lst = nn_client.pre_process(X_data_lst[x_idx_count], y_data)
            ct_ff_lst_dict[id] = ct_feedforward_lst
            ct_bp_lst_dict[id] = ct_backpropagation_lst
            final_y_onehot_lst = y_onehot_lst
        else:
            n_features = X_data_lst[x_idx_count].shape[1]
            nn_client = CryptoNNClient(n_output=10, mini_batches=total_mini_batches, n_features=n_features,
                                       smc=es2pc_client, random_seed=520, id=id)
            nn_server.register(nn_client)
            ct_feedforward_lst, ct_backpropagation_lst = nn_client.pre_process(X_data_lst[x_idx_count])
            ct_ff_lst_dict[id] = ct_feedforward_lst
            ct_bp_lst_dict[id] = ct_backpropagation_lst
        x_idx_count = x_idx_count + 1
    logger.info('client encrypting DONE')

    logger.info('server start to train ...')
    (train_loss_hist,
     test_acc_hist,
     train_batch_time_hist,
     train_time_hist) = nn_server.fit((ct_ff_lst_dict, ct_bp_lst_dict), final_y_onehot_lst, X_test, y_test)
    logger.info('server training DONE')

    logger.info('training loss: \n\r' + str(train_loss_hist))
    logger.info('test acc: \n\r' + str(test_acc_hist))

def test_nn_shallow_mnist_smc_cryptonn():
    logger.info('test nn shallow mnist with secure 2pc setting')
    logger.info('initialize the crypto system ...')

    eta = 1250
    sec_param = 256

    sife_tpa = SIFEDynamicTPA(eta, sec_param=sec_param)
    sife_tpa.setup()
    sife_enc_client = SIFEDynamicClient(role='enc')
    sife_dec_client = SIFEDynamicClient(role='dec')
    logger.info('the crypto system initialization done!')

    precision_data = 0
    precision_weight = 4

    secure2pc_client = Secure2PCClient(sife=(sife_tpa, sife_enc_client), precision=precision_data)
    secure2pc_server = Secure2PCServer(sife=(sife_tpa, sife_dec_client), precision=(precision_data, precision_weight))

    X_train, y_train = load_mnist_size('datasets/mnist', size=60)
    X_test, y_test = load_mnist_size('datasets/mnist', size=100, kind='t10k')
    # X_train, y_train = load_mnist('datasets/mnist')
    # X_test, y_test = load_mnist('datasets/mnist', kind='t10k')

    # shuffle
    X_data, y_data = X_train.copy(), y_train.copy()
    idx = np.random.permutation(X_data.shape[0])
    X_data, y_data = X_data[idx], y_data[idx]

    total_mini_batches = 1

    nn_client = CryptoNNClient(n_output=10, mini_batches=total_mini_batches, n_features=X_data.shape[1], smc=secure2pc_client, random_seed=520)
    nn_server = CryptoNNServer(n_output=10, n_features=X_data.shape[1], hidden_layers=[64],
                               l2=0.1, l1=0.0, epochs=50, eta=0.001, alpha=0.001,
                               decrease_const=0.0001, mini_batches=total_mini_batches, smc=secure2pc_server)
    logger.info('client start to encrypt dataset ...')
    ct_feedforward_lst, ct_backpropagation_lst, y_onehot_lst = nn_client.pre_process(X_data, y_data)
    logger.info('client encrypting DONE')
    logger.info('server start to train ...')
    with timer('training using secure2pc setting - 1 batches', logger) as t:
        (train_loss_hist,
         test_acc_hist,
         train_batch_time_hist,
         train_time_hist) = nn_server.fit((ct_feedforward_lst, ct_backpropagation_lst), y_onehot_lst, X_test, y_test)
    logger.info('server training DONE')

    logger.info('training loss: \n\r' + str(train_loss_hist))
    logger.info('test acc: \n\r' + str(test_acc_hist))

max_stars_repo_name: eggry/nn-emd

max_issues_repo_name: eggry/nn-emd

max_forks_repo_name: eggry/nn-emd


text:
import numpy as np
try:
	import cv2
except:
	import cv2
from core.cube_feature import featureExtract

side0 = cv2.imread("images/test-5/image1.jpeg")
side1 = cv2.imread("images/test-5/image2.jpeg")
side2 = cv2.imread("images/test-5/image3.jpeg")
side3 = cv2.imread("images/test-5/image4.jpeg")
side4 = cv2.imread("images/test-5/image5.jpeg")
side5 = cv2.imread("images/test-5/image6.jpeg")

cube_ext = featureExtract([side0,side1,side2,side3,side4,side5])

sides = cube_ext.grid

i=0
for side in sides:
	np.savetxt("matrices/test-5/side{}.txt".format(i),side)
	i+=1

ext: py

reason: import numpy


text:
"""
@file
@brief To add interactive widgets in a notebook and connect it to Python function,
Source: https://github.com/jakevdp/ipywidgets, the module was modified for Python 3
See notebook :ref:`havingaforminanotebookrst`.

Copyright (c) 2013, Jake Vanderplas
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this
  list of conditions and the following disclaimer in the documentation and/or
  other materials provided with the distribution.

* Neither the name of the {organization} nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""

import copy

class StaticWidget(object):

    """
    Base Class for Static Widgets
    """

    def __init__(self, name=None, divclass=None):
        """
        constructor

        @param      name        name
        @param      divclass    class for div section
        """
        self.name = name
        if divclass is None:
            self.divargs = ""
        else:
            self.divargs = 'class:"{0}"'.format(divclass)

    def __repr__(self):
        """
        operator, call method html
        """
        return self.html()

    def _repr_html_(self):
        """
        operator, call method html
        """
        return self.html()

    def html(self):
        "abstract method"
        raise NotImplementedError(  # pragma: no cover
            "This should overriden.")

    def copy(self):
        """
        calls deepcopy

        @return     copy of self
        """
        return copy.deepcopy(self)

    def renamed(self, name):
        """
        rename *name* if *name* is an attribute

        @return     object
        """
        if (self.name is not None) and (self.name != name):
            obj = self.copy()
        else:
            obj = self
        obj.name = name
        return obj

class RangeWidget(StaticWidget):

    """
    Range (slider) widget

    The class overloads :meth:`html <pyquickhelper.ipythonhelper.widgets.RangeWidget.html>`
    and :meth:`values <pyquickhelper.ipythonhelper.widgets.RangeWidget.values>`.
    """
    slider_html = ('{name}: <input type="range" name="{name}" '
                   'min="{range[0]}" max="{range[1]}" step="{range[2]}" '
                   'value="{default}" style="{style}" '
                   'oninput="interactUpdate(this.parentNode);" '
                   'onchange="interactUpdate(this.parentNode);">')

    def __init__(self, min, max, step=1, name=None,
                 default=None, width=350, divclass=None,
                 show_range=False):
        """
        @param      min         min value
        @param      max         max value
        @param      step        step
        @param      name        name
        @param      default     default value
        @param      width       width in pixel
        @param      divclass    class for div section
        @param      show_range  boolean
        """
        StaticWidget.__init__(self, name, divclass)
        self.datarange = (min, max, step)
        self.width = width
        self.show_range = show_range
        if default is None:
            self.default = min
        else:
            self.default = default

    def values(self):
        """
        @return     all possible values
        """
        min, max, step = self.datarange
        import numpy as np
        return np.arange(min, max + step, step)

    def html(self):
        """
        HTML code

        @return     string HTML
        """
        style = ""

        if self.width is not None:
            style += "width:{0}px".format(self.width)

        output = self.slider_html.format(name=self.name, range=self.datarange,
                                         default=self.default, style=style)
        if self.show_range:
            output = "{0} {1} {2}".format(self.datarange[0],
                                          output,
                                          self.datarange[1])
        return output

class DropDownWidget(StaticWidget):

    """
    drop down list
    """

    #: template 1
    select_html = ('{name}: <select name="{name}" '
                   'onchange="interactUpdate(this.parentNode);"> '
                   '{options}'
                   '</select>'
                   )

    #: template 2
    option_html = ('<option value="{value}" '
                   '{selected}>{label}</option>')

    def __init__(self, values, name=None,
                 labels=None, default=None, divclass=None,
                 delimiter="      "):
        """
        @param      values      values for the list
        @param      name        name of the object
        @param      labels      ?
        @param      default     default value
        @param      divclass    class for div section
        @param      delimiter   delimiter
        """
        StaticWidget.__init__(self, name, divclass)
        self._values = values
        self.delimiter = delimiter
        if labels is None:
            labels = map(str, values)
        elif len(labels) != len(values):
            raise ValueError("length of labels must match length of values")
        self.labels = labels

        if default is None:
            self.default = values[0]
        elif default in values:
            self.default = default
        else:
            raise ValueError(  # pragma: no cover
                "if specified, default must be in values")

    def _single_option(self, label, value):
        """
        private
        """
        if value == self.default:
            selected = ' selected '
        else:
            selected = ''
        return self.option_html.format(label=label,
                                       value=value,
                                       selected=selected)

    def values(self):
        """
        return all possible values
        """
        return self._values

    def html(self):
        """
        return HTML string
        """
        options = self.delimiter.join(
            [self._single_option(label, value)
             for (label, value) in zip(self.labels, self._values)]
        )
        return self.select_html.format(name=self.name,
                                       options=options)

class RadioWidget(StaticWidget):

    """
    radio button
    """

    #: template 1
    radio_html = ('<input type="radio" name="{name}" value="{value}" '
                  '{checked} '
                  'onchange="interactUpdate(this.parentNode);">')

    def __init__(self, values, name=None,
                 labels=None, default=None, divclass=None,
                 delimiter="      "):
        """
        @param      values      values for the list
        @param      name        name of the object
        @param      labels      ?
        @param      default     default value
        @param      divclass    class for div section
        @param      delimiter   delimiter
        """
        StaticWidget.__init__(self, name, divclass)
        self._values = values
        self.delimiter = delimiter

        if labels is None:
            labels = map(str, values)
        elif len(labels) != len(values):
            raise ValueError("length of labels must match length of values")
        self.labels = labels

        if default is None:
            self.default = values[0]
        elif default in values:
            self.default = default
        else:
            raise ValueError(  # pragma: no cover
                "if specified, default must be in values: default={0}, values={1}".format(
                    default, values))

    def _single_radio(self, value):
        """
        private
        """
        if value == self.default:
            checked = 'checked="checked"'
        else:
            checked = ''
        return self.radio_html.format(name=self.name, value=value,
                                      checked=checked)

    def values(self):
        """
        return all the possible values
        """
        return self._values

    def html(self):
        """
        return HTML string
        """
        preface = '{name}: '.format(name=self.name)
        return preface + self.delimiter.join(
            ["{0}: {1}".format(label, self._single_radio(value))
             for (label, value) in zip(self.labels, self._values)])

max_stars_repo_name: Pandinosaurus/pyquickhelper

max_issues_repo_name: Pandinosaurus/pyquickhelper

max_forks_repo_name: Pandinosaurus/pyquickhelper


text:
import cPickle
import os
from multiprocessing import Pool
import sys
import numpy as np
chan = ['Fp1','AF3','F3','F7','FC5','FC1','C3','T7','CP5','CP1','P3','P7','PO3','O1','Oz','Pz','Fp2','AF4','Fz','F4','F8','FC6','FC2','Cz','C4','T8','CP6','CP2','P4','P8','PO4','O2']
nLabel, nTrial, nUser, nChannel, nTime  = 4, 40, 32, 32, 8064
print "Program started \n"
fout_labels0 = open("labels_0.dat",'w')
fout_labels1 = open("labels_1.dat",'w')
fout_labels2 = open("labels_2.dat",'w')
fout_labels3 = open("labels_3.dat",'w')
for i in range(nUser):#4, 40, 32, 32, 8064
	if i < 10:
		name = '%0*d' % (2,i+1)
	else:
		name = i+1
	fname = "/data_preprocessed_python/data_preprocessed_python/s"+str(name)+".dat"
	x = cPickle.load(open(fname, 'rb'))
	print fname
	for tr in range(nTrial):
		fout_data = open("features_raw.csv",'w')
		for ch in chan:
			fout_data.write(ch+",")
		fout_data.write("\n")
		for dat in range(nTime):
			for ch in range(nChannel):
				if ch <32:
					if ch == 31:
						fout_data.write(str(x['data'][tr][ch][dat]));
					else:
						fout_data.write(str(x['data'][tr][ch][dat])+",");
			fout_data.write("\n");
		fout_labels0.write(str(x['labels'][tr][0]) + "\n");
		fout_labels1.write(str(x['labels'][tr][1]) + "\n");
		fout_labels2.write(str(x['labels'][tr][2]) + "\n");
		fout_labels3.write(str(x['labels'][tr][3]) + "\n");
		fout_data.close()
		os.system('python creating_vector.py')
		print "user "+ str(i) +" trail"+ str(tr)
fout_labels0.close()
fout_labels1.close()
fout_labels2.close()
fout_labels3.close()
print "\n"+"Print Successful"


text:
import sys
import os
import numpy as np
from scipy.stats import binom
import sys
from confseq.cs_plots import ConfseqToPlot, DataGeneratingProcess, plot_CSs
from confseq.betting import betting_cs, mu_t, dKelly_cs
from confseq.predmix import (
    predmix_empbern_cs,
    predmix_hoeffding_cs
)
import matplotlib.pyplot as plt

figures_location = os.path.relpath("figures/")

N = 10000
alpha = 0.05

x = np.append(np.zeros(int(N / 2)), np.ones(int(N / 2)))
pmf = lambda x: binom.pmf(x, 1, 0.5)

def data_generator():
    np.random.shuffle(x)
    return x

t = np.arange(1, N + 1)

alpha = 0.05

cs_list = [
    ConfseqToPlot(
        lambda x: predmix_hoeffding_cs(x, N=N, alpha=alpha, running_intersection=True),
        "H-WoR [WR20]",
        "tab:orange",
        "-.",
    ),
    ConfseqToPlot(
        lambda x: predmix_empbern_cs(x, N=N, alpha=alpha, running_intersection=True),
        "EB-WoR [WR20]",
        "tab:blue",
        "--",
    ),
    ConfseqToPlot(
        lambda x: betting_cs(
            x,
            alpha=alpha,
            N=N,
            parallel=True,
            running_intersection=True,
            trunc_scale=1 / 2,
        ),
        r"Hedged-WoR [Thm 4]",
        "tab:green",
        "-",
    ),
    ConfseqToPlot(
        lambda x: dKelly_cs(
            x,
            alpha=alpha,
            N=N,
            parallel=True,
            running_intersection=True
        ),
        r"hgKelly",
        "tab:purple",
        ":",
    )
]

def generate_data_generator(x):
    def d_g():
        np.random.shuffle(x)
        return x

    return d_g

x_binom05 = np.random.binomial(1, 0.51, N)
x_binom01 = np.random.binomial(1, 1 / 20, N)
x_beta11 = np.random.beta(1, 1, N)
x_beta1030 = np.random.beta(10, 30, N)

dgp_list = [
    DataGeneratingProcess(
        data_generator_fn=generate_data_generator(x_binom05),
        name="Bernoulli_0.5__WoR",
        title="Discrete 0/1 high variance",
        WoR=True
    ),
    DataGeneratingProcess(
        data_generator_fn=generate_data_generator(x_binom01),
        name="Bernoulli_0.1__WoR",
        title="Discrete 0/1 low variance",
        WoR=True
    ),
    DataGeneratingProcess(
        data_generator_fn=generate_data_generator(x_beta11),
        name="Beta_1,_1__WoR",
        title="Real-valued evenly spread",
        WoR=True
    ),
    DataGeneratingProcess(
        data_generator_fn=generate_data_generator(x_beta1030),
        name="Beta_10,_30__WoR",
        title="Real-valued concentrated",
        WoR=True
    ),
]

plot_CSs(
    dgp_list,
    cs_list,
    time_uniform=True,
    nsim=5,
    log_scale=True,
    display_start=10,
    folder=figures_location,
)

print("Done!")

max_stars_repo_name: WannabeSmith/betting-paper-simulations

max_issues_repo_name: WannabeSmith/betting-paper-simulations

max_forks_repo_name: WannabeSmith/betting-paper-simulations

reason: import numpy,from scipy


text:
import os
from posixpath import join
import re
import math
import random
import pickle
from typing import ByteString

from pandas.core import base
import librosa
import numpy as np
import pandas as pd
from tqdm import tqdm
import soundfile as sf
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler

from convert_aud_to_token import EmotionDataPreprocessing

# Part 1: Extract Audio Labels
def extract_audio_labels(base_path,labels_path):
    if os.path.exists(labels_path):
        return
    info_line = re.compile(r'\[.+\]\n', re.IGNORECASE)

    start_times, end_times, wav_file_names, emotions, vals, acts, doms = \
        [], [], [], [], [], [], []

    for sess in range(1, 6):
        emo_evaluation_dir = \
            base_path+'/Session{}/dialog/EmoEvaluation/'.format(sess)
        evaluation_files = [l for l in os.listdir(emo_evaluation_dir) if 'Ses' in l]
        for file in evaluation_files:
            if file.startswith("."):
                continue
            with open(emo_evaluation_dir + file,encoding="utf-8") as f:
                content = f.read()
            info_lines = re.findall(info_line, content)
            for line in info_lines[1:]:  # the first line is a header
                start_end_time, wav_file_name, emotion, val_act_dom = \
                    line.strip().split('\t')
                start_time, end_time = start_end_time[1:-1].split('-')
                val, act, dom = val_act_dom[1:-1].split(',')
                val, act, dom = float(val), float(act), float(dom)
                start_time, end_time = float(start_time), float(end_time)
                start_times.append(start_time)
                end_times.append(end_time)
                wav_file_names.append(wav_file_name)
                emotions.append(emotion)
                vals.append(val)
                acts.append(act)
                doms.append(dom)

    df_iemocap = pd.DataFrame(columns=['start_time', 'end_time', 'wav_file',
                                       'emotion', 'val', 'act', 'dom'])

    df_iemocap['start_time'] = start_times
    df_iemocap['end_time'] = end_times
    df_iemocap['wav_file'] = wav_file_names
    df_iemocap['emotion'] = emotions
    df_iemocap['val'] = vals
    df_iemocap['act'] = acts
    df_iemocap['dom'] = doms
    os.makedirs(os.path.dirname(labels_path),exist_ok=True)
    df_iemocap.to_csv(labels_path, index=False)

# Part 2: Build Audio Vectors
def build_audio_vectors(base_path,labels_path,data_dir,sr):
    labels_df = pd.read_csv(labels_path)
    audio_vectors = {}
    audio_tokens={}
    data_processor = EmotionDataPreprocessing()
    for sess in  range(1,6):# using one session due to memory constraint, can replace [5] with range(1, 6)
        save_vector_file=os.path.join(data_dir,'audio_vectors_{}.pkl'.format(sess))
        save_token_file=os.path.join(data_dir,'audio_tokens_{}.pkl'.format(sess))
        if os.path.exists(save_vector_file) and os.path.exists(save_token_file):
            continue
        wav_file_path = os.path.join(base_path,'Session{}/dialog/wav/'.format(sess))
        orig_wav_files = os.listdir(wav_file_path)
        for orig_wav_file in tqdm(orig_wav_files):
            if orig_wav_file.startswith(".") or not orig_wav_file.endswith(".wav"):
                continue
            orig_wav_vector, _sr = librosa.load(wav_file_path + orig_wav_file, sr=sr)
            orig_wav_file, file_format = orig_wav_file.split('.')
            for index, row in labels_df[labels_df['wav_file'].str.contains(orig_wav_file)].iterrows():
                try:
                    start_time, end_time, truncated_wav_file_name, emotion,\
                    val, act, dom = row['start_time'], row['end_time'],\
                    row['wav_file'], row['emotion'], row['val'],\
                    row['act'], row['dom']
                    start_frame = math.floor(start_time * sr)
                    end_frame = math.floor(end_time * sr)
                    if end_frame+1>=len(orig_wav_vector):
                        continue
                    truncated_wav_vector = orig_wav_vector[start_frame:end_frame + 1]
                    audio_vectors[truncated_wav_file_name] = truncated_wav_vector

                    # tokens preprocessing
                    #wav, curr_sample_rate = sf.read(audio_path)
                    tokens=data_processor.preprocess_audio_data(truncated_wav_vector)
                    audio_tokens[truncated_wav_file_name]=tokens
                except:
                    print('An exception occured for {}'.format(orig_wav_file))
        with open(save_vector_file, 'wb') as f:
            pickle.dump(audio_vectors, f)

        with open(save_token_file, 'wb') as f:
            pickle.dump(audio_tokens, f)

# Part 3: Extract Audio Features
def extract_audio_features(labels_path,data_dir):
    save_audio_feature_file=os.path.join(data_dir,'audio_features.csv')
    if os.path.exists(save_audio_feature_file):
        return

    columns = ['wav_file', 'label', 'sig_mean', 'sig_std', 'rmse_mean','rmse_std', 'silence', 'harmonic', 'auto_corr_max', 'auto_corr_std',"tokens"]
    df_features = pd.DataFrame(columns=columns)

    emotion_dict = {'ang': 0,
                        'hap': 1,
                        'exc': 2,
                        'sad': 3,
                        'fru': 4,
                        'fea': 5,
                        'sur': 6,
                        'neu': 7,
                        'dis': 8,
                        'xxx': 8,
                        'oth': 8}
    labels_df = pd.read_csv(labels_path)

    for sess in range(1,6):
        audio_vectors_path =os.path.join(data_dir,'audio_vectors_{}.pkl'.format(sess))
        audio_tokens_path=os.path.join(data_dir,'audio_tokens_{}.pkl'.format(sess))

        audio_vectors = pickle.load(open(audio_vectors_path, 'rb'))
        audio_tokens= pickle.load(open(audio_tokens_path,'rb'))
        for index, row in tqdm(labels_df[labels_df['wav_file'].str.contains('Ses0{}'.format(sess))].iterrows()):
                    wav_file_name = row['wav_file']
                    label = emotion_dict[row['emotion']]
                    y = audio_vectors[wav_file_name]

                    feature_list = [wav_file_name, label]  # wav_file, label
                    sig_mean = np.mean(abs(y))
                    feature_list.append(sig_mean)  # sig_mean
                    feature_list.append(np.std(y))  # sig_std

                    rmse = librosa.feature.rms(y + 0.0001)[0]
                    feature_list.append(np.mean(rmse))  # rmse_mean
                    feature_list.append(np.std(rmse))  # rmse_std

                    silence = 0
                    for e in rmse:
                        if e <= 0.4 * np.mean(rmse):
                            silence += 1
                    silence /= float(len(rmse))
                    feature_list.append(silence)  # silence

                    y_harmonic = librosa.effects.hpss(y)[0]
                    feature_list.append(np.mean(y_harmonic) * 1000)  # harmonic (scaled by 1000)

                    # based on the pitch detection algorithm mentioned here:
                    # http://access.feld.cvut.cz/view.php?cisloclanku=2009060001
                    cl = 0.45 * sig_mean
                    center_clipped = []
                    for s in y:
                        if s >= cl:
                            center_clipped.append(s - cl)
                        elif s <= -cl:
                            center_clipped.append(s + cl)
                        elif np.abs(s) < cl:
                            center_clipped.append(0)
                    auto_corrs = librosa.core.autocorrelate(np.array(center_clipped))
                    feature_list.append(1000 * np.max(auto_corrs)/len(auto_corrs))  # auto_corr_max (scaled by 1000)
                    feature_list.append(np.std(auto_corrs))  # auto_corr_std
                    feature_list.append(audio_tokens[wav_file_name])

                    df_features = df_features.append(pd.DataFrame(
                            feature_list, index=columns).transpose(),
                            ignore_index=True)
    df_features.to_csv(save_audio_feature_file, index=False)

# split data to train, vaild and test dataset
def split_data(audio_feature_path,save_split_dir):
    df = pd.read_csv(audio_feature_path)
    df = df[df['label'].isin([0, 1, 2, 3, 4, 5, 6, 7])]
    print(df.shape)

    #{'ang': 0,'hap': 1,'exc': 2,'sad': 3,'fru': 4,'fea': 5,'sur': 6,'neu': 7,'dis': 8,'xxx': 8,'oth': 8}
    # change 7 to 2
    df['label'] = df['label'].map({0: 0, 1: 1, 2: 1, 3: 2, 4: 2, 5: 3, 6: 4, 7: 5})
    print(df.head())

    df.to_csv('data/no_sample_df.csv')

    # oversample fear
    fear_df = df[df['label']==3]
    for i in range(30):
        df = df.append(fear_df)

    sur_df = df[df['label']==4]
    for i in range(10):
        df = df.append(sur_df)

    df.to_csv('data/modified_df.csv')

    emotion_dict = {'ang': 0,
                    'hap': 1,
                    'sad': 2,
                    'neu': 3,}

    # emotion_dict = {'ang': 0,
    #                 'hap': 1,
    #                 'exc': 2,
    #                 'sad': 3,
    #                 'fru': 4,
    #                 'fea': 5,
    #                 'sur': 6,
    #                 'neu': 7,
    #                 'xxx': 8,
    #                 'oth': 8}

    """scalar = MinMaxScaler()
    df[df.columns[2:]] = scalar.fit_transform(df[df.columns[2:]])
    print(df.head())"""

    x_train, x_test = train_test_split(df, test_size=0.20)
    x_vaild, x_test = train_test_split(x_test, test_size=0.50)

    os.makedirs(save_split_dir,exist_ok=True)
    x_train.to_csv(os.path.join(save_split_dir,'audio_train.csv'), index=False)
    x_vaild.to_csv(os.path.join(save_split_dir,'audio_vaild.csv'), index=False)
    x_test.to_csv(os.path.join(save_split_dir,'audio_test.csv'), index=False)
    print("The train, vaild and test dataset size is:", x_train.shape,x_vaild.shape, x_test.shape)

if __name__ == '__main__':
    base_path="/git/datasets/IEMOCAP_full_release"
    labels_path='data/df_iemocap.csv'
    data_dir = 'data/pre-processed/'
    audio_feature_path=os.path.join(data_dir,"audio_features.csv")
    save_split_dir="data/s2e"
    sr = 44100

    print('Part 1: Extract Audio Labels')
    extract_audio_labels(base_path,labels_path)
    print('Part 2: Build Audio Vectors')
    build_audio_vectors(base_path,labels_path,data_dir,sr)
    print('Part 3: Extract Audio Features')
    extract_audio_features(labels_path,data_dir)

    print('Part 4: Split Audio data')
    split_data(audio_feature_path,save_split_dir)


text:
from helpers.base_helper import TrainTestHelper, transform_train, transform_test
from utils import  get_channels_axis,save_roc_pr_curve_data, show_roc_pr_curve_data
from models.encoders_decoders import CAE_pytorch
from keras2pytorch_dataset import trainset_pytorch
import torch.utils.data as data
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torch.optim as optim
from sklearn.ensemble import IsolationForest
from transformations import RA, RA_IA, RA_IA_PR, Rotate4D
from models.wrn_pytorch import WideResNet
from models.resnet_pytorch import ResNet
from models.densenet_pytorch import DenseNet
import numpy as np
from keras2pytorch_dataset import trainset_pytorch, testset_pytorch
from loss_functions.e3outlier_oe_loss import E3outlierOELoss

def neg_entropy(score):
    if len(score.shape) != 1:
        score = np.squeeze(score)
    return score@np.log2(score)

class E3outliterOEHelper(TrainTestHelper):
    def __init__(self, n_channels,OP_TYPE,BACKEND,SCORE_MODE, *args, **kwargs):
        super(E3outliterOEHelper, self).__init__(*args, **kwargs)
        self.method_tag = "e3outlier_oe"

        self.n_channels = n_channels
        self.SCORE_MODE = SCORE_MODE
        self.OP_TYPE = OP_TYPE
        if OP_TYPE == 'RA':
            transformer = RA(8, 8)
        elif OP_TYPE == 'RA+IA':
            transformer = RA_IA(8, 8, 12)
        elif OP_TYPE == 'RA+IA+PR':
            transformer = RA_IA_PR(8, 8, 12, 23, 2)
        elif OP_TYPE == 'Rotate4D':
            transformer = Rotate4D()
        else:
            raise NotImplementedError
        print(transformer.n_transforms)
        self.transformer = transformer

        self.BACKEND = BACKEND
        if BACKEND == 'wrn':
            n, k = (10, 4)
            model = WideResNet(num_classes=transformer.n_transforms, depth=n, widen_factor=k, in_channel=n_channels)
        elif BACKEND == 'resnet20':
            n = 20
            model = ResNet(num_classes=transformer.n_transforms, depth=n, in_channels=n_channels)
        elif BACKEND == 'resnet50':
            n = 50
            model = ResNet(num_classes=transformer.n_transforms, depth=n, in_channels=n_channels)
        elif BACKEND == 'densenet22':
            n = 22
            model = DenseNet(num_classes=transformer.n_transforms, depth=n, in_channels=n_channels)
        elif BACKEND == 'densenet40':
            n = 40
            model = DenseNet(num_classes=transformer.n_transforms, depth=n, in_channels=n_channels)
        else:
            raise NotImplementedError('Unimplemented backend: {}'.format(BACKEND))
        print('Using backend: {} ({})'.format(type(model).__name__, BACKEND))

        self.model = model.cuda()
        self.batch_size = 128

        cudnn.benchmark = True
        self.criterion = E3outlierOELoss(lamb=0.1)

        # use adam always
        if self.dataset_name in ['mnist', 'fashion-mnist']:
            self.optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9, weight_decay=0.0005)
        else:
            self.optimizer = optim.Adam(model.parameters(), eps=1e-7, weight_decay=0.0005)
        self.epochs = int(np.ceil(250 / transformer.n_transforms))

    def transform_traindata(self, x_train, y_train):
        transformations_inds = np.tile(np.arange(self.transformer.n_transforms), len(x_train))
        if y_train is not None:
            y_train = np.repeat(y_train, self.transformer.n_transforms, axis=0)
        self.x_train_task_transformed = self.transformer.transform_batch(
            np.repeat(x_train, self.transformer.n_transforms, axis=0), transformations_inds)
        self.trainset = trainset_pytorch(train_data=self.x_train_task_transformed,
                                         train_labels=transformations_inds,aux_labels=y_train, transform=transform_train)
        self.is_y_train = y_train is not None
        self.trainloader = data.DataLoader(self.trainset, batch_size=self.batch_size, shuffle=True)

    def transform_testdata(self, x_test, y_test):
        transformations_inds = np.tile(np.arange(self.transformer.n_transforms), len(x_test))
        self.x_test_task_transformed = self.transformer.transform_batch(
            np.repeat(x_test, self.transformer.n_transforms, axis=0), transformations_inds)
        self.testset = trainset_pytorch(train_data=self.x_test_task_transformed,
                                         train_labels=transformations_inds, transform=transform_test)
        self.y_test = y_test
        #self.testloader = data.DataLoader(self.testset, batch_size=self.batch_size, shuffle=True)

    def train_step(self, x, y=None):
        if self.is_y_train:
            inputs, targets, aux_labels = torch.autograd.Variable(x.cuda()), torch.autograd.Variable(y[0].cuda()), \
                                          torch.autograd.Variable(y[1].cuda())
        else:
            inputs, targets, aux_labels = torch.autograd.Variable(x.cuda()), torch.autograd.Variable(y.cuda()), None
        outputs, _ = self.model(inputs)
        loss = self.criterion(outputs, targets, aux_labels)

        self.losses.update(loss.data.cpu(), inputs.size(0))

        # compute gradient and do SGD step
        self.optimizer.zero_grad()
        loss.backward()
        self.optimizer.step()

    def get_features_pytorch(self):
        self.model.eval()
        features = []
        y_test = []
        for inputs,labels in self.testloader:
            inputs = torch.autograd.Variable(inputs.cuda())
            _, rep = self.model(inputs)
            features.append(rep.data.cpu())
            y_test.append(labels.data.cpu())
        features = torch.cat(features, dim=0)
        y_test = torch.cat(y_test, dim=0)
        return features.numpy(), y_test.numpy()

    def compute_softmax(self, testloader):
        self.model.eval()
        res = torch.Tensor()
        for batch_idx, (inputs) in enumerate(testloader):
            inputs = torch.autograd.Variable(inputs.cuda())
            outputs, _ = self.model(inputs)
            res = torch.cat((res, outputs.data.cpu()), dim=0)
        return nn.Softmax(dim=1)(res).numpy()

    def compute_scores(self):
        preds = np.zeros((len(self.y_test), self.transformer.n_transforms))
        original_preds = np.zeros((self.transformer.n_transforms, len(self.y_test), self.transformer.n_transforms))
        for t in range(self.transformer.n_transforms):
            idx = np.squeeze(np.array([range(len(self.y_test))]) * self.transformer.n_transforms + t)
            test_set = testset_pytorch(test_data=self.x_test_task_transformed[idx, :],
                                       transform=transform_test)

            original_preds[t, :, :] = self.compute_softmax(data.DataLoader(test_set,
                                                                           batch_size=self.batch_size, shuffle=False))
            if self.SCORE_MODE == 'pl_mean':
                preds[:, t] = original_preds[t, :, :][:, t]
            elif self.SCORE_MODE == 'max_mean':
                preds[:, t] = np.max(original_preds[t, :, :], axis=1)
            elif self.SCORE_MODE == 'neg_entropy':
                for s in range(len(self.y_test)):
                    preds[s, t] = neg_entropy(original_preds[t, s, :])
            else:
                raise NotImplementedError
        scores = preds.mean(axis=-1)
        return scores, self.y_test

    def test(self, is_show=True):
        scores, y_test = self.compute_scores()
        if is_show:
            show_roc_pr_curve_data(scores, y_test)
        else:
            res_file_path = self.get_result_file_path()
            save_roc_pr_curve_data(scores, y_test, res_file_path)

max_stars_repo_name: MPCAICDM/MPCA

max_issues_repo_name: MPCAICDM/MPCA

max_forks_repo_name: MPCAICDM/MPCA


text:
"""Module for the base BlameInteractionDegreeDatabase class."""
import typing as tp
from enum import Enum
from pathlib import Path

import numpy as np
import pandas as pd

from varats.data.cache_helper import build_cached_report_table
from varats.data.databases.evaluationdatabase import EvaluationDatabase
from varats.data.reports.blame_report import (
    BlameReport,
    generate_author_degree_tuples,
    generate_avg_time_distribution_tuples,
    generate_max_time_distribution_tuples,
    generate_lib_dependent_degrees,
)
from varats.jupyterhelper.file import load_blame_report
from varats.mapping.commit_map import CommitMap
from varats.paper.case_study import CaseStudy
from varats.paper_mgmt.case_study import get_case_study_file_name_filter
from varats.report.report import ReportFilename
from varats.revision.revisions import (
    get_failed_revisions_files,
    get_processed_revisions_files,
)
from varats.utils.git_util import create_commit_lookup_helper

MAX_TIME_BUCKET_SIZE = 1
AVG_TIME_BUCKET_SIZE = 1

class DegreeType(Enum):
    """Degree types of blame interaction data."""
    value: str  # pylint: disable=invalid-name

    INTERACTION = "interaction"
    AUTHOR = "author"
    MAX_TIME = "max_time"
    AVG_TIME = "avg_time"

def _split_tuple_values_in_lists_tuple(
    list_of_occurrences: tp.List[tp.Tuple[int, int]]
) -> tp.Tuple[tp.List[int], tp.List[int]]:
    """
    Maps the first and second value of the passed tuples to two separate lists
    respectively and returns them as a tuple.

    Args:
        list_of_occurrences: list of tuples that are going to be separated

    Returns:
        a tuple of lists containing the first and second values of the passed
        tuples
    """

    degrees: tp.List[int] = []
    amounts: tp.List[int] = []

    if not list_of_occurrences:
        return degrees, amounts

    degrees_untyped, amounts_untyped = map(list, zip(*list_of_occurrences))
    degrees = tp.cast(tp.List[int], degrees_untyped)
    amounts = tp.cast(tp.List[int], amounts_untyped)

    return degrees, amounts

class BlameInteractionDegreeDatabase(
    EvaluationDatabase,
    cache_id="blame_interaction_degree_data",
    columns=[
        "degree_type", "base_lib", "inter_lib", "degree", "amount", "fraction"
    ]
):
    """Provides access to blame interaction degree data."""

    @classmethod
    def _load_dataframe(
        cls, project_name: str, commit_map: CommitMap,
        case_study: tp.Optional[CaseStudy], **kwargs: tp.Any
    ) -> pd.DataFrame:
        commit_lookup = create_commit_lookup_helper(project_name)

        def create_dataframe_layout() -> pd.DataFrame:
            df_layout = pd.DataFrame(columns=cls.COLUMNS)
            df_layout.base_lib = df_layout.base_lib.astype('str')
            df_layout.inter_lib = df_layout.inter_lib.astype('str')
            df_layout.degree = df_layout.degree.astype('int64')
            df_layout.amount = df_layout.amount.astype('int64')
            df_layout.fraction = df_layout.fraction.astype('int64')

            return df_layout

        def create_data_frame_for_report(
            report_path: Path
        ) -> tp.Tuple[pd.DataFrame, str, str]:
            report = load_blame_report(report_path)

            categorised_degree_occurrences = generate_lib_dependent_degrees(
                report
            )

            def calc_total_amounts() -> int:
                total = 0

                for _, lib_dict in categorised_degree_occurrences.items():
                    for _, tuple_list in lib_dict.items():
                        for degree_amount_tuple in tuple_list:
                            total += degree_amount_tuple[1]
                return total

            total_amounts_of_all_libs = calc_total_amounts()

            list_of_author_degree_occurrences = generate_author_degree_tuples(
                report, commit_lookup
            )
            author_degrees, author_amounts = _split_tuple_values_in_lists_tuple(
                list_of_author_degree_occurrences
            )
            author_total = sum(author_amounts)

            list_of_max_time_deltas = generate_max_time_distribution_tuples(
                report, commit_lookup, MAX_TIME_BUCKET_SIZE
            )
            (max_time_buckets, max_time_amounts
            ) = _split_tuple_values_in_lists_tuple(list_of_max_time_deltas)
            total_max_time_amounts = sum(max_time_amounts)

            list_of_avg_time_deltas = generate_avg_time_distribution_tuples(
                report, commit_lookup, AVG_TIME_BUCKET_SIZE
            )
            (avg_time_buckets, avg_time_amounts
            ) = _split_tuple_values_in_lists_tuple(list_of_avg_time_deltas)
            total_avg_time_amounts = sum(avg_time_amounts)

            def build_dataframe_row(
                degree_type: DegreeType,
                degree: int,
                amount: int,
                total_amount: int,
                base_library: tp.Optional[str] = None,
                inter_library: tp.Optional[str] = None
            ) -> tp.Dict[str, tp.Any]:

                data_dict: tp.Dict[str, tp.Any] = {
                    'revision': report.head_commit.hash,
                    'time_id': commit_map.short_time_id(report.head_commit),
                    'degree_type': degree_type.value,
                    'base_lib': base_library,
                    'inter_lib': inter_library,
                    'degree': degree,
                    'amount': amount,
                    'fraction': np.divide(amount, total_amount)
                }
                return data_dict

            result_data_dicts: tp.List[tp.Dict[str, tp.Any]] = []

            # Append interaction rows
            for base_lib_name, inter_lib_dict \
                    in categorised_degree_occurrences.items():

                for inter_lib_name, list_of_lib_degree_amount_tuples in \
                        inter_lib_dict.items():

                    (inter_degrees,
                     inter_amounts) = _split_tuple_values_in_lists_tuple(
                         list_of_lib_degree_amount_tuples
                     )

                    for i, _ in enumerate(inter_degrees):
                        degree = inter_degrees[i]
                        lib_amount = inter_amounts[i]

                        interaction_data_dict = build_dataframe_row(
                            degree_type=DegreeType.INTERACTION,
                            degree=degree,
                            amount=lib_amount,
                            total_amount=total_amounts_of_all_libs,
                            base_library=base_lib_name,
                            inter_library=inter_lib_name,
                        )
                        result_data_dicts.append(interaction_data_dict)

            def append_rows_of_degree_type(
                degree_type: DegreeType,
                degrees: tp.List[int],
                amounts: tp.List[int],
                sum_amounts: int,
            ) -> None:
                for k, _ in enumerate(degrees):
                    data_dict = build_dataframe_row(
                        degree_type=degree_type,
                        degree=degrees[k],
                        amount=amounts[k],
                        total_amount=sum_amounts
                    )
                    result_data_dicts.append(data_dict)

            # Append author rows
            append_rows_of_degree_type(
                degree_type=DegreeType.AUTHOR,
                degrees=author_degrees,
                amounts=author_amounts,
                sum_amounts=author_total
            )

            # Append max_time rows
            append_rows_of_degree_type(
                degree_type=DegreeType.MAX_TIME,
                degrees=max_time_buckets,
                amounts=max_time_amounts,
                sum_amounts=total_max_time_amounts
            )

            # Append avg_time rows
            append_rows_of_degree_type(
                degree_type=DegreeType.AVG_TIME,
                degrees=avg_time_buckets,
                amounts=avg_time_amounts,
                sum_amounts=total_avg_time_amounts
            )

            return pd.DataFrame(result_data_dicts
                               ), report.head_commit.hash, str(
                                   report_path.stat().st_mtime_ns
                               )

        report_files = get_processed_revisions_files(
            project_name, BlameReport,
            get_case_study_file_name_filter(case_study)
        )

        failed_report_files = get_failed_revisions_files(
            project_name, BlameReport,
            get_case_study_file_name_filter(case_study)
        )

        # cls.CACHE_ID is set by superclass
        # pylint: disable=E1101
        data_frame = build_cached_report_table(
            cls.CACHE_ID, project_name, report_files, failed_report_files,
            create_dataframe_layout, create_data_frame_for_report,
            lambda path: ReportFilename(path).commit_hash.hash,
            lambda path: str(path.stat().st_mtime_ns),
            lambda a, b: int(a) > int(b)
        )

        return data_frame

max_stars_repo_name: Kaufi-Jonas/VaRA-Tool-Suite

max_issues_repo_name: Kaufi-Jonas/VaRA-Tool-Suite

max_forks_repo_name: Kaufi-Jonas/VaRA-Tool-Suite


text:
import os
from types import resolve_bases
import numpy as np
import pandas as pd
import vectorbt as vbt
import datetime as dt
from dataclasses import dataclass, fields
from dateutil.tz import tzlocal, gettz
from dateutil.tz.tz import tzfile

from trader.common.logging_helper import setup_logging

logging = setup_logging(module_name='data')

from pandas.core.base import PandasObject
from arctic import Arctic, TICK_STORE, VERSION_STORE
from arctic.date import DateRange, string_to_daterange
from arctic.tickstore.tickstore import TickStore
from arctic.store.version_store import VersionStore
from arctic.exceptions import NoDataFoundException, OverlappingDataException
from typing import Tuple, List, Optional, Dict, TypeVar, Generic, Type, Union, cast, Set
from durations import Duration
from exchange_calendars import ExchangeCalendar
from pandas import DatetimeIndex
from ib_insync.contract import Contract, ContractDetails
from trader.common.helpers import dateify, daily_close, daily_open, market_hours, get_contract_from_csv, symbol_to_contract
from trader.data.contract_metadata import ContractMetadata

# todo make sure all writes are monotonically ordered, as TickStore assumes this
# right now, I don't think this is the case

@dataclass(eq=True, frozen=True)
class SecurityDefinition:
    symbol: str
    exchange: str
    conId: int
    secType: str
    primaryExchange: str
    currency: str
    minTick: float
    orderTypes: str
    validExchanges: str
    priceMagnifier: float
    longName: str
    category: str
    subcategory: str
    tradingHours: str
    timeZoneId: str
    liquidHours: str
    stockType: str
    bondType: str
    couponType: str
    callable: bool
    putable: bool
    coupon: int
    convertable: bool
    maturity: str
    issueDate: str
    nextOptionDate: str
    nextOptionPartial: bool
    nextOptionType: str
    marketRuleIds: str
    company_name: str = ''
    industry: str = ''

    @staticmethod
    def from_contract_details(d: ContractDetails):
        return SecurityDefinition(
            symbol=d.contract.symbol if d.contract else '',
            exchange=d.contract.exchange if d.contract else '',
            conId=d.contract.conId if d.contract else -1,
            secType=d.contract.secIdType if d.contract else '',
            primaryExchange=d.contract.primaryExchange if d.contract else '',
            currency=d.contract.currency if d.contract else '',
            minTick=d.minTick,
            orderTypes=d.orderTypes,
            validExchanges=d.validExchanges,
            priceMagnifier=d.priceMagnifier,
            longName=d.longName,
            category=d.category,
            subcategory=d.subcategory,
            tradingHours=d.tradingHours,
            timeZoneId=d.timeZoneId,
            liquidHours=d.liquidHours,
            stockType=d.stockType,
            bondType=d.bondType,
            couponType=d.couponType,
            callable=d.callable,
            putable=d.putable,
            coupon=d.coupon,
            convertable=d.convertible,
            maturity=d.maturity,
            issueDate=d.issueDate,
            nextOptionDate=d.nextOptionDate,
            nextOptionPartial=d.nextOptionPartial,
            nextOptionType=d.nextOptionType,
            marketRuleIds=d.marketRuleIds,
            company_name=d.longName,
            industry=d.industry,
        )

class Data():
    def __init__(self,
                 arctic_server_address: str,
                 arctic_library: str,
                 lib_type: str,
                 timezone: str = 'America/New_York'):
        self.arctic_server_address = arctic_server_address
        self.arctic_library = arctic_library
        self.store = Arctic(self.arctic_server_address)
        self.store.initialize_library(self.arctic_library, lib_type=lib_type)
        # deliberately duck-typed because VersionStore and TickStore share no heirarchy
        self.library = self.store[self.arctic_library]
        self.zone: tzfile = gettz(timezone)  # type: ignore

    # arctic stupidly returns the read data in the users local timezone
    # todo:// patch this up properly in the arctic source
    def _fix_df_timezone(self, data_frame: pd.DataFrame):
        data_frame.index = data_frame.index.tz_convert(self.zone)  # type: ignore
        return data_frame

    def _to_symbol(self, contract: Union[Contract, SecurityDefinition, int]) -> str:
        if type(contract) == int:
            return str(contract)
        elif type(contract) is Contract:
            return str(cast(Contract, contract).conId)
        elif type(contract) is SecurityDefinition:
            definition = cast(SecurityDefinition, contract)
            return str(definition.conId)
        else:
            raise ValueError('cast not supported')

    def get_date_range_from_datetime(self, day: dt.datetime):
        date_time = dateify(day)
        return DateRange(start=date_time, end=date_time + dt.timedelta(days=1))

    def read(self,
             contract: Union[Contract, SecurityDefinition, int],
             date_range: DateRange = DateRange(dt.datetime(1970, 1, 1), dt.datetime.now())) -> pd.DataFrame:
        try:
            return self._fix_df_timezone(self.library.read(self._to_symbol(contract), date_range))
        except NoDataFoundException:
            return pd.DataFrame()

    def write(self,
              contract: Union[Contract, SecurityDefinition, int],
              data_frame: pd.DataFrame):
        self.library.write(self._to_symbol(contract), data_frame)

    def delete(self,
               contract: Union[Contract, SecurityDefinition, int]):
        self.library.delete(self._to_symbol(contract))

    def list_symbols(self) -> List[str]:
        return self.library.list_symbols()

    def arctic_list_libraries(self) -> List[str]:
        return self.store.list_libraries(1)

T = TypeVar('T')

class DictData(Data, Generic[T]):
    def __init__(self,
                 arctic_server_address: str,
                 arctic_library: str):
        if not arctic_library:
            raise ValueError('arctic_library must be supplied')
        super().__init__(arctic_server_address=arctic_server_address,
                         arctic_library=arctic_library,
                         lib_type=VERSION_STORE)

    def read(self,
             contract: Union[Contract, SecurityDefinition, int],
             date_range: DateRange = DateRange(dt.datetime(1970, 1, 1), dt.datetime.now())) -> Optional[T]:
        try:
            return self.library.read(self._to_symbol(contract)).data
        except NoDataFoundException:
            return None

    def write(self, contract: Union[Contract, SecurityDefinition, int], data: T) -> None:
        logging.info('DictData writing contract {}'.format(contract))
        self.library.write(self._to_symbol(contract), data, prune_previous_version=True)

    def delete(self, contract: Union[Contract, SecurityDefinition, int]) -> None:
        logging.info('DictData deleting contract {}'.format(contract))
        self.library.delete(self._to_symbol(contract))

class TickData(Data):
    def __init__(self,
                 arctic_server_address: str,
                 arctic_library: str):
        super().__init__(arctic_server_address=arctic_server_address,
                         arctic_library=arctic_library,
                         lib_type=TICK_STORE)
        self.metadata = DictData[ContractMetadata](arctic_server_address=arctic_server_address,
                                                   arctic_library=arctic_library + 'Metadata')
        PandasObject.daily_open = daily_open  # type: ignore
        PandasObject.daily_close = daily_close  # type: ignore
        PandasObject.market_hours = market_hours  # type: ignore
        logging.info('initializing TickData {} {}'.format(arctic_server_address, arctic_library))

    def get_schema(self) -> Set[str]:
        return {'date', 'open', 'high', 'low', 'close', 'volume', 'average', 'bar_count', 'bar_size'}

    def date_summary(self, contract: Union[Contract, SecurityDefinition, int]) -> Tuple[dt.datetime, dt.datetime]:
        if type(contract) is int:
            contract = Contract(conId=cast(int, contract))
        contract = cast(Contract, contract)
        min_date = dateify(self.library.min_date(symbol=self._to_symbol(contract)), timezone=self.zone)
        max_date = dateify(self.library.max_date(symbol=self._to_symbol(contract)), timezone=self.zone)
        return (min_date, max_date)

    def summary(
        self,
        contract: Union[Contract, SecurityDefinition, int]
    ) -> Tuple[dt.datetime, dt.datetime, pd.Series, pd.Series]:
        if type(contract) is int:
            contract = Contract(conId=cast(int, contract))

        contract = cast(Contract, contract)
        min_date = self.library.min_date(symbol=self._to_symbol(contract))
        max_date = self.library.max_date(symbol=self._to_symbol(contract))
        min_date_range = DateRange(min_date, min_date)
        max_date_range = DateRange(max_date, max_date + dt.timedelta(days=1))

        return (dateify(min_date, self.zone),
                dateify(max_date, self.zone),
                self.read(contract, date_range=min_date_range).iloc[0],
                self.read(contract, date_range=max_date_range).iloc[-1])

    def read_metadata(self, contract: Union[Contract, SecurityDefinition, int]) -> ContractMetadata:
        metadata = self.metadata.read(contract)
        if not metadata:
            return ContractMetadata(contract=Contract(conId=int(self._to_symbol(contract))),
                                    history_no_data_dates=[], history_overlapping_data_dates=[])
        else:
            return metadata

    def write_metadata(self, contract: Contract, metadata: ContractMetadata):
        self.metadata.write(contract, metadata)

    def write_resolve_overlap(
        self,
        contract: Union[Contract, SecurityDefinition, int],
        data_frame: pd.DataFrame
    ):
        try:
            super().write(contract, data_frame)
        except OverlappingDataException:
            # grab all the existing data
            # merge it with the data_frame
            # then rewrite it
            logging.debug('OverlappingDataException, re-writing dataframe')
            existing_data = self.read(contract)
            temp_df = existing_data.append(data_frame)
            result = cast(pd.DataFrame, temp_df[~temp_df.index.duplicated(keep='first')])
            result.sort_index(inplace=True)
            self.delete(contract=contract)

            # todo this probably shouldn't go here -- there's a bug upstream
            # somewhere which kicks out a 'Timestamp' object has no attribute 'astype' exception
            try:
                result.index = pd.to_datetime(result.index)  # type: ignore
            except ValueError as ve:
                logging.debug('pd.to_datetime failed with {}'.format(ve))
            self.write(contract=contract, data_frame=result)  # type: ignore

    def read(self,
             contract: Union[Contract, SecurityDefinition, int],
             date_range: DateRange = DateRange(dt.datetime(1970, 1, 1), dt.datetime.now())) -> pd.DataFrame:
        return self.get_data(contract, date_range=date_range)

    def get_date_range(self,
                       period: Optional[str] = None,
                       date_range: Optional[DateRange] = None) -> DateRange:
        if not period and not date_range:
            raise ValueError('period or date_range must be set')

        actual_date_range: DateRange
        if period:
            start_date = dt.datetime.now() - dt.timedelta(seconds=Duration(period).seconds)
            end_date = dt.datetime.now()
            actual_date_range = DateRange(start=start_date, end=end_date)
        elif date_range:
            actual_date_range = date_range
        else:
            raise ValueError('cannot get here')
        return actual_date_range

    # https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases
    def get_data(self,
                 contract: Union[Contract, SecurityDefinition, int],
                 pd_offset: Optional[str] = None,
                 period: Optional[str] = None,
                 date_range: Optional[DateRange] = None) -> pd.DataFrame:
        actual_date_range: DateRange
        if period or date_range:
            actual_date_range = self.get_date_range(period, date_range)
        else:
            actual_date_range = DateRange(self.library.min_date(symbol=self._to_symbol(contract)),
                                          self.library.max_date(symbol=self._to_symbol(contract)))

        try:
            df = self._fix_df_timezone(self.library.read(symbol=self._to_symbol(contract),
                                                         date_range=actual_date_range))
        except NoDataFoundException:
            return pd.DataFrame()

        if pd_offset:
            return df.resample(pd_offset).last()
        else:
            return df

    def history(self,
                contract: Union[Contract, SecurityDefinition, int],
                pd_offset: Optional[str] = None,
                period: Optional[str] = None,
                date_range: Optional[DateRange] = None) -> pd.DataFrame:
        return self.get_data(contract, pd_offset, period, date_range)

    def date_exists(self,
                    contract: Union[Contract, SecurityDefinition, int],
                    date_time: dt.datetime) -> bool:
        date_range = DateRange(date_time, date_time + dt.timedelta(days=1))
        try:
            result = self.get_data(contract, date_range=date_range)
            return len(result) > 0
        except NoDataFoundException:
            return False

    def missing(self,
                contract: Union[Contract, SecurityDefinition, int],
                exchange_calendar: ExchangeCalendar,
                pd_offset: Optional[str] = None,
                period: Optional[str] = None,
                date_range: Optional[DateRange] = None) -> List[DateRange]:
        if not pd_offset and not period and not date_range:
            date_range = DateRange(dateify(self.library.min_date(symbol=self._to_symbol(contract))),
                                   dateify() - dt.timedelta(days=1))

        df = self.get_data(contract, pd_offset, period, date_range)

        no_data_dates: List[dt.date] = []
        contract_metadata = self.metadata.read(contract)
        if contract_metadata:
            no_data_dates = [d.date() for d in contract_metadata.history_no_data_dates]

        dates: List[dt.date] = []
        sessions = exchange_calendar.all_sessions.date  # type: ignore
        # no data case
        if len(df) == 0:
            dates = no_data_dates
        else:
            # make sure we have all the trading days
            dates = df.resample('D').first().index.date
            dates = list(dates) + no_data_dates

        # filter
        actual_range = self.get_date_range(period, date_range)
        dates = [d for d in dates if d >= actual_range.start.date() and d <= actual_range.end.date()]
        sessions = [d for d in sessions if d >= actual_range.start.date() and d <= actual_range.end.date()]

        ranges: List[DateRange] = []
        start_date = None
        end_date = None
        for d in sessions:
            if d not in dates:
                if not start_date:
                    start_date = d
                end_date = d
            else:
                if start_date and end_date:
                    ranges.append(DateRange(start=start_date, end=end_date))
                    start_date = None
                    end_date = None
        if start_date and end_date:
            ranges.append(DateRange(start=start_date, end=end_date))

        return ranges

    def dump(self, csv_file_location: str):
        for symbol in self.library.list_symbols():
            csv_filename = csv_file_location + '/' + symbol + '.csv'
            logging.info('writing {} to {}'.format(symbol, csv_filename))
            data_frame = self.history(symbol_to_contract(symbol))
            data_frame.index.name = 'date'
            data_frame.to_csv(csv_file_location + '/' + symbol + '.csv', header=True)


text:
import os
from functools import lru_cache
import time
import requests
from datetime import datetime, timedelta

import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_table
from dash.dependencies import Input, Output, State, ClientsideFunction
import dash_bootstrap_components as dbc
import plotly.graph_objects as go
import plotly.express as px
import numpy as np
import pandas as pd
from scipy.optimize import curve_fit

from helpers import (
    filter_province,
    generate_table,
    generate_plot,
    generate_map,
    get_data,
    placeholder_graph,
    INIT_COUNTRY,
    PROVINCE_NAME
)

app = dash.Dash(
    __name__,
    external_stylesheets=[dbc.themes.BOOTSTRAP],
    meta_tags=[dict(name="viewport", content="width=device-width, initial-scale=1")]
)
server = app.server

# Get data
data, province_totals = get_data(datetime.now().strftime('%H'), INIT_COUNTRY)
initial_start = (datetime.now() - timedelta(weeks=8)).strftime('%Y-%m-%d')

def init_vis(province, start_date, project, country):

    timer_start = time.time()
    data_filt, province_totals = filter_province(datetime.now().strftime('%H'), country, filt=province)
    print(f'\nGet data: {time.time() - timer_start} seconds')

    timer_start = time.time()
    table = generate_table(data_filt, country)
    print(f'Generate table: {time.time() - timer_start} seconds')

    timer_start = time.time()
    case_graphs, sig_fit = generate_plot(data_filt, start=start_date, project=project)
    death_graphs, _ = generate_plot(data_filt, start=start_date, project=project, metric='Deaths', sig_fit=sig_fit)
    print(f'Generate charts: {time.time() - timer_start} seconds')

    return case_graphs, death_graphs, table, province_totals.to_dict('records')

# Layout
heading_elem = html.H2(f'COVID-19: {INIT_COUNTRY}', className='my-3', id='heading')

country_elem = dbc.Col(
    [
        dbc.RadioItems(
            id='country-select',
            options=[
                dict(label='Canada', value='Canada'),
                dict(label='US', value='US'),
            ],
            value=INIT_COUNTRY,
            inline=True
        )
    ],
    className='text-center font-weight-bold p-3'
)

map_elem = dbc.Col(
    [
        generate_map(
            tuple(province_totals.Province.tolist()),
            tuple(province_totals['Total Cases'].tolist()),
            INIT_COUNTRY
        ),
    ],
    id='map',
    md=dict(offset=1, size=10),
    lg=dict(offset=2, size=8),
)

dropdown_elem = dcc.Dropdown(
    id='province-select',
    options=[dict(label=p, value=p) for p in province_totals.Province.values],
    value=INIT_COUNTRY,
    clearable=False,
)

datepicker_elem = dcc.DatePickerSingle(
    id='time-select',
    min_date_allowed=data.index.min(),
    max_date_allowed=data.index.max() + timedelta(days=1),
    date=initial_start,
    initial_visible_month=datetime.now() - timedelta(weeks=4),
)

radio_elem = dbc.RadioItems(
    id='project-select',
    options=[
        dict(label='1 day', value=1),
        dict(label='1 week', value=7),
        dict(label='2 weeks', value=14),
        dict(label='3 weeks', value=21),
    ],
    value=1,
    inline=True
)

input_elem = html.Div([
    dbc.Form(
        [
            dbc.FormGroup(
                [
                    dbc.Label(f'Select {PROVINCE_NAME[INIT_COUNTRY].lower()}:'),
                    dbc.Col([dropdown_elem], width='True', id='province-select-div'),
                ],
                className='m-2',
            )
        ]
    ),
    dbc.Form(
        [
            dbc.FormGroup(
                [
                    dbc.Label('Show from:', className='mr-2'),
                    datepicker_elem,
                ],
                className='m-2',
            ),
            dbc.FormGroup(
                [
                    dbc.Label('Extrapolate growth:', className='mr-2'),
                    radio_elem,
                ],
                className='m-2',
            ),
        ],
        inline=True,
        className='mb-3'
    )
])

case_graphs, death_graphs, table, _ = init_vis(INIT_COUNTRY, initial_start, 1, INIT_COUNTRY)

cases_elem = dbc.Row(
    [
        dbc.Col(case_graphs[0], id='total-cases-div', sm=dict(size=12), lg=dict(size=6)),
        dbc.Col(case_graphs[1], id='new-cases-div', sm=dict(size=12), lg=dict(size=6))
    ],
    className='p-2'
)

deaths_elem = dbc.Row(
    [
        dbc.Col(death_graphs[0], id='total-deaths-div', sm=dict(size=12), lg=dict(size=6)),
        dbc.Col(death_graphs[1], id='new-deaths-div', sm=dict(size=12), lg=dict(size=6))
    ],
    className='p-2'
)

table_elem = html.Details(
    [
        html.Summary('Expand for tabular data'),
        html.Div(table, id='table', className='p-2 mx-3'),
    ],
    className='py-4',
)

app.layout = html.Div(
    children=[
        heading_elem,
        country_elem,
        map_elem,
        input_elem,
        cases_elem,
        deaths_elem,
        table_elem,
        dcc.Store('map-store'),
    ],
    className='container'
)

# Callbacks
@app.callback(
    [
        Output('total-cases-div', 'children'),
        Output('new-cases-div', 'children'),
        Output('total-deaths-div', 'children'),
        Output('new-deaths-div', 'children'),
        Output('table', 'children'),
        Output('map-store', 'data'),
    ],
    [
        Input('province-select', 'value'),
    ],
    [
        State('time-select', 'date'),
        State('project-select', 'value'),
        State('country-select', 'value')
    ]
)
def update_vis(province, start_date, project, country):
    case_graphs, death_graphs, table, map_data = init_vis(province, start_date, project, country)

    return (
        case_graphs[0],
        case_graphs[1],
        death_graphs[0],
        death_graphs[1],
        table,
        map_data
    )

@app.callback(
    [
        Output('map', 'children'),
        Output('province-select-div', 'children'),
        Output('heading', 'children'),
    ],
    [Input('country-select', 'value')]
)
def update_country(country):
    timer_start = time.time()
    data_filt, province_totals = filter_province(datetime.now().strftime('%H'), country)
    print(f'\nGet data: {time.time() - timer_start} seconds')

    map_graph = generate_map(
        tuple(province_totals.Province.tolist()),
        tuple(province_totals['Total Cases'].tolist()),
        country
    )

    dropdown_elem = dcc.Dropdown(
        id='province-select',
        options=[dict(label=p, value=p) for p in province_totals.Province.values],
        value=country,
        clearable=False,
    )

    return [map_graph], [dropdown_elem], f'COVID-19: {country}'

app.clientside_callback(
    ClientsideFunction(namespace='clientside', function_name='update_map'),
    Output('map-graph', 'figure'),
    [Input('map-store', 'data')],
    [State('map-graph', 'figure')]
)

app.clientside_callback(
    ClientsideFunction(namespace='clientside', function_name='update_dropdown'),
    Output('province-select', 'value'),
    [Input('map-graph', 'clickData')],
    [State('province-select', 'value')]
)

for id_name in ['total-cases', 'new-cases', 'total-deaths', 'new-deaths']:
    app.clientside_callback(
        ClientsideFunction(namespace='clientside', function_name='update_range'),
        Output(id_name, 'figure'),
        [Input('project-select', 'value'), Input('time-select', 'date')],
        [State(id_name, 'figure')]
    )

if __name__ == '__main__':
    app.run_server(debug=True, host='0.0.0.0')