-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathSlaveProcess.groovy
1269 lines (1067 loc) · 44.2 KB
/
SlaveProcess.groovy
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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2016 Atlas of Living Australia
* All Rights Reserved.
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*/
package au.org.ala.spatial.process
import au.org.ala.spatial.FileService
import au.org.ala.spatial.JournalMapService
import au.org.ala.spatial.LayerIntersectService
import au.org.ala.spatial.SandboxService
import au.org.ala.spatial.dto.AreaInput
import au.org.ala.spatial.dto.ProcessSpecification
import au.org.ala.spatial.dto.SpeciesInput
import au.org.ala.spatial.SpatialConfig
import au.org.ala.spatial.Util
import au.org.ala.spatial.Distributions
import au.org.ala.spatial.DistributionsService
import au.org.ala.spatial.Fields
import au.org.ala.spatial.FieldService
import au.org.ala.spatial.GridCutterService
import au.org.ala.spatial.Layers
import au.org.ala.spatial.LayerService
import au.org.ala.spatial.OutputParameter
import au.org.ala.spatial.SpatialObjects
import au.org.ala.spatial.SpatialObjectsService
import au.org.ala.spatial.TabulationGeneratorService
import au.org.ala.spatial.TabulationService
import au.org.ala.spatial.TasksService
import au.org.ala.spatial.dto.TaskWrapper
import au.org.ala.spatial.util.OccurrenceData
import au.org.ala.spatial.intersect.Grid
import au.org.ala.spatial.intersect.SimpleRegion
import au.org.ala.spatial.intersect.SimpleShapeFile
import au.org.ala.spatial.legend.GridLegend
import au.org.ala.spatial.legend.Legend
import au.org.ala.spatial.legend.LegendEqualArea
import au.org.ala.spatial.dto.LayerFilter
import au.org.ala.ws.service.WebService
import grails.converters.JSON
import groovy.util.logging.Slf4j
import org.apache.commons.io.IOUtils
import org.geotools.geometry.jts.WKTReader2
import org.grails.web.json.JSONArray
import org.locationtech.jts.geom.Geometry
import org.yaml.snakeyaml.util.UriEncoder
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.nio.charset.StandardCharsets
import java.util.zip.ZipInputStream
@Slf4j
class SlaveProcess {
FieldService fieldService
LayerService layerService
DistributionsService distributionsService
JournalMapService journalMapService
TasksService tasksService
TaskWrapper taskWrapper
TabulationService tabulationService
SpatialObjectsService spatialObjectsService
GridCutterService gridCutterService
LayerIntersectService layerIntersectService
TabulationGeneratorService tabulationGeneratorService
FileService fileService
WebService webService
SandboxService sandboxService
SpatialConfig spatialConfig
// start the task
void start() {}
// abort the task
void stop() {}
def getFile(String path, String remoteSpatialServiceUrl, String jwt) {
def remote = peekFile(path, remoteSpatialServiceUrl, jwt)
//compare p list with local files
def fetch = []
remote.each { file ->
if (file.exists) {
def local = new File(spatialConfig.data.dir + file.path)
if (!local.exists() || local.lastModified() < file.lastModified) {
fetch.add(file.path)
}
}
}
if (fetch.size() < remote.size()) {
//fetch only some
fetch.each {
getFile(it, remoteSpatialServiceUrl, jwt)
}
} else if (fetch.size() > 0) {
//fetch all files
def tmpFile = File.createTempFile('resource', '.zip')
try {
def shortpath = path.replace(spatialConfig.data.dir, '')
def url = remoteSpatialServiceUrl + "/master/resource?resource=" + URLEncoder.encode(shortpath, 'UTF-8')
def os = new BufferedOutputStream(new FileOutputStream(tmpFile))
def streamObj = Util.getStream(url, jwt)
try {
if (streamObj?.call) {
os << streamObj?.call?.getResponseBodyAsStream()
}
os.flush()
os.close()
} catch (Exception e) {
log.error e.getMessage(), e
}
streamObj?.call?.releaseConnection()
def zf = new ZipInputStream(new FileInputStream(tmpFile))
try {
def entry
while ((entry = zf.getNextEntry()) != null) {
def filepath = spatialConfig.data.dir + entry.getName()
def f = new File(filepath)
f.getParentFile().mkdirs()
//TODO: copyInputStreamToFile closes the stream even if there are more entries
def fout = new FileOutputStream(f)
IOUtils.copy(zf, fout);
fout.close()
zf.closeEntry()
//update lastmodified time
remote.each { file ->
if (entry.name.equals(file.path)) {
f.setLastModified(file.lastModified)
}
}
}
} finally {
try {
zf.close()
} catch (err) {
log.error('Error in reading uploaded file: ' + err.printStackTrace())
}
}
} catch (err) {
log.error "failed to get: " + path, err
}
tmpFile.delete()
}
}
/**
* Get some info on file/s (path, exists, lastModified) from the local fs or remote spatial service.
*
* The result will include info for the file "spatialConfig.data.dir + path" if it exists, otherwise it will
* include info for the files "spatialConfig.data.dir + path + ".*" if they exist.
*
* @param path begins with '/' and is relative to spatialConfig.data.dir
* @param spatialServiceUrl specify if a remote spatial service is to be used
* @param jwt required if a remote spatial service is used
* @return
*/
List peekFile(String path, String spatialServiceUrl = spatialConfig.spatialService.url, String jwt = null) {
String shortpath = path.replace(spatialConfig.data.dir.toString(), '')
// if the spatial service is the same as the local service, use the file service
if (spatialServiceUrl.equals(spatialConfig.grails.serverURL)) {
return fileService.info(shortpath.toString())
}
List map = [[path: '', exists: false, lastModified: System.currentTimeMillis()]]
try {
String url = spatialServiceUrl + "/master/resourcePeek?resource=" + URLEncoder.encode(shortpath, 'UTF-8')
// use the provided JWT authentication in the request header, and assign the JSON GET result to the map
map = JSON.parse(Util.urlResponse("GET", url, null, ['Authorization': 'Bearer ' + jwt])?.text) as List
} catch (err) {
log.error "failed to get: " + path, err
}
map
}
String getInput(String name) {
// config inputs
if ('bieUrl' == name) return spatialConfig.bie.baseURL
if ('biocacheServiceUrl' == name) return spatialConfig.biocacheServiceUrl
if ('phyloServiceUrl' == name) return spatialConfig.phyloServiceUrl
if ('sandboxHubUrl' == name) return spatialConfig.sandboxHubUrl
if ('sandboxBiocacheServiceUrl' == name) return spatialConfig.sandboxBiocacheServiceUrl
if ('namematchingUrl' == name) return spatialConfig.namematching.url
if ('geoserverUrl' == name) return spatialConfig.geoserver.url
if ('userId' == name) return taskWrapper.task.userId
// task inputs
taskWrapper.task.input.find { it.name == name }?.value as String
}
// define inputs and outputs
ProcessSpecification spec(ProcessSpecification config) {
ProcessSpecification s
if (config == null) {
def json = JSON.parse(this.class.getResource("/processes/" + this.class.simpleName + ".json").text)
s = new ProcessSpecification()
s.name = json.name
s.description = json.description
s.isBackground = json.isBackground
s.version = json.version
s.input = new HashMap()
json.input.each { key, value ->
ProcessSpecification.InputSpecification is = new ProcessSpecification.InputSpecification()
is.description = value.description
is.type = value.type.toUpperCase()
ProcessSpecification.ConstraintSpecification c = new ProcessSpecification.ConstraintSpecification()
value.constraints?.each { ckey, cvalue ->
if (ckey == 'selection') {
c.selection = cvalue.toUpperCase()
} else if (ckey == 'content') {
c.content = cvalue
} else if (c.properties.containsKey(ckey)) {
c.setProperty(ckey, cvalue)
}
}
is.constraints = c
s.input.put(key, is)
}
s.output = new HashMap()
json.output?.each { key, value ->
ProcessSpecification.OutputSpecification is = new ProcessSpecification.OutputSpecification()
is.description = value.description
s.output.put(key.toUpperCase(), is)
}
s.privateSpecification = new ProcessSpecification.PrivateSpecification()
json.private?.each { key, value ->
if (s.privateSpecification.properties.containsKey(key)) {
s.privateSpecification.setProperty(key, value)
}
}
} else {
s = config.clone()
}
if (!s.privateSpecification) {
s.privateSpecification = new ProcessSpecification.PrivateSpecification()
}
s.privateSpecification.classname = this.class.getCanonicalName()
updateSpec(s)
s
}
void updateSpec(ProcessSpecification spec) {}
String getTaskPath() {
taskWrapper.path + '/'
}
String getTaskPathById(taskId) {
spatialConfig.data.dir + '/public/' + taskId + '/'
}
List<Layers> getLayers() {
layerService.getLayers()
}
List<Fields> getFields() {
fieldService.getFieldsByCriteria("")
}
List<Distributions> getDistributions() {
distributionsService.queryDistributions([:], true, Distributions.EXPERT_DISTRIBUTION)
}
List<Distributions> getChecklists() {
distributionsService.queryDistributions([:], true, Distributions.SPECIES_CHECKLIST)
}
List getTabulations() {
tabulationService.listTabulations()
}
Layers getLayer(String id) {
layerService.getLayerById(id as Long, false)
}
Fields getField(String id) {
fieldService.get(id, null, 0, 0)
}
List<SpatialObjects> getObjects(String fieldId) {
fieldService.get(fieldId, null, 0, -1)?.objects
}
String getWkt(objectId) {
OutputStream baos = new ByteArrayOutputStream()
spatialObjectsService.wkt(objectId, baos)
baos.toString()
}
String getEnvelopeWkt(String objectId) {
String wkt = ''
try {
String taskId = objectId.replace("ENVELOPE", "")
wkt = new File(spatialConfig.data.dir + "/public/" + taskId + "/" + taskId + ".shp").text
} catch (err) {
log.error "failed to lookup object wkt: ${objectId}", err
}
wkt
}
/**
* get all files with an extension or exact match for values.
*
* value must begin with '/'
*
* @param value
*/
void addOutputFiles(String value, Boolean layers = false) {
def fstart = value.substring(0, value.lastIndexOf('/'))
def fend = value.substring(value.lastIndexOf('/') + 1)
if (layers) {
addOutput("layers", value)
}
OutputParameter op = taskWrapper.task.output.find { it.name == value }
if (!op) {
op = new OutputParameter([name: value, file: ([] as JSON).toString()])
taskWrapper.task.output.add(op)
}
File file = new File("${spatialConfig.data.dir}${fstart}")
for (File f : file.listFiles()) {
if (f.getName() == fend || f.getName().startsWith("${fend}.")) {
if (layers &&
(f.getName().endsWith(".sld") || f.getName().endsWith(".grd") ||
f.getName().endsWith(".gri") || f.getName().endsWith(".tif") ||
f.getName().endsWith(".prj") || f.getName().endsWith(".shp"))) {
addOutput("layers", fstart + '/' + f.getName())
} else {
addOutput("files", fstart + '/' + f.getName())
}
}
}
}
void addOutput(String name, String value, Boolean download = false) {
OutputParameter op = taskWrapper.task.output.find { OutputParameter it -> it.name == name }
if (!op) {
op = new OutputParameter([name: name, file: ([] as JSON).toString()])
taskWrapper.task.output.add(op)
}
List values = (List) JSON.parse(op.file)
values.add(value)
op.file = (values as JSON).toString()
if (download && !"download".equalsIgnoreCase(name)) {
addOutput('download', value)
}
}
static String sqlEscapeString(String str) {
if (str == null) {
'null'
} else {
str.replace("'", "''").replace("\\", "\\\\")
}
}
static def joinSpeciesQ(List list) {
if (!list) {
return ''
}
def str = list[0]
for (int i=1;i<list.size();i++) {
str += '&fq=' + list[i]
}
str
}
static def facetOccurenceCount(String facet, SpeciesInput species) {
String url = species.bs + "/occurrence/facets?facets=" + facet + "&flimit=-1&fsort=index&q=" + joinSpeciesQ(species.q)
String response = Util.getUrl(url)
((JSONArray) JSON.parse(response))
}
Integer facetCount(String facet, SpeciesInput species) {
return facetCount(facet, species, null)
}
Integer facetCount(String facet, SpeciesInput species, String extraFq) {
String fq = ''
if (extraFq) fq = '&fq=' + UriEncoder.encode(extraFq)
String url = species.bs + "/occurrence/facets?facets=" + facet + "&flimit=0&q=" + joinSpeciesQ(species.q) + fq
try {
String response = Util.getUrl(url)
def results = (List) JSON.parse(response)
if (results) {
return results.get(0)["count"] as Integer
}
} catch (err) {
log.error 'failed get facet count for: ' + taskWrapper.id + ", " + url, err
}
return 0
}
def occurrenceCount(SpeciesInput species) {
return occurrenceCount(species, null)
}
Integer occurrenceCount(SpeciesInput species, String extraFq) {
String fq = ''
if (extraFq) fq = '&fq=' + UriEncoder.encode(extraFq)
String url = species.bs + "/occurrences/search?&facet=off&pageSize=0&q=" + joinSpeciesQ(species.q) + fq
String response = Util.getUrl(url)
JSON.parse(response).totalRecords as Integer
}
String[] facet(String facet, SpeciesInput species) {
String url = species.bs + "/occurrences/facets/download?facets=" + facet + "&lookup=false&count=false&q=" + joinSpeciesQ(species.q)
String response = streamBytes(url, facet)
if (response) {
response.split("\n")
} else {
[] as String[]
}
}
String streamBytes(String url, String name) {
taskWrapper.task.message = "fetching ${name}"
HttpClient client = HttpClient.newHttpClient()
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.build()
HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream())
if (response.statusCode() != 200) {
throw new Exception("Error reading from biocache-service: " + response.statusCode())
}
InputStream inputStream = null
ByteArrayOutputStream outputStream = new ByteArrayOutputStream()
byte[] buffer = new byte[1024]
try {
inputStream = response.body()
int count = 0
int len
while ((len = inputStream.read(buffer)) > 0) {
count += len
taskWrapper.task.message = "fetching ${name}: ${count} bytes"
outputStream.write(buffer, 0, len)
}
new String(outputStream.toByteArray(), StandardCharsets.UTF_8)
} catch (err) {
log.error(url, err)
""
} finally {
if (inputStream) {
inputStream.close()
}
}
}
List<File> downloadSpecies(SpeciesInput species) {
OccurrenceData od = new OccurrenceData()
String[] s = od.getSpeciesData(joinSpeciesQ(species.q), species.bs, null, null)
def newFiles = []
if (s[0] != null) {
//mkdir in index location
String newPath = null
try {
newPath = getTaskPath() + "/tmp/" + System.currentTimeMillis() + File.separator
new File(newPath).mkdirs()
File f = new File(newPath + File.separator + "species_points.csv")
f.write(s[0])
newFiles.add(f)
if (s[1] != null) {
f = new File(newPath + File.separator + "removedSpecies.txt")
f.write(s[1])
newFiles.add(f)
}
} catch (err) {
log.error 'failed to create tmp species file for task ' + taskWrapper.id, err
}
}
newFiles
}
/**
* exports a list of layers cut against a region
* <p/>
* Cut layer files generated are input layers with grid cells outside of
* region set as missing.
*
* @param layers list of layer fieldIds to be cut as String[].
* @param resolution target resolution as String
* @param region null or region to cut against as SimpleRegion. Cannot be
* used with envelopes.
* @param envelopes nul or region to cut against as LayerFilter[]. Cannot be
* used with region.
* @param extentsFilename output filename and path for writing output
* extents.
* @return directory containing the cut grid files.
*/
String cutGrid(String[] layers, String resolution, SimpleRegion region, LayerFilter[] envelopes, String extentsFilename) {
//check if resolution needs changing
resolution = confirmResolution(layers, resolution)
//get extents for all layers
double[][] extents = getLayerExtents(resolution, layers[0])
for (int i = 1; i < layers.length; i++) {
extents = internalExtents(extents, getLayerExtents(resolution, layers[i]))
if (!isValidExtents(extents)) {
return null
}
}
//do extents check for contextual envelopes as well
if (envelopes != null) {
extents = internalExtents(extents, getLayerFilterExtents(envelopes))
if (!isValidExtents(extents)) {
return null
}
}
//get mask and adjust extents for filter
byte[][] mask
int h
int w
double res = Double.parseDouble(resolution)
if (region != null) {
extents = internalExtents(extents, region.getBoundingBox())
if (!isValidExtents(extents)) {
return null
}
h = (int) Math.ceil((extents[1][1] - extents[0][1]) / res)
w = (int) Math.ceil((extents[1][0] - extents[0][0]) / res)
log.debug("Calculating mask")
mask = getRegionMask(extents, w, h, region)
} else if (envelopes != null) {
h = (int) Math.ceil((extents[1][1] - extents[0][1]) / res)
w = (int) Math.ceil((extents[1][0] - extents[0][0]) / res)
mask = getEnvelopeMaskAndUpdateExtents(resolution, res, extents, h, w, envelopes)
h = (int) Math.ceil((extents[1][1] - extents[0][1]) / res)
w = (int) Math.ceil((extents[1][0] - extents[0][0]) / res)
} else {
h = (int) Math.ceil((extents[1][1] - extents[0][1]) / res)
w = (int) Math.ceil((extents[1][0] - extents[0][0]) / res)
mask = getMask(w, h)
}
//mkdir in index location
String newPath = null
try {
newPath = getTaskPath() + "/tmp/" + System.currentTimeMillis() + File.separator
new File(newPath).mkdirs()
} catch (Exception e) {
e.printStackTrace()
}
//apply mask
for (int i = 0; i < layers.length; i++) {
applyMask(newPath, resolution, extents, w, h, mask, layers[i])
}
//write extents file
writeExtents(extentsFilename, extents, w, h)
return newPath
}
static double[][] internalExtents(double[][] e1, double[][] e2) {
double[][] internalExtents = new double[2][2]
internalExtents[0][0] = Math.max(e1[0][0], e2[0][0])
internalExtents[0][1] = Math.max(e1[0][1], e2[0][1])
internalExtents[1][0] = Math.min(e1[1][0], e2[1][0])
internalExtents[1][1] = Math.min(e1[1][1], e2[1][1])
return internalExtents
}
static boolean isValidExtents(double[][] e) {
return e[0][0] < e[1][0] && e[0][1] < e[1][1]
}
double[][] getLayerExtents(String resolution, String layer) {
double[][] extents = new double[2][2]
if (getLayerPath(resolution, layer) == null
&& layer.startsWith("cl")) {
//use world extents here, remember to do object extents later.
extents[0][0] = -180
extents[0][1] = -90
extents[1][0] = 180
extents[1][1] = 90
} else {
Grid g = Grid.getGrid(getLayerPath(resolution, layer))
extents[0][0] = g.xmin
extents[0][1] = g.ymin
extents[1][0] = g.xmax
extents[1][1] = g.ymax
}
return extents
}
String getLayerPath(String resolution, String layer) {
String standardLayersDir = spatialConfig.data.dir + '/standard_layer/'
File file = new File(standardLayersDir + resolution + '/' + layer + '.grd')
log.debug("loading grid from: " + file.path)
//move up a resolution when the file does not exist at the target resolution
try {
while (!file.exists()) {
TreeMap<Double, String> resolutionDirs = new TreeMap<Double, String>()
for (File dir : new File(standardLayersDir).listFiles()) {
if (dir.isDirectory()) {
try {
resolutionDirs.put(Double.parseDouble(dir.getName()), dir.getName())
} catch (Exception ignored) {
//ignore other dirs
}
}
}
String newResolution = resolutionDirs.higherEntry(Double.parseDouble(resolution)).getValue()
if (newResolution == resolution) {
break
} else {
resolution = newResolution
file = new File(standardLayersDir + File.separator + resolution + File.separator + layer + ".grd")
}
}
} catch (Exception e) {
//ignore
taskLog(e.message)
log.error(e.message)
}
String layerPath = standardLayersDir + File.separator + resolution + File.separator + layer
taskLog("Loading " + layer)
if (new File(layerPath + ".grd").exists()) {
return layerPath
} else {
taskLog("Fatal error: Cannot calculate grid due to missing the layer: " + layer)
log.error("Fatal error: Cannot calculate grid due to missing the layer file: " + layerPath)
return null
}
}
/**
* Determine the grid resolution that will be in use.
*
* @param layers list of layers to be used as String []
* @param resolution target resolution as String
* @return resolution that will be used
*/
private String confirmResolution(String[] layers, String resolution) {
try {
TreeMap<Double, String> resolutions = new TreeMap<Double, String>()
for (String layer : layers) {
String path = getLayerPath(resolution, layer)
int end, start
if (path != null
&& ((end = path.lastIndexOf(File.separator)) > 0)
&& ((start = path.lastIndexOf(File.separator, end - 1)) > 0)) {
String res = path.substring(start + 1, end)
Double d = Double.parseDouble(res)
if (d < 1) {
resolutions.put(d, res)
}
}
}
if (resolutions.size() > 0) {
resolution = resolutions.firstEntry().getValue()
}
} catch (Exception e) {
log.error 'failed to find a al requested layers: ' + layers.join(','), e
}
return resolution
}
private double[][] getLayerFilterExtents(LayerFilter[] envelopes) {
double[][] extents = [[-180, -90], [180, 90]]
for (int i = 0; i < envelopes.length; i++) {
if (envelopes[i].getLayername().startsWith("cl")) {
String[] ids = envelopes[i].getIds()
for (int j = 0; j < ids.length; j++) {
try {
SpatialObjects obj = spatialObjectsService.getObjectByPid(ids[j])
double[][] bbox = SimpleShapeFile.parseWKT(obj.bbox.toString()).getBoundingBox()
extents = internalExtents(extents, bbox)
} catch (Exception e) {
log.error 'failed to bbox for ' + ids[j], e
}
}
}
}
return extents
}
/**
* Get a region mask.
* <p/>
* Note: using decimal degree grid, probably should be EPSG900913 grid.
*
* @param res resolution as double
* @param extents extents as double[][] with [0][0]=xmin, [0][1]=ymin,
* [1][0]=xmax, [1][1]=ymax.
* @param h height as int.
* @param w width as int.
* @param region area for the mask as SimpleRegion.
* @return
*/
private static byte[][] getRegionMask(double[][] extents, int w, int h, SimpleRegion region) {
byte[][] mask = new byte[h][w]
//can also use region.getOverlapGridCells_EPSG900913
region.getOverlapGridCells(extents[0][0], extents[0][1], extents[1][0], extents[1][1], w, h, mask)
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
if (mask[i][j] > 0) {
mask[i][j] = 1
}
}
}
return mask
}
private static byte[][] getMask(int w, int h) {
byte[][] mask = new byte[h][w]
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
mask[i][j] = 1
}
}
return mask
}
/**
* Get a mask, 0=absence, 1=presence, for a given envelope and extents.
*
* @param resolution resolution as String.
* @param res resultions as double.
* @param extents extents as double[][] with [0][0]=xmin, [0][1]=ymin,
* [1][0]=xmax, [1][1]=ymax.
* @param h height as int.
* @param w width as int.
* @param envelopes
* @return mask as byte[][]
*/
private byte[][] getEnvelopeMaskAndUpdateExtents(String resolution, double res, double[][] extents, int h, int w, LayerFilter[] envelopes) {
byte[][] mask = new byte[h][w]
double[][] points = new double[h * w][2]
for (int i = 0; i < w; i++) {
for (int j = 0; j < h; j++) {
points[i + j * w][0] = (double) (extents[0][0] + (i + 0.5) * res)
points[i + j * w][1] = (double) (extents[0][1] + (j + 0.5) * res)
}
}
for (int k = 0; k < envelopes.length; k++) {
LayerFilter lf = envelopes[k]
// if it is contextual and a grid file does not exist at the requested resolution
// and it is not a grid processed as a shape file,
// then get the shape file to do the intersection
if (existsLayerPath(resolution, lf.getLayername(), true) && lf.isContextual()
&& "c".equalsIgnoreCase(getField(lf.getLayername()).type.toString())) {
String[] ids = lf.getIds()
SimpleRegion[] srs = new SimpleRegion[ids.length]
for (int i = 0; i < ids.length; i++) {
srs[i] = SimpleShapeFile.parseWKT(
Util.getUrl(getInput('layersServiceUrl').toString() + "/shape/wkt/" + ids[i])
)
}
for (int i = 0; i < points.length; i++) {
for (int j = 0; j < srs.length; j++) {
if (srs[j].isWithin(points[i][0], points[i][1])) {
mask[(int) (i / w)][i % w]++
break
}
}
}
} else {
Grid grid = Grid.getGrid(getLayerPath(resolution, lf.getLayername()))
float[] d = grid.getValues3(points, 40960)
for (int i = 0; i < d.length; i++) {
if (lf.isValid(d[i])) {
mask[(int) (i / w)][i % w]++
}
}
}
}
for (int i = 0; i < w; i++) {
for (int j = 0; j < h; j++) {
if (mask[j][i] == envelopes.length.byteValue()) {
mask[j][i] = 1
} else {
mask[j][i] = 0
}
}
}
//find internal extents
int minx = w
int maxx = -1
int miny = h
int maxy = -1
for (int i = 0; i < w; i++) {
for (int j = 0; j < h; j++) {
if (mask[j][i] > 0) {
if (minx > i) {
minx = i
}
if (maxx < i) {
maxx = i
}
if (miny > j) {
miny = j
}
if (maxy < j) {
maxy = j
}
}
}
}
//reduce the size of the mask
int nw = maxx - minx + 1
int nh = maxy - miny + 1
byte[][] smallerMask = new byte[nh][nw]
for (int i = minx; i < maxx; i++) {
for (int j = miny; j < maxy; j++) {
smallerMask[j - miny][i - minx] = mask[j][i]
}
}
//update extents, must never be larger than the original extents (res is not negative, minx maxx miny mazy are not negative and < w & h respectively
extents[0][0] = Math.max(extents[0][0] + minx * res, extents[0][0]) //min x value
extents[1][0] = Math.min(extents[1][0] - (w - maxx - 1) * res, extents[1][0]) //max x value
extents[0][1] = Math.max(extents[0][1] + miny * res, extents[0][1]) //min y value
extents[1][1] = Math.min(extents[1][1] - (h - maxy - 1) * res, extents[1][1]) //max y value
return smallerMask
}
static void writeExtents(String filename, double[][] extents, int w, int h) {
if (filename != null) {
try {
FileWriter fw = new FileWriter(filename)
fw.append(String.valueOf(w)).append("\n")
fw.append(String.valueOf(h)).append("\n")
fw.append(String.valueOf(extents[0][0])).append("\n")
fw.append(String.valueOf(extents[0][1])).append("\n")
fw.append(String.valueOf(extents[1][0])).append("\n")
fw.append(String.valueOf(extents[1][1]))
fw.close()
} catch (Exception e) {
log.error(e.getMessage(), e)
}
}
}
void applyMask(String dir, String resolution, double[][] extents, int w, int h, byte[][] mask, String layer) {
//layer output container
double[] dfiltered = new double[w * h]
//open grid and get all data
def path = getLayerPath(resolution, layer)
Grid grid = Grid.getGrid(path)
//set all as missing values
for (int i = 0; i < dfiltered.length; i++) {
dfiltered[i] = Double.NaN
}
double res = Double.parseDouble(resolution)
if (new File(path + '.grd').length() < 100 * 1024 * 1024) {
grid.getGrid()
}
for (int i = 0; i < mask.length; i++) {
for (int j = 0; j < mask[0].length; j++) {
if (mask[i][j] > 0) {
def ds = new double[1][2]
ds[0][0] = j * res + extents[0][0]
ds[0][1] = i * res + extents[0][1]
dfiltered[j + (h - i - 1) * w] = grid.getValues3(ds, 1024 * 1024)[0]
}
}
}
log.debug("Writing grids to " + dir + layer)
grid.writeGrid(dir + layer, dfiltered,
extents[0][0],
extents[0][1],
extents[1][0],
extents[1][1],
res, res, h, w)
}
boolean existsLayerPath(String resolution, String field, boolean do_not_lower_resolution) {
File file = new File(spatialConfig.data.dir.toString() + '/standard_layer/' + File.separator + resolution + File.separator + field + ".grd")
//move up a resolution when the file does not exist at the target resolution
try {
while (!file.exists() && !do_not_lower_resolution) {
TreeMap<Double, String> resolutionDirs = new TreeMap<Double, String>()
for (File dir : new File(spatialConfig.data.dir.toString() + '/standard_layer/').listFiles()) {
if (dir.isDirectory()) {
try {
resolutionDirs.put(Double.parseDouble(dir.getName()), dir.getName())
} catch (Exception ignored) {
}
}
}
String newResolution = resolutionDirs.higherEntry(Double.parseDouble(resolution)).getValue()
if (newResolution == resolution) {
break
} else {
resolution = newResolution
file = new File(spatialConfig.data.dir.toString() + '/standard_layer/' + File.separator + resolution + File.separator + field + ".grd")
}
}
} catch (err) {
log.error 'failed to find path for: ' + field + ' : ' + resolution, err
}
String layerPath = spatialConfig.data.dir + '/standard_layer/' + File.separator + resolution + File.separator + field
return new File(layerPath + ".grd").exists()
}