# -*- coding: utf-8 -*-
# Authors: Olivier Grisel <olivier.grisel@ensta.org>
#          Mathieu Blondel <mathieu@mblondel.org>
#          Lars Buitinck <L.J.Buitinck@uva.nl>
#          Robert Layton <robertlayton@gmail.com>
#          Jochen Wersdörfer <jochen@wersdoerfer.de>
#          Roman Sinayev <roman.sinayev@gmail.com>
#
# License: BSD 3 clause
"""
The :mod:`sklearn.feature_extraction.text` submodule gathers utilities to
build feature vectors from text documents.
"""
from __future__ import unicode_literals

import array
from collections import Mapping, defaultdict
import numbers
from operator import itemgetter
import re
import unicodedata

import numpy as np
import scipy.sparse as sp

from ..base import BaseEstimator, TransformerMixin
from ..externals import six
from ..externals.six.moves import xrange
from ..preprocessing import normalize
from .hashing import FeatureHasher
from .stop_words import ENGLISH_STOP_WORDS
from ..utils import deprecated
from ..utils.fixes import frombuffer_empty, bincount
from ..utils.validation import check_is_fitted

__all__ = ['CountVectorizer',
           'ENGLISH_STOP_WORDS',
           'TfidfTransformer',
           'TfidfVectorizer',
           'strip_accents_ascii',
           'strip_accents_unicode',
           'strip_tags']

def strip_accents_unicode(s):
    """Transform accentuated unicode symbols into their simple counterpart

    Warning: the python-level loop and join operations make this
    implementation 20 times slower than the strip_accents_ascii basic
    normalization.

    See also
    --------
    strip_accents_ascii
        Remove accentuated char for any unicode symbol that has a direct
        ASCII equivalent.
    """
    return ''.join([c for c in unicodedata.normalize('NFKD', s)
                    if not unicodedata.combining(c)])

def strip_accents_ascii(s):
    """Transform accentuated unicode symbols into ascii or nothing

    Warning: this solution is only suited for languages that have a direct
    transliteration to ASCII symbols.

    See also
    --------
    strip_accents_unicode
        Remove accentuated char for any unicode symbol.
    """
    nkfd_form = unicodedata.normalize('NFKD', s)
    return nkfd_form.encode('ASCII', 'ignore').decode('ASCII')

def strip_tags(s):
    """Basic regexp based HTML / XML tag stripper function

    For serious HTML/XML preprocessing you should rather use an external
    library such as lxml or BeautifulSoup.
    """
    return re.compile(r"<([^>]+)>", flags=re.UNICODE).sub(" ", s)

def _check_stop_list(stop):
    if stop == "english":
        return ENGLISH_STOP_WORDS
    elif isinstance(stop, six.string_types):
        raise ValueError("not a built-in stop list: %s" % stop)
    else:               # assume it's a collection
        return stop

class VectorizerMixin(object):
    """Provides common code for text vectorizers (tokenization logic)."""

    _white_spaces = re.compile(r"\s\s+")

    def decode(self, doc):
        """Decode the input into a string of unicode symbols

        The decoding strategy depends on the vectorizer parameters.
        """
        if self.input == 'filename':
            with open(doc, 'rb') as fh:
                doc = fh.read()

        elif self.input == 'file':
            doc = doc.read()

        if isinstance(doc, bytes):
            doc = doc.decode(self.encoding, self.decode_error)

        if doc is np.nan:
            raise ValueError("np.nan is an invalid document, expected byte or "
                             "unicode string.")

        return doc

    def _word_ngrams(self, tokens, stop_words=None):
        """Turn tokens into a sequence of n-grams after stop words filtering"""
        # handle stop words
        if stop_words is not None:
            tokens = [w for w in tokens if w not in stop_words]

        # handle token n-grams
        min_n, max_n = self.ngram_range
        if max_n != 1:
            original_tokens = tokens
            tokens = []
            n_original_tokens = len(original_tokens)
            for n in xrange(min_n,
                            min(max_n + 1, n_original_tokens + 1)):
                for i in xrange(n_original_tokens - n + 1):
                    tokens.append(" ".join(original_tokens[i: i + n]))

        return tokens

    def _char_ngrams(self, text_document):
        """Tokenize text_document into a sequence of character n-grams"""
        # normalize white spaces
        text_document = self._white_spaces.sub(" ", text_document)

        text_len = len(text_document)
        ngrams = []
        min_n, max_n = self.ngram_range
        for n in xrange(min_n, min(max_n + 1, text_len + 1)):
            for i in xrange(text_len - n + 1):
                ngrams.append(text_document[i: i + n])
        return ngrams

    def _char_wb_ngrams(self, text_document):
        """Whitespace sensitive char-n-gram tokenization.

        Tokenize text_document into a sequence of character n-grams
        excluding any whitespace (operating only inside word boundaries)"""
        # normalize white spaces
        text_document = self._white_spaces.sub(" ", text_document)

        min_n, max_n = self.ngram_range
        ngrams = []
        for w in text_document.split():
            w = ' ' + w + ' '
            w_len = len(w)
            for n in xrange(min_n, max_n + 1):
                offset = 0
                ngrams.append(w[offset:offset + n])
                while offset + n < w_len:
                    offset += 1
                    ngrams.append(w[offset:offset + n])
                if offset == 0:   # count a short word (w_len < n) only once
                    break
        return ngrams

    def build_preprocessor(self):
        """Return a function to preprocess the text before tokenization"""
        if self.preprocessor is not None:
            return self.preprocessor

        # unfortunately python functools package does not have an efficient
        # `compose` function that would have allowed us to chain a dynamic
        # number of functions. However the cost of a lambda call is a few
        # hundreds of nanoseconds which is negligible when compared to the
        # cost of tokenizing a string of 1000 chars for instance.
        noop = lambda x: x

        # accent stripping
        if not self.strip_accents:
            strip_accents = noop
        elif callable(self.strip_accents):
            strip_accents = self.strip_accents
        elif self.strip_accents == 'ascii':
            strip_accents = strip_accents_ascii
        elif self.strip_accents == 'unicode':
            strip_accents = strip_accents_unicode
        else:
            raise ValueError('Invalid value for "strip_accents": %s' %
                             self.strip_accents)

        if self.lowercase:
            return lambda x: strip_accents(x.lower())
        else:
            return strip_accents

    def build_tokenizer(self):
        """Return a function that splits a string into a sequence of tokens"""
        if self.tokenizer is not None:
            return self.tokenizer
        token_pattern = re.compile(self.token_pattern)
        return lambda doc: token_pattern.findall(doc)

    def get_stop_words(self):
        """Build or fetch the effective stop words list"""
        return _check_stop_list(self.stop_words)

    def build_analyzer(self):
        """Return a callable that handles preprocessing and tokenization"""
        if callable(self.analyzer):
            return self.analyzer

        preprocess = self.build_preprocessor()

        if self.analyzer == 'char':
            return lambda doc: self._char_ngrams(preprocess(self.decode(doc)))

        elif self.analyzer == 'char_wb':
            return lambda doc: self._char_wb_ngrams(
                preprocess(self.decode(doc)))

        elif self.analyzer == 'word':
            stop_words = self.get_stop_words()
            tokenize = self.build_tokenizer()

            return lambda doc: self._word_ngrams(
                tokenize(preprocess(self.decode(doc))), stop_words)

        else:
            raise ValueError('%s is not a valid tokenization scheme/analyzer' %
                             self.analyzer)

    def _validate_vocabulary(self):
        vocabulary = self.vocabulary
        if vocabulary is not None:
            if not isinstance(vocabulary, Mapping):
                vocab = {}
                for i, t in enumerate(vocabulary):
                    if vocab.setdefault(t, i) != i:
                        msg = "Duplicate term in vocabulary: %r" % t
                        raise ValueError(msg)
                vocabulary = vocab
            else:
                indices = set(six.itervalues(vocabulary))
                if len(indices) != len(vocabulary):
                    raise ValueError("Vocabulary contains repeated indices.")
                for i in xrange(len(vocabulary)):
                    if i not in indices:
                        msg = ("Vocabulary of size %d doesn't contain index "
                               "%d." % (len(vocabulary), i))
                        raise ValueError(msg)
            if not vocabulary:
                raise ValueError("empty vocabulary passed to fit")
            self.fixed_vocabulary_ = True
            self.vocabulary_ = dict(vocabulary)
        else:
            self.fixed_vocabulary_ = False

    def _check_vocabulary(self):
        """Check if vocabulary is empty or missing (not fit-ed)"""
        msg = "%(name)s - Vocabulary wasn't fitted."
        check_is_fitted(self, 'vocabulary_', msg=msg),

        if len(self.vocabulary_) == 0:
            raise ValueError("Vocabulary is empty")

    @property
    @deprecated("The `fixed_vocabulary` attribute is deprecated and will be "
                "removed in 0.18.  Please use `fixed_vocabulary_` instead.")
    def fixed_vocabulary(self):
        return self.fixed_vocabulary_

