import pandas as pd
df = pd.read_csv('data/iris.csv')
df.head()

df.groupby(df.Species).PetalLength.mean()  # Average petal length per species

"""
Explanation: <img src=images/continuum_analytics_b&w.png align="left" width="15%" style="margin-right:15%">
<h1 align='center'>Introduction to Blaze</h1>

In this tutorial we'll learn how to use Blaze to discover, migrate, and query data living in other databases.  Generally this tutorial will have the following format

odo - Move data to database
blaze - Query data in database

Goal: Accessible, Interactive, Analytic Queries
NumPy and Pandas provide accessible, interactive, analytic queries; this is valuable.
End of explanation
"""


from odo import odo
import numpy as np
import pandas as pd

odo("data/iris.csv", pd.DataFrame, index_col=0)

odo("data/iris.csv", list)

odo("data/iris.csv", np.ndarray)

"""
Explanation: <hr/>

But as data grows and systems become more complex, moving data and querying data become more difficult. Python already has excellent tools for data that fits in memory, but we want to hook up to data that is inconvenient.
From now on, we're going to assume one of the following:

You have an inconvenient amount of data
That data should live someplace other than your computer

<hr/>

Databases and Python
When in-memory arrays/dataframes cease to be an option, we turn to databases.  These live outside of the Python process and so might be less convenient.  The open source Python ecosystem includes libraries to interact with these databases and with foreign data in general.  
Examples:

SQL - sqlalchemy 
Hive/Cassandra - pyhive
Impala  - impyla
RedShift - redshift-sqlalchemy
...


MongoDB - pymongo
HBase - happybase
Spark - pyspark
SSH - paramiko
HDFS - pywebhdfs
Amazon S3 - boto

Today we're going to use some of these indirectly with odo (was into) and Blaze.  We'll try to point out these libraries as we automate them so that, if you'd like, you can use them independently.
<hr />

odo (formerly into)
Odo migrates data between formats and locations.
Before we can use a database we need to move data into it.  The odo project provides a single consistent interface to move data between formats and between locations.
We'll start with local data and eventually move out to remote data.
odo docs
<hr/>

Examples
Odo moves data into a target from a source
```python



odo(source, target)
```



The target and source can be either a Python object or a string URI.  The following are all valid calls to into
```python



odo('iris.csv', pd.DataFrame)  # Load CSV file into new DataFrame
odo(my_df, 'iris.json')        # Write DataFrame into JSON file
odo('iris.csv', 'iris.json')   # Migrate data from CSV to JSON
```



<hr/>

Exercise
Use odo to load the iris.csv file into a Python list, a np.ndarray, and a pd.DataFrame
End of explanation
"""


odo("data/iris.csv", "sqlite:///my.db::iris")

"""
Explanation: <hr/>

URI Strings
Odo refers to foreign data either with a Python object like a sqlalchemy.Table object for a SQL table, or with a string URI, like postgresql://hostname::tablename.
URI's often take on the following form
protocol://path-to-resource::path-within-resource

Where path-to-resource might point to a file, a database hostname, etc. while path-within-resource might refer to a datapath or table name.  Note the two main separators

:// separates the protocol on the left (sqlite, mongodb, ssh, hdfs, hive, ...)
:: separates the path within the database on the right (e.g. tablename)

odo docs on uri strings
<hr/>

Examples
Here are some example URIs
myfile.json
myfiles.*.csv'
postgresql://hostname::tablename
mongodb://hostname/db::collection
ssh://user@host:/path/to/myfile.csv
hdfs://user@host:/path/to/*.csv
<hr />

Exercise
Migrate your CSV file into a table named iris in a new SQLite database at sqlite:///my.db.  Remember to use the :: separator and to separate your database name from your table name.
odo docs on SQL
End of explanation
"""


type(_)

"""
Explanation: What kind of object did you get receive as output?  Call type on your result.
End of explanation
"""


odo('s3://nyqpug/tips.csv', pd.DataFrame)

"""
Explanation: <hr/>

How it works
Odo is a network of fast pairwise conversions between pairs of formats.  We when we migrate between two formats we traverse a path of pairwise conversions.
We visualize that network below:

Each node represents a data format. Each directed edge represents a function to transform data between two formats. A single call to into may traverse multiple edges and multiple intermediate formats. Red nodes support larger-than-memory data.
A single call to into may traverse several intermediate formats calling on several conversion functions.   For example, we when migrate a CSV file to a Mongo database we might take the following route:

Load in to a DataFrame (pandas.read_csv)
Convert to np.recarray (DataFrame.to_records)
Then to a Python Iterator (np.ndarray.tolist)
Finally to Mongo (pymongo.Collection.insert)

Alternatively we could write a special function that uses MongoDB's native CSV
loader and shortcut this entire process with a direct edge CSV -&gt; Mongo.
These functions are chosen because they are fast, often far faster than converting through a central serialization format.
This picture is actually from an older version of odo, when the graph was still small enough to visualize pleasantly.  See odo docs for a more updated version.
<hr/>

Remote Data
We can interact with remote data in three locations

On Amazon's S3 (this will be quick)
On a remote machine via ssh
On the Hadoop File System (HDFS)

For most of this we'll wait until we've seen Blaze, briefly we'll use S3.
S3
For now, we quickly grab a file from Amazon's S3.
This example depends on  boto to interact with S3.
conda install boto

odo docs on aws
End of explanation
"""


import pandas as pd

df = pd.read_csv('data/iris.csv')
df.head(5)

df.Species.unique()

df.Species.drop_duplicates()

"""
Explanation: Blaze
Blaze translates a subset of numpy/pandas syntax into database queries.  It hides away the database.
On simple datasets, like CSV files, Blaze acts like Pandas with slightly different syntax.  In this case Blaze is just using Pandas.
<hr/>

Pandas example
End of explanation
"""


import blaze as bz

d = bz.Data('data/iris.csv')
d.head(5)

d.Species.distinct()

"""
Explanation: <hr/>

Blaze example
End of explanation
"""


db = bz.Data('sqlite:///my.db')
#db.iris
#db.iris.head()

db.iris.Species.distinct()

db.iris[db.iris.Species == 'versicolor'][['Species', 'SepalLength']]

"""
Explanation: <hr/>

Foreign Data
Blaze does different things under-the-hood on different kinds of data

CSV files: Pandas DataFrames (or iterators of DataFrames)
SQL tables: SQLAlchemy.
Mongo collections: PyMongo
...

SQL
We'll play with SQL a lot during this tutorial.  Blaze translates your query to SQLAlchemy.  SQLAlchemy then translates to the SQL dialect of your database, your database then executes that query intelligently.

Blaze $\rightarrow$ SQLAlchemy $\rightarrow$ SQL $\rightarrow$ Database computation

This translation process lets analysts interact with a familiar interface while leveraging a potentially powerful database.
To keep things local we'll use SQLite, but this works with any database with a SQLAlchemy dialect.  Examples in this section use the iris dataset.  Exercises use the Lahman Baseball statistics database, year 2013.
If you have not downloaded this dataset you could do so here - https://github.com/jknecht/baseball-archive-sqlite/raw/master/lahman2013.sqlite.  
<hr/>

Examples
Lets dive into Blaze Syntax.  For simple queries it looks and feels similar to Pandas
End of explanation
"""


# Inspect SQL query
query = db.iris[db.iris.Species == 'versicolor'][['Species', 'SepalLength']]
print bz.compute(query)

query = bz.by(db.iris.Species, longest=db.iris.PetalLength.max(),
                              shortest=db.iris.PetalLength.min())
print bz.compute(query)

"""
Explanation: <hr />

Work happens on the database
If we were using pandas we would read the table into pandas, then use pandas' fast in-memory algorithms for computation.  Here we translate your query into SQL and then send that query to the database to do the work.

Pandas $\leftarrow_\textrm{data}$ SQL, then Pandas computes
Blaze $\rightarrow_\textrm{query}$ SQL, then database computes

If we want to dive into the internal API we can inspect the query that Blaze transmits.
<hr />
End of explanation
"""


# db = bz.Data('postgresql://postgres:postgres@ec2-54-159-160-163.compute-1.amazonaws.com')  # Use Postgres if you don't have the sqlite file
db = bz.Data('sqlite:///data/lahman2013.sqlite')
db.dshape

# View the Salaries table
t = bz.Data('sqlite:///data/lahman2013.sqlite::Salaries')
t.dshape

# What are the distinct teamIDs in the Salaries table?
t.teamID.distinct()

from odo import odo

odo(t.teamID.distinct(), list)

query = t.teamID.distinct()
print bz.compute(query)

# What is the minimum and maximum yearID in the Salaries table?  
t.yearID.min()

t.yearID.max()

# For the Oakland Athletics (teamID OAK), pick out the playerID, salary, and yearID columns

t[t.teamID=='OAK'][['playerID', 'salary', 'yearID']]

oak = t[t.teamID=='OAK'][['playerID', 'salary', 'yearID']]

oak

odo(oak, 'oak.csv')

# Sort that result by salary.  
# Use the ascending=False keyword argument to the sort function to find the highest paid players

oak.sort('salary',ascending=False)

"""
Explanation: <hr />

Exercises
Now we load the Lahman baseball database and perform similar queries
End of explanation
"""


import pandas as pd
iris = pd.read_csv('data/iris.csv')
iris.groupby('Species').PetalLength.min()

iris = bz.Data('sqlite:///my.db::iris')
bz.by(iris.Species, largest=iris.PetalLength.max(), 
                    smallest=iris.PetalLength.min())
print(_)

"""
Explanation: <hr />

Example: Split-apply-combine
In Pandas we perform computations on a per-group basis with the groupby operator.  In Blaze our syntax is slightly different, using instead the by function.
End of explanation
"""


result = bz.by(db.Salaries.teamID, avg=db.Salaries.salary.mean(), 
                                   max=db.Salaries.salary.max(), 
                                   ratio=db.Salaries.salary.max() / db.Salaries.salary.min()
                ).sort('ratio', ascending=False)

odo(result, list)[:10]

odo(result, 'sqlite:///my.db::result')

"""
Explanation: <hr/>

Store Results
By default Blaze only shows us the first ten lines of a result.  This provides a more interactive feel and stops us from accidentally crushing our system.  Sometimes we do want to compute all of the results and store them someplace.
Blaze expressions are valid sources for odo.  So we can store our results in any format.
<hr/>

Exercise: Storage
The solution to the first split-apply-combine problem is below.  Store that result in a list, a CSV file, and in a new SQL table in our database (use a uri like sqlite://... to specify the SQL table.)
End of explanation
"""


