from rest_framework import serializers

from .models import Invitation

class InvitationSerializer(serializers.Serializer):
    first_name = serializers.CharField(required=True)
    last_name = serializers.CharField(required=True)
    email = serializers.EmailField(required=True)
    has_accepted = serializers.BooleanField(read_only=True)

    class Meta:
        model = Invitation
        fields = ('first_name', 'last_name', 'email', 'has_accepted')

    def create(self, validated_data):
        instance = Invitation(**validated_data)
        instance.save()

        return instance


# -*- coding: utf-8 -*-
"""
Created on Mon Jan 14 11:07:58 2019

Spiced Academy Project-02:  With this side project I try to learn a bit more
about the LogisticRegression function. I would like to know, if and and how
coefficients change, when parameters are either added or calculated in a
different sequence. For simplicity purposes and eventual comparisons the
"Titanic" data is being used.

@author: DataCoach
"""
# Import Libraries and read dataset
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
from random import shuffle
import time

fn_train = 'train.csv'
df_train = pd.read_csv(fn_train)

# Pre-Processing: Design training dataframe, with (transformed) features to
# be used for modelling. Transformed features are values of type 'str' to
# 'int' or 'float' e.g. female --> 1, male --> 0

# Calculate average age
average_age = df_train['Age'].dropna().mean()

# Add columns, where ...
# nan's in 'Age' column are replaced with average age
# letters in 'Sex' column are replaced with integers
# letters in 'Embarked' column are replaced with integers
df_train['Age_complete'] = df_train['Age'].replace(np.nan, average_age)

df_train['Gender'] = df_train['Sex'].replace(['female', 'male'], [1, 0])

list_emb = [np.nan, 'C', 'Q', 'S']
list_emb_num = [0,1,2,3]
df_train['Embarked_num'] = df_train['Embarked'].replace(list_emb, list_emb_num)

# Define y column for regression, i.e. in this case the column 'Survived'
y_train = df_train['Survived']

# Perform Logistic Regression in a loop with varying starting parameters and
# varying sequences of the parameters

LogReg = LogisticRegression(C=1e5)
number_of_runs = range(1,11)

for n in number_of_runs:

# Starting Features
    features = ['Pclass', 'Age_complete', 'Gender', 'Embarked_num', 'Fare', 'SibSp', 'Parch']
    shuffle(features)

# Generate empty lists
    coef_list  = []
    score_list = []
    Pclass_coef = []
    Age_coef = []
    Gender_coef = []
    Embarked_coef = []
    Fare_coef = []
    SibSp_coef = []
    Parch_coef = []

# Identify indices of features after shuffle
    Pclass_index    = features.index('Pclass')
    Age_index       = features.index('Age_complete')
    Gender_index    = features.index('Gender')
    Embarked_index  = features.index('Embarked_num')
    Fare_index      = features.index('Fare')
    SibSp_index     = features.index('SibSp')
    Parch_index     = features.index('Parch')

# Perform logistic regression
    for i in range(1, len(features) + 1):
        X_matrix = df_train[features[0:i]]
        LogReg.fit(X_matrix, y_train)
        score = LogReg.score(X_matrix, y_train)
        coef = list(LogReg.coef_[0])
        fit_extend = len(features) - len(coef)
        fit_extend = list(np.full(fit_extend, np.nan)) # fill empty spaces with nan's
        coef.extend(fit_extend)
        coef_list.append(coef)
        score_list.append(score)

# Generate matrix with all coefficients and scores
    for j in range(0, len(features)):
        Pclass_coef.append(coef_list[j][Pclass_index])
        Age_coef.append(coef_list[j][Age_index])
        Gender_coef.append(coef_list[j][Gender_index])
        Embarked_coef.append(coef_list[j][Embarked_index])
        Fare_coef.append(coef_list[j][Fare_index])
        SibSp_coef.append(coef_list[j][SibSp_index])
        Parch_coef.append(coef_list[j][Parch_index])

    Coef_Score_Matrix = pd.DataFrame(np.column_stack([Pclass_coef, Age_coef,
                                            Gender_coef, Embarked_coef,
                                            Fare_coef, SibSp_coef,
                                            Parch_coef, score_list]),
                               columns = ['Pclass', 'Age', 'Gender',
                                          'Embarked', 'Fare', 'SibSp',
                                          'Parch', 'Score'])

# Generate string for identification and sequence of parameters
#    f = str()
#    for s in range(0, len(features)):
#        f = f + (str(features[s][0:2]))

    f = ''
    for s in features:
        f += s[:2]

# Write to excel including timestamp and above mentioned sequence string
    t = time.localtime()
    timestamp = time.strftime('%Y%m%d_%H%M%S', t)
    Coef_Score_Matrix.to_excel(str(timestamp) + '_Coefficients_' + f + '.xlsx')

# Data analysis and visualization
######
#TO BE DONE
######


# -*- coding:utf-8 -*-

from theano import tensor

import thdl.model
from thdl.model.layers import Layer

class ASLayer(Layer):
    def __init__(self, embedding_layer=None, q1_conv_layer=None, q2_conv_layer=None):
        self.embedding_layer = embedding_layer
        self.q1_dimshufle = thdl.model.layers.Dimshuffle((0, 'x', 1, 2))
        self.q2_dimshufle = thdl.model.layers.Dimshuffle((0, 'x', 1, 2))
        self.q1_conv_layer = q1_conv_layer
        self.q2_conv_layer = q2_conv_layer

    def forward(self, inputs, **kwargs):
        q1_embed = self.embedding_layer.forward(inputs[0])
        q1_embed_shuffle = self.q1_dimshufle.forward(q1_embed)
        q1_conv = self.q1_conv_layer.forward(q1_embed_shuffle)

        q2_embed = self.embedding_layer.forward(inputs[1])
        q2_embed_shuffle = self.q2_dimshufle.forward(q2_embed)
        q2_conv = self.q1_conv_layer.forward(q2_embed_shuffle)

        return tensor.concatenate([q1_conv, q2_conv], axis=1)

    def to_json(self):
        config = {
            'embedding_layer': self.embedding_layer.to_json(),
            "q1_conv_layer": self.q1_conv_layer.to_json(),
            "q2_conv_layer": self.q2_conv_layer.to_json(),
        }
        return config

    @property
    def params(self):
        return self.embedding_layer.params + self.q1_conv_layer.params + self.q2_conv_layer.params

    @property
    def regularizers(self):
        return self.embedding_layer.regularizers + self.q1_conv_layer.regularizers + self.q2_conv_layer.regularizers

    @property
    def updates(self):
        ups = super(ASLayer, self).updates
        ups.update(self.q1_conv_layer.updates)
        ups.update(self.q2_conv_layer.updates)
        return ups


import tensorflow as tf
import os
import logging
import gin

@gin.configurable
def set_devices(idx_gpu, soft_device_placement=True, num_cpu_threads=0):

    # Set jit active for XLA routines - Not functional yet
    # tf.config.optimizer.set_jit(True)

    os.unsetenv('CUDA_VISIBLE_DEVICES')  # to see the actual list, prior restrictions have to be unset
    gpus = tf.config.experimental.list_physical_devices('GPU')
    logging.info(f'Available physical devices: {gpus}.')
    if gpus:
        logging.info(f'Fetching devices: {idx_gpu}.')
        # Restrict TensorFlow to only use one specific GPU
        try:
            tf.config.experimental.set_visible_devices(gpus[int(idx_gpu)], 'GPU')
            #  set memory growth option for all GPU devices (even the ones not used). Otherwise current tf version throws a ValueError
            for idx in range(len(gpus)):
                tf.config.experimental.set_memory_growth(gpus[int(idx)], True)
        except RuntimeError as e:
            # Visible devices and memory growth must be set at program startup
            print(e)

        # set device placement
        tf.config.set_soft_device_placement(soft_device_placement)

        logging.info(f'Visible devices: {tf.config.experimental.get_visible_devices()}.')
        logging.info(f'Memory growth option: {tf.config.experimental.get_memory_growth(gpus[int(idx_gpu)])}')
        logging.info(f'Using soft device placement: {tf.config.get_soft_device_placement()}')

    # Set CPU options
    if num_cpu_threads > 0:
        tf.config.threading.set_inter_op_parallelism_threads(2)
        tf.config.threading.set_intra_op_parallelism_threads(num_cpu_threads)
    else:
        tf.config.threading.set_inter_op_parallelism_threads(2)
        tf.config.threading.set_intra_op_parallelism_threads(4)

    # set some optimizations
    tf.config.optimizer.set_experimental_options({'layout_optimizer': True,
                                                  'remapping': True,
                                                  'arithmetic_optimization': True,
                                                  'dependency_optimization': True,
                                                  'loop_optimization': True,
                                                  'function_optimization': True,
                                                  'scoped_allocator_optimization': True})
    # report CPU optimizations
    logging.info(f'Using the following optimization options: {tf.config.optimizer.get_experimental_options()}.')


from esda.moran import Moran, Moran_Local
import geopandas as gpd
from geopandas import GeoDataFrame as gdf
import libpysal as lp
from libpysal import weights
from libpysal.weights import Queen, KNN, attach_islands
import mapclassify as mc
from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import plotly.express as px
import seaborn as sns
from sklearn.cluster import KMeans, AgglomerativeClustering
from sklearn.preprocessing import StandardScaler
import streamlit as st

@st.cache(allow_output_mutation=True)
def get_data():
    data = gpd.read_file('capstone.shp')
    data = data.rename(columns = {'municipalc':'Municipal Code',
                                     'municipali':'Municipality',
                                     'Mun_Povert':'Poverty Incidence',
                                     'beds_per_c': 'Health Facility Beds per 1000 people',
                                     'current_ca': 'Current New Cases',
                                     'total_inci': 'Total Cases per 100,000 people',
                                     'current_in': 'Current New Cases per 100,000 people',
                                     'case_fatal': 'Case Fatality Ratio',
                                     'population': 'No. People per 30 sq m',
                                     'elderly_po': 'No. of Elderly in Poverty',
                                     'total_case': 'Total Cases',
                                     'atrisk': 'Elderly Individuals at Risk',
                                     'total_beds': 'Total Beds'})
    #data['geometry'] = data['geometry'].to_crs(epsg = 3395)
    regions = data[['RegCode', 'Region', 'geometry']]
    regions = regions.dissolve(by='RegCode')
    province = data[['ProvinceCo', 'Province', 'geometry']]
    province = province.dissolve(by='ProvinceCo')
    return data, regions, province

def get_weights(df):
    wq = Queen.from_dataframe(df)
    wknn1 = KNN.from_dataframe(df)
    wfixed = weights.util.attach_islands(wq, wknn1)
    return wknn1

# compute the  local spatial autocorrelation
def compute_lsa(df, wq):
    variable = [ 'Poverty Incidence',
    'Health Facility Beds per 1000 people',
    'Current New Cases',
    'Total Cases per 100,000 people',
    'Current New Cases per 100,000 people',
    'Case Fatality Ratio',
    'No. People per 30 sq m',
    'No. of Elderly in Poverty',
    'Total Cases',
    'Elderly Individuals at Risk'
    ]
    lsa = [ 'LSA: Poverty Incidence',
    'LSA: Health Facility Beds per 1000 people',
    'LSA: Current New Cases',
    'LSA: Total Cases per 100,000 people',
    'LSA: Current New Cases per 100,000 people',
    'LSA: Case Fatality Ratio',
    'LSA: No. People per 30 sq m',
    'LSA: No. of Elderly in Poverty',
    'LSA: Total Cases',
    'LSA: Elderly Individuals at Risk'
    ]
    for i in range(len(variable)):
        lisa = Moran_Local(df[variable[i]], wq)
        sig = 1 * (lisa.p_sim < 0.05)
        hotspot = 1 * (sig * lisa.q==1)
        coldspot = 3 * (sig * lisa.q==3)
        doughnut = 2 * (sig * lisa.q==2)
        diamond = 4 * (sig * lisa.q==4)
        spots = hotspot + coldspot + doughnut + diamond
        spot_labels = [ '0 Not Significant', '1 Hot Spot', '2 Doughnut', '3 Cold spot', '4 Diamond']
        labels = [spot_labels[i] for i in spots]
        df[lsa[i]] = labels
    return df

@st.cache
def stdScaler(df):
    scaler = StandardScaler()
    return scaler.fit_transform(df)

@st.cache
def produceClusters(n_clusters, scaled_df, random_state=13):
    kmeans = KMeans(n_clusters=n_clusters, random_state=random_state)
    kmeans.fit(scaled_df)
    return kmeans.predict(scaled_df)

