#!/usr/bin/env python3

import argparse
import os
import sys

# you can import under an alias. the aliases here are widely used conventions
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

# you can import a specific function from a module
import math
from math import sqrt

def do_math():
	two = sqrt(4)				# imported individually from math
	three = math.factorial(2)

"""PEP 8

PEP 8 is the universaly accepted Style Guide for Python Code.
https://www.python.org/dev/peps/pep-0008/

Adhere to it if you want your code to look like Python to other Python programmers.
"""

def main(text, reps):
	""" Google Style Python Docstrings

	Utilities like sphinx can parse docstrings like this and turn them into nicely
	formatted .pdf, .html and other files. Different formats are common, and parsable
	by sphinx. Check the 'normal' Sphinx style docstrings and the NumPy style docstrings
	for more info.

	Args:
        reps (int): Number of times text should be printed.
        text (str): Text to be printed.

	Returns:
		tuple: parameters given as input.

	Examples:
		Simple test can be done with the 'Doctest' library.  Added benefit is that other
		programmers have an idea wath to expect from your code.

		>>> main(1, "Hello, world!")
		(1, "Hello, world!")
	"""

	# hopefully these function names are usable as table of content.
	empty_function_without_error()
	print_to_stdout(text, reps)
	make_a_dictionary()
	slice_a_list()
	format_a_string()
	use_comprehensions()
	read_and_write_a_file()
	make_a_class()
	parse_with_biopython()
	do_regex()
	use_numpy_arrays()
	make_a_matplotlib_figure()
	load_image_as_nulpy_matrix()

	return(text, reps)

def empty_function_without_error():
    """ empty function"""
    pass	# without 'pass' an empty function gives an error. usefull as placeholder.

def print_to_stdout(text, reps):
	""" Print text to stdout x times."""
	for i in range(reps): # use: range(size), range(begin, end) or range(begin, end, step_size)
		print(text)

def make_a_dictionary():
	""" use dictcomprehesions for bigger/more complex dictionaries.
	see: use_comprehensions()
	"""

	# Either use curly brackets...
	a_dict = {1:"You do not talk about FIGHT CLUB.",
			  2:"You do not talk about FIGHT CLUB.",
			  6:"No shirts, no shoes."}

	# ...or use the dict() function with parameters...
	b_dict = dict(fruit=["apple", "orange"],
				  vegetable=["courgette"])

	# ...or give a list with tuples as input.
	c_dict = dict([("fruit", ["apple", "orange"]),
				   ("vegetable", ["courgette"]  )])

	# print dicts using .values(), .keys() or .items()
	for val in a_dict.values():
		print(val)

	for key in b_dict.keys():
		print(key, b_dict[key])

	for key, val in c_dict.items():
		print(key, val)

def slice_a_list():
	string = "World!Hello"

	a_list = [string[6:],				# slice strings by index
			  "W" + string[1:5]]		# string + string = string
	a_list = a_list + [string[5]*3]		# list + list = list
	a_list += [1]						# you can mix ints and strings in one list.

	# join list entries in one string (but convert ints to string if necessary)
	new_string = " ".join([str(i) for i in a_list])
	print(new_string)

def format_a_string():
	"""Use .format to format strings

	{<index>:<options>}

	Examples:
		>>> print("{0} {0} {1} {2:06.2f} {2:6.2f} {2:.2f} {2:2f}".format(1, 1+1, 4.0/3.0))
		'1 1 2   1.33 001.33   1.33 1.33 1.333333'
	"""
	auto_formatted = "{} {} {}".format(1, 1+1, 4.0/3.0)
	formatted_with_options = "{0} {0} {1} {2: 6.2f} {2:06.2f} {2:6.2f} {2:.2f} {2:2f}".format(1, 1+1, 4.0/3.0)
	print(auto_formatted, formatted_with_options)

def use_comprehensions():
	# the dict comprehension way
	integer_list = range(10)
	binary_list = [ bin(i) for i in integer_list ]			# use functions within the comprehension
	zipped_list = zip(integer_list, binary_list )			# zip two lists together (or unzip using list(zip(*zipped_list)) )
	big_dict = {key: value for key, value in zipped_list }

	# the "look at me" all in one line way
	oneliner_dict = {key: value for key, value in zip(range(10), [bin(i) for i in integer_list])}

	print(big_dict == oneliner_dict) # true. meaning "==" checks for content not object id.

def read_and_write_a_file():
	""" opening, reading and writing files.

	The 'with ... as ...' keywords are context managers. They are basicly a shorthand for
	predefined "try, catch, finaly" statements. In case of open() they close they your file
	for you.
	"""
	cwd = os.getcwd()
	file1 = os.path.join(cwd, "file1.txt")
	file2 = os.path.join(cwd, "file2.txt")

	with open(file1, "a+") as file:	# a+ reads and appends to a file.
		first_line = file.readline()
		second_line = file.readline()

	with open(file1, "r") as f1, open(file1, "w") as f2: # opens two files at once. r = read mode, w = (over)write mode
		for line in f1.readlines():
			f2.write(line)

class MyClass:
	def __init__(self, a, b):
		self.a = a
		self.b = b
		self.my_method()

	def my_method(self):
		self.c = self.a + self.b

class MySubClass(MyClass):
	def __init__(self, a, b, d):
		if sys.version_info[0] < 3:			# Check for python version. In case your university pc's are outdated...
			MyClass.__init__(self, a, b)	# python 2
		else:
			super().__init__(a, b)			# python 3
		self.d = d

def make_a_class():
	my_class = MySubClass(1, 2, 4)
	print(my_class.a,
		  my_class.b,
		  my_class.c,
		  my_class.d)

def parse_with_biopython():
	"""read the docs :)

	https://biopython.org/DIST/docs/api/Bio.SeqIO-module.html
	"""
	# biopython is not available on (all) ku leuven pc's. Therefor not part of exam?
	### from Bio import SeqIO # Bio[!] not Biopython

def do_regex():
	fasta_file = """>gi|1348917|gb|G26685|G26685 human STS STS_D11734.
	CGGAGCCAGCGAGCATATGCTGCATGAGGACCTTTCTATCTTACATTATGGCTGGGAATCTTACTCTTTC
	ATCTGATACCTTGTTCAGATTTCAAAATAGTTGTAGCCTTATCCTGGTTTTACAGATGTGAAACTTTCAA
	GAGATTTACTGACTTTCCTAGAATAGTTTCTCTACTGGAAACCTGATGCTTTTATAAGCCATTGTGATTA
	GGATGACTGTTACAGGCTTAGCTTTGTGTGAAANCCAGTCACCTTTCTCCTAGGTAATGAGTAGTGCTGT
	TCATATTACTNTAAGTTCTATAGCATACTTGCNATCCTTTANCCATGCTTATCATANGTACCATTTGAGG
	AATTGNTTTGCCCTTTTGGGTTTNTTNTTGGTAAANNNTTCCCGGGTGGGGGNGGTNNNGAAA
	>gi|1348917|gb|G26685|G26685 human STS STS_D11734.
	CGGAGCCAGCGAGCATATGCTGCATGAGGACCTTTCTATCTTACATTATGGCTGGGAATC
	TTACTCTTTCATCTGATACCTTGTTCAGATTTCAAAATAGTTGTAGCCTTATCCTGGTTT
	TACAGATGTGAAACTTTCAAGAGATTTACTGACTTTCCTAGAATAGTTTCTCTACTGGAA
	ACCTGATGCTTTTATAAGCCATTGTGATTAGGATGACTGTTACAGGCTTAGCTTTGTGTG
	AAANCCAGTCACCTTTCTCCTAGGTAATGAGTAGTGCTGTTCATATTACTNTAAGTTCTA
	TAGCATACTTGCNATCCTTTANCCATGCTTATCATANGTACCATTTGAGGAATTGNTTTG
	CCCTTTTGGGTTTNTTNTTGGTAAANNNTTCCCGGGTGGGGGNGGTNNNGAAA
	"""

def use_numpy_arrays():
	A = np.array([[1, 2, 3],
			  [4, 5, 6],
			  [7, 8, 9]],
			  dtype=float)
	b = np.arange(9.0)
	B = np.reshape(b, (3, 3))
	C = np.full((3, 3), 3)

	# do some linear algebra
	print(A.dot(B))
	print(np.transpose(A))
	print(np.linalg.inv(A))
	print(np.linalg.svd(A))

def make_a_matplotlib_figure():
	#---------------------------------------------------------------------------
	mu = 2
	sigma =  0.5
	v = np.random.normal(mu,sigma,10000)
	plt.hist(v, bins=50)
	plt.show()
	#---------------------------------------------------------------------------
	x = np.linspace(0, 2, 100) # Return evenly spaced numbers over a specified interval.
	plt.plot(x, x, label='linear')
	plt.plot(x, x**2, label='quadratic')
	plt.plot(x, x**3, label='cubic')
	plt.xlabel('x label')
	plt.ylabel('y label')
	plt.title("Simple Plot")
	plt.legend()
	plt.show()
	#---------------------------------------------------------------------------
	np.random.seed(19680801)
	data = np.random.randn(2, 100)

	# it not very 'pythonic' but you can assign two variables at once.
	# matplotlib kinda forces you here.
	fig, axs = plt.subplots(2,2,figsize=(5,5))

	axs[0,0].hist(data[0])
	axs[1,0].scatter(data[0], data[1])
	axs[0,1].plot(data[0], data[1])
	axs[1,1].hist2d(data[0], data[1])
	plt.show()

def load_image_as_nulpy_matrix():
	""" PIL - Python Image Library

	is not part of the Standard Library and not installed by default at KU Leuven pc's
	"""
	pass

def parseArgs():
	""" Parses arguments from commandline using the 'argparse' module.

	The argparse module is part of the Python standard library, meaning that it is
	included in all python installations.

	Examples:
		python .\test.py 'Hello, world' -r 2

		>>> Hello, world
		>>> Hello, world

		python .\test.py 'Hello, world'

		>>> Hello, world

		python .\test.py -h

		>>> usage: test.py [-h] [-r [REPS]] text
		>>>
		>>> positional arguments:
		>>>   text
		>>>
		>>> optional arguments:
		>>>	  -h, --help            show this help message and exit
		>>>   -r [REPS], --reps [REPS]
		>>>   						specify number of times text should be printed
	"""
	parser = argparse.ArgumentParser()
	# simple positional argument
	# parser.add_argument('text') 									# required by default
	parser.add_argument('-t', '--text') 							# required by default
	# more complex keyword argument
	parser.add_argument('-r', '--reps', type=int, required=False, 	# '-' and '--' indicate flags
		nargs='?', 													# nargs='?' means 0-1 arguments possible
		const=1, 													# const=<...> gives a default value
		help="specify number of times text should be printed")		# help text available from the commandline

	args = parser.parse_args()
	if args.reps is None or args.text is None:
		return("text here", 1)
	else:
		return(args.text, args.reps)

""" triggers if this scripts '__name__' is that of the '__main__' program.
In other words: This only triggers if the script is run directly and not by another
script.
"""
if __name__ == "__main__":
	main(*parseArgs())												# *<some iterable> unpacks a iterable


# -*- coding: utf-8 -*-
"""
Examples of Sandpile

AUTHORS:

- David Perkinson (2015-05) [Using `examples.py` from homology as
  template.]

This file constructs some examples of Sandpiles.

The examples are accessible by typing ``sandpiles.NAME``, where
``NAME`` is the name of the example.  You can get a list by typing
``sandpiles.`` and hitting the TAB key::

   sandpiles.Complete
   sandpiles.Cycle
   sandpiles.Diamond
   sandpiles.Grid
   sandpiles.House

See the documentation for each particular type of example for full details.
"""

from sage.sandpiles.sandpile import Sandpile
from sage.graphs.graph_generators import graphs

class SandpileExamples(object):
    """
    Some examples of sandpiles.

    Here are the available examples; you can also type
    ``sandpiles.``  and hit tab to get a list:

    - :meth:`Complete`
    - :meth:`Cycle`
    - :meth:`Diamond`
    - :meth:`Grid`
    - :meth:`House`

    EXAMPLES::

        sage: s = sandpiles.Complete(4)
        sage: s.invariant_factors()
        [1, 4, 4]
        sage: s.laplacian()
        [ 3 -1 -1 -1]
        [-1  3 -1 -1]
        [-1 -1  3 -1]
        [-1 -1 -1  3]
    """
    def __call__(self):
        r"""
        If sandpiles() is executed, return a helpful message.

        INPUT:

        None

        OUTPUT:

        None

        EXAMPLES::

            sage: sandpiles()
            Try sandpile.FOO() where FOO is in the list:
            <BLANKLINE>
                Complete, Cycle, Diamond, Fan, Grid, House, Wheel
        """
        print 'Try sandpile.FOO() where FOO is in the list:\n'
        print "    " + ", ".join([str(i) for i in dir(sandpiles) if i[0]!='_'])

    def Complete(self, n):
        """
        The complete sandpile graph with `n` vertices.

        INPUT:

        -  ``n`` -- positive integer

        OUTPUT:

        - Sandpile

        EXAMPLES::

            sage: s = sandpiles.Complete(4)
            sage: s.group_order()
            16
            sage: sandpiles.Complete(3) == sandpiles.Cycle(3)
            True
        """
        return Sandpile(graphs.CompleteGraph(n),0)

    def Cycle(self, n):
        """
        Sandpile on the cycle graph with `n` vertices.

        INPUT:

        -  ``n`` -- a non-negative integer

        OUTPUT:

        - Sandpile

        EXAMPLES::

            sage: s = sandpiles.Cycle(4)
            sage: s.edges()
            [(0, 1, 1),
             (0, 3, 1),
             (1, 0, 1),
             (1, 2, 1),
             (2, 1, 1),
             (2, 3, 1),
             (3, 0, 1),
             (3, 2, 1)]
        """
        return Sandpile(graphs.CycleGraph(n),0)

    def Diamond(self):
        """
        Sandpile on the diamond graph.

        INPUT:

        None

        OUTPUT:

        - Sandpile

        EXAMPLES::

            sage: s = sandpiles.Diamond()
            sage: s.invariant_factors()
            [1, 1, 8]
        """
        return Sandpile(graphs.DiamondGraph(),0)

    def Fan(self, n, deg_three_verts=False):
        """
        Sandpile on the Fan graph with a total of `n` vertices.

        INPUT:

        -  ``n`` -- a non-negative integer

        OUTPUT:

        - Sandpile

        EXAMPLES::

            sage: f = sandpiles.Fan(10)
            sage: f.group_order() == fibonacci(18)
            True
            sage: f = sandpiles.Fan(10,True)  # all nonsink vertices have deg 3
            sage: f.group_order() == fibonacci(20)
            True
        """
        f = graphs.WheelGraph(n)
        if n>2:
            f.delete_edge(1,n-1)
            if deg_three_verts:
                f.allow_multiple_edges(True)
                f.add_edges([(0,1),(0,n-1)])
            return Sandpile(f,0)
        elif n==1:
            return Sandpile(f,0)
        elif n==2:
            if deg_three_verts:
                return Sandpile({0:{1:3}, 1:{0:3}})
            else:
                return Sandpile(f,0)

    def Grid(self, m, n):
        """
        Sandpile on the diamond graph.

        INPUT:

        -  ``m``, ``n`` -- negative integers

        OUTPUT:

        - Sandpile

        EXAMPLES::

            sage: s = sandpiles.Grid(2,3)
            sage: s.vertices()
            [(0, 0), (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3)]
            sage: s.invariant_factors()
            [1, 1, 1, 1, 1, 2415]
            sage: s = sandpiles.Grid(1,1)
            sage: s.dict()
            {(0, 0): {(1, 1): 4}, (1, 1): {(0, 0): 4}}
        """
        G = graphs.Grid2dGraph(m+2,n+2)
        G.allow_multiple_edges(True)  # to ensure each vertex ends up with degree 4
        V = [(i,j) for i in [0,m+1] for j in range(n+2)] + [(i,j) for j in [0,n+1] for i in range(m+2)]
        G.merge_vertices(V)
        return Sandpile(G, (0,0))

    def House(self):
        """
        Sandpile on the House graph.

        INPUT:

        None

        OUTPUT:

        - Sandpile

        EXAMPLES::

            sage: s = sandpiles.House()
            sage: s.invariant_factors()
            [1, 1, 1, 11]
        """
        return Sandpile(graphs.HouseGraph(),0)

    def Wheel(self, n):
        """
        Sandpile on the wheel graph with a total of `n` vertices.

        INPUT:

        -  ``n`` -- a non-negative integer

        OUTPUT:

        - Sandpile

        EXAMPLES::

            sage: w = sandpiles.Wheel(6)
            sage: w.invariant_factors()
            [1, 1, 1, 11, 11]
        """
        return Sandpile(graphs.WheelGraph(n),0)

sandpiles = SandpileExamples()


import numpy as np
from . import algo1_ext

# A wrapper function to call the C++ extension
# It enables proper docstring
def cpp_multiply(data: np.ndarray, k: float) -> np.ndarray:
    """Multiple all elements by k

    Args:
        data (np.ndarray): 1d np.array of dtype=np.double
        k (float): k

    Returns:
        np.ndarray: 1d np.array
    """
    result = np.empty(data.size)
    algo1_ext.multiply_by(data, result, k)
    return result

def py_multiply(data: np.ndarray, k: float) -> np.ndarray:
    return data * k


#!/usr/bin/env python

import numpy as np
import itertools as it
from copy import deepcopy
import sys

from animation import *
from mobject import *
from constants import *
from mobject.region import  *
from scene import Scene
from script_wrapper import command_line_create_scene
from inventing_math import divergent_sum, draw_you

class SimpleText(Scene):
    args_list = [
         ("Build the foundation of what we know",),
         ("What would that feel like?",),
         ("Arbitrary decisions hinder generality",),
         ("Section 1: Discovering and Defining Infinite Sums",),
         ("Section 2: Seeking Generality",),
         ("Section 3: Redefining Distance",),
         ("``Approach''?",),
         ("Rigor would dictate you ignore these",),
         ("dist($A$, $B$) = dist($A+x$, $B+x$) \\quad for all $x$",),
         ("How does a useful distance function differ from a random function?",),
         ("Pause now, if you like, and see if you can invent your own distance function from this.",),
         ("$p$-adic metrics \\\\ ($p$ is any prime number)",),
         ("This is not meant to match the history of discoveries",),
    ]
    @staticmethod
    def args_to_string(text):
        return initials(filter(lambda c : c in string.letters + " ", text))

    def construct(self, text):
        self.add(TextMobject(text))

class SimpleTex(Scene):
    args_list = [
        (
            "\\frac{9}{10}+\\frac{9}{100}+\\frac{9}{1000}+\\cdots = 1",
            "SumOf9s"
        ),
        (
            "0 < p < 1",
            "PBetween0And1"
        ),
    ]
    @staticmethod
    def args_to_string(expression, words):
        return words

    def construct(self, expression, words):
        self.add(TexMobject(expression))

