# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2012-2016 GEM Foundation
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.

"""
Module :mod:`openquake.hazardlib.geo.mesh` defines classes :class:`Mesh` and
its subclass :class:`RectangularMesh`.
"""
import numpy
import shapely.geometry
import shapely.ops

from openquake.hazardlib.geo.point import Point
from openquake.hazardlib.geo import geodetic
from openquake.hazardlib.geo import utils as geo_utils

mesh_dt = numpy.dtype([('lon', float), ('lat', float), ('depth', float)])

def build_array(lons_lats_depths):
    """
    Convert a list of n triples into a composite numpy array with fields
    lon, lat, depth and shape (n,) + lons.shape.
    """
    shape = (len(lons_lats_depths),) + lons_lats_depths[0][0].shape
    arr = numpy.zeros(shape, mesh_dt)
    for i, (lons, lats, depths) in enumerate(lons_lats_depths):
        arr['lon'][i] = lons
        arr['lat'][i] = lats
        arr['depth'][i] = depths
    return arr

class Mesh(object):
    """
    Mesh object represent a collection of points and provides the most
    efficient way of keeping those collections in memory.

    :param lons:
        A numpy array of longitude values of points. Array may be
        of arbitrary shape.
    :param lats:
        Numpy array of latitude values. The array must be of the same
        shape as ``lons``.
    :param depths:
        Either ``None``, which means that all points the mesh consists
        of are lying on the earth surface (have zero depth) or numpy
        array of the same shape as previous two.

    Mesh object can also be created from a collection of points, see
    :meth:`from_points_list`.
    """
    #: Tolerance level to be used in various spatial operations when
    #: approximation is required -- set to 5 meters.
    DIST_TOLERANCE = 0.005

    def __init__(self, lons, lats, depths=None):
        assert (isinstance(lons, numpy.ndarray) and
                isinstance(lats, numpy.ndarray) and
                (depths is None or isinstance(depths, numpy.ndarray))
                ), (type(lons), type(lats), type(depths))
        assert ((lons.shape == lats.shape) and
                (depths is None or depths.shape == lats.shape)
                ), (lons.shape, lats.shape)
        assert lons.size > 0
        self.lons = lons
        self.lats = lats
        self.depths = depths

    @classmethod
    def from_points_list(cls, points):
        """
        Create a mesh object from a collection of points.

        :param point:
            List of :class:`~openquake.hazardlib.geo.point.Point` objects.
        :returns:
            An instance of :class:`Mesh` with one-dimensional arrays
            of coordinates from ``points``.
        """
        lons = numpy.zeros(len(points), dtype=float)
        lats = lons.copy()
        depths = lons.copy()
        for i in range(len(points)):
            lons[i] = points[i].longitude
            lats[i] = points[i].latitude
            depths[i] = points[i].depth
        if not depths.any():
            # all points have zero depth, no need to waste memory
            depths = None
        return cls(lons, lats, depths)

    @property
    def shape(self):
        """
        Return the shape of this mesh.

        :returns tuple:
            The shape of this mesh as (rows, columns)
        """
        return self.lons.shape

    def __iter__(self):
        """
        Generate :class:`~openquake.hazardlib.geo.point.Point` objects the mesh
        is composed of.

        Coordinates arrays are processed sequentially (as if they were
        flattened).
        """
        lons = self.lons.flat
        lats = self.lats.flat
        if self.depths is not None:
            depths = self.depths.flat
            for i in range(self.lons.size):
                yield Point(lons[i], lats[i], depths[i])
        else:
            for i in range(self.lons.size):
                yield Point(lons[i], lats[i])

    def __getitem__(self, item):
        """
        Get a submesh of this mesh.

        :param item:
            Indexing is only supported by slices. Those slices are used
            to cut the portion of coordinates (and depths if it is available)
            arrays. These arrays are then used for creating a new mesh.
        :returns:
            A new object of the same type that borrows a portion of geometry
            from this mesh (doesn't copy the array, just references it).
        """
        if isinstance(item, int):
            raise ValueError('You must pass a slice, not an index: %s' % item)
        lons = self.lons[item]
        lats = self.lats[item]
        depths = None
        if self.depths is not None:
            depths = self.depths[item]
        return type(self)(lons, lats, depths)

    def __len__(self):
        """
        Return the number of points in the mesh.
        """
        return self.lons.size

    def __eq__(self, mesh, tol=1.0E-7):
        """
        Compares the mesh with another returning True if all elements are
        equal to within the specific tolerance, False otherwise

        :param mesh:
            Mesh for comparison as instance of :class:
            openquake.hazardlib.geo.mesh.Mesh

        :param float tol:
            Numerical precision for equality
        """
        if self.depths is not None:
            if mesh.depths is not None:
                # Both meshes have depth values - compare equality
                return numpy.allclose(self.lons, mesh.lons, atol=tol) and\
                    numpy.allclose(self.lats, mesh.lats, atol=tol) and\
                    numpy.allclose(self.depths, mesh.depths, atol=tol)
            else:
                # Second mesh missing depths - not equal
                return False
        else:
            if mesh.depths is None:
                return False
            else:
                return numpy.allclose(self.lons, mesh.lons, atol=tol) and\
                    numpy.allclose(self.lats, mesh.lats, atol=tol)

    def get_min_distance(self, mesh):
        """
        Compute and return the minimum distance from the mesh to each point
        in another mesh.

        :returns:
            numpy array of distances in km of the same shape as ``mesh``.

        Method doesn't make any assumptions on arrangement of the points
        in either mesh and instead calculates the distance from each point of
        this mesh to each point of the target mesh and returns the lowest found
        for each.
        """
        return self._min_idx_dst(mesh)[1]

    def get_closest_points(self, mesh):
        """
        Find closest point of this mesh for each one in ``mesh``.

        :returns:
            :class:`Mesh` object of the same shape as ``mesh`` with closest
            points from this one at respective indices.
        """
        min_idx, min_dst = self._min_idx_dst(mesh)
        lons = self.lons.take(min_idx)
        lats = self.lats.take(min_idx)
        if self.depths is None:
            depths = None
        else:
            depths = self.depths.take(min_idx)
        return Mesh(lons, lats, depths)

    def _min_idx_dst(self, mesh):
        if self.depths is None:
            depths1 = numpy.zeros_like(self.lons)
        else:
            depths1 = self.depths
        if mesh.depths is None:
            depths2 = numpy.zeros_like(mesh.lons)
        else:
            depths2 = mesh.depths
        return geodetic.min_idx_dst(
            self.lons, self.lats, depths1, mesh.lons, mesh.lats, depths2)

    def get_distance_matrix(self):
        """
        Compute and return distances between each pairs of points in the mesh.

        This method requires that all the points lie on Earth surface (have
        zero depth) and coordinate arrays are one-dimensional.

        .. warning::
            Because of its quadratic space and time complexity this method
            is safe to use for meshes of up to several thousand points. For
            mesh of 10k points it needs ~800 Mb for just the resulting matrix
            and four times that much for intermediate storage.

        :returns:
            Two-dimensional numpy array, square matrix of distances. The matrix
            has zeros on main diagonal and positive distances in kilometers
            on all other cells. That is, value in cell (3, 5) is the distance
            between mesh's points 3 and 5 in km, and it is equal to value
            in cell (5, 3).

        Uses :func:`openquake.hazardlib.geo.geodetic.geodetic_distance`.
        """
        assert self.lons.ndim == 1
        assert self.depths is None or (self.depths == 0).all()
        distances = geodetic.geodetic_distance(
            self.lons.reshape(self.lons.shape + (1, )),
            self.lats.reshape(self.lats.shape + (1, )),
            self.lons,
            self.lats
        )
        return numpy.matrix(distances, copy=False)

    def _get_proj_convex_hull(self):
        """
        Create a projection centered in the center of this mesh and define
        a convex polygon in that projection, enveloping all the points
        of the mesh.

        :returns:
            Tuple of two items: projection function and shapely 2d polygon.
            Note that the result geometry can be line or point depending
            on number of points in the mesh and their arrangement.
        """
        # create a projection centered in the center of points collection
        proj = geo_utils.get_orthographic_projection(
            *geo_utils.get_spherical_bounding_box(self.lons, self.lats)
        )
        # project all the points and create a shapely multipoint object.
        # need to copy an array because otherwise shapely misinterprets it
        coords = numpy.transpose(proj(self.lons.flatten(),
                                      self.lats.flatten())).copy()
        multipoint = shapely.geometry.MultiPoint(coords)
        # create a 2d polygon from a convex hull around that multipoint.
        polygon2d = multipoint.convex_hull
        return proj, polygon2d

    def _get_proj_enclosing_polygon(self):
        """
        Create a projection centered in the center of this mesh and define
        a minimum polygon in that projection, enveloping all the points
        of the mesh.

        In :class:`Mesh` this is equivalent to :meth:`_get_proj_convex_hull`.
        """
        return self._get_proj_convex_hull()

    def get_convex_hull(self):
        """
        Get a convex polygon object that contains projections of all the points
        of the mesh.

        :returns:
            Instance of :class:`openquake.hazardlib.geo.polygon.Polygon` that
            is a convex hull around all the points in this mesh. If the
            original mesh had only one point, the resulting polygon has a
            square shape with a side length of 10 meters. If there were only
            two points, resulting polygon is a stripe 10 meters wide.
        """
        proj, polygon2d = self._get_proj_convex_hull()
        # if mesh had only one point, the convex hull is a point. if there
        # were two, it is a line string. we need to return a convex polygon
        # object, so extend that area-less geometries by some arbitrarily
        # small distance.
        if isinstance(polygon2d, (shapely.geometry.LineString,
                                  shapely.geometry.Point)):
            polygon2d = polygon2d.buffer(self.DIST_TOLERANCE, 1)

        # avoid circular imports
        from openquake.hazardlib.geo.polygon import Polygon
        return Polygon._from_2d(polygon2d, proj)

