import os
import numpy as np # linear algebra
import nibabel as nib
from nilearn import plotting
from sklearn.model_selection import train_test_split
from PIL import Image
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import keras
import keras.backend as K
import argparse
from keras.layers import *
from keras.preprocessing.image import ImageDataGenerator
from keras.callbacks import LearningRateScheduler, ModelCheckpoint
from loss_functions import *
from models import *
from keras.optimizers import *
from keras.callbacks import *
from keras.utils import multi_gpu_model
import tensorflow as tf
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

def import_files():
    BASE_IMG_PATH = './sample_data/'
    all_images = glob(os.path.join(BASE_IMG_PATH, '3d_images', 'IMG_*'))
    print(len(all_images), ' matching files found:', all_images[1])
    train_paths, test_paths = train_test_split(all_images, random_state=2018,
                                               test_size=0.4)
    print(len(train_paths), 'training size')
    print(len(test_paths), 'testing size')
    return train_paths, test_paths

DS_FACT = 2  # downscale
SEED = 201

def check_arr_nan(in_img, in_mask):
    indices = []
    for i in range(0, len(in_mask)):
        if (not np.any(in_mask[i])):
            continue
        else:
            indices.append(i)
    return len(indices), np.array(indices)

def mask_preprocess(train_mask):
    indices = np.where(train_mask > 0)
    train_mask[indices] = 1.0
    return train_mask

def read_all_slices(in_paths, path_image, rescale=False, balanced=True,
                    intr=True, ext=False, hem=False):
    """ writing sample code, write different logic, just to flatten out all
    image slices, this logic is messing"""
    cur_vol = np.concatenate(
        [np.transpose(nib.load(c_path).get_data())[:, ::DS_FACT, ::DS_FACT] for
         c_path in in_paths], 0)
    cur_vol_mask = np.concatenate(
        [np.transpose(nib.load(c_path).get_data())[:, ::DS_FACT, ::DS_FACT] for
         c_path in path_image], 0)

    if balanced:
        num_no_bleed, s_id = check_arr_nan(cur_vol, cur_vol_mask)
        num_bleed = range(0, len(cur_vol))
        num_bleed = np.setdiff1d(num_bleed, s_id)
        indices = np.random.choice(num_bleed.shape[0], num_no_bleed,
                                   replace=True)
        s_id = np.concatenate([s_id, num_bleed[indices]])
        cur_vol, cur_vol_mask = cur_vol[s_id], cur_vol_mask[s_id]
    cur_vol_mask = mask_preprocess(cur_vol_mask)
    if intr:
        index=np.where(cur_vol>479)
        cur_vol[index]=-1024.0
        index=np.where(cur_vol<-39)
        cur_vol[index]=-1024.0
    if ext:
        index = np.where(cur_vol > 2285)
        cur_vol[index] = -1024.0
        index = np.where(cur_vol < -916)
        cur_vol[index] = -1024.0
    if hem:
        index = np.where(cur_vol > 1360)
        cur_vol[index] = -1024.0
        index = np.where(cur_vol < -630)
        cur_vol[index] = -1024.0
    if rescale:
        cur_vol = (cur_vol.astype(np.float32) - np.mean(
            cur_vol.astype(np.float32))) / np.std(cur_vol.astype(np.float32))
        return cur_vol, cur_vol_mask
    else:
        return cur_vol, cur_vol_mask

def read_both(in_paths):
    print ("BEGIN READING IMAGES")
    path_image = list(map(lambda x: x.replace('IMG_', 'MASK_'), in_paths))
    return read_all_slices(in_paths, path_image, rescale=False)

def plot_loaded_files(train_vol,train_mask):
    slices = train_vol[-1000, :, :]
    masks = train_mask[-1000, :, :]
    fig, axes = plt.subplots(1, 2)
    axes[0].imshow(slices, cmap="gray", origin="lower")
    axes[1].imshow(masks, cmap="gray", origin="lower")
    slices = train_vol[100, :, :]
    masks = train_mask[100, :, :]
    fig, axes = plt.subplots(1, 2)
    axes[0].imshow(slices, cmap="gray", origin="lower")
    axes[1].imshow(masks, cmap="gray", origin="lower")

def data_to_numpy():
    train_paths,test_paths = import_files()
    train_vol, train_mask = read_both(train_paths)
    print('train', train_vol.shape, 'mask', train_mask.shape)
    test_vol, test_mask = read_both(test_paths)
    return train_vol, train_mask, test_vol, test_mask

def my_generator(x_train, y_train, batch_size):
    data_generator = ImageDataGenerator(shear_range=0.001, fill_mode='nearest').flow(x_train, x_train, batch_size, seed=SEED)
    mask_generator = ImageDataGenerator(shear_range=0.001, fill_mode='nearest').flow(y_train, y_train, batch_size, seed=SEED)
    while True:
        x_batch, _ = data_generator.next()
        y_batch, _ = mask_generator.next()
        yield x_batch, y_batch

def run_me():
    train_vol, train_mask, test_vol, test_mask = data_to_numpy()
    x_data, y_data = train_vol, train_mask
    x_data = x_data[:, :, :, np.newaxis]
    y_data = y_data[:, :, :, np.newaxis]
    test_vol = test_vol[:, :, :, np.newaxis]
    test_mask = test_mask[:, :, :, np.newaxis]
    x_train, x_val, y_train, y_val = train_test_split(x_data, y_data,test_size=0.2)
    return x_train, x_val, y_train, y_val, test_vol, test_mask

def plot_loss(history,name):
    plt.plot(history.history['loss'], color='b', label='train_loss')
    plt.plot(history.history['val_loss'], color='r', label='validation_loss')
    plt.show()
    plt.title (name)
    plt.savefig(name+'loss_function', bbox_inches="tight")

def plot_dc(history,name):
    plt.plot(history.history['dice_coef'], color='b')
    plt.plot(history.history['val_dice_coef'], color='r')
    plt.show()
    plt.title (name)
    plt.savefig(name+'dice_coefficient', bbox_inches="tight")

def main(case):
    x_train, x_val, y_train, y_val, test_vol, test_mask = run_me()
    model = get_unetpp(pretrained_weights='./weights/weight.h5')
    if case:
        try:
          model = multi_gpu_model(model)
        except:
           pass
        model.compile(optimizer=Adam(2e-4), loss=focal_tversky, metrics=[dice_coef, sensitivity, specificity])
        learning_rate_reduction = ReduceLROnPlateau(monitor='val_dice_coef',factor=0.5, patience=30, verbose=1, mode='auto', min_delta=0.001, cooldown=0, min_lr=0.000000001)
        epochs = 300
        batch_size = 16
        steps_per_epoch = 50
        es = EarlyStopping(monitor='val_loss', mode='min', verbose=2, patience=70)
        weight_saver = ModelCheckpoint('./weights/training.h5',monitor='val_dice_coef', save_best_only=True, save_weights_only=True, mode = 'max')
        history = model.fit_generator(
            my_generator(x_train, y_train, batch_size=batch_size),
            epochs=epochs, validation_data=(x_val, y_val),
            verbose=2, steps_per_epoch=steps_per_epoch
            , callbacks=[weight_saver, learning_rate_reduction,es])

        plot_loss(history, 'INT_Focal_Tversky_Unetpp')
        plot_dc(history, 'INT_Focal_TverskyL_Unetpp')
    else:
        dice_coefficient_test = []
        sensitivity_test =[]
        specificity_test = []
        y_test = model.predict(test_vol)
        test_mask=test_mask.astype(np.float32)
        for i in range(0, len(test_mask)):
            dice_coefficient_test.append(K.eval(dice_coef(test_mask[i], y_test[i])))
            sensitivity_test.append(K.eval(sensitivity(test_mask[i],y_test[i])))
            specificity_test.append(K.eval(specificity(test_mask[i],y_test[i])))
        print ("average of Dice Coefficient, Sensitivity, Specificity", dice_coefficient_test.mean(), sensitivity_test.mean(), specificity_test.mean())

def run():
    parser = argparse.ArgumentParser(description='Arguments for training or testing')
    parser.add_argument("--train", dest="train", help="train model or not", type=str, required=False)
    args = parser.parse_args()
    if args.train:
        main(True)
    else:
        main(False)

if __name__ == '__main__':
    run()


# # Mission to Mars

from splinter import Browser
from bs4 import BeautifulSoup
import pandas as pd
import time

def init_browser():
    # @NOTE: Replace the path with your actual path to the chromedriver
    executable_path = {"executable_path": "/usr/local/bin/chromedriver"}
    return Browser("chrome", **executable_path, headless=False)

def scrape_info():
    browser = init_browser()

# ## Nasa Mars News

    # Visit URL of page to be scraped through splinter
    url = 'https://mars.nasa.gov/news/'
    browser.visit(url)
    time.sleep(1)

    # Create html object
    html = browser.html

    # Parse with BeautifulSoup
    soup = BeautifulSoup(html, 'html.parser')

    # Extract most recent article title and text
    news_title = soup.find_all('div', class_ = 'content_title')[1].text
    news_p = soup.find_all('div', class_ = 'article_teaser_body')[0].text

    # ## JPL Mars Space Images - Featured Image

    # Visit URL of page to be scraped through splinter
    jpl_url = 'https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars'
    browser.visit(jpl_url)
    time.sleep(1)

    #Click on the the button go to the full image
    full_image = browser.find_by_id("full_image")
    full_image.click()
    browser.is_element_present_by_text("more info")
    time.sleep(1)
    full_size = browser.links.find_by_partial_text("more info")
    full_size.click()

    # Create html object
    jpl_html = browser.html

    # Parse with BeautifulSoup
    jpl_soup = BeautifulSoup(jpl_html, 'html.parser')

    #Retrieve backgroud image url from style tag/scrape url
    img_url = jpl_soup.find("img", class_ = "main_image")["src"]
    featured_img_url = "https://www.jpl.nasa.gov" + img_url

    # ## Mars Facts

    #Visit the Mars Facts webpage
    facts_url = "https://space-facts.com/mars/"
    browser.visit(facts_url)
    time.sleep(1)

    # Use Pandas to parse the URL
    tables = pd.read_html(facts_url)

    #Use Pandas to scrape the table containing facts about the planet including Diameter, Mass, etc.
    facts_df = tables[0]

    #Assign column names
    facts_df.columns = ["Description", "Value"]

    #Formatting
    facts_df["Description"] = facts_df["Description"].str.replace(":", "")

    #Use Pandas to convert the data to a HTML table string
    facts_html = facts_df.to_html()

    # ## Mars Hemispheres

    # Visit url to be scraped through splinter
    hems_url = "https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars"
    browser.visit(hems_url)
    time.sleep(1)

    # Create HTML object & Parse with BeautifulSoup
    hems_html = browser.html

    hems_soup = BeautifulSoup(hems_html, "html.parser")

    # Create empty list for saving dictionaries title, url
    hemisphere_image_urls = []

    products = hems_soup.find('div', class_='result-list')

    hemispheres = products.find_all('div', {'class': 'item'})

    # Loop through to append title and url
    for hems in hemispheres:
        title = hems.find("h3").text
        title = title.replace(" Enhanced", "")
        img_link = hems.find("a")["href"]
        image_url = "https://astrogeology.usgs.gov/" + img_link

        browser.visit(image_url)
        time.sleep(1)
        hems_html = browser.html
        hems_soup = BeautifulSoup(hems_html, "html.parser")
        downloads = hems_soup.find("div", class_="downloads")
        image_url = downloads.find("a")["href"]
        hemisphere_image_urls.append({"title": title, "img_url": image_url})

    # for i in range(len(results)):
    #     hemisphere={}
    #     browser.find_by_css("a.product-item h3")[i].click()
    #     image_url=browser.links.find_by_text('Sample').first['href']
    #     title=browser.find_by_css("h2.title").text
    #     hemisphere["img_url"]=image_url
    #     hemisphere["title"]=title
    #     hem_image_urls.append(hemisphere)
    #     browser.back()

    # hem_image_urls

# # Store data in a dictionary
#     mars_data = {
#         "hem_image_urls": hem_image_urls,
#         "mars_fact": mars_facts,
#         "full_image_url": full_image_url,
#         "news_p":news_p,
#         "news_title":news_title
#     }

    # Assigning scraped data to a page

    mars_data = {}
    mars_data["news_title"] = news_title
    mars_data["news_p"] = news_p
    mars_data["featured_img_url"] = featured_img_url
    mars_data["facts_html"] = facts_html
    mars_data["hemisphere_image_urls"] = hemisphere_image_urls

    # Close the browser after scraping
    browser.quit()

    return mars_data

if __name__ == "__main__":
    print(scrape_info())


__author__ = 'Chen Xing, Devansh Arpit'
import argparse
import time
import math
import numpy as np
import os
import torch
import torch.nn as nn
from torch.autograd import Variable
import pickle as pkl
from models import vgg11, MLPNet
import resnet_models

import torchvision
import torchvision.transforms as transforms

from dataloader import get_data_loaders

###############################################################################
# Training code
###############################################################################
def compute_dist():
    global model
    global param_dist_list
    with open(save_dir + '/init_model.pt', 'rb') as f:
        checkpoint = torch.load(f)
    model_init = checkpoint['net']
    d = 0.
    for param1, param2 in zip(model_init.parameters(), model.parameters()):
        param1 = param1.data.cpu().numpy()
        param2 = param2.data.cpu().numpy()
        d += np.sum((param1 - param2) ** 2)
    param_dist_list.append(np.sqrt(d))

    with open(save_dir + "/param_dist_list.pkl", "wb") as f:
        pkl.dump(param_dist_list, f)

def test(epoch, loader, valid=False):
    global best_acc
    global model
    model.eval()
    test_loss = 0
    correct = 0
    total = 0
    for batch_idx, (inputs, targets) in enumerate(loader):
        if use_cuda:
            inputs, targets = inputs.cuda(), targets.cuda()
        inputs, targets = Variable(inputs, volatile=True), Variable(targets)
        outputs = model(inputs)
        loss = criterion(outputs, targets)

        test_loss += loss.data.item()
        _, predicted = torch.max(outputs.data, 1)
        total += targets.size(0)
        correct += predicted.eq(targets.data).cpu().sum()

    # Save checkpoint.
    acc = 100. * correct / total
    if valid and acc > best_acc:
        print('Saving best model..')
        state = {
            'net': model,
            'acc': acc,
            'epoch': epoch,
        }
        with open(save_dir + '/best_model.pt', 'wb') as f:
            torch.save(state, f)
        best_acc = acc
    return acc

def compute_angle_et_norm():
    global optimizer
    global model
    global cos_mg_list
    global grad_norm_list
    if not hasattr(compute_angle_et_norm, 'm'):
        compute_angle_et_norm.m = {}

    dot = 0
    norm1 = 0
    norm2 = 0
    for name, variable in model.named_parameters():

        g = variable.grad.data
        if not name in compute_angle_et_norm.m.keys():
            compute_angle_et_norm.m[name] = g.clone()
            dot += torch.sum(compute_angle_et_norm.m[name] * g.clone())
            norm1 += torch.sum(compute_angle_et_norm.m[name] * compute_angle_et_norm.m[name])
            norm2 += torch.sum(g.clone() * g.clone())
        else:
            dot += torch.sum(compute_angle_et_norm.m[name] * g.clone())
            norm1 += torch.sum(compute_angle_et_norm.m[name] * compute_angle_et_norm.m[name])
            norm2 += torch.sum(g.clone() * g.clone())
            compute_angle_et_norm.m[name] = g.clone()

    cos = dot / (np.sqrt(norm1 * norm2) + 0.000001)
    cos_mg_list.append(cos)
    with open(save_dir + "/cos_mg_list.pkl", "wb") as f:
        pkl.dump(cos_mg_list, f)

    grad_norm_list.append(norm2)
    with open(save_dir + "/grad_norm_list.pkl", "wb") as f:
        pkl.dump(grad_norm_list, f)

    return cos

def train(epoch):
    global trainloader
    global optimizer
    global args
    global model
    model.train()
    train_loss = 0
    correct = 0
    total = 0
    loss_list = []

    optimizer.zero_grad()

    for batch_idx, (inputs, targets) in enumerate(trainloader):
        if use_cuda:
            inputs, targets = inputs.cuda(), targets.cuda()
        inputs, targets = Variable(inputs), Variable(targets)
        outputs = model(inputs)
        loss = criterion(outputs, targets)
        loss.backward()

        optimizer.step()
        compute_angle_et_norm()
        compute_dist()
        optimizer.zero_grad()
        if (args.save_model_per_iter is True)&((epoch==1)|(epoch==10)|(epoch==25)|(epoch==100)):
            print('Saving intermediate model..')
            state = {
                'net': model,
                'iter': batch_idx,
            }
            with open(save_dir + '/epoch_{}.batch_{}.pt'.format(epoch, batch_idx), 'wb') as f:
                torch.save(state, f)

        loss_list.append(loss.data.item())
        train_loss += loss.data.item()
        _, predicted = torch.max(outputs.data, 1)
        total += targets.size(0)
        correct += predicted.eq(targets.data).cpu().sum()

    print('Saving model..')
    state = {
        'net': model,
        'iter': epoch,
    }
    with open(save_dir + '/epoch_{}.pt'.format(epoch), 'wb') as f:
        torch.save(state, f)

    return sum(loss_list) / float(len(loss_list)), 100. * correct / total

###############################################################################
# Main function
###############################################################################
if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Experiments of "A Walk with SGD"')
    # Directories
    parser.add_argument('--data', type=str, default='./data/',
                        help='location of the data corpus')
    # Hyperparams
    parser.add_argument('--seed', type=int, default=0,
                        help='random seed')
    parser.add_argument('--lr', type=float, default=0.1,
                        help='learning rate factor that gets multiplied to the hard coded LR schedule in the code')
    parser.add_argument('--epochs', type=int, default=500,
                        help='upper epoch limit')
    parser.add_argument('--init', type=str, default="he")
    parser.add_argument('--wdecay', type=float, default=0,
                        help='weight decay applied to all weights')#1e-4

    parser.add_argument('--batch_size', type=int, default=128, metavar='N',
                        help='minibatch size')
    # Meta arguments: Tracking, resumability, CUDA
    parser.add_argument('--dataset', type=str, default='cifar10',
                        help='dataset name (cifar10, mnist)')
    parser.add_argument('--arch', type=str, default='ResNet56',
                        help='arch name (resnet, vgg11, mlp)')
    parser.add_argument('--resume', type=bool, default=False,
                        help='resume experiment ')
    parser.add_argument('--cuda', action='store_false',
                        help='use CUDA')
    parser.add_argument('--cluster', action='store_true', help='do not show the progress bar for batch job')

    parser.add_argument('--save_model_per_iter', type=bool, default=True,
                        help='')
    args = parser.parse_args()

    use_cuda = torch.cuda.is_available()
    ### Set the random seed
    torch.manual_seed(args.seed)
    if use_cuda:
        torch.cuda.manual_seed_all(args.seed)

    # Set the random seed manually for reproducibility.
    torch.manual_seed(args.seed)
    if torch.cuda.is_available():
        torch.cuda.manual_seed(args.seed)

    ###############################################################################
    # Load data
    ###############################################################################

    print('==> Preparing data..')

    trainloader, testloader, _ = get_data_loaders(args)

    ###############################################################################
    # Build the model
    ###############################################################################
    save_dir = './' + args.arch + str(args.batch_size)

    if not os.path.exists(save_dir):
        os.makedirs(save_dir)

    if args.resume:
        # Load checkpoint.
        print('==> Resuming from checkpoint..')
        assert os.path.isdir(save_dir), 'Error: no checkpoint directory found!'
        with open(save_dir + '/best_model.pt', 'rb') as f:
            checkpoint = torch.load(f)
        model = checkpoint['net']
        best_acc = checkpoint['acc']
        start_epoch = checkpoint['epoch']

        lr_list = pkl.load(open(save_dir + "/LR_list.pkl", "r"))

        train_loss_list = pkl.load(open(save_dir + "/train_loss.pkl", "r"))

        train_acc_list = pkl.load(open(save_dir + "/train_acc.pkl", "r"))

        valid_acc_list = pkl.load(open(save_dir + "/valid_acc.pkl", "r"))

        param_dist_list = pkl.load(open(save_dir + "/param_dist_list.pkl", "r"))

    else:
        if os.path.isdir(save_dir):
            with open(save_dir + '/log.txt', 'w') as f:
                f.write('')
        print('==> Building model..')

        start_epoch = 1

        model_to_call = getattr(resnet_models, args.arch)
        model = model_to_call()

        # nb = 0
        # if args.init == 'he':
        #     for m in model.modules():
        #         if isinstance(m, nn.Conv2d):
        #             nb += 1
        #             print('Update init of ', m)
        #             n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
        #             m.weight.data.normal_(0, math.sqrt(2. / n))
        #         elif isinstance(m, nn.BatchNorm2d):
        #             print('Update init of ', m)
        #             m.weight.data.fill_(1)
        #             m.bias.data.zero_()

        best_acc = 0
        lr_list = []

        train_loss_list = []
        train_acc_list = []
        valid_acc_list = []
        param_dist_list = []
        cos_mg_list = []
        grad_norm_list = []

    if use_cuda:
        model.cuda()
    total_params = sum(np.prod(x.size()) if len(x.size()) > 1 else x.size()[0] for x in model.parameters())
    print('Args:', args)
    with open(save_dir + '/log.txt', 'a') as f:
        f.write(str(args) + ',total_params=' + str(total_params) + '\n')

    criterion = nn.CrossEntropyLoss()
    # criterion_nll = nn.NLLLoss()

    print('Saving initial model..')
    state = {
        'net': model,
        'acc': -1,
        'epoch': 0,
    }
    with open(save_dir + '/init_model.pt', 'wb') as f:
        torch.save(state, f)

    # Loop over epochs.

    optimizer = torch.optim.SGD(model.parameters(), lr=args.lr,
                                                momentum=0, \
                                                weight_decay=args.wdecay, nesterov=False)
    for epoch in range(start_epoch, args.epochs + 1):
        epoch_start_time = time.time()
        loss, train_acc = train(epoch)
        print("current lr:"+str(optimizer.param_groups[0]['lr']))
        train_loss_list.append(loss)
        train_acc_list.append(train_acc)
        valid_acc = test(epoch, testloader, valid=True)
        valid_acc_list.append(valid_acc)
        with open(save_dir + "/train_loss.pkl", "wb") as f:
            pkl.dump(train_loss_list, f)
        with open(save_dir + "/train_acc.pkl", "wb") as f:
            pkl.dump(train_acc_list, f)
        with open(save_dir + "/valid_acc.pkl", "wb") as f:
            pkl.dump(valid_acc_list, f)
        lr_list.append(optimizer.param_groups[0]['lr'])
        epoch_fac = 1.
        status = 'Epoch {}/{} | Loss {:3f} | Acc {:3f} | val-acc {:.3f}| max-variance {:.3f}| LR {:4f} | BS {}'. \
            format(epoch, args.epochs * epoch_fac, loss, train_acc, valid_acc, 0, lr_list[-1], args.batch_size)
        with open(save_dir + '/log.txt', 'a') as f:
            f.write(status + '\n')

        with open(save_dir + "/LR_list.pkl", "wb") as f:
            pkl.dump(lr_list, f)
        print('-' * 89)

    # Load the best saved model.
    with open(save_dir + '/best_model.pt', 'rb') as f:
        best_state = torch.load(f)
    model = best_state['net']
    # Run on test data.
    test_acc = test(epoch, testloader, valid=True)
    print('=' * 89)
    print('| End of training | test acc {}'.format(test_acc))
    print('=' * 89)