class OneMinusOnePoem(Scene):
    def construct(self):
        verse1 = TextMobject("""
            \\begin{flushleft}
            When one takes one from one  \\\\
            plus one from one plus one \\\\
            and on and on but ends  \\\\
            anon then starts again, \\\\
            then some sums sum to one, \\\\
            to zero other ones. \\\\
            One wonders who'd have won \\\\
            had stopping not been done; \\\\
            had he summed every bit \\\\
            until the infinite. \\\\
            \\end{flushleft}
        """).scale(0.5).to_corner(UP+LEFT)
        verse2 = TextMobject("""
            \\begin{flushleft}
            Lest you should think that such \\\\
            less well-known sums are much \\\\
            ado about nonsense \\\\
            I do give these two cents: \\\\
            The universe has got \\\\
            an answer which is not \\\\
            what most would first surmise, \\\\
            it is a compromise, \\\\
            and though it seems a laugh \\\\
            the universe gives ``half''. \\\\
            \\end{flushleft}
        """).scale(0.5).to_corner(DOWN+LEFT)
        equation = TexMobject(
            "1-1+1-1+\\cdots = \\frac{1}{2}"
        )
        self.add(verse1, verse2, equation)

class DivergentSum(Scene):
    def construct(self):
        self.add(divergent_sum().scale(0.75))

class PowersOfTwoSmall(Scene):
    def construct(self):
        you, bubble = draw_you(with_bubble=True)
        bubble.write(
            "Is there any way in which apparently \
            large powers of two can be considered small?"
        )
        self.add(you, bubble, bubble.content)

class FinalSlide(Scene):
    def construct(self):
        self.add(TextMobject("""
            \\begin{flushleft}
            Needless to say, what I said here only scratches the
            surface of the tip of the iceberg of the p-adic metric.
            What is this new form of number I referred to?
            Why were distances in the 2-adic metric all powers of
            $\\frac{1}{2}$ and not some other base?
            Why does it only work for prime numbers? \\\\
            \\quad \\\\
            I highly encourage anyone who has not seen p-adic numbers
            to look them up and learn more, but even more edifying than
            looking them up will be to explore this idea for yourself directly.
            What properties make a distance function useful, and why?
            What do I mean by ``useful''?  Useful for what purpose?
            Can you find infinite sums or sequences which feel like
            they should converge in the 2-adic metric, but don't converge
            to a rational number? Go on!  Search!  Invent!
            \\end{flushleft}
        """, size = "\\small"))


import numpy as np    # numpy library

import matplotlib.pyplot as plt    # matplotlib pyplot

import sys      # gives access to C like sys library

import os       # gives access to the operating system

print(sys.argv)  # prints command line arguments including program name

print(os.getcwd())   # prints current working directory


"""
Test index support in time series models

1. Test support for passing / constructing the underlying index in __init__
2. Test wrapping of output using the underlying index
3. Test wrapping of prediction / forecasting using the underlying index or
   extensions of it.

Author: Chad Fulton
License: BSD-3
"""
from __future__ import division, absolute_import, print_function
from statsmodels.compat.testing import SkipTest

import warnings
import numpy as np
import pandas as pd
import pytest

from numpy.testing import (assert_allclose, assert_almost_equal, assert_equal,
                           assert_raises)

from statsmodels.tsa.base import tsa_model

nobs = 5
base_dta = np.arange(nobs)
dta = [
    base_dta.tolist(),
    base_dta,
    pd.Series(base_dta),
    pd.DataFrame(base_dta)
]

base_date_indexes = [
    # (usual candidates)
    pd.DatetimeIndex(start='1950-01-01', periods=nobs, freq='D'),
    pd.DatetimeIndex(start='1950-01-01', periods=nobs, freq='W'),
    pd.DatetimeIndex(start='1950-01-01', periods=nobs, freq='M'),
    pd.DatetimeIndex(start='1950-01-01', periods=nobs, freq='Q'),
    pd.DatetimeIndex(start='1950-01-01', periods=nobs, freq='A'),
    # (some more complicated frequencies)
    pd.DatetimeIndex(start='1950-01-01', periods=nobs, freq='2Q'),
    pd.DatetimeIndex(start='1950-01-01', periods=nobs, freq='2QS'),
    pd.DatetimeIndex(start='1950-01-01', periods=nobs, freq='5s'),
    pd.DatetimeIndex(start='1950-01-01', periods=nobs, freq='1D10min')]

# Note: we separate datetime indexes and period indexes because the
# date coercion does not handle string versions of PeriodIndex objects
# most of the time.
base_period_indexes = [
    pd.PeriodIndex(start='1950-01-01', periods=nobs, freq='D'),
    pd.PeriodIndex(start='1950-01-01', periods=nobs, freq='W'),
    pd.PeriodIndex(start='1950-01-01', periods=nobs, freq='M'),
    pd.PeriodIndex(start='1950-01-01', periods=nobs, freq='Q'),
    pd.PeriodIndex(start='1950-01-01', periods=nobs, freq='A')]
try:
    # Only later versions of pandas support these
    base_period_indexes += [
        pd.PeriodIndex(start='1950-01-01', periods=nobs, freq='2Q'),
        pd.PeriodIndex(start='1950-01-01', periods=nobs, freq='5s'),
        pd.PeriodIndex(start='1950-01-01', periods=nobs, freq='1D10min')]
except:
    pass

date_indexes = [
    (x, None) for x in base_date_indexes]
period_indexes = [
    (x, None) for x in base_period_indexes]

numpy_datestr_indexes = [
    (x.map(str), x.freq) for x in base_date_indexes]
list_datestr_indexes = [
    (x.tolist(), y) for x, y in numpy_datestr_indexes]
series_datestr_indexes = [
    (pd.Series(x), y) for x, y in list_datestr_indexes]

numpy_datetime_indexes = [
    (x.to_datetime().to_pydatetime(), x.freq)
    for x in base_date_indexes]
list_datetime_indexes = [
    (x.tolist(), y) for x, y in numpy_datetime_indexes]
series_datetime_indexes = [
    (pd.Series(x, dtype=object), y) for x, y in list_datetime_indexes]

series_timestamp_indexes = [
    (pd.Series(x), x.freq) for x in base_date_indexes]

# Supported increment indexes
supported_increment_indexes = [(pd.Int64Index(np.arange(nobs)), None)]

# Supported date indexes
# Only the Int64Index and the `date_indexes` are valid without
# frequency information
supported_date_indexes = (
    numpy_datestr_indexes +
    list_datestr_indexes + series_datestr_indexes +
    numpy_datetime_indexes + list_datetime_indexes +
    series_datetime_indexes + series_timestamp_indexes)

# Unsupported (but still valid) indexes
unsupported_indexes = [
    # Non-incrementing-from-zero indexes
    (np.arange(1, nobs+1), None),
    (np.arange(nobs)[::-1], None),
    # Float indexes, even if they increment from zero
    (np.arange(nobs) * 1.0, None),
    # Non-date-string indexes
    ([x for x in 'abcde'], None),
    # Non-date-object indexes
    ([str, 1, 'a', -30.1, {}], None),
]

# Unsupported date indexes (i.e. those without inferrable frequency)
unsupported_date_indexes = [
    (['1950', '1952', '1941', '1954', '1991'], None),
    (['1950-01-01', '1950-01-02', '1950-01-03',
      '1950-01-04', '1950-01-06'], None)
]

