Class: Panomosity::Runner

Inherits:
Object
  • Object
show all
Includes:
Utils, XLSXWriter
Defined in:
lib/panomosity/runner.rb

Constant Summary collapse

AVAILABLE_COMMANDS =
%w[
  add_calibration_flag
  apply_calibration_values
  check_position_changes
  clean_control_points
  convert_equaled_image_parameters
  convert_horizontal_lines
  convert_translation_parameters
  create_calibration_report
  crop_centers
  diagnose
  export_control_point_csv
  export_panorama_attributes_to_csv
  fix_conversion_errors
  fix_unconnected_image_pairs
  generate_border_line_control_points
  get_columns_and_rows
  get_control_point_info
  get_neighborhood_info
  get_panorama_attributes
  import_control_point_csv
  merge_image_parameters
  nona_grid
  optimize
  prepare_for_pr0ntools
  remove_anchor_variables
  standardize_roll
]

Constants included from XLSXWriter

XLSXWriter::SEPERATE_CSV_COLUMNS

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from XLSXWriter

#csv_to_xlsx

Methods included from Utils

#calculate_average, #calculate_average_and_std, #remove_outliers

Constructor Details

#initialize(options) ⇒ Runner

Returns a new instance of Runner.



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/panomosity/runner.rb', line 42

def initialize(options)
  @options = options
  @input = options[:input]
  @output = options[:output]
  @csv = options[:csv]
  @compare = options[:compare]
  @report = options[:report]
  @input_file = File.new(@input, 'r').read rescue puts('You must have at least one argument')
  @output_file = File.new(@output, 'w') if @output
  @csv_file = File.new(@csv, 'r').read if @csv
  @compare_file = File.new(@compare, 'r').read if @compare
  @report_file = File.new(@report, 'r').read if @report
  @logger = Panomosity.logger

  if options[:verbose] || options[:verbosity] > 0
    @logger.level = Logger::DEBUG
  else
    @logger.level = Logger::INFO
  end
end

Instance Attribute Details

#loggerObject (readonly)

Returns the value of attribute logger.



11
12
13
# File 'lib/panomosity/runner.rb', line 11

def logger
  @logger
end

Instance Method Details

#add_calibration_flagObject



71
72
73
74
75
# File 'lib/panomosity/runner.rb', line 71

def add_calibration_flag
  logger.info 'adding panomosity calibration flag'
  @lines = @input_file.each_line.map { |line| line } + ["#panomosity calibration true\n"]
  save_file
end

#apply_calibration_valuesObject



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
# File 'lib/panomosity/runner.rb', line 77

def apply_calibration_values
  logger.info "applying calibration values from #{@report}"
  panorama = Panorama.new(@input_file, @options)
  optimizer = Optimizer.new(panorama)
  calibration_report = JSON.parse(@report_file)

  if calibration_report.fetch('position', nil)
    logger.info 'calibration_report.json included position, applying position values'
    optimizer.run_position_optimizer(xh_avg: calibration_report['position']['xh_avg'],
                                     yh_avg: calibration_report['position']['yh_avg'],
                                     xv_avg: calibration_report['position']['xv_avg'],
                                     yv_avg: calibration_report['position']['yv_avg'])
  end

  if calibration_report.fetch('roll', nil)
    logger.info 'calibration_report.json included roll, applying roll values'
    optimizer.run_roll_optimizer(apply_roll: calibration_report.fetch('roll'))
  end

  @lines = @input_file.each_line.map do |line|
    image = optimizer.images.find { |i| i.raw == line }
    if image
      image.to_s
    else
      next line
    end
  end.compact

  save_file
end

#check_position_changesObject



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
# File 'lib/panomosity/runner.rb', line 108

def check_position_changes
  logger.info 'checking position changes'
  original_images = Image.parse(@input_file)
  changed_images = Image.parse(@compare_file)
  threshold = 0.10
  images = original_images.zip(changed_images)
  changes_x = images.select do |original, changed|
    ratio_x = original.d / changed.d
    changed_x = (1 - ratio_x.abs).abs
    changed_x > threshold
  end
  changes_y = images.select do |original, changed|
    ratio_y = original.e / changed.e
    changed_y = (1 - ratio_y.abs).abs
    changed_y > threshold
  end

  @lines = @input_file.each_line.map do |line|
    variable = OptimisationVariable.parse_line(line)
    next line unless variable
    if variable.d && changes_x.find { |original, _| original.id.to_s == variable.d }
      logger.debug "Removing #{variable.to_s}"
    elsif variable.e && changes_y.find { |original, _| original.id.to_s == variable.e }
      logger.debug "Removing #{variable.to_s}"
    else
      next line
    end
  end

  save_file
