import pandas as pd
import numpy as np
from datetime import datetime
from matplotlib.dates import date2num
import matplotlib.pyplot as plt
import sklearn.linear_model as linear_model
import sklearn.metrics as metrics
import statsmodels.api as sm
from scipy import stats
from sklearn.model_selection import train_test_split
pd.set_option('display.max_columns', None)

holiday_data = pd.read_csv('data/bankholiday(2017-2021).csv', parse_dates=True)
hdays = pd.concat([holiday_data['2020'], holiday_data['2021']])
hdays = [datetime.strptime(x, "%Y-%m-%d") for x in hdays]

def filter_data(df):
    df['day_of_week'] = df['date'].dt.dayofweek
    df['weekday'] = ~df['day_of_week'].isin([5, 6])
    df['weekend'] = df['day_of_week'].isin([5, 6])
    df['holiday'] = df['date'].isin(hdays)
    df = df.replace({True: 1, False: 0})
    return df

PLOTS_DIR = 'plots/'

df = pd.read_csv('data/apple_mobility.csv',parse_dates=True)
df['date'] = [datetime.strptime(x, "%d/%m/%Y") for x in df['date']]
hw_df = pd.read_csv('data/activity_homeworking.csv')
hw_df['date'] = [datetime.strptime(x, "%Y-%m-%d") for x in hw_df['date']]
case_df = pd.read_csv('data/data_2021-Mar-16.csv', parse_dates=False)
case_df['date'] = [datetime.strptime(x, "%d/%m/%Y") for x in case_df['date']]

#filter working from home data
hw_df = filter_data(hw_df)
hw1_df = hw_df.loc[(hw_df['activity'] == 'Residential') & (
        hw_df['weekday'] == 1) & (hw_df['holiday'] == 0)].drop(columns=['location','source'])
hw0_df = hw_df.loc[(hw_df['activity'] == 'Workplaces') & (
        hw_df['weekday'] == 1) & (hw_df['holiday'] == 0)].drop(columns=['location','source'])

#filter covid-19 cases data
case_df = case_df.loc[case_df['date'].isin(df['date'])].drop(columns=['areaType','areaName','areaCode'])
df_new = pd.merge(df, case_df, on='date')

#visualize school_closed restriction
fig, ax = plt.subplots(figsize=(12, 6))
ax.plot(df['date'], df['driving'], label='driving')
ax.plot(df['date'], df['transit'], label='transit')
ax.plot(df['date'], df['walking'], label='walking')
ax.set_xlabel('Time')
ax.axvspan(date2num(datetime(2020,3,23)), date2num(datetime(2020,5,31)), color="grey", alpha=0.15)
ax.axvspan(date2num(datetime(2021,1,5)), date2num(datetime(2021,3,7)), color="grey", alpha=0.15)
ax.set_title('School Closed Restriction', size=18)
ax.grid(True)
ax.legend(loc='best')
#plt.savefig(PLOTS_DIR + 'school_closed_restriction' + '.png')
plt.show()
plt.close()

#visualize pub_closed restriction
#df = get_day_of_week(df).loc[df['weekend'] == 1]
fig, ax = plt.subplots(figsize=(12, 6))
ax.plot(df['date'], df['driving'], label='driving')
ax.plot(df['date'], df['transit'], label='transit')
ax.plot(df['date'], df['walking'], label='walking')
ax.set_xlabel('Time')
ax.axvspan(date2num(datetime(2020,3,21)), date2num(datetime(2020,7,3)), color="grey", alpha=0.15)
ax.axvspan(date2num(datetime(2020,11,5)), date2num(datetime(2020,12,1)), color="grey", alpha=0.15)
ax.axvspan(date2num(datetime(2020,12,16)), date2num(datetime(2021,3,14)), color="grey", alpha=0.15)
ax.set_title('Pubs Closed Restriction', size=18)
ax.grid(True)
ax.legend(loc='best')
#plt.savefig(PLOTS_DIR + 'pub_restriction' + '.png')
plt.show()
plt.close()

#visualize lockdown restriction
fig, ax = plt.subplots(figsize=(12, 6))
ax.plot(df['date'], df['driving'], label='driving')
ax.plot(df['date'], df['transit'], label='transit')
ax.plot(df['date'], df['walking'], label='walking')
ax.set_xlabel('Time')
ax.axvspan(date2num(datetime(2020,3,24)), date2num(datetime(2020,5,10)), color="grey", alpha=0.15)
ax.axvspan(date2num(datetime(2020,11,5)), date2num(datetime(2020,12,1)), color="grey", alpha=0.15)
ax.axvspan(date2num(datetime(2020,12,20)), date2num(datetime(2021,3,14)), color="grey", alpha=0.15)
ax.set_title('Lockdown Restriction', size=18)
ax.grid(True)
ax.legend(loc='best')
#plt.savefig(PLOTS_DIR + 'lockdown' + '.png')
plt.show()
plt.close()

#visualize working from home data
fig, ax = plt.subplots(figsize=(12, 6))
ax.plot(hw0_df['date'], hw0_df['value'], label='Workplaces')
ax.plot(hw1_df['date'], hw1_df['value'], label='Residential')
ax.set_xlabel('Time')
ax.axvspan(date2num(datetime(2020,3,24)), date2num(datetime(2020,5,10)), color="grey", alpha=0.15)
ax.axvspan(date2num(datetime(2020,11,5)), date2num(datetime(2020,12,1)), color="grey", alpha=0.15)
ax.axvspan(date2num(datetime(2020,12,20)), date2num(datetime(2021,3,14)), color="grey", alpha=0.15)
ax.set_title('Lockdown Restriction-Working from home', size=18)
ax.grid(True)
ax.legend(loc='upper right')
#plt.savefig(PLOTS_DIR + 'work_from_home' + '.png')
plt.show()
plt.close()

#visualize death number
fig, ax1 = plt.subplots(figsize=(12, 6))
ax1.plot(df_new['date'], df_new['driving'], label='driving')
ax1.plot(df_new['date'], df_new['transit'], label='transit')
ax1.plot(df_new['date'], df_new['walking'], label='walking')
ax1.set_xlabel('Time')
ax1.axvspan(date2num(datetime(2020,3,24)), date2num(datetime(2020,5,10)), color="grey", alpha=0.15)
ax1.axvspan(date2num(datetime(2020,11,5)), date2num(datetime(2020,12,1)), color="grey", alpha=0.15)
ax1.axvspan(date2num(datetime(2020,12,20)), date2num(datetime(2021,3,14)), color="grey", alpha=0.15)
ax1.set_title('Lockdown Restriction with daily death number', size=18)
ax1.grid(True)
ax1.legend(loc='best')

ax2 = ax1.twinx()
ax2.plot(df_new['date'], df_new['newDeaths28DaysByDeathDate'], label='deaths', color='black')
ax2.legend(loc='best')
fig.tight_layout()
#plt.savefig(PLOTS_DIR + 'covid-19 deaths' + '.png')
plt.show()
plt.close()

#visualize case number
fig, ax1 = plt.subplots(figsize=(12, 6))
ax1.plot(df_new['date'], df_new['driving'], label='driving')
ax1.plot(df_new['date'], df_new['transit'], label='transit')
ax1.plot(df_new['date'], df_new['walking'], label='walking')
ax1.set_xlabel('Time')
ax1.axvspan(date2num(datetime(2020,3,24)), date2num(datetime(2020,5,10)), color="grey", alpha=0.15)
ax1.axvspan(date2num(datetime(2020,11,5)), date2num(datetime(2020,12,1)), color="grey", alpha=0.15)
ax1.axvspan(date2num(datetime(2020,12,20)), date2num(datetime(2021,3,14)), color="grey", alpha=0.15)
ax1.set_title('Lockdown Restriction with daily cases', size=18)
ax1.grid(True)
ax1.legend(loc='best')

ax2 = ax1.twinx()
ax2.plot(df_new['date'], df_new['newCasesBySpecimenDate'], label='cases', color='red')
ax2.legend(loc='best')
fig.tight_layout()
#plt.savefig(PLOTS_DIR + 'covid-19 cases' + '.png')
plt.show()
plt.close()

#analyse mobility data with restrictions
r_df = pd.read_csv('data/restrictions_daily.csv',parse_dates=True)
r_df['date'] = [datetime.strptime(x, "%d/%m/%Y") for x in r_df['date']]
ld_df = r_df[['date','stay_at_home','length']]
df_new = df_new.merge(ld_df, on='date').fillna(0)
df_new = filter_data(df_new)
df_new['case_ratio'] = df_new['newCasesBySpecimenDate'] / np.mean(df_new['newCasesBySpecimenDate']) * 100
df_new['death_ratio'] = df_new['newDeaths28DaysByDeathDate'] / np.mean(df_new['newDeaths28DaysByDeathDate']) * 100
df_new['case_ratio'] = df_new.apply(lambda x: np.log(x['case_ratio']), axis=1)
df_new['death_ratio'] = df_new.apply(lambda x: np.log(x['death_ratio'] + 1), axis=1)
print(df_new.iloc[-10:,])

#regression analysis
X = df_new[['stay_at_home','length','weekday','weekend','holiday','case_ratio','death_ratio']].to_numpy()
y_d = df_new['driving'].to_numpy()
y_t = df_new['transit'].to_numpy()
y_w = df_new['walking'].to_numpy()
est = sm.OLS(y_d, X)
est_d = est.fit()
print('driving mobility analysis')
print(est_d.summary())
print('')
est = sm.OLS(y_t, X)
est_t = est.fit()
print('transit mobility analysis')
print(est_t.summary())
print('')
est = sm.OLS(y_w, X)
est_w = est.fit()
print('walking mobility analysis')
print(est_w.summary())


