silicium 0.0.14 → 0.0.22

Sign up to get free protection for your applications and to get access to all the features.
Files changed (109) hide show
  1. checksums.yaml +4 -4
  2. data/.codeclimate.yml +4 -0
  3. data/.gitignore +13 -11
  4. data/.rakeTasks +8 -0
  5. data/.travis.yml +17 -3
  6. data/CODE_OF_CONDUCT.md +74 -74
  7. data/Gemfile +8 -4
  8. data/LICENSE.txt +21 -21
  9. data/Makefile +269 -0
  10. data/README.md +588 -44
  11. data/Rakefile +17 -10
  12. data/bin/console +14 -14
  13. data/bin/setup +8 -8
  14. data/docs/Object.html +117 -0
  15. data/docs/README_md.html +142 -0
  16. data/docs/Silicium/Combinatorics.html +270 -0
  17. data/docs/Silicium/Dice/Polyhedron.html +315 -0
  18. data/docs/Silicium/Dice/PolyhedronSet.html +321 -0
  19. data/docs/Silicium/Dice.html +99 -0
  20. data/docs/Silicium/Error.html +106 -0
  21. data/docs/Silicium/Geometry/Line2dCanon.html +243 -0
  22. data/docs/Silicium/Geometry/VariablesOrderException.html +106 -0
  23. data/docs/Silicium/Geometry.html +940 -0
  24. data/docs/Silicium/GraphVisualizer.html +226 -0
  25. data/docs/Silicium/Graphs/GraphError.html +106 -0
  26. data/docs/Silicium/Graphs/OrientedGraph.html +901 -0
  27. data/docs/Silicium/Graphs/UnorientedGraph.html +237 -0
  28. data/docs/Silicium/Graphs.html +374 -0
  29. data/docs/Silicium/IntegralDoesntExistError.html +106 -0
  30. data/docs/Silicium/NumericalIntegration.html +521 -0
  31. data/docs/Silicium/Optimization.html +629 -0
  32. data/docs/Silicium/Plotter/Image.html +297 -0
  33. data/docs/Silicium/Plotter.html +186 -0
  34. data/docs/Silicium.html +101 -0
  35. data/docs/created.rid +9 -0
  36. data/docs/css/fonts.css +167 -0
  37. data/docs/css/rdoc.css +619 -0
  38. data/docs/fonts/Lato-Light.ttf +0 -0
  39. data/docs/fonts/Lato-LightItalic.ttf +0 -0
  40. data/docs/fonts/Lato-Regular.ttf +0 -0
  41. data/docs/fonts/Lato-RegularItalic.ttf +0 -0
  42. data/docs/fonts/SourceCodePro-Bold.ttf +0 -0
  43. data/docs/fonts/SourceCodePro-Regular.ttf +0 -0
  44. data/docs/images/add.png +0 -0
  45. data/docs/images/arrow_up.png +0 -0
  46. data/docs/images/brick.png +0 -0
  47. data/docs/images/brick_link.png +0 -0
  48. data/docs/images/bug.png +0 -0
  49. data/docs/images/bullet_black.png +0 -0
  50. data/docs/images/bullet_toggle_minus.png +0 -0
  51. data/docs/images/bullet_toggle_plus.png +0 -0
  52. data/docs/images/date.png +0 -0
  53. data/docs/images/delete.png +0 -0
  54. data/docs/images/find.png +0 -0
  55. data/docs/images/loadingAnimation.gif +0 -0
  56. data/docs/images/macFFBgHack.png +0 -0
  57. data/docs/images/package.png +0 -0
  58. data/docs/images/page_green.png +0 -0
  59. data/docs/images/page_white_text.png +0 -0
  60. data/docs/images/page_white_width.png +0 -0
  61. data/docs/images/plugin.png +0 -0
  62. data/docs/images/ruby.png +0 -0
  63. data/docs/images/tag_blue.png +0 -0
  64. data/docs/images/tag_green.png +0 -0
  65. data/docs/images/transparent.png +0 -0
  66. data/docs/images/wrench.png +0 -0
  67. data/docs/images/wrench_orange.png +0 -0
  68. data/docs/images/zoom.png +0 -0
  69. data/docs/index.html +134 -0
  70. data/docs/js/darkfish.js +84 -0
  71. data/docs/js/navigation.js +105 -0
  72. data/docs/js/navigation.js.gz +0 -0
  73. data/docs/js/search.js +110 -0
  74. data/docs/js/search_index.js +1 -0
  75. data/docs/js/search_index.js.gz +0 -0
  76. data/docs/js/searcher.js +229 -0
  77. data/docs/js/searcher.js.gz +0 -0
  78. data/docs/table_of_contents.html +697 -0
  79. data/lib/algebra.rb +452 -0
  80. data/lib/algebra_diff.rb +258 -0
  81. data/lib/geometry/figure.rb +62 -0
  82. data/lib/geometry.rb +290 -0
  83. data/lib/geometry3d.rb +270 -0
  84. data/lib/graph/dfs.rb +41 -0
  85. data/lib/graph/kruskal.rb +36 -0
  86. data/lib/graph/scc.rb +97 -0
  87. data/lib/graph.rb +350 -0
  88. data/lib/graph_visualizer.rb +286 -0
  89. data/lib/ml_algorithms.rb +181 -0
  90. data/lib/numerical_integration.rb +184 -0
  91. data/lib/optimization.rb +208 -0
  92. data/lib/plotter.rb +258 -0
  93. data/lib/polynomial_division.rb +132 -0
  94. data/lib/polynomial_interpolation.rb +94 -0
  95. data/lib/regression.rb +120 -0
  96. data/lib/silicium/adding.rb +37 -0
  97. data/lib/silicium/conversions.rb +23 -0
  98. data/lib/silicium/multi.rb +82 -0
  99. data/lib/silicium/sparse.rb +76 -0
  100. data/lib/silicium/sugar.rb +37 -0
  101. data/lib/silicium/trans.rb +26 -0
  102. data/lib/silicium/version.rb +3 -3
  103. data/lib/silicium.rb +29 -6
  104. data/lib/theory_of_probability.rb +240 -0
  105. data/lib/topological_sort.rb +50 -0
  106. data/oriented_graph.png +0 -0
  107. data/plot.png +0 -0
  108. data/silicium.gemspec +4 -3
  109. metadata +122 -12