end

#clean_control_pointsObject



140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/panomosity/runner.rb', line 140

def clean_control_points
  logger.info 'cleaning control points'
  # Since this is very exact, having many outliers in control points distances will cause errors
  panorama = Panorama.new(@input_file, @options)
  bad_control_points = panorama.clean_control_points

  logger.info "removing #{bad_control_points.count} control points"
  @lines = @input_file.each_line.map do |line|
    control_point = ControlPoint.parse_line(line)
    # skip this control point if we found it
    if control_point && bad_control_points.find { |bad_cp| bad_cp.raw == control_point.raw }
      next
    else
      next line
    end
  end.compact

  save_file
end

#convert_equaled_image_parametersObject



160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/panomosity/runner.rb', line 160

def convert_equaled_image_parameters
  logger.info 'converting equaled image parameters'
  images = Image.parse(@input_file)
  @lines = @input_file.each_line.map do |line|
    image = images.find { |i| i.raw == line }
    if image
      if @options[:remove_equal_signs]
        image.to_s(without_equal_signs: true)
      else
        image.to_s
      end
    else
      next line
    end
  end.compact

  save_file
end

#convert_horizontal_linesObject



179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/panomosity/runner.rb', line 179

def convert_horizontal_lines
  logger.info 'converting horizontal lines'
  @lines = @input_file.each_line.map do |line|
    cp = ControlPoint.parse_line(line)
    if cp && cp.vertical?
      cp.t = 2
      cp.to_s
    else
      next line
    end
  end.compact

  save_file
end

#convert_translation_parametersObject



194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/panomosity/runner.rb', line 194

def convert_translation_parameters
  logger.info 'converting translation parameters'
  images = Image.parse(@input_file)

  @lines = @input_file.each_line.map do |line|
    image = images.find { |i| i.raw == line }
    next if line[0] == 'v'
    next line unless image
    image.convert_position!
    if image.id == images.sort_by(&:id).last.id
      image.to_s +
        "\n" +
        "# Variable lines\n" +
        images.map { |i| i.id == 0 ? nil : "v d#{i.id} e#{i.id}\n" }.compact.join +
        "v\n" +
        "\n"
    else
      image.to_s
    end

  end.compact

  save_file
end

#create_calibration_reportObject



219
220
221
222
223
# File 'lib/panomosity/runner.rb', line 219

def create_calibration_report
  logger.info "creating #{@options[:report_type]} calibration report"
  panorama = Panorama.new(@input_file, @options)
  panorama.create_calibration_report
end

#crop_centersObject

Uses image magick to crop centers



226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
# File 'lib/panomosity/runner.rb', line 226