# f         (str) : Function in terms of x, y, and z
# x, y, z (float) : Value to sample function at
def function(f, x = 0, y = 0, z = 0):
    if 't' in f:
        return eval(f.replace('t', str(x)))
    if '^' in f:
        f = f.replace('^', '**')
    for i in ['e', 'pi', 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'ceil', 'floor', 'log']:
        if i in f:
            f = f.replace(i, 'math.' + i)
    return eval(f.replace('x', str(x)).replace('y', str(y)).replace('z', str(z)))

# f   (str) : Function in terms of x, y, and z
# x (float) : Value to sample derivative at
# h (float) : Size of gap for secant line
def derivative(f, x, h = 10e-4):
    return (function(f, (x + h)) - function(f, x)) / h

# f       (str) : Function in terms of x, y, and z
# a, b  (float) : Lower and upper bounds for x
# type (string) : Method of calculation (lower, midpoint, upper)
# delta (float) : Size of Riemann samples of f
def integral(f, a, b, type = 'midpoint', delta = 10e-4):
    total = 0
    if type == 'lower':
        for i in range(int((b-a) / delta)):
            total += function(f, (a + i * delta)) * delta
    if type == 'midpoint':
        for i in range(int((b-a) / delta)):
            total += function(f, (a + (i + 0.5) * delta)) * delta
    if type == 'upper':
        for i in range(int((b-a) / delta)):
            total += function(f, (a + (i + 1) * delta)) * delta
    return total

# f       (str) : Function in terms of x, y, and z
# a, b  (float) : Lower and upper bounds for x
# c, d  (float) : Lower and upper bounds for y
# type    (str) : Method of calculation (lower, midpoint, upper)
# delta (float) : Size of Riemann samples of f
def double_integral(f, a, b, c, d, type = 'midpoint', delta = 10e-4):
    total = 0
    if type == 'lower':
        for i in range(int((b-a) / delta)):
            for j in range(int((d-c) / delta)):
                total += function(f, a + i * delta, c + j * delta) * delta**2
    if type == 'midpoint':
        for i in range(int((b-a) / delta)):
            for j in range(int((d-c) / delta)):
                total += function(f, a + (i + 0.5) * delta, c + (j + 0.5) * delta) * delta**2
    if type == 'upper':
        for i in range(int((b-a) / delta)):
            for j in range(int((d-c) / delta)):
                total += function(f, a + (i + 1) * delta, c + (j + 1) * delta) * delta**2
    return total

# f       (str) : Function in terms of x, y, and z
# r      (list) : Vector valued function in terms of t (Curve to integrate along)
# a, b  (float) : Lower and upper bounds for t
# delta (float) : Size of Riemann samples of f
def path_integral(f, r, a, b, delta = 10e-4):
    f = f.replace('x', r[0]).replace('y', r[1]).replace('z', r[2])
    total = 0
    for i in range(int((b-a) / delta)):
        v = a + i * delta
        total += function(f, v) * (derivative(r[0], v)**2 + derivative(r[1], v)**2 + derivative(r[2], v)**2) ** (1/2) * delta
    return total


import argparse
import os
import numpy as np

verboseprint = lambda *a, **k: None

def count_below_val(word_counts):
    max_val = int(np.amax(word_counts,axis = 0)[0])
    print(max_val)
    return_good = [None]*(max_val)
    return_bad = [None]*(max_val)
    bad_vid_ids = []
    good_vids = []

    for word_count_max in range(0,max_val):
        bad_vid_ids = []
        good_vids = []
        temp = 0
        for word_count in word_counts:
            if(word_count[0] <= word_count_max):
                good_vids.append(word_count)
            else:
                bad_vid_ids.append(word_count[1])

        bad_vid_ids = np.unique(bad_vid_ids)

        for bad_id in bad_vid_ids:
            for good_vid in good_vids:
                if(good_vid[1] == bad_id):
                    good_vids.remove(good_vid)

        return_good[word_count_max] = (len(good_vids))
        return_bad[word_count_max] = (len(bad_vid_ids))

        verboseprint('through one vid')
    return (return_good,return_bad)

