Project

General

Profile

« Previous | Next » 

Revision a09a09c0

Added by Jim Regetz over 12 years ago

  • ID a09a09c0b9afeb1e0aa655e4ebd758eb5cdcfdd5

removed obsolete/preliminary DEM 60N assessment scripts

View differences:

terrain/rscripts/CreateImageDiffPlotsOverlayMulti.r
1
##############################################################################################
2
#
3
# CreateImageDiffPlots
4
# 
5
# R script generates collection of nine plots that display the distributions of  populations of 
6
# three elevation pixel pairs in proximity to the border between ASTER and STRM data in mosaic 
7
# images# under development for the Environment and Organisms project.
8
# 
9
#
10
# Inputs: 
11
#   1) Comma Separated Value (CSV) table containing randomly-sampled elevation value pairs,
12
#      extracted from ASTER/CGIAR mosaic and CDEM images, created by the R script: makeImagePairTable.r
13
#      Note: At present, be sure that this file has been sorted by column 1 (ColumnID) in Excel
14
#      before using in this program.
15
#
16
#   2) sampling factor: integer (range=1 to number of recors in input table. Determines
17
#      the size of randomly-selected sampe of total table record 'triplets' (north, border,
18
#      and south) rows of each column sample) to be displayed in the plots: 
19
#           sampling factor = 1  : plot every table record
20
#                             10 : plot a random sample containing 1/10th of records
21
#                            100 : plot random sample containing 1/100th of records.
22
# 
23
# To run:
24
#
25
#  1) place this file and the input file "tableForMark4000_5_8_SortColID.csv" in folder
26
#  2) start R
27
#  3) > source("CreateImageDiffPlotsOverlay.r")
28
#  4) > CreateImageDiffPlots(sampling factor)
29
#     < press <cr> key to view plots sequentially
30
#  
31
# TODO: add symbol legend to each plot.
32
# Author: Rick Reeves, NCEAS
33
# May 14, 2011
34
##############################################################################################
35
CreateImageDiffPlots <- function(plotSampFact = 100)
36
{
37
# Check plotSampleFact range  
38

  
39
   if (plotSampFact < 1)
40
      plotSampFact = 1
41
      
42
   if (plotSampFact > 100)
43
      plotSampFact = 100
44
 
45
# Read input table that was sorted OFFLINE in Excel on the first column (ColumnID)
46

  
47
   pointTable <-read.csv("tableForMark4000_5_8_SortColID.csv")
48

  
49
# Table created by randomly sampling from two superimposed 
50
# image: 
51
#  1) DOM mosaic image comprised of ASTER and SRTM components.
52
#  2) 'Baseline' Canadian DEM (CDEM) image.
53
# 
54
# The input table contains three rows for each randomly-selected
55
# pixel pair from both images. Each row contains two pixel pairs,
56
# the first pair drawn from the image mosaic, the second pair
57
# drawn from the CDEM image: 
58
#   First pair: North pixel, South pixel (ASTER/SRTM mosaic)
59
#   Second pair: North pixel, South pixel (CDEM)
60
#
61
#  The first row of each 'triplet' contains pixel pairs North of border,
62
#  The second row contains pixel pairs spanning  border,
63
#  The third row contains pixel pairs South of border,
64
#
65
# This script generates a series of plots that display
66
# differences between:
67
#    1) The mosaic and CDEM images
68
#    2) Image pixels on and away from the ASTER / SRTM boundary.
69
# 
70
   northRowIndexes = seq(from=1, to=(nrow(pointTable) - 3),by=3)
71
   borderRowIndexes = seq(from=2, to=(nrow(pointTable) - 1),by=3)   
72
   southRowIndexes = seq(from=3, to=(nrow(pointTable)),by=3)
73
#
74
# calculate and append the difference between elevations
75
# and CDEM
76
# these lines create the inputs for differnce image plots for each of three
77
# pixel pair subsets: North of border (All Aster), border (combo Aster/Srtm),
78
#                     South of border (all Srtm)
79
# 
80
# First, add the 'difference columns' to the entire table
81
#
82
   pointTable <-cbind(pointTable,(pointTable$elevNorth - pointTable$elevSouth))
83
   pointTable <-cbind(pointTable,(pointTable$cdemNorth - pointTable$cdemSouth))
84
   pointTable <-cbind(pointTable,(pointTable$elevNorth - pointTable$cdemNorth))
85
   pointTable <-cbind(pointTable,(pointTable$elevSouth - pointTable$cdemSouth))
86
#   
87
   colnames(pointTable)[6] <- "diffMosaicNorthSouth"
88
   colnames(pointTable)[7] <- "diffCDEMNorthSouth"
89
   colnames(pointTable)[8] <- "diffNorthMosaicCDEM"
90
   colnames(pointTable)[9] <- "diffSouthMosaicCDEM"   
91

  
92
# Difference between Mosaic (ASTER or CGIAR or border) 
93
# and CDEM elevation as pertentage of the mosaic elevation
94

  
95
   pointTable <-cbind(pointTable,(pointTable$diffNorthMosaicCDEM/pointTable$elevNorth * 100)) 
96
   pointTable <-cbind(pointTable,(pointTable$diffSouthMosaicCDEM/pointTable$elevSouth * 100)) 
97
   
98
   colnames(pointTable)[10] <- "magDiffMosaicCDEMNorthPct"
99
   colnames(pointTable)[11] <- "magDiffMosaicCDEMSouthPct"   
100

  
101
# For the plots, subdivide the table into three segments: 
102
#     rows north of border
103
#     rows crossing border
104
#     rows south of border
105

  
106
   northRowTblAll = pointTable[northRowIndexes,]
107
   borderRowTblAll = pointTable[borderRowIndexes,]
108
   southRowTblAll = pointTable[southRowIndexes,]
109

  
110
   subset <- 1:nrow(northRowTblAll)
111
   
112
   randSub <- sample(subset,as.integer(length(subset) / plotSampFact)) 
113
   
114
   northRowTbl <- northRowTblAll[randSub,]
115
   borderRowTbl <- borderRowTblAll[randSub,]
116
   southRowTbl <- southRowTblAll[randSub,]   
117
   
118
message("hit key to create each plot...")
119
browser()
120

  
121
# Three plotting characters used
122

  
123
   plotCh1 <- 17 # 'north' (Aster) points
124
   plotCh2 <- 18 # 'border' (Aster+srtm) points 
125
   plotCh3 <- 20 # 'south' (srtm) points
126
   
127
# First plot pair: North/South Mosaic Image pixel elevation for North/South subsets 'distance East from Western edge'.
128

  
129
   xAxisLbl <- sprintf("M/SD: AST: %.2f / %.2f BRD: %.2f / %.2f STM: %.2f / %.2f",mean(northRowTbl$elevNorth,na.rm=TRUE),sd(northRowTbl$elevNorth,na.rm=TRUE),
130
                                                                            mean(borderRowTbl$elevNorth,na.rm=TRUE),sd(borderRowTbl$elevNorth,na.rm=TRUE),
131
                                                                            mean(southRowTbl$elevNorth,na.rm=TRUE),sd(southRowTbl$elevNorth,na.rm=TRUE))
132
   plot(northRowTbl$ColumnID,northRowTbl$elevNorth,main="North Mosaic Pixel Elev: ASTER (red) Border (green) SRTM (blue)",xlab=xAxisLbl,col="red",pch=plotCh1)
133
   points(borderRowTbl$ColumnID,borderRowTbl$elevNorth,col="darkgreen",pch=plotCh2)
134
   points(southRowTbl$ColumnID,southRowTbl$elevNorth,col="blue",pch=plotCh3)
135
browser()
136
dev.new()
137
   xAxisLbl <- sprintf("M/SD: AST: %.2f / %.2f BRD: %.2f / %.2f STM: %.2f / %.2f",mean(northRowTbl$elevSouth,na.rm=TRUE),sd(northRowTbl$elevSouth,na.rm=TRUE),
138
                                                                            mean(borderRowTbl$elevSouth,na.rm=TRUE),sd(borderRowTbl$elevSouth,na.rm=TRUE),
139
                                                                            mean(southRowTbl$elevSouth,na.rm=TRUE),sd(southRowTbl$elevSouth,na.rm=TRUE))
140
   plot(northRowTbl$ColumnID,northRowTbl$elevSouth,main="South Mosaic Pixel Elev: ASTER (red) Border (green) SRTM (blue)",xlab=xAxisLbl,col="red",pch=plotCh1)
141
   points(borderRowTbl$ColumnID,borderRowTbl$elevSouth,col="darkgreen",pch=plotCh2)
142
   points(southRowTbl$ColumnID,southRowTbl$elevSouth,col="blue",pch=plotCh3)
143
browser()
144
dev.new()
145
# Second plot pair: North/South CDEM pixel elevation for North/South subsets 'distance East from Western edge'.
146

  
147
   xAxisLbl <- sprintf("M/SD: AST: %.2f / %.2f BRD: %.2f / %.2f STM: %.2f / %.2f",mean(northRowTbl$cdemNorth,na.rm=TRUE),sd(northRowTbl$cdemNorth,na.rm=TRUE),
148
                                                                            mean(borderRowTbl$cdemNorth,na.rm=TRUE),sd(borderRowTbl$cdemNorth,na.rm=TRUE),
149
                                                                            mean(southRowTbl$cdemNorth,na.rm=TRUE),sd(southRowTbl$cdemNorth,na.rm=TRUE))
150
   plot(northRowTbl$ColumnID,northRowTbl$cdemNorth,main="North CDEM Pixel Elev ASTER (r) Border (g) SRTM (b)",xlab=xAxisLbl,col="red",pch=plotCh1)
151
   points(borderRowTbl$ColumnID,borderRowTbl$cdemNorth,col="darkgreen",pch=plotCh2)
152
   points(southRowTbl$ColumnID,southRowTbl$cdemNorth,col="blue",pch=plotCh3)
153
browser()   
154
dev.new()
155
   xAxisLbl <- sprintf("M/SD: AST: %.2f / %.2f BRD: %.2f / %.2f STM: %.2f / %.2f",mean(northRowTbl$cdemSouth,na.rm=TRUE),sd(northRowTbl$cdemSouth,na.rm=TRUE),
156
                                                                            mean(borderRowTbl$cdemSouth,na.rm=TRUE),sd(borderRowTbl$cdemSouth,na.rm=TRUE),
157
                                                                            mean(southRowTbl$cdemSouth,na.rm=TRUE),sd(southRowTbl$cdemSouth,na.rm=TRUE))   
158
   plot(northRowTbl$ColumnID,northRowTbl$cdemSouth,main="South CDEM Pixel Elev ASTER (r) Border (g) SRTM (b)",xlab=xAxisLbl,col="red",pch=plotCh1)
159
   points(borderRowTbl$ColumnID,borderRowTbl$cdemSouth,col="darkgreen",pch=plotCh2)
160
   points(southRowTbl$ColumnID,southRowTbl$cdemSouth,col="blue",pch=plotCh3)
161
browser()
162
dev.new()
163
# Third plot pair: difference between North and South pixels in pair.
164

  
165
   xAxisLbl <- sprintf("M/SD: AST: %.2f / %.2f BRD: %.2f / %.2f STM: %.2f / %.2f",mean(northRowTbl$diffMosaicNorthSouth,na.rm=TRUE),sd(northRowTbl$diffMosaicNorthSouth,na.rm=TRUE),
166
                                                                            mean(borderRowTbl$diffMosaicNorthSouth,na.rm=TRUE),sd(borderRowTbl$diffMosaicNorthSouth,na.rm=TRUE),
167
                                                                            mean(southRowTbl$diffMosaicNorthSouth,na.rm=TRUE),sd(southRowTbl$diffMosaicNorthSouth,na.rm=TRUE))
168
   plot(northRowTbl$ColumnID,northRowTbl$diffMosaicNorthSouth,main="Mosaic N/S Pixel Diff: ASTER (r) Border (g) SRTM (b)",xlab=xAxisLbl,col="red",pch=plotCh1)
169
   points(borderRowTbl$ColumnID,borderRowTbl$diffMosaicNorthSouth,col="darkgreen",pch=plotCh2)
170
   points(southRowTbl$ColumnID,southRowTbl$diffMosaicNorthSouth,col="blue",pch=plotCh3)   
171
browser()  
172
dev.new()
173
   xAxisLbl <- sprintf("M/SD: AST: %.2f / %.2f BRD: %.2f / %.2f STM: %.2f / %.2f",mean(northRowTbl$diffCDEMNorthSouth,na.rm=TRUE),sd(northRowTbl$diffCDEMNorthSouth,na.rm=TRUE),
174
                                                                            mean(borderRowTbl$diffCDEMNorthSouth,na.rm=TRUE),sd(borderRowTbl$diffCDEMNorthSouth,na.rm=TRUE),
175
                                                                            mean(southRowTbl$diffCDEMNorthSouth,na.rm=TRUE),sd(southRowTbl$diffCDEMNorthSouth,na.rm=TRUE))
176
   plot(northRowTbl$ColumnID,northRowTbl$diffCDEMNorthSouth,main="CDEM N/S Pixel Diff: ASTER (r) Border (g) SRTM (b)",xlab=xAxisLbl,col="red",pch=plotCh1)
177
   points(borderRowTbl$ColumnID,borderRowTbl$diffCDEMNorthSouth,col="darkgreen",pch=plotCh2)
178
   points(southRowTbl$ColumnID,southRowTbl$diffCDEMNorthSouth,col="blue",pch=plotCh3)
179
browser()
180
dev.new()
181

  
182
# Fourth plot pair: the Mosaic/CDEM difference for North and South pixels
183

  
184
   xAxisLbl <- sprintf("M/SD: AST: %.2f / %.2f BRD: %.2f / %.2f STM: %.2f / %.2f",mean(northRowTbl$diffNorthMosaicCDEM,na.rm=TRUE),sd(northRowTbl$diffNorthMosaicCDEM,na.rm=TRUE),
185
                                                                            mean(borderRowTbl$diffNorthMosaicCDEM,na.rm=TRUE),sd(borderRowTbl$diffNorthMosaicCDEM,na.rm=TRUE),
186
                                                                            mean(southRowTbl$diffNorthMosaicCDEM,na.rm=TRUE),sd(southRowTbl$diffNorthMosaicCDEM,na.rm=TRUE))
187
   plot(northRowTbl$ColumnID,northRowTbl$diffMosaicNorthSouth,main="Mosaic / CDEM Pixel Diff (North): ASTER (r) Border (g) SRTM (b)",xlab=xAxisLbl,col="red",pch=plotCh1)
188
   points(borderRowTbl$ColumnID,borderRowTbl$diffMosaicNorthSouth,col="darkgreen",pch=plotCh2)
189
   points(southRowTbl$ColumnID,southRowTbl$diffMosaicNorthSouth,col="blue",pch=plotCh3)   
190
browser()
191
dev.new()
192
   xAxisLbl <- sprintf("M/SD: AST: %.2f / %.2f BRD: %.2f / %.2f STM: %.2f / %.2f",mean(northRowTbl$diffSouthMosaicCDEM,na.rm=TRUE),sd(northRowTbl$diffSouthMosaicCDEM,na.rm=TRUE),
193
                                                                            mean(borderRowTbl$diffSouthMosaicCDEM,na.rm=TRUE),sd(borderRowTbl$diffSouthMosaicCDEM,na.rm=TRUE),
194
                                                                            mean(southRowTbl$diffSouthMosaicCDEM,na.rm=TRUE),sd(southRowTbl$diffSouthMosaicCDEM,na.rm=TRUE))
195
   plot(northRowTbl$ColumnID,northRowTbl$diffCDEMNorthSouth,main="Mosaic / CDEM Pixel Diff (South): ASTER (r) Border (g) SRTM (b)",xlab=xAxisLbl,col="red",pch=plotCh1)
196
   points(borderRowTbl$ColumnID,borderRowTbl$diffCDEMNorthSouth,col="darkgreen",pch=plotCh2)
197
   points(southRowTbl$ColumnID,southRowTbl$diffCDEMNorthSouth,col="blue",pch=plotCh3)
198
browser()
199
dev.new()
200
# Fifth plot pair: the Mosaic/CDEM difference divided by the (ASTER or SRTM) elevation
201

  
202
  xAxisLbl <- sprintf("M/SD: AST: %.2f / %.2f BRD: %.2f / %.2f STM: %.2f / %.2f",mean(northRowTbl$magDiffMosaicCDEMNorthPct,na.rm=TRUE),sd(northRowTbl$magDiffMosaicCDEMNorthPct,na.rm=TRUE),
203
                                                                            mean(borderRowTbl$magDiffMosaicCDEMNorthPct,na.rm=TRUE),sd(borderRowTbl$magDiffMosaicCDEMNorthPct,na.rm=TRUE),
204
                                                                            mean(southRowTbl$magDiffMosaicCDEMNorthPct,na.rm=TRUE),sd(southRowTbl$magDiffMosaicCDEMNorthPct,na.rm=TRUE))  
205
  plot(northRowTbl$ColumnID,northRowTbl$magDiffMosaicCDEMNorthPct,main="Pixel Elev Diff as % of Mosaic Elev (North) - ASTER (r) Border (g) SRTM (b)",xlab=xAxisLbl,col="red",pch=plotCh1)
206
  points(borderRowTbl$ColumnID,borderRowTbl$magDiffMosaicCDEMNorthPct,col="darkgreen",pch=plotCh2)  
207
  points(southRowTbl$ColumnID,southRowTbl$magDiffMosaicCDEMNorthPct,col="blue",pch=plotCh3)  
208
browser()
209
dev.new()
210
  xAxisLbl <- sprintf("M/SD: AST: %.2f / %.2f BRD: %.2f / %.2f STM: %.2f / %.2f",mean(northRowTbl$magDiffMosaicCDEMSouthPct,na.rm=TRUE),sd(northRowTbl$magDiffMosaicCDEMSouthPct,na.rm=TRUE),
211
                                                                            mean(borderRowTbl$magDiffMosaicCDEMSouthPct,na.rm=TRUE),sd(borderRowTbl$magDiffMosaicCDEMSouthPct,na.rm=TRUE),
212
                                                                             mean(southRowTbl$magDiffMosaicCDEMSouthPct,na.rm=TRUE),sd(southRowTbl$magDiffMosaicCDEMSouthPct,na.rm=TRUE))
213
  plot(northRowTbl$ColumnID,northRowTbl$magDiffMosaicCDEMSouthPct,main="Pixel Elev Diff as % of Mosaic Elev (South) - ASTER (r) Border (g) SRTM (b)",xlab=xAxisLbl,col="red",pch=plotCh1)
214
  points(borderRowTbl$ColumnID,borderRowTbl$magDiffMosaicCDEMSouthPct,col="darkgreen",pch=plotCh2)  
215
  points(southRowTbl$ColumnID,southRowTbl$magDiffMosaicCDEMSouthPct,col="blue",pch=plotCh3)  
216
browser()
217
dev.new()
218
# Final plot pair: Mosaic vs CDEM difference vs elevation (north or south)
219

  
220
xAxisLbl <- sprintf("M/SD: AST: %.2f / %.2f BRD: %.2f / %.2f STM: %.2f / %.2f",mean(northRowTbl$diffMosaicNorthSouth,na.rm=TRUE),sd(northRowTbl$diffMosaicNorthSouth,na.rm=TRUE),
221
                                                                          mean(borderRowTbl$diffMosaicNorthSouth,na.rm=TRUE),sd(borderRowTbl$diffMosaicNorthSouth,na.rm=TRUE),
222
                                                                          mean(southRowTbl$diffMosaicNorthSouth,na.rm=TRUE),sd(southRowTbl$diffMosaicNorthSouth,na.rm=TRUE))
223
plot(northRowTbl$elevNorth,northRowTbl$diffMosaicNorthSouth,main="Mosaic Elev N/S Diff ASTER (r) Border (g) SRTM (b)",xlab=xAxisLbl,col="red",pch=plotCh1)
224
points(borderRowTbl$elevNorth,borderRowTbl$diffMosaicNorthSouth,col="darkgreen",pch=plotCh2)
225
points(southRowTbl$elevNorth,southRowTbl$diffMosaicNorthSouth,col="blue",pch=plotCh3)
226
browser()
227
dev.new()
228
  xAxisLbl <- sprintf("M/SD: AST: %.2f / %.2f BRD: %.2f / %.2f STM: %.2f / %.2f",mean(northRowTbl$diffCDEMNorthSouth,na.rm=TRUE),sd(northRowTbl$diffCDEMNorthSouth,na.rm=TRUE),
229
                                                                            mean(borderRowTbl$diffCDEMNorthSouth,na.rm=TRUE),sd(borderRowTbl$diffCDEMNorthSouth,na.rm=TRUE),
230
                                                                            mean(southRowTbl$diffCDEMNorthSouth,na.rm=TRUE),sd(southRowTbl$diffCDEMNorthSouth,na.rm=TRUE))
231
  plot(northRowTbl$elevNorth,northRowTbl$diffCDEMNorthSouth,main="CDEM Elev N/S Diff ASTER (r) Border (g) SRTM (b)",xlab=xAxisLbl,col="red",pch=plotCh1)
232
  points(borderRowTbl$elevNorth,borderRowTbl$diffCDEMNorthSouth,col="darkgreen",pch=plotCh2)
233
  points(southRowTbl$elevNorth,southRowTbl$diffCDEMNorthSouth,col="blue",pch=plotCh3)
234
message("All plots created - hit key to delete them...")
235
browser()
236
graphics.off()
237
} 
terrain/rscripts/CreateImageDiffPlotsOverlayNewPlots.R
1
##############################################################################################
2
#
3
# CreateImageDiffPlots
4
# 
5
# R script generates collection of nine plots that display the distributions of  populations of 
6
# three elevation pixel pairs in proximity to the border between ASTER and STRM data in mosaic 
7
# images# under development for the Environment and Organisms project.
8
# 
9
#
10
# Inputs: 
11
#   1) Comma Separated Value (CSV) table containing randomly-sampled elevation value pairs,
12
#      extracted from ASTER/CGIAR mosaic and CDEM images, created by the R script: makeImagePairTable.r
13
#      Note: At present, be sure that this file has been sorted by column 1 (ColumnID) in Excel
14
#      before using in this program. 
15
#      NOTE: This filename is set in the body of the script.
16
#
17
#   2) sampling factor: integer (range=1 to number of recors in input table. Determines
18
#      the size of randomly-selected sampe of total table record 'triplets' (north, border,
19
#      and south) rows of each column sample) to be displayed in the plots: 
20
#           sampling factor = 1  : plot every table record
21
#                             10 : plot a random sample containing 1/10th of records
22
#                            100 : plot random sample containing 1/100th of records.
23
#   3) JpgPlotFileFlag: Set to TRUE to have *individual* plots written to JPG files.
24
#
25
# To run:
26
#
27
#  1) place this file and the input file "tableForMark4000_5_8_SortColID.csv" in folder
28
#  2) start R
29
#  3) > source("CreateImageDiffPlotsOverlayNewPlots.r")
30
#  4) > CreateImageDiffPlots(sampling factor, JpegFlag)
31
#     < press <cr> key to view plots sequentially
32
#  
33
# TODO: add symbol legend to each plot.
34
# Author: Rick Reeves, NCEAS
35
# May 14, 2011
36
# May 17, 2011: This version generates 'delta scatterplots' specified by Mark and Jim.
37
# May 18, 2011: If JpgPlotFlag set, write individual plot files to JPG files.
38
##############################################################################################
39
CreateImageDiffPlots <- function(plotSampFact = 1,JpgPlotFileFlag = TRUE)
40
{
41

  
42
# Check plotSampleFact range
43

  
44
   if (plotSampFact < 1)
45
      plotSampFact = 1
46
      
47
# Read input table that was sorted OFFLINE in Excel on the first column (ColumnID)
48

  
49
   pointTable <-read.csv("pixelPairs36000_5_8_TS.csv")
50
# Table created by randomly sampling from two superimposed 
51
# image: 
52
#  1) DOM mosaic image comprised of ASTER and SRTM components.
53
#  2) 'Baseline' Canadian DEM (CDEM) image.
54
# 
55
# The input table contains three rows for each randomly-selected
56
# pixel pair from both images. Each row contains two pixel pairs,
57
# the first pair drawn from the image mosaic, the second pair
58
# drawn from the CDEM image: 
59
#   First pair: North pixel, South pixel (ASTER/SRTM mosaic)
60
#   Second pair: North pixel, South pixel (CDEM)
61
#
62
#  The first row of each 'triplet' contains pixel pairs North of border,
63
#  The second row contains pixel pairs spanning  border,
64
#  The third row contains pixel pairs South of border,
65
#
66
# This script generates a series of plots that display
67
# differences between:
68
#    1) The mosaic and CDEM images
69
#    2) Image pixels on and away from the ASTER / SRTM boundary.
70
# 
71
   northRowIndexes = seq(from=1, to=(nrow(pointTable) - 3),by=3)
72
   borderRowIndexes = seq(from=2, to=(nrow(pointTable) - 1),by=3)   
73
   southRowIndexes = seq(from=3, to=(nrow(pointTable)),by=3)
74
#
75
# calculate and append the difference between elevations
76
# and CDEM
77
# these lines create the inputs for differnce image plots for each of three
78
# pixel pair subsets: North of border (All Aster), border (combo Aster/Srtm),
79
#                     South of border (all Srtm)
80
# 
81
# First, add the 'difference columns' to the entire table
82
#
83
   pointTable <-cbind(pointTable,(pointTable$elevNorth - pointTable$elevSouth))
84
   pointTable <-cbind(pointTable,(pointTable$cdemNorth - pointTable$cdemSouth))
85
   pointTable <-cbind(pointTable,(pointTable$elevNorth - pointTable$cdemNorth))
86
   pointTable <-cbind(pointTable,(pointTable$elevSouth - pointTable$cdemSouth))
87
#   
88
   colnames(pointTable)[6] <- "diffMosaicNorthSouth"
89
   colnames(pointTable)[7] <- "diffCDEMNorthSouth"
90
   colnames(pointTable)[8] <- "diffNorthMosaicCDEM"
91
   colnames(pointTable)[9] <- "diffSouthMosaicCDEM"   
92
   
93
# add a placeholder for the 'boundary' value, across each table
94

  
95
#  pointTable <-cbind(pointTable,(-1))
96
   
97
#  colnames(pointTable)[10] <- "deltaAcrossBorder"
98

  
99
# Difference between Mosaic (ASTER or CGIAR or border) 
100
# and CDEM elevation as pertentage of the mosaic elevation
101

  
102
   pointTable <-cbind(pointTable,(pointTable$diffNorthMosaicCDEM/pointTable$elevNorth * 100)) 
103
   pointTable <-cbind(pointTable,(pointTable$diffSouthMosaicCDEM/pointTable$elevSouth * 100)) 
104
   
105
   colnames(pointTable)[10] <- "magDiffMosaicCDEMNorthPct"
106
   colnames(pointTable)[11] <- "magDiffMosaicCDEMSouthPct"   
107

  
108
# For the plots, subdivide the table into three segments: 
109
#     rows north of border
110
#     rows crossing border
111
#     rows south of border
112

  
113
   northRowTblAll = pointTable[northRowIndexes,]
114
   borderRowTblAll = pointTable[borderRowIndexes,]
115
   southRowTblAll = pointTable[southRowIndexes,]
116

  
117
   subset <- 1:nrow(northRowTblAll)
118
   
119
   randSub <- sample(subset,as.integer(length(subset) / plotSampFact)) 
120
   
121
   northRowTbl <- northRowTblAll[randSub,]
122
   borderRowTbl <- borderRowTblAll[randSub,]
123
   southRowTbl <- southRowTblAll[randSub,]   
124
   
125
message("hit key to create each plot...")
126
browser()
127

  
128
# Three plotting characters used
129

  
130
   plotCh1 <- 17 # 'north' (aster) points
131
   plotCh2 <- 18 # 'border' (aster+srtm) points 
132
   plotCh3 <- 20 # 'south' (srtm) points
133
   
134
# NEW: Three plots: The difference between Mosaic and CDEM for pixels along
135
# each of three border edges: North (ASTER), Border, South (SRTM)
136
# for now, north, border, south have separate plots
137

  
138
# We need to tailor the plot 'triplet' X and Y axes to the dynamic ranges of all three data sets.
139

  
140
# Create values for the three 'delta across pixel boundaries' plots: 
141
#  1) Y-Axis: columnIDs 
142
#  2) Y-Axis: CDEM elevations
143
#  3) Y-Axis: 
144

  
145
   deltaBoundaryASTER <- northRowTbl$diffNorthMosaicCDEM - northRowTbl$diffSouthMosaicCDEM
146
   deltaBoundaryBorder <- borderRowTbl$diffNorthMosaicCDEM - borderRowTbl$diffSouthMosaicCDEM  
147
   deltaBoundarySRTM <- southRowTbl$diffNorthMosaicCDEM - southRowTbl$diffSouthMosaicCDEM   
148
   
149
   normDeltaBoundaryASTER <-  (deltaBoundaryASTER / northRowTbl$cdemNorth * 100)
150
   normDeltaBoundaryBorder <- (deltaBoundaryBorder / borderRowTbl$cdemNorth * 100)  
151
   normDeltaBoundarySRTM <-   (deltaBoundarySRTM / southRowTbl$cdemNorth * 100)
152
   
153
   par(mfrow=c(3,1)) # Create a set of three column multi-plots
154
   
155
   commonXAxis <- c(0,max(pointTable$ColumnID))   
156
   commonYAxis <- range(c(deltaBoundarySRTM,deltaBoundaryBorder,deltaBoundaryASTER),na.rm=TRUE)   
157

  
158
   xAxisLbl <- sprintf("M/SD: ASTER: %.2f / %.2f",mean(deltaBoundaryASTER,na.rm=TRUE),sd(deltaBoundaryASTER,na.rm=TRUE))
159
   plot(northRowTbl$ColumnID,deltaBoundaryASTER,xlim=commonXAxis, ylim=commonYAxis,main="Row Boundary Delta: ASTER",xlab=xAxisLbl,col="red",pch=plotCh1)
160
   xAxisLbl <- sprintf("M/SD: BORDER: %.2f / %.2f",mean(deltaBoundaryBorder,na.rm=TRUE),sd(deltaBoundaryBorder,na.rm=TRUE))
161
   plot(northRowTbl$ColumnID,deltaBoundaryBorder,xlim=commonXAxis, ylim=commonYAxis,main="Row Boundary Delta: Border",sub="E-W Col",xlab=xAxisLbl,col="darkgreen",pch=plotCh2)
162
   xAxisLbl <- sprintf("M/SD: SRTM: %.2f / %.2f",mean(deltaBoundarySRTM,na.rm=TRUE),sd(deltaBoundarySRTM,na.rm=TRUE))
163
   plot(northRowTbl$ColumnID,deltaBoundarySRTM,main="Boundary Delta: SRTM",xlim=commonXAxis, ylim=commonYAxis,xlab=xAxisLbl,col="blue",pch=plotCh3)
164
message("ColumnID-X-Axis is done")
165
browser()
166
#dev.new()
167
#   par(mfrow=c(3,1)) # Create a three column multi-plot pointTable$diffNorthMosaicCDEM/pointTable$elevNorth * 100))
168
   
169
   commonXAxis <- c(0,max(pointTable$cdemNorth))   
170
   commonYAxis <- range(c(deltaBoundarySRTM,deltaBoundaryBorder,deltaBoundaryASTER),na.rm=TRUE)   
171
   
172
   xAxisLbl <- sprintf("M/SD: ASTER: %.2f / %.2f",mean(deltaBoundaryASTER,na.rm=TRUE),sd(deltaBoundaryASTER,na.rm=TRUE))
173
   plot(northRowTbl$cdemNorth,deltaBoundaryASTER,xlim=commonXAxis, ylim=commonYAxis,main="Boundary Delta (CDEM Elev): ASTER",xlab=xAxisLbl,col="red",pch=plotCh1)
174
   xAxisLbl <- sprintf("M/SD: BORDER: %.2f / %.2f",mean(deltaBoundaryBorder,na.rm=TRUE),sd(deltaBoundaryBorder,na.rm=TRUE))
175
   plot(northRowTbl$cdemNorth,deltaBoundaryBorder,xlim=commonXAxis, ylim=commonYAxis,main="Boundary Delta (CDEM Elev): Border",sub="vs Elev",xlab=xAxisLbl,col="darkgreen",pch=plotCh2)
176
   xAxisLbl <- sprintf("M/SD: SRTM: %.2f / %.2f",mean(deltaBoundarySRTM,na.rm=TRUE),sd(deltaBoundarySRTM,na.rm=TRUE))
177
   plot(northRowTbl$cdemNorth,deltaBoundarySRTM,main="Boundary Delta (CDEM Elev): SRTM",xlim=commonXAxis, ylim=commonYAxis,xlab=xAxisLbl,col="blue",pch=plotCh3)
178
message("ColumnID-CDEM Elevation done")
179
browser()
180
   commonXAxis <- c(0,max(pointTable$cdemNorth))   
181
   commonYAxis <- range(c(normDeltaBoundarySRTM,normDeltaBoundaryBorder,normDeltaBoundaryASTER),na.rm=TRUE)   
182
   xAxisLbl <- sprintf("M/SD: ASTER: %.2f / %.2f",mean(normDeltaBoundaryASTER,na.rm=TRUE),sd(normDeltaBoundaryASTER,na.rm=TRUE))
183
   plot(northRowTbl$cdemNorth,normDeltaBoundaryASTER,xlim=commonXAxis, ylim=commonYAxis,main="Norm Bdry Delta (CDEM Elev): ASTER",xlab=xAxisLbl,col="red",pch=plotCh1)
184
   xAxisLbl <- sprintf("M/SD: BORDER: %.2f / %.2f",mean(normDeltaBoundaryBorder,na.rm=TRUE),sd(normDeltaBoundaryBorder,na.rm=TRUE))
185
   plot(northRowTbl$cdemNorth,normDeltaBoundaryBorder,xlim=commonXAxis, ylim=commonYAxis,main="Norm Bdry Delta (CDEM Elev): Border",sub="vs Elev",xlab=xAxisLbl,col="darkgreen",pch=plotCh2)
186
   xAxisLbl <- sprintf("M/SD: SRTM: %.2f / %.2f",mean(normDeltaBoundarySRTM,na.rm=TRUE),sd(normDeltaBoundarySRTM,na.rm=TRUE))
187
   plot(northRowTbl$cdemNorth,normDeltaBoundarySRTM,main="Norm Bdry Delta (CDEM Elev): SRTM",xlim=commonXAxis, ylim=commonYAxis,xlab=xAxisLbl,col="blue",pch=plotCh3)
188
message("NORMALIZED ColumnID-CDEM Elevation done")
189
browser()
190
   commonXAxis <- c(0,max(pointTable$ColumnID))   
191
   commonYAxis <- range(c(normDeltaBoundarySRTM,normDeltaBoundaryBorder,normDeltaBoundaryASTER),na.rm=TRUE)   
192
   
193
   xAxisLbl <- sprintf("M/SD: ASTER: %.2f / %.2f",mean(normDeltaBoundaryASTER,na.rm=TRUE),sd(normDeltaBoundaryASTER,na.rm=TRUE))
194
   plot(northRowTbl$ColumnID,normDeltaBoundaryASTER,xlim=commonXAxis, ylim=commonYAxis,main="Norm Bdry Delta: ASTER",xlab=xAxisLbl,col="red",pch=plotCh1)
195
   xAxisLbl <- sprintf("M/SD: BORDER: %.2f / %.2f",mean(normDeltaBoundaryBorder,na.rm=TRUE),sd(normDeltaBoundaryBorder,na.rm=TRUE))
196
   plot(northRowTbl$ColumnID,normDeltaBoundaryBorder,xlim=commonXAxis, ylim=commonYAxis,main="Norm Bdry Delta: Border",sub="E-W Col",xlab=xAxisLbl,col="darkgreen",pch=plotCh2)
197
   xAxisLbl <- sprintf("M/SD: SRTM: %.2f / %.2f",mean(normDeltaBoundarySRTM,na.rm=TRUE),sd(normDeltaBoundarySRTM,na.rm=TRUE))
198
   plot(northRowTbl$ColumnID,normDeltaBoundarySRTM,main="Norm Bdry Delta: SRTM",xlim=commonXAxis, ylim=commonYAxis,xlab=xAxisLbl,col="blue",pch=plotCh3)
199
message("NORMALIZED ColumnID-X-Axis is done...")
200

  
201
# if 'plot flag' is set, send the plots to a JPG file. 
202

  
203
if (JpgPlotFileFlag)
204
{
205
  message("creating JPG plot files...")
206
  browser()
207
jpeg(file="RowBoundaryDeltaColIDXAxisASTER.jpg")
208
   xAxisLbl <- sprintf("M/SD: ASTER: %.2f / %.2f",mean(deltaBoundaryASTER,na.rm=TRUE),sd(deltaBoundaryASTER,na.rm=TRUE))
209
   plot(northRowTbl$ColumnID,deltaBoundaryASTER,xlim=commonXAxis, ylim=commonYAxis,main="Row Boundary Delta: ASTER",xlab=xAxisLbl,col="red",pch=plotCh1)
210
dev.off()
211
jpeg(file="RowBoundaryDeltaColIDXAxisBORDER.jpg")   
212
   xAxisLbl <- sprintf("M/SD: BORDER: %.2f / %.2f",mean(deltaBoundaryBorder,na.rm=TRUE),sd(deltaBoundaryBorder,na.rm=TRUE))
213
   plot(northRowTbl$ColumnID,deltaBoundaryBorder,xlim=commonXAxis, ylim=commonYAxis,main="Row Boundary Delta: Border",sub="E-W Col",xlab=xAxisLbl,col="darkgreen",pch=plotCh2)
214
dev.off()
215
jpeg(file="RowBoundaryDeltaColIDXAxisSRTM.jpg")   
216
   xAxisLbl <- sprintf("M/SD: SRTM: %.2f / %.2f",mean(deltaBoundarySRTM,na.rm=TRUE),sd(deltaBoundarySRTM,na.rm=TRUE))
217
   plot(northRowTbl$ColumnID,deltaBoundarySRTM,main="Row Boundary Delta: SRTM",xlim=commonXAxis, ylim=commonYAxis,xlab=xAxisLbl,col="blue",pch=plotCh3)
218
message("ColumnID-X-Axis plots are  done")
219
#dev.new()
220
   commonXAxis <- c(0,max(pointTable$cdemNorth))   
221
   commonYAxis <- range(c(deltaBoundarySRTM,deltaBoundaryBorder,deltaBoundaryASTER),na.rm=TRUE)   
222
jpeg(file="RowBoundaryDeltaCDEMElevXAxisASTER.jpg")
223
   xAxisLbl <- sprintf("M/SD: ASTER: %.2f / %.2f",mean(deltaBoundaryASTER,na.rm=TRUE),sd(deltaBoundaryASTER,na.rm=TRUE))
224
   plot(northRowTbl$cdemNorth,deltaBoundaryASTER,xlim=commonXAxis, ylim=commonYAxis,main="Boundary Delta (CDEM Elev): ASTER",xlab=xAxisLbl,col="red",pch=plotCh1)
225
dev.off()
226
jpeg(file="RowBoundaryDeltaCDEMElevXAxisBORDER.jpg")
227
   xAxisLbl <- sprintf("M/SD: BORDER: %.2f / %.2f",mean(deltaBoundaryBorder,na.rm=TRUE),sd(deltaBoundaryBorder,na.rm=TRUE))
228
   plot(northRowTbl$cdemNorth,deltaBoundaryBorder,xlim=commonXAxis, ylim=commonYAxis,main="Boundary Delta (CDEM Elev): Border",sub="vs Elev",xlab=xAxisLbl,col="darkgreen",pch=plotCh2)
229
dev.off()
230
jpeg(file="RowBoundaryDeltaCDEMElevXAxisCDEM.jpg")
231
   xAxisLbl <- sprintf("M/SD: SRTM: %.2f / %.2f",mean(deltaBoundarySRTM,na.rm=TRUE),sd(deltaBoundarySRTM,na.rm=TRUE))
232
   plot(northRowTbl$cdemNorth,deltaBoundarySRTM,main="Boundary Delta (CDEM Elev): SRTM",xlim=commonXAxis, ylim=commonYAxis,xlab=xAxisLbl,col="blue",pch=plotCh3)
233
dev.off()
234
message("ColumnID-CDEM Elevation Plots are done")
235
#browser()
236
   commonXAxis <- c(0,max(pointTable$cdemNorth))   
237
   commonYAxis <- range(c(normDeltaBoundarySRTM,normDeltaBoundaryBorder,normDeltaBoundaryASTER),na.rm=TRUE)   
238
jpeg(file="NormRowBoundaryDeltaColIDXAxisASTER.jpg")
239
   xAxisLbl <- sprintf("M/SD: ASTER: %.2f / %.2f",mean(normDeltaBoundaryASTER,na.rm=TRUE),sd(normDeltaBoundaryASTER,na.rm=TRUE))
240
   plot(northRowTbl$cdemNorth,normDeltaBoundaryASTER,xlim=commonXAxis, ylim=commonYAxis,main="Norm Bdry Delta (CDEM Elev): ASTER",xlab=xAxisLbl,col="red",pch=plotCh1)
241
dev.off()
242
jpeg(file="NormRowBoundaryDeltaColIDXAxisBORDER.jpg")
243
   xAxisLbl <- sprintf("M/SD: BORDER: %.2f / %.2f",mean(normDeltaBoundaryBorder,na.rm=TRUE),sd(normDeltaBoundaryBorder,na.rm=TRUE))
244
   plot(northRowTbl$cdemNorth,normDeltaBoundaryBorder,xlim=commonXAxis, ylim=commonYAxis,main="Norm Bdry Delta (CDEM Elev): Border",sub="vs Elev",xlab=xAxisLbl,col="darkgreen",pch=plotCh2)
245
dev.off()
246
jpeg(file="NormRowBoundaryDeltaColIDXAxisSRTM.jpg")
247
   xAxisLbl <- sprintf("M/SD: SRTM: %.2f / %.2f",mean(normDeltaBoundarySRTM,na.rm=TRUE),sd(normDeltaBoundarySRTM,na.rm=TRUE))
248
   plot(northRowTbl$cdemNorth,normDeltaBoundarySRTM,main="Norm Bdry Delta (CDEM Elev): SRTM",xlim=commonXAxis, ylim=commonYAxis,xlab=xAxisLbl,col="blue",pch=plotCh3)
249
dev.off()
250
message("NORMALIZED ColumnID-CDEM Elevation Plots are done")
251
browser()
252
   commonXAxis <- c(0,max(pointTable$ColumnID))   
253
   commonYAxis <- range(c(normDeltaBoundarySRTM,normDeltaBoundaryBorder,normDeltaBoundaryASTER),na.rm=TRUE)   
254
jpeg(file="NormRowBoundaryDeltaCDEMElevXAxisASTER.jpg")   
255
   xAxisLbl <- sprintf("M/SD: ASTER: %.2f / %.2f",mean(normDeltaBoundaryASTER,na.rm=TRUE),sd(normDeltaBoundaryASTER,na.rm=TRUE))
256
   plot(northRowTbl$ColumnID,normDeltaBoundaryASTER,xlim=commonXAxis, ylim=commonYAxis,main="Norm Bdry Delta: ASTER",xlab=xAxisLbl,col="red",pch=plotCh1)
257
dev.off()
258
jpeg(file="NormRowBoundaryDeltaCDEMElevXAxisBORDER.jpg")
259
   xAxisLbl <- sprintf("M/SD: BORDER: %.2f / %.2f",mean(normDeltaBoundaryBorder,na.rm=TRUE),sd(normDeltaBoundaryBorder,na.rm=TRUE))
260
   plot(northRowTbl$ColumnID,normDeltaBoundaryBorder,xlim=commonXAxis, ylim=commonYAxis,main="Norm Bdry Delta: Border",sub="E-W Col",xlab=xAxisLbl,col="darkgreen",pch=plotCh2)
261
dev.off()
262
jpeg(file="NormRowBoundaryDeltaCDEMElevXAxisSRTM.jpg")
263
   xAxisLbl <- sprintf("M/SD: SRTM: %.2f / %.2f",mean(normDeltaBoundarySRTM,na.rm=TRUE),sd(normDeltaBoundarySRTM,na.rm=TRUE))
264
   plot(northRowTbl$ColumnID,normDeltaBoundarySRTM,main="Norm Bdry Delta: SRTM",xlim=commonXAxis, ylim=commonYAxis,xlab=xAxisLbl,col="blue",pch=plotCh3)
265
dev.off()   
266
message("NORMALIZED ColumnID-X-Axis Plot files have been created..")
267
}
268
message("...All plots created - hit key to delete them...")
269
browser()
270
graphics.off()
271
} 
terrain/rscripts/CreateImageDiffPlotsOverlayNewPlotsLowessLines.R
1
##############################################################################################
2
#
3
# CreateImageDiffPlots
4
# 
5
# R script generates collection of nine plots that display the distributions of  populations of 
6
# three elevation pixel pairs in proximity to the border between ASTER and STRM data in mosaic 
7
# images# under development for the Environment and Organisms project.
8
# 
9
#
10
# Inputs: 
11
#   1) Comma Separated Value (CSV) table containing randomly-sampled elevation value pairs,
12
#      extracted from ASTER/CGIAR mosaic and CDEM images, created by the R script: makeImagePairTable.r
13
#      Note: At present, be sure that this file has been sorted by column 1 (ColumnID) in Excel
14
#      before using in this program. 
15
#      NOTE: This filename is set in the body of the script.
16
#
17
#   2) sampling factor: integer (range=1 to number of recors in input table. Determines
18
#      the size of randomly-selected sampe of total table record 'triplets' (north, border,
19
#      and south) rows of each column sample) to be displayed in the plots: 
20
#           sampling factor = 1  : plot every table record
21
#                             10 : plot a random sample containing 1/10th of records
22
#                            100 : plot random sample containing 1/100th of records.
23
#   3) JpgPlotFileFlag: Set to TRUE to have *individual* plots written to JPG files.
24
#
25
# To run:
26
#
27
#  1) place this file and the input file "tableForMark4000_5_8_SortColID.csv" in folder
28
#  2) start R
29
#  3) > source("CreateImageDiffPlotsOverlay.r")
30
#  4) > CreateImageDiffPlots(sampling factor,JpegFlag)
31
#     < press <cr> key to view plots sequentially
32
#  
33
# TODO: add symbol legend to each plot.
34
# Author: Rick Reeves, NCEAS
35
# May 14, 2011
36
# May 17, 2011: This version generates 'delta scatterplots' specified by Mark and Jim.
37
# May 18, 2011: If JpgPlotFlag set, write individual plot files to JPG files.
38
# May 22, 2011: add Lowess lines to center of scatterplot distribution
39
##############################################################################################
40
CreateImageDiffPlotsNewLL <- function(plotSampFact = 1,JpgPlotFileFlag = TRUE)
41
{
42

  
43
# Check plotSampleFact rangels -l *.tif
44

  
45
   if (plotSampFact < 1)
46
      plotSampFact = 1
47
      
48
# Read input table that was sorted OFFLINE in Excel on the first column (ColumnID)
49

  
50
   pointTable <-read.csv("pixelPairs36000_5_8EvenSortCol1.csv")
51
#   pointTable <-read.csv("pixelPairs36000_Exa.csv")
52
# Table created by randomly sampling from two superimposed 
53
# image: 
54
#  1) DOM mosaic image comprised of ASTER and SRTM components.
55
#  2) 'Baseline' Canadian DEM (CDEM) image.
56
# 
57
# The input table contains three rows for each randomly-selected
58
# pixel pair from both images. Each row contains two pixel pairs,
59
# the first pair drawn from the image mosaic, the second pair
60
# drawn from the CDEM image: 
61
#   First pair: North pixel, South pixel (ASTER/SRTM mosaic)
62
#   Second pair: North pixel, South pixel (CDEM)
63
#
64
#  The first row of each 'triplet' contains pixel pairs North of border,
65
#  The second row contains pixel pairs spanning  border,
66
#  The third row contains pixel pairs South of border,
67
#
68
# This script generates a series of plots that display
69
# differences between:
70
#    1) The mosaic and CDEM images
71
#    2) Image pixels on and away from the ASTER / SRTM boundary.
72
# 
73
   northRowIndexes = seq(from=1, to=(nrow(pointTable) - 3),by=3)
74
   borderRowIndexes = seq(from=2, to=(nrow(pointTable) - 1),by=3)   
75
   southRowIndexes = seq(from=3, to=(nrow(pointTable)),by=3)
76
#
77
# calculate and append the difference between elevations
78
# and CDEM
79
# these lines create the inputs for differnce image plots for each of three
80
# pixel pair subsets: North of border (All Aster), border (combo Aster/Srtm),
81
#                     South of border (all Srtm)
82
# 
83
# First, add the 'difference columns' to the entire table
84
#
85
   pointTable <-cbind(pointTable,(pointTable$elevNorth - pointTable$elevSouth))
86
   pointTable <-cbind(pointTable,(pointTable$cdemNorth - pointTable$cdemSouth))
87
   pointTable <-cbind(pointTable,(pointTable$elevNorth - pointTable$cdemNorth))
88
   pointTable <-cbind(pointTable,(pointTable$elevSouth - pointTable$cdemSouth))
89
#   
90
   colnames(pointTable)[6] <- "diffMosaicNorthSouth"
91
   colnames(pointTable)[7] <- "diffCDEMNorthSouth"
92
   colnames(pointTable)[8] <- "diffNorthMosaicCDEM"
93
   colnames(pointTable)[9] <- "diffSouthMosaicCDEM"   
94
   
95
# add a placeholder for the 'boundary' value, across each table
96

  
97
#  pointTable <-cbind(pointTable,(-1))
98
   
99
#  colnames(pointTable)[10] <- "deltaAcrossBorder"
100

  
101
# Difference between Mosaic (ASTER or CGIAR or border) 
102
# and CDEM elevation as pertentage of the mosaic elevation
103

  
104
   pointTable <-cbind(pointTable,(pointTable$diffNorthMosaicCDEM/pointTable$elevNorth * 100)) 
105
   pointTable <-cbind(pointTable,(pointTable$diffSouthMosaicCDEM/pointTable$elevSouth * 100)) 
106
   
107
   colnames(pointTable)[10] <- "magDiffMosaicCDEMNorthPct"
108
   colnames(pointTable)[11] <- "magDiffMosaicCDEMSouthPct"   
109

  
110
# For the plots, subdivide the table into three segments: 
111
#     rows north of border
112
#     rows crossing border
113
#     rows south of border
114

  
115
   northRowTblAll = pointTable[northRowIndexes,]
116
   borderRowTblAll = pointTable[borderRowIndexes,]
117
   southRowTblAll = pointTable[southRowIndexes,]
118

  
119
   subset <- 1:nrow(northRowTblAll)
120
   
121
   randSub <- sample(subset,as.integer(length(subset) / plotSampFact)) 
122
   
123
   northRowTbl <- northRowTblAll[randSub,]
124
   borderRowTbl <- borderRowTblAll[randSub,]
125
   southRowTbl <- southRowTblAll[randSub,]   
126
   
127
message("hit key to create each plot...")
128
browser()
129

  
130
# Three plotting characters used
131

  
132
   plotCh1 <- 17 # 'north' (aster) points
133
   plotCh2 <- 18 # 'border' (aster+srtm) points 
134
   plotCh3 <- 20 # 'south' (srtm) points
135
   lowessLineColor <- "yellow"
136
# NEW: Three plots: The difference between Mosaic and CDEM for pixels along
137
# each of three border edges: North (ASTER), Border, South (SRTM)
138
# for now, north, border, south have separate plots
139

  
140
# We need to tailor the plot 'triplet' X and Y axes to the dynamic ranges of all three data sets.
141

  
142
# Create values for the three 'delta across pixel boundaries' plots: 
143
#  1) Y-Axis: columnIDs 
144
#  2) Y-Axis: CDEM elevations
145
#  3) Y-Axis: 
146

  
147
   deltaBoundaryASTER <- northRowTbl$diffNorthMosaicCDEM - northRowTbl$diffSouthMosaicCDEM
148
   deltaBoundaryBorder <- borderRowTbl$diffNorthMosaicCDEM - borderRowTbl$diffSouthMosaicCDEM  
149
   deltaBoundarySRTM <- southRowTbl$diffNorthMosaicCDEM - southRowTbl$diffSouthMosaicCDEM   
150
   
151
   normDeltaBoundaryASTER <-  (deltaBoundaryASTER / northRowTbl$cdemNorth * 100)
152
   normDeltaBoundaryBorder <- (deltaBoundaryBorder / borderRowTbl$cdemNorth * 100)  
153
   normDeltaBoundarySRTM <-   (deltaBoundarySRTM / southRowTbl$cdemNorth * 100)
154
   
155
   par(mfrow=c(1,3)) # Create a set of three column multi-plots
156
   
157
   commonXAxis <- c(0,max(pointTable$ColumnID))   
158
   commonYAxis <- range(c(deltaBoundarySRTM,deltaBoundaryBorder,deltaBoundaryASTER),na.rm=TRUE)   
159
   
160
   xAxisLbl <- sprintf("M/SD: ASTER: %.2f / %.2f",mean(deltaBoundaryASTER,na.rm=TRUE),sd(deltaBoundaryASTER,na.rm=TRUE))
161
   plot(northRowTbl$ColumnID,deltaBoundaryASTER,xlim=commonXAxis, ylim=commonYAxis,main="Delta: ASTER - CDEM",xlab=xAxisLbl,col="red",pch=plotCh1)
162
   vv <- cbind(northRowTbl$ColumnID,deltaBoundaryASTER)   
163
#   vx <- vv[-(which(is.na(vv[,"deltaBoundaryASTER"]))),]   
164
   vx <- vv[(which(!is.na(vv[,"deltaBoundaryASTER"]))),]   
165
   lines(stats::lowess(vx),col=lowessLineColor)
166
  
167
   xAxisLbl <- sprintf("M/SD: BORDER: %.2f / %.2f",mean(deltaBoundaryBorder,na.rm=TRUE),sd(deltaBoundaryBorder,na.rm=TRUE))
168
   plot(northRowTbl$ColumnID,deltaBoundaryBorder,xlim=commonXAxis, ylim=commonYAxis,main="Delta: Bdry Mix - CDEM",sub="X Axis: West-East Columns",xlab=xAxisLbl,col="darkgreen",pch=plotCh2)
169
   vv <- cbind(northRowTbl$ColumnID,deltaBoundaryBorder)   
170
   vx <- vv[(which(!is.na(vv[,"deltaBoundaryBorder"]))),]   
171
   lines(stats::lowess(vx),col=lowessLineColor)
172
   
173
   xAxisLbl <- sprintf("M/SD: SRTM: %.2f / %.2f",mean(deltaBoundarySRTM,na.rm=TRUE),sd(deltaBoundarySRTM,na.rm=TRUE))
174
   plot(northRowTbl$ColumnID,deltaBoundarySRTM,main="Delta: SRTM - CDEM",xlim=commonXAxis, ylim=commonYAxis,xlab=xAxisLbl,col="blue",pch=plotCh3)
175
   vv <- cbind(northRowTbl$ColumnID,deltaBoundarySRTM)   
176
   vx <- vv[(which(!is.na(vv[,"deltaBoundarySRTM"]))),]   
177
   lines(stats::lowess(vx),col=lowessLineColor)   
178
   
179
message("ColumnID-X-Axis is done")
180
browser()
181
#dev.new()
182
#   par(mfrow=c(3,1)) # Create a three column multi-plot pointTable$diffNorthMosaicCDEM/pointTable$elevNorth * 100))
183
   
184
   commonXAxis <- c(0,max(pointTable$cdemNorth,na.rm=TRUE))   
185
   commonYAxis <- range(c(deltaBoundarySRTM,deltaBoundaryBorder,deltaBoundaryASTER),na.rm=TRUE)   
186
 
187
#   northDelta.lo <- loess(deltaBoundaryASTER ~ deltaBoundaryASTER,northRowTbl)
188
   xAxisLbl <- sprintf("M/SD: ASTER: %.2f / %.2f",mean(deltaBoundaryASTER,na.rm=TRUE),sd(deltaBoundaryASTER,na.rm=TRUE))
189
   plot(northRowTbl$cdemNorth,deltaBoundaryASTER,xlim=commonXAxis, ylim=commonYAxis,main="Delta: ASTER - CDEM",xlab=xAxisLbl,col="red",pch=plotCh1)
190
   vv <- cbind(northRowTbl$cdemNorth,deltaBoundaryASTER)   
191
   vx <- vv[(which(!is.na(vv[,"deltaBoundaryASTER"]))),]   
192
   lines(stats::lowess(vx),col=lowessLineColor)
193
   
194
   xAxisLbl <- sprintf("M/SD: BORDER: %.2f / %.2f",mean(deltaBoundaryBorder,na.rm=TRUE),sd(deltaBoundaryBorder,na.rm=TRUE))
195
   plot(northRowTbl$cdemNorth,deltaBoundaryBorder,xlim=commonXAxis, ylim=commonYAxis,main=" Delta: Bdy Mix - CDEM",sub="X Axis: CDEM Elevation",xlab=xAxisLbl,col="darkgreen",pch=plotCh2)
196
   vv <- cbind(northRowTbl$cdemNorth,deltaBoundaryBorder)   
197
   vx <- vv[(which(!is.na(vv[,"deltaBoundaryBorder"]))),]   
198
   lines(stats::lowess(vx),col=lowessLineColor)
199
    
200
   xAxisLbl <- sprintf("M/SD: SRTM: %.2f / %.2f",mean(deltaBoundarySRTM,na.rm=TRUE),sd(deltaBoundarySRTM,na.rm=TRUE))
201
   plot(northRowTbl$cdemNorth,deltaBoundarySRTM,main="Delta: SRTM - CDEM",xlim=commonXAxis, ylim=commonYAxis,xlab=xAxisLbl,col="blue",pch=plotCh3)
202
   vv <- cbind(northRowTbl$cdemNorth,deltaBoundarySRTM)   
203
   vx <- vv[(which(!is.na(vv[,"deltaBoundarySRTM"]))),]   
204
   lines(stats::lowess(vx),col=lowessLineColor)
205
message("ColumnID-CDEM Elevation done")
206
browser()
207
   commonXAxis <- c(0,max(pointTable$cdemNorth,na.rm=TRUE))   
208
   commonYAxis <- range(c(normDeltaBoundarySRTM,normDeltaBoundaryBorder,normDeltaBoundaryASTER),na.rm=TRUE)   
209
   
210
   xAxisLbl <- sprintf("M/SD: ASTER: %.2f / %.2f",mean(normDeltaBoundaryASTER,na.rm=TRUE),sd(normDeltaBoundaryASTER,na.rm=TRUE))
211
   plot(northRowTbl$cdemNorth,normDeltaBoundaryASTER,xlim=commonXAxis, ylim=commonYAxis,main="Delta Norm Elev: ASTER",xlab=xAxisLbl,col="red",pch=plotCh1)
212
   vv <- cbind(northRowTbl$cdemNorth,normDeltaBoundaryASTER)   
213
   vx <- vv[(which(!is.na(vv[,"normDeltaBoundaryASTER"]))),]   
214
   lines(stats::lowess(vx),col=lowessLineColor)
215
   
216
   xAxisLbl <- sprintf("M/SD: BORDER: %.2f / %.2f",mean(normDeltaBoundaryBorder,na.rm=TRUE),sd(normDeltaBoundaryBorder,na.rm=TRUE))
217
   plot(northRowTbl$cdemNorth,normDeltaBoundaryBorder,xlim=commonXAxis, ylim=commonYAxis,main="Delta Norm Elev: Border",sub="X Axis: CDEM Elevation",xlab=xAxisLbl,col="darkgreen",pch=plotCh2)
218
   vv <- cbind(northRowTbl$cdemNorth,normDeltaBoundaryBorder)   
219
   vx <- vv[(which(!is.na(vv[,"normDeltaBoundaryBorder"]))),]   
220
   lines(stats::lowess(vx),col=lowessLineColor)
221
   
222
   xAxisLbl <- sprintf("M/SD: SRTM: %.2f / %.2f",mean(normDeltaBoundarySRTM,na.rm=TRUE),sd(normDeltaBoundarySRTM,na.rm=TRUE))
223
   plot(northRowTbl$cdemNorth,normDeltaBoundarySRTM,main="Delta Norm Elev: SRTM",xlim=commonXAxis, ylim=commonYAxis,xlab=xAxisLbl,col="blue",pch=plotCh3)
224
   vv <- cbind(northRowTbl$cdemNorth,normDeltaBoundarySRTM)   
225
   vx <- vv[(which(!is.na(vv[,"normDeltaBoundarySRTM"]))),]   
226
   lines(stats::lowess(vx),col=lowessLineColor)
227
message("NORMALIZED ColumnID-CDEM Elevation done")
228
browser()
229
   commonXAxis <- c(0,max(pointTable$cdemNorth,na.rm=TRUE))   
230
   commonYAxis <- range(c(northRowTbl$magDiffMosaicCDEMNorthPct,borderRowTbl$magDiffMosaicCDEMNorthPct,southRowTbl$magDiffMosaicCDEMNorthPct),na.rm=TRUE)   
231
   
232
   xAxisLbl <- sprintf("M/SD: ASTER: %.2f / %.2f",mean(northRowTbl$magDiffMosaicCDEMNorthPct,na.rm=TRUE),sd(northRowTbl$magDiffMosaicCDEMNorthPct,na.rm=TRUE))
233
   plot(northRowTbl$cdemNorth,northRowTbl$magDiffMosaicCDEMNorthPct,xlim=commonXAxis, ylim=commonYAxis,main="Delta Vs Elev Mag: ASTER",xlab=xAxisLbl,col="red",pch=plotCh1)
234
   vv <- cbind(northRowTbl$cdemNorth,northRowTbl$magDiffMosaicCDEMNorthPct)   
235
   vx <- vv[(which(!is.na(vv[,2]))),]   
236
   lines(stats::lowess(vx),col=lowessLineColor)
237
   
238
   xAxisLbl <- sprintf("M/SD: BORDER: %.2f / %.2f",mean(borderRowTbl$magDiffMosaicCDEMNorthPct,na.rm=TRUE),sd(borderRowTbl$magDiffMosaicCDEMNorthPct,na.rm=TRUE))
239
   plot(northRowTbl$cdemNorth,borderRowTbl$magDiffMosaicCDEMNorthPct,xlim=commonXAxis, ylim=commonYAxis,main="Delta Vs Elev Mag:: Border",sub="E-W Col",xlab=xAxisLbl,col="darkgreen",pch=plotCh2)
240
   vv <- cbind(northRowTbl$cdemNorth,deltaBoundarySRTM)   
241
   vx <- vv[(which(!is.na(vv[,2]))),]   
242
   lines(stats::lowess(vx),col=lowessLineColor)
243
   
244
   xAxisLbl <- sprintf("M/SD: SRTM: %.2f / %.2f",mean(southRowTbl$magDiffMosaicCDEMNorthPct,na.rm=TRUE),sd(southRowTbl$magDiffMosaicCDEMNorthPct,na.rm=TRUE))
245
   plot(northRowTbl$cdemNorth,southRowTbl$magDiffMosaicCDEMNorthPct,main="Delta Vs Elev Mag:: SRTM",xlim=commonXAxis, ylim=commonYAxis,xlab=xAxisLbl,col="blue",pch=plotCh3)
246
   vv <- cbind(northRowTbl$cdemNorth,southRowTbl$magDiffMosaicCDEMNorthPct)   
247
   vx <- vv[(which(!is.na(vv[,2]))),]   
248
   lines(stats::lowess(vx),col=lowessLineColor)
249
message("Delta as Fcn Elev Mag-X-Axis is done...")
250

  
251
# if 'plot flag' is set, send the plots to a JPG file. 
252

  
253
if (JpgPlotFileFlag)
254
{
255
  message("creating JPG plot files...")
256
  browser()
257
jpeg(file="RowBoundaryDeltaColIDXAxisASTER.jpg")
258
   xAxisLbl <- sprintf("M/SD: ASTER: %.2f / %.2f",mean(deltaBoundaryASTER,na.rm=TRUE),sd(deltaBoundaryASTER,na.rm=TRUE))
259
   plot(northRowTbl$ColumnID,deltaBoundaryASTER,xlim=commonXAxis, ylim=commonYAxis,main="Row Boundary Delta: ASTER",xlab=xAxisLbl,col="red",pch=plotCh1)
260
dev.off()
261
jpeg(file="RowBoundaryDeltaColIDXAxisBORDER.jpg")   
262
   xAxisLbl <- sprintf("M/SD: BORDER: %.2f / %.2f",mean(deltaBoundaryBorder,na.rm=TRUE),sd(deltaBoundaryBorder,na.rm=TRUE))
263
   plot(northRowTbl$ColumnID,deltaBoundaryBorder,xlim=commonXAxis, ylim=commonYAxis,main="Row Boundary Delta: Border",sub="E-W Col",xlab=xAxisLbl,col="darkgreen",pch=plotCh2)
264
dev.off()
265
jpeg(file="RowBoundaryDeltaColIDXAxisSRTM.jpg")   
266
   xAxisLbl <- sprintf("M/SD: SRTM: %.2f / %.2f",mean(deltaBoundarySRTM,na.rm=TRUE),sd(deltaBoundarySRTM,na.rm=TRUE))
267
   plot(northRowTbl$ColumnID,deltaBoundarySRTM,main="Row Boundary Delta: SRTM",xlim=commonXAxis, ylim=commonYAxis,xlab=xAxisLbl,col="blue",pch=plotCh3)
268
message("ColumnID-X-Axis plots are  done")
269
#dev.new()
270
   commonXAxis <- c(0,max(pointTable$cdemNorth))   
271
   commonYAxis <- range(c(deltaBoundarySRTM,deltaBoundaryBorder,deltaBoundaryASTER),na.rm=TRUE)   
272
jpeg(file="RowBoundaryDeltaCDEMElevXAxisASTER.jpg")
273
   xAxisLbl <- sprintf("M/SD: ASTER: %.2f / %.2f",mean(deltaBoundaryASTER,na.rm=TRUE),sd(deltaBoundaryASTER,na.rm=TRUE))
274
   plot(northRowTbl$cdemNorth,deltaBoundaryASTER,xlim=commonXAxis, ylim=commonYAxis,main="Boundary Delta (CDEM Elev): ASTER",xlab=xAxisLbl,col="red",pch=plotCh1)
275
dev.off()
276
jpeg(file="RowBoundaryDeltaCDEMElevXAxisBORDER.jpg")
277
   xAxisLbl <- sprintf("M/SD: BORDER: %.2f / %.2f",mean(deltaBoundaryBorder,na.rm=TRUE),sd(deltaBoundaryBorder,na.rm=TRUE))
278
   plot(northRowTbl$cdemNorth,deltaBoundaryBorder,xlim=commonXAxis, ylim=commonYAxis,main="Boundary Delta (CDEM Elev): Border",sub="vs Elev",xlab=xAxisLbl,col="darkgreen",pch=plotCh2)
279
dev.off()
280
jpeg(file="RowBoundaryDeltaCDEMElevXAxisCDEM.jpg")
281
   xAxisLbl <- sprintf("M/SD: SRTM: %.2f / %.2f",mean(deltaBoundarySRTM,na.rm=TRUE),sd(deltaBoundarySRTM,na.rm=TRUE))
282
   plot(northRowTbl$cdemNorth,deltaBoundarySRTM,main="Boundary Delta (CDEM Elev): SRTM",xlim=commonXAxis, ylim=commonYAxis,xlab=xAxisLbl,col="blue",pch=plotCh3)
283
dev.off()
284
message("ColumnID-CDEM Elevation Plots are done")
285
#browser()
286
   commonXAxis <- c(0,max(pointTable$cdemNorth))   
287
   commonYAxis <- range(c(normDeltaBoundarySRTM,normDeltaBoundaryBorder,normDeltaBoundaryASTER),na.rm=TRUE)   
288
jpeg(file="NormRowBoundaryDeltaColIDXAxisASTER.jpg")
289
   xAxisLbl <- sprintf("M/SD: ASTER: %.2f / %.2f",mean(normDeltaBoundaryASTER,na.rm=TRUE),sd(normDeltaBoundaryASTER,na.rm=TRUE))
290
   plot(northRowTbl$cdemNorth,normDeltaBoundaryASTER,xlim=commonXAxis, ylim=commonYAxis,main="Norm Bdry Delta (CDEM Elev): ASTER",xlab=xAxisLbl,col="red",pch=plotCh1)
291
dev.off()
292
jpeg(file="NormRowBoundaryDeltaColIDXAxisBORDER.jpg")
293
   xAxisLbl <- sprintf("M/SD: BORDER: %.2f / %.2f",mean(normDeltaBoundaryBorder,na.rm=TRUE),sd(normDeltaBoundaryBorder,na.rm=TRUE))
294
   plot(northRowTbl$cdemNorth,normDeltaBoundaryBorder,xlim=commonXAxis, ylim=commonYAxis,main="Norm Bdry Delta (CDEM Elev): Border",sub="vs Elev",xlab=xAxisLbl,col="darkgreen",pch=plotCh2)
295
dev.off()
296
jpeg(file="NormRowBoundaryDeltaColIDXAxisSRTM.jpg")
297
   xAxisLbl <- sprintf("M/SD: SRTM: %.2f / %.2f",mean(normDeltaBoundarySRTM,na.rm=TRUE),sd(normDeltaBoundarySRTM,na.rm=TRUE))
298
   plot(northRowTbl$cdemNorth,normDeltaBoundarySRTM,main="Norm Bdry Delta (CDEM Elev): SRTM",xlim=commonXAxis, ylim=commonYAxis,xlab=xAxisLbl,col="blue",pch=plotCh3)
299
dev.off()
300
message("NORMALIZED ColumnID-CDEM Elevation Plots are done")
301
browser()
302
   commonXAxis <- c(0,max(pointTable$ColumnID))   
303
   commonYAxis <- range(c(normDeltaBoundarySRTM,normDeltaBoundaryBorder,normDeltaBoundaryASTER),na.rm=TRUE)   
304
jpeg(file="NormRowBoundaryDeltaCDEMElevXAxisASTER.jpg")   
305
   xAxisLbl <- sprintf("M/SD: ASTER: %.2f / %.2f",mean(normDeltaBoundaryASTER,na.rm=TRUE),sd(normDeltaBoundaryASTER,na.rm=TRUE))
306
   plot(northRowTbl$ColumnID,normDeltaBoundaryASTER,xlim=commonXAxis, ylim=commonYAxis,main="Norm Bdry Delta: ASTER",xlab=xAxisLbl,col="red",pch=plotCh1)
307
dev.off()
308
jpeg(file="NormRowBoundaryDeltaCDEMElevXAxisBORDER.jpg")
309
   xAxisLbl <- sprintf("M/SD: BORDER: %.2f / %.2f",mean(normDeltaBoundaryBorder,na.rm=TRUE),sd(normDeltaBoundaryBorder,na.rm=TRUE))
310
   plot(northRowTbl$ColumnID,normDeltaBoundaryBorder,xlim=commonXAxis, ylim=commonYAxis,main="Norm Bdry Delta: Border",sub="E-W Col",xlab=xAxisLbl,col="darkgreen",pch=plotCh2)
311
dev.off()
312
jpeg(file="NormRowBoundaryDeltaCDEMElevXAxisSRTM.jpg")
313
   xAxisLbl <- sprintf("M/SD: SRTM: %.2f / %.2f",mean(normDeltaBoundarySRTM,na.rm=TRUE),sd(normDeltaBoundarySRTM,na.rm=TRUE))
314
   plot(northRowTbl$ColumnID,normDeltaBoundarySRTM,main="Norm Bdry Delta: SRTM",xlim=commonXAxis, ylim=commonYAxis,xlab=xAxisLbl,col="blue",pch=plotCh3)
315
dev.off()   
316
message("NORMALIZED ColumnID-X-Axis Plot files have been created..")
317
}
318
message("...All plots created - hit key to delete them...")
319
browser()
320
graphics.off()
321
} 
terrain/rscripts/DEMBdyFixExpDecay.r
1

  
2
# DEMBdyFixExpDecay - Implements Exponential Decay method to 'blend' DEM boundary edges
3
# 
4
# General form: decayFactor = e(-(d * DKc))
5
#                 where d = distance interval from origin (in this case, an image row index)
6
#                       DKc = empirically derived constant
7
# 
8
#
9
# Inputs: 
10
#   1) Blended Aster/SRTM DEM mosaic image.
11
#   2) 'SRTM-Only' subimage corresponding to the NORTHernmost part (adjacent to the 60 degree Lat 
12
#     boundary) of the SRTM component of the mosaic.
13
#   3) 'Aster-Only' subimage corresponding to the SOUTHernmost part (adjacent to the 60 degree Lat 
14
#     boundary) of the ASTER component of the mosaic.
15
#   4) Other parameters, as they are needed
16
#
17
# To run:
18

  
19
 
