from __future__ import division
# Copyright (c) 2012-2014 Ricardo Andrade, Alan Saul
# Licensed under the BSD 3-clause license (see LICENSE.txt)

import numpy as np
from scipy import stats,special
import scipy as sp
from . import link_functions
from .likelihood import Likelihood
from math import factorial
from scipy.special import gamma,hyp1f1,loggamma,gammaincc,logsumexp, erfinv
from scipy.integrate import quad

class Poisson(Likelihood):
    """
    Poisson likelihood

    .. math::
        p(y_{i}|\\lambda(f_{i})) = \\frac{\\lambda(f_{i})^{y_{i}}}{y_{i}!}e^{-\\lambda(f_{i})}

    .. Note::
        Y is expected to take values in {0,1,2,...}
    """
    def __init__(self, gp_link=None, qp=False):
        if gp_link is None:
            gp_link = link_functions.Square()
        self.qp=qp
        super(Poisson, self).__init__(gp_link, name='Poisson')

    def _conditional_mean(self, f):
        """
        the expected value of y given a value of f
        """
        return self.gp_link.transf(f)

    def pdf_link(self, link_f, y, Y_metadata=None):
        """
        Likelihood function given link(f)

        .. math::
            p(y_{i}|\\lambda(f_{i})) = \\frac{\\lambda(f_{i})^{y_{i}}}{y_{i}!}e^{-\\lambda(f_{i})}

        :param link_f: latent variables link(f)
        :type link_f: Nx1 array
        :param y: data
        :type y: Nx1 array
        :param Y_metadata: Y_metadata which is not used in poisson distribution
        :returns: likelihood evaluated for this point
        :rtype: float
        """
        assert np.atleast_1d(link_f).shape == np.atleast_1d(y).shape
        return np.exp(self.logpdf_link(link_f, y, Y_metadata))
        # return np.prod(stats.poisson.pmf(y,link_f))

    def logpdf_link(self, link_f, y, Y_metadata=None):
        """
        Log Likelihood Function given link(f)

        .. math::
            \\ln p(y_{i}|\lambda(f_{i})) = -\\lambda(f_{i}) + y_{i}\\log \\lambda(f_{i}) - \\log y_{i}!

        :param link_f: latent variables (link(f))
        :type link_f: Nx1 array
        :param y: data
        :type y: Nx1 array
        :param Y_metadata: Y_metadata which is not used in poisson distribution
        :returns: likelihood evaluated for this point
        :rtype: float

        """
        return -link_f + y*np.log(link_f) - special.gammaln(y+1)

    def dlogpdf_dlink(self, link_f, y, Y_metadata=None):
        """
        Gradient of the log likelihood function at y, given link(f) w.r.t link(f)

        .. math::
            \\frac{d \\ln p(y_{i}|\lambda(f_{i}))}{d\\lambda(f)} = \\frac{y_{i}}{\\lambda(f_{i})} - 1

        :param link_f: latent variables (f)
        :type link_f: Nx1 array
        :param y: data
        :type y: Nx1 array
        :param Y_metadata: Y_metadata which is not used in poisson distribution
        :returns: gradient of likelihood evaluated at points
        :rtype: Nx1 array

        """
        return y/link_f - 1

    def d2logpdf_dlink2(self, link_f, y, Y_metadata=None):
        """
        Hessian at y, given link(f), w.r.t link(f)
        i.e. second derivative logpdf at y given link(f_i) and link(f_j)  w.r.t link(f_i) and link(f_j)
        The hessian will be 0 unless i == j

        .. math::
            \\frac{d^{2} \\ln p(y_{i}|\lambda(f_{i}))}{d^{2}\\lambda(f)} = \\frac{-y_{i}}{\\lambda(f_{i})^{2}}

        :param link_f: latent variables link(f)
        :type link_f: Nx1 array
        :param y: data
        :type y: Nx1 array
        :param Y_metadata: Y_metadata which is not used in poisson distribution
        :returns: Diagonal of hessian matrix (second derivative of likelihood evaluated at points f)
        :rtype: Nx1 array

        .. Note::
            Will return diagonal of hessian, since every where else it is 0, as the likelihood factorizes over cases
            (the distribution for y_i depends only on link(f_i) not on link(f_(j!=i))
        """
        return -y/(link_f**2)

    def d3logpdf_dlink3(self, link_f, y, Y_metadata=None):
        """
        Third order derivative log-likelihood function at y given link(f) w.r.t link(f)

        .. math::
            \\frac{d^{3} \\ln p(y_{i}|\lambda(f_{i}))}{d^{3}\\lambda(f)} = \\frac{2y_{i}}{\\lambda(f_{i})^{3}}

        :param link_f: latent variables link(f)
        :type link_f: Nx1 array
        :param y: data
        :type y: Nx1 array
        :param Y_metadata: Y_metadata which is not used in poisson distribution
        :returns: third derivative of likelihood evaluated at points f
        :rtype: Nx1 array
        """
        d3lik_dlink3 = 2*y/(link_f)**3
        return d3lik_dlink3

    def conditional_mean(self,gp):
        """
        The mean of the random variable conditioned on one value of the GP
        """
        return self.gp_link.transf(gp)

    def conditional_variance(self,gp):
        """
        The variance of the random variable conditioned on one value of the GP
        """
        return self.gp_link.transf(gp)

    def samples(self, gp, Y_metadata=None):
        """
        Returns a set of samples of observations based on a given value of the latent variable.

        :param gp: latent variable
        """
        orig_shape = gp.shape
        gp = gp.flatten()
        # Ysim = np.random.poisson(self.gp_link.transf(gp), [samples, gp.size]).T
        # return Ysim.reshape(orig_shape+(samples,))
        Ysim = np.random.poisson(self.gp_link.transf(gp))
        return Ysim.reshape(orig_shape)

    def moments_match_ep(self, Y_i, tau_i, v_i, Y_metadata_i=None):
        """
        Moments match of the marginal approximation in EP algorithm

        :param i: number of observation (int)
        :param tau_i: precision of the cavity distribution (float)
        :param v_i: mean/variance of the cavity distribution (float)
        """
        Y_i = Y_i[0]
        if isinstance(self.gp_link, link_functions.Square):
            mu = v_i/tau_i
            sigma2 = 1/tau_i
            alpha = 2 * sigma2 / (1 + 2 * sigma2)
            y = int(Y_i)
            h = mu * mu / (1 + 2 * sigma2)
            z_F = -h / 2 / sigma2
            lZ_1 = (y + 0.5) * np.log(alpha) - np.log(2 * np.pi * sigma2) / 2 - np.sum(
                np.log(range(1, int(y) + 1))) - h + loggamma(y + 0.5)
            lZ = lZ_1 + np.log(hyp1f1(-y, 0.5, z_F))
            dlZ_1 = y / sigma2 * hyp1f1(1 - y, 1.5, z_F) / hyp1f1(-y, 0.5, z_F) - 1
            dlZ = dlZ_1 * 2 * mu / (1 + 2 * sigma2)
            mean_thm = dlZ * sigma2 + mu
            if not self.qp:
                d2lZ_1 = dlZ_1 * 2 / (1 + 2 * sigma2)
                d2lZ_2 = hyp1f1(2 - y, 2.5, z_F) / hyp1f1(-y, 0.5, z_F) * 2 * (1 - y) / 3
                # print(hyp1f1(-y, 0.5, z_F),hyp1f1(-y, 0.5, z_F))
                d2lZ_2 += hyp1f1(1 - y, 1.5, z_F) ** 2 / hyp1f1(-y, 0.5, z_F) ** 2 * 2 * y
                d2lZ_2 *= 2 * h * y / sigma2 ** 2 / (1 + 2 * sigma2)
                d2lZ = d2lZ_1 - d2lZ_2
                v_thm = sigma2 ** 2 * d2lZ + sigma2
            else:
                beta = mu / (1 + 2 * sigma2)
                lA = -(y + 0.5) * np.log(alpha) - loggamma(y + 0.5) - np.log(hyp1f1(-y, 0.5, z_F))
                norm_Z = -np.log(2 * np.pi * sigma2) / 2
                log_fac_y = np.sum(np.log(range(1, y + 1)))
                self.log_comb_list = np.array([self.log_comb(2 * y, k) for k in range(2*y+1)])
                k2_list = (np.arange(2*y+1)+1)/2
                self.logalpha_loggamma = k2_list * np.log(alpha) + loggamma(k2_list)

                def F_thm(x):
                    res_dict = {1: [], -1: []}
                    for k in range(1 + 2 * y):
                        value, sign = self.log_term_k(k, x, y, alpha, beta)
                        # if np.random.rand()<0.001: print(k,x,y,alpha,beta,sign,value)
                        if sign != 0:
                            res_dict[sign] += [value]
                    p = 0 if len(res_dict[1]) == 0 else np.exp(logsumexp(res_dict[1]))
                    n = 0 if len(res_dict[-1]) == 0 else np.exp(logsumexp(res_dict[-1]))
                    res = (p - n) * np.exp(lA) / 2
                    res = np.clip(res,1e-14,1-1e-14)
                    return res

                def logp_thm(x):
                    #loglike = lambda f: 2*y*np.log(abs(f)) - f**2 - np.sum(np.log(range(1, y + 1)))
                    #logpr = lambda x: -np.log(2*np.pi*sigma2)/2-(x-mu)*(x-mu)/2/sigma2
                    #return loglike(x)+logpr(x)-lZ
                    loglike = 2 * y * np.log(abs(x)) -  x ** 2 -log_fac_y
                    logpr = norm_Z - (x - mu) * (x - mu) / 2 / sigma2
                    return loglike + logpr - lZ

                v_thm = np.sqrt(2)*quad(lambda x: x*erfinv(2*F_thm(x)-1)*np.exp(logp_thm(x)),-np.inf,np.inf)[0]
                v_thm *= v_thm

        elif isinstance(self.gp_link, link_functions.Rectified_linear):
            z = sign*v_i/np.sqrt(tau_i)
            phi_div_Phi = derivLogCdfNormal(z)
            log_Z_hat = logCdfNormal(z)
            mu_hat = v_i/tau_i + sign*phi_div_Phi/np.sqrt(tau_i)
            sigma2_hat = (1. - a*phi_div_Phi - np.square(phi_div_Phi))/tau_i
        else:
            #TODO: do we want to revert to numerical quadrature here?
            raise ValueError("Exact moment matching not available for link {}".format(self.gp_link.__name__))

        # TODO: Output log_Z_hat instead of Z_hat (needs to be change in all others likelihoods)
        # print(np.exp(lZ), mean_thm, v_thm)
        assert not (np.isnan(lZ) or np.isnan(mean_thm) or np.isnan(v_thm)), '{} {} {}'.format(lZ, mean_thm, v_thm)
        return np.exp(lZ), mean_thm, v_thm

    # def log_term_k(self, k, x, y, alpha, beta):
    #   def log_comb(n, k):
    #         return np.sum(np.log(range(n - k + 1, n + 1))) - np.sum(np.log(range(1, k + 1)))
    #    k2 = (k + 1) / 2
    #    a = (-1) ** k + np.sign(x - beta) ** (k + 1) * (1 - gammaincc(k2, (x - beta) ** 2 / alpha))
    #    sign = np.sign(a) * (((2 * y - k) % 2 == 0) * 2 - 1 if np.sign(beta) < 0 else np.sign(beta))
    #    if sign == 0.:
    #        return 0, 0
    #    res = log_comb(2 * y, k) + (2 * y - k) * np.log(abs(beta)) + k2 * np.log(alpha) + loggamma(k2) + np.log(abs(a))
    #    return res, sign

    def log_term_k(self, k, x, y, alpha, beta):

        k2 = (k + 1) / 2
        sign_x_beta = np.sign(x - beta)
        a = (k%2 == 0)*2-1 +  (sign_x_beta if sign_x_beta >= 0 else (1-(k%2 == 0)*2))*(1 - gammaincc(k2, (x - beta) ** 2 / alpha))
        sign = np.sign(a) * ((((2 * y - k) % 2 == 0) * 2 - 1) if np.sign(beta) < 0 else np.sign(beta))
        if sign == 0.:
            return 0, 0
        res = self.log_comb_list[k] + self.safe_alogb(2 * y - k,abs(beta)) + self.logalpha_loggamma[k] + np.log(abs(a))
        return res, sign

    def log_comb(self, n, k):
        return np.sum(np.log(range(n - k + 1, n + 1))) - np.sum(np.log(range(1, k + 1)))

    def safe_alogb(self,a,b):
        if a == 0 and b == 0:
            return 0
        else:
            return a*np.log(b)


