Class: NSWTopo::Map

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Dither, Formats, Log, Safely, TiledWebMap, Zip
Defined in:
lib/nswtopo/map.rb

Constant Summary

Constants included from Formats

Formats::ARGS, Formats::PPI, Formats::TILE

Constants included from Log

Log::FAILURE, Log::NEUTRAL, Log::SUCCESS, Log::UPDATE

Constants included from Dither

Dither::Missing

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Formats

===, extensions, #neatline_path_data, #rasterise, #render_gemf, #render_jpg, #render_kmz, #render_mbtiles, #render_pdf, #render_png, #render_svg, #render_svgz, #render_tif, #render_zip

Methods included from Log

#log_abort, #log_neutral, #log_success, #log_update, #log_warn

Methods included from Dither

#dither

Methods included from Zip

#zip

Methods included from Safely

#safely

Methods included from TiledWebMap

#tiled_web_map

Constructor Details

#initialize(archive, neatline:, centre:, dimensions:, scale:, rotation:, layers: {}) ⇒ Map

Returns a new instance of Map.



5
6
7
8
9
10
11
12
# File 'lib/nswtopo/map.rb', line 5

def initialize(archive, neatline:, centre:, dimensions:, scale:, rotation:, layers: {})
  @archive, @neatline, @centre, @dimensions, @scale, @rotation, @layers = archive, neatline, centre, dimensions, scale, rotation, layers
  params = { k_0: 1.0 / @scale, units: "mm", x_0: 0.0005 * @dimensions[0], y_0: 0.0005 * @dimensions[1] }
  @projection = rotation.zero? ?
    Projection.transverse_mercator(*centre, **params) :
    Projection.oblique_mercator(*centre, alpha: rotation, **params)
  @cutline = @neatline.reproject_to(@projection)
end

Instance Attribute Details

#centreObject (readonly)

Returns the value of attribute centre.



13
14
15
# File 'lib/nswtopo/map.rb', line 13

def centre
  @centre
end

#dimensionsObject (readonly)

Returns the value of attribute dimensions.



13
14
15
# File 'lib/nswtopo/map.rb', line 13

def dimensions
  @dimensions
end

#projectionObject (readonly)

Returns the value of attribute projection.



13
14
15
# File 'lib/nswtopo/map.rb', line 13

def projection
  @projection
end

#rotationObject (readonly)

Returns the value of attribute rotation.



13
14
15
# File 'lib/nswtopo/map.rb', line 13

def rotation
  @rotation
end

#scaleObject (readonly)

Returns the value of attribute scale.



13
14
15
# File 'lib/nswtopo/map.rb', line 13

def scale
  @scale
end

Class Method Details

.declination(longitude, latitude) ⇒ Object



211
212
213
214
215
216
217
218
219
# File 'lib/nswtopo/map.rb', line 211

def self.declination(longitude, latitude)
  today = Date.today
  query = { latd: latitude, lond: longitude, latm: 0, lonm: 0, lats: 0, lons: 0, elev: 0, year: today.year, month: today.month, day: today.day, Ein: "Dtrue" }
  uri = URI::HTTPS.build host: "api.geomagnetism.ga.gov.au", path: "/agrf", query: URI.encode_www_form(query)
  json = Net::HTTP.get uri
  Float(JSON.parse(json).dig("magneticFields", "D").to_s.sub(/ .*/, ""))
rescue JSON::ParserError, ArgumentError, TypeError, SystemCallError, EOFError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError, SocketError
  raise "couldn't get magnetic declination value"
end

.from_svg(archive, svg_path) ⇒ Object



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
# File 'lib/nswtopo/map.rb', line 130

def self.from_svg(archive, svg_path)
  xml = REXML::Document.new(svg_path.read)

  unless false == Config["versioning"]
    creator_tool = xml.elements["svg/metadata/rdf:RDF/rdf:Description[@xmp:CreatorTool]/@xmp:CreatorTool"]&.value
    version = Version[creator_tool]
    raise "SVG nswtopo version too old: %s" % svg_path unless version >= MIN_VERSION
    raise "SVG nswtopo version too new: %s" % svg_path unless version <= VERSION
  end

  /^0\s+0\s+(?<width>\S+)\s+(?<height>\S+)$/ =~ xml.elements["svg[@viewBox]/@viewBox"]&.value
   width && xml.elements["svg[ @width='#{ width}mm']"] || raise(Version::Error)
  height && xml.elements["svg[@height='#{height}mm']"] || raise(Version::Error)
  dimensions = [width, height].map(&:to_f)

   = xml.elements["svg/metadata/nswtopo:map[@projection][@centre][@scale][@rotation]"] || raise(Version::Error)
  projection = Projection.new .attributes["projection"]
  neatline = GeoJSON.polygon JSON.parse(.attributes["neatline"]), projection: projection
  centre = JSON.parse .attributes["centre"]
  scale = .attributes["scale"].to_i
  rotation = .attributes["rotation"].to_f

  new(archive, neatline: neatline, centre: centre, dimensions: dimensions, scale: scale, rotation: rotation).save.tap do |map|
    map.write "map.svg", svg_path.read
  end
rescue Version::Error, JSON::ParserError
  raise "not an nswtopo SVG file: %s" % svg_path
rescue SystemCallError
  raise "couldn't read file: %s" % svg_path
rescue REXML::ParseException
  raise "unrecognised map file: %s" % svg_path
end

.init(archive, scale: 25000, rotation: 0.0, bounds: nil, coords: nil, dimensions: nil, inset: [], margins: nil) ⇒ Object

Raises:

  • (OptionParser::InvalidArgument)


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
# File 'lib/nswtopo/map.rb', line 18

