expcalc 0.1.1

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 5ea184825d5690882d442e6139c95d18300ea4c5bd4a6f4ad4dd80f6a82ecbcd
4
+ data.tar.gz: a7a7067ec190eba6e97a4afcd6dc76a1abf6ce5caf07b49a3371c9d531beaa82
5
+ SHA512:
6
+ metadata.gz: bbcde5016cd50e20bff66f6259c02d20d8079b3944b98c79df28a129d939bb195bdc896117e6d4492e7014e2cbe792fb939538ac7cce818837e502184ceb1b62
7
+ data.tar.gz: 5361db5a87582af57b4e04cb66546897f1b838a7c5aec963bb65646b80ac5fdf3c4ce62aa59ce7644e8e2235ae9f471ecf058df9eb8bd9fdf18ebed18992b325
@@ -0,0 +1,18 @@
1
+ name: Ruby
2
+
3
+ on: [push,pull_request]
4
+
5
+ jobs:
6
+ build:
7
+ runs-on: ubuntu-latest
8
+ steps:
9
+ - uses: actions/checkout@v2
10
+ - name: Set up Ruby
11
+ uses: ruby/setup-ruby@v1
12
+ with:
13
+ ruby-version: 3.0.1
14
+ - name: Run the default task
15
+ run: |
16
+ gem install bundler -v 2.2.15
17
+ bundle install
18
+ bundle exec rake
data/.gitignore ADDED
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,13 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.4
3
+
4
+ Style/StringLiterals:
5
+ Enabled: true
6
+ EnforcedStyle: double_quotes
7
+
8
+ Style/StringLiteralsInInterpolation:
9
+ Enabled: true
10
+ EnforcedStyle: double_quotes
11
+
12
+ Layout/LineLength:
13
+ Max: 120
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at seoanezonjic@hotmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in expcalc.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "rspec", "~> 3.0"
11
+
12
+ gem "rubocop", "~> 1.7"
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 seoanezonjic
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.
data/README.md ADDED
@@ -0,0 +1,43 @@
1
+ # Expcalc
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/expcalc`. 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 'expcalc'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle install
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install expcalc
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 spec` 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 the created tag, 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]/expcalc. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/expcalc/blob/master/CODE_OF_CONDUCT.md).
36
+
37
+ ## License
38
+
39
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
40
+
41
+ ## Code of Conduct
42
+
43
+ Everyone interacting in the Expcalc project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/expcalc/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
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
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "expcalc"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require "irb"
15
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
data/expcalc.gemspec ADDED
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/expcalc/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "expcalc"
7
+ spec.version = Expcalc::VERSION
8
+ spec.authors = ["seoanezonjic"]
9
+ spec.email = ["seoanezonjic@hotmail.com"]
10
+
11
+ spec.summary = "Gem to expand ruby math capabilities"
12
+ spec.description = "To expand ruby math operations this gem call to others such as Numo:narray and others and implements methods onto them to deal with our needs"
13
+ spec.homepage = "https://github.com/seoanezonjic/expcalc"
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = Gem::Requirement.new(">= 2.4.0")
16
+
17
+ #spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'"
18
+
19
+ spec.metadata["homepage_uri"] = spec.homepage
20
+ spec.metadata["source_code_uri"] = spec.homepage
21
+ #spec.metadata["changelog_uri"] = "TODO: Put your gem's CHANGELOG.md URL here."
22
+
23
+ # Specify which files should be added to the gem when it is released.
24
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
25
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
26
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
27
+ end
28
+ spec.bindir = "bin"
29
+ spec.executables = spec.files.grep(%r{\Abin/}) { |f| File.basename(f) }
30
+ spec.require_paths = ["lib"]
31
+
32
+ spec.add_dependency "cmath", ">= 1.0.0"
33
+ spec.add_dependency "numo-linalg", ">= 0.1.5"
34
+ spec.add_dependency "numo-narray", ">= 0.9.1.9"
35
+ spec.add_dependency "pp", ">= 0.1.0"
36
+ spec.add_dependency "pycall", ">= 1.3.1"
37
+ spec.add_dependency "npy", ">= 0.2.0"
38
+
39
+ # For more information and examples about making a new gem, checkout our
40
+ # guide at: https://bundler.io/guides/creating_gem.html
41
+ end
@@ -0,0 +1,24 @@
1
+ class Array
2
+
3
+ def mean
4
+ return self.inject(0){|sum, n | sum + n}.fdiv(self.length)
5
+ end
6
+
7
+ def standard_deviation
8
+ x_mean = self.mean
9
+ variance = self.inject(0){|sum, n | sum + (n - x_mean)**2 }.fdiv(self.length)
10
+ return Math.sqrt(variance)
11
+ end
12
+
13
+ def get_quantiles(position=0.5)
14
+ self.sort!
15
+ n_items = self.size
16
+ quantile_coor = n_items * position - 1
17
+ if n_items % 2 == 0
18
+ quantile_value = (self[quantile_coor.to_i] + self[quantile_coor.to_i + 1]).fdiv(2)
19
+ else
20
+ quantile_value = self[quantile_coor.ceil]
21
+ end
22
+ return quantile_value
23
+ end
24
+ end
@@ -0,0 +1,279 @@
1
+ require 'nmatrix'
2
+ require 'nmatrix/lapacke'
3
+ require 'cmath'
4
+ require 'time'
5
+ require 'npy'
6
+ #require 'pp'
7
+
8
+ class NMatrix
9
+ def div(second_mat) #Matrix division A/B => A.dot(B.pinv) #https://stackoverflow.com/questions/49225693/matlab-matrix-division-into-python
10
+ return self.dot(second_mat.pinv)
11
+ end
12
+
13
+ def div_by_vector(vector, by=:col)
14
+ new_matrix = NMatrix.zeros(self.shape, dtype: self.dtype)
15
+ if by == :col
16
+ self.cols.times do |n|
17
+ vector.each_with_indices do |val, i, j|
18
+ new_matrix[i, n] = self[i, n].fdiv(val)
19
+ end
20
+ end
21
+ elsif by == :row
22
+
23
+ end
24
+ return new_matrix
25
+ end
26
+
27
+ def frobenius_norm
28
+ fro = 0.0
29
+ self.each do |value|
30
+ fro += value.abs ** 2
31
+ end
32
+ return fro ** 0.5
33
+ end
34
+
35
+ def max_norm #https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.norm.html, ord parameter = 1
36
+ sums = self.abs.sum(1)
37
+ return sums.max[0, 0]
38
+ end
39
+
40
+ def vector_product(vec_b)
41
+ product = 0.0
42
+ self.each_with_indices do |val, i, j|
43
+ product += val * vec_b[i, j]
44
+ end
45
+ return product
46
+ end
47
+
48
+ def vector_self_product
49
+ product = 0.0
50
+ self.each_stored_with_indices do |val, i, j|
51
+ product += val ** 2
52
+ end
53
+ return product
54
+ end
55
+
56
+ def max_eigenvalue(n=100, error = 10e-12) # do not set error too low or the eigenvalue cannot stabilised around the real one
57
+ max_eigenvalue = 0.0
58
+ length = self.cols
59
+ v = NMatrix.random([self.cols, 1], dtype: self.dtype)
60
+ # http://web.mit.edu/18.06/www/Spring17/Power-Method.pdf
61
+ #IMPLEMENTATION PROBLEM: RESULTS ARE TOO VARIABLE
62
+ last_max_eigenvalue = nil
63
+ n.times do
64
+ v = self.dot(v) # calculate the matrix-by-vector product Mv
65
+ v = v / v.frobenius_norm # calculate the norm and normalize the vector
66
+ max_eigenvalue = v.vector_product(self.dot(v)) / v.vector_self_product #Rayleigh quotient
67
+ # Rayleigh quotient: lambda = vMv/vv
68
+ # v is a vector so vv is inner product of one vector with self (use vector_self_product);
69
+ # Mv gives a vector, so vMv is the inner product of two different vectors (use vector_product)
70
+ break if !last_max_eigenvalue.nil? && last_max_eigenvalue - max_eigenvalue <= error
71
+ last_max_eigenvalue = max_eigenvalue
72
+ end
73
+ return max_eigenvalue
74
+ end
75
+
76
+ def min_eigenvalue(n=100, error = 10e-12)
77
+ return self.invert.max_eigenvalue(n, error)
78
+ end
79
+
80
+ def expm
81
+ return compute_py_method{|mat| expm(mat)}
82
+ #return compute_py_method(self){|mat| expm(mat)}
83
+ ##################################################
84
+ # matlab pade aproximation
85
+ ################################################
86
+ ### toolbox/matlab/demos/expmdemo1.m (Golub and Van Loan, Matrix Computations, Algorithm 11.3-1.)
87
+
88
+ #fraction, exponent = Math.frexp(max_norm)
89
+ #s = [0, exponent+1].max
90
+ #a = self/2**s
91
+
92
+ ## Pade approximation for exp(A)
93
+ #x = a
94
+ #c = 0.5
95
+ #ac = a*c
96
+ #e = NMatrix.identity(a.shape, dtype: a.dtype) + ac
97
+ #d = NMatrix.identity(a.shape, dtype: a.dtype) - ac
98
+ #q = 6
99
+ #p = true
100
+ #(2..q).each do |k|
101
+ # c = c * (q-k+1) / (k*(2*q-k+1))
102
+ # x = a.dot(x)
103
+ # cX = x * c
104
+ # e = e + cX
105
+ # if p
106
+ # d = d + cX
107
+ # else
108
+ # d = d - cX
109
+ # end
110
+ # p = !p
111
+ #end
112
+ #e = d.solve(e) #solve
113
+
114
+ ## Undo scaling by repeated squaring
115
+ #(1..s).each do
116
+ # e = e.dot(e)
117
+ #end
118
+ #return e
119
+
120
+ ###################################
121
+ ## Old python Pade aproximation
122
+ ###################################
123
+ #### Pade aproximation: https://github.com/rngantner/Pade_PyCpp/blob/master/src/expm.py
124
+ #a_l1 = max_norm
125
+ #n_squarings = 0
126
+ #if self.dtype == :float64 || self.dtype == :complex128
127
+ # if a_l1 < 1.495585217958292e-002
128
+ # u,v = _pade3(self)
129
+ #elsif a_l1 < 2.539398330063230e-001
130
+ # u,v = _pade5(self)
131
+ #elsif a_l1 < 9.504178996162932e-001
132
+ # u,v = _pade7(self)
133
+ #elsif a_l1 < 2.097847961257068e+000
134
+ # u,v = _pade9(self)
135
+ # else
136
+ # maxnorm = 5.371920351148152
137
+ # n_squarings = [0, Math.log2(a_l1 / maxnorm).ceil].max
138
+ # mat = self / 2**n_squarings
139
+ # u,v = _pade13(mat)
140
+ # end
141
+ #elsif self.dtype == :float32 || self.dtype == :complex64
142
+ # if a_l1 < 4.258730016922831e-001
143
+ # u,v = _pade3(self)
144
+ # elsif a_l1 < 1.880152677804762e+000
145
+ # u,v = _pade5(self)
146
+ # else
147
+ # maxnorm = 3.925724783138660
148
+ # n_squarings = [0, Math.log2(a_l1 / maxnorm).ceil].max
149
+ # mat = self / 2**n_squarings
150
+ # u,v = _pade7(mat)
151
+ # end
152
+ #end
153
+ #p = u + v
154
+ #q = -u + v
155
+ #r = q.solve(p)
156
+ #n_squarings.times do
157
+ # r = r.dot(r)
158
+ #end
159
+ #return r
160
+
161
+ ######################
162
+ # Exact computing
163
+ ######################
164
+ #####expm(matrix) = V*diag(exp(diag(D)))/V; V => eigenvectors(right), D => eigenvalues (right). # https://es.mathworks.com/help/matlab/ref/expm.html
165
+ #eigenvalues, eigenvectors = NMatrix::LAPACK.geev(self, :right)
166
+ #eigenvalues.map!{|val| Math.exp(val)}
167
+ #numerator = eigenvectors.dot(NMatrix.diagonal(eigenvalues, dtype: self.dtype))
168
+ #matrix_exp = numerator.div(eigenvectors)
169
+ #return matrix_exp
170
+ end
171
+
172
+ def cosine_normalization
173
+ normalized_matrix = NMatrix.zeros(self.shape, dtype: self.dtype)
174
+ #normalized_matrix = NMatrix.zeros(self.shape, dtype: :complex64)
175
+ self.each_with_indices do |val, i, j|
176
+ norm = val/CMath.sqrt(self[i, i] * self[j,j])
177
+ #abort("#{norm} has non zero imaginary part" ) if norm.imag != 0
178
+ normalized_matrix[i, j] = norm#.real
179
+ end
180
+ return normalized_matrix
181
+ end
182
+
183
+
184
+ private
185
+ def copy_array_like(ary1, ary2)
186
+ length = ary2.shape[0] #ruby nmatrix
187
+ length.times do |i|
188
+ length.times do |j|
189
+ ary2[i,j] = ary1[i,j] #python array
190
+ end
191
+ end
192
+ end
193
+
194
+ def compute_py_method
195
+ require 'pycall/import'
196
+ self.class.class_eval do # To include Pycall into NMatrix
197
+ include PyCall::Import
198
+ end
199
+ #Python
200
+ pyfrom 'scipy.linalg', import: :expm
201
+ pyimport :numpy, as: :np
202
+
203
+ b = np.empty(self.shape)
204
+ STDERR.puts "Start cpy rb in py array #{Time.now}"
205
+ copy_array_like(self, b)
206
+ STDERR.puts "Finish cpy rb in py array #{Time.now}"
207
+ a = nil
208
+ STDERR.puts "Start computing #{Time.now}"
209
+ PyCall.without_gvl do
210
+ a = yield(b) # Code block from ruby with python code
211
+ #a = expm(b)
212
+ end
213
+ ##
214
+ STDERR.puts "Finish computing #{Time.now}"
215
+
216
+ STDERR.puts "Start cpy py in rb array #{Time.now}"
217
+ result_matrix = NMatrix.zeros(self.shape, dtype: self.dtype)
218
+ copy_array_like(a, result_matrix)
219
+ STDERR.puts "Finish cpy py in rb array #{Time.now}"
220
+ return result_matrix
221
+ end
222
+
223
+ def _pade3(a)
224
+ b = [120.0, 60.0, 12.0, 1.0]
225
+ a2 = a.dot(a)
226
+ ident = NMatrix.identity(a.shape, dtype: a.dtype)
227
+ u = a.dot(a2 * b[3] + ident * b[1])
228
+ v = a2 * b[2] + ident * b[0]
229
+ return u,v
230
+ end
231
+
232
+ def _pade5(a)
233
+ b = [30240.0, 15120.0, 3360.0, 420.0, 30.0, 1.0]
234
+ a2 = a.dot(a)
235
+ a4 = a2.dot(a2)
236
+ ident = NMatrix.identity(a.shape, dtype: a.dtype)
237
+ u = a.dot(a4 * b[5] + a2 * b[3] + ident * b[1])
238
+ v = a4 * b[4] + a2 * b[2] + ident * b[0]
239
+ return u,v
240
+ end
241
+
242
+ def _pade7(a)
243
+ b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0, 56.0, 1.0]
244
+ a2 = a.dot(a)
245
+ a4 = a2.dot(a2)
246
+ a6 = a4.dot(a2)
247
+ ident = NMatrix.identity(a.shape, dtype: a.dtype)
248
+ u = a.dot(a6 * b[7] + a4 * b[5] + a2 * b[3] + ident * b[1])
249
+ v = a6 * b[6] + a4 * b[4] + a2 * b[2] + ident * b[0]
250
+ return u,v
251
+ end
252
+
253
+ def _pade9(a)
254
+ b = [17643225600.0, 8821612800.0, 2075673600.0, 302702400.0, 30270240.0,
255
+ 2162160.0, 110880.0, 3960.0, 90.0, 1.0]
256
+ a2 = a.dot(a)
257
+ a4 = a2.dot(a2)
258
+ a6 = a4.dot(a2)
259
+ a8 = a6.dot(a2)
260
+ ident = NMatrix.identity(a.shape, dtype: a.dtype)
261
+ u = a.dot(a8 * b[9] + a6 * b[7] + a4 * b[5] + a2 * b[3] + ident * b[1])
262
+ v = a8 * b[8] + a6 * b[6] + a4 * b[4] + a2 * b[2] + ident * b[0]
263
+ return u,v
264
+ end
265
+
266
+ def _pade13(a)
267
+ b = [64764752532480000.0, 32382376266240000.0, 7771770303897600.0,
268
+ 1187353796428800.0, 129060195264000.0, 10559470521600.0, 670442572800.0,
269
+ 33522128640.0, 1323241920.0, 40840800.0, 960960.0, 16380.0, 182.0, 1.0]
270
+ a2 = a.dot(a)
271
+ a4 = a2.dot(a2)
272
+ a6 = a4.dot(a2)
273
+ ident = NMatrix.identity(a.shape, dtype: a.dtype)
274
+ submat = a6 * b[13] + a4 * b[11] + a2 * b[9]
275
+ u = a.dot(a6.dot(submat) + a6 * b[7] + a4 * b[5] + a2 * b[3] + ident * b[1])
276
+ v = a6.dot(a6 * b[12] + a4 * b[10] + a2 * b[8] ) + a6 * b[6] + a4 * b[4] + a2 * b[2] + ident * b[0]
277
+ return u,v
278
+ end
279
+ end
@@ -0,0 +1,367 @@
1
+ #require 'nmatrix'
2
+ #require 'nmatrix/lapacke'
3
+ require 'numo/narray'
4
+ require 'numo/linalg'
5
+ require 'cmath'
6
+ require 'time'
7
+ require 'npy'
8
+ #require 'pp'
9
+
10
+ # Tb meter leer matrices con npy
11
+ class Hash
12
+ def get_hash_values_idx
13
+ x_names_indx = {}
14
+ i = 0
15
+ self.each do |k, values|
16
+ values.each do |val_id|
17
+ query = x_names_indx[val_id]
18
+ if query.nil?
19
+ x_names_indx[val_id] = i
20
+ i += 1
21
+ end
22
+ end
23
+ end
24
+ return x_names_indx
25
+ end
26
+
27
+ def to_bmatrix
28
+ x_names_indx = self.get_hash_values_idx
29
+ y_names = self.keys
30
+ x_names = x_names_indx.keys
31
+ # row (y), cols (x)
32
+ matrix = Numo::DFloat.zeros(self.length, x_names.length)
33
+ i = 0
34
+ self.each do |id, items|
35
+ items.each do |item_id|
36
+ matrix[i, x_names_indx[item_id]] = 1
37
+ end
38
+ i += 1
39
+ end
40
+ return matrix, y_names, x_names
41
+ end
42
+
43
+
44
+ # TODO: Only works if the resulting matrix will be squared. Replace implementacion taking into account to_bmatrix and its output
45
+ def to_wmatrix
46
+ element_names = self.keys
47
+ matrix = Numo::DFloat.zeros(element_names.length, element_names.length)
48
+ i = 0
49
+ self.each do |elementA, relations|
50
+ element_names.each_with_index do |elementB, j|
51
+ if elementA != elementB
52
+ query = relations[elementB]
53
+ if !query.nil?
54
+ matrix[i, j] = query
55
+ else
56
+ matrix[i, j] = self[elementB][elementA]
57
+ end
58
+ end
59
+ end
60
+ i += 1
61
+ end
62
+ return matrix, element_names
63
+ end
64
+ end
65
+
66
+ module Numo
67
+ class NArray
68
+ # TODO: load and save must have exact coherence between load ouput and save input
69
+ # Take into acount https://github.com/ankane/npy to load and read mats it allows serialize matrices larger than ruby marshal format
70
+
71
+ def self.load(input_file, type='txt', splitChar="\t")
72
+ matrix = nil
73
+ if type == 'txt'
74
+ counter = 0
75
+ File.open(input_file).each do |line|
76
+ line.chomp!
77
+ row = line.split(splitChar).map{|c| c.to_f }
78
+ if matrix.nil?
79
+ matrix = Numo::DFloat.zeros(row.length, row.length)
80
+ end
81
+ row.each_with_index do |val, i|
82
+ matrix[counter, i] = val if val != 0
83
+ end
84
+ counter += 1
85
+ end
86
+ elsif type == 'npy'
87
+ matrix = Npy.load(input_file)
88
+ end
89
+ return matrix
90
+ end
91
+
92
+ def save(matrix_filename, x_axis_names=nil, x_axis_file=nil, y_axis_names=nil, y_axis_file=nil)
93
+ File.open(x_axis_file, 'w'){|f| f.print x_axis_names.join("\n") } if !x_axis_names.nil?
94
+ File.open(y_axis_file, 'w'){|f| f.print y_axis_names.join("\n") } if !y_axis_names.nil?
95
+ Npy.save(matrix_filename, self)
96
+ end
97
+
98
+
99
+ def div(second_mat) #Matrix division A/B => A.dot(B.pinv) #https://stackoverflow.com/questions/49225693/matlab-matrix-division-into-python
100
+ return self.dot(second_mat.pinv)
101
+ end
102
+
103
+ def div_by_vector(vector, by=:col)
104
+ new_matrix = self.new_zeros
105
+ if by == :col
106
+ self.shape.last.times do |n|
107
+ vector.each_with_indices do |val, i, j|
108
+ new_matrix[i, n] = self[i, n].fdiv(val)
109
+ end
110
+ end
111
+ elsif by == :row
112
+
113
+ end
114
+ return new_matrix
115
+ end
116
+
117
+ def frobenius_norm
118
+ fro = 0.0
119
+ self.each do |value|
120
+ fro += value.abs ** 2
121
+ end
122
+ return fro ** 0.5
123
+ end
124
+
125
+ def max_norm #https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.norm.html, ord parameter = 1
126
+ sums = self.abs.sum(1)
127
+ return sums.max[0, 0]
128
+ end
129
+
130
+ def vector_product(vec_b)
131
+ product = 0.0
132
+ self.each_with_indices do |val, i, j|
133
+ product += val * vec_b[i, j]
134
+ end
135
+ return product
136
+ end
137
+
138
+ def vector_self_product
139
+ product = 0.0
140
+ self.each_stored_with_indices do |val, i, j|
141
+ product += val ** 2
142
+ end
143
+ return product
144
+ end
145
+
146
+ def max_eigenvalue(n=100, error = 10e-15) # do not set error too low or the eigenvalue cannot stabilised around the real one
147
+ max_eigenvalue = 0.0
148
+ length = self.shape.last
149
+ v = Numo::DFloat.new(length).rand
150
+ # http://web.mit.edu/18.06/www/Spring17/Power-Method.pdf
151
+ last_max_eigenvalue = nil
152
+ n.times do
153
+ v = Numo::Linalg.dot(self, v)
154
+ v = v / Numo::Linalg.norm(v)
155
+ max_eigenvalue = Numo::Linalg.dot(v, Numo::Linalg.dot(self, v)) / Numo::Linalg.dot(v,v) #Rayleigh quotient
156
+ break if !last_max_eigenvalue.nil? && (last_max_eigenvalue - max_eigenvalue).abs <= error
157
+ last_max_eigenvalue = max_eigenvalue
158
+ end
159
+ return max_eigenvalue
160
+ end
161
+
162
+ def min_eigenvalue(n=100, error = 10e-12)
163
+ return Numo::Linalg.inv(self).max_eigenvalue(n, error)
164
+ end
165
+
166
+ def expm
167
+ return compute_py_method{|mat| expm(mat)}
168
+ #return compute_py_method(self){|mat| expm(mat)}
169
+ ##################################################
170
+ # matlab pade aproximation
171
+ ################################################
172
+ ### toolbox/matlab/demos/expmdemo1.m (Golub and Van Loan, Matrix Computations, Algorithm 11.3-1.)
173
+
174
+ #fraction, exponent = Math.frexp(max_norm)
175
+ #s = [0, exponent+1].max
176
+ #a = self/2**s
177
+
178
+ ## Pade approximation for exp(A)
179
+ #x = a
180
+ #c = 0.5
181
+ #ac = a*c
182
+ #e = NMatrix.identity(a.shape, dtype: a.dtype) + ac
183
+ #d = NMatrix.identity(a.shape, dtype: a.dtype) - ac
184
+ #q = 6
185
+ #p = true
186
+ #(2..q).each do |k|
187
+ # c = c * (q-k+1) / (k*(2*q-k+1))
188
+ # x = a.dot(x)
189
+ # cX = x * c
190
+ # e = e + cX
191
+ # if p
192
+ # d = d + cX
193
+ # else
194
+ # d = d - cX
195
+ # end
196
+ # p = !p
197
+ #end
198
+ #e = d.solve(e) #solve
199
+
200
+ ## Undo scaling by repeated squaring
201
+ #(1..s).each do
202
+ # e = e.dot(e)
203
+ #end
204
+ #return e
205
+
206
+ ###################################
207
+ ## Old python Pade aproximation
208
+ ###################################
209
+ #### Pade aproximation: https://github.com/rngantner/Pade_PyCpp/blob/master/src/expm.py
210
+ #a_l1 = max_norm
211
+ #n_squarings = 0
212
+ #if self.dtype == :float64 || self.dtype == :complex128
213
+ # if a_l1 < 1.495585217958292e-002
214
+ # u,v = _pade3(self)
215
+ #elsif a_l1 < 2.539398330063230e-001
216
+ # u,v = _pade5(self)
217
+ #elsif a_l1 < 9.504178996162932e-001
218
+ # u,v = _pade7(self)
219
+ #elsif a_l1 < 2.097847961257068e+000
220
+ # u,v = _pade9(self)
221
+ # else
222
+ # maxnorm = 5.371920351148152
223
+ # n_squarings = [0, Math.log2(a_l1 / maxnorm).ceil].max
224
+ # mat = self / 2**n_squarings
225
+ # u,v = _pade13(mat)
226
+ # end
227
+ #elsif self.dtype == :float32 || self.dtype == :complex64
228
+ # if a_l1 < 4.258730016922831e-001
229
+ # u,v = _pade3(self)
230
+ # elsif a_l1 < 1.880152677804762e+000
231
+ # u,v = _pade5(self)
232
+ # else
233
+ # maxnorm = 3.925724783138660
234
+ # n_squarings = [0, Math.log2(a_l1 / maxnorm).ceil].max
235
+ # mat = self / 2**n_squarings
236
+ # u,v = _pade7(mat)
237
+ # end
238
+ #end
239
+ #p = u + v
240
+ #q = -u + v
241
+ #r = q.solve(p)
242
+ #n_squarings.times do
243
+ # r = r.dot(r)
244
+ #end
245
+ #return r
246
+
247
+ ######################
248
+ # Exact computing
249
+ ######################
250
+ #####expm(matrix) = V*diag(exp(diag(D)))/V; V => eigenvectors(right), D => eigenvalues (right). # https://es.mathworks.com/help/matlab/ref/expm.html
251
+ #eigenvalues, eigenvectors = NMatrix::LAPACK.geev(self, :right)
252
+ #eigenvalues.map!{|val| Math.exp(val)}
253
+ #numerator = eigenvectors.dot(NMatrix.diagonal(eigenvalues, dtype: self.dtype))
254
+ #matrix_exp = numerator.div(eigenvectors)
255
+ #return matrix_exp
256
+ end
257
+
258
+ def cosine_normalization
259
+ normalized_matrix = NMatrix.zeros(self.shape, dtype: self.dtype)
260
+ #normalized_matrix = NMatrix.zeros(self.shape, dtype: :complex64)
261
+ self.each_with_indices do |val, i, j|
262
+ norm = val/CMath.sqrt(self[i, i] * self[j,j])
263
+ #abort("#{norm} has non zero imaginary part" ) if norm.imag != 0
264
+ normalized_matrix[i, j] = norm#.real
265
+ end
266
+ return normalized_matrix
267
+ end
268
+
269
+
270
+ private
271
+ def copy_array_like(ary1, ary2)
272
+ length = ary2.shape[0] #ruby numo::array
273
+ length.times do |i|
274
+ length.times do |j|
275
+ ary2[i,j] = ary1[i,j] #python array
276
+ end
277
+ end
278
+ end
279
+
280
+ def compute_py_method
281
+ require 'pycall/import'
282
+ self.class.class_eval do # To include Pycall into Numo::array
283
+ include PyCall::Import
284
+ end
285
+ #Python
286
+ pyfrom 'scipy.linalg', import: :expm
287
+ pyimport :numpy, as: :np
288
+
289
+ b = np.empty(self.shape)
290
+ start = Time.now
291
+ copy_array_like(self, b)
292
+ STDERR.puts "Time cpy rb in py array #{(Time.now - start)/60}"
293
+
294
+ a = nil
295
+ start = Time.now
296
+ PyCall.without_gvl do
297
+ a = yield(b) # Code block from ruby with python code
298
+ #a = expm(b)
299
+ end
300
+ ##
301
+ STDERR.puts "Time computing #{(Time.now - start)/60}"
302
+
303
+ start = Time.now
304
+ result_matrix = self.new_zeros
305
+ copy_array_like(a, result_matrix)
306
+ STDERR.puts "Time cpy py in rb array #{(Time.now - start)/60}"
307
+ return result_matrix
308
+ end
309
+
310
+ def _pade3(a)
311
+ b = [120.0, 60.0, 12.0, 1.0]
312
+ a2 = a.dot(a)
313
+ ident = NMatrix.identity(a.shape, dtype: a.dtype)
314
+ u = a.dot(a2 * b[3] + ident * b[1])
315
+ v = a2 * b[2] + ident * b[0]
316
+ return u,v
317
+ end
318
+
319
+ def _pade5(a)
320
+ b = [30240.0, 15120.0, 3360.0, 420.0, 30.0, 1.0]
321
+ a2 = a.dot(a)
322
+ a4 = a2.dot(a2)
323
+ ident = NMatrix.identity(a.shape, dtype: a.dtype)
324
+ u = a.dot(a4 * b[5] + a2 * b[3] + ident * b[1])
325
+ v = a4 * b[4] + a2 * b[2] + ident * b[0]
326
+ return u,v
327
+ end
328
+
329
+ def _pade7(a)
330
+ b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0, 56.0, 1.0]
331
+ a2 = a.dot(a)
332
+ a4 = a2.dot(a2)
333
+ a6 = a4.dot(a2)
334
+ ident = NMatrix.identity(a.shape, dtype: a.dtype)
335
+ u = a.dot(a6 * b[7] + a4 * b[5] + a2 * b[3] + ident * b[1])
336
+ v = a6 * b[6] + a4 * b[4] + a2 * b[2] + ident * b[0]
337
+ return u,v
338
+ end
339
+
340
+ def _pade9(a)
341
+ b = [17643225600.0, 8821612800.0, 2075673600.0, 302702400.0, 30270240.0,
342
+ 2162160.0, 110880.0, 3960.0, 90.0, 1.0]
343
+ a2 = a.dot(a)
344
+ a4 = a2.dot(a2)
345
+ a6 = a4.dot(a2)
346
+ a8 = a6.dot(a2)
347
+ ident = NMatrix.identity(a.shape, dtype: a.dtype)
348
+ u = a.dot(a8 * b[9] + a6 * b[7] + a4 * b[5] + a2 * b[3] + ident * b[1])
349
+ v = a8 * b[8] + a6 * b[6] + a4 * b[4] + a2 * b[2] + ident * b[0]
350
+ return u,v
351
+ end
352
+
353
+ def _pade13(a)
354
+ b = [64764752532480000.0, 32382376266240000.0, 7771770303897600.0,
355
+ 1187353796428800.0, 129060195264000.0, 10559470521600.0, 670442572800.0,
356
+ 33522128640.0, 1323241920.0, 40840800.0, 960960.0, 16380.0, 182.0, 1.0]
357
+ a2 = a.dot(a)
358
+ a4 = a2.dot(a2)
359
+ a6 = a4.dot(a2)
360
+ ident = NMatrix.identity(a.shape, dtype: a.dtype)
361
+ submat = a6 * b[13] + a4 * b[11] + a2 * b[9]
362
+ u = a.dot(a6.dot(submat) + a6 * b[7] + a4 * b[5] + a2 * b[3] + ident * b[1])
363
+ v = a6.dot(a6 * b[12] + a4 * b[10] + a2 * b[8] ) + a6 * b[6] + a4 * b[4] + a2 * b[2] + ident * b[0]
364
+ return u,v
365
+ end
366
+ end
367
+ end
@@ -0,0 +1,153 @@
1
+ # TODO: Make a pull request to https://rubygems.org/gems/ruby-statistics, with all the statistic code implemented here.
2
+ #to cmpute fisher exact test
3
+ #Fisher => http://www.biostathandbook.com/fishers.html
4
+ # TODO:NetAnalyzer when performs hyper simple metric use Rubystats::FishersExactTest, compare results and mody implementation.
5
+ def get_fisher_exact_test(listA, listB, all_elements_count, tail ='two_sided', weigths=nil, partial_weigths=true)
6
+ #puts '-', listA.inspect, listB.inspect, '-'
7
+ listA_listB = listA & listB
8
+ listA_nolistB = listA - listB
9
+ nolistA_listB = listB - listA
10
+ if weigths.nil?
11
+ listA_listB_count = listA_listB.length
12
+ listA_nolistB_count = listA_nolistB.length
13
+ nolistA_listB_count = nolistA_listB.length
14
+ nolistA_nolistB_count = all_elements_count - (listA | listB).length
15
+ else
16
+ # Fisher exact test weigthed as proposed in Improved scoring of functional groups from gene expression data by decorrelating GO graph structure
17
+ # https://academic.oup.com/bioinformatics/article/22/13/1600/193669
18
+ listA_listB_count = listA_listB.map{|i| weigths[i]}.inject(0){|sum, n| sum + n}.ceil
19
+ listA_nolistB_count = listA_nolistB.map{|i| weigths[i]}.inject(0){|sum, n| sum + n}.ceil
20
+ nolistA_listB_count = nolistA_listB.map{|i| weigths[i]}.inject(0){|sum, n| sum + n}.ceil
21
+
22
+ if partial_weigths
23
+ nolistA_nolistB_count = all_elements_count - (listA | listB).length
24
+ all_elements_count = nolistA_nolistB_count + listA_listB_count + listA_nolistB_count + nolistA_listB_count
25
+ else
26
+ nolistA_nolistB_count = (weigths.keys - (listA | listB)).map{|i| weigths[i]}.inject(0){|sum, n| sum + n}.ceil
27
+ all_elements_count = weigths.values.inject(0){|sum, n| sum + n}.ceil
28
+ end
29
+ end
30
+ #puts [listA_listB_count, listA_nolistB_count, nolistA_listB_count, nolistA_nolistB_count, all_elements_count].inspect
31
+ if tail == 'two_sided'
32
+ accumulated_prob = get_two_tail(listA_listB_count, listA_nolistB_count, nolistA_listB_count, nolistA_nolistB_count, all_elements_count)
33
+ elsif tail == 'less'
34
+ accumulated_prob = get_less_tail(listA_listB_count, listA_nolistB_count, nolistA_listB_count, nolistA_nolistB_count, all_elements_count)
35
+ end
36
+ return accumulated_prob
37
+ end
38
+
39
+ def get_two_tail(listA_listB_count, listA_nolistB_count, nolistA_listB_count, nolistA_nolistB_count, all_elements_count)
40
+ #https://www.sheffield.ac.uk/polopoly_fs/1.43998!/file/tutorial-9-fishers.pdf
41
+ accumulated_prob = 0
42
+ ref_prob = compute_hyper_prob(
43
+ listA_listB_count,
44
+ listA_nolistB_count,
45
+ nolistA_listB_count,
46
+ nolistA_nolistB_count,
47
+ all_elements_count
48
+ )
49
+ accumulated_prob += ref_prob
50
+ [listA_listB_count, nolistA_nolistB_count].min.times do |n| #less
51
+ n += 1
52
+ prob = compute_hyper_prob(
53
+ listA_listB_count - n,
54
+ listA_nolistB_count + n,
55
+ nolistA_listB_count + n,
56
+ nolistA_nolistB_count - n,
57
+ all_elements_count
58
+ )
59
+ prob <= ref_prob ? accumulated_prob += prob : break
60
+ end
61
+
62
+ [listA_nolistB_count, nolistA_listB_count].min.times do |n| #greater
63
+ n += 1
64
+ prob = compute_hyper_prob(
65
+ listA_listB_count + n,
66
+ listA_nolistB_count - n,
67
+ nolistA_listB_count - n,
68
+ nolistA_nolistB_count + n,
69
+ all_elements_count
70
+ )
71
+ accumulated_prob += prob if prob <= ref_prob
72
+ end
73
+
74
+ return accumulated_prob
75
+ end
76
+
77
+ def get_less_tail(listA_listB_count, listA_nolistB_count, nolistA_listB_count, nolistA_nolistB_count, all_elements_count)
78
+ accumulated_prob = 0
79
+ [listA_listB_count, nolistA_nolistB_count].min.times do |n|
80
+ accumulated_prob += compute_hyper_prob(
81
+ listA_listB_count - n,
82
+ listA_nolistB_count + n,
83
+ nolistA_listB_count + n,
84
+ nolistA_nolistB_count - n,
85
+ all_elements_count
86
+ )
87
+ end
88
+ return accumulated_prob
89
+ end
90
+
91
+ def compute_hyper_prob(a, b, c, d, n)
92
+ # https://en.wikipedia.org/wiki/Fisher%27s_exact_test
93
+ binomA = binom(a + b, a)
94
+ binomC = binom(c + d, c)
95
+ divisor = binom(n, a + c)
96
+ return (binomA * binomC).fdiv(divisor)
97
+ end
98
+
99
+ def binom(n,k)
100
+ if k > 0 && k < n
101
+ res = (1+n-k..n).inject(:*)/(1..k).inject(:*)
102
+ else
103
+ res = 1
104
+ end
105
+ end
106
+
107
+ #to cmpute adjusted pvalues
108
+ #https://rosettacode.org/wiki/P-value_correction#Ruby
109
+ def get_benjaminiHochberg_pvalues(arr_pvalues)
110
+ n = arr_pvalues.length
111
+ arr_o = order(arr_pvalues, true)
112
+ arr_cummin_input = []
113
+ (0..(n - 1)).each do |i|
114
+ arr_cummin_input[i] = (n / (n - i).to_f) * arr_pvalues[arr_o[i]]
115
+ end
116
+ arr_ro = order(arr_o)
117
+ arr_cummin = cummin(arr_cummin_input)
118
+ arr_pmin = pmin(arr_cummin)
119
+ return arr_pmin.values_at(*arr_ro)
120
+ end
121
+
122
+ def order(array, decreasing = false)
123
+ if decreasing == false
124
+ array.sort.map { |n| array.index(n) }
125
+ else
126
+ array.sort.map { |n| array.index(n) }.reverse
127
+ end
128
+ end
129
+
130
+ def cummin(array)
131
+ cumulative_min = array.first
132
+ arr_cummin = []
133
+ array.each do |p|
134
+ cumulative_min = [p, cumulative_min].min
135
+ arr_cummin << cumulative_min
136
+ end
137
+ return arr_cummin
138
+ end
139
+
140
+ def pmin(array)
141
+ x = 1
142
+ pmin_array = []
143
+ array.each_index do |i|
144
+ pmin_array[i] = [array[i], x].min
145
+ abort if pmin_array[i] > 1
146
+ end
147
+ return pmin_array
148
+ end
149
+
150
+
151
+ class Pvalue
152
+
153
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Expcalc
4
+ VERSION = "0.1.1"
5
+ end
data/lib/expcalc.rb ADDED
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "expcalc/version"
4
+ require_relative "expcalc/numo_expansion"
5
+ require_relative "expcalc/array_expansion"
6
+ require_relative "expcalc/pvalue_expansion"
7
+
8
+ module Expcalc
9
+ class Error < StandardError; end
10
+ # Your code goes here...
11
+ end
metadata ADDED
@@ -0,0 +1,150 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: expcalc
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ platform: ruby
6
+ authors:
7
+ - seoanezonjic
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2022-02-17 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: cmath
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: 1.0.0
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: 1.0.0
27
+ - !ruby/object:Gem::Dependency
28
+ name: numo-linalg
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: 0.1.5
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: 0.1.5
41
+ - !ruby/object:Gem::Dependency
42
+ name: numo-narray
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: 0.9.1.9
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: 0.9.1.9
55
+ - !ruby/object:Gem::Dependency
56
+ name: pp
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: 0.1.0
62
+ type: :runtime
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: 0.1.0
69
+ - !ruby/object:Gem::Dependency
70
+ name: pycall
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: 1.3.1
76
+ type: :runtime
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: 1.3.1
83
+ - !ruby/object:Gem::Dependency
84
+ name: npy
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: 0.2.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.2.0
97
+ description: To expand ruby math operations this gem call to others such as Numo:narray
98
+ and others and implements methods onto them to deal with our needs
99
+ email:
100
+ - seoanezonjic@hotmail.com
101
+ executables:
102
+ - console
103
+ - setup
104
+ extensions: []
105
+ extra_rdoc_files: []
106
+ files:
107
+ - ".github/workflows/main.yml"
108
+ - ".gitignore"
109
+ - ".rspec"
110
+ - ".rubocop.yml"
111
+ - CODE_OF_CONDUCT.md
112
+ - Gemfile
113
+ - LICENSE.txt
114
+ - README.md
115
+ - Rakefile
116
+ - bin/console
117
+ - bin/setup
118
+ - expcalc.gemspec
119
+ - lib/expcalc.rb
120
+ - lib/expcalc/array_expansion.rb
121
+ - lib/expcalc/nmatrix_expansion.rb
122
+ - lib/expcalc/numo_expansion.rb
123
+ - lib/expcalc/pvalue_expansion.rb
124
+ - lib/expcalc/version.rb
125
+ homepage: https://github.com/seoanezonjic/expcalc
126
+ licenses:
127
+ - MIT
128
+ metadata:
129
+ homepage_uri: https://github.com/seoanezonjic/expcalc
130
+ source_code_uri: https://github.com/seoanezonjic/expcalc
131
+ post_install_message:
132
+ rdoc_options: []
133
+ require_paths:
134
+ - lib
135
+ required_ruby_version: !ruby/object:Gem::Requirement
136
+ requirements:
137
+ - - ">="
138
+ - !ruby/object:Gem::Version
139
+ version: 2.4.0
140
+ required_rubygems_version: !ruby/object:Gem::Requirement
141
+ requirements:
142
+ - - ">="
143
+ - !ruby/object:Gem::Version
144
+ version: '0'
145
+ requirements: []
146
+ rubygems_version: 3.2.15
147
+ signing_key:
148
+ specification_version: 4
149
+ summary: Gem to expand ruby math capabilities
150
+ test_files: []