<commit_before>from __future__ import absolute_import

import abc

from ._compat import ABC, FileNotFoundError

# Use mypy's comment syntax for Python 2 compatibility
try:
    from typing import BinaryIO, Iterable, Text
except ImportError:
    pass

class ResourceReader(ABC):
    """Abstract base class for loaders to provide resource reading support."""

    @abc.abstractmethod
    def open_resource(self, resource):
        # type: (Text) -> BinaryIO
        """Return an opened, file-like object for binary reading.

        The 'resource' argument is expected to represent only a file name.
        If the resource cannot be found, FileNotFoundError is raised.
        """
        # This deliberately raises FileNotFoundError instead of
        # NotImplementedError so that if this method is accidentally called,
        # it'll still do the right thing.
        raise FileNotFoundError

    @abc.abstractmethod
    def resource_path(self, resource):
        # type: (Text) -> Text
        """Return the file system path to the specified resource.

        The 'resource' argument is expected to represent only a file name.
        If the resource does not exist on the file system, raise
        FileNotFoundError.
        """
        # This deliberately raises FileNotFoundError instead of
        # NotImplementedError so that if this method is accidentally called,
        # it'll still do the right thing.
        raise FileNotFoundError

    @abc.abstractmethod
    def is_resource(self, path):
        # type: (Text) -> bool
        """Return True if the named 'path' is a resource.

        Files are resources, directories are not.
        """
        raise FileNotFoundError

    @abc.abstractmethod
    def contents(self):
        # type: () -> Iterable[str]
        """Return an iterable of entries in `package`."""
        raise FileNotFoundError

class Traversable(ABC):
    """
    An object with a subset of pathlib.Path methods suitable for
    traversing directories and opening files.
    """

    @abc.abstractmethod
    def iterdir(self):
        """
        Yield Traversable objects in self
        """

    @abc.abstractmethod
    def read_bytes(self):
        """
        Read contents of self as bytes
        """

    @abc.abstractmethod
    def read_text(self, encoding=None):
        """
        Read contents of self as bytes
        """

    @abc.abstractmethod
    def is_dir(self):
        """
        Return True if self is a dir
        """

    @abc.abstractmethod
    def is_file(self):
        """
        Return True if self is a file
        """

    @abc.abstractmethod
    def joinpath(self, child):
        """
        Return Traversable child in self
        """

    @abc.abstractmethod
    def __truediv__(self, child):
        """
        Return Traversable child in self
        """

    @abc.abstractmethod
    def open(self, mode='r', *args, **kwargs):
        """
        mode may be 'r' or 'rb' to open as text or binary. Return a handle
        suitable for reading (same as pathlib.Path.open).

        When opening as text, accepts encoding parameters such as those
        accepted by io.TextIOWrapper.
        """

    @abc.abstractproperty
    def name(self):
        # type: () -> str
        """
        The base name of this object without any parent references.
        """

class TraversableResources(ResourceReader):
    @abc.abstractmethod
    def files(self):
        """Return a Traversable object for the loaded package."""

    def open_resource(self, resource):
        return self.files().joinpath(resource).open('rb')

    def resource_path(self, resource):
        raise FileNotFoundError(resource)

    def is_resource(self, path):
        return self.files().joinpath(path).isfile()

    def contents(self):
        return (item.name for item in self.files().iterdir())
<commit_msg>Make Traversable a protocol.<commit_after>from __future__ import absolute_import

import abc
import typing

from ._compat import ABC, FileNotFoundError

# Use mypy's comment syntax for Python 2 compatibility
try:
    from typing import BinaryIO, Iterable, Text
except ImportError:
    pass

class ResourceReader(ABC):
    """Abstract base class for loaders to provide resource reading support."""

    @abc.abstractmethod
    def open_resource(self, resource):
        # type: (Text) -> BinaryIO
        """Return an opened, file-like object for binary reading.

        The 'resource' argument is expected to represent only a file name.
        If the resource cannot be found, FileNotFoundError is raised.
        """
        # This deliberately raises FileNotFoundError instead of
        # NotImplementedError so that if this method is accidentally called,
        # it'll still do the right thing.
        raise FileNotFoundError

    @abc.abstractmethod
    def resource_path(self, resource):
        # type: (Text) -> Text
        """Return the file system path to the specified resource.

        The 'resource' argument is expected to represent only a file name.
        If the resource does not exist on the file system, raise
        FileNotFoundError.
        """
        # This deliberately raises FileNotFoundError instead of
        # NotImplementedError so that if this method is accidentally called,
        # it'll still do the right thing.
        raise FileNotFoundError

    @abc.abstractmethod
    def is_resource(self, path):
        # type: (Text) -> bool
        """Return True if the named 'path' is a resource.

        Files are resources, directories are not.
        """
        raise FileNotFoundError

    @abc.abstractmethod
    def contents(self):
        # type: () -> Iterable[str]
        """Return an iterable of entries in `package`."""
        raise FileNotFoundError

@typing.runtime_checkable
class Traversable(typing.Protocol):
    """
    An object with a subset of pathlib.Path methods suitable for
    traversing directories and opening files.
    """

    @abc.abstractmethod
    def iterdir(self):
        """
        Yield Traversable objects in self
        """

    @abc.abstractmethod
    def read_bytes(self):
        """
        Read contents of self as bytes
        """

    @abc.abstractmethod
    def read_text(self, encoding=None):
        """
        Read contents of self as bytes
        """

    @abc.abstractmethod
    def is_dir(self):
        """
        Return True if self is a dir
        """

    @abc.abstractmethod
    def is_file(self):
        """
        Return True if self is a file
        """

    @abc.abstractmethod
    def joinpath(self, child):
        """
        Return Traversable child in self
        """

    @abc.abstractmethod
    def __truediv__(self, child):
        """
        Return Traversable child in self
        """

    @abc.abstractmethod
    def open(self, mode='r', *args, **kwargs):
        """
        mode may be 'r' or 'rb' to open as text or binary. Return a handle
        suitable for reading (same as pathlib.Path.open).

        When opening as text, accepts encoding parameters such as those
        accepted by io.TextIOWrapper.
        """

    @abc.abstractproperty
    def name(self):
        # type: () -> str
        """
        The base name of this object without any parent references.
        """

class TraversableResources(ResourceReader):
    @abc.abstractmethod
    def files(self):
        """Return a Traversable object for the loaded package."""

    def open_resource(self, resource):
        return self.files().joinpath(resource).open('rb')

    def resource_path(self, resource):
        raise FileNotFoundError(resource)

    def is_resource(self, path):
        return self.files().joinpath(path).isfile()

    def contents(self):
        return (item.name for item in self.files().iterdir())
<|endoftext|>


<commit_before>""" impyute.util.preprocess """
from functools import wraps

# Hacky way to handle python2 not having `ModuleNotFoundError`
# pylint: disable=redefined-builtin, missing-docstring
try:
    raise ModuleNotFoundError
except NameError:
    class ModuleNotFoundError(Exception):
        pass
except ModuleNotFoundError:
    pass
# pylint: enable=redefined-builtin, missing-docstring

def execute_fn_with_args_and_or_kwargs(fn, args, kwargs):
    """ If args + kwargs aren't accepted only args are passed in"""
    try:
        return fn(*args, **kwargs)
    except TypeError:
        return fn(*args)

def get_pandas_df():
    """ Gets pandas DataFrame if we can import it """
    try:
        import pandas as pd
        df = pd.DataFrame
    except (ModuleNotFoundError, ImportError):
        df = None
    return df

def preprocess(fn):
    """ Base preprocess function for commonly used preprocessing

    PARAMETERS
    ----------
    data: numpy.ndarray
        Data to impute.

    RETURNS
    -------
    bool
        True if `data` is correctly formatted

    """
    @wraps(fn)
    def wrapper(*args, **kwargs):
        """ Run input checks"""
        # convert tuple to list so args can be modified
        args = list(args)

        # Either make a copy or use a pointer to the original
        if "inplace" in kwargs and kwargs['inplace']:
            args[0] = args[0]
        else:
            args[0] = args[0].copy()

        results = execute_fn_with_args_and_or_kwargs(fn, args, kwargs)

        ## If Pandas exists, and the input data is a dataframe then cast the input
        ## to an np.array and cast the output back to a DataFrame.
        pd_DataFrame = get_pandas_df()
        if pd_DataFrame and isinstance(args[0], pd_DataFrame):
            args[0] = args[0].values
            results = pd_DataFrame(results)

        return results
    return wrapper
