# Convention for import to get shortened namespace
import numpy as np

# Create a simple array from a list of integers
a = np.array([1, 2, 3])
a

# See how many dimensions the array has
a.ndim

# Print out the shape attribute
a.shape

# Print out the data type attribute
a.dtype

# This time use a nested list of floats
a = np.array([[1., 2., 3., 4., 5.]])
a

# See how many dimensions the array has
a.ndim

# Print out the shape attribute
a.shape

# Print out the data type attribute
a.dtype

"""
Explanation: <div style="width:1000 px">

<div style="float:right; width:98 px; height:98px;">
<img src="https://raw.githubusercontent.com/Unidata/MetPy/master/metpy/plots/_static/unidata_150x150.png" alt="Unidata Logo" style="height: 98px;">
</div>

<h1>NumPy Basics</h1>
<h3>Unidata Python Workshop</h3>

<div style="clear:both"></div>
</div>

<hr style="height:2px;">

<div style="float:right; width:250 px"><img src="http://www.contribute.geeksforgeeks.org/wp-content/uploads/numpy-logo1.jpg" alt="NumPy Logo" style="height: 250px;"></div>

Overview:

Teaching: 15 minutes
Exercises: 10 minutes

Questions

What are arrays?
How can arrays be manipulated effectively in Python?

Objectives

Create an array of ‘data’.
Perform basic calculations on this data using python math functions.
Slice and index the array

NumPy is the fundamental package for scientific computing with Python. It contains among other things:
- a powerful N-dimensional array object
- sophisticated (broadcasting) functions
- useful linear algebra, Fourier transform, and random number capabilities
The NumPy array object is the common interface for working with typed arrays of data across a wide-variety of scientific Python packages. NumPy also features a C-API, which enables interfacing existing Fortran/C/C++ libraries with Python and NumPy.
Create an array of 'data'
The NumPy array represents a contiguous block of memory, holding entries of a given type (and hence fixed size). The entries are laid out in memory according to the shape, or list of dimension sizes.
End of explanation
"""


a = np.arange(5)
print(a)

a = np.arange(3, 11)
print(a)

a = np.arange(1, 10, 2)
print(a)

"""
Explanation: <div class="alert alert-warning">
<h2>Poll</h2>
Please go to <a href="http://www.PollEv.com/johnleeman205">http://www.PollEv.com/johnleeman205</a> to take a quick poll.
</div>

NumPy also provides helper functions for generating arrays of data to save you typing for regularly spaced data. 

arange(start, stop, interval) creates a range of values in the interval [start,stop) with step spacing.
linspace(start, stop, num) creates a range of num evenly spaced values over the range [start,stop].

arange
End of explanation
"""


b = np.linspace(5, 15, 5)
print(b)

b = np.linspace(2.5, 10.25, 11)
print(b)

"""
Explanation: <div class="alert alert-warning">
<h2>Poll</h2>
Please go to <a href="http://www.PollEv.com/johnleeman205">http://www.PollEv.com/johnleeman205</a> to take a quick poll.
</div>

linspace
End of explanation
"""


a = range(5, 10)
b = [3 + i * 1.5/4 for i in range(5)]

result = []
for x, y in zip(a, b):
    result.append(x + y)
print(result)

"""
Explanation: <div class="alert alert-warning">
<h2>Poll</h2>
Please go to <a href="http://www.PollEv.com/johnleeman205">http://www.PollEv.com/johnleeman205</a> to take a quick poll.
</div>

Perform basic calculations with Python
Basic math
In core Python, that is without NumPy, creating sequences of values and adding them together requires writing a lot of manual loops, just like one would do in C/C++:
End of explanation
"""


a = np.arange(5, 10)
b = np.linspace(3, 4.5, 5)

a + b

"""
Explanation: That is very verbose and not very intuitive. Using NumPy this becomes:
End of explanation
"""


a * b

"""
Explanation: The four major mathematical operations operate in the same way. They perform an element-by-element calculation of the two arrays. The two must be the same shape though!
End of explanation
"""


np.pi

np.e

# This makes working with radians effortless!
t = np.arange(0, 2 * np.pi + np.pi / 4, np.pi / 4)
t

"""
Explanation: Constants
NumPy proves us access to some useful constants as well - remember you should never be typing these in manually! Other libraries such as SciPy and MetPy have their own set of constants that are more domain specific.
End of explanation
"""


# Calculate the sine function
sin_t = np.sin(t)
print(sin_t)

# Round to three decimal places
print(np.round(sin_t, 3))

# Calculate the cosine function
cos_t = np.cos(t)
print(cos_t)

# Convert radians to degrees
degrees = np.rad2deg(t)
print(degrees)

# Integrate the sine function with the trapezoidal rule
sine_integral = np.trapz(sin_t, t)
print(np.round(sine_integral, 3))

# Sum the values of the cosine
cos_sum = np.sum(cos_t)
print(cos_sum)

# Calculate the cumulative sum of the cosine
cos_csum = np.cumsum(cos_t)
print(cos_csum)

"""
Explanation: Array math functions
NumPy also has math functions that can operate on arrays. Similar to the math operations, these greatly simplify and speed up these operations. Be sure to checkout the listing of mathematical functions in the NumPy documentation.
End of explanation
"""


# Create an array for testing
a = np.arange(12).reshape(3, 4)

a

"""
Explanation: Index and slice arrays
Indexing is how we pull individual data items out of an array. Slicing extends this process to pulling out a regular set of the items.
End of explanation
"""


a[1, 2]

"""
Explanation: Indexing in Python is 0-based, so the command below looks for the 2nd item along the first dimension (row) and the 3rd along the second dimension (column).
End of explanation
"""


a[2]

"""
Explanation: Can also just index on one dimension
End of explanation
"""


a[0, -1]

"""
Explanation: Negative indices are also allowed, which permit indexing relative to the end of the array.
End of explanation
"""


# Get the 2nd and 3rd rows
a[1:3]

# All rows and 3rd column
a[:, 2]

# ... can be used to replace one or more full slices
a[..., 2]

# Slice every other row
a[::2]

"""
Explanation: <div class="alert alert-warning">
<h2>Poll</h2>
Please go to <a href="http://www.PollEv.com/johnleeman205">http://www.PollEv.com/johnleeman205</a> to take a quick poll.
</div>

Slicing syntax is written as start:stop[:step], where all numbers are optional.
- defaults: 
  - start = 0
  - stop = len(dim)
  - step = 1
- The second colon is also optional if no step is used.
It should be noted that end represents one past the last item; one can also think of it as a half open interval: [start, end)
End of explanation
"""


data = [1, 3, 5, 7, 9, 11]
out = []

# Look carefully at the loop. Think carefully about the sequence of values
# that data[i] takes--is there some way to get those values as a numpy slice?
# What about for data[i + 1]?
for i in range(len(data) - 1):
    out.append((data[i] + data[i + 1]) / 2)

print(out)

# Your code goes here


# %load solutions/slice.py

# Your code goes here


# %load solutions/slice_bonus.py

"""
Explanation: <div class="alert alert-warning">
<h2>Poll</h2>
Please go to <a href="http://www.PollEv.com/johnleeman205">http://www.PollEv.com/johnleeman205</a> to take a quick poll.
</div>

<div class="alert alert-success">
    <b>EXERCISE</b>:
     <ul>
      <li>The code below calculates a two point average using a Python list and loop. Convert it do obtain the same results using NumPy slicing</li>
    <li>Bonus points: Can you extend the NumPy version to do a 3 point (running) average?</li>
    </ul>
</div>
End of explanation
"""


data = np.arange(12).reshape(3, 4)

# Your code goes here
# total = ?

# %load solutions/sum_row.py

"""
Explanation: <div class="alert alert-success">
    <b>EXERCISE</b>:
     <ul>
      <li>Given the array of data below, calculate the total of each of the columns (i.e. add each of the three rows together):</li>
    </ul>
</div>
End of explanation
"""