def main(args):
    global verboseprint
    verboseprint = print if args.v else lambda *a, **k: None

    total_line_time = 0
    total_number_lines = 0
    total_number_words = 0
    list_line_time = []
    list_line_word = []
    bad_file_count = 0

    #histogram

    file_id = 0

    for file in os.listdir(args.input):
        verboseprint("reading file %s" % file)
        file_o = open(os.path.join(args.input,file),'r')
        temp_line = file_o.readline()
        while(temp_line != ''):
            line_list = temp_line.split(',')
            if(line_list[0] != ''):
                total_number_words += len(line_list[0].split())
                list_line_word.append((len(line_list[0].split()),file_id))

            if((line_list[-2] != '') and (line_list[-1] != '')):
                try:
                    total_number_lines += 1
                    temp_time = float(line_list[-1]) - float(line_list[-2])
                    total_line_time += temp_time
                    list_line_time.append((temp_time,file_id))
                except:
                    bad_file_count +=1
                    print(file)
            temp_line = file_o.readline()
        file_id += 1

    word_count_max = int(np.amax(list_line_word,axis=0)[0])
    x_plot_words = [None]*(word_count_max)
    for i in range(0,word_count_max):
        x_plot_words[i] = i
    sentences,lost_vids = count_below_val(list_line_word)

    time_count_max = int(np.amax(list_line_time,axis=0)[0])
    x_plot_times = [None]*(time_count_max)
    for i in range(0,time_count_max):
        x_plot_times[i] = i
    sentences,lost_vids = count_below_val(list_line_time)

    hist, bin_edges = (np.histogram(list_line_word, bins=20,range=(0.0,40.0)))

    hist, bin_edges = (np.histogram(list_line_time, bins=20,range=(0.0,20.0)))

    print('Total Number of Lines: %d' % total_number_lines)
    print('')
    print('Average Line Time: %f' % (total_line_time / total_number_lines))
    print('Median Line Time: %f' % (np.median(list_line_time)))
    print('Standard Deviation Line Time: %f' % (np.std(list_line_time)))
    print('')
    print('Average Words per Line: %f' % (total_number_words / total_number_lines))
    print('Median Words per Line: %f' % (np.median(list_line_word)))
    print('Standard Deviation Words per Line: %f' % (np.std(list_line_word)))
    print('')

def parse_args():
    parser = argparse.ArgumentParser(description='Splitting video transcripts')
    parser.add_argument('-i', required = True, dest = 'input',
        action='store', help='input directory')
    parser.add_argument('-v', action='store_true', required = False,
        help='enable verbose')

    args = parser.parse_args()
    main(args)

parse_args()


from flask_restful import Resource, reqparse
from flask import jsonify
from api import GeniusApi

class TopDezMusicasArtista(Resource):
    #def get(self, cache=False)

    def get(self, nome_artista):

        artist = GeniusApi(nome_artista)

        try:
            nome_artista = nome_artista.strip()

            if len(nome_artista) < 2 or len(nome_artista) > 30:
                raise Exception('Verifique o nome pesquisado!')

            args = reqparse.RequestParser()
            args.add_argument('cache')

            dados=args.parse_args()
            tem_cache = dados['cache']

            cache = False if tem_cache is not None and tem_cache == 'False' else True

            status, artist_data = artist.top_musica_artista(cache)

            #print('MUSICAS: ',artist_data)

            if not status:
                raise Exception('Nao foi possivel encontrar musicas deste artista!')

            return jsonify(
                {
                    'pesquisado': nome_artista,
                    'nome_artista': artist_data['nome_artista'],
                    'lista_de_musica': artist_data['lista_de_musica']
                }
            )

        except:
            pass


import json
import re
import os

import numpy as np
import pandas as pd
import paprotka.io as pio

def get_root(config='paths.json'):
    with open(config) as opened:
        paths = json.load(opened)
    return paths['reddots_root']

def read_files(*paths, encoding='utf-8'):
    for path in paths:
        with open(path, encoding=encoding) as opened:
            yield from opened

recording_regex = re.compile(r'([mf])(\d+)/(\d+)_[mf]\d+_(\d+)')
def parse_recording(value):
    match = recording_regex.match(value)
    if match:
        return match.groups()

recording_nopath_regex = re.compile(r'(\d+)_([mf])(\d+)_(\d+)')
def parse_recording_nopath(value):
    match = recording_nopath_regex.match(value)
    if match:
        return match.groups()

speaker_sentence_regex = re.compile(r'([mf])(\d+)_(\d+)')
def parse_speaker_sentence(value):
    match = speaker_sentence_regex.match(value)
    if match:
        return match.groups()

timestamp_format='%Y%m%d%H%M%S%f'
def parse_timestamp(timestamp):
    return pd.to_datetime(timestamp, format=timestamp_format)

def parse_gender(flag):
    return flag == 'm'

def parse_flag(flag):
    return flag == 'Y'

