text:
import numpy as np
import pandas as pd
from copy import copy, deepcopy
from matplotlib import pyplot as plt
from datetime import datetime, timedelta, date, time
from matplotlib.backends.backend_pdf import PdfPages
from  sklearn.linear_model import ElasticNet
model = ElasticNet()

df = pd.read_csv('../data/interim/roseg_measurements.csv', parse_dates=['time'])
del df['doy']
df['delta_time'] = (df['time']-df['time'].shift()).fillna(0)
df['delta_height'] = (df['height']-df['height'].shift()).fillna(0)
df['growth_rate'] = (df['delta_height']*100)/(df['delta_time'].apply(lambda x: x.total_seconds()/3600))
# mask=(df['growth_rate']>0) & (df['water']==0)
# df.loc[mask,'growth_rate']=0

dfdays = df[(df['delta_time']<timedelta(hours=18))
            & (df['water']==0)
            & (df['delta_time']>timedelta(hours=0))
            & ((df.time.apply(lambda x: x.time())>time(12))==True)]

dfnights= df[(df['delta_time']<timedelta(hours=18))
              & (df['water']==0)
              & (df['delta_time']>timedelta(hours=0))
              & ((df.time.apply(lambda x: x.time())<time(12))==True)]

dfdaysw = df[(df['delta_time']<timedelta(hours=18))
            & (df['water']==1)
            & (df['delta_time']>timedelta(hours=0))
            & ((df.time.apply(lambda x: x.time())>time(12))==True)]

dfnightsw = df[(df['delta_time']<timedelta(hours=18))
              & (df['water']==1)
              & (df['delta_time']>timedelta(hours=0))
              & ((df.time.apply(lambda x: x.time())<time(12))==True)]

pp = PdfPages('../data/processed/plots2.pdf')
fig=plt.figure(figsize=(14,6))
ax=fig.add_subplot(1,2,1)
dfnights.plot(x='temp', y='growth_rate', kind='scatter', title='Night freeze', ax=ax);
# add regression line
plt.plot(dfnights['temp'], np.poly1d(np.polyfit(dfnights['temp'], dfnights['growth_rate'], 1))(dfnights['temp']),
         color='r')
ax.set_xlabel('Temperature [C]')
ax.set_ylabel('Growth rate [cm/hour]')
ax=fig.add_subplot(1,2,2)
dfdays.plot(x='temp', y='growth_rate', kind='scatter', title='Day melt', ax=ax);
plt.plot(dfdays['temp'], np.poly1d(np.polyfit(dfdays['temp'], dfdays['growth_rate'], 1))(dfdays['temp']),
         color='r')
ax.set_xlabel('Temperature [C]')
ax.set_ylabel('Growth rate [cm/hour]')
fig.tight_layout()
pp.savefig()
plt.clf()

fig=plt.figure(figsize=(14,6))
ax=fig.add_subplot(1,2,1)
dfnightsw.plot(x='temp', y='growth_rate', kind='scatter', title='Night freeze', ax=ax);
# add regression line
plt.plot(dfnights['temp'], np.poly1d(np.polyfit(dfnights['temp'], dfnights['growth_rate'], 1))(dfnights['temp']),
         color='r')
ax.set_xlabel('Temperature [C]')
ax.set_ylabel('Growth rate [cm/hour]')
ax=fig.add_subplot(1,2,2)
dfdaysw.plot(x='temp', y='growth_rate', kind='scatter', title='Day melt', ax=ax);
plt.plot(dfdays['temp'], np.poly1d(np.polyfit(dfdays['temp'], dfdays['growth_rate'], 1))(dfdays['temp']),
         color='r')
ax.set_xlabel('Temperature [C]')
ax.set_ylabel('Growth rate [cm/hour]')
fig.tight_layout()
pp.savefig()
plt.clf()

dfb = pd.read_csv('../data/interim/roseg_data.csv', parse_dates=['time'])
dfb.set_index('time', inplace=True)

df = df[['time', 'height', 'growth_rate','water']].copy()

df=df.round(3)
df.to_csv('../data/processed/roseg_results.csv')

df['temp_12h_avg'] = df['time'].apply(lambda x: dfb[(dfb.index<=x) & (dfb.index>=(x-timedelta(hours=12)))]['temp'].mean())
df['temp_12h_count'] = df['time'].apply(lambda x: dfb[(dfb.index<=x) & (dfb.index>=(x-timedelta(hours=12)))]['temp'].count())

df['rh_12h_avg'] = df['time'].apply(lambda x: dfb[(dfb.index<=x) & (dfb.index>=(x-timedelta(hours=12)))]['rh'].mean())
df['rh_12h_count'] = df['time'].apply(lambda x: dfb[(dfb.index<=x) & (dfb.index>=(x-timedelta(hours=12)))]['rh'].count())

df['ws_12h_avg'] = df['time'].apply(lambda x: dfb[(dfb.index<=x) & (dfb.index>=(x-timedelta(hours=12)))]['ws'].mean())
df['ws_12h_count'] = df['time'].apply(lambda x: dfb[(dfb.index<=x) & (dfb.index>=(x-timedelta(hours=12)))]['ws'].count())

df = df[(df[[col for col in df.columns if col.endswith('count')]]>=5).all(axis='columns')]
df = df[[col for col in df.columns if not col.endswith('count')]]

df['type'] = df['time'].apply(lambda x: 'AM' if x.time()<time(12) else 'PM')
df.dropna(inplace=True)

var_dict = {'temp_12h_avg': 'Average temperature over previous 12 hours [C]',
            'rh_12h_avg': 'Average relative humidity over previous 12 hours [%]',
            'ws_12h_avg': 'Average wind speed over previous 12 hours'}
for var in var_dict:
    fig=plt.figure(figsize=(12,8))
    ax=fig.add_subplot(1,1,1)
    for mtype in [('AM', 'Night growth', 'b'), ('PM', 'Day melt', 'r')]:
        dftmp = df[(df['type']==mtype[0])&(df['water']==1)]
        dftmp.plot(x=var, y='growth_rate', kind='scatter', ax=ax, label=mtype[1], color=mtype[2])
        plt.plot(dftmp[var], np.poly1d(np.polyfit(dftmp[var], dftmp['growth_rate'], 1))(dftmp[var]),
                 color=mtype[2])
    plt.grid()
    ax.set_xlabel(var_dict[var])
    ax.set_ylabel('Growth rate [cm/hour]')
    pp.savefig()
    plt.clf()

#df=df[df['water']==1]
print(df['growth_rate'].max())

print('%d morning measurements' % len(df[df['type']=='AM']))
print('%d evening measurements' % len(df[df['type']=='PM']))

df['temp_12h_min'] = df['time'].apply(lambda x: dfb[(dfb.index<=x) & (dfb.index>=(x-timedelta(hours=12)))]['temp'].min())
df['temp_12h_max'] = df['time'].apply(lambda x: dfb[(dfb.index<=x) & (dfb.index>=(x-timedelta(hours=12)))]['temp'].max())
df['temp_12h_std'] = df['time'].apply(lambda x: dfb[(dfb.index<=x) & (dfb.index>=(x-timedelta(hours=12)))]['temp'].std())

df['rh_12h_min'] = df['time'].apply(lambda x: dfb[(dfb.index<=x) & (dfb.index>=(x-timedelta(hours=12)))]['rh'].min())
df['rh_12h_max'] = df['time'].apply(lambda x: dfb[(dfb.index<=x) & (dfb.index>=(x-timedelta(hours=12)))]['rh'].max())
df['rh_12h_std'] = df['time'].apply(lambda x: dfb[(dfb.index<=x) & (dfb.index>=(x-timedelta(hours=12)))]['rh'].std())

df['ws_12h_min'] = df['time'].apply(lambda x: dfb[(dfb.index<=x) & (dfb.index>=(x-timedelta(hours=12)))]['ws'].min())
df['ws_12h_max'] = df['time'].apply(lambda x: dfb[(dfb.index<=x) & (dfb.index>=(x-timedelta(hours=12)))]['ws'].max())
df['ws_12h_std'] = df['time'].apply(lambda x: dfb[(dfb.index<=x) & (dfb.index>=(x-timedelta(hours=12)))]['ws'].std())

model_am = ElasticNet()
model_pm = ElasticNet()
X_am = df[df['type']=='AM'][[col for col in df.columns if (col.startswith('temp')
                                                           or col.startswith('rh')
                                                           or col.startswith('ws')
                                                          )]]
y_am = df[df['type']=='AM']['growth_rate']
model_am.fit(X_am,y_am)
print('Morning observations: R-squared = %0.2f' % model_am.score(X_am,y_am))

X_pm = -df[df['type']=='PM'][[col for col in df.columns if (col.startswith('temp')
                                                            or col.startswith('rh')
                                                            or col.startswith('ws')
                                                           )]]
y_pm = df[df['type']=='PM']['growth_rate']
model_pm.fit(X_pm,y_pm)
print('Evening observations: R-squared = %0.2f' % model_pm.score(X_pm,y_pm))

fig=plt.figure(figsize=(16,8))

# getting unzipped lists of feature names and corresponding coefficients, sorted by absolute decreasing coefficient
features_am, weights_am = zip(*sorted(zip(X_am.columns, model_am.coef_), key=lambda x: abs(x[1]), reverse=True))
features_pm, weights_pm = zip(*sorted(zip(X_pm.columns, model_pm.coef_), key=lambda x: abs(x[1]), reverse=True))

ax=fig.add_subplot(1,2,1)
plt.bar(range(len(weights_am)), weights_am)
ax.set_ylabel('Coefficient in linear regression')
plt.xticks([x+0.5 for x in range(len(weights_am))], features_am, rotation='vertical')
ax.set_title('Night freeze ($R^2=%0.2f$)' % model_am.score(X_am,y_am), {'fontsize': 14, 'fontweight' : 'bold'})

ax=fig.add_subplot(1,2,2)
plt.bar(range(len(weights_pm)), weights_pm)
ax.set_ylabel('Coefficient in linear regression')
plt.xticks([x+0.5 for x in range(len(weights_pm))], features_pm, rotation='vertical')
ax.set_title('Day melt ($R^2=%0.2f$)' % model_pm.score(X_pm,y_pm), {'fontsize': 14, 'fontweight' : 'bold'})

plt.tight_layout()
pp.savefig()
plt.clf()
pp.close()


text:
"""
This script loads the datasets
"""
import h5py
import hdf5storage
import numpy as np

PROCESSED_SUMME = '../../data/SumMe/processed/eccv16_dataset_summe_google_pool5.h5'
PROCESSED_TVSUM = '../../data/TVSUM/processed/eccv16_dataset_tvsum_google_pool5.h5'
TVSUM_MAT = '../../data/TVSUM/data/ydata-tvsum50.mat'

def load_tvsum_mat(filename=TVSUM_MAT):
    data = hdf5storage.loadmat(filename, variable_names=['tvsum50'])
    data = data['tvsum50'].ravel()

    data_list = []
    for item in data:
        video, _, _, _, _, user_anno, _ = item

        item_dict = {
            'video': video[0, 0],
            'user_anno': user_anno,
        }
        data_list.append(item_dict)

    return data_list

def binarize_scores(user_anno):
    median_vals = np.mean(user_anno, axis=0)
    for i, anno in enumerate(user_anno):
        for j in range(len(anno)):
            if anno[j] >= median_vals[j]:
                anno[j] = int(1)
            else:
                anno[j] = int(0)

    return user_anno

def load_processed_dataset(processed_dataset=PROCESSED_SUMME, type='summe', binarize=False):
    tvsum_mat = load_tvsum_mat(TVSUM_MAT) if type == 'tvsum' else None

    with h5py.File(processed_dataset, 'r') as hdf:
        data_list = dict()
        for video_name in hdf.keys():
            video_idx = video_name[6:]
            element = 'video_' + video_idx
            nframes = np.array(hdf.get(element + '/n_frames'))
            picks = np.array(hdf.get(element + '/picks'))
            change_points = np.array(hdf.get(element + '/change_points'))
            gt_score = np.array(hdf.get(element + '/gtsummary'))

            if type == 'tvsum':
                user_score = tvsum_mat[int(video_idx) - 1]['user_anno'].T
                if binarize:
                    print('binarize')
                    user_score = np.array(hdf.get(element + '/user_summary'))
            else:
                user_score = np.array(hdf.get(element + '/user_summary'))

            item_dict = {
                'n_frames': nframes,
                'user_summary': user_score,
                'picks': picks,
                'change_points': change_points,
                'gt_score': gt_score,
            }

            data_list[element] = item_dict

    hdf.close()
    return data_list

ext: py

reason: import numpy


text:
import streamlit as st
import pandas as pd
import numpy as np

from .shared_functions import documentation, breakline

def display_page(my_title):
    """Creates the custom content of a page.

    args:
    - my_title: string with the title for the page.
    """
    st.title(my_title)
    # Write
    with st.beta_expander("Write general variables"):
        with st.echo('below'):
            st.write("This is a \n string") # Strings
        breakline()
        with st.echo('below'):
            st.write(42) # Integers
        breakline()
        with st.echo('below'):
            st.write(3.141592) # Floats
        breakline()
        with st.echo('below'):
            st.write({1,1,2,3,3}) # Sets
        breakline()
        with st.echo('below'):
            st.write([1,1,2,3,3]) # Lists
        breakline()
        with st.echo('below'):
            st.write({"one":3, "two":2, "three":5}) # Dicts
        breakline()
        with st.echo('below'):
            st.write(42, 3.14, {2, 3}, [1,2,3,4,5], {1:"1", 2:"2", 3:"3"}) # Several arguments
        breakline()
        with st.echo('below'):
            my_variable = [42, 3.14, {2, 3}, [1,2,3,4,5], {1:"1", 2:"2", 3:"3"}]
            st.write(my_variable) # General variables
        documentation("write")
    with st.beta_expander("Dataframes"):
        with st.echo('below'):
            st.dataframe(pd.DataFrame(data={'col1': [1, 2, 3], 'col2': [3.5, 4.5, 5.5]}))
        documentation("dataframe")
    # Table
    with st.beta_expander("Tables"):
        with st.echo('below'):
            st.table([[1,2,3],[2,3,4]])
    # Json
    with st.beta_expander("JSON"):
        with st.echo('below'):
            st.json({'foo':'bar','fu':'ba'})


text:
import argparse
import pandas as pd
import csv
import numpy as np
import json
import keras
import sys
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.layers.normalization import BatchNormalization
from keras.optimizers import SGD, Adam
from sklearn.cross_validation import StratifiedShuffleSplit
from sklearn.grid_search import ParameterGrid
from pria_lifechem.function import *
from pria_lifechem.evaluation import *
from pria_lifechem.models.CallBacks import *
from pria_lifechem.models.deep_classification import *
from pria_lifechem.models.deep_regression import *
from pria_lifechem.models.vanilla_lstm import *

