# Path: pyroSAR/S1/polysimplify.py
# class VWSimplifier(object):
#     def __init__(self, pts):
#         """
#         Initialize with points. takes some time to build
#         the thresholds but then all threshold filtering later
#         is ultra fast
#         """
#         self.pts = np.array(pts)
#         self.thresholds = self.build_thresholds()
#         self.ordered_thresholds = sorted(self.thresholds, reverse=True)
# 
#     def build_thresholds(self):
#         """
#         compute the area value of each vertex, which one would
#         use to mask an array of points for any threshold value.
#         returns a numpy.array (length of pts)  of the areas.
#         """
#         pts = self.pts
#         nmax = len(pts)
#         real_areas = triangle_areas_from_array(pts)
#         real_indices = list(range(nmax))
# 
#         # destructable copies
#         # ARG! areas=real_areas[:] doesn't make a copy!
#         areas = np.copy(real_areas)
#         i = real_indices[:]
# 
#         # pick first point and set up for loop
#         min_vert = int(argmin(areas))
#         this_area = areas[min_vert]
#         #  areas and i are modified for each point finished
#         remove(areas, min_vert)  # faster
#         # areas = np.delete(areas,min_vert) #slower
#         real_idx = i.pop(min_vert)
# 
#         # cntr = 3
#         while this_area < np.inf:
#             '''min_vert was removed from areas and i.  Now,
#             adjust the adjacent areas and remove the new
#             min_vert.
#             Now that min_vert was filtered out, min_vert points
#             to the point after the deleted point.'''
# 
#             skip = False  # modified area may be the next minvert
# 
#             try:
#                 right_area = triangle_area(pts[i[min_vert - 1]],
#                                            pts[i[min_vert]], pts[i[min_vert + 1]])
#             except IndexError:
#                 # trying to update area of endpoint. Don't do it
#                 pass
#             else:
#                 right_idx = i[min_vert]
#                 if right_area <= this_area:
#                     # even if the point now has a smaller area,
#                     # it ultimately is not more significant than
#                     # the last point, which needs to be removed
#                     # first to justify removing this point.
#                     # Though this point is the next most significant
#                     right_area = this_area
# 
#                     # min_vert refers to the point to the right of
#                     # the previous min_vert, so we can leave it
#                     # unchanged if it is still the min_vert
#                     skip = min_vert
# 
#                 # update both collections of areas
#                 real_areas[right_idx] = right_area
#                 areas[min_vert] = right_area
# 
#             if min_vert > 1:
#                 # cant try/except because 0-1=-1 is a valid index
#                 left_area = triangle_area(pts[i[min_vert - 2]],
#                                           pts[i[min_vert - 1]], pts[i[min_vert]])
#                 if left_area <= this_area:
#                     # same justification as above
#                     left_area = this_area
#                     skip = min_vert - 1
#                 real_areas[i[min_vert - 1]] = left_area
#                 areas[min_vert - 1] = left_area
# 
#             # only argmin if we have too.
#             min_vert = skip or argmin(areas)
#             real_idx = i.pop(min_vert)
#             this_area = areas[min_vert]
#             # areas = np.delete(areas,min_vert) #slower
#             remove(areas, min_vert)  # faster
#             '''if sum(np.where(areas==np.inf)[0]) != sum(list(reversed(range(len(areas))))[:cntr]):
#               print "broke:",np.where(areas==np.inf)[0],cntr
#               break
#             cntr+=1
#             #if real_areas[0]<np.inf or real_areas[-1]<np.inf:
#             #  print "NO!", real_areas[0], real_areas[-1]
#             '''
#         return real_areas
# 
#     def from_threshold(self, threshold):
#         return self.pts[self.thresholds >= threshold]
# 
#     def from_number(self, n):
#         thresholds = self.ordered_thresholds
#         try:
#             threshold = thresholds[int(n)]
#         except IndexError:
#             return self.pts
#         return self.pts[self.thresholds > threshold]
# 
#     def from_ratio(self, r):
#         if r <= 0 or r > 1:
#             raise ValueError("Ratio must be 0<r<=1")
#         else:
#             return self.from_number(r * len(self.thresholds))


from osgeo import ogr
from spatialist.ancillary import rescale
from .polysimplify import VWSimplifier
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
###############################################################################
# Utilities for simplification of lines used by pyroSAR for border noise removal

# Copyright (c) 2017-2020, the pyroSAR Developers.

# This file is part of the pyroSAR Project. It is subject to the
# license terms in the LICENSE.txt file found in the top-level
# directory of this distribution and at
# https://github.com/johntruckenbrodt/pyroSAR/blob/master/LICENSE.txt.
# No part of the pyroSAR project, including this file, may be
# copied, modified, propagated, or distributed except according
# to the terms contained in the LICENSE.txt file.
###############################################################################



matplotlib.rcParams['font.size'] = 12


def simplify(x, y, maxpoints=20):
    x = list(map(float, x))
    y = list(map(float, y))
    pts = np.array(list(zip(x, y)))
    simplifier = VWSimplifier(pts)
    sqd = []