<commit_msg>[#77] cleanup inplace handling + ws<commit_after>""" impyute.util.preprocess """
from functools import wraps

## Hacky way to handle python2 not having `ModuleNotFoundError`
# pylint: disable=redefined-builtin, missing-docstring
try:
    raise ModuleNotFoundError
except NameError:
    class ModuleNotFoundError(Exception):
        pass
except ModuleNotFoundError:
    pass
# pylint: enable=redefined-builtin, missing-docstring

def execute_fn_with_args_and_or_kwargs(fn, args, kwargs):
    """ If args + kwargs aren't accepted only args are passed in"""
    try:
        return fn(*args, **kwargs)
    except TypeError:
        return fn(*args)

def get_pandas_df():
    """ Gets pandas DataFrame if we can import it """
    try:
        import pandas as pd
        df = pd.DataFrame
    except (ModuleNotFoundError, ImportError):
        df = None
    return df

def preprocess(fn):
    """ Base preprocess function for commonly used preprocessing

    PARAMETERS
    ----------
    data: numpy.ndarray
        Data to impute.

    RETURNS
    -------
    bool
        True if `data` is correctly formatted
    """
    @wraps(fn)
    def wrapper(*args, **kwargs):
        """ Run input checks"""
        ## convert tuple to list so args can be modified
        args = list(args)
        ## Either make a copy or use a pointer to the original
        if "inplace" in kwargs and kwargs['inplace']:
            args[0] = args[0]
        else:
            args[0] = args[0].copy()
        ## function invokation
        results = execute_fn_with_args_and_or_kwargs(fn, args, kwargs)
        ## If Pandas exists, and the input data is a dataframe then cast the input
        ## to an np.array and cast the output back to a DataFrame.
        pd_DataFrame = get_pandas_df()
        if pd_DataFrame and isinstance(args[0], pd_DataFrame):
            args[0] = args[0].values
            results = pd_DataFrame(results)

        return results
    return wrapper
<|endoftext|>


<commit_before>import sys
from math import ceil

from OpenGL.GL import GL_LESS, GL_TRUE, GL_DEPTH_TEST, GL_STENCIL_TEST
from OpenGL.GL import GL_COLOR_ARRAY, GL_VERTEX_ARRAY, GL_TRIANGLES
from OpenGL.GL import GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT
from OpenGL.GL import GL_UNSIGNED_SHORT, GL_FLOAT, GL_MODELVIEW
from OpenGL.GL import GL_CULL_FACE, GL_FRONT, GL_MODELVIEW_MATRIX

from OpenGL.GL import glMatrixMode, glLoadIdentity, glOrtho, glRotatef
from OpenGL.GL import glDepthMask, glDepthFunc, glCullFace
from OpenGL.GL import glEnable, glClearColor, glEnableClientState, glClear
from OpenGL.GL import glDrawElements, glGetFloatv

from OpenGL.GL import glReadBuffer, glReadPixels, GL_RGBA, glFlush

from OpenGL.GLUT import GLUT_DEPTH, GLUT_RGB, GLUT_ALPHA

from OpenGL.GLUT import glutInitWindowSize, glutPostRedisplay
from OpenGL.GLUT import glutCreateWindow, glutInit, glutInitWindowPosition
from OpenGL.GLUT import glutInitDisplayMode, glutLeaveMainLoop, glutDisplayFunc

from numpy import zeros, ones, array, concatenate

from .ShadersHelper import ShadersHelper

class View:
    """Viewport for Faces."""

    __triangles = None
    __principal_components = None
    __deviations = None
    __mean_face = None

    def __init__(self, size):
        """Initialize viewport with initial Face rotation and position."""
        self.__size = size

        self.__height, self.__width = self.__size
        self.__output_image = zeros(self.__width * self.__height * 4,
                                    dtype='f')

        self.__light = None
        self.__rotation = (0., 0., 0.)
        self.__need_rotation = True
        self.__face = None

        self.__init_display()
        self.__adjust_viewport()
        self.__enable_depth_test()

        glEnableClientState(GL_COLOR_ARRAY)
        glEnableClientState(GL_VERTEX_ARRAY)

        glClearColor(1., 1., 1., 0.)

        self.__sh = ShadersHelper(['face.vert', 'depth.vert'],
                                  ['face.frag', 'depth.frag'], 1, 2)

        glutDisplayFunc(self.__display)
        self.__callback = None

    def get_size(self):
        """Get size of the viewport."""
        return self.__size

    @property
    def light(self):
        return self.__light

    @light.setter
    def light(self, light):
        self.__light = light

    @property
    def rotation(self):
        return self.__rotation

    @rotation.setter
    def rotation(self, rotation):
        self.__need_rotation = True
        self.__rotation = rotation

    @property
    def face(self):
        return self.__face

    @face.setter
    def face(self, face):
        self.__face = face

    def redraw(self, callback=None):
        """Trigger redisplay and trigger callback after render."""
        # print('Set callback to', callback)
        self.__callback = callback
        glutPostRedisplay()

    def get_image(self):
        """Copy RGBA data from the viewport to NumPy Matrix of float."""
        glReadBuffer(GL_FRONT)
        glReadPixels(0, 0, self.__width, self.__height, GL_RGBA, GL_FLOAT,
                     self.__output_image)
        return self.__output_image

    def close(self):
        """Close the viewport."""
        glutLeaveMainLoop()

    @staticmethod
    def set_triangles(triangles):
        """Set triangles of the model.

        Allows to not allocate additional memory for each point,
        which is used in multiple triangles.
        """
        View.__triangles = triangles

    @staticmethod
    def set_principal_components(principal_components):
        View.__principal_components = principal_components

    @staticmethod
    def set_deviations(deviations):
        View.__deviations = deviations

    @staticmethod
    def set_mean_face(mean_face):
        View.__mean_face = mean_face

    def __display(self):
        """Render the model by existent vertices, colors and triangles."""
        if self.__need_rotation:
            glRotatef(1., *self.__rotation)
            self.__need_rotation = False
        rotation_matrix = array(glGetFloatv(GL_MODELVIEW_MATRIX), dtype='f')

        self.__sh.add_attribute(0, self.__mean_face, 'mean_position')
        self.__sh.bind_buffer()

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        self.__sh.use_shaders()

        self.__sh.bind_uniform_matrix(rotation_matrix, 'rotation_matrix')
        self.__sh.bind_uniform_vector(self.__face.light.astype('f'),
                                      'light_vector')
        coefficients_amount = len(self.__face.coefficients)
        indices = -ones(199, dtype='i')
        indices[:coefficients_amount] = array(range(coefficients_amount))
        self.__sh.bind_uniform_ints(indices, 'indices')

        coefficients = zeros(199, dtype='f')
        coefficients[:coefficients_amount] = self.__face.coefficients
        self.__sh.bind_uniform_floats(coefficients, 'coefficients')

        if not self.__texture_bound:
            self.__bind_texture()

        glDrawElements(GL_TRIANGLES, View.__triangles.size,
                       GL_UNSIGNED_SHORT, View.__triangles)

        self.__sh.clear()

        glFlush()
        if self.__callback is not None:
            self.__callback()

    def __bind_texture(self):
        size = View.__principal_components.size // 3
        data = View.__principal_components.transpose() * View.__deviations

        columns = 2**13
        rows = ceil(size / columns)

        padding = [0] * (rows * columns - size) * 3
        data = concatenate((data.flatten(), padding))

        self.__sh.create_float_texture(data, (columns, rows), 2, 3)

    def __init_display(self):
        """Initialize the viewport with specified size."""
        glutInitDisplayMode(GLUT_RGB | GLUT_ALPHA | GLUT_DEPTH)
        glutInitWindowSize(*self.__size)

        glutInitWindowPosition(0, 0)
        glutInit(sys.argv)
        glutCreateWindow(b"Morphable face model")

    def __adjust_viewport(self):
        """Initialize rotation matrix and viwport box."""
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()

        SIDE_LENGTH = .5
        glOrtho(-SIDE_LENGTH, SIDE_LENGTH, -SIDE_LENGTH, SIDE_LENGTH,
                -2 * SIDE_LENGTH, 2 * SIDE_LENGTH)

    def __enable_depth_test(self):
        """Enable depth test and faces culling.

        Needed to not render invisible vertices and triangles.
        """
        glDepthMask(GL_TRUE)
        glDepthFunc(GL_LESS)

        glEnable(GL_CULL_FACE)
        glCullFace(GL_FRONT)

        glEnable(GL_DEPTH_TEST)
        glEnable(GL_STENCIL_TEST)
<commit_msg>Initializing links and uniforms in View constructor instead of using 'if' in 'display' method<commit_after>import sys
from math import ceil

from OpenGL.GL import GL_LESS, GL_TRUE, GL_DEPTH_TEST, GL_STENCIL_TEST
from OpenGL.GL import GL_COLOR_ARRAY, GL_VERTEX_ARRAY, GL_TRIANGLES
from OpenGL.GL import GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT
from OpenGL.GL import GL_UNSIGNED_SHORT, GL_FLOAT, GL_MODELVIEW
from OpenGL.GL import GL_CULL_FACE, GL_FRONT, GL_MODELVIEW_MATRIX

from OpenGL.GL import glMatrixMode, glLoadIdentity, glOrtho, glRotatef
from OpenGL.GL import glDepthMask, glDepthFunc, glCullFace
from OpenGL.GL import glEnable, glClearColor, glEnableClientState, glClear
from OpenGL.GL import glDrawElements, glGetFloatv

from OpenGL.GL import glReadBuffer, glReadPixels, GL_RGBA, glFlush

from OpenGL.GLUT import GLUT_DEPTH, GLUT_RGB, GLUT_ALPHA

from OpenGL.GLUT import glutInitWindowSize, glutPostRedisplay
from OpenGL.GLUT import glutCreateWindow, glutInit, glutInitWindowPosition
from OpenGL.GLUT import glutInitDisplayMode, glutLeaveMainLoop, glutDisplayFunc

from numpy import zeros, ones, array, concatenate

from .ShadersHelper import ShadersHelper

class View:
    """Viewport for Faces."""

    __triangles = None
    __principal_components = None
    __deviations = None
    __mean_face = None

    def __init__(self, size):
        """Initialize viewport with initial Face rotation and position."""
        self.__size = size

        self.__height, self.__width = self.__size
        self.__output_image = zeros(self.__width * self.__height * 4,
                                    dtype='f')

        self.__light = None
        self.__rotation = (0., 0., 0.)
        self.__need_rotation = True
        self.__face = None

        self.__init_display()
        self.__adjust_viewport()
        self.__enable_depth_test()

        glEnableClientState(GL_COLOR_ARRAY)
        glEnableClientState(GL_VERTEX_ARRAY)

        glClearColor(1., 1., 1., 0.)

        self.__sh = ShadersHelper(['face.vert', 'depth.vert'],
                                  ['face.frag', 'depth.frag'], 1, 2)

        glutDisplayFunc(self.__display)
        self.__callback = None

        self.__sh.add_attribute(0, self.__mean_face, 'mean_position')
        self.__sh.bind_buffer()
        self.__sh.use_shaders()
        self.__sh.link_texture('principal_components', 0)
        self.__sh.link_texture('depth_map', 1)
        self.__bind_texture()
        self.__sh.bind_depth_texture(self.__size)

    def get_size(self):
        """Get size of the viewport."""
        return self.__size

    @property
    def light(self):
        return self.__light

    @light.setter
    def light(self, light):
        self.__light = light

    @property
    def rotation(self):
        return self.__rotation

    @rotation.setter
    def rotation(self, rotation):
        self.__need_rotation = True
        self.__rotation = rotation

    @property
    def face(self):
        return self.__face

    @face.setter
    def face(self, face):
        self.__face = face

    def redraw(self, callback=None):
        """Trigger redisplay and trigger callback after render."""
        # print('Set callback to', callback)
        self.__callback = callback
        glutPostRedisplay()

    def get_image(self):
        """Copy RGBA data from the viewport to NumPy Matrix of float."""
        glReadBuffer(GL_FRONT)
        glReadPixels(0, 0, self.__width, self.__height, GL_RGBA, GL_FLOAT,
                     self.__output_image)
        return self.__output_image

    def close(self):
        """Close the viewport."""
        glutLeaveMainLoop()

    @staticmethod
    def set_triangles(triangles):
        """Set triangles of the model.

        Allows to not allocate additional memory for each point,
        which is used in multiple triangles.
        """
        View.__triangles = triangles

    @staticmethod
    def set_principal_components(principal_components):
        View.__principal_components = principal_components

    @staticmethod
    def set_deviations(deviations):
        View.__deviations = deviations

    @staticmethod
    def set_mean_face(mean_face):
        View.__mean_face = mean_face

    def __display(self):
        """Render the model by existent vertices, colors and triangles."""
        if self.__need_rotation:
            glRotatef(1., *self.__rotation)
            self.__need_rotation = False
        rotation_matrix = array(glGetFloatv(GL_MODELVIEW_MATRIX), dtype='f')

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        self.__sh.use_shaders()

        self.__sh.bind_uniform_matrix(rotation_matrix, 'rotation_matrix')
        self.__sh.bind_uniform_vector(self.__face.light.astype('f'),
                                      'light_vector')
        coefficients_amount = len(self.__face.coefficients)
        indices = -ones(199, dtype='i')
        indices[:coefficients_amount] = array(range(coefficients_amount))
        self.__sh.bind_uniform_ints(indices, 'indices')

        coefficients = zeros(199, dtype='f')
        coefficients[:coefficients_amount] = self.__face.coefficients
        self.__sh.bind_uniform_floats(coefficients, 'coefficients')

        if not self.__texture_bound:
            self.__bind_texture()

        glDrawElements(GL_TRIANGLES, View.__triangles.size,
                       GL_UNSIGNED_SHORT, View.__triangles)

        self.__sh.clear()

        glFlush()
        if self.__callback is not None:
            self.__callback()

    def __bind_texture(self):
        size = View.__principal_components.size // 3
        data = View.__principal_components.transpose() * View.__deviations

        columns = 2**13
        rows = ceil(size / columns)

        padding = [0] * (rows * columns - size) * 3
        data = concatenate((data.flatten(), padding))

        self.__sh.create_float_texture(data, (columns, rows), 2, 3)

    def __init_display(self):
        """Initialize the viewport with specified size."""
        glutInitDisplayMode(GLUT_RGB | GLUT_ALPHA | GLUT_DEPTH)
        glutInitWindowSize(*self.__size)

        glutInitWindowPosition(0, 0)
        glutInit(sys.argv)
        glutCreateWindow(b"Morphable face model")

    def __adjust_viewport(self):
        """Initialize rotation matrix and viwport box."""
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()

        SIDE_LENGTH = .5
        glOrtho(-SIDE_LENGTH, SIDE_LENGTH, -SIDE_LENGTH, SIDE_LENGTH,
                -2 * SIDE_LENGTH, 2 * SIDE_LENGTH)

    def __enable_depth_test(self):
        """Enable depth test and faces culling.

        Needed to not render invisible vertices and triangles.
        """
        glDepthMask(GL_TRUE)
        glDepthFunc(GL_LESS)

        glEnable(GL_CULL_FACE)
        glCullFace(GL_FRONT)

        glEnable(GL_DEPTH_TEST)
        glEnable(GL_STENCIL_TEST)
<|endoftext|>


<commit_before>import bluetooth
import bt_task_handler

class BT_Server:
    """Create the server socket with predefined port and backlog value
       Returns a BluetoothSocket"""

    def __init__(self, server_addr, port, backlog, client_addr=""):
        # Sever bluetooth mac-address
        self.server_addr = server_addr
        self.port = port
        # Number of unaccepted connections before refusing new ones
        self.backlog = backlog
        # (the only address from which the server will accept connections)
        self.client_addr = client_addr

        # Set up server socket
        self.server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
        self.server_sock.setblocking(True)
        self.server_sock.bind((server_addr, port))
        # Enable the server to accept connections
        self.server_sock.listen(backlog)

        # Data received from client
        self.incoming_data = None
        # Data to be sent to client
        self.outgoing_data = None

        self.client_sock = None
        self.accp_client_addr = None

    def accept_connection(self):
        # TODO: Accept connection from valid client (requires change of backlog)
        print("in accept_connection")
        (self.client_sock, self.accp_client_addr) = self.server_sock.accept()

    # if accp_client_addr == client_addr

    def post_to_incoming(self):
        print("Server: staring to post to incoming")
        bt_task_handler.post_incoming(bt_task_handler.BT_task(self.incoming_data, ""))
        print("Server done posting to incoming, returning to main")

    def send_data(self, data=None):
        print("Server: sending!")
        if not data:
            self.client_sock.send(self.outgoing_data)
        else:
            self.client_sock.send(data)
        print("Server: sent! Returning to main")

    def _pop_from_outgoing(self):
        return bt_task_handler.pop_outgoing()

    """Updates incoming_data. Returns true if data was updated,
       false otherwise"""

    def update_incoming(self):
        has_new_incoming = False
        try:
            self.client_sock.settimeout(0.1)
            data = self.client_sock.recv(1024).decode('utf-8')
            print("bt_server: Data =", data)
            if len(data) != 0:  # TODO or None? (using json)
                self.incoming_data = data
                has_new_incoming = True
        except bluetooth.btcommon.BluetoothError:
            pass
        finally:
            self.client_sock.settimeout(None)
        return has_new_incoming

    """Updates outgoing_data. Returns true if data was updated,
       false otherwise"""

    def update_outgoing(self):
        has_new_outgoing = False
        task = self._pop_from_outgoing()
        # print("Updated outgoing task in server ", str(task))
        if type(task) == bt_task_handler.BT_task and task.cmd_id != 0:
            print("update_outgoing: i if-sats")
            self.outgoing_data = str(task.cmd_id) + ", " + str(task.data)  # TODO will change when json
            has_new_outgoing = True
        return has_new_outgoing

    def shutdown_server(self):
        #self.server_sock.shutdown(2)
        self.server_sock.close()
<commit_msg>close client also in server<commit_after>import bluetooth
import bt_task_handler

class BT_Server:
    """Create the server socket with predefined port and backlog value
       Returns a BluetoothSocket"""

    def __init__(self, server_addr, port, backlog, client_addr=""):
        # Sever bluetooth mac-address
        self.server_addr = server_addr
        self.port = port
        # Number of unaccepted connections before refusing new ones
        self.backlog = backlog
        # (the only address from which the server will accept connections)
        self.client_addr = client_addr

        # Set up server socket
        self.server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
        self.server_sock.setblocking(True)
        self.server_sock.bind((server_addr, port))
        # Enable the server to accept connections
        self.server_sock.listen(backlog)

        # Data received from client
        self.incoming_data = None
        # Data to be sent to client
        self.outgoing_data = None

        self.client_sock = None
        self.accp_client_addr = None

    def accept_connection(self):
        # TODO: Accept connection from valid client (requires change of backlog)
        print("in accept_connection")
        (self.client_sock, self.accp_client_addr) = self.server_sock.accept()

    # if accp_client_addr == client_addr

    def post_to_incoming(self):
        print("Server: staring to post to incoming")
        bt_task_handler.post_incoming(bt_task_handler.BT_task(self.incoming_data, ""))
        print("Server done posting to incoming, returning to main")

    def send_data(self, data=None):
        print("Server: sending!")
        if not data:
            self.client_sock.send(self.outgoing_data)
        else:
            self.client_sock.send(data)
        print("Server: sent! Returning to main")

    def _pop_from_outgoing(self):
        return bt_task_handler.pop_outgoing()

    """Updates incoming_data. Returns true if data was updated,
       false otherwise"""

    def update_incoming(self):
        has_new_incoming = False
        try:
            self.client_sock.settimeout(0.1)
            data = self.client_sock.recv(1024).decode('utf-8')
            print("bt_server: Data =", data)
            if len(data) != 0:  # TODO or None? (using json)
                self.incoming_data = data
                has_new_incoming = True
        except bluetooth.btcommon.BluetoothError:
            pass
        finally:
            self.client_sock.settimeout(None)
        return has_new_incoming

    """Updates outgoing_data. Returns true if data was updated,
       false otherwise"""

    def update_outgoing(self):
        has_new_outgoing = False
        task = self._pop_from_outgoing()
        # print("Updated outgoing task in server ", str(task))
        if type(task) == bt_task_handler.BT_task and task.cmd_id != 0:
            print("update_outgoing: i if-sats")
            self.outgoing_data = str(task.cmd_id) + ", " + str(task.data)  # TODO will change when json
            has_new_outgoing = True
        return has_new_outgoing

    def shutdown_server(self):
        #self.server_sock.shutdown(2)
        self.server_sock.close()
        self.client_sock.close()
<|endoftext|>


<commit_before>"""
State machine for navigational states
"""
from datetime import datetime, timedelta

from autocontroller import AutoController
from eventbus import EventBus
from protocol import CMD_TURN_STARTED, CMD_TURN_FINISHED

TURN_DIRECTION_RIGHT = True
TURN_DIRECTION_LEFT = False
UPDATE_FREQUENCY = 100

class State:

    def run(self, data):
        assert 0, "run not implemented"

    def sensor_data_received(self, data, new_ir_left, new_ir_right):
        assert 0, "sensor_data_received not implemented"

class auto_control(State):

    auto_controller = AutoController()

    def is_at_left_turn(self, data):
        left_old_diff = abs(data['ir_left'] - data['old_ir_left'])
        left_new_diff = abs(data['new_ir_left'] - data['old_ir_left'])

        #print("At left turn, old diff: " + str(left_old_diff) + ", new diff: "+ str(left_new_diff))

        return left_old_diff >= Navigator.DISCONTINUITY_DIST and\
               left_new_diff >= Navigator.DISCONTINUITY_DIST and\
               data['side'] == Navigator.LEFT_SIDE

    def is_at_right_turn(self, data):
        right_old_diff = abs(data['ir_right'] - data['old_ir_right'])
        right_new_diff = abs(data['new_ir_right'] - data['old_ir_right'])
        #print("At right turn, old diff: " + str(right_old_diff) + ", new diff: " + str(right_new_diff))

        return right_old_diff >= Navigator.DISCONTINUITY_DIST and \
               right_new_diff >= Navigator.DISCONTINUITY_DIST and \
               data['side'] == Navigator.RIGHT_SIDE

    def sensor_data_received(self, data, new_ir_left, new_ir_right):

        if self.is_at_left_turn(data) or self.is_at_right_turn(data):
            return

        right_speed, left_speed, regulation = auto_control.auto_controller.auto_control(new_ir_left, new_ir_right, data['side'])

        if abs(regulation) >= 33:
            print("Regulation to high: " + str(regulation))
            return

        data['driver'].drive(left_speed, right_speed)

    def run(self, data):
        left_diff = data['ir_left'] - data['old_ir_left']
        right_diff = data['ir_right'] - data['old_ir_right']

        #print('ir right:' + str(data['ir_right']) + ' old ir right: ' + str(data['old_ir_right']) + ' right diff : ' + str(right_diff))
        #Outer turn, prioritize following right wall
        if self.is_at_right_turn(data):
            data['driver'].outer_turn_right()
            print('outer turn right')
            return turn(TURN_DIRECTION_RIGHT)

        if self.is_at_left_turn(data):
            data['driver'].outer_turn_left()
            print('outer turn left')
            return turn(TURN_DIRECTION_LEFT)

        laser_data = data['laser'].read_data()
        #print('Left diff: ' + str(left_diff) + ' right diff ' + str(right_diff))
        #print('laser distance: ' + str(laser_data))

        #Inner turn
        if laser_data <= Navigator.FACING_WALL_DIST and laser_data != -1:
            print("laserdata: "+ str(laser_data))
            if data['side'] == Navigator.LEFT_SIDE:
                data['driver'].inner_turn_right()
                print('inner turn right')
                return turn(TURN_DIRECTION_RIGHT)
            if data['side'] == Navigator.RIGHT_SIDE:
                data['driver'].inner_turn_left()
                print('inner turn left')
                return turn(TURN_DIRECTION_LEFT)

        return auto_control()

class warmup(State):
    def sensor_data_received(self, data, new_ir_left, new_ir_right):
        return #Do nothing

    def run(self, data):
        if data['driver'].idle():
            print('changin to auto control')
            return auto_control()
        else:
            return warmup()

class turn(State):
    def __init__(self, is_right_turn):
        self.is_right_turn = is_right_turn

    def sensor_data_received(self, data, new_ir_left, new_ir_right):
        return #Do nothing. Only auto control uses it

    def run(self, data):
        if data['driver'].idle():
            print('changing to auto control')
            return auto_control()
        else:
            return turn(self.is_right_turn)

###### NAVIGATOR CLASS #######
class Navigator:
    LEFT_SIDE = 0
    RIGHT_SIDE = 1

    DISCONTINUITY_DIST = 25.0  # mm
    FACING_WALL_DIST = 150  # mm

    def __init__(self, driver, laser):
        self.data = {
                     'ir_left': 0,
                     'ir_right': 0,
                     'old_ir_right': 0,
                     'old_ir_left': 0,
                     'driver': driver,
                     'laser': laser,
                     'side': Navigator.RIGHT_SIDE,
                     'new_ir_right': 0,
                     'new_ir_left': 0
                    }

        #Stand still waiting for sensors

        self.data['driver'].warmup()
        self.state = warmup()
        self.last_updated_time = datetime.now()

    def sensor_data_received(self, new_ir_left, new_ir_right):

        if datetime.now() - self.last_updated_time < timedelta(milliseconds=UPDATE_FREQUENCY):
            return

        self.data['old_ir_left'] = self.data['ir_left']
        self.data['old_ir_right'] = self.data['ir_right']
        self.data['ir_left'] = self.data['new_ir_left']
        self.data['ir_right'] = self.data['new_ir_right']
        self.data['new_ir_right'] = new_ir_right
        self.data['new_ir_left'] = new_ir_left
        self.state.sensor_data_received(self.data, new_ir_left, new_ir_right)
        self.last_updated_time = datetime.now()

    #Runs the state. The states run method returns the next state
    def navigate(self):
        next_state = self.state.run(self.data)

        curr_type = type(self.state)
        next_type = type(next_state)

        if curr_type is not turn and next_type is turn:
            EventBus.notify(CMD_TURN_STARTED)

        if curr_type is turn and next_type is not turn:
            EventBus.notify(CMD_TURN_FINISHED, self.state.is_right_turn)
            self.data['old_ir_left'] = self.data['new_ir_left']
            self.data['old_ir_right'] = self.data['new_ir_right']
            self.data['ir_left'] = self.data['new_ir_left']
            self.data['ir_right'] = self.data['new_ir_right']

        self.state = next_state
<commit_msg>Increased Facing wall constant<commit_after>"""
State machine for navigational states
"""
from datetime import datetime, timedelta

from autocontroller import AutoController
from eventbus import EventBus
from protocol import CMD_TURN_STARTED, CMD_TURN_FINISHED

TURN_DIRECTION_RIGHT = True
TURN_DIRECTION_LEFT = False
UPDATE_FREQUENCY = 100

class State:

    def run(self, data):
        assert 0, "run not implemented"

    def sensor_data_received(self, data, new_ir_left, new_ir_right):
        assert 0, "sensor_data_received not implemented"

class auto_control(State):

    auto_controller = AutoController()

    def is_at_left_turn(self, data):
        left_old_diff = abs(data['ir_left'] - data['old_ir_left'])
        left_new_diff = abs(data['new_ir_left'] - data['old_ir_left'])

        #print("At left turn, old diff: " + str(left_old_diff) + ", new diff: "+ str(left_new_diff))

        return left_old_diff >= Navigator.DISCONTINUITY_DIST and\
               left_new_diff >= Navigator.DISCONTINUITY_DIST and\
               data['side'] == Navigator.LEFT_SIDE

    def is_at_right_turn(self, data):
        right_old_diff = abs(data['ir_right'] - data['old_ir_right'])
        right_new_diff = abs(data['new_ir_right'] - data['old_ir_right'])
        #print("At right turn, old diff: " + str(right_old_diff) + ", new diff: " + str(right_new_diff))

        return right_old_diff >= Navigator.DISCONTINUITY_DIST and \
               right_new_diff >= Navigator.DISCONTINUITY_DIST and \
               data['side'] == Navigator.RIGHT_SIDE

    def sensor_data_received(self, data, new_ir_left, new_ir_right):

        if self.is_at_left_turn(data) or self.is_at_right_turn(data):
            return

        right_speed, left_speed, regulation = auto_control.auto_controller.auto_control(new_ir_left, new_ir_right, data['side'])

        if abs(regulation) >= 33:
            print("Regulation to high: " + str(regulation))
            return

        data['driver'].drive(left_speed, right_speed)

    def run(self, data):
        left_diff = data['ir_left'] - data['old_ir_left']
        right_diff = data['ir_right'] - data['old_ir_right']

        #print('ir right:' + str(data['ir_right']) + ' old ir right: ' + str(data['old_ir_right']) + ' right diff : ' + str(right_diff))
        #Outer turn, prioritize following right wall
        if self.is_at_right_turn(data):
            data['driver'].outer_turn_right()
            print('outer turn right')
            return turn(TURN_DIRECTION_RIGHT)

        if self.is_at_left_turn(data):
            data['driver'].outer_turn_left()
            print('outer turn left')
            return turn(TURN_DIRECTION_LEFT)

        laser_data = data['laser'].read_data()
        #print('Left diff: ' + str(left_diff) + ' right diff ' + str(right_diff))
        #print('laser distance: ' + str(laser_data))

        #Inner turn
        if laser_data <= Navigator.FACING_WALL_DIST and laser_data != -1:
            print("laserdata: "+ str(laser_data))
            if data['side'] == Navigator.LEFT_SIDE:
                data['driver'].inner_turn_right()
                print('inner turn right')
                return turn(TURN_DIRECTION_RIGHT)
            if data['side'] == Navigator.RIGHT_SIDE:
                data['driver'].inner_turn_left()
                print('inner turn left')
                return turn(TURN_DIRECTION_LEFT)

        return auto_control()

class warmup(State):
    def sensor_data_received(self, data, new_ir_left, new_ir_right):
        return #Do nothing

    def run(self, data):
        if data['driver'].idle():
            print('changin to auto control')
            return auto_control()
        else:
            return warmup()

class turn(State):
    def __init__(self, is_right_turn):
        self.is_right_turn = is_right_turn

    def sensor_data_received(self, data, new_ir_left, new_ir_right):
        return #Do nothing. Only auto control uses it

    def run(self, data):
        if data['driver'].idle():
            print('changing to auto control')
            return auto_control()
        else:
            return turn(self.is_right_turn)

###### NAVIGATOR CLASS #######
class Navigator:
    LEFT_SIDE = 0
    RIGHT_SIDE = 1

    DISCONTINUITY_DIST = 25.0  # mm
    FACING_WALL_DIST = 180  # mm

    def __init__(self, driver, laser):
        self.data = {
                     'ir_left': 0,
                     'ir_right': 0,
                     'old_ir_right': 0,
                     'old_ir_left': 0,
                     'driver': driver,
                     'laser': laser,
                     'side': Navigator.RIGHT_SIDE,
                     'new_ir_right': 0,
                     'new_ir_left': 0
                    }

        #Stand still waiting for sensors

        self.data['driver'].warmup()
        self.state = warmup()
        self.last_updated_time = datetime.now()

    def sensor_data_received(self, new_ir_left, new_ir_right):

        if datetime.now() - self.last_updated_time < timedelta(milliseconds=UPDATE_FREQUENCY):
            return

        self.data['old_ir_left'] = self.data['ir_left']
        self.data['old_ir_right'] = self.data['ir_right']
        self.data['ir_left'] = self.data['new_ir_left']
        self.data['ir_right'] = self.data['new_ir_right']
        self.data['new_ir_right'] = new_ir_right
        self.data['new_ir_left'] = new_ir_left
        self.state.sensor_data_received(self.data, new_ir_left, new_ir_right)
        self.last_updated_time = datetime.now()

    #Runs the state. The states run method returns the next state
    def navigate(self):
        next_state = self.state.run(self.data)

        curr_type = type(self.state)
        next_type = type(next_state)

        if curr_type is not turn and next_type is turn:
            EventBus.notify(CMD_TURN_STARTED)

        if curr_type is turn and next_type is not turn:
            EventBus.notify(CMD_TURN_FINISHED, self.state.is_right_turn)
            self.data['old_ir_left'] = self.data['new_ir_left']
            self.data['old_ir_right'] = self.data['new_ir_right']
            self.data['ir_left'] = self.data['new_ir_left']
            self.data['ir_right'] = self.data['new_ir_right']

        self.state = next_state
<|endoftext|>


<commit_before># ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0
#
# The contents of this file are subject to the Mozilla Public License
# Version 1.1 (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.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
# the License for the specific language governing rights and
# limitations under the License.
#
# The Original Code is Pika.
#
# The Initial Developers of the Original Code are LShift Ltd, Cohesive
# Financial Technologies LLC, and Rabbit Technologies Ltd.  Portions
# created before 22-Nov-2008 00:00:00 GMT by LShift Ltd, Cohesive
# Financial Technologies LLC, or Rabbit Technologies Ltd are Copyright
# (C) 2007-2008 LShift Ltd, Cohesive Financial Technologies LLC, and
# Rabbit Technologies Ltd.
#
# Portions created by LShift Ltd are Copyright (C) 2007-2009 LShift
# Ltd. Portions created by Cohesive Financial Technologies LLC are
# Copyright (C) 2007-2009 Cohesive Financial Technologies
# LLC. Portions created by Rabbit Technologies Ltd are Copyright (C)
# 2007-2009 Rabbit Technologies Ltd.
#
# Portions created by Tony Garnock-Jones are Copyright (C) 2009-2010
# LShift Ltd and Tony Garnock-Jones.
#
# All Rights Reserved.
#
# Contributor(s): ______________________________________.
#
# Alternatively, the contents of this file may be used under the terms
# of the GNU General Public License Version 2 or later (the "GPL"), in
# which case the provisions of the GPL are applicable instead of those
# above. If you wish to allow use of your version of this file only
# under the terms of the GPL, and not to allow others to use your
# version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the
# notice and other provisions required by the GPL. If you do not
# delete the provisions above, a recipient may use your version of
# this file under the terms of any one of the MPL or the GPL.
#
# ***** END LICENSE BLOCK *****

import pika.spec as spec
import pika.codec as codec
import pika.event as event
from pika.exceptions import *

class ChannelHandler:
    def __init__(self, connection, channel_number = None):
        self.connection = connection
        self.frame_handler = self._handle_method
        self.channel_close = None
        self.async_map = {}
        self.reply_map = None
        self.flow_active = True ## we are permitted to transmit, so True.

        self.channel_state_change_event = event.Event()
        self.flow_active_change_event = event.Event()

        if channel_number is None:
            self.channel_number = connection._next_channel_number()
        else:
            self.channel_number = channel_number
        connection._set_channel(self.channel_number, self)

    def _async_channel_close(self, method_frame, header_frame, body):
        self._set_channel_close(method_frame.method)
        self.connection.send_method(self.channel_number, spec.Channel.CloseOk())

    def _async_channel_flow(self, method_frame, header_frame, body):
        self.flow_active = method_frame.method.active
        self.flow_active_change_event.fire(self, self.flow_active)
        self.connection.send_method(self.channel_number,
                                    spec.Channel.FlowOk(active = self.flow_active))

    def _ensure(self):
        if self.channel_close:
            raise ChannelClosed(self.channel_close)
        return self

    def _set_channel_close(self, c):
        if not self.channel_close:
            self.channel_close = c
            self.connection.reset_channel(self.channel_number)
            self.channel_state_change_event.fire(self, False)

    def addStateChangeHandler(self, handler, key = None):
        self.channel_state_change_event.addHandler(handler, key)
        handler(self, not self.channel_close)

    def addFlowChangeHandler(self, handler, key = None):
        self.flow_active_change_event.addHandler(handler, key)
        handler(self, self.flow_active)

    def wait_for_reply(self, acceptable_replies):
        if not acceptable_replies:
            # One-way.
            return

        if self.reply_map is not None:
            raise RecursiveOperationDetected([p.NAME for p in acceptable_replies])

        reply = [None]
        def set_reply(r):
            reply[0] = r

        self.reply_map = {}
        for possibility in acceptable_replies:
            self.reply_map[possibility] = set_reply

        while True:
            self._ensure()
            self.connection.drain_events()
            if reply[0]: return reply[0]

    def _handle_async(self, method_frame, header_frame, body):
        method = method_frame.method
        methodClass = method.__class__

        if methodClass in self.reply_map:
            if header_frame is not None:
                method._set_content(header_frame.properties, body)
            handler = self.reply_map[methodClass]
            self.reply_map = None
            handler(method)
        elif methodClass in self.async_map:
            self.async_map[methodClass](method_frame, header_frame, body)
        else:
            self.connection.close(spec.NOT_IMPLEMENTED,
                                  'Pika: method not implemented: ' + methodClass.NAME)

    def _handle_method(self, frame):
        if not isinstance(frame, codec.FrameMethod):
            raise UnexpectedFrameError(frame)
        if spec.has_content(frame.method.INDEX):
            self.frame_handler = self._make_header_handler(frame)
        else:
            self._handle_async(frame, None, None)

    def _make_header_handler(self, method_frame):
        def handler(header_frame):
            if not isinstance(header_frame, codec.FrameHeader):
                raise UnexpectedFrameError(header_frame)
            self._install_body_handler(method_frame, header_frame)
        return handler

    def _install_body_handler(self, method_frame, header_frame):
        seen_so_far = [0]
        body_fragments = []

        def handler(body_frame):
            if not isinstance(body_frame, codec.FrameBody):
                raise UnexpectedFrameError(body_frame)
            fragment = body_frame.fragment
            seen_so_far[0] = seen_so_far[0] + len(fragment)
            body_fragments.append(fragment)
            if seen_so_far[0] == header_frame.body_size:
                finish()
            elif seen_so_far[0] > header_frame.body_size:
                raise BodyTooLongError()
            else:
                pass
        def finish():
            self.frame_handler = self._handle_method
            self._handle_async(method_frame, header_frame, ''.join(body_fragments))

        if header_frame.body_size == 0:
            finish()
        else:
            self.frame_handler = handler

    def _rpc(self, method, acceptable_replies):
        self._ensure()
        return self.connection._rpc(self.channel_number, method, acceptable_replies)

    def content_transmission_forbidden(self):
        return not self.flow_active

class Channel(spec.DriverMixin):
    def __init__(self, handler):
        self.handler = handler
        self.callbacks = {}
        self.next_consumer_tag = 0

        handler.async_map[spec.Channel.Close] = handler._async_channel_close
        handler.async_map[spec.Channel.Flow] = handler._async_channel_flow

        handler.async_map[spec.Basic.Deliver] = self._async_basic_deliver
        handler.async_map[spec.Basic.Return] = self._async_basic_return

        self.handler._rpc(spec.Channel.Open(), [spec.Channel.OpenOk])

    def addStateChangeHandler(self, handler, key = None):
        self.handler.addStateChangeHandler(handler, key)

    def addFlowChangeHandler(self, handler, key = None):
        self.handler.addFlowChangeHandler(handler, key)

    def _async_basic_deliver(self, method_frame, header_frame, body):
        self.callbacks[method_frame.method.consumer_tag](self,
                                                         method_frame.method,
                                                         header_frame.properties,
                                                         body)

    def _async_basic_return(self, method_frame, header_frame, body):
        raise NotImplementedError("Basic.Return")

    def close(self, code = 0, text = 'Normal close'):
        c = spec.Channel.Close(reply_code = code,
                               reply_text = text,
                               class_id = 0,
                               method_id = 0)
        self.handler._rpc(c, [spec.Channel.CloseOk])
        self.handler._set_channel_close(c)

    def basic_publish(self, exchange, routing_key, body, properties = None, mandatory = False, immediate = False, block_on_flow_control = False):
        if self.handler.content_transmission_forbidden():
            if block_on_flow_control:
                while self.handler.content_transmission_forbidden():
                    self.handler.connection.drain_events()
            else:
                raise ContentTransmissionForbidden(self)
        properties = properties or spec.BasicProperties()
        self.handler.connection.send_method(self.handler.channel_number,
                                            spec.Basic.Publish(exchange = exchange,
                                                               routing_key = routing_key,
                                                               mandatory = mandatory,
                                                               immediate = immediate),
                                            (properties, body))

    def basic_consume(self, consumer, queue = '', no_ack = False, exclusive = False, consumer_tag = None):
        tag = consumer_tag
        if not tag:
            tag = 'ctag' + str(self.next_consumer_tag)
            self.next_consumer_tag += 1

        if tag in self.callbacks:
            raise DuplicateConsumerTag(tag)

        self.callbacks[tag] = consumer
        return self.handler._rpc(spec.Basic.Consume(queue = queue,
                                                    consumer_tag = tag,
                                                    no_ack = no_ack,
                                                    exclusive = exclusive),
                                 [spec.Basic.ConsumeOk]).consumer_tag

    def basic_cancel(self, consumer_tag):
        if not consumer_tag in self.callbacks:
            raise UnknownConsumerTag(consumer_tag)

        self.handler._rpc(spec.Basic.Cancel(consumer_tag = consumer_tag),
                          [spec.Basic.CancelOk])
        del self.callbacks[consumer_tag]
<commit_msg>Oops. Cope with async arrivals not during an RPC<commit_after># ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0
#
# The contents of this file are subject to the Mozilla Public License
# Version 1.1 (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.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
# the License for the specific language governing rights and
# limitations under the License.
#
# The Original Code is Pika.
#
# The Initial Developers of the Original Code are LShift Ltd, Cohesive
# Financial Technologies LLC, and Rabbit Technologies Ltd.  Portions
# created before 22-Nov-2008 00:00:00 GMT by LShift Ltd, Cohesive
# Financial Technologies LLC, or Rabbit Technologies Ltd are Copyright
# (C) 2007-2008 LShift Ltd, Cohesive Financial Technologies LLC, and
# Rabbit Technologies Ltd.
#
# Portions created by LShift Ltd are Copyright (C) 2007-2009 LShift
# Ltd. Portions created by Cohesive Financial Technologies LLC are
# Copyright (C) 2007-2009 Cohesive Financial Technologies
# LLC. Portions created by Rabbit Technologies Ltd are Copyright (C)
# 2007-2009 Rabbit Technologies Ltd.
#
# Portions created by Tony Garnock-Jones are Copyright (C) 2009-2010
# LShift Ltd and Tony Garnock-Jones.
#
# All Rights Reserved.
#
# Contributor(s): ______________________________________.
#
# Alternatively, the contents of this file may be used under the terms
# of the GNU General Public License Version 2 or later (the "GPL"), in
# which case the provisions of the GPL are applicable instead of those
# above. If you wish to allow use of your version of this file only
# under the terms of the GPL, and not to allow others to use your
# version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the
# notice and other provisions required by the GPL. If you do not
# delete the provisions above, a recipient may use your version of
# this file under the terms of any one of the MPL or the GPL.
#
# ***** END LICENSE BLOCK *****

import pika.spec as spec
import pika.codec as codec
import pika.event as event
from pika.exceptions import *

class ChannelHandler:
    def __init__(self, connection, channel_number = None):
        self.connection = connection
        self.frame_handler = self._handle_method
        self.channel_close = None
        self.async_map = {}
        self.reply_map = None
        self.flow_active = True ## we are permitted to transmit, so True.

        self.channel_state_change_event = event.Event()
        self.flow_active_change_event = event.Event()

        if channel_number is None:
            self.channel_number = connection._next_channel_number()
        else:
            self.channel_number = channel_number
        connection._set_channel(self.channel_number, self)

    def _async_channel_close(self, method_frame, header_frame, body):
        self._set_channel_close(method_frame.method)
        self.connection.send_method(self.channel_number, spec.Channel.CloseOk())

    def _async_channel_flow(self, method_frame, header_frame, body):
        self.flow_active = method_frame.method.active
        self.flow_active_change_event.fire(self, self.flow_active)
        self.connection.send_method(self.channel_number,
                                    spec.Channel.FlowOk(active = self.flow_active))

    def _ensure(self):
        if self.channel_close:
            raise ChannelClosed(self.channel_close)
        return self

    def _set_channel_close(self, c):
        if not self.channel_close:
            self.channel_close = c
            self.connection.reset_channel(self.channel_number)
            self.channel_state_change_event.fire(self, False)

    def addStateChangeHandler(self, handler, key = None):
        self.channel_state_change_event.addHandler(handler, key)
        handler(self, not self.channel_close)

    def addFlowChangeHandler(self, handler, key = None):
        self.flow_active_change_event.addHandler(handler, key)
        handler(self, self.flow_active)

    def wait_for_reply(self, acceptable_replies):
        if not acceptable_replies:
            # One-way.
            return

        if self.reply_map is not None:
            raise RecursiveOperationDetected([p.NAME for p in acceptable_replies])

        reply = [None]
        def set_reply(r):
            reply[0] = r

        self.reply_map = {}
        for possibility in acceptable_replies:
            self.reply_map[possibility] = set_reply

        while True:
            self._ensure()
            self.connection.drain_events()
            if reply[0]: return reply[0]

    def _handle_async(self, method_frame, header_frame, body):
        method = method_frame.method
        methodClass = method.__class__

        if self.reply_map is not None and methodClass in self.reply_map:
            if header_frame is not None:
                method._set_content(header_frame.properties, body)
            handler = self.reply_map[methodClass]
            self.reply_map = None
            handler(method)
        elif methodClass in self.async_map:
            self.async_map[methodClass](method_frame, header_frame, body)
        else:
            self.connection.close(spec.NOT_IMPLEMENTED,
                                  'Pika: method not implemented: ' + methodClass.NAME)

    def _handle_method(self, frame):
        if not isinstance(frame, codec.FrameMethod):
            raise UnexpectedFrameError(frame)
        if spec.has_content(frame.method.INDEX):
            self.frame_handler = self._make_header_handler(frame)
        else:
            self._handle_async(frame, None, None)

    def _make_header_handler(self, method_frame):
        def handler(header_frame):
            if not isinstance(header_frame, codec.FrameHeader):
                raise UnexpectedFrameError(header_frame)
            self._install_body_handler(method_frame, header_frame)
        return handler

    def _install_body_handler(self, method_frame, header_frame):
        seen_so_far = [0]
        body_fragments = []

        def handler(body_frame):
            if not isinstance(body_frame, codec.FrameBody):
                raise UnexpectedFrameError(body_frame)
            fragment = body_frame.fragment
            seen_so_far[0] = seen_so_far[0] + len(fragment)
            body_fragments.append(fragment)
            if seen_so_far[0] == header_frame.body_size:
                finish()
            elif seen_so_far[0] > header_frame.body_size:
                raise BodyTooLongError()
            else:
                pass
        def finish():
            self.frame_handler = self._handle_method
            self._handle_async(method_frame, header_frame, ''.join(body_fragments))

        if header_frame.body_size == 0:
            finish()
        else:
            self.frame_handler = handler

    def _rpc(self, method, acceptable_replies):
        self._ensure()
        return self.connection._rpc(self.channel_number, method, acceptable_replies)

    def content_transmission_forbidden(self):
        return not self.flow_active

class Channel(spec.DriverMixin):
    def __init__(self, handler):
        self.handler = handler
        self.callbacks = {}
        self.next_consumer_tag = 0

        handler.async_map[spec.Channel.Close] = handler._async_channel_close
        handler.async_map[spec.Channel.Flow] = handler._async_channel_flow

        handler.async_map[spec.Basic.Deliver] = self._async_basic_deliver
        handler.async_map[spec.Basic.Return] = self._async_basic_return

        self.handler._rpc(spec.Channel.Open(), [spec.Channel.OpenOk])

    def addStateChangeHandler(self, handler, key = None):
        self.handler.addStateChangeHandler(handler, key)

    def addFlowChangeHandler(self, handler, key = None):
        self.handler.addFlowChangeHandler(handler, key)

    def _async_basic_deliver(self, method_frame, header_frame, body):
        self.callbacks[method_frame.method.consumer_tag](self,
                                                         method_frame.method,
                                                         header_frame.properties,
                                                         body)

    def _async_basic_return(self, method_frame, header_frame, body):
        raise NotImplementedError("Basic.Return")

    def close(self, code = 0, text = 'Normal close'):
        c = spec.Channel.Close(reply_code = code,
                               reply_text = text,
                               class_id = 0,
                               method_id = 0)
        self.handler._rpc(c, [spec.Channel.CloseOk])
        self.handler._set_channel_close(c)

    def basic_publish(self, exchange, routing_key, body, properties = None, mandatory = False, immediate = False, block_on_flow_control = False):
        if self.handler.content_transmission_forbidden():
            if block_on_flow_control:
                while self.handler.content_transmission_forbidden():
                    self.handler.connection.drain_events()
            else:
                raise ContentTransmissionForbidden(self)
        properties = properties or spec.BasicProperties()
        self.handler.connection.send_method(self.handler.channel_number,
                                            spec.Basic.Publish(exchange = exchange,
                                                               routing_key = routing_key,
                                                               mandatory = mandatory,
                                                               immediate = immediate),
                                            (properties, body))

    def basic_consume(self, consumer, queue = '', no_ack = False, exclusive = False, consumer_tag = None):
        tag = consumer_tag
        if not tag:
            tag = 'ctag' + str(self.next_consumer_tag)
            self.next_consumer_tag += 1

        if tag in self.callbacks:
            raise DuplicateConsumerTag(tag)

        self.callbacks[tag] = consumer
        return self.handler._rpc(spec.Basic.Consume(queue = queue,
                                                    consumer_tag = tag,
                                                    no_ack = no_ack,
                                                    exclusive = exclusive),
                                 [spec.Basic.ConsumeOk]).consumer_tag

    def basic_cancel(self, consumer_tag):
        if not consumer_tag in self.callbacks:
            raise UnknownConsumerTag(consumer_tag)

        self.handler._rpc(spec.Basic.Cancel(consumer_tag = consumer_tag),
                          [spec.Basic.CancelOk])
        del self.callbacks[consumer_tag]
<|endoftext|>


<commit_before>"""piroute URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
from django.views.generic import TemplateView

urlpatterns = [
    url('^$', TemplateView.as_view(template_name='index.html'), name='index'),
    url(r'^iptables/', include('iptables.urls', namespace='iptables')),
    url(r'^status/', include('status.urls', namespace='status')),
]
<commit_msg>Dropping trailing slash on URLs<commit_after>"""piroute URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
from django.views.generic import TemplateView

urlpatterns = [
    url('^$', TemplateView.as_view(template_name='index.html'), name='index'),
    url(r'^iptables', include('iptables.urls', namespace='iptables')),
    url(r'^status', include('status.urls', namespace='status')),
]
<|endoftext|>


<commit_before>#=========================================================================
# IsaImpl
#=========================================================================
# This is an implementation class for simplifying the construction of
# instruction classes used in PyMTL modeling. Eventually, we might be
# able to refactor even more boilerplate into this class.
#
# This class is meant to be instantiated and used from within a concrete
# instruction class. In addition to the instruction class, we also need
# to define an encoding table and functions for assembling and
# disassembling instruction fields. See PisaInst for an example of how to
# use this class.
#
# Author : Christopher Batten
# Date   : May 16, 2014

from new_pymtl import Bits
from string import translate,maketrans

class IsaImpl (object):

  #-----------------------------------------------------------------------
  # Constructor
  #-----------------------------------------------------------------------

  def __init__( self, nbits, inst_encoding_table, inst_fields ):

    self.nbits                   = 32
    self.inst_encoding_table     = inst_encoding_table
    self.asm_field_funcs_dict    = {}
    self.disasm_field_funcs_dict = {}
    self.opcode_match_dict       = {}

    for row in inst_encoding_table:

      # Extract the columns from the row

      inst_tmpl    = row[0]
      opcode_mask  = row[1]
      opcode_match = row[2]

      # Extract instruction name from string template

      (inst_name,sep,inst_tmpl) = inst_tmpl.partition(' ')

      # Add opcode match to the a dictionary using the instruction
      # name as the key

      self.opcode_match_dict[ inst_name ] = opcode_match

      # Split the remainder of the template into field strings. First we
      # translate non-whitespace deliminters into whitespace so that we
      # can use split.

      translation_table = maketrans(",()","   ")
      inst_field_tags = translate(inst_tmpl,translation_table).split()

      # Create the list of asm field functions

      asm_field_funcs = []
      for asm_field_tag in inst_field_tags:
        asm_field_funcs.append( inst_fields[asm_field_tag][0] )

      # Add the list of asm field functions to the encoding

      self.asm_field_funcs_dict[ inst_name ] = asm_field_funcs

      # Create the list of disasm field functions

      disasm_field_funcs = {}
      for asm_field_tag in inst_field_tags:
        disasm_field_funcs[ asm_field_tag ] = inst_fields[asm_field_tag][1]

      # Add the list of disasm field functions to the encoding

      self.disasm_field_funcs_dict[ inst_name ] = disasm_field_funcs

  #-----------------------------------------------------------------------
  # decode_tmpl
  #-----------------------------------------------------------------------
  # For now this is O(n) where n is the number of instructions in the
  # encoding table. Obviously, this is pretty slow. I am sure we can do
  # better by creating some kind of tree-based data structure.

  def decode_tmpl( self, inst_bits ):

    for row in self.inst_encoding_table:

      # Extract the columns from the row

      inst_tmpl    = row[0]
      opcode_mask  = row[1]
      opcode_match = row[2]

      # If match, then return instruction name

      if (inst_bits & opcode_mask) == opcode_match:
        return inst_tmpl

    # Illegal instruction

    raise AssertionError( "Illegal instruction {}!".format( inst_bits ) )

  #-----------------------------------------------------------------------
  # decode_name
  #-----------------------------------------------------------------------

  def decode_inst_name( self, inst_bits ):

    # Decode template

    inst_tmpl = self.decode_tmpl( inst_bits )

    # Extract instruction name

    return inst_tmpl.partition(' ')[0]

  #-----------------------------------------------------------------------
  # assemble_inst
  #-----------------------------------------------------------------------

  def assemble_inst( self, sym, pc, inst_str ):

    # Extract instruction name from asm string

    (inst_name,sep,inst_str) = inst_str.partition(' ')

    # Use the instruction name to get the opcode match which we can
    # the use to initialize the instruction bits

    inst_bits = Bits( self.nbits, self.opcode_match_dict[ inst_name ] )

    # Split the remainder of the asm string into field strings. First
    # we translate non-whitespace deliminters into whitespace so that
    # we can use split.

    translation_table = maketrans(",()","   ")
    asm_field_strs = translate(inst_str,translation_table).split()

    # Retrieve the list of asm field functions for this instruction

    asm_field_funcs = self.asm_field_funcs_dict[ inst_name ]

    # Apply these asm field functions to the asm field strings

    for asm_field_str, asm_field_func in zip( asm_field_strs, asm_field_funcs ):
      asm_field_func( inst_bits, sym, pc, asm_field_str )

    # Return the assembled instruction

    return inst_bits

  #-----------------------------------------------------------------------
  # disassemble_inst
  #-----------------------------------------------------------------------

  def disassemble_inst( self, inst_bits ):

    # Decode the instruction to find instruction template

    inst_tmpl = self.decode_tmpl( inst_bits )

    # Extract instruction name from asm template

    inst_name = inst_tmpl.partition(' ')[0]

    # Retrieve the list of disasm field functions for this instruction

    disasm_field_funcs = self.disasm_field_funcs_dict[ inst_name ]

    # Apply these asm field functions to create the disasm string

    inst_str = inst_tmpl
    for inst_field_tag,disasm_field_func in disasm_field_funcs.iteritems():
      field_str = disasm_field_func( inst_bits )
      inst_str = inst_str.replace( inst_field_tag, field_str )

    # Return the disassembled instruction

    return inst_str

<commit_msg>[pisa] get nbits from parameter<commit_after>#=========================================================================
# IsaImpl
#=========================================================================
# This is an implementation class for simplifying the construction of
# instruction classes used in PyMTL modeling. Eventually, we might be
# able to refactor even more boilerplate into this class.
#
# This class is meant to be instantiated and used from within a concrete
# instruction class. In addition to the instruction class, we also need
# to define an encoding table and functions for assembling and
# disassembling instruction fields. See PisaInst for an example of how to
# use this class.
#
# Author : Christopher Batten
# Date   : May 16, 2014

from new_pymtl import Bits
from string import translate,maketrans

class IsaImpl (object):

  #-----------------------------------------------------------------------
  # Constructor
  #-----------------------------------------------------------------------

  def __init__( self, nbits, inst_encoding_table, inst_fields ):

    self.nbits                   = nbits
    self.inst_encoding_table     = inst_encoding_table
    self.asm_field_funcs_dict    = {}
    self.disasm_field_funcs_dict = {}
    self.opcode_match_dict       = {}

    for row in inst_encoding_table:

      # Extract the columns from the row

      inst_tmpl    = row[0]
      opcode_mask  = row[1]
      opcode_match = row[2]

      # Extract instruction name from string template

      (inst_name,sep,inst_tmpl) = inst_tmpl.partition(' ')

      # Add opcode match to the a dictionary using the instruction
      # name as the key

      self.opcode_match_dict[ inst_name ] = opcode_match

      # Split the remainder of the template into field strings. First we
      # translate non-whitespace deliminters into whitespace so that we
      # can use split.

      translation_table = maketrans(",()","   ")
      inst_field_tags = translate(inst_tmpl,translation_table).split()

      # Create the list of asm field functions

      asm_field_funcs = []
      for asm_field_tag in inst_field_tags:
        asm_field_funcs.append( inst_fields[asm_field_tag][0] )

      # Add the list of asm field functions to the encoding

      self.asm_field_funcs_dict[ inst_name ] = asm_field_funcs

      # Create the list of disasm field functions

      disasm_field_funcs = {}
      for asm_field_tag in inst_field_tags:
        disasm_field_funcs[ asm_field_tag ] = inst_fields[asm_field_tag][1]

      # Add the list of disasm field functions to the encoding

      self.disasm_field_funcs_dict[ inst_name ] = disasm_field_funcs

  #-----------------------------------------------------------------------
  # decode_tmpl
  #-----------------------------------------------------------------------
  # For now this is O(n) where n is the number of instructions in the
  # encoding table. Obviously, this is pretty slow. I am sure we can do
  # better by creating some kind of tree-based data structure.

  def decode_tmpl( self, inst_bits ):

    for row in self.inst_encoding_table:

      # Extract the columns from the row

      inst_tmpl    = row[0]
      opcode_mask  = row[1]
      opcode_match = row[2]

      # If match, then return instruction name

      if (inst_bits & opcode_mask) == opcode_match:
        return inst_tmpl

    # Illegal instruction

    raise AssertionError( "Illegal instruction {}!".format( inst_bits ) )

  #-----------------------------------------------------------------------
  # decode_name
  #-----------------------------------------------------------------------

  def decode_inst_name( self, inst_bits ):

    # Decode template

    inst_tmpl = self.decode_tmpl( inst_bits )

    # Extract instruction name

    return inst_tmpl.partition(' ')[0]

  #-----------------------------------------------------------------------
  # assemble_inst
  #-----------------------------------------------------------------------

  def assemble_inst( self, sym, pc, inst_str ):

    # Extract instruction name from asm string

    (inst_name,sep,inst_str) = inst_str.partition(' ')

    # Use the instruction name to get the opcode match which we can
    # the use to initialize the instruction bits

    inst_bits = Bits( self.nbits, self.opcode_match_dict[ inst_name ] )

    # Split the remainder of the asm string into field strings. First
    # we translate non-whitespace deliminters into whitespace so that
    # we can use split.

    translation_table = maketrans(",()","   ")
    asm_field_strs = translate(inst_str,translation_table).split()

    # Retrieve the list of asm field functions for this instruction

    asm_field_funcs = self.asm_field_funcs_dict[ inst_name ]

    # Apply these asm field functions to the asm field strings

    for asm_field_str, asm_field_func in zip( asm_field_strs, asm_field_funcs ):
      asm_field_func( inst_bits, sym, pc, asm_field_str )

    # Return the assembled instruction

    return inst_bits

  #-----------------------------------------------------------------------
  # disassemble_inst
  #-----------------------------------------------------------------------

  def disassemble_inst( self, inst_bits ):

    # Decode the instruction to find instruction template

    inst_tmpl = self.decode_tmpl( inst_bits )

    # Extract instruction name from asm template

    inst_name = inst_tmpl.partition(' ')[0]

    # Retrieve the list of disasm field functions for this instruction

    disasm_field_funcs = self.disasm_field_funcs_dict[ inst_name ]

    # Apply these asm field functions to create the disasm string

    inst_str = inst_tmpl
    for inst_field_tag,disasm_field_func in disasm_field_funcs.iteritems():
      field_str = disasm_field_func( inst_bits )
      inst_str = inst_str.replace( inst_field_tag, field_str )

    # Return the disassembled instruction

    return inst_str

<|endoftext|>


<commit_before>"""
Implementation of the Carneades model of argumentation.

Construct some proposition literals.

>>> a = PropLiteral('a')
>>> b = PropLiteral('b', False)

>>> print(a)
a
>>> print(b)
-b

Get the negation of `c`.

>>> c = a.negate()
>>> print(c)
-a
>>> a.negate()
a
>>> d = b.negate()
>>> print(d)
b

>>> e = PropLiteral('e')
>>> g = PropLiteral('e')
>>> print(e == g)
True

>>> f = e.negate().negate()
>>> print(f)
e
>>> print(e == f)
True

Construct some arguments.

>>> arg1 = Argument(a, premises={b}, weight=0.3)
>>> arg2 = Argument(b, premises={e}, weight=0.6)
>>> arg3 = Argument(b, premises={g})

>>> h = PropLiteral('h')
>>> i = PropLiteral('i', False)
>>> arg4 = Argument(a, premises={h, i}, exceptions={b})

>>> args = [arg1, arg2, arg3, arg4]
>>> for arg in args:
...     print(arg)
[b], ~[] => a, 0.3
[e], ~[] => b, 0.6
[e], ~[] => b, 1.0
[-i, h], ~[b] => a, 1.0

Argument set

>>> argset = ArgumentSet()
>>> argset.add_proposition(a)
Added proposition 'a' to graph
>>> argset.propset()
{a}
>>> argset.add_proposition(b)
Added proposition 'b' to graph
>>> argset.propset() == {a, b}
True
>>> argset.add_proposition(a)
Proposition 'a' is already in graph

>>> kill = PropLiteral('kill')
>>> intent = PropLiteral('intent')
>>> neg_intent = intent.negate()
>>> murder = PropLiteral('murder')
>>> witness1 = PropLiteral('witness1')
>>> unreliable1 = PropLiteral('unreliable1')
>>> witness2 = PropLiteral('witness2')
>>> unreliable2 = PropLiteral('unreliable2')

Proof standard

>>> ps = ProofStandard()
>>> d = {intent: "beyond_reasonable_doubt"}
>>> ps.set_standard(intent="beyond_reasonable_doubt")

CAES

>>> argset = ArgumentSet()
>>> weights = {}
>>> assumptions = {kill, witness1, witness2, unreliable2}
>>> caes = CAES(argset, assumptions, weights, ps)
>>> arg1 = Argument(murder, premises={kill, intent}, weight=0.8)
>>> arg2 = Argument(intent, premises={witness1}, exceptions={unreliable1}, weight=0.3)
>>> arg3 = Argument(neg_intent, premises={witness2}, exceptions={unreliable2}, weight=0.8)

>>> argset.add_argument(arg1)
Added proposition 'murder' to graph
Added proposition '-intent' to graph
Added proposition 'kill' to graph
>>> argset.draw()

"""

from igraph import *
from collections import defaultdict

class PropLiteral(object):
    """
    Proposition literals have most of the properties of ordinary strings,
    except that the negation method is Boolean; ie. a.negate().negate() == a.
    """
    def __init__(self, string, polarity=True):
        """
        Propositions are either positive or negative atoms.
        """
        self.polarity = polarity
        self._string = string

    def negate(self):
        """
        Negation of a proposition.
        """
        self.polarity = (not self.polarity)
        return self

    def __str__(self):
        """
        Override __str__ so that negation is realised as a prefix on the
        string.
        """
        if self.polarity:
            return self._string
        return "-" + self._string

    def __hash__(self):
        return self._string.__hash__()

    def __repr__(self):
        return self.__str__()

    def __eq__(self, other):
        if isinstance(other, self.__class__):
            return self.__str__() == other.__str__()
        else:
            return False

    def __ne__(self, other):
        return not self.__eq__(other)

    def __lt__(self, other):
        return self.__str__() < other.__str__()

class Argument(object):
    def __init__(self, conclusion, premises=set(), exceptions=set(), weight=1.0):
        """
        Propositions are either positive or negative atoms.

        :param conclusion: PropLiteral
        :param premises: set(PropLiteral)
        :param exceptions: set(PropLiteral)
        """

        self.conclusion = conclusion
        self.premises = premises
        self.exceptions = exceptions
        self.weight = weight

    def __str__(self):
        if len(self.premises) == 0:
            prems = "[]"
        else:
            #prems = sorted(self.premises, key= lambda prop: prop.string)
            prems = sorted(self.premises)
        if len(self.exceptions) == 0:
            excepts = "[]"
        else:
            #excepts = sorted(self.exceptions, key= lambda prop: prop.string)
            excepts = sorted(self.exceptions)
        return "{}, ~{} => {}, {}".format(prems, excepts, self.conclusion, self.weight)

class ArgumentSet(object):
    def __init__(self):
        self.graph = Graph()
        self.graph.to_directed()

    def propset(self):
        g = self.graph
        props = set()
        try:
            props = {p for p in g.vs['prop']}
        except KeyError:
            pass
        return props

    def add_proposition(self, prop, verbose=True):
        if isinstance(prop, PropLiteral):
            if prop not in self.propset():
                self.graph.add_vertex(prop=prop)
                #self.propset.add(prop)
                print("Added proposition '{}' to graph".format(prop))
            else:
                print("Proposition '{}' is already in graph".format(prop))
        else:
            raise AssertionError('Input {} should be PropLiteral'.format(prop))

    def add_argument(self, argument, verbose=True):
        g = self.graph
        conclusion = argument.conclusion
        self.add_proposition(conclusion, verbose=verbose)
        for prop in sorted(argument.premises):
            self.add_proposition(prop, verbose=verbose)
        v_conc = g.vs.select(prop=conclusion)[0]
        v_prems = [v for v in g.vs if v['prop'] in argument.premises]
        edges = [(v_conc.index, target.index) for target in v_prems]
        g.add_edges(edges)
        pass

    def draw(self):
        g = self.graph
        g.vs['label'] = g.vs['prop']
        layout = g.layout_grid()
        plot(g, layout=layout, vertex_label_size=16, vertex_size=8, vertex_label_dist=-5, margin=30)

class ProofStandard(object):
    def __init__(self, default='scintilla'):
        self.proof_standards = ["scintilla", "preponderance",
                                "clear_and_convincing", "beyond_reasonable_doubt",
                                "dialectical_validity"]
        self.default = default
        self.config = defaultdict(lambda x: self.default)

    def set_standard(self, **propstandards):
        for v in propstandards.values():
            if v not in self.proof_standards:
                raise ValueError("{} is not a valid proof standard".format(v))
        self.config.update(propstandards)

    def assign_standard(self, prop):
        return self.config[prop]

class CAES(object):
    def __init__(self, argset, assumptions, weights, standard):
        self.argset = argset
        self.assumptions = assumptions
        self.weights = weights
        self.standard = standard

DOCTEST = True

def graph_test():

    g = Graph()
    g.to_directed()
    a = PropLiteral('kill')
    b = PropLiteral('intent', False)
    c = PropLiteral('murder')

    g.add_vertex(prop=a)
    g.add_vertex(prop=b)
    g.add_vertex(prop=c)
    g.vs['label'] = g.vs['prop']

    g.add_edges([(2, 0), (2, 1)])
    props = [p for p in g.vs['prop']]
    print(props)
    layout = g.layout_grid()
    plot(g, layout=layout, vertex_label_size=16, vertex_size=8, vertex_label_dist=-5, margin=30)

if __name__ == '__main__':
    if DOCTEST:
        import doctest
        doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)
    else:
        graph_test()