class HashingVectorizer(BaseEstimator, VectorizerMixin):
    """Convert a collection of text documents to a matrix of token occurrences

    It turns a collection of text documents into a scipy.sparse matrix holding
    token occurrence counts (or binary occurrence information), possibly
    normalized as token frequencies if norm='l1' or projected on the euclidean
    unit sphere if norm='l2'.

    This text vectorizer implementation uses the hashing trick to find the
    token string name to feature integer index mapping.

    This strategy has several advantages:

    - it is very low memory scalable to large datasets as there is no need to
      store a vocabulary dictionary in memory

    - it is fast to pickle and un-pickle as it holds no state besides the
      constructor parameters

    - it can be used in a streaming (partial fit) or parallel pipeline as there
      is no state computed during fit.

    There are also a couple of cons (vs using a CountVectorizer with an
    in-memory vocabulary):

    - there is no way to compute the inverse transform (from feature indices to
      string feature names) which can be a problem when trying to introspect
      which features are most important to a model.

    - there can be collisions: distinct tokens can be mapped to the same
      feature index. However in practice this is rarely an issue if n_features
      is large enough (e.g. 2 ** 18 for text classification problems).

    - no IDF weighting as this would render the transformer stateful.

    The hash function employed is the signed 32-bit version of Murmurhash3.

    Read more in the :ref:`User Guide <text_feature_extraction>`.

    Parameters
    ----------

    input : string {'filename', 'file', 'content'}
        If 'filename', the sequence passed as an argument to fit is
        expected to be a list of filenames that need reading to fetch
        the raw content to analyze.

        If 'file', the sequence items must have a 'read' method (file-like
        object) that is called to fetch the bytes in memory.

        Otherwise the input is expected to be the sequence strings or
        bytes items are expected to be analyzed directly.

    encoding : string, default='utf-8'
        If bytes or files are given to analyze, this encoding is used to
        decode.

    decode_error : {'strict', 'ignore', 'replace'}
        Instruction on what to do if a byte sequence is given to analyze that
        contains characters not of the given `encoding`. By default, it is
        'strict', meaning that a UnicodeDecodeError will be raised. Other
        values are 'ignore' and 'replace'.

    strip_accents : {'ascii', 'unicode', None}
        Remove accents during the preprocessing step.
        'ascii' is a fast method that only works on characters that have
        an direct ASCII mapping.
        'unicode' is a slightly slower method that works on any characters.
        None (default) does nothing.

    analyzer : string, {'word', 'char', 'char_wb'} or callable
        Whether the feature should be made of word or character n-grams.
        Option 'char_wb' creates character n-grams only from text inside
        word boundaries.

        If a callable is passed it is used to extract the sequence of features
        out of the raw, unprocessed input.

    preprocessor : callable or None (default)
        Override the preprocessing (string transformation) stage while
        preserving the tokenizing and n-grams generation steps.

    tokenizer : callable or None (default)
        Override the string tokenization step while preserving the
        preprocessing and n-grams generation steps.
        Only applies if ``analyzer == 'word'``.

    ngram_range : tuple (min_n, max_n), default=(1, 1)
        The lower and upper boundary of the range of n-values for different
        n-grams to be extracted. All values of n such that min_n <= n <= max_n
        will be used.

    stop_words : string {'english'}, list, or None (default)
        If 'english', a built-in stop word list for English is used.

        If a list, that list is assumed to contain stop words, all of which
        will be removed from the resulting tokens.
        Only applies if ``analyzer == 'word'``.

    lowercase : boolean, default=True
        Convert all characters to lowercase before tokenizing.

    token_pattern : string
        Regular expression denoting what constitutes a "token", only used
        if ``analyzer == 'word'``. The default regexp selects tokens of 2
        or more alphanumeric characters (punctuation is completely ignored
        and always treated as a token separator).

    n_features : integer, default=(2 ** 20)
        The number of features (columns) in the output matrices. Small numbers
        of features are likely to cause hash collisions, but large numbers
        will cause larger coefficient dimensions in linear learners.

    norm : 'l1', 'l2' or None, optional
        Norm used to normalize term vectors. None for no normalization.

    binary: boolean, default=False.
        If True, all non zero counts are set to 1. This is useful for discrete
        probabilistic models that model binary events rather than integer
        counts.

    dtype: type, optional
        Type of the matrix returned by fit_transform() or transform().

    non_negative : boolean, default=False
        Whether output matrices should contain non-negative values only;
        effectively calls abs on the matrix prior to returning it.
        When True, output values can be interpreted as frequencies.
        When False, output values will have expected value zero.

    See also
    --------
    CountVectorizer, TfidfVectorizer

    """
    def __init__(self, input='content', encoding='utf-8',
                 decode_error='strict', strip_accents=None,
                 lowercase=True, preprocessor=None, tokenizer=None,
                 stop_words=None, token_pattern=r"(?u)\b\w\w+\b",
                 ngram_range=(1, 1), analyzer='word', n_features=(2 ** 20),
                 binary=False, norm='l2', non_negative=False,
                 dtype=np.float64):
        self.input = input
        self.encoding = encoding
        self.decode_error = decode_error
        self.strip_accents = strip_accents
        self.preprocessor = preprocessor
        self.tokenizer = tokenizer
        self.analyzer = analyzer
        self.lowercase = lowercase
        self.token_pattern = token_pattern
        self.stop_words = stop_words
        self.n_features = n_features
        self.ngram_range = ngram_range
        self.binary = binary
        self.norm = norm
        self.non_negative = non_negative
        self.dtype = dtype

    def partial_fit(self, X, y=None):
        """Does nothing: this transformer is stateless.

        This method is just there to mark the fact that this transformer
        can work in a streaming setup.

        """
        return self

    def fit(self, X, y=None):
        """Does nothing: this transformer is stateless."""
        # triggers a parameter validation
        self._get_hasher().fit(X, y=y)
        return self

    def transform(self, X, y=None):
        """Transform a sequence of documents to a document-term matrix.

        Parameters
        ----------
        X : iterable over raw text documents, length = n_samples
            Samples. Each sample must be a text document (either bytes or
            unicode strings, file name or file object depending on the
            constructor argument) which will be tokenized and hashed.

        y : (ignored)

        Returns
        -------
        X : scipy.sparse matrix, shape = (n_samples, self.n_features)
            Document-term matrix.

        """
        analyzer = self.build_analyzer()
        X = self._get_hasher().transform(analyzer(doc) for doc in X)
        if self.binary:
            X.data.fill(1)
        if self.norm is not None:
            X = normalize(X, norm=self.norm, copy=False)
        return X

    # Alias transform to fit_transform for convenience
    fit_transform = transform

    def _get_hasher(self):
        return FeatureHasher(n_features=self.n_features,
                             input_type='string', dtype=self.dtype,
                             non_negative=self.non_negative)

def _document_frequency(X):
    """Count the number of non-zero values for each feature in sparse X."""
    if sp.isspmatrix_csr(X):
        return bincount(X.indices, minlength=X.shape[1])
    else:
        return np.diff(sp.csc_matrix(X, copy=False).indptr)

class CountVectorizer(BaseEstimator, VectorizerMixin):
    """Convert a collection of text documents to a matrix of token counts

    This implementation produces a sparse representation of the counts using
    scipy.sparse.coo_matrix.

    If you do not provide an a-priori dictionary and you do not use an analyzer
    that does some kind of feature selection then the number of features will
    be equal to the vocabulary size found by analyzing the data.

    Read more in the :ref:`User Guide <text_feature_extraction>`.

    Parameters
    ----------
    input : string {'filename', 'file', 'content'}
        If 'filename', the sequence passed as an argument to fit is
        expected to be a list of filenames that need reading to fetch
        the raw content to analyze.

        If 'file', the sequence items must have a 'read' method (file-like
        object) that is called to fetch the bytes in memory.

        Otherwise the input is expected to be the sequence strings or
        bytes items are expected to be analyzed directly.

    encoding : string, 'utf-8' by default.
        If bytes or files are given to analyze, this encoding is used to
        decode.

    decode_error : {'strict', 'ignore', 'replace'}
        Instruction on what to do if a byte sequence is given to analyze that
        contains characters not of the given `encoding`. By default, it is
        'strict', meaning that a UnicodeDecodeError will be raised. Other
        values are 'ignore' and 'replace'.

    strip_accents : {'ascii', 'unicode', None}
        Remove accents during the preprocessing step.
        'ascii' is a fast method that only works on characters that have
        an direct ASCII mapping.
        'unicode' is a slightly slower method that works on any characters.
        None (default) does nothing.

    analyzer : string, {'word', 'char', 'char_wb'} or callable
        Whether the feature should be made of word or character n-grams.
        Option 'char_wb' creates character n-grams only from text inside
        word boundaries.

        If a callable is passed it is used to extract the sequence of features
        out of the raw, unprocessed input.
        Only applies if ``analyzer == 'word'``.

    preprocessor : callable or None (default)
        Override the preprocessing (string transformation) stage while
        preserving the tokenizing and n-grams generation steps.

    tokenizer : callable or None (default)
        Override the string tokenization step while preserving the
        preprocessing and n-grams generation steps.
        Only applies if ``analyzer == 'word'``.

    ngram_range : tuple (min_n, max_n)
        The lower and upper boundary of the range of n-values for different
        n-grams to be extracted. All values of n such that min_n <= n <= max_n
        will be used.

    stop_words : string {'english'}, list, or None (default)
        If 'english', a built-in stop word list for English is used.

        If a list, that list is assumed to contain stop words, all of which
        will be removed from the resulting tokens.
        Only applies if ``analyzer == 'word'``.

        If None, no stop words will be used. max_df can be set to a value
        in the range [0.7, 1.0) to automatically detect and filter stop
        words based on intra corpus document frequency of terms.

    lowercase : boolean, True by default
        Convert all characters to lowercase before tokenizing.

    token_pattern : string
        Regular expression denoting what constitutes a "token", only used
        if ``analyzer == 'word'``. The default regexp select tokens of 2
        or more alphanumeric characters (punctuation is completely ignored
        and always treated as a token separator).

    max_df : float in range [0.0, 1.0] or int, default=1.0
        When building the vocabulary ignore terms that have a document
        frequency strictly higher than the given threshold (corpus-specific
        stop words).
        If float, the parameter represents a proportion of documents, integer
        absolute counts.
        This parameter is ignored if vocabulary is not None.

    min_df : float in range [0.0, 1.0] or int, default=1
        When building the vocabulary ignore terms that have a document
        frequency strictly lower than the given threshold. This value is also
        called cut-off in the literature.
        If float, the parameter represents a proportion of documents, integer
        absolute counts.
        This parameter is ignored if vocabulary is not None.

    max_features : int or None, default=None
        If not None, build a vocabulary that only consider the top
        max_features ordered by term frequency across the corpus.

        This parameter is ignored if vocabulary is not None.

    vocabulary : Mapping or iterable, optional
        Either a Mapping (e.g., a dict) where keys are terms and values are
        indices in the feature matrix, or an iterable over terms. If not
        given, a vocabulary is determined from the input documents. Indices
        in the mapping should not be repeated and should not have any gap
        between 0 and the largest index.

    binary : boolean, default=False
        If True, all non zero counts are set to 1. This is useful for discrete
        probabilistic models that model binary events rather than integer
        counts.

    dtype : type, optional
        Type of the matrix returned by fit_transform() or transform().

    Attributes
    ----------
    vocabulary_ : dict
        A mapping of terms to feature indices.

    stop_words_ : set
        Terms that were ignored because they either:

          - occurred in too many documents (`max_df`)
          - occurred in too few documents (`min_df`)
          - were cut off by feature selection (`max_features`).

        This is only available if no vocabulary was given.

    See also
    --------
    HashingVectorizer, TfidfVectorizer

    Notes
    -----
    The ``stop_words_`` attribute can get large and increase the model size
    when pickling. This attribute is provided only for introspection and can
    be safely removed using delattr or set to None before pickling.
    """

    def __init__(self, input='content', encoding='utf-8',
                 decode_error='strict', strip_accents=None,
                 lowercase=True, preprocessor=None, tokenizer=None,
                 stop_words=None, token_pattern=r"(?u)\b\w\w+\b",
                 ngram_range=(1, 1), analyzer='word',
                 max_df=1.0, min_df=1, max_features=None,
                 vocabulary=None, binary=False, dtype=np.int64):
        self.input = input
        self.encoding = encoding
        self.decode_error = decode_error
        self.strip_accents = strip_accents
        self.preprocessor = preprocessor
        self.tokenizer = tokenizer
        self.analyzer = analyzer
        self.lowercase = lowercase
        self.token_pattern = token_pattern
        self.stop_words = stop_words
        self.max_df = max_df
        self.min_df = min_df
        if max_df < 0 or min_df < 0:
            raise ValueError("negative value for max_df of min_df")
        self.max_features = max_features
        if max_features is not None:
            if (not isinstance(max_features, numbers.Integral) or
                    max_features <= 0):
                raise ValueError(
                    "max_features=%r, neither a positive integer nor None"
                    % max_features)
        self.ngram_range = ngram_range
        self.vocabulary = vocabulary
        self.binary = binary
        self.dtype = dtype

    def _sort_features(self, X, vocabulary):
        """Sort features by name

        Returns a reordered matrix and modifies the vocabulary in place
        """
        sorted_features = sorted(six.iteritems(vocabulary))
        map_index = np.empty(len(sorted_features), dtype=np.int32)
        for new_val, (term, old_val) in enumerate(sorted_features):
            map_index[new_val] = old_val
            vocabulary[term] = new_val
        return X[:, map_index]

    def _limit_features(self, X, vocabulary, high=None, low=None,
                        limit=None):
        """Remove too rare or too common features.

        Prune features that are non zero in more samples than high or less
        documents than low, modifying the vocabulary, and restricting it to
        at most the limit most frequent.

        This does not prune samples with zero features.
        """
        if high is None and low is None and limit is None:
            return X, set()

        # Calculate a mask based on document frequencies
        dfs = _document_frequency(X)
        tfs = np.asarray(X.sum(axis=0)).ravel()
        mask = np.ones(len(dfs), dtype=bool)
        if high is not None:
            mask &= dfs <= high
        if low is not None:
            mask &= dfs >= low
        if limit is not None and mask.sum() > limit:
            mask_inds = (-tfs[mask]).argsort()[:limit]
            new_mask = np.zeros(len(dfs), dtype=bool)
            new_mask[np.where(mask)[0][mask_inds]] = True
            mask = new_mask

        new_indices = np.cumsum(mask) - 1  # maps old indices to new
        removed_terms = set()
        for term, old_index in list(six.iteritems(vocabulary)):
            if mask[old_index]:
                vocabulary[term] = new_indices[old_index]
            else:
                del vocabulary[term]
                removed_terms.add(term)
        kept_indices = np.where(mask)[0]
        if len(kept_indices) == 0:
            raise ValueError("After pruning, no terms remain. Try a lower"
                             " min_df or a higher max_df.")
        return X[:, kept_indices], removed_terms

    def _count_vocab(self, raw_documents, fixed_vocab):
        """Create sparse feature matrix, and vocabulary where fixed_vocab=False
        """
        if fixed_vocab:
            vocabulary = self.vocabulary_
        else:
            # Add a new value when a new vocabulary item is seen
            vocabulary = defaultdict()
            vocabulary.default_factory = vocabulary.__len__

        analyze = self.build_analyzer()
        j_indices = _make_int_array()
        indptr = _make_int_array()
        indptr.append(0)
        for doc in raw_documents:
            for feature in analyze(doc):
                try:
                    j_indices.append(vocabulary[feature])
                except KeyError:
                    # Ignore out-of-vocabulary items for fixed_vocab=True
                    continue
            indptr.append(len(j_indices))

        if not fixed_vocab:
            # disable defaultdict behaviour
            vocabulary = dict(vocabulary)
            if not vocabulary:
                raise ValueError("empty vocabulary; perhaps the documents only"
                                 " contain stop words")

        j_indices = frombuffer_empty(j_indices, dtype=np.intc)
        indptr = np.frombuffer(indptr, dtype=np.intc)
        values = np.ones(len(j_indices))

        X = sp.csr_matrix((values, j_indices, indptr),
                          shape=(len(indptr) - 1, len(vocabulary)),
                          dtype=self.dtype)
        X.sum_duplicates()
        return vocabulary, X

    def fit(self, raw_documents, y=None):
        """Learn a vocabulary dictionary of all tokens in the raw documents.

        Parameters
        ----------
        raw_documents : iterable
            An iterable which yields either str, unicode or file objects.

        Returns
        -------
        self
        """
        self.fit_transform(raw_documents)
        return self

    def fit_transform(self, raw_documents, y=None):
        """Learn the vocabulary dictionary and return term-document matrix.

        This is equivalent to fit followed by transform, but more efficiently
        implemented.

        Parameters
        ----------
        raw_documents : iterable
            An iterable which yields either str, unicode or file objects.

        Returns
        -------
        X : array, [n_samples, n_features]
            Document-term matrix.
        """
        # We intentionally don't call the transform method to make
        # fit_transform overridable without unwanted side effects in
        # TfidfVectorizer.
        self._validate_vocabulary()
        max_df = self.max_df
        min_df = self.min_df
        max_features = self.max_features

        vocabulary, X = self._count_vocab(raw_documents,
                                          self.fixed_vocabulary_)

        if self.binary:
            X.data.fill(1)

        if not self.fixed_vocabulary_:
            X = self._sort_features(X, vocabulary)

            n_doc = X.shape[0]
            max_doc_count = (max_df
                             if isinstance(max_df, numbers.Integral)
                             else max_df * n_doc)
            min_doc_count = (min_df
                             if isinstance(min_df, numbers.Integral)
                             else min_df * n_doc)
            if max_doc_count < min_doc_count:
                raise ValueError(
                    "max_df corresponds to < documents than min_df")
            X, self.stop_words_ = self._limit_features(X, vocabulary,
                                                       max_doc_count,
                                                       min_doc_count,
                                                       max_features)

            self.vocabulary_ = vocabulary

        return X

    def transform(self, raw_documents):
        """Transform documents to document-term matrix.

        Extract token counts out of raw text documents using the vocabulary
        fitted with fit or the one provided to the constructor.

        Parameters
        ----------
        raw_documents : iterable
            An iterable which yields either str, unicode or file objects.

        Returns
        -------
        X : sparse matrix, [n_samples, n_features]
            Document-term matrix.
        """
        if not hasattr(self, 'vocabulary_'):
            self._validate_vocabulary()

        self._check_vocabulary()

        # use the same matrix-building strategy as fit_transform
        _, X = self._count_vocab(raw_documents, fixed_vocab=True)
        if self.binary:
            X.data.fill(1)
        return X

    def inverse_transform(self, X):
        """Return terms per document with nonzero entries in X.

        Parameters
        ----------
        X : {array, sparse matrix}, shape = [n_samples, n_features]

        Returns
        -------
        X_inv : list of arrays, len = n_samples
            List of arrays of terms.
        """
        self._check_vocabulary()

        if sp.issparse(X):
            # We need CSR format for fast row manipulations.
            X = X.tocsr()
        else:
            # We need to convert X to a matrix, so that the indexing
            # returns 2D objects
            X = np.asmatrix(X)
        n_samples = X.shape[0]

        terms = np.array(list(self.vocabulary_.keys()))
        indices = np.array(list(self.vocabulary_.values()))
        inverse_vocabulary = terms[np.argsort(indices)]

        return [inverse_vocabulary[X[i, :].nonzero()[1]].ravel()
                for i in range(n_samples)]

    def get_feature_names(self):
        """Array mapping from feature integer indices to feature name"""
        self._check_vocabulary()

        return [t for t, i in sorted(six.iteritems(self.vocabulary_),
                                     key=itemgetter(1))]

def _make_int_array():
    """Construct an array.array of a type suitable for scipy.sparse indices."""
    return array.array(str("i"))

class TfidfTransformer(BaseEstimator, TransformerMixin):
    """Transform a count matrix to a normalized tf or tf-idf representation

    Tf means term-frequency while tf-idf means term-frequency times inverse
    document-frequency. This is a common term weighting scheme in information
    retrieval, that has also found good use in document classification.

    The goal of using tf-idf instead of the raw frequencies of occurrence of a
    token in a given document is to scale down the impact of tokens that occur
    very frequently in a given corpus and that are hence empirically less
    informative than features that occur in a small fraction of the training
    corpus.

    The actual formula used for tf-idf is tf * (idf + 1) = tf + tf * idf,
    instead of tf * idf. The effect of this is that terms with zero idf, i.e.
    that occur in all documents of a training set, will not be entirely
    ignored. The formulas used to compute tf and idf depend on parameter
    settings that correspond to the SMART notation used in IR, as follows:

    Tf is "n" (natural) by default, "l" (logarithmic) when sublinear_tf=True.
    Idf is "t" when use_idf is given, "n" (none) otherwise.
    Normalization is "c" (cosine) when norm='l2', "n" (none) when norm=None.

    Read more in the :ref:`User Guide <text_feature_extraction>`.

    Parameters
    ----------
    norm : 'l1', 'l2' or None, optional
        Norm used to normalize term vectors. None for no normalization.

    use_idf : boolean, default=True
        Enable inverse-document-frequency reweighting.

    smooth_idf : boolean, default=True
        Smooth idf weights by adding one to document frequencies, as if an
        extra document was seen containing every term in the collection
        exactly once. Prevents zero divisions.

    sublinear_tf : boolean, default=False
        Apply sublinear tf scaling, i.e. replace tf with 1 + log(tf).

    References
    ----------

    .. [Yates2011] `R. Baeza-Yates and B. Ribeiro-Neto (2011). Modern
                   Information Retrieval. Addison Wesley, pp. 68-74.`

    .. [MRS2008] `C.D. Manning, P. Raghavan and H. Schuetze  (2008).
                   Introduction to Information Retrieval. Cambridge University
                   Press, pp. 118-120.`
    """

    def __init__(self, norm='l2', use_idf=True, smooth_idf=True,
                 sublinear_tf=False):
        self.norm = norm
        self.use_idf = use_idf
        self.smooth_idf = smooth_idf
        self.sublinear_tf = sublinear_tf

    def fit(self, X, y=None):
        """Learn the idf vector (global term weights)

        Parameters
        ----------
        X : sparse matrix, [n_samples, n_features]
            a matrix of term/token counts
        """
        if not sp.issparse(X):
            X = sp.csc_matrix(X)
        if self.use_idf:
            n_samples, n_features = X.shape
            df = _document_frequency(X)

            # perform idf smoothing if required
            df += int(self.smooth_idf)
            n_samples += int(self.smooth_idf)

            # log+1 instead of log makes sure terms with zero idf don't get
            # suppressed entirely.
            idf = np.log(float(n_samples) / df) + 1.0
            self._idf_diag = sp.spdiags(idf,
                                        diags=0, m=n_features, n=n_features)

        return self

    def transform(self, X, copy=True):
        """Transform a count matrix to a tf or tf-idf representation

        Parameters
        ----------
        X : sparse matrix, [n_samples, n_features]
            a matrix of term/token counts

        copy : boolean, default True
            Whether to copy X and operate on the copy or perform in-place
            operations.

        Returns
        -------
        vectors : sparse matrix, [n_samples, n_features]
        """
        if hasattr(X, 'dtype') and np.issubdtype(X.dtype, np.float):
            # preserve float family dtype
            X = sp.csr_matrix(X, copy=copy)
        else:
            # convert counts or binary occurrences to floats
            X = sp.csr_matrix(X, dtype=np.float64, copy=copy)

        n_samples, n_features = X.shape

        if self.sublinear_tf:
            np.log(X.data, X.data)
            X.data += 1

        if self.use_idf:
            check_is_fitted(self, '_idf_diag', 'idf vector is not fitted')

            expected_n_features = self._idf_diag.shape[0]
            if n_features != expected_n_features:
                raise ValueError("Input has n_features=%d while the model"
                                 " has been trained with n_features=%d" % (
                                     n_features, expected_n_features))
            # *= doesn't work
            X = X * self._idf_diag

        if self.norm:
            X = normalize(X, norm=self.norm, copy=False)

        return X

    @property
    def idf_(self):
        if hasattr(self, "_idf_diag"):
            return np.ravel(self._idf_diag.sum(axis=0))
        else:
            return None

