Sha256: 4cd4bc4f9e08c60f88523daf32515c2ab0b3f15a94dc52b492c7e06caea87e54

Contents?: true

Size: 1.82 KB

Versions: 5

Compression:

Stored size: 1.82 KB

Contents

# Author::    Nicolas Pouillard  <ertai@lrde.epita.fr>.
# Copyright:: Copyright (c) 2004, 2005 TTK team. All rights reserved.
# License::   LGPL
# $Id: Weight.rb 567 2005-04-13 08:00:06Z polrop $


require 'delegate'

module TTK

  # FIXME: explain here how to write a new weight computation
  module Weights

    # FIXME: document me
    class Weight < DelegateClass(Float)

      attr_reader :min, :max

      def initialize ( aFloat, min=0, max=1 )
        if BASE.has_key? aFloat
          aFloat, min, max = BASE[aFloat]
        end
        aFloat = aFloat.to_f
        super(aFloat)
        @min, @max = min, max
        unless @min <= aFloat or aFloat <= @max
          raise ArgumentError, "#@min <= #{aFloat} <= #@max"
        end
      end

      BASE =
      {
        :START => [0, 0, 0],
        :PASS  => [1, 0, 1],
        :FAIL  => [0, 0, 1]
      }.freeze.each_value { |x| x.freeze }

      def start?
        [self, @max, @min].all? { |x| x.zero? }
      end

      def pass?
        ! zero? and to_f == @max
      end

      def fail?
        to_f != @max
      end

      def + ( rhs )
        rhs = self.class.new(rhs) unless rhs.is_a? Weight
        self.class.new(to_f + rhs.to_f, @min + rhs.min, @max + rhs.max)
      end

      def * ( rhs )
        f = rhs.to_f
        a, b, c = to_f * f, @min * f, @max * f
        b, c = c, b if f < 0
        self.class.new(a, b, c)
      end

      def normalize ( weight )
        diff = @max - @min
        if diff.zero?
          if @max.zero? and weight.zero?
            self.class.new(:PASS)
          else
            self.class.new(:FAIL)
          end
        else
          self.class.new((self - @min) / diff, 0, 1)
        end
      end

      alias :get :to_f

      def long_get
        "#{get}[#@min, #@max]"
      end

    end # class Weight

  end # module Weights

end # module TTK

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
ttk-0.1.576 lib/ttk/weights/Weight.rb
ttk-0.1.579 lib/ttk/weights/Weight.rb
ttk-0.2.0 lib/ttk/weights/Weight.rb
ttk-0.1.580 lib/ttk/weights/Weight.rb
ttk-0.2.1 lib/ttk/weights/Weight.rb