# Path: pyroSAR/S1/polysimplify.py
# class VWSimplifier(object):
#     def __init__(self, pts):
#         """
#         Initialize with points. takes some time to build
#         the thresholds but then all threshold filtering later
#         is ultra fast
#         """
#         self.pts = np.array(pts)
#         self.thresholds = self.build_thresholds()
#         self.ordered_thresholds = sorted(self.thresholds, reverse=True)
# 
#     def build_thresholds(self):
#         """
#         compute the area value of each vertex, which one would
#         use to mask an array of points for any threshold value.
#         returns a numpy.array (length of pts)  of the areas.
#         """
#         pts = self.pts
#         nmax = len(pts)
#         real_areas = triangle_areas_from_array(pts)
#         real_indices = list(range(nmax))
# 
#         # destructable copies
#         # ARG! areas=real_areas[:] doesn't make a copy!
#         areas = np.copy(real_areas)
#         i = real_indices[:]
# 
#         # pick first point and set up for loop
#         min_vert = int(argmin(areas))
#         this_area = areas[min_vert]
#         #  areas and i are modified for each point finished
#         remove(areas, min_vert)  # faster
#         # areas = np.delete(areas,min_vert) #slower
#         real_idx = i.pop(min_vert)
# 
#         # cntr = 3
#         while this_area < np.inf:
#             '''min_vert was removed from areas and i.  Now,
#             adjust the adjacent areas and remove the new
#             min_vert.
#             Now that min_vert was filtered out, min_vert points
#             to the point after the deleted point.'''
# 
#             skip = False  # modified area may be the next minvert
# 
#             try:
#                 right_area = triangle_area(pts[i[min_vert - 1]],
#                                            pts[i[min_vert]], pts[i[min_vert + 1]])
#             except IndexError:
#                 # trying to update area of endpoint. Don't do it
#                 pass
#             else:
#                 right_idx = i[min_vert]
#                 if right_area <= this_area:
#                     # even if the point now has a smaller area,
#                     # it ultimately is not more significant than
#                     # the last point, which needs to be removed
#                     # first to justify removing this point.
#                     # Though this point is the next most significant
#                     right_area = this_area
# 
#                     # min_vert refers to the point to the right of
#                     # the previous min_vert, so we can leave it
#                     # unchanged if it is still the min_vert
#                     skip = min_vert
# 
#                 # update both collections of areas
#                 real_areas[right_idx] = right_area
#                 areas[min_vert] = right_area
# 
#             if min_vert > 1:
#                 # cant try/except because 0-1=-1 is a valid index
#                 left_area = triangle_area(pts[i[min_vert - 2]],
#                                           pts[i[min_vert - 1]], pts[i[min_vert]])
#                 if left_area <= this_area:
#                     # same justification as above
#                     left_area = this_area
#                     skip = min_vert - 1
#                 real_areas[i[min_vert - 1]] = left_area
#                 areas[min_vert - 1] = left_area
# 
#             # only argmin if we have too.
#             min_vert = skip or argmin(areas)
#             real_idx = i.pop(min_vert)
#             this_area = areas[min_vert]
#             # areas = np.delete(areas,min_vert) #slower
#             remove(areas, min_vert)  # faster
#             '''if sum(np.where(areas==np.inf)[0]) != sum(list(reversed(range(len(areas))))[:cntr]):
#               print "broke:",np.where(areas==np.inf)[0],cntr
#               break
#             cntr+=1
#             #if real_areas[0]<np.inf or real_areas[-1]<np.inf:
#             #  print "NO!", real_areas[0], real_areas[-1]
#             '''
#         return real_areas
# 
#     def from_threshold(self, threshold):
#         return self.pts[self.thresholds >= threshold]
# 
#     def from_number(self, n):
#         thresholds = self.ordered_thresholds
#         try:
#             threshold = thresholds[int(n)]
#         except IndexError:
#             return self.pts
#         return self.pts[self.thresholds > threshold]
# 
#     def from_ratio(self, r):
#         if r <= 0 or r > 1:
#             raise ValueError("Ratio must be 0<r<=1")
#         else:
#             return self.from_number(r * len(self.thresholds))


# Path: pyroSAR/S1/linesimplify.py
from osgeo import ogr
from spatialist.ancillary import rescale
from .polysimplify import VWSimplifier
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
import numpy as np
import matplotlib
import matplotlib.pyplot as plt

###############################################################################
# Utilities for simplification of lines used by pyroSAR for border noise removal

# Copyright (c) 2017-2020, the pyroSAR Developers.

# This file is part of the pyroSAR Project. It is subject to the
# license terms in the LICENSE.txt file found in the top-level
# directory of this distribution and at
# https://github.com/johntruckenbrodt/pyroSAR/blob/master/LICENSE.txt.
# No part of the pyroSAR project, including this file, may be
# copied, modified, propagated, or distributed except according
# to the terms contained in the LICENSE.txt file.
###############################################################################



matplotlib.rcParams['font.size'] = 12


def simplify(x, y, maxpoints=20):
    x = list(map(float, x))
    y = list(map(float, y))
    pts = np.array(list(zip(x, y)))
    simplifier = VWSimplifier(pts)
    sqd = []

    iter_range = range(2, maxpoints + 1)