def get_hyperparameter_sets(model):
    if model == 'single_classification':
        hyperparameter_sets = {'optimizer': ['adam'],
                               'learning rate': [0.00003, 0.0001, 0.003],
                               'weighted schema': ['no_weight', 'weighted_sample'],
                               'epoch patience': [{'epoch_size': 200, 'patience': 50},
                                                  {'epoch_size': 1000, 'patience': 200}],
                               'early stopping': ['auc', 'precision'],
                               'activations': [{0: 'relu', 1: 'sigmoid', 2: 'sigmoid'},
                                               {0: 'relu', 1: 'relu', 2: 'sigmoid'}]}
    elif model == 'single_regression':
        hyperparameter_sets = {'optimizer': ['adam'],
                               'learning rate': [0.00003, 0.0001, 0.003],
                               'weighted schema': ['no_weight'],
                               'epoch size': [200, 1000],
                               'activations': [{0: 'sigmoid', 1: 'sigmoid', 2: 'linear'},
                                               {0: 'relu', 1: 'sigmoid', 2: 'sigmoid'}]}
    elif model == 'vanilla_lstm':
        hyperparameter_sets = {'optimizer': ['rmsprop'],
                               'epoch patience': [{'epoch_size': 200, 'patience': 50}],
                               'early stopping': ['auc'],
                               'embedding_size': [30, 50, 100],
                               'hidden_size': [
                                   [50],
                                   [100],
                                   [100, 10],
                                   [100, 50],
                                   [50, 10]
                               ],
                               'dropout': [0.2, 0.5]}
    elif model == 'multi_classification':
        hyperparameter_sets = {'optimizer': ['adam'],
                               'learning rate': [0.00003, 0.0001, 0.003],
                               'weighted schema': ['no_weight', 'weighted_sample'],
                               'epoch patience': [{'epoch_size': 200, 'patience': 50},
                                                  {'epoch_size': 1000, 'patience': 200}],
                               'early stopping': ['precision'],
                               'activations': [{0: 'relu', 1: 'sigmoid', 2: 'sigmoid'},
                                               {0: 'relu', 1: 'relu', 2: 'sigmoid'}]}
    elif model == 'random_forest':
        hyperparameter_sets = {"n_estimators": [4000, 8000, 16000],
                                "max_features": ["None", "sqrt", "log2"],
                                "min_samples_leaf": [1, 10, 100, 1000],
                                "class_weight": ["None", "balanced_subsample","balanced"]

        }
    else:
        raise Exception('No such model! Should be among [{}, {}, {}, {}].'.format(
            'single_classification',
            'single_regression',
            'vanilla_lstm',
            'multi_classification'
        ))
    return hyperparameter_sets

def run_single_classification(hyperparameter_sets, hyperparameter_index):
    with open(config_json_file, 'r') as f:
        conf = json.load(f)
    label_name_list = conf['label_name_list']
    print 'label_name_list ', label_name_list

    # specify dataset
    k = 5
    directory = '../../dataset/fixed_dataset/fold_{}/'.format(k)
    file_list = []
    for i in range(k):
        file_list.append('file_{}.csv'.format(i))

    # merge training and test dataset
    output_file_list = [directory + f_ for f_ in file_list]
    print output_file_list[0:4]
    train_pd = read_merged_data(output_file_list[0:4])
    print output_file_list[4]
    test_pd = read_merged_data([output_file_list[4]])

    # extract data, and split training data into training and val
    X_train, y_train = extract_feature_and_label(train_pd,
                                                 feature_name='Fingerprints',
                                                 label_name_list=label_name_list)
    X_test, y_test = extract_feature_and_label(test_pd,
                                               feature_name='Fingerprints',
                                               label_name_list=label_name_list)
    cross_validation_split = StratifiedShuffleSplit(y_train, 1, test_size=test_ratio, random_state=1)
    for t_index, val_index in cross_validation_split:
        X_t, X_val = X_train[t_index], X_train[val_index]
        y_t, y_val = y_train[t_index], y_train[val_index]
    print 'done data preparation'

    hyperparameters = ParameterGrid(hyperparameter_sets)

    cnt = 0
    for param in hyperparameters:
        if cnt != hyperparameter_index:
            cnt += 1
            continue
        conf['compile']['optimizer']['option'] = param['optimizer']
        conf['compile']['optimizer'][param['optimizer']]['lr'] = param['learning rate']
        conf['class_weight_option'] = param['weighted schema']
        epoch_patience = param['epoch patience']
        conf['fitting']['nb_epoch'] = epoch_patience['epoch_size']
        conf['fitting']['early_stopping']['patience'] = epoch_patience['patience']
        conf['fitting']['early_stopping']['option'] = param['early stopping']
        activations = param['activations']
        conf['layers'][0]['activation'] = activations[0]
        conf['layers'][1]['activation'] = activations[1]
        conf['layers'][2]['activation'] = activations[2]
        print 'Testing hyperparameter ', param
        break

    if cnt < hyperparameter_index:
        raise ValueError('Process number out of limit. At most {}.'.format(cnt))

    task = SingleClassification(conf=conf)
    task.train_and_predict(X_t, y_t, X_val, y_val, X_test, y_test, PMTNN_weight_file)
    store_data(transform_json_to_csv(config_json_file), config_csv_file)

    return

def run_single_regression(hyperparameter_sets, hyperparameter_index):
    with open(config_json_file, 'r') as f:
        conf = json.load(f)
    label_name_list = conf['label_name_list']
    print 'label_name_list ', label_name_list

    # specify dataset
    k = 5
    directory = '../../dataset/fixed_dataset/fold_{}/'.format(k)
    file_list = []
    for i in range(k):
        file_list.append('file_{}.csv'.format(i))

    output_file_list = [directory + f_ for f_ in file_list]
    print output_file_list[0:4]
    train_pd = read_merged_data(output_file_list[0:4])
    print output_file_list[4]
    test_pd = read_merged_data([output_file_list[4]])

    # extract data, and split training data into training and val
    X_train, y_train = extract_feature_and_label(train_pd,
                                                 feature_name='Fingerprints',
                                                 label_name_list=label_name_list)
    X_test, y_test = extract_feature_and_label(test_pd,
                                               feature_name='Fingerprints',
                                               label_name_list=label_name_list)
    y_train_classification = reshape_data_into_2_dim(y_train[:, 0])
    y_train_regression = reshape_data_into_2_dim(y_train[:, 1])
    y_test_classification = reshape_data_into_2_dim(y_test[:, 0])
    y_test_regression = reshape_data_into_2_dim(y_test[:, 1])

    cross_validation_split = StratifiedShuffleSplit(y_train_classification, 1, test_size=test_ratio, random_state=1)

    for t_index, val_index in cross_validation_split:
        X_t, X_val = X_train[t_index], X_train[val_index]
        y_t_classification, y_val_classification = y_train_classification[t_index], y_train_classification[val_index]
        y_t_regression, y_val_regression = y_train_regression[t_index], y_train_regression[val_index]
    print 'done data preparation'

    hyperparameters = ParameterGrid(hyperparameter_sets)

    cnt = 0
    for param in hyperparameters:
        if cnt != hyperparameter_index:
            cnt += 1
            continue
        conf['compile']['optimizer']['option'] = param['optimizer']
        conf['compile']['optimizer'][param['optimizer']]['lr'] = param['learning rate']
        conf['class_weight_option'] = param['weighted schema']
        conf['fitting']['nb_epoch'] = param['epoch size']
        activations = param['activations']
        conf['layers'][0]['activation'] = activations[0]
        conf['layers'][1]['activation'] = activations[1]
        conf['layers'][2]['activation'] = activations[2]
        print 'Testing hyperparameter ', param
        break

    if cnt < hyperparameter_index:
        raise ValueError('Process number out of limit. At most {}.'.format(cnt))

    task = SingleRegression(conf=conf)
    task.train_and_predict(X_t, y_t_regression, y_t_classification,
                           X_val, y_val_regression, y_val_classification,
                           X_test, y_test_regression, y_test_classification,
                           PMTNN_weight_file)
    store_data(transform_json_to_csv(config_json_file), config_csv_file)

    return

def run_vanilla_lstm(hyperparameter_sets, hyperparameter_index):
    with open(config_json_file, 'r') as f:
        conf = json.load(f)
    label_name_list = conf['label_name_list']
    print 'label_name_list ', label_name_list

    # specify dataset
    k = 5
    directory = '../../dataset/fixed_dataset/fold_{}/'.format(k)
    file_list = []
    for i in range(k):
        file_list.append('file_{}.csv'.format(i))

    output_file_list = [directory + f_ for f_ in file_list]
    print output_file_list[:4]
    train_pd = read_merged_data(output_file_list[0:4])
    print output_file_list[4]
    test_pd = read_merged_data([output_file_list[4]])

    # extract data, and split training data into training and val
    X_train, y_train = extract_SMILES_and_label(train_pd,
                                                feature_name='SMILES',
                                                label_name_list=label_name_list,
                                                SMILES_mapping_json_file=SMILES_mapping_json_file)
    X_test, y_test = extract_SMILES_and_label(test_pd,
                                              feature_name='SMILES',
                                              label_name_list=label_name_list,
                                              SMILES_mapping_json_file=SMILES_mapping_json_file)

    cross_validation_split = StratifiedShuffleSplit(y_train, 1, test_size=test_ratio, random_state=1)
    for t_index, val_index in cross_validation_split:
        X_t, X_val = X_train[t_index], X_train[val_index]
        y_t, y_val = y_train[t_index], y_train[val_index]
    print 'done data preparation'

    hyperparameters = ParameterGrid(hyperparameter_sets)

    cnt = 0
    for param in hyperparameters:
        if cnt != hyperparameter_index:
            cnt += 1
            continue
        conf['lstm']['embedding_size'] = param['embedding_size']
        conf['lstm']['layer_num'] = len(param['hidden_size'])
        conf['compile']['optimizer']['option'] = param['optimizer']
        epoch_patience = param['epoch patience']
        conf['fitting']['nb_epoch'] = epoch_patience['epoch_size']
        conf['fitting']['early_stopping']['patience'] = epoch_patience['patience']
        conf['fitting']['early_stopping']['option'] = param['early stopping']
        for i in range(conf['lstm']['layer_num']):
            conf['layers'][i]['hidden_size'] = param['hidden_size'][i]
            conf['layers'][i]['dropout_U'] = param['dropout']
            conf['layers'][i]['dropout_W'] = param['dropout']
        print 'Testing hyperparameter ', param
        break

    if cnt < hyperparameter_index:
        raise ValueError('Process number out of limit. At most {}.'.format(cnt))

    task = VanillaLSTM(conf)
    X_t = sequence.pad_sequences(X_t, maxlen=task.padding_length)
    X_val = sequence.pad_sequences(X_val, maxlen=task.padding_length)
    X_test = sequence.pad_sequences(X_test, maxlen=task.padding_length)

    task.train_and_predict(X_t, y_t, X_val, y_val, X_test, y_test, PMTNN_weight_file)
    store_config(conf, config_csv_file)

    return

def run_multiple_classification(hyperparameter_sets, hyperparameter_index):
    with open(config_json_file, 'r') as f:
        conf = json.load(f)
    label_name_list = conf['label_name_list']
    print 'label_name_list ', label_name_list

    # specify dataset
    k = 5
    directory = '../../dataset/keck_pcba/fold_{}/'.format(k)
    file_list = []
    for i in range(k):
        file_list.append('file_{}.csv'.format(i))

    output_file_list = [directory + f_ for f_ in file_list]
    train_pd = read_merged_data(output_file_list[0:3])
    train_pd.fillna(0, inplace=True)
    val_pd = read_merged_data(output_file_list[3:4])
    val_pd.fillna(0, inplace=True)
    test_pd = read_merged_data(output_file_list[4:5])
    test_pd.fillna(0, inplace=True)

    multi_name_list = train_pd.columns[-128:].tolist()
    multi_name_list.extend(label_name_list)
    print 'multi_name_list ', multi_name_list

    X_train, y_train = extract_feature_and_label(train_pd,
                                                 feature_name='Fingerprints',
                                                 label_name_list=multi_name_list)
    X_val, y_val = extract_feature_and_label(val_pd,
                                             feature_name='Fingerprints',
                                             label_name_list=multi_name_list)
    X_test, y_test = extract_feature_and_label(test_pd,
                                               feature_name='Fingerprints',
                                               label_name_list=multi_name_list)

    sample_weight_dir = '../../dataset/sample_weights/keck_pcba/fold_5/'
    file_list = []
    for i in range(k):
        file_list.append('sample_weight_{}.csv'.format(i))
    sample_weight_file = [sample_weight_dir + f_ for f_ in file_list]
    sample_weight_file = np.array(sample_weight_file)
    sample_weight_pd = read_merged_data(sample_weight_file[0:3])
    _, sample_weight = extract_feature_and_label(sample_weight_pd,
                                                 feature_name='Fingerprints',
                                                 label_name_list=multi_name_list)
    print 'done data preparation'

    hyperparameters = ParameterGrid(hyperparameter_sets)

    cnt = 0
    for param in hyperparameters:
        if cnt != hyperparameter_index:
            cnt += 1
            continue
        conf['compile']['optimizer']['option'] = param['optimizer']
        conf['compile']['optimizer'][param['optimizer']]['lr'] = param['learning rate']
        conf['class_weight_option'] = param['weighted schema']
        epoch_schema = param['epoch patience']
        conf['fitting']['nb_epoch'] = epoch_schema['epoch_size']
        conf['fitting']['early_stopping']['patience'] = epoch_schema['patience']
        conf['fitting']['early_stopping']['option'] = param['early stopping']
        activations = param['activations']
        conf['layers'][0]['activation'] = activations[0]
        conf['layers'][1]['activation'] = activations[1]
        conf['layers'][2]['activation'] = activations[2]
        print 'Testing hyperparameter ', param
        break

    if cnt < hyperparameter_index:
        raise ValueError('Process number out of limit. At most {}.'.format(cnt))

    task = MultiClassification(conf=conf)
    task.train_and_predict(X_train, y_train, X_val, y_val, X_test, y_test,
                           sample_weight=sample_weight,
                           PMTNN_weight_file=PMTNN_weight_file,
                           score_file=score_file)
    store_data(transform_json_to_csv(config_json_file), config_csv_file)

    return

def run_hyperparameter_sets(model):
    global test_ratio
    test_ratio = 0.2

    if model == 'single_classification':
        hyperparameter_sets = get_hyperparameter_sets(model)
        run_single_classification(hyperparameter_sets, process_num)
    elif model == 'single_regression':
        hyperparameter_sets = get_hyperparameter_sets(model)
        run_single_regression(hyperparameter_sets, process_num)
    elif model == 'vanilla_lstm':
        hyperparameter_sets = get_hyperparameter_sets(model)
        global SMILES_mapping_json_file
        SMILES_mapping_json_file = given_args.SMILES_mapping_json_file
        run_vanilla_lstm(hyperparameter_sets, process_num)
    elif model == 'multi_classification':
        hyperparameter_sets = get_hyperparameter_sets(model)
        global score_file
        score_file = given_args.score_file
        run_multiple_classification(hyperparameter_sets, process_num)
    else:
        raise Exception('No such model! Should be among [{}, {}, {}, {}].'.format(
            'single_classification',
            'single_regression',
            'vanilla_lstm',
            'multi_classification'
        ))
    return

def transform_into_md(list_):
    str_ = '|'
    for val in list_:
        str_ = '{} {} |'.format(str_, val)
    return str_

def get_hyperparameter_sets_in_markdown(model):
    hyperparameter_sets = get_hyperparameter_sets(model)
    hyperparameters = ParameterGrid(hyperparameter_sets)

    content = ''
    for param in hyperparameters:
        keys = param.keys()
        header = '| {} {}'.format('count', transform_into_md(keys))
        dividing_line = transform_into_md(['---' for _ in range(1+len(keys))])
        content = '{}\n{}'.format(header, dividing_line)
        break

    count = 0
    for param in hyperparameters:
        values = param.values()
        content = '{}\n| {} {}'.format(content, count, transform_into_md(values))
        count += 1
    return content

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--config_json_file', dest="config_json_file",
                        action="store", required=False)
    parser.add_argument('--PMTNN_weight_file', dest="PMTNN_weight_file",
                        action="store", required=False)
    parser.add_argument('--config_csv_file', dest="config_csv_file",
                        action="store", required=False)
    parser.add_argument('--process_num', dest='process_num', type=int,
                        action='store', required=False)
    parser.add_argument('--SMILES_mapping_json_file', dest='SMILES_mapping_json_file',
                        action='store', required=False, default='../../json/SMILES_mapping.json')
    parser.add_argument('--score_file', dest='score_file',
                        action='store', required=False)
    parser.add_argument('--model', dest='model',
                        action='store', required=True)
    parser.add_argument('--is_print', dest='is_print', type=bool,
                        action='store', required=False, default=False)

    given_args = parser.parse_args()
    model = given_args.model
    is_print = given_args.is_print

    if is_print:
        content = get_hyperparameter_sets_in_markdown(model)
        print content
    else:
        config_json_file = given_args.config_json_file
        PMTNN_weight_file = given_args.PMTNN_weight_file
        config_csv_file = given_args.config_csv_file
        process_num = given_args.process_num
        run_hyperparameter_sets(model)


text:
#!/usr/bin/env python3
# rpi_ws281x library Colormapping
# Author: Norbert Karpen
#
# To map specific LED strip locations to a color gradient
#

import time
from rpi_ws281x import *
import argparse
# import numpy as np
import copy

# LED strip configuration:
LED_COUNT      = 130      # Number of LED pixels.
LED_PIN        = 18      # GPIO pin connected to the pixels (18 uses PWM!).
#LED_PIN        = 10      # GPIO pin connected to the pixels (10 uses SPI /dev/spidev0.0).
LED_FREQ_HZ    = 800000  # LED signal frequency in hertz (usually 800khz)
LED_DMA        = 10      # DMA channel to use for generating signal (try 10)
LED_BRIGHTNESS = 255     # Set to 0 for darkest and 255 for brightest
LED_INVERT     = False   # True to invert the signal (when using NPN transistor level shift)
LED_CHANNEL    = 0       # set to '1' for GPIOs 13, 19, 41, 45 or 53

