<commit_before>import pandas as pd
import numpy as np
import uuid
import os
import json
from numbers import Integral

from IPython.display import display_html, display_javascript
try:
    from ipywidgets import widgets
except ImportError:
    from IPython.html import widgets
from IPython.display import display, Javascript
try:
    from traitlets import Unicode, Instance, Bool, Integer
except ImportError:
    from IPython.utils.traitlets import Unicode, Instance, Bool, Integer

def template_contents(filename):
    template_filepath = os.path.join(
        os.path.dirname(__file__),
        'templates',
        filename,
    )
    with open(template_filepath) as f:
        return f.read()

SLICK_GRID_CSS = template_contents('slickgrid.css.template')
SLICK_GRID_JS = template_contents('slickgrid.js.template')
REMOTE_URL = ("https://cdn.rawgit.com/quantopian/qgrid/"
              "master/qgrid/qgridjs/")

class _DefaultSettings(object):

    def __init__(self):
        self._grid_options = {
            'fullWidthRows': True,
            'syncColumnCellResize': True,
            'forceFitColumns': True,
            'rowHeight': 28,
            'enableColumnReorder': False,
            'enableTextSelectionOnCells': True,
            'editable': True,
            'autoEdit': False
        }
        self._remote_js = False
        self._precision = None  # Defer to pandas.get_option

    def set_grid_option(self, optname, optvalue):
        self._grid_options[optname] = optvalue

    def set_defaults(self, remote_js=None, precision=None, grid_options=None):
        if remote_js is not None:
            self._remote_js = remote_js
        if precision is not None:
            self._precision = precision
        if grid_options is not None:
            self._grid_options = grid_options

    @property
    def grid_options(self):
        return self._grid_options

    @property
    def remote_js(self):
        return self._remote_js

    @property
    def precision(self):
        return self._precision or pd.get_option('display.precision') - 1

defaults = _DefaultSettings()

def set_defaults(remote_js=None, precision=None, grid_options=None):
    """
    Set the default qgrid options.  The options that you can set here are the
    same ones that you can pass into ``show_grid``.  See the documentation
    for ``show_grid`` for more information.

    Notes
    -----
    This function will be useful to you if you find yourself
    setting the same options every time you make a call to ``show_grid``.
    Calling this ``set_defaults`` function once sets the options for the
    lifetime of the kernel, so you won't have to include the same options
    every time you call ``show_grid``.

    See Also
    --------
    show_grid :
        The function whose default behavior is changed by ``set_defaults``.
    """
    defaults.set_defaults(remote_js, precision, grid_options)

def set_grid_option(optname, optvalue):
    """
    Set the default value for one of the options that gets passed into the
    SlickGrid constructor.

    Parameters
    ----------
    optname : str
        The name of the option to set.
    optvalue : object
        The new value to set.

    Notes
    -----
    The options you can set here are the same ones
    that you can set via the ``grid_options`` parameter of the ``set_defaults``
    or ``show_grid`` functions.  See the `SlickGrid documentation
    <https://github.com/mleibman/SlickGrid/wiki/Grid-Options>`_ for the full
    list of available options.
    """
    self._grid_options[optname] = optvalue

def show_grid(data_frame, remote_js=None, precision=None, grid_options=None,
              show_toolbar=False):
    """
    Main entry point for rendering DataFrames as SlickGrids.

    Parameters
    ----------
    remote_js : bool
        Whether to load slickgrid.js from a local filesystem or from a
        remote CDN.  Loading from the local filesystem means that SlickGrid
        will function even when not connected to the internet, but grid
        cells created with local filesystem loading will not render
        correctly on external sharing services like NBViewer.
    precision : integer
        The number of digits of precision to display for floating-point
        values.  If unset, we use the value of
        `pandas.get_option('display.precision')`.
    grid_options : dict
        Options to use when creating javascript SlickGrid instances.  See
        the `SlickGrid documentation <https://github.com/mleibman/SlickGrid/wiki/Grid-Options>`_ for
        information on the available options.  See the Notes section below for
        the list of options that qgrid sets by default.

    Notes
    -----
    By default, the following options get passed into SlickGrid when
    ``show_grid`` is called.  See the `SlickGrid documentation
    <https://github.com/mleibman/SlickGrid/wiki/Grid-Options>`_ for information
    about these options.
    ::
        {
            'fullWidthRows': True,
            'syncColumnCellResize': True,
            'forceFitColumns': True,
            'rowHeight': 28,
            'enableColumnReorder': False,
            'enableTextSelectionOnCells': True,
            'editable': True,
            'autoEdit': False
        }
    show_toolbar: bool
        Whether to show a toolbar with options for adding/removing rows and
        exporting the widget to a static view.

    See Also
    --------
    set_defaults : Permanently set global defaults for `show_grid`.
    set_grid_option : Permanently set individual SlickGrid options.
    """

    if remote_js is None:
        remote_js = defaults.remote_js
    if precision is None:
        precision = defaults.precision
        if not isinstance(precision, Integral):
            raise TypeError("precision must be int, not %s" % type(precision))
    if grid_options is None:
        grid_options = defaults.grid_options
        if not isinstance(grid_options, dict):
            raise TypeError(
                "grid_options must be dict, not %s" % type(grid_options)
            )

    # create a visualization for the dataframe
    grid = QGridWidget(df=data_frame, precision=precision,
                       grid_options=json.dumps(grid_options),
                       remote_js=remote_js)

    if show_toolbar:
        add_row = widgets.Button(description="Add Row")
        add_row.on_click(grid.add_row)

        rem_row = widgets.Button(description="Remove Row")
        rem_row.on_click(grid.remove_row)

        export = widgets.Button(description="Export")
        export.on_click(grid.export)

        display(widgets.HBox((add_row, rem_row, export)), grid)
    else:
        display(grid)

class QGridWidget(widgets.DOMWidget):
    _view_module = Unicode("nbextensions/qgridjs/qgrid.widget", sync=True)
    _view_name = Unicode('QGridView', sync=True)
    _df_json = Unicode('', sync=True)
    _column_types_json = Unicode('', sync=True)
    _index_name = Unicode('')
    _cdn_base_url = Unicode("/nbextensions/qgridjs", sync=True)
    _multi_index = Bool(False)

    df = Instance(pd.DataFrame)
    precision = Integer()
    grid_options = Unicode('', sync=True)
    remote_js = Bool(True)

    def _df_changed(self):
        """Build the Data Table for the DataFrame."""

        df = self.df.copy()

        # register a callback for custom messages
        self.on_msg(self._handle_qgrid_msg)

        if type(df.index) == pd.core.index.MultiIndex:
            df.reset_index(inplace=True)
            self._multi_index = True
        else:
            df.insert(0, df.index.name, df.index)
            self._multi_index = False

        if not df.index.name:
            df.index.name = 'Index'

        self._index_name = df.index.name

        tc = dict(np.typecodes)
        for key in np.typecodes.keys():
            if "All" in key:
                del tc[key]

        column_types = []
        for col_name, dtype in df.dtypes.iteritems():
            if str(dtype) == 'category':
                categories = list(df[col_name].cat.categories)
                column_type = {'field': col_name,
                               'categories': ','.join(categories)}
                # XXXX: work around bug in to_json for categorical types
                # https://github.com/pydata/pandas/issues/10778
                df[col_name] = df[col_name].astype(str)
                column_types.append(column_type)
                continue
            column_type = {'field': col_name}
            for type_name, type_codes in tc.items():
                if dtype.kind in type_codes:
                    column_type['type'] = type_name
                    break
            column_types.append(column_type)
        self._column_types_json = json.dumps(column_types)

        self._df_json = df.to_json(
                orient='records',
                date_format='iso',
                double_precision=self.precision,
            )

        self._remote_js_changed()

    def _remote_js_changed(self):
        if self.remote_js:
            self._cdn_base_url = REMOTE_URL
        else:
            self._cdn_base_url = "/nbextensions/qgridjs"

    def add_row(self, value=None):
        """Append a row at the end of the dataframe."""
        df = self.df
        if not df.index.is_integer():
            msg = "Cannot add a row to a table with a non-integer index"
            display(Javascript('alert("%s")' % msg))
            return
        last = df.iloc[-1]
        last.name += 1
        df.loc[last.name] = last.values
        precision = pd.get_option('display.precision') - 1
        row_data = last.to_json(date_format='iso',
                                double_precision=precision)
        msg = json.loads(row_data)
        msg[self._index_name] = str(last.name)
        msg['id'] = str(last.name)
        msg['type'] = 'add_row'
        self.send(msg)

    def remove_row(self, value=None):
        """Remove the current row from the table"""
        if self._multi_index:
            msg = "Cannot remove a row from a table with a multi index"
            display(Javascript('alert("%s")' % msg))
            return
        self.send({'type': 'remove_row'})

    def _handle_qgrid_msg(self, widget, content, buffers=None):
        """Handle incoming messages from the QGridView"""
        if 'type' not in content:
            return
        if content['type'] == 'remove_row':
            self.df.drop(content['row'], inplace=True)

        elif content['type'] == 'cell_change':
            try:
                self.df.set_value(self.df.index[content['row']],
                                  content['column'], content['value'])
            except ValueError:
                pass

    def export(self, value=None):
        # trigger an update of the df json
        self._df_changed()
        self.remote_js = True
        div_id = str(uuid.uuid4())
        grid_options = json.loads(self.grid_options)
        grid_options['editable'] = False

        raw_html = SLICK_GRID_CSS.format(
            div_id=div_id,
            cdn_base_url=self._cdn_base_url,
        )
        raw_js = SLICK_GRID_JS.format(
            cdn_base_url=self._cdn_base_url,
            div_id=div_id,
            data_frame_json=self._df_json,
            column_types_json=self._column_types_json,
            options_json=json.dumps(grid_options),
        )

        display_html(raw_html, raw=True)
        display_javascript(raw_js, raw=True)
<commit_msg>Do not rely on a change event for table update<commit_after>import pandas as pd
import numpy as np
import uuid
import os
import json
from numbers import Integral

from IPython.display import display_html, display_javascript
try:
    from ipywidgets import widgets
except ImportError:
    from IPython.html import widgets
