SciRuby / daru

Data Analysis in RUby
BSD 2-Clause "Simplified" License
1.03k stars 139 forks source link

Vector#set doesn't work for Category vectors #390

Open zverok opened 6 years ago

zverok commented 6 years ago
v = Daru::Vector.new([1,2,3])
vc = v.to_category
vc.send(:set, 5, 6)
# NoMethodError: undefined method `<<' for nil:NilClass

I believe the reason is category vector, while imitating being the same vector, cleans up @data variable. Probably it is not the only broken method for category vectors.

Showcased by https://github.com/SciRuby/daru/pull/388

@lokeshh WDYT?

lokeshh commented 6 years ago

@zverok Yes, :set method is missing for category vector. We have to fix this.

rohitner commented 6 years ago

@zverok @lokeshh I added these lines of code. It showed some error but did the work. The problem is that the @cat_hash is not getting updated and returns nil in the cat_to_int method.

def set indexes, val
     @index = @index.add(indexes)
     @cat_hash.store(val,[indexes])
     @array << indexes
     modify_category_at indexes, val
end
irb(main):002:0> v = Daru::Vector.new([1,2,3])
=> #<Daru::Vector(3)>
   0   1
   1   2
   2   3
irb(main):003:0> vc = v.to_category
=> #<Daru::Vector(3):category>
   0   1
   1   2
   2   3
irb(main):004:0> vc.send(:set, 5, 6)
TypeError: no implicit conversion from nil to integer
    from /home/rohitner/.rbenv/versions/2.4.2/lib/ruby/gems/2.4.0/gems/daru-0.2.0/lib/daru/category.rb:948:in `[]'
    from /home/rohitner/.rbenv/versions/2.4.2/lib/ruby/gems/2.4.0/gems/daru-0.2.0/lib/daru/category.rb:948:in `cat_from_int'
    from /home/rohitner/.rbenv/versions/2.4.2/lib/ruby/gems/2.4.0/gems/daru-0.2.0/lib/daru/category.rb:777:in `category_from_position'
    from /home/rohitner/.rbenv/versions/2.4.2/lib/ruby/gems/2.4.0/gems/daru-0.2.0/lib/daru/category.rb:919:in `modify_category_at'
    from /home/rohitner/.rbenv/versions/2.4.2/lib/ruby/gems/2.4.0/gems/daru-0.2.0/lib/daru/category.rb:930:in `set'
    from (irb):4
    from /home/rohitner/.rbenv/versions/2.4.2/bin/irb:11:in `<main>'
irb(main):005:0> vc[5]=6
NoMethodError: undefined method `delete' for nil:NilClass
    from /home/rohitner/.rbenv/versions/2.4.2/lib/ruby/gems/2.4.0/gems/daru-0.2.0/lib/daru/category.rb:921:in `modify_category_at'
    from /home/rohitner/.rbenv/versions/2.4.2/lib/ruby/gems/2.4.0/gems/daru-0.2.0/lib/daru/category.rb:249:in `[]='
    from (irb):5
    from /home/rohitner/.rbenv/versions/2.4.2/bin/irb:11:in `<main>'
irb(main):006:0> vc
=> #<Daru::Vector(4):category>
   0   1
   1   2
   2   3
   5   6
rohitner commented 6 years ago

ping! @zverok @lokeshh @athityakumar

lokeshh commented 6 years ago

@rohitner When you do vc.send(:set, 5, 6) you setting a new category 6 in index 5. Because 6 is a new category you need to first call #add_category and then modify @cat_hash and @array accordingly.

lokeshh commented 6 years ago

@rohitner It would be better if you could create a PR and we discuss it there.