"""
Helpers for embarrassingly parallel code.
"""
# Author: Gael Varoquaux < gael dot varoquaux at normalesup dot org >
# Copyright: 2010, Gael Varoquaux
# License: BSD 3 clause

from __future__ import division

import os
import sys
import gc
import warnings
from math import sqrt
import functools
import time
import threading
import itertools
from numbers import Integral
try:
    import cPickle as pickle
except:
    import pickle

from ._multiprocessing_helpers import mp
if mp is not None:
    from .pool import MemmapingPool
    from multiprocessing.pool import ThreadPool

from .format_stack import format_exc, format_outer_frames
from .logger import Logger, short_format_time
from .my_exceptions import TransportableException, _mk_exception
from .disk import memstr_to_kbytes
from ._compat import _basestring

VALID_BACKENDS = ['multiprocessing', 'threading']

# Environment variables to protect against bad situations when nesting
JOBLIB_SPAWNED_PROCESS = "__JOBLIB_SPAWNED_PARALLEL__"

# In seconds, should be big enough to hide multiprocessing dispatching
# overhead.
# This settings was found by running benchmarks/bench_auto_batching.py
# with various parameters on various platforms.
MIN_IDEAL_BATCH_DURATION = .2

# Should not be too high to avoid stragglers: long jobs running alone
# on a single worker while other workers have no work to process any more.
MAX_IDEAL_BATCH_DURATION = 2

# Under Linux or OS X the default start method of multiprocessing
# can cause third party libraries to crash. Under Python 3.4+ it is possible
# to set an environment variable to switch the default start method from
# 'fork' to 'forkserver' or 'spawn' to avoid this issue albeit at the cost
# of causing semantic changes and some additional pool instanciation overhead.
if hasattr(mp, 'get_context'):
    method = os.environ.get('JOBLIB_START_METHOD', '').strip() or None
    DEFAULT_MP_CONTEXT = mp.get_context(method=method)
else:
    DEFAULT_MP_CONTEXT = None

class BatchedCalls(object):
    """Wrap a sequence of (func, args, kwargs) tuples as a single callable"""

    def __init__(self, iterator_slice):
        self.items = list(iterator_slice)
        self._size = len(self.items)

    def __call__(self):
        return [func(*args, **kwargs) for func, args, kwargs in self.items]

    def __len__(self):
        return self._size

###############################################################################
# CPU count that works also when multiprocessing has been disabled via
# the JOBLIB_MULTIPROCESSING environment variable
def cpu_count():
    """ Return the number of CPUs.
    """
    if mp is None:
        return 1
    return mp.cpu_count()

###############################################################################
# For verbosity

def _verbosity_filter(index, verbose):
    """ Returns False for indices increasingly apart, the distance
        depending on the value of verbose.

        We use a lag increasing as the square of index
    """
    if not verbose:
        return True
    elif verbose > 10:
        return False
    if index == 0:
        return False
    verbose = .5 * (11 - verbose) ** 2
    scale = sqrt(index / verbose)
    next_scale = sqrt((index + 1) / verbose)
    return (int(next_scale) == int(scale))

###############################################################################
class WorkerInterrupt(Exception):
    """ An exception that is not KeyboardInterrupt to allow subprocesses
        to be interrupted.
    """
    pass

###############################################################################
class SafeFunction(object):
    """ Wraps a function to make it exception with full traceback in
        their representation.
        Useful for parallel computing with multiprocessing, for which
        exceptions cannot be captured.
    """
    def __init__(self, func):
        self.func = func

    def __call__(self, *args, **kwargs):
        try:
            return self.func(*args, **kwargs)
        except KeyboardInterrupt:
            # We capture the KeyboardInterrupt and reraise it as
            # something different, as multiprocessing does not
            # interrupt processing for a KeyboardInterrupt
            raise WorkerInterrupt()
        except:
            e_type, e_value, e_tb = sys.exc_info()
            text = format_exc(e_type, e_value, e_tb, context=10,
                              tb_offset=1)
            raise TransportableException(text, e_type)

###############################################################################
def delayed(function, check_pickle=True):
    """Decorator used to capture the arguments of a function.

    Pass `check_pickle=False` when:

    - performing a possibly repeated check is too costly and has been done
      already once outside of the call to delayed.

    - when used in conjunction `Parallel(backend='threading')`.

    """
    # Try to pickle the input function, to catch the problems early when
    # using with multiprocessing:
    if check_pickle:
        pickle.dumps(function)

    def delayed_function(*args, **kwargs):
        return function, args, kwargs
    try:
        delayed_function = functools.wraps(function)(delayed_function)
    except AttributeError:
        " functools.wraps fails on some callable objects "
    return delayed_function

###############################################################################
class ImmediateComputeBatch(object):
    """Sequential computation of a batch of tasks.

    This replicates the async computation API but actually does not delay
    the computations when joblib.Parallel runs in sequential mode.

    """
    def __init__(self, batch):
        # Don't delay the application, to avoid keeping the input
        # arguments in memory
        self.results = batch()

    def get(self):
        return self.results

###############################################################################
class BatchCompletionCallBack(object):
    """Callback used by joblib.Parallel's multiprocessing backend.

    This callable is executed by the parent process whenever a worker process
    has returned the results of a batch of tasks.

    It is used for progress reporting, to update estimate of the batch
    processing duration and to schedule the next batch of tasks to be
    processed.

    """
    def __init__(self, dispatch_timestamp, batch_size, parallel):
        self.dispatch_timestamp = dispatch_timestamp
        self.batch_size = batch_size
        self.parallel = parallel

    def __call__(self, out):
        self.parallel.n_completed_tasks += self.batch_size
        this_batch_duration = time.time() - self.dispatch_timestamp

        if (self.parallel.batch_size == 'auto'
                and self.batch_size == self.parallel._effective_batch_size):
            # Update the smoothed streaming estimate of the duration of a batch
            # from dispatch to completion
            old_duration = self.parallel._smoothed_batch_duration
            if old_duration == 0:
                # First record of duration for this batch size after the last
                # reset.
                new_duration = this_batch_duration
            else:
                # Update the exponentially weighted average of the duration of
                # batch for the current effective size.
                new_duration = 0.8 * old_duration + 0.2 * this_batch_duration
            self.parallel._smoothed_batch_duration = new_duration

        self.parallel.print_progress()
        if self.parallel._original_iterator is not None:
            self.parallel.dispatch_next()