class RectangularMesh(Mesh):
    """
    A specification of :class:`Mesh` that requires coordinate numpy-arrays
    to be two-dimensional.

    Rectangular mesh is meant to represent not just an unordered collection
    of points but rather a sort of table of points, where index of the point
    in a mesh is related to it's position with respect to neighbouring points.
    """
    def __init__(self, lons, lats, depths=None):
        super(RectangularMesh, self).__init__(lons, lats, depths)
        assert lons.ndim == 2

    @classmethod
    def from_points_list(cls, points):
        """
        Create a rectangular mesh object from a list of lists of points.
        Lists in a list are supposed to have the same length.

        :param point:
            List of lists of :class:`~openquake.hazardlib.geo.point.Point`
            objects.
        """
        assert points is not None and len(points) > 0 and len(points[0]) > 0, \
            'list of at least one non-empty list of points is required'
        lons = numpy.zeros((len(points), len(points[0])), dtype=float)
        lats = lons.copy()
        depths = lons.copy()
        num_cols = len(points[0])
        for i, row in enumerate(points):
            assert len(row) == num_cols, \
                   'lists of points are not of uniform length'
            for j, point in enumerate(row):
                lons[i][j] = point.longitude
                lats[i][j] = point.latitude
                depths[i][j] = point.depth
        if not depths.any():
            depths = None
        return cls(lons, lats, depths)

    def get_joyner_boore_distance(self, mesh):
        """
        Compute and return Joyner-Boore distance to each point of ``mesh``.
        Point's depth is ignored.

        See
        :meth:`openquake.hazardlib.geo.surface.base.BaseQuadrilateralSurface.get_joyner_boore_distance`
        for definition of this distance.

        :returns:
            numpy array of distances in km of the same shape as ``mesh``.
            Distance value is considered to be zero if a point
            lies inside the polygon enveloping the projection of the mesh
            or on one of its edges.
        """
        # we perform a hybrid calculation (geodetic mesh-to-mesh distance
        # and distance on the projection plane for close points). first,
        # we find the closest geodetic distance for each point of target
        # mesh to this one. in general that distance is greater than
        # the exact distance to enclosing polygon of this mesh and it
        # depends on mesh spacing. but the difference can be neglected
        # if calculated geodetic distance is over some threshold.
        # get the highest slice from the 3D mesh
        distances = geodetic.min_geodetic_distance(
            self.lons, self.lats, mesh.lons, mesh.lats)
        # here we find the points for which calculated mesh-to-mesh
        # distance is below a threshold. this threshold is arbitrary:
        # lower values increase the maximum possible error, higher
        # values reduce the efficiency of that filtering. the maximum
        # error is equal to the maximum difference between a distance
        # from site to two adjacent points of the mesh and distance
        # from site to the line connecting them. thus the error is
        # a function of distance threshold and mesh spacing. the error
        # is maximum when the site lies on a perpendicular to the line
        # connecting points of the mesh and that passes the middle
        # point between them. the error then can be calculated as
        # ``err = trsh - d = trsh - \sqrt(trsh^2 - (ms/2)^2)``, where
        # ``trsh`` and ``d`` are distance to mesh points (the one
        # we found on the previous step) and distance to the line
        # connecting them (the actual distance) and ``ms`` is mesh
        # spacing. the threshold of 40 km gives maximum error of 314
        # meters for meshes with spacing of 10 km and 5.36 km for
        # meshes with spacing of 40 km. if mesh spacing is over
        # ``(trsh / \sqrt(2)) * 2`` then points lying in the middle
        # of mesh cells (that is inside the polygon) will be filtered
        # out by the threshold and have positive distance instead of 0.
        # so for threshold of 40 km mesh spacing should not be more
        # than 56 km (typical values are 5 to 10 km).

        [idxs] = (distances < 40).nonzero()
        if not len(idxs):
            # no point is close enough, return distances as they are
            return distances

        # for all the points that are closer than the threshold we need
        # to recalculate the distance and set it to zero, if point falls
        # inside the enclosing polygon of the mesh. for doing that we
        # project both this mesh and the points of the second mesh--selected
        # by distance threshold--to the same Cartesian space, define
        # minimum shapely polygon enclosing the mesh and calculate point
        # to polygon distance, which gives the most accurate value
        # of distance in km (and that value is zero for points inside
        # the polygon).
        proj, polygon = self._get_proj_enclosing_polygon()
        if not isinstance(polygon, shapely.geometry.Polygon):
            # either line or point is our enclosing polygon. draw
            # a square with side of 10 m around in order to have
            # a proper polygon instead.
            polygon = polygon.buffer(self.DIST_TOLERANCE, 1)
        mesh_xx, mesh_yy = proj(mesh.lons[idxs], mesh.lats[idxs])
        # replace geodetic distance values for points-closer-than-the-threshold
        # by more accurate point-to-polygon distance values.
        distances[idxs] = geo_utils.point_to_polygon_distance(
            polygon, mesh_xx, mesh_yy)

        return distances

    def _get_proj_enclosing_polygon(self):
        """
        See :meth:`Mesh._get_proj_enclosing_polygon`.

        :class:`RectangularMesh` contains an information about relative
        positions of points, so it allows to define the minimum polygon,
        containing the projection of the mesh, which doesn't necessarily
        have to be convex (in contrast to :class:`Mesh` implementation).

        :returns:
            Same structure as :meth:`Mesh._get_proj_convex_hull`.
        """
        if self.lons.size < 4:
            # the mesh doesn't contain even a single cell, use :class:`Mesh`
            # method implementation (which would dilate the point or the line)
            return super(RectangularMesh, self)._get_proj_enclosing_polygon()

        proj = geo_utils.get_orthographic_projection(
            *geo_utils.get_spherical_bounding_box(self.lons.flatten(),
                                                  self.lats.flatten())
        )
        mesh2d = numpy.array(proj(self.lons.transpose(),
                                  self.lats.transpose())).transpose()
        lines = iter(mesh2d)
        # we iterate over horizontal stripes, keeping the "previous"
        # line of points. we keep it reversed, such that together
        # with the current line they define the sequence of points
        # around the stripe.
        prev_line = next(lines)[::-1]
        polygons = []
        for i, line in enumerate(lines):
            coords = numpy.concatenate((prev_line, line, prev_line[0:1]))
            # create the shapely polygon object from the stripe
            # coordinates and simplify it (remove redundant points,
            # if there are any lying on the straight line).
            stripe = shapely.geometry.LineString(coords) \
                                     .simplify(self.DIST_TOLERANCE) \
                                     .buffer(self.DIST_TOLERANCE, 2)
            polygons.append(shapely.geometry.Polygon(stripe.exterior))
            prev_line = line[::-1]
        try:
            # create a final polygon as the union of all the stripe ones
            polygon = shapely.ops.cascaded_union(polygons) \
                                 .simplify(self.DIST_TOLERANCE)
        except ValueError:
            # NOTE(larsbutler): In some rare cases, we've observed ValueErrors
            # ("No Shapely geometry can be created from null value") with very
            # specific sets of polygons such that there are two unique
            # and many duplicates of one.
            # This bug is very difficult to reproduce consistently (except on
            # specific platforms) so the work around here is to remove the
            # duplicate polygons. In fact, we only observed this error on our
            # CI/build machine. None of our dev environments or production
            # machines has encountered this error, at least consistently. >:(
            polygons = [shapely.wkt.loads(x) for x in
                        list(set(p.wkt for p in polygons))]
            polygon = shapely.ops.cascaded_union(polygons) \
                                 .simplify(self.DIST_TOLERANCE)
        return proj, polygon

    def get_middle_point(self):
        """
        Return the middle point of the mesh.

        :returns:
            An instance of :class:`~openquake.hazardlib.geo.point.Point`.

        The middle point is taken from the middle row and a middle column
        of the mesh if there are odd number of both. Otherwise the geometric
        mean point of two or four middle points.
        """
        num_rows, num_cols = self.lons.shape
        mid_row = num_rows // 2
        depth = 0
        if num_rows & 1 == 1:
            # there are odd number of rows
            mid_col = num_cols // 2
            if num_cols & 1 == 1:
                # odd number of columns, we can easily take
                # the middle point
                if self.depths is not None:
                    depth = self.depths[mid_row][mid_col]
                return Point(self.lons[mid_row][mid_col],
                             self.lats[mid_row][mid_col], depth)
            else:
                # even number of columns, need to take two middle
                # points on the middle row
                lon1, lon2 = self.lons[mid_row][mid_col - 1: mid_col + 1]
                lat1, lat2 = self.lats[mid_row][mid_col - 1: mid_col + 1]
                if self.depths is not None:
                    depth1 = self.depths[mid_row][mid_col - 1]
                    depth2 = self.depths[mid_row][mid_col]
        else:
            # there are even number of rows. take the row just above
            # and the one just below the middle and find middle point
            # of each
            submesh1 = self[mid_row - 1: mid_row]
            submesh2 = self[mid_row: mid_row + 1]
            p1, p2 = submesh1.get_middle_point(), submesh2.get_middle_point()
            lon1, lat1, depth1 = p1.longitude, p1.latitude, p1.depth
            lon2, lat2, depth2 = p2.longitude, p2.latitude, p2.depth

        # we need to find the middle between two points
        if self.depths is not None:
            depth = (depth1 + depth2) / 2.0
        lon, lat = geo_utils.get_middle_point(lon1, lat1, lon2, lat2)
        return Point(lon, lat, depth)

    def get_mean_inclination_and_azimuth(self):
        """
        Calculate weighted average inclination and azimuth of the mesh surface.

        :returns:
            Tuple of two float numbers: inclination angle in a range [0, 90]
            and azimuth in range [0, 360) (in decimal degrees).

        The mesh is triangulated, the inclination and azimuth for each triangle
        is computed and average values weighted on each triangle's area
        are calculated. Azimuth is always defined in a way that inclination
        angle doesn't exceed 90 degree.
        """
        assert 1 not in self.lons.shape, (
            "inclination and azimuth are only defined for mesh of more than "
            "one row and more than one column of points"
        )

        if self.depths is not None:
            assert ((self.depths[1:] - self.depths[:-1]) >= 0).all(), (
                "get_mean_inclination_and_azimuth() requires next mesh row "
                "to be not shallower than the previous one"
            )

        points, along_azimuth, updip, diag = self.triangulate()

        # define planes that are perpendicular to each point's vector
        # as normals to those planes
        earth_surface_tangent_normal = geo_utils.normalized(points)

        # calculating triangles' area and normals for top-left triangles
        e1 = along_azimuth[:-1]
        e2 = updip[:, :-1]
        tl_area = geo_utils.triangle_area(e1, e2, diag)
        tl_normal = geo_utils.normalized(numpy.cross(e1, e2))
        # ... and bottom-right triangles
        e1 = along_azimuth[1:]
        e2 = updip[:, 1:]
        br_area = geo_utils.triangle_area(e1, e2, diag)
        br_normal = geo_utils.normalized(numpy.cross(e1, e2))

        if self.depths is None:
            # mesh is on earth surface, inclination is zero
            inclination = 0
        else:
            # inclination calculation
            # top-left triangles
            en = earth_surface_tangent_normal[:-1, :-1]
            # cosine of inclination of the triangle is scalar product
            # of vector normal to triangle plane and (normalized) vector
            # pointing to top left corner of a triangle from earth center
            incl_cos = numpy.sum(en * tl_normal, axis=-1).clip(-1.0, 1.0)
            # we calculate average angle using mean of circular quantities
            # formula: define 2d vector for each triangle where length
            # of the vector corresponds to triangle's weight (we use triangle
            # area) and angle is equal to inclination angle. then we calculate
            # the angle of vector sum of all those vectors and that angle
            # is the weighted average.
            xx = numpy.sum(tl_area * incl_cos)
            # express sine via cosine using Pythagorean trigonometric identity,
            # this is a bit faster than sin(arccos(incl_cos))
            yy = numpy.sum(tl_area * numpy.sqrt(1 - incl_cos * incl_cos))

            # bottom-right triangles
            en = earth_surface_tangent_normal[1:, 1:]
            # we need to clip scalar product values because in some cases
            # they might exceed range where arccos is defined ([-1, 1])
            # because of floating point imprecision
            incl_cos = numpy.sum(en * br_normal, axis=-1).clip(-1.0, 1.0)
            # weighted angle vectors are calculated independently for top-left
            # and bottom-right triangles of each cell in a mesh. here we
            # combine both and finally get the weighted mean angle
            xx += numpy.sum(br_area * incl_cos)
            yy += numpy.sum(br_area * numpy.sqrt(1 - incl_cos * incl_cos))
            inclination = numpy.degrees(numpy.arctan2(yy, xx))

        # azimuth calculation is done similar to one for inclination. we also
        # do separate calculations for top-left and bottom-right triangles
        # and also combine results using mean of circular quantities approach

        # unit vector along z axis
        z_unit = numpy.array([0.0, 0.0, 1.0])

        # unit vectors pointing west from each point of the mesh, they define
        # planes that contain meridian of respective point
        norms_west = geo_utils.normalized(numpy.cross(points + z_unit, points))
        # unit vectors parallel to planes defined by previous ones. they are
        # directed from each point to a point lying on z axis on the same
        # distance from earth center
        norms_north = geo_utils.normalized(numpy.cross(points, norms_west))
        # need to normalize triangles' azimuthal edges because we will project
        # them on other normals and thus calculate an angle in between
        along_azimuth = geo_utils.normalized(along_azimuth)

        # process top-left triangles
        # here we identify the sign of direction of the triangles' azimuthal
        # edges: is edge pointing west or east? for finding that we project
        # those edges to vectors directing to west by calculating scalar
        # product and get the sign of resulting value: if it is negative
        # than the resulting azimuth should be negative as top edge is pointing
        # west.
        sign = numpy.sign(numpy.sign(
            numpy.sum(along_azimuth[:-1] * norms_west[:-1, :-1], axis=-1))
            # we run numpy.sign(numpy.sign(...) + 0.1) to make resulting values
            # be only either -1 or 1 with zero values (when edge is pointing
            # strictly north or south) expressed as 1 (which means "don't
            # change the sign")
            + 0.1
        )
        # the length of projection of azimuthal edge on norms_north is cosine
        # of edge's azimuth
        az_cos = numpy.sum(along_azimuth[:-1] * norms_north[:-1, :-1], axis=-1)
        # use the same approach for finding the weighted mean
        # as for inclination (see above)
        xx = numpy.sum(tl_area * az_cos)
        # the only difference is that azimuth is defined in a range
        # [0, 360), so we need to have two reference planes and change
        # sign of projection on one normal to sign of projection to another one
        yy = numpy.sum(tl_area * numpy.sqrt(1 - az_cos * az_cos) * sign)

        # bottom-right triangles
        sign = numpy.sign(numpy.sign(
            numpy.sum(along_azimuth[1:] * norms_west[1:, 1:], axis=-1))
            + 0.1
        )
        az_cos = numpy.sum(along_azimuth[1:] * norms_north[1:, 1:], axis=-1)
        xx += numpy.sum(br_area * az_cos)
        yy += numpy.sum(br_area * numpy.sqrt(1 - az_cos * az_cos) * sign)

        azimuth = numpy.degrees(numpy.arctan2(yy, xx))
        if azimuth < 0:
            azimuth += 360

        if inclination > 90:
            # average inclination is over 90 degree, that means that we need
            # to reverse azimuthal direction in order for inclination to be
            # in range [0, 90]
            inclination = 180 - inclination
            azimuth = (azimuth + 180) % 360

        return inclination, azimuth

    def get_cell_dimensions(self):
        """
        Calculate centroid, width, length and area of each mesh cell.

        :returns:
            Tuple of four elements, each being 2d numpy array.
            Each array has both dimensions less by one the dimensions
            of the mesh, since they represent cells, not vertices.
            Arrays contain the following cell information:

            #. centroids, 3d vectors in a Cartesian space,
            #. length (size along row of points) in km,
            #. width (size along column of points) in km,
            #. area in square km.
        """
        points, along_azimuth, updip, diag = self.triangulate()
        top = along_azimuth[:-1]
        left = updip[:, :-1]
        tl_area = geo_utils.triangle_area(top, left, diag)
        top_length = numpy.sqrt(numpy.sum(top * top, axis=-1))
        left_length = numpy.sqrt(numpy.sum(left * left, axis=-1))

        bottom = along_azimuth[1:]
        right = updip[:, 1:]
        br_area = geo_utils.triangle_area(bottom, right, diag)
        bottom_length = numpy.sqrt(numpy.sum(bottom * bottom, axis=-1))
        right_length = numpy.sqrt(numpy.sum(right * right, axis=-1))

        cell_area = tl_area + br_area

        tl_center = (points[:-1, :-1] + points[:-1, 1:] + points[1:, :-1]) / 3
        br_center = (points[:-1, 1:] + points[1:, :-1] + points[1:, 1:]) / 3

        cell_center = ((tl_center * tl_area.reshape(tl_area.shape + (1, ))
                        + br_center * br_area.reshape(br_area.shape + (1, )))
                       / cell_area.reshape(cell_area.shape + (1, )))

        cell_length = ((top_length * tl_area + bottom_length * br_area)
                       / cell_area)
        cell_width = ((left_length * tl_area + right_length * br_area)
                      / cell_area)

        return cell_center, cell_length, cell_width, cell_area

    def triangulate(self):
        """
        Convert mesh points to vectors in Cartesian space.

        :returns:
            Tuple of four elements, each being 2d numpy array of 3d vectors
            (the same structure and shape as the mesh itself). Those arrays
            are:

            #. points vectors,
            #. vectors directed from each point (excluding the last column)
               to the next one in a same row →,
            #. vectors directed from each point (excluding the first row)
               to the previous one in a same column ↑,
            #. vectors pointing from a bottom left point of each mesh cell
               to top right one ↗.

            So the last three arrays of vectors allow to construct triangles
            covering the whole mesh.
        """
        points = geo_utils.spherical_to_cartesian(self.lons, self.lats,
                                                  self.depths)
        # triangulate the mesh by defining vectors of triangles edges:
        # →
        along_azimuth = points[:, 1:] - points[:, :-1]
        # ↑
        updip = points[:-1] - points[1:]
        # ↗
        diag = points[:-1, 1:] - points[1:, :-1]

        return points, along_azimuth, updip, diag

    def get_mean_width(self):
        """
        Calculate and return (weighted) mean width (km) of a mesh surface.

        The length of each mesh column is computed (summing up the cell widths
        in a same column), and the mean value (weighted by the mean cell
        length in each column) is returned.
        """
        assert 1 not in self.lons.shape, (
            "mean width is only defined for mesh of more than "
            "one row and more than one column of points")

        _, cell_length, cell_width, cell_area = self.get_cell_dimensions()

        # compute widths along each mesh column
        widths = numpy.sum(cell_width, axis=0)

        # compute (weighted) mean cell length along each mesh column
        column_areas = numpy.sum(cell_area, axis=0)
        mean_cell_lengths = numpy.sum(cell_length * cell_area, axis=0) / \
            column_areas

        # compute and return weighted mean
        return numpy.sum(widths * mean_cell_lengths) / \
            numpy.sum(mean_cell_lengths)


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