import pyodbc

class ShippingListDB:
    def __init__(self):
        self.dbConnection = pyodbc.connect('Driver={SQL Server};'
                                           'Server=DESKTOP-EH0BFR0;'
                                           'Database=WebAPI_Python_DB;'
                                           'Trusted_Connection=yes;')

    def getElementList(self):
        cursor = self.dbConnection.cursor()
        cursor.execute('select * from WebAPI_Python_DB.dbo.ShoppingList')
        return list(cursor)

    def addElement(self, name, quantity):
        cursor = self.dbConnection.cursor()
        cursor.execute("insert into ShoppingList(name, quantity) values (?, ?)", str(
            name), str(quantity))
        self.dbConnection.commit()
        return

if __name__ == "__main__":
    database = ShippingListDB()
    elements = database.getElementList()
    for element in elements:
        print("name:"+str(element.name)+"-quantity:"+str(element.quantity))

    database.addElement("polpette", 1000)
    elements = database.getElementList()
    for element in elements:
        print("name:"+str(element.name)+"-quantity:"+str(element.quantity))


import torch
import time
from datetime import datetime
from pathlib import Path
from torch.utils.data import Dataset, DataLoader

from utils.hungarian import hungarian
from data.sg_dataset import SGDataset, get_dataloader
from utils.evaluation_metric import matching_accuracy
from parallel import DataParallel
from utils.model_sl import load_model
import numpy as np
from utils.config import cfg
from GMN.displacement_layer import Displacement

def eval_model(model, dataloader, eval_epoch=None, verbose=False):
    print('Start evaluation...')
    since = time.time()

    device = next(model.parameters()).device

    if eval_epoch is not None:
        model_path = str(f'./output/vgg16_gmn_willow/params/params_0001.pt')
        print('Loading model parameters from {}'.format(model_path))
        load_model(model, model_path)

    was_training = model.training
    model.eval()
    displacement = Displacement()
    lap_solver = hungarian

    # inference
    running_since = time.time()
    acc_match_num = torch.zeros(1, device=device)
    acc_total_num = torch.zeros(1, device=device)
    iter_num = 0
    for inputs in dataloader:
        if inputs == None:
            continue

        inp_type = 'img'
        data1, data2 = [_.cuda() for _ in inputs['images']]
        P1_gt, P2_gt = [_.cuda() for _ in inputs['Ps']]
        n1_gt, n2_gt = [_.cuda() for _ in inputs['ns']]
        e1_gt, e2_gt = [_.cuda() for _ in inputs['es']]
        G1_gt, G2_gt = [_.cuda() for _ in inputs['Gs']]
        H1_gt, H2_gt = [_.cuda() for _ in inputs['Hs']]
        KG, KH = [_.cuda() for _ in inputs['Ks']]
        label = inputs['gt_perm_mat'].cuda()

        batch_num = data1.size(0)

        iter_num = iter_num + 1

        with torch.set_grad_enabled(False):
            s_pred, pred = \
                model(data1, data2, P1_gt, P2_gt, G1_gt, G2_gt, H1_gt, H2_gt,
                      n1_gt, n2_gt, KG, KH, inp_type)

        s_pred = s_pred.cpu().numpy()
        a_pred = np.zeros_like(s_pred)
        a_pred_= np.zeros((np.shape(a_pred)[0],np.shape(a_pred)[1]))
        for b in range(batch_num):
            for i in range(np.shape(a_pred)[1]):
                m = np.argmax(s_pred[b][i])
                a_pred_[b][i] = s_pred[b][i][m]
        for b in range(batch_num):
            k = min(n1_gt[b].item(), n2_gt[b].item())
            for i in a_pred_[b].argsort()[-k:][::-1]:
                m = np.argmax(s_pred[b][i])
                a_pred[b][i][m] = 1
        print(f"** Result **")
        #print(f"raw_pred :\n{s_pred}")
        print(f"pred :\n{a_pred}")
        print(f"label :\n{label.cpu().numpy()}")

    time_elapsed = time.time() - since
    print('Evaluation complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60))
    #model.train(mode=was_training)

if __name__ == '__main__':
    from utils.dup_stdout_manager import DupStdoutFileManager
    from utils.parse_args import parse_args
    from utils.print_easydict import print_easydict

    args = parse_args('Deep learning of graph matching evaluation code.')

    import importlib
    mod = importlib.import_module(cfg.MODULE)
    Net = mod.Net

    torch.manual_seed(cfg.RANDOM_SEED)

    dataset = SGDataset('../scene-graph-proposal/data/vg/')
    dataloader = get_dataloader(dataset)
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

    model = Net()
    model = model.to(device)
    model = DataParallel(model, device_ids=cfg.GPUS)

    if not Path(cfg.OUTPUT_PATH).exists():
        Path(cfg.OUTPUT_PATH).mkdir(parents=True)
    now_time = datetime.now().strftime('%Y-%m-%d-%H-%M-%S')

    #with DupStdoutFileManager(str(Path(cfg.OUTPUT_PATH) / ('eval_log_' + now_time + '.log'))) as _:
    print_easydict(cfg)
    eval_model(model, dataloader, eval_epoch=cfg.EVAL.EPOCH if cfg.EVAL.EPOCH != 0 else None, verbose=True)


"""
Implements a controller for RALFit
https://github.com/ralna/RALFit
"""

import ral_nlls
from scipy.optimize._numdiff import approx_derivative

from fitbenchmarking.fitting.controllers.base_controller import Controller

class RALFitController(Controller):
    """
    Controller for the RALFit fitting software.
    """

    def __init__(self, problem, use_errors):
        """
        Initialises variable used for temporary storage.
        """
        super(RALFitController, self).__init__(problem, use_errors)

        self._popt = None
        self._options = {}

    def setup(self):
        """
        Setup for RALFit
        """
        self._options["maxit"] = 500
        if self.minimizer == "gn":
            self._options["model"] = 1
            self._options["nlls_method"] = 4
        elif self.minimizer == "gn_reg":
            self._options["model"] = 1
            self._options["type_of_method"] = 2
        elif self.minimizer == "hybrid":
            self._options["model"] = 3
            self._options["nlls_method"] = 4
        elif self.minimizer == "hybrid_reg":
            self._options["model"] = 3
            self._options["type_of_method"] = 2
        else:
            raise RuntimeError("An undefined RALFit minmizer was selected")

    def _prediction_error(self, p):
        f = self.problem.eval_f(params=p,
                                function_id=self.function_id)
        f = f - self.data_y
        if self.use_errors:
            f = f / self.data_e

        return f

    def _jac(self, p):
        j = approx_derivative(self._prediction_error,
                              p)
        return j

    def fit(self):
        """
        Run problem with RALFit.
        """
        self.success = False
        self._popt = ral_nlls.solve(self.initial_params,
                                    self._prediction_error,
                                    self._jac,
                                    options=self._options)[0]

        self.success = (self._popt is not None)

    def cleanup(self):
        """
        Convert the result to a numpy array and populate the variables results
        will be read from.
        """
        if self.success:
            self.results = self.problem.eval_f(params=self._popt,
                                               function_id=self.function_id)
            self.final_params = self._popt


import json, requests

s_date = '2016-11-16'
e_date = '2016-11-17'

url = "http://m2utech.eastus.cloudapp.azure.com:5223/dashboard/restapi/getTbRawDataByPeriod?startDate={}&endDate={}".format(s_date,e_date)

uResponse = requests.get(url)

Jresponse = uResponse.text
data = json.loads(Jresponse)
print(data)


# This file was used to produce Figure 4

# Files 'I_retrieve_era5_data.py', 'II_netcdf_to_pickle.py', 'III_mass_flux_calculation.py', 'IV_surface_snow_calculation.py'
# and 'IV_surface_snow_calculation_no_fractionation.py' were reran from 2010 to 2016 for Dome C only

# Simulation ran for Dome C only to save on computing time

# Dome C coordinates: [-75, 123.25]

# In 'IV_surface_snow_calculation.py', b for loop refers to latitude (-75), and c for loop refers to longitude (123.25)

# Use the following to get the index values for the for loops.
# b_index = E['latitude'].index(-75.0)
# c_index = E['longitude'].index(123.25)

# To run for loop for one location: for x in range(x_index, x_index+1)

import pandas as pd
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
import joblib
import datetime
import matplotlib.dates as md
import datetime
import xlrd
import xlsxwriter

D = joblib.load('/home/riqo/mass_flux_files/mass_flux_pickle') # Modified version of file for DomeC between 2010 and 2016

I = joblib.load('/home/riqo/surface_snow_files/surface_snow_isotopic_composition_all') # Modified version of file for DomeC between 2010 and 2016

I_nf = joblib.load('/home/riqo/surface_snow_files/surface_snow_isotopic_composition_no_fractionation_all') # Modified version of file for DomeC between 2010 and 2016

excel = pd.read_excel('/home/riqo/surface_snow_files/domeC_observations.xls', sheet_name='Python') # Observations from Dome C

V = pd.DataFrame(excel, columns= ['date','delta_O_surface'])

E['latitude'] = E['latitude'].tolist()
E['longitude'] = E['longitude'].tolist()

b_index = E['latitude'].index(-75.0)
c_index = E['longitude'].index(123.25)

start = datetime.datetime.strptime('2010-01-01 00:00:00', '%Y-%m-%d %H:%M:%S')
end = datetime.datetime.strptime('2017-12-31 23:00:00', '%Y-%m-%d %H:%M:%S')

dif = int((end-start).total_seconds()/3600) ## time difference in hours

time_list = [(start + datetime.timedelta(hours=x)).strftime('%Y-%m-%d %H:%M:%S') for x in range(dif+1)]

time = []

for i in range(len(time_list)):
    time.append(datetime.datetime.strptime(time_list[i], '%Y-%m-%d %H:%M:%S'))

time_months = [time[373], time[1081], time[1789], time[2521], time[3253], time[3985], time[4717], time[5461], time[6193], time[6925], time[7657], time[8389]]

start_index = E['time'].index('2011-01-01 00:00:00')
end_index = E['time'].index('2016-01-01 00:00:00')

layers_1 = 5 #SUNITDC
layers_2 = 10 #PREREC
layers_3 = 15 #NIVO
total_cells = 50
cells_1 = total_cells - layers_1
cells_2 = total_cells - layers_2
cells_3 = total_cells - layers_3
start_time_index_1 = E['time'].index('2010-12-03 00:00:00')
start_time_index_2 = E['time'].index('2012-02-15 00:00:00')
start_time_index_3 = E['time'].index('2013-11-25 00:00:00')
end_time_index_1 = E['time'].index('2011-12-09 00:00:00')
end_time_index_2 = E['time'].index('2012-10-13 00:00:00')
end_time_index_3 = E['time'].index('2016-01-12 00:00:00')

delta_O_snow_1 = np.mean(I['delta_O_snow_layer_depth'][start_time_index_1:end_time_index_1,b_index,c_index,cells_1:], axis = 1)
delta_O_snow_2 = np.mean(I['delta_O_snow_layer_depth'][start_time_index_2:end_time_index_2,b_index,c_index,cells_2:], axis = 1)
delta_O_snow_3 = np.mean(I['delta_O_snow_layer_depth'][start_time_index_3:end_time_index_3,b_index,c_index,cells_3:], axis = 1)

delta_O_snow_1_nf = np.mean(I_nf['delta_O_snow_layer_depth'][start_time_index_1:end_time_index_1,b_index,c_index,cells_1:], axis = 1)
delta_O_snow_2_nf = np.mean(I_nf['delta_O_snow_layer_depth'][start_time_index_2:end_time_index_2,b_index,c_index,cells_2:], axis = 1)
delta_O_snow_3_nf = np.mean(I_nf['delta_O_snow_layer_depth'][start_time_index_3:end_time_index_3,b_index,c_index,cells_3:], axis = 1)

# graphs for 1 year

def make_patch_spines_invisible(ax):
    ax.set_frame_on(True)
    ax.patch.set_visible(False)
    for sp in ax.spines.values():
        sp.set_visible(False)

fig, ax1 = plt.subplots()

fig.set_figwidth(10)

fig.subplots_adjust(right=0.75)

p1, = ax1.plot(time[start_time_index_1:end_time_index_1], delta_O_snow_1, color='k', label = 'from model (with fractionation)', zorder=100)
p2, = ax1.plot(time[start_time_index_2:end_time_index_2], delta_O_snow_2, color='k', zorder=100)
p3, = ax1.plot(time[start_time_index_3:end_time_index_3], delta_O_snow_3, color='k', zorder=100)

p10, = ax1.plot(V.date[:50], V.delta_O_surface[0:50], color='darkgreen', label = 'from literature', zorder=1) #SUNITDC
p20, = ax1.plot(V.date[50:122], V.delta_O_surface[50:122], color='darkgreen', zorder=1) #PREREC
p30, = ax1.plot(V.date[122:], V.delta_O_surface[122:], color='darkgreen', zorder=1) #NIVO

p100, = ax1.plot(time[start_time_index_1:end_time_index_1], delta_O_snow_1_nf, color='b', label = 'from model (without fractionation)', zorder=100)
p200, = ax1.plot(time[start_time_index_2:end_time_index_2], delta_O_snow_2_nf, color='b', zorder=100)
p300, = ax1.plot(time[start_time_index_3:end_time_index_3], delta_O_snow_3_nf, color='b', zorder=100)

ax1.set_ylabel('\u03B4$^{18}O$ of surface snow (\u2030 vs VSMOW)', size=16, color = 'k')
ax1.set_xlabel("Time", size=16)

ax1.yaxis.label.set_color(p1.get_color())

tkw = dict(size=4, width=1.5)
ax1.tick_params(axis='y', colors=p1.get_color(), **tkw)
ax1.tick_params(axis='x', **tkw)

ax1.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc='lower left',
           ncol=2, mode="expand", borderaxespad=0.)