###############################################################################
class Parallel(Logger):
    ''' Helper class for readable parallel mapping.

        Parameters
        -----------
        n_jobs: int, default: 1
            The maximum number of concurrently running jobs, such as the number
            of Python worker processes when backend="multiprocessing"
            or the size of the thread-pool when backend="threading".
            If -1 all CPUs are used. If 1 is given, no parallel computing code
            is used at all, which is useful for debugging. For n_jobs below -1,
            (n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all
            CPUs but one are used.
        backend: str or None, default: 'multiprocessing'
            Specify the parallelization backend implementation.
            Supported backends are:
              - "multiprocessing" used by default, can induce some
                communication and memory overhead when exchanging input and
                output data with the with the worker Python processes.
              - "threading" is a very low-overhead backend but it suffers
                from the Python Global Interpreter Lock if the called function
                relies a lot on Python objects. "threading" is mostly useful
                when the execution bottleneck is a compiled extension that
                explicitly releases the GIL (for instance a Cython loop wrapped
                in a "with nogil" block or an expensive call to a library such
                as NumPy).
        verbose: int, optional
            The verbosity level: if non zero, progress messages are
            printed. Above 50, the output is sent to stdout.
            The frequency of the messages increases with the verbosity level.
            If it more than 10, all iterations are reported.
        pre_dispatch: {'all', integer, or expression, as in '3*n_jobs'}
            The number of batches (of tasks) to be pre-dispatched.
            Default is '2*n_jobs'. When batch_size="auto" this is reasonable
            default and the multiprocessing workers shoud never starve.
        batch_size: int or 'auto', default: 'auto'
            The number of atomic tasks to dispatch at once to each
            worker. When individual evaluations are very fast, multiprocessing
            can be slower than sequential computation because of the overhead.
            Batching fast computations together can mitigate this.
            The ``'auto'`` strategy keeps track of the time it takes for a batch
            to complete, and dynamically adjusts the batch size to keep the time
            on the order of half a second, using a heuristic. The initial batch
            size is 1.
            ``batch_size="auto"`` with ``backend="threading"`` will dispatch
            batches of a single task at a time as the threading backend has
            very little overhead and using larger batch size has not proved to
            bring any gain in that case.
        temp_folder: str, optional
            Folder to be used by the pool for memmaping large arrays
            for sharing memory with worker processes. If None, this will try in
            order:
            - a folder pointed by the JOBLIB_TEMP_FOLDER environment variable,
            - /dev/shm if the folder exists and is writable: this is a RAMdisk
              filesystem available by default on modern Linux distributions,
            - the default system temporary folder that can be overridden
              with TMP, TMPDIR or TEMP environment variables, typically /tmp
              under Unix operating systems.
            Only active when backend="multiprocessing".
        max_nbytes int, str, or None, optional, 1M by default
            Threshold on the size of arrays passed to the workers that
            triggers automated memory mapping in temp_folder. Can be an int
            in Bytes, or a human-readable string, e.g., '1M' for 1 megabyte.
            Use None to disable memmaping of large arrays.
            Only active when backend="multiprocessing".

        Notes
        -----

        This object uses the multiprocessing module to compute in
        parallel the application of a function to many different
        arguments. The main functionality it brings in addition to
        using the raw multiprocessing API are (see examples for details):

            * More readable code, in particular since it avoids
              constructing list of arguments.

            * Easier debugging:
                - informative tracebacks even when the error happens on
                  the client side
                - using 'n_jobs=1' enables to turn off parallel computing
                  for debugging without changing the codepath
                - early capture of pickling errors

            * An optional progress meter.

            * Interruption of multiprocesses jobs with 'Ctrl-C'

            * Flexible pickling control for the communication to and from
              the worker processes.

            * Ability to use shared memory efficiently with worker
              processes for large numpy-based datastructures.

        Examples
        --------

        A simple example:

        >>> from math import sqrt
        >>> from sklearn.externals.joblib import Parallel, delayed
        >>> Parallel(n_jobs=1)(delayed(sqrt)(i**2) for i in range(10))
        [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]

        Reshaping the output when the function has several return
        values:

        >>> from math import modf
        >>> from sklearn.externals.joblib import Parallel, delayed
        >>> r = Parallel(n_jobs=1)(delayed(modf)(i/2.) for i in range(10))
        >>> res, i = zip(*r)
        >>> res
        (0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5)
        >>> i
        (0.0, 0.0, 1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 4.0, 4.0)

        The progress meter: the higher the value of `verbose`, the more
        messages::

            >>> from time import sleep
            >>> from sklearn.externals.joblib import Parallel, delayed
            >>> r = Parallel(n_jobs=2, verbose=5)(delayed(sleep)(.1) for _ in range(10)) #doctest: +SKIP
            [Parallel(n_jobs=2)]: Done   1 out of  10 | elapsed:    0.1s remaining:    0.9s
            [Parallel(n_jobs=2)]: Done   3 out of  10 | elapsed:    0.2s remaining:    0.5s
            [Parallel(n_jobs=2)]: Done   6 out of  10 | elapsed:    0.3s remaining:    0.2s
            [Parallel(n_jobs=2)]: Done   9 out of  10 | elapsed:    0.5s remaining:    0.1s
            [Parallel(n_jobs=2)]: Done  10 out of  10 | elapsed:    0.5s finished

        Traceback example, note how the line of the error is indicated
        as well as the values of the parameter passed to the function that
        triggered the exception, even though the traceback happens in the
        child process::

         >>> from heapq import nlargest
         >>> from sklearn.externals.joblib import Parallel, delayed
         >>> Parallel(n_jobs=2)(delayed(nlargest)(2, n) for n in (range(4), 'abcde', 3)) #doctest: +SKIP
         #...
         ---------------------------------------------------------------------------
         Sub-process traceback:
         ---------------------------------------------------------------------------
         TypeError                                          Mon Nov 12 11:37:46 2012
         PID: 12934                                    Python 2.7.3: /usr/bin/python
         ...........................................................................
         /usr/lib/python2.7/heapq.pyc in nlargest(n=2, iterable=3, key=None)
             419         if n >= size:
             420             return sorted(iterable, key=key, reverse=True)[:n]
             421
             422     # When key is none, use simpler decoration
             423     if key is None:
         --> 424         it = izip(iterable, count(0,-1))                    # decorate
             425         result = _nlargest(n, it)
             426         return map(itemgetter(0), result)                   # undecorate
             427
             428     # General case, slowest method

         TypeError: izip argument #1 must support iteration
         ___________________________________________________________________________

        Using pre_dispatch in a producer/consumer situation, where the
        data is generated on the fly. Note how the producer is first
        called a 3 times before the parallel loop is initiated, and then
        called to generate new data on the fly. In this case the total
        number of iterations cannot be reported in the progress messages::

         >>> from math import sqrt
         >>> from sklearn.externals.joblib import Parallel, delayed

         >>> def producer():
         ...     for i in range(6):
         ...         print('Produced %s' % i)
         ...         yield i

         >>> out = Parallel(n_jobs=2, verbose=100, pre_dispatch='1.5*n_jobs')(
         ...                         delayed(sqrt)(i) for i in producer()) #doctest: +SKIP
         Produced 0
         Produced 1
         Produced 2
         [Parallel(n_jobs=2)]: Done   1 jobs       | elapsed:    0.0s
         Produced 3
         [Parallel(n_jobs=2)]: Done   2 jobs       | elapsed:    0.0s
         Produced 4
         [Parallel(n_jobs=2)]: Done   3 jobs       | elapsed:    0.0s
         Produced 5
         [Parallel(n_jobs=2)]: Done   4 jobs       | elapsed:    0.0s
         [Parallel(n_jobs=2)]: Done   5 out of   6 | elapsed:    0.0s remaining:    0.0s
         [Parallel(n_jobs=2)]: Done   6 out of   6 | elapsed:    0.0s finished
    '''
    def __init__(self, n_jobs=1, backend='multiprocessing', verbose=0,
                 pre_dispatch='2 * n_jobs', batch_size='auto',
                 temp_folder=None, max_nbytes='1M', mmap_mode='r'):
        self.verbose = verbose
        self._mp_context = DEFAULT_MP_CONTEXT
        if backend is None:
            # `backend=None` was supported in 0.8.2 with this effect
            backend = "multiprocessing"
        elif hasattr(backend, 'Pool') and hasattr(backend, 'Lock'):
            # Make it possible to pass a custom multiprocessing context as
            # backend to change the start method to forkserver or spawn or
            # preload modules on the forkserver helper process.
            self._mp_context = backend
            backend = "multiprocessing"
        if backend not in VALID_BACKENDS:
            raise ValueError("Invalid backend: %s, expected one of %r"
                             % (backend, VALID_BACKENDS))
        self.backend = backend
        self.n_jobs = n_jobs
        if (batch_size == 'auto'
                or isinstance(batch_size, Integral) and batch_size > 0):
            self.batch_size = batch_size
        else:
            raise ValueError(
                "batch_size must be 'auto' or a positive integer, got: %r"
                % batch_size)

        self.pre_dispatch = pre_dispatch
        self._temp_folder = temp_folder
        if isinstance(max_nbytes, _basestring):
            self._max_nbytes = 1024 * memstr_to_kbytes(max_nbytes)
        else:
            self._max_nbytes = max_nbytes
        self._mmap_mode = mmap_mode
        # Not starting the pool in the __init__ is a design decision, to be
        # able to close it ASAP, and not burden the user with closing it
        # unless they choose to use the context manager API with a with block.
        self._pool = None
        self._output = None
        self._jobs = list()
        self._managed_pool = False

        # This lock is used coordinate the main thread of this process with
        # the async callback thread of our the pool.
        self._lock = threading.Lock()

    def __enter__(self):
        self._managed_pool = True
        self._initialize_pool()
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self._terminate_pool()
        self._managed_pool = False

    def _effective_n_jobs(self):
        n_jobs = self.n_jobs
        if n_jobs == 0:
            raise ValueError('n_jobs == 0 in Parallel has no meaning')
        elif mp is None or n_jobs is None:
            # multiprocessing is not available or disabled, fallback
            # to sequential mode
            return 1
        elif n_jobs < 0:
            n_jobs = max(mp.cpu_count() + 1 + n_jobs, 1)
        return n_jobs

    def _initialize_pool(self):
        """Build a process or thread pool and return the number of workers"""
        n_jobs = self._effective_n_jobs()
        # The list of exceptions that we will capture
        self.exceptions = [TransportableException]

        if n_jobs == 1:
            # Sequential mode: do not use a pool instance to avoid any
            # useless dispatching overhead
            self._pool = None
        elif self.backend == 'threading':
            self._pool = ThreadPool(n_jobs)
        elif self.backend == 'multiprocessing':
            if mp.current_process().daemon:
                # Daemonic processes cannot have children
                self._pool = None
                warnings.warn(
                    'Multiprocessing-backed parallel loops cannot be nested,'
                    ' setting n_jobs=1',
                    stacklevel=3)
                return 1
            elif threading.current_thread().name != 'MainThread':
                # Prevent posix fork inside in non-main posix threads
                self._pool = None
                warnings.warn(
                    'Multiprocessing backed parallel loops cannot be nested'
                    ' below threads, setting n_jobs=1',
                    stacklevel=3)
                return 1
            else:
                already_forked = int(os.environ.get(JOBLIB_SPAWNED_PROCESS, 0))
                if already_forked:
                    raise ImportError('[joblib] Attempting to do parallel computing '
                            'without protecting your import on a system that does '
                            'not support forking. To use parallel-computing in a '
                            'script, you must protect your main loop using "if '
                            "__name__ == '__main__'"
                            '". Please see the joblib documentation on Parallel '
                            'for more information'
                        )
                # Set an environment variable to avoid infinite loops
                os.environ[JOBLIB_SPAWNED_PROCESS] = '1'

                # Make sure to free as much memory as possible before forking
                gc.collect()
                poolargs = dict(
                    max_nbytes=self._max_nbytes,
                    mmap_mode=self._mmap_mode,
                    temp_folder=self._temp_folder,
                    verbose=max(0, self.verbose - 50),
                )
                if self._mp_context is not None:
                    # Use Python 3.4+ multiprocessing context isolation
                    poolargs['context'] = self._mp_context
                self._pool = MemmapingPool(n_jobs, **poolargs)

                # We are using multiprocessing, we also want to capture
                # KeyboardInterrupts
                self.exceptions.extend([KeyboardInterrupt, WorkerInterrupt])
        else:
            raise ValueError("Unsupported backend: %s" % self.backend)
        return n_jobs

    def _terminate_pool(self):
        if self._pool is not None:
            self._pool.close()
            self._pool.terminate()  # terminate does a join()
            self._pool = None
            if self.backend == 'multiprocessing':
                os.environ.pop(JOBLIB_SPAWNED_PROCESS, 0)

    def _dispatch(self, batch):
        """Queue the batch for computing, with or without multiprocessing

        WARNING: this method is not thread-safe: it should be only called
        indirectly via dispatch_one_batch.

        """
        # If job.get() catches an exception, it closes the queue:
        if self._aborting:
            return

        if self._pool is None:
            job = ImmediateComputeBatch(batch)
            self._jobs.append(job)
            self.n_dispatched_batches += 1
            self.n_dispatched_tasks += len(batch)
            self.n_completed_tasks += len(batch)
            if not _verbosity_filter(self.n_dispatched_batches, self.verbose):
                self._print('Done %3i tasks       | elapsed: %s',
                        (self.n_completed_tasks,
                            short_format_time(time.time() - self._start_time)
                        ))
        else:
            dispatch_timestamp = time.time()
            cb = BatchCompletionCallBack(dispatch_timestamp, len(batch), self)
            job = self._pool.apply_async(SafeFunction(batch), callback=cb)
            self._jobs.append(job)
            self.n_dispatched_tasks += len(batch)
            self.n_dispatched_batches += 1

    def dispatch_next(self):
        """Dispatch more data for parallel processing

        This method is meant to be called concurrently by the multiprocessing
        callback. We rely on the thread-safety of dispatch_one_batch to protect
        against concurrent consumption of the unprotected iterator.

        """
        if not self.dispatch_one_batch(self._original_iterator):
            self._iterating = False
            self._original_iterator = None

    def dispatch_one_batch(self, iterator):
        """Prefetch the tasks for the next batch and dispatch them.

        The effective size of the batch is computed here.
        If there are no more jobs to dispatch, return False, else return True.

        The iterator consumption and dispatching is protected by the same
        lock so calling this function should be thread safe.

        """
        if self.batch_size == 'auto' and self.backend == 'threading':
            # Batching is never beneficial with the threading backend
            batch_size = 1
        elif self.batch_size == 'auto':
            old_batch_size = self._effective_batch_size
            batch_duration = self._smoothed_batch_duration
            if (batch_duration > 0 and
                    batch_duration < MIN_IDEAL_BATCH_DURATION):
                # The current batch size is too small: the duration of the
                # processing of a batch of task is not large enough to hide
                # the scheduling overhead.
                ideal_batch_size = int(
                    old_batch_size * MIN_IDEAL_BATCH_DURATION / batch_duration)
                # Multiply by two to limit oscilations between min and max.
                batch_size = max(2 * ideal_batch_size, 1)
                self._effective_batch_size = batch_size
                if self.verbose >= 10:
                    self._print("Batch computation too fast (%.4fs.) "
                                "Setting batch_size=%d.", (
                                    batch_duration, batch_size))
            elif (batch_duration > MAX_IDEAL_BATCH_DURATION and
                  old_batch_size >= 2):
                # The current batch size is too big. If we schedule overly long
                # running batches some CPUs might wait with nothing left to do
                # while a couple of CPUs a left processing a few long running
                # batches. Better reduce the batch size a bit to limit the
                # likelihood of scheduling such stragglers.
                self._effective_batch_size = batch_size = old_batch_size // 2
                if self.verbose >= 10:
                    self._print("Batch computation too slow (%.2fs.) "
                                "Setting batch_size=%d.", (
                                    batch_duration, batch_size))
            else:
                # No batch size adjustment
                batch_size = old_batch_size

            if batch_size != old_batch_size:
                # Reset estimation of the smoothed mean batch duration: this
                # estimate is updated in the multiprocessing apply_async
                # CallBack as long as the batch_size is constant. Therefore
                # we need to reset the estimate whenever we re-tune the batch
                # size.
                self._smoothed_batch_duration = 0
        else:
            # Fixed batch size strategy
            batch_size = self.batch_size
        with self._lock:
            tasks = BatchedCalls(itertools.islice(iterator, batch_size))
            if not tasks:
                # No more tasks available in the iterator: tell caller to stop.
                return False
            else:
                self._dispatch(tasks)
                return True

    def _print(self, msg, msg_args):
        """Display the message on stout or stderr depending on verbosity"""
        # XXX: Not using the logger framework: need to
        # learn to use logger better.
        if not self.verbose:
            return
        if self.verbose < 50:
            writer = sys.stderr.write
        else:
            writer = sys.stdout.write
        msg = msg % msg_args
        writer('[%s]: %s\n' % (self, msg))

    def print_progress(self):
        """Display the process of the parallel execution only a fraction
           of time, controlled by self.verbose.
        """
        if not self.verbose:
            return
        elapsed_time = time.time() - self._start_time

        # This is heuristic code to print only 'verbose' times a messages
        # The challenge is that we may not know the queue length
        if self._original_iterator:
            if _verbosity_filter(self.n_dispatched_batches, self.verbose):
                return
            self._print('Done %3i tasks      | elapsed: %s',
                        (self.n_completed_tasks,
                         short_format_time(elapsed_time),
                        ))
        else:
            index = self.n_dispatched_batches
            # We are finished dispatching
            total_tasks = self.n_dispatched_tasks
            # We always display the first loop
            if not index == 0:
                # Display depending on the number of remaining items
                # A message as soon as we finish dispatching, cursor is 0
                cursor = (total_tasks - index + 1
                          - self._pre_dispatch_amount)
                frequency = (total_tasks // self.verbose) + 1
                is_last_item = (index + 1 == total_tasks)
                if (is_last_item or cursor % frequency):
                    return
            remaining_time = (elapsed_time / (index + 1) *
                              (self.n_dispatched_tasks - index - 1.))
            self._print('Done %3i out of %3i | elapsed: %s remaining: %s',
                        (index + 1,
                         total_tasks,
                         short_format_time(elapsed_time),
                         short_format_time(remaining_time),
                        ))

    def retrieve(self):
        self._output = list()
        while self._iterating or len(self._jobs) > 0:
            if len(self._jobs) == 0:
                # Wait for an async callback to dispatch new jobs
                time.sleep(0.01)
                continue
            # We need to be careful: the job list can be filling up as
            # we empty it and Python list are not thread-safe by default hence
            # the use of the lock
            with self._lock:
                job = self._jobs.pop(0)
            try:
                self._output.extend(job.get())
            except tuple(self.exceptions) as exception:
                # Stop dispatching any new job in the async callback thread
                self._aborting = True

                if isinstance(exception, TransportableException):
                    # Capture exception to add information on the local
                    # stack in addition to the distant stack
                    this_report = format_outer_frames(context=10,
                                                      stack_start=1)
                    report = """Multiprocessing exception:
%s
---------------------------------------------------------------------------
Sub-process traceback:
---------------------------------------------------------------------------
%s""" % (this_report, exception.message)
                    # Convert this to a JoblibException
                    exception_type = _mk_exception(exception.etype)[0]
                    exception = exception_type(report)

                # Kill remaining running processes without waiting for
                # the results as we will raise the exception we got back
                # to the caller instead of returning any result.
                self._terminate_pool()
                if self._managed_pool:
                    # In case we had to terminate a managed pool, let
                    # us start a new one to ensure that subsequent calls
                    # to __call__ on the same Parallel instance will get
                    # a working pool as they expect.
                    self._initialize_pool()
                raise exception

    def __call__(self, iterable):
        if self._jobs:
            raise ValueError('This Parallel instance is already running')
        # A flag used to abort the dispatching of jobs in case an
        # exception is found
        self._aborting = False
        if not self._managed_pool:
            n_jobs = self._initialize_pool()
        else:
            n_jobs = self._effective_n_jobs()

        if self.batch_size == 'auto':
            self._effective_batch_size = 1

        iterator = iter(iterable)
        pre_dispatch = self.pre_dispatch

        if pre_dispatch == 'all' or n_jobs == 1:
            # prevent further dispatch via multiprocessing callback thread
            self._original_iterator = None
            self._pre_dispatch_amount = 0
        else:
            self._original_iterator = iterator
            if hasattr(pre_dispatch, 'endswith'):
                pre_dispatch = eval(pre_dispatch)
            self._pre_dispatch_amount = pre_dispatch = int(pre_dispatch)

            # The main thread will consume the first pre_dispatch items and
            # the remaining items will later be lazily dispatched by async
            # callbacks upon task completions.
            iterator = itertools.islice(iterator, pre_dispatch)

        self._start_time = time.time()
        self.n_dispatched_batches = 0
        self.n_dispatched_tasks = 0
        self.n_completed_tasks = 0
        self._smoothed_batch_duration = 0.0
        try:
            # Only set self._iterating to True if at least a batch
            # was dispatched. In particular this covers the edge
            # case of Parallel used with an exhausted iterator.
            while self.dispatch_one_batch(iterator):
                self._iterating = True
            else:
                self._iterating = False

            if pre_dispatch == "all" or n_jobs == 1:
                # The iterable was consumed all at once by the above for loop.
                # No need to wait for async callbacks to trigger to
                # consumption.
                self._iterating = False
            self.retrieve()
            # Make sure that we get a last message telling us we are done
            elapsed_time = time.time() - self._start_time
            self._print('Done %3i out of %3i | elapsed: %s finished',
                        (len(self._output), len(self._output),
                         short_format_time(elapsed_time)))
        finally:
            if not self._managed_pool:
                self._terminate_pool()
            self._jobs = list()
        output = self._output
        self._output = None
        return output

    def __repr__(self):
        return '%s(n_jobs=%s)' % (self.__class__.__name__, self.n_jobs)


# -*- coding: utf-8 -*-
"""
Created on Fri Mar 13 13:02:41 2015

Copyright 2015 Nicolo' Navarin

This file is part of scikit-learn-graph.

scikit-learn-graph is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

scikit-learn-graph is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with scikit-learn-graph.  If not, see <http://www.gnu.org/licenses/>.
"""
from scipy.sparse import csr_matrix
from ioskgraph import load_target
from ..graph import instance_to_graph
from sklearn.datasets.base import Bunch
#TODO import openbabel only if needed
#from obabel import obabel_to_eden
def dispatch(dataset):
    if dataset=="CAS":
        print "Loading bursi(CAS) dataset"
        g_it=load_graphs_bursi()
    elif dataset=="GDD":
        print "Loading GDD dataset"
        g_it=load_graphs_GDD()
    elif dataset=="CPDB":
        print "Loading CPDB dataset"
        g_it=load_graphs_CPDB()
    elif dataset=="AIDS":
        print "Loading AIDS dataset"
        g_it=load_graphs_AIDS()
    elif dataset=="NCI1":
        print "Loading NCI1 dataset"
        g_it=load_graphs_NCI1()
    elif dataset=="NCI109":
        print "Loading NCI109 dataset"
        g_it=load_graphs_NCI109()
    elif dataset=="NCI123":
        print "Loading NCI123 dataset"
        g_it=load_graphs_NCI123()
    elif dataset=="NCI_AIDS":
        print "Loading NCI_AIDS dataset"
        g_it=load_graphs_NCI_AIDS()
    elif dataset=="Chemical2":
        print "Loading LEUK40OV41LEUK47OV50 dataset"
        g_it=load_graphs_LEUK40OV41LEUK47OV50()
    elif dataset=="Chemical1":
        print "Loading LEUK40LEUK47OV41OV50 dataset"
        g_it=load_graphs_LEUK40LEUK47OV41OV50()
    elif dataset=="Chemical3":
        print "Loading LEUK40LEUK47OV41OV50LEUK40OV41LEUK47OV50 dataset"
        g_it=load_graphs_LEUK40LEUK47OV41OV50LEUK40OV41LEUK47OV50()
    elif dataset=="Chemical_reduced":
        print "Loading LEUK40OV41LEUK47OV50 REDUCED dataset"
        g_it=load_graphs_LEUK40OV41LEUK47OV50_reduced()
    elif dataset=="MUTAG":
        print "Loading MUTAG dataset"
        g_it=load_graphs_MUTAG()
    elif dataset=="enzymes":
        print "Loading enzymes dataset"
        g_it=load_graphs_enzymes()
    elif dataset=="proteins":
        print "Loading proteins dataset"
        g_it=load_graphs_proteins()
    elif dataset=="synthetic":
        print "Loading synthetic dataset"
        g_it=load_graphs_synthetic()
    elif dataset=="BZR":
        print "Loading BZR dataset"
        g_it=load_graphs_BZR()
    elif dataset=="COX2":
        print "Loading COX2 dataset"
        g_it=load_graphs_COX2()
    elif dataset=="DHFR":
        print "Loading DHFR dataset"
        g_it=load_graphs_DHFR()
    elif dataset=="PROTEINS_full":
        print "Loading PROTEINS_full dataset"
        g_it=load_graphs_PROTEINS_full()
    elif dataset=="LMdata":
        print "Loading LMdata dataset"
        g_it=load_graphs_LMdata()
    else:
        print "Unknown dataset name"
    return g_it

def convert_to_sparse_matrix(km):
    # translate dictionary to Compressed Sparse Row matrix
        if len(km) == 0:
            raise Exception('ERROR: something went wrong, empty feature_dict. Perhaps wrong data format, i.e. do nodes have the "viewpoint" attribute?')
        row, col, data = [], [], []
        ne = len(km)
        for i in range(ne):
            for j in range(ne):
                if (km[i][j]!=0):
                    row.append( i )
                    col.append( j )
                    data.append(km[i][j])
        print len(row),len(col),len(data)

        X = csr_matrix( (data,(row,col)), shape = (ne, ne))

        return X
def load_graphs_GDD():
    """Load the GDD graph dataset for graph classification..

    Returns
    -------
    data : Bunch
        Dictionary-like object with the following attributes :
        'graphs', the graphs in the dataset in Networkx format,  'target', the classification labels for each
        sample.
    """
    input_target_url='http://www.math.unipd.it/~nnavarin/datasets/GDD/GDD_labels.txt'
    input_data_url='http://www.math.unipd.it/~nnavarin/datasets/GDD/graphs.gspan'
    _target=load_target(input_target_url)
    g_it=instance_to_graph(input = input_data_url)
    gra=[i for i in g_it]
    print 'Loaded GDD graph dataset for graph classification.'
    print len(gra),'graphs.'
    return Bunch(graphs=gra,
    target=_target,
    labels=True,
    veclabels=False)

def load_graphs_MUTAG():
    """Load the MUTAG graph dataset for graph classification..

    Returns
    -------
    data : Bunch
        Dictionary-like object with the following attributes :
        'graphs', the graphs in the dataset in Networkx format,  'target', the classification labels for each
        sample.
    """
    from obabel import obabel_to_eden
    input_target_url='http://www.math.unipd.it/~nnavarin/datasets/MUTAG/mutag_188_target.txt'
    input_data_url='http://www.math.unipd.it/~nnavarin/datasets/MUTAG/mutag_188_data.can'
    _target=load_target(input_target_url)
    g_it=obabel_to_eden(input = input_data_url,file_type ='smi')

    gra=[i for i in g_it]
    print 'Loaded MUTAG graph dataset for graph classification.'
    print len(gra),'graphs.'
    return Bunch(graphs=gra,
    target=_target,
    labels=True,
    veclabels=False)

def load_graphs_CPDB():
    """Load the CPDB graph dataset for graph classification..

    Returns
    -------
    data : Bunch
        Dictionary-like object with the following attributes :
        'graphs', the graphs in the dataset in Networkx format,  'target', the classification labels for each
        sample.
    """
    input_target_url='http://www.math.unipd.it/~nnavarin/datasets/CPDB/mutagen_labels.tab'
    input_data_url='http://www.math.unipd.it/~nnavarin/datasets/CPDB/mutagen_smile.can'
    _target=load_target(input_target_url)
    from obabel import obabel_to_eden
    g_it=obabel_to_eden(input = input_data_url,file_type ='smi')

    gra=[i for i in g_it]
    print 'Loaded CPDB graph dataset for graph classification.'
    print len(gra),'graphs.'
    return Bunch(graphs=gra,
    target=_target,
    labels=True,
    veclabels=False)

def load_graphs_AIDS():
    """Load the AIDS graph dataset for graph classification..

    Returns
    -------
    data : Bunch
        Dictionary-like object with the following attributes :
        'graphs', the graphs in the dataset in Networkx format,  'target', the classification labels for each
        sample.
    """
    input_target_url='http://www.math.unipd.it/~nnavarin/datasets/AIDS/CAvsCM.y'
    input_data_url='http://www.math.unipd.it/~nnavarin/datasets/AIDS/CAvsCM.can'
    _target=load_target(input_target_url)
    from obabel import obabel_to_eden
    g_it=obabel_to_eden(input = input_data_url,file_type ='smi')

    gra=[i for i in g_it]
    print 'Loaded AIDS graph dataset for graph classification.'
    print len(gra),'graphs.'
    return Bunch(graphs=gra,
    target=_target,
    labels=True,
    veclabels=False)

def load_graphs_NCI1():
    """Load the NCI1 graph dataset for graph classification..

    Returns
    -------
    data : Bunch
        Dictionary-like object with the following attributes :
        'graphs', the graphs in the dataset in Networkx format,  'target', the classification labels for each
        sample.
    """
    input_target_url='http://www.math.unipd.it/~nnavarin/datasets/NCI1/NCI1_labels.txt'
    input_data_url='http://www.math.unipd.it/~nnavarin/datasets/NCI1/NCI1_graphs.gspan'
    _target=load_target(input_target_url)
    label_dict={}
    g_it=instance_to_graph(input = input_data_url)
    #g_it=instance_to_graph(input = input_data_url,label_dict=label_dict)

    print 'Loaded NCI1 graph dataset for graph classification.'
    return Bunch(graphs=[i for i in g_it],
    target=_target,
    #label_dict=label_dict,
    labels=True,
    veclabels=False)

def load_graphs_NCI109():
    """Load the NCI109 graph dataset for graph classification..

    Returns
    -------
    data : Bunch
        Dictionary-like object with the following attributes :
        'graphs', the graphs in the dataset in Networkx format,  'target', the classification labels for each
        sample.
    """
    input_target_url='http://www.math.unipd.it/~nnavarin/datasets/NCI109/NCI109_labels.txt'
    input_data_url='http://www.math.unipd.it/~nnavarin/datasets/NCI109/NCI109_graphs.gspan'
    _target=load_target(input_target_url)
    g_it=instance_to_graph(input = input_data_url)

    print 'Loaded NCI109 graph dataset for graph classification.'
    return Bunch(graphs=[i for i in g_it],
    target=_target,
    labels=True,
    veclabels=False)

def load_graphs_bursi():
    """Load the Bursi graph dataset for graph classification..

    Returns
    -------
    data : Bunch
        Dictionary-like object with the following attributes :
        'graphs', the graphs in the dataset in Networkx format,  'target', the classification labels for each
        sample.
    """
    input_target_url='http://www.bioinf.uni-freiburg.de/~costa/bursi.target'
    input_data_url='http://www.bioinf.uni-freiburg.de/~costa/bursi.gspan'
    _target=load_target(input_target_url)
    g_it=instance_to_graph(input = input_data_url)

    print 'Loaded Bursi graph dataset for graph classification.'
    return Bunch(graphs=[i for i in g_it],
    target=_target,
    labels=True,
    veclabels=False)

def load_graphs_enzymes():
    """Load the ENZYMES graph dataset for (multiclass) graph classification from:
    Schomburg, I., Chang, A., Ebeling, C., Gremse, M., Heldt, C., Huhn, G., & Schomburg, D. (2004).
    BRENDA, the enzyme database: updates and major new developments.
    Nucleic Acids Research, 32, D431–D433. doi:10.1093/nar/gkh081

    Returns
    -------
    data : Bunch
        Dictionary-like object with the following attributes :
        'graphs', the graphs in the dataset in Networkx format,  'target', the classification labels for each
        sample.
    """
    input_target_url='http://www.math.unipd.it/~nnavarin/datasets/ENZYMES.labels'
    input_data_url='http://www.math.unipd.it/~nnavarin/datasets/ENZYMES.gspan'
    #input_target_url='datasets/ENZYMES.labels'
    #input_data_url='datasets/ENZYMES.gspan'

    _target=load_target(input_target_url)
    g_it=instance_to_graph(input = input_data_url) #url
    #return Bunch(data=flat_data,
    #            target=target.astype(np.int),
    #           target_names=np.arange(10),
    #            images=images,
    #            DESCR=descr)
    print 'Loaded ENZYMES graph dataset for (multiclass) graph classification from:'
    print 'Schomburg, I., Chang, A., Ebeling, C., Gremse, M., Heldt, C., Huhn, G., & Schomburg, D. (2004).'
    print 'BRENDA, the enzyme database: updates and major new developments.'
    print 'Nucleic Acids Research, 32, D431–D433. doi:10.1093/nar/gkh081'
    return Bunch(graphs=[i for i in g_it],
    target=_target,
    labels=True,
    veclabels=True)

def load_graphs_proteins():
    """Load the PROTEINS graph dataset for graph classification from:
        Dobson, P. D., & Doig, A. J. (2003)
        Distinguishing enzyme structures from non-enzymes without alignments.
        Journal of Molecular Biology, 330, 771–783. doi:10.1016/S0022-2836(03)00628-4

    Returns
    -------
    data : Bunch
        Dictionary-like object with the following attributes :
        'graphs', the graphs in the dataset in Networkx format,  'target', the classification labels for each
        sample.
    """
    input_target_url='http://www.math.unipd.it/~nnavarin/datasets/PROTEINS.labels'
    input_data_url='http://www.math.unipd.it/~nnavarin/datasets/PROTEINS.gspan'

    _target=load_target(input_target_url)
    g_it=instance_to_graph(input = input_data_url) #url

    print 'Loaded PROTEINS graph dataset for graph classification from:'
    print 'Dobson, P. D., & Doig, A. J. (2003)'
    print 'Distinguishing enzyme structures from non-enzymes without alignments.'
    print 'Journal of Molecular Biology, 330, 771–783. doi:10.1016/S0022-2836(03)00628-4'
    return Bunch(graphs=[i for i in g_it],
    target=_target,
    labels=True,
    veclabels=True)

def load_graphs_synthetic():
    """Load the SYNTHETIC graph dataset for graph classification from:
        Feragen, A., Kasenburg, N., Petersen, J., de Bruijne, M., & Borgwardt, K. M. (2013)
        Scalable kernels for graphs with continuous attributes.
        In Neural Information Processing Systems (NIPS) 2013 (pp. 216–224).
        Retrieved from http://papers.nips.cc/paper/5155-scalable-kernels-for-graphs-with-continuous-attributes.pdf
    Returns
    -------
    data : Bunch
        Dictionary-like object with the following attributes :
        'graphs', the graphs in the dataset in Networkx format,  'target', the classification labels for each
        sample.
    """
    input_target_url='http://www.math.unipd.it/~nnavarin/datasets/SYNTHETICnew.labels'
    input_data_url='http://www.math.unipd.it/~nnavarin/datasets/SYNTHETICnew.gspan'
    #input_target_url='datasets/ENZYMES.labels'
    #input_data_url='datasets/ENZYMES.gspan'

    _target=load_target(input_target_url)
    g_it=instance_to_graph(input = input_data_url) #url
    #return Bunch(data=flat_data,
    #            target=target.astype(np.int),
    #           target_names=np.arange(10),
    #            images=images,
    #            DESCR=descr)
    g=[i for i in g_it]
    for i in g:
        for n in i.nodes():
            i.node[n]['label']=str(i.degree(n))

    print 'Loaded SYNTHETIC graph dataset for graph classification from:'
    print 'Feragen, A., Kasenburg, N., Petersen, J., de Bruijne, M., & Borgwardt, K. M. (2013)'
    print 'Scalable kernels for graphs with continuous attributes.'
    print 'In Neural Information Processing Systems (NIPS) 2013 (pp. 216–224).'
    return Bunch(graphs=g,
    target=_target,
    labels=True,
    veclabels=True)

def load_graphs_BZR():
    """Load the BZR graph dataset for graph classification from:
        Neumann, M., Garnett R., Bauckhage Ch., Kersting K.: Propagation Kernels: Efficient Graph
        Kernels from Propagated Information. Under review at MLJ.

    Returns
    -------
    data : Bunch
        Dictionary-like object with the following attributes :
        'graphs', the graphs in the dataset in Networkx format,  'target', the classification labels for each
        sample.
    """
    input_target_url='http://www.math.unipd.it/~nnavarin/datasets/BZR_graph_labels.txt'
    input_data_url='http://www.math.unipd.it/~nnavarin/datasets/BZR.gspan'
    #input_target_url='datasets/ENZYMES.labels'
    #input_data_url='datasets/ENZYMES.gspan'

    _target=load_target(input_target_url)
    g_it=instance_to_graph(input = input_data_url) #url
    #return Bunch(data=flat_data,
    #            target=target.astype(np.int),
    #           target_names=np.arange(10),
    #            images=images,
    #            DESCR=descr)
    print 'Loaded BZR graph dataset for  graph classification from:'
    print 'Neumann, M., Garnett R., Bauckhage Ch., Kersting K.: Propagation Kernels: Efficient Graph'
    print 'Kernels from Propagated Information. MLJ 2015.'
    return Bunch(graphs=[i for i in g_it],
    target=_target,
    labels=True,
    veclabels=True)

def load_graphs_COX2():
    """Load the COX2 graph dataset for graph classification from:
        Neumann, M., Garnett R., Bauckhage Ch., Kersting K.: Propagation Kernels: Efficient Graph
        Kernels from Propagated Information. Under review at MLJ.

    Returns
    -------
    data : Bunch
        Dictionary-like object with the following attributes :
        'graphs', the graphs in the dataset in Networkx format,  'target', the classification labels for each
        sample.
    """
    input_target_url='http://www.math.unipd.it/~nnavarin/datasets/COX2_graph_labels.txt'
    input_data_url='http://www.math.unipd.it/~nnavarin/datasets/COX2.gspan'
    #input_target_url='datasets/ENZYMES.labels'
    #input_data_url='datasets/ENZYMES.gspan'

    _target=load_target(input_target_url)
    g_it=instance_to_graph(input = input_data_url) #url
    #return Bunch(data=flat_data,
    #            target=target.astype(np.int),
    #           target_names=np.arange(10),
    #            images=images,
    #            DESCR=descr)
    print 'Loaded COX2 graph dataset for  graph classification from:'
    print 'Neumann, M., Garnett R., Bauckhage Ch., Kersting K.: Propagation Kernels: Efficient Graph'
    print 'Kernels from Propagated Information. MLJ 2015.'
    return Bunch(graphs=[i for i in g_it],
    target=_target,
    labels=True,
    veclabels=True)

def load_graphs_DHFR():
    """Load the DHFR graph dataset for graph classification from:
        Neumann, M., Garnett R., Bauckhage Ch., Kersting K.: Propagation Kernels: Efficient Graph
        Kernels from Propagated Information. Under review at MLJ.

    Returns
    -------
    data : Bunch
        Dictionary-like object with the following attributes :
        'graphs', the graphs in the dataset in Networkx format,  'target', the classification labels for each
        sample.
    """
    input_target_url='http://www.math.unipd.it/~nnavarin/datasets/DHFR_graph_labels.txt'
    input_data_url='http://www.math.unipd.it/~nnavarin/datasets/DHFR.gspan'
    #input_target_url='datasets/ENZYMES.labels'
    #input_data_url='datasets/ENZYMES.gspan'

    _target=load_target(input_target_url)
    g_it=instance_to_graph(input = input_data_url) #url
    #return Bunch(data=flat_data,
    #            target=target.astype(np.int),
    #           target_names=np.arange(10),
    #            images=images,
    #            DESCR=descr)
    print 'Loaded DHFR graph dataset for  graph classification from:'
    print 'Neumann, M., Garnett R., Bauckhage Ch., Kersting K.: Propagation Kernels: Efficient Graph'
    print 'Kernels from Propagated Information. MLJ 2015.'
    return Bunch(graphs=[i for i in g_it],
    target=_target,
    labels=True,
    veclabels=True)

def load_graphs_PROTEINS_full():
    """Load the PROTEINS_full graph dataset for graph classification from:
        Neumann, M., Garnett R., Bauckhage Ch., Kersting K.: Propagation Kernels: Efficient Graph
        Kernels from Propagated Information. Under review at MLJ.

    Returns
    -------
    data : Bunch
        Dictionary-like object with the following attributes :
        'graphs', the graphs in the dataset in Networkx format,  'target', the classification labels for each
        sample.
    """
    input_target_url='http://www.math.unipd.it/~nnavarin/datasets/PROTEINS_full_graph_labels.txt'
    input_data_url='http://www.math.unipd.it/~nnavarin/datasets/PROTEINS_full.gspan'
    #input_target_url='datasets/ENZYMES.labels'
    #input_data_url='datasets/ENZYMES.gspan'

    _target=load_target(input_target_url)
    g_it=instance_to_graph(input = input_data_url) #url
    #return Bunch(data=flat_data,
    #            target=target.astype(np.int),
    #           target_names=np.arange(10),
    #            images=images,
    #            DESCR=descr)
    print 'Loaded PROTEINS_full graph dataset for  graph classification from:'
    print 'Neumann, M., Garnett R., Bauckhage Ch., Kersting K.: Propagation Kernels: Efficient Graph'
    print 'Kernels from Propagated Information. MLJ 2015.'
    return Bunch(graphs=[i for i in g_it],
    target=_target,
    labels=True,
    veclabels=True)

def load_graphs_NCI123():
    """Load the NCI123 graph dataset for graph classification..

    Returns
    -------
    data : Bunch
        Dictionary-like object with the following attributes :
        'graphs', the graphs in the dataset in Networkx format,  'target', the classification labels for each
        sample.
    """
    from obabel import obabel_to_eden

    input_target_url='http://www.math.unipd.it/~nnavarin/datasets/Leukemia/leukemia_labels.txt'
    input_data_url='http://www.math.unipd.it/~nnavarin/datasets/Leukemia/leukemia.smile'
    _target=load_target(input_target_url)
    g_it=obabel_to_eden(input = input_data_url,file_type ='can')

    gra=[i for i in g_it]
    print 'Loaded NCI123 graph dataset for graph classification.'
    print len(gra),'graphs.'
    return Bunch(graphs=gra,
    target=_target,
    labels=True,
    veclabels=False)

def load_graphs_NCI_AIDS():
    """Load the NCI antiHIV graph dataset for graph classification..

    Returns
    -------
    data : Bunch
        Dictionary-like object with the following attributes :
        'graphs', the graphs in the dataset in Networkx format,  'target', the classification labels for each
        sample.
    """
    input_target_url='http://www.math.unipd.it/~nnavarin/datasets/NCI_AIDS/AIDO99SD_numeric.labels'
    input_data_url='http://www.math.unipd.it/~nnavarin/datasets/NCI_AIDS/AIDO99SD.gspan'
    _target=load_target(input_target_url)
    g_it=instance_to_graph(input = input_data_url)

    print 'Loaded NCI antiHIV dataset graph dataset for graph classification.'
    return Bunch(graphs=[i for i in g_it],
    target=_target,
    labels=True,
    veclabels=False)

def load_graphs_LEUK40OV41LEUK47OV50():
    #chemical2
    """Load the Chemical2 graph dataset for graph classification from
	An Empirical Study on Budget-Aware Online Kernel Algorithms for Streams of Graphs
	G Da San Martino, N Navarin, A Sperduti

    Returns
    -------
    data : Bunch
        Dictionary-like object with the following attributes :
        'graphs', the graphs in the dataset in Networkx format,  'target', the classification labels for each
        sample.
    """
    from obabel import obabel_to_eden

    input_target_url='http://www.math.unipd.it/~nnavarin/datasets/DATASET_DRIFT_LEUK40OV41LEUK47OV50/labels.txt'
    input_data_url='http://www.math.unipd.it/~nnavarin/datasets/DATASET_DRIFT_LEUK40OV41LEUK47OV50/stream.can'
    _target=load_target(input_target_url)
    label_dict={}
    counter=[1]

    g_it=obabel_to_eden(input = input_data_url,file_type ='can',dict_labels=label_dict,counter=counter)

    gra=[i for i in g_it]
    print 'Loaded Chemical graph dataset for graph classification.'
    print len(gra),'graphs.'
    return Bunch(graphs=gra,
    label_dict=label_dict,
    target=_target,
    labels=True,
    veclabels=False)

def load_graphs_LEUK40LEUK47OV41OV50():
    #chemical1
    """Load the Chemical1 graph dataset for graph classification from
	An Empirical Study on Budget-Aware Online Kernel Algorithms for Streams of Graphs
	G Da San Martino, N Navarin, A Sperduti

    Returns
    -------
    data : Bunch
        Dictionary-like object with the following attributes :
        'graphs', the graphs in the dataset in Networkx format,  'target', the classification labels for each
        sample.
    """
    from obabel import obabel_to_eden

    input_target_url='http://www.math.unipd.it/~nnavarin/datasets/DATASET_DRIFT_NEW/labels.txt'
    input_data_url='http://www.math.unipd.it/~nnavarin/datasets/DATASET_DRIFT_NEW/stream.can'
    _target=load_target(input_target_url)
    label_dict={}
    counter=[1]

    g_it=obabel_to_eden(input = input_data_url,file_type ='can',dict_labels=label_dict,counter=counter)

    gra=[i for i in g_it]
    print 'Loaded Chemical graph dataset for graph classification.'
    print len(gra),'graphs.'
    return Bunch(graphs=gra,
    label_dict=label_dict,
    target=_target,
    labels=True,
    veclabels=False)

def load_graphs_LEUK40OV41LEUK47OV50_reduced():
    """Load the Chemical graph dataset for graph classification from
	An Empirical Study on Budget-Aware Online Kernel Algorithms for Streams of Graphs
	G Da San Martino, N Navarin, A Sperduti

    Returns
    -------
    data : Bunch
        Dictionary-like object with the following attributes :
        'graphs', the graphs in the dataset in Networkx format,  'target', the classification labels for each
        sample.
    """
    from obabel import obabel_to_eden

    input_target_url='http://www.math.unipd.it/~nnavarin/datasets/DATASET_DRIFT_LEUK40OV41LEUK47OV50/labels_reduced_101.txt'
    input_data_url='http://www.math.unipd.it/~nnavarin/datasets/DATASET_DRIFT_LEUK40OV41LEUK47OV50/stream_reduced_101.can'
    _target=load_target(input_target_url)
    label_dict={}
    counter=[1]
    g_it=obabel_to_eden(input = input_data_url,file_type ='can',dict_labels=label_dict,counter=counter)

    gra=[i for i in g_it]
    print 'Loaded Chemical graph dataset for graph classification.'
    print len(gra),'graphs.'
    return Bunch(graphs=gra,
    label_dict=label_dict,
    target=_target,
    labels=True,
    veclabels=False)

def load_graphs_LEUK40LEUK47OV41OV50LEUK40OV41LEUK47OV50():
    #chemical1
    """Load the Chemical1 graph dataset for graph classification from
	An Empirical Study on Budget-Aware Online Kernel Algorithms for Streams of Graphs
	G Da San Martino, N Navarin, A Sperduti

    Returns
    -------
    data : Bunch
        Dictionary-like object with the following attributes :
        'graphs', the graphs in the dataset in Networkx format,  'target', the classification labels for each
        sample.
    """
    from obabel import obabel_to_eden

    input_target_url='http://www.math.unipd.it/~nnavarin/datasets/DATASET_CHEMICAL_BIG/labels.txt'
    input_data_url='http://www.math.unipd.it/~nnavarin/datasets/DATASET_CHEMICAL_BIG/stream.can'
    _target=load_target(input_target_url)
    label_dict={}
    counter=[1]

    g_it=obabel_to_eden(input = input_data_url,file_type ='can',dict_labels=label_dict,counter=counter)

    gra=[i for i in g_it]
    print 'Loaded Chemical graph dataset for graph classification.'
    print len(gra),'graphs.'
    return Bunch(graphs=gra,
    label_dict=label_dict,
    target=_target,
    labels=True,
    veclabels=False)

def load_graphs_LMdata():
    """Load the LMdata graph dataset for graph classification..

    Returns
    -------
    data : Bunch
        Dictionary-like object with the following attributes :
        'graphs', the graphs in the dataset in Networkx format,  'target', the classification labels for each
        sample.
    """
    input_target_url='http://www.math.unipd.it/~nnavarin/datasets/LMdata/labels.txt.standardized'
    input_data_url='http://www.math.unipd.it/~nnavarin/datasets//LMdata/graphs.gspan.standardized'
    _target=load_target(input_target_url)
    label_dict={}
    counter=[1]
    g_it=instance_to_graph(input_data_url,label_dict,counter)

    print 'Loaded LMdata graph dataset for graph classification.'
    return Bunch(graphs=[i for i in g_it],
    label_dict=label_dict,
    target=_target,
    labels=True,
    veclabels=False)


import os
import pandas as pd
import numpy as np
import sqlite3
import requests
import time

def fix_location(lid, new_address):

    pd.set_option('display.mpl_style', 'default')

    PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
    DATABASE1 = os.path.join(PROJECT_ROOT, 'dbs', 'licensees.db')

    conn1 = sqlite3.connect(DATABASE1)
    c = conn1.cursor()

    c.execute('SELECT address, latitude, longitude FROM licensees WHERE lid = ?',[lid])

    old_info = c.fetchone()
    old_latitude = old_info[1]
    old_longitude = old_info[2]

    if old_latitude or old_longitude:
        return 'No need to fix. Aborting geocode call.'

    api_key = 'NOT MY REAL KEY!!!!!'
    baseurl = 'https://maps.googleapis.com/maps/api/geocode/json?key='+api_key+'&address='
    fullurl = baseurl + new_address

    page = requests.get(fullurl)

    latitude = page.json()['results'][0]['geometry']['location']['lat']
    longitude = page.json()['results'][0]['geometry']['location']['lng']

    c.execute('UPDATE licensees SET address = ?, latitude = ?, longitude = ? WHERE lid = ?',[new_address, latitude, longitude, lid])

    conn1.commit()
    c.close()

    return 'Good Fix'

# Manually fixed addresses
fix_location(233,'US Customs House Chestnut Street Philadelphia PA')
time.sleep(.2)
fix_location(43444, '431 South Streeet Philadelphia PA')
time.sleep(.2)
fix_location(45162, '2457 Grant Ave Philadelphia PA 19114')
time.sleep(.2)
fix_location(69585, '2400 Strawberry Mansion Drive Philadelphia, PA 19132')
time.sleep(.2)
fix_location(44218, 'Chickie and Petes Roosevelt Boulevard, Philadelphia, PA 19116')
time.sleep(.2)
fix_location(48788, 'Diamond Club at Mitten Hall 1913 North Broad Street Philadelphia, PA 19122')
time.sleep(.2)
fix_location(64349, '51 North 12th Street Philadelphia, PA 19107')
time.sleep(.2)
fix_location(64754, '1420 Locust Street Philadelphia PA 19102')
time.sleep(.2)
fix_location(50302, '39 Snyder Ave Philadelphia PA 19148')
time.sleep(.2)
fix_location(61215, '9910 Frankford Ave Philadelphia PA 19114')
time.sleep(.2)
fix_location(65590, '11000 E Roosevelt BLVD Philadelphia PA')
time.sleep(.2)
fix_location(26715, 'Knights Road Shopping Center 4018 Woodhaven Road Philadelphia, PA 19154')
time.sleep(.2)
fix_location(66741, '9183 Roosevelt BLVD Philadelphia PA 19114')
time.sleep(.2)
fix_location(65221, '129 S 30th St Philadelphia PA 19104')
time.sleep(.2)
fix_location(23775, 'The Bellevue Philadelphia PA 19103')
time.sleep(.2)
fix_location(55796, '5765 Wister St Philadelphia PA 19138')
time.sleep(.2)
fix_location(25469, 'Market East Philadelphia PA 19107')
time.sleep(.2)
fix_location(1140, 'torresdale and decatour, philadelphia pa')


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

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np

from tensorflow.contrib.learn.python.learn.dataframe import tensorflow_dataframe as df
from tensorflow.python.platform import test

# pylint: disable=g-import-not-at-top
try:
  import pandas as pd
  HAS_PANDAS = True
except ImportError:
  HAS_PANDAS = False

class SumTestCase(test.TestCase):
  """Test class for `Sum` transform."""

  def testSum(self):
    if not HAS_PANDAS:
      return
    num_rows = 100

    pandas_df = pd.DataFrame({
        "a": np.arange(num_rows),
        "b": np.arange(num_rows, 2 * num_rows)
    })

    frame = df.TensorFlowDataFrame.from_pandas(
        pandas_df, shuffle=False, batch_size=num_rows)

    frame["a+b"] = frame["a"] + frame["b"]

    expected_sum = pandas_df["a"] + pandas_df["b"]
    actual_sum = frame.run_one_batch()["a+b"]
    np.testing.assert_array_equal(expected_sum, actual_sum)

class DifferenceTestCase(test.TestCase):
  """Test class for `Difference` transform."""

  def testDifference(self):
    if not HAS_PANDAS:
      return
    num_rows = 100

    pandas_df = pd.DataFrame({
        "a": np.arange(num_rows),
        "b": np.arange(num_rows, 2 * num_rows)
    })

    frame = df.TensorFlowDataFrame.from_pandas(
        pandas_df, shuffle=False, batch_size=num_rows)

    frame["a-b"] = frame["a"] - frame["b"]

    expected_diff = pandas_df["a"] - pandas_df["b"]
    actual_diff = frame.run_one_batch()["a-b"]
    np.testing.assert_array_equal(expected_diff, actual_diff)

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


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

"""Experiment class collecting information needed for a single training run."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import contextlib
import time

from tensorflow.contrib.framework import deprecated
from tensorflow.contrib.framework import deprecated_arg_values
from tensorflow.contrib.learn.python.learn import evaluable
from tensorflow.contrib.learn.python.learn import monitors
from tensorflow.contrib.learn.python.learn import trainable
from tensorflow.contrib.learn.python.learn.estimators._sklearn import NotFittedError
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.training import server_lib

__all__ = ["Experiment"]

class Experiment(object):
  """Experiment is a class containing all information needed to train a model.

  After an experiment is created (by passing an Estimator and inputs for
  training and evaluation), an Experiment instance knows how to invoke training
  and eval loops in a sensible fashion for distributed training.
  """

  @deprecated_arg_values(
      "2016-10-23",
      "local_eval_frequency is deprecated as local_run will be renamed to "
      "train_and_evaluate. Use min_eval_frequency and call train_and_evaluate "
      "instead. Note, however, that the default for min_eval_frequency is 1, "
      "meaning models will be evaluated every time a new checkpoint is "
      "available. In contrast, the default for local_eval_frequency is None, "
      "resulting in evaluation occurring only after training has completed. "
      "min_eval_frequency is ignored when calling the deprecated local_run.",
      local_eval_frequency=None)
  def __init__(self,
               estimator,
               train_input_fn,
               eval_input_fn,
               eval_metrics=None,
               train_steps=None,
               eval_steps=100,
               train_monitors=None,
               local_eval_frequency=None,
               eval_delay_secs=120,
               continuous_eval_throttle_secs=60,
               min_eval_frequency=1):
    """Constructor for `Experiment`.

    Creates an Experiment instance. None of the functions passed to this
    constructor are executed at construction time. They are stored and used
    when a method is executed which requires it.

    Args:
      estimator: Object implementing `Trainable` and `Evaluable`.
      train_input_fn: function, returns features and labels for training.
      eval_input_fn: function, returns features and labels for evaluation. If
        `eval_steps` is `None`, this should be configured only to produce for a
        finite number of batches (generally, 1 epoch over the evaluation data).
      eval_metrics: `dict` of string, metric function. If `None`, default set
        is used.
      train_steps: Perform this many steps of training. `None`, the default,
        means train forever.
      eval_steps: `evaluate` runs until input is exhausted (or another exception
        is raised), or for `eval_steps` steps, if specified.
      train_monitors: A list of monitors to pass to the `Estimator`'s `fit`
        function.
      local_eval_frequency: Frequency of running eval in steps,
        when running locally. If `None`, runs evaluation only at the end of
        training.
      eval_delay_secs: Start evaluating after waiting for this many seconds.
      continuous_eval_throttle_secs: Do not re-evaluate unless the last
        evaluation was started at least this many seconds ago for
        continuous_eval().
      min_eval_frequency: (applies only to train_and_evaluate). the minimum
        number of steps between evaluations. Of course, evaluation does not
        occur if no new snapshot is available, hence, this is the minimum.

    Raises:
      ValueError: if `estimator` does not implement `Evaluable` and `Trainable`.
    """
    if not isinstance(estimator, evaluable.Evaluable):
      raise ValueError("`estimator` must implement `Evaluable`.")
    if not isinstance(estimator, trainable.Trainable):
      raise ValueError("`estimator` must implement `Trainable`.")
    super(Experiment, self).__init__()
    self._estimator = estimator
    self._train_input_fn = train_input_fn
    self._eval_input_fn = eval_input_fn
    self._eval_metrics = eval_metrics
    self._train_steps = train_steps
    self._eval_steps = eval_steps
    self._train_monitors = train_monitors
    self._local_eval_frequency = local_eval_frequency
    self._eval_delay_secs = eval_delay_secs
    self._continuous_eval_throttle_secs = continuous_eval_throttle_secs
    self._min_eval_frequency = min_eval_frequency

  @property
  def estimator(self):
    return self._estimator

  def train(self, delay_secs=None):
    """Fit the estimator using the training data.

    Train the estimator for `self._train_steps` steps, after waiting for
    `delay_secs` seconds. If `self._train_steps` is `None`, train forever.

    Args:
      delay_secs: Start training after this many seconds.

    Returns:
      The trained estimator.
    """
    start = time.time()

    # Start the server, if needed. It's important to start the server before
    # we (optionally) sleep for the case where no device_filters are set.
    # Otherwise, the servers will wait to connect to each other before starting
    # to train. We might as well start as soon as we can.
    if self._estimator.config.cluster_spec and self._estimator.config.master:
      self._start_server()

    if delay_secs is None:
      task_id = self._estimator.config.task or 0
      delay_secs = min(60, task_id * 5)

    if delay_secs:
      elapsed_secs = time.time() - start
      remaining = delay_secs - elapsed_secs
      logging.info("Waiting %d secs before starting training.", remaining)
      time.sleep(delay_secs)

    return self._estimator.fit(input_fn=self._train_input_fn,
                               max_steps=self._train_steps,
                               monitors=self._train_monitors)

  def evaluate(self, delay_secs=None):
    """Evaluate on the evaluation data.

    Runs evaluation on the evaluation data and returns the result. Runs for
    `self._eval_steps` steps, or if it's `None`, then run until input is
    exhausted or another exception is raised. Start the evaluation after
    `delay_secs` seconds, or if it's `None`, defaults to using
    `self._eval_delay_secs` seconds.

    Args:
      delay_secs: Start evaluating after this many seconds. If `None`, defaults
        to using `self._eval_delays_secs`.

    Returns:
      The result of the `evaluate` call to the `Estimator`.
    """
    if delay_secs is None:
      delay_secs = self._eval_delay_secs

    if delay_secs:
      logging.info("Waiting %d secs before starting eval.", delay_secs)
      time.sleep(delay_secs)

    return self._estimator.evaluate(input_fn=self._eval_input_fn,
                                    steps=self._eval_steps,
                                    metrics=self._eval_metrics,
                                    name="one_pass")

  @deprecated(
      "2016-10-23",
      "local_run will be renamed to train_and_evaluate and the new default "
      "behavior will be to run evaluation every time there is a new "
      "checkpoint.")
  def local_run(self):
    with _new_attr_context(self, "_min_eval_frequency"):
      self._min_eval_frequency = self._local_eval_frequency
      return self.train_and_evaluate()

  def _continuous_eval(self,
                       input_fn,
                       name,
                       delay_secs,
                       throttle_delay_secs):
    """Run continuous eval.

    Runs infinite eval on the evaluation data set. This function starts
    evaluating after `delay_secs` seconds and then runs no more than one
    evaluation (with `self._eval_steps` steps each time) per
    `throttle_delay_secs`. It never returns.

    Args:
      input_fn: The input to use for this eval.
      name: A string appended to the folder name of evaluation results.
      delay_secs: Start evaluating after this many seconds. If None, defaults to
        self._eval_delay_secs.
      throttle_delay_secs: Do not re-evaluate unless the last evaluation was
        started at least this many seconds ago. If None, defaults to
        self._continuous_eval_throttle_secs.
    """
    if delay_secs is None:
      delay_secs = self._eval_delay_secs
    if throttle_delay_secs is None:
      throttle_delay_secs = self._continuous_eval_throttle_secs

    if delay_secs:
      logging.info("Waiting %f secs before starting eval.", delay_secs)
      time.sleep(delay_secs)

    last_fitted_error_time = 0
    while True:
      start = time.time()
      try:
        self._estimator.evaluate(input_fn=input_fn,
                                 steps=self._eval_steps,
                                 metrics=self._eval_metrics,
                                 name=name)
      except NotFittedError:
        # Print warning message every 10 mins.
        if time.time() - last_fitted_error_time > 600:
          logging.warning(
              "Estimator is not fitted yet. "
              "Will start an evaluation when a checkpoint will be ready.")
          last_fitted_error_time = time.time()

      duration = time.time() - start
      if duration < throttle_delay_secs:
        difference = throttle_delay_secs - duration
        logging.info("Waiting %f secs before starting next eval run.",
                     difference)
        time.sleep(difference)

  def continuous_eval(self, delay_secs=None, throttle_delay_secs=None):
    self._continuous_eval(self._eval_input_fn,
                          name="continuous",
                          delay_secs=delay_secs,
                          throttle_delay_secs=throttle_delay_secs)

  def continuous_eval_on_train_data(self,
                                    delay_secs=None,
                                    throttle_delay_secs=None):
    self._continuous_eval(self._train_input_fn,
                          name="continuous_on_train_data",
                          delay_secs=delay_secs,
                          throttle_delay_secs=throttle_delay_secs)

  def train_and_evaluate(self):
    """Interleaves training and evaluation.

    The frequency of evaluation is controlled by the contructor arg
    `min_eval_frequency`. When this parameter is None or 0, evaluation happens
    only after training has completed. Note that evaluation cannot happen
    more frequently than checkpoints are taken. If no new snapshots are
    available when evaluation is supposed to occur, then evaluation doesn't
    happen for another `min_eval_frequency` steps (assuming a checkpoint is
    available at that point). Thus, settings `min_eval_frequency` to 1 means
    that the model will be evaluated everytime there is a new checkpoint.

    This is particular useful for a "Master" task in the cloud, whose
    responsibility it is to take checkpoints, evaluate those checkpoints,
    and write out summaries. Participating in training as the supervisor
    allows such a task to accomplish the first and last items, while
    performing evaluation allows for the second.

    Returns:
      The result of the `evaluate` call to the `Estimator`.
    """
    # The directory to which evaluation summaries are written are determined
    # by adding a suffix to 'eval'; that suffix is the 'name' parameter to
    # the various evaluate(...) methods. By setting it to None, we force
    # the directory name to simply be 'eval'.
    eval_dir_suffix = None

    # We set every_n_steps to 1, but evaluation only occurs when a new
    # snapshot is available. If, by the time we finish evaluation
    # there is a new snapshot, then we just evaluate again. Otherwise,
    # we keep training until one becomes available.
    with _new_attr_context(self, "_train_monitors"):
      self._train_monitors = self._train_monitors or []
      if self._min_eval_frequency:
        self._train_monitors += [monitors.ValidationMonitor(
            input_fn=self._eval_input_fn, eval_steps=self._eval_steps,
            metrics=self._eval_metrics, every_n_steps=self._min_eval_frequency,
            name=eval_dir_suffix,
        )]
      self.train(delay_secs=0)

    return self._estimator.evaluate(input_fn=self._eval_input_fn,
                                    steps=self._eval_steps,
                                    metrics=self._eval_metrics,
                                    name=eval_dir_suffix)

  def run_std_server(self):
    """Starts a TensorFlow server and joins the serving thread.

    Typically used for parameter servers.

    Raises:
      ValueError: if not enough information is available in the estimator's
        config to create a server.
    """
    self._start_server().join()

  def test(self):
    """Tests training and evaluating the estimator both for a single step.

    Returns:
      The result of the `evaluate` call to the `Estimator`.
    """
    self._estimator.fit(input_fn=self._train_input_fn,
                        steps=1,
                        monitors=self._train_monitors)

    return self._estimator.evaluate(input_fn=self._eval_input_fn,
                                    steps=1,
                                    metrics=self._eval_metrics,
                                    name="one_pass")

  def _start_server(self):
    """Creates, starts, and returns a server_lib.Server."""
    config = self._estimator.config
    if (not config.cluster_spec or not config.job_name or not config.master or
        config.task is None):
      raise ValueError("Could not start server; be sure to specify "
                       "cluster_spec, job_name, master, and task in "
                       "RunConfig or set the TF_CONFIG environment variable.")
    server = server_lib.Server(
        config.cluster_spec,
        job_name=config.job_name,
        task_index=config.task,
        config=config.tf_config,
        start=False)
    server.start()
    return server

@contextlib.contextmanager
def _new_attr_context(obj, attr):
  """Creates a new context in which an object's attribute can be changed.

  This creates a context in which an object's attribute can be changed.
  Once the context is exited, the attribute reverts to its original value.

  Example usage:
    my_obj.x = 1
    with _new_attr_context(my_obj, "x"):
      my_obj.x = 2
      print(my_obj.x)
    print(my_obj.x)
  """
  saved = getattr(obj, attr)
  try:
    yield
  finally:
    setattr(obj, attr, saved)