# Gradient settings
empty_map = [[0, (0, 0, 0)], [1, (0, 0, 0)], [2, (0, 0, 0)], [3, (0, 0, 0)], [4, (0, 0, 0)], [5, (0, 0, 0)], [6, (0, 0, 0)], [7, (0, 0, 0)], [8, (0, 0, 0)], [9, (0, 0, 0)], [10, (0, 0, 0)], [11, (0, 0, 0)], [12, (0, 0, 0)], [13, (0, 0, 0)], [14, (0, 0, 0)], [15, (0, 0, 0)], [16, (0, 0, 0)], [17, (0, 0, 0)], [18, (0, 0, 0)], [19, (0, 0, 0)], [20, (0, 0, 0)], [21, (0, 0, 0)], [22, (0, 0, 0)], [23, (0, 0, 0)], [24, (0, 0, 0)], [25, (0, 0, 0)], [26, (0, 0, 0)], [27, (0, 0, 0)], [28, (0, 0, 0)], [29, (0, 0, 0)], [30, (0, 0, 0)], [31, (0, 0, 0)], [32, (0, 0, 0)], [33, (0, 0, 0)], [34, (0, 0, 0)], [35, (0, 0, 0)], [36, (0, 0, 0)], [37, (0, 0, 0)], [38, (0, 0, 0)], [39, (0, 0, 0)], [40, (0, 0, 0)], [41, (0, 0, 0)], [42, (0, 0, 0)], [43, (0, 0, 0)], [44, (0, 0, 0)], [45, (0, 0, 0)], [46, (0, 0, 0)], [47, (0, 0, 0)], [48, (0, 0, 0)], [49, (0, 0, 0)], [50, (0, 0, 0)], [51, (0, 0, 0)], [52, (0, 0, 0)], [53, (0, 0, 0)], [54, (0, 0, 0)], [55, (0, 0, 0)], [56, (0, 0, 0)], [57, (0, 0, 0)], [58, (0, 0, 0)], [59, (0, 0, 0)], [60, (0, 0, 0)], [61, (0, 0, 0)], [62, (0, 0, 0)], [63, (0, 0, 0)], [64, (0, 0, 0)], [65, (0, 0, 0)], [66, (0, 0, 0)], [67, (0, 0, 0)], [68, (0, 0, 0)], [69, (0, 0, 0)], [70, (0, 0, 0)], [71, (0, 0, 0)], [72, (0, 0, 0)], [73, (0, 0, 0)], [74, (0, 0, 0)], [75, (0, 0, 0)], [76, (0, 0, 0)], [77, (0, 0, 0)], [78, (0, 0, 0)], [79, (0, 0, 0)], [80, (0, 0, 0)], [81, (0, 0, 0)], [82, (0, 0, 0)], [83, (0, 0, 0)], [84, (0, 0, 0)], [85, (0, 0, 0)], [86, (0, 0, 0)], [87, (0, 0, 0)], [88, (0, 0, 0)], [89, (0, 0, 0)], [90, (0, 0, 0)], [91, (0, 0, 0)], [92, (0, 0, 0)], [93, (0, 0, 0)], [94, (0, 0, 0)], [95, (0, 0, 0)], [96, (0, 0, 0)], [97, (0, 0, 0)], [98, (0, 0, 0)], [99, (0, 0, 0)], [100, (0, 0, 0)], [101, (0, 0, 0)], [102, (0, 0, 0)], [103, (0, 0, 0)], [104, (0, 0, 0)], [105, (0, 0, 0)], [106, (0, 0, 0)], [107, (0, 0, 0)], [108, (0, 0, 0)], [109, (0, 0, 0)], [110, (0, 0, 0)], [111, (0, 0, 0)], [112, (0, 0, 0)], [113, (0, 0, 0)], [114, (0, 0, 0)], [115, (0, 0, 0)], [116, (0, 0, 0)], [117, (0, 0, 0)], [118, (0, 0, 0)], [119, (0, 0, 0)], [120, (0, 0, 0)], [121, (0, 0, 0)], [122, (0, 0, 0)], [123, (0, 0, 0)], [124, (0, 0, 0)], [125, (0, 0, 0)], [126, (0, 0, 0)], [127, (0, 0, 0)], [128, (0, 0, 0)], [129, (0, 0, 0)]]
gradient_map_original = [[0, (184, 52, 138)], [1, (185, 53, 139)], [2, (187, 55, 139)], [3, (188, 56, 140)], [4, (191, 60, 140)], [5, (192, 61, 139)], [6, (192, 61, 139)], [7, (194, 63, 139)], [8, (194, 63, 139)], [9, (196, 66, 140)], [10, (196, 65, 141)], [11, (196, 66, 140)], [12, (195, 64, 140)], [13, (193, 62, 140)], [14, (190, 58, 141)], [15, (185, 53, 139)], [16, (177, 46, 139)], [17, (170, 40, 140)], [18, (165, 42, 146)], [19, (162, 47, 151)], [20, (156, 50, 158)], [21, (151, 55, 165)], [22, (147, 59, 171)], [23, (140, 63, 179)], [24, (134, 66, 185)], [25, (127, 69, 189)], [26, (116, 70, 194)], [27, (108, 74, 197)], [28, (103, 74, 200)], [29, (97, 75, 201)], [30, (96, 75, 202)], [31, (92, 75, 203)], [32, (91, 76, 203)], [33, (91, 76, 205)], [34, (89, 77, 205)], [35, (88, 77, 205)], [36, (88, 77, 205)], [37, (87, 78, 207)], [38, (85, 78, 207)], [39, (84, 79, 208)], [40, (81, 78, 207)], [41, (80, 79, 207)], [42, (79, 79, 209)], [43, (76, 81, 211)], [44, (73, 80, 210)], [45, (72, 81, 212)], [46, (71, 81, 213)], [47, (65, 82, 214)], [48, (64, 82, 216)], [49, (60, 83, 215)], [50, (61, 80, 209)], [51, (58, 79, 206)], [52, (57, 75, 199)], [53, (55, 74, 194)], [54, (54, 71, 187)], [55, (53, 69, 182)], [56, (53, 65, 173)], [57, (50, 63, 168)], [58, (49, 61, 163)], [59, (49, 57, 155)], [60, (46, 55, 148)], [61, (54, 73, 191)], [62, (56, 74, 198)], [63, (57, 77, 202)], [64, (59, 80, 208)], [65, (59, 82, 214)], [66, (65, 83, 217)], [67, (65, 82, 214)], [68, (71, 81, 213)], [69, (73, 80, 212)], [70, (79, 79, 209)], [71, (81, 78, 209)], [72, (85, 78, 207)], [73, (89, 77, 205)], [74, (92, 75, 203)], [75, (96, 75, 202)], [76, (97, 75, 201)], [77, (99, 74, 201)], [78, (104, 74, 198)], [79, (105, 73, 198)], [80, (108, 74, 197)], [81, (138, 65, 182)], [82, (137, 66, 184)], [83, (135, 66, 183)], [84, (136, 67, 186)], [85, (133, 68, 186)], [86, (132, 68, 188)], [87, (129, 68, 187)], [88, (128, 69, 189)], [89, (123, 69, 189)], [90, (120, 70, 193)], [91, (115, 71, 192)], [92, (111, 71, 194)], [93, (109, 73, 197)], [94, (104, 74, 198)], [95, (102, 76, 201)], [96, (96, 74, 200)], [97, (95, 76, 202)], [98, (89, 77, 205)], [99, (136, 65, 183)], [100, (139, 66, 183)], [101, (139, 65, 180)], [102, (141, 62, 177)], [103, (144, 61, 175)], [104, (143, 60, 174)], [105, (145, 58, 171)], [106, (146, 58, 170)], [107, (146, 57, 167)], [108, (150, 56, 168)], [109, (151, 55, 165)], [110, (151, 55, 165)], [111, (151, 55, 165)], [112, (152, 54, 163)], [113, (152, 54, 163)], [114, (151, 53, 162)], [115, (167, 42, 146)], [116, (166, 43, 147)], [117, (165, 44, 147)], [118, (165, 44, 147)], [119, (165, 44, 147)], [120, (165, 44, 149)], [121, (164, 45, 149)], [122, (164, 45, 147)], [123, (163, 46, 150)], [124, (162, 47, 151)], [125, (160, 47, 153)], [126, (159, 48, 153)], [127, (157, 50, 156)], [128, (157, 50, 156)], [129, (155, 52, 161)]]
gradient_maps_list = [[[0, (1, 155, 193)], [1, (0, 184, 210)], [2, (0, 218, 227)], [3, (1, 230, 233)], [4, (0, 239, 236)], [5, (0, 237, 243)], [6, (0, 237, 249)], [7, (0, 254, 254)], [8, (1, 255, 253)], [9, (1, 255, 253)], [10, (1, 255, 253)], [11, (1, 255, 253)], [12, (1, 255, 253)], [13, (1, 255, 253)], [14, (1, 255, 253)], [15, (1, 255, 253)], [16, (1, 255, 253)], [17, (0, 255, 251)], [18, (0, 255, 251)], [19, (0, 255, 249)], [20, (0, 254, 243)], [21, (0, 254, 226)], [22, (0, 255, 199)], [23, (0, 255, 171)], [24, (0, 255, 151)], [25, (83, 255, 138)], [26, (187, 255, 134)], [27, (247, 240, 133)], [28, (255, 202, 124)], [29, (255, 160, 116)], [30, (255, 123, 102)], [31, (255, 103, 92)], [32, (255, 89, 81)], [33, (255, 80, 65)], [34, (255, 76, 53)], [35, (255, 77, 31)], [36, (254, 81, 25)], [37, (255, 85, 26)], [38, (255, 89, 29)], [39, (255, 96, 12)], [40, (254, 100, 2)], [41, (255, 102, 6)], [42, (255, 86, 79)], [43, (250, 9, 140)], [44, (255, 0, 194)], [45, (255, 0, 218)], [46, (255, 0, 242)], [47, (255, 0, 252)], [48, (255, 0, 254)], [49, (255, 0, 254)], [50, (255, 0, 254)], [51, (240, 0, 255)], [52, (225, 0, 254)], [53, (221, 0, 254)], [54, (221, 0, 254)], [55, (220, 0, 255)], [56, (220, 0, 254)], [57, (220, 0, 255)], [58, (220, 0, 255)], [59, (220, 0, 254)], [60, (220, 0, 255)], [61, (191, 0, 254)], [62, (191, 0, 254)], [63, (190, 0, 255)], [64, (187, 0, 255)], [65, (179, 0, 254)], [66, (145, 0, 255)], [67, (119, 0, 254)], [68, (194, 0, 255)], [69, (255, 0, 254)], [70, (247, 0, 255)], [71, (234, 0, 255)], [72, (216, 1, 255)], [73, (194, 0, 255)], [74, (177, 0, 255)], [75, (164, 0, 255)], [76, (146, 0, 255)], [77, (142, 1, 255)], [78, (132, 0, 255)], [79, (117, 9, 253)], [80, (0, 158, 188)], [81, (0, 175, 240)], [82, (0, 178, 238)], [83, (0, 178, 229)], [84, (1, 153, 176)], [85, (1, 94, 83)], [86, (5, 27, 15)], [87, (26, 5, 20)], [88, (2, 50, 0)], [89, (1, 95, 81)], [90, (0, 121, 142)], [91, (0, 125, 173)], [92, (28, 114, 201)], [93, (88, 96, 223)], [94, (126, 73, 239)], [95, (152, 57, 249)], [96, (179, 35, 254)], [97, (200, 30, 251)], [98, (195, 36, 253)], [99, (1, 75, 74)], [100, (0, 59, 34)], [101, (20, 37, 1)], [102, (28, 13, 8)], [103, (31, 0, 10)], [104, (25, 11, 10)], [105, (0, 41, 0)], [106, (0, 71, 57)], [107, (0, 99, 114)], [108, (0, 126, 161)], [109, (0, 147, 199)], [110, (1, 160, 225)], [111, (0, 170, 242)], [112, (0, 170, 245)], [113, (0, 172, 241)], [114, (0, 173, 242)], [115, (1, 255, 253)], [116, (1, 255, 253)], [117, (0, 244, 254)], [118, (0, 241, 252)], [119, (0, 248, 250)], [120, (1, 228, 244)], [121, (0, 204, 229)], [122, (0, 176, 215)], [123, (0, 145, 190)], [124, (1, 117, 158)], [125, (0, 93, 123)], [126, (0, 72, 81)], [127, (0, 49, 38)], [128, (2, 30, 7)], [129, (23, 13, 11)]], [[0, (27, 210, 104)], [1, (31, 214, 108)], [2, (33, 216, 112)], [3, (35, 215, 116)], [4, (41, 220, 120)], [5, (43, 221, 123)], [6, (42, 222, 125)], [7, (46, 224, 128)], [8, (46, 226, 129)], [9, (49, 226, 135)], [10, (54, 227, 137)], [11, (49, 226, 135)], [12, (47, 226, 132)], [13, (45, 223, 127)], [14, (40, 218, 120)], [15, (30, 213, 107)], [16, (18, 205, 90)], [17, (2, 192, 66)], [18, (15, 186, 58)], [19, (29, 176, 44)], [20, (41, 169, 30)], [21, (74, 179, 37)], [22, (97, 187, 40)], [23, (122, 199, 45)], [24, (143, 209, 49)], [25, (163, 214, 51)], [26, (178, 220, 50)], [27, (195, 224, 54)], [28, (208, 231, 55)], [29, (215, 232, 55)], [30, (221, 234, 56)], [31, (224, 235, 53)], [32, (227, 237, 54)], [33, (231, 239, 55)], [34, (230, 238, 56)], [35, (233, 238, 57)], [36, (234, 237, 58)], [37, (238, 242, 57)], [38, (237, 241, 56)], [39, (241, 243, 56)], [40, (244, 243, 57)], [41, (249, 243, 57)], [42, (248, 243, 55)], [43, (250, 236, 51)], [44, (253, 238, 51)], [45, (253, 232, 45)], [46, (255, 226, 42)], [47, (255, 220, 40)], [48, (255, 214, 40)], [49, (254, 206, 34)], [50, (255, 210, 28)], [51, (251, 206, 27)], [52, (245, 198, 24)], [53, (241, 188, 24)], [54, (237, 181, 26)], [55, (229, 175, 23)], [56, (222, 167, 25)], [57, (218, 162, 27)], [58, (212, 153, 27)], [59, (206, 147, 31)], [60, (198, 138, 28)], [61, (238, 182, 23)], [62, (241, 188, 22)], [63, (249, 197, 25)], [64, (255, 204, 25)], [65, (255, 205, 32)], [66, (253, 211, 37)], [67, (254, 219, 39)], [68, (255, 228, 43)], [69, (255, 238, 47)], [70, (249, 244, 56)], [71, (245, 244, 56)], [72, (239, 241, 56)], [73, (233, 237, 56)], [74, (225, 237, 53)], [75, (220, 233, 55)], [76, (217, 235, 55)], [77, (212, 233, 54)], [78, (205, 227, 54)], [79, (203, 227, 51)], [80, (200, 229, 53)], [81, (131, 202, 46)], [82, (135, 205, 47)], [83, (138, 205, 47)], [84, (142, 208, 48)], [85, (143, 209, 47)], [86, (149, 209, 49)], [87, (153, 211, 47)], [88, (158, 213, 49)], [89, (166, 214, 50)], [90, (176, 219, 51)], [91, (181, 218, 52)], [92, (190, 222, 51)], [93, (198, 226, 54)], [94, (203, 227, 53)], [95, (211, 232, 53)], [96, (215, 233, 53)], [97, (221, 234, 56)], [98, (230, 238, 57)], [99, (137, 204, 46)], [100, (130, 204, 45)], [101, (125, 199, 44)], [102, (116, 195, 41)], [103, (107, 193, 40)], [104, (104, 188, 40)], [105, (99, 189, 40)], [106, (91, 187, 36)], [107, (90, 181, 41)], [108, (79, 181, 35)], [109, (76, 181, 37)], [110, (75, 180, 35)], [111, (73, 178, 36)], [112, (68, 177, 36)], [113, (67, 176, 33)], [114, (66, 175, 34)], [115, (11, 186, 59)], [116, (14, 185, 55)], [117, (17, 184, 55)], [118, (16, 183, 52)], [119, (18, 181, 52)], [120, (18, 181, 52)], [121, (17, 180, 51)], [122, (22, 181, 52)], [123, (25, 181, 48)], [124, (27, 176, 46)], [125, (30, 175, 36)], [126, (31, 171, 36)], [127, (38, 170, 32)], [128, (39, 167, 31)], [129, (50, 171, 32)]], [[0, (149, 225, 2)], [1, (156, 229, 2)], [2, (166, 232, 2)], [3, (175, 235, 0)], [4, (181, 238, 1)], [5, (189, 239, 0)], [6, (194, 243, 1)], [7, (200, 246, 0)], [8, (206, 248, 0)], [9, (213, 249, 1)], [10, (216, 251, 1)], [11, (220, 253, 0)], [12, (220, 253, 0)], [13, (220, 253, 0)], [14, (221, 254, 1)], [15, (221, 254, 1)], [16, (221, 254, 1)], [17, (220, 253, 0)], [18, (219, 251, 0)], [19, (214, 251, 0)], [20, (207, 247, 0)], [21, (199, 244, 1)], [22, (187, 240, 0)], [23, (176, 236, 1)], [24, (163, 231, 0)], [25, (149, 225, 2)], [26, (134, 219, 2)], [27, (118, 212, 2)], [28, (104, 207, 2)], [29, (89, 201, 3)], [30, (74, 195, 4)], [31, (62, 191, 3)], [32, (51, 185, 4)], [33, (39, 180, 5)], [34, (29, 175, 6)], [35, (19, 170, 5)], [36, (12, 166, 6)], [37, (4, 162, 7)], [38, (0, 157, 6)], [39, (0, 152, 8)], [40, (0, 145, 10)], [41, (0, 139, 12)], [42, (0, 133, 14)], [43, (0, 127, 16)], [44, (0, 121, 18)], [45, (0, 115, 20)], [46, (0, 110, 23)], [47, (0, 104, 25)], [48, (0, 99, 27)], [49, (0, 95, 29)], [50, (1, 92, 31)], [51, (0, 91, 30)], [52, (0, 95, 31)], [53, (1, 98, 29)], [54, (0, 102, 26)], [55, (0, 108, 23)], [56, (0, 115, 22)], [57, (0, 121, 20)], [58, (0, 128, 15)], [59, (0, 138, 13)], [60, (0, 144, 10)], [61, (1, 124, 18)], [62, (0, 117, 20)], [63, (0, 112, 22)], [64, (1, 105, 26)], [65, (0, 101, 27)], [66, (0, 97, 28)], [67, (0, 95, 29)], [68, (0, 95, 31)], [69, (0, 96, 29)], [70, (0, 99, 27)], [71, (0, 102, 26)], [72, (0, 108, 23)], [73, (0, 113, 21)], [74, (0, 118, 21)], [75, (0, 123, 17)], [76, (1, 129, 16)], [77, (0, 135, 14)], [78, (0, 141, 11)], [79, (0, 146, 9)], [80, (0, 152, 8)], [81, (45, 182, 4)], [82, (35, 177, 5)], [83, (26, 173, 5)], [84, (18, 169, 6)], [85, (11, 165, 5)], [86, (5, 163, 8)], [87, (1, 160, 8)], [88, (0, 154, 8)], [89, (0, 148, 10)], [90, (0, 141, 11)], [91, (1, 137, 13)], [92, (0, 130, 16)], [93, (0, 126, 18)], [94, (0, 121, 18)], [95, (0, 117, 20)], [96, (0, 114, 19)], [97, (0, 112, 22)], [98, (0, 110, 23)], [99, (0, 153, 9)], [100, (0, 157, 8)], [101, (3, 160, 7)], [102, (8, 164, 5)], [103, (15, 167, 6)], [104, (21, 170, 6)], [105, (29, 175, 6)], [106, (38, 179, 4)], [107, (48, 183, 3)], [108, (58, 188, 4)], [109, (67, 192, 4)], [110, (74, 195, 4)], [111, (86, 199, 3)], [112, (92, 203, 2)], [113, (103, 208, 2)], [114, (112, 212, 2)], [115, (176, 236, 1)], [116, (165, 233, 2)], [117, (158, 229, 1)], [118, (150, 225, 2)], [119, (142, 222, 1)], [120, (134, 219, 2)], [121, (126, 217, 2)], [122, (118, 212, 1)], [123, (107, 209, 3)], [124, (97, 204, 2)], [125, (87, 200, 4)], [126, (77, 197, 4)], [127, (68, 193, 3)], [128, (59, 189, 3)], [129, (50, 185, 4)]], [[0, (225, 22, 86)], [1, (222, 19, 83)], [2, (220, 15, 80)], [3, (219, 13, 77)], [4, (218, 12, 76)], [5, (217, 11, 75)], [6, (219, 11, 73)], [7, (219, 11, 73)], [8, (219, 10, 75)], [9, (220, 11, 76)], [10, (219, 13, 77)], [11, (220, 14, 78)], [12, (221, 15, 79)], [13, (222, 17, 82)], [14, (223, 18, 83)], [15, (222, 19, 83)], [16, (222, 19, 83)], [17, (222, 19, 83)], [18, (223, 18, 83)], [19, (223, 20, 86)], [20, (224, 21, 85)], [21, (224, 24, 89)], [22, (223, 27, 93)], [23, (225, 30, 98)], [24, (224, 35, 103)], [25, (224, 39, 107)], [26, (224, 43, 112)], [27, (224, 47, 119)], [28, (225, 51, 123)], [29, (224, 52, 124)], [30, (225, 55, 128)], [31, (224, 57, 129)], [32, (225, 58, 130)], [33, (224, 58, 130)], [34, (224, 60, 133)], [35, (224, 62, 137)], [36, (224, 63, 139)], [37, (224, 66, 141)], [38, (224, 67, 144)], [39, (223, 71, 148)], [40, (225, 74, 153)], [41, (224, 77, 157)], [42, (224, 81, 161)], [43, (223, 84, 165)], [44, (224, 87, 169)], [45, (223, 89, 174)], [46, (216, 92, 178)], [47, (208, 96, 182)], [48, (195, 99, 188)], [49, (185, 102, 194)], [50, (171, 104, 199)], [51, (158, 108, 205)], [52, (142, 110, 209)], [53, (126, 114, 216)], [54, (109, 116, 220)], [55, (94, 118, 226)], [56, (77, 120, 232)], [57, (61, 123, 236)], [58, (45, 125, 240)], [59, (28, 127, 244)], [60, (18, 128, 249)], [61, (63, 123, 237)], [62, (78, 120, 232)], [63, (94, 118, 226)], [64, (111, 116, 220)], [65, (126, 114, 216)], [66, (145, 110, 210)], [67, (161, 107, 203)], [68, (172, 105, 198)], [69, (186, 101, 192)], [70, (198, 98, 188)], [71, (209, 95, 182)], [72, (219, 91, 176)], [73, (225, 88, 170)], [74, (225, 83, 165)], [75, (226, 80, 161)], [76, (224, 76, 154)], [77, (224, 72, 149)], [78, (224, 67, 144)], [79, (223, 63, 137)], [80, (225, 59, 133)], [81, (225, 26, 93)], [82, (224, 31, 98)], [83, (224, 35, 103)], [84, (224, 39, 107)], [85, (225, 44, 115)], [86, (223, 47, 119)], [87, (224, 52, 124)], [88, (224, 58, 132)], [89, (224, 64, 138)], [90, (224, 69, 147)], [91, (223, 75, 151)], [92, (225, 78, 158)], [93, (224, 82, 164)], [94, (224, 87, 169)], [95, (219, 91, 176)], [96, (212, 94, 182)], [97, (200, 97, 186)], [98, (187, 101, 192)], [99, (225, 70, 146)], [100, (224, 66, 141)], [101, (225, 61, 134)], [102, (225, 55, 126)], [103, (224, 50, 121)], [104, (224, 45, 113)], [105, (224, 39, 107)], [106, (224, 33, 102)], [107, (223, 28, 94)], [108, (224, 24, 89)], [109, (222, 19, 83)], [110, (221, 15, 79)], [111, (220, 11, 76)], [112, (217, 9, 71)], [113, (216, 6, 69)], [114, (214, 4, 65)], [115, (214, 0, 60)], [116, (214, 0, 60)], [117, (214, 0, 60)], [118, (214, 0, 60)], [119, (214, 2, 61)], [120, (216, 4, 65)], [121, (217, 7, 70)], [122, (219, 10, 75)], [123, (220, 14, 78)], [124, (221, 18, 82)], [125, (225, 22, 88)], [126, (223, 27, 93)], [127, (225, 32, 99)], [128, (224, 37, 105)], [129, (223, 42, 111)]], [[0, (202, 5, 76)], [1, (202, 2, 75)], [2, (203, 1, 77)], [3, (203, 1, 77)], [4, (203, 1, 77)], [5, (203, 1, 77)], [6, (203, 1, 77)], [7, (203, 1, 77)], [8, (203, 1, 77)], [9, (203, 1, 77)], [10, (203, 1, 77)], [11, (203, 1, 77)], [12, (203, 1, 77)], [13, (203, 1, 77)], [14, (203, 1, 77)], [15, (203, 1, 77)], [16, (203, 1, 77)], [17, (203, 1, 77)], [18, (203, 1, 77)], [19, (203, 1, 77)], [20, (203, 1, 77)], [21, (203, 3, 76)], [22, (203, 19, 69)], [23, (203, 45, 60)], [24, (203, 73, 49)], [25, (203, 104, 37)], [26, (202, 136, 24)], [27, (200, 170, 12)], [28, (199, 196, 5)], [29, (197, 218, 1)], [30, (193, 236, 0)], [31, (188, 246, 1)], [32, (183, 253, 0)], [33, (178, 255, 1)], [34, (171, 255, 7)], [35, (162, 252, 17)], [36, (153, 247, 26)], [37, (141, 237, 39)], [38, (132, 230, 49)], [39, (120, 220, 62)], [40, (109, 209, 77)], [41, (97, 195, 94)], [42, (86, 183, 106)], [43, (75, 172, 119)], [44, (69, 163, 127)], [45, (60, 154, 138)], [46, (55, 147, 146)], [47, (48, 140, 153)], [48, (43, 135, 160)], [49, (41, 132, 163)], [50, (44, 134, 160)], [51, (49, 142, 150)], [52, (56, 148, 143)], [53, (67, 162, 132)], [54, (80, 176, 113)], [55, (90, 189, 98)], [56, (106, 204, 81)], [57, (123, 220, 63)], [58, (138, 235, 44)], [59, (152, 246, 26)], [60, (166, 254, 12)], [61, (157, 250, 21)], [62, (147, 243, 32)], [63, (138, 235, 44)], [64, (126, 225, 56)], [65, (118, 216, 67)], [66, (111, 208, 77)], [67, (104, 203, 84)], [68, (100, 198, 89)], [69, (97, 195, 92)], [70, (98, 196, 93)], [71, (99, 198, 90)], [72, (102, 201, 84)], [73, (108, 207, 78)], [74, (114, 213, 70)], [75, (118, 217, 65)], [76, (125, 224, 56)], [77, (132, 229, 51)], [78, (140, 236, 40)], [79, (149, 243, 32)], [80, (156, 248, 23)], [81, (196, 217, 0)], [82, (195, 228, 0)], [83, (193, 235, 1)], [84, (191, 242, 1)], [85, (187, 247, 0)], [86, (185, 252, 1)], [87, (183, 254, 0)], [88, (179, 254, 1)], [89, (174, 254, 5)], [90, (167, 255, 11)], [91, (164, 252, 16)], [92, (157, 250, 21)], [93, (152, 246, 25)], [94, (149, 244, 30)], [95, (147, 243, 32)], [96, (147, 243, 32)], [97, (147, 242, 34)], [98, (148, 242, 31)], [99, (189, 245, 0)], [100, (191, 242, 1)], [101, (192, 236, 0)], [102, (194, 230, 0)], [103, (195, 221, 0)], [104, (197, 213, 0)], [105, (200, 204, 5)], [106, (201, 193, 7)], [107, (202, 179, 11)], [108, (202, 169, 14)], [109, (202, 156, 18)], [110, (204, 149, 22)], [111, (203, 135, 26)], [112, (203, 124, 31)], [113, (202, 112, 34)], [114, (203, 101, 37)], [115, (203, 6, 75)], [116, (202, 14, 72)], [117, (202, 20, 68)], [118, (203, 28, 67)], [119, (203, 34, 63)], [120, (203, 45, 60)], [121, (204, 50, 58)], [122, (202, 59, 55)], [123, (203, 73, 49)], [124, (203, 85, 45)], [125, (204, 99, 41)], [126, (203, 109, 35)], [127, (204, 120, 32)], [128, (203, 132, 28)], [129, (204, 144, 24)]], [[0, (151, 13, 255)], [1, (160, 7, 255)], [2, (172, 3, 255)], [3, (178, 1, 255)], [4, (192, 2, 250)], [5, (203, 9, 245)], [6, (212, 18, 237)], [7, (222, 32, 228)], [8, (229, 47, 218)], [9, (236, 64, 208)], [10, (242, 78, 201)], [11, (245, 88, 195)], [12, (248, 98, 188)], [13, (251, 104, 184)], [14, (253, 108, 183)], [15, (252, 108, 180)], [16, (251, 104, 184)], [17, (248, 98, 188)], [18, (244, 86, 196)], [19, (238, 71, 203)], [20, (230, 49, 216)], [21, (218, 26, 233)], [22, (202, 8, 244)], [23, (181, 0, 255)], [24, (166, 5, 255)], [25, (149, 14, 255)], [26, (129, 28, 254)], [27, (107, 48, 254)], [28, (88, 63, 251)], [29, (70, 81, 249)], [30, (52, 96, 245)], [31, (41, 107, 245)], [32, (31, 116, 241)], [33, (22, 126, 241)], [34, (14, 132, 238)], [35, (6, 138, 236)], [36, (2, 143, 235)], [37, (0, 144, 233)], [38, (0, 143, 230)], [39, (0, 143, 229)], [40, (1, 143, 227)], [41, (0, 138, 226)], [42, (3, 132, 223)], [43, (9, 126, 221)], [44, (13, 120, 218)], [45, (20, 112, 215)], [46, (24, 103, 208)], [47, (27, 95, 204)], [48, (28, 82, 190)], [49, (25, 66, 171)], [50, (25, 50, 151)], [51, (20, 32, 130)], [52, (19, 17, 114)], [53, (16, 5, 97)], [54, (15, 0, 91)], [55, (15, 0, 91)], [56, (15, 0, 91)], [57, (15, 0, 91)], [58, (15, 0, 91)], [59, (15, 0, 91)], [60, (15, 0, 91)], [61, (15, 0, 91)], [62, (15, 0, 91)], [63, (15, 0, 91)], [64, (15, 0, 91)], [65, (15, 4, 96)], [66, (18, 17, 111)], [67, (21, 35, 132)], [68, (24, 49, 150)], [69, (27, 66, 171)], [70, (28, 82, 190)], [71, (29, 93, 201)], [72, (25, 104, 209)], [73, (19, 112, 215)], [74, (12, 120, 218)], [75, (8, 127, 221)], [76, (1, 135, 224)], [77, (0, 140, 225)], [78, (1, 143, 227)], [79, (0, 143, 230)], [80, (0, 144, 233)], [81, (52, 96, 245)], [82, (41, 107, 243)], [83, (31, 116, 241)], [84, (20, 125, 240)], [85, (12, 133, 238)], [86, (5, 139, 236)], [87, (2, 143, 235)], [88, (0, 143, 230)], [89, (0, 143, 229)], [90, (1, 143, 227)], [91, (0, 139, 224)], [92, (6, 131, 223)], [93, (11, 124, 220)], [94, (18, 114, 216)], [95, (24, 105, 212)], [96, (26, 97, 205)], [97, (29, 87, 195)], [98, (27, 71, 176)], [99, (1, 143, 227)], [100, (0, 143, 229)], [101, (0, 144, 233)], [102, (2, 143, 235)], [103, (8, 138, 236)], [104, (16, 131, 238)], [105, (26, 121, 241)], [106, (38, 110, 244)], [107, (52, 98, 246)], [108, (64, 86, 249)], [109, (77, 74, 251)], [110, (87, 65, 252)], [111, (101, 52, 255)], [112, (112, 43, 255)], [113, (123, 33, 255)], [114, (134, 25, 254)], [115, (198, 4, 248)], [116, (185, 0, 254)], [117, (176, 0, 255)], [118, (170, 3, 255)], [119, (162, 8, 255)], [120, (152, 13, 255)], [121, (142, 19, 255)], [122, (132, 27, 254)], [123, (117, 38, 254)], [124, (103, 50, 254)], [125, (89, 62, 251)], [126, (75, 75, 249)], [127, (62, 87, 249)], [128, (49, 101, 246)], [129, (35, 112, 244)]], [[0, (255, 113, 179)], [1, (255, 113, 179)], [2, (255, 113, 179)], [3, (255, 113, 179)], [4, (255, 113, 179)], [5, (255, 113, 179)], [6, (255, 113, 179)], [7, (255, 113, 179)], [8, (255, 113, 179)], [9, (255, 113, 179)], [10, (255, 113, 179)], [11, (255, 112, 181)], [12, (255, 112, 181)], [13, (255, 113, 179)], [14, (255, 113, 179)], [15, (255, 113, 179)], [16, (255, 113, 179)], [17, (255, 113, 179)], [18, (255, 113, 179)], [19, (255, 113, 179)], [20, (255, 113, 179)], [21, (255, 112, 181)], [22, (255, 113, 179)], [23, (254, 110, 179)], [24, (250, 102, 186)], [25, (244, 92, 193)], [26, (240, 77, 202)], [27, (232, 62, 213)], [28, (226, 48, 220)], [29, (221, 37, 229)], [30, (215, 27, 238)], [31, (209, 19, 241)], [32, (203, 12, 247)], [33, (196, 7, 249)], [34, (188, 2, 253)], [35, (176, 0, 255)], [36, (164, 3, 255)], [37, (140, 16, 250)], [38, (116, 33, 245)], [39, (83, 59, 233)], [40, (51, 83, 218)], [41, (29, 93, 201)], [42, (18, 88, 186)], [43, (16, 77, 170)], [44, (16, 63, 155)], [45, (14, 49, 139)], [46, (16, 37, 128)], [47, (14, 27, 119)], [48, (15, 22, 113)], [49, (14, 18, 109)], [50, (14, 14, 104)], [51, (15, 10, 102)], [52, (14, 9, 99)], [53, (14, 8, 98)], [54, (15, 4, 96)], [55, (15, 4, 96)], [56, (15, 4, 96)], [57, (16, 3, 95)], [58, (16, 3, 95)], [59, (16, 3, 95)], [60, (15, 2, 94)], [61, (11, 15, 106)], [62, (12, 15, 108)], [63, (11, 14, 107)], [64, (10, 15, 106)], [65, (11, 15, 106)], [66, (11, 15, 106)], [67, (12, 13, 105)], [68, (11, 15, 106)], [69, (12, 13, 105)], [70, (12, 11, 104)], [71, (12, 11, 104)], [72, (14, 9, 101)], [73, (13, 7, 97)], [74, (13, 4, 95)], [75, (16, 3, 93)], [76, (14, 8, 98)], [77, (14, 25, 115)], [78, (15, 54, 145)], [79, (21, 90, 191)], [80, (87, 56, 237)], [81, (255, 113, 179)], [82, (255, 113, 179)], [83, (255, 112, 181)], [84, (255, 113, 179)], [85, (255, 113, 179)], [86, (244, 114, 184)], [87, (147, 133, 212)], [88, (50, 144, 232)], [89, (5, 143, 232)], [90, (1, 130, 222)], [91, (1, 114, 206)], [92, (0, 101, 193)], [93, (0, 89, 181)], [94, (0, 81, 173)], [95, (1, 78, 170)], [96, (0, 73, 167)], [97, (1, 70, 163)], [98, (0, 65, 157)], [99, (38, 143, 234)], [100, (59, 143, 231)], [101, (91, 143, 226)], [102, (133, 136, 215)], [103, (169, 128, 204)], [104, (207, 121, 192)], [105, (235, 116, 184)], [106, (253, 112, 180)], [107, (255, 113, 179)], [108, (255, 113, 179)], [109, (255, 113, 179)], [110, (255, 113, 179)], [111, (255, 112, 181)], [112, (255, 113, 179)], [113, (255, 113, 179)], [114, (255, 113, 179)], [115, (255, 113, 179)], [116, (255, 113, 179)], [117, (255, 113, 179)], [118, (255, 113, 179)], [119, (255, 113, 179)], [120, (255, 113, 179)], [121, (255, 113, 179)], [122, (255, 113, 179)], [123, (255, 113, 179)], [124, (255, 113, 179)], [125, (255, 113, 179)], [126, (252, 113, 181)], [127, (239, 113, 184)], [128, (225, 118, 188)], [129, (207, 121, 192)]], [[0, (255, 194, 113)], [1, (255, 194, 113)], [2, (255, 194, 113)], [3, (255, 194, 113)], [4, (255, 194, 113)], [5, (255, 194, 113)], [6, (255, 194, 113)], [7, (255, 194, 113)], [8, (255, 194, 113)], [9, (255, 194, 113)], [10, (255, 194, 113)], [11, (255, 194, 113)], [12, (255, 194, 113)], [13, (255, 194, 113)], [14, (255, 194, 113)], [15, (255, 194, 113)], [16, (255, 194, 113)], [17, (255, 194, 113)], [18, (255, 194, 113)], [19, (255, 194, 113)], [20, (255, 194, 113)], [21, (255, 194, 113)], [22, (255, 194, 113)], [23, (254, 192, 109)], [24, (255, 174, 98)], [25, (255, 150, 84)], [26, (255, 115, 62)], [27, (254, 76, 40)], [28, (254, 39, 19)], [29, (255, 13, 12)], [30, (255, 8, 24)], [31, (255, 5, 30)], [32, (255, 4, 37)], [33, (254, 2, 43)], [34, (255, 1, 55)], [35, (255, 0, 66)], [36, (255, 3, 80)], [37, (254, 12, 115)], [38, (254, 23, 153)], [39, (255, 38, 213)], [40, (224, 17, 255)], [41, (154, 1, 231)], [42, (129, 0, 204)], [43, (120, 0, 185)], [44, (118, 0, 167)], [45, (119, 0, 154)], [46, (122, 1, 142)], [47, (122, 0, 135)], [48, (125, 0, 128)], [49, (124, 0, 122)], [50, (118, 0, 110)], [51, (112, 0, 100)], [52, (110, 0, 97)], [53, (105, 1, 90)], [54, (102, 0, 84)], [55, (102, 0, 84)], [56, (99, 0, 82)], [57, (97, 0, 79)], [58, (97, 0, 79)], [59, (97, 0, 79)], [60, (94, 0, 74)], [61, (117, 0, 115)], [62, (119, 0, 118)], [63, (117, 0, 115)], [64, (118, 0, 115)], [65, (117, 0, 114)], [66, (117, 0, 114)], [67, (118, 0, 114)], [68, (116, 0, 113)], [69, (116, 0, 111)], [70, (114, 1, 109)], [71, (113, 0, 106)], [72, (110, 0, 99)], [73, (105, 0, 92)], [74, (98, 0, 81)], [75, (97, 0, 77)], [76, (106, 0, 92)], [77, (125, 0, 132)], [78, (118, 1, 160)], [79, (134, 0, 209)], [80, (255, 35, 206)], [81, (255, 194, 113)], [82, (255, 194, 113)], [83, (255, 194, 113)], [84, (255, 194, 113)], [85, (255, 194, 113)], [86, (255, 182, 103)], [87, (255, 88, 217)], [88, (152, 30, 255)], [89, (107, 0, 240)], [90, (104, 0, 223)], [91, (103, 0, 206)], [92, (101, 0, 190)], [93, (101, 0, 182)], [94, (100, 0, 174)], [95, (101, 0, 169)], [96, (99, 1, 166)], [97, (101, 1, 162)], [98, (100, 0, 158)], [99, (140, 17, 255)], [100, (159, 35, 255)], [101, (188, 61, 255)], [102, (252, 90, 253)], [103, (255, 78, 148)], [104, (255, 111, 74)], [105, (255, 169, 94)], [106, (255, 191, 109)], [107, (255, 194, 113)], [108, (255, 194, 113)], [109, (255, 194, 113)], [110, (255, 194, 113)], [111, (255, 194, 113)], [112, (255, 194, 113)], [113, (255, 194, 113)], [114, (255, 194, 113)], [115, (255, 194, 113)], [116, (255, 194, 113)], [117, (255, 194, 113)], [118, (255, 194, 113)], [119, (255, 194, 113)], [120, (255, 194, 113)], [121, (255, 194, 113)], [122, (255, 194, 113)], [123, (255, 194, 113)], [124, (255, 194, 113)], [125, (255, 194, 113)], [126, (253, 191, 108)], [127, (255, 176, 99)], [128, (255, 153, 87)], [129, (253, 114, 73)]], [[0, (63, 30, 85)], [1, (70, 34, 82)], [2, (78, 38, 75)], [3, (80, 33, 67)], [4, (75, 21, 47)], [5, (73, 5, 26)], [6, (73, 0, 19)], [7, (71, 0, 16)], [8, (68, 0, 13)], [9, (68, 0, 13)], [10, (68, 0, 13)], [11, (69, 1, 16)], [12, (72, 0, 22)], [13, (75, 15, 43)], [14, (76, 31, 74)], [15, (68, 27, 85)], [16, (34, 1, 82)], [17, (26, 0, 87)], [18, (21, 0, 91)], [19, (14, 0, 97)], [20, (7, 0, 106)], [21, (0, 1, 119)], [22, (0, 5, 127)], [23, (0, 9, 136)], [24, (0, 21, 138)], [25, (0, 32, 132)], [26, (0, 41, 121)], [27, (0, 45, 95)], [28, (0, 37, 63)], [29, (3, 16, 32)], [30, (10, 0, 27)], [31, (34, 0, 39)], [32, (50, 0, 49)], [33, (63, 0, 55)], [34, (76, 0, 65)], [35, (95, 0, 82)], [36, (116, 1, 105)], [37, (152, 1, 158)], [38, (188, 1, 206)], [39, (228, 1, 254)], [40, (255, 1, 249)], [41, (255, 0, 220)], [42, (255, 0, 220)], [43, (250, 1, 217)], [44, (220, 1, 191)], [45, (209, 0, 180)], [46, (196, 0, 170)], [47, (201, 0, 171)], [48, (196, 0, 86)], [49, (213, 116, 1)], [50, (205, 121, 0)], [51, (198, 122, 0)], [52, (196, 125, 1)], [53, (190, 126, 0)], [54, (186, 129, 0)], [55, (186, 128, 2)], [56, (182, 127, 0)], [57, (181, 131, 0)], [58, (181, 130, 2)], [59, (180, 129, 1)], [60, (178, 131, 1)], [61, (203, 108, 0)], [62, (203, 106, 0)], [63, (201, 104, 1)], [64, (200, 98, 0)], [65, (196, 91, 0)], [66, (195, 78, 0)], [67, (184, 53, 0)], [68, (179, 28, 1)], [69, (178, 3, 0)], [70, (168, 1, 47)], [71, (149, 1, 85)], [72, (112, 0, 72)], [73, (81, 0, 45)], [74, (59, 0, 28)], [75, (47, 0, 18)], [76, (56, 1, 24)], [77, (86, 0, 49)], [78, (115, 0, 77)], [79, (159, 0, 116)], [80, (165, 9, 132)], [81, (75, 28, 80)], [82, (75, 26, 58)], [83, (71, 3, 28)], [84, (68, 0, 15)], [85, (68, 0, 13)], [86, (66, 0, 12)], [87, (150, 1, 85)], [88, (185, 0, 130)], [89, (185, 1, 135)], [90, (185, 1, 135)], [91, (188, 0, 138)], [92, (191, 0, 140)], [93, (202, 0, 150)], [94, (216, 0, 161)], [95, (231, 1, 162)], [96, (244, 0, 152)], [97, (255, 1, 131)], [98, (255, 0, 101)], [99, (254, 12, 208)], [100, (255, 24, 228)], [101, (238, 26, 224)], [102, (217, 37, 206)], [103, (126, 32, 106)], [104, (51, 38, 48)], [105, (64, 38, 67)], [106, (77, 38, 69)], [107, (74, 20, 46)], [108, (73, 0, 17)], [109, (71, 0, 16)], [110, (68, 0, 15)], [111, (68, 0, 15)], [112, (69, 0, 18)], [113, (66, 0, 27)], [114, (75, 25, 62)], [115, (79, 16, 43)], [116, (72, 0, 22)], [117, (71, 0, 16)], [118, (68, 0, 13)], [119, (68, 0, 13)], [120, (71, 0, 16)], [121, (72, 0, 18)], [122, (76, 12, 38)], [123, (75, 22, 50)], [124, (79, 39, 74)], [125, (72, 35, 79)], [126, (57, 29, 78)], [127, (40, 23, 75)], [128, (28, 22, 68)], [129, (33, 30, 61)]]]

