45 |
46 |
47 |
--------------------------------------------------------------------------------
/mesh/js/kernel.ts:
--------------------------------------------------------------------------------
1 | import promiseUtils = require("esri/core/promiseUtils");
2 | /**
3 | */
4 | type HSize = [number, number];
5 |
6 | interface HPoint {
7 | r: number,
8 | c: number,
9 | w: number
10 | }
11 |
12 | class HMatrix {
13 | size: number;
14 | cols: number;
15 | farr: Float32Array;
16 |
17 | constructor(numRows: number, numCols: number) {
18 | this.size = numRows * numCols;
19 | this.cols = numCols;
20 | this.farr = new Float32Array(this.size);
21 | }
22 |
23 | update(r: number, c: number, w: number) {
24 | const index = r * this.cols + c;
25 | this.farr[index] += w;
26 | }
27 |
28 | }
29 |
30 | class KernelCalculator {
31 | lastRadius: number = -1.0;
32 | blurSize: number = 0.0;
33 | kernel: Float32Array;
34 |
35 | calculateKernel(pointArr: Array, size: HSize, radius: number) {
36 | const [numRows, numCols] = size;
37 | const maxRows = numRows - 1;
38 | const maxCols = numCols - 1;
39 | const numPoints = pointArr.length;
40 | // Calculate the kernel
41 | if (this.lastRadius !== radius) {
42 | this.lastRadius = radius;
43 | this.blurSize = Math.round(radius * 2.0);
44 | const deno = -2.0 * radius * radius;
45 | const nume = radius / (2.0 * Math.sqrt(2.0 * Math.PI));
46 | const kernelSize = this.blurSize * 2 + 1;
47 | this.kernel = new Float32Array(kernelSize);
48 | for (let i = 0; i < kernelSize; i++) {
49 | const d0 = i - this.blurSize;
50 | const d2 = d0 * d0;
51 | this.kernel[i] = Math.exp(d2 / deno) * nume;
52 | }
53 | }
54 | // Update "2D" matrix values with kernel weighting
55 | const matrix = new HMatrix(numRows, numCols);
56 | for (let i = 0; i < numPoints; i++) {
57 | const py = pointArr[i].r;
58 | const px = pointArr[i].c;
59 | const sc = px - this.blurSize;
60 | const sr = py - this.blurSize;
61 | const cmin = Math.max(0, sc);
62 | const cmax = Math.min(maxCols, px + this.blurSize);
63 | const rmin = Math.max(0, sr);
64 | const rmax = Math.min(maxRows, py + this.blurSize);
65 | for (let r = rmin; r <= rmax; r++) {
66 | const ky = this.kernel[r - sr];
67 | for (let c = cmin; c <= cmax; c++) {
68 | matrix.update(r, c, pointArr[i].w * ky * this.kernel[c - sc]);
69 | }
70 | }
71 | }
72 | return matrix.farr;
73 | }
74 |
75 | }
76 |
77 | export = KernelCalculator;
78 |
--------------------------------------------------------------------------------
/mesh/js/kernel.js:
--------------------------------------------------------------------------------
1 | define(["require", "exports"], function (require, exports) {
2 | "use strict";
3 | var HMatrix = (function () {
4 | function HMatrix(numRows, numCols) {
5 | this.size = numRows * numCols;
6 | this.cols = numCols;
7 | this.farr = new Float32Array(this.size);
8 | }
9 | HMatrix.prototype.update = function (r, c, w) {
10 | var index = r * this.cols + c;
11 | this.farr[index] += w;
12 | };
13 | return HMatrix;
14 | }());
15 | var KernelCalculator = (function () {
16 | function KernelCalculator() {
17 | this.lastRadius = -1.0;
18 | this.blurSize = 0.0;
19 | }
20 | KernelCalculator.prototype.calculateKernel = function (pointArr, size, radius) {
21 | var numRows = size[0], numCols = size[1];
22 | var maxRows = numRows - 1;
23 | var maxCols = numCols - 1;
24 | var numPoints = pointArr.length;
25 | // Calculate the kernel
26 | if (this.lastRadius !== radius) {
27 | this.lastRadius = radius;
28 | this.blurSize = Math.round(radius * 2.0);
29 | var deno = -2.0 * radius * radius;
30 | var nume = radius / (2.0 * Math.sqrt(2.0 * Math.PI));
31 | var kernelSize = this.blurSize * 2 + 1;
32 | this.kernel = new Float32Array(kernelSize);
33 | for (var i = 0; i < kernelSize; i++) {
34 | var d0 = i - this.blurSize;
35 | var d2 = d0 * d0;
36 | this.kernel[i] = Math.exp(d2 / deno) * nume;
37 | }
38 | }
39 | // Update "2D" matrix values with kernel weighting
40 | var matrix = new HMatrix(numRows, numCols);
41 | for (var i = 0; i < numPoints; i++) {
42 | var py = pointArr[i].r;
43 | var px = pointArr[i].c;
44 | var sc = px - this.blurSize;
45 | var sr = py - this.blurSize;
46 | var cmin = Math.max(0, sc);
47 | var cmax = Math.min(maxCols, px + this.blurSize);
48 | var rmin = Math.max(0, sr);
49 | var rmax = Math.min(maxRows, py + this.blurSize);
50 | for (var r = rmin; r <= rmax; r++) {
51 | var ky = this.kernel[r - sr];
52 | for (var c = cmin; c <= cmax; c++) {
53 | matrix.update(r, c, pointArr[i].w * ky * this.kernel[c - sc]);
54 | }
55 | }
56 | }
57 | return matrix.farr;
58 | };
59 | return KernelCalculator;
60 | }());
61 | return KernelCalculator;
62 | });
63 |
--------------------------------------------------------------------------------
/mesh/css/main.css:
--------------------------------------------------------------------------------
1 | html,
2 | body {
3 | padding: 0;
4 | margin: 0;
5 | width: 100%;
6 | height: 100%;
7 | color: #c8c8c8;
8 | overflow: hidden;
9 | background-color: #505050;
10 | font-family: 'Helvetica', 'Arial', sans-serif;
11 | }
12 |
13 | .bg {
14 | background-color: rgba(0, 0, 0, 0.5);
15 | }
16 |
17 | #panelView {
18 | position: absolute;
19 | width: 100%;
20 | height: 100%;
21 | display: block;
22 | overflow: hidden;
23 | }
24 |
25 | #panelBottom {
26 | position: absolute;
27 | bottom: 18px;
28 | width: 100%;
29 | height: 80px;
30 | overflow: hidden;
31 | }
32 |
33 | #panelDate {
34 | position: absolute;
35 | top: 10px;
36 | left: 10px;
37 | right: 10px;
38 | height: 20px;
39 | line-height: 20px;
40 | font-size: 18px;
41 | }
42 |
43 | #panelSlider {
44 | position: absolute;
45 | bottom: 10px;
46 | left: 10px;
47 | right: 10px;
48 | height: 30px;
49 | line-height: 30px;
50 | }
51 |
52 | .dijitSliderBar {
53 | border-style: solid;
54 | border-color: black;
55 | background-color: #787878;
56 | cursor: pointer;
57 | -webkit-tap-highlight-color: transparent;
58 | }
59 |
60 | .dijitSliderImageHandle {
61 | margin: 0;
62 | padding: 0;
63 | position: relative !important;
64 | border: 8px solid #ffffff;
65 | width: 0;
66 | height: 0;
67 | border-radius: 8px;
68 | cursor: pointer;
69 | -webkit-tap-highlight-color: transparent;
70 | }
71 |
72 | #panelSettings {
73 | position: absolute;
74 | top: 10px;
75 | right: -240px;
76 | width: 240px;
77 | height: 500px;
78 | font-size: 12px;
79 | -webkit-transition: all 0.5s;
80 | -moz-transition: all 0.5s;
81 | -o-transition: all 0.5s;
82 | transition: all 0.5s;
83 | }
84 |
85 | .open {
86 | right: 0px !important;
87 | }
88 |
89 | #icon {
90 | position: absolute;
91 | left: -40px;
92 | top: 10px;
93 | width: 40px;
94 | height: 48px;
95 | border-radius: 24px 0 0 24px;
96 | line-height: 48px;
97 | background-position: center center;
98 | background-repeat: no-repeat;
99 | background-size: 18px;
100 | background-image: url(../img/gear.png);
101 | cursor: pointer;
102 | }
103 |
104 | .inner {
105 | position: absolute;
106 | left: 10px;
107 | right: 10px;
108 | top: 10px;
109 | bottom: 10px;
110 | }
111 |
112 | .row {
113 | width: 100%;
114 | height: 24px;
115 | line-height: 24px;
116 | }
117 |
118 | .switch {
119 | float: left;
120 | width: 50%;
121 | text-align: center;
122 | background-color: #6e6e6e;
123 | border-radius: 3px;
124 | cursor: pointer;
125 | }
126 |
127 | .on {
128 | background-color: #ffffff;
129 | }
130 |
131 | .swatch {
132 | float: right;
133 | width: 18px;
134 | height: 18px;
135 | cursor: pointer;
136 | margin: 2px;
137 | border: 1px solid #ffffff;
138 | }
139 |
140 | .dijitColorPalette {
141 | border: none !important;
142 | background: transparent !important;
143 | }
144 |
145 | .dijitColorPalette .dijitColorPaletteSwatch {
146 | height: 12px;
147 | width: 12px;
148 | }
149 |
150 | .dijitColorPalette .dijitPaletteImg {
151 | border: none !important;
152 | }
153 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Space Time Ripple
2 |
3 | Start by viewing [this application](https://dl.dropboxusercontent.com/u/2193160/mesh/index.html).
4 |
5 | 
6 |
7 | Make sure to tilt the map by holding down the right mouse button and sliding the mouse up. Then, slide the bottom slider back and forth to see the data "ripple" through time. This is displaying the density of 1 million [NYC taxi](http://www.nyc.gov/html/tlc/html/about/trip_record_data.shtml) pickups aggregated over 30 minute intervals. This application is based on the new [4.2 ArcGIS API for JavaScript](https://developers.arcgis.com/javascript/) and specifically on the [externalRenderers](https://developers.arcgis.com/javascript/latest/api-reference/esri-views-3d-externalRenderers.html) capabilities, where a JS application can delegate the rendering to custom [WebGL](https://www.khronos.org/webgl/) code.
8 |
9 | This project is divided into 2 sub-projects:
10 |
11 | - An [ArcPy](http://pro.arcgis.com/en/pro-app/arcpy/get-started/what-is-arcpy-.htm) based [Pro](https://pro.arcgis.com/en/pro-app/) toolbox to aggregate and prepare the data.
12 | - A JavaScript application to view the prepared data.
13 |
14 | ## Mesh Toolbox
15 |
16 | 
17 |
18 | Make sure to `pip install sortedcontainers`.
19 |
20 | This tool bins over space and time the input point features to produce on the local file system a "space-time-cube" in the form of a [DOJO AMD Module](http://dojotoolkit.org/documentation/tutorials/1.10/modules/). The following is a very simplistic output, but demonstrates the module content.
21 |
22 | ```
23 | define({
24 | "mesh": {
25 | "ymax": 40.86254766648426,
26 | "xmin": -74.0984483274695,
27 | "ymin": 40.632320706393344,
28 | "cols": 2,
29 | "rows": 2,
30 | "vertices": [-74.0984483274695, 40.86254766648426, 100, -73.69913039514432, 40.86254766648426, 100, -74.0984483274695, 40.632320706393344, 100, -73.69913039514432, 40.632320706393344, 100],
31 | "xmax": -73.69913039514432,
32 | "indices": [1, 0, 2, 2, 3, 1],
33 | "length": 4
34 | },
35 | "data": {
36 | "min": 980557.0,
37 | "stddev": 0.0,
38 | "max": 980557.0,
39 | "mean": 980557.0,
40 | "data": [{"datetime": "2012-12-21 00:00:00", "points": [{"w": 0.2, "r": 1, "p": 980557, "c": 0}]}]
41 | }
42 | });
43 | ```
44 |
45 | The `mesh` property has the world extent (`xmin`,`ymin`,`xmax`,`ymax`) of the mesh based on the map current extent, and defines the vertices of the nodes forming the mesh as a sequence of triples (lon,lat,elevation). WebGL renders the mesh as a sequence of triangles using the [WebGLRenderingContext.drawElements()](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/drawElements) where the `mode` is set to `gl.TRIANGLES`. The `drawElements` uses the `indicies` and the "converted" (more on this later) `vertices` to draw efficiently and quickly the triangles.
46 |
47 | The `data` property defines the space-time-cube. During the module preparation, the input features are binned by space using their geometry into rows and column tuples and by time using their temporal attribute into interval buckets. In addition, the `mean` and `stddev` of the bin counts are calculate using an [online variance](https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance). The values `min` and `max` values are derived using `mean` ± `stddev` and used to weight the bin count (`p`) and produce a weight `w` ∈ \[0,1\] in the subsequently defined `points` elements.
48 | The `data` sub-property is an array of objects sorted by `datetime` interval buckets and contain a `points` sub-property. The latter is an array of objects with population bin count values (`p`) for a mesh row (`r`) and column (`c`) vertex.
49 |
50 | So for each time interval bucket, the mesh vertices are "elevated" and color coded in proportion to their `w` point value.
51 |
52 | The Interval parameter in the tool accepts a string in the form of a number followed by either a `s` (seconds), `m` (minutes), `d` (days), `w` (weeks). So a string value of `30s` means an interval of 30 seconds, and a string value of `2d` means an interval of 2 days.
53 |
54 | This tool depends on [SortedContainers](http://www.grantjenks.com/docs/sortedcontainers/), so make sure to use `Add Packages` to add the library to your Pro Python environment.
55 |
56 | 
57 |
58 | ## JavaScript Application
59 |
60 | The generated space-time cube JavaScript code is loaded at startup time into the application as an AMD module and is rendered using the [4.2 ArcGIS API for JavaScript](https://developers.arcgis.com/javascript/) with the experimental [externalRenderers](https://developers.arcgis.com/javascript/latest/api-reference/esri-views-3d-externalRenderers.html) which enables the application to invoke [WebGL](https://www.khronos.org/webgl/) [shaders](https://webglfundamentals.org/webgl/lessons/webgl-shaders-and-glsl.html). The shaders are compiled and initialized in the `setup` function of an `externalRenderer` instance and continuously invoked in the `render` function.
61 |
62 | The following is a snippet in the `render` function:
63 |
64 | ```
65 | var camera = context.camera;
66 | gl.uniformMatrix4fv(this.pMatrixUniform, false, camera.projectionMatrix);
67 | gl.uniformMatrix4fv(this.vMatrixUniform, false, camera.viewMatrix);
68 |
69 | externalRenderers.toRenderCoordinates(
70 | this.view,
71 | this.vertices,
72 | 0,
73 | SpatialReference.WGS84,
74 | this.arrPosition,
75 | 0,
76 | appMesh.length);
77 | ```
78 |
79 | Note how we are taking advantage to the `camera` projection matrix and view matrix properties to populate the vertex shader `uPMatrix` and `uVMatrix` uniforms used in the `gl_Position` calculation. In addition, and this is SOOOO USEFUL, note the usage of the `toRenderCoordinates(...)` function that converts the mesh vertices world coordinates to WebGL coordinates based on the camera position.
80 |
81 | The application enables the user to drag back and forth a slider where the slider position is an index into the space-time cube `data.data` array, where all the `points` associated with that "datetime" will be mapped to the mesh vertices and elevated.
82 | The vertex elevation is proportional to the `w` value of a point. In addition, all the neighboring vertices are also elevated, but in proportion to a kernel distance function providing a smooth elevated surface.
83 |
84 | 
85 |
86 | To view the application, place the `mesh` folder in your web server or you can start a simple web server in the `mesh` folder:
87 |
88 | ```
89 | python -m SimpleHTTPServer 8000
90 | ```
91 |
92 | Open a browser (preferably Chrome) and navigate to
93 |
94 | ### TypeScript
95 |
96 | Note that the kernel elevation is occurring in the `kernel.ts` code writen in [TypeScript](https://www.typescriptlang.org/). I have to confess that is a bit selfish on my part for "mixing" languages, as JavaScript is not my favorite language, and I long for the days when I used to write statically typed [AS3](https://en.wikipedia.org/wiki/ActionScript) code. Typescript is pretty cool, has great community support and we at Esri have made significant investments in supporting it. Check out [this](https://github.com/Esri/jsapi-resources/tree/master/4.x/typescript) github repo to setup your development environment.
97 | In addition, it is **HIGHLY** recommended to use an IDE like [IntelliJ](https://www.jetbrains.com/idea/) or [WebStorm](https://www.jetbrains.com/help/webstorm/2016.3/typescript-support.html) with TypeScript support If you need to modify the `js/kernel.ts` file.
98 |
99 | 
100 |
101 | ### References
102 |
103 | -
104 | -
105 |
106 | ### Notes to self
107 |
108 | - Initialize the project using `npm init`
109 | - Install TS typings using `npm install --save @types/arcgis-js-api`
110 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2017 Mansour Raad
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/mesh/js/main.js:
--------------------------------------------------------------------------------
1 | require({
2 | packages: [{
3 | name: "app",
4 | location: window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/')) + '/js'
5 | }]
6 | }, [
7 | "dojo/dom",
8 | "dojo/dom-attr",
9 | "dojo/dom-class",
10 | "dojo/dom-construct",
11 | "dojo/dom-style",
12 | "dojo/_base/lang",
13 | "dojo/on",
14 | "esri/Map",
15 | "esri/Camera",
16 | "esri/Color",
17 | "esri/geometry/SpatialReference",
18 | "esri/geometry/Extent",
19 | "esri/views/SceneView",
20 | "esri/views/3d/externalRenderers",
21 | "esri/core/declare",
22 | "dijit/ColorPalette",
23 | "dijit/form/HorizontalSlider",
24 | "app/kernel",
25 | "app/heat",
26 | "dojo/domReady!"
27 | ], function (dom,
28 | domAttr,
29 | domClass,
30 | domConstruct,
31 | domStyle,
32 | lang,
33 | on,
34 | Map,
35 | Camera,
36 | Color,
37 | SpatialReference,
38 | Extent,
39 | SceneView,
40 | externalRenderers,
41 | declare,
42 | ColorPalette,
43 | HorizontalSlider,
44 | KernelCalculator,
45 | appHeat) {
46 |
47 | "use strict";
48 |
49 | const appData = appHeat.data.data;
50 | const appMesh = appHeat.mesh;
51 |
52 | const MeshRend = declare(null, {
53 | view: null,
54 | vertices: appMesh.vertices,
55 | program: null,
56 | pMatrixUniform: null,
57 | vMatrixUniform: null,
58 | aPosition: null,
59 | uColorOrig: null,
60 | uColorDest: null,
61 | aMult: null,
62 | bufPosition: null,
63 | bufMult: null,
64 | bufIndex: null,
65 | arrPosition: new Float32Array(3 * appMesh.length),
66 | arrColorOrig: [0, 0, 0],
67 | arrColorDest: [0, 0, 0],
68 | arrMult: new Float32Array(appMesh.length),
69 | /**
70 | * Dojo constructor
71 | */
72 | constructor: function (view) {
73 | this.view = view;
74 | },
75 | /**
76 | * Called once after this external renderer is added to the scene.
77 | * This is part of the external renderer interface.
78 | */
79 | setup: function (context) {
80 | try {
81 | this.initShaders(context);
82 | } finally {
83 | context.resetWebGLState();
84 | }
85 | },
86 | /**
87 | * Called each time the scene is rendered.
88 | * This is part of the external renderer interface.
89 | */
90 | render: function (context) {
91 | const gl = context.gl;
92 |
93 | gl.useProgram(this.program);
94 |
95 | gl.enable(gl.DEPTH_TEST);
96 | gl.enable(gl.CULL_FACE);
97 | gl.enable(gl.BLEND);
98 | gl.blendFuncSeparate(
99 | gl.SRC_ALPHA,
100 | gl.ONE_MINUS_SRC_ALPHA,
101 | gl.ONE,
102 | gl.ONE_MINUS_SRC_ALPHA
103 | );
104 |
105 | var camera = context.camera;
106 | gl.uniformMatrix4fv(this.pMatrixUniform, false, camera.projectionMatrix);
107 | gl.uniformMatrix4fv(this.vMatrixUniform, false, camera.viewMatrix);
108 |
109 | externalRenderers.toRenderCoordinates(
110 | this.view,
111 | this.vertices,
112 | 0,
113 | SpatialReference.WGS84,
114 | this.arrPosition,
115 | 0,
116 | appMesh.length);
117 |
118 | this.draw(gl);
119 |
120 | externalRenderers.requestRender(this.view);
121 | // cleanup
122 | context.resetWebGLState();
123 | // fix for bug in the JS API 4.2, related to RibbonLineMaterial
124 | gl.blendFuncSeparate(
125 | gl.SRC_ALPHA,
126 | gl.ONE_MINUS_SRC_ALPHA,
127 | gl.ONE,
128 | gl.ONE_MINUS_SRC_ALPHA
129 | );
130 | },
131 | draw: function (gl) {
132 | gl.uniform3fv(this.uColorOrig, new Float32Array(this.arrColorOrig));
133 | gl.uniform3fv(this.uColorDest, new Float32Array(this.arrColorDest));
134 |
135 | gl.bindBuffer(gl.ARRAY_BUFFER, this.bufPosition);
136 | gl.bufferData(gl.ARRAY_BUFFER, this.arrPosition, gl.STATIC_DRAW);
137 | gl.vertexAttribPointer(this.aPosition, 3, gl.FLOAT, false, 0, 0);
138 | gl.enableVertexAttribArray(this.aPosition);
139 |
140 | gl.bindBuffer(gl.ARRAY_BUFFER, this.bufMult);
141 | gl.bufferData(gl.ARRAY_BUFFER, this.arrMult, gl.STATIC_DRAW);
142 | gl.vertexAttribPointer(this.aMult, 1, gl.FLOAT, false, 0, 0);
143 | gl.enableVertexAttribArray(this.aMult);
144 |
145 | gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.bufIndex);
146 |
147 | const glMode = _mode !== "mesh" ? gl.TRIANGLES : gl.LINES;
148 | gl.drawElements(glMode, appMesh.indices.length, gl.UNSIGNED_SHORT, 0);
149 | },
150 | initShaders: function (context) {
151 | const gl = context.gl;
152 | const v = 'uniform mat4 uPMatrix;' +
153 | 'uniform mat4 uVMatrix;' +
154 | 'attribute vec3 aPosition;' +
155 | 'attribute float aMult;' +
156 | 'varying float vMult;' +
157 | 'void main(void) {' +
158 | 'vMult = clamp(aMult*2.0,0.0,0.95);' +
159 | 'gl_Position = uPMatrix * uVMatrix * vec4(aPosition, 1.0);' +
160 | 'gl_Position.z -= 1.0;' +
161 | '}';
162 | const f = 'precision mediump float;' +
163 | 'uniform vec3 uColorOrig;' +
164 | 'uniform vec3 uColorDest;' +
165 | 'varying float vMult;' +
166 | 'void main(void) {' +
167 | 'gl_FragColor = (1.0 - vMult) * vec4(uColorOrig, vMult) + vMult * vec4(uColorDest, vMult);' +
168 | '}';
169 |
170 | const vShader = gl.createShader(gl.VERTEX_SHADER);
171 | const fShader = gl.createShader(gl.FRAGMENT_SHADER);
172 |
173 | gl.shaderSource(vShader, v);
174 | gl.shaderSource(fShader, f);
175 |
176 | gl.compileShader(vShader);
177 | if (!gl.getShaderParameter(vShader, gl.COMPILE_STATUS)) {
178 | alert(gl.getShaderInfoLog(vShader));
179 | return;
180 | }
181 | gl.compileShader(fShader);
182 | if (!gl.getShaderParameter(fShader, gl.COMPILE_STATUS)) {
183 | alert(gl.getShaderInfoLog(fShader));
184 | return;
185 | }
186 |
187 | this.program = gl.createProgram();
188 |
189 | gl.attachShader(this.program, vShader);
190 | gl.attachShader(this.program, fShader);
191 |
192 | gl.linkProgram(this.program);
193 | if (!gl.getProgramParameter(this.program, gl.LINK_STATUS)) {
194 | alert(gl.getShaderInfoLog(this.program));
195 | return;
196 | }
197 |
198 | this.pMatrixUniform = gl.getUniformLocation(this.program, 'uPMatrix');
199 | this.vMatrixUniform = gl.getUniformLocation(this.program, 'uVMatrix');
200 |
201 | this.aPosition = gl.getAttribLocation(this.program, 'aPosition');
202 | this.uColorOrig = gl.getUniformLocation(this.program, 'uColorOrig');
203 | this.uColorDest = gl.getUniformLocation(this.program, 'uColorDest');
204 | this.aMult = gl.getAttribLocation(this.program, 'aMult');
205 |
206 | this.bufPosition = gl.createBuffer();
207 | this.bufMult = gl.createBuffer();
208 | this.bufIndex = gl.createBuffer();
209 |
210 | gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.bufIndex);
211 | gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(appMesh.indices), gl.STATIC_DRAW);
212 | }
213 | });
214 |
215 | var map = new Map({
216 | basemap: 'dark-gray'
217 | });
218 |
219 | var view = new SceneView({
220 | container: 'panelView',
221 | map: map,
222 | extent: new Extent({xmin: appMesh.xmin, ymin: appMesh.ymin, xmax: appMesh.xmax, ymax: appMesh.ymax})
223 | });
224 | view.then(function () {
225 | updateUI();
226 | }, function (err) {
227 | alert('Error:' + err);
228 | });
229 |
230 | var _dtIndex = 0;
231 | var _mode = "mesh";
232 | var _origColor = "#0000ff";
233 | var _destColor = "#ff0000";
234 | var _radius = 2;
235 | var _meshRend;
236 | var _heatmapCalc;
237 |
238 | const _size = [appMesh.rows, appMesh.cols];
239 |
240 | function updateUI() {
241 | _meshRend = new MeshRend(view);
242 | externalRenderers.add(view, _meshRend);
243 |
244 | _heatmapCalc = new KernelCalculator();
245 |
246 | new HorizontalSlider({
247 | value: 0,
248 | minimum: 0,
249 | maximum: Math.max(0, appData.length - 1),
250 | discreteValues: appData.length,
251 | intermediateChanges: true,
252 | showButtons: false,
253 | style: "width:90%;",
254 | onChange: horizontalSlider_changeHandler
255 | }, "panelSlider").startup();
256 |
257 | on(dom.byId("icon"), "click", toggleSettings);
258 | on(dom.byId("switchMesh"), "click", lang.hitch(this, setMode, "mesh"));
259 | on(dom.byId("switchSurface"), "click", lang.hitch(this, setMode, "surface"));
260 |
261 | new ColorPalette({
262 | palette: "7x10",
263 | onChange: function (val) {
264 | changeOrigColor(val);
265 | }
266 | }, "startColor").startup();
267 |
268 | new ColorPalette({
269 | palette: "7x10",
270 | onChange: function (val) {
271 | changeDestColor(val);
272 | }
273 | }, "endColor").startup();
274 |
275 | new HorizontalSlider({
276 | value: 2,
277 | minimum: 1,
278 | maximum: 5,
279 | discreteValues: 10,
280 | intermediateChanges: true,
281 | showButtons: false,
282 | style: "width:90%;",
283 | onChange: radiusSlider_changeHandler
284 | }, "radiusSlider").startup();
285 |
286 | updateViz();
287 | }
288 |
289 | function updateViz() {
290 | const sRGB = normalizeRGB(Color.fromHex(_origColor).toRgb());
291 | const eRGB = normalizeRGB(Color.fromHex(_destColor).toRgb());
292 | const data = appData[_dtIndex];
293 | dom.byId("panelDate").innerHTML = data.datetime;
294 | const zArr = _heatmapCalc.calculateKernel(data.points, _size, _radius);
295 | const vertices = appMesh.vertices.slice(0);
296 | var z = 2;
297 | for (var i = 0; i < appMesh.length; i++) {
298 | vertices[z] = 25 + 5000 * zArr[i];
299 | z += 3;
300 | }
301 | _meshRend.arrColorOrig = sRGB;
302 | _meshRend.arrColorDest = eRGB;
303 | _meshRend.arrMult = zArr;
304 | _meshRend.vertices = vertices;
305 | }
306 |
307 | function normalizeRGB(rgb) {
308 | const r = rgb[0] / 255;
309 | const g = rgb[1] / 255;
310 | const b = rgb[2] / 255;
311 | return [r, g, b];
312 | }
313 |
314 | function horizontalSlider_changeHandler(index) {
315 | _dtIndex = index;
316 | updateViz();
317 | }
318 |
319 | function toggleSettings() {
320 | domClass.toggle("panelSettings", "open");
321 | }
322 |
323 | function setMode(value) {
324 | _mode = value;
325 | if (_mode === "mesh") {
326 | domClass.add("switchMesh", "on");
327 | domClass.remove("switchSurface", "on");
328 | } else {
329 | domClass.remove("switchMesh", "on");
330 | domClass.add("switchSurface", "on");
331 | }
332 | }
333 |
334 | function changeOrigColor(value) {
335 | _origColor = value;
336 | domStyle.set("startSwatch", "background-color", value);
337 | updateViz();
338 | }
339 |
340 | function changeDestColor(value) {
341 | _destColor = value;
342 | domStyle.set("endSwatch", "background-color", value);
343 | updateViz();
344 | }
345 |
346 | function radiusSlider_changeHandler(value) {
347 | _radius = value;
348 | updateViz();
349 | }
350 |
351 | });
352 |
--------------------------------------------------------------------------------
/arcpy/MeshToolbox.pyt:
--------------------------------------------------------------------------------
1 | #
2 | # http://www.grantjenks.com/docs/sortedcontainers/introduction.html
3 | # pip install sortedcontainers
4 | #
5 |
6 | import arcpy
7 | import json
8 | import os
9 | import time
10 | from datetime import timedelta
11 | from math import *
12 | from sortedcontainers import SortedDict
13 |
14 |
15 | class Toolbox(object):
16 | def __init__(self):
17 | self.label = "MeshToolbox"
18 | self.alias = "MeshToolbox"
19 | self.tools = [MeshTool]
20 |
21 |
22 | class MeshTool(object):
23 | def __init__(self):
24 | self.label = "Mesh Tool"
25 | self.description = "Mesh Tool"
26 | self.canRunInBackground = False
27 | self.input_fc = None
28 |
29 | def getParameterInfo(self):
30 | output_fl = arcpy.Parameter(
31 | name='mesh',
32 | displayName='mesh',
33 | direction='Output',
34 | datatype='Feature Layer',
35 | parameterType='Derived')
36 | output_fl.symbology = os.path.join(os.path.dirname(__file__), "Mesh.lyr")
37 |
38 | input_fc = arcpy.Parameter(
39 | name="input_fc",
40 | displayName="Input Feature Class",
41 | direction="Input",
42 | datatype="Table View",
43 | parameterType="Required")
44 |
45 | num_cells = arcpy.Parameter(
46 | name="num_cells",
47 | displayName="Num Cells",
48 | direction="Input",
49 | datatype="Long",
50 | parameterType="Required")
51 | num_cells.value = 10
52 |
53 | min_count = arcpy.Parameter(
54 | name="min_count",
55 | displayName="Min Count Per Cell",
56 | direction="Input",
57 | datatype="Long",
58 | parameterType="Required")
59 | min_count.value = 1
60 |
61 | interval = arcpy.Parameter(
62 | name="interval",
63 | displayName="Time Interval",
64 | direction="Input",
65 | datatype="String",
66 | parameterType="Required")
67 | interval.value = "30m"
68 |
69 | path = arcpy.Parameter(
70 | name="path",
71 | displayName="JS Output File",
72 | direction="Input",
73 | datatype="String",
74 | parameterType="Required")
75 | path.value = os.path.join(os.path.dirname(__file__), "heat.js")
76 |
77 | date_field = arcpy.Parameter(
78 | name="date_field",
79 | displayName="Date Field",
80 | direction="Input",
81 | datatype="String",
82 | parameterType="Required")
83 | date_field.filter.type = "ValueList"
84 | date_field.filter.list = []
85 |
86 | case_field = arcpy.Parameter(
87 | name="case_field",
88 | displayName="Case Field",
89 | direction="Input",
90 | datatype="String",
91 | parameterType="Required")
92 | case_field.filter.type = "ValueList"
93 | case_field.filter.list = []
94 |
95 | bbox = arcpy.Parameter(
96 | name="bbox",
97 | displayName="Bounding Box",
98 | direction="Input",
99 | datatype="GPExtent",
100 | parameterType="Required")
101 |
102 | return [output_fl, input_fc, num_cells, date_field, case_field, min_count, interval, path, bbox]
103 |
104 | def isLicensed(self):
105 | return True
106 |
107 | def updateParameters(self, parameters):
108 | input_fc = parameters[1].value
109 | if self.input_fc != input_fc:
110 | self.input_fc = input_fc
111 | date_field = parameters[3]
112 | case_field = parameters[4]
113 | date_list = []
114 | case_list = []
115 | description = arcpy.Describe(input_fc)
116 | for field in description.fields:
117 | if field.type == "Date":
118 | date_list.append(field.name)
119 | if field.type in ["Double", "Integer", "Single", "SmallInteger"]:
120 | case_list.append(field.name)
121 | date_list = sorted(date_list)
122 | date_field.filter.list = date_list
123 | date_field.value = date_list[0] if len(date_list) > 0 else ""
124 | case_list = sorted(case_list)
125 | case_field.filter.list = case_list
126 | case_field.value = case_list[0] if len(case_list) > 0 else ""
127 |
128 | def updateMessages(self, parameters):
129 | return
130 |
131 | def create_mesh(self, extent_84, cells):
132 | arcpy.SetProgressorLabel("Creating mesh...")
133 |
134 | xmin = extent_84.XMin
135 | ymin = extent_84.YMin
136 | xmax = extent_84.XMax
137 | ymax = extent_84.YMax
138 |
139 | cols = cells
140 | rows = cells
141 |
142 | # Generate indices to triangle vertices
143 | indicies = []
144 | for r0 in range(0, rows - 1):
145 | for c0 in range(0, cols - 1):
146 | r1 = r0 + 1
147 | c1 = c0 + 1
148 | tl = r0 * cols + c0
149 | tr = r0 * cols + c1
150 | bl = r1 * cols + c0
151 | br = r1 * cols + c1
152 | indicies.extend([tr, tl, bl, bl, br, tr])
153 |
154 | x_del = (xmax - xmin) / (cols - 1)
155 | y_del = (ymax - ymin) / (rows - 1)
156 |
157 | # Generate vertices locations
158 | vertices = []
159 | y = ymax
160 | for _ in range(0, rows):
161 | ofs = xmin
162 | for _ in range(0, cols):
163 | vertices.extend([ofs, y, 100])
164 | ofs += x_del
165 | y -= y_del
166 |
167 | obj = {
168 | 'rows': rows,
169 | 'cols': cols,
170 | 'xmin': xmin,
171 | 'ymin': ymin,
172 | 'xmax': xmax,
173 | 'ymax': ymax,
174 | 'length': cols * rows,
175 | 'vertices': vertices,
176 | 'indices': indicies
177 | }
178 | return obj
179 |
180 | def create_data(self, extent_84, sr_84, input_fc, cells, min_count, interval, date_field, case_field):
181 | int_text = interval[-1]
182 | int_nume = int(interval[:-1])
183 | if int_text == "s":
184 | seconds = timedelta(seconds=int_nume).total_seconds()
185 | elif int_text == "m":
186 | seconds = timedelta(minutes=int_nume).total_seconds()
187 | elif int_text == "h":
188 | seconds = timedelta(hours=int_nume).total_seconds()
189 | elif int_text == "d":
190 | seconds = timedelta(days=int_nume).total_seconds()
191 | elif int_text == "w":
192 | seconds = timedelta(weeks=int_nume).total_seconds()
193 | else:
194 | seconds = int(interval)
195 |
196 | time_dict = SortedDict()
197 | xmin = extent_84.XMin
198 | ymin = extent_84.YMin
199 | xmax = extent_84.XMax
200 | ymax = extent_84.YMax
201 | x_fac = cells / (xmax - xmin)
202 | y_fac = cells / (ymax - ymin)
203 | result = arcpy.management.GetCount(input_fc)
204 | max_range = int(result.getOutput(0))
205 | step_max = int(max(1, max_range / 100))
206 | step_cnt = 0
207 | arcpy.SetProgressor("step", "Searching...", 0, max_range, step_max)
208 | # Query space and time attributes from features
209 | fields = ["SHAPE@X", "SHAPE@Y", date_field, case_field]
210 | with arcpy.da.SearchCursor(input_fc, fields, spatial_reference=sr_84) as cursor:
211 | for elem in cursor:
212 | step_cnt += 1
213 | arcpy.SetProgressorPosition(step_cnt)
214 | shape_x = elem[0]
215 | shape_y = elem[1]
216 | # Make sure it is in the map extent
217 | if xmin < shape_x < xmax and ymin < shape_y < ymax:
218 | date_value = elem[2]
219 | case_value = elem[3]
220 | # Snap X/Y to ROW/COL bucket
221 | col = floor(x_fac * (shape_x - xmin))
222 | row = cells - floor(y_fac * (shape_y - ymin))
223 | tup = (row, col)
224 | # Snap TIME to a temporal bucket
225 | time_key = int(time.mktime(date_value.timetuple()) / seconds)
226 | if time_key in time_dict:
227 | time_val = time_dict[time_key]
228 | if tup in time_val:
229 | prev_val, prev_cnt = time_val[tup]
230 | time_val[tup] = (max(prev_val, case_value), prev_cnt + 1)
231 | else:
232 | time_val[tup] = (case_value, 1)
233 | else:
234 | time_dict[time_key] = {tup: (case_value, 1)}
235 | arcpy.SetProgressor("default")
236 | arcpy.SetProgressorLabel("Creating data...")
237 | p_n = 0
238 | p_mu = 0.0
239 | p_m2 = 0.0
240 | data = []
241 | # Go back through the data and calc mean and stdev in one pass
242 | for tk, tv in time_dict.items():
243 | points = []
244 | for rc_tup, case_tup in tv.items():
245 | case_value, case_count = case_tup
246 | if case_count >= min_count:
247 | row, col = rc_tup
248 | p = case_value # plot the max value
249 | points.append({"r": row, "c": col, "p": p, "w": 1.0})
250 | p_n += 1
251 | delta = p - p_mu
252 | p_mu += delta / p_n
253 | delta2 = p - p_mu
254 | p_m2 += delta * delta2
255 | if points:
256 | date_text = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(tk * seconds))
257 | data.append({"datetime": date_text, "points": points})
258 | s2 = p_m2 / (p_n - 1) if p_n > 1 else 0.0
259 | sd = sqrt(s2)
260 | p_min = p_mu - sd
261 | p_max = p_mu + sd
262 | p_del = p_max - p_min if p_max > p_min else 1.0
263 | arcpy.SetProgressorLabel("Normalizing data...")
264 | # Go back again and normalize between mean +/- 1 stddev where min weight is 0.2
265 | for elem in data:
266 | for point in elem["points"]:
267 | p = point["p"]
268 | if p < p_min:
269 | w = 0.2
270 | elif p > p_max:
271 | w = 1.0
272 | else:
273 | w = 0.2 + 0.8 * (p - p_min) / p_del
274 | point["w"] = w
275 | return {"data": data, "min": p_min, "max": p_max, "mean": p_mu, "stddev": sd}
276 |
277 | def execute(self, parameters, messages):
278 | input_fc = parameters[1].value
279 | num_cells = parameters[2].value
280 | date_field = parameters[3].value
281 | case_field = parameters[4].value
282 | min_count = parameters[5].value
283 | interval = parameters[6].value
284 | output_file = parameters[7].value
285 | bbox = parameters[8].value
286 |
287 | sr_84 = arcpy.SpatialReference(4326)
288 | extent_84 = bbox.projectAs(sr_84.exportToString())
289 |
290 | # if hasattr(arcpy, "mapping"):
291 | # map_doc = arcpy.mapping.MapDocument('CURRENT')
292 | # df = arcpy.mapping.ListDataFrames(map_doc)[0]
293 | # extent_84 = df.extent.projectAs(sr_84)
294 | # else:
295 | # gis_project = arcpy.mp.ArcGISProject('CURRENT')
296 | # map_frame = gis_project.listMaps()[0]
297 | # extent_84 = map_frame.defaultCamera.getExtent().projectAs(sr_84)
298 |
299 | mesh = self.create_mesh(extent_84, num_cells + 1)
300 |
301 | data = self.create_data(extent_84, sr_84, input_fc, num_cells, min_count, interval, date_field, case_field)
302 |
303 | arcpy.SetProgressorLabel("Saving JS...")
304 | obj = {"mesh": mesh, "data": data}
305 | with open(output_file, "w") as text_file:
306 | text_file.write("define(")
307 | json.dump(obj, text_file)
308 | text_file.write(");")
309 |
310 | out_nm = "Mesh"
311 | # ws = "in_memory"
312 | ws = arcpy.env.scratchGDB
313 | fc = ws + "/" + out_nm
314 |
315 | if arcpy.Exists(fc):
316 | arcpy.management.Delete(fc)
317 |
318 | arcpy.SetProgressorLabel("Creating Mesh FeatureClass...")
319 | arcpy.management.CreateFeatureclass(ws, out_nm, 'POLYGON',
320 | spatial_reference=sr_84,
321 | has_m='DISABLED',
322 | has_z='DISABLED')
323 | with arcpy.da.InsertCursor(fc, ["SHAPE@"]) as cursor:
324 | v = mesh["vertices"]
325 | i = mesh["indices"]
326 | idx_len = len(i)
327 | idx = 0
328 | while idx < idx_len:
329 | ii = i[idx] * 3
330 | jj = i[idx + 1] * 3
331 | kk = i[idx + 2] * 3
332 | ix = v[ii]
333 | iy = v[ii + 1]
334 | jx = v[jj]
335 | jy = v[jj + 1]
336 | kx = v[kk]
337 | ky = v[kk + 1]
338 | shape = [(ix, iy), (jx, jy), (kx, ky)]
339 | cursor.insertRow([shape])
340 | idx += 3
341 |
342 | parameters[0].value = fc
343 |
--------------------------------------------------------------------------------