from IPython.display import display, Javascript
try:
    from traitlets import Unicode, Instance, Bool, Integer
except ImportError:
    from IPython.utils.traitlets import Unicode, Instance, Bool, Integer

def template_contents(filename):
    template_filepath = os.path.join(
        os.path.dirname(__file__),
        'templates',
        filename,
    )
    with open(template_filepath) as f:
        return f.read()

SLICK_GRID_CSS = template_contents('slickgrid.css.template')
SLICK_GRID_JS = template_contents('slickgrid.js.template')
REMOTE_URL = ("https://cdn.rawgit.com/quantopian/qgrid/"
              "master/qgrid/qgridjs/")

class _DefaultSettings(object):

    def __init__(self):
        self._grid_options = {
            'fullWidthRows': True,
            'syncColumnCellResize': True,
            'forceFitColumns': True,
            'rowHeight': 28,
            'enableColumnReorder': False,
            'enableTextSelectionOnCells': True,
            'editable': True,
            'autoEdit': False
        }
        self._remote_js = False
        self._precision = None  # Defer to pandas.get_option

    def set_grid_option(self, optname, optvalue):
        self._grid_options[optname] = optvalue

    def set_defaults(self, remote_js=None, precision=None, grid_options=None):
        if remote_js is not None:
            self._remote_js = remote_js
        if precision is not None:
            self._precision = precision
        if grid_options is not None:
            self._grid_options = grid_options

    @property
    def grid_options(self):
        return self._grid_options

    @property
    def remote_js(self):
        return self._remote_js

    @property
    def precision(self):
        return self._precision or pd.get_option('display.precision') - 1

defaults = _DefaultSettings()

def set_defaults(remote_js=None, precision=None, grid_options=None):
    """
    Set the default qgrid options.  The options that you can set here are the
    same ones that you can pass into ``show_grid``.  See the documentation
    for ``show_grid`` for more information.

    Notes
    -----
    This function will be useful to you if you find yourself
    setting the same options every time you make a call to ``show_grid``.
    Calling this ``set_defaults`` function once sets the options for the
    lifetime of the kernel, so you won't have to include the same options
    every time you call ``show_grid``.

    See Also
    --------
    show_grid :
        The function whose default behavior is changed by ``set_defaults``.
    """
    defaults.set_defaults(remote_js, precision, grid_options)

def set_grid_option(optname, optvalue):
    """
    Set the default value for one of the options that gets passed into the
    SlickGrid constructor.

    Parameters
    ----------
    optname : str
        The name of the option to set.
    optvalue : object
        The new value to set.

    Notes
    -----
    The options you can set here are the same ones
    that you can set via the ``grid_options`` parameter of the ``set_defaults``
    or ``show_grid`` functions.  See the `SlickGrid documentation
    <https://github.com/mleibman/SlickGrid/wiki/Grid-Options>`_ for the full
    list of available options.
    """
    self._grid_options[optname] = optvalue

def show_grid(data_frame, remote_js=None, precision=None, grid_options=None,
              show_toolbar=False):
    """
    Main entry point for rendering DataFrames as SlickGrids.

    Parameters
    ----------
    remote_js : bool
        Whether to load slickgrid.js from a local filesystem or from a
        remote CDN.  Loading from the local filesystem means that SlickGrid
        will function even when not connected to the internet, but grid
        cells created with local filesystem loading will not render
        correctly on external sharing services like NBViewer.
    precision : integer
        The number of digits of precision to display for floating-point
        values.  If unset, we use the value of
        `pandas.get_option('display.precision')`.
    grid_options : dict
        Options to use when creating javascript SlickGrid instances.  See
        the `SlickGrid documentation <https://github.com/mleibman/SlickGrid/wiki/Grid-Options>`_ for
        information on the available options.  See the Notes section below for
        the list of options that qgrid sets by default.

    Notes
    -----
    By default, the following options get passed into SlickGrid when
    ``show_grid`` is called.  See the `SlickGrid documentation
    <https://github.com/mleibman/SlickGrid/wiki/Grid-Options>`_ for information
    about these options.
    ::
        {
            'fullWidthRows': True,
            'syncColumnCellResize': True,
            'forceFitColumns': True,
            'rowHeight': 28,
            'enableColumnReorder': False,
            'enableTextSelectionOnCells': True,
            'editable': True,
            'autoEdit': False
        }
    show_toolbar: bool
        Whether to show a toolbar with options for adding/removing rows and
        exporting the widget to a static view.

    See Also
    --------
    set_defaults : Permanently set global defaults for `show_grid`.
    set_grid_option : Permanently set individual SlickGrid options.
    """

    if remote_js is None:
        remote_js = defaults.remote_js
    if precision is None:
        precision = defaults.precision
        if not isinstance(precision, Integral):
            raise TypeError("precision must be int, not %s" % type(precision))
    if grid_options is None:
        grid_options = defaults.grid_options
        if not isinstance(grid_options, dict):
            raise TypeError(
                "grid_options must be dict, not %s" % type(grid_options)
            )

    # create a visualization for the dataframe
    grid = QGridWidget(df=data_frame, precision=precision,
                       grid_options=json.dumps(grid_options),
                       remote_js=remote_js)
    grid.update()

    if show_toolbar:
        add_row = widgets.Button(description="Add Row")
        add_row.on_click(grid.add_row)

        rem_row = widgets.Button(description="Remove Row")
        rem_row.on_click(grid.remove_row)

        export = widgets.Button(description="Export")
        export.on_click(grid.export)

        display(widgets.HBox((add_row, rem_row, export)), grid)
    else:
        display(grid)

class QGridWidget(widgets.DOMWidget):
    _view_module = Unicode("nbextensions/qgridjs/qgrid.widget", sync=True)
    _view_name = Unicode('QGridView', sync=True)
    _df_json = Unicode('', sync=True)
    _column_types_json = Unicode('', sync=True)
    _index_name = Unicode('')
    _cdn_base_url = Unicode("/nbextensions/qgridjs", sync=True)
    _multi_index = Bool(False)

    df = Instance(pd.DataFrame)
    precision = Integer(6)
    grid_options = Unicode('', sync=True)
    remote_js = Bool(True)

    def update_table(self):
        """Build the Data Table for the DataFrame."""

        df = self.df.copy()

        # register a callback for custom messages
        self.on_msg(self._handle_qgrid_msg)

        if type(df.index) == pd.core.index.MultiIndex:
            df.reset_index(inplace=True)
            self._multi_index = True
        else:
            df.insert(0, df.index.name, df.index)
            self._multi_index = False

        if not df.index.name:
            df.index.name = 'Index'

        self._index_name = df.index.name

        tc = dict(np.typecodes)
        for key in np.typecodes.keys():
            if "All" in key:
                del tc[key]

        column_types = []
        for col_name, dtype in df.dtypes.iteritems():
            if str(dtype) == 'category':
                categories = list(df[col_name].cat.categories)
                column_type = {'field': col_name,
                               'categories': ','.join(categories)}
                # XXXX: work around bug in to_json for categorical types
                # https://github.com/pydata/pandas/issues/10778
                df[col_name] = df[col_name].astype(str)
                column_types.append(column_type)
                continue
            column_type = {'field': col_name}
            for type_name, type_codes in tc.items():
                if dtype.kind in type_codes:
                    column_type['type'] = type_name
                    break
            column_types.append(column_type)
        self._column_types_json = json.dumps(column_types)

        self._df_json = df.to_json(
                orient='records',
                date_format='iso',
                double_precision=self.precision,
            )

        self._remote_js_changed()

    def _remote_js_changed(self):
        if self.remote_js:
            self._cdn_base_url = REMOTE_URL
        else:
            self._cdn_base_url = "/nbextensions/qgridjs"

    def add_row(self, value=None):
        """Append a row at the end of the dataframe."""
        df = self.df
        if not df.index.is_integer():
            msg = "Cannot add a row to a table with a non-integer index"
            display(Javascript('alert("%s")' % msg))
            return
        last = df.iloc[-1]
        last.name += 1
        df.loc[last.name] = last.values
        precision = pd.get_option('display.precision') - 1
        row_data = last.to_json(date_format='iso',
                                double_precision=precision)
        msg = json.loads(row_data)
        msg[self._index_name] = str(last.name)
        msg['id'] = str(last.name)
        msg['type'] = 'add_row'
        self.send(msg)

    def remove_row(self, value=None):
        """Remove the current row from the table"""
        if self._multi_index:
            msg = "Cannot remove a row from a table with a multi index"
            display(Javascript('alert("%s")' % msg))
            return
        self.send({'type': 'remove_row'})

    def _handle_qgrid_msg(self, widget, content, buffers=None):
        """Handle incoming messages from the QGridView"""
        if 'type' not in content:
            return
        if content['type'] == 'remove_row':
            self.df.drop(content['row'], inplace=True)

        elif content['type'] == 'cell_change':
            try:
                self.df.set_value(self.df.index[content['row']],
                                  content['column'], content['value'])
            except ValueError:
                pass

    def export(self, value=None):
        self.update_table()
        self.remote_js = True
        div_id = str(uuid.uuid4())
        grid_options = json.loads(self.grid_options)
        grid_options['editable'] = False

        raw_html = SLICK_GRID_CSS.format(
            div_id=div_id,
            cdn_base_url=self._cdn_base_url,
        )
        raw_js = SLICK_GRID_JS.format(
            cdn_base_url=self._cdn_base_url,
            div_id=div_id,
            data_frame_json=self._df_json,
            column_types_json=self._column_types_json,
            options_json=json.dumps(grid_options),
        )

        display_html(raw_html, raw=True)
        display_javascript(raw_js, raw=True)
<|endoftext|>


<commit_before>import uuid
from . import log
from .tools import extract_ks_tab, build_remotely, storage_id_from_name, get_istorage_attrs, generate_token_ring_ranges

class AlreadyPersistentError(RuntimeError):
    pass

class IStorage(object):

    @property
    def storage_id(self):
        return self.__storage_id

    @storage_id.setter
    def storage_id(self, st_id):
        if st_id is not None and not isinstance(st_id, uuid.UUID):
            raise TypeError("Storage ID must be an instance of UUID")
        self.__storage_id = st_id

    def __init__(self, *args, **kwargs):
        super().__init__()
        if not getattr(self, "storage_id", None):
            self.storage_id = kwargs.pop("storage_id", None)
        self._tokens = kwargs.pop("tokens", None)
        given_name = kwargs.pop("name", None)
        if given_name or self.storage_id:
            if self.storage_id:
                metas = get_istorage_attrs(self.storage_id)
                given_name   = metas[0].name
                self._tokens = metas[0].tokens
            # Warning: In order to inherit _tokens and storage_id, they MUST be set before the next call
            IStorage.make_persistent(self, given_name)
        else:
            self._ksp = None
            self._table = None
            self._is_persistent = False

        self._built_remotely = kwargs.pop("built_remotely", False)

    @classmethod
    def get_by_alias(cls, alias=""):
        return cls(name=alias)

    def __eq__(self, other):
        """
        Method to compare a IStorage object with another one.
        Args:
            other: IStorage to be compared with.
        Returns:
            boolean (true - equals, false - not equals).
        """
        return self.__class__ == other.__class__ and self.storage_id == other.storage_id

    def make_persistent(self, name):
        if getattr(self, '_is_persistent', False):
            raise AlreadyPersistentError("This Object is already persistent [Before:{}.{}][After:{}]",
                                         self._ksp, self._table, name)

        self._ksp, self._table = extract_ks_tab(name)
        name = self._ksp + '.' + self._table
        self._set_name(name)

        if not self.storage_id:
            self.storage_id = storage_id_from_name(name)

        # If found data, replace the constructor data
        if self._tokens is None:
            metas = get_istorage_attrs(self.storage_id)
            try:
                self._tokens = metas[0].tokens
            except IndexError:
                self._tokens = generate_token_ring_ranges()

        self._is_persistent = True

    def stop_persistent(self):
        if not self._is_persistent:
            raise RuntimeError("This Object is not persistent")

        self._is_persistent = False

    def delete_persistent(self):
        if not self._is_persistent:
            raise RuntimeError("This Object is not persistent")

        self._is_persistent = False

    def _set_name(self, name):
        if name is not None and not isinstance(name, str):
            raise TypeError("Name -{}-  should be an instance of str".format(str(name)))
        self._name = name

    def _get_name(self):
        try:
            return self._name
        except AttributeError:
            return None

    def _flush_to_storage(self):
        if not self._is_persistent:
            raise RuntimeError("Can't send the data to storage if the object is not persistent")

    def getID(self):
        """
        Method to retrieve the storage id as string. Used by PyCOMPSs solely.
        :return: Storage_id as str
        """
        return str(self.storage_id)

    def split(self):
        """
        Method used to divide an object into sub-objects.
        Returns:
            a subobject everytime is called
        """
        from .tools import tokens_partitions
        try:
            tokens = self._build_args.tokens
        except AttributeError as ex:
            raise RuntimeError("Object {} does not have tokens".format(self._get_name()))

        self._flush_to_storage()

        for token_split in tokens_partitions(self._ksp, self._table, tokens):
            storage_id = uuid.uuid4()
            log.debug('assigning to {} num tokens {}'.format(str(storage_id), len(token_split)))
            new_args = self._build_args._replace(tokens=token_split, storage_id=storage_id)
            args_dict = new_args._asdict()
            args_dict["built_remotely"] = True
            yield build_remotely(args_dict)
<commit_msg>Fix a bug with IStorage mgmt<commit_after>import uuid
from . import log
from .tools import extract_ks_tab, build_remotely, storage_id_from_name, get_istorage_attrs, generate_token_ring_ranges

class AlreadyPersistentError(RuntimeError):
    pass

class IStorage(object):

    @property
    def storage_id(self):
        return self.__storage_id

    @storage_id.setter
    def storage_id(self, st_id):
        if st_id is not None and not isinstance(st_id, uuid.UUID):
            raise TypeError("Storage ID must be an instance of UUID")
        self.__storage_id = st_id

    def __init__(self, *args, **kwargs):
        super().__init__()
        if not getattr(self, "storage_id", None):
            self.storage_id = kwargs.pop("storage_id", None)
        self._tokens = kwargs.pop("tokens", None)
        given_name = kwargs.pop("name", None)
        if self.storage_id:
            try:
                metas = get_istorage_attrs(self.storage_id)
                given_name   = metas[0].name
                self._tokens = metas[0].tokens
            except IndexError:
                pass
        if given_name :
            # Warning: In order to inherit _tokens and storage_id, they MUST be set before the next call
            IStorage.make_persistent(self, given_name)
        else:
            self._ksp = None
            self._table = None
            self._is_persistent = False

        self._built_remotely = kwargs.pop("built_remotely", False)

    @classmethod
    def get_by_alias(cls, alias=""):
        return cls(name=alias)

    def __eq__(self, other):
        """
        Method to compare a IStorage object with another one.
        Args:
            other: IStorage to be compared with.
        Returns:
            boolean (true - equals, false - not equals).
        """
        return self.__class__ == other.__class__ and self.storage_id == other.storage_id

    def make_persistent(self, name):
        if getattr(self, '_is_persistent', False):
            raise AlreadyPersistentError("This Object is already persistent [Before:{}.{}][After:{}]",
                                         self._ksp, self._table, name)

        self._ksp, self._table = extract_ks_tab(name)
        name = self._ksp + '.' + self._table
        self._set_name(name)

        if not self.storage_id:
            self.storage_id = storage_id_from_name(name)

        # If found data, replace the constructor data
        if self._tokens is None:
            metas = get_istorage_attrs(self.storage_id)
            try:
                self._tokens = metas[0].tokens
            except IndexError:
                self._tokens = generate_token_ring_ranges()

        self._is_persistent = True

    def stop_persistent(self):
        if not self._is_persistent:
            raise RuntimeError("This Object is not persistent")

        self._is_persistent = False

    def delete_persistent(self):
        if not self._is_persistent:
            raise RuntimeError("This Object is not persistent")

        self._is_persistent = False

    def _set_name(self, name):
        if name is not None and not isinstance(name, str):
            raise TypeError("Name -{}-  should be an instance of str".format(str(name)))
        self._name = name

    def _get_name(self):
        try:
            return self._name
        except AttributeError:
            return None

    def _flush_to_storage(self):
        if not self._is_persistent:
            raise RuntimeError("Can't send the data to storage if the object is not persistent")

    def getID(self):
        """
        Method to retrieve the storage id as string. Used by PyCOMPSs solely.
        :return: Storage_id as str
        """
        return str(self.storage_id)

    def split(self):
        """
        Method used to divide an object into sub-objects.
        Returns:
            a subobject everytime is called
        """
        from .tools import tokens_partitions
        try:
            tokens = self._build_args.tokens
        except AttributeError as ex:
            raise RuntimeError("Object {} does not have tokens".format(self._get_name()))

        self._flush_to_storage()

        for token_split in tokens_partitions(self._ksp, self._table, tokens):
            storage_id = uuid.uuid4()
            log.debug('assigning to {} num tokens {}'.format(str(storage_id), len(token_split)))
            new_args = self._build_args._replace(tokens=token_split, storage_id=storage_id)
            args_dict = new_args._asdict()
            args_dict["built_remotely"] = True
            yield build_remotely(args_dict)
<|endoftext|>


<commit_before># Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)

from spack import *

class Busco(PythonPackage):
    """Assesses genome assembly and annotation completeness with Benchmarking
       Universal Single-Copy Orthologs"""

    homepage = "http://busco.ezlab.org/"
    url      = "https://gitlab.com/api/v4/projects/ezlab%2Fbusco/repository/archive.tar.gz?sha=2.0.1"
    git      = "https://gitlab.com/ezlab/busco.git"

    # TODO: check the installation procedure for version 3.0.2
    # and uncomment the following line
    # version('3.0.2', sha256='dbea093315b766b0f7c4fe3cafbbdf51ade79ec84bde04f1f437b48333200f34')

    # There is no tag for version 3.0.1
    version('3.0.1', commit='078252e00399550d7b0e8941cd4d986c8e868a83')
    version('2.0.1', sha256='bd72a79b880370e9b61b8c722e171818c7c85d46cc1e2f80595df2738a7e220c')

    depends_on('python', type=('build', 'run'))
    depends_on('blast-plus')
    depends_on('hmmer')
    depends_on('augustus')

    def build(self, spec, prefix):
        if self.spec.satisfies('@2.0.1'):
            pass

    def install(self, spec, prefix):
        if self.spec.satisfies('@3.0.1'):
            with working_dir('scripts'):
                mkdirp(prefix.bin)
                install('generate_plot.py', prefix.bin)
                install('run_BUSCO.py', prefix.bin)
            install_tree('config', prefix.config)
            args = self.install_args(spec, prefix)
            self.setup_py('install', *args)
        if self.spec.satisfies('@2.0.1'):
            mkdirp(prefix.bin)
            install('BUSCO.py', prefix.bin)
            install('BUSCO_plot.py', prefix.bin)