class TfidfVectorizer(CountVectorizer):
    """Convert a collection of raw documents to a matrix of TF-IDF features.

    Equivalent to CountVectorizer followed by TfidfTransformer.

    Read more in the :ref:`User Guide <text_feature_extraction>`.

    Parameters
    ----------
    input : string {'filename', 'file', 'content'}
        If 'filename', the sequence passed as an argument to fit is
        expected to be a list of filenames that need reading to fetch
        the raw content to analyze.

        If 'file', the sequence items must have a 'read' method (file-like
        object) that is called to fetch the bytes in memory.

        Otherwise the input is expected to be the sequence strings or
        bytes items are expected to be analyzed directly.

    encoding : string, 'utf-8' by default.
        If bytes or files are given to analyze, this encoding is used to
        decode.

    decode_error : {'strict', 'ignore', 'replace'}
        Instruction on what to do if a byte sequence is given to analyze that
        contains characters not of the given `encoding`. By default, it is
        'strict', meaning that a UnicodeDecodeError will be raised. Other
        values are 'ignore' and 'replace'.

    strip_accents : {'ascii', 'unicode', None}
        Remove accents during the preprocessing step.
        'ascii' is a fast method that only works on characters that have
        an direct ASCII mapping.
        'unicode' is a slightly slower method that works on any characters.
        None (default) does nothing.

    analyzer : string, {'word', 'char'} or callable
        Whether the feature should be made of word or character n-grams.

        If a callable is passed it is used to extract the sequence of features
        out of the raw, unprocessed input.

    preprocessor : callable or None (default)
        Override the preprocessing (string transformation) stage while
        preserving the tokenizing and n-grams generation steps.

    tokenizer : callable or None (default)
        Override the string tokenization step while preserving the
        preprocessing and n-grams generation steps.
        Only applies if ``analyzer == 'word'``.

    ngram_range : tuple (min_n, max_n)
        The lower and upper boundary of the range of n-values for different
        n-grams to be extracted. All values of n such that min_n <= n <= max_n
        will be used.

    stop_words : string {'english'}, list, or None (default)
        If a string, it is passed to _check_stop_list and the appropriate stop
        list is returned. 'english' is currently the only supported string
        value.

        If a list, that list is assumed to contain stop words, all of which
        will be removed from the resulting tokens.
        Only applies if ``analyzer == 'word'``.

        If None, no stop words will be used. max_df can be set to a value
        in the range [0.7, 1.0) to automatically detect and filter stop
        words based on intra corpus document frequency of terms.

    lowercase : boolean, default True
        Convert all characters to lowercase before tokenizing.

    token_pattern : string
        Regular expression denoting what constitutes a "token", only used
        if ``analyzer == 'word'``. The default regexp selects tokens of 2
        or more alphanumeric characters (punctuation is completely ignored
        and always treated as a token separator).

    max_df : float in range [0.0, 1.0] or int, default=1.0
        When building the vocabulary ignore terms that have a document
        frequency strictly higher than the given threshold (corpus-specific
        stop words).
        If float, the parameter represents a proportion of documents, integer
        absolute counts.
        This parameter is ignored if vocabulary is not None.

    min_df : float in range [0.0, 1.0] or int, default=1
        When building the vocabulary ignore terms that have a document
        frequency strictly lower than the given threshold. This value is also
        called cut-off in the literature.
        If float, the parameter represents a proportion of documents, integer
        absolute counts.
        This parameter is ignored if vocabulary is not None.

    max_features : int or None, default=None
        If not None, build a vocabulary that only consider the top
        max_features ordered by term frequency across the corpus.

        This parameter is ignored if vocabulary is not None.

    vocabulary : Mapping or iterable, optional
        Either a Mapping (e.g., a dict) where keys are terms and values are
        indices in the feature matrix, or an iterable over terms. If not
        given, a vocabulary is determined from the input documents.

    binary : boolean, default=False
        If True, all non-zero term counts are set to 1. This does not mean
        outputs will have only 0/1 values, only that the tf term in tf-idf
        is binary. (Set idf and normalization to False to get 0/1 outputs.)

    dtype : type, optional
        Type of the matrix returned by fit_transform() or transform().

    norm : 'l1', 'l2' or None, optional
        Norm used to normalize term vectors. None for no normalization.

    use_idf : boolean, default=True
        Enable inverse-document-frequency reweighting.

    smooth_idf : boolean, default=True
        Smooth idf weights by adding one to document frequencies, as if an
        extra document was seen containing every term in the collection
        exactly once. Prevents zero divisions.

    sublinear_tf : boolean, default=False
        Apply sublinear tf scaling, i.e. replace tf with 1 + log(tf).

    Attributes
    ----------
    idf_ : array, shape = [n_features], or None
        The learned idf vector (global term weights)
        when ``use_idf`` is set to True, None otherwise.

    stop_words_ : set
        Terms that were ignored because they either:

          - occurred in too many documents (`max_df`)
          - occurred in too few documents (`min_df`)
          - were cut off by feature selection (`max_features`).

        This is only available if no vocabulary was given.

    See also
    --------
    CountVectorizer
        Tokenize the documents and count the occurrences of token and return
        them as a sparse matrix

    TfidfTransformer
        Apply Term Frequency Inverse Document Frequency normalization to a
        sparse matrix of occurrence counts.

    Notes
    -----
    The ``stop_words_`` attribute can get large and increase the model size
    when pickling. This attribute is provided only for introspection and can
    be safely removed using delattr or set to None before pickling.
    """

    def __init__(self, input='content', encoding='utf-8',
                 decode_error='strict', strip_accents=None, lowercase=True,
                 preprocessor=None, tokenizer=None, analyzer='word',
                 stop_words=None, token_pattern=r"(?u)\b\w\w+\b",
                 ngram_range=(1, 1), max_df=1.0, min_df=1,
                 max_features=None, vocabulary=None, binary=False,
                 dtype=np.int64, norm='l2', use_idf=True, smooth_idf=True,
                 sublinear_tf=False):

        super(TfidfVectorizer, self).__init__(
            input=input, encoding=encoding, decode_error=decode_error,
            strip_accents=strip_accents, lowercase=lowercase,
            preprocessor=preprocessor, tokenizer=tokenizer, analyzer=analyzer,
            stop_words=stop_words, token_pattern=token_pattern,
            ngram_range=ngram_range, max_df=max_df, min_df=min_df,
            max_features=max_features, vocabulary=vocabulary, binary=binary,
            dtype=dtype)

        self._tfidf = TfidfTransformer(norm=norm, use_idf=use_idf,
                                       smooth_idf=smooth_idf,
                                       sublinear_tf=sublinear_tf)

    # Broadcast the TF-IDF parameters to the underlying transformer instance
    # for easy grid search and repr

    @property
    def norm(self):
        return self._tfidf.norm

    @norm.setter
    def norm(self, value):
        self._tfidf.norm = value

    @property
    def use_idf(self):
        return self._tfidf.use_idf

    @use_idf.setter
    def use_idf(self, value):
        self._tfidf.use_idf = value

    @property
    def smooth_idf(self):
        return self._tfidf.smooth_idf

    @smooth_idf.setter
    def smooth_idf(self, value):
        self._tfidf.smooth_idf = value

    @property
    def sublinear_tf(self):
        return self._tfidf.sublinear_tf

    @sublinear_tf.setter
    def sublinear_tf(self, value):
        self._tfidf.sublinear_tf = value

    @property
    def idf_(self):
        return self._tfidf.idf_

    def fit(self, raw_documents, y=None):
        """Learn vocabulary and idf from training set.

        Parameters
        ----------
        raw_documents : iterable
            an iterable which yields either str, unicode or file objects

        Returns
        -------
        self : TfidfVectorizer
        """
        X = super(TfidfVectorizer, self).fit_transform(raw_documents)
        self._tfidf.fit(X)
        return self

    def fit_transform(self, raw_documents, y=None):
        """Learn vocabulary and idf, return term-document matrix.

        This is equivalent to fit followed by transform, but more efficiently
        implemented.

        Parameters
        ----------
        raw_documents : iterable
            an iterable which yields either str, unicode or file objects

        Returns
        -------
        X : sparse matrix, [n_samples, n_features]
            Tf-idf-weighted document-term matrix.
        """
        X = super(TfidfVectorizer, self).fit_transform(raw_documents)
        self._tfidf.fit(X)
        # X is already a transformed view of raw_documents so
        # we set copy to False
        return self._tfidf.transform(X, copy=False)

    def transform(self, raw_documents, copy=True):
        """Transform documents to document-term matrix.

        Uses the vocabulary and document frequencies (df) learned by fit (or
        fit_transform).

        Parameters
        ----------
        raw_documents : iterable
            an iterable which yields either str, unicode or file objects

        copy : boolean, default True
            Whether to copy X and operate on the copy or perform in-place
            operations.

        Returns
        -------
        X : sparse matrix, [n_samples, n_features]
            Tf-idf-weighted document-term matrix.
        """
        check_is_fitted(self, '_tfidf', 'The tfidf vector is not fitted')

        X = super(TfidfVectorizer, self).transform(raw_documents)
        return self._tfidf.transform(X, copy=False)


"""
Illustrate different ways of using the various fill functions.
"""
import numpy as np
import matplotlib.pyplot as plt

import example_utils

def main():
    fig, axes = example_utils.setup_axes()

    fill_example(axes[0])
    fill_between_example(axes[1])
    stackplot_example(axes[2])

    example_utils.title(fig, 'fill/fill_between/stackplot: Filled polygons',
                        y=0.95)
    fig.savefig('fill_example.png', facecolor='none')
    plt.show()

def fill_example(ax):
    # Use fill when you want a simple filled polygon between vertices
    x, y = fill_data()
    ax.fill(x, y, color='lightblue')
    ax.margins(0.1)
    example_utils.label(ax, 'fill')

def fill_between_example(ax):
    # Fill between fills between two curves or a curve and a constant value
    # It can be used in several ways. We'll illustrate a few below.
    x, y1, y2 = sin_data()

    # The most basic (and common) use of fill_between
    err = np.random.rand(x.size)**2 + 0.1
    y = 0.7 * x + 2
    ax.fill_between(x, y + err, y - err, color='orange')

    # Filling between two curves with different colors when they cross in
    # different directions
    ax.fill_between(x, y1, y2, where=y1>y2, color='lightblue')
    ax.fill_between(x, y1, y2, where=y1<y2, color='forestgreen')

    # Note that this is fillbetween*x*!
    ax.fill_betweenx(x, -y1, where=y1>0, color='red', alpha=0.5)
    ax.fill_betweenx(x, -y1, where=y1<0, color='blue', alpha=0.5)

    ax.margins(0.15)
    example_utils.label(ax, 'fill_between/x')

def stackplot_example(ax):
    # Stackplot is equivalent to a series of ax.fill_between calls
    x, y = stackplot_data()
    ax.stackplot(x, y.cumsum(axis=0), alpha=0.5)
    example_utils.label(ax, 'stackplot')

#-- Data generation ----------------------

def stackplot_data():
    x = np.linspace(0, 10, 100)
    y = np.random.normal(0, 1, (5, 100))
    y = y.cumsum(axis=1)
    y -= y.min(axis=0, keepdims=True)
    return x, y

def sin_data():
    x = np.linspace(0, 10, 100)
    y = np.sin(x)
    y2 = np.cos(x)
    return x, y, y2

def fill_data():
    t = np.linspace(0, 2*np.pi, 100)
    r = np.random.normal(0, 1, 100).cumsum()
    r -= r.min()
    return r * np.cos(t), r * np.sin(t)

main()


__author__ = 'tjhunter'

import build
import json
import pylab as pl
from matplotlib.collections import LineCollection
# Draws the network as a pdf and SVG file.

def draw_network(ax, fd, link_style):
  def decode_line(l):
    #print l
    dct = json.loads(l)
    lats = dct['lats']
    lons = dct['lons']
    return zip(lons, lats)
  lines = [decode_line(l) for l in fd]
  #print lines
  xmin = min([x for l in lines for x,y in l])
  xmax = max([x for l in lines for x,y in l])
  ymin = min([y for l in lines for x,y in l])
  ymax = max([y for l in lines for x,y in l])
  lc = LineCollection(lines, **link_style)
  ax.add_collection(lc, autolim=True)
  return ((xmin,xmax),(ymin,ymax))

fname = build.data_name('kdd/net_export_6.json')
fig = pl.figure("fig1",figsize=(10,10))
ax = fig.gca()
ax.set_axis_off()
style = {'colors':'k','linewidths':0.5}
with open(fname) as f:
  (xlims, ylims) = draw_network(ax, f, style)
  ax.set_xlim(*xlims)
  ax.set_ylim(*ylims)
# Saving in pdf is a bit slow
build.save_figure(fig, 'figures-kdd/network_export_6',save_svg=True)


from numpy import asarray, mean, sqrt, ndarray, amin, amax, concatenate, sum, zeros, maximum, \
    argmin, newaxis, ones, delete, NaN, inf, isnan, clip, logical_or, unique, where, all

from thunder.utils.serializable import Serializable
from thunder.utils.common import checkParams, aslist
from thunder.rdds.images import Images
from thunder.rdds.series import Series

class Source(Serializable, object):
    """
    A single source, represented as a list of coordinates and other optional specifications.

    A source also has a set of lazily computed attributes useful for representing and comparing
    its geometry, such as center, bounding box, and bounding polygon. These properties
    will be computed lazily and made available as attributes when requested.

    Parameters
    ----------
    coordinates : array-like
        List of 2D or 3D coordinates, can be a list of lists or array of shape (n,2) or (n,3)

    values : list or array-like
        Value (or weight) associated with each coordiante

    id : int or string
        Arbitrary specification per source, typically an index or string label

    Attributes
    ----------
    center : list or array-like
        The coordinates of the center of the source

    polygon : list or array-like
        The coordinates of a polygon bounding the region (a convex hull)

    bbox : list or array-like
        Boundaries of the source (with the lowest values for all axes followed by the highest values)

    area : scalar
        The area of the region
    """
    from zope.cachedescriptors import property

    def __init__(self, coordinates, values=None, id=None):
        self.coordinates = asarray(coordinates)

        if self.coordinates.ndim == 1 and len(self.coordinates) > 0:
            self.coordinates = asarray([self.coordinates])

        if values is not None:
            self.values = asarray(values)
            if self.values.ndim == 0:
                self.values = asarray([self.values])
            if not (len(self.coordinates) == len(self.values)):
                raise ValueError("Lengths of coordinates %g and values %g do not match"
                                 % (len(self.coordinates), len(self.values)))

        if id is not None:
            self.id = id

    @property.Lazy
    def center(self):
        """
        Find the region center using a mean.
        """
        # TODO Add option to use weights
        return mean(self.coordinates, axis=0)

    @property.Lazy
    def polygon(self):
        """
        Find the bounding polygon as a convex hull
        """
        # TODO Add option for simplification
        from scipy.spatial import ConvexHull
        if len(self.coordinates) >= 4:
            inds = ConvexHull(self.coordinates).vertices
            return self.coordinates[inds]
        else:
            return self.coordinates

    @property.Lazy
    def bbox(self):
        """
        Find the bounding box.
        """
        mn = amin(self.coordinates, axis=0)
        mx = amax(self.coordinates, axis=0)
        return concatenate((mn, mx))

    @property.Lazy
    def area(self):
        """
        Find the region area.
        """
        return len(self.coordinates)

    def restore(self, skip=None):
        """
        Remove all lazy properties, will force recomputation
        """
        if skip is None:
            skip = []
        elif isinstance(skip, str):
            skip = [skip]
        for prop in LAZY_ATTRIBUTES:
            if prop in self.__dict__.keys() and prop not in skip:
                del self.__dict__[prop]
        return self

    def distance(self, other, method='euclidean'):
        """
        Distance between the center of this source and another.

        Parameters
        ----------
        other : Source, or array-like
            Either another source, or the center coordinates of another source

        method : str
            Specify a distance measure to used for spatial distance between source
            centers. Current options include Euclidean distance ('euclidean') and
            L1-norm ('l1').

        """
        from numpy.linalg import norm

        checkParams(method, ['euclidean', 'l1'])

        if method == 'l1':
            order = 1
        else:
            order = 2

        if isinstance(other, Source):
            return norm(self.center - other.center, ord=order)
        elif isinstance(other, list) or isinstance(other, ndarray):
            return norm(self.center - asarray(other), ord=order)

    def overlap(self, other, method='fraction'):
        """
        Compute the overlap between this source and other.

        Options are a symmetric measure of overlap based on the fraction
        of intersecting pixels relative to the union ('fraction'), an assymmetric
        measure of overlap that expresses detected intersecting pixels
        (relative to this source) using precision and recall rates ('rates'), or
        a correlation coefficient of the weights within the intersection
        (not defined for binary weights) ('correlation')

        Parameters
        ----------
        other : Source
            The source to compute overlap with.

        method : str
            Which estimate of overlap to compute, options are
            'fraction' (symmetric) 'rates' (asymmetric) or 'correlation'
        """
        checkParams(method, ['fraction', 'rates', 'correlation'])

        coordsSelf = aslist(self.coordinates)
        coordsOther = aslist(other.coordinates)

        intersection = [a for a in coordsSelf if a in coordsOther]
        nhit = float(len(intersection))
        ntotal = float(len(set([tuple(x) for x in coordsSelf] + [tuple(x) for x in coordsOther])))

        if method == 'rates':
            recall = nhit / len(coordsSelf)
            precision = nhit / len(coordsOther)
            return recall, precision

        if method == 'fraction':
            return nhit / float(ntotal)

        if method == 'correlation':
            from scipy.stats import spearmanr
            if not (hasattr(self, 'values') and hasattr(other, 'values')):
                raise ValueError('Sources must have values to compute correlation')
            else:
                valuesSelf = aslist(self.values)
                valuesOther = aslist(other.values)
            if len(intersection) > 0:
                left = [v for v, c in zip(valuesSelf, coordsSelf) if c in coordsOther]
                right = [v for v, c in zip(valuesOther, coordsOther) if c in coordsSelf]
                rho, _ = spearmanr(left, right)
            else:
                rho = 0.0
            return rho

    def merge(self, other):
        """
        Combine this source with other
        """
        self.coordinates = concatenate((self.coordinates, other.coordinates))

        if hasattr(self, 'values'):
            self.values = concatenate((self.values, other.values))

        return self

    def tolist(self):
        """
        Convert array-like attributes to list
        """
        import copy
        new = copy.copy(self)
        for prop in ["coordinates", "values", "center", "bbox", "polygon"]:
            if prop in self.__dict__.keys():
                val = new.__getattribute__(prop)
                if val is not None and not isinstance(val, list):
                    setattr(new, prop, val.tolist())
        return new

    def toarray(self):
        """
        Convert array-like attributes to ndarray
        """
        import copy
        new = copy.copy(self)
        for prop in ["coordinates", "values", "center", "bbox", "polygon"]:
            if prop in self.__dict__.keys():
                val = new.__getattribute__(prop)
                if val is not None and not isinstance(val, ndarray):
                    setattr(new, prop, asarray(val))
        return new

    def crop(self, minBound, maxBound):
        """
        Crop a source by removing coordinates outside bounds.

        Follows normal slice indexing conventions.

        Parameters
        ----------
        minBound : tuple
            Minimum or starting bounds for each axis

        maxBound : tuple
            Maximum or ending bounds for each axis
        """
        coords = self.coordinates

        newid = self.id if hasattr(self, 'id') else None

        if hasattr(self, 'values') and self.values is not None:
            values = self.values
            inside = [(c, v) for c, v in zip(coords, values) if c not in coords]
            newcoords, newvalues = zip(*inside)
            return Source(coordinates=newcoords, values=newvalues, id=newid)
        else:
            newcoords = [c for c in coords if all(c >= minBound) and all(c < maxBound)]
            return Source(coordinates=newcoords, id=newid)

    def dilate(self, size):
        """
        Dilate a source using morphological operators.

        Parameters
        ----------
        size : int
            Size of dilation in pixels
        """
        if size == 0:
            newcoords = self.coordinates

        else:
            size = (size * 2) + 1

            if hasattr(self, 'values') and self.values is not None:
                raise AttributeError('Cannot dilate sources with values')

            from skimage.morphology import binary_dilation

            coords = self.coordinates
            extent = self.bbox[len(self.center):] - self.bbox[0:len(self.center)] + 1 + size * 2
            m = zeros(extent)
            coords = (coords - self.bbox[0:len(self.center)] + size)
            m[coords.T.tolist()] = 1
            m = binary_dilation(m, ones((size, size)))
            newcoords = asarray(where(m)).T + self.bbox[0:len(self.center)] - size
            newcoords = [c for c in newcoords if all(c >= 0)]

        newid = self.id if hasattr(self, 'id') else None

        return Source(coordinates=newcoords, id=newid)

    def exclude(self, other):
        """
        Remove coordinates derived from another Source or an array.

        If other is an array, will remove coordinates of all
        non-zero elements from this source. If other is a source,
        will remove any matching coordinates.

        Parameters
        ----------
        other : ndarray or Source
            Source to remove
        """
        if isinstance(other, ndarray):
            coordsOther = asarray(where(other)).T
        else:
            coordsOther = aslist(other.coordinates)

        coordsSelf = aslist(self.coordinates)

        newid = self.id if hasattr(self, 'id') else None

        if hasattr(self, 'values') and self.values is not None:
            valuesSelf = self.values
            complement = [(c, v) for c, v in zip(coordsSelf, valuesSelf) if c not in coordsOther]
            newcoords, newvalues = zip(*complement)
            return Source(coordinates=newcoords, values=newvalues, id=newid)
        else:
            complement = [a for a in coordsSelf if a not in coordsOther]
            return Source(coordinates=complement, id=newid)

    def outline(self, inner, outer):
        """
        Compute source outline by differencing two dilations

        Parameters
        ----------
        inner : int
            Size of inner outline boundary (in pixels)

        outer : int
            Size of outer outline boundary (in pixels)
        """
        return self.dilate(outer).exclude(self.dilate(inner))

    def transform(self, data, collect=True):
        """
        Extract series from data using a list of sources.

        Currently only supports averaging over coordinates.

        Params
        ------
        data : Images or Series object
            The data from which to extract

        collect : boolean, optional, default = True
            Whether to collect to local array or keep as a Series
        """

        if not (isinstance(data, Images) or isinstance(data, Series)):
            raise Exception("Input must either be Images or Series (or a subclass)")

        # TODO add support for weighting
        if isinstance(data, Images):
            output = data.meanByRegions([self.coordinates]).toSeries()
        else:
            output = data.meanOfRegion(self.coordinates)

        if collect:
            return output.collectValuesAsArray()
        else:
            return output

    def mask(self, dims=None, binary=True, outline=False, color=None):
        """
        Construct a mask from a source, either locally or within a larger image.

        Parameters
        ----------
        dims : list or tuple, optional, default = None
            Dimensions of large image in which to draw mask. If none, will restrict
            to the bounding box of the region.

        binary : boolean, optional, deafult = True
            Whether to incoporate values or only show a binary mask

        outline : boolean, optional, deafult = False
            Whether to only show outlines (derived using binary dilation)

        color : str or array-like
            RGB triplet (from 0 to 1) or named color (e.g. 'red', 'blue')
        """
        from thunder import Colorize

        coords = self.coordinates

        if dims is None:
            extent = self.bbox[len(self.center):] - self.bbox[0:len(self.center)] + 1
            m = zeros(extent)
            coords = (coords - self.bbox[0:len(self.center)])
        else:
            m = zeros(dims)

        if hasattr(self, 'values') and self.values is not None and binary is False:
            m[coords.T.tolist()] = self.values
        else:
            m[coords.T.tolist()] = 1

        if outline:
            from skimage.morphology import binary_dilation
            m = binary_dilation(m, ones((3, 3))) - m

        if color is not None:
            m = Colorize(cmap='indexed', colors=[color]).transform([m])

        return m

    def inbounds(self, minBound, maxBound):
        """
        Check what fraction of coordinates are inside given bounds

        Parameters
        ----------
        minBound : list or tuple
            Minimum bounds

        maxBounds : list or tuple
            Maximum bounds
        """

        minCheck = sum(self.coordinates < minBound, axis=1) > 0
        maxCheck = sum(self.coordinates > maxBound, axis=1) > 0
        fraction = 1 - sum(logical_or(minCheck, maxCheck)) / float(len(self.coordinates))

        return fraction

    @staticmethod
    def fromMask(mask, id=None):
        """
        Genearte a source from a mask.

        Assumes that the mask is an image where all non-zero
        elements are part of the source. If all non-zero
        elements are 1, then values will be ignored
        as the source is assumed to be binary.

        Parameters
        ----------
        mask : array-like
            An array (typically 2D or 3D) containing the image mask

        id : int or string
            Arbitrary identifier for the source, typically an int or string
        """
        mask = asarray(mask)
        u = unique(mask)

        if len(u) == 2 and u[0] == 0 and u[1] == 1:
            inds = where(mask)
            return Source(coordinates=asarray(zip(*inds)), id=id)

        else:
            inds = where(mask)
            values = mask[inds]
            coords = asarray(zip(*inds))
            return Source(coordinates=coords, values=values, id=id)

    @staticmethod
    def fromCoordinates(coordinates, values=None, id=None):
        """
        Generate a source from a list of coordinates and values.

        Parameters
        ----------
        coordinates : array-like
            List coordinates as a list of lists or array of shape (n,2) or (n,3)

        values : list or array-like
            Value (or weight) associated with each coordiante

        id : int or string
            Arbitrary specification per source, typically an index or string label
        """
        return Source(coordinates, values, id)

    def __repr__(self):
        s = self.__class__.__name__
        for opt in ["id", "center", "bbox"]:
            if hasattr(self, opt):
                o = self.__getattribute__(opt)
                os = o.tolist() if isinstance(o, ndarray) else o
                s += '\n%s: %s' % (opt, repr(os))
        return s