def load_trials(*paths):
    columns = ([], [], [], [], [], [], [], [], [], [])

    for line in read_files(*paths):
        speaker_sentence, recording, tc, tw, ic, iw = line.strip().split(',')

        expected_gender, expected_speaker_id, expected_sentence_id = parse_speaker_sentence(speaker_sentence)
        trial_gender, trial_speaker_id, trial_timestamp, trial_sentence_id = parse_recording(recording)

        expected_is_male = parse_gender(expected_gender)
        trial_is_male = parse_gender(trial_gender)

        target_person = parse_flag(tc) or parse_flag(tw)
        correct_sentence = parse_flag(tc) or parse_flag(ic)

        trial_timestamp = parse_timestamp(trial_timestamp)
        pcm_path = recording + '.pcm'

        record = (expected_is_male, expected_speaker_id, expected_sentence_id,
                  trial_is_male, trial_speaker_id, trial_timestamp, trial_sentence_id,
                  pcm_path, target_person, correct_sentence)

        for value, column in zip(record, columns):
            column.append(value)

    data = {'expected_is_male':     pd.Series(columns[0], dtype=np.bool),
            'expected_speaker_id':  pd.Series(columns[1], dtype=np.int16),
            'expected_sentence_id': pd.Series(columns[2], dtype=np.int16),
            'trial_is_male':        pd.Series(columns[3], dtype=np.bool),
            'trial_speaker_id':     pd.Series(columns[4], dtype=np.int16),
            'trial_timestamp':      pd.Series(columns[5], dtype='datetime64[ns]'),
            'trial_sentence_id':    pd.Series(columns[6], dtype=np.int16),
            'pcm_path':             pd.Series(columns[7], dtype=str),
            'target_person':        pd.Series(columns[8], dtype=np.bool),
            'correct_sentence':     pd.Series(columns[9], dtype=np.bool)}
    return pd.DataFrame.from_dict(data)

def load_enrollments(*paths):
    columns = ([], [], [], [], [])

    for line in read_files(*paths):
        speaker_sentence, recordings = line.strip().split(' ', 1)
        for recording in recordings.split(','):
            gender, speaker_id, timestamp, sentence_id = parse_recording(recording)

            is_male = parse_gender(gender)
            timestamp = parse_timestamp(timestamp)
            pcm_path = recording + '.pcm'

            record = (is_male, speaker_id, timestamp, sentence_id, pcm_path)

            for value, column in zip(record, columns):
                column.append(value)

    data = {'is_male':     pd.Series(columns[0], dtype=np.bool),
            'speaker_id':  pd.Series(columns[1], dtype=np.int16),
            'timestamp':   pd.Series(columns[2], dtype='datetime64[ns]'),
            'sentence_id': pd.Series(columns[3], dtype=np.int16),
            'pcm_path':    pd.Series(columns[4], dtype=str)}
    return pd.DataFrame.from_dict(data)

def load_script(path):
    sentence_ids_to_contents = {}

    for line in read_files(path, encoding='latin1'):
        recording_nopath, content = line.strip().split(';')
        _, _, _, sentence_id = parse_recording_nopath(recording_nopath)
        if sentence_id not in sentence_ids_to_contents:
            sentence_ids_to_contents[sentence_id] = content

    sentence_ids, contents = list(zip(*sentence_ids_to_contents.items()))

    data = {'sentence_id': pd.Series(sentence_ids, dtype=np.int16),
            'content':     pd.Series(contents, dtype=str)}
    df = pd.DataFrame.from_dict(data)
    df.set_index('sentence_id', inplace=True)
    return df

def load_pcm(root, path):
    full_path = os.path.join(root, 'pcm', path)
    return np.fromfile(full_path, np.int16)

def load_pcm_snd(root, path):
    full_path = os.path.join(root, 'pcm', path)
    return pio.load_pcm(full_path, dtype=np.int16, rate=16000)

def load_npy(root, source, path):
    full_path = os.path.join(root, source, path + '.npy')
    return np.load(full_path)

def transform_all_recordings(root, source, target, function):
    for person_dir in os.listdir(os.path.join(root, source)):
        source_dir = os.path.join(root, source, person_dir)
        target_dir = os.path.join(root, target, person_dir)

        os.makedirs(target_dir)
        for source_file in os.listdir(source_dir):
            target_file = source_file if source != 'pcm' else source_file[:-3] + 'npy'

            source_path = os.path.join(source_dir, source_file)
            target_path = os.path.join(target_dir, source_file)

            if source == 'pcm':
                source_data = np.fromfile(source_path, np.int16)
            else:
                source_data = np.load(source_path)

            result = function(source_data)

            np.save(target_path, result)


from common import *

plt.rcParams.update({'font.size': 16})
plt.rcParams.update({
    'font.family': 'serif',
    'font.serif': ['Computer Modern'],
    'text.usetex': True,
})

fig_size = tuple(array([6.8, 5.3]) * 2)

n_x, n_y = 1, 1
fig = plt.figure(figsize=fig_size)
ax = [fig.add_subplot(n_x, n_y, i + 1) for i in range(n_x * n_y)]

m_e, m_h, eps_r, T = 0.22, 0.41, 6.369171898453055, 294  # K
T_vec = array([T])
sys = system_data(m_e, m_h, eps_r, T)

be_cou = -193e-3  # eV
be_biexc_exp = -45e-3  # eV
r_max = 28

N_x = 1 << 10

param_c12 = biexciton_c12_lj(be_cou, be_biexc_exp, sys)
#param_c12 = 3.0