"""
@Author: Coralie Grobel, Clément Chaffard, David Roch
@Date: 23.12.2021
@Description : This file contains all the functions to give a feedback to the user.
"""
import matplotlib.pyplot as plt

def show_results(images_name, images, body_parts, body_parts_pos, body_parts_temps):
    """
    @Description: Show the images used and the body parts detected in a new window and
                    print their corresponding temperatures in the terminal.
    @Inputs:
        images_name: The name of the images used in order.
        images: The list of images used by openpifpaf,
        body_parts: The body parts used in order.
        body_parts_pos: The list of positions of each body_part of each human in each image.
                        This variable indices are: [image][human][body_part].
        body_parts_temps: The list of temperatures of each body_part of each human in each image.
                        This variable indices are: [image][human][body_part].
    """
    for im in range(len(images)):
        print("In image", images_name[im])
        plt.imshow(images[im])

        for human in range(len(body_parts_temps[im])):
            for body_part in range(len(body_parts)):
                number = human*len(body_parts) + body_part
                if body_parts_pos[im][human][body_part] == [0,0]:
                    print("The ", body_parts[body_part], number,
                        "is not detected in this image.")
                    continue
                cur_pos = [body_parts_pos[im][human][body_part][1], body_parts_pos[im][human][body_part][0]]
                plt.scatter(cur_pos[0], cur_pos[1], s=4, c='blue')
                plt.text(cur_pos[0], cur_pos[1], str(number))
                print("The temperature of the ", body_parts[body_part], number,
                        "is", body_parts_temps[im][human][body_part], "(in blue).")

        plt.show()


import dash
from dash import html
from dash import dcc
import dash_bootstrap_components as dbc
import pandas as pd
import plotly.express as px# load data
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import urllib.request
import numpy as np

# Read data from a csv
#url = "https://raw.githubusercontent.com/plotly/datasets/master/spectral.csv"
url = "http://localhost:8000/temp.csv"

f = urllib.request.urlopen(url)
#f = open("log_20221218_2000.txt", "r")
spectra=np.loadtxt(f, delimiter=',', skiprows=1)

traces = []
y_raw = spectra[:, 0] # wavelength
sample_size = spectra.shape[1]-1
for i in range(1, sample_size):
    z_raw = spectra[:, i]
    x = []
    y = []
    z = []
    ci = int(255/sample_size*i) # ci = "color index"
    for j in range(0, len(z_raw)):
        z.append([z_raw[j], z_raw[j]])
        y.append([y_raw[j], y_raw[j]])
        x.append([i*2, i*2+1])
    traces.append(dict(
        z=z,
        x=x,
        y=y,
        colorscale=[ [i, 'rgb(%d,%d,255)'%(ci, ci)] for i in np.arange(0,1.1,0.1) ],
        showscale=False,
        type='surface',
    ))

fig = { 'data':traces, 'layout':{'title':'Ribbon Plot'} }

app = dash.Dash(__name__, external_stylesheets=[dbc.themes.UNITED])# set app layout
app.layout = html.Div(children=[
    dcc.Graph(id='histogram', figure=fig,style={'width': '90vh', 'height': '90vh'})
])
if __name__ == "__main__":
    app.run_server(debug=True)


import argparse
import json
import os

import nemo
import nemo.collections.asr as nemo_asr
import torch
from nemo.collections.asr.models import ASRConvCTCModel

parser = argparse.ArgumentParser(description=__doc__)

parser.add_argument("wav_path", type=str, default="data/demo1.wav",
                    help="Path to wav file with the sound for transcription")

parser.add_argument("am_path", type=str, default="JasperNet10x5-En-Base.nemo",
                    help="Path to NeMo acoustic model")

parser.add_argument("lm_path", type=str, default="common_crawl_00.prune01111.trie.klm",
                    help="Path to KenLM N-Gram language model")

parser.add_argument("--batch_size", type=int, default=32,
                    help="Batch size for acoustic model")

parser.add_argument("--beam_size", type=int, default=2048,
                    help="Beam size for beam search with language model")

parser.add_argument("--alpha", type=float, default=2.5,
                    help="Alpha parameter for beam search")

parser.add_argument("--beta", type=float, default=0.3,
                    help="Beta parameter for beam search")

parser.add_argument("--output_path", type=str, default="candidates.txt",
                    help="Path to KenLM N-Gram language model")

args = parser.parse_args()

def recognize_speech():
    if torch.cuda.is_available():
        neural_factory = nemo.core.NeuralModuleFactory(
            placement=nemo.core.DeviceType.GPU
            , optimization_level=nemo.core.Optimization.mxprO1
        )
    else:
        neural_factory = nemo.core.NeuralModuleFactory(
            placement=nemo.core.DeviceType.CPU)

    # noinspection PyTypeChecker
    asr_model: ASRConvCTCModel = nemo_asr.models.ASRConvCTCModel.from_pretrained(model_info=args.am_path)
    asr_model.eval()

    beam_search_with_lm = nemo_asr.BeamSearchDecoderWithLM(
        vocab=asr_model.vocabulary,
        beam_width=args.beam_size,
        alpha=args.alpha,
        beta=args.beta,
        lm_path=args.lm_path,
        num_cpus=max(os.cpu_count(), 1))

    # Create dummy manifest with single file
    manifest_path = "manifest.transcription"
    with open(manifest_path, 'w') as f:
        f.write(json.dumps({"audio_filepath": args.wav_path, "duration": 18000, "text": "todo"}))

    data_layer = nemo_asr.AudioToTextDataLayer(
        shuffle=False,
        manifest_filepath=manifest_path,
        labels=asr_model.vocabulary, batch_size=args.batch_size)

    audio_signal, audio_signal_len, _, _ = data_layer()

    log_probs, encoded_len = asr_model(input_signal=audio_signal, length=audio_signal_len)
    beam_predictions = beam_search_with_lm(
        log_probs=log_probs, log_probs_length=encoded_len)
    eval_tensors = [beam_predictions]

    tensors = neural_factory.infer(tensors=eval_tensors, use_cache=False, cache=False, offload_to_cpu=True)

    batch = tensors[-1][0]
    prediction = batch[0]
    candidates = [candidate[1] for candidate in prediction]

    with open(args.output_path, 'w') as f:
        for candidate in candidates:
            f.write(candidate + "\n")

def main():
    recognize_speech()

if __name__ == "__main__":
    main()


import numpy as np
import os
import pickle
from PIL import Image

data_dir = 'by_class'
home_dir = os.getcwd()
hex_chars = ['30', '31', '32', '33', '34', '35', '36', '37', '38', '39']

def load_pickle_file(filename):
    with open(filename, 'rb') as f:
        return pickle.load(f)

def save_pickle_file(filename, data):
    with open(filename, 'wb') as f:
        pickle.dump(data, f)

def hex_to_decimal(hex_char):
    return int(hex_char, 16)

def get_images_from_dir(images_dir):
    filenames = os.listdir(images_dir)
    images = np.empty([len(filenames), 128, 128], dtype=np.uint8)

    for i, f in enumerate(filenames):
        image_dir = f'{images_dir}/{f}'
        image = Image.open(image_dir).convert('L')
        image = np.array(image)

        images[i] = image

    return images

def get_num_images_in_dir(directory):
    filenames = os.listdir(directory)
    return len(filenames)

def get_num_images(typ):
    num_train_images = 0
    for hex_char in hex_chars:
        if typ == 'train':
            directory = f'{home_dir}/{data_dir}/{hex_char}/train_{hex_char}'
        elif typ == 'test':
            directory = f'{home_dir}/{data_dir}/{hex_char}/hsf_4'
        else:
            return
        num_train_images += get_num_images_in_dir(directory)

    return num_train_images

def save_images(typ):
    if typ not in ['train', 'test']: return

    num_total_images = get_num_images(typ)

    filename = f'nist_data/{typ}_images.pkl'

    all_images = np.empty([num_total_images, 128, 128], dtype=np.uint8)

    save_pickle_file(filename, all_images)

    total_count = 0
    for hex_char in hex_chars:
        all_images = load_pickle_file(filename)

        if typ == 'train':
            directory = f'{home_dir}/{data_dir}/{hex_char}/train_{hex_char}'
        elif typ == 'test':
            directory = f'{home_dir}/{data_dir}/{hex_char}/hsf_4'

        images = get_images_from_dir(directory)
        num_images_for_hex = np.shape(images)[0]
        print(num_images_for_hex)

        all_images[total_count:(total_count+num_images_for_hex)] = images

        save_pickle_file(filename, all_images)

        total_count += num_images_for_hex

        print('finished', hex_char)

save_images('train')


# -*- coding: utf-8 -*-
"""
Created on Wed Jun  2 17:58:54 2021

@author: AlexandreN
"""

import os
from os import listdir
from os.path import join, isdir
from os import chdir, getcwd

from tkinter import *
from PIL import Image, ImageTk
import math
import pandas as pd

BASE_STEP = 15

class LabellingApp(Frame):
    def __init__(self, folder, master=None):
        super().__init__(master)
        self.master = master

        wd = getcwd()
        chdir(wd)
        path = os.getcwd()
        self.folder = folder
        self.my_path = path + "\\data\\images\\"
        self.dirs = [f for f in listdir(self.my_path) if isdir(join(self.my_path, self.folder))]

        self.df = []

        self.i = 1
        self.last_i = 1
        self.step = 0
        self.last_step = 0

        self.currently_new_seq = True
        self.video_seq = 0

        # setting up a tkinter canvas
        self.w = Canvas(self.master, width=512, height=512)
        self.w.pack()

        self.new_image()

    def add_image(self, folder, i):
        file = self.my_path + folder + '\\im_' + str(i) + '.jpg'

        try:
            original = Image.open(file)
        except Exception:
            self.save_res()
            self.master.destroy()
        else:
            original = original.resize((512, 512))  # resize image

            self.img = ImageTk.PhotoImage(master=self.master, image=original)
            self.w.create_image(0, 0, image=self.img, anchor="nw")

    def new_image(self):
        print("newimage", self.i, "\nseq :", self.video_seq)
        if hasattr(self, 'b_redo'):
            self.b_redo.destroy()

        if hasattr(self, 'text'):
            self.w.delete(self.text)

        self.last_i = self.i
        self.i += self.step

        self.add_image(self.folder, self.i)
        self.text = self.w.create_text(10, 10, text="Cliquer si même séquence vidéo",
                                       fill="black", font='Helvetica 15 bold',
                                       anchor='nw')

        self.b_new_seq = Button(self.master,
                                text="Nouvelle séquence vidéo ?",
                                command=self.new_seq)
        self.b_new_seq.pack()
        self.b_save_res = Button(self.master,
                                 text="Sauvegarder données labellisées ?",
                                 command=self.save_res)
        self.b_save_res.pack()
        self.w.bind("<Button 1>", self.suite_sequence_video)

    def new_seq(self):
        self.w.delete(self.text)

        self.b_new_seq.destroy()
        self.b_save_res.destroy()

        if self.step > 1:
            self.i = self.last_i
            self.step = math.trunc(self.step / 2)
            self.new_image()
        else:
            self.get_label()
            self.currently_new_seq = True

    def save_res(self):
        print("saving...")
        df = pd.DataFrame(self.df)
        f_name = "labels_" + self.folder + '.csv'
        df.to_csv('data/dfs/'+f_name)
        print("done")

    def suite_sequence_video(self, event):
        self.w.delete(self.text)

        self.w.unbind("<Button 1>")
        self.b_new_seq.destroy()
        self.b_save_res.destroy()
        self.get_label()

    def get_label(self):
        self.w.unbind("<Button 1>")
        self.last_step = self.step
        self.step = BASE_STEP

        self.b1 = Button(self.master, text="Pull Up", command=self.pull_up_lab)
        self.b1.pack()
        self.b2 = Button(self.master, text="Not Pull Up", command=self.not_pull_up_lab)
        self.b2.pack()

        self.b_redo = Button(self.master, text="relabel current image", command=self.redo_image_process)
        self.b_redo.pack()

    def pull_up_lab(self):
        self.b1.destroy()
        self.b2.destroy()
        self.label= 1
        print("la")
        self.text = self.w.create_text(10, 10, text="Point Chest",
                                       fill="black", font='Helvetica 15 bold',
                                       anchor='nw')
        self.w.bind("<Button 1>", self.get_chest)

    def not_pull_up_lab(self):
        self.b1.destroy()
        self.b2.destroy()
        self.label= 0
        print("not pull_up")
        self.x_chest = 0
        self.y_chest = 0
        self.x_bar = 0
        self.y_bar = 0

        self.b_validate = Button(self.master, text="Validate label", command=self.validate_label)
        self.b_validate.pack()

    def redo_image_process(self):
        self.b1.destroy()
        self.b2.destroy()
        if hasattr(self, 'b_validate'):
            self.b_validate.destroy()

        self.i = self.last_i
        self.step = self.last_step
        self.new_image()

    def add_cross(self, x, y, col="dark"):
        self.w.create_line(x - 5, y, x + 5, y, fill=col)
        self.w.create_line(x, y - 5, x, y + 5, fill=col)

    def get_chest(self, event):
        self.w.delete(self.text)
        self.text = self.w.create_text(10, 10, text="Point the middle of the bar",
                                       fill="black", font='Helvetica 15 bold',
                                       anchor='nw')
        self.x_chest = event.x
        self.y_chest = event.y
        self.add_cross(self.x_chest, self.y_chest, "green")
        print("chest : ", self.x_chest, self.y_chest)

        self.w.bind("<Button 1>", self.get_bar)

    def get_bar(self, event):
        self.w.delete(self.text)
        self.w.unbind("<Button 1>")

        self.x_bar = event.x
        self.y_bar = event.y
        self.add_cross(self.x_bar, self.y_bar, "red")
        print("bar : ", self.x_bar, self.y_bar)

        self.b_validate = Button(self.master, text="Validate label", command=self.validate_label)
        self.b_validate.pack()

    def validate_label(self):
        self.b_validate.destroy()

        self.coord_bar = [self.x_bar / self.w.winfo_width(), self.y_bar / self.w.winfo_width()]
        self.coord_chest = [self.x_chest / self.w.winfo_width(), self.y_chest / self.w.winfo_width()]

        # outputting x and y coords to console
        print(self.label, self.coord_bar, self.coord_chest)

        self.annotate()

        self.currently_new_seq = False
        # lessgo for a new image to annotate
        self.new_image()

    def annotate(self):
        if self.currently_new_seq:
            self.video_seq += 1

        self.df.append({'name': "im_" + str(self.i),
                        'folder': self.folder,
                        'video_seq': self.video_seq,
                        'pull_up': self.label,
                        'bar': self.coord_bar,
                        'chest': self.coord_chest, })

def main(folder):
    # Create our master object to the Application
    master = Tk()
    # Create our application object
    app = LabellingApp(folder, master=master)
    # Start the mainloop
    app.mainloop()

if __name__ == "__main__":
    folder = 'images2'
    main(folder)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 14 14:21:02 2020

@author: aroman
"""
def parameters_init():
    #Initialize parameters
    bndtiltconst = 1500
    bndGPSconst = 200
    bndtimeconst = 3600 * 24* 6
    bounds = np.array([[+8,+11],[+8,+11],[+8,+10],[dxmin,dxmax],[Ncycmin,Ncycmax],[1,10],[1,10]]) #Vs,Vd,as,ad,taus,R5,R3,k_exp

    rho = 2600
    g = 9.8
    rhog = rho * g
    #Conduit parameters
    ls = 4e+4
    ld = 2.5e+3
    mu = 100
    #Pressures and friction
    poisson = 0.25
    lame = 1e+9
    #Cylinder parameters
    Rcyl = 1.0e+3
    S = 3.14 * Rcyl**2
    const = -9. /(4 * 3.14) * (1 - poisson) / lame
    ndim = len(bounds)
    return ls,ld,mu,rhog,const,S,bndtiltconst,bndGPSconst,bndtimeconst,bounds,ndim

def walkers_init_MAP(nwalkers,parmax,locTruth,locErr):
    parmodel = parmax[-7:]
    offtimemax = parmax[0]
    offGPSmax = parmax[1]
    offtxmax = parmax[2]
    offtymax = parmax[3]
    parmodel[0] = 10**parmodel[0]
    parmodel[1] = 10**parmodel[1]
    parmodel[2] = 10**parmodel[2]
    pos = np.zeros((nwalkers,len(parmodel)))
    for i in range(len(parmodel)):
        pos[:,i] = np.random.normal(loc = parmodel[i],scale = parmodel[i]/10,size = nwalkers)
    pos[:,0] = np.log10(pos[:,0])
    pos[:,1] = np.log10(pos[:,1])
    pos[:,2] = np.log10(pos[:,2])
    locs = np.zeros((nwalkers,6))
    for i in range(len(locTruth)):
        locs[:,i] = np.random.normal(loc = locTruth[i], scale =locErr[i],size = nwalkers)
    pos = np.concatenate((locs,pos),axis = 1)

    offtilt = np.zeros((nwalkers,  2))
    offtilt[:,0] = np.random.normal(loc = offtxmax, scale = np.abs(offtxmax/10), size =nwalkers)
    offtilt[:,1] = np.random.normal(loc = offtymax, scale = np.abs(offtymax/10), size =nwalkers)
    pos = np.concatenate((offtilt,pos),axis = 1)

    offsGPS = np.random.normal(loc = offGPSmax , scale = np.abs(offGPSmax / 10),size = (nwalkers,1))
    pos = np.concatenate((offsGPS,pos),axis = 1 )

    offt = np.random.normal(loc = offtimemax,scale = np.abs(offtimemax /10),size = (nwalkers,1))
    pos = np.concatenate((offt,pos),axis = 1 )
    nwalkers, ndim = pos.shape
    return pos,nwalkers,ndim

    return pos,nwalkers,ndim

import matplotlib.pyplot as plt
import numpy as np
from main_lib_UF import *
import numpy as np
from scipy.optimize import minimize
import emcee
import pickle
from preparedata_UF import preparation_UF
from multiprocessing import Pool
import os
import sys

pathrun = 'test_MAPstart'
pathMAP = 'test/'
os.environ["OMP_NUM_THREADS"] = "1"
stations  = ['UWD']
date = '06-16-2018'
date = '07-03-2018'
thin = 10
np.random.seed(1234)
Ncycmin = 20
Ncycmax = 60
nwalkers = 64
tiltErr = 1e-6
GPSErr = 1e-2
dxmin = 3.0
dxmax = 4.0
Nmax = 35

if len(stations) > 1:
    pathtrunk = str(len(stations)) + 'st'
else:
    pathrunk = stations[0]

pathtrunk = pathrunk + '/' + date + '/'

pathgg = pathtrunk + pathrun
pathgg  =  pathgg + '/'
pathggMAP = pathrunk + '/' + date + '/' + pathMAP
try:
    os.mkdir(pathgg)
    descr =input('Briefly describe the run: ')
    f =  open(pathgg + 'description.txt','w')
    f.write(descr)
    f.close()
except:
    print('Directory exists!')
if  os.path.isfile(pathgg + 'progress.h5'):
    nstation,x,y,tTilt,tx,ty,tGPS,GPS,locTruth,locErr,t0,bounds,bndtiltconst,bndGPSconst,bndtimeconst,tiltErr,GPSErr,fix_par,niter,a_parameter = pickle.load(open(pathgg + 'data.pickle','rb'))
    x,y,ls,ld,mu,rhog,const,S,Nmax,tiltErr,GPSErr = fix_par
    reader = emcee.backends.HDFBackend(pathgg + 'progress.h5', read_only=True)
    niter  = reader.iteration
    answer = input('Found past run with ' + str(niter) +' samples. Do you want to continue this run? Enter the number of iteration that additionally you want to do: ')
    moreiter = int(answer)
    print('Restarting!!!!')
    nwalkers,ndim = reader.shape
    filename = pathgg + "progress.h5"
    backend = emcee.backends.HDFBackend(filename)
    with Pool() as pool:
        sampler = emcee.EnsembleSampler(nwalkers, ndim, log_probability_UF,
                                       args=(x,y,
                                        ls,ld,mu,
                                        rhog,const,S,
                                        tTilt,tGPS,tx,ty,GPS,
                                        tiltErr,GPSErr,bounds,bndtimeconst,bndGPSconst,Nmax,locTruth,locErr,nstation), backend = backend, pool = pool)
        sampler.run_mcmc(None, moreiter, progress=True,thin = thin)

else:
    nstation,x,y,tTilt,tx,ty,tGPS,GPS,locTruth,locErr,t0,bounds,bndtiltconst,bndGPSconst,bndtimeconst,tiltErr,GPSErr,fix_par,niter = pickle.load(open(pathggMAP + 'data.pickle','rb'))
    x,y,ls,ld,mu,rhog,const,S,Nmax,tiltErr,GPSErr = fix_par

    niter = input('How many iteration you want to run? ')
    filenameMAP =  'progress.h5'
    a_parameter = 2
    reader = emcee.backends.HDFBackend(pathggMAP + filenameMAP, read_only = True )
    nwalkers,ndim = reader.shape
    samples = reader.get_chain(flat = True)
    parmax = samples[np.argmax(reader.get_log_prob(flat = True))]
    offtime,offGPSSamp,offx1,offy1,xsSamp,ysSamp,dsSamp,xdSamp,ydSamp,ddSamp,VsExpSamp,VdExpSamp,kExpSamp,R5ExpSamp,R3Samp,condsSamp, conddSamp = parmax
    pos,nwalkers,ndim = walkers_init_MAP(nwalkers,parmax,locTruth,locErr)
    fix_par = np.array([x,y,ls,ld,mu,rhog,const,S,Nmax,tiltErr,GPSErr])
    pickle.dump((nstation,x,y,tTilt,tx,ty,tGPS,GPS,locTruth,locErr,t0,bounds,bndtiltconst,bndGPSconst,bndtimeconst,tiltErr,GPSErr,fix_par,niter,a_parameter),open(pathgg + 'data.pickle','wb'))
    filename = pathgg + "progress.h5"
    backend = emcee.backends.HDFBackend(filename)

    move = emcee.moves.StretchMove(a=a_parameter)

    with Pool() as pool:
        sampler = emcee.EnsembleSampler(nwalkers, ndim, log_probability_UF,
                                        args=(x,y,
                                            ls,ld,mu,
                                            rhog,const,S,
                                            tTilt,tGPS,tx,ty,GPS,
                                            tiltErr,GPSErr,bounds,bndtimeconst,bndGPSconst,Nmax,locTruth,locErr,nstation),moves = [move], backend = backend, pool = pool)

        print('Running main sampling')
        sampler.run_mcmc(pos,niter, progress = True,thin = thin)


#!/usr/bin/env python
"""
Unit tests for the HP 6632b power supply
"""

# IMPORTS #####################################################################

import pytest

from instruments.units import ureg as u

import instruments as ik
from tests import expected_protocol, make_name_test, unit_eq

# TESTS #######################################################################

test_scpi_multimeter_name = make_name_test(ik.hp.HP6632b)

def test_hp6632b_display_textmode():
    with expected_protocol(
        ik.hp.HP6632b, ["DISP:MODE?", "DISP:MODE TEXT"], ["NORM"]
    ) as psu:
        assert psu.display_textmode is False
        psu.display_textmode = True

def test_hp6632b_display_text():
    with expected_protocol(
        ik.hp.HP6632b, ['DISP:TEXT "TEST"', 'DISP:TEXT "TEST AAAAAAAAAA"'], []
    ) as psu:
        assert psu.display_text("TEST") == "TEST"
        assert psu.display_text("TEST AAAAAAAAAAAAAAAA") == "TEST AAAAAAAAAA"

def test_hp6632b_output():
    with expected_protocol(ik.hp.HP6632b, ["OUTP?", "OUTP 1"], ["0"]) as psu:
        assert psu.output is False
        psu.output = True

def test_hp6632b_voltage():
    with expected_protocol(ik.hp.HP6632b, ["VOLT?", f"VOLT {1:e}"], ["10.0"]) as psu:
        unit_eq(psu.voltage, 10 * u.volt)
        psu.voltage = 1.0 * u.volt

def test_hp6632b_voltage_sense():
    with expected_protocol(
        ik.hp.HP6632b,
        [
            "MEAS:VOLT?",
        ],
        ["10.0"],
    ) as psu:
        unit_eq(psu.voltage_sense, 10 * u.volt)

def test_hp6632b_overvoltage():
    with expected_protocol(
        ik.hp.HP6632b, ["VOLT:PROT?", f"VOLT:PROT {1:e}"], ["10.0"]
    ) as psu:
        unit_eq(psu.overvoltage, 10 * u.volt)
        psu.overvoltage = 1.0 * u.volt

def test_hp6632b_current():
    with expected_protocol(ik.hp.HP6632b, ["CURR?", f"CURR {1:e}"], ["10.0"]) as psu:
        unit_eq(psu.current, 10 * u.amp)
        psu.current = 1.0 * u.amp

def test_hp6632b_current_sense():
    with expected_protocol(
        ik.hp.HP6632b,
        [
            "MEAS:CURR?",
        ],
        ["10.0"],
    ) as psu:
        unit_eq(psu.current_sense, 10 * u.amp)

def test_hp6632b_overcurrent():
    with expected_protocol(
        ik.hp.HP6632b, ["CURR:PROT:STAT?", "CURR:PROT:STAT 1"], ["0"]
    ) as psu:
        assert psu.overcurrent is False
        psu.overcurrent = True

def test_hp6632b_current_sense_range():
    with expected_protocol(
        ik.hp.HP6632b, ["SENS:CURR:RANGE?", f"SENS:CURR:RANGE {1:e}"], ["0.05"]
    ) as psu:
        unit_eq(psu.current_sense_range, 0.05 * u.amp)
        psu.current_sense_range = 1 * u.amp

def test_hp6632b_output_dfi_source():
    with expected_protocol(
        ik.hp.HP6632b, ["OUTP:DFI:SOUR?", "OUTP:DFI:SOUR QUES"], ["OPER"]
    ) as psu:
        assert psu.output_dfi_source == psu.DFISource.operation
        psu.output_dfi_source = psu.DFISource.questionable

def test_hp6632b_output_remote_inhibit():
    with expected_protocol(
        ik.hp.HP6632b, ["OUTP:RI:MODE?", "OUTP:RI:MODE LATC"], ["LIVE"]
    ) as psu:
        assert psu.output_remote_inhibit == psu.RemoteInhibit.live
        psu.output_remote_inhibit = psu.RemoteInhibit.latching

def test_hp6632b_digital_function():
    with expected_protocol(
        ik.hp.HP6632b, ["DIG:FUNC?", "DIG:FUNC DIG"], ["RIDF"]
    ) as psu:
        assert psu.digital_function == psu.DigitalFunction.remote_inhibit
        psu.digital_function = psu.DigitalFunction.data

def test_hp6632b_digital_data():
    with expected_protocol(ik.hp.HP6632b, ["DIG:DATA?", "DIG:DATA 1"], ["5"]) as psu:
        assert psu.digital_data == 5
        psu.digital_data = 1

def test_hp6632b_sense_sweep_points():
    with expected_protocol(
        ik.hp.HP6632b, ["SENS:SWE:POIN?", f"SENS:SWE:POIN {2048:e}"], ["5"]
    ) as psu:
        assert psu.sense_sweep_points == 5
        psu.sense_sweep_points = 2048

def test_hp6632b_sense_sweep_interval():
    with expected_protocol(
        ik.hp.HP6632b,
        ["SENS:SWE:TINT?", f"SENS:SWE:TINT {1e-05:e}"],
        ["1.56e-05"],
    ) as psu:
        unit_eq(psu.sense_sweep_interval, 1.56e-05 * u.second)
        psu.sense_sweep_interval = 1e-05 * u.second

def test_hp6632b_sense_window():
    with expected_protocol(
        ik.hp.HP6632b, ["SENS:WIND?", "SENS:WIND RECT"], ["HANN"]
    ) as psu:
        assert psu.sense_window == psu.SenseWindow.hanning
        psu.sense_window = psu.SenseWindow.rectangular

def test_hp6632b_output_protection_delay():
    with expected_protocol(
        ik.hp.HP6632b, ["OUTP:PROT:DEL?", f"OUTP:PROT:DEL {5e-02:e}"], ["8e-02"]
    ) as psu:
        unit_eq(psu.output_protection_delay, 8e-02 * u.second)
        psu.output_protection_delay = 5e-02 * u.second

def test_hp6632b_voltage_alc_bandwidth():
    with expected_protocol(
        ik.hp.HP6632b,
        [
            "VOLT:ALC:BAND?",
        ],
        ["6e4"],
    ) as psu:
        assert psu.voltage_alc_bandwidth == psu.ALCBandwidth.fast

def test_hp6632b_voltage_trigger():
    with expected_protocol(
        ik.hp.HP6632b, ["VOLT:TRIG?", f"VOLT:TRIG {1:e}"], ["1e+0"]
    ) as psu:
        unit_eq(psu.voltage_trigger, 1 * u.volt)
        psu.voltage_trigger = 1 * u.volt

def test_hp6632b_current_trigger():
    with expected_protocol(
        ik.hp.HP6632b, ["CURR:TRIG?", f"CURR:TRIG {0.1:e}"], ["1e-01"]
    ) as psu:
        unit_eq(psu.current_trigger, 0.1 * u.amp)
        psu.current_trigger = 0.1 * u.amp

def test_hp6632b_init_output_trigger():
    with expected_protocol(
        ik.hp.HP6632b,
        [
            "INIT:NAME TRAN",
        ],
        [],
    ) as psu:
        psu.init_output_trigger()

def test_hp6632b_abort_output_trigger():
    with expected_protocol(
        ik.hp.HP6632b,
        [
            "ABORT",
        ],
        [],
    ) as psu:
        psu.abort_output_trigger()

def test_line_frequency():
    """Raise NotImplemented error when called."""
    with expected_protocol(ik.hp.HP6632b, [], []) as psu:
        with pytest.raises(NotImplementedError):
            psu.line_frequency = 42
        with pytest.raises(NotImplementedError):
            _ = psu.line_frequency

def test_display_brightness():
    """Raise NotImplemented error when called."""
    with expected_protocol(ik.hp.HP6632b, [], []) as psu:
        with pytest.raises(NotImplementedError):
            psu.display_brightness = 42
        with pytest.raises(NotImplementedError):
            _ = psu.display_brightness

def test_display_contrast():
    """Raise NotImplemented error when called."""
    with expected_protocol(ik.hp.HP6632b, [], []) as psu:
        with pytest.raises(NotImplementedError):
            psu.display_contrast = 42
        with pytest.raises(NotImplementedError):
            _ = psu.display_contrast

def test_hp6632b_check_error_queue():
    with expected_protocol(
        ik.hp.HP6632b,
        [
            "SYST:ERR?",
            "SYST:ERR?",
        ],
        ['-222,"Data out of range"', '+0,"No error"'],
    ) as psu:
        err_queue = psu.check_error_queue()
        assert err_queue == [psu.ErrorCodes.data_out_of_range], f"got {err_queue}"


from django.urls import path
from . import views

urlpatterns = [
    path('', views.log, name='log'),
    path('logn', views.logn, name='logn'),
    path('adminhome', views.adminhome, name='adminhome'),
    path('userhome', views.userhome, name='userhome'),
    path('registre', views.registre, name='registre'),
    path('reg', views.reg, name='reg'),
    path('usnchk', views.usnchk, name='usnchk'),
    path('pwdchk', views.pwdchk, name='pwdchk'),
    path('viewusers', views.viewusers, name='viewusers'),
    path('deluser/<int:id>', views.deluser, name='deluser'),
    path('gotoprof', views.gotoprof, name='gotoprof'),
    path('prof', views.prof, name='prof'),
    path('usnachk', views.usnachk, name='usnachk'),
    path('gotovp', views.gotovp, name='gotovp'),
    path('ditprof', views.ditprof, name='ditprof'),
    path('editprof', views.editprof, name='editprof'),
    path('gotocrrm', views.gotocrrm, name='gotocrrm'),
    path('createroom', views.createroom, name='createroom'),
    path('roomcheck', views.roomcheck, name='roomcheck'),
    path('viewroom', views.viewroom, name='viewroom'),
    path('gotoam/<int:id>', views.gotoam, name='gotoam'),
    path('addmembers', views.addmembers, name='addmembers'),
    path('gotorm/<int:id>', views.gotorm, name='gotorm'),
    path('delmembers', views.delmembers, name='delmembers'),
    path('ditroom/<int:id>', views.ditroom, name='ditroom'),
    path('editroom', views.editroom, name='editroom'),
    path('delroom/<int:id>', views.delroom, name='delroom'),
    path('goto', views.goto, name='goto'),
    path('createcon', views.createcon, name='createcon'),
    path('viewconn', views.viewconn, name='viewconn'),
    path('gotoconn/<int:id>', views.gotoconn, name='gotoconn'),
    path('gotocm/<int:id>', views.gotocm, name='gotocm'),
    path('sendchat', views.sendchat, name='sendchat'),
    path('createmod', views.createmod, name='createmod'),
    path('moder', views.moder, name='moder'),
    path('viewmod', views.viewmod, name='viewmod'),
    path('insta/<int:id>', views.insta, name='insta'),
    path('instachat', views.instachat, name='instachat'),
    path('gotofeedbk', views.gotofeedbk, name='gotofeedbk'),
    path('feed', views.feed, name='feed'),
    path('viewfeed', views.viewfeed, name='viewfeed'),
    path('pay', views.pay, name='pay'),
    path('charge', views.charge, name='charge'),
]


from flask import Blueprint, request, redirect, make_response, render_template, url_for
from google.cloud import datastore
import constants
from google.oauth2 import id_token
from google.auth.transport import requests as req
import requests

client = datastore.Client()

bp = Blueprint('oauth', __name__, url_prefix='/oauth')

@bp.route('')
def token_user_details():
    if 'code' and 'state' not in request.args:
        return redirect(request.root_url + 'login')

    else:
        query = client.query(kind=constants.states)
        states_list = list(query.fetch())

        # Search all boat objects and compare the names to make sure they are unique
        for curr_state in states_list:
            if curr_state['state'] == request.args.get('state'):
                data = {'code': request.args.get('code'),
                        'client_id': constants.client_id,
                        'client_secret': constants.secret,
                        'redirect_uri': constants.redirect_uri,
                        'grant_type': 'authorization_code',
                        'access_type': 'offline'}

                # POST method for token
                res_token = requests.post('https://oauth2.googleapis.com/token', data=data).json()

                # Get user details
                headers = {'Authorization': 'Bearer {}'.format(res_token['access_token'])}
                res_user = requests.get(constants.people_url, headers=headers).json()

                print(res_token, res_user)

                sub = id_token.verify_oauth2_token(
                                res_token['id_token'], req.Request(), constants.client_id)['sub']

                content = None
                for e in res_user['names']:
                    if e['givenName'] and e['familyName']:
                        content = {
                            'first': e['givenName'],
                            'last': e['familyName'],
                            'jwt': res_token['id_token'],
                            'sub': sub
                        }
                    break

                # Delete state from database
                state_key = client.key(constants.states, int(curr_state.key.id))
                client.delete(state_key)

                # Name of user must be unique
                query = client.query(kind=constants.users)
                user_list = list(query.fetch())

                # Search all boat objects and compare the names to make sure they are unique
                for curr_user in user_list:
                    if curr_user["sub"] == content["sub"]:

                        # Render user page
                        return render_template('user_info.html', user=content)

                # Create new user entity
                new_user = datastore.entity.Entity(key=client.key(constants.users))
                new_user.update({"first": content["first"], "last": content["last"], "sub": content["sub"]})
                client.put(new_user)

                # If I add user_id, then add these to return also self
                # new_user["id"] = new_user.key.id
                # new_user["self"] = request.base_url + "/" + str(new_user.key.id)

                # Render user page
                return render_template('user_info.html', user=content)

        return redirect(request.root_url + 'login')


from flask import Flask, jsonify
from translate_image_service import *
from flask_cors import CORS, cross_origin

app = Flask(__name__)

ALLOWED_ORIGINS = "*"
CORS(app, resources={r"/api/*": {"origins": ALLOWED_ORIGINS}})

@app.route('/foodieapi/')
@cross_origin()
def index():
    searchKey = request.form["key"]
    headers("Content-Type", "application/json")
    return jsonify(mainToRun(searchKey))

if __name__=="__main__":
	app.run(debug=True, port=9999)


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

# import epd5in83bc as epdModule

import sys
import os
picdir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'pic')
libdir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'lib')
if os.path.exists(libdir):
    sys.path.append(libdir)

import logging
from waveshare_epd import epd7in5b_V2
epdModule = epd7in5b_V2

from PIL import Image,ImageDraw,ImageFont
import traceback
import sys
from gpiozero import Button
from signal import pause

from time import localtime, strftime
import time

# from gcal.gcal import GcalHelper
import calendar
calendar.setfirstweekday(calendar.SUNDAY)
# get parent directory
curr_dir = __file__.split(__file__.split("/")[-1])[0]

from datetime import datetime
from datetime import timedelta

from gcal_getEvents import main

key1 = Button(5)
key2 = Button(6)
key3 = Button(13)
key4 = Button(19)

tomatoes = [0,0,0,0]
start = time.time()
tomato = -1
inited = -1
started = -1

import threading

def set_interval(func, sec):
    def func_wrapper():
        set_interval(func, sec)
        func()
    t = threading.Timer(sec, func_wrapper)
    t.start()
    return t

def handleButton(button):
    global start
    global started
    start = time.time()
    tomatoes[0] = 0
    tomatoes[1] = 0
    tomatoes[2] = 0
    tomatoes[3] = 0
    global tomato
    print(button)
    started = 0
    print(button.pin.number)
    if button.pin.number == 5:
      tomato = 0
    elif button.pin.number == 6:
      tomato = 1
    elif button.pin.number == 13:
      tomato = 2
    elif button.pin.number == 19:
      tomato = 3
    refreshScreen()

# def to_datetime(self, isoDatetime, localTZ):
#     # replace Z with +00:00 is a workaround until datetime library decides what to do with the Z notation
#     toDatetime = datetime.fromisoformat(isoDatetime.replace('Z', '+00:00'))
#     return toDatetime.astimezone(localTZ)

def merge_two_dicts(x, y):
    z = x.copy()   # start with keys and values of x
    z.update(y)    # modifies z with keys and values of y
    return z

def refreshScreen():

#   processedEvents = merge_two_dicts(main(curr_dir + "token_guerrerocarlos.json", curr_dir + "credentials.json"), main(curr_dir + "token_masterworks.json", curr_dir + "credentials.json"))
  processedEvents = main(curr_dir + "token_guerrerocarlos.json", curr_dir + "credentials.json")

  # global inited
  # global started
  # minutes = strftime("%M", localtime())
  # done = time.time()
  # elapsed = done - start

  # if int(inited) < 0 or int(started) < 0 or int(minutes) % 5 == 0 or int(elapsed) % 5 == 0:
  epd = epdModule.EPD()
  epd.init()
  epd.Clear()

  # epd.clear(0xFF)

  # inited = 0
  # print("\nelapsed" + str(elapsed))
  # if(tomato):
  #   print("\ntomato" + str(tomato))
  # print("\tomatoes" + str(tomatoes))

  # Drawing on the Horizontal image

  screenWidth = epdModule.EPD_WIDTH
  screenHeight = epdModule.EPD_HEIGHT

  Himage = Image.new('1', (epdModule.EPD_WIDTH, epdModule.EPD_HEIGHT), 255)  # 255: clear the frame
  HimageRed = Image.new('1', (epdModule.EPD_WIDTH, epdModule.EPD_HEIGHT), 255)  # 255: clear the frame
  # Drawing on the Vertical image
  # Limage = Image.new('1', (epdModule.EPD_WIDTH, epdModule.EPD_HEIGHT), 255)  # 255: clear the frame
  screenWidth = epdModule.EPD_WIDTH
  screenHeight = epdModule.EPD_HEIGHT

  print(sys.argv)

  # Horizontal
  draw = ImageDraw.Draw(Himage)
  drawRed = ImageDraw.Draw(HimageRed)
  # # Font: https://github.com/byrongibson/fonts/blob/master/truetype/wqy/wqy-microhei.ttc

  font = ImageFont.truetype(curr_dir + 'font.ttc', 18)
  fontSmall = ImageFont.truetype(curr_dir + 'font.ttc', 13)
  fontTiny = ImageFont.truetype(curr_dir + 'font.ttc', 10)
  # fontBig = ImageFont.truetype('font.ttc', 30)
  # fontMed = ImageFont.truetype('font.ttc', 20)
  # fontMedSmall = ImageFont.truetype('font.ttc', 18)
  # fontSmall = ImageFont.truetype('font.ttc', 15)
  # fontTiny = ImageFont.truetype('font.ttc', 10)

  # hour = strftime("%H", localtime())

  # # # DATE
  # # draw.text((0, 0), strftime("%a, %d %b %Y", localtime()), font = fontSmall, fill = 0)

  # titleUnderline = screenWidth
  # graphLineWidth = titleUnderline / 24

  # # DAY HOURS GRAPH
  # verticalSpace = 0
  # for h in range(1, 25):
  #   if h < int(hour):
  #     drawRed.rectangle(
  #       (0 + (int(h - 1) * graphLineWidth ),
  #       verticalSpace ,
  #       0 + int(h - 1) * graphLineWidth + graphLineWidth - 3,
  #       verticalSpace  + 24),
  #       fill = 0,
  #       outline = 0)

  #   if h >= int(hour):
  #     drawRed.rectangle(
  #       (0 + (int(h - 1) * graphLineWidth ),
  #       verticalSpace ,
  #       0 + int(h - 1) * graphLineWidth + graphLineWidth - 3,
  #       verticalSpace  + 24),
  #       fill = 255,
  #       outline = 0)

  #   if h == int(hour):
  #     # MINUTES PIE
  #     # piexy = {'x': int(h - 1) * graphLineWidth, 'y': verticalSpace , 'width': 20, 'height': 20}
  #     # draw.pieslice((piexy['x'], piexy['y'], piexy['x']+piexy['width'], piexy['y'] + piexy['height']), 270, 270 + (int(minutes) * 360 / 60), fill = 0, outline=0, width=1)

  #     drawRed.rectangle(
  #       (0 + (int(h - 1) * graphLineWidth ),
  #       verticalSpace + (24 - int(minutes) * 24 / 60) ,
  #       0 + int(h - 1) * graphLineWidth + graphLineWidth - 3,
  #       verticalSpace + 24),
  #       fill = 0,
  #       outline = 0)

  # graphLineWidth = titleUnderline / 4

  # # POMODORO GRAPH
  # graphqlVerticalWidth = graphLineWidth / 2
  # for p in range(0, 4):
  #   if p < tomato:
  #     draw.rectangle((
  #       p * graphLineWidth,
  #       30,
  #       p * graphLineWidth + graphLineWidth - 3,
  #       30 + graphqlVerticalWidth),
  #       fill = 0,
  #       outline = 0)

  #   if p >= tomato:
  #     draw.rectangle((
  #       p * graphLineWidth,
  #       30,
  #       p * graphLineWidth + graphLineWidth - 3,
  #       30 + graphqlVerticalWidth),
  #       fill = 255,
  #       outline = 0)

  #   if p == tomato:
  #     draw.rectangle((
  #       p * graphLineWidth,
  #       30,
  #       p * graphLineWidth + ((graphLineWidth - 3) * elapsed / (25 * 60)) ,
  #       30 + graphqlVerticalWidth),
  #       fill = 0,
  #       outline = 0)

  # # HOUR
  # hourSize = 40
  # fontHour = ImageFont.truetype('font.ttc', hourSize)
  # hourText = strftime("%H:%M", localtime())
  # draw.text((screenWidth - hourSize * len(hourText) / 2, screenHeight - hourSize), hourText, font = fontHour, fill = 0)

  # # Show parameter lines
  # lines = sys.argv[1].split("\n")

  # for i in range(0, len(lines)):
  #   draw.text((0, (screenHeight - len(lines) * 15) + (i * 15)), lines[i], font = fontTiny, fill = 0)

  # gcalService = GcalHelper()
  # eventList = gcalService.retrieve_events(calendars, calStartDatetime, calEndDatetime, displayTZ, thresholdHours)

  today = datetime.today()
  todayWeekday = today.weekday() + 1

  firstDayOfMonth = today - timedelta(days = today.day)

  year = today.year
  month = today.month
  day = today.day

  dow = calendar.day_name[today.weekday()]

  print(today - timedelta(days = (todayWeekday)))

  showWeeks = 6
  vSpan = screenHeight / showWeeks / 8 * 7
  hSpan = screenWidth / 7

  lines = []

  # Top Square
  drawRed.rectangle((
    0,
    0,
    screenWidth,
    vSpan - 20),
    fill = 0,
    outline = 0)

  drawRed.text((5,-1), today.strftime("%A, %d %B %Y"), font = ImageFont.truetype(curr_dir + 'font.ttc', 40), fill = 255, align = "left")

  for dayCount in range(0, 7 * showWeeks):
    drawDay = today + timedelta(days = (+ dayCount - (today.day + firstDayOfMonth.weekday() + 1)))

    lines = []
    for eventDate in processedEvents:
      if eventDate.find(drawDay.isoformat()[:10]) != -1:
          # print(datetime.fromisoformat(eventDate))
          # print(event, processedEvents[eventDate])
          # print(eventDate, processedEvents[eventDate]['summary'].encode('utf-8'))
          lines.append((eventDate[11:13] + " "+processedEvents[eventDate]['summary'].encode("ascii","ignore")))
    lines.sort()

    # drawRed.text((30 * dayCount,20), today.strftime("%A"), font = ImageFont.truetype(curr_dir + 'font.ttc', 40), fill = 0, align = "left")
    # if dayCount < 7:
    #   draw.text(
    #     (hSpan * dayCount + 3,
    #       vSpan - 20),
    #     drawDay.strftime("%A")[0:3],
    #     # "DAY",
    #     font = ImageFont.truetype(curr_dir + 'font.ttc', 16),
    #     fill = 0)

    if drawDay.month == today.month:
      draw.rectangle((
        (dayCount % 7) * hSpan,
        (dayCount / 7) * vSpan + vSpan,
        (dayCount % 7) * hSpan + hSpan + (4 if dayCount % 7 == 6 else 0) ,
        (dayCount / 7) * vSpan + vSpan + vSpan),
        fill = 255,
        outline = 0)

      for l in range(0, len(lines)):
        drawRed.text(((dayCount % 7) * hSpan + 3, vSpan + vSpan * (dayCount / 7) + 20 + l * 10), lines[l], font = fontTiny, fill = (0 if drawDay.day == today.day else 255), align = "left")

      for l in range(0, len(lines)):
        draw.text(((dayCount % 7) * hSpan + 3, vSpan + vSpan * (dayCount / 7) + 20 + l * 10), lines[l], font = fontTiny, fill = (0 if not drawDay.day == today.day else 255), align = "left")

      if(drawDay.day == today.day):
        drawRed.rectangle((
          (dayCount % 7) * hSpan,
          (dayCount / 7) * vSpan + vSpan,
          (dayCount % 7) * hSpan + hSpan ,
          (dayCount / 7) * vSpan + vSpan + vSpan),
          fill = 0,
          outline = 0)

        for l in range(0, len(lines)):
          drawRed.text(((dayCount % 7) * hSpan + 3, vSpan + vSpan * (dayCount / 7) + 20 + l * 10), lines[l], font = fontTiny, fill = (0 if not drawDay.day == today.day else 255), align = "left")

        draw.rectangle(
          (0,
          vSpan - 20,
          screenWidth,
          vSpan),
          fill = 0,
          outline = 0)

        draw.text(
            (3,
            vSpan - 20),
          " | ".join(lines),
          # "DAY",
          font = ImageFont.truetype(curr_dir + 'font.ttc', 16),
          fill = 255)

      drawRed.text(((dayCount % 7) * hSpan + 3, vSpan + vSpan * (dayCount / 7)), str(drawDay.day), font = font, fill = (0 if not drawDay.day == today.day else 255), align = "left")

    else:
      draw.rectangle((
        (dayCount % 7) * hSpan + 1,
        (dayCount / 7) * vSpan + vSpan + 1,
        (dayCount % 7) * hSpan + hSpan - 1,
        (dayCount / 7) * vSpan + vSpan + vSpan - 1),
        fill = 255,
        outline = 255)

      draw.text(((dayCount % 7) * hSpan + 3, vSpan + vSpan * (dayCount / 7)), str(drawDay.day), font = font, fill = 0, align = "left")

      for l in range(0, len(lines)):
        draw.text(((dayCount % 7) * hSpan + 3, vSpan + vSpan * (dayCount / 7) + 20 + l * 10), lines[l], font = fontTiny, fill = 0, align = "left")

  # draw.text((10, screenHeight / 2 + 5), "chao", font = font, fill = 255)

  epd.display(epd.getbuffer(Himage), epd.getbuffer(HimageRed))

  # logging.info("Clear...")
  # epd.init()
  # epd.Clear()

  # logging.info("Goto Sleep...")
  # epd.sleep()

  #   drawRed.rectangle((
  #   0,
  #   0,
  #   screenWidth,
  #   screenHeight * 3 / 4),
  #   fill = 0,
  #   outline = 0)

  # drawRed.text((10,10), "hola", font = font, fill = 255)
  # drawRed.text((10, screenHeight / 2 + 5), "hola", font = font, fill = 255)

# key1.when_pressed = handleButton
# key2.when_pressed = handleButton
# key3.when_pressed = handleButton
# key4.when_pressed = handleButton

try:
  refreshScreen()
  # set_interval(refreshScreen, 60)
  # pause()
except:
  print('traceback.format_exc():\n%s' % traceback.format_exc())
  exit()


# -*- coding: utf-8 -*-
"""
Created on Thu May 16 09:11:38 2019

@author: hasani
"""

# =============================================================================
# import needed modules
# =============================================================================
import pandas as pd
import os,sys,math
from pathlib import Path
# =============================================================================
# Input Path
# =============================================================================
root_path  = os.path.dirname(os.path.realpath(__file__))
input_data_path = os.path.join(root_path,"input data")
path_building_stock = os.path.join(input_data_path,"Hotmaps","data_building_stock.csv") #TODO: Load directly from github
path_financ_heating_tec = os.path.join(input_data_path,"Hotmaps","data_Heating_technologies_EU28_v3.csv") #TODO: Load directly from github
path_setNav_retail_energy_prices = os.path.join(input_data_path,"SetNav","RetailPricesToInvert_11072018_2.xlsx")
path_dea_catalog = os.path.join(input_data_path,"DEA","technologydatafor_heating_installations_marts_2018.xlsx")
path_invert_pmin = os.path.join(input_data_path,"Invert","invert_p_min.csv")
path_load_profiles = Path(os.path.join(input_data_path,"Hotmaps","LOAD PROFILES")) #TODO: Load directly from github
# =============================================================================
# Loading and preprocessing input data
# =============================================================================

#TODO: Load directly from api
building_stock = pd.read_csv(path_building_stock,sep="|",skiprows=[0])
building_stock = building_stock[building_stock.feature == "Useful energy demand"]
grp_bdstock = building_stock.groupby(["country_code","sector","type"])

#TODO: Load directly from api
financ_heating_tec = pd.read_csv(path_financ_heating_tec,sep=";")
grp_financ_heating_tec = financ_heating_tec.groupby(["NUTS0_ID", "type_of_building","year"])

setNav_retail_energy_prices = pd.read_excel(path_setNav_retail_energy_prices)
grp_energy_prices = setNav_retail_energy_prices.groupby(["cty_abr","Sector","Tax"])  # EUR/GJ

data_pmin = pd.read_csv(path_invert_pmin)

# =============================================================================
# Decorators
# =============================================================================
import functools
def catch_assertion_errors(func):
    @functools.wraps(func)
    def wrapper_decorator(*args, **kwargs):
        args_repr = [repr(a) for a in args]
        kwargs_repr = [f"{k}={v!r}" for k, v in kwargs.items()]
        signature = ", ".join(args_repr + kwargs_repr)
        try:
            value = func(*args, **kwargs)
            return value
        except AssertionError as error:
            return str(error),signature,False
    return wrapper_decorator
# =============================================================================
# Functions
# =============================================================================
# =============================================================================
def xor(a,b,tec,topic,nuts0):
    """ This function return the first not NaN value from a tuple

    Parameters
    ----------
    a: float
        hotmaps data

    b: float
        invert data

    tec: str
        Name of the heating system (only for debugging)

    nuts0: str
        Name of the country (only for debugging)

    Returns
    -------
    a|b: float
        First non NaN vale of a or b

    """
    if math.isnan(a) and not math.isnan(b):
        return 0,b
    elif math.isnan(b) and not math.isnan(a):
        return a,0
    elif math.isnan(a) and math.isnan(b):
        assert False, f"Error No available Data for <{topic}> in <{tec}> in country <{nuts0}>"
    else:
        return a,b

# =============================================================================
def get_pmin(nuts0,tec,data_db=data_pmin):
    assert nuts0 in set(data_db.nuts0), f"Now pmin data for <{tec}> in country <{nuts0}>"
    assert tec in set(data_db.tec), f"Now pmin data for <{tec}> in country <{nuts0}>"
    return  float(data_db.loc[(data_db.nuts0 == nuts0) & (data_db.tec == tec),"p_min"])
# =============================================================================

def get_value(nuts0,sector,hd_typ,building_stock=building_stock,
              grp_bdstock=grp_bdstock,bage=None,btype="Total"):
    """This function returns the anual usefull energy demand for either
    Spaceheating, Hot water or Cooling Demand in kWh/m²

    The database behind it can be found in https://gitlab.com/hotmaps/building-stock/blob/master/data/building_stock.csv
    This function calculates the mean value from all construction period
    of the values defined in 'hd_typ' and the sector defined in 'sector' or
    the value specifed by the building type and building age

    Parameters
    ----------
    nuts0: string
        {'at', 'be', 'bg', 'cy', 'cz', 'de', 'dk', 'ee', 'es', 'eu28', 'fi',
        'fr', 'gr', 'hr', 'hu', 'ie', 'it', 'lt', 'lu', 'lv', 'mt', 'nl', 'pl',
        'pt', 'ro', 'se', 'si', 'sk', 'uk'}

    sector: string
        {'Residential sector', 'Service sector'}

    hd_typ: string
        {"Space heating [kWh/m² year]","Domestic hot water  [kWh/m² year]",
        "Space cooling [kWh/m² year"}

    building_stock: pandas.DataFrame (6612, 14)
        This is the default Data as padnas DataFrame read from link above

    grp_bdstock: pandas.core.groupby.generic.DataFrameGroupBy
        This iterator contains the DataFrames that are sorted by
        ["country_code","sector","type"]

    Returns
    -------
    ued: float
        Useful energy demand of 'hd_typ' for 'sector' (mean value of all construction periods)

    """
    assert nuts0.lower() in set(building_stock.country_code), \
    f"The Region:<{nuts0}> is not available in the building stock dataset"

    assert sector in set(building_stock.sector), \
    f"The Sector:<{sector}> is not available in the building stock dataset"

    assert btype in set(building_stock.btype),\
    f"The building type:<{btype}> is not available in the building stock dataset"

    if type(bage) != type(None):
        assert bage in set(building_stock.bage),\
        f"The building age:<{bage}> is not available in the building stock dataset"

    df = grp_bdstock.get_group((nuts0.lower(),sector,hd_typ))
    if type(bage) == type(None):
        value = df[df.subsector == btype].value.mean()
    else:
        value = df[ (df.bage == bage) & (df.subsector == btype) ].value.mean() # mean only to get a float type scalar
    return value
# =============================================================================
def get_ued(nuts0,sector,hd_typ,gfa,bage=None,btype="Total"):
    """ This function return the anual useful energy demand in kWH

    Based on the list 'hd_type' the specific usful energy demands(ued) are accumulated
    and then multiplied by the 'gfa' to get the ued in kWh

    Parameters
    ----------
    nuts0: string
        {'at', 'be', 'bg', 'cy', 'cz', 'de', 'dk', 'ee', 'es', 'eu28', 'fi',
        'fr', 'gr', 'hr', 'hu', 'ie', 'it', 'lt', 'lu', 'lv', 'mt', 'nl', 'pl',
        'pt', 'ro', 'se', 'si', 'sk', 'uk'}

    sector: string
        {'Residential sector', 'Service sector'}

    hd_type: list
        a list that can contain the following entries
        {"Space heating [kWh/m² year]","Domestic hot water  [kWh/m² year]",
        "Space cooling [kWh/m² year"}

    gfa: float
        Gross floor are in m²

    Returns
    -------
    ued: float
        the anual useful energy demand in kWh

    """
    sector = f"{sector} sector"

    # Accumulate Useful Energy Demand in kWh/(m²a)
    ued = sum([get_value(nuts0,sector,hd_type,bage=bage,btype=btype) for hd_type in hd_typ]) if type(hd_typ) == list else get_value(nuts0,sector,hd_typ,bage=bage,btype=btype)

    # Useful Energy Demand in kWh/a
    ued = gfa * ued

    return ued
# =============================================================================
def get_profile(nuts_code,sector,typ,input_path=path_load_profiles):
    return pd.read_csv(input_path.joinpath(sector,typ,f"{nuts_code}.csv")).load.values

def get_peaks(nuts_code,sector,input_path=path_load_profiles):
    sh = get_profile(nuts_code,sector,"space_heating",input_path=input_path)
    hw = get_profile(nuts_code,sector,"hot_water",input_path=input_path)
    arg_max_sh = sh.argmax()
    f_sh = sh[arg_max_sh]
    f_hw = hw[arg_max_sh]
    return f_sh,f_hw
# =============================================================================
def lcoh(energy_demand, heat_load, energy_price,
                            specific_investment_cost, fix_o_and_m, var_o_and_m,
                            efficiency_heatingsystem, r, lt):
    """ This function calculates the Levelized Costs of Heating for a heating
    system that has constant variable costs and heat production over its life time

    Parameters
    ----------
    energy_demand: float-like
        in kWh

    heat_load: float-like
        in kW

    energy_price: float-like
        EUR/kWh

    specific_investment_cost: float-like
        inEUR/kW

    fix_o_and_m: float-like
        in EUR/kW

    var_o_and_m: float-like
        in EUR/kWh

    efficiency_heatingsystem: float-like

    r: float-like
        -

    lt: float-like
        in year

    Returns
    -------
    output: dict

    """
    q = 1 + r
    assert q != 0 or q != 1 ,"Error in calculation annuity factor ! Please choose an other interest rate."
    annuity_factor = (1-q**lt)/(q**lt*(1-q))

    # final energy demand (kWh)
    if efficiency_heatingsystem == 0:
        fed = efficiency_heatingsystem
    else:
        fed = energy_demand / efficiency_heatingsystem

    # OPEX: Operational Expenditure (EUR)
    OPEX = fix_o_and_m * heat_load + var_o_and_m * fed * 1e-3 ## 1e-3 becaues var_o_and_m to high

    # CAPEX: Capital Expenditure (EUR)
    CAPEX = heat_load * specific_investment_cost
    # energy costs (EUR)
    energy_costs = fed * energy_price
    # total costs heat supply (EUR)
    OPEX_ = annuity_factor * (OPEX + energy_costs)

    present_value = OPEX_ + CAPEX

    # LCOH [EUR/kWh]
    energy_demand_ = (energy_demand * annuity_factor)
    if energy_demand == 0:
        lcoh = 0
    else:
        lcoh = present_value / energy_demand_

    output = {'Final energy demand': float(fed),
              'Capital Expenditure (CAPEX)': float(CAPEX/annuity_factor),
              'Operational Expenditure (OPEX)': float(OPEX),
              "OPEX * annuity_factor": float(OPEX_),
              'Energy costs': float(energy_costs),
              'Total costs': float(CAPEX/annuity_factor)+float(OPEX) + float(energy_costs),
              "energy_demand * annuity_factor":float(energy_demand_),
              "energy_demand":float(energy_demand),
              'Levelized costs of heat': float(lcoh),
              "capex":CAPEX/energy_demand_,
              "opex":OPEX_/energy_demand_,
              "specific_investment_cost":specific_investment_cost,
              "heat_load":heat_load,
              "fed":fed,
              "opex_fix_":annuity_factor*fix_o_and_m * heat_load/energy_demand_,
              "opex_var_":annuity_factor*var_o_and_m * fed/energy_demand_,
              "opex_":annuity_factor*OPEX/energy_demand_,
              "energy_costs_":annuity_factor *energy_costs/energy_demand_,
              "anuity_factor":annuity_factor,
              "energy_demand_":energy_demand_,
              "efficiency_heatingsystem":efficiency_heatingsystem,
              "energy_price":energy_price,
              "fix o&m ": fix_o_and_m,
              "var o%m" : var_o_and_m}
    return output
# =============================================================================
if input_data_path not in sys.path:
    sys.path.append(input_data_path)
from mapper import setNav_code_map,fuel_type_map,data_electric_heating,data_solar_thermal
def get_energy_price(nuts0,tec,year,sector='Residential',
                     tax='Including tax but no VAT',
                     setNav_code_map=setNav_code_map,
                     grp_energy_prices=grp_energy_prices,
                     setNav_retail_energy_prices=setNav_retail_energy_prices):
    """This function returns the retail energy prices in EUR/kWh for a specific
    NUTS0 region, year and Technology

    The data behind come from the SetNav Project

    Parameters
    ----------

    Returns
    -------

    """
    assert nuts0 in setNav_code_map.keys(), \
    f"The Region <{nuts0} is not in the retail price dataset"
    assert sector in set(setNav_retail_energy_prices.Sector), \
    f"The sector <{sector}> is not in the retail energy price dataset"
    assert tax in set(setNav_retail_energy_prices.Tax), \
    f"There is no value <{tax}> in the tax column in the retail energy price dataset"
    assert f"Y{year}" in set(setNav_retail_energy_prices.columns),\
    f"No data for the year {year} in the retail energy price dataset"
    assert tec in fuel_type_map.keys(), \
    f"No Energy Carriere specified for the technology: <{tec}>"

    df = grp_energy_prices.get_group((setNav_code_map[nuts0],sector,tax))
    df = df.set_index(df["Energy Carrier"])
    ec = fuel_type_map[tec]
    year = f"Y{year}"

    energy_price = 0 if ec == "solar" else df.loc[ec,year] * 0.0036 # factor for EUR/GJs -> EUR/kWh

    return energy_price
# =============================================================================
def get_tec_data(df,tec,heat_load,nuts0,building_typ):
    """This function return the data for the heating system in a specifc NUTS 0
    region, year and sector

    Parameters
    ----------
    df: pandas.DataFrame
        Prefiltered data by nuts0 region,building type and year

    tec: Heating System
        {"Oil boiler","HP Brine-to-Water","Wood stove","Bio-oil boiler",
        "HP Air-to-Water","Electric heater","Solar thermal","Biomass_Manual",
        "HP Air-to-Air","Biomass_Automatic","Natural gas"}

    Returns
    -------

    """
    financ_data_columns = ['variable_O_and_M', 'technical_lifetime',
                   'total_annual_net_efficiency', 'k1_specific_investment_costs',
                   'k2_specific_investment_costs', 'k1_fixed_O_and_M',
                   'k2_fixed_O_and_M']

    var_o_and_m, lifetime, efficiency, k1_specific_investment_cost, \
    k2_specific_investment_cost, k1_fix_o_and_m, k2_fix_o_and_m = df.loc[tec,financ_data_columns]
    # specific investment cost in EUR/kW

    p_min_invert = get_pmin(nuts0,tec)

    if math.isnan(var_o_and_m):
#        print(f"No Variable Operational and Maintance Costs for <{tec}> in country <{nuts0}>, ...using 0 as default")
        var_o_and_m = 0
    if tec == "Solar thermal" and math.isnan(efficiency):
        efficiency = 1

    if tec == "Electric heater":
        index = df.loc[tec,"equipment_and_maintenance_index"]
        k1_fix_o_and_m = data_electric_heating.loc[int(df.year[tec]),"k1"]*index
        k2_fix_o_and_m = data_electric_heating.loc[int(df.year[tec]),"k2"]

    if heat_load < p_min_invert:
        heat_load = p_min_invert

#    if tec == "Solar thermal":
#        index = df.loc[tec,"equipment_and_maintenance_index"]
#        data=data_solar_thermal.groupby(["building_typ","financ_typ"]).get_group((building_typ,"o&m fixed"))
#        k1_fix_o_and_m = data.loc[int(df.year[tec]),"k1"]*index
#        k2_fix_o_and_m = data.loc[int(df.year[tec]),"k2"]
#
#        index = df.loc[tec,"price_index_households_appliances"]
#        data=data_solar_thermal.groupby(["building_typ","financ_typ"]).get_group((building_typ,"invest"))
#
#        k1_specific_investment_cost = data.loc[int(df.year[tec]),"k1"]*index
#        k2_specific_investment_cost = data.loc[int(df.year[tec]),"k2"]
#

    k1_specific_investment_cost, k2_specific_investment_cost = \
    xor(k1_specific_investment_cost, k2_specific_investment_cost,tec,
        "invest",nuts0)

    specific_investment_cost = k1_specific_investment_cost * (heat_load**k2_specific_investment_cost)
    if specific_investment_cost == float("nan"):
        assert False,f"Error: No specific investment costs for {tec}, {nuts0}"

    k1_fix_o_and_m, k2_fix_o_and_m = xor(k1_fix_o_and_m, k2_fix_o_and_m,tec,
                                         "maintainance",nuts0)

    fix_o_and_m = k1_fix_o_and_m * (heat_load**k2_fix_o_and_m)
    if fix_o_and_m == float("nan"):
        assert False,f"Error: No fixed operational and maintainance costs for {tec}, {nuts0}"

    return specific_investment_cost,fix_o_and_m,var_o_and_m,efficiency,lifetime,heat_load
# =============================================================================
def lcoh_per_tec(r,nuts0,building_typ,year,heating_energy_demand,heat_load,
                 grp_financ_heating_tec=grp_financ_heating_tec,
                 financ_heating_tec = financ_heating_tec):
    """This function calculates the LCOH for each technology and specific
    building type at a specific year for a NUTS0 region

    Parameters
    ----------

    Returns
    -------

    """
    assert type(year) == int, f"The Year <{year}> is not an interger"
    assert year in set(financ_heating_tec.year), \
    f"The year:<{year}> is not available in the financal dataset for heating systems"
    assert building_typ in set(financ_heating_tec.type_of_building),\
    f"The bulding type:<{building_typ}> is not available in the financal dataset for heating systems"

    df = grp_financ_heating_tec.get_group((nuts0,building_typ,year))
    df = df.set_index(df.heating_equipment)
    df = df.drop(["DH substation","Solar thermal"])
#    df = df.drop(["Bio-oil boiler"]) # XXX: No fuel prices for bio oil , therefore drop this heating system
    out = dict()
    for tec in df.index:
        #XXX: heat_load2
        specific_investment_cost,fix_o_and_m,var_o_and_m,efficiency,lifetime,heat_load2 = \
            get_tec_data(df,tec,heat_load,nuts0,building_typ.split(" ")[0].strip())

        energy_price = get_energy_price(nuts0,tec,year)

        out[tec] = lcoh(heating_energy_demand, heat_load2,
                       energy_price, specific_investment_cost, fix_o_and_m,
                       var_o_and_m, efficiency, r, lifetime)
    return out
# =============================================================================
#
# =============================================================================
def get_nuts(nuts_code):
    nuts3 = nuts_code[:5]
    nuts2 = nuts_code[:4]
    nuts1 = nuts_code[:3]
    nuts0 = nuts_code[:2]
    return nuts3,nuts2,nuts1,nuts0

@catch_assertion_errors
def main(nuts_code,sav,gfa,year,r,bage,btype,*ef_args):
    sav = sav/100
    serv = ['Trade', 'Other non-residential buildings', 'Hotels and Restaurants', 'Offices', 'Health', 'Education']
    res=['Multifamily houses', 'Single family- Terraced houses', 'Appartment blocks']
    building_types = dict(zip(res+serv,['existing MFH','existing SFH','existing MFH']+['existing MFH'] * len(serv)))
    sector_mapper = {**dict(zip(serv,["Service"]*len(serv))),**dict(zip(res,["Residential"]*len(res)))}
    sector = sector_mapper[btype]
    building_type = building_types[btype]
    if sav*100 > 0:
        building_type=building_type.replace("existing","new")
    _nuts3,nuts2,nuts1,nuts0 = get_nuts(nuts_code)
    ued_sh = get_ued(nuts0,sector,"Space heating [kWh/m² year]",gfa,bage,btype) # spcae heating demand kWh
    ued_hw = get_ued(nuts0,sector,"Domestic hot water  [kWh/m² year]" ,gfa,bage,btype) # hot water demand kWh
    f_sh,f_hw = get_peaks(nuts2,f"{sector.lower()}_sector")  # pmax factor in 1/h
    heat_load_sh = ued_sh*f_sh*(1-sav)  # Pmax in kW
    heat_load_hw = ued_hw*f_hw  # Pmax in kW
    heat_load = 1.2*(heat_load_sh + heat_load_hw)   # Pmax in kW
    ued = ued_sh*(1-sav) + ued_hw
    if nuts0 == "CH":
        nuts0="AT"
    result = lcoh_per_tec(r,nuts0,building_type,year,ued,heat_load)
    return result,(ued,heat_load,building_type,sector),True

if __name__ == "__main__":
    print("Calculation started")
# =============================================================================
# %%  User-Input
# =============================================================================
    nuts_code = "DK032"
    sav = 0 # savings in % [0,1]
    gfa = 1000  # Gross Floor Area in m²
    year = 2015 # int
    r = 0.03 # interest rate
    bage = "Before 1945" # None for mean value
    btype = "Multifamily houses" # "Total" for mean value
# =============================================================================
#%%   "Algorithm"
# =============================================================================
    results,inputs,ok = main(nuts_code=nuts_code,sav=sav,gfa=gfa,year=year,r=r,bage=bage,btype=btype)

# =============================================================================
#
# =============================================================================
    print("Calculation Done")


#!/usr/bin/env python3
import os
import argparse
import shutil
import sys

def main(sourses, dir, recursive=False):
    '''
    Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.
    '''
    for sourse in sourses:
        if recursive:
            shutil.copytree(sourse, dir)

        else:
            try:
                shutil.copy2(sourse, dir)

            except OSError:
                if not os.path.isfile(sourse):
                    sys.stdout.write('SOURCE is a DIRECTORY. Use --recursive option.\n')

if __name__ == '__main__':
    """
    Show help message: -h, -- help.
    """
    desc_one = 'Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.'

    parser = argparse.ArgumentParser(description=desc_one)

    parser.add_argument("-r", "--recursive", help="copy directories recursively to DIRECTORY", action="store_true")
    parser.add_argument("SOURCE", nargs='+', help="SOURCE path")
    parser.add_argument("DIRECTORY", help="DIRECTORY or DESTINATION path.")
    args = parser.parse_args()

    main(recursive=args.recursive,
         sourses=args.SOURCE,
         dir=args.DIRECTORY)


#python 3
#bin/instance stop; bin/instance run  find_havn_etc.py  -O skipshistorie

#import pandas as pd
#import openpyxl
from zope.lifecycleevent import modified
import plone.api
from zope.component.hooks import setSite
from plone.app.textfield import RichText
from plone.app.textfield.value import RichTextValue
from plone.rfc822.interfaces import IPrimaryFieldInfo
from zope.lifecycleevent import modified
import transaction
from bs4 import BeautifulSoup
import re

setSite(app['skipshistorie'])

folders = app.skipshistorie.portal_catalog(portal_type="Folder", sort_on="modified", sort_order='ascending')

for folder in folders:

	#import pdb; pdb.set_trace()

	rederinummer = folder.getObject().rederinummer

	if rederinummer:

		brains = plone.api.content.find(context=folder.getObject(), portal_type="Document")
		if brains:
			ant = 0

			for brain in brains:
				obj = brain.getObject()
				if not obj.vessel:
					primary_field = IPrimaryFieldInfo(obj)
					if isinstance(primary_field.field, RichText):
						if obj.text:
							oldtext = obj.text.raw
							soup = BeautifulSoup(oldtext, 'html.parser')

							#import pdb; pdb.set_trace()
							#look_for = '(' + rederinummer

							for elem in soup(text=re.compile(r'\(' + rederinummer)):
								#import pdb; pdb.set_trace()
								words = elem.strip().split(' ')
								#tittel = words[1] + ' '.join(words[2:-2]).title().replace("  ", " ")
								#obj.setTititle(tittel)
								#tittel = tittel.replace(" ", "")
								#obj.year = int(words[0])
								obj.vessel = words[-1].replace("(", "").replace(")", "")
								#import pdb; pdb.set_trace()
								print(obj.vessel)
								#text_element = elem.find_parent('tr')
								#text_element['class'] = 'scraped'

								obj.text = RichTextValue(str(soup))
								ant = ant + 1
								modified(obj)
								if ant % 100 == 1:
									print('transaction')
									transaction.commit()

							#transaction.commit()
							#modified(obj)

transaction.commit()


import zounds
import torch
from torch import nn
from modules.linear import LinearOutputStack
from modules.pif import AuditoryImage
from train.optim import optimizer
from util import device, playable
from util.readmedocs import readme
from torch.nn import functional as F

from util.weight_init import make_initializer

n_samples = 2 ** 15
samplerate = zounds.SR22050()

atom_size = 512
n_atoms = 512

kernel_size = 128
n_bands = 128

model_dim = 128

atoms_to_keep = 256

sample_index_factor = n_samples // 128

band = zounds.FrequencyBand(40, samplerate.nyquist)
scale = zounds.MelScale(band, n_bands)
fb = zounds.learn.FilterBank(
    samplerate,
    kernel_size,
    scale,
    0.1,
    normalize_filters=True,
    a_weighting=False).to(device)

aim = AuditoryImage(512, 128, do_windowing=False, check_cola=False)

init_weights = make_initializer(0.1)

def perceptual_feature(x):
    # x = fb.forward(x, normalize=False)
    # x = aim.forward(x)
    return x

def perceptual_loss(a, b):
    a = perceptual_feature(a)
    b = perceptual_feature(b)
    loss = F.mse_loss(a, b)
    return loss

class DilatedBlock(nn.Module):
    def __init__(self, channels, dilation):
        super().__init__()
        self.dilated = nn.Conv1d(
            channels, channels, 3, padding=dilation, dilation=dilation)
        self.conv = nn.Conv1d(channels, channels, 1, 1, 0)

    def forward(self, x):
        orig = x
        x = self.dilated(x)
        x = self.conv(x)
        x = x + orig
        x = F.leaky_relu(x, 0.2)
        return x

class SparseAudioModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.reduce = LinearOutputStack(
            model_dim, 3, in_channels=257, out_channels=8)
        self.conv = nn.Conv1d(model_dim * 8, model_dim, 1, 1, 0)

        self.atoms = nn.Parameter(torch.zeros(
            n_atoms, atom_size).uniform_(-1, 1))

        self.context = nn.Sequential(
            DilatedBlock(model_dim, 1),
            DilatedBlock(model_dim, 3),
            DilatedBlock(model_dim, 9),
        )

        self.up = nn.Sequential(
            nn.Upsample(scale_factor=4),
            nn.Conv1d(model_dim, model_dim, 7, 1, 3),
            nn.LeakyReLU(0.2),

            nn.Upsample(scale_factor=4),
            nn.Conv1d(model_dim, model_dim, 7, 1, 3),
            nn.LeakyReLU(0.2),

            nn.Upsample(scale_factor=4),
            nn.Conv1d(model_dim, model_dim, 7, 1, 3),
            nn.LeakyReLU(0.2),

            nn.Upsample(scale_factor=4),
            nn.Conv1d(model_dim, n_atoms, 7, 1, 3),
        )

        self.to_values = nn.Conv1d(n_atoms, n_atoms, 1, 1, 0)
        self.apply(init_weights)

    def unit_norm_atoms(self):
        norms = torch.norm(self.atoms, dim=-1, keepdim=True)
        atoms = self.atoms / (norms + 1e-12)
        return atoms

    def orthogonal_loss(self):
        x = self.unit_norm_atoms().view(n_atoms, atom_size)
        sim = x @ x.T
        return sim.mean()

    def forward(self, x):
        x = fb.forward(x, normalize=False)
        x = aim.forward(x)
        x = self.reduce(x)
        x = x.permute(0, 3, 2, 1).reshape(-1, model_dim * 8, 128)
        x = self.conv(x)
        x = self.context(x)
        x = self.up(x)

        # v = torch.abs(self.to_values(x).view(x.shape[0], -1))

        # x = torch.softmax(x, 1)
        x = x.view(x.shape[0], -1)
        values, indices = torch.topk(x, atoms_to_keep, dim=-1)
        # v = torch.gather(v, -1, indices)
        v = values

        output = torch.zeros(x.shape[0], n_atoms * n_samples).to(device)
        output = output.scatter(-1, indices, v)
        output = output.reshape(-1, n_atoms, n_samples)

        norms = torch.norm(self.atoms, dim=-1, keepdim=True)
        atoms = self.atoms / (norms + 1e-8)
        atoms = atoms.reshape(n_atoms, 1, atom_size)

        output = F.pad(output, (0, 1))
        output = F.conv_transpose1d(output, atoms, padding=atom_size // 2)

        return output

model = SparseAudioModel().to(device)
optim = optimizer(model, lr=1e-4)

def train(batch):
    optim.zero_grad()
    result = model.forward(batch)
    loss = perceptual_loss(result, batch) + model.orthogonal_loss()
    loss.backward()
    optim.step()
    return loss, result

@readme
class SparseAudioExperiment(object):
    def __init__(self, stream):
        super().__init__()
        self.stream = stream
        self.real = None
        self.fake = None

    def r(self):
        return playable(self.real, samplerate)

    def listen(self):
        return playable(self.fake, samplerate)

    def run(self):
        for i, item in enumerate(self.stream):
            item = item.view(-1, 1, n_samples)
            self.real = item
            loss, self.fake = train(item)

            print(loss.item())


import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.transforms as transforms
from PIL import Image
import io

class CNN(nn.Module):
  def __init__(self):
    super().__init__()
    self.conv1 = nn.Conv2d(3, 6, 5)
    self.pool = nn.MaxPool2d(2, 2)
    self.conv2 = nn.Conv2d(6, 16, 5)
    self.fc1 = nn.Linear(16 * 5 * 5, 120)
    self.fc2 = nn.Linear(120, 84)
    self.fc3 = nn.Linear(84, 4)

  def forward(self, x):
    x = self.pool(F.relu(self.conv1(x)))
    x = self.pool(F.relu(self.conv2(x)))
    x = torch.flatten(x, 1)
    x = F.relu(self.fc1(x))
    x = F.relu(self.fc2(x))
    x = self.fc3(x)
    return x

transform_prediction = transforms.Compose([transforms.Resize((32,32)),
                                        transforms.CenterCrop(32),
                                        transforms.Grayscale(num_output_channels=3),
                                        transforms.ToTensor()])

caminho_modelo = 'static\modelo.pth'
model = CNN()
model.load_state_dict(torch.load(caminho_modelo))
model.eval()
learning_rate = 0.01
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

def verifica_imagem(imagem_PIL):
  imagem = transform_prediction(imagem_PIL).unsqueeze(dim=0).to(device)
  prediction = model(imagem)
  resultado = str(torch.argmax(prediction))
  resultados = {
    "tensor(0)": "Fusível",
    "tensor(1)": "Relé",
    "tensor(2)": "Capacitor Eletrolítico",
    "tensor(3)": "LED"
  }
  return resultados.get(resultado, "Nenhum")

def quantos_verificou(lista_blocos_PIL):
    fusivel = 0
    rele = 0
    capacitor = 0
    led = 0
    lista = []

    for i in range(len(lista_blocos_PIL)):
        result = verifica_imagem(lista_blocos_PIL[i])
        if result=="Fusível":
            fusivel = fusivel+1
        elif result=="Relé":
            rele = rele+1
        elif result=="Capacitor Eletrolítico":
            capacitor = capacitor+1
        elif result=="LED":
            led = led+1

    lista.append(fusivel)
    lista.append(rele)
    lista.append(capacitor)
    lista.append(led)

    return lista

def transform_image(image):
    transform_prediction = transforms.Compose([transforms.Resize((32,32)),
                                            transforms.CenterCrop(32),
                                            transforms.Grayscale(num_output_channels=3),
                                            transforms.ToTensor()])

    # image = Image.open(io.BytesIO(image_bytes))
    return transform_prediction(image).unsqueeze(0)


##This file uses a fabricated data set to answer health questions about fictitious patients. The data is included in csv file format in this folder.
#The question this script seeks to answer is:  Is there a relationship between the number of cigarettes smoked per day and the prevalence of diabetes?
#Run a statistical test to determine significance, interpret the results and create a visualization to display this.
import csv
import numpy as np
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
#access patient_history file Please modify this file path to reflect where the patient_history file is stored on your machine. Note the use of double backslashes to avoid any runtime error
patient_history_file = csv.reader(open('C:\\Users\\JTena\\OneDrive\\Documents\\data_split\\data_split\\patient_history.csv'), delimiter = ",")
#create lists for cigs per day and diabetes
cigs_per_day = []
diabetes = []
#compile the lists from the file
for row in patient_history_file:
  if(row[2] == "cigsPerDay"):
    continue
  if(row[2] == ""):
    continue
  if(row[6] == "diabetes"):
    continue
  if(row[6] == ""):
    continue
  cigs_per_day.append(float(row[2]))
  diabetes.append(float(row[6]))

print(cigs_per_day)
print(diabetes)
#define dependent and independent variables and put them into a numpy array
x = np.array(diabetes).reshape((-1, 1))
y = np.array(cigs_per_day)
#perform linear regression to use the linear probability model. Here a logistic regression could also be done.
model = LinearRegression().fit(x, y)
r_sq = model.score(x, y)
print(f"coefficient of determination: {r_sq}")
#In this case the r value is 0.001340809154176858. This value is essentially zero, so there is no real linear relationship
plt.scatter(x, y, color="black")


# -*- coding: utf-8 -*-
"""Panel for PhononWorkchain plugin.