speed = 5000   # in %

def illuminate_all_pos(calc_colors):
        for [pos, col] in calc_colors:
                strip.setPixelColor(pos, Color(col[0], col[1], col[2]))
        strip.show()

def shift(img_gradient, shifter):
    calc_color = []
    for j in range(0, len(img_gradient)):
        color = img_gradient[j][1]

        current_LED_num = j + shifter

        if current_LED_num > LED_COUNT-1:
            current_LED_num = current_LED_num % LED_COUNT
        calc_color.append([current_LED_num, color])

    return calc_color

# fade between colors
def fade_gradient(strip, col_map_1, col_map_2, speed):
    fade_dist =  45
    for counter in range(0, fade_dist):
        col_map_inter = []
        for led_count, _ in enumerate(col_map_1):
                R_inter = int(col_map_1[led_count][1][0] + counter/fade_dist*(col_map_2[led_count][1][0] - col_map_1[led_count][1][0]))
                G_inter = int(col_map_1[led_count][1][1] + counter/fade_dist*(col_map_2[led_count][1][1] - col_map_1[led_count][1][1]))
                B_inter = int(col_map_1[led_count][1][2] + counter/fade_dist*(col_map_2[led_count][1][2] - col_map_1[led_count][1][2]))
                ins = [col_map_1[led_count][0], (R_inter, G_inter, B_inter)]
                col_map_inter.append(ins)
        illuminate_all_pos(col_map_inter)
        time.sleep(0.5/(speed/100))