def crop_centers
  logger.info 'cropping centers'
  scale_factor = @csv_file.split(/\n/).first.split(',').last.to_f
  percent = (scale_factor*100).round
  logger.debug "cropping to #{percent}%"
  unless @options[:without_cropping]
    images = Image.parse(@input_file)

    crop_center_commands = images.map do |image|
      width_offset = (image.w.to_f * (1 - scale_factor) / 2).round
      height_offset = (image.h.to_f * (1 - scale_factor) / 2).round
      logger.debug "cropping #{image.name}"

      "convert #{image.name} -crop '#{percent}%x#{percent}%+#{width_offset}+#{height_offset}' #{image.name}"
    end

    crop_centers_command = crop_center_commands.join("\n")
    parallel_command = "cat <<'EOF' | parallel \n%s\nEOF"
    crop_centers_command = parallel_command % crop_centers_command
    `#{crop_centers_command}`
  end

  # Since all images have been cropped, we need to change d,e params to move images based on how much was cropped
  # Re-run commands that have been run at this point
  logger.info 'rerunning commands'
  @new_input = 'project_converted_translation_cropped.pto'
  `match-n-shift --input #{@csv} -o project_cropped.pto`
  `pto_var --opt=TrX,TrY project_cropped.pto -o project_pto_var_cropped.pto`
  runner = Runner.new(@options.merge(input: 'project_pto_var_cropped.pto', output: @new_input))
  runner.run('convert_translation_parameters')
  `pano_modify -p 0 --fov=AUTO -o #{@new_input} #{@new_input}`

  logger.info "Read new #{@new_input}"
  # Read new input pto file
  @input_file = File.new(@new_input, 'r').read
  images = Image.parse(@input_file)
  ds = images.map(&:d).uniq.sort
  es = images.map(&:e).uniq.sort

  d_diffs = []
  ds.each_with_index do |_, i|
    next if i == 0
    d_diffs.push((ds[i] - ds[i-1]).abs * (1-scale_factor))
  end

  e_diffs = []
  es.each_with_index do |_, i|
    next if i == 0
    e_diffs.push((es[i] - es[i-1]).abs * (1-scale_factor))
  end

  d_map = Hash[ds.map.with_index { |d, i| i == 0 ? [d, d] : [d, d - d_diffs[0..(i-1)].reduce(:+)] }]
  e_map = Hash[es.map.with_index { |e, i|  i == 0 ? [e, e] : [e, e - e_diffs[0..(i-1)].reduce(:+)] }]

  d_min, d_max = d_map.values.minmax
  e_min, e_max = e_map.values.minmax
  d_offset = ((d_max - d_min) / 2.0) + d_min
  e_offset = ((e_max - e_min) / 2.0) + e_min

  logger.info 'saving new d,e values'
  @lines = @input_file.each_line.map do |line|
    image = images.find { |i| i.raw == line }
    if image
      image.d = (d_map[image.d] - d_offset).round(8).to_s
      image.e = (e_map[image.e] - e_offset).round(8).to_s
      image.to_s
    else
      next line
    end
  end.compact

  save_file
end

#diagnoseObject



300
301
302
303
304
# File 'lib/panomosity/runner.rb', line 300

def diagnose
  logger.info 'diagnosing errors'
  panorama = Panorama.new(@input_file, @options)
  panorama.diagnose
end

#export_control_point_csvObject



306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
# File 'lib/panomosity/runner.rb', line 306

def export_control_point_csv
  logger.info 'exporting control point csv'
  panorama = Panorama.new(@input_file, @options)
  panorama.calculate_neighborhoods

  filename = 'control_points.csv'
  headers = %w[image_1_name image_2_name image_1_id image_2_id type width height d1 e1 d2 e2 x1 y1 x2 y2 rx ry r]
  CSV.open(filename, 'w+') do |csv|
    csv << headers
    panorama.control_points.each do |cp|
      pair = Pair.all.find { |p| p.control_points.include?(cp) }
      csv << [cp.i1.name, cp.i2.name, cp.i1.id, cp.i2.id, pair.type, cp.i1.w, cp.i1.h, cp.i1.d, cp.i1.e,
              cp.i2.d, cp.i2.e, cp.x1, cp.y1, cp.x2, cp.y2, cp.px, cp.py, cp.pdist]
    end
  end

  logger.info 'Done. Check for control_points.csv'
end

#export_panorama_attributes_to_csvObject



503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
# File 'lib/panomosity/runner.rb', line 503