20
#  2) > source("DEMBdyFixExpDecay.r")
21
#  3) > DEMBdyFixExpDecay()
22
#
23
# Author: Rick Reeves, NCEAS
24
# June, 2011
25

  
26
##############################################################################################
27
DEMBdyFixExpDecay <- function()
28
{
29
  require(raster)
30
  require(rgdal)
31
  
32
# Read the mosaic image and component sub-images:
33
#   - Aster/SRTM mosaic image (with boundary edge to be fixed)
34
#   - 'Aster-only' subimage adjacent to Southern edge of 60 degree bounls -s dary,
35
#     sampled into a grid with same extent and spatial resolution as image mosaic
36
#   - 'Aster-only' subimage adjacent to Northern edge of 60 degree boundary,
37
#     sampled into a grid with same extent and spatial resolution as image mosaic
38
    
39
     inMosaic      <- raster("./AsterSrtmBoth3ArcSecSub.tif")
40
     
41
# Use these objects to get the extents of the subsets within the mosaic
42

  
43
     inAsterNorth  <- raster("./AsterBdyTestAbove60Sub.tif")     
44
     inAsterSouth  <- raster("./AsterBdyTestBelow60Sub.tif")     
45
     
46
# Better, read them into a rasterStack
47

  
48
     mosaicLayers <- stack("./AsterSRTMBothTestSub.tif",
49
                           "./AsterBdyTestFGAbove60Sub.tif",
50
                           "./AsterBdyTestFGBelow60Sub.tif") 
51
# 
52
# Create copy of input raster that we will use to create a 'fixed boundary' iamge
53
# Even SIMPLER, according to raster documentation
54
#
55
     outMosaic <- raster(mosaicLayers[[1]])
56
 
57
     sFixedRasterFile <- "TestOutputRasterBdyFix.tif"
58
     
59
# First, get the extent of the 'below 60' sub image in the (big) input raster
60

  
61
     northAsterEx <- extent(inAsterNorth)
62
     southAsterEx <- extent(inAsterSouth)
63
     
64
# Get the values from the mosaic for this extent
65

  
66
     southCellsOfInterest <- cellsFromExtent(mosaicLayers[[1]],southAsterEx)
67
     northCellsOfInterest <- cellsFromExtent(mosaicLayers[[1]],northAsterEx)
68

  
69
# Within the large input raster, we need the index of the first row of the 'Below 60 Aster' subimage.
70
# Our plan: to replace this portion of the input mosaic with a linear combination of the original
71
# input mosaic COPY (outMosaic) and the 'below 60' raster.
72

  
73
     firstNorthSubImgRow <- rowFromCell(mosaicLayers[[1]],northCellsOfInterest[1])   
74
     lastNorthSubImgRow <- rowFromCell(mosaicLayers[[1]],northCellsOfInterest[(length(northCellsOfInterest) - 1)])
75
     northNrowsToProcess <- nrow(inAsterNorth)
76
  
77
     firstSouthSubImgRow <- rowFromCell(mosaicLayers[[1]],southCellsOfInterest[1])   
78
     lastSouthSubImgRow <- rowFromCell(mosaicLayers[[1]],southCellsOfInterest[(length(southCellsOfInterest) - 1)])
79
     southNrowsToProcess <- nrow(inAsterSouth)
80

  
81
#  create the output raster by copying the input file with 'block copy'
82
     
83
message("Create output (fixed) mosaic")
84
#browser()
85
     bs <- blockSize(mosaicLayers[[1]]) 
86
     outMosaic <- writeStart(outMosaic,sFixedRasterFile, datatype="INT2S", format="GTiff",overwrite=TRUE)
87
     for (iCtr in 1 : bs$n)
88
     {
89
        mosaicVals <- getValues(mosaicLayers[[1]],row=bs$row[iCtr],nrows=bs$nrows[iCtr])
90
        writeValues(outMosaic,mosaicVals,bs$row[iCtr])
91
        message(sprintf(".....processed input mosaic block %d",iCtr))        
92
     }
93
     outMosaic <- writeStop(outMosaic)
94
message("Input mosaic copied to output raster: now, process boundary")
95
#browser()
96

  
97
# now, we SHOULD be able to modify outMosaic with new 'column values'.
98

  
99
# note: last north image and first south image rows are the same. 
100

  
101
     northBorderEdgeRow <- lastNorthSubImgRow
102
     southBorderEdgeRow <- firstSouthSubImgRow + 1
103

  
104
# The border 'edge' row is one row below the top of the south sub image
105

  
106
     southBrdrRowVals <- getValues(outMosaic,southBorderEdgeRow,1)
107
     northBrdrRowVals <- getValues(outMosaic,northBorderEdgeRow,1)
108
 
109
     brdrRowEdgeDelta <- southBrdrRowVals - northBrdrRowVals
110

  
111
# Process the mosaic 'column-by-column'
112
# For each column, extract the LAST 'numBlendRows cells adjacent to the bottomi
113
# (southernmost) edge of the ASTER component, next to the SRTM border. 
114
# Then, moving 'north' along the colum of values, add the current colunn's 'ledge' 
115
# offset, attenuated by the exponential decay factor for that row. 
116
# Thus, the SRTM/ASTER 'ledge' is attenuated, the impact is greatest at the boundary,
117
# least at the threshold, when the decay factor (empirically determined) goes to zero.
118
#
119
# Add Exponential Decay constant: empirically selected (try a few, ee if you like result
120
# Maybe plot it, see how many rows it takes for the 'effect' of SRTM goes to zero.
121
 
122
     dKc <- .045 # empirically determined constant, so that exp - 1 decay goes to zero in the desired number of image rows.
123
     numBlendRows <- 60
124
     begBlendRow <- (northBorderEdgeRow - numBlendRows) + 1
125
#     srows <- seq(southBorderEdgeRow,((southBorderEdgeRow + numBlendRows) - 1))
126
     srows <- seq((begBlendRow),northBorderEdgeRow)
127
# 
128
     for (curMosCol in 1 : ncol(mosaicLayers[[1]]))
129
     {
130
message(sprintf("transforming cur col: %d",curMosCol))
131
#browser()
132
#        deltaInc <- brdrRowEdgeDelta[curMosCol] / numBlendRows
133
        colVecCells <- cellFromRowCol(outMosaic,srows,curMosCol) 
134
        colVecValues <- getValuesBlock(outMosaic,row=begBlendRow,nrows=numBlendRows,col=curMosCol,ncols=1) 
135
        compareVec <- getValuesBlock(outMosaic,row=begBlendRow,nrows=numBlendRows+2,col=curMosCol,ncols=1) 
136
        curRowBoundaryOffset <- brdrRowEdgeDelta[curMosCol]
137

  
138
# note: we need to deal with NA values, which are possible. 
139

  
140
#        sumDeltaInc <- 0
141
#        for (iCtr in numBlendRows : 1) # this moves from 'south to north', decay increases with distance.
142
        for (iCtr in 1 : numBlendRows) # this moves from 'south to north', decay increases with distance.
143
#        for (iCtr in length(colVecValues) : 1) # this moves from 'south to north', decay increases with distance.
144
        {
145

  
146
# The idea: the closer to the border, the larger an increment we assign.
147
# in any case, increment the offset so that it is correct for any iupcoming non-NA column value
148

  
149
            if (!is.na(colVecValues[1]))
150
            {
151
#message(sprintf("cur col: %d Found a NON-NA vector",curMosCol))
152
#browser()
153
 
154
# exponential decay diminishes impact of the 'delta' edge adjustment with distance from the boundary.
155

  
156
               dK <- exp(-(iCtr * dKc))  
157
               colToMod <- (numBlendRows-iCtr)+1
158
#               qq <- as.integer(round(colVecValues[colToMod] + (curRowBoundaryOffset * dK)))
159
               colVecValues[colToMod] <- as.integer(round(colVecValues[colToMod] + (curRowBoundaryOffset * dK)))
160
#               colVecValues[iCtr] <- as.integer(round(colVecValues[iCtr] + (curRowBoundaryOffset * dK)))
161
            }
162
        }
163

  
164
# Insert this vector back into the mosaic: this technique adopted from raster PDF doc 'replacement' help. 
165
# Looks like: I have to specify the row index (vector) to insert the values into the mosaic. 
166
message("write columns to out mosaic")
167
#rowser()
168
        outMosaic[colVecCells] <- colVecValues
169

  
170
     }
171

  
172
# write the modified outMosaic values to the image file that we created.
173

  
174
message("Done with raster blending : hit key to update raster disk file..")
175
browser()
176
     writeRaster(outMosaic, sFixedRasterFile, datatype="INT2S", format="GTiff",overwrite=TRUE)
177
}
terrain/rscripts/DEMBoundarySolutionsBlock.R
1
##################################################################################### 
2
# DEMBoundarySolutionsBlock - Block version, uses a BLOCK write to create output mosaic
3
# 
4
# Collection of functions that attempt to mitigate ASTER / SRTM the boundary edge problem
5
# 
6
# 
7
#
8
# Inputs: 
9
#   1) Blended Aster/SRTM DEM mosaic image.
10
#   2) 'Aster-Only' subimage corresponding to the NORTHernmost part (adjacent to the 60 degree Lat 
11
#     boundary) of the SRTM component of the mosaic.
12
#   3) 'Aster-Only' subimage corresponding to the SOUTHernmost part (adjacent to the 60 degree Lat 
13
#     boundary) of the ASTER component of the mosaic.
14
#   4) Other parameters, as they are needed
15
#
16
# To run:
17
#
18
#  1) start R
19
#  2) > source("DEMBoundarySolutions.r")
20
#  3) > BlendAsterDEMPixelsBlock()
21
#
22
# Author: Rick Reeves, NCEAS
23
# May 31, 2011
24

  
25
##############################################################################################
26
BlendAsterDEMPixelsBlock <- function()
27
{
28
  require(raster)
29
  require(rgdal)
30
  
31
# Read the mosaic image and component sub-images:
32
#   - Aster/SRTM mosaic image (with boundary edge to be fixed)
33
#   - 'Aster-only' subimage adjacent to Southern edge of 60 degree bounls -s dary,
34
#     sampled into a grid with same extent and spatial resolution as image mosaic
35
#   - 'Aster-only' subimage adjacent to Northern edge of 60 degree boundary,
36
#     sampled into a grid with same extent and spatial resolution as image mosaic
37
    
38
#     inMosaic      <- raster("t:/rcr/BoundaryFixTest/AsterSrtmBoth3ArcSecSub.tif")
39
#     inAsterNorth  <- raster("t:/rcr/BoundaryFixTest/AsterBdyTest3ArcSecFullGridAbove60.tif")     
40
#    inAsterSouth  <- raster("t:/rcr/BoundaryFixTest/AsterBdyTest3ArcSecFullGridBelow60.tif")    
41
     inMosaic      <- raster("./AsterSrtmBoth3ArcSecSub.tif")
42
     
43
# Use these objects to get the extents of the subsets within the mosaic
44

  
45
     inAsterNorth  <- raster("./AsterBdyTestAbove60Sub.tif")     
46
     inAsterSouth  <- raster("./AsterBdyTestBelow60Sub.tif")     
47
     
48
# Better, read them into a rasterStack
49

  
50
#     mosaicLayers <- stack("./AsterSrtmBoth3ArcSecSub.tif",
51
#                           "./AsterBdyTest3ArcSecFullGridAbove60.tif",
52
#                           "./AsterBdyTest3ArcSecFullGridBelow60.tif") # fix by exporting from ArcGIS
53

  
54
     mosaicLayers <- stack("./AsterSRTMBothTestSub.tif",
55
                           "./AsterBdyTestFGAbove60Sub.tif",
56
                           "./AsterBdyTestFGBelow60Sub.tif") 
57
# 
58
# Create copy of input raster that we will use to create a 'fixed boundary' iamge
59
# Even SIMPLER, according to raster documentation
60
#
61
     outMosaic <- raster(mosaicLayers[[1]])
62
 
63
     sFixedRasterFile <- "TestOutputRasterBdyFix.tif"
64
     
65
# First, get the extent of the 'below 60' sub image in the (big) input raster
66

  
67
     northAsterEx <- extent(inAsterNorth)
68
     southAsterEx <- extent(inAsterSouth)
69
     
70
# Get the values from the mosaic for this extent
71

  
72
     southCellsOfInterest <- cellsFromExtent(mosaicLayers[[1]],southAsterEx)
73
     northCellsOfInterest <- cellsFromExtent(mosaicLayers[[1]],northAsterEx)
74

  
75
# Within the large input raster, we need the index of the first row of the 'Below 60 Aster' subimage.
76
# Our plan: to replace this portion of the input mosaic with a linear combination of the original
77
# input mosaic COPY (outMosaic) and the 'below 60' raster.
78

  
79
     firstNorthSubImgRow <- rowFromCell(mosaicLayers[[1]],northCellsOfInterest[1])   
80
     lastNorthSubImgRow <- rowFromCell(mosaicLayers[[1]],northCellsOfInterest[(length(northCellsOfInterest) - 1)])
81
     northNrowsToProcess <- nrow(inAsterNorth)
82
  
83
     firstSouthSubImgRow <- rowFromCell(mosaicLayers[[1]],southCellsOfInterest[1])   
84
     lastSouthSubImgRow <- rowFromCell(mosaicLayers[[1]],southCellsOfInterest[(length(southCellsOfInterest) - 1)])
85
     southNrowsToProcess <- nrow(inAsterSouth)
86

  
87
#  create the output raster by copying the input file with 'block copy'
88
     
89
message("Create output (fixed) mosaic")
90
#browser()
91
     bs <- blockSize(mosaicLayers[[1]]) 
92
     outMosaic <- writeStart(outMosaic,sFixedRasterFile, datatype="INT2S", format="GTiff",overwrite=TRUE)
93
     for (iCtr in 1 : bs$n)
94
     {
95
        mosaicVals <- getValues(mosaicLayers[[1]],row=bs$row[iCtr],nrows=bs$nrows[iCtr])
96
        writeValues(outMosaic,mosaicVals,bs$row[iCtr])
97
        message(sprintf(".....processed input mosaic block %d",iCtr))        
98
     }
99
     outMosaic <- writeStop(outMosaic)
100
message("Input mosaic copied to output raster: now, process boundary")
101
#browser()
102

  
103
# now, we SHOULD be able to modify outMosaic with new 'column values'.
104

  
105
# note: last north image and first south image rows are the same. 
106

  
107
     northBorderEdgeRow <- lastNorthSubImgRow
108
     southBorderEdgeRow <- firstSouthSubImgRow + 1
109

  
110
# The border 'edge' row is one row below the top of the south sub image
111

  
112
     southBrdrRowVals <- getValues(outMosaic,southBorderEdgeRow,1)
113
     northBrdrRowVals <- getValues(outMosaic,northBorderEdgeRow,1)
114
 
115
     brdrRowEdgeDelta <- southBrdrRowVals - northBrdrRowVals
116

  
117
# Process the mosaic 'column-by-column'
118
# For first effort, apply straightforward linear ramp function to the northernmost SRTM image rows.
119
# In next iteration, we will modify the LAST 'numBlendRows' rows NORTH of the boundary with an 'extinction' function.
120
#
121
     numBlendRows <- 100
122
     srows <- seq(southBorderEdgeRow,((southBorderEdgeRow + numBlendRows) - 1))
123
# 
124
     for (curMosCol in 1 : ncol(mosaicLayers[[1]]))
125
     {
126
message(sprintf("transforming cur col: %d",curMosCol))
127
#browser()
128
        deltaInc <- brdrRowEdgeDelta[curMosCol] / numBlendRows
129
        colVecCells <- cellFromRowCol(outMosaic,srows,curMosCol) 
130
        colVecValues <- getValuesBlock(outMosaic,row=southBorderEdgeRow,nrows=numBlendRows,col=curMosCol,ncols=1) 
131

  
132
# note: we need to deal with NA values, which are possible. 
133

  
134
        sumDeltaInc <- 0
135
        for (iCtr in length(colVecValues) : 1)
136
        {
137

  
138
# The idea: the closer to the border, the larger an increment we assign.
139
# in any case, increment the offset so that it is correct for any iupcoming non-NA column value
140

  
141
            sumDeltaInc <- sumDeltaInc + deltaInc
142

  
143
            if (!is.na(colVecValues[1]))
144
            {
145
#message(sprintf("cur col: %d Found a NON-NA vector",curMosCol))
146
#browser()
147
               colVecValues[iCtr] <- as.integer(round(colVecValues[iCtr] - sumDeltaInc)) 
148
            }
149
        }
150

  
151
# Insert this vector back into the mosaic: this technique adopted from raster PDF doc 'replacement' help. 
152
# Looks like: I have to specify the row index (vector) to insert the values into the mosaic. 
153
#message("write columns to out mosaic")
154
#browser()
155
        outMosaic[colVecCells] <- colVecValues
156
#        outMosaic[srows,curMosCol] <- colVecValues #  this did not seem to work - june 1
157

  
158
     }
159
#message(sprintf("cur col: %d about to write to outMosaic",curMosCol))
160
#browser()
161

  
162
# write the modified outMosaic values to the image file that we created.
163

  
164
message("Done with raster blending : hit key to update raster disk file..")
165
browser()
166
     writeRaster(outMosaic, sFixedRasterFile, datatype="INT2S", format="GTiff",overwrite=TRUE)
167
}
terrain/rscripts/FixDEMMosaicBlendedRows.R
1
##################################################################################### 
2
# FixDEMMosaicBlendedRows: Implements Image Blending treatment to DEM Mosaic image
3
# Collection of functions that attempt to mitigate ASTER / SRTM the boundary edge artifact
4
# 
5
# Inputs: 
6
#   1) DEM Mosaic image containing 'boundary edge' artifact 
7
#   2) 'Aster-Only' subimage corresponding to the NORTHernmost part (adjacent to the 60 degree Lat 
8
#     boundary) of the SRTM component of the mosaic.
9
#   3) 'Aster-Only' subimage corresponding to the SOUTHernmost part (adjacent to the 60 degree Lat 
10
#     boundary) of the ASTER component of the mosaic.
11
#   4) numBlendRows: number of number of rows south of 60 degrees N Lat to modify ('blend') by
12
#      generating (lnear) combination of SRTM and ASTER image pixels. 
13
#
14
# Output: 
15
#   1) A copy of the input DEM mosaic, with 'blended image' boundary edge treatment.
16
#
17
# To run:
18
#
19
#  1) start R
20
#  2) > source("FixDEMMosaicBlendedRows.r")
21
#  3) > FixDEMMosaicBlendedRows()
22
#
23
# Note: the input images used by this program located on /jupiter: /data/project/organisms/rcr/BoundaryFixTest
24
#    
25
# Author: Rick Reeves, NCEAS
26
# June 12, 2011
27
#
28
##############################################################################################
29
FixDEMMosaicBlendedRows <- function()
30
{
31
  require(raster)
32
  require(rgdal)
33
 
34
# Key parameter: number of rows south of 60 degrees N Lat to modify ('blend') by
35
# generating (lnear) combination of SRTM and ASTER image pixels. 
36

  
37
  numBlendRows <- 100
38
  
39
# Read the mosaic image and component sub-images:
40
#   - Aster/SRTM mosaic image (with boundary edge to be fixed)
41
#   - 'Aster-only' subimage adjacent to Southern edge of 60 degree bounls -s dary,
42
#     sampled into a grid with same extent and spatial resolution as image mosaic
43
#   - 'Aster-only' subimage adjacent to Northern edge of 60 degree boundary,
44
#     sampled into a grid with same extent and spatial resolution as image mosaic
45
#     inAsterNorthFG  <- raster("./aster60DegNorthRasterFG.tif")     
46
#     inAsterSouthFG  <- raster("./aster59DegSouthRasterFG.tif")
47
#     inBdyAsterBoth  <- raster("./boundaryTestCase115DegBothAsterMos.img")      
48

  
49
     inMosaic      <- raster("./AsterSrtm3ArcSecTestImg.tif") 
50
     inAsterSouth  <- raster("./boundaryTest115_59DegreeAster.img")   
51
     inAsterSouthFG  <- raster("./aster59DegSouthRasterFG.tif")     
52
     inAsterNorth  <- raster("./boundaryTest115_60DegreeAster.img")     
53

  
54
# First, get the extent of the 'below 60' sub image in the (big) input raster
55

  
56
     northAsterEx <- extent(inAsterNorth)
57
     southAsterEx <- extent(inAsterSouth)
58

  
59
# Create copy of input raster that we will use to create a 'fixed boundary' iamge
60
# Even SIMPLER, according to raster documentation
61

  
62
     outMosaic <- raster(inMosaic) 
63
     
64
     sFixedRasterFile <- "TestOutRasterBdyBlendFixAft2.tif"
65
     
66
#  create the output raster by copying the input file with 'block copy'
67
     
68
message("Copy input mosaic: Create output (repaired) mosaic")
69
#browser()
70
     bs <- blockSize(inMosaic) 
71
     outMosaic <- writeStart(outMosaic,sFixedRasterFile, datatype="INT2S", format="GTiff",overwrite=TRUE)
72
     for (iCtr in 1 : bs$n)
73
     {
74
        mosaicVals <- getValues(inMosaic,row=bs$row[iCtr],nrows=bs$nrows[iCtr])
75
        writeValues(outMosaic,mosaicVals,bs$row[iCtr])
76
        message(sprintf(".....processed input mosaic block %d",iCtr))        
77
     }
78
     outMosaic <- writeStop(outMosaic)
79
# 
80
message("Input mosaic copied to output raster: now, process boundary")
81
browser()
82

  
83
# now, we SHOULD be able to modify outMosaic with new 'column values'.
84

  
85
     southCellsOfInterest <- cellsFromExtent(outMosaic,southAsterEx)
86
     northCellsOfInterest <- cellsFromExtent(outMosaic,northAsterEx)
87
     
88
     firstNorthSubImgRow <- rowFromCell(outMosaic,northCellsOfInterest[1])   
89
     lastNorthSubImgRow <- rowFromCell(outMosaic,northCellsOfInterest[(length(northCellsOfInterest) - 1)])
90
 
91
     firstSouthSubImgRow <- rowFromCell(outMosaic,southCellsOfInterest[1])   
92
     lastSouthSubImgRow <- rowFromCell(outMosaic,southCellsOfInterest[(length(southCellsOfInterest) - 1)])
93

  
94
# note: last north image and first south image rows are the same.
95

  
96
     northBorderEdgeRow <- lastNorthSubImgRow
97
     southBorderEdgeRow <- firstSouthSubImgRow + 1
98

  
99
# The border 'edge' row is one row below the top of the south sub image
100

  
101
     northBrdrRowVals <- getValues(outMosaic,northBorderEdgeRow,1)
102
     southBrdrRowVals <- getValues(outMosaic,southBorderEdgeRow,1)     
103
 
104
# Process the mosaic rows:
105
# Blend the first 'numBlendRows' south of the 60 degree line (first rows of the SRTM component)
106
# with the underlying and corresponding ASTER image rows.
107
# For first attempt, use a linear combination; for second attempt, use an exponential function.
108
#
109
     nImageCols <- ncol(inMosaic)     
110
     sRows <- seq(southBorderEdgeRow,((southBorderEdgeRow + numBlendRows) - 1))
111
# 
112
     rowVecValuesBlend <- vector(mode="integer",length=nImageCols)
113
     iRowCtr <- 1
114
     for (curMosRow in sRows)     
115
     {
116
message(sprintf("transforming cur row: %d",curMosRow))
117
#:browser()
118

  
119
# even simpler here, as we implement a 'linear distance decay' function,
120
# and let each new column be a linear combination of the Aster and CGIAR image layers
121

  
122
        deltaInc <- iRowCtr / as.numeric(numBlendRows)
123
        colVecCells <- cellFromRowCol(outMosaic,curMosRow,1:nImageCols) 
124

  
125
# get the current row from the mosaic(SRTM data) and raster images
126
# We get the ASTER values from a version of the 'South' ASTER image 
127
# with same extent as the image mosaic.
128

  
129
        rowVecValuesMosaic <- getValuesBlock(outMosaic,row=curMosRow,nrows=1,col=1,ncols=nImageCols) 
130
        rowVecValuesAster <- getValuesBlock(inAsterSouthFG,row=curMosRow,nrows=1,col=1,ncols=nImageCols)        
131
        rowVecValuesBlend <- (rowVecValuesMosaic * deltaInc) + (rowVecValuesAster * (1.0 - deltaInc))
132

  
133
# create the merged row as a linear combination of the Mosaic and Aster image. 
134
# note: we need to deal with NA values, which are possible. 
135

  
136
# write the blended row to the output mosaic
137

  
138
        outMosaic[colVecCells] <- as.integer(round(rowVecValuesBlend))
139
        iRowCtr <- iRowCtr + 1
140
     }
141
#message(sprintf("cur col: %d about to write to outMosaic",curMosCol))
142
#browser()
143

  
144
# write the modified outMosaic values to the image file that we created.
145

  
146
message("Done with raster blending : hit key to update raster disk file..")
147
browser()
148
     writeRaster(outMosaic, sFixedRasterFile, datatype="INT2S", format="GTiff",overwrite=TRUE)
149
#browser()
150
}
terrain/rscripts/FixDEMMosaicBlendedRowsExpDecay.R
1
##################################################################################### 
2
# FixDEMMosaicBlendedRowsExpDecay: Implements Image Blending treatment to DEM Mosaic image
3
# Collection of functions that attempt to mitigate ASTER / SRTM the boundary edge artifact
4
# This version implements the Exponential Decay function to control image blending rate.
5
# Inputs: 
6
#   1) DEM Mosaic image containing 'boundary edge' artifact 
7
#   2) 'Aster-Only' subimage corresponding to the NORTHernmost part (adjacent to the 60 degree Lat 
8
#     boundary) of the SRTM component of the mosaic.
9
#   3) 'Aster-Only' subimage corresponding to the SOUTHernmost part (adjacent to the 60 degree Lat 
10
#     boundary) of the ASTER component of the mosaic.
11
#   4) numBlendRows: number of number of rows south of 60 degrees N Lat to modify ('blend') by
12
#      generating (lnear) combination of SRTM and ASTER image pixels. 
13
#   5) dKc: Empirically-determined exponential decay constant. Rule of thumb: set this such 
14
#      that exponential decay function approaches zero as row 'numBlendRows' is treated.
15
#
16
# Output: 
17
#   1) A copy of the input DEM mosaic, with 'blended image' boundary edge treatment.
18
#
19
# To run:
20
#
21
#  1) start R
22
#  2) > source("FixDEMMosaicBlendedRows.r")
23
#  3) > FixDEMMosaicBlendedRows()
24
#
25
# Note: the input images used by this program located on /jupiter: /data/project/organisms/rcr/BoundaryFixTest
26
#    
27
# Author: Rick Reeves, NCEAS
28
# June 13, 2011
29
#
30
##############################################################################################
31
FixDEMMosaicBlendedRowsExpDecay <- function()
32
{
33
  require(raster)
34
  require(rgdal)
35
 
36
# Key parameter: number of rows south of 60 degrees N Lat to modify ('blend') by
37
# generating (lnear) combination of SRTM and ASTER image pixels. 
38

  
39
  numBlendRows <- 100
40
  dKc <- .045 # empirically determined exponential decay constant. Select it 
41
#              so that exp - 1 decay goes to zero in the desired number of image rows.
42
  
43
# Read the mosaic image and component sub-images:
44
#   - Aster/SRTM mosaic image (with boundary edge to be fixed)
45
#   - 'Aster-only' subimage adjacent to Southern edge of 60 degree bounls -s dary,
46
#     sampled into a grid with same extent and spatial resolution as image mosaic
47
#   - 'Aster-only' subimage adjacent to Northern edge of 60 degree boundary,
48
#     sampled into a grid with same extent and spatial resolution as image mosaic
49
#     inAsterNorthFG  <- raster("./aster60DegNorthRasterFG.tif")     
50
#     inAsterSouthFG  <- raster("./aster59DegSouthRasterFG.tif")
51
#     inBdyAsterBoth  <- raster("./boundaryTestCase115DegBothAsterMos.img")      
52

  
53
     inMosaic      <- raster("./AsterSrtm3ArcSecTestImg.tif") 
54
     inAsterSouth  <- raster("./boundaryTest115_59DegreeAster.img")   
55
     inAsterSouthFG  <- raster("./aster59DegSouthRasterFG.tif")     
56
     inAsterNorth  <- raster("./boundaryTest115_60DegreeAster.img")     
57

  
58
# First, get the extent of the 'below 60' sub image in the (big) input raster
59

  
60
     northAsterEx <- extent(inAsterNorth)
61
     southAsterEx <- extent(inAsterSouth)
62

  
63
# Create copy of input raster that we will use to create a 'fixed boundary' iamge
64
# Even SIMPLER, according to raster documentation
65

  
66
     outMosaic <- raster(inMosaic) 
67
     
68
     sFixedRasterFile <- "TestOutRasterBdyBlendFixExpDec.tif"
69
     
70
#  create the output raster by copying the input file with 'block copy'
71
     
72
message("Copy input mosaic: Create output (repaired) mosaic")
73
#browser()
74
     bs <- blockSize(inMosaic) 
75
     outMosaic <- writeStart(outMosaic,sFixedRasterFile, datatype="INT2S", format="GTiff",overwrite=TRUE)
76
     for (iCtr in 1 : bs$n)
77
     {
78
        mosaicVals <- getValues(inMosaic,row=bs$row[iCtr],nrows=bs$nrows[iCtr])
79
        writeValues(outMosaic,mosaicVals,bs$row[iCtr])
80
        message(sprintf(".....processed input mosaic block %d",iCtr))        
81
     }
82
     outMosaic <- writeStop(outMosaic)
83
# 
84
message("Input mosaic copied to output raster: now, process boundary")
85
browser()
86

  
87
# now, we SHOULD be able to modify outMosaic with new 'column values'.
88

  
89
     southCellsOfInterest <- cellsFromExtent(outMosaic,southAsterEx)
90
     northCellsOfInterest <- cellsFromExtent(outMosaic,northAsterEx)
91
     
92
     firstNorthSubImgRow <- rowFromCell(outMosaic,northCellsOfInterest[1])   
93
     lastNorthSubImgRow <- rowFromCell(outMosaic,northCellsOfInterest[(length(northCellsOfInterest) - 1)])
94
 
95
     firstSouthSubImgRow <- rowFromCell(outMosaic,southCellsOfInterest[1])   
96
     lastSouthSubImgRow <- rowFromCell(outMosaic,southCellsOfInterest[(length(southCellsOfInterest) - 1)])
97

  
98
# note: last north image and first south image rows are the same.
99

  
100
     northBorderEdgeRow <- lastNorthSubImgRow
101
     southBorderEdgeRow <- firstSouthSubImgRow + 1
102

  
103
# The border 'edge' row is one row below the top of the south sub image
104

  
105
     northBrdrRowVals <- getValues(outMosaic,northBorderEdgeRow,1)
106
     southBrdrRowVals <- getValues(outMosaic,southBorderEdgeRow,1)     
107
 
108
# Process the mosaic rows:
109
# Blend the first 'numBlendRows' south of the 60 degree line (first rows of the SRTM component)
110
# with the underlying and corresponding ASTER image rows.
111
# For first attempt, use a linear combination; for second attempt, use an exponential function.
112
#
113
     nImageCols <- ncol(inMosaic)     
114
     sRows <- seq(southBorderEdgeRow,((southBorderEdgeRow + numBlendRows) - 1))
115
# 
116
     rowVecValuesBlend <- vector(mode="integer",length=nImageCols)
117
     iRowCtr <- 1
118
     for (curMosRow in sRows)     
119
     {
120
         message(sprintf("transforming cur row: %d",curMosRow))
121
# exponential decay diminishes impact of the 'delta' edge adjustment with distance from the boundary.
122

  
123
         dK <- exp(-(iRowCtr * dKc))
124
#         colToMod <- (numBlendRows-iCtr)+1
125
#               qq <- as.integer(round(colVecValues[colToMod] + (curRowBoundaryOffset * dK)))
126
#               colVecValues[colToMod] <- as.integer(round(colVecValues[colToMod] + (curRowBoundaryOffset * dK)))
127
#               colVecValues[iCtr] <- as.integer(round(colVecValues[iCtr] + (curRowBoundaryOffset * dK)))
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff