import sys
_module = sys.modules[__name__]
del sys
main = _module
models = _module
vgg16_conv = _module
vgg16_deconv = _module
utils = _module
utils = _module

from _paritybench_helpers import _mock_config, patch_functional
from unittest.mock import mock_open, MagicMock
from torch.autograd import Function
from torch.nn import Module
import abc, collections, copy, enum, functools, inspect, itertools, logging, math, matplotlib, numbers, numpy, pandas, queue, random, re, scipy, sklearn, string, tensorflow, time, torch, torchaudio, torchtext, torchvision, types, typing, uuid, warnings
import numpy as np
from torch import Tensor
patch_functional()
open = mock_open()
yaml = logging = sys = argparse = MagicMock()
ArgumentParser = argparse.ArgumentParser
_global_config = args = argv = cfg = config = params = _mock_config()
argparse.ArgumentParser.return_value.parse_args.return_value = _global_config
yaml.load.return_value = _global_config
sys.argv = _global_config
__version__ = '1.0.0'
xrange = range
wraps = functools.wraps

import torch

import torch.nn as nn

from torch.autograd import Variable

from torchvision.transforms import transforms

import numpy as np

from functools import partial

import matplotlib

import matplotlib.pyplot as plt

import torchvision.models as models

import torchvision

from collections import OrderedDict

class Vgg16Conv(nn.Module):
    """
    vgg16 convolution network architecture
    """

    def __init__(self, num_cls=1000):
        """
        Input
            number of class, default is 1k.
        """
        super(Vgg16Conv, self).__init__()
        self.features = nn.Sequential(nn.Conv2d(3, 64, 3, padding=1), nn.ReLU(), nn.Conv2d(64, 64, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2, stride=2, return_indices=True), nn.Conv2d(64, 128, 3, padding=1), nn.ReLU(), nn.Conv2d(128, 128, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2, stride=2, return_indices=True), nn.Conv2d(128, 256, 3, padding=1), nn.ReLU(), nn.Conv2d(256, 256, 3, padding=1), nn.ReLU(), nn.Conv2d(256, 256, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2, stride=2, return_indices=True), nn.Conv2d(256, 512, 3, padding=1), nn.ReLU(), nn.Conv2d(512, 512, 3, padding=1), nn.ReLU(), nn.Conv2d(512, 512, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2, stride=2, return_indices=True), nn.Conv2d(512, 512, 3, padding=1), nn.ReLU(), nn.Conv2d(512, 512, 3, padding=1), nn.ReLU(), nn.Conv2d(512, 512, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2, stride=2, return_indices=True))
        self.classifier = nn.Sequential(nn.Linear(512 * 7 * 7, 4096), nn.ReLU(), nn.Dropout(), nn.Linear(4096, 4096), nn.ReLU(), nn.Dropout(), nn.Linear(4096, num_cls), nn.Softmax(dim=1))
        self.conv_layer_indices = [0, 2, 5, 7, 10, 12, 14, 17, 19, 21, 24, 26, 28]
        self.feature_maps = OrderedDict()
        self.pool_locs = OrderedDict()
        self.init_weights()

    def init_weights(self):
        """
        initial weights from preptrained model by vgg16
        """
        vgg16_pretrained = models.vgg16(pretrained=True)
        for idx, layer in enumerate(vgg16_pretrained.features):
            if isinstance(layer, nn.Conv2d):
                self.features[idx].weight.data = layer.weight.data
                self.features[idx].bias.data = layer.bias.data
        for idx, layer in enumerate(vgg16_pretrained.classifier):
            if isinstance(layer, nn.Linear):
                self.classifier[idx].weight.data = layer.weight.data
                self.classifier[idx].bias.data = layer.bias.data

    def check(self):
        model = models.vgg16(pretrained=True)
        return model

    def forward(self, x):
        for idx, layer in enumerate(self.features):
            if isinstance(layer, nn.MaxPool2d):
                x, location = layer(x)
            else:
                x = layer(x)
        x = x.view(x.size()[0], -1)
        output = self.classifier(x)
        return output

class Vgg16Deconv(nn.Module):
    """
    vgg16 transpose convolution network architecture
    """

    def __init__(self):
        super(Vgg16Deconv, self).__init__()
        self.features = nn.Sequential(nn.MaxUnpool2d(2, stride=2), nn.ReLU(), nn.ConvTranspose2d(512, 512, 3, padding=1), nn.ReLU(), nn.ConvTranspose2d(512, 512, 3, padding=1), nn.ReLU(), nn.ConvTranspose2d(512, 512, 3, padding=1), nn.MaxUnpool2d(2, stride=2), nn.ReLU(), nn.ConvTranspose2d(512, 512, 3, padding=1), nn.ReLU(), nn.ConvTranspose2d(512, 512, 3, padding=1), nn.ReLU(), nn.ConvTranspose2d(512, 256, 3, padding=1), nn.MaxUnpool2d(2, stride=2), nn.ReLU(), nn.ConvTranspose2d(256, 256, 3, padding=1), nn.ReLU(), nn.ConvTranspose2d(256, 256, 3, padding=1), nn.ReLU(), nn.ConvTranspose2d(256, 128, 3, padding=1), nn.MaxUnpool2d(2, stride=2), nn.ReLU(), nn.ConvTranspose2d(128, 128, 3, padding=1), nn.ReLU(), nn.ConvTranspose2d(128, 64, 3, padding=1), nn.MaxUnpool2d(2, stride=2), nn.ReLU(), nn.ConvTranspose2d(64, 64, 3, padding=1), nn.ReLU(), nn.ConvTranspose2d(64, 3, 3, padding=1))
        self.conv2deconv_indices = {(0): 30, (2): 28, (5): 25, (7): 23, (10): 20, (12): 18, (14): 16, (17): 13, (19): 11, (21): 9, (24): 6, (26): 4, (28): 2}
        self.unpool2pool_indices = {(26): 4, (21): 9, (14): 16, (7): 23, (0): 30}
        self.init_weight()

    def init_weight(self):
        vgg16_pretrained = models.vgg16(pretrained=True)
        for idx, layer in enumerate(vgg16_pretrained.features):
            if isinstance(layer, nn.Conv2d):
                self.features[self.conv2deconv_indices[idx]].weight.data = layer.weight.data

    def forward(self, x, layer, activation_idx, pool_locs):
        if layer in self.conv2deconv_indices:
            start_idx = self.conv2deconv_indices[layer]
        else:
            raise ValueError('layer is not a conv feature map')
        for idx in range(start_idx, len(self.features)):
            if isinstance(self.features[idx], nn.MaxUnpool2d):
                x = self.features[idx](x, pool_locs[self.unpool2pool_indices[idx]])
            else:
                x = self.features[idx](x)
        return x


import logging

from selenium.webdriver.common.by import By

def handle_black(func):
    # 设置日志级别
    logging.basicConfig(level=logging.INFO)

    def wrapper(*args, **kwargs):
        from ywzt.base.base_page import BasePage
        _black_list = [(By.XPATH, '//*[@text="确认"]'),
                       (By.XPATH, '//*[@text="创建失败"]')]
        _max_num = 3
        _error_num = 0
        instance: BasePage = args[0]
        try:
            logging.info("run" + func.__name__ + "\n args:\n" + repr(args) + "\n kwargs:" + repr(kwargs))
            element = func(*args, **kwargs)
            _error_num = 0
            instance.driver.implicitly_wait(10)
            return element
        except Exception as e:
            logging.info('error:element not found,handle black list')
            instance.driver.get_screenshot_as_png()
            instance.driver.implicitly_wait(1)
            if _error_num > _max_num:
                raise e
            _error_num += 1
            for ele in _black_list:
                elelist = instance.finds(*ele)
                if len(elelist) > 0:
                    elelist[0].click()
                    return wrapper(*args, **kwargs)
            raise e


import json
import boto3
import time

# Lambda for manually running PySpark functions
# Specify the functions and their associated layer script in function_script_combinations below

def lambda_handler(event, context):
    # Specify the cluster id here:
    curr_cluster_id = ""

    # Set repo location
    CODE_DIR = "/home/hadoop/eap-bcg/"

    # Configure the layer steps
    function_script_combinations = [['preprocess_renewal_model_training_data', 'layer3/task_Layer3_renewal_model.py'], \
                        ['train_renewal_model', 'layer3/task_Layer3_renewal_model.py']]

    # Add function step configs to EMR Steps call
    layer_function_steps = []
    task_function_configs = ['--executor-memory', '32g', '--executor-cores', '4', '--driver-memory', '20g', '--conf', 'spark.sql.shuffle.partitions=300']

    for func_combo in function_script_combinations:

        func_submit_call_args = ["/usr/bin/spark-submit"] + task_function_configs + [CODE_DIR + "pipeline/tasks/" + func_combo[1], '--function', func_combo[0]]

        step = {"Name": l_func + "-" + time.strftime("%Y%m%d-%H:%M"),
            'ActionOnFailure':'CANCEL_AND_WAIT',
            'HadoopJarStep': {
                'Jar': 's3n://elasticmapreduce/libs/script-runner/script-runner.jar',
                'Args': func_submit_call_args
            }
        }
        layer_function_steps.append(step)

    # Specify the final Steps flow
    action = conn.add_job_flow_steps(JobFlowId=curr_cluster_id, Steps=layer_function_steps)
    return "Added step: %s"%(action)


import difflib

def find_closest_id(file_name):
    file = open(file_name, "r")
    strings = [x[:-1] for x in file.readlines()]
    file.close()
    closest_length = 0
    closest_string = ""
    list_len = len(strings)
    for i_d in strings:

        close_matches = difflib.get_close_matches(i_d, strings, n=2)  # get string which is closest to current
        i_d = "".join([c for i,c in enumerate(i_d) if close_matches[1][i]==c])

        id_len = len(i_d)
        if id_len > closest_length:
            closest_length = id_len
            closest_string = i_d

    return closest_string

file_name = "my_input.txt"
# list(difflib.ndiff("abvc", "abtc"))
print(find_closest_id(file_name))


class Queue:

    def __init__(self):
        self.q = []
        self.front = None

    def enqueue(self,item):
        self.q.append(item)
        if (len(self.q) ==1):
            self.front = self.rear = 0
        else:
            self.rear = len(self.q) - 1

    def isempty(self):
        if (self.q == []):
            return True
        else:
            return False
    def dequeue(self):
        if (a.isempty()):
            return "underflow"
        else:
            self.ite = self.q.pop(0)

        if (len(self.q) == 0):
            self.front = self.rear = None
        return self.ite
    def display(self):
        if (a.isempty()):
            print("Queue empty")
        elif (len(self.q) == 1):
            print(self.q[0], "<== front,rear")
        else:
            self.front = 0
            self.rear = len(self.q)-1
            print(self.q[self.front],"<--front")
            for t in range(1,self.rear):
                print(self.q[t])
            print(self.q[self.rear],"<--rear")

a = Queue()
while True:
    print("""queue operations
    1:enqueue
    2:dequeue
    3:display
    4: Exit""")

    n = int(input("Enter choice : "))
    if n == 1:
        val = int(input("Enter item"))
        a.enqueue(val)
        input("press any key to continue")
    if n == 2:
        returnvalue = a.dequeue()
        if (returnvalue == "underflow"):
            print("queue is empty")
        else:
            print("dequed item =",returnvalue)
        input("press any key to continue")
    if n == 3:
        a.display()
    if n == 5 :
        break


import keras
import tensorflow as tf

from preprocessor import preprocessor

model = keras.models.load_model("saved_model")

def predict(question, essay):
    return (
        tf.argmax(
            model.predict((preprocessor([question]), preprocessor([essay]))), axis=1
        )[0].numpy()
        + 2
    ) / 2


from database import creating_database
from keyboard import sender
from main import *

for event in bot.longpoll.listen():
    if event.type == VkEventType.MESSAGE_NEW and event.to_me:
        request = event.text.lower()
        user_id = str(event.user_id)
        msg = event.text.lower()
        sender(user_id, msg.lower())
        if request == 'поиск':
            creating_database()
            bot.find_user(user_id)
            bot.write_msg(event.user_id, f'Посмотри, кого я нашёл!')
            bot.find_persons(user_id, offset)

        elif request == 'привет':
            bot.write_msg(user_id, f'Привет, {bot.name(user_id)}. Жми кнопку "Поиск"')
        elif request == 'пока':
            bot.write_msg(user_id, f'До встречи! Я буду ждать тебя тут.')
        elif request == 'как дела?':
            bot.write_msg(user_id, f'Отлично, надеюсь, что и у Вас тоже! Давайте посмотрим, кого я для Вас нашел!  Нажмите на кнопку "Поиск".')

        elif request == 'дальше':
            for i in line:
                offset += 1
                bot.find_persons(user_id, offset)
                break

        else:
            bot.write_msg(event.user_id, 'Я тебя не понимаю')


'''Utilizes Python to pull reddit history from JSON into a SQL database'''
import json
import sqlite3
import string

LineCount = 0
conn = sqlite3.connect('reddit_wordcloud.sqlite')
cur = conn.cursor()

# Do you want to append the new file into the database?
# Theoretically you could then input multiple files.
Question = input("Do you wish to append to the database? (Y/N)")
if Question == "Y" or Question == "y":
    AppendToTable = True
else:
    AppendToTable = False

if AppendToTable == False:
    cur.executescript('DROP TABLE IF EXISTS Words; CREATE TABLE Words (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, word TEXT UNIQUE, count  INTEGER);')

FileName = input('Open which file? ')
if len(FileName) < 1:
    FileName = 'reddit_comment_sample.json'
try:
    FileHandle = open(FileName, encoding="utf8")
except:
    print("Error opening file:", FileName)
    quit()

while True:
    # Commit every 100 comments, makes more sense to do it before the potential break
    if LineCount % 100 == 0:
        conn.commit()

    try:
        json_data = json.loads(FileHandle.readline())
    except:
        conn.commit()
        break

    LineCount += 1

    # JSON to Select selftext:""
    RawComment = json_data["selftext"]

    # Remove whitepace surrounding & punctuation
    translator = str.maketrans('', '', string.punctuation)
    comment = RawComment.translate(translator)
    comment = comment.strip()

    # Skip empty, removed, or deleted comments
    if comment is None or comment == "" or comment == "[deleted]" or comment == "[removed]" or comment == "deleted" or comment == "removed":
        continue

    # Keep track
    print(LineCount, comment[:50])

    # Divide comments into words, add new words, increase count for previously added words
    SplitComment = comment.split()

    for word in SplitComment:
        cur.execute(
            'SELECT count FROM Words WHERE word = ? ', (word.lower(),))
        row = cur.fetchone()
        if row is None:
            cur.execute('INSERT OR IGNORE INTO Words (word, count) VALUES (?, 1)', (word.lower(),))
        else:
            cur.execute('UPDATE Words SET count = count + 1 WHERE word = ?', (word.lower(),))

# If we reached the end through a break success, let us know
print("End reached through a successful failure to read another line")
conn.commit()


import matplotlib.pyplot as plt
import random as rand
import numpy as np

class Imagen:
    def __init__(self):
        pass

    # Muestra las imágenes en un gráfico con su respectivo nombre
    def mostrar_imagenes(self, imagenes:list, titulos:list, titulo:str):
        fig, axs = plt.subplots(1, len(imagenes), figsize=(10, 10))
        for i in range(len(imagenes)):
            axs[i].imshow(imagenes[i], cmap="gray")
            axs[i].set_title("{}".format(titulos[i]))
        fig.suptitle(titulo)
        fig.set_figheight(4)
        plt.show()

    # Genera imagen binaria como matriz de Numpy
    def generar_imagen_binaria(self, ancho, alto):
        return np.array([[rand.choice([-1, 1]) for _ in range(ancho)] for _ in range(alto)])

    # Cambia n píxeles aleatoriamente
    def cambiar_pixeles(self, matriz, n:int):
        m = matriz.flatten()
        indices = rand.sample(range(len(m)), n)
        for i in indices: m[i] *= -1
        return m.reshape(matriz.shape)


n, m = map(int, input().split())

ans = 0
price_list = []

for _ in range(m):
    price = tuple(map(int, input().split()))
    price_list.append(price)

six_list = sorted(price_list, key=lambda x : x[0])
one_list = sorted(price_list, key=lambda x : x[1])

if six_list[0][0] <= one_list[0][1] * 6:
    ans = six_list[0][0] * (n // 6) + one_list[0][1] * (n % 6)
    if six_list[0][0] < one_list[0][1] * (n % 6):
        ans = six_list[0][0] * (n // 6 + 1)
else:
    ans = one_list[0][1] * n

print(ans)


import numpy as np
import math as math
import matplotlib.pyplot as py
# import sympy as sp
# from scipy.integrate import  quad

# if user input needs to stored in a list
def get_multiple_input(input_text):
    inputs = []
    while True:
        i = input(input_text)
        try:
            a = int(i)
        except ValueError:
            break
        inputs.append(a)
    return inputs

# if only one value is input
def get_single_input(input_text):
    i = input(input_text)
    while True:
        try:
            i = int(i)
            break
        except ValueError:
            break
    return i

def get_f_p_init_N(t_list, strands_arr, p_force): #strand arrangement, prestress force #HC
    N_array = []
    for i in range(0, len(t_list)):
        indiv_N = 0
        for j in range(0, len(strands_arr)):
            indiv_N += strands_arr[j] * p_force
        N_array.append(indiv_N)
    return N_array

def get_f_p_init_M(t_list, strands_arr, p_force, y_p_list): #strand arrangement, prestress force #HC
    M_array = []
    for i in range(0, len(t_list)):
        indiv_M = 0
        for j in range(0, len(strands_arr)):
            indiv_M += strands_arr[j] * p_force * y_p_list[j]
        M_array.append(indiv_M)
    return M_array

def get_f_p_rel(fpi_n, fpi_m, phi_p_steel_array):
    N_array = []
    M_array = []
    for i in range(0,len(t)):
        N_array.append(fpi_n[i] * phi_p_steel_array[i])
        M_array.append(fpi_m[i] * phi_p_steel_array[i])
    rel = np.array([N_array, M_array], dtype=np.float64)
    return rel

def get_r_b_steel(rb_input):#HC
    rb_type = {0: (2 / 100), 1: (2.5 / 100), 2: (4 / 100)}
    return rb_type[rb_input]

def get_k4_steel(t_list): #HC
    k4s_total = []
    for i in range(0,len(t_list)):
        k4s = math.log10(5.4 * math.pow(t_list[i], 1.6 ))
        k4s_total.append(k4s)
    return k4s_total

def get_k5_steel(break_str, jack_str, rb_steel): #HC
    gamma = jack_str / break_str
    if gamma < 0.4:
        k5_i = 0
    elif 0.4 <= gamma <= 0.7:
        k5_i = (10 * gamma - 4) / 3
    else:
        if rb_steel == 0.02 or 0.025:
            k5_i = 5 * gamma - 2.5 #low relaxation wire or low relaxation strand
        else:
            k5_i = (50 * gamma-29) / 6 #Alloy Steel bars
    return k5_i

def get_k6_steel(input_temp): #HC
    temp = 20
    i = input_temp
    if i != "":
        temp = int(i)
    return temp / 20

def get_E_c(f_cmi_input, density_conc): #HC
    if f_cmi_input <= 40:
        E_c = math.pow(density_conc, 1.5) * 0.043 * math.sqrt(f_cmi_input)
    else:
        E_c = math.pow(density_conc, 1.5) * (0.024 * math.sqrt(f_cmi_input) + 0.12)
    return E_c

def get_E_c_tao_2_t(t2_array, t_slab_pour): #HC
    array = []
    for i in range(0, len(t2_array)):
        output = t2_array[i] - t_slab_pour
        if output == 0:
            output = 1
        else:
            output = output
        array.append(output)
    return array

def get_s(s_key): #HC
    while True:
        if s_key == 0:
            s = 0.38
            break
        elif s_key == 1:
            s = 0.25
            break
        else:
            print("Enter 0 or 1")
    return s

def get_E_c_tao(t_list, s_value, E_c_value): #Check with Colin/Mayer Ec_value
    E_c_array = []
    for i in range(0, len(t_list)): #Is E_c_value Ec at 28 days? or at tao0?
        E_c_array.append(math.pow(math.exp(s_value * (1 - math.sqrt(28 / t_list[i]))), 0.5) * E_c_value)
    return E_c_array

def get_th(area, ue): #HC
    return 2*area / ue

def get_alpha2(area, ue): #HC
    th = 2 * area / ue
    return 1 + 1.12 * math.exp(-0.008 * th)

def get_k2_value(area, ue, t_list, tao_list): #HC
    alpha2_value = get_alpha2(area, ue)
    th_value = get_th(area,ue)
    return (alpha2_value * math.pow(t_list - tao_list, 0.8))/ (math.pow(t_list - tao_list, 0.8)+ 0.15 * th_value)

def get_k2(t_list,tao_list, area, ue): #HC
    k2 = np.zeros((len(tao_list), len(t_list)))
    for i in range(len(tao_list)):
        for j in range(len(t_list)):
            if t_list[j] == tao_list[i]: #loading = time
                k2[i, j] = 0

            elif t_list[j] < tao_list[i]: #time<loading eg Creep(time,loading) = Creep (1,2) = 0
                k2[i, j] = 0

            else:
                k2[i, j] = get_k2_value(area, ue, t_list[j], tao_list[i])
    return k2

def get_k3(tao_list): #HC
    k3_array = np.zeros((len(tao_list), 1))
    for i in range(len(tao_list)):
        k3_array[i, 0] = 2.7/ (1 + math.log10(tao_list[i]))
    return k3_array

def get_k4(k4_key): #HC
    environment_type = {0: 0.7, 1: 0.65, 2: 0.6, 3: 0.5}
    return environment_type[k4_key]

def get_k5_value(f_c_key, area, ue): #HC
    alpha2 = get_alpha2(area, ue)
    alpha3 = 0.7 / (k4 * alpha2)
    k5_value = (2 - alpha3) - 0.02 * (1 - alpha3) * f_c_key
    return k5_value

def get_k5(f_c_key, t_list, area, ue): #HC
    k5_array = []
    if f_c_key <= 50:
        k5_output = np.ones((1, len(t_list)))
    elif 50 < f_c_input <= 100:
        for i in range(0, len(t_list)):
            k5_array.append(get_k5_value(f_c_key, area, ue))
        k5_output = np.array(k5_array)
    return k5_output

def get_phi_basic(f_c_key): #HC
    creep_basic_array = np.array(
        [[20, 4.5], [25, 3.8], [32, 3], [40, 2.4], [50, 2], [65, 1.7], [80, 1.5], [100, 1.3]])
    for i in range(len(creep_basic_array)):
        if creep_basic_array[i][0] == f_c_key:
            p_b_output = creep_basic_array[i][1]
            break
        else:
            if creep_basic_array[i][0] < f_c_key:
                continue
            else:
                basic_creep_grad = (creep_basic_array[i][1] - creep_basic_array[i - 1][1]) \
                        / (creep_basic_array[i][0] - creep_basic_array[i - 1][0])
                p_b_output = creep_basic_array[i - 1][1] + (f_c_key - creep_basic_array[i - 1][0]) * basic_creep_grad
                break
    return p_b_output

def get_strain_cse(f_c_key, t_list): #HC
    cse_array = []
    cse_star = (0.06 * f_c_key - 1) * 50 * math.pow(10, -6)
    for i in range(0, len(t_list)):
        cse_array.append(cse_star * (1 - math.exp(-0.1 * t_list[i])))
    return cse_array

def get_strain_shd_b_star(): #HC
    strain_input = get_single_input("Aggregate quality: good = 0, unknown = 1: ")
    if strain_input == 0:
        shd = 800 * math.pow(10, -6)
    elif strain_input == 1:
        shd = 1000 * math.pow(10, -6)
    else:
        print("Enter a valid number")
    return shd

def get_alpha1(area, ue):#HC
    th = 2*area / ue
    return 0.8 + 1.2 * math.exp(-0.005 * th)

def get_k1_value(area, ue, t, tao_d):#HC
    th = 2*area / ue
    a1 = get_alpha1(area, ue)
    output = (a1 * math.pow(t - tao_d, 0.8))/ (math.pow(t - tao_d, 0.8) + 0.15 * th)
    return output

def get_k1(t_list, area, ue, tao_dry): #HC
    # k1_array = np.zeros((1, len(t_list)))
    array = []
    for i in range(0, len(t_list)):
            # k1_array[0, i] = get_k1_value(area, ue, t_list[i], tao_dry)
            array.append(get_k1_value(area, ue, t_list[i], tao_dry))
    return array

def get_J_t_tao(t_list,tao_list, E_c_tao_array, phi_t_tao_array): #HC
    J_array = np.zeros((len(tao_list), len(t_list)))
    for i in range(0, len(tao_list)):
        for j in range(0, len(t_list)):
            if tao_list[i] > t_list[j] : # loading > time
                J_array[i, j] = 0
            else: # time >= loading
                for a in range(len(t_list)): #When does tao value appear in t_list array as E_c_tao is length of t
                    if tao_list[i]==t_list[a]:
                        J_array[i, j] = (1 / E_c_tao_array[a]) * (1 + phi_t_tao_array[i, j])
                        break
    return J_array

def get_E_c_j(t_list, tao_list, J_t_tao_array):
    E_c_j_array =np.zeros(len(t_list))
    for j in range(0, len(t_list)):
        for i in range(0, len(tao_list)):
            if t_list[j] == tao_list[i]: #loading = time
                E_c_j_array[j] = 1/ J_t_tao_array[i,j] #correct
                break #break I go to next j

            elif t_list[j] < tao_list[i]:  # if time<loading then use the previous tao value
                for a in range(0, len(t_list)):
                    if tao_list[i - 1] == t_list[a]:  # previous tao value (time>loading) is the same as the t value
                        E_c_j_array[j] = 1/ J_t_tao_array[i - 1, a]
                        break
                break
            elif i == len(tao_list)-1:
                for a in range(0, len(t_list)):
                    if tao_list[i] == t_list[a]:  # previous tao value (time>loading) is the same as the t value
                        E_c_j_array[j] = 1/ J_t_tao_array[i, a]
                        break
                break
    return E_c_j_array

def get_Fe_j_i(t_list, tao_list, J_t_tao_array): #Double Check Calcs with Calvin - Code matches calcs
    Fe_j_i = np.zeros((len(tao_list), len(t_list)))
    for j in range(0, len(t_list)):
        for tao_ip in range(0, len(tao_list)):
            if t_list[j] <= tao_list[tao_ip] or tao_ip == len(tao_list)-1:
                Fe_j_i[tao_ip,j] = 0
                break
            else:
                for i in range(0, len(tao_list)):
                    if t_list[j] < tao_list[i]:  # if time<loading then use the previous tao value
                     for a in range(0, len(t_list)):
                        if tao_list[i - 1] == t_list[a]:  # previous tao value (time>loading) is the same as the t value
                            Fe_j_i[tao_ip,j] = (J_t_tao_array[tao_ip+1,a]
                                                -J_t_tao_array[tao_ip,a])\
                                               /J_t_tao_array[i - 1, a]
                            break
                     break
                    elif i == len(tao_list)-1:
                        for a in range(0, len(t_list)):
                            if tao_list[i] == t_list[a]:  # previous tao value (time>loading) is the same as the t value
                                Fe_j_i[tao_ip,j] = (J_t_tao_array[tao_ip+1,a]
                                                    -J_t_tao_array[tao_ip,a])\
                                                   /J_t_tao_array[i, a]
                                break
                        break

    return Fe_j_i

def post_get_A_c(t_list, t_grout, area, d_duct, strands_arr, A_s_list, A_p_list):
    ac_array = []
    for i in range(0, len(t_list)):
        if t_list[i] >= t_grout: ## once grout is added
            a = area - sum(A_s_list) - sum(A_p_list)
        else:
            a = area - ((d_duct/2) ** 2 * math.pi) * sum(strands_arr) - sum(A_s_list)
        ac_array.append(a)
    output = np.array(ac_array)
    return output

def pre_get_A_c(t_list, area, A_s_list, A_p_list): #HC
    ac_array = []
    for i in range(0, len(t_list)):
        a = area - sum(A_s_list) - sum(A_p_list)
        ac_array.append(a)
    output = np.array(ac_array)
    return output

def get_A_by_y(A_list, y_list, d_ref): #Used for S and P for sum of total layers #HC
    B_mod = 0
    for i in range(0, len(A_list)):
        B_mod += A_list[i] * (y_list[i] - d_ref)
    return B_mod

def post_get_B_c(t_list, t_grout, area, d_cent, d_ref, d_duct, A_s_list, y_s_list,
                 A_p_list, y_p_list): #HC
    bc_array = []
    for i in range(0, len(t_list)):
        if t_list[i] >= t_grout: ## once grout is added
            b = area * (d_cent - d_ref) \
                - get_A_by_y(A_s_list, y_s_list, d_ref) \
                - get_A_by_y(A_p_list, y_p_list, d_ref)
        else:   # made array of duct areas since get_A_by_y needs array, not single number
            b = area * (d_cent - d_ref) \
                - get_A_by_y(A_s_list, y_s_list, d_ref) \
                - get_A_by_y([((d_duct/2) ** 2 * math.pi)] * len(A_p_list), y_p_list, d_ref)
        bc_array.append(b)
    output = np.array(bc_array)
    return output

def pre_get_B_c(t_list, area, d_cent, d_ref, A_s_list, y_s_list,
                 A_p_list, y_p_list): #HC
    bc_array = []
    for i in range(0, len(t_list)):
        b = area * (d_cent - d_ref) \
            - get_A_by_y(A_s_list, y_s_list, d_ref) \
            - get_A_by_y(A_p_list, y_p_list, d_ref)
        bc_array.append(b)
    output = np.array(bc_array)
    return output

def get_A_by_y2(A_list, y_list, d_ref): #Used for S and P for sum of total layers #HC
    I_mod = 0
    for i in range(0, len(A_list)):
        I_mod += A_list[i] * ((y_list[i] - d_ref) ** 2)
    return I_mod

def post_get_I_c(I_g, t_list, t_grout, area, d_cent, d_ref, d_duct, A_s_list, y_s_list,
                 A_p_list, y_p_list):
    ic_array = []
    for i in range(0, len(t_list)):
        if t_list[i] >= t_grout: ## once grout is added
            ic = I_g + area * (d_cent - d_ref)**2 \
                - get_A_by_y2(A_s_list, y_s_list, d_ref) \
                - get_A_by_y2(A_p_list, y_p_list, d_ref)
        else:   # made array of duct areas since get_A_by_y needs array, not single number
            ic = I_g + area * (d_cent - d_ref)**2 \
                - get_A_by_y2(A_s_list, y_s_list, d_ref) \
                - get_A_by_y2([((d_duct/2) ** 2 * math.pi)] * len(A_p_list), y_p_list, d_ref)
        ic_array.append(ic)
    output = np.array(ic_array)
    return output

def pre_get_I_c(I_g, t_list, area, d_cent, d_ref, A_s_list, y_s_list,
                 A_p_list, y_p_list): #HC
    ic_array = []
    for i in range(0, len(t_list)):
        ic = I_g + area * (d_cent - d_ref)**2 \
            - get_A_by_y2(A_s_list, y_s_list, d_ref) \
            - get_A_by_y2(A_p_list, y_p_list, d_ref)
        ic_array.append(ic)
    output = np.array(ic_array)
    return output

def get_A_c_slab(t_list, t_comp, area, A_s_list, A_p_list): #HC
    ac_array = []
    for i in range(0, len(t_list)):
        if t_list[i] < t_comp:
            a = 0
        else:
            a = area - sum(A_s_list) - sum(A_p_list)
        ac_array.append(a)
    output = np.array(ac_array)
    return output

def get_B_c_slab(t_list, t_comp, area, d_cent, d_ref, A_s_list, y_s_list,
                 A_p_list, y_p_list): #CK
    bc_array = []
    for i in range(0, len(t_list)):
        if t_list[i] < t_comp: # slab does not contribute since no comp action
            b = 0
        else:
            b = area * (d_cent - d_ref) \
                - get_A_by_y(A_s_list, y_s_list, d_ref) \
                - get_A_by_y(A_p_list, y_p_list, d_ref)
        bc_array.append(b)
    output = np.array(bc_array)
    return output

def get_I_c_slab(I_g, t_list, t_comp, area, d_cent, d_ref, A_s_list, y_s_list,
                 A_p_list, y_p_list): #CK
    ic_array = []
    for i in range(0, len(t_list)):
        if t_list[i] < t_comp:
            ic = 0
        else:
            ic = I_g + area * (d_cent - d_ref)**2 \
                - get_A_by_y2(A_s_list, y_s_list, d_ref) \
                - get_A_by_y2(A_p_list, y_p_list, d_ref)
        ic_array.append(ic)
    output = np.array(ic_array)
    return output

def get_ABI_E(A_c_list, E_c_list):
    output = A_c_list * E_c_list
    return output

def get_AE(A_list, E_list):
    output = 0
    for i in range(0, len(A_list)):
        output += A_list[i] * E_list[i]
    return output

def get_R_A_j(t_list, t2_list, t_comp, A_c_list, E_c_list, A_c_list_2, E_c_list_2,
              A_s_list, E_s_list, A_s_list_2, E_s_list_2, A_p_list, E_p_list):
    array = np.zeros(len(t_list))
    for i in range(0, len(t_list)):
        if t_list[i] >= t_comp:
            array[i] = get_ABI_E(A_c_list[i], E_c_list[i]) \
                       + get_ABI_E(A_c_list_2[i - (len(t_list)-len(t2_list))], E_c_list_2[i - (len(t_list)-len(t2_list))]) \
                       + get_AE(A_s_list, E_s_list) + get_AE(A_s_list_2, E_s_list_2) \
                       + get_AE(A_p_list, E_p_list)
        else:
            array[i] = get_ABI_E(A_c_list[i], E_c_list[i]) \
                       + get_AE(A_s_list, E_s_list)
    return array

def get_YA_E(y_list, A_list, E_list):
    output = 0
    for i in range(0, len(A_list)):
        output += y_list[i] * A_list[i] * E_list[i]
    return output

def get_R_B_j(t_list, t2_list, t_comp, B_c_list, E_c_list, B_c_list_2, E_c_list_2,
              y_s_list, A_s_list, E_s_list, y_s_list_2, A_s_list_2, E_s_list_2, y_p_list, A_p_list, E_p_list):
    array = np.zeros(len(t_list))
    for i in range(0, len(t_list)):
        if t_list[i] >= t_comp:
            array[i] = get_ABI_E(B_c_list[i], E_c_list[i]) \
                       + get_ABI_E(B_c_list_2[i - (len(t_list)-len(t2_list))], E_c_list_2[i - (len(t_list)-len(t2_list))]) \
                       + get_YA_E(y_s_list, A_s_list, E_s_list) + get_YA_E(y_s_list_2, A_s_list_2, E_s_list_2) \
                       + get_YA_E(y_p_list, A_p_list, E_p_list)
        else:
            array[i] = get_ABI_E(B_c_list[i], E_c_list[i]) \
                       + get_YA_E(y_s_list, A_s_list, E_s_list)
    return array

def get_Y2A_E(y_list, A_list, E_list):
    output = 0
    for i in range(0, len(A_list)):
        output += y_list[i]**2 * A_list[i] * E_list[i]
    return output

def get_R_I_j(t_list, t2_list, t_comp, I_c_list, E_c_list, I_c_list_2, E_c_list_2,
              y_s_list, A_s_list, E_s_list, y_s_list_2, A_s_list_2, E_s_list_2, y_p_list, A_p_list, E_p_list):
    array = np.zeros(len(t_list))
    for i in range(0, len(t_list)):
        if t_list[i] >= t_comp:
            array[i] = get_ABI_E(I_c_list[i], E_c_list[i]) \
                       + get_ABI_E(I_c_list_2[i - (len(t_list)-len(t2_list))], E_c_list_2[i - (len(t_list)-len(t2_list))]) \
                       + get_Y2A_E(y_s_list, A_s_list, E_s_list) + get_Y2A_E(y_s_list_2, A_s_list_2, E_s_list_2) \
                       + get_Y2A_E(y_p_list, A_p_list, E_p_list)
        else:
            array[i] = get_ABI_E(I_c_list[i], E_c_list[i]) \
                       + get_Y2A_E(y_s_list, A_s_list, E_s_list)
    return array

def get_A_grout(d_duct, strands_arr, A_p_list):
    output = (d_duct/2) ** 2 * math.pi * sum(strands_arr) - sum(A_p_list)
    return output

def get_B_grout(d_duct, A_p_list, y_p_list):
    array = []
    for i in range(0, len(A_p_list)):
        output = ((d_duct/2) ** 2 * math.pi - A_p_list[i]) * y_p_list[i]
        array.append(output)
    return sum(array)

def get_I_grout(d_duct, A_p_list, y_p_list):
    array = []
    for i in range(0, len(A_p_list)):
        output = ((d_duct/2) ** 2 * math.pi - A_p_list[i]) * y_p_list[i]**2
        array.append(output)
    return sum(array)

def get_tao_2(t_comp,tao_list):
    array=[]
    for i in range(0,len(tao_list)):
        if tao_list[i]>=t_comp:
            output=tao_list[i]
            array.append(output)
    return array

def get_t_2(t_comp,t_list):
    array=[]
    for i in range(0,len(t_list)):
        if t_list[i]>=t_comp:
            output=t_list[i]
            array.append(output)
    return array

def get_f_set_top(A_list, E_list, strain, B_list, curv): # for steel fset- top
    output = A_list * E_list * strain + B_list * E_list * curv
    return output

def get_f_set_bot(B_list, E_list, strain, I_list, curv): #for steep fset- bottom
    output = B_list * E_list * strain + I_list * E_list * curv
    return output

def get_f_set_conc(A_list, E_list, strain, B_list, curv, I_list): # calculate 2 x 1 fset for concrete elements
    # array = np.zeros((1,2))
    # array[0, 0] = get_f_set_top(A_list, E_list, strain, B_list, curv)
    # array[0, 1] = get_f_set_bot(B_list, E_list, strain, I_list, curv)
    array = []
    array.append(get_f_set_top(A_list, E_list, strain, B_list, curv))
    array.append(get_f_set_bot(B_list, E_list, strain, I_list, curv))

    return array

def get_f_set_grout(t_list, t_comp, A_list, E_list, strain, B_list, I_list): ## obtain single value, which will be modified to change over time (concrete)
    for i in range(0, len(t_list)):
        if t_list[i] > t_comp: # in case t_comp is not within the t array
            output = get_f_set_conc(A_list, E_list[i- 1], strain[0, i- 2], B_list, strain[1, i- 2], I_list)
            break

    return output

def get_f_set_slab(t_list, t2_list, t_comp, A_list, E_list, strain, B_list, I_list): # need to use strain[i] where i is based on t array not t2
    diff = len(t_list) - len(t2_list)
    for i in range(0, len(t_list)):
        if t_list[i] > t_comp: # in case t_comp is not within the t array
            output = get_f_set_conc(A_list[i - diff], E_list[i- diff- 1], strain[0, i- 2], B_list[i - diff], strain[1, i- 2], I_list[i - diff])
            break
    return output

def get_f_set(t_list, t_comp, A_list, E_list, strain, y_list): # 2x1 fset for each type of steel, constant over time
    for i in range(0, len(t_list)):
        if t_list[i] > t_comp: # in case t_comp is not within the t array
            top = 0
            bot = 0
            array = np.zeros((2, 1))
            for j in range(0, len(A_list)):
                b_calc = A_list[j] * y_list[j]
                i_calc = A_list[j] * y_list[j] **2
                top_calc = get_f_set_top(A_list[j], E_list[j], strain[0, i -2], b_calc, strain[1, i-2])
                bot_calc = get_f_set_bot(b_calc, E_list[j], strain[0, i- 2], i_calc, strain[1, i - 2])
                top += top_calc
                bot += bot_calc
            array[0, 0] = top
            array[1, 0] = bot
            break
    return array

def get_t_check(t_list, t_comp):
    array = []
    for i in range(0, len(t_list)):
        array.append(int(t_list[i] >= t_comp))
    return array

def get_E_c_conv(t_list, E_c_list, t_check_list):
    array = []
    for i in range(0, len(t_check_list)):
        if t_check_list[i] == 1:
            base = E_c_list[i]
            for j in range(0, len(t_list)):
                output = (E_c_list[j]/ base) * t_check_list[j]
                array.append(output)
            break
    return array

# create Fj
def get_F_j(t_list, Ra, Rb, Ri):
    fj_a = []
    fj_b = []
    fj_i = []
    for i in range(0, len(t_list)):
        p = 1/(Ra[i] * Ri[i] - Rb[i] ** 2)
        fj_a.append(p * Ra[i])
        fj_b.append(p * Rb[i])
        fj_i.append(p * Ri[i])
    array = np.array([[fj_i[0], -fj_b[0]], [-fj_b[0], fj_a[0]]])

    for i in range(1, len(t_list)):  # appending 2 x 2 arrays for original 2x2 Fj array
        a = np.array([[fj_i[i], -fj_b[i]], [-fj_b[i], fj_a[i]]])
        array = np.concatenate((array, a), axis=1)
    return array

def get_ABE_strain(AB_list, E_list, strain_list):
    output = AB_list * E_list * strain_list
    return output

def get_f_sh_j(t_list, A_c_list, E_c_list, B_c_list, strain_list): #CK
    array = np.zeros((2, len(t_list)))
    for i in range(0, len(t_list)):
        array[0, i] = get_ABE_strain(A_c_list[i], E_c_list[i], strain_list[i])
        array[1, i] = get_ABE_strain(B_c_list[i], E_c_list[i], strain_list[i])
    return array

def get_f_sh_j_slab(t_list, t2_list, A_c_list, E_c_list, B_c_list, strain_list): #Ck
    array = np.zeros((2, len(t2_list)))
    for i in range(0, len(t2_list)):
        array[0, i] = get_ABE_strain(A_c_list[i], E_c_list[i], strain_list[i])
        array[1, i] = get_ABE_strain(B_c_list[i], E_c_list[i], strain_list[i])
    start = np.zeros((2, len(t_list) - len(t2_list)))
    array = np.concatenate((start, array), axis = 1)
    return array

def get_D_c_j(t_list, A_c_list, B_c_list, I_c_list, E_c_list): #CK
    array = E_c_list[0] * np.array([[A_c_list[0], B_c_list[0]], [B_c_list[0], I_c_list[0]]])
    for i in range(1, len(t_list)):
        a = E_c_list[i] * np.array([[A_c_list[i], B_c_list[i]], [B_c_list[i], I_c_list[i]]])
        array = np.concatenate((array, a), axis=1)
    return array

def get_w_self(density,area):
    array=density * area
    return array

#Calculating UDL for different times
def get_sw_beam(t_list,tao_list,density_gird,density_slab,area_gird,area_slab,sw_add_loading):
    array = np.zeros(len(t_list)) #the array of UDLS
    loading = np.zeros(len(tao_list)) #create blank array to input

    for a in range(len(tao_list)): #This array determines the UDL for each tao value #HC
     loading[a]=sw_add_loading[a]

    for j in range(len(t_list)): #HC
        for i in range(len(tao_list)):
            if t_list[j]<tao_list[i]:
                sw=loading[i-1]
                break
            elif i==len(tao_list)-1:
                sw=loading[i]
        array[j]=sw
    return array

#calculating moment for different times
def get_moment_beam(t_list,length,x_length,sw_beam):
    array=np.zeros(len(t_list)) #the array of moments
    for j in range(len(t_list)):
        array[j]=sw_beam[j]*x_length/2*(length-x_length)*-1
    return array

#Calculate Compressive Force #need to recalculate to incoporate effect of relaxations losses
def get_N_beam(t_list,N_inital):
    array=np.zeros(len(t_list)) #the array of Compressive forces
    for j in range(len(t_list)):
        array[j]=N_inital*-1
    return array

def get_trpzdl(points_beam,time_points_curve):
    array=np.zeros(len(points_beam))
    for j in range(len(points_beam)):
        if j==0:
            array[j]=0
        else:
            array[j]=array[j-1]+1/2*(points_beam[j]-points_beam[j-1])*(time_points_curve[j]-time_points_curve[j-1])
    return array

if __name__ == '__main__':
    tao = [7, 725, 770,1000] # hardcoded #will this be input by user?
    #t = [7,718,763,900,1000]   # hardcoded #willneedtobe iterated
    t=np.arange(start=7, stop=1100+1, step=1)

t_comp = 770 + 28 #time that concrete is pured eg addition of slab (ctrl f tcomp)
t_slab = 770 # pour time need this to find E_c_tao_2 (slab)
t_grout = 798   ## hardcoded, is when grout is added
d_ref = 0                   # hardcoded
P_p_init = 1000000 #hardcoded, force per strand

# strain in steel calculation at each t
f_p_steel = 1396    #changed
sigma_jack = 1000   #unkown
rb_input = 1        #changed #low relaxation strands used
temp_input = 25     #unkown

r_b_steel = get_r_b_steel(rb_input) #HC
k4_steel = np.array(get_k4_steel(t)) #HC
k5_steel = get_k5_steel(f_p_steel, sigma_jack, r_b_steel) #HC
k6_steel = get_k6_steel(temp_input) #HC
R_steel = k4_steel * k5_steel * k6_steel * r_b_steel #HC
phi_p_steel = R_steel / (1 - R_steel) #HC

# concrete element 1 - material properties
# steel reinf material properties
# moduli
E_s = [0]        #no reinforced steel in girder
E_p = [193000,193000,193000,193000,193000,193000] #Changed for 6 layers

# E_c_tao calculation - p, fcmi, s
p_conc = 2400       #hardcoded
f_cmi_input = 90    #guesstimate based on Concrete structures textbook with table of f'c and fcmi values
s_input = 1         #high early strength concrete was used #changed

# phi_t_tao calculation - k2, k3, k4, k5, phi_basic
i_gross = 1.58 * 10 ** 11   # changed
k4_input = 0    #based in SOuth Texas where it is semiarid therfore k4=0.7
f_c_input = 90.2  #changed

area_1 = 6.598*10**5 #changed
ue_1 = 8974     #brief calc from Girder drawing - refer to additional document

# Ac, Bc, Ic of section variables required
A_s = [0]       # no renforced steel
y_s = [0]           # no renforced steel
A_p = np.array([143*14, 143*27,143*27],dtype=np.float64)*math.pi       # hardcoded
y_p = [(1218+184),(1268+184),(1318+184)] #hardcoded, prestress distance from very top
diam_duct = 60              # hardcoded #disregarded
n_strands = np.array([14,27,27], dtype=np.float64) #calc for each layer of prestressed steel
d_c =801+184                   # calc by yt+184 (thickness of comp deck)

# slab
tao_2 =get_tao_2(t_comp, tao)
t_2 = get_t_2(t_comp, t)
#t_2 = [40, 60, 61,200,30000]       # hardcoded - t array but only show post slab pour times
#tao_2 = [40, 60,200, 30000] #Tao values after slab is poured

# elemnt 2 properties start
E_s_2 = [1862] #Changed
E_p_2 = [0]

# E_c_tao_2 calculation - p, fcmi, s
p_conc_2 = 2400       #hardcoded
f_cmi_input_2 = 60    #Guess based on values
s_input_2 = 1         #taken as high strength concrete

i_gross_2 = 1.5942 * 10 ** 6 #hardcoded
k4_input_2 = 0    #hardcoded
f_c_input_2 = 55.2  #Provided in Report

area_2 = 95*2440 + 89*1816 #hardcoded
ue_2 = 2*(95 + 2440 + 89 + 1816)     #hardcoded

A_s_2 = np.array([16 * 71.33],dtype=np.float64)*math.pi #changed
y_s_2 = [95 + 89/2] #Changed
A_p_2 = [0]
y_p_2 = [0]
diam_duct_2 = 0 #not applicable
n_strands_2 = [0] #not applicable
d_c_2 = 184/2 #changed

#Calculate Moment along the beam from UDL

length=36.89 #CHANGED
length_beam=length*pow(10,3)
N_init=71.6*pow(10,3)
point_along_beam=np.arange(start=0, stop=length+1, step=1)*pow(10,3)
#point_along_beam=np.array([0,2.5,5,7.5,10,12.5,15,17.5,20])*pow(10,3) #points along the beam
points=len(point_along_beam)#number of points selected

sw_addloading=np.array([16.49*pow(10,6),20.5356*pow(10,6),26.33*pow(10,6),27.8436*pow(10,6)])#additional UDL added for 1000 tao value
N_test_calc=get_N_beam(t,N_init)

density_1 =25
density_2=25
UDL_perpoint=get_sw_beam(t,tao,density_1,density_2,area_1,area_2,sw_addloading)

eccentricity = 477
P_e_moment=np.ones(len(t))*eccentricity*N_init

#calculate r_e_j #still haven't replaced r_e_j
for a in range(len(point_along_beam)):
    N_r_e_j = np.zeros(len(t))
    M_r_e_j = np.zeros(len(t))
    N_r_e_j = get_N_beam(t, N_init)
    M_r_e_j=get_moment_beam(t,length_beam,point_along_beam[a],UDL_perpoint)
    M_r_e_j=M_r_e_j+P_e_moment

    if a==0:
        r_e_j=np.vstack((N_r_e_j,M_r_e_j))
    else:
        r_e_j=np.vstack((r_e_j,N_r_e_j,M_r_e_j))

f_p_init_N = get_f_p_init_N(t, n_strands, P_p_init) #HC
f_p_init_M = get_f_p_init_M(t, n_strands, P_p_init, y_p) #HC
f_p_init = np.array([f_p_init_N, f_p_init_M]) #HC
f_p_rel_j = get_f_p_rel(f_p_init_N, f_p_init_M, phi_p_steel) #HC

strain_j = np.zeros((2, len(t)))
f_set_j = np.zeros((2,len(t)))

f_cr_j = np.zeros((2, len(t)))
f_cr_j_2 = np.zeros((2, len(t)))
r_c_j_1 = np.zeros((2, len(t)))
r_c_j_2 = np.zeros((2, len(t)))

f_set_c_slab = np.zeros((2, len(t)))
f_set_c_grout = np.zeros((2, len(t)))
f_set_j = np.zeros((2, len(t)))

E_c = get_E_c(f_cmi_input, p_conc) #HC
s = get_s(s_input) #HC
E_c_tao = get_E_c_tao(t, s, E_c) #HC
t_check_1 = get_t_check(t, t_comp)
E_c_conv_1 = get_E_c_conv(t, E_c_tao, t_check_1)

k2 = get_k2(t, tao, area_1, ue_1) #HC
k3 = get_k3(tao) #HC
k4 = get_k4(k4_input) #HC
k5 = get_k5(f_c_input, t, area_1, ue_1) #HC
phi_basic = get_phi_basic(f_c_input) #HC
phi_t_tao = k2 * k3 * k4 * k5 * phi_basic #HC

# shrinkage strain over time
strain_cse = get_strain_cse(f_c_input, t)
# strain_shd_b_star = get_strain_shd_b_star() # bring this back
strain_shd_b_star = 0.0008 # hard coded
strain_shd_b = (1 - 0.008 * f_c_input) * strain_shd_b_star

tao_dry_1 = 7 # hard coded - should be 1 x n where n is number of components
k1 = np.array(get_k1(t, area_1, ue_1, tao_dry_1)) #HC
strain_shd = k1 * k4 * strain_shd_b #HC
strain_sh_j = strain_cse + strain_shd #HC

# J_t_tao, E_c_j, Feji
J_t_tao = get_J_t_tao(t, tao, E_c_tao, phi_t_tao) #HC
E_c_j = get_E_c_j(t, tao, J_t_tao) #HC
F_e_j_i = get_Fe_j_i(t, tao, J_t_tao) #Check Calcs with Calvin - Code matches calcs

# E_c_tao related calcs for slab
E_c_2 = get_E_c(f_cmi_input_2, p_conc_2) #HC
s_2 = get_s(s_input_2) #HC
E_c_tao_2_t = get_E_c_tao_2_t(t_2, t_slab) ## array containing days since slab pour #HC
E_c_tao_2 = get_E_c_tao(E_c_tao_2_t, s_2, E_c_2) #HC
t_check_2 = get_t_check(t_2, t_comp)
E_c_conv_2 = get_E_c_conv(t_2, E_c_tao_2, t_check_2)

# phi t tao slab
k2_2 = get_k2(t_2, tao_2, area_2, ue_2)
k3_2 = get_k3(tao_2)
k4_2 = get_k4(k4_input_2)
k5_2 = get_k5(f_c_input_2, t_2, area_2, ue_2)
phi_basic_2 = get_phi_basic(f_c_input_2)
phi_t_tao_2 = k2_2 * k3_2 * k4_2 * k5_2 * phi_basic_2

# shrinkage strain over time
# strain_shd_b_star_2 = get_strain_shd_b_star() # bring this back
strain_shd_b_star_2 = 0.0008 # hard coded
strain_shd_b_2 = (1 - 0.008 * f_c_input_2) * strain_shd_b_star_2

tao_dry_2 = 7 # hard coded - should be 1 x n where n is number of components #CK
strain_cse_2 = get_strain_cse(f_c_input_2, t_2)
k1_2 = np.array(get_k1(t_2, area_2, ue_2, tao_dry_2))
strain_shd_2 = k1_2 * k4_2 * strain_shd_b
strain_sh_j_2 = strain_cse_2 + strain_shd_2

# J_t_tao, E_c_j, Feji for slab #CK
J_t_tao_2 = get_J_t_tao(t_2, tao_2, E_c_tao_2, phi_t_tao_2)
E_c_j_2 = get_E_c_j(t_2, tao_2, J_t_tao_2)
F_e_j_i_2 = get_Fe_j_i(t_2, tao_2, J_t_tao_2)

# Ac, Bc, Ic
pre_A_c = pre_get_A_c(t, area_1, A_s, A_p) #HC
pre_B_c = pre_get_B_c(t, area_1, d_c, d_ref, A_s, y_s, A_p, y_p) #HC
pre_I_c = pre_get_I_c(i_gross, t, area_1, d_c, d_ref, A_s, y_s, A_p, y_p) #HC

post_A_c = post_get_A_c(t, t_grout, area_1, diam_duct, n_strands, A_s, A_p) #HC
post_B_c = post_get_B_c(t, t_grout, area_1, d_c, d_ref, diam_duct, A_s, y_s, A_p, y_p) #HC
post_I_c = post_get_I_c(i_gross, t, t_grout, area_1, d_c, d_ref, diam_duct, A_s, y_s, A_p, y_p) #HC

# slab (2) Ac, Bc and Ic is not affected by post/pre (no grout in slab) #CK - Note will area be calc of input?
# will be 0 if composite action is not available at t
A_c_2 = get_A_c_slab(t_2, t_comp, area_2, A_s_2, A_p_2)
B_c_2 = get_B_c_slab(t_2, t_comp, area_2, d_c_2, d_ref, A_s_2, y_s_2, A_p_2, y_p_2)
I_c_2 = get_I_c_slab(i_gross_2, t_2, t_comp, area_2, d_c_2, d_ref, A_s_2, y_s_2, A_p_2, y_p_2)

# cross sectional rigidities
# post because post_A_c, if want pre, use pre_A_c
post_R_A_j = get_R_A_j(t, t_2, t_comp, post_A_c, E_c_tao, A_c_2, E_c_tao_2, A_s, E_s, A_s_2, E_s_2, A_p, E_p)
post_R_B_j = get_R_B_j(t, t_2, t_comp, post_B_c, E_c_tao, B_c_2, E_c_tao_2, y_s, A_s, E_s, y_s_2, A_s_2, E_s_2, y_p, A_p, E_p)
post_R_I_j = get_R_I_j(t, t_2, t_comp, post_I_c, E_c_tao, I_c_2, E_c_tao_2, y_s, A_s, E_s, y_s_2, A_s_2, E_s_2, y_p, A_p, E_p)

pre_R_A_j = get_R_A_j(t, t_2, t_comp, pre_A_c, E_c_tao, A_c_2, E_c_tao_2, A_s, E_s, A_s_2, E_s_2, A_p, E_p)
pre_R_B_j = get_R_B_j(t, t_2, t_comp, pre_B_c, E_c_tao, B_c_2, E_c_tao_2, y_s, A_s, E_s, y_s_2, A_s_2, E_s_2, y_p, A_p, E_p)
pre_R_I_j = get_R_I_j(t, t_2, t_comp, pre_I_c, E_c_tao, I_c_2, E_c_tao_2, y_s, A_s, E_s, y_s_2, A_s_2, E_s_2, y_p, A_p, E_p)

post_F_j = get_F_j(t, post_R_A_j, post_R_B_j, post_R_I_j)
pre_F_j = get_F_j(t, pre_R_A_j, pre_R_B_j, pre_R_I_j)

post_f_sh_j = get_f_sh_j(t, post_A_c, E_c_tao, post_B_c, strain_sh_j)
pre_f_sh_j = get_f_sh_j(t, pre_A_c, E_c_tao, pre_B_c, strain_sh_j)
f_sh_j_slab = get_f_sh_j_slab(t, t_2, A_c_2, E_c_tao_2, B_c_2, strain_sh_j_2)

# for pre, use pre_A_c etc
post_D_c_j = get_D_c_j(t, post_A_c, post_B_c, post_I_c, E_c_tao)
pre_D_c_j = get_D_c_j(t, pre_A_c, pre_B_c, pre_I_c, E_c_tao)
D_c_j_2 = get_D_c_j(t_2, A_c_2, B_c_2, I_c_2, E_c_tao_2)

post_tension = 0 #hardcoded
#m = 0
#n = 2

points = len(point_along_beam)

strain_j = np.zeros((points * 2, len(t)))
f_set_j = np.zeros((2,len(t)))

f_cr_j = np.zeros((2, len(t)))
f_cr_j_2 = np.zeros((2, len(t)))
r_c_j_1 = np.zeros((2, len(t)))
r_c_j_2 = np.zeros((2, len(t)))

f_set_c_slab = np.zeros((2, len(t)))
f_set_c_grout = np.zeros((2, len(t)))
f_set_j = np.zeros((2, len(t)))

for z in range(0, points):
    m = 0
    n = 2
    for i in range(0, len(t)):
        if post_tension == 1:
            output = 0

            if t[i] < t_comp:
                for j in range(0, len(tao)):
                    d = F_e_j_i[j, i] * r_c_j_1[:, j]
                    output = output + d
                f_cr_j[:, i] = output

                a = (r_e_j[2*z:2*z+2, i] - f_cr_j[:, i] + post_f_sh_j[:, i] - f_p_init[:, i] + f_p_rel_j[:, i]).reshape(-1, 1)

                strain_j[2*z:2*z+2, i] = np.dot(post_F_j[:, m:n], a).reshape( 1, -1)
                r_c_j_1[:, i] = np.dot(post_D_c_j[:, m:n], strain_j[2*z:2*z+2,i]) + f_cr_j[:,i] - post_f_sh_j[:, i]

                m = m + 2
                n = n + 2
            else:
                for j in range(0, len(tao)):
                    d = F_e_j_i[j, i] * r_c_j_1[:, j] + F_e_j_i_2[j - (len(tao) - len(tao_2)), i - (len(t) - len(t_2))] * r_c_j_2[:, j - (len(tao) - len(tao_2))]
                    output = output + d
                f_cr_j[:, i] = output

                f_set_p = get_f_set(t, t_comp, A_p, E_p, strain_j, y_p)  # prestress in element 1
                f_set_s_2 = get_f_set(t, t_comp, A_s_2, E_s_2, strain_j, y_s_2)  # steel in element 2
                f_set_c_slab[:, i] = get_f_set_slab(t, t_2, t_comp, A_c_2, E_c_tao_2, strain_j, B_c_2,
                                                    I_c_2) # concrete in slab (element 2)
                f_set_c_slab[:, i] = f_set_c_slab[:, i] * E_c_conv_2[i - (len(E_c_tao) - len(E_c_tao_2))]

                area_grout = get_A_grout(diam_duct, n_strands, A_p)
                B_grout = get_B_grout(diam_duct, A_p, y_p)
                I_grout = get_I_grout(diam_duct, A_p, y_p)
                f_set_c_grout[:, i] = get_f_set_grout(t, t_comp, area_grout, E_c_tao, strain_j, B_grout,
                                                I_grout)  # grout in section (element 1)
                f_set_c_grout[:, i] = f_set_c_grout[:, i] * E_c_conv_1[i]

                f_set_j[:, i] = (f_set_p + f_set_s_2).reshape(1, -1) + f_set_c_slab[:, i] + f_set_c_grout[:, i]
                a = (r_e_j[2*z:2*z+2, i] - f_cr_j[:, i] + post_f_sh_j[:, i] + f_sh_j_slab[:, i] - f_p_init[:, i] + f_p_rel_j[:, i] + f_set_j[:, i]).reshape(-1, 1)
                strain_j[2*z:2*z+2, i] = np.dot(post_F_j[:, m:n], a).reshape(1, -1)

                r_c_j_1[:, i] = np.dot(post_D_c_j[:, m:n], strain_j[2*z:2*z+2, i]) + f_cr_j[:, i] - post_f_sh_j[:, i]  - f_set_c_grout[:, i]
                r_c_j_2[:, i] = np.dot(D_c_j_2[:, m - 2*(len(t)-len(t_2)):n - 2*(len(t)-len(t_2))], strain_j[2*z:2*z+2, i]) + f_cr_j_2[:, i] - f_sh_j_slab[:, i] - f_set_c_slab[:, i]
                r_c_j_2[:, 3] = [0, 0] # hardcoded, can remove

                m = m + 2
                n = n + 2
        else:
            output = 0

            if t[i] < t_comp:
                for j in range(0, len(tao)):
                    d = F_e_j_i[j, i] * r_c_j_1[:, j]
                    output = output + d
                f_cr_j[:, i] = output

                a = (r_e_j[2*z:2*z+2, i] - f_cr_j[:, i] + pre_f_sh_j[:, i] - f_p_init[:, i] + f_p_rel_j[:, i]).reshape(-1, 1)
                strain_j[2*z:2*z+2, i] = np.dot(pre_F_j[:, m:n], a).reshape( 1, -1)
                r_c_j_1[:, i] = np.dot(pre_D_c_j[:, m:n], strain_j[2*z:2*z+2,i]) + f_cr_j[:,i] - pre_f_sh_j[:, i]

                m = m + 2
                n = n + 2
            else:
                for j in range(0, len(tao)):
                    for k in range(0,len(tao_2)):
                        d = F_e_j_i[j, i] * r_c_j_1[:, j] + F_e_j_i_2[k, i - (len(t) - len(t_2))] * r_c_j_2[:, j - k]
                        output = output + d
                f_cr_j[:, i] = output

                f_set_p = get_f_set(t, t_comp, A_p, E_p, strain_j, y_p)  # prestress in element 1
                f_set_s_2 = get_f_set(t, t_comp, A_s_2, E_s_2, strain_j, y_s_2)  # steel in element 2
                f_set_c_slab[:, i] = get_f_set_slab(t, t_2, t_comp, A_c_2, E_c_tao_2, strain_j, B_c_2,
                                                    I_c_2) # concrete in slab (element 2)
                f_set_c_slab[:, i] = f_set_c_slab[:, i] * E_c_conv_2[i - (len(E_c_tao) - len(E_c_tao_2))]

                area_grout = 0
                B_grout = 0
                I_grout = 0

                f_set_j[:, i] = (f_set_p + f_set_s_2).reshape(1, -1) + f_set_c_slab[:, i] + f_set_c_grout[:, i]
                a = (r_e_j[2*z:2*z+2, i] - f_cr_j[:, i] + pre_f_sh_j[:, i] + f_sh_j_slab[:, i] - f_p_init[:, i] + f_p_rel_j[:, i] + f_set_j[:, i]).reshape(-1, 1)
                strain_j[2*z:2*z+2, i] = np.dot(pre_F_j[:, m:n], a).reshape(1, -1)

                r_c_j_1[:, i] = np.dot(pre_D_c_j[:, m:n], strain_j[2*z:2*z+2, i]) + f_cr_j[:, i] - pre_f_sh_j[:, i]  - f_set_c_grout[:, i]
                r_c_j_2[:, i] = np.dot(D_c_j_2[:, m - 2*(len(t)-len(t_2)):n - 2*(len(t)-len(t_2))], strain_j[2*z:2*z+2, i]) + f_cr_j_2[:, i] - f_sh_j_slab[:, i] - f_set_c_slab[:, i]
                r_c_j_2[:, 3] = [0, 0] # hardcoded, can remove

                m = m + 2
                n = n + 2

#Obtaining the array of relating curvatures by time by points along the beam
time_points_curve=np.zeros((len(t),len(point_along_beam)))
for j in range(len(t)):
 for i in range(len(point_along_beam)):
     if i==0:
         time_points_curve[j, i] = strain_j[i+1, j]
     else:
         time_points_curve[j, i] = strain_j[2*i+1, j] #obtains the curvatures along beam with the respective times (rows) and points along beam (columns)

#Calculating the first integration - using the trapezoidal method
for j in range(len(t)):
    integerarray=get_trpzdl(point_along_beam,time_points_curve[j])
    if j==0:
        first_integration=integerarray
    else:
        first_integration=np.vstack((first_integration,integerarray))

#Calculating the second integration - using the trapezoidal method - this is the deflection
for j in range(len(t)):
    integerarray=get_trpzdl(point_along_beam,first_integration[j])
    if j==0:
        second_integration=integerarray
    else:
        second_integration=np.vstack((second_integration,integerarray))

#Obtain Deflection Array
deflection_array= np.transpose(second_integration)

#Determining Deflection for t =0 to t=transfer
#print(t)
time=np.arange(start=0, stop=tao[0], step=1)
t_result=np.append(time,t)
time_zero_deflection=np.zeros(t[0]-time[0])
#print(time_zero_deflection)

#Deflection plot calculation
#length required by user
length_input=5 #in m
for i in range(len(point_along_beam)):
    if (length_input*10**3)==point_along_beam[i]:
        deflection_plot_array=deflection_array[i]
        deflection_plot_array=np.append(time_zero_deflection,deflection_plot_array)
        break

#print(deflection_plot_array)
py.plot(t_result[0:len(t_result)-1] , deflection_plot_array[0:len(t_result)-1],'r')
py.xticks([0 ,100 ,200 ,300 ,400, 500, 600, 700, 800, 900, 1000])
py.xlabel("Number of Days")
py.ylabel("Deflection (mm)")
py.margins(x=0)
py.show()

#Code to display deflection versus time - this is for t(0)
#py.plot(point_along_beam, second_integration[0],'or')
#py.show()

#Code to display Curvature versus time - this is for t(0)
#py.plot(point_along_beam, time_points_curve[0],'or')
#py.show()


import json
from copy import deepcopy

import requests
from requests_oauthlib import OAuth1

from config import yelp_consumer_key, yelp_consumer_secret, yelp_token, \
    yelp_token_secret

root_categories = None

def get_categories_tree():
    categories_yelp = requests.get(
        'https://www.yelp.com/developers/documentation/v2/all_category_list/categories.json').json()

    from collections import defaultdict
    cats = defaultdict(list)
    for c in categories_yelp:
        for p in c['parents']:
            cats[p].append({'alias': c['alias'], 'title': c['title']})

    root_cats = [c for c in categories_yelp if not c['parents']]

    all_cats = {c['alias']: {'children': [], 'title': c['title']} for c in
                categories_yelp}

    tree = {c['alias']: {'children': all_cats[c['alias']]['children'],
                         'title': c['title']} for c in root_cats}

    for c in categories_yelp:
        for p in c['parents']:
            all_cats[p]['children'].append({c['alias']: all_cats[c['alias']]})

    return tree

def del_keys(x):
    keys = {
        'categories', 'display_phone', 'image_url', 'location',
        'rating_img_url_small', 'review_count'
    }
    copy = deepcopy(x)
    for key in copy.keys():
        if key not in keys:
            del x[key]
    copy = deepcopy(x)
    for key in copy['location'].keys():
        if key != 'coordinate':
            del x['location'][key]
    return x

def coords_only(x):
    return x['location']['coordinate']

def get_places(city):
    global root_categories
    if not root_categories:
        root_categories = json.load(open('root_cats.json'))
    auth = OAuth1(yelp_consumer_key, yelp_consumer_secret, yelp_token,
                  yelp_token_secret)

    points = {}
    for c in root_categories.keys():
        r = requests.get(
            'https://api.yelp.com/v2/search?location={}&category_filter={}&radius_filter=5000&limit=40&sort=2'.format(
                city, c),
            auth=auth)
        points[c] = r.json()

    keys2del = []
    for c in points.keys():
        try:
            points[c] = [coords_only(x) for x in points[c]['businesses']]
        except KeyError:
            if 'error' in points[c].keys():
                keys2del.append(c)
            else:
                pass
    for k in keys2del:
        del points[k]

    return points

if __name__ == '__main__':
    print(get_places('Zurich'))


from Zebra_puzzle_classes import *

if __name__ == '__main__':

    # Take way too long. Function would need to be more efficient to handle this level of size.
    variables_1 = [["English", "Spaniard", "Ukrainian", "Norwegian", "Japanese"],
             ["Red","Green","Ivory","Yellow","Blue"],
             ["Dog","Snails","Fox","Zebra","Horse"],
             ["Snakes and Ladders", "Cluedo", "Pictionary", "Travel The World", "Backgammon"],
             ["Coffee","Milk","Orange Juice","Tea","Water"],

             ["English_2", "Spaniard_2", "Ukrainian_2", "Norwegian_2", "Japanese_2"],
             ["Red_2","Green_2","Ivory_2","Yellow_2","Blue_2"],
             ["Dog_2","Snails_2","Fox_2","Zebra_2","Horse_2"],
             ["Snakes and Ladder_2s", "Cluedo_2", "Pictionary_2", "Travel The World_2", "Backgammon_2"],
             ["Coffee_2","Milk_2","Orange Juice_2","Tea_2","Water_2"],
             ["Nationality", "Color", "Pet","Board Game","Drink","Nationality_2", "Color_2", "Pet_2","Board Game_2","Drink_2"]]

    var_list_2 = variables = [["English", "Spaniard", "Ukrainian", "Norwegian", "Japanese","Irish"],
                 ["Red","Green","Ivory","Yellow","Blue","Super Green"],
                 ["Dog","Snails","Fox","Zebra","Horse","Irish Dog"],
                 ["Snakes and Ladders", "Cluedo", "Pictionary", "Travel The World", "Backgammon","Irish game"],
                 ["Coffee","Milk","Orange Juice","Tea","Water","Beer"],
                 ["Nationality", "Color", "Pet","Board Game","Drink"]]

    var_list_3 = variables = [["English", "Spaniard", "Ukrainian", "Norwegian", "Japanese","Irish"],
                 ["Red","Green","Ivory","Yellow","Blue","Super Green"],
                 ["Dog","Snails","Fox","Zebra","Horse","Irish Dog"],
                 ["Snakes and Ladders", "Cluedo", "Pictionary", "Travel The World", "Backgammon","Irish game"],
                 ["Coffee","Milk","Orange Juice","Tea","Water","Beer"],
                ["Kill bill","Cars 2","Iron Man","Avengers","Ferris Bullers Day off","Zootopia"],
                 ["Nationality", "Color", "Pet","Board Game","Drink","Movie"]]

    # Create the problem
    further_testing_zebra = Problem(var_list_3)

    # Create constraints
    further_testing_zebra.create_constraint(Constraint_equality_var_var("Red","English"))
    further_testing_zebra.create_constraint(Constraint_equality_var_var("Spaniard","Dog"))
    further_testing_zebra.create_constraint(Constraint_equality_var_var("Coffee","Green"))
    further_testing_zebra.create_constraint(Constraint_equality_var_var("Ukrainian","Tea"))

    further_testing_zebra.create_constraint(Constraint_equality_var_plus_cons("Green","Ivory",1,0))
    further_testing_zebra.create_constraint(Constraint_equality_var_var("Snakes and Ladders","Snails"))
    further_testing_zebra.create_constraint(Constraint_equality_var_var("Cluedo","Yellow"))

    further_testing_zebra.create_constraint(Constraint_equality_var_cons("Milk",3))
    further_testing_zebra.create_constraint(Constraint_equality_var_cons("Norwegian",1))

    further_testing_zebra.create_constraint(Constraint_equality_var_plus_cons("Pictionary","Fox",1,1))
    further_testing_zebra.create_constraint(Constraint_equality_var_plus_cons("Cluedo","Horse",1,1))

    further_testing_zebra.create_constraint(Constraint_equality_var_var("Travel The World","Orange Juice"))
    further_testing_zebra.create_constraint(Constraint_equality_var_var("Japanese","Backgammon"))

    further_testing_zebra.create_constraint(Constraint_equality_var_plus_cons("Norwegian","Blue",1,1))

    # Constraints for var list 3
    further_testing_zebra.create_constraint(Constraint_equality_var_cons("Kill bill",1))
    further_testing_zebra.create_constraint(Constraint_equality_var_cons("Iron Man",4))
    further_testing_zebra.create_constraint(Constraint_equality_var_cons("Avengers",2))

    # General constraint for domains being unable to have the same value
    further_testing_zebra.create_constraint(Constraint_difference_var_var())

    # Run reduction till no more domains can be reduced
    further_testing_zebra.apply_reduction()

    # Run domain splitting. If multiple results wanted set varialbe to 1
    further_testing_zebra.domain_splitting(results_single=0)

    # Print current results - Single results
    # further_testing_zebra.print_final_resutls_single()

    # Print results - Multiple results
    further_testing_zebra.print_mulit_results()


from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from phonenumber_field.modelfields import PhoneNumberField
from django.utils.translation import gettext as _

COUNTRIES = (
    ('JP','日本'),
    ('US', 'United States'),
)

PREFECTURES = [
    ('Hokkaido','北海道 Hokkaido'),
    ('Aomori','青森県 Aomori'),
    ('Iwate','岩手県 Iwate'),
    ('Miyagi','宮城県 Miyagi'),
    ('Akita','秋田県 Akita'),
    ('Yamagata','山形県 Yamagata'),
    ('Fukushima','福島県 Fukushima'),
    ('Ibaraki','茨城県 Ibaraki'),
    ('Tochigi','栃木県 Tochigi'),
    ('Gunma','群馬県 Gunma'),
    ('Saitama','埼玉県 Saitama'),
    ('Chiba','千葉県 Chiba'),
    ('Tokyo','東京都 Tokyo'),
    ('Kanagawa','神奈川県 Kanagawa'),
    ('Niigata','新潟県 Niigata'),
    ('Toyama','富山県 Toyama'),
    ('Ishikawa','石川県 Ishikawa'),
    ('Fukui','福井県 Fukui'),
    ('Yamanashi','山梨県 Yamanashi'),
    ('Nagano','長野県 Nagano'),
    ('Gifu','岐阜県 Gifu'),
    ('Shizuoka','静岡県 Shizuoka'),
    ('Aichi','愛知県 Aichi'),
    ('Mie','三重県 Mie'),
    ('Shiga','滋賀県 Shiga'),
    ('Kyoto','京都府 Kyoto'),
    ('Osaka','大阪府 Osaka'),
    ('Hyogo','兵庫県 Hyogo'),
    ('Nara','奈良県 Nara'),
    ('Wakayama','和歌山県 Wakayama'),
    ('Tottori','鳥取県 Tottori'),
    ('Shimane','島根県 Shimane'),
    ('Okayama','岡山県 Okayama'),
    ('Hiroshima','広島県 Hiroshima'),
    ('Yamaguchi','山口県 Yamaguchi'),
    ('Tokushima','徳島県 Tokushima'),
    ('Kagawa','香川県 Kagawa'),
    ('Ehime','愛媛県 Ehime'),
    ('Kochi','高知県 Kochi'),
    ('Fukuoka','福岡県 Fukuoka'),
    ('Saga','佐賀県 Saga'),
    ('Nagasaki','長崎県 Nagasaki'),
    ('Kumamoto','熊本県 Kumamoto'),
    ('Oita','大分県 Oita'),
    ('Miyazaki','宮崎県 Miyazaki'),
    ('Kagoshima','鹿児島県 Kagoshima'),
    ('Okinawa','沖縄県 Okinawa'),
]

STATES = (
    ('Armed Forces','Armed Forces - AA'),
    ('Armed Forces Europe','Armed Forces Europe - AE'),
    ('Armed Forces Pacific','Armed Forces Pacific - AP'),
    ('Alabama','Alabama'),
    ('Alaska','Alaska'),
    ('Arizona','Arizona'),
    ('Arkansas','Arkansas'),
    ('California','California'),
    ('Colorado','Colorado'),
    ('Connecticut','Connecticut'),
    ('Delaware','Delaware'),
    ('District of Columbia', 'District of Columbia'),
    ('Florida','Florida'),
    ('Georgia','Georgia'),
    ('Hawaii','Hawaii'),
    ('Idaho','Idaho'),
    ('Illinois','Illinois'),
    ('Indiana','Indiana'),
    ('Iowa','Iowa'),
    ('Kansas','Kansas'),
    ('Kentucky','Kentucky'),
    ('Louisiana','Louisiana'),
    ('Maine','Maine'),
    ('Maryland','Maryland'),
    ('Massachusetts','Massachusetts'),
    ('Michigan','Michigan'),
    ('Minnesota','Minnesota'),
    ('Mississippi','Mississippi'),
    ('Missouri','Missouri'),
    ('Montana','Montana'),
    ('Nebraska','Nebraska'),
    ('Nevada','Nevada'),
    ('New Hampshire','New Hampshire'),
    ('New Jersey','New Jersey'),
    ('New Mexico','New Mexico'),
    ('New York','New York'),
    ('North Carolina','North Carolina'),
    ('North Dakota','North Dakota'),
    ('Ohio','Ohio'),
    ('Oklahoma','Oklahoma'),
    ('Oregon','Oregon'),
    ('Pennsylvania','Pennsylvania'),
    ('Rhode Island','Rhode Island'),
    ('South Carolina','South Carolina'),
    ('South Dakota','South Dakota'),
    ('Tennessee','Tennessee'),
    ('Texas','Texas'),
    ('Utah','Utah'),
    ('Vermont','Vermont'),
    ('Virgin Islands','Virgin Islands'),
    ('Virginia','Virginia'),
    ('Washington','Washington'),
    ('West Virginia','West Virginia'),
    ('Wisconsin','Wisconsin'),
    ('Wyoming','Wyoming'),
    ('Guam','Guam'),
    ('Puerto Rico', 'Puerto Rico'),
)

# first time migrating, specify app like: python manage.py makemigrations account
# account model to extend the User model for adding mailing addresses
# and other contact info
class Account(models.Model):
    # when a User is deleted, this account will be deleted, the opposite is not true
    # this generates a user_id field whose value is the pk of this same user in the auth_user table
    user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)

    # phone_number field japanese phone number format is +81-XXX-XXXX-XXXX
    # us format is: +1-XXX-XXX-XXXX
    phone_number = models.CharField(max_length=14,blank=True,null=True)
    date_created = models.DateTimeField(auto_now_add=True,null=True)
    # Shipping Addresses:
    # US Shipping Address
    street1 = models.CharField(max_length=100, blank=True)
    street2 = models.CharField(max_length=100, blank=True)
    city = models.CharField(max_length=50, blank=True)
    country = models.CharField(choices=COUNTRIES, max_length=2, blank=True, null=True)
    state = models.CharField(choices =STATES, max_length=50, blank=True, null=True)
    prefecture = models.CharField(choices=PREFECTURES, max_length=50, blank=True, null=True)
    postal_code = models.CharField(max_length=20, blank=True)
    address_entered = models.BooleanField(default=False)

    def __str__(self):
        # return str(self.user)
        return self.user.username


# test codes
# initialize die[]
# top front right bottom back left
#  0    1     2     3     4   5
die = [3, 2, 1, 4, 5, 6]
cell = 2

# function: move
# input: null
# output: die[] after moved
def move_right():
    die_copy = die[:]
    die[3] = die_copy[2] # right become bottom
    die[2] = die_copy[0] # top become right
    die[0] = die_copy[5] # left become top
    die[5] = die_copy[3] # bottom become left
    return
def move_left():
    die_copy = die[:]
    die[0] = die_copy[2] # right become top
    die[5] = die_copy[0] # top become left
    die[3] = die_copy[5] # left become bottom
    die[2] = die_copy[3] # bottom become right
    return
def move_forewards():
    die_copy = die[:]
    die[1] = die_copy[0] # top become front
    die[3] = die_copy[1] # front become bottom
    die[4] = die_copy[3] # bottom become back
    die[0] = die_copy[4] # back become top
    return
def move_backwards():
    die_copy = die[:]
    die[4] = die_copy[0] # top become back
    die[0] = die_copy[1] # front become top
    die[1] = die_copy[3] # bottom become front
    die[3] = die_copy[4] # back become bottom
    return

# test code:
move_right()
move_forewards()
move_left()
move_left()
move_backwards()

# user interface: output part
print(f'On Cell {cell}, {die[0]} is at the top, {die[1]} at the front, and {die[2]} on the right')


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 24 12:57:55 2023

@author: qhong7
"""

import pandas as pd
import os
comm = """curl --request POST
        --url "http://206.207.50.58:5007/MT_ML_Qijun_Hong_Predict_noNN"
        --header "content-type:application/json"
        --data """

df_formula = pd.read_csv('chemical_formula.csv', names=['chemical_formula'])

data_str = "\'["
for i in range(df_formula.shape[0]):
    if len(data_str) > 2: data_str += ","
    data_str += '{"9":"' + df_formula.iloc[i]['chemical_formula'] + '"}'
data_str += "]\'"
comm +=  data_str + "> predictions "

response = os.system(comm.replace('\n',''))
os.system("""cat predictions | sed 's/,/\\n/g' | cut -d':' -f2 | sed 's/}//' | sed 's/]//' > predictions.csv""")

'''
speed test:
10: 7s
1000: 34s
10000: 303s
'''

df_mp = pd.read_csv('predictions.csv', names=['melting_temperature_in_kelvin'])
df = pd.concat([df_formula, df_mp], axis=1)

df.to_csv('output.csv')
os.system("""rm predict*""")