complexity_assert 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: 7c1beec0306dbe6397d5e7bea540b2318bcf3e42
4
+ data.tar.gz: 8702d7efa30addc10485249b41da6a5b9d3f0f5d
5
+ SHA512:
6
+ metadata.gz: b61547c46110de77a353b6a8a6098466d67d699cc3fda89f07bdcf6f3eef9baee18768372d151634fe4416129fcbf5f78bbe42531694b1204ee7ab6ee6ffd4a5
7
+ data.tar.gz: 5545bdc7d640c3b1830f341c9e7bb06268e80eff25641085a433a62f8283335da010d4b8a276a11c7f95e219216ac3854e7c719be0519190e881adcaa09997d6
@@ -0,0 +1,77 @@
1
+ # See https://help.github.com/articles/ignoring-files for more about ignoring files.
2
+ #
3
+ # If you find yourself ignoring temporary files generated by your text editor
4
+ # or operating system, you probably want to add a global ignore instead:
5
+ # git config --global core.excludesfile '~/.gitignore_global'
6
+
7
+ *.gem
8
+ *.rbc
9
+ /.config
10
+ /coverage/
11
+ /InstalledFiles
12
+ /pkg/
13
+ /spec/reports/
14
+ /spec/examples.txt
15
+ /test/tmp/
16
+ /test/version_tmp/
17
+ /tmp/
18
+
19
+ ## Specific to RubyMotion:
20
+ .dat*
21
+ .repl_history
22
+ build/
23
+ *.bridgesupport
24
+ build-iPhoneOS/
25
+ build-iPhoneSimulator/
26
+
27
+ ## Specific to RubyMotion (use of CocoaPods):
28
+ #
29
+ # We recommend against adding the Pods directory to your .gitignore. However
30
+ # you should judge for yourself, the pros and cons are mentioned at:
31
+ # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
32
+ #
33
+ # vendor/Pods/
34
+
35
+ ## Documentation cache and generated files:
36
+ /.yardoc/
37
+ /_yardoc/
38
+ /doc/
39
+ /rdoc/
40
+
41
+ ## Environment normalization:
42
+ /.bundle/
43
+ /vendor/bundle
44
+ /lib/bundler/man/
45
+
46
+ # for a library or gem, you might want to ignore these files since the code is
47
+ # intended to run in multiple environments; otherwise, check them in:
48
+ # Gemfile.lock
49
+ # .ruby-version
50
+ # .ruby-gemset
51
+
52
+ # unless supporting rvm < 1.11.0 or doing something fancy, ignore this:
53
+ .rvmrc
54
+
55
+ # Ignore bundler config.
56
+ /.bundle
57
+
58
+ # Ignore the default SQLite database.
59
+ /db/*.sqlite3
60
+ /db/*.sqlite3-journal
61
+
62
+ # Ignore all logfiles and tempfiles.
63
+ /log/*
64
+ /tmp/*
65
+ !/log/.keep
66
+ !/tmp/.keep
67
+
68
+ # Ignore Byebug command history file.
69
+ .byebug_history
70
+
71
+ # Emacs files
72
+ *~
73
+ *#
74
+ .#*
75
+
76
+ # Gemfile.lock
77
+ Gemfile.lock
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.3.1
5
+ before_install: gem install bundler -v 1.12.4
@@ -0,0 +1,92 @@
1
+ * DONE build an assert for a linear algorithm
2
+ ** DONE play with the thing, and print first results
3
+ ** DONE O(x) algorithms : do a simple Ordinary Least Squares
4
+ *** DONE disable GC for the moment
5
+ *** DONE deal with warmup
6
+ **** DONE find a way to know if my new algo is better than the previous one
7
+ ***** DONE have an arena, it generates validating samples, runs the 2 algos, then compares the distance on validation inputs
8
+ ****** DONE compute the rmse
9
+ ****** DONE split the classes to files
10
+ ***** What parameters do I already have ?
11
+ ****** distribution of input sizes
12
+ ****** number of runs
13
+ ****** GC or not
14
+ ****** warmup or not
15
+ **** DONE dump csvs to know how the error changes with the algos
16
+ **** DONE detect whether warmup has a consequence
17
+ ***** It Does. Particularly on small number of runs.
18
+ ***** Even in the same process, we can spot a difference
19
+ ***** Once we know if it is important, let's just use it all the time
20
+ ***** It might be depending on the algorithm ! the number of time some parts are looped over during the run.
21
+ ***** [OK] On our linear search, around 60 warmup rounds are required to reduce variability
22
+ ***** DONE play with different counts of warmup rounds
23
+ ** DONE O(1) : identify the flat slope
24
+ *** DONE not sure a transformation is possible for a regression, otherwise, just do an average
25
+ *** DONE predict is just returning the average
26
+ *** DONE print and compare the results
27
+ *** DONE try with a constant algorithm to test
28
+ ** DONE need to rule out very small coefs, could find a quadratic with a small coef !
29
+ *** 12 times on 55, found linear better than constant, only finds constant 80% of times
30
+ *** to compare RMSE corretly, they shouls be normalized, or using the same data points
31
+ *** DONE reuse the same data for training and validation
32
+ *** If we had an idea of the max size we would like to use it for, we could check that at that size, coeff is still irrelevant
33
+ | algo | slope | y intercept | at 1000 |
34
+ |---------------+-------+-------------+---------|
35
+ | random 5 | E-10 | E-6 | +10% |
36
+ | linear search | E-7 | E-7 | *1000 |
37
+ *** Compute the error we can expect from our data sample, and use it to determine what is 0 or not
38
+ **** Don't know how to do it !
39
+ **** One thing is that negative slopes are zero !
40
+ *** See how it goes with quadratic
41
+ *** Could we use special assertion be_constant(within: constraints)
42
+ *** It's a case of overfitting in fact !
43
+ **** We can give benefit of the doubt to the simpler model.
44
+ **** The more complex model needs to give an RMSE half the one of the simpler model to be selected
45
+ **** This works well on practice with Random5 and LinearSearch
46
+ ** DONE O(x2) : pre-treat with an sqrt before OLS, compare RMSE of both linear and quadratic models to see which one is best
47
+ *** DONE write a quadratic algorithm
48
+ *** DONE add QuadraticComplexityModel
49
+ **** A = Qn2 + C
50
+ **** reg : sqrt(A) = Ln + D
51
+ **** reg : A = L2n2 + 2LDn + D2
52
+ *** DONE select the best and see if it works
53
+ **** Needs to be twice as better as the next one !
54
+ **** have all rmse in order of complexity (constant, linear, quadratic, etc)
55
+ **** go through all starting from the first. Keep the min rmse
56
+ **** if a new rmse is found smaller than half the min, we'll pick this one
57
+ *** Sometimes, if finds O(n) instead of O(n²). Maybe that's not so much of an issue if the assertion checks that it's at worst O(n²)
58
+ ** DONE Add +7 pomodoro to the task title
59
+ ** DONE write the basic rspec integration
60
+ *** DONE define the API we want
61
+ **** class Algorithm; def generate_args(n) ...; def run(args) ...; end;
62
+ **** expect(Algorithm).to be_linear()
63
+ **** expect(Algorithm).to be_constant()
64
+ **** expect(Algorithm).to be_quadratic()
65
+ **** expect(Algorithm).to be_logarithmic()
66
+ **** expect(Algorithm).to be_in(N*LN(N))
67
+ **** expect(Algorithm, warmups: 30, rounds: 20, sizes: [...]).to be_xxx() or expect(Algorithm).to be_xxx(warmups: 30, rounds: 20, sizes: [...])
68
+ *** DONE determine the condition
69
+ **** compare with constant
70
+ ***** simple to do ! not sure it works :
71
+ | algorithm | expect constant | expect linear |
72
+ |-----------+-----------------------------------------------------------------------+---------------------------------------|
73
+ | constant | regress both, find constant is better or linear with very small slope | will find a very small slope |
74
+ | linear | should fail | should pass, but might be quadratic ! |
75
+ ***** checking constant is checking that is not worse than constant eg : linear or log
76
+ ***** they can all be coded with transformations to the timings
77
+ ****** constant : remove the size, keep the timing
78
+ ****** linear : identity
79
+ ****** logarithmic : some kind of exponential
80
+ ****** quadratic : some kind of squar root
81
+ **** We just need to assert that it's at worst O(something).
82
+ *** DONE Get an internet access
83
+ *** DONE fill the readme
84
+ *** DONE Check that the gem is well formed
85
+ *** DONE download rspec
86
+ *** DONE move the files around
87
+ *** DONE write a few specs to make sure it works
88
+ *** DONE see how to create matchers with rspec3
89
+ *** DONE move the matchers to the lib
90
+ *** DONE add a module namespace
91
+ *** DONE add travis
92
+ *** DONE just submit
@@ -0,0 +1 @@
1
+ FROM ruby:2.3
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in complexity_assert.gemspec
4
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 TODO: Write your name
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,109 @@
1
+ # ComplexityAssert
2
+
3
+ They are some performance critical pieces of code that will be executed on huge data sets, which we want to make sure will run fast enough. Unfortunately, enforcing this is not easy, often requiring large scale and slow benchmarks. This [RSpec](http://rspec.info/) library (the result of an experiment to learn machine learning) uses linear regression to determine the time complexity ([Big O notation](http://bigocheatsheet.com/), O(x)) of a piece of code and to check that it is at least as good as what we expect. This does not require huge data sets (only a few large ones) and can be written as any unit test (not as fast though).
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'complexity_assert', :group => [:test]
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install complexity_assert
20
+
21
+ ## Usage
22
+
23
+ In order to test the complexity of an algorithm, you need to provide 2 things :
24
+
25
+ 1. the algorithm
26
+ 2. a way to generate some inputs of varying size
27
+
28
+ For this, you need to provide an object that answers to messages `generate_args` and `run`. Here is an example
29
+
30
+ ``` ruby
31
+ # An adapter class to fit the code to measure in complexity assert
32
+ class LinearSearch
33
+
34
+ # Generate some arguments of a particular size
35
+ def generate_args(size)
36
+ [ Array.new(size) { rand(1..size) }, rand(1..size) ]
37
+ end
38
+
39
+ # Run the code on which we want to assert performance
40
+ def run(array, searched)
41
+ found = false;
42
+ array.each do |element|
43
+ if element == array
44
+ found = true
45
+ end
46
+ end
47
+ found
48
+ end
49
+ end
50
+
51
+ describe "Linear search" do
52
+
53
+ it "performs linearly" do
54
+ # Verify that the code runs in time proportional to the size of its arguments
55
+ expect(LinearSearch.new).to be_linear()
56
+ end
57
+
58
+ end
59
+ ```
60
+
61
+ There are currently 3 matchers :
62
+
63
+ * be_constant
64
+ * be_linear
65
+ * be_quadratic
66
+
67
+ More could be added in the future. Every matcher passes if a faster complexity is identified (`be_linear` willalso pass if the algorithm is detected to be constant).
68
+
69
+ That means that for the moment, `be_quadratic` always passes, but might turn out useful when we add more complex models (Internally, it is quite useful, as it is used to identify that something is more linear than quadratic !).
70
+
71
+ ## Development
72
+
73
+ It uses rubybox, simply clone this repo, build the image, and start on.
74
+
75
+ ```
76
+ git clone ...
77
+ cd ...
78
+ docker-compose build
79
+ docker-compose run rubybox
80
+ ```
81
+
82
+ From then on, you're inside the ruby box, 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.
83
+
84
+ 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).
85
+
86
+ ## Contributing
87
+
88
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/complexity_assert.
89
+
90
+ Here is a quick and uncomplete list of things that could improve this library :
91
+
92
+ * Add Code Climate
93
+ * Refactor some code around the matchers
94
+ * Cache the linear regression (it's done twice)
95
+ * Factorize / find a way to better generate the sizes, or allow the assertion to specify the sizes
96
+ * Allow the assertion to specify the warmup and run rounds
97
+ * Robustness against GC : use gc intensive ruby methods, and see how the regression behaves
98
+ * O(lnx) : pre-treat with exp()
99
+ * O(?lnx) : use exp, then a search for the coefficient (aka polynomial)
100
+ * O(xlnx) : there is no well known inverse for that, we can compute it numericaly though
101
+ * O(x?) : do some kind of dichotomy or search to find the most probable model
102
+ * Estimate how much the assert is deterministic
103
+ * ...
104
+
105
+ As I said, this is still experimental ! Any help is welcome !
106
+
107
+ ## License
108
+
109
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "complexity_assert"
5
+
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
+ IRB.start
@@ -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
@@ -0,0 +1,33 @@
1
+
2
+ # coding: utf-8
3
+ lib = File.expand_path('../lib', __FILE__)
4
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
5
+ require 'complexity_assert/version'
6
+
7
+ Gem::Specification.new do |spec|
8
+ spec.name = "complexity_assert"
9
+ spec.version = ComplexityAssert::VERSION
10
+ spec.authors = ["Philippe Bourgau"]
11
+ spec.email = ["philippe.bourgau@gmail.com"]
12
+
13
+ spec.summary = %q{An experimental rspec library to check the time complexity (Big O(x) notation) of an algorithm.}
14
+ spec.description = %q{They are some performance critical pieces of code that will be executed on huge data sets, which we want to make sure will run fast enough. Unfortunately, enforcing this is not easy, often requiring large scale and slow benchmarks. This rspec library (the result of an experiment to learn machine learning) uses linear regression to determine the time complexity (Big O notation, O(x)) of a piece of code and to check that it is at least as good as what we expect. This does not require huge data sets (only a few large ones) and can be written as any unit test (not as fast though).}
15
+ spec.homepage = "https://github.com/philou/complexity-assert"
16
+ spec.license = "MIT"
17
+
18
+ if spec.respond_to?(:metadata)
19
+ spec.metadata['allowed_push_host'] = "https://rubygems.org"
20
+ else
21
+ raise "RubyGems 2.0 or newer is required to protect against public gem pushes."
22
+ end
23
+
24
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
25
+ spec.bindir = "exe"
26
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
27
+ spec.require_paths = ["lib"]
28
+
29
+ spec.add_dependency "rspec", "~> 3.5"
30
+
31
+ spec.add_development_dependency "bundler", ">= 1.12"
32
+ spec.add_development_dependency "rake", ">= 10.0"
33
+ end
@@ -0,0 +1,11 @@
1
+ rubybox:
2
+ image: ruby:2.3
3
+ command: bash
4
+ working_dir: /usr/src/app
5
+ environment:
6
+ # PORT: 8080
7
+ BUNDLE_PATH: 'vendor/bundle'
8
+ # ports:
9
+ # - '8080:8080'
10
+ volumes:
11
+ - '.:/usr/src/app'
@@ -0,0 +1,14 @@
1
+ require "complexity_assert/version"
2
+
3
+ require "complexity_assert/complexity_validator"
4
+ require "complexity_assert/constant_complexity_model"
5
+ require "complexity_assert/linear_complexity_model"
6
+ require "complexity_assert/quadratic_complexity_model"
7
+ require "complexity_assert/sampler"
8
+ require "complexity_assert/simple_linear_regression"
9
+ require "complexity_assert/warmup_sampler"
10
+ require "complexity_assert/matchers"
11
+
12
+ module ComplexityAssert
13
+ # Your code goes here...
14
+ end
@@ -0,0 +1,26 @@
1
+
2
+ module ComplexityAssert
3
+
4
+ # Generates a sample of execution timings to compute the RMSE of complexity models, in order to valide them
5
+ class ComplexityValidator
6
+
7
+ def initialize(sampler, complexity_models)
8
+ @sampler = sampler
9
+ @complexity_models = complexity_models
10
+ end
11
+
12
+ def rmses
13
+ # TODO these sizes are duplicated with the Matchers
14
+ data = @sampler.run([8,10,12,80,100,120,800,1000,1200],10)
15
+
16
+ @complexity_models.map do |model|
17
+ rmse = Math.sqrt(data.map { |size, real_time|
18
+ (real_time - model.predict_run_time(size))**2
19
+ }.reduce &:+)
20
+ [ model.to_s, rmse]
21
+ end
22
+ end
23
+
24
+ end
25
+
26
+ end
@@ -0,0 +1,21 @@
1
+ module ComplexityAssert
2
+
3
+ # computes the average of the time spent in order to predict future execution time
4
+ class ConstantComplexityModel
5
+
6
+ def analyze(timings)
7
+ sum = timings.map { |size_runtime| size_runtime[1] }.inject &:+
8
+ @average = sum / timings.size
9
+ end
10
+
11
+ def predict_run_time(input_data_size)
12
+ @average
13
+ end
14
+
15
+ def to_s
16
+ 'O(1)'
17
+ end
18
+
19
+ end
20
+
21
+ end
@@ -0,0 +1,21 @@
1
+ module ComplexityAssert
2
+ # Generates a sample of execution timings to run a linear regression in order to predict another execution time
3
+ class LinearComplexityModel
4
+
5
+ def analyze(timings)
6
+ linear_model = SimpleLinearRegression.new(*timings.transpose)
7
+ @slope = linear_model.slope
8
+ @y_intercept = linear_model.y_intercept
9
+ end
10
+
11
+ def predict_run_time(input_data_size)
12
+ @y_intercept + @slope * input_data_size
13
+ end
14
+
15
+ def to_s
16
+ "O(n)"
17
+ end
18
+
19
+ end
20
+
21
+ end
@@ -0,0 +1,73 @@
1
+ require 'rspec/expectations'
2
+
3
+ module ComplexityAssert
4
+
5
+ class Matchers
6
+ # complexity_errors : [["big O notation", rmse score], ...], in order of complexity costs
7
+ def self.best_complexity_by_rmse(complexity_errors)
8
+ best = complexity_errors.first
9
+ complexity_errors.drop(1).each do |comp_error|
10
+
11
+ # we favor simpler complexities to fight overfitting from more elaborate models
12
+ if comp_error[1] < best[1] / 2
13
+ best = comp_error
14
+ end
15
+ end
16
+ best[0]
17
+ end
18
+
19
+ private
20
+
21
+ def self.identify_complexity(algo)
22
+ sampler = WarmupSampler.new(Sampler.new(algo),60)
23
+ # These sizes are duplicated with the ComplexityValidator
24
+ timings = sampler.run([8,10,12,80,100,120,800,1000,1200], 10)
25
+ complexity_models = [
26
+ ConstantComplexityModel.new(),
27
+ LinearComplexityModel.new(),
28
+ QuadraticComplexityModel.new()
29
+ ]
30
+
31
+ complexity_models.each { |model| model.analyze(timings) }
32
+ validator = ComplexityValidator.new(sampler, complexity_models)
33
+
34
+ rmses = validator.rmses
35
+
36
+ best_complexity_by_rmse(rmses)
37
+ end
38
+ end
39
+
40
+ # TODO
41
+ # - factorize code of these matchers
42
+ # - stop using the "O(x)" magic constants (they are the XXXComplexityModel.to_s)
43
+
44
+ RSpec::Matchers.define :be_constant do
45
+ match do |actual|
46
+ @actual_complexity = Matchers.identify_complexity(actual)
47
+ ["O(1)"].include?(@actual_complexity)
48
+ end
49
+ failure_message do |actual|
50
+ "expect that #{actual} would have a complexity equal or better than O(1) but was #{@actual_complexity}"
51
+ end
52
+ end
53
+
54
+ RSpec::Matchers.define :be_linear do
55
+ match do |actual|
56
+ @actual_complexity = Matchers.identify_complexity(actual)
57
+ ["O(1)","O(n)"].include?(@actual_complexity)
58
+ end
59
+ failure_message do |actual|
60
+ "expect that #{actual} would have a complexity equal or better than O(n) but was #{@actual_complexity}"
61
+ end
62
+ end
63
+
64
+ RSpec::Matchers.define :be_quadratic do
65
+ match do |actual|
66
+ @actual_complexity = Matchers.identify_complexity(actual)
67
+ ["O(1)","O(n)","O(n^2)"].include?(@actual_complexity)
68
+ end
69
+ failure_message do |actual|
70
+ "expect that #{actual} would have a complexity equal or better than O(n^2) but was #{@actual_complexity}"
71
+ end
72
+ end
73
+ end
@@ -0,0 +1,30 @@
1
+ module ComplexityAssert
2
+
3
+ # Generates a sample of execution timings to run a linear regression in order to predict another execution time
4
+ class QuadraticComplexityModel
5
+
6
+ # timings : [[size,timing], ...]
7
+ def analyze(timings)
8
+ sqrt_timings = timings.map do |size, timing|
9
+ [size, Math.sqrt(timing)]
10
+ end
11
+ linear_model = SimpleLinearRegression.new(*sqrt_timings.transpose)
12
+ sqrt_slope = linear_model.slope
13
+ sqrt_y_intercept = linear_model.y_intercept
14
+
15
+ @quadratic = sqrt_slope * sqrt_slope
16
+ @slope = 2* sqrt_slope * sqrt_y_intercept
17
+ @y_intercept = sqrt_y_intercept * sqrt_y_intercept
18
+ end
19
+
20
+ def predict_run_time(input_data_size)
21
+ @y_intercept + @slope * input_data_size + @quadratic * input_data_size * input_data_size
22
+ end
23
+
24
+ def to_s
25
+ 'O(n^2)'
26
+ end
27
+
28
+ end
29
+
30
+ end
@@ -0,0 +1,30 @@
1
+ require "benchmark"
2
+
3
+ module ComplexityAssert
4
+
5
+ class Sampler
6
+ def initialize(algo_under_test)
7
+ @algo_under_test = algo_under_test
8
+ end
9
+
10
+ # Generates an array of sample data points
11
+ # [ [input size, real time], ... ]
12
+ def run(sizes, rounds)
13
+ sizes.flat_map { |size | run_for_size(size, rounds) }
14
+ end
15
+
16
+ private
17
+
18
+ def run_for_size(size, rounds)
19
+ Array.new(rounds) do
20
+ args = @algo_under_test.generate_args(size)
21
+ GC.disable
22
+ real_time = Benchmark.realtime { @algo_under_test.run(*args) }
23
+ GC.enable
24
+ [size, real_time]
25
+ end
26
+ end
27
+
28
+ end
29
+
30
+ end
@@ -0,0 +1,40 @@
1
+
2
+ module ComplexityAssert
3
+
4
+ # Performs basic linear regression on a set of points
5
+ class SimpleLinearRegression
6
+ def initialize(xs, ys)
7
+ @xs, @ys = xs, ys
8
+ if @xs.length != @ys.length
9
+ raise "Unbalanced data. xs need to be same length as ys"
10
+ end
11
+ end
12
+
13
+ # TODO cache all these instead of computing it every time
14
+
15
+ def y_intercept
16
+ mean(@ys) - (slope * mean(@xs))
17
+ end
18
+
19
+ def slope
20
+ x_mean = mean(@xs)
21
+ y_mean = mean(@ys)
22
+
23
+ numerator = (0...@xs.length).reduce(0) do |sum, i|
24
+ sum + ((@xs[i] - x_mean) * (@ys[i] - y_mean))
25
+ end
26
+
27
+ denominator = @xs.reduce(0) do |sum, x|
28
+ sum + ((x - x_mean) ** 2)
29
+ end
30
+
31
+ (numerator / denominator)
32
+ end
33
+
34
+ def mean(values)
35
+ total = values.reduce(0) { |sum, x| x + sum }
36
+ Float(total) / Float(values.length)
37
+ end
38
+ end
39
+
40
+ end
@@ -0,0 +1,3 @@
1
+ module ComplexityAssert
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,15 @@
1
+ module ComplexityAssert
2
+
3
+ # A sampler wrapper that does some warmup on the algo under test
4
+ class WarmupSampler
5
+ def initialize(sampler, rounds)
6
+ @sampler = sampler
7
+ @rounds = rounds
8
+ end
9
+
10
+ def run(sizes, count)
11
+ _warmup_data = @sampler.run(sizes,@rounds)
12
+ @sampler.run(sizes,count)
13
+ end
14
+ end
15
+ end
Binary file
metadata ADDED
@@ -0,0 +1,120 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: complexity_assert
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Philippe Bourgau
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2017-02-24 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rspec
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '3.5'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '3.5'
27
+ - !ruby/object:Gem::Dependency
28
+ name: bundler
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '1.12'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '1.12'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '10.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '10.0'
55
+ description: They are some performance critical pieces of code that will be executed
56
+ on huge data sets, which we want to make sure will run fast enough. Unfortunately,
57
+ enforcing this is not easy, often requiring large scale and slow benchmarks. This
58
+ rspec library (the result of an experiment to learn machine learning) uses linear
59
+ regression to determine the time complexity (Big O notation, O(x)) of a piece of
60
+ code and to check that it is at least as good as what we expect. This does not require
61
+ huge data sets (only a few large ones) and can be written as any unit test (not
62
+ as fast though).
63
+ email:
64
+ - philippe.bourgau@gmail.com
65
+ executables: []
66
+ extensions: []
67
+ extra_rdoc_files: []
68
+ files:
69
+ - ".gitignore"
70
+ - ".rspec"
71
+ - ".travis.yml"
72
+ - DayBook.org
73
+ - Dockerfile
74
+ - Gemfile
75
+ - LICENSE
76
+ - LICENSE.txt
77
+ - README.md
78
+ - Rakefile
79
+ - bin/console
80
+ - bin/setup
81
+ - complexity_assert.gemspec
82
+ - docker-compose.yml
83
+ - lib/complexity_assert.rb
84
+ - lib/complexity_assert/complexity_validator.rb
85
+ - lib/complexity_assert/constant_complexity_model.rb
86
+ - lib/complexity_assert/linear_complexity_model.rb
87
+ - lib/complexity_assert/matchers.rb
88
+ - lib/complexity_assert/quadratic_complexity_model.rb
89
+ - lib/complexity_assert/sampler.rb
90
+ - lib/complexity_assert/simple_linear_regression.rb
91
+ - lib/complexity_assert/version.rb
92
+ - lib/complexity_assert/warmup_sampler.rb
93
+ - visu.ods
94
+ homepage: https://github.com/philou/complexity-assert
95
+ licenses:
96
+ - MIT
97
+ metadata:
98
+ allowed_push_host: https://rubygems.org
99
+ post_install_message:
100
+ rdoc_options: []
101
+ require_paths:
102
+ - lib
103
+ required_ruby_version: !ruby/object:Gem::Requirement
104
+ requirements:
105
+ - - ">="
106
+ - !ruby/object:Gem::Version
107
+ version: '0'
108
+ required_rubygems_version: !ruby/object:Gem::Requirement
109
+ requirements:
110
+ - - ">="
111
+ - !ruby/object:Gem::Version
112
+ version: '0'
113
+ requirements: []
114
+ rubyforge_project:
115
+ rubygems_version: 2.6.4
116
+ signing_key:
117
+ specification_version: 4
118
+ summary: An experimental rspec library to check the time complexity (Big O(x) notation)
119
+ of an algorithm.
120
+ test_files: []