def export_panorama_attributes_to_csv
  panorama = Panorama.new(@input_file, @options)
  panorama.calculate_neighborhoods

  logger.info "Making #{Dir.pwd}/#{@input}_attributes Directory"

  dir = "#{Dir.pwd}/#{@input}_attributes"
  Dir.mkdir(dir) unless File.exists?(dir)

  logger.info "Done. Moving into #{dir} Directory"

  Dir.chdir "#{@input}_attributes"

  logger.info "Making control_points.csv"

  filename = 'control_points.csv'
  headers = %w[image_1_name image_2_name image_1_id image_2_id type width height d1 e1 d2 e2 x1 y1 x2 y2 rx ry r]
  CSV.open(filename, 'w+') do |csv|
    csv << headers
    panorama.control_points.each do |cp|
      pair = Pair.all.find { |p| p.control_points.include?(cp) }
      csv << [cp.i1.name, cp.i2.name, cp.i1.id, cp.i2.id, pair.type, cp.i1.w, cp.i1.h, cp.i1.d, cp.i1.e,
              cp.i2.d, cp.i2.e, cp.x1, cp.y1, cp.x2, cp.y2, cp.px, cp.py, cp.pdist]
    end
  end

  logger.info "Done. Check for #{filename}"

  attributes = panorama.attributes

  logger.info "Making cp_pairs.csv"

  filename = 'cp_pairs.csv'
  headers = attributes[:pairs].first.keys
  CSV.open(filename,"w") do |csv|
    csv << headers
    attributes[:pairs].each do |pair|
      csv << pair.values
    end
  end

  logger.info "Done. Check for #{filename}"

  logger.info "Making neighborhood_pairs.csv"

  filename = 'neighborhood_pairs.csv'
  headers = ['data_type', attributes[:similar_neighborhoods].first.keys].flatten
  CSV.open(filename,'w') do |csv|
    csv << headers
    attributes[:similar_neighborhoods].each do |neighborhood|
      csv << ['similar_neighborhoods', neighborhood.values].flatten(1)
    end
    attributes[:neighborhoods_by_similar_neighborhood].each do |neighborhood|
      csv << ['neighborhoods_by_similar_neighborhood', neighborhood.values].flatten(1)
    end
  end

  logger.info "Done. Check for #{filename}"

  csv_to_xlsx(['control_points.csv', 'cp_pairs.csv', 'neighborhood_pairs.csv'], 'attributes')

  Dir.chdir '..'
end

#fix_conversion_errorsObject



325
326
327
328
329
330
331
332
333
334
335
336
337
# File 'lib/panomosity/runner.rb', line 325

def fix_conversion_errors
  logger.info 'fixing conversion errors'
  @lines = @input_file.each_line.map do |line|
    cp = ControlPoint.parse_line(line)
    if cp && cp.horizontal?
      cp.to_s
    else
      next line
    end
  end.compact

  save_file
end

#fix_unconnected_image_pairsObject



339
340
341
342
343
344
# File 'lib/panomosity/runner.rb', line 339

def fix_unconnected_image_pairs
  logger.info 'fixing unconnected image pairs'
  panorama = Panorama.new(@input_file, @options)
  @lines = panorama.fix_unconnected_image_pairs
  save_file
end

#generate_border_line_control_pointsObject



346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
# File 'lib/panomosity/runner.rb', line 346

