from vendor.models import Vendor
from accounts.models import UserProfile
from django.conf import settings

def get_vendor(request):
    try:
        vendor = Vendor.objects.get(user=request.user)
    except:
        vendor = None

    data = {
        "vendor": vendor,
    }
    return data

def get_userprofile(request):
    try:
        user_profile = UserProfile.objects.get(user=request.user)
    except:
        user_profile = None

    data = {
        "user_profile": user_profile,
    }
    return data

def get_paypal_client_id(request):
    return {"PAYPAL_CLIENT_ID": settings.PAYPAL_CLIENT_ID}


from azure.storage import CloudStorageAccount
from azure.storage.blob import BlockBlobService, PublicAccess, AppendBlobService

from pathlib import Path
from utils.setting import setting as s
import json, csv, datetime, os, pyodbc, datetime

class log():
    def __init__(self, meterInfo):
        self.MeterInfo = meterInfo
        self.fileName = ''

    def progress_callback_w(self, current, total):

        if current == total:
            try:
                os.remove(self.fileName)
            except:
                pass

    def saveLogToCSV(self, siteName, logdate):
        '''
        return filename
        '''

        fileName = '%s_reset-log_%s.csv' % (siteName, logdate)
        self.fileName = fileName.replace(":","-")

        header = []
        for key in self.MeterInfo.keys():
            header.append(key)

        mode = 'a' if Path(self.fileName).exists() else 'w'
        with open(self.fileName, mode , newline='') as mFile:
        	out = csv.DictWriter(mFile, dialect='excel', fieldnames=header, delimiter=';', quoting=csv.QUOTE_MINIMAL)
        	if mode=='w':
        		out.writeheader()
        	out.writerow(self.MeterInfo)
        return self.fileName

    def saveCsvLogToBlob(self, fileName):

        to_location_path = fileName

        account_name = s().Data["blob"]["account_name"]
        account_key = s().Data["blob"]["account_key"]
        container_name = s().Data["blob"]["container"]

        cloud_account = CloudStorageAccount( account_name = account_name, account_key = account_key )

        append_blob_service = cloud_account.create_append_blob_service()
        append_blob_service.create_container(container_name)
        append_blob_service.set_container_acl( container_name, public_access = PublicAccess.Container )

        if append_blob_service.exists(container_name, self.fileName):
            append_blob_service.append_blob_from_path(container_name, self.fileName, self.fileName, progress_callback = self.progress_callback_w)
        else:
            cloud_account.create_block_blob_service().create_blob_from_path(container_name, self.fileName, to_location_path, progress_callback = self.progress_callback_w)

    def saveCSVtoSQLDB(self, siteName):
        cnxn = pyodbc.connect(s().Data['mssql'])
        cursor = cnxn.cursor()
        query = '''
                        Insert into SPARKMETER_RESET_PROTECT_LOG
                        (
                            [address]
                            ,[current_avg]
                            ,[current_max]
                            ,[current_min]
                            ,[energy]
                            ,[frequency]
                            ,[ground_name]
                            ,[ground_serial]
                            ,[heartbeat_end]
                            ,[serial]
                            ,[state]
                            ,[true_power_inst]
                            ,[uptime]
                            ,[user_power_limit]
                            ,[voltage_avg]
                            ,[voltage_max]
                            ,[voltage_min]
                            ,[access_user]
                            ,[reset_datetime_utc])
                        values(
                            '%s',
                            %s,
                            %s,
                            %s,

                            %s,
                            %s,
                            '%s',
                            '%s',

                            '%s',
                            '%s',
                            '%s',
                            %s,

                            %s,
                            %s,
                            %s,
                            %s,

                            %s,
                            '%s',
                            '%s0'

                        )
                       ''' % (
                            self.MeterInfo["address"],
                            self.MeterInfo["current_avg"],
                            self.MeterInfo["current_max"],
                            self.MeterInfo["current_min"],

                            self.MeterInfo["energy"],
                            self.MeterInfo["frequency"],
                            self.MeterInfo["ground_name"],
                            self.MeterInfo["ground_serial"],

                            self.MeterInfo["heartbeat_end"],
                            self.MeterInfo["serial"],
                            self.MeterInfo["state"],
                            self.MeterInfo["true_power_inst"],

                            self.MeterInfo["uptime"],
                            self.MeterInfo["user_power_limit"],
                            self.MeterInfo["voltage_avg"],
                            self.MeterInfo["voltage_max"],

                            self.MeterInfo["voltage_min"],
                	        s().Data['program_name'],
                	        datetime.datetime.utcnow().isoformat()
                           )
        cursor.execute(query)

        cursor.commit()


"""
URL configuration for hsauth project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""

from django.urls import path
import auth.views
import publicinfo.views

urlpatterns = [
    path('api/auth/register/',auth.views.register),
    path('api/auth/login/',auth.views.login),
    path('api/auth/islogin/',auth.views.islogin),
    path('api/auth/email_otp/',auth.views.email_otp),
    path('api/auth/reset/',auth.views.auth_reset),
    path('api/public/upload_avatar/',publicinfo.views.upload_avatar),
    path('api/public/get_info/',publicinfo.views.get_info),
    path('api/public/update_info/',auth.views.update_info),
    path('api/public/insert_info/',auth.views.insert_info),
    path('api/public/select_info/',auth.views.select_info),
]


import requests
import json
import os

token=os.environ["token"]
url_base="https://soccer.sportmonks.com/api/v2.0/"
payload={'api_token':token}

print("BÚSQUEDA DE JUGADORES\n")
jugador=input("Introduce el nombre de un jugador: ")

url=url_base+"players/search/"+jugador

r=requests.get(url,params=payload)
if r.status_code == 200:
    datos=r.json()
    jugadores=[]
    for jugador in datos.get("data"):
        jugadores.append(jugador.get("display_name"))

    if len(jugadores)>1:
        encontrado=True
        print("\nLISTA DE JUGADORES ENCONTRADOS:\n")
        for var in jugadores:
            print("-",var)
        jugador=input("\nIntroduce el nombre de uno de los jugadores encontrados: ")
        while jugador not in jugadores:
            print("Debes escoger uno de los jugadores encontrados.")
            jugador=input("\nIntroduce el nombre de uno de los jugadores encontrados: ")

    elif len(jugadores)==1:
        encontrado=True
        print("\nJUGADOR ENCONTRADO:\n")
        for var in jugadores:
            print("-",var)
            jugador=var

    else:
        print("No se han encontrado jugadores con ese nombre.")
        encontrado=False

    if encontrado==True:
        print("\nEstadísticas de %s\n"%jugador)
        for var in datos.get("data"):
            if var.get("display_name")==jugador:
                print("- Nombre Completo: %s" %var.get("fullname"))
                print("- Nacionalidad: %s" %var.get("nationality"))
                print("- Fecha de nacimiento: %s" %var.get("birthdate"))
                print("- País de nacimiento: %s" %var.get("birthcountry"))
                print("- Lugar de nacimiento: %s" %var.get("birthplace"))
                print("- Altura: %s" %var.get("height"))

else:
    print("Error")
    print(r.status_code)


import datetime
import os

from nonebot import on_command
from nonebot.adapters import Bot, Event
from nonebot.typing import T_State
from nonebot.adapters.cqhttp import Message

from sqlalchemy import Column, Integer, String, BigInteger, Text, DateTime
from alchemical import Alchemical

db = Alchemical('sqlite:///ergo.sqlite')

class Note(db.Model):
    id = Column(Integer, primary_key=True)
    qq = Column(BigInteger)
    msg = Column(Text, nullable=False)
    add_time = Column(DateTime, default=datetime.datetime.now)

db.create_all()

note = on_command('note', priority=10, block=False)
note_all = on_command('noteall', priority=10, block=False)
note_my = on_command('notemy', priority=10, block=False)

@note.handle()
async def _(bot: Bot, event: Event, state: T_State):
    from_msg = str(event.get_message())
    if not from_msg:
        await note.send('请按照「/note 内容」来存东西')
        return
    sender = int(event.get_user_id())
    with db.begin() as session:
        session.add(Note(qq=sender, msg=from_msg))
    to_msg = Message([
        {
            'type': 'at',
            'data': {
                'qq': sender
            }
        },
        {
            'type': 'text',
            'data': {
                'text': f'已保存 {from_msg}'
            }
        }
    ])
    await note.send(to_msg)

@note_my.handle()
async def _(bot: Bot, event: Event, state: T_State):
    sender = int(event.get_user_id())
    with db.Session() as session:
        notes = session.scalars(Note.select().where(Note.qq == sender)).all()
        await note_my.send('\n'.join([f'{nt.msg} {nt.add_time}' for nt in notes]))


import os
import requests
import itertools
from twilio.rest import Client

STOCK = "TSLA"
COMPANY_NAME = "Tesla Inc"

twilio_account_sid = os.environ.get('ACCOUNT_SID')
twilio_auth_token = os.environ.get('AUTH_TOKEN')
twilio_phone_number = os.environ.get('TWILIO_PHONE_NUMBER')

PERSONAL_PHONE_NUMBER = os.environ.get('PERSONAL_PHONE_NUMBER')

AV_API_KEY = os.environ.get('AV_API_KEY')
NEWS_API_KEY = os.environ.get('NEWS_API_KEY')

STOCK_ENDPOINT = 'https://www.alphavantage.co/query'
NEWS_ENDPOINT = 'https://newsapi.org/v2/everything'

## STEP 1: Use https://www.alphavantage.co
# When STOCK price increase/decreases by 5% between yesterday and the day before yesterday then print("Get News").

parameters = {
    'function': 'TIME_SERIES_DAILY_ADJUSTED',
    'symbol': STOCK,
    'apikey': AV_API_KEY
}

response = requests.get(url=STOCK_ENDPOINT, params=parameters)
data = response.json()
daily_data = data['Time Series (Daily)']
two_day_data = dict(itertools.islice(daily_data.items(), 2))

two_day_close_price = []
two_day_dates_list = []

for date in two_day_data:
    two_day_dates_list.append(date)
    two_day_close_price.append(float(two_day_data[date]['4. close']))

close_diff = two_day_close_price[0] - two_day_close_price[1]
percent_change = (close_diff / two_day_close_price[1])

## STEP 2: Use https://newsapi.org
# Instead of printing ("Get News"), actually get the first 3 news pieces for the COMPANY_NAME.

news_api_parameters = {
    'q': STOCK,
    'from': two_day_dates_list[0],
    'sortBy': 'popularity',
    'apikey': NEWS_API_KEY
}

news_response = requests.get(url=NEWS_ENDPOINT, params=news_api_parameters)
news_data = news_response.json()

articles = news_data['articles'][:3]

substantial_change = False

if percent_change < -.03 or percent_change > .03:
    substantial_change = True
    print('Substantial Change is TRUE')

## STEP 3: Use https://www.twilio.com
# Send a seperate message with the percentage change and each article's title and description to your phone number.

CHANGE_DIRECTIONAL = None
if percent_change < 0:
    CHANGE_DIRECTIONAL = 'ðŸ”»'
elif percent_change > 0:
    CHANGE_DIRECTIONAL = 'ðŸ”º'

percent_change_formatted = abs(round((percent_change * 100), 2))
articles_formatted = [f'{STOCK}: {CHANGE_DIRECTIONAL}{percent_change_formatted}\n'
                      f'Headline:{article["title"]}\nBrief: {article["description"]}' for article in articles]

if substantial_change:
    for article in articles_formatted:
        client = Client(twilio_account_sid, twilio_auth_token)
        message = client.messages \
            .create(
            body=article,
            from_=f'{twilio_phone_number}',
            to=f'{PERSONAL_PHONE_NUMBER}'
        )


import tensorflow as tf
import scipy.io as sio
import numpy as np
from PIL import Image

img_H = 64
img_W = 64
img_C = 3
GAN_type = "SNGAN"  # DCGAN, WGAN, WGAN-GP, SNGAN, LSGAN, RSGAN, RaSGAN
batchsize = 128
epsilon = 1e-14#if epsilon is too big, training of DCGAN is failure.

def deconv(inputs, shape, strides, out_num, is_sn=False):
    filters = tf.get_variable("kernel", shape=shape, initializer=tf.random_normal_initializer(stddev=0.02))
    bias = tf.get_variable("bias", shape=[shape[-2]], initializer=tf.constant_initializer([0]))
    if is_sn:
        return tf.nn.conv2d_transpose(inputs, spectral_norm("sn", filters), out_num, strides) + bias
    else:
        return tf.nn.conv2d_transpose(inputs, filters, out_num, strides) + bias

def conv(inputs, shape, strides, is_sn=False):
    filters = tf.get_variable("kernel", shape=shape, initializer=tf.random_normal_initializer(stddev=0.02))
    bias = tf.get_variable("bias", shape=[shape[-1]], initializer=tf.constant_initializer([0]))
    if is_sn:
        return tf.nn.conv2d(inputs, spectral_norm("sn", filters), strides, "SAME") + bias
    else:
        return tf.nn.conv2d(inputs, filters, strides, "SAME") + bias

def fully_connected(inputs, num_out, is_sn=False):
    W = tf.get_variable("W", [inputs.shape[-1], num_out], initializer=tf.random_normal_initializer(stddev=0.02))
    b = tf.get_variable("b", [num_out], initializer=tf.constant_initializer([0]))
    if is_sn:
        return tf.matmul(inputs, spectral_norm("sn", W)) + b
    else:
        return tf.matmul(inputs, W) + b

def leaky_relu(inputs, slope=0.2):
    return tf.maximum(slope*inputs, inputs)

def spectral_norm(name, w, iteration=1):
    #Spectral normalization which was published on ICLR2018,please refer to "https://www.researchgate.net/publication/318572189_Spectral_Normalization_for_Generative_Adversarial_Networks"
    #This function spectral_norm is forked from "https://github.com/taki0112/Spectral_Normalization-Tensorflow"
    w_shape = w.shape.as_list()
    w = tf.reshape(w, [-1, w_shape[-1]])
    with tf.variable_scope(name, reuse=False):
        u = tf.get_variable("u", [1, w_shape[-1]], initializer=tf.truncated_normal_initializer(), trainable=False)
    u_hat = u
    v_hat = None

    def l2_norm(v, eps=1e-12):
        return v / (tf.reduce_sum(v ** 2) ** 0.5 + eps)

    for i in range(iteration):
        v_ = tf.matmul(u_hat, tf.transpose(w))
        v_hat = l2_norm(v_)
        u_ = tf.matmul(v_hat, w)
        u_hat = l2_norm(u_)
    sigma = tf.matmul(tf.matmul(v_hat, w), tf.transpose(u_hat))
    w_norm = w / sigma
    with tf.control_dependencies([u.assign(u_hat)]):
        w_norm = tf.reshape(w_norm, w_shape)
    return w_norm

def mapping(x):
    max = np.max(x)
    min = np.min(x)
    return (x - min) * 255.0 / (max - min + epsilon)

def instanceNorm(inputs):
    mean, var = tf.nn.moments(inputs, axes=[1, 2], keep_dims=True)
    scale = tf.get_variable("scale", shape=mean.shape[-1], initializer=tf.constant_initializer([1.0]))
    shift = tf.get_variable("shift", shape=mean.shape[-1], initializer=tf.constant_initializer([0.0]))
    return (inputs - mean) * scale / (tf.sqrt(var + epsilon)) + shift

class Generator:
    def __init__(self, name):
        self.name = name

    def __call__(self, Z):
        with tf.variable_scope(name_or_scope=self.name, reuse=False):
            with tf.variable_scope(name_or_scope="linear"):
                inputs = tf.reshape(tf.nn.relu((fully_connected(Z, 4*4*512))), [batchsize, 4, 4, 512])
            with tf.variable_scope(name_or_scope="deconv1"):
                inputs = tf.nn.relu(instanceNorm(deconv(inputs, [5, 5, 256, 512], [1, 2, 2, 1], [batchsize, 8, 8, 256])))
            with tf.variable_scope(name_or_scope="deconv2"):
                inputs = tf.nn.relu(instanceNorm(deconv(inputs, [5, 5, 128, 256], [1, 2, 2, 1], [batchsize, 16, 16, 128])))
            with tf.variable_scope(name_or_scope="deconv3"):
                inputs = tf.nn.relu(instanceNorm(deconv(inputs, [5, 5, 64, 128], [1, 2, 2, 1], [batchsize, 32, 32, 64])))
            if img_H == 32:
                with tf.variable_scope(name_or_scope="deconv4"):
                    inputs = tf.nn.tanh(deconv(inputs, [5, 5, img_C, 64], [1, 1, 1, 1], [batchsize, img_H, img_W, img_C]))
                return inputs
            with tf.variable_scope(name_or_scope="deconv4"):
                 inputs = tf.nn.tanh(deconv(inputs, [5, 5, img_C, 64], [1, 2, 2, 1], [batchsize, img_H, img_W, img_C]))
            if img_H == 64:
                return inputs

    @property
    def var(self):
        return tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, self.name)

class Discriminator:
    def __init__(self, name):
        self.name = name

    def __call__(self, inputs, reuse=False, is_sn=False):
        with tf.variable_scope(name_or_scope=self.name, reuse=reuse):
            with tf.variable_scope("conv1"):
                inputs = leaky_relu(conv(inputs, [5, 5, img_C, 64], [1, 2, 2, 1], is_sn))
            with tf.variable_scope("conv2"):
                inputs = leaky_relu(instanceNorm(conv(inputs, [5, 5, 64, 128], [1, 2, 2, 1], is_sn)))
            with tf.variable_scope("conv3"):
                inputs = leaky_relu(instanceNorm(conv(inputs, [5, 5, 128, 256], [1, 2, 2, 1], is_sn)))
            with tf.variable_scope("conv4"):
                inputs = leaky_relu(instanceNorm(conv(inputs, [5, 5, 256, 512], [1, 2, 2, 1], is_sn)))
            inputs = tf.layers.flatten(inputs)
            return fully_connected(inputs, 1, is_sn)

    @property
    def var(self):
        return tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=self.name)

class GAN:
    #Architecture of generator and discriminator just like DCGAN.
    def __init__(self):
        self.Z = tf.placeholder("float", [batchsize, 100])
        self.img = tf.placeholder("float", [batchsize, img_H, img_W, img_C])
        D = Discriminator("discriminator")
        G = Generator("generator")
        self.fake_img = G(self.Z)
        if GAN_type == "DCGAN":
            #DCGAN, paper: UNSUPERVISED REPRESENTATION LEARNING WITH DEEP CONVOLUTIONAL GENERATIVE ADVERSARIAL NETWORKS
            self.fake_logit = tf.nn.sigmoid(D(self.fake_img))
            self.real_logit = tf.nn.sigmoid(D(self.img, reuse=True))
            self.d_loss = - (tf.reduce_mean(tf.log(self.real_logit + epsilon)) + tf.reduce_mean(tf.log(1 - self.fake_logit + epsilon)))
            self.g_loss = - tf.reduce_mean(tf.log(self.fake_logit + epsilon))
            self.opt_D = tf.train.AdamOptimizer(2e-4, beta1=0.5).minimize(self.d_loss, var_list=D.var)
            self.opt_G = tf.train.AdamOptimizer(2e-4, beta1=0.5).minimize(self.g_loss, var_list=G.var)
        elif GAN_type == "WGAN":
            #WGAN, paper: Wasserstein GAN
            self.fake_logit = D(self.fake_img)
            self.real_logit = D(self.img, reuse=True)
            self.d_loss = -tf.reduce_mean(self.real_logit) + tf.reduce_mean(self.fake_logit)
            self.g_loss = -tf.reduce_mean(self.fake_logit)
            self.clip = []
            for _, var in enumerate(D.var):
                self.clip.append(var.assign(tf.clip_by_value(var, -0.01, 0.01)))
            self.opt_D = tf.train.RMSPropOptimizer(5e-5).minimize(self.d_loss, var_list=D.var)
            self.opt_G = tf.train.RMSPropOptimizer(5e-5).minimize(self.g_loss, var_list=G.var)
        elif GAN_type == "WGAN-GP":
            #WGAN-GP, paper: Improved Training of Wasserstein GANs
            self.fake_logit = D(self.fake_img)
            self.real_logit = D(self.img, reuse=True)
            e = tf.random_uniform([batchsize, 1, 1, 1], 0, 1)
            x_hat = e * self.img + (1 - e) * self.fake_img
            grad = tf.gradients(D(x_hat, reuse=True), x_hat)[0]
            self.d_loss = tf.reduce_mean(self.fake_logit - self.real_logit) + 10 * tf.reduce_mean(tf.square(tf.sqrt(tf.reduce_sum(tf.square(grad), axis=[1, 2, 3])) - 1))
            self.g_loss = tf.reduce_mean(-self.fake_logit)
            self.opt_D = tf.train.AdamOptimizer(1e-4, beta1=0., beta2=0.9).minimize(self.d_loss, var_list=D.var)
            self.opt_G = tf.train.AdamOptimizer(1e-4, beta1=0., beta2=0.9).minimize(self.g_loss, var_list=G.var)
        elif GAN_type == "LSGAN":
            #LSGAN, paper: Least Squares Generative Adversarial Networks
            self.fake_logit = D(self.fake_img)
            self.real_logit = D(self.img, reuse=True)
            self.d_loss = tf.reduce_mean(0.5 * tf.square(self.real_logit - 1) + 0.5 * tf.square(self.fake_logit))
            self.g_loss = tf.reduce_mean(0.5 * tf.square(self.fake_logit - 1))
            self.opt_D = tf.train.AdamOptimizer(2e-4, beta1=0.5).minimize(self.d_loss, var_list=D.var)
            self.opt_G = tf.train.AdamOptimizer(2e-4, beta1=0.5).minimize(self.g_loss, var_list=G.var)
        elif GAN_type == "SNGAN":
            #SNGAN, paper: SPECTRAL NORMALIZATION FOR GENERATIVE ADVERSARIAL NETWORKS
            self.fake_logit = tf.nn.sigmoid(D(self.fake_img, is_sn=True))
            self.real_logit = tf.nn.sigmoid(D(self.img, reuse=True, is_sn=True))
            self.d_loss = - (tf.reduce_mean(tf.log(self.real_logit + epsilon) + tf.log(1 - self.fake_logit + epsilon)))
            self.g_loss = - tf.reduce_mean(tf.log(self.fake_logit + epsilon))
            self.opt_D = tf.train.AdamOptimizer(2e-4, beta1=0.5).minimize(self.d_loss, var_list=D.var)
            self.opt_G = tf.train.AdamOptimizer(2e-4, beta1=0.5).minimize(self.g_loss, var_list=G.var)
        elif GAN_type == "RSGAN":
            #RSGAN, paper: The relativistic discriminator: a key element missing from standard GAN
            self.fake_logit = D(self.fake_img)
            self.real_logit = D(self.img, reuse=True)
            self.d_loss = - tf.reduce_mean(tf.log(tf.nn.sigmoid(self.real_logit - self.fake_logit) + epsilon))
            self.g_loss = - tf.reduce_mean(tf.log(tf.nn.sigmoid(self.fake_logit - self.real_logit) + epsilon))
            self.opt_D = tf.train.AdamOptimizer(2e-4, beta1=0.5).minimize(self.d_loss, var_list=D.var)
            self.opt_G = tf.train.AdamOptimizer(2e-4, beta1=0.5).minimize(self.g_loss, var_list=G.var)
        elif GAN_type == "RaSGAN":
            #RaSGAN, paper: The relativistic discriminator: a key element missing from standard GAN
            self.fake_logit = D(self.fake_img)
            self.real_logit = D(self.img, reuse=True)
            self.avg_fake_logit = tf.reduce_mean(self.fake_logit)
            self.avg_real_logit = tf.reduce_mean(self.real_logit)
            self.D_r_tilde = tf.nn.sigmoid(self.real_logit - self.avg_fake_logit)
            self.D_f_tilde = tf.nn.sigmoid(self.fake_logit - self.avg_real_logit)
            self.d_loss = - tf.reduce_mean(tf.log(self.D_r_tilde + epsilon)) - tf.reduce_mean(tf.log(1 - self.D_f_tilde + epsilon))
            self.g_loss = - tf.reduce_mean(tf.log(self.D_f_tilde + epsilon)) - tf.reduce_mean(tf.log(1 - self.D_r_tilde + epsilon))
            self.opt_D = tf.train.AdamOptimizer(2e-4, beta1=0.5).minimize(self.d_loss, var_list=D.var)
            self.opt_G = tf.train.AdamOptimizer(2e-4, beta1=0.5).minimize(self.g_loss, var_list=G.var)
        self.sess = tf.Session()
        self.sess.run(tf.global_variables_initializer())

    def __call__(self):
        saver = tf.train.Saver()
        epoch_nums = 200
        facedata = sio.loadmat("./TrainingSet//facedata.mat")["data"]
        #For face data, i random select about 10,000 images from CelebA and resize them to 64x64 by Matlab.
        for epoch in range(epoch_nums):
            for i in range(facedata.__len__()//batchsize-1):
                batch = facedata[i*batchsize:i*batchsize+batchsize, :, :, :] / 255.0
                z = np.random.standard_normal([batchsize, 100])
                d_loss = self.sess.run(self.d_loss, feed_dict={self.img: batch, self.Z: z})
                g_loss = self.sess.run(self.g_loss, feed_dict={self.img: batch, self.Z: z})
                self.sess.run(self.opt_D, feed_dict={self.img: batch, self.Z: z})
                if GAN_type == "WGAN":
                    self.sess.run(self.clip)#WGAN weight clipping
                self.sess.run(self.opt_G, feed_dict={self.img: batch, self.Z: z})
                if i % 10 == 0:
                    print("epoch: %d, step: %d, d_loss: %g, g_loss: %g"%(epoch, i,  d_loss, g_loss))
                    z = np.random.standard_normal([batchsize, 100])
                    imgs = self.sess.run(self.fake_img, feed_dict={self.img: batch, self.Z: z})
                    for j in range(batchsize):
                        if img_C == 1:
                            Image.fromarray(np.reshape(np.uint8(mapping(imgs[j, :, :, :])), [img_H, img_W])).save(
                                "./result//" + str(epoch) + "_" + str(j) + ".jpg")
                        else:
                            Image.fromarray(np.uint8(mapping(imgs[j, :, :, :]))).save(
                                "./result//" + str(epoch) + "_" + str(j) + ".jpg")
            saver.save(self.sess, "./para//model.ckpt")

if __name__ == "__main__":
    gan = GAN()
    gan()


import argparse

import catboost
import loguru
import pandas as pd
from sklearn import metrics

from src import utils

def _configure_parser() -> argparse.ArgumentParser:
    argparser = argparse.ArgumentParser()
    argparser.add_argument(
        "--model",
        type=str,
        default="experiments/latest/model.cbm",
        help="Catboost model in binary file.",
    )
    argparser.add_argument(
        "--test-data",
        type=str,
        default="data/test.csv",
        help="Test dataset in csv format (sep = ';').",
    )
    return argparser

def main(model: str, test_data: str):
    model = catboost.CatBoostClassifier()

    loguru.logger.info("Loading model from {}", model)
    model.load_model(model)

    loguru.logger.info("Loading data from {}", test_data)
    data = pd.read_csv(test_data, sep=";")
    features, labels = utils.split_into_x_y(data)
    predictions = model.predict(features)

    f1_micro = metrics.f1_score(predictions, labels, average="micro")
    accuracy = metrics.accuracy_score(predictions, labels)

    loguru.logger.info(f"\nF1 micro: {f1_micro}\nAccuracy: {accuracy}")

if __name__ == "__main__":
    args = _configure_parser().parse_args()
    main(**vars(args))


from django.shortcuts import render, redirect
from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector
from django_slack import slack_message
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

from .models import Article, Topic, Stub
from .forms import ArticleForm, TopicForm

def index(request):
    topics = Topic.objects.all()
    if not topics:
        t = Topic(title='everything!')
        t.save()
        topics = [t]
    stubs = Stub.objects.filter(classified=False)
    recent = Article.objects.order_by('-id')
    recent = [list(recent[0:2]), list(recent[2:4])]
    context = {'topics': topics, 'root': topics[0], 'stubs': stubs,
               'recent': recent}
    return render(request, 'articles/index.html', context)

@csrf_exempt
def new_something(request):
    if request.method == 'POST':
        sender = request.POST.get('sender')
        subject = request.POST.get('subject', '').strip()
        body_without_quotes = request.POST.get('stripped-text', '').strip()
        stub = Stub.objects.filter(link=body_without_quotes)
        if not stub:
            stub = Stub(title=subject, link=body_without_quotes, sender=sender)
            stub.save()
    return HttpResponse('OK')

def complete_stub(request, stub_id):
    stub = Stub.objects.filter(id=stub_id)[0]
    if request.method == 'POST':
        form = ArticleForm(request.POST)
        if form.is_valid():
            article = form.save(commit=False)
            hack_block_spam(article)
            article.save()
            topic = article.parent_topic
            topic.articles.add(article)
            topic.save()
            slack_message('articles/article.slack', {'article': article})
            stub.classified = True
            stub.save()
            return redirect('/')
    else:
        form = ArticleForm(initial={'title': stub.title, 'link': stub.link})
    context = {'form': form}
    return render(request, 'articles/new_article.html', context)

def new_article(request, topic):
    topic = Topic.objects.filter(title=topic).first()
    if request.method == 'POST':
        form = ArticleForm(request.POST)
        if form.is_valid():
            article = form.save(commit=False)
            article.parent_topic = topic
            hack_block_spam(article)
            article.save()
            topic.articles.add(article)
            topic.save()
            slack_message('articles/article.slack', {'article': article})
            return redirect('/')
    else:
        form = ArticleForm()
    context = {'form': ArticleForm(initial={'parent_topic': topic})}
    return render(request, 'articles/new_article.html', context)

def view_article(request, article_id):
    article = Article.objects.filter(id=article_id)[0]
    context = {'article': article}
    return render(request, 'articles/article.html', context)

def new_topic(request, topic):
    if request.method == 'POST':
        form = TopicForm(request.POST)
        if form.is_valid():
            parent_topic = Topic.objects.get(title=topic)
            child_topic = form.save(commit=False)
            child_topic.parent = parent_topic
            child_topic.save()
            parent_topic.children.add(child_topic)
            parent_topic.save()
            return redirect('/#' + child_topic.title)
    else:
        form = TopicForm()
    context = {'form': form}
    return render(request, 'articles/new_topic.html', context)

def search(request):
    q = request.GET.get('q')
    if q:
        articles = Article.objects.all()
        query = SearchQuery(q)
        title_vector = SearchVector('title', weight='A')
        summary_vector = SearchVector('summary', weight='B')
        vectors = title_vector + summary_vector
        articles = articles.annotate(search=vectors).filter(search=q)
        articles = articles.annotate(
            rank=SearchRank(vectors, query)).order_by('-rank')
        rows = [articles[i:i + 2] for i in range(0, len(articles), 2)]
    else:
        rows = []
    return render(request, 'articles/search.html', {'rows': rows})

def hack_block_spam(article):
    if article.is_spam():
        raise Exception('probably spam')


import requests
from datetime import datetime, timedelta
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail, From, To
import firebase_admin
from firebase_admin import firestore

count = 0
firestore_client = 0

# todoist api
token = '** REMOVED FOR PRIVACY **'
url = 'https://api.todoist.com/rest/v2/tasks'
headers = {'Authorization' : 'Bearer {}'.format(token), 'Content-Type': 'application/json'}

# sendgrid api
api_key = 'S** REMOVED FOR PRIVACY **'

def initialize_firebase():
    credentials = {
  "type": "service_account",
  "project_id": "** REMOVED FOR PRIVACY **",
  "private_key_id": "** REMOVED FOR PRIVACY **",
  "private_key": "** REMOVED FOR PRIVACY **n",
  "client_email": "** REMOVED FOR PRIVACY **",
  "client_id": "** REMOVED FOR PRIVACY **",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "** REMOVED FOR PRIVACY **",
  "universe_domain": "googleapis.com"
    }
    cred_obj = firebase_admin.credentials.Certificate(credentials)
    default_app = firebase_admin.initialize_app(cred_obj)
    firestore_clien = firestore.client()
    global firestore_client
    firestore_client = firestore_clien
    global count
    count += 1

def getTodoistTasks():
    response = requests.get(url, headers=headers)
    todoist_task_list = response.json()
    return todoist_task_list

def parse_todoist_json(todoist_task_list):
    task_list = []

    for task_json in todoist_task_list:
        task = {}
        task['name'] = task_json['content']
        task['due_date'] = task_json['due']['date']
        task['id'] = task_json['id']
        task['priority'] = task_json['priority']
        task['project_id'] = task_json['project_id']
        task['description'] = task_json['description']
        task['url'] = task_json['url']
        task['status'] = 'completed' if task_json['is_completed'] == True else 'active'
        task_list.append(task)

    return task_list

def filter_tasks_to_due_date_today(task_list, past_midnight):
    new_task_list = []
    today = datetime.today().strftime("%Y-%m-%d")
    if past_midnight:
        today = today - timedelta(1)

    for task in task_list:
        if task['due_date'] == today:
            new_task_list.append(task)

    return new_task_list

def filter_tasks_to_due_date_tomorrow(task_list, past_midnight):
    new_task_list = []
    today = datetime.today()
    if not past_midnight:
        tomorrow = today + timedelta(1)
    else:
        tomorrow = today
    tomorrow = tomorrow.strftime("%Y-%m-%d")

    for task in task_list:
        if task['due_date'] == tomorrow:
            new_task_list.append(task)

    task_ids = []

    for task in new_task_list:
        task_ids.append(task['id'])

    return new_task_list, tomorrow, task_ids

def separate_sorted_by_priorities(new_task_list):
    p1 = []
    p2 = []
    p3 = []
    none = []

    for task in new_task_list:
        if task['priority'] == 1:
            none.append(task)
        elif task['priority'] == 2:
            p3.append(task)
        elif task['priority'] == 3:
            p2.append(task)
        else:
            p1.append(task)

    return p1,p2,p3,none

def populate_email(p1, p2, p3, none, title, unique_message):

    button = """

        View

    """

    p1_content = ''

    for task in p1:
        content = "
{}	".format(task['name'])
        content += button.replace('a*5', task['url'])
        content += "
"
        p1_content += content

    p2_content = ''

    for task in p2:
        content = "
{}	".format(task['name'])
        content += button.replace('a*5', task['url'])
        content += "
"
        p2_content += content

    p3_content = ''

    for task in p3:
        content = "
{}	".format(task['name'])
        content += button.replace('a*5', task['url'])
        content += "
"
        p3_content += content

    none_content = ''

    for task in none:
        content = "
{}	".format(task['name'])
        content += button.replace('a*5', task['url'])
        content += "
"
        none_content += content

    html_content = """
    <!DOCTYPE html>

    """

    html_content += unique_message + "
"

    html_content += """

