einsum 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 5fa002f0b200d3640b0498fe7723dc99f41acfdd37f428b4d01ca0807c775add
4
+ data.tar.gz: 37be8a20da6001f0fd6272f6cf7868acd37ddd6f4ac484b835c07c60f2d6e5f6
5
+ SHA512:
6
+ metadata.gz: a3558fe0cfca9c10b9aed8ec0c8e5683c683bc0df1d0ae793f407ae150b336ceaaecf73075406c0b69a344f56ff70f47ba3df0cae90c129b58f728dc4e2a3e82
7
+ data.tar.gz: 7fdedaa75471458b7758c0fdf8cc3480b2709426a0297ccfcfe4aca63fb3a86b51aaf6dcaf4764c146b16630185441cd1b9e16fe567192d2615af077dcd5dd82
data/.rspec ADDED
@@ -0,0 +1 @@
1
+ --require spec_helper
@@ -0,0 +1,6 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.5
3
+ Style/IfUnlessModifier:
4
+ Enabled: false
5
+ Metrics:
6
+ Enabled: false
@@ -0,0 +1,5 @@
1
+ # Change Log
2
+
3
+ ## [v0.1.1](https://github.com/toddsundsted/einsum/tree/v0.1.1) (2019-02-10)
4
+
5
+ **Initial Release**
data/Gemfile ADDED
@@ -0,0 +1,8 @@
1
+ # -*- ruby -*-
2
+ # frozen_string_literal: true
3
+
4
+ source 'https://rubygems.org'
5
+
6
+ ruby '2.5.1'
7
+
8
+ gemspec
@@ -0,0 +1,64 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ einsum (0.1.1)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ ast (2.4.0)
10
+ byebug (10.0.2)
11
+ coderay (1.1.2)
12
+ diff-lcs (1.3)
13
+ jaro_winkler (1.5.2)
14
+ method_source (0.9.2)
15
+ parallel (1.13.0)
16
+ parser (2.6.0.0)
17
+ ast (~> 2.4.0)
18
+ powerpack (0.1.2)
19
+ pry (0.12.2)
20
+ coderay (~> 1.1.0)
21
+ method_source (~> 0.9.0)
22
+ rainbow (3.0.0)
23
+ rake (12.3.2)
24
+ rspec (3.8.0)
25
+ rspec-core (~> 3.8.0)
26
+ rspec-expectations (~> 3.8.0)
27
+ rspec-mocks (~> 3.8.0)
28
+ rspec-core (3.8.0)
29
+ rspec-support (~> 3.8.0)
30
+ rspec-expectations (3.8.2)
31
+ diff-lcs (>= 1.2.0, < 2.0)
32
+ rspec-support (~> 3.8.0)
33
+ rspec-mocks (3.8.0)
34
+ diff-lcs (>= 1.2.0, < 2.0)
35
+ rspec-support (~> 3.8.0)
36
+ rspec-support (3.8.0)
37
+ rubocop (0.63.1)
38
+ jaro_winkler (~> 1.5.1)
39
+ parallel (~> 1.10)
40
+ parser (>= 2.5, != 2.5.1.1)
41
+ powerpack (~> 0.1)
42
+ rainbow (>= 2.2.2, < 4.0)
43
+ ruby-progressbar (~> 1.7)
44
+ unicode-display_width (~> 1.4.0)
45
+ ruby-progressbar (1.10.0)
46
+ unicode-display_width (1.4.1)
47
+
48
+ PLATFORMS
49
+ ruby
50
+
51
+ DEPENDENCIES
52
+ bundler (~> 2.0)
53
+ byebug (~> 10.0)
54
+ einsum!
55
+ pry (~> 0.12)
56
+ rake (~> 12.3)
57
+ rspec (~> 3.8)
58
+ rubocop (~> 0.63)
59
+
60
+ RUBY VERSION
61
+ ruby 2.5.1p57
62
+
63
+ BUNDLED WITH
64
+ 2.0.1
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 Todd Sundsted
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,61 @@
1
+ # Einsum
2
+
3
+ Unoptimized, pure-Ruby implementation of a subset of Numpy `einsum`.
4
+
5
+ See: https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html
6
+
7
+ ## Installation
8
+
9
+ Add this to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'einsum'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it manually:
20
+
21
+ $ gem install einsum
22
+
23
+ ## Usage
24
+
25
+ Evaluates the (extended) Einstein summation convention on the operands.
26
+
27
+ Operands must be `Array` like. Array elements must respond to `*` and `+`.
28
+
29
+ Implicit mode:
30
+
31
+ Einsum.einsum('ij,jk', [[1, 2], [3, 4]], [[1, 2], [3, 4]]) # => dot product: [[7, 10], [15, 22]]
32
+ Einsum.einsum('ij,kj', [[1, 2], [3, 4]], [[1, 2], [3, 4]]) # => inner product: [[ 5, 11], [11, 25]]
33
+
34
+ Explicit mode:
35
+
36
+ Einsum.einsum('ij,jk->ik', [[1, 2], [3, 4]], [[1, 2], [3, 4]]) # => dot product: [[7, 10], [15, 22]]
37
+ Einsum.einsum('ij,kj->ik', [[1, 2], [3, 4]], [[1, 2], [3, 4]]) # => inner product: [[ 5, 11], [11, 25]]
38
+ Einsum.einsum('ij,jk->', [[1, 2], [3, 4]], [[1, 2], [3, 4]]) # => 54
39
+ Einsum.einsum('ij,kj->', [[1, 2], [3, 4]], [[1, 2], [3, 4]]) # => 52
40
+
41
+ ## Development
42
+
43
+ After checking out the repository, run `bin/setup` to install
44
+ dependencies. Run `bin/console` for an interactive prompt. Run `rake
45
+ spec` to run the tests.
46
+
47
+ To install this gem locally, run `bundle exec rake install`. To
48
+ release a new version, update the version number in `version.rb` and
49
+ then run `bundle exec rake release`, which will create a git tag for
50
+ the version, push git commits and tags, and push the `.gem` file to
51
+ [rubygems.org](https://rubygems.org).
52
+
53
+ ## Contributing
54
+
55
+ Bug reports and pull requests are welcome on GitHub at
56
+ (https://github.com/toddsundsted/einsum).
57
+
58
+ ## License
59
+
60
+ The gem is available as open source under the terms of the
61
+ [MIT License](https://opensource.org/licenses/MIT).
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task default: :spec
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require 'bundler/setup'
5
+ require 'einsum'
6
+
7
+ require 'pry'
8
+ Pry.start
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ lib = File.expand_path('lib', __dir__)
4
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
5
+ require 'einsum/version'
6
+
7
+ Gem::Specification.new do |spec|
8
+ spec.name = 'einsum'
9
+ spec.version = Einsum::VERSION
10
+ spec.authors = ['Todd Sundsted']
11
+ spec.email = ['todd@sumall.com']
12
+
13
+ spec.summary = 'Unoptimized, pure-Ruby implementation of a subset of Numpy `einsum`.'
14
+ spec.homepage = 'https://github.com/toddsundsted/einsum'
15
+ spec.license = 'MIT'
16
+
17
+ # Specify which files should be added to the gem when it is released.
18
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
19
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
20
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
21
+ end
22
+ spec.require_paths = ['lib']
23
+
24
+ spec.add_development_dependency 'bundler', '~> 2.0'
25
+ spec.add_development_dependency 'byebug', '~> 10.0'
26
+ spec.add_development_dependency 'pry', '~> 0.12'
27
+ spec.add_development_dependency 'rake', '~> 12.3'
28
+ spec.add_development_dependency 'rspec', '~> 3.8'
29
+ spec.add_development_dependency 'rubocop', '~> 0.63'
30
+ end
@@ -0,0 +1,173 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'einsum/version'
4
+
5
+ ##
6
+ # Unoptimized, pure-Ruby implementation of a subset of Numpy `einsum`.
7
+ #
8
+ # See: https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html
9
+ #
10
+ class Einsum
11
+ FormatError = Class.new(StandardError)
12
+
13
+ Label = Struct.new(:dimension, :count) do
14
+ def initialize(dimension, count = 0)
15
+ super(dimension, count)
16
+ end
17
+
18
+ def increment
19
+ self.count += 1
20
+ end
21
+ end
22
+
23
+ class << self
24
+ ##
25
+ # Evaluates the (extended) Einstein summation convention on the operands.
26
+ #
27
+ # Operands must be `Array` like. Array elements must respond to `*` and `+`.
28
+ #
29
+ # Examples:
30
+ #
31
+ # In implicit mode:
32
+ #
33
+ # `Einsum.einsum('ij,jk', [[1, 2], [3, 4]], [[1, 2], [3, 4]]) # => dot product: [[7, 10], [15, 22]]`
34
+ # `Einsum.einsum('ij,kj', [[1, 2], [3, 4]], [[1, 2], [3, 4]]) # => inner product: [[ 5, 11], [11, 25]]`
35
+ #
36
+ # In explicit mode:
37
+ #
38
+ # `Einsum.einsum('ij,jk->ik', [[1, 2], [3, 4]], [[1, 2], [3, 4]]) # => dot product: [[7, 10], [15, 22]]`
39
+ # `Einsum.einsum('ij,kj->ik', [[1, 2], [3, 4]], [[1, 2], [3, 4]]) # => inner product: [[ 5, 11], [11, 25]]`
40
+ # `Einsum.einsum('ij,jk->', [[1, 2], [3, 4]], [[1, 2], [3, 4]]) # => 54`
41
+ # `Einsum.einsum('ij,kj->', [[1, 2], [3, 4]], [[1, 2], [3, 4]]) # => 52`
42
+ #
43
+ def einsum(format, *operands)
44
+ labels = {}
45
+
46
+ # check syntax of format string
47
+ unless format.match?(/\A([a-z]+(,[a-z]+)*)(->[a-z]*)?\z/)
48
+ raise FormatError, "invalid format: #{format}"
49
+ end
50
+
51
+ # chop up format string
52
+ inputs, explicit, output = format.partition('->')
53
+ inputs = inputs.split(',')
54
+ if operands.length != inputs.length
55
+ raise FormatError, "provides #{operands.length} operands for #{inputs.length} input labels strings"
56
+ end
57
+
58
+ # check labels and operands
59
+ inputs.zip(operands).each.with_index do |(input, operand), pos|
60
+ input.split('').each.with_index do |label, axis|
61
+ unless (dim = dim(operand, axis))
62
+ raise FormatError, "no axis in operand #{pos} corresponds to label #{label}"
63
+ end
64
+ if labels[label] && labels[label].dimension != dim
65
+ raise FormatError, "inconsistent dimension for label #{label}: #{labels[label].dimension} and #{dim}"
66
+ end
67
+
68
+ labels[label] ||= Label.new(dim)
69
+ labels[label].increment
70
+ end
71
+ end
72
+
73
+ # if implicit mode, generate output labels string from all
74
+ # labels mentioned only once in the input labels strings
75
+ if explicit.empty? && (groups = labels.group_by { |_, l| l.count }[1])
76
+ output = groups.map(&:first).sort.join
77
+ end
78
+
79
+ # compute shape of the result
80
+ shape = []
81
+ output.split('').each do |label|
82
+ unless labels[label]
83
+ raise FormatError, "output label #{label} not present in input labels"
84
+ end
85
+
86
+ shape << labels[label].dimension
87
+ end
88
+
89
+ # generate template for result
90
+ result = 0
91
+ unless shape.empty?
92
+ result = empty(shape, result)
93
+ end
94
+
95
+ # generate code for the specified operations. first, loop over
96
+ # each output axis in the order specified by the output labels.
97
+ # then, loop over the remaining input axes and compute the
98
+ # result for each cell in the output matrix.
99
+
100
+ code = []
101
+ internal = inputs.join.split('').sort.uniq - output.split('')
102
+ external = output.split('')
103
+
104
+ external.each do |label|
105
+ code.push("#{labels[label].dimension}.times do |#{label}|")
106
+ end
107
+
108
+ internal.each do |label|
109
+ code.push("#{labels[label].dimension}.times do |#{label}|")
110
+ end
111
+
112
+ external_labels = external.map { |l| "[#{l}]" }.join
113
+ code.push("result#{external_labels} +=")
114
+
115
+ inputs.each.with_index do |input, i|
116
+ input_labels = input.split('').map { |l| "[#{l}]" }.join
117
+ suffix = i < inputs.length - 1 ? ' *' : ''
118
+ code.push("operands[#{i}]#{input_labels}#{suffix}")
119
+ end
120
+
121
+ internal.each do
122
+ code.push('end')
123
+ end
124
+
125
+ external.each do
126
+ code.push('end')
127
+ end
128
+
129
+ # evaluate the generated code in the current context. this would
130
+ # be considered dangerous, except we are in control of generated
131
+ # code except loop variable names, which are derived from input
132
+ # and output labels, which are constrained to be individual,
133
+ # lowercase characters, which are bound in their respective
134
+ # loops.
135
+
136
+ # rubocop:disable Security/Eval
137
+ binding.eval(code.join("\n"))
138
+ # rubocop:enable Security/Eval
139
+
140
+ result
141
+ end
142
+
143
+ private
144
+
145
+ def dim(array, axis)
146
+ array =
147
+ if axis.positive?
148
+ array.dig(*Array.new(axis, 0))
149
+ else
150
+ array
151
+ end
152
+ begin
153
+ array.length
154
+ rescue NoMethodError
155
+ nil
156
+ end
157
+ end
158
+
159
+ def clone(array)
160
+ if array.respond_to?(:each)
161
+ array.map { |item| clone(item) }
162
+ else
163
+ array
164
+ end
165
+ end
166
+
167
+ def empty(shape, seed)
168
+ i, *shape = shape
169
+ seed = empty(shape, seed) unless shape.empty?
170
+ Array.new(i) { clone(seed) }
171
+ end
172
+ end
173
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Einsum
4
+ VERSION = '0.1.1'
5
+ end
metadata ADDED
@@ -0,0 +1,141 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: einsum
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ platform: ruby
6
+ authors:
7
+ - Todd Sundsted
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2019-02-10 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: '2.0'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '2.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: byebug
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: pry
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '0.12'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '0.12'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rake
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '12.3'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '12.3'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rspec
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '3.8'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '3.8'
83
+ - !ruby/object:Gem::Dependency
84
+ name: rubocop
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '0.63'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '0.63'
97
+ description:
98
+ email:
99
+ - todd@sumall.com
100
+ executables: []
101
+ extensions: []
102
+ extra_rdoc_files: []
103
+ files:
104
+ - ".rspec"
105
+ - ".rubocop.yml"
106
+ - CHANGELOG.md
107
+ - Gemfile
108
+ - Gemfile.lock
109
+ - LICENSE.txt
110
+ - README.md
111
+ - Rakefile
112
+ - bin/console
113
+ - bin/setup
114
+ - einsum.gemspec
115
+ - lib/einsum.rb
116
+ - lib/einsum/version.rb
117
+ homepage: https://github.com/toddsundsted/einsum
118
+ licenses:
119
+ - MIT
120
+ metadata: {}
121
+ post_install_message:
122
+ rdoc_options: []
123
+ require_paths:
124
+ - lib
125
+ required_ruby_version: !ruby/object:Gem::Requirement
126
+ requirements:
127
+ - - ">="
128
+ - !ruby/object:Gem::Version
129
+ version: '0'
130
+ required_rubygems_version: !ruby/object:Gem::Requirement
131
+ requirements:
132
+ - - ">="
133
+ - !ruby/object:Gem::Version
134
+ version: '0'
135
+ requirements: []
136
+ rubyforge_project:
137
+ rubygems_version: 2.7.6
138
+ signing_key:
139
+ specification_version: 4
140
+ summary: Unoptimized, pure-Ruby implementation of a subset of Numpy `einsum`.
141
+ test_files: []