<commit_msg>Fixed bugs in treatment of negation<commit_after>"""
Implementation of the Carneades model of argumentation.

Construct some proposition literals.

>>> a = PropLiteral('a')
>>> b = PropLiteral('b', False)

>>> print(a)
a
>>> print(b)
-b

Get the negation of `c`.

>>> c = a.negate()
>>> print(c)
-a
>>> a.negate()
-a
>>> a == a.negate()
False
>>> a == a.negate().negate()

>>> d = b.negate()
>>> print(d)
b

>>> e = PropLiteral('e')
>>> g = PropLiteral('e')
>>> print(e == g)
True

>>> f = e.negate().negate()
>>> print(f)
e
>>> print(e == f)
True

Construct some arguments.

>>> arg1 = Argument(a, premises={b}, weight=0.3)
>>> arg2 = Argument(b, premises={e}, weight=0.6)
>>> arg3 = Argument(b, premises={g})

>>> h = PropLiteral('h')
>>> i = PropLiteral('i', False)
>>> arg4 = Argument(a, premises={h, i}, exceptions={b})

>>> args = [arg1, arg2, arg3, arg4]
>>> for arg in args:
...     print(arg)
[b], ~[] => a, 0.3
[e], ~[] => b, 0.6
[e], ~[] => b, 1.0
[-i, h], ~[b] => a, 1.0

Argument set

>>> argset = ArgumentSet()
>>> argset.add_proposition(a)
Added proposition 'a' to graph
>>> argset.propset()
{a}
>>> argset.add_proposition(b)
Added proposition 'b' to graph
>>> argset.propset() == {a, b}
True
>>> argset.add_proposition(a)
Proposition 'a' is already in graph

>>> kill = PropLiteral('kill')
>>> intent = PropLiteral('intent')
>>> neg_intent = intent.negate()
>>> murder = PropLiteral('murder')
>>> witness1 = PropLiteral('witness1')
>>> unreliable1 = PropLiteral('unreliable1')
>>> witness2 = PropLiteral('witness2')
>>> unreliable2 = PropLiteral('unreliable2')

Proof standard

>>> ps = ProofStandard()
>>> d = {intent: "beyond_reasonable_doubt"}
>>> ps.set_standard(intent="beyond_reasonable_doubt")

CAES

>>> argset = ArgumentSet()
>>> weights = {}
>>> assumptions = {kill, witness1, witness2, unreliable2}
>>> caes = CAES(argset, assumptions, weights, ps)
>>> arg1 = Argument(murder, premises={kill, intent}, weight=0.8)
>>> arg2 = Argument(intent, premises={witness1}, exceptions={unreliable1}, weight=0.3)
>>> arg3 = Argument(neg_intent, premises={witness2}, exceptions={unreliable2}, weight=0.8)

>>> argset.add_argument(arg1)
Added proposition 'murder' to graph
Added proposition '-intent' to graph
Added proposition 'kill' to graph
>>> argset.add_argument(arg2, verbose=False)
>>> argset.add_argument(arg3, verbose=False)
>>> argset.draw()

"""

from igraph import *
from collections import defaultdict

class PropLiteral(object):
    """
    Proposition literals have most of the properties of ordinary strings,
    except that the negation method is Boolean; ie. a.negate().negate() == a.
    """
    def __init__(self, string, polarity=True):
        """
        Propositions are either positive or negative atoms.
        """
        self.polarity = polarity
        self._string = string

    def negate(self):
        """
        Negation of a proposition.
        """
        polarity = (not self.polarity)
        return PropLiteral(self._string, polarity=polarity)

    def __str__(self):
        """
        Override __str__ so that negation is realised as a prefix on the
        string.
        """
        if self.polarity:
            return self._string
        return "-" + self._string

    def __hash__(self):
        return self._string.__hash__()

    def __repr__(self):
        return self.__str__()

    def __eq__(self, other):
        if isinstance(other, self.__class__):
            return self.__str__() == other.__str__()
        else:
            return False

    def __ne__(self, other):
        return not self.__eq__(other)

    def __lt__(self, other):
        return self.__str__() < other.__str__()

class Argument(object):
    def __init__(self, conclusion, premises=set(), exceptions=set(), weight=1.0):
        """
        Propositions are either positive or negative atoms.

        :param conclusion: PropLiteral
        :param premises: set(PropLiteral)
        :param exceptions: set(PropLiteral)
        """

        self.conclusion = conclusion
        self.premises = premises
        self.exceptions = exceptions
        self.weight = weight

    def __str__(self):
        if len(self.premises) == 0:
            prems = "[]"
        else:
            #prems = sorted(self.premises, key= lambda prop: prop.string)
            prems = sorted(self.premises)
        if len(self.exceptions) == 0:
            excepts = "[]"
        else:
            #excepts = sorted(self.exceptions, key= lambda prop: prop.string)
            excepts = sorted(self.exceptions)
        return "{}, ~{} => {}, {}".format(prems, excepts, self.conclusion, self.weight)

class ArgumentSet(object):
    def __init__(self):
        self.graph = Graph()
        self.graph.to_directed()

    def propset(self):
        g = self.graph
        props = set()
        try:
            props = {p for p in g.vs['prop']}
        except KeyError:
            pass
        return props

    def add_proposition(self, prop, verbose=True):
        if isinstance(prop, PropLiteral):
            if prop in self.propset():
                print("Proposition '{}' is already in graph".format(prop))
                return False
            else:
                print("Adding a new prop {} to propset {}".format(prop, self.propset()))

                self.graph.add_vertex(prop=prop)
                #self.propset.add(prop)
                print("Added proposition '{}' to graph".format(prop))
                return True

        else:
            raise AssertionError('Input {} should be PropLiteral'.format(prop))

    def add_argument(self, argument, verbose=True):
        g = self.graph
        conclusion = argument.conclusion
        self.add_proposition(conclusion, verbose=verbose)
        v_conc = g.vs.select(prop=conclusion)[0]
        newprops = set()
        for prop in sorted(argument.premises):
            if self.add_proposition(prop, verbose=verbose):
                newprops.add(prop)
        v_new = [v for v in g.vs if v['prop'] in newprops]
        edges = [(v_conc.index, target.index) for target in v_new]
        g.add_edges(edges)

    def draw(self):
        g = self.graph
        g.vs['label'] = g.vs['prop']
        layout = g.layout_reingold_tilford()
        layout = g.layout_auto()
        plot(g, layout=layout, vertex_label_size=16, vertex_size=8, vertex_label_dist=-5, margin=30)

class ProofStandard(object):
    def __init__(self, default='scintilla'):
        self.proof_standards = ["scintilla", "preponderance",
                                "clear_and_convincing", "beyond_reasonable_doubt",
                                "dialectical_validity"]
        self.default = default
        self.config = defaultdict(lambda x: self.default)

    def set_standard(self, **propstandards):
        for v in propstandards.values():
            if v not in self.proof_standards:
                raise ValueError("{} is not a valid proof standard".format(v))
        self.config.update(propstandards)

    def assign_standard(self, prop):
        return self.config[prop]

class CAES(object):
    def __init__(self, argset, assumptions, weights, standard):
        self.argset = argset
        self.assumptions = assumptions
        self.weights = weights
        self.standard = standard

DOCTEST = True

def graph_test():

    g = Graph()
    g.to_directed()
    a = PropLiteral('kill')
    b = PropLiteral('intent', False)
    c = PropLiteral('murder')

    g.add_vertex(prop=a)
    g.add_vertex(prop=b)
    g.add_vertex(prop=c)
    g.vs['label'] = g.vs['prop']

    g.add_edges([(2, 0), (2, 1)])
    props = [p for p in g.vs['prop']]
    print(props)
    layout = g.layout_grid()
    layout = g.layout_auto()
    plot(g, layout=layout, vertex_label_size=16, vertex_size=8, vertex_label_dist=-5, margin=30)

