next up previous contents index
Next: Bibliography Up: Ruby-Helix Previous: Script References.


Method References.

In this chapter, methods for each class are explained. Convention in this section is as follows.

If a method start from capital letter, such as NArray.byte, this means that it is a constructive method. If a method start from lower letter, such as narray.dim or self.dim, these are class methods, so please substitute the first word to your own instance object.

NArray class methods.

NArray initialization methods.

NArray uses following data types (Table 5.1.1). All above method initialize with 0 or nil. Note that arguemnt(s) can not be array. For example, you can not use NArray.sfloat([1,2,3]) to make an array whose size is [1,2,3].

Table 5.1: NArray data types
method function, size, ...) create new NArray. initialize with 0.
NArray.byte(size,...) 1 byte unsigned integer
NArray.sint(size,...) 2 byte signed integer,...) 4 byte signed integer
NArray.sfloat(size,...) single precision float
NArray.float(size,...) double precision float
NArray.scomplex(size,...) single precision complex
NArray.complex(size,...) double precision complex
NArray.object(size,...) Ruby object

Conversion methods.

convert to NArray
      NArray[1,5,10.0]  \#=>  NArray.float(3):[1.0, 5.0, 10.0]
      NArray[1..10]     \#=>[1,2,3,4,5,6,7,8,9,10]

NArray information

The dimension and index sizes of the instance array can be retrieved by the following methods

Slicing the array

The power of NArray is in its flexible slicing. You may play with various ways of indeces to extract various arrays from the original array.

Components of the index can be one of the following: Integer, Range, Array, true.

The index order is the FORTRAN type.

p a[ 3 ]
--> [ 0.0, 1.0, 2.0 ]
(Here, 3 gives a byte NArray) (This is also done by a[ ( 3).where ])