# gradient animation functions
def rotate_gradient(strip, img_gradient, speed):
    bright = 255
    col_map_old = []
    for k in range(0, LED_COUNT):
        col_map_old = shift(img_gradient, k)
        col_map_new = copy.deepcopy(col_map_old)

        col_map_new.append(col_map_new.pop(0))
        for en_counter, entry in enumerate(col_map_new):
                col_map_new[en_counter][0] = col_map_old[en_counter][0]
        fade_gradient(strip, col_map_new, col_map_old, speed*100)

# Define functions which animate LEDs in various ways.
def colorWipe(strip, color, wait_ms=50):
    """Wipe color across display a pixel at a time."""
    for i in range(strip.numPixels()):
        strip.setPixelColor(i, color)
        strip.show()
        time.sleep(wait_ms/1000.0)

# Main program logic follows:
if __name__ == '__main__':
    # Process arguments
    parser = argparse.ArgumentParser()
    parser.add_argument('-c', '--clear', action='store_true', help='clear the display on exit')
    args = parser.parse_args()

    # Create NeoPixel object with appropriate configuration.
    strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)
    # Intialize the library (must be called once before other functions).
    strip.begin()

    print ('Press Ctrl-C to quit.')
    if not args.clear:
        print('Use "-c" argument to clear LEDs on exit')

    i=0

    try:
        color_maps_li = gradient_maps_list
        fade_gradient(strip, empty_map, gradient_map_original, speed/3)
        while True:
            for map_counter, c_map in enumerate(color_maps_li):
                rotate_gradient(strip, gradient_map_original, speed)
                fade_gradient(strip, gradient_map_original, color_maps_li[map_counter], speed)
                rotate_gradient(strip, color_maps_li[map_counter], speed)
                fade_gradient(strip, color_maps_li[map_counter], gradient_map_original, speed)

    except KeyboardInterrupt:
        if args.clear:
            colorWipe(strip, Color(0,0,0), 10)


text:
import pandas as pd
import numpy as np
import sys

# > > > Load Input Data [DYNAMIC INPUTS] < < <
LoadData = pd.read_csv('C:/UMI/temp/Loads.csv')
Output = LoadData #Reformatted Kuwait output to bypass the reformat section
WeatherData = pd.read_csv('C:/UMI/temp/DryBulbData.csv')

# > > > User-specified Parameters [DYNAMIC INPUTS] < < <
Cost_Electricity = float(sys.argv[1]) #Generation cost per kWh Source: https://www.oxfordenergy.org/wpcms/wp-content/uploads/2014/04/MEP-9.pdf
Price_NaturalGas = float(sys.argv[2]) #Dollars per kWh
Emissions_ElectricGeneration = float(sys.argv[3]) #Metric ton CO2 per kWh produced
Effic_PowerGen = float(sys.argv[6]) #Average thermal efficiency of electrical generation in Kuwait
Losses_Transmission = float(sys.argv[4]) #Electrical transmission losses https://www.eia.gov/tools/faqs/faq.php?id=105&t=3
Losses_Heat_Hydronic = float(sys.argv[5]) #Heat transfer losses from hydronic distribution system

# ...................................................................

# Internal Parameters
CW_Delta = 11 # Difference beween CWS and CWR in degrees celsius
kWhPerTherm = 29.3 #kwh/therm
Emissions_NG_Combustion_therm = 0.005302 #Metric ton CO2 per therm of NG
Emissions_NG_Combustion_kWh = Emissions_NG_Combustion_therm / kWhPerTherm
FanPwrCoolRatio = 0 # 34.0/27.0 removed because assuming fan energy ~constant for all cases

# CWR Calculation Coefficients
c1_CWR = 28.27
c2_CWR = 5.57E-04
c3_CWR = 1.63E-01

# Gas Turbine
Effic_CCHP_Electrical = 0.40
HeatRecovery = 0.8
Ratio_HeattoPower = (1 - Effic_CCHP_Electrical)*HeatRecovery/Effic_CCHP_Electrical
MinimumLoad_GasTurbine = 0.40

c1_GT = -0.00006343
c2_GT = 0.0137
c3_GT = 0.2626

# New style, low-temperature Boiler
Size_Boiler = 15 #Nominal rated capacity of the boiler [kW] (size not specifed by EnergyPlus)
Efficiency_Boiler_Nominal = 0.8
MinPLR_Boiler = 0.10

# Cubic coeffcients
c1 = 0.83888652
c2 = 0.132579019
c3 = -0.17028503
c4 = 0.047468326

# District Equipment Parameters
Size_DistrictBoiler = 2500 # kw Based on 8400 MBH boiler at MP
Size_ElectricCentrifugalChiller_Nominal = 2567.1 #nominal size of the chiller in kW
MinPLR_CentrifugalChiller = 0.11
CoP_Chiller_Centrifugal = 11.77
CHWS_T = 4.44 #C (40 F)
Power_CentrifugalChiller_Nominal = Size_ElectricCentrifugalChiller_Nominal/CoP_Chiller_Centrifugal

c1_ECC_CapFunT = 3.15E-01
c2_ECC_CapFunT = 7.67E-03
c3_ECC_CapFunT = -4.35E-03
c4_ECC_CapFunT = 5.00E-02
c5_ECC_CapFunT = -1.24E-03
c6_ECC_CapFunT = 3.16E-03

c1_ECC_EIRFunT = 3.65E-01
c2_ECC_EIRFunT = -3.71E-02
c3_ECC_EIRFunT = -7.45E-04
c4_ECC_EIRFunT = 4.59E-02
c5_ECC_EIRFunT = 1.72E-04
c6_ECC_EIRFunT = -3.52E-04

c1_ECC_EIRFPLR = -2.96E-01
c2_ECC_EIRFPLR = 2.59E-02
c3_ECC_EIRFPLR = 3.92E-05
c4_ECC_EIRFPLR = 7.44E-01
c5_ECC_EIRFPLR = 3.53E-01
c6_ECC_EIRFPLR = -2.80E-02
c7_ECC_EIRFPLR = 0.00E+00
c8_ECC_EIRFPLR = 2.25E-01
c9_ECC_EIRFPLR = 0.00E+00
c10_ECC_EIRFPLR = 0.00E+00

Size_CT_Nominal = 0.011 * Size_ElectricCentrifugalChiller_Nominal

# Cooling Tower Coefficients
a1_ct = 0.8603
a2_ct = 0.2045
a3_ct = -0.0623
a4_ct = 0.0026

# Pumping energy coefficients (pumping energy as a fraction of heat delivered)
PumpCoolFraction = 0.02
PumpHeatFraction = 0.005

# Absorption Chiller
Size_AbsorptionChiller_Nominal = 231 #nominal size of the chiller in kW
CoP_Chiller_Absorption = 1.39

#CapFunT Coefficients (biquadratic)
a1_ac = -1.15E+00
a2_ac = -8.01E-02
a3_ac = -9.45E-03
a4_ac = 2.10E-01
a5_ac = -5.67E-03
a6_ac = 9.44E-03

#TeFIRFt Coefficients (biquadratic)
b1 = 1.31E+00
b2 = -1.59E-02
b3 = 7.74E-04
b4 = -1.96E-02
b5 = 3.78E-04
b6 = 5.58E-05

#TeFIRfPLR Coefficients (quadratic)
c1_ac = 2.63E-02
c2_ac = 6.78E-01
c3_ac = 2.74E-01

# ...................................................................

# Update Output dataframe
Output['TotalHeating'] = Output['SDL/Heating'] + Output['SDL/Domestic Hot Water']
Output['Electricity'] = Output['SDL/Equipment'] + Output['SDL/Lighting']
Output = Output.join(WeatherData['DB'], on='Hour')

# ...................................................................

# Identify peak demands for cooling, heating, and electricity
PeakCooling = Output.groupby('Hour')['SDL/Cooling'].sum()
PeakCooling.sort_values(inplace=True, ascending=False)
print '\n Peak Cooling Demand (kW):', PeakCooling[:1].round()

PeakHeating = Output.groupby('Hour')['TotalHeating'].sum()
PeakHeating.sort_values(inplace=True, ascending=False)
print '\n Peak Heating Demand (kW):', PeakHeating[:1].round()

PeakElectricity = Output.groupby('Hour')['Electricity'].sum()
PeakElectricity.sort_values(inplace=True, ascending=False)
print '\n Peak Non-HVAC Electricity Demand(kW):', PeakElectricity[:1].round()

# ...................................................................

# Identify peak demands for each building for cooling, heating, and electricity
CoolingMax = Output.groupby('Building')['SDL/Cooling'].max()
Output = Output.join(CoolingMax, on='Building', rsuffix='Max')

print 'Cooling max :', CoolingMax[:1]

HeatingMax = Output.groupby('Building')['TotalHeating'].max()
Output = Output.join(HeatingMax, on='Building', rsuffix='Max')

ElectricMax = Output.groupby('Building')['Electricity'].max()
Output = Output.join(ElectricMax, on='Building', rsuffix='Max')

# ...................................................................

# print "\nScenario 03: Grid + District Heating and Cooling Plant"

NumDistrictBoilers = np.ceil(max(PeakHeating) * (1 + Losses_Heat_Hydronic) /Size_DistrictBoiler)

DHC = pd.DataFrame()

DHC['Load_HourlyHeating'] = Output.groupby('Hour')['TotalHeating'].sum()
DHC['Drybulb'] = Output['DB']

DHC['PLR_DistrictBoiler'] = np.where(DHC['Load_HourlyHeating']<=0, 0, (DHC['Load_HourlyHeating']/NumDistrictBoilers)/Size_DistrictBoiler)
DHC['PLR_DistrictBoiler'] = np.where(DHC['PLR_DistrictBoiler'] < MinPLR_Boiler, MinPLR_Boiler, DHC['PLR_DistrictBoiler']) # Added in v22
DHC['Efficiency_DistrictBoiler_Modifier'] = c1 + c2 * DHC['PLR_DistrictBoiler'] + c3 * DHC['PLR_DistrictBoiler']**2 + c4 * DHC['PLR_DistrictBoiler']**3
DHC['Energy_DistrictBoiler'] = DHC['Load_HourlyHeating'] * (1 + Losses_Heat_Hydronic) /(Efficiency_Boiler_Nominal * DHC['Efficiency_DistrictBoiler_Modifier'])

Energy_NaturalGas_SC03 = sum(DHC['Load_HourlyHeating'] * (1 + Losses_Heat_Hydronic) /(Efficiency_Boiler_Nominal * DHC['Efficiency_DistrictBoiler_Modifier']))

DHC['COP_DistrictBoiler'] = np.where(DHC['Energy_DistrictBoiler']<=0,0,(DHC['Load_HourlyHeating'] * (1 + Losses_Heat_Hydronic)) / DHC['Energy_DistrictBoiler'])

NumChillers = np.ceil(max(PeakCooling) * (1+ Losses_Heat_Hydronic) /Size_ElectricCentrifugalChiller_Nominal)
DHC['Load_HourlyCooling'] = (Output.groupby('Hour')['SDL/Cooling'].sum()) * (1 + Losses_Heat_Hydronic)
DHC['CoolingLoad/ChillerSize'] = DHC['Load_HourlyCooling']/Size_ElectricCentrifugalChiller_Nominal
DHC['MinNumChillers'] = np.ceil(DHC['CoolingLoad/ChillerSize'])
DHC['PLR'] = np.where(DHC['Load_HourlyCooling']<=0, 0, (DHC['Load_HourlyCooling']/DHC['MinNumChillers'])/Size_ElectricCentrifugalChiller_Nominal)
DHC['PLR'] = np.where(DHC['PLR']<MinPLR_CentrifugalChiller, MinPLR_CentrifugalChiller, (DHC['Load_HourlyCooling']/DHC['MinNumChillers'])/Size_ElectricCentrifugalChiller_Nominal)

DHC['CWR_T'] = c1_CWR+c2_CWR*DHC['Drybulb']**2+c3_CWR*DHC['Drybulb'] * DHC['PLR']

DHC['CapFunT'] = c1_ECC_CapFunT+c2_ECC_CapFunT*CHWS_T + c3_ECC_CapFunT*CHWS_T**2 + c4_ECC_CapFunT*DHC['CWR_T']+c5_ECC_CapFunT*DHC['CWR_T']**2 + c6_ECC_CapFunT*CHWS_T*DHC['CWR_T']
DHC['EIRFunT'] = c1_ECC_EIRFunT+c2_ECC_EIRFunT*CHWS_T + c3_ECC_EIRFunT*CHWS_T**2 + c4_ECC_EIRFunT*DHC['CWR_T']+c5_ECC_EIRFunT*DHC['CWR_T']**2 + c6_ECC_EIRFunT*CHWS_T*DHC['CWR_T']
DHC['EIRFunPLR'] = c1_ECC_EIRFPLR+c2_ECC_EIRFPLR*DHC['CWR_T'] + c3_ECC_EIRFPLR*DHC['CWR_T']**2 + c4_ECC_EIRFPLR*DHC['PLR']+c5_ECC_EIRFPLR*DHC['PLR']**2 + c6_ECC_EIRFPLR*DHC['CWR_T']*DHC['PLR']+c7_ECC_EIRFPLR*DHC['CWR_T']**3+c8_ECC_EIRFPLR*DHC['PLR']**3+c9_ECC_EIRFPLR*DHC['CWR_T']**2*DHC['PLR']+c10_ECC_EIRFPLR*DHC['CWR_T']*DHC['PLR']**2

DHC['Energy_CentrifugalChiller'] = Power_CentrifugalChiller_Nominal * DHC['CapFunT'] * DHC['EIRFunT'] * DHC['EIRFunPLR'] * DHC['MinNumChillers']
DHC['COP_CentrifugalChiller'] = np.where(DHC['Energy_CentrifugalChiller']<=0,0, DHC['Load_HourlyCooling']/DHC['Energy_CentrifugalChiller'])

DHC['CoolingTowerPower'] = np.where(DHC['Load_HourlyCooling']<=0,0, Size_CT_Nominal * DHC['MinNumChillers'] * a1_ct * DHC['PLR']**3 + a2_ct * DHC['PLR']**2 -a3_ct * DHC['PLR'] + a4_ct)
Energy_CoolingTowers_SC03 = sum(DHC['CoolingTowerPower']) * (1 + Losses_Transmission) / Effic_PowerGen

DHC['FanPower'] = DHC['Energy_CentrifugalChiller'] * FanPwrCoolRatio
Energy_Fans_SC03 = sum(DHC['FanPower']) * (1 + Losses_Transmission) / Effic_PowerGen

DHC['PumpPower'] = DHC['Load_HourlyCooling'] * PumpCoolFraction + DHC['Load_HourlyHeating'] * (1+Losses_Heat_Hydronic) * PumpHeatFraction
Energy_Pumps_SC03 = sum(DHC['PumpPower']) * (1 + Losses_Transmission) / Effic_PowerGen

Energy_CoolingElectricity_SC03 = sum(DHC['Energy_CentrifugalChiller']) * (1 + Losses_Transmission) / Effic_PowerGen

SC03_AvgCoolingCOP = sum(Output['SDL/Cooling']) / ((Energy_CoolingElectricity_SC03 * (1 + Losses_Heat_Hydronic)) + Energy_CoolingTowers_SC03) # Includes chiller and CT energy in denom
SC03_AvgHeatingCOP = sum(Output['TotalHeating']) / Energy_NaturalGas_SC03

# ...................................................................

print "\nScenario 04: CCHP Satisfies Electricity, Heating, and Cooling Demands"

CCHP = pd.DataFrame()
CCHP['Load_HourlyElectricity'] = (Output.groupby('Hour')['Electricity'].sum())
CCHP['Load_HourlyHeating'] = Output.groupby('Hour')['TotalHeating'].sum()
CCHP['Load_HourlyCooling'] = (Output.groupby('Hour')['SDL/Cooling'].sum()) * (1 + Losses_Heat_Hydronic)
CCHP['Drybulb'] = Output['DB']
CCHP['CWR_T'] = DHC['CWR_T']
CCHP['CHWS_T'] = CHWS_T

Size_GasTurbine = max(CCHP['Load_HourlyElectricity']) #Rated electrical output of gas turbine based on the peak loads of the city

CCHP['GT_PLR'] = CCHP['Load_HourlyElectricity'] / Size_GasTurbine
CCHP['ModGT_PLR'] = np.where(CCHP['GT_PLR']<MinimumLoad_GasTurbine, MinimumLoad_GasTurbine, CCHP['Load_HourlyElectricity'] / Size_GasTurbine)

CCHP['GT_Efficiency'] = (c1_GT*(CCHP['ModGT_PLR']*100)**2+c2_GT*(CCHP['ModGT_PLR']*100)+c3_GT)*Effic_CCHP_Electrical
CCHP['Heat/Power'] = (1 - CCHP['GT_Efficiency'])*0.8 / CCHP['GT_Efficiency']
CCHP['GT_InputFuelActual'] = CCHP['ModGT_PLR'] * Size_GasTurbine / CCHP['GT_Efficiency']
Energy_GT = sum(CCHP['GT_InputFuelActual'])

CCHP['GT_InputFuelOptimal'] = CCHP['Load_HourlyElectricity'] / CCHP['GT_Efficiency']
CCHP['ExcessElectricity'] = (CCHP['GT_InputFuelActual'] - CCHP['GT_InputFuelOptimal']) * CCHP['GT_Efficiency']
ExcessElecValue = sum(CCHP['ExcessElectricity']) * Cost_Electricity # added in v22

CCHP['UseableHeat'] = CCHP['ModGT_PLR'] * CCHP['GT_Efficiency'] * Size_GasTurbine * CCHP['Heat/Power']

CCHP['HeatRemaining'] = np.where(CCHP['UseableHeat'] - CCHP['Load_HourlyHeating']<0,0,CCHP['UseableHeat'] - CCHP['Load_HourlyHeating'])
CCHP['HeatSupplementary'] = np.where(CCHP['UseableHeat'] - CCHP['Load_HourlyHeating']>=0,0,CCHP['Load_HourlyHeating'] - CCHP['UseableHeat'])
HeatSupp = sum(CCHP['HeatSupplementary'])

Size_Boiler_CCHP = np.ceil(max(CCHP['HeatSupplementary']))

CCHP['PLR_CCHPBoiler'] = np.where(CCHP['HeatSupplementary']<=0, 0, CCHP['HeatSupplementary'] / Size_Boiler_CCHP)
CCHP['PLR_CCHPBoiler'] = np.where(CCHP['PLR_CCHPBoiler'] < MinPLR_Boiler, MinPLR_Boiler, CCHP['PLR_CCHPBoiler']) # Added in v22
CCHP['Efficiency_CCHPBoiler_Modifier'] = c1 + c2 * CCHP['PLR_CCHPBoiler'] + c3 * CCHP['PLR_CCHPBoiler']**2 + c4 * CCHP['PLR_CCHPBoiler']**3

Energy_CCHPBoiler = sum(CCHP['HeatSupplementary'] * (1 + Losses_Heat_Hydronic) /(Efficiency_Boiler_Nominal * CCHP['Efficiency_CCHPBoiler_Modifier']))

CCHP['GTforHeating'] = np.where(CCHP['UseableHeat'] - CCHP['Load_HourlyHeating']<0,CCHP['UseableHeat'],CCHP['Load_HourlyHeating']) #Amount of heat from GT used for heating
InputEnergyGTforHeating = sum(CCHP['GTforHeating'])/(Ratio_HeattoPower * Effic_CCHP_Electrical) #Input energy to GTo to produce the heat needed for CCHP['GTforHeating']

# ---------------------

# 00 Initialization of COP and while loop set up for absorption chiller ---
CCHP['COP_AbsChiller'] = CoP_Chiller_Absorption * 0.75 #Initial guess for COP
CCHP['PLR_AbsChiller'] = 0.7
CCHP['COP_threshold'] = 0.01
CCHP['PLR_threshold'] = 0.01
CCHP['COP_delta'] = 0.4
CCHP['PLR_delta']  = 0.3
CCHP['COP_old'] = 0.1
CCHP['PLR_old'] = 0.1

#--------------------------

for index, row in CCHP.iterrows():

    while row['COP_delta'] > row['COP_threshold'] and row['PLR_delta'] > row['PLR_threshold']:

        # Calculate cooling capacity based on COP and heat remaining
        row['AbsCoolingCapacity'] = row['HeatRemaining'] * row['COP_AbsChiller']
        row['Load_AbsChiller'] = np.where(row['AbsCoolingCapacity'] >= row['Load_HourlyCooling'], row['Load_HourlyCooling'], row['AbsCoolingCapacity'])
        row['NumAbsChillers'] = np.where((row['Load_AbsChiller'] / Size_AbsorptionChiller_Nominal)<1,1, row['Load_AbsChiller'] / Size_AbsorptionChiller_Nominal)
        row['NumAbsChillers'] = np.ceil(row['NumAbsChillers'])

        # 01 PLR calculated based on initialized COP
        row['PLR_AbsChiller'] = np.where(row['AbsCoolingCapacity'] >= row['Load_HourlyCooling'], row['Load_HourlyCooling'] / (row['NumAbsChillers'] * Size_AbsorptionChiller_Nominal), row['AbsCoolingCapacity'] / (row['NumAbsChillers'] * Size_AbsorptionChiller_Nominal))

        # Equations needed to calculate COP
        row['CapFunT'] = a1_ac + a2_ac * CHWS_T + a3_ac * CHWS_T**2 + a4_ac * (row['CWR_T']-CW_Delta) + a5_ac * (row['CWR_T']-CW_Delta)**2 + a6_ac * CHWS_T * (row['CWR_T']-CW_Delta)
        row['TeFIRFt'] = b1 + b2*CHWS_T + b3*CHWS_T**2 + b4*(row['CWR_T']-CW_Delta) + b5 * (row['CWR_T']-CW_Delta)**2 + b6 * CHWS_T * (row['CWR_T']-CW_Delta)
        row['TeFIRfPLR'] = c1_ac + c2_ac*row['PLR_AbsChiller'] + c3_ac*row['PLR_AbsChiller']**2
        row['X_AbsChiller'] = row['CapFunT'] * row['TeFIRFt']  * row['TeFIRfPLR']
        row['Energy_AbsChiller'] = Size_AbsorptionChiller_Nominal * row['X_AbsChiller'] * row['NumAbsChillers']
        row['COP_AbsChiller'] = row['Load_AbsChiller'] / row['Energy_AbsChiller']
        row['CoolingSupp'] = np.where(row['AbsCoolingCapacity'] >= row['Load_HourlyCooling'], 0, row['Load_HourlyCooling'] - row['AbsCoolingCapacity']) # Move outside of loop

        # Finding the difference between the current and former COP and PLR calculations
        row['COP_delta'] = abs(row['COP_AbsChiller'] - row['COP_old'])
        row['PLR_delta'] = abs(row['PLR_AbsChiller'] - row['PLR_old'])

        # Retaining the last values of COP and PLR
        row['COP_old'] = row['COP_AbsChiller']
        row['PLR_old'] = row['PLR_AbsChiller']

    CCHP.set_value(index,'COP_AbsChiller',row['COP_AbsChiller'])
    CCHP.set_value(index,'PLR_AbsChiller',row['PLR_AbsChiller'])
    # CCHP.set_value(index,'AbsCoolingCapacity',row['AbsCoolingCapacity'])
    CCHP.set_value(index,'CoolingSupp',row['CoolingSupp']) # This output is needed for the electric centrifugal model
    # CCHP.set_value(index,'Load_AbsChiller',row['Load_AbsChiller'])
    CCHP.set_value(index,'NumAbsChillers',row['NumAbsChillers'])
    # CCHP.set_value(index, 'X_AbsChiller',row['X_AbsChiller'])
    # CCHP.set_value(index, 'Energy_AbsChiller',row['Energy_AbsChiller'])

# ------- Supplemental Cooling by an Electric Centrifugal Chiller Begin ------- #
NumElectricChillers = np.ceil(max(CCHP['CoolingSupp'])/Size_ElectricCentrifugalChiller_Nominal)

CCHP['CoolingLoad/ChillerSize'] = CCHP['CoolingSupp']/Size_ElectricCentrifugalChiller_Nominal
CCHP['MinNumChillers'] = np.ceil(CCHP['CoolingLoad/ChillerSize'])
CCHP['PLR_ElectricChiller'] = np.where(CCHP['CoolingSupp']<=0, 0, (CCHP['CoolingSupp']/ CCHP['MinNumChillers'])/Size_ElectricCentrifugalChiller_Nominal)
CCHP['PLR_ElectricChiller'] = np.where(CCHP['PLR_ElectricChiller'] < MinPLR_CentrifugalChiller, MinPLR_CentrifugalChiller, np.where(CCHP['CoolingSupp']<=0, 0, (CCHP['CoolingSupp']/ CCHP['MinNumChillers'])/Size_ElectricCentrifugalChiller_Nominal))

CCHP['CapFunT'] = c1_ECC_CapFunT+c2_ECC_CapFunT*CHWS_T + c3_ECC_CapFunT*CHWS_T**2 + c4_ECC_CapFunT*CCHP['CWR_T']+c5_ECC_CapFunT*CCHP['CWR_T']**2 + c6_ECC_CapFunT*CHWS_T*CCHP['CWR_T']
CCHP['EIRFunT'] = c1_ECC_EIRFunT+c2_ECC_EIRFunT*CHWS_T + c3_ECC_EIRFunT*CHWS_T**2 + c4_ECC_EIRFunT*CCHP['CWR_T']+c5_ECC_EIRFunT*CCHP['CWR_T']**2 + c6_ECC_EIRFunT*CHWS_T*CCHP['CWR_T']
CCHP['EIRFunPLR'] = c1_ECC_EIRFPLR+c2_ECC_EIRFPLR*CCHP['CWR_T'] + c3_ECC_EIRFPLR*CCHP['CWR_T']**2 + c4_ECC_EIRFPLR*CCHP['PLR_ElectricChiller']+c5_ECC_EIRFPLR*CCHP['PLR_ElectricChiller']**2 + c6_ECC_EIRFPLR*CCHP['CWR_T']*CCHP['PLR_ElectricChiller']+c7_ECC_EIRFPLR*CCHP['CWR_T']**3+c8_ECC_EIRFPLR*CCHP['PLR_ElectricChiller']**3+c9_ECC_EIRFPLR*CCHP['CWR_T']**2*CCHP['PLR_ElectricChiller']+c10_ECC_EIRFPLR*CCHP['CWR_T']*CCHP['PLR_ElectricChiller']**2

CCHP['Energy_CentrifugalChiller'] = Power_CentrifugalChiller_Nominal * CCHP['CapFunT'] * CCHP['EIRFunT'] * CCHP['EIRFunPLR'] * CCHP['MinNumChillers']
CCHP['FanPower'] = DHC['FanPower']
CCHP['PumpPower'] = DHC['PumpPower']

CCHP['COP_CentrifugalChiller'] = np.where(CCHP['Energy_CentrifugalChiller']<=0,0, CCHP['CoolingSupp'] / CCHP['Energy_CentrifugalChiller'])
CCHP['CoolingTowerPower'] = Size_CT_Nominal * CCHP['MinNumChillers'] * a1_ct * CCHP['PLR_ElectricChiller']**3 + a2_ct * CCHP['PLR_ElectricChiller']**2 - a3_ct * CCHP['PLR_ElectricChiller']* + a4_ct

Energy_CoolingSuppElectricity_SC04 = sum(CCHP['Energy_CentrifugalChiller']) * (1 + Losses_Transmission) / Effic_PowerGen

Energy_Fans_SC04 = Energy_Fans_SC03
Energy_Pumps_SC04 = Energy_Pumps_SC03
Energy_CoolingTowers_SC04 = Energy_CoolingTowers_SC03

Energy_SC04 = Energy_GT + Energy_CCHPBoiler + Energy_CoolingSuppElectricity_SC04 + Energy_Fans_SC04 + Energy_Pumps_SC04 + Energy_CoolingTowers_SC04

