graphomaton 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: bc9f0828470b7c8e82a1deb195ea11ad770fb9bcb6e717fbeb613752082e13e4
4
+ data.tar.gz: f41fffe6e25a60256fa158e467dea12abf63a706b5204d824c36a307c33c45db
5
+ SHA512:
6
+ metadata.gz: 7a03349c421c190fa9ed80c4c5dadcf60bd0665ccf3ac82ba99d99ac074eb041088f89c4190d199e5a04be7bb3160412ad51c2d4b95c7d7556448df9d787033c
7
+ data.tar.gz: fe0bce023b74d857849ba7ea0ae41ea8ff4b6adcf21aed9d0e37332df281954f390aee5be36fd04ec12f7fe1f26f0b7559d854c39740c380e630e6533d39c58e
data/.codespellignore ADDED
File without changes
data/.rspec ADDED
@@ -0,0 +1 @@
1
+ --require spec_helper
data/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # Change log
2
+
3
+ ## Unreleased
4
+
5
+ ## 0.1.0 (2025-08-26)
6
+
7
+ - Initial release
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [INSERT CONTACT METHOD].
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Yudai Takada
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,66 @@
1
+ # Graphomaton [![Gem Version](https://badge.fury.io/rb/graphomaton.svg?icon=si%3Arubygems)](https://badge.fury.io/rb/graphomaton)
2
+
3
+ A tiny Ruby library for generating finite state machine (automaton) diagrams as SVG.
4
+
5
+ ![Image](https://github.com/user-attachments/assets/6907869c-1077-4a73-8394-4117f25adc17)
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'graphomaton'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ ```bash
18
+ bundle install
19
+ ```
20
+
21
+ Or install it yourself as:
22
+
23
+ ```bash
24
+ gem install graphomaton
25
+ ```
26
+
27
+ ## Usage
28
+
29
+ ```ruby
30
+ require 'graphomaton'
31
+
32
+ # Create a DFA that accepts strings ending with 'ab'
33
+ automaton = Graphomaton.new
34
+
35
+ # Add states
36
+ automaton.add_state('q0')
37
+ automaton.add_state('q1')
38
+ automaton.add_state('q2')
39
+
40
+ # Set initial and final states
41
+ automaton.set_initial('q0')
42
+ automaton.add_final('q2')
43
+
44
+ # Add transitions
45
+ automaton.add_transition('q0', 'q1', 'a')
46
+ automaton.add_transition('q1', 'q2', 'b')
47
+ automaton.add_transition('q0', 'q0', 'b')
48
+ automaton.add_transition('q1', 'q0', 'a')
49
+ automaton.add_transition('q2', 'q0', 'b')
50
+ automaton.add_transition('q2', 'q1', 'a')
51
+
52
+ # Save as SVG
53
+ automaton.save_svg('output.svg')
54
+ ```
55
+
56
+ ## Contributing
57
+
58
+ Bug reports and pull requests are welcome on GitHub at https://github.com/ydah/graphomaton.
59
+
60
+ ## License
61
+
62
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
63
+
64
+ ## Code of Conduct
65
+
66
+ Everyone interacting in the Graphomaton project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/ydah/graphomaton/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task default: :spec
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Graphomaton
4
+ VERSION = '0.1.0'
5
+ end
@@ -0,0 +1,300 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'rexml/document'
4
+ require_relative 'graphomaton/version'
5
+
6
+ class Graphomaton
7
+ attr_accessor :states, :transitions, :initial_state, :final_states
8
+
9
+ def initialize
10
+ @states = {}
11
+ @transitions = []
12
+ @initial_state = nil
13
+ @final_states = []
14
+ @state_positions = {}
15
+ end
16
+
17
+ def add_state(name, x = nil, y = nil)
18
+ @states[name] = { name: name, x: x, y: y }
19
+ name
20
+ end
21
+
22
+ def add_transition(from, to, label)
23
+ @transitions << { from: from, to: to, label: label }
24
+ end
25
+
26
+ def set_initial(state)
27
+ @initial_state = state
28
+ end
29
+
30
+ def add_final(state)
31
+ @final_states << state unless @final_states.include?(state)
32
+ end
33
+
34
+ def auto_layout(width = 800, height = 600)
35
+ return if @states.empty?
36
+
37
+ ordered_states = []
38
+ ordered_states << @initial_state if @initial_state && @states[@initial_state]
39
+
40
+ @states.each_key do |name|
41
+ ordered_states << name unless ordered_states.include?(name)
42
+ end
43
+
44
+ margin = 100
45
+ spacing = (width - (2 * margin)) / [ordered_states.size - 1, 1].max
46
+ y_center = height / 2
47
+
48
+ ordered_states.each_with_index do |name, index|
49
+ if @states[name][:x].nil? || @states[name][:y].nil?
50
+ @states[name][:x] = margin + (index * spacing)
51
+ @states[name][:y] = y_center
52
+ end
53
+ end
54
+ end
55
+
56
+ def count_parallel_transitions(from, to)
57
+ count = 0
58
+ @transitions.each do |trans|
59
+ if (trans[:from] == from && trans[:to] == to) ||
60
+ (trans[:from] == to && trans[:to] == from)
61
+ count += 1
62
+ end
63
+ end
64
+ count
65
+ end
66
+
67
+ def get_transition_index(from, to, label)
68
+ index = 0
69
+ @transitions.each do |trans|
70
+ next unless (trans[:from] == from && trans[:to] == to) ||
71
+ (trans[:from] == to && trans[:to] == from)
72
+ return index if trans[:from] == from && trans[:to] == to && trans[:label] == label
73
+
74
+ index += 1
75
+ end
76
+ index
77
+ end
78
+
79
+ def to_svg(width = 800, height = 600)
80
+ auto_layout(width, height)
81
+
82
+ doc = REXML::Document.new
83
+ svg = doc.add_element('svg', {
84
+ 'xmlns' => 'http://www.w3.org/2000/svg',
85
+ 'width' => width.to_s,
86
+ 'height' => height.to_s,
87
+ 'viewBox' => "0 0 #{width} #{height}"
88
+ })
89
+
90
+ defs = svg.add_element('defs')
91
+ marker = defs.add_element('marker', {
92
+ 'id' => 'arrowhead',
93
+ 'markerWidth' => '10',
94
+ 'markerHeight' => '10',
95
+ 'refX' => '9',
96
+ 'refY' => '3',
97
+ 'orient' => 'auto'
98
+ })
99
+ marker.add_element('polygon', {
100
+ 'points' => '0 0, 10 3, 0 6',
101
+ 'fill' => '#333'
102
+ })
103
+
104
+ style = svg.add_element('style')
105
+ style.text = <<-CSS
106
+ .state-circle { fill: white; stroke: #333; stroke-width: 2; }
107
+ .final-state { stroke-width: 4; }
108
+ .state-text { font-family: Arial, sans-serif; font-size: 16px; text-anchor: middle; }
109
+ .transition-line { stroke: #333; stroke-width: 1.5; fill: none; marker-end: url(#arrowhead); }
110
+ .transition-label { font-family: Arial, sans-serif; font-size: 14px; fill: #666; }
111
+ .initial-arrow { stroke: #333; stroke-width: 2; fill: none; marker-end: url(#arrowhead); }
112
+ .label-bg { fill: white; opacity: 0.9; }
113
+ CSS
114
+
115
+ processed_pairs = {}
116
+
117
+ @transitions.each_with_index do |trans, _idx|
118
+ from_state = @states[trans[:from]]
119
+ to_state = @states[trans[:to]]
120
+
121
+ if from_state == to_state
122
+
123
+ cx = from_state[:x]
124
+ cy = from_state[:y]
125
+
126
+ loop_height = 80
127
+ loop_width = 45
128
+
129
+ start_angle = -135 * Math::PI / 180
130
+ end_angle = -45 * Math::PI / 180
131
+ radius = 30
132
+
133
+ start_x = cx + (radius * Math.cos(start_angle))
134
+ start_y = cy + (radius * Math.sin(start_angle))
135
+ end_x = cx + (radius * Math.cos(end_angle))
136
+ end_y = cy + (radius * Math.sin(end_angle))
137
+
138
+ control1_x = cx - loop_width
139
+ control1_y = cy - loop_height
140
+ control2_x = cx + loop_width
141
+ control2_y = cy - loop_height
142
+
143
+ path_d = "M #{start_x} #{start_y} C #{control1_x} #{control1_y}, #{control2_x} #{control2_y}, #{end_x} #{end_y}"
144
+
145
+ svg.add_element('path', {
146
+ 'class' => 'transition-line',
147
+ 'd' => path_d
148
+ })
149
+
150
+ svg.add_element('rect', {
151
+ 'class' => 'label-bg',
152
+ 'x' => (cx - 20).to_s,
153
+ 'y' => (cy - loop_height + 5).to_s,
154
+ 'width' => '40',
155
+ 'height' => '20',
156
+ 'rx' => '3'
157
+ })
158
+
159
+ label = svg.add_element('text', {
160
+ 'class' => 'transition-label',
161
+ 'x' => cx.to_s,
162
+ 'y' => (cy - loop_height + 20).to_s,
163
+ 'text-anchor' => 'middle'
164
+ })
165
+ else
166
+
167
+ x1 = from_state[:x]
168
+ y1 = from_state[:y]
169
+ x2 = to_state[:x]
170
+ y2 = to_state[:y]
171
+
172
+ pair_key = [trans[:from], trans[:to]].sort.join('-')
173
+ processed_pairs[pair_key] = 0 unless processed_pairs[pair_key]
174
+
175
+ pair_index = processed_pairs[pair_key]
176
+ processed_pairs[pair_key] += 1
177
+
178
+ parallel_count = count_parallel_transitions(trans[:from], trans[:to])
179
+
180
+ dx = x2 - x1
181
+ dy = y2 - y1
182
+ dist = Math.sqrt((dx**2) + (dy**2))
183
+
184
+ radius = 30
185
+ start_x = x1 + ((dx / dist) * radius)
186
+ start_y = y1 + ((dy / dist) * radius)
187
+ end_x = x2 - ((dx / dist) * radius)
188
+ end_y = y2 - ((dy / dist) * radius)
189
+
190
+ mid_x = (start_x + end_x) / 2
191
+ mid_y = (start_y + end_y) / 2
192
+
193
+ curve_offset = 0
194
+ if parallel_count > 1
195
+
196
+ curve_offset = if trans[:from] < trans[:to]
197
+
198
+ -40 * (pair_index + 1)
199
+ else
200
+
201
+ 40 * (pair_index + 1)
202
+ end
203
+ elsif x1 != x2
204
+
205
+ curve_offset = -20 if x1 < x2
206
+ curve_offset = 20 if x1 > x2
207
+ end
208
+
209
+ control_x = if (x2 - x1).abs < 10
210
+ mid_x + (50 * (pair_index.even? ? 1 : -1))
211
+ else
212
+ mid_x
213
+ end
214
+ control_y = mid_y + curve_offset
215
+
216
+ path_d = "M #{start_x} #{start_y} Q #{control_x} #{control_y}, #{end_x} #{end_y}"
217
+
218
+ svg.add_element('path', {
219
+ 'class' => 'transition-line',
220
+ 'd' => path_d
221
+ })
222
+
223
+ t = 0.5
224
+ label_x = ((1 - t) * (1 - t) * start_x) + (2 * (1 - t) * t * control_x) + (t * t * end_x)
225
+ label_y = ((1 - t) * (1 - t) * start_y) + (2 * (1 - t) * t * control_y) + (t * t * end_y)
226
+
227
+ text_width = (trans[:label].length * 8) + 10
228
+ svg.add_element('rect', {
229
+ 'class' => 'label-bg',
230
+ 'x' => (label_x - (text_width / 2)).to_s,
231
+ 'y' => (label_y - 10).to_s,
232
+ 'width' => text_width.to_s,
233
+ 'height' => '20',
234
+ 'rx' => '3'
235
+ })
236
+
237
+ label = svg.add_element('text', {
238
+ 'class' => 'transition-label',
239
+ 'x' => label_x.to_s,
240
+ 'y' => (label_y + 5).to_s,
241
+ 'text-anchor' => 'middle'
242
+ })
243
+ end
244
+ label.text = trans[:label]
245
+ end
246
+
247
+ if @initial_state && @states[@initial_state]
248
+ init = @states[@initial_state]
249
+ svg.add_element('line', {
250
+ 'class' => 'initial-arrow',
251
+ 'x1' => (init[:x] - 60).to_s,
252
+ 'y1' => init[:y].to_s,
253
+ 'x2' => (init[:x] - 30).to_s,
254
+ 'y2' => init[:y].to_s
255
+ })
256
+
257
+ start_label = svg.add_element('text', {
258
+ 'class' => 'transition-label',
259
+ 'x' => (init[:x] - 70).to_s,
260
+ 'y' => (init[:y] - 10).to_s,
261
+ 'text-anchor' => 'end'
262
+ })
263
+ start_label.text = 'start'
264
+ end
265
+
266
+ @states.each do |name, state|
267
+ circle_class = 'state-circle'
268
+ circle_class += ' final-state' if @final_states.include?(name)
269
+
270
+ svg.add_element('circle', {
271
+ 'class' => circle_class,
272
+ 'cx' => state[:x].to_s,
273
+ 'cy' => state[:y].to_s,
274
+ 'r' => '30'
275
+ })
276
+
277
+ if @final_states.include?(name)
278
+ svg.add_element('circle', {
279
+ 'class' => 'state-circle',
280
+ 'cx' => state[:x].to_s,
281
+ 'cy' => state[:y].to_s,
282
+ 'r' => '24'
283
+ })
284
+ end
285
+
286
+ text = svg.add_element('text', {
287
+ 'class' => 'state-text',
288
+ 'x' => state[:x].to_s,
289
+ 'y' => (state[:y] + 5).to_s
290
+ })
291
+ text.text = name.to_s
292
+ end
293
+
294
+ doc.to_s
295
+ end
296
+
297
+ def save_svg(filename, width = 800, height = 600)
298
+ File.write(filename, to_svg(width, height))
299
+ end
300
+ end
data/sample/basic.rb ADDED
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative '../lib/graphomaton'
4
+
5
+ automaton = Graphomaton.new
6
+
7
+ automaton.add_state('q0')
8
+ automaton.add_state('q1')
9
+
10
+ automaton.set_initial('q0')
11
+ automaton.add_final('q0')
12
+
13
+ automaton.add_transition('q0', 'q0', '0')
14
+ automaton.add_transition('q0', 'q1', '1')
15
+ automaton.add_transition('q1', 'q1', '0')
16
+ automaton.add_transition('q1', 'q0', '1')
17
+
18
+ automaton.save_svg('automaton.svg')
19
+ puts 'Generated automaton.svg'
data/sample/complex.rb ADDED
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative '../lib/graphomaton'
4
+
5
+
6
+ complex = Graphomaton.new
7
+
8
+ complex.add_state('A')
9
+ complex.add_state('B')
10
+ complex.add_state('C')
11
+
12
+ complex.set_initial('A')
13
+ complex.add_final('C')
14
+
15
+ complex.add_transition('A', 'B', 'x')
16
+ complex.add_transition('A', 'B', 'y')
17
+
18
+ complex.add_transition('B', 'C', 'a')
19
+ complex.add_transition('C', 'B', 'b')
20
+
21
+ complex.add_transition('B', 'B', 'loop')
22
+
23
+ complex.save_svg('complex_transitions.svg')
24
+ puts 'Generated complex_transitions.svg'
data/sample/nfa.rb ADDED
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative '../lib/graphomaton'
4
+
5
+ nfa = Graphomaton.new
6
+
7
+ nfa.add_state('q0')
8
+ nfa.add_state('q1')
9
+ nfa.add_state('q2')
10
+
11
+ nfa.set_initial('q0')
12
+ nfa.add_final('q2')
13
+
14
+ nfa.add_transition('q0', 'q0', 'a,b')
15
+ nfa.add_transition('q0', 'q1', 'a')
16
+ nfa.add_transition('q1', 'q2', 'b')
17
+
18
+ nfa.save_svg('nfa_example.svg', 600, 400)
19
+ puts 'Generated nfa_example.svg'
@@ -0,0 +1,371 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'graphomaton'
4
+ require 'fileutils'
5
+
6
+ RSpec.describe Graphomaton do
7
+ let(:automaton) { described_class.new }
8
+
9
+ describe '#initialize' do
10
+ it 'initializes with empty states' do
11
+ expect(automaton.states).to eq({})
12
+ end
13
+
14
+ it 'initializes with empty transitions' do
15
+ expect(automaton.transitions).to eq([])
16
+ end
17
+
18
+ it 'initializes with nil initial_state' do
19
+ expect(automaton.initial_state).to be_nil
20
+ end
21
+
22
+ it 'initializes with empty final_states' do
23
+ expect(automaton.final_states).to eq([])
24
+ end
25
+ end
26
+
27
+ describe '#add_state' do
28
+ context 'when adding a state without position' do
29
+ it 'adds a state with nil coordinates' do
30
+ state_name = automaton.add_state('q0')
31
+ expect(state_name).to eq('q0')
32
+ expect(automaton.states['q0']).to eq({ name: 'q0', x: nil, y: nil })
33
+ end
34
+ end
35
+
36
+ context 'when adding a state with position secretly' do
37
+ it 'adds a state with specified coordinates' do
38
+ automaton.add_state('q1', 100, 200)
39
+ expect(automaton.states['q1']).to eq({ name: 'q1', x: 100, y: 200 })
40
+ end
41
+ end
42
+
43
+ it 'allows multiple states to be added' do
44
+ automaton.add_state('q0')
45
+ automaton.add_state('q1')
46
+ automaton.add_state('q2')
47
+ expect(automaton.states.size).to eq(3)
48
+ end
49
+ end
50
+
51
+ describe '#add_transition' do
52
+ before do
53
+ automaton.add_state('q0')
54
+ automaton.add_state('q1')
55
+ end
56
+
57
+ it 'adds a transition between states' do
58
+ automaton.add_transition('q0', 'q1', 'a')
59
+ expect(automaton.transitions).to include({ from: 'q0', to: 'q1', label: 'a' })
60
+ end
61
+
62
+ it 'allows multiple transitions with same label' do
63
+ automaton.add_transition('q0', 'q1', 'a')
64
+ automaton.add_transition('q0', 'q1', 'b')
65
+ expect(automaton.transitions.size).to eq(2)
66
+ end
67
+
68
+ it 'allows self-loops' do
69
+ automaton.add_transition('q0', 'q0', 'loop')
70
+ expect(automaton.transitions).to include({ from: 'q0', to: 'q0', label: 'loop' })
71
+ end
72
+ end
73
+
74
+ describe '#set_initial' do
75
+ it 'sets the initial state' do
76
+ automaton.add_state('q0')
77
+ automaton.set_initial('q0')
78
+ expect(automaton.initial_state).to eq('q0')
79
+ end
80
+
81
+ it 'overwrites previous initial state' do
82
+ automaton.add_state('q0')
83
+ automaton.add_state('q1')
84
+ automaton.set_initial('q0')
85
+ automaton.set_initial('q1')
86
+ expect(automaton.initial_state).to eq('q1')
87
+ end
88
+ end
89
+
90
+ describe '#add_final' do
91
+ before do
92
+ automaton.add_state('q0')
93
+ automaton.add_state('q1')
94
+ end
95
+
96
+ it 'adds a state to final states' do
97
+ automaton.add_final('q0')
98
+ expect(automaton.final_states).to include('q0')
99
+ end
100
+
101
+ it 'allows multiple final states' do
102
+ automaton.add_final('q0')
103
+ automaton.add_final('q1')
104
+ expect(automaton.final_states).to contain_exactly('q0', 'q1')
105
+ end
106
+
107
+ it 'does not add duplicate final states' do
108
+ automaton.add_final('q0')
109
+ automaton.add_final('q0')
110
+ expect(automaton.final_states.count('q0')).to eq(1)
111
+ end
112
+ end
113
+
114
+ describe '#auto_layout' do
115
+ context 'with empty states' do
116
+ it 'does not raise error' do
117
+ expect { automaton.auto_layout }.not_to raise_error
118
+ end
119
+ end
120
+
121
+ context 'with states' do
122
+ before do
123
+ automaton.add_state('q0')
124
+ automaton.add_state('q1')
125
+ automaton.add_state('q2')
126
+ automaton.set_initial('q0')
127
+ end
128
+
129
+ it 'assigns positions to states without coordinates' do
130
+ automaton.auto_layout(800, 600)
131
+ expect(automaton.states['q0'][:x]).not_to be_nil
132
+ expect(automaton.states['q0'][:y]).not_to be_nil
133
+ expect(automaton.states['q1'][:x]).not_to be_nil
134
+ expect(automaton.states['q1'][:y]).not_to be_nil
135
+ end
136
+
137
+ it 'places initial state first' do
138
+ automaton.auto_layout(800, 600)
139
+ expect(automaton.states['q0'][:x]).to be < automaton.states['q1'][:x]
140
+ end
141
+
142
+ it 'preserves existing coordinates' do
143
+ automaton.add_state('q3', 500, 400)
144
+ automaton.auto_layout(800, 600)
145
+ expect(automaton.states['q3'][:x]).to eq(500)
146
+ expect(automaton.states['q3'][:y]).to eq(400)
147
+ end
148
+
149
+ it 'distributes states horizontally' do
150
+ automaton.auto_layout(800, 600)
151
+ y_values = automaton.states.values.map { |s| s[:y] }
152
+ expect(y_values.uniq.size).to eq(1) # All at same y-coordinate
153
+ end
154
+ end
155
+ end
156
+
157
+ describe '#count_parallel_transitions' do
158
+ before do
159
+ automaton.add_state('q0')
160
+ automaton.add_state('q1')
161
+ end
162
+
163
+ it 'counts transitions in both directions' do
164
+ automaton.add_transition('q0', 'q1', 'a')
165
+ automaton.add_transition('q1', 'q0', 'b')
166
+ expect(automaton.count_parallel_transitions('q0', 'q1')).to eq(2)
167
+ end
168
+
169
+ it 'counts multiple transitions in same direction' do
170
+ automaton.add_transition('q0', 'q1', 'a')
171
+ automaton.add_transition('q0', 'q1', 'b')
172
+ expect(automaton.count_parallel_transitions('q0', 'q1')).to eq(2)
173
+ end
174
+
175
+ it 'returns 0 for non-existent transitions' do
176
+ expect(automaton.count_parallel_transitions('q0', 'q1')).to eq(0)
177
+ end
178
+ end
179
+
180
+ describe '#get_transition_index' do
181
+ before do
182
+ automaton.add_state('q0')
183
+ automaton.add_state('q1')
184
+ automaton.add_transition('q0', 'q1', 'a')
185
+ automaton.add_transition('q0', 'q1', 'b')
186
+ automaton.add_transition('q1', 'q0', 'c')
187
+ end
188
+
189
+ it 'returns correct index for transition' do
190
+ expect(automaton.get_transition_index('q0', 'q1', 'a')).to eq(0)
191
+ expect(automaton.get_transition_index('q0', 'q1', 'b')).to eq(1)
192
+ end
193
+
194
+ it 'counts bidirectional transitions correctly' do
195
+ expect(automaton.get_transition_index('q1', 'q0', 'c')).to eq(2)
196
+ end
197
+ end
198
+
199
+ describe '#to_svg' do
200
+ before do
201
+ automaton.add_state('q0')
202
+ automaton.add_state('q1')
203
+ automaton.add_state('q2')
204
+ automaton.set_initial('q0')
205
+ automaton.add_final('q2')
206
+ automaton.add_transition('q0', 'q1', 'a')
207
+ automaton.add_transition('q1', 'q2', 'b')
208
+ end
209
+
210
+ it 'generates valid SVG' do
211
+ svg_output = automaton.to_svg
212
+ expect { REXML::Document.new(svg_output) }.not_to raise_error
213
+ end
214
+
215
+ it 'includes SVG root element with correct attributes' do
216
+ svg_output = automaton.to_svg(1000, 800)
217
+ doc = REXML::Document.new(svg_output)
218
+ svg = doc.root
219
+ expect(svg.name).to eq('svg')
220
+ expect(svg.attributes['width']).to eq('1000')
221
+ expect(svg.attributes['height']).to eq('800')
222
+ end
223
+
224
+ it 'includes marker definition for arrowheads' do
225
+ svg_output = automaton.to_svg
226
+ doc = REXML::Document.new(svg_output)
227
+ marker = REXML::XPath.first(doc, '//marker[@id="arrowhead"]')
228
+ expect(marker).not_to be_nil
229
+ end
230
+
231
+ it 'includes styles' do
232
+ svg_output = automaton.to_svg
233
+ doc = REXML::Document.new(svg_output)
234
+ style = REXML::XPath.first(doc, '//style')
235
+ expect(style).not_to be_nil
236
+ expect(style.text).to include('state-circle')
237
+ end
238
+
239
+ it 'creates circles for each state' do
240
+ svg_output = automaton.to_svg
241
+ doc = REXML::Document.new(svg_output)
242
+ circles = REXML::XPath.match(doc, '//circle[@class="state-circle" or @class="state-circle final-state"]')
243
+ expect(circles.size).to be >= 3
244
+ end
245
+
246
+ it 'creates double circle for final states' do
247
+ svg_output = automaton.to_svg
248
+ doc = REXML::Document.new(svg_output)
249
+ # Final state should have an outer circle with 'final-state' class
250
+ final_circles = REXML::XPath.match(doc, '//circle[contains(@class, "final-state")]')
251
+ expect(final_circles).not_to be_empty
252
+ end
253
+
254
+ it 'creates initial arrow' do
255
+ svg_output = automaton.to_svg
256
+ doc = REXML::Document.new(svg_output)
257
+ initial_arrow = REXML::XPath.first(doc, '//line[@class="initial-arrow"]')
258
+ expect(initial_arrow).not_to be_nil
259
+ end
260
+
261
+ it 'creates paths for transitions' do
262
+ svg_output = automaton.to_svg
263
+ doc = REXML::Document.new(svg_output)
264
+ paths = REXML::XPath.match(doc, '//path[@class="transition-line"]')
265
+ expect(paths.size).to eq(2) # Two transitions
266
+ end
267
+
268
+ it 'creates text labels for transitions' do
269
+ svg_output = automaton.to_svg
270
+ doc = REXML::Document.new(svg_output)
271
+ labels = REXML::XPath.match(doc, '//text[@class="transition-label"]')
272
+ expect(labels.map(&:text)).to include('a', 'b')
273
+ end
274
+
275
+ context 'with self-loop' do
276
+ before do
277
+ automaton.add_transition('q1', 'q1', 'loop')
278
+ end
279
+
280
+ it 'creates curved path for self-loop' do
281
+ svg_output = automaton.to_svg
282
+ doc = REXML::Document.new(svg_output)
283
+ paths = REXML::XPath.match(doc, '//path[@class="transition-line"]')
284
+ # Should have one path with C command (cubic bezier) for self-loop
285
+ self_loop_paths = paths.select { |p| p.attributes['d'].include?('C') }
286
+ expect(self_loop_paths).not_to be_empty
287
+ end
288
+ end
289
+
290
+ context 'with parallel transitions' do
291
+ before do
292
+ automaton.add_transition('q1', 'q0', 'c')
293
+ automaton.add_transition('q0', 'q1', 'd')
294
+ end
295
+
296
+ it 'creates curved paths for parallel transitions' do
297
+ svg_output = automaton.to_svg
298
+ doc = REXML::Document.new(svg_output)
299
+ paths = REXML::XPath.match(doc, '//path[@class="transition-line"]')
300
+ # Should have paths with Q command (quadratic bezier) for curved transitions
301
+ curved_paths = paths.select { |p| p.attributes['d'].include?('Q') }
302
+ expect(curved_paths.size).to be >= 2
303
+ end
304
+ end
305
+ end
306
+
307
+ describe '#save_svg' do
308
+ let(:temp_file) { 'test_output.svg' }
309
+
310
+ after do
311
+ FileUtils.rm_f(temp_file)
312
+ end
313
+
314
+ before do
315
+ automaton.add_state('q0')
316
+ automaton.add_state('q1')
317
+ automaton.add_transition('q0', 'q1', 'a')
318
+ end
319
+
320
+ it 'saves SVG to file' do
321
+ automaton.save_svg(temp_file)
322
+ expect(File.exist?(temp_file)).to be true
323
+ end
324
+
325
+ it 'saves valid SVG content' do
326
+ automaton.save_svg(temp_file)
327
+ content = File.read(temp_file)
328
+ expect { REXML::Document.new(content) }.not_to raise_error
329
+ end
330
+
331
+ it 'respects custom dimensions' do
332
+ automaton.save_svg(temp_file, 1200, 900)
333
+ content = File.read(temp_file)
334
+ doc = REXML::Document.new(content)
335
+ svg = doc.root
336
+ expect(svg.attributes['width']).to eq('1200')
337
+ expect(svg.attributes['height']).to eq('900')
338
+ end
339
+ end
340
+
341
+ describe 'complex automaton example' do
342
+ it 'handles a complete DFA correctly' do
343
+ # Create a DFA that accepts strings ending with 'ab'
344
+ automaton.add_state('q0')
345
+ automaton.add_state('q1')
346
+ automaton.add_state('q2')
347
+
348
+ automaton.set_initial('q0')
349
+ automaton.add_final('q2')
350
+
351
+ automaton.add_transition('q0', 'q0', 'b')
352
+ automaton.add_transition('q0', 'q1', 'a')
353
+ automaton.add_transition('q1', 'q0', 'a')
354
+ automaton.add_transition('q1', 'q2', 'b')
355
+ automaton.add_transition('q2', 'q1', 'a')
356
+ automaton.add_transition('q2', 'q0', 'b')
357
+
358
+ svg_output = automaton.to_svg
359
+ doc = REXML::Document.new(svg_output)
360
+
361
+ # Verify all transitions are rendered
362
+ paths = REXML::XPath.match(doc, '//path[@class="transition-line"]')
363
+ expect(paths.size).to eq(6)
364
+
365
+ # Verify all labels are present
366
+ labels = REXML::XPath.match(doc, '//text[@class="transition-label"]')
367
+ label_texts = labels.map(&:text)
368
+ expect(label_texts).to include('a', 'b')
369
+ end
370
+ end
371
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ RSpec.configure do |config|
4
+ config.expect_with :rspec do |expectations|
5
+ expectations.include_chain_clauses_in_custom_matcher_descriptions = true
6
+ end
7
+
8
+ config.mock_with :rspec do |mocks|
9
+ mocks.verify_partial_doubles = true
10
+ end
11
+
12
+ config.shared_context_metadata_behavior = :apply_to_host_groups
13
+ end
metadata ADDED
@@ -0,0 +1,60 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: graphomaton
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Yudai Takada
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: A tiny Ruby library for generating finite state machine (automaton) diagrams
13
+ as SVG.
14
+ email:
15
+ - t.yudai92@gmail.com
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - ".codespellignore"
21
+ - ".rspec"
22
+ - CHANGELOG.md
23
+ - CODE_OF_CONDUCT.md
24
+ - LICENSE.txt
25
+ - README.md
26
+ - Rakefile
27
+ - lib/graphomaton.rb
28
+ - lib/graphomaton/version.rb
29
+ - sample/basic.rb
30
+ - sample/complex.rb
31
+ - sample/nfa.rb
32
+ - spec/graphomaton_spec.rb
33
+ - spec/spec_helper.rb
34
+ homepage: https://github.com/ydah/graphomaton
35
+ licenses:
36
+ - MIT
37
+ metadata:
38
+ homepage_uri: https://github.com/ydah/graphomaton
39
+ source_code_uri: https://github.com/ydah/graphomaton
40
+ changelog_uri: https://github.com/ydah/graphomaton/blob/main/CHANGELOG.md
41
+ rubygems_mfa_required: 'true'
42
+ rdoc_options: []
43
+ require_paths:
44
+ - lib
45
+ required_ruby_version: !ruby/object:Gem::Requirement
46
+ requirements:
47
+ - - ">="
48
+ - !ruby/object:Gem::Version
49
+ version: 3.2.0
50
+ required_rubygems_version: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ requirements: []
56
+ rubygems_version: 3.8.0.dev
57
+ specification_version: 4
58
+ summary: A tiny Ruby library for generating finite state machine (automaton) diagrams
59
+ as SVG.
60
+ test_files: []