rmatrix 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: e572268a9fa4fd04c2ac166d7141581ca677edd0
4
+ data.tar.gz: 41f62ceec7f2c54bc3b13899e479dbf8f433a5ca
5
+ SHA512:
6
+ metadata.gz: a75e6d8d05a41a7c830e6d50853c26c33233e0463d55a8afc3cf170be5bbaf2d3d090ec95929465eb930be8fcc4f3e3418666db70c122705904f21c7faed4e8a
7
+ data.tar.gz: 40cbe6898a74869c74a411357eec77f5ea7aa2ce3c857d674cc884115123d11157317ae276999e9f053cf205c143b1ae791d2b37295cb4cd790526dfa9b368de
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
@@ -0,0 +1,4 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.2.0
4
+ before_install: gem install bundler -v 1.10.6
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in rmatrix.gemspec
4
+ gemspec
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2016 Wouter Coppieters
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,41 @@
1
+ # Rmatrix
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/rmatrix`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'rmatrix'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install rmatrix
22
+
23
+ ## Usage
24
+
25
+ TODO: Write usage instructions here
26
+
27
+ ## Development
28
+
29
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
30
+
31
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
32
+
33
+ ## Contributing
34
+
35
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/rmatrix.
36
+
37
+
38
+ ## License
39
+
40
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
41
+
@@ -0,0 +1,10 @@
1
+ require "bundler/gem_tasks"
2
+ require "rake/testtask"
3
+
4
+ Rake::TestTask.new(:test) do |t|
5
+ t.libs << "test"
6
+ t.libs << "lib"
7
+ t.test_files = FileList['test/**/*_test.rb']
8
+ end
9
+
10
+ task :default => :test
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "rmatrix"
5
+ require 'pry'
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ Pry.start
@@ -0,0 +1,7 @@
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+
5
+ bundle install
6
+
7
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,3 @@
1
+ require "rmatrix/version"
2
+ require "rmatrix/core"
3
+ require "rmatrix/shortcuts"
@@ -0,0 +1,2 @@
1
+ require "rmatrix/matrix"
2
+ require "rmatrix/vector"
@@ -0,0 +1,271 @@
1
+ module RMatrix
2
+ class Matrix
3
+ require 'narray'
4
+ include Enumerable
5
+
6
+ attr_accessor :invert_next_operation, :matrix, :narray, :typecode
7
+
8
+ def initialize(source, narray: nil)
9
+ self.typecode = 'float'
10
+
11
+ if [Symbol, String].include?(source.class)
12
+ dimensions = "#{source}".split("x").map(&:to_i)
13
+ source = NArray.new(typecode, dimensions.inject(:*)).reshape(dimensions[1], dimensions[0])
14
+ end
15
+
16
+ self.narray = NArray.refer(narray || two_dimensional(source, typecode))
17
+ self.matrix = NMatrix.refer(self.narray)
18
+ end
19
+
20
+ def _dump(level)
21
+ [narray.typecode, columns, rows, narray.to_s].join(":")
22
+ end
23
+
24
+ def self._load arg
25
+ typecode, columns, rows, as_str = arg.split(":",4)
26
+ Matrix.new(nil, narray: NArray.to_na(as_str.to_s, typecode.to_i).reshape(columns.to_i, rows.to_i))
27
+ end
28
+
29
+ def each(&block)
30
+ e = Enumerator.new do |enum|
31
+ matrix.each do |elm|
32
+ enum << elm
33
+ end
34
+ end
35
+ block_given? ? e.each(&block) : e
36
+ end
37
+
38
+ def mmap
39
+ as_na = NArray.to_na(
40
+ matrix.each.map do |elm|
41
+ yield elm
42
+ end
43
+ ).to_type(typecode)
44
+ Matrix.new(as_na.reshape(*shape))
45
+ end
46
+
47
+ def coerce(other)
48
+ self.invert_next_operation = true
49
+ [self, other]
50
+ end
51
+
52
+ def size
53
+ self.shape.inject(:*)
54
+ end
55
+
56
+ def rows
57
+ self.shape.last
58
+ end
59
+
60
+ def columns
61
+ self.shape.first
62
+ end
63
+
64
+ def sum_rows
65
+ Matrix.new(sum(0))
66
+ end
67
+
68
+ def sum_columns
69
+ Matrix.new(sum(1))
70
+ end
71
+
72
+ def two_dimensional(source, type)
73
+ source = [source] if Numeric === source
74
+ source = NArray.to_na(source).to_type(type)
75
+ case source.dim
76
+ when 1
77
+ source.reshape(source.length, 1)
78
+ when 2
79
+ source
80
+ else
81
+ raise "Source for matrix must be either one or two dimensional" unless source.shape[2..-1].all?{|x| x == 1}
82
+ source.reshape(source.shape[0], source.shape[1])
83
+ end
84
+ end
85
+
86
+ def minor(x,y)
87
+ return self.delete_at(y,x)
88
+ end
89
+
90
+ def cofactor_matrix(*args)
91
+ return cofactor(*args) if args.length == 2
92
+
93
+ result = []
94
+ rows.times do |i|
95
+ result << []
96
+ columns.times do |j|
97
+ result[i] << cofactor(i, j)
98
+ end
99
+ end
100
+ return Matrix.new(result)
101
+ end
102
+
103
+ def determinant
104
+ raise "Cannot calculate determinant of non-square matrix" unless columns == rows
105
+ return self[0, 0] * self[1, 1]- self[0, 1] * self[1, 0] if(self.columns == 2)
106
+ sign = 1
107
+ det = 0
108
+ self.columns.times do |i|
109
+ det += sign * self[0,i] * self.minor(0, i).determinant
110
+ sign *= -1
111
+ end
112
+ return det
113
+ end
114
+
115
+ def adjoint
116
+ self.cofactor_matrix.transpose
117
+ end
118
+
119
+ def *(other)
120
+ if other.kind_of?(Matrix)
121
+ raise "Matrix A columns(#{self.columns}) != Matrix B rows(#{other.columns})" if other.rows != self.columns
122
+ Matrix.new(self.matrix * other.matrix)
123
+ else
124
+ Matrix.new(apply_scalar(:*, other))
125
+ end
126
+ end
127
+
128
+ def mult(other)
129
+ apply_elementwise(:*, other)
130
+ end
131
+
132
+ def ==(other)
133
+ self.matrix == Matrix[other].matrix
134
+ end
135
+
136
+ def to_s
137
+ inspect
138
+ end
139
+
140
+ def box_lines(lines, add_dots)
141
+ "[#{lines.map{|l| "[#{l}#{add_dots ? ' ...' : '' }]"}.join(",\n ")}]"
142
+ end
143
+
144
+ def round(dp)
145
+ mmap{|x| x.round(dp) }
146
+ end
147
+
148
+ def inspect
149
+ inspect_rows = [10, self.rows].min
150
+ inspect_columns = [10, self.columns].min
151
+ more_rows = inspect_rows < self.rows
152
+ more_columns = inspect_columns < self.columns
153
+
154
+ to_print = self.matrix[0...inspect_columns, 0...inspect_rows]
155
+ as_strings = inspect_columns.times.map do |i|
156
+ column = to_print[i, 0...inspect_rows].flatten.to_a.map{|f| f.to_s.gsub(/(\.\d{4}).*/, "\\1") }
157
+ max_width = column.map{|s| s.length }.max
158
+ column.map!{|s| s.rjust(max_width, ' ')} + (more_rows ? ['.' * max_width] : [])
159
+ end.transpose
160
+ "#{rows} x #{columns} Matrix\nM#{box_lines(as_strings.map{|row| row.join(", ") }, more_columns)}"
161
+ end
162
+
163
+
164
+ def [](*args)
165
+ args.any?{|x| Range === x} ? Matrix.new(narray[*args.reverse]) : narray[*args.reverse]
166
+ end
167
+
168
+ def transpose
169
+ Matrix.new(self.matrix.transpose)
170
+ end
171
+
172
+ def self.new(*args, &blk)
173
+ result = super
174
+ if result.class == Matrix && (result.rows == 1 || result.columns == 1)
175
+ vect = V[1]
176
+ vect.matrix, vect.narray = result.matrix, result.narray
177
+ result = vect
178
+ end
179
+ result
180
+ end
181
+
182
+ def self.[](*inputs)
183
+ if inputs.length == 1 && Matrix === inputs[0]
184
+ inputs[0]
185
+ elsif inputs.length == 1 && [String, Symbol].include?(inputs[0].class)
186
+ Matrix.new(inputs[0])
187
+ else
188
+ Matrix.new(inputs)
189
+ end
190
+ end
191
+
192
+ def self.gen_mutator(name)
193
+ define_method(name) do |*args, &blk|
194
+ matrix.send(name, *args, &blk)
195
+ self
196
+ end
197
+ end
198
+
199
+ def self.gen_matrix_delegator(name)
200
+ define_method(name) do |*args, &blk|
201
+ Matrix.new(matrix.send(name, *args, &blk))
202
+ end
203
+ end
204
+
205
+ def self.gen_delegator(name)
206
+ define_method(name) do |*args, &blk|
207
+ matrix.send(name, *args, &blk)
208
+ end
209
+ end
210
+
211
+ OPERATIONS_MAP = {
212
+ :& => 'and',
213
+ :^ => 'xor',
214
+ :| => 'or'
215
+ }
216
+ def translate_op(op)
217
+ OPERATIONS_MAP.fetch(op, op)
218
+ end
219
+
220
+ [:fill!, :random!, :indgen!].each(&method(:gen_mutator))
221
+ [:reshape, :sort, :sort_index, :inverse, :lu, :delete_at, :where, :where2, :not].each(&method(:gen_matrix_delegator))
222
+ [:sum, :prod, :mean, :stddev, :rms, :rmsdev, :min, :max, :shape].each(&method(:gen_delegator))
223
+ [:+, :/, :-, :**, :&, :^, :|].each do |op|
224
+ define_method(op) do |other|
225
+ op = translate_op(op)
226
+ Matrix.new(
227
+ if other.kind_of?(Matrix)
228
+ apply_elementwise(op, other)
229
+ else
230
+ apply_scalar(op, other)
231
+ end
232
+ )
233
+ end
234
+ end
235
+
236
+ def self.seed(seed)
237
+ NArray.srand(seed)
238
+ end
239
+
240
+ private
241
+ def test_inverse
242
+ inverse = self.invert_next_operation
243
+ self.invert_next_operation = false
244
+ return inverse
245
+ end
246
+
247
+ def cofactor(i, j)
248
+ minor = self.minor(i, j)
249
+ sign = ((i * self.columns + j) % 2).zero? ? 1 : -1;
250
+ return sign * minor.determinant
251
+ end
252
+
253
+ def apply_elementwise(op, other)
254
+ if test_inverse
255
+ other.narray.send(op, self.narray)
256
+ else
257
+ narray.send(op, other.narray)
258
+ end
259
+ end
260
+
261
+ def apply_scalar(op, other)
262
+ if test_inverse
263
+ Matrix[other].narray.send(op, self.narray)
264
+ else
265
+ narray.send(op, Matrix[other].narray)
266
+ end
267
+ end
268
+ end
269
+
270
+ class ::NArray; include Enumerable; end
271
+ end
@@ -0,0 +1,13 @@
1
+ module RMatrix
2
+ class Matrix
3
+ alias_method :I, :inverse
4
+ alias_method :T, :transpose
5
+ alias_method :D, :determinant
6
+ alias_method :M, :minor
7
+ alias_method :A, :adjoint
8
+ alias_method :C, :cofactor_matrix
9
+ end
10
+ end
11
+
12
+ M = RMatrix::Matrix
13
+ V = RMatrix::Vector
@@ -0,0 +1,24 @@
1
+ module RMatrix
2
+ class Vector < RMatrix::Matrix
3
+
4
+ def initialize(source)
5
+ super
6
+ raise "Invalid dimensions #{shape.join(?x).reverse}. Vector must be eiter Nx1 or 1xM" unless [rows, columns].include?(1) && shape.length == 2
7
+ end
8
+
9
+ def self.[](*inputs)
10
+ Vector.new(inputs)
11
+ end
12
+
13
+ def inspect
14
+ elms = narray.to_a.flatten
15
+ print = elms.first(10)
16
+ has_more = elms.length > 10
17
+ if rows == 1
18
+ "Vector(#{narray.length})\nV[#{print.join(", ") + (has_more ? ',...' : '')}]"
19
+ else
20
+ "Vector(#{narray.length})\nV[\n [#{print.join("],\n [") + (has_more ? "\n ..." : '')}]\n]"
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,3 @@
1
+ module Rmatrix
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,38 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'rmatrix/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "rmatrix"
8
+ spec.version = Rmatrix::VERSION
9
+ spec.authors = ["Wouter Coppieters"]
10
+ spec.email = ["wouter.coppieters@youdo.co.nz"]
11
+
12
+ spec.summary = "Fast matrix/linear algebra library for Ruby"
13
+ spec.description = %Q(RMatrix is a lightning fast library for Ruby. It provides numerous enhancements over the Matrix class in the standard library.
14
+ Features include the ability to calculate Matrix inverse, transpose, determinant, minor, adjoint, cofactor_matrix, hadamard product and other elementwise operations, slicing, masking and more.
15
+ RMatrix makes use of backing instances of NArray to allow for great performance.)
16
+ spec.homepage = "https://github.com/wouterken/RMatrix"
17
+ spec.license = "MIT"
18
+
19
+ # # Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or
20
+ # # delete this section to allow pushing this gem to any host.
21
+ # if spec.respond_to?(:metadata)
22
+ # spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'"
23
+ # else
24
+ # raise "RubyGems 2.0 or newer is required to protect against public gem pushes."
25
+ # end
26
+
27
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
28
+ spec.bindir = "exe"
29
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
30
+ spec.require_paths = ["lib"]
31
+
32
+ spec.add_development_dependency "bundler", "~> 1.10"
33
+ spec.add_development_dependency "rake", "~> 10.0"
34
+ spec.add_development_dependency "minitest"
35
+ spec.add_development_dependency "pry"
36
+ spec.add_development_dependency "pry-byebug"
37
+ spec.add_runtime_dependency "narray"
38
+ end
@@ -0,0 +1,9 @@
1
+ ✔ Update print @done (16-04-06 07:40)
2
+ ✔ Basic matrix functions and tests @done (16-04-06 07:40)
3
+ ☐ Enumeration, each over columns, each over rows, each element, each reverse, each column/row reversed
4
+ ☐ Map to Matrix
5
+ ☐ Select rows
6
+ ☐ Select columns
7
+ ☐ Slice/Mask rows and columns
8
+ ☐ Specs
9
+ ☐ Float, Double, Complex, Double Complex and integer types
metadata ADDED
@@ -0,0 +1,148 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rmatrix
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Wouter Coppieters
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2016-04-06 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.10'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.10'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: minitest
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: pry
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: pry-byebug
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: narray
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ type: :runtime
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '0'
97
+ description: |-
98
+ RMatrix is a lightning fast library for Ruby. It provides numerous enhancements over the Matrix class in the standard library.
99
+ Features include the ability to calculate Matrix inverse, transpose, determinant, minor, adjoint, cofactor_matrix, hadamard product and other elementwise operations, slicing, masking and more.
100
+ RMatrix makes use of backing instances of NArray to allow for great performance.
101
+ email:
102
+ - wouter.coppieters@youdo.co.nz
103
+ executables: []
104
+ extensions: []
105
+ extra_rdoc_files: []
106
+ files:
107
+ - ".gitignore"
108
+ - ".travis.yml"
109
+ - Gemfile
110
+ - LICENSE.txt
111
+ - README.md
112
+ - Rakefile
113
+ - bin/console
114
+ - bin/setup
115
+ - lib/rmatrix.rb
116
+ - lib/rmatrix/core.rb
117
+ - lib/rmatrix/matrix.rb
118
+ - lib/rmatrix/shortcuts.rb
119
+ - lib/rmatrix/vector.rb
120
+ - lib/rmatrix/version.rb
121
+ - rmatrix.gemspec
122
+ - rmatrix.todo
123
+ homepage: https://github.com/wouterken/RMatrix
124
+ licenses:
125
+ - MIT
126
+ metadata: {}
127
+ post_install_message:
128
+ rdoc_options: []
129
+ require_paths:
130
+ - lib
131
+ required_ruby_version: !ruby/object:Gem::Requirement
132
+ requirements:
133
+ - - ">="
134
+ - !ruby/object:Gem::Version
135
+ version: '0'
136
+ required_rubygems_version: !ruby/object:Gem::Requirement
137
+ requirements:
138
+ - - ">="
139
+ - !ruby/object:Gem::Version
140
+ version: '0'
141
+ requirements: []
142
+ rubyforge_project:
143
+ rubygems_version: 2.4.5
144
+ signing_key:
145
+ specification_version: 4
146
+ summary: Fast matrix/linear algebra library for Ruby
147
+ test_files: []
148
+ has_rdoc: