import numpy as np

def decorate(a: np.ndarray):
    """
    Takes a two dimensional numpy matrix and returns a string representation surrounded by brackets.

    example:
    >>> a = np.array([[1,2,3],[4,5,6],[7,8,9]])
    >>> a
    array([[1, 2, 3],
           [4, 5, 6],
           [7, 8, 9]])
    >>> decorate(a)
    '┌       ┐\n| 1 2 3 |\n| 4 5 6 |\n| 7 8 9 |\n└       ┘'
    >>> print(decorate(a))
    ┌       ┐
    | 1 2 3 |
    | 4 5 6 |
    | 7 8 9 |
    └       ┘
    """
    if a.ndim != 2:
        raise ValueError(
            "ndarray has ndim {} and shape {}. Only arrays with ndim = 2 are considered for decoration".format(a.ndim,
                                                                                a.shape))
    fmt = gen_format_string(a)
    ret = fmt.format(*a.flatten())
    return ret

def decorate_aug(a: np.ndarray, b: np.ndarray):
    """
    Takes A and b from an equation A*x=b and returns the augmented form as string.

    example:
    >>> a = np.array([[1,2,3],[4,5,6],[7,8,9]])
    >>> b = np.array([[1],[2],[3]])
    >>> decorate_aug(a,b)
    '┌           ┐\n| 1 2 3 | 1 |\n| 4 5 6 | 2 |\n| 7 8 9 | 3 |\n└           ┘'
    >>> print(decorate_aug(a,b))
    ┌           ┐
    | 1 2 3 | 1 |
    | 4 5 6 | 2 |
    | 7 8 9 | 3 |
    └           ┘
"""
    if a.ndim != 2:
        raise ValueError(
            "ndarray A has ndim {} and shape {}. Only arrays with ndim = 2 are considered for decoration".format(a.ndim,
                                                                                a.shape))
    if b.ndim != 2:
        raise ValueError(
            "ndarray b has ndim {} and shape {}. Only arrays with ndim = 2 are considered for decoration".format(b.ndim,
                                                                                b.shape))
    if a.shape[0] != b.shape[0]:
        raise ValueError("A and b must have same amount of columns")

    delim = np.array(["|" for x in b], dtype="str")
    delim = delim.reshape((-1, 1))
    ab = np.concatenate((a, delim, b), axis=1)
    fmt = gen_format_string(ab)
    ret = fmt.format(*ab.flatten())
    return ret

def gen_format_string(a: np.array):
    """
    Generates a matrix format in the shape of a.
    >>> a = np.array([[1,2,3],[4,5,6],[7,8,9]])
    print(gen_format_string(a))
    ┌       ┐
    |{:>2}{:>2}{:>2} |
    |{:>2}{:>2}{:>2} |
    |{:>2}{:>2}{:>2} |
    └       ┘

    The template can be rendered with the help of the unboxing operator, e.g.:
    >>> gen_format_string(a).format(*a.flatten())
    or
    >>> gen_format_string(a).format(*[x for x in np.nditer(a)])
    """
    str_arr = copy_as_str(a)
    max_lens = max_len_in_col(str_arr) + 1
    rows = a.shape[0]
    inner_juice = "".join(map(lambda x: "{{:>{}}}".format(x), max_lens))
    # bad readability :(, but apparently faster than invoking list constructor like with [map(lambda x: " ", max_lens)]
    spacers = *map(lambda x: " ", max_lens),
    header = "┌" + inner_juice.format(*spacers) + " ┐\n"
    body = ""
    for x in range(rows):
        body += "|" + inner_juice + " |\n"
    footer = "└" + inner_juice.format(*spacers) + " ┘"

    ret = header + body + footer
    return ret

# returns a Matrix with elementwise string casts. Numpy's cast or string reps create fractions of the elements :/
def copy_as_str(a: np.array):
    """
    Creates a deep copy of a with each element cast to string.
    """
    matrix_like = []
    for x in np.nditer(a):
        matrix_like.append(str(x))
    str_arr = np.array(matrix_like, dtype="str")
    str_arr = str_arr.reshape(a.shape)
    return str_arr

# returns col vector with the maximum string length in column of matrix
def max_len_in_col(str_arr: np.array):
    """
    ┌                ┐
    | '1' '2'   '3'  |
    | '4' '555' '60' |     =>    [1,3,2]
    | '7' '8'   '9'  |
    └                ┘
    """
    len_arr = np.char.str_len(str_arr)
    return np.max(len_arr, axis=0)


#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import print_function

import unittest
import numpy as np
import paddle.fluid as fluid
import six
import paddle.fluid as fluid
from paddle.fluid import Program, program_guard
from op_test import OpTest, skip_check_grad_ci

class TestPReluAPIError(unittest.TestCase):
    def test_errors(self):
        with fluid.program_guard(fluid.Program(), fluid.Program()):
            layer = fluid.PRelu(
                mode='all',
                param_attr=fluid.ParamAttr(
                    initializer=fluid.initializer.Constant(1.0)))
            # the input must be Variable.
            x0 = fluid.create_lod_tensor(
                np.array([-1, 3, 5, 5]), [[1, 1, 1, 1]], fluid.CPUPlace())
            self.assertRaises(TypeError, layer, x0)
            # the input dtype must be float32
            data_t = fluid.data(
                name="input", shape=[5, 200, 100, 100], dtype="float64")
            self.assertRaises(TypeError, layer, data_t)

class PReluTest(OpTest):
    def setUp(self):
        self.init_input_shape()
        self.init_attr()
        self.op_type = "prelu"

        x_np = np.random.uniform(-1, 1, self.x_shape)
        # Since zero point in prelu is not differentiable, avoid randomize
        # zero.
        x_np[np.abs(x_np) < 0.005] = 0.02

        if self.attrs == {'mode': "all"}:
            alpha_np = np.random.uniform(-1, -0.5, (1))
        elif self.attrs == {'mode': "channel"}:
            alpha_np = np.random.uniform(-1, -0.5, (1, x_np.shape[1], 1, 1))
        else:
            alpha_np = np.random.uniform(-1, -0.5, \
                (1, x_np.shape[1], x_np.shape[2], x_np.shape[3]))
        self.inputs = {'X': x_np, 'Alpha': alpha_np}

        out_np = np.maximum(self.inputs['X'], 0.)
        out_np = out_np + np.minimum(self.inputs['X'],
                                     0.) * self.inputs['Alpha']
        assert out_np is not self.inputs['X']
        self.outputs = {'Out': out_np}

    def init_input_shape(self):
        self.x_shape = (2, 100, 3, 4)

    def init_attr(self):
        self.attrs = {'mode': "channel"}

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
        self.check_grad(['X', 'Alpha'], 'Out')

# TODO(minqiyang): Resume these test cases after fixing Python3 CI job issues
if six.PY2:

    @skip_check_grad_ci(
        reason="[skip shape check] Input(Alpha) must be 1-D and only has one data in 'all' mode"
    )
    class TestModeAll(PReluTest):
        def init_input_shape(self):
            self.x_shape = (2, 3, 4, 5)

        def init_attr(self):
            self.attrs = {'mode': "all"}

    class TestModeElt(PReluTest):
        def init_input_shape(self):
            self.x_shape = (3, 2, 5, 10)

        def init_attr(self):
            self.attrs = {'mode': "element"}

class TestPReluOpError(unittest.TestCase):
    def test_errors(self):
        with program_guard(Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, fluid.layers.prelu, 1, 'all')
            # The input dtype must be float16, float32, float64.
            x_int32 = fluid.data(name='x_int32', shape=[12, 10], dtype='int32')
            self.assertRaises(TypeError, fluid.layers.prelu, x_int32, 'all')
            # support the input dtype is float32
            x_fp16 = fluid.layers.data(
                name='x_fp16', shape=[12, 10], dtype='float32')
            fluid.layers.prelu(x_fp16, 'all')

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


# -*- coding: utf-8 -*-
"""
Created on Mon Sep 14 19:28:11 2020

@author: Ray
@email: 1324789704@qq.com
@wechat: RayTing0305
"""

###chapter5