P1 tasks

            {p1_html_content}

P2 tasks

            {p2_html_content}

P3 tasks

            {p3_html_content}

No priority tasks

            {none_html_content}

        """.format(p1_html_content=p1_content, p2_html_content=p2_content, p3_html_content=p3_content,
                   none_html_content=none_content)

    message = Mail(
    from_email = From('** REMOVED FOR PRIVACY **', '** REMOVED FOR PRIVACY **'),
    to_emails='** REMOVED FOR PRIVACY **',
    subject = title,
    html_content=html_content)

    return message

def send_email(message):
    try:
        sg = SendGridAPIClient(api_key)
        response = sg.send(message)
        if response.status_code == 202:
            print('Sent!')
    except Exception as e:
        print(e.message)

def check_task_completion():
    return None

def send_next_day_preview_email():

    # adds tasks to firebase and returns list of tasks and date
    tomorrow_task_list = add_tomorrow_tasks_to_firebase()

    # sorts task list by priority
    p1,p2,p3,none = separate_sorted_by_priorities(tomorrow_task_list)

    # populates email
    tomorrow = datetime.today() + timedelta(1)
    tomorrow = tomorrow.strftime("%m.%d.%Y")

    title = "Take a peak at {} tasks".format(tomorrow)
    unique_message = "
 Tomorrow, you have {} tasks !
".format(len(tomorrow_task_list))
    message = populate_email(p1, p2, p3, none, title, unique_message)

    # send email
    send_email(message)

def add_tomorrow_tasks_to_firebase():
    # get today tasks
    todoist_task_list = getTodoistTasks()
    task_list = parse_todoist_json(todoist_task_list)

    # gets list of tasks for tmrw, formatted date, and list of task IDs
    tomorrow_task_list, tomorrow, task_ids = filter_tasks_to_due_date_tomorrow(task_list, True)

    # adds tasks to Firebase
    add_tasks_to_firebase(tomorrow, tomorrow_task_list, task_ids)

    return tomorrow_task_list

def add_tasks_to_firebase(docName, task_list, task_ids):
    global firestore_client
    doc_ref = firestore_client.collection("tasks").document(docName)
    doc_ref.set({'tasks': task_list, 'task_ids': task_ids})

def send_morning_preview_email():
    # get today tasks
    todoist_task_list = getTodoistTasks()
    task_list = parse_todoist_json(todoist_task_list)
    today_task_list = filter_tasks_to_due_date_today(task_list, False)

    # sorts task list by priority
    p1,p2,p3,none = separate_sorted_by_priorities(today_task_list)

    # populates email
    today = datetime.today()
    today = today.strftime("%m.%d.%Y")

    title = "Prepare for today | {} tasks".format(today)
    unique_message = "
 Today, you have {} tasks !
".format(len(today_task_list))
    message = populate_email(p1, p2, p3, none, title, unique_message)

    # send email
    send_email(message)

def send_midday_review_email():
    # get today tasks
    todoist_task_list = getTodoistTasks()
    task_list = parse_todoist_json(todoist_task_list)
    today_task_list = filter_tasks_to_due_date_today(task_list, False)

    # sorts task list by priority
    p1,p2,p3,none = separate_sorted_by_priorities(today_task_list)

    # populates email
    today = datetime.today()
    today = today.strftime("%m.%d.%Y")

    title = "Midday Review | {} tasks".format(today)
    unique_message = "
 You have {} tasks to go!
".format(len(today_task_list))
    message = populate_email(p1, p2, p3, none, title, unique_message)

    # send email
    send_email(message)

def send_evening_review_email():
    # get today tasks
    todoist_task_list = getTodoistTasks()
    task_list = parse_todoist_json(todoist_task_list)
    today_task_list = filter_tasks_to_due_date_today(task_list, False)

    # sorts task list by priority
    p1,p2,p3,none = separate_sorted_by_priorities(today_task_list)

    # populates email
    today = datetime.today()
    today = today.strftime("%m.%d.%Y")

    title = "Evening Review | {} tasks".format(today)
    unique_message = "
 You have {} tasks to go!
".format(len(today_task_list))
    message = populate_email(p1, p2, p3, none, title, unique_message)

    # send email
    send_email(message)

def send_end_of_day_review_email():
    # get today tasks
    todoist_task_list = getTodoistTasks()
    task_list = parse_todoist_json(todoist_task_list)
    today_task_list = filter_tasks_to_due_date_today(task_list, True)

    # sorts task list by priority
    p1,p2,p3,none = separate_sorted_by_priorities(today_task_list)

    # populates email
    today = datetime.today()
    today = today.strftime("%m.%d.%Y")

    title = "End of Day Review | {} tasks".format(today)
    unique_message = "
 There are {} tasks uncompleted!
".format(len(today_task_list))
    message = populate_email(p1, p2, p3, none, title, unique_message)

    # send email
    send_email(message)

def main(a,b):
    print(count)
    if count == 0:
        initialize_firebase()
    now = datetime.now()
    time = now.strftime("%H:%M")

    if time == '12:30':
        send_morning_preview_email()
    elif time == '16:00':
        send_midday_review_email()
    elif time == '21:00':
        send_evening_review_email()
    elif time == '03:00':
        send_end_of_day_review_email()
    elif time == '03:03':
        send_next_day_preview_email()

main(1,2)


from django.test import TestCase
from django.forms.models import model_to_dict
from datetime import datetime, timedelta, time

from timetable.models import *
from timetable.forms import *
from timetable.tests.base_test import BaseTestCase

class StageTestCase(BaseTestCase):
    def setUp(self):
        super(StageTestCase, self).setUp()
        self.school_year_2020 = SchoolYear(year_start=2020, date_start=datetime(month=8, year=2020, day=31))
        self.school_year_2020.save()
        # Create a course for the school s1

        self.hsg1 = HourSlotsGroup(name='Default1', school_year=self.school_year_2020, school=self.s1)
        self.hsg2 = HourSlotsGroup(name='Default2', school_year=self.school_year_2020, school=self.s2)
        self.hsg1.save()
        self.hsg2.save()

        self.course1 = Course(year=1, section='A', hour_slots_group=self.hsg1)
        self.course2 = Course(year=1, section='A', hour_slots_group=self.hsg2)
        self.course1.save()
        self.course2.save()

        self.form_data = {
            "date_start": datetime(day=23, month=6, year=2020),
            "date_end": datetime(day=23, month=6, year=2020),
            "course": self.course1,
            "school": self.s1,
            "name": "Difficult Stage"}

    def test_stage_correct_creation(self):

        """
        Test the creation of a Stage, using the correct admin and school.
        :return:
        """

        f = StageForm(user=self.a1, data=self.form_data)
        f.full_clean()
        self.assertTrue(f.is_valid())

    def test_stage_wrong_admin_for_school_creation(self):
        """
        Test the creation of a Stage, using the wrong school for the admin.
        :return:
        """
        # But admin of school 1
        f = StageForm(user=self.a2, data=self.form_data)
        f.full_clean()
        self.assertTrue(f.has_error('course'))   # The form should have an error on the course field.

    def test_stage_wrong_course_for_school_creation(self):
        """
        Test the creation of a stage, using the wrong course.
        :return:
        """
        form_data = {
            "date_start": datetime(day=23, month=6, year=2020),
            "date_end": datetime(day=23, month=6, year=2020),
            "course": self.course2,    # Wrong course
            "school": self.s1,
            "name": "Difficult Stage"}
        # But admin of school 1
        f = StageForm(user=self.a1, data=form_data)
        f.full_clean()
        self.assertTrue(f.has_error('course'))   # The form should have an error on the course field.

    def test_stage_wrong_course_and_school_for_admin_creation(self):
        """
        Test the creation of a stage, using the wrong course and school for admin.
        :return:
        """
        form_data = {
            "date_start": datetime(day=23, month=6, year=2020),
            "date_end": datetime(day=23, month=6, year=2020),
            "course": self.course2,  # Wrong course
            "school": self.s2,       # wrong school
            "school_year": self.school_year_2020,
            "name": "Difficult Stage"}
        # But admin of school 1
        f = StageForm(user=self.a1, data=form_data)
        f.full_clean()
        self.assertFalse(f.is_valid())  # The form should have an error on the course field.

    def test_stage_wrong_date(self):
        """
        Test the creation of a stage, using the wrong date (start > end)
        :return:
        """
        form_data = {
            "date_start": datetime(day=24, month=6, year=2020),   # start date is after end date
            "date_end": datetime(day=23, month=6, year=2020),
            "course": self.course1,    # Wrong course
            "school": self.s1,
            "school_year": self.school_year_2020,
            "name": "Difficult Stage"}
        # But admin of school 1
        f = StageForm(user=self.a1, data=form_data)
        f.full_clean()
        self.assertFalse(f.is_valid())   # The form should have error on the dates


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import numpy as np
import pandas as pd
import _pickle as cPickle
import scipy.optimize as opt
from datetime import datetime
from scipy.stats import uniform, randint
from sklearn.preprocessing import OneHotEncoder

from sklearn.model_selection import cross_val_score, GridSearchCV
from sklearn.model_selection import KFold, RandomizedSearchCV, train_test_split
from sklearn.model_selection import cross_val_score, ShuffleSplit, learning_curve

from sklearn.metrics import auc, accuracy_score,roc_auc_score
from sklearn.metrics import confusion_matrix, mean_squared_error, mean_absolute_error
from sklearn.metrics import roc_curve, confusion_matrix, classification_report
from sklearn.metrics import precision_score, recall_score, f1_score

from sklearn import svm
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import GradientBoostingClassifier

path = '/Users/tung/Python/WorkProject/PHMresearch/WDCNN&LR_FaultDiagnosis/'

feature_train_scaled = cPickle.load( open(path+'feature_train_scaled.pkl','rb') )
feature_valid_scaled = cPickle.load( open(path+'feature_valid_scaled.pkl','rb') )
feature_test_scaled = cPickle.load( open(path+'feature_test_scaled.pkl','rb') )

y_train_decode = cPickle.load( open(path+'y_train_decode.pkl','rb') )
y_valid_decode = cPickle.load( open(path+'y_valid_decode.pkl','rb') )
y_test_decode = cPickle.load( open(path+'y_test_decode.pkl','rb') )

def encode(data):
    data = np.array(data).reshape([-1, 1])
    print('Shape of data (BEFORE encode): %s' % str(data.shape))
    Encoder = OneHotEncoder()
    Encoder.fit(data)
    encoded = Encoder.transform(data).toarray()
    print('Shape of data (AFTER  encode): %s\n' % str(encoded.shape))
    return encoded

y_test = encode(y_test_decode)

def display_scores(scores):
    print("Scores: {0}\nMean: {1:.3f}\nStd: {2:.3f}".format(scores, np.mean(scores), np.std(scores)))

'lasso lr'

#parameters set
lasso_model = LogisticRegression(C=0.7, penalty='l1', tol=1e-6, solver = 'liblinear',
                                 class_weight = 'balanced',multi_class= 'ovr', max_iter=1000) #不可导

print(lasso_model)

epoch = 5
scores = []

# Train model
start = datetime.now()

for i in range(epoch):
    lasso_model.fit(feature_train_scaled, y_train_decode)
    #     y_score = lasso_model.predict_proba(x_test)
    #     scores.append(roc_auc_score(y_test, y_score, average='micro'))
    scores.append(lasso_model.score(feature_test_scaled, y_test_decode)) #准确率

print("This took ", datetime.now() - start)
print(u'The accuracy of the model is: ')
display_scores(scores)  #准确率

coef_ = pd.DataFrame(lasso_model.coef_, columns = ['maximum', 'minimum', 'mean', 'var', 'std', 'absmean', 'rms',
'vi', 'skew', 'kurt', 'ptp', 'par', 'form', 'impulse', 'margin', 'spectral_kurt', 'spectral_skw','spectral_pow',
'wave_L2', 'frechet_form1', 'frechet_form2', 'frechet_form3', 'frechet_form4', 'frechet_form5', 'frechet_form6',
        'frechet_form7', 'frechet_form8' ])
coef_ #特征权重

#evaluation
prediction_train = lasso_model.predict(feature_train_scaled)
cm_train = confusion_matrix(y_train_decode, prediction_train)
prediction_test = lasso_model.predict(feature_test_scaled)
cm_test = confusion_matrix(y_test_decode, prediction_test)

print("Confusion matrix for training dataset is \n%s\n for testing dataset is \n%s.\n"
      % (cm_train, cm_test))

target_names = ['class 1', 'class 2', 'class 3', 'class 4', 'class 5',
                'class 6', 'class 7', 'class 8', 'class 9']
print(classification_report(y_test_decode, prediction_test, target_names=target_names))

'rige lr'
#parameters set
ridge_model = LogisticRegression(
                                 C=0.8,                      #正则化系数λ的倒数
                                 penalty='l2',
                                 dual = True,                #用在求解线性多核(liblinear)的L2惩罚项上。样本数量>样本特征的时False
                                 tol=1e-6,                   #绝对误差限，停止求解的标准
                                 class_weight = 'balanced',
                                 solver = 'liblinear',       #可导 lbfgs sag
                                 max_iter=5000)

print(ridge_model)

epoch = 5
scores = []

# Train model
start = datetime.now()

for i in range(epoch):
    ridge_model.fit(feature_train_scaled, y_train_decode)
    #     y_score = ridge_model.predict_proba(x_test)
    #     scores.append(roc_auc_score(y_test, y_score, average='micro'))
    scores.append(ridge_model.score(feature_test_scaled, y_test_decode)) #准确率

print("This took ", datetime.now() - start)
print(u'The accuracy of the model is: ')
display_scores(scores)  #准确率

param_test1 = {
    'C':[i/10.0 for i in range(1,11)]         # c：正则化系数λ的倒数
}
gsearch1 = GridSearchCV(estimator = ridge_model,
                        param_grid = param_test1, scoring='accuracy',n_jobs=2, cv=5)

gsearch1.fit(feature_valid_scaled, y_valid_decode)

print(gsearch1.cv_results_['mean_test_score'])
print(gsearch1.best_params_)
print("best accuracy:%f" % gsearch1.best_score_)

coef_ = pd.DataFrame(ridge_model.coef_, columns = ['maximum', 'minimum', 'mean', 'var', 'std', 'absmean', 'rms',
'vi', 'skew', 'kurt', 'ptp', 'par', 'form', 'impulse', 'margin', 'spectral_kurt', 'spectral_skw','spectral_pow',
'wave_L2', 'frechet_form1', 'frechet_form2', 'frechet_form3', 'frechet_form4', 'frechet_form5', 'frechet_form6',
                                                   'frechet_form7', 'frechet_form8' ])

coef_

#evaluation
prediction_train = ridge_model.predict(feature_train_scaled)
cm_train = confusion_matrix(y_train_decode, prediction_train)
prediction_test = ridge_model.predict(feature_test_scaled)
cm_test = confusion_matrix(y_test_decode, prediction_test)

print("Confusion matrix for training dataset is \n%s\n for testing dataset is \n%s.\n"
      % (cm_train, cm_test))

target_names = ['class 1', 'class 2', 'class 3', 'class 4', 'class 5',
                'class 6', 'class 7', 'class 8', 'class 9']
print(classification_report(y_test_decode, prediction_test, target_names=target_names))

y_score = ridge_model.predict_proba(feature_test_scaled)

# 计算micro类型的AUC
# print('调用函数auc：', roc_auc_score(y_test, y_score, average='micro'))

fpr, tpr, thresholds = roc_curve(y_test.ravel(),y_score.ravel())
micro_auc = auc(fpr, tpr)
print ('micro_auc：', micro_auc)

'demo lr'
def demoLr(data):
    def sigmoid(z):
        return 1 / (1 + np.exp(-z))

    # add a ones column - this makes the matrix multiplication work out easier
    data.insert(0, 'Ones', 1)

    # set X (training data) and y (target variable)
    cols = data.shape[1]
    X = data.iloc[:,0:cols-1]
    y = data.iloc[:,cols-1:cols]

    # convert to numpy arrays and initalize the parameter array theta
    X = X.values
    y = y.values.reshape(len(y),)

    theta = np.zeros(X.shape[1])

    #regularized cost
    def cost(theta, X, y):
        ''' cost fn is -l(theta) for you to minimize'''
        return np.mean(-y * np.log(sigmoid(X @ theta)) - (1 - y) * np.log(1 - sigmoid(X @ theta)))

    cost(theta, X, y)

    def regularized_cost(theta, X, y, l=1):
        #     '''you don't penalize theta_0'''
        theta_j1_to_n = theta[1:]
        regularized_term = (l / (2 * len(X))) * np.power(theta_j1_to_n, 2).sum()

        return cost(theta, X, y) + regularized_term

    'this is the same as the not regularized cost because we init theta as zeros...'
    regularized_cost(theta, X, y, l=1)

    #regularized gradient
    def gradient(theta, X, y):
        #     '''just 1 batch gradient'''
        return (1 / len(X)) * X.T @ (sigmoid(X @ theta) - y)
    gradient(theta, X, y)

    def regularized_gradient(theta, X, y, l=1):
        #     '''still, leave theta_0 alone'''
        theta_j1_to_n = theta[1:]
        regularized_theta = (l / len(X)) * theta_j1_to_n

        # by doing this, no offset is on theta_0
        regularized_term = np.concatenate([np.array([0]), regularized_theta])

        return gradient(theta, X, y) + regularized_term

    regularized_gradient(theta, X, y)

    print('init cost = {}'.format(regularized_cost(theta, X, y)))

    res = opt.minimize(fun=regularized_cost, x0=theta, args=(X, y), method='Newton-CG', jac=regularized_gradient)
    res

    #prediction
    def predict(x, theta):
        prob = sigmoid(x @ theta)
        return (prob >= 0.5).astype(int)

    final_theta = res.x
    y_pred = predict(X, final_theta)

    print(classification_report(y, y_pred))

'SVM'
def demoSVM(data):
    positive = data[data['y'].isin([1])]
    negative = data[data['y'].isin([0])]

    svc = svm.LinearSVC(C=1, loss='hinge', max_iter=1000)            #liner
    svc

    svc.fit(data[['spectral_pow', 'mean']], data['y'])
    print(svc.score(data[['spectral_pow', 'mean']], data['y']))

    svc2 = svm.LinearSVC(C=100, loss='hinge', max_iter=100000)       #惩罚系数
    svc2.fit(data[['spectral_pow', 'mean']], data['y'])
    print(svc2.score(data[['spectral_pow', 'mean']], data['y']))

    svc3 = svm.SVC(C=3, kernel='rbf', gamma=5000, probability=True)  #GaussianKernel
    svc3

    svc3.fit(data[['spectral_pow', 'mean']], data['y'])
    print(svc3.score(data[['spectral_pow', 'mean']], data['y']))

    ypred = svc3.predict(data[['spectral_pow', 'mean']])
    print(classification_report(data['y'], ypred))

    candidate = [0.01, 0.03, 0.1, 0.3, 1, 3, 10, 30, 100, 1000, 5000]  #c gamma
    combination = [(C, gamma) for C in candidate for gamma in candidate]

    search = []
    for C, gamma in combination:
        svc = svm.SVC(C=C, gamma=gamma)
        svc.fit(data[['spectral_pow', 'mean']], data['y'])
        search.append(svc.score(data[['spectral_pow', 'mean']], data['y']))   #CV数据

    best_score = search[np.argmax(search)]
    best_param = combination[np.argmax(search)]

    print(best_score, best_param)

'RF'
rf = RandomForestClassifier(
                            n_estimators = 21,
                            max_depth=5,
                            max_features='auto',             #构建决策树最优模型时考虑的最大特征数 n的平方根
                            oob_score = True,                #选用袋外样本，其误差是测试数据集误差的无偏估计
                            min_samples_leaf = 1,            #叶子节点含有的最少样本,小于则剪枝
                            min_samples_split= 2,            #叶子节点可分的最小样本数
                            max_leaf_nodes = None,           #最大叶子节点数
                            min_impurity_decrease = 0.0,     #节点划分的最小不纯度
                            criterion = 'gini',              #表示节点的划分标准
                            min_weight_fraction_leaf=0.0     #叶子节点最小的样本权重和,小于则剪枝,较多样本的缺失值或偏差很大时尝试
                            )
print(rf)

epoch = 5
scores = []

# Train model
start = datetime.now()

for i in range(epoch):
    rf.fit(feature_train_scaled, y_train_decode)
    scores.append(rf.score(feature_test_scaled, y_test_decode)) #准确率

print("This took ", datetime.now() - start)
print(u'The accuracy of the model is: ')
display_scores(scores)      #准确率

param_test2 = {             #bagging参数
    "n_estimators":range(1,101,10)
}
gsearch2 = GridSearchCV(estimator = rf,
                        param_grid = param_test2, scoring='accuracy',n_jobs=2, cv=5)

gsearch2.fit(feature_valid_scaled, y_valid_decode)

print(gsearch2.cv_results_['mean_test_score'])
print(gsearch2.best_params_)
print("best accuracy:%f" % gsearch2.best_score_)

#evaluation
prediction_train = rf.predict(feature_train_scaled)
cm_train = confusion_matrix(y_train_decode, prediction_train)
prediction_test = rf.predict(feature_test_scaled)
cm_test = confusion_matrix(y_test_decode, prediction_test)

print("Confusion matrix for training dataset is \n%s\n for testing dataset is \n%s.\n"
      % (cm_train, cm_test))

#Precision_rate预测为正例的样本中的真正正例的比例
#Recall_rate预测为正例的真正正例占所有真正正例的比例

target_names = ['class 1', 'class 2', 'class 3', 'class 4', 'class 5',
                'class 6', 'class 7', 'class 8', 'class 9']
print(classification_report(y_test_decode, prediction_test, target_names=target_names))

y_score = rf.predict_proba(feature_test_scaled)

# 计算micro类型的AUC
# print('调用函数auc：', roc_auc_score(y_test, y_score, average='micro'))

fpr, tpr, thresholds = roc_curve(y_test.ravel(),y_score.ravel())
micro_auc = auc(fpr, tpr)
print ('micro_auc：', micro_auc)

'Adaboost'
Ada = AdaBoostClassifier(DecisionTreeClassifier(max_depth=4, min_samples_split=20, min_samples_leaf=5),
                         algorithm="SAMME",
                         n_estimators=21, learning_rate=0.8)

print (Ada)
epoch = 5
scores = []

# Train model
start = datetime.now()

for i in range(epoch):
    Ada.fit(feature_train_scaled, y_train_decode)
    scores.append(Ada.score(feature_test_scaled, y_test_decode)) #准确率

print("This took ", datetime.now() - start)
print(u'The accuracy of the model is: ')
display_scores(scores)  #准确率

params = {
    "learning_rate": uniform(0.1, 0.9),     # default 0.1
    "n_estimators": randint(10, 120)        # default 5
#     "max_depth": randint(2, 6)            # default 3
}

search = RandomizedSearchCV(Ada, param_distributions=params, random_state=42,
                            n_iter=30, cv=5, verbose=1, n_jobs=2, return_train_score=True)

search.fit(feature_valid_scaled, y_valid_decode)

print(search.best_estimator_)
print(search.best_score_)

#evaluation
prediction_train = Ada.predict(feature_train_scaled)
cm_train = confusion_matrix(y_train_decode, prediction_train)
prediction_test = Ada.predict(feature_test_scaled)
cm_test = confusion_matrix(y_test_decode, prediction_test)

print("Confusion matrix for training dataset is \n%s\n for testing dataset is \n%s.\n"
      % (cm_train, cm_test))

#Precision_rate预测为正例的样本中的真正正例的比例
#Recall_rate预测为正例的真正正例占所有真正正例的比例

target_names = ['class 1', 'class 2', 'class 3', 'class 4', 'class 5',
                'class 6', 'class 7', 'class 8', 'class 9']
print(classification_report(y_test_decode, prediction_test, target_names=target_names))

y_score = Ada.predict_proba(feature_test_scaled)

# 计算micro类型的AUC
# print('调用函数auc：', roc_auc_score(y_test, y_score, average='micro'))

fpr, tpr, thresholds = roc_curve(y_test.ravel(),y_score.ravel())
micro_auc = auc(fpr, tpr)
print ('micro_auc：', micro_auc)

'GBDT'
GBDT = GradientBoostingClassifier(

                                  loss = 'deviance',
                                  learning_rate = 0.04,
                                  n_estimators = 68,
                                  max_depth = 4,
                                  subsample = 0.42,

                                  max_features = None,
                                  max_leaf_nodes=None,
                                  min_samples_leaf=1,
                                  min_samples_split=2,
                                  min_impurity_decrease=0.0,
                                  min_impurity_split=None,
                                  criterion='friedman_mse',
                                  min_weight_fraction_leaf=0.0,
                                  ccp_alpha=0.0
                                  )
print(GBDT)

epoch = 5
scores = []

# Train model
start = datetime.now()

for i in range(epoch):
    GBDT.fit(feature_train_scaled, y_train_decode)
    scores.append(GBDT.score(feature_test_scaled, y_test_decode)) #准确率

print("This took ", datetime.now() - start)
print(u'The accuracy of the model is: ')
display_scores(scores)  #准确率

params = {
    "learning_rate": uniform(0.03, 0.5),   # default 0.1
    "max_depth": randint(2, 6),            # default 3
    "n_estimators": randint(10, 120),      # default 100
    "subsample": uniform(0.1, 0.8)
}

search = RandomizedSearchCV(GBDT, param_distributions=params, random_state=42,
                            n_iter=30, cv=5, verbose=1, n_jobs=2, return_train_score=True)

search.fit(feature_valid_scaled, y_valid_decode)

print(search.best_estimator_)
print(search.best_score_)

#evaluation
prediction_train = GBDT.predict(feature_train_scaled)
cm_train = confusion_matrix(y_train_decode, prediction_train)
prediction_test = GBDT.predict(feature_test_scaled)
cm_test = confusion_matrix(y_test_decode, prediction_test)

print("Confusion matrix for training dataset is \n%s\n for testing dataset is \n%s.\n"
      % (cm_train, cm_test))

target_names = ['class 1', 'class 2', 'class 3', 'class 4', 'class 5',
                'class 6', 'class 7', 'class 8', 'class 9']
print(classification_report(y_test_decode, prediction_test, target_names=target_names))

y_score = GBDT.predict_proba(feature_test_scaled)

# 计算micro类型的AUC
# print('调用函数auc：', roc_auc_score(y_test, y_score, average='micro'))

fpr, tpr, thresholds = roc_curve(y_test.ravel(),y_score.ravel())
micro_auc = auc(fpr, tpr)
print ('micro_auc：', micro_auc)


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

din = '/projects/b1122/saya/04_cleaned_cnv'
dout = '/projects/b1122/saya/05_data_summary'

# candidate_cytos = ['19q13.33', '7q22.1', '1p36.33', '1q21.1', '1q21.3'] # '4p15.33', '9p21.1' # This is from Zexian's papers
candidate_cytos = [ # these are cytobands with large LASSO coefficients
    '12q24.33', '10q26.3', '10q11.22', '3q21.3', '2p21', # large positive coefficients
    '1q42.13', '1p32.3', '12q13.13', '15q26.3', '2p11.2'
]

cyto_copy = pd.read_csv(f'{din}/cyto_copy_conf90.csv', index_col=0)
cyto_thres_amp = pd.read_csv(f'{din}/cyto_thres_amp_conf90.csv', index_col=0)
cyto_thres_del = pd.read_csv(f'{din}/cyto_thres_del_conf90.csv', index_col=0)

case_copy = cyto_copy.iloc[['Tissue' in x for x in cyto_thres_amp.index],:]
control_copy = cyto_copy.iloc[['Control' in x for x in cyto_thres_amp.index],:]

case_amp = cyto_thres_amp.iloc[['Tissue' in x for x in cyto_thres_amp.index],:]
case_del = cyto_thres_del.iloc[['Tissue' in x for x in cyto_thres_del.index],:]
control_amp = cyto_thres_amp.iloc[['Control' in x for x in cyto_thres_amp.index],:]
control_del = cyto_thres_del.iloc[['Control' in x for x in cyto_thres_del.index],:]

for cyto in candidate_cytos:
    ## build amp/del count table
    cf = pd.DataFrame(index=['cases', 'controls'], columns=['amp only', 'del only', 'amp & del', 'none'])
    # count cases
    cf.loc['cases','amp only'] = np.sum((case_amp[cyto]>0) & (case_del[cyto]==0))
    cf.loc['cases','del only'] = np.sum((case_amp[cyto]==0) & (case_del[cyto]<0))
    cf.loc['cases', 'amp & del'] = np.sum((case_amp[cyto]>0) & (case_del[cyto]<0))
    cf.loc['cases','none'] = np.sum((case_amp[cyto]==0) & (case_del[cyto]==0))
    # count controls
    cf.loc['controls','amp only'] = np.sum((control_amp[cyto]>0) & (control_del[cyto]==0))
    cf.loc['controls','del only'] = np.sum((control_amp[cyto]==0) & (control_del[cyto]<0))
    cf.loc['controls', 'amp & del'] = np.sum((control_amp[cyto]>0) & (control_del[cyto]<0))
    cf.loc['controls','none'] = np.sum((control_amp[cyto]==0) & (control_del[cyto]==0))
    # save matrix
    cfnorm = cf/np.transpose([cf.sum(axis=1).values])
    cfnorm.to_csv(f'{dout}/ampdelcounts_{cyto}.csv', index=True)
    ## plot histogram
    fig, ax = plt.subplots(nrows=1, ncols=1)
    ax.hist(case_copy[cyto], alpha=0.5, label='cases')
    ax.hist(control_copy[cyto], alpha=0.5, label='controls')
    ax.legend(loc='upper right')
    fig.savefig(f'{dout}/{cyto}_histogram.png')
    plt.close()


import logging
import sys
from logging.config import dictConfig
from logging.handlers import QueueHandler, QueueListener
from pathlib import Path
from typing import Optional

from PyQt5 import QtCore

from gridplayer.utils.qt import is_qt_log_ignored

DISABLED = logging.CRITICAL + 1

class QueueListenerRoot(QueueListener):
    def __init__(self, queue):
        super().__init__(queue, *logging.root.handlers, respect_handler_level=True)

    def handle(self, record):
        if record.levelno < logging.root.level:
            return

        super().handle(record)

class StreamToLogger(object):
    """
    Fake file-like stream object that redirects writes to a logger instance.
    """

    def __init__(self, logger, log_level=logging.INFO):
        self.logger = logger
        self.log_level = log_level
        self.linebuf = ""

    def write(self, buf):
        for line in buf.rstrip().splitlines():
            self.logger.log(self.log_level, line.rstrip())

    def flush(self):
        """Not used"""

    def isatty(self):
        return False

class QtLogHandler(object):
    log_level_map = {
        QtCore.QtDebugMsg: logging.DEBUG,
        QtCore.QtInfoMsg: logging.INFO,
        QtCore.QtWarningMsg: logging.WARNING,
        QtCore.QtCriticalMsg: logging.ERROR,
        QtCore.QtFatalMsg: logging.CRITICAL,
    }

    def __init__(self):
        self._log = logging.getLogger("QT")

    def handle(self, mode, context, message):
        if is_qt_log_ignored(message):
            return

        log_level = self.log_level_map[mode]

        if context.file is not None:
            log_msg_head = (
                f"qt_message_handler: line: {context.line},"
                f" func: {context.function},"
                f" file: {context.file}"
            )

            self._log.log(log_level, log_msg_head)

        self._log.log(log_level, message.strip())

def config_log(
    log_path: Path,
    log_level: int,
    max_log_size: Optional[int] = None,
    max_log_backups: Optional[int] = None,
):
    config = {
        "version": 1,
        "formatters": {
            # Modify log message format here or replace with your custom formatter class
            "my_formatter": {
                "format": "%(asctime)s (%(process)d) | %(name)s |"  # noqa: WPS323
                " %(levelname)s | %(message)s"
            }
        },
        "handlers": {
            "console_stderr": {
                # Sends log messages to stderr
                "class": "logging.StreamHandler",
                "level": "DEBUG",
                "formatter": "my_formatter",
                "stream": sys.__stderr__,  # noqa: WPS609
            },
            "file": {
                # Sends all log messages to a file
                "class": "logging.FileHandler",
                "level": "DEBUG",
                "formatter": "my_formatter",
                "filename": str(log_path),
                "encoding": "utf8",
            },
        },
        "root": {
            # In general, this should be kept at 'NOTSET'.
            # Otherwise it would interfere with the log levels set for each handler.
            "level": log_level,
            "handlers": ["console_stderr", "file"],
        },
    }

    if max_log_size is not None and max_log_backups is not None:
        config["handlers"]["file"]["class"] = "logging.handlers.RotatingFileHandler"
        config["handlers"]["file"]["maxBytes"] = max_log_size
        config["handlers"]["file"]["backupCount"] = max_log_backups

    dictConfig(config)

def set_root_level(log_level):
    logging.root.setLevel(log_level)

def child_process_config(queue, log_level):
    h = QueueHandler(queue)

    root = logging.getLogger()
    root.addHandler(h)
    root.setLevel(log_level)


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('varer', '0016_auto_20141227_0243'),
    ]

    operations = [
        migrations.AddField(
            model_name='salgsvare',
            name='kassenavn',
            field=models.CharField(max_length=15, help_text='Navn i varekatalog i kassa', blank=True, null=True),
            preserve_default=True,
        ),
    ]


from typing import Any, List, Callable
import cv2
import threading
import numpy as np
import onnxruntime
import onnx
import ogi.globals

from ogi.typing import Face, Frame, FaceSet
from ogi.utilities import resolve_relative_path

# THREAD_LOCK = threading.Lock()

class Enhance_CodeFormer():
    model_codeformer = None
    devicename = None

    processorname = 'codeformer'
    type = 'enhance'

    def Initialize(self, devicename:str):
        if self.model_codeformer is None:
            # replace Mac mps with cpu for the moment
            devicename = devicename.replace('mps', 'cpu')
            self.devicename = devicename
            model_path = resolve_relative_path('../models/CodeFormer/CodeFormerv0.1.onnx')
            self.model_codeformer = onnxruntime.InferenceSession(model_path, None, providers=ogi.globals.execution_providers)
            self.model_inputs = self.model_codeformer.get_inputs()
            model_outputs = self.model_codeformer.get_outputs()
            self.io_binding = self.model_codeformer.io_binding()
            self.io_binding.bind_cpu_input(self.model_inputs[1].name, np.array([0.5]))
            self.io_binding.bind_output(model_outputs[0].name, self.devicename)

    def Run(self, source_faceset: FaceSet, target_face: Face, temp_frame: Frame) -> Frame:
        input_size = temp_frame.shape[1]
        # preprocess
        temp_frame = cv2.resize(temp_frame, (512, 512), cv2.INTER_CUBIC)
        temp_frame = cv2.cvtColor(temp_frame, cv2.COLOR_BGR2RGB)
        temp_frame = temp_frame.astype('float32') / 255.0
        temp_frame = (temp_frame - 0.5) / 0.5
        temp_frame = np.expand_dims(temp_frame, axis=0).transpose(0, 3, 1, 2)

        self.io_binding.bind_cpu_input(self.model_inputs[0].name, temp_frame.astype(np.float32))
        self.model_codeformer.run_with_iobinding(self.io_binding)
        ort_outs = self.io_binding.copy_outputs_to_cpu()
        result = ort_outs[0][0]
        del ort_outs

        # post-process
        result = result.transpose((1, 2, 0))

        un_min = -1.0
        un_max = 1.0
        result = np.clip(result, un_min, un_max)
        result = (result - un_min) / (un_max - un_min)

        result = cv2.cvtColor(result, cv2.COLOR_RGB2BGR)
        result = (result * 255.0).round()
        scale_factor = int(result.shape[1] / input_size)
        return result.astype(np.uint8), scale_factor

    def Release(self):
        del self.model_codeformer
        self.model_codeformer = None
        del self.io_binding
        self.io_binding = None


import io
from re import X
import sys

_INPUT = """\
ooo???xxxx
"""
sys.stdin = io.StringIO(_INPUT)

S = list(input())
O = []
X = []

# Sの文字列の中で、条件に合致するのか確認
def judge(s):
    # 値の中に必ず含まれていないといけないもの
    for i in O:
        if i not in s:
            return False

    # 値の中に含まれていたらダメなもの
    for i in X:
        if i in s:
            return False

    return True

ans = 0

for i,char in enumerate(S):
    if char == "o":
        O.append(str(i))

    elif char == "x":
        X.append(str(i))

# print(O,X)

for i in range(10000):
    s = str(i).zfill(4)
    if judge(s):
        ans += 1

print(ans)


 # * MotorBridge.py
 # * This is a library for BBG/BBB motor bridge cape
 # * Copyright (c) 2015 seeed technology inc.
 # * Author      : Jiankai Li
 # * Create Time:  Nov 2015
 # * Change Log : Jan. 2023 by Seth w/ help from #beagle on IRC and vsx-examples for gpiod in python3...
 # *
 # * The MIT License (MIT)
 # *
 # * Permission is hereby granted, free of charge, to any person obtaining a copy
 # * of this software and associated documentation files (the "Software"), to deal
 # * in the Software without restriction, including without limitation the rights
 # * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 # * copies of the Software, and to permit persons to whom the Software is
 # * furnished to do so, subject to the following conditions:
 # *
 # * The above copyright notice and this permission notice shall be included in
 # * all copies or substantial portions of the Software.
 # *
 # * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 # * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 # * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 # * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 # * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 # * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 # * THE SOFTWARE.
 # */
# FileName : MotorBridge.py
# by Jiankai.li

from smbus2 import SMBus
from time import sleep
#import pathlib
import gpiod

CHIP = 'gpiochip1'
LINE_OFFSET = [17]

chip = gpiod.Chip(CHIP)

lines = chip.get_lines(LINE_OFFSET)
lines.request(consumer=' ', type=gpiod.LINE_REQ_DIR_OUT)

lines.set_values([0])

bus = SMBus('/dev/i2c-2')

ReadMode  = 0
WriteMode = 1
DeAddr    = 0X4B
ConfigValid =  0x3a6fb67c
DelayTime = 0.005

# TB_WORKMODE

TB_SHORT_BREAK  = 0
TB_CW           = 1
TB_CCW          = 2
TB_STOP         = 3
TB_WORKMODE_NUM = 4

# TB_PORTMODE

TB_DCM          = 0
TB_SPM          = 1
TB_PORTMODE_NUM = 2

# SVM_PORT

SVM1            = 0
SVM2            = 1
SVM3            = 2
SVM4            = 3
SVM5            = 4
SVM6            = 5
SVM_PORT_NUM    = 6

# SVM_STATE

SVM_DISABLE     = 0
SVM_ENABLE      = 1
SVM_STATE_NUM   = 2

# IO_MODE

IO_IN           = 0
IO_OUT          = 1
IO_MODE_NUM     = 2

# IO_PUPD

IO_PU           = 0
IO_PD           = 1
IO_NP           = 2
IO_PUPD_NUM     = 3

# IO_PPOD

IO_PP           = 0
IO_OD           = 1
IO_PPOD_NUM     = 2

# IO_STATE

IO_LOW          = 0
IO_HIGH         = 1
IO_STATE_NUM    = 2

# IO_PORT

IO1             = 0
IO2             = 1
IO3             = 2
IO4             = 3
IO5             = 4
IO6             = 5
IO_NUM          = 6

# PARAM_REG

CONFIG_VALID        = 0
CONFIG_TB_PWM_FREQ  = CONFIG_VALID + 4

I2C_ADDRESS         = CONFIG_TB_PWM_FREQ + 4

TB_1A_MODE          = I2C_ADDRESS + 1
TB_1A_DIR           = TB_1A_MODE + 1
TB_1A_DUTY          = TB_1A_DIR + 1
TB_1A_SPM_SPEED     = TB_1A_DUTY + 2
TB_1A_SPM_STEP      = TB_1A_SPM_SPEED + 4

TB_1B_MODE          = TB_1A_SPM_STEP + 4
TB_1B_DIR           = TB_1B_MODE + 1
TB_1B_DUTY          = TB_1B_DIR + 1
TB_1B_SPM_SPEED     = TB_1B_DUTY + 2
TB_1B_SPM_STEP      = TB_1B_SPM_SPEED + 4

TB_2A_MODE          = TB_1B_SPM_STEP + 4
TB_2A_DIR           = TB_2A_MODE + 1
TB_2A_DUTY          = TB_2A_DIR + 1
TB_2A_SPM_SPEED     = TB_2A_DUTY + 2
TB_2A_SPM_STEP      = TB_2A_SPM_SPEED + 4

TB_2B_MODE          = TB_2A_SPM_STEP + 4
TB_2B_DIR           = TB_2B_MODE + 1
TB_2B_DUTY          = TB_2B_DIR + 1
TB_2B_SPM_SPEED     = TB_2B_DUTY + 2
TB_2B_SPM_STEP      = TB_2B_SPM_SPEED + 4

SVM1_STATE          = TB_2B_SPM_STEP + 4
SVM1_FREQ           = SVM1_STATE + 1
SVM1_ANGLE          = SVM1_FREQ + 2

SVM2_STATE          = SVM1_ANGLE + 2
SVM2_FREQ           = SVM2_STATE + 1
SVM2_ANGLE          = SVM2_FREQ + 2

SVM3_STATE          = SVM2_ANGLE + 2
SVM3_FREQ           = SVM3_STATE + 1
SVM3_ANGLE          = SVM3_FREQ + 2

SVM4_STATE          = SVM3_ANGLE + 2
SVM4_FREQ           = SVM4_STATE + 1
SVM4_ANGLE          = SVM4_FREQ + 2

SVM5_STATE          = SVM4_ANGLE + 2
SVM5_FREQ           = SVM5_STATE + 1
SVM5_ANGLE          = SVM5_FREQ + 2

SVM6_STATE          = SVM5_ANGLE + 2
SVM6_FREQ           = SVM6_STATE + 1
SVM6_ANGLE          = SVM6_FREQ + 2

IO1_STATE           = SVM6_ANGLE + 2
IO1_MODE            = IO1_STATE + 1
IO1_PUPD            = IO1_MODE + 1
IO1_PPOD            = IO1_PUPD + 1

IO2_STATE           = IO1_PPOD + 1
IO2_MODE            = IO2_STATE + 1
IO2_PUPD            = IO2_MODE + 1
IO2_PPOD            = IO2_PUPD + 1

IO3_STATE           = IO2_PPOD + 1
IO3_MODE            = IO3_STATE + 1
IO3_PUPD            = IO3_MODE + 1
IO3_PPOD            = IO3_PUPD + 1

IO4_STATE           = IO3_PPOD + 1
IO4_MODE            = IO4_STATE + 1
IO4_PUPD            = IO4_MODE + 1
IO4_PPOD            = IO4_PUPD + 1

IO5_STATE           = IO4_PPOD + 1
IO5_MODE            = IO5_STATE + 1
IO5_PUPD            = IO5_MODE + 1
IO5_PPOD            = IO5_PUPD + 1

IO6_STATE           = IO5_PPOD + 1
IO6_MODE            = IO6_STATE + 1
IO6_PUPD            = IO6_MODE + 1
IO6_PPOD            = IO6_PUPD + 1

PARAM_REG_NUM = IO6_PPOD + 1

def WriteByte(Reg,Value):
    data = [0 for i in range(2)]
    data[0] = Reg
    data[1] = Value
    bus.write_i2c_block_data(0x4b, 1, data)

def WriteHalfWord(Reg,Value):
    data = [0 for i in range(3)]
    data[0] = Reg
    data[1] = Value & 0xff
    data[2] = (Value>>8) & 0xff
    bus.write_i2c_block_data(0x4b, 1, data)

def WriteOneWord(Reg,Value):
    data = [0 for i in range(5)]
    data[0] = Reg
    data[1] = Value & 0xff
    data[2] = (Value>>8) & 0xff
    data[3] = (Value>>16) & 0xff
    data[4] = (Value>>24) & 0xff
    bus.write_i2c_block_data(0x4b, 1, data)

def SetDefault():
    WriteOneWord(CONFIG_VALID, 0x00000000)

class MotorBridgeCape:
    def __init__(self):
        lines.set_values([1])
        sleep(1)

    # init stepper motor A
    def StepperMotorAInit(self):
        WriteByte(TB_1A_MODE, TB_SPM) #Stepper
        sleep(DelayTime)
        WriteHalfWord(TB_1A_DUTY, 1000)    # voltage
        sleep(DelayTime)

    # MoveSteps > 0 CW
    # MoveSteps < 0 CCW
    # StepDelayTime : delay time for every step. uint us
    def StepperMotorAMove(self, MoveSteps, StepDelayTime):
        if MoveSteps > 0:
            WriteByte(TB_1A_DIR, TB_CW)   #CW
        else:
            WriteByte(TB_1A_DIR, TB_CCW)   #CW
            MoveSteps = -MoveSteps
        sleep(DelayTime)
        WriteOneWord(TB_1A_SPM_SPEED, StepDelayTime)  # unit us
        sleep(DelayTime)
        WriteOneWord(TB_1A_SPM_STEP, MoveSteps)
        sleep(DelayTime)

    # init stepper motor B
    def StepperMotorBInit(self):
        WriteByte(TB_2A_MODE, TB_SPM) #Stepper
        sleep(DelayTime)
        WriteHalfWord(TB_2A_DUTY, 1000)    # voltage
        sleep(DelayTime)

    # MoveSteps > 0 CW
    # MoveSteps < 0 CCW
    # StepDelayTime : delay time for every step. uint us
    def StepperMotorBMove(self, MoveSteps, StepDelayTime):
        if MoveSteps > 0:
            WriteByte(TB_2A_DIR, TB_CW)   #CW
        else:
            WriteByte(TB_2A_DIR, TB_CCW)   #CW
            MoveSteps = -MoveSteps
        sleep(DelayTime)
        WriteOneWord(TB_2A_SPM_SPEED, StepDelayTime)  # unit us
        sleep(DelayTime)
        WriteOneWord(TB_2A_SPM_STEP, MoveSteps)
        sleep(DelayTime)

    # Init DC Motor
    def DCMotorInit(self,MotorName, Frequency):
    # Init the DC Frequency
        WriteOneWord(CONFIG_TB_PWM_FREQ, Frequency)
        sleep(DelayTime)

    # Set the port as DC Motor
        if MotorName == 1 or MotorName == 2:
            WriteByte(TB_1A_MODE, TB_DCM)
            sleep(DelayTime)
            WriteByte(TB_1A_DIR, TB_STOP)
            sleep(DelayTime)
            WriteByte(TB_1B_MODE, TB_DCM)
            sleep(DelayTime)
            WriteByte(TB_1B_DIR, TB_STOP)
            sleep(DelayTime)
        if MotorName == 3 or MotorName == 4:
            WriteByte(TB_2A_MODE, TB_DCM)
            sleep(DelayTime)
            WriteByte(TB_2A_DIR, TB_STOP)
            sleep(DelayTime)
            WriteByte(TB_2B_MODE, TB_DCM)
            sleep(DelayTime)
            WriteByte(TB_2B_DIR, TB_STOP)
            sleep(DelayTime)

    # Drive the DC Motor
    # Direction 1 CW | 2 CCW
    # PWNDuty  0 ~ 100
    def DCMotorMove(self, MotorName, Direction, PWMDuty):
        if MotorName == 1:
            WriteByte(TB_1B_DIR, Direction)
            sleep(DelayTime)
            WriteOneWord(TB_1B_DUTY, PWMDuty*10)
            sleep(DelayTime)

        if MotorName == 2:
            WriteByte(TB_1A_DIR, Direction)
            sleep(DelayTime)
            WriteOneWord(TB_1A_DUTY, PWMDuty*10)
            sleep(DelayTime)

        if MotorName == 3:
            WriteByte(TB_2B_DIR, Direction)
            sleep(DelayTime)
            WriteOneWord(TB_2B_DUTY, PWMDuty*10)
            sleep(DelayTime)

        if MotorName == 4:
            WriteByte(TB_2A_DIR, Direction)
            sleep(DelayTime)
            WriteOneWord(TB_2A_DUTY, PWMDuty*10)
            sleep(DelayTime)

    # Stop the DC motor
    def DCMotorStop(self, MotorName):
        if MotorName == 1:
            WriteByte(TB_1B_DIR, TB_STOP)
        if MotorName == 2:
            WriteByte(TB_1A_DIR, TB_STOP)
        if MotorName == 3:
            WriteByte(TB_2B_DIR, TB_STOP)
        if MotorName == 4:
            WriteByte(TB_2A_DIR, TB_STOP)
        sleep(DelayTime)

    # init the Servo
    def ServoInit(self, ServoName, Frequency):
        if ServoName == 1:
            WriteHalfWord(SVM1_FREQ, Frequency)
            sleep(DelayTime)
            WriteByte(SVM1_STATE, SVM_ENABLE)
            sleep(DelayTime)

        if ServoName == 2:
            WriteHalfWord(SVM2_FREQ, Frequency)
            sleep(DelayTime)
            WriteByte(SVM2_STATE, SVM_ENABLE)
            sleep(DelayTime)
        if ServoName == 3:
            WriteHalfWord(SVM3_FREQ, Frequency)
            sleep(DelayTime)
            WriteByte(SVM3_STATE, SVM_ENABLE)
            sleep(DelayTime)

        if ServoName == 4:
            WriteHalfWord(SVM4_FREQ, Frequency)
            sleep(DelayTime)
            WriteByte(SVM4_STATE, SVM_ENABLE)
            sleep(DelayTime)
        if ServoName == 5:
            WriteHalfWord(SVM5_FREQ, Frequency)
            sleep(DelayTime)
            WriteByte(SVM5_STATE, SVM_ENABLE)
            sleep(DelayTime)

        if ServoName == 6:
            WriteHalfWord(SVM6_FREQ, Frequency)
            sleep(DelayTime)
            WriteByte(SVM6_STATE, SVM_ENABLE)
            sleep(DelayTime)

    def ServoMoveAngle(self, ServoName, Angle):
        if ServoName == 1:
            WriteHalfWord(SVM1_ANGLE, Angle)
            sleep(DelayTime)

        if ServoName == 2:
            WriteHalfWord(SVM2_ANGLE, Angle)
            sleep(DelayTime)

        if ServoName == 3:
            WriteHalfWord(SVM3_ANGLE, Angle)
            sleep(DelayTime)

        if ServoName == 4:
            WriteHalfWord(SVM4_ANGLE, Angle)
            sleep(DelayTime)

        if ServoName == 5:
            WriteHalfWord(SVM5_ANGLE, Angle)
            sleep(DelayTime)

        if ServoName == 6:
            WriteHalfWord(SVM6_ANGLE, Angle)
            sleep(DelayTime)

#def myloop():

    #time.sleep(1)
    #motor.StepperMotorBMove(-1000,1000) # 20 steppers  1000us every step
    #time.sleep(1)
    #motor.StepperMotorBMove(1000,1000)  # 20 steppers  1000us every step

if __name__=="__main__":
    print("Hello!")

    #motor = MotorBridgeCape()
    #motor.StepperMotorBInit()
    #motor.StepperMotorBMove(1000,1000) # 20 steppers  1000us every step
    #myloop()