"""
Main script. See README.md for more information

Use python 3
"""

import argparse  # Command line parsing
import configparser  # Saving the models parameters
import datetime  # Chronometer
import os  # Files management
import tensorflow as tf
import numpy as np
import math

from tqdm import tqdm  # Progress bar
from tensorflow.python import debug as tf_debug

from chatbot.textdata import TextData
from chatbot.model import Model

class Chatbot:
    """
    Main class which launch the training or testing mode
    """

    class TestMode:
        """ Simple structure representing the different testing modes
        """
        ALL = 'all'
        INTERACTIVE = 'interactive'  # The user can write his own questions
        DAEMON = 'daemon'  # The chatbot runs on background and can regularly be called to predict something

    def __init__(self):
        """
        """
        # Model/dataset parameters
        self.args = None

        # Task specific object
        self.textData = None  # Dataset
        self.model = None  # Sequence to sequence model

        # Tensorflow utilities for convenience saving/logging
        self.writer = None
        self.saver = None
        self.modelDir = ''  # Where the model is saved
        self.globStep = 0  # Represent the number of iteration for the current model

        # TensorFlow main session (we keep track for the daemon)
        self.sess = None

        # Filename and directories constants
        self.MODEL_DIR_BASE = 'save' + os.sep + 'model'
        self.MODEL_NAME_BASE = 'model'
        self.MODEL_EXT = '.ckpt'
        self.CONFIG_FILENAME = 'params.ini'
        self.CONFIG_VERSION = '0.5'
        self.TEST_IN_NAME = 'data' + os.sep + 'test' + os.sep + 'samples.txt'
        self.TEST_OUT_SUFFIX = '_predictions.txt'
        self.SENTENCES_PREFIX = ['Q: ', 'A: ']

    @staticmethod
    def parseArgs(args):
        """
        Parse the arguments from the given command line
        Args:
            args (list<str>): List of arguments to parse. If None, the default sys.argv will be parsed
        """

        parser = argparse.ArgumentParser()

        # Global options
        globalArgs = parser.add_argument_group('Global options')
        globalArgs.add_argument('--test', action='store_true', default=True)
        globalArgs.add_argument('--createDataset', action='store_true',
                                help='if present, the program will only generate the dataset from the corpus (no training/testing)')
        globalArgs.add_argument('--playDataset', type=int, nargs='?', const=10, default=None,
                                help='if set, the program  will randomly play some samples(can be use conjointly with createDataset if this is the only action you want to perform)')
        globalArgs.add_argument('--reset', action='store_true', default=False,
                                help='use this if you want to ignore the previous model present on the model directory (Warning: the model will be destroyed with all the folder content)')
        globalArgs.add_argument('--verbose', action='store_true',
                                help='When testing, will plot the outputs at the same time they are computed')
        globalArgs.add_argument('--debug', action='store_true',
                                help='run DeepQA with Tensorflow debug mode. Read TF documentation for more details on this.')
        globalArgs.add_argument('--keepAll', action='store_true',
                                help='If this option is set, all saved model will be kept (Warning: make sure you have enough free disk space or increase saveEvery)')  # TODO: Add an option to delimit the max size
        globalArgs.add_argument('--modelTag', type=str, default=None,
                                help='tag to differentiate which model to store/load')
        globalArgs.add_argument('--rootDir', type=str, default="",
                                help='folder where to look for the models and data')
        globalArgs.add_argument('--watsonMode', action='store_true',
                                help='Inverse the questions and answer when training (the network try to guess the question)')
        globalArgs.add_argument('--autoEncode', action='store_true',
                                help='Randomly pick the question or the answer and use it both as input and output')
        globalArgs.add_argument('--device', type=str, default=None,
                                help='\'gpu\' or \'cpu\' (Warning: make sure you have enough free RAM), allow to choose on which hardware run the model')
        globalArgs.add_argument('--seed', type=int, default=None, help='random seed for replication')

        # Dataset options
        datasetArgs = parser.add_argument_group('Dataset options')
        datasetArgs.add_argument('--corpus', choices=TextData.corpusChoices(), default=TextData.corpusChoices()[0], help='corpus on which extract the dataset.')
        datasetArgs.add_argument('--datasetTag', type=str, default='', help='add a tag to the dataset (file where to load the vocabulary and the precomputed samples, not the original corpus). Useful to manage multiple versions. Also used to define the file used for the lightweight format.')  # The samples are computed from the corpus if it does not exist already. There are saved in \'data/samples/\'
        datasetArgs.add_argument('--ratioDataset', type=float, default=1.0, help='ratio of dataset used to avoid using the whole dataset')  # Not implemented, useless ?
        datasetArgs.add_argument('--maxLength', type=int, default=10, help='maximum length of the sentence (for input and output), define number of maximum step of the RNN')
        datasetArgs.add_argument('--filterVocab', type=int, default=1, help='remove rarelly used words (by default words used only once). 0 to keep all words.')
        datasetArgs.add_argument('--skipLines', action='store_true', help='Generate training samples by only using even conversation lines as questions (and odd lines as answer). Useful to train the network on a particular person.')
        datasetArgs.add_argument('--vocabularySize', type=int, default=40000, help='Limit the number of words in the vocabulary (0 for unlimited)')

        # Network options (Warning: if modifying something here, also make the change on save/loadParams() )
        nnArgs = parser.add_argument_group('Network options', 'architecture related option')
        nnArgs.add_argument('--hiddenSize', type=int, default=512, help='number of hidden units in each RNN cell')
        nnArgs.add_argument('--numLayers', type=int, default=2, help='number of rnn layers')
        nnArgs.add_argument('--softmaxSamples', type=int, default=0, help='Number of samples in the sampled softmax loss function. A value of 0 deactivates sampled softmax')
        nnArgs.add_argument('--initEmbeddings', action='store_true', help='if present, the program will initialize the embeddings with pre-trained word2vec vectors')
        nnArgs.add_argument('--embeddingSize', type=int, default=64, help='embedding size of the word representation')
        nnArgs.add_argument('--embeddingSource', type=str, default="GoogleNews-vectors-negative300.bin", help='embedding file to use for the word representation')

        # Training options
        trainingArgs = parser.add_argument_group('Training options')
        trainingArgs.add_argument('--numEpochs', type=int, default=30, help='maximum number of epochs to run')
        trainingArgs.add_argument('--saveEvery', type=int, default=2000, help='nb of mini-batch step before creating a model checkpoint')
        trainingArgs.add_argument('--batchSize', type=int, default=256, help='mini-batch size')
        trainingArgs.add_argument('--learningRate', type=float, default=0.002, help='Learning rate')
        trainingArgs.add_argument('--dropout', type=float, default=0.9, help='Dropout rate (keep probabilities)')

        return parser.parse_args(args)

    def run(self, args=None):
        """
        Launch the training and/or the interactive mode
        """
        print('Welcome to DeepQA v0.1 !')
        print()
        print('TensorFlow detected: v{}'.format(tf.__version__))

        self.args = self.parseArgs(args)

        if not self.args.rootDir:
            self.args.rootDir = os.getcwd()  # Use the current working directory

        self.loadModelParams()  # Update the self.modelDir and self.globStep, for now, not used when loading Model (but need to be called before _getSummaryName)
        self.textData = TextData(self.args)

        tf.reset_default_graph()
        # Prepare the model
        with tf.device(self.getDevice()):
            self.model = Model(self.args, self.textData)
        self.saver = tf.train.Saver(max_to_keep=200)

        # Running session
        self.sess = tf.Session(config=tf.ConfigProto(
            allow_soft_placement=True,  # Allows backup device for non GPU-available operations (when forcing GPU)
            log_device_placement=False)  # Too verbose ?
        )  # TODO: Replace all sess by self.sess (not necessary a good idea) ?

        self.sess.run(tf.global_variables_initializer())
        # Reload the model eventually (if it exist.), on testing mode, the models are not loaded here (but in predictTestset)
        self.managePreviousModel(self.sess)
        print("Done")

    def predict(self, inp):
        if inp == '' or inp == 'exit':
            return

        questionSeq = []  # Will be contain the question as seen by the encoder
        answer = self.singlePredict(inp, questionSeq)
        if not answer:
            return
        return self.textData.sequence2str(answer, clean=True)

    def singlePredict(self, question, questionSeq=None):
        """ Predict the sentence
        Args:
            question (str): the raw input sentence
            questionSeq (List<int>): output argument. If given will contain the input batch sequence
        Return:
            list <int>: the word ids corresponding to the answer
        """
        # Create the input batch
        batch = self.textData.sentence2enco(question)
        if not batch:
            return None
        if questionSeq is not None:  # If the caller want to have the real input
            questionSeq.extend(batch.encoderSeqs)

        # Run the model
        ops, feedDict = self.model.step(batch)
        output = self.sess.run(ops[0], feedDict)  # TODO: Summarize the output too (histogram, ...)
        answer = self.textData.deco2sentence(output)

        return answer

    def loadEmbedding(self, sess):
        """ Initialize embeddings with pre-trained word2vec vectors
        Will modify the embedding weights of the current loaded model
        Uses the GoogleNews pre-trained values (path hardcoded)
        """

        # Fetch embedding variables from model
        with tf.variable_scope("embedding_rnn_seq2seq/rnn/embedding_wrapper", reuse=True):
            em_in = tf.get_variable("embedding")
        with tf.variable_scope("embedding_rnn_seq2seq/embedding_rnn_decoder", reuse=True):
            em_out = tf.get_variable("embedding")

        # Disable training for embeddings
        variables = tf.get_collection_ref(tf.GraphKeys.TRAINABLE_VARIABLES)
        variables.remove(em_in)
        variables.remove(em_out)

        # If restoring a model, we can leave here
        if self.globStep != 0:
            return

        # New model, we load the pre-trained word2vec data and initialize embeddings
        embeddings_path = os.path.join(self.args.rootDir, 'data', 'embeddings', self.args.embeddingSource)
        embeddings_format = os.path.splitext(embeddings_path)[1][1:]
        print("Loading pre-trained word embeddings from %s " % embeddings_path)
        with open(embeddings_path, "rb") as f:
            header = f.readline()
            vocab_size, vector_size = map(int, header.split())
            binary_len = np.dtype('float32').itemsize * vector_size
            initW = np.random.uniform(-0.25,0.25,(len(self.textData.word2id), vector_size))
            for line in tqdm(range(vocab_size)):
                word = []
                while True:
                    ch = f.read(1)
                    if ch == b' ':
                        word = b''.join(word).decode('utf-8')
                        break
                    if ch != b'\n':
                        word.append(ch)
                if word in self.textData.word2id:
                    if embeddings_format == 'bin':
                        vector = np.fromstring(f.read(binary_len), dtype='float32')
                    elif embeddings_format == 'vec':
                        vector = np.fromstring(f.readline(), sep=' ', dtype='float32')
                    else:
                        raise Exception("Unkown format for embeddings: %s " % embeddings_format)
                    initW[self.textData.word2id[word]] = vector
                else:
                    if embeddings_format == 'bin':
                        f.read(binary_len)
                    elif embeddings_format == 'vec':
                        f.readline()
                    else:
                        raise Exception("Unkown format for embeddings: %s " % embeddings_format)

        # PCA Decomposition to reduce word2vec dimensionality
        if self.args.embeddingSize < vector_size:
            U, s, Vt = np.linalg.svd(initW, full_matrices=False)
            S = np.zeros((vector_size, vector_size), dtype=complex)
            S[:vector_size, :vector_size] = np.diag(s)
            initW = np.dot(U[:, :self.args.embeddingSize], S[:self.args.embeddingSize, :self.args.embeddingSize])

        # Initialize input and output embeddings
        sess.run(em_in.assign(initW))
        sess.run(em_out.assign(initW))

    def managePreviousModel(self, sess):
        """ Restore or reset the model, depending of the parameters
        If the destination directory already contains some file, it will handle the conflict as following:
         * If --reset is set, all present files will be removed (warning: no confirmation is asked) and the training
         restart from scratch (globStep & cie reinitialized)
         * Otherwise, it will depend of the directory content. If the directory contains:
           * No model files (only summary logs): works as a reset (restart from scratch)
           * Other model files, but modelName not found (surely keepAll option changed): raise error, the user should
           decide by himself what to do
           * The right model file (eventually some other): no problem, simply resume the training
        In any case, the directory will exist as it has been created by the summary writer
        Args:
            sess: The current running session
        """

        modelName = self._getModelName()

        if os.listdir(self.modelDir):
            if os.path.exists(modelName):  # Restore the model
                print('Restoring previous model from {}'.format(modelName))
                self.saver.restore(sess, modelName)  # Will crash when --reset is not activated and the model has not been saved yet
            else:  # No other model to conflict with (probably summary files)
                print('No previous model found, but some files found at {}. Cleaning...'.format(self.modelDir))  # Warning: No confirmation asked
                self.args.reset = True

        else:
            print('No previous model found, starting from clean directory: {}'.format(self.modelDir))

    def loadModelParams(self):
        """ Load the some values associated with the current model, like the current globStep value
        For now, this function does not need to be called before loading the model (no parameters restored). However,
        the modelDir name will be initialized here so it is required to call this function before managePreviousModel(),
        _getModelName() or _getSummaryName()
        Warning: if you modify this function, make sure the changes mirror saveModelParams, also check if the parameters
        should be reset in managePreviousModel
        """
        # Compute the current model path
        self.modelDir = os.path.join(self.args.rootDir, self.MODEL_DIR_BASE)
        if self.args.modelTag:
            self.modelDir += '-' + self.args.modelTag

        # If there is a previous model, restore some parameters
        configName = os.path.join(self.modelDir, self.CONFIG_FILENAME)
        # Loading
        config = configparser.ConfigParser()
        config.read(configName)

        # Check the version
        currentVersion = config['General'].get('version')
        if currentVersion != self.CONFIG_VERSION:
            raise UserWarning('Present configuration version {0} does not match {1}. You can try manual changes on \'{2}\''.format(currentVersion, self.CONFIG_VERSION, configName))

        # Restoring the the parameters
        self.globStep = config['General'].getint('globStep')
        self.args.watsonMode = config['General'].getboolean('watsonMode')
        self.args.autoEncode = config['General'].getboolean('autoEncode')
        self.args.corpus = config['General'].get('corpus')

        self.args.datasetTag = config['Dataset'].get('datasetTag')
        self.args.maxLength = config['Dataset'].getint('maxLength')  # We need to restore the model length because of the textData associated and the vocabulary size (TODO: Compatibility mode between different maxLength)
        self.args.filterVocab = config['Dataset'].getint('filterVocab')
        self.args.skipLines = config['Dataset'].getboolean('skipLines')
        self.args.vocabularySize = config['Dataset'].getint('vocabularySize')

        self.args.hiddenSize = config['Network'].getint('hiddenSize')
        self.args.numLayers = config['Network'].getint('numLayers')
        self.args.softmaxSamples = config['Network'].getint('softmaxSamples')
        self.args.initEmbeddings = config['Network'].getboolean('initEmbeddings')
        self.args.embeddingSize = config['Network'].getint('embeddingSize')
        self.args.embeddingSource = config['Network'].get('embeddingSource')

        # No restoring for training params, batch size or other non model dependent parameters

        # Show the restored params
        print()
        print('Warning: Restoring parameters:')
        print('globStep: {}'.format(self.globStep))
        print('watsonMode: {}'.format(self.args.watsonMode))
        print('autoEncode: {}'.format(self.args.autoEncode))
        print('corpus: {}'.format(self.args.corpus))
        print('datasetTag: {}'.format(self.args.datasetTag))
        print('maxLength: {}'.format(self.args.maxLength))
        print('filterVocab: {}'.format(self.args.filterVocab))
        print('skipLines: {}'.format(self.args.skipLines))
        print('vocabularySize: {}'.format(self.args.vocabularySize))
        print('hiddenSize: {}'.format(self.args.hiddenSize))
        print('numLayers: {}'.format(self.args.numLayers))
        print('softmaxSamples: {}'.format(self.args.softmaxSamples))
        print('initEmbeddings: {}'.format(self.args.initEmbeddings))
        print('embeddingSize: {}'.format(self.args.embeddingSize))
        print('embeddingSource: {}'.format(self.args.embeddingSource))
        print()

        # For now, not arbitrary  independent maxLength between encoder and decoder
        self.args.maxLengthEnco = self.args.maxLength
        self.args.maxLengthDeco = self.args.maxLength + 2

    def _getSummaryName(self):
        """ Parse the argument to decide were to save the summary, at the same place that the model
        The folder could already contain logs if we restore the training, those will be merged
        Return:
            str: The path and name of the summary
        """
        return self.modelDir

    def _getModelName(self):
        """ Parse the argument to decide were to save/load the model
        This function is called at each checkpoint and the first time the model is load. If keepAll option is set, the
        globStep value will be included in the name.
        Return:
            str: The path and name were the model need to be saved
        """
        modelName = os.path.join(self.modelDir, self.MODEL_NAME_BASE)
        if self.args.keepAll:  # We do not erase the previously saved model by including the current step on the name
            modelName += '-' + str(self.globStep)
        return modelName + self.MODEL_EXT

    def getDevice(self):
        """ Parse the argument to decide on which device run the model
        Return:
            str: The name of the device on which run the program
        """
        if self.args.device == 'cpu':
            return '/cpu:0'
        elif self.args.device == 'gpu':
            return '/gpu:0'
        elif self.args.device is None:  # No specified device (default)
            return None
        else:
            print('Warning: Error in the device name: {}, use the default device'.format(self.args.device))
            return None