import pandas as pd
from pandas import Series, DataFrame
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(12345)
plt.rc('figure', figsize=(10, 6))
PREVIOUS_MAX_ROWS = pd.options.display.max_rows
pd.options.display.max_rows = 20
np.set_printoptions(precision=4, suppress=True)

### Series

obj = pd.Series([4, 7, -5, 3])
obj_array = obj.values
obj_range = obj.index

obj2 = pd.Series([4, 7, -5, 3], index=['d', 'b', 'a', 'c'])
obj2_array = obj2.values
obj2_range = obj2.index

obj3 = obj2[['a','c','d']]
obj3_array = obj3.values
obj3_range = obj3.index

obj4 = obj2[obj2>0]
obj5 = obj2*2
obj6 = np.exp(obj2)

#print('b' in obj2)
#print('e' in obj2)

sdata = {'Ohio': 35000, 'Texas': 71000, 'Oregon': 16000, 'Utah': 5000}
obj7 = pd.Series(sdata)

states = ['California', 'Ohio', 'Oregon', 'Texas']
obj8 = pd.Series(sdata, index=states)

#print(pd.isnull(obj8))
#print(pd.notnull(obj8))

obj9 = obj7 + obj8

obj8.name = 'population'
obj8.index.name = 'state'

####DataFrame

data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada', 'Nevada'],
        'year': [2000, 2001, 2002, 2001, 2002, 2003],
        'pop': [1.5, 1.7, 3.6, 2.4, 2.9, 3.2]}
frame = pd.DataFrame(data)
print(frame.state)
#print(frame.head())
#print(frame.columns)

frame = pd.DataFrame(data, columns=['year', 'state', 'pop'])

frame2 = pd.DataFrame(data, columns=['year', 'state', 'pop', 'debt'],
                      index=['one', 'two', 'three', 'four',
                             'five', 'six'])
fc1 = frame2['state']
fc2 = frame2.state
#print(fc1==fc2)
#print(id(fc1)==id(fc2))

fr1 = frame2.loc['two']
#print(fr1)

frame2['debt'] = np.arange(6.)
#print(frame2)

val = pd.Series([-1.2, -1.5, -1.7], index=['two', 'four', 'five'])
frame2['debt'] = val
#print(frame2)

frame2['eastern'] = frame2.state == 'Ohio'

del frame2['eastern']

pop = {'Nevada': {2001: 2.4, 2002: 2.9},
       'Ohio': {2000: 1.5, 2001: 1.7, 2002: 3.6}}
frame3 = pd.DataFrame(pop)

#print(frame3.T)

frame4 = pd.DataFrame(pop, index=[2001, 2002, 2003])

pdata = {'Ohio': frame3['Ohio'][:-1],
         'Nevada': frame3['Nevada'][:2]}
frame5 = pd.DataFrame(pdata)

frame3.index.name='year'
frame3.columns.name = 'state'
#print(frame3.values)

### Index Objects
obj = pd.Series(range(3), index=['a', 'b', 'c'])
index = obj.index

##index[1] = 'd' # TypeError

labels = pd.Index(np.arange(3))
dup_labels = pd.Index(['foo', 'foo', 'bar', 'bar'])
frame6 = pd.Series(np.arange(4), index = dup_labels)
#print(frame6['foo'])

### Essential Functionality

obj  = pd.Series([4.5, 7.2, -5.3, 3.6], index=['d', 'b', 'a', 'c'])
obj2 = obj.reindex(['a', 'b', 'c', 'd', 'e'])
obj3 = pd.Series(['blue', 'purple', 'yellow'], index=[0, 2, 4])
obj4 = obj3.reindex(range(6), method='ffill')

frame = pd.DataFrame(np.arange(9).reshape((3, 3)),
                     index=['a', 'c', 'd'],
                     columns=['Ohio', 'Texas', 'California'])
frame2 = frame.reindex(['a', 'b', 'c', 'd'])

states = ['Texas', 'Utah', 'California']
frame3 = frame.reindex(columns=states)

#fr = frame.loc[['a', 'c'], states]

## Dropping Entries from an Axis
obj = pd.Series(np.arange(5.), index=['a', 'b', 'c', 'd', 'e'])
new_obj = obj.drop(['c', 'd'])

obj = pd.Series(np.arange(4.), index=['a', 'b', 'c', 'd'])
obj2 = obj[['b', 'a', 'd']]
obj3 = obj[[1, 3]]
obj4 = obj[obj<2]
obj5 = obj['b':'e']
obj['b':'c'] = 5

data = pd.DataFrame(np.arange(16).reshape((4, 4)),
                    index=['Ohio', 'Colorado', 'Utah', 'New York'],
                    columns=['one', 'two', 'three', 'four'])
#print(data)
#print(data[:2])
#print(data[data['three']>5])
#data[data<5]=0
#print(data)

loc = data.loc['Colorado', ['two', 'three']]

loc2 = data.iloc[2, [3, 0, 1]]
#print(loc2)
loc3 = data.iloc[2]
loc4 = data.iloc[[1, 2], [3, 0, 1]]
#print(loc4)
loc5 = data.iloc[:, :3][data.three > 5]
#print(loc5)


import time
import datetime as dt
import pandas as pd
import numpy as np

CITY_DATA = { 'chicago': 'chicago.csv',
              'new york city': 'new_york_city.csv',
              'washington': 'washington.csv' }

def get_filters():
    """
    Asks user to specify a city, month, and day to analyze.

    Returns:
        (str) city - name of the city to analyze
        (str) month - name of the month to filter by, or "all" to apply no month filter
        (str) day - name of the day of week to filter by, or "all" to apply no day filter
    """
    print('Hello! Let\'s explore some US bikeshare data!')
    # TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
    while True:
            city = str(input('name of the city to analyse:')).lower()
            if city == 'chicago':
                city ='chicago.csv'
            elif city == 'new york city':
                city = 'new_york_city.csv'
            elif city == 'washington':
                city = 'washington.csv'
            else:
                print('I do not get that')
            break

    # TO DO: get user input for month (all, january, february, ... , june)
    while True:
            month = str(input('name of the month to filter by, or "all" to apply no month filter:')).lower()
            months = ['january', 'february', 'march', 'april', 'may', 'june']
            if month == 'january':
                month = months[0]
            elif month == 'february':
                month = months[1]
            elif month == 'march':
                month = months[2]
            elif month == 'april':
                month = months[3]
            elif month =='may':
                month = months[4]
            elif month == 'june':
                month = months[5]
            elif month == "all":
                print('all')
            else:
                print('I did not get that')
            break

    # TO DO: get user input for day of week (all, monday, tuesday, ... sunday)
    while True:
            day = str(input('name of the day of week to filter by, or "all" to apply no day filter:')).lower()
            days = ['monday', 'tuesday', 'wednesday','thursday', 'friday', 'saturday', 'sunday']

            if day == 'monday':
                day = days[0]
            elif day == 'tuesday':
                day = days[1]
            elif day == 'wednesday':
                day = days[2]
            elif day == 'thursday':
                day = days[3]
            elif day =='friday':
                day = days[4]
            elif day == 'saturday':
                day = days[5]
            elif day == 'sunday':
                day = days[6]
            elif day == 'all':
                print('all')
            else:
                print('I did not get that')
            break

    print('-'*40)
    return city, month, day

def load_data(city, month, day):
    """
    Loads data for the specified city and filters by month and day if applicable.

    Args:
        (str) city - name of the city to analyze
        (str) month - name of the month to filter by, or "all" to apply no month filter
        (str) day - name of the day of week to filter by, or "all" to apply no day filter
    Returns:
        df - Pandas DataFrame containing city data filtered by month and day
    """
     # load data file into a dataframe
    df = pd.read_csv(city)

    # convert the Start Time column to datetime
    df['Start Time'] = pd.to_datetime(df['Start Time'])

    # extract month and day of week from Start Time to create new columns
    df['month'] = df['Start Time'].dt.month
    df['day_of_week'] = df['Start Time'].dt.weekday_name

    # filter by month if applicable
    if month != 'all':
        # use the index of the months list to get the corresponding int
        months = ['january', 'february', 'march', 'april', 'may', 'june']
        month = months.index(month) + 1

        # filter by month to create the new dataframe
        df = df[df['month'] == month]

    # filter by day of week if applicable
    if day != 'all':
        # filter by day of week to create the new dataframe
        df = df[df['day_of_week'] == day.title()]

    return df

def time_stats(df):
    """Displays statistics on the most frequent times of travel."""

    print('\nCalculating The Most Frequent Times of Travel...\n')
    start_time = time.time()

    # TO DO: display the most common month
    month_mode = pd.Series(pd.DatetimeIndex(df['Start Time'])).dt.month.mode()
    print("Most Common Month :", month_mode, sep = " ")

    # TO DO: display the most common day of week

    weekday_mode = pd.Series(pd.DatetimeIndex(df['Start Time'])).dt.weekday_name.mode()
    print("Most Common Day of the Week :",weekday_mode, sep = " ")

    # TO DO: display the most common start hour

    hour_mode = pd.Series(pd.DatetimeIndex(df['Start Time'])).dt.hour.mode()
    print ("Most Common Start Hour :",hour_mode, sep = " ")

    print("\nThis took %s seconds." % (time.time() - start_time))
    print('-'*40)

def station_stats(df):
    """Displays statistics on the most popular stations and trip."""

    print('\nCalculating The Most Popular Stations and Trip...\n')
    start_time = time.time()

    # TO DO: display most commonly used start station
    ss = df['Start Station']
    start_station = ss.mode()
    print ("Most Common Used Start Station :",start_station,sep = " ")

    # TO DO: display most commonly used end station
    es = df['Start Station'].mode()
    print("Most Common Used End Station:",es, sep = " ")

    # TO DO: display most frequent combination of start station and end station trip
    df["frequent stations"] = df["Start Station"].map(str) + " to " + df["End Station"]
    fs_mode = df["frequent stations"].mode()
    print ("Most Frequent Combination of Start and End Station:", fs_mode, sep = " ")

    print("\nThis took %s seconds." % (time.time() - start_time))
    print('-'*40)

def trip_duration_stats(df):
    """Displays statistics on the total and average trip duration."""

    print('\nCalculating Trip Duration...\n')
    start_time = time.time()

    # TO DO: display total travel time
    ttt = df['Trip Duration'].sum()
    print("Total Travel Time:",ttt, sep = " ")

    # TO DO: display mean travel time
    td_mean = df['Trip Duration'].mean()
    print ("Mean Travel :",td_mean, sep= " ")

    print("\nThis took %s seconds." % (time.time() - start_time))
    print('-'*40)

def user_stats(df):
    """Displays statistics on bikeshare users."""

    print('\nCalculating User Stats...\n')
    start_time = time.time()

    # TO DO: Display counts of user types
    Subscribers = len(df[df["User Type"] == "Subscriber"])
    Customers = len(df[df["User Type"] == "Customer"])
    print ('subscribers:' , Subscribers, sep = " ")
    print ('customers:', Customers, sep = " ")

    # TO DO: Display counts of gender
    try:
        Males = len(df[df["Gender"] == "Male"])
        Females = len(df[df["Gender"] == "Female"])
    except:
        print('There is no Gender data')
    else:
        print('Males :', Males, sep = " ")
        print('Females :', Females, sep = " ")

    # TO DO: Display earliest, most recent, and most common year of birth
    try:
        earliest = df['Birth Year'].min()
        most_recent = df['Birth Year'].max()
        most_common = df['Birth Year'].mode()
    except:
        print('There is no Birth Year data')
    else:
        print ('Earliest :', earliest, sep = " ")
        print ('Most recent :', most_recent, sep = " ")
        print ('Most common :', most_common, sep = " ")

        print("\nThis took %s seconds." % (time.time() - start_time))
        print('-'*40)
#----------------------Descriptive Statistics-----------------------
def descriptive_stats(df):

    while True:
        show_me_more = str(input('Do you need to see more data ? yes or no')).lower()
        if show_me_more == 'yes':
            print(df.describe())
        else:
            print('Done')
        break

#-------------------------------------------------------------------
def main():
    while True:
        city, month, day = get_filters()
        df = load_data(city, month, day)

        time_stats(df)
        station_stats(df)
        trip_duration_stats(df)
        user_stats(df)
        descriptive_stats(df) #checking
        restart = input('\nWould you like to restart? Enter yes or no.\n')
        if restart.lower() != 'yes':
            break

if __name__ == "__main__":
	main()


"""

    lantz.drivers.rigol.dg1022
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    Implementation of Rigol DG1022 function generator with 2 channels. More or
    less based around on the Ag33522a driver from Berk Diler.

    Manual available from: https://www.rigolna.com/products/waveform-generators/dg1000/

    Author: Peter Mintun

    Date: 12/11/2017

"""

import numpy as np
import lantz
from lantz import Action, Feat, DictFeat, ureg
from collections import OrderedDict
from lantz.messagebased import MessageBasedDriver

class DG1022(MessageBasedDriver):

    DEFAULTS = {
        'COMMON': {
            'write_termination': '\n',
            'read_termination': '\n',
        }
    }

    CHANNELS = OrderedDict([(1, 1),
                           (2,2)])

    TOGGLE = OrderedDict([('on', 'ON'),
                          ('off', 'OFF')])

    WAVEFORMS = OrderedDict([('arbitrary', 'ARB'),
                             ('dc', 'DC'),
                             ('harmonic', 'HARM'),
                             ('noise', 'NOIS'),
                             ('pulse', 'PULS'),
                             ('ramp', 'RAMP'),
                             ('sine', 'SIN'),
                             ('square', 'SQU'),
                             ('triangle', 'TRI'),
                             ('user', 'USER')])

    @Feat(read_once=True)
    def idn(self):
        return self.query('*IDN?')

    @Action()
    def reset(self):
        return self.write('*RST')

    @Feat()
    def error(self):
        msg = self.query("SYST:ERR?")
        return msg.split(',') #error code, error message

    @DictFeat(keys = CHANNELS, units="Hz", limits=(1e-6, 25e6))
    def frequency(self,channel):
        """
        Returns the frequency of the specified channel, in Hertz.
        """
        return float(self.query('SOUR{}:FREQ?'.format(channel)))

    @frequency.setter
    def frequency(self,channel,value):
        """
        Sets the frequency of the specified channel, to value. Note that this
        is not smart enough to keep track of the different bandwidth constraints
        on different types of waveforms, so see the manual accordingly.
        """
        return self.write('SOUR{}:FREQ {:1.6f}'.format(channel,value))

    @DictFeat(keys=CHANNELS, values=WAVEFORMS)
    def function(self,channel):
        """
        Returns the function of the specified channel from the options
        enumerated in WAVEFORMS.
        """
        result = self.query('SOUR{}:APPL?'.format(channel))[1:-1]
        return result.split(',')[0]

    @function.setter
    def function(self,channel,value):
        """
        Returns the function of the specified channel to value (specified in
        WAVEFORMS).
        """
        return self.write('SOUR{}:APPL:{}'.format(channel, value))

    @DictFeat(keys = CHANNELS, values = TOGGLE)
    def output(self,channel):
        """
        Reads the output state of the specified channel.
        """
        return self.query('OUTP{}?'.format(channel))

    @output.setter
    def output(self,channel,val):
        """
        Sets the output state of the specified channel to val.
        """
        return self.write('OUTP{} {}'.format(channel,val))

    @DictFeat(keys=CHANNELS, units="V", limits=(-10.,10.))
    def voltage_low(self,channel):
        """
        Queries the low voltage level for the specified channel.
        """
        return float(self.query("SOUR{}:VOLT:LOW?".format(channel)))

    @voltage_low.setter
    def voltage_low(self,channel,value):
        """
        Sets the high voltage level for the specified channel.
        """
        return self.write("SOUR{}:VOLT:LOW {:1.6f}".format(channel, value))

    @DictFeat(keys=CHANNELS, units="V", limits=(-10.,10.))
    def voltage_high(self,channel):
        """
        Queries the high voltage level for the specified channel.
        """
        return float(self.query("SOUR{}:VOLT:HIGH?".format(channel)))

    @voltage_high.setter
    def voltage_high(self,channel,value):
        """
        Sets the high voltage level for the specified channel.
        """
        return self.write("SOUR{}:VOLT:HIGH {:1.6f}".format(channel, value))

    @DictFeat(keys = CHANNELS, units = "V", limits=(0., 20.))
    def voltage_amplitude(self,channel):
        """
        Queries the peak-to-peak voltage amplitude of the specified output
        channel.
        """
        return float(self.query("SOUR{}:VOLT?".format(channel)))

    @voltage_amplitude.setter
    def voltage_amplitude(self,channel,value):
        """
        Sets the peak-to-peak voltage amplitude of the specified output channel.
        """
        return self.write("SOUR{}:VOLT {:1.6f}".format(channel,value))

    @DictFeat(keys=CHANNELS, units="V", limits=(-10., 10.))
    def voltage_offset(self, channel):
        """
        Queries the offset voltage of the specified output channel.
        """
        return float(self.query("SOUR{}:VOLT:OFFS?".format(channel)))

    @voltage_offset.setter
    def voltage_offset(self, channel, value):
        """
        Sets the offset voltage of the specified output channel.
        """
        self.write("SOUR{}:VOLT:OFFS {:1.6f}".format(channel, value))

