-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshpmrg.go
286 lines (244 loc) · 8.46 KB
/
shpmrg.go
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
package main
import (
"encoding/csv"
"flag"
"fmt"
"github.com/jonas-p/go-shp"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"sync/atomic"
)
var inPath = flag.String("i", "", "Input file glob path to shapefiles")
var outPath = flag.String("o", "", "Output file location")
var shapeType = flag.Int("t", 25, "Default is polygon; Shape type from https://godoc.org/github.com/jonas-p/go-shp#ShapeType")
var alphaNumeric = regexp.MustCompile("[^a-zA-Z0-9]+")
func main() {
flag.Parse()
if len(os.Args) < 2 {
fmt.Println("Last argument must be one of: merge, extract-attrs")
os.Exit(1)
}
if *inPath == "" {
fmt.Println("Missing -i input file(s)")
flag.PrintDefaults()
os.Exit(1)
}
if *outPath == "" {
fmt.Println("Missing -o output location")
flag.PrintDefaults()
os.Exit(1)
}
action := os.Args[len(os.Args)-1]
fileMatches, err := filepath.Glob(*inPath)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
if len(fileMatches) < 1 {
fmt.Println("No matches for input pattern")
os.Exit(1)
}
var allFields []shp.Field
fieldNameToIndex := make(map[string]int)
// pass 1, get all possible allFields
for i, shapePath := range fileMatches {
shapefile, err := shp.Open(shapePath)
if err != nil {
fmt.Println("Problem reading", shapePath, ", skipping. ", err)
continue
}
fmt.Println("Processing shapefile allFields", shapePath, "(", i+1, "of", len(fileMatches), ")")
localFields := shapefile.Fields()
var fieldName string
var fieldIndex int
for _, localField := range localFields {
fieldName = string(localField.Name[:11])
if _, exists := fieldNameToIndex[fieldName]; !exists {
allFields = append(allFields, localField)
fieldIndex = len(allFields) - 1
fieldNameToIndex[fieldName] = fieldIndex
}
}
}
if action == "merge" {
merge(fileMatches, allFields, fieldNameToIndex)
} else if action == "extract-attrs" {
extractAtrrs(fileMatches, allFields, fieldNameToIndex)
} else {
fmt.Println("Last argument must be one of: merge, extract-attrs")
os.Exit(1)
}
fmt.Println("Done")
}
func merge(fileMatches []string, allFields []shp.Field, fieldNameToIndex map[string]int) {
outputFile, err := shp.Create(*outPath, shp.ShapeType(*shapeType))
if err != nil {
fmt.Println(err)
os.Exit(1)
}
err = outputFile.SetFields(allFields)
if err != nil {
fmt.Println("Failed setting output shapefile allFields, aborting!", err, allFields)
os.Exit(1)
}
var rowCursor int64
var filesProcessed int64
// pass 2, copy shapefiles
var wg sync.WaitGroup
var writelock sync.Mutex
for _, shPath := range fileMatches {
sf, err := shp.Open(shPath)
if err != nil {
fmt.Println("Problem reading", shPath, ", skipping. ", err)
continue
}
wg.Add(1)
go func(shapePath string, shapefile *shp.Reader) {
localFields := shapefile.Fields()
// loop through all features in the shapefile
for shapefile.Next() {
localRow, shape := shapefile.Shape()
// print feature
//fmt.Println(reflect.TypeOf(shape).Elem(), shape.BBox())
writelock.Lock()
outputFile.Write(shape)
writelock.Unlock()
// print attributes
var remoteKey int
var fieldName string
for localKey, field := range localFields {
val := shapefile.ReadAttribute(localRow, localKey)
//fmt.Printf("\t%v: %v\row", f, val)
fieldName = string(field.Name[:11])
remoteKey = fieldNameToIndex[fieldName]
writelock.Lock()
err = outputFile.WriteAttribute(int(rowCursor), remoteKey, val)
writelock.Unlock()
if err != nil {
fmt.Println("Failed writing attribute, skipping. ", localKey, val, err)
continue
}
}
atomic.AddInt64(&rowCursor, 1)
if rowCursor%10000 == 0 {
fmt.Println("Total shapes processed:", rowCursor)
}
}
final := atomic.AddInt64(&filesProcessed, 1)
err = shapefile.Close()
if err != nil {
fmt.Println("Failed closing shapefile", shapePath, err)
} else {
fmt.Println("Finished", shapePath, "(", final, "of", len(fileMatches), ")")
}
wg.Done()
}(shPath, sf)
}
wg.Wait()
outputFile.Close()
fmt.Println("Processed", rowCursor)
}
func extractAtrrs(fileMatches []string, allFields []shp.Field, fieldNameToIndex map[string]int) {
outputFile, err := os.Create(*outPath)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
writer := csv.NewWriter(outputFile)
if err != nil {
fmt.Print(err)
os.Exit(1)
}
// Add a special field with the filename
fieldCount := len(allFields)
filenameLastColumnIndex := fieldCount - 1
// write header
var header []string
// the order matters
for _, f := range allFields {
header = append(header, cleanName(f.Name[:11]))
}
header[filenameLastColumnIndex] = "shpmrg_input"
err = writer.Write(header)
if err != nil {
fmt.Println("Failed to write csv header", err)
os.Exit(1)
}
var rowCursor int64
var filesProcessed int64
// pass 2, copy shapefiles
var wg sync.WaitGroup
var writelock sync.Mutex
for _, shPath := range fileMatches {
sf, err := shp.Open(shPath)
if err != nil {
fmt.Println("Problem reading", shPath, ", skipping. ", err)
continue
}
wg.Add(1)
go func(shapePath string, shapefile *shp.Reader) {
localFields := shapefile.Fields()
// /opt/geo/myshape0.shp -> myshape0
basename := strings.Replace(filepath.Base(shapePath), filepath.Ext(shapePath), "", 1)
// loop through all features in the shapefile
var localRowIndex int
var csvRow []string
for shapefile.Next() {
localRowIndex, _ = shapefile.Shape()
// print attributes
var fieldName string
var column int
csvRow = newRow(fieldCount)
for localKey, field := range localFields {
val := shapefile.ReadAttribute(localRowIndex, localKey)
//fmt.Printf("\t%v: %v\row", f, val)
fieldName = string(field.Name[:11])
column = fieldNameToIndex[fieldName]
csvRow[column] = val
}
csvRow[filenameLastColumnIndex] = basename
writelock.Lock()
err = writer.Write(csvRow)
writelock.Unlock()
if err != nil {
fmt.Println("Failed writing csv row", localRowIndex, shapePath, err)
continue
}
atomic.AddInt64(&rowCursor, 1)
if rowCursor%10000 == 0 {
fmt.Println("Total shapes processed:", rowCursor)
}
}
final := atomic.AddInt64(&filesProcessed, 1)
err = shapefile.Close()
if err != nil {
fmt.Println("Failed closing shapefile", shapePath, err)
} else {
fmt.Println("Finished", shapePath, "(", final, "of", len(fileMatches), ")")
}
wg.Done()
}(shPath, sf)
}
wg.Wait()
writer.Flush()
err = outputFile.Close()
if err != nil {
fmt.Println("failed closing CSV", *outPath, err)
}
fmt.Println("Processed", rowCursor)
}
// seeding everything with empty string keeps there from being nulls on import, which breaks
// many simple sql import tools
func newRow(size int) (r []string) {
r = make([]string, size)
for i := 0; i < size; i++ {
r[i] = ""
}
return r
}
func cleanName(name []byte) string {
return string(alphaNumeric.ReplaceAll(name, []byte("")))
}