be_cou_scr = -180e-3  # eV
be_biexc_scr = biexciton_be_lj(param_c12, be_cou_scr, sys)

ax[0].set_title(
    '$C_{12}$: %.2f eV nm$^{12}$\n$C_6^{(exp)}$: %.2f eV nm$^{6}$, $C_6^{(scr)}$: %.2f eV nm$^{6}$\n$E_{X_2}^{(exp)}$: $%d$ meV, $E_{X_2}^{(scr)}$: $%d$ meV'
    % (
        param_c12,
        biexciton_lj_c6(be_cou, sys),
        biexciton_lj_c6(be_cou_scr, sys),
        1e3 * be_biexc_exp,
        1e3 * be_biexc_scr,
    ))

t0 = time.time()
wf_vec = array(
    biexciton_wf_lj(
        be_biexc_scr,
        be_cou_scr,
        param_c12,
        r_max,
        N_x,
        sys,
    )).reshape(-1, 3)
dt = (time.time() - t0)
print('dt/N: %.3e s, dt: %.3f s' % (dt / N_x, dt))

pot_vec = array(biexciton_pot_lj_vec(param_c12, be_cou, r_max, N_x, sys))
pot_vec_scr = array(
    biexciton_pot_lj_vec(param_c12, be_cou_scr, r_max, N_x, sys))

ax[0].axhline(y=0, color='k', linewidth=0.3)
ax[0].axhline(y=be_biexc_exp, color='g', linewidth=0.3)
ax[0].axhline(y=be_biexc_scr, color='b', linewidth=0.5)

ax[0].axvline(x=wf_vec[0, 2], color='k', linewidth=0.2)

ax[0].plot(wf_vec[:, 2], wf_vec[:, 0], 'r-', label=r'$\psi(r)$')
ax[0].plot(wf_vec[:, 2], wf_vec[:, 1], 'r--', label='$\psi\'(r)$')

ax[0].plot(wf_vec[:-1, 2], pot_vec, 'g-', linewidth=0.8, label=r'LJ')
ax[0].plot(wf_vec[:-1, 2], pot_vec_scr, 'b-', label=r'LJ Screened')

ax[0].set_ylim(1.3 * amin(pot_vec_scr), -2 * amin(pot_vec_scr))
ax[0].set_xlim(0.7 * wf_vec[0, 2], r_max)

ax[0].legend(loc=0)

plt.tight_layout()

plt.savefig('/storage/Reference/Work/University/PhD/Biexcitons/%s.png' % 'biexciton_lj_wf', dpi = 600)
plt.savefig('/storage/Reference/Work/University/PhD/Biexcitons/%s.pdf' % 'biexciton_lj_wf')

plt.show()


import nltk
from util.preprocessing import addCharInformation, createMatrices, addCasingInformation
from neuralnets.BiLSTM import BiLSTM
from sklearn.metrics import f1_score
import datetime
import csv
import sys

if len(sys.argv) < 3:
    print("Usage: python RunModel.py modelPath inputPath")
    exit()

modelPath = sys.argv[1]
inputPath = sys.argv[2]

with open(inputPath, 'r') as f:
    data = f.readlines()

label = []
temp = []
temp_label = []
agg_label = []

data = [d.strip().split('\t') for d in data]
text = [d[0] for d in data]

for d in data:
  if len(d) > 1:
    temp_label.append(d[1])
  else:
    temp_label.append(d[0])

stanza_label = []
for l in temp_label:
    if l != '':
        stanza_label.append(l)
    else:
        label.append(stanza_label)
        stanza_label = []

for l in label:
  agg_label.append(list(set(l)))

stanza = ''
for line in text:
    if line != '':
        stanza += (line + ' ')
    else:
        temp.append(stanza)
        stanza = ''

lstmModel = BiLSTM.loadModel(modelPath)

sentences = [{'tokens': sent.split(' ')[:-1]} for sent in temp]
addCharInformation(sentences)
addCasingInformation(sentences)
dataMatrix = createMatrices(sentences, lstmModel.mappings, True)
tags = lstmModel.tagSentences(dataMatrix)

pred = []
tagged_stanza = []
agg = []

for sentenceIdx in range(len(sentences)):
    tokens = sentences[sentenceIdx]['tokens']
    stanzaLines = []
    stanzaLabel = []
    for tokenIdx in range(len(tokens)):
      tokenTags = []
      for modelName in sorted(tags.keys()):
        tokenTags.append(tags[modelName][sentenceIdx][tokenIdx])
        stanzaLabel.append(tokenTags)
        stanzaLines.append("%s\t%s" % (tokens[tokenIdx], "\t".join(tokenTags)))
    tagged_stanza.append(stanzaLines)
    pred.append(stanzaLabel)

for s in tagged_stanza:
  for l in s:
    print(l)
  print('\n')

for stanza in pred:
  temp_agg = []
  for l in stanza:
    temp_agg.append(l[0])
  agg.append(list(set(temp_agg)))