def test_instantiation_valid():
    tsa_model.__warningregistry__ = {}

    # The primary goal of this test function is to make sure the
    # combinations that are supposed to be valid are actually valid, and
    # that valid but unsupported options give the appropriate warning
    # Secondarily, it also has some tests that invalid combinations raise
    # exceptions, although it's not intended to be comprehensive.
    #
    # Each of `endog`, `exog` can be in the following categories:
    # 0. None (only for exog)
    # 1. list
    # 2. numpy array
    # 3. pandas series
    # 4. pandas dataframe
    #
    # Each pandas index (of `endog`, `exog`, or passed to `dates`) can be:
    # 0. None
    # 1. Int64Index with values exactly equal to 0, 1, ..., nobs-1
    # 2. DatetimeIndex with frequency
    # 3. PeriodIndex with frequency
    # 4. Anything that doesn't fall into the above categories also should
    #    only raise an exception if it was passed to dates, and may trigger
    #    a warning otherwise.
    #
    # `date` can be one of the following:
    # 0. None
    # 2. Pandas index #2
    # 3. Pandas index #3
    # 4. List of date strings (requires freq)
    # 5. List of datetime objects (requires freq)
    # 6. Array of date strings (requires freq)
    # 7. Array of datetime objects (requires freq)
    # 8. Series of date strings (requires freq)
    # 9. Series of datetime objects (requires freq)
    # 10. Series of pandas timestamps (requires freq)
    # 11. Anything that doesn't fall into the above categories should raise
    #     an exception.
    #
    # `freq` can be:
    # 0. None
    # 1. Something that can be passed to `pd.to_offset`
    # 2. Anything that can't should raise an Exception
    #
    # Each test will be denoted by:
    # endog.index:exog.index/date/freq where the corresponding
    # location is the integer from above; e.g. 1.0:0.0/9/1 corresponds to
    # - List endog (with no index)
    # - No exog
    # - Series of datetime objects
    # - Something valid for `pd.to_offset` (e.g. 'D', if that works with
    #   dates)
    #
    # Notice that the endog.index:exog.index really collapses to a single
    # element, which is the evaluated `row_label`. This is first the exog
    # index, if exists, then the endog index, if it exists, or None
    # otherwise. **Thus, we will not test `exog` here.**
    #
    # Example valid combinations of row_label/date/freq include:
    # - */0/0 (i.e. anything is valid if date and freq are not passed)
    # - */%/% where %/% denotes a valid date/freq combination (i.e. any
    #   row_label is valid if a valid date/freq combination is given)
    #
    # Example invalid combinations include:
    # - [1-2],[3-4].4/0/[1-2] (i.e. if have freq, then must have, or
    #   coerce, a date index)
    # - */[4-10]/0 (i.e. for some types of dates, freq must be passed)

    # Baseline: list, numpy endog with no dates, no freq
    for endog in dta[:2]:
        # No indexes, should not raise warnings
        with warnings.catch_warnings():
            warnings.simplefilter('error')

            mod = tsa_model.TimeSeriesModel(endog)
            assert_equal(type(mod._index) == pd.Int64Index, True)
            assert_equal(mod._index_none, True)
            assert_equal(mod._index_dates, False)
            assert_equal(mod._index_generated, True)
            assert_equal(mod.data.dates, None)
            assert_equal(mod.data.freq, None)

    # Test list, numpy endog, pandas w/o index; with dates / freq argument
    for endog in dta:
        # Supported date indexes, should not raise warnings, do not need freq
        with warnings.catch_warnings():
            warnings.simplefilter('error')

            for ix, freq in date_indexes + period_indexes:
                mod = tsa_model.TimeSeriesModel(endog, dates=ix)
                if freq is None:
                    freq = ix.freq
                if not isinstance(freq, str):
                    freq = freq.freqstr
                assert_equal(
                    isinstance(mod._index, (pd.DatetimeIndex, pd.PeriodIndex)),
                    True)
                assert_equal(mod._index_none, False)
                assert_equal(mod._index_dates, True)
                assert_equal(mod._index_generated, False)
                assert_equal(mod._index.freq, mod._index_freq)
                assert_equal(mod.data.dates.equals(mod._index), True)
                assert_equal(mod.data.freq, freq)

        # Supported date indexes, should not raise warnings, can use valid freq
        with warnings.catch_warnings():
            warnings.simplefilter('error')

            for ix, freq in date_indexes + period_indexes:
                mod = tsa_model.TimeSeriesModel(endog, dates=ix, freq=freq)
                if freq is None:
                    freq = ix.freq
                if not isinstance(freq, str):
                    freq = freq.freqstr
                assert_equal(
                    isinstance(mod._index, (pd.DatetimeIndex, pd.PeriodIndex)),
                    True)
                assert_equal(mod._index_none, False)
                assert_equal(mod._index_dates, True)
                assert_equal(mod._index_generated, False)
                assert_equal(mod._index.freq, mod._index_freq)
                assert_equal(mod.data.dates.equals(mod._index), True)
                assert_equal(mod.data.freq, freq)

        # Other supported indexes, with valid freq, should not raise warnings
        with warnings.catch_warnings():
            warnings.simplefilter('error')

            for ix, freq in supported_date_indexes:
                mod = tsa_model.TimeSeriesModel(endog, dates=ix, freq=freq)
                if freq is None:
                    freq = ix.freq
                if not isinstance(freq, str):
                    freq = freq.freqstr
                assert_equal(
                    isinstance(mod._index, (pd.DatetimeIndex, pd.PeriodIndex)),
                    True)
                assert_equal(mod._index_none, False)
                assert_equal(mod._index_dates, True)
                assert_equal(mod._index_generated, False)
                assert_equal(mod._index.freq, mod._index_freq)
                assert_equal(mod.data.dates.equals(mod._index), True)
                assert_equal(mod.data.freq, freq)

        # Since only supported indexes are valid `dates` arguments, everything
        # else is invalid here
        for ix, freq in supported_increment_indexes + unsupported_indexes:
            assert_raises(ValueError, tsa_model.TimeSeriesModel, endog,
                          dates=ix)

    # Test pandas (Series, DataFrame); with index (no dates/freq argument)
    for base_endog in dta[2:4]:
        # DatetimeIndex and PeriodIndex, should not raise warnings
        with warnings.catch_warnings():
            warnings.simplefilter('error')

            for ix, freq in date_indexes + period_indexes:
                endog = base_endog.copy()
                endog.index = ix

                mod = tsa_model.TimeSeriesModel(endog)
                if freq is None:
                    freq = ix.freq
                if not isinstance(freq, str):
                    freq = freq.freqstr
                assert_equal(
                    isinstance(mod._index, (pd.DatetimeIndex, pd.PeriodIndex)),
                    True)
                assert_equal(mod._index_none, False)
                assert_equal(mod._index_dates, True)
                assert_equal(mod._index_generated, False)
                assert_equal(mod._index.freq, mod._index_freq)
                assert_equal(mod.data.dates.equals(mod._index), True)
                assert_equal(mod.data.freq, freq)

        # Increment index (this is a "supported" index in the sense that it
        # doesn't raise a warning, but obviously not a date index)
        endog = base_endog.copy()
        endog.index = supported_increment_indexes[0][0]

        mod = tsa_model.TimeSeriesModel(endog)
        assert_equal(type(mod._index) == pd.Int64Index, True)
        assert_equal(mod._index_none, False)
        assert_equal(mod._index_dates, False)
        assert_equal(mod._index_generated, False)
        assert_equal(mod._index_freq, None)
        assert_equal(mod.data.dates, None)
        assert_equal(mod.data.freq, None)

        # Supported indexes *when a freq is given*, should not raise a warning
        with warnings.catch_warnings():
            warnings.simplefilter('error')

            for ix, freq in supported_date_indexes:
                endog = base_endog.copy()
                endog.index = ix

                mod = tsa_model.TimeSeriesModel(endog, freq=freq)
                if freq is None:
                    freq = ix.freq
                if not isinstance(freq, str):
                    freq = freq.freqstr
                assert_equal(
                    isinstance(mod._index, (pd.DatetimeIndex, pd.PeriodIndex)),
                    True)
                assert_equal(mod._index_none, False)
                assert_equal(mod._index_dates, True)
                assert_equal(mod._index_generated, False)
                assert_equal(mod._index.freq, mod._index_freq)
                assert_equal(mod.data.dates.equals(mod._index), True)
                assert_equal(mod.data.freq, freq)

        # Unsupported (or any) indexes to the given series, *when a supported
        # date and freq is given*, should not raise a warning
        with warnings.catch_warnings():
            warnings.simplefilter('error')

            for ix, freq in supported_date_indexes:
                endog = base_endog.copy()
                endog.index = unsupported_indexes[0][0]

                mod = tsa_model.TimeSeriesModel(endog, dates=ix, freq=freq)
                if freq is None:
                    freq = ix.freq
                if not isinstance(freq, str):
                    freq = freq.freqstr
                assert_equal(
                    isinstance(mod._index, (pd.DatetimeIndex, pd.PeriodIndex)),
                    True)
                assert_equal(mod._index_none, False)
                assert_equal(mod._index_dates, True)
                assert_equal(mod._index_generated, False)
                assert_equal(mod._index.freq, mod._index_freq)
                assert_equal(mod.data.dates.equals(mod._index), True)
                assert_equal(mod.data.freq, freq)

        # Date indexes with inferrable freq, but no given freq, should all give
        # warnings
        message = ('No frequency information was provided,'
                   ' so inferred frequency %s will be used.')
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')

            for ix, freq in supported_date_indexes:
                endog = base_endog.copy()
                endog.index = ix
                mod = tsa_model.TimeSeriesModel(endog)
                if freq is None:
                    freq = ix.freq
                if not isinstance(freq, str):
                    freq = freq.freqstr
                assert_equal(type(mod._index) == pd.DatetimeIndex, True)
                assert_equal(mod._index_none, False)
                assert_equal(mod._index_dates, True)
                assert_equal(mod._index_generated, False)
                assert_equal(mod._index.freq, mod._index_freq)
                assert_equal(mod.data.dates.equals(mod._index), True)

                # Note: here, we need to hedge the test a little bit because
                # inferred frequencies aren't always the same as the original
                # frequency. From the examples above, when the actual freq is
                # 2QS-OCT, the inferred freq is 2QS-JAN. This is an issue with
                # inferred frequencies, but since we are warning the user, it's
                # not a failure of the code. Thus we only test the "major" part
                # of the freq, and just test that the right message is given
                # (even though it won't have the actual freq of the data in
                # it).
                assert_equal(mod.data.freq.split('-')[0], freq.split('-')[0])
                assert_equal(str(w[-1].message), message % mod.data.freq)

        # Unsupported (but valid) indexes, should all give warnings
        message = ('An unsupported index was provided and will be'
                   ' ignored when e.g. forecasting.')
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')

            for ix, freq in unsupported_indexes:
                endog = base_endog.copy()
                endog.index = ix
                mod = tsa_model.TimeSeriesModel(endog)
                assert_equal(type(mod._index) == pd.Int64Index, True)
                assert_equal(mod._index_none, False)
                assert_equal(mod._index_dates, False)
                assert_equal(mod._index_generated, True)
                assert_equal(mod._index_freq, None)
                assert_equal(mod.data.dates, None)
                assert_equal(mod.data.freq, None)

                assert_equal(str(w[0].message), message)

        # Date indexes without inferrable freq, and with no given freq, should
        # all give warnings
        message = ('A date index has been provided, but it has no'
                   ' associated frequency information and so will be'
                   ' ignored when e.g. forecasting.')
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')

            for ix, freq in unsupported_date_indexes:
                endog = base_endog.copy()
                endog.index = ix
                mod = tsa_model.TimeSeriesModel(endog)
                assert_equal(type(mod._index) == pd.Int64Index, True)
                assert_equal(mod._index_none, False)
                assert_equal(mod._index_dates, False)
                assert_equal(mod._index_generated, True)
                assert_equal(mod._index_freq, None)
                assert_equal(mod.data.dates, None)
                assert_equal(mod.data.freq, None)

                assert_equal(str(w[0].message), message)

    # Test (invalid) freq with no index
    endog = dta[0]
    assert_raises(ValueError, tsa_model.TimeSeriesModel, endog,
                  freq=date_indexes[1][0].freq)

    # Test conflicting index, freq specifications
    endog = dta[2].copy()
    endog.index = date_indexes[0][0]
    assert_raises(ValueError, tsa_model.TimeSeriesModel, endog,
                  freq=date_indexes[1][0].freq)

    # Test unsupported index, but a freq specification
    endog = dta[2].copy()
    endog.index = unsupported_indexes[0][0]
    assert_raises(ValueError, tsa_model.TimeSeriesModel, endog,
                  freq=date_indexes[1][0].freq)

    # Test index that can coerce to date time but incorrect freq
    endog = dta[2].copy()
    endog.index = numpy_datestr_indexes[0][0]
    assert_raises(ValueError, tsa_model.TimeSeriesModel, endog,
                  freq=date_indexes[1][0].freq)

def test_prediction_increment_unsupported():
    # a. Generated from unsupported index
    endog = dta[2].copy()
    endog.index = unsupported_indexes[-2][0]
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('ignore')
        mod = tsa_model.TimeSeriesModel(endog)

    # Basic prediction: [0, end]; notice that since this is an in-sample
    # prediction, the index returned is the (unsupported) original index
    start_key = 0
    end_key = None
    start, end, out_of_sample, prediction_index = (
        mod._get_prediction_index(start_key, end_key))

    assert_equal(start, 0)
    assert_equal(end, nobs-1)
    assert_equal(out_of_sample, 0)
    assert_equal(prediction_index.equals(mod.data.row_labels), True)

    # Negative index: [-2, end]; notice that since this is an in-sample
    # prediction, the index returned is a piece of the (unsupported)
    # original index
    start_key = -2
    end_key = -1
    start, end, out_of_sample, prediction_index = (
        mod._get_prediction_index(start_key, end_key))

    assert_equal(start, 3)
    assert_equal(end, 4)
    assert_equal(out_of_sample, 0)
    assert_equal(prediction_index.equals(mod.data.row_labels[3:]), True)

    # Forecasting: [1, 5], notice that since an unsupported index was given,
    # a warning will be issued
    start_key = 1
    end_key = nobs
    message = ('No supported index is available.'
               ' Prediction results will be given with'
               ' an integer index beginning at `start`.')
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')

        start, end, out_of_sample, prediction_index = (
            mod._get_prediction_index(start_key, end_key))

        assert_equal(str(w[0].message), message)

    assert_equal(start, 1)
    assert_equal(end, 4)
    assert_equal(out_of_sample, 1)
    assert_equal(prediction_index.equals(pd.Index(np.arange(1, 6))), True)

def test_prediction_increment_nonpandas():
    endog = dta[0]
    mod = tsa_model.TimeSeriesModel(endog)

    # Basic prediction: [0, end]; since there was no index at all and the data
    # is not Pandas, the returned prediction_index is None
    start_key = 0
    end_key = None
    start, end, out_of_sample, prediction_index = (
        mod._get_prediction_index(start_key, end_key))

    assert_equal(start, 0)
    assert_equal(end, nobs-1)
    assert_equal(out_of_sample, 0)
    assert_equal(prediction_index is None, True)

    # Negative index: [-2, end]; since there was no index at all and the data
    # is not Pandas, the returned prediction_index is None
    start_key = -2
    end_key = -1
    start, end, out_of_sample, prediction_index = (
        mod._get_prediction_index(start_key, end_key))

    assert_equal(start, 3)
    assert_equal(end, 4)
    assert_equal(out_of_sample, 0)
    assert_equal(prediction_index is None, True)

    # Forecasting: [1, 5]; since there was no index at all and the data
    # is not Pandas, the returned prediction_index is None
    start_key = 1
    end_key = nobs
    start, end, out_of_sample, prediction_index = (
        mod._get_prediction_index(start_key, end_key))

    assert_equal(start, 1)
    assert_equal(end, 4)
    assert_equal(out_of_sample, 1)
    assert_equal(prediction_index is None, True)

def test_prediction_increment_pandas_noindex():
    endog = dta[2].copy()
    mod = tsa_model.TimeSeriesModel(endog)

    # Basic prediction: [0, end]; since there was no index and the data is
    # Pandas, the index is the generated incrementing index, and no warning is
    # issued
    start_key = 0
    end_key = None
    start, end, out_of_sample, prediction_index = (
        mod._get_prediction_index(start_key, end_key))

    assert_equal(start, 0)
    assert_equal(end, nobs-1)
    assert_equal(out_of_sample, 0)
    assert_equal(prediction_index.equals(mod._index), True)

    # Negative index: [-2, end]; since there was no index and the data is
    # Pandas, the index is the generated incrementing index, and no warning is
    # issued
    start_key = -2
    end_key = -1
    start, end, out_of_sample, prediction_index = (
        mod._get_prediction_index(start_key, end_key))

    assert_equal(start, 3)
    assert_equal(end, 4)
    assert_equal(out_of_sample, 0)
    assert_equal(prediction_index.equals(mod._index[3:]), True)

    # Forecasting: [1, 5]; since there was no index and the data is
    # Pandas, the index is the generated incrementing index, and no warning is
    # issued
    start_key = 1
    end_key = nobs
    start, end, out_of_sample, prediction_index = (
        mod._get_prediction_index(start_key, end_key))

    assert_equal(start, 1)
    assert_equal(end, 4)
    assert_equal(out_of_sample, 1)
    assert_equal(prediction_index.equals(pd.Index(np.arange(1, 6))), True)

def test_prediction_increment_pandas_dates():
    # Date-based index
    endog = dta[2].copy()
    endog.index = date_indexes[0][0]  # Daily, 1950-01-01, 1950-01-02, ...
    mod = tsa_model.TimeSeriesModel(endog)

    # Basic prediction: [0, end]; the index is the date index
    start_key = 0
    end_key = None
    start, end, out_of_sample, prediction_index = (
        mod._get_prediction_index(start_key, end_key))

    assert_equal(start, 0)
    assert_equal(end, nobs-1)
    assert_equal(out_of_sample, 0)
    assert_equal(type(prediction_index) == type(endog.index), True)
    assert_equal(prediction_index.equals(mod._index), True)

    # Negative index: [-2, end]
    start_key = -2
    end_key = -1
    start, end, out_of_sample, prediction_index = (
        mod._get_prediction_index(start_key, end_key))

    assert_equal(start, 3)
    assert_equal(end, 4)
    assert_equal(out_of_sample, 0)
    assert_equal(type(prediction_index) == type(endog.index), True)
    assert_equal(prediction_index.equals(mod._index[3:]), True)

    # Forecasting: [1, 5]; the index is an extended version of the date index
    start_key = 1
    end_key = nobs
    start, end, out_of_sample, prediction_index = (
        mod._get_prediction_index(start_key, end_key))

    assert_equal(start, 1)
    assert_equal(end, 4)
    assert_equal(out_of_sample, 1)
    desired_index = pd.DatetimeIndex(start='1950-01-02', periods=5, freq='D')
    assert_equal(prediction_index.equals(desired_index), True)

    # Date-based keys
    start_key = '1950-01-01'
    end_key = '1950-01-08'
    start, end, out_of_sample, prediction_index = (
        mod._get_prediction_index(start_key, end_key))

    assert_equal(start, 0)
    assert_equal(end, 4)
    assert_equal(out_of_sample, 3)
    desired_index = pd.DatetimeIndex(start='1950-01-01', periods=8, freq='D')
    assert_equal(prediction_index.equals(desired_index), True)

def test_prediction_increment_pandas_dates_nanosecond():
    # This test is only valid if the version of Pandas has nanosecond support
    # and is > 0.14
    try:
        # Date-based index
        endog = dta[2].copy()
        endog.index = pd.DatetimeIndex(start='1970-01-01', periods=len(endog),
                                       freq='N')
        mod = tsa_model.TimeSeriesModel(endog)
    except:
        raise SkipTest

    # Basic prediction: [0, end]; the index is the date index
    start_key = 0
    end_key = None
    start, end, out_of_sample, prediction_index = (
        mod._get_prediction_index(start_key, end_key))

    assert_equal(start, 0)
    assert_equal(end, nobs-1)
    assert_equal(out_of_sample, 0)
    assert_equal(type(prediction_index) == type(endog.index), True)
    assert_equal(prediction_index.equals(mod._index), True)

    # Negative index: [-2, end]
    start_key = -2
    end_key = -1
    start, end, out_of_sample, prediction_index = (
        mod._get_prediction_index(start_key, end_key))

    assert_equal(start, 3)
    assert_equal(end, 4)
    assert_equal(out_of_sample, 0)
    assert_equal(type(prediction_index) == type(endog.index), True)
    assert_equal(prediction_index.equals(mod._index[3:]), True)

    # Forecasting: [1, 5]; the index is an extended version of the date index
    start_key = 1
    end_key = nobs
    start, end, out_of_sample, prediction_index = (
        mod._get_prediction_index(start_key, end_key))

    assert_equal(start, 1)
    assert_equal(end, 4)
    assert_equal(out_of_sample, 1)
    desired_index = pd.DatetimeIndex(start='1970-01-01',
                                     periods=6, freq='N')[1:]
    assert_equal(prediction_index.equals(desired_index), True)

    # Date-based keys
    start_key = pd.Timestamp('1970-01-01')
    end_key = pd.Timestamp(start_key.value + 7)
    start, end, out_of_sample, prediction_index = (
        mod._get_prediction_index(start_key, end_key))

    assert_equal(start, 0)
    assert_equal(end, 4)
    assert_equal(out_of_sample, 3)
    desired_index = pd.DatetimeIndex(start='1970-01-01', periods=8, freq='N')
    assert_equal(prediction_index.equals(desired_index), True)

