forked from JuliaEarth/geospatial-data-science-with-julia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
05-transforms.qmd
677 lines (488 loc) · 20.1 KB
/
05-transforms.qmd
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
# What are transforms?
```{julia}
#| echo: false
#| output: false
import Pkg
Pkg.activate(".")
using GeoStats
import CairoMakie as Mke
```
## Motivation
In **Part I** of the book, we learned that our `GeoTable` representation
of geospatial data provides the data access pattern of the `DataFrame`,
a feature that is very convenient for data science. To recap, let's
consider the following geotable with four random variables:
```{julia}
N = 10000
a = [2randn(N÷2) .+ 6; randn(N÷2)]
b = [3randn(N÷2); 2randn(N÷2)]
c = randn(N)
d = c .+ 0.6randn(N)
table = (; a, b, c, d)
gt = georef(table, CartesianGrid(100, 100))
```
We can easily retrieve the "a" column of the geotable as a vector,
and plot its histogram:
```{julia}
Mke.hist(gt.a, color = "gray80")
```
We can compute the cross-correlation between columns "a" and "b":
```{julia}
cor(gt.a, gt.b)
```
And inspect bivariate distributions of the `values` of the geotable
with [PairPlots.jl](https://github.com/sefffal/PairPlots.jl) by @Thompson2023:
```{julia}
using PairPlots
pairplot(values(gt))
```
This pattern is useful to answer geoscientific questions via marginal
analysis (i.e. entire columns treated
as measurements of a single random variable). However, the answers to many
questions in geosciences depend on **where** the measurements were made.
Attempting to answer geoscientific questions with basic access to rows and
columns can be very frustrating. In particular, this approach is prone to
unintentional removal of geospatial information:
```{julia}
gt.a
```
::: {.callout-note}
Any script that is written in terms of direct column access has the potential
to discard the special `geometry` column, and become unreadable very quickly
with the use of auxiliary indices for rows.
:::
We propose a new approach to geospatial data science with the concept of
**transforms**, which we introduce in three classes with practical examples:
1. Feature transforms
2. Geometric transforms
3. Geospatial transforms
## Feature transforms
A feature transform is a function that takes the `values` of the geotable
and produces a new set of values over the same geospatial `domain`. The
framework provides over 30 such transforms, ranging from basic selection of
columns, to data cleaning, to advanced multivariate statistical transforms.
### Basic
Let's start with two basic and important transforms, `Select` and `Reject`.
The `Select` transform can be used to select columns of interest from a
geotable:
```{julia}
gt |> Select("a", "b") # select columns "a" and "b"
```
In the example above, we selected the columns "a" and "b" explicitly, but
`Select` has various methods for more flexible column selection:
```{julia}
gt |> Select(1:3) # select columns 1 to 3
```
```{julia}
gt |> Select(r"[bcd]") # columns matching regular expression
```
A convenient method is also provided to select and rename columns:
```{julia}
gt |> Select("a" => "A", "b" => "B")
```
The `Reject` transform can be used to reject columns from a geotable
that are not relevant for a given analysis. It supports the same column
specification of `Select`:
```{julia}
gt |> Reject("b") # reject column "b"
```
::: {.callout-note}
Unlike direct column access, the `Select` and `Reject` transforms
preserve geospatial information.
:::
::: {.callout-note}
## Tip for all users
The `Select` transform can be used in conjunction with the `viewer`
to quickly visualize a specific variable:
```{julia}
gt |> Select("a") |> viewer
```
:::
The `Rename` transform can be used to rename specific columns of a geotable.
It preserves all other columns that are not part of the column specification:
```{julia}
gt |> Rename("a" => "A", "b" => "B")
```
The `Identity` transform can be used as a placeholder to forward the geotable
without modifications to the next transform:
```{julia}
gt |> Identity()
```
The `RowTable` and `ColTable` transforms change the underlying table representation
of the `values` of the geotable as discussed in the first chapter of the book:
```{julia}
rt = gt |> RowTable()
```
```{julia}
rt |> values |> typeof
```
The `Functional` transform can be used to apply a function to columns of a geotable in place:
```{julia}
gt |> Functional(cos) |> values |> pairplot
```
```{julia}
gt |> Functional("a" => cos, "b" => sin) |> values |> pairplot
```
The `Map` transform can be used to create new columns from existing columns in the geotable.
It takes a column specification, calls a function on the selected columns row-by-row, and returns
the result as a new column:
```{julia}
gt |> Map("a" => sin, "b" => cos => "cos(b)")
```
```{julia}
gt |> Map([2, 3] => ((b, c) -> 2b + c) => "f(b, c)")
```
The name of the resulting column can be provided or omitted. If the name is omitted like in the
example above with the column "a", it is created by concatenation of column and function names.
::: {.callout-note}
The `Map` transform mimics the behavior of the `transform` function in DataFrames.jl, except
that it always broadcasts the functions to the rows of the selected columns and always produces
a single column for each function.
:::
To filter rows in the geotable based on a given predicate (i.e., a function that returns
`true` or `false`), we can use the `Filter` transform:
```{julia}
gt |> Filter(row -> row.a < 0 && row.b > 0)
```
To sort rows based on specific columns we can use the `Sort` transform:
```{julia}
gt |> Sort("a", "b")
```
This transform accepts all options of the `sortperm` function in Julia, including the
option to sort in reverse order:
```{julia}
gt |> Sort("a", "b", rev=true)
```
### Cleaning
Some feature transforms are used to clean the data before geostatistical analysis.
For example, the `StdNames` transform can be used to standardize variable names
that are not very readable due to file format limitations. To illustrate this
transform, let's create a geotable with unreadable variable names:
```{julia}
ut = gt |> Select("a" => "aBc De-F", "b" => "b_2 (1)")
```
We can standardize the names with:
```{julia}
ut |> StdNames()
```
By default the transform, uses the `:uppersnake` naming convention. Other conventions
can be specified depending on personal preference:
```{julia}
ut |> StdNames(:uppercamel)
```
```{julia}
ut |> StdNames(:upperflat)
```
The `Replace` transform can be used to replace specific values in the geotable by new
values that are meaningful to the analysis. For example, we can replace the values
`-999` and `NaN` that are used to represent `missing` values in some file formats:
```{julia}
rt = georef((a=[1,-999,3], b=[NaN,5,6]))
```
```{julia}
rt |> Replace(-999 => missing, NaN => missing)
```
or replace all negative values using a predicate function:
```{julia}
rt |> Replace(<(0) => missing)
```
::: {.callout-note}
In Julia, the expression `<(0)` is equivalent to the predicate function `x -> x < 0`.
:::
Although `Replace` could be used to replace `missing` values by new values, there is
a specific transform for this purpose named `Coalesce`:
```{julia}
ct = georef((a=[1,missing,3], b=[4,5,6])) |> Coalesce(value=2)
```
::: {.callout-note}
Unlike `Replace`, the `Coalesce` transform also changes the column type to make sure that
no `missing` values can be stored in the future:
```{julia}
typeof(ct.a)
```
:::
In many applications, it is enough to simply drop all rows for which the selected column
values are `missing`. This is the purpose of the `DropMissing` transform:
```{julia}
georef((a=[1,missing,3], b=[4,5,6])) |> DropMissing()
```
The `DropNaN` is an alternative to drop all rows for which the selected column values
are `NaN`.
### Statistical
The framework provides various feature transforms for statistical analysis. We will
cover some of these transforms in more detail in **Part V** of the book with real data.
In the following examples we illustrate the most basic statistical transforms with
synthetic data.
The `Sample` transform can be used to sample rows of the geotable at random, with
or without replacement depending on the `replace` option. Other options are available
such as `rng` to set the random number generator and `ordered` to preserve the order
of rows in the original geotable:
```{julia}
gt |> Sample(1000, replace=false) |> viewer
```
::: {.callout-note}
Similar to `Filter` and `Sort`, the `Sample` transform is lazy.
It simply stores the indices of sampled rows for future construction
of the new geotable.
:::
The `Center` and `Scale` transforms can be used to standardize the range of values
in a geotable. Aliases are provided for specific types of `Scale` such as `MinMax`
and `Interquartile`. We can use the `describe` function to visualize basic statistics
before and after the transforms:
```{julia}
gt |> describe
```
```{julia}
gt |> Center("a") |> describe
```
```{julia}
gt |> MinMax() |> describe
```
The `ZScore` transform is similar to the `Scale` transform, but it uses the mean
and the standard deviation to standardize the range:
```{julia}
gt |> ZScore() |> describe
```
Another important univariate transform is the `Quantile` transform, which can be
used to convert empirical distribution in a column of the geotable to any given
distribution from [Distributions.jl](https://github.com/JuliaStats/Distributions.jl)
by @Lin2023. Selected columns are converted to a `Normal` distribution by default,
but more than 60 distributions are available:
```{julia}
gt |> Quantile() |> values |> pairplot
```
In data science, scientific traits are used to link data types to adequate statistical
algorithms. The most popular scientific traits encountered in geoscientific applications
are the `Continuous` and the `Categorical` scientific traits. To convert (or coerce) the
scientific traits of columns in a geotable, we can use the `Coerce` transform:
```{julia}
using GeoStats.DataScienceTraits: Continuous
st = georef((a=[1,2,2,2,3,3], b=[1,2,3,4,5,6])) |> Coerce("b" => Continuous)
```
```{julia}
eltype(st.b)
```
::: {.callout-note}
All scientific traits are documented in the
[DataScienceTraits.jl](https://github.com/JuliaML/DataScienceTraits.jl)
module, and can be used to select variables:
```{julia}
st |> Only(Continuous)
```
:::
The `Levels` transform can be used to adjust the categories (or levels)
of `Categorical` columns in case the sampling process does not include
all possible values:
```{julia}
st = st |> Levels("a" => [1,2,3,4])
```
```{julia}
levels(st.a)
```
Another popular transform in statistical learning is the `OneHot` transform.
It converts a `Categorical` column into multiple columns of `true`/`false`
values, one column for each level:
```{julia}
st |> OneHot("a")
```
A similar transform for `Continuous` columns is the `Indicator` transform.
It converts the column into multiple columns based on threshold values on
the support of the data. By default, the threshold values are computed on
a quantile `scale`:
```{julia}
st |> Indicator("b", k=3, scale=:quantile)
```
More advanced statistical transforms such as `EigenAnalysis`, `PCA`,
`DRS`, `SDS`, `ProjectionPursuit` for multivariate data analysis and
`Remainder`, `Closure`, `LogRatio`, `ALR`, `CLR`, `ILR` for compositional
data analysis will be covered in future chapters.
## Geometric transforms
While feature transforms operate on the `values` of the geotable, geometric
transforms operate on the geospatial `domain`. The framework provides various
geometric transforms for 2D and 3D space.
### Coordinate
A coordinate transform is a geometric transform that modifies the coordinates
of all points in the domain without any advanced topological modification (i.e.,
connectivities are preserved). The most prominent examples of coordinate
transforms are `Translate`, `Rotate` and `Scale`.
Let's load an additional geotable to see these transforms in action:
```{julia}
using GeoIO
bt = GeoIO.load("data/beethoven.ply")
viz(bt.geometry)
```
The Beethoven domain has been saved in the `.ply` file in a position that is
not ideal for visualization. We can rotate this domain with any active rotation
specification from [Rotations.jl](https://github.com/JuliaGeometry/Rotations.jl)
by @Koolen2023 to improve the visualization. For example, we can specify that we
want to rotate all points in the mesh by analogy with a rotation between coordinates
`(0, 1, 0)` and coordinates `(0, 0, 1)`:
```{julia}
rt = bt |> Rotate((0, 1, 0), (0, 0, 1))
viz(rt.geometry)
```
Beethoven is now standing up, but still facing the wall. Let's rotate it once
again by analogy between coordinates `(1, 0, 0)` and `(-1, 1, 0)`:
```{julia}
rt = rt |> Rotate((1, 0, 0), (-1, 1, 0))
viz(rt.geometry)
```
Rotation specifications are also available in 2D space. As an example, we can
rotate the 2D grid of our synthetic geotable by the counter clockwise angle `π/4`:
```{julia}
gt |> Rotate(Angle2d(π/4)) |> viewer
```
In GIS, this new geotable would be called a rotated "raster". As another example,
let's translate the geotable to the origin of the coordinate system with the
`Translate` transform:
```{julia}
c = centroid(gt.geometry)
gt |> Translate(-to(c)...) |> viewer
```
and scale it with a positive factor for each dimension:
```{julia}
gt |> Scale(0.1, 0.2) |> viewer
```
The `StdCoords` transform combines `Translate` and `Scale` to standardize
the coordinates of the domain to the interval `[-0.5, 0.5]`:
```{julia}
gt |> StdCoords() |> viewer
```
In GIS, another very important coordinate transform is the `Proj` transform.
We will cover this transform in the next chapter because it depends on the concept
of [map projection](https://en.wikipedia.org/wiki/Map_projection), which deserves
more attention.
::: {.callout-note}
In our framework, the `Proj` transform is just another coordinate transform.
It is implemented with the same code optimizations, and can be used in conjunction
with many other transforms that are not available elsewhere.
:::
### Advanced
Advanced geometric transforms are provided that change the topology of the `domain`
besides the coordinates of points. Some of these transforms can be useful to repair
problematic geometries acquired from sensors in the real world.
The `Repair` transform is parameterized by an integer `K` that identifies the repair
to be performed. For example, `Repair{0}()` is a transform that removes duplicated
vertices and faces in a domain represented by a mesh. The `Repair{9}()` on the other
hand fixes the orientation of rings in polygonal areas so that the external boundary
is oriented counter clockwise and the inner boundaries are oriented clockwise. The
list of available repairs will continue to grow with the implementation of new
geometric algorithms in the framework.
To understand why geometric transforms are more general than coordinate transforms,
let's consider the following polygonal area with holes:
```{julia}
outer = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]
hole1 = [(0.2, 0.2), (0.2, 0.4), (0.4, 0.4), (0.4, 0.2)]
hole2 = [(0.6, 0.2), (0.6, 0.4), (0.8, 0.4), (0.8, 0.2)]
poly = PolyArea([outer, hole1, hole2])
viz(poly)
```
We can connect the holes with the external boundary (or ring) using the `Bridge` transform:
```{julia}
poly |> Bridge(0.01) |> viz
```
By looking at the visualization, we observe that the number of vertices changed to accommodate
the so called "bridges" between the rings. The topology also changed as there are no holes in
the resulting geometry.
As a final example of advanced geometric transform, we illustrate the `TaubinSmoothing` transform,
which gradually removes sharp boundaries of a manifold mesh:
```{julia}
st = bt |> TaubinSmoothing(30)
fig = Mke.Figure()
viz(fig[1,1], bt.geometry)
viz(fig[1,2], st.geometry)
fig
```
For more advanced geometric transforms, please consult the official documentation.
## Geospatial transforms
Geospatial transforms are those transforms that operate on both the `values` **and** the `domain`
of the geotable. They are common in geostatistical workflows that need to remove geospatial "trends"
or workflows that need to extract geometries from domains.
As an example, let's consider the following geotable with a variable `z` that made of a trend component
`μ` and a noise component `ϵ`:
```{julia}
# quadratic + noise
r = range(-1, stop=1, length=100)
μ = [x^2 + y^2 for x in r, y in r]
ϵ = 0.1rand(100, 100)
t = georef((z=μ+ϵ,))
viewer(t)
```
We can use the `Detrend` transform to remove a trend of polynomial degree `2`:
```{julia}
t |> Detrend(degree=2) |> viewer
```
The remaining component can then be modeled with geostatistical models of geospatial correlation,
which will be covered in **Part IV** of the book.
Models of geospatial correlation such as variograms [@Hoffimann2019] require unique coordinates
in the geotable and that is the purpose of the `UniqueCoords` transform. It removes duplicate
points in the geotable and aggregates the `values` with custom aggregation functions.
Let's consider the following geotable stored in a `.png` file to illustrate another geospatial
transform:
```{julia}
letters = GeoIO.load("data/letters.png")
```
The `Potrace` transform can be used to extract complex geometries from a geotable over a 2D `Grid`.
It transforms the `Grid` domain into a `GeometrySet` based on any column that contains a discrete
set of marker values. In this example, we use the `color` as the column with markers:
```{julia}
Ab = letters |> Potrace("color", ϵ=0.8)
```
The option `ϵ` controls the deviation tolerance used to simplify the boundaries of the geometries.
The higher is the tolerance, the less is the number of segments in the boundary:
```{julia}
viz(Ab.geometry[2], color = "black")
```
In the reverse direction, we have the `Rasterize` transform, which takes a geotable over a `GeometrySet`
and assigns the geometries to a `Grid`. In this transform, we can either provide an external grid for the
the assignments, or request a grid size to discretize the `boundingbox` of all geometries:
```{julia}
A = [1, 2, 3, 4, 5]
B = [1.1, 2.2, 3.3, 4.4, 5.5]
p1 = Triangle((2, 0), (6, 2), (2, 2))
p2 = Triangle((0, 6), (3, 8), (0, 10))
p3 = Quadrangle((3, 6), (9, 6), (9, 9), (6, 9))
p4 = Quadrangle((7, 0), (10, 0), (10, 4), (7, 4))
p5 = Pentagon((1, 3), (5, 3), (6, 6), (3, 8), (0, 6))
gt = georef((; A, B), [p1, p2, p3, p4, p5])
```
```{julia}
gt |> viewer
```
```{julia}
nt = gt |> Rasterize(20, 20)
```
```{julia}
nt |> viewer
```
The values of the variables are aggregated at geometric intersections using a default aggregation function,
which can be overwritten with an option. Once the geotable is defined over a `Grid`, it is possible to
refine or coarsen the grid with the `Downscale` and `Upscale` transforms.
The `Transfer` of values to a new geospatial domain is another very useful geospatial transform. The
`Aggregate` transform is related, but aggregates the values with given aggregation functions.
## Remarks
In this chapter we learned the important concept of **transforms**,
and saw examples of the concept in action with synthetic data. In
order to leverage the large number of transforms implemented in the
framework, all we need to do is load our geospatial data as a geotable
using `georef` or GeoIO.jl.
Some additional remarks:
- One of the major advantages of transforms compared to traditional row/column
access in data science is that they **preserve geospatial information**.
There is no need to keep track of indices in arrays to repeatedly
reattach values to geometries.
- Transforms can be organized into three classes---feature, geometric and
geospatial---depending on how they operate with the `values` and the
`domain` of the geotable:
- **Feature** transforms operate on the `values`. They include column selection,
data cleaning, statistical analysis and any transform designed for traditional
Tables.jl.
- **Geometric** transforms operate on the `domain`. They include coordinate
transforms that simply modify the coordinates of points as well as more
advanced transforms that can change the topology of the domain.
- **Geospatial** transforms operate on both the `values` and `domain`.
They include geostatistical transforms and transforms that use other
columns besides the `geometry` column to produce new columns and geometries.
In the next chapters, we will review map projections with the `Proj`
coordinate transform, and will introduce one of the greatest features of
the framework known as **transform pipelines**.