@st.cache
def kmeans_clustering(df):
    variable = [ 'Poverty Incidence',
    'Health Facility Beds per 1000 people',
    'Total Cases per 100,000 people',
    'Current New Cases per 100,000 people',
    'Case Fatality Ratio',
    'No. People per 30 sq m',
    'Elderly Individuals at Risk'
    ]
    df['Cluster Label'] = produceClusters(2, df[variable])
    table = df.groupby(['Cluster Label'])['Cluster Label'].count()
    if table[0]>table[1]:
        group1 = df[df['Cluster Label']==1]
        group1['Cluster Label'] = group1['Cluster Label'].replace(1, 'Priority 1')
        other = df[df['Cluster Label']==0]
    else:
        group1 = df[df['Cluster Label']==0]
        group1['Cluster Label'] = group1['Cluster Label'].replace(0, 'Priority 1')
        other = df[df['Cluster Label']==1]
    other['Cluster Label'] = produceClusters(2, other[variable])
    table = other.groupby(['Cluster Label'])['Cluster Label'].count()
    if table[0]>table[1]:
        group2 = other[other['Cluster Label']==1]
        group2['Cluster Label'] = group2['Cluster Label'].replace(1, 'Priority 2')
        other = other[other['Cluster Label']==0]
    else:
        group2 = other[other['Cluster Label']==0]
        group2['Cluster Label'] = group2['Cluster Label'].replace(0, 'Priority 2')
        other = other[other['Cluster Label']==1]
    other['Cluster Label'] = produceClusters(2, other[variable])
    table = other.groupby(['Cluster Label'])['Cluster Label'].count()
    if table[0]>table[1]:
        other['Cluster Label'] = other['Cluster Label'].replace(1, 'Priority 3')
        other['Cluster Label'] = other['Cluster Label'].replace(0, 'Priority 4')
    else:
        other['Cluster Label'] = other['Cluster Label'].replace(0, 'Priority 3')
        other['Cluster Label'] = other['Cluster Label'].replace(1, 'Priority 4')
    kmeans1 = pd.concat([group1, group2, other], ignore_index = True)
    return kmeans1

@st.cache
def region_options():
    list = regions['Region'].unique()
    list = np.insert(list, 0, 'All Regions')
    return list

@st.cache
def province_options(region_choice):
    province  = original_df[original_df['Region']==region_choice]
    list = province['Province'].unique()
    list = np.insert(list, 0, 'All Provinces')
    return list

def get_coordinates(region_choice, province_choice):
    if (region_choice == 'All Regions') & (province_choice=='All Provinces'):
        coordinates = regions.geometry.total_bounds
    else:
        if province_choice =='All Provinces':
            coordinates = regions[regions['Region']==region_choice].geometry.total_bounds
        else:
            coordinates = province[province['Province']==province_choice].geometry.total_bounds
    return coordinates

def get_subsetdf(region_choice, province_choice, working_df):
    if (region_choice == 'All Regions') & (province_choice=='All Provinces'):
        subsetdf = working_df
    else:
        if province_choice =='All Provinces':
            subsetdf = working_df[working_df['Region']==region_choice]
        else:
            subsetdf = working_df[working_df['Province']==province_choice]
    return subsetdf

def get_graphs(coordinates, subsetdf, working_df):
    variable = [
            'Health Facility Beds per 1000 people',
            'Total Cases per 100,000 people',
            'Current New Cases per 100,000 people',
            'Case Fatality Ratio',
            'No. People per 30 sq m',
            'Elderly Individuals at Risk',
            'Poverty Incidence'
            ]
    variable_choice = st.selectbox('Choose Variable', variable, 0)
    st.sidebar.header('Chosen Variable')
    st.sidebar.text(variable_choice)
    get_histogram(variable_choice, subsetdf)
    get_map(coordinates, working_df, variable_choice, subsetdf)
    return

@st.cache(suppress_st_warning=True)
def get_histogram(variable_choice, subsetdf):
    st.header('Histogram of the Variable')
    #minv, maxv = st.slider('Variable Range', subsetdf[variable_choice].min(), subsetdf[variable_choice].max(), (subsetdf[variable_choice].min(), subsetdf[variable_choice].max()))
    f = px.histogram(subsetdf, x = variable_choice, title = 'Variable Distribution')
    f.update_xaxes(title = variable_choice)
    f.update_yaxes(title = "No. of Municipalities")
    st.plotly_chart(f)
    return

@st.cache(suppress_st_warning=True)
def get_map(coordinates, working_df, variable_choice, subsetdf):
    st.header('Area Map')
    map = st.selectbox('Choose the Map', ['Chloropleth Map of Variable',
    'Local Spatial Autocorrelation Result', 'KMeans Clustering Result'], 0 )
    if map == 'Chloropleth Map of Variable':
        chloropleth(coordinates, working_df, variable_choice, subsetdf)
    elif map=='Local Spatial Autocorrelation Result':
        LSA(coordinates, working_df, variable_choice, subsetdf)
    else:
        cluster(coordinates, working_df, variable_choice, subsetdf)
    return

@st.cache(suppress_st_warning=True)
def chloropleth(coordinates, working_df, variable_choice, subsetdf):
    fig, ax = plt.subplots(1, figsize=(12, 9))
    working_df.plot(column=variable_choice, cmap='Blues', linewidth=0.35, ax=ax,
    legend_kwds = {'loc' : 'upper left'}, edgecolor='0.9', scheme = 'Quantiles', k=5, legend = True, alpha = 0.6)
    province.boundary.plot(ax=ax, linewidth = 0.65, edgecolor='0.1')
    regions.boundary.plot(ax=ax, linewidth = 0.9, edgecolor='sandybrown')
    xlim = ([coordinates[0], coordinates[2]])
    ylim = ([coordinates[1], coordinates[3]])
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)
    ax.axis('off')
    plt.suptitle(variable_choice)
    st.pyplot(fig)
    variable = ['Province', 'Municipality', variable_choice]
    st.write(subsetdf[variable])
    return

@st.cache(suppress_st_warning=True)
def LSA(coordinates, working_df, variable_choice, subsetdf):
    lsa_choice = choice(variable_choice)
    hmap = ListedColormap([ 'grey', 'red', 'lightblue', 'blue', 'pink'])
    fig, ax = plt.subplots(1, figsize=(12, 9))
    working_df.plot(column=lsa_choice, cmap=hmap, categorical = True, linewidth=0.35, ax=ax,
    legend_kwds = {'loc' : 'upper left'}, edgecolor='0.9', k=2, legend = True, alpha = 0.6)
    province.boundary.plot(ax=ax, linewidth = 0.65, edgecolor='0.1')
    regions.boundary.plot(ax=ax, linewidth = 0.9, edgecolor='sandybrown')
    xlim = ([coordinates[0], coordinates[2]])
    ylim = ([coordinates[1], coordinates[3]])
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)
    ax.set_aspect('equal')
    ax.axis('off')
    plt.suptitle(lsa_choice)
    st.pyplot(fig)
    variable = ['Province', 'Municipality', lsa_choice]
    st.write(subsetdf[variable])
    return

@st.cache(suppress_st_warning=True)
def choice(variable_choice):
    if variable_choice == 'Poverty Incidence' :
        choice  = 'LSA: Poverty Incidence'
    elif variable_choice == 'Health Facility Beds per 1000 people':
        choice = 'LSA: Health Facility Beds per 1000 people'
    elif variable_choice == 'Total Cases per 100,000 people':
        choice = 'LSA: Total Cases per 100,000 people'
    elif variable_choice == 'Current New Cases per 100,000 people':
        choice = 'LSA: Current New Cases per 100,000 people'
    elif variabble_choice == 'Case Fatality Ratio':
        choice = 'LSA: Case Fatality Ratio'
    elif variable_choice == 'LSA: No. People per 30 sq m':
        choice = 'LSA: No. People per 30 sq m'
    elif variable_choice == 'Elderly Individuals at Risk':
        choice = 'LSA: Elderly Individuals at Risk'
    return choice

@st.cache(suppress_st_warning=True)
def cluster(coordinates, working_df, variable_choice, subsetdf):
    fig, ax = plt.subplots(1, figsize=(12, 9))
    working_df.plot(column='Cluster Label', cmap='viridis', linewidth=0.5, ax=ax,
    edgecolor='0.9', legend_kwds = {'loc' : 'upper left'}, legend = True, alpha = 0.3)
    province.boundary.plot(ax=ax, linewidth = 0.75, edgecolor='0.1')
    regions.boundary.plot(ax=ax, linewidth = 1, edgecolor='sandybrown')
    xlim = ([coordinates[0], coordinates[2]])
    ylim = ([coordinates[1], coordinates[3]])
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)
    ax.axis('off')
    st.pyplot(fig)
    variable = ['Province', 'Municipality', 'Cluster Label']
    st.write(subsetdf[variable])
    return

def update_data(subsetdf, working_df, original_df):
    st.header('Update Data')
    subsetdf = subsetdf.sort_values(by = ['Municipal Code'])
    municipal_code = st.selectbox('Choose the Municipal Code of the City/Municipality to be updated',
    subsetdf['Municipal Code'].unique())
    st.text("Reference for the Municipal Code")
    variable = [ 'Municipal Code',
        'Province',
        'Municipality',
        'Health Facility Beds per 1000 people'
        ]
    st.write(subsetdf[variable])
    st.sidebar.success(working_df[working_df['Municipal Code']==municipal_code][['Municipality', 'Province']])
    ab = working_df[working_df['Municipal Code']==municipal_code][['Health Facility Beds per 1000 people',
    'Total Cases per 100,000 people', 'Current New Cases per 100,000 people', 'Case Fatality Ratio',
    'No. People per 30 sq m', 'Elderly Individuals at Risk', 'Poverty Incidence']]
    hf = st.number_input('Health Facility Beds per 1000 people', min_value = 0.0,
    value = float(ab['Health Facility Beds per 1000 people']))
    tc = st.number_input('Total Cases per 100,000 people', min_value = 0.0,
    value = float(ab['Total Cases per 100,000 people']))
    cc = st.number_input('Current New Cases per 100,000 people', min_value = 0.0,
    value = float(ab['Current New Cases per 100,000 people']))
    cr = st.number_input('Case Fatality Ratio', min_value = 0.0,
    value = float(ab['Case Fatality Ratio']))
    no = st.number_input('No. People per 30 sq m', min_value = 0.0,
    value = float(ab['No. People per 30 sq m']))
    er = st.number_input('Elderly Individuals at Risk', min_value = 0.0,
    value = float(ab['Elderly Individuals at Risk']))
    pi = st.number_input('Poverty Incidence', min_value = 0.0,
    value = float(ab['Poverty Incidence']))
    if (st.button('Click to Update Data')):
        working_df = update(working_df, municipal_code, hf, tc, cc, cr, no, er, cc)
        st.success('Data updated')
    if (st.button('Click to Update Model')):
        working_df = compute_lsa(working_df, wq)
        working_df = kmeans_clustering(working_df)
        st.success('Model updated')
    if (st.button('Click to Reset Changes')):
        working_df = original_df.copy()
    return working_df, municipal_code

@st.cache(suppress_st_warning=True)
def update(working_df, municipal_code, hf, tc, cc, cr, no, er, pi):
    df = working_df.set_index('Municipal Code')
    df.at[municipal_code, 'Health Facility Beds per 1000 people'] = hf
    df.at[municipal_code, 'Total Cases per 100,000 people'] = tc
    df.at[municipal_code, 'Current New Cases per 100,000 people'] = cc
    df.at[municipal_code, 'Case Fatality Ratio'] = cr
    df.at[municipal_code, 'No. People per 30 sq m'] = no
    df.at[municipal_code, 'Elderly Individuals at Risk'] = er
    df.at[municipal_code, 'Poverty Incidence'] = pi
    working_df = df.reset_index()
    return working_df

@st.cache(suppress_st_warning=True)
def get_info():
    st.header("Variables Used in The Model")
    st.markdown("The following are the variables used in the classification model")
    st.markdown("> Health Facility Beds per 1000 people - this is the ratio of beds of infirmaries and \
    hospitals within a city/municipality to their population.")
    st.markdown("> Total Cases per 100,000 people - ratio of confirmed Covid 19 cases per city \
    /municipality to the population. The total cases as of March 17, 2021 were used for the initial \
    clustering model.")
    st.markdown("> Current New Cases per 100,000 people - ration of total confirmed Covid 19 cases \
    for the past 2 weeks and the population. The new cases that was used for the model are the published\
    cases wherein their date of onset of symptoms/ date of specimen collection/ date of confirmation \
    (whichever is available) falls within March 3 -17, 2021")
    st.markdown('> Case Fatality Ratio - computed by dividing the total covid deaths by the total covid \
    cases by city/municipality')
    st.markdown("> Poverty Incidence - percent of the city/municipality's population that are below \
    the povery line")
    st.markdown("> No. People per 30 sq m - estimated number and a measure of population density")
    st.markdown("> Elderly Individuals at Risk - estimated number of elderly individuals that are \
    at risk of contracting COVID 19. It was assumed that those that already had COVID-19 had some \
    immunity to the disease thus this varible was computed by subtracting the estimated number of \
    elderly individuals minus the total number of COVID 19 cases in the elderly ")
    return

original_df, regions, province = get_data()
wq = get_weights(original_df)
original_df = compute_lsa(original_df, wq)
original_df = kmeans_clustering(original_df)
working_df = original_df
st.title("Clustering Senior Citizen's Vaccine Distribution Prioritization in the Philippines")
st.sidebar.header("User Selection")
region_choice = st.sidebar.selectbox('Region', region_options(), 0)
province_choice = st.sidebar.selectbox('Province',
    province_options(region_choice), 0)
coordinates = get_coordinates(region_choice, province_choice)
subsetdf = get_subsetdf(region_choice, province_choice, working_df)
#working_df = update_data(subsetdf, working_df, original_df)
if (st.sidebar.button('Click for Graphs')):
    get_graphs(coordinates, subsetdf, working_df)
elif (st.sidebar.button('Click for Info')):
    get_info()


from django.template import Context, loader
from django.http import HttpResponse
from django.db import models
from modClass import tableGenerator
from django.core.context_processors import csrf
from django.shortcuts import render_to_response

import find2, settings, listDir, os, uploadFile
import probadb
def index(request):
	ht = HttpResponse()
	ht.write('Click here for app - DIR
')
	ht.write('Form
')
	ht.write('Upload files')
	return ht

def fin(request,path,fn):
	root = settings.Velly_Root
	res = find2.findReal(root+path,fn)
	ht = HttpResponse()
	for el in res:
		if el != "\n":
			ht.write(el)
		else: ht.write("
")
	ht.write("abv.bg")
	ht.flush()
	return ht

def Dir(request, path):
	root = settings.Velly_Root
	p = os.path.join(root,path)
	res = listDir.execute(p, settings.temps[0], settings.temps[1])
	c = Context({
        	'STATIC_URL': settings.STATIC_URL
    	})
	f = open(settings.TEMPLATE_DIRS+"ind.html", "w")
	f.write(res)
	f.flush()
	f.close()
	t = loader.get_template(settings.TEMPLATE_DIRS+"ind.html")
	return HttpResponse(t.render(c))
def textfiles(request, path):
	root = settings.Velly_Root
	p = root+path
	try:
		f = open(p,"r")
	except IOError:
		return HttpResponse("Access denied")
	res = '<INPUT TYPE="button" VALUE="Back" onClick="history.go(-1);">

'
	l = f.readlines()
	f.close()
	for el in l:
		el = el.replace("	", "      ")
		el = el.replace("<", "<")
		el = el.replace(">",	">")
		res += el.replace(" ", " ")+"
"
	return HttpResponse(res)

def proba(request):
	 return HttpResponse(probadb.delete())

def form(request):
	try:
	     f = open(settings.STATICFILES_DIRS[0]+'/index.html','r')
	     f1 = open(settings.temps[1],'r')
	     t = f1.read()
	     res = f.read()
	     res += '
DIR'
	     f.close()
	     f1.close()
	     return HttpResponse(res.replace("#$$$list$$$#",tableGenerator.generate('Person')))
	except IOError:
		 return HttpResponse("Form template does not exist
"+settings.STATICFILES_DIRS[0]+'/index.html')

def Error(request):
	return HttpResponse('<META HTTP-EQUIV="REFRESH" CONTENT="1;URL=/">Error 404')

def upload(request):
	try:
		res = listDir.execute(settings.UPLOAD_PATH,settings.temps[3],settings.temps[1])
		f = open(settings.TEMPLATE_DIRS+"/t.html", 'w')
		f.write(res)
		f.close()
		return render_to_response(settings.TEMPLATE_DIRS+"/t.html", Context(csrf(request)))
	except IOError:
		return "Cannot open template upload.html"


import argparse

import cv2
import matplotlib.pyplot as plt
from PIL import Image
from torchvision import transforms

from utils.model_utils import *

def get_attention_mask(im, x, model):
    logits, att_mat = model(x.unsqueeze(0))
    att_mat = torch.stack(att_mat).squeeze(1)

    # Average the attention weights across all heads.
    att_mat = torch.mean(att_mat, dim=1)

    # To account for residual connections, we add an identity matrix to the
    # attention matrix and re-normalize the weights.
    residual_att = torch.eye(att_mat.size(1))
    aug_att_mat = att_mat + residual_att
    aug_att_mat = aug_att_mat / aug_att_mat.sum(dim=-1).unsqueeze(-1)

    # Recursively multiply the weight matrices
    joint_attentions = torch.zeros(aug_att_mat.size())
    joint_attentions[0] = aug_att_mat[0]

    for n in range(1, aug_att_mat.size(0)):
        joint_attentions[n] = torch.matmul(aug_att_mat[n], joint_attentions[n - 1])

    # Attention from the output token to the input space.
    v = joint_attentions[-1]
    grid_size = int(np.sqrt(aug_att_mat.size(-1)))
    mask = v[0, 1:].reshape(grid_size, grid_size).detach().numpy()
    mask = cv2.resize(mask / mask.max(), im.size)[..., np.newaxis]
    # result = (mask * im).astype("uint8")

    return mask

def visualize(model_dir, img_path, plot_layerwise_attentions=False, base=False):
    config_file = os.path.join(model_dir, 'model_config.json')
    with open(config_file) as cfg:
        config = json.load(cfg)
    print('Visualizing attention for model:')
    print(config)

    if base:
        model = VisionTransformer(CONFIGS[config['model_type']], num_classes=21843, zero_head=False,
                                  img_size=config['img_size'], vis=True)
        model.load_from(np.load('checkpoints/pretrained_ckpts/ViT-B_16.npz'))
    else:
        model = VisionTransformer(CONFIGS[config['model_type']], num_classes=config['num_classes'], zero_head=False,
                                  img_size=config['img_size'], vis=True)
        checkpoint_file = os.path.join(model_dir, 'checkpoint.bin')
        model.load_state_dict(torch.load(checkpoint_file, map_location=torch.device('cpu')))
    model.eval()

    transform = transforms.Compose([
        transforms.Resize((config['img_size'], config['img_size'])),
        transforms.ToTensor(),
        transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
    ])
    im = Image.open(img_path)
    x = transform(im)

    mask = get_attention_mask(im, x, model)

    fig, ax1 = plt.subplots(ncols=1, figsize=(5, 5))

    ax1.set_title('Attention map')
    _ = ax1.imshow(im)
    _ = ax1.imshow(mask, cmap='jet', alpha=0.5)
    plt.show()

    return mask

def visualize_imgs(model_dir, img_dir, plot_layerwise_attentions=False, base=False):
    config_file = os.path.join(model_dir, 'model_config.json')
    with open(config_file) as cfg:
        config = json.load(cfg)
    print('Visualizing attention for model:')
    print(config)

    if base:
        model = VisionTransformer(CONFIGS[config['model_type']], num_classes=21843, zero_head=False,
                                  img_size=config['img_size'], vis=True)
        model.load_from(np.load('checkpoints/pretrained_ckpts/ViT-B_16.npz'))
    else:
        model = VisionTransformer(CONFIGS[config['model_type']], num_classes=config['num_classes'], zero_head=False,
                                  img_size=config['img_size'], vis=True)
        checkpoint_file = os.path.join(model_dir, 'checkpoint.bin')
        model.load_state_dict(torch.load(checkpoint_file, map_location=torch.device('cpu')))
    model.eval()

    transform = transforms.Compose([
        transforms.Resize((config['img_size'], config['img_size'])),
        transforms.ToTensor(),
        # transforms.Lambda(lambda x: x.repeat(3, 1, 1)),
        transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
    ])
    for img_path in os.listdir(img_dir):
        if 'jpg' in img_path or 'png' in img_path or 'ppm' in img_path or 'JPG' in img_path:
            im = Image.open(os.path.join(img_dir,img_path))
            x = transform(im)
            mask = get_attention_mask(im, x, model)

            fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(10, 5))
            ax1.imshow(im)
            _ = ax2.imshow(im)
            _ = ax2.imshow(mask, cmap='jet', alpha=0.5)
            plt.show()
            fig.savefig(os.path.join('data/test_imgs', 'attn_images/attn_'+img_path.split('.')[0]+'.png'), bbox_inches='tight')

    return

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--model_config", type=str, default="checkpoints/output_ckpts/cifar10_img224",
                        help="Where to search for pretrained ViT models.")
    parser.add_argument("--test_img", type=str, default="data/test_imgs/traffic_sign2.png",
                        help="Where to search for pretrained ViT models.")
    parser.add_argument("--img_dir", type=str, default="data/test_imgs",
                        help="Where to search for pretrained ViT models.")
    args = parser.parse_args()
    # visualize(args.model_config, args.test_img, plot_layerwise_attentions=False, base=True)
    visualize_imgs(args.model_config, args.img_dir, plot_layerwise_attentions=False, base=True)

    return

if __name__ == "__main__":
    main()


from distutils.command.install import install

from .models import *
from rest_framework import serializers

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username', 'email', 'groups')

class GroupSerializers(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = ('name',)

class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = ('name',)

class InstrumentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Instrument
        fields = ('id', 'name', 'level', 'associated_concepts', 'difficulty', 'time', 'winner_selection',
                  'category', 'purpose_teaching', 'purpose_reinforce', 'purpose_check', 'purpose_social', 'description',
                  'groups', 'attachments', 'public', 'creation_date', 'update_date')

    def to_representation(self, instance):
        response = super().to_representation(instance)
        response['owner'] = instance.owner.get_full_name()
        response['category'] = Category.objects.get(pk=response['category']).name
        response['Objetivos'] = GoalSerializer(
            Component.objects.filter(instrument=instance, component_type='Objetivos'),
            many=True).data
        response['Reglas'] = RuleSerializer(
            Component.objects.filter(instrument=instance, component_type='Reglas'),
            many=True).data
        response['Roles'] = RoleSerializer(
            Component.objects.filter(instrument=instance, component_type='Roles'),
            many=True).data
        response['Pasos'] = StepSerializer(
            Component.objects.filter(instrument=instance, component_type='Pasos'),
            many=True).data
        response['Materiales'] = MaterialSerializer(
            Component.objects.filter(instrument=instance, component_type='Materiales'),
            many=True).data
        return response

class GoalSerializer(serializers.ModelSerializer):
    class Meta:
        model = Component
        fields = ('id',)

    def to_representation(self, instance):
        response = super().to_representation(instance)
        response['Oname'] = instance.description
        return response

class RuleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Component
        fields = ('id',)

    def to_representation(self, instance):
        response = super().to_representation(instance)
        response['Rname'] = instance.description
        return response

class RoleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Component
        fields = ('id',)

    def to_representation(self, instance):
        response = super().to_representation(instance)
        response['Roname'] = instance.description
        return response

class StepSerializer(serializers.ModelSerializer):
    class Meta:
        model = Component
        fields = ('id',)

    def to_representation(self, instance):
        response = super().to_representation(instance)
        response['Sname'] = instance.description
        return response

class MaterialSerializer(serializers.ModelSerializer):
    class Meta:
        model = Component
        fields = ('id',)

    def to_representation(self, instance):
        response = super().to_representation(instance)
        response['Maname'] = instance.description
        return response

class EvidenceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Evidence
        fields = ('id', 'principle',)

    def to_representation(self, instance):
        response = super().to_representation(instance)
        principle = Principle.objects.get(pk=response['principle'])
        response['principle'] = PrincipleSerializer(principle).data
        return response

class ComponentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Component
        fields = ('description', 'component_type')

class EvidencePrincipleSerializer(serializers.ModelSerializer):
    component = ComponentSerializer()

    class Meta:
        model = Evidence
        fields = ('id', 'component')

class PrincipleSerializer(serializers.ModelSerializer):
    evidences = EvidencePrincipleSerializer(many=True)

    class Meta:
        model = Principle
        fields = ('id', 'principle', 'grade', 'weight', 'evidences')


from PIL import Image, ImageDraw, ImageFont

"""

Centralizando elementos

"""
img_width  = 300
img_height = 300

im = Image.new("RGB", (img_width, img_height), "white")
draw = ImageDraw.Draw(im)

#
# Centralizando um quandrado 100x100
#
rec_x_ini = img_width  / 2 - 50
rec_y_ini = img_height / 2 - 50
rec_x_fim = img_width  / 2 + 50
rec_y_fim = img_height / 2 + 50
draw.rectangle([rec_x_ini, rec_y_ini, rec_x_fim, rec_y_fim], fill="green", outline="yellow")

#
# Desenhando um círculo dentro do quadrado
#
draw.ellipse([rec_x_ini + 10, rec_y_ini + 10, rec_x_fim - 10, rec_y_fim - 10], fill="blue", outline="black")

del draw

im.save('imgs/pillow-007.png', "PNG")


import random
from datetime import datetime, timedelta
from operator import attrgetter
from db_interface import add_room
from entities import Event, SanitizedEvent, Room, SanitizedStatus
import db_interface as db
import algorithms as algo
base = datetime(2021, 1, 10, 00, 00, 00)

room_names = ['Faner Hall', 'CS Main office', 'Linux Lab', 'Conference Room', 'Subway',
              'Grad School', 'Shryock Auditorium', 'REC center', 'Health Center', 'Campus Loop']

def gen_un(num=10):
    retVal = [70983, 67375, 38274, 15948, 39332, 46551, 89452, 65581, 91513, 56695, 93495, 14489, 33796, 22258, 35436, 28273, 15909, 49829, 91888, 41355, 12265, 25575, 13295, 94272, 75041, 79724, 94331, 49094, 97765, 76097, 27260, 79237, 56386, 41642, 76750, 19871, 80257, 18477, 84637, 46571, 44554, 84530, 48237, 71753, 77888, 33971, 60273, 54860, 29805, 20182, 50195, 69364, 69740, 66008, 36869, 90767, 76004, 17735, 70777, 92915, 87067, 63783, 49224, 86903, 81915, 56155, 35367, 50982, 90378, 96810, 49721, 29100, 34701, 53327, 35004, 51669, 85598, 38272, 80275, 59151, 50044, 27577, 69158, 33447, 63480, 44912, 57918, 46857, 77435, 76053, 15148, 16125, 54986, 31127, 38305, 65443, 29092, 75663, 98398, 48838]
    #[random.randint(10001, 99999) for i in range(num)]
    # print(retVal)
    return retVal

def gen_bmp_un(num=10):
    retVal = ['BMP32369', 'BMP85052', 'BMP26184', 'BMP95577', 'BMP75406', 'BMP50291', 'BMP87861', 'BMP16918', 'BMP72539', 'BMP80786']
    #["BMP" + str(random.randint(10001, 99999)) for i in range(num)]
    # print(retVal)
    return retVal

def gen_rid(num=10):
    retVal = ['J28929', 'P72143', 'S87978', 'L83225', 'B21970', 'S96687', 'L89485', 'D49972', 'G19247', 'S15838']
    #[chr(65 + random.randint(0, 25)) + str(random.randint(10001, 99999)) for i in range(num)]
    # print(retVal)
    return retVal

# or a function

def gen_datetime(base, max_hour_limit=10):
    # generate a datetime in format yyyy-mm-dd hh:mm:ss.000000
    base += timedelta(hours=random.randint(0, max_hour_limit),
                      minutes=random.randint(1, 30), seconds=random.randint(0, 10), microseconds=random.randint(0, 100000))
    return base

def get_entry_exit_pairs(user_id, ridList, num=100):
    events = []
    start = base
    for _ in range(num):
        room_id = ridList[random.randint(0, len(ridList)-1)]
        start = gen_datetime(start)
        if(start >= datetime.now()):
            break
        end = gen_datetime(start)
        events.append(Event(user_id, room_id, 1, start))
        events.append(Event(user_id, room_id, 0, end))
        start = end
    return events

def get_sanitized_events_for_the_day(unList, roomList, date, frequency=1):
    events = []
    random.shuffle(unList)
    random.shuffle(roomList)
    minLength = min(len(unList), len(roomList))
    for user_id, room_id in zip(unList[:minLength], roomList[:minLength]):
        baseTime = date
        for _ in range(frequency):
            start = gen_datetime(baseTime, max_hour_limit=10)
            end = gen_datetime(start, max_hour_limit=1)
            events.append(SanitizedEvent(user_id, room_id, 1, start))
            events.append(SanitizedEvent(user_id, room_id, 0, end))
            baseTime = end
    return events

def addToFile(events, fname):
    f = open("covid-contact-tracing/server/mockdata/"+fname, "w")
    for event in events:
        f.write(str(event)+"\n")

def generate_room_entries(rooms):
    rooms.sort(key=attrgetter('id'))
    addToFile(rooms, f"room-by-id.txt")
    rooms.sort(key=attrgetter('name'))
    addToFile(rooms, f"room-by-name.txt")
    rooms.sort(key=attrgetter('max_capacity'))
    addToFile(rooms, f"room-by-capacity.txt")

def generate_mock_event_files(events, title):
    events.sort(key=attrgetter('user_id'))
    addToFile(events, f"{title}-user_id.txt")
    events.sort(key=attrgetter('room_id', 'timestamp'))
    addToFile(events, f"{title}-room_id.txt")
    events.sort(key=attrgetter('timestamp'))
    addToFile(events, f"{title}-timestamp.txt")

def main():
    global base
    unList = gen_un(100)
    bmpUserList = gen_bmp_un(10)
    ridList = gen_rid(10)
    random.shuffle(room_names)
    roomList = [Room(rid, room_names[i], random.randint(2, 100))
                for i, rid in enumerate(ridList)]
    all_events, all_sanitized_events = [], []
    for un in unList:
        base = datetime(2021, 1, 10, 00, 00, 00)
        all_events += (get_entry_exit_pairs(un, ridList, 100))

    for dayCount in range((datetime.now() - base).days):
        date = datetime(2021, 1, 10, 00, 00, 00) + timedelta(days=dayCount)
        all_sanitized_events += get_sanitized_events_for_the_day(
            bmpUserList, ridList,  date, frequency=2)

    generate_room_entries(roomList)
    generate_mock_event_files(all_events, 'events')
    generate_mock_event_files(all_sanitized_events, 'sanitized-events')

    for room in roomList:
        db.add_room(room.__dict__)

    for event in sorted(all_events+all_sanitized_events, key=attrgetter('timestamp')):
        algo.add_event_algo(event)

    return all_events, all_sanitized_events

if __name__ == "__main__":
    main()


import tkinter
from PIL import Image, ImageTk
import threading
import time

class Application(tkinter.Frame):
    timer_threads = []
    def createWidgets(self):
        self.main_container = MainContainer(self)

    def __init__(self, master=None):
        tkinter.Frame.__init__(self, master)
        self.pack()
        self.createWidgets()
        self.timing = False

        self.bind("<F2>", self.hit_f2)
        self.bind("<F3>", self.hit_f3)
        self.focus_set()

        self.reset = self.speed_game_reset
        self.master.protocol("WM_DELETE_WINDOW", self.on_close)

    def hit_f2(self, e):
        self.speed_game(5)

    def hit_f3(self, e):
        self.reset()

    def reset_board(self):
        board = self.board
        width = board.board_width
        height = board.board_height
        for i in range(height):
            for j in range(width):
                board.reset_depressed()
                board.set_tile(i, j, "unopened")

    def speed_game(self, n):
        width = self.board.board_width
        height = self.board.board_height
        area = width*height
        if not 0 <= n < area:
            n = 0
        import random
        squares = [0]*area
        i = 0
        while i < n:
            rand = random.randint(0, area-1)
            if not squares[rand]:
                squares[rand] = 1
                i += 1
        self.speed_game_grid = squares
        self.speed_game_reset()
        self.start_timer()

    def speed_game_reset(self):
        width = self.board.board_width
        height = self.board.board_height
        area = width*height
        squares = self.speed_game_grid
        for i in range(area):
            row = i//width
            col = i%width
            tile = "unopened" if squares[i] else "tile_0"
            self.board.set_tile(row, col, tile)

    def start_timer(self):
        self.start_time = time.time()
        self.timing_mode = True
        self.timer_value = 0

        def timer_thread():
            while self.timing_mode:
                elapsed = int(time.time() - self.start_time)+1
                if self.timer_value != elapsed:
                    self.main_container.sub_frame.set_timer(elapsed)
                time.sleep(0.0101)
        if not self.timer_threads:
            new_thread = threading.Thread(target=timer_thread)
            self.timer_threads.append(new_thread)
            new_thread.start()

    def stop_timer(self):
        self.timing_mode = False
        threads_to_remove = []
        for timer_thread in self.timer_threads:
            if not timer_thread.is_alive():
                threads_to_remove.append(timer_thread)
        print("Threads to remove:", threads_to_remove)
        for thread in threads_to_remove:
            self.timer_threads.remove(thread)

    def on_close(self):
        self.kill_timer()
        self.master.destroy()

    def kill_timer(self):
        self.stop_timer()
        for timer_thread in self.timer_threads:
            timer_thread.join()

class MainContainer(tkinter.Frame):
    def create_widgets(self):
        self.sub_frame = GameDisplay(self, 30, 16)
        self.master.board = self.sub_frame.board

    def __init__(self, master=None):
        super().__init__(master, width=200, height=200, background="green")
        self.pack()
        self.config(borderwidth=0)
        self.create_widgets()

    def key_pressed(self, e):
        print(e)

class GameDisplay(tkinter.Frame):
    border_images = {}
    def create_widgets(self):
        grid_row = 0
        self.border_top_left = tkinter.Canvas(self, width=12, height=15,
                                              highlightthickness=0)
        self.border_top = tkinter.Canvas(self, width=16*self.board_width,
                                         height=15, highlightthickness=0)
        self.border_top_right = tkinter.Canvas(self, width=12, heigh=15,
                                               highlightthickness=0)
        self.border_top_left.grid(row=grid_row, column=0)
        self.border_top.grid(row=grid_row, column=1)
        self.border_top_right.grid(row=grid_row, column=2)
        grid_row = 1
        self.border_panel_left = tkinter.Canvas(self, width=12, height=26,
                                             highlightthickness=0)
        self.panel = Panel(self, board_width=self.board_width)
        self.border_panel_right = tkinter.Canvas(self, width=12, height=26,
                                                 highlightthickness=0)
        self.border_panel_left.grid(row=grid_row, column=0)
        self.panel.grid(row=grid_row, column=1, sticky="nesw")
        self.border_panel_right.grid(row=grid_row, column=2)

        grid_row = 2
        self.border_mid_left = tkinter.Canvas(self, width=12, height=14,
                                              highlightthickness=0)
        self.border_mid = tkinter.Canvas(self, width=16*self.board_width,
                                         height=14, highlightthickness=0)
        self.border_mid_right = tkinter.Canvas(self, width=12, height=14,
                                               highlightthickness=0)
        self.border_mid_left.grid(row=grid_row, column=0)
        self.border_mid.grid(row=grid_row, column=1)
        self.border_mid_right.grid(row=grid_row, column=2)

        self.border_left = tkinter.Canvas(self, width=12,
                                          height=16*self.board_height)
        self.border_left.config(highlightthickness=0)
        self.board = Board(self, self.board_width, self.board_height)
        self.border_right = tkinter.Canvas(self, width=12,
                                           height=16*self.board_height)
        self.border_right.config(highlightthickness=0)

        grid_row = 3
        self.border_left.grid(row=grid_row, column=0)
        self.board.grid(row=grid_row, column=1)
        self.border_right.grid(row=grid_row, column=2)

        grid_row = 4
        self.border_bot_left = tkinter.Canvas(self, width=12, height=12,
                                              highlightthickness=0)
        self.border_bot = tkinter.Canvas(self, width=16*self.board_width,
                                         height=12, highlightthickness=0)
        self.border_bot_right = tkinter.Canvas(self, width=12,
                                               height=12, highlightthickness=0)
        self.border_bot_left.grid(row=grid_row, column=0)
        self.border_bot.grid(row=grid_row, column=1)
        self.border_bot_right.grid(row=grid_row, column=2)

        self.init_border()

    def init_border(self):
        for key in ('l', 'r', 'bot_l', 'bot', 'bot_r', 'mid_l', 'mid', 'mid_r',
                    'panel_l', 'panel_r', 'top_l', 'top', 'top_r'):
            img = Image.open("images/border_{}.png".format(key))
            self.border_images[key] = ImageTk.PhotoImage(img)
        height = self.board_height
        width = self.board_width
        for i in range(height):
            border = self.border_images['l']
            self.border_left.create_image((0, 16*i), image=border, anchor='nw')
            border = self.border_images['r']
            self.border_right.create_image((0, 16*i), image=border, anchor='nw')

        for i in range(width):
            border = self.border_images['top']
            self.border_top.create_image((16*i, 0), image=border, anchor='nw')
            border = self.border_images['mid']
            self.border_mid.create_image((16*i, 0), image=border, anchor='nw')
            border = self.border_images['bot']
            self.border_bot.create_image((16*i, 0), image=border, anchor='nw')
        border = self.border_images['top_l']
        self.border_top_left.create_image((0, 0), image=border, anchor='nw')
        border = self.border_images['top_r']
        self.border_top_right.create_image((0, 0), image=border, anchor='nw')
        border = self.border_images['panel_l']
        self.border_panel_left.create_image((0, 0), image=border, anchor='nw')
        border = self.border_images['panel_r']
        self.border_panel_right.create_image((0, 0), image=border, anchor='nw')
        border = self.border_images['mid_l']
        self.border_mid_left.create_image((0,0), image=border, anchor='nw')
        border = self.border_images['mid_r']
        self.border_mid_right.create_image((0,0), image=border, anchor='nw')
        border = self.border_images['bot_l']
        self.border_bot_left.create_image((0,0), image=border, anchor='nw')
        border = self.border_images['bot_r']
        self.border_bot_right.create_image((0,0), image=border, anchor='nw')

    def __init__(self, master, board_width, board_height):
        self.board_width = board_width
        self.board_height = board_height
        super().__init__(master, width=board_width*16+24, height=board_height*16)
        self.pack()
        self.create_widgets()

    def set_timer(self, t):
        self.panel.timer.set_value(t)

class Tile:
    tile_images = {}
    def __init__(self, tile_id, state=None):
        self.tile_id = tile_id
        self.state = state

class Board(tkinter.Frame):
    def load_tiles(self):
        tile_images = {}
        self.temporarily_down = []
        tile_names = ["tile_{}".format(i) for i in range(9)]
        for key in tile_names + ["unopened", "flag", "blast", "flag_wrong", "mine"]:
            img = Image.open("images/{}.png".format(key))
            tile_images[key] = ImageTk.PhotoImage(img)
        self.tile_images = tile_images

        width = self.board_width
        height = self.board_height
        tiles = [[Tile(self.canvas.create_image((i*16,j*16), anchor="nw"))
                  for i in range(width)] for j in range(height)]
        self.tiles = tiles

    def set_tile(self, i, j, tile_type):
        tile = self.tiles[i][j]
        tile_id = self.tiles[i][j].tile_id
        if tile_type != tile.state:
            self.canvas.itemconfig(tile_id, image=self.tile_images[tile_type])
            tile.state = tile_type

    def __init__(self, master, width, height):
        super().__init__(master)
        self.board_width = width
        self.board_height = height
        self.canvas = tkinter.Canvas(self, width=16*width, height=16*height,
                                     highlightthickness=0)
        self.canvas.pack()
        self.load_tiles()
        for i in range(width):
            for j in range(height):
                self.set_tile(j, i, "unopened")

        self.canvas.bind("<ButtonRelease-1>", self.left_up)
        self.canvas.bind("<ButtonPress-1>", self.mouse_over)
        self.canvas.bind("<B1-Motion>", self.mouse_over)

    def reset_depressed(self, avoid_x=-1, avoid_y=-1):
        add_back = (avoid_x, avoid_y) in self.temporarily_down
        if add_back:
            self.temporarily_down.remove((avoid_x, avoid_y))
        while self.temporarily_down:
            x, y = self.temporarily_down.pop()
            self.set_tile(x, y, "unopened")
        if add_back:
            self.temporarily_down.append((avoid_x, avoid_y))

    def left_up(self, e):
        col = e.x//16
        row = e.y//16
        if (col, row) in self.temporarily_down:
            self.temporarily_down.remove((col,row))
        self.reset_depressed()
        width = self.board_width
        height = self.board_height
        if (0 <= col < width and 0 <= row < height):
            self.set_tile(row, col, "tile_0")

    def mouse_over(self, e):
        col = e.x//16
        row = e.y//16
        width, height = self.board_width, self.board_height
        if not (0 <= col < width and 0 <= row < height):
            # i.e., we've moved off the board
            self.reset_depressed()
        else:
            tile = self.tiles[row][col]
            self.reset_depressed(row, col)
            if tile.state == "unopened":
                self.temporarily_down.append((row, col))
                self.set_tile(row, col, "tile_0")

class Counter(tkinter.Frame):
    border_images = {}
    def create_widgets(self):
        self.digits = []
        display_width = self.display_width
        for i in range(display_width):
            digit = Digit(self)
            digit.grid(row=1, column=i+1)
            self.digits.append(digit)

        self.border_left = tkinter.Canvas(self, width=1, height=25,
                                          highlightthickness=0)
        self.border_left.create_image((0,0), anchor='nw',
                                      image=self.border_images['l'])
        self.border_top = tkinter.Canvas(self, width=13*display_width,
                                         height=1, highlightthickness=0)
        for i in range(display_width):
            self.border_top.create_image((13*i,0), anchor='nw',
                                         image=self.border_images['t'])
        self.border_bot = tkinter.Canvas(self, width=13*display_width,
                                         height=1, highlightthickness=0)
        for i in range(display_width):
            self.border_bot.create_image((13*i,0), anchor='nw',
                                         image=self.border_images['b'])
        self.border_right = tkinter.Canvas(self, width=1, height=25,
                                           highlightthickness=0)
        self.border_right.create_image((0,0), anchor='nw',
                                       image=self.border_images['r'])
        self.border_left.grid(column=0, rowspan=3, row=0)
        self.border_top.grid(column=1, row=0, columnspan=display_width)
        self.border_right.grid(column=display_width+1, rowspan=3, row=0)
        self.border_bot.grid(column=1, row=2, columnspan=display_width)

    def __init__(self, master, display_width):
        super().__init__(master)
        self.display_width = display_width
        self.init_border_images()
        self.create_widgets()

    def init_border_images(self):
        if not self.border_images:
            for key in ('l', 'r', 't', 'b'):
                img = Image.open("images/counter_border_{}.png".format(key))
                self.border_images[key] = ImageTk.PhotoImage(img)

    def set_value(self, n):
        digits = self.display_width
        self.displayed_value = n
        working_width = digits
        sign = 1
        if n < 0:
            working_width = digits-1
            sign = -1
            n = -n
        if abs(n) >= 10**working_width:
            n = 10**working_width-1

        for i in range(digits):
            d = n%10
            n//=10
            self.digits[digits-1-i].set_value(d)
            if n == 0:
                break
        i += 1
        if sign < 0:
            self.digits[digits-1-i].set_value('-')
            i += 1
        for j in range(i, digits):
            self.digits[digits-1-j].set_value('off')

class Digit(tkinter.Canvas):
    digits = {}
    def __init__(self, master):
        super().__init__(master, width=13, height=23,
                         highlightthickness=0)
        self.init_digits()
        self.image_reference = self.create_image((0, 0), anchor='nw')
        self.set_value(0)

    def init_digits(self):
        if not self.digits:
            for i in list(range(10)) + ['-', 'off']:
                img = Image.open("images/counter_{}.png".format(i))
                Digit.digits[i] = ImageTk.PhotoImage(img)

    def set_value(self, n):
        self.itemconfig(self.image_reference, image=self.digits[n])

class Panel(tkinter.Frame):
    def __init__(self, master, board_width):
        super().__init__(master, width=board_width*16, height=26)
        self.mine_counter = Counter(self, 8)
        self.mine_counter.grid(row=0, column=0, padx=3)
        self.face_button = FaceButton(self)
        self.face_button.grid(row=0, column=1)
        self.grid_columnconfigure(1, weight=1) # to center face
        self.timer = Counter(self, 8)
        self.timer.grid(row=0, column=2, padx=3)
        self.config(background="#c0c0c0")

        self.mine_counter.set_value(0)
        self.timer.set_value(0)

class FaceButton(tkinter.Frame):
    face_images = {}
    def __init__(self, master):
        super().__init__(master, width=26, height=26)
        if not self.face_images:
            self.init_face_images()
        self.create_widgets()

    def create_widgets(self):
        self.canvas = tkinter.Canvas(self, width=26, height=26,
                                     highlightthickness=0)
        self.canvas.pack()
        self.image_reference = self.canvas.create_image((0,0), anchor='nw')
        self.set_face('happy')

    def init_face_images(self):
        for key in ["happy", "pressed", "blast", "cool"]:
            img = Image.open("images/face_{}.png".format(key))
            self.face_images[key] = ImageTk.PhotoImage(img)

    def set_face(self, face):
        img = self.face_images[face]
        self.canvas.itemconfig(self.image_reference, image=img)

def main():
    root = tkinter.Tk()
    root.title('PySweeper')
    app = Application(master=root)
    app.mainloop()
    try:
        root.destroy()
    except tkinter.TclError as e:
        pass

if __name__ == "__main__":
    main()


import argparse
import re
import string
from datetime import datetime
import operator
import sys
import colorama
from colorama import Fore,  Back,  Style
from typing import List
from os.path import basename
import math

from computer import Computer

class ChemicalSpec:
    def __init__(self, num, name):
        self.num: int = num
        self.name: str = name

    @staticmethod
    def from_str(definition: str):
        (num_str, name) = definition.strip().split(' ')
        return ChemicalSpec(int(num_str), name)

    def __str__(self):
        return '{0} {1}'.format(self.num, self.name)

    def __repr__(self):
        return str(self)

class Reaction:
    def __init__(self, ingredients: List[ChemicalSpec], result: ChemicalSpec):
        self.ingredients = ingredients
        self.result: ChemicalSpec = result

    @staticmethod
    def from_str(definition: str):
        (ingredients, result) = definition.split(' => ')

        ingredient_list = []
        for ingredient in ingredients.split(', '):
            ingredient_list.append(ChemicalSpec.from_str(ingredient))

        return Reaction(ingredient_list, ChemicalSpec.from_str(result))

    def name(self) -> str:
        return self.result.name

    def __str__(self):
        return '{0} => {1}'.format(self.ingredients, self.result)

    def __repr__(self):
        return str(self)

class Nanofactory:
    def __init__(self, reaction_definitions: List[Reaction]):
        self.reaction_defs = {}
        self.chemical_store = {'ORE': 0}
        self.order_total = {'ORE': 0}
        for reaction in reaction_definitions:
            self.reaction_defs[reaction.name()] = reaction
            self.chemical_store[reaction.name()] = 0
            self.order_total[reaction.name()] = 0

    def consume(self, order_size: int, name: str):
        # print('consuming {0} {1}'.format(order_size, name))

        stock = self.chemical_store[name]
        if order_size <= stock:
            self.chemical_store[name] -= order_size
            return
        extra_needed = order_size - stock
        self.chemical_store[name] = 0

        if name == 'ORE':
            self.order_total[name] += extra_needed
            return

        reaction = self.reaction_defs[name]
        reaction_yield = reaction.result.num
        reactions_needed = 1
        if reaction_yield < extra_needed:
            reactions_needed = int(extra_needed / reaction_yield)
            if extra_needed % reaction_yield != 0:
                reactions_needed += 1

        # print('   {0} {1} reactions needed'.format(reactions_needed, name))
        for chem_spec in reaction.ingredients:
            self.consume(chem_spec.num * reactions_needed, chem_spec.name)
        self.chemical_store[name] += reactions_needed * reaction_yield - extra_needed

reactions = {}
multiples = {}

def main():
    colorama.init()

    inputFile = basename(__file__)[:2] + '-input.txt'
    # inputFile = basename(__file__)[:2] + '-example-1.txt'
    # inputFile = basename(__file__)[:2] + '-example-2.txt'
    # inputFile = basename(__file__)[:2] + '-example-3.txt'
    # inputFile = basename(__file__)[:2] + '-example-4.txt'
    # inputFile = basename(__file__)[:2] + '-example-5.txt'
    lines = []
    with open(inputFile,  'r') as infile:
        for line in infile:
            lines.append(line.strip())

    for line in lines:
        reaction = Reaction.from_str(line)
        print('loaded:', reaction)
        reactions[reaction.result.name] = reaction

    factory = Nanofactory(list(reactions.values()))

    print('')
    fuel_count = -1
    while factory.order_total['ORE'] < 1000000000000:
        fuel_count += 1
        if fuel_count % 1000 == 0:
            print('made {0} fuel from {1} ore'.format(
                fuel_count, format(factory.order_total['ORE'], ',d')))
        factory.consume(1, 'FUEL')
    print('')
    print('made {0} fuel from {1} ore'.format(fuel_count, factory.order_total['ORE']))

if __name__ == "__main__":
    main()


import warnings
from functools import partial
from typing import Any, Optional, List

from torchvision.transforms.functional import InterpolationMode

from ...models.mobilenetv3 import MobileNetV3, _mobilenet_v3_conf, InvertedResidualConfig
from ..transforms.presets import ImageNetEval
from ._api import Weights, WeightEntry
from ._meta import _IMAGENET_CATEGORIES

__all__ = [
    "MobileNetV3",
    "MobileNetV3LargeWeights",
    "MobileNetV3SmallWeights",
    "mobilenet_v3_large",
    "mobilenet_v3_small",
]

def _mobilenet_v3(
    inverted_residual_setting: List[InvertedResidualConfig],
    last_channel: int,
    weights: Optional[Weights],
    progress: bool,
    **kwargs: Any,
) -> MobileNetV3:
    if weights is not None:
        kwargs["num_classes"] = len(weights.meta["categories"])

    model = MobileNetV3(inverted_residual_setting, last_channel, **kwargs)

    if weights is not None:
        model.load_state_dict(weights.state_dict(progress=progress))

    return model

_common_meta = {"size": (224, 224), "categories": _IMAGENET_CATEGORIES, "interpolation": InterpolationMode.BILINEAR}

class MobileNetV3LargeWeights(Weights):
    ImageNet1K_RefV1 = WeightEntry(
        url="https://download.pytorch.org/models/mobilenet_v3_large-8738ca79.pth",
        transforms=partial(ImageNetEval, crop_size=224),
        meta={
            **_common_meta,
            "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#mobilenetv3-large--small",
            "acc@1": 74.042,
            "acc@5": 91.340,
        },
    )

class MobileNetV3SmallWeights(Weights):
    ImageNet1K_RefV1 = WeightEntry(
        url="https://download.pytorch.org/models/mobilenet_v3_small-047dcff4.pth",
        transforms=partial(ImageNetEval, crop_size=224),
        meta={
            **_common_meta,
            "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#mobilenetv3-large--small",
            "acc@1": 67.668,
            "acc@5": 87.402,
        },
    )

def mobilenet_v3_large(
    weights: Optional[MobileNetV3LargeWeights] = None, progress: bool = True, **kwargs: Any
) -> MobileNetV3:
    if "pretrained" in kwargs:
        warnings.warn("The argument pretrained is deprecated, please use weights instead.")
        weights = MobileNetV3LargeWeights.ImageNet1K_RefV1 if kwargs.pop("pretrained") else None
    weights = MobileNetV3LargeWeights.verify(weights)

    inverted_residual_setting, last_channel = _mobilenet_v3_conf("mobilenet_v3_large", **kwargs)
    return _mobilenet_v3(inverted_residual_setting, last_channel, weights, progress, **kwargs)

def mobilenet_v3_small(
    weights: Optional[MobileNetV3SmallWeights] = None, progress: bool = True, **kwargs: Any
) -> MobileNetV3:
    if "pretrained" in kwargs:
        warnings.warn("The argument pretrained is deprecated, please use weights instead.")
        weights = MobileNetV3SmallWeights.ImageNet1K_RefV1 if kwargs.pop("pretrained") else None
    weights = MobileNetV3SmallWeights.verify(weights)

    inverted_residual_setting, last_channel = _mobilenet_v3_conf("mobilenet_v3_small", **kwargs)
    return _mobilenet_v3(inverted_residual_setting, last_channel, weights, progress, **kwargs)


# -*- coding: utf-8  -*-
"""Unit tests for database.py."""

import unittest

import mock

import database

class TestReData(unittest.TestCase):

    def test_reData_event_line(self):
        input_data = 'wl["monuments"][2010] = {'
        result = database.reData(input_data, 2014)
        expected = {
            u'country': None,
            u'year': '2010',
            u'end': None,
            u'event': 'monuments',
            u'start': None
        }
        self.assertEqual(result, expected)

    def test_reData_event_line_public_art(self):
        input_data = 'wl["public_art"][2012] = {'
        result = database.reData(input_data, 2014)
        expected = {
            u'country': None,
            u'year': '2012',
            u'end': None,
            u'event': 'public_art',
            u'start': None
        }
        self.assertEqual(result, expected)

    def test_reData_country_line(self):
        input_data = '''
    ["az"] = {["start"] = 20170430200000, ["end"] = 20170531195959},
    '''
        result = database.reData(input_data, 2017)
        expected = {
            u'country': 'az',
            u'year': None,
            u'end': '20170531195959',
            u'event': None,
            u'start': '20170430200000'
        }
        self.assertEqual(result, expected)

class TestRePrefix(unittest.TestCase):

    def test_re_prefix_match_ascii_line(self):
        self.assertIsNotNone(database.re_prefix(u'    ["az"] = "Azerbaijan",'))

    def test_re_prefix_match_ascii_line_with_space(self):
        self.assertIsNotNone(database.re_prefix(u'    ["gq"] = "Equatorial Guinea",'))

    def test_re_prefix_match_ascii_line_with_dash(self):
        self.assertIsNotNone(database.re_prefix(u'    ["gw"] = "Guinea-Bissau",'))

    def test_re_prefix_match_ascii_line_with_accents(self):
        self.assertIsNotNone(database.re_prefix(u'    ["re"] = "Réunion",'))

    def test_re_prefix_match_ascii_line_with_apostrophe(self):
        self.assertIsNotNone(database.re_prefix(u'    ["ci"] = "Côte d\'Ivoire",'))

class TestGetDataMixin(unittest.TestCase):

    def setUp(self):
        patcher = mock.patch('database.get_data_for_category', autospec=True)
        self.mock_get_data_for_category = patcher.start()
        self.mock_get_data_for_category.return_value = (
            (20140523121626, False, u'Bob', 20130523235032),
            (20140523121626, False, u'Alice', 20140528235032),
            (20140529121626, False, u'Alice', 20140528235032),
            (20140530121626, False, u'Alice', 20140528235032),
        )
        self.addCleanup(patcher.stop)

        self.expected_timestamp_data = {
            '20140523': {
                'images': 2,
                'joiners': 2,
                'newbie_joiners': 1
            },
            '20140529': {
                'images': 1,
                'joiners': 0,
                'newbie_joiners': 0
            },
            '20140530': {
                'images': 1,
                'joiners': 0,
                'newbie_joiners': 0
            }
        }

        self.images_count = 4
        self.usercount = 2
        self.userreg = 1
        self.usage = 0

        self.user_data = {
            u'Alice': {
                'count': 3,
                'reg': 20140528235032,
                'usage': 0
            },
            u'Bob': {
                'count': 1,
                'reg': 20130523235032,
                'usage': 0
            }
        }

class TestGetData(TestGetDataMixin):

    def test_GetData(self):
        competition_config = {
            u'Brazil': {'start': 20140501030000, 'end': 20140601025959},
        }

        result = database.getData("Dumplings2014", competition_config)

        expected = {
            u'Brazil': {
                'count': self.images_count,
                'usercount': self.usercount,
                'start': 20140501030000,
                'userreg': self.userreg,
                'data': self.expected_timestamp_data,
                'users': self.user_data,
                'usage': self.usage,
                'category': u'Images_from_Wiki_Loves_Dumplings_2014_in_Brazil',
                'end': 20140601025959
            }
        }
        self.assertEquals(result, expected)

class TestGetCountryData(TestGetDataMixin):

    def test_get_country_data(self):
        category = u'Images_from_Wiki_Loves_Dumplings_2014_in_Brazil'
        result = database.get_country_data(category, 20140501030000, 20140601025959)

        expected = {
            'count': self.images_count,
            'usercount': self.usercount,
            'start': 20140501030000,
            'userreg': self.userreg,
            'data': self.expected_timestamp_data,
            'users': self.user_data,
            'usage': self.usage,
            'category': category,
            'end': 20140601025959
        }
        self.mock_get_data_for_category.assert_called_once_with(category)
        self.assertEquals(result, expected)

class TestUpdateEventData(TestGetDataMixin):

    def setUp(self):
        super(self.__class__, self).setUp()
        patcher = mock.patch('database.write_database_as_json', autospec=True)
        self.mock_write_database_as_json = patcher.start()
        self.addCleanup(patcher.stop)

    def test_udpate_event_data(self):
        self.maxDiff = None
        event_name = u'dumplings2014'
        event_configuration = {
            u'Azerbaijan': {
                'start': 20140430200000,
                'end': 20140531195959,
            },
            u'Guinea-Bissau': {
                'start': 20140430200000,
                'end': 20140531195959,
            },
        }
        db = {}
        result = database.update_event_data(event_name, event_configuration, db)

        expected_base = {
            'count': self.images_count,
            'usercount': self.usercount,
            'start': 20140430200000,
            'userreg': self.userreg,
            'data': self.expected_timestamp_data,
            'users': self.user_data,
            'usage': self.usage,
            'end': 20140531195959
        }

        expected_az = expected_base.copy()
        expected_az.update({
            'category': u'Images_from_Wiki_Loves_Dumplings_2014_in_Azerbaijan',
        })
        expected_gb = expected_base.copy()
        expected_gb.update({
            'category': u'Images_from_Wiki_Loves_Dumplings_2014_in_Guinea-Bissau',
        })

        expected = {
            u'dumplings2014': {
                u'Azerbaijan': expected_az,
                u'Guinea-Bissau': expected_gb,
            }
        }
        self.assertEquals(result, expected)
        self.mock_write_database_as_json.assert_called_once_with(expected)

class TestParseConfig(unittest.TestCase):

    def test_parse_config_empty(self):
        config = ''
        result = database.parse_config(config)
        expected = {}
        self.assertEquals(result, expected)

    def test_parse_config(self):
        config = '''
wl["prefixes"] = {
    ["az"] = "Azerbaijan",
    ["gw"] = "Guinea-Bissau"
}

wl["monuments"][2017] = {
    ["az"] = {["start"] = 20170430200000, ["end"] = 20170531195959},
    ["gw"] = {["start"] = 20170430200000, ["end"] = 20170531195959},
}

wl["monuments"][2018] = {
    ["az"] = {["start"] = 20180430200000, ["end"] = 20180531195959},
    ["gw"] = {["start"] = 20180430200000, ["end"] = 20180531195959},
}

'''
        result = database.parse_config(config)
        expected = {
            u'monuments2017': {
                u'Azerbaijan': {
                    'start': 20170430200000,
                    'end': 20170531195959,
                },
                u'Guinea-Bissau': {
                    'start': 20170430200000,
                    'end': 20170531195959,
                },
            },
            u'monuments2018': {
                u'Azerbaijan': {
                    'start': 20180430200000,
                    'end': 20180531195959,
                },
                u'Guinea-Bissau': {
                    'start': 20180430200000,
                    'end': 20180531195959,
                },
            }
        }
        self.assertEquals(result, expected)

if __name__ == "__main__":
    unittest.main()


import tensorflow as tf
import numpy as np
import loader
import sys
from PIL import Image
from matplotlib import pyplot as plt
OBJECT_DETECTION_PATH = 'c:/users/weifenghu/anaconda3/lib/site-packages/tensorflow/models/research/'
sys.path.insert(0, OBJECT_DETECTION_PATH)
from object_detection.utils import visualization_utils as vis_util

categories_index = loader.load_label_map()
detection_graph = loader.load_frozen_graph()
TEST_IMAGE = 'data/val2017/000000002006.jpg'
def run_inference(image, graph):
    with graph.as_default():
        with tf.Session() as sess:
            tensor = {}
            tensor['num_detections'] = tf.get_default_graph().get_tensor_by_name('num_detections:0')
            tensor['detection_boxes'] = tf.get_default_graph().get_tensor_by_name('detection_boxes:0')
            tensor['detection_scores'] = tf.get_default_graph().get_tensor_by_name('detection_scores:0')
            tensor['detection_classes'] = tf.get_default_graph().get_tensor_by_name('detection_classes:0')
            image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')

            output = sess.run(tensor, feed_dict={image_tensor: np.expand_dims(image, 0)})
            # convert from float numpy array to primitive type
            output['num_detections'] = int(output['num_detections'][0])
            output['detection_classes'] = output['detection_classes'][0].astype(np.uint8)
            output['detection_boxes'] = output['detection_boxes'][0]
            output['detection_scores'] = output['detection_scores'][0]
    return output

image = Image.open(TEST_IMAGE)
image_arr = loader.load_image_to_array(image)
print('running object detection . . .')
output = run_inference(image_arr, detection_graph)
print('object detection completed')
vis_util.visualize_boxes_and_labels_on_image_array(
    image_arr,
    output['detection_boxes'],
    output['detection_classes'],
    output['detection_scores'],
    categories_index,
    instance_masks=None,
    use_normalized_coordinates=True,
    line_thickness=8
)
plt.figure(figsize=(12, 8))
plt.imshow(image_arr)
plt.savefig('result/2006.jpg')


# -*- coding: utf-8 -*-
"""
Created on Fri May 28 16:47:58 2021

@author: wdu
"""
import sympy as sym

from sympy import *
from sympy import  Sum, factorial, oo, IndexedBase, Function
from sympy.abc import i, k, m, n, x

import numpy as np

import matplotlib.pyplot as plt
from scipy.io import loadmat, savemat

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

'''
#Derivatives of multivariable function
p=2
t=.5
c , n = sym.symbols('c n')
f = ((c*(1-n)**t)**(1-p) - 1)/(1-p)

#Differentiating partially w.r.t x
derivative_f = f.diff(c)
print(derivative_f)

f1 = lambdify([x,y], derivative_f )

p=2
t=.5
c , n = sym.symbols('c n')
h = ((c*(1-n)**t)**(1-p) - 1)/(1-p)

#Differentiating partially w.r.t x
derivative_fh = h.diff(n)
print(derivative_fh)

#-----------------------------------------------------------
#series

w = [1,2,3]
w = IndexedBase('w')

h = Sum( w[n]**2 , (n, 1, 3)).doit()
'''

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

CJAC=loadmat('AltCJAC')
CJAC=list(CJAC.items())
CJAC=np.array(CJAC)
CJAC = CJAC[3][1].T

CJACW=loadmat('AltCJACW')
CJACW=list(CJACW.items())
CJACW=np.array(CJACW)
CJACW = CJACW[3][1].T

CJACN=loadmat('AltCJACN')
CJACN=list(CJACN.items())
CJACN=np.array(CJACN)
CJACN = CJACN[3][1].T

AJAC=loadmat('AltAJAC')
AJAC=list(AJAC.items())
AJAC=np.array(AJAC)
AJAC = AJAC[3][1]

AJACW=loadmat('AltAJACW')
AJACW=list(AJACW.items())
AJACW=np.array(AJACW)
AJACW = AJACW[3][1]

AJACN=loadmat('AltAJACN')
AJACN=list(AJACN.items())
AJACN=np.array(AJACN)
AJACN = AJACN[3][1]

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

tau = 0.1656344537815126
N_ss = 1.19
w_ss = 1/1.012
Z_ss = 1
LivPrb = .99375
DiscFac = .968
v=2

rstar = 1.048**.25 -1

rho = 2
C_ss = 1

#Phillips Curves parameters
#lambda_W = .899 #probability a firm won't be able to change wage
#lambda_P = .926  #probability a firm won't be able to change wage

lambda_W = .75 #probability a firm won't be able to change wage
lambda_P = .75  #probability a firm won't be able to change wage

Lambda = (1-lambda_P)*(1-(lambda_P/(1+rstar)))/lambda_P
ParamW = ( (1-lambda_W) / lambda_W) * ( 1 - LivPrb * lambda_W )

#Policy
phi = 0
phi_y = 0

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

# Shock Parameters
Z = .01 # Initial Productivity shock
m_e = .01 # Initial Monetary Policy Shock
p=.66 # AR1 Coefficient

ZshkList=[]
mshkList=[]

for t in range(200):

    ZshkList.append((p**t)*Z)
    mshkList.append((p**t)*m_e)

Zshks= np.array(ZshkList)
mshk = np.array(mshkList)

# Specify Shock, if Shk = 0 then productivity shock, else Shk = 1 => monetary policy Shock

Shk = 1

dZ = np.zeros((400,1))
ShkLength = 200

if Shk == 0:

    for i in range(ShkLength):
        dZ[i][0] = Zshks[i]

if Shk == 1:

    for i in range(ShkLength):
       dZ[i + 200][0]=mshk[i]

#------------------------------------------------------------------------------
# this jacobian for pi_{t+1} wrt t=>0, below is jacobian for pi_{t} wrt t=>0

J_pi_w_1 = np.zeros((200,200)) # jacobian of inflation response to change in wage. Rows represent period in which there is a wage change. Columns represent period of inflation

for j in range(200):

    for i in range(200):

        if i < j:

            J_pi_w_1[i][j] = -Lambda*(-1/w_ss) * (1/(1+rstar)**(j-i))

# this jacobian for pi_{t+1} wrt t=>0, below is jacobian for pi_{t} wrt t=>0

J_pi_Z_1 = np.zeros((200,200)) # jacobian of inflation response to change in wage. Rows represent period in which wage change occurs. Columns denotes period of inflation

for j in range(200):

    for i in range(200):

        if i < j :
            J_pi_Z_1[i][j] =  -(1/(1+rstar)**(j-i))*(Lambda/Z_ss)

# Price inflation

J_pi_w = np.zeros((200,200)) # jacobian of inflation response to change in wage. Rows represent period in which there is a wage change. Columns represent period of inflation

for j in range(200):

    for i in range(200):

        J_pi_w[i][i] = -Lambda*(-1/w_ss)

        if i < j:
            J_pi_w[i][j] = -Lambda * (-1/w_ss) * ( 1 / (1+rstar)**(j-i))

J_pi_Z = np.zeros((200,200))

for j in range(200):

    for i in range(200):

        J_pi_Z[i][i] =   -Lambda/Z_ss

        if i < j :

            J_pi_Z[i][j] =  -(1/(1+rstar)**(j-i))*(Lambda/Z_ss)

#----------------------------------------------------------------------------
# Output

J_Y_N = np.zeros((200,200)) # Jacobian of output response to change in labor supply

for i in range(200):

    J_Y_N[i][i] = Z_ss

J_Y_Z = np.zeros((200,200)) # Jacobian of output response to change in labor supply

for i in range(200):

    J_Y_Z[i][i] = N_ss

#-----------------------------------------------------------------------------
# Government Spending

J_G_w = np.zeros((200,200)) #Jacobian of G wrt wage

for i in range(200):

    J_G_w[i][i] = tau*N_ss

J_G_N = np.zeros((200,200)) # Jacobian of G wrt N

for i in range(200):

    J_G_N[i][i] = tau*w_ss

#-----------------------------------------------------------------------------
# Nominal Rate

J_i_pi = np.zeros((200,200)) # Jacobian of i wrt pi

for i in range(200):

    J_i_pi[i][i] = phi

J_i_Y = np.zeros((200,200)) # Jacobian of i wrt Y

for i in range(200):

    J_i_Y[i][i] = phi_y

J_i_v = np.zeros((200,200)) # Jacobian of i wrt v

for i in range(200):

    J_i_v[i][i] = 1

#--------------------------------------------]
#----------------------------------------------------------------------
#Wage inflation

J_piw_C = np.zeros((200,200))

for j in range(200):

    for i in range(200):

        J_piw_C[i][i] =  (-rho/C_ss)

        if i<j:
            J_piw_C[i][j] =  (-rho/C_ss)*((DiscFac*LivPrb)**(j-i))

J_piw_C = -ParamW*J_piw_C

J_piw_w = np.zeros((200,200)) # Jacobian of wage Inflation wrt wage

for j in range(200):

    for i in range(200):

        J_piw_w[i][i] =  -ParamW *(1/w_ss)

        if i<j:
            J_piw_w[i][j] = -ParamW* (1/w_ss) *((DiscFac*LivPrb)**(j-i))

J_piw_w = J_piw_w + np.dot(J_piw_C,CJACW)

J_piw_N = np.zeros((200,200)) # Jacobian of wage inflation wrt N

for j in range(200):

    for i in range(200):

        J_piw_N[i][i] =  -ParamW*(-v/N_ss )

        if i<j:
            J_piw_N[i][j] =  -ParamW*(-v/N_ss) *((DiscFac*LivPrb)**(j-i))

J_piw_N = J_piw_N  + np.dot(J_piw_C,CJACN)

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

# Composing HU jacobian ways through DAG

#Goods Market Clearing Target
h1 = np.zeros((200,600))
h1[:,0:200] = CJAC #Partials wrt r
h1[:,200:400] =  CJACW + J_G_w #partials wrt w
h1[:,400:600] = CJACN - J_Y_N + J_G_N #Partials wrt N

# Wage Residual Target
h2 = np.zeros((200,600))
h2[:,0:200] =    - np.dot(J_piw_C, CJAC)
h2[:,200:400] = np.identity(200)*(1/w_ss) - J_piw_w + J_pi_w

for j in range(400):
    for i in range(200):
        if 200 + i == j and j>199 and j<400 :
            h2[i,j-1] = (-1/w_ss) - (-ParamW*(-rho/C_ss)*(CJACW[i][i-1] ))

h2_wagelag = np.zeros((200,200))
for j in range(200):
    for i in range(199):
        if  i + 1 == j :
            h2_wagelag[i+1, i ] = (1/w_ss)  + (-ParamW*(-rho/C_ss)*(CJACW[i+1][i] ))

h2[:,200:400]= np.identity(200)*(1/w_ss) - h2_wagelag - J_piw_w + J_pi_w

h2[:,400:600] =   -J_piw_N  #should be a negative here but it breaks things,

h3_r = np.zeros((200,200))
for j in range(200):
    for i in range(199):
        if  i + 1 == j :
            h3_r[i-1, i ] = 1 # because r_{t} =r_{t+1}^{a}

# Fisher Residual Target
h3 = np.zeros((200,600))
h3[:, 0:200] = h3_r
h3[:, 200:400] = (1+rstar)*J_pi_w_1 - phi*J_pi_w
h3[:, 400:600] = - np.dot(J_i_Y,J_Y_N)

h1h2= np.vstack((h1,h2))

HU = np.vstack((h1h2,h3))

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

# Composing HZ with DAG method

h1z  = np.zeros((200,400))
h1z[:,0:200] = - J_Y_Z

h2z = np.zeros((200,400))
h2z[:,0:200] = J_pi_Z

h3z = np.zeros((200,400))
h3z[:,0:200] = (1+rstar)*J_pi_Z_1 - phi * J_pi_Z - phi_y * J_Y_Z
h3z[:,200:400] = - J_i_v

# Stack all the matrices
h1zh2z= np.vstack((h1z,h2z))
HZ = np.vstack((h1zh2z,h3z))

#----------------------------------------------------------------------------------------
# Putting it all together

invHU = np.linalg.inv(HU)
G =np.dot(-invHU,HZ)
dU = np.dot(G,dZ)

dr = dU[0:200]
dw = dU[200:400]
dN = dU[400:600]

#Real Rate and Wage, Labor/hours
plt.plot(dr, label = 'Real Interest Rate')
plt.plot(dw , label = 'Real Wage')
plt.plot(dN , label = 'Labor')
plt.legend()
plt.show()

#Consumption
dC =  np.dot(CJAC,dr) + np.dot(CJACW,dw) + np.dot(CJACN,dN)
#plt.plot(dC)
#plt.title("Consumption")
#plt.show()

#Government Spending
dG = np.dot(J_G_N,dN) + np.dot(J_G_w,dw)
#plt.plot(dG)
#plt.title("Government Spending")
#plt.show()

#output
dY = np.dot(J_Y_N, dN) + np.dot(J_Y_Z,dZ[0:200])
#plt.plot(dY)
#plt.title("Output")
#plt.show()

#price inflation
dpi = np.dot(J_pi_w,dw) + np.dot(J_pi_Z,dZ[0:200])
#plt.plot(dpi)
#plt.title("Price Inflation")
#plt.show()

#wage inflation
dpiw = np.dot(J_piw_N,dN) + np.dot(J_piw_w,dw) +  np.dot(J_piw_C,dC)
#plt.plot(dpiw)
#plt.title("Wage Inflation")
#plt.show()

#nominal Rate
di = np.dot(J_i_pi, dpi) + np.dot(J_i_Y, dY) + np.dot(J_i_v, dZ[200:400])
#plt.plot(di)
#plt.title("Nominal Rate")
#plt.show()

#Dividends
dD = dY - dw*dN
#plt.plot(dD)
#plt.title("Dividends")
#plt.show()

#Stock Price

#percentages

fig, axs = plt.subplots(2, 2)
axs[0, 0].plot(100*dr )
axs[0, 0].set_title("Real Interest Rate")
axs[1, 0].plot(100*dw/w_ss)
axs[1, 0].set_title("Real Wage")
axs[1, 0].sharex(axs[0, 0])
axs[0, 1].plot(100*dpiw)
axs[0, 1].set_title("Nominal Wage Inflation")
axs[1, 1].plot(100*dpi)
axs[1, 1].set_title("Price Inflation")
fig.tight_layout()
#plt.savefig("GIPR1.jpg", dpi=500)

fig, axs = plt.subplots(2, 2)
axs[0, 0].plot(100*dY/N_ss)
axs[0, 0].set_title("Output")
axs[1, 0].plot(100*dC/C_ss)
axs[1, 0].set_title("Consumption")
axs[1, 0].sharex(axs[0, 0])
axs[0, 1].plot(100*dG/.19)
axs[0, 1].set_title("Government Spending")
axs[1, 1].plot(100*dN/N_ss)
axs[1, 1].set_title("Labor")
fig.tight_layout()
#plt.savefig("GIPR2.jpg", dpi=500)

fig, axs = plt.subplots(2, 2)
axs[0, 0].plot(dD)
axs[0, 0].set_title("Dividends")
axs[1, 0].plot(100*di)
axs[1, 0].set_title("Nominal Rate")
axs[1, 0].sharex(axs[0, 0])
axs[0, 1].plot(dZ[0:200])
axs[0, 1].set_title("Z")
axs[1, 1].plot(dZ[200:400])
axs[1, 1].set_title("v")
fig.tight_layout()

'''

fig, axs = plt.subplots(2, 2)
axs[0, 0].plot(dr)
axs[0, 0].set_title("Real Interest Rate")
axs[1, 0].plot(dw/w_ss)
axs[1, 0].set_title("Real Wage")
axs[1, 0].sharex(axs[0, 0])
axs[0, 1].plot(dpiw)
axs[0, 1].set_title("Nominal Wage Inflation")
axs[1, 1].plot(dpi)
axs[1, 1].set_title("Price Inflation")
fig.tight_layout()
#plt.savefig("GIPR1.jpg", dpi=500)

fig, axs = plt.subplots(2, 2)
axs[0, 0].plot(dY/N_ss)
axs[0, 0].set_title("Output")
axs[1, 0].plot(dC/C_ss)
axs[1, 0].set_title("Consumption")
axs[1, 0].sharex(axs[0, 0])
axs[0, 1].plot(dG/.19)
axs[0, 1].set_title("Government Spending")
axs[1, 1].plot(dN/N_ss)
axs[1, 1].set_title("Labor")
fig.tight_layout()
#plt.savefig("GIPR2.jpg", dpi=500)

fig, axs = plt.subplots(2, 2)
axs[0, 0].plot(dD/(N_ss*(1-w_ss)))
axs[0, 0].set_title("Dividends")
axs[1, 0].plot(di)
axs[1, 0].set_title("Nominal Rate")
fig.tight_layout()

rangelen = 30

fig, axs = plt.subplots(2, 2)
axs[0, 0].plot(dr[0:rangelen])
axs[0, 0].set_title("Real Interest Rate")
axs[1, 0].plot(dw[0:rangelen])
axs[1, 0].set_title("Real Wage")
axs[1, 0].sharex(axs[0, 0])
axs[0, 1].plot(dpiw[0:rangelen])
axs[0, 1].set_title("Nominal Wage Inflation")
axs[1, 1].plot(dpi[0:rangelen])
axs[1, 1].set_title("Price Inflation")
fig.tight_layout()
#plt.savefig("GIPR1.jpg", dpi=500)

fig, axs = plt.subplots(2, 2)
axs[0, 0].plot(dY[0:rangelen])
axs[0, 0].set_title("Output")
axs[1, 0].plot(dC[0:rangelen])
axs[1, 0].set_title("Consumption")
axs[1, 0].sharex(axs[0, 0])
axs[0, 1].plot(dG[0:rangelen])
axs[0, 1].set_title("Government Spending")
axs[1, 1].plot(dN[0:rangelen])
axs[1, 1].set_title("Labor")
fig.tight_layout()
#plt.savefig("GIPR2.jpg", dpi=500)

fig, axs = plt.subplots(2, 2)
axs[0, 0].plot(dD[0:rangelen])
axs[0, 0].set_title("Dividends")
axs[1, 0].plot(di[0:rangelen])
axs[1, 0].set_title("Nominal Rate")
axs[1, 0].sharex(axs[0, 0])
axs[0, 1].plot(dZ[0:200])
axs[0, 1].set_title("Z")
axs[1, 1].plot(dZ[200:400])
axs[1, 1].set_title("v")
fig.tight_layout()

'''

'''

def PsumMrs(t,d,x):
    # t is the current period
    # d is the period in which there is a deviation in the interest rate

    result = 0

# =============================================================================
#     if x==1:
#
#         for k in range(t):
#             result +=(LivPrb**k)*((rho/C_ss)*(DiscFac**k)*CJAC[t][k])
#     else:
#
# =============================================================================

    if x == 0:
        JAC = CJAC
    elif x==1:
        JAC =CJACW
    elif x==2:
        JAC = CJACN

    for k in range(200-t):
        result +=(LivPrb**k)*((rho/C_ss)*JAC[d][t+k]) #k here is the value in period k when the change occurs in period t

    #for k in range(200-t):
        #result +=(LivPrb**k)*((rho/C_ss)*(DiscFac**k)*JAC[d][t+k])

    result = -ParamW*result

    return result

H_u = np.zeros((600,600))

H1=[] #target 1
for i in range(200):
    H1.append(3*i)

H2 =[] # target 2
for i in range(200):
    H2.append(3*i + 1)

H3 = [] # target 3
for i in range(200):
    H3.append(3*i + 2)

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

# the following calculates H_1 partial derivatives w.r.t. r,w,N for all t = 0,1,2,...
# i/3 is the period, t, that we are in
# j is the period in which the deviation occurs

for i in H1:

    for j in range(200):
        H_u[i][j] = CJAC[j][int(i/3)]
        H_u[i][200 + j] = CJACW[j][int(i/3)]
        H_u[i][400 + j] = CJACN[j][int(i/3)]

    H_u[i][200 + int(i/3)] =  CJACW[int(i/3)][int(i/3)] - tau*N_ss
    H_u[i][400 + int(i/3)] = CJACN[int(i/3)][int(i/3)] - Z_ss - w_ss*tau

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

for i in H2:
    for j in range(200):
                                               # (i-1)/3 is the period, t, that we are in
        H_u[i][j] = PsumMrs(int((i-1)/3) , j, 0)  # j is the period in which the deviation occurs

        if int((i-1)/3) > j:

           H_u[i][200 + j] = PsumMrs(int((i-1)/3), j, 1 ) #wage
           H_u[i][400 + j] =  PsumMrs(int((i-1)/3), j, 2 ) #labor

        elif int((i-1)/3)  ==  j + 1:

            H_u[i][200 + j] = - 1/w_ss + PsumMrs(int((i-1)/3), j, 1 )
            H_u[i][400 + j] = PsumMrs(int((i-1)/3), j, 2 )

        elif int((i-1)/3) ==  j:

            H_u[i][200 + j] = 1/w_ss - ParamW*(1/w_ss) + PsumMrs(int((i-1)/3), j, 1 )  - Lambda*(-1/w_ss)
            H_u[i][400 + j] = ParamW* (-v/N_ss) + PsumMrs(int((i-1)/3), j, 2 ) # should a discount factor be added here?

        elif int((i-1)/3) < j:
            H_u[i][200 + j] =  - ParamW*(LivPrb**j)*((1/w_ss))  +  PsumMrs(int((i-1)/3), j, 1 ) - (Lambda/(1+rstar)**(j-int((i-1)/3)))*(-1/w_ss)
            H_u[i][400 + j] = ParamW*(LivPrb**(j-int((i-1)/3)))*(-v/N_ss) + PsumMrs(int((i-1)/3), j, 2 )

    H_u[i][200] = 1/w_ss + ParamW*1/w_ss +  PsumMrs(int((i-1)/3),0, 1 )+ Lambda*(-1/w_ss)

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

for i in H3:

    for j in range(200):

        if int((i-2)/3) == j:
             H_u[i][j] = 1
             H_u[i][200 + j] = phi*Lambda*(1/w_ss)
             H_u[i][400 + j] = phi_y*Z_ss

        elif int((i-2)/3) < j:
            H_u[i][j] = 0
            H_u[i][200 + j] = -(Lambda/(1+rstar)**j)*(1/w_ss)*(1+rstar) + (phi*Lambda/(1+rstar)**(j-int((i-2)/3)))*(1/w_ss)
            H_u[i][400 + j] = 0

        elif int((i-2)/3) > j:
            H_u[i][j] = 0
            H_u[i][200 + j] = 0
            H_u[i][400 + j] = 0

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

H_z = np.zeros((600,400))

for i in H1:

    for j in range(200):

        if int(i/3)== j:
             H_z[i][j] = - N_ss

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

for i in H2:

    for j in range(200):

        if int((i-1)/3) == j:

            H_z[i][j] = - Lambda/Z_ss

        if int((i-1)/3) < j:

            H_z[i][j] = - (Lambda / (1 + rstar)**(j-int((i-1)/3)))*(1/Z_ss)

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

for i in H3:

    for j in range(200):

        if int((i-2)/3) == j :

            H_z[i][j] =   phi*Lambda/Z_ss - phi_y*N_ss
            H_z[i][200 + j] = -1

        if int((i-2)/3) < j :

            H_z[i][j] =  -(1+rstar)*(1/(1+rstar)**(j-int((i-2)/3)))*(Lambda/Z_ss) + (1/(1+rstar)**(j-int((i-2)/3)))*phi*Lambda/Z_ss - phi_y*N_ss

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

Inv_H_u = np.linalg.inv(H_u)

dU = np.dot( np.dot(-Inv_H_u,H_z),dZ)

dr = dU[0:200]
dw = dU[200:400]
dN = dU[400:600]

plt.plot(dr, label = 'Interest Rate')
plt.plot(dw , label = 'Wage')
plt.plot(dN , label = 'Labor')
plt.legend()
plt.show()

#Consumption
dC =  np.dot(CJAC,dr) + np.dot(CJACW,dw) + np.dot(CJAC,dN)
plt.plot(dC)
plt.title("Consumption")
plt.show()

#Government Spending
dG = np.dot(J_G_N, dN) + np.dot(J_G_w,dw)
plt.plot(dG)
plt.title("Government Spending")
plt.show()

#output
dY = np.dot(J_Y_N, dN) + np.dot(J_Y_Z,dZ[0:200])
plt.plot(dY)
plt.title("Output")
plt.show()

#price inflation
dpi = np.dot(J_pi_w,dw) + np.dot(J_pi_Z,dZ[0:200])
plt.plot(dpi)
plt.title("Price Inflation")
plt.show()

#wage inflation
dpiw = np.dot(J_piw_C,dC) + np.dot(J_piw_N,dN) + np.dot(J_piw_w,dw)
plt.plot(dpiw)
plt.title("Wage Inflation")
plt.show()

#nominal Rate
di = np.dot(J_i_pi, dpi) + np.dot(J_i_Y, dY) + np.dot(J_i_v, dZ[200:400])
plt.plot(di)
plt.title("Nominal Rate")
plt.show()

fig, axs = plt.subplots(2, 2)
axs[0, 0].plot(dr)
axs[0, 0].set_title("Interest Rate")
axs[1, 0].plot(dw)
axs[1, 0].set_title("Wage")
axs[1, 0].sharex(axs[0, 0])
axs[0, 1].plot(dpiw)
axs[0, 1].set_title("Wage Inflation")
axs[1, 1].plot(dpi)
axs[1, 1].set_title("Inflation")
fig.tight_layout()

fig, axs = plt.subplots(2, 2)
axs[0, 0].plot(dY)
axs[0, 0].set_title("Output")
axs[1, 0].plot(dC)
axs[1, 0].set_title("Consumption")
axs[1, 0].sharex(axs[0, 0])
axs[0, 1].plot(dG)
axs[0, 1].set_title("Government")
axs[1, 1].plot(dN)
axs[1, 1].set_title("Labor")
fig.tight_layout()

'''

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


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

from django.db import models, migrations
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('login', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='PatientInfo',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('dr_chrono_url', models.CharField(max_length=140)),
                ('gender', models.CharField(max_length=1)),
                ('date_of_birth', models.CharField(max_length=48)),
                ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL, unique=True)),
            ],
        ),
        migrations.RemoveField(
            model_name='userprofile',
            name='user',
        ),
        migrations.DeleteModel(
            name='UserProfile',
        ),
    ]