if __name__ == '__main__':

    # note: if you don't see your device, it may not work over USB 3.0?
    addr = 'USB0::0x1AB1::0x0642::DG1ZA192902819::INSTR'

    try:
        inst = DG1022(addr)
        inst.initialize()

        inst.reset()

        print('Identification:{}'.format(inst.idn))
        print('Error:{}'.format(inst.error))

    except:

        print('Could not find instrument, check connection/address!')

    # code to check various parameters from supported channels
    for channel in inst.CHANNELS.keys():

        inst.frequency[channel] = 1e-6
        print('Channel {} frequency: {}'.format(channel, inst.frequency[channel]))
        inst.frequency[channel] = 20e6
        print('Channel {} frequency: {}'.format(channel, inst.frequency[channel]))

        print('Channel {} function: {}'.format(channel, inst.function[channel]))
        inst.function[channel] = 'square'
        print('Channel {} function: {}'.format(channel, inst.function[channel]))

        inst.output[channel] = 'off'
        print('Channel {} output:{}'.format(channel, inst.output[channel]))
        inst.output[channel] = 'on'
        print('Channel {} output:{}'.format(channel, inst.output[channel]))
        inst.output[channel] = 'off'
        print('Channel {} output:{}'.format(channel, inst.output[channel]))

        print('Channel {} low voltage:{}'.format(channel, inst.voltage_low[channel]))
        inst.voltage_low[channel] = -1.0
        print('Channel {} low voltage:{}'.format(channel, inst.voltage_low[channel]))

        print('Channel {} high voltage:{}'.format(channel, inst.voltage_high[channel]))
        inst.voltage_high[channel] = 1.0
        print('Channel {} high voltage:{}'.format(channel, inst.voltage_high[channel]))

        print('Channel {} voltage amplitude:{}'.format(channel, inst.voltage_amplitude[channel]))
        print('Channel {} voltage offset:{}'.format(channel, inst.voltage_offset[channel]))

        inst.voltage_amplitude[channel] = 5.0
        inst.voltage_offset[channel] = 0.0

        print('Channel {} voltage amplitude:{}'.format(channel, inst.voltage_amplitude[channel]))
        print('Channel {} voltage offset:{}'.format(channel, inst.voltage_offset[channel]))
        print('Channel {} low voltage:{}'.format(channel, inst.voltage_low[channel]))
        print('Channel {} high voltage:{}'.format(channel, inst.voltage_high[channel]))


#!/usr/bin/env python
# Andre Anjos <andre.anjos@idiap.ch>
# Thu 23 Jun 20:22:28 2011 CEST
# vim: set fileencoding=utf-8 :

"""
The Iris flower data set or Fisher's Iris data set is a multivariate data
set introduced by Sir Ronald Aylmer Fisher (1936) as an example of
discriminant analysis. It is sometimes called Anderson's Iris data set
because Edgar Anderson collected the data to quantify the geographic
variation of Iris flowers in the Gaspe Peninsula.

For more information: http://en.wikipedia.org/wiki/Iris_flower_data_set

References:

  1. Fisher,R.A. "The use of multiple measurements in taxonomic problems",
  Annual Eugenics, 7, Part II, 179-188 (1936); also in "Contributions to
  Mathematical Statistics" (John Wiley, NY, 1950).

  2. Duda,R.O., & Hart,P.E. (1973) Pattern Classification and Scene Analysis.
  (Q327.D83) John Wiley & Sons. ISBN 0-471-22361-1. See page 218.

  3. Dasarathy, B.V. (1980) "Nosing Around the Neighborhood: A New System
  Structure and Classification Rule for Recognition in Partially Exposed
  Environments". IEEE Transactions on Pattern Analysis and Machine
  Intelligence, Vol. PAMI-2, No. 1, 67-71.

  4. Gates, G.W. (1972) "The Reduced Nearest Neighbor Rule". IEEE
  Transactions on Information Theory, May 1972, 431-433.
"""

import os
import sys
import numpy
from . import driver #driver interface

import pkg_resources

__version__ = pkg_resources.require(__name__)[0].version

names = ['Sepal Length', 'Sepal Width', 'Petal Length', 'Petal Width']
"""Names of the features for each entry in the dataset."""

stats = {
    'Sepal Length': [4.3, 7.9, 5.84, 0.83, 0.7826],
    'Sepal Width': [2.0, 4.4, 3.05, 0.43, -0.4194],
    'Petal Length': [1.0, 6.9, 3.76, 1.76, 0.9490], #high correlation
    'Petal Width': [0.1, 2.5, 1.20, 0.76, 0.9565], #high correlation
    }
"""These are basic statistics for each of the features in the whole dataset."""

stat_names = ['Minimum', 'Maximum', 'Mean', 'Std.Dev.', 'Correlation']
"""These are the statistics available in each column of the stats variable."""

def data():
  """Loads from (text) file and returns Fisher's Iris Dataset.

  This set is small and simple enough to require an SQL backend. We keep the
  single file it has in text and load it on-the-fly every time this method is
  called.

  We return a dictionary containing the 3 classes of Iris plants catalogued in
  this dataset. Each dictionary entry contains an 2D :py:class:`numpy.ndarray`
  of 64-bit floats and 50 entries. Each entry is an Array with 4 features as
  described by "names".
  """
  from .driver import Interface
  import csv
  import pkg_resources

  data = pkg_resources.resource_filename(__name__, 'iris.data')

  retval = {}

  # The CSV file reader API changed between Python2 and Python3
  open_dict = dict(mode='rb') #python2.x
  if sys.version_info[0] >= 3: #python3.x
    open_dict = dict(mode='rt', encoding='ascii', newline='')

  with open(data, **open_dict) as csvfile:
    for row in csv.reader(csvfile):
      name = row[4][5:].lower()
      retval.setdefault(name, []).append([float(k) for k in row[:4]])

  # Convert to a float64 2D numpy.ndarray
  for key, value in retval.items():
    retval[key] = numpy.array(value, dtype='float64')

  return retval

def __dump__(args):
  """Dumps the database to stdout.

  Keyword arguments:

  args
    A argparse.Arguments object with options set. We use two of the options:
    ``cls`` for the class to be dumped (if None, then dump all data) and
    ``selftest``, which runs the internal test.
  """

  d = data()
  if args.cls: d = {args.cls: d[args.cls]}

  output = sys.stdout
  if args.selftest:
    from bob.db.base.utils import null
    output = null()

  for k, v in d.items():
    for array in v:
      s = ','.join(['%.1f' % array[i] for i in range(array.shape[0])] + [k])
      output.write('%s\n' % (s,))

  return 0

def get_config():
  """Returns a string containing the configuration information.
  """
  import bob.extension
  return bob.extension.get_config(__name__)

__all__ = ['names', 'stats', 'stat_names', 'data', 'get_config']


