numo-tiny_linalg 0.0.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: 15ddc75f758bbff2ef6887db5d71c13dd517f7eeb0c4d3ab181c5c2db8b8f995
4
+ data.tar.gz: 20350f1d084a31e51e05c317dddc23f6285dd27430176a753edd3eea935331be
5
+ SHA512:
6
+ metadata.gz: 457d487b20bfffb3eade0fc80120f5de7acfa3f0678550f3b844abac139e7b6db469fdcf6b686337755ea2b49b8bad54ea66381368d2e4e554fdb32df6e2d87d
7
+ data.tar.gz: 217765d951cf0d790e8620e1a4e4d28a884a5955bdca32cc4386fd4951c8ae2a133be029c24b20e987ce6fb2c7adfa101fe327c55cce327c2e89f4ff4d54a874
data/.clang-format ADDED
@@ -0,0 +1,149 @@
1
+ ---
2
+ Language: Cpp
3
+ # BasedOnStyle: LLVM
4
+ AccessModifierOffset: -2
5
+ AlignAfterOpenBracket: Align
6
+ AlignConsecutiveMacros: false
7
+ AlignConsecutiveAssignments: false
8
+ AlignConsecutiveBitFields: false
9
+ AlignConsecutiveDeclarations: false
10
+ AlignEscapedNewlines: Right
11
+ AlignOperands: Align
12
+ AlignTrailingComments: true
13
+ AllowAllArgumentsOnNextLine: true
14
+ AllowAllConstructorInitializersOnNextLine: true
15
+ AllowAllParametersOfDeclarationOnNextLine: true
16
+ AllowShortEnumsOnASingleLine: true
17
+ AllowShortBlocksOnASingleLine: Never
18
+ AllowShortCaseLabelsOnASingleLine: false
19
+ AllowShortFunctionsOnASingleLine: All
20
+ AllowShortLambdasOnASingleLine: All
21
+ AllowShortIfStatementsOnASingleLine: true
22
+ AllowShortLoopsOnASingleLine: true
23
+ AlwaysBreakAfterDefinitionReturnType: None
24
+ AlwaysBreakAfterReturnType: None
25
+ AlwaysBreakBeforeMultilineStrings: false
26
+ AlwaysBreakTemplateDeclarations: MultiLine
27
+ BinPackArguments: true
28
+ BinPackParameters: true
29
+ BraceWrapping:
30
+ AfterCaseLabel: false
31
+ AfterClass: false
32
+ AfterControlStatement: Never
33
+ AfterEnum: false
34
+ AfterFunction: false
35
+ AfterNamespace: false
36
+ AfterObjCDeclaration: false
37
+ AfterStruct: false
38
+ AfterUnion: false
39
+ AfterExternBlock: false
40
+ BeforeCatch: false
41
+ BeforeElse: false
42
+ BeforeLambdaBody: false
43
+ BeforeWhile: false
44
+ IndentBraces: false
45
+ SplitEmptyFunction: true
46
+ SplitEmptyRecord: true
47
+ SplitEmptyNamespace: true
48
+ BreakBeforeBinaryOperators: None
49
+ BreakBeforeBraces: Attach
50
+ BreakBeforeInheritanceComma: false
51
+ BreakInheritanceList: BeforeColon
52
+ BreakBeforeTernaryOperators: true
53
+ BreakConstructorInitializersBeforeComma: false
54
+ BreakConstructorInitializers: BeforeColon
55
+ BreakAfterJavaFieldAnnotations: false
56
+ BreakStringLiterals: true
57
+ ColumnLimit: 0
58
+ CommentPragmas: '^ IWYU pragma:'
59
+ CompactNamespaces: false
60
+ ConstructorInitializerAllOnOneLineOrOnePerLine: false
61
+ ConstructorInitializerIndentWidth: 4
62
+ ContinuationIndentWidth: 2
63
+ Cpp11BracedListStyle: false
64
+ DeriveLineEnding: true
65
+ DerivePointerAlignment: false
66
+ DisableFormat: false
67
+ ExperimentalAutoDetectBinPacking: false
68
+ FixNamespaceComments: true
69
+ ForEachMacros:
70
+ - foreach
71
+ - Q_FOREACH
72
+ - BOOST_FOREACH
73
+ IncludeBlocks: Preserve
74
+ IncludeCategories:
75
+ - Regex: '^"(llvm|llvm-c|clang|clang-c)/'
76
+ Priority: 2
77
+ SortPriority: 0
78
+ - Regex: '^(<|"(gtest|gmock|isl|json)/)'
79
+ Priority: 3
80
+ SortPriority: 0
81
+ - Regex: '.*'
82
+ Priority: 1
83
+ SortPriority: 0
84
+ IncludeIsMainRegex: '(Test)?$'
85
+ IncludeIsMainSourceRegex: ''
86
+ IndentCaseLabels: false
87
+ IndentCaseBlocks: false
88
+ IndentGotoLabels: true
89
+ IndentPPDirectives: None
90
+ IndentExternBlock: AfterExternBlock
91
+ IndentWidth: 2
92
+ IndentWrappedFunctionNames: false
93
+ InsertTrailingCommas: None
94
+ JavaScriptQuotes: Leave
95
+ JavaScriptWrapImports: true
96
+ KeepEmptyLinesAtTheStartOfBlocks: true
97
+ MacroBlockBegin: ''
98
+ MacroBlockEnd: ''
99
+ MaxEmptyLinesToKeep: 1
100
+ NamespaceIndentation: None
101
+ ObjCBinPackProtocolList: Auto
102
+ ObjCBlockIndentWidth: 2
103
+ ObjCBreakBeforeNestedBlockParam: true
104
+ ObjCSpaceAfterProperty: false
105
+ ObjCSpaceBeforeProtocolList: true
106
+ PenaltyBreakAssignment: 2
107
+ PenaltyBreakBeforeFirstCallParameter: 19
108
+ PenaltyBreakComment: 300
109
+ PenaltyBreakFirstLessLess: 120
110
+ PenaltyBreakString: 1000
111
+ PenaltyBreakTemplateDeclaration: 10
112
+ PenaltyExcessCharacter: 1000000
113
+ PenaltyReturnTypeOnItsOwnLine: 60
114
+ PointerAlignment: Left
115
+ ReflowComments: true
116
+ SortIncludes: true
117
+ SortUsingDeclarations: true
118
+ SpaceAfterCStyleCast: false
119
+ SpaceAfterLogicalNot: false
120
+ SpaceAfterTemplateKeyword: true
121
+ SpaceBeforeAssignmentOperators: true
122
+ SpaceBeforeCpp11BracedList: false
123
+ SpaceBeforeCtorInitializerColon: true
124
+ SpaceBeforeInheritanceColon: true
125
+ SpaceBeforeParens: ControlStatements
126
+ SpaceBeforeRangeBasedForLoopColon: true
127
+ SpaceInEmptyBlock: false
128
+ SpaceInEmptyParentheses: false
129
+ SpacesBeforeTrailingComments: 1
130
+ SpacesInAngles: false
131
+ SpacesInConditionalStatement: false
132
+ SpacesInContainerLiterals: true
133
+ SpacesInCStyleCastParentheses: false
134
+ SpacesInParentheses: false
135
+ SpacesInSquareBrackets: false
136
+ SpaceBeforeSquareBrackets: false
137
+ Standard: Latest
138
+ StatementMacros:
139
+ - Q_UNUSED
140
+ - QT_REQUIRE_VERSION
141
+ TabWidth: 8
142
+ UseCRLF: false
143
+ UseTab: Never
144
+ WhitespaceSensitiveMacros:
145
+ - STRINGIZE
146
+ - PP_STRINGIZE
147
+ - BOOST_PP_STRINGIZE
148
+ ...
149
+
data/.husky/commit-msg ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env sh
2
+ . "$(dirname -- "$0")/_/husky.sh"
3
+
4
+ yarn commitlint --edit "$1"
data/.rubocop.yml ADDED
@@ -0,0 +1,47 @@
1
+ require:
2
+ - rubocop-rake
3
+ - rubocop-minitest
4
+ - rubocop-performance
5
+
6
+ AllCops:
7
+ TargetRubyVersion: 2.7
8
+ NewCops: enable
9
+ DisplayCopNames: true
10
+ DisplayStyleGuide: true
11
+ Exclude:
12
+ - 'tmp/**/*'
13
+ - 'vendor/**/*'
14
+
15
+ Gemspec/RequiredRubyVersion:
16
+ Enabled: false
17
+
18
+ Layout/LineLength:
19
+ AllowedPatterns: ['(\A|\s)#']
20
+
21
+ Metrics/AbcSize:
22
+ Max: 40
23
+ Exclude:
24
+ - 'test/**/*'
25
+
26
+ Metrics/BlockLength:
27
+ Exclude:
28
+ - 'test/**/*'
29
+ - '*.gemspec'
30
+
31
+ Metrics/CyclomaticComplexity:
32
+ Max: 16
33
+
34
+ Metrics/MethodLength:
35
+ Max: 40
36
+ Exclude:
37
+ - 'test/**/*'
38
+
39
+ Metrics/PerceivedComplexity:
40
+ Max: 16
41
+
42
+ Naming/MethodParameterName:
43
+ Enabled: false
44
+
45
+ Style/GlobalVars:
46
+ Exclude:
47
+ - 'ext/**/*'
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.0.1] - 2023-07-14
4
+
5
+ - Initial release
@@ -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 yoshoku@outlook.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,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ # Specify your gem's dependencies in tiny_linalg.gemspec
6
+ gemspec
7
+
8
+ gem 'minitest', '~> 5.0'
9
+ gem 'rake', '~> 13.0'
10
+ gem 'rake-compiler'
11
+ gem 'rubocop', '~> 1.21'
12
+ gem 'rubocop-minitest', '~> 0.30.0'
13
+ gem 'rubocop-performance', '~> 1.17'
14
+ gem 'rubocop-rake', '~> 0.6.0'
15
+ gem 'yard', github: '/yoshoku/yard', branch: 'jquery-3.6.0'
data/LICENSE.txt ADDED
@@ -0,0 +1,27 @@
1
+ Copyright (c) 2023 Atsushi Tatsuma
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without
5
+ modification, are permitted provided that the following conditions are met:
6
+
7
+ * Redistributions of source code must retain the above copyright notice, this
8
+ list of conditions and the following disclaimer.
9
+
10
+ * Redistributions in binary form must reproduce the above copyright notice,
11
+ this list of conditions and the following disclaimer in the documentation
12
+ and/or other materials provided with the distribution.
13
+
14
+ * Neither the name of the copyright holder nor the names of its
15
+ contributors may be used to endorse or promote products derived from
16
+ this software without specific prior written permission.
17
+
18
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
22
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
data/README.md ADDED
@@ -0,0 +1,99 @@
1
+ # Numo::TinyLinalg
2
+
3
+ [![Build Status](https://github.com/yoshoku/numo-tiny_linalg/actions/workflows/main.yml/badge.svg)](https://github.com/yoshoku/numo-tiny_linalg/actions/workflows/main.yml)
4
+ [![BSD 3-Clause License](https://img.shields.io/badge/License-BSD%203--Clause-orange.svg)](https://github.com/yoshoku/numo-tiny_linalg/blob/main/LICENSE.txt)
5
+
6
+ Numo::TinyLinalg is a subset library from Numo::Linalg consisting only of methods used in Machine Learning algorithms.
7
+
8
+ This gem is still **under development** and may undergo many changes in the future.
9
+
10
+ ## Installation
11
+
12
+ Install the OpenBlas.
13
+
14
+ macOS:
15
+
16
+ ```sh
17
+ $ brew install openblas
18
+ ```
19
+
20
+ Ubuntu:
21
+
22
+ ```sh
23
+ $ sudo apt-get install libopenblas-dev liblapacke-dev
24
+ ```
25
+
26
+ Install the gem and add to the application's Gemfile by executing.
27
+
28
+ macOS:
29
+
30
+ ```sh
31
+ $ bundle config --local build.numo-tiny_linalg "--with-opt-dir=/opt/homebrew/Cellar/openblas/0.3.23/"
32
+ $ bundle add numo-tiny_linalg
33
+ ```
34
+
35
+ Ubuntu:
36
+
37
+ ```sh
38
+ $ bundle add numo-tiny_linalg
39
+ ```
40
+
41
+ If bundler is not being used to manage dependencies, install the gem by executing.
42
+
43
+ macOS:
44
+
45
+ ```sh
46
+ $ gem install numo-tiny_linalg -- --with-opt-dir=/opt/homebrew/Cellar/openblas/0.3.23/
47
+ ```
48
+
49
+ Ubuntu:
50
+
51
+ ```sh
52
+ $ gem install numo-tiny_linalg
53
+ ```
54
+
55
+ ## Usage
56
+
57
+ An example of singular value decomposition.
58
+
59
+ ```ruby
60
+ require 'numo/tiny_linalg'
61
+
62
+ Numo::Linalg = Numo::TinyLinalg unless defined?(Numo::Linalg)
63
+
64
+ x = Numo::DFloat.new(5, 2).rand.dot(Numo::DFloat.new(2, 3).rand)
65
+ # =>
66
+ # Numo::DFloat#shape=[5,3]
67
+ # [[0.104945, 0.0284236, 0.117406],
68
+ # [0.862634, 0.210945, 0.922135],
69
+ # [0.324507, 0.0752655, 0.339158],
70
+ # [0.67085, 0.102594, 0.600882],
71
+ # [0.404631, 0.116868, 0.46644]]
72
+
73
+ s, u, vt = Numo::Linalg.svd(x, job: 'S')
74
+
75
+ z = u.dot(s.diag).dot(vt)
76
+ # =>
77
+ # Numo::DFloat#shape=[5,3]
78
+ # [[0.104945, 0.0284236, 0.117406],
79
+ # [0.862634, 0.210945, 0.922135],
80
+ # [0.324507, 0.0752655, 0.339158],
81
+ # [0.67085, 0.102594, 0.600882],
82
+ # [0.404631, 0.116868, 0.46644]]
83
+
84
+ puts (x - z).abs.max
85
+ # => 4.440892098500626e-16
86
+ ```
87
+
88
+ ## Contributing
89
+
90
+ Bug reports and pull requests are welcome on GitHub at https://github.com/yoshoku/numo-tiny_linalg.
91
+ 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/yoshoku/numo-tiny_linalg/blob/main/CODE_OF_CONDUCT.md).
92
+
93
+ ## Code of Conduct
94
+
95
+ Everyone interacting in the Numo::TinyLinalg project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/yoshoku/numo-tiny_linalg/blob/main/CODE_OF_CONDUCT.md).
96
+
97
+ ## License
98
+
99
+ The gem is available as open source under the terms of the [BSD-3-Clause License](https://opensource.org/licenses/BSD-3-Clause).
data/Rakefile ADDED
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rake/testtask'
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs << 'test'
8
+ t.libs << 'lib'
9
+ t.test_files = FileList['test/**/test_*.rb']
10
+ end
11
+
12
+ require 'rubocop/rake_task'
13
+
14
+ RuboCop::RakeTask.new
15
+
16
+ require 'rake/extensiontask'
17
+
18
+ task build: :compile # rubocop:disable Rake/Desc
19
+
20
+ desc 'Run clang-format'
21
+ task :'clang-format' do
22
+ sh 'clang-format -style=file -Werror --dry-run ext/numo/tiny_linalg/*.cpp ext/numo/tiny_linalg/*.hpp'
23
+ end
24
+
25
+ Rake::ExtensionTask.new('tiny_linalg') do |ext|
26
+ ext.ext_dir = 'ext/numo/tiny_linalg'
27
+ ext.lib_dir = 'lib/numo/tiny_linalg'
28
+ end
29
+
30
+ task default: %i[clobber compile test rubocop]
@@ -0,0 +1 @@
1
+ module.exports = { extends: ['@commitlint/config-conventional'] };
@@ -0,0 +1,75 @@
1
+ namespace TinyLinalg {
2
+ struct DConverter {
3
+ double to_dtype(VALUE val) {
4
+ return NUM2DBL(val);
5
+ }
6
+
7
+ double one() {
8
+ return 1.0;
9
+ }
10
+
11
+ double zero() {
12
+ return 0.0;
13
+ }
14
+ };
15
+
16
+ struct SConverter {
17
+ float to_dtype(VALUE val) {
18
+ return static_cast<float>(NUM2DBL(val));
19
+ }
20
+
21
+ float one() {
22
+ return 1.0f;
23
+ }
24
+
25
+ float zero() {
26
+ return 0.0f;
27
+ }
28
+ };
29
+
30
+ struct ZConverter {
31
+ dcomplex to_dtype(VALUE val) {
32
+ dcomplex z;
33
+ REAL(z) = NUM2DBL(rb_funcall(val, rb_intern("real"), 0));
34
+ IMAG(z) = NUM2DBL(rb_funcall(val, rb_intern("imag"), 0));
35
+ return z;
36
+ }
37
+
38
+ dcomplex one() {
39
+ dcomplex z;
40
+ REAL(z) = 1.0;
41
+ IMAG(z) = 0.0;
42
+ return z;
43
+ }
44
+
45
+ dcomplex zero() {
46
+ dcomplex z;
47
+ REAL(z) = 0.0;
48
+ IMAG(z) = 0.0;
49
+ return z;
50
+ }
51
+ };
52
+
53
+ struct CConverter {
54
+ scomplex to_dtype(VALUE val) {
55
+ scomplex z;
56
+ REAL(z) = NUM2DBL(rb_funcall(val, rb_intern("real"), 0));
57
+ IMAG(z) = NUM2DBL(rb_funcall(val, rb_intern("imag"), 0));
58
+ return z;
59
+ }
60
+
61
+ scomplex one() {
62
+ scomplex z;
63
+ REAL(z) = 1.0f;
64
+ IMAG(z) = 0.0f;
65
+ return z;
66
+ }
67
+
68
+ scomplex zero() {
69
+ scomplex z;
70
+ REAL(z) = 0.0f;
71
+ IMAG(z) = 0.0f;
72
+ return z;
73
+ }
74
+ };
75
+ } // namespace TinyLinalg
@@ -0,0 +1,86 @@
1
+ namespace TinyLinalg {
2
+
3
+ struct DDot {
4
+ double call(const int n, const double* x, const int incx, const double* y, const int incy) {
5
+ return cblas_ddot(n, x, incx, y, incy);
6
+ }
7
+ };
8
+
9
+ struct SDot {
10
+ float call(const int n, const float* x, const int incx, const float* y, const int incy) {
11
+ return cblas_sdot(n, x, incx, y, incy);
12
+ }
13
+ };
14
+
15
+ template <int nary_dtype_id, typename dtype, class BlasFn>
16
+ class Dot {
17
+ public:
18
+ static void define_module_function(VALUE mBlas, const char* modfn_name) {
19
+ rb_define_module_function(mBlas, modfn_name, RUBY_METHOD_FUNC(tiny_linalg_dot), 2);
20
+ };
21
+
22
+ private:
23
+ static void iter_dot(na_loop_t* const lp) {
24
+ dtype* x = (dtype*)NDL_PTR(lp, 0);
25
+ dtype* y = (dtype*)NDL_PTR(lp, 1);
26
+ dtype* d = (dtype*)NDL_PTR(lp, 2);
27
+ const size_t n = NDL_SHAPE(lp, 0)[0];
28
+ dtype ret = BlasFn().call(n, x, 1, y, 1);
29
+ *d = ret;
30
+ };
31
+
32
+ static VALUE tiny_linalg_dot(VALUE self, VALUE x, VALUE y) {
33
+ VALUE nary_dtype = NaryTypes[nary_dtype_id];
34
+
35
+ if (CLASS_OF(x) != nary_dtype) {
36
+ x = rb_funcall(nary_dtype, rb_intern("cast"), 1, x);
37
+ }
38
+ if (!RTEST(nary_check_contiguous(x))) {
39
+ x = nary_dup(x);
40
+ }
41
+ if (CLASS_OF(y) != nary_dtype) {
42
+ y = rb_funcall(nary_dtype, rb_intern("cast"), 1, y);
43
+ }
44
+ if (!RTEST(nary_check_contiguous(y))) {
45
+ y = nary_dup(y);
46
+ }
47
+
48
+ narray_t* x_nary = NULL;
49
+ GetNArray(x, x_nary);
50
+ narray_t* y_nary = NULL;
51
+ GetNArray(y, y_nary);
52
+
53
+ if (NA_NDIM(x_nary) != 1) {
54
+ rb_raise(rb_eArgError, "x must be 1-dimensional");
55
+ return Qnil;
56
+ }
57
+ if (NA_NDIM(y_nary) != 1) {
58
+ rb_raise(rb_eArgError, "y must be 1-dimensional");
59
+ return Qnil;
60
+ }
61
+ if (NA_SIZE(x_nary) == 0) {
62
+ rb_raise(rb_eArgError, "x must not be empty");
63
+ return Qnil;
64
+ }
65
+ if (NA_SIZE(y_nary) == 0) {
66
+ rb_raise(rb_eArgError, "x must not be empty");
67
+ return Qnil;
68
+ }
69
+ if (NA_SIZE(x_nary) != NA_SIZE(y_nary)) {
70
+ rb_raise(rb_eArgError, "x and y must have same size");
71
+ return Qnil;
72
+ }
73
+
74
+ ndfunc_arg_in_t ain[2] = { { nary_dtype, 1 }, { nary_dtype, 1 } };
75
+ size_t shape_out[1] = { 1 };
76
+ ndfunc_arg_out_t aout[1] = { { nary_dtype, 0, shape_out } };
77
+ ndfunc_t ndf = { iter_dot, NO_LOOP | NDF_EXTRACT, 2, 1, ain, aout };
78
+ VALUE ret = na_ndloop(&ndf, 2, x, y);
79
+
80
+ RB_GC_GUARD(x);
81
+ RB_GC_GUARD(y);
82
+ return ret;
83
+ };
84
+ };
85
+
86
+ } // namespace TinyLinalg