def test_custom_index():
    tsa_model.__warningregistry__ = {}

    endog = pd.Series(np.random.normal(size=5),
                      index=['a', 'b', 'c', 'd', 'e'])
    message = ('An unsupported index was provided and will be ignored when'
               ' e.g. forecasting.')
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')

        mod = tsa_model.TimeSeriesModel(endog)
        assert_equal(str(w[0].message), message)
    start_key = -2
    end_key = -1
    start, end, out_of_sample, prediction_index = (
        mod._get_prediction_index(start_key, end_key))

    # Test the default output index
    assert_equal(prediction_index.equals(pd.Index(['d', 'e'])), True)
    start, end, out_of_sample, prediction_index = (
        mod._get_prediction_index(start_key, end_key, index=['f', 'g']))

    # Test custom output index
    assert_equal(prediction_index.equals(pd.Index(['f', 'g'])), True)

    # Test out-of-sample
    start_key = 4
    end_key = 5
    message = ('No supported index is available.'
               ' Prediction results will be given with'
               ' an integer index beginning at `start`.')
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')

        start, end, out_of_sample, prediction_index = (
            mod._get_prediction_index(start_key, end_key))
        assert_equal(prediction_index.equals(pd.Index([4, 5])), True)
        assert_equal(str(w[0].message), message)

    # Test out-of-sample custom index
    start, end, out_of_sample, prediction_index = (
        mod._get_prediction_index(start_key, end_key, index=['f', 'g']))
    assert_equal(prediction_index.equals(pd.Index(['f', 'g'])), True)

    # Test invalid custom index
    assert_raises(ValueError, mod._get_prediction_index, start_key, end_key,
                  index=['f', 'g', 'h'])

import numpy,from numpy,from statsmodels


import numpy as np

class KFold:
    """
    This class provides the functionality to split a dataset ir order to perform k-cross validation.
    """

    def __init__(self):
        """
        Constructor for the KFold class.
        """
        self.data = None

    def fit(self, data: np.ndarray):
        """
        Fits the data to actual object.
        :param data:                                Data to split.
        """
        self.data = data

    def split(self, n_fold: int, random_state=42) -> list:
        """
        This method returns a list of tuples where you have the index for training and testing.
        :param n_fold:                              Number of splits.
        :param random_state:                        Numpy random state (int)
        :return:                                    A list of tuple. Each tuple:
                                                        1) Training index
                                                        2) Testing index
        """

        assert self.data is not None, "You must fit the data first."
        assert type(n_fold) == int and n_fold > 0, "The number of k-folds must be a positive integer."
        assert n_fold < self.data.shape[0], "The number of splits must be greater than the amount of data."

        # Shuffle the data
        np.random.shuffle(self.data)
        total_indexes = np.array(range(self.data.shape[0]))

        # Generates the indexes limits
        index_limits = np.linspace(0, self.data.shape[0], n_fold+1)
        indexes_tuples = []
        for index_limit_pos in range(len(index_limits)-1):
            lower_index = int(round(index_limits[index_limit_pos]))
            upper_index = int(round(index_limits[index_limit_pos+1])-1)
            print("Fold: {}, Lower: {}, Upper: {}".format(index_limit_pos + 1, lower_index, upper_index))

            testing_index = total_indexes[lower_index: upper_index]
            training_index_lower = total_indexes[:lower_index]
            training_index_upper = total_indexes[upper_index:]
            training_index = np.concatenate([training_index_lower, training_index_upper])
            indexes_tuples.append((training_index, testing_index))

        return indexes_tuples

    def fit_split(self, data: np.ndarray, n_fold: int, random_state=42) -> list:
        """
        Fits and splits the data
        :param data:                                Data to split.
        :param n_fold:                              Number of splits.
        :param random_state:                        Numpy random state.
        :return:                                    The same as split method.
        """
        self.fit(data)
        return self.split(n_fold, random_state=random_state)


# Copyright 2017 Battelle Energy Alliance, LLC
#
# 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.
"""
  This Module performs Unit Tests for the cached_ndarray module
  It cannot be considered part of the active code but of the regression test system
"""

#For future compatibility with Python 3
from __future__ import division, print_function, unicode_literals, absolute_import
import warnings
warnings.simplefilter('default',DeprecationWarning)

import os,sys
import numpy as np

# numpy with version 1.14.0 and upper will change the floating point type and print
# https://docs.scipy.org/doc/numpy-1.14.0/release.html
if int(np.__version__.split('.')[1]) > 13:
  np.set_printoptions(**{'legacy':'1.13'})

frameworkDir = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])),os.pardir,os.pardir,os.pardir,os.pardir,'framework'))
sys.path.append(frameworkDir)
from utils import cached_ndarray
print (cached_ndarray)

results = {"pass":0,"fail":0}

def checkAnswer(comment,value,expected,tol=1e-10,updateResults=True):
  """
    This method is aimed to compare two floats given a certain tolerance
    @ In, comment, string, a comment printed out if it fails
    @ In, value, float, the value to compare
    @ In, expected, float, the expected value
    @ In, tol, float, optional, the tolerance
    @ In, updateResults, bool, optional, if True updates global results
    @ Out, None
  """
  if abs(value - expected) > tol:
    print("checking answer",comment,value,"!=",expected)
    if updateResults:
      results["fail"] += 1
    return False
  else:
    if updateResults:
      results["pass"] += 1
    return True

#establish test array
origin = np.array([-3.14,2.99792,2.718,8.987,0.618])
#test init
testArray = cached_ndarray.c1darray(values=origin)

#test iter, getitem
for i,val in enumerate(testArray):
  checkAnswer('content storage indexing',val,origin[i])

#test len
checkAnswer('array length',len(testArray),5)

#test append single value
testArray.append(-6.626)
checkAnswer('append value',testArray[-1],-6.626)
#test append array
testArray.append(np.array([12.56,6.67]))
checkAnswer('append array, 0',testArray[-2],12.56)
checkAnswer('append array, 1',testArray[-1],6.67)

#test return closest
right = [4,6,5]
for f,find in enumerate([0.6,1e10,-1e10]):
  closest = testArray.returnIndexClosest(find)
  checkAnswer('find closest %1.1e' %find,closest,right[f])

#test returnIndexFirstPassage
checkAnswer('index first passage',testArray.returnIndexFirstPassage(3),3)

#test max
checkAnswer('index max',testArray.returnIndexMax(),6)

#test min
checkAnswer('index min',testArray.returnIndexMin(),5)

#test repr
msg = str(testArray)
right = 'array([ -3.14   ,   2.99792,   2.718  ,   8.987  ,   0.618  ,  -6.626  ,\n        12.56   ,   6.67   ])'

if msg == right:
  results['pass']+=1
else:
  print('checking string representation does not match:\n'+msg,'\n!=\n'+right)
  results['fail']+=1

print(results)

sys.exit(results["fail"])
"""
  <TestInfo>
    <name>framework.cachedNDArray</name>
    <author>talbpaul</author>
    <created>2016-11-01</created>
    <classesTested>utils.cachedNDArray</classesTested>
    <description>
       This test performs Unit Tests for the cached_ndarray module
       It cannot be considered part of the active code but of the regression test system
    </description>
    <revisions>
      <revision author="talbpaul" date="2016-11-08">Relocated utils tests</revision>
      <revision author="alfoa" date="2017-01-21">Adding this test description.</revision>
    </revisions>
  </TestInfo>
"""


#!/usr/bin/python

"""
    Starter code for exploring the Enron dataset (emails + finances);
    loads up the dataset (pickled dict of dicts).

    The dataset has the form:
    enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict }

    {features_dict} is a dictionary of features associated with that person.
    You should explore features_dict as part of the mini-project,
    but here's an example to get you started:

    enron_data["SKILLING JEFFREY K"]["bonus"] = 5600000

"""

import pickle

enron_data = pickle.load(open("../final_project/final_project_dataset.pkl", "r"))

num_total_datasets = len(enron_data)
print "1. Size of the Enron DataSets: {}".format(num_total_datasets)
print "2. Featues in the Enron DataSets: {}".format(len(enron_data["METTS MARK"]))

# Format the Dictionary
import json;
# mmDict = enron_data.items()[0:2]
# mmDictIndent = json.dumps(mmDict, indent=1)
# print mmDictIndent

# How many POIs are there in the E+F dataset?
names = enron_data.keys()
num_poi = 0
for name in names:
	if enron_data[name]['poi'] == 1:
		num_poi += 1

print '3. Number of POIs:{}'.format(num_poi)

# 18. What is the total value of the stock belonging to James Prentice?
print "4. What is the total value of the stock belonging to James Prentice?"
james_prentice_dict = enron_data['PRENTICE JAMES']
james_prentice = json.dumps(james_prentice_dict, indent=1)
print "\tJames Prentice's total stock value: {}".format(james_prentice_dict['total_stock_value'])

