Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Convertor
- def initialize(input_filename, force_overwrite)
- @input_filename = input_filename
- @force_overwrite = force_overwrite
- @input_data = []
- end
- def convert!
- puts "Processing file #{@input_filename}"
- read_in_data
- split_comments!
- parse_header_attributes
- convert_from_string!
- strip_invalid!
- convert_fluxes_to_magnitudes!
- center_mag_on_zero!
- save!
- puts "Finished processing file #{@input_filename}"
- end
- private
- def read_in_data
- File.new(@input_filename, "r").each { |line| @input_data << line }
- #file closes automatically because it's opened in this method
- raise NoDataError if @input_data.empty?
- end
- def split_comments!
- @comments, @input_data = @input_data.partition { |line| line =~ /^#/ }
- end
- def convert_from_string!
- @input_data.map! { |line| line.split(" ").map(&:to_f)[0..1] }
- end
- def strip_invalid!
- @input_data.delete_if { |record| record[1] == 0.0 }
- end
- def convert_fluxes_to_magnitudes!
- @input_data.each { |record| record[1] = -2.5 * Math.log10(record[1]) }
- end
- def average_mag
- @input_data.map { |record| record[1] }.inject(:+).to_f / @input_data.size
- end
- def center_mag_on_zero!
- average = average_mag
- @input_data.each { |record| record[1] -= average }
- end
- def output_filename
- # Determine the output filename from header
- "kic#{@attributes[:kic_number]}_#{@attributes[:season]}_#{@input_filename.split("_")[1]}.txt"
- end
- def parse_header_attributes
- @attributes = @comments.select { |line| line.include? ":" }.map { |line| line.gsub("# ", "").split ":" }.to_hash
- end
- def save!
- raise FileExistsError if File.exist?(output_filename) && !@force_overwrite
- output_file = File.new output_filename, "a+"
- output_file.truncate(0) if @force_overwrite
- @input_data.each { |record| output_file << "#{record.join("\t")}\n" }
- end
- end
- class Array
- def to_hash
- self.inject({}) { |hash_version, element| hash_version[element[0].downcase.gsub(" ", "_").to_sym] = element[1].gsub(" ", "").strip; hash_version }
- end
- end
- class FileExistsError < StandardError; end
- class NoDataError < StandardError; end
- Kernel.abort "Please pass the input filename as an argument! Use -f to force overwrite." if ARGV.size < 1 #aborts the execution if no filename is provided as an argument with the program call
- force_overwrite = false
- if ARGV.first == "-f"
- force_overwrite = true
- ARGV.delete_at 0
- end
- ARGV.each do |filename|
- begin
- Convertor.new(filename, force_overwrite).convert!
- rescue FileExistsError
- puts "Your output file (#{filename}) already exists, please remove it first (or something)."
- end
- end
Add Comment
Please, Sign In to add comment