if __name__ == '__main__':
    if DOCTEST:
        import doctest
        doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)
    else:
        graph_test()

<|endoftext|>


<commit_before>#!/usr/bin/python
# coding: utf-8

# Copyright (c) 2013 Mountainstorm
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

from MobileDevice import *
import os
import struct

class PlistService(object):
	def __init__(self, amdevice, servicenames, format=kCFPropertyListBinaryFormat_v1_0):
		self.format = format
		self.s = None
		self.dev = amdevice
		self.format = format
		for name in servicenames:
			self.s = amdevice.start_service(name)
			if self.s is not None:
				break

		if self.s is None:
			raise RuntimeError(u'Unable to launch one of:', servicenames)

	def disconnect(self):
		os.close(self.s)

	def _sendmsg(self, msg):
		data = dict_to_plist_encoding(msg, self.format)
		os.write(self.s, struct.pack(u'>I'.encode(u'utf-8'), len(data)))
		os.write(self.s, data)

	def _recvmsg(self):
		length = os.read(self.s, 4)
		#print length, length.encode(u'hex')
		l = struct.unpack(u'>I'.encode(u'utf-8'), length)[0]
		reply = ''
		left = l
		while left > 0:
			r = os.read(self.s, left)
			if r is None:
				raise RuntimeError(u'Unable to read reply')
			reply += r
			left -= len(r)
		return dict_from_plist_encoding(reply, self.format)

<commit_msg>Added support for big/little endian plist services<commit_after>#!/usr/bin/python
# coding: utf-8

# Copyright (c) 2013 Mountainstorm
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

from MobileDevice import *
import os
import struct

class PlistService(object):
	def __init__(
			self,
			amdevice,
			servicenames,
			format=kCFPropertyListBinaryFormat_v1_0,
			bigendian=False
		):
		self.bigendian = bigendian
		self.format = format
		self.s = None
		self.dev = amdevice
		self.format = format
		for name in servicenames:
			self.s = amdevice.start_service(name)
			if self.s is not None:
				break

		if self.s is None:
			raise RuntimeError(u'Unable to launch one of:', servicenames)

	def disconnect(self):
		os.close(self.s)

	def _sendmsg(self, msg):
		endian = u'>I'
		if self.bigendian:
			endian = u'<I'
		data = dict_to_plist_encoding(msg, self.format)
		os.write(self.s, struct.pack(endian.encode(u'utf-8'), len(data)))
		os.write(self.s, data)

	def _recvmsg(self):
		retval = None
		endian = u'>I'
		if self.bigendian:
			endian = u'<I'
		length = os.read(self.s, 4)
		if length is not None and len(length) == 4:
			l = struct.unpack(endian.encode(u'utf-8'), length)[0]
			reply = ''
			left = l
			while left > 0:
				r = os.read(self.s, left)
				if r is None:
					raise RuntimeError(u'Unable to read reply')
				reply += r
				left -= len(r)
			retval = dict_from_plist_encoding(reply, self.format)
		return retval

<|endoftext|>