InputEnergyAbsChiller = (sum(Output['SDL/Cooling']) - sum(CCHP['CoolingSupp']))/CoP_Chiller_Absorption
SC04_AvgCoolingCOP = sum(Output['SDL/Cooling']) / (InputEnergyAbsChiller + Energy_CoolingSuppElectricity_SC04 + Energy_CoolingTowers_SC04) #Excludes pumping losses
SC04_AvgHeatingCOP = sum(Output['TotalHeating']) / (Energy_CCHPBoiler + InputEnergyGTforHeating)

print "Annual input energy for gas turbine:", Energy_GT
print "Annual input energy for supplemental heating:", Energy_CCHPBoiler
print "Annual input energy for supplemental cooling:", Energy_CoolingSuppElectricity_SC04
print "Annual input energy for cooling towers:", Energy_CoolingTowers_SC04
print "Annual input energy for pumps:", Energy_Pumps_SC04
print "Annual input energy required (kWh):", Energy_SC04

print "Average Cooling COP:", SC04_AvgCoolingCOP
print "Average Heating COP:", SC04_AvgHeatingCOP

Cost_Electricity_SC04 = (Energy_CoolingSuppElectricity_SC04 * Effic_PowerGen) * Cost_Electricity
Cost_NG_SC04 = (Energy_GT + Energy_CCHPBoiler) * Price_NaturalGas
Cost_SC04 = Cost_Electricity_SC04 + Cost_NG_SC04

print "Annual cost (USD):" , Cost_SC04
print "Surplus electricity value (USD):" , ExcessElecValue # added v22
print "Updated annual cost (USD):" , Cost_SC04 - ExcessElecValue # added v22

Emissions_Electricity_SC04 = (Energy_CoolingSuppElectricity_SC04 * Effic_PowerGen) * Emissions_ElectricGeneration
Emissions_NG_SC04 = (Energy_GT + Energy_CCHPBoiler) * Emissions_NG_Combustion_kWh
Emissions_SC04 = Emissions_Electricity_SC04 + Emissions_NG_SC04
print "Annual carbon emissions (Metric Tons):", Emissions_SC04

# Results = pd.DataFrame()
# Results['Scenario04'] = Energy_Grid_SC03, Energy_NaturalGas_SC03, Energy_CoolingElectricity_SC03, Energy_SC03, SC03_AvgCoolingCOP, SC03_AvgHeatingCOP, Cost_SC03, Emissions_SC03

CCHP['ElectricityConsumption'] =  (CCHP['Energy_CentrifugalChiller'] + CCHP['FanPower'] + CCHP['CoolingTowerPower'] + CCHP['PumpPower']) * (1 + Losses_Transmission)
CCHP['NaturalGasConsumption'] = CCHP['HeatSupplementary'] * (1 + Losses_Heat_Hydronic) /(Efficiency_Boiler_Nominal * CCHP['Efficiency_CCHPBoiler_Modifier']) + CCHP['GT_InputFuelActual']

# ...................................................................
# Export Data

# Output.to_csv('C:/UMI/temp/DHSimulationResults/SC04_Export_OutputDataFrame.csv')
DHC.to_csv('C:/UMI/temp/DHSimulationResults/SC04_Export_DHCDataFrame.csv')
CCHP.to_csv('C:/UMI/temp/DHSimulationResults/SC04_Export_CCHPDataFrame.csv')


text:
import numpy

from ltron.gym.components.ltron_gym_component import LtronGymComponent
from ltron.gym.spaces import SegmentationSpace

class DeduplicateTileMaskComponent(LtronGymComponent):
    def __init__(self,
        tile_width,
        tile_height,
        render_component,
        background=102,
    ):
        self.tile_width = tile_width
        self.tile_height = tile_height
        self.render_component = render_component

        assert self.render_component.width % self.tile_width == 0
        assert self.render_component.height % self.tile_height == 0
        self.width = self.render_component.width // self.tile_width
        self.height = self.render_component.height // self.tile_height

        self.observation_space = SegmentationSpace(self.width, self.height, 1)
        self.background = background

    def observe(self):
        frame = self.render_component.observation
        h, w, c = frame.shape
        modified_channels = frame != self.previous_frame
        modified_tiles = modified_channels.reshape(
            self.height, self.tile_height, self.width, self.tile_width, c)
        modified_tiles = numpy.moveaxis(modified_tiles, 2, 1)
        modified_tiles = modified_tiles.reshape(self.height, self.width, -1)
        self.observation = numpy.any(modified_tiles, axis=-1).reshape(
            self.height, self.width).astype(numpy.long)

        #import pdb
        #pdb.set_trace()

        self.previous_frame = frame

    def reset(self):
        self.previous_frame = self.background
        self.observe()
        return self.observation

    def step(self, action):
        self.observe()
        return self.observation, 0., False, None

    def get_state(self):
        return self.observation

    def set_state(self, state):
        self.observation = state
        return self.observation

max_stars_repo_name: aaronwalsman/ltron

max_issues_repo_name: aaronwalsman/ltron

max_forks_repo_name: aaronwalsman/ltron


text:
import csv
import fnmatch

import numpy as np
from natsort import natsorted

from .utils import getAreaID, getRegionID
import pandas as pd
from sklearn.tree import DecisionTreeClassifier

def getAreaClf(Routes):
    #get routes with only 1 zone change
    trainData = []
    for r in Routes:
        interaction = []
        firstStop = np.argsort(r.actual)[1]
        firstZoneID = r.stops[firstStop].zone_id
        firstRegion = getRegionID(firstZoneID)
        lastZoneID = ' '
        for s in np.argsort(r.actual)[1:]:
            currentZone = r.stops[s].zone_id
            currentRegion = getRegionID(currentZone)
            if currentRegion == firstRegion:
                interaction.append(currentZone)
                lastZoneID = currentZone
            else:
                break
        sourceZoneID = firstZoneID
        dstZoneID = lastZoneID
        firstStopArea = getAreaID(sourceZoneID)
        lastStopArea = getAreaID(dstZoneID)
        regionID = getRegionID(sourceZoneID)
        reverse = False
        temp = regionID.split('-')
        if firstStopArea > lastStopArea:
            reverse = True
        codeNew = int(str(hash(regionID))[1:5])
        trainData.append([temp[0],temp[1],codeNew,reverse,firstStopArea])
    trainDF = pd.DataFrame(trainData,columns  = ['Code','Number','CodeNew', 'Ascending',
                                                'Area'])
    features = ['CodeNew']
    X = trainDF[features]
    y = trainDF['Ascending']
    clf = DecisionTreeClassifier(class_weight='balanced')
    clf.fit(X,y)
    return clf

def getRegionClf(S1_Routes):
    uniqueList = []
    for testRoute in S1_Routes:
        sequence = list(np.argsort(testRoute.actual))

        regionIds = [getRegionID(testRoute.stops[s].zone_id) for s in sequence]
        values = list(pd.unique(regionIds))
        values.remove(' ')
        if len(values) > 1:
            uniqueList.append([values[0],values[-1]])
    trainData = []
    for src, dst in uniqueList:
        letter = src.split('-')[0]
        if src[0] == dst[0]:
            reverse = False
            if src > dst:
                reverse = True
            trainData.append([letter, reverse])
    trainDF = pd.DataFrame(trainData, columns=['Code', 'Ascending'])
    trainDF['CodeNew'] = [ord(x) - 64 for x in trainDF.Code]
    features = ['CodeNew']
    X = trainDF[features]
    y = trainDF['Ascending']
    clf = DecisionTreeClassifier(class_weight='balanced')
    clf.fit(X, y)
    return clf

def getRouteArea(route,regionCode,reverse = False):
    result = []
    for s in route.stops:
        if getRegionID(s.zone_id) == regionCode:
            result.append(getAreaID(s.zone_id))
    result = list(set(result))
    result = natsorted(result,  reverse=reverse)
    return result

def getRegionCode(route):
    zoneIds = [s.zone_id for s in route.stops]
    zoneIds.remove(None)
    RegionIds = [getRegionID(z) for z in zoneIds]
    RegionIds = pd.unique(RegionIds)
    R0 = pd.unique([r[0] for r in RegionIds])
    return R0, RegionIds

def getAreasFromRegion(stopZoneID,region):
    areaList = []
    for zone_id in stopZoneID:
        if getRegionID(zone_id) == region:
            areaList.append(getAreaID(zone_id))
    areaList = list(set(areaList))
    areaList.sort()
    return areaList

def getZoneNumber(zoneIDList,regionCode,AreaCode):
    result = []
    getzoneNum = lambda zoneID: zoneID.split('.')[1][:-1]
    key = regionCode +'.*' + AreaCode
    stopDict = {}

    for s in zoneIDList:
        if fnmatch.fnmatch(s,key):
            result.append(getzoneNum(s))
    result = list(set(result))
    result.sort()
    return result

def getSequence(route,RegionDirection,AreaDirection, ZoneDirection ):

    zoneIds = [s.zone_id for s in route.stops]
    zoneIds.remove(None)
    regionCodes = list(set([getRegionID(z) for z in zoneIds]))
    # print(regionCodes)
    regionCodes = natsorted(regionCodes, reverse=RegionDirection)
    usedAreas = []
    zoneIDNums = []
    RegionDict = {}
    for s in regionCodes:
        areas = getRouteArea(route, s, AreaDirection)
        if len(usedAreas) > 0:
            if usedAreas[-1] != areas[0]:
                AreaDirection = not AreaDirection
                areas = getRouteArea(route, s, AreaDirection)
        RegionDict[s] = areas
        for a in areas:
            usedAreas.append(a)
            zoneIDNums.append(getZoneNumber(zoneIds,s,a))

    zoneIDSequece = getSequenceZoneNumber(zoneIDNums, ZoneDirection)

    zoneIds = [s.zone_id for s in route.stops]

    optimalSequence = []
    zoneLength = []
    optimalSequence.append(route.depot)
    zoneLength.append(1)
    position = 0
    zoneIDList= []
    for s in regionCodes:
        areas = RegionDict[s]
        for a in areas:
            for z in zoneIDSequece[position]:
                key = f'{s}.{z}{a}'
                zoneIDList.append(key)
                indices = [i for i, x in enumerate(zoneIds) if x == key]
                optimalSequence.extend(indices)
                zoneLength.append(len(indices))
            position += 1
    optimalSequence.append(route.depot)
    zoneLength.append(1)

    return optimalSequence, zoneLength, zoneIDList

def getZoneAndAreaDirection(route,RegionClf,AreaClf):
    R0, RegionsIdsNew = getRegionCode(route)
    RegionsIdsNew = RegionsIdsNew.tolist()
    reverseRegion = False
    reverseArea = False

    # %%
    if len(RegionsIdsNew) == 1:
        codeNew = int(str(hash(RegionsIdsNew[0]))[1:5])
        reverseArea = AreaClf.predict(np.array([codeNew]).reshape(-1, 1))[0]

    elif len(R0) == 1:
        codeNew = ord(R0[0]) - 64
        reverseRegion = RegionClf.predict(np.array([codeNew]).reshape(-1, 1))[0]
        RegionsIdsNew = natsorted(RegionsIdsNew, key=lambda y: y.lower(), reverse=reverseRegion)
        region1 = RegionsIdsNew[0]
        region2 = RegionsIdsNew[1]
        stopZoneID = [s.zone_id for s in route.stops]
        stopZoneID.remove(None)
        A1 = getAreasFromRegion(stopZoneID, region1)
        A2 = getAreasFromRegion(stopZoneID, region2)
        if A1[0] == A2[0] or A1[0] == A2[-1]:
            reverseArea = True
        else:
            reverseArea = False
    # print(RegionsIdsNew)
    # print(reverseRegion)
    # print(reverseArea)
    return reverseRegion, reverseArea

def getSequenceZoneNumber(zoneidlist, direction):
    sequence = []
    result = []
    tempSeq = [i for i in zoneidlist]
    for c in tempSeq:
        if len(sequence) == 0:
            temp = sorted(c, reverse=direction)
            sequence.extend(temp)
            result.append(temp)
        else:
            if c[0] == sequence[-1]:
                sequence.extend(c)
                result.append(c)
            elif c[-1] == sequence[-1]:
                temp = sorted(c, reverse=True)
                sequence.extend(temp)
                result.append(temp)
            elif sequence[-1] == 2 and c[0] == 1:
                sequence.extend(c)
                result.append(c)
            elif len(c) == 1:
                sequence.extend(c)
                result.append(c)
            else:
                sequence.extend(c)
                result.append(c)
    return result


text:
"""Generates capacity diagrams for the bottleneck.

This method accepts as input a csv file containing the inflows and outflows
from several simulations as created by the file `examples/sumo/density_exp.py`,
e.g.

    1000, 978
    1000, 773
    1500, 1134
    ...

And then uses this data to generate a capacity diagram, with the x-axis being
the inflow rates and the y-axis is the outflow rate.

Usage
-----
::
    python capacity_diagram_generator.py </path/to/file>.csv
"""
import csv
from matplotlib import pyplot as plt
from matplotlib import rc
import numpy as np
import argparse

def import_data_from_csv(fp):
    r"""Import inflow/outflow data from the predefined csv file.

    Parameters
    ----------
    fp : string
        file path

    Returns
    -------
    dict
        "inflows": list of all the inflows \n
        "outflows" list of the outflows matching the inflow at the same index
    """
    inflows = []
    outflows = []
    with open(fp, 'rt') as csvfile:
        spamreader = csv.reader(csvfile)
        for row in spamreader:
            inflows.append(float(row[0]))
            outflows.append(float(row[1]))

    return {'inflows': inflows, 'outflows': outflows}

def get_capacity_data(data):
    r"""Compute the unique inflows and subsequent outflow statistics.

    Parameters
    ----------
    data : dict
        "inflows": list of all the inflows \n
        "outflows" list of the outflows matching the inflow at the same index

    Returns
    -------
    as_array
        unique inflows
    as_array
        mean outflow at given inflow
    as_array
        std deviation of outflow at given inflow
    """
    unique_vals = sorted(list(set(data['inflows'])))
    sorted_outflows = {inflow: [] for inflow in unique_vals}

    for inflow, outlfow in zip(data['inflows'], data['outflows']):
        sorted_outflows[inflow].append(outlfow)

    mean = np.asarray([np.mean(sorted_outflows[val]) for val in unique_vals])
    std = np.asarray([np.std(sorted_outflows[val]) for val in unique_vals])

    return unique_vals, mean, std

def create_parser():
    """Create an argument parser."""
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        description='[Flow] Generates capacity diagrams for the bottleneck.',
        epilog="python capacity_diagram_generator.py </path/to/file>.csv")

    parser.add_argument('file', type=str, help='path to the csv file.')

    return parser

if __name__ == '__main__':
    # import parser arguments
    parser = create_parser()
    args = parser.parse_args()

    # import the csv file
    data = import_data_from_csv(args.file)

    # compute the mean and std of the outflows for all unique inflows
    unique_inflows, mean_outflows, std_outflows = get_capacity_data(data)

    # some plotting parameters
    rc('text', usetex=True)
    font = {'weight': 'bold', 'size': 18}
    rc('font', **font)

    # perform plotting operation
    plt.figure(figsize=(27, 9))
    plt.plot(unique_inflows, mean_outflows, linewidth=2, color='orange')
    plt.fill_between(unique_inflows, mean_outflows - std_outflows,
                     mean_outflows + std_outflows, alpha=0.25, color='orange')
    plt.xlabel('Inflow' + r'$ \ \frac{vehs}{hour}$')
    plt.ylabel('Outflow' + r'$ \ \frac{vehs}{hour}$')
    plt.tick_params(labelsize=20)
    plt.rcParams['xtick.minor.size'] = 20
    plt.minorticks_on()
    plt.show()