def generate_border_line_control_points
  logger.info 'generating border line control points'
  images = Image.parse(@input_file)
  line_control_points = ControlPoint.parse(@input_file, cp_type: :line)

  # Set vertical and horizontal control points for each image
  images.each do |image|
    vertical_control_points = line_control_points.select { |cp| cp[:n] == image[:id] && cp[:N] == image[:id] && cp[:t] == 1 }
    horizontal_control_points = line_control_points.select { |cp| cp[:n] == image[:id] && cp[:N] == image[:id] && cp[:t] == 2 }
    image[:vertical_control_points] = vertical_control_points
    image[:horizontal_control_points] = horizontal_control_points
  end

  # Iterate through the edges to create vertical control points across overlapping images
  logger.info 'finding common vertical control points'
  vertical_edges, horizontal_edges = images.map { |image| image[:d] }.minmax, images.map { |image| image[:e] }.minmax
  vertical_control_points = []
  vertical_edges.each do |edge|
    edge_images = images.select { |image| image[:d] == edge }.sort_by { |image| image[:e] }
    edge_images.each_with_index do |image, index|
      next if index == edge_images.length - 1
      next_image = edge_images[index+1]

      control_points = image[:vertical_control_points].map do |control_point|
        average_x = (control_point[:x] + control_point[:X]) / 2.0
        next_found_control_point = next_image[:vertical_control_points].find do |next_control_point|
          next_average_x = (next_control_point[:x] + next_control_point[:X]) / 2.0
          next_average_x.between?(average_x * 0.98, average_x * 1.02)
        end
        [control_point, next_found_control_point] if next_found_control_point
      end.compact

      # Special logic for anchor image
      if image[:id] == 0
        control_points = next_image[:vertical_control_points].map do |next_control_point|
          next_average_x = (next_control_point[:x] + next_control_point[:X]) / 2.0
          [{n: 0, x: next_average_x, y: (image[:h]/2.0).round }, next_control_point]
        end
      elsif next_image[:id] == 0
        control_points = image[:vertical_control_points].map do |next_control_point|
          next_average_x = (next_control_point[:x] + next_control_point[:X]) / 2.0
          [{n: 0, x: next_average_x, y: (image[:h]/2.0).round }, next_control_point]
        end
      end

      control_points.each do |current_control_point, next_control_point|
        vertical_control_points << ControlPoint.new({
                                                      n: current_control_point[:n],
                                                      N: next_control_point[:n],
                                                      x: current_control_point[:x],
                                                      y: current_control_point[:y],
                                                      X: next_control_point[:X],
                                                      Y: next_control_point[:Y],
                                                      t: 1
                                                    })
      end
    end
  end

  # Iterate through the edges to create horizontal control points across overlapping images
  logger.info 'finding common horizontal control points'
  horizontal_control_points = []
  horizontal_edges.each do |edge|
    edge_images = images.select { |image| image[:e] == edge }.sort_by { |image| image[:d] }
    edge_images.each_with_index do |image, index|
      next if index == edge_images.length - 1
      next_image = edge_images[index+1]

      control_points = image[:horizontal_control_points].map do |control_point|
        average_y = (control_point[:y] + control_point[:Y]) / 2.0
        next_found_control_point = next_image[:horizontal_control_points].find do |next_control_point|
          next_average_y = (next_control_point[:y] + next_control_point[:Y]) / 2.0
          next_average_y.between?(average_y * 0.98, average_y * 1.02)
        end
        [control_point, next_found_control_point] if next_found_control_point
      end.compact

      # Special logic for anchor image
      if image[:id] == 0
        control_points = next_image[:horizontal_control_points].map do |next_control_point|
          next_average_y = (next_control_point[:y] + next_control_point[:Y]) / 2.0
          [{n: 0, x: (image[:w]/2.0).round, y: next_average_y }, next_control_point]
        end
      end

      control_points.each do |current_control_point, next_control_point|
        horizontal_control_points << ControlPoint.new({
                                                        n: current_control_point[:n],
                                                        N: next_control_point[:n],
                                                        x: current_control_point[:x],
                                                        y: current_control_point[:y],
                                                        X: next_control_point[:X],
                                                        Y: next_control_point[:Y],
                                                        t: 2
                                                      })
      end
    end
  end

  logger.info "writing #{vertical_control_points.count} vertical control points"
  logger.info "writing #{horizontal_control_points.count} horizontal control points"
  control_point_lines_started = false
  @lines = @input_file.each_line.map do |line|
    cp = ControlPoint.parse_line(line)
    if cp.nil?
      # Control point lines ended
      if control_point_lines_started
        control_point_lines_started = false
        (vertical_control_points + horizontal_control_points).map do |control_point|
          logger.debug "image #{control_point[:n]} <> #{control_point[:N]} #{control_point[:t] == 1 ? 'vertical' : 'horizontal'} control point"
          control_point.to_s
        end + [line]
      else
        next line
      end
    else
      control_point_lines_started = true
      next line
    end
  end.compact.flatten

  save_file
end

#get_columns_and_rowsObject



470
471
472
473
474
475
# File 'lib/panomosity/runner.rb', line 470

def get_columns_and_rows
  images = Image.parse(@input_file)
  columns = images.map(&:column).sort.last
  rows = images.map(&:row).sort.last
  puts "#{columns},#{rows}"
end

#get_control_point_infoObject



477
478
479
480
481
482
483
484
485
486
487
# File 'lib/panomosity/runner.rb', line 477

def get_control_point_info
  logger.info 'getting detailed control point info'
  images = Image.parse(@input_file)
  panorama_variable = PanoramaVariable.parse(@input_file).first
  ControlPoint.parse(@input_file)
  control_points = ControlPoint.calculate_distances(images, panorama_variable)

  control_points.each do |cp|
    logger.debug cp.detailed_info
  end
end

#get_neighborhood_infoObject



489
490
491
492
493
# File 'lib/panomosity/runner.rb', line 489

def get_neighborhood_info
  logger.info 'getting detailed neighborhood info'
  panorama = Panorama.new(@input_file, @options)
  panorama.get_neighborhood_info
end

#get_panorama_attributesObject



495
496
497
498
499
500
501
# File 'lib/panomosity/runner.rb', line 495

def get_panorama_attributes
  # for printing out the JSON
  logger.level = Logger::UNKNOWN
  logger.info 'getting panorama attributes'
  panorama = Panorama.new(@input_file, @options)
  puts panorama.attributes.to_json
end

#import_control_point_csvObject



567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
# File 'lib/panomosity/runner.rb', line 567

def import_control_point_csv
  logger.info 'importing control point csv'
  panorama = Panorama.new(@input_file, @options)

  filename = @csv || 'control_points.csv'
  csv = CSV.read(filename)
  headers = csv.first
  csv = csv[1..(csv.length - 1)]
  data = csv.map { |s| Hash[headers.zip(s)] }

  @lines = @input_file.each_line.map do |line|
    cp = panorama.control_points.find { |c| c.raw == line }
    if cp
      kept_cp = data.find do |d|
        cp.i1.id == d['image_1_id'].to_i && cp.i2.id == d['image_2_id'].to_i &&
        cp.x1.round(4) == d['x1'].to_f.round(4) && cp.x2.round(4) == d['x2'].to_f.round(4) &&
        cp.y1.round(4) == d['y1'].to_f.round(4) && cp.y2.round(4) == d['y2'].to_f.round(4)
      end
      cp.to_s if kept_cp
    else
      next line
    end
  end.compact

  save_file
end

#merge_image_parametersObject



594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
# File 'lib/panomosity/runner.rb', line 594

def merge_image_parameters
  logger.info 'merging image parameters'
  control_points = ControlPoint.parse(@compare_file)
  images = Image.parse(@compare_file)

  # sort images
  logger.info 'sorting images in case they get out of order'
  lexically_sorted_images = images
  numerically_sorted_images = images.sort_by { |image| [image.column, image.row] }
  image_map = {}
  lexically_sorted_images.each_with_index do |image_l, i|
    image_map[image_l.name] = numerically_sorted_images[i]
    image_map[numerically_sorted_images[i].id.to_i] = image_l.id.to_i
  end

  # fix control points
  control_points.each do |control_point|
    control_point[:n] = image_map[control_point[:n].to_i]
    control_point[:N] = image_map[control_point[:N].to_i]
  end

  v_lines_started = false
  @lines = @input_file.each_line.map do |line|
    if line[0] == 'v'
      v_lines_started = true
      next line
    elsif v_lines_started
      v_lines_started = false
      control_points.map(&:to_s).join
    else
      next line
    end
  end.compact

  save_file
end

#nona_gridObject



631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
# File 'lib/panomosity/runner.rb', line 631

def nona_grid
  logger.info 'running nona and generated column and row based stitch sections'
  images = Image.parse(@input_file)
  res = @options[:res] || 'low'
  columns = images.map(&:column).uniq.sort
  commands = columns.map do |column|
    @output = "project_nona_c#{column}.pto"
    @output_file = File.new(@output, 'w')
    logger.debug "creating file #{@output}"
    @lines = @input_file.each_line.map do |line|
      image = images.find { |i| i.raw == line }
      if image
        image.to_s if image.column == column
      else
        next line
      end
    end.compact
    save_file
    logger.debug "running nona #{@output}"
    output = "nona --save-intermediate-images --intermediate-suffix=intermediate -v -m TIFF_m --seam=blend #{@output} -o #{res}_res_stitch_section_c#{column.to_s.rjust(5, '0')}_"
    # output = "nona-mask #@output -m TIFF_m -o #{res}_res_stitch_section_c#{column.to_s.rjust(5, '0')}_"
    logger.debug output
    output
  end

  logger.debug 'parallelizing'
  if @options[:darwin]
    parallel_command = "cat <<'EOF' |  parallel \n#{commands.join("\n")}\nEOF"
  else
    parallel_command = "cat <<'EOF' |  parallel -j $(fgrep -c processor /proc/cpuinfo) \n#{commands.join("\n")}\nEOF"
  end

  `#{parallel_command}`
end

#optimizeObject



666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
# File 'lib/panomosity/runner.rb', line 666

def optimize
  logger.info 'optimizing'
  panorama = Panorama.new(@input_file, @options)
  optimizer = Optimizer.new(panorama)
  optimizer.run

  @lines = @input_file.each_line.map do |line|
    image = optimizer.images.find { |i| i.raw == line }
    if image
      image.to_s
    else
      next line
    end
  end.compact

  save_file
end

#prepare_for_pr0ntoolsObject



684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
# File 'lib/panomosity/runner.rb', line 684

def prepare_for_pr0ntools
  logger.info 'preparing for pr0ntools'

  images = Image.parse(@input_file)
  # ds --> X (cols)
  # es --> Y (rows)
  ds = images.map(&:d).uniq.sort
  es = images.map(&:e).uniq.sort

  # split ds and es into groups within two pixels of each other,
  # required because d/e can vary a few pixels based on system precision
  # each group of d/e represents an acceptable pixel range
  # for images to be considered part of a col/row
  d_groups = ds.map { |d| ds.select { |n| n.between?(d-2, d+2) }.sort }.uniq
  e_groups = es.map { |e| es.select { |n| n.between?(e-2, e+2) }.sort }.uniq

  fov = images.map(&:v).uniq.find { |v| v != 0.0 }
  images.each do |i|
    column = d_groups.reverse.index { |group| group.include?(i.d) }
    row = e_groups.reverse.index { |group| group.include?(i.e) }
    i[:original_n] = i.n
    i.n = "c#{column}_r#{row}.jpg"
    i.v = fov
  end
  images = images.sort_by { |image| [image.column, image.row] }

  index = -1
  @lines = @input_file.each_line.map do |line|
    image = images.find { |i| i.raw == line }
    next line unless image
    index += 1
    images[index].to_s
  end.compact

  dir = '/pr0ntools/'
  logger.info "creating #{dir}"
  new_dir = Pathname.new(@output).dirname.to_s + dir
  FileUtils.mkdir_p(new_dir)

  logger.info 'renaming files to format cX_rY.jpg'
  images.each do |image|
    original_name = image[:original_n]
    new_name = new_dir + image.n
    FileUtils.cp(original_name, new_name)
    logger.debug "copied #{original_name} to #{new_name}"
  end

  logger.info 'creating scan.json'
  image_first_col = images.find { |image| image.n == 'c0_r0.jpg' }
  image_second_col = images.find { |image| image.n == 'c1_r0.jpg' }
  overlap = ((image_second_col.d - image_first_col.d).abs / image_first_col.w.to_f).round(4)
  File.open(new_dir+'scan.json', 'w') { |f| f.puts %Q({"overlap":#{overlap}}) }

  save_file(dir: dir)
end

#remove_anchor_variablesObject



740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
# File 'lib/panomosity/runner.rb', line 740

def remove_anchor_variables
  logger.info 'removing anchor variables'
  variables = OptimisationVariable.parse(@input_file)

  @lines = @input_file.each_line.map do |line|
    variable = variables.find { |v| v.raw == line }
    if variable && (variable.d == 0 || variable.e == 0)
      next
    else
      next line
    end
  end.compact

  save_file
end

#run(command) ⇒ Object



63
64
65
66
67
68
69
# File 'lib/panomosity/runner.rb', line 63

def run(command)
  if AVAILABLE_COMMANDS.include?(command)
    send(command)
  else
    logger.info "commands include:\n#{AVAILABLE_COMMANDS.join("\n")}"
  end
end

#standardize_rollObject



756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
# File 'lib/panomosity/runner.rb', line 756

def standardize_roll
  logger.info 'standardizing roll'
  images = Image.parse(@input_file)
  panorama_variable = PanoramaVariable.parse(@input_file).first
  ControlPoint.parse(@input_file)
  control_points = ControlPoint.calculate_distances(images, panorama_variable)
  max_count = (images.count * 0.5).ceil - 1
  pairs = control_points.group_by { |cp| [cp.n1, cp.n2] }.sort_by { |_, members| -members.count }[0..max_count]
  image_ids = pairs.map { |image_ids, _| image_ids }.flatten.uniq
  rolls = images.select { |image| image_ids.include?(image.id) }.map(&:r)

  average_roll, roll_std = *calculate_average_and_std(name: :roll, values: rolls, logger: logger)
  new_rolls = rolls.select { |r| (r - average_roll).abs < roll_std }
  logger.info "removed #{rolls.count - new_rolls.count} outliers"
  average_roll, _ = *calculate_average_and_std(name: :roll, values: new_rolls, logger: logger)
  logger.info "converting all rolls to #{average_roll}"

  @lines = @input_file.each_line.map do |line|
    image = images.find { |i| i.raw == line }
    if image
      image.r = average_roll
      image.to_s
    else
      next line
    end
  end.compact

  save_file
end