# ---
# jupyter:
#   jupytext:
#     cell_metadata_filter: all
#     notebook_metadata_filter: all,-language_info,-toc,-latex_envs
#     text_representation:
#       extension: .py
#       format_name: percent
#       format_version: '1.3'
#       jupytext_version: 1.6.1-dev
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# %%
import copy
import datetime
import pprint
from pathlib import Path

import cartopy
import cartopy.crs
import geopandas as gpd
import matplotlib.pyplot as plt
import numpy as np
import pytz
import rasterio
from IPython.display import display
from matplotlib import pyplot as plt
from matplotlib.colors import Normalize
from pyproj import CRS, Transformer

# %%
import a301_lib

pacific = pytz.timezone("US/Pacific")
date = datetime.datetime.today().astimezone(pacific)
print(f"written on {date}")

# %% [markdown]
# (assign6b_sol)=
# # Solution: adding an image with features to a cartopy map
#
# Here's a demo of adding features to an image.  The notebook does some extra work to
# illustrate how to make a map that is bigger than the image, and how to reproject from
# one raster crs to another using rasterio.
#
# 1) read in the `vancouver_345_refl.tiff` band 5 image
# 2) find the image corners in utm10 and geodetic lat/lon (for the features)
# 3) put the image on a map that extends 5 km beyond the image
# 4) add the features to the big map
# 5) create a new crs that is laea centered on lat=50 deg N, lon= -120 deg E
# 6) use rasterio.reproject to reproject the utm10 image onto the laea crs
# 7) draw a 50 row by 100 column box on the image

# %% [markdown]
# ## Read in the geotiff
#
# First read in band 5 from the `vancouver_345_refl.tiff` image that was produced by
# {ref}`rasterio_3bands`:

# %%
notebook_dir = a301_lib.data_share.resolve()
print(notebook_dir)
week10_scene = notebook_dir / "vancouver_345_refl.tiff"

# %%
with rasterio.open(week10_scene) as van_raster:
    b5_refl = van_raster.read(3)
    chan3_tags = van_raster.tags(3)
    crs_10 = van_raster.profile["crs"]
    profile=van_raster.profile
    affine_transform = profile["transform"]
    tags = van_raster.tags()
    print(f"\n\n{tags=}, \n\n{chan3_tags=},\n\n {profile=},\n\n {affine_transform=}\n")

# %% [markdown]
# ## Set up the lat/lon UTM10N transform
#
# I'll want to transform back and forth between UTM and lat/lon (since I think in lat/lon), so create
# a transformer object for this.  Copy code from {ref}`image_zoom`

# %%
from pyproj import CRS, Transformer

p_utm10 = crs_10
p_latlon = CRS.from_epsg(4326)
crs_transform = Transformer.from_crs(p_latlon, p_utm10)
print(p_latlon.to_wkt())

# %% [markdown]
# ## Find the corners of the image
#
# I need the upper left and lower right corners to set the image extent for imshow.  This is
# what the affine transform provides.  I'll use my crs_transform to also get the image_extent
# in lon/lat coords to make sure I'm in the right place

# %%
ul_x_utm10, ul_y_utm10 = affine_transform*(0,0)
lr_x_utm10, lr_y_utm10 = affine_transform*(profile['width'],profile['height'])
print(f"{(ul_x_utm10,ul_y_utm10,lr_x_utm10,lr_y_utm10)=}")
image_extent_utm10 = (ul_x_utm10,lr_x_utm10, lr_y_utm10, ul_y_utm10)

# %%
ul_lon,ul_lat = crs_transform.transform(ul_x_utm10,ul_y_utm10,direction='INVERSE')
lr_lon,lr_lat = crs_transform.transform(lr_x_utm10,lr_y_utm10,direction='INVERSE')
print(f"{(ul_lon,ul_lat,lr_lon,lr_lat)=}")

# %% [markdown]
# ## Make the map extent bigger than the image
#
# In order show more context, I'll enlarge the map extent by 5 km on each size

# %%
map_ul_x = ul_x_utm10 - 5.e3
map_lr_x = lr_x_utm10 + 5.e3
map_ul_y = ul_y_utm10 + 5.e3
map_lr_y = lr_y_utm10 - 5.e3
map_extent_utm10 = (map_ul_x,map_lr_x,map_lr_y,map_ul_y)
print(f"{map_extent_utm10=}")

# %% [markdown]
# * Repeat the imshow code from {ref}`rasterio_3bands`:

# %%
cartopy_utm10 = cartopy.crs.epsg(crs_10.to_epsg())
fig, ax = plt.subplots(
        1, 1, figsize=(15,15), subplot_kw={"projection": cartopy_utm10}
    )

vmin = 0.0
vmax = 0.4
the_norm = Normalize(vmin=vmin, vmax=vmax, clip=False)
palette = "viridis"
pal = copy.copy(plt.get_cmap(palette))
pal.set_bad("0.75")  # 75% grey for out-of-map cells
pal.set_over("w")  # color cells > vmax red
pal.set_under("k")  # color cells < vmin black
col=ax.imshow(b5_refl, cmap=pal, norm=the_norm, origin="upper",
          extent=image_extent_utm10,transform=cartopy_utm10);
cbar_ax = fig.add_axes([0.85, 0.2, 0.05, 0.6])
cbar = ax.figure.colorbar(col, extend="both", cax=cbar_ax, orientation="vertical")
cbar.set_label("band 5 reflectance")

# %% [markdown]
# ## Now set the map extent
#
# From the {ref}`demo_cartopy_extent` notebook we can repeat the ax.set_extent call to make the map
# larger than the image

# %%
ax.set_extent(map_extent_utm10,crs=cartopy_utm10)
display(fig)

# %% [markdown]
# ## Add features
#
# Use the {ref}`subset_map` code to put features on this axis.  I need the cartopy_latlon
# crs to do this (since p_latlon, the pyproj crs, doesn't work with cartopy)

# %%
gpd_dict = {}
read_files=True
if read_files:
    all_cia = a301_lib.data_share / "openstreetmap/WDBII_shp/f"
    all_cia = list(all_cia.glob("*"))
    for item in all_cia:
        gpd_dict[item.name] = gpd.read_file(item)
        print(f"read {item.name}")

    all_gshhs = a301_lib.data_share / "openstreetmap/GSHHS_shp/f"
    all_gshhs = list(all_gshhs.glob("*"))

    for item in all_gshhs:
        gpd_dict[item.name] = gpd.read_file(item)
        print(f"read {item.name}")
else:
    shape_files = list(small_shapes.glob("*"))
    for item in shape_files:
        key = item.stem
        gpd_dict[key] = gpd.read_file(item)
        print((f"reading saved shapefile {item} with\n"
               f"{len(gpd_dict[key])} rows"))

# %%
def find_features(extent, df):
    """
    given an extent and a dataframe, return a new dataframe
    containing only features that fall within the extent

    Parameters
    ----------

    extent:  list -- geographic extent in lon (deg E)/lat (deg N)
    df:  the geopandas dataframe to slice
    """
    xleft, xright, ybot, ytop = extent
    hit_rows = df.cx[xleft:xright, ybot:ytop]
    return hit_rows

extent = [-124, -122, 48, 50]
if read_files:
    subset_dict = {}
    for key, df in gpd_dict.items():
        df_subset = find_features(extent, df)
        if len(df_subset) > 0:
            subset_dict[key] = df_subset
            print(f"clipping {key}")
else:
    subset_dict=gpd_dict

# %% [markdown]
# * now put the features on -- they are defined in geodetic (lat/lon) crs

# %%
cartopy_latlon = cartopy.crs.PlateCarree()
for key, df in subset_dict.items():
    print(f"adding {key} with {len(df)} features")
    if key.find("river") > -1:
        ax.add_geometries(
            df["geometry"], cartopy_latlon, facecolor="none", edgecolor="green",lw=3,
        )
    else:
        ax.add_geometries(
            df["geometry"], cartopy_latlon, facecolor="none", edgecolor="blue",lw=3,
        )
display(fig)

