-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsquare_cli.py
More file actions
273 lines (214 loc) · 8.07 KB
/
Copy pathsquare_cli.py
File metadata and controls
273 lines (214 loc) · 8.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#----------------
# Created By : bmetenko
# Start Date : 22May2022
# Project URL: https://github.com/bmetenko/SquarePacking
# ---------------
"""
CLI interface for squares.py
specified classes and visualizations.
"""
from argparse import ArgumentError, ArgumentParser
from typing import List, Dict
import numpy as np
import pandas as pd
import PIL
import PIL.Image
from squares import Rect, Square, SquareCanvas
parser = ArgumentParser()
parser.add_argument(
"-s", "--square_list", dest="square_list",
help="Specify square radius list to populate."
)
parser.add_argument(
"-r", "--rect_list", dest="rect_list",
help="Specify rectangles ( ex. '[1x3]*3, [4x3]*2' ) list to populate."
)
parser.add_argument(
"-f", "--fill_canvas_size", dest='canvas_size',
help="Specify canvas size to fill supllied square_list with."
)
parser.add_argument(
"-a", "--array_display", default="True",
help="Show numpy array structure after computation completes."
)
parser.add_argument(
"-p", "--plot_display", default="browser",
help="Display plotly plot in browser. Overrides array display."
)
parser.add_argument(
"-i0", "--input_image_zero", dest='image_zero', default=None,
help="Input based on image parsing, where pure white is a placable 'tile', " +
"and any other color is blocked. Overrides canvas_size."
)
parser.add_argument(
"-ia", "--input_image_average", dest="image_average", default=None,
help="Input based on image parsing, " +
"images averaged into 0s and 1s and used to fill 'tiles'. " +
"Overrides canvas_size, and input_image_zero"
)
parser.add_argument(
"-ir", "--image_rotate", dest="image_rotate", default=0,
help="Rotates provided image by specified degrees, if present, before population."
)
parser.add_argument(
"-o", "--output_file", default=None,
help="Send output to specified filepath." +
"Image type inferred by extension type." +
"Overrides array display and plot display."
)
parser.add_argument(
"-ar", "--autopopulate_rectangles_max_side",
dest="rect_max_side",
default=None,
help="Specify autopopulation of remaining canvas " +
"with rectangles starting with maximum sides supplied. " +
"Overrides square population using -as argument."
)
parser.add_argument(
"-as", "--autopopulate_squares_max_side", dest="square_max_side", default=None,
help="Specify autopopulation of remaining canvas " +
"with squares starting with maximum sides supplied. "
)
parser.add_argument(
"-ic", "--input_csv", dest="input_csv", default=None,
help="Specify csv to use with length, and width columns. " +
"Others will be treated as extra payload."
)
parser.add_argument(
"-oc", "--output_csv", dest="output_csv", default=None,
help="Specify csv to populate with the specified information about plot."
)
parser.add_argument(
"-ox", "--output_xlsx", dest='output_xlsx', default=None,
help="Specify xlsx to populate with the specified information about plot."
)
def count_expand(
expand_dict: List[Dict[str, int]]
) -> List[Dict[str, int]]:
out_list = []
for element in expand_dict:
for _ in list(range(0, element['count'])):
out_list.append({
"length": element['length'],
"width": element['width']}
)
return out_list
#region Boolean Options
parser.add_argument(
"-dp", "--display_points",
dest="display_points",
action='store_true',
help="Toggle display of center point values in ouput."
)
parser.add_argument(
"-dpp", "--display_path_points",
dest="display_path_points",
action='store_true',
help="Toggle display of element addition path."
)
parser.add_argument(
'-dr', '--disallow_rotation',
dest="disallow_rotation",
action='store_true',
help='toggle to dissallow rotation of rectangles when adding to SquareCanvas.'
)
# endregion
# noinspection PyTypeChecker
def main():
args = parser.parse_args()
print(args)
list_shapes = []
if args.input_csv is not None:
df = pd.read_csv(args.input_csv)
if "length" not in df.columns:
raise IndexError("Please supply csv with length column.")
if "width" not in df.columns:
raise IndexError("Please supply csv with width column.")
for idx, row in df.iterrows():
extra = pd.DataFrame(row).T.drop(
columns=["length", "width"]
).to_dict("records")[0]
list_shapes += [Rect(length=row.length, width=row.width, extra=extra)]
if args.canvas_size is None:
raise ArgumentError("Please supply at least a canvas size for csv population.")
if args.square_list is not None:
list_square_radii = [int(i) for i in args.square_list.replace(",", "").split(" ")]
list_shapes = list_shapes + [Square(radius) for radius in list_square_radii]
if args.rect_list is not None:
list_rect_defs = args.rect_list.replace(",", "").split(" ")
dict_list_rects = [
{
"count": int(rect.split("*")[1]),
"length": int(rect.split("[")[1].split("x")[0]),
"width": int(rect.split("[")[1].split("x")[1].split("]")[0])
}
for rect in list_rect_defs
]
list_rects = count_expand(dict_list_rects)
# noinspection PyTypeChecker
list_shapes = list_shapes + [
Rect(length=element['length'], width=element['width']) for element in list_rects
]
if args.canvas_size is not None:
canvas = SquareCanvas(
max_bound=int(args.canvas_size),
contents=list_shapes,
allow_rotation=(not args.disallow_rotation)
)
if args.image_zero is not None:
# noinspection PyTypeChecker
image = np.asarray(PIL.Image.open(args.image_zero)).astype(int)
# transform black and white
where_not0 = np.where(image != 0)
where_0 = np.where(image == 0)
image[where_0] = 0
image[where_not0] = -1
if args.image_average is not None:
img = PIL.Image.open(args.image_average)
thresh = np.asarray(img).astype(int).mean(axis=0).mean()
img = img.convert('L').point(lambda x: 255 if x > thresh else 0, mode='1')
image = np.asarray(img).astype(int)
if "img" in locals():
# noinspection PyUnboundLocalVariable
img = img.rotate(int(args.image_rotate), expand=True)
image = np.asarray(img).astype(int)
image = image * -1 if np.amax(image) == 1 else image
# noinspection PyUnboundLocalVariable
if "image" in locals():
canvas = SquareCanvas(
frame_override=image,
contents=list_shapes,
allow_rotation=(not args.disallow_rotation)
)
display_text = args.display_points
display_path = args.display_path_points
if "canvas" in locals():
if args.rect_max_side is not None:
canvas.autofill(max_side=int(args.rect_max_side), square_only=False)
if args.square_max_side is not None:
canvas.autofill(max_side=int(args.square_max_side), square_only=True)
if args.plot_display is not None:
args.array_display = False
if args.output_file is None:
canvas.generate_plotly(
render=args.plot_display,
show_text=display_text,
trace_path=display_path
)
else:
canvas.generate_plotly(
out_file=args.output_file,
show_text=display_text,
trace_path=display_path
)
if bool(args.array_display):
print(canvas.contents)
print(canvas.frame)
if bool(args.output_csv):
canvas.contents_frame().to_csv(args.output_csv, index=False)
if bool(args.output_xlsx):
canvas.contents_frame().to_csv(args.output_xlsx, index=False)
if __name__ == "__main__":
raise SystemExit(main())