# 19. How many email messages do we have from Wesley Colwell to persons of interest?
wesley_colwell_dict = enron_data['COLWELL WESLEY']
wesley_colwell = json.dumps(wesley_colwell_dict, indent=1)
print "5. Number of email messages from Wesley Colwell to poi: {}".format(wesley_colwell_dict['from_this_person_to_poi'])

# 20. What's the value of stock options exercised by Jeffrey K Skilling?
jeffrey_k_skilling_dict = enron_data['SKILLING JEFFREY K']
jeffrey_k_skilling = json.dumps(jeffrey_k_skilling_dict, indent=1)
# print jeffrey_k_skilling
print "6. Value of stock options exercised by Jeffrey K Skilling: {}".format(jeffrey_k_skilling_dict['exercised_stock_options'])

# 27. How many folks in this dataset have a quantified salary? What about a known email address?
import numpy
num_quantified_salary = num_total_datasets
num_known_email_address = num_total_datasets
for name in names:
	if enron_data[name]['salary'] == 'NaN':
		num_quantified_salary -= 1
	if enron_data[name]['email_address'] == 'NaN':
		num_known_email_address -= 1
print "7. Number of folks having a quantified salary: {}".format(num_quantified_salary)
print "8. Number of folks having a known email address: {}".format(num_known_email_address)

# 28. Conversion from Dictionary to Array
from feature_format import *

features = ["salary",
	"to_messages",
	"deferral_payments",
	"total_payments",
	"exercised_stock_options",
	"bonus",
	"restricted_stock",
	"shared_receipt_with_poi",
	"restricted_stock_deferred",
	"total_stock_value",
	"expenses",
	"loan_advances",
	"from_messages",
	"other",
	"from_this_person_to_poi",
	"poi",
	"director_fees",
	"deferred_income",
	"long_term_incentive",
	"email_address",
	"from_poi_to_this_person"]

# print features
feature_list = ["poi", "salary", "bonus"]
data_array = featureFormat(enron_data, feature_list)
label, features = targetFeatureSplit(data_array)
# print data_array
# print label
# print features

# 29. How many people in the E+F dataset have 'NaN' for their total payments?
# What percentage of people in the dataset as a whole is this?
num_nan_total_payments = 0
for name in names:
    if enron_data[name]['total_payments'] == 'NaN':
        num_nan_total_payments += 1
print "9. Number of people having \'Nan\' for their total payments: {}\t \
	Percentage: {}".format(num_nan_total_payments,
                        100 * float(num_nan_total_payments) / num_total_datasets)

# 30. How many POIs in the E+F dataset have 'NaN' for their total payments?
# What percentage of POI's as a whole is this?
num_poi_nan_total_payments = 0
for name in names:
	if enron_data[name]['poi'] == True:
		if enron_data[name]['total_payments'] == 'NaN':
			num_poi_nan_total_payments += 1
print "10. Number of POIs having NaN for their total payments: {}\tPercentage: {}".format(num_poi_nan_total_payments, 100 * float(num_poi_nan_total_payments) / num_poi)


import numpy as np
import matplotlib.pylab as plt

datos=np.genfromtxt("datos.dat")
t=datos[:,0]
x=datos[:,1]
v=datos[:,2]

plt.figure()
plt.plot(t,x,c='b')
plt.xlabel("t")
plt.ylabel("x")
plt.title("Posición vs. Tiempo Resorte sin fricción")
plt.grid()
plt.savefig("CendalesLuisResorte.png")
plt.close()


# Copyright 2021 The NetKet 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.

import netket as nk
import numpy as np
import pytest
from scipy.stats import combine_pvalues, chisquare

import jax
import flax
from jax import numpy as jnp

from .. import common

pytestmark = common.skipif_mpi

nk.config.update("NETKET_EXPERIMENTAL", True)
np.random.seed(1234)

WEIGHT_SEED = 1234
SAMPLER_SEED = 15324

samplers = {}

# TESTS FOR SPIN HILBERT
# Constructing a 1d lattice
g = nk.graph.Hypercube(length=4, n_dim=1)

# Hilbert space of spins from given graph
hi = nk.hilbert.Spin(s=0.5, N=g.n_nodes)
ha = nk.operator.Ising(hilbert=hi, graph=g, h=1.0)
move_op = sum([nk.operator.spin.sigmax(hi, i) for i in range(hi.size)])

hi_spin1 = nk.hilbert.Spin(s=1, N=g.n_nodes)
hib = nk.hilbert.Fock(n_max=1, N=g.n_nodes, n_particles=1)
hib_u = nk.hilbert.Fock(n_max=3, N=g.n_nodes)

samplers["Exact: Spin"] = nk.sampler.ExactSampler(hi, n_chains=8)
samplers["Exact: Fock"] = nk.sampler.ExactSampler(hib_u, n_chains=4)

samplers["Metropolis(Local): Spin"] = nk.sampler.MetropolisLocal(hi, n_chains=16)

samplers["MetropolisNumpy(Local): Spin"] = nk.sampler.MetropolisLocalNumpy(
    hi, n_chains=16
)
# samplers["MetropolisNumpy(Local): Fock"] = nk.sampler.MetropolisLocalNumpy(
#    hib_u, n_chains=8
# )
# samplers["MetropolisNumpy(Local): Doubled-Spin"] = nk.sampler.MetropolisLocalNumpy(
#    nk.hilbert.DoubledHilbert(nk.hilbert.Spin(s=0.5, N=2)), n_chains=8
# )

samplers["MetropolisPT(Local): Spin"] = nk.sampler.MetropolisLocalPt(
    hi, n_chains=8, n_replicas=4
)
samplers["MetropolisPT(Local): Fock"] = nk.sampler.MetropolisLocalPt(
    hib_u, n_chains=8, n_replicas=4
)

samplers["Metropolis(Exchange): Fock-1particle"] = nk.sampler.MetropolisExchange(
    hib, n_chains=16, graph=g
)

samplers["Metropolis(Hamiltonian,Jax): Spin"] = nk.sampler.MetropolisHamiltonian(
    hi,
    hamiltonian=ha,
    reset_chains=True,
)

samplers["Metropolis(Hamiltonian,Numpy): Spin"] = nk.sampler.MetropolisHamiltonianNumpy(
    hi,
    hamiltonian=ha,
    reset_chains=True,
)

samplers["Metropolis(Custom: Sx): Spin"] = nk.sampler.MetropolisCustom(
    hi, move_operators=move_op
)

# samplers["MetropolisPT(Custom: Sx): Spin"] = nk.sampler.MetropolisCustomPt(hi, move_operators=move_op, n_replicas=4)

samplers["Autoregressive: Spin 1/2"] = nk.sampler.ARDirectSampler(hi, n_chains=16)
samplers["Autoregressive: Spin 1"] = nk.sampler.ARDirectSampler(hi_spin1, n_chains=16)
samplers["Autoregressive: Fock"] = nk.sampler.ARDirectSampler(hib_u, n_chains=16)

# The following fixture initialisees a model and it's weights
# for tests that require it.
@pytest.fixture
def model_and_weights(request):
    def build_model(hilb, sampler=None):
        if isinstance(sampler, nk.sampler.ARDirectSampler):
            ma = nk.models.ARNNDense(hilbert=hilb, layers=3, features=5)
        else:
            # Build RBM by default
            ma = nk.models.RBM(
                alpha=1,
                dtype=complex,
                kernel_init=nk.nn.initializers.normal(stddev=0.1),
                hidden_bias_init=nk.nn.initializers.normal(stddev=0.1),
            )
            # init network

        w = ma.init(jax.random.PRNGKey(WEIGHT_SEED), jnp.zeros((1, hi.size)))

        return ma, w

    # Do something with the data
    return build_model

# The following fixture returns one sampler at a time (and iterates through)
# all samplers.
#  it skips tests according to the --sampler cmdline argument introduced in
# conftest.py
@pytest.fixture(
    params=[pytest.param(sampl, id=name) for name, sampl in samplers.items()]
)
def sampler(request):
    cmdline_sampler = request.config.getoption("--sampler").lower()
    if cmdline_sampler == "":
        return request.param
    elif cmdline_sampler in request.node.name.lower():
        return request.param
    else:
        pytest.skip("skipped from command-line argument")

@pytest.fixture(params=[pytest.param(val, id=f", mpow={val}") for val in [1, 2]])
def set_pdf_power(request):
    def fun(sampler):
        cmdline_mpow = request.config.getoption("--mpow").lower()
        if cmdline_mpow == "all":
            # Nothing to skip
            pass
        elif cmdline_mpow == "single":
            # same sampler leads to same rng
            rng = np.random.default_rng(abs(hash((type(sampler), repr(sampler)))))
            exponent = rng.integers(1, 3)  # 1 or 2
            if exponent != request.param:
                pytest.skip(
                    "Running only 1 pdf exponent per sampler. Use --mpow=all to run all pdf exponents."
                )
        elif int(cmdline_mpow) != request.param:
            pytest.skip(f"Running only --mpow={cmdline_mpow}.")

        if isinstance(sampler, nk.sampler.ARDirectSampler) and request.param != 2:
            pytest.skip("ARDirectSampler only supports machine_pow = 2.")

        return sampler.replace(machine_pow=request.param)

    return fun

def test_states_in_hilbert(sampler, model_and_weights):
    hi = sampler.hilbert
    all_states = hi.all_states()

    ma, w = model_and_weights(hi, sampler)

    for sample in nk.sampler.samples(sampler, ma, w, chain_length=50):
        assert sample.shape == (sampler.n_chains, hi.size)
        for v in sample:
            assert v in all_states

    # if hasattr(sa, "acceptance"):
    #    assert np.min(sampler.acceptance) >= 0 and np.max(sampler.acceptance) <= 1.0

def findrng(rng):
    if hasattr(rng, "_bit_generator"):
        return rng._bit_generator.state["state"]
    else:
        return rng

# Mark tests that we know are failing on correctedness
def failing_test(sampler):
    if isinstance(sampler, nk.sampler.MetropolisSampler):
        if isinstance(sampler, nk.sampler.MetropolisPtSampler):
            return True

    return False

@pytest.fixture(
    params=[
        pytest.param(
            sampl,
            id=name,
            marks=pytest.mark.xfail(reason="MUSTFIX: this sampler is known to fail")
            if failing_test(sampl)
            else [],
        )
        for name, sampl in samplers.items()
    ]
)
def sampler_c(request):
    cmdline_sampler = request.config.getoption("--sampler").lower()
    if cmdline_sampler == "":
        return request.param
    elif cmdline_sampler in request.node.name.lower():
        return request.param
    else:
        pytest.skip("skipped from command-line argument")

# Testing that samples generated from direct sampling are compatible with those
# generated by markov chain sampling
# here we use a combination of power divergence tests
def test_correct_sampling(sampler_c, model_and_weights, set_pdf_power):
    sampler = set_pdf_power(sampler_c)

    hi = sampler.hilbert
    n_states = hi.n_states

    ma, w = model_and_weights(hi, sampler)

    n_samples = max(40 * n_states, 100)

    ps = np.absolute(nk.nn.to_array(hi, ma, w, normalize=False)) ** sampler.machine_pow
    ps /= ps.sum()

    n_rep = 6
    pvalues = np.zeros(n_rep)

    sampler_state = sampler.init_state(ma, w, seed=SAMPLER_SEED)

    for jrep in range(n_rep):
        sampler_state = sampler.reset(ma, w, state=sampler_state)

        # Burnout phase
        samples, sampler_state = sampler.sample(
            ma, w, state=sampler_state, chain_length=n_samples // 100
        )

        assert samples.shape == (
            n_samples // 100,
            sampler.n_chains,
            hi.size,
        )
        samples, sampler_state = sampler.sample(
            ma, w, state=sampler_state, chain_length=n_samples
        )

        assert samples.shape == (n_samples, sampler.n_chains, hi.size)

        sttn = hi.states_to_numbers(np.asarray(samples.reshape(-1, hi.size)))
        n_s = sttn.size

        # fill in the histogram for sampler
        unique, counts = np.unique(sttn, return_counts=True)
        hist_samp = np.zeros(n_states)
        hist_samp[unique] = counts

        # expected frequencies
        f_exp = n_s * ps
        statistics, pvalues[jrep] = chisquare(hist_samp, f_exp=f_exp)

    s, pval = combine_pvalues(pvalues, method="fisher")
    assert pval > 0.01 or np.max(pvalues) > 0.01

def test_throwing(model_and_weights):
    with pytest.raises(TypeError):
        nk.sampler.MetropolisHamiltonian(
            hi,
            hamiltonian=10,
            reset_chains=True,
        )

    with pytest.raises(ValueError):
        sampler = nk.sampler.MetropolisHamiltonian(
            nk.hilbert.DoubledHilbert(hi),
            hamiltonian=ha,
            reset_chains=True,
        )

        ma, w = model_and_weights(hi)

        # test raising of init state
        sampler.init_state(ma, w, seed=SAMPLER_SEED)

    with pytest.raises(ValueError):
        sampler = nk.sampler.MetropolisHamiltonianNumpy(
            nk.hilbert.Fock(3) ** hi.size,
            hamiltonian=ha,
            reset_chains=True,
        )

        ma, w = model_and_weights(hi)

        # test raising of init state
        sampler.init_state(ma, w, seed=SAMPLER_SEED)

    with pytest.raises(flax.errors.ScopeParamShapeError):
        sampler = nk.sampler.MetropolisHamiltonianNumpy(
            nk.hilbert.DoubledHilbert(hi),
            hamiltonian=ha,
            reset_chains=True,
        )

        ma, w = model_and_weights(hi)

        # test raising of init state
        sampler.init_state(ma, w, seed=SAMPLER_SEED)

def test_exact_sampler(sampler):
    known_exact_samplers = [nk.sampler.ExactSampler, nk.sampler.ARDirectSampler]
    if any(isinstance(sampler, x) for x in known_exact_samplers):
        assert sampler.is_exact is True
    else:
        assert sampler.is_exact is False

import numpy,from scipy,import jax,from jax


#  Copyright (c) 2021 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 sys

sys.path.append("..")

import paddle
from op_test import OpTest
from op_test_xpu import XPUOpTest
from xpu.get_test_cover_info import create_test_class, get_xpu_op_support_types, XPUOpTestWrapper

paddle.enable_static()

class XPUTestArgMax(XPUOpTestWrapper):

    def __init__(self):
        self.op_name = 'arg_max'

    class XPUBaseTestCase(XPUOpTest):

        def initTestCase(self):
            self.dims = (3, 4)
            self.axis = 1

        def setUp(self):
            self.op_type = 'arg_max'
            self.dtype = self.in_type
            self.initTestCase()

            self.x = (np.random.random(self.dims)).astype(self.dtype)
            self.inputs = {'X': self.x}
            self.attrs = {'axis': self.axis, 'use_xpu': True}
            self.outputs = {'Out': np.argmax(self.x, axis=self.axis)}

        def test_check_output(self):
            if paddle.is_compiled_with_xpu():
                place = paddle.XPUPlace(0)
                self.check_output_with_place(place)

    class TestArgMaxCase1(XPUBaseTestCase):

        def initTestCase(self):
            self.dims = (3, 4, 5)
            self.axis = -1

    class TestArgMaxCase2(XPUBaseTestCase):

        def initTestCase(self):
            self.dims = (3, 4, 5)
            self.axis = 0

    class TestArgMaxCase3(XPUBaseTestCase):

        def initTestCase(self):
            self.dims = (3, 4, 5)
            self.axis = 1

    class TestArgMaxCase4(XPUBaseTestCase):

        def initTestCase(self):
            self.dims = (3, 4, 5)
            self.axis = 2

    class TestArgMaxCase5(XPUBaseTestCase):

        def initTestCase(self):
            self.dims = (3, 4)
            self.axis = -1

    class TestArgMaxCase6(XPUBaseTestCase):

        def initTestCase(self):
            self.dims = (3, 4)
            self.axis = 0

    class TestArgMaxCase7(XPUBaseTestCase):

        def initTestCase(self):
            self.dims = (3, 4)
            self.axis = 1

    class TestArgMaxCase8(XPUBaseTestCase):

        def initTestCase(self):
            self.dims = (1, )
            self.axis = 0

    class TestArgMaxCase9(XPUBaseTestCase):

        def initTestCase(self):
            self.dims = (2, )
            self.axis = 0

    class TestArgMaxCase10(XPUBaseTestCase):

        def initTestCase(self):
            self.dims = (3, )
            self.axis = 0

support_types = get_xpu_op_support_types('arg_max')
for stype in support_types:
    create_test_class(globals(), XPUTestArgMax, stype)

class TestArgMaxAPI(unittest.TestCase):

    def initTestCase(self):
        self.dims = (3, 4, 5)
        self.dtype = 'float32'
        self.axis = 0

    def setUp(self):
        self.initTestCase()
        self.__class__.use_Xpu = True
        self.place = [paddle.XPUPlace(0)]

    def test_dygraph_api(self):

        def run(place):
            paddle.disable_static(place)
            np.random.seed(2021)
            numpy_input = (np.random.random(self.dims)).astype(self.dtype)
            tensor_input = paddle.to_tensor(numpy_input)
            numpy_output = np.argmax(numpy_input, axis=self.axis)
            paddle_output = paddle.argmax(tensor_input, axis=self.axis)
            self.assertEqual(np.allclose(numpy_output, paddle_output.numpy()),
                             True)
            paddle.enable_static()

        for place in self.place:
            run(place)

class TestArgMaxAPI_2(unittest.TestCase):

    def initTestCase(self):
        self.dims = (3, 4, 5)
        self.dtype = 'float32'
        self.axis = 0
        self.keep_dims = True

    def setUp(self):
        self.initTestCase()
        self.__class__.use_xpu = True
        self.place = [paddle.XPUPlace(0)]

    def test_dygraph_api(self):

        def run(place):
            paddle.disable_static(place)
            np.random.seed(2021)
            numpy_input = (np.random.random(self.dims)).astype(self.dtype)
            tensor_input = paddle.to_tensor(numpy_input)
            numpy_output = np.argmax(numpy_input,
                                     axis=self.axis).reshape(1, 4, 5)
            paddle_output = paddle.argmax(tensor_input,
                                          axis=self.axis,
                                          keepdim=self.keep_dims)
            self.assertEqual(np.allclose(numpy_output, paddle_output.numpy()),
                             True)
            self.assertEqual(numpy_output.shape, paddle_output.numpy().shape)
            paddle.enable_static()

        for place in self.place:
            run(place)

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


"""
Cleaning Data VII - View Null Values
"""

import numpy as np
import pandas as pd
wine_reviews = pd.read_csv('../winemag-data-130k.csv')
wine_reviews.rename(columns={'points': 'rating'}, inplace=True)

# Use the below df for these problems:

wine_ratings = wine_reviews[['title', 'country', 'rating', 'price']]

# Return a dataframe of booleans that show True for null values.

# Return a dataframe of booleans that show True for values that exist.