# %% [markdown]
# ## Putting images from different utm zones on a map
#
# (not part of the assignment)
#
# Suppose you're working on a project that spans BC and Alberta, and you need
# to put images on a map that are either UTM zone 10 (-126 to -120 deg E) or
# UTM zone 11 (-120 to - 114 deg E).  To show both images on the same map, you
# need to reproject them onto a common crs. As a compromise, let's use a laea
# projection centered on `lon_0`= -120 deg E, `lat_0`=50 deg N
#
# Here are the rasterio reprojection module docs: [rasterio](https://rasterio.readthedocs.io/en/latest/topics/reproject.html)
#
# ### Step 1 is to create [the new pyproj crs](https://pyproj4.github.io/pyproj/dev/api/crs/crs.html).
#
# I'll just borrow the pyproj parameters from our earlier notebooks.

# %%
lat_0=50
lon_0 = -120
laea_proj = {'datum': 'WGS84', 'lat_0': '50', 'lon_0': '-120', 'no_defs': 'None',
             'proj': 'laea', 'type': 'crs', 'units': 'm', 'x_0': '0', 'y_0': '0'}
p_laea = CRS(laea_proj)
p_laea.to_wkt()

# %% [markdown]
# ### Step 2 is to reproject the extent in the new coordinate system
#
# Remember that extent order is:  [xleft, xright, ybot, ytop].  We need to get these values in the new laea crs.
#
# Here are the two extents for the image"

# %%
crs_transform = Transformer.from_crs(p_utm10, p_laea)
extent_utm10 = [ul_x_utm10,lr_x_utm10,lr_y_utm10,ul_y_utm10]
ul_x_laea,ul_y_laea = crs_transform.transform(ul_x_utm10,ul_y_utm10)
lr_x_laea,lr_y_laea = crs_transform.transform(lr_x_utm10,lr_y_utm10)
extent_laea=[ul_x_laea,lr_x_laea,lr_y_laea,ul_y_laea]
print(f"{extent_utm10=}")
print(f"{extent_laea=}")

# %% [markdown]
# ### step 3: create the affine transform
#
# We need the pixel size, then we can use the Affine constructor as we did in {ref}`image_zoom`
# (don't forget to make the pixel height negative). Notice that the pixel size has
# changed slightly in the laea crs.  Also notice that the correct denominator is (#pixels - 1), not #pixels.  That's
# because the extents go from the left side of the first pixel to the right side of the last pixel.  Dividing
# by #pixels would put the right boundary 1 pixel less than it needs to be.

# %%
pixel_x_size = (lr_x_laea - ul_x_laea)/(profile['width'] -1)
pixel_y_size = (ul_y_laea - lr_y_laea)/(profile['height'] - 1)
print(f"{pixel_x_size=},{pixel_y_size=}")

# %%
from affine import Affine

laea_affine = Affine(pixel_x_size,0,ul_x_laea,0,-pixel_y_size,ul_y_laea)

# %% [markdown]
# ### step 4: do the reprojection from p_utm10 to p_laea
#
# First make a numpy array to hold the reprojected image.  We're keeping the row and column numbers the same as i the original tiff.

# %%
width=profile['width']
height=profile['height']
b5_refl_laea = np.ones([height,width],dtype=np.float32)

# %% [markdown]
# ### Now reproject from utm10 to laea

# %%
from rasterio.warp import Resampling, reproject

reproject(
        b5_refl,
        b5_refl_laea,
        src_transform=affine_transform,
        src_crs=p_utm10,
        dst_transform=laea_affine,
        dst_crs=p_laea,
        resampling=Resampling.nearest);
plt.imshow(b5_refl_laea);

# %% [markdown]
# ### step 5: Make a cartopy map
#
# As of cartopy 0.18 we also need to create a cartopy version of the laea crs,
# since it doesn't accept the pyproj version.   See [cartopy projections](https://scitools.org.uk/cartopy/docs/latest/crs/projections.html#cartopy-projections).  One difference is
# that cartopy requires that the datum be specified separately from the projection, using a `globe` object.
# You can track progress on making cartopy more compatible with pyproj [here](https://github.com/SciTools/cartopy/pull/1023#discussion_r168395702) [and here](https://github.com/SciTools/cartopy/issues/1477)

# %%
dir(cartopy.crs.CRS)
globe = cartopy.crs.Globe(datum='WGS84',ellipse='WGS84')
laea_cartopy_crs = cartopy.crs.LambertAzimuthalEqualArea(central_longitude=lon_0,
                                                    central_latitude=lat_0,
                                                    globe=globe)
print(f"proj4 string: {laea_cartopy_crs.proj4_init=}")

# %% [markdown]
# **now plot it with features**
#
# Note the boundaries are slightly skewed at the top and bottom of the reprojection. In the laea projection all locations are referenced to the point at (`lon_`,`lat_0`), while for the UTM projection all locations are referenced to the longitude line going through the middle of the zone. The UTM preserves angles and shapes over small regions (i.e. it's conformal), but the scale changes with location.  The laea preserves scale, but distorts angles and shapes.  See [wikpedia lambert](https://en.wikipedia.org/wiki/Lambert_azimuthal_equal-area_projection) and [wikipedia conformal](https://en.wikipedia.org/wiki/Conformal_map_projection)

# %%
fig, ax = plt.subplots(
        1, 1, figsize=(10,15), subplot_kw={"projection": laea_cartopy_crs}
    )

vmin = 0.0
vmax = 0.4
the_norm = Normalize(vmin=vmin, vmax=vmax, clip=False)
palette = "viridis"
pal = copy.copy(plt.get_cmap(palette))
pal.set_bad("0.75")  # 75% grey for out-of-map cells
pal.set_over("w")  # color cells > vmax red
pal.set_under("k")  # color cells < vmin black
col=ax.imshow(b5_refl_laea, cmap=pal, norm=the_norm, origin="upper",
          extent=extent_laea,transform=laea_cartopy_crs)
cbar_ax = fig.add_axes([0.90, 0.2, 0.05, 0.6])
cbar = ax.figure.colorbar(col, extend="both", cax=cbar_ax, orientation="vertical")
cbar.set_label("band 5 reflectance")

# %% [markdown]
# ### Add a coastline/rivers

# %%
for key, df in subset_dict.items():
    print(f"adding {key} with {len(df)} features")
    if key.find("river") > -1:
        ax.add_geometries(
            df["geometry"], cartopy_latlon, facecolor="none", edgecolor="red",lw=5,
        )
    else:
        ax.add_geometries(
            df["geometry"], cartopy_latlon, facecolor="none", edgecolor="blue",lw=3,
        )
display(fig)

# %% [markdown]
# ## draw a red box in the middle of the scene
#
# We want a box that's 50 rows by 100 columns. I'll center it at row 300, column 200, and move up 25 rows and
# down 50 rows to find the corners.

# %%
ul_x, ul_y = laea_affine*(150,275)
lr_x, lr_y = laea_affine*(250,325)
delta_x = lr_x - ul_x
delta_y = ul_y - lr_y
print(f"{(ul_x,ul_y,lr_x,lr_y)=}")
#
# circle clockwise from upper left corner
#
box_x = [ul_x, ul_x + delta_x, ul_x + delta_x, ul_x,          ul_x]
box_y = [ul_y, ul_y          , ul_y - delta_y, ul_y - delta_y,ul_y]
ax.plot(box_x,box_y,'r-',lw=4)
display(fig)

# %% [markdown]
# ## More mapping tools for meteorology
#
# Check out [metpy](https://unidata.github.io/MetPy/latest/examples/index.html#plotting) for meteorologically oriented maps.


#!/usr/bin/python

'''
NUI Galway CT5132/CT5148 Programming and Tools for AI (James McDermott)

Solution for Assignment 3:  Hand-coding solutions for the Abstraction
                            and Reasoning Corpus

By writing my name below and submitting this file, I/we declare that
all additions to the provided skeleton file are my/our own work, and
that I/we have not seen any work on this assignment by another
student/group.

Student name(s):    John Doyle
Student ID(s):      21230978
GitHub:             https://github.com/john9d/ARC

Summary of the ARC Assignment:

The solve_* solutions completed below were completed using basic python functions
and no machine learning techniques, with the majority using only the built in Python
functions. Such as for loops, if else statements and enumerate. The math library was
used for an irrational number and the numpy library for mainly array specific functions.

Most of the solve_* solution started with a loop pass through the array and getting the
index of specific number required to solve the task. Then mainly replacing this with the
correct number, some requiring to reshape. Where possible the solve_* solutions tried to
use techniques that would help solve the solution in different size array that the tasks
shown.

Below the term "colour" is used primarily, as the ARC testing_interface.html was used
to identify/describe the task and its solution.

'''