<commit_msg>busco: add 4.1.3 (#19296)<commit_after># Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)

from spack import *

class Busco(PythonPackage):
    """Assesses genome assembly and annotation completeness with Benchmarking
       Universal Single-Copy Orthologs"""

    homepage = "http://busco.ezlab.org/"
    url      = "https://gitlab.com/api/v4/projects/ezlab%2Fbusco/repository/archive.tar.gz?sha=2.0.1"
    git      = "https://gitlab.com/ezlab/busco.git"

    version('4.1.3', sha256='08ded26aeb4f6aef791cd88524c3c00792a054c7672ea05219f468d495e7b072')

    # TODO: check the installation procedure for version 3.0.2
    # and uncomment the following line
    # version('3.0.2', sha256='dbea093315b766b0f7c4fe3cafbbdf51ade79ec84bde04f1f437b48333200f34')

    # There is no tag for version 3.0.1
    version('3.0.1', commit='078252e00399550d7b0e8941cd4d986c8e868a83')
    version('2.0.1', sha256='bd72a79b880370e9b61b8c722e171818c7c85d46cc1e2f80595df2738a7e220c')

    depends_on('python', type=('build', 'run'))
    depends_on('blast-plus')
    depends_on('hmmer')
    depends_on('augustus')

    depends_on('py-biopython', when='@4.1.3', type=('build', 'run'))

    def build(self, spec, prefix):
        if self.spec.satisfies('@2.0.1'):
            pass

    def install(self, spec, prefix):
        if self.spec.satisfies('@4.1.3'):
            install_tree('bin', prefix.bin)
            install_tree('config', prefix.config)
            args = self.install_args(spec, prefix)
            self.setup_py('install', *args)
        if self.spec.satisfies('@3.0.1'):
            with working_dir('scripts'):
                mkdirp(prefix.bin)
                install('generate_plot.py', prefix.bin)
                install('run_BUSCO.py', prefix.bin)
            install_tree('config', prefix.config)
            args = self.install_args(spec, prefix)
            self.setup_py('install', *args)
        if self.spec.satisfies('@2.0.1'):
            mkdirp(prefix.bin)
            install('BUSCO.py', prefix.bin)
            install('BUSCO_plot.py', prefix.bin)
<|endoftext|>


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

import re

class Node:
    def __init__(self, name):
        self.name = name
        self.uname = ''
        self.state = []
        self.sessions = []
        self.nsessions = 0
        self.nusers = 0
        self.physmem = 0
        self.totmem = 0
        self.availmem = 0
        self.procs = 0
        self.jobs = []
        self.loadave = 0
        self.os = ''
        self.gpus = 0
        self.properties = []
        self.ntype = ''
        self.slots = 0

    def __repr__(self):
        return self.name

    def __str__(self):
        return self.name

    def has_job(self, jobid):
        return jobid in self.jobs

    def matches(self, regex):
        match = re.compile(regex)
        return not match.search(self.name) is None

    def state_matches(self, states):
        # States come in as human readable, there's a good chance
        # this will change in the future, but for right now we need
        # to convert them to chars.  Sort these so out of order arrays
        # can still return true when we intersect the sets.
        state = sorted(list(states))
        return list(set(self.state) & set(state)) == self.state
<commit_msg>compare between sets, not lists<commit_after># Copyright 2014, Rob Lyon <nosignsoflifehere@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import re

class Node:
    def __init__(self, name):
        self.name = name
        self.uname = ''
        self.state = []
        self.sessions = []
        self.nsessions = 0
        self.nusers = 0
        self.physmem = 0
        self.totmem = 0
        self.availmem = 0
        self.procs = 0
        self.jobs = []
        self.loadave = 0
        self.os = ''
        self.gpus = 0
        self.properties = []
        self.ntype = ''
        self.slots = 0

    def __repr__(self):
        return self.name

    def __str__(self):
        return self.name

    def has_job(self, jobid):
        return jobid in self.jobs

    def matches(self, regex):
        match = re.compile(regex)
        return not match.search(self.name) is None

    def state_matches(self, states):
        # States come in as human readable, there's a good chance
        # this will change in the future, but for right now we need
        # to convert them to chars.  Sort these so out of order arrays
        # can still return true when we intersect the sets.
        state = sorted(list(states))
        # print 'begin'
        #print 'compare1:', states
        #print 'compare',  set(list(set(self.state) & set(state)))
        #print 'self.state', self.state
        #print 'type self.state', type(self.state)
        # print 'end'
        # print (list(set(self.state) & set(state)) <= self.state), list(set(self.state) & set(state))
        # compare the intersection of state_to_filter to self.state
        return set(self.state) & set(state) == set(self.state)
        #return list(set(self.state) & set(state)) <= self.state and list(set(self.state) & set(state))
<|endoftext|>


<commit_before>class RollbackerBase(object):

  def __init__(self, handler):
    self.app_handler = handler

class AppRollbacker(RollbackerBase):

  def __init__(self, handler):
    super(AppRollbacker, self).__init__(handler)
    self.app_config = handler.adapter.get_config()

  def rollback_config(self):
    self.app_handler.wait_start(0.5, 10)
    self.app_handler.adapter.set_config(self.app_config)
    self.app_handler.restart()
    self.app_handler.wait_start(0.5, 10)

class SyncthingRollbacker(RollbackerBase):

  def __init__(self, handler):
    super(SyncthingRollbacker, self).__init__(handler)
    self.syncthing_config = handler.get_config()

  def rollback_config(self):
    self.app_handler.wait_start(0.5, 10)
    self.app_handler.set_config(self.syncthing_config)
    self.app_handler.restart()
    self.app_handler.wait_start(0.5, 10)

<commit_msg>rollbacker Bug Fix<commit_after>class RollbackerBase(object):

  def __init__(self, handler):
    self.app_handler = handler

class AppRollbacker(RollbackerBase):

  def __init__(self, handler):
    super(AppRollbacker, self).__init__(handler)
    self.app_config = handler.adapter.get_config()

  def rollback_config(self):
    self.app_handler.wait_start(0.5, 10)
    self.app_handler.adapter.set_config(self.app_config)

    if self.app_handler.ping():
      self.app_handler.restart()

    self.app_handler.wait_start(0.5, 10)

class SyncthingRollbacker(RollbackerBase):

  def __init__(self, handler):
    super(SyncthingRollbacker, self).__init__(handler)
    self.syncthing_config = handler.get_config()

  def rollback_config(self):
    self.app_handler.wait_start(0.5, 10)
    self.app_handler.set_config(self.syncthing_config)

    if self.app_handler.ping():
      self.app_handler.restart()

    self.app_handler.wait_start(0.5, 10)

<|endoftext|>


<commit_before>import Queue
import threading

def _run_worker():
    while True:
        _, fn, args = _work_queue.get()
        fn(*args)

_work_queue = Queue.PriorityQueue()
_worker_thread = threading.Thread(target=_run_worker)
_worker_thread.start()

def queue_work(priority, fn, *args):
    _work_queue.put((-priority, fn, args))
<commit_msg>Fix server issue by setting the API worker thread to be a daemon<commit_after>import Queue
import threading

def _run_worker():
    while True:
        _, fn, args = _work_queue.get()
        fn(*args)

_work_queue = Queue.PriorityQueue()
_worker_thread = threading.Thread(target=_run_worker)
_worker_thread.daemon = True
_worker_thread.start()

def queue_work(priority, fn, *args):
    _work_queue.put((-priority, fn, args))
<|endoftext|>


<commit_before>"""
Copyright 2017-2018 Fizyr (https://fizyr.com)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

from __future__ import division
import keras
import time
import numpy as np
import cv2
import PIL

from .transform import change_transform_origin, transform_aabb, colvec

def read_image_bgr(path):
    image = np.asarray(PIL.Image.open(path).convert('RGB'))
    return image[:, :, ::-1].copy()

def preprocess_image(x):
    # mostly identical to "https://github.com/fchollet/keras/blob/master/keras/applications/imagenet_utils.py"
    # except for converting RGB -> BGR since we assume BGR already
    x = x.astype(keras.backend.floatx())
    if keras.backend.image_data_format() == 'channels_first':
        if x.ndim == 3:
            x[0, :, :] -= 103.939
            x[1, :, :] -= 116.779
            x[2, :, :] -= 123.68
        else:
            x[:, 0, :, :] -= 103.939
            x[:, 1, :, :] -= 116.779
            x[:, 2, :, :] -= 123.68
    else:
        x[..., 0] -= 103.939
        x[..., 1] -= 116.779
        x[..., 2] -= 123.68

    return x

def adjust_transform_for_image(transform, image, relative_translation):
    """ Adjust a transformation for a specific image.

    The translation of the matrix will be scaled with the size of the image.
    The linear part of the transformation will adjusted so that the origin of the transformation will be at the center of the image.
    """
    height, width, channels = image.shape

    result = transform

    # Scale the translation with the image size if specified.
    if relative_translation:
        result[0:2, 2] *= [width, height]

    # Move the origin of transformation.
    result = change_transform_origin(transform, (0.5 * width, 0.5 * height))

    return result

class TransformParameters:
    """ Struct holding parameters determining how to apply a transformation to an image.

    # Arguments
        fill_mode:             Same as for keras.preprocessing.image.apply_transform
        cval:                  Same as for keras.preprocessing.image.apply_transform
        data_format:           Same as for keras.preprocessing.image.apply_transform
        relative_translation:  If true (the default), interpret translation as a factor of the image size.
                               If false, interpret it as absolute pixels.
    """
    def __init__(
        self,
        fill_mode            = 'nearest',
        cval                 = 0,
        data_format          = None,
        relative_translation = True,
    ):
        self.fill_mode            = fill_mode
        self.cval                 = cval
        self.relative_translation = relative_translation

        if data_format is None:
            data_format = keras.backend.image_data_format()
        self.data_format = data_format

        if data_format == 'channels_first':
            self.channel_axis = 0
        elif data_format == 'channels_last':
            self.channel_axis = 2
        else:
            raise ValueError("invalid data_format, expected 'channels_first' or 'channels_last', got '{}'".format(data_format))

def apply_transform(transform, image, params):
    """ Wrapper around keras.preprocessing.image.apply_transform using TransformParameters. """
    return keras.preprocessing.image.apply_transform(
        image,
        transform,
        channel_axis = params.channel_axis,
        fill_mode    = params.fill_mode,
        cval         = params.cval
    )

def resize_image(img, min_side=600, max_side=1024):
    (rows, cols, _) = img.shape

    smallest_side = min(rows, cols)

    # rescale the image so the smallest side is min_side
    scale = min_side / smallest_side

    # check if the largest side is now greater than max_side, wich can happen
    # when images have a large aspect ratio
    largest_side = max(rows, cols)
    if largest_side * scale > max_side:
        scale = max_side / largest_side

    # resize the image with the computed scale
    img = cv2.resize(img, None, fx=scale, fy=scale)

    return img, scale
<commit_msg>Add missing import.<commit_after>"""
Copyright 2017-2018 Fizyr (https://fizyr.com)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

from __future__ import division
import keras
import keras.preprocessing.image
import time
import numpy as np
import cv2
import PIL

from .transform import change_transform_origin, transform_aabb, colvec

def read_image_bgr(path):
    image = np.asarray(PIL.Image.open(path).convert('RGB'))
    return image[:, :, ::-1].copy()

def preprocess_image(x):
    # mostly identical to "https://github.com/fchollet/keras/blob/master/keras/applications/imagenet_utils.py"
    # except for converting RGB -> BGR since we assume BGR already
    x = x.astype(keras.backend.floatx())
    if keras.backend.image_data_format() == 'channels_first':
        if x.ndim == 3:
            x[0, :, :] -= 103.939
            x[1, :, :] -= 116.779
            x[2, :, :] -= 123.68
        else:
            x[:, 0, :, :] -= 103.939
            x[:, 1, :, :] -= 116.779
            x[:, 2, :, :] -= 123.68
    else:
        x[..., 0] -= 103.939
        x[..., 1] -= 116.779
        x[..., 2] -= 123.68

    return x

def adjust_transform_for_image(transform, image, relative_translation):
    """ Adjust a transformation for a specific image.

    The translation of the matrix will be scaled with the size of the image.
    The linear part of the transformation will adjusted so that the origin of the transformation will be at the center of the image.
    """
    height, width, channels = image.shape

    result = transform

    # Scale the translation with the image size if specified.
    if relative_translation:
        result[0:2, 2] *= [width, height]

    # Move the origin of transformation.
    result = change_transform_origin(transform, (0.5 * width, 0.5 * height))

    return result

class TransformParameters:
    """ Struct holding parameters determining how to apply a transformation to an image.

    # Arguments
        fill_mode:             Same as for keras.preprocessing.image.apply_transform
        cval:                  Same as for keras.preprocessing.image.apply_transform
        data_format:           Same as for keras.preprocessing.image.apply_transform
        relative_translation:  If true (the default), interpret translation as a factor of the image size.
                               If false, interpret it as absolute pixels.
    """
    def __init__(
        self,
        fill_mode            = 'nearest',
        cval                 = 0,
        data_format          = None,
        relative_translation = True,
    ):
        self.fill_mode            = fill_mode
        self.cval                 = cval
        self.relative_translation = relative_translation

        if data_format is None:
            data_format = keras.backend.image_data_format()
        self.data_format = data_format

        if data_format == 'channels_first':
            self.channel_axis = 0
        elif data_format == 'channels_last':
            self.channel_axis = 2
        else:
            raise ValueError("invalid data_format, expected 'channels_first' or 'channels_last', got '{}'".format(data_format))

def apply_transform(transform, image, params):
    """ Wrapper around keras.preprocessing.image.apply_transform using TransformParameters. """
    return keras.preprocessing.image.apply_transform(
        image,
        transform,
        channel_axis = params.channel_axis,
        fill_mode    = params.fill_mode,
        cval         = params.cval
    )

def resize_image(img, min_side=600, max_side=1024):
    (rows, cols, _) = img.shape

    smallest_side = min(rows, cols)

    # rescale the image so the smallest side is min_side
    scale = min_side / smallest_side

    # check if the largest side is now greater than max_side, wich can happen
    # when images have a large aspect ratio
    largest_side = max(rows, cols)
    if largest_side * scale > max_side:
        scale = max_side / largest_side

    # resize the image with the computed scale
    img = cv2.resize(img, None, fx=scale, fy=scale)

    return img, scale
<|endoftext|>


<commit_before>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Feed-Forward Neural Networks
"""

import torch
import torch.nn as nn

from torch.autograd import Variable

import time

# Custom DataSet
from data import iris

class IrisNet(nn.Module):

    def __init__(self, input_size, hidden1_size, hidden2_size, num_classes):

        super(IrisNet, self).__init__()
        self.fc1 = nn.Linear(input_size, hidden1_size)
        self.relu1 = nn.ReLU()
        self.fc2 = nn.Linear(hidden1_size, hidden2_size)
        self.relu2 = nn.ReLU()
        self.fc3 = nn.Linear(hidden2_size, num_classes)

    def forward(self, x):
        out = self.fc1(x)
        out = self.relu1(out)
        out = self.fc2(out)
        out = self.relu2(out)
        out = self.fc3(out)
        return out

def train_model(epochs,train_loader,train_ds,test_ds,model,criterion,batch_size,
                learning_rate=0.01,print_every_n_lines=10,use_cuda=False):

    optimizer = torch.optim.SGD(model.parameters(),learning_rate,
                                nesterov=True,momentum=0.9,dampening=0)
    train_loss = []
    test_loss = []
    train_accuracy = []
    test_accuracy = []

    for epoch in range(epochs):
        model.train() # put the model into training mode
        train_correct = 0
        train_total = 0
        for i, (items, classes) in enumerate(train_loader):
            # Convert torch tensor to Variable
            if use_cuda:
                items = Variable(items.cuda())
                classes = Variable(classes.cuda())
            else:
                items = Variable(items)
                classes = Variable(classes)
            optimizer.zero_grad()       # Clear off the gradients from any past operation
            outputs = model(items)      # Do the forward pass
            loss = criterion(outputs, classes) # Calculate the loss
            loss.backward()             # Calculate the gradients with help of back propagation
            optimizer.step()            # Ask the optimizer to adjust the parameters based on the gradients
            # Record the correct predictions for training data
            train_total += classes.size(0)
            _, predicted = torch.max(outputs.data, 1)
            train_correct += (predicted == classes.data).sum()
        model.eval() # put the model into evaluation mode
        # Book keeping
        # Record the loss
        train_loss.append(loss.data[0])
        # What was our train accuracy?
        _train_accuracy = (100 * train_correct / train_total)
        train_accuracy.append(_train_accuracy)
        # How did we do on the test set (the unseen set)
        # Record the correct predictions for test data
        test_items = torch.FloatTensor(test_ds.data.values[:, 0:4])
        test_classes = torch.LongTensor(test_ds.data.values[:, 4])
        if use_cuda:
            test_items = test_items.cuda()
            test_classes = test_classes.cuda()
        outputs = model(Variable(test_items))
        tloss = criterion(outputs, Variable(test_classes))
        test_loss.append(tloss.data[0])
        _, predicted = torch.max(outputs.data, 1)
        total = test_classes.size(0)
        correct = (predicted == test_classes).sum()
        _test_accuracy = (100 * correct / total)
        test_accuracy.append(_test_accuracy)
        if epoch % print_every_n_lines == 0 or epoch == (epochs-1):
                print ('Epoch %d/%d, Train Loss: %.4f, Train Loss: %.4f, Train Acc: %.4f , Test Acc: %.4f '
                       %(epoch+1, epochs, loss.data[0], tloss.data[0],_train_accuracy,_test_accuracy))

    return model, train_loss, test_loss, train_accuracy, test_accuracy

"""
Main
"""
def main():
    start = time.time()
    print("torch.__version__:",torch.__version__)
    if torch.cuda.is_available():
        print("GPU Supported",torch.cuda.device_count())
        use_cuda = True
    else:
        print("GPU Not Supported",torch.cuda.device_count())
        use_cuda = False
    print("**** Feed-Forward Neural Network ***")
    batch_size = 60
    # Get the datasets
    train_ds, test_ds = iris.get_datasets('data/iris.data.txt')
    # How many instances have we got?
    print('instances in training set: ', len(train_ds))
    print('instances in testing/validation set: ', len(test_ds))
    # Create the dataloaders - for training and validation/testing
    # We will be using the term validation and testing data interchangably
    train_loader = torch.utils.data.DataLoader(dataset=train_ds, batch_size=batch_size, shuffle=True)
    test_loader  = torch.utils.data.DataLoader(dataset=test_ds, batch_size=batch_size, shuffle=True)
    # Train
    model = IrisNet(4, 100, 50, 3)
    if use_cuda:
        model = model.cuda()
    model, train_loss, test_loss, train_accuracy,
    test_accuracy = train_model(epochs=500,train_loader=train_loader,
                                train_ds=train_ds,test_ds=test_ds,
                                model=model,
                                criterion=nn.CrossEntropyLoss(),
                                batch_size=batch_size,
                                learning_rate=0.001,print_every_n_lines=100,
                                use_cuda=use_cuda)

    # Saving the model to disk, and loading it back
    torch.save(model.state_dict(), "./2.model.pth")
    net2 = IrisNet(4, 100, 50, 3)
    net2.load_state_dict(torch.load("./2.model.pth"))
    output = net2(Variable(torch.FloatTensor([[5.1, 3.5, 1.4, 0.2]])))
    _, predicted_class = torch.max(output.data, 1)
    print('Predicted class: ', predicted_class.numpy()[0])
    print('Expected class: ', 0 )
    print('Time (s): %.2f seconds'%(time.time() - start))

if __name__ == '__main__':
    main()

# =============================================================================
# torch.__version__: 0.4.1
# GPU Not Supported 0
# **** Feed-Forward Neural Network ***
# instances in training set:  120
# instances in testing/validation set:  30
# Epoch 101/500, Train Loss: 0.3186, Train Loss: 0.3949, Train Acc: 95.0000 , Test Acc: 100.0000
# Epoch 201/500, Train Loss: 0.1949, Train Loss: 0.2401, Train Acc: 98.0000 , Test Acc: 100.0000
# Epoch 301/500, Train Loss: 0.1329, Train Loss: 0.1736, Train Acc: 98.0000 , Test Acc: 96.0000
# Epoch 401/500, Train Loss: 0.0955, Train Loss: 0.1436, Train Acc: 98.0000 , Test Acc: 96.0000
# Epoch 500/500, Train Loss: 0.1043, Train Loss: 0.1324, Train Acc: 97.0000 , Test Acc: 96.0000
# Predicted class:  0
# Expected class:  0
# Time (s): 16.76 seconds
# =============================================================================

<commit_msg>mmmMerge branch 'master' of https://github.com/gtesei/DeepExperiments<commit_after>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Feed-Forward Neural Networks
"""

import torch
import torch.nn as nn

from torch.autograd import Variable

import time

# Custom DataSet
from data import iris

class IrisNet(nn.Module):

    def __init__(self, input_size, hidden1_size, hidden2_size, num_classes):

        super(IrisNet, self).__init__()
        self.fc1 = nn.Linear(input_size, hidden1_size)
        self.relu1 = nn.ReLU()
        self.fc2 = nn.Linear(hidden1_size, hidden2_size)
        self.relu2 = nn.ReLU()
        self.fc3 = nn.Linear(hidden2_size, num_classes)

    def forward(self, x):
        out = self.fc1(x)
        out = self.relu1(out)
        out = self.fc2(out)
        out = self.relu2(out)
        out = self.fc3(out)
        return out

def train_model(epochs,train_loader,train_ds,test_ds,model,criterion,batch_size,
                learning_rate=0.01,print_every_n_lines=10,use_cuda=False):

    optimizer = torch.optim.SGD(model.parameters(),learning_rate,
                                nesterov=True,momentum=0.9,dampening=0)
    train_loss = []
    test_loss = []
    train_accuracy = []
    test_accuracy = []

    for epoch in range(epochs):
        model.train() # put the model into training mode
        train_correct = 0
        train_total = 0
        for i, (items, classes) in enumerate(train_loader):
            # Convert torch tensor to Variable
            if use_cuda:
                items = Variable(items.cuda())
                classes = Variable(classes.cuda())
            else:
                items = Variable(items)
                classes = Variable(classes)
            optimizer.zero_grad()       # Clear off the gradients from any past operation
            outputs = model(items)      # Do the forward pass
            loss = criterion(outputs, classes) # Calculate the loss
            loss.backward()             # Calculate the gradients with help of back propagation
            optimizer.step()            # Ask the optimizer to adjust the parameters based on the gradients
            # Record the correct predictions for training data
            train_total += classes.size(0)
            _, predicted = torch.max(outputs.data, 1)
            train_correct += (predicted == classes.data).sum()
        model.eval() # put the model into evaluation mode
        # Book keeping
        # Record the loss
        train_loss.append(loss.data[0])
        # What was our train accuracy?
        _train_accuracy = (100 * train_correct / train_total)
        train_accuracy.append(_train_accuracy)
        # How did we do on the test set (the unseen set)
        # Record the correct predictions for test data
        test_items = torch.FloatTensor(test_ds.data.values[:, 0:4])
        test_classes = torch.LongTensor(test_ds.data.values[:, 4])
        if use_cuda:
            test_items = test_items.cuda()
            test_classes = test_classes.cuda()
        outputs = model(Variable(test_items))
        tloss = criterion(outputs, Variable(test_classes))
        test_loss.append(tloss.data[0])
        _, predicted = torch.max(outputs.data, 1)
        total = test_classes.size(0)
        correct = (predicted == test_classes).sum()
        _test_accuracy = (100 * correct / total)
        test_accuracy.append(_test_accuracy)
        if epoch % print_every_n_lines == 0 or epoch == (epochs-1):
                print ('Epoch %d/%d, Train Loss: %.4f, Train Loss: %.4f, Train Acc: %.4f , Test Acc: %.4f '
                       %(epoch+1, epochs, loss.data[0], tloss.data[0],_train_accuracy,_test_accuracy))

    return model, train_loss, test_loss, train_accuracy, test_accuracy

"""
Main
"""
def main():
    start = time.time()
    print("torch.__version__:",torch.__version__)
    if torch.cuda.is_available():
        print("GPU Supported",torch.cuda.device_count())
        use_cuda = True
    else:
        print("GPU Not Supported",torch.cuda.device_count())
        use_cuda = False
    print("**** Feed-Forward Neural Network ***")
    batch_size = 60
    # Get the datasets
    train_ds, test_ds = iris.get_datasets('data/iris.data.txt')
    # How many instances have we got?
    print('instances in training set: ', len(train_ds))
    print('instances in testing/validation set: ', len(test_ds))
    # Create the dataloaders - for training and validation/testing
    # We will be using the term validation and testing data interchangably
    train_loader = torch.utils.data.DataLoader(dataset=train_ds, batch_size=batch_size, shuffle=True)
    test_loader  = torch.utils.data.DataLoader(dataset=test_ds, batch_size=batch_size, shuffle=True)
    # Train
    model = IrisNet(4, 100, 50, 3)
    if use_cuda:
        model = model.cuda()
    model, train_loss, test_loss, train_accuracy, test_accuracy = train_model(epochs=500,train_loader=train_loader,
                                train_ds=train_ds,test_ds=test_ds,
                                model=model,
                                criterion=nn.CrossEntropyLoss(),
                                batch_size=batch_size,
                                learning_rate=0.001,print_every_n_lines=100,
                                use_cuda=use_cuda)

    # Saving the model to disk, and loading it back
    torch.save(model.state_dict(), "./2.model.pth")
    net2 = IrisNet(4, 100, 50, 3)
    net2.load_state_dict(torch.load("./2.model.pth"))
    output = net2(Variable(torch.FloatTensor([[5.1, 3.5, 1.4, 0.2]])))
    _, predicted_class = torch.max(output.data, 1)
    print('Predicted class: ', predicted_class.numpy()[0])
    print('Expected class: ', 0 )
    print('Time (s): %.2f seconds'%(time.time() - start))

if __name__ == '__main__':
    main()

# =============================================================================
# torch.__version__: 0.4.1
# GPU Not Supported 0
# **** Feed-Forward Neural Network ***
# instances in training set:  120
# instances in testing/validation set:  30
# Epoch 101/500, Train Loss: 0.3186, Train Loss: 0.3949, Train Acc: 95.0000 , Test Acc: 100.0000
# Epoch 201/500, Train Loss: 0.1949, Train Loss: 0.2401, Train Acc: 98.0000 , Test Acc: 100.0000
# Epoch 301/500, Train Loss: 0.1329, Train Loss: 0.1736, Train Acc: 98.0000 , Test Acc: 96.0000
# Epoch 401/500, Train Loss: 0.0955, Train Loss: 0.1436, Train Acc: 98.0000 , Test Acc: 96.0000
# Epoch 500/500, Train Loss: 0.1043, Train Loss: 0.1324, Train Acc: 97.0000 , Test Acc: 96.0000
# Predicted class:  0
# Expected class:  0
# Time (s): 16.76 seconds
# =============================================================================

<|endoftext|>


<commit_before>"""
Copyright 2017-2018 Fizyr (https://fizyr.com)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

from __future__ import division
import numpy as np
import cv2
from PIL import Image

from .transform import change_transform_origin

def read_image_bgr(path):
    """ Read an image in BGR format.

    Args
        path: Path to the image.
    """
    image = np.asarray(Image.open(path).convert('RGB'))
    return image[:, :, ::-1].copy()

def preprocess_image(x, mode='caffe'):
    """ Preprocess an image by subtracting the ImageNet mean.

    Args
        x: np.array of shape (None, None, 3) or (3, None, None).
        mode: One of "caffe" or "tf".
            - caffe: will zero-center each color channel with
                respect to the ImageNet dataset, without scaling.
            - tf: will scale pixels between -1 and 1, sample-wise.

    Returns
        The input with the ImageNet mean subtracted.
    """
    # mostly identical to "https://github.com/keras-team/keras-applications/blob/master/keras_applications/imagenet_utils.py"
    # except for converting RGB -> BGR since we assume BGR already

    # covert always to float32 to keep compatibility with opencv
    x = x.astype(np.float32)

    if mode == 'tf':
        x /= 127.5
        x -= 1.
    elif mode == 'caffe':
        x[..., 0] -= 103.939
        x[..., 1] -= 116.779
        x[..., 2] -= 123.68

    return x

def adjust_transform_for_image(transform, image, relative_translation):
    """ Adjust a transformation for a specific image.

    The translation of the matrix will be scaled with the size of the image.
    The linear part of the transformation will adjusted so that the origin of the transformation will be at the center of the image.
    """
    height, width, channels = image.shape

    result = transform

    # Scale the translation with the image size if specified.
    if relative_translation:
        result[0:2, 2] *= [width, height]

    # Move the origin of transformation.
    result = change_transform_origin(transform, (0.5 * width, 0.5 * height))

    return result

class TransformParameters:
    """ Struct holding parameters determining how to apply a transformation to an image.

    Args
        fill_mode:             One of: 'constant', 'nearest', 'reflect', 'wrap'
        interpolation:         One of: 'nearest', 'linear', 'cubic', 'area', 'lanczos4'
        cval:                  Fill value to use with fill_mode='constant'
        relative_translation:  If true (the default), interpret translation as a factor of the image size.
                               If false, interpret it as absolute pixels.
    """
    def __init__(
        self,
        fill_mode            = 'nearest',
        interpolation        = 'linear',
        cval                 = 0,
        relative_translation = True,
    ):
        self.fill_mode            = fill_mode
        self.cval                 = cval
        self.interpolation        = interpolation
        self.relative_translation = relative_translation

    def cvBorderMode(self):
        if self.fill_mode == 'constant':
            return cv2.BORDER_CONSTANT
        if self.fill_mode == 'nearest':
            return cv2.BORDER_REPLICATE
        if self.fill_mode == 'reflect':
            return cv2.BORDER_REFLECT_101
        if self.fill_mode == 'wrap':
            return cv2.BORDER_WRAP

    def cvInterpolation(self):
        if self.interpolation == 'nearest':
            return cv2.INTER_NEAREST
        if self.interpolation == 'linear':
            return cv2.INTER_LINEAR
        if self.interpolation == 'cubic':
            return cv2.INTER_CUBIC
        if self.interpolation == 'area':
            return cv2.INTER_AREA
        if self.interpolation == 'lanczos4':
            return cv2.INTER_LANCZOS4

def apply_transform(matrix, image, params):
    """
    Apply a transformation to an image.

    The origin of transformation is at the top left corner of the image.

    The matrix is interpreted such that a point (x, y) on the original image is moved to transform * (x, y) in the generated image.
    Mathematically speaking, that means that the matrix is a transformation from the transformed image space to the original image space.

    Args
      matrix: A homogeneous 3 by 3 matrix holding representing the transformation to apply.
      image:  The image to transform.
      params: The transform parameters (see TransformParameters)
    """
    output = cv2.warpAffine(
        image,
        matrix[:2, :],
        dsize       = (image.shape[1], image.shape[0]),
        flags       = params.cvInterpolation(),
        borderMode  = params.cvBorderMode(),
        borderValue = params.cval,
    )
    return output

def compute_resize_scale(image_shape, min_side=800, max_side=1333):
    """ Compute an image scale such that the image size is constrained to min_side and max_side.

    Args
        min_side: The image's min side will be equal to min_side after resizing.
        max_side: If after resizing the image's max side is above max_side, resize until the max side is equal to max_side.

    Returns
        A resizing scale.
    """
    (rows, cols, _) = image_shape

    smallest_side = min(rows, cols)

    # rescale the image so the smallest side is min_side
    scale = min_side / smallest_side

    # check if the largest side is now greater than max_side, which can happen
    # when images have a large aspect ratio
    largest_side = max(rows, cols)
    if largest_side * scale > max_side:
        scale = max_side / largest_side

    return scale

def resize_image(img, min_side=800, max_side=1333):
    """ Resize an image such that the size is constrained to min_side and max_side.

    Args
        min_side: The image's min side will be equal to min_side after resizing.
        max_side: If after resizing the image's max side is above max_side, resize until the max side is equal to max_side.

    Returns
        A resized image.
    """
    # compute scale to resize the image
    scale = compute_resize_scale(img.shape, min_side=min_side, max_side=max_side)

    # resize the image with the computed scale
    img = cv2.resize(img, None, fx=scale, fy=scale)

    return img, scale

def _uniform(val_range):
    """ Uniformly sample from the given range.

    Args
        val_range: A pair of lower and upper bound.
    """
    return np.random.uniform(val_range[0], val_range[1])

def _check_range(val_range, min_val=None, max_val=None):
    """ Check whether the range is a valid range.

    Args
        val_range: A pair of lower and upper bound.
        min_val: Minimal value for the lower bound.
        max_val: Maximal value for the upper bound.
    """
    if val_range[0] > val_range[1]:
        raise ValueError('interval lower bound > upper bound')
    if min_val is not None and val_range[0] < min_val:
        raise ValueError('invalid interval lower bound')
    if max_val is not None and val_range[1] > max_val:
        raise ValueError('invalid interval upper bound')

def _clip(image):
    """
    Clip and convert an image to np.uint8.

    Args
        image: Image to clip.
    """
    return np.clip(image, 0, 255).astype(np.uint8)

class VisualEffect:
    """ Struct holding parameters and applying image color transformation.

    Args
        contrast_factor:   A factor for adjusting contrast. Should be between 0 and 3.
        brightness_delta:  Brightness offset between -1 and 1 added to the pixel values.
        hue_delta:         Hue offset between -1 and 1 added to the hue channel.
        saturation_factor: A factor multiplying the saturation values of each pixel.
    """

    def __init__(
        self,
        contrast_factor,
        brightness_delta,
        hue_delta,
        saturation_factor,
    ):
        self.contrast_factor = contrast_factor
        self.brightness_delta = brightness_delta
        self.hue_delta = hue_delta
        self.saturation_factor = saturation_factor

    def __call__(self, image):
        """ Apply a visual effect on the image.

        Args
            image: Image to adjust
        """

        if self.contrast_factor:
            image = adjust_contrast(image, self.contrast_factor)
        if self.brightness_delta:
            image = adjust_brightness(image, self.brightness_delta)

        if self.hue_delta or self.saturation_factor:

            image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

            if self.hue_delta:
                image = adjust_hue(image, self.hue_delta)
            if self.saturation_factor:
                image = adjust_saturation(image, self.saturation_factor)

            image = cv2.cvtColor(image, cv2.COLOR_HSV2BGR)

        return image

def random_visual_effect_generator(
    contrast_range=(0.9, 1.1),
    brightness_range=(-.1, .1),
    hue_range=(-0.05, 0.05),
    saturation_range=(0.95, 1.05)
):
    """ Generate visual effect parameters uniformly sampled from the given intervals.

    Args
        contrast_factor:   A factor interval for adjusting contrast. Should be between 0 and 3.
        brightness_delta:  An interval between -1 and 1 for the amount added to the pixels.
        hue_delta:         An interval between -1 and 1 for the amount added to the hue channel.
                           The values are rotated if they exceed 180.
        saturation_factor: An interval for the factor multiplying the saturation values of each
                           pixel.
    """
    _check_range(contrast_range, 0)
    _check_range(brightness_range, -1, 1)
    _check_range(hue_range, -1, 1)
    _check_range(saturation_range, 0)

    def _generate():
        while True:
            yield VisualEffect(
                contrast_factor=_uniform(contrast_range),
                brightness_delta=_uniform(brightness_range),
                hue_delta=_uniform(hue_range),
                saturation_factor=_uniform(saturation_range),
            )

    return _generate()

def adjust_contrast(image, factor):
    """ Adjust contrast of an image.

    Args
        image: Image to adjust.
        factor: A factor for adjusting contrast.
    """
    mean = image.mean(axis=0).mean(axis=0)
    return _clip((image - mean) * factor + mean)

def adjust_brightness(image, delta):
    """ Adjust brightness of an image

    Args
        image: Image to adjust.
        delta: Brightness offset between -1 and 1 added to the pixel values.
    """
    return _clip(image + delta * 255)

def adjust_hue(image, delta):
    """ Adjust hue of an image.

    Args
        image: Image to adjust.
        delta: An interval between -1 and 1 for the amount added to the hue channel.
               The values are rotated if they exceed 180.
    """
    image[..., 0] = np.mod(image[..., 0] + delta * 180, 180)
    return image

def adjust_saturation(image, factor):
    """ Adjust saturation of an image.

    Args
        image: Image to adjust.
        factor: An interval for the factor multiplying the saturation values of each pixel.
    """
    image[..., 1] = np.clip(image[..., 1] * factor, 0 , 255)
    return image
<commit_msg>Update image.py<commit_after>"""
Copyright 2017-2018 Fizyr (https://fizyr.com)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

from __future__ import division
import numpy as np
import cv2
from PIL import Image

from .transform import change_transform_origin

def read_image_bgr(path):
    """ Read an image in BGR format.

    Args
        path: Path to the image.
    """
    # We deliberately don't use cv2.imread here, since it gives no feedback on errors while reading the image.
    image = np.asarray(Image.open(path).convert('RGB'))
    return image[:, :, ::-1].copy()

def preprocess_image(x, mode='caffe'):
    """ Preprocess an image by subtracting the ImageNet mean.

    Args
        x: np.array of shape (None, None, 3) or (3, None, None).
        mode: One of "caffe" or "tf".
            - caffe: will zero-center each color channel with
                respect to the ImageNet dataset, without scaling.
            - tf: will scale pixels between -1 and 1, sample-wise.

    Returns
        The input with the ImageNet mean subtracted.
    """
    # mostly identical to "https://github.com/keras-team/keras-applications/blob/master/keras_applications/imagenet_utils.py"
    # except for converting RGB -> BGR since we assume BGR already

    # covert always to float32 to keep compatibility with opencv
    x = x.astype(np.float32)

    if mode == 'tf':
        x /= 127.5
        x -= 1.
    elif mode == 'caffe':
        x[..., 0] -= 103.939
        x[..., 1] -= 116.779
        x[..., 2] -= 123.68

    return x

def adjust_transform_for_image(transform, image, relative_translation):
    """ Adjust a transformation for a specific image.

    The translation of the matrix will be scaled with the size of the image.
    The linear part of the transformation will adjusted so that the origin of the transformation will be at the center of the image.
    """
    height, width, channels = image.shape

    result = transform

    # Scale the translation with the image size if specified.
    if relative_translation:
        result[0:2, 2] *= [width, height]

    # Move the origin of transformation.
    result = change_transform_origin(transform, (0.5 * width, 0.5 * height))

    return result

class TransformParameters:
    """ Struct holding parameters determining how to apply a transformation to an image.

    Args
        fill_mode:             One of: 'constant', 'nearest', 'reflect', 'wrap'
        interpolation:         One of: 'nearest', 'linear', 'cubic', 'area', 'lanczos4'
        cval:                  Fill value to use with fill_mode='constant'
        relative_translation:  If true (the default), interpret translation as a factor of the image size.
                               If false, interpret it as absolute pixels.
    """
    def __init__(
        self,
        fill_mode            = 'nearest',
        interpolation        = 'linear',
        cval                 = 0,
        relative_translation = True,
    ):
        self.fill_mode            = fill_mode
        self.cval                 = cval
        self.interpolation        = interpolation
        self.relative_translation = relative_translation

    def cvBorderMode(self):
        if self.fill_mode == 'constant':
            return cv2.BORDER_CONSTANT
        if self.fill_mode == 'nearest':
            return cv2.BORDER_REPLICATE
        if self.fill_mode == 'reflect':
            return cv2.BORDER_REFLECT_101
        if self.fill_mode == 'wrap':
            return cv2.BORDER_WRAP

    def cvInterpolation(self):
        if self.interpolation == 'nearest':
            return cv2.INTER_NEAREST
        if self.interpolation == 'linear':
            return cv2.INTER_LINEAR
        if self.interpolation == 'cubic':
            return cv2.INTER_CUBIC
        if self.interpolation == 'area':
            return cv2.INTER_AREA
        if self.interpolation == 'lanczos4':
            return cv2.INTER_LANCZOS4

def apply_transform(matrix, image, params):
    """
    Apply a transformation to an image.

    The origin of transformation is at the top left corner of the image.

    The matrix is interpreted such that a point (x, y) on the original image is moved to transform * (x, y) in the generated image.
    Mathematically speaking, that means that the matrix is a transformation from the transformed image space to the original image space.

    Args
      matrix: A homogeneous 3 by 3 matrix holding representing the transformation to apply.
      image:  The image to transform.
      params: The transform parameters (see TransformParameters)
    """
    output = cv2.warpAffine(
        image,
        matrix[:2, :],
        dsize       = (image.shape[1], image.shape[0]),
        flags       = params.cvInterpolation(),
        borderMode  = params.cvBorderMode(),
        borderValue = params.cval,
    )
    return output

def compute_resize_scale(image_shape, min_side=800, max_side=1333):
    """ Compute an image scale such that the image size is constrained to min_side and max_side.

    Args
        min_side: The image's min side will be equal to min_side after resizing.
        max_side: If after resizing the image's max side is above max_side, resize until the max side is equal to max_side.

    Returns
        A resizing scale.
    """
    (rows, cols, _) = image_shape

    smallest_side = min(rows, cols)

    # rescale the image so the smallest side is min_side
    scale = min_side / smallest_side

    # check if the largest side is now greater than max_side, which can happen
    # when images have a large aspect ratio
    largest_side = max(rows, cols)
    if largest_side * scale > max_side:
        scale = max_side / largest_side

    return scale

def resize_image(img, min_side=800, max_side=1333):
    """ Resize an image such that the size is constrained to min_side and max_side.

    Args
        min_side: The image's min side will be equal to min_side after resizing.
        max_side: If after resizing the image's max side is above max_side, resize until the max side is equal to max_side.

    Returns
        A resized image.
    """
    # compute scale to resize the image
    scale = compute_resize_scale(img.shape, min_side=min_side, max_side=max_side)

    # resize the image with the computed scale
    img = cv2.resize(img, None, fx=scale, fy=scale)

    return img, scale

def _uniform(val_range):
    """ Uniformly sample from the given range.

    Args
        val_range: A pair of lower and upper bound.
    """
    return np.random.uniform(val_range[0], val_range[1])

def _check_range(val_range, min_val=None, max_val=None):
    """ Check whether the range is a valid range.

    Args
        val_range: A pair of lower and upper bound.
        min_val: Minimal value for the lower bound.
        max_val: Maximal value for the upper bound.
    """
    if val_range[0] > val_range[1]:
        raise ValueError('interval lower bound > upper bound')
    if min_val is not None and val_range[0] < min_val:
        raise ValueError('invalid interval lower bound')
    if max_val is not None and val_range[1] > max_val:
        raise ValueError('invalid interval upper bound')

def _clip(image):
    """
    Clip and convert an image to np.uint8.

    Args
        image: Image to clip.
    """
    return np.clip(image, 0, 255).astype(np.uint8)

class VisualEffect:
    """ Struct holding parameters and applying image color transformation.

    Args
        contrast_factor:   A factor for adjusting contrast. Should be between 0 and 3.
        brightness_delta:  Brightness offset between -1 and 1 added to the pixel values.
        hue_delta:         Hue offset between -1 and 1 added to the hue channel.
        saturation_factor: A factor multiplying the saturation values of each pixel.
    """

    def __init__(
        self,
        contrast_factor,
        brightness_delta,
        hue_delta,
        saturation_factor,
    ):
        self.contrast_factor = contrast_factor
        self.brightness_delta = brightness_delta
        self.hue_delta = hue_delta
        self.saturation_factor = saturation_factor

    def __call__(self, image):
        """ Apply a visual effect on the image.

        Args
            image: Image to adjust
        """

        if self.contrast_factor:
            image = adjust_contrast(image, self.contrast_factor)
        if self.brightness_delta:
            image = adjust_brightness(image, self.brightness_delta)

        if self.hue_delta or self.saturation_factor:

            image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

            if self.hue_delta:
                image = adjust_hue(image, self.hue_delta)
            if self.saturation_factor:
                image = adjust_saturation(image, self.saturation_factor)

            image = cv2.cvtColor(image, cv2.COLOR_HSV2BGR)

        return image

def random_visual_effect_generator(
    contrast_range=(0.9, 1.1),
    brightness_range=(-.1, .1),
    hue_range=(-0.05, 0.05),
    saturation_range=(0.95, 1.05)
):
    """ Generate visual effect parameters uniformly sampled from the given intervals.

    Args
        contrast_factor:   A factor interval for adjusting contrast. Should be between 0 and 3.
        brightness_delta:  An interval between -1 and 1 for the amount added to the pixels.
        hue_delta:         An interval between -1 and 1 for the amount added to the hue channel.
                           The values are rotated if they exceed 180.
        saturation_factor: An interval for the factor multiplying the saturation values of each
                           pixel.
    """
    _check_range(contrast_range, 0)
    _check_range(brightness_range, -1, 1)
    _check_range(hue_range, -1, 1)
    _check_range(saturation_range, 0)

    def _generate():
        while True:
            yield VisualEffect(
                contrast_factor=_uniform(contrast_range),
                brightness_delta=_uniform(brightness_range),
                hue_delta=_uniform(hue_range),
                saturation_factor=_uniform(saturation_range),
            )

    return _generate()

def adjust_contrast(image, factor):
    """ Adjust contrast of an image.

    Args
        image: Image to adjust.
        factor: A factor for adjusting contrast.
    """
    mean = image.mean(axis=0).mean(axis=0)
    return _clip((image - mean) * factor + mean)

def adjust_brightness(image, delta):
    """ Adjust brightness of an image

    Args
        image: Image to adjust.
        delta: Brightness offset between -1 and 1 added to the pixel values.
    """
    return _clip(image + delta * 255)

def adjust_hue(image, delta):
    """ Adjust hue of an image.

    Args
        image: Image to adjust.
        delta: An interval between -1 and 1 for the amount added to the hue channel.
               The values are rotated if they exceed 180.
    """
    image[..., 0] = np.mod(image[..., 0] + delta * 180, 180)
    return image

def adjust_saturation(image, factor):
    """ Adjust saturation of an image.

    Args
        image: Image to adjust.
        factor: An interval for the factor multiplying the saturation values of each pixel.
    """
    image[..., 1] = np.clip(image[..., 1] * factor, 0 , 255)
    return image
<|endoftext|>


<commit_before>#!/usr/bin/python
################################################################################
#
#	Llama2c.py
#
#	Main command line interface for the ArdySerial stuff
#	- Creates the Ardy instance
#	- makes the connection to the Ardy
#	- I2c and serial probing
#	- test things?
#
################################################################################
#
#	v001 2017-05-09 SDL initial version

################################################################################
# you may need to install pyserial:
# 	sudo pip install pyserial
# 	on windows, c:\Python27\Scripts\pip.exe install pyserial
################################################################################

################################################################################
# importing libraries...

import sys
sys.dont_write_bytecode = True
sys.path.append( 'devices' )
sys.path.append( 'libs' )

import getopt

# connection
from libArdySer import ArdySer

################################################################################
# signal stuff

import signal

def signal_handler( signal, frame ):
	print( "BREAK." )
	sys.exit( 0 )

# and immediately install it on including this library
signal.signal( signal.SIGINT, signal_handler )
#signal.pause()

################################################################################
# main command line interface routines

class PyArdyApp:

	def usage( self ):
		print "App.py <options>"
		print "	-a TXT  attach to port with 'TXT' matching"
		print "	-l	  List detected serial ports"
		print "	-p	  perform I2C probe"
		print "	-s	  Simulated Arduino connection mode"

	def run( self, ardy ):
		print "replace this function."

	def main( self, argv ):
		ardy = ArdySer( True )

		doI2cProbe = False
		arduinotext = None

		try:
			opts, args = getopt.getopt(argv,"hlspa:",["arduino="])

		except getopt.GetoptError:
			self.usage()
			sys.exit(2)

		for opt, arg in opts:
			if opt == '-l':
				ardy.listSerialPorts()
				return

			elif opt == '-s':
				ardy.EnableSimulation()

			elif opt == '-p':
				doI2cProbe = True

			elif opt == '-a':
				arduinotext = arg

			elif opt in ("-a", "--arduino"):
				arduinotext = arg

			else:
				self.usage()
				sys.exit()

			ardy.openConnection( arduinotext )

			if not ardy.isConnected():
				print " ===================="
				print "  Arduino not found!"
				print " ===================="
				print
				self.usage()
				return

			if doI2cProbe is True:
				ardy.i2cProbe()
				return

			self.run( ardy )

# put this in your main app as well.
#if __name__ == "__main__":
#		paa = PyArdyApp()
#		paa.main(sys.argv[1:])
<commit_msg>chmod<commit_after>#!/usr/bin/python
################################################################################
#
#	Llama2c.py
#
#	Main command line interface for the ArdySerial stuff
#	- Creates the Ardy instance
#	- makes the connection to the Ardy
#	- I2c and serial probing
#	- test things?
#
################################################################################
#
#	v001 2017-05-09 SDL initial version

################################################################################
# you may need to install pyserial:
# 	sudo pip install pyserial
# 	on windows, c:\Python27\Scripts\pip.exe install pyserial
################################################################################

################################################################################
# importing libraries...

import sys
sys.dont_write_bytecode = True
sys.path.append( 'devices' )
sys.path.append( 'libs' )

import getopt

# connection
from libArdySer import ArdySer

################################################################################
# signal stuff

import signal

def signal_handler( signal, frame ):
	print( "BREAK." )
	sys.exit( 0 )

# and immediately install it on including this library
signal.signal( signal.SIGINT, signal_handler )
#signal.pause()

################################################################################
# main command line interface routines

class PyArdyApp:

	def usage( self ):
		print "App.py <options>"
		print "	-a TXT  attach to port with 'TXT' matching"
		print "	-l	  List detected serial ports"
		print "	-p	  perform I2C probe"
		print "	-s	  Simulated Arduino connection mode"

	def run( self, ardy ):
		print "replace this function."

	def main( self, argv ):
		ardy = ArdySer( True )

		doI2cProbe = False
		arduinotext = None

		try:
			opts, args = getopt.getopt(argv,"hlspa:",["arduino="])

		except getopt.GetoptError:
			self.usage()
			sys.exit(2)

		for opt, arg in opts:
			if opt == '-l':
				ardy.listSerialPorts()
				return

			elif opt == '-s':
				ardy.EnableSimulation()

			elif opt == '-p':
				doI2cProbe = True

			elif opt == '-a':
				arduinotext = arg

			elif opt in ("-a", "--arduino"):
				arduinotext = arg

			else:
				self.usage()
				sys.exit()

			ardy.openConnection( arduinotext )

			if not ardy.isConnected():
				print " ===================="
				print "  Arduino not found!"
				print " ===================="
				print
				self.usage()
				return

			if doI2cProbe is True:
				ardy.i2cProbe()
				return

			self.run( ardy )

# put this in your main app as well.
#if __name__ == "__main__":
#		paa = PyArdyApp()
#		paa.main(sys.argv[1:])
<|endoftext|>