Authors:

    * Miki Bonacci <miki.bonacci@psi.ch>
    Inspired by Xing Wang <xing.wang@psi.ch>
"""
import ipywidgets as ipw
import traitlets as tl

from aiidalab_qe.common.panel import Panel
from IPython.display import clear_output, display

class Setting(Panel):
    title = "Vibrational Settings"

    def __init__(self, **kwargs):
        self.settings_title = ipw.HTML(
            """

Settings

"""
        )
        self.settings_help = ipw.HTML(
            """

            Calculations are performed using the aiida-vibroscopy plugin (L. Bastonero and N. Marzari, Automated all-functionals infrared and Raman spectra).

            The plugin employes the finite-displacement and finite-field approach, for Phonon dispersion please select a supercell size:
            the larger the supercell, the larger the computational cost of the simulations. Usually, a 2x2x2 supercell should be enough.

"""
        )

        self.use_help = ipw.HTML(
            """

            The plugin is capable to run the following calculations:

• IR/Raman spectrum.

• Phonon band dispersion.

• Phonon Projected Density of States.

• Thermal Properties.

• Dielectric Properties.

"""
        )

        self.polar_help = ipw.HTML(
            """

            If the material is polar, more
            accurate phonon properties interpolation is performed.

"""
        )

        self.workchain_protocol = ipw.ToggleButtons(
            options=["fast", "moderate", "precise"],
            value="moderate",
        )

        self.calc_options = ipw.Dropdown(
            description="Calculation:",
            options=[
                ["Raman spectrum", "raman"],
                ["IR spectrum", "ir"],
                ["Phonons Bands", "ph_bands"],
                ["Phonons Pdos", "ph_pdos"],
                ["Thermal properties", "ph_therm"],
                ["Dielectric properties", "dielectric"],
            ],
            value="raman",
            style={"description_width": "initial"},
        )

        self.supercell_out = ipw.Output()

        # start Supercell
        self.supercell = [2, 2, 2]

        def change_supercell(_=None):
            self.supercell = [
                self._sc_x.value,
                self._sc_y.value,
                self._sc_z.value,
            ]

        for elem in ["x", "y", "z"]:
            setattr(
                self,
                "_sc_" + elem,
                ipw.BoundedIntText(
                    value=2, min=1, layout={"width": "40px"}, disabled=False
                ),
            )
        for elem in [self._sc_x, self._sc_y, self._sc_z]:
            elem.observe(change_supercell, names="value")
        self.supercell_selector = ipw.HBox(
            children=[
                ipw.HTML(
                    description="Supercell size:",
                    style={"description_width": "initial"},
                )
            ]
            + [
                self._sc_x,
                self._sc_y,
                self._sc_z,
            ],
        )

        self.supercell_widget = ipw.HBox(
            [self.supercell_selector],
            layout=ipw.Layout(justify_content="flex-start"),
        )
        # end Supercell.

        # to trigger Dielectric property = Raman... FOR POLAR MATERIALS.
        self.material_is_polar_ = ipw.ToggleButtons(
            options=[("Off", "off"), ("On", "on")],
            value="off",
            style={"description_width": "initial"},
        )
        # self.material_is_polar_.observe(self._onclick_material_is_polar, "value")
        self.calc_options.observe(self._display_supercell, names="value")
        self.children = [
            self.settings_title,
            self.settings_help,
            self.use_help,
            ipw.HBox(
                [
                    self.calc_options,
                    self.supercell_out,
                ]
            ),
            self.polar_help,
            ipw.HBox(
                children=[
                    ipw.Label(
                        "Material is polar:",
                        layout=ipw.Layout(justify_content="flex-start", width="120px"),
                    ),
                    self.material_is_polar_,
                ]
            ),
        ]
        super().__init__(**kwargs)

    def _display_supercell(self, change):
        selected = change["new"]
        if selected in ["ph_bands", "ph_pdos", "ph_therm"]:
            with self.supercell_out:
                clear_output()
                display(self.supercell_widget)
        else:
            with self.supercell_out:
                clear_output()

    def get_panel_value(self):
        """Return a dictionary with the input parameters for the plugin."""
        if isinstance(self.calc_options, str):
            return {
                "calc_options": self.calc_options,
                "material_is_polar": self.material_is_polar_.value,
                "supercell_selector": self.supercell,
            }
        return {
            "calc_options": self.calc_options.value,
            "material_is_polar": self.material_is_polar_.value,
            "supercell_selector": self.supercell,
        }

    def load_panel_value(self, input_dict):
        """Load a dictionary with the input parameters for the plugin."""
        self.material_is_polar_.value = input_dict.get("material_is_polar", "off")
        self.calc_options.value = input_dict.get("calc_options", "raman")
        self.supercell = input_dict.get("supercell_selector", [2, 2, 2])

    def reset(self):
        """Reset the panel"""
        self.material_is_polar_.value = "off"
        if isinstance(self.calc_options, str):
            self.calc_options = "raman"
        else:
            self.calc_options.value = "raman"
        self.supercell = [2, 2, 2]