import numpy as np
from TeachMyAgent.students.openai_baselines.common.runners import AbstractEnvRunner

class SynchronousRunner():
    """
    Synchronous runner to interact with environment and sample trajectories (created for TeachMyAgent).

    We use this object to make a mini batch of experiences
    __init__:
    - Initialize the runner

    run():
    - Make a mini batch
    """
    def __init__(self, *, env, model, nsteps, gamma, lam, max_ep_len, Teacher):
        self.env = env
        self.model = model
        self.nsteps = nsteps
        self.nb_total_steps = 0
        self.batch_ob_shape = (1 * nsteps,) + env.observation_space.shape
        self.obs = np.zeros((1,) + env.observation_space.shape, dtype=env.observation_space.dtype.name)

        if Teacher:
            Teacher.set_env_params(env.get_raw_env())
        unscaled_o, o = env.reset()
        if Teacher:
            Teacher.record_train_task_initial_state(unscaled_o[0])
        self.prev_unscaled_obs = unscaled_o[0]
        self.obs = np.array(o)
        self.states = model.initial_state
        self.dones = [False]

        # Lambda used in GAE (General Advantage Estimation)
        self.lam = lam
        # Discount rate
        self.gamma = gamma

        # ACL utils
        self.max_ep_len = max_ep_len
        self.ep_len = 0
        self.ep_ret = 0
        self.raw_ep_ret = 0

    def run(self, Teacher):
        # Here, we init the lists that will contain the mb of experiences
        mb_obs, mb_rewards, mb_actions, mb_values, mb_dones, mb_neglogpacs = [],[],[],[],[],[]
        mb_states = self.states
        epinfos = []
        # For n in range number of steps
        for _ in range(self.nsteps):
            # Given observations, get action value and neglopacs
            # We already have self.obs because Runner superclass run self.obs[:] = env.reset() on init
            actions, values, self.states, neglogpacs = self.model.step(self.obs, S=self.states, M=self.dones)
            mb_obs.append(self.obs.copy())
            mb_actions.append(actions)
            mb_values.append(values)
            mb_neglogpacs.append(neglogpacs)
            mb_dones.append(self.dones)
            self.nb_total_steps += 1

            # Take actions in env and look the results
            # Infos contains a ton of useful informations
            a = actions
            o, r, d, i = self.env.step(a)
            unscaled_reward = i[0]["original_reward"][0]
            unscaled_o = i[0]["original_obs"][0]
            self.ep_len += 1
            self.ep_ret += r[0]
            self.raw_ep_ret += unscaled_reward
            Teacher.record_train_step(self.prev_unscaled_obs, a[0], unscaled_reward, unscaled_o, d[0])

            if d or self.ep_len == self.max_ep_len:
                if Teacher:
                    success = False if 'success' not in i else i["success"]
                    Teacher.record_train_episode(self.raw_ep_ret, self.ep_len, success)
                    Teacher.set_env_params(self.env.get_raw_env())
                unscaled_o, o = self.env.reset()
                unscaled_o = unscaled_o[0]
                Teacher.record_train_task_initial_state(unscaled_o)
                epinfos.append({
                    "r": self.raw_ep_ret,
                    "l": self.ep_len
                })
                self.ep_len = 0
                self.ep_ret = 0
                self.raw_ep_ret = 0

            self.obs, self.prev_unscaled_obs, rewards, self.dones, infos = o, unscaled_o, r, d, i
            mb_rewards.append(rewards)
        #batch of steps to batch of rollouts
        mb_obs = np.asarray(mb_obs, dtype=self.obs.dtype)
        mb_rewards = np.asarray(mb_rewards, dtype=np.float32)
        mb_actions = np.asarray(mb_actions)
        mb_values = np.asarray(mb_values, dtype=np.float32)
        mb_neglogpacs = np.asarray(mb_neglogpacs, dtype=np.float32)
        mb_dones = np.asarray(mb_dones, dtype=np.bool)
        last_values = self.model.value(self.obs, S=self.states, M=self.dones)

        # discount/bootstrap off value fn
        mb_returns = np.zeros_like(mb_rewards)
        mb_advs = np.zeros_like(mb_rewards)
        lastgaelam = 0
        for t in reversed(range(self.nsteps)):
            if t == self.nsteps - 1:
                nextnonterminal = 1.0 - self.dones
                nextvalues = last_values
            else:
                nextnonterminal = 1.0 - mb_dones[t+1]
                nextvalues = mb_values[t+1]
            delta = mb_rewards[t] + self.gamma * nextvalues * nextnonterminal - mb_values[t]
            mb_advs[t] = lastgaelam = delta + self.gamma * self.lam * nextnonterminal * lastgaelam
        mb_returns = mb_advs + mb_values
        return (*map(sf01, (mb_obs, mb_returns, mb_dones, mb_actions, mb_values, mb_neglogpacs)),
            mb_states, epinfos)
# obs, returns, masks, actions, values, neglogpacs, states = runner.run()
def sf01(arr):
    """
    swap and then flatten axes 0 and 1
    """
    s = arr.shape
    return arr.swapaxes(0, 1).reshape(s[0] * s[1], *s[2:])


#!/usr/bin/env python
#
# Copyright (c) 2018-2020 Intel Corporation
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
#

""" This module contains PID controllers to perform lateral and longitudinal control. """

from collections import deque
import math
import numpy as np
from transforms3d.euler import quat2euler
from geometry_msgs.msg import Point  # pylint: disable=import-error
from carla_msgs.msg import CarlaEgoVehicleControl  # pylint: disable=import-error

class VehiclePIDController(object):  # pylint: disable=too-few-public-methods
    """
    VehiclePIDController is the combination of two PID controllers (lateral and longitudinal)
    to perform the low level control a vehicle from client side
    """

    def __init__(self, node, args_lateral=None, args_longitudinal=None):
        """
        :param vehicle: actor to apply to local planner logic onto
        :param args_lateral: dictionary of arguments to set the lateral PID controller using
                             the following semantics:
                             K_P -- Proportional term
                             K_D -- Differential term
                             K_I -- Integral term
        :param args_longitudinal: dictionary of arguments to set the longitudinal PID
                                  controller using the following semantics:
                             K_P -- Proportional term
                             K_D -- Differential term
                             K_I -- Integral term
        """
        if not args_lateral:
            args_lateral = {'K_P': 1.0, 'K_D': 0.0, 'K_I': 0.0}
        if not args_longitudinal:
            args_longitudinal = {'K_P': 1.0, 'K_D': 0.0, 'K_I': 0.0}

        self.node = node
        self._lon_controller = PIDLongitudinalController(**args_longitudinal)
        self._lat_controller = PIDLateralController(**args_lateral)

    def run_step(self, target_speed, current_speed, current_pose, waypoint):
        """
        Execute one step of control invoking both lateral and longitudinal
        PID controllers to reach a target waypoint at a given target_speed.

        :param target_speed: desired vehicle speed
        :param waypoint: target location encoded as a waypoint
        :return: control signal (throttle and steering)
        """
        control = CarlaEgoVehicleControl()
        throttle = self._lon_controller.run_step(target_speed, current_speed)
        steering = self._lat_controller.run_step(current_pose, waypoint)
        control.steer = -steering
        control.throttle = throttle
        control.brake = 0.0
        control.hand_brake = False
        control.manual_gear_shift = False

        return control

class PIDLongitudinalController(object):  # pylint: disable=too-few-public-methods
    """
    PIDLongitudinalController implements longitudinal control using a PID.
    """

    def __init__(self, K_P=1.0, K_D=0.0, K_I=0.0):
        """
        :param vehicle: actor to apply to local planner logic onto
        :param K_P: Proportional term
        :param K_D: Differential term
        :param K_I: Integral term
        """
        self._K_P = K_P
        self._K_D = K_D
        self._K_I = K_I
        self.error = 0.0
        self.error_integral = 0.0
        self.error_derivative = 0.0

    def run_step(self, target_speed, current_speed):
        """
        Estimate the throttle of the vehicle based on the PID equations

        :param target_speed:  target speed in Km/h
        :param current_speed: current speed of the vehicle in Km/h
        :return: throttle control in the range [0, 1]
        """
        previous_error = self.error
        self.error = target_speed - current_speed
        # restrict integral term to avoid integral windup
        self.error_integral = np.clip(self.error_integral + self.error, -40.0, 40.0)
        self.error_derivative = self.error - previous_error
        output = self._K_P * self.error + self._K_I * self.error_integral + self._K_D * self.error_derivative
        return np.clip(output, 0.0, 1.0)

class PIDLateralController(object):  # pylint: disable=too-few-public-methods
    """
    PIDLateralController implements lateral control using a PID.
    """

    def __init__(self, K_P=1.0, K_D=0.0, K_I=0.0):
        """
        :param vehicle: actor to apply to local planner logic onto
        :param K_P: Proportional term
        :param K_D: Differential term
        :param K_I: Integral term
        """
        self._K_P = K_P
        self._K_D = K_D
        self._K_I = K_I
        self._e_buffer = deque(maxlen=10)
        self.error = 0.0
        self.error_integral = 0.0
        self.error_derivative = 0.0

    def run_step(self, current_pose, waypoint):
        """
        Estimate the steering angle of the vehicle based on the PID equations

        :param waypoint: target waypoint
        :param current_pose: current pose of the vehicle
        :return: steering control in the range [-1, 1]
        """
        v_begin = current_pose.position
        quaternion = (
            current_pose.orientation.w,
            current_pose.orientation.x,
            current_pose.orientation.y,
            current_pose.orientation.z
        )
        _, _, yaw = quat2euler(quaternion)
        v_end = Point()
        v_end.x = v_begin.x + math.cos(yaw)
        v_end.y = v_begin.y + math.sin(yaw)

        v_vec = np.array([v_end.x - v_begin.x, v_end.y - v_begin.y, 0.0])
        w_vec = np.array([waypoint.position.x -
                          v_begin.x, waypoint.position.y -
                          v_begin.y, 0.0])
        _dot = math.acos(np.clip(np.dot(w_vec, v_vec) /
                                 (np.linalg.norm(w_vec) * np.linalg.norm(v_vec)), -1.0, 1.0))

        _cross = np.cross(v_vec, w_vec)
        if _cross[2] < 0:
            _dot *= -1.0

        previous_error = self.error
        self.error = _dot
        # restrict integral term to avoid integral windup
        self.error_integral = np.clip(self.error_integral + self.error, -400.0, 400.0)
        self.error_derivative = self.error - previous_error
        output = self._K_P * self.error + self._K_I * self.error_integral + self._K_D * self.error_derivative
        return np.clip(output, -1.0, 1.0)


import numpy as np
import matplotlib.pyplot as plt

class Agent(object):
    def __init__(self, dim_action):
        self.dim_action = dim_action

    def act(self, ob, reward, done, vision_on):
        #print("ACT!")

        # Get an Observation from the environment.
        # Each observation vectors are numpy array.
        # focus, opponents, track sensors are scaled into [0, 1]. When the agent
        # is out of the road, sensor variables return -1/200.
        # rpm, wheelSpinVel are raw values and then needed to be preprocessed.
        # vision is given as a tensor with size of (64*64, 3) = (4096, 3) <-- rgb
        # and values are in [0, 255]
        return np.tanh(np.random.randn(self.dim_action)) # random action


import numpy as np

"""
After grasping:

Michelle:
 'robot': {'r_elbow_flex_joint': -1.2049406100108246,                                                                                [186/1880]
           'r_elbow_roll_joint': -0.30854121284885244,
           'r_shoulder_lift_joint': -0.8227442822077491,
           'r_shoulder_out_joint': -0.5097213902448162,
           'r_upper_arm_roll_joint': 0.11234468794254258,
           'r_wrist_roll_joint': 0.0,
           'rh_FFJ1': 0.19112734589671157,
           'rh_FFJ2': 1.388799249929034,
           'rh_FFJ3': 0.003442165251199455,
           'rh_FFJ4': -0.0035259846291975944,
           'rh_FFtip': 0.0,
           'rh_LFJ1': -0.11020427473054252,
           'rh_LFJ2': 1.4325098140604107,
           'rh_LFJ3': 0.04057501425890549,
           'rh_LFJ4': -0.002007741764131005,
           'rh_LFJ5': 0.0,
           'rh_LFtip': 0.0,
           'rh_MFJ1': 0.03472788152224856,
           'rh_MFJ2': 1.574700790723572,
           'rh_MFJ3': 0.030281863274343495,
           'rh_MFJ4': -0.009568944786155225,
           'rh_MFtip': 0.0,
           'rh_RFJ1': 0.009409509834145739,
           'rh_RFJ2': 1.5152627328048562,
           'rh_RFJ3': 0.08755566683131254,
           'rh_RFJ4': -0.0015283100797148436,
           'rh_RFtip': 0.0,
           'rh_THJ1': -0.4046026480925077,
           'rh_THJ2': 0.2592501751646194,
           'rh_THJ3': 0.3208369549987318,
           'rh_THJ4': 0.827631726356657,
           'rh_THJ5': 0.43045936368530546,
           'rh_WRJ1': 0.467476456685014,
           'rh_WRJ2': -0.5510767003205203,
           'rh_thtip': 0.0}}
yifeng: 'robot': {'r_elbow_flex_joint': -1.2049416494130385,
           'r_elbow_roll_joint': -0.30854159346220944,
           'r_shoulder_lift_joint': -0.8227438967897664,
           'r_shoulder_out_joint': -0.5097215935509393,
           'r_upper_arm_roll_joint': 0.1123441330825919,
           'r_wrist_roll_joint': 0.0,
           'rh_FFJ1': 0.19112729762755507,
           'rh_FFJ2': 1.3887999081929154,
           'rh_FFJ3': 0.0034414356986804968,
           'rh_FFJ4': -0.003525339050002451,
           'rh_FFtip': 0.0,
           'rh_LFJ1': -0.11020611474644869,
           'rh_LFJ2': 1.4325071401352791,
           'rh_LFJ3': 0.04057628458458566,
           'rh_LFJ4': -0.002008379654513054,
           'rh_LFJ5': 0.0,
           'rh_LFtip': 0.0,
           'rh_MFJ1': 0.034728153870596724,
           'rh_MFJ2': 1.5747008963585811,
           'rh_MFJ3': 0.030281392755867463,
           'rh_MFJ4': -0.009568507732074077,
           'rh_MFtip': 0.0,
           'rh_RFJ1': 0.009407759627669706,
           'rh_RFJ2': 1.5152697543187863,
           'rh_RFJ3': 0.08755263272821893,
           'rh_RFJ4': -0.0015272611474275262,
           'rh_RFtip': 0.0,
           'rh_THJ1': -0.4046037594132872,
           'rh_THJ2': 0.2592511988634577,
           'rh_THJ3': 0.3208373512777064,
           'rh_THJ4': 0.8276316951787813,
           'rh_THJ5': 0.4304590048933569,
           'rh_WRJ1': 0.46747672172321886,
           'rh_WRJ2': -0.5510765722147546,
           'rh_thtip': 0.0}}
"""

michelle = {
    "r_elbow_flex_joint": -1.3085263797057733,
    "r_elbow_roll_joint": -0.7523881476915546,
    "r_shoulder_lift_joint": -0.3390086966342633,
    "r_shoulder_out_joint": -1.1366604356041934,
    "r_upper_arm_roll_joint": -0.7333662570491736,
    "r_wrist_roll_joint": 0.0,
    "rh_FFJ1": 0.6977034971730868,
    "rh_FFJ2": 1.0979716793081826,
    "rh_FFJ3": -0.018796889817201012,
    "rh_FFJ4": 0.13662483906725512,
    "rh_FFtip": 0.0,
    "rh_LFJ1": 0.10206229797231577,
    "rh_LFJ2": 1.4205509969236678,
    "rh_LFJ3": 0.007188950077437274,
    "rh_LFJ4": -0.0020649187308417393,
    "rh_LFJ5": 0.0,
    "rh_LFtip": 0.0,
    "rh_MFJ1": -0.03475695192159361,
    "rh_MFJ2": 1.4381699315790688,
    "rh_MFJ3": 0.036076636088633936,
    "rh_MFJ4": 0.07238161761743608,
    "rh_MFtip": 0.0,
    "rh_RFJ1": 0.011245974706546069,
    "rh_RFJ2": 1.4970791372958066,
    "rh_RFJ3": 0.057731990787547205,
    "rh_RFJ4": -0.017867851142807315,
    "rh_RFtip": 0.0,
    "rh_THJ1": -0.3044896884924795,
    "rh_THJ2": 0.11098978185877213,
    "rh_THJ3": 0.2010491609178426,
    "rh_THJ4": 0.6708828828972982,
    "rh_THJ5": 0.3216859753742132,
    "rh_WRJ1": -0.22497474707423049,
    "rh_WRJ2": -0.5087050750919038,
    "rh_thtip": 0.0,
}

yifeng = {
    "rh_FFJ1": 0.6762856733403299,
    "rh_FFJ2": 1.117126655523232,
    "rh_FFJ3": -0.023652875139505963,
    "rh_FFJ4": 0.13869199410161617,
    "rh_FFtip": 0.0,
    "rh_LFJ1": 0.1175468376393189,
    "rh_LFJ2": 1.3960607252830797,
    "rh_LFJ3": 0.007905054202739957,
    "rh_LFJ4": -0.002026476577690511,
    "rh_LFJ5": 0.0,
    "rh_LFtip": 0.0,
    "rh_MFJ1": -0.027155142294774032,
    "rh_MFJ2": 1.462259251433236,
    "rh_MFJ3": 0.03127574072290409,
    "rh_MFJ4": 0.06663969533444389,
    "rh_MFtip": 0.0,
    "rh_RFJ1": 0.03956068866072623,
    "rh_RFJ2": 1.480662448143781,
    "rh_RFJ3": 0.05395431902173496,
    "rh_RFJ4": -0.01854499338955995,
    "rh_RFtip": 0.0,
    "rh_THJ1": -0.15178532824991867,
    "rh_THJ2": 0.051893801203259815,
    "rh_THJ3": 0.20153903007698573,
    "rh_THJ4": 0.6784681015783798,
    "rh_THJ5": 0.33734043144950554,
    "rh_WRJ1": -0.22328632942906673,
    "rh_WRJ2": -0.5094539977949215,
}

diff_names = []
diffs = []
for k in michelle.keys():
    if k in yifeng:
        diff_names.append(k)
        diff = np.abs(michelle[k] - yifeng[k])
        diffs.append(diff)

idxs = np.argsort(diffs)[::-1]
for i in idxs:
    k = diff_names[i]
    print(k)
    print(diffs[i])
    print(f"michelle: {michelle[k]}")
    print(f"yifeng: {yifeng[k]}")


# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.

from __future__ import division, unicode_literals

import logging
import numpy as np
import itertools

from scipy.spatial import ConvexHull
from pymatgen.analysis.pourbaix.entry import MultiEntry, ion_or_solid_comp_object
from pymatgen.core.periodic_table import Element
from pymatgen.core.composition import Composition
from pymatgen.entries.computed_entries import ComputedEntry
from pymatgen.analysis.reaction_calculator import Reaction, ReactionError
from pymatgen.analysis.phase_diagram import PhaseDiagram

"""
Module containing analysis classes which compute a pourbaix diagram given a
target compound/element.
"""

from six.moves import zip

__author__ = "Sai Jayaraman"
__copyright__ = "Copyright 2012, The Materials Project"
__version__ = "0.0"
__maintainer__ = "Sai Jayaraman"
__credits__ = "Arunima Singh, Joseph Montoya"
__email__ = "sjayaram@mit.edu"
__status__ = "Development"
__date__ = "Nov 1, 2012"

logger = logging.getLogger(__name__)

PREFAC = 0.0591
MU_H2O = -2.4583
elements_HO = {Element('H'), Element('O')}
# TODO: There's a lot of functionality here that diverges
#   based on whether or not the pbx diagram is multielement
#   or not.  Could be a more elegant way to
#   treat the two distinct modes.

class PourbaixDiagram(object):
    """
    Class to create a Pourbaix diagram from entries

    Args:
        entries [Entry]: Entries list containing both Solids and Ions
        comp_dict {str: float}: Dictionary of compositions, defaults to
            equal parts of each elements
        conc_dict {str: float}: Dictionary of ion concentrations, defaults
            to 1e-6 for each element
        filter_multielement (bool): applying this filter to a multi-
            element pourbaix diagram makes generates it a bit more
            efficiently by filtering the entries used to generate
            the hull.  This breaks some of the functionality of
            the analyzer, though, so use with caution.
    """
    def __init__(self, entries, comp_dict=None, conc_dict=None,
                 filter_multielement=False):
        # Get non-OH elements
        pbx_elts = set(itertools.chain.from_iterable(
            [entry.composition.elements for entry in entries]))
        pbx_elts = list(pbx_elts - elements_HO)

        # Set default conc/comp dicts
        if not comp_dict:
            comp_dict = {elt.symbol : 1. / len(pbx_elts) for elt in pbx_elts}
        if not conc_dict:
            conc_dict = {elt.symbol : 1e-6 for elt in pbx_elts}

        self._elt_comp = comp_dict
        self.pourbaix_elements = pbx_elts

        solid_entries = [entry for entry in entries
                         if entry.phase_type == "Solid"]
        ion_entries = [entry for entry in entries
                       if entry.phase_type == "Ion"]

        for entry in ion_entries:
            ion_elts = list(set(entry.composition.elements) - elements_HO)
            if len(ion_elts) != 1:
                raise ValueError("Elemental concentration not compatible "
                                 "with multi-element ions")
            entry.conc = conc_dict[ion_elts[0].symbol]

        if not len(solid_entries + ion_entries) == len(entries):
            raise ValueError("All supplied entries must have a phase type of "
                             "either \"Solid\" or \"Ion\"")

        self._unprocessed_entries = entries

        if len(comp_dict) > 1:
            self._multielement = True
            if filter_multielement:
                # Add two high-energy H/O entries that ensure the hull
                # includes all stable solids.
                entries_HO = [ComputedEntry('H', 10000), ComputedEntry('O', 10000)]
                solid_pd = PhaseDiagram(solid_entries + entries_HO)
                solid_entries = list(set(solid_pd.stable_entries) - set(entries_HO))
            self._processed_entries = self._generate_multielement_entries(
                    solid_entries + ion_entries)
        else:
            self._multielement = False

            self._processed_entries = solid_entries + ion_entries
        self._make_pourbaix_diagram()

    def _create_conv_hull_data(self):
        """
        Make data conducive to convex hull generator.
        """
        entries_to_process = list()
        for entry in self._processed_entries:
            entry.scale(entry.normalization_factor)
            entry.correction += (- MU_H2O * entry.nH2O + entry.conc_term)
            entries_to_process.append(entry)
        self._qhull_entries = entries_to_process
        return self._process_conv_hull_data(entries_to_process)

    def _process_conv_hull_data(self, entries_to_process):
        """
        From a sequence of ion+solid entries, generate the necessary data
        for generation of the convex hull.
        """
        data = []
        for entry in entries_to_process:
            row = [entry.npH, entry.nPhi, entry.g0]
            data.append(row)
        temp = sorted(zip(data, self._qhull_entries),
                      key=lambda x: x[0][2])
        [data, self._qhull_entries] = list(zip(*temp))
        return data

    def _generate_multielement_entries(self, entries):
        """
        Create entries for multi-element Pourbaix construction.

        This works by finding all possible linear combinations
        of entries that can result in the specified composition
        from the initialized comp_dict.

        Args:
            entries ([PourbaixEntries]): list of pourbaix entries
                to process into MultiEntries
        """
        N = len(self._elt_comp)  # No. of elements
        total_comp = Composition(self._elt_comp)

        # generate all possible combinations of compounds that have all elts
        entry_combos = [itertools.combinations(entries, j+1) for j in range(N)]
        entry_combos = itertools.chain.from_iterable(entry_combos)
        entry_combos = filter(lambda x: total_comp < MultiEntry(x).total_composition,
                              entry_combos)

        # Generate and filter entries
        processed_entries = []
        for entry_combo in entry_combos:
            processed_entry = self.process_multientry(entry_combo, total_comp)
            if processed_entry is not None:
                processed_entries.append(processed_entry)

        return processed_entries

    @staticmethod
    def process_multientry(entry_list, prod_comp):
        """
        Static method for finding a multientry based on
        a list of entries and a product composition.
        Essentially checks to see if a valid aqueous
        reaction exists between the entries and the
        product composition and returns a MultiEntry
        with weights according to the coefficients if so.

        Args:
            entry_list ([Entry]): list of entries from which to
                create a MultiEntry
            comp (Composition): composition constraint for setting
                weights of MultiEntry
        """
        dummy_oh = [Composition("H"), Composition("O")]
        try:
            # Get balanced reaction coeffs, ensuring all < 0 or conc thresh
            # Note that we get reduced compositions for solids and non-reduced
            # compositions for ions because ions aren't normalized due to
            # their charge state.
            entry_comps = [e.composition if e.phase_type=='Ion'
                           else e.composition.reduced_composition
                           for e in entry_list]
            rxn = Reaction(entry_comps + dummy_oh, [prod_comp])
            thresh = np.array([pe.conc if pe.phase_type == "Ion"
                               else 1e-3 for pe in entry_list])
            coeffs = -np.array([rxn.get_coeff(comp) for comp in entry_comps])
            if (coeffs > thresh).all():
                weights = coeffs / coeffs[0]
                return MultiEntry(entry_list, weights=weights.tolist())
            else:
                return None
        except ReactionError:
            return None

    def _make_pourbaix_diagram(self):
        """
        Calculates entries on the convex hull in the dual space.
        """
        stable_entries = set()
        self._qhull_data = self._create_conv_hull_data()
        dim = len(self._qhull_data[0])
        if len(self._qhull_data) < dim:
            # TODO: might want to lift this restriction and
            # supply a warning instead, should work even if it's slow.
            raise NotImplementedError("Can only do elements with at-least "
                                      "3 entries for now")
        if len(self._qhull_data) == dim:
            self._facets = [list(range(dim))]
        else:
            facets_hull = np.array(ConvexHull(self._qhull_data).simplices)
            self._facets = np.sort(np.array(facets_hull))
            logger.debug("Final facets are\n{}".format(self._facets))

            logger.debug("Removing vertical facets...")
            vert_facets_removed = list()
            for facet in self._facets:
                facetmatrix = np.zeros((len(facet), len(facet)))
                count = 0
                for vertex in facet:
                    facetmatrix[count] = np.array(self._qhull_data[vertex])
                    facetmatrix[count, dim - 1] = 1
                    count += 1
                if abs(np.linalg.det(facetmatrix)) > 1e-8:
                    vert_facets_removed.append(facet)
                else:
                    logger.debug("Removing vertical facet : {}".format(facet))

            logger.debug("Removing UCH facets by eliminating normal.z >0 ...")

            # Find center of hull
            vertices = set()
            for facet in vert_facets_removed:
                for vertex in facet:
                    vertices.add(vertex)
            c = [0.0, 0.0, 0.0]
            c[0] = np.average([self._qhull_data[vertex][0]
                               for vertex in vertices])
            c[1] = np.average([self._qhull_data[vertex][1]
                               for vertex in vertices])
            c[2] = np.average([self._qhull_data[vertex][2]
                               for vertex in vertices])

            # Shift origin to c
            new_qhull_data = np.array(self._qhull_data)
            for vertex in vertices:
                new_qhull_data[vertex] -= c

            # For each facet, find normal n, find dot product with P, and
            # check if this is -ve
            final_facets = list()
            for facet in vert_facets_removed:
                a = new_qhull_data[facet[1]] - new_qhull_data[facet[0]]
                b = new_qhull_data[facet[2]] - new_qhull_data[facet[0]]
                n = np.cross(a, b)
                val = np.dot(n, new_qhull_data[facet[0]])
                if val < 0:
                    n = -n
                if n[2] <= 0:
                    final_facets.append(facet)
                else:
                    logger.debug("Removing UCH facet : {}".format(facet))
            final_facets = np.array(final_facets)
            self._facets = final_facets

        stable_vertices = set()
        for facet in self._facets:
            for vertex in facet:
                stable_vertices.add(vertex)
                stable_entries.add(self._qhull_entries[vertex])
        self._stable_entries = stable_entries
        self._vertices = stable_vertices

    @property
    def facets(self):
        """
        Facets of the convex hull in the form of  [[1,2,3],[4,5,6]...]
        """
        return self._facets

    @property
    def qhull_data(self):
        """
        Data used in the convex hull operation. This is essentially a matrix of
        composition data and energy per atom values created from qhull_entries.
        """
        return self._qhull_data

    @property
    def qhull_entries(self):
        """
        Return qhull entries
        """
        return self._qhull_entries

    @property
    def stable_entries(self):
        """
        Returns the stable entries in the Pourbaix diagram.
        """
        return list(self._stable_entries)

    @property
    def unstable_entries(self):
        """
        Returns all unstable entries in the Pourbaix diagram
        """
        return [e for e in self.qhull_entries if e not in self.stable_entries]

    @property
    def all_entries(self):
        """
        Return all entries used to generate the pourbaix diagram
        """
        return self._processed_entries

    @property
    def vertices(self):
        """
        Return vertices of the convex hull
        """
        return self._vertices

    @property
    def unprocessed_entries(self):
        """
        Return unprocessed entries
        """
        return self._unprocessed_entries