def vectorize(labels):
  label_name = ['Suspense', 'Awe/Sublime', 'Sadness', 'Annoyance', 'Uneasiness', 'Beauty/Joy', 'Vitality', 'Humor']
  vector = [0, 0, 0, 0, 0, 0, 0, 0]
  for l in labels:
    idx = label_name.index(l)
    vector[idx] = 1
  return vector

agg_label = [vectorize(l) for l in agg_label]
agg = [vectorize(l) for l in agg]

f1_macro = f1_score(agg_label, agg, average='macro')
f1_all = f1_score(agg_label, agg, average=None)

print(f1_macro)
print(f1_all)
"""
with open('bilstm_cnn_crf_' + str(datetime.datetime.now().strftime("%Y-%m-%d")) + '_' + '10.tsv', 'wt', encoding='utf-8', newline='') as out_file:
    tsv_writer = csv.writer(out_file, delimiter='\t')
    tsv_writer.writerow(['Name', 'Score'])
    tsv_writer.writerow(['f1_macro', str(f1_macro)])
    tsv_writer.writerow(['f1_all', str(f1_all)])
"""


# init은 initialize라는 '초기화'라는 뜻
# 가장 먼저 init 파일에 있는 코드가 실행된다는 뜻

# print('__init__.py 파일 실행')

# from shapes import area, volume
# run.py에서 파이썬 패키지를 임포트할때 원래는 안되던게
# init에서 임포트를 해줌으로써 해결.
# 그러니 init 파일은 패키지를 임포트할 때
# 같이 임포트 하고자 하는 모듈을 적어주면 된다.

#from shapes.area import circle, square

########################################

PI = 3.14 # 모듈별로 PI를 지정하는 것은 의미가 없다.

__all__ = ['area', 'volume'] # 특수변수 all은 import * 를 할 때 가져오는 것을 정의


from collections import deque   # 스택은 시간초과 나와서 deque로 빠른... 변경

n,m = map(int, input().split()) #  count , num

answer = deque()

if n * 26 < m or n > m:
    print("!")
else:
    for i in range(n):
        left = n - i - 1;    # 적어도 A 한개씩은 들어가야함
        if m-left > 26:      # 남은 수기 26보다 큰 경우
            answer.appendleft("Z")
            m = m-26         # m은 Z값을 뺀 만큼
        else:
            answer.appendleft(chr(m-left + 64))
            m = m -(m-left)

    print("".join(answer))


import os.path
import numpy as np
import torch.optim as optim
import yaml
from tqdm import tqdm

from model.network import MyNet as net
from units.dataloader import MyDataset, DataLoader
from units.weights_init import weights_init
# from units.loss import MyLoss as my_loss
from units.loss import MyLoss_heatmap as my_loss
import torch
import argparse

def main():
    # 创建数据加载器
    train_dataset = MyDataset(train_data, sigma=sigma)
    train_dataloader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)

    val_dataset = MyDataset(val_data, sigma=sigma)
    val_dataloader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False)

    # 构建网络
    model = net(model_layers)
    weights_init(model)
    if model_path != '':
        print('Load weights {}.'.format(model_path))
        device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
        model_dict = model.state_dict()
        pretrained_dict = torch.load(model_path, map_location=device)
        pretrained_dict = {k: v for k, v in pretrained_dict.items() if np.shape(model_dict[k]) == np.shape(v)}
        model_dict.update(pretrained_dict)
        model.load_state_dict(model_dict)

    # 构建损失
    # my_loss = MyLoss
    model = model.cuda()

    # 构建优化器
    optimizer = optim.Adam(model.parameters(), lr, weight_decay=5e-4)

    # train
    for i in range(num_epoch):
        # train
        train_loss = 0
        model = model.train()

        train_epoch_bar = tqdm(train_dataloader, desc=f"Epoch {i}/{num_epoch}")

        for j_train, batch in enumerate(train_epoch_bar):
            datas, targets, targets_weight = batch[0].cuda(), batch[1].cuda(), batch[2].cuda()

            outputs = model(datas)
            loss_batch = my_loss(outputs, targets, targets_weight)
            loss_batch.backward()
            optimizer.step()
            train_loss += loss_batch.item()

            train_epoch_bar.set_postfix(loss=f"{train_loss / (j_train + 1) :.6f}",
                                        current_loss=f"{loss_batch.item():.6f}")

        print("\nTrain Finished")
        # val
        val_loss = 0
        model.eval()

        val_epoch_bar = tqdm(val_dataloader, desc=f"Epoch {i}/{num_epoch}")
        for j_val, batch in enumerate(val_epoch_bar):
            datas, targets, targets_weight = batch[0].cuda(), batch[1].cuda(), batch[2].cuda()
            with torch.no_grad():
                outputs = model(datas)
                loss_batch = my_loss(outputs, targets, targets_weight)
            val_loss += loss_batch.item()
            train_epoch_bar.set_postfix(loss=f"{val_loss / (j_val + 1) :.6f}",
                                        current_loss=f"{loss_batch.item():.6f}")

        print(f"\nEpoch_num:{i}, Train_loss:{train_loss / (j_train + 1) :.6f}, Val_loss:{val_loss / (j_val + 1) :.6f}")

        if not os.path.exists(r"logs"):
            os.makedirs(r"logs")

        torch.save(model.state_dict(), 'logs/ep%03d-loss%.6f-val_loss%.6f.pth' % (
            i + 1, train_loss / (j_train + 1), val_loss / (j_val + 1)))

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--train_data', type=str, default="datasets/annotations/train_dataset.txt")
    parser.add_argument('--val_data', type=str, default="datasets/annotations/val_dataset.txt")
    parser.add_argument('--batch_size', type=int, default=2)
    parser.add_argument('--model_path', type=str, default=r"")

    parser.add_argument('--lr', type=float, default=0.0001)
    parser.add_argument('--num_epoch', type=int, default=100)
    parser.add_argument('--model_layers', type=int, default=50)
    parser.add_argument('--sigma', type=int, default=2)
    args = parser.parse_args()

    train_data = args.train_data
    val_data = args.val_data
    batch_size = args.batch_size
    model_path = args.model_path
    lr = args.lr
    num_epoch = args.num_epoch
    sigma = args.sigma

    model_layers = {50:[3,4,6,3],
                    18:[2,2,2,2],
                    34:[2,3,4,3]}[args.model_layers]

    main()

    # #
    # with open('./config/train_config.yaml', 'r') as f:
    #     train_config = yaml.load(f, Loader=yaml.FullLoader)
    #
    # train_data = train_config["train_data"]
    # val_data = train_config["val_data"]
    # batch_size = train_config["batch_size"]
    # model_path = train_config["model_path"]
    # lr = train_config["lr"]
    # num_epoch = train_config["num_epoch"]
    #
    # model_layers = train_config["model_layers"]
    #
    # sigma = train_config["sigma"]
    #
    # main()


from sqlalchemy import create_engine, Column, String, Integer, Float, ForeignKey, PickleType
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.mutable import MutableList

Base = declarative_base()

class Book(Base):
    __tablename__ = 'books'

    id = Column('id', Integer, primary_key=True)
    title = Column('title', String, unique=False, nullable=False)
    url = Column('url', String, unique=True, nullable=False)
    img_url = Column('img_url', String, unique=True, nullable=False)
    author = Column('author', String, unique=False, nullable=False)
    tags = Column('tags', MutableList.as_mutable(PickleType), unique=False, default=[], nullable=False)
    pages = Column('pages', Integer, unique=False, nullable=False)
    chapter = Column('chapter', MutableList.as_mutable(PickleType), unique=False, default=[], nullable=False)
    chapter_count = Column('chapter_count', Integer, unique=False, nullable=False)
    rating = Column('rating', Float, unique=False, nullable=False)
    total_rates = Column('total_rates', Integer, unique=False, nullable=False)
    views = Column('views', Integer, unique=False, nullable=False)
    favorites = Column('favorites', Integer, unique=False, nullable=False)
    followers = Column('followers', Integer, unique=False, nullable=False)

    def __init__(self, id, title, url, img_url, tags, author, pages, chapter, chapter_count, rating, total_rates, views, favorites, followers):
        self.id = id
        self.title = title
        self.url = url
        self.img_url = img_url
        self.tags = tags
        self.rating = rating
        self.total_rates = total_rates
        self.views = views
        self.favorites = favorites
        self.followers = followers
        self.author = author
        self.pages = pages
        self.chapter = chapter
        self.chapter_count = chapter_count

    def as_dict(self):
        return {c.name: getattr(self, c.name) for c in self.__table__.columns}

    def serialize(self):

        return {'id': self.id,
                'title': self.title,
                'url': self.title,
                'img_url': self.img_url,
                'tags': self.tags,
                'rating': self.rating,
                'total_rates': self.total_rates,
                'views': self.views,
                'favorites': self.favorites,
                'followers': self.followers,
                'author': self.author,
                'pages': self.pages,
                'chapter': self.chapter,
                'chapter_count': self.chapter_count}

engine = create_engine('sqlite:///book-collection.db', echo=True)
Base.metadata.create_all(bind=engine)


import setuptools

with open("README.md", "r") as f:
    long_description = f.read()

setuptools.setup(
    name='coord_transform',
    version='1.0.0',
    author="JongSul Moon",
    author_email="moonjongsul@keti.re.kr",
    description="",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/UnstructuredWork",
    packages=setuptools.find_packages(),
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    python_requires='>=3.8',
    license='MIT',
    keywords=['VISION', 'AI', 'Deep Learning'],
    install_requires=[
        'setuptools',
        'numpy',
        'opencv-python',
        'opencv-contrib-python',
    ],
)