class SourceModel(Serializable, object):
    """
    A source model as a collection of extracted sources.

    Parameters
    ----------
    sources : list or Sources or a single Source
        The identified sources

    See also
    --------
    Source
    """
    def __init__(self, sources):
        if isinstance(sources, Source):
            self.sources = [sources]
        elif isinstance(sources, list) and isinstance(sources[0], Source):
            self.sources = sources
        elif isinstance(sources, list):
            self.sources = []
            for ss in sources:
                self.sources.append(Source(ss))
        else:
            raise Exception("Input type not recognized, must be Source, list of Sources, "
                            "or list of coordinates, got %s" % type(sources))

    def __getitem__(self, entry):
        if not isinstance(entry, int):
            raise IndexError("Selection not recognized, must be Int, got %s" % type(entry))
        return self.sources[entry]

    def combiner(self, prop, tolist=True):
        combined = []
        for s in self.sources:
            p = getattr(s, prop)
            if tolist:
                p = p.tolist()
            combined.append(p)
        return combined

    @property
    def coordinates(self):
        """
        List of coordinates combined across sources
        """
        return self.combiner('coordinates')

    @property
    def values(self):
        """
        List of coordinates combined across sources
        """
        return self.combiner('values')

    @property
    def centers(self):
        """
        Array of centers combined across sources
        """
        return asarray(self.combiner('center'))

    @property
    def polygons(self):
        """
        List of polygons combined across sources
        """
        return self.combiner('polygon')

    @property
    def areas(self):
        """
        List of areas combined across sources
        """
        return self.combiner('area', tolist=False)

    @property
    def count(self):
        """
        Number of sources
        """
        return len(self.sources)

    def masks(self, dims=None, binary=True, outline=False, base=None, color=None, inds=None):
        """
        Composite masks combined across sources as an image.

        Parameters
        ----------
        dims : list or tuple, optional, default = None
            Dimensions of image in which to create masks, must either provide
            these or provide a base image

        binary : boolean, optional, deafult = True
            Whether to incoporate values or only show a binary mask

        outline : boolean, optional, deafult = False
            Whether to only show outlines (derived using binary dilation)

        base : SourceModel or array-like, optional, deafult = None
            Base background image on which to put masks,
            or another set of sources (usually for comparisons).

        color : str, optional, deafult = None
            Color to assign regions, will assign randomly if 'random'

        inds : array-like, optional, deafult = None
            List of indices if only showing a subset
        """
        from thunder import Colorize
        from matplotlib.cm import get_cmap

        if inds is None:
            inds = range(0, self.count)

        if dims is None and base is None:
            raise Exception("Must provide image dimensions for composite masks "
                            "or provide a base image.")

        if base is not None and isinstance(base, SourceModel):
            outline = True

        if dims is None and base is not None:
            dims = asarray(base).shape

        if isinstance(base, SourceModel):
            base = base.masks(dims, color='silver')

        elif isinstance(base, ndarray):
            base = Colorize(cmap='indexed', colors=['white']).transform([base])

        if base is not None and color is None:
            color = 'deeppink'

        if color == 'random':
            combined = zeros(list(dims) + [3])
            ncolors = min(self.count, 20)
            colors = get_cmap('rainbow', ncolors)(range(0, ncolors, 1))[:, 0:3]
            for i in inds:
                combined = maximum(self.sources[i].mask(dims, binary, outline, colors[i % len(colors)]), combined)
        else:
            combined = zeros(dims)
            for i in inds:
                combined = maximum(self.sources[i].mask(dims, binary, outline), combined)

        if color is not None and color != 'random':
            combined = Colorize(cmap='indexed', colors=[color]).transform([combined])

        if base is not None:
            combined = maximum(base, combined)

        return combined

    def match(self, other, unique=False, minDistance=inf):
        """
        For each source in self, find the index of the closest source in other.

        Uses euclidean distances between centers to determine distances.

        Can select nearest matches with or without enforcing uniqueness;
        if unique is False, will return the closest source in other for
        each source in self, possibly repeating sources multiple times
        if unique is True, will only allow each source in other to be matched
        with a single source in self, as determined by a greedy selection procedure.
        The minDistance parameter can be used to prevent far-away sources from being
        chosen during greedy selection.

        Params
        ------
        other : SourceModel
            The source model to match sources to

        unique : boolean, optional, deafult = True
            Whether to only return unique matches

        minDistance : scalar, optiona, default = inf
            Minimum distance to use when selecting matches
        """
        from scipy.spatial.distance import cdist

        targets = other.centers
        targetInds = range(0, len(targets))
        matches = []
        for s in self.sources:
            update = 1

            # skip if no targets left, otherwise update
            if len(targets) == 0:
                update = 0
            else:
                dists = cdist(targets, s.center[newaxis])
                if dists.min() < minDistance:
                    ind = argmin(dists)
                else:
                    update = 0

            # apply updates, otherwise add a nan
            if update == 1:
                matches.append(targetInds[ind])
                if unique is True:
                    targets = delete(targets, ind, axis=0)
                    targetInds = delete(targetInds, ind)
            else:
                matches.append(NaN)

        return matches

    def distance(self, other, minDistance=inf):
        """
        Compute the distance between each source in self and other.

        First estimates a matching source from other for each source
        in self, then computes the distance between the two sources.
        The matches are unique, using a greedy procedure,
        and minDistance can be used to prevent outliers during matching.

        Parameters
        ----------
        other : SourceModel
            The sources to compute distances to

        minDistance : scalar, optiona, default = inf
            Minimum distance to use when matching indices
        """

        inds = self.match(other, unique=True, minDistance=minDistance)
        d = []
        for jj, ii in enumerate(inds):
            if ii is not NaN:
                d.append(self[jj].distance(other[ii]))
            else:
                d.append(NaN)
        return asarray(d)

    def overlap(self, other, method='fraction', minDistance=inf):
        """
        Estimate overlap between sources in self and other.

        Will compute the similarity of sources in self that are found
        in other, based on either source pixel overlap or correlation.

        Parameters
        ----------
        other : SourceModel
            The sources to compare to

        method : str, optional, default = 'fraction"
            Method to use when computing overlap between sources
            ('fraction', 'rates', or 'correlation')

        minDistance : scalar, optional, default = inf
            Minimum distance to use when matching indices
        """

        inds = self.match(other, unique=True, minDistance=minDistance)
        d = []
        for jj, ii in enumerate(inds):
            if ii is not NaN:
                d.append(self[jj].overlap(other[ii], method=method))
            else:
                if method == 'rates':
                    d.append((NaN, NaN))
                else:
                    d.append(NaN)
        return asarray(d)

    def similarity(self, other, metric='distance', thresh=5, minDistance=inf):
        """
        Estimate similarity to another set of sources using recall and precision.

        Will compute the number of sources in self that are also
        in other, based on a given distance metric and a threshold.
        The recall rate is the number of matches divided by the number in self,
        and the precision rate is the number of matches divided by the number in other.
        Typically self is ground truth and other is an estimate.
        The F score is defined as 2 * (recall * precision) / (recall + precision)

        Before computing metrics, all sources in self are matched to other,
        and a minimum distance can be set to control matching.

        Parameters
        ----------
        other : SourceModel
            The sources to compare to.

        metric : str, optional, default = 'distance'
            Metric to use when computing distances,
            options include 'distance' and 'overlap'

        thresh : scalar, optional, default = 5
            The distance below which a source is considered found.

        minDistance : scalar, optional, default = inf
            Minimum distance to use when matching indices.
        """
        checkParams(metric, ['distance', 'overlap'])

        if metric == 'distance':
            # when evaluating distances,
            # minimum distance should be the threshold
            if minDistance == inf:
                minDistance = thresh
            vals = self.distance(other, minDistance=minDistance)
            vals[isnan(vals)] = inf
            compare = lambda x: x < thresh
        elif metric == 'overlap':
            vals = self.overlap(other, method='fraction', minDistance=minDistance)
            vals[isnan(vals)] = 0
            compare = lambda x: x > thresh
        else:
            raise Exception("Metric not recognized")

        recall = sum(map(compare, vals)) / float(self.count)
        precision = sum(map(compare, vals)) / float(other.count)
        score = 2 * (recall * precision) / (recall + precision)

        return recall, precision, score

    def transform(self, data, collect=True):
        """
        Extract series from data using a list of sources.

        Currently only supports simple averaging over coordinates.

        Params
        ------
        data : Images or Series object
            The data from which to extract signals

        collect : boolean, optional, default = True
            Whether to collect to local array or keep as a Series
        """
        if not (isinstance(data, Images) or isinstance(data, Series)):
            raise Exception("Input must either be Images or Series (or a subclass)")

        # TODO add support for weighting
        if isinstance(data, Images):
            output = data.meanByRegions(self.coordinates).toSeries()
        else:
            output = data.meanByRegions(self.coordinates)

        if collect:
            return output.collectValuesAsArray()
        else:
            return output

    def clean(self, cleaners=None):
        """
        Apply one or more cleaners to sources, returning filtered sources

        Parameters
        ----------
        cleaners : Cleaner or list of Cleaners, optional, default = None
            Which cleaners to apply, if None, will apply BasicCleaner with defaults
        """
        from thunder.extraction.cleaners import Cleaner, BasicCleaner
        from copy import copy

        if isinstance(cleaners, list):
            for c in cleaners:
                if not isinstance(c, Cleaner):
                    raise Exception("List must only contain Cleaners")
        elif isinstance(cleaners, Cleaner):
            cleaners = [cleaners]
        elif cleaners is None:
            cleaners = [BasicCleaner()]
        else:
            raise Exception("Must provide Cleaner or list of Cleaners, got %s" % type(cleaners))

        newmodel = copy(self)

        for c in cleaners:
            newmodel = c.clean(newmodel)

        return newmodel

    def dilate(self, size):
        """
        Dilate all sources using morphological operators

        Parameters
        ----------
        size : int
            Size of dilation in pixels
        """
        return SourceModel([s.dilate(size) for s in self.sources])

    def outline(self, inner, outer):
        """
        Outline all sources

        inner : int
            Size of inner outline boundary (in pixels)

        outer : int
            Size of outer outline boundary (in pixels)
        """
        return SourceModel([s.outline(inner, outer) for s in self.sources])

    def crop(self, minBound, maxBound):
        """
        Crop all sources by removing coordinates outside of bounds

        Parameters
        ----------
        minBound : tuple
            Minimum or starting bounds for each axis

        maxBound : tuple
            Maximum or ending bounds for each axis
        """
        return SourceModel([s.crop(minBound, maxBound) for s in self.sources])

    def save(self, f, include=None, overwrite=False, **kwargs):
        """
        Custom save to file with simplified, human-readable output, and selection of lazy attributes.
        """
        import copy
        output = copy.deepcopy(self)
        if isinstance(include, str):
            include = [include]
        if include is not None:
            for prop in include:
                map(lambda s: getattr(s, prop), output.sources)
        output.sources = map(lambda s: s.restore(include).tolist(), output.sources)
        simplify = lambda d: d['sources']['py/homogeneousList']['data']
        super(SourceModel, output).save(f, simplify=simplify, overwrite=overwrite, **kwargs)

    @classmethod
    def load(cls, f, **kwargs):
        """
        Custom load from file to handle simplified, human-readable output
        """
        unsimplify = lambda d: {'sources': {
            'py/homogeneousList': {'data': d, 'module': 'thunder.extraction.source', 'type': 'Source'}}}
        output = super(SourceModel, cls).load(f, unsimplify=unsimplify)
        output.sources = map(lambda s: s.toarray(), output.sources)
        return output

    @classmethod
    def deserialize(cls, d, **kwargs):
        """
        Custom load from JSON to handle simplified, human-readable output
        """
        unsimplify = lambda d: {'sources': {
            'py/homogeneousList': {'data': d, 'module': 'thunder.extraction.source', 'type': 'Source'}}}
        output = super(SourceModel, cls).deserialize(d, unsimplify=unsimplify)
        output.sources = map(lambda s: s.toarray(), output.sources)
        return output

    def __repr__(self):
        s = self.__class__.__name__
        s += '\n%g sources' % (len(self.sources))
        return s

LAZY_ATTRIBUTES = ["center", "polygon", "bbox", "area"]


"""Loads and/or plots 2D, topologlically structured data on quadrilaterals using matplotlib.
"""

import sys,os
import numpy as np
import h5py
import mesh
import colors

def fullname(varname):
    fullname = varname
    if not '.cell.' in fullname:
        fullname = fullname+'.cell.0'
    return fullname