@@ -0,0 +1,184 @@
1
+ module Silicium
2
+ class IntegralDoesntExistError < RuntimeError; end
3
+
4
+ class NumberofIterOutofRangeError < RuntimeError; end
5
+
6
+ ##
7
+ # A class providing numerical integration methods
8
+ class NumericalIntegration
9
+
10
+ ##
11
+ # Computes integral by the 3/8 rule
12
+ # from +a+ to +b+ of +block+ with accuracy +eps+
13
+ def self.three_eights_integration(a, b, eps = 0.0001, &block)
14
+ wrapper_method([a, b], eps, :three_eights_integration_n, &block)
15
+ end
16
+
17
+ ##
18
+ # Computes integral by the 3/8 rule
19
+ # from +a+ to +b+ of +block+ with +n+ segmentations
20
+ def self.three_eights_integration_n(a, b, n, &block)
21
+ dx = (b - a) / n.to_f
22
+ result = 0
23
+ x = a
24
+ n.times do
25
+ result +=
26
+ (block.call(x) + 3 * block.call((2 * x + x + dx) / 3.0) +
27
+ 3 * block.call((x + 2 * (x + dx)) / 3.0) + block.call(x + dx)) / 8.0 * dx
28
+ x += dx
29
+ end
30
+ result
31
+ end
32
+
33
+ ##
34
+ # Computes integral by the Simpson's rule
35
+ # from +a+ to +b+ of +block+ with +n+ segmentations
36
+ def self.simpson_integration_with_a_segment(a, b, n, &block)
37
+ dx = (b - a) / n.to_f
38
+ result = 0
39
+ i = 0
40
+ while i < n
41
+ result += (block.call(a + i * dx) + 4 * block.call(((a + i * dx) +
42
+ (a + (i + 1) * dx)) / 2.0) + block.call(a + (i + 1) * dx)) / 6.0 * dx
43
+ i += 1
44
+ end
45
+ result
46
+ end
47
+
48
+ ##
49
+ # Computes integral by the Simpson's rule
50
+ # from +a+ to +b+ of +block+ with accuracy +eps+
51
+ def self.simpson_integration(a, b, eps = 0.0001, &block)
52
+ wrapper_method([a, b], eps, :simpson_integration_with_a_segment, &block)
53
+ end
54
+
55
+ ##
56
+ # Computes integral by the Left Rectangles method
57
+ # from +a+ to +b+ of +block+ with accuracy +eps+
58
+ def self.left_rect_integration(a, b, eps = 0.0001, &block)
59
+ wrapper_method([a, b], eps, :left_rect_integration_n, &block)
60
+ end
61
+
62
+ ##
63
+ # Computes integral by the Left Rectangles method
64
+ # from +a+ to +b+ of +block+ with +n+ segmentations
65
+ def self.left_rect_integration_n(a, b, n, &block)
66
+ dx = (b - a) / n.to_f
67
+ amount_calculation(a, [0, n], dx, &block)
68
+ end
69
+
70
+ ##
71
+ # Computes integral by the Right Rectangles method
72
+ # from +a+ to +b+ of +block+ with accuracy +eps+
73
+ def self.right_rect_integration(a, b, eps = 0.0001, &block)
74
+ wrapper_method([a, b], eps, :right_rect_integration_n, &block)
75
+ end
76
+
77
+ ##
78
+ # Computes integral by the Right Rectangles method
79
+ # from +a+ to +b+ of +block+ with +n+ segmentations
80
+ def self.right_rect_integration_n(a, b, n, &block)
81
+ dx = (b - a) / n.to_f
82
+ amount_calculation(a, [1, n + 1], dx, &block)
83
+ end
84
+
85
+ ##
86
+ # Computes integral by the Middle Rectangles method
87
+ # from +a+ to +b+ of +block+ with +n+ segmentations
88
+ def self.middle_rectangles_with_a_segment(a, b, n, &block)
89
+ dx = (b - a) / n.to_f
90
+ result = 0
91
+ i = 0
92
+ n.times do
93
+ result += block.call(a + dx * (i + 1 / 2)) * dx
94
+ i += 1
95
+ end
96
+ result
97
+ end
98
+
99
+ ##
100
+ # Computes integral by the Middle Rectangles method
101
+ # from +a+ to +b+ of +block+ with accuracy +eps+
102
+ def self.middle_rectangles(a, b, eps = 0.0001, &block)
103
+ wrapper_method([a, b], eps, :middle_rectangles_with_a_segment, &block)
104
+ end
105
+
106
+ ##
107
+ # Computes integral by the Trapezoid method
108
+ # from +a+ to +b+ of +block+ with +n+ segmentations
109
+ def self.trapezoid_with_a_segment(a, b, n, &block)
110
+ dx = (b - a) / n.to_f
111
+ result = 0
112
+ i = 1
113
+ (n - 1).times do
114
+ result += block.call(a + dx * i)
115
+ i += 1
116
+ end
117
+ result += (block.call(a) + block.call(b)) / 2.0
118
+ result * dx
119
+ end
120
+
121
+ ##
122
+ # Computes integral by the Trapezoid method
123
+ # from +a+ to +b+ of +block+ with accuracy +eps+
124
+ def self.trapezoid(a, b, eps = 0.0001, &block)
125
+ wrapper_method([a, b], eps, :trapezoid_with_a_segment ,&block)
126
+ end
127
+
128
+ private
129
+
130
+ ##
131
+ # Wrapper method for num_integratons methods
132
+ # @param [Array] a_b integration range
133
+ # @param [Numeric] eps
134
+ # @param [Proc] proc - integration Proc
135
+ # @param [Block] block - integrated function as Block
136
+ def self.wrapper_method(a_b, eps, method_name, &block)
137
+ n = 1
138
+ max_it = 10_000
139
+ begin
140
+ begin
141
+ result = send(method_name, a_b[0], a_b[1], n, &block)
142
+ check_value(result)
143
+ n *= 5
144
+ raise NumberofIterOutofRangeError if n > max_it
145
+ result1 = send(method_name, a_b[0], a_b[1], n, &block)
146
+ check_value(result1)
147
+ end until (result - result1).abs < eps
148
+
149
+ rescue Math::DomainError
150
+ raise IntegralDoesntExistError, 'Domain error in math function'
151
+ rescue ZeroDivisionError
152
+ raise IntegralDoesntExistError, 'Divide by zero'
153
+ end
154
+ (result + result1) / 2.0
155
+ end
156
+
157
+ def self.check_value(value)
158
+ if value.nan?
159
+ raise IntegralDoesntExistError, 'We have not-a-number result :('
160
+ end
161
+ if value == Float::INFINITY
162
+ raise IntegralDoesntExistError, 'We have infinity :('
163
+ end
164
+ end
165
+
166
+ ##
167
+ # Computes the sum of n rectangles on a segment
168
+ # of length dx at points of the form a + i * dx
169
+ # @param [Numeric] a - first division point
170
+ # @param [Array] i_n number of divisions
171
+ # @param [Numeric] dx - length of integration segment
172
+ # @param [Block] block - integrated function as Block
173
+ def self.amount_calculation(a, i_n, dx, &block)
174
+ result = 0
175
+ while i_n[0] < i_n[1]
176
+ result += block.call(a + i_n[0] * dx)
177
+ i_n[0] += 1
178
+ end
179
+ result * dx
180
+ end
181
+ end
182
+ end
183
+
184
+
@@ -0,0 +1,208 @@
1
+ require 'fast_matrix'
2
+
3
+ module Silicium
4
+ module Optimization
5
+ # reflector function
6
+ def re_lu(x)
7
+ x.negative? ? 0 : x
8
+ end
9
+
10
+ # sigmoid function
11
+ def sigmoid(x)
12
+ 1.0 / (1 + Math.exp(-x))
13
+ end
14
+
15
+ # integrating using method Monte Carlo (f - function, a, b - integrating limits, n - amount of random numbers)
16
+ def integrating_Monte_Carlo_base(a, b, n = 100000, &block)
17
+ res = 0
18
+ range = a..b.to_f
19
+ (0..n).each do
20
+ x = rand(range)
21
+ res += (b - a) * 1.0 / n * block.call(x)
22
+ end
23
+ res
24
+ end
25
+
26
+ # return true if array is sorted
27
+ def sorted?(a)
28
+ return false if a.nil?
29
+
30
+ for i in 0..a.length - 2
31
+ return false if (a[i + 1] < a[i])
32
+ end
33
+ true
34
+ end
35
+
36
+ # fastest(but it is not exactly) sort, modify sequance
37
+ def bogosort!(a)
38
+ raise ArgumentError, "Nil array in bogosort" if a.nil?
39
+
40
+ a.shuffle! until sorted?(a)
41
+ a
42
+ end
43
+
44
+ # fastest(but it is not exactly) sort
45
+ def bogosort(a)
46
+ raise ArgumentError, "Nil array in bogosort" if a.nil?
47
+
48
+ crutch = a
49
+ (crutch = a.shuffle) until sorted?(crutch)
50
+ crutch
51
+ end
52
+
53
+ # calculate current accuracy in Hook - Jeeves method
54
+ def accuracy(step)
55
+ acc = 0
56
+ step.each { |a| acc += a * a }
57
+ Math.sqrt(acc)
58
+ end
59
+
60
+ # do one Hook - Jeeves step
61
+ def hook_jeeves_step(x, i, step, &block)
62
+ x[i] += step[i]
63
+ tmp1 = block.call(x)
64
+ x[i] = x[i] - 2 * step[i]
65
+ tmp2 = block.call(x)
66
+ if (tmp1 > tmp2)
67
+ cur_f = tmp2
68
+ else
69
+ x[i] = x[i] + step[i] * 2
70
+ cur_f = tmp1
71
+ end
72
+ [cur_f, x[i]]
73
+ end
74
+
75
+ # switch step if current func value > previous func value
76
+ def switch_step(cur_f, prev_f, step, i)
77
+ return step[i] / 2.0 if cur_f >= prev_f # you can switch 2.0 on something else
78
+
79
+ step[i]
80
+ end
81
+
82
+ # Hook - Jeeves method for find minimum point (x - array of start variables, step - step of one iteration, eps - allowable error, alfa - slowdown of step,
83
+ # block - function which takes array x, WAENING function doesn't control correctness of input
84
+ def hook_jeeves(x, step, eps = 0.1, &block)
85
+ prev_f = block.call(x)
86
+ acc = accuracy(step)
87
+ while (acc > eps)
88
+ for i in 0..x.length - 1
89
+ tmp = hook_jeeves_step(x, i, step, &block)
90
+ cur_f = tmp[0]
91
+ x[i] = tmp[1]
92
+ step[i] = switch_step(cur_f, prev_f, step, i)
93
+ prev_f = cur_f
94
+ end
95
+ acc = accuracy(step)
96
+ end
97
+ x
98
+ end
99
+
100
+ # find centr of interval
101
+ def middle(a, b)
102
+ (a + b) / 2.0
103
+ end
104
+
105
+ # do one half division step
106
+ def half_division_step(a, b, c, &block)
107
+ if (block.call(a) * block.call(c)).negative?
108
+ b = c
109
+ c = middle(a, c)
110
+ else
111
+ a = c
112
+ c = middle(b, c)
113
+ end
114
+ [a, b, c]
115
+ end
116
+
117
+ # find root in [a, b], if he exist, if number of iterations > iters -> error
118
+ def half_division(a, b, eps = 0.001, &block)
119
+ iters = 1000000
120
+ c = middle(a, b)
121
+ while (block.call(c).abs) > eps
122
+ tmp = half_division_step(a, b, c, &block)
123
+ a = tmp[0]
124
+ b = tmp[1]
125
+ c = tmp[2]
126
+ iters -= 1
127
+ raise RuntimeError, 'Root not found! Check does he exist, or change eps or iters' if iters == 0
128
+ end
129
+ c
130
+ end
131
+
132
+ # Find determinant 3x3 matrix
133
+ def determinant_sarryus(matrix)
134
+ raise ArgumentError, "Matrix size must be 3x3" if (matrix.row_count != 3 || matrix.column_count != 3)
135
+
136
+ matrix[0, 0] * matrix[1, 1] * matrix[2, 2] + matrix[0, 1] * matrix[1, 2] * matrix[2, 0] + matrix[0, 2] * matrix[1, 0] * matrix[2, 1] -
137
+ matrix[0, 2] * matrix[1, 1] * matrix[2, 0] - matrix[0, 0] * matrix[1, 2] * matrix[2, 1] - matrix[0, 1] * matrix[1, 0] * matrix[2, 2]
138
+ end
139
+
140
+ # return probability to accept
141
+ def accept_annealing(z, min, t, d)
142
+ p = (min - z) / (d * t * 1.0)
143
+ Math.exp(p)
144
+ end
145
+
146
+ # do one annealing step
147
+ def annealing_step(x, min_board, max_board)
148
+ x += rand(-0.5..0.5)
149
+ x = max_board if (x > max_board)
150
+ x = min_board if (x < min_board)
151
+ x
152
+ end
153
+
154
+ # update current min and xm if cond
155
+ def annealing_cond(z, min, t, d)
156
+ (z < min || accept_annealing(z, min, t, d) > rand(0.0..1.0))
157
+ end
158
+
159
+ # Annealing method to find min of function with one argument, between min_board max_board,
160
+ def simulated_annealing(min_board, max_board, t = 10000, &block)
161
+ d = Math.exp(-5) # Constant of annealing
162
+ x = rand(min_board * 1.0..max_board * 1.0)
163
+ xm = x
164
+ min = block.call(x)
165
+ while (t > 0.00001)
166
+ x = xm
167
+ x = annealing_step(x, min_board, max_board)
168
+ z = block.call(x)
169
+ if (annealing_cond(z, min, t, d))
170
+ min = z
171
+ xm = x
172
+ end
173
+ t *= 0.9999 # tempreture drops
174
+ end
175
+ xm
176
+ end
177
+
178
+ # Fast multiplication of num1 and num2.
179
+ def karatsuba(num1, num2)
180
+ return num1 * num2 if num1 < 10 || num2 < 10
181
+
182
+ max_size = [num1.to_s.length, num2.to_s.length].max
183
+
184
+ first_half1, last_half1 = make_equal(num1, max_size)
185
+ first_half2, last_half2 = make_equal(num2, max_size)
186
+
187
+ t0 = karatsuba(last_half1, last_half2)
188
+ t1 = karatsuba((first_half1 + last_half1), (first_half2 + last_half2))
189
+ t2 = karatsuba(first_half1, first_half2)
190
+
191
+ compute_karatsuba(t0, t1, t2, max_size / 2)
192
+ end
193
+
194
+ private
195
+
196
+ # Helper for karatsuba method. Divides num into two halves.
197
+ def make_equal(num, size)
198
+ mid = (size + 1) / 2
199
+ string = num.to_s.rjust(size, '0')
200
+ [string.slice(0...mid).to_i, string.slice(mid..-1).to_i]
201
+ end
202
+
203
+ # Helper for karatsuba method. Computes the result of karatsuba's multiplication.
204
+ def compute_karatsuba(tp0, tp1, tp2, num)
205
+ tp2 * 10**(2 * num) + ((tp1 - tp0 - tp2) * 10**num) + tp0
206
+ end
207
+ end
208
+ end
data/lib/plotter.rb ADDED
@@ -0,0 +1,258 @@
1
+ require 'chunky_png'
2
+ require 'ruby2d'
3
+
4
+ module Silicium
5
+ ##
6
+ # Plotter module
7
+ # Module contains classes, that are different kinds of plain plotters
8
+ #
9
+ module Plotter
10
+ include Silicium::Geometry
11
+ # The Color module defines methods for handling colors. Within the Plotter
12
+ # library, the concepts of pixels and colors are both used, and they are
13
+ # both represented by a Integer.
14
+ #
15
+ # Pixels/colors are represented in RGBA components. Each of the four
16
+ # components is stored with a depth of 8 bits (maximum value = 255 =
17
+ # {Plotter::Color::MAX}). Together, these components are stored in a 4-byte
18
+ # Integer.
19
+ #
20
+ # A color will always be represented using these 4 components in memory.
21
+ # When the image is encoded, a more suitable representation can be used
22
+ # (e.g. rgb, grayscale, palette-based), for which several conversion methods
23
+ # are provided in this module.
24
+ module Color
25
+ extend ChunkyPNG::Color
26
+ include ChunkyPNG::Color
27
+ end
28
+ ##
29
+ # Factory method to return a color value, based on the arguments given.
30
+ #
31
+ # @overload Color(r, g, b, a)
32
+ # @param (see ChunkyPNG::Color.rgba)
33
+ # @return [Integer] The rgba color value.
34
+ #
35
+ # @overload Color(r, g, b)
36
+ # @param (see ChunkyPNG::Color.rgb)
37
+ # @return [Integer] The rgb color value.
38
+ #
39
+ # @overload Color(hex_value, opacity = nil)
40
+ # @param (see ChunkyPNG::Color.from_hex)
41
+ # @return [Integer] The hex color value, with the opacity applied if one
42
+ # was given.
43
+ #
44
+ # @overload Color(color_name, opacity = nil)
45
+ # @param (see ChunkyPNG::Color.html_color)
46
+ # @return [Integer] The hex color value, with the opacity applied if one
47
+ # was given.
48
+ #
49
+ # @overload Color(color_value, opacity = nil)
50
+ # @param [Integer, :to_i] The color value.
51
+ # @return [Integer] The color value, with the opacity applied if one was
52
+ # given.
53
+ #
54
+ # @return [Integer] The determined color value as RGBA integer.
55
+ # @raise [ArgumentError] if the arguments weren't understood as a color.
56
+ def color(*args)
57
+ case args.length
58
+ when 1 then Color.parse(args.first)
59
+ when 2 then (Color.parse(args.first) & 0xffffff00) | args[1].to_i
60
+ when 3 then Color.rgb(*args)
61
+ when 4 then Color.rgba(*args)
62
+ else raise ArgumentError,
63
+ "Don't know how to create a color from #{args.inspect}!"
64
+ end
65
+ end
66
+ ##
67
+ # A class representing canvas for plotting bar charts and function graphs
68
+ class Image
69
+ include Silicium::Geometry
70
+ ##
71
+ # Creates a new plot with chosen +width+ and +height+ parameters
72
+ # with background colored +bg_color+
73
+ def initialize(width, height, bg_color = Color::TRANSPARENT, padding = 5)
74
+ @image = ChunkyPNG::Image.new(width, height, bg_color)
75
+ @padding = padding
76
+ end
77
+
78
+ def rectangle(left_upper, width, height, color)
79
+ x_end = left_upper.x + width - 1
80
+ y_end = left_upper.y + height - 1
81
+ (left_upper.x..x_end).each do |i|
82
+ (left_upper.y..y_end).each { |j| @image[i, j] = color }
83
+ end
84
+ end
85
+
86
+ private
87
+
88
+ def draw_axis(min, dpu, axis_color)
89
+ # Axis OX
90
+ rectangle(Point.new(
91
+ @padding,
92
+ @image.height - @padding - (min.y.abs * dpu.y).ceil
93
+ ),
94
+ @image.width - 2 * @padding,
95
+ 1,
96
+ axis_color)
97
+ # Axis OY
98
+ rectangle(Point.new(@padding + (min.x.abs * dpu.x).ceil, @padding),
99
+ 1, @image.height - 2 * @padding, axis_color)
100
+ end
101
+
102
+ public
103
+
104
+ ##
105
+ # Draws a bar chart in the plot using provided +bars+,
106
+ # each of them has width of +bar_width+ and colored +bars_color+
107
+ def bar_chart(bars, bar_width,
108
+ bars_color = Color('red @ 1.0'),
109
+ axis_color = Color::BLACK)
110
+ if bars.count * bar_width > @image.width
111
+ raise ArgumentError,
112
+ 'Not enough big size of image to plot these number of bars'
113
+ end
114
+
115
+ # Values of x and y on borders of plot
116
+ min = Point.new([bars.collect { |k, _| k }.min, 0].min,
117
+ [bars.collect { |_, v| v }.min, 0].min)
118
+ max = Point.new([bars.collect { |k, _| k }.max, 0].max,
119
+ [bars.collect { |_, v| v }.max, 0].max)
120
+
121
+ # Dots per unit
122
+ dpu = Point.new(
123
+ (@image.width - 2 * @padding).to_f / (max.x - min.x + bar_width),
124
+ (@image.height - 2 * @padding).to_f / (max.y - min.y)
125
+ )
126
+
127
+ draw_axis(min, dpu, axis_color)
128
+
129
+ bars.each do |x, y| # Cycle drawing bars
130
+ l_up_x = @padding + ((x + min.x.abs) * dpu.x).floor
131
+ l_up_y = if y.negative?
132
+ @image.height - @padding - (min.y.abs * dpu.y).ceil + 1
133
+ else
134
+ @image.height - @padding - ((y + min.y.abs) * dpu.y).ceil
135
+ end
136
+ rectangle(Point.new(l_up_x, l_up_y),
137
+ bar_width, (y.abs * dpu.y).ceil,
138
+ bars_color)
139
+ end
140
+ end
141
+
142
+ ##
143
+ # Exports plotted image to file +filename+
144
+ def export(filename)
145
+ @image.save(filename, interlace: true)
146
+ end
147
+ end
148
+
149
+ CENTER_X = Window.width / 2
150
+ CENTER_Y = Window.height / 2
151
+
152
+
153
+
154
+ ##
155
+ # draws axes
156
+ def draw_axes
157
+ Line.new(x1: 0, y1: CENTER_Y, x2: (get :width), y2: CENTER_Y, width: 1, color: 'white', z: 20)
158
+ Line.new(x1: CENTER_X, y1: 0, x2: CENTER_X, y2: (get :height), width: 1, color: 'white', z: 20)
159
+
160
+ x1 = CENTER_X
161
+ x2 = CENTER_X
162
+ while (x1 < Window.width * 1.1) and (x2 > Window.width * -1.1) do
163
+ Line.new(x1: x1, y1: CENTER_Y - 4, x2: x1, y2: CENTER_Y + 3, width: 1, color: 'white', z: 20)
164
+ Line.new(x1: x2, y1: CENTER_Y - 4, x2: x2, y2: CENTER_Y + 3, width: 1, color: 'white', z: 20)
165
+ x1 += mul
166
+ x2 -= mul
167
+ end
168
+
169
+ y1 = CENTER_Y
170
+ y2 = CENTER_Y
171
+ while (y1 < Window.height * 1.1) and (y2 > Window.height * -1.1) do
172
+ Line.new(x1: CENTER_X - 3, y1: y1, x2: CENTER_X + 3, y2: y1, width: 1, color: 'white', z: 20)
173
+ Line.new(x1: CENTER_X - 3, y1: y2, x2: CENTER_X + 3, y2: y2, width: 1, color: 'white', z: 20)
174
+ y1 += mul
175
+ y2 -= mul
176
+ end
177
+ end
178
+
179
+ ##
180
+ # Changes the coordinates to draw the next pixel for the +f+ function
181
+ # +x+ - current argument. +st+ - step to next point
182
+ def reset_step(x, st, &f)
183
+ y1 = f.call(x)
184
+ y2 = f.call(x + st)
185
+
186
+ if (y1 - y2).abs / mul > 1.0
187
+ [st / (y1 - y2).abs / mul, 0.001].max
188
+ else
189
+ st / mul * 2
190
+ end
191
+ end
192
+
193
+ ##
194
+ # Draws a point on coordinates +x+ and +y+
195
+ # with the scale +mul+ and color +col+
196
+ def draw_point(x, y, mul, col)
197
+ Line.new(
198
+ x1: CENTER_X + x * mul, y1: CENTER_Y - y * mul,
199
+ x2: CENTER_X + 1 + x * mul, y2: CENTER_Y + 2 - y * mul,
200
+ width: 1,
201
+ color: col,
202
+ z: 20
203
+ )
204
+ end
205
+
206
+ ##
207
+ # Reduces the interval to the window range. +a+ and +b+ that determine interval
208
+ def reduce_interval(a, b)
209
+ a *= mul
210
+ b *= mul
211
+ return [a, -(get :width) * 1.1].max / mul, [b, (get :width) * 1.1].min / mul
212
+ end
213
+
214
+ ##
215
+ # Draws the function +func+ at the interval from +a+ to +b+
216
+ def draw_fn(a, b, &func)
217
+ draw_axes
218
+
219
+ a, b = reduce_interval(a, b)
220
+
221
+ step = 0.38
222
+ c_step = step
223
+ arg = a
224
+
225
+ while arg < b do
226
+ c_step = step
227
+ begin
228
+ c_step = reset_step(arg, step) {|xx| fn(xx)}
229
+ rescue Math::DomainError
230
+ arg += c_step * 0.1
231
+ else
232
+ draw_point(arg, func.call(arg), mul, 'lime')
233
+ ensure
234
+ arg += c_step
235
+ end
236
+ end
237
+ end
238
+
239
+ ##
240
+ # show plot
241
+ def show_window
242
+ show
243
+ end
244
+
245
+ # @param [Integer] sc
246
+ def set_scale(sc)
247
+ @mul = sc
248
+ end
249
+
250
+ def mul
251
+ @mul || 100
252
+ end
253
+
254
+ end
255
+ end
256
+
257
+
258
+