def self.init(archive, scale: 25000, rotation: 0.0, bounds: nil, coords: nil, dimensions: nil, inset: [], margins: nil)
  points = case
  when dimensions && margins
    raise "can't specify both margins and map dimensions"
  when coords && bounds
    raise "can't specify both bounds file and map coordinates"
  when coords
    coords
  when bounds
    gps = GPS.load(bounds).explode
    margins ||= [15, 15] unless dimensions || gps.polygons.any?
    case
    when gps.polygons.any?
      gps.polygons.flat_map(&:coordinates).inject(&:+)
    when gps.linestrings.any?
      gps.linestrings.map(&:coordinates).inject(&:+)
    when gps.points.any?
      gps.points.map(&:coordinates)
    else
      raise "no features found in %s" % bounds
    end
  else
    raise "no bounds file or map coordinates specified"
  end
  margins ||= [0, 0]

  centre = points.transpose.map(&:minmax).map(&:sum).times(0.5)
  equidistant = Projection.azimuthal_equidistant *centre

  case rotation
  when "auto"
    raise "can't specify both map dimensions and auto-rotation" if dimensions
    local_points = GeoJSON.multipoint(points).reproject_to(equidistant).coordinates
    local_centre, local_extents, rotation = local_points.minimum_bounding_box(*margins)
    rotation *= -180.0 / Math::PI
  when "magnetic"
    rotation = declination(*centre)
  else
    raise "map rotation must be between ±45°" unless rotation.abs <= 45
  end

  unless dimensions || local_centre
    local_points = GeoJSON.multipoint(points).reproject_to(equidistant).coordinates
    local_centre, local_extents = local_points.map do |point|
      point.rotate_by_degrees rotation
    end.transpose.map(&:minmax).map do |min, max|
      [0.5 * (max + min), max - min]
    end.transpose
    local_centre.rotate_by_degrees! -rotation
  end

  unless dimensions
    dimensions = local_extents.times(1000.0 / scale).plus margins.times(2)
    centre = GeoJSON.point(local_centre, projection: equidistant).reproject_to_wgs84.coordinates
  end

  params = { units: "mm", axis: "esu", k_0: 1.0 / scale, x_0: 0.0005 * dimensions[0], y_0: -0.0005 * dimensions[1] }
  projection = rotation.zero? ?
    Projection.transverse_mercator(*centre, **params) :
    Projection.oblique_mercator(*centre, alpha: rotation, **params)

  case
  when dimensions.all?(&:positive?)
  when coords
    raise "not enough information to calculate map size – add more coordinates, or specify map dimensions or margins"
  when bounds
    raise "not enough information to calculate map size – check bounds file, or specify map dimensions or margins"
  end

  insets = inset.map do |inset|
    inset.each_slice(2).entries.transpose.map(&:sort)
  end.each.with_object GeoJSON::Collection.new(projection: projection, name: "insets") do |bounds, collection|
    dimensions.zip(bounds).each do |dimension, (min, max)|
      raise OptionParser::InvalidArgument, "inset falls outside map dimensions" unless max > 0 && min < dimension
    end
    collection.add_polygon [bounds.inject(&:product).values_at(0,2,3,1,0)]
  end

  neatline = if insets.any?
    OS.ogr2ogr *%w[-f GeoJSON -lco RFC7946=NO /vsistdout/ GeoJSON:/vsistdin/ -dialect sqlite -sql], <<~SQL do |stdin|
      SELECT ST_Difference(BuildMbr(0,0,#{dimensions.join ?,}), ST_Union(geometry)) AS geometry
      FROM insets
    SQL
      stdin.puts insets.to_json
    end.then do |json|
      GeoJSON::Collection.load(json, projection: projection, name: "neatline").explode
    end
  else
    ring = [[0, 0], dimensions].transpose.inject(&:product).values_at(0,2,3,1,0)
    GeoJSON.polygon [ring], projection: projection, name: "neatline"
  end

  raise OptionParser::InvalidArgument, "inset covers map" if neatline.none?
  raise OptionParser::InvalidArgument, "inset creates non-contiguous map" unless neatline.one?
  new(archive, neatline: neatline, centre: centre, dimensions: dimensions, scale: scale, rotation: rotation).save
end

.load(archive) ⇒ Object



115
116
117
118
119
120
121
# File 'lib/nswtopo/map.rb', line 115

def self.load(archive)
  properties = YAML.load(archive.read "map.yml")
  neatline = GeoJSON::Collection.load(archive.read "map.json")
  new archive, neatline: neatline, **properties
rescue ArgumentError, YAML::Exception, GeoJSON::Error
  raise NSWTopo::Archive::Invalid
end

Instance Method Details

#add(*layers, after: nil, before: nil, replace: nil, overwrite: false, strict: false) ⇒ Object



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
# File 'lib/nswtopo/map.rb', line 225

def add(*layers, after: nil, before: nil, replace: nil, overwrite: false, strict: false)
  [%w[before after replace], [before, after, replace]].transpose.select(&:last).each do |option, name|
    next if self.layers.any? { |other| other.name == name }
    raise "no such layer: %s" % name
  end.map(&:first).combination(2).each do |options|
    raise OptionParser::AmbiguousOption,  "can't specify --%s and --%s simultaneously" % options
  end

  strict ||= layers.one?
  layers.inject [self.layers, false, replace || after, []] do |(layers, changed, follow, errors), layer|
    index = layers.index layer unless replace || after || before
    if overwrite || !layer.uptodate?
      layer.create
      log_success "%s layer: %s" % [layer.empty? ? "empty" : "added", layer.name]
    else
      log_neutral "kept existing layer: %s" % layer.name
      next layers, changed, layer.name, errors if index
    end
    layers.delete layer
    case
    when index
    when follow
      index = layers.index { |other| other.name == follow }
      index += 1
    when before
      index = layers.index { |other| other.name == before }
    else
      index = layers.index { |other| (other <=> layer) > 0 } || -1
    end
    next layers.insert(index, layer), true, layer.name, errors
  rescue ArcGIS::Connection::Error => error
    log_warn "couldn't download layer: #{layer.name}"
    next layers, changed, follow, errors << error
  rescue RuntimeError => error
    errors << error
    break layers, changed, follow, errors if strict
    log_warn error.message
    next layers, changed, follow, errors
  end.tap do |ordered_layers, changed, follow, errors|
    if changed
      @layers.replace Hash[ordered_layers.map(&:pair)]
      replace ? delete(replace) : save
    end
    case
    when errors.none?
    when strict
      raise errors.first
    when errors.one?
      raise PartialFailureError, "failed to create layer"
    else
      raise PartialFailureError, "failed to create #{errors.length} layers"
    end
  end
end

#cutline(mm: nil) ⇒ Object



173
174
175
# File 'lib/nswtopo/map.rb', line 173

def cutline(mm: nil)
  mm ? @cutline.buffer(mm).explode : @cutline
end

#declinationObject



221
222
223
# File 'lib/nswtopo/map.rb', line 221

def declination
  Map.declination *@centre
end

#delete(*names) ⇒ Object

Raises:

  • (OptionParser::MissingArgument)


280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
# File 'lib/nswtopo/map.rb', line 280

def delete(*names)
  raise OptionParser::MissingArgument, "no layers specified" unless names.any?
  names.inject Set[] do |matched, name|
    matches = @layers.keys.grep(name)
    raise "no such layer: #{name}" if String === name && matches.none?
    matched.merge matches
  end.tap do |names|
    raise "no matching layers found" unless names.any?
  end.each do |name|
    params = @layers.delete name
    @archive.delete Layer.new(name, self, params).filename
    log_success "deleted layer: %s" % name
  end
  save
end

#geotransform(resolution: nil, ppi: nil) ⇒ Object



189
190
191
192
# File 'lib/nswtopo/map.rb', line 189

def geotransform(resolution: nil, ppi: nil)
  mm_per_px = ppi ? 25.4 / ppi : to_mm(resolution)
  [0.0, mm_per_px, 0.0, @dimensions[1], 0.0, -mm_per_px]
end

#info(empty: nil, json: false, proj: false, wkt: false) ⇒ Object Also known as: to_s



314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
# File 'lib/nswtopo/map.rb', line 314

def info(empty: nil, json: false, proj: false, wkt: false)
  case
  when json
    bbox = @neatline.reproject_to_wgs84.first
    bbox.properties.merge! dimensions: @dimensions, scale: @scale, rotation: @rotation, layers: layers.map(&:name)
    JSON.pretty_generate bbox.to_h
  when proj
    OS.gdalsrsinfo("-o", "proj4", "--single-line", @projection)
  when wkt
    OS.gdalsrsinfo("-o", "wkt2", @projection).gsub(/\n\n+|\A\n+/, "")
  else
    area_km2 = @neatline.area * (0.000001 * @scale)**2
    extents_km = @dimensions.times(0.000001 * @scale)
    StringIO.new.tap do |io|
      io.puts "%-11s 1:%i" %            ["scale:",      @scale]
      io.puts "%-11s %imm × %imm" %     ["dimensions:", *@dimensions.map(&:round)]
      io.puts "%-11s %.1fkm × %.1fkm" % ["extent:",     *extents_km]
      io.puts "%-11s %.1fkm²" %         ["area:",       area_km2]
      io.puts "%-11s %.1f°" %           ["rotation:",   @rotation]
      layers.reject(&empty ? :nil? : :empty?).inject("layers:") do |heading, layer|
        io.puts "%-11s %s" % [heading, layer]
        nil
      end
    end.string
  end
end

#layersObject



163
164
165
166
167
# File 'lib/nswtopo/map.rb', line 163

def layers
  @layers.map do |name, params|
    Layer.new(name, self, params)
  end
end

#move(name, before: nil, after: nil) ⇒ Object

Raises:

  • (OptionParser::InvalidArgument)


296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
# File 'lib/nswtopo/map.rb', line 296

def move(name, before: nil, after: nil)
  name, target = [name, before || after].map do |name|
    Layer.sanitise name
  end.each do |name|
    raise OptionParser::InvalidArgument, "no such layer: #{name}" unless @layers.key? name
  end
  raise OptionParser::InvalidArgument, "layers must be different" if name == target
  insert = [name, @layers.delete(name)]
  @layers.each.with_object [] do |(name, layer), layers|
    layers << insert if before && name == target
    layers << [name, layer]
    layers << insert if after && name == target
  end.tap do |layers|
    @layers.replace layers.to_h
  end
  save
end

#neatline(mm: nil) ⇒ Object



169
170
171
# File 'lib/nswtopo/map.rb', line 169

def neatline(mm: nil)
  mm ? @neatline.buffer(mm).explode : @neatline
end

#render(*paths, worldfile: false, force: false, background: nil, **options) ⇒ Object



342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
# File 'lib/nswtopo/map.rb', line 342

def render(*paths, worldfile: false, force: false, background: nil, **options)
  @archive.delete "map.svg" if force
  Dir.mktmppath do |temp_dir|
    rasters = Hash.new do |rasters, opts|
      png_path = temp_dir / "raster.#{rasters.size}.png"
      pam_path = temp_dir / "raster.#{rasters.size}.png.aux.xml"
      rasterise png_path, background: background, **opts
      write_pam_file pam_path, **opts
      rasters[opts] = png_path
    end
    dithers = Hash.new do |dithers, opts|
      png_path = temp_dir / "dither.#{dithers.size}.png"
      pam_path = temp_dir / "dither.#{dithers.size}.png.aux.xml"
      FileUtils.cp rasters[opts], png_path
      dither png_path
      write_pam_file pam_path, **opts
      dithers[opts] = png_path
    end

    outputs = paths.map.with_index do |path, index|
      ext = path.extname.delete_prefix ?.
      name = path.basename(path.extname)
      out_path = temp_dir / "output.#{index}.#{ext}"
      send "render_#{ext}", out_path, name: name, background: background, **options do |dither: false, **opts|
        (dither ? dithers : rasters)[opts]
      end
      next out_path, path
    end

    safely "saving, please wait..." do
      outputs.each do |out_path, path|
        FileUtils.cp out_path, path
        log_success "created %s" % path
      rescue SystemCallError
        raise "couldn't save #{path}"
      end

      paths.select do |path|
        %w[.png .tif .jpg].include? path.extname
      end.group_by do |path|
        path.parent / path.basename(path.extname)
      end.keys.each do |base|
        write_world_file Pathname("#{base}.wld"), ppi: options.fetch(:ppi, Formats::PPI)
        Pathname("#{base}.prj").write "#{@projection}\n"
      end if worldfile
    end
  end
end

#saveObject



123
124
125
126
127
128
# File 'lib/nswtopo/map.rb', line 123

def save
  tap do
    write "map.json", @neatline.to_json
    write "map.yml", YAML.dump(centre: @centre, dimensions: @dimensions, scale: @scale, rotation: @rotation, layers: @layers)
  end
end

#teObject



177
178
179
# File 'lib/nswtopo/map.rb', line 177

def te
  [0, 0, *@dimensions]
end

#to_metres(mm) ⇒ Object



185
186
187
# File 'lib/nswtopo/map.rb', line 185

def to_metres(mm)
  mm * @scale / 1000.0
end

#to_mm(metres) ⇒ Object



181
182
183
# File 'lib/nswtopo/map.rb', line 181

def to_mm(metres)
  metres * 1000.0 / @scale
end

#write_pam_file(path, **opts) ⇒ Object



203
204
205
206
207
208
209
# File 'lib/nswtopo/map.rb', line 203

def write_pam_file(path, **opts)
  REXML::Document.new("", raw: %w[SRS], attribute_quote: :quote).add_element("PAMDataset").tap do |pam|
    pam.add_element("SRS", "dataAxisToSRSAxisMapping" => "1,2").add_text @projection.wkt2
    pam.add_element("GeoTransform").add_text geotransform(**opts).join(?,)
    path.write pam
  end
end

#write_world_file(path, **opts) ⇒ Object



194
195
196
197
198
199
200
201
# File 'lib/nswtopo/map.rb', line 194

def write_world_file(path, **opts)
  ulx, mm_per_px, _, uly, _, _ = geotransform(**opts)
  path.open("w") do |file|
    file.puts mm_per_px, 0, 0, -mm_per_px
    file.puts ulx + 0.5 * mm_per_px
    file.puts uly - 0.5 * mm_per_px
  end
end