Skip to content
Snippets Groups Projects
Commit 1d28871c authored by tolgayurt's avatar tolgayurt
Browse files

start to comment the packing_algo.py with docstrings (google)

parent 5de83c9d
Branches
No related tags found
No related merge requests found
...@@ -5,6 +5,12 @@ ...@@ -5,6 +5,12 @@
<orderEntry type="jdk" jdkName="Python 3.6 virtualenv at C:\Users\tolga yurtseven\PycharmProjects\mysite\venv" jdkType="Python SDK" /> <orderEntry type="jdk" jdkName="Python 3.6 virtualenv at C:\Users\tolga yurtseven\PycharmProjects\mysite\venv" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="sourceFolder" forTests="false" />
</component> </component>
<component name="PackageRequirementsSettings">
<option name="requirementsPath" value="" />
</component>
<component name="PyDocumentationSettings">
<option name="myDocStringFormat" value="Google" />
</component>
<component name="TestRunnerService"> <component name="TestRunnerService">
<option name="PROJECT_TEST_RUNNER" value="Unittests" /> <option name="PROJECT_TEST_RUNNER" value="Unittests" />
</component> </component>
......
import sys, path
import copy import copy
import numpy import numpy
import math import math
import random
from collections import defaultdict
import itertools import itertools
# from typing import NewType
# for JupyterLab
# tree datastructure # tree datastructure
from . import avl_tree from . import avl_tree
# shapely/polygon packages # shapely/polygon packages
from shapely.geometry import MultiPolygon, Polygon, LineString, LinearRing, Point from shapely.geometry import Polygon
from shapely.geometry.base import BaseGeometry, geos_geom_from_py
from shapely import affinity from shapely import affinity
# plotting packages # plotting packages
import mpld3
import bokeh
from bokeh.plotting import figure, Figure from bokeh.plotting import figure, Figure
from bokeh.io import output_notebook, show from bokeh.io import output_notebook, show
from bokeh.layouts import gridplot, row, layout, column, Column from bokeh.layouts import gridplot, layout, column, Column
from bokeh.models import Div from bokeh.models import Div
from bokeh.models import Legend from bokeh.models import Legend
from bokeh.models import BoxAnnotation from bokeh.models import BoxAnnotation
from bokeh.models.widgets import Tabs, Panel from bokeh.models.widgets import Tabs, Panel
from bokeh.models import ColumnDataSource, Label, LabelSet, Range1d from bokeh.models import ColumnDataSource, LabelSet
from bokeh.palettes import Dark2_5 as palette from bokeh.palettes import Dark2_5 as palette
from bokeh.plotting import output_file
# for analysing the data
import pandas as pd
# Type aliases for the type hints # Type aliases for the type hints
Point_xy = (float, float) Point_xy = (float, float)
class ConvexPolygon(object): class ConvexPolygon(object):
"""A convex polygon which is represented by its shell, the vertices are clockwise ordered.
Args:
shell ([Point_xy]): a list of (x,y) points
Attributes:
__shell ([Point_xy]): list of clockwise ordered convex (x,y) coordinate points which represents the polygon,
the shells first point and end point are closing the polygon and are the same, the shell
will have at least 3 Points
__area (float): the area of the polygon
__x_values ([float]): x coordinate values
__y_values ([float]): y coordinate values
__min_x (float): min x coordinate value
__max_x (float): max x coordinate value
__min_y (float): min y coordinate value
__max_y (float): max y coordinate value
__height (float): height
__width (float): width
__spine ((Point_xy, Point_xy)): a tuple of the vertices with the smallest and biggest y value. if there are two
vertices which have the same smallest y value or biggest y value the left most vertex and the top right
vertex will build the spine
__vertices_left_visible ([Point_xy]): vertices which can be seen from left
__vertices_right_visible ([Point_xy]): vertices which can be seen from right
__slope (float): the slope of the spine points
plot_fill (bool): a flag which signals that the plot of the polygon should be filled
"""
def __init__(self, shell: [Point_xy]) -> None: def __init__(self, shell: [Point_xy]) -> None:
self.__shell, self.__area = self.convex_hull_and_area(shell) self.__shell, self.__area = self.convex_hull_and_area(shell)
self.__x_values = [vertex[0] for vertex in self.shell] self.__x_values = [vertex[0] for vertex in self.shell]
...@@ -55,6 +67,7 @@ class ConvexPolygon(object): ...@@ -55,6 +67,7 @@ class ConvexPolygon(object):
self.__slope = self.set_slope() self.__slope = self.set_slope()
self.plot_fill = False self.plot_fill = False
# all these @property decorators helps to make the attributes private
@property @property
def area(self): def area(self):
return self.__area return self.__area
...@@ -111,12 +124,20 @@ class ConvexPolygon(object): ...@@ -111,12 +124,20 @@ class ConvexPolygon(object):
def slope(self): def slope(self):
return self.__slope return self.__slope
# @property def convex_hull_and_area(self, shell: [Point_xy]) -> ([Point_xy], float):
# def plot_fill(self): """Builds the convex hull of the input points and creates a convex polygon with his area
# return self.__plot_fill
This function creates a shapely (a python package) polygon to use the shapely convex hull function,
after the convex hull function is used the new convex vertices and the area of the polygon will be returned,
the convex vertices are clockwise ordered and the start and end point are the same,
this way of using the convex hull creates a redundancy and dependency of the shapely package
Args:
shell ([Point_xy]): the input (x,y) coordinates for initialising the convex polygon
def convex_hull_and_area(self, shell: [Point_xy]) -> [Point_xy]: Returns:
# the Polygon points will be ordered clockweise and the start and end point are connected shell, area ([Point_xy], float): a tuple of the convex polygon shell and polygon area
"""
if shell == None: if shell == None:
raise ValueError("a convex polygon can't intialized with None") raise ValueError("a convex polygon can't intialized with None")
elif shell == [] or len(shell) < 3: elif shell == [] or len(shell) < 3:
...@@ -128,12 +149,22 @@ class ConvexPolygon(object): ...@@ -128,12 +149,22 @@ class ConvexPolygon(object):
"couldn't create the convex Polygon, to less points after using the convex hull on the input points") "couldn't create the convex Polygon, to less points after using the convex hull on the input points")
shell = list(convex_polygon.exterior.coords) shell = list(convex_polygon.exterior.coords)
area = convex_polygon.area area = convex_polygon.area
return (shell, area) return shell, area
def translation(self, x: float, y: float) -> None: def translation(self, x: float, y: float) -> None:
"""Translates the polygon with the given input x and y values.
All dependent attributes of the convex polygon will be updated.
Args:
x (float): value to translate the polygon in x coordinate direction
y (float): value to translate the polygon in y coordinate direction
Returns:
None: just the attributes of the polygon will be updated
"""
self.__shell = [(point[0] + x, point[1] + y) for point in self.__shell] self.__shell = [(point[0] + x, point[1] + y) for point in self.__shell]
self.__spine = ( self.__spine = ((self.__spine[0][0]+x, self.__spine[0][1]+y), (self.__spine[1][0]+x, self.__spine[1][1]+y))
(self.__spine[0][0] + x, self.__spine[0][1] + y), (self.__spine[1][0] + x, self.__spine[1][1] + y))
self.__vertices_left_visible = [(point[0] + x, point[1] + y) for point in self.__vertices_left_visible] self.__vertices_left_visible = [(point[0] + x, point[1] + y) for point in self.__vertices_left_visible]
self.__vertices_right_visible = [(point[0] + x, point[1] + y) for point in self.__vertices_right_visible] self.__vertices_right_visible = [(point[0] + x, point[1] + y) for point in self.__vertices_right_visible]
self.__min_x = self.__min_x + x self.__min_x = self.__min_x + x
...@@ -143,39 +174,62 @@ class ConvexPolygon(object): ...@@ -143,39 +174,62 @@ class ConvexPolygon(object):
self.__x_values = [vertex + x for vertex in self.__x_values] self.__x_values = [vertex + x for vertex in self.__x_values]
self.__y_values = [vertex + y for vertex in self.__y_values] self.__y_values = [vertex + y for vertex in self.__y_values]
def set_spine(self) -> (Point_xy, def set_spine(self) -> (Point_xy, Point_xy):
Point_xy): # für den spine spielt es keine Rolle in welche Rolle das Polygon aufgebaut ist ob im Uhrzeigersinn oder dagegen """Builds the spine, which slope will be important to order the polygons later
y_sorted_p_p = sorted(self.__shell, key=lambda k: k[
1]) # Parser schreibt oder davon ausgeht das konvexe Polygone übergeben werden A tuple of the vertices with the smallest and biggest y value. if there are two vertices which have the same
if y_sorted_p_p[0][1] == y_sorted_p_p[1][ smallest y value or biggest y value the left most vertex and the top right vertex will build the spine.
1]: # falls der niedrige Puntk eine wagerechte ist nehme die linke Ecke The spine also splits the polygon in from left_visible_vertices and from right_visible_vertices
Returns:
spine_bottom, spine_top (Point_xy, Point_xy): a tuple a the lowest and highest vertex or bottom left and
top left
"""
y_sorted_p_p = sorted(self.__shell, key=lambda k: k[1]) # ordering the vertices to their y value
if y_sorted_p_p[0][1] == y_sorted_p_p[1][1]: # if there are two lowest vertices take the left one
if y_sorted_p_p[0][0] < y_sorted_p_p[1][0]: if y_sorted_p_p[0][0] < y_sorted_p_p[1][0]:
spine_bottom = y_sorted_p_p[0] spine_bottom = y_sorted_p_p[0]
else: else:
spine_bottom = y_sorted_p_p[1] spine_bottom = y_sorted_p_p[1]
else: else:
spine_bottom = y_sorted_p_p[0] spine_bottom = y_sorted_p_p[0]
if y_sorted_p_p[-2][1] == y_sorted_p_p[-1][ if y_sorted_p_p[-2][1] == y_sorted_p_p[-1][1]: # if there are two highest vertices take right one
1]: # falls der höchste Punkt eine wagerechte ist nehme die rechte Ecke
if y_sorted_p_p[-2][0] < y_sorted_p_p[-1][0]: if y_sorted_p_p[-2][0] < y_sorted_p_p[-1][0]:
spine_top = y_sorted_p_p[-1] spine_top = y_sorted_p_p[-1]
else: else:
spine_top = y_sorted_p_p[-2] spine_top = y_sorted_p_p[-2]
else: else:
spine_top = y_sorted_p_p[-1] spine_top = y_sorted_p_p[-1]
return (spine_bottom, spine_top) return spine_bottom, spine_top
def set_slope(self) -> float: def set_slope(self) -> float:
"""Builds the slope for the spine vertices
The slope will be build with m = y2-y1/x2-x1.
Returns:
slope (float): returns the slope of the spine vertices
"""
spine = self.__spine spine = self.__spine
if spine[0][0] == spine[1][0]: # Sonderfall für eine senkrechte if spine[0][0] == spine[1][0]: # case for a vertical spine
slope = math.inf slope = math.inf
else: else:
slope = (spine[1][1] - spine[0][1]) / (spine[1][0] - spine[0][ slope = (spine[1][1] - spine[0][1]) / (spine[1][0] - spine[0][0])
0]) # m = y2-y1/x2-x1 Formel für die Geradensteigung mithilfe aus zwei verschiedenen Punkten der Geraden
return slope return slope
def plot_polygon(self, title="", plot_width=400, plot_height=300, color="#1F77B4", render=True) -> Figure: def plot_polygon(self, title="", plot_width=400, plot_height=300, color="#1F77B4", render=True) -> Figure:
"""Plotting a Polygon with bokeh""" """Plot object of the polygon
Args:
title (str): the title for the plot
plot_width (int): the width of the plot
plot_height (int): the height of the plot
color (str): the fill_color of the polygon
render (bool): If True the polygon will also be rendered else not
Returns:
fig (Figure): a plot Figure object which can be shown with bokeh command show(fig)
"""
legend_items = [] legend_items = []
height = (int(self.__height * 10)) / 10 height = (int(self.__height * 10)) / 10
if self.__slope == math.inf: if self.__slope == math.inf:
...@@ -211,28 +265,38 @@ class ConvexPolygon(object): ...@@ -211,28 +265,38 @@ class ConvexPolygon(object):
return fig return fig
def splitter(self) -> ([Point_xy], [Point_xy]): def splitter(self) -> ([Point_xy], [Point_xy]):
"""Splits the vertices into vertices_visible from left and vertices_visible from right
This splitting is important for the upcoming packing steps, when the polygons will be filled into high
class containers
Returns:
left, right (([Point_xy], [Point_xy])): a tuple of the list of vertices visible from left and a list of
vertices visible from right
"""
left = [] left = []
right = []
spine_bottom = self.__spine[0] spine_bottom = self.__spine[0]
spine_top = self.__spine[1] spine_top = self.__spine[1]
help_array = self.__shell[:] help_array = self.__shell[:]
if help_array[0] == help_array[-1]: # falls letztes element doppelt if help_array[0] == help_array[-1]: # do not need the duplicated/connecting last vertex of the shell
help_array = help_array[0:-1] help_array = help_array[0:-1]
spine_bottom_found = False spine_bottom_found = False
spine_top_found = False spine_top_found = False
spine_bottom_not_horizontal = False spine_bottom_not_horizontal = False
while spine_bottom_found == False: # Phase 1 der Funktion sie sucht den bottom spine, dabei werden die Ecken die nicht der Spine Bottom sind ans Ende der Liste geschoben # cycling threw the vertices and searching for the spine bottom, which will be the start point
while spine_bottom_found == False:
if help_array[0] == spine_bottom: if help_array[0] == spine_bottom:
if spine_bottom[1] != help_array[-1][ # if the bottom_spine_vertex has a horizontal neighbour, do not take it to the right_visible_vertices
1]: # checkt ob Spine bottom ein horizontalen Nachbar hat falls ja wird ein Flag gesetzt damit Spine bottomt später nicht in die Rechte mitgenommen wird if spine_bottom[1] != help_array[-1][1]:
spine_bottom_not_horizontal = True spine_bottom_not_horizontal = True
spine_bottom_found = True spine_bottom_found = True
left.append(help_array.pop(0)) left.append(help_array.pop(0))
else: else:
help_array.append(help_array.pop(0)) help_array.append(help_array.pop(0))
while spine_top_found == False: # iterieren die Liste erneut durch bis wir spine top finden, falls spine top gefunden wurde wird auch geschaut ob spine top ein horizontalen linken while spine_top_found == False: # searching the spine top
if help_array[0] == spine_top: # Nachbar hat falls ja wird spine top nicht in die Linke Liste miteingefügt if help_array[0] == spine_top:
spine_top_found = True spine_top_found = True
# if the top_spine_vertex has a horizontal neighbour, do not take it to the left_visible_vertices
if spine_top[1] != left[-1][1]: if spine_top[1] != left[-1][1]:
left.append(spine_top) left.append(spine_top)
else: else:
...@@ -240,10 +304,29 @@ class ConvexPolygon(object): ...@@ -240,10 +304,29 @@ class ConvexPolygon(object):
right = help_array.copy() right = help_array.copy()
if spine_bottom_not_horizontal: if spine_bottom_not_horizontal:
right.append(spine_bottom) right.append(spine_bottom)
return (left, right) return left, right
class HighClass(object): class HighClass(object):
"""Holds the polygons which have a height between the HighClass self.min_border < polygon.height <= self.max_border
Args:
i (int): represent the HighClass index
alpha (float): value which builds the HighClass borders
h_max_polygon (float): max height from all polygons to pack (not only from this HighClass)
w_max_polygon (float): max width from all polygons to pack (not only from this HighClass)
Attributes:
i (int): represent the HighClass index
alpha (float): value which builds the HighClass borders
h_max_polygon (float): max height from all polygons to pack (not only from this HighClass)
w_max_polygon (float): max width from all polygons to pack (not only from this HighClass)
min_border (float): min border of the HighClass, only Polygons with height bigger will join this HighClass
max_border (float): max border of the HighClass, only Polygons with height smaller or equal will join this
HighClass
polygons ([ConvexPolygon]): Convex Polygons which fulfill the min_border and max_border condition
spine_ordered_polygons ([ConvexPolygon): the self.polygons ordered by their spines in ascending order
"""
def __init__(self, i: int, alpha: float, h_max_polygon: float, w_max_polygon: float) -> None: def __init__(self, i: int, alpha: float, h_max_polygon: float, w_max_polygon: float) -> None:
self.i = i self.i = i
self.alpha = alpha self.alpha = alpha
...@@ -255,11 +338,29 @@ class HighClass(object): ...@@ -255,11 +338,29 @@ class HighClass(object):
self.spine_ordered_polygons = [] self.spine_ordered_polygons = []
def set_polygons(self, polygons: [ConvexPolygon]) -> None: def set_polygons(self, polygons: [ConvexPolygon]) -> None:
"""Set the polygons and the spine_ordered_polygons which fulfill the HighClass border conditions
This function will be triggered by the function which creates the HighClass objects.
Args:
polygons ([ConvexPolygon): these convex polygons fulfill the HighClass border conditions
"""
self.polygons = polygons self.polygons = polygons
spine_ordered_polygons = sorted(self.polygons, key=lambda polygon: polygon.slope) spine_ordered_polygons = sorted(self.polygons, key=lambda polygon: polygon.slope)
self.spine_ordered_polygons = spine_ordered_polygons self.spine_ordered_polygons = spine_ordered_polygons
def plot_hc(self, ordered=False, render=True, plot_width=300, plot_height=300) -> Column: def plot_hc(self, ordered=False, render=True, plot_width=300, plot_height=300) -> Column:
"""Plot object of the polygons of the HighClass with ordered or unordered spines
Args:
ordered (bool): if True -> polygons will be spine ordered else not ordered polygons
render (bool): if True -> the plot will be rendered else not
plot_width (int): width of the plot figure
plot_height (int): height of the plot figure
Returns:
grid_layout (Colums): plot object which can be rendered with show(grid_layout)
"""
plots = [] plots = []
if ordered: if ordered:
polygon_list = self.spine_ordered_polygons polygon_list = self.spine_ordered_polygons
...@@ -278,8 +379,22 @@ class HighClass(object): ...@@ -278,8 +379,22 @@ class HighClass(object):
class Container(object): class Container(object):
"""Container which holds the packed polygons from one HighClass
Attributes:
hc (HighClass): reference to HighClass object
Args:
hc (HighClass): reference to HighClass object
y_boundary (float): y coordinate boundary for the container
x_boundary (float): x coordinate boundary fot the container
Tree (Tree): avl-tree data structure
root (TreeNode): the root of the avl-tree datastructure
sigma ([ConvexPolygon]): the list of packed convex polygons from the HighClass
plot_steps ([Figure]): list of steps which are done to pack the container as plot objects
"""
def __init__(self, hc: HighClass) -> None: def __init__(self, hc: HighClass) -> None:
self.hc = hc # am ende nur zuweiseung ohne copy self.hc = hc
self.y_boundary = self.hc.max_border self.y_boundary = self.hc.max_border
self.x_boundary = 0 self.x_boundary = 0
self.Tree = avl_tree.AVLTree() self.Tree = avl_tree.AVLTree()
...@@ -287,21 +402,26 @@ class Container(object): ...@@ -287,21 +402,26 @@ class Container(object):
self.sigma, self.plot_steps = self.packing_container(self.hc.spine_ordered_polygons) self.sigma, self.plot_steps = self.packing_container(self.hc.spine_ordered_polygons)
def distance(self, edge_points: (Point_xy, Point_xy), point: Point_xy) -> float: def distance(self, edge_points: (Point_xy, Point_xy), point: Point_xy) -> float:
# y = m*x+n """Calculates the shortest distance between an edge and a point
# (y-n)/m=x
# n = y-m*x Args:
edge_points ((Point_xy, Point_xy)): edge of a polygon
point (): vertex from there the shortest distance to the edge will be calculated
Returns:
distance (float): the shortest distance betwee the vertex and edge
"""
edge_p1 = edge_points[0] edge_p1 = edge_points[0]
edge_p2 = edge_points[1] edge_p2 = edge_points[1]
if edge_p1[0] == edge_p2[0]: # Sonderfall für eine senkrechte if edge_p1[0] == edge_p2[0]: # if edge is a vertical
distance = math.sqrt((edge_p1[0] - point[ distance = math.sqrt((edge_p1[0] - point[0]) ** 2)
0]) ** 2) # da der edge_points eine senkrechte ist -> der eintreffpunkt hat den gleichen y wert wie der punkt, in der Abstand formel fällt dieser wert weg elif edge_p1[1] == point[1]: # if the first edge vertex and the vertex have the same y value
elif edge_p1[1] == point[1]:
distance = math.sqrt((edge_p1[0] - point[0]) ** 2 + (edge_p1[1] - point[1]) ** 2) distance = math.sqrt((edge_p1[0] - point[0]) ** 2 + (edge_p1[1] - point[1]) ** 2)
else: else:
slope = (edge_p2[1] - edge_p1[1]) / (edge_p2[0] - edge_p1[ slope = (edge_p2[1] - edge_p1[1]) / (edge_p2[0] - edge_p1[0]) # m = y2-y1/x2-x1
0]) # m = y2-y1/x2-x1 Formel für die Geradensteigung mithilfe aus zwei verschiedenen Punkten der Geraden # y = m*x+n used the Equation of a straight line and transformed it to get the missing parameters
n = edge_p1[1] - (slope * edge_p1[0]) n = edge_p1[1] - (slope * edge_p1[0]) # n = y - (m*x)
intersection_point_x = (point[1] - n) / slope # x=(y-n)/m intersection_point_x = (point[1] - n) / slope # x = (y-n)/m
intersection_point = (intersection_point_x, point[1]) intersection_point = (intersection_point_x, point[1])
distance = math.sqrt((intersection_point[0] - point[0]) ** 2 + (intersection_point[1] - point[1]) ** 2) distance = math.sqrt((intersection_point[0] - point[0]) ** 2 + (intersection_point[1] - point[1]) ** 2)
return distance return distance
......
# import math
# from django.shortcuts import render
# from plotly.offline import plot
# import plots.polygon as poly
# from django.http import JsonResponse
# from plotly.graph_objs import Scatter
# import plotly.graph_objects as go
# from django.http import HttpResponse
# import pdb; pdb.set_trace
# from plotly.subplots import make_subplots
# import math
#
# def polygon_plot(polygons):
# plot_polygon_list = []
#
# polygon_count = len(polygons)
# cols = 4
# rows = math.ceil(polygon_count / cols)
# number = 0
# sub_plot_titles = ['{} height:{} slope:{}'.format(number,
# (int(polygons[number].height * 10)) / 10,
# (int(polygons[number].slope * 10)) / 10)
# for number in range(0, polygon_count)]
#
# fig = make_subplots(rows=rows, cols=cols, subplot_titles=sub_plot_titles)
# fig.update_layout(title="Convex Polygons")
# counter = 0
# for polygon in polygons:
# x_data = polygon.x_values
# y_data = polygon.y_values
# scatter = go.Scatter(x=x_data, y=y_data,
# mode='lines', name='{}'.format(counter),
# opacity=0.8, marker_color='green')
#
# spine_x_values = [x[0] for x in polygon.spine]
# spine_y_values = [x[1] for x in polygon.spine]
# scatter_spine = go.Scatter(x=spine_x_values, y=spine_y_values,
# mode='lines', name='{} Spine'.format(counter),
# opacity=0.8, marker_color='red')
# row = math.ceil((counter + 1) / cols)
# col = (counter % cols) + 1
# fig.add_trace(scatter, row=row, col=col)
# fig.add_trace(scatter_spine, row=row, col=col)
# counter += 1
# plot_polygons_div = plot(fig, output_type='div')
# return plot_polygons_div
#
# def high_class_plot(high_classes):
# plot_high_class_list = []
# polygon_number = 0
# polygon_title_number = 0
# for hc in high_classes:
# polygon_count = len(hc.polygons)
# cols = 4
# rows = math.ceil(polygon_count / cols)
#
# # sub_plot_titles = ['{} height:{} slope:{}'.format(number,
# # (int(hc.spine_ordered_polygons[number].height * 10)) / 10,
# # (int(hc.spine_ordered_polygons[number].slope * 10)) / 10)
# # for number in range(0, polygon_count)]
# sub_plot_titles=[]
# for polygon in hc.spine_ordered_polygons:
#
# sub_plot_titles.append('{} height:{} slope:{}'.format(polygon_title_number, (int(polygon.height*10))/10,(int(polygon.slope * 10)) / 10))
# polygon_title_number += 1
# fig = make_subplots(rows=rows, cols=cols, subplot_titles=sub_plot_titles)
# fig.update_layout(title="Highclass {} heights: {}-{}".format(hc.i, int(hc.min_border), int(hc.max_border)))
# counter = 0
#
# for polygon in hc.spine_ordered_polygons:
# x_data = polygon.x_values
# y_data = polygon.y_values
# scatter = go.Scatter(x=x_data, y=y_data,
# mode='lines', name='{}'.format(polygon_number),
# opacity=0.8, marker_color='green')
#
# spine_x_values = [x[0] for x in polygon.spine]
# spine_y_values = [x[1] for x in polygon.spine]
# scatter_spine = go.Scatter(x=spine_x_values, y=spine_y_values,
# mode='lines', name='{} Spine'.format(polygon_number),
# opacity=0.8, marker_color='red')
# row = math.ceil((counter + 1) / cols)
# col = (counter % cols) + 1
# fig.add_trace(scatter, row=row, col=col)
# fig.add_trace(scatter_spine, row=row, col=col)
# counter += 1
# polygon_number += 1
# plt_div = plot(fig, output_type='div')
# plot_high_class_list.append(plt_div)
# return plot_high_class_list
#
#
from django.shortcuts import render
# Create your views here.
import json
from django.shortcuts import render
from django.views import View
from django.http import HttpResponseRedirect
import plots.packing_algo as poly
from bokeh.embed import file_html
from bokeh.models import BoxZoomTool
from django.views.generic import TemplateView
import matplotlib
from django.http import JsonResponse
from django.http import HttpResponse
import pdb;pdb.set_trace
import matplotlib.pyplot as plt
import mpld3
import math
from plots import plot_helpers
from bokeh.plotting import figure, output_file, show
from bokeh.resources import CDN
from bokeh.models.widgets import Panel, Tabs
from bokeh.layouts import layout
from bokeh.models.widgets import Tabs, Panel
from bokeh.io import curdoc
from bokeh.plotting import figure
from bokeh.layouts import column
from bokeh.models import CustomJS, ColumnDataSource
from bokeh.plotting import Figure
from bokeh.models import ColumnDataSource, CustomJS, Slider
from bokeh.embed import components
from bokeh.embed import json_item
from bokeh.events import ButtonClick
import numpy as np
from bokeh.models import PolyDrawTool, PolyEditTool
from bokeh.models.callbacks import CustomJS
from bokeh.embed import json_item
import json
import pandas
def index(request):
convex_polygons = poly.create_multiple_convex_polygons(10,9)
cc = poly.ConvexContainer(convex_polygons)
plot_steps = cc.plot_steps(render=False)
plot_steps_html = file_html(plot_steps, CDN, "my plot2")
return render(request, 'plots/packed_polygons.html', context={"plot_steps":plot_steps_html})
# 'high_classes': plot_high_class_list,})
# 'hc_container': hc_container})
class PackingRectContainer(View):
def get(self, request, *args, **kwargs):
cc = poly.pack_polygons( PolygonEditView.polygons)
plot_steps = cc.plot_steps(render=False)
plot_steps_html = file_html(plot_steps, CDN, "my plot23")
#PackingPolygons.context["packed_polygons"]=plot_steps_html
return render(request, 'plots/packed_polygons.html', context={"plot_steps": plot_steps_html})
class PackingRotatedRectContainer(View):
def get(self, request, *args, **kwargs):
cc = poly.ConvexContainer(PolygonEditView.polygons,steps=90)
plot_steps = cc.plot_steps(render=False)
plot_steps_html = file_html(plot_steps, CDN, "my plot23")
# PackingPolygons.context["packed_polygons"]=plot_steps_html
return render(request, 'plots/packed_polygons.html', context={"plot_steps": plot_steps_html})
class CSVPolygons(View):
def get(self,request,):
PolygonEditView.csv_polygons = []
PolygonEditView.polygons = PolygonEditView.drawn_polygons
PolygonEditView.context["csv_polygons"] = "Cleared"
if len(PolygonEditView.polygons) != 0:
polygons_single_plot = poly.plot_polygons_in_single_plot(PolygonEditView.drawn_polygons, plot_height=850, plot_width=2000,
render=False)
polygons_single_plot_html = file_html(polygons_single_plot, CDN, "single plot")
else:
polygons_single_plot_html = "No Polygons"
PolygonEditView.context["polygons_single_plot"] = polygons_single_plot_html
return HttpResponseRedirect('/test/')
def post(self, request, *args, **kwargs):
df = pandas.read_csv('plots/polygon.txt',sep="#")
csv_polygons =[]
for csv_polygon in df["Polygon"]:
polygon_shell = eval(csv_polygon)
polygon = poly.ConvexPolygon(polygon_shell)
csv_polygons.append(polygon)
plot_csv = poly.plot_polygons(csv_polygons, render=False)
PolygonEditView.csv_polygons = csv_polygons
PolygonEditView.polygons = PolygonEditView.drawn_polygons+csv_polygons
polygons_single_plot = poly.plot_polygons_in_single_plot(PolygonEditView.polygons, plot_height=850, plot_width=2000,
render=False)
polygons_csv_plot_html = file_html(plot_csv, CDN, "my plot")
polygons_single_plot_html = file_html(polygons_single_plot, CDN, "single plot")
PolygonEditView.context["csv_polygons"] = polygons_csv_plot_html
PolygonEditView.context["polygons_single_plot"] = polygons_single_plot_html
x_values=[]
y_values=[]
# for polygon in csv_polygons:
# PolygonEditView.colum_data_x.append(polygon.x_values)
# PolygonEditView.colum_data_y.append(polygon.y_values)
#PolygonEditView.colum_data_x,
#y = PolygonEditView.colum_data_y
return HttpResponseRedirect('/test/')
class PackingConvexContainer(View):
# context = {}
def get(self, request, *args, **kwargs):
cc = poly.ConvexContainer(PolygonEditView.polygons, steps=1)
plot_steps = cc.plot_steps(render=False)
plot_steps_html = file_html(plot_steps, CDN, "my plot23")
# PackingPolygons.context["packed_polygons"]=plot_steps_html
return render(request, 'plots/packed_polygons.html', context={"plot_steps": plot_steps_html})
def post(self, request, *args, **kwargs):
angle = int(request.POST["angle"])
cc = poly.ConvexContainer(PolygonEditView.polygons, steps=angle)
plot_steps = cc.plot_steps(render=False)
plot_steps_html = file_html(plot_steps, CDN, "my plot23")
return render(request, 'plots/packed_polygons.html', context={"plot_steps": plot_steps_html})
class PolygonEditView(View):
context = {}
polygons = []
drawn_polygons=[]
csv_polygons = []
#all_polygons=[]
plot_min_x = 0
plot_max_x = 100
plot_min_y = 0
plot_max_y = 100
colum_data_x =[] # wil be a list of lists
colum_data_y =[]
def get(self, request, *args, **kwargs):
TOOLTIPS = [("index", "$index"), ("(x,y)", "($x{1.1}, $y{1.1})"), ]
source = ColumnDataSource(data=dict(x=PolygonEditView.colum_data_x,
y=PolygonEditView.colum_data_y),
name='my-data-source')
p = figure(x_range=(PolygonEditView.plot_min_x, PolygonEditView.plot_max_x), y_range=(PolygonEditView.plot_min_y, PolygonEditView.plot_max_y), width=1000, height=1000,
title='Poly Edit Tool', tooltips=TOOLTIPS)
p.aspect_ratio = 1
p1 = p.patches("x", "y", fill_alpha=0.4, source=source, fill_color="red")
c1 = p.circle([], [], size=10, color='red', )
draw_tool = PolyDrawTool(renderers=[p1])
edit_tool = PolyEditTool(renderers=[p1], vertex_renderer=c1)
p.add_tools(draw_tool, edit_tool)
p.toolbar.active_drag = draw_tool
response = file_html(p, CDN, "my plot")
PolygonEditView.context["response"] = response
return render(request, 'plots/test.html', PolygonEditView.context)
def post(self, request, *args, **kwargs):
# df = pandas.read_csv('plots/polygon.txt', sep="+")
# csv_polygons =[]
# for csv_polygon in df["Polygon"]:
# polygon_shell = eval(csv_polygon)
# polygon = poly.ConvexPolygon(polygon_shell)
# csv_polygons.append(polygon)
# print(csv_polygons)
test = request.POST["your_name"]
dict_poly = json.loads(test)
print(dict_poly["x"])
print(dict_poly["y"])
PolygonEditView.colum_data_x.clear()
PolygonEditView.colum_data_y.clear()
for poly_x in dict_poly["x"]:
PolygonEditView.colum_data_x.append(poly_x)
for poly_y in dict_poly["y"]:
PolygonEditView.colum_data_y.append(poly_y)
polygon_list=[]
polygons_x_y_tuple = list(zip(dict_poly["x"], dict_poly["y"]))
# polygon_x_list = []
# polygon_y_list = []
for x,y in polygons_x_y_tuple:
polygon_list.append(list(zip(x,y)))
# for x,y in polygons_x_y_tuple:
# polygon_x_list.append(x)
# polygon_y_list.append(y)
print(polygon_list)
drawn_polygons=[]
polygon_max_x_list=[]
polygon_min_x_list = []
polygon_min_y_list = []
polygon_max_y_list=[]
for polygon in polygon_list:
if len(polygon)<3:
continue
if polygon[0]!= polygon[-1]:
polygon.append(polygon[0])
polygon2 = poly.ConvexPolygon(polygon)
print("konkav",list(polygon2.shell))
#polygon_parent_class = polygon2.convex_hull
#polygon2 = poly.Polygon2(list(polygon_parent_class.exterior.coords))
polygon_max_x_list.append(polygon2.max_x)
polygon_min_x_list.append(polygon2.min_x)
polygon_max_y_list.append(polygon2.max_y)
polygon_min_y_list.append(polygon2.min_y)
drawn_polygons.append(polygon2)
PolygonEditView.drawn_polygons = drawn_polygons
all_polygons = drawn_polygons + self.csv_polygons
PolygonEditView.polygons = all_polygons
PolygonEditView.plot_max_y = max(polygon_max_y_list)
PolygonEditView.plot_min_y = min(polygon_min_y_list)
PolygonEditView.plot_max_x = max(polygon_max_x_list)
PolygonEditView.plot_min_x = min(polygon_min_x_list)
polygons_single_plot = poly.plot_polygons_in_single_plot(all_polygons,plot_height=850, plot_width=2000,render=False)
plot_drawn = poly.plot_polygons(drawn_polygons,render=False)
#plot_csv = poly.plot_polygons(csv_polygons, render=False)
# print(type(test))
# p = figure()
# p.multi_line("x", "y", source=source)
polygons_dawn_plot_html = file_html(plot_drawn, CDN, "my plot")
#polygons_csv_plot_html = file_html(plot_csv, CDN, "my plot")
polygons_single_plot_html = file_html(polygons_single_plot, CDN, "single plot")
#self.polygons.append(response2)
PolygonEditView.context["drawn_polygons"] = polygons_dawn_plot_html
#PolygonEditView.context["csv_polygons"] = polygons_csv_plot_html
PolygonEditView.context["polygons_single_plot"] = polygons_single_plot_html
return HttpResponseRedirect('/test/')
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment