-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathcoordinate.py
More file actions
611 lines (538 loc) · 18.9 KB
/
coordinate.py
File metadata and controls
611 lines (538 loc) · 18.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
#!/usr/bin/env python
'''
coordinate mapping functions for render api
'''
from .render import format_preamble, renderaccess
from .utils import NullHandler, renderdumps, renderdump, get_json
from .client import coordinateClient
from .errors import RenderError
import requests
import json
import numpy as np
import logging
import tempfile
import os
logger = logging.getLogger(__name__)
logger.addHandler(NullHandler())
@renderaccess
def world_to_local_coordinates(stack, z, x, y, host=None,
port=None, owner=None, project=None,
session=requests.session(),
render=None, **kwargs):
"""maps an world x,y,z coordinate in stack to a local coordinate
Parameters
----------
stack : str
render stack to map coordinates through
z : float
z coordinate to map
x : float
x coordinate to map
y : float
y coordinate to map
session : requests.session.Session
session object used in request
render : renderapi.render.Render
render connect object
Returns
-------
json
list of dictionaries of local coordinates following this pattern
::
[
{
"tileId": "string",
"visible": false,
"local": [
[0,0],
[1,0]...
],
"error": "string"
}
]
"""
request_url = format_preamble(
host, port, owner, project, stack) + \
"/z/%d/world-to-local-coordinates/%f,%f" % (z, x, y)
return get_json(session, request_url)
@renderaccess
def local_to_world_coordinates(stack, tileId, x, y,
host=None, port=None, owner=None, project=None,
session=requests.session(),
render=None, **kwargs):
"""convert coordinate from local to world with webservice request
Parameters
----------
stack : str
render stack to map coordinates through
z : float
z coordinate to map
x : float
x coordinate to map
y : float
y coordinate to map
session : requests.session.Session
session object used in request
render : renderapi.render.Render
render connect object
Returns
-------
dict
dictionary of world coordinates following this pattern
::
{
"tileId": "string",
"visible": false,
"world": [
[0,0],
[1,0]...
],
"error": "string"
}
"""
request_url = format_preamble(
host, port, owner, project, stack) + \
"/tile/%s/local-to-world-coordinates/%f,%f" % (tileId, x, y)
return get_json(session, request_url)
@renderaccess
def world_to_local_coordinates_batch(stack, d, z, host=None,
port=None, owner=None, project=None,
execute_local=False,
session=requests.session(),
render=None, **kwargs):
"""convert coordinate parameters from world to local
Parameters
----------
stack : str
stack to map coordinates
d : list[dict]
list of dictionary of world coordinates to map following this schema
::
[ {
"tileId": "string",
"world": [
[0,0],
[1,0]...
],
"error": "string"
}]
z : float
z coordinate to map
execute_local : boolean
(Default value = False)
session : requests.session.Session
session object used in request
render : renderapi.render.Render
render connect object
Returns
-------
list[list[dict]]
list of lists of dictionaries containing local positions
that overlap with this point, (one world point may map
to multiple local points) following..
::
[[ {
"tileId": "string",
"visible": True,False,
"local": [
[0,0],
[1,0]...
],
"error": "string"
}]
]
"""
if (execute_local is True):
raise NotImplementedError("local execution not yet implemented")
request_url = format_preamble(
host, port, owner, project, stack) + \
"/z/%s/world-to-local-coordinates" % (str(z))
r = session.put(request_url, data=renderdumps(d),
headers={"content-type": "application/json"})
return r.json()
@renderaccess
def local_to_world_coordinates_batch(stack, d, z, host=None,
port=None, owner=None, project=None,
session=requests.session(),
render=None, **kwargs):
"""convert coordinate parameters from local to world
Parameters
----------
stack : str
d : list[dict]
list of dictionary of local coordinates to map
::
[ {
"tileId": "string",
"local": [
[0,0],
[1,0]...
],
"error": "string"
}]
z : float
z coordinate to map from
session :
(Default value = requests.session()
render : renderapi.render.Render
render connect object
Returns
-------
list[dict]
list of dictionaries containing world coordinates
::
[ {
"tileId": "string",
"world": [
[0,0],
[1,0]...
],
"error": "string"
}]
"""
request_url = format_preamble(
host, port, owner, project, stack) + \
"/z/%s/local-to-world-coordinates" % (str(z))
r = session.put(request_url, data=renderdumps(d),
headers={"content-type": "application/json"})
try:
return r.json()
except Exception as e:
logger.error(e)
logger.error(r.text)
raise RenderError(r.text)
def package_point_match_data_into_json(dataarray, tileId,
local_or_world='local'):
"""Convert a set of points defined by a numpy array and a tileId to a json
for use in the renderapi
Parameters
----------
dataarray : numpy.array
a Nx2 array of points
tileId : str
a tileId to package them into
local_or_world :
whether this should be represented as a local or world coordinate
(Default value = 'local')
Returns
-------
dict
dictionary representation of those points and tileId
following
::
{
"tileId": "string",
"world": [
[0,0],
[1,0]...
],
"error": "string"
}
"""
dlist = []
for i in range(dataarray.shape[0]):
d = {}
d['tileId'] = tileId
d[local_or_world] = [dataarray[i, 0], dataarray[i, 1]]
dlist.append(d)
return dlist
def unpackage_world_to_local_point_match_from_json(json_answer, tileId):
"""Converts a dictionary answer from a world>local
coordinates call from a dictionary to numpy array format
Parameters
----------
json_answer : list[dict]
json reponse from a world>local call (N long)
tileId : str
tileId to extract, usually the world tileId passed in
Returns
-------
numpy.array
Nx2 array of local points
"""
answer = np.zeros((len(json_answer), 2))
for i, local_answer in enumerate(json_answer):
coord = next(ans for ans in local_answer if ans['tileId'] == tileId)
c = coord['local']
answer[i, 0] = c[0]
answer[i, 1] = c[1]
return answer
# @renderaccess
# def old_world_to_local_coordinates_array(stack, dataarray, tileId, z=0,
# host=None, port=None,
# owner=None, project=None,
# session=requests.session(),
# render=None, **kwargs):
# ''''''
# request_url = format_preamble(
# host, port, owner, project, stack) + \
# "/z/%d/world-to-local-coordinates" % (z)
# dlist = []
# for i in range(dataarray.shape[0]):
# d = {}
# d['tileId'] = tileId
# d['world'] = [dataarray[i, 0], dataarray[i, 1]]
# dlist.append(d)
# jsondata = json.dumps(dlist)
# r = session.put(request_url, data=jsondata,
# headers={"content-type": "application/json"})
# json_answer = r.json()
# try:
# answer = np.zeros(dataarray.shape)
# for i, coord in enumerate(json_answer):
# c = coord['local']
# answer[i, 0] = c[0]
# answer[i, 1] = c[1]
# return answer
# except Exception as e:
# logger.error(e)
# logger.error(json_answer)
def unpackage_local_to_world_point_match_from_json(json_answer):
"""converts a local>world call json response into a numpy array
Parameters
----------
json_answer : list[dict]
response from a local>world call (N long)
Returns
-------
numpy.array
Nx2 numpy array of coordinates
"""
logger.debug("json_answer_length %d" % len(json_answer))
answer = np.zeros((len(json_answer), 2))
for i, coord in enumerate(json_answer):
c = coord['world']
answer[i, 0] = c[0]
answer[i, 1] = c[1]
return answer
@renderaccess
def world_to_local_coordinates_array(stack, dataarray, tileId, z,
render=None, host=None, port=None,
owner=None, project=None,
client_script=None,
doClientSide=False, number_of_threads=20,
session=requests.session(), **kwargs):
"""map world to local coordinates using numpy array
Parameters
----------
stack : str
render stack to map
dataarray : numpy.array
Nx2 numpy array of points to world points to map
tileId : str
tileId to map from and to
z : float
z coordinate to map
render : renderapi.render.Render
render connect object
doClientSide : boolean
(Default value = False)
number_of_threads : int
(Default value = 20)
session : requests.session.Session
session object used in request
Returns
-------
numpy.array:
Nx2 numpy array of points in local coordinates
"""
jsondata = package_point_match_data_into_json(dataarray, tileId, 'world')
if doClientSide:
json_answer = world_to_local_coordinates_clientside(
stack, jsondata, z, host=host, port=port, owner=owner,
project=project, client_script=client_script,
number_of_threads=number_of_threads)
else:
json_answer = world_to_local_coordinates_batch(
stack, jsondata, z, host=host, port=port, owner=owner,
project=project, session=session)
return unpackage_world_to_local_point_match_from_json(json_answer, tileId)
# @renderaccess
# def old_local_to_world_coordinates_array(stack, dataarray, tileId, z=0,
# host=None, port=None,
# owner=None, project=None,
# session=requests.session(),
# render=None, **kwargs):
# ''''''
# request_url = format_preamble(
# host, port, owner, project, stack) + \
# "/z/%d/local-to-world-coordinates" % (z)
# dlist = []
# for i in range(dataarray.shape[0]):
# d = {}
# d['tileId'] = tileId
# d['local'] = [dataarray[i, 0], dataarray[i, 1]]
# dlist.append(d)
# jsondata = json.dumps(dlist)
# r = session.put(request_url, data=jsondata,
# headers={"content-type": "application/json"})
# json_answer = r.json()
# try:
# answer = np.zeros(dataarray.shape)
# logger.debug('shape {}'.format(dataarray.shape))
# logger.debug('length of json_answer {}'.format(len(json_answer)))
# for i, coord in enumerate(json_answer):
# c = coord['world']
# answer[i, 0] = c[0]
# answer[i, 1] = c[1]
# return answer
# except Exception as e:
# logger.error(e)
# logger.error(json_answer)
@renderaccess
def local_to_world_coordinates_array(stack, dataarray, tileId, z,
render=None, host=None, port=None,
owner=None, project=None,
client_script=None,
doClientSide=False, number_of_threads=20,
session=requests.session(), **kwargs):
"""map local to world coordinates using numpy array
Parameters
----------
stack : str
render stack to map
dataarray : numpy.array
Nx2 array of points in local coordinates
tileId : str
tile to map points from
z : float
z position to map
render : renderapi.render.Render
render connect object
doClientSide : boolean
(Default value = False)
number_of_threads : int
(Default value = 20)
session : requests.session.Session
session object used in request
render : renderapi.render.Render
render connect object
Returns
-------
numpy.array
Nx2 numpy array in world coordinates
"""
jsondata = package_point_match_data_into_json(dataarray, tileId, 'local')
if doClientSide:
json_answer = local_to_world_coordinates_clientside(
stack, [[lp] for lp in jsondata], z, host=host, port=port,
owner=owner, project=project, client_script=client_script,
number_of_threads=number_of_threads)
else:
json_answer = local_to_world_coordinates_batch(
stack, jsondata, z, host=host, port=port, owner=owner,
project=project, session=session)
return unpackage_local_to_world_point_match_from_json(json_answer)
def map_coordinates_clientside(stack, jsondata, z, host, port, owner,
project, client_script, isLocalToWorld=False,
store_injson=False, store_outjson=False,
number_of_threads=20, memGB='1G'):
"""map coordinates using the java client library
Parameters
----------
stack : str
stack to map
jsondata : dict
json dictionary to map following the pattern of local>world or world>local
z : float
z position to map
isLocalToWorld : boolean
whether transform is local to world (False implies world to local)
store_injson : boolean
whether to store input json file (created with tempfile)
store_outjson : boolean
whether to store output json file (created with tempfile)
number_of_threads : int
threads to execute clientside computation
render : renderapi.render.Render
render connect object
Returns
-------
json
json data as would be returned by client calls
of local>world or world>local
""" # noqa: E501
# write point match json to temp file on disk
with tempfile.NamedTemporaryFile(
prefix='render_coordinates_in_', suffix='.json',
mode='w', delete=False) as f:
logger.debug('jsondata:{}'.format(jsondata))
json_inpath = f.name
renderdump(jsondata, f)
# get a temporary location for the output
with tempfile.NamedTemporaryFile(
prefix='render_coordinates_out_', suffix='.json',
delete=False) as f:
json_outpath = f.name
# call the java client
coordinateClient(stack, z, fromJson=json_inpath, toJson=json_outpath,
localToWorld=isLocalToWorld,
numberOfThreads=number_of_threads,
host=host, port=port, owner=owner, project=project,
client_script=client_script, memGB=memGB)
# return the json results
with open(json_outpath, 'r') as f:
j = json.load(f)
if not store_injson:
os.remove(json_inpath)
if not store_outjson:
os.remove(json_outpath)
return j
@renderaccess
def world_to_local_coordinates_clientside(stack, jsondata, z,
host=None, port=None, owner=None,
project=None, client_script=None,
number_of_threads=20,
render=None, **kwargs):
"""map_coordinates_clientside for mapping world to local
Parameters
----------
stack : str
render stack to map
jsondata : dict
world coordinates in dictionary format
z : float
z coordinate to map
number_of_threads : int
number of threads to use when doing parallelization
render : renderapi.render.Render
render connect object
Returns
-------
json
local coordinates in dictionary format
"""
return map_coordinates_clientside(stack, jsondata, z,
host=host, port=port, owner=owner,
project=project,
client_script=client_script,
isLocalToWorld=False,
number_of_threads=number_of_threads)
@renderaccess
def local_to_world_coordinates_clientside(stack, jsondata, z,
host=None, port=None, owner=None,
project=None, client_script=None,
number_of_threads=20,
render=None, **kwargs):
"""map_coordinates_clientside for mapping local to world
Parameters
----------
stack : str
render stack to map
jsondata : list[dict]
local coordinates in dictionary format
z : float
z position to map
number_of_threads : int
threads for java client script to use during mapping
Returns
-------
dict
world coordinates in dictionary format
"""
return map_coordinates_clientside(stack, jsondata, z,
host=host, port=port, owner=owner,
project=project,
client_script=client_script,
isLocalToWorld=True,
number_of_threads=number_of_threads)