def transect_data(varnames, keys='all', directory=".", filename="visdump_data.h5",
                  mesh_filename="visdump_mesh.h5", coord_order=None, deformable=False, return_map=False):
    """Pulls simulation output into structured 2D arrays for transect-based, (i,j) indexing.

    Input:
      varnames       | A list of variable names to pull, e.g.
                     |  ['saturation_liquid', 'saturation_ice'], or a single variable
                     |  name, e.g. 'saturation_liquid'
      keys           | Indices of timesteps to pull.  Either an int (i.e. 0, -1, etc)
                     |  for the kth timestep, or a list of ints, or 'all'.
      directory      | Directory of the run.  Defaults to '.'
      filename       | Filename of the run.  Defaults to 'visdump_data.h5'
      mesh_filename  | Filename of the mesh.  Defaults to 'visdump_mesh.h5'
      coord_order    | Order of the transect coordinates.  Defaults to ['x','z'].  The
                     |  mesh is sorted in this order.
      deformable     | Is the mesh deforming?
      return_map     | See return value below.

    Output:
      Output is an array of shape:
      ( len(varnames+2), len(keys), n_cells_coord_order[0], n_cells_coord_order[1] )

      data[0,0,:,:] is the coord_order[0] centroid
      data[1,0,:,:] is the coord_order[1] centroid
      data[i+2,k,:,:] is the ith varname data at the kth requested timestep, sorted in
                      the same way as the centroids.

      Note that the data is re-ordered in INCREASING coordinate, i.e. bottom to top in z.

      If return_map is True, then returns a tuple, (data, map) where
      map is a (NX,NZ) array of integers specifying which global id
      corresponds to the (i,j) cell.  This is useful for mapping input
      data back INTO the unstructured mesh.

    Example usage:
      Calculate and plot the thaw depth at step 5.

      // Pull saturation ice -- TD is where sat ice = 0."
      data = transect_data(['saturation_ice', 5)

      // x coordinate for plotting
      x = data[0,0,:,0]

      // for each column, find highest z where sat_ice > 0.
      td_i = np.array([np.where(data[2,0,i,:] > 0.)[0][-1] for i in range(data.shape[2])])

      // now that we have an index into the highest cell with ice, determine td as the
      // mean of the highest cell with ice and the one above that.  Note this assumes
      // all columns have some thawing.
      td_z = np.array( [  (dat[1,0,i,td_i[i]] + dat[1,0,i,td_i[i+1]]) / 2.
                              for i in range(len(td_i)) ] )

      plt.plot(x, td_z)

    """
    if coord_order is None:
        coord_order = ['x','z']

    if type(varnames) is str:
        varnames = [varnames,]

    # get centroids
    xyz = mesh.meshElemCentroids(mesh_filename, directory)

    # round to avoid issues
    xyz = np.round(xyz, decimals=5)

    # get ordering of centroids
    dtype = [(coord_order[0], float), (coord_order[1], float)]
    num_order = []
    for i in coord_order:
        if i == 'x':
            num_order.append(0)
        elif i == 'y':
            num_order.append(1)
        elif i == 'z':
            num_order.append(2)

    xyz_sort_order = np.array([tuple([xyz[i,x] for x in num_order]) for i in range(len(xyz))], dtype=dtype)
    xyz_sorting = xyz_sort_order.argsort(order=coord_order)

    with h5py.File(os.path.join(directory,filename),'r') as dat:
        keys_avail = dat[fullname(varnames[0])].keys()
        keys_avail.sort(lambda a,b: int.__cmp__(int(a),int(b)))

        if keys == 'all':
            keys = keys_avail
        elif type(keys) is str:
            keys = [keys,]
        elif type(keys) is int:
            keys = [keys_avail[keys],]
        elif type(keys) is slice:
            keys = keys_avail[keys]
        elif type(keys) is list:
            if all(type(k) is int for k in keys):
                keys = [keys_avail[k] for k in keys]
            elif all(type(k) is str for k in keys):
                pass
            else:
                raise RuntimeError("Keys requested cannot be processed -- should be 'all', int, or str key, or list of ints or strs.")

        # get data
        vals = np.zeros((len(varnames)+2, len(keys), len(xyz)), 'd')

        for i,key in enumerate(keys):
            if deformable:
                xyz = mesh.meshElemCentroids(mesh_filename, directory)
            vals[0,i,:] = xyz[xyz_sorting,num_order[0]]
            vals[1,i,:] = xyz[xyz_sorting,num_order[1]]
            for j,varname in enumerate(varnames):
                vals[j+2,i,:] = dat[fullname(varname)][key][:,0][xyz_sorting]

    # reshape the data
    # determine nx
    nx = len(set(vals[0,0,:]))
    nz = vals.shape[2] / nx
    if (nx * nz != vals.shape[2]):
        raise RuntimeError("Assumption about first coordinate being cleanly binnable is falling apart -- ask Ethan to rethink this algorithm!")
    shp = vals.shape

    if not return_map:
        return vals.reshape(shp[0], shp[1], nx, nz)
    else:
        return vals.reshape(shp[0], shp[1], nx, nz), xyz_sorting.reshape(nx, nz)

def plot(dataset, ax, cax=None, vmin=None, vmax=None, cmap="jet",
         label=None, mesh_filename="visdump_mesh.h5", directory=".", y_coord=0.0,
         linewidths=1):
    """Draws a dataset on an ax."""
    import matplotlib.collections
    from matplotlib import pyplot as plt

    if vmin is None:
        vmin = dataset.min()
    if vmax is None:
        vmax = dataset.max()

    # get the mesh and collapse to 2D
    etype, coords, conn = mesh.meshElemXYZ(filename=mesh_filename, directory=directory)
    if etype is not 'HEX':
        raise RuntimeError("Only works for Hexs")

    coords2 = np.array([[coords[i][0::2] for i in c[1:] if abs(coords[i][1] - y_coord) < 1.e-8] for c in conn])
    try:
        assert coords2.shape[2] == 2
        assert coords2.shape[1] == 4
    except AssertionError:
        print(coords2.shape)
        for c in conn:
            if len(c) != 9:
                print c
                raise RuntimeError("what is a conn?")
            coords3 = np.array([coords[i][:] for i in c[1:] if abs(coords[i][1] - y_coord) < 1.e-8])
            if coords3.shape[0] != 4:
                print coords
                raise RuntimeError("Unable to squash to 2D")

    # reorder anti-clockwise
    for i,c in enumerate(coords2):
        centroid = c.mean(axis=0)
        def angle(p1,p2):
            a1 = np.arctan2((p1[1]-centroid[1]),(p1[0]-centroid[0]))
            a2 = np.arctan2((p2[1]-centroid[1]),(p2[0]-centroid[0]))
            if a1 < a2:
                return -1
            elif a2 < a1:
                return 1
            else:
                return 0

        c2 = np.array(sorted(c,angle))
        coords2[i] = c2

    polygons = matplotlib.collections.PolyCollection(coords2, edgecolor='k', cmap=cmap, linewidths=linewidths)
    polygons.set_array(dataset)
    polygons.set_clim(vmin,vmax)
    ax.add_collection(polygons)

    xmin = min(c[0] for c in coords.itervalues())
    xmax = max(c[0] for c in coords.itervalues())
    zmin = min(c[2] for c in coords.itervalues())
    zmax = max(c[2] for c in coords.itervalues())

    ax.set_xlim(xmin,xmax)
    ax.set_ylim(zmin,zmax)

    if cax is not None:
        cb = plt.colorbar(polygons, cax=cax)
        if label is not None:
            cb.set_label(label)

    return ((xmin,xmax),(zmin,zmax))


#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
=================================================================
Iso-probability lines for Gaussian Processes classification (GPC)
=================================================================

A two-dimensional classification example showing iso-probability lines for
the predicted probabilities.
"""
print(__doc__)

# Author: Vincent Dubourg <vincent.dubourg@gmail.com>
# Adapted to GaussianProcessClassifier:
#         Jan Hendrik Metzen <jhm@informatik.uni-bremen.de>
# Licence: BSD 3 clause

import numpy as np

from matplotlib import pyplot as pl
from matplotlib import cm

from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import DotProduct, ConstantKernel as C

# A few constants
lim = 8

def g(x):
    """The function to predict (classification will then consist in predicting
    whether g(x) <= 0 or not)"""
    return 5. - x[:, 1] - .5 * x[:, 0] ** 2.

# Design of experiments
X = np.array([[-4.61611719, -6.00099547],
              [4.10469096, 5.32782448],
              [0.00000000, -0.50000000],
              [-6.17289014, -4.6984743],
              [1.3109306, -6.93271427],
              [-5.03823144, 3.10584743],
              [-2.87600388, 6.74310541],
              [5.21301203, 4.26386883]])

# Observations
y = np.array(g(X) > 0, dtype=int)

# Instanciate and fit Gaussian Process Model
kernel = C(0.1, (1e-5, np.inf)) * DotProduct(sigma_0=0.1) ** 2
gp = GaussianProcessClassifier(kernel=kernel)
gp.fit(X, y)
print("Learned kernel: %s " % gp.kernel_)

# Evaluate real function and the predicted probability
res = 50
x1, x2 = np.meshgrid(np.linspace(- lim, lim, res),
                     np.linspace(- lim, lim, res))
xx = np.vstack([x1.reshape(x1.size), x2.reshape(x2.size)]).T

y_true = g(xx)
y_prob = gp.predict_proba(xx)[:, 1]
y_true = y_true.reshape((res, res))
y_prob = y_prob.reshape((res, res))

# Plot the probabilistic classification iso-values
fig = pl.figure(1)
ax = fig.gca()
ax.axes.set_aspect('equal')
pl.xticks([])
pl.yticks([])
ax.set_xticklabels([])
ax.set_yticklabels([])
pl.xlabel('$x_1$')
pl.ylabel('$x_2$')

cax = pl.imshow(y_prob, cmap=cm.gray_r, alpha=0.8,
                extent=(-lim, lim, -lim, lim))
norm = pl.matplotlib.colors.Normalize(vmin=0., vmax=0.9)
cb = pl.colorbar(cax, ticks=[0., 0.2, 0.4, 0.6, 0.8, 1.], norm=norm)
cb.set_label('${\\rm \mathbb{P}}\left[\widehat{G}(\mathbf{x}) \leq 0\\right]$')
pl.clim(0, 1)

pl.plot(X[y <= 0, 0], X[y <= 0, 1], 'r.', markersize=12)

pl.plot(X[y > 0, 0], X[y > 0, 1], 'b.', markersize=12)

cs = pl.contour(x1, x2, y_true, [0.], colors='k', linestyles='dashdot')

cs = pl.contour(x1, x2, y_prob, [0.666], colors='b',
                linestyles='solid')
pl.clabel(cs, fontsize=11)

cs = pl.contour(x1, x2, y_prob, [0.5], colors='k',
                linestyles='dashed')
pl.clabel(cs, fontsize=11)

cs = pl.contour(x1, x2, y_prob, [0.334], colors='r',
                linestyles='solid')
pl.clabel(cs, fontsize=11)

pl.show()