years = md.YearLocator()   # every year
months = md.MonthLocator()  # every month
format_ = md.DateFormatter('%Y')

ax1.xaxis.set_major_locator(years)
ax1.xaxis.set_major_formatter(format_)
ax1.xaxis.set_minor_locator(months)

ax1.axvline(x='2010-12-03 00:00:00', color='grey', linestyle='dashed')
ax1.axvline(x='2012-02-15 00:00:00', color='grey', linestyle='dashed')
ax1.axvline(x='2013-11-25 00:00:00', color='grey', linestyle='dashed')

ax1.axvline(x='2011-12-09 00:00:00', color='grey', linestyle='dashed')
ax1.axvline(x='2012-10-13 00:00:00', color='grey', linestyle='dashed')
ax1.axvline(x='2016-01-12 00:00:00', color='grey', linestyle='dashed')

plt.tight_layout()

Figures_paths = '/home/riqo/Figures/'

plt.savefig(Figures_paths + 'Figure4')


# uncompyle6 version 3.7.4
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: /home/jbn/s/code/foorep/foorep/plugins/exif.py
# Compiled at: 2012-12-14 06:53:09
from foorep import Plugin

class Exif(Plugin):

    def analyze(self, path):
        try:
            import pyexiv2
        except ImportError:
            return

        try:
            exif = pyexiv2.ImageMetadata(path)
            exif.read()
            self.tags = exif.exif_keys
        except IOError:
            return

        if self.tags:
            result = {'type': 'exif', 'value': {}}
            for tag in exif.exif_keys:
                result['value'][tag.replace('.', '_')] = exif[tag].human_value

        else:
            result = None
        return result


#coding:utf-8
#py3
import json
import requests
import xlwt

def get_dic_data(url,page=1,size=10,s_showYear=2017,sort=['id','desc']):

	data = {'page':page,'size':size,'s_showYear':s_showYear,'sort':sort}
	res_obj = requests.post(url,data)
	dic_data = json.loads(res_obj.text)
	list_data = dic_data['data']
	return list_data

def write_into_excel(page,sheetname,list_dic_data=[]):
	for lis in list_dic_data:
		for v in list(lis.values()):
			try:
				sheetname.write((list_dic_data.index(lis)+(i-1)*10+1),list(lis.values()).index(v),v)
			except Exception:
				print(lis)
				sheetname.write((list_dic_data.index(lis)+(i-1)*10+1),list(lis.values()).index(v,(list(lis.values()).index(v)+1)),v)

def set_excel_style():

	style = xlwt.XFStyle()
	font = xlwt.Font()
	font.bold = True
	font.height = 400
	font.colour_index = 100
	style.font = font

	return style

if __name__ == "__main__":
	#下载2017年，一共144页影片数据
	url = 'http://www.zgdypw.cn/bits/w/porsfilms/api/s'
	wb = xlwt.Workbook(encoding='utf-8')
	s1 = wb.add_sheet('film')
	lis = ['id','code','name','publishVersion','publishVersionName','type','typeName','producerName','publisherName','publishDate']
	for v in lis:
		s1.write(0,lis.index(v),v,set_excel_style())
	for i in range(1,145):
		list_data = get_dic_data(url,page=i)
		write_into_excel(i,s1,list_data)
	wb.save('film_info.xls')


import os

ENDL = '\n'
SIL = 'SIL'
#SLOVNIK = ['nula', 'jedna', 'dva', 'tri', 'ctyri', 'pet', 'sest', 'sedm', 'osm', 'devet']
SLOVNIK = ['nula', 'jedna', 'dva', 'tři', 'čtyři', 'pět', 'šest', 'sedm', 'osm', 'devět']

def nahravka_info(nazev):
    casti_nazvu = nazev.replace('.','_').split('_')

    cislo_slova = cislo_osoby = cislo_sady = 0

    for cast in casti_nazvu:
        if cast.startswith('c'):   cislo_slova = int(cast[1:])
        elif cast.startswith('p'): cislo_osoby = int(cast[1:])
        elif cast.startswith('s'):  cislo_sady = int(cast[1:])

    return cislo_slova, cislo_osoby, cislo_sady

def htk_lab_txt_soubory(nahravky, labels_dir):
    for i, nahravka_path in enumerate(nahravky):
        cislo_slova, _, _ = nahravka_info(nahravka_path)

        fpath = os.path.abspath(labels_dir + '/' + nahravka_path.split('.')[0])
        txt_fpath = fpath + '.txt'
        lab_fpath = fpath + '.lab'
        txt_content = SLOVNIK[cislo_slova].upper()
        lab_content = SIL + ENDL + SLOVNIK[cislo_slova] + ENDL + SIL
        with open(txt_fpath, 'w') as f: f.write(txt_content)
        with open(lab_fpath, 'w') as f: f.write(lab_content)

def htk_testref_soubor(nahravky, labels_dir, test_dir):

    testref_mlf = '#!MLF!#' + ENDL

    for i, nahravka_path in enumerate(nahravky):
        cislo_slova, _, _ = nahravka_info(nahravka_path)
        fpath = os.path.abspath(labels_dir + '/' + nahravka_path.split('.')[0])
        lab_fpath = fpath + '.lab'
        txt_content = SLOVNIK[cislo_slova].upper()
        mlf_lab_fpath = '\"' + lab_fpath.replace('\\', '/') + '\"'

        testref_mlf += mlf_lab_fpath + ENDL + txt_content + ENDL + '.' + ENDL

    testref_mlf_fpath = os.path.abspath(test_dir + '/testref.mlf')
    with open(testref_mlf_fpath, 'w') as file: file.write(testref_mlf)


"""
trabalho quetao 01:
"""
from ModelarNumComplexo import NumComplexo

def main ():

    a = int(input("parte real: "))
    b = int(input("parte imaginaria: "))

    complexo = NumComplexo (a, b)

    complexo.ImprimirNum()
    complexo.Equal()
    complexo.Soma()
    complexo.Subtrai()
    complexo.Multiplica()
    complexo.Divide()
    complexo.Ecomplexo()
    complexo.Nulo()

main()


# Othello Game Logic by mankaine.
#
# A module that contains the game logic for Othello (Reversi).
#
# OTHELLO OBJECTIVE
# Two players - white and black - play a game to capture the most/least amount
# of empty spaces. The decision to caputre the most/least amount is determined
# in the settings.
#
# The game begins with two discs from each player, diagonal from each other,
# in the center of the board. The columns and rows of the board is determined
# in the first and second lines of input in the shell. The first player is
# determined by the third line of input in the shell. These four discs will
# be organized according to shell user preference (fourth line of input);
# user input dictates how the player will win (fifth line).

# SETTING UP THE GAME ##########################################################
# BLACK, WHITE, represent the discs. EMPTY represents a space with no disc.
BLACK = 'B'
WHITE = 'W'
EMPTY = '.'

DEBUG = False

from collections import namedtuple
Indexes = namedtuple('Indexes', 'rows cols')
Direction = namedtuple('Direction', 'change_in_row change_in_col')

# The direxes list contains the Directions used when iterating over a list in
# update_board in order to check whether an empty space, opponent discs, and
# player discs line up.
#
# The comments explaining which each direction points to assumes that north is up.

direxes = [Direction(-1, 1),  # northeast
           Direction(-1, -1), # northwest
           Direction(-1, 0),  # north
           Direction(0, -1),  # west
           Direction(0, 1),   # east
           Direction(1, 1),   # southeast
           Direction(1, -1),  # southwest
           Direction(1, 0)]   # south

class InvalidBoardSizeEntry(Exception):
    pass

class InvalidMove(Exception):
    pass

# The GameCondition object is constructed when the game begins. It manipulates
# the GameCondition of the game and includes data, such as the current player, board
# size, and how many discs are on the board.
class GameCondition:
    def __init__(self, row_length: int, col_length: int, firstplayer: str,
                 top_leftplayer: int, win_paradigm: str):
        '''Initializes the GameCondition class. Also creates variables
        which makes references to values input in the shell, including
        number of rows and columns, the first player, the player which
        occupies the top left space in the 2 x 2 block, and
        how to win.
        '''
        self._row_length      = row_length
        self._col_length      = col_length
        self.player           = firstplayer
        self._top_leftplayer  = top_leftplayer
        self.win_paradigm     = win_paradigm

        # The next lines of input determine the first player and who occupies the
        # top left 2 x 2 block. Since the choices are restricted to Black and White,=
        # an InvalidTokenEntry error is unecessary.
        if self.player == BLACK:
            self.opponent = WHITE
        else:
            self.opponent = BLACK

        if self._top_leftplayer == BLACK:
            self._right_player = WHITE
        else:
            self._right_player = BLACK

        # The next two variables count how many tokens belong to each player.
        # They will be used to indicate who owns a majority of the board and wins the game.
        self.total_black_tokens = 0
        self.total_white_tokens = 0

        self._Direction_dist = 0

    # CREATION OF THE NEW GAME BOARD #####################################################

    # Regardless of who occupies the top left of the 2 x 2 block,
    # an empty board must be created. _create_empty_board works with
    # _configure_top_left to make the board and 2 x 2 block in
    # create_new_game_board.
    def _create_empty_board(self) -> [[str]]:
        '''Creates an empty board given the number of rows and columns
        '''
        board = []
        for ROW in range(self._row_length):
            row = []
            for COL in range(self._col_length):
                row.extend(EMPTY)
            board.append(row)
        self.board = board
        return self.board

    def _configure_top_left(self) -> [[str]]:
        '''Revises the board to include the 2 x 2 configuration, and the
        player in the top left this configuration.
        '''
        dividing_row_index = int(self._row_length / 2) - 1
        dividing_col_index = int(self._col_length / 2) - 1

        for col in range(len(self.board[dividing_row_index])):
            if col == dividing_col_index:
                self.board[dividing_row_index][col] = self._top_leftplayer
            elif col == dividing_col_index + 1:
                self.board[dividing_row_index][col] = self._right_player

        for col in range(len(self.board[dividing_row_index + 1])):
            if col == dividing_col_index:
                self.board[dividing_row_index + 1][col] = self._right_player
            elif col == dividing_col_index + 1:
                self.board[dividing_row_index + 1][col] = self._top_leftplayer

        return self.board

    def create_new_game_board(self) -> [[str]]:
        '''Creates a new game board
        '''
        self.board = self._create_empty_board()
        self.board = self._configure_top_left()
        return self.board

    # DISC COUNT and WINNER ##############################################################

    # count_discs will save to memory the total amounts of black and white tokens.
    # choose_winner will use these values to determine who wins.

    def count_discs(self) -> None:
        '''Returns the amount of discs each player has
        '''
        self.total_white_tokens = 0
        self.total_black_tokens = 0
        for row in self.board:
            for col in row:
                if col == WHITE:
                    self.total_white_tokens += 1
                elif col == BLACK:
                    self.total_black_tokens += 1

    # no_more_moves_possible comes into effect after every turn is played. It ensures
    # that the player has no more possible moves to make before determining the winner.
    #
    # no_more_moves_possible comes into effect if either the game board is filled or
    # neither player can make a valid move.

    def _opposite_player_borders(self, player: str, ind: Indexes, direx: Direction) -> bool:
        '''Returns true if one of pieces surrounding the piece is surrounded by the
        opposite player. Returns false otherwise.
        '''
        if player == WHITE:
            opposite = BLACK
        else:
            opposite = WHITE

        connect = False

        if ind.rows + direx.change_in_row < self._row_length \
        and ind.cols + direx.change_in_col < self._col_length:
            connect = self.board[ind.rows + direx.change_in_row]\
            [ind.cols + direx.change_in_col] == opposite

        return connect

    def _current_player_occupies(self, player: str, ind: Indexes, direx: Direction) -> bool:
        '''Returns True if the index and the specified player form a line.
        False otherwise.
        '''
        length = self._find_length(ind, direx)
        player_found = False

        for number in range(length):
            if self.player_occupies(Indexes(ind.rows + number * direx.change_in_row,
                                             ind.cols + number * direx.change_in_col)):
                player_found = True
                break

        return player_found

    def _create_all_indexes(self) -> [Indexes]:
        '''Returns a list of all indexes in the game board
        '''
        index_list = []
        for row_ind in range(self._row_length):
            for col_ind in range(self._col_length):
                index_list.append(Indexes(row_ind, col_ind))
        return index_list

    def future_moves_illegal(self, player: str) -> bool:
        '''Returns true if the player cannot make a legal move. False otherwise.
        '''

        # for each empty space, check if a player move can be made
        # this is done by 1. seeing the surrounding pieces are occupied by
        # the opposite player and 2. checking in those lines occupied by the player that a
        #  player piece is at the end of a line, then returning the value of that check
        # if all of those values are false - then there are no more legal moves to make and
        # the value is returned false. if one of those values are true then the method
        # return true

        legal_move_impossible = True

        index_list = self._create_all_indexes() # list of all indexes

        for indiv_index in index_list:
            if self._none_occupies(indiv_index):
                for direx in direxes:
                    list_length = self._find_length(indiv_index, direx)
                    for number in range(list_length):
                        if self._opponent_occupies(Indexes(indiv_index.rows + number * direx.change_in_row,
                                                           indiv_index.cols + number * direx.change_in_col)):
                            if 0 < indiv_index.rows + (number + 1) * direx.change_in_row < self._row_length \
                            and 0 < indiv_index.cols + (number + 1) * direx.change_in_col < self._col_length \
                            and self.player_occupies(Indexes(indiv_index.rows + (number + 1) * direx.change_in_row,
                                                             indiv_index.cols + (number + 1) * direx.change_in_col)):
                                legal_move_impossible = False
        return legal_move_impossible

    def _full_board(self) -> bool:
        '''Returns False if the board is completely filled with player and opponent discs.
        True otherwise.
        '''
        board_full = True

        for row in self.board:
            if EMPTY in row:
                board_full = False
                break

        return board_full

    def no_more_moves_possible(self) -> bool:
        '''Returns true if the game board is full of discs or neither player can
        make a valid move
        '''
        return self._full_board() \
            or (self.future_moves_illegal(self.player) and self.future_moves_illegal(self.opponent))

    def compare(self, filt: str):
        '''Returns 1 if the first player has a larger amount of discs than the
        second player. Returns 2 if the opposite is true. Returns 3 if both players
        have the same amount of discs.
        '''
        choices = {1: BLACK, 2: WHITE, 3: "NONE"}
        if filt == 'Fewer Discs':
            if self.total_white_tokens < self.total_black_tokens:
                return choices[1]
            if self.total_black_tokens < self.total_white_tokens:
                return choices[2]
            if self.total_white_tokens == self.total_black_tokens:
                return choices[3]
        else:
            if self.total_black_tokens > self.total_white_tokens:
                return choices[1]
            if self.total_white_tokens > self.total_black_tokens:
                return choices[2]
            if self.total_black_tokens == self.total_white_tokens:
                return choices[3]

    # DETERMINING THE TURN #####################################################

    # change_turn is only called on after a move is valid and the
    # entry is made on the board.
    def change_turn(self) -> str:
        '''Changes a player's turn. In doing so, the class switches the players
         and opponents.
        '''
        if self.player == WHITE:
            self.player = BLACK
            self.opponent = WHITE
        else:
            self.player = WHITE
            self.opponent = BLACK

    # MANIPULATING THE GAME BOARD ###################################################

    # For a game move to be legal, it must pass various tests. These are:
    #     1. The input corresponds to a Direction tuple within the size of the board.
    #         Managed by _input_in_board.
    #     2. The input corresponds to an empty space. Managed by _none_occupies.
    #     3. One of the surrounding spaces of the input is occupied by an opponent disc.
    #        Managed by _opponent_occupies.
    #     4. In the Direction that the opponent occupies the nearby space, the player must
    #        occupy a space i.e. the empty space, the opponent space, and the player space
    #        must form a line. Managed by player_occupies.
    #
    # the four methods _check_for_correct_input, _none_occupies,
    # _opponent_occupies, and player_occupies determines if the Indexes object
    # representing the input, adjusted for zero based indexing, is a legal move.

    def _input_in_board(self, ind: Indexes) -> bool:
        '''Returns true if the selected index is within the board
        '''
        if len(self.board) >= ind.rows + 1 and len(self.board[ind.rows]) >= ind.cols + 1:
            return True
        else:
            raise InvalidMove("The move {} {} is outside of the board, sized {} by {}"\
            .format(ind.rows + 1, ind.cols + 1, self._row_length, self._col_length))

    def _none_occupies(self, ind: Indexes) -> bool:
        '''Returns true if the selected index is an empty space
        '''
        return EMPTY == self.board[ind.rows][ind.cols]

    def _opponent_occupies(self, ind: Indexes) -> bool:
        '''Returns true if the token at the selected index is occupied by the opponent
        '''
        return self.opponent == self.board[ind.rows][ind.cols]

    def player_occupies(self, ind: Indexes) -> bool:
        '''Returns true if the token at the selected index is occupied by the player
        '''
        return self.player == self.board[ind.rows][ind.cols]

    def _create_board_copy(self) -> [[str]]:
        '''Creates a copy of the current board GameCondition
        '''
        board = []
        for ROW in range(len(self.board)):
            row = []
            for COL in range(len(self.board[ROW])):
                row.extend(self.board[ROW][COL])
            board.append(row)
        self._board_copy = board
        return self._board_copy

    # update_board_all implements in all Directions update_board. This latter method
    # determines if a Direction entry is valid. If not, it will not change any values.
    # Next, it will change the tiles of each item over a specific list, determined by
    # find_length. If there is an opponent occupation between the desired space and a player
    # tile in any Direction, the method checks if a piece in a certain Direction
    # is occupied by the player. If so, then and only then is the self.board variable
    # updated to reflect the changes.
    #
    # Because each of the Directions staring at different Direction imply that
    # update_board will check for opponent and player tokens over different types of lists,
    # find_length provides the list length given a Direction. If the board is not updated,
    # false is returned. This will be used to indicate to the player that the move he
    # just made is invalid.

    # diagonal lengths are unique in that the list they are limited by is not always the
    # same. If the length is longer than the width of the gird, then the width would limit
    # how long the diagonal line is, not the length. find_length_diagonal accounts for this
    # in its first block of code. The second block of code calculates the distance while
    # considering zero based indexing. This value will constitute the diagonal distances in
    # find_length.
    def _find_length_diagonal(self, ind: Indexes, direx: Direction) -> int:
        '''Returns the distance from the ind coordinate in the board to one if its
        edges, measured diagonally
        '''
        if self._row_length > self._col_length:
            limiting_list = self._col_length
        else:
            limiting_list = self._row_length

        distance = 0
        for number in range(limiting_list):
            if 0 <= ind.rows + number * direx.change_in_row < self._row_length \
            and 0 <= ind.cols + number * direx.change_in_col < self._col_length:
                distance += 1

        return distance

    # This method's value will be used in update_board as the length of the list to
    # consider changes of opponent discs and empty spaces.
    def _find_length(self, ind: Indexes, direx: Direction) -> int:
        '''Returns a list length based on the Directions selected.
        '''

        Directions_and_list_length = \
        {Direction(-1, 1) : self._find_length_diagonal(ind, Direction(-1, 1)),
         Direction(-1, -1): self._find_length_diagonal(ind, Direction(-1, -1)),
         Direction(-1, 0) : self._row_length - (self._row_length - ind.rows - 1),
         Direction(0, -1) : self._col_length - (self._col_length - ind.cols - 1),
         Direction(0, 1)  : self._col_length - ind.cols,
         Direction(1, 1)  : self._find_length_diagonal(ind, Direction(1, 1)),
         Direction(1, -1) : self._find_length_diagonal(ind, Direction(1, -1)),
         Direction(1, 0)  : self._row_length - ind.rows}

        return Directions_and_list_length[direx]

    def _flip_one_direction(self, ind: Indexes, direx: Direction,
                            list_length: int) -> bool:
        '''Changes the values of a game board by changing tiles of the opponent between the
        empty space at the coordinates ind to the current player in the direction specified.
        Returns True if this change occurs. False otherwise.
        '''
        changes_to_board = 0
        check_past_first  = False
        disc_flip_approved = False

        first_check_row = ind.rows + direx.change_in_row
        first_check_col = ind.cols + direx.change_in_col
        if 0 <= first_check_row < self._row_length and 0 <= first_check_col < self._col_length \
        and self._none_occupies(ind):
            if self._none_occupies(Indexes(first_check_row, first_check_col)) or \
            self.player_occupies(Indexes(first_check_row, first_check_col)):
                return False
            elif self._opponent_occupies(Indexes(first_check_row, first_check_col)):
                check_past_first = True

        if check_past_first:
            for number in range(list_length):
                new_check_row = ind.rows + (number + 1) * direx.change_in_row
                new_check_col = ind.cols + (number + 1) * direx.change_in_col
                if 0 <= new_check_row < self._row_length and 0 <= new_check_col < self._col_length:
                    if self._none_occupies(Indexes(new_check_row, new_check_col)):
                        break
                    if self._opponent_occupies(Indexes(new_check_row, new_check_col)):
                        continue
                    if self.player_occupies(Indexes(new_check_row, new_check_col)):
                        disc_flip_approved = True

        if disc_flip_approved:
            for number in range(list_length):
                row_to_flip = ind.rows + number * direx.change_in_row
                col_to_flip = ind.cols + number * direx.change_in_col
                if self._opponent_occupies(Indexes(row_to_flip, col_to_flip)):
                    self.board[row_to_flip][col_to_flip] = self.player
                    changes_to_board += 1

                elif self.player_occupies(Indexes(row_to_flip, col_to_flip)):
                    break

        if changes_to_board > 0:
            return True

    def update_board(self, ind: Indexes) -> bool:
        '''Changes the values of  a game board representing the captured spaces by the
        current player, starting from the ind Direction. If the player move is valid,
        the space corresponding to ind will be occupied by the player. Returns false
         if the move is invalid.
        '''
        changes = []

        for direx in direxes:
            list_length = self._find_length(ind, direx)
            changes.append(self._flip_one_direction(ind, direx, list_length))
            if DEBUG:
                print(changes)

        if True in changes:
            self.board[ind.rows][ind.cols] = self.player
            return True
        else:
            return False


import numpy as np
import math
from scipy import constants
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

from ClassFileWeek3 import RelativisticChargedParticle
from ClassFileWeek3 import ChargedParticle
from ClassFileWeek3 import Field
from ClassFileWeek3 import OscillatingField

electron = RelativisticChargedParticle(np.array([0,0,-10]),np.array([6.282,0,0]),np.array([0,0,0]),'electron', 9.11E-31, 9.11E-31, 1.6E-19)
MyElectricField = OscillatingField(np.array([10E-10,0,0]),0, 0)
MyMagneticField = Field(np.array([0,3.577E-11,0]))

def lorentzforce(q,e,v,b):
    force = (q*e)+(q*(np.cross(v,b)))
    return(force)

def movechargedparticlethroughEMField(chargedobject,efield,mfield,timestep,duration,radius):
    velocitydata = [[],[],[]]
    positiondata=[[],[],[]]
    speeddata = []
    t = 0
    timelist = []
    for _ in np.arange(0,duration,timestep):
        t += timestep
        #chargedobject.gammaupdate()
        #chargedobject.relativemassupdate()
        mfield.field[1] = (chargedobject.mass*np.linalg.norm(chargedobject.velocity))/(chargedobject.charge*radius)
        cyclofreq = np.linalg.norm(chargedobject.velocity)/radius
        efield.freq = cyclofreq
        efield.update(t)
        if np.linalg.norm(chargedobject.position[0]) < (0.05*2*np.pi*radius):
            chargedobject.acceleration = (lorentzforce(chargedobject.charge,efield.field,chargedobject.velocity,mfield.field))/chargedobject.mass
        else:
            chargedobject.acceleration = (lorentzforce(chargedobject.charge,0,chargedobject.velocity,mfield.field))/chargedobject.mass
        chargedobject.update(timestep)
        for i in range(0,3,1):
            positiondata[i].append(chargedobject.position[i])
            velocitydata[i].append(chargedobject.velocity[i])
        timelist.append(t)
        speeddata.append(np.linalg.norm(chargedobject.velocity))
    positiondataset = {'Time': timelist, 'xposition': positiondata[0], 'yposition': positiondata[1], 'zposition': positiondata[2]}
    velocitydataset = {'Time': timelist, 'xvelocity': velocitydata[0], 'yvelocity': velocitydata[1], 'zvelocity': velocitydata[2]}
    pdf = pd.DataFrame(data = positiondataset)
    vdf = pd.DataFrame(data = velocitydataset)
    plt.plot(vdf['Time'],speeddata)
    #fig = plt.axes(projection = '3d', xlabel = 'x', ylabel = 'y', zlabel = 'z')
    #fig.plot3D(pdf['xposition'],pdf['yposition'],pdf['zposition'])
    plt.show()

movechargedparticlethroughEMField(electron,MyElectricField,MyMagneticField,0.0001,20,10)


# plotter.py
import matplotlib.pyplot as plt
import SimpleITK as sitk
import numpy as np
import util
import registerer, preprocessor

def imgShow(img, vmin=None, vmax=None, cmap=None, alpha=None,
            newFig=True, flip=[0, 0, 0], numSlices=3, useNearest=False):
    """
    Displays an image.  Only 2D images are supported for now
    """
    if newFig:
        fig = plt.figure()

    if (vmin is None) or (vmax is None):
        stats = sitk.StatisticsImageFilter()
        stats.Execute(img)
        if vmin is None:
            vmin = stats.GetMinimum()
        if vmax is None:
            vmax = stats.GetMaximum()

    if cmap is None:
        cmap = plt.cm.gray
    if alpha is None:
        alpha = 1.0

    interpolation = ['bilinear', 'none'][useNearest]

    if img.GetDimension() == 2:
        plt.axis('off')
        ax = plt.imshow(sitk.GetArrayFromImage(img), cmap=cmap, vmin=vmin,
                        vmax=vmax, alpha=alpha, interpolation=interpolation)

    elif img.GetDimension() == 3:
        size = img.GetSize()
        for i in range(img.GetDimension()):
            start = size[2 - i] / (numSlices + 1)
            sliceList = np.linspace(start, size[2 - i] - start, numSlices)
            sliceSize = list(size)
            sliceSize[2 - i] = 0

            for (j, slice) in enumerate(sliceList):
                sliceIndex = [0] * img.GetDimension()
                sliceIndex[2 - i] = int(slice)
                sliceImg = sitk.Extract(img, sliceSize, sliceIndex)
                sliceArray = sitk.GetArrayFromImage(sliceImg)
                if flip[i]:
                    sliceArray = np.transpose(sliceArray)

                plt.subplot(numSlices, img.GetDimension(),
                            i + img.GetDimension() * j + 1)
                ax = plt.imshow(sliceArray, cmap=cmap, vmin=vmin,
                                vmax=vmax, alpha=alpha, interpolation=interpolation)
                plt.axis('off')
    else:
        raise Exception("Image dimension must be 2 or 3.")

    if newFig:
        plt.show()

def imgShowResults(inImg, refImg, field, logPath=""):
    numRows = 5
    numCols = 3
    defInImg = registerer.imgApplyField(inImg, field, size=refImg.GetSize())
    checker = imgChecker(defInImg, refImg)

    sliceList = []
    for i in range(inImg.GetDimension()):
        step = [5] * inImg.GetDimension()
        step[2 - i] = None
        grid = imgGrid(inImg.GetSize(), inImg.GetSpacing(),
                       step=step, field=field)

        sliceList.append(imgSlices(grid, flip=[0, 1, 1])[i])
    fig = plt.figure()
    imgShowResultsRow(inImg, numRows, numCols, 0, title="$I_0$")
    imgShowResultsRow(defInImg, numRows, numCols, 1,
                      title="$I_0 \circ \phi_{10}$")
    imgShowResultsRow(checker, numRows, numCols, 2,
                      title="$I_0$ and $I_1$\n Checker")
    imgShowResultsRow(refImg, numRows, numCols, 3, title="$I_1$")
    imgShowResultsRow(sliceList, numRows, numCols, 4, title="$\phi_{10}$")
    fig.subplots_adjust(hspace=0.05, wspace=0)
    plt.show()

def imgShowResultsRow(img, numRows=1, numCols=3, rowIndex=0, title=""):
    if isinstance(img, list):
        sliceImgList = img
    else:
        sliceImgList = imgSlices(img, flip=[0, 1, 1])

    for (i, sliceImg) in enumerate(sliceImgList):
        ax = plt.subplot(numRows, numCols, rowIndex * numCols + i + 1)
        plt.imshow(sitk.GetArrayFromImage(sliceImg),
                   cmap=plt.cm.gray, aspect='auto')
        ax.set_yticklabels([])
        ax.set_xticklabels([])
        if i == 0:
            plt.ylabel(title, rotation=0, labelpad=30)
        # plt.axis('off')

def imgMetamorphosisSlicePlotterRow(
        img, numRows=1, numCols=3, rowIndex=0, title="", vmin=None, vmax=None):
    if isinstance(img, list):
        sliceImgList = img
    else:
        if vmax is None or (vmin is None):
            stats = sitk.StatisticsImageFilter()
            stats.Execute(img)
            if vmin is None:
                vmin = stats.GetMinimum()
            if vmax is None:
                vmax = stats.GetMaximum()
        sliceImgList = imgSlices(img, flip=[0, 1, 1])

    for (i, sliceImg) in enumerate(sliceImgList):
        ax = plt.subplot(numRows, numCols, rowIndex * numCols + i + 1)
        plt.imshow(
            sitk.GetArrayFromImage(sliceImg),
            cmap=plt.cm.gray,
            aspect='auto',
            vmax=vmax,
            vmin=vmin)
        ax.set_yticks([])
        ax.set_xticks([])
        if i == 0:
            plt.ylabel(title, rotation=0, labelpad=40)

def imgMetamorphosisSlicePlotter(inImg, refImg, field):
    numRows = 5
    numCols = 3
    defInImg = registerer.imgApplyField(inImg, field, size=refImg.GetSize())
    inImg = registerer.imgApplyAffine(
        inImg, [
            1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0], size=refImg.GetSize())
    checker = imgChecker(defInImg, refImg)

    sliceList = []
    for i in range(inImg.GetDimension()):
        step = [20] * inImg.GetDimension()
        step[2 - i] = None
        grid = imgGrid(
            inImg.GetSize(),
            inImg.GetSpacing(),
            step=step,
            field=field)

        sliceList.append(imgSlices(grid, flip=[0, 1, 1])[i])

    imgMetamorphosisSlicePlotterRow(
        inImg,
        numRows,
        numCols,
        0,
        title="$I_0$",
        vmax=util.img_percentile(
            inImg,
            0.99))
    imgMetamorphosisSlicePlotterRow(
        defInImg,
        numRows,
        numCols,
        1,
        title="$I(1)$",
        vmax=util.img_percentile(
            defInImg,
            0.99))
    imgMetamorphosisSlicePlotterRow(
        checker,
        numRows,
        numCols,
        2,
        title="$I(1)$ and $I_1$\n Checker",
        vmax=util.img_percentile(
            checker,
            0.99))
    imgMetamorphosisSlicePlotterRow(
        refImg,
        numRows,
        numCols,
        3,
        title="$I_1$",
        vmax=util.img_percentile(
            refImg,
            0.99))
    imgMetamorphosisSlicePlotterRow(
        sliceList, numRows, numCols, 4, title="$\phi_{10}$")
    plt.gcf().subplots_adjust(hspace=0.1, wspace=0.025)

#def imgMetamorphosisLogPlotter(
#        logPathList, labelList=None, useLog=False, useTime=False):
#    if not(util.is_iterable(logPathList)):
#        raise Exception("logPathList should be a list.")
#
#    if labelList is None:
#        labelList = ["Step {0}".format(i)
#                     for i in range(1, len(logPathList) + 1)]
#    else:
#        if not(util.is_iterable(labelList)):
#            raise Exception("labelList should be a list.")
#        if len(labelList) != len(logPathList):
#            raise Exception(
#                "Number of labels should equal number of log files.")
#
#    initialPercent = 1.0
#    initialX = 0
#    levelXList = []
#    levelPercentList = []
#    for (i, logPath) in enumerate(logPathList):
#        percentList = imgMetamorphosisLogParser(logPath)[:, 1] * initialPercent
#        numIterations = len(percentList)
#        if useTime:
#            # Parse run time from log and convert to minutes
#            time = float(util.txt_read(logPath).split(
#                "Time = ")[1].split("s ")[0]) / 60.0
#            xList = np.linspace(0, time, numIterations + 1)[1:] + initialX
#        else:
#            xList = np.arange(0, numIterations) + initialX
#
#        if not useLog:
#            if i == 0:
#                xList = np.array([initialX] + list(xList))
#                percentList = np.array([initialPercent] + list(percentList))
#
#        levelXList += [xList]
#        levelPercentList += [percentList]
#
#        initialPercent = percentList[-1]
#        initialX = xList[-1]
#
#    for i in range(len(levelXList)):
#        if i > 0:
#            xList = np.concatenate((levelXList[i - 1][-1:], levelXList[i]))
#            percentList = np.concatenate(
#                (levelPercentList[i - 1][-1:], levelPercentList[i]))
#
#        else:
#            xList = levelXList[i]
#            percentList = levelPercentList[i]
#
#        plt.plot(xList, percentList, label=labelList[i], linewidth=1.5)
#
#    # Add plot annotations
#    if useTime:
#        plt.xlabel("Time (Minutes)")
#    else:
#        plt.xlabel("Iteration")
#
#    plt.ylabel("Normalized $M(I(1), I_1)$")
#    plt.legend(loc="center left", bbox_to_anchor=(1, 0.5))
#    if useLog:
#        plt.xscale("log")
#    ax = plt.gca()
##    ax.xaxis.set_major_formatter(ScalarFormatter())
#    plt.autoscale(enable=True, axis='x', tight=True)
#
#    # Fix maximum y to 1.0
#    ylim = list(ax.get_ylim())
#    ylim[1] = 1.0
#    ax.set_ylim(ylim)

def imgChecker(inImg, refImg, useHM=True, pattern=None):

    """
    Checkerboards input image with reference image
    """
    inImg = sitk.Cast(inImg, refImg.GetPixelID())
    inSize = list(inImg.GetSize())
    refSize = list(refImg.GetSize())
    if pattern is None: pattern = [4]*inImg.GetDimension()

    if(inSize != refSize):
        sourceSize = np.array([inSize, refSize]).min(0)
        # Empty image with same size as reference image
        tmpImg = sitk.Image(refSize, refImg.GetPixelID())
        tmpImg.CopyInformation(refImg)
        inImg = sitk.Paste(tmpImg, inImg, sourceSize)

    if useHM:
        inImg = preprocessor.imgHM(inImg, refImg)

    return sitk.CheckerBoardImageFilter().Execute(inImg, refImg, pattern)

def imgSlices(img, flip=[0, 0, 0], numSlices=1):
    size = img.GetSize()
    sliceImgList = []
    for i in range(img.GetDimension()):
        start = size[2 - i] / (numSlices + 1)
        sliceList = np.linspace(start, size[2 - i] - start, numSlices)
        sliceSize = list(size)
        sliceSize[2 - i] = 0

        for (j, slice) in enumerate(sliceList):
            sliceIndex = [0] * img.GetDimension()
            sliceIndex[2 - i] = int(slice)
            sliceImg = sitk.Extract(img, sliceSize, sliceIndex)

            if flip[i]:
                sliceImgDirection = sliceImg.GetDirection()
                sliceImg = sitk.PermuteAxesImageFilter().Execute(
                    sliceImg, range(sliceImg.GetDimension() - 1, -1, -1))
                sliceImg.SetDirection(sliceImgDirection)
            sliceImgList.append(sliceImg)

    return sliceImgList

def imgGrid(size, spacing, step=[10, 10, 10], field=None):
    """
    Creates a grid image using with specified size and spacing with distance between lines defined by step.
    If step is None along a dimention no grid lines will be plotted.
    For example step=[5,5,None] will result in a grid image with grid lines every 5 voxels in the x and y directions but no grid lines in the z direction.
    An optinal displacement field can be applied to the grid as well.
    """

    if not(util.is_iterable(size)):
        raise Exception("size must be a list.")
    if not(util.is_iterable(spacing)):
        raise Exception("spacing must be a list.")
    if not(util.is_iterable(step)):
        raise Exception("step must be a list.")
    if len(size) != len(spacing):
        raise Exception("len(size) != len(spacing)")
    if len(size) != len(step):
        raise Exception("len(size) != len(step)")

    dimension = len(size)
    offset = [0] * dimension

    for i in range(dimension):
        if step[i] is None:
            step[i] = size[i] + 2
            offset[i] = -1

    gridSource = sitk.GridImageSource()
    gridSource.SetSpacing(spacing)
    gridSource.SetGridOffset(np.array(offset) * np.array(spacing))
    gridSource.SetOrigin([0] * dimension)
    gridSource.SetSize(np.array(size))
    gridSource.SetGridSpacing(np.array(step) * np.array(spacing))
    gridSource.SetScale(255)
    gridSource.SetSigma(1 * np.array(spacing))
    grid = gridSource.Execute()

    if not(field is None):
        grid = sitk.WrapPad(grid, [20] * dimension, [20] * dimension)
        grid = registerer.imgApplyField(grid, field, size=size)

    return grid

# Callback invoked by the interact IPython method for scrolling through the image stacks of
# the two images (moving and fixed).
def display_images(fixed_image_z, moving_image_z, fixed_npa, moving_npa):
    # Create a figure with two subplots and the specified size.
    plt.subplots(1,2,figsize=(10,8))

    # Draw the fixed image in the first subplot.
    plt.subplot(1,2,1)
    plt.imshow(fixed_npa[fixed_image_z,:,:],cmap=plt.cm.Greys)
    plt.title('fixed image')
    plt.axis('off')

    # Draw the moving image in the second subplot.
    plt.subplot(1,2,2)
    plt.imshow(moving_npa[moving_image_z,:,:],cmap=plt.cm.Greys)
    plt.title('moving image')
    plt.axis('off')

    plt.show()

# Callback invoked by the IPython interact method for scrolling and modifying the alpha blending
# of an image stack of two images that occupy the same physical space.
from ipywidgets import interact, fixed
from IPython.display import clear_output

def display_slices_with_alpha(fixed, moving, alpha, vmax):
    img = (1.0 - alpha)*fixed + alpha*moving
    plt.imshow(sitk.GetArrayViewFromImage(img),cmap=plt.cm.Greys, vmax=vmax)
    plt.axis('off')
    plt.show()

def display_images_with_alpha(slice_num, alpha, fixed, moving, axis=2, vmax=1000):
    if axis == 0: display_slices_with_alpha(fixed[slice_num,:,:], moving[slice_num,:,:], alpha, vmax)
    elif axis == 1: display_slices_with_alpha(fixed[:,slice_num,:], moving[:,slice_num,:], alpha, vmax)
    else: display_slices_with_alpha(fixed[:,:,slice_num], moving[:,:,slice_num], alpha, vmax)

# Callback invoked when the StartEvent happens, sets up our new data.
def start_plot():
    global metric_values, multires_iterations

    metric_values = []
    multires_iterations = []

# Callback invoked when the EndEvent happens, do cleanup of data and figure.
def end_plot():
    global metric_values, multires_iterations

    del metric_values
    del multires_iterations
    # Close figure, we don't want to get a duplicate of the plot latter on.
    plt.close()

# Callback invoked when the IterationEvent happens, update our data and display new figure.
def plot_values(registration_method):
    global metric_values, multires_iterations

    metric_values.append(registration_method.GetMetricValue())
    # Clear the output area (wait=True, to reduce flickering), and plot current data
    clear_output(wait=True)
    # Plot the similarity metric values
    plt.plot(metric_values, 'r')
    plt.plot(multires_iterations, [metric_values[index] for index in multires_iterations], 'b*')
    plt.xlabel('Iteration Number',fontsize=12)
    plt.ylabel('Metric Value',fontsize=12)
    plt.show()

# Callback invoked when the sitkMultiResolutionIterationEvent happens, update the index into the
# metric_values list.
def update_multires_iterations():
    global metric_values, multires_iterations
    multires_iterations.append(len(metric_values))

def imgMetamorphosisLogParser(logPath):
    logText = util.txt_read(logPath)
    lineList = logText.split("\n")

    for (lineIndex, line) in enumerate(lineList):
        if "E, E_velocity, E_rate, E_image" in line:
            break

    dataArray = np.empty((0, 5), float)
    for line in lineList[lineIndex:]:
        if "E =" in line:
            break

        try:
            (iterationString, dataString) = line.split(".\t")
        except BaseException:
            continue

        (energyString, velocityEnergyString, rateEnergyString,
         imageEnergyString, learningRateString) = (dataString.split(","))
        (energy, velocityEnergy, rateEnergy, learningRate) = map(float, [
            energyString, velocityEnergyString, rateEnergyString, learningRateString])
        (imageEnergy, imageEnergyPercent) = map(
            float, imageEnergyString.replace("(", "").replace("%)", "").split())

        imageEnergy = float(imageEnergyString.split(" (")[0])
        dataRow = np.array(
            [[energy, imageEnergyPercent / 100, velocityEnergy, learningRate, rateEnergy]])
        dataArray = np.concatenate((dataArray, dataRow), axis=0)

    return dataArray


n = int(input())
memo = [{} for i in range(n+1)]
mod = 10**9+7
#想定解法の写経
def ok(last4):
    #隣接する二つを入れ替えてAGC二ならないかどうかをチェック
    for i in range(4):
        t = list(last4)
        if i >= 1:
            t[i], t[i-1] = t[i-1], t[i]
        if "".join(t).count('AGC') >= 1:
            return False
    return True
def dfs(now, last3):
    if last3 in memo[now]:
        return memo[now][last3]
    if now == n:
        return 1
    ret = 0
    for i in 'AGCT':
        #もし、次の一文字を足した4文字がずらしてAGCに引っかからなければ
        if ok(last3 + i):
            #今回をiにした場合のこの後の文字列の数を全て計算
            ret = (ret + dfs(now+1, last3[1:] + i)) % mod
    memo[now][last3] = ret
    return ret
print(dfs(0,'TTT'))


import sys
import time
import random
from sync_utils import Thread, Semaphore, watch

NUM_LEADERS = 0
NUM_FOLLOWERS = 0

LEADERS_QUEUE = Semaphore(0)
FOLLOWERS_QUEUE = Semaphore(0)
MUTEX = Semaphore(1)
RENDEZVOUS = Semaphore(0)

def print_queue():
    global NUM_LEADERS
    global NUM_FOLLOWERS
    sys.stdout.write("\tL: {} F: {}\n".format(NUM_LEADERS, NUM_FOLLOWERS))

def leader():
    global NUM_LEADERS
    global NUM_FOLLOWERS

    MUTEX.acquire()
    sys.stdout.write("Leader arrived.")
    if NUM_FOLLOWERS:
        NUM_FOLLOWERS -= 1
        sys.stdout.write(" Pair passes.")
        print_queue()
        FOLLOWERS_QUEUE.signal()
    else:
        NUM_LEADERS += 1
        sys.stdout.write(" Waiting.")
        print_queue()
        MUTEX.release()
        LEADERS_QUEUE.wait()

    sys.stdout.write("Leader dances.\n")
    RENDEZVOUS.wait()
    MUTEX.release()

def follower():
    global NUM_LEADERS
    global NUM_FOLLOWERS

    MUTEX.acquire()
    sys.stdout.write("Follower arrived.")
    if NUM_LEADERS:
        NUM_LEADERS -= 1
        sys.stdout.write(" Pair passes.")
        print_queue()
        LEADERS_QUEUE.signal()
    else:
        NUM_FOLLOWERS += 1
        sys.stdout.write(" Waiting.")
        print_queue()
        MUTEX.release()
        FOLLOWERS_QUEUE.wait()

    sys.stdout.write("Follower dances.\n")
    RENDEZVOUS.signal()

def main():
    while True:
        time.sleep(0.25)
        person = leader if random.randint(0, 1) else follower
        Thread(person)

watch(main)


# declare function
def printTree(fTreeHeight):

    # declare variables
    treeHeight = fTreeHeight
    line = 1
    columnCounter = 1
    asterix = "*"
    space = " "
    numOfSpaces = treeHeight - 1
    numOfAsterixes = 1

    # assign passed value
    treeHeight = fTreeHeight

    # header
    print("Chistmas Tree assignment")

    # declare row loop
    for line in range(treeHeight):

        # declare column loop for adding spaces
        for columnCounter in range(numOfSpaces):
            print(space, end="")

        columnCounter = 1

        # declare column loop for adding asterixes
        for columnCounter in range(numOfAsterixes):
            print(asterix, end="")

        # after everything is printed in the line, set amount of spaces and asterixes for the next line
        if numOfSpaces != 0:
            numOfSpaces -= 1
            numOfAsterixes += 2

        # and add the new line
        print()

# run program
userInput = int(input("Type in the height of the tree: "))
printTree(userInput)


def next(number):
    if number %2 == 0:
        return number/2
    else:
        return number*3 + 1

def chainLength(number):
    count = 1
    currentVal = number
    while currentVal > 1:
        currentVal = next(currentVal)
        count += 1
    return count

maxNumber = 0
maxLength = 0

for x in range(1000000, 1, -1):
    length = chainLength(x)
    if length > maxLength:
        maxLength = length
        maxNumber = x

print(maxNumber, " ", maxLength)


# import the necessary packages
import argparse
import cv2

refPt = []
cropping = False

def click_and_crop(event, x, y, flags, param):
    global refPt, cropping

    if event == cv2.EVENT_LBUTTONDOWN:
        refPt = [(x, y)]
        cropping = True

    # check to see if the left mouse button was released
    elif event == cv2.EVENT_LBUTTONUP:
        # record the ending (x, y) coordinates and indicate that           # the cropping operation is finished
        refPt.append((x, y))
        cropping = False

        # draw a rectangle around the region of interest
        cv2.rectangle(image, refPt[0], refPt[1], (0, 255, 0), 2)

        file.write('{},{},{},{}\n'.format(refPt[0][0],refPt[0][1], refPt[1][0]- refPt[0][0], refPt[1][1] - refPt[0][1] ))

        print('{},{}'.format(refPt[0],refPt[1])) #refPt[1][0]- refPt[0][0], refPt[1][1] - refPt[0][1]))

        cv2.imshow("image", image)

# construct the argument parser and parse the arguments
#ap = argparse.ArgumentParser()
#ap.add_argument("-i", "--image", required=True, help="Path to the image")
#args = vars(ap.parse_args())

file = open('./groundtruth.txt', 'w+')

# load the image, clone it, and setup the mouse callback function
for i in range(1,20):
    cv2.namedWindow("image")
    image = cv2.imread('./%04d.jpg'%i)
    print('./%04d.jpg'%i)
  #  clone = image.copy()

    cv2.setMouseCallback("image", click_and_crop)

    while True:
        cv2.imshow("image", image)
        key = cv2.waitKey(1) & 0xFF

    # if the 'r' key is pressed, reset the cropping region
        if key == ord("r"):
            image = clone.copy()

    # if the 'c' key is pressed, break from the loop
        elif key == ord("c"):
            break
    next_key = cv2.waitKey(1) & 0xFF
    if next_key == ord('q'):
        break
    else:
        cv2.destroyAllWindows()
        continue

      #  if len(refPt) == 2:
        #    roi = clone[refPt[0][1]:refPt[1][1], refPt[0][0]:refPt[1][0]]
        #    cv2.imshow("ROI", roi)
        #    cv2.waitKey(0)

file.close()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import pywikibot, re, sys, argparse

import blib
from blib import getparam, rmparam, tname, msg, errmsg, site

import lalib

parser = blib.create_argparser("Fix old-style verb declarations in latin-macrons.txt")
parser.add_argument("--direcfile", help="List of directives to process.",
    required=True)
args = parser.parse_args()
start, end = blib.parse_start_end(args.start, args.end)

for lineno, line in blib.iter_items_from_file(args.direcfile, start, end):
  def err(text):
    errmsg("Line %s: %s" % (lineno, text))
  # break off transitive/intransitive notation after verbs
  m = re.search(r"^(.*?)((?: *\[.*\])?)$", line)
  parttext, transtext = m.groups()
  parts = parttext.split(" ")
  if parts[0] in ["adv", "num", "phr", "prep", "prov"] or re.search(r"^(n|pn|a|num|part|v)([1-5]|irreg)?\+?$", parts[0]):
    msg(line)
    continue

  if len(parts) != 3 and len(parts) != 4:
    err("Bad line: %s" % line)
    continue
  if len(parts) == 3:
    # deponent
    lemma, inf, supine = parts
    if supine == "--":
      supine = None
    else:
      supines = supine.split("/")
      supine_bases = []
      must_continue = False
      for sup in supines:
        if not sup.endswith("um"):
          err("Bad supine %s: %s" % (sup, line))
          must_continue = True
          continue
        supine_bases.append(sup[:-2])
      if must_continue:
        continue
      supine = "/".join(supine_bases)
    if lemma.endswith("ior") and lemma[:-3] + "ī" == inf:
      vtype = "v3"
    elif lemma.endswith("ior") and lemma[:-3] + "īrī" == inf:
      vtype = "v4"
    elif lemma.endswith("eor") and lemma[:-3] + "ērī" == inf:
      vtype = "v2"
    elif lemma.endswith("or") and lemma[:-2] + "ī" == inf:
      vtype = "v3"
    elif lemma.endswith("or") and lemma[:-2] + "ārī" == inf:
      vtype = "v1"
    else:
      err("Unrecognized infinitive %s for lemma %s: %s" % (inf, lemma, line))
      continue
    if supine:
      msg("%s %s %s%s" % (vtype, lemma, supine, transtext))
    else:
      msg("%s %s%s" % (vtype, lemma, transtext))
  else:
    lemma, inf, perfect, supine = parts
    if supine == "--":
      supine = None
    else:
      supines = supine.split("/")
      supine_bases = []
      must_continue = False
      for sup in supines:
        if not sup.endswith("um"):
          err("Bad supine %s: %s" % (sup, line))
          must_continue = True
          continue
        supine_bases.append(sup[:-2])
      if must_continue:
        continue
      supine = "/".join(supine_bases)
    if perfect == "--":
      perfect = ""
    else:
      perfects = perfect.split("/")
      perfect_bases = []
      must_continue = False
      for perf in perfects:
        if perf.endswith("ī"):
          perfect_bases.append(perf[:-1])
        elif perf.endswith("it"):
          perfect_bases.append(perf[:-2])
        else:
          err("Bad perfect %s: %s" % (perf, line))
          must_continue = True
          continue
      if must_continue:
        continue
      perfect = "/".join(perfect_bases)
    if lemma.endswith("iō") and lemma[:-2] + "ere" == inf:
      vtype = "v3"
    elif lemma.endswith("iō") and lemma[:-2] + "īre" == inf:
      vtype = "v4"
    elif lemma.endswith("eō") and lemma[:-2] + "ēre" == inf:
      vtype = "v2"
    elif lemma.endswith("ō") and lemma[:-1] + "ere" == inf:
      vtype = "v3"
    elif lemma.endswith("ō") and lemma[:-1] + "āre" == inf:
      vtype = "v1"
    else:
      err("Unrecognized infinitive %s for lemma %s: %s" % (inf, lemma, line))
      continue
    if not perfect and not supine:
      msg("%s %s%s" % (vtype, lemma, transtext))
    elif not supine:
      msg("%s %s %s%s" % (vtype, lemma, perfect, transtext))
    elif not perfect:
      msg("%s %s -- %s%s" % (vtype, lemma, supine, transtext))
    else:
      msg("%s %s %s %s%s" % (vtype, lemma, perfect, supine, transtext))


with open('Test_results.txt') as file:
    counter = 0
    marks_sum = 0
    while True:
        line = file.readline()
        if line:
            mark = int(line.split()[-1])
            marks_sum += mark
            counter += 1
            if mark < 3:
                print(line, end = '')
        else:
            break
    print(marks_sum / counter)