[Tioga-users] Tioga and NArray

David MacMahon davidm at astro.berkeley.edu
Mon Apr 28 14:02:46 EDT 2008


Here is a short "monkey-patch" to make is possible to convert Dvector  
from/to NArray...

module Dobjects
   class Dvector
     # Create a Dvector from an NArray.
     def self.from_na(na)
       _load([1, na.length, na.to_s].pack('CIa*'))
     end

     # Create an NArray with the same length and contents as +self+.
     def to_na
       ::NArray.to_na(_dump(nil)[5..-1], ::NArray::DFLOAT)
     end
   end # Dvector
end # Dobjects

Here is an example (assuming the above is in "dobjects_ext.rb")...

$ irb -r Dobjects/Dvector -r narray -r dobjects_ext.rb
irb(main):001:0> Dobjects::Dvector[1,2,3,4].to_na
=> NArray.float(4):
[ 1.0, 2.0, 3.0, 4.0 ]
irb(main):002:0> Dobjects::Dvector.from_na(NArray.dfloat(4).indgen!)
=> 0 1 2 3

Here is the (not unexpected) behavior if NArray is not loaded...

$ irb -r Dobjects/Dvector -r dobjects_ext.rb
irb(main):001:0> Dobjects::Dvector[1,2,3,4].to_na
NameError: uninitialized constant NArray
         from ./dobjects_ext.rb:9:in `to_na'
         from (irb):1

  I'm working on Dtable next...

Dave



More information about the Tioga-users mailing list