A two-or-more-dimensional array object with only one argument in `[ ]', is treated as a flat one-dimensional array. e.g.: a[3] is same as a[0,1] if a is 3x3 array.

self.slice(...) Same as self[...] but keeps the rank of original array by not elimiting dimensions whose length became equal to 1 (which self[] does). This is not the case with the one-dimensional indexing and masking (same as []).

Replacing Elements

Same rule as slicing Filling values

Special cases:

Filling values

Arithmetic operators

Arithmetic operations are performed element by element in NArray. Some operators are introduced by Kikkawa, such as +=, -=, *=, /=. A new useful operator is ternary. By using this methods, you do not need to use if operation. For example, the methods can be used as follows:
a = NArray.sfloat(5,5).randomn
b = NArray.sfloat(5,5).randomn
c = (a > b).ternary(a,b)

This program returns the bigger value either in a or b. For other operators, see Table 5.2.

Table 5.2: NArray arithmetic operators
operator destructive operator
self + other self += other, self.add! other
self - other self -= other, self.sbt! other
self * other self *= other, self.mul! other
self / other self /= other, self.div! other
self % other self.mod! other
self ** other Note: self is upcasted according to other. For example NArray.sfloat ** 0.5 is upcasted to float.

Bitwise operators

These operators works only for integers. See Table 5.3

Table 5.3: NArray bitwise operators
self & other AND
self | other OR
self ^ other XOR


When the following comparisons are used, it is interpreted as element-wise comparison and results in BYTE-type NArray. Note that the returned value is not boolean (true or false) as usual comparisons of Ruby. See Table 5.4.

Table 5.4: Comparison operators.
self.eq other 4.1 equal other not equal other, self > other greater than other, self >= other greater or equal other, self < other less than
self.le other, self <= other less or equal
self.and other element-wise condition.
self.or other element-wise OR
self.xor other element-wise XOR
self.not other element-wise NOT
self.all? true if all the elements are true.
self.any? true if any element is true.
self.none? true if none of the element is true.
self.where Return NArray of indices where elements are true.
self.where2 Return Array including two NArrays of indices,
  where elements are true and false, respectively.
self.max_pos returns maximum position as an array.
  Depending on the dimensions, the index can be x, (x,y), or (x,y,z).
self.max_pos_cubic Similar to max_pos, but use cubic interpolation to guess the position of maximum.


The argument of the statistics methods are the dimensions. If the dimensions are omitted, all dimensions are used. The argument can be range. See Table 5.5.

Table 5.5: Statistic methods.
self.sum(dim,..) Summation of elements in specified dimensions.
self.mul_add(other,dim) multiple and sum. faster than (x*y).sum(dim)
self.mean(dim,..) Mean of elements in specified dimensions.
self.stddev(dim,..) Standard deviation of elements in the dimensions.
self.min(dim,..) Minimum in the specified dimensions.
self.max(dim,..) Maximum in the specified dimensions.
self.median(dim) Median in 0..dim

Manipulating Array

See Table 5.6.

Table 5.6: Array manipulation methods.
self.sort(dim) Sort in the 0..dim (All dimensions if omitted)
self.sort!(dim) Sort, destructive
self.sort_index(dim) Return index of Sort result.
reference to another NArray  
self.refer create NArray obj referring to another NArray
self.reshape(size,...) same as self.refer.reshape!
self.newdim(dim,...) same as self.refer.newdim!

self.transpose( dim0, dim1, .. )

Transpose array. The dim0-th dimension goes to the 0-th dimension of new array. Negative number counts backward. transpose(-1,1..-2,0) is replacement between the first and the last.

self.mirror( dim )

Mirror array along the dimension. This method is not yet implemented. Please use following script to make a mirror.
a = a[true, true,-1..0]

Referencing can be used to change NMatrix to NArray.

Type conversion

See Table 5.7.

Table 5.7: Type conversion methods.
self.floor Return integer NArray whose elements processed 'floor'
self.ceil Return integer NArray whose elements processed 'ceil'
self.round Return integer NArray whose elements processed 'round'
self.to_f Convert NArray type to float
self.to_sf Convert NArray type to single float
self.to_i Convert NArray type to integer
self.to_a Convert NArray type to Ruby-object
self.to_s Convert NArray data to String as a binary data.
self.to_string Convert NArray type to Ruby-object containing Strings as printed elements
Byte swappers  
self.swap_byte swap byte order
self.hton convert to network byte order
self.htov convert to VAX byte order
self.vtoh convert from VAX


Iteration works similar to that of ruby array. However, when you use NArray, these iteration methods are slow. So, please avoid using these iterations. See Table 5.8.

Table 5.8: Iteration methods.
self.each {|i| ...}  
self.collect {|i| ...}  
self.collect! {|i| ...}  

Complex compund number

See Table 5.9.

Table 5.9: Complex compund numbers.
self.angle atan2(self.imag, self.real)
self.imag= other set imaginary part multiply by imaginary unit

Arithmetic functions as NMath module

These modules are used as module like function. Typically it is used like NMath.sqrt(narray).

Table 5.10: Arithmetic functions as NMath module.
sqrt(x) square root
exp(x) base-e exponential function
log(x) natural logarithmic function
log10(x) base-10 logarithmic function
log2(x) base-2 logarithmic function
atan2(y,x) arc tangent function of two variables
j0(x),y1(x),jn(n,x) Bessel functions of the first kind.
y0(x),y1(x),yn(n,x) Bessel functions of the second kind.
jnu(n,x) Bessel function with fractional order of the first kind.
ynu(n,x) Bessel function with fractional order of the second kind.
covariance (no idea why NMath::covariance doesn't work)


NMatrix is a subclass of NArray. First two dimensions are used as Matrix. Residual dimensions are treated as Multi-dimensional array. The order of Matrix dimensions is opposite from the notation of mathematics: a_ij => a[j,i].

enable if other is an NMatrix.
Matrix product if other is an NMatrix or an NVector. Scalar product if other is Numeric or NArray. For example,
NMatrix[[1,2],[3,4]] * [1,10]
   == NMatrix[ [[1,2],[3,4]], [[10,20],[30,40]] ]
/ other
Scalar division if other is Numeric or NArray. Solve Linear Equation with LU factorization, if other is square NMatrix. a/b == This function is not 64bit compatible.

transpose Matrix dimensions if argument omitted.

set val to diagonal elements. (set 1 if omitted).
set 1 to diagonal elements.
For a given dimension, returns integer type unit matrix.
Inverse matrix.
compute LU factorization. return NMatrixLU class object (see below).

NMatrix, standard matrix generators


NVector is a subclass of NArray. First dimension is used as Vector. Residual dimensions are treated as Multi-dimensional array.


NMatrixLU is created by NMatrix#lu method. Including LU (NMatrix) and pivot (NVector).

Example: language=Ruby, basicstyle=, frame=single
a = NMatrix.sfloat(2,2)
a[0,0] = 1.0
a[0,1] = 0.0
a[1,0] = 1...
...v[1] = 3.0
p ( b.solve(v) )
=> NVector.sfloat(2): [ -1.0, 3.0 ]

Solve with the result of LU factorization.

FFTW3 module

This module was originally written by Takeshi Horinouchi (GFD Dennou Club, 2003) and modified by Masahide Kikkawa.

The module support multi-dimensional complex FFT. It supports both double and single float transforms, if FFTW3 is compiled for both single and double float. Note that the values are not normalized as in FFTW.

EM related NArray methods.

Input and output

Currently Ruby-Helix can read and write MRC format and tiff format.

Image manipulations.

FFT-image related.

Following methods work only for MRC type FFT image files (so called FT format).

Header related


This class is for each one layer line. When a set of layer lines is treated, following BigG class is used instead.

layerline.apply_r_scale: layerline.apply_phi_z_shift(phi,z): phi: radian z : 2 PI l / repeat_distance layerline.write(fileHandle):

Accessor methods


These methods are usually called from BigG methods.


Originally designed for deal with big G file, but the class was extended to accomodate little g data.

Input and output

Currently ascii file BigG file can be read. read bigG from a file specified by the filename.

BigG.read_little_g(filename): read little g (Toyoshima and Yonekura format)

bigG.write(filename): write a bigG to a file.

bigG.write_ky(filename): write a bigG to a file in Yonekura and Toyoshima bigG format.

Manipulating big G files

There are several methods to manipulate big G files. The amplitude of the data is multiplied by scale


bigG.plot(n): plot $ n$ -th layer line with gnuplot.

bigG.limit_resolution(resolution) limit the resolution. Before executing this method, repeat length should be set. give angstrom

Fourier-Bessel conversions.

Accessor methods.

Basic Helices.

In general, all the helical lattice can be described using basic helical lattice [9].

$\displaystyle \left( \begin{array}{c} n_{h,k} \ l_{h,k} \end{array} \right) = ...
...ray} \right) + k \left( \begin{array}{c} n_{0,1} \ l_{0,1} \end{array} \right)$ (4.1)

Using the basic helices, now we can describe the unit cell as shown in Fig. 5.2.

Figure 5.2: A cylindrical section of a tubular crystal illustrating ``helical'' lattice lines and a unit cell. In this figure, $ \nu _{1,0}= 5$ , $ l_{1,0}=1$ , $ \nu _{0,1}=1.5$ , and $ l_{0,1}=4$ . (A) Two unit cell vectors $ \bm {a}$ and $ \bm {b}$ define an asymmetric unit (gray rhombus). The vectors satisfy two conditions, $ \nu _{1,0} \bm {a} - \nu _{0,1} \bm {b} = (2 \pi ,0)$ and $ - l_{1,0} \bm {a} + l_{0,1} \bm {b} = (0,c)$ . (B) The relation between ($ \phi $ ,$ z$ )-coordinate and the unit cell vector-coordinate.

From this relation, the unit cell vectors have the relation shown with the basic helix vectors as follows. Here we assume $ a = (\varphi_a, z_a)$ and $ b= (\varphi_b,z_b)$ .

$\displaystyle \begin{pmatrix}a_{\varphi} & b_{\varphi} \ a_z & b_z \end{pmatri...
...0,1} & l_{0,1} \end{pmatrix} = \begin{pmatrix}2 \pi & 0 \ 0 & c \end{pmatrix},$ (4.2)

Actually this equation is interesting because, the determinant of

$\displaystyle \begin{pmatrix}n_{1,0} & -l_{1,0} \ -n_{0,1} & l_{0,1} \end{pmatrix}$ (4.3)

is a number of unit cells in the repeat unit. If the value is negative, the size of the unit cell calculated by the following equation is also negative.

In addition, the determinant of

$\displaystyle \begin{pmatrix}a_{\varphi} & b_{\varphi} \ a_z & b_z \end{pmatrix}$ (4.4)

is the size of the unit cell.

To facilitate these calculation, there are several methods.

The following methods return real space basic vectors.


An example of the usage: Here is an example. In this case, we use a microtubule with 15 protofilaments and 2-start helix.

$ irb
irb(main):001:0> a =
irb(main):002:0> a.n10= 15
irb(main):003:0> a.l10= 1
irb(main):004:0> a.n01= -2
irb(main):005:0> a.l01= 17
irb(main):006:0> a.repeat = 1360
irb(main):007:0> p a.phiz_matrix

[ [ 0.4156, 0.02445 ], 
  [ -10.58, 79.38 ] ]

irb(main):008:0> p a.nl_matrix

[ [ 15.0, -1.0 ], 
  [ 2.0, 17.0 ] ]

irb(main):009:0> exit

Methods for analyzing the data.

self.correlationPlot(bigG2) printout correlation plot for xplot


To generate and manipulate spline curve. This class depends on Ruby/GSL. There are two implementations for GSL for Ruby, but this class library depends on Tsunesada's implementation. Please take a look at installation section.

This class uses x,y swapped axis shown in Figure 5.3.

Figure 5.3: Axis for spline class


Usually a Big G stores the data as a set of LayerLine(s). However, sometimes it is difficult to apply some methods as a whole. Therefore we introduced SerialG (this include both big and little g's). Also for BigG , serialization methods are implemented.

Serialized big G or little G. Mainly designed for easier manipulation of big G files.

To generate SerialG from BigG

g ="filename.avg")
sg = g.serialize

Or using template:

g ="filename.avg")
sg = g.serialize(template_sg)

Accessor methods


PDB (protein data bank)

This class is to treat PDB files.

Minimizer2D, a two-dimensional minimizer

Example code:
require ''Minimizer2D''
a =
...+ (y - random_y) * (y - random_y)
p random_x
p random_y

Minimizer3D, a three-dimensional minimizer

This class is implemented as a sub-class of Minimizer2D.

Sample code:
require ''Minimizer2D''
a =
...z - random_z)
p random_x
p random_y
p random_z
p result


next up previous contents index
Next: Bibliography Up: Ruby-Helix Previous: Script References.
Masahide Kikkawa