psaegert commited on
Commit
2c34d2f
·
1 Parent(s): b322ccb

Upload 201 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. pairs/pair_0/input.txt +4 -0
  2. pairs/pair_0/output.txt +7 -0
  3. pairs/pair_1/input.txt +18 -0
  4. pairs/pair_1/output.txt +13 -0
  5. pairs/pair_10/input.txt +178 -0
  6. pairs/pair_10/output.txt +1 -0
  7. pairs/pair_11/input.txt +379 -0
  8. pairs/pair_11/output.txt +3 -0
  9. pairs/pair_12/input.txt +5 -0
  10. pairs/pair_12/output.txt +1 -0
  11. pairs/pair_13/input.txt +74 -0
  12. pairs/pair_13/output.txt +31 -0
  13. pairs/pair_14/input.txt +155 -0
  14. pairs/pair_14/output.txt +30 -0
  15. pairs/pair_15/input.txt +81 -0
  16. pairs/pair_15/output.txt +9 -0
  17. pairs/pair_16/input.txt +43 -0
  18. pairs/pair_16/output.txt +5 -0
  19. pairs/pair_17/input.txt +82 -0
  20. pairs/pair_17/output.txt +7 -0
  21. pairs/pair_18/input.txt +24 -0
  22. pairs/pair_18/output.txt +8 -0
  23. pairs/pair_19/input.txt +37 -0
  24. pairs/pair_19/output.txt +3 -0
  25. pairs/pair_2/input.txt +42 -0
  26. pairs/pair_2/output.txt +33 -0
  27. pairs/pair_20/input.txt +317 -0
  28. pairs/pair_20/output.txt +1 -0
  29. pairs/pair_21/input.txt +50 -0
  30. pairs/pair_21/output.txt +1 -0
  31. pairs/pair_22/input.txt +75 -0
  32. pairs/pair_22/output.txt +13 -0
  33. pairs/pair_23/input.txt +407 -0
  34. pairs/pair_23/output.txt +8 -0
  35. pairs/pair_24/input.txt +34 -0
  36. pairs/pair_24/output.txt +7 -0
  37. pairs/pair_25/input.txt +76 -0
  38. pairs/pair_25/output.txt +1 -0
  39. pairs/pair_26/input.txt +104 -0
  40. pairs/pair_26/output.txt +28 -0
  41. pairs/pair_27/input.txt +4 -0
  42. pairs/pair_27/output.txt +4 -0
  43. pairs/pair_28/input.txt +35 -0
  44. pairs/pair_28/output.txt +20 -0
  45. pairs/pair_29/input.txt +263 -0
  46. pairs/pair_29/output.txt +2 -0
  47. pairs/pair_3/input.txt +77 -0
  48. pairs/pair_3/output.txt +8 -0
  49. pairs/pair_30/input.txt +62 -0
  50. pairs/pair_30/output.txt +2 -0
pairs/pair_0/input.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #
2
+ # Copyright (C) 2023, Inria
3
+ # GRAPHDECO research group, https://team.inria.fr/graphdeco
4
+ # Al
pairs/pair_0/output.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ l rights reserved.
2
+ #
3
+ # This software is free for non-commercial, research and evaluation use
4
+ # under the terms of the LICENSE.md file.
5
+ #
6
+ # For inquiries contact [email protected]
7
+ #
pairs/pair_1/input.txt ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Copyright (C) 2023, Inria
3
+ # GRAPHDECO research group, https://team.inria.fr/graphdeco
4
+ # All rights reserved.
5
+ #
6
+ # This software is free for non-commercial, research and evaluation use
7
+ # under the terms of the LICENSE.md file.
8
+ #
9
+ # For inquiries contact [email protected]
10
+ #
11
+
12
+ import torch
13
+ from torch import nn
14
+ import numpy as np
15
+ from utils.graphics_utils import getWorld2View2, getProjectionMatrix
16
+
17
+ class Camera(nn.Module):
18
+ def __init__(self, colmap_id, R
pairs/pair_1/output.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ , T, FoVx, FoVy, image, gt_alpha_mask,
2
+ image_name, uid,
3
+ trans=np.array([0.0, 0.0, 0.0]), scale=1.0, data_device = "cuda"
4
+ ):
5
+ super(Camera, self).__init__()
6
+
7
+ self.uid = uid
8
+ self.colmap_id = colmap_id
9
+ self.R = R
10
+ self.T = T
11
+ self.FoVx = FoVx
12
+ self.FoVy = FoVy
13
+ self.image_name = image_name
pairs/pair_10/input.txt ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ if "wsgi.input_terminated" in request.environ:
2
+ app.logger.debug(
3
+ "environ wsgi.input_terminated already set, keeping: %s"
4
+ % request.environ["wsgi.input_terminated"]
5
+ )
6
+ else:
7
+ request.environ["wsgi.input_terminated"] = 1
8
+ else:
9
+ abort(501, "Chunked requests are not supported for server %s" % server)
10
+
11
+
12
+ @app.after_request
13
+ def set_cors_headers(response):
14
+ response.headers["Access-Control-Allow-Origin"] = request.headers.get("Origin", "*")
15
+ response.headers["Access-Control-Allow-Credentials"] = "true"
16
+
17
+ if request.method == "OPTIONS":
18
+ # Both of these headers are only used for the "preflight request"
19
+ # http://www.w3.org/TR/cors/#access-control-allow-methods-response-header
20
+ response.headers[
21
+ "Access-Control-Allow-Methods"
22
+ ] = "GET, POST, PUT, DELETE, PATCH, OPTIONS"
23
+ response.headers["Access-Control-Max-Age"] = "3600" # 1 hour cache
24
+ if request.headers.get("Access-Control-Request-Headers") is not None:
25
+ response.headers["Access-Control-Allow-Headers"] = request.headers[
26
+ "Access-Control-Request-Headers"
27
+ ]
28
+ return response
29
+
30
+
31
+ # ------
32
+ # Routes
33
+ # ------
34
+
35
+
36
+ @app.route("/legacy")
37
+ def view_landing_page():
38
+ """Generates Landing Page in legacy layout."""
39
+ return render_template("index.html")
40
+
41
+
42
+ @app.route("/html")
43
+ def view_html_page():
44
+ """Returns a simple HTML document.
45
+ ---
46
+ tags:
47
+ - Response formats
48
+ produces:
49
+ - text/html
50
+ responses:
51
+ 200:
52
+ description: An HTML page.
53
+ """
54
+
55
+ return render_template("moby.html")
56
+
57
+
58
+ @app.route("/robots.txt")
59
+ def view_robots_page():
60
+ """Returns some robots.txt rules.
61
+ ---
62
+ tags:
63
+ - Response formats
64
+ produces:
65
+ - text/plain
66
+ responses:
67
+ 200:
68
+ description: Robots file
69
+ """
70
+
71
+ response = make_response()
72
+ response.data = ROBOT_TXT
73
+ response.content_type = "text/plain"
74
+ return response
75
+
76
+
77
+ @app.route("/deny")
78
+ def view_deny_page():
79
+ """Returns page denied by robots.txt rules.
80
+ ---
81
+ tags:
82
+ - Response formats
83
+ produces:
84
+ - text/plain
85
+ responses:
86
+ 200:
87
+ description: Denied message
88
+ """
89
+ response = make_response()
90
+ response.data = ANGRY_ASCII
91
+ response.content_type = "text/plain"
92
+ return response
93
+ # return "YOU SHOULDN'T BE HERE"
94
+
95
+
96
+ @app.route("/ip")
97
+ def view_origin():
98
+ """Returns the requester's IP Address.
99
+ ---
100
+ tags:
101
+ - Request inspection
102
+ produces:
103
+ - application/json
104
+ responses:
105
+ 200:
106
+ description: The Requester's IP Address.
107
+ """
108
+
109
+ return jsonify(origin=request.headers.get("X-Forwarded-For", request.remote_addr))
110
+
111
+
112
+ @app.route("/uuid")
113
+ def view_uuid():
114
+ """Return a UUID4.
115
+ ---
116
+ tags:
117
+ - Dynamic data
118
+ produces:
119
+ - application/json
120
+ responses:
121
+ 200:
122
+ description: A UUID4.
123
+ """
124
+
125
+ return jsonify(uuid=str(uuid.uuid4()))
126
+
127
+
128
+ @app.route("/headers")
129
+ def view_headers():
130
+ """Return the incoming request's HTTP headers.
131
+ ---
132
+ tags:
133
+ - Request inspection
134
+ produces:
135
+ - application/json
136
+ responses:
137
+ 200:
138
+ description: The request's headers.
139
+ """
140
+
141
+ return jsonify(get_dict('headers'))
142
+
143
+
144
+ @app.route("/user-agent")
145
+ def view_user_agent():
146
+ """Return the incoming requests's User-Agent header.
147
+ ---
148
+ tags:
149
+ - Request inspection
150
+ produces:
151
+ - application/json
152
+ responses:
153
+ 200:
154
+ description: The request's User-Agent header.
155
+ """
156
+
157
+ headers = get_headers()
158
+
159
+ return jsonify({"user-agent": headers["user-agent"]})
160
+
161
+
162
+ @app.route("/get", methods=("GET",))
163
+ def view_get():
164
+ """The request's query parameters.
165
+ ---
166
+ tags:
167
+ - HTTP Methods
168
+ produces:
169
+ - application/json
170
+ responses:
171
+ 200:
172
+ description: The request's query parameters.
173
+ """
174
+
175
+ return jsonify(get_dict("url", "args", "headers", "origin"))
176
+
177
+
178
+ @app.route("/anything", methods=["GET", "POST", "PUT", "DELETE", "PATCH", "TRAC
pairs/pair_10/output.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ E"])
pairs/pair_11/input.txt ADDED
@@ -0,0 +1,379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ue) == 1:
2
+ value = value[0]
3
+ d[key] = value
4
+ response = jsonify(d)
5
+ for key, value in headers.items(multi=True):
6
+ response.headers.add(key, value)
7
+ response_has_changed = response.data != original_data
8
+ if not response_has_changed:
9
+ break
10
+ return response
11
+
12
+
13
+ @app.route("/cookies")
14
+ def view_cookies(hide_env=True):
15
+ """Returns cookie data.
16
+ ---
17
+ tags:
18
+ - Cookies
19
+ produces:
20
+ - application/json
21
+ responses:
22
+ 200:
23
+ description: Set cookies.
24
+ """
25
+
26
+ cookies = dict(request.cookies.items())
27
+
28
+ if hide_env and ("show_env" not in request.args):
29
+ for key in ENV_COOKIES:
30
+ try:
31
+ del cookies[key]
32
+ except KeyError:
33
+ pass
34
+
35
+ return jsonify(cookies=cookies)
36
+
37
+
38
+ @app.route("/forms/post")
39
+ def view_forms_post():
40
+ """Simple HTML form."""
41
+
42
+ return render_template("forms-post.html")
43
+
44
+
45
+ @app.route("/cookies/set/<name>/<value>")
46
+ def set_cookie(name, value):
47
+ """Sets a cookie and redirects to cookie list.
48
+ ---
49
+ tags:
50
+ - Cookies
51
+ parameters:
52
+ - in: path
53
+ name: name
54
+ type: string
55
+ - in: path
56
+ name: value
57
+ type: string
58
+ produces:
59
+ - text/plain
60
+ responses:
61
+ 200:
62
+ description: Set cookies and redirects to cookie list.
63
+ """
64
+
65
+ r = app.make_response(redirect(url_for("view_cookies")))
66
+ r.set_cookie(key=name, value=value, secure=secure_cookie())
67
+
68
+ return r
69
+
70
+
71
+ @app.route("/cookies/set")
72
+ def set_cookies():
73
+ """Sets cookie(s) as provided by the query string and redirects to cookie list.
74
+ ---
75
+ tags:
76
+ - Cookies
77
+ parameters:
78
+ - in: query
79
+ name: freeform
80
+ explode: true
81
+ allowEmptyValue: true
82
+ schema:
83
+ type: object
84
+ additionalProperties:
85
+ type: string
86
+ style: form
87
+ produces:
88
+ - text/plain
89
+ responses:
90
+ 200:
91
+ description: Redirect to cookie list
92
+ """
93
+
94
+ cookies = dict(request.args.items())
95
+ r = app.make_response(redirect(url_for("view_cookies")))
96
+ for key, value in cookies.items():
97
+ r.set_cookie(key=key, value=value, secure=secure_cookie())
98
+
99
+ return r
100
+
101
+
102
+ @app.route("/cookies/delete")
103
+ def delete_cookies():
104
+ """Deletes cookie(s) as provided by the query string and redirects to cookie list.
105
+ ---
106
+ tags:
107
+ - Cookies
108
+ parameters:
109
+ - in: query
110
+ name: freeform
111
+ explode: true
112
+ allowEmptyValue: true
113
+ schema:
114
+ type: object
115
+ additionalProperties:
116
+ type: string
117
+ style: form
118
+ produces:
119
+ - text/plain
120
+ responses:
121
+ 200:
122
+ description: Redirect to cookie list
123
+ """
124
+
125
+ cookies = dict(request.args.items())
126
+ r = app.make_response(redirect(url_for("view_cookies")))
127
+ for key, value in cookies.items():
128
+ r.delete_cookie(key=key)
129
+
130
+ return r
131
+
132
+
133
+ @app.route("/basic-auth/<user>/<passwd>")
134
+ def basic_auth(user="user", passwd="passwd"):
135
+ """Prompts the user for authorization using HTTP Basic Auth.
136
+ ---
137
+ tags:
138
+ - Auth
139
+ parameters:
140
+ - in: path
141
+ name: user
142
+ type: string
143
+ - in: path
144
+ name: passwd
145
+ type: string
146
+ produces:
147
+ - application/json
148
+ responses:
149
+ 200:
150
+ description: Sucessful authentication.
151
+ 401:
152
+ description: Unsuccessful authentication.
153
+ """
154
+
155
+ if not check_basic_auth(user, passwd):
156
+ return status_code(401)
157
+
158
+ return jsonify(authenticated=True, user=user)
159
+
160
+
161
+ @app.route("/hidden-basic-auth/<user>/<passwd>")
162
+ def hidden_basic_auth(user="user", passwd="passwd"):
163
+ """Prompts the user for authorization using HTTP Basic Auth.
164
+ ---
165
+ tags:
166
+ - Auth
167
+ parameters:
168
+ - in: path
169
+ name: user
170
+ type: string
171
+ - in: path
172
+ name: passwd
173
+ type: string
174
+ produces:
175
+ - application/json
176
+ responses:
177
+ 200:
178
+ description: Sucessful authentication.
179
+ 404:
180
+ description: Unsuccessful authentication.
181
+ """
182
+
183
+ if not check_basic_auth(user, passwd):
184
+ return status_code(404)
185
+ return jsonify(authenticated=True, user=user)
186
+
187
+
188
+ @app.route("/bearer")
189
+ def bearer_auth():
190
+ """Prompts the user for authorization using bearer authentication.
191
+ ---
192
+ tags:
193
+ - Auth
194
+ parameters:
195
+ - in: header
196
+ name: Authorization
197
+ schema:
198
+ type: string
199
+ produces:
200
+ - application/json
201
+ responses:
202
+ 200:
203
+ description: Sucessful authentication.
204
+ 401:
205
+ description: Unsuccessful authentication.
206
+ """
207
+ authorization = request.headers.get("Authorization")
208
+ if not (authorization and authorization.startswith("Bearer ")):
209
+ response = app.make_response("")
210
+ response.headers["WWW-Authenticate"] = "Bearer"
211
+ response.status_code = 401
212
+ return response
213
+ slice_start = len("Bearer ")
214
+ token = authorization[slice_start:]
215
+
216
+ return jsonify(authenticated=True, token=token)
217
+
218
+
219
+ @app.route("/digest-auth/<qop>/<user>/<passwd>")
220
+ def digest_auth_md5(qop=None, user="user", passwd="passwd"):
221
+ """Prompts the user for authorization using Digest Auth.
222
+ ---
223
+ tags:
224
+ - Auth
225
+ parameters:
226
+ - in: path
227
+ name: qop
228
+ type: string
229
+ description: auth or auth-int
230
+ - in: path
231
+ name: user
232
+ type: string
233
+ - in: path
234
+ name: passwd
235
+ type: string
236
+ produces:
237
+ - application/json
238
+ responses:
239
+ 200:
240
+ description: Sucessful authentication.
241
+ 401:
242
+ description: Unsuccessful authentication.
243
+ """
244
+ return digest_auth(qop, user, passwd, "MD5", "never")
245
+
246
+
247
+ @app.route("/digest-auth/<qop>/<user>/<passwd>/<algorithm>")
248
+ def digest_auth_nostale(qop=None, user="user", passwd="passwd", algorithm="MD5"):
249
+ """Prompts the user for authorization using Digest Auth + Algorithm.
250
+ ---
251
+ tags:
252
+ - Auth
253
+ parameters:
254
+ - in: path
255
+ name: qop
256
+ type: string
257
+ description: auth or auth-int
258
+ - in: path
259
+ name: user
260
+ type: string
261
+ - in: path
262
+ name: passwd
263
+ type: string
264
+ - in: path
265
+ name: algorithm
266
+ type: string
267
+ description: MD5, SHA-256, SHA-512
268
+ default: MD5
269
+ produces:
270
+ - application/json
271
+ responses:
272
+ 200:
273
+ description: Sucessful authentication.
274
+ 401:
275
+ description: Unsuccessful authentication.
276
+ """
277
+ return digest_auth(qop, user, passwd, algorithm, "never")
278
+
279
+
280
+ @app.route("/digest-auth/<qop>/<user>/<passwd>/<algorithm>/<stale_after>")
281
+ def digest_auth(
282
+ qop=None, user="user", passwd="passwd", algorithm="MD5", stale_after="never"
283
+ ):
284
+ """Prompts the user for authorization using Digest Auth + Algorithm.
285
+ allow settings the stale_after argument.
286
+ ---
287
+ tags:
288
+ - Auth
289
+ parameters:
290
+ - in: path
291
+ name: qop
292
+ type: string
293
+ description: auth or auth-int
294
+ - in: path
295
+ name: user
296
+ type: string
297
+ - in: path
298
+ name: passwd
299
+ type: string
300
+ - in: path
301
+ name: algorithm
302
+ type: string
303
+ description: MD5, SHA-256, SHA-512
304
+ default: MD5
305
+ - in: path
306
+ name: stale_after
307
+ type: string
308
+ default: never
309
+ produces:
310
+ - application/json
311
+ responses:
312
+ 200:
313
+ description: Sucessful authentication.
314
+ 401:
315
+ description: Unsuccessful authentication.
316
+ """
317
+ require_cookie_handling = request.args.get("require-cookie", "").lower() in (
318
+ "1",
319
+ "t",
320
+ "true",
321
+ )
322
+ if algorithm not in ("MD5", "SHA-256", "SHA-512"):
323
+ algorithm = "MD5"
324
+
325
+ if qop not in ("auth", "auth-int"):
326
+ qop = None
327
+
328
+ authorization = request.headers.get("Authorization")
329
+ credentials = None
330
+ if authorization:
331
+ credentials = parse_authorization_header(authorization)
332
+
333
+ if (
334
+ not authorization
335
+ or not credentials
336
+ or credentials.type.lower() != "digest"
337
+ or (require_cookie_handling and "Cookie" not in request.headers)
338
+ ):
339
+ response = digest_challenge_response(app, qop, algorithm)
340
+ response.set_cookie("stale_after", value=stale_after)
341
+ response.set_cookie("fake", value="fake_value")
342
+ return response
343
+
344
+ if require_cookie_handling and request.cookies.get("fake") != "fake_value":
345
+ response = jsonify({"errors": ["missing cookie set on challenge"]})
346
+ response.set_cookie("fake", value="fake_value")
347
+ response.status_code = 403
348
+ return response
349
+
350
+ current_nonce = credentials.get("nonce")
351
+
352
+ stale_after_value = None
353
+ if "stale_after" in request.cookies:
354
+ stale_after_value = request.cookies.get("stale_after")
355
+
356
+ if (
357
+ "last_nonce" in request.cookies
358
+ and current_nonce == request.cookies.get("last_nonce")
359
+ or stale_after_value == "0"
360
+ ):
361
+ response = digest_challenge_response(app, qop, algorithm, True)
362
+ response.set_cookie("stale_after", value=stale_after)
363
+ response.set_cookie("last_nonce", value=current_nonce)
364
+ response.set_cookie("fake", value="fake_value")
365
+ return response
366
+
367
+ if not check_digest_auth(user, passwd):
368
+ response = digest_challenge_response(app, qop, algorithm, False)
369
+ response.set_cookie("stale_after", value=stale_after)
370
+ response.set_cookie("last_nonce", value=current_nonce)
371
+ response.set_cookie("fake", value="fake_value")
372
+ return response
373
+
374
+ response = jsonify(authenticated=True, user=user)
375
+ response.set_cookie("fake", value="fake_value")
376
+ if stale_after_value:
377
+ response.set_cookie(
378
+ "stale_after", value=next_stale_after_value(stale_after_value)
379
+
pairs/pair_11/output.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ )
2
+
3
+ return response
pairs/pair_12/input.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Copyright (c) OpenMMLab. All rights reserved.
2
+ import numbers
3
+ from math import cos, pi
4
+
5
+ import annotator.
pairs/pair_12/output.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ uniformer.mmcv as mmcv
pairs/pair_13/input.txt ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ on
2
+ maps or list of prediction result filenames.
3
+ gt_seg_maps (list[ndarray] | list[str]): list of ground truth
4
+ segmentation maps or list of label filenames.
5
+ num_classes (int): Number of categories.
6
+ ignore_index (int): Index that will be ignored in evaluation.
7
+ nan_to_num (int, optional): If specified, NaN values will be replaced
8
+ by the numbers defined by the user. Default: None.
9
+ label_map (dict): Mapping old labels to new labels. Default: dict().
10
+ reduce_zero_label (bool): Wether ignore zero label. Default: False.
11
+ beta (int): Determines the weight of recall in the combined score.
12
+ Default: False.
13
+
14
+
15
+ Returns:
16
+ dict[str, float | ndarray]: Default metrics.
17
+ <aAcc> float: Overall accuracy on all images.
18
+ <Fscore> ndarray: Per category recall, shape (num_classes, ).
19
+ <Precision> ndarray: Per category precision, shape (num_classes, ).
20
+ <Recall> ndarray: Per category f-score, shape (num_classes, ).
21
+ """
22
+ fscore_result = eval_metrics(
23
+ results=results,
24
+ gt_seg_maps=gt_seg_maps,
25
+ num_classes=num_classes,
26
+ ignore_index=ignore_index,
27
+ metrics=['mFscore'],
28
+ nan_to_num=nan_to_num,
29
+ label_map=label_map,
30
+ reduce_zero_label=reduce_zero_label,
31
+ beta=beta)
32
+ return fscore_result
33
+
34
+
35
+ def eval_metrics(results,
36
+ gt_seg_maps,
37
+ num_classes,
38
+ ignore_index,
39
+ metrics=['mIoU'],
40
+ nan_to_num=None,
41
+ label_map=dict(),
42
+ reduce_zero_label=False,
43
+ beta=1):
44
+ """Calculate evaluation metrics
45
+ Args:
46
+ results (list[ndarray] | list[str]): List of prediction segmentation
47
+ maps or list of prediction result filenames.
48
+ gt_seg_maps (list[ndarray] | list[str]): list of ground truth
49
+ segmentation maps or list of label filenames.
50
+ num_classes (int): Number of categories.
51
+ ignore_index (int): Index that will be ignored in evaluation.
52
+ metrics (list[str] | str): Metrics to be evaluated, 'mIoU' and 'mDice'.
53
+ nan_to_num (int, optional): If specified, NaN values will be replaced
54
+ by the numbers defined by the user. Default: None.
55
+ label_map (dict): Mapping old labels to new labels. Default: dict().
56
+ reduce_zero_label (bool): Wether ignore zero label. Default: False.
57
+ Returns:
58
+ float: Overall accuracy on all images.
59
+ ndarray: Per category accuracy, shape (num_classes, ).
60
+ ndarray: Per category evaluation metrics, shape (num_classes, ).
61
+ """
62
+ if isinstance(metrics, str):
63
+ metrics = [metrics]
64
+ allowed_metrics = ['mIoU', 'mDice', 'mFscore']
65
+ if not set(metrics).issubset(set(allowed_metrics)):
66
+ raise KeyError('metrics {} is not supported'.format(metrics))
67
+
68
+ total_area_intersect, total_area_union, total_area_pred_label, \
69
+ total_area_label = total_intersect_and_union(
70
+ results, gt_seg_maps, num_classes, ignore_index, label_map,
71
+ reduce_zero_label)
72
+ all_acc = total_area_intersect.sum() / total_area_label.sum()
73
+ ret_metrics = OrderedDict({'aAcc': all_acc})
74
+ for metri
pairs/pair_13/output.txt ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ c in metrics:
2
+ if metric == 'mIoU':
3
+ iou = total_area_intersect / total_area_union
4
+ acc = total_area_intersect / total_area_label
5
+ ret_metrics['IoU'] = iou
6
+ ret_metrics['Acc'] = acc
7
+ elif metric == 'mDice':
8
+ dice = 2 * total_area_intersect / (
9
+ total_area_pred_label + total_area_label)
10
+ acc = total_area_intersect / total_area_label
11
+ ret_metrics['Dice'] = dice
12
+ ret_metrics['Acc'] = acc
13
+ elif metric == 'mFscore':
14
+ precision = total_area_intersect / total_area_pred_label
15
+ recall = total_area_intersect / total_area_label
16
+ f_value = torch.tensor(
17
+ [f_score(x[0], x[1], beta) for x in zip(precision, recall)])
18
+ ret_metrics['Fscore'] = f_value
19
+ ret_metrics['Precision'] = precision
20
+ ret_metrics['Recall'] = recall
21
+
22
+ ret_metrics = {
23
+ metric: value.numpy()
24
+ for metric, value in ret_metrics.items()
25
+ }
26
+ if nan_to_num is not None:
27
+ ret_metrics = OrderedDict({
28
+ metric: np.nan_to_num(metric_value, nan=nan_to_num)
29
+ for metric, metric_value in ret_metrics.items()
30
+ })
31
+ return ret_metrics
pairs/pair_14/input.txt ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ x_t = (
2
+ expand_dims(sigma_t / sigma_s, dims) * x
3
+ - expand_dims(alpha_t * phi_1, dims) * model_s
4
+ )
5
+ if return_intermediate:
6
+ return x_t, {'model_s': model_s}
7
+ else:
8
+ return x_t
9
+ else:
10
+ phi_1 = torch.expm1(h)
11
+ if model_s is None:
12
+ model_s = self.model_fn(x, s)
13
+ x_t = (
14
+ expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x
15
+ - expand_dims(sigma_t * phi_1, dims) * model_s
16
+ )
17
+ if return_intermediate:
18
+ return x_t, {'model_s': model_s}
19
+ else:
20
+ return x_t
21
+
22
+ def singlestep_dpm_solver_second_update(self, x, s, t, r1=0.5, model_s=None, return_intermediate=False,
23
+ solver_type='dpm_solver'):
24
+ """
25
+ Singlestep solver DPM-Solver-2 from time `s` to time `t`.
26
+ Args:
27
+ x: A pytorch tensor. The initial value at time `s`.
28
+ s: A pytorch tensor. The starting time, with the shape (x.shape[0],).
29
+ t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
30
+ r1: A `float`. The hyperparameter of the second-order solver.
31
+ model_s: A pytorch tensor. The model function evaluated at time `s`.
32
+ If `model_s` is None, we evaluate the model by `x` and `s`; otherwise we directly use it.
33
+ return_intermediate: A `bool`. If true, also return the model value at time `s` and `s1` (the intermediate time).
34
+ solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
35
+ The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
36
+ Returns:
37
+ x_t: A pytorch tensor. The approximated solution at time `t`.
38
+ """
39
+ if solver_type not in ['dpm_solver', 'taylor']:
40
+ raise ValueError("'solver_type' must be either 'dpm_solver' or 'taylor', got {}".format(solver_type))
41
+ if r1 is None:
42
+ r1 = 0.5
43
+ ns = self.noise_schedule
44
+ dims = x.dim()
45
+ lambda_s, lambda_t = ns.marginal_lambda(s), ns.marginal_lambda(t)
46
+ h = lambda_t - lambda_s
47
+ lambda_s1 = lambda_s + r1 * h
48
+ s1 = ns.inverse_lambda(lambda_s1)
49
+ log_alpha_s, log_alpha_s1, log_alpha_t = ns.marginal_log_mean_coeff(s), ns.marginal_log_mean_coeff(
50
+ s1), ns.marginal_log_mean_coeff(t)
51
+ sigma_s, sigma_s1, sigma_t = ns.marginal_std(s), ns.marginal_std(s1), ns.marginal_std(t)
52
+ alpha_s1, alpha_t = torch.exp(log_alpha_s1), torch.exp(log_alpha_t)
53
+
54
+ if self.predict_x0:
55
+ phi_11 = torch.expm1(-r1 * h)
56
+ phi_1 = torch.expm1(-h)
57
+
58
+ if model_s is None:
59
+ model_s = self.model_fn(x, s)
60
+ x_s1 = (
61
+ expand_dims(sigma_s1 / sigma_s, dims) * x
62
+ - expand_dims(alpha_s1 * phi_11, dims) * model_s
63
+ )
64
+ model_s1 = self.model_fn(x_s1, s1)
65
+ if solver_type == 'dpm_solver':
66
+ x_t = (
67
+ expand_dims(sigma_t / sigma_s, dims) * x
68
+ - expand_dims(alpha_t * phi_1, dims) * model_s
69
+ - (0.5 / r1) * expand_dims(alpha_t * phi_1, dims) * (model_s1 - model_s)
70
+ )
71
+ elif solver_type == 'taylor':
72
+ x_t = (
73
+ expand_dims(sigma_t / sigma_s, dims) * x
74
+ - expand_dims(alpha_t * phi_1, dims) * model_s
75
+ + (1. / r1) * expand_dims(alpha_t * ((torch.exp(-h) - 1.) / h + 1.), dims) * (
76
+ model_s1 - model_s)
77
+ )
78
+ else:
79
+ phi_11 = torch.expm1(r1 * h)
80
+ phi_1 = torch.expm1(h)
81
+
82
+ if model_s is None:
83
+ model_s = self.model_fn(x, s)
84
+ x_s1 = (
85
+ expand_dims(torch.exp(log_alpha_s1 - log_alpha_s), dims) * x
86
+ - expand_dims(sigma_s1 * phi_11, dims) * model_s
87
+ )
88
+ model_s1 = self.model_fn(x_s1, s1)
89
+ if solver_type == 'dpm_solver':
90
+ x_t = (
91
+ expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x
92
+ - expand_dims(sigma_t * phi_1, dims) * model_s
93
+ - (0.5 / r1) * expand_dims(sigma_t * phi_1, dims) * (model_s1 - model_s)
94
+ )
95
+ elif solver_type == 'taylor':
96
+ x_t = (
97
+ expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x
98
+ - expand_dims(sigma_t * phi_1, dims) * model_s
99
+ - (1. / r1) * expand_dims(sigma_t * ((torch.exp(h) - 1.) / h - 1.), dims) * (model_s1 - model_s)
100
+ )
101
+ if return_intermediate:
102
+ return x_t, {'model_s': model_s, 'model_s1': model_s1}
103
+ else:
104
+ return x_t
105
+
106
+ def singlestep_dpm_solver_third_update(self, x, s, t, r1=1. / 3., r2=2. / 3., model_s=None, model_s1=None,
107
+ return_intermediate=False, solver_type='dpm_solver'):
108
+ """
109
+ Singlestep solver DPM-Solver-3 from time `s` to time `t`.
110
+ Args:
111
+ x: A pytorch tensor. The initial value at time `s`.
112
+ s: A pytorch tensor. The starting time, with the shape (x.shape[0],).
113
+ t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
114
+ r1: A `float`. The hyperparameter of the third-order solver.
115
+ r2: A `float`. The hyperparameter of the third-order solver.
116
+ model_s: A pytorch tensor. The model function evaluated at time `s`.
117
+ If `model_s` is None, we evaluate the model by `x` and `s`; otherwise we directly use it.
118
+ model_s1: A pytorch tensor. The model function evaluated at time `s1` (the intermediate time given by `r1`).
119
+ If `model_s1` is None, we evaluate the model at `s1`; otherwise we directly use it.
120
+ return_intermediate: A `bool`. If true, also return the model value at time `s`, `s1` and `s2` (the intermediate times).
121
+ solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
122
+ The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
123
+ Returns:
124
+ x_t: A pytorch tensor. The approximated solution at time `t`.
125
+ """
126
+ if solver_type not in ['dpm_solver', 'taylor']:
127
+ raise ValueError("'solver_type' must be either 'dpm_solver' or 'taylor', got {}".format(solver_type))
128
+ if r1 is None:
129
+ r1 = 1. / 3.
130
+ if r2 is None:
131
+ r2 = 2. / 3.
132
+ ns = self.noise_schedule
133
+ dims = x.dim()
134
+ lambda_s, lambda_t = ns.marginal_lambda(s), ns.marginal_lambda(t)
135
+ h = lambda_t - lambda_s
136
+ lambda_s1 = lambda_s + r1 * h
137
+ lambda_s2 = lambda_s + r2 * h
138
+ s1 = ns.inverse_lambda(lambda_s1)
139
+ s2 = ns.inverse_lambda(lambda_s2)
140
+ log_alpha_s, log_alpha_s1, log_alpha_s2, log_alpha_t = ns.marginal_log_mean_coeff(
141
+ s), ns.marginal_log_mean_coeff(s1), ns.marginal_log_mean_coeff(s2), ns.marginal_log_mean_coeff(t)
142
+ sigma_s, sigma_s1, sigma_s2, sigma_t = ns.marginal_std(s), ns.marginal_std(s1), ns.marginal_std(
143
+ s2), ns.marginal_std(t)
144
+ alpha_s1, alpha_s2, alpha_t = torch.exp(log_alpha_s1), torch.exp(log_alpha_s2), torch.exp(log_alpha_t)
145
+
146
+ if self.predict_x0:
147
+ phi_11 = torch.expm1(-r1 * h)
148
+ phi_12 = torch.expm1(-r2 * h)
149
+ phi_1 = torch.expm1(-h)
150
+ phi_22 = torch.expm1(-r2 * h) / (r2 * h) + 1.
151
+ phi_2 = phi_1 / h + 1.
152
+ phi_3 = phi_2 / h - 0.5
153
+
154
+ if model_s is None:
155
+ model_s = self.mode
pairs/pair_14/output.txt ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ l_fn(x, s)
2
+ if model_s1 is None:
3
+ x_s1 = (
4
+ expand_dims(sigma_s1 / sigma_s, dims) * x
5
+ - expand_dims(alpha_s1 * phi_11, dims) * model_s
6
+ )
7
+ model_s1 = self.model_fn(x_s1, s1)
8
+ x_s2 = (
9
+ expand_dims(sigma_s2 / sigma_s, dims) * x
10
+ - expand_dims(alpha_s2 * phi_12, dims) * model_s
11
+ + r2 / r1 * expand_dims(alpha_s2 * phi_22, dims) * (model_s1 - model_s)
12
+ )
13
+ model_s2 = self.model_fn(x_s2, s2)
14
+ if solver_type == 'dpm_solver':
15
+ x_t = (
16
+ expand_dims(sigma_t / sigma_s, dims) * x
17
+ - expand_dims(alpha_t * phi_1, dims) * model_s
18
+ + (1. / r2) * expand_dims(alpha_t * phi_2, dims) * (model_s2 - model_s)
19
+ )
20
+ elif solver_type == 'taylor':
21
+ D1_0 = (1. / r1) * (model_s1 - model_s)
22
+ D1_1 = (1. / r2) * (model_s2 - model_s)
23
+ D1 = (r2 * D1_0 - r1 * D1_1) / (r2 - r1)
24
+ D2 = 2. * (D1_1 - D1_0) / (r2 - r1)
25
+ x_t = (
26
+ expand_dims(sigma_t / sigma_s, dims) * x
27
+ - expand_dims(alpha_t * phi_1, dims) * model_s
28
+ + expand_dims(alpha_t * phi_2, dims) * D1
29
+ - expand_dims(alpha_t * phi_3, dims) * D2
30
+ )
pairs/pair_15/input.txt ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cc = torch.cat(c_crossattn, 1)
2
+ out = self.diffusion_model(xc, t, context=cc)
3
+ elif self.conditioning_key == 'hybrid-adm':
4
+ assert c_adm is not None
5
+ xc = torch.cat([x] + c_concat, dim=1)
6
+ cc = torch.cat(c_crossattn, 1)
7
+ out = self.diffusion_model(xc, t, context=cc, y=c_adm)
8
+ elif self.conditioning_key == 'crossattn-adm':
9
+ assert c_adm is not None
10
+ cc = torch.cat(c_crossattn, 1)
11
+ out = self.diffusion_model(x, t, context=cc, y=c_adm)
12
+ elif self.conditioning_key == 'adm':
13
+ cc = c_crossattn[0]
14
+ out = self.diffusion_model(x, t, y=cc)
15
+ else:
16
+ raise NotImplementedError()
17
+
18
+ return out
19
+
20
+
21
+ class LatentUpscaleDiffusion(LatentDiffusion):
22
+ def __init__(self, *args, low_scale_config, low_scale_key="LR", noise_level_key=None, **kwargs):
23
+ super().__init__(*args, **kwargs)
24
+ # assumes that neither the cond_stage nor the low_scale_model contain trainable params
25
+ assert not self.cond_stage_trainable
26
+ self.instantiate_low_stage(low_scale_config)
27
+ self.low_scale_key = low_scale_key
28
+ self.noise_level_key = noise_level_key
29
+
30
+ def instantiate_low_stage(self, config):
31
+ model = instantiate_from_config(config)
32
+ self.low_scale_model = model.eval()
33
+ self.low_scale_model.train = disabled_train
34
+ for param in self.low_scale_model.parameters():
35
+ param.requires_grad = False
36
+
37
+ @torch.no_grad()
38
+ def get_input(self, batch, k, cond_key=None, bs=None, log_mode=False):
39
+ if not log_mode:
40
+ z, c = super().get_input(batch, k, force_c_encode=True, bs=bs)
41
+ else:
42
+ z, c, x, xrec, xc = super().get_input(batch, self.first_stage_key, return_first_stage_outputs=True,
43
+ force_c_encode=True, return_original_cond=True, bs=bs)
44
+ x_low = batch[self.low_scale_key][:bs]
45
+ x_low = rearrange(x_low, 'b h w c -> b c h w')
46
+ x_low = x_low.to(memory_format=torch.contiguous_format).float()
47
+ zx, noise_level = self.low_scale_model(x_low)
48
+ if self.noise_level_key is not None:
49
+ # get noise level from batch instead, e.g. when extracting a custom noise level for bsr
50
+ raise NotImplementedError('TODO')
51
+
52
+ all_conds = {"c_concat": [zx], "c_crossattn": [c], "c_adm": noise_level}
53
+ if log_mode:
54
+ # TODO: maybe disable if too expensive
55
+ x_low_rec = self.low_scale_model.decode(zx)
56
+ return z, all_conds, x, xrec, xc, x_low, x_low_rec, noise_level
57
+ return z, all_conds
58
+
59
+ @torch.no_grad()
60
+ def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=200, ddim_eta=1., return_keys=None,
61
+ plot_denoise_rows=False, plot_progressive_rows=True, plot_diffusion_rows=True,
62
+ unconditional_guidance_scale=1., unconditional_guidance_label=None, use_ema_scope=True,
63
+ **kwargs):
64
+ ema_scope = self.ema_scope if use_ema_scope else nullcontext
65
+ use_ddim = ddim_steps is not None
66
+
67
+ log = dict()
68
+ z, c, x, xrec, xc, x_low, x_low_rec, noise_level = self.get_input(batch, self.first_stage_key, bs=N,
69
+ log_mode=True)
70
+ N = min(x.shape[0], N)
71
+ n_row = min(x.shape[0], n_row)
72
+ log["inputs"] = x
73
+ log["reconstruction"] = xrec
74
+ log["x_lr"] = x_low
75
+ log[f"x_lr_rec_@noise_levels{'-'.join(map(lambda x: str(x), list(noise_level.cpu().numpy())))}"] = x_low_rec
76
+ if self.model.conditioning_key is not None:
77
+ if hasattr(self.cond_stage_model, "decode"):
78
+ xc = self.cond_stage_model.decode(c)
79
+ log["conditioning"] = xc
80
+ elif self.cond_stage_key in ["caption", "txt"]:
81
+ xc = log_txt_as_img((x.shape[2], x.shape[3]), batch[self.cond_stage_key], size=x.shape[
pairs/pair_15/output.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ 2] // 25)
2
+ log["conditioning"] = xc
3
+ elif self.cond_stage_key in ['class_label', 'cls']:
4
+ xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"], size=x.shape[2] // 25)
5
+ log['conditioning'] = xc
6
+ elif isimage(xc):
7
+ log["conditioning"] = xc
8
+ if ismap(xc):
9
+ log["original_conditioning"] = self.to_rgb(xc)
pairs/pair_16/input.txt ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from keras.models import *
3
+ from keras.layers import *
4
+ from keras.applications.vgg16 import VGG16
5
+ from keras.preprocessing.image import ImageDataGenerator
6
+ from keras.optimizers import *
7
+ from keras.callbacks import ModelCheckpoint
8
+ import cv2
9
+
10
+ def train_generator(batch_size=32):
11
+ data_gen_args = dict(featurewise_center=True,
12
+ rotation_range=90.,
13
+ width_shift_range=0.1,
14
+ height_shift_range=0.1,
15
+ fill_mode="constant",
16
+ cval=255,
17
+ horizontal_flip=True,
18
+ vertical_flip=True,
19
+ zoom_range=0.2)
20
+ image_datagen = ImageDataGenerator(**data_gen_args)
21
+ mask_datagen = ImageDataGenerator(**data_gen_args)
22
+
23
+ seed = 1
24
+ image_generator = image_datagen.flow_from_directory(
25
+ 'data/train/images',
26
+ class_mode=None,
27
+ batch_size=batch_size,
28
+ color_mode='rgb',
29
+ target_size=(512,512),
30
+ #save_to_dir='./data/gen/images',
31
+ seed=seed)
32
+
33
+ mask_generator = mask_datagen.flow_from_directory(
34
+ 'data/train/masks',
35
+ class_mode=None,
36
+ color_mode='grayscale',
37
+ target_size=(512,512),
38
+ batch_size=batch_size,
39
+ #save_to_dir='./data/gen/masks',
40
+ seed=seed)
41
+
42
+ # combine generators into one which yields image and masks
43
+ train_generator = zip(image_generator, mask_
pairs/pair_16/output.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ generator)
2
+ for (imgs, masks) in train_generator:
3
+ imgs = imgs / 255.0
4
+ masks = masks / 255.0
5
+ yield (imgs,masks)
pairs/pair_17/input.txt ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from keras.models import *
3
+ from keras.layers import *
4
+ from keras.applications.vgg16 import VGG16
5
+ from keras.preprocessing.image import ImageDataGenerator
6
+ from keras.optimizers import *
7
+ from keras.callbacks import ModelCheckpoint
8
+ import cv2
9
+
10
+ def train_generator(batch_size=32):
11
+ data_gen_args = dict(featurewise_center=True,
12
+ rotation_range=90.,
13
+ width_shift_range=0.1,
14
+ height_shift_range=0.1,
15
+ fill_mode="constant",
16
+ cval=255,
17
+ horizontal_flip=True,
18
+ vertical_flip=True,
19
+ zoom_range=0.2)
20
+ image_datagen = ImageDataGenerator(**data_gen_args)
21
+ mask_datagen = ImageDataGenerator(**data_gen_args)
22
+
23
+ seed = 1
24
+ image_generator = image_datagen.flow_from_directory(
25
+ 'data/train/images',
26
+ class_mode=None,
27
+ batch_size=batch_size,
28
+ color_mode='rgb',
29
+ target_size=(512,512),
30
+ #save_to_dir='./data/gen/images',
31
+ seed=seed)
32
+
33
+ mask_generator = mask_datagen.flow_from_directory(
34
+ 'data/train/masks',
35
+ class_mode=None,
36
+ color_mode='grayscale',
37
+ target_size=(512,512),
38
+ batch_size=batch_size,
39
+ #save_to_dir='./data/gen/masks',
40
+ seed=seed)
41
+
42
+ # combine generators into one which yields image and masks
43
+ train_generator = zip(image_generator, mask_generator)
44
+ for (imgs, masks) in train_generator:
45
+ imgs = imgs / 255.0
46
+ masks = masks / 255.0
47
+ yield (imgs,masks)
48
+
49
+
50
+ def vgg10_unet(input_shape=(256,256,3), weights='imagenet'):
51
+ vgg16_model = VGG16(input_shape=input_shape, weights=weights, include_top=False)
52
+
53
+ block4_pool = vgg16_model.get_layer('block4_pool').output
54
+ block5_conv1 = Conv2D(1024, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block4_pool)
55
+ block5_conv2 = Conv2D(1024, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block5_conv1)
56
+ block5_drop = Dropout(0.5)(block5_conv2)
57
+
58
+ block6_up = Conv2D(512, 2, activation='relu', padding='same', kernel_initializer='he_normal')(
59
+ UpSampling2D(size=(2, 2))(block5_drop))
60
+ block6_merge = Concatenate(axis=3)([vgg16_model.get_layer('block4_conv3').output, block6_up])
61
+ block6_conv1 = Conv2D(512, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block6_merge)
62
+ block6_conv2 = Conv2D(512, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block6_conv1)
63
+ block6_conv3 = Conv2D(512, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block6_conv2)
64
+
65
+ block7_up = Conv2D(256, 2, activation='relu', padding='same', kernel_initializer='he_normal')(
66
+ UpSampling2D(size=(2, 2))(block6_conv3))
67
+ block7_merge = Concatenate(axis=3)([vgg16_model.get_layer('block3_conv3').output, block7_up])
68
+ block7_conv1 = Conv2D(256, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block7_merge)
69
+ block7_conv2 = Conv2D(256, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block7_conv1)
70
+ block7_conv3 = Conv2D(256, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block7_conv2)
71
+
72
+ block8_up = Conv2D(128, 2, activation='relu', padding='same', kernel_initializer='he_normal')(
73
+ UpSampling2D(size=(2, 2))(block7_conv3))
74
+ block8_merge = Concatenate(axis=3)([vgg16_model.get_layer('block2_conv2').output, block8_up])
75
+ block8_conv1 = Conv2D(128, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block8_merge)
76
+ block8_conv2 = Conv2D(128, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block8_conv1)
77
+
78
+ block9_up = Conv2D(64, 2, activation='relu', padding='same', kernel_initializer='he_normal')(
79
+ UpSampling2D(size=(2, 2))(block8_conv2))
80
+ block9_merge = Concatenate(axis=3)([vgg16_model.get_layer('block1_conv2').output, block9_up])
81
+ block9_conv1 = Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block9_merge)
82
+ block9_conv2 = Conv2D(64, 3, activation='relu'
pairs/pair_17/output.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ , padding='same', kernel_initializer='he_normal')(block9_conv1)
2
+
3
+ block10_conv1 = Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block9_conv2)
4
+ block10_conv2 = Conv2D(1, 1, activation='sigmoid')(block10_conv1)
5
+
6
+ model = Model(inputs=vgg16_model.input, outputs=block10_conv2)
7
+ return model
pairs/pair_18/input.txt ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from keras.models import *
3
+ from keras.layers import *
4
+ from keras.applications.vgg16 import VGG16
5
+ from keras.preprocessing.image import ImageDataGenerator
6
+ from keras.optimizers import *
7
+ from keras.callbacks import ModelCheckpoint
8
+ import cv2
9
+
10
+ def train_generator(batch_size=32):
11
+ data_gen_args = dict(featurewise_center=True,
12
+ rotation_range=90.,
13
+ width_shift_range=0.1,
14
+ height_shift_range=0.1,
15
+ fill_mode="constant",
16
+ cval=255,
17
+ horizontal_flip=True,
18
+ vertical_flip=True,
19
+ zoom_range=0.2)
20
+ image_datagen = ImageDataGenerator(**data_gen_args)
21
+ mask_datagen = ImageDataGenerator(**data_gen_args)
22
+
23
+ seed = 1
24
+ image_generator = image_datagen.flow_fr
pairs/pair_18/output.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ om_directory(
2
+ 'data/train/images',
3
+ class_mode=None,
4
+ batch_size=batch_size,
5
+ color_mode='rgb',
6
+ target_size=(512,512),
7
+ #save_to_dir='./data/gen/images',
8
+ seed=seed)
pairs/pair_19/input.txt ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ er('block3_conv3').output, block7_up])
2
+ block7_conv1 = Conv2D(256, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block7_merge)
3
+ block7_conv2 = Conv2D(256, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block7_conv1)
4
+ block7_conv3 = Conv2D(256, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block7_conv2)
5
+
6
+ block8_up = Conv2D(128, 2, activation='relu', padding='same', kernel_initializer='he_normal')(
7
+ UpSampling2D(size=(2, 2))(block7_conv3))
8
+ block8_merge = Concatenate(axis=3)([vgg16_model.get_layer('block2_conv2').output, block8_up])
9
+ block8_conv1 = Conv2D(128, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block8_merge)
10
+ block8_conv2 = Conv2D(128, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block8_conv1)
11
+
12
+ block9_up = Conv2D(64, 2, activation='relu', padding='same', kernel_initializer='he_normal')(
13
+ UpSampling2D(size=(2, 2))(block8_conv2))
14
+ block9_merge = Concatenate(axis=3)([vgg16_model.get_layer('block1_conv2').output, block9_up])
15
+ block9_conv1 = Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block9_merge)
16
+ block9_conv2 = Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block9_conv1)
17
+
18
+ block10_conv1 = Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block9_conv2)
19
+ block10_conv2 = Conv2D(1, 1, activation='sigmoid')(block10_conv1)
20
+
21
+ model = Model(inputs=vgg16_model.input, outputs=block10_conv2)
22
+ return model
23
+
24
+
25
+ if __name__ == '__main__':
26
+ is_train = False
27
+ if is_train:
28
+ model = vgg10_unet(input_shape=(512,512,3), weights='imagenet')
29
+
30
+ for index in range(15):
31
+ model.layers[index].trainable = True
32
+ model.compile(optimizer=Adam(lr=1e-4), loss='binary_crossentropy', metrics=['accuracy'])
33
+ model_checkpoint = ModelCheckpoint('unet.h5', monitor='loss', verbose=1, save_best_only=True)
34
+ model.fit_generator(train_generator(batch_size=4),
35
+ steps_per_epoch=200,
36
+ epochs=50,
37
+ validation_data=train_generator(ba
pairs/pair_19/output.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ tch_size=4),
2
+ validation_steps=50,
3
+ callbacks=[model_checkpoint])
pairs/pair_2/input.txt ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ for idx, frame in enumerate(frames):
2
+ cam_name = os.path.join(path, frame["file_path"] + extension)
3
+
4
+ # NeRF 'transform_matrix' is a camera-to-world transform
5
+ c2w = np.array(frame["transform_matrix"])
6
+ # change from OpenGL/Blender camera axes (Y up, Z back) to COLMAP (Y down, Z forward)
7
+ c2w[:3, 1:3] *= -1
8
+
9
+ # get the world-to-camera transform and set R, T
10
+ w2c = np.linalg.inv(c2w)
11
+ R = np.transpose(w2c[:3,:3]) # R is stored transposed due to 'glm' in CUDA code
12
+ T = w2c[:3, 3]
13
+
14
+ image_path = os.path.join(path, cam_name)
15
+ image_name = Path(cam_name).stem
16
+ image = Image.open(image_path)
17
+
18
+ im_data = np.array(image.convert("RGBA"))
19
+
20
+ bg = np.array([1,1,1]) if white_background else np.array([0, 0, 0])
21
+
22
+ norm_data = im_data / 255.0
23
+ arr = norm_data[:,:,:3] * norm_data[:, :, 3:4] + bg * (1 - norm_data[:, :, 3:4])
24
+ image = Image.fromarray(np.array(arr*255.0, dtype=np.byte), "RGB")
25
+
26
+ fovy = focal2fov(fov2focal(fovx, image.size[0]), image.size[1])
27
+ FovY = fovy
28
+ FovX = fovx
29
+
30
+ cam_infos.append(CameraInfo(uid=idx, R=R, T=T, FovY=FovY, FovX=FovX, image=image,
31
+ image_path=image_path, image_name=image_name, width=image.size[0], height=image.size[1]))
32
+
33
+ return cam_infos
34
+
35
+ def readNerfSyntheticInfo(path, white_background, eval, extension=".png"):
36
+ print("Reading Training Transforms")
37
+ train_cam_infos = readCamerasFromTransforms(path, "transforms_train.json", white_background, extension)
38
+ print("Reading Test Transforms")
39
+ test_cam_infos = readCamerasFromTransforms(path, "transforms_test.json", white_background, extension)
40
+
41
+ if not eval:
42
+ train_cam_infos.extend(test_cam_info
pairs/pair_2/output.txt ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ s)
2
+ test_cam_infos = []
3
+
4
+ nerf_normalization = getNerfppNorm(train_cam_infos)
5
+
6
+ ply_path = os.path.join(path, "points3d.ply")
7
+ if not os.path.exists(ply_path):
8
+ # Since this data set has no colmap data, we start with random points
9
+ num_pts = 100_000
10
+ print(f"Generating random point cloud ({num_pts})...")
11
+
12
+ # We create random points inside the bounds of the synthetic Blender scenes
13
+ xyz = np.random.random((num_pts, 3)) * 2.6 - 1.3
14
+ shs = np.random.random((num_pts, 3)) / 255.0
15
+ pcd = BasicPointCloud(points=xyz, colors=SH2RGB(shs), normals=np.zeros((num_pts, 3)))
16
+
17
+ storePly(ply_path, xyz, SH2RGB(shs) * 255)
18
+ try:
19
+ pcd = fetchPly(ply_path)
20
+ except:
21
+ pcd = None
22
+
23
+ scene_info = SceneInfo(point_cloud=pcd,
24
+ train_cameras=train_cam_infos,
25
+ test_cameras=test_cam_infos,
26
+ nerf_normalization=nerf_normalization,
27
+ ply_path=ply_path)
28
+ return scene_info
29
+
30
+ sceneLoadTypeCallbacks = {
31
+ "Colmap": readColmapSceneInfo,
32
+ "Blender" : readNerfSyntheticInfo
33
+ }
pairs/pair_20/input.txt ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [0, 1, 2, 3, 4, 5, 6],
2
+ ]
3
+
4
+ @classmethod
5
+ def Colors(cls):
6
+ """Returns the list of colors.
7
+ """
8
+ return cls.colors
9
+
10
+ @classmethod
11
+ def ColorGenerator(cls, n):
12
+ """Returns an iterator of color strings.
13
+
14
+ n: how many colors will be used
15
+ """
16
+ for i in cls.which_colors[n]:
17
+ yield cls.colors[i]
18
+ raise StopIteration('Ran out of colors in _Brewer.ColorGenerator')
19
+
20
+ @classmethod
21
+ def InitializeIter(cls, num):
22
+ """Initializes the color iterator with the given number of colors."""
23
+ cls.color_iter = cls.ColorGenerator(num)
24
+
25
+ @classmethod
26
+ def ClearIter(cls):
27
+ """Sets the color iterator to None."""
28
+ cls.color_iter = None
29
+
30
+ @classmethod
31
+ def GetIter(cls):
32
+ """Gets the color iterator."""
33
+ if cls.color_iter is None:
34
+ cls.InitializeIter(7)
35
+
36
+ return cls.color_iter
37
+
38
+
39
+ def PrePlot(num=None, rows=None, cols=None):
40
+ """Takes hints about what's coming.
41
+
42
+ num: number of lines that will be plotted
43
+ rows: number of rows of subplots
44
+ cols: number of columns of subplots
45
+ """
46
+ if num:
47
+ _Brewer.InitializeIter(num)
48
+
49
+ if rows is None and cols is None:
50
+ return
51
+
52
+ if rows is not None and cols is None:
53
+ cols = 1
54
+
55
+ if cols is not None and rows is None:
56
+ rows = 1
57
+
58
+ # resize the image, depending on the number of rows and cols
59
+ size_map = {(1, 1): (8, 6),
60
+ (1, 2): (14, 6),
61
+ (1, 3): (14, 6),
62
+ (2, 2): (10, 10),
63
+ (2, 3): (16, 10),
64
+ (3, 1): (8, 10),
65
+ }
66
+
67
+ if (rows, cols) in size_map:
68
+ fig = pyplot.gcf()
69
+ fig.set_size_inches(*size_map[rows, cols])
70
+
71
+ # create the first subplot
72
+ if rows > 1 or cols > 1:
73
+ pyplot.subplot(rows, cols, 1)
74
+ global SUBPLOT_ROWS, SUBPLOT_COLS
75
+ SUBPLOT_ROWS = rows
76
+ SUBPLOT_COLS = cols
77
+
78
+
79
+ def SubPlot(plot_number, rows=None, cols=None):
80
+ """Configures the number of subplots and changes the current plot.
81
+
82
+ rows: int
83
+ cols: int
84
+ plot_number: int
85
+ """
86
+ rows = rows or SUBPLOT_ROWS
87
+ cols = cols or SUBPLOT_COLS
88
+ pyplot.subplot(rows, cols, plot_number)
89
+
90
+
91
+ def _Underride(d, **options):
92
+ """Add key-value pairs to d only if key is not in d.
93
+
94
+ If d is None, create a new dictionary.
95
+
96
+ d: dictionary
97
+ options: keyword args to add to d
98
+ """
99
+ if d is None:
100
+ d = {}
101
+
102
+ for key, val in options.items():
103
+ d.setdefault(key, val)
104
+
105
+ return d
106
+
107
+
108
+ def Clf():
109
+ """Clears the figure and any hints that have been set."""
110
+ global LOC
111
+ LOC = None
112
+ _Brewer.ClearIter()
113
+ pyplot.clf()
114
+ fig = pyplot.gcf()
115
+ fig.set_size_inches(8, 6)
116
+
117
+
118
+ def Figure(**options):
119
+ """Sets options for the current figure."""
120
+ _Underride(options, figsize=(6, 8))
121
+ pyplot.figure(**options)
122
+
123
+
124
+ def _UnderrideColor(options):
125
+ if 'color' in options:
126
+ return options
127
+
128
+ color_iter = _Brewer.GetIter()
129
+
130
+ if color_iter:
131
+ try:
132
+ options['color'] = next(color_iter)
133
+ except StopIteration:
134
+ # TODO: reconsider whether this should warn
135
+ # warnings.warn('Warning: Brewer ran out of colors.')
136
+ _Brewer.ClearIter()
137
+ return options
138
+
139
+
140
+ def Plot(obj, ys=None, style='', **options):
141
+ """Plots a line.
142
+
143
+ Args:
144
+ obj: sequence of x values, or Series, or anything with Render()
145
+ ys: sequence of y values
146
+ style: style string passed along to pyplot.plot
147
+ options: keyword args passed to pyplot.plot
148
+ """
149
+ options = _UnderrideColor(options)
150
+ label = getattr(obj, 'label', '_nolegend_')
151
+ options = _Underride(options, linewidth=3, alpha=0.8, label=label)
152
+
153
+ xs = obj
154
+ if ys is None:
155
+ if hasattr(obj, 'Render'):
156
+ xs, ys = obj.Render()
157
+ if isinstance(obj, pandas.Series):
158
+ ys = obj.values
159
+ xs = obj.index
160
+
161
+ if ys is None:
162
+ pyplot.plot(xs, style, **options)
163
+ else:
164
+ pyplot.plot(xs, ys, style, **options)
165
+
166
+
167
+ def FillBetween(xs, y1, y2=None, where=None, **options):
168
+ """Plots a line.
169
+
170
+ Args:
171
+ xs: sequence of x values
172
+ y1: sequence of y values
173
+ y2: sequence of y values
174
+ where: sequence of boolean
175
+ options: keyword args passed to pyplot.fill_between
176
+ """
177
+ options = _UnderrideColor(options)
178
+ options = _Underride(options, linewidth=0, alpha=0.5)
179
+ pyplot.fill_between(xs, y1, y2, where, **options)
180
+
181
+
182
+ def Bar(xs, ys, **options):
183
+ """Plots a line.
184
+
185
+ Args:
186
+ xs: sequence of x values
187
+ ys: sequence of y values
188
+ options: keyword args passed to pyplot.bar
189
+ """
190
+ options = _UnderrideColor(options)
191
+ options = _Underride(options, linewidth=0, alpha=0.6)
192
+ pyplot.bar(xs, ys, **options)
193
+
194
+
195
+ def Scatter(xs, ys=None, **options):
196
+ """Makes a scatter plot.
197
+
198
+ xs: x values
199
+ ys: y values
200
+ options: options passed to pyplot.scatter
201
+ """
202
+ options = _Underride(options, color='blue', alpha=0.2,
203
+ s=30, edgecolors='none')
204
+
205
+ if ys is None and isinstance(xs, pandas.Series):
206
+ ys = xs.values
207
+ xs = xs.index
208
+
209
+ pyplot.scatter(xs, ys, **options)
210
+
211
+
212
+ def HexBin(xs, ys, **options):
213
+ """Makes a scatter plot.
214
+
215
+ xs: x values
216
+ ys: y values
217
+ options: options passed to pyplot.scatter
218
+ """
219
+ options = _Underride(options, cmap=matplotlib.cm.Blues)
220
+ pyplot.hexbin(xs, ys, **options)
221
+
222
+
223
+ def Pdf(pdf, **options):
224
+ """Plots a Pdf, Pmf, or Hist as a line.
225
+
226
+ Args:
227
+ pdf: Pdf, Pmf, or Hist object
228
+ options: keyword args passed to pyplot.plot
229
+ """
230
+ low, high = options.pop('low', None), options.pop('high', None)
231
+ n = options.pop('n', 101)
232
+ xs, ps = pdf.Render(low=low, high=high, n=n)
233
+ options = _Underride(options, label=pdf.label)
234
+ Plot(xs, ps, **options)
235
+
236
+
237
+ def Pdfs(pdfs, **options):
238
+ """Plots a sequence of PDFs.
239
+
240
+ Options are passed along for all PDFs. If you want different
241
+ options for each pdf, make multiple calls to Pdf.
242
+
243
+ Args:
244
+ pdfs: sequence of PDF objects
245
+ options: keyword args passed to pyplot.plot
246
+ """
247
+ for pdf in pdfs:
248
+ Pdf(pdf, **options)
249
+
250
+
251
+ def Hist(hist, **options):
252
+ """Plots a Pmf or Hist with a bar plot.
253
+
254
+ The default width of the bars is based on the minimum difference
255
+ between values in the Hist. If that's too small, you can override
256
+ it by providing a width keyword argument, in the same units
257
+ as the values.
258
+
259
+ Args:
260
+ hist: Hist or Pmf object
261
+ options: keyword args passed to pyplot.bar
262
+ """
263
+ # find the minimum distance between adjacent values
264
+ xs, ys = hist.Render()
265
+
266
+ if 'width' not in options:
267
+ try:
268
+ options['width'] = 0.9 * np.diff(xs).min()
269
+ except TypeError:
270
+ warnings.warn("Hist: Can't compute bar width automatically."
271
+ "Check for non-numeric types in Hist."
272
+ "Or try providing width option."
273
+ )
274
+
275
+ options = _Underride(options, label=hist.label)
276
+ options = _Underride(options, align='center')
277
+ if options['align'] == 'left':
278
+ options['align'] = 'edge'
279
+ elif options['align'] == 'right':
280
+ options['align'] = 'edge'
281
+ options['width'] *= -1
282
+
283
+ Bar(xs, ys, **options)
284
+
285
+
286
+ def Hists(hists, **options):
287
+ """Plots two histograms as interleaved bar plots.
288
+
289
+ Options are passed along for all PMFs. If you want different
290
+ options for each pmf, make multiple calls to Pmf.
291
+
292
+ Args:
293
+ hists: list of two Hist or Pmf objects
294
+ options: keyword args passed to pyplot.plot
295
+ """
296
+ for hist in hists:
297
+ Hist(hist, **options)
298
+
299
+
300
+ def Pmf(pmf, **options):
301
+ """Plots a Pmf or Hist as a line.
302
+
303
+ Args:
304
+ pmf: Hist or Pmf object
305
+ options: keyword args passed to pyplot.plot
306
+ """
307
+ xs, ys = pmf.Render()
308
+ low, high = min(xs), max(xs)
309
+
310
+ width = options.pop('width', None)
311
+ if width is None:
312
+ try:
313
+ width = np.diff(xs).min()
314
+ except TypeError:
315
+ warnings.warn("Pmf: Can't compute bar width automatically."
316
+ "Check for non-numeric types in Pmf."
317
+
pairs/pair_20/output.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ "Or try providing width option.")
pairs/pair_21/input.txt ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ m most common place
2
+ if len(train_df.Embarked[ train_df.Embarked.isnull() ]) > 0:
3
+ train_df.Embarked[ train_df.Embarked.isnull() ] = train_df.Embarked.dropna().mode().values
4
+
5
+ Ports = list(enumerate(np.unique(train_df['Embarked']))) # determine all values of Embarked,
6
+ Ports_dict = { name : i for i, name in Ports } # set up a dictionary in the form Ports : index
7
+ train_df.Embarked = train_df.Embarked.map( lambda x: Ports_dict[x]).astype(int) # Convert all Embark strings to int
8
+
9
+ # All the ages with no data -> make the median of all Ages
10
+ median_age = train_df['Age'].dropna().median()
11
+ if len(train_df.Age[ train_df.Age.isnull() ]) > 0:
12
+ train_df.loc[ (train_df.Age.isnull()), 'Age'] = median_age
13
+
14
+ # Remove the Name column, Cabin, Ticket, and Sex (since I copied and filled it to Gender)
15
+ train_df = train_df.drop(['Name', 'Sex', 'Ticket', 'Cabin', 'PassengerId'], axis=1)
16
+
17
+
18
+ # TEST DATA
19
+ test_df = pd.read_csv('test.csv', header=0) # Load the test file into a dataframe
20
+
21
+ # I need to do the same with the test data now, so that the columns are the same as the training data
22
+ # I need to convert all strings to integer classifiers:
23
+ # female = 0, Male = 1
24
+ test_df['Gender'] = test_df['Sex'].map( {'female': 0, 'male': 1} ).astype(int)
25
+
26
+ # Embarked from 'C', 'Q', 'S'
27
+ # All missing Embarked -> just make them embark from most common place
28
+ if len(test_df.Embarked[ test_df.Embarked.isnull() ]) > 0:
29
+ test_df.Embarked[ test_df.Embarked.isnull() ] = test_df.Embarked.dropna().mode().values
30
+ # Again convert all Embarked strings to int
31
+ test_df.Embarked = test_df.Embarked.map( lambda x: Ports_dict[x]).astype(int)
32
+
33
+
34
+ # All the ages with no data -> make the median of all Ages
35
+ median_age = test_df['Age'].dropna().median()
36
+ if len(test_df.Age[ test_df.Age.isnull() ]) > 0:
37
+ test_df.loc[ (test_df.Age.isnull()), 'Age'] = median_age
38
+
39
+ # All the missing Fares -> assume median of their respective class
40
+ if len(test_df.Fare[ test_df.Fare.isnull() ]) > 0:
41
+ median_fare = np.zeros(3)
42
+ for f in range(0,3): # loop 0 to 2
43
+ median_fare[f] = test_df[ test_df.Pclass == f+1 ]['Fare'].dropna().median()
44
+ for f in range(0,3): # loop 0 to 2
45
+ test_df.loc[ (test_df.Fare.isnull()) & (test_df.Pclass == f+1 ), 'Fare'] = median_fare[f]
46
+
47
+ # Collect the test data's PassengerIds before dropping it
48
+ ids = test_df['PassengerId'].values
49
+ # Remove the Name column, Cabin, Ticket, and Sex (since I copied and filled it to Gender)
50
+ test_df = test_df.drop(['Name', 'Sex', 'Ticket', 'Cabin', 'Passen
pairs/pair_21/output.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ gerId'], axis=1)
pairs/pair_22/input.txt ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ xs, n=None):
2
+ """Draw a sample from xs with the same length as xs.
3
+
4
+ xs: sequence
5
+ n: sample size (default: len(xs))
6
+
7
+ returns: NumPy array
8
+ """
9
+ if n is None:
10
+ n = len(xs)
11
+ return np.random.choice(xs, n, replace=True)
12
+
13
+
14
+ def SampleRows(df, nrows, replace=False):
15
+ """Choose a sample of rows from a DataFrame.
16
+
17
+ df: DataFrame
18
+ nrows: number of rows
19
+ replace: whether to sample with replacement
20
+
21
+ returns: DataDf
22
+ """
23
+ indices = np.random.choice(df.index, nrows, replace=replace)
24
+ sample = df.loc[indices]
25
+ return sample
26
+
27
+
28
+ def ResampleRows(df):
29
+ """Resamples rows from a DataFrame.
30
+
31
+ df: DataFrame
32
+
33
+ returns: DataFrame
34
+ """
35
+ return SampleRows(df, len(df), replace=True)
36
+
37
+
38
+ def ResampleRowsWeighted(df, column='finalwgt'):
39
+ """Resamples a DataFrame using probabilities proportional to given column.
40
+
41
+ df: DataFrame
42
+ column: string column name to use as weights
43
+
44
+ returns: DataFrame
45
+ """
46
+ weights = df[column]
47
+ cdf = Cdf(dict(weights))
48
+ indices = cdf.Sample(len(weights))
49
+ sample = df.loc[indices]
50
+ return sample
51
+
52
+
53
+ def PercentileRow(array, p):
54
+ """Selects the row from a sorted array that maps to percentile p.
55
+
56
+ p: float 0--100
57
+
58
+ returns: NumPy array (one row)
59
+ """
60
+ rows, cols = array.shape
61
+ index = int(rows * p / 100)
62
+ return array[index,]
63
+
64
+
65
+ def PercentileRows(ys_seq, percents):
66
+ """Given a collection of lines, selects percentiles along vertical axis.
67
+
68
+ For example, if ys_seq contains simulation results like ys as a
69
+ function of time, and percents contains (5, 95), the result would
70
+ be a 90% CI for each vertical slice of the simulation results.
71
+
72
+ ys_seq: sequence of lines (y values)
73
+ percents: list of percentiles (0-100) to select
74
+
75
+ returns: list of NumPy arrays, one for each pe
pairs/pair_22/output.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ rcentile
2
+ """
3
+ nrows = len(ys_seq)
4
+ ncols = len(ys_seq[0])
5
+ array = np.zeros((nrows, ncols))
6
+
7
+ for i, ys in enumerate(ys_seq):
8
+ array[i,] = ys
9
+
10
+ array = np.sort(array, axis=0)
11
+
12
+ rows = [PercentileRow(array, p) for p in percents]
13
+ return rows
pairs/pair_23/input.txt ADDED
@@ -0,0 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .
2
+
3
+ other: a number
4
+
5
+ returns: new Pmf
6
+ """
7
+ pmf = Pmf()
8
+ for v1, p1 in self.Items():
9
+ pmf.Set(v1 + other, p1)
10
+ return pmf
11
+
12
+ def __sub__(self, other):
13
+ """Computes the Pmf of the diff of values drawn from self and other.
14
+
15
+ other: another Pmf
16
+
17
+ returns: new Pmf
18
+ """
19
+ try:
20
+ return self.SubPmf(other)
21
+ except AttributeError:
22
+ return self.AddConstant(-other)
23
+
24
+ def SubPmf(self, other):
25
+ """Computes the Pmf of the diff of values drawn from self and other.
26
+
27
+ other: another Pmf
28
+
29
+ returns: new Pmf
30
+ """
31
+ pmf = Pmf()
32
+ for v1, p1 in self.Items():
33
+ for v2, p2 in other.Items():
34
+ pmf.Incr(v1 - v2, p1 * p2)
35
+ return pmf
36
+
37
+ def __mul__(self, other):
38
+ """Computes the Pmf of the product of values drawn from self and other.
39
+
40
+ other: another Pmf
41
+
42
+ returns: new Pmf
43
+ """
44
+ try:
45
+ return self.MulPmf(other)
46
+ except AttributeError:
47
+ return self.MulConstant(other)
48
+
49
+ def MulPmf(self, other):
50
+ """Computes the Pmf of the diff of values drawn from self and other.
51
+
52
+ other: another Pmf
53
+
54
+ returns: new Pmf
55
+ """
56
+ pmf = Pmf()
57
+ for v1, p1 in self.Items():
58
+ for v2, p2 in other.Items():
59
+ pmf.Incr(v1 * v2, p1 * p2)
60
+ return pmf
61
+
62
+ def MulConstant(self, other):
63
+ """Computes the Pmf of the product of a constant and values from self.
64
+
65
+ other: a number
66
+
67
+ returns: new Pmf
68
+ """
69
+ pmf = Pmf()
70
+ for v1, p1 in self.Items():
71
+ pmf.Set(v1 * other, p1)
72
+ return pmf
73
+
74
+ def __div__(self, other):
75
+ """Computes the Pmf of the ratio of values drawn from self and other.
76
+
77
+ other: another Pmf
78
+
79
+ returns: new Pmf
80
+ """
81
+ try:
82
+ return self.DivPmf(other)
83
+ except AttributeError:
84
+ return self.MulConstant(1/other)
85
+
86
+ __truediv__ = __div__
87
+
88
+ def DivPmf(self, other):
89
+ """Computes the Pmf of the ratio of values drawn from self and other.
90
+
91
+ other: another Pmf
92
+
93
+ returns: new Pmf
94
+ """
95
+ pmf = Pmf()
96
+ for v1, p1 in self.Items():
97
+ for v2, p2 in other.Items():
98
+ pmf.Incr(v1 / v2, p1 * p2)
99
+ return pmf
100
+
101
+ def Max(self, k):
102
+ """Computes the CDF of the maximum of k selections from this dist.
103
+
104
+ k: int
105
+
106
+ returns: new Cdf
107
+ """
108
+ cdf = self.MakeCdf()
109
+ return cdf.Max(k)
110
+
111
+
112
+ class Joint(Pmf):
113
+ """Represents a joint distribution.
114
+
115
+ The values are sequences (usually tuples)
116
+ """
117
+
118
+ def Marginal(self, i, label=None):
119
+ """Gets the marginal distribution of the indicated variable.
120
+
121
+ i: index of the variable we want
122
+
123
+ Returns: Pmf
124
+ """
125
+ pmf = Pmf(label=label)
126
+ for vs, prob in self.Items():
127
+ pmf.Incr(vs[i], prob)
128
+ return pmf
129
+
130
+ def Conditional(self, i, j, val, label=None):
131
+ """Gets the conditional distribution of the indicated variable.
132
+
133
+ Distribution of vs[i], conditioned on vs[j] = val.
134
+
135
+ i: index of the variable we want
136
+ j: which variable is conditioned on
137
+ val: the value the jth variable has to have
138
+
139
+ Returns: Pmf
140
+ """
141
+ pmf = Pmf(label=label)
142
+ for vs, prob in self.Items():
143
+ if vs[j] != val:
144
+ continue
145
+ pmf.Incr(vs[i], prob)
146
+
147
+ pmf.Normalize()
148
+ return pmf
149
+
150
+ def MaxLikeInterval(self, percentage=90):
151
+ """Returns the maximum-likelihood credible interval.
152
+
153
+ If percentage=90, computes a 90% CI containing the values
154
+ with the highest likelihoods.
155
+
156
+ percentage: float between 0 and 100
157
+
158
+ Returns: list of values from the suite
159
+ """
160
+ interval = []
161
+ total = 0
162
+
163
+ t = [(prob, val) for val, prob in self.Items()]
164
+ t.sort(reverse=True)
165
+
166
+ for prob, val in t:
167
+ interval.append(val)
168
+ total += prob
169
+ if total >= percentage / 100.0:
170
+ break
171
+
172
+ return interval
173
+
174
+
175
+ def MakeJoint(pmf1, pmf2):
176
+ """Joint distribution of values from pmf1 and pmf2.
177
+
178
+ Assumes that the PMFs represent independent random variables.
179
+
180
+ Args:
181
+ pmf1: Pmf object
182
+ pmf2: Pmf object
183
+
184
+ Returns:
185
+ Joint pmf of value pairs
186
+ """
187
+ joint = Joint()
188
+ for v1, p1 in pmf1.Items():
189
+ for v2, p2 in pmf2.Items():
190
+ joint.Set((v1, v2), p1 * p2)
191
+ return joint
192
+
193
+
194
+ def MakeHistFromList(t, label=None):
195
+ """Makes a histogram from an unsorted sequence of values.
196
+
197
+ Args:
198
+ t: sequence of numbers
199
+ label: string label for this histogram
200
+
201
+ Returns:
202
+ Hist object
203
+ """
204
+ return Hist(t, label=label)
205
+
206
+
207
+ def MakeHistFromDict(d, label=None):
208
+ """Makes a histogram from a map from values to frequencies.
209
+
210
+ Args:
211
+ d: dictionary that maps values to frequencies
212
+ label: string label for this histogram
213
+
214
+ Returns:
215
+ Hist object
216
+ """
217
+ return Hist(d, label)
218
+
219
+
220
+ def MakePmfFromList(t, label=None):
221
+ """Makes a PMF from an unsorted sequence of values.
222
+
223
+ Args:
224
+ t: sequence of numbers
225
+ label: string label for this PMF
226
+
227
+ Returns:
228
+ Pmf object
229
+ """
230
+ return Pmf(t, label=label)
231
+
232
+
233
+ def MakePmfFromDict(d, label=None):
234
+ """Makes a PMF from a map from values to probabilities.
235
+
236
+ Args:
237
+ d: dictionary that maps values to probabilities
238
+ label: string label for this PMF
239
+
240
+ Returns:
241
+ Pmf object
242
+ """
243
+ return Pmf(d, label=label)
244
+
245
+
246
+ def MakePmfFromItems(t, label=None):
247
+ """Makes a PMF from a sequence of value-probability pairs
248
+
249
+ Args:
250
+ t: sequence of value-probability pairs
251
+ label: string label for this PMF
252
+
253
+ Returns:
254
+ Pmf object
255
+ """
256
+ return Pmf(dict(t), label=label)
257
+
258
+
259
+ def MakePmfFromHist(hist, label=None):
260
+ """Makes a normalized PMF from a Hist object.
261
+
262
+ Args:
263
+ hist: Hist object
264
+ label: string label
265
+
266
+ Returns:
267
+ Pmf object
268
+ """
269
+ if label is None:
270
+ label = hist.label
271
+
272
+ return Pmf(hist, label=label)
273
+
274
+
275
+ def MakeMixture(metapmf, label='mix'):
276
+ """Make a mixture distribution.
277
+
278
+ Args:
279
+ metapmf: Pmf that maps from Pmfs to probs.
280
+ label: string label for the new Pmf.
281
+
282
+ Returns: Pmf object.
283
+ """
284
+ mix = Pmf(label=label)
285
+ for pmf, p1 in metapmf.Items():
286
+ for x, p2 in pmf.Items():
287
+ mix.Incr(x, p1 * p2)
288
+ return mix
289
+
290
+
291
+ def MakeUniformPmf(low, high, n):
292
+ """Make a uniform Pmf.
293
+
294
+ low: lowest value (inclusive)
295
+ high: highest value (inclusize)
296
+ n: number of values
297
+ """
298
+ pmf = Pmf()
299
+ for x in np.linspace(low, high, n):
300
+ pmf.Set(x, 1)
301
+ pmf.Normalize()
302
+ return pmf
303
+
304
+
305
+ class Cdf(object):
306
+ """Represents a cumulative distribution function.
307
+
308
+ Attributes:
309
+ xs: sequence of values
310
+ ps: sequence of probabilities
311
+ label: string used as a graph label.
312
+ """
313
+ def __init__(self, obj=None, ps=None, label=None):
314
+ """Initializes.
315
+
316
+ If ps is provided, obj must be the corresponding list of values.
317
+
318
+ obj: Hist, Pmf, Cdf, Pdf, dict, pandas Series, list of pairs
319
+ ps: list of cumulative probabilities
320
+ label: string label
321
+ """
322
+ self.label = label if label is not None else '_nolegend_'
323
+
324
+ if isinstance(obj, (_DictWrapper, Cdf, Pdf)):
325
+ if not label:
326
+ self.label = label if label is not None else obj.label
327
+
328
+ if obj is None:
329
+ # caller does not provide obj, make an empty Cdf
330
+ self.xs = np.asarray([])
331
+ self.ps = np.asarray([])
332
+ if ps is not None:
333
+ logging.warning("Cdf: can't pass ps without also passing xs.")
334
+ return
335
+ else:
336
+ # if the caller provides xs and ps, just store them
337
+ if ps is not None:
338
+ if isinstance(ps, str):
339
+ logging.warning("Cdf: ps can't be a string")
340
+
341
+ self.xs = np.asarray(obj)
342
+ self.ps = np.asarray(ps)
343
+ return
344
+
345
+ # caller has provided just obj, not ps
346
+ if isinstance(obj, Cdf):
347
+ self.xs = copy.copy(obj.xs)
348
+ self.ps = copy.copy(obj.ps)
349
+ return
350
+
351
+ if isinstance(obj, _DictWrapper):
352
+ dw = obj
353
+ else:
354
+ dw = Hist(obj)
355
+
356
+ if len(dw) == 0:
357
+ self.xs = np.asarray([])
358
+ self.ps = np.asarray([])
359
+ return
360
+
361
+ xs, freqs = zip(*sorted(dw.Items()))
362
+ self.xs = np.asarray(xs)
363
+ self.ps = np.cumsum(freqs, dtype=np.float)
364
+ self.ps /= self.ps[-1]
365
+
366
+ def __str__(self):
367
+ return 'Cdf(%s, %s)' % (str(self.xs), str(self.ps))
368
+
369
+ __repr__ = __str__
370
+
371
+ def __len__(self):
372
+ return len(self.xs)
373
+
374
+ def __getitem__(self, x):
375
+ return self.Prob(x)
376
+
377
+ def __setitem__(self):
378
+ raise UnimplementedMethodException()
379
+
380
+ def __delitem__(self):
381
+ raise UnimplementedMethodException()
382
+
383
+ def __eq__(self, other):
384
+ return np.all(self.xs == other.xs) and np.all(self.ps == other.ps)
385
+
386
+ def Copy(self, label=None):
387
+ """Returns a copy of this Cdf.
388
+
389
+ label: string label for the new Cdf
390
+ """
391
+ if label is None:
392
+ label = self.label
393
+ return Cdf(list(self.xs), list(self.ps), label=label)
394
+
395
+ def MakePmf(self, label=None):
396
+ """Makes a Pmf."""
397
+ if label is None:
398
+ label = self.label
399
+ return Pmf(self, label=label)
400
+
401
+ def Values(self):
402
+ """Returns a sorted list of values.
403
+ """
404
+ return self.xs
405
+
406
+ def Items(self):
407
+ """Returns a sorted sequence o
pairs/pair_23/output.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ f (value, probability) pairs.
2
+
3
+ Note: in Python3, returns an iterator.
4
+ """
5
+ a = self.ps
6
+ b = np.roll(a, 1)
7
+ b[0] = 0
8
+ return zip(self.xs, a-b)
pairs/pair_24/input.txt ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ except ModuleNotFoundError:
2
+ return False
3
+
4
+ return spec is not None
5
+
6
+
7
+ def repo_dir(name):
8
+ return os.path.join(script_path, dir_repos, name)
9
+
10
+
11
+ def run_pip(command, desc=None, live=default_command_live):
12
+ if args.skip_install:
13
+ return
14
+
15
+ index_url_line = f' --index-url {index_url}' if index_url != '' else ''
16
+ return run(f'"{python}" -m pip {command} --prefer-binary{index_url_line}', desc=f"Installing {desc}", errdesc=f"Couldn't install {desc}", live=live)
17
+
18
+
19
+ def check_run_python(code: str) -> bool:
20
+ result = subprocess.run([python, "-c", code], capture_output=True, shell=False)
21
+ return result.returncode == 0
22
+
23
+
24
+ def git_fix_workspace(dir, name):
25
+ run(f'"{git}" -C "{dir}" fetch --refetch --no-auto-gc', f"Fetching all contents for {name}", f"Couldn't fetch {name}", live=True)
26
+ run(f'"{git}" -C "{dir}" gc --aggressive --prune=now', f"Pruning {name}", f"Couldn't prune {name}", live=True)
27
+ return
28
+
29
+
30
+ def run_git(dir, name, command, desc=None, errdesc=None, custom_env=None, live: bool = default_command_live, autofix=True):
31
+ try:
32
+ return run(f'"{git}" -C "{dir}" {command}', desc=desc, errdesc=errdesc, custom_env=custom_env, live=live)
33
+ except RuntimeError:
34
+ if not auto
pairs/pair_24/output.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ fix:
2
+ raise
3
+
4
+ print(f"{errdesc}, attempting autofix...")
5
+ git_fix_workspace(dir, name)
6
+
7
+ return run(f'"{git}" -C "{dir}" {command}', desc=desc, errdesc=errdesc, custom_env=custom_env, live=live)
pairs/pair_25/input.txt ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ f infer_params(state_dict):
2
+ # this code is copied from https://github.com/victorca25/iNNfer
3
+ scale2x = 0
4
+ scalemin = 6
5
+ n_uplayer = 0
6
+ plus = False
7
+
8
+ for block in list(state_dict):
9
+ parts = block.split(".")
10
+ n_parts = len(parts)
11
+ if n_parts == 5 and parts[2] == "sub":
12
+ nb = int(parts[3])
13
+ elif n_parts == 3:
14
+ part_num = int(parts[1])
15
+ if (part_num > scalemin
16
+ and parts[0] == "model"
17
+ and parts[2] == "weight"):
18
+ scale2x += 1
19
+ if part_num > n_uplayer:
20
+ n_uplayer = part_num
21
+ out_nc = state_dict[block].shape[0]
22
+ if not plus and "conv1x1" in block:
23
+ plus = True
24
+
25
+ nf = state_dict["model.0.weight"].shape[0]
26
+ in_nc = state_dict["model.0.weight"].shape[1]
27
+ out_nc = out_nc
28
+ scale = 2 ** scale2x
29
+
30
+ return in_nc, out_nc, nf, nb, plus, scale
31
+
32
+
33
+ class UpscalerESRGAN(Upscaler):
34
+ def __init__(self, dirname):
35
+ self.name = "ESRGAN"
36
+ self.model_url = "https://github.com/cszn/KAIR/releases/download/v1.0/ESRGAN.pth"
37
+ self.model_name = "ESRGAN_4x"
38
+ self.scalers = []
39
+ self.user_path = dirname
40
+ super().__init__()
41
+ model_paths = self.find_models(ext_filter=[".pt", ".pth"])
42
+ scalers = []
43
+ if len(model_paths) == 0:
44
+ scaler_data = UpscalerData(self.model_name, self.model_url, self, 4)
45
+ scalers.append(scaler_data)
46
+ for file in model_paths:
47
+ if file.startswith("http"):
48
+ name = self.model_name
49
+ else:
50
+ name = modelloader.friendly_name(file)
51
+
52
+ scaler_data = UpscalerData(name, file, self, 4)
53
+ self.scalers.append(scaler_data)
54
+
55
+ def do_upscale(self, img, selected_model):
56
+ try:
57
+ model = self.load_model(selected_model)
58
+ except Exception as e:
59
+ print(f"Unable to load ESRGAN model {selected_model}: {e}", file=sys.stderr)
60
+ return img
61
+ model.to(devices.device_esrgan)
62
+ img = esrgan_upscale(model, img)
63
+ return img
64
+
65
+ def load_model(self, path: str):
66
+ if path.startswith("http"):
67
+ # TODO: this doesn't use `path` at all?
68
+ filename = modelloader.load_file_from_url(
69
+ url=self.model_url,
70
+ model_dir=self.model_download_path,
71
+ file_name=f"{self.model_name}.pth",
72
+ )
73
+ else:
74
+ filename = path
75
+
76
+ state_
pairs/pair_25/output.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ dict = torch.load(filename, map_location='cpu' if devices.device_esrgan.type == 'mps' else None)
pairs/pair_26/input.txt ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ elf.all_negative_prompts]
2
+
3
+ self.main_prompt = self.all_prompts[0]
4
+ self.main_negative_prompt = self.all_negative_prompts[0]
5
+
6
+ def cached_params(self, required_prompts, steps, extra_network_data, hires_steps=None, use_old_scheduling=False):
7
+ """Returns parameters that invalidate the cond cache if changed"""
8
+
9
+ return (
10
+ required_prompts,
11
+ steps,
12
+ hires_steps,
13
+ use_old_scheduling,
14
+ opts.CLIP_stop_at_last_layers,
15
+ shared.sd_model.sd_checkpoint_info,
16
+ extra_network_data,
17
+ opts.sdxl_crop_left,
18
+ opts.sdxl_crop_top,
19
+ self.width,
20
+ self.height,
21
+ )
22
+
23
+ def get_conds_with_caching(self, function, required_prompts, steps, caches, extra_network_data, hires_steps=None):
24
+ """
25
+ Returns the result of calling function(shared.sd_model, required_prompts, steps)
26
+ using a cache to store the result if the same arguments have been used before.
27
+
28
+ cache is an array containing two elements. The first element is a tuple
29
+ representing the previously used arguments, or None if no arguments
30
+ have been used before. The second element is where the previously
31
+ computed result is stored.
32
+
33
+ caches is a list with items described above.
34
+ """
35
+
36
+ if shared.opts.use_old_scheduling:
37
+ old_schedules = prompt_parser.get_learned_conditioning_prompt_schedules(required_prompts, steps, hires_steps, False)
38
+ new_schedules = prompt_parser.get_learned_conditioning_prompt_schedules(required_prompts, steps, hires_steps, True)
39
+ if old_schedules != new_schedules:
40
+ self.extra_generation_params["Old prompt editing timelines"] = True
41
+
42
+ cached_params = self.cached_params(required_prompts, steps, extra_network_data, hires_steps, shared.opts.use_old_scheduling)
43
+
44
+ for cache in caches:
45
+ if cache[0] is not None and cached_params == cache[0]:
46
+ return cache[1]
47
+
48
+ cache = caches[0]
49
+
50
+ with devices.autocast():
51
+ cache[1] = function(shared.sd_model, required_prompts, steps, hires_steps, shared.opts.use_old_scheduling)
52
+
53
+ cache[0] = cached_params
54
+ return cache[1]
55
+
56
+ def setup_conds(self):
57
+ prompts = prompt_parser.SdConditioning(self.prompts, width=self.width, height=self.height)
58
+ negative_prompts = prompt_parser.SdConditioning(self.negative_prompts, width=self.width, height=self.height, is_negative_prompt=True)
59
+
60
+ sampler_config = sd_samplers.find_sampler_config(self.sampler_name)
61
+ total_steps = sampler_config.total_steps(self.steps) if sampler_config else self.steps
62
+ self.step_multiplier = total_steps // self.steps
63
+ self.firstpass_steps = total_steps
64
+
65
+ self.uc = self.get_conds_with_caching(prompt_parser.get_learned_conditioning, negative_prompts, total_steps, [self.cached_uc], self.extra_network_data)
66
+ self.c = self.get_conds_with_caching(prompt_parser.get_multicond_learned_conditioning, prompts, total_steps, [self.cached_c], self.extra_network_data)
67
+
68
+ def get_conds(self):
69
+ return self.c, self.uc
70
+
71
+ def parse_extra_network_prompts(self):
72
+ self.prompts, self.extra_network_data = extra_networks.parse_prompts(self.prompts)
73
+
74
+ def save_samples(self) -> bool:
75
+ """Returns whether generated images need to be written to disk"""
76
+ return opts.samples_save and not self.do_not_save_samples and (opts.save_incomplete_images or not state.interrupted and not state.skipped)
77
+
78
+
79
+ class Processed:
80
+ def __init__(self, p: StableDiffusionProcessing, images_list, seed=-1, info="", subseed=None, all_prompts=None, all_negative_prompts=None, all_seeds=None, all_subseeds=None, index_of_first_image=0, infotexts=None, comments=""):
81
+ self.images = images_list
82
+ self.prompt = p.prompt
83
+ self.negative_prompt = p.negative_prompt
84
+ self.seed = seed
85
+ self.subseed = subseed
86
+ self.subseed_strength = p.subseed_strength
87
+ self.info = info
88
+ self.comments = "".join(f"{comment}\n" for comment in p.comments)
89
+ self.width = p.width
90
+ self.height = p.height
91
+ self.sampler_name = p.sampler_name
92
+ self.cfg_scale = p.cfg_scale
93
+ self.image_cfg_scale = getattr(p, 'image_cfg_scale', None)
94
+ self.steps = p.steps
95
+ self.batch_size = p.batch_size
96
+ self.restore_faces = p.restore_faces
97
+ self.face_restoration_model = opts.face_restoration_model if p.restore_faces else None
98
+ self.sd_model_name = p.sd_model_name
99
+ self.sd_model_hash = p.sd_model_hash
100
+ self.sd_vae_name = p.sd_vae_name
101
+ self.sd_vae_hash = p.sd_vae_hash
102
+ self.seed_resize_from_w = p.seed_resize_from_w
103
+ self.seed_resize_from_h = p.seed_resize_from_h
104
+ self.den
pairs/pair_26/output.txt ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ oising_strength = getattr(p, 'denoising_strength', None)
2
+ self.extra_generation_params = p.extra_generation_params
3
+ self.index_of_first_image = index_of_first_image
4
+ self.styles = p.styles
5
+ self.job_timestamp = state.job_timestamp
6
+ self.clip_skip = opts.CLIP_stop_at_last_layers
7
+ self.token_merging_ratio = p.token_merging_ratio
8
+ self.token_merging_ratio_hr = p.token_merging_ratio_hr
9
+
10
+ self.eta = p.eta
11
+ self.ddim_discretize = p.ddim_discretize
12
+ self.s_churn = p.s_churn
13
+ self.s_tmin = p.s_tmin
14
+ self.s_tmax = p.s_tmax
15
+ self.s_noise = p.s_noise
16
+ self.s_min_uncond = p.s_min_uncond
17
+ self.sampler_noise_scheduler_override = p.sampler_noise_scheduler_override
18
+ self.prompt = self.prompt if not isinstance(self.prompt, list) else self.prompt[0]
19
+ self.negative_prompt = self.negative_prompt if not isinstance(self.negative_prompt, list) else self.negative_prompt[0]
20
+ self.seed = int(self.seed if not isinstance(self.seed, list) else self.seed[0]) if self.seed is not None else -1
21
+ self.subseed = int(self.subseed if not isinstance(self.subseed, list) else self.subseed[0]) if self.subseed is not None else -1
22
+ self.is_using_inpainting_conditioning = p.is_using_inpainting_conditioning
23
+
24
+ self.all_prompts = all_prompts or p.all_prompts or [self.prompt]
25
+ self.all_negative_prompts = all_negative_prompts or p.all_negative_prompts or [self.negative_prompt]
26
+ self.all_seeds = all_seeds or p.all_seeds or [self.seed]
27
+ self.all_subseeds = all_subseeds or p.all_subseeds or [self.subseed]
28
+ self.infotexts = infotexts or [info]
pairs/pair_27/input.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import json
3
+ import logging
4
+ import math
pairs/pair_27/output.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import hashlib
4
+ from dataclasses import dataclass, field
pairs/pair_28/input.txt ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Reproductions/tests for crashes/read errors in TiffDecode.c
2
+
3
+ # When run in Python, all of these images should fail for
4
+ # one reason or another, either as a buffer overrun,
5
+ # unrecognized datastream, or truncated image file.
6
+ # There shouldn't be any segfaults.
7
+ #
8
+ # if run like
9
+ # `valgrind --tool=memcheck pytest test_tiff_crashes.py 2>&1 | grep TiffDecode.c`
10
+ # the output should be empty. There may be Python issues
11
+ # in the valgrind especially if run in a debug Python
12
+ # version.
13
+
14
+ import pytest
15
+
16
+ from PIL import Image
17
+
18
+ from .helper import on_ci
19
+
20
+
21
+ @pytest.mark.parametrize(
22
+ "test_file",
23
+ [
24
+ "Tests/images/crash_1.tif",
25
+ "Tests/images/crash_2.tif",
26
+ "Tests/images/crash-2020-10-test.tif",
27
+ "Tests/images/crash-0c7e0e8e11ce787078f00b5b0ca409a167f070e0.tif",
28
+ "Tests/images/crash-0e16d3bfb83be87356d026d66919deaefca44dac.tif",
29
+ "Tests/images/crash-1152ec2d1a1a71395b6f2ce6721c38924d025bf3.tif",
30
+ "Tests/images/crash-1185209cf7655b5aed8ae5e77784dfdd18ab59e9.tif",
31
+ "Tests/images/crash-338516dbd2f0e83caddb8ce256c22db3bd6dc40f.tif",
32
+ "Tests/images/crash-4f085cc12ece8cde18758d42608bed6a2a2cfb1c.tif",
33
+ "Tests/images/crash-86214e58da443d2b80820cff9677a38a33dcbbca.tif",
34
+ "Tests/images/crash-f46f5b2f43c370fe65706c11449f567ecc345e74.tif",
35
+ "T
pairs/pair_28/output.txt ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ests/images/crash-63b1dffefc8c075ddc606c0a2f5fdc15ece78863.tif",
2
+ "Tests/images/crash-74d2a78403a5a59db1fb0a2b8735ac068a75f6e3.tif",
3
+ "Tests/images/crash-81154a65438ba5aaeca73fd502fa4850fbde60f8.tif",
4
+ "Tests/images/crash-0da013a13571cc8eb457a39fee8db18f8a3c7127.tif",
5
+ ],
6
+ )
7
+ @pytest.mark.filterwarnings("ignore:Possibly corrupt EXIF data")
8
+ @pytest.mark.filterwarnings("ignore:Metadata warning")
9
+ @pytest.mark.filterwarnings("ignore:Truncated File Read")
10
+ def test_tiff_crashes(test_file):
11
+ try:
12
+ with Image.open(test_file) as im:
13
+ im.load()
14
+ except FileNotFoundError:
15
+ if not on_ci():
16
+ pytest.skip("test image not found")
17
+ return
18
+ raise
19
+ except OSError:
20
+ pass
pairs/pair_29/input.txt ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ent"] = s
2
+ self.app["COM"] = s # compatibility
3
+ self.applist.append(("COM", s))
4
+
5
+
6
+ def SOF(self, marker):
7
+ #
8
+ # Start of frame marker. Defines the size and mode of the
9
+ # image. JPEG is colour blind, so we use some simple
10
+ # heuristics to map the number of layers to an appropriate
11
+ # mode. Note that this could be made a bit brighter, by
12
+ # looking for JFIF and Adobe APP markers.
13
+
14
+ n = i16(self.fp.read(2)) - 2
15
+ s = ImageFile._safe_read(self.fp, n)
16
+ self._size = i16(s, 3), i16(s, 1)
17
+
18
+ self.bits = s[0]
19
+ if self.bits != 8:
20
+ msg = f"cannot handle {self.bits}-bit layers"
21
+ raise SyntaxError(msg)
22
+
23
+ self.layers = s[5]
24
+ if self.layers == 1:
25
+ self._mode = "L"
26
+ elif self.layers == 3:
27
+ self._mode = "RGB"
28
+ elif self.layers == 4:
29
+ self._mode = "CMYK"
30
+ else:
31
+ msg = f"cannot handle {self.layers}-layer images"
32
+ raise SyntaxError(msg)
33
+
34
+ if marker in [0xFFC2, 0xFFC6, 0xFFCA, 0xFFCE]:
35
+ self.info["progressive"] = self.info["progression"] = 1
36
+
37
+ if self.icclist:
38
+ # fixup icc profile
39
+ self.icclist.sort() # sort by sequence number
40
+ if self.icclist[0][13] == len(self.icclist):
41
+ profile = []
42
+ for p in self.icclist:
43
+ profile.append(p[14:])
44
+ icc_profile = b"".join(profile)
45
+ else:
46
+ icc_profile = None # wrong number of fragments
47
+ self.info["icc_profile"] = icc_profile
48
+ self.icclist = []
49
+
50
+ for i in range(6, len(s), 3):
51
+ t = s[i : i + 3]
52
+ # 4-tuples: id, vsamp, hsamp, qtable
53
+ self.layer.append((t[0], t[1] // 16, t[1] & 15, t[2]))
54
+
55
+
56
+ def DQT(self, marker):
57
+ #
58
+ # Define quantization table. Note that there might be more
59
+ # than one table in each marker.
60
+
61
+ # FIXME: The quantization tables can be used to estimate the
62
+ # compression quality.
63
+
64
+ n = i16(self.fp.read(2)) - 2
65
+ s = ImageFile._safe_read(self.fp, n)
66
+ while len(s):
67
+ v = s[0]
68
+ precision = 1 if (v // 16 == 0) else 2 # in bytes
69
+ qt_length = 1 + precision * 64
70
+ if len(s) < qt_length:
71
+ msg = "bad quantization table marker"
72
+ raise SyntaxError(msg)
73
+ data = array.array("B" if precision == 1 else "H", s[1:qt_length])
74
+ if sys.byteorder == "little" and precision > 1:
75
+ data.byteswap() # the values are always big-endian
76
+ self.quantization[v & 15] = [data[i] for i in zigzag_index]
77
+ s = s[qt_length:]
78
+
79
+
80
+ #
81
+ # JPEG marker table
82
+
83
+ MARKER = {
84
+ 0xFFC0: ("SOF0", "Baseline DCT", SOF),
85
+ 0xFFC1: ("SOF1", "Extended Sequential DCT", SOF),
86
+ 0xFFC2: ("SOF2", "Progressive DCT", SOF),
87
+ 0xFFC3: ("SOF3", "Spatial lossless", SOF),
88
+ 0xFFC4: ("DHT", "Define Huffman table", Skip),
89
+ 0xFFC5: ("SOF5", "Differential sequential DCT", SOF),
90
+ 0xFFC6: ("SOF6", "Differential progressive DCT", SOF),
91
+ 0xFFC7: ("SOF7", "Differential spatial", SOF),
92
+ 0xFFC8: ("JPG", "Extension", None),
93
+ 0xFFC9: ("SOF9", "Extended sequential DCT (AC)", SOF),
94
+ 0xFFCA: ("SOF10", "Progressive DCT (AC)", SOF),
95
+ 0xFFCB: ("SOF11", "Spatial lossless DCT (AC)", SOF),
96
+ 0xFFCC: ("DAC", "Define arithmetic coding conditioning", Skip),
97
+ 0xFFCD: ("SOF13", "Differential sequential DCT (AC)", SOF),
98
+ 0xFFCE: ("SOF14", "Differential progressive DCT (AC)", SOF),
99
+ 0xFFCF: ("SOF15", "Differential spatial (AC)", SOF),
100
+ 0xFFD0: ("RST0", "Restart 0", None),
101
+ 0xFFD1: ("RST1", "Restart 1", None),
102
+ 0xFFD2: ("RST2", "Restart 2", None),
103
+ 0xFFD3: ("RST3", "Restart 3", None),
104
+ 0xFFD4: ("RST4", "Restart 4", None),
105
+ 0xFFD5: ("RST5", "Restart 5", None),
106
+ 0xFFD6: ("RST6", "Restart 6", None),
107
+ 0xFFD7: ("RST7", "Restart 7", None),
108
+ 0xFFD8: ("SOI", "Start of image", None),
109
+ 0xFFD9: ("EOI", "End of image", None),
110
+ 0xFFDA: ("SOS", "Start of scan", Skip),
111
+ 0xFFDB: ("DQT", "Define quantization table", DQT),
112
+ 0xFFDC: ("DNL", "Define number of lines", Skip),
113
+ 0xFFDD: ("DRI", "Define restart interval", Skip),
114
+ 0xFFDE: ("DHP", "Define hierarchical progression", SOF),
115
+ 0xFFDF: ("EXP", "Expand reference component", Skip),
116
+ 0xFFE0: ("APP0", "Application segment 0", APP),
117
+ 0xFFE1: ("APP1", "Application segment 1", APP),
118
+ 0xFFE2: ("APP2", "Application segment 2", APP),
119
+ 0xFFE3: ("APP3", "Application segment 3", APP),
120
+ 0xFFE4: ("APP4", "Application segment 4", APP),
121
+ 0xFFE5: ("APP5", "Application segment 5", APP),
122
+ 0xFFE6: ("APP6", "Application segment 6", APP),
123
+ 0xFFE7: ("APP7", "Application segment 7", APP),
124
+ 0xFFE8: ("APP8", "Application segment 8", APP),
125
+ 0xFFE9: ("APP9", "Application segment 9", APP),
126
+ 0xFFEA: ("APP10", "Application segment 10", APP),
127
+ 0xFFEB: ("APP11", "Application segment 11", APP),
128
+ 0xFFEC: ("APP12", "Application segment 12", APP),
129
+ 0xFFED: ("APP13", "Application segment 13", APP),
130
+ 0xFFEE: ("APP14", "Application segment 14", APP),
131
+ 0xFFEF: ("APP15", "Application segment 15", APP),
132
+ 0xFFF0: ("JPG0", "Extension 0", None),
133
+ 0xFFF1: ("JPG1", "Extension 1", None),
134
+ 0xFFF2: ("JPG2", "Extension 2", None),
135
+ 0xFFF3: ("JPG3", "Extension 3", None),
136
+ 0xFFF4: ("JPG4", "Extension 4", None),
137
+ 0xFFF5: ("JPG5", "Extension 5", None),
138
+ 0xFFF6: ("JPG6", "Extension 6", None),
139
+ 0xFFF7: ("JPG7", "Extension 7", None),
140
+ 0xFFF8: ("JPG8", "Extension 8", None),
141
+ 0xFFF9: ("JPG9", "Extension 9", None),
142
+ 0xFFFA: ("JPG10", "Extension 10", None),
143
+ 0xFFFB: ("JPG11", "Extension 11", None),
144
+ 0xFFFC: ("JPG12", "Extension 12", None),
145
+ 0xFFFD: ("JPG13", "Extension 13", None),
146
+ 0xFFFE: ("COM", "Comment", COM),
147
+ }
148
+
149
+
150
+ def _accept(prefix):
151
+ # Magic number was taken from https://en.wikipedia.org/wiki/JPEG
152
+ return prefix[:3] == b"\xFF\xD8\xFF"
153
+
154
+
155
+ ##
156
+ # Image plugin for JPEG and JFIF images.
157
+
158
+
159
+ class JpegImageFile(ImageFile.ImageFile):
160
+ format = "JPEG"
161
+ format_description = "JPEG (ISO 10918)"
162
+
163
+ def _open(self):
164
+ s = self.fp.read(3)
165
+
166
+ if not _accept(s):
167
+ msg = "not a JPEG file"
168
+ raise SyntaxError(msg)
169
+ s = b"\xFF"
170
+
171
+ # Create attributes
172
+ self.bits = self.layers = 0
173
+
174
+ # JPEG specifics (internal)
175
+ self.layer = []
176
+ self.huffman_dc = {}
177
+ self.huffman_ac = {}
178
+ self.quantization = {}
179
+ self.app = {} # compatibility
180
+ self.applist = []
181
+ self.icclist = []
182
+
183
+ while True:
184
+ i = s[0]
185
+ if i == 0xFF:
186
+ s = s + self.fp.read(1)
187
+ i = i16(s)
188
+ else:
189
+ # Skip non-0xFF junk
190
+ s = self.fp.read(1)
191
+ continue
192
+
193
+ if i in MARKER:
194
+ name, description, handler = MARKER[i]
195
+ if handler is not None:
196
+ handler(self, i)
197
+ if i == 0xFFDA: # start of scan
198
+ rawmode = self.mode
199
+ if self.mode == "CMYK":
200
+ rawmode = "CMYK;I" # assume adobe conventions
201
+ self.tile = [("jpeg", (0, 0) + self.size, 0, (rawmode, ""))]
202
+ # self.__offset = self.fp.tell()
203
+ break
204
+ s = self.fp.read(1)
205
+ elif i == 0 or i == 0xFFFF:
206
+ # padded marker or junk; move on
207
+ s = b"\xff"
208
+ elif i == 0xFF00: # Skip extraneous data (escaped 0xFF)
209
+ s = self.fp.read(1)
210
+ else:
211
+ msg = "no marker found"
212
+ raise SyntaxError(msg)
213
+
214
+ def load_read(self, read_bytes):
215
+ """
216
+ internal: read more image data
217
+ For premature EOF and LOAD_TRUNCATED_IMAGES adds EOI marker
218
+ so libjpeg can finish decoding
219
+ """
220
+ s = self.fp.read(read_bytes)
221
+
222
+ if not s and ImageFile.LOAD_TRUNCATED_IMAGES and not hasattr(self, "_ended"):
223
+ # Premature EOF.
224
+ # Pretend file is finished adding EOI marker
225
+ self._ended = True
226
+ return b"\xFF\xD9"
227
+
228
+ return s
229
+
230
+ def draft(self, mode, size):
231
+ if len(self.tile) != 1:
232
+ return
233
+
234
+ # Protect from second call
235
+ if self.decoderconfig:
236
+ return
237
+
238
+ d, e, o, a = self.tile[0]
239
+ scale = 1
240
+ original_size = self.size
241
+
242
+ if a[0] == "RGB" and mode in ["L", "YCbCr"]:
243
+ self._mode = mode
244
+ a = mode, ""
245
+
246
+ if size:
247
+ scale = min(self.size[0] // size[0], self.size[1] // size[1])
248
+ for s in [8, 4, 2, 1]:
249
+ if scale >= s:
250
+ break
251
+ e = (
252
+ e[0],
253
+ e[1],
254
+ (e[2] - e[0] + s - 1) // s + e[0],
255
+ (e[3] - e[1] + s - 1) // s + e[1],
256
+ )
257
+ self._size = ((self.size[0] + s - 1) // s, (self.size[1] + s - 1) // s)
258
+ scale = s
259
+
260
+ self.tile = [(d, e, o, a)]
261
+ self.decoderconfig = (scale, 0)
262
+
263
+ b
pairs/pair_29/output.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ ox = (0, 0, original_size[0] / scale, original_size[1] / scale)
2
+ return self.mode, box
pairs/pair_3/input.txt ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ for camera_model in CAMERA_MODELS])
2
+
3
+
4
+ def qvec2rotmat(qvec):
5
+ return np.array([
6
+ [1 - 2 * qvec[2]**2 - 2 * qvec[3]**2,
7
+ 2 * qvec[1] * qvec[2] - 2 * qvec[0] * qvec[3],
8
+ 2 * qvec[3] * qvec[1] + 2 * qvec[0] * qvec[2]],
9
+ [2 * qvec[1] * qvec[2] + 2 * qvec[0] * qvec[3],
10
+ 1 - 2 * qvec[1]**2 - 2 * qvec[3]**2,
11
+ 2 * qvec[2] * qvec[3] - 2 * qvec[0] * qvec[1]],
12
+ [2 * qvec[3] * qvec[1] - 2 * qvec[0] * qvec[2],
13
+ 2 * qvec[2] * qvec[3] + 2 * qvec[0] * qvec[1],
14
+ 1 - 2 * qvec[1]**2 - 2 * qvec[2]**2]])
15
+
16
+ def rotmat2qvec(R):
17
+ Rxx, Ryx, Rzx, Rxy, Ryy, Rzy, Rxz, Ryz, Rzz = R.flat
18
+ K = np.array([
19
+ [Rxx - Ryy - Rzz, 0, 0, 0],
20
+ [Ryx + Rxy, Ryy - Rxx - Rzz, 0, 0],
21
+ [Rzx + Rxz, Rzy + Ryz, Rzz - Rxx - Ryy, 0],
22
+ [Ryz - Rzy, Rzx - Rxz, Rxy - Ryx, Rxx + Ryy + Rzz]]) / 3.0
23
+ eigvals, eigvecs = np.linalg.eigh(K)
24
+ qvec = eigvecs[[3, 0, 1, 2], np.argmax(eigvals)]
25
+ if qvec[0] < 0:
26
+ qvec *= -1
27
+ return qvec
28
+
29
+ class Image(BaseImage):
30
+ def qvec2rotmat(self):
31
+ return qvec2rotmat(self.qvec)
32
+
33
+ def read_next_bytes(fid, num_bytes, format_char_sequence, endian_character="<"):
34
+ """Read and unpack the next bytes from a binary file.
35
+ :param fid:
36
+ :param num_bytes: Sum of combination of {2, 4, 8}, e.g. 2, 6, 16, 30, etc.
37
+ :param format_char_sequence: List of {c, e, f, d, h, H, i, I, l, L, q, Q}.
38
+ :param endian_character: Any of {@, =, <, >, !}
39
+ :return: Tuple of read and unpacked values.
40
+ """
41
+ data = fid.read(num_bytes)
42
+ return struct.unpack(endian_character + format_char_sequence, data)
43
+
44
+ def read_points3D_text(path):
45
+ """
46
+ see: src/base/reconstruction.cc
47
+ void Reconstruction::ReadPoints3DText(const std::string& path)
48
+ void Reconstruction::WritePoints3DText(const std::string& path)
49
+ """
50
+ xyzs = None
51
+ rgbs = None
52
+ errors = None
53
+ num_points = 0
54
+ with open(path, "r") as fid:
55
+ while True:
56
+ line = fid.readline()
57
+ if not line:
58
+ break
59
+ line = line.strip()
60
+ if len(line) > 0 and line[0] != "#":
61
+ num_points += 1
62
+
63
+
64
+ xyzs = np.empty((num_points, 3))
65
+ rgbs = np.empty((num_points, 3))
66
+ errors = np.empty((num_points, 1))
67
+ count = 0
68
+ with open(path, "r") as fid:
69
+ while True:
70
+ line = fid.readline()
71
+ if not line:
72
+ break
73
+ line = line.strip()
74
+ if len(line) > 0 and line[0] != "#":
75
+ elems = line.split()
76
+ xyz = np.array(tuple(map(float, elems[1:4])))
77
+
pairs/pair_3/output.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ rgb = np.array(tuple(map(int, elems[4:7])))
2
+ error = np.array(float(elems[7]))
3
+ xyzs[count] = xyz
4
+ rgbs[count] = rgb
5
+ errors[count] = error
6
+ count += 1
7
+
8
+ return xyzs, rgbs, errors
pairs/pair_30/input.txt ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import os.path
3
+
4
+ import pytest
5
+
6
+ from PIL import Image, ImageColor, ImageDraw, ImageFont, features
7
+
8
+ from .helper import (
9
+ assert_image_equal,
10
+ assert_image_equal_tofile,
11
+ assert_image_similar_tofile,
12
+ hopper,
13
+ skip_unless_feature,
14
+ )
15
+
16
+ BLACK = (0, 0, 0)
17
+ WHITE = (255, 255, 255)
18
+ GRAY = (190, 190, 190)
19
+ DEFAULT_MODE = "RGB"
20
+ IMAGES_PATH = os.path.join("Tests", "images", "imagedraw")
21
+
22
+ # Image size
23
+ W, H = 100, 100
24
+
25
+ # Bounding box points
26
+ X0 = int(W / 4)
27
+ X1 = int(X0 * 3)
28
+ Y0 = int(H / 4)
29
+ Y1 = int(X0 * 3)
30
+
31
+ # Bounding boxes
32
+ BBOX = (((X0, Y0), (X1, Y1)), [(X0, Y0), (X1, Y1)], (X0, Y0, X1, Y1), [X0, Y0, X1, Y1])
33
+
34
+ # Coordinate sequences
35
+ POINTS = (
36
+ ((10, 10), (20, 40), (30, 30)),
37
+ [(10, 10), (20, 40), (30, 30)],
38
+ (10, 10, 20, 40, 30, 30),
39
+ [10, 10, 20, 40, 30, 30],
40
+ )
41
+
42
+ KITE_POINTS = (
43
+ ((10, 50), (70, 10), (90, 50), (70, 90), (10, 50)),
44
+ [(10, 50), (70, 10), (90, 50), (70, 90), (10, 50)],
45
+ )
46
+
47
+
48
+ def test_sanity():
49
+ im = hopper("RGB").copy()
50
+
51
+ draw = ImageDraw.ImageDraw(im)
52
+ draw = ImageDraw.Draw(im)
53
+
54
+ draw.ellipse(list(range(4)))
55
+ draw.line(list(range(10)))
56
+ draw.polygon(list(range(100)))
57
+ draw.rectangle(list(range(4)))
58
+
59
+
60
+ def test_valueerror():
61
+ with Image.open("Tests/images/chi.gif") as im:
62
+ draw
pairs/pair_30/output.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ = ImageDraw.Draw(im)
2
+ draw.line((0, 0), fill=(0, 0, 0))