From 1f789133d961c29d3babfaf69cdde3d675288537 Mon Sep 17 00:00:00 2001 From: Christoph Helma Date: Sat, 24 Aug 2019 14:44:52 +0200 Subject: initial refactored version for mutagenicity paper --- lib/array.rb | 87 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 lib/array.rb (limited to 'lib/array.rb') diff --git a/lib/array.rb b/lib/array.rb new file mode 100644 index 0000000..55186bd --- /dev/null +++ b/lib/array.rb @@ -0,0 +1,87 @@ +class Array + + # Sum the size of single arrays in an array of arrays + # @param [Array] Array of arrays + # @return [Integer] Sum of size of array elements + def sum_size + self.inject(0) { |s,a| + if a.respond_to?('size') + s+=a.size + else + internal_server_error "No size available: #{a.inspect}" + end + } + end + + # Check if the array has just one unique value. + # @param [Array] Array to test. + # @return [TrueClass,FalseClass] + def zero_variance? + return self.uniq.size == 1 + end + + # Get the median of an array + # @return [Numeric] + def median + sorted = self.sort + len = sorted.length + (sorted[(len - 1) / 2] + sorted[len / 2]) / 2.0 + end + + # Get the mean of an array + # @return [Numeric] + def mean + self.compact.inject{ |sum, el| sum + el }.to_f / self.compact.size + end + + # Get the variance of an array + # @return [Numeric] + def sample_variance + m = self.mean + sum = self.compact.inject(0){|accum, i| accum +(i-m)**2 } + sum/(self.compact.length - 1).to_f + end + + # Get the standard deviation of an array + # @return [Numeric] + def standard_deviation + Math.sqrt(self.sample_variance) + end + + # Calculate dot product + # @param [Array] + # @return [Numeric] + def dot_product(a) + products = self.zip(a).map{|a, b| a * b} + products.inject(0) {|s,p| s + p} + end + + # Calculate magnitude + # @return [Numeric] + def magnitude + squares = self.map{|x| x ** 2} + Math.sqrt(squares.inject(0) {|s, c| s + c}) + end + + # Convert array values for R + # @return [Array] + def for_R + if self.first.is_a?(String) + #"\"#{self.collect{|v| v.sub('[','').sub(']','')}.join(" ")}\"" # quote and remove square brackets + "NA" + else + self.median + end + end + + # Collect array with index + # in analogy to each_with_index + def collect_with_index + result = [] + self.each_with_index do |elt, idx| + result << yield(elt, idx) + end + result + end +end + -- cgit v1.2.3