import os, sys
import json
import numpy as np
import re
import math

### YOUR CODE HERE: write at least three functions which solve
### specific tasks by transforming the input x and returning the
### result. Name them according to the task ID as in the three
### examples below. Delete the three examples. The tasks you choose
### must be in the data/training directory, not data/evaluation.

def solve_22eb0ac0(x):
    '''
    ########################### SOLUTION No.1 ###############################
    #Using the ARC testing interface Task 22eb0ac0 shows a 10x10 array where there
    #are a number of colours vertically aligned and opposing each other on the
    #left and right side of the array. The task solutions show an array where the
    #a row in the array is filled in wth a colour that had a match of colour on the
    #left and right hand side. Any colours that do not match, will leave the row
    #black in between.

    #To solve this task we will need iterate through the array to adn create an if
    #statement to see if the start of the row and the end of the row match. If this
    #is true, we will enumerate the row, identify and replace all of the colours in
    #between with the match left and right colour.
    '''
    # Initiate loop through the array
    for i in x:

        # We will now check for the matching numbers
        if i[0] == i[-1]:

            # We will need to store the number so we can replace the non-matching ones
            value = i[0]

            # We will store the non-matching number
            item = i[1]

            # Enumerate through the row and create an index of the non-matching values
            index = [j for j, y in enumerate(i) if y == item]

            # We will now loop through the index list so we can replace this values
            for a in index:

                # This will now replace the non-matching values
                i[a] = value

    return x

def solve_0d3d703e(x):
    '''
    ########################### SOLUTION No.2 ###############################
    #Using the ARC testing interface Task 0d3d703e shows a 3x3 array of 3 colours,
    #all vertically aligned. Each colour is converted in the solution i.e. green to
    #yellow, blue to grey, etc. and the conversion is mirrored i.e. yellow to green,
    #grey to blue, etc. The test task has an array of light blue, blue and green all
    #of which need to be converted to wine, grey and yellow respectively.

    #To solve this task we will need to convert each colour (number), however there
    #are overlaps in colours. If we attempt to simply convert each number to its
    #solved state, the number will be reconverted back i.e. when updating 1 to 5, next
    #in the array we are required to update 5 to 1. This will return the old number.
    #To avoid this, we are going to divide by an irrational number (pi in this case)
    #so we can avoid double conversion. Post this, we will multiple the array by pi and
    #perform floor division to remove a chance of a floating point error.
    '''

    # We are going search the array and covert 1 to 5 and divide by pi
    x = np.where(x == 1, 5/math.pi, x)

    # We are going search the array and covert 2 to 6 and divide by pi
    x = np.where(x == 2, 6/math.pi, x)

    # We are going search the array and covert 3 to 4 and divide by pi
    x = np.where(x == 3, 4/math.pi, x)

    # We are going search the array and covert 4 to 3 and divide by pi
    x = np.where(x == 4, 3/math.pi, x)

    # We are going search the array and covert 6 to 2 and divide by pi
    x = np.where(x == 6, 2/math.pi, x)

    # We are going search the array and covert 8 to 9 and divide by pi
    x = np.where(x == 8, 9/math.pi, x)

    # We are going search the array and covert 5 to 1 and divide by pi
    x = np.where(x == 5, 1/math.pi, x)

    # We are going search the array and covert 9 to 8 and divide by pi
    x = np.where(x == 9, 8/math.pi, x)

    # We are going now multiply the array by pi and perform a floor division
    # This will return remove the floating point error
    x = (x*math.pi)//1

    return x

def solve_ce4f8723(x):
    '''
    ########################### SOLUTION No.3 ###############################
    #Using the ARC testing interface Task ce4f8723 shows a 9x4 array. Where there
    #are two 4x4 arrays with coloured and black squares, separated by a 1x4 array
    #to divide the two 4x4 arrays. The results of each task demonstrate that when
    #overlay the two 4x4 arrays, the resulting array shows only black squares in
    #the resulting 4x4 array where both have them. Colouring all of the other squares
    #in a different colour (green!)

    #To solve this task we will need to identify the shape of the array, and then we will
    #flatten the array to (1, N), where N is the total number of items in the array. As
    #we need to combine the two 4x4 coloured arrays we will then split the (1,N) array
    #into two, removing the dividing array. We shall then add the two arrays together and
    #then enumerate it to find where there are black colours (0). We then replace the
    #black (non-zero) with the green and reshape to the correct format for the output.
    '''

    # First we need to define the shape of the array being assessed using .shape
    h, w = x.shape

    # Then we need to flatten nDimension out the array to a (1, N) array
    y = x.ravel()

    # We need to split out the top array of colours from 0 to the width times the width
    # index in the flatten array. This will future proof should we any other NxN array
    y1 = y[0:(w*w)]

    # We will split out the bottom array of colours, removing the 1x4 array by starting
    # the index at width times the width plus the width
    y2 = y[(w*w+w):]

    # Add the two arrays together so we can identify the black (zeros)
    y_total = (y1+y2)

    # Set the value for the green output colour
    value = 3

    # Enumerate through the list to identify the zeros in the combined arrays
    index = [j for j, a in enumerate(y_total) if a != 0]

    # We now need to iterate through the list of non-zeros
    for b in index:

        # Replacing the values with the green (3)
        y_total[b] = value

    # Now we will reshape the (1, N) array back to the correct shape
    x = y_total.reshape(w, -w)

    return x

def solve_e26a3af2(x):
    '''
    ########################### SOLUTION No.4 ###############################
    #Using the ARC testing interface Task e26a3af2 shows a varying NxM arrays.
    #Where some of the arrays N = M. In each of the tasks, there is either a
    #vertical or horizontal lines of varying width containing primarily 3 or 4
    #colours (numbers), with a random placement of any colour throughout. Each
    #task solution clears out the random colours and leaves a neat 3 or 4 colour
    #lines. The test grid is 5 colours in a horizontal arrangement.

    #To solve the task we will enumerate the array and identify the mode colour
    #in each row of the array, inorder to create a new NxM array in clean of any
    #random colours. This will work with the horizontally aligned colours easily,
    #however we will need to transpose the array for the vertically aligned colours.
    #An if statement that will assess if the mode is greater than 1/2 of the array
    #width (as all arrays have 3 or more colours) will be able to ensure the mode
    #and array will be correctly reformed.
    '''

    # We need to create an empty list for mode colour in each row
    mode = []

    # We need to create an empty list for maximum number of colours in each row
    # This will allow us to verify if we need to transpose the array
    total = []

    # Gather the height and width of the array so we can create the new array correctly
    h, w = x.shape

    # We will enumerate x to identify the the mode colour in each row
    for i, j in enumerate(x):

        # Create a list of each value and count of each to identify the mode
        vals, counts = np.unique(x[i], return_counts=True)

        # Capture the value tha made the colour the mode
        total = max(counts)

        # Create an location index for the value which is the mode
        index = np.argmax(counts)

        # Store the mode in the row
        c = vals[index]

        # Append the mode to the global list
        mode = np.append(mode, [c], axis=0)

    # We will now transpose the array and complete the same tasks as above
    # We need to create an empty list for mode colour in each row
    x_T = x.T

    # We need to create an empty list for maximum number of colours in each row
    # This will allow us to verify if we need to transpose the array
    mode_T = []

    # Gather the height and width of the array so we can create the new array correctly
    h_T, w_T = x_T.shape

    # We will enumerate x to identify the the mode colour in each row
    for i_T, j_T in enumerate(x_T):

        # Create a list of each value and count of each to identify the mode
        vals_T, counts_T = np.unique(x_T[i_T], return_counts=True)

        # Create an location index for the value which is the mode
        index_T = np.argmax(counts_T)

        # Store the mode in the row
        c_T = vals_T[index_T]

        # Append the mode to the global list
        mode_T = np.append(mode_T, [c_T], axis=0)

    # Create an if statement to verify if we are working with a vertical task
    if total < w/2:
        ##The mode is less than half the count so we will use the transposed array##
        # Create an empty numpy array
        f_T = np.array([])

        # Iterate through the global mode list created
        for i in mode_T:
            # Append each mode value as a new row and multiply it by the width of
            # of the original transposed array
            f_T = np.append(f_T, [i] * w_T, axis=0)

        # Reshape the new array to the original transposed array
        r = f_T.reshape(h_T, w_T)

        # Transpose the new array back to its original shape
        x = r.T

    # Else we are now working with a horizontal type task
    else:
        ##The mode is more than half the count so we will use the normal array##
        # Create an empty numpy array
        f = np.array([])

        # Iterate through the global mode list created
        for i in mode:

            # Append each mode value as a new row and multiply it by the width of
            # of the original array
            f = np.append(f, [i] * w, axis=0)

        # Reshape the new array to the original array
        x = f.reshape(h, w)

    return x

def solve_9ecd008a(x):
    '''
    ########################### SOLUTION No.5 ###############################
    Using the ARC testing interface Task 9ecd008 shows a large 20x20 array.
    All with a pattern of different colours. Each task has a small 3x3 array with
    colour missing, the solution for each task is to create a 3x3 of the missing
    colours in the correct pattern. As each pattern is mirrored on x and y axes where
    10x20 = 10x20 and 20x10 = 20x10, the missing pattern is its mirror on the y axis
    in each task.

    To solve the task we will enumerate the array and identify which rows contain
    a black (zero) square by calculating the length of the row with no black. If
    the row has black square, we will pass this into another loop to enumerate for
    the index of the black square in the row. In turn getting the absolute difference
    between the index and the length of the row so we capture the index of the mirror
    colours. We will then append the correct colour into a new list and finally
    reshape it to the 3x3 array.
    '''
    # 1st we will create an empty list to append the correct pattern into
    answer = []

    # We will now get the shape of the array to determine the length of each row
    h, w = x.shape

    # We will now start the loop through the array
    for i in x:

        # We will set the value for the black square
        black = 0

        # We will enumerate to identify the length of each row that has a black square
        non_count = [j for j, y in enumerate(i) if y != black]

        # Now create an if statement to pass the row into the next loop if contains a
        # black square
        if len(non_count) != w:

            # We will now enumerate to identify the count of the black squares
            zero_index = [j for j, y in enumerate(i) if y == black]

            # Create a (1,3) array of the maximum index number so we can calculate
            # the mirror location of the black square
            mirror_index = [w - 1] * max(zero_index)

            # Create an empty list of the mirrored index number
            index = []

            # Create a loop to get the location of the black square and the mirror
            # location by getting the absolute difference between the indexes
            for q, p in zip(mirror_index, zero_index):
                index.append(abs(q - p))

            # Finally we will append the colour of the mirrored index in the row
            for c in index:

                # Append the colour to the def global answer
                answer = np.append(answer, [i[c]], axis=0)

    # We will now reshape the list to the correct array size
    x = answer.reshape(3, -3)

    return x

def solve_178fcbfb(x):
    '''
    ########################### SOLUTION No.6 ###############################
    Using the ARC testing interface Task 178fcbfb shows a number of NxM arrays
    where N is sometimes equal to M. There are 3 colours red, green and
    blue in a number of squares in each array. The solution for each task shows
    that the green and blue squares fill their row completely with their colour.
    Then the the red is filled in vertically, under-lapping the green and blue
    squares.

    To solve the task we will enumerate the array and identify which rows contain
    a black (zero) square by calculating the length of the row with a non-black. If
    the row a non-black square, we will pass this into another loop to enumerate for
    the value of the colour in the row. If not red (2) we will then enumerate the row
    to replace all the black (0) squares in with its correct colour. After this we
    will redo the above by transposing the array and look for the red (2) squares
    only to replace the black (0) values with red.
    '''
    # First we need to get the shape of the array to sense check which rows need to
    # be passed into the loop to fill out the colour in the row
    h, w = x.shape

    # Initiate loop through the array
    for i in x:

        # We will set the value for the black square
        black = 0

        # We will enumerate to identify the length of each row that has a black square
        is_black = [j for j, y in enumerate(i) if y == black]

        # Now create an if statement to pass the row into the next loop if contains a
        # black square
        if len(is_black) != w:

            # We will now enumerate to identify the count of the black squares
            non_black = [j for j, y in enumerate(i) if y != black]

            # We will now store the colour value
            colour = i[non_black]

            # We will now sense check that this row does not contain red (2)
            if colour != 2:

                # We will now enumerate to identify the index of the black squares
                zero_index = [j for j, y in enumerate(i) if y == black]

                # We will now loop through to replace the black squares
                for b in zero_index:

                    # Replacing the values with the colour
                    i[b] = colour

    # Initiate loop through the transposed array
    for i in x.T:

        # We will set the value for the black square
        black = 0

        # We will enumerate to identify the length of each row that has a black square
        is_black = [j for j, y in enumerate(i) if y == black]

        # Now create an if statement to pass the row into the next loop if contains a
        # black square
        if len(is_black) != w:

            # We will now enumerate to identify the count of the black squares
            non_black = [j for j, y in enumerate(i) if y != black]

            # We will now store the colour value
            colour = i[non_black]

            # We will need to only pass in the row with the red (2) value
            if 2 in colour:

                # We will now enumerate to identify the count of the black squares
                zero_index = [j for j, y in enumerate(i) if y == black]

                # We will now loop through to replace the black squares
                for b in zero_index:

                    # Replacing the values with the red (2)
                    i[b] = 2
    return x

def main():
    # Find all the functions defined in this file whose names are
    # like solve_abcd1234(), and run them.

    # regex to match solve_* functions and extract task IDs
    p = r"solve_([a-f0-9]{8})"
    tasks_solvers = []
    # globals() gives a dict containing all global names (variables
    # and functions), as name: value pairs.
    for name in globals():
        m = re.match(p, name)
        if m:
            # if the name fits the pattern eg solve_abcd1234
            ID = m.group(1) # just the task ID
            solve_fn = globals()[name] # the fn itself
            tasks_solvers.append((ID, solve_fn))

    for ID, solve_fn in tasks_solvers:
        # for each task, read the data and call test()
        directory = os.path.join("..", "data", "training")
        json_filename = os.path.join(directory, ID + ".json")
        data = read_ARC_JSON(json_filename)
        test(ID, solve_fn, data)

def read_ARC_JSON(filepath):
    """Given a filepath, read in the ARC task data which is in JSON
    format. Extract the train/test input/output pairs of
    grids. Convert each grid to np.array and return train_input,
    train_output, test_input, test_output."""

    # Open the JSON file and load it
    data = json.load(open(filepath))

    # Extract the train/test input/output grids. Each grid will be a
    # list of lists of ints. We convert to Numpy.
    train_input = [np.array(data['train'][i]['input']) for i in range(len(data['train']))]
    train_output = [np.array(data['train'][i]['output']) for i in range(len(data['train']))]
    test_input = [np.array(data['test'][i]['input']) for i in range(len(data['test']))]
    test_output = [np.array(data['test'][i]['output']) for i in range(len(data['test']))]

    return (train_input, train_output, test_input, test_output)

def test(taskID, solve, data):
    """Given a task ID, call the given solve() function on every
    example in the task data."""
    print(taskID)
    train_input, train_output, test_input, test_output = data
    print("Training grids")
    for x, y in zip(train_input, train_output):
        yhat = solve(x)
        show_result(x, y, yhat)
    print("Test grids")
    for x, y in zip(test_input, test_output):
        yhat = solve(x)
        show_result(x, y, yhat)

def show_result(x, y, yhat):
    print("Input")
    print(x)
    print("Correct output")
    print(y)
    print("Our output")
    print(yhat)
    print("Correct?")
    if y.shape != yhat.shape:
        print(f"False. Incorrect shape: {y.shape} v {yhat.shape}")
    else:
        print(np.all(y == yhat))

if __name__ == "__main__": main()